<commit_before>package main

import (
	".."
	"../filters"
	"fmt"
	"os"
)

func main() {
	gitmedia.SetupDebugging()

	cleaned, err := gitmediafilters.Clean(os.Stdin)
	if err != nil {
		fmt.Println("Error cleaning asset")
		panic(err)
	}
	defer cleaned.Close()

	tmpfile := cleaned.File.Name()
	mediafile := gitmedia.LocalMediaPath(cleaned.Sha)
	if stat, _ := os.Stat(mediafile); stat != nil {
		if stat.Size() != cleaned.Size {
			gitmedia.Panic(nil, "Files don't match:\n%s\n%s", mediafile, tmpfile)
		}
		gitmedia.Debug("%s exists", mediafile)
	} else {
		if err := os.Rename(tmpfile, mediafile); err != nil {
			gitmedia.Panic(err, "Unable to move %s to %s\n", tmpfile, mediafile)
		}
		gitmedia.Debug("Writing %s", mediafile)
	}

	gitmedia.Encode(os.Stdout, cleaned.Sha)
}
<commit_msg>アーア アアアア アーアー<commit_after>package main

import (
	".."
	"../filters"
	"../queuedir"
	"fmt"
	"os"
	"path/filepath"
)

func main() {
	gitmedia.SetupDebugging()
	qdir := queuedir.New(filepath.Join(gitmedia.LocalMediaDir, "queue"))
	cleanqueue, err := qdir.Queue("clean")
	if err != nil {
		fmt.Println("Error setting up queue")
		panic(err)
	}

	cleaned, err := gitmediafilters.Clean(os.Stdin)
	if err != nil {
		fmt.Println("Error cleaning asset")
		panic(err)
	}
	defer cleaned.Close()

	tmpfile := cleaned.File.Name()
	mediafile := gitmedia.LocalMediaPath(cleaned.Sha)
	if stat, _ := os.Stat(mediafile); stat != nil {
		if stat.Size() != cleaned.Size {
			gitmedia.Panic(nil, "Files don't match:\n%s\n%s", mediafile, tmpfile)
		}
		gitmedia.Debug("%s exists", mediafile)
	} else {
		if err := os.Rename(tmpfile, mediafile); err != nil {
			gitmedia.Panic(err, "Unable to move %s to %s\n", tmpfile, mediafile)
		}
		if _, err := cleanqueue.AddString(cleaned.Sha); err != nil {
			gitmedia.Panic(err, "Unable to add %s to queue", cleaned.Sha)
		}
		gitmedia.Debug("Writing %s", mediafile)
	}

	gitmedia.Encode(os.Stdout, cleaned.Sha)
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strconv"
	"time"

	"github.com/Songmu/timeout"

	"code.google.com/p/getopt"
)

func main() {
	optKillAfter := getopt.StringLong("kill-after", 'k', "", "help message for f")
	optSig := getopt.StringLong("signal", 's', "", "help message for long")
	p := getopt.BoolLong("preserve-status", 0, "help message for bool")

	opts := getopt.CommandLine
	opts.Parse(os.Args)

	rest := opts.Args()
	if len(rest) < 2 {
		opts.PrintUsage(os.Stderr)
		os.Exit(1)
	}

	var err error
	killAfter := float64(0)
	if *optKillAfter != "" {
		killAfter, err = parseDuration(*optKillAfter)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			os.Exit(125)
		}
	}

	var sig os.Signal
	if *optSig != "" {
		sig, err = parseSignal(*optSig)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			os.Exit(125)
		}
	}

	dur, err := parseDuration(rest[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(125)
	}

	cmd := exec.Command(rest[1], rest[2:]...)

	tio := &timeout.Timeout{
		Duration:  time.Duration(dur * float64(time.Second)),
		Cmd:       cmd,
		KillAfter: time.Duration(killAfter * float64(time.Second)),
		Signal:    sig,
	}
	exit := tio.RunSimple(*p)
	os.Exit(exit)
}

var durRe = regexp.MustCompile(`^([-0-9e.]+)([smhd])?$`)

func parseDuration(durStr string) (float64, error) {
	matches := durRe.FindStringSubmatch(durStr)
	if len(matches) == 0 {
		return 0, fmt.Errorf("duration format invalid: %s", durStr)
	}

	base, err := strconv.ParseFloat(matches[1], 64)
	if err != nil {
		return 0, fmt.Errorf("invalid time interval `%s`", durStr)
	}
	switch matches[2] {
	case "", "s":
		return base, nil
	case "m":
		return base * 60, nil
	case "h":
		return base * 60 * 60, nil
	case "d":
		return base * 60 * 60 * 24, nil
	default:
		return 0, fmt.Errorf("invalid time interval `%s`", durStr)
	}
}
<commit_msg>fix deps<commit_after>package main

import (
	"fmt"
	"os"
	"os/exec"
	"regexp"
	"strconv"
	"time"

	"github.com/Songmu/timeout"
	"github.com/pborman/getopt"
)

func main() {
	optKillAfter := getopt.StringLong("kill-after", 'k', "", "help message for f")
	optSig := getopt.StringLong("signal", 's', "", "help message for long")
	p := getopt.BoolLong("preserve-status", 0, "help message for bool")

	opts := getopt.CommandLine
	opts.Parse(os.Args)

	rest := opts.Args()
	if len(rest) < 2 {
		opts.PrintUsage(os.Stderr)
		os.Exit(1)
	}

	var err error
	killAfter := float64(0)
	if *optKillAfter != "" {
		killAfter, err = parseDuration(*optKillAfter)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			os.Exit(125)
		}
	}

	var sig os.Signal
	if *optSig != "" {
		sig, err = parseSignal(*optSig)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			os.Exit(125)
		}
	}

	dur, err := parseDuration(rest[0])
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(125)
	}

	cmd := exec.Command(rest[1], rest[2:]...)

	tio := &timeout.Timeout{
		Duration:  time.Duration(dur * float64(time.Second)),
		Cmd:       cmd,
		KillAfter: time.Duration(killAfter * float64(time.Second)),
		Signal:    sig,
	}
	exit := tio.RunSimple(*p)
	os.Exit(exit)
}

var durRe = regexp.MustCompile(`^([-0-9e.]+)([smhd])?$`)

func parseDuration(durStr string) (float64, error) {
	matches := durRe.FindStringSubmatch(durStr)
	if len(matches) == 0 {
		return 0, fmt.Errorf("duration format invalid: %s", durStr)
	}

	base, err := strconv.ParseFloat(matches[1], 64)
	if err != nil {
		return 0, fmt.Errorf("invalid time interval `%s`", durStr)
	}
	switch matches[2] {
	case "", "s":
		return base, nil
	case "m":
		return base * 60, nil
	case "h":
		return base * 60 * 60, nil
	case "d":
		return base * 60 * 60 * 24, nil
	default:
		return 0, fmt.Errorf("invalid time interval `%s`", durStr)
	}
}
<|endoftext|>


<commit_before>package main

// ke: {"notest":true}

import (
	"log"
	"path/filepath"

	"strings"

	"fmt"

	"golang.org/x/net/context"
	"golang.org/x/tools/cover"
	"kego.io/cmd/gotests/scanner"
	"kego.io/cmd/gotests/tester"
	"kego.io/process/packages"
)

var baseDir string

func excludeWrap(profiles []*cover.Profile) error {
	source, err := scanner.Get(baseDir)
	if err != nil {
		return err
	}
	m := map[string]*cover.Profile{}
	for _, p := range profiles {
		m[p.FileName] = p
	}

	for _, w := range source.Wraps {
		p, ok := m[w.File]
		if !ok {
			continue
		}
		for _, b := range p.Blocks {
			if b.StartLine <= w.Line && b.EndLine >= w.Line && b.Count != 1 {
				b.Count = 1
				fmt.Printf("Excluding kerr.Wrap from %s:%d\n", w.File, w.Line)
			}
		}
	}
	return err
}
func excludeGenerated(profiles []*cover.Profile) error {
	for _, p := range profiles {
		if strings.HasSuffix(p.FileName, "/generated.go") {
			fmt.Println("Excluding", p.FileName)
			// summarize the original Profile
			statements := 0
			lastLine := 0
			lastCol := 0
			for _, pb := range p.Blocks {
				statements += pb.NumStmt
				if pb.EndLine >= lastLine {
					lastLine = pb.EndLine
					if pb.EndCol >= lastCol {
						lastCol = pb.EndCol
					}
				}
			}
			// overwrite with a single block
			p.Blocks = []cover.ProfileBlock{
				cover.ProfileBlock{
					StartLine: 0,
					StartCol:  0,
					EndLine:   lastLine,
					EndCol:    lastCol,
					NumStmt:   statements,
					Count:     1,
				},
			}
		}
	}

	return nil
}

func main() {
	var err error
	baseDir, err = packages.GetDirFromPackage(context.Background(), "kego.io")
	if err != nil {
		log.Fatal(err)
	}
	profiles, err := tester.Get(baseDir)
	if err != nil {
		log.Fatal(err)
	}
	err = excludeGenerated(profiles)
	if err != nil {
		log.Fatal(err)
	}
	err = excludeWrap(profiles)
	if err != nil {
		log.Fatal(err)
	}
	err = tester.Save(profiles, filepath.Join(baseDir, "coverage.out"))
	if err != nil {
		log.Fatal(err)
	}
}
<commit_msg>Gotests command excludes kerr.Wrap fix save<commit_after>package main

// ke: {"notest":true}

import (
	"log"
	"path/filepath"

	"strings"

	"fmt"

	"golang.org/x/net/context"
	"golang.org/x/tools/cover"
	"kego.io/cmd/gotests/scanner"
	"kego.io/cmd/gotests/tester"
	"kego.io/process/packages"
)

var baseDir string

func excludeWrap(profiles []*cover.Profile) error {
	source, err := scanner.Get(baseDir)
	if err != nil {
		return err
	}
	m := map[string]*cover.Profile{}
	for _, p := range profiles {
		m[p.FileName] = p
	}

	for _, w := range source.Wraps {
		p, ok := m[w.File]
		if !ok {
			continue
		}
		for i, b := range p.Blocks {
			if b.StartLine <= w.Line && b.EndLine >= w.Line && b.Count != 1 {
				b.Count = 1
				p.Blocks[i] = b
				fmt.Printf("Excluding kerr.Wrap from %s:%d\n", w.File, w.Line)
			}
		}
	}
	return err
}
func excludeGenerated(profiles []*cover.Profile) error {
	for _, p := range profiles {
		if strings.HasSuffix(p.FileName, "/generated.go") {
			fmt.Println("Excluding", p.FileName)
			// summarize the original Profile
			statements := 0
			lastLine := 0
			lastCol := 0
			for _, pb := range p.Blocks {
				statements += pb.NumStmt
				if pb.EndLine >= lastLine {
					lastLine = pb.EndLine
					if pb.EndCol >= lastCol {
						lastCol = pb.EndCol
					}
				}
			}
			// overwrite with a single block
			p.Blocks = []cover.ProfileBlock{
				cover.ProfileBlock{
					StartLine: 0,
					StartCol:  0,
					EndLine:   lastLine,
					EndCol:    lastCol,
					NumStmt:   statements,
					Count:     1,
				},
			}
		}
	}

	return nil
}

