<commit_before>package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strings"
)

const queueSize int = 10

var (
	configFile = flag.String("c", "repos.json", "Repo configuration")
)

type Service struct {
	config   *Config
	incoming chan *Payload
	queue    map[string]chan *Payload
}

func (s *Service) Watch() {
	var repos []string
	for p := range s.incoming {
		repos = append(repos, p.Repository.Name)

		for _, repo := range repos {
			if !s.config.hasRepo(repo) {
				continue
			}

			repositories := s.config.getReposWithName(repo)

			branches := p.GetBranches()

			for _, r := range repositories {
				needToUpdate := false
				for _, b := range branches {
					if b == r.Branch {
						needToUpdate = true
						break
					}
				}
				if !needToUpdate {
					continue
				}

				repoBranchKey := repo + "#" + r.Branch

				channel := make(chan *Payload, queueSize)
				s.queue[repoBranchKey] = channel

				go s.Process(channel, r)

				select {
				case s.queue[repoBranchKey] <- p:
				default:
				}
			}
		}
	}
}

func (s *Service) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	log.Printf("New request from %s\n", req.RemoteAddr)
	if req.Method != "POST" {
		log.Printf("Not a POST but a %s from %s\n", req.Method, req.RemoteAddr)
		res.WriteHeader(http.StatusBadRequest)
		return
	}

	GET, err := url.ParseQuery(req.URL.RawQuery)
	if err != nil {
		log.Printf("Invalid query from %s\n", req.RemoteAddr)
		res.WriteHeader(http.StatusForbidden)
		return
	}

	secret, ok := GET["secret"]
	if !ok || secret[0] != s.config.Secret {
		if !ok {
			log.Printf("No secret from %s\n", req.RemoteAddr)
		} else {
			log.Printf("Bad secret from %s [secret: %s]\n", req.RemoteAddr, secret[0])
		}
		res.WriteHeader(http.StatusForbidden)
		return
	}

	err = req.ParseForm()
	if err != nil {
		log.Printf("Bad form from %s\n", req.RemoteAddr)
		res.WriteHeader(http.StatusBadRequest)
		return
	}

	content := req.FormValue("payload")
	log.Print(content)
	payload, err := parsePayload(content)

	if err != nil {
		log.Printf("Invalid payload from %s\n", req.RemoteAddr)
		log.Print(err)
		res.WriteHeader(http.StatusBadRequest)
		return
	}

	s.incoming <- payload
}

func (s *Service) Process(ch chan *Payload, repo *RepoConfig) {
	log.Printf("Run `%s` on '%s'\n", repo.Command, repo.Name)

	for payload := range ch {
		log.Printf("New changeset:\n - %s\n", strings.Join(payload.GetCommitMessages(), "\n - "))
		log.Printf("Run command on %s: %s", payload.Repository.Name, repo.Command)

		command := strings.Split(repo.Command, " ")
		cmd := exec.Command(command[0], command[1:]...)

		cmd.Dir = repo.Root
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr

		if err := cmd.Run(); err != nil {
			log.Println(err)
		}
	}
}

func main() {
	flag.Parse()
	config, err := ParseConfigurationFile(*configFile)

	if err != nil {
		log.Fatal(err)
	}

	service := &Service{
		config:   config,
		incoming: make(chan *Payload, 5),
		queue:    make(map[string]chan *Payload),
	}

	go service.Watch()

	address := fmt.Sprintf(":%d", config.Port)

	log.Printf("Listening on %s\n", address)
	http.ListenAndServe(address, service)
}
<commit_msg>remove debug message<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"net/url"
	"os"
	"os/exec"
	"strings"
)

const queueSize int = 10

var (
	configFile = flag.String("c", "repos.json", "Repo configuration")
)

type Service struct {
	config   *Config
	incoming chan *Payload
	queue    map[string]chan *Payload
}

func (s *Service) Watch() {
	var repos []string
	for p := range s.incoming {
		repos = repos[:0]
		repos = append(repos, p.Repository.Name)

		for _, repo := range repos {
			if !s.config.hasRepo(repo) {
				continue
			}

			repositories := s.config.getReposWithName(repo)

			branches := p.GetBranches()

			for _, r := range repositories {
				needToUpdate := false
				for _, b := range branches {
					if b == r.Branch {
						needToUpdate = true
						break
					}
				}
				if !needToUpdate {
					continue
				}

				repoBranchKey := repo + "#" + r.Branch

				channel := make(chan *Payload, queueSize)
				s.queue[repoBranchKey] = channel

				go s.Process(channel, r)

				select {
				case s.queue[repoBranchKey] <- p:
				default:
				}
			}
		}
	}
}

func (s *Service) ServeHTTP(res http.ResponseWriter, req *http.Request) {
	log.Printf("New request from %s\n", req.RemoteAddr)
	if req.Method != "POST" {
		log.Printf("Not a POST but a %s from %s\n", req.Method, req.RemoteAddr)
		res.WriteHeader(http.StatusBadRequest)
		return
	}

	GET, err := url.ParseQuery(req.URL.RawQuery)
	if err != nil {
		log.Printf("Invalid query from %s\n", req.RemoteAddr)
		res.WriteHeader(http.StatusForbidden)
		return
	}

	secret, ok := GET["secret"]
	if !ok || secret[0] != s.config.Secret {
		if !ok {
			log.Printf("No secret from %s\n", req.RemoteAddr)
		} else {
			log.Printf("Bad secret from %s [secret: %s]\n", req.RemoteAddr, secret[0])
		}
		res.WriteHeader(http.StatusForbidden)
		return
	}

	err = req.ParseForm()
	if err != nil {
		log.Printf("Bad form from %s\n", req.RemoteAddr)
		res.WriteHeader(http.StatusBadRequest)
		return
	}

	content := req.FormValue("payload")
	payload, err := parsePayload(content)

	if err != nil {
		log.Printf("Invalid payload from %s\n", req.RemoteAddr)
		log.Print(err)
		res.WriteHeader(http.StatusBadRequest)
		return
	}

	s.incoming <- payload
}

func (s *Service) Process(ch chan *Payload, repo *RepoConfig) {
	log.Printf("Run `%s` on '%s'\n", repo.Command, repo.Name)

	for payload := range ch {
		log.Printf("New changeset:\n - %s\n", strings.Join(payload.GetCommitMessages(), "\n - "))
		log.Printf("Run command on %s: %s", payload.Repository.Name, repo.Command)

		command := strings.Split(repo.Command, " ")
		cmd := exec.Command(command[0], command[1:]...)

		cmd.Dir = repo.Root
		cmd.Stdout = os.Stdout
		cmd.Stderr = os.Stderr

		if err := cmd.Run(); err != nil {
			log.Println(err)
		}
	}
}

func main() {
	flag.Parse()
	config, err := ParseConfigurationFile(*configFile)

	if err != nil {
		log.Fatal(err)
	}

	service := &Service{
		config:   config,
		incoming: make(chan *Payload, 5),
		queue:    make(map[string]chan *Payload),
	}

	go service.Watch()

	address := fmt.Sprintf(":%d", config.Port)

	log.Printf("Listening on %s\n", address)
	http.ListenAndServe(address, service)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/xellio/pxl/core/cli"
)

func main() {

	encode := flag.Bool("e", false, "encode flag")
	decode := flag.Bool("d", false, "decode flag")
	filePath := flag.String("f", "", "the file to convert")
	outputFileName := flag.String("o", "", "the filename of your output")

	flag.Parse()

	if !*encode && !*decode {
		fmt.Println("No action ('-d' for decode or '-e' for encode) specified")
		os.Exit(0)
	}

	if len(*filePath) <= 0 {
		fmt.Println("No input file specified ('-f=/path/to/file')")
		os.Exit(0)
	}

	if *encode {
		startEncodingTime := time.Now()
		dat, err := ioutil.ReadFile(*filePath)
		if err != nil {
			fmt.Println(err)
			os.Exit(0)
		}

		if len(*outputFileName) <= 0 {
			*outputFileName = "out.png"
		}

		_, err = pxl.Encode(dat, *outputFileName)
		if err != nil {
			fmt.Println(err)
			os.Exit(0)
		}

		//	//imgFile, err := ioutil.ReadFile("out.png")
		//	var b bytes.Buffer
		//	w := gzip.NewWriter(&b)
		//	w.Write(dat)
		//	w.Close()
		//	err = ioutil.WriteFile("out.gz", b.Bytes(), 0666)

		elapsedEncodingTime := time.Since(startEncodingTime)

		fmt.Printf("Time for encoding: %s\n", elapsedEncodingTime)
	}

	if *decode {

		startDecodingTime := time.Now()
		decodedOutput, err := pxl.Decode(*filePath)
		if err != nil {
			fmt.Println(err)
			os.Exit(0)
		}
		elapsedDecodingTime := time.Since(startDecodingTime)
		fmt.Printf("Time for decoding: %s\n", elapsedDecodingTime)
		fmt.Println(string(decodedOutput))
	}
}
<commit_msg>removed file<commit_after><|endoftext|>


<commit_before>package main

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"github.com/mrosset/util"
	"github.com/mrosset/util/console/command"
	"github.com/mrosset/util/file"
	"github.com/mrosset/util/json"
	"github.com/mrosset/via/pkg"
	"gopkg.in/urfave/cli.v2"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

var (
	elog     = log.New(os.Stderr, "", log.Lshortfile)
	root     = flag.String("r", "/", "root directory")
	verbose  = flag.Bool("v", false, "verbose output")
	finstall = flag.Bool("i", true, "install package after build (default true)")
	fdebug   = flag.Bool("d", false, "debug output")
	config   = via.GetConfig()
	fclean   = flag.Bool("c", false, "clean before build")
	fupdate  = flag.Bool("u", false, "force download source")
	fdeps    = flag.Bool("deps", false, "build depends if needed")
	app      = &cli.App{
		Name:  "via",
		Usage: "a systems package manager",
	}

	// build command
	cBuild = &cli.Command{
		Name:   "build",
		Usage:  "builds a plan locally",
		Action: local,
		Flags: []cli.Flag{
			&cli.BoolFlag{
				Name:  "c, clean",
				Value: false,
				Usage: "clean build directory before building",
			},
		},
	}
	// install command
	cInstall = &cli.Command{
		Name:   "install",
		Usage:  "installs package",
		Action: install,
	}
)

func main() {
	app.Commands = []*cli.Command{
		cInstall,
		cBuild,
	}
	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
	return
	flag.Parse()
	via.Verbose(*verbose)
	via.Update(*fupdate)
	via.Deps(*fdeps)

	via.Root(*root)
	util.Verbose = *verbose
	via.Debug(*fdebug)
	command.Add("add", add, "add plan/s to git index")
	command.Add("branch", branch, "prints plan branch to stdout")
	command.Add("dock", dock, "build plan inside docker")
	command.Add("cd", cd, "returns a bash evaluable cd path")
	command.Add("checkout", checkout, "changes plan branch")
	command.Add("clean", clean, "clean build dir")
	command.Add("config", fnConfig, "prints config to stdout")
	command.Add("create", create, "create plan from URL")
	command.Add("diff", diff, "prints git diff for plan(s)")
	command.Add("edit", edit, "calls EDITOR to edit plan")
	command.Add("elf", elf, "prints elf information to stdout")
	command.Add("ipfs", ipfs, "test ipfs connection")
	command.Add("lint", lint, "lint plans")
	command.Add("log", plog, "print config log for plan")
	command.Add("owns", owns, "finds which package owns a file")
	command.Add("options", options, "prints the GNU configure options for a package")
	command.Add("pack", pack, "package plan")
	command.Add("remove", remove, "remove package")
	command.Add("repo", repo, "update repo")
	command.Add("search", search, "search for plans (currently lists all use grep)")
	command.Add("show", fnShow, "prints plan to stdout")
	command.Add("sync", sync, "fetch remote repo data")
	command.Add("synchashs", synchashs, "DEV ONLY sync the plans Oid with binary banch")
	if *fdebug {
		pdebug()
	}
	err = command.Run()
	if err != nil {
		elog.Fatal(err)
	}
	return
}

