package runner
import (
	"net/http"
	"fmt"
	"sync"
	"bytes"
	"github.com/dudang/golt/parser"
)

var wg sync.WaitGroup

type httpRequest func(string) (*http.Response, error)

func ExecuteGoltTest(goltTest parser.Golt) {
	for _, element := range goltTest.Golt {
		executeElement(element)
	}
}

func executeElement(element parser.GoltJson) {
	wg.Add(element.Threads)
	for i:= 0; i < element.Threads; i++ {
		go executeHttpRequest(element)
	}
	wg.Wait()
}

func executeHttpRequest(element parser.GoltJson) {
	for i := 1; i <= element.Repetitions; i++ {
		payload := []byte(element.Payload)
		req, err := http.NewRequest(element.Method, element.URL, bytes.NewBuffer(payload))

		client := &http.Client{}
		resp, err := client.Do(req)
		if err != nil {
			fmt.Printf("%v\n", err)
		}
		defer resp.Body.Close()
		fmt.Printf("Repetitions: %d  Status Code: %d Success: %t\n", i, resp.StatusCode, resp.StatusCode == element.Assert.Status)
	}
	wg.Done()
}

package runner
import (
	"net/http"
	"fmt"
	"sync"
	"bytes"
	"github.com/dudang/golt/parser"
)

var wg sync.WaitGroup

var httpClient = &http.Client{}

func ExecuteGoltTest(goltTest parser.Golt) {
	for _, element := range goltTest.Golt {
		executeElement(element)
	}
}

func executeElement(element parser.GoltJson) {
	wg.Add(element.Threads)
	for i:= 0; i < element.Threads; i++ {
		go executeHttpRequest(element)
	}
	wg.Wait()
}

func executeHttpRequest(element parser.GoltJson) {
	for i := 1; i <= element.Repetitions; i++ {
		payload := []byte(element.Payload)
		req, err := http.NewRequest(element.Method, element.URL, bytes.NewBuffer(payload))

		resp, err := httpClient.Do(req)
		if err != nil {
			fmt.Printf("%v\n", err)
		}
		defer resp.Body.Close()
		fmt.Printf("Repetitions: %d  Status Code: %d Success: %t\n", i, resp.StatusCode, resp.StatusCode == element.Assert.Status)
	}
	wg.Done()
}

Make a static HTTP Client to re-use TCP connections


package atcclient

import "github.com/concourse/atc"

//go:generate counterfeiter . Handler
type Handler interface {
	// 	AbortBuild()
	// 	BuildEvents()
	// 	CreateBuild()
	// 	CreatePipe()
	// 	DeletePipeline()
	// 	DownloadCLI()
	// 	GetConfig()
	// 	HijackContainer()
	// 	ListContainer()
	// 	ListJobInputs()
	// 	ReadPipe()
	// 	SaveConfig()
	// 	WritePipe()
	AllBuilds() ([]atc.Build, error)
	Build(buildID string) (atc.Build, error)
	Job(pipelineName, jobName string) (atc.Job, error)
	JobBuild(pipelineName, jobName, buildName string) (atc.Build, error)
}

type AtcHandler struct {
	client Client
}

func NewAtcHandler(c Client) AtcHandler {
	return AtcHandler{client: c}
}

package atcclient

import "github.com/concourse/atc"

//go:generate counterfeiter . Handler
type Handler interface {
	// 	AbortBuild()
	// 	BuildEvents()
	// 	CreateBuild()
	// 	CreatePipe()
	// 	DeletePipeline()
	// 	DownloadCLI()
	// 	HijackContainer()
	// 	ListContainer()
	// 	ListJobInputs()
	// 	ReadPipe()
	// 	SaveConfig()
	// 	WritePipe()
	AllBuilds() ([]atc.Build, error)
	Build(buildID string) (atc.Build, error)
	Job(pipelineName, jobName string) (atc.Job, error)
	JobBuild(pipelineName, jobName, buildName string) (atc.Build, error)
	PipelineConfig(pipelineName string) (atc.Config, error)
}

type AtcHandler struct {
	client Client
}

func NewAtcHandler(c Client) AtcHandler {
	return AtcHandler{client: c}
}

Use atcHandler.PipelineConfig instead of GetConfig


package xlsx

import "fmt"

func ExampleRow_ReadStruct() {
	//example type
	type structTest struct {
		IntVal     int     `xlsx:"0"`
		StringVal  string  `xlsx:"1"`
		FloatVal   float64 `xlsx:"2"`
		IgnoredVal int     `xlsx:"-"`
		BoolVal    bool    `xlsx:"4"`
	}
	structVal := structTest{
		IntVal:     16,
		StringVal:  "heyheyhey :)!",
		FloatVal:   3.14159216,
		IgnoredVal: 7,
		BoolVal:    true,
	}
	//create a new xlsx file and write a struct
	//in a new row
	f := NewFile()
	sheet, _ := f.AddSheet("TestRead")
	row := sheet.AddRow()
	row.WriteStruct(&structVal, -1)

	//read the struct from the same row
	readStruct := &structTest{}
	err := row.ReadStruct(readStruct)
	if err != nil {
		fmt.Println(readStruct)
	} else {
		panic(err)
	}
}

package xlsx

import "fmt"

func ExampleRow_ReadStruct() {
	//example type
	type structTest struct {
		IntVal     int     `xlsx:"0"`
		StringVal  string  `xlsx:"1"`
		FloatVal   float64 `xlsx:"2"`
		IgnoredVal int     `xlsx:"-"`
		BoolVal    bool    `xlsx:"4"`
	}
	structVal := structTest{
		IntVal:     16,
		StringVal:  "heyheyhey :)!",
		FloatVal:   3.14159216,
		IgnoredVal: 7,
		BoolVal:    true,
	}
	//create a new xlsx file and write a struct
	//in a new row
	f := NewFile()
	sheet, _ := f.AddSheet("TestRead")
	row := sheet.AddRow()
	row.WriteStruct(&structVal, -1)

	//read the struct from the same row
	readStruct := &structTest{}
	err := row.ReadStruct(readStruct)
	if err != nil {
		panic(err)
	} else {
		fmt.Println(readStruct)
	}
}

Fix documentation example showing use of ReadStruct


package drum

// DecodeFile decodes the drum machine file found at the provided path
// and returns a pointer to a parsed pattern which is the entry point to the
// rest of the data.
// TODO: implement
func DecodeFile(path string) (*Pattern, error) {
	p := &Pattern{}
	return p, nil
}

// Pattern is the high level representation of the
// drum pattern contained in a .splice file.
// TODO: implement
type Pattern struct{}

package drum

import (
	"encoding/binary"
	"encoding/hex"
	"fmt"
	"os"
)

// DecodeFile decodes the drum machine file found at the provided path
// and returns a pointer to a parsed pattern which is the entry point to the
// rest of the data.
// TODO: implement
func DecodeFile(path string) (*Pattern, error) {

	fmt.Println("Reading file", path)

	f, err := os.Open(path)
	if err != nil {
		panic(err)
	}

	stats, _ := f.Stat()
	size := stats.Size()

	data := make([]byte, size)

	defer f.Close()

	err = binary.Read(f, binary.LittleEndian, &data)
	if err != nil {
		fmt.Println("binary.Read failed:", err)
	}

	fmt.Println(hex.Dump(data))

	p := &Pattern{}
	return p, nil
}

// Pattern is the high level representation of the
// drum pattern contained in a .splice file.
// TODO: implement
type Pattern struct{}

Read binary data from file


package main

import (
	"fmt"
	"log"
	"os"

	"github.com/arachnist/gorepost/bot"
	"github.com/arachnist/gorepost/config"
	"github.com/arachnist/gorepost/irc"
)

func main() {
	var exit chan struct{}

	config, err := config.ReadConfig(os.Args[1])
	if err != nil {
		fmt.Println("Error reading configuration from", os.Args[1], "error:", err.Error())
		os.Exit(1)
	}

	logfile, err := os.OpenFile(config.Logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		fmt.Println("Error opening", config.Logpath, "for writing, error:", err.Error())
		os.Exit(1)
	}
	log.SetOutput(logfile)

	connections := make([]irc.Connection, len(config.Networks))
	for i, _ := range connections {
		network := config.Networks[i]
		connections[i].Setup(bot.Dispatcher, network, config.Servers[network], config.Nick, config.User, config.RealName)
	}
	<-exit
}

package main

import (
	"log"
	"os"

	"github.com/arachnist/gorepost/bot"
	"github.com/arachnist/gorepost/config"
	"github.com/arachnist/gorepost/irc"
)

func main() {
	var exit chan struct{}

	if len(os.Args) < 2 {
		log.Fatalln("Usage:", os.Args[0], "<config-file.json>")
	}
	config, err := config.ReadConfig(os.Args[1])
	if err != nil {
		log.Fatalln("Error reading configuration from", os.Args[1], "error:", err.Error())
	}

	logfile, err := os.OpenFile(config.Logpath, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		log.Fatalln("Error opening", config.Logpath, "for writing, error:", err.Error())
	}
	log.SetOutput(logfile)

	connections := make([]irc.Connection, len(config.Networks))
	for i, _ := range connections {
		network := config.Networks[i]
		connections[i].Setup(bot.Dispatcher, network, config.Servers[network], config.Nick, config.User, config.RealName)
	}
	<-exit
}

Print a nicer error messages on startup


package rabbithole

// Extra arguments as a map (on queues, bindings, etc)
type Properties map[string]interface{}

// Port used by RabbitMQ or clients
type Port int

// Rate of change of a numerical value
type RateDetails struct {
	Rate float32 `json:"rate"`
}

// RabbitMQ context (Erlang app) running on
// a node
type BrokerContext struct {
	Node        string `json:"node"`
	Description string `json:"description"`
	Path        string `json:"path"`
	Port        Port   `json:"port"`
	Ignore      bool   `json:"ignore_in_use"`
}

// Basic published messages statistics
type MessageStats struct {
	Publish        int         `json:"publish"`
	PublishDetails RateDetails `json:"publish_details"`
}

package rabbithole

import "strconv"

// Extra arguments as a map (on queues, bindings, etc)
type Properties map[string]interface{}

// Port used by RabbitMQ or clients
type Port int

func (p *Port) UnmarshalJSON(b []byte) error {
	stringValue := string(b)
	var parsed int64
	var err error
	if stringValue[0] == '"' && stringValue[len(stringValue)-1] == '"' {
		parsed, err = strconv.ParseInt(stringValue[1:len(stringValue)-1], 10, 32)
	} else {
		parsed, err = strconv.ParseInt(stringValue, 10, 32)
	}
	if err == nil {
		*p = Port(int(parsed))
	}
	return err
}

// Rate of change of a numerical value
type RateDetails struct {
	Rate float32 `json:"rate"`
}

// RabbitMQ context (Erlang app) running on
// a node
type BrokerContext struct {
	Node        string `json:"node"`
	Description string `json:"description"`
	Path        string `json:"path"`
	Port        Port   `json:"port"`
	Ignore      bool   `json:"ignore_in_use"`
}

// Basic published messages statistics
type MessageStats struct {
	Publish        int         `json:"publish"`
	PublishDetails RateDetails `json:"publish_details"`
}

Handle when rabbitmq sends a port value in a string


package main

import (
	"regexp"
	"strings"
)

var (
	branches = regexp.MustCompile(`(?:[^,\\]|\\.)*`)
)

func newMatcher(pat string) (*regexp.Regexp, error) {
	sp := branches.FindAllString(pat, -1)
	for i := 0; i < len(sp); i++ {
		sp[i] = strings.Replace(sp[i], `\,`, `,`, -1)
		sp[i] = regexp.QuoteMeta(sp[i])
	}
	pat = "(" + strings.Join(sp, "|") + ")"
	return regexp.Compile(pat)
}

package main

import (
	"regexp"
	"strconv"
	"strings"
)

var (
	branches = regexp.MustCompile(`(?:[^,\\]|\\.)*`)
)

func newMatcher(pat string) (m *regexp.Regexp, err error) {
	pat = strings.Replace(pat, `\,`, `\\,`, -1)
	pat = `"` + pat + `"`
	pat, err = strconv.Unquote(pat)
	if err != nil {
		return nil, err
	}
	sp := branches.FindAllString(pat, -1)
	for i := 0; i < len(sp); i++ {
		sp[i] = strings.Replace(sp[i], `\,`, `,`, -1)
		sp[i] = regexp.QuoteMeta(sp[i])
	}
	pat = "(" + strings.Join(sp, "|") + ")"
	return regexp.Compile(pat)
}

Implement unquote special values in newMatcher


package specs

import "fmt"

const (
	// VersionMajor is for an API incompatible changes
	VersionMajor = 0
	// VersionMinor is for functionality in a backwards-compatible manner
	VersionMinor = 2
	// VersionPatch is for backwards-compatible bug fixes
	VersionPatch = 0
)

// Version is the specification version that the package types support.
var Version = fmt.Sprintf("%d.%d.%d", VersionMajor, VersionMinor, VersionPatch)

Fix an extra space in VersionMinor


package models_test

import (
	"encoding/json"
	"github.com/herald-it/goncord/models"
	"testing"
)

