<commit_before>// Copyright (c) 2016, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information

package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"runtime/pprof"
	"strings"

	"github.com/mvdan/sh/syntax"
)

var (
	write      = flag.Bool("w", false, "write result to file instead of stdout")
	list       = flag.Bool("l", false, "list files whose formatting differs from shfmt's")
	indent     = flag.Int("i", 0, "indent: 0 for tabs (default), >0 for number of spaces")
	posix      = flag.Bool("p", false, "parse POSIX shell code instead of bash")
	cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

	parseMode         syntax.ParseMode
	printConfig       syntax.PrintConfig
	readBuf, writeBuf bytes.Buffer

	out io.Writer
)

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	out = os.Stdout
	printConfig.Spaces = *indent
	parseMode |= syntax.ParseComments
	if *posix {
		parseMode |= syntax.PosixConformant
	}
	if flag.NArg() == 0 {
		if err := formatStdin(); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		return
	}
	anyErr := false
	onError := func(err error) {
		anyErr = true
		fmt.Fprintln(os.Stderr, err)
	}
	for _, path := range flag.Args() {
		walk(path, onError)
	}
	if anyErr {
		os.Exit(1)
	}
}

func formatStdin() error {
	if *write || *list {
		return fmt.Errorf("-w and -l can only be used on files")
	}
	readBuf.Reset()
	if _, err := io.Copy(&readBuf, os.Stdin); err != nil {
		return err
	}
	src := readBuf.Bytes()
	prog, err := syntax.Parse(src, "", parseMode)
	if err != nil {
		return err
	}
	return printConfig.Fprint(out, prog)
}

var (
	shellFile    = regexp.MustCompile(`^.*\.(sh|bash)$`)
	validShebang = regexp.MustCompile(`^#!\s?/(usr/)?bin/(env *)?(sh|bash)`)
	vcsDir       = regexp.MustCompile(`^(\.git|\.svn|\.hg)$`)
)

type shellConfidence int

const (
	notShellFile shellConfidence = iota
	ifValidShebang
	isShellFile
)

func getConfidence(info os.FileInfo) shellConfidence {
	name := info.Name()
	switch {
	case info.IsDir(), name[0] == '.', !info.Mode().IsRegular():
		return notShellFile
	case shellFile.MatchString(name):
		return isShellFile
	case strings.Contains(name, "."):
		return notShellFile // different extension
	case info.Size() < 8:
		return notShellFile // cannot possibly hold valid shebang
	default:
		return ifValidShebang
	}
}

func walk(path string, onError func(error)) {
	info, err := os.Stat(path)
	if err != nil {
		onError(err)
		return
	}
	if !info.IsDir() {
		if err := formatPath(path, false); err != nil {
			onError(err)
		}
		return
	}
	filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() && vcsDir.MatchString(info.Name()) {
			return filepath.SkipDir
		}
		if err != nil {
			onError(err)
			return nil
		}
		conf := getConfidence(info)
		if conf == notShellFile {
			return nil
		}
		err = formatPath(path, conf == ifValidShebang)
		if err != nil && !os.IsNotExist(err) {
			onError(err)
		}
		return nil
	})
}

func empty(f *os.File) error {
	if err := f.Truncate(0); err != nil {
		return err
	}
	_, err := f.Seek(0, 0)
	return err
}

func formatPath(path string, checkShebang bool) error {
	openMode := os.O_RDONLY
	if *write {
		openMode = os.O_RDWR
	}
	f, err := os.OpenFile(path, openMode, 0)
	if err != nil {
		return err
	}
	defer f.Close()
	readBuf.Reset()
	if _, err := io.Copy(&readBuf, f); err != nil {
		return err
	}
	src := readBuf.Bytes()
	if checkShebang && !validShebang.Match(src[:32]) {
		return nil
	}
	prog, err := syntax.Parse(src, path, parseMode)
	if err != nil {
		return err
	}
	writeBuf.Reset()
	printConfig.Fprint(&writeBuf, prog)
	res := writeBuf.Bytes()
	if !bytes.Equal(src, res) {
		if *list {
			fmt.Fprintln(out, path)
		}
		if *write {
			if err := empty(f); err != nil {
				return err
			}
			if _, err := f.Write(res); err != nil {
				return err
			}
		}
	}
	if !*list && !*write {
		if _, err := out.Write(res); err != nil {
			return err
		}
	}
	return nil
}
<commit_msg>cmd/shfmt: simplify regexes<commit_after>// Copyright (c) 2016, Daniel Martí <mvdan@mvdan.cc>
// See LICENSE for licensing information

package main

import (
	"bytes"
	"flag"
	"fmt"
	"io"
	"log"
	"os"
	"path/filepath"
	"regexp"
	"runtime/pprof"
	"strings"

	"github.com/mvdan/sh/syntax"
)

var (
	write      = flag.Bool("w", false, "write result to file instead of stdout")
	list       = flag.Bool("l", false, "list files whose formatting differs from shfmt's")
	indent     = flag.Int("i", 0, "indent: 0 for tabs (default), >0 for number of spaces")
	posix      = flag.Bool("p", false, "parse POSIX shell code instead of bash")
	cpuprofile = flag.String("cpuprofile", "", "write cpu profile to file")

	parseMode         syntax.ParseMode
	printConfig       syntax.PrintConfig
	readBuf, writeBuf bytes.Buffer

	out io.Writer
)

func main() {
	flag.Parse()
	if *cpuprofile != "" {
		f, err := os.Create(*cpuprofile)
		if err != nil {
			log.Fatal(err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()
	}

	out = os.Stdout
	printConfig.Spaces = *indent
	parseMode |= syntax.ParseComments
	if *posix {
		parseMode |= syntax.PosixConformant
	}
	if flag.NArg() == 0 {
		if err := formatStdin(); err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		return
	}
	anyErr := false
	onError := func(err error) {
		anyErr = true
		fmt.Fprintln(os.Stderr, err)
	}
	for _, path := range flag.Args() {
		walk(path, onError)
	}
	if anyErr {
		os.Exit(1)
	}
}

func formatStdin() error {
	if *write || *list {
		return fmt.Errorf("-w and -l can only be used on files")
	}
	readBuf.Reset()
	if _, err := io.Copy(&readBuf, os.Stdin); err != nil {
		return err
	}
	src := readBuf.Bytes()
	prog, err := syntax.Parse(src, "", parseMode)
	if err != nil {
		return err
	}
	return printConfig.Fprint(out, prog)
}

var (
	shellFile    = regexp.MustCompile(`\.(sh|bash)$`)
	validShebang = regexp.MustCompile(`^#!\s?/(usr/)?bin/(env *)?(sh|bash)`)
	vcsDir       = regexp.MustCompile(`^\.(git|svn|hg)$`)
)

type shellConfidence int

const (
	notShellFile shellConfidence = iota
	ifValidShebang
	isShellFile
)

func getConfidence(info os.FileInfo) shellConfidence {
	name := info.Name()
	switch {
	case info.IsDir(), name[0] == '.', !info.Mode().IsRegular():
		return notShellFile
	case shellFile.MatchString(name):
		return isShellFile
	case strings.Contains(name, "."):
		return notShellFile // different extension
	case info.Size() < 8:
		return notShellFile // cannot possibly hold valid shebang
	default:
		return ifValidShebang
	}
}

func walk(path string, onError func(error)) {
	info, err := os.Stat(path)
	if err != nil {
		onError(err)
		return
	}
	if !info.IsDir() {
		if err := formatPath(path, false); err != nil {
			onError(err)
		}
		return
	}
	filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
		if info.IsDir() && vcsDir.MatchString(info.Name()) {
			return filepath.SkipDir
		}
		if err != nil {
			onError(err)
			return nil
		}
		conf := getConfidence(info)
		if conf == notShellFile {
			return nil
		}
		err = formatPath(path, conf == ifValidShebang)
		if err != nil && !os.IsNotExist(err) {
			onError(err)
		}
		return nil
	})
}

func empty(f *os.File) error {
	if err := f.Truncate(0); err != nil {
		return err
	}
	_, err := f.Seek(0, 0)
	return err
}

func formatPath(path string, checkShebang bool) error {
	openMode := os.O_RDONLY
	if *write {
		openMode = os.O_RDWR
	}
	f, err := os.OpenFile(path, openMode, 0)
	if err != nil {
		return err
	}
	defer f.Close()
	readBuf.Reset()
	if _, err := io.Copy(&readBuf, f); err != nil {
		return err
	}
	src := readBuf.Bytes()
	if checkShebang && !validShebang.Match(src[:32]) {
		return nil
	}
	prog, err := syntax.Parse(src, path, parseMode)
	if err != nil {
		return err
	}
	writeBuf.Reset()
	printConfig.Fprint(&writeBuf, prog)
	res := writeBuf.Bytes()
	if !bytes.Equal(src, res) {
		if *list {
			fmt.Fprintln(out, path)
		}
		if *write {
			if err := empty(f); err != nil {
				return err
			}
			if _, err := f.Write(res); err != nil {
				return err
			}
		}
	}
	if !*list && !*write {
		if _, err := out.Write(res); err != nil {
			return err
		}
	}
	return nil
}
<|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 tsuru

import (
	"encoding/json"
	"fmt"
	"github.com/globocom/tsuru/cmd"
	"io"
	"io/ioutil"
	"launchpad.net/gnuflag"
	"net/http"
)

var AppName = gnuflag.String("app", "", "App name for running app related commands.")
var AssumeYes = gnuflag.Bool("assume-yes", false, "Don't ask for confirmation on operations.")
var LogLines = gnuflag.Int("lines", 10, "The number of log lines to display")
var LogSource = gnuflag.String("source", "", "The log from the given source")

type AppInfo struct {
	GuessingCommand
}

func (c *AppInfo) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "app-info",
		Usage: "app-info [--app appname]",
		Desc: `show information about your app.

If you don't provide the app name, tsuru will try to guess it.`,
		MinArgs: 0,
	}
}

func (c *AppInfo) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s", appName))
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	if response.StatusCode == http.StatusNoContent {
		return nil
	}
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	return c.Show(result, context)
}

func (c *AppInfo) Show(result []byte, context *cmd.Context) error {
	var app map[string]interface{}
	err := json.Unmarshal(result, &app)
	if err != nil {
		return err
	}
	template := `Application: %s
State: %s
Repository: %s
Platform: %s
Units: %s
Teams: %s
`
	name := app["Name"]
	state := app["State"]
	platform := app["Framework"]
	repository := app["Repository"]
	units := ""
	for _, unit := range app["Units"].([]interface{}) {
		if len(units) > 0 {
			units += ", "
		}
		units += fmt.Sprintf("%s", unit.(map[string]interface{})["Ip"].(string))
	}
	teams := ""
	for _, team := range app["Teams"].([]interface{}) {
		if len(teams) > 0 {
			teams += ", "
		}
		teams += fmt.Sprintf("%s", team.(string))
	}
	out := fmt.Sprintf(template, name, state, repository, platform, units, teams)
	context.Stdout.Write([]byte(out))
	return nil
}

type AppGrant struct {
	GuessingCommand
}

func (c *AppGrant) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "app-grant",
		Usage: "app-grant <teamname> [--app appname]",
		Desc: `grants access to an app to a team.

If you don't provide the app name, tsuru will try to guess it.`,
		MinArgs: 1,
	}
}

func (c *AppGrant) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	teamName := context.Args[0]
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s/%s", appName, teamName))
	request, err := http.NewRequest("PUT", url, nil)
	if err != nil {
		return err
	}
	_, err = client.Do(request)
	if err != nil {
		return err
	}
	fmt.Fprintf(context.Stdout, `Team "%s" was added to the "%s" app`+"\n", teamName, appName)
	return nil
}

type AppRevoke struct {
	GuessingCommand
}

func (c *AppRevoke) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "app-revoke",
		Usage: "app-revoke <teamname> [--app appname]",
		Desc: `revokes access to an app from a team.

If you don't provide the app name, tsuru will try to guess it.`,
		MinArgs: 1,
	}
}

func (c *AppRevoke) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	teamName := context.Args[0]
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s/%s", appName, teamName))
	request, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return err
	}
	_, err = client.Do(request)
	if err != nil {
		return err
	}
	fmt.Fprintf(context.Stdout, `Team "%s" was removed from the "%s" app`+"\n", teamName, appName)
	return nil
}

type AppModel struct {
	Name  string
	State string
	Units []Units
}

type Units struct {
	Ip string
}

type AppList struct{}

func (c *AppList) Run(context *cmd.Context, client cmd.Doer) error {
	request, err := http.NewRequest("GET", cmd.GetUrl("/apps"), nil)
	if err != nil {
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	if response.StatusCode == http.StatusNoContent {
		return nil
	}
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	return c.Show(result, context)
}

func (c *AppList) Show(result []byte, context *cmd.Context) error {
	var apps []AppModel
	err := json.Unmarshal(result, &apps)
	if err != nil {
		return err
	}
	table := cmd.NewTable()
	table.Headers = cmd.Row([]string{"Application", "State", "Ip"})
	for _, app := range apps {
		ip := ""
		if len(app.Units) > 0 {
			ip = app.Units[0].Ip
		}
		table.AddRow(cmd.Row([]string{app.Name, app.State, ip}))
	}
	context.Stdout.Write(table.Bytes())
	return nil
}

func (c *AppList) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "app-list",
		Usage: "app-list",
		Desc:  "list all your apps.",
	}
}

type AppRestart struct {
	GuessingCommand
}