func install(ctx *cli.Context) error {
	if !ctx.Args().Present() {
		return fmt.Errorf("install requires a 'PLAN' argument. see: 'via help install'")
	}
	return via.Install(ctx.Args().First())
}

func local(ctx *cli.Context) error {
	if !ctx.Args().Present() {
		return fmt.Errorf("build requires a 'PLAN' argument. see: 'via help build'")
	}
	plan, err := via.NewPlan(ctx.Args().First())
	if err != nil {
		return err
	}
	err = via.BuildSteps(plan)
	if err != nil {
		return err
	}

	/*
		arg = strings.Replace(arg, ".json", "", 1)
		if *fclean {
			via.Clean(arg)
		}
		if *fdeps {
			err := via.BuildDeps(plan)
			if err != nil {
				return err
			}
		}
		err = via.BuildSteps(plan)
		if err != nil {
			return err
		}
		if *finstall {
			err := via.Install(plan.Name)
			if err != nil {
				return err
			}
		}
	*/
	return nil
}

func pdebug() {
	path, _ := os.LookupEnv("PATH")
	home, _ := os.LookupEnv("HOME")
	fmt.Println("PATH", path)
	fmt.Println("HOME", home)
	which("GCC", "gcc")
	which("PYTHON", "python")
}

func which(label, path string) {
	fmt.Printf("%s ", label)
	cmd := exec.Command("which", path)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		elog.Println(err)
	}
}

func ipfs() error {
	res, err := http.Get(config.Binary)
	io.Copy(os.Stdout, res.Body)
	return err
}

func cd() error {
	if len(command.Args()) < 1 {
		return errors.New("you need to specify a config path")
	}
	arg := command.Args()[0]
	switch arg {
	case "plans":
		fmt.Printf("cd %s", config.Plans)
	default:
		err := fmt.Sprintf("config path %s not found", arg)
		return errors.New(err)
	}
	return nil
}

func add() error {
	if len(command.Args()) < 1 {
		return errors.New("no plans specified")
	}
	for _, arg := range command.Args() {
		glob := filepath.Join(config.Plans, "*", arg+".json")
		res, err := filepath.Glob(glob)
		if err != nil {
			return err
		}
		git := exec.Command("git", "add", strings.Join(res, " "))
		git.Dir = config.Plans
		git.Stdout = os.Stdout
		git.Stderr = os.Stderr
		err = git.Run()
		if err != nil {
			return err
		}
	}
	return nil
}

func diff() error {
	if len(command.Args()) < 1 {
		return errors.New("no plans specified")
	}
	for _, arg := range command.Args() {
		glob := filepath.Join(config.Plans, "*", arg+".json")
		res, err := filepath.Glob(glob)
		if err != nil {
			return err
		}
		git := exec.Command("git", "diff", strings.Join(res, " "))
		git.Dir = config.Plans
		git.Stdout = os.Stdout
		git.Stderr = os.Stderr
		err = git.Run()
		if err != nil {
			return err
		}
	}
	return nil
}

func checkout() error {
	if len(command.Args()) < 1 {
		return errors.New("git branch needs to be specified")
	}
	arg := command.Args()[0]
	git := exec.Command("git", "checkout", arg)
	git.Dir = config.Plans
	git.Stdout = os.Stdout
	git.Stderr = os.Stderr
	return git.Run()
}

func branch() error {
	git := exec.Command("git", "branch")
	git.Dir = config.Plans
	git.Stdout = os.Stdout
	git.Stderr = os.Stderr
	return git.Run()

}
func edit() error {
	var (
		editor = os.Getenv("EDITOR")
		arg0   = command.Args()[0]
		p      = filepath.Join(config.Plans, "config.json")
		err    error
	)
	if arg0 != "config" {
		p, err = via.FindPlanPath(arg0)
		if err != nil {
			return err
		}
	}
	cmd := exec.Command(editor, p)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		return err
	}
	elog.Println("linting...")
	via.Verbose(false)
	return via.Lint()
}

func create() error {
	url := command.Args()[0]
	group := command.Args()[1]
	err := via.Create(url, group)
	if err != nil {
		return err
	}
	return nil
}

func plog() error {
	for _, arg := range command.Args() {
		plan, err := via.NewPlan(arg)
		if err != nil {
			return err
		}
		f := filepath.Join(plan.BuildDir(), "config.log")
		err = file.Cat(os.Stdout, f)
		if err != nil {
			log.Fatal(err)
		}
	}
	return nil
}

func dock() error {
	arg := command.Args()[0]
	return via.CircuitBuild(arg)
}

func pack() error {
	for _, arg := range command.Args() {
		plan, err := via.NewPlan(arg)
		if err != nil {
			return err
		}
		err = via.Package("", plan)
		if err != nil {
			return err
		}
	}
	return nil
}

func list() error {
	for _, arg := range command.Args() {
		plan, err := via.NewPlan(arg)
		if err != nil {
			return err
		}
		for _, f := range plan.Files {
			fmt.Println(f)
		}
	}
	return nil
}

func remove() error {
	return command.ArgsDo(via.Remove)
}

func lint() error {
	return via.Lint()
}

func fnShow() error {
	for _, arg := range command.Args() {
		plan, err := via.NewPlan(arg)
		if err != nil {
			elog.Fatal(err)
		}
		buf := new(bytes.Buffer)
		less := exec.Command("less")
		less.Stdin = buf
		less.Stdout = os.Stdout
		less.Stderr = os.Stderr
		err = json.WritePretty(&plan, buf)
		if err != nil {
			fmt.Println(err)
		}
		less.Run()
	}
	return nil
}

func fnConfig() error {
	err := json.WritePretty(via.GetConfig(), os.Stdout)
	if err != nil {
		return err
	}
	return nil
}

func clean() error {
	return command.ArgsDo(via.Clean)
}

func elf() error {
	for _, arg := range command.Args() {
		err := via.Readelf(arg)
		if err != nil {
			return err
		}
	}
	return nil
}

func sync() error {
	return via.PlanSync()
}

func synchashs() error {
	via.SyncHashs()
	return nil
}
func owns() error {
	rfiles, err := via.ReadRepoFiles()
	if err != nil {
		return err
	}
	for _, arg := range command.Args() {
		owner := rfiles.Owns(arg)
		if owner == "" {
			fmt.Println(arg+":", "owner not found.")
			continue
		}
		fmt.Println(owner)
	}
	return nil
}

