package helper

import (
	"encoding/json"
	"testing"
)

// Asserts that the request did not return an error.
// Optionally perform some checks only if the request did not fail
func AssertRequestOk(t *testing.T, response interface{}, err error, check_fn func()) {
	if err != nil {
		response_json, _ := json.MarshalIndent(response, "", "  ")
		errorPayload, _ := json.MarshalIndent(err, "", " ")
		t.Fatalf("Failed to perform request, because %s. Response:\n%s", errorPayload, response_json)
	} else {
		if check_fn != nil {
			check_fn()
		}
	}
}

// Asserts that the request _did_ return an error.
// Optionally perform some checks only if the request failed
func AssertRequestFail(t *testing.T, response interface{}, err error, check_fn func()) {
	if err == nil {
		response_json, _ := json.MarshalIndent(response, "", "  ")
		t.Fatalf("Request succeeded unexpectedly. Response:\n%s", response_json)
	} else {
		if check_fn != nil {
			check_fn()
		}
	}
}

package helper

import (
	"encoding/json"
	"reflect"
	"testing"
)

// Asserts that the request did not return an error.
// Optionally perform some checks only if the request did not fail
func AssertRequestOk(t *testing.T, response interface{}, err error, check_fn func()) {
	if err != nil {
		response_json, _ := json.MarshalIndent(response, "", "  ")
		errorPayload, _ := json.MarshalIndent(err, "", " ")
		t.Fatalf("Failed to perform request! Error: %s %s. Response: %s", getType(err), errorPayload, response_json)
	} else {
		if check_fn != nil {
			check_fn()
		}
	}
}

// Asserts that the request _did_ return an error.
// Optionally perform some checks only if the request failed
func AssertRequestFail(t *testing.T, response interface{}, err error, check_fn func()) {
	if err == nil {
		response_json, _ := json.MarshalIndent(response, "", "  ")
		t.Fatalf("Request succeeded unexpectedly. Response:\n%s", response_json)
	} else {
		if check_fn != nil {
			check_fn()
		}
	}
}

// Get type name of some value, according to https://stackoverflow.com/questions/35790935/using-reflection-in-go-to-get-the-name-of-a-struct
func getType(myvar interface{}) string {
	if t := reflect.TypeOf(myvar); t.Kind() == reflect.Ptr {
		return "*" + t.Elem().Name()
	} else {
		return t.Name()
	}
}

Improve acceptance test assertion by printing out error type


package main

// +build linux darwin

import (
	"errors"

	"github.com/koding/klient/cmd/klientctl/util"
)

// AdminRequired parses through an arg list and requires an admin (sudo)
// for the specified commands.
//
// Note that if the command is required, *and* we failed to get admin
// permission information, let the user run the command anyway.
// Better UX than failing for a possible non-issue.
func AdminRequired(args, reqs []string, p *util.Permissions) error {
	// Ignore the permErr in the beginning. If the arg command
	isAdmin, permErr := p.IsAdmin()

	// If the user is admin, any admin requiring command is already
	// satisfied.
	if isAdmin {
		return nil
	}

	// At the moment, we're only checking the first level of commands.
	// Subcommands are ignored.
	if len(args) < 2 {
		return nil
	}

	c := args[1]

	var err error
	for _, r := range reqs {
		if c == r {
			// Use sudo terminology, for unix
			err = errors.New("Command requires sudo")
		}
	}

	// If the command is required, *and* we failed to get admin permission
	// information, let the user run the command anyway. Better UX than
	// failing for a possible non-issue.
	if err != nil && permErr != nil {
		return nil
	}

	return err
}

package main

// +build linux darwin

import (
	"errors"

	"github.com/koding/klient/cmd/klientctl/util"
)

// AdminRequired parses through an arg list and requires an admin (sudo)
// for the specified commands.
//
// Note that if the command is required, *and* we failed to get admin
// permission information, let the user run the command anyway.
// Better UX than failing for a possible non-issue.
func AdminRequired(args, reqs []string, p *util.Permissions) error {
	// Ignore the permErr in the beginning. If the arg command
	isAdmin, permErr := p.IsAdmin()

	// If the user is admin, any admin requiring command is already
	// satisfied.
	if isAdmin {
		return nil
	}

	// At the moment, we're only checking the first level of commands.
	// Subcommands are ignored.
	if len(args) < 2 {
		return nil
	}

	c := args[1]

	var err error
	for _, r := range reqs {
		if c == r {
			// Use sudo terminology, for unix
			err = errors.New("Command requires sudo")
			break
		}
	}

	// If the command is required, *and* we failed to get admin permission
	// information, let the user run the command anyway. Better UX than
	// failing for a possible non-issue.
	if err != nil && permErr != nil {
		return nil
	}

	return err
}

Break from loop if requirement is found


package gomposer

import (
    "os"

    "encoding/json"
)

type Reader interface {
	Read(filename string) *Version
}

type PackageReader struct {
}

func (pr PackageReader) Read(filename string) (*Version, error) {

    buf, err := os.Open(filename)

    if err != nil {
        return nil, err
    }

    output := &Version{}

    json.NewDecoder(buf).Decode(output)

	return output, nil
}

Refactor dependency resolver + add test for later on


package models

import (
	"github.com/herald-it/goncord/utils"

	"gopkg.in/yaml.v2"

	"io/ioutil"
)

type Setting struct {
	Database struct {
		Host       string
		DbName     string
		TokenTable string
		UserTable  string
	}
}

var Set Setting

func LoadSettings() {
	text, err := ioutil.ReadFile("./settings.yml")
	utils.LogError(err)

	err = yaml.Unmarshal(text, &Set)
	utils.LogError(err)
}

package models

import (
	"github.com/herald-it/goncord/utils"

	"gopkg.in/yaml.v2"

	"io/ioutil"
)

type Setting struct {
	Database struct {
		Host       string
		DbName     string
		TokenTable string
		UserTable  string
	}
}

var Set Setting

func LoadSettings() error {
	text, err := ioutil.ReadFile("./settings.yml")
	if err != nil {
		return err
	}

	if err = yaml.Unmarshal(text, &Set); err != nil {
		return err
	}

	return nil
}

Add returned value from LoadSettings method.


package compare_test

import (
	"testing"

	"github.com/xgfone/go-tools/compare"
)

func TestCompare(t *testing.T) {
	v1 := []uint16{1, 2, 4}
	v2 := []uint16{1, 2, 3}
	if !compare.GT(v1, v2) {
		t.Fail()
	}

	if !compare.LT(v2, v1) {
		t.Fail()
	}

	if compare.EQ(v1, v2) {
		t.Fail()
	}

	if !compare.EQ([]int{1, 2, 3}, []int{1, 2, 3}) {
		t.Fail()
	}
}

package compare_test

import (
	"testing"

	"github.com/xgfone/go-tools/compare"
)

func TestCompare(t *testing.T) {
	v1 := []uint16{1, 2, 4}
	v2 := []uint16{1, 2, 3}
	if !compare.GT(v1, v2) {
		t.Fail()
	}

	if !compare.LT(v2, v1) {
		t.Fail()
	}

	if compare.EQ(v1, v2) {
		t.Fail()
	}

	if !compare.EQ([]int{1, 2, 3}, []int{1, 2, 3}) {
		t.Fail()
	}

	if compare.LT([]int{1, 2, 3}, []int{1, 2, 3}) {
		t.Fail()
	}
}

Add the test for compare


package dockerguard

type Container struct {
	Id       string
	Hostname string
}

package dockerguard

type DockerInfo struct {
	Containers         int         `json:"Containers"`
	Debug              int         `json:"Debug"`
	DockerRootDir      string      `json:"DockerRootDir"`
	Driver             string      `json:"Driver"`
	DriverStatus       [][]string  `json:"DriverStatus"`
	ExecutionDriver    string      `json:"ExecutionDriver"`
	ID                 string      `json:"ID"`
	IPv4Forwarding     int         `json:"IPv4Forwarding"`
	Images             int         `json:"Images"`
	IndexServerAddress string      `json:"IndexServerAddress"`
	InitPath           string      `json:"InitPath"`
	InitSha1           string      `json:"InitSha1"`
	KernelVersion      string      `json:"KernelVersion"`
	Labels             interface{} `json:"Labels"`
	MemTotal           int         `json:"MemTotal"`
	MemoryLimit        int         `json:"MemoryLimit"`
	NCPU               int         `json:"NCPU"`
	NEventsListener    int         `json:"NEventsListener"`
	NFd                int         `json:"NFd"`
	NGoroutines        int         `json:"NGoroutines"`
	Name               string      `json:"Name"`
	OperatingSystem    string      `json:"OperatingSystem"`
	RegistryConfig     struct {
		IndexConfigs struct {
			Docker_io struct {
				Mirrors  interface{} `json:"Mirrors"`
				Name     string      `json:"Name"`
				Official bool        `json:"Official"`
				Secure   bool        `json:"Secure"`
			} `json:"docker.io"`
		} `json:"IndexConfigs"`
		InsecureRegistryCIDRs []string `json:"InsecureRegistryCIDRs"`
	} `json:"RegistryConfig"`
	SwapLimit  int    `json:"SwapLimit"`
	SystemTime string `json:"SystemTime"`
}

type DockerVersion struct {
	APIVersion    string `json:"ApiVersion"`
	Arch          string `json:"Arch"`
	Experimental  bool   `json:"Experimental"`
	GitCommit     string `json:"GitCommit"`
	GoVersion     string `json:"GoVersion"`
	KernelVersion string `json:"KernelVersion"`
	Os            string `json:"Os"`
	Version       string `json:"Version"`
}

Add DockerInfo & DockerVersion struct


package osversion

const (
	// RS1 (version 1607, codename "Redstone 1") corresponds to Windows Server
	// 2016 (ltsc2016) and Windows 10 (Anniversary Update).
	RS1 = 14393

	// RS2 (version 1703, codename "Redstone 2") was a client-only update, and
	// corresponds to Windows 10 (Creators Update).
	RS2 = 15063

	// RS3 (version 1709, codename "Redstone 3") corresponds to Windows Server
	// 1709 (Semi-Annual Channel (SAC)), and Windows 10 (Fall Creators Update).
	RS3 = 16299

	// RS4 (version 1803, codename "Redstone 4") corresponds to Windows Server
	// 1809 (Semi-Annual Channel (SAC)), and Windows 10 (April 2018 Update).
	RS4 = 17134

	// RS5 (version 1809, codename "Redstone 5") corresponds to Windows Server
	// 2019 (ltsc2019), and Windows 10 (October 2018 Update).
	RS5 = 17763
)

package osversion

const (
	// RS1 (version 1607, codename "Redstone 1") corresponds to Windows Server
	// 2016 (ltsc2016) and Windows 10 (Anniversary Update).
	RS1 = 14393

	// RS2 (version 1703, codename "Redstone 2") was a client-only update, and
	// corresponds to Windows 10 (Creators Update).
	RS2 = 15063

	// RS3 (version 1709, codename "Redstone 3") corresponds to Windows Server
	// 1709 (Semi-Annual Channel (SAC)), and Windows 10 (Fall Creators Update).
	RS3 = 16299

	// RS4 (version 1803, codename "Redstone 4") corresponds to Windows Server
	// 1803 (Semi-Annual Channel (SAC)), and Windows 10 (April 2018 Update).
	RS4 = 17134

	// RS5 (version 1809, codename "Redstone 5") corresponds to Windows Server
	// 2019 (ltsc2019), and Windows 10 (October 2018 Update).
	RS5 = 17763
)

Fix Windows Server version for RS4 in comment


package flagparse

import (
	"fmt"
	"os"
	"path"
)

// ArgumentParser is a struct for parsing command line strings
type ArgumentParser struct {
	prog string
}

// NewArgumentParser returns new ArgumentParser pointer
func NewArgumentParser(prog string) *ArgumentParser {
	ap := &ArgumentParser{}
	if prog == "" {
		prog = path.Base(os.Args[0])
	}
	ap.prog = prog
	return ap
}

func (ap *ArgumentParser) ParseArgs(args, namespace string) {
	fmt.Printf("usage: %s [-h]\n", ap.prog)
	fmt.Println(`
optional arguments:
  -h, --help  show this help message and exit`)
}

package flagparse

import (
	"fmt"
	"os"
	"path"
)

// ArgumentParser is a struct for parsing command line strings
type ArgumentParser struct {
	prog string
}

// NewArgumentParser returns new ArgumentParser pointer
func NewArgumentParser(prog string) *ArgumentParser {
	ap := &ArgumentParser{}
	if prog == "" {
		prog = path.Base(os.Args[0])
	}
	ap.prog = prog
	return ap
}

func (ap *ArgumentParser) ParseArgs(args, namespace string) {
	var argList []string
	if args == "" {
		argList = os.Args[1:]
	}
	fmt.Printf("usage: %s [-h]\n", ap.prog)

	if 0 < len(argList) && (argList[0] == "-h" || argList[0] == "--help") {
		fmt.Println(`
optional arguments:
  -h, --help  show this help message and exit`)
	} else {
		fmt.Printf("%s: error: unrecognized arguments %s\n", ap.prog, argList[0])
	}
}

Print error message when receive unrecogonized arguments.


package formats

import (
	"fmt"

	"github.com/anaminus/rbxmk"
)

// registry contains registered Formats.
var registry []func() rbxmk.Format