func (c *AppRestart) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s/restart", appName))
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	_, err = io.Copy(context.Stdout, response.Body)
	if err != nil {
		return err
	}
	return nil
}

func (c *AppRestart) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "restart",
		Usage: "restart [--app appname]",
		Desc: `restarts an app.

If you don't provide the app name, tsuru will try to guess it.`,
		MinArgs: 0,
	}
}
<commit_msg>cmd/tsuru: refactoring AppInfo.Show<commit_after>// 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 tsuru

import (
	"encoding/json"
	"fmt"
	"github.com/globocom/tsuru/cmd"
	"io"
	"io/ioutil"
	"launchpad.net/gnuflag"
	"net/http"
	"strings"
)

var AppName = gnuflag.String("app", "", "App name for running app related commands.")
var AssumeYes = gnuflag.Bool("assume-yes", false, "Don't ask for confirmation on operations.")
var LogLines = gnuflag.Int("lines", 10, "The number of log lines to display")
var LogSource = gnuflag.String("source", "", "The log from the given source")

type AppInfo struct {
	GuessingCommand
}

func (c *AppInfo) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "app-info",
		Usage: "app-info [--app appname]",
		Desc: `show information about your app.

If you don't provide the app name, tsuru will try to guess it.`,
		MinArgs: 0,
	}
}

func (c *AppInfo) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s", appName))
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	if response.StatusCode == http.StatusNoContent {
		return nil
	}
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	return c.Show(result, context)
}

type unit struct {
	Name  string
	Ip    string
	State string
}

type app struct {
	Name       string
	Framework  string
	Repository string
	State      string
	Teams      []string
	Units      []unit
}

func (a *app) String() string {
	format := `Application: %s
State: %s
Repository: %s
Platform: %s
Units: %s
Teams: %s`
	teams := strings.Join(a.Teams, ", ")
	ips := make([]string, len(a.Units))
	for i, unit := range a.Units {
		ips[i] = unit.Ip
	}
	units := strings.Join(ips, ", ")
	return fmt.Sprintf(format, a.Name, a.State, a.Repository, a.Framework, units, teams)
}

func (c *AppInfo) Show(result []byte, context *cmd.Context) error {
	var a app
	err := json.Unmarshal(result, &a)
	if err != nil {
		return err
	}
	fmt.Fprintln(context.Stdout, &a)
	return nil
}

type AppGrant struct {
	GuessingCommand
}

func (c *AppGrant) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "app-grant",
		Usage: "app-grant <teamname> [--app appname]",
		Desc: `grants access to an app to a team.

If you don't provide the app name, tsuru will try to guess it.`,
		MinArgs: 1,
	}
}

func (c *AppGrant) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	teamName := context.Args[0]
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s/%s", appName, teamName))
	request, err := http.NewRequest("PUT", url, nil)
	if err != nil {
		return err
	}
	_, err = client.Do(request)
	if err != nil {
		return err
	}
	fmt.Fprintf(context.Stdout, `Team "%s" was added to the "%s" app`+"\n", teamName, appName)
	return nil
}

type AppRevoke struct {
	GuessingCommand
}

func (c *AppRevoke) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "app-revoke",
		Usage: "app-revoke <teamname> [--app appname]",
		Desc: `revokes access to an app from a team.

If you don't provide the app name, tsuru will try to guess it.`,
		MinArgs: 1,
	}
}

func (c *AppRevoke) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	teamName := context.Args[0]
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s/%s", appName, teamName))
	request, err := http.NewRequest("DELETE", url, nil)
	if err != nil {
		return err
	}
	_, err = client.Do(request)
	if err != nil {
		return err
	}
	fmt.Fprintf(context.Stdout, `Team "%s" was removed from the "%s" app`+"\n", teamName, appName)
	return nil
}

type AppModel struct {
	Name  string
	State string
	Units []Units
}

type Units struct {
	Ip string
}

type AppList struct{}

func (c *AppList) Run(context *cmd.Context, client cmd.Doer) error {
	request, err := http.NewRequest("GET", cmd.GetUrl("/apps"), nil)
	if err != nil {
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	if response.StatusCode == http.StatusNoContent {
		return nil
	}
	defer response.Body.Close()
	result, err := ioutil.ReadAll(response.Body)
	if err != nil {
		return err
	}
	return c.Show(result, context)
}

func (c *AppList) Show(result []byte, context *cmd.Context) error {
	var apps []AppModel
	err := json.Unmarshal(result, &apps)
	if err != nil {
		return err
	}
	table := cmd.NewTable()
	table.Headers = cmd.Row([]string{"Application", "State", "Ip"})
	for _, app := range apps {
		ip := ""
		if len(app.Units) > 0 {
			ip = app.Units[0].Ip
		}
		table.AddRow(cmd.Row([]string{app.Name, app.State, ip}))
	}
	context.Stdout.Write(table.Bytes())
	return nil
}

func (c *AppList) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "app-list",
		Usage: "app-list",
		Desc:  "list all your apps.",
	}
}

type AppRestart struct {
	GuessingCommand
}

func (c *AppRestart) Run(context *cmd.Context, client cmd.Doer) error {
	appName, err := c.Guess()
	if err != nil {
		return err
	}
	url := cmd.GetUrl(fmt.Sprintf("/apps/%s/restart", appName))
	request, err := http.NewRequest("GET", url, nil)
	if err != nil {
		return err
	}
	response, err := client.Do(request)
	if err != nil {
		return err
	}
	defer response.Body.Close()
	_, err = io.Copy(context.Stdout, response.Body)
	if err != nil {
		return err
	}
	return nil
}

func (c *AppRestart) Info() *cmd.Info {
	return &cmd.Info{
		Name:  "restart",
		Usage: "restart [--app appname]",
		Desc: `restarts an app.

If you don't provide the app name, tsuru will try to guess it.`,
		MinArgs: 0,
	}
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"io"
	"strconv"
	"strings"

	"github.com/itchyny/volume-go"
)

func run(args []string, out io.Writer) error {
	if len(args) == 0 {
		return errors.New("no arg")
	}
	switch args[0] {
	case "-v", "version", "-version", "--version":
		return printVersion(out)
	case "-h", "help", "-help", "--help":
		return printHelp(out)
	case "status":
		if len(args) == 1 {
			return printStatus(out)
		}
	case "get":
		if len(args) == 1 {
			return getVolume(out)
		}
	case "set":
		if len(args) == 2 {
			return setVolume(args[1])
		}
	case "up":
		if len(args) == 1 {
			return upVolume("6")
		} else if len(args) == 2 {
			return upVolume(args[1])
		}
	case "down":
		if len(args) == 1 {
			return downVolume("6")
		} else if len(args) == 2 {
			return downVolume(args[1])
		}
	case "mute":
		if len(args) == 1 {
			return volume.Mute()
		}
	case "unmute":
		if len(args) == 1 {
			return volume.Unmute()
		}
	}
	return fmt.Errorf("invalid argument for volume: %+v", args)
}

func printStatus(out io.Writer) error {
	vol, err := volume.GetVolume()
	if err != nil {
		return err
	}
	muted, err := volume.GetMuted()
	if err != nil {
		return err
	}
	fmt.Fprintf(out, "volume: %d\n", vol)
	fmt.Fprintf(out, "muted: %t\n", muted)
	return nil
}

func getVolume(out io.Writer) error {
	vol, err := volume.GetVolume()
	if err != nil {
		return err
	}
	fmt.Fprintln(out, vol)
	return nil
}

func setVolume(volStr string) error {
	vol, err := strconv.Atoi(volStr)
	if err != nil {
		return err
	}
	return volume.SetVolume(vol)
}

func upVolume(diffStr string) error {
	diff, err := strconv.Atoi(diffStr)
	if err != nil {
		return err
	}
	return volume.IncreaseVolume(diff)
}

func downVolume(diffStr string) error {
	diff, err := strconv.Atoi(diffStr)
	if err != nil {
		return err
	}
	return volume.IncreaseVolume(-diff)
}

func printVersion(out io.Writer) error {
	fmt.Fprintf(out, "%s version %s\n", name, version)
	return nil
}

func printHelp(out io.Writer) error {
	fmt.Fprintf(out, strings.Replace(`NAME:
   $NAME - %s

USAGE:
   $NAME command [argument...]

COMMANDS:
   status      prints the volume status
   get         prints the current volume
   set [vol]   sets the audio volume
   up [diff]   volume up by [diff]
   down [diff] volume down by [diff]
   mute        mutes the audio
   unmute      unmutes the audio
   version     prints the version
   help        prints this help

VERSION:
   %s

AUTHOR:
   %s
`, "$NAME", name, -1), description, version, author)
	return nil
}
<commit_msg>simplify help generation<commit_after>package main

import (
	"errors"
	"fmt"
	"io"
	"strconv"

	"github.com/itchyny/volume-go"
)

func run(args []string, out io.Writer) error {
	if len(args) == 0 {
		return errors.New("no arg")
	}
	switch args[0] {
	case "-v", "version", "-version", "--version":
		return printVersion(out)
	case "-h", "help", "-help", "--help":
		return printHelp(out)
	case "status":
		if len(args) == 1 {
			return printStatus(out)
		}
	case "get":
		if len(args) == 1 {
			return getVolume(out)
		}
	case "set":
		if len(args) == 2 {
			return setVolume(args[1])
		}
	case "up":
		if len(args) == 1 {
			return upVolume("6")
		} else if len(args) == 2 {
			return upVolume(args[1])
		}
	case "down":
		if len(args) == 1 {
			return downVolume("6")
		} else if len(args) == 2 {
			return downVolume(args[1])
		}
	case "mute":
		if len(args) == 1 {
			return volume.Mute()
		}
	case "unmute":
		if len(args) == 1 {
			return volume.Unmute()
		}
	}
	return fmt.Errorf("invalid argument for volume: %+v", args)
}

func printStatus(out io.Writer) error {
	vol, err := volume.GetVolume()
	if err != nil {
		return err
	}
	muted, err := volume.GetMuted()
	if err != nil {
		return err
	}
	fmt.Fprintf(out, "volume: %d\n", vol)
	fmt.Fprintf(out, "muted: %t\n", muted)
	return nil
}

func getVolume(out io.Writer) error {
	vol, err := volume.GetVolume()
	if err != nil {
		return err
	}
	fmt.Fprintln(out, vol)
	return nil
}

func setVolume(volStr string) error {
	vol, err := strconv.Atoi(volStr)
	if err != nil {
		return err
	}
	return volume.SetVolume(vol)
}

func upVolume(diffStr string) error {
	diff, err := strconv.Atoi(diffStr)
	if err != nil {
		return err
	}
	return volume.IncreaseVolume(diff)
}

func downVolume(diffStr string) error {
	diff, err := strconv.Atoi(diffStr)
	if err != nil {
		return err
	}
	return volume.IncreaseVolume(-diff)
}

func printVersion(out io.Writer) error {
	fmt.Fprintf(out, "%s version %s\n", name, version)
	return nil
}

func printHelp(out io.Writer) error {
	fmt.Fprintf(out, `%[1]s - %[2]s

USAGE:
   %[1]s command [argument...]

COMMANDS:
   status      prints the volume status
   get         prints the current volume
   set [vol]   sets the audio volume
   up [diff]   volume up by [diff]
   down [diff] volume down by [diff]
   mute        mutes the audio
   unmute      unmutes the audio
   version     prints the version
   help        prints this help

VERSION:
   %[3]s

AUTHOR:
   %[4]s
`, name, description, version, author)
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"time"

	"github.com/gonuts/commander"
	"github.com/gonuts/flag"
	"github.com/hwaf/gas"
)

func hwaf_make_cmd_self_bdist() *commander.Command {
	cmd := &commander.Command{
		Run:       hwaf_run_cmd_self_bdist,
		UsageLine: "bdist [options]",
		Short:     "create a binary distribution of hwaf itself",
		Long: `
self bdist creates a binary distribution of hwaf itself.

ex:
 $ hwaf self bdist
 $ hwaf self bdist -version=20130101
`,
		Flag: *flag.NewFlagSet("hwaf-self-bdist", flag.ExitOnError),
	}
	cmd.Flag.Bool("v", false, "enable verbose output")
	cmd.Flag.String("version", "", "version of the binary distribution (default: 'time now')")

	return cmd
}

