package commands

import (
	"fmt"
	"github.com/spf13/cobra"
)

var minCommits, maxCommits int

var randomCmd = &cobra.Command{
	Use:   "random",
	Short: "Random will add commits throughout the past 365 days.",
	Long: `Random will create a git repo at the given location and create
random commits, random meaning the number of commits per day.
This will be done for the past 365 days and the commits are in the range of
--min and --max commits.`,
	Run: randomRun,
}

func randomRun(cmd *cobra.Command, args []string) {
	fmt.Println(Location)
}

func init() {
	randomCmd.Flags().IntVar(&minCommits, "min", 1,
		"minimal #commits on a given day.")
	randomCmd.Flags().IntVar(&maxCommits, "max", 10,
		"maximal #commits on a given day.")
	PunchCardCmd.AddCommand(randomCmd)
}

package commands

import (
	"fmt"
	"github.com/spf13/cobra"
)

var minCommits, maxCommits int

var randomCmd = &cobra.Command{
	Use:   "random",
	Short: "Random will add commits throughout the past 365 days.",
	Long: `Random will create a git repo at the given location and create
random commits, random meaning the number of commits per day.
This will be done for the past 365 days and the commits are in the range of
--min and --max commits.`,
	Run: randomRun,
}

func randomRun(cmd *cobra.Command, args []string) {
	// TODO replace with actual function
	fmt.Println(Location)
}

func init() {
	randomCmd.Flags().IntVar(&minCommits, "min", 1,
		"minimal #commits on a given day.")
	randomCmd.Flags().IntVar(&maxCommits, "max", 10,
		"maximal #commits on a given day.")
	PunchCardCmd.AddCommand(randomCmd)
}

Add TODO for actual functionality.


// Copyright 2014 Vic Demuzere
//
// Use of this source code is governed by the MIT license.

// Package irc allows your application to speak the IRC protocol.
//
// The Message and Prefix structs provide translation to and from raw IRC messages:
//
//    // Parse the IRC-encoded data and store the result in a new struct:
//    message := irc.ParseMessage(raw)
//
//    // Translate back to a raw IRC message string:
//    raw = message.String()
//
// Decoder and Encoder can be used to decode and encode messages in a stream:
//
//    // Create a decoder that reads from given io.Reader
//    dec := irc.NewDecoder(reader)
//
//    // Decode the next IRC message
//    message, err := dec.Decode()
//
//    // Create an encoder that writes to given io.Writer
//    enc := irc.NewEncoder(writer)
//
//    // Send a message to the writer.
//    enc.Encode(message)
//
// The Conn type combines an Encoder and Decoder for a duplex connection.
//
//    c, err := irc.Dial("irc.server.net:6667")
//
//    // Methods from both Encoder and Decoder are available
//    message, err := c.Decode()
//
package irc // import "github.com/sorcix/irc"

Add Go 1.4 import comment


package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

func main() {
	for _, arg := range os.Args[1:] {
		fmt.Println("address was " + arg)
		fetch(arg)
	}
}

func fetch(arg string) {
	start := time.Now()
	response, err := http.Get(arg)
	contents, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Printf("ERROR %s\n", err)
	} else {
		fmt.Printf("%s\n", string(contents))
	}
	elapsed := time.Since(start)
	fmt.Printf("%dnS\n", elapsed.Nanoseconds())
}

package main

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"time"
)

func main() {
	for _, arg := range os.Args[1:] {
		fmt.Println("address was " + arg)
		fetch(arg)
	}
}

func fetch(arg string) {
	start := time.Now()
	response, err := http.Get(arg)
	if err != nil {
		fmt.Printf("ERROR %s\n", err)
		return
	}
	contents, err := ioutil.ReadAll(response.Body)
	if err != nil {
		fmt.Printf("ERROR %s\n", err)
		return
	}
	fmt.Printf("%s\n", string(contents))
	elapsed := time.Since(start)
	fmt.Printf("%dnS\n", elapsed.Nanoseconds())
}

Fix segfault on invalid address


package read

// Fk scores the Flesch-Kincaid Grade Level.
// See https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests.
func Fk(text string) float64 {
	sylCnt := float64(CntSyls(text))
	wordCnt := float64(CntWords(text))
	sentCnt := float64(CntSents(text))
	return 0.39*(wordCnt/sentCnt) + 11.8*(sylCnt/wordCnt) - 15.59

}

package read

import (
	"github.com/mtso/syllables"
)

// Fk scores the Flesch-Kincaid Grade Level.
// See https://en.wikipedia.org/wiki/Flesch%E2%80%93Kincaid_readability_tests.
func Fk(text string) float64 {
	syllableCount := float64(syllables.In(text))
	wordCnt := float64(CntWords(text))
	sentCnt := float64(CntSents(text))
	return 0.39*(wordCnt/sentCnt) + 11.8*(syllableCount/wordCnt) - 15.59
}

Add better syllable counter to flesch kincaid func


package clock

import "time"

type Clock interface {
	NewTicker(time.Duration) Ticker
	Now() time.Time
}

func New() Clock {
	return clock{}
}

type clock struct{}

func (c clock) NewTicker(d time.Duration) Ticker {
	return &ticker{
		ticker: time.NewTicker(d),
	}
}

func (c clock) Now() time.Time {
	return time.Now()
}

type Ticker interface {
	C() <-chan time.Time
	Stop()
	Reset(time.Duration)
}

type ticker struct {
	ticker *time.Ticker
}

func (t *ticker) Stop() {
	t.ticker.Stop()
}

func (t *ticker) Reset(d time.Duration) {
	t.ticker.Reset(d)
}

func (t *ticker) C() <-chan time.Time {
	return t.ticker.C
}

var _ Ticker = &ticker{}

package clock

import "time"

type Clock interface {
	NewTicker(time.Duration) Ticker
	Now() time.Time
}

func New() Clock {
	return clock{}
}

type clock struct{}

func (c clock) NewTicker(d time.Duration) Ticker {
	return &ticker{
		ticker: time.NewTicker(d),
	}
}

func (c clock) Now() time.Time {
	return time.Now()
}

type Ticker interface {
	C() <-chan time.Time
	Stop()
	Reset(time.Duration)
}

type ticker struct {
	ticker *time.Ticker
}

func (t *ticker) Stop() {
	t.ticker.Stop()
}

func (t *ticker) Reset(d time.Duration) {
	ticker, ok := (interface{})(t.ticker).(interface {
		Reset(time.Duration)
	})
	if !ok {
		panic("Ticker.Reset not implemented in this Go version.")
	}

	ticker.Reset(d)
}

func (t *ticker) C() <-chan time.Time {
	return t.ticker.C
}

var _ Ticker = &ticker{}

Fix compile error in Go 1.14 due to time.Ticker.Reset


package gorand

import (
	"testing"
)

func TestID(t *testing.T) {
	id, err := ID()
	if err != nil {
		t.Error(err.Error())
	}

	if len(id) != 128 {
		t.Error("Length of UUID isn't 128")
	}
}

func TestUUID(t *testing.T) {
	uuid, err := UUID()
	if err != nil {
		t.Error(err.Error())
	}

	if len(uuid) != 36 {
		t.Error("Length of UUID isn't 36")
	}
}

func TestMarshalUUID(t *testing.T) {
	uuid, err := UUID()
	if err != nil {
		t.Error(err.Error())
	}

	m, err := UnmarshalUUID(uuid)
	if err != nil {
		t.Error(err.Error())
	}

	u, err := MarshalUUID(m)
	if err != nil {
		t.Error(err.Error())
	}

	if u != uuid {
		t.Errorf("%s != %s after Unmarshal and Marshal")
	}
}

func BenchmarkID(b *testing.B) {
	for n := 0; n < b.N; n++ {
		ID()
	}
}

func BenchmarkUUID(b *testing.B) {
	for n := 0; n < b.N; n++ {
		UUID()
	}
}

package gorand

import (
	"testing"
)

func TestID(t *testing.T) {
	id, err := ID()
	if err != nil {
		t.Error(err.Error())
	}

	if len(id) != 128 {
		t.Error("Length of UUID isn't 128")
	}
}

func TestUUID(t *testing.T) {
	uuid, err := UUID()
	if err != nil {
		t.Error(err.Error())
	}

	if len(uuid) != 36 {
		t.Error("Length of UUID isn't 36")
	}
}

func TestMarshalUUID(t *testing.T) {
	uuid, err := UUID()
	if err != nil {
		t.Error(err.Error())
	}

	m, err := UnmarshalUUID(uuid)
	if err != nil {
		t.Error(err.Error())
	}

	u, err := MarshalUUID(m)
	if err != nil {
		t.Error(err.Error())
	}

	if u != uuid {
		t.Errorf("%s != %s after Unmarshal and Marshal", u, uuid)
	}
}

func BenchmarkID(b *testing.B) {
	for n := 0; n < b.N; n++ {
		ID()
	}
}

func BenchmarkUUID(b *testing.B) {
	for n := 0; n < b.N; n++ {
		UUID()
	}
}

Fix error reporting on test.


package tunnelserver

import (
	"net/http"

	"github.com/rancher/remotedialer"
	"github.com/sirupsen/logrus"
)

type Authorizers struct {
	chain []remotedialer.Authorizer
}

func ErrorWriter(rw http.ResponseWriter, req *http.Request, code int, err error) {
	logrus.Errorf("Failed to handling tunnel request from %s: response %d: %v", req.RemoteAddr, code, err)
	remotedialer.DefaultErrorWriter(rw, req, code, err)
}

func (a *Authorizers) Authorize(req *http.Request) (clientKey string, authed bool, err error) {
	var (
		firstErr error
	)

	for _, auth := range a.chain {
		key, authed, err := auth(req)
		if err != nil || !authed {
			if firstErr == nil {
				firstErr = err
			}
			continue
		}
		return key, authed, err
	}

	return "", false, firstErr
}

func (a *Authorizers) Add(authorizer remotedialer.Authorizer) {
	a.chain = append(a.chain, authorizer)
}

package tunnelserver

import (
	"fmt"
	"net/http"

	"github.com/rancher/remotedialer"
	"github.com/sirupsen/logrus"
)

type Authorizers struct {
	chain []remotedialer.Authorizer
}

func ErrorWriter(rw http.ResponseWriter, req *http.Request, code int, err error) {
	fullAddress := req.RemoteAddr
	forwardedFor := req.Header.Get("X-Forwarded-For")
	if forwardedFor != "" {
		fullAddress = fmt.Sprintf("%s (X-Forwarded-For: %s)", req.RemoteAddr, forwardedFor)
	}
	logrus.Errorf("Failed to handling tunnel request from remote address %s: response %d: %v", fullAddress, code, err)
	logrus.Tracef("ErrorWriter: response code: %d, request: %v", code, req)
	remotedialer.DefaultErrorWriter(rw, req, code, err)
}

func (a *Authorizers) Authorize(req *http.Request) (clientKey string, authed bool, err error) {
	var (
		firstErr error
	)

	for _, auth := range a.chain {
		key, authed, err := auth(req)
		if err != nil || !authed {
			if firstErr == nil {
				firstErr = err
			}
			continue
		}
		return key, authed, err
	}

	return "", false, firstErr
}

func (a *Authorizers) Add(authorizer remotedialer.Authorizer) {
	a.chain = append(a.chain, authorizer)
}

Add more logging on failed tunnel requests


package cliedit

import (
	"testing"

	"github.com/elves/elvish/cli/el/codearea"
	"github.com/elves/elvish/edit/ui"
	"github.com/elves/elvish/eval"
	"github.com/elves/elvish/styled"
	"github.com/elves/elvish/util"
)

func TestCompletion(t *testing.T) {
	_, cleanupDir := eval.InTempHome()
	util.ApplyDir(util.Dir{"a": "", "b": ""})
	defer cleanupDir()
	ed, ttyCtrl, ev, _, cleanup := setupStarted()
	defer cleanup()

	ed.app.CodeArea().MutateState(func(s *codearea.State) {
		s.CodeBuffer.InsertAtDot("echo ")
	})
	evalf(ev, "edit:completion:start")
	wantBuf := ui.NewBufferBuilder(40).
		WriteStyled(styled.MarkLines(
			"~> echo a ", styles,
			"        --",
			"COMPLETING argument ", styles,
			"mmmmmmmmmmmmmmmmmmm ")).
		SetDotToCursor().
		Newline().
		WriteStyled(styled.MarkLines(
			"a  b", styles,
			"#   ",
		)).
		Buffer()
	ttyCtrl.TestBuffer(t, wantBuf)
}

package cliedit

import (
	"testing"

	"github.com/elves/elvish/cli/el/codearea"
	"github.com/elves/elvish/edit/ui"
	"github.com/elves/elvish/eval"
	"github.com/elves/elvish/styled"
	"github.com/elves/elvish/util"
)

func TestCompletion(t *testing.T) {
	_, cleanupDir := eval.InTempHome()
	util.ApplyDir(util.Dir{"a": "", "b": ""})
	defer cleanupDir()
	ed, ttyCtrl, ev, _, cleanup := setupStarted()
	defer cleanup()

	ed.app.CodeArea().MutateState(func(s *codearea.State) {
		s.CodeBuffer.InsertAtDot("echo ")
	})
	evalf(ev, "edit:completion:start")
	wantBuf := ui.NewBufferBuilder(40).
		WriteStyled(styled.MarkLines(
			"~> echo a ", styles,
			"   gggg --",
			"COMPLETING argument ", styles,
			"mmmmmmmmmmmmmmmmmmm ")).
		SetDotToCursor().
		Newline().
		WriteStyled(styled.MarkLines(
			"a  b", styles,
			"#   ",
		)).
		Buffer()
	ttyCtrl.TestBuffer(t, wantBuf)
}

