<commit_before>package ebuf

import (
	"fmt"
	"regexp/syntax"
	"strings"
)

type Scanner struct {
	program      *syntax.Prog
	captureNames []string
	threads      []*_Thread
	pos          int
	Captures     []Capture
}

type _Thread struct {
	pc       uint32
	captures map[uint32]int
}

type Capture struct {
	Name  string
	Begin Cursor
	End   Cursor
}

func (b *Buffer) SetScanner(rules map[string][]string) {
	b.Scanners = []*Scanner{
		NewScanner(rules),
	}
}

func NewScanner(rules map[string][]string) *Scanner {
	exprs := []string{}
	for name, subs := range rules {
		exprs = append(exprs, fmt.Sprintf(`(?P<%s>%s)`, name,
			strings.Join(subs, "|")))
	}
	expr := strings.Join(exprs, "|")

	re, err := syntax.Parse(expr, syntax.Perl)
	if err != nil {
		panic(fmt.Errorf("rule syntax error %v", err))
	}
	capNames := re.CapNames()
	re = re.Simplify()
	program, _ := syntax.Compile(re)

	return &Scanner{
		program:      program,
		captureNames: capNames,
		threads: []*_Thread{
			&_Thread{
				pc:       uint32(program.Start),
				captures: make(map[uint32]int),
			},
		},
	}
}

func (s *Scanner) FeedRune(r rune, l int) {
	threads := s.threads
	blockingThreads := []*_Thread{}
loop:
	for len(threads) > 0 {
		thread := threads[len(threads)-1]
		threads = threads[:len(threads)-1]
		runeConsumed := false
		pc := thread.pc
		inst := s.program.Inst[pc]
	runLoop:
		for {
			switch inst.Op {
			case syntax.InstAlt, syntax.InstAltMatch:
				// new thread
				captures := make(map[uint32]int, len(thread.captures))
				for nameIndex, pos := range thread.captures {
					captures[nameIndex] = pos
				}
				threads = append(threads, &_Thread{
					pc:       inst.Arg,
					captures: captures,
				})
				pc = inst.Out
				inst = s.program.Inst[pc]
			case syntax.InstCapture:
				nameIndex := inst.Arg / 2
				name := s.captureNames[nameIndex]
				if name != "" { // skip nameless groups
					if pos, ok := thread.captures[nameIndex]; ok { // end of named group
						s.Captures = append(s.Captures, Capture{
							Name:  s.captureNames[nameIndex],
							Begin: Cursor(pos),
							End:   Cursor(s.pos + l),
						})
						delete(thread.captures, nameIndex)
					} else {
						thread.captures[nameIndex] = s.pos
					}
				}
				pc = inst.Out
				inst = s.program.Inst[pc]
			case syntax.InstEmptyWidth:
				panic("empty string pattern is not supported")
			case syntax.InstMatch, syntax.InstFail: // clear all threads, restart
				blockingThreads = nil
				break loop
			case syntax.InstNop:
				pc = inst.Out
				inst = s.program.Inst[pc]
			case syntax.InstRune1, syntax.InstRune, syntax.InstRuneAny, syntax.InstRuneAnyNotNL:
				if runeConsumed { // thread blocks
					thread.pc = pc
					blockingThreads = append(blockingThreads, thread)
					break runLoop
				} else { // consume rune
					if inst.Op == syntax.InstRune1 && r == inst.Rune[0] ||
						inst.Op == syntax.InstRune && inst.MatchRune(r) ||
						inst.Op == syntax.InstRuneAny ||
						inst.Op == syntax.InstRuneAnyNotNL && r != '\n' { // rune matchs
						runeConsumed = true
						pc = inst.Out
						inst = s.program.Inst[pc]
					} else { // thread dies
						break runLoop
					}
				}
			}
		}
	}

	if len(blockingThreads) > 0 {
		s.threads = blockingThreads
	} else { // restart
		s.threads = []*_Thread{
			{
				pc:       uint32(s.program.Start),
				captures: make(map[uint32]int),
			},
		}
	}

	s.pos += l
}
<commit_msg>remove one allocation in Scanner.FeedRune<commit_after>package ebuf

import (
	"fmt"
	"regexp/syntax"
	"strings"
)

type Scanner struct {
	program      *syntax.Prog
	captureNames []string
	threads      []*_Thread
	tmpThreads   []*_Thread
	pos          int
	Captures     []Capture
}

type _Thread struct {
	pc       uint32
	captures map[uint32]int
}

type Capture struct {
	Name  string
	Begin Cursor
	End   Cursor
}

func (b *Buffer) SetScanner(rules map[string][]string) {
	b.Scanners = []*Scanner{
		NewScanner(rules),
	}
}

func NewScanner(rules map[string][]string) *Scanner {
	exprs := []string{}
	for name, subs := range rules {
		exprs = append(exprs, fmt.Sprintf(`(?P<%s>%s)`, name,
			strings.Join(subs, "|")))
	}
	expr := strings.Join(exprs, "|")

	re, err := syntax.Parse(expr, syntax.Perl)
	if err != nil {
		panic(fmt.Errorf("rule syntax error %v", err))
	}
	capNames := re.CapNames()
	re = re.Simplify()
	program, _ := syntax.Compile(re)

	return &Scanner{
		program:      program,
		captureNames: capNames,
		threads: []*_Thread{
			&_Thread{
				pc:       uint32(program.Start),
				captures: make(map[uint32]int),
			},
		},
	}
}

func (s *Scanner) FeedRune(r rune, l int) {
	threads := s.threads
	blockingThreads := s.tmpThreads
loop:
	for len(threads) > 0 {
		thread := threads[len(threads)-1]
		threads = threads[:len(threads)-1]
		runeConsumed := false
		pc := thread.pc
		inst := s.program.Inst[pc]
	runLoop:
		for {
			switch inst.Op {
			case syntax.InstAlt, syntax.InstAltMatch:
				// new thread
				captures := make(map[uint32]int, len(thread.captures))
				for nameIndex, pos := range thread.captures {
					captures[nameIndex] = pos
				}
				threads = append(threads, &_Thread{
					pc:       inst.Arg,
					captures: captures,
				})
				pc = inst.Out
				inst = s.program.Inst[pc]
			case syntax.InstCapture:
				nameIndex := inst.Arg / 2
				name := s.captureNames[nameIndex]
				if name != "" { // skip nameless groups
					if pos, ok := thread.captures[nameIndex]; ok { // end of named group
						s.Captures = append(s.Captures, Capture{
							Name:  s.captureNames[nameIndex],
							Begin: Cursor(pos),
							End:   Cursor(s.pos + l),
						})
						delete(thread.captures, nameIndex)
					} else {
						thread.captures[nameIndex] = s.pos
					}
				}
				pc = inst.Out
				inst = s.program.Inst[pc]
			case syntax.InstEmptyWidth:
				panic("empty string pattern is not supported")
			case syntax.InstMatch, syntax.InstFail: // clear all threads, restart
				blockingThreads = nil
				break loop
			case syntax.InstNop:
				pc = inst.Out
				inst = s.program.Inst[pc]
			case syntax.InstRune1, syntax.InstRune, syntax.InstRuneAny, syntax.InstRuneAnyNotNL:
				if runeConsumed { // thread blocks
					thread.pc = pc
					blockingThreads = append(blockingThreads, thread)
					break runLoop
				} else { // consume rune
					if inst.Op == syntax.InstRune1 && r == inst.Rune[0] ||
						inst.Op == syntax.InstRune && inst.MatchRune(r) ||
						inst.Op == syntax.InstRuneAny ||
						inst.Op == syntax.InstRuneAnyNotNL && r != '\n' { // rune matchs
						runeConsumed = true
						pc = inst.Out
						inst = s.program.Inst[pc]
					} else { // thread dies
						break runLoop
					}
				}
			}
		}
	}
	s.tmpThreads = threads

	if len(blockingThreads) > 0 {
		s.threads = blockingThreads
	} else { // restart
		s.threads = []*_Thread{
			{
				pc:       uint32(s.program.Start),
				captures: make(map[uint32]int),
			},
		}
	}

	s.pos += l
}
<|endoftext|>