func hwaf_run_cmd_self_bdist(cmd *commander.Command, args []string) {
	var err error

	n := "hwaf-self-" + cmd.Name()

	switch len(args) {
	case 0:
		// ok
	default:
		err = fmt.Errorf("%s: does NOT take any argument", n)
		handle_err(err)
	}

	verbose := cmd.Flag.Lookup("v").Value.Get().(bool)

	bdist_name := "hwaf"
	bdist_vers := cmd.Flag.Lookup("version").Value.Get().(string)
	bdist_variant := fmt.Sprintf("%s-%s", runtime.GOOS, runtime.GOARCH)

	if bdist_vers == "" {
		bdist_vers = time.Now().Format("20060102")
	}

	dirname := fmt.Sprintf("%s-%s-%s", bdist_name, bdist_vers, bdist_variant)
	fname := dirname + ".tar.gz"

	if verbose {
		fmt.Printf("%s [%s]...\n", n, fname)
	}

	tmpdir, err := ioutil.TempDir("", "hwaf-self-bdist-")
	handle_err(err)
	defer os.RemoveAll(tmpdir)
	//fmt.Printf(">>> [%s]\n", tmpdir)

	//
	top := filepath.Join(tmpdir, dirname)
	// create hierarchy of dirs for bdist
	for _, dir := range []string{
		"bin",
		"share",
		filepath.Join("share", "hwaf"),
	} {
		err = os.MkdirAll(filepath.Join(top, dir), 0755)
		handle_err(err)
	}

	// add hep-waftools cache
	hwaf_dir, err := gas.Abs("github.com/hwaf/hwaf")
	handle_err(err)

	src_hwaf_tools := filepath.Join(hwaf_dir, "py-hwaftools")
	hwaf_tools := filepath.Join(top, "share", "hwaf", "tools")

	err = copytree(hwaf_tools, src_hwaf_tools)
	handle_err(err)

	// remove git stuff
	err = os.RemoveAll(filepath.Join(hwaf_tools, ".git"))
	handle_err(err)

	// add share/hwaf/hwaf.conf
	err = ioutil.WriteFile(
		filepath.Join(top, "share", "hwaf", "hwaf.conf"),
		[]byte(`# hwaf config file
[hwaf]

## EOF ##
`),
		0644,
	)
	handle_err(err)

	// temporary GOPATH - install go-deps
	gopath := filepath.Join(tmpdir, "gocode")
	err = os.MkdirAll(gopath, 0755)
	handle_err(err)

	orig_gopath := os.Getenv("GOPATH")
	err = os.Setenv("GOPATH", gopath)
	handle_err(err)
	defer os.Setenv("GOPATH", orig_gopath)

	for _, gopkg := range []string{
		"github.com/hwaf/hwaf",
		"github.com/hwaf/git-tools/git-archive-all",
		"github.com/hwaf/git-tools/git-rm-submodule",
		"github.com/hwaf/git-tools/git-check-clean",
		"github.com/hwaf/git-tools/git-check-non-tracking",
		"github.com/hwaf/git-tools/git-check-unpushed",
	} {
		goget := exec.Command("go", "get", "-v", gopkg)
		goget.Dir = gopath
		if verbose {
			goget.Stdout = os.Stdout
			goget.Stderr = os.Stderr
		}
		err = goget.Run()
		handle_err(err)

		// install under /bin
		dst_fname := filepath.Join(top, "bin", filepath.Base(gopkg))
		dst, err := os.OpenFile(dst_fname, os.O_WRONLY|os.O_CREATE, 0755)
		handle_err(err)
		defer func(dst *os.File) {
			err := dst.Sync()
			handle_err(err)
			err = dst.Close()
			handle_err(err)
		}(dst)

		src_fname := filepath.Join(gopath, "bin", filepath.Base(gopkg))
		if !path_exists(src_fname) {
			// maybe a cross-compilation ?
			src_fname = filepath.Join(gopath, "bin", runtime.GOOS+"_"+runtime.GOARCH, filepath.Base(gopkg))
		}
		src, err := os.Open(src_fname)
		handle_err(err)
		defer func(src *os.File) {
			err := src.Close()
			handle_err(err)
		}(src)

		_, err = io.Copy(dst, src)
		handle_err(err)
	}

	// add waf-bin
	waf_fname := filepath.Join(top, "bin", "waf")
	if path_exists(waf_fname) {
		err = os.Remove(waf_fname)
		handle_err(err)
	}
	waf_dst, err := os.OpenFile(waf_fname, os.O_WRONLY|os.O_CREATE, 0777)
	handle_err(err)
	defer func() {
		err = waf_dst.Sync()
		handle_err(err)
		err = waf_dst.Close()
		handle_err(err)
	}()

	waf_src, err := os.Open(filepath.Join(
		gopath, "src", "github.com", "hwaf", "hwaf", "waf"),
	)
	handle_err(err)
	defer waf_src.Close()
	_, err = io.Copy(waf_dst, waf_src)
	handle_err(err)

	const bq = "`"
	// add setup.sh
	setup_fname, err := os.Create(filepath.Join(top, "setup-hwaf.sh"))
	handle_err(err)
	defer setup_fname.Close()
	_, err = fmt.Fprintf(setup_fname, `#!/bin/sh

if [ "x${BASH_ARGV[0]}" = "x" ]; then
    ## assume zsh
    SOURCE="$( cd -P "$( dirname "$0" )" && pwd )"
else
    SOURCE="$( cd -P "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
fi

DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
echo ":: adding [$DIR/bin] to PATH"
export PATH=$DIR/bin:$PATH

## EOF
## EOF
`)
	handle_err(err)

	handle_err(setup_fname.Sync())

	// add setup.csh
	csetup_fname, err := os.Create(filepath.Join(top, "setup-hwaf.csh"))
	handle_err(err)
	defer csetup_fname.Close()
	_, err = fmt.Fprintf(csetup_fname, `#!/bin/csh
# Absolute path to this script
set SCRIPT=%sreadlink -f "$0"%s
# Absolute path this script is in
set SCRIPTPATH=%sdirname "$SCRIPT"%s
echo ":: adding [$SCRIPTPATH/bin] to PATH"
setenv PATH $SCRIPTPATH/bin:$PATH

## EOF
`, bq, bq, bq, bq)
	handle_err(err)
	handle_err(csetup_fname.Sync())

	pwd, err := os.Getwd()
	handle_err(err)

	// package everything up
	err = _tar_gz(filepath.Join(pwd, fname), top)
	handle_err(err)

	if verbose {
		fmt.Printf("%s [%s]... [ok]\n", n, fname)
	}
}

// EOF
<commit_msg>self-bdist: fixed one-off dir for setup-hwaf.sh<commit_after>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"runtime"
	"time"

	"github.com/gonuts/commander"
	"github.com/gonuts/flag"
	"github.com/hwaf/gas"
)

func hwaf_make_cmd_self_bdist() *commander.Command {
	cmd := &commander.Command{
		Run:       hwaf_run_cmd_self_bdist,
		UsageLine: "bdist [options]",
		Short:     "create a binary distribution of hwaf itself",
		Long: `
self bdist creates a binary distribution of hwaf itself.

ex:
 $ hwaf self bdist
 $ hwaf self bdist -version=20130101
`,
		Flag: *flag.NewFlagSet("hwaf-self-bdist", flag.ExitOnError),
	}
	cmd.Flag.Bool("v", false, "enable verbose output")
	cmd.Flag.String("version", "", "version of the binary distribution (default: 'time now')")

	return cmd
}

func hwaf_run_cmd_self_bdist(cmd *commander.Command, args []string) {
	var err error

	n := "hwaf-self-" + cmd.Name()

	switch len(args) {
	case 0:
		// ok
	default:
		err = fmt.Errorf("%s: does NOT take any argument", n)
		handle_err(err)
	}

	verbose := cmd.Flag.Lookup("v").Value.Get().(bool)

	bdist_name := "hwaf"
	bdist_vers := cmd.Flag.Lookup("version").Value.Get().(string)
	bdist_variant := fmt.Sprintf("%s-%s", runtime.GOOS, runtime.GOARCH)

	if bdist_vers == "" {
		bdist_vers = time.Now().Format("20060102")
	}

	dirname := fmt.Sprintf("%s-%s-%s", bdist_name, bdist_vers, bdist_variant)
	fname := dirname + ".tar.gz"

	if verbose {
		fmt.Printf("%s [%s]...\n", n, fname)
	}

	tmpdir, err := ioutil.TempDir("", "hwaf-self-bdist-")
	handle_err(err)
	defer os.RemoveAll(tmpdir)
	//fmt.Printf(">>> [%s]\n", tmpdir)

	//
	top := filepath.Join(tmpdir, dirname)
	// create hierarchy of dirs for bdist
	for _, dir := range []string{
		"bin",
		"share",
		filepath.Join("share", "hwaf"),
	} {
		err = os.MkdirAll(filepath.Join(top, dir), 0755)
		handle_err(err)
	}

	// add hep-waftools cache
	hwaf_dir, err := gas.Abs("github.com/hwaf/hwaf")
	handle_err(err)

	src_hwaf_tools := filepath.Join(hwaf_dir, "py-hwaftools")
	hwaf_tools := filepath.Join(top, "share", "hwaf", "tools")

	err = copytree(hwaf_tools, src_hwaf_tools)
	handle_err(err)

	// remove git stuff
	err = os.RemoveAll(filepath.Join(hwaf_tools, ".git"))
	handle_err(err)

	// add share/hwaf/hwaf.conf
	err = ioutil.WriteFile(
		filepath.Join(top, "share", "hwaf", "hwaf.conf"),
		[]byte(`# hwaf config file
[hwaf]

## EOF ##
`),
		0644,
	)
	handle_err(err)

	// temporary GOPATH - install go-deps
	gopath := filepath.Join(tmpdir, "gocode")
	err = os.MkdirAll(gopath, 0755)
	handle_err(err)

	orig_gopath := os.Getenv("GOPATH")
	err = os.Setenv("GOPATH", gopath)
	handle_err(err)
	defer os.Setenv("GOPATH", orig_gopath)

	for _, gopkg := range []string{
		"github.com/hwaf/hwaf",
		"github.com/hwaf/git-tools/git-archive-all",
		"github.com/hwaf/git-tools/git-rm-submodule",
		"github.com/hwaf/git-tools/git-check-clean",
		"github.com/hwaf/git-tools/git-check-non-tracking",
		"github.com/hwaf/git-tools/git-check-unpushed",
	} {
		goget := exec.Command("go", "get", "-v", gopkg)
		goget.Dir = gopath
		if verbose {
			goget.Stdout = os.Stdout
			goget.Stderr = os.Stderr
		}
		err = goget.Run()
		handle_err(err)

		// install under /bin
		dst_fname := filepath.Join(top, "bin", filepath.Base(gopkg))
		dst, err := os.OpenFile(dst_fname, os.O_WRONLY|os.O_CREATE, 0755)
		handle_err(err)
		defer func(dst *os.File) {
			err := dst.Sync()
			handle_err(err)
			err = dst.Close()
			handle_err(err)
		}(dst)

		src_fname := filepath.Join(gopath, "bin", filepath.Base(gopkg))
		if !path_exists(src_fname) {
			// maybe a cross-compilation ?
			src_fname = filepath.Join(gopath, "bin", runtime.GOOS+"_"+runtime.GOARCH, filepath.Base(gopkg))
		}
		src, err := os.Open(src_fname)
		handle_err(err)
		defer func(src *os.File) {
			err := src.Close()
			handle_err(err)
		}(src)

		_, err = io.Copy(dst, src)
		handle_err(err)
	}

	// add waf-bin
	waf_fname := filepath.Join(top, "bin", "waf")
	if path_exists(waf_fname) {
		err = os.Remove(waf_fname)
		handle_err(err)
	}
	waf_dst, err := os.OpenFile(waf_fname, os.O_WRONLY|os.O_CREATE, 0777)
	handle_err(err)
	defer func() {
		err = waf_dst.Sync()
		handle_err(err)
		err = waf_dst.Close()
		handle_err(err)
	}()

	waf_src, err := os.Open(filepath.Join(
		gopath, "src", "github.com", "hwaf", "hwaf", "waf"),
	)
	handle_err(err)
	defer waf_src.Close()
	_, err = io.Copy(waf_dst, waf_src)
	handle_err(err)

	const bq = "`"
	// add setup.sh
	setup_fname, err := os.Create(filepath.Join(top, "setup-hwaf.sh"))
	handle_err(err)
	defer setup_fname.Close()
	_, err = fmt.Fprintf(setup_fname, `#!/bin/sh

if [ "x${BASH_ARGV[0]}" = "x" ]; then
    ## assume zsh
    SOURCE="$0"
else
    SOURCE="${BASH_SOURCE[0]}"
fi

DIR="$( cd -P "$( dirname "$SOURCE" )" && pwd )"
echo ":: adding [$DIR/bin] to PATH"
export PATH=$DIR/bin:$PATH
## EOF
`)
	handle_err(err)

	handle_err(setup_fname.Sync())

	// add setup.csh
	csetup_fname, err := os.Create(filepath.Join(top, "setup-hwaf.csh"))
	handle_err(err)
	defer csetup_fname.Close()
	_, err = fmt.Fprintf(csetup_fname, `#!/bin/csh
# Absolute path to this script
set SCRIPT=%sreadlink -f "$0"%s
# Absolute path this script is in
set SCRIPTPATH=%sdirname "$SCRIPT"%s
echo ":: adding [$SCRIPTPATH/bin] to PATH"
setenv PATH $SCRIPTPATH/bin:$PATH

## EOF
`, bq, bq, bq, bq)
	handle_err(err)
	handle_err(csetup_fname.Sync())

	pwd, err := os.Getwd()
	handle_err(err)

	// package everything up
	err = _tar_gz(filepath.Join(pwd, fname), top)
	handle_err(err)

	if verbose {
		fmt.Printf("%s [%s]... [ok]\n", n, fname)
	}
}

// EOF
<|endoftext|>


<commit_before>// Copyright © 2015 Steve Francia <spf@spf13.com>.
//
// 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"
	"github.com/spf13/cobra/cobra/tpl"
	"os"
	"path"
	"path/filepath"
	"text/template"

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