func options() error {
	if len(command.Args()) < 1 {

	}
	arg := command.Args()[0]

	plan, err := via.NewPlan(arg)
	if err != nil {
		return err
	}
	c := filepath.Join(plan.GetStageDir(), "configure")
	fmt.Println(c)
	cmd := exec.Command(c, "--help")
	cmd.Stdout = os.Stdout
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func repo() error {
	return via.RepoCreate()
}

func search() error {
	plans, err := via.GetPlans()
	if err != nil {
		return err
	}
	plans.SortSize().Print()
	return nil
}
<commit_msg>dock command, build flags<commit_after>package main

import (
	"bytes"
	"errors"
	"flag"
	"fmt"
	"github.com/mrosset/util"
	"github.com/mrosset/util/console/command"
	"github.com/mrosset/util/file"
	"github.com/mrosset/util/json"
	"github.com/mrosset/via/pkg"
	"gopkg.in/urfave/cli.v2"
	"io"
	"log"
	"net/http"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
)

var (
	elog     = log.New(os.Stderr, "", log.Lshortfile)
	root     = flag.String("r", "/", "root directory")
	verbose  = flag.Bool("v", false, "verbose output")
	finstall = flag.Bool("i", true, "install package after build (default true)")
	fdebug   = flag.Bool("d", false, "debug output")
	config   = via.GetConfig()
	fclean   = flag.Bool("c", false, "clean before build")
	fupdate  = flag.Bool("u", false, "force download source")
	fdeps    = flag.Bool("deps", false, "build depends if needed")

	app = &cli.App{
		Name:  "via",
		Usage: "a systems package manager",
	}

	// build command
	cBuild = &cli.Command{
		Name:   "build",
		Usage:  "builds a plan locally",
		Action: local,
		Flags: []cli.Flag{
			&cli.BoolFlag{
				Name:  "c",
				Value: false,
				Usage: "clean build directory before building",
			},
			&cli.BoolFlag{
				Name:  "v",
				Value: false,
				Usage: "displays more information when building",
			},
			&cli.BoolFlag{
				Name:  "d",
				Value: false,
				Usage: "displays debugging information when building",
			},
			&cli.BoolFlag{
				Name:  "i",
				Value: false,
				Usage: "install package after building",
			},
		},
	}

	// dock command
	cDock = &cli.Command{
		Name:   "dock",
		Usage:  "builds a package inside a clean docker image",
		Action: dock,
		Flags: []cli.Flag{
			&cli.BoolFlag{
				Name:  "c",
				Value: false,
				Usage: "clean build directory before building",
			},
		},
	}

	// install command
	cInstall = &cli.Command{
		Name:   "install",
		Usage:  "installs package",
		Action: install,
	}
)

func main() {
	app.Commands = []*cli.Command{
		cInstall,
		cBuild,
		cDock,
	}
	err := app.Run(os.Args)
	if err != nil {
		log.Fatal(err)
	}
	return
	flag.Parse()
	via.Verbose(*verbose)
	via.Update(*fupdate)
	via.Deps(*fdeps)

	via.Root(*root)
	util.Verbose = *verbose
	via.Debug(*fdebug)
	command.Add("add", add, "add plan/s to git index")
	command.Add("branch", branch, "prints plan branch to stdout")
	command.Add("cd", cd, "returns a bash evaluable cd path")
	command.Add("checkout", checkout, "changes plan branch")
	command.Add("clean", clean, "clean build dir")
	command.Add("config", fnConfig, "prints config to stdout")
	command.Add("create", create, "create plan from URL")
	command.Add("diff", diff, "prints git diff for plan(s)")
	command.Add("edit", edit, "calls EDITOR to edit plan")
	command.Add("elf", elf, "prints elf information to stdout")
	command.Add("ipfs", ipfs, "test ipfs connection")
	command.Add("lint", lint, "lint plans")
	command.Add("log", plog, "print config log for plan")
	command.Add("owns", owns, "finds which package owns a file")
	command.Add("options", options, "prints the GNU configure options for a package")
	command.Add("pack", pack, "package plan")
	command.Add("remove", remove, "remove package")
	command.Add("repo", repo, "update repo")
	command.Add("search", search, "search for plans (currently lists all use grep)")
	command.Add("show", fnShow, "prints plan to stdout")
	command.Add("sync", sync, "fetch remote repo data")
	command.Add("synchashs", synchashs, "DEV ONLY sync the plans Oid with binary banch")
	if *fdebug {
		pdebug()
	}
	err = command.Run()
	if err != nil {
		elog.Fatal(err)
	}
	return
}

func install(ctx *cli.Context) error {
	if !ctx.Args().Present() {
		return fmt.Errorf("install requires a 'PLAN' argument. see: 'via help install'")
	}
	return via.Install(ctx.Args().First())
}

func local(ctx *cli.Context) error {
	if !ctx.Args().Present() {
		return fmt.Errorf("build requires a 'PLAN' argument. see: 'via help build'")
	}
	plan, err := via.NewPlan(ctx.Args().First())
	if err != nil {
		return err
	}

	via.Verbose(ctx.Bool("v"))
	via.Debug(ctx.Bool("d"))

	if ctx.Bool("c") {
		via.Clean(plan.Name)
	}
	err = via.BuildSteps(plan)
	if err != nil {
		return err
	}
	if ctx.Bool("i") {
		return via.Install(plan.Name)
	}
	return nil
}

func pdebug() {
	path, _ := os.LookupEnv("PATH")
	home, _ := os.LookupEnv("HOME")
	fmt.Println("PATH", path)
	fmt.Println("HOME", home)
	which("GCC", "gcc")
	which("PYTHON", "python")
}

func which(label, path string) {
	fmt.Printf("%s ", label)
	cmd := exec.Command("which", path)
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err := cmd.Run()
	if err != nil {
		elog.Println(err)
	}
}

func ipfs() error {
	res, err := http.Get(config.Binary)
	io.Copy(os.Stdout, res.Body)
	return err
}

func cd() error {
	if len(command.Args()) < 1 {
		return errors.New("you need to specify a config path")
	}
	arg := command.Args()[0]
	switch arg {
	case "plans":
		fmt.Printf("cd %s", config.Plans)
	default:
		err := fmt.Sprintf("config path %s not found", arg)
		return errors.New(err)
	}
	return nil
}

func add() error {
	if len(command.Args()) < 1 {
		return errors.New("no plans specified")
	}
	for _, arg := range command.Args() {
		glob := filepath.Join(config.Plans, "*", arg+".json")
		res, err := filepath.Glob(glob)
		if err != nil {
			return err
		}
		git := exec.Command("git", "add", strings.Join(res, " "))
		git.Dir = config.Plans
		git.Stdout = os.Stdout
		git.Stderr = os.Stderr
		err = git.Run()
		if err != nil {
			return err
		}
	}
	return nil
}

func diff() error {
	if len(command.Args()) < 1 {
		return errors.New("no plans specified")
	}
	for _, arg := range command.Args() {
		glob := filepath.Join(config.Plans, "*", arg+".json")
		res, err := filepath.Glob(glob)
		if err != nil {
			return err
		}
		git := exec.Command("git", "diff", strings.Join(res, " "))
		git.Dir = config.Plans
		git.Stdout = os.Stdout
		git.Stderr = os.Stderr
		err = git.Run()
		if err != nil {
			return err
		}
	}
	return nil
}

func checkout() error {
	if len(command.Args()) < 1 {
		return errors.New("git branch needs to be specified")
	}
	arg := command.Args()[0]
	git := exec.Command("git", "checkout", arg)
	git.Dir = config.Plans
	git.Stdout = os.Stdout
	git.Stderr = os.Stderr
	return git.Run()
}

func branch() error {
	git := exec.Command("git", "branch")
	git.Dir = config.Plans
	git.Stdout = os.Stdout
	git.Stderr = os.Stderr
	return git.Run()

}
func edit() error {
	var (
		editor = os.Getenv("EDITOR")
		arg0   = command.Args()[0]
		p      = filepath.Join(config.Plans, "config.json")
		err    error
	)
	if arg0 != "config" {
		p, err = via.FindPlanPath(arg0)
		if err != nil {
			return err
		}
	}
	cmd := exec.Command(editor, p)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	err = cmd.Run()
	if err != nil {
		return err
	}
	elog.Println("linting...")
	via.Verbose(false)
	return via.Lint()
}

func create() error {
	url := command.Args()[0]
	group := command.Args()[1]
	err := via.Create(url, group)
	if err != nil {
		return err
	}
	return nil
}

func plog() error {
	for _, arg := range command.Args() {
		plan, err := via.NewPlan(arg)
		if err != nil {
			return err
		}
		f := filepath.Join(plan.BuildDir(), "config.log")
		err = file.Cat(os.Stdout, f)
		if err != nil {
			log.Fatal(err)
		}
	}
	return nil
}

func dock(ctx *cli.Context) error {
	return via.CircuitBuild(ctx.Args().First())
}

func pack() error {
	for _, arg := range command.Args() {
		plan, err := via.NewPlan(arg)
		if err != nil {
			return err
		}
		err = via.Package("", plan)
		if err != nil {
			return err
		}
	}
	return nil
}

func list() error {
	for _, arg := range command.Args() {
		plan, err := via.NewPlan(arg)
		if err != nil {
			return err
		}
		for _, f := range plan.Files {
			fmt.Println(f)
		}
	}
	return nil
}

func remove() error {
	return command.ArgsDo(via.Remove)
}

func lint() error {
	return via.Lint()
}

func fnShow() error {
	for _, arg := range command.Args() {
		plan, err := via.NewPlan(arg)
		if err != nil {
			elog.Fatal(err)
		}
		buf := new(bytes.Buffer)
		less := exec.Command("less")
		less.Stdin = buf
		less.Stdout = os.Stdout
		less.Stderr = os.Stderr
		err = json.WritePretty(&plan, buf)
		if err != nil {
			fmt.Println(err)
		}
		less.Run()
	}
	return nil
}

func fnConfig() error {
	err := json.WritePretty(via.GetConfig(), os.Stdout)
	if err != nil {
		return err
	}
	return nil
}

func clean() error {
	return command.ArgsDo(via.Clean)
}

func elf() error {
	for _, arg := range command.Args() {
		err := via.Readelf(arg)
		if err != nil {
			return err
		}
	}
	return nil
}

func sync() error {
	return via.PlanSync()
}

func synchashs() error {
	via.SyncHashs()
	return nil
}
func owns() error {
	rfiles, err := via.ReadRepoFiles()
	if err != nil {
		return err
	}
	for _, arg := range command.Args() {
		owner := rfiles.Owns(arg)
		if owner == "" {
			fmt.Println(arg+":", "owner not found.")
			continue
		}
		fmt.Println(owner)
	}
	return nil
}

func options() error {
	if len(command.Args()) < 1 {

	}
	arg := command.Args()[0]

	plan, err := via.NewPlan(arg)
	if err != nil {
		return err
	}
	c := filepath.Join(plan.GetStageDir(), "configure")
	fmt.Println(c)
	cmd := exec.Command(c, "--help")
	cmd.Stdout = os.Stdout
	cmd.Stdin = os.Stdin
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

func repo() error {
	return via.RepoCreate()
}

func search() error {
	plans, err := via.GetPlans()
	if err != nil {
		return err
	}
	plans.SortSize().Print()
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"encoding/json"
	"encoding/base64"
	"fmt"
	"flag"
	"gopkg.in/gomail.v1"
	"github.com/mpdroog/beanstalkd" //"github.com/maxid/beanstalkd"
	"smtpw/config"
	"time"
	"strings"
	"os"
)

const ERR_WAIT_SEC = 5
var verbose bool
var readonly bool
var hostname string

func proc(m config.Email) error {
	conf, ok := config.C.From[m.From]
	if !ok {
		return errors.New("From does not exist: " + m.From)
	}

	msg := gomail.NewMessage()
	msg.SetHeader("Message-ID", RandText(32) + "@" + hostname)
	msg.SetHeader("From", conf.Display + " <" + conf.From + ">")
	msg.SetHeader("To", m.To...)
	msg.SetHeader("Bcc", conf.Bcc...)
	msg.SetHeader("Subject", m.Subject)
	msg.SetBody("text/plain", m.Text)
	msg.AddAlternative("text/html", m.Html)

	for name, embed := range m.HtmlEmbed {
		raw, e := base64.StdEncoding.DecodeString(embed)
		if e != nil {
			return errors.New("HtmlEmbed: " + name + " is not base64!")
		}
		if !strings.Contains(m.Html, fmt.Sprintf("cid:" + name)) {
			return errors.New("HtmlEmbed: " + name + " is not used in the HTML!")
		}
		msg.Embed(gomail.CreateFile(name, raw))
	}

	if readonly {
		fmt.Println("From: " + conf.Display + " <" + conf.From + ">")
		fmt.Println(fmt.Sprintf("To: %v", m.To))
		fmt.Println(fmt.Sprintf("Bcc: %v", conf.Bcc))
		fmt.Println("Subject: " + m.Subject)
		fmt.Println("\ntext/plain")
		fmt.Println(m.Text)
		fmt.Println("\ntext/html")
		fmt.Println(m.Html)
		fmt.Println("\n")
		return nil
	}

	mailer := gomail.NewMailer(conf.Host, conf.User, conf.Pass, conf.Port)
	return mailer.Send(msg)
}

func connect() (*beanstalkd.BeanstalkdClient, error) {
	queue, e := beanstalkd.Dial(config.C.Beanstalk)
	if e != nil {
		return nil, e
	}
	// Only listen to email queue.
	queue.Use("email")
	if _, e := queue.Watch("email"); e != nil {
		return nil, e
	}
	queue.Ignore("default")
	return queue, nil
}

func main() {
	var (
		configPath string
		skipOne bool
	)
	flag.BoolVar(&verbose, "v", false, "Verbose-mode")
	flag.BoolVar(&skipOne, "s", false, "Delete e-mail on deverr")
	flag.BoolVar(&readonly, "r", false, "Don't email but flush to stdout")
	flag.StringVar(&configPath, "c", "./config.json", "Path to config.json")
	flag.Parse()

	if e := config.Init(configPath); e != nil {
		panic(e)
	}
	// TODO: Test config before starting?

	queue, e := connect()
	if e != nil {
		panic(e)
	}
	hostname, e := os.Hostname()
	if e != nil {
		panic(e)
	}

	if verbose {
		fmt.Println("SMTPw(" + hostname + ") email-tube (ignoring default)")
	}
	if readonly {
		fmt.Println("!! ReadOnly mode !!")
	}
	for {
		job, e := queue.Reserve(0)
		if e != nil {
			fmt.Println("Beanstalkd err: " + e.Error())
			time.Sleep(time.Second * ERR_WAIT_SEC)
			if strings.HasSuffix(e.Error(), "broken pipe") {
				// Beanstalkd down, reconnect!
				q, e := connect()
				if e != nil {
					fmt.Println("Reconnect err: " + e.Error())
				}
				if q != nil {
					queue = q
				}
			}
			continue
		}
		if verbose {
			fmt.Println(fmt.Sprintf("Parse job %d", job.Id))
			fmt.Println("JSON:\r\n" + string(job.Data))
		}
		// Parse
		var m config.Email
		if e := json.Unmarshal(job.Data, &m); e != nil {
			// Broken JSON
			if skipOne {
				fmt.Println("WARN: Skip job as JSON is invalid")
				queue.Delete(job.Id)
				skipOne = false
				continue
			}

			// Ignore decode trouble
			fmt.Println("CRIT: Invalid JSON received (msg=" + e.Error() + ")")
			continue
		}

		if e := proc(m); e != nil {
			// TODO: Isolate deverr from senderr
			// Processing trouble?
			fmt.Println("WARN: Failed sending, retry in 20sec (msg=" + e.Error() + ")")
			continue
		}
		queue.Delete(job.Id)
		if verbose {
			fmt.Println(fmt.Sprintf("Finished job %d", job.Id))
		}
	}
	queue.Quit()
}
<commit_msg>Bugfix. hostname-var in wrong scope and wrong msgid pattern<commit_after>package main

import (
	"errors"
	"encoding/json"
	"encoding/base64"
	"fmt"
	"flag"
	"gopkg.in/gomail.v1"
	"github.com/mpdroog/beanstalkd" //"github.com/maxid/beanstalkd"
	"smtpw/config"
	"time"
	"strings"
	"os"
)

const ERR_WAIT_SEC = 5
var verbose bool
var readonly bool
var hostname string

func proc(m config.Email) error {
	conf, ok := config.C.From[m.From]
	if !ok {
		return errors.New("From does not exist: " + m.From)
	}

	msg := gomail.NewMessage()
	msg.SetHeader("Message-ID", fmt.Sprintf("<%s@%s>", RandText(32), hostname))
	msg.SetHeader("From", conf.Display + " <" + conf.From + ">")
	msg.SetHeader("To", m.To...)
	msg.SetHeader("Bcc", conf.Bcc...)
	msg.SetHeader("Subject", m.Subject)
	msg.SetBody("text/plain", m.Text)
	msg.AddAlternative("text/html", m.Html)

	for name, embed := range m.HtmlEmbed {
		raw, e := base64.StdEncoding.DecodeString(embed)
		if e != nil {
			return errors.New("HtmlEmbed: " + name + " is not base64!")
		}
		if !strings.Contains(m.Html, fmt.Sprintf("cid:" + name)) {
			return errors.New("HtmlEmbed: " + name + " is not used in the HTML!")
		}
		msg.Embed(gomail.CreateFile(name, raw))
	}

	if readonly {
		fmt.Println("From: " + conf.Display + " <" + conf.From + ">")
		fmt.Println(fmt.Sprintf("To: %v", m.To))
		fmt.Println(fmt.Sprintf("Bcc: %v", conf.Bcc))
		fmt.Println("Subject: " + m.Subject)
		fmt.Println("\ntext/plain")
		fmt.Println(m.Text)
		fmt.Println("\ntext/html")
		fmt.Println(m.Html)
		fmt.Println("\n")
		return nil
	}

	mailer := gomail.NewMailer(conf.Host, conf.User, conf.Pass, conf.Port)
	return mailer.Send(msg)
}

func connect() (*beanstalkd.BeanstalkdClient, error) {
	queue, e := beanstalkd.Dial(config.C.Beanstalk)
	if e != nil {
		return nil, e
	}
	// Only listen to email queue.
	queue.Use("email")
	if _, e := queue.Watch("email"); e != nil {
		return nil, e
	}
	queue.Ignore("default")
	return queue, nil
}

func main() {
	var (
		configPath string
		skipOne bool
	)
	flag.BoolVar(&verbose, "v", false, "Verbose-mode")
	flag.BoolVar(&skipOne, "s", false, "Delete e-mail on deverr")
	flag.BoolVar(&readonly, "r", false, "Don't email but flush to stdout")
	flag.StringVar(&configPath, "c", "./config.json", "Path to config.json")
	flag.Parse()

	if e := config.Init(configPath); e != nil {
		panic(e)
	}
	// TODO: Test config before starting?

	queue, e := connect()
	if e != nil {
		panic(e)
	}
	hostname, e = os.Hostname()
	if e != nil {
		panic(e)
	}

	if verbose {
		fmt.Println("SMTPw(" + hostname + ") email-tube (ignoring default)")
	}
	if readonly {
		fmt.Println("!! ReadOnly mode !!")
	}
	for {
		job, e := queue.Reserve(0)
		if e != nil {
			fmt.Println("Beanstalkd err: " + e.Error())
			time.Sleep(time.Second * ERR_WAIT_SEC)
			if strings.HasSuffix(e.Error(), "broken pipe") {
				// Beanstalkd down, reconnect!
				q, e := connect()
				if e != nil {
					fmt.Println("Reconnect err: " + e.Error())
				}
				if q != nil {
					queue = q
				}
			}
			continue
		}
		if verbose {
			fmt.Println(fmt.Sprintf("Parse job %d", job.Id))
			fmt.Println("JSON:\r\n" + string(job.Data))
		}
		// Parse
		var m config.Email
		if e := json.Unmarshal(job.Data, &m); e != nil {
			// Broken JSON
			if skipOne {
				fmt.Println("WARN: Skip job as JSON is invalid")
				queue.Delete(job.Id)
				skipOne = false
				continue
			}

			// Ignore decode trouble
			fmt.Println("CRIT: Invalid JSON received (msg=" + e.Error() + ")")
			continue
		}

		if e := proc(m); e != nil {
			// TODO: Isolate deverr from senderr
			// Processing trouble?
			fmt.Println("WARN: Failed sending, retry in 20sec (msg=" + e.Error() + ")")
			continue
		}
		queue.Delete(job.Id)
		if verbose {
			fmt.Println(fmt.Sprintf("Finished job %d", job.Id))
		}
	}
	queue.Quit()
}
<|endoftext|>


<commit_before>// Copyright 2014 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"github.com/tsuru/tsuru/cmd"
	"github.com/tsuru/tsuru/cmd/tsuru-base"
	"os"
)

const (
	version = "0.8.11.1"
	header  = "Supported-Tsuru"
)

func buildManager(name string) *cmd.Manager {
	lookup := func(m *cmd.Manager, args []string) error {
		context := cmd.Context{Args: args}
		client := cmd.NewClient(nil, nil, m)
		command := plugin{}
		return command.Run(&context, client)
	}
	m := cmd.BuildBaseManager(name, version, header, lookup)
	m.Register(&tsuru.AppRun{})
	m.Register(&tsuru.AppInfo{})
	m.Register(&AppCreate{})
	m.Register(&AppRemove{})
	m.Register(&UnitAdd{})
	m.Register(&UnitRemove{})
	m.Register(tsuru.AppList{})
	m.Register(&tsuru.AppLog{})
	m.Register(&tsuru.AppGrant{})
	m.Register(&tsuru.AppRevoke{})
	m.Register(&tsuru.AppRestart{})
	m.Register(&tsuru.AppStart{})
	m.Register(&tsuru.SetCName{})
	m.Register(&tsuru.UnsetCName{})
	m.Register(&tsuru.EnvGet{})
	m.Register(&tsuru.EnvSet{})
	m.Register(&tsuru.EnvUnset{})
	m.Register(&KeyAdd{})
	m.Register(&KeyRemove{})
	m.Register(tsuru.ServiceList{})
	m.Register(tsuru.ServiceAdd{})
	m.Register(tsuru.ServiceRemove{})
	m.Register(tsuru.ServiceDoc{})
	m.Register(tsuru.ServiceInfo{})
	m.Register(tsuru.ServiceInstanceStatus{})
	m.Register(&tsuru.ServiceBind{})
	m.Register(&tsuru.ServiceUnbind{})
	m.Register(platformList{})
	m.Register(&pluginInstall{})
	m.Register(&pluginRemove{})
	m.Register(&pluginList{})
	m.Register(swap{})
	return m
}

func main() {
	name := cmd.ExtractProgramName(os.Args[0])
	manager := buildManager(name)
	manager.Run(os.Args[1:])
}
<commit_msg>update client versions.<commit_after>// Copyright 2014 tsuru authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	"github.com/tsuru/tsuru/cmd"
	"github.com/tsuru/tsuru/cmd/tsuru-base"
	"os"
)