func TestNewDumpTokenModel(t *testing.T) {
	dump_token := &models.DumpToken{}

	if dump_token == nil {
		t.Fatal("Nil pointer after create new dump token")
	}
}

func TestJsonDumpTokenModel(t *testing.T) {
	dump_token := models.DumpToken{
		Token: "my_secret_token"}

	const str = `{"token":"my_secret_token"}`
	b, e := json.Marshal(&dump_token)

	if e != nil {
		t.Fatalf("Error: %v", e.Error())
	}

	if string(b) != str {
		t.Fatalf("%v not equal %v", string(b), str)
	}
}

package models_test

import (
	"encoding/json"
	"github.com/herald-it/goncord/models"
	. "github.com/smartystreets/goconvey/convey"
	"testing"
)

func TestNewDumpTokenModel(t *testing.T) {
	dump_token := &models.DumpToken{}

	Convey("Create new dump token", t, func() {
		So(dump_token, ShouldNotBeNil)
	})
}

func TestJsonDumpTokenModel(t *testing.T) {
	dump_token := models.DumpToken{
		Token: "my_secret_token"}

	const str = `{"token":"my_secret_token"}`
	b, e := json.Marshal(&dump_token)

	Convey("Marshal struct to json", t, func() {
		So(e, ShouldBeNil)
	})

	Convey("Test correct jsonify", t, func() {
		So(string(b), ShouldEqual, str)
	})
}

Change test fraemwork on Convey.


// +build !consulent

package state

import (
	"github.com/hashicorp/consul/agent/structs"
	"github.com/hashicorp/go-memdb"
)

func firstWithTxn(tx *txn,
	table, index, idxVal string, entMeta *structs.EnterpriseMeta) (interface{}, error) {

	return tx.First(table, index, idxVal)
}

func firstWatchWithTxn(tx *txn,
	table, index, idxVal string, entMeta *structs.EnterpriseMeta) (<-chan struct{}, interface{}, error) {

	return tx.FirstWatch(table, index, idxVal)
}

func firstWatchCompoundWithTxn(tx *txn,
	table, index string, _ *structs.EnterpriseMeta, idxVals ...interface{}) (<-chan struct{}, interface{}, error) {
	return tx.FirstWatch(table, index, idxVals...)
}

func getWithTxn(tx *txn,
	table, index, idxVal string, entMeta *structs.EnterpriseMeta) (memdb.ResultIterator, error) {

	return tx.Get(table, index, idxVal)
}

func getCompoundWithTxn(tx *txn, table, index string,
	_ *structs.EnterpriseMeta, idxVals ...interface{}) (memdb.ResultIterator, error) {

	return tx.Get(table, index, idxVals...)
}

// +build !consulent

package state

import (
	"github.com/hashicorp/consul/agent/structs"
	"github.com/hashicorp/go-memdb"
)

func firstWithTxn(tx ReadTxn,
	table, index, idxVal string, entMeta *structs.EnterpriseMeta) (interface{}, error) {

	return tx.First(table, index, idxVal)
}

func firstWatchWithTxn(tx ReadTxn,
	table, index, idxVal string, entMeta *structs.EnterpriseMeta) (<-chan struct{}, interface{}, error) {

	return tx.FirstWatch(table, index, idxVal)
}

func firstWatchCompoundWithTxn(tx ReadTxn,
	table, index string, _ *structs.EnterpriseMeta, idxVals ...interface{}) (<-chan struct{}, interface{}, error) {
	return tx.FirstWatch(table, index, idxVals...)
}

func getWithTxn(tx ReadTxn,
	table, index, idxVal string, entMeta *structs.EnterpriseMeta) (memdb.ResultIterator, error) {

	return tx.Get(table, index, idxVal)
}

func getCompoundWithTxn(tx ReadTxn, table, index string,
	_ *structs.EnterpriseMeta, idxVals ...interface{}) (memdb.ResultIterator, error) {

	return tx.Get(table, index, idxVals...)
}

Use ReadTxn interface in state store helper functions


package h2spec

import (
	"fmt"
	"time"

	"github.com/summerwind/h2spec/config"
	"github.com/summerwind/h2spec/http2"
	"github.com/summerwind/h2spec/log"
	"github.com/summerwind/h2spec/reporter"
	"github.com/summerwind/h2spec/spec"
)

func Run(c *config.Config) error {
	failed := false

	specs := []*spec.TestGroup{
		http2.Spec(),
	}

	start := time.Now()
	for _, s := range specs {
		s.Test(c)
		if s.FailedCount > 0 {
			failed = true
		}
	}
	end := time.Now()
	d := end.Sub(start)

	if c.DryRun {
		return nil
	}

	if failed {
		log.SetIndentLevel(0)
		reporter.FailedTests(specs)
	}

	log.SetIndentLevel(0)
	log.Println(fmt.Sprintf("Finished in %.4f seconds", d.Seconds()))
	reporter.Summary(specs)

	if c.JUnitReport != "" {
		err := reporter.JUnitReport(specs, c.JUnitReport)
		if err != nil {
			return err
		}
	}

	return nil
}

package h2spec

import (
	"fmt"
	"time"

	"github.com/summerwind/h2spec/config"
	"github.com/summerwind/h2spec/http2"
	"github.com/summerwind/h2spec/log"
	"github.com/summerwind/h2spec/reporter"
	"github.com/summerwind/h2spec/spec"
)

func Run(c *config.Config) error {
	total := 0
	failed := false

	specs := []*spec.TestGroup{
		http2.Spec(),
	}

	start := time.Now()
	for _, s := range specs {
		s.Test(c)

		if s.FailedCount > 0 {
			failed = true
		}

		total += s.FailedCount
		total += s.SkippedCount
		total += s.PassedCount
	}
	end := time.Now()
	d := end.Sub(start)

	if c.DryRun {
		return nil
	}

	if total == 0 {
		log.SetIndentLevel(0)
		log.Println("No matched tests found.")
		return nil
	}

	if failed {
		log.SetIndentLevel(0)
		reporter.FailedTests(specs)
	}

	log.SetIndentLevel(0)
	log.Println(fmt.Sprintf("Finished in %.4f seconds", d.Seconds()))
	reporter.Summary(specs)

	if c.JUnitReport != "" {
		err := reporter.JUnitReport(specs, c.JUnitReport)
		if err != nil {
			return err
		}
	}

	return nil
}

Print messagen if there is no matched test


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

package main_test