<commit_before>/*

   Copyright 2016 Wenhui Shen <www.webx.top>

   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 session

import (
	"github.com/webx-top/echo"
)

func Sessions(name string, store Store) echo.MiddlewareFunc {
	return echo.MiddlewareFunc(func(h echo.Handler) echo.Handler {
		return echo.HandlerFunc(func(c echo.Context) error {
			s := NewMySession(store, name, c)
			c.InitSession(s)
			err := h.Handle(c)
			s.Save()
			return err
		})
	})
}

func Middleware(options *echo.SessionOptions, setting interface{}) echo.MiddlewareFunc {
	store := StoreEngine(options, setting)
	return Sessions(options.Name, store)
}
<commit_msg>update<commit_after>/*

   Copyright 2016 Wenhui Shen <www.webx.top>

   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 session

import (
	"github.com/webx-top/echo"
)

func Sessions(name string, store Store) echo.MiddlewareFuncd {
	return func(h echo.Handler) echo.HandlerFunc {
		return func(c echo.Context) error {
			s := NewMySession(store, name, c)
			c.InitSession(s)
			err := h.Handle(c)
			s.Save()
			return err
		}
	}
}

func Middleware(options *echo.SessionOptions, setting interface{}) echo.MiddlewareFuncd {
	store := StoreEngine(options, setting)
	return Sessions(options.Name, store)
}
<|endoftext|>


<commit_before>package main

import (
	"os/exec"
	"strings"

	"github.com/go-check/check"
)

// ensure that an added file shows up in docker diff
func (s *DockerSuite) TestDiffFilenameShownInOutput(c *check.C) {
	containerCmd := `echo foo > /root/bar`
	runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sh", "-c", containerCmd)
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatalf("failed to start the container: %s, %v", out, err)
	}

	cleanCID := strings.TrimSpace(out)

	diffCmd := exec.Command(dockerBinary, "diff", cleanCID)
	out, _, err = runCommandWithOutput(diffCmd)
	if err != nil {
		c.Fatalf("failed to run diff: %s %v", out, err)
	}

	found := false
	for _, line := range strings.Split(out, "\n") {
		if strings.Contains("A /root/bar", line) {
			found = true
			break
		}
	}
	if !found {
		c.Errorf("couldn't find the new file in docker diff's output: %v", out)
	}
}

// test to ensure GH #3840 doesn't occur any more
func (s *DockerSuite) TestDiffEnsureDockerinitFilesAreIgnored(c *check.C) {
	// this is a list of files which shouldn't show up in `docker diff`
	dockerinitFiles := []string{"/etc/resolv.conf", "/etc/hostname", "/etc/hosts", "/.dockerinit", "/.dockerenv"}

	// we might not run into this problem from the first run, so start a few containers
	for i := 0; i < 20; i++ {
		containerCmd := `echo foo > /root/bar`
		runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sh", "-c", containerCmd)
		out, _, err := runCommandWithOutput(runCmd)
		if err != nil {
			c.Fatal(out, err)
		}

		cleanCID := strings.TrimSpace(out)

		diffCmd := exec.Command(dockerBinary, "diff", cleanCID)
		out, _, err = runCommandWithOutput(diffCmd)
		if err != nil {
			c.Fatalf("failed to run diff: %s, %v", out, err)
		}

		for _, filename := range dockerinitFiles {
			if strings.Contains(out, filename) {
				c.Errorf("found file which should've been ignored %v in diff output", filename)
			}
		}
	}
}

func (s *DockerSuite) TestDiffEnsureOnlyKmsgAndPtmx(c *check.C) {
	runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "0")
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	cleanCID := strings.TrimSpace(out)

	diffCmd := exec.Command(dockerBinary, "diff", cleanCID)
	out, _, err = runCommandWithOutput(diffCmd)
	if err != nil {
		c.Fatalf("failed to run diff: %s, %v", out, err)
	}

	expected := map[string]bool{
		"C /dev":         true,
		"A /dev/full":    true, // busybox
		"C /dev/ptmx":    true, // libcontainer
		"A /dev/kmsg":    true, // lxc
		"A /dev/fd":      true,
		"A /dev/fuse":    true,
		"A /dev/ptmx":    true,
		"A /dev/null":    true,
		"A /dev/random":  true,
		"A /dev/stdout":  true,
		"A /dev/stderr":  true,
		"A /dev/tty1":    true,
		"A /dev/stdin":   true,
		"A /dev/tty":     true,
		"A /dev/urandom": true,
		"A /dev/zero":    true,
	}

	for _, line := range strings.Split(out, "\n") {
		if line != "" && !expected[line] {
			c.Errorf("%q is shown in the diff but shouldn't", line)
		}
	}
}
<commit_msg>fixed TestDiffEnsureDockerinitFilesAreIgnored is too long #12672<commit_after>package main

import (
	"os/exec"
	"strings"

	"github.com/go-check/check"
)

// ensure that an added file shows up in docker diff
func (s *DockerSuite) TestDiffFilenameShownInOutput(c *check.C) {
	containerCmd := `echo foo > /root/bar`
	runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sh", "-c", containerCmd)
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatalf("failed to start the container: %s, %v", out, err)
	}

	cleanCID := strings.TrimSpace(out)

	diffCmd := exec.Command(dockerBinary, "diff", cleanCID)
	out, _, err = runCommandWithOutput(diffCmd)
	if err != nil {
		c.Fatalf("failed to run diff: %s %v", out, err)
	}

	found := false
	for _, line := range strings.Split(out, "\n") {
		if strings.Contains("A /root/bar", line) {
			found = true
			break
		}
	}
	if !found {
		c.Errorf("couldn't find the new file in docker diff's output: %v", out)
	}
}

// test to ensure GH #3840 doesn't occur any more
func (s *DockerSuite) TestDiffEnsureDockerinitFilesAreIgnored(c *check.C) {
	// this is a list of files which shouldn't show up in `docker diff`
	dockerinitFiles := []string{"/etc/resolv.conf", "/etc/hostname", "/etc/hosts", "/.dockerinit", "/.dockerenv"}
	containerCount := 5

	// we might not run into this problem from the first run, so start a few containers
	for i := 0; i < containerCount; i++ {
		containerCmd := `echo foo > /root/bar`
		runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sh", "-c", containerCmd)
		out, _, err := runCommandWithOutput(runCmd)

		if err != nil {
			c.Fatal(out, err)
		}

		cleanCID := strings.TrimSpace(out)

		diffCmd := exec.Command(dockerBinary, "diff", cleanCID)
		out, _, err = runCommandWithOutput(diffCmd)
		if err != nil {
			c.Fatalf("failed to run diff: %s, %v", out, err)
		}

		for _, filename := range dockerinitFiles {
			if strings.Contains(out, filename) {
				c.Errorf("found file which should've been ignored %v in diff output", filename)
			}
		}
	}
}

func (s *DockerSuite) TestDiffEnsureOnlyKmsgAndPtmx(c *check.C) {
	runCmd := exec.Command(dockerBinary, "run", "-d", "busybox", "sleep", "0")
	out, _, err := runCommandWithOutput(runCmd)
	if err != nil {
		c.Fatal(out, err)
	}

	cleanCID := strings.TrimSpace(out)

	diffCmd := exec.Command(dockerBinary, "diff", cleanCID)
	out, _, err = runCommandWithOutput(diffCmd)
	if err != nil {
		c.Fatalf("failed to run diff: %s, %v", out, err)
	}

	expected := map[string]bool{
		"C /dev":         true,
		"A /dev/full":    true, // busybox
		"C /dev/ptmx":    true, // libcontainer
		"A /dev/kmsg":    true, // lxc
		"A /dev/fd":      true,
		"A /dev/fuse":    true,
		"A /dev/ptmx":    true,
		"A /dev/null":    true,
		"A /dev/random":  true,
		"A /dev/stdout":  true,
		"A /dev/stderr":  true,
		"A /dev/tty1":    true,
		"A /dev/stdin":   true,
		"A /dev/tty":     true,
		"A /dev/urandom": true,
		"A /dev/zero":    true,
	}

	for _, line := range strings.Split(out, "\n") {
		if line != "" && !expected[line] {
			c.Errorf("%q is shown in the diff but shouldn't", line)
		}
	}
}
<|endoftext|>


<commit_before>package global

import (
	"code.cloudfoundry.org/cli/integration/helpers"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"
)

var _ = Describe("marketplace command", func() {
	When("an API endpoint is set", func() {
		When("not logged in", func() {
			When("there are no accessible services", func() {
				BeforeEach(func() {
					helpers.LogoutCF()
				})

				It("displays a message that no services are available", func() {
					session := helpers.CF("marketplace")
					Eventually(session).Should(Say("OK"))
					Eventually(session).Should(Say("\n\n"))
					Eventually(session).Should(Say("No service offerings found"))
					Eventually(session).Should(Exit(0))
				})
			})
		})
	})
})
<commit_msg>Remove Global marketplace test<commit_after><|endoftext|>


<commit_before>package config

import (
	"os"
	"reflect"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

var (
	f       = new(File)
	yamlCfg *Config
	jsonCfg *Config
)

func TestFileFromArg(t *testing.T) {
	loadFromArgs(t, "yaml")
	cleanArgs()
	loadFromArgs(t, "json")
}

func TestJsonRemoveComments(t *testing.T) {
	f.Data = []byte(`{
    // hey
    // wat
  }`)

	f.RemoveJSONComments()
	assert.Equal(t, `{

  }`, string(f.Data))
}

func TestJsonLoad(t *testing.T) {
	var err error
	f.FilePath, err = os.Getwd()
	assert.NoError(t, err)
	assert.NotEmpty(t, f.FilePath)
	f.FilePath += "/../_example/simple/b0x.json"

	cfg, err := f.Load()
	assert.NoError(t, err)
	assert.NotNil(t, cfg)

	assert.NotEqual(t, `{

  }`, string(f.Data))

	cfg.Defaults()
	jsonCfg = cfg
}

func TestYamlLoad(t *testing.T) {
	loadFromArgs(t, "yaml")

	var err error
	f.FilePath, err = os.Getwd()
	assert.NoError(t, err)
	assert.NotEmpty(t, f.FilePath)
	f.FilePath += "/../_example/simple/b0x.yaml"

	cfg, err := f.Load()
	assert.NoError(t, err)
	assert.NotNil(t, cfg)
	assert.NotEmpty(t, string(f.Data))

	cfg.Defaults()
	yamlCfg = cfg
}

func TestComparison(t *testing.T) {
	assert.True(t, reflect.DeepEqual(yamlCfg, jsonCfg))
}

func loadFromArgs(t *testing.T, ext string) {
	// insert "b0x.ext" to args
	os.Args = append(os.Args, "b0x."+ext)

	// test b0x.ext from args
	err := f.FromArg()
	assert.NoError(t, err)
	assert.True(t, strings.HasSuffix(f.FilePath, "b0x."+ext))
}

func cleanArgs() {
	// remove "b0x.*" from last arg
	os.Args = os.Args[:len(os.Args)]
}
<commit_msg>fixed cleanArgs() on test<commit_after>package config

import (
	"os"
	"reflect"
	"strings"
	"testing"

	"github.com/stretchr/testify/assert"
)

var (
	f       = new(File)
	yamlCfg *Config
	jsonCfg *Config
)

func TestFileFromArg(t *testing.T) {
	loadFromArgs(t, "yaml")
	cleanArgs()
	loadFromArgs(t, "json")
}

func TestJsonRemoveComments(t *testing.T) {
	f.Data = []byte(`{
    // hey
    // wat
  }`)

	f.RemoveJSONComments()
	assert.Equal(t, `{

  }`, string(f.Data))
}

func TestJsonLoad(t *testing.T) {
	var err error
	f.FilePath, err = os.Getwd()
	assert.NoError(t, err)
	assert.NotEmpty(t, f.FilePath)
	f.FilePath += "/../_example/simple/b0x.json"

	cfg, err := f.Load()
	assert.NoError(t, err)
	assert.NotNil(t, cfg)

	assert.NotEqual(t, `{

  }`, string(f.Data))

	cfg.Defaults()
	jsonCfg = cfg
}

func TestYamlLoad(t *testing.T) {
	loadFromArgs(t, "yaml")

	var err error
	f.FilePath, err = os.Getwd()
	assert.NoError(t, err)
	assert.NotEmpty(t, f.FilePath)
	f.FilePath += "/../_example/simple/b0x.yaml"

	cfg, err := f.Load()
	assert.NoError(t, err)
	assert.NotNil(t, cfg)
	assert.NotEmpty(t, string(f.Data))

	cfg.Defaults()
	yamlCfg = cfg
}

func TestComparison(t *testing.T) {
	assert.True(t, reflect.DeepEqual(yamlCfg, jsonCfg))
}

func loadFromArgs(t *testing.T, ext string) {
	// insert "b0x.ext" to args
	os.Args = append(os.Args, "b0x."+ext)

	// test b0x.ext from args
	err := f.FromArg()
	assert.NoError(t, err)
	assert.True(t, strings.HasSuffix(f.FilePath, "b0x."+ext))
}

func cleanArgs() {
	// remove "b0x.*" from last arg
	os.Args = os.Args[:len(os.Args)-1]
}
<|endoftext|>


<commit_before>package hush

import (
	"bytes"
	"crypto/rand"
	"errors"
	"fmt"
	"io"
	"os"
)

func CmdInit(w io.Writer, input *os.File) error {
	// make sure hush file doesn't exist yet
	hushFilename, err := hushPath()
	if !os.IsNotExist(err) {
		return fmt.Errorf(
			"A hush file already exists at %s\nYou don't have to run init again",
			hushFilename,
		)
	}

	// prompt for passwords
	io.WriteString(w, "Preparing to initialize your hush file. Please provide\n")
	io.WriteString(w, "and verify a password to use for encryption.\n")
	io.WriteString(w, "\n")
	password, err := readPassword(w, input, "Password: ")
	if err != nil {
		return err
	}
	verify, err := readPassword(w, input, "Verify password: ")
	if err != nil {
		return err
	}
	if !bytes.Equal(password, verify) {
		return errors.New("Passwords don't match")
	}

	// generate keys
	encryptionKey := make([]byte, 32) // 256-bit key for AES
	_, err = rand.Read(encryptionKey)
	if err != nil {
		return err
	}
	salt := make([]byte, 16) // double the RFC8018 minimum
	_, err = rand.Read(salt)
	if err != nil {
		return err
	}
	pwKey := stretchPassword(password, salt)

	t := newT(nil)
	p := NewPath("hush-configuration/salt")
	v := NewPlaintext(salt, Public)
	t.set(p, v)
	p = NewPath("hush-configuration/encryption-key")
	v = NewPlaintext(encryptionKey, Private)
	v = v.Ciphertext(pwKey)
	t.set(p, v)
	err = t.Save()
	if err != nil {
		die("%s", err)
	}

	fmt.Fprintf(w, "Hush file created at %s\n", hushFilename)
	return nil
}
<commit_msg>init: slightly shorter error message<commit_after>package hush

import (
	"bytes"
	"crypto/rand"
	"errors"
	"fmt"
	"io"
	"os"
)

func CmdInit(w io.Writer, input *os.File) error {
	// make sure hush file doesn't exist yet
	hushFilename, err := hushPath()
	if !os.IsNotExist(err) {
		return fmt.Errorf(
			"A hush file already exists at %s\nNo need to run init",
			hushFilename,
		)
	}

	// prompt for passwords
	io.WriteString(w, "Preparing to initialize your hush file. Please provide\n")
	io.WriteString(w, "and verify a password to use for encryption.\n")
	io.WriteString(w, "\n")
	password, err := readPassword(w, input, "Password: ")
	if err != nil {
		return err
	}
	verify, err := readPassword(w, input, "Verify password: ")
	if err != nil {
		return err
	}
	if !bytes.Equal(password, verify) {
		return errors.New("Passwords don't match")
	}

	// generate keys
	encryptionKey := make([]byte, 32) // 256-bit key for AES
	_, err = rand.Read(encryptionKey)
	if err != nil {
		return err
	}
	salt := make([]byte, 16) // double the RFC8018 minimum
	_, err = rand.Read(salt)
	if err != nil {
		return err
	}
	pwKey := stretchPassword(password, salt)

	t := newT(nil)
	p := NewPath("hush-configuration/salt")
	v := NewPlaintext(salt, Public)
	t.set(p, v)
	p = NewPath("hush-configuration/encryption-key")
	v = NewPlaintext(encryptionKey, Private)
	v = v.Ciphertext(pwKey)
	t.set(p, v)
	err = t.Save()
	if err != nil {
		die("%s", err)
	}

	fmt.Fprintf(w, "Hush file created at %s\n", hushFilename)
	return nil
}
<|endoftext|>


<commit_before>package cmd

import (
	dcli "github.com/jeffjen/go-discovery/cli"

	cli "github.com/codegangsta/cli"
)

var (
	Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "addr",
			Usage: "API endpoint for admin",
		},
		cli.BoolFlag{
			Name:  "idle",
			Usage: "Set flag to disable active container life cycle event",
		},
		cli.BoolFlag{
			Name:  "persist",
			Usage: "Experimental: Set flag to persist data",
		},
		cli.StringFlag{
			Name:  "prefix",
			Usage: "Prefix to apply for discovery",
			Value: "/docker/swarm/nodes",
		},
	}
)

func NewFlag() []cli.Flag {
	return append(Flags, dcli.Flags...)
}
<commit_msg>NIT: default prefix<commit_after>package cmd

import (
	dcli "github.com/jeffjen/go-discovery/cli"

	cli "github.com/codegangsta/cli"
)

var (
	Flags = []cli.Flag{
		cli.StringFlag{
			Name:  "addr",
			Usage: "API endpoint for admin",
		},
		cli.BoolFlag{
			Name:  "idle",
			Usage: "Set flag to disable active container life cycle event",
		},
		cli.BoolFlag{
			Name:  "persist",
			Usage: "Experimental: Set flag to persist data",
		},
		cli.StringFlag{
			Name:  "prefix",
			Usage: "Prefix to apply for discovery",
			Value: "/debug/docker/swarm/nodes",
		},
	}
)

func NewFlag() []cli.Flag {
	return append(Flags, dcli.Flags...)
}
<|endoftext|>


<commit_before>package main

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

	"github.com/cloudflare/cfssl/csr"
	"github.com/cloudflare/cfssl/initca"
	"github.com/ericyan/lorica/cryptoki"
)

func initCommand(tk *cryptoki.Token, args []string) {
	flags := flag.NewFlagSet("init", flag.ExitOnError)
	selfsign := flags.Bool("selfsign", false, "self-sign the CSR and output the signed certificate")
	flags.Parse(args)

	csrFilename := flags.Arg(0)
	csrJSON, err := readFile(csrFilename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	csr := csr.New()
	err = json.Unmarshal(csrJSON, csr)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	key, err := cryptoki.NewKeyPair(tk, csr.CN, csr.KeyRequest)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	certPEM, csrPEM, err := initca.NewFromSigner(csr, key)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	if *selfsign {
		certPEMFilename := strings.Replace(csrFilename, ".json", ".pem", 1)
		err = writeFile(certPEMFilename, certPEM)
	} else {
		csrPEMFilename := strings.Replace(csrFilename, ".json", ".csr.pem", 1)
		err = writeFile(csrPEMFilename, csrPEM)
	}
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
<commit_msg>Do not sign CSR for new CA if not requested<commit_after>package main

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

	"github.com/cloudflare/cfssl/csr"
	"github.com/ericyan/lorica"
	"github.com/ericyan/lorica/cryptoki"
)

func initCommand(tk *cryptoki.Token, args []string) {
	flags := flag.NewFlagSet("init", flag.ExitOnError)
	selfsign := flags.Bool("selfsign", false, "self-sign the CSR and output the signed certificate")
	flags.Parse(args)

	csrFilename := flags.Arg(0)
	csrJSON, err := readFile(csrFilename)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	req := csr.New()
	err = json.Unmarshal(csrJSON, req)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	key, err := cryptoki.NewKeyPair(tk, req.CN, req.KeyRequest)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	csrPEM, err := csr.Generate(key, req)
	if err != nil {
		os.Exit(1)
	}

	if *selfsign {
		ca, err := lorica.NewCA(nil, nil, key)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		certPEM, err := ca.Sign(csrPEM)
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}

		certPEMFilename := strings.Replace(csrFilename, ".json", ".pem", 1)
		err = writeFile(certPEMFilename, certPEM)
	} else {
		csrPEMFilename := strings.Replace(csrFilename, ".json", ".csr.pem", 1)
		err = writeFile(csrPEMFilename, csrPEM)
	}
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}
<|endoftext|>


<commit_before>// Simple utility for counting messages on a Kafka topic.
//
// Copyright (C) 2017 ENEO Tecnologia SL
// Author: Diego Fernández Barrera <bigomby@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"flag"
	"io/ioutil"
	"os"
	"os/signal"
	"sync"

	"github.com/Sirupsen/logrus"
	prefixed "github.com/x-cray/logrus-prefixed-formatter"
)

var (
	version    string
	configFile string

	wg        = new(sync.WaitGroup)
	terminate = make(chan struct{})
)

var log = logrus.New()

func init() {
	log.Formatter = &prefixed.TextFormatter{}

	versionFlag := flag.Bool("version", false, "Show version info")
	debugFlag := flag.Bool("debug", false, "Show debug info")
	configFlag := flag.String("config", "", "Application configuration file")
	flag.Parse()

	if *versionFlag {
		PrintVersion()
		os.Exit(0)
	}

	if len(*configFlag) == 0 {
		flag.Usage()
		os.Exit(1)
	}

	if *debugFlag {
		log.Level = logrus.DebugLevel
	}

	configFile = *configFlag
}

func main() {
	///////////////////////
	// App Configuration //
	///////////////////////

	rawConfig, err := ioutil.ReadFile(configFile)
	if err != nil {
		log.Fatalln("Error reading config file: " + err.Error())
	}

	config, err := ParseConfig(rawConfig)
	if err != nil {
		log.Fatalln("Error parsing config: " + err.Error())
	}

	/////////////////////////////////////////////////
	// Start the pipeline for accounting messages //
	/////////////////////////////////////////////////

	UUIDCountersPipeline(config)

	//////////////////////////////////////////////
	// Start the pipeline for limits reporting //
	//////////////////////////////////////////////

	CountersMonitor(config)

	///////////////////
	// Handle SIGINT //
	///////////////////

	sigint := make(chan os.Signal)
	signal.Notify(sigint, os.Interrupt)

	go func() {
		<-sigint
		close(terminate)
	}()

	/////////////
	// The End //
	/////////////

	wg.Wait()
	log.Infoln("Bye bye...")
}
<commit_msg>:lipstick: Color logging<commit_after>// Simple utility for counting messages on a Kafka topic.
//
// Copyright (C) 2017 ENEO Tecnologia SL
// Author: Diego Fernández Barrera <bigomby@gmail.com>
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

package main

import (
	"flag"
	"io/ioutil"
	"os"
	"os/signal"
	"sync"

	"github.com/Sirupsen/logrus"
	prefixed "github.com/x-cray/logrus-prefixed-formatter"
)

var (
	version    string
	configFile string

	wg        = new(sync.WaitGroup)
	terminate = make(chan struct{})
)

var log = logrus.New()

func init() {
	log.Formatter = &prefixed.TextFormatter{
		ForceColors:      true,
		DisableTimestamp: true,
	}

	versionFlag := flag.Bool("version", false, "Show version info")
	debugFlag := flag.Bool("debug", false, "Show debug info")
	configFlag := flag.String("config", "", "Application configuration file")
	flag.Parse()

	if *versionFlag {
		PrintVersion()
		os.Exit(0)
	}

	if len(*configFlag) == 0 {
		flag.Usage()
		os.Exit(1)
	}

	if *debugFlag {
		log.Level = logrus.DebugLevel
	}

	configFile = *configFlag
}

func main() {
	///////////////////////
	// App Configuration //
	///////////////////////

	rawConfig, err := ioutil.ReadFile(configFile)
	if err != nil {
		log.Fatalln("Error reading config file: " + err.Error())
	}

	config, err := ParseConfig(rawConfig)
	if err != nil {
		log.Fatalln("Error parsing config: " + err.Error())
	}

	/////////////////////////////////////////////////
	// Start the pipeline for accounting messages //
	/////////////////////////////////////////////////

	UUIDCountersPipeline(config)

	//////////////////////////////////////////////
	// Start the pipeline for limits reporting //
	//////////////////////////////////////////////

	CountersMonitor(config)

	///////////////////
	// Handle SIGINT //
	///////////////////

	sigint := make(chan os.Signal)
	signal.Notify(sigint, os.Interrupt)

	go func() {
		<-sigint
		close(terminate)
	}()

	/////////////
	// The End //
	/////////////

	wg.Wait()
	log.Infoln("Bye bye...")
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"log"
	"math"
	"sort"
	"time"

	"github.com/phil-mansfield/shellfish/los/geom"
	"github.com/phil-mansfield/shellfish/cmd/catalog"
	"github.com/phil-mansfield/shellfish/cmd/env"
	"github.com/phil-mansfield/shellfish/logging"
	"github.com/phil-mansfield/shellfish/parse"
	"github.com/phil-mansfield/shellfish/io"
	"github.com/phil-mansfield/shellfish/cmd/memo"
)

type ProfConfig struct {
	bins, order int64
	pType profileType

	rMaxMult, rMinMult float64
}

type profileType int
const (
	densityProfile profileType = iota
	containedDensityProfile
	angularFractionProfile
)

var _ Mode = &ProfConfig{}

func (config *ProfConfig) ExampleConfig() string {
	return `[prof.config]

#####################
## Required Fields ##
#####################

# ProfileType determines what type of profile will be output.
# Known profile types are:
# density -          the traditional spherical densiy profile that we all
                     know and love.
# contained-densiy - a density profile which only uses particles.
# angular-fraction - the angular fraction at each radius which is contained
                     within the shell.
ProfileType = density

# Order is the order of the Penna-Dines shell fit that Shellfish uses. This
# variable only needs to be set if ProfileType is set to contained-density
# or angular-fraction.
Order = 3

#####################
## Optional Fields ##
#####################

# Bins is the number of logarithmic radial bins used in a profile.
# Bins = 150

# RMaxMult is the maximum radius of the profile as a function of R_200m.
# RMaxMult = 3

# RMinMult is the minimum radius of the profile as a function of R_200m.
# RMinMult = 0.03
`
}

func (config *ProfConfig) ReadConfig(fname string) error {
	if fname == "" {
		return nil
	}

	vars := parse.NewConfigVars("shell.config")

	vars.Int(&config.bins, "Bins", 150)
	vars.Int(&config.order, "Order", 3)
	vars.Float(&config.rMaxMult, "RMaxMult", 3.0)
	vars.Float(&config.rMinMult, "RMinMult", 0.03)
	var pType string
	vars.String(&pType, "ProfileType", "")

	if err := parse.ReadConfig(fname, vars); err != nil {
		return err
	}

	switch pType {
	case "":
		return fmt.Errorf("The variable 'ProfileType' was not set".)
	case "density":
		config.pType = densityProfile
	case "contained-density":
		config.pType = containedDensityProfile
	case "angular-fraction":
		config.pType = angularFractionProfile
	default:
		return fmt.Errorf("The varaiable 'ProfileType' was set to '%s'.", pType)
	}

	return config.validate()
}

func (config *ProfConfig) validate() error {
	if config.bins < 0 {
		return fmt.Errorf("The variable '%s' was set to %d.",
			"Bins", config.bins)
	} else if config.rMinMult <= 0 {
		return fmt.Errorf("The variable '%s' was set to %g.",
			"RMinMult", config.rMinMult)
	} else if config.rMaxMult <= 0 {
		return fmt.Errorf("The variable '%s' was set to %g.",
			"RMinMult", config.rMinMult)
	}
	return nil
}

func (config *ProfConfig) Run(
	flags []string, gConfig *GlobalConfig, e *env.Environment, stdin []string,
) ([]string, error) {
	if logging.Mode != logging.Nil {
		log.Println(`
####################
## shellfish tree ##
####################`,
		)
	}

	var t time.Time
	if logging.Mode == logging.Performance {
		t = time.Now()
	}

	var (
		intCols []int
		coords, coeffs []float64
		err error
	)

	switch config.pType {
	case densityProfile:
		intColIdxs := []int{0, 1}
		floatColIdxs := []int{2, 3, 4, 5}

		intCols, coords, err = catalog.ParseCols(
			stdin, intColIdxs, floatColIdxs,
		)

		if err != nil {
			return nil, err
		}
	case containedDensityProfile, angularFractionProfile:
		intColIdxs := []int{0, 1}
		floatColIdxs := make([]int, 4 + pType.order*pType.order*2)
		for i := range floatColIdxs {
			floatColIdxs[i] + i + 2
		}

		var floatCols []float64
		intCols, floatCols, err = catalog.ParseCols(
			stdin, intColIdxs, floatColIdxs,
		)

		if err != nil {
			return nil, err
		}

		coords = floatCols[:4]
		coeffs = floatCols[4:]
	}

	if len(intCols) == 0 {
		return nil, fmt.Errorf("No input IDs.")
	}

	ids, snaps := intCols[0], intCols[1]
	snapBins, idxBins := binBySnap(snaps, ids)

	rSets := make([][]float64, len(ids))
	rhoSets := make([][]float64, len(ids))
	for i := range rSets {
		rSets[i] = make([]float64, config.bins)
		rhoSets[i] = make([]float64, config.bins)
	}

	sortedSnaps := []int{}
	for snap := range snapBins {
		sortedSnaps = append(sortedSnaps, snap)
	}
	sort.Ints(sortedSnaps)

	buf, err := getVectorBuffer(
		e.ParticleCatalog(snaps[0], 0),
		gConfig.SnapshotType, gConfig.Endianness,
	)
	if err != nil {
		return nil, err
	}

	for _, snap := range sortedSnaps {
		if snap == -1 {
			continue
		}

		idxs := idxBins[snap]
		snapCoords := [][]float64{
			make([]float64, len(idxs)), make([]float64, len(idxs)),
			make([]float64, len(idxs)), make([]float64, len(idxs)),
		}
		for i, idx := range idxs {
			snapCoords[0][i] = coords[0][idx]
			snapCoords[1][i] = coords[1][idx]
			snapCoords[2][i] = coords[2][idx]
			snapCoords[3][i] = coords[3][idx]
		}

		hds, files, err := memo.ReadHeaders(snap, buf, e)
		if err != nil {
			return nil, err
		}
		hBounds, err := boundingSpheres(snapCoords, &hds[0], e)
		if err != nil {
			return nil, err
		}
		_, intrIdxs := binSphereIntersections(hds, hBounds)

		for i := range hds {
			if len(intrIdxs[i]) == 0 {
				continue
			}

			xs, ms, _, err := buf.Read(files[i])
			if err != nil {
				return nil, err
			}

			// Waarrrgggble
			for _, j := range intrIdxs[i] {
				rhos := rhoSets[idxs[j]]
				s := hBounds[j]

				insertPoints(rhos, s, xs, ms, config, &hds[i])
			}

			buf.Close()
		}
	}

	for i := range rSets {
		rMax := coords[3][i]*config.rMaxMult
		rMin := coords[3][i]*config.rMinMult
		processProfile(rSets[i], rhoSets[i], rMin, rMax)
	}

	rSets = transpose(rSets)
	rhoSets = transpose(rhoSets)

	order := make([]int, len(rSets) + len(rhoSets) + 2)
	for i := range order { order[i] = i }
	lines := catalog.FormatCols(
			[][]int{ids, snaps}, append(rSets, rhoSets...), order,
	)

	cString := catalog.CommentString(
		[]string{"ID", "Snapshot", "R [cMpc/h]", "Rho [h^2 Msun/cMpc^3]"},
		[]string{}, []int{0, 1, 2, 3},
		[]int{1, 1, int(config.bins), int(config.bins)},
	)

	if logging.Mode == logging.Performance {
		log.Printf("Time: %s", time.Since(t).String())
		log.Printf("Memory:\n%s", logging.MemString())
	}

	return append([]string{cString}, lines...), nil
}

func insertPoints(
	rhos []float64, s geom.Sphere, xs [][3]float32,
	ms []float32, config *ProfConfig, hd *io.Header,
) {
	lrMax := math.Log(float64(s.R) * config.rMaxMult)
	lrMin := math.Log(float64(s.R) * config.rMinMult)
	dlr := (lrMax - lrMin) / float64(config.bins)
	rMax2 := s.R * float32(config.rMaxMult)
	rMin2 := s.R * float32(config.rMinMult)
	rMax2 *= rMax2
	rMin2 *= rMin2

	x0, y0, z0 := s.C[0], s.C[1], s.C[2]
	tw2 := float32(hd.TotalWidth) / 2

	for i, vec := range xs {
		x, y, z := vec[0], vec[1], vec[2]
		dx, dy, dz := x - x0, y - y0, z - z0
		dx = wrap(dx, tw2)
		dy = wrap(dy, tw2)
		dz = wrap(dz, tw2)

		r2 := dx*dx + dy*dy + dz*dz
		if r2 <= rMin2 || r2 >= rMax2 { continue }
		lr := math.Log(float64(r2)) / 2
		ir := int(((lr) - lrMin) / dlr)
		if ir == len(rhos) { ir-- }
		if ir < 0 || i < 0 || ir >= len(rhos) || i >= len(ms) {
			log.Println(
				"ir", ir,
				"i", i,
				"|rhos|", len(rhos),
				"|ms|", len(ms),
			)
		}
		rhos[ir] += float64(ms[i])
	}
}

func processProfile(rs, rhos []float64, rMin, rMax float64) {
	n := len(rs)

	dlr := (math.Log(rMax) - math.Log(rMin)) / float64(n)
	lrMin := math.Log(rMin)

	for j := range rs {
		rs[j] = math.Exp(lrMin + dlr*(float64(j) + 0.5))

		rLo := math.Exp(dlr*float64(j) + lrMin)
		rHi := math.Exp(dlr*float64(j+1) + lrMin)
		dV := (rHi*rHi*rHi - rLo*rLo*rLo) * 4 * math.Pi / 3

		rhos[j] = rhos[j] / dV
	}
}
<commit_msg>Implemented contained density profile.<commit_after>package cmd

import (
	"fmt"
	"log"
	"math"
	"sort"
	"time"

	"github.com/phil-mansfield/shellfish/los/geom"
	"github.com/phil-mansfield/shellfish/los/analyze"
	"github.com/phil-mansfield/shellfish/cmd/catalog"
	"github.com/phil-mansfield/shellfish/cmd/env"
	"github.com/phil-mansfield/shellfish/logging"
	"github.com/phil-mansfield/shellfish/parse"
	"github.com/phil-mansfield/shellfish/io"
	"github.com/phil-mansfield/shellfish/cmd/memo"
)

type ProfConfig struct {
	bins, order int64
	pType profileType

	rMaxMult, rMinMult float64
}

type profileType int
const (
	densityProfile profileType = iota
	containedDensityProfile
	angularFractionProfile
)

var _ Mode = &ProfConfig{}

func (config *ProfConfig) ExampleConfig() string {
	return `[prof.config]

#####################
## Required Fields ##
#####################

# ProfileType determines what type of profile will be output.
# Known profile types are:
# density -          the traditional spherical densiy profile that we all
                     know and love.
# contained-densiy - a density profile which only uses particles.
# angular-fraction - the angular fraction at each radius which is contained
                     within the shell.
ProfileType = density

# Order is the order of the Penna-Dines shell fit that Shellfish uses. This
# variable only needs to be set if ProfileType is set to contained-density
# or angular-fraction.
Order = 3

#####################
## Optional Fields ##
#####################

# Bins is the number of logarithmic radial bins used in a profile.
# Bins = 150

# RMaxMult is the maximum radius of the profile as a function of R_200m.
# RMaxMult = 3

# RMinMult is the minimum radius of the profile as a function of R_200m.
# RMinMult = 0.03
`
}

func (config *ProfConfig) ReadConfig(fname string) error {
	if fname == "" {
		return nil
	}

	vars := parse.NewConfigVars("shell.config")

	vars.Int(&config.bins, "Bins", 150)
	vars.Int(&config.order, "Order", 3)
	vars.Float(&config.rMaxMult, "RMaxMult", 3.0)
	vars.Float(&config.rMinMult, "RMinMult", 0.03)
	var pType string
	vars.String(&pType, "ProfileType", "")

	if err := parse.ReadConfig(fname, vars); err != nil {
		return err
	}

	switch pType {
	case "":
		return fmt.Errorf("The variable 'ProfileType' was not set.")
	case "density":
		config.pType = densityProfile
	case "contained-density":
		config.pType = containedDensityProfile
	case "angular-fraction":
		config.pType = angularFractionProfile
	default:
		return fmt.Errorf("The varaiable 'ProfileType' was set to '%s'.", pType)
	}

	return config.validate()
}

func (config *ProfConfig) validate() error {
	if config.bins < 0 {
		return fmt.Errorf("The variable '%s' was set to %d.",
			"Bins", config.bins)
	} else if config.rMinMult <= 0 {
		return fmt.Errorf("The variable '%s' was set to %g.",
			"RMinMult", config.rMinMult)
	} else if config.rMaxMult <= 0 {
		return fmt.Errorf("The variable '%s' was set to %g.",
			"RMinMult", config.rMinMult)
	}
	return nil
}

func (config *ProfConfig) Run(
	flags []string, gConfig *GlobalConfig, e *env.Environment, stdin []string,
) ([]string, error) {
	if logging.Mode != logging.Nil {
		log.Println(`
####################
## shellfish tree ##
####################`,
		)
	}

	var t time.Time
	if logging.Mode == logging.Performance {
		t = time.Now()
	}

	var (
		intCols [][]int
		coords [][]float64
		shells []analyze.Shell
		err error
	)

	switch config.pType {
	case densityProfile:
		intColIdxs := []int{0, 1}
		floatColIdxs := []int{2, 3, 4, 5}

		intCols, coords, err = catalog.ParseCols(
			stdin, intColIdxs, floatColIdxs,
		)

		if err != nil {
			return nil, err
		}
	case containedDensityProfile, angularFractionProfile:
		intColIdxs := []int{0, 1}
		floatColIdxs := make([]int, 4 + config.order*config.order*2)
		for i := range floatColIdxs {
			floatColIdxs[i] += i + 2
		}

		var floatCols [][]float64
		intCols, floatCols, err = catalog.ParseCols(
			stdin, intColIdxs, floatColIdxs,
		)

		if err != nil {
			return nil, err
		}

		coords = floatCols[:4]
		coeffs := floatCols[4:]
		shells = make([]analyze.Shell, len(coords[0]))
		for i := range shells {
			coeffVec := make([]float64, len(coeffs))
			for j := range coeffVec {
				coeffVec[j] = coeffs[j][i]
			}
			order := int(config.order)
			shells[i] = analyze.PennaFunc(coeffVec, order, order, 2)
		}
	}

	if len(intCols) == 0 {
		return nil, fmt.Errorf("No input IDs.")
	}

	ids, snaps := intCols[0], intCols[1]
	snapBins, idxBins := binBySnap(snaps, ids)

	rSets := make([][]float64, len(ids))
	rhoSets := make([][]float64, len(ids))
	for i := range rSets {
		rSets[i] = make([]float64, config.bins)
		rhoSets[i] = make([]float64, config.bins)
	}

	sortedSnaps := []int{}
	for snap := range snapBins {
		sortedSnaps = append(sortedSnaps, snap)
	}
	sort.Ints(sortedSnaps)

	buf, err := getVectorBuffer(
		e.ParticleCatalog(snaps[0], 0),
		gConfig.SnapshotType, gConfig.Endianness,
	)
	if err != nil {
		return nil, err
	}

	for _, snap := range sortedSnaps {
		if snap == -1 {
			continue
		}

		idxs := idxBins[snap]
		snapCoords := [][]float64{
			make([]float64, len(idxs)), make([]float64, len(idxs)),
			make([]float64, len(idxs)), make([]float64, len(idxs)),
		}
		for i, idx := range idxs {
			snapCoords[0][i] = coords[0][idx]
			snapCoords[1][i] = coords[1][idx]
			snapCoords[2][i] = coords[2][idx]
			snapCoords[3][i] = coords[3][idx]
		}

		hds, files, err := memo.ReadHeaders(snap, buf, e)
		if err != nil {
			return nil, err
		}
		hBounds, err := boundingSpheres(snapCoords, &hds[0], e)
		if err != nil {
			return nil, err
		}
		_, intrIdxs := binSphereIntersections(hds, hBounds)

		for i := range hds {
			if len(intrIdxs[i]) == 0 {
				continue
			}

			xs, ms, _, err := buf.Read(files[i])
			if err != nil {
				return nil, err
			}

			// Waarrrgggble
			for _, j := range intrIdxs[i] {
				rhos := rhoSets[idxs[j]]
				s := hBounds[j]

				insertPoints(rhos, s, xs, ms, shells[idxs[j]], config, &hds[i])
			}

			buf.Close()
		}
	}

	for i := range rSets {
		rMax := coords[3][i]*config.rMaxMult
		rMin := coords[3][i]*config.rMinMult
		processProfile(rSets[i], rhoSets[i], rMin, rMax)
	}

	rSets = transpose(rSets)
	rhoSets = transpose(rhoSets)

	order := make([]int, len(rSets) + len(rhoSets) + 2)
	for i := range order { order[i] = i }
	lines := catalog.FormatCols(
			[][]int{ids, snaps}, append(rSets, rhoSets...), order,
	)

	cString := catalog.CommentString(
		[]string{"ID", "Snapshot", "R [cMpc/h]", "Rho [h^2 Msun/cMpc^3]"},
		[]string{}, []int{0, 1, 2, 3},
		[]int{1, 1, int(config.bins), int(config.bins)},
	)

	if logging.Mode == logging.Performance {
		log.Printf("Time: %s", time.Since(t).String())
		log.Printf("Memory:\n%s", logging.MemString())
	}

	return append([]string{cString}, lines...), nil
}

func insertPoints(
	rhos []float64, s geom.Sphere, xs [][3]float32,
	ms []float32, shell analyze.Shell, config *ProfConfig, hd *io.Header,
) {
	lrMax := math.Log(float64(s.R) * config.rMaxMult)
	lrMin := math.Log(float64(s.R) * config.rMinMult)
	dlr := (lrMax - lrMin) / float64(config.bins)
	rMax2 := s.R * float32(config.rMaxMult)
	rMin2 := s.R * float32(config.rMinMult)
	rMax2 *= rMax2
	rMin2 *= rMin2

	x0, y0, z0 := s.C[0], s.C[1], s.C[2]
	tw2 := float32(hd.TotalWidth) / 2

	for i, vec := range xs {
		x, y, z := vec[0], vec[1], vec[2]
		dx, dy, dz := x - x0, y - y0, z - z0
		dx = wrap(dx, tw2)
		dy = wrap(dy, tw2)
		dz = wrap(dz, tw2)

		r2 := dx*dx + dy*dy + dz*dz
		if r2 <= rMin2 || r2 >= rMax2 {
			continue
		}

		if config.pType == containedDensityProfile &&
			!shell.Contains(float64(dx), float64(dy), float64(dz)) {
			continue
		}

		lr := math.Log(float64(r2)) / 2
		ir := int(((lr) - lrMin) / dlr)
		if ir == len(rhos) { ir-- }
		rhos[ir] += float64(ms[i])
	}
}

func processProfile(rs, rhos []float64, rMin, rMax float64) {
	n := len(rs)

	dlr := (math.Log(rMax) - math.Log(rMin)) / float64(n)
	lrMin := math.Log(rMin)

	for j := range rs {
		rs[j] = math.Exp(lrMin + dlr*(float64(j) + 0.5))

		rLo := math.Exp(dlr*float64(j) + lrMin)
		rHi := math.Exp(dlr*float64(j+1) + lrMin)
		dV := (rHi*rHi*rHi - rLo*rLo*rLo) * 4 * math.Pi / 3

		rhos[j] = rhos[j] / dV
	}
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/spf13/cobra"
	"github.com/voidint/gbb/config"
	"github.com/voidint/gbb/tool"
	"github.com/voidint/gbb/util"
)

const (
	// DefaultConfFile default configuration file path
	DefaultConfFile = "gbb.json"
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "gbb",
	Short: "Compile assistant",
	Long:  ``,

	Run: func(cmd *cobra.Command, args []string) {
		if gopts.ConfigFile == DefaultConfFile {
			gopts.ConfigFile = filepath.Join(wd, "gbb.json")
		}

		if !util.FileExist(gopts.ConfigFile) {
			genConfigFile(gopts.ConfigFile)
			return
		}
		conf, err := config.Load(gopts.ConfigFile)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			os.Exit(-1)
			return
		}
		conf.Debug = gopts.Debug
		conf.All = gopts.All

		if conf.Version != Version {
			gt, err := util.VersionGreaterThan(Version, conf.Version)
			if err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
				os.Exit(-1)
				return
			}

			if gt { // 程序版本大于配置文件版本，重新生成配置文件。
				fmt.Printf("Warning: The gbb.json file needs to be upgraded.\n\n")
				genConfigFile(gopts.ConfigFile)
			} else {
				// 配置文件版本大于程序版本，提醒用户升级程序。
				fmt.Printf("Warning: This program needs to be upgraded by `go get -u -v github.com/voidint/gbb`\n\n")
			}
			return
		}

		if err := tool.Build(conf, wd); err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			os.Exit(-1)
			return
		}
	},
}

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

// GlobalOptions global options
type GlobalOptions struct {
	All        bool
	Debug      bool
	ConfigFile string
}

var (
	wd    string // current work directory
	gopts GlobalOptions
)

func init() {
	cobra.OnInitialize(initConfig)
	RootCmd.PersistentFlags().BoolVarP(&gopts.All, "all", "a", false, "Act on all go packages")
	RootCmd.PersistentFlags().BoolVarP(&gopts.Debug, "debug", "D", false, "Enable debug mode")
	RootCmd.PersistentFlags().StringVarP(&gopts.ConfigFile, "config", "c", DefaultConfFile, "Configuration file")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	var err error
	wd, err = os.Getwd()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
		return
	}
}
<commit_msg>Add copyright to help information. close https://github.com/voidint/gbb/issues/30<commit_after>package cmd

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/spf13/cobra"
	"github.com/voidint/gbb/config"
	"github.com/voidint/gbb/tool"
	"github.com/voidint/gbb/util"
)

const (
	// DefaultConfFile default configuration file path
	DefaultConfFile = "gbb.json"
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use: "gbb",
	Long: `Compile assistant.
Copyright (c) 2016, 2018, voidint. All rights reserved.`,

	Run: func(cmd *cobra.Command, args []string) {
		if gopts.ConfigFile == DefaultConfFile {
			gopts.ConfigFile = filepath.Join(wd, "gbb.json")
		}

		if !util.FileExist(gopts.ConfigFile) {
			genConfigFile(gopts.ConfigFile)
			return
		}
		conf, err := config.Load(gopts.ConfigFile)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			os.Exit(-1)
			return
		}
		conf.Debug = gopts.Debug
		conf.All = gopts.All

		if conf.Version != Version {
			gt, err := util.VersionGreaterThan(Version, conf.Version)
			if err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
				os.Exit(-1)
				return
			}

			if gt { // 程序版本大于配置文件版本，重新生成配置文件。
				fmt.Printf("Warning: The gbb.json file needs to be upgraded.\n\n")
				genConfigFile(gopts.ConfigFile)
			} else {
				// 配置文件版本大于程序版本，提醒用户升级程序。
				fmt.Printf("Warning: This program needs to be upgraded by `go get -u -v github.com/voidint/gbb`\n\n")
			}
			return
		}

		if err := tool.Build(conf, wd); err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			os.Exit(-1)
			return
		}
	},
}

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

// GlobalOptions global options
type GlobalOptions struct {
	All        bool
	Debug      bool
	ConfigFile string
}

var (
	wd    string // current work directory
	gopts GlobalOptions
)

func init() {
	cobra.OnInitialize(initConfig)
	RootCmd.PersistentFlags().BoolVarP(&gopts.All, "all", "a", false, "Act on all go packages")
	RootCmd.PersistentFlags().BoolVarP(&gopts.Debug, "debug", "D", false, "Enable debug mode")
	RootCmd.PersistentFlags().StringVarP(&gopts.ConfigFile, "config", "c", DefaultConfFile, "Configuration file")
}

// initConfig reads in config file and ENV variables if set.
func initConfig() {
	var err error
	wd, err = os.Getwd()
	if err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(-1)
		return
	}
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"log"
	"os"

	"github.com/fatih/color"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	"github.com/stormforger/cli/api"
)

var (
	// RootCmd represents the cobra root command
	RootCmd = &cobra.Command{
		Use: "forge",
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			if !stringInSlice(rootOpts.OutputFormat, []string{"human", "plain", "json"}) {
				log.Fatalf("Unknown output format '%s'", rootOpts.OutputFormat)
			}
		},
		Short: "Command line client to StormForger (https://stormforger.com)",
		Long: `The command line client "forge" to StormForger offers a interface
to the StormForger API and several convenience methods
to handle load and performance tests.

Happy Load Testing :)`,
	}

	rootOpts struct {
		APIEndpoint  string
		JWT          string
		OutputFormat string
	}
)

const (
	// ConfigFilename is the forge config file without extension
	ConfigFilename = ".stormforger"
	// EnvPrefix is the prefix for environment configuration
	EnvPrefix = "stormforger"
)

// Execute is the entry function for cobra
func Execute() {
	setupConfig()

	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	if viper.GetString("jwt") == "" {
		color.Yellow(`No JWT token in config file, environment or via command line flag!

Use forge login to obtain a new JWT token.
`)
	}
}

// NewClient initializes a new API Client
func NewClient() *api.Client {
	return api.NewClient(viper.GetString("endpoint"), viper.GetString("jwt"))
}

/*
	Configuration for JWT can come from (in this order)
	* Environment
	* Configuration ~/.stormforger.toml, ./.stormforger.toml
	* Command line flag
*/
func setupConfig() {
	var err error

	viper.SetEnvPrefix(EnvPrefix)

	err = viper.BindEnv("jwt")
	if err != nil {
		log.Fatal(err)
	}

	err = viper.BindEnv("endpoint")
	if err != nil {
		log.Fatal(err)
	}

	viper.SetConfigName(ConfigFilename)
	viper.AddConfigPath(".")
	viper.AddConfigPath("$HOME")

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

	err = viper.BindPFlag("jwt", RootCmd.PersistentFlags().Lookup("jwt"))
	if err != nil {
		log.Fatal(err)
	}

	err = viper.BindPFlag("endpoint", RootCmd.PersistentFlags().Lookup("endpoint"))
	if err != nil {
		log.Fatal(err)
	}
}