func main() {
	var err error
	baseDir, err = packages.GetDirFromPackage(context.Background(), "kego.io")
	if err != nil {
		log.Fatal(err)
	}
	profiles, err := tester.Get(baseDir)
	if err != nil {
		log.Fatal(err)
	}
	err = excludeGenerated(profiles)
	if err != nil {
		log.Fatal(err)
	}
	err = excludeWrap(profiles)
	if err != nil {
		log.Fatal(err)
	}
	err = tester.Save(profiles, filepath.Join(baseDir, "coverage.out"))
	if err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>/*
Copyright The Helm Authors.
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 main

import (
	"bytes"
	"io"

	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

const completionDesc = `
Generate autocompletions script for Helm for the specified shell (bash or zsh).

This command can generate shell autocompletions. e.g.

	$ helm completion bash

Can be sourced as such

	$ source <(helm completion bash)
`

var (
	completionShells = map[string]func(out io.Writer, cmd *cobra.Command) error{
		"bash": runCompletionBash,
		"zsh":  runCompletionZsh,
	}
)

func newCompletionCmd(out io.Writer) *cobra.Command {
	shells := []string{}
	for s := range completionShells {
		shells = append(shells, s)
	}

	cmd := &cobra.Command{
		Use:   "completion SHELL",
		Short: "Generate autocompletions script for the specified shell (bash or zsh)",
		Long:  completionDesc,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runCompletion(out, cmd, args)
		},
		ValidArgs: shells,
	}

	return cmd
}

func runCompletion(out io.Writer, cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return errors.New("shell not specified")
	}
	if len(args) > 1 {
		return errors.New("too many arguments, expected only the shell type")
	}
	run, found := completionShells[args[0]]
	if !found {
		return errors.Errorf("unsupported shell type %q", args[0])
	}

	return run(out, cmd)
}

func runCompletionBash(out io.Writer, cmd *cobra.Command) error {
	return cmd.Root().GenBashCompletion(out)
}

func runCompletionZsh(out io.Writer, cmd *cobra.Command) error {
	zshInitialization := `#compdef helm

__helm_bash_source() {
	alias shopt=':'
	alias _expand=_bash_expand
	alias _complete=_bash_comp
	emulate -L sh
	setopt kshglob noshglob braceexpand
	source "$@"
}
__helm_type() {
	# -t is not supported by zsh
	if [ "$1" == "-t" ]; then
		shift
		# fake Bash 4 to disable "complete -o nospace". Instead
		# "compopt +-o nospace" is used in the code to toggle trailing
		# spaces. We don't support that, but leave trailing spaces on
		# all the time
		if [ "$1" = "__helm_compopt" ]; then
			echo builtin
			return 0
		fi
	fi
	type "$@"
}
__helm_compgen() {
	local completions w
	completions=( $(compgen "$@") ) || return $?
	# filter by given word as prefix
	while [[ "$1" = -* && "$1" != -- ]]; do
		shift
		shift
	done
	if [[ "$1" == -- ]]; then
		shift
	fi
	for w in "${completions[@]}"; do
		if [[ "${w}" = "$1"* ]]; then
			echo "${w}"
		fi
	done
}
__helm_compopt() {
	true # don't do anything. Not supported by bashcompinit in zsh
}
__helm_declare() {
	if [ "$1" == "-F" ]; then
		whence -w "$@"
	else
		builtin declare "$@"
	fi
}
__helm_ltrim_colon_completions()
{
	if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then
		# Remove colon-word prefix from COMPREPLY items
		local colon_word=${1%${1##*:}}
		local i=${#COMPREPLY[*]}
		while [[ $((--i)) -ge 0 ]]; do
			COMPREPLY[$i]=${COMPREPLY[$i]#"$colon_word"}
		done
	fi
}
__helm_get_comp_words_by_ref() {
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[${COMP_CWORD}-1]}"
	words=("${COMP_WORDS[@]}")
	cword=("${COMP_CWORD[@]}")
}
__helm_filedir() {
	local RET OLD_IFS w qw
	__debug "_filedir $@ cur=$cur"
	if [[ "$1" = \~* ]]; then
		# somehow does not work. Maybe, zsh does not call this at all
		eval echo "$1"
		return 0
	fi
	OLD_IFS="$IFS"
	IFS=$'\n'
	if [ "$1" = "-d" ]; then
		shift
		RET=( $(compgen -d) )
	else
		RET=( $(compgen -f) )
	fi
	IFS="$OLD_IFS"
	IFS="," __debug "RET=${RET[@]} len=${#RET[@]}"
	for w in ${RET[@]}; do
		if [[ ! "${w}" = "${cur}"* ]]; then
			continue
		fi
		if eval "[[ \"\${w}\" = *.$1 || -d \"\${w}\" ]]"; then
			qw="$(__helm_quote "${w}")"
			if [ -d "${w}" ]; then
				COMPREPLY+=("${qw}/")
			else
				COMPREPLY+=("${qw}")
			fi
		fi
	done
}
__helm_quote() {
	if [[ $1 == \'* || $1 == \"* ]]; then
		# Leave out first character
		printf %q "${1:1}"
	else
		printf %q "$1"
	fi
}
autoload -U +X bashcompinit && bashcompinit
# use word boundary patterns for BSD or GNU sed
LWORD='[[:<:]]'
RWORD='[[:>:]]'
if sed --help 2>&1 | grep -q 'GNU\|BusyBox'; then
	LWORD='\<'
	RWORD='\>'
fi
__helm_convert_bash_to_zsh() {
	sed \
	-e 's/declare -F/whence -w/' \
	-e 's/_get_comp_words_by_ref "\$@"/_get_comp_words_by_ref "\$*"/' \
	-e 's/local \([a-zA-Z0-9_]*\)=/local \1; \1=/' \
	-e 's/flags+=("\(--.*\)=")/flags+=("\1"); two_word_flags+=("\1")/' \
	-e 's/must_have_one_flag+=("\(--.*\)=")/must_have_one_flag+=("\1")/' \
	-e "s/${LWORD}_filedir${RWORD}/__helm_filedir/g" \
	-e "s/${LWORD}_get_comp_words_by_ref${RWORD}/__helm_get_comp_words_by_ref/g" \
	-e "s/${LWORD}__ltrim_colon_completions${RWORD}/__helm_ltrim_colon_completions/g" \
	-e "s/${LWORD}compgen${RWORD}/__helm_compgen/g" \
	-e "s/${LWORD}compopt${RWORD}/__helm_compopt/g" \
	-e "s/${LWORD}declare${RWORD}/__helm_declare/g" \
	-e "s/\\\$(type${RWORD}/\$(__helm_type/g" \
	-e 's/aliashash\["\(.\{1,\}\)"\]/aliashash[\1]/g' \
	<<'BASH_COMPLETION_EOF'
`
	out.Write([]byte(zshInitialization))

	buf := new(bytes.Buffer)
	cmd.Root().GenBashCompletion(buf)
	out.Write(buf.Bytes())

	zshTail := `
BASH_COMPLETION_EOF
}
__helm_bash_source <(__helm_convert_bash_to_zsh)
`
	out.Write([]byte(zshTail))
	return nil
}
<commit_msg>fix(completion): --flag=val breaks zsh completion<commit_after>/*
Copyright The Helm Authors.
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 main

import (
	"bytes"
	"io"

	"github.com/pkg/errors"
	"github.com/spf13/cobra"
)

const completionDesc = `
Generate autocompletions script for Helm for the specified shell (bash or zsh).

This command can generate shell autocompletions. e.g.

	$ helm completion bash

Can be sourced as such

	$ source <(helm completion bash)
`

var (
	completionShells = map[string]func(out io.Writer, cmd *cobra.Command) error{
		"bash": runCompletionBash,
		"zsh":  runCompletionZsh,
	}
)

func newCompletionCmd(out io.Writer) *cobra.Command {
	shells := []string{}
	for s := range completionShells {
		shells = append(shells, s)
	}

	cmd := &cobra.Command{
		Use:   "completion SHELL",
		Short: "Generate autocompletions script for the specified shell (bash or zsh)",
		Long:  completionDesc,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runCompletion(out, cmd, args)
		},
		ValidArgs: shells,
	}

	return cmd
}

func runCompletion(out io.Writer, cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return errors.New("shell not specified")
	}
	if len(args) > 1 {
		return errors.New("too many arguments, expected only the shell type")
	}
	run, found := completionShells[args[0]]
	if !found {
		return errors.Errorf("unsupported shell type %q", args[0])
	}

	return run(out, cmd)
}

func runCompletionBash(out io.Writer, cmd *cobra.Command) error {
	return cmd.Root().GenBashCompletion(out)
}

func runCompletionZsh(out io.Writer, cmd *cobra.Command) error {
	zshInitialization := `#compdef helm

__helm_bash_source() {
	alias shopt=':'
	alias _expand=_bash_expand
	alias _complete=_bash_comp
	emulate -L sh
	setopt kshglob noshglob braceexpand
	source "$@"
}
__helm_type() {
	# -t is not supported by zsh
	if [ "$1" == "-t" ]; then
		shift
		# fake Bash 4 to disable "complete -o nospace". Instead
		# "compopt +-o nospace" is used in the code to toggle trailing
		# spaces. We don't support that, but leave trailing spaces on
		# all the time
		if [ "$1" = "__helm_compopt" ]; then
			echo builtin
			return 0
		fi
	fi
	type "$@"
}
__helm_compgen() {
	local completions w
	completions=( $(compgen "$@") ) || return $?
	# filter by given word as prefix
	while [[ "$1" = -* && "$1" != -- ]]; do
		shift
		shift
	done
	if [[ "$1" == -- ]]; then
		shift
	fi
	for w in "${completions[@]}"; do
		if [[ "${w}" = "$1"* ]]; then
			echo "${w}"
		fi
	done
}
__helm_compopt() {
	true # don't do anything. Not supported by bashcompinit in zsh
}
__helm_ltrim_colon_completions()
{
	if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then
		# Remove colon-word prefix from COMPREPLY items
		local colon_word=${1%${1##*:}}
		local i=${#COMPREPLY[*]}
		while [[ $((--i)) -ge 0 ]]; do
			COMPREPLY[$i]=${COMPREPLY[$i]#"$colon_word"}
		done
	fi
}
__helm_get_comp_words_by_ref() {
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[${COMP_CWORD}-1]}"
	words=("${COMP_WORDS[@]}")
	cword=("${COMP_CWORD[@]}")
}
__helm_filedir() {
	local RET OLD_IFS w qw
	__debug "_filedir $@ cur=$cur"
	if [[ "$1" = \~* ]]; then
		# somehow does not work. Maybe, zsh does not call this at all
		eval echo "$1"
		return 0
	fi
	OLD_IFS="$IFS"
	IFS=$'\n'
	if [ "$1" = "-d" ]; then
		shift
		RET=( $(compgen -d) )
	else
		RET=( $(compgen -f) )
	fi
	IFS="$OLD_IFS"
	IFS="," __debug "RET=${RET[@]} len=${#RET[@]}"
	for w in ${RET[@]}; do
		if [[ ! "${w}" = "${cur}"* ]]; then
			continue
		fi
		if eval "[[ \"\${w}\" = *.$1 || -d \"\${w}\" ]]"; then
			qw="$(__helm_quote "${w}")"
			if [ -d "${w}" ]; then
				COMPREPLY+=("${qw}/")
			else
				COMPREPLY+=("${qw}")
			fi
		fi
	done
}
__helm_quote() {
	if [[ $1 == \'* || $1 == \"* ]]; then
		# Leave out first character
		printf %q "${1:1}"
	else
		printf %q "$1"
	fi
}
autoload -U +X bashcompinit && bashcompinit
# use word boundary patterns for BSD or GNU sed
LWORD='[[:<:]]'
RWORD='[[:>:]]'
if sed --help 2>&1 | grep -q 'GNU\|BusyBox'; then
	LWORD='\<'
	RWORD='\>'
fi
__helm_convert_bash_to_zsh() {
	sed \
	-e 's/declare -F/whence -w/' \
	-e 's/_get_comp_words_by_ref "\$@"/_get_comp_words_by_ref "\$*"/' \
	-e 's/local \([a-zA-Z0-9_]*\)=/local \1; \1=/' \
	-e 's/flags+=("\(--.*\)=")/flags+=("\1"); two_word_flags+=("\1")/' \
	-e 's/must_have_one_flag+=("\(--.*\)=")/must_have_one_flag+=("\1")/' \
	-e "s/${LWORD}_filedir${RWORD}/__helm_filedir/g" \
	-e "s/${LWORD}_get_comp_words_by_ref${RWORD}/__helm_get_comp_words_by_ref/g" \
	-e "s/${LWORD}__ltrim_colon_completions${RWORD}/__helm_ltrim_colon_completions/g" \
	-e "s/${LWORD}compgen${RWORD}/__helm_compgen/g" \
	-e "s/${LWORD}compopt${RWORD}/__helm_compopt/g" \
	-e "s/${LWORD}declare${RWORD}/builtin declare/g" \
	-e "s/\\\$(type${RWORD}/\$(__helm_type/g" \
	-e 's/aliashash\["\(.\{1,\}\)"\]/aliashash[\1]/g' \
	<<'BASH_COMPLETION_EOF'
`
	out.Write([]byte(zshInitialization))

	buf := new(bytes.Buffer)
	cmd.Root().GenBashCompletion(buf)
	out.Write(buf.Bytes())

	zshTail := `
BASH_COMPLETION_EOF
}
__helm_bash_source <(__helm_convert_bash_to_zsh)
`
	out.Write([]byte(zshTail))
	return nil
}
<|endoftext|>


<commit_before>/*
Copyright 2016 The Kubernetes Authors All rights reserved.
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 main

import (
	"bytes"
	"fmt"
	"io"

	"github.com/spf13/cobra"
)

const completionDesc = `
Generate autocompletions script for Helm for the specified shell (bash or zsh).

This command can generate shell autocompletions. e.g.

	$ helm completion bash

Can be sourced as such

	$ source <(helm completion bash)
`

var (
	completionShells = map[string]func(out io.Writer, cmd *cobra.Command) error{
		"bash": runCompletionBash,
		"zsh":  runCompletionZsh,
	}
)

func newCompletionCmd(out io.Writer) *cobra.Command {
	shells := []string{}
	for s := range completionShells {
		shells = append(shells, s)
	}

	cmd := &cobra.Command{
		Use:   "completion SHELL",
		Short: "Generate autocompletions script for the specified shell (bash or zsh)",
		Long:  completionDesc,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runCompletion(out, cmd, args)
		},
		ValidArgs: shells,
	}

	return cmd
}

func runCompletion(out io.Writer, cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return fmt.Errorf("shell not specified")
	}
	if len(args) > 1 {
		return fmt.Errorf("too many arguments, expected only the shell type")
	}
	run, found := completionShells[args[0]]
	if !found {
		return fmt.Errorf("unsupported shell type %q", args[0])
	}

	return run(out, cmd)
}

func runCompletionBash(out io.Writer, cmd *cobra.Command) error {
	return cmd.Root().GenBashCompletion(out)
}

func runCompletionZsh(out io.Writer, cmd *cobra.Command) error {
	zshInitialization := `
__helm_bash_source() {
	alias shopt=':'
	alias _expand=_bash_expand
	alias _complete=_bash_comp
	emulate -L sh
	setopt kshglob noshglob braceexpand
	source "$@"
}
__helm_type() {
	# -t is not supported by zsh
	if [ "$1" == "-t" ]; then
		shift
		# fake Bash 4 to disable "complete -o nospace". Instead
		# "compopt +-o nospace" is used in the code to toggle trailing
		# spaces. We don't support that, but leave trailing spaces on
		# all the time
		if [ "$1" = "__helm_compopt" ]; then
			echo builtin
			return 0
		fi
	fi
	type "$@"
}
__helm_compgen() {
	local completions w
	completions=( $(compgen "$@") ) || return $?
	# filter by given word as prefix
	while [[ "$1" = -* && "$1" != -- ]]; do
		shift
		shift
	done
	if [[ "$1" == -- ]]; then
		shift
	fi
	for w in "${completions[@]}"; do
		if [[ "${w}" = "$1"* ]]; then
			echo "${w}"
		fi
	done
}
__helm_compopt() {
	true # don't do anything. Not supported by bashcompinit in zsh
}
__helm_declare() {
	if [ "$1" == "-F" ]; then
		whence -w "$@"
	else
		builtin declare "$@"
	fi
}
__helm_ltrim_colon_completions()
{
	if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then
		# Remove colon-word prefix from COMPREPLY items
		local colon_word=${1%${1##*:}}
		local i=${#COMPREPLY[*]}
		while [[ $((--i)) -ge 0 ]]; do
			COMPREPLY[$i]=${COMPREPLY[$i]#"$colon_word"}
		done
	fi
}
__helm_get_comp_words_by_ref() {
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[${COMP_CWORD}-1]}"
	words=("${COMP_WORDS[@]}")
	cword=("${COMP_CWORD[@]}")
}
__helm_filedir() {
	local RET OLD_IFS w qw
	__debug "_filedir $@ cur=$cur"
	if [[ "$1" = \~* ]]; then
		# somehow does not work. Maybe, zsh does not call this at all
		eval echo "$1"
		return 0
	fi
	OLD_IFS="$IFS"
	IFS=$'\n'
	if [ "$1" = "-d" ]; then
		shift
		RET=( $(compgen -d) )
	else
		RET=( $(compgen -f) )
	fi
	IFS="$OLD_IFS"
	IFS="," __debug "RET=${RET[@]} len=${#RET[@]}"
	for w in ${RET[@]}; do
		if [[ ! "${w}" = "${cur}"* ]]; then
			continue
		fi
		if eval "[[ \"\${w}\" = *.$1 || -d \"\${w}\" ]]"; then
			qw="$(__helm_quote "${w}")"
			if [ -d "${w}" ]; then
				COMPREPLY+=("${qw}/")
			else
				COMPREPLY+=("${qw}")
			fi
		fi
	done
}
__helm_quote() {
	if [[ $1 == \'* || $1 == \"* ]]; then
		# Leave out first character
		printf %q "${1:1}"
	else
		printf %q "$1"
	fi
}
autoload -U +X bashcompinit && bashcompinit
# use word boundary patterns for BSD or GNU sed
LWORD='[[:<:]]'
RWORD='[[:>:]]'
if sed --help 2>&1 | grep -q GNU; then
	LWORD='\<'
	RWORD='\>'
fi
__helm_convert_bash_to_zsh() {
	sed \
	-e 's/declare -F/whence -w/' \
	-e 's/_get_comp_words_by_ref "\$@"/_get_comp_words_by_ref "\$*"/' \
	-e 's/local \([a-zA-Z0-9_]*\)=/local \1; \1=/' \
	-e 's/flags+=("\(--.*\)=")/flags+=("\1"); two_word_flags+=("\1")/' \
	-e 's/must_have_one_flag+=("\(--.*\)=")/must_have_one_flag+=("\1")/' \
	-e "s/${LWORD}_filedir${RWORD}/__helm_filedir/g" \
	-e "s/${LWORD}_get_comp_words_by_ref${RWORD}/__helm_get_comp_words_by_ref/g" \
	-e "s/${LWORD}__ltrim_colon_completions${RWORD}/__helm_ltrim_colon_completions/g" \
	-e "s/${LWORD}compgen${RWORD}/__helm_compgen/g" \
	-e "s/${LWORD}compopt${RWORD}/__helm_compopt/g" \
	-e "s/${LWORD}declare${RWORD}/__helm_declare/g" \
	-e "s/\\\$(type${RWORD}/\$(__helm_type/g" \
	<<'BASH_COMPLETION_EOF'
`
	out.Write([]byte(zshInitialization))

	buf := new(bytes.Buffer)
	cmd.Root().GenBashCompletion(buf)
	out.Write(buf.Bytes())

	zshTail := `
BASH_COMPLETION_EOF
}
__helm_bash_source <(__helm_convert_bash_to_zsh)
`
	out.Write([]byte(zshTail))
	return nil
}
<commit_msg>Allow zsh completion to be autoloaded by compinit<commit_after>/*
Copyright 2016 The Kubernetes Authors All rights reserved.
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 main

import (
	"bytes"
	"fmt"
	"io"

	"github.com/spf13/cobra"
)

const completionDesc = `
Generate autocompletions script for Helm for the specified shell (bash or zsh).

This command can generate shell autocompletions. e.g.

	$ helm completion bash

Can be sourced as such

	$ source <(helm completion bash)
`

var (
	completionShells = map[string]func(out io.Writer, cmd *cobra.Command) error{
		"bash": runCompletionBash,
		"zsh":  runCompletionZsh,
	}
)

func newCompletionCmd(out io.Writer) *cobra.Command {
	shells := []string{}
	for s := range completionShells {
		shells = append(shells, s)
	}

	cmd := &cobra.Command{
		Use:   "completion SHELL",
		Short: "Generate autocompletions script for the specified shell (bash or zsh)",
		Long:  completionDesc,
		RunE: func(cmd *cobra.Command, args []string) error {
			return runCompletion(out, cmd, args)
		},
		ValidArgs: shells,
	}

	return cmd
}

func runCompletion(out io.Writer, cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return fmt.Errorf("shell not specified")
	}
	if len(args) > 1 {
		return fmt.Errorf("too many arguments, expected only the shell type")
	}
	run, found := completionShells[args[0]]
	if !found {
		return fmt.Errorf("unsupported shell type %q", args[0])
	}

	return run(out, cmd)
}

func runCompletionBash(out io.Writer, cmd *cobra.Command) error {
	return cmd.Root().GenBashCompletion(out)
}

func runCompletionZsh(out io.Writer, cmd *cobra.Command) error {
	zshInitialization := `
#compdef helm

__helm_bash_source() {
	alias shopt=':'
	alias _expand=_bash_expand
	alias _complete=_bash_comp
	emulate -L sh
	setopt kshglob noshglob braceexpand
	source "$@"
}
__helm_type() {
	# -t is not supported by zsh
	if [ "$1" == "-t" ]; then
		shift
		# fake Bash 4 to disable "complete -o nospace". Instead
		# "compopt +-o nospace" is used in the code to toggle trailing
		# spaces. We don't support that, but leave trailing spaces on
		# all the time
		if [ "$1" = "__helm_compopt" ]; then
			echo builtin
			return 0
		fi
	fi
	type "$@"
}
__helm_compgen() {
	local completions w
	completions=( $(compgen "$@") ) || return $?
	# filter by given word as prefix
	while [[ "$1" = -* && "$1" != -- ]]; do
		shift
		shift
	done
	if [[ "$1" == -- ]]; then
		shift
	fi
	for w in "${completions[@]}"; do
		if [[ "${w}" = "$1"* ]]; then
			echo "${w}"
		fi
	done
}
__helm_compopt() {
	true # don't do anything. Not supported by bashcompinit in zsh
}
__helm_declare() {
	if [ "$1" == "-F" ]; then
		whence -w "$@"
	else
		builtin declare "$@"
	fi
}
__helm_ltrim_colon_completions()
{
	if [[ "$1" == *:* && "$COMP_WORDBREAKS" == *:* ]]; then
		# Remove colon-word prefix from COMPREPLY items
		local colon_word=${1%${1##*:}}
		local i=${#COMPREPLY[*]}
		while [[ $((--i)) -ge 0 ]]; do
			COMPREPLY[$i]=${COMPREPLY[$i]#"$colon_word"}
		done
	fi
}
__helm_get_comp_words_by_ref() {
	cur="${COMP_WORDS[COMP_CWORD]}"
	prev="${COMP_WORDS[${COMP_CWORD}-1]}"
	words=("${COMP_WORDS[@]}")
	cword=("${COMP_CWORD[@]}")
}
__helm_filedir() {
	local RET OLD_IFS w qw
	__debug "_filedir $@ cur=$cur"
	if [[ "$1" = \~* ]]; then
		# somehow does not work. Maybe, zsh does not call this at all
		eval echo "$1"
		return 0
	fi
	OLD_IFS="$IFS"
	IFS=$'\n'
	if [ "$1" = "-d" ]; then
		shift
		RET=( $(compgen -d) )
	else
		RET=( $(compgen -f) )
	fi
	IFS="$OLD_IFS"
	IFS="," __debug "RET=${RET[@]} len=${#RET[@]}"
	for w in ${RET[@]}; do
		if [[ ! "${w}" = "${cur}"* ]]; then
			continue
		fi
		if eval "[[ \"\${w}\" = *.$1 || -d \"\${w}\" ]]"; then
			qw="$(__helm_quote "${w}")"
			if [ -d "${w}" ]; then
				COMPREPLY+=("${qw}/")
			else
				COMPREPLY+=("${qw}")
			fi
		fi
	done
}
__helm_quote() {
	if [[ $1 == \'* || $1 == \"* ]]; then
		# Leave out first character
		printf %q "${1:1}"
	else
		printf %q "$1"
	fi
}
autoload -U +X bashcompinit && bashcompinit
# use word boundary patterns for BSD or GNU sed
LWORD='[[:<:]]'
RWORD='[[:>:]]'
if sed --help 2>&1 | grep -q GNU; then
	LWORD='\<'
	RWORD='\>'
fi
__helm_convert_bash_to_zsh() {
	sed \
	-e 's/declare -F/whence -w/' \
	-e 's/_get_comp_words_by_ref "\$@"/_get_comp_words_by_ref "\$*"/' \
	-e 's/local \([a-zA-Z0-9_]*\)=/local \1; \1=/' \
	-e 's/flags+=("\(--.*\)=")/flags+=("\1"); two_word_flags+=("\1")/' \
	-e 's/must_have_one_flag+=("\(--.*\)=")/must_have_one_flag+=("\1")/' \
	-e "s/${LWORD}_filedir${RWORD}/__helm_filedir/g" \
	-e "s/${LWORD}_get_comp_words_by_ref${RWORD}/__helm_get_comp_words_by_ref/g" \
	-e "s/${LWORD}__ltrim_colon_completions${RWORD}/__helm_ltrim_colon_completions/g" \
	-e "s/${LWORD}compgen${RWORD}/__helm_compgen/g" \
	-e "s/${LWORD}compopt${RWORD}/__helm_compopt/g" \
	-e "s/${LWORD}declare${RWORD}/__helm_declare/g" \
	-e "s/\\\$(type${RWORD}/\$(__helm_type/g" \
	<<'BASH_COMPLETION_EOF'
`
	out.Write([]byte(zshInitialization))

	buf := new(bytes.Buffer)
	cmd.Root().GenBashCompletion(buf)
	out.Write(buf.Bytes())

	zshTail := `
BASH_COMPLETION_EOF
}
__helm_bash_source <(__helm_convert_bash_to_zsh)
`
	out.Write([]byte(zshTail))
	return nil
}
<|endoftext|>


<commit_before>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 siv

import (
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	"testing"
)

func TestS2v(t *testing.T) { RunTests(t) }

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type S2vTest struct{}

func init() { RegisterTestSuite(&S2vTest{}) }

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

func (t *S2vTest) NilKey() {
	key := []byte(nil)
	associatedData := [][]byte{}

	f := func() { s2v(key, associatedData) }
	ExpectThat(f, Panics(HasSubstr("16-byte")))
}

func (t *S2vTest) ShortKey() {
	key := make([]byte, 15)
	associatedData := [][]byte{}

	f := func() { s2v(key, associatedData) }
	ExpectThat(f, Panics(HasSubstr("16-byte")))
}

func (t *S2vTest) LongKey() {
	key := make([]byte, 17)
	associatedData := [][]byte{}

	f := func() { s2v(key, associatedData) }
	ExpectThat(f, Panics(HasSubstr("16-byte")))
}

func (t *S2vTest) Rfc5297GoldenTestCaseA1() {
	key := fromRfcHex(
		"fffefdfc fbfaf9f8 f7f6f5f4 f3f2f1f0" +
		"f0f1f2f3 f4f5f6f7 f8f9fafb fcfdfeff")

	associatedData := [][]byte{
		fromRfcHex(
			"10111213 14151617 18191a1b 1c1d1e1f" +
			"20212223 24252627"),
	}

	expected := fromRfcHex("85632d07 c6e8f37f 950acd32 0a2ecc93")

	ExpectThat(s2v(key, associatedData), DeepEquals(expected))
}

func (t *S2vTest) Rfc5297GoldenTestCaseA2() {
	ExpectEq("TODO", "")
}

func (t *S2vTest) GeneratedTestCases() {
	ExpectEq("TODO", "")
}
<commit_msg>S2vTest.Rfc5297GoldenTestCaseA2<commit_after>// Copyright 2012 Aaron Jacobs. All Rights Reserved.
// Author: aaronjjacobs@gmail.com (Aaron Jacobs)
//
// 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 siv

import (
	. "github.com/jacobsa/oglematchers"
	. "github.com/jacobsa/ogletest"
	"testing"
)

func TestS2v(t *testing.T) { RunTests(t) }

////////////////////////////////////////////////////////////////////////
// Helpers
////////////////////////////////////////////////////////////////////////

type S2vTest struct{}

func init() { RegisterTestSuite(&S2vTest{}) }

////////////////////////////////////////////////////////////////////////
// Tests
////////////////////////////////////////////////////////////////////////

func (t *S2vTest) NilKey() {
	key := []byte(nil)
	associatedData := [][]byte{}

	f := func() { s2v(key, associatedData) }
	ExpectThat(f, Panics(HasSubstr("16-byte")))
}

func (t *S2vTest) ShortKey() {
	key := make([]byte, 15)
	associatedData := [][]byte{}

	f := func() { s2v(key, associatedData) }
	ExpectThat(f, Panics(HasSubstr("16-byte")))
}

func (t *S2vTest) LongKey() {
	key := make([]byte, 17)
	associatedData := [][]byte{}

	f := func() { s2v(key, associatedData) }
	ExpectThat(f, Panics(HasSubstr("16-byte")))
}

func (t *S2vTest) Rfc5297GoldenTestCaseA1() {
	key := fromRfcHex(
		"fffefdfc fbfaf9f8 f7f6f5f4 f3f2f1f0" +
		"f0f1f2f3 f4f5f6f7 f8f9fafb fcfdfeff")

	associatedData := [][]byte{
		fromRfcHex(
			"10111213 14151617 18191a1b 1c1d1e1f" +
			"20212223 24252627"),
	}

	expected := fromRfcHex("85632d07 c6e8f37f 950acd32 0a2ecc93")

	ExpectThat(s2v(key, associatedData), DeepEquals(expected))
}

func (t *S2vTest) Rfc5297GoldenTestCaseA2() {
	key := fromRfcHex(
		"7f7e7d7c 7b7a7978 77767574 73727170" +
		"40414243 44454647 48494a4b 4c4d4e4f")

	associatedData := [][]byte{
		fromRfcHex(
			"00112233 44556677 8899aabb ccddeeff" +
			"deaddada deaddada ffeeddcc bbaa9988" +
			"77665544 33221100"),
		fromRfcHex("10203040 50607080 90a0"),
	}

	expected := fromRfcHex("7bdb6e3b 432667eb 06f4d14b ff2fbd0f")

	ExpectThat(s2v(key, associatedData), DeepEquals(expected))
}

func (t *S2vTest) GeneratedTestCases() {
	ExpectEq("TODO", "")
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/cad-san/ikaring"

	"bufio"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/user"
	"path/filepath"
	"strings"

	"github.com/bgentry/speakeasy"
)

func getCacheFile() (string, error) {
	me, err := user.Current()
	if err != nil {
		return "", err
	}
	return filepath.Join(me.HomeDir, ".ikaring.session"), nil
}

func readSession(path string) (string, error) {
	buff, err := ioutil.ReadFile(path)
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(buff)), nil
}

func writeSession(path string, session string) error {
	return ioutil.WriteFile(path, []byte(session), 600)
}

func getAccount(r io.Reader) (string, string, error) {
	scanner := bufio.NewScanner(r)
	for {
		fmt.Print("User: ")
		if scanner.Scan() {
			break
		}
	}
	username := scanner.Text()
	password, err := speakeasy.Ask("Password: ")
	return username, password, err
}

func login(client *ikaring.IkaClient) error {
	path, err := getCacheFile()
	if err != nil {
		return err
	}

	session, err := readSession(path)
	if err == nil && len(session) > 0 {
		client.SetSession(session)
		return nil // already authorized
	}

	username, password, err := getAccount(os.Stdin)
	session, err = client.Login(username, password)
	if err != nil {
		return err
	}

	if len(session) <= 0 {
		return errors.New("login failure")
	}
	writeSession(path, session)
	return nil
}

func stage(client *ikaring.IkaClient) error {
	info, err := client.GetStageInfo()
	if err != nil {
		return err
	}

	if info.FesSchedules != nil {
		for _, s := range *info.FesSchedules {
			fmt.Printf("%v\n", s)
		}
	}

	if info.Schedules != nil {
		for _, s := range *info.Schedules {
			fmt.Printf("%v\n", s)
		}
	}
	return nil
}

func main() {
	client, err := ikaring.CreateClient()
	if err != nil {
		fmt.Println(err)
		return
	}

	if err = login(client); err != nil {
		fmt.Println(err)
		return
	}

	if err = stage(client); err != nil {
		fmt.Println(err)
		return
	}
}
<commit_msg>add ranking() function<commit_after>package main

import (
	"github.com/cad-san/ikaring"

	"bufio"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"os/user"
	"path/filepath"
	"strings"

	"github.com/bgentry/speakeasy"
)

func getCacheFile() (string, error) {
	me, err := user.Current()
	if err != nil {
		return "", err
	}
	return filepath.Join(me.HomeDir, ".ikaring.session"), nil
}

func readSession(path string) (string, error) {
	buff, err := ioutil.ReadFile(path)
	if err != nil {
		return "", err
	}
	return strings.TrimSpace(string(buff)), nil
}

func writeSession(path string, session string) error {
	return ioutil.WriteFile(path, []byte(session), 600)
}

func getAccount(r io.Reader) (string, string, error) {
	scanner := bufio.NewScanner(r)
	for {
		fmt.Print("User: ")
		if scanner.Scan() {
			break
		}
	}
	username := scanner.Text()
	password, err := speakeasy.Ask("Password: ")
	return username, password, err
}

func login(client *ikaring.IkaClient) error {
	path, err := getCacheFile()
	if err != nil {
		return err
	}

	session, err := readSession(path)
	if err == nil && len(session) > 0 {
		client.SetSession(session)
		return nil // already authorized
	}

	username, password, err := getAccount(os.Stdin)
	session, err = client.Login(username, password)
	if err != nil {
		return err
	}

	if len(session) <= 0 {
		return errors.New("login failure")
	}
	writeSession(path, session)
	return nil
}

func stage(client *ikaring.IkaClient) error {
	info, err := client.GetStageInfo()
	if err != nil {
		return err
	}

	if info.FesSchedules != nil {
		for _, s := range *info.FesSchedules {
			fmt.Printf("%v\n", s)
		}
	}

	if info.Schedules != nil {
		for _, s := range *info.Schedules {
			fmt.Printf("%v\n", s)
		}
	}
	return nil
}

func ranking(client *ikaring.IkaClient) error {
	info, err := client.GetRanking()
	if err != nil {
		return err
	}

	if len(info.Regular) > 0 {
		fmt.Println("レギュラーマッチ")
		for _, p := range info.Regular {
			fmt.Printf("\t[%d] %3d %s (%s)\n", p.Rank, p.Score, p.Name, p.Weapon)
		}
	}

	if len(info.Gachi) > 0 {
		fmt.Println("ガチマッチ")
		for _, p := range info.Gachi {
			fmt.Printf("\t[%d] %3d %s (%s)\n", p.Rank, p.Score, p.Name, p.Weapon)
		}
	}
	return nil
}

func main() {
	client, err := ikaring.CreateClient()
	if err != nil {
		fmt.Println(err)
		return
	}

	if err = login(client); err != nil {
		fmt.Println(err)
		return
	}

	if err = stage(client); err != nil {
		fmt.Println(err)
		return
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"github.com/Symantec/Dominator/imagebuilder/builder"
	"github.com/Symantec/Dominator/imagebuilder/httpd"
	"github.com/Symantec/Dominator/imagebuilder/rpcd"
	"github.com/Symantec/Dominator/lib/constants"
	"github.com/Symantec/Dominator/lib/logbuf"
	"github.com/Symantec/Dominator/lib/srpc/setupserver"
	"github.com/Symantec/tricorder/go/tricorder"
	"log"
	"os"
	"syscall"
	"time"
)

const (
	dirPerms = syscall.S_IRWXU | syscall.S_IRGRP | syscall.S_IXGRP |
		syscall.S_IROTH | syscall.S_IXOTH
)

var (
	configurationUrl = flag.String("configurationUrl",
		"file:///etc/imaginator/conf.json", "URL containing configuration")
	imageServerHostname = flag.String("imageServerHostname", "localhost",
		"Hostname of image server")
	imageServerPortNum = flag.Uint("imageServerPortNum",
		constants.ImageServerPortNumber,
		"Port number of image server")
	imageRebuildInterval = flag.Duration("imageRebuildInterval", time.Hour,
		"time between automatic rebuilds of images")
	portNum = flag.Uint("portNum", constants.ImaginatorPortNumber,
		"Port number to allocate and listen on for HTTP/RPC")
	stateDir = flag.String("stateDir", "/var/lib/imaginator",
		"Name of state directory")
	variablesFile = flag.String("variablesFile", "",
		"A JSON encoded file containing special variables (i.e. secrets)")
)

func main() {
	flag.Parse()
	tricorder.RegisterFlags()
	if os.Geteuid() != 0 {
		fmt.Fprintln(os.Stderr, "Must run the Image Builder as root")
		os.Exit(1)
	}
	circularBuffer := logbuf.New()
	logger := log.New(circularBuffer, "", log.LstdFlags)
	if err := setupserver.SetupTls(); err != nil {
		logger.Println(err)
		circularBuffer.Flush()
		os.Exit(1)
	}
	if err := os.MkdirAll(*stateDir, dirPerms); err != nil {
		fmt.Fprintf(os.Stderr, "Cannot create state directory: %s\n", err)
		os.Exit(1)
	}
	builderObj, err := builder.Load(*configurationUrl, *variablesFile,
		*stateDir,
		fmt.Sprintf("%s:%d", *imageServerHostname, *imageServerPortNum),
		*imageRebuildInterval, logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Cannot start builder: %s\n", err)
		os.Exit(1)
	}
	rpcHtmlWriter, err := rpcd.Setup(builderObj, logger)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Cannot start builder: %s\n", err)
		os.Exit(1)
	}
	httpd.AddHtmlWriter(builderObj)
	httpd.AddHtmlWriter(rpcHtmlWriter)
	httpd.AddHtmlWriter(circularBuffer)
	if err = httpd.StartServer(*portNum, builderObj, false); err != nil {
		fmt.Fprintf(os.Stderr, "Unable to create http server: %s\n", err)
		os.Exit(1)
	}
}
<commit_msg>Switch imaginator to lib/log/serverlogger package.<commit_after>package main

import (
	"flag"
	"fmt"
	"github.com/Symantec/Dominator/imagebuilder/builder"
	"github.com/Symantec/Dominator/imagebuilder/httpd"
	"github.com/Symantec/Dominator/imagebuilder/rpcd"
	"github.com/Symantec/Dominator/lib/constants"
	"github.com/Symantec/Dominator/lib/log/serverlogger"
	"github.com/Symantec/Dominator/lib/srpc/setupserver"
	"github.com/Symantec/tricorder/go/tricorder"
	"os"
	"syscall"
	"time"
)

const (
	dirPerms = syscall.S_IRWXU | syscall.S_IRGRP | syscall.S_IXGRP |
		syscall.S_IROTH | syscall.S_IXOTH
)

var (
	configurationUrl = flag.String("configurationUrl",
		"file:///etc/imaginator/conf.json", "URL containing configuration")
	imageServerHostname = flag.String("imageServerHostname", "localhost",
		"Hostname of image server")
	imageServerPortNum = flag.Uint("imageServerPortNum",
		constants.ImageServerPortNumber,
		"Port number of image server")
	imageRebuildInterval = flag.Duration("imageRebuildInterval", time.Hour,
		"time between automatic rebuilds of images")
	portNum = flag.Uint("portNum", constants.ImaginatorPortNumber,
		"Port number to allocate and listen on for HTTP/RPC")
	stateDir = flag.String("stateDir", "/var/lib/imaginator",
		"Name of state directory")
	variablesFile = flag.String("variablesFile", "",
		"A JSON encoded file containing special variables (i.e. secrets)")
)

func main() {
	flag.Parse()
	tricorder.RegisterFlags()
	if os.Geteuid() != 0 {
		fmt.Fprintln(os.Stderr, "Must run the Image Builder as root")
		os.Exit(1)
	}
	logger := serverlogger.New("")
	if err := setupserver.SetupTls(); err != nil {
		logger.Fatalln(err)
	}
	if err := os.MkdirAll(*stateDir, dirPerms); err != nil {
		logger.Fatalf("Cannot create state directory: %s\n", err)
	}
	builderObj, err := builder.Load(*configurationUrl, *variablesFile,
		*stateDir,
		fmt.Sprintf("%s:%d", *imageServerHostname, *imageServerPortNum),
		*imageRebuildInterval, logger)
	if err != nil {
		logger.Fatalf("Cannot start builder: %s\n", err)
	}
	rpcHtmlWriter, err := rpcd.Setup(builderObj, logger)
	if err != nil {
		logger.Fatalf("Cannot start builder: %s\n", err)
	}
	httpd.AddHtmlWriter(builderObj)
	httpd.AddHtmlWriter(rpcHtmlWriter)
	httpd.AddHtmlWriter(logger)
	if err = httpd.StartServer(*portNum, builderObj, false); err != nil {
		logger.Fatalf("Unable to create http server: %s\n", err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/datawire/teleproxy/pkg/k8s"
	"github.com/spf13/cobra"
)

func main() {
	var st = &cobra.Command{
		Use:           "kubestatus <kind>",
		Short:         "kubestatus",
		Long:          "kubestatus - get and set status of kubernetes resources",
		Args:          cobra.ExactArgs(1),
		SilenceErrors: true,
		SilenceUsage:  true,
	}

	info := k8s.NewKubeInfoFromFlags(st.Flags())
	fields := st.Flags().StringP("field-selector", "f", "", "field selector")
	labels := st.Flags().StringP("label-selector", "l", "", "label selector")
	statusFile := st.Flags().StringP("update", "u", "", "update with new status from file (must be json)")

	st.RunE = func(cmd *cobra.Command, args []string) error {
		var status map[string]interface{}

		if *statusFile != "" {
			rawStatus, err := os.Open(*statusFile)
			if err != nil {
				return err
			}
			defer rawStatus.Close()

			dec := json.NewDecoder(rawStatus)
			err = dec.Decode(&status)
			if err != nil {
				return err
			}
		}

		kind := args[0]
		namespace, err := info.Namespace()
		if err != nil {
			return err
		}

		w := k8s.MustNewWatcher(info)
		err = w.WatchQuery(k8s.Query{
			Kind:          kind,
			Namespace:     namespace,
			FieldSelector: *fields,
			LabelSelector: *labels,
		}, func(w *k8s.Watcher) {
			for _, rsrc := range w.List(kind) {
				if *statusFile == "" {
					fmt.Println("Status of", rsrc.QName())
					fmt.Printf("  %q\n", rsrc["status"])
				} else {
					fmt.Println("Updating", rsrc.QName())
					rsrc["status"] = status
					_, err := w.UpdateStatus(rsrc)
					if err != nil {
						log.Println(err)
					}
				}
			}
			w.Stop()
		})

		if err != nil {
			return err
		}

		w.Wait()
		return nil
	}

	err := st.Execute()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}

}
<commit_msg>remove long in favor of short<commit_after>package main

import (
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/datawire/teleproxy/pkg/k8s"
	"github.com/spf13/cobra"
)

func main() {
	var st = &cobra.Command{
		Use:           "kubestatus <kind>",
		Short:         "get and set status of kubernetes resources",
		Args:          cobra.ExactArgs(1),
		SilenceErrors: true,
		SilenceUsage:  true,
	}

	info := k8s.NewKubeInfoFromFlags(st.Flags())
	fields := st.Flags().StringP("field-selector", "f", "", "field selector")
	labels := st.Flags().StringP("label-selector", "l", "", "label selector")
	statusFile := st.Flags().StringP("update", "u", "", "update with new status from file (must be json)")

	st.RunE = func(cmd *cobra.Command, args []string) error {
		var status map[string]interface{}

		if *statusFile != "" {
			rawStatus, err := os.Open(*statusFile)
			if err != nil {
				return err
			}
			defer rawStatus.Close()

			dec := json.NewDecoder(rawStatus)
			err = dec.Decode(&status)
			if err != nil {
				return err
			}
		}

		kind := args[0]
		namespace, err := info.Namespace()
		if err != nil {
			return err
		}

		w := k8s.MustNewWatcher(info)
		err = w.WatchQuery(k8s.Query{
			Kind:          kind,
			Namespace:     namespace,
			FieldSelector: *fields,
			LabelSelector: *labels,
		}, func(w *k8s.Watcher) {
			for _, rsrc := range w.List(kind) {
				if *statusFile == "" {
					fmt.Println("Status of", rsrc.QName())
					fmt.Printf("  %q\n", rsrc["status"])
				} else {
					fmt.Println("Updating", rsrc.QName())
					rsrc["status"] = status
					_, err := w.UpdateStatus(rsrc)
					if err != nil {
						log.Println(err)
					}
				}
			}
			w.Stop()
		})

		if err != nil {
			return err
		}

		w.Wait()
		return nil
	}

	err := st.Execute()
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %v\n", err)
		os.Exit(1)
	}

}
<|endoftext|>


<commit_before>package manager

import (
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/spf13/cobra"

	bivacCmd "github.com/camptocamp/bivac/cmd"
	"github.com/camptocamp/bivac/internal/manager"
	"github.com/camptocamp/bivac/pkg/volume"
)

var (
	server       manager.Server
	orchestrator string

	// Orchestrators is a copy of manager.Orchestrators which allows orchestrator
	// configuration from Cobra variables
	Orchestrators manager.Orchestrators

	dbPath           string
	resticForgetArgs string

	providersFile    string
	targetURL        string
	retryCount       int
	logServer        string
	agentImage       string
	whitelistVolumes string
	blacklistVolumes string
	whitelistAnnotation bool
)
var envs = make(map[string]string)

var managerCmd = &cobra.Command{
	Use:   "manager",
	Short: "Start Bivac backup manager",
	Run: func(cmd *cobra.Command, args []string) {
		volumesFilters := volume.Filters{
			Blacklist:           strings.Split(blacklistVolumes, ","),
			Whitelist:           strings.Split(whitelistVolumes, ","),
			WhitelistAnnotation: whitelistAnnotation,
		}

		o, err := manager.GetOrchestrator(orchestrator, Orchestrators)
		if err != nil {
			log.Errorf("failed to retrieve orchestrator: %s", err)
			return
		}

		err = manager.Start(bivacCmd.BuildInfo, o, server, volumesFilters, providersFile, targetURL, logServer, agentImage, retryCount)
		if err != nil {
			log.Errorf("failed to start manager: %s", err)
			return
		}
	},
}

func init() {
	managerCmd.Flags().StringVarP(&server.Address, "server.address", "", "0.0.0.0:8182", "Address to bind on.")
	envs["BIVAC_SERVER_ADDRESS"] = "server.address"
	managerCmd.Flags().StringVarP(&server.PSK, "server.psk", "", "", "Pre-shared key.")
	envs["BIVAC_SERVER_PSK"] = "server.psk"

	managerCmd.Flags().StringVarP(&orchestrator, "orchestrator", "o", "", "Orchestrator on which Bivac should connect to.")
	envs["BIVAC_ORCHESTRATOR"] = "orchestrator"

	managerCmd.Flags().StringVarP(&Orchestrators.Docker.Endpoint, "docker.endpoint", "", "unix:///var/run/docker.sock", "Docker endpoint.")
	envs["BIVAC_DOCKER_ENDPOINT"] = "docker.endpoint"

	managerCmd.Flags().StringVarP(&Orchestrators.Cattle.URL, "cattle.url", "", "", "The Cattle URL.")
	envs["CATTLE_URL"] = "cattle.url"
	managerCmd.Flags().StringVarP(&Orchestrators.Cattle.AccessKey, "cattle.accesskey", "", "", "The Cattle access key.")
	envs["CATTLE_ACCESS_KEY"] = "cattle.accesskey"
	managerCmd.Flags().StringVarP(&Orchestrators.Cattle.SecretKey, "cattle.secretkey", "", "", "The Cattle secret key.")
	envs["CATTLE_SECRET_KEY"] = "cattle.secretkey"

	managerCmd.Flags().StringVarP(&Orchestrators.Kubernetes.Namespace, "kubernetes.namespace", "", "", "Namespace where you want to run Bivac.")
	envs["KUBERNETES_NAMESPACE"] = "kubernetes.namespace"
	managerCmd.Flags().BoolVarP(&Orchestrators.Kubernetes.AllNamespaces, "kubernetes.all-namespaces", "", false, "Backup volumes of all namespaces.")
	envs["KUBERNETES_ALL_NAMESPACES"] = "kubernetes.all-namespaces"
	managerCmd.Flags().StringVarP(&Orchestrators.Kubernetes.KubeConfig, "kubernetes.kubeconfig", "", "", "Path to your kuberconfig file.")
	envs["KUBERNETES_KUBECONFIG"] = "kubernetes.kubeconfig"
	managerCmd.Flags().StringVarP(&Orchestrators.Kubernetes.AgentServiceAccount, "kubernetes.agent-service-account", "", "", "Specify service account for agents.")
	envs["KUBERNETES_AGENT_SERVICE_ACCOUNT"] = "kubernetes.agent-service-account"

	managerCmd.Flags().StringVarP(&resticForgetArgs, "restic.forget.args", "", "--group-by host --keep-daily 15 --prune", "Restic forget arguments.")
	envs["RESTIC_FORGET_ARGS"] = "restic.forget.args"

	managerCmd.Flags().StringVarP(&providersFile, "providers.config", "", "/providers-config.default.toml", "Configuration file for providers.")
	envs["BIVAC_PROVIDERS_CONFIG"] = "providers.config"

	managerCmd.Flags().StringVarP(&targetURL, "target.url", "r", "", "The target URL to push the backups to.")
	envs["BIVAC_TARGET_URL"] = "target.url"

	managerCmd.Flags().IntVarP(&retryCount, "retry.count", "", 0, "Retry to backup the volume if something goes wrong with Bivac.")
	envs["BIVAC_RETRY_COUNT"] = "retry.count"

	managerCmd.Flags().StringVarP(&logServer, "log.server", "", "", "Manager's API address that will receive logs from agents.")
	envs["BIVAC_LOG_SERVER"] = "log.server"

	managerCmd.Flags().StringVarP(&agentImage, "agent.image", "", "camptocamp/bivac:2.0.0", "Agent's Docker image.")
	envs["BIVAC_AGENT_IMAGE"] = "agent.image"

	managerCmd.Flags().StringVarP(&whitelistVolumes, "whitelist", "", "", "Whitelist volumes.")
	envs["BIVAC_WHITELIST"] = "whitelist"

	managerCmd.Flags().StringVarP(&blacklistVolumes, "blacklist", "", "", "Blacklist volumes.")
	envs["BIVAC_BLACKLIST"] = "blacklist"

  managerCmd.Flags().BoolVarP(&whitelistAnnotation, "whitelist.annotations", "", false, "Require pvc whitelist annotation")
	envs["BIVAC_WHITELIST_ANNOTATION"] = "whitelist.annotations"

	bivacCmd.SetValuesFromEnv(envs, managerCmd.Flags())
	bivacCmd.RootCmd.AddCommand(managerCmd)
}
<commit_msg>linting<commit_after>package manager

import (
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/spf13/cobra"

	bivacCmd "github.com/camptocamp/bivac/cmd"
	"github.com/camptocamp/bivac/internal/manager"
	"github.com/camptocamp/bivac/pkg/volume"
)

var (
	server       manager.Server
	orchestrator string

	// Orchestrators is a copy of manager.Orchestrators which allows orchestrator
	// configuration from Cobra variables
	Orchestrators manager.Orchestrators

	dbPath           string
	resticForgetArgs string

	providersFile       string
	targetURL           string
	retryCount          int
	logServer           string
	agentImage          string
	whitelistVolumes    string
	blacklistVolumes    string
	whitelistAnnotation bool
)
var envs = make(map[string]string)

var managerCmd = &cobra.Command{
	Use:   "manager",
	Short: "Start Bivac backup manager",
	Run: func(cmd *cobra.Command, args []string) {
		volumesFilters := volume.Filters{
			Blacklist:           strings.Split(blacklistVolumes, ","),
			Whitelist:           strings.Split(whitelistVolumes, ","),
			WhitelistAnnotation: whitelistAnnotation,
		}

		o, err := manager.GetOrchestrator(orchestrator, Orchestrators)
		if err != nil {
			log.Errorf("failed to retrieve orchestrator: %s", err)
			return
		}

		err = manager.Start(bivacCmd.BuildInfo, o, server, volumesFilters, providersFile, targetURL, logServer, agentImage, retryCount)
		if err != nil {
			log.Errorf("failed to start manager: %s", err)
			return
		}
	},
}

func init() {
	managerCmd.Flags().StringVarP(&server.Address, "server.address", "", "0.0.0.0:8182", "Address to bind on.")
	envs["BIVAC_SERVER_ADDRESS"] = "server.address"
	managerCmd.Flags().StringVarP(&server.PSK, "server.psk", "", "", "Pre-shared key.")
	envs["BIVAC_SERVER_PSK"] = "server.psk"

	managerCmd.Flags().StringVarP(&orchestrator, "orchestrator", "o", "", "Orchestrator on which Bivac should connect to.")
	envs["BIVAC_ORCHESTRATOR"] = "orchestrator"

	managerCmd.Flags().StringVarP(&Orchestrators.Docker.Endpoint, "docker.endpoint", "", "unix:///var/run/docker.sock", "Docker endpoint.")
	envs["BIVAC_DOCKER_ENDPOINT"] = "docker.endpoint"

	managerCmd.Flags().StringVarP(&Orchestrators.Cattle.URL, "cattle.url", "", "", "The Cattle URL.")
	envs["CATTLE_URL"] = "cattle.url"
	managerCmd.Flags().StringVarP(&Orchestrators.Cattle.AccessKey, "cattle.accesskey", "", "", "The Cattle access key.")
	envs["CATTLE_ACCESS_KEY"] = "cattle.accesskey"
	managerCmd.Flags().StringVarP(&Orchestrators.Cattle.SecretKey, "cattle.secretkey", "", "", "The Cattle secret key.")
	envs["CATTLE_SECRET_KEY"] = "cattle.secretkey"

	managerCmd.Flags().StringVarP(&Orchestrators.Kubernetes.Namespace, "kubernetes.namespace", "", "", "Namespace where you want to run Bivac.")
	envs["KUBERNETES_NAMESPACE"] = "kubernetes.namespace"
	managerCmd.Flags().BoolVarP(&Orchestrators.Kubernetes.AllNamespaces, "kubernetes.all-namespaces", "", false, "Backup volumes of all namespaces.")
	envs["KUBERNETES_ALL_NAMESPACES"] = "kubernetes.all-namespaces"
	managerCmd.Flags().StringVarP(&Orchestrators.Kubernetes.KubeConfig, "kubernetes.kubeconfig", "", "", "Path to your kuberconfig file.")
	envs["KUBERNETES_KUBECONFIG"] = "kubernetes.kubeconfig"
	managerCmd.Flags().StringVarP(&Orchestrators.Kubernetes.AgentServiceAccount, "kubernetes.agent-service-account", "", "", "Specify service account for agents.")
	envs["KUBERNETES_AGENT_SERVICE_ACCOUNT"] = "kubernetes.agent-service-account"

	managerCmd.Flags().StringVarP(&resticForgetArgs, "restic.forget.args", "", "--group-by host --keep-daily 15 --prune", "Restic forget arguments.")
	envs["RESTIC_FORGET_ARGS"] = "restic.forget.args"

	managerCmd.Flags().StringVarP(&providersFile, "providers.config", "", "/providers-config.default.toml", "Configuration file for providers.")
	envs["BIVAC_PROVIDERS_CONFIG"] = "providers.config"

	managerCmd.Flags().StringVarP(&targetURL, "target.url", "r", "", "The target URL to push the backups to.")
	envs["BIVAC_TARGET_URL"] = "target.url"

	managerCmd.Flags().IntVarP(&retryCount, "retry.count", "", 0, "Retry to backup the volume if something goes wrong with Bivac.")
	envs["BIVAC_RETRY_COUNT"] = "retry.count"

	managerCmd.Flags().StringVarP(&logServer, "log.server", "", "", "Manager's API address that will receive logs from agents.")
	envs["BIVAC_LOG_SERVER"] = "log.server"

	managerCmd.Flags().StringVarP(&agentImage, "agent.image", "", "camptocamp/bivac:2.0.0", "Agent's Docker image.")
	envs["BIVAC_AGENT_IMAGE"] = "agent.image"

	managerCmd.Flags().StringVarP(&whitelistVolumes, "whitelist", "", "", "Whitelist volumes.")
	envs["BIVAC_WHITELIST"] = "whitelist"

	managerCmd.Flags().StringVarP(&blacklistVolumes, "blacklist", "", "", "Blacklist volumes.")
	envs["BIVAC_BLACKLIST"] = "blacklist"

	managerCmd.Flags().BoolVarP(&whitelistAnnotation, "whitelist.annotations", "", false, "Require pvc whitelist annotation")
	envs["BIVAC_WHITELIST_ANNOTATION"] = "whitelist.annotations"

	bivacCmd.SetValuesFromEnv(envs, managerCmd.Flags())
	bivacCmd.RootCmd.AddCommand(managerCmd)
}
<|endoftext|>


<commit_before>package ls

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"path"

	"github.com/asjoyner/shade"
	"github.com/asjoyner/shade/config"

	"golang.org/x/net/context"

	"github.com/google/subcommands"
)

func init() {
	subcommands.Register(&lsCmd{}, "")
}

var (
	defaultConfig = path.Join(shade.ConfigDir(), "config.json")
)

type lsCmd struct {
	long   bool
	config string
}

func (*lsCmd) Name() string     { return "ls" }
func (*lsCmd) Synopsis() string { return "List files in the respository." }
func (*lsCmd) Usage() string {
	return `ls [-l] [-f FILE]:
  List all the files in the configured shade repositories.
`
}

func (p *lsCmd) SetFlags(f *flag.FlagSet) {
	f.BoolVar(&p.long, "l", false, "Long format listing")
	f.StringVar(&p.config, "f", defaultConfig, "Path to shade config")
}

func (p *lsCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
	// read in the config
	clients, err := config.Clients(p.config)
	if err != nil {
		fmt.Printf("could not initialize clients: %s", err)
		return subcommands.ExitFailure
	}

	file := &shade.File{}
	for _, client := range clients {
		fmt.Println(client.GetConfig().Provider)
		lfm, err := client.ListFiles()
		if err != nil {
			fmt.Fprintf(os.Stderr, "could not get files: %s\n", err)
			return subcommands.ExitFailure
		}
		for id, sha256sum := range lfm {
			fileJSON, err := client.GetChunk(sha256sum)
			if err != nil {
				fmt.Fprintf(os.Stderr, "could not get file %q: %s\n", id, err)
				continue
			}
			err = json.Unmarshal(fileJSON, file)
			if err != nil {
				fmt.Printf("failed to unmarshal: %s\n", err)
				continue
			}
			if p.long {
				fmt.Printf("  %s (%x):\n    %s\n", id, sha256sum, file)
			} else {
				fmt.Printf("  %s (%x)\n", id, sha256sum)
			}
		}
	}
	return subcommands.ExitSuccess
}
<commit_msg>Make shadeutil ls output a little better<commit_after>package ls

import (
	"encoding/json"
	"flag"
	"fmt"
	"os"
	"path"
	"text/tabwriter"
	"time"

	"github.com/asjoyner/shade"
	"github.com/asjoyner/shade/config"

	"golang.org/x/net/context"

	"github.com/google/subcommands"
)

func init() {
	subcommands.Register(&lsCmd{}, "")
}

var (
	defaultConfig = path.Join(shade.ConfigDir(), "config.json")
)

type lsCmd struct {
	long   bool
	config string
}

func (*lsCmd) Name() string     { return "ls" }
func (*lsCmd) Synopsis() string { return "List files in the respository." }
func (*lsCmd) Usage() string {
	return `ls [-l] [-f FILE]:
  List all the files in the configured shade repositories.
`
}

func (p *lsCmd) SetFlags(f *flag.FlagSet) {
	f.BoolVar(&p.long, "l", false, "Long format listing")
	f.StringVar(&p.config, "f", defaultConfig, "Path to shade config")
}

func (p *lsCmd) Execute(_ context.Context, f *flag.FlagSet, _ ...interface{}) subcommands.ExitStatus {
	// read in the config
	clients, err := config.Clients(p.config)
	if err != nil {
		fmt.Printf("could not initialize clients: %v", err)
		return subcommands.ExitFailure
	}

	file := &shade.File{}
	w := &tabwriter.Writer{}
	w.Init(os.Stdout, 0, 2, 1, ' ', 0)
	if p.long {
		fmt.Fprint(w, "\tid\t(sha)\tsize\tchunksize\tchunks\tmtime\tfilename\n")
	}
	for _, client := range clients {
		fmt.Println(client.GetConfig().Provider)
		lfm, err := client.ListFiles()
		if err != nil {
			fmt.Fprintf(os.Stderr, "could not get files: %v\n", err)
			return subcommands.ExitFailure
		}
		for id, sha256sum := range lfm {
			fileJSON, err := client.GetChunk(sha256sum)
			if err != nil {
				fmt.Fprintf(os.Stderr, "could not get file %q: %v\n", id, err)
				continue
			}
			err = json.Unmarshal(fileJSON, file)
			if err != nil {
				fmt.Printf("failed to unmarshal: %v\n", err)
				continue
			}
			if p.long {
				fmt.Fprintf(w, "\t%v\t(%x)\t%v\t%v\t%v\t%v\t%v\n", id, sha256sum, file.Filesize, file.Chunksize, file.Chunks, file.ModifiedTime.Format(time.Stamp), file.Filename)
			} else {
				fmt.Fprintf(w, "\t%v\n", file.Filename)
			}
		}
		w.Flush()
	}
	return subcommands.ExitSuccess
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"math"
	"os"
	"os/exec"
	"runtime"
	"strconv"
	"strings"
	"time"

	"github.com/ChristopherRabotin/smd"
)

const (
	debug = false
)

var (
	cpus     int
	planet   string
	stepSize float64
)

func init() {
	// Read flags
	flag.IntVar(&cpus, "cpus", -1, "number of CPUs to use for this simulation (set to 0 for max CPUs)")
	flag.StringVar(&planet, "planet", "undef", "departure planet to perform the spiral from")
	flag.Float64Var(&stepSize, "step", 15, "step size (10 to 30 recommended)")
}

/*
 * This example shows how to find the greatest heliocentric velocity at the end of a spiral by iterating on the initial
 * true anomaly.
 */

func sc() *smd.Spacecraft {
	eps := smd.NewUnlimitedEPS()
	thrusters := []smd.EPThruster{smd.NewGenericEP(5, 5000)} // VASIMR (approx.)
	dryMass := 10000.0
	fuelMass := 5000.0
	return smd.NewSpacecraft("Spiral", dryMass, fuelMass, eps, thrusters, false, []*smd.Cargo{},
		[]smd.Waypoint{smd.NewToHyperbolic(nil)})
}

func initEarthOrbit(i, Ω, ω, ν float64) *smd.Orbit {
	a, e := smd.Radii2ae(39300+smd.Earth.Radius, 290+smd.Earth.Radius)
	return smd.NewOrbitFromOE(a, e, i, Ω, ω, ν, smd.Earth)
}

// initMarsOrbit returns the initial orbit.
func initMarsOrbit(i, Ω, ω, ν float64) *smd.Orbit {
	// Exomars TGO.
	a, e := smd.Radii2ae(44500+smd.Mars.Radius, 426+smd.Mars.Radius)
	return smd.NewOrbitFromOE(a, e, i, Ω, ω, ν, smd.Mars)
}

func main() {
	flag.Parse()
	availableCPUs := runtime.NumCPU()
	if cpus <= 0 || cpus > availableCPUs {
		cpus = availableCPUs
	}
	runtime.GOMAXPROCS(cpus)
	fmt.Printf("running on %d CPUs\n", cpus)

	if stepSize <= 0 {
		fmt.Println("step size must be positive")
		flag.Usage()
		return
	} else if stepSize <= 5 {
		fmt.Println("[WARNING] A small step size will take several days to iterate over all possibilities")
	}

	var orbitPtr func(i, Ω, ω, ν float64) *smd.Orbit
	planet = strings.ToLower(planet)
	switch planet {
	case "mars":
		orbitPtr = initMarsOrbit
	case "earth":
		orbitPtr = initEarthOrbit
	default:
		fmt.Printf("unsupported planet `%s`\n", planet)
		flag.Usage()
		return
	}

	fmt.Printf("Finding spirals leaving from %s\n", planet)

	//name := "spiral-mars"
	depart := time.Date(2018, 11, 8, 0, 0, 0, 0, time.UTC)
	chgframePath := "../refframes/chgframe.py"
	maxV := -1e3
	minV := +1e3
	var maxOrbit smd.Orbit
	var minOrbit smd.Orbit
	a, e, _, _, _, _, _, _, _ := initMarsOrbit(10, 10, 10, 10).Elements()
	tsv := fmt.Sprintf("#a=%f km\te=%f\n#V(km/s), i (degrees), raan (degrees), arg peri (degrees),nu (degrees)\n", a, e)
	for i := 1.0; i < 90; i += stepSize {
		for Ω := 0.0; Ω < 360; Ω += stepSize {
			for ω := 0.0; ω < 360; ω += stepSize {
				for ν := 0.0; ν < 360; ν += stepSize {
					initOrbit := orbitPtr(i, Ω, ω, ν)
					astro := smd.NewMission(sc(), initOrbit, depart, depart.Add(-1), smd.Cartesian, smd.Perturbations{}, smd.ExportConfig{})
					astro.Propagate()

					// Run chgframe
					// We're now done so let's convert the position and velocity to heliocentric and check the output.
					R, V := initOrbit.RV()
					state := fmt.Sprintf("[%f,%f,%f,%f,%f,%f]", R[0], R[1], R[2], V[0], V[1], V[2])
					if debug {
						fmt.Printf("\n=== RUNNING CMD ===\npython %s -t J2000 -f IAU_Earth -e \"%s\" -s \"%s\"\n", chgframePath, astro.CurrentDT.Format(time.ANSIC), state)
					}
					cmd := exec.Command("python", chgframePath, "-t", "J2000", "-f", "IAU_Mars", "-e", astro.CurrentDT.Format(time.ANSIC), "-s", state)
					cmdOut, err := cmd.Output()
					if err != nil {
						fmt.Fprintln(os.Stderr, "Error converting orbit to helio ", err)
						os.Exit(1)
					}
					out := string(cmdOut)

					// Process output
					newState := strings.TrimSpace(string(out))
					// Cf. https://play.golang.org/p/g-a4idjhIb
					newState = newState[1 : len(newState)-1]
					components := strings.Split(newState, ",")
					var nR = make([]float64, 3)
					var nV = make([]float64, 3)
					for i := 0; i < 6; i++ {
						fl, err := strconv.ParseFloat(strings.TrimSpace(components[i]), 64)
						if err != nil {
							panic(err)
						}
						if i < 3 {
							nR[i] = fl
						} else {
							nV[i-3] = fl
						}
					}
					vNorm := math.Sqrt(math.Pow(nV[0], 2) + math.Pow(nV[1], 2) + math.Pow(nV[2], 2))
					// Add to TSV file
					tsv += fmt.Sprintf("%f,%f,%f,%f,%f\n", vNorm, i, Ω, ω, ν)
					if vNorm > maxV {
						maxV = vNorm
						maxOrbit = *initMarsOrbit(i, Ω, ω, ν)
					} else if vNorm < minV {
						minV = vNorm
						minOrbit = *initMarsOrbit(i, Ω, ω, ν)
					}
					if debug {
						fmt.Printf("\nν=%f\t=>V=%+v\t|V|=%f\n", ν, nV, vNorm)
					}
				}
			}
		}
	}
	fmt.Printf("\n\n=== RESULT ===\n\nmaxV=%.3f km/s\t%s\nminV=%.3f km/s\t%s\n\n", maxV, maxOrbit, minV, minOrbit)
	// Write CSV file.
	f, err := os.Create(fmt.Sprintf("./results-.csv"))
	if err != nil {
		panic(err)
	}
	defer f.Close()
	if _, err := f.WriteString(tsv); err != nil {
		panic(err)
	}
}
<commit_msg>Stream results<commit_after>package main

import (
	"flag"
	"fmt"
	"math"
	"os"
	"os/exec"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"

	"github.com/ChristopherRabotin/smd"
)

const (
	debug = false
)

var (
	cpus     int
	planet   string
	stepSize float64
	wg       sync.WaitGroup
)

func init() {
	// Read flags
	flag.IntVar(&cpus, "cpus", -1, "number of CPUs to use for this simulation (set to 0 for max CPUs)")
	flag.StringVar(&planet, "planet", "undef", "departure planet to perform the spiral from")
	flag.Float64Var(&stepSize, "step", 15, "step size (10 to 30 recommended)")
}

/*
 * This example shows how to find the greatest heliocentric velocity at the end of a spiral by iterating on the initial
 * true anomaly.
 */

func sc() *smd.Spacecraft {
	eps := smd.NewUnlimitedEPS()
	thrusters := []smd.EPThruster{smd.NewGenericEP(5, 5000)} // VASIMR (approx.)
	dryMass := 10000.0
	fuelMass := 5000.0
	return smd.NewSpacecraft("Spiral", dryMass, fuelMass, eps, thrusters, false, []*smd.Cargo{},
		[]smd.Waypoint{smd.NewToHyperbolic(nil)})
}

func initEarthOrbit(i, Ω, ω, ν float64) *smd.Orbit {
	a, e := smd.Radii2ae(39300+smd.Earth.Radius, 290+smd.Earth.Radius)
	return smd.NewOrbitFromOE(a, e, i, Ω, ω, ν, smd.Earth)
}

// initMarsOrbit returns the initial orbit.
func initMarsOrbit(i, Ω, ω, ν float64) *smd.Orbit {
	// Exomars TGO.
	a, e := smd.Radii2ae(44500+smd.Mars.Radius, 426+smd.Mars.Radius)
	return smd.NewOrbitFromOE(a, e, i, Ω, ω, ν, smd.Mars)
}

func main() {
	flag.Parse()
	availableCPUs := runtime.NumCPU()
	if cpus <= 0 || cpus > availableCPUs {
		cpus = availableCPUs
	}
	runtime.GOMAXPROCS(cpus)
	fmt.Printf("running on %d CPUs\n", cpus)

	if stepSize <= 0 {
		fmt.Println("step size must be positive")
		flag.Usage()
		return
	} else if stepSize <= 5 {
		fmt.Println("[WARNING] A small step size will take several days to iterate over all possibilities")
	}

	var orbitPtr func(i, Ω, ω, ν float64) *smd.Orbit
	planet = strings.ToLower(planet)
	switch planet {
	case "mars":
		orbitPtr = initMarsOrbit
	case "earth":
		orbitPtr = initEarthOrbit
	default:
		fmt.Printf("unsupported planet `%s`\n", planet)
		flag.Usage()
		return
	}

	fmt.Printf("Finding spirals leaving from %s\n", planet)

	//name := "spiral-mars"
	depart := time.Date(2018, 11, 8, 0, 0, 0, 0, time.UTC)
	chgframePath := "../refframes/chgframe.py"
	maxV := -1e3
	minV := +1e3
	var maxOrbit smd.Orbit
	var minOrbit smd.Orbit
	a, e, _, _, _, _, _, _, _ := orbitPtr(10, 10, 10, 10).Elements()
	rslts := make(chan string, 10)
	wg.Add(1)
	go streamResults(a, e, fmt.Sprintf("%s-%.0fstep", planet, stepSize), rslts)
	for i := 1.0; i < 90; i += stepSize {
		for Ω := 0.0; Ω < 360; Ω += stepSize {
			for ω := 0.0; ω < 360; ω += stepSize {
				for ν := 0.0; ν < 360; ν += stepSize {
					initOrbit := orbitPtr(i, Ω, ω, ν)
					astro := smd.NewMission(sc(), initOrbit, depart, depart.Add(-1), smd.Cartesian, smd.Perturbations{}, smd.ExportConfig{})
					astro.Propagate()

					// Run chgframe
					// We're now done so let's convert the position and velocity to heliocentric and check the output.
					R, V := initOrbit.RV()
					state := fmt.Sprintf("[%f,%f,%f,%f,%f,%f]", R[0], R[1], R[2], V[0], V[1], V[2])
					if debug {
						fmt.Printf("\n=== RUNNING CMD ===\npython %s -t J2000 -f IAU_Earth -e \"%s\" -s \"%s\"\n", chgframePath, astro.CurrentDT.Format(time.ANSIC), state)
					}
					cmd := exec.Command("python", chgframePath, "-t", "J2000", "-f", "IAU_Mars", "-e", astro.CurrentDT.Format(time.ANSIC), "-s", state)
					cmdOut, err := cmd.Output()
					if err != nil {
						fmt.Fprintln(os.Stderr, "Error converting orbit to helio ", err)
						os.Exit(1)
					}
					out := string(cmdOut)

					// Process output
					newState := strings.TrimSpace(string(out))
					// Cf. https://play.golang.org/p/g-a4idjhIb
					newState = newState[1 : len(newState)-1]
					components := strings.Split(newState, ",")
					var nR = make([]float64, 3)
					var nV = make([]float64, 3)
					for i := 0; i < 6; i++ {
						fl, err := strconv.ParseFloat(strings.TrimSpace(components[i]), 64)
						if err != nil {
							panic(err)
						}
						if i < 3 {
							nR[i] = fl
						} else {
							nV[i-3] = fl
						}
					}
					vNorm := math.Sqrt(math.Pow(nV[0], 2) + math.Pow(nV[1], 2) + math.Pow(nV[2], 2))
					// Add to TSV file
					rslts <- fmt.Sprintf("%f,%f,%f,%f,%f\n", vNorm, i, Ω, ω, ν)
					if vNorm > maxV {
						maxV = vNorm
						maxOrbit = *initMarsOrbit(i, Ω, ω, ν)
					} else if vNorm < minV {
						minV = vNorm
						minOrbit = *initMarsOrbit(i, Ω, ω, ν)
					}
					if debug {
						fmt.Printf("\nν=%f\t=>V=%+v\t|V|=%f\n", ν, nV, vNorm)
					}
				}
			}
		}
	}
	fmt.Printf("\n\n=== RESULT ===\n\nmaxV=%.3f km/s\t%s\nminV=%.3f km/s\t%s\n\n", maxV, maxOrbit, minV, minOrbit)
}

func streamResults(a, e float64, fn string, rslts <-chan string) {
	// Write CSV file.
	f, err := os.Create(fmt.Sprintf("./%s.csv", fn))
	if err != nil {
		panic(err)
	}
	defer f.Close()
	// Header
	f.WriteString(fmt.Sprintf("#a=%f km\te=%f\n#V(km/s), i (degrees), raan (degrees), arg peri (degrees),nu (degrees)\n", a, e))
	for {
		rslt, more := <-rslts
		if more {
			if _, err := f.WriteString(rslt); err != nil {
				panic(err)
			}
		} else {
			break
		}
	}
	f.Close()
	wg.Done()
}
<|endoftext|>


<commit_before>package cmd

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/pkg/browser"
	"github.com/spf13/cobra"
	"github.com/stormforger/cli/api"
	"github.com/stormforger/cli/api/testrun"
	"github.com/stormforger/cli/internal/esbundle"
	"github.com/stormforger/cli/internal/pflagutil"
	"github.com/stormforger/cli/internal/stringutil"
)