// register registers a Format to be returned by All.
func register(f func() rbxmk.Format) {
	registry = append(registry, f)
}

// All returns a list of Formats defined in the package.
func All() []func() rbxmk.Format {
	return registry
}

// cannotEncode returns an error indicating that v cannot be encoded.
func cannotEncode(v interface{}) error {
	return fmt.Errorf("cannot encode %T", v)
}

package formats

import (
	"fmt"

	"github.com/anaminus/rbxmk"
	"github.com/robloxapi/types"
)

// registry contains registered Formats.
var registry []func() rbxmk.Format

// register registers a Format to be returned by All.
func register(f func() rbxmk.Format) {
	registry = append(registry, f)
}

// All returns a list of Formats defined in the package.
func All() []func() rbxmk.Format {
	return registry
}

// cannotEncode returns an error indicating that v cannot be encoded.
func cannotEncode(v interface{}) error {
	if v, ok := v.(types.Value); ok {
		return fmt.Errorf("cannot encode %s", v.Type())
	}
	return fmt.Errorf("cannot encode %T", v)
}

Use Type method in error message, if possible.


package databath

import ()

type QueryConditions struct {
	collection string
	where      []QueryCondition
	pk         *uint64
	fieldset   *string
	limit      *int64
	filter     *map[string]interface{}
	offset     *int64
	sort       []*QuerySort
	search     map[string]string
}

type QueryCondition interface {
	GetConditionString(q *Query) (string, []interface{}, bool, error)
}

type QuerySort struct {
	Direction int32  `json:"direction"`
	FieldName string `json:"fieldName"`
}

type QueryConditionString struct {
	Str        string // No JSON. This CANNOT be exposed to the user, Utility Only.
	Parameters []interface{}
}

func (qc *QueryConditionString) GetConditionString(q *Query) (string, []interface{}, bool, error) {
	return "(" + qc.Str + ")", qc.Parameters, false, nil
}

func GetMinimalQueryConditions(collectionName string, fieldset string) *QueryConditions {
	qc := QueryConditions{
		collection: collectionName,
		where:      make([]QueryCondition, 0, 0),
		fieldset:   &fieldset,
	}
	return &qc
}

package databath

import ()

type QueryConditions struct {
	collection string
	where      []QueryCondition
	pk         *uint64
	fieldset   *string
	limit      *int64
	filter     *map[string]interface{}
	offset     *int64
	sort       []*QuerySort
	search     map[string]string
}

func (qc *QueryConditions) CollectionName() string {
	return qc.collection
}

func (qc *QueryConditions) AndWhere(extraCondition QueryCondition) {
	qc.where = append(qc.where, extraCondition)
}

type QueryCondition interface {
	GetConditionString(q *Query) (string, []interface{}, bool, error)
}

type QuerySort struct {
	Direction int32  `json:"direction"`
	FieldName string `json:"fieldName"`
}

type QueryConditionString struct {
	Str        string // No JSON. This CANNOT be exposed to the user, Utility Only.
	Parameters []interface{}
}

func (qc *QueryConditionString) GetConditionString(q *Query) (string, []interface{}, bool, error) {
	return "(" + qc.Str + ")", qc.Parameters, false, nil
}

func GetMinimalQueryConditions(collectionName string, fieldset string) *QueryConditions {
	qc := QueryConditions{
		collection: collectionName,
		where:      make([]QueryCondition, 0, 0),
		fieldset:   &fieldset,
	}
	return &qc
}

Add getters for query things (BM Portal)


package assert

import (
	"fmt"
	"strings"
)

type Line []string

func (line Line) String() string {
	return strings.Join(line, ", ")
}

type Lines []Line

func SliceContains(actual []string, expected Lines, msgAndArgs ...interface{}) bool {
	expectedIndex := 0
	for _, actualValue := range actual {
		allStringsFound := true
		for _, expectedValue := range expected[expectedIndex] {
			allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue))
		}

		if allStringsFound {
			expectedIndex++
			if expectedIndex == len(expected) {
				return true
			}
		}
	}
	return Fail(fmt.Sprintf("\"%s\" not found", expected[expectedIndex]), msgAndArgs...)
}

func SliceDoesNotContain(actual []string, expected Lines, msgAndArgs ...interface{}) bool {
	for i, actualValue := range actual {
		for _, expectedLine := range expected {
			allStringsFound := true
			for _, expectedValue := range expectedLine {
				allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue))
			}
			if allStringsFound {
				return Fail(fmt.Sprintf("\"%s\" found on line %d", expectedLine, i), msgAndArgs...)
			}
		}
	}
	return true
}

package assert

import (
	"fmt"
	"strings"
)

type Line []string

func (line Line) String() string {
	return strings.Join(line, ", ")
}

type Lines []Line

func SliceContains(actual Line, expected Lines, msgAndArgs ...interface{}) bool {
	expectedIndex := 0
	for _, actualValue := range actual {
		allStringsFound := true
		for _, expectedValue := range expected[expectedIndex] {
			allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue))
		}

		if allStringsFound {
			expectedIndex++
			if expectedIndex == len(expected) {
				return true
			}
		}
	}
	return Fail(fmt.Sprintf("\"%s\" not found in actual:\n'%s'\n", expected[expectedIndex], actual), msgAndArgs...)
}

func SliceDoesNotContain(actual Line, expected Lines, msgAndArgs ...interface{}) bool {
	for i, actualValue := range actual {
		for _, expectedLine := range expected {
			allStringsFound := true
			for _, expectedValue := range expectedLine {
				allStringsFound = allStringsFound && strings.Contains(strings.ToLower(actualValue), strings.ToLower(expectedValue))
			}
			if allStringsFound {
				return Fail(fmt.Sprintf("\"%s\" found on line %d", expectedLine, i), msgAndArgs...)
			}
		}
	}
	return true
}

Improve error message for SliceContains


package main

import "testing"

func TestHandleConfigFile(t *testing.T) {

	if _, err := HandleConfigFile(""); err == nil {
		t.FailNow()
	}

	// Depends on default config being avaiable and correct (which is nice!)
	if _, err := HandleConfigFile("config.yaml"); err != nil {
		t.FailNow()
	}

}

Add test for handling config files.


package main

import (
	"fmt"

	"github.com/pgombola/knowmads/client"
)

func main() {
	nodes := client.Status()
	for _, node := range nodes {
		fmt.Printf("ID=%v;Name=%v;Drain=%v\n", node.ID, node.Name, node.Drain)
	}
}

package main

import (
	"fmt"

	"github.com/pgombola/gomad/client"
)

func main() {
	nodes := client.Status()
	for _, node := range nodes {
		fmt.Printf("ID=%v;Name=%v;Drain=%v\n", node.ID, node.Name, node.Drain)
	}
}

Change name of package to 'gomad'


package scoring

import (
	"fmt"
	"math"
	"time"
)

// A point of reference Score.Update and Score.Relevance use to reference the
// current time. It is used in testing, so we always have the same current
// time. This is okay for this programs as it won't run for long.
var Now time.Time

// Represents a weight of a score and the age of it.
type Score struct {
	Weight int64
	Age    time.Time
}

// Update the weight and age of the current score.
func (s *Score) Update() {
	s.Weight++
	s.Age = Now
}

// Relevance of a score is the difference between the current time and when the
// score was last updated.
func (s *Score) Relevance() time.Duration {
	return Now.Sub(s.Age)
}

// Calculate the final score from the score weight and the age.
func (s *Score) Calculate() float64 {
	return float64(s.Weight) * math.Log(float64(s.Relevance()))
}

// Calculate the final score from the score weight and the age.
func (s *Score) String() string {
	return fmt.Sprintf("{%s %s}", s.Weight, s.Age)
}

// Create a new score object with default weight of 1 and age set to now.
func NewScore() *Score {
	return &Score{1, Now}
}

func init() {
	Now = time.Now()
}

package scoring

import (
	"fmt"
	"math"
	"time"
)

// A point of reference Score.Update and Score.Relevance use to reference the
// current time. It is used in testing, so we always have the same current
// time. This is okay for this programs as it won't run for long.
var Now time.Time

// Represents a weight of a score and the age of it.
type Score struct {
	Weight int64
	Age    time.Time
}

// Update the weight and age of the current score.
func (s *Score) Update() {
	s.Weight++
	s.Age = Now
}

// Relevance of a score is the difference between the current time and when the
// score was last updated.
func (s *Score) Relevance() float64 {
	return float64(s.Age.Unix()) / float64(Now.Unix())
}

// Calculate the final score from the score weight and the age.
func (s *Score) Calculate() float64 {
	return float64(s.Weight) * math.Log(s.Relevance())
}

// Calculate the final score from the score weight and the age.
func (s *Score) String() string {
	return fmt.Sprintf("{%s %s}", s.Weight, s.Age)
}

// Create a new score object with default weight of 1 and age set to now.
func NewScore() *Score {
	return &Score{1, Now}
}

func init() {
	Now = time.Now()
}

Make sure s.Relevance is normalized (0, 1)


package ocspd

import (
	"reflect"
	"testing"
)

func TestParsePEM(t *testing.T) {
	for _, tt := range []string{"testdata/cert_only", "testdata/full"} {
		cert, issuer, err := ParsePEMCertificateBundle(tt)
		if err != nil {
			t.Fatal(err)
		}
		if cert.SerialNumber.Uint64() != 4455460921000457498 {
			t.Error("failed")
		}
		if issuer.SerialNumber.Uint64() != 146051 {
			t.Error("failed")
		}
		if !reflect.DeepEqual(cert.Issuer, issuer.Subject) {
			t.Error("failed")
		}
	}
}

package ocspd

import (
	"reflect"
	"testing"
)

func TestParsePEM(t *testing.T) {
	for _, tt := range []string{"testdata/cert_only", "testdata/full"} {
		cert, issuer, err := ParsePEMCertificateBundle(tt)
		if err != nil {
			t.Error(err)
			continue
		}
		if cert.SerialNumber.Uint64() != 4455460921000457498 {
			t.Error("failed")
		}
		if issuer.SerialNumber.Uint64() != 146051 {
			t.Error("failed")
		}
		if !reflect.DeepEqual(cert.Issuer, issuer.Subject) {
			t.Error("failed")
		}
	}
}

Fix TestParsePEM: use t.Error rather than t.Fatal in table-driven test


// Copyright 2014 SteelSeries ApS.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file runs lisp based tests.

package golisp

import (
    . "gopkg.in/check.v1"
    "path/filepath"
)

type LispSuite struct {
}

var _ = Suite(&LispSuite{})

func (s *LispSuite) TestLisp(c *C) {
    files, err := filepath.Glob("tests/*.lsp")
    if err != nil {
        c.Fail()
    }
    for _, f := range files {
        c.Logf("Loading %s\n", f)
        _, err := ProcessFile(f)
        if err != nil {
            c.Logf("Error: %s\n", err)
        }
    }
    PrintTestResults()
}

// Copyright 2014 SteelSeries ApS.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

// This package implements a basic LISP interpretor for embedding in a go program for scripting.
// This file runs lisp based tests.

package golisp

import (
	. "gopkg.in/check.v1"
	"path/filepath"
)

type LispSuite struct {
}

var _ = Suite(&LispSuite{})

func (s *LispSuite) TestLisp(c *C) {
	files, err := filepath.Glob("tests/*.lsp")
	if err != nil {
		c.Fail()
	}
	VerboseTests = false
	for _, f := range files {
		c.Logf("Loading %s\n", f)
		_, err := ProcessFile(f)
		if err != nil {
			c.Logf("Error: %s\n", err)
		}
	}
	PrintTestResults()
}

Use quiet mode for lisp tests when running go test


// Package httpclient provides an HTTP client with several conveniency
// functions.
//
// This package is cross platform, so it works on both standalone deployments
// as well as on App Engine.
package httpclient

// Package httpclient provides an HTTP client with several conveniency
// functions.
//
// This package is cross platform, so it works on both standalone deployments
// as well as on App Engine.
//
// Also, requests made with an httpclient instance are properly measured
// when profiling an app.
package httpclient

Clarify that this package supports profiling


package ActiveObject