func init() {
	RootCmd.PersistentFlags().StringVar(&rootOpts.APIEndpoint, "endpoint", "https://api.stormforger.com", "API Endpoint")
	RootCmd.PersistentFlags().StringVar(&rootOpts.JWT, "jwt", "", "JWT access token")
	RootCmd.PersistentFlags().StringVar(&rootOpts.OutputFormat, "output", "human", "Output format: human,plain,json")
}
<commit_msg>don't fail if .stormforger.toml could not be found<commit_after>package cmd

import (
	"fmt"
	"log"
	"os"

	"github.com/fatih/color"
	"github.com/spf13/cobra"
	"github.com/spf13/viper"

	"github.com/stormforger/cli/api"
)

var (
	// RootCmd represents the cobra root command
	RootCmd = &cobra.Command{
		Use: "forge",
		PersistentPreRun: func(cmd *cobra.Command, args []string) {
			if !stringInSlice(rootOpts.OutputFormat, []string{"human", "plain", "json"}) {
				log.Fatalf("Unknown output format '%s'", rootOpts.OutputFormat)
			}
		},
		Short: "Command line client to StormForger (https://stormforger.com)",
		Long: `The command line client "forge" to StormForger offers a interface
to the StormForger API and several convenience methods
to handle load and performance tests.

Happy Load Testing :)`,
	}

	rootOpts struct {
		APIEndpoint  string
		JWT          string
		OutputFormat string
	}
)