const (
	version = "0.9.0"
	header  = "Supported-Tsuru"
)

func buildManager(name string) *cmd.Manager {
	lookup := func(m *cmd.Manager, args []string) error {
		context := cmd.Context{Args: args}
		client := cmd.NewClient(nil, nil, m)
		command := plugin{}
		return command.Run(&context, client)
	}
	m := cmd.BuildBaseManager(name, version, header, lookup)
	m.Register(&tsuru.AppRun{})
	m.Register(&tsuru.AppInfo{})
	m.Register(&AppCreate{})
	m.Register(&AppRemove{})
	m.Register(&UnitAdd{})
	m.Register(&UnitRemove{})
	m.Register(tsuru.AppList{})
	m.Register(&tsuru.AppLog{})
	m.Register(&tsuru.AppGrant{})
	m.Register(&tsuru.AppRevoke{})
	m.Register(&tsuru.AppRestart{})
	m.Register(&tsuru.AppStart{})
	m.Register(&tsuru.SetCName{})
	m.Register(&tsuru.UnsetCName{})
	m.Register(&tsuru.EnvGet{})
	m.Register(&tsuru.EnvSet{})
	m.Register(&tsuru.EnvUnset{})
	m.Register(&KeyAdd{})
	m.Register(&KeyRemove{})
	m.Register(tsuru.ServiceList{})
	m.Register(tsuru.ServiceAdd{})
	m.Register(tsuru.ServiceRemove{})
	m.Register(tsuru.ServiceDoc{})
	m.Register(tsuru.ServiceInfo{})
	m.Register(tsuru.ServiceInstanceStatus{})
	m.Register(&tsuru.ServiceBind{})
	m.Register(&tsuru.ServiceUnbind{})
	m.Register(platformList{})
	m.Register(&pluginInstall{})
	m.Register(&pluginRemove{})
	m.Register(&pluginList{})
	m.Register(swap{})
	return m
}

func main() {
	name := cmd.ExtractProgramName(os.Args[0])
	manager := buildManager(name)
	manager.Run(os.Args[1:])
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	mqtt "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
	"log"
	"math"
	"strconv"
	"strings"
	"time"
)

var (
	hub *mqtt.Client
)

type event struct {
	Topic    string
	Payload  []byte
	Retained bool
}

func main() {
	log.Println("Connecting to MQTT... ")

	parserStatus := connectToHub("avr-structparser", "tcp://192.168.42.15:1883", true)
	//parserStatus := connectToHub("avr-structparser", "tcp://localhost:1883", true)
	defer hub.Disconnect(250)

	go logListener("logger/jeelink/+")

	parserStatus <- 1

	done := make(chan struct{})
	<-done // hang around forever
}

// connectToHub sets up an MQTT client and registers as a "jet/..." client.
// Uses last-will to automatically unregister on disconnect. This returns a
// "topic notifier" channel to allow updating the registered status value.
func connectToHub(clientName, port string, retain bool) chan<- interface{} {
	// add a "fairly random" 6-digit suffix to make the client name unique
	nanos := time.Now().UnixNano()
	clientID := fmt.Sprintf("%s/%06d", clientName, nanos%1e6)

	options := mqtt.NewClientOptions()
	options.AddBroker(port)
	options.SetClientID(clientID)
	options.SetKeepAlive(10)
	options.SetBinaryWill("jet/"+clientID, nil, 1, retain)
	hub = mqtt.NewClient(options)

	if t := hub.Connect(); t.Wait() && t.Error() != nil {
		log.Fatal(t.Error())
	}

	if retain {
		log.Println("connected as", clientID, "to", port)
	}

	// register as jet client, cleared on disconnect by the will
	feed := topicNotifier("jet/"+clientID, retain)
	feed <- 0 // start off with state "0" to indicate connection

	// return a topic feed to allow publishing hub status changes
	return feed
}

// topicWatcher turns an MQTT subscription into a channel feed of events.
func topicWatcher(pattern string) <-chan event {
	feed := make(chan event)

	t := hub.Subscribe(pattern, 0, func(hub *mqtt.Client, msg mqtt.Message) {
		feed <- event{
			Topic:    msg.Topic(),
			Payload:  msg.Payload(),
			Retained: msg.Retained(),
		}
	})
	if t.Wait() && t.Error() != nil {
		log.Fatal(t.Error())
	}

	return feed
}

// topicNotifier returns a channel which publishes all its messages to MQTT.
func topicNotifier(topic string, retain bool) chan<- interface{} {
	feed := make(chan interface{})

	go func() {
		for msg := range feed {
			sendToHub(topic, msg, retain)
		}
	}()

	return feed
}

// sendToHub publishes a message, and waits for it to complete successfully.
// Note: does no JSON conversion if the payload is already a []byte.
func sendToHub(topic string, payload interface{}, retain bool) {
	data, ok := payload.([]byte)
	if !ok {
		var e error
		data, e = json.Marshal(payload)
		if e != nil {
			log.Println("json conversion failed:", e, payload)
			return
		}
	}
	t := hub.Publish(topic, 1, retain, data)
	if t.Wait() && t.Error() != nil {
		log.Print(t.Error())
	}
}

/**
 * toBinString
 * Convert received array of bytes representing one byte each to a byte array representing the
 * binary value of the reverted bytes (LSB<>MSB). The returned bytes are '0' and '1'
 */
func toBinData(slices [][]byte) []byte {
	// get the bytes out of the string
	data := make([]byte, 8*(len(slices)))

	// ignore first two and last part (OK, Header and signal quality)
	for i, onenumber := range slices {
		// convert string representation (DEC) of number to a binary one
		uint_onenumber, _ := strconv.ParseUint(string(onenumber), 10, 8)

		// Convert byte to binary represantation AND do MSB<>LSB conversation
		for j := uint(0); j < 8; j++ {
			if 0 != uint_onenumber&(1<<j) {
				data[8*i+int(j)] = '1'
			} else {
				data[8*i+int(j)] = '0'
			}
		}
	}

	return data
}

/**
 * logListener
 * Listens for log messages and parses received data.
 */