import (
	"sync"
	"testing"
	"time"

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

func TestActiveObject(t *testing.T) {
	var activeObject IActiveObject

	var wait sync.WaitGroup
	wait.Add(1)

	activeObject = NewActiveObjectWithInterval(time.Millisecond * 50)

	counter := 0
	activeObject.SetWorkerFunction(func(param interface{}) {
		counter++

		if counter > 3 {
			wait.Done()
		}
	})

	activeObject.Run(10)

	wait.Wait()

	activeObject.ForceStop()

	time.Sleep(time.Millisecond * 1000)

	assert.Equal(t, counter, 4, "counter is wrong")
}

package ActiveObject

import (
	"sync"
	"testing"
	"time"

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

func TestActiveObject(t *testing.T) {
	var activeObject IActiveObject

	var wait sync.WaitGroup
	wait.Add(1)

	activeObject = NewActiveObjectWithInterval(time.Millisecond * 50)

	counter := 0
	activeObject.SetWorkerFunction(func(param interface{}) {
		assert.Equal(t, param, 20, "param is incorrect")

		counter++

		if counter > 3 {
			wait.Done()
		}
	})

	activeObject.Run(10)

	wait.Wait()

	activeObject.ForceStop()

	time.Sleep(time.Millisecond * 1000)

	assert.Equal(t, counter, 4, "counter is wrong")
}

Make sure the param passed is correct


package main

import (
	"fmt"
	"flag"
	"io/ioutil"
	"os"
	"github.com/robertkrimen/otto"
)

func main() {
	flag.Parse()
	var script []byte
	var err error
	filename := flag.Arg(0)
	if filename == "" || filename == "-" {
		script, err = ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Printf("Can't read stdin: %v\n", err)
			os.Exit(64)
		}
	} else {
		script, err = ioutil.ReadFile(filename)
		if err != nil {
			fmt.Printf("Can't open file \"%v\": %v\n", filename, err)
			os.Exit(64)
		}
	}
	Otto := otto.New()
	_, err = Otto.Run(string(script))
	if err != nil {
		fmt.Println(err)
		os.Exit(64)
	}
}

package main

import (
	"fmt"
	"flag"
	"io/ioutil"
	"os"
	"github.com/robertkrimen/otto"
	"github.com/robertkrimen/otto/underscore"
)

var underscoreFlag *bool = flag.Bool("underscore", true, "Load underscore into the runtime environment")

func main() {
	flag.Parse()
	var script []byte
	var err error
	filename := flag.Arg(0)
	if filename == "" || filename == "-" {
		script, err = ioutil.ReadAll(os.Stdin)
		if err != nil {
			fmt.Printf("Can't read stdin: %v\n", err)
			os.Exit(64)
		}
	} else {
		script, err = ioutil.ReadFile(filename)
		if err != nil {
			fmt.Printf("Can't open file \"%v\": %v\n", filename, err)
			os.Exit(64)
		}
	}
	if !*underscoreFlag {
		underscore.Disable()
	}
	Otto := otto.New()
	_, err = Otto.Run(string(script))
	if err != nil {
		fmt.Println(err)
		os.Exit(64)
	}
}

Add underscore to the commandline


package watch

import etcd "github.com/coreos/etcd/clientv3"

// OpOption is a simple typedef for etcd.OpOption.
type OpOption struct {
	Get   etcd.OpOption
	Watch etcd.OpOption
}

// WithFilterPut discards PUT events from the watcher.
func WithFilterPut() OpOption {
	return OpOption{Watch: etcd.WithFilterPut(), Get: nil}
}

// WithSort specifies the sort to use for the watcher
func WithSort(sortBy etcd.SortTarget, sortOrder etcd.SortOrder) OpOption {
	return OpOption{Get: etcd.WithSort(sortBy, sortOrder), Watch: nil}
}

// WithFilterDelete discards DELETE events from the watcher.
func WithFilterDelete() OpOption {
	return OpOption(etcd.WithFilterDelete())
}

Add delete filter to watch package


package tuikit

import "time"

type ProgressSpinner struct {
	*TextView

	spinRunes []rune
	current   int
}

func NewProgressSpinner() *ProgressSpinner {
	ps := &ProgressSpinner{
		TextView:  NewTextView(),
		spinRunes: []rune{'|', '/', '—', '\\', '|', '/', '—', '\\'},
	}

	go func() {
		l := len(ps.spinRunes)
		for _ = range time.Tick(150 * time.Millisecond) {
			ps.current = (ps.current + 1) % l
			ps.SetText(string(ps.spinRunes[ps.current]))
		}
	}()

	return ps
}

package tuikit

import "time"

type ProgressSpinner struct {
	*TextView

	spinRunes []rune
	current   int
}

func NewProgressSpinner() *ProgressSpinner {
	ps := &ProgressSpinner{
		TextView:  NewTextView(),
		spinRunes: []rune{'|', '/', '—', '\\', '|', '/', '—', '\\'},
	}

	go func() {
		l := len(ps.spinRunes)
		for _ = range time.Tick(110 * time.Millisecond) {
			ps.current = (ps.current + 1) % l
			ps.SetText(string(ps.spinRunes[ps.current]))
		}
	}()

	return ps
}

Adjust ProgressSpinner tick time to 110 ms


package data

import (
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Document struct {
	ID          bson.ObjectId `bson:"_id"`
	ShortId     string        `bson:"short_id"`
	Title       string        `bson:"title"`
	Content     string        `bson:"content"`
	Tags        []string      `bson:"tags"`
	Published   bool          `bson:"publishd"`
	PublishedAt time.Time     `bson:"pushlished_at"`
	AccessToken string        `bson:"access_token"`
	CreatedAt   time.Time     `bson:"created_at"`
	ModifiedAt  time.Time     `bson:"modified_at"`
}

func GetDocument(id bson.ObjectId) (*Document, error) {
	doc := Document{}
	err := sess.DB("").C(documentC).FindId(id).One(&doc)
	if err == mgo.ErrNotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &doc, nil
}

package data

import (
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Document struct {
	ID          bson.ObjectId `bson:"_id"`
	ShortID     string        `bson:"short_id"`
	Title       string        `bson:"title"`
	Content     string        `bson:"content"`
	Tags        []string      `bson:"tags"`
	Published   bool          `bson:"publishd"`
	PublishedAt time.Time     `bson:"pushlished_at"`
	AccessToken string        `bson:"access_token"`
	CreatedAt   time.Time     `bson:"created_at"`
	ModifiedAt  time.Time     `bson:"modified_at"`
}

func GetDocument(id bson.ObjectId) (*Document, error) {
	doc := Document{}
	err := sess.DB("").C(documentC).FindId(id).One(&doc)
	if err == mgo.ErrNotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &doc, nil
}

func (d *Document) Put() error {
	d.ModifiedAt = time.Now()

	if d.ID == "" {
		d.ID = bson.NewObjectId()
		d.CreatedAt = d.ModifiedAt
	}
	_, err := sess.DB("").C(documentC).UpsertId(d.ID, d)
	return err
}

Implement Put for Document struct


package fnlog_test

import (
	"github.com/northbright/fnlog"
	"log"
)

var (
	noTagLog *log.Logger
)

func Example() {
	iLog := fnlog.New("i")
	wLog := fnlog.New("w")
	eLog := fnlog.New("e")

	// Global *log.Logger
	noTagLog = fnlog.New("")

	iLog.Printf("print infos")
	wLog.Printf("print warnnings")
	eLog.Printf("print errors")
	noTagLog.Printf("print messages without tag")

	// Output:
	// 2015/06/09 14:32:59 unit_test.go:14 fnlog_test.Example(): i: print infos
	// 2015/06/09 14:32:59 unit_test.go:15 fnlog_test.Example(): w: print warnnings
	// 2015/06/09 14:32:59 unit_test.go:16 fnlog_test.Example(): e: print errors
	// 2015/06/09 14:32:59 unit_test.go:17 fnlog_test.Example(): print messages without tag
}

package fnlog_test

import (
	"github.com/northbright/fnlog"
	"log"
)

var (
	noTagLog *log.Logger
)

func Example() {
	iLog := fnlog.New("i")
	wLog := fnlog.New("w")
	eLog := fnlog.New("e")

	noTagLog = fnlog.New("")

	iLog.Printf("print infos")
	wLog.Printf("print warnnings")
	eLog.Printf("print errors")
	noTagLog.Printf("print messages without tag")

	// Output:
	// 2015/06/09 14:32:59 unit_test.go:14 fnlog_test.Example(): i: print infos
	// 2015/06/09 14:32:59 unit_test.go:15 fnlog_test.Example(): w: print warnnings
	// 2015/06/09 14:32:59 unit_test.go:16 fnlog_test.Example(): e: print errors
	// 2015/06/09 14:32:59 unit_test.go:17 fnlog_test.Example(): print messages without tag
}

Remove comment to see outputs works in godoc


package async

// import "fmt"

func Waterfall(routines []Routine, callbacks ...Done) {
  l := New()
  l.Multiple(routines...)

  l.RunWaterfall(callbacks...)
}

func (l *List) RunWaterfall(callbacks ...Done) {
  fall := fall(l, callbacks...)
  next := next(l, callbacks...)

  l.Wait.Add(l.Len())

  fall(next)
}

func fall(l *List, callbacks ...Done) func(Done, ...interface{}) {
  return func(next Done, args ...interface{}) {
    e := l.Front()
    _, r := l.Remove(e)

    // Run the first waterfall routine and give it the next function, and
    // any arguments that were provided
    go r(next, args...)
    l.Wait.Wait()
  }
}

func next(l *List, callbacks ...Done) Done {
  fall := fall(l, callbacks...)

  return func(err error, args ...interface{}) {
    next := next(l, callbacks...)

    l.Wait.Done()
    if err != nil || l.Len() == 0 {
      // Just in case it's an error, let's make sure we've cleared
      // all of the sync.WaitGroup waits that we initiated.
      for i := 0; i < l.Len(); i++ {
        l.Wait.Done()
      }

      // Send the results to the callbacks
      for i := 0; i < len(callbacks); i++ {
        callbacks[i](err, args...)
      }
      return
    }

    // Run the next waterfall routine with any arguments that were provided
    fall(next, args...)
    return
  }
}

package async

func Waterfall(routines []Routine, callbacks ...Done) {
  l := New()
  l.Multiple(routines...)

  l.RunWaterfall(callbacks...)
}

func (l *List) RunWaterfall(callbacks ...Done) {
  fall := fall(l, callbacks...)
  next := next(l, callbacks...)

  l.Wait.Add(l.Len())

  fall(next)
}

func fall(l *List, callbacks ...Done) func(Done, ...interface{}) {
  return func(next Done, args ...interface{}) {
    e := l.Front()
    _, r := l.Remove(e)

    // Run the first waterfall routine and give it the next function, and
    // any arguments that were provided
    go r(next, args...)
    l.Wait.Wait()
  }
}

func next(l *List, callbacks ...Done) Done {
  fall := fall(l, callbacks...)

  return func(err error, args ...interface{}) {
    next := next(l, callbacks...)

    l.Wait.Done()
    if err != nil || l.Len() == 0 {
      // Just in case it's an error, let's make sure we've cleared
      // all of the sync.WaitGroup waits that we initiated.
      for i := 0; i < l.Len(); i++ {
        l.Wait.Done()
      }

      // Send the results to the callbacks
      for i := 0; i < len(callbacks); i++ {
        callbacks[i](err, args...)
      }
      return
    }

    // Run the next waterfall routine with any arguments that were provided
    fall(next, args...)
    return
  }
}

Remove commented import that isn't used


//go:build !linux && !freebsd

package tuntap

const flagTruncated = 0

func createInterface(ifPattern string, kind DevKind) (*Interface, error) {
	panic("tuntap: Not implemented on this platform")
}

//go:build !linux && !freebsd

package tuntap

import (
	"net"
)

const flagTruncated = 0

func createInterface(ifPattern string, kind DevKind) (*Interface, error) {
	panic("tuntap: Not implemented on this platform")
}

// IPv6SLAAC enables/disables stateless address auto-configuration (SLAAC) for the interface.
func (t *Interface) IPv6SLAAC(ctrl bool) error {
	panic("tuntap: Not implemented on this platform")
}

// IPv6Forwarding enables/disables ipv6 forwarding for the interface.
func (t *Interface) IPv6Forwarding(ctrl bool) error {
	panic("tuntap: Not implemented on this platform")
}

// IPv6 enables/disable ipv6 for the interface.
func (t *Interface) IPv6(ctrl bool) error {
	panic("tuntap: Not implemented on this platform")
}

// AddAddress adds an IP address to the tunnel interface.
func (t *Interface) AddAddress(ip net.IP, subnet *net.IPNet) error {
	panic("tuntap: Not implemented on this platform")
}

// SetMTU sets the tunnel interface MTU size.
func (t *Interface) SetMTU(mtu int) error {
	panic("tuntap: Not implemented on this platform")
}

// Up sets the tunnel interface to the UP state.
func (t *Interface) Up() error {
	panic("tuntap: Not implemented on this platform")
}

// GetAddrList returns the IP addresses (as bytes) associated with the interface.
func (t *Interface) GetAddrList() ([][]byte, error) {
	panic("tuntap: Not implemented on this platform")
}

Add stubs for non-linux, non-freebsd platforms to fix builds on MacOS.


package dns

import (
	"testing"
)

func TestRadixName(t *testing.T) {
	tests := map[string]string{".": ".",
		"www.miek.nl.": ".nl.miek.www",
		"miek.nl.":     ".nl.miek",
		"mi\\.ek.nl.":  ".nl.mi\\.ek",
		`mi\\.ek.nl.`:  `.nl.ek.mi\\`,
		"":             "."}
	for i, o := range tests {
		t.Logf("%s %v\n", i, SplitLabels(i))
		if x := toRadixName(i); x != o {
			t.Logf("%s should convert to %s, not %s\n", i, o, x)
			t.Fail()
		}
	}
}

func TestInsert(t *testing.T) {
}
func TestRemove(t *testing.T) {
}

package dns

import (
	"testing"
)

func TestRadixName(t *testing.T) {
	tests := map[string]string{".": ".",
		"www.miek.nl.": ".nl.miek.www",
		"miek.nl.":     ".nl.miek",
		"mi\\.ek.nl.":  ".nl.mi\\.ek",
		`mi\\.ek.nl.`:  `.nl.ek.mi\\`,
		"":             "."}
	for i, o := range tests {
		t.Logf("%s %v\n", i, SplitLabels(i))
		if x := toRadixName(i); x != o {
			t.Logf("%s should convert to %s, not %s\n", i, o, x)
			t.Fail()
		}
	}
}

func TestInsert(t *testing.T) {
	z := NewZone("miek.nl.")
	mx, _ := NewRR("foo.miek.nl. MX 10 mx.miek.nl.")
	z.Insert(mx)
	zd, exact := z.Find("foo.miek.nl.")
	if exact != true {
		t.Fail() // insert broken?
	}
}

func TestRemove(t *testing.T) {
	z := NewZone("miek.nl.")
	mx, _ := NewRR("foo.miek.nl. MX 10 mx.miek.nl.")
	z.Insert(mx)
	zd, exact := z.Find("foo.miek.nl.")
	if exact != true {
		t.Fail() // insert broken?
	}
	z.Remove(mx)
	zd, exact = z.Find("foo.miek.nl.")
	if exact != false {
		t.Errorf("zd(%s) exact(%s) still exists", zd, exact) // it should no longer be in the zone
	}
}

Add zone test from Alex Polvi


// Copyright (c) 2016, Janoš Guljaš <janos@resenje.org>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fileServer

import (
	"net/http"
	"os"
	"path"
	"path/filepath"
	"strings"
)

func redirect(w http.ResponseWriter, r *http.Request, location string) {
	if q := r.URL.RawQuery; q != "" {
		location += "?" + q
	}
	w.Header().Set("Location", location)
	w.Header().Set("Cache-Control", "no-cache")
	w.WriteHeader(http.StatusFound)
}

func open(root, name string) (http.File, error) {
	if filepath.Separator != '/' && strings.IndexRune(name, filepath.Separator) >= 0 ||
		strings.Contains(name, "\x00") {
		return nil, errNotFound // invalid character in file path
	}
	if root == "" {
		root = "."
	}
	f, err := os.Open(filepath.Join(root, filepath.FromSlash(path.Clean("/"+name))))
	if err != nil {
		return nil, err
	}
	return f, nil
}

// Copyright (c) 2016, Janoš Guljaš <janos@resenje.org>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package fileServer

import (
	"net/http"
	"os"
	"path"
	"path/filepath"
)

func redirect(w http.ResponseWriter, r *http.Request, location string) {
	if q := r.URL.RawQuery; q != "" {
		location += "?" + q
	}
	w.Header().Set("Location", location)
	w.Header().Set("Cache-Control", "no-cache")
	w.WriteHeader(http.StatusFound)
}

func open(root, name string) (http.File, error) {
	if root == "" {
		root = "."
	}
	return os.Open(filepath.Join(root, filepath.FromSlash(path.Clean("/"+name))))
}

Simplify open function for file server


package system

import (
	"fmt"
	"io/ioutil"
	"strconv"
	"strings"
)

// parseCPUInfo returns a newline-delimited string slice of '/proc/cpuinfo'.
func parseCPUInfo() []string {
	cached, _ := ioutil.ReadFile("/proc/cpuinfo")
	return strings.Split(string(cached), "\n")
}

// parseCPUCount returns the number of CPU cores in the system.
func parseCPUCount(cpuinfo []string) int {
	cores, _ := strconv.Atoi(strings.Fields(cpuinfo[len(cpuinfo) - 18])[3])
	return cores + 1
}

// Model returns the CPU Model
func CPUModel() string {
	modelinfo := strings.Fields(parseCPUInfo()[4])[3:]
	return modelinfo[0] + " " + modelinfo[1]
}

// CPUTemp sets the temperature of the CPU.
func CPUTemp(cputemp *int, done chan bool) {
	*cputemp = getTemperature()
	done <- true
}

// Frequencies sets '*cpufreq' with a string containing all core frequencies.
func CPUFrequencies(cpufreqs *string, done chan bool) {
	*cpufreqs = "Cores:" + getFrequencyString()
	done <- true
}

package system

import (
	"io/ioutil"
	"strconv"
	"strings"
)

// parseCPUInfo returns a newline-delimited string slice of '/proc/cpuinfo'.
func parseCPUInfo() []string {
	cached, _ := ioutil.ReadFile("/proc/cpuinfo")
	return strings.Split(string(cached), "\n")
}

// parseCPUCount returns the number of CPU cores in the system.
func parseCPUCount(cpuinfo []string) int {
	cores, _ := strconv.Atoi(strings.Fields(cpuinfo[len(cpuinfo) - 18])[3])
	return cores + 1
}

// Model returns the CPU Model
func CPUModel() string {
	modelinfo := strings.Fields(parseCPUInfo()[4])[3:]
	return modelinfo[0] + " " + modelinfo[1]
}

// CPUTemp sets the temperature of the CPU.
func CPUTemp(cputemp *int, done chan bool) {
	*cputemp = getTemperature()
	done <- true
}

// Frequencies sets '*cpufreq' with a string containing all core frequencies.
func CPUFrequencies(cpufreqs *string, done chan bool) {
	*cpufreqs = "Cores:" + getFrequencyString()
	done <- true
}

Remove fmt since it's not used


package source

import (
	"github.com/pkg/errors"
	"github.com/dpb587/metalink/repository"
	"github.com/dpb587/metalink/repository/filter"
)

func FilterInMemory(files []repository.RepositoryMetalink, filter filter.Filter) ([]repository.RepositoryMetalink, error) {
	results := []repository.RepositoryMetalink{}

	for _, meta4 := range files {
		matched, err := filter.IsTrue(meta4)
		if err != nil {
			return nil, errors.Wrap(err, "Matching metalink")
		} else if !matched {
			continue
		}

		results = append(results, meta4)
	}

	return results, nil
}

package source

import (
	"github.com/dpb587/metalink/repository"
	"github.com/dpb587/metalink/repository/filter"
	"github.com/pkg/errors"
)

func FilterInMemory(files []repository.RepositoryMetalink, filter filter.Filter) ([]repository.RepositoryMetalink, error) {
	results := []repository.RepositoryMetalink{}

	for _, meta4 := range files {
		matched, err := filter.IsTrue(meta4)
		if err != nil {
			return nil, errors.Wrapf(err, "Matching metalink %s", meta4.Reference.Path)
		} else if !matched {
			continue
		}

		results = append(results, meta4)
	}

	return results, nil
}

Include meta4 path in filtering errors


package integration_test

import (
	"path/filepath"

	"github.com/cloudfoundry/libbuildpack/cutlass"

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

var _ = Describe("deploy a staticfile app", func() {
	var app *cutlass.App
	AfterEach(func() {
		if app != nil {
			app.Destroy()
		}
		app = nil
	})

	BeforeEach(func() {
		app = cutlass.New(filepath.Join(bpDir, "fixtures", "reverse_proxy"))
		PushAppAndConfirm(app)
	})

	It("proxies", func() {
		Expect(app.GetBody("/intl/en/policies")).To(ContainSubstring("Welcome to the Google Privacy Policy"))

		By("hides the nginx.conf file", func() {
			Expect(app.GetBody("/nginx.conf")).To(ContainSubstring("<title>404 Not Found</title>"))
		})
	})
})

package integration_test

import (
	"path/filepath"

	"github.com/cloudfoundry/libbuildpack/cutlass"

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

var _ = Describe("deploy a staticfile app", func() {
	var app *cutlass.App
	AfterEach(func() {
		if app != nil {
			app.Destroy()
		}
		app = nil
	})

	BeforeEach(func() {
		app = cutlass.New(filepath.Join(bpDir, "fixtures", "reverse_proxy"))
		PushAppAndConfirm(app)
	})

	It("proxies", func() {
		Expect(app.GetBody("/intl/en/policies")).To(ContainSubstring("Google Privacy Policy"))

		By("hides the nginx.conf file", func() {
			Expect(app.GetBody("/nginx.conf")).To(ContainSubstring("<title>404 Not Found</title>"))
		})
	})
})

Fix integration tests due to Google Privacy Policy content changes.


/*
Copyright IBM Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package ccintf

//This package defines the interfaces that support runtime and
//communication between chaincode and peer (chaincode support).
//Currently inproccontroller uses it. dockercontroller does not.

import (
	"github.com/hyperledger/fabric/core/chaincode/persistence/intf"
	pb "github.com/hyperledger/fabric/protos/peer"
)

// ChaincodeStream interface for stream between Peer and chaincode instance.
type ChaincodeStream interface {
	Send(*pb.ChaincodeMessage) error
	Recv() (*pb.ChaincodeMessage, error)
}

// CCSupport must be implemented by the chaincode support side in peer
// (such as chaincode_support)
type CCSupport interface {
	HandleChaincodeStream(ChaincodeStream) error
}

// CCID encapsulates chaincode ID
type CCID string

// String returns a string version of the chaincode ID
func (c CCID) String() string {
	return string(c)
}

// New returns a chaincode ID given the supplied package ID
func New(packageID persistence.PackageID) CCID {
	return CCID(packageID.String())
}

/*
Copyright IBM Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package ccintf

//This package defines the interfaces that support runtime and
//communication between chaincode and peer (chaincode support).
//Currently inproccontroller uses it. dockercontroller does not.

import (
	persistence "github.com/hyperledger/fabric/core/chaincode/persistence/intf"
	pb "github.com/hyperledger/fabric/protos/peer"
)

// ChaincodeStream interface for stream between Peer and chaincode instance.
type ChaincodeStream interface {
	Send(*pb.ChaincodeMessage) error
	Recv() (*pb.ChaincodeMessage, error)
}

// CCSupport must be implemented by the chaincode support side in peer
// (such as chaincode_support)
type CCSupport interface {
	HandleChaincodeStream(ChaincodeStream) error
}

// CCID encapsulates chaincode ID
type CCID string

// String returns a string version of the chaincode ID
func (c CCID) String() string {
	return string(c)
}

// New returns a chaincode ID given the supplied package ID
func New(packageID persistence.PackageID) CCID {
	return CCID(packageID.String())
}

Fix goimport errors in core/container


package main

import (
	"time"

	log "github.com/Sirupsen/logrus"
	logx "github.com/cerana/cerana/pkg/logrusx"
	"github.com/cerana/cerana/provider"
	"github.com/cerana/cerana/providers/clusterconf"
	flag "github.com/spf13/pflag"
)

func main() {
	log.SetFormatter(&logx.MistifyFormatter{})

	config := clusterconf.NewConfig(nil, nil)
	flag.DurationP("dataset-ttl", "d", time.Minute, "ttl for dataset usage heartbeats")
	flag.DurationP("bundle-ttl", "b", time.Minute, "ttl for bundle usage heartbeats")
	flag.DurationP("node-ttl", "o", time.Minute, "ttl for node heartbeats")
	flag.Parse()

	dieOnError(config.LoadConfig())
	dieOnError(config.SetupLogging())

	server, err := provider.NewServer(config.Config)
	dieOnError(err)
	c := clusterconf.New(config, server.Tracker())
	dieOnError(err)
	c.RegisterTasks(server)

	if len(server.RegisteredTasks()) != 0 {
		dieOnError(server.Start())
		server.StopOnSignal()
	} else {
		log.Warn("no registered tasks, exiting")
	}
}

func dieOnError(err error) {
	if err != nil {
		log.Fatal("encountered an error during startup")
	}
}

package main

import (
	"time"

	log "github.com/Sirupsen/logrus"
	logx "github.com/cerana/cerana/pkg/logrusx"
	"github.com/cerana/cerana/provider"
	"github.com/cerana/cerana/providers/clusterconf"
	flag "github.com/spf13/pflag"
)

func main() {
	log.SetFormatter(&logx.JSONFormatter{})

	config := clusterconf.NewConfig(nil, nil)
	flag.DurationP("dataset-ttl", "d", time.Minute, "ttl for dataset usage heartbeats")
	flag.DurationP("bundle-ttl", "b", time.Minute, "ttl for bundle usage heartbeats")
	flag.DurationP("node-ttl", "o", time.Minute, "ttl for node heartbeats")
	flag.Parse()

	dieOnError(config.LoadConfig())
	dieOnError(config.SetupLogging())

	server, err := provider.NewServer(config.Config)
	dieOnError(err)
	c := clusterconf.New(config, server.Tracker())
	dieOnError(err)
	c.RegisterTasks(server)

	if len(server.RegisteredTasks()) != 0 {
		dieOnError(server.Start())
		server.StopOnSignal()
	} else {
		log.Warn("no registered tasks, exiting")
	}
}

func dieOnError(err error) {
	if err != nil {
		log.Fatal("encountered an error during startup")
	}
}

Update clusterconfig-provider binary to use logrusx.JSONFormatter


package main

import (
	"io/ioutil"
	"os"
	"testing"

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

func TestResizeImage(t *testing.T) {
	tmpfile, err := ioutil.TempFile("", "resized_image")
	assert.NoError(t, err)
	defer os.Remove(tmpfile.Name())

	err = resizeImage(nil, "./content/images/about/avatar.jpg", tmpfile.Name(), 100)
	assert.NoError(t, err)
}

func TestResizeImage_NoMozJPEG(t *testing.T) {
	if conf.MozJPEGBin == "" {
		return
	}

	oldMozJPEGBin := conf.MozJPEGBin
	defer func() {
		conf.MozJPEGBin = oldMozJPEGBin
	}()
	conf.MozJPEGBin = ""

	tmpfile, err := ioutil.TempFile("", "resized_image")
	assert.NoError(t, err)
	defer os.Remove(tmpfile.Name())

	err = resizeImage(nil, "./content/images/about/avatar.jpg", tmpfile.Name(), 100)
	assert.NoError(t, err)
}

Add test for without MozJPEG


package of10

import "net"

type Match struct {
	Wildcards    uint32
	InPort       PortNumber
	EthSrc       net.HardwareAddr
	EthDst       net.HardwareAddr
	VlanId       VlanId
	VlanPriority VlanPriority
	pad1         [1]uint8
	EtherType    EtherType
	IpTos        Dscp
	IpProtocol   ProtocolNumber
	pad2         [2]uint8
	IpSrc        net.IP
	IpDst        net.IP
	NetworkSrc   NetworkPort
	NetworkDst   NetworkPort
}

type VlanId uint16
type VlanPriority uint8
type EtherType uint16
type Dscp uint8
type ProtocolNumber uint8
type NetworkPort uint16

package of10

import "net"

type Match struct {
	Wildcards    Wildcard
	InPort       PortNumber
	EthSrc       net.HardwareAddr
	EthDst       net.HardwareAddr
	VlanId       VlanId
	VlanPriority VlanPriority
	pad1         [1]uint8
	EtherType    EtherType
	IpTos        Dscp
	IpProtocol   ProtocolNumber
	pad2         [2]uint8
	IpSrc        net.IP
	IpDst        net.IP
	NetworkSrc   NetworkPort
	NetworkDst   NetworkPort
}

type Wildcard uint32
type VlanId uint16
type VlanPriority uint8
type EtherType uint16
type Dscp uint8
type ProtocolNumber uint8
type NetworkPort uint16

const (
	OFPFW_IN_PORT Wildcard = 1 << iota
	OFPFW_DL_VLAN
	OFPFW_DL_SRC
	OFPFW_DL_DST
	OFPFW_DL_TYPE
	OFPFW_NW_PROTO
	OFPFW_TP_SRC
	OFPFW_TP_DST

	OFPFW_NW_SRC_SHIFT Wildcard = 8
	OFPFW_NW_SRC_BITS  Wildcard = 6
	OFPFW_NW_SRC_MASK  Wildcard = ((1 << OFPFW_NW_SRC_BITS) - 1) << OFPFW_NW_SRC_SHIFT

	OFPFW_NW_DST_SHIFT Wildcard = 16
	OFPFW_NW_DST_BITS  Wildcard = 6
	OFPFW_NW_DST_MASK  Wildcard = ((1 << OFPFW_NW_DST_BITS) - 1) << OFPFW_NW_DST_SHIFT
	OFPFW_NW_DST_ALL   Wildcard = 32 << OFPFW_NW_DST_SHIFT

	OFPFW_DL_VLAN_PCP Wildcard = 1 << 20
	OFPFW_NW_TOS      Wildcard = 1 << 21

	OFPFW_ALL Wildcard = ((1 << 22) - 1)
)

Declare constant related to wildcard


package orm

import (
	"gnd.la/orm/query"
)

// Interface is implemented by both Orm
// and Transaction. This allows functions to
// receive an orm.Interface parameter and work
// with both transactions and outside of them.
// See the Orm documentation to find what each
// method does.
type Interface interface {
	Table(t *Table) *Query
	Exists(t *Table, q query.Q) (bool, error)
	Count(t *Table, q query.Q) (uint64, error)
	Query(q query.Q) *Query
	One(q query.Q, out ...interface{}) (bool, error)
	MustOne(q query.Q, out ...interface{}) bool
	All() *Query
	Insert(obj interface{}) (Result, error)
	MustInsert(obj interface{}) Result
	Update(q query.Q, obj interface{}) (Result, error)
	MustUpdate(q query.Q, obj interface{}) Result
	Upsert(q query.Q, obj interface{}) (Result, error)
	MustUpsert(q query.Q, obj interface{}) Result
	Save(obj interface{}) (Result, error)
	MustSave(obj interface{}) Result
	DeleteFrom(t *Table, q query.Q) (Result, error)
	Delete(obj interface{}) error
	MustDelete(obj interface{})
	Begin() (*Tx, error)
}

package orm

import (
	"reflect"

	"gnd.la/orm/operation"
	"gnd.la/orm/query"
)

// Interface is implemented by both Orm
// and Transaction. This allows functions to
// receive an orm.Interface parameter and work
// with both transactions and outside of them.
// See the Orm documentation to find what each
// method does.
type Interface interface {
	TypeTable(reflect.Type) *Table
	Table(t *Table) *Query
	Exists(t *Table, q query.Q) (bool, error)
	Count(t *Table, q query.Q) (uint64, error)
	Query(q query.Q) *Query
	One(q query.Q, out ...interface{}) (bool, error)
	MustOne(q query.Q, out ...interface{}) bool
	All() *Query
	Insert(obj interface{}) (Result, error)
	MustInsert(obj interface{}) Result
	Update(q query.Q, obj interface{}) (Result, error)
	MustUpdate(q query.Q, obj interface{}) Result
	Upsert(q query.Q, obj interface{}) (Result, error)
	MustUpsert(q query.Q, obj interface{}) Result
	Save(obj interface{}) (Result, error)
	MustSave(obj interface{}) Result
	DeleteFrom(t *Table, q query.Q) (Result, error)
	Delete(obj interface{}) error
	MustDelete(obj interface{})
	Begin() (*Tx, error)
	Operate(*Table, query.Q, ...*operation.Operation) (Result, error)
	MustOperate(*Table, query.Q, ...*operation.Operation) Result
}

Add TypeTable(), Operate() and MustOperate() to orm.Interface


// Copyright 2016 Hajime Hoshi
//
// 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.

// +build !js
// +build !windows

package clock

import (
	"time"
)

func now() int64 {
	// time.Now() is monotonic:
	// https://golang.org/pkg/time/#hdr-Monotonic_Clocks
	return time.Now().UnixNano()
}

// Copyright 2016 Hajime Hoshi
//
// 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.

// +build !js
// +build !windows

package clock

import (
	"time"
)

var initTime = time.Now()

func now() int64 {
	// time.Since() returns monotonic timer difference (#875):
	// https://golang.org/pkg/time/#hdr-Monotonic_Clocks
	return int64(time.Since(initTime))
}

Use time.Since for monotonic timer


/*
Package aetest provides an API for running dev_appserver for use in tests.

An example test file:

	package foo_test

	import (
		"testing"

		"google.golang.org/appengine/memcache"
		"google.golang.org/appengine/aetest"
	)

	func TestFoo(t *testing.T) {
		ctx, done, err := aetest.NewContext(nil)
		if err != nil {
			t.Fatal(err)
		}
		defer done()

		it := &memcache.Item{
			Key:   "some-key",
			Value: []byte("some-value"),
		}
		err = memcache.Set(ctx, it)
		if err != nil {
			t.Fatalf("Set err: %v", err)
		}
		it, err = memcache.Get(ctx, "some-key")
		if err != nil {
			t.Fatalf("Get err: %v; want no error", err)
		}
		if g, w := string(it.Value), "some-value" ; g != w {
			t.Errorf("retrieved Item.Value = %q, want %q", g, w)
		}
	}

The environment variable APPENGINE_DEV_APPSERVER specifies the location of the
dev_appserver.py executable to use. If unset, the system PATH is consulted.
*/
package aetest

/*
Package aetest provides an API for running dev_appserver for use in tests.

An example test file:

	package foo_test

	import (
		"testing"

		"google.golang.org/appengine/memcache"
		"google.golang.org/appengine/aetest"
	)

	func TestFoo(t *testing.T) {
		ctx, done, err := aetest.NewContext()
		if err != nil {
			t.Fatal(err)
		}
		defer done()

		it := &memcache.Item{
			Key:   "some-key",
			Value: []byte("some-value"),
		}
		err = memcache.Set(ctx, it)
		if err != nil {
			t.Fatalf("Set err: %v", err)
		}
		it, err = memcache.Get(ctx, "some-key")
		if err != nil {
			t.Fatalf("Get err: %v; want no error", err)
		}
		if g, w := string(it.Value), "some-value" ; g != w {
			t.Errorf("retrieved Item.Value = %q, want %q", g, w)
		}
	}

The environment variable APPENGINE_DEV_APPSERVER specifies the location of the
dev_appserver.py executable to use. If unset, the system PATH is consulted.
*/
package aetest

Fix example code use of aetest.NewContext.


package reflect

import (
	"github.com/anaminus/rbxmk"
)

func All() []func() rbxmk.Type {
	return []func() rbxmk.Type{
		Array,
		Axes,
		BinaryString,
		Bool,
		BrickColor,
		CFrame,
		Color3,
		Color3uint8,
		ColorSequence,
		ColorSequenceKeypoint,
		Content,
		Dictionary,
		Double,
		Faces,
		Float,
		Instance,
		Instances,
		Int,
		Int64,
		Nil,
		Number,
		NumberRange,
		NumberSequence,
		NumberSequenceKeypoint,
		PhysicalProperties,
		ProtectedString,
		Ray,
		Rect,
		Region3,
		Region3int16,
		SharedString,
		String,
		Symbol,
		Table,
		Tuple,
		UDim,
		UDim2,
		Variant,
		Vector2,
		Vector2int16,
		Vector3,
		Vector3int16,
	}
}

package reflect

import (
	"github.com/anaminus/rbxmk"
)

func All() []func() rbxmk.Type {
	return []func() rbxmk.Type{
		Array,
		Axes,
		BinaryString,
		Bool,
		BrickColor,
		CFrame,
		Color3,
		Color3uint8,
		ColorSequence,
		ColorSequenceKeypoint,
		Content,
		Dictionary,
		Double,
		Faces,
		Float,
		Instance,
		Instances,
		Int,
		Int64,
		Nil,
		Number,
		NumberRange,
		NumberSequence,
		NumberSequenceKeypoint,
		PhysicalProperties,
		ProtectedString,
		Ray,
		Rect,
		Region3,
		Region3int16,
		SharedString,
		String,
		Symbol,
		Table,
		Token,
		Tuple,
		UDim,
		UDim2,
		Variant,
		Vector2,
		Vector2int16,
		Vector3,
		Vector3int16,
	}
}

Fix Token not being registered.


package health

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

type HealthChecker struct {
	SubPID int
}

//TODO: Add additional health checks
//TODO: add health check if Kubernetes API is still reachable
func (hc HealthChecker) HealthCheckHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if hc.SubPID != 0 {
			_, err := os.FindProcess(hc.SubPID)
			if err == nil {
				// assume that Python process is still running
				w.WriteHeader(http.StatusOK)
				w.Write([]byte("Ok"))
				return
			}
			log.Println(err)
		}

		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Python process is dead"))
	})
}

package health

import (
	"net/http"
	"os"

	log "github.com/F5Networks/k8s-bigip-ctlr/pkg/vlogger"
)

type HealthChecker struct {
	SubPID int
}

//TODO: Add additional health checks
//TODO: add health check if Kubernetes API is still reachable
func (hc HealthChecker) HealthCheckHandler() http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if hc.SubPID != 0 {
			_, err := os.FindProcess(hc.SubPID)
			if err == nil {
				// assume that Python process is still running
				w.WriteHeader(http.StatusOK)
				w.Write([]byte("Ok"))
				return
			}

			log.Errorf(err.Error())
		}

		w.WriteHeader(http.StatusInternalServerError)
		w.Write([]byte("Python process is dead"))
	})
}