const (
	// ConfigFilename is the forge config file without extension
	ConfigFilename = ".stormforger"
	// EnvPrefix is the prefix for environment configuration
	EnvPrefix = "stormforger"
)

// Execute is the entry function for cobra
func Execute() {
	setupConfig()

	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}

	if viper.GetString("jwt") == "" {
		color.Yellow(`No JWT token in config file, environment or via command line flag!

Use forge login to obtain a new JWT token.
`)
	}
}

// NewClient initializes a new API Client
func NewClient() *api.Client {
	return api.NewClient(viper.GetString("endpoint"), viper.GetString("jwt"))
}

/*
	Configuration for JWT can come from (in this order)
	* Environment
	* Configuration ~/.stormforger.toml, ./.stormforger.toml
	* Command line flag
*/
func setupConfig() {
	var err error

	viper.SetEnvPrefix(EnvPrefix)

	err = viper.BindEnv("jwt")
	if err != nil {
		log.Fatal(err)
	}

	err = viper.BindEnv("endpoint")
	if err != nil {
		log.Fatal(err)
	}

	viper.SetConfigName(ConfigFilename)
	viper.AddConfigPath(".")
	viper.AddConfigPath("$HOME")

	// ignore errors, e.g. when config could not be found
	_ = viper.ReadInConfig()

	err = viper.BindPFlag("jwt", RootCmd.PersistentFlags().Lookup("jwt"))
	if err != nil {
		log.Fatal(err)
	}

	err = viper.BindPFlag("endpoint", RootCmd.PersistentFlags().Lookup("endpoint"))
	if err != nil {
		log.Fatal(err)
	}
}