func logListener(feed string) {
	for evt := range topicWatcher(feed) {

		// ignore line if it does not start with "OK"
		if !bytes.HasPrefix(evt.Payload, []byte("OK ")) {
			continue
		}

		// Parse timestamp as uint64
		ts, _ := strconv.ParseUint(evt.Topic[strings.LastIndex(evt.Topic, "/")+1:], 10, 64)

		// slicing up the data and extract nodeId of source
		slices := bytes.Split(evt.Payload, []byte(" "))
		origin, _ := strconv.ParseUint(string(slices[1]), 10, 8)
		origin = origin & 0x1F

		// Output received data
		log.Printf("received data on %s from %d at time %d", string(evt.Topic), origin, ts)
		log.Printf("=> parsing payload '%s'", string(evt.Payload))

		// decode received data
		bin := toBinData(slices[2 : len(slices)-1])
		log.Printf("=> %v", string(bin))
		decode(uint(origin), ts, bin)
	}
}

// struct defining one single parsable data field
type fieldTemplate struct {
	size             uint8
	fieldType, label string
	multi            float32
	round            int
	unit             string
	retain           bool
	ignoreUnless     string // ignore this field unless node has corresponding flag set
}

// Correlation between sketches (driver) and fields contained in struct
var drivers = map[string][]fieldTemplate{
	"roomnode.1": {
		{8, "uint", "light", 1, -1, "", true, ""},
		{1, "bool", "moved", 1, -1, "", true, "pir"},
		{7, "uint", "humidity", 1, -1, "%", true, ""},
		{10, "int", "temp", 0.1, 1, "°C", true, ""},
		{8, "batvolt", "bat", 1, -1, "V", true, ""},
	},
	"doornode.1": {
		{10, "int", "temp", 0.1, 1, "°C", true, ""},
		{19, "uint", "pressure", 0.01, 0, "", true, ""},
		{1, "bool", "door1", 1, -1, "", true, "door1"},
		{1, "bool", "door2", 1, -1, "", true, "door2"},
		{1, "bool", "door3", 1, -1, "", true, "door3"},
	},
}

// Correlation between nodeIds and sketch running on it
var nodes = map[uint]struct {
	driver, location string
	flags            []string
}{
	5:  {"roomnode.1", "entrance", []string{"pir"}},
	6:  {"doornode.1", "north", []string{"door1", "door2", "door3"}},
	7:  {"roomnode.1", "outside", []string{}},
	25: {"roomnode.1", "office", []string{}},
	26: {"roomnode.1", "shower", []string{}},
}

func decode(origin uint, ts uint64, data []byte) {
	// locate configuration for node
	node := nodes[origin]
	if node.location == "" {
		log.Printf("!! Node '%d' is not known, ignoring data", origin)
		return
	}
	pattern := drivers[node.driver]
	if len(pattern) == 0 {
		log.Printf("!! Node '%d' uses unknown driver '%s', ignoring data", origin, node.driver)
		return
	}
	log.Printf("=> Node %d (%s) is using driver %s", origin, node.location, node.driver)

	results := make(map[string]interface{})
	var start uint = 0
	for _, field := range pattern {
		// Extracting bits for this specific field and rotate them once more while doing so
		part := make([]byte, field.size)
		for j := uint(0); j < uint(field.size); j++ {
			part[j] = data[start+uint(field.size)-1-j]
		}

		// increment start-index for next field
		start = start + uint(field.size)

		// handle ignoreUnless and check if flag is present
		if field.ignoreUnless != "" {
			skip := true
			for _, flag := range node.flags {
				if flag == field.ignoreUnless {
					skip = false
				}
			}
			if skip {
				continue
			}
		}

		// prepare result for this item
		result := map[string]interface{}{
			"updated": ts,
			"unit":    field.unit,
		}

		switch fieldType := field.fieldType; fieldType {
		case "uint":
			result["value"] = decodeUint(field, part)
		case "int":
			result["value"] = decodeInt(field, part)
		case "bool":
			result["value"] = decodeBool(field, part)
		case "batvolt":
			result["value"] = decodeBatvolt(field, part)
		case "ignore":
			continue
		default:
			log.Printf("Don't know how to handle '%s'", fieldType)
		}
		results[field.label] = result

	}
	log.Printf("%v", results)
}

func decodeUint(field fieldTemplate, data []byte) uint {
	value, _ := strconv.ParseInt(string(data), 2, 32)
	log.Printf("-> Decoded '%s' (%s, %s) as: %d%s", string(data), field.label, field.fieldType, value, field.unit)
	return uint(value)
}

func decodeInt(field fieldTemplate, data []byte) interface{} {
	unsig_tmp, _ := strconv.ParseInt(string(data), 2, 32)

	unsig := int(unsig_tmp)
	mask := 1 << (field.size - 1)
	value := (unsig & ^mask) - (unsig & mask)
	if field.multi != 1.0 {
		floatValue := float64(field.multi) * float64(value)
		shift := math.Pow(10, float64(field.round))
		floatValue = math.Floor((shift*floatValue)+0.5) / shift
		log.Printf("-> Decoded '%s' (%s, %s) as: %s%s", string(data),
			field.label, field.fieldType, strconv.FormatFloat(floatValue, 'f',
				field.round, 64), field.unit)
		return floatValue
	} else {
		log.Printf("-> Decoded '%s' (%s, %s) as: %d%s", string(data), field.label,
			field.fieldType, value, field.unit)
		return value
	}
}

func decodeBool(field fieldTemplate, data []byte) bool {
	value := (data[0] == 49)
	log.Printf("-> Decoded '%s' (%s, %s) as: %t%s", string(data), field.label,
		field.fieldType, value, field.unit)
	return value
}

func decodeBatvolt(field fieldTemplate, data []byte) float64 {
	intValue, _ := strconv.ParseInt(string(data), 2, 64)
	value := float64(3.3/1024) * float64(intValue*4+100)
	log.Printf("-> Decoded '%s' (%s, %s) as: %s%s", string(data), field.label,
		field.fieldType, strconv.FormatFloat(value, 'f', 1, 64), field.unit)
	return value
}
<commit_msg>node-configuration now imported from MQTT at config/tht/avr-structparser/nodes/26<commit_after>package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	mqtt "git.eclipse.org/gitroot/paho/org.eclipse.paho.mqtt.golang.git"
	"log"
	"math"
	"strconv"
	"strings"
	"time"
)

var (
	hub *mqtt.Client
)

type event struct {
	Topic    string
	Payload  []byte
	Retained bool
}

func main() {
	log.Println("Connecting to MQTT... ")

	parserStatus := connectToHub("avr-structparser", "tcp://192.168.42.15:1883", true)
	//parserStatus := connectToHub("avr-structparser", "tcp://localhost:1883", true)
	defer hub.Disconnect(250)

	go nodeConfigListener("config/tht/avr-structparser/nodes/+")

	// Let the config some time to settle down and start the log-listener afterwards
	time.Sleep(1000)
	go logListener("logger/jeelink/+")

	parserStatus <- 1

	done := make(chan struct{})
	<-done // hang around forever
}

// connectToHub sets up an MQTT client and registers as a "jet/..." client.
// Uses last-will to automatically unregister on disconnect. This returns a
// "topic notifier" channel to allow updating the registered status value.
func connectToHub(clientName, port string, retain bool) chan<- interface{} {
	// add a "fairly random" 6-digit suffix to make the client name unique
	nanos := time.Now().UnixNano()
	clientID := fmt.Sprintf("%s/%06d", clientName, nanos%1e6)

	options := mqtt.NewClientOptions()
	options.AddBroker(port)
	options.SetClientID(clientID)
	options.SetKeepAlive(10)
	options.SetBinaryWill("jet/"+clientID, nil, 1, retain)
	hub = mqtt.NewClient(options)

	if t := hub.Connect(); t.Wait() && t.Error() != nil {
		log.Fatal(t.Error())
	}

	if retain {
		log.Println("connected as", clientID, "to", port)
	}

	// register as jet client, cleared on disconnect by the will
	feed := topicNotifier("jet/"+clientID, retain)
	feed <- 0 // start off with state "0" to indicate connection

	// return a topic feed to allow publishing hub status changes
	return feed
}

// topicWatcher turns an MQTT subscription into a channel feed of events.
func topicWatcher(pattern string) <-chan event {
	feed := make(chan event)

	t := hub.Subscribe(pattern, 0, func(hub *mqtt.Client, msg mqtt.Message) {
		feed <- event{
			Topic:    msg.Topic(),
			Payload:  msg.Payload(),
			Retained: msg.Retained(),
		}
	})
	if t.Wait() && t.Error() != nil {
		log.Fatal(t.Error())
	}

	return feed
}

// topicNotifier returns a channel which publishes all its messages to MQTT.
func topicNotifier(topic string, retain bool) chan<- interface{} {
	feed := make(chan interface{})

	go func() {
		for msg := range feed {
			sendToHub(topic, msg, retain)
		}
	}()

	return feed
}

// sendToHub publishes a message, and waits for it to complete successfully.
// Note: does no JSON conversion if the payload is already a []byte.
func sendToHub(topic string, payload interface{}, retain bool) {
	data, ok := payload.([]byte)
	if !ok {
		var e error
		data, e = json.Marshal(payload)
		if e != nil {
			log.Println("json conversion failed:", e, payload)
			return
		}
	}
	t := hub.Publish(topic, 1, retain, data)
	if t.Wait() && t.Error() != nil {
		log.Print(t.Error())
	}
}

/**
 * toBinString
 * Convert received array of bytes representing one byte each to a byte array representing the
 * binary value of the reverted bytes (LSB<>MSB). The returned bytes are '0' and '1'
 */
func toBinData(slices [][]byte) []byte {
	// get the bytes out of the string
	data := make([]byte, 8*(len(slices)))

	// ignore first two and last part (OK, Header and signal quality)
	for i, onenumber := range slices {
		// convert string representation (DEC) of number to a binary one
		uint_onenumber, _ := strconv.ParseUint(string(onenumber), 10, 8)

		// Convert byte to binary represantation AND do MSB<>LSB conversation
		for j := uint(0); j < 8; j++ {
			if 0 != uint_onenumber&(1<<j) {
				data[8*i+int(j)] = '1'
			} else {
				data[8*i+int(j)] = '0'
			}
		}
	}

	return data
}

/**
 * nodeConfigListener
 * Listens for log messages and parses received data.
 */
func nodeConfigListener(feed string) {
	for evt := range topicWatcher(feed) {

		// Output received data
		log.Printf("Receiving configuration for: %s", string(evt.Topic))

		// Extract nodeId
		nodeId, _ := strconv.ParseUint(evt.Topic[strings.LastIndex(evt.Topic, "/")+1:], 10, 64)

		var payload nodeInfo
		if err := json.Unmarshal(evt.Payload, &payload); err != nil {
			log.Println("decode error:", err, evt)
			return
		}
		log.Printf("Decoded data for node %d: %v", nodeId, payload)
		nodes[uint(nodeId)] = payload
	}
}

/**
 * logListener
 * Listens for log messages and parses received data.
 */
func logListener(feed string) {
	for evt := range topicWatcher(feed) {

		// ignore line if it does not start with "OK"
		if !bytes.HasPrefix(evt.Payload, []byte("OK ")) {
			continue
		}

		// Parse timestamp as uint64
		ts, _ := strconv.ParseUint(evt.Topic[strings.LastIndex(evt.Topic, "/")+1:], 10, 64)

		// slicing up the data and extract nodeId of source
		slices := bytes.Split(evt.Payload, []byte(" "))
		origin, _ := strconv.ParseUint(string(slices[1]), 10, 8)
		origin = origin & 0x1F

		// Output received data
		log.Printf("received data on %s from %d at time %d", string(evt.Topic), origin, ts)
		log.Printf("=> parsing payload '%s'", string(evt.Payload))

		// decode received data
		bin := toBinData(slices[2 : len(slices)-1])
		log.Printf("=> %v", string(bin))
		decode(uint(origin), ts, bin)
	}
}

// struct defining one single parsable data field
type fieldTemplate struct {
	size             uint8
	fieldType, label string
	multi            float32
	round            int
	unit             string
	retain           bool
	ignoreUnless     string // ignore this field unless node has corresponding flag set
}

