<commit_before>package cmd

import (
	"fmt"
	"log"
	"strings"

	"github.com/spf13/cobra"
	"github.com/tcnksm/go-gitconfig"
	"github.com/xanzy/go-gitlab"
	"github.com/zaquestion/lab/internal/git"
	lab "github.com/zaquestion/lab/internal/gitlab"
)

var (
	skipClone  = false
	waitFork   = true
	targetData struct {
		project string
		group   string
		path    string
	}
	forkOpts *gitlab.ForkProjectOptions
)

// forkCmd represents the fork command
var forkCmd = &cobra.Command{
	Use:              "fork [upstream-to-fork]",
	Short:            "Fork a remote repository on GitLab and add as remote",
	Long:             ``,
	Args:             cobra.MaximumNArgs(1),
	PersistentPreRun: LabPersistentPreRun,
	Run: func(cmd *cobra.Command, args []string) {
		skipClone, _ = cmd.Flags().GetBool("skip-clone")
		noWaitFork, _ := cmd.Flags().GetBool("no-wait")
		waitFork = !noWaitFork
		targetData.project, _ = cmd.Flags().GetString("name")
		targetData.group, _ = cmd.Flags().GetString("group")
		targetData.path, _ = cmd.Flags().GetString("path")

		if targetData.project != "" || targetData.group != "" ||
			targetData.path != "" {
			forkOpts = &gitlab.ForkProjectOptions{
				Name:      gitlab.String(targetData.project),
				Namespace: gitlab.String(targetData.group),
				Path:      gitlab.String(targetData.path),
			}
		}

		if len(args) == 1 {
			forkToUpstream(cmd, args)
			return
		}
		forkFromOrigin(cmd, args)
	},
}

func forkFromOrigin(cmd *cobra.Command, args []string) {
	// Check for custom target namespace
	remote := lab.User()
	if targetData.group != "" {
		remote = targetData.group
	}

	if _, err := gitconfig.Local("remote." + remote + ".url"); err == nil {
		log.Fatalf("remote: %s already exists", remote)
	}
	if _, err := gitconfig.Local("remote.upstream.url"); err == nil {
		log.Fatal("remote: upstream already exists")
	}

	remoteURL, err := gitconfig.Local("remote.origin.url")
	if err != nil {
		log.Fatal(err)
	}
	if git.IsHub && strings.Contains(remoteURL, "github.com") {
		git := git.New("fork")
		git.Run()
		if err != nil {
			log.Fatal(err)
		}
		return
	}

	project, err := git.PathWithNameSpace("origin")
	if err != nil {
		log.Fatal(err)
	}

	forkRemoteURL, err := lab.Fork(project, forkOpts, useHTTP, waitFork)
	if err != nil {
		if err.Error() == "not finished" {
			fmt.Println("This fork is not ready yet and might take some minutes.")
		} else {
			log.Fatal(err)
		}
	}

	name := determineForkRemote(project)
	err = git.RemoteAdd(name, forkRemoteURL, ".")
	if err != nil {
		log.Fatal(err)
	}
}

func forkToUpstream(cmd *cobra.Command, args []string) {
	project := args[0]
	// lab.Fork doesn't have access to the useHTTP var, so we need to pass
	// this info to that, so the process works correctly.
	_, err := lab.Fork(project, forkOpts, useHTTP, waitFork)
	if err != nil {
		if err.Error() == "not finished" && !skipClone {
			fmt.Println("This fork is not ready yet and might take some minutes.")
			skipClone = true
		} else {
			log.Fatal(err)
		}
	}

	if !skipClone {
		// the clone may happen in a different name/path when compared to
		// the original source project
		namespace := ""
		if targetData.group != "" {
			namespace = targetData.group + "/"
		}

		name := project
		if targetData.path != "" {
			name = targetData.path
		} else if targetData.project != "" {
			name = targetData.project
		} else {
			nameParts := strings.Split(name, "/")
			name = nameParts[len(nameParts)-1]
		}
		cloneCmd.Run(nil, []string{namespace + name})
	}
}

func determineForkRemote(project string) string {
	name := lab.User()
	if targetData.group != "" {
		name = targetData.group
	}
	if strings.Split(project, "/")[0] == name {
		// #78 allow upstream remote to be added when "origin" is
		// referring to the user fork (and the fork already exists)
		name = "upstream"
	}
	return name
}

func init() {
	forkCmd.Flags().BoolP("skip-clone", "s", false, "skip clone after remote fork")
	forkCmd.Flags().Bool("no-wait", false, "don't wait for forking operation to finish")
	forkCmd.Flags().StringP("name", "n", "", "fork project with a different name")
	forkCmd.Flags().StringP("group", "g", "", "fork project in a different group (namespace)")
	forkCmd.Flags().StringP("path", "p", "", "fork project with a different path")
	// useHTTP is defined in "project_create.go"
	forkCmd.Flags().BoolVar(&useHTTP, "http", false, "fork using HTTP protocol instead of SSH")
	RootCmd.AddCommand(forkCmd)
}
<commit_msg>fork: cleanup function args<commit_after>package cmd

import (
	"fmt"
	"log"
	"strings"

	"github.com/spf13/cobra"
	"github.com/tcnksm/go-gitconfig"
	"github.com/xanzy/go-gitlab"
	"github.com/zaquestion/lab/internal/git"
	lab "github.com/zaquestion/lab/internal/gitlab"
)

var (
	skipClone  = false
	waitFork   = true
	targetData struct {
		project string
		group   string
		path    string
	}
	forkOpts *gitlab.ForkProjectOptions
)

// forkCmd represents the fork command
var forkCmd = &cobra.Command{
	Use:              "fork [upstream-to-fork]",
	Short:            "Fork a remote repository on GitLab and add as remote",
	Long:             ``,
	Args:             cobra.MaximumNArgs(1),
	PersistentPreRun: LabPersistentPreRun,
	Run: func(cmd *cobra.Command, args []string) {
		skipClone, _ = cmd.Flags().GetBool("skip-clone")
		noWaitFork, _ := cmd.Flags().GetBool("no-wait")
		waitFork = !noWaitFork
		targetData.project, _ = cmd.Flags().GetString("name")
		targetData.group, _ = cmd.Flags().GetString("group")
		targetData.path, _ = cmd.Flags().GetString("path")

		if targetData.project != "" || targetData.group != "" ||
			targetData.path != "" {
			forkOpts = &gitlab.ForkProjectOptions{
				Name:      gitlab.String(targetData.project),
				Namespace: gitlab.String(targetData.group),
				Path:      gitlab.String(targetData.path),
			}
		}

		if len(args) == 1 {
			forkToUpstream(args[0])
			return
		}
		forkFromOrigin()
	},
}

func forkFromOrigin() {
	// Check for custom target namespace
	remote := lab.User()
	if targetData.group != "" {
		remote = targetData.group
	}

	if _, err := gitconfig.Local("remote." + remote + ".url"); err == nil {
		log.Fatalf("remote: %s already exists", remote)
	}
	if _, err := gitconfig.Local("remote.upstream.url"); err == nil {
		log.Fatal("remote: upstream already exists")
	}

	remoteURL, err := gitconfig.Local("remote.origin.url")
	if err != nil {
		log.Fatal(err)
	}
	if git.IsHub && strings.Contains(remoteURL, "github.com") {
		git := git.New("fork")
		git.Run()
		if err != nil {
			log.Fatal(err)
		}
		return
	}

	project, err := git.PathWithNameSpace("origin")
	if err != nil {
		log.Fatal(err)
	}

	forkRemoteURL, err := lab.Fork(project, forkOpts, useHTTP, waitFork)
	if err != nil {
		if err.Error() == "not finished" {
			fmt.Println("This fork is not ready yet and might take some minutes.")
		} else {
			log.Fatal(err)
		}
	}

	name := determineForkRemote(project)
	err = git.RemoteAdd(name, forkRemoteURL, ".")
	if err != nil {
		log.Fatal(err)
	}
}

func forkToUpstream(project string) {
	// lab.Fork doesn't have access to the useHTTP var, so we need to pass
	// this info to that, so the process works correctly.
	_, err := lab.Fork(project, forkOpts, useHTTP, waitFork)
	if err != nil {
		if err.Error() == "not finished" && !skipClone {
			fmt.Println("This fork is not ready yet and might take some minutes.")
			skipClone = true
		} else {
			log.Fatal(err)
		}
	}

	if !skipClone {
		// the clone may happen in a different name/path when compared to
		// the original source project
		namespace := ""
		if targetData.group != "" {
			namespace = targetData.group + "/"
		}

		name := project
		if targetData.path != "" {
			name = targetData.path
		} else if targetData.project != "" {
			name = targetData.project
		} else {
			nameParts := strings.Split(name, "/")
			name = nameParts[len(nameParts)-1]
		}
		cloneCmd.Run(nil, []string{namespace + name})
	}
}

func determineForkRemote(project string) string {
	name := lab.User()
	if targetData.group != "" {
		name = targetData.group
	}
	if strings.Split(project, "/")[0] == name {
		// #78 allow upstream remote to be added when "origin" is
		// referring to the user fork (and the fork already exists)
		name = "upstream"
	}
	return name
}

func init() {
	forkCmd.Flags().BoolP("skip-clone", "s", false, "skip clone after remote fork")
	forkCmd.Flags().Bool("no-wait", false, "don't wait for forking operation to finish")
	forkCmd.Flags().StringP("name", "n", "", "fork project with a different name")
	forkCmd.Flags().StringP("group", "g", "", "fork project in a different group (namespace)")
	forkCmd.Flags().StringP("path", "p", "", "fork project with a different path")
	// useHTTP is defined in "project_create.go"
	forkCmd.Flags().BoolVar(&useHTTP, "http", false, "fork using HTTP protocol instead of SSH")
	RootCmd.AddCommand(forkCmd)
}
<|endoftext|>


<commit_before>package main

import (
	"os"

	"github.com/urfave/cli"

	"github.com/manifoldco/manifold-cli/config"
)

var cmds []cli.Command

func main() {
	cli.VersionPrinter = func(ctx *cli.Context) {
		versionLookup(ctx)
	}

	app := cli.NewApp()
	app.Name = "manifold-cli"
	app.HelpName = "manifold-cli"
	app.Usage = "A tool making it easy to buy, manage, and integrate developer services into an application."
	app.Version = config.Version
	app.Commands = cmds

	app.Run(os.Args)
}
<commit_msg>Change help output name<commit_after>package main

import (
	"os"

	"github.com/urfave/cli"

	"github.com/manifoldco/manifold-cli/config"
)

var cmds []cli.Command

func main() {
	cli.VersionPrinter = func(ctx *cli.Context) {
		versionLookup(ctx)
	}

	app := cli.NewApp()
	app.Name = "manifold"
	app.HelpName = "manifold"
	app.Usage = "A tool making it easy to buy, manage, and integrate developer services into an application."
	app.Version = config.Version
	app.Commands = cmds

	app.Run(os.Args)
}
<|endoftext|>


<commit_before>package main

import (
	"compress/gzip"
	"errors"
	"flag"
	"fmt"
	"io"
	"os"
	"unicode/utf8"
)

var (
	pkg     = flag.String("p", "main", "package name")
	in      = flag.String("i", "", "input filename")
	out     = flag.String("o", "", "output filename")
	varname = flag.String("v", "httpdir", "http dir variable name")
	help    = flag.Bool("h", false, "show help")
	comp    = flag.Bool("c", false, "compress using gzip")
)

func errHandler(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
}

type replacer struct {
	f *os.File
}

var hexArr = [16]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}