func init() {
	RootCmd.PersistentFlags().StringVar(&rootOpts.APIEndpoint, "endpoint", "https://api.stormforger.com", "API Endpoint")
	RootCmd.PersistentFlags().StringVar(&rootOpts.JWT, "jwt", "", "JWT access token")
	RootCmd.PersistentFlags().StringVar(&rootOpts.OutputFormat, "output", "human", "Output format: human,plain,json")
}
<|endoftext|>


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

package cmd

import (
	"fmt"
	"log"
	"os"

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

var (
	cfgFile     string
	clearbitKey string
	cb          *clearbit.Client
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "stalk",
	Short: "A little command line stalker using the Clearbit API",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		email, _ := cmd.Flags().GetString("email")
		stalk(email)
	},
}

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

func init() {
	cobra.OnInitialize(initConfig)

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

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.stalk/config.yaml)")
	RootCmd.PersistentFlags().StringVar(&clearbitKey, "key", "", "ClearBit API key")
	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	RootCmd.Flags().StringP("email", "e", "alex@clearbit.com", "Email of the person to find")
}

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

	viper.SetConfigName("config")       // name of config file (without extension)
	viper.AddConfigPath("$HOME/.stalk") // adding home directory as first search path
	viper.AddConfigPath(".")            // optionally look for config in the working directory
	viper.AutomaticEnv()                // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal(err)
	}

	clearbitKey = viper.GetString("clearbit_key")
}