Fix the completion test case.


package rpcd

import (
	"encoding/gob"
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/proto/objectserver"
	"io"
	"runtime"
)

func (t *srpcType) AddObjects(conn *srpc.Conn) {
	defer runtime.GC() // An opportune time to take out the garbage.
	defer conn.Flush()
	decoder := gob.NewDecoder(conn)
	encoder := gob.NewEncoder(conn)
	numAdded := 0
	numObj := 0
	for ; ; numObj++ {
		var request objectserver.AddObjectRequest
		var response objectserver.AddObjectResponse
		if err := decoder.Decode(&request); err != nil {
			if err == io.EOF || err == io.ErrUnexpectedEOF {
				break
			}
			response.Error = err
		} else if request.Length < 1 {
			break
		} else {
			var added bool
			response.Hash, response.Added, response.Error =
				t.objectServer.AddObject(
					conn, request.Length, request.ExpectedHash)
			if added {
				numAdded++
			}
		}
		encoder.Encode(response)
		if response.Error != nil {
			return
		}
	}
	t.logger.Printf("AddObjects(): %d of %d are new objects", numAdded, numObj)
}

package rpcd

import (
	"encoding/gob"
	"github.com/Symantec/Dominator/lib/srpc"
	"github.com/Symantec/Dominator/proto/objectserver"
	"io"
	"runtime"
)

func (t *srpcType) AddObjects(conn *srpc.Conn) {
	defer runtime.GC() // An opportune time to take out the garbage.
	defer conn.Flush()
	decoder := gob.NewDecoder(conn)
	encoder := gob.NewEncoder(conn)
	numAdded := 0
	numObj := 0
	for ; ; numObj++ {
		var request objectserver.AddObjectRequest
		var response objectserver.AddObjectResponse
		if err := decoder.Decode(&request); err != nil {
			if err == io.EOF || err == io.ErrUnexpectedEOF {
				break
			}
			response.Error = err
		} else if request.Length < 1 {
			break
		} else {
			response.Hash, response.Added, response.Error =
				t.objectServer.AddObject(
					conn, request.Length, request.ExpectedHash)
			if response.Added {
				numAdded++
			}
		}
		encoder.Encode(response)
		if response.Error != nil {
			return
		}
	}
	t.logger.Printf("AddObjects(): %d of %d are new objects", numAdded, numObj)
}

Fix bug in AddObjects() RPC: new objects were not being counted.


package testutils

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

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

func BuildExecutable() error {
	return BuildExecutableForArch("")
}

func BuildExecutableForArch(arch string) error {
	buildArg := "./../bin/build"
	if arch != "" {
		buildArg = buildArg + "-" + arch
	}

	session, err := RunCommand(buildArg)
	if session.ExitCode() != 0 {
		return fmt.Errorf("Failed to build bosh-micro:\nstdout:\n%s\nstderr:\n%s", session.Out.Contents(), session.Err.Contents())
	}
	return err
}

func RunBoshMicro(args ...string) (*gexec.Session, error) {
	return RunCommand("./../out/bosh-micro", args...)
}

func RunCommand(cmd string, args ...string) (*gexec.Session, error) {
	command := exec.Command(cmd, args...)
	return RunComplexCommand(command)
}

func RunComplexCommand(cmd *exec.Cmd) (*gexec.Session, error) {
	session, err := gexec.Start(cmd, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter)
	if err != nil {
		return nil, err
	}

	session.Wait(10 * time.Second)
	return session, nil
}

package testutils

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

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

func BuildExecutable() error {
	return BuildExecutableForArch("")
}

func BuildExecutableForArch(arch string) error {
	buildArg := "./../bin/build"
	if arch != "" {
		buildArg = buildArg + "-" + arch
	}

	session, err := RunCommand(buildArg)
	if session.ExitCode() != 0 {
		return fmt.Errorf("Failed to build bosh-micro:\nstdout:\n%s\nstderr:\n%s", session.Out.Contents(), session.Err.Contents())
	}
	return err
}

func RunBoshMicro(args ...string) (*gexec.Session, error) {
	return RunCommand("./../out/bosh-micro", args...)
}

func RunCommand(cmd string, args ...string) (*gexec.Session, error) {
	command := exec.Command(cmd, args...)
	return RunComplexCommand(command)
}

func RunComplexCommand(cmd *exec.Cmd) (*gexec.Session, error) {
	session, err := gexec.Start(cmd, ginkgo.GinkgoWriter, ginkgo.GinkgoWriter)
	if err != nil {
		return nil, err
	}

	session.Wait(20 * time.Second)
	return session, nil
}

Increase wait time for bosh-micro build


// +build !php7

package engine

// #cgo CFLAGS: -Iinclude/php5
// #cgo LDFLAGS: -lphp5
import "C"

// +build !php7

package engine

// #cgo CFLAGS: -I/usr/include/php5 -I/usr/include/php5/main -I/usr/include/php5/TSRM
// #cgo CFLAGS: -I/usr/include/Zend -Iinclude/php5
// #cgo LDFLAGS: -lphp5
import "C"

Add necessary include directives for PHP 5 path


package gocql

import (
	"testing"
)

func TestErrorsParse(t *testing.T) {
	session := createSession(t)
	defer session.Close()

	if err := session.Query(`CREATE TABLE errors_parse (id int primary key)`).Exec(); err != nil {
		t.Fatal("create:", err)
	}

	if err := session.Query(`CREATE TABLE errors_parse (id int primary key)`).Exec(); err == nil {
		t.Fatal("Should have gotten already exists error from cassandra server.")
	} else {
		switch e := err.(type) {
		case RequestErrAlreadyExists:
			if e.Table != "errors_parse" {
				t.Fatal("Failed to parse error response from cassandra for ErrAlreadyExists.")
			}
		default:
			t.Fatal("Failed to parse error response from cassandra for ErrAlreadyExists.")
		}
	}
}

package gocql

import (
	"testing"
)

func TestErrorsParse(t *testing.T) {
	session := createSession(t)
	defer session.Close()

	if err := createTable(session, `CREATE TABLE errors_parse (id int primary key)`); err != nil {
		t.Fatal("create:", err)
	}

	if err := createTable(session, `CREATE TABLE errors_parse (id int primary key)`); err == nil {
		t.Fatal("Should have gotten already exists error from cassandra server.")
	} else {
		switch e := err.(type) {
		case RequestErrAlreadyExists:
			if e.Table != "errors_parse" {
				t.Fatal("Failed to parse error response from cassandra for ErrAlreadyExists.")
			}
		default:
			t.Fatal("Failed to parse error response from cassandra for ErrAlreadyExists.")
		}
	}
}

Use createTable to create tables, this test is slightly racy with > 1 node


package isolated

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"

	"code.cloudfoundry.org/cli/integration/helpers"
)

var _ = Describe("set-org-role command", func() {
	When("the org and user both exist", func() {
		var (
			username string
			orgName  string
		)

		BeforeEach(func() {
			helpers.LoginCF()
			orgName = helpers.NewOrgName()
			helpers.CreateOrg(orgName)
			username, _ = helpers.CreateUser()
		})

		It("sets the org role for the user", func() {
			session := helpers.CF("set-org-role", username, orgName, "OrgAuditor")
			Eventually(session).Should(Say("Assigning role OrgAuditor to user %s in org %s as admin...", username, orgName))
			Eventually(session).Should(Say("OK"))
			Eventually(session).Should(Exit(0))
		})
	})
})

package isolated

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/onsi/gomega/gbytes"
	. "github.com/onsi/gomega/gexec"

	"code.cloudfoundry.org/cli/integration/helpers"
)

var _ = Describe("set-org-role command", func() {
	When("the org and user both exist", func() {
		var (
			username string
			orgName  string
		)

		BeforeEach(func() {
			helpers.LoginCF()
			orgName = helpers.NewOrgName()
			helpers.CreateOrg(orgName)
			username, _ = helpers.CreateUser()
		})

		It("sets the org role for the user", func() {
			session := helpers.CF("set-org-role", username, orgName, "OrgAuditor")
			Eventually(session).Should(Say("Assigning role OrgAuditor to user %s in org %s as admin...", username, orgName))
			Eventually(session).Should(Say("OK"))
			Eventually(session).Should(Exit(0))
		})

		When("the user already has the desired role", func() {
			BeforeEach(func() {
				session := helpers.CF("set-org-role", username, orgName, "OrgManager")
				Eventually(session).Should(Say("Assigning role OrgManager to user %s in org %s as admin...", username, orgName))
				Eventually(session).Should(Exit(0))
			})

			It("is idempotent", func() {
				session := helpers.CF("set-org-role", username, orgName, "OrgManager")
				Eventually(session).Should(Say("Assigning role OrgManager to user %s in org %s as admin...", username, orgName))
				Eventually(session).Should(Exit(0))
			})
		})
	})
})

Test that set-org-role is idempotent


package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func killBrowserHandler(c *gin.Context) {

	var data struct {
		Action  string `json:"action"`
		Process string `json:"process"`
		URL     string `json:"url"`
	}

	c.BindJSON(&data)

	command, err := findBrowser(data.Process)

	log.Println(command)

	if err != nil {
		c.JSON(http.StatusInternalServerError, err)
	}

	if data.Action == "kill" || data.Action == "restart" {
		_, err := killBrowser(data.Process)
		if err != nil {
			c.JSON(http.StatusInternalServerError, err)
		}
	}

	if data.Action == "restart" {
		_, err := startBrowser(command, data.URL)
		if err != nil {
			c.JSON(http.StatusInternalServerError, err)
		}
	}

}

package main

import (
	"log"
	"net/http"

	"github.com/gin-gonic/gin"
)

func killBrowserHandler(c *gin.Context) {

	var data struct {
		Action  string `json:"action"`
		Process string `json:"process"`
		URL     string `json:"url"`
	}

	c.BindJSON(&data)

	command, err := findBrowser(data.Process)

	log.Println(command)

	if err != nil {
		c.JSON(http.StatusInternalServerError, err)
	}

	if data.Action == "kill" || data.Action == "restart" {
		// _, err := killBrowser(data.Process)
		// if err != nil {
		// 	c.JSON(http.StatusInternalServerError, err)
		// }
	}

	if data.Action == "restart" {
		_, err := startBrowser(command, data.URL)
		if err != nil {
			c.JSON(http.StatusInternalServerError, err)
		}
	}

}

Test without killing to see what's going wrong on windows


package main

import (
	"bufio"
	"io"
	"log"
	"time"

	"github.com/logplex/logplexc"
)

func lineWorker(die dieCh, r *bufio.Reader, cfg logplexc.Config, sr *serveRecord) {
	cfg.Logplex = sr.u

	target, err := logplexc.NewClient(&cfg)
	if err != nil {
		log.Fatalf("could not create logging client: %v", err)
	}

	for {
		select {
		case <-die:
			return
		default:
			break
		}

		l, _, err := r.ReadLine()
		if len(l) > 0 {
			target.BufferMessage(134, time.Now(), "app", "redis", l)
		}

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

package main

import (
	"bufio"
	"io"
	"log"
	"regexp"
	"time"

	"github.com/logplex/logplexc"
)

var prefix = regexp.MustCompile(`^(\[\d*\] [^-*#]+|.*)`)

func lineWorker(die dieCh, r *bufio.Reader, cfg logplexc.Config, sr *serveRecord) {
	cfg.Logplex = sr.u

	target, err := logplexc.NewClient(&cfg)
	if err != nil {
		log.Fatalf("could not create logging client: %v", err)
	}

	for {
		select {
		case <-die:
			return
		default:
			break
		}

		l, _, err := r.ReadLine()
		l = prefix.ReplaceAll(l, []byte(""))
		if len(l) > 0 {
			target.BufferMessage(134, time.Now(), "redis",
				sr.Name, l)
		}

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

Remove prefix and use name as procId.


package main_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"

	"testing"
)

func TestBinaries(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Binaries Suite")
}

var _ = AfterSuite(func() {
	gexec.CleanupBuildArtifacts()
})

var _ = Describe("Binaries", func() {
	It("builds cred-alert-ingestor", func() {
		_, err := gexec.Build("cred-alert/cmd/cred-alert-ingestor")
		Expect(err).NotTo(HaveOccurred())
	})

	It("builds cred-alert-worker", func() {
		_, err := gexec.Build("cred-alert/cmd/cred-alert-worker")
		Expect(err).NotTo(HaveOccurred())
	})

	It("builds stats-monitor", func() {
		_, err := gexec.Build("cred-alert/cmd/stats-monitor")
		Expect(err).NotTo(HaveOccurred())
	})
})

package main_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"

	"testing"
)

func TestBinaries(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "Binaries Suite")
}

var _ = AfterSuite(func() {
	gexec.CleanupBuildArtifacts()
})

var _ = Describe("Binaries", func() {
	It("builds cred-alert-worker-ng", func() {
		_, err := gexec.Build("cred-alert/cmd/cred-alert-worker-ng")
		Expect(err).NotTo(HaveOccurred())
	})

	It("builds cred-alert-ingestor", func() {
		_, err := gexec.Build("cred-alert/cmd/cred-alert-ingestor")
		Expect(err).NotTo(HaveOccurred())
	})

	It("builds cred-alert-worker", func() {
		_, err := gexec.Build("cred-alert/cmd/cred-alert-worker")
		Expect(err).NotTo(HaveOccurred())
	})

	It("builds stats-monitor", func() {
		_, err := gexec.Build("cred-alert/cmd/stats-monitor")
		Expect(err).NotTo(HaveOccurred())
	})
})

Add missing cred-alert-worker-ng build test


package main

import (
    "github.com/itsankoff/gotcha/server"
    "time"
    "log"
)

func main() {
    s := server.New()
    wss := server.NewWebSocket()
    s.AddTransport("127.0.0.1:9000", &wss)
    done := make(chan interface{})
    go func() {
        log.Println("Will close done channel")
        time.Sleep(10 * time.Second)
        log.Println("Close done channel")
        close(done)
    }()

    err := s.Start(done)
    if err != nil {
        log.Fatal("Failed to start server")
    }
}

package main

import (
    "github.com/itsankoff/gotcha/server"
    "log"
)

func main() {
    s := server.New()
    wss := server.NewWebSocket()
    s.AddTransport("127.0.0.1:9000", &wss)
    done := make(chan interface{})

    err := s.Start(done)
    if err != nil {
        log.Fatal("Failed to start server")
    }
}

Remove test code from cmd server code


package eventnotifier

import (
	"net/http"
	"sync"

	"github.com/Symantec/Dominator/lib/log"
	"github.com/Symantec/keymaster/proto/eventmon"
)

type EventNotifier struct {
	logger log.DebugLogger
	mutex  sync.Mutex
	// Protected by lock.
	transmitChannels map[chan<- eventmon.EventV0]chan<- eventmon.EventV0
}

func New(logger log.DebugLogger) *EventNotifier {
	return newEventNotifier(logger)
}

func (n *EventNotifier) PublishAuthEvent(authType, username string) {
	n.publishAuthEvent(authType, username)
}

func (n *EventNotifier) PublishServiceProviderLoginEvent(url string) {
}

func (n *EventNotifier) PublishSSH(cert []byte) {
	n.publishCert(eventmon.EventTypeSSHCert, cert)
}

func (n *EventNotifier) PublishWebLoginEvent(username string) {
	n.publishWebLoginEvent(username)
}

func (n *EventNotifier) PublishX509(cert []byte) {
	n.publishCert(eventmon.EventTypeX509Cert, cert)
}

func (n *EventNotifier) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	n.serveHTTP(w, req)
}