import (
	"testing"

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

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

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

package main_test

import (
	"testing"

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

func TestStatic(t *testing.T) {
	RegisterFailHandler(Fail)
	RunSpecs(t, "plugins/ipam/static")
}

Align test suite name with others


package vsphere

import (
	"fmt"

	"github.com/cloudfoundry/bosh-bootloader/storage"
)

type TemplateGenerator struct{}

func NewTemplateGenerator() TemplateGenerator {
	return TemplateGenerator{}
}

func (t TemplateGenerator) Generate(state storage.State) string {
	return fmt.Sprintf(`
variable "vsphere_subnet" {}
variable "jumpbox_ip" {
  default = ""
}
variable "internal_gw" {}
variable "network_name" {}
variable "vcenter_cluster" {}
variable "bosh_director_internal_ip" {
  default = ""
}

output "internal_cidr" { value = "${var.vsphere_subnet}" }
output "internal_gw" { value = "${var.internal_gw}" }
output "network_name" { value = "${var.network_name}" }
output "vcenter_cluster" { value = "${var.vcenter_cluster}" }
output "jumpbox_url" { value = "${var.jumpbox_ip}:22" }
output "external_ip" { value = "${var.jumpbox_ip}" }
output "jumpbox_internal_ip" { value = "${var.jumpbox_ip}" }
output "bosh_director_internal_ip" { value = "${var.bosh_director_internal_ip}" }
`)
}

package vsphere

import (
	"fmt"

	"github.com/cloudfoundry/bosh-bootloader/storage"
)

type TemplateGenerator struct{}

func NewTemplateGenerator() TemplateGenerator {
	return TemplateGenerator{}
}

func (t TemplateGenerator) Generate(state storage.State) string {
	return fmt.Sprintf(`
variable "vsphere_subnet" {}
variable "jumpbox_ip" {}
variable "internal_gw" {}
variable "network_name" {}
variable "vcenter_cluster" {}
variable "bosh_director_internal_ip" {}

output "internal_cidr" { value = "${var.vsphere_subnet}" }
output "internal_gw" { value = "${var.internal_gw}" }
output "network_name" { value = "${var.network_name}" }
output "vcenter_cluster" { value = "${var.vcenter_cluster}" }
output "jumpbox_url" { value = "${var.jumpbox_ip}:22" }
output "external_ip" { value = "${var.jumpbox_ip}" }
output "jumpbox_internal_ip" { value = "${var.jumpbox_ip}" }
output "bosh_director_internal_ip" { value = "${var.bosh_director_internal_ip}" }
`)
}

Remove default for director & jb ip in vsphere terraform template


package main

import (
	"fmt"
	"os"
	"strings"
)

func BoolString(tf bool) string {
	if tf {
		return "Y"
	}
	return "F"
}

func CurrentUser() string {
	return fmt.Sprintf("%s@%s", os.Getenv("USER"), os.Getenv("HOSTNAME"))
}

func DEBUG(format string, args ...interface{}) {
	if debug {
		content := fmt.Sprintf(format, args...)
		lines := strings.Split(content, "\n")
		for i, line := range lines {
			lines[i] = "DEBUG> " + line
		}
		content = strings.Join(lines, "\n")
		fmt.Fprintf(os.Stderr, "%s\n", content)
	}
}

package main

import (
	"fmt"
	"os"
	"strings"
)

func BoolString(tf bool) string {
	if tf {
		return "Y"
	}
	return "N"
}

func CurrentUser() string {
	return fmt.Sprintf("%s@%s", os.Getenv("USER"), os.Getenv("HOSTNAME"))
}

func DEBUG(format string, args ...interface{}) {
	if debug {
		content := fmt.Sprintf(format, args...)
		lines := strings.Split(content, "\n")
		for i, line := range lines {
			lines[i] = "DEBUG> " + line
		}
		content = strings.Join(lines, "\n")
		fmt.Fprintf(os.Stderr, "%s\n", content)
	}
}

Fix stupid bug with true/false = Y/N


package socket

import (
    "time"
    "net/http"
    "github.com/gorilla/websocket"
    "app/hub"
    "app/message"
)

var upgrader = websocket.Upgrader{}

func writeSocket(socket *websocket.Conn, c hub.Connection)  {
    defer socket.Close()
    for {
        m := <- c.Out
        socket.WriteJSON(&m)
    }
}

// Handler handles websocket connections at /ws
func Handler(w http.ResponseWriter, r *http.Request) {
    socket, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
        panic(err)
	}
	defer socket.Close()

    c := hub.NewConnection()

    go writeSocket(socket, c)

    for {
        m := message.SocketMessage{}
        m.CreatedAt = time.Now().UTC()

		socket.ReadJSON(&m)

        switch m.Action {
        case "publish":
            hub.Publish(m)
        case "subscribe":
            hub.Subscribe(m.Event, c)
        case "unsubscribe":
            hub.Unsubscribe(m.Event, c)
        case "unsubscribe:all":
            hub.UnsubscribeAll(c)
        }
	}
}

package socket

import (
    "time"
    "net/http"
    "github.com/gorilla/websocket"
    "app/hub"
    "app/message"
)

var upgrader = websocket.Upgrader{}

func writeSocket(socket *websocket.Conn, c hub.Connection)  {
    defer socket.Close()
    for {
        m := <- c.Out
        socket.WriteJSON(&m)
    }
}

// Handler handles websocket connections at /ws
func Handler(w http.ResponseWriter, r *http.Request) {
    socket, err := upgrader.Upgrade(w, r, nil)
	if err != nil {
        panic(err)
	}
	defer socket.Close()

    c := hub.NewConnection()
    defer hub.UnsubscribeAll(c)

    go writeSocket(socket, c)

    for {
        m := message.SocketMessage{}
        m.CreatedAt = time.Now().UTC()

		socket.ReadJSON(&m)

        switch m.Action {
        case "publish":
            hub.Publish(m)
        case "subscribe":
            hub.Subscribe(m.Event, c)
        case "unsubscribe":
            hub.Unsubscribe(m.Event, c)
        case "unsubscribe:all":
            hub.UnsubscribeAll(c)
        }
	}
}

Clean up all subscriptions when socket closes


package transport

import (
	"time"
)

type Message struct {
	Header map[string]string
	Body   []byte
}

type Socket interface {
	Recv(*Message) error
	Send(*Message) error
	Close() error
}

type Client interface {
	Recv(*Message) error
	Send(*Message) error
	Close() error
}

type Listener interface {
	Addr() string
	Close() error
	Accept(func(Socket)) error
}

// Transport is an interface which is used for communication between
// services. It uses socket send/recv semantics and had various
// implementations {HTTP, RabbitMQ, NATS, ...}
type Transport interface {
	Dial(addr string, opts ...DialOption) (Client, error)
	Listen(addr string, opts ...ListenOption) (Listener, error)
	String() string
}

type Option func(*Options)

type DialOption func(*DialOptions)

type ListenOption func(*ListenOptions)

var (
	DefaultTransport Transport = newHTTPTransport()

	DefaultDialTimeout = time.Second * 5
)

func NewTransport(opts ...Option) Transport {
	return newHTTPTransport(opts...)
}

func Dial(addr string, opts ...DialOption) (Client, error) {
	return DefaultTransport.Dial(addr, opts...)
}

func Listen(addr string, opts ...ListenOption) (Listener, error) {
	return DefaultTransport.Listen(addr, opts...)
}

func String() string {
	return DefaultTransport.String()
}

package transport

import (
	"time"
)

type Message struct {
	Header map[string]string
	Body   []byte
}

type Socket interface {
	Recv(*Message) error
	Send(*Message) error
	Close() error
}

type Client interface {
	Socket
}

type Listener interface {
	Addr() string
	Close() error
	Accept(func(Socket)) error
}

// Transport is an interface which is used for communication between
// services. It uses socket send/recv semantics and had various
// implementations {HTTP, RabbitMQ, NATS, ...}
type Transport interface {
	Dial(addr string, opts ...DialOption) (Client, error)
	Listen(addr string, opts ...ListenOption) (Listener, error)
	String() string
}

type Option func(*Options)

type DialOption func(*DialOptions)

type ListenOption func(*ListenOptions)

var (
	DefaultTransport Transport = newHTTPTransport()

	DefaultDialTimeout = time.Second * 5
)

func NewTransport(opts ...Option) Transport {
	return newHTTPTransport(opts...)
}

func Dial(addr string, opts ...DialOption) (Client, error) {
	return DefaultTransport.Dial(addr, opts...)
}

func Listen(addr string, opts ...ListenOption) (Listener, error) {
	return DefaultTransport.Listen(addr, opts...)
}

func String() string {
	return DefaultTransport.String()
}

Use Socket in the Client interface


package cli

import (
	"os"

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

func ExampleAddCommand() {
	os.Setenv("AWS_ACCESS_KEY_ID", "llamas")
	os.Setenv("AWS_SECRET_ACCESS_KEY", "rock")
	os.Setenv("AWS_VAULT_BACKEND", "file")
	os.Setenv("AWS_VAULT_FILE_PASSPHRASE", "password")

	defer os.Unsetenv("AWS_ACCESS_KEY_ID")
	defer os.Unsetenv("AWS_SECRET_ACCESS_KEY")
	defer os.Unsetenv("AWS_VAULT_BACKEND")
	defer os.Unsetenv("AWS_VAULT_FILE_PASSPHRASE")

	app := kingpin.New(`aws-vault`, ``)
	ConfigureGlobals(app)
	ConfigureAddCommand(app)
	kingpin.MustParse(app.Parse([]string{"add", "--env", "foo"}))

	// Output:
	// Added credentials to profile "foo" in vault
}

package cli

import (
	"io/ioutil"
	"log"
	"os"

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

func ExampleAddCommand() {
	f, err := ioutil.TempFile("", "aws-config")
	if err != nil {
		log.Fatal(err)
	}
	defer os.Remove(f.Name())

	os.Setenv("AWS_CONFIG_FILE", f.Name())
	os.Setenv("AWS_ACCESS_KEY_ID", "llamas")
	os.Setenv("AWS_SECRET_ACCESS_KEY", "rock")
	os.Setenv("AWS_VAULT_BACKEND", "file")
	os.Setenv("AWS_VAULT_FILE_PASSPHRASE", "password")

	defer os.Unsetenv("AWS_ACCESS_KEY_ID")
	defer os.Unsetenv("AWS_SECRET_ACCESS_KEY")
	defer os.Unsetenv("AWS_VAULT_BACKEND")
	defer os.Unsetenv("AWS_VAULT_FILE_PASSPHRASE")

	app := kingpin.New(`aws-vault`, ``)
	ConfigureGlobals(app)
	ConfigureAddCommand(app)
	kingpin.MustParse(app.Parse([]string{"add", "--env", "foo"}))

	// Output:
	// Added credentials to profile "foo" in vault
}

Use temp config for add test


package gen

func entryScript() string {
	return `
var system=sys();
`
}

package gen

func entryScript() string {
	return `
var system=sys();
var Tpl={};
Tpl.funcs={};
Tpl.funcs.world=function(name){
	return name+",world"
}
Tpl.getTplFuncs=function(){
	var rst=[]
	for (var prop in Tpl.funcs){
		if (Tpl.funcs.hasOwnProperty(prop)){
			rst.push(prop)
		}
	}
	return rst
}
`
}

Add Tpl to the entry script


package json

import (
	"github.com/agext/levenshtein"
)

var keywords = []string{"false", "true", "null"}

// keywordSuggestion tries to find a valid JSON keyword that is close to the
// given string and returns it if found. If no keyword is close enough, returns
// the empty string.
func keywordSuggestion(given string) string {
	for _, kw := range keywords {
		dist := levenshtein.Distance(given, kw, nil)
		if dist < 3 { // threshold determined experimentally
			return kw
		}
	}
	return ""
}

package json

import (
	"github.com/agext/levenshtein"
)

var keywords = []string{"false", "true", "null"}

// keywordSuggestion tries to find a valid JSON keyword that is close to the
// given string and returns it if found. If no keyword is close enough, returns
// the empty string.
func keywordSuggestion(given string) string {
	return nameSuggestion(given, keywords)
}

// nameSuggestion tries to find a name from the given slice of suggested names
// that is close to the given name and returns it if found. If no suggestion
// is close enough, returns the empty string.
//
// The suggestions are tried in order, so earlier suggestions take precedence
// if the given string is similar to two or more suggestions.
//
// This function is intended to be used with a relatively-small number of
// suggestions. It's not optimized for hundreds or thousands of them.
func nameSuggestion(given string, suggestions []string) string {
	for _, suggestion := range suggestions {
		dist := levenshtein.Distance(given, suggestion, nil)
		if dist < 3 { // threshold determined experimentally
			return suggestion
		}
	}
	return ""
}

Generalize "keywordSuggestion" for general name suggestions


/*
Package "matrix" provides types and operations for matrix manipulation.
*/
package matrix

type Matrix interface {
	// Return the shape of matrix, which consists of the "rows" and the "columns".
	Shape() (rows, columns int)

	// Return the "rows" of matrix.
	Rows() (rows int)

	// Return the "columns" of matrix.
	Columns() (columns int)
}

type Row interface {
}

type Column interface {
}

Create "Row" interface and "Column" interface.


// +build lambdabinary,noop

package cgo

import (
	"net/http"

	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	sparta "github.com/mweagle/Sparta"
)

////////////////////////////////////////////////////////////////////////////////
// cgoMain is the primary entrypoint for the library version
func cgoMain(callerFile string,
	serviceName string,
	serviceDescription string,
	lambdaAWSInfos []*sparta.LambdaAWSInfo,
	api *sparta.API,
	site *sparta.S3Site,
	workflowHooks *sparta.WorkflowHooks) error {
	// NOOP
	return nil
}

// LambdaHandler is the public handler that's called by the transformed
// CGO compliant userinput. Users should not need to call this function
// directly
func LambdaHandler(functionName string,
	eventJSON string,
	awsCredentials *credentials.Credentials) ([]byte, http.Header, error) {
	// NOOP
	return nil, nil, nil
}

// NewSession returns a CGO-aware AWS session that uses the Python
// credentials provided by the CGO interface.
func NewSession() *session.Session {
	// NOOP
	return nil
}

// +build lambdabinary,noop

package cgo

import (
	"net/http"

	"github.com/aws/aws-sdk-go/aws/credentials"
	"github.com/aws/aws-sdk-go/aws/session"
	sparta "github.com/mweagle/Sparta"
)

////////////////////////////////////////////////////////////////////////////////
// cgoMain is the primary entrypoint for the library version
func cgoMain(callerFile string,
	serviceName string,
	serviceDescription string,
	lambdaAWSInfos []*sparta.LambdaAWSInfo,
	api *sparta.API,
	site *sparta.S3Site,
	workflowHooks *sparta.WorkflowHooks) error {
	// NOOP
	return nil
}

// LambdaHandler is the public handler that's called by the transformed
// CGO compliant userinput. Users should not need to call this function
// directly
func LambdaHandler(functionName string,
	logLevel string,
	eventJSON string,
	awsCredentials *credentials.Credentials) ([]byte, http.Header, error) {
	// NOOP
	return nil, nil, nil
}

// NewSession returns a CGO-aware AWS session that uses the Python
// credentials provided by the CGO interface.
func NewSession() *session.Session {
	// NOOP
	return nil
}

Update signature for NOP codepath


package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/glaslos/tlsh"
)

var (
	// VERSION is set by the makefile
	VERSION = "v0.0.0"
	// BUILDDATE is set by the makefile
	BUILDDATE = ""
)

func main() {
	var file = flag.String("f", "", "path to the file to be hashed")
	var raw = flag.Bool("r", false, "set to get only the hash")
	var version = flag.Bool("version", false, "print version")
	flag.Parse()
	if *version {
		fmt.Printf("%s %s\n", VERSION, BUILDDATE)
		return
	}
	if *file == "" {
		fmt.Fprintf(os.Stderr, "Usage of %s [-f <file>]\n\n", os.Args[0])
		flag.PrintDefaults()
		fmt.Println()
		return
	}
	hash, err := tlsh.Hash(*file)
	if err != nil {
		fmt.Println(err)
		return
	}
	if *raw {
		fmt.Println(hash)
	} else {
		fmt.Printf("%s  %s\n", hash, *file)
	}
}

package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/glaslos/tlsh"
)

var (
	// VERSION is set by the makefile
	VERSION = "v0.0.0"
	// BUILDDATE is set by the makefile
	BUILDDATE = ""
)

func main() {
	var file = flag.String("f", "", "path to the `file` to be hashed")
	var raw = flag.Bool("r", false, "set to get only the hash")
	var version = flag.Bool("version", false, "print version")
	flag.Parse()
	if *version {
		fmt.Printf("%s %s\n", VERSION, BUILDDATE)
		return
	}
	if *file == "" {
		fmt.Fprintf(os.Stderr, "Usage of %s [-f <file>]\n\n", os.Args[0])
		flag.PrintDefaults()
		fmt.Println()
		return
	}
	hash, err := tlsh.Hash(*file)
	if err != nil {
		fmt.Println(err)
		return
	}
	if *raw {
		fmt.Println(hash)
	} else {
		fmt.Printf("%s  %s\n", hash, *file)
	}
}

Set parameter name for flag


package master

type pqSlice struct {
	Slice          []interface{}
	LessComparator func(i, j interface{}) bool
}

func (s pqSlice) Len() int {
	return len(s.Slice)
}

func (s pqSlice) Less(left, right int) bool {
	return s.LessComparator(s.Slice[left], s.Slice[right])
}

func (s *pqSlice) Swap(i, j int) {
	s.Slice[i], s.Slice[j] = s.Slice[j], s.Slice[i]
}

func (s pqSlice) Push(i interface{}) {
	s.Slice = append(s.Slice, i)
}

func (s pqSlice) Pop() interface{} {
	ret := s.Slice[len(s.Slice)-1]
	s.Slice = s.Slice[0 : len(s.Slice)-1]
	return ret
}

package master

type pqSlice struct {
	Slice          []interface{}
	LessComparator func(i, j interface{}) bool
}

func (s pqSlice) Len() int {
	return len(s.Slice)
}

func (s pqSlice) Less(left, right int) bool {
	return s.LessComparator(s.Slice[left], s.Slice[right])
}

func (s *pqSlice) Swap(i, j int) {
	s.Slice[i], s.Slice[j] = s.Slice[j], s.Slice[i]
}

func (s *pqSlice) Push(i interface{}) {
	s.Slice = append(s.Slice, i)
}

func (s *pqSlice) Pop() interface{} {
	ret := s.Slice[len(s.Slice)-1]
	s.Slice = s.Slice[0 : len(s.Slice)-1]
	return ret
}

Use call-by-reference methods for Push and Pop


package python

import (
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"sourcegraph.com/sourcegraph/toolchain"
)

func runCmdLogError(cmd *exec.Cmd) {
	err := runCmdStderr(cmd)
	if err != nil {
		log.Printf("Error running `%s`: %s", strings.Join(cmd.Args, " "), err)
	}
}

func runCmdStderr(cmd *exec.Cmd) error {
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stderr
	return cmd.Run()
}

func getVENVBinPath() (string, error) {
	if os.Getenv("IN_DOCKER_CONTAINER") == "" {
		tc, err := toolchain.Lookup("sourcegraph.com/sourcegraph/srclib-python")
		if err != nil {
			return "", err
		}
		return filepath.Join(tc.Dir, ".env", "bin"), nil
	}
	return "", nil
}

package python

import (
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"

	"sourcegraph.com/sourcegraph/srclib/toolchain"
)

func runCmdLogError(cmd *exec.Cmd) {
	err := runCmdStderr(cmd)
	if err != nil {
		log.Printf("Error running `%s`: %s", strings.Join(cmd.Args, " "), err)
	}
}

func runCmdStderr(cmd *exec.Cmd) error {
	cmd.Stderr = os.Stderr
	cmd.Stdout = os.Stderr
	return cmd.Run()
}

func getVENVBinPath() (string, error) {
	if os.Getenv("IN_DOCKER_CONTAINER") == "" {
		tc, err := toolchain.Lookup("sourcegraph.com/sourcegraph/srclib-python")
		if err != nil {
			return "", err
		}
		return filepath.Join(tc.Dir, ".env", "bin"), nil
	}
	return "", nil
}

Fix `goimports` fail, no idea how it compiles on local machine.


package main

import (
	"log"
	"net/http"
	"os"

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

func main() {
	p := os.Getenv("PORT")
	if p == "" {
		log.Fatal("$PORT must be set")
	}

	r := gin.Default()

	// PING test
	r.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "PONG")
	})

	r.Run(":" + p)
}