func stalk(email string) {
	cb := clearbit.NewClient(clearbitKey, nil)

	enrichment, err := cb.Enrichements.GetCombined(email)
	if err != nil {
		log.Printf("Getting an enrichment failed: %s\n", err)
		return
	}

	if enrichment.Person == nil {
		fmt.Printf("Didn't find a person associated with: %s\n", email)
		return
	}

	person := enrichment.Person
	printName(person)
	printEmployment(person)
	printLinks(person)
}

func printName(p *clearbit.Person) {
	if p.Name.FullName != nil {
		fmt.Printf("This email seems to belong to: %s\n", *p.Name.FullName)
	}
}

func printEmployment(p *clearbit.Person) {
	if p.Employment.Name != nil {
		if p.Employment.Title != nil {
			fmt.Printf("Looks like they are working at %s as a %s\n", *p.Employment.Name, *p.Employment.Title)
		} else {
			fmt.Printf("Looks like they are working at %s\n", *p.Employment.Name)
		}
	}
}

func printLinks(p *clearbit.Person) {
	links := map[string]string{}

	if p.Facebook.Handle != nil {
		links["facebook"] = fmt.Sprintf("Facebook: https://facebook.com/%s", *p.Facebook.Handle)
	}
	if p.Twitter.Handle != nil {
		links["twitter"] = fmt.Sprintf("Twitter:  https://twitter.com/%s", *p.Twitter.Handle)
	}
	if p.Github.Handle != nil {
		links["github"] = fmt.Sprintf("GitHub:   https://github.com/%s", *p.Github.Handle)
	}
	if p.Linkedin.Handle != nil {
		links["linkedin"] = fmt.Sprintf("LinkedIn: https://linkedin.com/%s", *p.Linkedin.Handle)
	}
	if p.Googleplus.Handle != nil {
		links["googleplus"] = fmt.Sprintf("Google+:  https://plus.google.com/%s", *p.Googleplus.Handle)
	}

	if len(links) == 0 {
		fmt.Println("No public links found.")
		return
	}

	fmt.Println("You can follow them at:")
	for _, v := range links {
		fmt.Println(v)
	}
}
<commit_msg>remove template comments<commit_after>// Copyright © 2016 Piotr Zurek <p.zurek@gmail.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"fmt"
	"log"
	"os"

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

var (
	cfgFile     string
	clearbitKey string
	cb          *clearbit.Client
)

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "stalk",
	Short: "A little command line stalker using the Clearbit API",
	Long:  ``,
	Run: func(cmd *cobra.Command, args []string) {
		email, _ := cmd.Flags().GetString("email")
		stalk(email)
	},
}

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

func init() {
	cobra.OnInitialize(initConfig)

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.stalk/config.yaml)")
	RootCmd.PersistentFlags().StringVar(&clearbitKey, "key", "", "ClearBit API key")

	RootCmd.Flags().StringP("email", "e", "alex@clearbit.com", "Email of the person to find")
}

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

	viper.SetConfigName("config")       // name of config file (without extension)
	viper.AddConfigPath("$HOME/.stalk") // adding home directory as first search path
	viper.AddConfigPath(".")            // optionally look for config in the working directory
	viper.AutomaticEnv()                // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err != nil {
		log.Fatal(err)
	}

	clearbitKey = viper.GetString("clearbit_key")
}

func stalk(email string) {
	cb := clearbit.NewClient(clearbitKey, nil)

	enrichment, err := cb.Enrichements.GetCombined(email)
	if err != nil {
		log.Printf("Getting an enrichment failed: %s\n", err)
		return
	}

	if enrichment.Person == nil {
		fmt.Printf("Didn't find a person associated with: %s\n", email)
		return
	}

	person := enrichment.Person
	printName(person)
	printEmployment(person)
	printLinks(person)
}

func printName(p *clearbit.Person) {
	if p.Name.FullName != nil {
		fmt.Printf("This email seems to belong to: %s\n", *p.Name.FullName)
	}
}

func printEmployment(p *clearbit.Person) {
	if p.Employment.Name != nil {
		if p.Employment.Title != nil {
			fmt.Printf("Looks like they are working at %s as a %s\n", *p.Employment.Name, *p.Employment.Title)
		} else {
			fmt.Printf("Looks like they are working at %s\n", *p.Employment.Name)
		}
	}
}

func printLinks(p *clearbit.Person) {
	links := map[string]string{}

	if p.Facebook.Handle != nil {
		links["facebook"] = fmt.Sprintf("Facebook: https://facebook.com/%s", *p.Facebook.Handle)
	}
	if p.Twitter.Handle != nil {
		links["twitter"] = fmt.Sprintf("Twitter:  https://twitter.com/%s", *p.Twitter.Handle)
	}
	if p.Github.Handle != nil {
		links["github"] = fmt.Sprintf("GitHub:   https://github.com/%s", *p.Github.Handle)
	}
	if p.Linkedin.Handle != nil {
		links["linkedin"] = fmt.Sprintf("LinkedIn: https://linkedin.com/%s", *p.Linkedin.Handle)
	}
	if p.Googleplus.Handle != nil {
		links["googleplus"] = fmt.Sprintf("Google+:  https://plus.google.com/%s", *p.Googleplus.Handle)
	}

	if len(links) == 0 {
		fmt.Println("No public links found.")
		return
	}

	fmt.Println("You can follow them at:")
	for _, v := range links {
		fmt.Println(v)
	}
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var cfgFile string
var userLicense string

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "dockerlayer",
	Short: "A generator for Cobra based Applications",
	Long: `Cobra is a CLI library for Go that empowers applications.
This application is a tool to generate the needed files
to quickly create a Cobra application.`,
}

//Execute adds all child commands to the root command sets flags appropriately.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}
<commit_msg>Update help message<commit_after>package cmd

import (
	"fmt"
	"os"

	"github.com/spf13/cobra"
)

var cfgFile string
var userLicense string

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "dockerlayer",
	Short: "Display some docker layer information.",
	Long: `Display some docker layer information.
filtering file name support`,
}