func (r replacer) Write(p []byte) (int, error) {
	var (
		toWrite [5]byte
		t       []byte
		n       int
	)
	toWrite[0] = '\\'
	for len(p) > 0 {
		_, s := utf8.DecodeRune(p)
		t = toWrite[:2]
		if s > 1 || (p[0] >= 0x20 && p[0] < 0x7f) {
			copy(toWrite[1:], p[:s])
			if p[0] != '"' && p[0] != '\\' {
				t = toWrite[1:2]
			}
		} else {
			switch p[0] {
			case '\a':
				toWrite[1] = 'a'
			case '\b':
				toWrite[1] = 'b'
			case '\f':
				toWrite[1] = 'f'
			case '\n':
				toWrite[1] = 'n'
			case '\t':
				toWrite[1] = '	'
				t = toWrite[1:2]
			case '\r':
				toWrite[1] = 'r'
			case '\v':
				toWrite[1] = 'v'
			default:
				toWrite[1] = 'x'
				toWrite[2] = hexArr[p[0]>>4]
				toWrite[3] = hexArr[p[0]&15]
				t = toWrite[:4]
			}
		}
		_, err := r.f.Write(t)
		n += s
		if err != nil {
			return n, err
		}
		p = p[s:]
	}
	return n, nil
}

type tickReplacer struct {
	f *os.File
}

func (r tickReplacer) Write(p []byte) (int, error) {
	var (
		m, n int
		err  error
	)
	hexes := make([]byte, 0, 32)
	toWrite := make([]byte, 0, 1024)
	for len(p) > 0 {
		dr, s := utf8.DecodeRune(p)
		if dr == utf8.RuneError || dr == '`' {
			hexes = append(hexes, p[0])
		} else {
			if len(hexes) > 0 {
				toWrite = toWrite[:0]
				toWrite = append(toWrite, '`', '+', '"')
				for _, b := range hexes {
					if b == '`' {
						toWrite = append(toWrite, '`')
					} else {
						toWrite = append(toWrite, '\\', 'x', hexArr[b>>4], hexArr[b&15])
					}
				}
				toWrite = append(toWrite, '"', '+', '`')
				_, err = r.f.Write(toWrite)
				n += len(hexes)
				if err != nil {
					break
				}
				hexes = hexes[:0]
			}
			m, err = r.f.Write(p[:s])
			n += m
			if err != nil {
				break
			}
		}
		p = p[s:]
	}
	return n, err
}

func main() {
	flag.Parse()
	if *help {
		flag.Usage()
		return
	}
	if *in == "" || *out == "" {
		errHandler(errors.New("missing in/out file"))
	}
	fi, err := os.Open(*in)
	errHandler(err)
	defer fi.Close()
	stat, err := fi.Stat()
	errHandler(err)
	fo, err := os.Create(*out)
	errHandler(err)
	defer fo.Close()
	if *comp {
		_, err = fmt.Fprintf(fo, compressedStart, *pkg)
		errHandler(err)
		w, err := gzip.NewWriterLevel(replacer{fo}, gzip.BestCompression)
		errHandler(err)
		_, err = io.Copy(w, fi)
		errHandler(err)
		errHandler(w.Close())
		_, err = fmt.Fprintf(fo, compressedEnd, stat.ModTime().Unix(), *varname, *in+".gz", *varname, *in, stat.Size())
		errHandler(err)
	} else {
		_, err = fmt.Fprintf(fo, uncompressedStart, *pkg, *varname, *in)
		errHandler(err)
		_, err = io.Copy(tickReplacer{fo}, fi)
		errHandler(err)
		_, err = fmt.Fprintf(fo, uncompressedEnd, stat.ModTime().Unix())
		errHandler(err)
	}
}

const (
	uncompressedStart = `package %s

import (
	"time"

	"github.com/MJKWoolnough/httpdir"
)

func init() {
	%s.Create(%q, httpdir.FileString(` + "`"
	uncompressedEnd = "`" + `, time.Unix(%d, 0)))
}
`

	compressedStart = `package %s

import (
	"time"

	"github.com/MJKWoolnough/httpdir"
)

func init() {
	n := httpdir.FileString("`
	compressedEnd = `", time.Unix(%d, 0))
	%s.Create(%q, n)
	%s.Create(%q, httpdir.Decompressed(n, %d))
}
`
)
<commit_msg>Corrected encoding errors<commit_after>package main

import (
	"compress/gzip"
	"errors"
	"flag"
	"fmt"
	"io"
	"os"
	"unicode/utf8"
)

var (
	pkg     = flag.String("p", "main", "package name")
	in      = flag.String("i", "", "input filename")
	out     = flag.String("o", "", "output filename")
	varname = flag.String("v", "httpdir", "http dir variable name")
	help    = flag.Bool("h", false, "show help")
	comp    = flag.Bool("c", false, "compress using gzip")
)

func errHandler(err error) {
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
}

type replacer struct {
	f *os.File
}

var hexArr = [16]byte{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'}

func (r replacer) Write(p []byte) (int, error) {
	var (
		toWrite [5]byte
		t       []byte
		n       int
	)
	toWrite[0] = '\\'
	for len(p) > 0 {
		dr, s := utf8.DecodeRune(p)
		if dr != utf8.RuneError && (s > 1 || (p[0] >= 0x20 && p[0] < 0x7f)) {
			t = append(toWrite[1:1], p[:s]...)
			if p[0] == '"' || p[0] == '\\' {
				t = toWrite[:2]
			}
		} else {
			t = toWrite[:2]
			switch p[0] {
			case '\a':
				toWrite[1] = 'a'
			case '\b':
				toWrite[1] = 'b'
			case '\f':
				toWrite[1] = 'f'
			case '\n':
				toWrite[1] = 'n'
			case '\t':
				toWrite[1] = '	'
				t = toWrite[1:2]
			case '\r':
				toWrite[1] = 'r'
			case '\v':
				toWrite[1] = 'v'
			default:
				toWrite[1] = 'x'
				toWrite[2] = hexArr[p[0]>>4]
				toWrite[3] = hexArr[p[0]&15]
				t = toWrite[:4]
			}
		}
		_, err := r.f.Write(t)
		n += s
		if err != nil {
			return n, err
		}
		p = p[s:]
	}
	return n, nil
}

type tickReplacer struct {
	f *os.File
}

func (r tickReplacer) Write(p []byte) (int, error) {
	var (
		m, n int
		err  error
	)
	hexes := make([]byte, 0, 32)
	toWrite := make([]byte, 0, 1024)
	for len(p) > 0 {
		dr, s := utf8.DecodeRune(p)
		if dr == utf8.RuneError || dr == '`' || dr == '\r' {
			hexes = append(hexes, p[0])
		} else {
			if len(hexes) > 0 {
				toWrite = toWrite[:0]
				toWrite = append(toWrite, '`', '+', '"')
				for _, b := range hexes {
					if b == '`' {
						toWrite = append(toWrite, '`')
					} else if b == '\r' {
						toWrite = append(toWrite, '\\', 'r')
					} else {
						toWrite = append(toWrite, '\\', 'x', hexArr[b>>4], hexArr[b&15])
					}
				}
				toWrite = append(toWrite, '"', '+', '`')
				_, err = r.f.Write(toWrite)
				n += len(hexes)
				if err != nil {
					break
				}
				hexes = hexes[:0]
			}
			m, err = r.f.Write(p[:s])
			n += m
			if err != nil {
				break
			}
		}
		p = p[s:]
	}
	return n, err
}

func main() {
	flag.Parse()
	if *help {
		flag.Usage()
		return
	}
	if *in == "" || *out == "" {
		errHandler(errors.New("missing in/out file"))
	}
	fi, err := os.Open(*in)
	errHandler(err)
	defer fi.Close()
	stat, err := fi.Stat()
	errHandler(err)
	fo, err := os.Create(*out)
	errHandler(err)
	defer fo.Close()
	if *comp {
		_, err = fmt.Fprintf(fo, compressedStart, *pkg)
		errHandler(err)
		w, err := gzip.NewWriterLevel(replacer{fo}, gzip.BestCompression)
		errHandler(err)
		_, err = io.Copy(w, fi)
		errHandler(err)
		errHandler(w.Close())
		_, err = fmt.Fprintf(fo, compressedEnd, stat.ModTime().Unix(), *varname, *in+".gz", *varname, *in, stat.Size())
		errHandler(err)
	} else {
		_, err = fmt.Fprintf(fo, uncompressedStart, *pkg, *varname, *in)
		errHandler(err)
		_, err = io.Copy(tickReplacer{fo}, fi)
		errHandler(err)
		_, err = fmt.Fprintf(fo, uncompressedEnd, stat.ModTime().Unix())
		errHandler(err)
	}
}

const (
	uncompressedStart = `package %s

import (
	"time"

	"github.com/MJKWoolnough/httpdir"
)

func init() {
	%s.Create(%q, httpdir.FileString(` + "`"
	uncompressedEnd = "`" + `, time.Unix(%d, 0)))
}
`

	compressedStart = `package %s

import (
	"time"

	"github.com/MJKWoolnough/httpdir"
)

func init() {
	n := httpdir.FileString("`
	compressedEnd = `", time.Unix(%d, 0))
	%s.Create(%q, n)
	%s.Create(%q, httpdir.Decompressed(n, %d))
}
`
)
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"os"
	"io/ioutil"
	"path/filepath"
	"strings"

	"github.com/guillaumebreton/regen/generator"
	"github.com/guillaumebreton/regen/loader"
	"github.com/spf13/cobra"
)

//OutputPath represents to path to which template will be outputed
var OutputPath string

// TemplatePath represents the path into which template will be searched
var TemplatePath string
var l = loader.NewLoader()

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "regen directory [-t template.html] [-o output]",
	Short: "Generate an html resume from toml",
	Long: `The tool generate html template from a set of toml file into
  an output directory. The Html template is using the golang templating system
  and the toml structure is defined in the structure.go file
  `,
	Run: func(cmd *cobra.Command, args []string) {
    dir := "."
		if len(args) > 0 {
      dir = args[0]
		}

		//load templates
		files, err := ioutil.ReadDir(dir)
		if err != nil {
			fmt.Println("Fail to list file in directory")
			os.Exit(2)
		}

		//create the ouput path
		_, err = os.Open(OutputPath)
		if err != nil {
			os.Mkdir(OutputPath, 0777)
		}
		fileInfo, err := os.Stat(OutputPath)
		if !fileInfo.IsDir() || err != nil {
			fmt.Printf("File %f is not a directory\n", OutputPath)
			os.Exit(3)
		}
		for _, file := range files {
			if !file.IsDir() {
				ext := filepath.Ext(file.Name())
				if ext == ".toml" {
					resume, err := l.Load(dir, file.Name())
					if err != nil {
						fmt.Printf("Fail to load resume : %+v\n", err)
					} else {
						output, err := generator.Execute(TemplatePath, resume)
						if err != nil {
							fmt.Printf("Fail to generate resume : %+v\n", err)
						} else {

							templateExt := filepath.Ext(TemplatePath)
							filename := strings.TrimSuffix(file.Name(), ext) + templateExt
							fp := filepath.Join(OutputPath, filename)
							err = writeString(fp, output)
							if err != nil {
								fmt.Printf("Fail write to file %s\n", fp)
								fmt.Println(err)
							}

						}
					}
				}
			}

		}
	},
}

//writeString write a string to a file. If the file does
//not exists, it is created, else it's overwritten
func writeString(fp string, data string) error {
	f, err := os.Create(fp)
	if err != nil {
		return err
	}
	_, err = f.WriteString(data)
	return err
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	RootCmd.PersistentFlags().StringVarP(&OutputPath, "output-path", "o", "output", "The destination path for the generated resume")
	RootCmd.PersistentFlags().StringVarP(&TemplatePath, "template", "t", "template.html", "The template to use to generate the resume")
}
<commit_msg>Add information output<commit_after>package cmd

import (
	"fmt"
	"os"
	"io/ioutil"
	"path/filepath"
	"strings"

	"github.com/guillaumebreton/regen/generator"
	"github.com/guillaumebreton/regen/loader"
	"github.com/spf13/cobra"
)

//OutputPath represents to path to which template will be outputed
var OutputPath string

// TemplatePath represents the path into which template will be searched
var TemplatePath string