const defaultNFRData = `version: "0.1"
requirements:
- test.completed: true
- checks:
    select: success_rate
    test: ["=", 1]
- http.error_ratio:
    test: ["=", 0]
`

var (
	// testRunLaunchCmd represents the test run launch command
	testRunLaunchCmd = &cobra.Command{
		Use:   "launch <test-case-ref>",
		Short: "Create and launch a new test run",
		Long: fmt.Sprintf(`Create and launch a new test run based on given test case

  <test-case-ref> can be 'organisation-name/test-case-name' or 'test-case-uid'.

Examples
--------

* Launch by organisation and test case name

  forge test-case launch acme-inc/checkout

* Alternatively the test case UID can also be provided

  forge test-case launch xPSX5KXM

Configuration
-------------

You can specify configuration for a test run that will overwrite what is defined
in your JavaScript definition.

* Available cluster sizings:
  * %s

Available cluster regions are available at https://docs.stormforger.com/reference/test-cluster/#cluster-region

%s
`, strings.Join(validSizings, "\n  * "), bundlingHelpInfo),
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			if len(args) < 1 {
				log.Fatal("Missing argument: test case reference")
			}

			if len(args) > 1 {
				log.Fatal("Too many arguments")
			}

			if testRunLaunchOpts.ClusterRegion != "" && !stringutil.InSlice(testRunLaunchOpts.ClusterRegion, validRegions) {
				log.Fatalf("%s is not a valid region", testRunLaunchOpts.ClusterRegion)
			}

			if testRunLaunchOpts.ClusterSizing != "" && !stringutil.InSlice(testRunLaunchOpts.ClusterSizing, validSizings) {
				log.Fatalf("%s is not a valid sizing", testRunLaunchOpts.ClusterSizing)
			}
		},
		Run: func(cmd *cobra.Command, args []string) {
			client := NewClient()
			MainTestRunLaunch(client, args[0], testRunLaunchOpts)
		},
		ValidArgsFunction: completeOrgaAndCase,
	}

	testRunLaunchOpts testRunLaunchCmdOpts

	validRegions = []string{
		"ap-east-1",
		"ap-northeast-1",
		"ap-northeast-2",
		"ap-south-1",
		"ap-southeast-1",
		"ap-southeast-2",
		"ca-central-1",
		"eu-central-1",
		"eu-north-1",
		"eu-west-1",
		"eu-west-2",
		"eu-west-3",
		"sa-east-1",
		"us-east-1",
		"us-east-2",
		"us-west-1",
		"us-west-2",
	}

	validSizings = []string{
		"preflight",
		"tiny",
		"small",
		"medium",
		"large",
		"xlarge",
		"2xlarge",
	}
)