var (
	pkgName string

	initCmd = &cobra.Command{
		Use:     "init [name]",
		Aliases: []string{"initialize", "initialise", "create"},
		Short:   "Initialize a Cobra Application",
		Long: `Initialize (cobra init) will create a new application, with a license
and the appropriate structure for a Cobra-based CLI application.

  * If a name is provided, it will be created in the current directory;
  * If no name is provided, the current directory will be assumed;
  * If a relative path is provided, it will be created inside $GOPATH
    (e.g. github.com/spf13/hugo);
  * If an absolute path is provided, it will be created;
  * If the directory already exists but is empty, it will be used.

Init will not use an existing directory with contents.`,

		Run: func(cmd *cobra.Command, args []string) {

			wd, err := os.Getwd()
			if err != nil {
				er(err)
			}

			project := &Project{
				AbsolutePath: wd,
				PkgName:      pkgName,
				Legal:        getLicense(),
				Copyright:    copyrightLine(),
				Viper:        viper.GetBool("useViper"),
				AppName:      path.Base(pkgName),
			}

			// create main.go
			mainFile, err := os.Create(fmt.Sprintf("%s/main.go", project.AbsolutePath))
			if err != nil {
				er(err)
			}
			defer mainFile.Close()

			mainTemplate := template.Must(template.New("main").Parse(string(tpl.MainTemplate())))
			err = mainTemplate.Execute(mainFile, project)
			if err != nil {
				er(err)
			}

			// create cmd/root.go
			rootFile, err := os.Create(fmt.Sprintf("%s/cmd/root.go", project.AbsolutePath))
			if err != nil {
				er(err)
			}
			defer rootFile.Close()

			rootTemplate := template.Must(template.New("root").Parse(string(tpl.RootTemplate())))
			err = rootTemplate.Execute(rootFile, project)
			if err != nil {
				er(err)
			}

			createLicenseFile(project.Legal, project.AbsolutePath)

			/*
				wd, err := os.Getwd()
				if err != nil {
					er(err)
				}

				var project *Project
				if len(args) == 0 {
					project = NewProjectFromPath(wd)
				} else if len(args) == 1 {
					arg := args[0]
					if arg[0] == '.' {
						arg = filepath.Join(wd, arg)
					}
					if filepath.IsAbs(arg) {
						project = NewProjectFromPath(arg)
					} else {
						project = NewProject(arg)
					}
				} else {
					er("please provide only one argument")
				}

				initializeProject(project)
			*/

			fmt.Printf("Your Cobra applicaton is ready at\n%s\n", project.AbsolutePath)
		},
	}
)

func init() {
	initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")
	initCmd.MarkFlagRequired("pkg-name")
}

func initializeProject(project *Project) {
	if !exists(project.AbsPath()) { // If path doesn't yet exist, create it
		err := os.MkdirAll(project.AbsPath(), os.ModePerm)
		if err != nil {
			er(err)
		}
	} else if !isEmpty(project.AbsPath()) { // If path exists and is not empty don't use it
		er("Cobra will not create a new project in a non empty directory: " + project.AbsPath())
	}

	// We have a directory and it's empty. Time to initialize it.
	createLicenseFile(project.License(), project.AbsPath())
	createMainFile(project)
	createRootCmdFile(project)
}

func createLicenseFile(license License, path string) {
	data := make(map[string]interface{})
	data["copyright"] = copyrightLine()

	// Generate license template from text and data.
	text, err := executeTemplate(license.Text, data)
	if err != nil {
		er(err)
	}

	// Write license text to LICENSE file.
	err = writeStringToFile(filepath.Join(path, "LICENSE"), text)
	if err != nil {
		er(err)
	}
}

func createMainFile(project *Project) {
	mainTemplate := `{{ comment .copyright }}
{{if .license}}{{ comment .license }}{{end}}

package main

import "{{ .importpath }}"

func main() {
	cmd.Execute()
}
`
	data := make(map[string]interface{})
	data["copyright"] = copyrightLine()
	data["license"] = project.License().Header
	data["importpath"] = path.Join(project.Name(), filepath.Base(project.CmdPath()))

	mainScript, err := executeTemplate(mainTemplate, data)
	if err != nil {
		er(err)
	}

	err = writeStringToFile(filepath.Join(project.AbsPath(), "main.go"), mainScript)
	if err != nil {
		er(err)
	}
}

func createRootCmdFile(project *Project) {
	template := `{{comment .copyright}}
{{if .license}}{{comment .license}}{{end}}

package cmd

import (
	"fmt"
	"os"
{{if .viper}}
	homedir "github.com/mitchellh/go-homedir"{{end}}
	"github.com/spf13/cobra"{{if .viper}}
	"github.com/spf13/viper"{{end}}
){{if .viper}}

var cfgFile string{{end}}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "{{.appName}}",
	Short: "A brief description of your application",
	Long: ` + "`" + `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.` + "`" + `,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	//	Run: func(cmd *cobra.Command, args []string) { },
}

// 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() { {{- if .viper}}
	cobra.OnInitialize(initConfig)
{{end}}
	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.{{ if .viper }}
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ else }}
	// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ end }}

	// 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")
}{{ if .viper }}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// Search config in home directory with name ".{{ .appName }}" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".{{ .appName }}")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}{{ end }}
`

	data := make(map[string]interface{})
	data["copyright"] = copyrightLine()
	data["viper"] = viper.GetBool("useViper")
	data["license"] = project.License().Header
	data["appName"] = path.Base(project.Name())

	rootCmdScript, err := executeTemplate(template, data)
	if err != nil {
		er(err)
	}

	err = writeStringToFile(filepath.Join(project.CmdPath(), "root.go"), rootCmdScript)
	if err != nil {
		er(err)
	}

}
<commit_msg>vgo - create directory<commit_after>// Copyright © 2015 Steve Francia <spf@spf13.com>.
//
// 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"
	"github.com/spf13/cobra/cobra/tpl"
	"os"
	"path"
	"path/filepath"
	"text/template"

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

var (
	pkgName string

	initCmd = &cobra.Command{
		Use:     "init [name]",
		Aliases: []string{"initialize", "initialise", "create"},
		Short:   "Initialize a Cobra Application",
		Long: `Initialize (cobra init) will create a new application, with a license
and the appropriate structure for a Cobra-based CLI application.

  * If a name is provided, it will be created in the current directory;
  * If no name is provided, the current directory will be assumed;
  * If a relative path is provided, it will be created inside $GOPATH
    (e.g. github.com/spf13/hugo);
  * If an absolute path is provided, it will be created;
  * If the directory already exists but is empty, it will be used.

Init will not use an existing directory with contents.`,

		Run: func(cmd *cobra.Command, args []string) {

			wd, err := os.Getwd()
			if err != nil {
				er(err)
			}

			project := &Project{
				AbsolutePath: wd,
				PkgName:      pkgName,
				Legal:        getLicense(),
				Copyright:    copyrightLine(),
				Viper:        viper.GetBool("useViper"),
				AppName:      path.Base(pkgName),
			}

			// create main.go
			mainFile, err := os.Create(fmt.Sprintf("%s/main.go", project.AbsolutePath))
			if err != nil {
				er(err)
			}
			defer mainFile.Close()

			mainTemplate := template.Must(template.New("main").Parse(string(tpl.MainTemplate())))
			err = mainTemplate.Execute(mainFile, project)
			if err != nil {
				er(err)
			}

			// create cmd/root.go
			if _, err = os.Stat(fmt.Sprintf("%s/cmd", project.AbsolutePath)); os.IsNotExist(err) {
				os.Mkdir("cmd", 0751)
			}
			rootFile, err := os.Create(fmt.Sprintf("%s/cmd/root.go", project.AbsolutePath))
			if err != nil {
				er(err)
			}
			defer rootFile.Close()

			rootTemplate := template.Must(template.New("root").Parse(string(tpl.RootTemplate())))
			err = rootTemplate.Execute(rootFile, project)
			if err != nil {
				er(err)
			}

			createLicenseFile(project.Legal, project.AbsolutePath)

			/*
				wd, err := os.Getwd()
				if err != nil {
					er(err)
				}

				var project *Project
				if len(args) == 0 {
					project = NewProjectFromPath(wd)
				} else if len(args) == 1 {
					arg := args[0]
					if arg[0] == '.' {
						arg = filepath.Join(wd, arg)
					}
					if filepath.IsAbs(arg) {
						project = NewProjectFromPath(arg)
					} else {
						project = NewProject(arg)
					}
				} else {
					er("please provide only one argument")
				}

				initializeProject(project)
			*/

			fmt.Printf("Your Cobra applicaton is ready at\n%s\n", project.AbsolutePath)
		},
	}
)

func init() {
	initCmd.Flags().StringVar(&pkgName, "pkg-name", "", "fully qualified pkg name")
	initCmd.MarkFlagRequired("pkg-name")
}

func initializeProject(project *Project) {
	if !exists(project.AbsPath()) { // If path doesn't yet exist, create it
		err := os.MkdirAll(project.AbsPath(), os.ModePerm)
		if err != nil {
			er(err)
		}
	} else if !isEmpty(project.AbsPath()) { // If path exists and is not empty don't use it
		er("Cobra will not create a new project in a non empty directory: " + project.AbsPath())
	}

	// We have a directory and it's empty. Time to initialize it.
	createLicenseFile(project.License(), project.AbsPath())
	createMainFile(project)
	createRootCmdFile(project)
}

func createLicenseFile(license License, path string) {
	data := make(map[string]interface{})
	data["copyright"] = copyrightLine()

	// Generate license template from text and data.
	text, err := executeTemplate(license.Text, data)
	if err != nil {
		er(err)
	}

	// Write license text to LICENSE file.
	err = writeStringToFile(filepath.Join(path, "LICENSE"), text)
	if err != nil {
		er(err)
	}
}

func createMainFile(project *Project) {
	mainTemplate := `{{ comment .copyright }}
{{if .license}}{{ comment .license }}{{end}}

package main

import "{{ .importpath }}"

func main() {
	cmd.Execute()
}
`
	data := make(map[string]interface{})
	data["copyright"] = copyrightLine()
	data["license"] = project.License().Header
	data["importpath"] = path.Join(project.Name(), filepath.Base(project.CmdPath()))

	mainScript, err := executeTemplate(mainTemplate, data)
	if err != nil {
		er(err)
	}

	err = writeStringToFile(filepath.Join(project.AbsPath(), "main.go"), mainScript)
	if err != nil {
		er(err)
	}
}

func createRootCmdFile(project *Project) {
	template := `{{comment .copyright}}
{{if .license}}{{comment .license}}{{end}}

package cmd

import (
	"fmt"
	"os"
{{if .viper}}
	homedir "github.com/mitchellh/go-homedir"{{end}}
	"github.com/spf13/cobra"{{if .viper}}
	"github.com/spf13/viper"{{end}}
){{if .viper}}

var cfgFile string{{end}}

// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
	Use:   "{{.appName}}",
	Short: "A brief description of your application",
	Long: ` + "`" + `A longer description that spans multiple lines and likely contains
examples and usage of using your application. For example:

Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.` + "`" + `,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	//	Run: func(cmd *cobra.Command, args []string) { },
}

// 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() { {{- if .viper}}
	cobra.OnInitialize(initConfig)
{{end}}
	// Here you will define your flags and configuration settings.
	// Cobra supports persistent flags, which, if defined here,
	// will be global for your application.{{ if .viper }}
	rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ else }}
	// rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.{{ .appName }}.yaml)"){{ end }}

	// 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")
}{{ if .viper }}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	if cfgFile != "" {
		// Use config file from the flag.
		viper.SetConfigFile(cfgFile)
	} else {
		// Find home directory.
		home, err := homedir.Dir()
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		// Search config in home directory with name ".{{ .appName }}" (without extension).
		viper.AddConfigPath(home)
		viper.SetConfigName(".{{ .appName }}")
	}

	viper.AutomaticEnv() // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}{{ end }}
`

	data := make(map[string]interface{})
	data["copyright"] = copyrightLine()
	data["viper"] = viper.GetBool("useViper")
	data["license"] = project.License().Header
	data["appName"] = path.Base(project.Name())

	rootCmdScript, err := executeTemplate(template, data)
	if err != nil {
		er(err)
	}

	err = writeStringToFile(filepath.Join(project.CmdPath(), "root.go"), rootCmdScript)
	if err != nil {
		er(err)
	}

}
<|endoftext|>


<commit_before>package commands

import (
	"time"

	"github.com/aymerick/kowa/models"
	"github.com/aymerick/kowa/server"
	"github.com/spf13/cobra"
	"gopkg.in/mgo.v2/bson"
)

var bootstrapCmd = &cobra.Command{
	Use:   "bootstrap",
	Short: "Bootstrap Kowa",
	Long:  `Creates records in database`,
	Run:   bootstrap,
}

func bootstrap(cmd *cobra.Command, args []string) {
	// @todo Check that we are NOT in production

	// Insert user
	user := models.User{
		Id:        bson.NewObjectId(),
		FirstName: "Jean-Claude",
		LastName:  "Trucmush",
		CreatedAt: time.Now(),
	}
	models.UsersCol().Insert(&user)

	// Insert site
	site := models.Site{
		Id:          bson.NewObjectId(),
		UserId:      user.Id,
		CreatedAt:   time.Now(),
		Name:        "My site",
		Tagline:     "So powerfull !",
		Description: "You will be astonished by what my site is about",
	}
	models.SitesCol().Insert(&site)

	// Insert oauth client
	oauthStorage := server.NewOAuthStorage()
	oauthStorage.SetupDefaultClient()
}
<commit_msg>Adds fixtures<commit_after>package commands

import (
	"time"

	"github.com/aymerick/kowa/models"
	"github.com/aymerick/kowa/server"
	"github.com/spf13/cobra"
	"gopkg.in/mgo.v2/bson"
)

var bootstrapCmd = &cobra.Command{
	Use:   "bootstrap",
	Short: "Bootstrap Kowa",
	Long:  `Creates records in database`,
	Run:   bootstrap,
}