Use vlogger instead of golangs log


package main

import "bufio"
import "fmt"
import "encoding/csv"
import "io"
import "os"

func check(err error) {
	if err != nil {
		panic(err)
	}
}

func parse_file(filename string) ([]string, []string, []string) {
	f, err := os.Open(filename)
	check(err)
	defer f.Close()

	var column_names []string
	var units []string
	var descriptions []string

	r := csv.NewReader(bufio.NewReader(f))
	r.Comma = ';'
RECORDS:
	for {
		record, err := r.Read()
		if err == io.EOF {
			break
		}

		headers := []*[]string{
			&column_names,
			&units,
			&descriptions,
		}

		for _, target := range headers {
			if *target == nil {
				*target = make([]string, len(record))
				copy(*target, record)
				continue RECORDS
			}
		}
	}

	return column_names, units, descriptions
}

func main() {
	column_names, units, descriptions := parse_file("example_headers")
	fmt.Println(column_names)
	fmt.Println(units)
	fmt.Println(descriptions)
}

package main

import "bufio"
import "gopkg.in/alecthomas/kingpin.v2"
import "fmt"
import "encoding/csv"
import "io"
import "os"

var (
	filename = kingpin.Arg("filename", "Filename to load").Required().String()
)

func check(err error) {
	if err != nil {
		panic(err)
	}
}