// Correlation between sketches (driver) and fields contained in struct
var drivers = map[string][]fieldTemplate{
	"roomnode.1": {
		{8, "uint", "light", 1, -1, "", true, ""},
		{1, "bool", "moved", 1, -1, "", true, "pir"},
		{7, "uint", "humidity", 1, -1, "%", true, ""},
		{10, "int", "temp", 0.1, 1, "°C", true, ""},
		{8, "batvolt", "bat", 1, -1, "V", true, ""},
	},
	"doornode.1": {
		{10, "int", "temp", 0.1, 1, "°C", true, ""},
		{19, "uint", "pressure", 0.01, 0, "", true, ""},
		{1, "bool", "door1", 1, -1, "", true, "door1"},
		{1, "bool", "door2", 1, -1, "", true, "door2"},
		{1, "bool", "door3", 1, -1, "", true, "door3"},
	},
}

// Correlation between nodeIds and sketch running on it
type nodeInfo struct {
	Driver, Location string
	Flags            []string
}
var nodes = map[uint]nodeInfo {
/*
	5:  {"roomnode.1", "entrance", []string{"pir"}},
	6:  {"doornode.1", "north", []string{"door1", "door2", "door3"}},
	7:  {"roomnode.1", "outside", []string{}},
	25: {"roomnode.1", "office", []string{}},
	26: {"roomnode.1", "shower", []string{}},
*/
}

func decode(origin uint, ts uint64, data []byte) {
	// locate configuration for node
	node := nodes[origin]
	if node.Location == "" {
		log.Printf("!! Node '%d' is not known, ignoring data", origin)
		return
	}
	pattern := drivers[node.Driver]
	if len(pattern) == 0 {
		log.Printf("!! Node '%d' uses unknown driver '%s', ignoring data", origin, node.Driver)
		return
	}
	log.Printf("=> Node %d (%s) is using driver %s", origin, node.Location, node.Driver)

	results := make(map[string]interface{})
	var start uint = 0
	for _, field := range pattern {
		// Extracting bits for this specific field and rotate them once more while doing so
		part := make([]byte, field.size)
		for j := uint(0); j < uint(field.size); j++ {
			part[j] = data[start+uint(field.size)-1-j]
		}

		// increment start-index for next field
		start = start + uint(field.size)

		// handle ignoreUnless and check if flag is present
		if field.ignoreUnless != "" {
			skip := true
			for _, flag := range node.Flags {
				if flag == field.ignoreUnless {
					skip = false
				}
			}
			if skip {
				continue
			}
		}

		// prepare result for this item
		result := map[string]interface{}{
			"updated": ts,
			"unit":    field.unit,
		}

		switch fieldType := field.fieldType; fieldType {
		case "uint":
			result["value"] = decodeUint(field, part)
		case "int":
			result["value"] = decodeInt(field, part)
		case "bool":
			result["value"] = decodeBool(field, part)
		case "batvolt":
			result["value"] = decodeBatvolt(field, part)
		case "ignore":
			continue
		default:
			log.Printf("Don't know how to handle '%s'", fieldType)
		}
		results[field.label] = result

	}
	log.Printf("%v", results)
}

func decodeUint(field fieldTemplate, data []byte) uint {
	value, _ := strconv.ParseInt(string(data), 2, 32)
	log.Printf("-> Decoded '%s' (%s, %s) as: %d%s", string(data), field.label, field.fieldType, value, field.unit)
	return uint(value)
}

func decodeInt(field fieldTemplate, data []byte) interface{} {
	unsig_tmp, _ := strconv.ParseInt(string(data), 2, 32)

	unsig := int(unsig_tmp)
	mask := 1 << (field.size - 1)
	value := (unsig & ^mask) - (unsig & mask)
	if field.multi != 1.0 {
		floatValue := float64(field.multi) * float64(value)
		shift := math.Pow(10, float64(field.round))
		floatValue = math.Floor((shift*floatValue)+0.5) / shift
		log.Printf("-> Decoded '%s' (%s, %s) as: %s%s", string(data),
			field.label, field.fieldType, strconv.FormatFloat(floatValue, 'f',
				field.round, 64), field.unit)
		return floatValue
	} else {
		log.Printf("-> Decoded '%s' (%s, %s) as: %d%s", string(data), field.label,
			field.fieldType, value, field.unit)
		return value
	}
}

func decodeBool(field fieldTemplate, data []byte) bool {
	value := (data[0] == 49)
	log.Printf("-> Decoded '%s' (%s, %s) as: %t%s", string(data), field.label,
		field.fieldType, value, field.unit)
	return value
}

func decodeBatvolt(field fieldTemplate, data []byte) float64 {
	intValue, _ := strconv.ParseInt(string(data), 2, 64)
	value := float64(3.3/1024) * float64(intValue*4+100)
	log.Printf("-> Decoded '%s' (%s, %s) as: %s%s", string(data), field.label,
		field.fieldType, strconv.FormatFloat(value, 'f', 1, 64), field.unit)
	return value
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"flag"

	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/ewhal/nyaa/cache"
	"github.com/ewhal/nyaa/config"
	"github.com/ewhal/nyaa/db"
	"github.com/ewhal/nyaa/network"
	"github.com/ewhal/nyaa/router"
	"github.com/ewhal/nyaa/service/scraper"
	"github.com/ewhal/nyaa/util/log"
	"github.com/ewhal/nyaa/util/search"
	"github.com/ewhal/nyaa/util/signals"
	"github.com/nicksnyder/go-i18n/i18n"
)

func initI18N() {
	/* Initialize the languages translation */
	i18n.MustLoadTranslationFile("translations/en-us.all.json")
	paths, err := filepath.Glob("translations/*.json")
	if err == nil {
		for _, path := range paths {
			i18n.LoadTranslationFile(path)
		}
	}
}

// RunServer runs webapp mainloop
func RunServer(conf *config.Config) {
	http.Handle("/", router.Router)

	// Set up server,
	srv := &http.Server{
		WriteTimeout: 15 * time.Second,
		ReadTimeout:  15 * time.Second,
	}
	l, err := network.CreateHTTPListener(conf)
	log.CheckError(err)
	if err == nil {
		// add http server to be closed gracefully
		signals.RegisterCloser(&network.GracefulHttpCloser{
			Server:   srv,
			Listener: l,
		})
		log.Infof("listening on %s", l.Addr())
		err := srv.Serve(l)
		if err != nil && err != network.ErrListenerStopped {
			log.CheckError(err)
		}

	}
}

// RunScraper runs tracker scraper mainloop
func RunScraper(conf *config.Config) {

	// bind to network
	pc, err := network.CreateScraperSocket(conf)
	if err != nil {
		log.Fatalf("failed to bind udp socket for scraper: %s", err)
	}
	// configure tracker scraperv
	var scraper *scraperService.Scraper
	scraper, err = scraperService.New(&conf.Scrape)
	if err != nil {
		pc.Close()
		log.Fatalf("failed to configure scraper: %s", err)
	}

	workers := conf.Scrape.NumWorkers
	if workers < 1 {
		workers = 1
	}

	// register udp socket with signals
	signals.RegisterCloser(pc)
	// register scraper with signals
	signals.RegisterCloser(scraper)
	// run udp scraper worker
	for workers > 0 {
		log.Infof("starting up worker %d", workers)
		go scraper.RunWorker(pc)
		workers--
	}
	// run scraper
	go scraper.Run()
	scraper.Wait()
}

func main() {
	conf := config.New()
	processFlags := conf.BindFlags()
	defaults := flag.Bool("print-defaults", false, "print the default configuration file on stdout")
	mode := flag.String("mode", "webapp", "which mode to run daemon in, either webapp or scraper")
	flag.Float64Var(&conf.Cache.Size, "c", config.DefaultCacheSize, "size of the search cache in MB")

	flag.Parse()
	if *defaults {
		stdout := bufio.NewWriter(os.Stdout)
		err := conf.Pretty(stdout)
		if err != nil {
			log.Fatal(err.Error())
		}
		err = stdout.Flush()
		if err != nil {
			log.Fatal(err.Error())
		}
		os.Exit(0)
	} else {
		err := processFlags()
		if err != nil {
			log.CheckError(err)
		}
		db.ORM, err = db.GormInit(conf, db.DefaultLogger)
		if err != nil {
			log.Fatal(err.Error())
		}
		initI18N()
		err = cache.Configure(&conf.Cache)
		if err != nil {
			log.Fatal(err.Error())
		}
		err = search.Configure(&conf.Search)
		if err != nil {
			log.Fatal(err.Error())
		}
		go signals.Handle()
		if len(config.TorrentFileStorage) > 0 {
			err := os.MkdirAll(config.TorrentFileStorage, 0700)
			if err != nil {
				log.Fatal(err.Error())
			}
		}
		if *mode == "scraper" {
			RunScraper(conf)
		} else if *mode == "webapp" {
			RunServer(conf)
		} else {
			log.Fatalf("invalid runtime mode: %s", *mode)
		}
	}
}
<commit_msg>Adjust read & write timeouts<commit_after>package main

import (
	"bufio"
	"flag"

	"net/http"
	"os"
	"path/filepath"
	"time"

	"github.com/ewhal/nyaa/cache"
	"github.com/ewhal/nyaa/config"
	"github.com/ewhal/nyaa/db"
	"github.com/ewhal/nyaa/network"
	"github.com/ewhal/nyaa/router"
	"github.com/ewhal/nyaa/service/scraper"
	"github.com/ewhal/nyaa/util/log"
	"github.com/ewhal/nyaa/util/search"
	"github.com/ewhal/nyaa/util/signals"
	"github.com/nicksnyder/go-i18n/i18n"
)

func initI18N() {
	/* Initialize the languages translation */
	i18n.MustLoadTranslationFile("translations/en-us.all.json")
	paths, err := filepath.Glob("translations/*.json")
	if err == nil {
		for _, path := range paths {
			i18n.LoadTranslationFile(path)
		}
	}
}

// RunServer runs webapp mainloop
func RunServer(conf *config.Config) {
	http.Handle("/", router.Router)

	// Set up server,
	srv := &http.Server{
		WriteTimeout: 24 * time.Second,
		ReadTimeout:  8 * time.Second,
	}
	l, err := network.CreateHTTPListener(conf)
	log.CheckError(err)
	if err == nil {
		// add http server to be closed gracefully
		signals.RegisterCloser(&network.GracefulHttpCloser{
			Server:   srv,
			Listener: l,
		})
		log.Infof("listening on %s", l.Addr())
		err := srv.Serve(l)
		if err != nil && err != network.ErrListenerStopped {
			log.CheckError(err)
		}

	}
}

// RunScraper runs tracker scraper mainloop
func RunScraper(conf *config.Config) {

	// bind to network
	pc, err := network.CreateScraperSocket(conf)
	if err != nil {
		log.Fatalf("failed to bind udp socket for scraper: %s", err)
	}
	// configure tracker scraperv
	var scraper *scraperService.Scraper
	scraper, err = scraperService.New(&conf.Scrape)
	if err != nil {
		pc.Close()
		log.Fatalf("failed to configure scraper: %s", err)
	}

	workers := conf.Scrape.NumWorkers
	if workers < 1 {
		workers = 1
	}

	// register udp socket with signals
	signals.RegisterCloser(pc)
	// register scraper with signals
	signals.RegisterCloser(scraper)
	// run udp scraper worker
	for workers > 0 {
		log.Infof("starting up worker %d", workers)
		go scraper.RunWorker(pc)
		workers--
	}
	// run scraper
	go scraper.Run()
	scraper.Wait()
}