func bootstrap(cmd *cobra.Command, args []string) {
	// @todo Check that we are NOT in production

	// Insert users
	userJeanClaude := models.User{
		Id:        bson.NewObjectId(),
		FirstName: "Jean-Claude",
		LastName:  "Trucmush",
		CreatedAt: time.Now(),
	}
	models.UsersCol().Insert(&userJeanClaude)

	userHenry := models.User{
		Id:        bson.NewObjectId(),
		FirstName: "Henry",
		LastName:  "Kanan",
		CreatedAt: time.Now(),
	}
	models.UsersCol().Insert(&userHenry)

	// Insert sites
	var site models.Site

	site = models.Site{
		Id:          bson.NewObjectId(),
		UserId:      userJeanClaude.Id,
		CreatedAt:   time.Now(),
		Name:        "My site",
		Tagline:     "So powerfull !",
		Description: "You will be astonished by what my site is about",
	}
	models.SitesCol().Insert(&site)

	site = models.Site{
		Id:          bson.NewObjectId(),
		UserId:      userJeanClaude.Id,
		CreatedAt:   time.Now(),
		Name:        "My second site",
		Tagline:     "Very interesting",
		Description: "Our projects are so importants, please help us",
	}
	models.SitesCol().Insert(&site)

	site = models.Site{
		Id:          bson.NewObjectId(),
		UserId:      userHenry.Id,
		CreatedAt:   time.Now(),
		Name:        "Ultimate petanque",
		Tagline:     "La petanque comme vous ne l'avez jamais vu",
		Description: "C'est vraiment le sport du futur. Messieurs, preparez vos boules !",
	}
	models.SitesCol().Insert(&site)

	// Insert oauth client
	oauthStorage := server.NewOAuthStorage()
	oauthStorage.SetupDefaultClient()
}
<|endoftext|>


<commit_before>// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package server

import (
	"github.com/juju/errors"
	"github.com/juju/loggo"
	"github.com/juju/names"
	"gopkg.in/juju/charm.v5"

	"github.com/juju/juju/apiserver/common"
	"github.com/juju/juju/process"
	"github.com/juju/juju/process/api"
	"github.com/juju/juju/process/plugin"
)

var logger = loggo.GetLogger("juju.process.api.server")

// API serves workload process-specific API methods.
type API struct {
	st State
}

// State is an interface that exposes functionality this package needs to wrap
// in an API.
type State interface {
	RegisterProcess(unit names.UnitTag, info process.Info) error
	ListProcesses(unit names.UnitTag, ids []string) ([]process.Info, error)
	SetProcessStatus(unit names.UnitTag, id string, status string) error
	UnregisterProcess(unit names.UnitTag, id string) error
}

// NewAPI creates a new instance of the Process API facade.
func NewAPI(st State, authorizer common.Authorizer) (API, error) {
	if !authorizer.AuthUnitAgent() {
		return API{}, errors.Trace(common.ErrPerm)
	}
	return API{st: st}, nil
}

// RegisterProcess registers a workload process in state.
func (a API) RegisterProcess(args api.RegisterProcessArgs) error {
	info := api2Proc(args.ProcessInfo)
	unit := names.NewUnitTag(info.Name)

	return errors.Trace(a.st.RegisterProcess(unit, info))
}

// ListProcesses builds the list of workload processes registered for
// the given unit and IDs. If no IDs are provided then all registered
// processes for the unit are returned.
func (a *API) ListProcesses(args api.ListProcessesArgs) ([]api.ProcessInfo, error) {
	infos, err := a.st.ListProcesses(names.NewUnitTag(args.UnitTag), args.IDs)
	if err != nil {
		return nil, errors.Trace(err)
	}
	rets := make([]api.ProcessInfo, len(infos))
	for i, info := range infos {
		rets[i] = proc2api(info)
	}
	return rets, nil
}

// SetProcessStatus sets the raw status of a workload process.
func (a *API) SetProcessStatus(args api.SetProcessStatusArgs) error {
	unit := names.NewUnitTag(args.UnitTag)
	return errors.Trace(a.st.SetProcessStatus(unit, args.ID, args.Status.Status))
}

// UnregisterProcess marks the identified process as unregistered.
func (a *API) UnregisterProcess(args api.UnregisterProcessArgs) error {
	unit := names.NewUnitTag(args.UnitTag)
	return errors.Trace(a.st.UnregisterProcess(unit, args.ID))
}

func api2Proc(p api.ProcessInfo) process.Info {
	return process.Info{
		Process: charm.Process{
			Name:        p.Process.Name,
			Description: p.Process.Description,
			Type:        p.Process.Type,
			TypeOptions: p.Process.TypeOptions,
			Command:     p.Process.Command,
			Image:       p.Process.Image,
			Ports:       api2charmPorts(p.Process.Ports),
			Volumes:     api2charmVolumes(p.Process.Volumes),
			EnvVars:     p.Process.EnvVars,
		},
		Status: process.Status(p.Status),
		Details: plugin.ProcDetails{
			ID: p.Details.ID,
			ProcStatus: plugin.ProcStatus{
				Status: p.Details.Status,
			},
		},
	}
}

func proc2api(p process.Info) api.ProcessInfo {
	return api.ProcessInfo{
		Process: api.Process{
			Name:        p.Process.Name,
			Description: p.Process.Description,
			Type:        p.Process.Type,
			TypeOptions: p.Process.TypeOptions,
			Command:     p.Process.Command,
			Image:       p.Process.Image,
			Ports:       charm2apiPorts(p.Process.Ports),
			Volumes:     charm2apiVolumes(p.Process.Volumes),
			EnvVars:     p.Process.EnvVars,
		},
		Status: int(p.Status),
		Details: api.ProcDetails{
			ID: p.Details.ID,
			ProcStatus: api.ProcStatus{
				Status: p.Details.Status,
			},
		},
	}
}

func api2charmPorts(ports []api.ProcessPort) []charm.ProcessPort {
	ret := make([]charm.ProcessPort, len(ports))
	for i, p := range ports {
		ret[i] = charm.ProcessPort{
			Internal: p.Internal,
			External: p.External,
			Endpoint: p.Endpoint,
		}
	}
	return ret
}

func api2charmVolumes(vols []api.ProcessVolume) []charm.ProcessVolume {
	ret := make([]charm.ProcessVolume, len(vols))
	for i, v := range vols {
		ret[i] = charm.ProcessVolume{
			ExternalMount: v.ExternalMount,
			InternalMount: v.InternalMount,
			Mode:          v.Mode,
			Name:          v.Name,
		}
	}
	return ret
}

func charm2apiPorts(ports []charm.ProcessPort) []api.ProcessPort {
	ret := make([]api.ProcessPort, len(ports))
	for i, p := range ports {
		ret[i] = api.ProcessPort{
			Internal: p.Internal,
			External: p.External,
			Endpoint: p.Endpoint,
		}
	}
	return ret
}

func charm2apiVolumes(vols []charm.ProcessVolume) []api.ProcessVolume {
	ret := make([]api.ProcessVolume, len(vols))
	for i, v := range vols {
		ret[i] = api.ProcessVolume{
			ExternalMount: v.ExternalMount,
			InternalMount: v.InternalMount,
			Mode:          v.Mode,
			Name:          v.Name,
		}
	}
	return ret
}
<commit_msg>fix up<commit_after>// Copyright 2015 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package server

import (
	"github.com/juju/errors"
	"github.com/juju/loggo"
	"github.com/juju/names"
	"gopkg.in/juju/charm.v5"

	"github.com/juju/juju/apiserver/common"
	"github.com/juju/juju/process"
	"github.com/juju/juju/process/api"
	"github.com/juju/juju/process/plugin"
)

var logger = loggo.GetLogger("juju.process.api.server")

// API serves workload process-specific API methods.
type API struct {
	st State
}

// State is an interface that exposes functionality this package needs to wrap
// in an API.
type State interface {
	RegisterProcess(unit names.UnitTag, info process.Info) error
	ListProcesses(unit names.UnitTag, ids []string) ([]process.Info, error)
	SetProcessStatus(unit names.UnitTag, id string, status string) error
	UnregisterProcess(unit names.UnitTag, id string) error
}

// NewAPI creates a new instance of the Process API facade.
func NewAPI(st State, authorizer common.Authorizer) (API, error) {
	if !authorizer.AuthUnitAgent() {
		return API{}, errors.Trace(common.ErrPerm)
	}
	return API{st: st}, nil
}

// RegisterProcess registers a workload process in state.
func (a API) RegisterProcess(args api.RegisterProcessArgs) error {
	info := api2Proc(args.ProcessInfo)
	unit := names.NewUnitTag(info.Name)

	return errors.Trace(a.st.RegisterProcess(unit, info))
}

// ListProcesses builds the list of workload processes registered for
// the given unit and IDs. If no IDs are provided then all registered
// processes for the unit are returned.
func (a *API) ListProcesses(args api.ListProcessesArgs) ([]api.ProcessInfo, error) {
	infos, err := a.st.ListProcesses(names.NewUnitTag(args.UnitTag), args.IDs)
	if err != nil {
		return nil, errors.Trace(err)
	}
	rets := make([]api.ProcessInfo, len(infos))
	for i, info := range infos {
		rets[i] = proc2api(info)
	}
	return rets, nil
}

// SetProcessStatus sets the raw status of a workload process.
func (a *API) SetProcessStatus(args api.SetProcessStatusArgs) error {
	unit := names.NewUnitTag(args.UnitTag)
	return errors.Trace(a.st.SetProcessStatus(unit, args.ID, args.Status.Status))
}

// UnregisterProcess marks the identified process as unregistered.
func (a *API) UnregisterProcess(args api.UnregisterProcessArgs) error {
	unit := names.NewUnitTag(args.UnitTag)
	return errors.Trace(a.st.UnregisterProcess(unit, args.ID))
}

func api2Proc(p api.ProcessInfo) process.Info {
	return process.Info{
		Process: charm.Process{
			Name:        p.Process.Name,
			Description: p.Process.Description,
			Type:        p.Process.Type,
			TypeOptions: p.Process.TypeOptions,
			Command:     p.Process.Command,
			Image:       p.Process.Image,
			Ports:       api2charmPorts(p.Process.Ports),
			Volumes:     api2charmVolumes(p.Process.Volumes),
			EnvVars:     p.Process.EnvVars,
		},
		Status: process.Status(p.Status),
		Details: plugin.ProcDetails{
			ID: p.Details.ID,
			ProcStatus: plugin.ProcStatus{
				Status: p.Details.Status,
			},
		},
	}
}

func proc2api(p process.Info) api.ProcessInfo {
	return api.ProcessInfo{
		Process: api.Process{
			Name:        p.Process.Name,
			Description: p.Process.Description,
			Type:        p.Process.Type,
			TypeOptions: p.Process.TypeOptions,
			Command:     p.Process.Command,
			Image:       p.Process.Image,
			Ports:       charm2apiPorts(p.Process.Ports),
			Volumes:     charm2apiVolumes(p.Process.Volumes),
			EnvVars:     p.Process.EnvVars,
		},
		Status: int(p.Status),
		Details: api.ProcDetails{
			ID: p.Details.ID,
			ProcStatus: api.ProcStatus{
				Status: p.Details.Status,
			},
		},
	}
}

func api2charmPorts(ports []api.ProcessPort) []charm.ProcessPort {
	ret := make([]charm.ProcessPort, len(ports))
	for i, p := range ports {
		ret[i] = charm.ProcessPort{
			Internal: p.Internal,
			External: p.External,
			Endpoint: p.Endpoint,
		}
	}
	return ret
}

func api2charmVolumes(vols []api.ProcessVolume) []charm.ProcessVolume {
	ret := make([]charm.ProcessVolume, len(vols))
	for i, v := range vols {
		ret[i] = charm.ProcessVolume{
			ExternalMount: v.ExternalMount,
			InternalMount: v.InternalMount,
			Mode:          v.Mode,
			Name:          v.Name,
		}
	}
	return ret
}

func charm2apiPorts(ports []charm.ProcessPort) []api.ProcessPort {
	ret := make([]api.ProcessPort, len(ports))
	for i, p := range ports {
		ret[i] = api.ProcessPort{
			Internal: p.Internal,
			External: p.External,
			Endpoint: p.Endpoint,
		}
	}
	return ret
}

func charm2apiVolumes(vols []charm.ProcessVolume) []api.ProcessVolume {
	ret := make([]api.ProcessVolume, len(vols))
	for i, v := range vols {
		ret[i] = api.ProcessVolume{
			ExternalMount: v.ExternalMount,
			InternalMount: v.InternalMount,
			Mode:          v.Mode,
			Name:          v.Name,
		}
	}
	return ret
}
<|endoftext|>


<commit_before>package vizzini_test

import (
	"code.cloudfoundry.org/bbs/models"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Cells", func() {
	It("should return all cells", func() {
		cells, err := bbsClient.Cells(logger)
		Expect(err).NotTo(HaveOccurred())
		Expect(len(cells)).To(BeNumerically(">=", 1))

		var cell_z1_0 *models.CellPresence
		for _, cell := range cells {
			if cell.CellId == "cell_z1-0" {
				cell_z1_0 = cell
				break
			}
		}

		Expect(cell_z1_0).NotTo(BeNil())
		Expect(cell_z1_0.CellId).To(Equal("cell_z1-0"))
		Expect(cell_z1_0.Zone).To(Equal("z1"))
		Expect(cell_z1_0.Capacity.MemoryMb).To(BeNumerically(">", 0))
		Expect(cell_z1_0.Capacity.DiskMb).To(BeNumerically(">", 0))
		Expect(cell_z1_0.Capacity.Containers).To(BeNumerically(">", 0))
		Expect(len(cell_z1_0.RootfsProviders)).To(BeNumerically(">", 0))
	})
})
<commit_msg>Fix cell id vizzini test<commit_after>package vizzini_test