package eventnotifier

import (
	"net/http"
	"sync"

	"github.com/Symantec/Dominator/lib/log"
	"github.com/Symantec/keymaster/proto/eventmon"
)

type EventNotifier struct {
	logger log.DebugLogger
	mutex  sync.Mutex
	// Protected by lock.
	transmitChannels map[chan<- eventmon.EventV0]chan<- eventmon.EventV0
}

func New(logger log.DebugLogger) *EventNotifier {
	return newEventNotifier(logger)
}

func (n *EventNotifier) PublishAuthEvent(authType, username string) {
	n.publishAuthEvent(authType, username)
}

func (n *EventNotifier) PublishServiceProviderLoginEvent(url, username string) {
}

func (n *EventNotifier) PublishSSH(cert []byte) {
	n.publishCert(eventmon.EventTypeSSHCert, cert)
}

func (n *EventNotifier) PublishWebLoginEvent(username string) {
	n.publishWebLoginEvent(username)
}

func (n *EventNotifier) PublishX509(cert []byte) {
	n.publishCert(eventmon.EventTypeX509Cert, cert)
}

func (n *EventNotifier) ServeHTTP(w http.ResponseWriter, req *http.Request) {
	n.serveHTTP(w, req)
}

Add username to PublishServiceProviderLoginEvent() arguments.


package analyze

type ValidMicro struct {
	Micro int64
	Valid bool
}

type ValidFloat struct {
	Value float64
	Valid bool
}

package analyze

import "encoding/json"

type ValidMicro struct {
	Micro int64
	Valid bool
}

func (vm ValidMicro) MarshalJson() ([]byte, error) {
	if vm.Valid {
		return json.Marshal(MicrosToDollars(vm.Micro))
	}
	return json.Marshal(nil)
}

type ValidFloat struct {
	Value float64
	Valid bool
}

func (vf ValidFloat) MarshalJson() ([]byte, error) {
	if vf.Valid {
		return json.Marshal(vf.Value)
	}
	return json.Marshal(nil)
}

Add custom json marshalling for indicators


package h2spec

import (
	"fmt"
	"io"
	"net"
	"syscall"
	"time"
)

func Http2ConnectionPrefaceTestGroup(ctx *Context) *TestGroup {
	tg := NewTestGroup("3.5", "HTTP/2 Connection Preface")

	tg.AddTestCase(NewTestCase(
		"Sends invalid connection preface",
		"The endpoint MUST terminate the TCP connection.",
		func(ctx *Context) (expected []Result, actual Result) {
			expected = []Result{
				&ResultConnectionClose{},
			}

			tcpConn := CreateTcpConn(ctx)
			defer tcpConn.conn.Close()

			fmt.Fprintf(tcpConn.conn, "INVALID CONNECTION PREFACE")
			timeCh := time.After(ctx.Timeout)

		loop:
			for {
				select {
				case <-tcpConn.dataCh:
					break
				case err := <-tcpConn.errCh:
					opErr, ok := err.(*net.OpError)
					if err == io.EOF || (ok && opErr.Err == syscall.ECONNRESET) {
						actual = &ResultConnectionClose{}
					} else {
						actual = &ResultError{err}
					}
					break loop
				case <-timeCh:
					actual = &ResultTestTimeout{}
					break loop
				}
			}

			return expected, actual
		},
	))

	return tg
}

package h2spec

import (
	"fmt"
	"io"
	"net"
	"syscall"
	"time"
)

func Http2ConnectionPrefaceTestGroup(ctx *Context) *TestGroup {
	tg := NewTestGroup("3.5", "HTTP/2 Connection Preface")

	tg.AddTestCase(NewTestCase(
		"Sends invalid connection preface",
		"The endpoint MUST terminate the TCP connection.",
		func(ctx *Context) (expected []Result, actual Result) {
			expected = []Result{
				&ResultConnectionClose{},
			}

			tcpConn := CreateTcpConn(ctx)
			defer tcpConn.conn.Close()

			fmt.Fprintf(tcpConn.conn, "INVALID CONNECTION PREFACE\r\n\r\n")
			timeCh := time.After(ctx.Timeout)

		loop:
			for {
				select {
				case <-tcpConn.dataCh:
					break
				case err := <-tcpConn.errCh:
					opErr, ok := err.(*net.OpError)
					if err == io.EOF || (ok && opErr.Err == syscall.ECONNRESET) {
						actual = &ResultConnectionClose{}
					} else {
						actual = &ResultError{err}
					}
					break loop
				case <-timeCh:
					actual = &ResultTestTimeout{}
					break loop
				}
			}

			return expected, actual
		},
	))

	return tg
}

Fix invalid connection preface as is able to process as HTTP request


// Copyright © 2015-2020 Hilko Bengen <bengen@hilluzination.de>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.

package yara

// #cgo !yara_no_pkg_config,!yara_static  pkg-config: yara
// #cgo !yara_no_pkg_config,yara_static   pkg-config: --static yara
// #cgo yara_no_pkg_config                LDFLAGS:    -lyara -lm -lcrypto
/*
#include <yara.h>
#if YR_VERSION_HEX < 0x040200
#error YARA version 4.2 required
#endif
*/
import "C"

// Copyright © 2015-2020 Hilko Bengen <bengen@hilluzination.de>
// All rights reserved.
//
// Use of this source code is governed by the license that can be
// found in the LICENSE file.

package yara

// #cgo !yara_no_pkg_config,!yara_static  pkg-config: yara
// #cgo !yara_no_pkg_config,yara_static   pkg-config: --static yara
// #cgo yara_no_pkg_config                LDFLAGS:    -lyara -lm
/*
#include <yara.h>
#if YR_VERSION_HEX < 0x040200
#error YARA version 4.2 required
#endif
*/
import "C"

Remove -lcrypto from LDFLAGS when yara_no_pkg_config is set.


package routes

import (
	"errors"
	"fmt"
	"strings"
)

// Converts patterns like "/users/:id" to "/users/(?P<id>\d+)"
func convertSimplePatternToRegexp(pattern string) string {
	parts := strings.Split(pattern, "/")
	for i, part := range parts {
		if len(part) != 0 && part[0] == ':' {
			parts[i] = fmt.Sprintf(`(?P<%s>\d+)`, part[1:])
		}
	}

	return strings.Join(parts, "/")
}

// Return path relative to "base"
func relativePath(base string, absolute string) (string, error) {
	baseLen := len(base)
	absoluteLen := len(absolute)

	if absoluteLen < baseLen {
		return "", errors.New("absolute len shorter than base len")
	}

	if absolute[:baseLen] != base {
		return "", errors.New("absolute path doesn't start with base path")
	}

	return absolute[baseLen:], nil
}

package routes

import (
	"errors"
	"fmt"
	"strings"
)

// Converts patterns like "/users/:id" to "/users/(?P<id>\d+)"
func convertSimplePatternToRegexp(pattern string) string {
	parts := strings.Split(pattern, "/")
	for i, part := range parts {
		if len(part) != 0 && part[0] == ':' {
			parts[i] = fmt.Sprintf(`(?P<%s>(?:/^[a-f\d]{24}$/i))`, part[1:])
		}
	}

	return strings.Join(parts, "/")
}

// Return path relative to "base"
func relativePath(base string, absolute string) (string, error) {
	baseLen := len(base)
	absoluteLen := len(absolute)

	if absoluteLen < baseLen {
		return "", errors.New("absolute len shorter than base len")
	}

	if absolute[:baseLen] != base {
		return "", errors.New("absolute path doesn't start with base path")
	}

	return absolute[baseLen:], nil
}

Make hex object id possible in path params.


// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package configstore_test

import (
	gc "launchpad.net/gocheck"

	"launchpad.net/juju-core/environs/configstore"
)

var _ = gc.Suite(&memInterfaceSuite{})

type memInterfaceSuite struct {
	interfaceSuite
}

func (s *memInterfaceSuite) SetUpSuite(c *gc.C) {
	s.NewStore = func(c *gc.C) configstore.Storage {
		return configstore.NewMem()
	}
}

func (s *memInterfaceSuite) TestMemInfoLocation(c *gc.C) {
	memStore := configstore.NewMem()
	c.Assert(memStore.Location(), gc.Equals, "memory")
}

// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.

package configstore_test

import (
	gc "launchpad.net/gocheck"

	"launchpad.net/juju-core/environs/configstore"
)

var _ = gc.Suite(&memInterfaceSuite{})

type memInterfaceSuite struct {
	interfaceSuite
}

func (s *memInterfaceSuite) SetUpSuite(c *gc.C) {
	s.NewStore = func(c *gc.C) configstore.Storage {
		return configstore.NewMem()
	}
}

func (s *memInterfaceSuite) TestMemInfoLocation(c *gc.C) {
	memStore := configstore.NewMem()
	memInfo, _ := memStore.CreateInfo("foo")
	c.Assert(memInfo.Location(), gc.Equals, "memory")
}

Create memInfo from memStore in test


package forge

import (
	"github.com/sclevine/forge/engine"
)

type Loader interface {
	Loading(message string, progress <-chan engine.Progress) error
}

type Colorizer func(string, ...interface{}) string

type AppConfig struct {
	Name       string            `yaml:"name"`
	Buildpack  string            `yaml:"buildpack,omitempty"`
	Buildpacks []string          `yaml:"buildpacks,omitempty"`
	Command    string            `yaml:"command,omitempty"`
	DiskQuota  string            `yaml:"disk_quota,omitempty"`
	Memory     string            `yaml:"memory,omitempty"`
	StagingEnv map[string]string `yaml:"staging_env,omitempty"`
	RunningEnv map[string]string `yaml:"running_env,omitempty"`
	Env        map[string]string `yaml:"env,omitempty"`
	Services   Services          `yaml:"services,omitempty"`
}

type NetworkConfig struct {
	ContainerID   string
	ContainerPort string
	HostIP        string
	HostPort      string
}

//go:generate mockgen -package mocks -destination mocks/container.go github.com/sclevine/forge/engine Container
//go:generate mockgen -package mocks -destination mocks/image.go github.com/sclevine/forge/engine Image
//go:generate mockgen -package mocks -destination mocks/engine.go github.com/sclevine/forge Engine
type Engine interface {
	NewContainer(config *engine.ContainerConfig) (engine.Container, error)
}

package forge

import (
	"github.com/sclevine/forge/engine"
)

type Loader interface {
	Loading(message string, progress <-chan engine.Progress) error
}

type Colorizer func(string, ...interface{}) string

type AppConfig struct {
	Name       string            `yaml:"name"`
	Buildpack  string            `yaml:"buildpack,omitempty"`
	Buildpacks []string          `yaml:"buildpacks,omitempty"`
	Command    string            `yaml:"command,omitempty"`
	DiskQuota  string            `yaml:"disk_quota,omitempty"`
	Memory     string            `yaml:"memory,omitempty"`
	StagingEnv map[string]string `yaml:"staging_env,omitempty"`
	RunningEnv map[string]string `yaml:"running_env,omitempty"`
	Env        map[string]string `yaml:"env,omitempty"`
	Services   Services          `yaml:"services,omitempty"`
}

type NetworkConfig struct {
	ContainerID   string
	ContainerPort string
	HostIP        string
	HostPort      string
}

//go:generate mockgen -package mocks -destination mocks/container.go github.com/sclevine/forge/engine Container
//go:generate mockgen -package mocks -destination mocks/engine.go github.com/sclevine/forge Engine
type Engine interface {
	NewContainer(config *engine.ContainerConfig) (engine.Container, error)
}