var l = loader.NewLoader()

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "regen directory [-t template.html] [-o output]",
	Short: "Generate an html resume from toml",
	Long: `The tool generate html template from a set of toml file into
  an output directory. The Html template is using the golang templating system
  and the toml structure is defined in the structure.go file
  `,
	Run: func(cmd *cobra.Command, args []string) {
    dir := "."
		if len(args) > 0 {
      dir = args[0]
		}

		//load templates
		files, err := ioutil.ReadDir(dir)
		if err != nil {
			fmt.Println("Fail to list file in directory")
			os.Exit(2)
		}

		//create the ouput path
		_, err = os.Open(OutputPath)
		if err != nil {
			os.Mkdir(OutputPath, 0777)
		}
		fileInfo, err := os.Stat(OutputPath)
		if !fileInfo.IsDir() || err != nil {
			fmt.Printf("File %f is not a directory\n", OutputPath)
			os.Exit(3)
		}
		for _, file := range files {
			if !file.IsDir() {
				ext := filepath.Ext(file.Name())
				if ext == ".toml" {
					resume, err := l.Load(dir, file.Name())
					if err != nil {
						fmt.Printf("Fail to load resume : %+v\n", err)
					} else {
						output, err := generator.Execute(TemplatePath, resume)
						if err != nil {
							fmt.Printf("Fail to generate resume : %+v\n", err)
						} else {

							templateExt := filepath.Ext(TemplatePath)
							filename := strings.TrimSuffix(file.Name(), ext) + templateExt
							fp := filepath.Join(OutputPath, filename)
							err = writeString(fp, output)
							if err != nil {
								fmt.Printf("Fail write to file %s\n", fp)
								fmt.Println(err)
							} else {
                fmt.Printf("%s generated to %s\n", file.Name(), fp)
              }

						}
					}
				}
			}

		}
	},
}

//writeString write a string to a file. If the file does
//not exists, it is created, else it's overwritten
func writeString(fp string, data string) error {
	f, err := os.Create(fp)
	if err != nil {
		return err
	}
	_, err = f.WriteString(data)
	return err
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	RootCmd.PersistentFlags().StringVarP(&OutputPath, "output-path", "o", "output", "The destination path for the generated resume")
	RootCmd.PersistentFlags().StringVarP(&TemplatePath, "template", "t", "template.html", "The template to use to generate the resume")
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"os"
	"time"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/ttacon/chalk"
)

var EffectiveTimeNow = time.Now() //.round(time.Minute)

var cfgFile string
var Clockfile string
var ModifyEffectiveTime time.Duration

var Debug bool

func D(args ...interface{}) {
	//if viper.GetBool("debug") {
	if Debug {
		//log.Println(chalk.Cyan.Color(fmt.Sprint(args...)))
		fmt.Println(chalk.Cyan.Color(fmt.Sprint(args...)))
	}
}

func GetEffectiveTime() time.Time {
	effectiveTimeNow := time.Now()

	//if ModifyEffectiveTime != nil {
	effectiveTimeNow = effectiveTimeNow.Add(-ModifyEffectiveTime).Round(time.Minute)
	//}
	// Rounding is not performed during entry
	//if roundTime != nil {
	//effectiveTimeNow = effectiveTimeNow.Round(RoundTime)
	//}
	D("Effective time: " + effectiveTimeNow.Format("2006-01-02 15:04"))
	return effectiveTimeNow
}

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "p",
	Short: "Punch or short 'p': A flexible time tracker and time reporting tool",
	Long: `Punch or short 'p': A flexible time tracker and time reporting tool.
made by (and mainly for) Jörg Ramb.

Use this tool to keep track of time spent on projects, assignments, work, etc.
Apart from registering the time periods in a database you
can use this to perform simple todo, logging and reporting on the data.`,
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Here you will define your flags and configuration settings.
	// Cobra supports Persistent Flags, which, if defined here,
	// will be global for your application.

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.punch.yaml)")
	RootCmd.PersistentFlags().StringVarP(&Clockfile, "clockfile", "c", "", "Path to the clockfile = time entry database")
	RootCmd.PersistentFlags().BoolVarP(&Debug, "debug", "D", false, "Enables debug output")
	RootCmd.PersistentFlags().DurationVarP(&ModifyEffectiveTime, "mod", "m", time.Duration(0), "modify effective time (backwards), eg 7m subtracts 7 minutes")
	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	//RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	viper.BindPFlag("clockfile", RootCmd.PersistentFlags().Lookup("clockfile"))
	viper.BindPFlag("debug", RootCmd.PersistentFlags().Lookup("debug"))
	//fmt.Println("2clockfile=", viper.GetString("clockfile"))
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName("punch")                                    // name of config file (without extension)
	viper.AddConfigPath(".")                                        //current
	viper.AddConfigPath("$HOME/.config")                            //config directory
	viper.AddConfigPath("$HOME")                                    // adding home directory as first search path
	if userprofile := os.Getenv("USERPROFILE"); userprofile != "" { //Windows
		viper.AddConfigPath(os.Getenv(userprofile))
	}
	//viper.AutomaticEnv()         // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		D("Using config file: " + viper.ConfigFileUsed())
	}
	//RootCmd.DebugFlags()
}
<commit_msg>fixed pathbugg<commit_after>package cmd

import (
	"fmt"
	"os"
	"time"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
	"github.com/ttacon/chalk"
)

var EffectiveTimeNow = time.Now() //.round(time.Minute)

var cfgFile string
var Clockfile string
var ModifyEffectiveTime time.Duration

var Debug bool

func D(args ...interface{}) {
	//if viper.GetBool("debug") {
	if Debug {
		//log.Println(chalk.Cyan.Color(fmt.Sprint(args...)))
		fmt.Println(chalk.Cyan.Color(fmt.Sprint(args...)))
	}
}

func GetEffectiveTime() time.Time {
	effectiveTimeNow := time.Now()

	//if ModifyEffectiveTime != nil {
	effectiveTimeNow = effectiveTimeNow.Add(-ModifyEffectiveTime).Round(time.Minute)
	//}
	// Rounding is not performed during entry
	//if roundTime != nil {
	//effectiveTimeNow = effectiveTimeNow.Round(RoundTime)
	//}
	D("Effective time: " + effectiveTimeNow.Format("2006-01-02 15:04"))
	return effectiveTimeNow
}

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "p",
	Short: "Punch or short 'p': A flexible time tracker and time reporting tool",
	Long: `Punch or short 'p': A flexible time tracker and time reporting tool.
made by (and mainly for) Jörg Ramb.

Use this tool to keep track of time spent on projects, assignments, work, etc.
Apart from registering the time periods in a database you
can use this to perform simple todo, logging and reporting on the data.`,
}

// Execute adds all child commands to the root command sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)

	// Here you will define your flags and configuration settings.
	// Cobra supports Persistent Flags, which, if defined here,
	// will be global for your application.

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.punch.yaml)")
	RootCmd.PersistentFlags().StringVarP(&Clockfile, "clockfile", "c", "", "Path to the clockfile = time entry database")
	RootCmd.PersistentFlags().BoolVarP(&Debug, "debug", "D", false, "Enables debug output")
	RootCmd.PersistentFlags().DurationVarP(&ModifyEffectiveTime, "mod", "m", time.Duration(0), "modify effective time (backwards), eg 7m subtracts 7 minutes")
	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	//RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
	viper.BindPFlag("clockfile", RootCmd.PersistentFlags().Lookup("clockfile"))
	viper.BindPFlag("debug", RootCmd.PersistentFlags().Lookup("debug"))
	//fmt.Println("2clockfile=", viper.GetString("clockfile"))
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" { // enable ability to specify config file via flag
		viper.SetConfigFile(cfgFile)
	}

	viper.SetConfigName("punch")                                    // name of config file (without extension)
	viper.AddConfigPath(".")                                        //current
	viper.AddConfigPath("$HOME/.config")                            //config directory
	viper.AddConfigPath("$HOME")                                    // adding home directory as first search path
	if userprofile := os.Getenv("USERPROFILE"); userprofile != "" { //Windows
		viper.AddConfigPath(userprofile)
	}
	//viper.AutomaticEnv()         // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		D("Using config file: " + viper.ConfigFileUsed())
	}
	//RootCmd.DebugFlags()
}
<|endoftext|>


<commit_before>// Copyright © 2019 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:     "spiff",
	Short:   "YAML in-domain templating processor",
	Version: "1.3.0-dev",
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	viper.AutomaticEnv() // read in environment variables that match
}

func ReadFile(file string) ([]byte, error) {
	if strings.HasPrefix(file, "http:") || strings.HasPrefix(file, "https:") {
		response, err := http.Get(file)
		if err != nil {
			return nil, fmt.Errorf("error getting [%s]: %s", file, err)
		} else {
			defer response.Body.Close()
			return ioutil.ReadAll(response.Body)
		}
	} else {
		return ioutil.ReadFile(file)
	}
}
<commit_msg>v1.3.0-beta-7<commit_after>// Copyright © 2019 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	"github.com/spf13/cobra"
	"github.com/spf13/viper"
)

var cfgFile string

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:     "spiff",
	Short:   "YAML in-domain templating processor",
	Version: "v1.3.0-beta-7",
}

// Execute adds all child commands to the root command and sets flags appropriately.
// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute() {
	if err := rootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

func init() {
	cobra.OnInitialize(initConfig)
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	viper.AutomaticEnv() // read in environment variables that match
}