import (
	"strings"

	"code.cloudfoundry.org/bbs/models"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Cells", func() {
	It("should return all cells", func() {
		cells, err := bbsClient.Cells(logger)
		Expect(err).NotTo(HaveOccurred())
		Expect(len(cells)).To(BeNumerically(">=", 1))

		var cell_z1_0 *models.CellPresence
		for _, cell := range cells {
			if strings.HasPrefix(cell.CellId, "cell_z1-0") {
				cell_z1_0 = cell
				break
			}
		}

		Expect(cell_z1_0).NotTo(BeNil())
		Expect(cell_z1_0.CellId).To(HavePrefix("cell_z1-0"))
		Expect(cell_z1_0.Zone).To(Equal("z1"))
		Expect(cell_z1_0.Capacity.MemoryMb).To(BeNumerically(">", 0))
		Expect(cell_z1_0.Capacity.DiskMb).To(BeNumerically(">", 0))
		Expect(cell_z1_0.Capacity.Containers).To(BeNumerically(">", 0))
		Expect(len(cell_z1_0.RootfsProviders)).To(BeNumerically(">", 0))
	})
})
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"math/rand"
	"sync"
	"time"

	"github.com/golang/glog"
	"github.com/google/certificate-transparency/go/x509"
	ctfe "github.com/google/trillian/examples/ct"
	"github.com/google/trillian/integration"
)

var (
	httpServersFlag = flag.String("ct_http_servers", "localhost:8092", "Comma-separated list of (assumed interchangeable) servers, each as address:port")
	testDir         = flag.String("testdata_dir", "testdata", "Name of directory with test data")
	seed            = flag.Int64("seed", -1, "Seed for random number generation")
	logConfigFlag   = flag.String("log_config", "", "File holding log config in JSON")
	mmdFlag         = flag.Duration("mmd", 2*time.Minute, "MMD for logs")
	operationsFlag  = flag.Uint64("operations", ^uint64(0), "Number of operations to perform")
)
var (
	addChainBias          = flag.Int("add_chain", 20, "Bias for add-chain operations")
	addPreChainBias       = flag.Int("add_pre_chain", 20, "Bias for add-pre-chain operations")
	getSTHBias            = flag.Int("get_sth", 2, "Bias for get-sth operations")
	getSTHConsistencyBias = flag.Int("get_sth_consistency", 2, "Bias for get-sth-consistency operations")
	getProofByHashBias    = flag.Int("get_proof_by_hash", 2, "Bias for get-proof-by-hash operations")
	getEntriesBias        = flag.Int("get_entries", 2, "Bias for get-entries operations")
	getRootsBias          = flag.Int("get_roots", 1, "Bias for get-roots operations")
	getEntryAndProofBias  = flag.Int("get_entry_and_proof", 0, "Bias for get-entry-and-proof operations")
)

func main() {
	flag.Parse()
	if *logConfigFlag == "" {
		glog.Fatal("Test aborted as no log config provided")
	}
	if *seed == -1 {
		*seed = time.Now().UTC().UnixNano() & 0xFFFFFFFF
	}
	rand.Seed(*seed)

	cfg, err := ctfe.LogConfigFromFile(*logConfigFlag)
	if err != nil {
		glog.Fatalf("Failed to read log config: %v", err)
	}

	// Retrieve the test data.
	caChain, err := integration.GetChain(*testDir, "int-ca.cert")
	if err != nil {
		glog.Fatalf("failed to load certificate: %v", err)
	}
	leafChain, err := integration.GetChain(*testDir, "leaf01.chain")
	if err != nil {
		glog.Fatalf("failed to load certificate: %v", err)
	}
	signer, err := integration.MakeSigner(*testDir)
	if err != nil {
		glog.Fatalf("failed to retrieve signer for re-signing: %v", err)
	}
	leafCert, err := x509.ParseCertificate(leafChain[0].Data)
	if err != nil {
		glog.Fatalf("failed to parse leaf certificate to build precert from: %v", err)
	}
	caCert, err := x509.ParseCertificate(caChain[0].Data)
	if err != nil {
		glog.Fatalf("failed to parse issuer for precert: %v", err)
	}
	bias := integration.HammerBias{Bias: map[ctfe.EntrypointName]int{
		ctfe.AddChainName:          *addChainBias,
		ctfe.AddPreChainName:       *addPreChainBias,
		ctfe.GetSTHName:            *getSTHBias,
		ctfe.GetSTHConsistencyName: *getSTHConsistencyBias,
		ctfe.GetProofByHashName:    *getProofByHashBias,
		ctfe.GetEntriesName:        *getEntriesBias,
		ctfe.GetRootsName:          *getRootsBias,
		ctfe.GetEntryAndProofName:  *getEntryAndProofBias,
	}}

	fmt.Print("\n\nStop")
	for i := 0; i < 8; i++ {
		time.Sleep(100 * time.Millisecond)
		fmt.Print(".")
	}

	fmt.Print(`
                                   ':++/.
                                  'sddhhyo'
                                  /hyyho+s-       '-:/+:.
                                 .sdhhysoy-  ' '/sdmNNmmy'
                             ':oooymmmdddmysymhmNNNNNNNh-
                      '.:::+so++++ymmmNNNdyyyNNNNNMMNd/'
             '...:::/://osoo++s+yyhmNNNMmdddhyymNNhs+.
     '..-://+++/////+//+sooosyyhdmmdNNNMmmmhhs+y/-'
    'oooooooo++++++/ossyyyyhhhhdddyymNNmhdmmdy:-'
  ':ohhso++/++//+/+/////:oyyyddhhy+/hmNNNMMMmo-'
  -hddo-''               +syyhhyyy+:ymNNMMNms:'
  'ss+'                  /sssyssyyo/sdmmmds+/.
   ''                    +sssssyyyysyhhyys+:.'
                         +ssyyssoosoosss+/:.'
                        -yyyyysooso+so+/::-'
                        smmdhyssssoso+//:-'
                       -mNMMMNdyssyso+/:.'
                   ':shmMMMMMMMMNMMNmo.
                  -hNMMMMMMMMMMMMMMMMd/'
                 .hNMMMMMMMMMMMMMMMMMMNy/.
                .yNMMMMMMMMMMMMMMMMMMMMMMd:
              .omMMMMMMMMMMMMMMMMMMMMNMMMMNo'
            .omMMMMMMMMMMMMMMMMMMMMMMMMMMMMMy.
           -dNMMMMMMMMMMMMMMMMMNNMMMMMNMMMMMMy'
          :dMMMMMMMMMMMMMMMMMMMNmNMMMMNNMMMMMN/
         .dMMMMMMMMMMMMMMMMMMMNmmMMMMMMMMMMMMMs'
         +NMMMMMMMMMMMMNmMMMMMNmNMMMMMMMMMMMMMy'
         -mMMMMMMMMMMMMMMMMMMMNNMMMMMMMMMMMMMMo'
         'hNMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNMNNh.
          sNMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNmh+.
          /NMMMMMMMMMMMMMMMMMNdmNMMMMMNNNm:
          -mMMMMMMMMMMMMMMNms-''/mMMMNddNm-
           oNMMMMMMMMMMMMd/'     +NMMNddmm:
           -mMMMMMMMMMMMN+'      'sNMMMNNmy-
            sNMMMMMMMMMNd.        'sNNMNNNmh-
            :NMMMMMMMMNm:          'yNNMMNNmy'
            'yNMMMMMMMNo'           .hNMMMNNm.
             .dMMMMMNNy'             -dNMMNNN:
              oNMMMNNm-               /NNMMNN/
              :NMMMMNh.                yNMMNms'
              :mMMMNN/                 -mMMMNy'
              'yNMmho'                  sNNmNNs.
            ''/mMMMmy'                  -mNMMMMNdhhy+'
          .yNNMMMMMNm+'                 /NMMMNNNmdy+-
           :hNNMMMNdd/'                 /dmNNdso+:.'`)
	fmt.Print("\n\nHammer Time\n\n")

	type result struct {
		prefix string
		err    error
	}
	results := make(chan result, len(cfg))
	var wg sync.WaitGroup
	for _, c := range cfg {
		wg.Add(1)
		cfg := integration.HammerConfig{
			LogCfg:     c,
			MMD:        *mmdFlag,
			LeafChain:  leafChain,
			LeafCert:   leafCert,
			CACert:     caCert,
			Signer:     signer,
			Servers:    *httpServersFlag,
			EPBias:     bias,
			Operations: *operationsFlag,
		}
		go func(cfg integration.HammerConfig) {
			defer wg.Done()
			err := integration.HammerCTLog(cfg)
			results <- result{prefix: cfg.LogCfg.Prefix, err: err}
		}(cfg)
	}
	wg.Wait()
	close(results)
	for e := range results {
		if e.err != nil {
			glog.Errorf("%s: %v", e.prefix, e.err)
		}
	}
}
<commit_msg>integration/ct: improve hammer test usability<commit_after>package main

import (
	"flag"
	"fmt"
	"math/rand"
	"os"
	"sync"
	"time"

	"github.com/golang/glog"
	"github.com/google/certificate-transparency/go/x509"
	ctfe "github.com/google/trillian/examples/ct"
	"github.com/google/trillian/integration"
)

var (
	httpServersFlag = flag.String("ct_http_servers", "localhost:8092", "Comma-separated list of (assumed interchangeable) servers, each as address:port")
	testDir         = flag.String("testdata_dir", "testdata", "Name of directory with test data")
	seed            = flag.Int64("seed", -1, "Seed for random number generation")
	logConfigFlag   = flag.String("log_config", "", "File holding log config in JSON")
	mmdFlag         = flag.Duration("mmd", 2*time.Minute, "MMD for logs")
	operationsFlag  = flag.Uint64("operations", ^uint64(0), "Number of operations to perform")
)
var (
	addChainBias          = flag.Int("add_chain", 20, "Bias for add-chain operations")
	addPreChainBias       = flag.Int("add_pre_chain", 20, "Bias for add-pre-chain operations")
	getSTHBias            = flag.Int("get_sth", 2, "Bias for get-sth operations")
	getSTHConsistencyBias = flag.Int("get_sth_consistency", 2, "Bias for get-sth-consistency operations")
	getProofByHashBias    = flag.Int("get_proof_by_hash", 2, "Bias for get-proof-by-hash operations")
	getEntriesBias        = flag.Int("get_entries", 2, "Bias for get-entries operations")
	getRootsBias          = flag.Int("get_roots", 1, "Bias for get-roots operations")
	getEntryAndProofBias  = flag.Int("get_entry_and_proof", 0, "Bias for get-entry-and-proof operations")
)