Remove unused image mock generator


package aws

// This list is copied from
// http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_website_region_endpoints
// It currently cannot be generated from the API json.
var hostedZoneIDsMap = map[string]string{
	"us-east-1":      "Z3AQBSTGFYJSTF",
	"us-west-2":      "Z3BJ6K6RIION7M",
	"us-west-1":      "Z2F56UZL2M1ACD",
	"eu-west-1":      "Z1BKCTXD74EZPE",
	"central-1":      "Z21DNDUVLTQW6Q",
	"ap-southeast-1": "Z3O0J2DXBE1FTB",
	"ap-southeast-2": "Z1WCIGYICN2BYD",
	"ap-northeast-1": "Z2M4EHUR26P7ZW",
	"sa-east-1":      "Z7KQH4QJS55SO",
	"us-gov-west-1":  "Z31GFT0UA1I2HV",
}

// Returns the hosted zone ID for an S3 website endpoint region. This can be
// used as input to the aws_route53_record resource's zone_id argument.
func HostedZoneIDForRegion(region string) string {
	return hostedZoneIDsMap[region]
}

package aws

// This list is copied from
// http://docs.aws.amazon.com/general/latest/gr/rande.html#s3_website_region_endpoints
// It currently cannot be generated from the API json.
var hostedZoneIDsMap = map[string]string{
	"us-east-1":      "Z3AQBSTGFYJSTF",
	"us-west-2":      "Z3BJ6K6RIION7M",
	"us-west-1":      "Z2F56UZL2M1ACD",
	"eu-west-1":      "Z1BKCTXD74EZPE",
	"eu-central-1":   "Z21DNDUVLTQW6Q",
	"ap-southeast-1": "Z3O0J2DXBE1FTB",
	"ap-southeast-2": "Z1WCIGYICN2BYD",
	"ap-northeast-1": "Z2M4EHUR26P7ZW",
	"sa-east-1":      "Z7KQH4QJS55SO",
	"us-gov-west-1":  "Z31GFT0UA1I2HV",
}

// Returns the hosted zone ID for an S3 website endpoint region. This can be
// used as input to the aws_route53_record resource's zone_id argument.
func HostedZoneIDForRegion(region string) string {
	return hostedZoneIDsMap[region]
}

Update Hosted Zones to fix issue with eu-central


package gogist

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

const t = `
<html>
  <head>
    <meta name="go-import" content="%s git https://gist.github.com/%s.git" />
    <script>window.location='https://github.com/ImJasonH/go-gist/';</script>
  </head>
</html>
`

func init() {
	r := mux.NewRouter()
	h := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
	}
	r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
	r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
	r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
	http.Handle("/", r)
}

package gogist

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

const t = `
<html>
  <head>
    <meta name="go-import" content="%s git https://gist.github.com/%s.git" />
    <script>window.location='https://github.com/ImJasonH/go-gist/';</script>
  </head>
</html>
`

func init() {
	r := mux.NewRouter()
	h := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
	}
	r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
	r.HandleFunc("/{username}/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
	r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
	r.HandleFunc("/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
	r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
	http.Handle("/", r)
}

Support user-defined convenience package names


package algoholic

import "testing"

func TestInsertionSortSortsReversedInts(t *testing.T) {
	correctlySortsReversedInts(t, 1e4, func(ns []int) []int {
		InsertionSort(ns)
		return ns
	})
}

package algoholic

import "testing"

func TestInsertionSortSortsReversedInts(t *testing.T) {
	correctlySortsReversedInts(t, 1e4, func(ns []int) []int {
		// In-place sort.
		InsertionSort(ns)
		return ns
	})
}

Add trivial though meaningful comment.


package steps

import (
	"fmt"
	"log"
	"regexp"

	"github.com/Originate/git-town/src/git"
)

// Step represents a dedicated activity within a Git Town command.
// Git Town commands are comprised of a number of steps that need to be executed.
type Step interface {
	CreateAbortStep() Step
	CreateContinueStep() Step
	CreateUndoStepBeforeRun() Step
	CreateUndoStepAfterRun() Step
	GetAutomaticAbortErrorMessage() string
	Run() error
	ShouldAutomaticallyAbortOnError() bool
}

// SerializedStep is used to store Steps as JSON.
type SerializedStep struct {
	Data []byte
	Type string
}

// SerializedRunState is used to store RunStates as JSON.
type SerializedRunState struct {
	AbortStep SerializedStep
	RunSteps  []SerializedStep
	UndoSteps []SerializedStep
}

func getRunResultFilename(command string) string {
	replaceCharacterRegexp, err := regexp.Compile("[[:^alnum:]]")
	if err != nil {
		log.Fatal("Error compiling replace character expression: ", err)
	}
	directory := replaceCharacterRegexp.ReplaceAllString(git.GetRootDirectory(), "-")
	return fmt.Sprintf("/tmp/%s_%s", command, directory)
}

package steps

import (
	"log"
	"os"
	"path"
	"regexp"

	"github.com/Originate/git-town/src/git"
)

// Step represents a dedicated activity within a Git Town command.
// Git Town commands are comprised of a number of steps that need to be executed.
type Step interface {
	CreateAbortStep() Step
	CreateContinueStep() Step
	CreateUndoStepBeforeRun() Step
	CreateUndoStepAfterRun() Step
	GetAutomaticAbortErrorMessage() string
	Run() error
	ShouldAutomaticallyAbortOnError() bool
}

// SerializedStep is used to store Steps as JSON.
type SerializedStep struct {
	Data []byte
	Type string
}

// SerializedRunState is used to store RunStates as JSON.
type SerializedRunState struct {
	AbortStep SerializedStep
	RunSteps  []SerializedStep
	UndoSteps []SerializedStep
}

func getRunResultFilename(command string) string {
	replaceCharacterRegexp, err := regexp.Compile("[[:^alnum:]]")
	if err != nil {
		log.Fatal("Error compiling replace character expression: ", err)
	}
	directory := replaceCharacterRegexp.ReplaceAllString(git.GetRootDirectory(), "-")
	return path.Join(os.TempDir(), command+"_"+directory)
}

Use the proper temp dir


package bittrex

type Order struct {
	OrderUuid         string  `json:"OrderUuid"`
	Exchange          string  `json:"Exchange"`
	TimeStamp         string  `json:"TimeStamp"`
	OrderType         string  `json:"OrderType"`
	Limit             float64 `json:"Limit"`
	Quantity          float64 `json:"Quantity"`
	QuantityRemaining float64 `json:"QuantityRemaining"`
	Commission        float64 `json:"Commission"`
	Price             float64 `json:"Price"`
	PricePerUnit      float64 `json:"PricePerUnit"`
}

// For getorder
type Order2 struct {
    AccountId         string
    OrderUuid         string  `json:"OrderUuid"`
	Exchange          string  `json:"Exchange"`
	Type              string
	Quantity          float64 `json:"Quantity"`
	QuantityRemaining float64 `json:"QuantityRemaining"`
	Limit             float64 `json:"Limit"`
    Reserved          float64
    ReserveRemaining  float64
    CommissionReserved          float64
    CommissionReserveRemaining  float64
    CommissionPaid    float64
	Price             float64 `json:"Price"`
	PricePerUnit      float64 `json:"PricePerUnit"`
	Opened            string
	Closed            string
	IsOpen            bool
	Sentinel          string
	CancelInitiated   bool
	ImmediateOrCancel bool
	IsConditional     bool
	Condition         string
	ConditionTarget   string
}

package bittrex

type Order struct {
	OrderUuid         string  `json:"OrderUuid"`
	Exchange          string  `json:"Exchange"`
	TimeStamp         jTime   `json:"TimeStamp"`
	OrderType         string  `json:"OrderType"`
	Limit             float64 `json:"Limit"`
	Quantity          float64 `json:"Quantity"`
	QuantityRemaining float64 `json:"QuantityRemaining"`
	Commission        float64 `json:"Commission"`
	Price             float64 `json:"Price"`
	PricePerUnit      float64 `json:"PricePerUnit"`
}

// For getorder
type Order2 struct {
	AccountId                  string
	OrderUuid                  string `json:"OrderUuid"`
	Exchange                   string `json:"Exchange"`
	Type                       string
	Quantity                   float64 `json:"Quantity"`
	QuantityRemaining          float64 `json:"QuantityRemaining"`
	Limit                      float64 `json:"Limit"`
	Reserved                   float64
	ReserveRemaining           float64
	CommissionReserved         float64
	CommissionReserveRemaining float64
	CommissionPaid             float64
	Price                      float64 `json:"Price"`
	PricePerUnit               float64 `json:"PricePerUnit"`
	Opened                     string
	Closed                     string
	IsOpen                     bool
	Sentinel                   string
	CancelInitiated            bool
	ImmediateOrCancel          bool
	IsConditional              bool
	Condition                  string
	ConditionTarget            string
}

Set TimeStamp field to jTime type. Run go fmt


package main

import (
	"github.com/itsankoff/gotcha/client"
)

func main() {
	c := client.New()
	c.Connect("wss://127.0.0.1:9999")
}

package main

import (
	"github.com/itsankoff/gotcha/client"
	"github.com/itsankoff/gotcha/common"
	"log"
	"time"
)

func main() {
	input := make(chan *common.Message)
	ws := client.NewWebSocketClient()
	ws.SetReceiver(input)

	c := client.New(ws)
	err := c.Connect("ws://127.0.0.1:9000/websocket")
	log.Println("connected", err)
	userId, err := c.Register("pesho", "123")
	log.Println("registered", err)

	err = c.Authenticate(userId, "123")
	log.Println("authenticated", err)

	time.Sleep(10 * time.Second)
}

Add simple show case of client usage


package release

import (
	"path/filepath"
)

// Factory is responsible for instantiating slices
// of Releases based upon queries given from the API.
type Factory struct {
	modulepath string
	fileurl    string
}

// NewFactory returns a new instance of Factory
// with the given modulepath.
func NewFactory(modulepath string, fileurl string) *Factory {
	return &Factory{
		modulepath: modulepath,
		fileurl:    fileurl,
	}
}

// AllForModule returns an instance of Release for each
// available version of a given module. Each instance will
// have had .FromDisk() called on it already prior to returning.
// An error will be returned if an error is encountered during
// the process of loading each release from disk.
func (f *Factory) AllForModule(slug string) (releases []*Release, err error) {
	tarballs, err := filepath.Glob(f.modulepath + "/" + slug + "-*.tar.gz")

	if err != nil {
		return nil, err
	}

	for _, tarball := range tarballs {
		release := New(tarball)
		release.FromDisk()
		release.File_uri = f.fileurl + "/" + release.Slug() + ".tar.gz"
		releases = append(releases, release)
	}

	return
}

package release

import (
	"path/filepath"
)

// Factory is responsible for instantiating slices
// of Releases based upon queries given from the API.
type Factory struct {
	modulepath string
	fileurl    string
}

// NewFactory returns a new instance of Factory
// with the given modulepath.
func NewFactory(modulepath string, fileurl string) *Factory {
	return &Factory{
		modulepath: modulepath,
		fileurl:    fileurl,
	}
}

// AllForModule returns an instance of Release for each
// available version of a given module. Each instance will
// have had .FromDisk() called on it already prior to returning.
// An error will be returned if an error is encountered during
// the process of loading each release from disk.
func (f *Factory) AllForModule(slug string) (releases []*Release, err error) {
	tarballs, err := filepath.Glob(f.modulepath + "/" + slug + "-*.tar.gz")

	if err != nil {
		return nil, err
	}

	for _, tarball := range tarballs {
		release := New(tarball)
		release.FromDisk()
		release.File_uri = f.fileurl + "/" + release.Slug() + ".tar.gz"
		releases = append(releases, release)
	}

	return []*Release{}, nil
}

Return array instead of nil when no results are found


package main

import (
	"fmt"
	"io/ioutil"

	"github.com/jeffail/gabs"
	"github.com/mitchellh/packer/packer"
)

func UpdateJsonFile(file string, paths []string, value string, ui packer.Ui) error {

	content, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}

	json, err := gabs.ParseJSON(content)
	if err != nil {
		return err
	}

	for _, path := range paths {
		var value string
		value, _ = json.Path(path).Data().(string)
		ui.Say(fmt.Sprintf("Updating %s to %s in %s...", path, value, file))
		json.SetP(value, path)
	}

	err = ioutil.WriteFile(file, []byte(json.StringIndent("", "    ")), 0644)
	return err
}

package main

import (
	"fmt"
	"io/ioutil"

	"github.com/jeffail/gabs"
	"github.com/mitchellh/packer/packer"
)

func UpdateJsonFile(file string, paths []string, newValue string, ui packer.Ui) error {

	content, err := ioutil.ReadFile(file)
	if err != nil {
		return err
	}

	json, err := gabs.ParseJSON(content)
	if err != nil {
		return err
	}

	for _, path := range paths {
		oldValue, _ := json.Path(path).Data().(string)
		ui.Say(fmt.Sprintf("Updating %s from %s to %s in %s...", path, oldValue, newValue, file))
		json.SetP(newValue, path)
	}

	err = ioutil.WriteFile(file, []byte(json.StringIndent("", "    ")), 0644)
	return err
}

Fix value to update to. Improve log message with old and new values.


package v1

import (
	"github.com/codegangsta/martini"
	"github.com/coopernurse/gorp"
	"github.com/hackedu/backend/v1/model"
	"github.com/hackedu/backend/v1/route"
	"github.com/martini-contrib/binding"
)