func parse_file(filename string) ([]string, []string, []string) {
	f, err := os.Open(filename)
	check(err)
	defer f.Close()

	var column_names []string
	var units []string
	var descriptions []string

	r := csv.NewReader(bufio.NewReader(f))
	r.Comma = ';'
RECORDS:
	for {
		record, err := r.Read()
		if err == io.EOF {
			break
		}

		headers := []*[]string{
			&column_names,
			&units,
			&descriptions,
		}

		for _, target := range headers {
			if *target == nil {
				*target = make([]string, len(record))
				copy(*target, record)
				continue RECORDS
			}
		}
	}

	return column_names, units, descriptions
}

func main() {
	kingpin.Parse()
	column_names, units, descriptions := parse_file(*filename)
	fmt.Println(column_names)
	fmt.Println(units)
	fmt.Println(descriptions)
}

Add command-line argument to choose filename.


// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.

package btrees

// findLCA walks the binary tree t and returns lowest common
// ancestor for the nodes n0 and n1. The cnt is 0, 1, or 2
// depending on nodes (n0, n1) presented in the tree.
func findLCA(t, n0, n1 *BTree) (cnt int, ancestor *BTree) {
	if t == nil {
		return 0, nil // Base case.
	}

	// Postorder walk.
	lc, la := findLCA(t.right, n0, n1)
	if lc == 2 {
		return lc, la
	}
	rc, ra := findLCA(t.left, n0, n1)
	if rc == 2 {
		return rc, ra
	}

	cnt = lc + rc
	if t == n0 {
		cnt++
	}
	if t == n1 {
		cnt++
	}
	if cnt == 2 {
		ancestor = t
	}
	return cnt, ancestor
}