type testRunLaunchCmdOpts struct {
	OpenInBrowser bool

	Title                    string
	Notes                    string
	JavascriptDefinitionFile string

	ClusterRegion         string
	ClusterSizing         string
	Watch                 bool
	MaxWatchTime          time.Duration
	CheckNFR              string
	DisableGzip           bool
	SkipWait              bool
	DumpTraffic           bool
	SessionValidationMode bool
	Validate              bool
	TestRunIDOutputFile   string

	Define map[string]string
}

func init() {
	TestCaseCmd.AddCommand(testRunLaunchCmd)

	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.TestRunIDOutputFile, "uid-file", "", "Output file for the test-run id")

	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.OpenInBrowser, "open", false, "Open test run in browser")

	testRunLaunchCmd.Flags().StringVarP(&testRunLaunchOpts.Title, "title", "t", "", "Descriptive title of test run")
	testRunLaunchCmd.Flags().StringVarP(&testRunLaunchOpts.Notes, "notes", "n", "", "Longer description (Markdown supported)")

	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.ClusterRegion, "region", "", "Region to start test in")
	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.ClusterSizing, "sizing", "", "Cluster sizing to use")

	testRunLaunchCmd.Flags().BoolVarP(&testRunLaunchOpts.Watch, "watch", "w", false, "Automatically watch newly launched test run")
	testRunLaunchCmd.Flags().DurationVar(&testRunLaunchOpts.MaxWatchTime, "watch-timeout", 0, "Maximum duration in seconds to watch")

	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.JavascriptDefinitionFile, "test-case-file", "", "Update the test-case definition from this file before the launch")
	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.CheckNFR, "nfr-check-file", "", "Check test result against NFR definition (implies --watch)")

	// options for debugging
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.DisableGzip, "disable-gzip", false, "Globally disable gzip")
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.SkipWait, "skip-wait", false, "Ignore defined waits")
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.DumpTraffic, "dump-traffic", false, "Create traffic dump")
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.SessionValidationMode, "session-validation-mode", false, "Enable session validation mode")
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.Validate, "validate", false, "Perform validation run")

	// bundling
	testRunLaunchCmd.PersistentFlags().Var(&pflagutil.KeyValueFlag{Map: &testRunLaunchOpts.Define}, "define", "Defines a list of K=V while parsing: debug=false")

	// hints for completion of flags
	testRunLaunchCmd.MarkFlagFilename("test-case-file", "js")
	testRunLaunchCmd.MarkFlagFilename("nfr-check-file", "yml", "yaml")
	testRunLaunchCmd.RegisterFlagCompletionFunc("region", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		return stringutil.FilterByPrefix(toComplete, validRegions), cobra.ShellCompDirectiveDefault
	})
	testRunLaunchCmd.RegisterFlagCompletionFunc("sizing", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		return stringutil.FilterByPrefix(toComplete, validSizings), cobra.ShellCompDirectiveDefault
	})

}