//Execute adds all child commands to the root command sets flags appropriately.
func Execute() {
	if err := RootCmd.Execute(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
}
<|endoftext|>


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

package cmd

import (
	"fmt"
	"os"

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

var cfgFile string

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

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

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

func init() {
	cobra.OnInitialize(initConfig)

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

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.docore.yaml)")
	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

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

	viper.SetConfigName(".docore") // name of config file (without extension)
	viper.AddConfigPath("$HOME")   // adding home directory as first search path
	viper.AutomaticEnv()           // read in environment variables that match

	// If a config file is found, read it in.
	if err := viper.ReadInConfig(); err == nil {
		fmt.Println("Using config file:", viper.ConfigFileUsed())
	}
}
<commit_msg>Added short and long descriptions for docore.<commit_after>// Copyright © 2017 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"fmt"
	"os"

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

var cfgFile string

// RootCmd represents the base command when called without any subcommands
var RootCmd = &cobra.Command{
	Use:   "docore",
	Short: "Docore is a CLI to manage a CoreOS cluster hosted on DigitalOcean",
	Long: `Docore is a CLI to manage a CoreOS cluster hosted on DigitalOcean.
This application provides cluster-level management interfaces as well as fine-
grained droplet-level control.`,
	// Uncomment the following line if your bare application
	// has an action associated with it:
	//	Run: func(cmd *cobra.Command, args []string) { },
}

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

func init() {
	cobra.OnInitialize(initConfig)

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

	RootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.docore.yaml)")
	// Cobra also supports local flags, which will only run
	// when this action is called directly.
	RootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
}

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

	viper.SetConfigName(".docore") // name of config file (without extension)
	viper.AddConfigPath("$HOME")   // adding home directory as first search path
	viper.AutomaticEnv()           // read in environment variables that match

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


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

package cmd

import (
	"bytes"
	"os"
	"path"

	"github.com/zerobotlabs/nestor-cli/Godeps/_workspace/src/github.com/fatih/color"
	"github.com/zerobotlabs/nestor-cli/Godeps/_workspace/src/github.com/spf13/cobra"
	"github.com/zerobotlabs/nestor-cli/app"
	"github.com/zerobotlabs/nestor-cli/login"
)

// saveCmd represents the save command
var saveCmd = &cobra.Command{
	Use:   "save",
	Short: "Saves your app to Nestor",
	Run:   runSave,
}

func runSave(cmd *cobra.Command, args []string) {
	var l *login.LoginInfo
	var a app.App

	// Check if you are logged in first
	if l = login.SavedLoginInfo(); l == nil {
		color.Red("You are not logged in. To login, type \"nestor login\"\n")
		os.Exit(1)
	}

	// Check if you have a valid nestor.json file
	nestorJsonPath, err := pathToNestorJson(args)
	if err != nil {
		color.Red("Could not find nestor.json in the path specified\n")
		os.Exit(1)
	}

	a.ManifestPath = nestorJsonPath

	err = a.ParseManifest()
	if err != nil {
		color.Red("%s\n", err.Error())
		os.Exit(1)
	}

	// Check if existing app exists and if so, then we should be making calls to the "UPDATE" function
	// We are ignoring the error for now but at some point we will have to show an error that is not annoying
	err = a.Hydrate(l)
	if err != nil {
		color.Red("- Error fetching details for app\n")
	}

	color.Green("+ Building deployment artifact...\n")
	err = a.BuildArtifact()
	if err != nil {
		color.Red("- Error while building deployment artifact for your app\n")
	}

	// Check if you need to do coffee compilation
	err = a.CompileCoffeescript()
	if err != nil {
		color.Red("- There was an error compiling coffeescript in your app\n")
		os.Exit(1)
	}

	err = a.CalculateLocalSha256()
	if err != nil {
		color.Red("- There was an error calculating whether your app needs to be uploaded\n")
		os.Exit(1)
	}

	if a.LocalSha256 != a.RemoteSha256 {
		color.Green("+ Generating zip...\n")
		zip, err := a.ZipBytes()
		if err != nil {
			color.Red("- Error creating a zip of your app's deployment artifact\n")
			os.Exit(1)
		}

		color.Green("+ Uploading zip...\n")
		// Upload app contents
		buffer := bytes.NewBuffer(zip)
		err = a.Upload(buffer, l)
		if err != nil {
			color.Red("- Error while uploading deployment artifact: %+v\n", err)
			os.Exit(1)
		}
	}

	// Make API call to Nestor with contents from JSON file along with S3 URL so that the API can create a functioning bot app
	color.Green("+ Saving app to Nestor...\n")
	err = a.SaveToNestor(l)
	if err != nil {
		color.Green("- Error while saving app to nestor: %+v\n", err)
		os.Exit(1)
	}

	color.Green("+Successfully saved app to Nestor!\n")
	color.Green("\nYou can test your app by running `nestor shell`\n")
}

func init() {
	RootCmd.AddCommand(saveCmd)
}

func pathToNestorJson(args []string) (string, error) {
	nestorJsonPath := func(base string) (string, error) {
		var err error
		p := path.Join(base, "nestor.json")
		if _, err = os.Stat(p); err != nil {
			return "", err
		}

		return p, err
	}

	if len(args) > 0 {
		return nestorJsonPath(args[0])
	} else {
		base, err := os.Getwd()
		if err != nil {
			return "", err
		}
		return nestorJsonPath(base)
	}
}
<commit_msg>Minor fix in CLI copy<commit_after>// Copyright © 2016 NAME HERE <EMAIL ADDRESS>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package cmd

import (
	"bytes"
	"os"
	"path"

	"github.com/zerobotlabs/nestor-cli/Godeps/_workspace/src/github.com/fatih/color"
	"github.com/zerobotlabs/nestor-cli/Godeps/_workspace/src/github.com/spf13/cobra"
	"github.com/zerobotlabs/nestor-cli/app"
	"github.com/zerobotlabs/nestor-cli/login"
)

// saveCmd represents the save command
var saveCmd = &cobra.Command{
	Use:   "save",
	Short: "Saves your app to Nestor",
	Run:   runSave,
}

func runSave(cmd *cobra.Command, args []string) {
	var l *login.LoginInfo
	var a app.App

	// Check if you are logged in first
	if l = login.SavedLoginInfo(); l == nil {
		color.Red("You are not logged in. To login, type \"nestor login\"\n")
		os.Exit(1)
	}

	// Check if you have a valid nestor.json file
	nestorJsonPath, err := pathToNestorJson(args)
	if err != nil {
		color.Red("Could not find nestor.json in the path specified\n")
		os.Exit(1)
	}

	a.ManifestPath = nestorJsonPath

	err = a.ParseManifest()
	if err != nil {
		color.Red("%s\n", err.Error())
		os.Exit(1)
	}

	// Check if existing app exists and if so, then we should be making calls to the "UPDATE" function
	// We are ignoring the error for now but at some point we will have to show an error that is not annoying
	err = a.Hydrate(l)
	if err != nil {
		color.Red("- Error fetching details for app\n")
	}

	color.Green("+ Building deployment artifact...\n")
	err = a.BuildArtifact()
	if err != nil {
		color.Red("- Error while building deployment artifact for your app\n")
	}

	// Check if you need to do coffee compilation
	err = a.CompileCoffeescript()
	if err != nil {
		color.Red("- There was an error compiling coffeescript in your app\n")
		os.Exit(1)
	}

	err = a.CalculateLocalSha256()
	if err != nil {
		color.Red("- There was an error calculating whether your app needs to be uploaded\n")
		os.Exit(1)
	}

	if a.LocalSha256 != a.RemoteSha256 {
		color.Green("+ Generating zip...\n")
		zip, err := a.ZipBytes()
		if err != nil {
			color.Red("- Error creating a zip of your app's deployment artifact\n")
			os.Exit(1)
		}

		color.Green("+ Uploading zip...\n")
		// Upload app contents
		buffer := bytes.NewBuffer(zip)
		err = a.Upload(buffer, l)
		if err != nil {
			color.Red("- Error while uploading deployment artifact: %+v\n", err)
			os.Exit(1)
		}
	}

	// Make API call to Nestor with contents from JSON file along with S3 URL so that the API can create a functioning bot app
	color.Green("+ Saving app to Nestor...\n")
	err = a.SaveToNestor(l)
	if err != nil {
		color.Green("- Error while saving app to nestor: %+v\n", err)
		os.Exit(1)
	}

	color.Green("+ Successfully saved app to Nestor!\n")
	color.Green("\nYou can test your app by running `nestor shell`\n")
}

func init() {
	RootCmd.AddCommand(saveCmd)
}

func pathToNestorJson(args []string) (string, error) {
	nestorJsonPath := func(base string) (string, error) {
		var err error
		p := path.Join(base, "nestor.json")
		if _, err = os.Stat(p); err != nil {
			return "", err
		}

		return p, err
	}

	if len(args) > 0 {
		return nestorJsonPath(args[0])
	} else {
		base, err := os.Getwd()
		if err != nil {
			return "", err
		}
		return nestorJsonPath(base)
	}
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"

	"github.com/ebfe/scard"
	"github.com/spf13/cobra"
)

var testCmd = &cobra.Command{
	Use:   "test",
	Short: "リーダーの動作確認",
	Long:  "カードリーダーの動作確認を行います",
	RunE:  test,
}

func test(cmd *cobra.Command, args []string) error {
	fmt.Printf("SCardEstablishContext: ")
	ctx, err := scard.EstablishContext()
	if err != nil {
		fmt.Printf("NG\n")
		fmt.Printf("%s\n", err)
		return nil
	}
	defer ctx.Release()
	fmt.Printf("OK\n")

	fmt.Printf("SCardListReaders: ")
	readers, err := ctx.ListReaders()
	if err != nil {
		fmt.Printf("NG\n")
		fmt.Printf("%s\n", err)
		return nil
	}
	fmt.Printf("OK\n")

	for i, reader := range readers {
		fmt.Printf("  Reader %d: %s\n", i, reader)
	}

	fmt.Printf("SCardGetStatusChange: ")
	rs := make([]scard.ReaderState, 1)
	rs[0].Reader = readers[0]
	err = ctx.GetStatusChange(rs, -1)
	if err != nil {
		fmt.Printf("NG\n")
		fmt.Printf("%s\n", err)
		return nil
	}
	fmt.Printf("OK\n")
	printEventState(rs[0].EventState)
	fmt.Printf("SCardConnect: ")
	card, err := ctx.Connect(readers[0], scard.ShareExclusive, scard.ProtocolAny)
	if err != nil {
		fmt.Printf("NG\n")
		fmt.Printf("%s\n", err)
		return nil
	}
	fmt.Printf("OK\n")

	fmt.Printf("SCardStatus: ")
	cs, err := card.Status()
	if err != nil {
		fmt.Printf("NG\n")
		fmt.Printf("%s\n", err)
		return nil
	}
	fmt.Printf("OK\n")

	fmt.Printf("  Reader: %s\n", cs.Reader)
	fmt.Printf("  State: 0x%08x\n", cs.State)
	fmt.Printf("  ActiveProtocol: %d\n", cs.ActiveProtocol)
	fmt.Printf("  Atr: % 02X\n", cs.Atr)

	fmt.Printf("SCardReleaseContext: ")

	err = ctx.Release()
	if err != nil {
		fmt.Printf("NG\n")
		fmt.Printf("%s\n", err)
		return nil
	}
	fmt.Printf("OK\n")
	return nil
}