func main() {
	conf := config.New()
	processFlags := conf.BindFlags()
	defaults := flag.Bool("print-defaults", false, "print the default configuration file on stdout")
	mode := flag.String("mode", "webapp", "which mode to run daemon in, either webapp or scraper")
	flag.Float64Var(&conf.Cache.Size, "c", config.DefaultCacheSize, "size of the search cache in MB")

	flag.Parse()
	if *defaults {
		stdout := bufio.NewWriter(os.Stdout)
		err := conf.Pretty(stdout)
		if err != nil {
			log.Fatal(err.Error())
		}
		err = stdout.Flush()
		if err != nil {
			log.Fatal(err.Error())
		}
		os.Exit(0)
	} else {
		err := processFlags()
		if err != nil {
			log.CheckError(err)
		}
		db.ORM, err = db.GormInit(conf, db.DefaultLogger)
		if err != nil {
			log.Fatal(err.Error())
		}
		initI18N()
		err = cache.Configure(&conf.Cache)
		if err != nil {
			log.Fatal(err.Error())
		}
		err = search.Configure(&conf.Search)
		if err != nil {
			log.Fatal(err.Error())
		}
		go signals.Handle()
		if len(config.TorrentFileStorage) > 0 {
			err := os.MkdirAll(config.TorrentFileStorage, 0700)
			if err != nil {
				log.Fatal(err.Error())
			}
		}
		if *mode == "scraper" {
			RunScraper(conf)
		} else if *mode == "webapp" {
			RunServer(conf)
		} else {
			log.Fatalf("invalid runtime mode: %s", *mode)
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"crypto/md5"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"strconv"
	"text/template"
	"time"

	"github.com/EthanG78/golang_chat/lib"
	"github.com/satori/go.uuid"
	"golang.org/x/crypto/bcrypt"
)

//////////////////////
//MAIN
/////////////////////

//Create a user
type user struct {
	UserName string
	Pass     string
}

//Establish variables
var dbUsers = map[string]user{}
var dbSessions = map[string]string{}
var tpl *template.Template

//Initialize template reader
func init() {
	tpl = template.Must(template.ParseGlob("templates/*"))
	dbUsers["Test"] = user{"Test", "eth787878"}
}

func homeHandler(tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tpl.Execute(w, r)
	})
}

//Redirects to error page
func forbidden(w http.ResponseWriter, req *http.Request) {
	tpl.ExecuteTemplate(w, "forbidden.gohtml", nil)
}

//Sign up function
func signUp(w http.ResponseWriter, req *http.Request) {
	c, err := req.Cookie("session")
	if err != nil {
		sID := uuid.NewV4()
		c = &http.Cookie{
			Name:  "session",
			Value: sID.String(),
		}
		http.SetCookie(w, c)
	}

	//Check form submission
	var u user
	if req.Method == http.MethodPost {
		un := req.FormValue("username")
		p := req.FormValue("password")

		//Checking to see if user filled out required fields.
		if un == "" {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return

		} else if p == "" {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return
		}
		//Must declare password as a byte after error checking
		pss := []byte(p)
		password, err := bcrypt.GenerateFromPassword(pss, 0)
		if err != nil {
			log.Fatalf("Error logging password for %s", un)
		}

		pass := string(password[:])
		c.Value = un
		u = user{un, pass}

		dbUsers[c.Value] = u
		http.Redirect(w, req, "/login", http.StatusSeeOther)

		log.Println(dbUsers)

		return
	}

	tpl.ExecuteTemplate(w, "signup.gohtml", nil)
}

//Login function
func login(w http.ResponseWriter, req *http.Request) {
	if req.Method == http.MethodPost {
		un := req.FormValue("username")
		pass := req.FormValue("password")

		if un == "" {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return

		} else if pass == "" {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return
		}
		//Does this user exist?? Using comma ok idiom
		u, ok := dbUsers[un]
		if !ok {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return
		}
		//does the username/password combo match at all??
		//Compares bcrypt hash to user input!

		password := []byte(pass)
		hash := []byte(u.Pass)
		err := bcrypt.CompareHashAndPassword(hash, password)
		if err != nil {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return
		}

		//Create a session
		sID := uuid.NewV4()
		c := &http.Cookie{
			Name:     "session",
			Value:    sID.String(),
			HttpOnly: true,
		}

		http.SetCookie(w, c)
		dbSessions[c.Value] = un

		//Genertaing random token for validations
		h := md5.New()
		crutime := int64(-42)
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		io.WriteString(h, "ganraomaxxxxxxxxx")
		Token := fmt.Sprintf("%x", h.Sum(nil))

		//Showing token for debugging
		log.Println(un, ":", Token)

		req.ParseForm()
		Token = req.Form.Get("token")
		if Token != "" {
			http.Redirect(w, req, "/chat", http.StatusSeeOther)
		} else {
			http.Error(w, "Error validating login token.", http.StatusForbidden)
		}
		return
	}

	tpl.ExecuteTemplate(w, "login.gohtml", nil)

}

//Handles site favicon
func faviconHandler(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "styling/favicon.ico")
}

//Handles lassajous animated gif
func lassajousHandler(w http.ResponseWriter, r *http.Request) {
	lib.Lassajous(w)
}

//Handles the home page
func home(w http.ResponseWriter, r *http.Request) {
	tpl.ExecuteTemplate(w, "home.gohtml", nil)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		home(w, r)
	} else {
		log.Printf("rootHandler: Could not forward request for %s any further.", r.RequestURI)
	}
}

//MAIN
func main() {

	//Wrapping handlers

	flag.Parse()
	tpl := template.Must(template.ParseFiles("templates/chat.gohtml"))
	H := lib.NewHub()
	router := http.NewServeMux()
	router.Handle("/styling/", http.StripPrefix("/styling/", http.FileServer(http.Dir("styling/"))))
	router.HandleFunc("/favicon.ico", faviconHandler)
	router.HandleFunc("/", rootHandler)
	router.HandleFunc("/signup", signUp)
	router.HandleFunc("/login", login)
	router.HandleFunc("/forbidden", forbidden)
	router.HandleFunc("/lassajous", lassajousHandler)
	router.Handle("/chat", homeHandler(tpl))
	router.Handle("/ws", lib.WsHandler{H: H})
	log.Println("serving on port 8080")
	log.Println("Users:", dbUsers)
	//log.Println("Sessions: ", dbSessions)
	log.Fatal(http.ListenAndServe(":8080", router))
}

//TODO: Here is a comment, current build is not user friendly!!
//TODO: Build a home function where users can be redirected to and from login, signup and the chat
//TODO: Add redirecting links to go html files
<commit_msg>Cleaned up main.go<commit_after>package main

import (
	"crypto/md5"
	"flag"
	"fmt"
	"io"
	"log"
	"net/http"
	"strconv"
	"text/template"
	"time"

	"github.com/EthanG78/golang_chat/lib"
	"github.com/satori/go.uuid"
	"golang.org/x/crypto/bcrypt"
)

//MAIN

///////////////
//Create a user
///////////////
type user struct {
	UserName string
	Pass     string
}

/////////////////////
//Establish variables
/////////////////////
var dbUsers = map[string]user{}
var dbSessions = map[string]string{}
var tpl *template.Template

////////////////////////////
//Initialize template reader
////////////////////////////
func init() {
	tpl = template.Must(template.ParseGlob("templates/*"))
	dbUsers["Test"] = user{"Test", "eth787878"}
}

func homeHandler(tpl *template.Template) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		tpl.Execute(w, r)
	})
}

/////////////////////////
//Redirects to error page
/////////////////////////
func forbidden(w http.ResponseWriter, req *http.Request) {
	tpl.ExecuteTemplate(w, "forbidden.gohtml", nil)
}

//////////////////
//Sign up function
//////////////////
func signUp(w http.ResponseWriter, req *http.Request) {
	c, err := req.Cookie("session")
	if err != nil {
		sID := uuid.NewV4()
		c = &http.Cookie{
			Name:  "session",
			Value: sID.String(),
		}
		http.SetCookie(w, c)
	}

	//Check form submission
	var u user
	if req.Method == http.MethodPost {
		un := req.FormValue("username")
		p := req.FormValue("password")

		//Checking to see if user filled out required fields.
		if un == "" {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return

		} else if p == "" {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return
		}
		//Must declare password as a byte after error checking
		pss := []byte(p)
		password, err := bcrypt.GenerateFromPassword(pss, 0)
		if err != nil {
			log.Fatalf("Error logging password for %s", un)
		}

		pass := string(password[:])
		c.Value = un
		u = user{un, pass}

		dbUsers[c.Value] = u
		http.Redirect(w, req, "/login", http.StatusSeeOther)

		log.Println(dbUsers)

		return
	}

	tpl.ExecuteTemplate(w, "signup.gohtml", nil)
}

////////////////
//Login function
////////////////
func login(w http.ResponseWriter, req *http.Request) {
	if req.Method == http.MethodPost {
		un := req.FormValue("username")
		pass := req.FormValue("password")

		if un == "" {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return

		} else if pass == "" {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return
		}
		//Does this user exist?? Using comma ok idiom
		u, ok := dbUsers[un]
		if !ok {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return
		}
		//does the username/password combo match at all??
		//Compares bcrypt hash to user input!

		password := []byte(pass)
		hash := []byte(u.Pass)
		err := bcrypt.CompareHashAndPassword(hash, password)
		if err != nil {
			time.Sleep(3000)
			http.Redirect(w, req, "/forbidden", http.StatusSeeOther)
			return
		}

		//Create a session
		sID := uuid.NewV4()
		c := &http.Cookie{
			Name:     "session",
			Value:    sID.String(),
			HttpOnly: true,
		}

		http.SetCookie(w, c)
		dbSessions[c.Value] = un

		//Genertaing random token for validations
		h := md5.New()
		crutime := int64(-42)
		io.WriteString(h, strconv.FormatInt(crutime, 10))
		io.WriteString(h, "ganraomaxxxxxxxxx")
		Token := fmt.Sprintf("%x", h.Sum(nil))

		//Showing token for debugging
		log.Println(un, ":", Token)

		req.ParseForm()
		Token = req.Form.Get("token")
		if Token != "" {
			http.Redirect(w, req, "/chat", http.StatusSeeOther)
		} else {
			http.Error(w, "Error validating login token.", http.StatusForbidden)
		}
		return
	}

	tpl.ExecuteTemplate(w, "login.gohtml", nil)

}

//////////////////////
//Handles site favicon
//////////////////////
func faviconHandler(w http.ResponseWriter, r *http.Request) {
	http.ServeFile(w, r, "styling/favicon.ico")
}

////////////////////////////////
//Handles lassajous animated gif
////////////////////////////////
func lassajousHandler(w http.ResponseWriter, r *http.Request) {
	lib.Lassajous(w)
}

///////////////////////
//Handles the home page
///////////////////////
func home(w http.ResponseWriter, r *http.Request) {
	tpl.ExecuteTemplate(w, "home.gohtml", nil)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	if r.URL.Path == "/" {
		home(w, r)
	} else {
		log.Printf("rootHandler: Could not forward request for %s any further.", r.RequestURI)
	}
}

//////
//MAIN
//////
func main() {

	//Wrapping handlers

	flag.Parse()
	tpl := template.Must(template.ParseFiles("templates/chat.gohtml"))
	H := lib.NewHub()
	router := http.NewServeMux()
	router.Handle("/styling/", http.StripPrefix("/styling/", http.FileServer(http.Dir("styling/"))))
	router.HandleFunc("/favicon.ico", faviconHandler)
	router.HandleFunc("/", rootHandler)
	router.HandleFunc("/signup", signUp)
	router.HandleFunc("/login", login)
	router.HandleFunc("/forbidden", forbidden)
	router.HandleFunc("/lassajous", lassajousHandler)
	router.Handle("/chat", homeHandler(tpl))
	router.Handle("/ws", lib.WsHandler{H: H})
	log.Println("serving on port 8080")
	log.Println("Users:", dbUsers)
	//log.Println("Sessions: ", dbSessions)
	log.Fatal(http.ListenAndServe(":8080", router))
}

//TODO Current build is beta v1.0, it was released on 1/29/2017
//This version is not suer friendly, this will change:)
<|endoftext|>


<commit_before>package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

var credit float64
var expense float64

func parseValue(value string) float64 {
	parsedValue := strings.Replace(value, ",", ".", -1)
	retValue, _ := strconv.ParseFloat(parsedValue, 64)

	return retValue
}

func parseRecord(record []string) {
	// for i := 0; i < len(record); i++ {
	// 	fmt.Println(" ", record[i])
	// }

	for i := 0; i < len(record); i++ {
		// Expense
		if i == 3 {
			value := parseValue(record[i])
			expense += value
			fmt.Println("Expense is ", expense)
		}

		// Credit
		if i == 4 {
			value := parseValue(record[i])
			credit += value
			fmt.Println("Credit is ", credit)
		}
	}

}