// MainTestRunLaunch runs a test-case and allows watching and validation that test-run.
// testCaseSpec is required and specifies the test-case to launch.
func MainTestRunLaunch(client *api.Client, testCaseSpec string, testRunLaunchOpts testRunLaunchCmdOpts) {
	var mapper esbundle.SourceMapper

	testCaseUID := mustLookupTestCase(client, testCaseSpec)

	launchOptions := api.TestRunLaunchOptions{
		Title: testRunLaunchOpts.Title,
		Notes: testRunLaunchOpts.Notes,

		ClusterRegion:         testRunLaunchOpts.ClusterRegion,
		ClusterSizing:         testRunLaunchOpts.ClusterSizing,
		DisableGzip:           testRunLaunchOpts.DisableGzip,
		SkipWait:              testRunLaunchOpts.SkipWait,
		DumpTraffic:           testRunLaunchOpts.DumpTraffic,
		SessionValidationMode: testRunLaunchOpts.SessionValidationMode,
	}
	if testRunLaunchOpts.JavascriptDefinitionFile != "" {
		bundler := testCaseFileBundler{Defines: testRunLaunchOpts.Define}
		bundle, err := bundler.Bundle(testRunLaunchOpts.JavascriptDefinitionFile, "test-case.js")
		if err != nil {
			log.Fatalf("Failed to open %s: %v", bundle.Name, err)
		}

		mapper = bundle.Mapper
		launchOptions.JavascriptDefinition.Filename = bundle.Name
		launchOptions.JavascriptDefinition.Reader = bundle.Content
	}

	if testRunLaunchOpts.Validate {
		launchOptions.SessionValidationMode = true
		launchOptions.ClusterSizing = "preflight"
	}

	status, response, err := client.TestRunCreate(testCaseUID, launchOptions)
	if err != nil {
		log.Fatal(err)
	}

	if !status {
		errorMeta, err := api.ErrorDecoder{SourceMapper: mapper}.UnmarshalErrorMeta(strings.NewReader(response))
		if err != nil {
			log.Fatal(err)
		}

		printValidationResultHuman(os.Stderr, status, errorMeta)
		cmdExit(status)
	}

	testRun, err := testrun.UnmarshalSingle(strings.NewReader(response))
	if err != nil {
		log.Fatal(err)
	}

	if testRunLaunchOpts.TestRunIDOutputFile != "" {
		f := testRunLaunchOpts.TestRunIDOutputFile
		err := ioutil.WriteFile(f, []byte(testRun.ID), 0644)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to write file: %v\n", err)
			os.Exit(1)
		}
	}

	if rootOpts.OutputFormat == "json" {
		fmt.Println(string(response))
	} else {
		// FIXME can we integrate this into testrun.UnmarshalSingle somehow?
		meta, err := api.UnmarshalMeta(strings.NewReader(response))
		if err != nil {
			log.Fatal(err)
		}

		if launchOptions.JavascriptDefinition.Reader != nil {
			fmt.Println("Test-Case successfully updated")
		}

		fmt.Printf(`Launching test %s
UID: %s
Web URL: %s
`,
			testRun.Scope,
			testRun.ID,
			meta.Links.SelfWeb,
		)

		fmt.Printf("Configuration: %s cluster in %s\n", testRun.TestConfiguration.ClusterSizing, testRun.TestConfiguration.ClusterRegion)

		if testRun.TestConfiguration.DisableGzip {
			fmt.Print("  [\u2713] Disabled GZIP\n")
		}
		if testRun.TestConfiguration.SkipWait {
			fmt.Print("  [\u2713] Skip Waits\n")
		}
		if testRun.TestConfiguration.DumpTrafficFull {
			fmt.Print("  [\u2713] Traffic Dump\n")
		}
		if testRun.TestConfiguration.SessionValidationMode {
			fmt.Print("  [\u2713] Session Validation Mode\n")
		}

		if testRunLaunchOpts.OpenInBrowser {
			fmt.Printf("Opening %s in browser...\n", meta.Links.SelfWeb)
			err = browser.OpenURL(meta.Links.SelfWeb)
			if err != nil {
				log.Fatal(err)
			}
		}
	}

	if testRunLaunchOpts.Watch || testRunLaunchOpts.CheckNFR != "" || testRunLaunchOpts.Validate {
		if rootOpts.OutputFormat != "json" {
			fmt.Println("\nWatching...")
		}

		watchTestRun(testRun.ID, testRunLaunchOpts.MaxWatchTime.Round(time.Second).Seconds(), rootOpts.OutputFormat)

		if testRunLaunchOpts.CheckNFR != "" || testRunLaunchOpts.Validate {
			fmt.Println("Test finished, running non-functional checks...")

			fileName := ""
			var nfrData io.Reader
			if testRunLaunchOpts.CheckNFR != "" {
				fileName = filepath.Base(testRunLaunchOpts.CheckNFR)
				nfrData, err = os.OpenFile(testRunLaunchOpts.CheckNFR, os.O_RDONLY, 0755)
				if err != nil {
					log.Fatal(err)
				}
			} else {
				fileName = "validation.yml"
				nfrData = bytes.NewBufferString(defaultNFRData)
			}

			runNfrCheck(*client, testRun.ID, fileName, nfrData)
		} else {
			result := fetchTestRun(*client, testRun.ID)
			fmt.Println(string(result))
		}
	}
}
<commit_msg>fix: Print input filename when bundling fails (#186)<commit_after>package cmd

import (
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"time"

	"github.com/pkg/browser"
	"github.com/spf13/cobra"
	"github.com/stormforger/cli/api"
	"github.com/stormforger/cli/api/testrun"
	"github.com/stormforger/cli/internal/esbundle"
	"github.com/stormforger/cli/internal/pflagutil"
	"github.com/stormforger/cli/internal/stringutil"
)

const defaultNFRData = `version: "0.1"
requirements:
- test.completed: true
- checks:
    select: success_rate
    test: ["=", 1]
- http.error_ratio:
    test: ["=", 0]
`

var (
	// testRunLaunchCmd represents the test run launch command
	testRunLaunchCmd = &cobra.Command{
		Use:   "launch <test-case-ref>",
		Short: "Create and launch a new test run",
		Long: fmt.Sprintf(`Create and launch a new test run based on given test case

  <test-case-ref> can be 'organisation-name/test-case-name' or 'test-case-uid'.

Examples
--------

* Launch by organisation and test case name

  forge test-case launch acme-inc/checkout

* Alternatively the test case UID can also be provided

  forge test-case launch xPSX5KXM

Configuration
-------------

You can specify configuration for a test run that will overwrite what is defined
in your JavaScript definition.

* Available cluster sizings:
  * %s

Available cluster regions are available at https://docs.stormforger.com/reference/test-cluster/#cluster-region

%s
`, strings.Join(validSizings, "\n  * "), bundlingHelpInfo),
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			if len(args) < 1 {
				log.Fatal("Missing argument: test case reference")
			}

			if len(args) > 1 {
				log.Fatal("Too many arguments")
			}

			if testRunLaunchOpts.ClusterRegion != "" && !stringutil.InSlice(testRunLaunchOpts.ClusterRegion, validRegions) {
				log.Fatalf("%s is not a valid region", testRunLaunchOpts.ClusterRegion)
			}

			if testRunLaunchOpts.ClusterSizing != "" && !stringutil.InSlice(testRunLaunchOpts.ClusterSizing, validSizings) {
				log.Fatalf("%s is not a valid sizing", testRunLaunchOpts.ClusterSizing)
			}
		},
		Run: func(cmd *cobra.Command, args []string) {
			client := NewClient()
			MainTestRunLaunch(client, args[0], testRunLaunchOpts)
		},
		ValidArgsFunction: completeOrgaAndCase,
	}

	testRunLaunchOpts testRunLaunchCmdOpts

	validRegions = []string{
		"ap-east-1",
		"ap-northeast-1",
		"ap-northeast-2",
		"ap-south-1",
		"ap-southeast-1",
		"ap-southeast-2",
		"ca-central-1",
		"eu-central-1",
		"eu-north-1",
		"eu-west-1",
		"eu-west-2",
		"eu-west-3",
		"sa-east-1",
		"us-east-1",
		"us-east-2",
		"us-west-1",
		"us-west-2",
	}

	validSizings = []string{
		"preflight",
		"tiny",
		"small",
		"medium",
		"large",
		"xlarge",
		"2xlarge",
	}
)