func Setup(m *martini.ClassicMartini) {
	// TODO: Only apply middleware on /v1/** routes
	m.Use(allowCORS)
	m.MapTo(Dbm, (*gorp.SqlExecutor)(nil))

	m.Get("/v1/schools", route.GetSchools)

	m.Post("/v1/users", binding.Bind(model.User{}), route.AddUser)
}

package v1

import (
	"net/http"
	"time"

	"github.com/codegangsta/martini"
	"github.com/coopernurse/gorp"
	"github.com/hackedu/backend/v1/model"
	"github.com/hackedu/backend/v1/route"
	"github.com/martini-contrib/binding"
	"github.com/zachlatta/cors"
)

func Setup(m *martini.ClassicMartini) {
	// TODO: Only apply middleware on /v1/** routes
	m.Use(cors.Allow(&cors.Options{
		AllowAllOrigins: true,
		AllowMethods:    []string{"GET", "POST"},
		MaxAge:          5 * time.Minute,
	}))
	m.MapTo(Dbm, (*gorp.SqlExecutor)(nil))

	m.Get("/v1/schools", route.GetSchools)

	m.Post("/v1/users", binding.Bind(model.User{}), route.AddUser)

	// OPTIONS catchall for CORS.
	m.Options("/**", func() int {
		return http.StatusOK
	})
}

Use Martini CORS service instead of our own.


// Copyright (c) 2013 Kelsey Hightower. All rights reserved.
// Use of this source code is governed by the Apache License, Version 2.0
// that can be found in the LICENSE file.
package config

import (
	"fmt"
)

// Nodes is a custom flag Var representing a list of etcd nodes.
type Nodes []string

// String returns the string representation of a node var.
func (n *Nodes) String() string {
	return fmt.Sprintf("%d", *n)
}

// Set appends the node to the etcd node list.
func (n *Nodes) Set(node string) error {
	*n = append(*n, node)
	return nil
}

// Copyright (c) 2013 Kelsey Hightower. All rights reserved.
// Use of this source code is governed by the Apache License, Version 2.0
// that can be found in the LICENSE file.
package config

import (
	"fmt"
)

// Nodes is a custom flag Var representing a list of etcd nodes.
type Nodes []string

// String returns the string representation of a node var.
func (n *Nodes) String() string {
	return fmt.Sprintf("%s", *n)
}

// Set appends the node to the etcd node list.
func (n *Nodes) Set(node string) error {
	*n = append(*n, node)
	return nil
}

Fix %d should be %s according to govet


package main

import (
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
)

func main() {
	SetTmuxStatusColor("yellow")
	args := os.Args[1:]

	if len(args) == 0 {
		log.Fatalln("Not enough arguments")
	}

	cmd := exec.Command(args[0], args[1:]...)

	stdout, err := cmd.StdoutPipe()
	if err != nil {
		log.Fatalln(err)
	}

	stderr, err := cmd.StderrPipe()
	if err != nil {
		log.Fatalln(err)
	}

	err = cmd.Start()

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	cmd.Wait()

	if cmd.ProcessState.Success() {
		fmt.Println("It finished bro")
		SetTmuxStatusColor("green")
	} else {
		fmt.Println("naw you didn't success it")
		SetTmuxStatusColor("red")
	}
}

func SetTmuxStatusColor(color string) error {
	cmd := exec.Command("tmux", "set", "status-bg", color)
	return cmd.Run()
}

package main

import (
	"fmt"
	"io"
	"log"
	"os"
	"os/exec"
)

func main() {
	SetTmuxStatusColor("yellow")
	args := os.Args[1:]

	if len(args) == 0 {
		log.Fatalln("Not enough arguments")
	}

	cmd := exec.Command(args[0], args[1:]...)

	stdout, err := cmd.StdoutPipe()
	ExitIfErr(err)

	stderr, err := cmd.StderrPipe()
	ExitIfErr(err)

	err = cmd.Start()

	go io.Copy(os.Stdout, stdout)
	go io.Copy(os.Stderr, stderr)

	cmd.Wait()

	if cmd.ProcessState.Success() {
		SetTmuxStatusColor("green")
	} else {
		SetTmuxStatusColor("red")
	}
}

func SetTmuxStatusColor(color string) error {
	cmd := exec.Command("tmux", "set", "status-bg", color)
	return cmd.Run()
}

func ExitIfErr(err error) {
	if err != nil {
		Exit(err)
	}
}

func Exit(message interface{}) {
	fmt.Fprint(os.Stderr, message)
	os.Exit(1)
}

Add better error interface and remove excess lines


package registry

import (
	"log"

	"github.com/arigatomachine/cli/daemon/envelope"
)

// KeyringMemberClient represents the `/keyring-members` registry end point for
// accessand creating memberships related to a set of Keyrings.
type KeyringMemberClient struct {
	client *Client
}

// Post sends a creation requests for a set of KeyringMember objects to the
// registry.
func (k *KeyringMemberClient) Post(members []envelope.Signed) ([]envelope.Signed, error) {

	req, err := k.client.NewRequest("POST", "/keyring-members", nil, members)
	if err != nil {
		log.Printf("Error creating POST /keyring-members request: %s", err)
		return nil, err
	}

	resp := []envelope.Signed{}
	_, err = k.client.Do(req, resp)
	if err != nil {
		log.Printf("Error performing POST /keyring-members request: %s", err)
		return nil, err
	}

	return resp, err
}

package registry

import (
	"log"

	"github.com/arigatomachine/cli/daemon/envelope"
)

// KeyringMemberClient represents the `/keyring-members` registry end point for
// accessand creating memberships related to a set of Keyrings.
type KeyringMemberClient struct {
	client *Client
}

// Post sends a creation requests for a set of KeyringMember objects to the
// registry.
func (k *KeyringMemberClient) Post(members []envelope.Signed) ([]envelope.Signed, error) {

	req, err := k.client.NewRequest("POST", "/keyring-members", nil, members)
	if err != nil {
		log.Printf("Error creating POST /keyring-members request: %s", err)
		return nil, err
	}

	resp := []envelope.Signed{}
	_, err = k.client.Do(req, &resp)
	if err != nil {
		log.Printf("Error performing POST /keyring-members request: %s", err)
		return nil, err
	}

	return resp, err
}

Fix unmarshal of keyring members response


// Copyright 2020 DSR Corporation
//
// 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 types

import (
	authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)

// Default parameter values.
const (
	DclMaxMemoCharacters      uint64  = authtypes.DefaultMaxMemoCharacters
	DclTxSigLimit             uint64  = authtypes.DefaultTxSigLimit
	DclTxSizeCostPerByte      uint64  = 0 // gas is not needed in DCL
	DclSigVerifyCostED25519   uint64  = 0 // gas is not needed in DCL
	DclSigVerifyCostSecp256k1 uint64  = 0 // gas is not needed in DCL
	AccountApprovalsPercent   float64 = 0.66
)

// Copyright 2020 DSR Corporation
//
// 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 types

import (
	authtypes "github.com/cosmos/cosmos-sdk/x/auth/types"
)

// Default parameter values.
const (
	DclMaxMemoCharacters          uint64  = authtypes.DefaultMaxMemoCharacters
	DclTxSigLimit                 uint64  = authtypes.DefaultTxSigLimit
	DclTxSizeCostPerByte          uint64  = 0 // gas is not needed in DCL
	DclSigVerifyCostED25519       uint64  = 0 // gas is not needed in DCL
	DclSigVerifyCostSecp256k1     uint64  = 0 // gas is not needed in DCL
	AccountApprovalsPercent       float64 = 0.66
	VendorAccountApprovalsPercent float64 = 0.33
)

Add a new constant which includes vendor account approvals percent


package vm

import "github.com/mediocregopher/seq"

type Dictionary struct{ hashMap *seq.HashMap }

func NewDictionary(ks []Object, vs []*Thunk) *Thunk {
	if len(ks) == len(vs) {
		return NewError("Number of keys doesn't match with number of values.")
	}

	d := Dictionary{seq.NewHashMap()}

	for i, k := range ks {
		d.Set(k, vs[i])
	}

	return Normal(d)
}

func (d Dictionary) Set(k, v interface{}) Dictionary {
	h, _ := d.hashMap.Set(k, v)
	return Dictionary{h}
}

func (d1 Dictionary) Equal(o Object) *Thunk {
	d2, ok := o.(Dictionary)

	if !ok {
		return False
	}

	return NewBool(d1.hashMap.Equal(d2.hashMap))
}

package vm

import "github.com/mediocregopher/seq"

type Dictionary struct{ hashMap *seq.HashMap }

func NewDictionary(ks []Object, vs []*Thunk) *Thunk {
	if len(ks) == len(vs) {
		return NewError("Number of keys doesn't match with number of values.")
	}

	d := Dictionary{seq.NewHashMap()}

	for i, k := range ks {
		d.Set(k, vs[i])
	}

	return Normal(d)
}

func (d Dictionary) Set(k, v interface{}) Dictionary {
	h, _ := d.hashMap.Set(k, v)
	return Dictionary{h}
}

func (d1 Dictionary) Equal(o Object) *Thunk {
	return NewBool(d1.hashMap.Equal(o.(Dictionary).hashMap))
}

Remove type check in Dictionary.Equal()


package main

import (
	"fmt"
	"github.com/zetamatta/nyagos/dos"
)

func main() {
	indent := 1
	var callback func(*dos.NetResource) bool

	callback = func(node *dos.NetResource) bool {
		fmt.Printf("%*s%s\n", indent*2, "", node.RemoteName())
		indent++
		node.Enum(callback)
		indent--
		return true
	}
	err := dos.WNetEnum(callback)
	if err != nil {
		println(err.Error())
	}
}

package main

import (
	"fmt"
	"time"

	"github.com/zetamatta/nyagos/dos"
)

func main() {
	indent := 1
	var callback func(*dos.NetResource) bool

	callback = func(node *dos.NetResource) bool {
		name := node.RemoteName()
		now := time.Now()
		fmt.Printf("%02d:%02d:%02d %*s%s\n",
			now.Hour(),
			now.Minute(),
			now.Second(),
			indent*2,
			"",
			name)
		if len(name) <= 0 || name[0] != '\\' {
			indent++
			node.Enum(callback)
			indent--
		}
		return true
	}
	err := dos.WNetEnum(callback)
	if err != nil {
		println(err.Error())
	}
}

Add benchmark code on dos/netest


// +build !windows

package reuseport

import (
	"syscall"

	"golang.org/x/sys/unix"
)

func Control(network, address string, c syscall.RawConn) error {
	var err error
	c.Control(func(fd uintptr) {
		err = syscall.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
		if err != nil {
			return
		}

		err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, syscall.SO_REUSEPORT, 1)
		if err != nil {
			return
		}
	})
	return err
}

// +build !windows

package reuseport

import (
	"syscall"

	"golang.org/x/sys/unix"
)

func Control(network, address string, c syscall.RawConn) error {
	var err error
	c.Control(func(fd uintptr) {
		err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEADDR, 1)
		if err != nil {
			return
		}

		err = unix.SetsockoptInt(int(fd), unix.SOL_SOCKET, unix.SO_REUSEPORT, 1)
		if err != nil {
			return
		}
	})
	return err
}

Use more constants from unix package


package main

import (
	"reflect"
	"regexp"
	"testing"
)

var genMatcherTests = []struct {
	src string
	dst *regexp.Regexp
}{
	{"abc", regexp.MustCompile(`(abc)`)},

	{"a,b", regexp.MustCompile(`(a|b)`)},
}

func TestGenMatcher(t *testing.T) {
	for _, test := range genMatcherTests {
		expect := test.dst
		actual, err := newMatcher(test.src)
		if err != nil {
			t.Errorf("NewSubvert(%q) returns %q, want nil",
				test.src, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("%q: got %q, want %q",
				test.src, actual, expect)
		}
	}
}

package main

import (
	"reflect"
	"regexp"
	"testing"
)

var genMatcherTests = []struct {
	src string
	dst *regexp.Regexp
}{
	{"abc", regexp.MustCompile(`(abc)`)},

	{"a,b", regexp.MustCompile(`(a|b)`)},

	{"a\\,b", regexp.MustCompile(`(a,b)`)},
}

func TestGenMatcher(t *testing.T) {
	for _, test := range genMatcherTests {
		expect := test.dst
		actual, err := newMatcher(test.src)
		if err != nil {
			t.Errorf("NewSubvert(%q) returns %q, want nil",
				test.src, err)
		}
		if !reflect.DeepEqual(actual, expect) {
			t.Errorf("%q: got %q, want %q",
				test.src, actual, expect)
		}
	}
}

Add case of escape branch for newMatcher


package rmq

import (
	"errors"
	"fmt"
)

var (
	ErrorNotFound         = errors.New("entity not found") // entitify being connection/queue/delivery
	ErrorAlreadyConsuming = errors.New("must not call StartConsuming() multiple times")
	ErrorNotConsuming     = errors.New("must call StartConsuming() before adding consumers")
	ErrorConsumingStopped = errors.New("consuming stopped")
)

type ConsumeError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *ConsumeError) Error() string {
	return fmt.Sprintf("rmq.ConsumeError (%d): %s", e.Count, e.RedisErr.Error())
}

type HeartbeatError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *HeartbeatError) Error() string {
	return fmt.Sprintf("rmq.HeartbeatError (%d): %s", e.Count, e.RedisErr.Error())
}

type DeliveryError struct {
	Delivery Delivery
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *DeliveryError) Error() string {
	return fmt.Sprintf("rmq.DeliveryError (%d): %s", e.Count, e.RedisErr.Error())
}