// documentation for csv is at http://golang.org/pkg/encoding/csv/
func main() {

	file, error := os.Open("comprovativo.csv")
	if error != nil {
		fmt.Println("Error:", error)
		return
	}
	defer file.Close()

	reader := csv.NewReader(file)
	reader.Comma = ';'
	lineCount := 0

	for {
		record, error := reader.Read()
		if error == io.EOF {
			break
		} else if error != nil {
			fmt.Println("Error:", error)
			return
		}

		fmt.Println("Record", lineCount, "is", record, "and has", len(record), "fields")
		parseRecord(record)

		lineCount++
	}

	// TODO: Fetch data
	// Here, i want this data
	// Initial balance
	// Final Balance
	// Expense per 'description field'
	// Total expense
	// Total credit

}
<commit_msg>Prints the sum of transactions by description<commit_after>package main

import (
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"strconv"
	"strings"
)

var credit float64
var expense float64

func parseValue(value string) float64 {
	parsedValue := strings.Replace(value, ",", ".", -1)
	retValue, _ := strconv.ParseFloat(parsedValue, 64)

	return retValue
}

func parseRecord(record []string) (float64, string) {

	// Columns in the file are:
	// Date of the movement, --, description, expense, credit, --, balance

	for i := 0; i < len(record); i++ {
		// Expense
		if i == 3 && record[i] != "" {
			value := parseValue(record[i])
			expense += value
			fmt.Println("Expense is ", expense)
			return value, record[2]
		}

		// Credit
		if i == 4 && record[i] != "" {
			value := parseValue(record[i])
			credit += value
			fmt.Println("Credit is ", credit)
			return value, record[2]
		}
	}

	return 0, ""
}

// documentation for csv is at http://golang.org/pkg/encoding/csv/
func main() {

	file, error := os.Open("comprovativo.csv")
	if error != nil {
		fmt.Println("Error:", error)
		return
	}
	defer file.Close()

	reader := csv.NewReader(file)
	reader.Comma = ';'
	lineCount := 0

	var report map[string]float64
	report = make(map[string]float64)

	for {
		record, error := reader.Read()
		if error == io.EOF {
			break
		} else if error != nil {
			fmt.Println("Error:", error)
			return
		}

		fmt.Println("Record", lineCount, "is", record, "and has", len(record), "fields")
		transactionValue, transactionDescription := parseRecord(record)
		report[transactionDescription] += transactionValue
		lineCount++
	}

	for transactionDescription, transactionValue := range report {
		fmt.Println(transactionDescription, transactionValue)
	}

	// TODO: Fetch data
	// Here, i want this data
	// Initial balance
	// Final Balance
	// Expense per 'description field'
	// Total expense
	// Total credit

}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"io/ioutil"
	"log"
	"os"
	"runtime"

	"github.com/client9/misspell/lib"
)

func worker(dryrun bool, debug bool, files <-chan string, results chan<- int) {
	fails := 0
	for filename := range files {
		//log.Printf("Scanning %q", filename)
		raw, err := ioutil.ReadFile(filename)
		if err != nil {
			log.Printf("Unable to read %q: %s", filename, err)
			continue
		}
		orig := string(raw)
		updated := lib.Replace(orig, debug)

		count := lib.DiffLines(filename, orig, updated, os.Stdout)
		if count == 0 {
			continue
		}
		fails += count
		//log.Printf("Updating %q", filename)
		if !dryrun {
			ioutil.WriteFile(filename, []byte(updated), 0)
		}
	}
	results <- fails
}

func main() {
	workers := flag.Int("j", 0, "Number of workers, 0 = number of CPUs")
	dryrun := flag.Bool("dry", false, "Dry run")
	debug := flag.Bool("debug", false, "Debug matching, very slow")
	flag.Parse()

	if *workers < 0 {
		log.Fatalf("-j must >= 0")
	}
	if *workers == 0 {
		*workers = runtime.NumCPU()
	}

	if *debug {
		*workers = 1
	}
	args := flag.Args()

	/*
		if len(args) == 0 {
			rawin, err := ioutil.ReadAll(os.Stdin)
			if err != nil {
				panic(err)
			}
			replacer.WriteString(os.Stdout, string(rawin))
			return
		}
	*/
	c := make(chan string, len(args))
	results := make(chan int, *workers)

	for i := 0; i < *workers; i++ {
		go worker(*dryrun, *debug, c, results)
	}

	for _, filename := range args {
		c <- filename
	}
	close(c)

	count := 0
	for i := 0; i < *workers; i++ {
		changed := <-results
		count += changed
	}
	if count != 0 {
		log.Printf("Got %d", count)
		// error
		os.Exit(1)
	}
}
<commit_msg>be quiet<commit_after>package main

import (
	"flag"
	"io/ioutil"
	"log"
	"os"
	"runtime"

	"github.com/client9/misspell/lib"
)

func worker(dryrun bool, debug bool, files <-chan string, results chan<- int) {
	fails := 0
	for filename := range files {
		//log.Printf("Scanning %q", filename)
		raw, err := ioutil.ReadFile(filename)
		if err != nil {
			log.Printf("Unable to read %q: %s", filename, err)
			continue
		}
		orig := string(raw)
		updated := lib.Replace(orig, debug)

		count := lib.DiffLines(filename, orig, updated, os.Stdout)
		if count == 0 {
			continue
		}
		fails += count
		//log.Printf("Updating %q", filename)
		if !dryrun {
			ioutil.WriteFile(filename, []byte(updated), 0)
		}
	}
	results <- fails
}

func main() {
	workers := flag.Int("j", 0, "Number of workers, 0 = number of CPUs")
	dryrun := flag.Bool("dry", false, "Dry run")
	debug := flag.Bool("debug", false, "Debug matching, very slow")
	flag.Parse()

	if *workers < 0 {
		log.Fatalf("-j must >= 0")
	}
	if *workers == 0 {
		*workers = runtime.NumCPU()
	}

	if *debug {
		*workers = 1
	}
	args := flag.Args()

	/*
		if len(args) == 0 {
			rawin, err := ioutil.ReadAll(os.Stdin)
			if err != nil {
				panic(err)
			}
			replacer.WriteString(os.Stdout, string(rawin))
			return
		}
	*/
	c := make(chan string, len(args))
	results := make(chan int, *workers)

	for i := 0; i < *workers; i++ {
		go worker(*dryrun, *debug, c, results)
	}

	for _, filename := range args {
		c <- filename
	}
	close(c)

	count := 0
	for i := 0; i < *workers; i++ {
		changed := <-results
		count += changed
	}
	if count != 0 {
		// log.Printf("Got %d", count)
		// error
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
	"github.com/opencontainers/specs"
)

const (
	version       = "0.3"
	specConfig    = "config.json"
	runtimeConfig = "runtime.json"
	usage         = `Open Container Initiative runtime

runc is a command line client for running applications packaged according to
the Open Container Format (OCF) and is a compliant implementation of the
Open Container Initiative specification.

runc integrates well with existing process supervisors to provide a production
container runtime environment for applications. It can be used with your
existing process monitoring tools and the container will be spawned as a
direct child of the process supervisor.

After creating config files for your root filesystem with runc, you can execute
a container in your shell by running:

    # cd /mycontainer
    # runc start [ -b bundle ]

If not specified, the default value for the 'bundle' is the current directory.
'Bundle' is the directory where '` + specConfig + `' and '` + runtimeConfig + `' must be located.`
)

func main() {
	app := cli.NewApp()
	app.Name = "runc"
	app.Usage = usage
	app.Version = version
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "id",
			Value: getDefaultID(),
			Usage: "specify the ID to be used for the container",
		},
		cli.BoolFlag{
			Name:  "debug",
			Usage: "enable debug output for logging",
		},
		cli.StringFlag{
			Name:  "log",
			Usage: "set the log file path where internal debug information is written",
		},
		cli.StringFlag{
			Name:  "log-format",
			Value: "text",
			Usage: "set the format used by logs ('text' (default), or 'json')",
		},
		cli.StringFlag{
			Name:  "root",
			Value: specs.LinuxStateDirectory,
			Usage: "root directory for storage of container state (this should be located in tmpfs)",
		},
		cli.StringFlag{
			Name:  "criu",
			Value: "criu",
			Usage: "path to the criu binary used for checkpoint and restore",
		},
	}
	app.Commands = []cli.Command{
		startCommand,
		checkpointCommand,
		eventsCommand,
		restoreCommand,
		killCommand,
		specCommand,
		pauseCommand,
		resumeCommand,
		execCommand,
	}
	app.Before = func(context *cli.Context) error {
		if context.GlobalBool("debug") {
			logrus.SetLevel(logrus.DebugLevel)
		}
		if path := context.GlobalString("log"); path != "" {
			f, err := os.Create(path)
			if err != nil {
				return err
			}
			logrus.SetOutput(f)
		}
		switch context.GlobalString("log-format") {
		case "text":
			// retain logrus's default.
		case "json":
			logrus.SetFormatter(new(logrus.JSONFormatter))
		default:
			logrus.Fatalf("unknown log-format %q", context.GlobalString("log-format"))
		}
		return nil
	}
	if err := app.Run(os.Args); err != nil {
		logrus.Fatal(err)
	}
}
<commit_msg>Bump version constant to 0.0.5 in preparation for a new release<commit_after>package main

import (
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
	"github.com/opencontainers/specs"
)

const (
	version       = "0.0.5"
	specConfig    = "config.json"
	runtimeConfig = "runtime.json"
	usage         = `Open Container Initiative runtime

runc is a command line client for running applications packaged according to
the Open Container Format (OCF) and is a compliant implementation of the
Open Container Initiative specification.

runc integrates well with existing process supervisors to provide a production
container runtime environment for applications. It can be used with your
existing process monitoring tools and the container will be spawned as a
direct child of the process supervisor.

After creating config files for your root filesystem with runc, you can execute
a container in your shell by running:

    # cd /mycontainer
    # runc start [ -b bundle ]

If not specified, the default value for the 'bundle' is the current directory.
'Bundle' is the directory where '` + specConfig + `' and '` + runtimeConfig + `' must be located.`
)

func main() {
	app := cli.NewApp()
	app.Name = "runc"
	app.Usage = usage
	app.Version = version
	app.Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "id",
			Value: getDefaultID(),
			Usage: "specify the ID to be used for the container",
		},
		cli.BoolFlag{
			Name:  "debug",
			Usage: "enable debug output for logging",
		},
		cli.StringFlag{
			Name:  "log",
			Usage: "set the log file path where internal debug information is written",
		},
		cli.StringFlag{
			Name:  "log-format",
			Value: "text",
			Usage: "set the format used by logs ('text' (default), or 'json')",
		},
		cli.StringFlag{
			Name:  "root",
			Value: specs.LinuxStateDirectory,
			Usage: "root directory for storage of container state (this should be located in tmpfs)",
		},
		cli.StringFlag{
			Name:  "criu",
			Value: "criu",
			Usage: "path to the criu binary used for checkpoint and restore",
		},
	}
	app.Commands = []cli.Command{
		startCommand,
		checkpointCommand,
		eventsCommand,
		restoreCommand,
		killCommand,
		specCommand,
		pauseCommand,
		resumeCommand,
		execCommand,
	}
	app.Before = func(context *cli.Context) error {
		if context.GlobalBool("debug") {
			logrus.SetLevel(logrus.DebugLevel)
		}
		if path := context.GlobalString("log"); path != "" {
			f, err := os.Create(path)
			if err != nil {
				return err
			}
			logrus.SetOutput(f)
		}
		switch context.GlobalString("log-format") {
		case "text":
			// retain logrus's default.
		case "json":
			logrus.SetFormatter(new(logrus.JSONFormatter))
		default:
			logrus.Fatalf("unknown log-format %q", context.GlobalString("log-format"))
		}
		return nil
	}
	if err := app.Run(os.Args); err != nil {
		logrus.Fatal(err)
	}
}
<|endoftext|>