type testRunLaunchCmdOpts struct {
	OpenInBrowser bool

	Title                    string
	Notes                    string
	JavascriptDefinitionFile string

	ClusterRegion         string
	ClusterSizing         string
	Watch                 bool
	MaxWatchTime          time.Duration
	CheckNFR              string
	DisableGzip           bool
	SkipWait              bool
	DumpTraffic           bool
	SessionValidationMode bool
	Validate              bool
	TestRunIDOutputFile   string

	Define map[string]string
}

func init() {
	TestCaseCmd.AddCommand(testRunLaunchCmd)

	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.TestRunIDOutputFile, "uid-file", "", "Output file for the test-run id")

	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.OpenInBrowser, "open", false, "Open test run in browser")

	testRunLaunchCmd.Flags().StringVarP(&testRunLaunchOpts.Title, "title", "t", "", "Descriptive title of test run")
	testRunLaunchCmd.Flags().StringVarP(&testRunLaunchOpts.Notes, "notes", "n", "", "Longer description (Markdown supported)")

	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.ClusterRegion, "region", "", "Region to start test in")
	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.ClusterSizing, "sizing", "", "Cluster sizing to use")

	testRunLaunchCmd.Flags().BoolVarP(&testRunLaunchOpts.Watch, "watch", "w", false, "Automatically watch newly launched test run")
	testRunLaunchCmd.Flags().DurationVar(&testRunLaunchOpts.MaxWatchTime, "watch-timeout", 0, "Maximum duration in seconds to watch")

	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.JavascriptDefinitionFile, "test-case-file", "", "Update the test-case definition from this file before the launch")
	testRunLaunchCmd.Flags().StringVar(&testRunLaunchOpts.CheckNFR, "nfr-check-file", "", "Check test result against NFR definition (implies --watch)")

	// options for debugging
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.DisableGzip, "disable-gzip", false, "Globally disable gzip")
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.SkipWait, "skip-wait", false, "Ignore defined waits")
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.DumpTraffic, "dump-traffic", false, "Create traffic dump")
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.SessionValidationMode, "session-validation-mode", false, "Enable session validation mode")
	testRunLaunchCmd.Flags().BoolVar(&testRunLaunchOpts.Validate, "validate", false, "Perform validation run")

	// bundling
	testRunLaunchCmd.PersistentFlags().Var(&pflagutil.KeyValueFlag{Map: &testRunLaunchOpts.Define}, "define", "Defines a list of K=V while parsing: debug=false")

	// hints for completion of flags
	testRunLaunchCmd.MarkFlagFilename("test-case-file", "js")
	testRunLaunchCmd.MarkFlagFilename("nfr-check-file", "yml", "yaml")
	testRunLaunchCmd.RegisterFlagCompletionFunc("region", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		return stringutil.FilterByPrefix(toComplete, validRegions), cobra.ShellCompDirectiveDefault
	})
	testRunLaunchCmd.RegisterFlagCompletionFunc("sizing", func(cmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
		return stringutil.FilterByPrefix(toComplete, validSizings), cobra.ShellCompDirectiveDefault
	})

}