// LCA returns the lowest common ancestor in
// the binary tree t for the nodes n0, n1.
func LCA(t, n0, n1 *BTree) *BTree {
	_, a := findLCA(t, n0, n1)
	return a
}

// Copyright (c) 2015, Peter Mrekaj. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE.txt file.

package btrees

// findLCA walks the binary tree t and returns lowest common
// ancestor for the nodes n0 and n1. The cnt is 0, 1, or 2
// depending on nodes (n0, n1) presented in the tree.
func findLCA(t, n0, n1 *BTree) (cnt int, ancestor *BTree) {
	if t == nil {
		return 0, nil // Base case.
	}

	// Postorder walk.
	lc, la := findLCA(t.left, n0, n1)
	if lc == 2 {
		return lc, la
	}
	rc, ra := findLCA(t.right, n0, n1)
	if rc == 2 {
		return rc, ra
	}

	cnt = lc + rc
	if t == n0 {
		cnt++
	}
	if t == n1 {
		cnt++
	}
	if cnt == 2 {
		ancestor = t
	}
	return cnt, ancestor
}

// LCA returns the lowest common ancestor in
// the binary tree t for the nodes n0, n1.
func LCA(t, n0, n1 *BTree) *BTree {
	_, a := findLCA(t, n0, n1)
	return a
}

Change the left and right subtree when recurring findLCA


package storage

import (
	"net/http"
	"time"

	"github.com/docker/distribution"
	"github.com/docker/distribution/digest"
)

// layerReader implements Layer and provides facilities for reading and
// seeking.
type layerReader struct {
	fileReader

	digest digest.Digest
}

var _ distribution.Layer = &layerReader{}

func (lr *layerReader) Digest() digest.Digest {
	return lr.digest
}

func (lr *layerReader) Length() int64 {
	return lr.size
}

func (lr *layerReader) CreatedAt() time.Time {
	return lr.modtime
}

// Close the layer. Should be called when the resource is no longer needed.
func (lr *layerReader) Close() error {
	return lr.closeWithErr(distribution.ErrLayerClosed)
}

func (lr *layerReader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Docker-Content-Digest", lr.digest.String())

	if url, err := lr.fileReader.driver.URLFor(lr.path, map[string]interface{}{}); err == nil {
		http.Redirect(w, r, url, http.StatusTemporaryRedirect)
	}
	http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr)
}

package storage

import (
	"net/http"
	"time"

	"github.com/docker/distribution"
	"github.com/docker/distribution/digest"
)

// layerReader implements Layer and provides facilities for reading and
// seeking.
type layerReader struct {
	fileReader

	digest digest.Digest
}

var _ distribution.Layer = &layerReader{}

func (lr *layerReader) Digest() digest.Digest {
	return lr.digest
}

func (lr *layerReader) Length() int64 {
	return lr.size
}

func (lr *layerReader) CreatedAt() time.Time {
	return lr.modtime
}

// Close the layer. Should be called when the resource is no longer needed.
func (lr *layerReader) Close() error {
	return lr.closeWithErr(distribution.ErrLayerClosed)
}

func (lr *layerReader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Docker-Content-Digest", lr.digest.String())

	if url, err := lr.fileReader.driver.URLFor(lr.path, map[string]interface{}{"method": r.Method}); err == nil {
		http.Redirect(w, r, url, http.StatusTemporaryRedirect)
	}
	http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr)
}

Insert request method option storage driver URLFor


// Copyright 2014-2015 Chadev. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package meetup

import (
	"os"
	"testing"
	"time"
)

func TestGetMeetupEvents(t *testing.T) {
	if os.Getenv("CHADEV_MEETUP") == "" {
		t.Skip("no meetup API key set, skipping test")
	}

	var l bool
	d := time.Now().Weekday().String()
	if d == "Thursday" {
		l = true
	}

	_, err := GetTalkDetails(l)
	if err != nil {
		t.Error(err)
	}
}

// Copyright 2014-2015 Chadev. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package meetup

import (
	"os"
	"testing"
)

func TestGetMeetupEvents(t *testing.T) {
	if os.Getenv("CHADEV_MEETUP") == "" {
		t.Skip("no meetup API key set, skipping test")
	}

	_, err := GetNextMeetup("chadevs")
	if err != nil {
		t.Error(err)
	}
}

Fix Meetup API unit test


package characteristic

type Brightness struct {
	*Int
}

func NewBrightness(value int) *Brightness {
	integer := NewInt(value, 0, 100, 1, PermsAll())
	integer.Unit = UnitPercentage
	integer.Type = CharTypeBrightness

	return &Brightness{integer}
}

package characteristic

type Brightness struct {
	*Int
}

func NewBrightness(value int) *Brightness {
	i := NewInt(value, 0, 100, 1, PermsAll())
	i.Unit = UnitPercentage
	i.Type = CharTypeBrightness

	return &Brightness{i}
}

Rename integer variable to i


package remote

import (
	"sync"
	"testing"

	"github.com/hashicorp/terraform/state"
)

func TestState_impl(t *testing.T) {
	var _ state.StateReader = new(State)
	var _ state.StateWriter = new(State)
	var _ state.StatePersister = new(State)
	var _ state.StateRefresher = new(State)
	var _ state.Locker = new(State)
}

func TestStateRace(t *testing.T) {
	s := &State{
		Client: nilClient{},
	}

	current := state.TestStateInitial()

	var wg sync.WaitGroup

	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			s.WriteState(current)
			s.PersistState()
			s.RefreshState()
		}()
	}
	wg.Wait()
}

package remote

import (
	"sync"
	"testing"

	"github.com/hashicorp/terraform/states/statemgr"
)

func TestState_impl(t *testing.T) {
	var _ statemgr.Reader = new(State)
	var _ statemgr.Writer = new(State)
	var _ statemgr.Persister = new(State)
	var _ statemgr.Refresher = new(State)
	var _ statemgr.Locker = new(State)
}

func TestStateRace(t *testing.T) {
	s := &State{
		Client: nilClient{},
	}

	current := state.TestStateInitial()

	var wg sync.WaitGroup

	for i := 0; i < 100; i++ {
		wg.Add(1)
		go func() {
			defer wg.Done()
			s.WriteState(current)
			s.PersistState()
			s.RefreshState()
		}()
	}
	wg.Wait()
}

Switch to statemgr interfaces in test


// Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.

// Package watcher provides a way of watching for filesystem events and
// notifying observers when they occur.
package watcher

type OpType int

const (
	Create OpType = iota
	Update
	Delete
)

// Event is a generalisation of events sent from the watcher to its listeners.
type Event struct {
	Op       OpType
	Pathname string
}

// Watcher describes an interface for filesystem watching.
type Watcher interface {
	Add(name string, handle int) error
	Close() error
	Remove(name string) error
	Events() (handle int, ch <-chan Event)
}

// Copyright 2015 Google Inc. All Rights Reserved.
// This file is available under the Apache license.

// Package watcher provides a way of watching for filesystem events and
// notifying observers when they occur.
package watcher

type OpType int

const (
	_ OpType = iota
	Create
	Update
	Delete
)

// Event is a generalisation of events sent from the watcher to its listeners.
type Event struct {
	Op       OpType
	Pathname string
}

// Watcher describes an interface for filesystem watching.
type Watcher interface {
	Add(name string, handle int) error
	Close() error
	Remove(name string) error
	Events() (handle int, ch <-chan Event)
}

Change the zero OpType to not be valid.


package file_storage

import (
	"github.com/photoshelf/photoshelf-storage/domain/model"
	"io/ioutil"
	"os"
	"path"
)

type FileStorage struct {
	baseDir string
}

func NewFileStorage(baseDir string) *FileStorage {
	return &FileStorage{baseDir}
}

func (storage *FileStorage) Save(photo model.Photo) (*model.Identifier, error) {
	data := photo.Image()
	id := photo.Id()
	if photo.IsNew() {
		id = *model.NewIdentifier(data)
	}

	dst, err := os.Create(path.Join(storage.baseDir, id.Value()))
	if err != nil {
		return nil, err
	}
	defer dst.Close()

	if _, err := dst.Write(data); err != nil {
		return nil, err
	}
	return &id, nil
}

func (storage *FileStorage) Read(id model.Identifier) (*model.Photo, error) {
	file, err := os.Open(path.Join(storage.baseDir, id.Value()))
	if err != nil {
		return nil, err
	}
	data, err := ioutil.ReadAll(file)
	if err != nil {
		return nil, err
	}

	return model.PhotoOf(id, data), nil
}

func (storage *FileStorage) Delete(id model.Identifier) error {
	if err := os.Remove(path.Join(storage.baseDir, id.Value())); err != nil {
		return err
	}
	return nil
}

package file_storage

import (
	"github.com/photoshelf/photoshelf-storage/domain/model"
	"io/ioutil"
	"os"
	"path"
)

type FileStorage struct {
	baseDir string
}

func NewFileStorage(baseDir string) *FileStorage {
	return &FileStorage{baseDir}
}

func (storage *FileStorage) Save(photo model.Photo) (*model.Identifier, error) {
	data := photo.Image()
	id := photo.Id()
	if photo.IsNew() {
		id = *model.NewIdentifier(data)
	}

	filename := path.Join(storage.baseDir, id.Value())
	ioutil.WriteFile(filename, data, 0600)

	return &id, nil
}

func (storage *FileStorage) Read(id model.Identifier) (*model.Photo, error) {
	filename := path.Join(storage.baseDir, id.Value())
	data, err := ioutil.ReadFile(filename)
	if err != nil {
		return nil, err
	}

	return model.PhotoOf(id, data), nil
}

func (storage *FileStorage) Delete(id model.Identifier) error {
	if err := os.Remove(path.Join(storage.baseDir, id.Value())); err != nil {
		return err
	}
	return nil
}

Use ioutil for reduce code line


package sub

import (
	"github.com/Symantec/Dominator/lib/filesystem"
	"github.com/Symantec/Dominator/lib/hash"
	"github.com/Symantec/Dominator/lib/triggers"
	"github.com/Symantec/Dominator/proto/common"
	"github.com/Symantec/Dominator/sub/scanner"
)

type Configuration struct {
	ScanSpeedPercent    uint
	NetworkSpeedPercent uint
	ScanExclusionList   []string
}

type FetchRequest struct {
	ServerAddress string
	Hashes        []hash.Hash
}

type FetchResponse common.StatusResponse

type GetConfigurationRequest struct {
}

type GetConfigurationResponse Configuration

type PollRequest struct {
	HaveGeneration uint64
}

type PollResponse struct {
	NetworkSpeed     uint64
	FetchInProgress  bool // Fetch() and Update() are mutually exclusive.
	UpdateInProgress bool
	GenerationCount  uint64
	FileSystem       *scanner.FileSystem
}

type SetConfigurationRequest Configuration

type SetConfigurationResponse common.StatusResponse

type Directory struct {
	Name string
	Mode filesystem.FileMode
	Uid  uint32
	Gid  uint32
}

type UpdateRequest struct {
	PathsToDelete     []string
	DirectoriesToMake []Directory
	Triggers          *triggers.Triggers
}

type UpdateResponse struct{}

package sub

import (
	"github.com/Symantec/Dominator/lib/filesystem"
	"github.com/Symantec/Dominator/lib/hash"
	"github.com/Symantec/Dominator/lib/triggers"
	"github.com/Symantec/Dominator/proto/common"
	"github.com/Symantec/Dominator/sub/scanner"
)

type Configuration struct {
	ScanSpeedPercent    uint
	NetworkSpeedPercent uint
	ScanExclusionList   []string
}

type FetchRequest struct {
	ServerAddress string
	Hashes        []hash.Hash
}

type FetchResponse common.StatusResponse

type GetConfigurationRequest struct {
}

type GetConfigurationResponse Configuration

type PollRequest struct {
	HaveGeneration uint64
}

type PollResponse struct {
	NetworkSpeed     uint64
	FetchInProgress  bool // Fetch() and Update() are mutually exclusive.
	UpdateInProgress bool
	GenerationCount  uint64
	FileSystem       *scanner.FileSystem
}

type SetConfigurationRequest Configuration

type SetConfigurationResponse common.StatusResponse

type Directory struct {
	Name string
	Mode filesystem.FileMode
	Uid  uint32
	Gid  uint32
}