package rmq

import (
	"errors"
	"fmt"
)

var (
	ErrorNotFound         = errors.New("entity not found") // entitify being connection/queue/delivery
	ErrorAlreadyConsuming = errors.New("must not call StartConsuming() multiple times")
	ErrorNotConsuming     = errors.New("must call StartConsuming() before adding consumers")
	ErrorConsumingStopped = errors.New("consuming stopped")
)

type ConsumeError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *ConsumeError) Error() string {
	return fmt.Sprintf("rmq.ConsumeError (%d): %s", e.Count, e.RedisErr.Error())
}

func (e *ConsumeError) Unwrap() error {
	return e.RedisErr
}

type HeartbeatError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *HeartbeatError) Error() string {
	return fmt.Sprintf("rmq.HeartbeatError (%d): %s", e.Count, e.RedisErr.Error())
}

func (e *HeartbeatError) Unwrap() error {
	return e.RedisErr
}

type DeliveryError struct {
	Delivery Delivery
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *DeliveryError) Error() string {
	return fmt.Sprintf("rmq.DeliveryError (%d): %s", e.Count, e.RedisErr.Error())
}

func (e *DeliveryError) Unwrap() error {
	return e.RedisErr
}

Add Unwrap() methods to error types


package google

// Asset is the CAI representation of a resource.
type Asset struct {
	// The name, in a peculiar format: `\\<api>.googleapis.com/<self_link>`
	Name string
	// The type name in `google.<api>.<resourcename>` format.
	Type      string
	Resource  *AssetResource
	IAMPolicy *IAMPolicy
}

// AssetResource is the Asset's Resource field.
type AssetResource struct {
	// Api version
	Version string
	// URI including scheme for the discovery doc - assembled from
	// product name and version.
	DiscoveryDocumentURI string
	// Resource name.
	DiscoveryName string
	// Actual resource state as per Terraform.  Note that this does
	// not necessarily correspond perfectly with the CAI representation
	// as there are occasional deviations between CAI and API responses.
	// This returns the API response values instead.
	Data map[string]interface{}
}

type IAMPolicy struct {
	Bindings []IAMBinding
}

type IAMBinding struct {
	Role    string
	Members []string
}

package google

// Asset is the CAI representation of a resource.
type Asset struct {
	// The name, in a peculiar format: `\\<api>.googleapis.com/<self_link>`
	Name string `json:"name"`
	// The type name in `google.<api>.<resourcename>` format.
	Type      string         `json:"asset_type"`
	Resource  *AssetResource `json:"resource,omitempty"`
	IAMPolicy *IAMPolicy     `json:"iam_policy,omitempty"`
}

// AssetResource is the Asset's Resource field.
type AssetResource struct {
	// Api version
	Version string `json:"version"`
	// URI including scheme for the discovery doc - assembled from
	// product name and version.
	DiscoveryDocumentURI string `json:"discovery_document_uri"`
	// Resource name.
	DiscoveryName string `json:"discovery_name"`
	// Actual resource state as per Terraform.  Note that this does
	// not necessarily correspond perfectly with the CAI representation
	// as there are occasional deviations between CAI and API responses.
	// This returns the API response values instead.
	Data map[string]interface{} `json:"data,omitempty"`
}

type IAMPolicy struct {
	Bindings []IAMBinding `json:"bindings"`
}

type IAMBinding struct {
	Role    string   `json:"role"`
	Members []string `json:"members"`
}

Add json tags to CAI asset.


package examples

import (
	"fmt"
	"github.com/ewilde/go-runscope"
	"log"
)

var accessToken = "{your token}"  // See https://www.runscope.com/applications
var teamUUID = "{your team uuid}" // See https://www.runscope.com/teams
var client = runscope.NewClient(runscope.APIURL, accessToken)

func createBucket() *runscope.Bucket {
	var bucket = &runscope.Bucket{
		Name: "My first bucket",
		Team: &runscope.Team{
			ID: teamUUID,
		},
	}

	bucket, err := client.CreateBucket(bucket)
	if err != nil {
		DebugF(1, "[ERROR] error creating bucket: %s", err)
	}

	fmt.Printf("Bucket created successfully: %s", bucket.String())
	return bucket
}

func readBucket() {
	bucket, err := client.ReadBucket("htqee6p4dhvc")
	if err != nil {
		DebugF(1, "[ERROR] error creating bucket: %s", err)
	}

	fmt.Printf("Bucket read successfully: %s", bucket.String())
}

func deleteBucket() {
	err := client.DeleteBucket("htqee6p4dhvc")
	if err != nil {
		DebugF(1, "[ERROR] error creating bucket: %s", err)
	}
}

package examples

import (
	"fmt"
	"github.com/ewilde/go-runscope"
)

var accessToken = "{your token}"  // See https://www.runscope.com/applications
var teamUUID = "{your team uuid}" // See https://www.runscope.com/teams
var client = runscope.NewClient(runscope.APIURL, accessToken)

func createBucket() *runscope.Bucket {
	var bucket = &runscope.Bucket{
		Name: "My first bucket",
		Team: &runscope.Team{
			ID: teamUUID,
		},
	}

	bucket, err := client.CreateBucket(bucket)
	if err != nil {
		runscope.DebugF(1, "[ERROR] error creating bucket: %s", err)
	}

	fmt.Printf("Bucket created successfully: %s", bucket.String())
	return bucket
}

func readBucket() {
	bucket, err := client.ReadBucket("htqee6p4dhvc")
	if err != nil {
		runscope.DebugF(1, "[ERROR] error creating bucket: %s", err)
	}

	fmt.Printf("Bucket read successfully: %s", bucket.String())
}

func deleteBucket() {
	err := client.DeleteBucket("htqee6p4dhvc")
	if err != nil {
		runscope.DebugF(1, "[ERROR] error creating bucket: %s", err)
	}
}

Fix example code compilation error


package nlgids

import (
	"testing"

	"github.com/miekg/nlgids/email"
	"github.com/miekg/nlgids/webcontact"
)

func newContact() *webcontact.Contact {
	return &webcontact.Contact{
		Name:    "Miek Gieben",
		Email:   "miek@miek.nl",
		Phone:   "07774 517 566",
		Message: "Hee, hoe is het daar?",
	}
}

func TestContactCreate(t *testing.T) {
	c := newContact()
	subject := c.MailSubject()
	body, err := c.MailBody()
	if err != nil {
		t.Fatal(err)
	}
	mail := email.NewContact(subject, body)

	if mail.Subject != "[NLgids] Contact van \"Miek Gieben\"" {
		t.Fatal("wrong email Subject")
	}
	if mail.From != "nlgids@nlgids.london" {
		t.Fatal("wrong email From")
	}
	if len(mail.Cc) != 0 {
		t.Fatal("wrong email Cc")
	}
}

package nlgids

import (
	"testing"

	"github.com/miekg/nlgids/email"
	"github.com/miekg/nlgids/webcontact"
)

func newContact() *webcontact.Contact {
	return &webcontact.Contact{
		Name:    "Miek Gieben",
		Email:   "miek@miek.nl",
		Phone:   "07774 517 566",
		Message: "Hee, hoe is het daar?",
	}
}

func TestContactCreate(t *testing.T) {
	c := newContact()
	subject := c.MailSubject()
	body, err := c.MailBody()
	if err != nil {
		t.Fatal(err)
	}
	mail := email.NewContact(subject, body)

	if mail.Subject != "[NLgids] Contact van \"Miek Gieben\"" {
		t.Fatal("wrong email Subject")
	}
	if mail.From != "nlgids@nlgids.london" {
		t.Fatal("wrong email From")
	}
	if len(mail.Cc) != 0 {
		t.Fatal("wrong email Cc")
	}
	if err := mail.Do(); err != nil {
		t.Fatalf("can't send mail %s: ", err)
	}
}

Send mail in the test


package main

import (
	"time"
)

// Deployment describes a deployment
type Deployment struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	ImageName string    `json:"image_name"`
	Version   string    `json:"version"`
	Priority  int       `json:"priority"`
	State     string    `json:"status"`
	LogKey    string    `json:"-"`
}

// Config for the deployment system for a user.
type Config struct {
	RepoURL        string `json:"repo_url" yaml:"repo_url"`
	RepoPath       string `json:"repo_path" yaml:"repo_path"`
	RepoKey        string `json:"repo_key" yaml:"repo_key"`
	KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"`
}

package main

import (
	"time"
)

// Deployment describes a deployment
type Deployment struct {
	ID        string    `json:"id"`
	CreatedAt time.Time `json:"created_at"`
	ImageName string    `json:"image_name"`
	Version   string    `json:"version"`
	Priority  int       `json:"priority"`
	State     string    `json:"status"`
	LogKey    string    `json:"-"`
}

// Config for the deployment system for a user.
type Config struct {
	RepoURL        string `json:"repo_url" yaml:"repo_url"`
	RepoPath       string `json:"repo_path" yaml:"repo_path"`
	RepoKey        string `json:"repo_key" yaml:"repo_key"`
	KubeconfigPath string `json:"kubeconfig_path" yaml:"kubeconfig_path"`

	Notifications []NotificationConfig `json:"notification" yaml:"notification"`
}

// NotificationConfig describes how to send notifications
type NotificationConfig struct {
	SlackWebhookURL string `json:"slack_webhook_url" yaml:"slack_webhook_url"`
	SlackUsername   string `json:"slack_username" yaml:"slack_username"`
}

Add notification config for wcloud


package main

import (
	"log"
	"os"
)

func check_main(args []string) {
	allCarr, err := allCarriersWithErrors()
	if err != nil {
		log.Fatalf("Unable to open library: %s", err)
	}

	exitStatus := 0

	for _, pc := range allCarr {
		if pc.Error != nil {
			exitStatus = 1
			log.Printf("Parse error in %s: %s", pc.Filename, pc.Error)
			continue
		}

		if pc.Carrier.ID == "" {
			exitStatus = 1
			log.Printf("%s: no carrier ID", pc.Filename)
		}
	}

	os.Exit(exitStatus)
}

package main

import (
	"fmt"
	"log"
	"os"
	"path"

	"github.com/thijzert/speeldoos"
	"github.com/thijzert/speeldoos/lib/zipmap"
)

type checkF func(*speeldoos.Carrier) []error

var allChecks []checkF = []checkF{
	check_carrierID,
	check_sourceFiles,
}

func check_main(args []string) {
	allCarr, err := allCarriersWithErrors()
	if err != nil {
		log.Fatalf("Unable to open library: %s", err)
	}

	exitStatus := 0

	for _, pc := range allCarr {
		if pc.Error != nil {
			exitStatus = 1
			log.Printf("Parse error in %s: %s", pc.Filename, pc.Error)
			continue
		}

		for _, f := range allChecks {
			errs := f(pc.Carrier)
			if errs != nil {
				for _, e := range errs {
					exitStatus = 1
					log.Printf("%s: %s", pc.Filename, e.Error())
				}
			}
		}
	}

	os.Exit(exitStatus)
}

func check_carrierID(foo *speeldoos.Carrier) []error {
	if foo.ID == "" {
		return []error{fmt.Errorf("no carrier ID")}
	}
	return nil
}

func check_sourceFiles(foo *speeldoos.Carrier) []error {
	rv := []error{}

	zm := zipmap.New()

	for _, perf := range foo.Performances {
		for _, sf := range perf.SourceFiles {
			if !zm.Exists(path.Join(Config.LibraryDir, sf.Filename)) {
				rv = append(rv, fmt.Errorf("source file missing: %s", sf))
			}
		}
	}

	return rv
}

Check if every source file exists


package icmd

// CmdOp is an operation which modified a Cmd structure used to execute commands
type CmdOp func(*Cmd)

package icmd

import (
	"io"
	"time"
)

// CmdOp is an operation which modified a Cmd structure used to execute commands
type CmdOp func(*Cmd)

// WithTimeout sets the timeout duration of the command
func WithTimeout(timeout time.Duration) CmdOp {
	return func(c *Cmd) {
		c.Timeout = timeout
	}
}

// WithEnv sets the environment variable of the command.
// Each arguments are in the form of KEY=VALUE
func WithEnv(env ...string) CmdOp {
	return func(c *Cmd) {
		c.Env = env
	}
}

// Dir sets the working directory of the command
func Dir(path string) CmdOp {
	return func(c *Cmd) {
		c.Dir = path
	}
}

// WithStdin sets the standard input of the command to the specified reader
func WithStdin(r io.Reader) CmdOp {
	return func(c *Cmd) {
		c.Stdin = r
	}
}

Add some CmdOps to make `RunCmd` more useful


package main

import (
	"fmt"
	"net/http"
	"strings"
)

// Returns the client's IP address.
func echoRemoteAddr(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	// RemoteAddr is formatted as host:port, so we just trim off the port here
	// and return the IP.
	var ip string
	switch strings.Count(r.RemoteAddr, ":") {
	case 1:
		// IPv4 addresses may be of the form IP:port
		index := strings.LastIndex(r.RemoteAddr, ":")
		ip = r.RemoteAddr[:index]
	default:
		// IPv6 addresses have multiple colons, and no ports.
		ip = r.RemoteAddr
	}
	fmt.Fprintf(w, "%s\n", ip)
}

// Returns a 404 Not Found page.
func notFound(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprintf(w, "%d Not Found\n", http.StatusNotFound)
}

package main

import (
	"fmt"
	"net"
	"net/http"
)