func ReadFile(file string) ([]byte, error) {
	if strings.HasPrefix(file, "http:") || strings.HasPrefix(file, "https:") {
		response, err := http.Get(file)
		if err != nil {
			return nil, fmt.Errorf("error getting [%s]: %s", file, err)
		} else {
			defer response.Body.Close()
			return ioutil.ReadAll(response.Body)
		}
	} else {
		return ioutil.ReadFile(file)
	}
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"

	"github.com/dtan4/valec/aws"
	"github.com/dtan4/valec/msg"
	"github.com/dtan4/valec/secret"
	"github.com/dtan4/valec/util"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

// syncCmd represents the sync command
var syncCmd = &cobra.Command{
	Use:   "sync SECRETDIR [NAMESPACE]",
	Short: "Synchronize secrets between local file and DynamoDB",
	RunE:  doSync,
}

var syncOpts = struct {
	dryRun bool
}{}

func doSync(cmd *cobra.Command, args []string) error {
	if len(args) < 1 {
		return errors.New("Please specify secret directory.")
	}
	dirname := args[0]

	if rootOpts.noColor {
		msg.DisableColor()
	}

	files, err := util.ListYAMLFiles(dirname)
	if err != nil {
		return errors.Wrapf(err, "Failed to read directory. dirname=%s", dirname)
	}

	srcNamespaces, err := aws.DynamoDB.ListNamespaces(rootOpts.tableName)
	if err != nil {
		return errors.Wrap(err, "Failed to retrieve namespaces.")
	}

	dstNamespaces := []string{}

	for _, file := range files {
		namespace, err := util.NamespaceFromPath(file, dirname)
		if err != nil {
			return errors.Wrap(err, "Failed to get namespace.")
		}
		dstNamespaces = append(dstNamespaces, namespace)

		if err := syncFile(file, namespace); err != nil {
			return errors.Wrapf(err, "Failed to synchronize file. filename=%s", file)
		}
	}

	_, deleted := util.CompareStrings(srcNamespaces, dstNamespaces)

	for _, namespace := range deleted {
		msg.RedBold.Printf("- %s\n", namespace)
	}

	if len(deleted) > 0 {
		fmt.Printf("%d namespaces will be deleted.\n", len(deleted))

		if !syncOpts.dryRun {
			for _, namespace := range deleted {
				if err := aws.DynamoDB.DeleteNamespace(rootOpts.tableName, namespace); err != nil {
					return errors.Wrapf(err, "Failed to delete namespace. namespace=%s", namespace)
				}
			}

			fmt.Printf("  %d namespaces were successfully deleted.\n", len(deleted))
		}
	}

	return nil
}

func syncFile(filename, namespace string) error {
	msg.Bold.Println(namespace)

	_, srcSecrets, err := secret.LoadFromYAML(filename)
	if err != nil {
		return errors.Wrapf(err, "Failed to load secrets. filename=%s", filename)
	}

	dstSecrets, err := aws.DynamoDB.ListSecrets(rootOpts.tableName, namespace)
	if err != nil {
		return errors.Wrapf(err, "Failed to retrieve secrets. namespace=%s", namespace)
	}

	added, updated, deleted := srcSecrets.CompareList(dstSecrets)

	if len(deleted) > 0 {
		fmt.Printf("%  d secrets will be deleted.\n", len(deleted))
		for _, secret := range deleted {
			msg.Red.Printf("    - %s\n", secret.Key)
		}

		if !syncOpts.dryRun {
			if err := aws.DynamoDB.Delete(rootOpts.tableName, namespace, deleted); err != nil {
				return errors.Wrapf(err, "Failed to delete secrets. namespace=%s", namespace)
			}

			fmt.Printf("  %d secrets were successfully deleted.\n", len(deleted))
		}
	}

	if len(updated) > 0 {
		fmt.Printf("  %d secrets will be updated.\n", len(updated))
		for _, secret := range updated {
			msg.Yellow.Printf("    + %s\n", secret.Key)
		}

		if !syncOpts.dryRun {
			if err := aws.DynamoDB.Insert(rootOpts.tableName, namespace, updated); err != nil {
				return errors.Wrapf(err, "Failed to insert secrets. namespace=%s")
			}

			fmt.Printf("  %d secrets were successfully updated.\n", len(updated))
		}
	}

	if len(added) > 0 {
		fmt.Printf("  %d secrets will be added.\n", len(added))
		for _, secret := range added {
			msg.Green.Printf("    + %s\n", secret.Key)
		}

		if !syncOpts.dryRun {
			if err := aws.DynamoDB.Insert(rootOpts.tableName, namespace, added); err != nil {
				return errors.Wrapf(err, "Failed to insert secrets. namespace=%s")
			}

			fmt.Printf("  %d secrets were successfully added.\n", len(added))
		}
	}

	return nil
}

func init() {
	RootCmd.AddCommand(syncCmd)

	syncCmd.Flags().BoolVar(&syncOpts.dryRun, "dry-run", false, "Dry run")
}
<commit_msg>Modify message indent<commit_after>package cmd

import (
	"fmt"

	"github.com/dtan4/valec/aws"
	"github.com/dtan4/valec/msg"
	"github.com/dtan4/valec/secret"
	"github.com/dtan4/valec/util"
	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

// syncCmd represents the sync command
var syncCmd = &cobra.Command{
	Use:   "sync SECRETDIR [NAMESPACE]",
	Short: "Synchronize secrets between local file and DynamoDB",
	RunE:  doSync,
}

var syncOpts = struct {
	dryRun bool
}{}

func doSync(cmd *cobra.Command, args []string) error {
	if len(args) < 1 {
		return errors.New("Please specify secret directory.")
	}
	dirname := args[0]

	if rootOpts.noColor {
		msg.DisableColor()
	}

	files, err := util.ListYAMLFiles(dirname)
	if err != nil {
		return errors.Wrapf(err, "Failed to read directory. dirname=%s", dirname)
	}

	srcNamespaces, err := aws.DynamoDB.ListNamespaces(rootOpts.tableName)
	if err != nil {
		return errors.Wrap(err, "Failed to retrieve namespaces.")
	}

	dstNamespaces := []string{}

	for _, file := range files {
		namespace, err := util.NamespaceFromPath(file, dirname)
		if err != nil {
			return errors.Wrap(err, "Failed to get namespace.")
		}
		dstNamespaces = append(dstNamespaces, namespace)

		if err := syncFile(file, namespace); err != nil {
			return errors.Wrapf(err, "Failed to synchronize file. filename=%s", file)
		}
	}

	_, deleted := util.CompareStrings(srcNamespaces, dstNamespaces)

	for _, namespace := range deleted {
		msg.RedBold.Printf("- %s\n", namespace)
	}

	if len(deleted) > 0 {
		fmt.Printf("%d namespaces will be deleted.\n", len(deleted))

		if !syncOpts.dryRun {
			for _, namespace := range deleted {
				if err := aws.DynamoDB.DeleteNamespace(rootOpts.tableName, namespace); err != nil {
					return errors.Wrapf(err, "Failed to delete namespace. namespace=%s", namespace)
				}
			}

			fmt.Printf("%d namespaces were successfully deleted.\n", len(deleted))
		}
	}

	return nil
}

func syncFile(filename, namespace string) error {
	msg.Bold.Println(namespace)

	_, srcSecrets, err := secret.LoadFromYAML(filename)
	if err != nil {
		return errors.Wrapf(err, "Failed to load secrets. filename=%s", filename)
	}

	dstSecrets, err := aws.DynamoDB.ListSecrets(rootOpts.tableName, namespace)
	if err != nil {
		return errors.Wrapf(err, "Failed to retrieve secrets. namespace=%s", namespace)
	}

	added, updated, deleted := srcSecrets.CompareList(dstSecrets)

	if len(deleted) > 0 {
		fmt.Printf("%  d secrets will be deleted.\n", len(deleted))
		for _, secret := range deleted {
			msg.Red.Printf("    - %s\n", secret.Key)
		}

		if !syncOpts.dryRun {
			if err := aws.DynamoDB.Delete(rootOpts.tableName, namespace, deleted); err != nil {
				return errors.Wrapf(err, "Failed to delete secrets. namespace=%s", namespace)
			}

			fmt.Printf("  %d secrets were successfully deleted.\n", len(deleted))
		}
	}

	if len(updated) > 0 {
		fmt.Printf("  %d secrets will be updated.\n", len(updated))
		for _, secret := range updated {
			msg.Yellow.Printf("    + %s\n", secret.Key)
		}

		if !syncOpts.dryRun {
			if err := aws.DynamoDB.Insert(rootOpts.tableName, namespace, updated); err != nil {
				return errors.Wrapf(err, "Failed to insert secrets. namespace=%s")
			}

			fmt.Printf("  %d secrets were successfully updated.\n", len(updated))
		}
	}

	if len(added) > 0 {
		fmt.Printf("  %d secrets will be added.\n", len(added))
		for _, secret := range added {
			msg.Green.Printf("    + %s\n", secret.Key)
		}

		if !syncOpts.dryRun {
			if err := aws.DynamoDB.Insert(rootOpts.tableName, namespace, added); err != nil {
				return errors.Wrapf(err, "Failed to insert secrets. namespace=%s")
			}

			fmt.Printf("  %d secrets were successfully added.\n", len(added))
		}
	}

	return nil
}

func init() {
	RootCmd.AddCommand(syncCmd)

	syncCmd.Flags().BoolVar(&syncOpts.dryRun, "dry-run", false, "Dry run")
}
<|endoftext|>


<commit_before>package bimg

import (
	"fmt"
	"path"
	"testing"
)

func TestImageResize(t *testing.T) {
	buf, err := initImage("test.jpg").Resize(300, 240)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	err = assertSize(buf, 300, 240)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_resize_out.jpg", buf)
}

func TestImageExtract(t *testing.T) {
	buf, err := initImage("test.jpg").Extract(100, 100, 300, 300)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 300, 300)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_extract_out.jpg", buf)
}

func TestImageEnlarge(t *testing.T) {
	buf, err := initImage("test.png").Enlarge(500, 375)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	err = assertSize(buf, 500, 375)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_enlarge_out.jpg", buf)
}

func TestImageCrop(t *testing.T) {
	buf, err := initImage("test.jpg").Crop(800, 600, NORTH)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 800, 600)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_crop_out.jpg", buf)
}

func TestImageCropByWidth(t *testing.T) {
	buf, err := initImage("test.jpg").CropByWidth(600)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 600, 375)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_crop_width_out.jpg", buf)
}

func TestImageCropByHeight(t *testing.T) {
	buf, err := initImage("test.jpg").CropByHeight(300)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 480, 300)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_crop_height_out.jpg", buf)
}

func TestImageThumbnail(t *testing.T) {
	buf, err := initImage("test.jpg").Thumbnail(100)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 100, 100)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_thumbnail_out.jpg", buf)
}

func TestImageWatermark(t *testing.T) {
	image := initImage("test.jpg")
	_, err := image.Crop(800, 600, NORTH)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	buf, err := image.Watermark(Watermark{
		Text:       "Copy me if you can",
		Opacity:    0.5,
		Width:      200,
		DPI:        100,
		Background: Color{255, 255, 255},
	})
	if err != nil {
		t.Error(err)
	}

	err = assertSize(buf, 800, 600)
	if err != nil {
		t.Error(err)
	}

	if DetermineImageType(buf) != JPEG {
		t.Fatal("Image is not jpeg")
	}

	Write("fixtures/test_watermark_out.jpg", buf)
}

func TestImageWatermarkNoReplicate(t *testing.T) {
	image := initImage("test.jpg")
	_, err := image.Crop(800, 600, NORTH)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	buf, err := image.Watermark(Watermark{
		Text:        "Copy me if you can",
		Opacity:     0.5,
		Width:       200,
		DPI:         100,
		NoReplicate: true,
		Background:  Color{255, 255, 255},
	})
	if err != nil {
		t.Error(err)
	}

	err = assertSize(buf, 800, 600)
	if err != nil {
		t.Error(err)
	}

	if DetermineImageType(buf) != JPEG {
		t.Fatal("Image is not jpeg")
	}

	Write("fixtures/test_watermark_replicate_out.jpg", buf)
}

func TestImageZoom(t *testing.T) {
	image := initImage("test.jpg")

	_, err := image.Extract(100, 100, 400, 300)
	if err != nil {
		t.Errorf("Cannot extract the image: %s", err)
	}

	buf, err := image.Zoom(1)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 800, 600)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_zoom_out.jpg", buf)
}

func TestImageFlip(t *testing.T) {
	buf, err := initImage("test.jpg").Flip()
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	Write("fixtures/test_flip_out.jpg", buf)
}

func TestImageFlop(t *testing.T) {
	buf, err := initImage("test.jpg").Flop()
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	Write("fixtures/test_flop_out.jpg", buf)
}

func TestImageRotate(t *testing.T) {
	buf, err := initImage("test_flip_out.jpg").Rotate(90)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	Write("fixtures/test_image_rotate_out.jpg", buf)
}

func TestImageConvert(t *testing.T) {
	buf, err := initImage("test.jpg").Convert(PNG)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	Write("fixtures/test_image_convert_out.png", buf)
}

func TestImageMetadata(t *testing.T) {
	data, err := initImage("test.png").Metadata()
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	if data.Alpha != true {
		t.Fatal("Invalid alpha channel")
	}
	if data.Size.Width != 400 {
		t.Fatal("Invalid width size")
	}
	if data.Type != "png" {
		t.Fatal("Invalid image type")
	}
}

func TestFluentInterface(t *testing.T) {
	image := initImage("test.jpg")
	_, err := image.CropByWidth(300)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	_, err = image.Flip()
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	_, err = image.Convert(PNG)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	data, _ := image.Metadata()
	if data.Alpha != false {
		t.Fatal("Invalid alpha channel")
	}
	if data.Size.Width != 300 {
		t.Fatal("Invalid width size")
	}
	if data.Type != "png" {
		t.Fatal("Invalid image type")
	}

	Write("fixtures/test_image_fluent_out.png", image.Image())
}

func initImage(file string) *Image {
	buf, _ := Read(path.Join("fixtures", file))
	return NewImage(buf)
}

func assertSize(buf []byte, width, height int) error {
	size, err := NewImage(buf).Size()
	if err != nil {
		return err
	}
	if size.Width != width || size.Height != height {
		return fmt.Errorf("Invalid image size: %dx%d", size.Width, size.Height)
	}
	return nil
}
<commit_msg>fix(#28): zoom requires extract params<commit_after>package bimg

import (
	"fmt"
	"path"
	"testing"
)

func TestImageResize(t *testing.T) {
	buf, err := initImage("test.jpg").Resize(300, 240)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	err = assertSize(buf, 300, 240)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_resize_out.jpg", buf)
}

func TestImageExtract(t *testing.T) {
	buf, err := initImage("test.jpg").Extract(100, 100, 300, 300)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 300, 300)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_extract_out.jpg", buf)
}

func TestImageEnlarge(t *testing.T) {
	buf, err := initImage("test.png").Enlarge(500, 375)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	err = assertSize(buf, 500, 375)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_enlarge_out.jpg", buf)
}

func TestImageCrop(t *testing.T) {
	buf, err := initImage("test.jpg").Crop(800, 600, NORTH)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 800, 600)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_crop_out.jpg", buf)
}