type UpdateRequest struct {
	PathsToDelete       []string
	DirectoriesToMake   []Directory
	DirectoriesToChange []Directory
	Triggers            *triggers.Triggers
}

type UpdateResponse struct{}

Add DirectoriesToChange field to sub.UpdateRequest message.


//go:generate go run maketables.go > tables.go

package confusables

import (
	"unicode/utf8"

	"golang.org/x/text/unicode/norm"
)

// TODO: document casefolding approaches
// (suggest to force casefold strings; explain how to catch paypal - pAypal)
// TODO: DOC you might want to store the Skeleton and check against it later
// TODO: implement xidmodifications.txt restricted characters

// Skeleton converts a string to it's "skeleton" form
// as descibed in http://www.unicode.org/reports/tr39/#Confusable_Detection
func Skeleton(s string) string {

	// 1. Converting X to NFD format
	s = norm.NFD.String(s)

	// 2. Successively mapping each source character in X to the target string
	// according to the specified data table
	for i, w := 0, 0; i < len(s); i += w {
		char, width := utf8.DecodeRuneInString(s[i:])
		replacement, exists := confusablesMap[char]
		if exists {
			s = s[:i] + replacement + s[i+width:]
			w = len(replacement)
		} else {
			w = width
		}
	}

	// 3. Reapplying NFD
	s = norm.NFD.String(s)

	return s
}

func Confusable(x, y string) bool {
	return Skeleton(x) == Skeleton(y)
}

//go:generate go run maketables.go > tables.go

package confusables

import (
	"bytes"

	"golang.org/x/text/unicode/norm"
)

// TODO: document casefolding approaches
// (suggest to force casefold strings; explain how to catch paypal - pAypal)
// TODO: DOC you might want to store the Skeleton and check against it later
// TODO: implement xidmodifications.txt restricted characters

func mapConfusableRunes(ss string) string {
	var buffer bytes.Buffer
	for _, r := range ss {
		replacement, replacementExists := confusablesMap[r]
		if replacementExists {
			buffer.WriteString(replacement)
		} else {
			buffer.WriteRune(r)
		}
	}
	return buffer.String()
}

// Skeleton converts a string to it's "skeleton" form
// as descibed in http://www.unicode.org/reports/tr39/#Confusable_Detection
//   1. Converting X to NFD format
//   2. Successively mapping each source character in X to the target string
//      according to the specified data table
//   3. Reapplying NFD
func Skeleton(s string) string {
	return norm.NFD.String(
		mapConfusableRunes(
			norm.NFD.String(s)))
}

func Confusable(x, y string) bool {
	return Skeleton(x) == Skeleton(y)
}

Improve performance of Skeleton func


package app

import (
	"strings"

	"github.com/materials-commons/config"
	"github.com/materials-commons/gohandy/ezhttp"
)

type mcapi struct{}

var MCApi mcapi

func (a mcapi) MCUrl() string {
	return config.GetString("mcurl")
}

func (a mcapi) MCClient() *ezhttp.EzClient {
	mcurl := a.MCUrl()
	if strings.HasPrefix(mcurl, "https") {
		return ezhttp.NewSSLClient()
	}
	return ezhttp.NewClient()
}

package app

import (
	"encoding/json"
	"fmt"
	"net/http"
	"net/url"
	"strings"

	"github.com/gtarcea/1DevDayTalk2014/app"
	"github.com/materials-commons/config"
	"github.com/materials-commons/gohandy/ezhttp"
	"gnd.la/net/urlutil"
)

type mcapi struct{}

var MCApi mcapi

func (a mcapi) MCUrl() string {
	return config.GetString("mcurl")
}

func (a mcapi) MCClient() *ezhttp.EzClient {
	mcurl := a.MCUrl()
	if strings.HasPrefix(mcurl, "https") {
		return ezhttp.NewSSLClient()
	}
	return ezhttp.NewClient()
}

func (a mcapi) APIUrl(path string) string {
	values := url.Values{}
	values.Add("apikey", config.GetString("apikey"))
	mcurl := urlutil.MustJoin(a.MCUrl(), path)
	mcurl = urlutil.AppendQuery(mcurl, values)
	return mcurl
}

func (a mcapi) APIError(resp *http.Response, errs []error) error {
	switch {
	case len(errs) != 0:
		return app.ErrInvalid
	case resp.StatusCode > 299:
		return fmt.Errorf("HTTP Error: %s", resp.Status)
	default:
		return nil
	}
}

func (a mcapi) ToJSON(from string, to interface{}) error {
	err := json.Unmarshal([]byte(from), to)
	return err
}

Add utility functions for dealing with the api.


package peer

import (
	"fmt"
	"io/ioutil"
	"testing"
)

func TestCrStates(t *testing.T) {
	t.Log("Running Peer Tests")

	text, err := ioutil.ReadFile("crstates.json")
	if err != nil {
		t.Log(err)
	}
	crStates, err := CrStatesUnMarshall(text)
	if err != nil {
		t.Log(err)
	}
	fmt.Println(len(crStates.Caches), "caches found")
	for cacheName, crState := range crStates.Caches {
		t.Logf("%v -> %v", cacheName, crState.IsAvailable)
	}

	fmt.Println(len(crStates.Deliveryservice), "deliveryservices found")
	for dsName, deliveryService := range crStates.Deliveryservice {
		t.Logf("%v -> %v (len:%v)", dsName, deliveryService.IsAvailable, len(deliveryService.DisabledLocations))
	}

}

package peer

import (
	"fmt"
	"io/ioutil"
	"testing"
)

func TestCrStates(t *testing.T) {
	t.Log("Running Peer Tests")

	text, err := ioutil.ReadFile("crstates.json")
	if err != nil {
		t.Log(err)
	}
	crStates, err := CrstatesUnMarshall(text)
	if err != nil {
		t.Log(err)
	}
	fmt.Println(len(crStates.Caches), "caches found")
	for cacheName, crState := range crStates.Caches {
		t.Logf("%v -> %v", cacheName, crState.IsAvailable)
	}

	fmt.Println(len(crStates.Deliveryservice), "deliveryservices found")
	for dsName, deliveryService := range crStates.Deliveryservice {
		t.Logf("%v -> %v (len:%v)", dsName, deliveryService.IsAvailable, len(deliveryService.DisabledLocations))
	}

}

Fix TM2 test to match renamed symbol


package cc_messages

type LRPInstanceState string

const (
	LRPInstanceStateStarting LRPInstanceState = "STARTING"
	LRPInstanceStateRunning  LRPInstanceState = "RUNNING"
	LRPInstanceStateCrashed  LRPInstanceState = "CRASHED"
	LRPInstanceStateUnknown  LRPInstanceState = "UNKNOWN"
)

type LRPInstance struct {
	ProcessGuid  string            `json:"process_guid"`
	InstanceGuid string            `json:"instance_guid"`
	Index        uint              `json:"index"`
	State        LRPInstanceState  `json:"state"`
	Details      string            `json:"details,omitempty"`
	Since        int64             `json:"since_in_ns"`
	Stats        *LRPInstanceStats `json:"stats,omitempty"`
}

type LRPInstanceStats struct {
	CpuPercentage float64 `json:"cpu"`
	MemoryBytes   uint64  `json:"mem"`
	DiskBytes     uint64  `json:"disk"`
}

package cc_messages

import "time"

type LRPInstanceState string

const (
	LRPInstanceStateStarting LRPInstanceState = "STARTING"
	LRPInstanceStateRunning  LRPInstanceState = "RUNNING"
	LRPInstanceStateCrashed  LRPInstanceState = "CRASHED"
	LRPInstanceStateUnknown  LRPInstanceState = "UNKNOWN"
)

type LRPInstance struct {
	ProcessGuid  string            `json:"process_guid"`
	InstanceGuid string            `json:"instance_guid"`
	Index        uint              `json:"index"`
	State        LRPInstanceState  `json:"state"`
	Details      string            `json:"details,omitempty"`
	Host         string            `json:"host,omitempty"`
	Port         uint16            `json:"port,omitempty"`
	Since        int64             `json:"since"`
	Stats        *LRPInstanceStats `json:"stats,omitempty"`
}

type LRPInstanceStats struct {
	Time          time.Time `json:"time"`
	CpuPercentage float64   `json:"cpu"`
	MemoryBytes   uint64    `json:"mem"`
	DiskBytes     uint64    `json:"disk"`
}

Add new fields to match DEA


package main

import (
	"bufio"
	"fmt"
	"os"
	"regexp"
	)

func main() {
	file, err := os.Open("targetlist.txt")

	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	defer file.Close()

	scanner := bufio.NewScanner(file)

	r, _ := regexp.Compile("https?://(www.)?[a-zA-Z0-9.]{2,512}.[a-z]{2,10}")

	for scanner.Scan() {
		line := scanner.Text()

		if r.MatchString(line) {
			fmt.Println("Valid: " + line)
		}
	}
}

package main

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

func check(e error) {
	if e != nil {
    	panic(e)
	}
}

// Request webcontent from url
func Webrequest(url string) string {
	resp, err := http.Get(url)
	if err != nil {
		fmt.Println(err)
	}
	defer resp.Body.Close()

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

	return string(body)
}

// Write content to file
func SaveFile(File string, ctx string) {
	d1 := []byte(ctx)
	err := ioutil.WriteFile(File, d1, 0644)
	check(err)
}

// Substract name from URL
func Makefilename(URL string) string {
	usz := len(URL)

	if URL[usz-1] == '/' {
		URL = URL[0:usz-1]
	}

	protpos := strings.Index(URL, "//")
	URL = URL[protpos+2:len(URL)]

	return strings.Replace(URL, ".", "_", -1)
}

func main() {
	file, err := os.Open("targetlist.txt")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	defer file.Close()

	scanner := bufio.NewScanner(file)
	r, _ := regexp.Compile("^https?://(www.)?[a-zA-Z0-9.]{2,512}.[a-z]{2,10}/?$")
	for scanner.Scan() {
		line := scanner.Text()

		if r.MatchString(line) {
			fmt.Println("Valid: " + line)
			html := Webrequest(line)
			OutName := Makefilename(line) + ".txt"
			SaveFile(OutName, html)
		}
	}
}

Make HTTP request and save to file


package ishell

import "strings"

type iCompleter struct {
	cmd *Cmd
}

func (ic iCompleter) Do(line []rune, pos int) (newLine [][]rune, length int) {
	words := strings.Fields(string(line))
	var cWords []string
	prefix := ""
	if len(words) > 0 && line[pos-1] != ' ' {
		prefix = words[len(words)-1]
		cWords = ic.getWords(words[:len(words)-1])
	} else {
		cWords = ic.getWords(words)
	}

	var suggestions [][]rune
	for _, w := range cWords {
		if strings.HasPrefix(w, prefix) {
			suggestions = append(suggestions, []rune(strings.TrimPrefix(w, prefix)))
		}
	}
	return suggestions, len(prefix)
}

func (ic iCompleter) getWords(w []string) (s []string) {
	cmd, args := ic.cmd.FindCmd(w)
	if cmd == nil {
		cmd, args = ic.cmd, w
	}
	if cmd.Completer != nil {
		return cmd.Completer(args)
	}
	for k := range cmd.children {
		s = append(s, k)
	}
	return
}

package ishell

import "strings"

type iCompleter struct {
	cmd *Cmd
}

func (ic iCompleter) Do(line []rune, pos int) (newLine [][]rune, length int) {
	words := strings.Fields(string(line))
	var cWords []string
	prefix := ""
	if len(words) > 0 && line[pos-1] != ' ' {
		prefix = words[len(words)-1]
		cWords = ic.getWords(words[:len(words)-1])
	} else {
		cWords = ic.getWords(words)
	}

	var suggestions [][]rune
	for _, w := range cWords {
		if strings.HasPrefix(w, prefix) {
			suggestions = append(suggestions, []rune(strings.TrimPrefix(w, prefix)))
		}
	}
	if len(suggestions) == 1 && prefix != "" && string(suggestions[0]) == "" {
		suggestions = [][]rune{[]rune(" ")}
	}
	return suggestions, len(prefix)
}

func (ic iCompleter) getWords(w []string) (s []string) {
	cmd, args := ic.cmd.FindCmd(w)
	if cmd == nil {
		cmd, args = ic.cmd, w
	}
	if cmd.Completer != nil {
		return cmd.Completer(args)
	}
	for k := range cmd.children {
		s = append(s, k)
	}
	return
}

Add space on tab with no suggestion


package hello

import (
	"fmt"
	"net/http"
)

func init() {
	http.HandleFunc("/", handler)

}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, world!")

}

package polling

import (
	"fmt"
	"net/http"
)

func init() {
	http.HandleFunc("/", handler)

}

func handler(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, world!")

}

Change of the package name


package state

import (
	"fmt"
	"testing"
)

var simpleFile = []byte(`
{"path": "/tmp/no-exist", "mode": 644}
`)

var simpleFileMeta = Metadata{
	Name: "Simple File",
	Type: "file",
	State: "rendered",
}

func TestStateFactory(t *testing.T) {
	state, err := StateFactory(simpleFileMeta, simpleFile)
	if err != nil {
		fmt.Println(err)
		t.Fail()
	}
	name := state.Meta().Name
	if name != "Simple File" {
		fmt.Printf("Did not load metadata correctly: %s", name)
		t.Fail()
	}
}

package state

import (
	"fmt"
	"testing"
)