// Returns the client's IP address.
func echoRemoteAddr(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
	w.WriteHeader(http.StatusOK)

	ip, _, _ := net.SplitHostPort(r.RemoteAddr)
	fmt.Fprintf(w, "%s\n", ip)
}

// Returns a 404 Not Found page.
func notFound(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "text/plain; charset=UTF-8")
	w.WriteHeader(http.StatusNotFound)
	fmt.Fprintf(w, "%d Not Found\n", http.StatusNotFound)
}

Use net.SplitHostPort instead of reimplementing it


package check_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"

	"testing"
)

var fakeBin string

func TestCheck(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "check")
}

var _ = BeforeSuite(func() {
	var err error
	fakeBin, err = gexec.Build("github.com/st3v/waitfor/check/fake/command")
	Expect(err).ToNot(HaveOccurred())
})

var _ = AfterSuite(func() {
	gexec.CleanupBuildArtifacts()
})

package check_test

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/onsi/gomega/gexec"

	"testing"
)

var fakeBin string

func TestCheck(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "check")
}

var _ = BeforeSuite(func() {
	var err error
	fakeBin, err = gexec.Build("./fake/command")
	Expect(err).ToNot(HaveOccurred())
})

var _ = AfterSuite(func() {
	gexec.CleanupBuildArtifacts()
})

Use relative package path in test


package taskmq

type TaskMQ struct {
	config *Config
	broker IBroker
}

func New(broker IBroker, config *Config) *TaskMQ {
	return &TaskMQ{config: config}
}

func (r *TaskMQ) Connect() error {

	return r.broker.Connect()
}

func (r *TaskMQ) Publish(queueName string, body []byte) {
	err := r.broker.Push(queueName, body)

	if err != nil {
		panic(err)
	}
}

func (r *TaskMQ) Consume(queueName string, fn callbackFunction) {
	broker := r.createBroker()
	c := newConsumer(broker, queueName)
	c.Listen(fn)
}

func (r *TaskMQ) createBroker() IBroker {
	return &BrokerRedis{client: r.redis}
}

package taskmq

type TaskMQ struct {
	config *Config
	broker IBroker
}

func New(broker IBroker, config *Config) *TaskMQ {
	return &TaskMQ{config: config}
}

func (r *TaskMQ) Connect() error {

	return r.broker.Connect()
}

func (r *TaskMQ) Publish(queueName string, body []byte) {
	err := r.broker.Push(queueName, body)

	if err != nil {
		panic(err)
	}
}

func (r *TaskMQ) Consume(queueName string, fn callbackFunction) {
	broker := r.broker.Clone()
	c := newConsumer(broker, queueName)
	c.Listen(fn)
}

Remove concrete redis broker from base package


package main

import (
	"flag"
	"fmt"
	"os"
)

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Fprint(os.Stderr, r)
		}
	}()

	var chewing bool

	var ctx BenchmarkContext
	defer func() {
		ctx.deinit()
	}()

	flag.BoolVar(&chewing, "chewing", true, "Enable libchewing benchmark")
	flag.Parse()

	if chewing {
		ctx.addBenchmarkItem(newChewingBenchmarkItem())
	}

	for _, input := range flag.Args() {
		fmt.Printf("Processing %s ... ", input)

		inputSeq, err := getBenchmarkInput(input)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Cannot open %s\n", input)
			continue
		}

		for _, input := range inputSeq {
			ctx.enterBenchmarkInput(&input)
		}

		fmt.Printf("Done\n")
	}

	ctx.print()
}

package main

import (
	"flag"
	"fmt"
	"os"
)

func main() {
	defer func() {
		if r := recover(); r != nil {
			fmt.Fprintf(os.Stderr, "%s\n", r)
		}
	}()

	var chewing bool

	var ctx BenchmarkContext
	defer func() {
		ctx.deinit()
	}()

	flag.BoolVar(&chewing, "chewing", true, "Enable libchewing benchmark")
	flag.Parse()

	if chewing {
		ctx.addBenchmarkItem(newChewingBenchmarkItem())
	}

	for _, input := range flag.Args() {
		fmt.Printf("Processing %s ... ", input)

		inputSeq, err := getBenchmarkInput(input)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Cannot open %s\n", input)
			continue
		}

		for _, input := range inputSeq {
			ctx.enterBenchmarkInput(&input)
		}

		fmt.Printf("Done\n")
	}

	ctx.print()
}

Print newline for error message


// +build vault

package vault

// IsPrimary checks if this is a primary Vault instance.
func (d dynamicSystemView) IsPrimary() bool {
	return true
}

// +build vault,!ent

package vault

// IsPrimary checks if this is a primary Vault instance.
func (d dynamicSystemView) IsPrimary() bool {
	return true
}

Fix up exclusion rules for dynamic system view IsPrimary


package piece

import (
	"chessboard"
	"point"
)

type Piece struct {
	movable []point.Point
	white   byte
	black   byte
}

func NewPiece(movable []point.Point, white, black byte) *Piece {
	piece := new(Piece)
	piece.movable = movable
	piece.white = white
	piece.black = black
	return piece
}

func (piece Piece) CanMove(from, to point.Point) bool {
	if chessboard.InBoard(from) == false || chessboard.InBoard(to) == false {
		return false
	}
	diff := from.Diff(to)
	for i := 0; i < len(piece.movable); i++ {
		if diff.Y <= piece.movable[i].Y && diff.X <= piece.movable[i].X {
			return true
		}
	}
	return false
}

package piece

import (
	"chessboard"
	"point"
)

type Piece struct {
	movable []point.Point
	white   byte
	black   byte
}

func NewPiece(movable []point.Point, white, black byte) *Piece {
	piece := new(Piece)
	piece.movable = movable
	piece.white = white
	piece.black = black
	return piece
}

func (piece Piece) CanMove(from, to point.Point) bool {
	if chessboard.InBoard(from) == false || chessboard.InBoard(to) == false {
		return false
	}
	diff := from.Diff(to)
	for i := 0; i < len(piece.movable); i++ {
		if diff.Y == piece.movable[i].Y && diff.X == piece.movable[i].X {
			return true
		}
	}
	return false
}

Change checking movable from <= to ==


package terraform

import (
	"bufio"
	"io"

	"github.com/docker/machine/libmachine/log"
)

// Scan STDOUT and STDERR pipes for a process.
//
// Calls the supplied PipeHandler once for each line encountered.
func scanProcessPipes(stdioPipe io.ReadCloser, stderrPipe io.ReadCloser, pipeOutput PipeHandler) {
	go scanPipe(stdioPipe, pipeOutput, "STDOUT")
	go scanPipe(stdioPipe, pipeOutput, "STDERR")
}

// Scan a process output pipe, and call the supplied PipeHandler once for each line encountered.
func scanPipe(pipe io.ReadCloser, pipeOutput PipeHandler, pipeName string) {
	lineScanner := bufio.NewScanner(pipe)
	for lineScanner.Scan() {
		line := lineScanner.Text()
		pipeOutput(line)
	}

	scanError := lineScanner.Err()
	if scanError != nil {
		log.Errorf("Error scanning pipe %s: %s",
			pipeName,
			scanError.Error(),
		)
	}

	pipe.Close()
}

package terraform

import (
	"bufio"
	"io"

	"github.com/docker/machine/libmachine/log"
)

// Scan STDOUT and STDERR pipes for a process.
//
// Calls the supplied PipeHandler once for each line encountered.
func scanProcessPipes(stdioPipe io.ReadCloser, stderrPipe io.ReadCloser, pipeOutput PipeHandler) {
	go scanPipe(stdioPipe, pipeOutput, "STDOUT")
	go scanPipe(stderrPipe, pipeOutput, "STDERR")
}

// Scan a process output pipe, and call the supplied PipeHandler once for each line encountered.
func scanPipe(pipe io.ReadCloser, pipeOutput PipeHandler, pipeName string) {
	lineScanner := bufio.NewScanner(pipe)
	for lineScanner.Scan() {
		line := lineScanner.Text()
		pipeOutput(line)
	}

	scanError := lineScanner.Err()
	if scanError != nil {
		log.Errorf("Error scanning pipe %s: %s",
			pipeName,
			scanError.Error(),
		)
	}

	pipe.Close()
}

Fix bug when streaming output from Terrafrm (STDERR was not being streamed, but STDOUT was being streamed twice).


package monitoring

func GetDefaultThresholdValues() (plugins []Plugin) {
	return []Plugin{
		{
			Name:   "df",
			Enable: true,
			Configs: []PluginConfig{
				{Category: THRESHOLD, Type: CRITICAL, Value: "90"},
				{Category: THRESHOLD, Type: WARNING, Value: "80"},
			},
		},
		{
			Name:   "memory",
			Enable: true,
			Configs: []PluginConfig{
				{Category: THRESHOLD, Type: CRITICAL, Value: "90"},
				{Category: THRESHOLD, Type: WARNING, Value: "80"},
			},
		},
		{
			Name:   "cpu",
			Enable: true,
			Configs: []PluginConfig{
				{Category: THRESHOLD, Type: CRITICAL, Value: "90"},
				{Category: THRESHOLD, Type: WARNING, Value: "80"},
			},
		},
		{
			Name:   "swap",
			Enable: true,
			Configs: []PluginConfig{
				{Category: THRESHOLD, Type: CRITICAL, Value: "70"},
				{Category: THRESHOLD, Type: WARNING, Value: "50"},
			},
		},
	}
}

var DefaultClusterMonitoringInterval = 10

package monitoring

func GetDefaultThresholdValues() (plugins []Plugin) {
	return []Plugin{
		{
			Name:   "df",
			Enable: true,
			Configs: []PluginConfig{
				{Category: THRESHOLD, Type: CRITICAL, Value: "90"},
				{Category: THRESHOLD, Type: WARNING, Value: "80"},
			},
		},
		{
			Name:   "memory",
			Enable: true,
			Configs: []PluginConfig{
				{Category: THRESHOLD, Type: CRITICAL, Value: "90"},
				{Category: THRESHOLD, Type: WARNING, Value: "80"},
			},
		},
		{
			Name:   "cpu",
			Enable: true,
			Configs: []PluginConfig{
				{Category: THRESHOLD, Type: CRITICAL, Value: "90"},
				{Category: THRESHOLD, Type: WARNING, Value: "80"},
			},
		},
		{
			Name:   "swap",
			Enable: true,
			Configs: []PluginConfig{
				{Category: THRESHOLD, Type: CRITICAL, Value: "70"},
				{Category: THRESHOLD, Type: WARNING, Value: "50"},
			},
		},
	}
}

var DefaultClusterMonitoringInterval = 600

Change monitoring interval to 10mins


package cmd

import (

	"fmt"
	"github.com/s3git/s3git-go"
	"github.com/spf13/cobra"
)

var message string

// commitCmd represents the commit command
var commitCmd = &cobra.Command{
	Use:   "commit",
	Short: "Commit the changes in the repository",
	Long: "Commit the changes in the repository",
	Run: func(cmd *cobra.Command, args []string) {

		repo, err := s3git.OpenRepository(".")
		if err != nil {
			er(err)
		}

		key, nothing, err := repo.Commit(message)
		if err != nil {
			er(err)
		}
		if nothing {
			fmt.Println("Nothing to commit")
		} else {
			fmt.Printf("[master%s]\n", key)
			fmt.Printf("X files added, Y files removed\n")
		}
	},
}

func init() {
	RootCmd.AddCommand(commitCmd)

	// Add local message flags
	commitCmd.Flags().StringVarP(&message, "message", "m", "", "Message for the commit")
}

package cmd

import (

	"fmt"
	"github.com/s3git/s3git-go"
	"github.com/spf13/cobra"
)

var message string

// commitCmd represents the commit command
var commitCmd = &cobra.Command{
	Use:   "commit",
	Short: "Commit the changes in the repository",
	Long: "Commit the changes in the repository",
	Run: func(cmd *cobra.Command, args []string) {

		repo, err := s3git.OpenRepository(".")
		if err != nil {
			er(err)
		}

		key, nothing, err := repo.Commit(message)
		if err != nil {
			er(err)
		}
		if nothing {
			fmt.Println("Nothing to commit")
		} else {
			fmt.Printf("[master %s]\n", key)
			fmt.Printf("X files added, Y files removed\n")
		}
	},
}

func init() {
	RootCmd.AddCommand(commitCmd)

	// Add local message flags
	commitCmd.Flags().StringVarP(&message, "message", "m", "", "Message for the commit")
}

Put space between master and hash


package autosignr

import (
	log "github.com/Sirupsen/logrus"
	"gopkg.in/fsnotify.v1"
)

func WatchDir(conf Config) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Create == fsnotify.Create {
					result, _ := CheckCert(conf, event.Name)
					if result {
						SignCert(conf, CertnameFromFilename(event.Name))
					}
				}
			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	log.Printf("watching %s", conf.Dir)
	err = watcher.Add(conf.Dir)
	if err != nil {
		log.Fatal(err)
	}
	<-done
}

package autosignr

import (
	log "github.com/Sirupsen/logrus"
	"gopkg.in/fsnotify.v1"
)

func WatchDir(conf Config) {
	watcher, err := fsnotify.NewWatcher()
	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()

	done := make(chan bool)
	go func() {
		for {
			select {
			case event := <-watcher.Events:
				if event.Op&fsnotify.Write == fsnotify.Write {
					result, _ := CheckCert(conf, event.Name)
					if result {
						SignCert(conf, CertnameFromFilename(event.Name))
					}
				}
			case err := <-watcher.Errors:
				log.Println("error:", err)
			}
		}
	}()

	log.Printf("watching %s", conf.Dir)
	err = watcher.Add(conf.Dir)
	if err != nil {
		log.Fatal(err)
	}
	<-done
}