// MainTestRunLaunch runs a test-case and allows watching and validation that test-run.
// testCaseSpec is required and specifies the test-case to launch.
func MainTestRunLaunch(client *api.Client, testCaseSpec string, testRunLaunchOpts testRunLaunchCmdOpts) {
	var mapper esbundle.SourceMapper

	testCaseUID := mustLookupTestCase(client, testCaseSpec)

	launchOptions := api.TestRunLaunchOptions{
		Title: testRunLaunchOpts.Title,
		Notes: testRunLaunchOpts.Notes,

		ClusterRegion:         testRunLaunchOpts.ClusterRegion,
		ClusterSizing:         testRunLaunchOpts.ClusterSizing,
		DisableGzip:           testRunLaunchOpts.DisableGzip,
		SkipWait:              testRunLaunchOpts.SkipWait,
		DumpTraffic:           testRunLaunchOpts.DumpTraffic,
		SessionValidationMode: testRunLaunchOpts.SessionValidationMode,
	}
	if testRunLaunchOpts.JavascriptDefinitionFile != "" {
		bundler := testCaseFileBundler{Defines: testRunLaunchOpts.Define}
		bundle, err := bundler.Bundle(testRunLaunchOpts.JavascriptDefinitionFile, "test-case.js")
		if err != nil {
			log.Fatalf("Failed to bundle %s: %v", testRunLaunchOpts.JavascriptDefinitionFile, err)
		}

		mapper = bundle.Mapper
		launchOptions.JavascriptDefinition.Filename = bundle.Name
		launchOptions.JavascriptDefinition.Reader = bundle.Content
	}

	if testRunLaunchOpts.Validate {
		launchOptions.SessionValidationMode = true
		launchOptions.ClusterSizing = "preflight"
	}

	status, response, err := client.TestRunCreate(testCaseUID, launchOptions)
	if err != nil {
		log.Fatal(err)
	}

	if !status {
		errorMeta, err := api.ErrorDecoder{SourceMapper: mapper}.UnmarshalErrorMeta(strings.NewReader(response))
		if err != nil {
			log.Fatal(err)
		}

		printValidationResultHuman(os.Stderr, status, errorMeta)
		cmdExit(status)
	}

	testRun, err := testrun.UnmarshalSingle(strings.NewReader(response))
	if err != nil {
		log.Fatal(err)
	}

	if testRunLaunchOpts.TestRunIDOutputFile != "" {
		f := testRunLaunchOpts.TestRunIDOutputFile
		err := ioutil.WriteFile(f, []byte(testRun.ID), 0644)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to write file: %v\n", err)
			os.Exit(1)
		}
	}

	if rootOpts.OutputFormat == "json" {
		fmt.Println(string(response))
	} else {
		// FIXME can we integrate this into testrun.UnmarshalSingle somehow?
		meta, err := api.UnmarshalMeta(strings.NewReader(response))
		if err != nil {
			log.Fatal(err)
		}

		if launchOptions.JavascriptDefinition.Reader != nil {
			fmt.Println("Test-Case successfully updated")
		}

		fmt.Printf(`Launching test %s
UID: %s
Web URL: %s
`,
			testRun.Scope,
			testRun.ID,
			meta.Links.SelfWeb,
		)

		fmt.Printf("Configuration: %s cluster in %s\n", testRun.TestConfiguration.ClusterSizing, testRun.TestConfiguration.ClusterRegion)

		if testRun.TestConfiguration.DisableGzip {
			fmt.Print("  [\u2713] Disabled GZIP\n")
		}
		if testRun.TestConfiguration.SkipWait {
			fmt.Print("  [\u2713] Skip Waits\n")
		}
		if testRun.TestConfiguration.DumpTrafficFull {
			fmt.Print("  [\u2713] Traffic Dump\n")
		}
		if testRun.TestConfiguration.SessionValidationMode {
			fmt.Print("  [\u2713] Session Validation Mode\n")
		}

		if testRunLaunchOpts.OpenInBrowser {
			fmt.Printf("Opening %s in browser...\n", meta.Links.SelfWeb)
			err = browser.OpenURL(meta.Links.SelfWeb)
			if err != nil {
				log.Fatal(err)
			}
		}
	}

	if testRunLaunchOpts.Watch || testRunLaunchOpts.CheckNFR != "" || testRunLaunchOpts.Validate {
		if rootOpts.OutputFormat != "json" {
			fmt.Println("\nWatching...")
		}

		watchTestRun(testRun.ID, testRunLaunchOpts.MaxWatchTime.Round(time.Second).Seconds(), rootOpts.OutputFormat)

		if testRunLaunchOpts.CheckNFR != "" || testRunLaunchOpts.Validate {
			fmt.Println("Test finished, running non-functional checks...")

			fileName := ""
			var nfrData io.Reader
			if testRunLaunchOpts.CheckNFR != "" {
				fileName = filepath.Base(testRunLaunchOpts.CheckNFR)
				nfrData, err = os.OpenFile(testRunLaunchOpts.CheckNFR, os.O_RDONLY, 0755)
				if err != nil {
					log.Fatal(err)
				}
			} else {
				fileName = "validation.yml"
				nfrData = bytes.NewBufferString(defaultNFRData)
			}

			runNfrCheck(*client, testRun.ID, fileName, nfrData)
		} else {
			result := fetchTestRun(*client, testRun.ID)
			fmt.Println(string(result))
		}
	}
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
)