var simpleFile = []byte(`
{"path": "/tmp/no-exist", "mode": 644, "source": "git:///git@github.com:vektorlab/otter/README.md"}
`)

var simpleFileMeta = Metadata{
	Name: "Simple File",
	Type: "file",
	State: "rendered",
}

func TestStateFactory(t *testing.T) {
	state, err := StateFactory(simpleFileMeta, simpleFile)
	if err != nil {
		fmt.Println(err)
		t.Fail()
	}
	name := state.Meta().Name
	if name != "Simple File" {
		fmt.Printf("Did not load metadata correctly: %s", name)
		t.Fail()
	}
}

Add source to simpleFile test


package gitbucket

import (
	"fmt"
	"net/http"
)

type RepositoriesService struct {
	client *Client
}

// Repository represents a API user.
type Repository struct {
	Name          *string `json:"name"`
	FullName      *string `json:"full_name"`
	Description   *string `json:"description"`
	Watchers      *int    `json:"watchers"`
	Forks         *int    `json:"forks"`
	Private       *bool   `json:"private"`
	DefaultBranch *string `json:"default_branch"`
	Owner         *User   `json:"owner"`
	ForksCount    *int    `json:"forks_count"`
	WatchersCount *int    `json:"watchers_coun"`
	URL           *string `json:"url"`
	HTTPURL       *string `json:"http_url"`
	CloneURL      *string `json:"clone_url"`
	HTMLURL       *string `json:"html_url"`
}

func (s *RepositoriesService) Get(owner, repo string) (*Repository, *http.Response, error) {
	u := fmt.Sprintf("/repos/%v/%v", owner, repo)
	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	r := new(Repository)
	resp, err := s.client.Do(req, r)
	if err != nil {
		return nil, resp, err
	}

	return r, resp, err
}

package gitbucket

import (
	"fmt"
	"net/http"
)

type RepositoriesService struct {
	client *Client
}

// Repository represents a API user.
type Repository struct {
	Name          *string `json:"name"`
	FullName      *string `json:"full_name"`
	Description   *string `json:"description"`
	Watchers      *int    `json:"watchers"`
	Forks         *int    `json:"forks"`
	Private       *bool   `json:"private"`
	DefaultBranch *string `json:"default_branch"`
	Owner         *User   `json:"owner"`
	ForksCount    *int    `json:"forks_count"`
	WatchersCount *int    `json:"watchers_count"`
	URL           *string `json:"url"`
	HTTPURL       *string `json:"http_url"`
	CloneURL      *string `json:"clone_url"`
	HTMLURL       *string `json:"html_url"`
}

func (s *RepositoriesService) Get(owner, repo string) (*Repository, *http.Response, error) {
	u := fmt.Sprintf("/repos/%v/%v", owner, repo)
	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

	r := new(Repository)
	resp, err := s.client.Do(req, r)
	if err != nil {
		return nil, resp, err
	}

	return r, resp, err
}

Update field name in the JSON.


package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os"

	"github.com/mgutz/logxi/v1"
)

func sendExternal(obj map[string]interface{}) {
	// normally you would send this to an external service like InfluxDB
	// or some logging framework. Let's filter out some data.
	fmt.Printf("Time: %s Level: %s Message: %s\n",
		obj[log.TimeKey],
		obj[log.LevelKey],
		obj[log.MessageKey],
	)
}

func main() {
	r := bufio.NewReader(os.Stdin)
	dec := json.NewDecoder(r)
	for {
		var obj map[string]interface{}
		if err := dec.Decode(&obj); err == io.EOF {
			break
		} else if err != nil {
			log.InternalLog.Fatal("Could not decode", "err", err)
		}
		sendExternal(obj)
	}
}

package main

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"os"

	"github.com/mgutz/logxi/v1"
)

func sendExternal(obj map[string]interface{}) {
	// normally you would send this to an external service like InfluxDB
	// or some logging framework. Let's filter out some data.
	fmt.Printf("Time: %s Level: %s Message: %s\n",
		obj[log.KeyMap.Time],
		obj[log.KeyMap.Level],
		obj[log.KeyMap.Message],
	)
}

func main() {
	r := bufio.NewReader(os.Stdin)
	dec := json.NewDecoder(r)
	for {
		var obj map[string]interface{}
		if err := dec.Decode(&obj); err == io.EOF {
			break
		} else if err != nil {
			log.InternalLog.Fatal("Could not decode", "err", err)
		}
		sendExternal(obj)
	}
}

Change filter example to use KeyMap


/*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.

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

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

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

package object

import (
	"github.com/vmware/govmomi/vim25/types"
	"golang.org/x/net/context"
)

// The NetworkReference interface is implemented by managed objects
// which can be used as the backing for a VirtualEthernetCard.
type NetworkReference interface {
	EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
}

/*
Copyright (c) 2014 VMware, Inc. All Rights Reserved.

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

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

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

package object

import (
	"github.com/vmware/govmomi/vim25/types"
	"golang.org/x/net/context"
)

// The NetworkReference interface is implemented by managed objects
// which can be used as the backing for a VirtualEthernetCard.
type NetworkReference interface {
	Reference

	EthernetCardBackingInfo(ctx context.Context) (types.BaseVirtualDeviceBackingInfo, error)
}

Embed Reference interface in NetworkReference


package flags

import (
	"os"
	"testing"

	"github.com/spf13/cobra"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestEnvConfig_Defaults(t *testing.T) {
	cmd := new(cobra.Command)
	SetDefaults()
	RegisterDockerFlags(cmd)

	err := EnvConfig(cmd)
	require.NoError(t, err)

	assert.Equal(t, "unix:///var/run/docker.sock", os.Getenv("DOCKER_HOST"))
	assert.Equal(t, "", os.Getenv("DOCKER_TLS_VERIFY"))
	assert.Equal(t, DockerAPIMinVersion, os.Getenv("DOCKER_API_VERSION"))
}

func TestEnvConfig_Custom(t *testing.T) {
	cmd := new(cobra.Command)
	SetDefaults()
	RegisterDockerFlags(cmd)

	err := cmd.ParseFlags([]string{"--host", "some-custom-docker-host", "--tlsverify", "--api-version", "1.99"})
	require.NoError(t, err)

	err = EnvConfig(cmd)
	require.NoError(t, err)

	assert.Equal(t, "some-custom-docker-host", os.Getenv("DOCKER_HOST"))
	assert.Equal(t, "1", os.Getenv("DOCKER_TLS_VERIFY"))
	assert.Equal(t, "1.99", os.Getenv("DOCKER_API_VERSION"))
}

package flags

import (
	"os"
	"testing"

	"github.com/spf13/cobra"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func TestEnvConfig_Defaults(t *testing.T) {
	cmd := new(cobra.Command)
	SetDefaults()
	RegisterDockerFlags(cmd)

	err := EnvConfig(cmd)
	require.NoError(t, err)

	assert.Equal(t, "unix:///var/run/docker.sock", os.Getenv("DOCKER_HOST"))
	assert.Equal(t, "", os.Getenv("DOCKER_TLS_VERIFY"))
	// Re-enable this test when we've moved to github actions.
	// assert.Equal(t, DockerAPIMinVersion, os.Getenv("DOCKER_API_VERSION"))
}

func TestEnvConfig_Custom(t *testing.T) {
	cmd := new(cobra.Command)
	SetDefaults()
	RegisterDockerFlags(cmd)

	err := cmd.ParseFlags([]string{"--host", "some-custom-docker-host", "--tlsverify", "--api-version", "1.99"})
	require.NoError(t, err)

	err = EnvConfig(cmd)
	require.NoError(t, err)

	assert.Equal(t, "some-custom-docker-host", os.Getenv("DOCKER_HOST"))
	assert.Equal(t, "1", os.Getenv("DOCKER_TLS_VERIFY"))
	// Re-enable this test when we've moved to github actions.
	// assert.Equal(t, "1.99", os.Getenv("DOCKER_API_VERSION"))
}

Comment out test that is incompatible with CircleCI


package models

import (
	"database/sql"

	"github.com/pborman/uuid"
	"github.com/stripe/stripe-go"
)

/*Roaster has information retrieved from stripe and the db
  about billing for roaster entities*/
type Roaster struct {
	//ID is the roaster ID in towncenter
	ID        uuid.UUID       `json:"id"`
	AccountID string          `json:"stripeAccountId"`
	Account   *stripe.Account `json:"account"`
}

/*RoasterRequest has information used in creating a roaster
  managed account in stripe*/
type RoasterRequest struct {
	UserID uuid.UUID `json:"userId" binding:"required"`
	/* TODO: more info as we need it */
}

/*NewRoaster initialized and returns a roaster model*/
func NewRoaster(id uuid.UUID, accountID string) *Roaster {
	return &Roaster{
		ID:        uuid.NewUUID(),
		AccountID: accountID,
	}
}

/*RoasterFromSQL maps an sql row to roaster properties,
  where order matters*/
func RoasterFromSQL(rows *sql.Rows) ([]*Roaster, error) {
	roasters := make([]*Roaster, 0)

	for rows.Next() {
		c := &Roaster{}
		rows.Scan(&c.ID, &c.AccountID)
		roasters = append(roasters, c)
	}

	return roasters, nil
}

package models

import (
	"database/sql"

	"github.com/pborman/uuid"
	"github.com/stripe/stripe-go"
)

/*Roaster has information retrieved from stripe and the db
  about billing for roaster entities*/
type Roaster struct {
	//ID is the roaster ID in towncenter
	ID        uuid.UUID       `json:"id"`
	AccountID string          `json:"stripeAccountId"`
	Account   *stripe.Account `json:"account"`
}

/*RoasterRequest has information used in creating a roaster
  managed account in stripe*/
type RoasterRequest struct {
	UserID uuid.UUID `json:"userId" binding:"required"`
	/* TODO: more info as we need it */
}

/*NewRoaster initialized and returns a roaster model*/
func NewRoaster(id uuid.UUID, accountID string) *Roaster {
	return &Roaster{
		ID:        id,
		AccountID: accountID,
	}
}

/*RoasterFromSQL maps an sql row to roaster properties,
  where order matters*/
func RoasterFromSQL(rows *sql.Rows) ([]*Roaster, error) {
	roasters := make([]*Roaster, 0)

	for rows.Next() {
		c := &Roaster{}
		rows.Scan(&c.ID, &c.AccountID)
		roasters = append(roasters, c)
	}

	return roasters, nil
}

Remove new account id generation


/*
 * Datadog API for Go
 *
 * Please see the included LICENSE file for licensing information.
 *
 * Copyright 2013 by authors and contributors.
 */

package datadog

import (
	"errors"
)

// reqInviteUsers contains email addresses to send invitations to.
type reqInviteUsers struct {
	Emails []string `json:"emails"`
}

// InviteUsers takes a slice of email addresses and sends invitations to them.
func (self *Client) InviteUsers(emails []string) error {
	return errors.New("datadog API docs don't list the endpoint")

	//	return self.doJsonRequest("POST", "/v1/alert",
	//		reqInviteUsers{Emails: emails}, nil)
}

/*
 * Datadog API for Go
 *
 * Please see the included LICENSE file for licensing information.
 *
 * Copyright 2013 by authors and contributors.
 */

package datadog

// reqInviteUsers contains email addresses to send invitations to.
type reqInviteUsers struct {
	Emails []string `json:"emails"`
}

// InviteUsers takes a slice of email addresses and sends invitations to them.
func (self *Client) InviteUsers(emails []string) error {
	return self.doJsonRequest("POST", "/v1/account/invite",
		reqInviteUsers{Emails: emails}, nil)
}

Implement the user invitation method


package main // import "eriol.xyz/piken"

import (
	"io"
	"net/http"
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/mitchellh/go-homedir"
)

func download(url, output string) error {

	r, err := http.Get(url)
	if err != nil {
		return err
	}
	defer r.Body.Close()

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

	// io.copyBuffer, the actual implementation of io.Copy, reads maximum 32 KB
	// from input, writes to output and then repeats. No need to worry about
	// the size of file to download.
	_, err = io.Copy(out, r.Body)
	if err != nil {
		return err
	}

	return nil

}

// Get user home directory or exit with a fatal error.
func getHome() string {

	homeDir, err := homedir.Dir()
	if err != nil {
		logrus.Fatal(err)
	}

	return homeDir
}

package main // import "eriol.xyz/piken"

import (
	"encoding/csv"
	"io"
	"net/http"
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/mitchellh/go-homedir"
)

func download(url, output string) error {

	r, err := http.Get(url)
	if err != nil {
		return err
	}
	defer r.Body.Close()

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

	// io.copyBuffer, the actual implementation of io.Copy, reads maximum 32 KB
	// from input, writes to output and then repeats. No need to worry about
	// the size of file to download.
	_, err = io.Copy(out, r.Body)
	if err != nil {
		return err
	}

	return nil

}

// Get user home directory or exit with a fatal error.
func getHome() string {

	homeDir, err := homedir.Dir()
	if err != nil {
		logrus.Fatal(err)
	}

	return homeDir
}

// Read a CSV file and return a slice of slice.
func readCsvFile(filepath string) (records [][]string, err error) {

	file, err := os.Open(filepath)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	reader := csv.NewReader(file)
	reader.Comma = ';'
	records, err = reader.ReadAll()
	if err != nil {
		return nil, err
	}

	return records, nil

}