Use Write instead of Create fsnotify event


package main

import (
	"testing"

	"github.com/sachaos/todoist/lib"
	"github.com/stretchr/testify/assert"
)

func TestEval(t *testing.T) {
	r, _ := Eval(Filter("p1"), todoist.Item{Priority: 1})
	assert.Equal(t, r, true, "they should be equal")
	r, _ = Eval(Filter("p2"), todoist.Item{Priority: 1})
	assert.Equal(t, r, false, "they should be equal")

	r, _ = Eval(Filter(""), todoist.Item{})
	assert.Equal(t, r, true, "they should be equal")
}

package main

import (
	"testing"

	"github.com/sachaos/todoist/lib"
	"github.com/stretchr/testify/assert"
)

func TestEval(t *testing.T) {
	r, _ := Eval(Filter("p1"), todoist.Item{Priority: 1})
	assert.Equal(t, r, true, "they should be equal")
	r, _ = Eval(Filter("p2"), todoist.Item{Priority: 1})
	assert.Equal(t, r, false, "they should be equal")

	r, _ = Eval(Filter(""), todoist.Item{})
	assert.Equal(t, r, true, "they should be equal")

	r, _ = Eval(Filter("p1 | p2"), todoist.Item{Priority: 1})
	assert.Equal(t, r, true, "they should be equal")
	r, _ = Eval(Filter("p1 | p2"), todoist.Item{Priority: 2})
	assert.Equal(t, r, true, "they should be equal")
	r, _ = Eval(Filter("p1 | p2"), todoist.Item{Priority: 3})
	assert.Equal(t, r, false, "they should be equal")

	r, _ = Eval(Filter("p1 & p2"), todoist.Item{Priority: 1})
	assert.Equal(t, r, false, "they should be equal")
	r, _ = Eval(Filter("p1 & p2"), todoist.Item{Priority: 2})
	assert.Equal(t, r, false, "they should be equal")
	r, _ = Eval(Filter("p1 & p2"), todoist.Item{Priority: 3})
	assert.Equal(t, r, false, "they should be equal")
}

Add test of evaluation of BoolInfixOpExpr


package main

import "github.com/dynport/urknall"

type Docker struct {
	Version          string `urknall:"required=true"` // e.g. 1.1.0
	CustomInstallDir string
	Public           bool
}

func (docker *Docker) Render(pkg urknall.Package) {
	pkg.AddCommands("packages", InstallPackages("aufs-tools", "cgroup-lite", "xz-utils", "git"))
	pkg.AddCommands("install",
		Mkdir("{{ .InstallDir }}/bin", "root", 0755),
		Download("http://get.docker.io/builds/Linux/x86_64/docker-{{ .Version }}", "{{ .InstallDir }}/bin/docker", "root", 0755),
	)
	pkg.AddCommands("upstart", WriteFile("/etc/init/docker.conf", dockerUpstart, "root", 0644))
}

const dockerUpstart = `exec {{ .InstallDir }}/bin/docker -d -H tcp://{{ if .Public }}0.0.0.0{{ else }}127.0.0.1{{ end }}:4243 -H unix:///var/run/docker.sock 2>&1 | logger -i -t docker
`

func (docker *Docker) InstallDir() string {
	if docker.Version == "" {
		panic("Version must be set")
	}
	if docker.CustomInstallDir != "" {
		return docker.CustomInstallDir
	}
	return "/opt/docker-" + docker.Version
}

package main

import "github.com/dynport/urknall"

type Docker struct {
	Version          string `urknall:"required=true"` // e.g. 1.1.0
	CustomInstallDir string
	Public           bool
}

func (docker *Docker) Render(pkg urknall.Package) {
	pkg.AddCommands("packages", InstallPackages("aufs-tools", "cgroup-lite", "xz-utils", "git", "linux-image-extra-$(uname -r)"))
	pkg.AddCommands("install",
		Mkdir("{{ .InstallDir }}/bin", "root", 0755),
		Download("http://get.docker.io/builds/Linux/x86_64/docker-{{ .Version }}", "{{ .InstallDir }}/bin/docker", "root", 0755),
	)
	pkg.AddCommands("upstart", WriteFile("/etc/init/docker.conf", dockerUpstart, "root", 0644))
}

const dockerUpstart = `exec {{ .InstallDir }}/bin/docker -d -H tcp://{{ if .Public }}0.0.0.0{{ else }}127.0.0.1{{ end }}:4243 -H unix:///var/run/docker.sock 2>&1 | logger -i -t docker
`

func (docker *Docker) InstallDir() string {
	if docker.Version == "" {
		panic("Version must be set")
	}
	if docker.CustomInstallDir != "" {
		return docker.CustomInstallDir
	}
	return "/opt/docker-" + docker.Version
}

Install kernel extensions for aufs


package rates

import "testing"

func TestFetch(t *testing.T) {
	c, _ := Country("NL")

	if r, _ := c.Rate("standard"); r != 21 {
		t.Errorf("Standard VAT rate for NL is supposed to be 21. Got %.2f", r)
	}

	if r, _ := c.Rate("reduced"); r != 6 {
		t.Errorf("Reduced VAT rate for NL is supposed to be 6. Got %.2f", r)
	}

	c, _ = Country("RO")
	if r, _ := c.Rate("standard"); r != 20 {
		t.Errorf("Standard VAT rate for RO is supposed to be 20. Got %.2f", r)
	}
}

package rates

import (
	"fmt"
	"testing"
)

func TestCountryRates_Rate(t *testing.T) {
	c, _ := Country("NL")

	if r, _ := c.Rate("standard"); r != 21 {
		t.Errorf("Standard VAT rate for NL is supposed to be 21. Got %.2f", r)
	}

	if r, _ := c.Rate("reduced"); r != 6 {
		t.Errorf("Reduced VAT rate for NL is supposed to be 6. Got %.2f", r)
	}

	c, _ = Country("RO")
	if r, _ := c.Rate("standard"); r != 20 {
		t.Errorf("Standard VAT rate for RO is supposed to be 20. Got %.2f", r)
	}
}

func ExampleCountryRates_Rate() {
	c, _ := Country("NL")
	r, _ := c.Rate("standard")

	fmt.Printf("Standard VAT rate for %s is %.2f", c.Name, r)
	// Output: Standard VAT rate for Netherlands is 21.00
}

Add example for `CountryRates.Rate` func.


package handlers

import (
	"testing"

	"github.com/rancherio/go-rancher/client"
)

func TestBuildContainerConfig(t *testing.T) {
	machine := new(client.Machine)

	machine.ExternalId = "externalId"
	labels := make(map[string]interface{})

	labels["abc"] = "def"
	labels["foo"] = "bar"

	machine.Labels = labels
	config := buildContainerConfig([]string{}, machine, "rancher/agent", "0.7.8")

	for _, elem := range config.Env {
		if elem == "CATTLE_HOST_LABELS=abc=def&foo=bar" {
			return
		}
	}
	t.Error("label is not being set!")
}

package handlers

import (
	"testing"

	"github.com/rancherio/go-rancher/client"
)

func TestBuildContainerConfig(t *testing.T) {
	machine := new(client.Machine)

	machine.ExternalId = "externalId"
	labels := make(map[string]interface{})

	labels["abc"] = "def"
	labels["foo"] = "bar"

	machine.Labels = labels
	config := buildContainerConfig([]string{}, machine, "rancher/agent", "0.7.8")

	for _, elem := range config.Env {
		if elem == "CATTLE_HOST_LABELS=abc=def&foo=bar" || elem == "CATTLE_HOST_LABELS=foo=bar&abc=def" {
			return
		}
	}
	t.Error("label is not being set!")
}

Make test insensitive to param order


package httpie

import (
    "testing"
    "strings"
    "bufio"
    "bytes"
)

var delimData = []string{
    "Hello",
    "World",
    "This",
    "Is",
    "A",
    "Test",
};

func TestDelim(t *testing.T) {
    data  := []byte(strings.Join(delimData, "\n") + "\n")
    delim := Delimeter{'\n'}

    reader := bufio.NewReader(bytes.NewBuffer(data))

    out := []string{}
    for _, seg := range delimData {
        b, _ := delim.Consume(reader)

        if string(b) == seg {
            out = append(out, string(b))
        }
    }

    if len(out) != len(delimData) {
        t.Errorf("Delimeter consumer output doesn't match: actual=%s expected=%s", out, delimData)
    }
}

package httpie

import (
    "testing"
    "strings"
    "bufio"
    "bytes"
)

var delimData = []string{
    "Hello",
    "World",
    "This",
    "Is",
    "A",
    "Test",
};

func TestDelim(t *testing.T) {
    data  := []byte(strings.Join(delimData, "\n") + "\n")
    delim := NewLine

    reader := bufio.NewReader(bytes.NewBuffer(data))

    out := []string{}
    for _, seg := range delimData {
        b, _ := delim.Consume(reader)

        if string(b) == seg {
            out = append(out, string(b))
        }
    }

    if len(out) != len(delimData) {
        t.Errorf("Delimeter consumer output doesn't match: actual=%s expected=%s", out, delimData)
    }
}

Use one of the defined ones


package emu

const (
	memorySize      = 4096
	vramSize        = 64 * 32
	registersNumber = 16
	stackSize       = 16
)

// Chip8 is the main struct holding all data relevant to the emulator.
// This includes registers (V0 to VF, PC, etc.), ram and framebuffer.
type Chip8 struct {
	I      uint16
	pc     uint16
	sp     uint16
	stack  []uint16
	V      []uint8
	memory []uint8
	vram   []uint8
	delayt uint8
	soundt uint8
}

func New() Chip8 {
	return Chip8{
		0,
		0,
		0,
		make([]uint16, stackSize, stackSize),
		make([]uint8, registersNumber, registersNumber),
		make([]uint8, memorySize, memorySize),
		make([]uint8, vramSize, vramSize),
		0,
		0,
	}
}

package emu

const (
	memorySize      = 4096
	vramSize        = 64 * 32
	registersNumber = 16
	stackSize       = 16
)

// Chip8 is the main struct holding all data relevant to the emulator.
// This includes registers (V0 to VF, PC, etc.), ram and framebuffer.
type Chip8 struct {
	I      uint16
	pc     uint16
	sp     uint16
	stack  []uint16
	V      []uint8
	memory []uint8
	vram   []uint8
	keypad []uint8
	delayt uint8
	soundt uint8
}

// New initializes basic Chip8 data, but the emulator won't be in a runnable
// state until something is loaded.
func New() Chip8 {
	return Chip8{
		0,
		0,
		0,
		make([]uint16, stackSize, stackSize),
		make([]uint8, registersNumber, registersNumber),
		make([]uint8, memorySize, memorySize),
		make([]uint8, vramSize, vramSize),
		make([]uint8, 16, 16),
		0,
		0,
	}
}

Add keypad and New comment


package config

import (
	"log"

	"github.com/bradylove/envstruct"
)

type Config struct {
	Addr                 string   `env:"ADDR,required"`
	IntraAddr            string   `env:"INTRA_ADDR,required"`
	TalariaNodeAddr      string   `env:"TALARIA_NODE_ADDR,required"`
	TalariaSchedulerAddr string   `env:"TALARIA_SCHEDULER_ADDR,required"`
	TalariaNodeList      []string `env:"TALARIA_NODE_LIST,required"`
	IntraAnalystList     []string `env:"INTRA_ANALYST_LIST,required"`
	PprofAddr             string   `env:"PPROF_ADDR"`

	ToAnalyst map[string]string
}

func Load() *Config {
	conf := Config{
		PprofAddr: "localhost:6063",
	}

	if err := envstruct.Load(&conf); err != nil {
		log.Fatalf("Invalid config: %s", err)
	}

	if len(conf.TalariaNodeList) != len(conf.IntraAnalystList) {
		log.Fatalf("List lengths of TALARIA_NODE_LIST and INTRA_ANALYST_LIST must match")
	}

	conf.ToAnalyst = make(map[string]string)
	for i := range conf.IntraAnalystList {
		conf.ToAnalyst[conf.TalariaNodeList[i]] = conf.IntraAnalystList[i]
	}

	return &conf
}

package config

import (
	"log"

	"github.com/bradylove/envstruct"
)

type Config struct {
	Addr                 string   `env:"ADDR,required"`
	IntraAddr            string   `env:"INTRA_ADDR,required"`
	TalariaNodeAddr      string   `env:"TALARIA_NODE_ADDR,required"`
	TalariaSchedulerAddr string   `env:"TALARIA_SCHEDULER_ADDR,required"`
	TalariaNodeList      []string `env:"TALARIA_NODE_LIST,required"`
	IntraAnalystList     []string `env:"INTRA_ANALYST_LIST,required"`
	PprofAddr            string   `env:"PPROF_ADDR"`

	ToAnalyst map[string]string
}

func Load() *Config {
	conf := Config{
		PprofAddr: "localhost:0",
	}

	if err := envstruct.Load(&conf); err != nil {
		log.Fatalf("Invalid config: %s", err)
	}

	if len(conf.TalariaNodeList) != len(conf.IntraAnalystList) {
		log.Fatalf("List lengths of TALARIA_NODE_LIST and INTRA_ANALYST_LIST must match")
	}

	conf.ToAnalyst = make(map[string]string)
	for i := range conf.IntraAnalystList {
		conf.ToAnalyst[conf.TalariaNodeList[i]] = conf.IntraAnalystList[i]
	}

	return &conf
}

Set analyst default pprof port to 0