const version = "0.1.3"

func main() {
	up := flag.Bool("update", false, "update command")
	flag.Parse()

	fmt.Printf("version %s\n", version)

	var code int
	if *up {
		if out, err := update(srcPath); err != nil {
			fmt.Printf("Update fail: %v\n", err)
			fmt.Println(string(out))
			os.Exit(1)
		}
		fmt.Println("Update done.")
		os.Exit(0)
	}

	fmt.Println("Command done.")

	os.Exit(code)
}

const srcPath = "github.com/dvrkps/dojo/cmdupdate"

func update(srcPath string) ([]byte, error) {
	cmd := exec.Command("go", "get", "-u", srcPath)
	return cmd.CombinedOutput()
}
<commit_msg>cmdupdate: clean constants<commit_after>package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
)

const (
	version = "0.1.3"

	srcPath = "github.com/dvrkps/dojo/cmdupdate"
)

func main() {
	up := flag.Bool("update", false, "update command")
	flag.Parse()

	fmt.Printf("version %s\n", version)

	var code int
	if *up {
		if out, err := update(srcPath); err != nil {
			fmt.Printf("Update fail: %v\n", err)
			fmt.Println(string(out))
			os.Exit(1)
		}
		fmt.Println("Update done.")
		os.Exit(0)
	}

	fmt.Println("Command done.")

	os.Exit(code)
}

func update(srcPath string) ([]byte, error) {
	cmd := exec.Command("go", "get", "-u", srcPath)
	return cmd.CombinedOutput()
}
<|endoftext|>


<commit_before>package main

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
)

func TestDiff(t *testing.T) {
	wd, _ := os.Getwd()
	td := filepath.Join(wd, "test")

	dirs, err := ioutil.ReadDir(td)
	if err != nil {
		t.Fatal(err)
	}
	for _, fi := range dirs {
		if !fi.IsDir() {
			continue
		}

		dir := filepath.Join(td, fi.Name())
		actualOutputDir := filepath.Join(dir, "actual_output")

		err := os.RemoveAll(actualOutputDir)
		if err != nil {
			t.Fatal(err)
		}

		err = os.MkdirAll(actualOutputDir, 0777)
		if err != nil {
			t.Fatal(err)
		}

		runProto(t, dir)
		runDiff(t, dir)
	}

}

func runProto(t *testing.T, dir string) {
	cmd := exec.Command("protoc", "--elm_out=../actual_output", "test.proto")
	cmd.Dir = filepath.Join(dir, "input")
	t.Logf("cmd: %v", cmd)
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("Error: %v, %v", err, string(out))
	}
}

func runDiff(t *testing.T, dir string) {
	cmd := exec.Command("diff", "-y", "expected_output", "actual_output")
	cmd.Dir = dir
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("Error: %v, %v", err, string(out))
	}
}
<commit_msg>Print protoc output in verbose tests<commit_after>package main

import (
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"testing"
)

func TestDiff(t *testing.T) {
	wd, _ := os.Getwd()
	td := filepath.Join(wd, "test")

	dirs, err := ioutil.ReadDir(td)
	if err != nil {
		t.Fatal(err)
	}
	for _, fi := range dirs {
		if !fi.IsDir() {
			continue
		}

		dir := filepath.Join(td, fi.Name())
		actualOutputDir := filepath.Join(dir, "actual_output")

		err := os.RemoveAll(actualOutputDir)
		if err != nil {
			t.Fatal(err)
		}

		err = os.MkdirAll(actualOutputDir, 0777)
		if err != nil {
			t.Fatal(err)
		}

		runProto(t, dir)
		runDiff(t, dir)
	}

}

func runProto(t *testing.T, dir string) {
	cmd := exec.Command("protoc", "--elm_out=../actual_output", "test.proto")
	cmd.Dir = filepath.Join(dir, "input")
	t.Logf("cmd: %v", cmd)
	out, err := cmd.CombinedOutput()
	t.Logf("Output: %s", out)
	if err != nil {
		t.Fatalf("Error: %v", err)
	}
}

func runDiff(t *testing.T, dir string) {
	cmd := exec.Command("diff", "-y", "expected_output", "actual_output")
	cmd.Dir = dir
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("Error: %v, %v", err, string(out))
	}
}
<|endoftext|>