package main

import (
	"log"
	"net/http"
	"os"

	"gopkg.in/mgo.v2"

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

func main() {
	session, err := mgo.Dial("localhost")
	if err != nil {
		log.Fatalln("FATAL", err)
	}
	defer session.Close()

	p := os.Getenv("PORT")
	if p == "" {
		log.Fatal("$PORT must be set")
	}

	r := gin.Default()

	// PING test
	r.GET("/ping", func(c *gin.Context) {
		c.String(http.StatusOK, "PONG")
	})

	r.Run(":" + p)
}

Add mgo dependency for testing.


package log

import (
	"github.com/getsentry/raven-go"
	"log"
	"os"
)

var activeSentry bool = true

func InitializeSentry() {
	sentry := os.Getenv("SENTRY_DSN")
	if sentry == "" {
		activeSentry = false
		log.Println("===> Error: Sentry DSN environment not provisoned")
	}
	raven.SetDSN(sentry)
}

func LogError2Sentry(err error) {
	if activeSentry {
		raven.CaptureError(err, nil)
	} else {
		log.Println("===> Error: Sentry DSN environment not provisoned. Error received:", err)
	}
}

package log

import (
	"github.com/getsentry/raven-go"
	"log"
	"os"
)

var isSentryActive bool = false

func InitializeSentry() {
	sentry := os.Getenv("SENTRY_DSN")
	if sentry == "" {
		isSentryActive = false
		log.Println("===> Error: Sentry DSN environment not provisoned")
	}
	raven.SetDSN(sentry)
}

func LogError2Sentry(err error) {
	if isSentryActive {
		raven.CaptureError(err, nil)
	} else {
		log.Println("===> Error: Sentry DSN environment not provisoned. Error received:", err)
	}
}

Rename variable and initial value


// Problem 6.18

package chapter6

import (
	"fmt"
	"strings"
	"unicode"
)

func Encoding(s string) string {
	runes := []rune(s)

	var out string

	cnt := 1

	for i := 1; i < len(runes); i++ {
		if runes[i] != runes[i-1] {
			out += fmt.Sprintf("%d%c", cnt, runes[i-1])
			cnt = 1
		} else {
			cnt++
		}
	}

	out += fmt.Sprintf("%d%c", cnt, runes[len(runes)-1])

	return out
}

func Decoding(s string) string {
	runes := []rune(s)

	var out string

	cnt := 0

	for i := 0; i < len(runes); i++ {
		if unicode.IsDigit(runes[i]) {
			cnt = cnt*10 + int(runes[i]-'0')
		} else {
			out += strings.Repeat(string(runes[i]), cnt)
			cnt = 0
		}

	}

	return out
}

// Problem 6.18

package chapter6

import (
	"fmt"
	"strings"
	"unicode"
)

func Encoding(s string) string {
	runes := []rune(s)

	var out string

	cnt := 1

	for i := 1; i < len(runes); i++ {
		if runes[i] != runes[i-1] {
			out += fmt.Sprintf("%d%c", cnt, runes[i-1])
			cnt = 1
		} else {
			cnt++
		}
	}

	out += fmt.Sprintf("%d%c", cnt, runes[len(runes)-1])

	return out
}

func Decoding(s string) string {
	var out string

	cnt := 0

	for _, r := range s {
		if unicode.IsDigit(r) {
			cnt = cnt*10 + int(r-'0')
		} else {
			out += strings.Repeat(string(r), cnt)
			cnt = 0
		}
	}

	return out
}

Fix 6.18 - do not need []rune


package core

import (
	"github.com/akutz/gofig"
)

func init() {
	initDrivers()
	gofig.Register(globalRegistration())
	gofig.Register(driverRegistration())
}

func globalRegistration() *gofig.Registration {
	r := gofig.NewRegistration("Global")
	r.Yaml(`
rexray:
    host: tcp://:7979
    logLevel: warn
`)
	r.Key(gofig.String, "h", "tcp://:7979",
		"The REX-Ray host", "rexray.host")
	r.Key(gofig.String, "l", "warn",
		"The log level (error, warn, info, debug)", "rexray.logLevel")
	return r
}

func driverRegistration() *gofig.Registration {
	r := gofig.NewRegistration("Driver")
	r.Yaml(`
rexray:
    osDrivers:
    - linux
    storageDrivers:
    - libstorage
    volumeDrivers:
    - docker
`)
	r.Key(gofig.String, "", "linux",
		"The OS drivers to consider", "rexray.osDrivers")
	r.Key(gofig.String, "", "",
		"The storage drivers to consider", "rexray.storageDrivers")
	r.Key(gofig.String, "", "docker",
		"The volume drivers to consider", "rexray.volumeDrivers")
	return r
}

package core

import (
	"fmt"

	"github.com/akutz/gofig"

	"github.com/emccode/rexray/util"
)

func init() {
	initDrivers()

	gofig.SetGlobalConfigPath(util.EtcDirPath())
	gofig.SetUserConfigPath(fmt.Sprintf("%s/.rexray", util.HomeDir()))

	gofig.Register(globalRegistration())
	gofig.Register(driverRegistration())
}

func globalRegistration() *gofig.Registration {
	r := gofig.NewRegistration("Global")
	r.Yaml(`
rexray:
    host: tcp://:7979
    logLevel: warn
`)
	r.Key(gofig.String, "h", "tcp://:7979",
		"The REX-Ray host", "rexray.host")
	r.Key(gofig.String, "l", "warn",
		"The log level (error, warn, info, debug)", "rexray.logLevel")
	return r
}

func driverRegistration() *gofig.Registration {
	r := gofig.NewRegistration("Driver")
	r.Yaml(`
rexray:
    osDrivers:
    - linux
    storageDrivers:
    - libstorage
    volumeDrivers:
    - docker
`)
	r.Key(gofig.String, "", "linux",
		"The OS drivers to consider", "rexray.osDrivers")
	r.Key(gofig.String, "", "",
		"The storage drivers to consider", "rexray.storageDrivers")
	r.Key(gofig.String, "", "docker",
		"The volume drivers to consider", "rexray.volumeDrivers")
	return r
}

Fix for not setting Gofig global/user dirs


package acme

type dvsniChallenge struct{}

func (s *dvsniChallenge) CanSolve() bool {
	return false
}

func (s *dvsniChallenge) Solve(challenge challenge, domain string) {

}

package acme

type dvsniChallenge struct{}

func (s *dvsniChallenge) CanSolve() bool {
	return false
}

func (s *dvsniChallenge) Solve(challenge challenge, domain string) error {
	return nil
}

Implement new interface with DVSNI


// +build !integration

package esapi

import (
	"testing"
)

func TestAPIHelpers(t *testing.T) {
	t.Run("BoolPtr", func(t *testing.T) {
		var v *bool

		v = BoolPtr(false)
		if v == nil || *v != false {
			t.Errorf("Expected false, got: %v", v)
		}

		v = BoolPtr(true)
		if v == nil || *v != true {
			t.Errorf("Expected true, got: %v", v)
		}
	})

	t.Run("IntPtr", func(t *testing.T) {
		var v *int

		v = IntPtr(0)
		if v == nil || *v != 0 {
			t.Errorf("Expected 0, got: %v", v)
		}
	})
}

// +build !integration

package esapi

import (
	"testing"
)

func TestAPIHelpers(t *testing.T) {
	t.Run("BoolPtr", func(t *testing.T) {
		v := BoolPtr(false)
		if v == nil || *v != false {
			t.Errorf("Expected false, got: %v", v)
		}

		v = BoolPtr(true)
		if v == nil || *v != true {
			t.Errorf("Expected true, got: %v", v)
		}
	})

	t.Run("IntPtr", func(t *testing.T) {
		v := IntPtr(0)
		if v == nil || *v != 0 {
			t.Errorf("Expected 0, got: %v", v)
		}
	})
}

Simplify tests for API helpers


// +build integration

package memory

import (
	"context"
	"runtime"
	"testing"
	"time"

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

func TestMemoryAllocationAttack(t *testing.T) {
	assert := assert.New(t)
	var size uint64 = 200 * MiB

	ma, err := NewMemAllocation(size)
	assert.NoError(err, "Creation of memory allocator shouldn't error")

	// Get current memory
	var mem runtime.MemStats
	runtime.ReadMemStats(&mem)
	startMem := mem.Alloc

	// Allocate memory and test if increased.
	ma.Apply(context.TODO())
	time.Sleep(1 * time.Millisecond)
	runtime.ReadMemStats(&mem)
	endMem := mem.Alloc

	// Let 10% margin delta from the wanted size
	assert.InDelta((endMem - startMem), size, float64(size)*0.35, "current memory allocation should be wanted allocation (35% deviation)")
	// Free memory and test if released.
	ma.Revert()
	time.Sleep(1 * time.Millisecond)
	runtime.ReadMemStats(&mem)

	// Let 10% margin delta from the wanted size
	assert.InDelta(startMem, mem.Alloc, float64(size)*0.35, "current memory and initial memory should be equal (35% deviation)")
}

// +build integration

package memory

import (
	"context"
	"runtime"
	"testing"
	"time"

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

// TODO: Research how to integrate this test correctly so if doesn't fail the 50% of the times.
func _TestMemoryAllocationAttack(t *testing.T) {
	assert := assert.New(t)
	var size uint64 = 200 * MiB

	ma, err := NewMemAllocation(size)
	assert.NoError(err, "Creation of memory allocator shouldn't error")

	// Get current memory
	var mem runtime.MemStats
	runtime.ReadMemStats(&mem)
	startMem := mem.Alloc

	// Allocate memory and test if increased.
	ma.Apply(context.TODO())
	time.Sleep(1 * time.Millisecond)
	runtime.ReadMemStats(&mem)
	endMem := mem.Alloc

	// Let 10% margin delta from the wanted size
	assert.InDelta((endMem - startMem), size, float64(size)*0.35, "current memory allocation should be wanted allocation (35% deviation)")
	// Free memory and test if released.
	ma.Revert()
	time.Sleep(1 * time.Millisecond)
	runtime.ReadMemStats(&mem)

	// Let 10% margin delta from the wanted size
	assert.InDelta(startMem, mem.Alloc, float64(size)*0.35, "current memory and initial memory should be equal (35% deviation)")
}

Remove integration tests that throws lots of false positives.


/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package options

import (
	"github.com/spf13/pflag"
)

type GenPodOptions struct {
	Kubeconfig string
	Verbose    bool
	Namespace  string
	Format     string
}

func NewGenPodOptions() *GenPodOptions {
	return &GenPodOptions{}
}

func (s *GenPodOptions) AddFlags(fs *pflag.FlagSet) {
	fs.StringVar(&s.Kubeconfig, "kubeconfig", s.Kubeconfig, "Path to kubeconfig file with authorization and master location information.")
	fs.BoolVar(&s.Verbose, "verbose", s.Verbose, "Verbose mode")
	fs.StringVar(&s.Namespace, "namespace", s.Namespace, "Cluster namespace")
	fs.StringVar(&s.Format, "output", s.Format, "Output format")
}

/*
Copyright 2017 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package options

import (
	"github.com/spf13/pflag"
)

type GenPodOptions struct {
	Kubeconfig string
	Verbose    bool
	Namespace  string
	Format     string
}

func NewGenPodOptions() *GenPodOptions {
	return &GenPodOptions{Namespace: "default"}
}

func (s *GenPodOptions) AddFlags(fs *pflag.FlagSet) {
	fs.StringVar(&s.Kubeconfig, "kubeconfig", s.Kubeconfig, "Path to kubeconfig file with authorization and master location information.")
	fs.BoolVar(&s.Verbose, "verbose", s.Verbose, "Verbose mode")
	fs.StringVar(&s.Namespace, "namespace", s.Namespace, "Cluster namespace")
	fs.StringVar(&s.Format, "output", s.Format, "Output format")
}

Fix genpod to have "default" namespace by default.


package helpers

import (
	"io"
	"os"
)

// Copyfile takes a source and destination file path and copies the file. Destination needs to be complete path of file, not a directory
func CopyFile(srcPath, destPath string) (err error) {
	// open files r and w
	r, err := os.Open(srcPath)
	if err != nil {
		return err
	}
	defer r.Close()

	w, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer w.Close()

	// do the actual work
	n, err := io.Copy(w, r) // <------ here !
	if err != nil {
		return err
	}

	// fmt.Printf("Copied %v bytes\n", n)
	return nil
}

package helpers

import (
	"io"
	"os"
)

// Copyfile takes a source and destination file path and copies the file. Destination needs to be complete path of file, not a directory
func CopyFile(srcPath, destPath string) (err error) {
	// open files r and w
	r, err := os.Open(srcPath)
	if err != nil {
		return err
	}
	defer r.Close()

	w, err := os.Create(destPath)
	if err != nil {
		return err
	}
	defer w.Close()

	// do the actual work
	_, err = io.Copy(w, r) // <------ here !
	if err != nil {
		return err
	}

	// fmt.Printf("Copied %v bytes\n", n)
	return nil
}

Remove update line in copy file


//go:build boringcrypto
// +build boringcrypto

package boring

import (
	"crypto/boring"

	"gitlab.com/gitlab-org/labkit/log"
)

// CheckBoring checks whether FIPS crypto has been enabled. For the FIPS Go
// compiler in https://github.com/golang-fips/go, this requires that:
//
// 1. The kernel has FIPS enabled (e.g. `/proc/sys/crypto/fips_enabled` is 1).
// 2. A system OpenSSL can be dynamically loaded via ldopen().
func CheckBoring() {
	if boring.Enabled() {
		log.Info("FIPS mode is enabled. Using an external SSL library.")
		return
	}
	log.Info("Gitaly was compiled with FIPS mode, but an external SSL library was not enabled.")
}

//go:build boringcrypto
// +build boringcrypto

package boring

import (
	"crypto/boring"

	"gitlab.com/gitlab-org/labkit/log"
)

// CheckBoring checks whether FIPS crypto has been enabled. For the FIPS Go
// compiler in https://github.com/golang-fips/go, this requires that:
//
// 1. The kernel has FIPS enabled (e.g. `/proc/sys/crypto/fips_enabled` is 1).
// 2. A system OpenSSL can be dynamically loaded via ldopen().
func CheckBoring() {
	if boring.Enabled() {
		log.Info("FIPS mode is enabled. Using an external SSL library.")
		return
	}
	log.Info("gitlab-shell was compiled with FIPS mode, but an external SSL library was not enabled.")
}

Fix typo in FIPS mode message


package octokit

import (
	"fmt"
	"time"
)

type Status struct {
	CreatedAt   time.Time `json:"created_at"`
	UpdatedAt   time.Time `json:"updated_at"`
	State       string    `json:"state"`
	TargetUrl   string    `json:"target_url"`
	Description string    `json:"description"`
	Id          int       `json:"id"`
	Url         string    `json:"url"`
}

type StatusCreator struct {
	Login      string `json:"login"`
	Id         int    `json:"id"`
	AvatarUrl  string `json:"avatar_url"`
	GravatarId string `json:"gravatar_id"`
	Url        string `json:"url"`
}

func (c *Client) Statuses(repo Repository, sha string) ([]Status, error) {
	path := fmt.Sprintf("repos/%s/statuses/%s", repo, sha)
	var statuses []Status
	err := c.jsonGet(path, nil, &statuses)
	if err != nil {
		return nil, err
	}

	return statuses, nil
}

package octokit

import (
	"fmt"
	"time"
)

type Status struct {
	CreatedAt   time.Time     `json:"created_at"`
	UpdatedAt   time.Time     `json:"updated_at"`
	State       string        `json:"state"`
	TargetUrl   string        `json:"target_url"`
	Description string        `json:"description"`
	Id          int           `json:"id"`
	Url         string        `json:"url"`
	Creator     StatusCreator `json:"creator"`
}

type StatusCreator struct {
	Login      string `json:"login"`
	Id         int    `json:"id"`
	AvatarUrl  string `json:"avatar_url"`
	GravatarId string `json:"gravatar_id"`
	Url        string `json:"url"`
}

func (c *Client) Statuses(repo Repository, sha string) ([]Status, error) {
	path := fmt.Sprintf("repos/%s/statuses/%s", repo, sha)
	var statuses []Status
	err := c.jsonGet(path, nil, &statuses)
	if err != nil {
		return nil, err
	}

	return statuses, nil
}

Add Creator to Status API


package myaws

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ssm"
	"github.com/pkg/errors"
)

// SSMParameterLsOptions customize the behavior of the ParameterGet command.
type SSMParameterLsOptions struct {
	Name string
}

// SSMParameterLs get values from SSM parameter store with KMS decryption.
func (client *Client) SSMParameterLs(options SSMParameterLsOptions) error {
	filter := &ssm.ParametersFilter{
		Key: aws.String("Name"),
		Values: []*string{
			aws.String(options.Name),
		},
	}
	filters := []*ssm.ParametersFilter{filter}

	params := &ssm.DescribeParametersInput{
		Filters: filters,
	}

	response, err := client.SSM.DescribeParameters(params)
	if err != nil {
		return errors.Wrap(err, "DescribeParameters failed:")
	}

	for _, parameter := range response.Parameters {
		fmt.Fprintln(client.stdout, *parameter.Name)
	}

	return nil
}

package myaws

import (
	"fmt"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ssm"
	"github.com/pkg/errors"
)

// SSMParameterLsOptions customize the behavior of the ParameterGet command.
type SSMParameterLsOptions struct {
	Name string
}

// SSMParameterLs get values from SSM parameter store with KMS decryption.
func (client *Client) SSMParameterLs(options SSMParameterLsOptions) error {
	var filter *ssm.ParametersFilter
	if len(options.Name) > 0 {
		filter = &ssm.ParametersFilter{
			Key: aws.String("Name"),
			Values: []*string{
				aws.String(options.Name),
			},
		}
	}
	filters := []*ssm.ParametersFilter{filter}

	params := &ssm.DescribeParametersInput{
		Filters: filters,
	}

	response, err := client.SSM.DescribeParameters(params)
	if err != nil {
		return errors.Wrap(err, "DescribeParameters failed:")
	}

	for _, parameter := range response.Parameters {
		fmt.Fprintln(client.stdout, *parameter.Name)
	}

	return nil
}

Fix bug of ssm parameter ls when name is empty


// Copyright 2015 Robert S. Gerus. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package bot

import (
	"math/rand"
	"strings"
	"time"

	"github.com/arachnist/gorepost/irc"
)

func pick(output func(irc.Message), msg irc.Message) {
	var args []string
	if !strings.HasPrefix(msg.Trailing, ":pick ") {
		return
	}

	a := strings.TrimPrefix(msg.Trailing, ":pick ")

	if strings.Contains(a, ",") {
		args = strings.Split(a, ",")
	} else {
		args = strings.Fields(a)
	}

	choice := args[rand.Intn(len(args))]

	output(reply(msg, choice))
}

func init() {
	rand.Seed(time.Now().UnixNano())
	addCallback("PRIVMSG", "pick", pick)
}

// Copyright 2015 Robert S. Gerus. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package bot

import (
	"math/rand"
	"strings"
	"time"

	"github.com/arachnist/gorepost/irc"
)

func pick(output func(irc.Message), msg irc.Message) {
	var args []string
	if !strings.HasPrefix(msg.Trailing, ":pick ") {
		return
	}

	a := strings.TrimPrefix(msg.Trailing, ":pick ")

	if strings.Contains(a, ", ") {
		args = strings.Split(a, ", ")
	} else if strings.Contains(a, ",") {
		args = strings.Split(a, ",")
	} else {
		args = strings.Fields(a)
	}

	choice := args[rand.Intn(len(args))]

	output(reply(msg, choice))
}

func init() {
	rand.Seed(time.Now().UnixNano())
	addCallback("PRIVMSG", "pick", pick)
}

Make splitting with commas more sensible.


package render

import (
	"path/filepath"
	"testing"

	"github.com/oakmound/oak/fileutil"
	"github.com/stretchr/testify/assert"
)

func TestBatchLoad(t *testing.T) {
	fileutil.BindataDir = AssetDir
	fileutil.BindataFn = Asset
	assert.Nil(t, BatchLoad(filepath.Join("assets", "images")))
	sh, err := GetSheet(filepath.Join("16", "jeremy.png"))
	assert.Nil(t, err)
	assert.Equal(t, len(sh.ToSprites()), 8)
	_, err = loadSprite("dir", "dummy.jpg")
	assert.NotNil(t, err)
	sp, err := GetSprite("dummy.gif")
	assert.Nil(t, sp)
	assert.NotNil(t, err)
	sp, err = GetSprite(filepath.Join("16", "jeremy.png"))
	assert.NotNil(t, sp)
	assert.Nil(t, err)
}

func TestSetAssetPath(t *testing.T) {
	fileutil.BindataDir = AssetDir
	fileutil.BindataFn = Asset
	_, err := LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
	assert.Nil(t, err)
	UnloadAll()
	SetAssetPaths(wd)
	_, err = LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
	assert.NotNil(t, err)
	UnloadAll()
	SetAssetPaths(
		filepath.Join(
			wd,
			"assets",
			"images"),
	)
	_, err = LoadSheet(dir, filepath.Join("16", "jeremy.png"), 16, 16, 0)
	assert.Nil(t, err)

}

Test for render loader checking custimizability.


package pages

import (
	"io"
	"io/ioutil"
)

// StaticPage is a static page.
type StaticPage struct {
	pageFields
}

// Static returns a bool indicating that the page is a static page.
func (p *StaticPage) Static() bool { return true }

func (p *StaticPage) Write(_ Context, w io.Writer) error {
	b, err := ioutil.ReadFile(p.filename)
	if err != nil {
		return err
	}
	_, err = w.Write(b)
	return err
}

package pages

import (
	"io"
	"os"
)

// StaticPage is a static page.
type StaticPage struct {
	pageFields
}

// Static returns a bool indicating that the page is a static page.
func (p *StaticPage) Static() bool { return true }

func (p *StaticPage) Write(_ Context, w io.Writer) error {
	in, err := os.Open(p.filename)
	if err != nil {
		return err
	}
	defer in.Close() // nolint: errcheck, gas
	_, err = io.Copy(w, in)
	return err
}

Use io.Copy to write static files


package caddytls

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
)

const challengeBasePath = "/.well-known/acme-challenge"

// HTTPChallengeHandler proxies challenge requests to ACME client if the
// request path starts with challengeBasePath. It returns true if it
// handled the request and no more needs to be done; it returns false
// if this call was a no-op and the request still needs handling.
func HTTPChallengeHandler(w http.ResponseWriter, r *http.Request, listenHost, altPort string) bool {
	if !strings.HasPrefix(r.URL.Path, challengeBasePath) {
		return false
	}
	if !namesObtaining.Has(r.Host) {
		return false
	}

	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}

	upstream, err := url.Parse(fmt.Sprintf("%s://%s:%s", scheme, listenHost, altPort))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("[ERROR] ACME proxy handler: %v", err)
		return true
	}

	proxy := httputil.NewSingleHostReverseProxy(upstream)
	proxy.Transport = &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	proxy.ServeHTTP(w, r)

	return true
}

package caddytls

import (
	"crypto/tls"
	"fmt"
	"log"
	"net/http"
	"net/http/httputil"
	"net/url"
	"strings"
)

const challengeBasePath = "/.well-known/acme-challenge"

// HTTPChallengeHandler proxies challenge requests to ACME client if the
// request path starts with challengeBasePath. It returns true if it
// handled the request and no more needs to be done; it returns false
// if this call was a no-op and the request still needs handling.
func HTTPChallengeHandler(w http.ResponseWriter, r *http.Request, listenHost, altPort string) bool {
	if !strings.HasPrefix(r.URL.Path, challengeBasePath) {
		return false
	}
	if !namesObtaining.Has(r.Host) {
		return false
	}

	scheme := "http"
	if r.TLS != nil {
		scheme = "https"
	}

	if listenHost == "" {
		listenHost = "localhost"
	}

	upstream, err := url.Parse(fmt.Sprintf("%s://%s:%s", scheme, listenHost, altPort))
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		log.Printf("[ERROR] ACME proxy handler: %v", err)
		return true
	}

	proxy := httputil.NewSingleHostReverseProxy(upstream)
	proxy.Transport = &http.Transport{
		TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
	}
	proxy.ServeHTTP(w, r)

	return true
}

Set listenHost to localhost if empty; fixes test on Windows


package edn

import . "testing"

func TestEmptyGivesOnlyEOF(t *T) {
	lexer := Lex("")
	token, _ := lexer.Next()

	if token.kind != tEOF {
		t.Error("expecting EOF")
	}
}

// I suspect there's a potential race condition here first since
// the lexer is in a different thread. If `Next()` is called while the lexer
// is still in its main `for{}` loop, `done` could still be `false`
func TestEmptyIsDoneAfterFirstToken(t *T) {
	lexer := Lex("")
	_, done := lexer.Next()

	if !done {
		t.Error("expecting no more tokens")
	}
}

func TestOpenCloseParens(t *T) {
	lexer := Lex("()")

	token, _ := lexer.Next()
	if token.kind != tOpenParen {
		t.Error("expecting open parenthesis")
	}

	token, _ = lexer.Next()
	if token.kind != tCloseParen {
		t.Error("expecting close parenthesis")
	}

	token, _ = lexer.Next()
	if token.kind != tEOF {
		t.Error("expecting EOF")
	}
}

Add a failing test for next step in lexer implementation


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

package upgrades_test

import (
	gc "launchpad.net/gocheck"

	"launchpad.net/juju-core/testing/testbase"
	"launchpad.net/juju-core/upgrades"
)

type steps118Suite struct {
	testbase.LoggingSuite
}

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

var expectedSteps = []string{
	"make $DATADIR/locks owned by ubuntu:ubuntu",
	"generate system ssh key",
	"update rsyslog port",
	"install rsyslog-gnutls",
	"remove deprecated environment config settings",
	"migrate local provider agent config",
}

func (s *steps118Suite) TestUpgradeOperationsContent(c *gc.C) {
	upgradeSteps := upgrades.StepsFor118()
	c.Assert(upgradeSteps, gc.HasLen, len(expectedSteps))
	assertExpectedSteps(c, upgradeSteps, expectedSteps)
}

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

package upgrades_test

import (
	gc "launchpad.net/gocheck"

	"launchpad.net/juju-core/testing/testbase"
	"launchpad.net/juju-core/upgrades"
)

type steps118Suite struct {
	testbase.LoggingSuite
}

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

var expectedSteps = []string{
	"make $DATADIR/locks owned by ubuntu:ubuntu",
	"generate system ssh key",
	"update rsyslog port",
	"install rsyslog-gnutls",
	"remove deprecated environment config settings",
	"migrate local provider agent config",
	"make /home/ubuntu/.profile source .juju-proxy file",
}

func (s *steps118Suite) TestUpgradeOperationsContent(c *gc.C) {
	upgradeSteps := upgrades.StepsFor118()
	c.Assert(upgradeSteps, gc.HasLen, len(expectedSteps))
	assertExpectedSteps(c, upgradeSteps, expectedSteps)
}

Add the extra step to the 1.18 test.


package main

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

var output string

func init() {
	flag.Usage = func() {
		fmt.Printf("Usage: %s [-out=out.path] in.path\n\n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.StringVar(&output, "out", "out.go", "Specify a path to the output file")

	flag.Parse()
}

func main() {
	checkRequirements()

	file, err := os.Open(flag.Arg(0))
	if err != nil {
		fmt.Printf("Error! %s\n", err)
		os.Exit(2)
	}
	defer file.Close()

	fmt.Printf("input file: %s, output file: %s\n", flag.Arg(0), output)
}

func checkRequirements() {
	args := flag.Args()

	if len(args) == 0 {
		flag.Usage()

		fmt.Printf("Error! The input file is required\n")

		os.Exit(1)
	} else if len(args) > 1 {
		fmt.Printf("Notice! To many positional arguments, ignoring %v\n", args[1:])
	}
}

package main

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

var output string

func init() {
	flag.Usage = func() {
		fmt.Printf("Usage: %s [-out=out.path] in.path\n\n", os.Args[0])
		flag.PrintDefaults()
	}

	flag.StringVar(&output, "out", "out.go", "Specify a path to the output file")

	flag.Parse()
}

func main() {
	checkRequirements()

	file, err := os.Open(flag.Arg(0))
	if err != nil {
		fmt.Printf("Error! %s\n", err)
		os.Exit(2)
	}
	defer file.Close()

	prog := "go"
	path, err := exec.LookPath(prog)
	if err != nil {
		fmt.Printf("Please, install %s first.", prog)
	}
	fmt.Printf("%s is available at %s\n", prog, path)

	fmt.Printf("input file: %s, output file: %s\n", flag.Arg(0), output)
}

func checkRequirements() {
	args := flag.Args()

	if len(args) == 0 {
		flag.Usage()

		fmt.Printf("Error! The input file is required\n")

		os.Exit(1)
	} else if len(args) > 1 {
		fmt.Printf("Notice! To many positional arguments, ignoring %v\n", args[1:])
	}
}

Add go binary existence check


package main

import (
	"log"
	"os"

	"github.com/FiloSottile/CVE-2016-2107/LuckyMinus20"
)

func main() {
	res, err := LuckyMinus20.Test(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Vulnerable:", res)
	if res {
		os.Exit(1)
	}
}

package main

import (
	"log"
	"os"

	"github.com/FiloSottile/CVE-2016-2107/LuckyMinus20"
)

func main() {
	res, err := LuckyMinus20.Test(os.Args[1])
	if err != nil {
		log.Fatal(err)
	}
	log.Println("Vulnerable:", res)
	if res {
		os.Exit(2)
	}
}

Exit with error code 2 for vulnerable to make scripting easier


package main

import (
	"fmt"
	"os"

	"github.com/jingweno/nut/vendor/_nuts/github.com/codegangsta/cli"
)

func main() {
	app := cli.NewApp()
	app.Name = "nut"
	app.Usage = "Vendor Go dependencies"
	app.Version = "0.0.1"
	app.Author = ""
	app.Email = ""

	app.Commands = []cli.Command{
		installCmd,
		listCmd,
		newCmd,
	}

	app.Run(os.Args)
}

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

package main

import (
	"fmt"
	"os"

	"github.com/jingweno/nut/vendor/_nuts/github.com/codegangsta/cli"
)

func main() {
	app := cli.NewApp()
	app.Name = "nut"
	app.Usage = "Vendor Go dependencies"
	app.Version = "0.0.1"
	app.Author = ""
	app.Email = ""

	app.Commands = []cli.Command{
		installCmd,
		newCmd,
	}

	app.Run(os.Args)
}

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

Remove list command for now


// +build go1.8

package main

import (
	"os"

	"github.com/github/hub/commands"
	"github.com/github/hub/github"
	"github.com/github/hub/ui"
)

func main() {
	defer github.CaptureCrash()

	err := commands.CmdRunner.Execute()
	if !err.Ran {
		ui.Errorln(err.Error())
	}
	os.Exit(err.ExitCode)
}

Enforce go1.8+ via build flags too


package main

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

const aURL = "http://artii.herokuapp.com"

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

	if len(args) == 0 {
		fmt.Printf("Usage:\n")
		return
	}

	switch args[0] {
	case "fonts":
		fmt.Printf("%v", fontList())
	}

	fmt.Println(draw(args[0]))
}

func fontList() string {
	url := aURL + "/fonts_list"

	resp, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	s := string(body) + "\n"
	return s
}

func draw(s string) string {
	url := fmt.Sprintf("%s/make?text=%s", aURL, s)

	resp, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	a := string(body)
	return a
}

package main

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

const aURL = "http://artii.herokuapp.com"

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

	if len(args) == 0 {
		fmt.Printf("Usage:\n")
		return
	}

	switch args[0] {
	case "fonts":
		fmt.Printf("%v", fontList())
		return
	}

	fmt.Println(draw(args))
}

func fontList() string {
	url := aURL + "/fonts_list"

	resp, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	s := string(body) + "\n"
	return s
}

func draw(s []string) string {
	f := strings.Split(s[0], " ")
	js := strings.Join(f, "+")
	url := fmt.Sprintf("%s/make?text=%s", aURL, js)

	resp, err := http.Get(url)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	a := string(body)
	return a
}

Address when args passed to cli are in quotes


// Challenge 32 - Break HMAC-SHA1 with a slightly less artificial timing leak
// http://cryptopals.com/sets/4/challenges/32

package cryptopals

import (
	"crypto/sha1"
	"net/http"
	"time"
)

type challenge32 struct {
}

func (challenge32) ForgeHmacSHA1SignaturePrecise(addr, file string) []byte {
	sig := make([]byte, sha1.Size)
	x := challenge31{}

	for i := 0; i < len(sig); i++ {
		var valBest byte
		var timeBest time.Duration

		for j := 0; j < 256; j++ {
			sig[i] = byte(j)
			url := x.buildURL(addr, file, sig)
			start := time.Now()

			for k := 0; k < 15; k++ {
				resp, _ := http.Get(url)
				resp.Body.Close()
			}

			elapsed := time.Since(start)

			if elapsed > timeBest {
				valBest = byte(j)
				timeBest = elapsed
			}
		}

		sig[i] = valBest
	}

	return sig
}

// Challenge 32 - Break HMAC-SHA1 with a slightly less artificial timing leak
// http://cryptopals.com/sets/4/challenges/32

package cryptopals

import (
	"crypto/sha1"
	"net/http"
	"time"
)

type challenge32 struct {
}

func (challenge32) ForgeHmacSHA1SignaturePrecise(addr, file string) []byte {
	sig := make([]byte, sha1.Size)
	x := challenge31{}

	for i := 0; i < len(sig); i++ {
		var valBest byte
		var timeBest time.Duration

		for j := 0; j < 256; j++ {
			sig[i] = byte(j)
			url := x.buildURL(addr, file, sig)
			fastest := time.Hour

			for k := 0; k < 10; k++ {
				start := time.Now()
				resp, _ := http.Get(url)
				elapsed := time.Since(start)
				resp.Body.Close()

				if elapsed < fastest {
					fastest = elapsed
				}
			}

			if fastest > timeBest {
				valBest = byte(j)
				timeBest = fastest
			}
		}

		sig[i] = valBest
	}

	return sig
}

Fix solution for challenge 32


// Challenge 37 - Break SRP with a zero key
// http://cryptopals.com/sets/5/challenges/37

package cryptopals

import "math/big"

type challenge37 struct {
}

func (challenge37) Client(net Network) bool {
	A := big.NewInt(0)

	net.Write(A)
	net.Read()
	net.Read()

	S := A
	K := sha256Digest(S.Bytes())

	mac := hmacSHA256(K, S.Bytes())
	net.Write(mac)

	return net.Read().(bool)
}

func (challenge37) Server(params srpParams, info srpClientInfo, net Network) bool {
	return challenge36{}.Server(params, info, net)
}

// Challenge 37 - Break SRP with a zero key
// http://cryptopals.com/sets/5/challenges/37

package cryptopals

import "math/big"

type challenge37 struct {
}

func (challenge37) Client(net Network) bool {
	A := big.NewInt(0)
	net.Write(A)

	s := readBytes(net)
	net.Read()

	S := A
	K := sha256Digest(S.Bytes())

	mac := hmacSHA256(K, s)
	net.Write(mac)

	return net.Read().(bool)
}

func (challenge37) Server(params srpParams, info srpClientInfo, net Network) bool {
	return challenge36{}.Server(params, info, net)
}

Fix client to hmac salt instead of secret


package cmd

import (
	"log"
	"os"

	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "mocli",
	Short: "",
	Long:  `Mobingi API command line interface.`,
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.Println(err)
		os.Exit(-1)
	}
}

func init() {
	rootCmd.PersistentFlags().StringP("token", "t", "", "access token for API access")
}

package cmd

import (
	"log"
	"os"

	"github.com/spf13/cobra"
)

var rootCmd = &cobra.Command{
	Use:   "mocli",
	Short: "Mobingi API command line interface.",
	Long:  `Mobingi API command line interface.`,
}

func Execute() {
	if err := rootCmd.Execute(); err != nil {
		log.Println(err)
		os.Exit(-1)
	}
}

func init() {
	rootCmd.PersistentFlags().StringP("token", "t", "", "access token for API access")
}

Add short description for help.


package toscalib

type Playbook struct {
	AdjacencyMatrix Matrix
	Index           map[int]Play
	Inputs          map[string]PropertyDefinition
	Outputs         map[string]Output
}

type Play struct {
	NodeTemplate  NodeTemplate
	OperationName string
}

func GeneratePlaybook(s ServiceTemplateDefinition) Playbook {
	var e Playbook
	i := 0
	index := make(map[int]Play, 0)
	for _, node := range s.TopologyTemplate.NodeTemplates {
		for _, intf := range node.Interfaces {
			for op, _ := range intf.Operations {
				index[i] = Play{node, op}
				i += 1
			}
		}
	}
	e.Index = index
	e.Inputs = s.TopologyTemplate.Inputs
	e.Outputs = s.TopologyTemplate.Outputs
	return e
}

package toscalib

type Playbook struct {
	AdjacencyMatrix Matrix
	Index           map[int]Play
	Inputs          map[string]PropertyDefinition
	Outputs         map[string]Output
}

type Play struct {
	NodeTemplate  NodeTemplate
	InterfaceName string
	OperationName string
}

func GeneratePlaybook(s ServiceTemplateDefinition) Playbook {
	var e Playbook
	i := 0
	index := make(map[int]Play, 0)
	for _, node := range s.TopologyTemplate.NodeTemplates {
		for intfn, intf := range node.Interfaces {
			for op, _ := range intf.Operations {
				index[i] = Play{node, intfn, op}
				i += 1
			}
		}
	}
	e.Index = index
	e.Inputs = s.TopologyTemplate.Inputs
	e.Outputs = s.TopologyTemplate.Outputs
	return e
}

Add the interface name for comodity


// +build !k8s

package k8s

import (
	"context"
	"fmt"

	"k8s.io/client-go/rest"
)

func getEmbedded(ctx context.Context) (context.Context, *rest.Config, error) {
	return ctx, nil, fmt.Errorf("embedded support is not compiled in, rebuild with -tags k8s")
}

// +build !k8s

package k8s

import (
	"context"
	"fmt"

	"k8s.io/client-go/rest"
)

func getEmbedded(ctx context.Context) (bool, context.Context, *rest.Config, error) {
	return false, ctx, nil, fmt.Errorf("embedded support is not compiled in, rebuild with -tags k8s")
}

Fix method signature for the non-embedded verison


// Copyright (c) 2013-2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

/*
This test file is part of the btcchain package rather than than the
btcchain_test package so it can bridge access to the internals to properly test
cases which are either not possible or can't reliably be tested via the public
interface.  The functions are only exported while the tests are being run.
*/

package btcchain

import (
	"time"

	"github.com/conformal/btcutil"
)

// TstSetCoinbaseMaturity makes the ability to set the coinbase maturity
// available to the test package.
func TstSetCoinbaseMaturity(maturity int64) {
	coinbaseMaturity = maturity
}

// TstTimeSorter makes the internal timeSorter type available to the test
// package.
func TstTimeSorter(times []time.Time) timeSorter {
	return timeSorter(times)
}

// TstCheckSerializedHeight makes the internal checkSerializedHeight function
// available to the test package.
func TstCheckSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int64) error {
	return checkSerializedHeight(coinbaseTx, wantHeight)
}

// TstSetMaxMedianTimeEntries makes the ability to set the maximum number of
// median tiem entries available to the test package.
func TstSetMaxMedianTimeEntries(val int) {
	maxMedianTimeEntries = val
}

// Copyright (c) 2013-2014 Conformal Systems LLC.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

/*
This test file is part of the btcchain package rather than than the
btcchain_test package so it can bridge access to the internals to properly test
cases which are either not possible or can't reliably be tested via the public
interface.  The functions are only exported while the tests are being run.
*/

package btcchain

import (
	"sort"
	"time"

	"github.com/conformal/btcutil"
)

// TstSetCoinbaseMaturity makes the ability to set the coinbase maturity
// available to the test package.
func TstSetCoinbaseMaturity(maturity int64) {
	coinbaseMaturity = maturity
}

// TstTimeSorter makes the internal timeSorter type available to the test
// package.
func TstTimeSorter(times []time.Time) sort.Interface {
	return timeSorter(times)
}

// TstCheckSerializedHeight makes the internal checkSerializedHeight function
// available to the test package.
func TstCheckSerializedHeight(coinbaseTx *btcutil.Tx, wantHeight int64) error {
	return checkSerializedHeight(coinbaseTx, wantHeight)
}

// TstSetMaxMedianTimeEntries makes the ability to set the maximum number of
// median tiem entries available to the test package.
func TstSetMaxMedianTimeEntries(val int) {
	maxMedianTimeEntries = val
}

Modify the time sorter tests to make golint happy.


package main

import (
	"log"
	"os"
	"sync"

	"github.com/joho/godotenv"
)

func init() {
	log.Println("Starting RFC-Bot")
	if err := godotenv.Load(); err != nil {
		log.Fatal("Error loading .env file")
	}
}

func main() {
	log.Println("Initialising Writers")
	writer := NewWriter()

	log.Println("Initialising Twitter")
	twitter, err := NewTwitter(os.Getenv("TWITTER_CONSUMER_KEY"), os.Getenv("TWITTER_CONSUMER_SECRET"), os.Getenv("TWITTER_ACCESS_TOKEN"), os.Getenv("TWITTER_ACCESS_TOKEN_SECRET"))
	if err != nil {
		log.Fatal("Could not authenticate to twitter:", err)
	}
	writer.AddWriter(twitter)

	log.Println("Initialising Readers")
	var wg sync.WaitGroup
	wg.Add(2)
	go ietfRFC(writer.Wchan)
	go ietfDraftRFC(writer.Wchan)

	log.Println("Initialised")
	wg.Wait()
}

package main

import (
	"log"
	"os"
	"runtime"

	"github.com/joho/godotenv"
)

func init() {
	log.Println("Starting RFC-Bot")
	if err := godotenv.Load(); err != nil {
		log.Fatal("Error loading .env file")
	}
}

func main() {
	log.Println("Initialising Writers")
	writer := NewWriter()

	log.Println("Initialising Twitter")
	twitter, err := NewTwitter(os.Getenv("TWITTER_CONSUMER_KEY"), os.Getenv("TWITTER_CONSUMER_SECRET"), os.Getenv("TWITTER_ACCESS_TOKEN"), os.Getenv("TWITTER_ACCESS_TOKEN_SECRET"))
	if err != nil {
		log.Fatal("Could not authenticate to twitter:", err)
	}
	writer.AddWriter(twitter)

	log.Println("Initialising Readers")
	go ietfRFC(writer.Wchan)
	go ietfDraftRFC(writer.Wchan)

	log.Println("Initialised")
	runtime.Goexit()
}

Switch to runtime.Goexit instead of sync.WaitGroup as goroutines run forever


// +build !windows

package fzf

const (
	// Reader
	defaultCommand = `find -L . -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | sed s/^..//`
)

// +build !windows

package fzf

const (
	// Reader
	defaultCommand = `find -L . -path '*/\.*' -prune -o -type f -print -o -type l -print 2> /dev/null | cut -b3-`
)

Use cut instead of sed in the default command


package main

import (
	"fmt"
	"os"
)

func main() {
	if len(os.Args) == 1 {
		fmt.Println("bad args")
		return
	}
}

package main

import (
	"fmt"
	"os"
	"strconv"
)

func main() {
	if len(os.Args) == 1 {
		fmt.Println("bad args")
		return
	}
	handRaw := make([]string, len(os.Args)-1)
	copy(handRaw, os.Args[1:])

	startCard := Card{
		suit: ToSuit(pop(&handRaw)),
		rank: ToRank(pop(&handRaw)),
	}

	var hand Hand
	for len(handRaw) > 0 {
		hand = append(hand, Card{
			suit: ToSuit(pop(&handRaw)),
			rank: ToRank(pop(&handRaw)),
		})
	}
	fmt.Println(startCard)
	fmt.Println(hand)

}

type Hand []Card

func (h Hand) Len() int           { return len(h) }
func (h Hand) Swap(i, j int)      { h[i], h[j] = h[j], h[i] }
func (h Hand) Less(i, j int) bool { return h[i].rank < h[j].rank }

func (h Hand) String() string {
	var ret string
	for _, c := range h {
		ret += c.String() + " "
	}
	return ret
}

type Card struct {
	rank Rank
	suit Suit
}

func (c Card) String() string {
	return fmt.Sprintf("%v%v", c.rank, c.suit)
}

type Rank int

func (r Rank) String() string {
	switch r {
	case 13:
		return "K"
	case 12:
		return "Q"
	case 11:
		return "J"
	default:
		return strconv.Itoa(int(r))
	}
}

func ToRank(a string) Rank {
	r, err := strconv.Atoi(a)
	if err != nil {
		panic(err)
	}
	return Rank(r)
}

type Suit byte

func (s Suit) String() string {
	return string([]byte{byte(s)})
}

func ToSuit(a string) Suit {
	return Suit(a[0])
}

func pop(a *[]string) string {
	val := (*a)[len(*a)-1]
	*a = (*a)[:len(*a)-1]
	return val
}

Read hand and start card from command line


package mrepo

import (
	"os/exec"
	"strings"
)

//Make invoke make on the prj with the target as argument.
func Make(prj, target string) (result string, err error) {
	cmd := exec.Command("make", target)
	cmd.Dir = prj
	out, err := cmd.CombinedOutput()
	if err != nil {
		return
	}
	result = strings.Trim(string(out), "\n \t")
	return result, nil
}

package mrepo

import (
	"io"
	"os/exec"
)

//Make invoke make on the prj with the target as argument.
func Make(prj, target string, buf io.Writer) (err error) {
	cmd := exec.Command("make", target)
	cmd.Dir = prj
	cmd.Stdout = buf
	cmd.Stderr = buf
	return cmd.Run()
}

Make cmd now suport buffer passing


package api

// NOTE: install protoc as described on grpc.io before running go generate.

//go:generate protoc -I. -I../../../vendor/ beam_fn_api.proto --go_out=Mbeam_runner_api.proto=github.com/apache/beam/sdks/go/pkg/beam/core/api/org_apache_beam_runner_v1,plugins=grpc:org_apache_beam_fn_v1
//go:generate protoc -I. -I../../../vendor/ beam_runner_api.proto --go_out=org_apache_beam_runner_v1

package api

// NOTE: install protoc as described on grpc.io before running go generate.

//go:generate protoc -I. -I../../../vendor/ beam_fn_api.proto --go_out=Mbeam_runner_api.proto=github.com/apache/beam/sdks/go/pkg/beam/core/runtime/api/org_apache_beam_runner_v1,plugins=grpc:org_apache_beam_fn_v1
//go:generate protoc -I. -I../../../vendor/ beam_runner_api.proto --go_out=org_apache_beam_runner_v1

Fix import reference path for runner API proto.


package main

import (
	"fmt"
	"os"

	"github.com/spf13/viper"

	"github.com/minamijoyo/myaws/cmd"
)

func main() {
	if err := cmd.RootCmd.Execute(); err != nil {
		if viper.GetBool("debug") {
			fmt.Printf("%+v\n", err)
		} else {
			fmt.Printf("%v\n", err)
		}
		os.Exit(1)
	}
}

package main

import (
	"fmt"
	"os"

	"github.com/spf13/viper"

	"github.com/minamijoyo/myaws/cmd"
)

func main() {
	if err := cmd.RootCmd.Execute(); err != nil {
		if viper.GetBool("debug") {
			fmt.Fprintf(os.Stderr, "%+v\n", err)
		} else {
			fmt.Fprintf(os.Stderr, "%v\n", err)
		}
		os.Exit(1)
	}
}

Write error messages to stderr instead of stdout


package main

import "fmt"
import "github.com/stianeikeland/go-rpio"

func main() {
	fmt.Println("foo")

	err := rpio.Open()
	defer rpio.Close()
}

package main

import "io"
import "log"
import "net/http"
import "time"

import "github.com/stianeikeland/go-rpio"

type gpioHandler struct {
  pin rpio.Pin
}

func GpioHandler(pin rpio.Pin) http.Handler {
  return &gpioHandler{pin}
}

func (f *gpioHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  io.WriteString(w, "hello, gpio!\n")

  timer := time.NewTimer(time.Second * 5)
  go func() {
    f.pin.Output()
    f.pin.High()
    <-timer.C
    f.pin.Low()
  }()
}

func main() {
  err := rpio.Open()
  defer rpio.Close()

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

  http.Handle("/hodoor", GpioHandler(rpio.Pin(18)))
  log.Fatal(http.ListenAndServe(":8080", nil))
}

Set pin 18 high on request to open door


package frame

var (
	V24CommonIDs = map[string]string{
		"Title":                      "TIT2",
		"Artist":                     "TPE1",
		"Album":                      "TALB",
		"Year":                       "TYER",
		"Genre":                      "TCON",
		"Attached Picture":           "APIC",
		"Unsynchronised Lyrics/Text": "USLT",
	}
)

package frame

var (
	V24CommonIDs = map[string]string{
		"Title":                      "TIT2",
		"Artist":                     "TPE1",
		"Album":                      "TALB",
		"Year":                       "TYER",
		"Genre":                      "TCON",
		"Attached Picture":           "APIC",
		"Unsynchronised Lyrics/Text": "USLT",
		"Comment":                    "COMM",
	}
)

Add comment ID to V24CommonIDs


package cmd

import "github.com/codegangsta/cli"

var Commands = []cli.Command{
	{
		Name:      "install",
		ShortName: "i",
		Usage:     "Install specific Note.js version",
		Action:    Install,
	},
	{
		Name:   "use",
		Usage:  "Create symlink for specific Note.js version",
		Action: Use,
	},
	{
		Name:      "remove",
		ShortName: "rm",
		Usage:     "Remove installed Node.js version",
		Action:    Remove,
	},
	{
		Name:      "ls-remote",
		ShortName: "lsr",
		Usage:     "List all available Note.js versions",
		Action:    LsRemote,
	},
	{
		Name:   "ls",
		Usage:  "List all installed Node.js versions",
		Action: LsLocal,
	},
}

package cmd

import "github.com/codegangsta/cli"

var Commands = []cli.Command{
	{
		Name:      "install",
		ShortName: "i",
		Usage:     "Install specific Note.js version",
		Action:    Install,
	},
	{
		Name:   "use",
		Usage:  "Set specified Note.js version as current",
		Action: Use,
	},
	{
		Name:      "remove",
		ShortName: "rm",
		Usage:     "Remove installed Node.js version",
		Action:    Remove,
	},
	{
		Name:      "ls-remote",
		ShortName: "lsr",
		Usage:     "List all available Note.js versions",
		Action:    LsRemote,
	},
	{
		Name:   "ls",
		Usage:  "List all installed Node.js versions",
		Action: LsLocal,
	},
}

Use command help message edited


package trog

type rawNode struct {
	Id        NodeId
	ParentIds []NodeId // Every ancestor id, all the way up to the root
	ChildIds  []NodeId // Every direct child id of this node
	Pairs     []Pair   // Key/value pairs
	Flags     []Flag   // Value-only flags
}

type Node struct {
	rawNode
	Parents  []*Node // Every ancestor, all the way up to the root
	Children []*Node // Every direct child of this node
}

package trog

type rawNode struct {
	Id        NodeId
	ParentIds []NodeId // Every ancestor id, all the way up to the root
	ChildIds  []NodeId // Every direct child id of this node
	Parents   []*Node  // Every ancestor, all the way up to the root
	Children  []*Node  // Every direct child of this node
}

type Node struct {
	Pairs    []Pair  // Key/value pairs
	Flags    []Flag  // Value-only flags
	Parent   *Node   // Direct ancestor of this node
	Children []*Node // Direct children of this node
	Parents  []*Node // Every ancestor, all the way up to the root
}

// Create a new, empty, node.
func NewNode() *Node {
	return &Node{}
}

// Add a new node between the given node and its parent.
func (node *Node) Split() *Node {
	newNode := NewNode()
	parent := node.Parent

	if parent != nil {
		parent.delChild(node)
		parent.addChild(newNode)
	}
	newNode.addChild(node)
	return newNode
}

// Add a new child to the given node.
func (node *Node) AddChild() *Node {
	newNode := NewNode()
	node.addChild(newNode)
	return newNode
}

func (node *Node) addChild(child *Node) {
	child.Parent = node
	node.Children = append(node.Children, child)
}

func (node *Node) delChild(child *Node) {
	for i := 0; i < len(node.Children); i++ {
		if node.Children[i] == child {
			node.Children[i] = node.Children[len(node.Children)-1]
			node.Children = node.Children[:len(node.Children)-1]
			child.Parent = nil
		}
	}
}

Add some basic tree functions


package mccli

import (
	"fmt"

	"github.com/codegangsta/cli"
	"github.com/materials-commons/config"
	"github.com/materials-commons/mcstore/server/mcstore"
)

var ShowCommand = cli.Command{
	Name:    "show",
	Aliases: []string{"sh"},
	Usage:   "Show commands",
	Subcommands: []cli.Command{
		showConfigCommand,
	},
}

var showConfigCommand = cli.Command{
	Name:    "config",
	Aliases: []string{"conf", "c"},
	Usage:   "Show configuration",
	Action:  showConfigCLI,
}

func showConfigCLI(c *cli.Context) {
	apikey := config.GetString("apikey")
	mcurl := mcstore.MCUrl()
	mclogging := config.GetString("mclogging")
	fmt.Println("apikey:", apikey)
	fmt.Println("mcurl:", mcurl)
	fmt.Println("mclogging:", mclogging)
}

package mccli

import (
	"fmt"

	"github.com/codegangsta/cli"
	"github.com/materials-commons/config"
	"github.com/materials-commons/mcstore/server/mcstore"
)

var ShowCommand = cli.Command{
	Name:    "show",
	Aliases: []string{"sh"},
	Usage:   "Show commands",
	Subcommands: []cli.Command{
		showConfigCommand,
	},
}

var showConfigCommand = cli.Command{
	Name:    "config",
	Aliases: []string{"conf", "c"},
	Usage:   "Show configuration",
	Action:  showConfigCLI,
}

func showConfigCLI(c *cli.Context) {
	fmt.Println("apikey:", config.GetString("apikey"))
	fmt.Println("mcurl:", mcstore.MCUrl())
	fmt.Println("mclogging:", config.GetString("mclogging"))
}

Remove creating variables and just show function call results.


package config

import (
	"log"
	"reflect"
	"testing"
)

func TestParseConfig(t *testing.T) {
	input := `
  queue "test" {
    type = "test_type"
    host = "localhost"
    port = 1234
  }
`
	expect := config{
		Queues: []*Queue{
			&Queue{
				Driver:  "test_type",
				Host:    "localhost",
				Port:    1234,
				Timeout: 2,
			},
		},
	}
	out, err := Parse(input)
	if err != nil {
		log.Println(err)
	}
	if !reflect.DeepEqual(out, expect) {
		t.Fatalf("bad: %#v !== %#v", out, expect)
	}
}

package config

import (
	"log"
	"reflect"
	"testing"
	"time"
)

func TestParseConfig(t *testing.T) {
	input := `
  queue "test" {
    type = "test_type"
    host = "localhost"
    port = 1234
  }
`
	expect := config{
		Queues: []*Queue{
			&Queue{
				Driver:  "test_type",
				Host:    "localhost",
				Port:    1234,
				Timeout: 2 * time.Second,
			},
		},
	}
	out, err := Parse(input)
	if err != nil {
		log.Println(err)
	}
	if !reflect.DeepEqual(out, expect) {
		t.Fatalf("bad: %#v !== %#v", out, expect)
	}
}

Fix Timeout test struct value


// +build !linux

/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cm

import (
	"k8s.io/kubernetes/pkg/kubelet/dockertools"
)

type unsupportedContainerManager struct {
}

func NewContainerManager(_ string, _ dockertools.DockerInterface) ContainerManager {
	return &unsupportedContainerManager{}
}

func (m *unsupportedContainerManager) Start() error {
	return fmt.Errorf("Container Manager is unsupported in this build")
}

// +build !linux

/*
Copyright 2016 The Kubernetes Authors.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package cm

import (
	"fmt"
	"k8s.io/kubernetes/pkg/kubelet/dockertools"
)

type unsupportedContainerManager struct {
}

func NewContainerManager(_ string, _ dockertools.DockerInterface) ContainerManager {
	return &unsupportedContainerManager{}
}

func (m *unsupportedContainerManager) Start() error {
	return fmt.Errorf("Container Manager is unsupported in this build")
}

Fix build break on non-Linux OS introduced in 87aaf4c0


package nico

import "strings"

type Mail struct {
	Is184 bool
}

func (m Mail) String() string {
	var strs []string
	if m.Is184 {
		strs = append(strs, "184")
	}
	return strings.Join(strs, " ")
}

package nico

import "strings"

// Mail is a structure that specifies comment options.
type Mail struct {
	Is184 bool
}

func (m Mail) String() string {
	var strs []string
	if m.Is184 {
		strs = append(strs, "184")
	}
	return strings.Join(strs, " ")
}

Add godoc for the Mail struct


package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"

	"gopkg.in/jcelliott/turnpike.v2"
)

func main() {
	turnpike.Debug()
	c, err := turnpike.NewWebsocketClient(turnpike.JSON, "ws://localhost:8000/", nil)
	if err != nil {
		log.Fatal(err)
	}
	_, err = c.JoinRealm("turnpike.examples", nil)
	if err != nil {
		log.Fatal(err)
	}

	quit := make(chan bool)
	c.Subscribe("alarm.ring", func([]interface{}, map[string]interface{}) {
		fmt.Println("The alarm rang!")
		c.Close()
		quit <- true
	})
	fmt.Print("Enter the timer duration: ")
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	if err := scanner.Err(); err != nil {
		log.Fatalln("reading stdin:", err)
	}
	text := scanner.Text()
	if duration, err := strconv.Atoi(text); err != nil {
		log.Fatalln("invalid integer input:", err)
	} else {
		if _, err := c.Call("alarm.set", []interface{}{duration}, nil); err != nil {
			log.Fatalln("error setting alarm:", err)
		}
	}
	<-quit
}

package main

import (
	"bufio"
	"fmt"
	"log"
	"os"
	"strconv"

	"gopkg.in/jcelliott/turnpike.v2"
)

func main() {
	turnpike.Debug()
	c, err := turnpike.NewWebsocketClient(turnpike.JSON, "ws://localhost:8000/", nil)
	if err != nil {
		log.Fatal(err)
	}
	_, err = c.JoinRealm("turnpike.examples", nil)
	if err != nil {
		log.Fatal(err)
	}

	quit := make(chan bool)
	c.Subscribe("alarm.ring", func([]interface{}, map[string]interface{}) {
		fmt.Println("The alarm rang!")
		c.Close()
		quit <- true
	})
	fmt.Print("Enter the timer duration: ")
	scanner := bufio.NewScanner(os.Stdin)
	scanner.Scan()
	if err := scanner.Err(); err != nil {
		log.Fatalln("reading stdin:", err)
	}
	text := scanner.Text()
	if duration, err := strconv.Atoi(text); err != nil {
		log.Fatalln("invalid integer input:", err)
	} else {
		if _, err := c.Call("alarm.set", nil, []interface{}{duration}, nil); err != nil {
			log.Fatalln("error setting alarm:", err)
		}
	}
	<-quit
}

Fix Call to pass in options


package slug

import (
	"code.google.com/p/go.text/unicode/norm"
	"regexp"
	"strings"
	"unicode"
)

// don't even quote these
var _SKIP = []*unicode.RangeTable{
	unicode.Mark,
	unicode.Sk,
	unicode.Lm,
}

var _SAFE = []*unicode.RangeTable{
	unicode.Letter,
	unicode.Number,
}

func safe(r rune) rune {
	switch {
	case unicode.IsOneOf(_SKIP, r):
		return -1
	case unicode.IsOneOf(_SAFE, r):
		return unicode.ToLower(r)
	}
	return '-'
}

var _DOUBLEDASH_RE = regexp.MustCompile("--+")

func noRepeat(s string) string {
	return _DOUBLEDASH_RE.ReplaceAllString(s, "-")
}

// Slugify a string. The result will only contain lowercase letters,
// digits and dashes. It will not begin or end with a dash, and it
// will not contain runs of multiple dashes.
//
// It is NOT forced into being ASCII, but may contain any Unicode
// characters, with the above restrictions.
func Slug(s string) string {
	s = norm.NFKD.String(s)
	s = strings.Map(safe, s)
	s = strings.Trim(s, "-")
	s = noRepeat(s)
	return s
}

package slug

import (
	"golang.org/x/text/unicode/norm"
	"regexp"
	"strings"
	"unicode"
)

// don't even quote these
var _SKIP = []*unicode.RangeTable{
	unicode.Mark,
	unicode.Sk,
	unicode.Lm,
}

var _SAFE = []*unicode.RangeTable{
	unicode.Letter,
	unicode.Number,
}

func safe(r rune) rune {
	switch {
	case unicode.IsOneOf(_SKIP, r):
		return -1
	case unicode.IsOneOf(_SAFE, r):
		return unicode.ToLower(r)
	}
	return '-'
}

var _DOUBLEDASH_RE = regexp.MustCompile("--+")

func noRepeat(s string) string {
	return _DOUBLEDASH_RE.ReplaceAllString(s, "-")
}

// Slugify a string. The result will only contain lowercase letters,
// digits and dashes. It will not begin or end with a dash, and it
// will not contain runs of multiple dashes.
//
// It is NOT forced into being ASCII, but may contain any Unicode
// characters, with the above restrictions.
func Slug(s string) string {
	s = norm.NFKD.String(s)
	s = strings.Map(safe, s)
	s = strings.Trim(s, "-")
	s = noRepeat(s)
	return s
}

Use new golang.org/x/ import paths


package kvlog_test

import (
	"bytes"
	"fmt"

	log "github.com/Sirupsen/logrus"
	"github.com/gwatts/kvlog"
)

func Example() {
	var buf bytes.Buffer

	log.SetOutput(&buf)
	log.SetFormatter(
		kvlog.New(
			kvlog.IncludeCaller(),
			kvlog.WithPrimaryFields("action", "status")))

	log.WithFields(log.Fields{
		"action":          "user_login",
		"status":          "ok",
		"username":        "joe_user",
		"email":           "joe@example.com",
		"active_sessions": 4,
	}).Info("User logged in")

	// replace the timestamp so the output is consistent
	output := "2017-01-02T12:00:00.000Z " + buf.String()[25:]
	fmt.Println(output)

	// Output: 2017-01-02T12:00:00.000Z ll="info" srcfnc="Example" srcline=29 action="user_login" status="ok" active_sessions=4 email="joe@example.com" username="joe_user" _msg="User logged in"
}

package kvlog_test

import (
	"bytes"
	"fmt"
	"regexp"

	log "github.com/Sirupsen/logrus"
	"github.com/gwatts/kvlog"
)

func Example() {
	var buf bytes.Buffer

	log.SetOutput(&buf)
	log.SetFormatter(
		kvlog.New(
			kvlog.IncludeCaller(),
			kvlog.WithPrimaryFields("action", "status")))

	log.WithFields(log.Fields{
		"action":          "user_login",
		"status":          "ok",
		"username":        "joe_user",
		"email":           "joe@example.com",
		"active_sessions": 4,
	}).Info("User logged in")

	// replace the timestamp so the output is consistent
	output := "2017-01-02T12:00:00.000Z " + buf.String()[25:]

	// replace srcline so tests aren't sensitive to exact line number
	output = regexp.MustCompile(`srcline=\d+`).ReplaceAllLiteralString(output, `srcline=100`)

	fmt.Println(output)
	// Output: 2017-01-02T12:00:00.000Z ll="info" srcfnc="Example" srcline=100 action="user_login" status="ok" active_sessions=4 email="joe@example.com" username="joe_user" _msg="User logged in"
}

Make test less sensitive to line numbers


package search

import (
	"net/url"
	"strconv"
)

type search struct {
	Keyword    string
	Pagenation int
	Sort       string
}

func New(keyword string, sort string) *search {
	return &search{
		Keyword:    keyword,
		Pagenation: 0,
		Sort:       sort,
	}
}

func (s *search) GetURL() string {
	q := url.Values{}
	q.Set("pagenetion", strconv.Itoa(s.Pagenation))
	q.Set("q", s.Keyword)
	q.Set("sort", s.Sort)
	u := url.URL{
		Scheme:   "https",
		Host:     "qiita.com",
		Path:     "search",
		RawQuery: q.Encode(),
	}

	return u.String()
}

func (s *search) NextPage() {
	s.Pagenation++
}

Add search next page method