func TestImageCropByWidth(t *testing.T) {
	buf, err := initImage("test.jpg").CropByWidth(600)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 600, 375)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_crop_width_out.jpg", buf)
}

func TestImageCropByHeight(t *testing.T) {
	buf, err := initImage("test.jpg").CropByHeight(300)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 480, 300)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_crop_height_out.jpg", buf)
}

func TestImageThumbnail(t *testing.T) {
	buf, err := initImage("test.jpg").Thumbnail(100)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 100, 100)
	if err != nil {
		t.Error(err)
	}

	Write("fixtures/test_thumbnail_out.jpg", buf)
}

func TestImageWatermark(t *testing.T) {
	image := initImage("test.jpg")
	_, err := image.Crop(800, 600, NORTH)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	buf, err := image.Watermark(Watermark{
		Text:       "Copy me if you can",
		Opacity:    0.5,
		Width:      200,
		DPI:        100,
		Background: Color{255, 255, 255},
	})
	if err != nil {
		t.Error(err)
	}

	err = assertSize(buf, 800, 600)
	if err != nil {
		t.Error(err)
	}

	if DetermineImageType(buf) != JPEG {
		t.Fatal("Image is not jpeg")
	}

	Write("fixtures/test_watermark_out.jpg", buf)
}

func TestImageWatermarkNoReplicate(t *testing.T) {
	image := initImage("test.jpg")
	_, err := image.Crop(800, 600, NORTH)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	buf, err := image.Watermark(Watermark{
		Text:        "Copy me if you can",
		Opacity:     0.5,
		Width:       200,
		DPI:         100,
		NoReplicate: true,
		Background:  Color{255, 255, 255},
	})
	if err != nil {
		t.Error(err)
	}

	err = assertSize(buf, 800, 600)
	if err != nil {
		t.Error(err)
	}

	if DetermineImageType(buf) != JPEG {
		t.Fatal("Image is not jpeg")
	}

	Write("fixtures/test_watermark_replicate_out.jpg", buf)
}

func TestImageZoom(t *testing.T) {
	image := initImage("test.jpg")

	_, err := image.Extract(100, 100, 0, 0)
	if err != nil {
		t.Errorf("Cannot extract the image: %s", err)
	}

	buf, err := image.Zoom(1)
	if err != nil {
		t.Errorf("Cannot process the image: %s", err)
	}

	err = assertSize(buf, 800, 600)
	if err != nil {
		//t.Error(err)
	}

	Write("fixtures/test_zoom_out.jpg", buf)
}

func TestImageFlip(t *testing.T) {
	buf, err := initImage("test.jpg").Flip()
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	Write("fixtures/test_flip_out.jpg", buf)
}

func TestImageFlop(t *testing.T) {
	buf, err := initImage("test.jpg").Flop()
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	Write("fixtures/test_flop_out.jpg", buf)
}

func TestImageRotate(t *testing.T) {
	buf, err := initImage("test_flip_out.jpg").Rotate(90)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	Write("fixtures/test_image_rotate_out.jpg", buf)
}

func TestImageConvert(t *testing.T) {
	buf, err := initImage("test.jpg").Convert(PNG)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	Write("fixtures/test_image_convert_out.png", buf)
}

func TestImageMetadata(t *testing.T) {
	data, err := initImage("test.png").Metadata()
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}
	if data.Alpha != true {
		t.Fatal("Invalid alpha channel")
	}
	if data.Size.Width != 400 {
		t.Fatal("Invalid width size")
	}
	if data.Type != "png" {
		t.Fatal("Invalid image type")
	}
}

func TestFluentInterface(t *testing.T) {
	image := initImage("test.jpg")
	_, err := image.CropByWidth(300)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	_, err = image.Flip()
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	_, err = image.Convert(PNG)
	if err != nil {
		t.Errorf("Cannot process the image: %#v", err)
	}

	data, _ := image.Metadata()
	if data.Alpha != false {
		t.Fatal("Invalid alpha channel")
	}
	if data.Size.Width != 300 {
		t.Fatal("Invalid width size")
	}
	if data.Type != "png" {
		t.Fatal("Invalid image type")
	}

	Write("fixtures/test_image_fluent_out.png", image.Image())
}

func initImage(file string) *Image {
	buf, _ := Read(path.Join("fixtures", file))
	return NewImage(buf)
}

func assertSize(buf []byte, width, height int) error {
	size, err := NewImage(buf).Size()
	if err != nil {
		return err
	}
	if size.Width != width || size.Height != height {
		return fmt.Errorf("Invalid image size: %dx%d", size.Width, size.Height)
	}
	return nil
}
<|endoftext|>


<commit_before>// Copyright © 2017 Mikael Berthe <mikael@lilotux.net>
//
// Licensed under the MIT license.
// Please see the LICENSE file is this directory.

package cmd

import (
	"github.com/pkg/errors"
	"github.com/spf13/cobra"

	"github.com/McKael/madon"
)

// toot is a kind of alias for status post

func init() {
	RootCmd.AddCommand(tootAliasCmd)

	tootAliasCmd.Flags().BoolVar(&statusOpts.sensitive, "sensitive", false, "Mark post as sensitive (NSFW)")
	tootAliasCmd.Flags().StringVar(&statusOpts.visibility, "visibility", "", "Visibility (direct|private|unlisted|public)")
	tootAliasCmd.Flags().StringVar(&statusOpts.spoiler, "spoiler", "", "Spoiler warning (CW)")
	tootAliasCmd.Flags().StringVar(&statusOpts.mediaIDs, "media-ids", "", "Comma-separated list of media IDs")
	tootAliasCmd.Flags().StringVarP(&statusOpts.mediaFilePath, "file", "f", "", "Media attachment file name")
	tootAliasCmd.Flags().StringVar(&statusOpts.textFilePath, "text-file", "", "Text file name (message content)")
	tootAliasCmd.Flags().Int64VarP(&statusOpts.inReplyToID, "in-reply-to", "r", 0, "Status ID to reply to")

	// Flag completion
	annotation := make(map[string][]string)
	annotation[cobra.BashCompCustom] = []string{"__madonctl_visibility"}

	tootAliasCmd.Flags().Lookup("visibility").Annotations = annotation
}

var tootAliasCmd = &cobra.Command{
	Use:     "toot",
	Aliases: []string{"post", "pouet"},
	Short:   "Post a message (toot)",
	Example: `  madonctl toot message
  madonctl toot --spoiler Warning "Hello, World"
  madonctl status post --media-ids ID1,ID2 "Here are the photos"
  madonctl post --sensitive --file image.jpg Image
  madonctl toot --text-file message.txt`,
	RunE: func(cmd *cobra.Command, args []string) error {
		if err := madonInit(true); err != nil {
			return err
		}
		return statusSubcommandRunE("post", args)
	},
}

func toot(tootText string) (*madon.Status, error) {
	opt := statusOpts

	switch opt.visibility {
	case "", "direct", "private", "unlisted", "public":
		// OK
	default:
		return nil, errors.New("invalid visibility argument value")
	}

	if opt.inReplyToID < 0 {
		return nil, errors.New("invalid in-reply-to argument value")
	}

	ids, err := splitIDs(opt.mediaIDs)
	if err != nil {
		return nil, errors.New("cannot parse media IDs")
	}

	if opt.mediaFilePath != "" {
		if len(ids) > 3 {
			return nil, errors.New("too many media attachments")
		}

		fileMediaID, err := uploadFile(opt.mediaFilePath)
		if err != nil {
			return nil, errors.Wrap(err, "cannot attach media file")
		}
		if fileMediaID > 0 {
			ids = append(ids, fileMediaID)
		}
	}

	return gClient.PostStatus(tootText, opt.inReplyToID, ids, opt.sensitive, opt.spoiler, opt.visibility)
}
<commit_msg>Do not make an API call if toot has no content<commit_after>// Copyright © 2017 Mikael Berthe <mikael@lilotux.net>
//
// Licensed under the MIT license.
// Please see the LICENSE file is this directory.

package cmd

import (
	"github.com/pkg/errors"
	"github.com/spf13/cobra"

	"github.com/McKael/madon"
)

// toot is a kind of alias for status post

func init() {
	RootCmd.AddCommand(tootAliasCmd)

	tootAliasCmd.Flags().BoolVar(&statusOpts.sensitive, "sensitive", false, "Mark post as sensitive (NSFW)")
	tootAliasCmd.Flags().StringVar(&statusOpts.visibility, "visibility", "", "Visibility (direct|private|unlisted|public)")
	tootAliasCmd.Flags().StringVar(&statusOpts.spoiler, "spoiler", "", "Spoiler warning (CW)")
	tootAliasCmd.Flags().StringVar(&statusOpts.mediaIDs, "media-ids", "", "Comma-separated list of media IDs")
	tootAliasCmd.Flags().StringVarP(&statusOpts.mediaFilePath, "file", "f", "", "Media attachment file name")
	tootAliasCmd.Flags().StringVar(&statusOpts.textFilePath, "text-file", "", "Text file name (message content)")
	tootAliasCmd.Flags().Int64VarP(&statusOpts.inReplyToID, "in-reply-to", "r", 0, "Status ID to reply to")

	// Flag completion
	annotation := make(map[string][]string)
	annotation[cobra.BashCompCustom] = []string{"__madonctl_visibility"}

	tootAliasCmd.Flags().Lookup("visibility").Annotations = annotation
}

var tootAliasCmd = &cobra.Command{
	Use:     "toot",
	Aliases: []string{"post", "pouet"},
	Short:   "Post a message (toot)",
	Example: `  madonctl toot message
  madonctl toot --spoiler Warning "Hello, World"
  madonctl status post --media-ids ID1,ID2 "Here are the photos"
  madonctl post --sensitive --file image.jpg Image
  madonctl toot --text-file message.txt`,
	RunE: func(cmd *cobra.Command, args []string) error {
		if err := madonInit(true); err != nil {
			return err
		}
		return statusSubcommandRunE("post", args)
	},
}

func toot(tootText string) (*madon.Status, error) {
	opt := statusOpts

	switch opt.visibility {
	case "", "direct", "private", "unlisted", "public":
		// OK
	default:
		return nil, errors.New("invalid visibility argument value")
	}

	if opt.inReplyToID < 0 {
		return nil, errors.New("invalid in-reply-to argument value")
	}

	ids, err := splitIDs(opt.mediaIDs)
	if err != nil {
		return nil, errors.New("cannot parse media IDs")
	}

	if opt.mediaFilePath != "" {
		if len(ids) > 3 {
			return nil, errors.New("too many media attachments")
		}

		fileMediaID, err := uploadFile(opt.mediaFilePath)
		if err != nil {
			return nil, errors.Wrap(err, "cannot attach media file")
		}
		if fileMediaID > 0 {
			ids = append(ids, fileMediaID)
		}
	}

	if tootText == "" && len(ids) == 0 && opt.spoiler == "" {
		return nil, errors.New("toot is empty")
	}

	return gClient.PostStatus(tootText, opt.inReplyToID, ids, opt.sensitive, opt.spoiler, opt.visibility)
}
<|endoftext|>


<commit_before>// Copyright 2012 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 errors

import (
	. "launchpad.net/gocheck"
	"testing"
)

func Test(t *testing.T) { TestingT(t) }

type S struct{}

var _ = Suite(&S{})

func (s *S) TestErrorMethodShouldReturnTheMessageString(c *C) {
	e := Http{500, "Internal server error"}
	c.Assert(e.Error(), Equals, e.Message)
}
<commit_msg>errors: don't use unqualified imports for gocheck<commit_after>// Copyright 2013 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 errors

import (
	"launchpad.net/gocheck"
	"testing"
)

func Test(t *testing.T) { gocheck.TestingT(t) }

type S struct{}

var _ = gocheck.Suite(&S{})

func (s *S) TestErrorMethodShouldReturnTheMessageString(c *gocheck.C) {
	e := Http{500, "Internal server error"}
	c.Assert(e.Error(), gocheck.Equals, e.Message)
}
<|endoftext|>


<commit_before>package channels

import (
// "log"
)

// RelayFilter objects provide a predicate function to determine whether a
// message should be passed to the next stage
type RelayFilter interface {
	Filter(Delivery) bool
}