func main() {
	flag.Parse()
	if *logConfigFlag == "" {
		glog.Fatal("Test aborted as no log config provided (via --log_config)")
	}
	if *seed == -1 {
		*seed = time.Now().UTC().UnixNano() & 0xFFFFFFFF
	}
	fmt.Printf("Today's test has been brought to you by the letters C and T and the number %#x\n", *seed)
	rand.Seed(*seed)

	cfg, err := ctfe.LogConfigFromFile(*logConfigFlag)
	if err != nil {
		glog.Fatalf("Failed to read log config: %v", err)
	}

	// Retrieve the test data.
	caChain, err := integration.GetChain(*testDir, "int-ca.cert")
	if err != nil {
		glog.Fatalf("failed to load certificate: %v", err)
	}
	leafChain, err := integration.GetChain(*testDir, "leaf01.chain")
	if err != nil {
		glog.Fatalf("failed to load certificate: %v", err)
	}
	signer, err := integration.MakeSigner(*testDir)
	if err != nil {
		glog.Fatalf("failed to retrieve signer for re-signing: %v", err)
	}
	leafCert, err := x509.ParseCertificate(leafChain[0].Data)
	if err != nil {
		glog.Fatalf("failed to parse leaf certificate to build precert from: %v", err)
	}
	caCert, err := x509.ParseCertificate(caChain[0].Data)
	if err != nil {
		glog.Fatalf("failed to parse issuer for precert: %v", err)
	}
	bias := integration.HammerBias{Bias: map[ctfe.EntrypointName]int{
		ctfe.AddChainName:          *addChainBias,
		ctfe.AddPreChainName:       *addPreChainBias,
		ctfe.GetSTHName:            *getSTHBias,
		ctfe.GetSTHConsistencyName: *getSTHConsistencyBias,
		ctfe.GetProofByHashName:    *getProofByHashBias,
		ctfe.GetEntriesName:        *getEntriesBias,
		ctfe.GetRootsName:          *getRootsBias,
		ctfe.GetEntryAndProofName:  *getEntryAndProofBias,
	}}

	fmt.Print("\n\nStop")
	for i := 0; i < 8; i++ {
		time.Sleep(100 * time.Millisecond)
		fmt.Print(".")
	}

	fmt.Print(`
                                   ':++/.
                                  'sddhhyo'
                                  /hyyho+s-       '-:/+:.
                                 .sdhhysoy-  ' '/sdmNNmmy'
                             ':oooymmmdddmysymhmNNNNNNNh-
                      '.:::+so++++ymmmNNNdyyyNNNNNMMNd/'
             '...:::/://osoo++s+yyhmNNNMmdddhyymNNhs+.
     '..-://+++/////+//+sooosyyhdmmdNNNMmmmhhs+y/-'
    'oooooooo++++++/ossyyyyhhhhdddyymNNmhdmmdy:-'
  ':ohhso++/++//+/+/////:oyyyddhhy+/hmNNNMMMmo-'
  -hddo-''               +syyhhyyy+:ymNNMMNms:'
  'ss+'                  /sssyssyyo/sdmmmds+/.
   ''                    +sssssyyyysyhhyys+:.'
                         +ssyyssoosoosss+/:.'
                        -yyyyysooso+so+/::-'
                        smmdhyssssoso+//:-'
                       -mNMMMNdyssyso+/:.'
                   ':shmMMMMMMMMNMMNmo.
                  -hNMMMMMMMMMMMMMMMMd/'
                 .hNMMMMMMMMMMMMMMMMMMNy/.
                .yNMMMMMMMMMMMMMMMMMMMMMMd:
              .omMMMMMMMMMMMMMMMMMMMMNMMMMNo'
            .omMMMMMMMMMMMMMMMMMMMMMMMMMMMMMy.
           -dNMMMMMMMMMMMMMMMMMNNMMMMMNMMMMMMy'
          :dMMMMMMMMMMMMMMMMMMMNmNMMMMNNMMMMMN/
         .dMMMMMMMMMMMMMMMMMMMNmmMMMMMMMMMMMMMs'
         +NMMMMMMMMMMMMNmMMMMMNmNMMMMMMMMMMMMMy'
         -mMMMMMMMMMMMMMMMMMMMNNMMMMMMMMMMMMMMo'
         'hNMMMMMMMMMMMMMMMMMMMMMMMMMMMNNNMNNh.
          sNMMMMMMMMMMMMMMMMMMMMMMMMMMNNNNmh+.
          /NMMMMMMMMMMMMMMMMMNdmNMMMMMNNNm:
          -mMMMMMMMMMMMMMMNms-''/mMMMNddNm-
           oNMMMMMMMMMMMMd/'     +NMMNddmm:
           -mMMMMMMMMMMMN+'      'sNMMMNNmy-
            sNMMMMMMMMMNd.        'sNNMNNNmh-
            :NMMMMMMMMNm:          'yNNMMNNmy'
            'yNMMMMMMMNo'           .hNMMMNNm.
             .dMMMMMNNy'             -dNMMNNN:
              oNMMMNNm-               /NNMMNN/
              :NMMMMNh.                yNMMNms'
              :mMMMNN/                 -mMMMNy'
              'yNMmho'                  sNNmNNs.
            ''/mMMMmy'                  -mNMMMMNdhhy+'
          .yNNMMMMMNm+'                 /NMMMNNNmdy+-
           :hNNMMMNdd/'                 /dmNNdso+:.'`)
	fmt.Print("\n\nHammer Time\n\n")

	type result struct {
		prefix string
		err    error
	}
	results := make(chan result, len(cfg))
	var wg sync.WaitGroup
	for _, c := range cfg {
		wg.Add(1)
		cfg := integration.HammerConfig{
			LogCfg:     c,
			MMD:        *mmdFlag,
			LeafChain:  leafChain,
			LeafCert:   leafCert,
			CACert:     caCert,
			Signer:     signer,
			Servers:    *httpServersFlag,
			EPBias:     bias,
			Operations: *operationsFlag,
		}
		go func(cfg integration.HammerConfig) {
			defer wg.Done()
			err := integration.HammerCTLog(cfg)
			results <- result{prefix: cfg.LogCfg.Prefix, err: err}
		}(cfg)
	}
	wg.Wait()
	close(results)
	errCount := 0
	for e := range results {
		if e.err != nil {
			errCount++
			glog.Errorf("%s: %v", e.prefix, e.err)
		}
	}
	if errCount > 0 {
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"os"

	"github.com/apognu/vault/crypt"
	"github.com/apognu/vault/util"

	"gopkg.in/alecthomas/kingpin.v2"
)

func main() {
	app := kingpin.New("vault", "Simple encrypted data store")
	app.HelpFlag.Short('h')
	app.UsageTemplate(kingpin.CompactUsageTemplate)

	appInit := app.Command("init", "initiate the vault")

	appKey := app.Command("key", "vault key management")
	appKeyList := appKey.Command("list", "list all keys available in the vault")
	appKeyAdd := appKey.Command("add", "add a key that unlocks the vault")
	appKeyAddComment := appKeyAdd.Flag("comment", "description of this key").Short('c').Required().String()
	appKeyDelete := appKey.Command("delete", "delete a key from the vault")
	appKeyDeleteID := appKeyDelete.Arg("id", "ID of the key to delete").Required().Int()
	appKeyRotate := appKey.Command("rotate", "[EXPERIMENTAL] rotate the vault master key")

	appList := app.Command("list", "list all secrets")
	appListPath := appList.Arg("path", "secret path").Default("/").String()

	appShow := app.Command("show", "show all secrets")
	appShowPath := appShow.Arg("path", "secret path").Required().String()
	appShowPrint := appShow.Flag("print", "print 'password' attribute on console").Short('p').Bool()
	appShowClipboard := appShow.Flag("clip", "copy 'password' attribute into clipboard").Short('c').Bool()
	appShowClipAttr := appShow.Flag("clip-attributes", "attribute to copy to clipboard").Short('a').Default("").String()
	appShowWrite := appShow.Flag("write", "write file attributes on the filesystem").Short('w').Bool()
	appShowWriteFiles := appShow.Flag("file", "which file attributes to write").Short('f').Strings()

	appAdd := app.Command("add", "add a secret")
	appAddPath := appAdd.Arg("path", "secret path").Required().String()
	appAddAttrs := appAdd.Arg("attributes", "secret attributes").Required().StringMap()
	appAddGeneratorLength := appAdd.Flag("length", "length of generated passwords").Short('l').Default("16").Int()

	appEdit := app.Command("edit", "edit an existing secret")
	appEditPath := appEdit.Arg("path", "path to the secret to edit").Required().String()
	appEditDeletedAttrs := appEdit.Flag("delete", "attributes to delete from the secret").Short('d').Strings()
	appEditAttrs := appEdit.Arg("attributes", "secret attributes").StringMap()
	appEditGeneratorLength := appEdit.Flag("length", "length of generated passwords").Short('l').Default("16").Int()

	appDelete := app.Command("delete", "delete a secret")
	appDeletePath := appDelete.Arg("path", "secret path").Required().String()

	appGit := app.Command("git", "archive the store in a git repository")
	appGitClone := appGit.Command("clone", "clone an existing store repository")
	appGitCloneURL := appGitClone.Arg("url", "remote store repository URL").Required().String()
	appGitRemote := appGit.Command("remote", "set the remote git repository to push to")
	appGitRemoteURL := appGitRemote.Arg("url", "git repository URL").Required().String()
	appGitPush := appGit.Command("push", "push the state of the store")
	appGitPull := appGit.Command("pull", "pull the state of the store")

	appUnseal := app.Command("unseal", "unseal store until next reboot")
	appSeal := app.Command("seal", "seal store")

	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case appInit.FullCommand():
		crypt.InitVault()
	}

	util.AssertVaultExists()

	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case appKeyList.FullCommand():
		crypt.ListKeys()
	case appKeyAdd.FullCommand():
		crypt.AddKey(*appKeyAddComment)
	case appKeyDelete.FullCommand():
		crypt.DeleteKey(*appKeyDeleteID)
	case appKeyRotate.FullCommand():
		crypt.RotateKey()

	case appList.FullCommand():
		listSecrets(*appListPath)
	case appShow.FullCommand():
		showSecret(*appShowPath, *appShowPrint, *appShowClipboard, *appShowClipAttr, *appShowWrite, *appShowWriteFiles)
	case appAdd.FullCommand():
		addSecret(*appAddPath, *appAddAttrs, *appAddGeneratorLength, false, []string{})
	case appEdit.FullCommand():
		editSecret(*appEditPath, *appEditAttrs, *appEditDeletedAttrs, *appEditGeneratorLength)
	case appDelete.FullCommand():
		deleteSecret(*appDeletePath)

	case appGitClone.FullCommand():
		util.GitClone(*appGitCloneURL)
	case appGitRemote.FullCommand():
		util.GitRemote(*appGitRemoteURL)
	case appGitPush.FullCommand():
		util.GitPush()
	case appGitPull.FullCommand():
		util.GitPull()

	case appUnseal.FullCommand():
		crypt.Unseal()
	case appSeal.FullCommand():
		crypt.Seal(false)
	}
}
<commit_msg>Better help template.<commit_after>package main

import (
	"os"

	"github.com/apognu/vault/crypt"
	"github.com/apognu/vault/util"

	"gopkg.in/alecthomas/kingpin.v2"
)

func main() {
	app := kingpin.New("vault", "Simple encrypted data store")
	app.HelpFlag.Short('h')
	app.UsageTemplate(kingpin.SeparateOptionalFlagsUsageTemplate)

	appInit := app.Command("init", "initiate the vault")

	appKey := app.Command("key", "vault key management")
	appKeyList := appKey.Command("list", "list all keys available in the vault")
	appKeyAdd := appKey.Command("add", "add a key that unlocks the vault")
	appKeyAddComment := appKeyAdd.Flag("comment", "description of this key").Short('c').Required().String()
	appKeyDelete := appKey.Command("delete", "delete a key from the vault")
	appKeyDeleteID := appKeyDelete.Arg("id", "ID of the key to delete").Required().Int()
	appKeyRotate := appKey.Command("rotate", "[EXPERIMENTAL] rotate the vault master key")

	appList := app.Command("list", "list all secrets")
	appListPath := appList.Arg("path", "secret path").Default("/").String()

	appShow := app.Command("show", "show all secrets")
	appShowPath := appShow.Arg("path", "secret path").Required().String()
	appShowPrint := appShow.Flag("print", "print 'password' attribute on console").Short('p').Bool()
	appShowClipboard := appShow.Flag("clip", "copy 'password' attribute into clipboard").Short('c').Bool()
	appShowClipAttr := appShow.Flag("clip-attributes", "attribute to copy to clipboard").Short('a').Default("").String()
	appShowWrite := appShow.Flag("write", "write file attributes on the filesystem").Short('w').Bool()
	appShowWriteFiles := appShow.Flag("file", "which file attributes to write").Short('f').Strings()

	appAdd := app.Command("add", "add a secret")
	appAddPath := appAdd.Arg("path", "secret path").Required().String()
	appAddAttrs := appAdd.Arg("attributes", "secret attributes").Required().StringMap()
	appAddGeneratorLength := appAdd.Flag("length", "length of generated passwords").Short('l').Default("16").Int()

	appEdit := app.Command("edit", "edit an existing secret")
	appEditPath := appEdit.Arg("path", "path to the secret to edit").Required().String()
	appEditDeletedAttrs := appEdit.Flag("delete", "attributes to delete from the secret").Short('d').Strings()
	appEditAttrs := appEdit.Arg("attributes", "secret attributes").StringMap()
	appEditGeneratorLength := appEdit.Flag("length", "length of generated passwords").Short('l').Default("16").Int()

	appDelete := app.Command("delete", "delete a secret")
	appDeletePath := appDelete.Arg("path", "secret path").Required().String()

	appGit := app.Command("git", "archive the store in a git repository")
	appGitClone := appGit.Command("clone", "clone an existing store repository")
	appGitCloneURL := appGitClone.Arg("url", "remote store repository URL").Required().String()
	appGitRemote := appGit.Command("remote", "set the remote git repository to push to")
	appGitRemoteURL := appGitRemote.Arg("url", "git repository URL").Required().String()
	appGitPush := appGit.Command("push", "push the state of the store")
	appGitPull := appGit.Command("pull", "pull the state of the store")

	appUnseal := app.Command("unseal", "unseal store until next reboot")
	appSeal := app.Command("seal", "seal store")

	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case appInit.FullCommand():
		crypt.InitVault()
	}

	util.AssertVaultExists()

	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case appKeyList.FullCommand():
		crypt.ListKeys()
	case appKeyAdd.FullCommand():
		crypt.AddKey(*appKeyAddComment)
	case appKeyDelete.FullCommand():
		crypt.DeleteKey(*appKeyDeleteID)
	case appKeyRotate.FullCommand():
		crypt.RotateKey()

	case appList.FullCommand():
		listSecrets(*appListPath)
	case appShow.FullCommand():
		showSecret(*appShowPath, *appShowPrint, *appShowClipboard, *appShowClipAttr, *appShowWrite, *appShowWriteFiles)
	case appAdd.FullCommand():
		addSecret(*appAddPath, *appAddAttrs, *appAddGeneratorLength, false, []string{})
	case appEdit.FullCommand():
		editSecret(*appEditPath, *appEditAttrs, *appEditDeletedAttrs, *appEditGeneratorLength)
	case appDelete.FullCommand():
		deleteSecret(*appDeletePath)

	case appGitClone.FullCommand():
		util.GitClone(*appGitCloneURL)
	case appGitRemote.FullCommand():
		util.GitRemote(*appGitRemoteURL)
	case appGitPush.FullCommand():
		util.GitPush()
	case appGitPull.FullCommand():
		util.GitPull()

	case appUnseal.FullCommand():
		crypt.Unseal()
	case appSeal.FullCommand():
		crypt.Seal(false)
	}
}
<|endoftext|>


<commit_before>package interfaces

import (
	"database/sql"
	"fmt"
	"github.com/kendellfab/publish/domain"
	"log"
	"strings"
)