var eventStateFlags = [][]interface{}{
	[]interface{}{scard.StateIgnore, "STATE_IGNORE"},
	[]interface{}{scard.StateChanged, "STATE_CHANGED"},
	[]interface{}{scard.StateUnknown, "STATE_UNKNOWN"},
	[]interface{}{scard.StateUnavailable, "STATE_UNAVAILABLE"},
	[]interface{}{scard.StateEmpty, "STATE_EMPTY"},
	[]interface{}{scard.StatePresent, "STATE_PRESENT"},
	[]interface{}{scard.StateAtrmatch, "STATE_ATRMATCH"},
	[]interface{}{scard.StateExclusive, "STATE_EXCLUSIVE"},
	[]interface{}{scard.StateInuse, "STATE_INUSE"},
	[]interface{}{scard.StateMute, "STATE_MUTE"},
	[]interface{}{scard.StateUnpowered, "STATE_UNPOWERED"},
}

func printEventState(eventState scard.StateFlag) {
	fmt.Printf("  EventState: 0x%08x\n", eventState)
	for _, flag := range eventStateFlags {
		if eventState&flag[0].(scard.StateFlag) != 0 {
			fmt.Printf("    %s\n", flag[1])
		}
	}
}

func init() {
}
<commit_msg>refactoring<commit_after>package cmd

import (
	"fmt"

	"github.com/ebfe/scard"
	"github.com/spf13/cobra"
)

var testCmd = &cobra.Command{
	Use:   "test",
	Short: "リーダーの動作確認",
	Long:  "カードリーダーの動作確認を行います",
	RunE:  test,
}

func test(cmd *cobra.Command, args []string) error {
	fmt.Printf("SCardEstablishContext: ")
	ctx, err := scard.EstablishContext()
	if err != nil {
		fmt.Printf("NG %s", err)
		return nil
	}
	defer ctx.Release()
	fmt.Printf("OK\n")

	fmt.Printf("SCardListReaders: ")
	readers, err := ctx.ListReaders()
	if err != nil {
		fmt.Printf("NG %s", err)
		return nil
	}
	fmt.Printf("OK\n")

	for i, reader := range readers {
		fmt.Printf("  Reader %d: %s\n", i, reader)
	}

	fmt.Printf("SCardGetStatusChange: ")
	rs := make([]scard.ReaderState, 1)
	rs[0].Reader = readers[0]
	err = ctx.GetStatusChange(rs, -1)
	if err != nil {
		fmt.Printf("NG %s", err)
		return nil
	}
	fmt.Printf("OK\n")
	printEventState(rs[0].EventState)
	fmt.Printf("SCardConnect: ")
	card, err := ctx.Connect(readers[0], scard.ShareExclusive, scard.ProtocolAny)
	if err != nil {
		fmt.Printf("NG %s", err)
		return nil
	}
	fmt.Printf("OK\n")

	fmt.Printf("SCardStatus: ")
	cs, err := card.Status()
	if err != nil {
		fmt.Printf("NG %s", err)
		return nil
	}
	fmt.Printf("OK\n")

	printCardState(cs)

	fmt.Printf("SCardReleaseContext: ")

	err = ctx.Release()
	if err != nil {
		fmt.Printf("NG %s", err)
		return nil
	}
	fmt.Printf("OK\n")
	return nil
}

var eventStateFlags = [][]interface{}{
	[]interface{}{scard.StateIgnore, "STATE_IGNORE"},
	[]interface{}{scard.StateChanged, "STATE_CHANGED"},
	[]interface{}{scard.StateUnknown, "STATE_UNKNOWN"},
	[]interface{}{scard.StateUnavailable, "STATE_UNAVAILABLE"},
	[]interface{}{scard.StateEmpty, "STATE_EMPTY"},
	[]interface{}{scard.StatePresent, "STATE_PRESENT"},
	[]interface{}{scard.StateAtrmatch, "STATE_ATRMATCH"},
	[]interface{}{scard.StateExclusive, "STATE_EXCLUSIVE"},
	[]interface{}{scard.StateInuse, "STATE_INUSE"},
	[]interface{}{scard.StateMute, "STATE_MUTE"},
	[]interface{}{scard.StateUnpowered, "STATE_UNPOWERED"},
}

func printEventState(eventState scard.StateFlag) {
	fmt.Printf("  EventState: 0x%08x\n", eventState)
	for _, flag := range eventStateFlags {
		if eventState&flag[0].(scard.StateFlag) != 0 {
			fmt.Printf("    %s\n", flag[1])
		}
	}
}

func printCardState(cs *scard.CardStatus) {
	fmt.Printf("  Reader: %s\n", cs.Reader)
	fmt.Printf("  State: 0x%08x\n", cs.State)
	fmt.Printf("  ActiveProtocol: %d\n", cs.ActiveProtocol)
	fmt.Printf("  Atr: % 02X\n", cs.Atr)
}

func init() {
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/aquasecurity/kube-bench/check"
	"github.com/fatih/color"
	"github.com/golang/glog"
)

var (
	// Print colors
	colors = map[check.State]*color.Color{
		check.PASS: color.New(color.FgGreen),
		check.FAIL: color.New(color.FgRed),
		check.WARN: color.New(color.FgYellow),
		check.INFO: color.New(color.FgBlue),
	}
)

func printWarn(msg string) {
	fmt.Fprintf(os.Stderr, "[%s] %s\n",
		colors[check.WARN].Sprintf("%s", check.WARN),
		msg,
	)
}

func printWarn(msg string) string {
	return fmt.Sprintf("[%s] %s",
		colors[check.WARN].Sprintf("%s", check.WARN),
		msg,
	)
}

func exitWithError(err error) {
	fmt.Fprintf(os.Stderr, "\n%v\n", err)
	os.Exit(1)
}

func continueWithError(err error, msg string) string {
	if err != nil {
		glog.V(1).Info(err)
	}

	if msg != "" {
		fmt.Fprintf(os.Stderr, "%s\n", msg)
	}

	return ""
}

func cleanIDs(list string) []string {
	list = strings.Trim(list, ",")
	ids := strings.Split(list, ",")

	for _, id := range ids {
		id = strings.Trim(id, " ")
	}

	return ids
}

func verifyConf(confPath ...string) {
	var missing string

	for _, c := range confPath {
		if _, err := os.Stat(c); err != nil && os.IsNotExist(err) {
			continueWithError(err, "")
			missing += c + ", "
		}
	}

	if len(missing) > 0 {
		missing = strings.Trim(missing, ", ")
		printWarn(fmt.Sprintf("Missing kubernetes config files: %s", missing))
	}

}

func verifyBin(binPath ...string) {
	var binSlice []string
	var bin string
	var missing string
	var notRunning string

	// Construct proc name for ps(1)
	for _, b := range binPath {
		_, err := exec.LookPath(b)
		bin = bin + "," + b
		binSlice = append(binSlice, b)
		if err != nil {
			missing += b + ", "
			continueWithError(err, "")
		}
	}
	bin = strings.Trim(bin, ",")

	cmd := exec.Command("ps", "-C", bin, "-o", "cmd", "--no-headers")
	out, err := cmd.Output()
	if err != nil {
		continueWithError(fmt.Errorf("%s: %s", cmd.Args, err), "")
	}

	for _, b := range binSlice {
		matched := strings.Contains(string(out), b)

		if !matched {
			notRunning += b + ", "
		}
	}

	if len(missing) > 0 {
		missing = strings.Trim(missing, ", ")
		printWarn(fmt.Sprintf("Missing kubernetes binaries: %s", missing))
	}

	if len(notRunning) > 0 {
		notRunning = strings.Trim(notRunning, ", ")
		printWarn(fmt.Sprintf("Kubernetes binaries not running: %s", notRunning))
	}
}

func verifyKubeVersion(b string) {
	// These executables might not be on the user's path.
	// TODO! Check the version number using kubectl, which is more likely to be on the path.

	_, err := exec.LookPath(b)
	if err != nil {
		continueWithError(err, printfWarn("Kubernetes version check skipped"))
		return
	}

	cmd := exec.Command(b, "--version")
	out, err := cmd.Output()
	if err != nil {
		continueWithError(err, printfWarn("Kubernetes version check skipped"))
		return
	}

	matched := strings.Contains(string(out), kubeVersion)
	if !matched {
		printWarn(fmt.Sprintf("Unsupported kubernetes version: %s", out))
	}
}
<commit_msg>Rename warning printing functions.<commit_after>package cmd

import (
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/aquasecurity/kube-bench/check"
	"github.com/fatih/color"
	"github.com/golang/glog"
)

var (
	// Print colors
	colors = map[check.State]*color.Color{
		check.PASS: color.New(color.FgGreen),
		check.FAIL: color.New(color.FgRed),
		check.WARN: color.New(color.FgYellow),
		check.INFO: color.New(color.FgBlue),
	}
)

func printlnWarn(msg string) {
	fmt.Fprintf(os.Stderr, "[%s] %s\n",
		colors[check.WARN].Sprintf("%s", check.WARN),
		msg,
	)
}

func sprintlnWarn(msg string) string {
	return fmt.Sprintf("[%s] %s",
		colors[check.WARN].Sprintf("%s", check.WARN),
		msg,
	)
}

func exitWithError(err error) {
	fmt.Fprintf(os.Stderr, "\n%v\n", err)
	os.Exit(1)
}

func continueWithError(err error, msg string) string {
	if err != nil {
		glog.V(1).Info(err)
	}

	if msg != "" {
		fmt.Fprintf(os.Stderr, "%s\n", msg)
	}

	return ""
}

func cleanIDs(list string) []string {
	list = strings.Trim(list, ",")
	ids := strings.Split(list, ",")

	for _, id := range ids {
		id = strings.Trim(id, " ")
	}

	return ids
}

func verifyConf(confPath ...string) {
	var missing string

	for _, c := range confPath {
		if _, err := os.Stat(c); err != nil && os.IsNotExist(err) {
			continueWithError(err, "")
			missing += c + ", "
		}
	}

	if len(missing) > 0 {
		missing = strings.Trim(missing, ", ")
		printlnWarn(fmt.Sprintf("Missing kubernetes config files: %s", missing))
	}

}

func verifyBin(binPath ...string) {
	var binSlice []string
	var bin string
	var missing string
	var notRunning string

	// Construct proc name for ps(1)
	for _, b := range binPath {
		_, err := exec.LookPath(b)
		bin = bin + "," + b
		binSlice = append(binSlice, b)
		if err != nil {
			missing += b + ", "
			continueWithError(err, "")
		}
	}
	bin = strings.Trim(bin, ",")

	cmd := exec.Command("ps", "-C", bin, "-o", "cmd", "--no-headers")
	out, err := cmd.Output()
	if err != nil {
		continueWithError(fmt.Errorf("%s: %s", cmd.Args, err), "")
	}

	for _, b := range binSlice {
		matched := strings.Contains(string(out), b)

		if !matched {
			notRunning += b + ", "
		}
	}

	if len(missing) > 0 {
		missing = strings.Trim(missing, ", ")
		printlnWarn(fmt.Sprintf("Missing kubernetes binaries: %s", missing))
	}

	if len(notRunning) > 0 {
		notRunning = strings.Trim(notRunning, ", ")
		printlnWarn(fmt.Sprintf("Kubernetes binaries not running: %s", notRunning))
	}
}

func verifyKubeVersion(b string) {
	// These executables might not be on the user's path.
	// TODO! Check the version number using kubectl, which is more likely to be on the path.

	_, err := exec.LookPath(b)
	if err != nil {
		continueWithError(err, sprintlnWarn("Kubernetes version check skipped"))
		return
	}

	cmd := exec.Command(b, "--version")
	out, err := cmd.Output()
	if err != nil {
		continueWithError(err, sprintlnWarn("Kubernetes version check skipped"))
		return
	}

	matched := strings.Contains(string(out), kubeVersion)
	if !matched {
		printlnWarn(fmt.Sprintf("Unsupported kubernetes version: %s", out))
	}
}
<|endoftext|>