type IncludeAll struct{}

func (filter *IncludeAll) Filter(delivery Delivery) bool {
	return true
}

type Relay struct {
	consumerChannel ConsumerChannel
	publisher       Publisher
	filter          RelayFilter
}

func (relay *Relay) Start() bool {
	return relay.consumerChannel.StartConsuming()
}

func (relay *Relay) Stop() bool {
	return relay.consumerChannel.StopConsuming()
}

type RelayConsumer struct {
	relay *Relay
}

func (consumer *RelayConsumer) Consume(delivery Delivery) {
	if consumer.relay.filter.Filter(delivery) {
		consumer.relay.publisher.Publish(delivery.Payload())
	}
	delivery.Ack()
}

func NewRelay(channel ConsumerChannel, publisher Publisher, filter RelayFilter) Relay {
	relay := Relay{
		channel,
		publisher,
		filter,
	}
	relay.consumerChannel.AddConsumer(&RelayConsumer{&relay})
	return relay
}
<commit_msg>Add logging to simplerelay<commit_after>package channels

import (
	"log"
)

// RelayFilter objects provide a predicate function to determine whether a
// message should be passed to the next stage
type RelayFilter interface {
	Filter(Delivery) bool
}

type IncludeAll struct{
	counter int64
}

func (filter *IncludeAll) Filter(delivery Delivery) bool {
	filter.counter++;
	log.Printf("Relayed message : '%v'", filter.counter)
	return true
}

type Relay struct {
	consumerChannel ConsumerChannel
	publisher       Publisher
	filter          RelayFilter
}

func (relay *Relay) Start() bool {
	return relay.consumerChannel.StartConsuming()
}

func (relay *Relay) Stop() bool {
	return relay.consumerChannel.StopConsuming()
}

type RelayConsumer struct {
	relay *Relay
}

func (consumer *RelayConsumer) Consume(delivery Delivery) {
	if consumer.relay.filter.Filter(delivery) {
		consumer.relay.publisher.Publish(delivery.Payload())
	}
	delivery.Ack()
}

func NewRelay(channel ConsumerChannel, publisher Publisher, filter RelayFilter) Relay {
	relay := Relay{
		channel,
		publisher,
		filter,
	}
	relay.consumerChannel.AddConsumer(&RelayConsumer{&relay})
	return relay
}
<|endoftext|>


<commit_before>package gps

import (
	"fmt"
	"os"
	"os/exec"
	"testing"
	"time"
)

func mkTestCmd(iterations int) *monitoredCmd {
	return newMonitoredCmd(
		exec.Command("./echosleep", "-n", fmt.Sprint(iterations)),
		(time.Duration(iterations+1))*100*time.Millisecond,
	)
}

func TestMonitoredCmd(t *testing.T) {
	err := exec.Command("go", "build", "./_testdata/cmd/echosleep.go").Run()
	if err != nil {
		t.Errorf("Unable to build echosleep binary: %s", err)
	}
	defer os.Remove("./echosleep")

	cmd := mkTestCmd(2)
	err = cmd.run()
	if err != nil {
		t.Errorf("Expected command not to fail: %s", err)
	}

	expectedOutput := "foo\nfoo\n"
	if cmd.stdout.buf.String() != expectedOutput {
		t.Errorf("Unexpected output:\n\t(GOT): %s\n\t(WNT): %s", cmd.stdout.buf.String(), expectedOutput)
	}

	cmd2 := mkTestCmd(10)
	err = cmd2.run()
	if err == nil {
		t.Error("Expected command to fail")
	}

	_, ok := err.(*timeoutError)
	if !ok {
		t.Errorf("Expected a timeout error, but got: %s", err)
	}

	expectedOutput = "foo\nfoo\nfoo\nfoo\n"
	if cmd2.stdout.buf.String() != expectedOutput {
		t.Errorf("Unexpected output:\n\t(GOT): %s\n\t(WNT): %s", cmd2.stdout.buf.String(), expectedOutput)
	}
}
<commit_msg>Revert change to TestMonitoredCmd<commit_after>package gps

import (
	"fmt"
	"os"
	"os/exec"
	"testing"
	"time"
)

func mkTestCmd(iterations int) *monitoredCmd {
	return newMonitoredCmd(
		exec.Command("./echosleep", "-n", fmt.Sprint(iterations)),
		200*time.Millisecond,
	)
}

func TestMonitoredCmd(t *testing.T) {
	err := exec.Command("go", "build", "./_testdata/cmd/echosleep.go").Run()
	if err != nil {
		t.Errorf("Unable to build echosleep binary: %s", err)
	}
	defer os.Remove("./echosleep")

	cmd := mkTestCmd(2)
	err = cmd.run()
	if err != nil {
		t.Errorf("Expected command not to fail: %s", err)
	}

	expectedOutput := "foo\nfoo\n"
	if cmd.stdout.buf.String() != expectedOutput {
		t.Errorf("Unexpected output:\n\t(GOT): %s\n\t(WNT): %s", cmd.stdout.buf.String(), expectedOutput)
	}

	cmd2 := mkTestCmd(10)
	err = cmd2.run()
	if err == nil {
		t.Error("Expected command to fail")
	}

	_, ok := err.(*timeoutError)
	if !ok {
		t.Errorf("Expected a timeout error, but got: %s", err)
	}

	expectedOutput = "foo\nfoo\nfoo\nfoo\n"
	if cmd2.stdout.buf.String() != expectedOutput {
		t.Errorf("Unexpected output:\n\t(GOT): %s\n\t(WNT): %s", cmd2.stdout.buf.String(), expectedOutput)
	}
}
<|endoftext|>


<commit_before>package gorm

import (
	"errors"
	"fmt"
	"reflect"
)

type Association struct {
	Scope       *Scope
	PrimaryKey  interface{}
	PrimaryType interface{}
	Column      string
	Error       error
	Field       *Field
}

func (association *Association) err(err error) *Association {
	if err != nil {
		association.Error = err
	}
	return association
}

func (association *Association) Find(value interface{}) *Association {
	association.Scope.related(value, association.Column)
	return association.err(association.Scope.db.Error)
}

func (association *Association) Append(values ...interface{}) *Association {
	scope := association.Scope
	field := association.Field
	fieldType := field.Field.Type()

	for _, value := range values {
		reflectvalue := reflect.ValueOf(value)
		if reflectvalue.Kind() == reflect.Ptr {
			if reflectvalue.Elem().Kind() == reflect.Struct {
				if fieldType.Elem().Kind() == reflect.Ptr {
					field.Set(reflect.Append(field.Field, reflectvalue))
				} else if fieldType.Elem().Kind() == reflect.Struct {
					field.Set(reflect.Append(field.Field, reflectvalue.Elem()))
				}
			} else if reflectvalue.Elem().Kind() == reflect.Slice {
				if fieldType.Elem().Kind() == reflect.Ptr {
					field.Set(reflect.AppendSlice(field.Field, reflectvalue))
				} else if fieldType.Elem().Kind() == reflect.Struct {
					field.Set(reflect.AppendSlice(field.Field, reflectvalue.Elem()))
				}
			}
		} else if reflectvalue.Kind() == reflect.Struct && fieldType.Elem().Kind() == reflect.Struct {
			field.Set(reflect.Append(field.Field, reflectvalue))
		} else if reflectvalue.Kind() == reflect.Slice && fieldType.Elem() == reflectvalue.Type().Elem() {
			field.Set(reflect.AppendSlice(field.Field, reflectvalue))
		} else {
			association.err(errors.New("invalid association type"))
		}
	}
	scope.callCallbacks(scope.db.parent.callback.updates)
	return association.err(scope.db.Error)
}

func (association *Association) getPrimaryKeys(values ...interface{}) []interface{} {
	primaryKeys := []interface{}{}
	scope := association.Scope

	for _, value := range values {
		reflectValue := reflect.ValueOf(value)
		if reflectValue.Kind() == reflect.Ptr {
			reflectValue = reflectValue.Elem()
		}
		if reflectValue.Kind() == reflect.Slice {
			for i := 0; i < reflectValue.Len(); i++ {
				newScope := scope.New(reflectValue.Index(i).Interface())
				primaryKey := newScope.PrimaryKeyValue()
				if !reflect.DeepEqual(reflect.ValueOf(primaryKey), reflect.Zero(reflect.ValueOf(primaryKey).Type())) {
					primaryKeys = append(primaryKeys, primaryKey)
				}
			}
		} else if reflectValue.Kind() == reflect.Struct {
			newScope := scope.New(value)
			primaryKey := newScope.PrimaryKeyValue()
			if !reflect.DeepEqual(reflect.ValueOf(primaryKey), reflect.Zero(reflect.ValueOf(primaryKey).Type())) {
				primaryKeys = append(primaryKeys, primaryKey)
			}
		}
	}
	return primaryKeys
}

func (association *Association) Delete(values ...interface{}) *Association {
	primaryKeys := association.getPrimaryKeys(values...)

	if len(primaryKeys) == 0 {
		association.err(errors.New("no primary key found"))
	} else {
		relationship := association.Field.Relationship
		// many to many
		if relationship.Kind == "many_to_many" {
			whereSql := fmt.Sprintf("%v.%v = ? AND %v.%v IN (?)",
				relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.ForeignKey)),
				relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.AssociationForeignKey)))

			association.Scope.db.Model("").Table(relationship.JoinTable).
				Where(whereSql, association.PrimaryKey, primaryKeys).Delete("")
		} else {
			association.err(errors.New("delete only support many to many"))
		}
	}
	return association
}

func (association *Association) Replace(values ...interface{}) *Association {
	relationship := association.Field.Relationship
	scope := association.Scope
	if relationship.Kind == "many_to_many" {
		field := association.Field.Field

		oldPrimaryKeys := association.getPrimaryKeys(field.Interface())
		association.Append(values...)
		newPrimaryKeys := association.getPrimaryKeys(field.Interface())

		var addedPrimaryKeys = []interface{}{}
		for _, new := range newPrimaryKeys {
			hasEqual := false
			for _, old := range oldPrimaryKeys {
				if reflect.DeepEqual(new, old) {
					hasEqual = true
					break
				}
			}
			if !hasEqual {
				addedPrimaryKeys = append(addedPrimaryKeys, new)
			}
		}
		for _, primaryKey := range association.getPrimaryKeys(values...) {
			addedPrimaryKeys = append(addedPrimaryKeys, primaryKey)
		}

		whereSql := fmt.Sprintf("%v.%v NOT IN (?)", relationship.JoinTable, scope.Quote(ToSnake(relationship.AssociationForeignKey)))
		scope.db.Model("").Table(relationship.JoinTable).Where(whereSql, addedPrimaryKeys).Delete("")
	} else {
		association.err(errors.New("replace only support many to many"))
	}
	return association
}

func (association *Association) Clear() *Association {
	relationship := association.Field.Relationship
	scope := association.Scope
	if relationship.Kind == "many_to_many" {
		whereSql := fmt.Sprintf("%v.%v = ?", relationship.JoinTable, scope.Quote(ToSnake(relationship.ForeignKey)))
		scope.db.Model("").Table(relationship.JoinTable).Where(whereSql, association.PrimaryKey).Delete("")
	} else {
		association.err(errors.New("clear only support many to many"))
	}
	return association
}

func (association *Association) Count() int {
	count := -1
	relationship := association.Field.Relationship
	scope := association.Scope
	field := association.Field.Field
	fieldValue := field.Interface()
	newScope := scope.New(fieldValue)

	if relationship.Kind == "many_to_many" {
		whereSql := fmt.Sprintf("%v.%v IN (SELECT %v.%v FROM %v WHERE %v.%v = ?)",
			newScope.QuotedTableName(),
			scope.Quote(newScope.PrimaryKey()),
			relationship.JoinTable,
			scope.Quote(ToSnake(relationship.AssociationForeignKey)),
			relationship.JoinTable,
			relationship.JoinTable,
			scope.Quote(ToSnake(relationship.ForeignKey)))
		scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey).Count(&count)
	} else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
		whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToSnake(relationship.ForeignKey)))
		countScope := scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey)
		if relationship.ForeignType != "" {
			countScope = countScope.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToSnake(relationship.ForeignType))), association.PrimaryType)
		}
		countScope.Count(&count)
	} else if relationship.Kind == "belongs_to" {
		if v, err := scope.FieldValueByName(association.Column); err == nil {
			whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToSnake(relationship.ForeignKey)))
			scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, v).Count(&count)
		}
	}

	return count
}
<commit_msg>Fix association Replace delete wrong records<commit_after>package gorm