type DbUserRepo struct {
	db    *sql.DB
	cache *AuthorCache
}

func NewDbUserRepo(db *sql.DB) domain.UserRepo {
	userRepo := &DbUserRepo{db: db}
	ac, err := NewAuthorCache(25)
	if err != nil {
		log.Fatal(err)
	}
	userRepo.cache = ac
	userRepo.init()
	return userRepo
}

func (repo *DbUserRepo) init() {
	if _, err := repo.db.Exec(CREATE_USER); err != nil && !strings.Contains(err.Error(), domain.ALREADY_EXISTS) {
		log.Fatal(err)
	}
}

func (repo *DbUserRepo) Store(user *domain.User) error {
	insertStmt := "INSERT INTO user(name, email, hash, password, bio, token, role) VALUES(?, ?, ?, ?)"
	res, err := repo.db.Exec(insertStmt, user.Name, user.Email, user.Hash, user.Password, user.Bio, user.Token, user.Role)

	if err == nil {
		if id, idErr := res.LastInsertId(); idErr == nil {
			user.Id = id
		}
	}

	return err
}

func (repo *DbUserRepo) Update(user *domain.User) error {
	up := "UPDATE user SET name = ?, email = ?, hash = ?, bio = ?, token = ? WHERE id = ?;"
	_, err := repo.db.Exec(up, user.Name, user.Email, user.Hash, user.Bio, user.Token, user.Id)
	return err
}

func (repo *DbUserRepo) FindById(id string) (*domain.User, error) {
	if user, ok := repo.cache.Get(id); ok {
		return user, nil
	}
	row := repo.db.QueryRow("SELECT id, name, email, hash, password, bio, token, role FROM user WHERE id=?", id)
	user, err := repo.scanRow(row)
	if err != nil {
		return nil, err
	}
	repo.cache.Add(id, user)
	return user, nil
}

func (repo *DbUserRepo) FindByIdInt(id int64) (*domain.User, error) {
	if user, ok := repo.cache.Get(fmt.Sprintf("%d", id)); ok {
		return user, nil
	}
	row := repo.db.QueryRow("SELECT id, name, email, hash, password, bio, token, role FROM user WHERE id=?", id)
	user, err := repo.scanRow(row)
	if err != nil {
		return nil, err
	}
	repo.cache.Add(fmt.Sprintf("%d", id), user)
	return user, nil
}

func (repo *DbUserRepo) FindByEmail(email string) (*domain.User, error) {
	row := repo.db.QueryRow("SELECT id, name, email, hash, password, bio, token, role FROM user WHERE email=?", email)
	return repo.scanRow(row)
}

func (repo *DbUserRepo) FindAdmin() (*[]domain.User, error) {
	rows, rowError := repo.db.Query("SELECT id, name, email, salt, role FROM user WHERE role=?", domain.Admin)
	if rowError != nil {
		return nil, rowError
	}
	users := repo.scanUsers(rows)
	return &users, nil
}

func (repo *DbUserRepo) UpdatePassword(userId, password string) error {
	up := "UPDATE user SET password = ? WHERE id = ?;"
	_, err := repo.db.Exec(up, password, userId)
	return err
}

func (repo *DbUserRepo) scanRow(row *sql.Row) (*domain.User, error) {
	var user domain.User
	scanErr := row.Scan(&user.Id, &user.Name, &user.Email, &user.Hash, &user.Password, &user.Bio, &user.Token, &user.Role)
	if scanErr != nil {
		return nil, scanErr
	}
	return &user, nil
}

func (repo *DbUserRepo) scanUsers(rows *sql.Rows) []domain.User {
	fmt.Println("Scanning...")
	users := make([]domain.User, 0)
	for {
		var user domain.User
		scanErr := rows.Scan(&user.Id, &user.Name, &user.Email, &user.Role)
		if scanErr == nil {
			users = append(users, user)
		}
		if !rows.Next() {
			break
		}
	}
	return users
}
<commit_msg>Added proper parameter count to user insert.<commit_after>package interfaces

import (
	"database/sql"
	"fmt"
	"github.com/kendellfab/publish/domain"
	"log"
	"strings"
)

type DbUserRepo struct {
	db    *sql.DB
	cache *AuthorCache
}

func NewDbUserRepo(db *sql.DB) domain.UserRepo {
	userRepo := &DbUserRepo{db: db}
	ac, err := NewAuthorCache(25)
	if err != nil {
		log.Fatal(err)
	}
	userRepo.cache = ac
	userRepo.init()
	return userRepo
}

func (repo *DbUserRepo) init() {
	if _, err := repo.db.Exec(CREATE_USER); err != nil && !strings.Contains(err.Error(), domain.ALREADY_EXISTS) {
		log.Fatal(err)
	}
}

func (repo *DbUserRepo) Store(user *domain.User) error {
	insertStmt := "INSERT INTO user(name, email, hash, password, bio, token, role) VALUES(?, ?, ?, ?, ?, ?, ?)"
	res, err := repo.db.Exec(insertStmt, user.Name, user.Email, user.Hash, user.Password, user.Bio, user.Token, user.Role)

	if err == nil {
		if id, idErr := res.LastInsertId(); idErr == nil {
			user.Id = id
		}
	}

	return err
}

func (repo *DbUserRepo) Update(user *domain.User) error {
	up := "UPDATE user SET name = ?, email = ?, hash = ?, bio = ?, token = ? WHERE id = ?;"
	_, err := repo.db.Exec(up, user.Name, user.Email, user.Hash, user.Bio, user.Token, user.Id)
	return err
}

func (repo *DbUserRepo) FindById(id string) (*domain.User, error) {
	if user, ok := repo.cache.Get(id); ok {
		return user, nil
	}
	row := repo.db.QueryRow("SELECT id, name, email, hash, password, bio, token, role FROM user WHERE id=?", id)
	user, err := repo.scanRow(row)
	if err != nil {
		return nil, err
	}
	repo.cache.Add(id, user)
	return user, nil
}

func (repo *DbUserRepo) FindByIdInt(id int64) (*domain.User, error) {
	if user, ok := repo.cache.Get(fmt.Sprintf("%d", id)); ok {
		return user, nil
	}
	row := repo.db.QueryRow("SELECT id, name, email, hash, password, bio, token, role FROM user WHERE id=?", id)
	user, err := repo.scanRow(row)
	if err != nil {
		return nil, err
	}
	repo.cache.Add(fmt.Sprintf("%d", id), user)
	return user, nil
}

func (repo *DbUserRepo) FindByEmail(email string) (*domain.User, error) {
	row := repo.db.QueryRow("SELECT id, name, email, hash, password, bio, token, role FROM user WHERE email=?", email)
	return repo.scanRow(row)
}

func (repo *DbUserRepo) FindAdmin() (*[]domain.User, error) {
	rows, rowError := repo.db.Query("SELECT id, name, email, salt, role FROM user WHERE role=?", domain.Admin)
	if rowError != nil {
		return nil, rowError
	}
	users := repo.scanUsers(rows)
	return &users, nil
}

func (repo *DbUserRepo) UpdatePassword(userId, password string) error {
	up := "UPDATE user SET password = ? WHERE id = ?;"
	_, err := repo.db.Exec(up, password, userId)
	return err
}

func (repo *DbUserRepo) scanRow(row *sql.Row) (*domain.User, error) {
	var user domain.User
	scanErr := row.Scan(&user.Id, &user.Name, &user.Email, &user.Hash, &user.Password, &user.Bio, &user.Token, &user.Role)
	if scanErr != nil {
		return nil, scanErr
	}
	return &user, nil
}

func (repo *DbUserRepo) scanUsers(rows *sql.Rows) []domain.User {
	fmt.Println("Scanning...")
	users := make([]domain.User, 0)
	for {
		var user domain.User
		scanErr := rows.Scan(&user.Id, &user.Name, &user.Email, &user.Role)
		if scanErr == nil {
			users = append(users, user)
		}
		if !rows.Next() {
			break
		}
	}
	return users
}
<|endoftext|>


<commit_before>package gps

import (
	"fmt"
	"net/url"
	"path/filepath"

	"github.com/Masterminds/vcs"
)

type maybeSource interface {
	try(cachedir string, an ProjectAnalyzer) (source, error)
}

type maybeSources []maybeSource

type maybeGitSource struct {
	n   string
	url *url.URL
}

func (m maybeGitSource) try(cachedir string, an ProjectAnalyzer) (source, error) {
	path := filepath.Join(cachedir, "sources", sanitizer.Replace(m.url.String()))
	r, err := vcs.NewGitRepo(m.url.String(), path)
	if err != nil {
		return nil, err
	}

	src := &gitSource{
		baseVCSSource: baseVCSSource{
			an: an,
			dc: newMetaCache(),
			crepo: &repo{
				r:     r,
				rpath: path,
			},
		},
	}

	_, err = src.listVersions()
	if err != nil {
		return nil, err
		//} else if pm.ex.f&existsUpstream == existsUpstream {
		//return pm, nil
	}

	return src, nil
}

type maybeBzrSource struct {
	n   string
	url *url.URL
}

func (m maybeBzrSource) try(cachedir string, an ProjectAnalyzer) (source, error) {
	path := filepath.Join(cachedir, "sources", sanitizer.Replace(m.url.String()))
	r, err := vcs.NewBzrRepo(m.url.String(), path)
	if err != nil {
		return nil, err
	}
	if !r.Ping() {
		return nil, fmt.Errorf("Remote repository at %s does not exist, or is inaccessible", m.url.String())
	}

	return &bzrSource{
		baseVCSSource: baseVCSSource{
			an: an,
			dc: newMetaCache(),
			crepo: &repo{
				r:     r,
				rpath: path,
			},
		},
	}, nil
}

type maybeHgSource struct {
	n   string
	url *url.URL
}

func (m maybeHgSource) try(cachedir string, an ProjectAnalyzer) (source, error) {
	path := filepath.Join(cachedir, "sources", sanitizer.Replace(m.url.String()))
	r, err := vcs.NewHgRepo(m.url.String(), path)
	if err != nil {
		return nil, err
	}
	if !r.Ping() {
		return nil, fmt.Errorf("Remote repository at %s does not exist, or is inaccessible", m.url.String())
	}

	return &hgSource{
		baseVCSSource: baseVCSSource{
			an: an,
			dc: newMetaCache(),
			crepo: &repo{
				r:     r,
				rpath: path,
			},
		},
	}, nil
}
<commit_msg>Add sourceFailures to hold multiple try() fails<commit_after>package gps

import (
	"bytes"
	"fmt"
	"net/url"
	"path/filepath"

	"github.com/Masterminds/vcs"
)

type maybeSource interface {
	try(cachedir string, an ProjectAnalyzer) (source, error)
}

type maybeSources []maybeSource

func (mbs maybeSources) try(cachedir string, an ProjectAnalyzer) (source, error) {
	var e sourceFailures
	for _, mb := range mbs {
		src, err := mb.try(cachedir, an)
		if err == nil {
			return src, nil
		}
		e = append(e, err)
	}
	return nil, e
}

type sourceFailures []error

func (sf sourceFailures) Error() string {
	var buf bytes.Buffer
	fmt.Fprintf(&buf, "No valid source could be created:\n")
	for _, e := range sf {
		fmt.Fprintf(&buf, "\t%s", e.Error())
	}

	return buf.String()
}

type maybeGitSource struct {
	url *url.URL
}

func (m maybeGitSource) try(cachedir string, an ProjectAnalyzer) (source, error) {
	path := filepath.Join(cachedir, "sources", sanitizer.Replace(m.url.String()))
	r, err := vcs.NewGitRepo(m.url.String(), path)
	if err != nil {
		return nil, err
	}

	src := &gitSource{
		baseVCSSource: baseVCSSource{
			an: an,
			dc: newMetaCache(),
			crepo: &repo{
				r:     r,
				rpath: path,
			},
		},
	}

	_, err = src.listVersions()
	if err != nil {
		return nil, err
		//} else if pm.ex.f&existsUpstream == existsUpstream {
		//return pm, nil
	}

	return src, nil
}

type maybeBzrSource struct {
	url *url.URL
}

func (m maybeBzrSource) try(cachedir string, an ProjectAnalyzer) (source, error) {
	path := filepath.Join(cachedir, "sources", sanitizer.Replace(m.url.String()))
	r, err := vcs.NewBzrRepo(m.url.String(), path)
	if err != nil {
		return nil, err
	}
	if !r.Ping() {
		return nil, fmt.Errorf("Remote repository at %s does not exist, or is inaccessible", m.url.String())
	}

	return &bzrSource{
		baseVCSSource: baseVCSSource{
			an: an,
			dc: newMetaCache(),
			crepo: &repo{
				r:     r,
				rpath: path,
			},
		},
	}, nil
}

type maybeHgSource struct {
	url *url.URL
}

func (m maybeHgSource) try(cachedir string, an ProjectAnalyzer) (source, error) {
	path := filepath.Join(cachedir, "sources", sanitizer.Replace(m.url.String()))
	r, err := vcs.NewHgRepo(m.url.String(), path)
	if err != nil {
		return nil, err
	}
	if !r.Ping() {
		return nil, fmt.Errorf("Remote repository at %s does not exist, or is inaccessible", m.url.String())
	}

	return &hgSource{
		baseVCSSource: baseVCSSource{
			an: an,
			dc: newMetaCache(),
			crepo: &repo{
				r:     r,
				rpath: path,
			},
		},
	}, nil
}
<|endoftext|>