import (
	"errors"
	"fmt"
	"reflect"
)

type Association struct {
	Scope       *Scope
	PrimaryKey  interface{}
	PrimaryType interface{}
	Column      string
	Error       error
	Field       *Field
}

func (association *Association) err(err error) *Association {
	if err != nil {
		association.Error = err
	}
	return association
}

func (association *Association) Find(value interface{}) *Association {
	association.Scope.related(value, association.Column)
	return association.err(association.Scope.db.Error)
}

func (association *Association) Append(values ...interface{}) *Association {
	scope := association.Scope
	field := association.Field
	fieldType := field.Field.Type()

	for _, value := range values {
		reflectvalue := reflect.ValueOf(value)
		if reflectvalue.Kind() == reflect.Ptr {
			if reflectvalue.Elem().Kind() == reflect.Struct {
				if fieldType.Elem().Kind() == reflect.Ptr {
					field.Set(reflect.Append(field.Field, reflectvalue))
				} else if fieldType.Elem().Kind() == reflect.Struct {
					field.Set(reflect.Append(field.Field, reflectvalue.Elem()))
				}
			} else if reflectvalue.Elem().Kind() == reflect.Slice {
				if fieldType.Elem().Kind() == reflect.Ptr {
					field.Set(reflect.AppendSlice(field.Field, reflectvalue))
				} else if fieldType.Elem().Kind() == reflect.Struct {
					field.Set(reflect.AppendSlice(field.Field, reflectvalue.Elem()))
				}
			}
		} else if reflectvalue.Kind() == reflect.Struct && fieldType.Elem().Kind() == reflect.Struct {
			field.Set(reflect.Append(field.Field, reflectvalue))
		} else if reflectvalue.Kind() == reflect.Slice && fieldType.Elem() == reflectvalue.Type().Elem() {
			field.Set(reflect.AppendSlice(field.Field, reflectvalue))
		} else {
			association.err(errors.New("invalid association type"))
		}
	}
	scope.callCallbacks(scope.db.parent.callback.updates)
	return association.err(scope.db.Error)
}

func (association *Association) getPrimaryKeys(values ...interface{}) []interface{} {
	primaryKeys := []interface{}{}
	scope := association.Scope

	for _, value := range values {
		reflectValue := reflect.ValueOf(value)
		if reflectValue.Kind() == reflect.Ptr {
			reflectValue = reflectValue.Elem()
		}
		if reflectValue.Kind() == reflect.Slice {
			for i := 0; i < reflectValue.Len(); i++ {
				newScope := scope.New(reflectValue.Index(i).Interface())
				primaryKey := newScope.PrimaryKeyValue()
				if !reflect.DeepEqual(reflect.ValueOf(primaryKey), reflect.Zero(reflect.ValueOf(primaryKey).Type())) {
					primaryKeys = append(primaryKeys, primaryKey)
				}
			}
		} else if reflectValue.Kind() == reflect.Struct {
			newScope := scope.New(value)
			primaryKey := newScope.PrimaryKeyValue()
			if !reflect.DeepEqual(reflect.ValueOf(primaryKey), reflect.Zero(reflect.ValueOf(primaryKey).Type())) {
				primaryKeys = append(primaryKeys, primaryKey)
			}
		}
	}
	return primaryKeys
}

func (association *Association) Delete(values ...interface{}) *Association {
	primaryKeys := association.getPrimaryKeys(values...)

	if len(primaryKeys) == 0 {
		association.err(errors.New("no primary key found"))
	} else {
		relationship := association.Field.Relationship
		// many to many
		if relationship.Kind == "many_to_many" {
			whereSql := fmt.Sprintf("%v.%v = ? AND %v.%v IN (?)",
				relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.ForeignKey)),
				relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.AssociationForeignKey)))

			association.Scope.db.Model("").Table(relationship.JoinTable).
				Where(whereSql, association.PrimaryKey, primaryKeys).Delete("")
		} else {
			association.err(errors.New("delete only support many to many"))
		}
	}
	return association
}

func (association *Association) Replace(values ...interface{}) *Association {
	relationship := association.Field.Relationship
	scope := association.Scope
	if relationship.Kind == "many_to_many" {
		field := association.Field.Field

		oldPrimaryKeys := association.getPrimaryKeys(field.Interface())
		association.Append(values...)
		newPrimaryKeys := association.getPrimaryKeys(field.Interface())

		var addedPrimaryKeys = []interface{}{}
		for _, new := range newPrimaryKeys {
			hasEqual := false
			for _, old := range oldPrimaryKeys {
				if reflect.DeepEqual(new, old) {
					hasEqual = true
					break
				}
			}
			if !hasEqual {
				addedPrimaryKeys = append(addedPrimaryKeys, new)
			}
		}
		for _, primaryKey := range association.getPrimaryKeys(values...) {
			addedPrimaryKeys = append(addedPrimaryKeys, primaryKey)
		}

		whereSql := fmt.Sprintf("%v.%v = ? AND %v.%v NOT IN (?)",
			relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.ForeignKey)),
			relationship.JoinTable, association.Scope.Quote(ToSnake(relationship.AssociationForeignKey)))

		scope.db.Model("").Table(relationship.JoinTable).Where(whereSql, association.PrimaryKey, addedPrimaryKeys).Delete("")
	} else {
		association.err(errors.New("replace only support many to many"))
	}
	return association
}

func (association *Association) Clear() *Association {
	relationship := association.Field.Relationship
	scope := association.Scope
	if relationship.Kind == "many_to_many" {
		whereSql := fmt.Sprintf("%v.%v = ?", relationship.JoinTable, scope.Quote(ToSnake(relationship.ForeignKey)))
		scope.db.Model("").Table(relationship.JoinTable).Where(whereSql, association.PrimaryKey).Delete("")
	} else {
		association.err(errors.New("clear only support many to many"))
	}
	return association
}

func (association *Association) Count() int {
	count := -1
	relationship := association.Field.Relationship
	scope := association.Scope
	field := association.Field.Field
	fieldValue := field.Interface()
	newScope := scope.New(fieldValue)

	if relationship.Kind == "many_to_many" {
		whereSql := fmt.Sprintf("%v.%v IN (SELECT %v.%v FROM %v WHERE %v.%v = ?)",
			newScope.QuotedTableName(),
			scope.Quote(newScope.PrimaryKey()),
			relationship.JoinTable,
			scope.Quote(ToSnake(relationship.AssociationForeignKey)),
			relationship.JoinTable,
			relationship.JoinTable,
			scope.Quote(ToSnake(relationship.ForeignKey)))
		scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey).Count(&count)
	} else if relationship.Kind == "has_many" || relationship.Kind == "has_one" {
		whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToSnake(relationship.ForeignKey)))
		countScope := scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, association.PrimaryKey)
		if relationship.ForeignType != "" {
			countScope = countScope.Where(fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToSnake(relationship.ForeignType))), association.PrimaryType)
		}
		countScope.Count(&count)
	} else if relationship.Kind == "belongs_to" {
		if v, err := scope.FieldValueByName(association.Column); err == nil {
			whereSql := fmt.Sprintf("%v.%v = ?", newScope.QuotedTableName(), newScope.Quote(ToSnake(relationship.ForeignKey)))
			scope.db.Model("").Table(newScope.QuotedTableName()).Where(whereSql, v).Count(&count)
		}
	}

	return count
}
<|endoftext|>


<commit_before>package audio

import (
	"errors"
	"fmt"

	"github.com/200sc/klangsynthese/audio"
	"github.com/200sc/klangsynthese/font"
)

// Audio is a struct of some audio data and the variables
// required to filter it through a sound font.
type Audio struct {
	*font.Audio
	toStop    audio.Audio
	X, Y      *float64
	setVolume int32
}

// New returns an audio from a font, some audio data, and optional
// positional coordinates
func New(f *font.Font, d Data, coords ...*float64) *Audio {
	a := new(Audio)
	a.Audio = font.NewAudio(f, d)
	if len(coords) > 0 {
		a.X = coords[0]
		if len(coords) > 1 {
			a.Y = coords[1]
		}
	}
	return a
}

// SetVolume attempts to set the volume of the underlying OS audio.
func (a *Audio) SetVolume(v int32) error {
	a.setVolume = v
	if a.toStop != nil {
		return a.toStop.SetVolume(v)
	}
	return nil
}

// Play begin's an audio's playback
func (a *Audio) Play() <-chan error {
	a2, err := a.Copy()
	if err != nil {
		return errChannel(err)
	}
	a3, err := a2.Filter(a.Font.Filters...)
	if err != nil {
		return errChannel(err)
	}
	a4, err := a3.(*Audio).FullAudio.Copy()
	if err != nil {
		return errChannel(err)
	}
	a.toStop = a4
	a.toStop.SetVolume(a.setVolume)
	return a4.Play()
}

func errChannel(err error) <-chan error {
	ch := make(chan error)
	go func() {
		ch <- err
	}()
	return ch
}

// Stop stops an audio's playback
func (a *Audio) Stop() error {
	if a == nil || a.toStop == nil {
		return errors.New("nil audio stopped")
	}
	return a.toStop.Stop()
}

// Copy returns a copy of the audio
func (a *Audio) Copy() (audio.Audio, error) {
	a2, err := a.Audio.Copy()
	if err != nil {
		return nil, err
	}
	return New(a.Audio.Font, a2.(audio.FullAudio), a.X, a.Y), nil
}

// MustCopy acts like Copy, but panics on an error.
func (a *Audio) MustCopy() audio.Audio {
	return New(a.Audio.Font, a.Audio.MustCopy().(audio.FullAudio), a.X, a.Y)
}

// Filter returns the audio with some set of filters applied to it.
func (a *Audio) Filter(fs ...audio.Filter) (audio.Audio, error) {
	var ad audio.Audio = a
	var err, consErr error
	for _, f := range fs {
		ad, err = f.Apply(ad)
		if err != nil {
			if consErr == nil {
				consErr = err
			} else {
				consErr = fmt.Errorf("%w, %v", err, consErr)
			}
		}
	}
	return ad, consErr
}

// MustFilter acts like Filter but ignores errors.
func (a *Audio) MustFilter(fs ...audio.Filter) audio.Audio {
	ad, _ := a.Filter(fs...)
	return ad
}

// Xp returns a pointer to the x position of this audio, if it has one.
// It has no position, this returns nil.
func (a *Audio) Xp() *float64 {
	return a.X
}

// Yp returns a pointer to the y position of this audio, if it has one.
// It has no position, this returns nil. If This is not nil, Xp will not be nil.
func (a *Audio) Yp() *float64 {
	return a.Y
}

var (
	// Guarantee that Audio can have positional filters applied to it
	_ SupportsPos = &Audio{}
)
<commit_msg>audio: use oakerr errors instead of errors.New<commit_after>package audio

import (
	"fmt"

	"github.com/200sc/klangsynthese/audio"
	"github.com/200sc/klangsynthese/font"
	"github.com/oakmound/oak/v2/oakerr"
)

// Audio is a struct of some audio data and the variables
// required to filter it through a sound font.
type Audio struct {
	*font.Audio
	toStop    audio.Audio
	X, Y      *float64
	setVolume int32
}

// New returns an audio from a font, some audio data, and optional
// positional coordinates
func New(f *font.Font, d Data, coords ...*float64) *Audio {
	a := new(Audio)
	a.Audio = font.NewAudio(f, d)
	if len(coords) > 0 {
		a.X = coords[0]
		if len(coords) > 1 {
			a.Y = coords[1]
		}
	}
	return a
}

// SetVolume attempts to set the volume of the underlying OS audio.
func (a *Audio) SetVolume(v int32) error {
	a.setVolume = v
	if a.toStop != nil {
		return a.toStop.SetVolume(v)
	}
	return nil
}

// Play begin's an audio's playback
func (a *Audio) Play() <-chan error {
	a2, err := a.Copy()
	if err != nil {
		return errChannel(err)
	}
	a3, err := a2.Filter(a.Font.Filters...)
	if err != nil {
		return errChannel(err)
	}
	a4, err := a3.(*Audio).FullAudio.Copy()
	if err != nil {
		return errChannel(err)
	}
	a.toStop = a4
	a.toStop.SetVolume(a.setVolume)
	return a4.Play()
}

func errChannel(err error) <-chan error {
	ch := make(chan error)
	go func() {
		ch <- err
	}()
	return ch
}

// Stop stops an audio's playback
func (a *Audio) Stop() error {
	if a == nil || a.toStop == nil {
		return oakerr.NilInput{InputName: "Audio"}
	}
	return a.toStop.Stop()
}

// Copy returns a copy of the audio
func (a *Audio) Copy() (audio.Audio, error) {
	a2, err := a.Audio.Copy()
	if err != nil {
		return nil, err
	}
	return New(a.Audio.Font, a2.(audio.FullAudio), a.X, a.Y), nil
}

// MustCopy acts like Copy, but panics on an error.
func (a *Audio) MustCopy() audio.Audio {
	return New(a.Audio.Font, a.Audio.MustCopy().(audio.FullAudio), a.X, a.Y)
}

// Filter returns the audio with some set of filters applied to it.
func (a *Audio) Filter(fs ...audio.Filter) (audio.Audio, error) {
	var ad audio.Audio = a
	var err, consErr error
	for _, f := range fs {
		ad, err = f.Apply(ad)
		if err != nil {
			if consErr == nil {
				consErr = err
			} else {
				consErr = fmt.Errorf("%w, %v", err, consErr)
			}
		}
	}
	return ad, consErr
}

// MustFilter acts like Filter but ignores errors.
func (a *Audio) MustFilter(fs ...audio.Filter) audio.Audio {
	ad, _ := a.Filter(fs...)
	return ad
}

// Xp returns a pointer to the x position of this audio, if it has one.
// It has no position, this returns nil.
func (a *Audio) Xp() *float64 {
	return a.X
}

// Yp returns a pointer to the y position of this audio, if it has one.
// It has no position, this returns nil. If This is not nil, Xp will not be nil.
func (a *Audio) Yp() *float64 {
	return a.Y
}

var (
	// Guarantee that Audio can have positional filters applied to it
	_ SupportsPos = &Audio{}
)
<|endoftext|>


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

package commands

import (
	"go/build"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"syscall"
	"time"

	"nvim-go/context"
	"nvim-go/nvim"

	"github.com/garyburd/neovim-go/vim"
	"github.com/garyburd/neovim-go/vim/plugin"
)

func init() {
	plugin.HandleCommand("Gobuild", &plugin.CommandOptions{Eval: "getcwd()"}, cmdBuild)
}

func cmdBuild(v *vim.Vim, cwd string) {
	go Build(v, cwd)
}

// Build building the current buffer's package use compile tool that determined from the directory structure.
func Build(v *vim.Vim, cwd string) error {
	defer context.WithGoBuildForPath(cwd)()
	defer nvim.Profile(time.Now(), "GoBuild")

	var (
		b vim.Buffer
		w vim.Window
	)

	p := v.NewPipeline()
	p.CurrentBuffer(&b)
	p.CurrentWindow(&w)
	if err := p.Wait(); err != nil {
		return nvim.Echoerr(v, "GoBuild: %v", err)
	}

	baseDir := context.FindVcsRoot(cwd)

	var compiler string

	buildDir := strings.Split(build.Default.GOPATH, ":")[0]
	if buildDir == os.Getenv("GOPATH") {
		compiler = "go"
	} else {
		compiler = "gb"
		baseDir = filepath.Join(baseDir, "src")
	}

	cmd := exec.Command(compiler, "build")
	out, _ := cmd.CombinedOutput()

	cmd.Run()

	s, _ := cmd.ProcessState.Sys().(syscall.WaitStatus)
	if s.ExitStatus() > 0 {
		loclist := nvim.ParseError(v, string(out), cwd, baseDir)
		if err := nvim.SetLoclist(p, loclist); err != nil {
			return nvim.Echoerr(v, "GoBuild: %v", err)
		}
		return nvim.OpenLoclist(p, w, loclist, true)
	}

	return nvim.Echohl(v, "GoBuild: ", "Function", "SUCCESS")
}
<commit_msg>Fix switch compiler terms<commit_after>// Copyright 2016 Koichi Shiraishi. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package commands

import (
	"go/build"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"syscall"
	"time"

	"nvim-go/context"
	"nvim-go/nvim"

	"github.com/garyburd/neovim-go/vim"
	"github.com/garyburd/neovim-go/vim/plugin"
)

func init() {
	plugin.HandleCommand("Gobuild", &plugin.CommandOptions{Eval: "getcwd()"}, cmdBuild)
}

func cmdBuild(v *vim.Vim, cwd string) {
	go Build(v, cwd)
}

// Build building the current buffer's package use compile tool that determined from the directory structure.
func Build(v *vim.Vim, cwd string) error {
	defer context.WithGoBuildForPath(cwd)()
	defer nvim.Profile(time.Now(), "GoBuild")

	var (
		b vim.Buffer
		w vim.Window
	)

	p := v.NewPipeline()
	p.CurrentBuffer(&b)
	p.CurrentWindow(&w)
	if err := p.Wait(); err != nil {
		return nvim.Echoerr(v, "GoBuild: %v", err)
	}

	baseDir := context.FindVcsRoot(cwd)

	var compiler string

	buildDir := strings.Split(build.Default.GOPATH, string(filepath.ListSeparator))[0]
	gopath := strings.Split(os.Getenv("GOPATH"), string(filepath.ListSeparator))[0]
	if buildDir == gopath {
		compiler = "go"
	} else {
		compiler = "gb"
		baseDir = filepath.Join(baseDir, "src")
	}

	cmd := exec.Command(compiler, "build")
	out, _ := cmd.CombinedOutput()

	cmd.Run()

	s, _ := cmd.ProcessState.Sys().(syscall.WaitStatus)
	if s.ExitStatus() > 0 {
		loclist := nvim.ParseError(v, string(out), cwd, baseDir)
		if err := nvim.SetLoclist(p, loclist); err != nil {
			return nvim.Echoerr(v, "GoBuild: %v", err)
		}
		return nvim.OpenLoclist(p, w, loclist, true)
	}

	return nvim.Echohl(v, "GoBuild: ", "Function", "SUCCESS")
}
<|endoftext|>


<commit_before>package checks

import (
	"fmt"
	"time"

	"github.com/mackerelio/mackerel-agent/config"
	"github.com/mackerelio/mackerel-agent/logging"
	"github.com/mackerelio/mackerel-agent/util"
)

var logger = logging.GetLogger("checks")

// Status is a status that is produced by periodical checking.
// It is currently compatible with Nagios.
type Status string

// Current possible statuses, which is taken from command's exit code.
// the mapping is given as exitCodeToStatus.
const (
	StatusUndefined Status = ""
	StatusOK        Status = "OK"
	StatusWarning   Status = "WARNING"
	StatusCritical  Status = "CRITICAL"
	StatusUnknown   Status = "UNKNOWN"
)

var exitCodeToStatus = map[int]Status{
	0: StatusOK,
	1: StatusWarning,
	2: StatusCritical,
	3: StatusUnknown,
}

// Checker is the main interface of check monitoring.
// It invokes its given command and transforms the result to a Report
// to be sent to Mackerel periodically.
type Checker struct {
	Name string
	// NOTE(motemen): We make use of config.PluginConfig as it happens
	// to have Command field which was used by metrics.pluginGenerator.
	// If the configuration of checks.Checker and metrics.pluginGenerator goes different ones,
	// we should reconcider using config.PluginConfig.
	Config config.PluginConfig
}

// Report is what Checker produces by invoking its command.
type Report struct {
	Name                 string
	Status               Status
	Message              string
	OccurredAt           time.Time
	NotificationInterval *int32
	MaxCheckAttempts     *int32
}

func (c Checker) String() string {
	return fmt.Sprintf("checker %q command=[%s]", c.Name, c.Config.Command)
}

// Check invokes the command and transforms its result to a Report.
func (c Checker) Check() (*Report, error) {
	now := time.Now()

	command := c.Config.Command
	logger.Debugf("Checker %q executing command %q", c.Name, command)
	message, stderr, exitCode, err := util.RunCommand(command)
	if stderr != "" {
		logger.Warningf("Checker %q output stderr: %s", c.Name, stderr)
	}

	status := StatusUnknown

	if err != nil {
		message = err.Error()
	} else {
		if s, ok := exitCodeToStatus[exitCode]; ok {
			status = s
		}

		logger.Debugf("Checker %q status=%s message=%q", c.Name, status, message)
	}

	return &Report{
		Name:                 c.Name,
		Status:               status,
		Message:              message,
		OccurredAt:           now,
		NotificationInterval: c.Config.NotificationInterval,
		MaxCheckAttempts:     c.Config.MaxCheckAttempts,
	}, nil
}

// Interval is the interval where the command is invoked.
// (Will be configurable in the future)
func (c Checker) Interval() time.Duration {
	return 1 * time.Minute
}
<commit_msg>fix comment in checker.go<commit_after>package checks

import (
	"fmt"
	"time"

	"github.com/mackerelio/mackerel-agent/config"
	"github.com/mackerelio/mackerel-agent/logging"
	"github.com/mackerelio/mackerel-agent/util"
)

var logger = logging.GetLogger("checks")

// Status is a status that is produced by periodical checking.
// It is currently compatible with Nagios.
type Status string

// Current possible statuses, which is taken from command's exit code.
// the mapping is given as exitCodeToStatus.
const (
	StatusUndefined Status = ""
	StatusOK        Status = "OK"
	StatusWarning   Status = "WARNING"
	StatusCritical  Status = "CRITICAL"
	StatusUnknown   Status = "UNKNOWN"
)

var exitCodeToStatus = map[int]Status{
	0: StatusOK,
	1: StatusWarning,
	2: StatusCritical,
	3: StatusUnknown,
}

// Checker is the main interface of check monitoring.
// It invokes its given command and transforms the result to a Report
// to be sent to Mackerel periodically.
type Checker struct {
	Name string
	// NOTE(motemen): We make use of config.PluginConfig as it happens
	// to have the Command field which was used by metrics.pluginGenerator.
	// If the configuration of checks.Checker and/or metrics.pluginGenerator changes,
	// we should reconsider using config.PluginConfig.
	Config config.PluginConfig
}

// Report is what Checker produces by invoking its command.
type Report struct {
	Name                 string
	Status               Status
	Message              string
	OccurredAt           time.Time
	NotificationInterval *int32
	MaxCheckAttempts     *int32
}

func (c Checker) String() string {
	return fmt.Sprintf("checker %q command=[%s]", c.Name, c.Config.Command)
}

// Check invokes the command and transforms its result to a Report.
func (c Checker) Check() (*Report, error) {
	now := time.Now()

	command := c.Config.Command
	logger.Debugf("Checker %q executing command %q", c.Name, command)
	message, stderr, exitCode, err := util.RunCommand(command)
	if stderr != "" {
		logger.Warningf("Checker %q output stderr: %s", c.Name, stderr)
	}

	status := StatusUnknown

	if err != nil {
		message = err.Error()
	} else {
		if s, ok := exitCodeToStatus[exitCode]; ok {
			status = s
		}

		logger.Debugf("Checker %q status=%s message=%q", c.Name, status, message)
	}

	return &Report{
		Name:                 c.Name,
		Status:               status,
		Message:              message,
		OccurredAt:           now,
		NotificationInterval: c.Config.NotificationInterval,
		MaxCheckAttempts:     c.Config.MaxCheckAttempts,
	}, nil
}

// Interval is the interval where the command is invoked.
// (Will be configurable in the future)
func (c Checker) Interval() time.Duration {
	return 1 * time.Minute
}
<|endoftext|>