package acmedns

import (
	"github.com/stretchr/testify/assert"
	"os"
	"testing"
)

var (
	acmednsLiveTest     bool
	acmednsHost         string
	acmednsAccountsJson []byte
	acmednsDomain       string
)

func init() {
	acmednsHost = os.Getenv("ACME_DNS_HOST")
	acmednsAccountsJson = []byte(os.Getenv("ACME_DNS_ACCOUNTS_JSON"))
	if len(acmednsHost) > 0 && len(acmednsAccountsJson) > 0 {
		acmednsLiveTest = true
	}
}

func TestLiveAcmeDnsPresent(t *testing.T) {
	if !acmednsLiveTest {
		t.Skip("skipping live test")
	}
	provider, err := NewDNSProviderHostBytes(acmednsHost, acmednsAccountsJson)
	assert.NoError(t, err)

	err = provider.Present(acmednsDomain, "", "123d==")
	assert.NoError(t, err)
}

package acmedns

import (
	"github.com/stretchr/testify/assert"
	"os"
	"testing"
)

var (
	acmednsLiveTest     bool
	acmednsHost         string
	acmednsAccountsJson []byte
	acmednsDomain       string
)

func init() {
	acmednsHost = os.Getenv("ACME_DNS_HOST")
	acmednsAccountsJson = []byte(os.Getenv("ACME_DNS_ACCOUNTS_JSON"))
	acmednsDomain = os.Getenv("ACME_DNS_DOMAIN")
	if len(acmednsHost) > 0 && len(acmednsAccountsJson) > 0 {
		acmednsLiveTest = true
	}
}

func TestLiveAcmeDnsPresent(t *testing.T) {
	if !acmednsLiveTest {
		t.Skip("skipping live test")
	}
	provider, err := NewDNSProviderHostBytes(acmednsHost, acmednsAccountsJson)
	assert.NoError(t, err)

	err = provider.Present(acmednsDomain, "", "123d==")
	assert.NoError(t, err)
}

Read test host from env variable


package youtube

import (
	"log"
	"time"
)

const defaultCacheExpiration = time.Minute * time.Duration(5)

type playerCache struct {
	key       string
	expiredAt time.Time
	config    playerConfig
}

// Get : get cache  when it has same video id and not expired
func (s playerCache) Get(key string) playerConfig {
	result := s.GetCacheBefore(key, time.Now())
	if result == nil {
		log.Println("Cache miss for", key)
	} else {
		log.Println("Cache hit for", key)
	}
	return result
}

// GetCacheBefore : can pass time for testing
func (s playerCache) GetCacheBefore(key string, time time.Time) playerConfig {
	if key == s.key && s.expiredAt.After(time) {
		return s.config
	}
	return nil
}

// Set : set cache with default expiration
func (s *playerCache) Set(key string, operations playerConfig) {
	s.setWithExpiredTime(key, operations, time.Now().Add(defaultCacheExpiration))
}

func (s *playerCache) setWithExpiredTime(key string, config playerConfig, time time.Time) {
	s.key = key
	s.config = config
	s.expiredAt = time
}

package youtube

import (
	"time"
)

const defaultCacheExpiration = time.Minute * time.Duration(5)

type playerCache struct {
	key       string
	expiredAt time.Time
	config    playerConfig
}

// Get : get cache  when it has same video id and not expired
func (s playerCache) Get(key string) playerConfig {
	return s.GetCacheBefore(key, time.Now())
}

// GetCacheBefore : can pass time for testing
func (s playerCache) GetCacheBefore(key string, time time.Time) playerConfig {
	if key == s.key && s.expiredAt.After(time) {
		return s.config
	}
	return nil
}

// Set : set cache with default expiration
func (s *playerCache) Set(key string, operations playerConfig) {
	s.setWithExpiredTime(key, operations, time.Now().Add(defaultCacheExpiration))
}

func (s *playerCache) setWithExpiredTime(key string, config playerConfig, time time.Time) {
	s.key = key
	s.config = config
	s.expiredAt = time
}

Remove debug output from playerCache


package aggregator

import "github.com/GoogleCloudPlatform/kubernetes/pkg/scaler/types"

type Node struct {
	Capacity types.Resource
	Usage    types.Resource
}

type Aggregator interface {
	// Returns a map with node name as key.
	GetClusterInfo() (map[string]Node, error)
}

package aggregator

import "github.com/GoogleCloudPlatform/kubernetes/pkg/scaler/types"

type Node struct {
	Capacity types.Resource
	Usage    types.Resource
	NumPods	 uint32
}

type Aggregator interface {
	// Returns a map with node name as key.
	GetClusterInfo() (map[string]Node, error)
}

Add number of pods to aggregator to identify empty machines. We might not need this when we add actual pod information.


//go:build android
// +build android

package platform

type Platform struct{}

const name = "platform"

func (self *Platform) Name() string {
	return name
}

func (self *Platform) Collect() (result interface{}, err error) {
	result, err = getPlatformInfo()
	return
}

func getPlatformInfo() (platformInfo map[string]string, err error) {

	return
}

func Get() (*Platform, []string, error) {
	return nil, nil, nil
}

Add missing android implementation for platform.Get()


// Based on aplay audio adaptor written by @colemanserious (https://github.com/colemanserious)

package audio

import (
	"testing"

	"github.com/hybridgroup/gobot/gobottest"
)

func TestAudioDriver(t *testing.T) {
	d := NewAudioDriver(NewAudioAdaptor("conn"), "dev", nil)

	gobottest.Assert(t, d.Name(), "dev")
	gobottest.Assert(t, d.Connection().Name(), "conn")

	gobottest.Assert(t, len(d.Start()), 0)

	gobottest.Assert(t, len(d.Halt()), 0)
}

func TestAudioDriverSoundWithNoFilename(t *testing.T) {
	d := NewAudioDriver(NewAudioAdaptor("conn"), "dev", nil)

	errors := d.Sound("")
	gobottest.Assert(t, errors[0].Error(), "Requires filename for audio file.")
}

Test coverage for execution of audio driver


package main

import (
	"flag"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"syscall"
)

var (
	path    string
	pidfile string
)

func init() {
	flag.StringVar(&path, "path", "/Database/branch/master/watch/com.docker.driver.amd64-linux.node/etc.node/docker.node/daemon.json.node/tree.live", "path of the file to watch")
	flag.StringVar(&pidfile, "pidfile", "/run/docker.pid", "pidfile for process to signal")
}

func main() {
	log.SetFlags(0)
	flag.Parse()

	watch, err := os.Open(path)
	if err != nil {
		log.Fatalln("Failed to open file", path, err)
	}
	buf := make([]byte, 512)
	for {
		_, err := watch.Read(buf)
		if err != nil {
			log.Fatalln("Error reading watch file", err)
		}
		bytes, err := ioutil.ReadFile(pidfile)
		pidstring := string(bytes[:])
		if err != nil {
			pid, err := strconv.Atoi(pidstring)
			if err != nil {
				syscall.Kill(pid, syscall.SIGHUP)
			}
		}
	}
}

package main

import (
	"flag"
	"io/ioutil"
	"log"
	"os"
	"strconv"
	"syscall"
)

var (
	path    string
	pidfile string
)

func init() {
	flag.StringVar(&path, "path", "/Database/branch/master/watch/com.docker.driver.amd64-linux.node/etc.node/docker.node/daemon.json.node/tree.live", "path of the file to watch")
	flag.StringVar(&pidfile, "pidfile", "/run/docker.pid", "pidfile for process to signal")
}

func main() {
	log.SetFlags(0)
	flag.Parse()

	watch, err := os.Open(path)
	if err != nil {
		log.Fatalln("Failed to open file", path, err)
	}
	// 43 bytes is the record size of the watch
	buf := make([]byte, 43)
	for {
		_, err := watch.Read(buf)
		if err != nil {
			log.Fatalln("Error reading watch file", err)
		}
		bytes, err := ioutil.ReadFile(pidfile)
		pidstring := string(bytes[:])
		if err != nil {
			pid, err := strconv.Atoi(pidstring)
			if err != nil {
				syscall.Kill(pid, syscall.SIGHUP)
			}
		}
	}
}

Read exactly 43 bytes from watch


// Command aws-gen-gocli parses a JSON description of an AWS API and generates a
// Go file containing a client for the API.
//
//     aws-gen-gocli EC2 apis/ec2/2014-10-01.api.json service/ec2/ec2.go
package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/awslabs/aws-sdk-go/model"
)

func main() {
	var svcPath string
	var forceService bool
	flag.StringVar(&svcPath, "path", "service", "generate in a specific directory (default: 'service')")
	flag.BoolVar(&forceService, "force", false, "force re-generation of PACKAGE/service.go")
	flag.Parse()

	api := os.Args[len(os.Args)-flag.NArg()]

	in, err := os.Open(api)
	if err != nil {
		panic(err)
	}
	defer in.Close()

	if err := model.Load(in); err != nil {
		panic(err)
	}

	if err := model.Generate(svcPath, forceService); err != nil {
		fmt.Fprintf(os.Stderr, "error generating %s\n", os.Args[1])
		panic(err)
	}
}

// Command aws-gen-gocli parses a JSON description of an AWS API and generates a
// Go file containing a client for the API.
//
//     aws-gen-gocli EC2 apis/ec2/2014-10-01.api.json service/ec2/ec2.go
package main

import (
	"flag"
	"fmt"
	"os"

	"github.com/awslabs/aws-sdk-go/model"
)

func main() {
	var svcPath string
	var forceService bool
	flag.StringVar(&svcPath, "path", "service", "generate in a specific directory (default: 'service')")
	flag.BoolVar(&forceService, "force", false, "force re-generation of PACKAGE/service.go")
	flag.Parse()
	api := flag.Arg(0)

	in, err := os.Open(api)
	if err != nil {
		panic(err)
	}
	defer in.Close()

	if err := model.Load(in); err != nil {
		panic(err)
	}

	if err := model.Generate(svcPath, forceService); err != nil {
		fmt.Fprintf(os.Stderr, "error generating %s\n", api)
		panic(err)
	}
}

Fix code that gets post-processed command-line args


package util

import (
	"os"
)

// FileExists returns true if path exists
func FileExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err != nil {
		if os.IsNotExist(err) {
			return false, nil
		}
		return false, err
	}
	return true, nil
}

func DirExists(path string) (bool, error) {
	fileInfo, err := os.Stat(path)
	if err != nil && os.IsNotExist(err) {
		return false, nil
	}

	return fileInfo.IsDir(), nil
}

package util

import (
	"os"
	"strings"
)

// FileExists returns true if path exists
func FileExists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err != nil {
		if isNotExistError(err) {
			return false, nil
		}

		return false, err
	}

	return true, nil
}

func DirExists(path string) (bool, error) {
	fileInfo, err := os.Stat(path)
	if err != nil {
		if isNotExistError(err) {
			return false, nil
		}

		return false, err
	}

	return fileInfo.IsDir(), nil
}

func isNotExistError(err error) bool {
	return os.IsNotExist(err) || IsNotADirectoryError(err)
}

func IsNotADirectoryError(err error) bool {
	return strings.HasSuffix(err.Error(), "not a directory")
}

Fix FileExists does not take into account "not a directory" error


package jsonpreprocess

import (
	"testing"
)

func TestUncomment(t *testing.T) {
	tests := []struct {
		name     string
		input    string
		expected string
	}{
		{"empty", ``, ``},
		{"spaces", " \t\n", " \t\n"},
		{"text", `[1, 2]`, `[1, 2]`},
		{"text with string", `{"foo": 1}`, `{"foo": 1}`},
		{"text with line comment ",
			`[1, 2] // this is a line comment`,
			`[1, 2] `},
		{"text with block comment ",
			"[1, 2, /* this is\na block comment */ 3]",
			"[1, 2,  3]"},
		{"text with string and comment",
			`{"url": "http://example.com"} // this is a line comment`,
			`{"url": "http://example.com"} `},
	}
	for _, test := range tests {
		actual, err := Uncomment(test.input)
		if err != nil {
			t.Fatal(err)
		}
		if actual != test.expected {
			t.Errorf("%s: got\n\t%+q\nexpected\n\t%q", test.name, actual, test.expected)
		}
	}
}

package jsonpreprocess

import (
	"testing"
)

func TestTrimComment(t *testing.T) {
	tests := []struct {
		name     string
		input    string
		expected string
	}{
		{"empty", ``, ``},
		{"spaces", " \t\n", " \t\n"},
		{"text", `[1, 2]`, `[1, 2]`},
		{"text with string", `{"foo": 1}`, `{"foo": 1}`},
		{"text with line comment ",
			`[1, 2] // this is a line comment`,
			`[1, 2] `},
		{"text with block comment ",
			"[1, 2, /* this is\na block comment */ 3]",
			"[1, 2,  3]"},
		{"text with string and comment",
			`{"url": "http://example.com"} // this is a line comment`,
			`{"url": "http://example.com"} `},
	}
	for _, test := range tests {
		actual, err := TrimComment(test.input)
		if err != nil {
			t.Fatal(err)
		}
		if actual != test.expected {
			t.Errorf("%s: got\n\t%+q\nexpected\n\t%q", test.name, actual, test.expected)
		}
	}
}

Rename forgotten Uncomment to TrimComment.


package auth

import (
	"github.com/robfig/revel"
	//_ "github.com/pjvds/acvte/modules/auth/routes"
)

type AuthenticatedResource struct {
	Resource interface{}
	Role     string
}

func init() {
	revel.OnAppStart(func() {

	})
}

var SessionAuthenticationFilter = func(c *revel.Controller, fc []revel.Filter) {
	c.Redirect()
}

func AclApply(m []AuthenticatedResource) {
	// revel.FilterController(controllers.Admin{}).
	//  Add(AuthenticationFilter)
	for _, a := range m {
		var fc revel.FilterConfigurator
		if reflect.TypeOf(a.Resource).Kind() == reflect.Func {
			// revel action
			fc = revel.FilterAction(a.Resource)
		} else {
			// revel controller
			fc = revel.FilterController(a.Resource)
		}
		fc.Add(SessionAuthenticationFilter)
	}
}

// func GetRole(u *models.User) string {
//     return "user"
// }

// func GetUser() *models.User {
//     u := new(models.User)
//     return u
// }

package auth

import (
	"github.com/robfig/revel"
	//_ "github.com/pjvds/acvte/modules/auth/routes"
)

type AuthenticatedResource struct {
	Resource interface{}
	Role     string
}

func init() {
	revel.OnAppStart(func() {

	})
}

var SessionAuthenticationFilter = func(c *revel.Controller, fc []revel.Filter) {
	// TODO: Fix redirect
	//c.Redirect()
}

func AclApply(m []AuthenticatedResource) {
	// revel.FilterController(controllers.Admin{}).
	//  Add(AuthenticationFilter)
	for _, a := range m {
		var fc revel.FilterConfigurator
		if reflect.TypeOf(a.Resource).Kind() == reflect.Func {
			// revel action
			fc = revel.FilterAction(a.Resource)
		} else {
			// revel controller
			fc = revel.FilterController(a.Resource)
		}
		fc.Add(SessionAuthenticationFilter)
	}
}

// func GetRole(u *models.User) string {
//     return "user"
// }

// func GetUser() *models.User {
//     u := new(models.User)
//     return u
// }

Mark c.Redirect as todo item


package steps

import (
	"github.com/mitchellh/multistep"
	"os"
	"os/exec"
	"testing"
)

func TestStepCloneRepo(t *testing.T) {
	env := make(map[string]interface{})
	env["path"] = "tmp"
	os.MkdirAll("tmp/pearkes/origin", 0777)

	// Create a fake repository to clone from
	cmdInit := exec.Command("git", "init", "tmp/pearkes/origin")
	// Commit to the repoistory to avoid warnings
	os.Create("tmp/pearkes/origin/test")
	cmdCommit := exec.Command("git", "commit", "-a", "-m", "'initial commit'")

	cmdInit.Run()
	cmdCommit.Run()

	repo := Repo{FullName: "pearkes/test", SSHUrl: "tmp/pearkes/origin"}
	env["repo"] = repo
	env["repo_state"] = "clone"

	step := &StepCloneRepo{}

	results := step.Run(env)

	if results != multistep.ActionContinue {
		t.Fatal("step did not return ActionContinue")
	}

	os.RemoveAll("tmp")
}

package steps

import (
	"github.com/mitchellh/multistep"
	"os"
	"os/exec"
	"testing"
)

func TestStepCloneRepo(t *testing.T) {
	env := make(map[string]interface{})
	env["path"] = "tmp"

	originPath := "tmp/pearkes/origin"

	os.MkdirAll(originPath, 0777)

	// Create a fake repository to clone from
	cmdInit := exec.Command("git", "init", originPath)

	// Commit to the repoistory to avoid warnings
	os.Create(originPath + "/test")
	cmdAdd := exec.Command("git", "add", "test")
	cmdAdd.Dir = originPath

	cmdCommit := exec.Command("git", "commit", "-m", "initial commit")
	cmdCommit.Dir = originPath

	cmdInit.Run()
	cmdAdd.Run()
	cmdCommit.Run()

	repo := Repo{FullName: "pearkes/test", SSHUrl: "../origin"}
	env["repo"] = repo
	env["repo_state"] = "clone"

	step := &StepCloneRepo{}

	results := step.Run(env)

	if results != multistep.ActionContinue {
		t.Fatal("step did not return ActionContinue")
	}

	os.RemoveAll("tmp")
}

Fix the clone path on the cloning test


// 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 graphs

// FindCelebrity returns an index into 2D slice f that represents a celebrity
// on the party who doesn't know no one. -1 is returned if such a celebrity
// doesn't exists in f or if a person exists who doesn't know the celebrity.
// The time complexity is O(n), and O(1) additional space is needed.
func FindCelebrity(f [][]bool) int {
	r, c := 0, 1 // c starts at 1 'cause that's start of diagonal where A<->A, B<->B, C<->C, ...
	for c < len(f) {
		if f[r][c] {
			r, c = c, c+1 // All candidates less then c are not celebrity candidates.
		} else {
			c++ // r is still a celebrity candidate but c is not.
		}
	}
	for _, status := range f[r] { // Check if selected candidate is really a celebrity.
		if status {
			return -1
		}
	}
	return r
}

// 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 graphs

// FindCelebrity returns an index into 2D slice f that represents a celebrity
// on the party who doesn't know no one. -1 is returned if such a celebrity
// doesn't exists in f or if a person exists who doesn't know the celebrity.
// The time complexity is O(n), and O(1) additional space is needed.
func FindCelebrity(f [][]bool) int {
	r, c := 0, 1 // c starts at 1 'cause it's after start of diagonal (A<->A, B<->B, C<->C, ...)
	for c < len(f) {
		if f[r][c] {
			r, c = c, c+1 // All candidates less then c are not celebrity candidates.
		} else {
			c++ // r is still a celebrity candidate but c is not.
		}
	}
	for _, status := range f[r] { // Check if selected candidate is really a celebrity.
		if status {
			return -1
		}
	}
	return r
}

Fix the comment of why column starts at 1


// Combinatoric is a simple Go port of the "combinatoric" parts of
// Python's itertools--specifically, combinations, permutations, and
// product.
//
// None of the iterators are threadsafe. Implement mutexes as required.
// Additionally, it should be assumed the return values for First and
// Next always share the same memory address. If return values must be
// persisted between iterations, copy them into another slice.
package combinatoric

// Iterator is the interface that wraps a basic iterator.
//
// Iterators are expected to track state and be able to calculate the
// number of iterations for a given implementation.
//
// First and Next should return nil when a result slice is not
// available.
type Iterator interface {
	First() []interface{}
	Next() []interface{}
	HasNext() bool
	Len() uint64
	Reset()
}

// Package combinatoric is a simple Go port of the "combinatoric" parts of
// Python's itertools--specifically, combinations, permutations, and
// product.
//
// None of the iterators are threadsafe. Implement mutexes as required.
// Additionally, it should be assumed the return values for First and
// Next always share the same memory address. If return values must be
// persisted between iterations, copy them into another slice.
package combinatoric

// Iterator is the interface that wraps a basic iterator.
//
// Iterators are expected to track state and be able to calculate the
// number of iterations for a given implementation.
//
// First and Next should return nil when a result slice is not
// available.
type Iterator interface {
	First() []interface{}
	Next() []interface{}
	HasNext() bool
	Len() uint64
	Reset()
}

Use correct package comment format


package scipipe

import (
	"testing"
)

const (
	TESTPATH = "somepath.txt"
)

func TestFileTargetPath(t *testing.T) {
	ft := NewFileTarget(TESTPATH)
	path := ft.GetPath()
	if path != TESTPATH {
		t.Errorf("Path not properly initialized! (Was", path, "but should be", TESTPATH)
	}
}

package scipipe

import (
	"github.com/stretchr/testify/assert"
	"testing"
)

const (
	TESTPATH = "somepath.txt"
)

func TestFileTargetPaths(t *testing.T) {
	ft := NewFileTarget(TESTPATH)
	assertPathsEqual(t, ft.GetPath(), TESTPATH)
	assertPathsEqual(t, ft.GetTempPath(), TESTPATH+".tmp")
	assertPathsEqual(t, ft.GetFifoPath(), TESTPATH+".fifo")
}

func assertPathsEqual(t *testing.T, path1 string, path2 string) {
	assert.Equal(t, path1, path2, "Wrong path returned! (Was", path1, "but should be", path2, ")")
}

Test more file path methods


package singleton

import(
	"errors"

	"golang.org/x/net/context"
)

var(
	ErrNoSuchEntity = errors.New("util/singleton: no such entity")
	ErrSingletonTooBig = errors.New("util/singleton: object too big to write")
)

type Singleton struct {
	Value []byte `datastore:",noindex"`
}

type SingletonProvider interface {
	ReadSingleton(ctx context.Context, name string, obj interface{}) error
	WriteSingleton(ctx context.Context, name string, obj interface{}) error
}

package singleton

import(
	"errors"

	"golang.org/x/net/context"
)

/*

type Foo struct {
  S string
}

sp := some.SingletonProvider{}

foo := Foo{S:"hello"}
err1 := sp.WriteSingleton(ctx, "Foo_007", &foo)

foo2 := Foo{}
err2 := sp.ReadSingleton(ctx, "Foo_007", &foo2)

*/

var(
	ErrNoSuchEntity = errors.New("util/singleton: no such entity")
	ErrSingletonTooBig = errors.New("util/singleton: object too big to write")
)

type Singleton struct {
	Value []byte `datastore:",noindex"`
}

type SingletonProvider interface {
	ReadSingleton(ctx context.Context, name string, obj interface{}) error
	WriteSingleton(ctx context.Context, name string, obj interface{}) error
}

Add reminder to use pointers all the time


package epub_test

import (
	"fmt"
	"log"

	"github.com/bmaupin/go-epub"
)

func ExampleAddImage() {
	// Create a new EPUB
	e := epub.NewEpub("My title")

	// Add an image from a local file
	img1Path, err := e.AddImage("testdata/gophercolor16x16.png", "go-gopher.png")
	if err != nil {
		log.Fatal(err)
	}

	// Add an image from a URL. The image filename is also optional
	img2Path, err := e.AddImage("https://golang.org/doc/gopher/gophercolor16x16.png", "")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(img1Path)
	fmt.Println(img2Path)

	// Output:
	// ../img/go-gopher.png
	// ../img/image0002.png
}

package epub_test

import (
	"fmt"
	"log"

	"github.com/bmaupin/go-epub"
)

func ExampleEpub_AddImage() {
	// Create a new EPUB
	e := epub.NewEpub("My title")

	// Add an image from a local file
	img1Path, err := e.AddImage("testdata/gophercolor16x16.png", "go-gopher.png")
	if err != nil {
		log.Fatal(err)
	}

	// Add an image from a URL. The image filename is also optional
	img2Path, err := e.AddImage("https://golang.org/doc/gopher/gophercolor16x16.png", "")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(img1Path)
	fmt.Println(img2Path)

	// Output:
	// ../img/go-gopher.png
	// ../img/image0002.png
}

Rename example so it gets picked up by godoc.org


package app

import (
	"database/sql"

	"github.com/goph/stdlib/errors"
	"github.com/goph/stdlib/log"
)

// ServiceOption sets options in the Service.
type ServiceOption func(s *Service)

// DB returns a ServiceOption that sets the DB object for the service.
func DB(db *sql.DB) ServiceOption {
	return func(s *Service) {
		s.db = db
	}
}

// Logger returns a ServiceOption that sets the logger for the service.
func Logger(l log.Logger) ServiceOption {
	return func(s *Service) {
		s.logger = l
	}
}

// ErrorHandler returns a ServiceOption that sets the error handler for the service.
func ErrorHandler(l errors.Handler) ServiceOption {
	return func(s *Service) {
		s.errorHandler = l
	}
}

// Service contains the main controller logic.
type Service struct {
	db *sql.DB

	logger       log.Logger
	errorHandler errors.Handler
}

// NewService creates a new service object.
func NewService(opts ...ServiceOption) *Service {
	s := new(Service)

	for _, opt := range opts {
		opt(s)
	}

	// Default logger
	if s.logger == nil {
		s.logger = log.NewNopLogger()
	}

	// Default error handler
	if s.errorHandler == nil {
		s.errorHandler = errors.NewNopHandler()
	}

	return s
}

package app

import (
	"database/sql"

	"github.com/goph/stdlib/errors"
	"github.com/goph/stdlib/log"
)

// ServiceOption sets options in the Service.
type ServiceOption func(s *Service)

// Logger returns a ServiceOption that sets the logger for the service.
func Logger(l log.Logger) ServiceOption {
	return func(s *Service) {
		s.logger = l
	}
}

// ErrorHandler returns a ServiceOption that sets the error handler for the service.
func ErrorHandler(l errors.Handler) ServiceOption {
	return func(s *Service) {
		s.errorHandler = l
	}
}

// Service contains the main controller logic.
type Service struct {
	db *sql.DB

	logger       log.Logger
	errorHandler errors.Handler
}

// NewService creates a new service object.
func NewService(db *sql.DB, opts ...ServiceOption) *Service {
	s := new(Service)

	s.db = db

	for _, opt := range opts {
		opt(s)
	}

	// Default logger
	if s.logger == nil {
		s.logger = log.NewNopLogger()
	}

	// Default error handler
	if s.errorHandler == nil {
		s.errorHandler = errors.NewNopHandler()
	}

	return s
}

Make db a required option


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

package backups_test

import (
	"sort"

	gc "launchpad.net/gocheck"

	"github.com/juju/juju/state/backups"
	"github.com/juju/juju/testing"
)

var getFilesToBackup = *backups.GetFilesToBackup

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

type sourcesSuite struct {
	testing.BaseSuite
}

func (s *sourcesSuite) TestGetFilesToBackup(c *gc.C) {
	files, err := getFilesToBackup()
	c.Assert(err, gc.IsNil)

	sort.Strings(files)
	c.Check(files, gc.DeepEquals, []string{
		"/etc/init/juju-db.conf",
		"/home/ubuntu/.ssh/authorized_keys",
		"/var/lib/juju/nonce.txt",
		"/var/lib/juju/server.pem",
		"/var/lib/juju/shared-secret",
		"/var/lib/juju/system-identity",
		"/var/lib/juju/tools",
		"/var/log/juju/all-machines.log",
		"/var/log/juju/machine-0.log",
	})
}

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

package backups_test

import (
	jc "github.com/juju/testing/checkers"
	gc "launchpad.net/gocheck"

	"github.com/juju/juju/state/backups"
	"github.com/juju/juju/testing"
)

var getFilesToBackup = *backups.GetFilesToBackup

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

type sourcesSuite struct {
	testing.BaseSuite
}

func (s *sourcesSuite) TestGetFilesToBackup(c *gc.C) {
	files, err := getFilesToBackup()
	c.Assert(err, gc.IsNil)

	c.Check(files, jc.SameContents, []string{
		"/etc/init/juju-db.conf",
		"/home/ubuntu/.ssh/authorized_keys",
		"/var/lib/juju/nonce.txt",
		"/var/lib/juju/server.pem",
		"/var/lib/juju/shared-secret",
		"/var/lib/juju/system-identity",
		"/var/lib/juju/tools",
		"/var/log/juju/all-machines.log",
		"/var/log/juju/machine-0.log",
	})
}

Use the SameContents checker in backups tests.


package model

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"time"
)

type Application struct {
	Id          bson.ObjectId `json:"id" bson:"_id,omitempty"`
	Userid      bson.ObjectId
	Name        string
	Secret      string
	Description string
}

/*
func (m *Application) serialize() map[string]interface{} {
	return map[string]interface{}{
			"name": m.Name,
			"appid": }
}*/
/*
func init() {
	c := Collection("app")
	c.EnsureIndex(mgo.Index{
		Key:        []string{"name"},
		Unique:     true,
		DropDups:   true,
		Background: true, // See notes.
		Sparse:     true,
	})
	c.EnsureIndex(mgo.Index{
		Key:        []string{"Userid"},
		DropDups:   true,
		Background: true, // See notes.
		Sparse:     true,
	})
}*/

func (m *Application) Save(session *mgo.Session) error {
	return AppCollection(session).Insert(m)
}

func Get(fromDate, toDate time.Time) interface{} {
	return nil
}

package model

import (
	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
	"time"
)

type Application struct {
	Id          bson.ObjectId `json:"id" bson:"_id,omitempty"`
	Userid      bson.ObjectId
	Name        string
	Secret      string
	Description string
}

func (m *Application) Save(session *mgo.Session) error {
	return AppCollection(session).Insert(m)
}

Remove some functions that not use


package i

import (
	. "github.com/alecthomas/chroma" // nolint
	"github.com/alecthomas/chroma/lexers/internal"
)

// Ini lexer.
var Ini = internal.Register(MustNewLexer(
	&Config{
		Name:      "INI",
		Aliases:   []string{"ini", "cfg", "dosini"},
		Filenames: []string{"*.ini", "*.cfg", "*.inf"},
		MimeTypes: []string{"text/x-ini", "text/inf"},
	},
	Rules{
		"root": {
			{`\s+`, Text, nil},
			{`[;#].*`, CommentSingle, nil},
			{`\[.*?\]$`, Keyword, nil},
			{`(.*?)([ \t]*)(=)([ \t]*)(.*(?:\n[ \t].+)*)`, ByGroups(NameAttribute, Text, Operator, Text, LiteralString), nil},
			{`(.+?)$`, NameAttribute, nil},
		},
	},
))

package i

import (
	. "github.com/alecthomas/chroma" // nolint
	"github.com/alecthomas/chroma/lexers/internal"
)

// Ini lexer.
var Ini = internal.Register(MustNewLexer(
	&Config{
		Name:      "INI",
		Aliases:   []string{"ini", "cfg", "dosini"},
		Filenames: []string{"*.ini", "*.cfg", "*.inf", ".gitconfig"},
		MimeTypes: []string{"text/x-ini", "text/inf"},
	},
	Rules{
		"root": {
			{`\s+`, Text, nil},
			{`[;#].*`, CommentSingle, nil},
			{`\[.*?\]$`, Keyword, nil},
			{`(.*?)([ \t]*)(=)([ \t]*)(.*(?:\n[ \t].+)*)`, ByGroups(NameAttribute, Text, Operator, Text, LiteralString), nil},
			{`(.+?)$`, NameAttribute, nil},
		},
	},
))

Add .gitconfig to Ini lexer filenames.


package terminal

/*
  Go 1.2 doesn't include Termios for FreeBSD. This should be added in
  1.3 and th is could be merged with terminal_darwin.
*/

import (
	"syscall"
)

const ioctlReadTermios = syscall.TIOCGETA

type termios struct {
	Iflag  uint32
	Oflag  uint32
	Cflag  uint32
	Lflag  uint32
	Cc     [20]uint8
	Ispeed uint32
	Ospeed uint32
}

package terminal

import (
	"syscall"
)

const ioctlReadTermios = syscall.TIOCGETA

/*
  Go 1.2 doesn't include Termios for FreeBSD. This should be added in
  1.3 and th is could be merged with terminal_darwin.
*/
type termios struct {
	Iflag  uint32
	Oflag  uint32
	Cflag  uint32
	Lflag  uint32
	Cc     [20]uint8
	Ispeed uint32
	Ospeed uint32
}

Move Termios note so it isn't taken as package comment.


package main

import (
	"fmt"
	"os"
	"testing"

	"github.com/nicksnyder/go-i18n/i18n"
	mylog "github.com/patrickalin/GoMyLog"
	"github.com/spf13/viper"
)

func TestSomething(t *testing.T) {
	viper.SetConfigName("config")
	viper.AddConfigPath(".")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf("%v", err)
	}
}
func TestMain(m *testing.M) {
	i18n.MustLoadTranslationFile("lang/en-US.all.json")
	i18n.MustLoadTranslationFile("lang/fr.all.json")
	mylog.Init(mylog.ERROR)

	os.Exit(m.Run())
}

func TestReadConfigFound(t *testing.T) {
	if err := readConfig("configForTest"); err != nil {
		fmt.Printf("%v", err)
	}
}

/*func TestReadConfigNotFound(t *testing.T) {
	if err := readConfig("configError"); err != nil {
		fmt.Printf("%v", err)
	}
}*/

package main

import (
	"fmt"
	"testing"

	"github.com/spf13/viper"
)

func TestSomething(t *testing.T) {
	viper.SetConfigName("config")
	viper.AddConfigPath(".")
	if err := viper.ReadInConfig(); err != nil {
		fmt.Printf("%v", err)
	}
}

/*
func TestMain(m *testing.M) {
	i18n.MustLoadTranslationFile("lang/en-US.all.json")
	i18n.MustLoadTranslationFile("lang/fr.all.json")
	mylog.Init(mylog.ERROR)

	os.Exit(m.Run())
}

func TestReadConfigFound(t *testing.T) {
	if err := readConfig("configForTest"); err != nil {
		fmt.Printf("%v", err)
	}
}*/

/*func TestReadConfigNotFound(t *testing.T) {
	if err := readConfig("configError"); err != nil {
		fmt.Printf("%v", err)
	}
}*/

Test + travis = error


package villa;

// CmpFunc is the function compares two elements.
type CmpFunc func(interface{}, interface{}) int

// IntCmpFunc is the function compares two int elements.
type IntCmpFunc func(int, int) int

// FloatCmpFunc is the function compares two float elements.
type FloatCmpFunc func(float64, float64) int

// ComplexCmpFunc is the function compares two complex128 elements.
type ComplexCmpFunc func(complex128, complex128) int

// IntValueCompare compares the input int values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
// This is a natual IntCmpFunc.
func IntValueCompare(a, b int) int {
    if a < b {
        return -1
    } else if a > b {
        return 1
    } // else if

    return 0
}

// FloatValueCompare compares the input float64 values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
// This is a natual FloatCmpFunc.
func FloatValueCompare(a, b float64) int {
    if a < b {
        return -1
    } else if a > b {
        return 1
    } // else if

    return 0
}

package villa;

// CmpFunc is the function compares two elements.
type CmpFunc func(interface{}, interface{}) int

// IntCmpFunc is the function compares two int elements.
type IntCmpFunc func(int, int) int

// FloatCmpFunc is the function compares two float elements.
type FloatCmpFunc func(float64, float64) int

// ComplexCmpFunc is the function compares two complex128 elements.
type ComplexCmpFunc func(complex128, complex128) int

// IntValueCompare compares the input int values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
// This is a natural IntCmpFunc.
func IntValueCompare(a, b int) int {
    if a < b {
        return -1
    } else if a > b {
        return 1
    } // else if

    return 0
}

// FloatValueCompare compares the input float64 values a and b, returns -1 if a < b, 1 if a > b, and 0 otherwise.
// This is a natural FloatCmpFunc.
func FloatValueCompare(a, b float64) int {
    if a < b {
        return -1
    } else if a > b {
        return 1
    } // else if

    return 0
}

FIX typo error on comments


package peerstore

import (
	core "github.com/libp2p/go-libp2p-core/peer"
	ma "github.com/multiformats/go-multiaddr"
)

// Deprecated: use github.com/libp2p/go-libp2p-core/peer.Info instead.
type PeerInfo = core.AddrInfo

// Deprecated: use github.com/libp2p/go-libp2p-core/peer.ErrInvalidAddr instead.
var ErrInvalidAddr = core.ErrInvalidAddr

// Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoFromP2pAddr instead.
func InfoFromP2pAddr(m ma.Multiaddr) (*core.AddrInfo, error) {
	return core.AddrInfoFromP2pAddr(m)
}

// Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoToP2pAddrs instead.
func InfoToP2pAddrs(pi *core.AddrInfo) ([]ma.Multiaddr, error) {
	return core.AddrInfoToP2pAddrs(pi)
}

package peerstore

import (
	core "github.com/libp2p/go-libp2p-core/peer"
	ma "github.com/multiformats/go-multiaddr"
)

// Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfo instead.
type PeerInfo = core.AddrInfo

// Deprecated: use github.com/libp2p/go-libp2p-core/peer.ErrInvalidAddr instead.
var ErrInvalidAddr = core.ErrInvalidAddr

// Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoFromP2pAddr instead.
func InfoFromP2pAddr(m ma.Multiaddr) (*core.AddrInfo, error) {
	return core.AddrInfoFromP2pAddr(m)
}

// Deprecated: use github.com/libp2p/go-libp2p-core/peer.AddrInfoToP2pAddrs instead.
func InfoToP2pAddrs(pi *core.AddrInfo) ([]ma.Multiaddr, error) {
	return core.AddrInfoToP2pAddrs(pi)
}

Correct path to peer.AddrInfo in deprecation


package parser

// This file contains any whitebox tests (with access to package internals), and wrappers
// to enable blackbox tests to set up environment.

// InitParserVersionForTest allows tests to rerun initParserVersion after initializing
// environment variables.
func InitParserVersionForTest() {
	initParserVersion()
}

package parser

// This file contains any whitebox tests (with access to package internals), and wrappers
// to enable blackbox tests to set up environment.

// InitParserVersionForTest allows tests to rerun initParserVersion after initializing
// environment variables.
// See https://groups.google.com/forum/#!topic/golang-nuts/v1TXLIRZjv4 and
// https://golang.org/src/net/http/export_test.go
var InitParserVersionForTest = initParserVersion

Add link to go-nuts discussion


package fasthttp

import (
	"bufio"
	"io"
	"runtime/debug"
	"sync"
)

// StreamWriter must write data to w.
//
// Usually StreamWriter writes data to w in a loop (aka 'data streaming').
//
// StreamWriter must return immediately if w returns error.
//
// Since the written data is buffered, do not forget calling w.Flush
// when the data must be propagated to reader.
type StreamWriter func(w *bufio.Writer)

// NewStreamReader returns a reader, which replays all the data generated by sw.
//
// The returned reader may be passed to Response.SetBodyStream.
//
// See also Response.SetBodyStreamWriter.
func NewStreamReader(sw StreamWriter) io.Reader {
	pr, pw := io.Pipe()

	var bw *bufio.Writer
	v := streamWriterBufPool.Get()
	if v == nil {
		bw = bufio.NewWriter(pw)
	} else {
		bw = v.(*bufio.Writer)
		bw.Reset(pw)
	}

	go func() {
		defer func() {
			if r := recover(); r != nil {
				defaultLogger.Printf("panic in StreamWriter: %s\nStack trace:\n%s", r, debug.Stack())
			}
		}()

		sw(bw)
		bw.Flush()
		pw.Close()

		streamWriterBufPool.Put(bw)
	}()

	return pr
}

var streamWriterBufPool sync.Pool

package fasthttp

import (
	"bufio"
	"io"
	"runtime/debug"
	"sync"
)

// StreamWriter must write data to w.
//
// Usually StreamWriter writes data to w in a loop (aka 'data streaming').
//
// StreamWriter must return immediately if w returns error.
//
// Since the written data is buffered, do not forget calling w.Flush
// when the data must be propagated to reader.
type StreamWriter func(w *bufio.Writer)

// NewStreamReader returns a reader, which replays all the data generated by sw.
//
// The returned reader may be passed to Response.SetBodyStream.
//
// Close must be called on the returned reader after after all the required data
// has been read. Otherwise goroutine leak may occur.
//
// See also Response.SetBodyStreamWriter.
func NewStreamReader(sw StreamWriter) io.ReadCloser {
	pr, pw := io.Pipe()

	var bw *bufio.Writer
	v := streamWriterBufPool.Get()
	if v == nil {
		bw = bufio.NewWriter(pw)
	} else {
		bw = v.(*bufio.Writer)
		bw.Reset(pw)
	}

	go func() {
		defer func() {
			if r := recover(); r != nil {
				defaultLogger.Printf("panic in StreamWriter: %s\nStack trace:\n%s", r, debug.Stack())
			}
		}()

		sw(bw)
		bw.Flush()
		pw.Close()

		streamWriterBufPool.Put(bw)
	}()

	return pr
}

var streamWriterBufPool sync.Pool

Document that Close must be called on the reader returned from NewStreamReader


package main

import (
	"log"
	"net/http"

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

func killBrowserHandler(c *gin.Context) {

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

	c.BindJSON(&data)

	command, err := findBrowser(data.Process)

	log.Println(command)

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

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

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

}

package main

import (
	"errors"
	"net/http"

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

func killBrowserHandler(c *gin.Context) {

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

	c.BindJSON(&data)

	if data.Process != "chrome" && data.Process != "chrom" {
		c.JSON(http.StatusBadRequest, errors.New("You can't kill the process"+data.Process))
		return
	}

	command, err := findBrowser(data.Process)

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

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

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

}

Add a bit of safeguard against malicious attacks


package main

// IIIFInfo represents the simplest possible data to provide a valid IIIF
// information JSON response
type IIIFInfo struct {
	Context  string   `json:"@context"`
	ID       string   `json:"@id"`
	Protocol string   `json:"protocol"`
	Width    int      `json:"width"`
	Height   int      `json:"height"`
	Profile  []string `json:"profile"`
}

// Creates the default structure for converting to the IIIF Information JSON.
// The handler is responsible for filling in ID and dimensions.
func NewIIIFInfo() *IIIFInfo {
	return &IIIFInfo{
		Context:  "http://iiif.io/api/image/2/context.json",
		Protocol: "http://iiif.io/api/image",
		Profile:  []string{"http://iiif.io/api/image/2/level1.json"},
	}
}

package main

type tiledata struct {
	Width        int   `json:"width"`
	Height       int   `json:"height,omitempty"`
	ScaleFactors []int `json:"scaleFactors"`
}

// IIIFInfo represents the simplest possible data to provide a valid IIIF
// information JSON response
type IIIFInfo struct {
	Context  string     `json:"@context"`
	ID       string     `json:"@id"`
	Protocol string     `json:"protocol"`
	Width    int        `json:"width"`
	Height   int        `json:"height"`
	Profile  []string   `json:"profile"`
	Tiles    []tiledata `json:"tiles"`
}

// Creates the default structure for converting to the IIIF Information JSON.
// The handler is responsible for filling in ID and dimensions.
func NewIIIFInfo() *IIIFInfo {
	return &IIIFInfo{
		Context:  "http://iiif.io/api/image/2/context.json",
		Protocol: "http://iiif.io/api/image",
		Profile:  []string{"http://iiif.io/api/image/2/level1.json"},
		Tiles:    []tiledata{
			tiledata{Width: 256, ScaleFactors: []int{1, 2, 4, 8, 16, 32, 64}},
			tiledata{Width: 512, ScaleFactors: []int{1, 2, 4, 8, 16, 32, 64}},
			tiledata{Width: 1024, ScaleFactors: []int{1, 2, 4, 8, 16, 32, 64}},
		},
	}
}

Add some totally arbitrary tile sizes to IIIF


package main

import (
    "github.com/bwmarrin/discordgo"
    Logger "./logger"
    "os"
    "os/signal"
    redis "gopkg.in/redis.v5"
    "github.com/Jeffail/gabs"
)

var (
    config *gabs.Container
    rcli *redis.Client
)

func main() {
    Logger.INF("Bootstrapping...")

    // Read config
    config = GetConfig("config.json")

    // Connect to DB
    rcli = redis.NewClient(&redis.Options{
        Addr: config.Path("redis").Data().(string),
        DB: 0,
    })

    _, err := rcli.Ping().Result()
    if err != nil {
        Logger.ERR("Cannot connect to redis!")
        os.Exit(1)
    }

    // Connect and add event handlers
    discord, err := discordgo.New(config.Path("discord.token").Data().(string))
    if err != nil {
        panic(err)
    }

    discord.AddHandler(onReady)
    discord.AddHandler(onMessageCreate)

    err = discord.Open()
    if err != nil {
        panic(err)
    }

    // Make a channel that waits for a os signal
    channel := make(chan os.Signal, 1)
    signal.Notify(channel, os.Interrupt, os.Kill)

    <-channel

    Logger.WRN("The OS is killing me :c")
    Logger.WRN("Disconnecting...")
    discord.Close()
}

package main

import (
    "github.com/bwmarrin/discordgo"
    Logger "./logger"
    "os"
    "os/signal"
    "github.com/Jeffail/gabs"
)

var (
    config *gabs.Container
)

func main() {
    Logger.INF("Bootstrapping...")

    // Read config
    config = GetConfig("config.json")

/*
    // Connect to DB
    ConnectDB(
        config.Path("mongo.url").Data().(string),
        config.Path("mongo.db").Data().(string),
    )
*/

    // Connect and add event handlers
    discord, err := discordgo.New("Bot " + config.Path("discord.token").Data().(string))
    if err != nil {
        panic(err)
    }

    discord.AddHandler(onReady)
    discord.AddHandler(onMessageCreate)

    err = discord.Open()
    if err != nil {
        panic(err)
    }

    // Make a channel that waits for a os signal
    channel := make(chan os.Signal, 1)
    signal.Notify(channel, os.Interrupt, os.Kill)

    <-channel

    Logger.WRN("The OS is killing me :c")
    Logger.WRN("Disconnecting...")
    discord.Close()
}

Switch from redis to mongo


package xml

type TextNode struct {
	*XmlNode
}

package xml

/*
#include "helper.h"
#include <string.h>
const xmlChar xmlStringTextNoenc[] = { 't', 'e', 'x', 't', 'n', 'o', 'e', 'n', 'c', 0 };
const xmlChar* disableEscaping = xmlStringTextNoenc;
*/
import "C"

type TextNode struct {
	*XmlNode
}

// DisableOutputEscaping disables the usual safeguards against creating invalid XML and allows the
// characters '<', '>', and '&' to be written out verbatim. Normally they are safely escaped as entities.
//
// This API is intended to provide support for XSLT processors and similar XML manipulation libraries that
// may need to output unsupported entity references or use the XML API for non-XML output. It should never
// be used in the normal course of XML processing.
func (node *TextNode) DisableOutputEscaping() {
	node.Ptr.name = C.disableEscaping
}

Allow output escaping to be disabled on an xml.TextNode


package transport

import (
	"github.com/sirupsen/logrus"
	"github.com/linuxkit/virtsock/pkg/vsock"
	"github.com/pkg/errors"
)

const (
	vmaddrCidHost = 2
	vmaddrCidAny  = 0xffffffff
)

// VsockTransport is an implementation of Transport which uses vsock
// sockets.
type VsockTransport struct{}

var _ Transport = &VsockTransport{}

// Dial accepts a vsock socket port number as configuration, and
// returns an unconnected VsockConnection struct.
func (t *VsockTransport) Dial(port uint32) (Connection, error) {
	logrus.Infof("vsock Dial port (%d)", port)

	conn, err := vsock.Dial(vmaddrCidHost, port)
	if err != nil {
		return nil, errors.Wrap(err, "failed connecting the VsockConnection")
	}
	logrus.Infof("vsock Connect port (%d)", port)

	return conn, nil
}

package transport

import (
	"fmt"
	"time"

	"github.com/linuxkit/virtsock/pkg/vsock"
	"github.com/sirupsen/logrus"
)

const (
	vmaddrCidHost = 2
	vmaddrCidAny  = 0xffffffff
)

// VsockTransport is an implementation of Transport which uses vsock
// sockets.
type VsockTransport struct{}

var _ Transport = &VsockTransport{}

// Dial accepts a vsock socket port number as configuration, and
// returns an unconnected VsockConnection struct.
func (t *VsockTransport) Dial(port uint32) (Connection, error) {
	// HACK: Remove loop when vsock bugs are fixed!
	// Retry 10 times because vsock.Dial can return connection time out
	// due to some underlying kernel bug.
	for i := 0; i < 10; i++ {
		logrus.Infof("vsock Dial port (%d)", port)
		conn, err := vsock.Dial(vmaddrCidHost, port)
		if err == nil {
			logrus.Infof("vsock Connect port (%d)", port)
			return conn, nil
		}

		// The virtsock wrapper eats up the syscall error, so we can't distinguish ETIMEDOUT from
		// other errors, so just sleep and try again
		time.Sleep(100 * time.Millisecond)
	}
	return nil, fmt.Errorf("failed connecting the VsockConnection: can't connect after 10 attempts")
}

Add a retry when connecting stdin/stdout/stderr


package main

import "os"
import "fmt"
import "net"
import "bufio"
import "bytes"

import "github.com/UniversityRadioYork/ury-rapid-go/tokeniser"

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:1350")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	t := tokeniser.NewTokeniser()
	for {
		data, err := bufio.NewReader(conn).ReadBytes('\n')
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		lines := t.Parse(data)
		buffer := new(bytes.Buffer)
		for _, line := range lines {
			for _, word := range line {
				buffer.WriteString(word + " ")
			}
			fmt.Println(buffer.String())
		}
	}
}

package main

import "os"
import "fmt"
import "net"
import "bufio"
import "bytes"

import "github.com/UniversityRadioYork/ury-rapid-go/baps3protocol"

func main() {
	conn, err := net.Dial("tcp", "127.0.0.1:1350")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	t := baps3protocol.NewTokeniser()
	for {
		data, err := bufio.NewReader(conn).ReadBytes('\n')
		if err != nil {
			fmt.Println(err)
			os.Exit(1)
		}
		lines := t.Parse(data)
		buffer := new(bytes.Buffer)
		for _, line := range lines {
			for _, word := range line {
				buffer.WriteString(word + " ")
			}
			fmt.Println(buffer.String())
		}
	}
}

Use baps3protocol package, not old tokeniser


package text

// This package contains strings to be used in error messages and calls to
// action for the enterprise product.

const (
	// OpenSourceProduct is the name of opensource Pachyderm.
	OpenSourceProduct = "Pachyderm Community Edition"
	// EnterpriseProduct is the name of enterprise Pachyderm.
	EnterpriseProduct = "Pachyderm Enterprise"
	// ActivateCTA is a CTA to users to enter their enterprise keys.
	ActivateCTA = "Use the command `pachctl enterprise activate` to enter your key."
	// RegisterCTA is a CTA to users to register for an enterprise key.
	RegisterCTA = `Pachyderm offers readily available activation keys for proofs-of-concept, startups, academic, nonprofit, or open-source projects. Tell us about your project to get one.

Learn about Pachyderm Enterprise here:

https://www.pachyderm.com/trial`
)

package text

// This package contains strings to be used in error messages and calls to
// action for the enterprise product.

const (
	// OpenSourceProduct is the name of opensource Pachyderm.
	OpenSourceProduct = "Pachyderm Community Edition"
	// EnterpriseProduct is the name of enterprise Pachyderm.
	EnterpriseProduct = "Pachyderm Enterprise"
	// ActivateCTA is a CTA to users to enter their enterprise keys.
	ActivateCTA = "Use the command `pachctl license activate` to enter your key."
	// RegisterCTA is a CTA to users to register for an enterprise key.
	RegisterCTA = `Pachyderm offers readily available activation keys for proofs-of-concept, startups, academic, nonprofit, or open-source projects. Tell us about your project to get one.

Learn about Pachyderm Enterprise here:

https://www.pachyderm.com/trial`
)

Fix error message for community edition


package ratelimit

import "time"

type basicLimiter struct {
	t   *time.Ticker
	bc  ByteCount
	cbc chan ByteCount
}

func (bl *basicLimiter) Start() {
	for {
		<-bl.t.C
		bl.cbc <- bl.bc
	}
}

func (bl basicLimiter) GetLimit() <-chan ByteCount {
	return bl.cbc
}

const TIME_UNIT = 50 * time.Millisecond

//BasicLimiter will divvy up the bytes into 100 smaller parts to spread the load
//across time
func BasicLimiter(b ByteCount, t time.Duration) Limiter {
	bl := &basicLimiter{
		t:   time.NewTicker(TIME_UNIT),
		bc:  b / ByteCount(t/TIME_UNIT),
		cbc: make(chan ByteCount),
	}
	go bl.Start()
	return bl
}

package ratelimit

import "time"

type basicLimiter struct {
	t   *time.Ticker
	bc  ByteCount
	cbc chan ByteCount
}

func (bl *basicLimiter) Start() {
	for {
		<-bl.t.C
		bl.cbc <- bl.bc
	}
}

func (bl basicLimiter) GetLimit() <-chan ByteCount {
	return bl.cbc
}

const timeSlice = 20 * time.Millisecond

//BasicLimiter will divvy up the bytes into 100 smaller parts to spread the load
//across time
func BasicLimiter(b ByteCount, t time.Duration) Limiter {
	bl := &basicLimiter{
		t:   time.NewTicker(timeSlice),
		bc:  b / ByteCount(t/timeSlice),
		cbc: make(chan ByteCount),
	}
	go bl.Start()
	return bl
}

Rename constant for appropriate metering of bursts


package client

import "net"

type Client struct {
	conn net.Conn
}

func NewClient(o *Options) (*Client, error) {
	conn, err := o.getDialer()()
	return &Client{
		conn: conn,
	}, err
}

func (c *Client) Cmd(args ...interface{}) (r *Reply) {
	return
}

func (c *Client) Close() {
	if c.conn != nil {
		c.conn.Close()
	}
}

func (c *Client) send(args []interface{}) (err error) {
	return
}

func (c *Client) recv() (r *Reply) {
	return
}

Define empty methods:Cmd, send and recv.


package events

import (
	"fmt"
	"strconv"
	"strings"
	"time"
)

type Event struct {
	Time time.Time
	Data map[string]*float64
	// TODO: change to map[string]struct{}
	Tags []string
}

func NewEvent(data map[string]*float64) *Event {
	return &Event{Time: time.Now(), Data: data, Tags: make([]string, 0)}
}

func (e *Event) AddTag(t string) {
	e.Tags = append(e.Tags, t)
}

func (e *Event) IsRedAlert() bool {
	for _, tag := range e.Tags {
		if tag == "redalert" {
			return true
		}
	}
	return false
}

func (e *Event) HasTag(t string) bool {
	for _, tag := range e.Tags {
		if tag == t {
			return true
		}
	}
	return false
}

func (e *Event) DisplayMetric(metric string) string {
	if e.Data[metric] == nil {
		return ""
	}
	return strconv.FormatFloat(*e.Data[metric], 'f', 1, 64)
}

func (e *Event) DisplayTags() string {
	if e == nil {
		return ""
	}
	// if e.Tags == nil {
	// 	return ""
	// }
	fmt.Println(e)
	return strings.Join(e.Tags, " ")
}

package events

import (
	"strconv"
	"strings"
	"time"
)

type Event struct {
	Time time.Time
	Data map[string]*float64
	// TODO: change to map[string]struct{}
	Tags []string
}

func NewEvent(data map[string]*float64) *Event {
	return &Event{Time: time.Now(), Data: data, Tags: make([]string, 0)}
}

func (e *Event) AddTag(t string) {
	e.Tags = append(e.Tags, t)
}

func (e *Event) IsRedAlert() bool {
	for _, tag := range e.Tags {
		if tag == "redalert" {
			return true
		}
	}
	return false
}

func (e *Event) HasTag(t string) bool {
	for _, tag := range e.Tags {
		if tag == t {
			return true
		}
	}
	return false
}

func (e *Event) DisplayMetric(metric string) string {
	if e.Data[metric] == nil {
		return ""
	}
	return strconv.FormatFloat(*e.Data[metric], 'f', 1, 64)
}

func (e *Event) DisplayTags() string {
	// required as used in template
	if e == nil {
		return ""
	}
	return strings.Join(e.Tags, " ")
}

Add comment for check for nil receiver.


package main

import (
	log "github.com/sirupsen/logrus"
	firego "gopkg.in/zabawaba99/firego.v1"
)

func apiRemove(path string) {
	f := firego.New(baseURL+"/"+path, nil)
	f.Auth(authToken)
	defer f.Unauth()
	if err := f.Remove(); err != nil {
		log.Fatal(err)
	}
}

func apiSet(path string, data interface{}) {
	f := firego.New(baseURL+"/"+path, nil)
	//log.Debug("F set url:" + baseURL + "/" + path)
	f.Auth(authToken)
	//log.Debug("F token set token:" + authToken)
	defer f.Unauth()
	//log.Debug("F sending")
	if err := f.Set(data); err != nil {
		//log.Debug("F sending error")
		log.Fatal(err)
	}
	//log.Debug("F send success")
}

package main

import (
	log "github.com/sirupsen/logrus"
	firego "gopkg.in/zabawaba99/firego.v1"
)

//TODO detectr fail and replay
//TODO queu FIFO message in order to recover from tiemout and keep message in track

func apiRemove(path string) {
	f := firego.New(baseURL+"data/"+path, nil)
	f.Auth(authToken)
	defer f.Unauth()
	if err := f.Remove(); err != nil {
		log.Fatal(err)
	}
}

func apiSet(path string, data interface{}) {
	f := firego.New(baseURL+"data/"+path, nil)
	//log.Debug("F set url:" + baseURL + "/" + path)
	f.Auth(authToken)
	//log.Debug("F token set token:" + authToken)
	defer f.Unauth()
	//log.Debug("F sending")
	if err := f.Set(data); err != nil {
		//log.Debug("F sending error")
		log.Fatal(err)
	}
	//log.Debug("F send success")
}

Add data/ in relative base path to separte from futur cahnge like config


// errchk $G $D/$F.go

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	OS "os"  // should require semicolon here; this is no different from other decls
	IO "io"
)

func main() {
}

// errchk $G $D/$F.go

// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package main

import (
	OS "os"  // should require semicolon here; this is no different from other decls
	IO "io"  // ERROR "missing"
)

func main() {
}

Add ERROR comment for errmsg to look for.


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

package hugolib

import (
	"testing"
)

// Issue #1123
// Testing prevention of cyclic refs in JSON encoding
// May be smart to run with: -timeout 4000ms
func TestEncodePage(t *testing.T) {
	t.Parallel()

	templ := `{{ index .Site.RegularPages 0 | jsonify }}`

	b := newTestSitesBuilder(t)
	b.WithSimpleConfigFile().WithTemplatesAdded("index.html", templ)
	b.WithContent("page.md", `---
title: "Page"
date: 2019-02-28
---

Content.

`)

	b.Build(BuildCfg{})

	b.AssertFileContent("public/index.html", `"Date":"2019-02-28T00:00:00Z"`)

}

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

package hugolib

import (
	"testing"
)

// Issue #1123
// Testing prevention of cyclic refs in JSON encoding
// May be smart to run with: -timeout 4000ms
func TestEncodePage(t *testing.T) {
	t.Parallel()

	templ := `Page: |{{ index .Site.RegularPages 0 | jsonify }}|
Site: {{ site | jsonify }}
`

	b := newTestSitesBuilder(t)
	b.WithSimpleConfigFile().WithTemplatesAdded("index.html", templ)
	b.WithContent("page.md", `---
title: "Page"
date: 2019-02-28
---

Content.

`)

	b.Build(BuildCfg{})

	b.AssertFileContent("public/index.html", `"Date":"2019-02-28T00:00:00Z"`)

}

Add a simple test for jsonify of Site


// Copyright 2013-2016 Adam Presley. All rights reserved
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.

package global

import "github.com/mailslurper/libmailslurper/storage"

const (
	// Version of the MailSlurper Server application
	SERVER_VERSION string = "1.9"
	DEBUG_ASSETS   bool   = true
)

var Database storage.IStorage

// Copyright 2013-2016 Adam Presley. All rights reserved
// Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.

package global

import "github.com/mailslurper/libmailslurper/storage"

const (
	// Version of the MailSlurper Server application
	SERVER_VERSION string = "1.9"
	DEBUG_ASSETS   bool   = false
)

var Database storage.IStorage

Debug mode off by default


// Copyright 2010 The W32 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package w32

import (
    "fmt"
    "syscall"
    "unicode/utf16"
    "unsafe"
)

func MakeIntResource(id uint16) *uint16 {
    return (*uint16)(unsafe.Pointer(uintptr(id)))
}

func LOWORD(dw uint) uint16 {
    return uint16(dw)
}

func HIWORD(dw uint) uint16 {
    return uint16(dw >> 16 & 0xffff)
}

func BoolToBOOL(value bool) BOOL {
	if value {
		return 1
	}

	return 0
}

func UTF16PtrToString(cstr *uint16) string {
    if cstr != nil {
        us := make([]uint16, 0, 256)
        for p := uintptr(unsafe.Pointer(cstr)); ; p += 2 {
            u := *(*uint16)(unsafe.Pointer(p))
            if u == 0 {
                return string(utf16.Decode(us))
            }
            us = append(us, u)
        }
    }

    return ""
}

// Copyright 2010 The W32 Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package w32

import (
    "unicode/utf16"
    "unsafe"
)

func MakeIntResource(id uint16) *uint16 {
    return (*uint16)(unsafe.Pointer(uintptr(id)))
}

func LOWORD(dw uint) uint16 {
    return uint16(dw)
}

func HIWORD(dw uint) uint16 {
    return uint16(dw >> 16 & 0xffff)
}

func BoolToBOOL(value bool) BOOL {
	if value {
		return 1
	}

	return 0
}

func UTF16PtrToString(cstr *uint16) string {
    if cstr != nil {
        us := make([]uint16, 0, 256)
        for p := uintptr(unsafe.Pointer(cstr)); ; p += 2 {
            u := *(*uint16)(unsafe.Pointer(p))
            if u == 0 {
                return string(utf16.Decode(us))
            }
            us = append(us, u)
        }
    }

    return ""
}

Remove import reference of "fmt" and "syscall".


package server_test

import (
	"github.com/concourse/skymarshal/bitbucket/server"
	"github.com/concourse/skymarshal/provider"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Bitbucket Server Provider", func() {
	Describe("AuthMethod", func() {
		var (
			authMethod provider.AuthMethod
			authConfig *server.AuthConfig
		)
		BeforeEach(func() {
			authConfig = &server.AuthConfig{}
			authMethod = authConfig.AuthMethod("http://bum-bum-bum.com", "dudududum")
		})

		It("creates a path for route", func() {
			Expect(authMethod).To(Equal(provider.AuthMethod{
				Type:        provider.AuthTypeOAuth,
				DisplayName: "Bitbucket Server",
				AuthURL:     "http://bum-bum-bum.com/auth/v1/bitbucket-server?team_name=dudududum",
			}))
		})
	})
})

package server_test

import (
	"github.com/concourse/skymarshal/bitbucket/server"
	"github.com/concourse/skymarshal/provider"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Bitbucket Server Provider", func() {
	Describe("AuthMethod", func() {
		var (
			authMethod provider.AuthMethod
			authConfig *server.AuthConfig
		)
		BeforeEach(func() {
			authConfig = &server.AuthConfig{}
			authMethod = authConfig.AuthMethod("http://bum-bum-bum.com", "dudududum")
		})

		It("creates a path for route", func() {
			Expect(authMethod).To(Equal(provider.AuthMethod{
				Type:        provider.AuthTypeOAuth,
				DisplayName: "Bitbucket Server",
				AuthURL:     "http://bum-bum-bum.com/oauth/v1/bitbucket-server?team_name=dudududum",
			}))
		})
	})
})

Fix accidental oauth/v1 route rename in bitbucket test


package lua

func (L Lua) CloneTo(newL Lua) error {
	L.GetGlobal("_G")
	defer L.Pop(1)
	err := L.ForInDo(-1, func(src Lua) error {
		if !src.IsString(-2) {
			return nil
		}
		key, err := src.ToString(-2)
		if err != nil {
			return err
		}
		println("KEY=", key)

		// If new instance has already the member, pass it.
		newL.GetGlobal(key)
		defer newL.Pop(1)
		if !newL.IsNil(-1) {
			return nil
		}
		println("not found and copy")
		val, err := src.ToPushable(-1)
		if err != nil {
			return err
		}
		println("push to new instance")
		val.Push(newL)
		newL.SetGlobal(key)
		return nil
	})
	return err
}

func (L Lua) Clone() (Lua, error) {
	newL, err := New()
	if err != nil {
		return Lua(0), err
	}
	newL.OpenLibs()
	err = L.CloneTo(newL)
	return newL, err
}

package lua

func (L Lua) CloneTo(newL Lua) error {
	L.GetGlobal("_G")
	defer L.Pop(1)
	err := L.ForInDo(-1, func(src Lua) error {
		if !src.IsString(-2) {
			return nil
		}
		key, err := src.ToString(-2)
		if err != nil {
			return err
		}
		//println("KEY=", key)

		// If new instance has already the member, pass it.
		newL.GetGlobal(key)
		defer newL.Pop(1)
		if !newL.IsNil(-1) {
			return nil
		}
		//println("not found and copy")
		val, err := src.ToPushable(-1)
		if err != nil {
			return err
		}
		//println("push to new instance")
		val.Push(newL)
		newL.SetGlobal(key)
		return nil
	})
	return err
}

func (L Lua) Clone() (Lua, error) {
	newL, err := New()
	if err != nil {
		return Lua(0), err
	}
	newL.OpenLibs()
	err = L.CloneTo(newL)
	return newL, err
}

Comment out debug-print in lua.Lua.Clone()


package minion

import (
	"time"

	"code.google.com/p/go-uuid/uuid"
)

type Minion interface {
	// Get minion identifier
	GetUUID() uuid.UUID

	// Set name of minion
	SetName(name string) error

	// Get name of minion
	GetName() (string, error)

	// Set the time the minion was last seen in seconds since the Epoch
	SetLastseen(s int64) error

	// Get a classifier for a minion
	GetClassifier(key string) (string, error)

	// Classify minion a with given a key and value
	SetClassifier(key, value, description string) error

	// Runs periodic functions, e.g. refreshes classifies and lastseen
	Refresh(t *time.Ticker) error

	// Start serving
	Serve() error
}

package minion

import (
	"time"

	"code.google.com/p/go-uuid/uuid"
)

type Minion interface {
	// Get minion identifier
	GetUUID() uuid.UUID

	// Set name of minion
	SetName(name string) error

	// Get name of minion
	GetName() (string, error)

	// Set the time the minion was last seen in seconds since the Epoch
	SetLastseen(s int64) error

	// Get a classifier for a minion
	GetClassifier(key string) (MinionClassifier, error)

	// Classify minion a with given a key and value
	SetClassifier(c MinionClassifier) error

	// Runs periodic functions, e.g. refreshes classifies and lastseen
	Refresh(t *time.Ticker) error

	// Listens for new tasks and processes them
	TaskListener(c chan<- int) error

	// Start serving
	Serve() error
}

type MinionTask interface {
	// Gets the command to be executed
	GetCommand() (string, error)

	// Gets the time the task was sent for processing
	GetTimestamp() (int64, error)
}

Add TaskListener method to the required methods for implementing Minion interface


package testhelpers

import "fmt"

const (
	// ERROR MESSAGEs - Used as first argument in Error() call
	EM_NEED_ERR = "Should have gotten an error, but didn't"
	EM_UN_ERR   = "Unexpected Error"

	// ERROR STRINGS - embed in
	// Could use a VAR block, fmt and %8s, but this is just as easy
	ES_EXPECTED = "\nexpected:"
	ES_GOT      = "\n  actual:"
	ES_ARGS     = "\n    args:"
	ES_SQL      = "\n     sql:"
	ES_ERR      = "\n     err:"
	ES_VALUE    = "\n   value:"
	ES_COUNT    = "\n   count:"
)

// Supply expected and actual values and a pretty formatted string will be returned that can be passed into t.Error()
func NotEqualMsg(expected, actual interface{}) string {
	return fmt.Sprintln(ES_EXPECTED, expected, ES_GOT, actual)
}

// Same as NotEqualMsg, except that the type names will be printed instead
func TypeNotEqualMsg(expected, actual interface{}) string {
	eType := TypeName(expected)
	aType := TypeName(actual)
	return fmt.Sprintln(ES_EXPECTED, eType, ES_GOT, aType)
}

func UnexpectedErrMsg(err string) string {
	return fmt.Sprintln(EM_UN_ERR, ES_ERR, err)
}

package testhelpers

import "fmt"

const (
	// ERROR MESSAGEs - Used as first argument in Error() call
	EM_NEED_ERR = "Should have gotten an error, but didn't"
	EM_UN_ERR   = "Unexpected Error"

	// ERROR STRINGS - embed in
	// Could use a VAR block, fmt and %8s, but this is just as easy
	ES_EXPECTED = "\nexpected:"
	ES_GOT      = "\n  actual:"
	ES_ARGS     = "\n    args:"
	ES_SQL      = "\n     sql:"
	ES_ERR      = "\n     err:"
	ES_VALUE    = "\n   value:"
	ES_COUNT    = "\n   count:"
)

// Supply expected and actual values and a pretty formatted string will be returned that can be passed into t.Error()
func NotEqualMsg(expected, actual interface{}) string {
	return fmt.Sprintln(ES_EXPECTED, expected, ES_GOT, actual)
}

func ValueWasNil(expected interface{}) string {
	return NotEqualMsg(expected, "(nil)")
}

// Same as NotEqualMsg, except that the type names will be printed instead
func TypeNotEqualMsg(expected, actual interface{}) string {
	eType := TypeName(expected)
	aType := TypeName(actual)
	return fmt.Sprintln(ES_EXPECTED, eType, ES_GOT, aType)
}

func UnexpectedErrMsg(err string) string {
	return fmt.Sprintln(EM_UN_ERR, ES_ERR, err)
}

Add `ValueWasNil` test message function


package projects

import (
	"testing"
)

func TestIsValidInventoryPath(t *testing.T) {
	if !IsValidInventoryPath("inventories/test") {
		t.Fatal(" a path below the cwd should be valid")
	}

	if !IsValidInventoryPath("inventories/test/../prod") {
		t.Fatal(" a path below the cwd should be valid")
	}

	if IsValidInventoryPath("/test/../../../inventory") {
		t.Fatal(" a path out of the cwd should be invalid")
	}

	if IsValidInventoryPath("/test/inventory") {
		t.Fatal(" a path out of the cwd should be invalid")
	}

	if IsValidInventoryPath("c:\\test\\inventory") {
		t.Fatal(" a path out of the cwd should be invalid")
	}
}

package projects

import (
	"testing"
	"runtime"
)

func TestIsValidInventoryPath(t *testing.T) {
	if !IsValidInventoryPath("inventories/test") {
		t.Fatal(" a path below the cwd should be valid")
	}

	if !IsValidInventoryPath("inventories/test/../prod") {
		t.Fatal(" a path below the cwd should be valid")
	}

	if IsValidInventoryPath("/test/../../../inventory") {
		t.Fatal(" a path out of the cwd should be invalid")
	}

	if IsValidInventoryPath("/test/inventory") {
		t.Fatal(" a path out of the cwd should be invalid")
	}

	if runtime.GOOS == "windows" && IsValidInventoryPath("c:\\test\\inventory") {
		t.Fatal(" a path out of the cwd should be invalid")
	}
}

Fix inventory test for windows path


package db

import "gopkg.in/mgo.v2"

// Interface for generic data source (e.g. database).
type DataSource interface {
	// Returns collection by name
	C(name string) Collection

	// Returns copy of data source (may be copy of session as well)
	Copy() DataSource
}

// Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
func (s MongoSession) Source(name string) DataSource {
	return &MongoDatabase{Database: s.Session.DB(name)}
}

// Wrapper around *mgo.DataSource.
type MongoDatabase struct {
	*mgo.Database
}

// Override C method of mgo.DataSource to return wrapper around *mgo.Collection
func (d MongoDatabase) C(name string) Collection {
	return &MongoCollection{Collection: d.Database.C(name)}
}

// Returns database associated with copied session
func (d MongoDatabase) Copy() DataSource {
	return MongoDatabase{d.With(d.Session.Copy())}
}

package db

import "gopkg.in/mgo.v2"

// Interface for generic data source (e.g. database).
type DataSource interface {
	// Returns collection by name
	C(name string) Collection

	// Returns copy of data source (may be copy of session as well)
	Copy() DataSource

	// Closes data source (it will be runtime error to use it after close)
	Close()
}

// Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
func (s MongoSession) Source(name string) DataSource {
	return &MongoDatabase{Database: s.Session.DB(name)}
}

// Wrapper around *mgo.DataSource.
type MongoDatabase struct {
	*mgo.Database
}

// Override C method of mgo.DataSource to return wrapper around *mgo.Collection
func (d MongoDatabase) C(name string) Collection {
	return &MongoCollection{Collection: d.Database.C(name)}
}

// Returns database associated with copied session
func (d MongoDatabase) Copy() DataSource {
	return MongoDatabase{d.With(d.Session.Copy())}
}

// Closes current session with mongo db
func (d MongoDatabase) Close() {
	d.Database.Session.Close()
}

Add close to DataSource interface.


package packet

import "github.com/spf13/cobra"

func deleteCmd() *cobra.Command {
	cmd := &cobra.Command{}
	return cmd
}

package packet

import (
	"errors"
	"fmt"

	"github.com/spf13/cobra"
)

func deleteCmd() *cobra.Command {
	var deleteAll bool
	cmd := &cobra.Command{
		Use:   "delete",
		Short: "Delete machines from the Packet.net project. This will destroy machines. Be ready.",
		Long: `Delete machines from the Packet.net project.

This command destroys machines on the project that is being managed with this tool.

It will destroy machines in the project, regardless of whether the machines were provisioned with this tool.

Be ready.
		`,
		RunE: func(cmd *cobra.Command, args []string) error {
			return doDelete(cmd, args, deleteAll)
		},
	}
	cmd.Flags().BoolVar(&deleteAll, "all", false, "Delete all machines in the project.")
	return cmd
}

func doDelete(cmd *cobra.Command, args []string, deleteAll bool) error {
	if !deleteAll && len(args) != 1 {
		return errors.New("You must provide the hostname of the machine to be deleted, or use the --all flag to destroy all machines in the project")
	}
	hostname := ""
	if !deleteAll {
		hostname = args[0]
	}
	client, err := newFromEnv()
	if err != nil {
		return err
	}
	nodes, err := client.ListNodes()
	if err != nil {
		return err
	}
	for _, n := range nodes {
		if hostname == n.Host || deleteAll {
			if err := client.DeleteNode(n.ID); err != nil {
				return err
			}
			fmt.Println("Deleted", n.Host)
		}
	}
	return nil
}

Add support for deleting packet machines


package oddb

import (
	"fmt"
)

// A RecordNotFoundError is an implementation of error which represents
// a record is not found in a Database
type RecordNotFoundError struct {
	Key  string
	Conn Conn
}

func (e *RecordNotFoundError) Error() string {
	return fmt.Sprintf("Record of %v not found in Database", e.Key)
}

// A Database represents a collection of record (either public or private)
// in a container
type Database interface {
	ID() string
	Get(key string, record *Record) error
	Save(record *Record) error
	Delete(key string) error
}

package oddb

import (
	"fmt"
)

// A RecordNotFoundError is an implementation of error which represents
// that a record is not found in a Database.
type RecordNotFoundError struct {
	Key  string
	Conn Conn
}

func (e *RecordNotFoundError) Error() string {
	return fmt.Sprintf("Record of %v not found in Database", e.Key)
}

// Database represents a collection of record (either public or private)
// in a container.
type Database interface {
	ID() string
	Get(key string, record *Record) error
	Save(record *Record) error
	Delete(key string) error

	Query(query string, args ...interface{}) (Rows, error)
}

// Rows is a cursor returned by execution of a query.
type Rows interface {
	// Close closes the rows iterator
	Close() error

	// Next populates the next Record in the current rows iterator into
	// the provided record.
	//
	// Next should return io.EOF when there are no more rows
	Next(record *Record) error
}

Add a Query method to Database interface


package main

import (
	"bufio"
	"fmt"
	"github.com/JacobHayes/locus"
	"log"
	"os"
	"strings"
)

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

func open(filename string) *os.File {
	file, err := os.Open(filename)
	check(err)

	return file
}

func readLine(scanner *bufio.Scanner) string {
	check(scanner.Err())
	line := scanner.Text()
	check(scanner.Err())

	return line
}

func main() {
	stdin := bufio.NewScanner(os.Stdin)

	key_file := open(`api`)
	defer key_file.Close()
	key_scanner := bufio.NewScanner(key_file)
	key_scanner.Scan()
	key := readLine(key_scanner)

	ips_file := open(`ips`)
	defer ips_file.Close()
	ips_scanner := bufio.NewScanner(ips_file)
	ips := make([]string, 0)
	for ips_scanner.Scan() {
		ips = append(ips, readLine(ips_scanner))
	}

	fmt.Print("Location Precision - City/[Country]: ")
	locations, err := locus.BulkLookupLocation(ips, strings.ToLower(readLine(stdin)), key)
	check(err)

	for _, location := range locations {
		fmt.Println(location)
	}
}

package main

import (
	"bufio"
	"fmt"
	"github.com/JacobHayes/locus"
	"log"
	"os"
	"strings"
)

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

func open(filename string) *os.File {
	file, err := os.Open(filename)
	check(err)

	return file
}

func readLine(scanner *bufio.Scanner) string {
	scanner.Scan()
	check(scanner.Err())
	line := scanner.Text()
	check(scanner.Err())

	return line
}

func main() {
	stdin := bufio.NewScanner(os.Stdin)

	key_file := open(`api`)
	defer key_file.Close()
	key_scanner := bufio.NewScanner(key_file)
	key := readLine(key_scanner)

	fmt.Print("Location Precision - City/[Country]: ")
	locations, err := locus.LookupLocationsFile(`ips`, strings.ToLower(readLine(stdin)), key)
	check(err)

	for _, location := range locations {
		fmt.Println(location)
	}
}

Use file lookup api to simplify logic


package memory_test

import (
	"testing"
	"time"

	"github.com/ulule/limiter/v3"
	"github.com/ulule/limiter/v3/drivers/store/memory"
	"github.com/ulule/limiter/v3/drivers/store/tests"
)

func TestMemoryStoreSequentialAccess(t *testing.T) {
	tests.TestStoreSequentialAccess(t, memory.NewStoreWithOptions(limiter.StoreOptions{
		Prefix:          "limiter:memory:sequential",
		CleanUpInterval: 30 * time.Second,
	}))
}

func TestMemoryStoreConcurrentAccess(t *testing.T) {
	tests.TestStoreConcurrentAccess(t, memory.NewStoreWithOptions(limiter.StoreOptions{
		Prefix:          "limiter:memory:concurrent",
		CleanUpInterval: 1 * time.Nanosecond,
	}))
}

package memory_test

import (
	"testing"
	"time"

	"github.com/ulule/limiter/v3"
	"github.com/ulule/limiter/v3/drivers/store/memory"
	"github.com/ulule/limiter/v3/drivers/store/tests"
)

func TestMemoryStoreSequentialAccess(t *testing.T) {
	tests.TestStoreSequentialAccess(t, memory.NewStoreWithOptions(limiter.StoreOptions{
		Prefix:          "limiter:memory:sequential-test",
		CleanUpInterval: 30 * time.Second,
	}))
}

func TestMemoryStoreConcurrentAccess(t *testing.T) {
	tests.TestStoreConcurrentAccess(t, memory.NewStoreWithOptions(limiter.StoreOptions{
		Prefix:          "limiter:memory:concurrent-test",
		CleanUpInterval: 1 * time.Nanosecond,
	}))
}

func BenchmarkRedisStoreSequentialAccess(b *testing.B) {
	tests.BenchmarkStoreSequentialAccess(b, memory.NewStoreWithOptions(limiter.StoreOptions{
		Prefix:          "limiter:memory:sequential-benchmark",
		CleanUpInterval: 1 * time.Second,
	}))
}

func BenchmarkRedisStoreConcurrentAccess(b *testing.B) {
	tests.BenchmarkStoreConcurrentAccess(b, memory.NewStoreWithOptions(limiter.StoreOptions{
		Prefix:          "limiter:memory:concurrent-benchmark",
		CleanUpInterval: 1 * time.Second,
	}))
}

Add benchmark for memory store


// index=3
package main

import (
	"fmt"
	"log"
	"time"

	_ "veyron.io/veyron/veyron/profiles"
	"veyron.io/veyron/veyron2/rt"

	"fortune"
)

func main() {
	var err error
	runtime, err := rt.New()
	if err != nil {
		log.Fatal("failure creating runtime: ", err)
	}

	// Create a new stub that binds to address without
	// using the name service.
	s := fortune.FortuneClient("fortune")

	// Issue a Get() RPC.
	// We do this in a loop to give the server time to start up.
	var fortune string
	for {
		if fortune, err = s.Get(runtime.NewContext()); err == nil {
			break
		}
		time.Sleep(100 * time.Millisecond)
	}
	fmt.Println(fortune)
}

// index=3
package main

import (
	"fmt"
	"log"
	"time"

	_ "veyron.io/veyron/veyron/profiles"
	"veyron.io/veyron/veyron2/rt"

	"fortune"
)

func main() {
	runtime, err := rt.New()
	if err != nil {
		log.Fatal("failure creating runtime: ", err)
	}

	// Create a new stub that binds to address without
	// using the name service.
	s := fortune.FortuneClient("fortune")

	// Issue a Get() RPC.
	// We do this in a loop to give the server time to start up.
	var fortune string
	for {
		if fortune, err = s.Get(runtime.NewContext()); err == nil {
			break
		}
		time.Sleep(100 * time.Millisecond)
	}
	fmt.Println(fortune)
}

Fix playground fortune example to work without rt.Init() Addressed nit by @nlacasse.


package pool

import (
	"runtime"
	"sync"
)

type Pool struct {
	wg         *sync.WaitGroup
	completion chan bool
	m          sync.Mutex
}

const (
	MaxConcurrencyLimit = -1
)

func New(concurrencyLimit int) *Pool {
	if concurrencyLimit == MaxConcurrencyLimit {
		concurrencyLimit = runtime.NumCPU()
	}

	wg := sync.WaitGroup{}
	completionChan := make(chan bool, concurrencyLimit)

	for i := 0; i < concurrencyLimit; i++ {
		completionChan <- true
	}

	return &Pool{&wg, completionChan, sync.Mutex{}}
}

func (pool *Pool) Spawn(job func()) {
	<-pool.completion
	pool.wg.Add(1)

	go func() {
		defer func() {
			pool.completion <- true
			pool.wg.Done()
		}()

		job()
	}()
}

func (pool *Pool) Lock() {
	pool.m.Lock()
}

func (pool *Pool) Unlock() {
	pool.m.Unlock()
}

func (pool *Pool) Wait() {
	pool.wg.Wait()
}

package pool

import (
	"runtime"
	"sync"
)

type Pool struct {
	wg         *sync.WaitGroup
	completion chan bool
	m          sync.Mutex
}

const (
	MaxConcurrencyLimit = -1
)

func New(concurrencyLimit int) *Pool {
	if concurrencyLimit == MaxConcurrencyLimit {
		// Completely arbitrary. Most of the time we could probably have unbounded concurrency, but the situations where we use
		// this pool is basically just S3 uploading and downloading, so this number is kind of a proxy for "What won't rate limit us"
		// TODO: Make artifact uploads and downloads gracefully handle rate limiting, remove this pool entirely, and use unbounded concurrency via a WaitGroup
		concurrencyLimit = runtime.NumCPU() * 10
	}

	wg := sync.WaitGroup{}
	completionChan := make(chan bool, concurrencyLimit)

	for i := 0; i < concurrencyLimit; i++ {
		completionChan <- true
	}

	return &Pool{&wg, completionChan, sync.Mutex{}}
}

func (pool *Pool) Spawn(job func()) {
	<-pool.completion
	pool.wg.Add(1)

	go func() {
		defer func() {
			pool.completion <- true
			pool.wg.Done()
		}()

		job()
	}()
}

func (pool *Pool) Lock() {
	pool.m.Lock()
}

func (pool *Pool) Unlock() {
	pool.m.Unlock()
}

func (pool *Pool) Wait() {
	pool.wg.Wait()
}

Increase max concurrency by 10x


package channels

import (
    "io"
    "os"
    helperModels "github.com/SpectraLogic/ds3_go_sdk/helpers/models"
)

// Implements the WriteChannelBuilder interface and uses a file as the WriteCloser implementation.
// This channel functions as a random-access and can be used concurrently so long as two writers
// are not writing to the same location within the file.
type ObjectWriteChannelBuilder struct {
    name string
}

func NewWriteChannelBuilder(name string) helperModels.WriteChannelBuilder {
    return &ObjectWriteChannelBuilder{name:name}
}

func (builder *ObjectWriteChannelBuilder) IsChannelAvailable(offset int64) bool {
    return true
}

func (builder *ObjectWriteChannelBuilder) GetChannel(offset int64) (io.WriteCloser, error) {
    f, err := os.OpenFile(builder.name, os.O_WRONLY, defaultPermissions)
    if err != nil {
        return nil, err
    }
    f.Seek(offset, io.SeekStart)
    return f, nil
}

func (builder *ObjectWriteChannelBuilder) OnDone(writer io.WriteCloser) {
    writer.Close()
}

package channels

import (
    "io"
    "os"
    helperModels "github.com/SpectraLogic/ds3_go_sdk/helpers/models"
)

// Implements the WriteChannelBuilder interface and uses a file as the WriteCloser implementation.
// This channel functions as a random-access and can be used concurrently so long as two writers
// are not writing to the same location within the file.
type ObjectWriteChannelBuilder struct {
    name string
}

func NewWriteChannelBuilder(name string) helperModels.WriteChannelBuilder {
    return &ObjectWriteChannelBuilder{name:name}
}

func (builder *ObjectWriteChannelBuilder) IsChannelAvailable(offset int64) bool {
    return true
}

func (builder *ObjectWriteChannelBuilder) GetChannel(offset int64) (io.WriteCloser, error) {
    f, err := os.OpenFile(builder.name, os.O_WRONLY | os.O_CREATE, os.ModePerm)
    if err != nil {
        return nil, err
    }

    f.Seek(offset, io.SeekStart)
    return f, nil
}

func (builder *ObjectWriteChannelBuilder) OnDone(writer io.WriteCloser) {
    writer.Close()
}

Fix for jira neo 996. BP GetObject() does not return an entire object, if the original file had been blobbed. Using a bulk get per object restored. Making write channel builder create the file if it doesn't exist.


package utils

import (
	"os"
	"os/user"
)

/*GetUserHomeDir returns the home directory of the current user.
 */
func GetUserHomeDir() string {
	usr, err := user.Current()
	// If the current user cannot be reached, get the HOME environment variable
	if err != nil {
		return os.Getenv("$HOME")
	}
	return usr.HomeDir
}

/*GetLocalhost returns the localhost name of the current computer.
 *If there is an error, it returns a default string.
 */
func GetLocalhost() string {
	lhost, err := os.Hostname()
	if err != nil {
		return "DefaultHostname"
	}
	return lhost
}

Add a function to get the localhost


package main

import (
	"fmt"
	"github.com/adrien-f/gotify/config"
	sp "github.com/op/go-libspotify"
)

func Ascii() {
	fmt.Println("             _   _  __")
	fmt.Println("  __ _  ___ | |_(_)/ _|_   _")
	fmt.Println(" / _` |/ _ \\| __| | |_| | | |")
	fmt.Println("| (_| | (_) | |_| |  _| |_| |")
	fmt.Println(" \\__, |\\___/ \\__|_|_|  \\__, |")
	fmt.Println(" |___/                 |___/")
	fmt.Println("\ngotify version 1.2 - libspotify", sp.BuildId())
}

var (
	configuration *config.Configuration
)

func main() {
	Ascii()
	configuration = config.LoadConfig()
}

// This is gotify, a lightweight Spotify player written in Go
package main

import (
	"flag"
	"fmt"
	"github.com/adrien-f/gotify/config"
	sp "github.com/op/go-libspotify"
)

func Ascii() {
	fmt.Println("             _   _  __")
	fmt.Println("  __ _  ___ | |_(_)/ _|_   _")
	fmt.Println(" / _` |/ _ \\| __| | |_| | | |")
	fmt.Println("| (_| | (_) | |_| |  _| |_| |")
	fmt.Println(" \\__, |\\___/ \\__|_|_|  \\__, |")
	fmt.Println(" |___/                 |___/")
	fmt.Println("\ngotify version 1.2 - libspotify", sp.BuildId())
}

var (
	configuration *config.Configuration
	debug         = flag.Bool("debug", false, "debug output")
)

func main() {
	flag.Parse()
	Ascii()
	configuration = config.LoadConfig()
}

Add godoc string and debug flag parsing


package chalmers_chop

import "time"

type Menu struct {
	Title  string `json:"title"`
	Date   string `json:"date"`
	Dishes []Dish `json:"dishes"`
}

func (m *Menu) AddDish(dish Dish) {
	m.Dishes = append(m.Dishes, dish)
}

func (r *Restaurant) TodaysMenu() *Menu {
	found, menu := r.findMenuByTime(time.Now())

	if !found {
		return nil
	}

	return menu
}

func (r *Restaurant) findMenuByTime(time time.Time) (bool, *Menu) {
	date := time.Format("2006-01-02")

	for _, m := range r.Menus {
		if m.Date == date {
			return true, &m
		}
	}

	return false, nil
}

package chalmers_chop

import "time"

type Menu struct {
	Title  string `json:"title"`
	Date   string `json:"date"`
	Dishes []Dish `json:"dishes"`
}

func (m *Menu) AddDish(dish Dish) {
	m.Dishes = append(m.Dishes, dish)
}

func (r *Restaurant) TodaysMenu() *Menu {
	found, menu := r.findMenuByTime(time.Now())

	if !found {
		return nil
	}

	return menu
}

func (r *Restaurant) findMenuByTime(t time.Time) (bool, *Menu) {
	date := t.Format("2006-01-02")

	for _, m := range r.Menus {
		if m.Date == date {
			return true, &m
		}
	}

	return false, nil
}

Rename variable to avoid confusion with time package


package main

import (
	"fmt"
	"os"

	"github.com/codegangsta/cli"
	_ "github.com/go-sql-driver/mysql"

	"github.com/containerops/vessel/cmd"
	"github.com/containerops/wrench/setting"
)

func main() {
	if err := setting.SetConfig("conf/containerops.conf"); err != nil {
		fmt.Printf("Read config error: %v", err.Error())
		return
	}

	app := cli.NewApp()

	app.Name = setting.AppName
	app.Usage = setting.Usage
	app.Version = setting.Version
	app.Author = setting.Author
	app.Email = setting.Email

	app.Commands = []cli.Command{
		cmd.CmdWeb,
		cmd.CmdDatabase,
	}

	app.Flags = append(app.Flags, []cli.Flag{}...)
	app.Run(os.Args)
}

package main

import (
	"fmt"
	"os"

	"github.com/codegangsta/cli"

	"github.com/containerops/vessel/cmd"
	"github.com/containerops/wrench/setting"
)

func main() {
	if err := setting.SetConfig("conf/containerops.conf"); err != nil {
		fmt.Printf("Read config error: %v", err.Error())
		return
	}

	app := cli.NewApp()

	app.Name = setting.AppName
	app.Usage = setting.Usage
	app.Version = setting.Version
	app.Author = setting.Author
	app.Email = setting.Email

	app.Commands = []cli.Command{
		cmd.CmdWeb,
		cmd.CmdDatabase,
	}

	app.Flags = append(app.Flags, []cli.Flag{}...)
	app.Run(os.Args)
}

Remove the unuse mysql driver


package main

import (
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
)

var log = logrus.New()

func main() {
	app := cli.NewApp()
	app.Commands = Commands
	app.CommandNotFound = cmdNotFound
	app.Version = Version

	app.Run(os.Args)
}

func cmdNotFound(c *cli.Context, command string) {
	log.Fatalf(
		"%s: '%s' is not a %s command. See '%s --help'.",
		c.App.Name,
		command,
		c.App.Name,
		c.App.Name,
	)
}

package main

import (
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/codegangsta/cli"
)

var log = logrus.New()

func main() {
	app := cli.NewApp()
	app.Usage = "A tool to easily manage your hosts file."
	app.Commands = Commands
	app.CommandNotFound = cmdNotFound
	app.Version = Version

	app.Run(os.Args)
}

func cmdNotFound(c *cli.Context, command string) {
	log.Fatalf(
		"%s: '%s' is not a %s command. See '%s --help'.",
		c.App.Name,
		command,
		c.App.Name,
		c.App.Name,
	)
}

Add a description to the cli interface.


package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "Hi there, I love %s!", r.URL.Path[1:])
}

func main() {
    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

package main

import (
    "fmt"
    "net/http"
)

func handler(w http.ResponseWriter, r *http.Request) {
    fmt.Fprintf(w, "path - %s", r.URL.Path[1:])
    fmt.Printf("GET %s\n", r.URL.Path)
}

func main() {
    fmt.Println("Server running at port 8080")

    http.HandleFunc("/", handler)
    http.ListenAndServe(":8080", nil)
}

Add a bit of logging


package main

import (
	"log"
	"net/http"
	"github.com/codegangsta/cli"
	"os"
)

func main() {
	app := cli.NewApp()
	app.Name = "go-http-server"
	app.Usage = "Start web server and public your current directory."

	app.Version = "0.0.1"
	app.Authors = append(app.Authors, cli.Author{Name: "Kohei Kawasaki", Email: "mynameiskawasaq@gmail.com"})

	app.Commands = []cli.Command{
		{
			Name: "start",
			Aliases: []string{"s"},
			Usage: "Start the web server",
			Action: start,
			Flags: []cli.Flag {
				cli.StringFlag {
					Name: "port, p",
					Value: "8000",
					Usage: "Port number to listen to",
					EnvVar: "PORT",
				},
			},
		},
	}

	app.Run(os.Args)
}

func start(c *cli.Context) {
		port := c.String("port")
		log.Fatal(http.ListenAndServe(":"+port, http.FileServer(http.Dir("."))))
}

package main

import (
	"log"
	"net/http"
	"github.com/codegangsta/cli"
	"os"
)

func main() {
	app := cli.NewApp()
	app.Name = "go-http-server"
	app.Usage = "Start web server and public your current directory."

	app.Version = "0.0.2"
	app.Authors = append(app.Authors, cli.Author{Name: "Kohei Kawasaki", Email: "mynameiskawasaq@gmail.com"})

	app.Commands = []cli.Command{
		{
			Name: "start",
			Aliases: []string{"s"},
			Usage: "Start the web server",
			Action: start,
			Flags: []cli.Flag {
				cli.StringFlag {
					Name: "port, p",
					Value: "8000",
					Usage: "Port number to listen to",
					EnvVar: "PORT",
				},
			},
		},
	}

	app.Action = start

	app.Run(os.Args)
}

func start(c *cli.Context) {
	port := c.String("port")
	if port == "" {
		port = "8000"
	}
	log.Fatal(http.ListenAndServe(":"+port, http.FileServer(http.Dir("."))))
}

Make command executable without any parameters


package main

import (
	"net/http"
	"log"
	"github.com/gorilla/mux"
)

const BIND_ADDRESS string = ":8000"
const STATIC_DIRECTORY string = "static"
const STATIC_MOUNT_POINT string = "/"

func RootHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Gorilla!\n"))
}

func main() {
	log.Printf("Starting server on %s.\n", BIND_ADDRESS)

	r := mux.NewRouter()
	// Routes consist of a path and a handler function.
	r.HandleFunc("/", RootHandler)

	r.PathPrefix(STATIC_MOUNT_POINT).Handler(
			http.StripPrefix(STATIC_MOUNT_POINT,
			http.FileServer(http.Dir(STATIC_DIRECTORY))))

	// Bind to a port and pass our router in
	log.Fatal(http.ListenAndServe(BIND_ADDRESS, r))
}

package main

import (
	"net/http"
	"log"
	"github.com/gorilla/mux"
)

const BIND_ADDRESS string = ":8000"
const STATIC_DIRECTORY string = "static"
const STATIC_MOUNT_POINT string = "/"

func RootHandler(w http.ResponseWriter, r *http.Request) {
	w.Write([]byte("Gorilla!\n"))
}

func main() {
	log.Printf("Starting server on %s.\n", BIND_ADDRESS)

	r := mux.NewRouter()
	// Routes consist of a path and a handler function.
	r.HandleFunc("/test", RootHandler)

	r.PathPrefix(STATIC_MOUNT_POINT).Handler(
			http.StripPrefix(STATIC_MOUNT_POINT,
			http.FileServer(http.Dir(STATIC_DIRECTORY))))

	// Bind to a port and pass our router in
	log.Fatal(http.ListenAndServe(BIND_ADDRESS, r))
}

Move code endpoint to test static index


package main

import (
	"flag"
	"fmt"
)

func main() {
	tester, err := NewTTFB()

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

	flag.Parse()

	results, err := tester.Report(flag.Arg(0))

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

	fmt.Printf("@ Testing domain '%s'\n", tester.domain)
	fmt.Printf("  Status: Connection Time, First Byte Time, Total Time\n")

	for _, data := range results {
		fmt.Printf("- %s -> %s, %s, %s %s\n",
			data.Output.ServerID,
			data.Output.ConnectTime,
			data.Output.FirstbyteTime,
			data.Output.TotalTime,
			data.Output.ServerTitle)
	}

	fmt.Println("  Finished")
}

package main

import (
	"flag"
	"fmt"
)

func main() {
	tester, err := NewTTFB()

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

	flag.Parse()

	results, err := tester.Report(flag.Arg(0))

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

	var icon string

	fmt.Printf("@ Testing domain '%s'\n", tester.domain)
	fmt.Printf("  Status: Connection Time, First Byte Time, Total Time\n")

	for _, data := range results {
		if data.Status == 1 {
			icon = "\033[0;92m\u2714\033[0m"
		} else {
			icon = "\033[0;91m\u2718\033[0m"
		}

		fmt.Printf("%s %s -> %s, %s, %s %s\n",
			icon,
			data.Output.ServerID,
			data.Output.ConnectTime,
			data.Output.FirstbyteTime,
			data.Output.TotalTime,
			data.Output.ServerTitle)
	}

	fmt.Println("  Finished")
}

Add icon to represent successful and failed requests


package main

import (
	"github.com/cloudtools/ssh-cert-authority/util"
	"github.com/codegangsta/cli"
	"os"
)

func main() {
	app := cli.NewApp()
	app.Name = "ssh-cert-authority"
	app.EnableBashCompletion = true
	app.Version = ssh_ca_util.BuildVersion

	app.Commands = []cli.Command{
		{
			Name:    "request",
			Aliases: []string{"r"},
			Flags:   requestCertFlags(),
			Usage:   "Request a new certificate",
			Action:  requestCert,
		},
		{
			Name:    "sign",
			Aliases: []string{"s"},
			Flags:   signCertFlags(),
			Usage:   "Sign a certificate",
			Action:  signCert,
		},
		{
			Name:    "get",
			Aliases: []string{"g"},
			Flags:   getCertFlags(),
			Usage:   "Get a certificate",
			Action:  getCert,
		},
		{
			Name:    "runserver",
			Aliases: []string{"g"},
			Flags:   signdFlags(),
			Usage:   "Get a certificate",
			Action:  signCertd,
		},
	}
	app.Run(os.Args)
}

package main

import (
	"github.com/cloudtools/ssh-cert-authority/util"
	"github.com/codegangsta/cli"
	"os"
)

func main() {
	app := cli.NewApp()
	app.Name = "ssh-cert-authority"
	app.EnableBashCompletion = true
	app.Version = ssh_ca_util.BuildVersion

	app.Commands = []cli.Command{
		{
			Name:    "request",
			Aliases: []string{"r"},
			Flags:   requestCertFlags(),
			Usage:   "Request a new certificate",
			Action:  requestCert,
		},
		{
			Name:    "sign",
			Aliases: []string{"s"},
			Flags:   signCertFlags(),
			Usage:   "Sign a certificate",
			Action:  signCert,
		},
		{
			Name:    "get",
			Aliases: []string{"g"},
			Flags:   getCertFlags(),
			Usage:   "Get a certificate",
			Action:  getCert,
		},
		{
			Name:   "runserver",
			Flags:  signdFlags(),
			Usage:  "Get a certificate",
			Action: signCertd,
		},
	}
	app.Run(os.Args)
}

Fix busted subcommand shortcut for runserver


package runner

import (
	"log"

	"github.com/sivel/overseer/monitor"
	"github.com/sivel/overseer/notifier"
	"github.com/sivel/overseer/status"
)

type Runner struct {
	StatusChan chan *status.Status
	Monitors   []monitor.Monitor
	Notifiers  []notifier.Notifier
}

func NewRunner(monitors []monitor.Monitor, notifiers []notifier.Notifier) *Runner {
	runner := &Runner{
		StatusChan: make(chan *status.Status),
		Monitors:   monitors,
		Notifiers:  notifiers,
	}
	return runner
}

func (r *Runner) Loop() {
	if len(r.Monitors) == 0 {
		log.Fatalf("No monitors are configured. Exiting...")
	}

	for _, monitor := range r.Monitors {
		go monitor.Watch(r.StatusChan)
	}

	for {
		stat := <-r.StatusChan
		if !notifier.ShouldNotify(stat) {
			continue
		}
		for _, n := range r.Notifiers {
			if notifier.NotifierMatch(stat, n) {
				n.Notify(stat)
			}
		}
	}
}

package runner

import (
	"log"

	"github.com/sivel/overseer/monitor"
	"github.com/sivel/overseer/notifier"
	"github.com/sivel/overseer/status"
)

type Runner struct {
	StatusChan chan *status.Status
	Monitors   []monitor.Monitor
	Notifiers  []notifier.Notifier
}

func NewRunner(monitors []monitor.Monitor, notifiers []notifier.Notifier) *Runner {
	runner := &Runner{
		StatusChan: make(chan *status.Status),
		Monitors:   monitors,
		Notifiers:  notifiers,
	}
	return runner
}

func (r *Runner) Loop() {
	if len(r.Monitors) == 0 {
		log.Fatalf("No monitors are configured. Exiting...")
	}

	for _, monitor := range r.Monitors {
		go monitor.Watch(r.StatusChan)
	}

	for {
		stat := <-r.StatusChan
		go func(stat *status.Status) {
			if notifier.ShouldNotify(stat) {
				for _, n := range r.Notifiers {
					go func(stat *status.Status, n notifier.Notifier) {
						if notifier.NotifierMatch(stat, n) {
							n.Notify(stat)
						}
					}(stat, n)
				}
			}
		}(stat)
	}
}

Improve notification performance with some more goroutines


// This is a "stub" file.  It's a little start on your solution.
// It's not a complete solution though; you have to write some code.

// Package twofer should have a package comment that summarizes what it's about.
// https://golang.org/doc/effective_go.html#commentary
package triangle

// Notice KindFromSides() returns this type. Pick a suitable data type.
type Kind

const (
    // Pick values for the following identifiers used by the test program.
    NaT // not a triangle
    Equ // equilateral
    Iso // isosceles
    Sca // scalene
)

// ShareWith should have a comment documenting it.
func KindFromSides(a, b, c float64) Kind {
	// Write some code here to pass the test suite.
	// Then remove all the stock comments.
	// They're here to help you get started but they only clutter a finished solution.
	// If you leave them in, reviewers may protest!
	var k Kind
	return k
}

// This is a "stub" file.  It's a little start on your solution.
// It's not a complete solution though; you have to write some code.

// Package triangle should have a package comment that summarizes what it's about.
// https://golang.org/doc/effective_go.html#commentary
package triangle

// Notice KindFromSides() returns this type. Pick a suitable data type.
type Kind

const (
    // Pick values for the following identifiers used by the test program.
    NaT // not a triangle
    Equ // equilateral
    Iso // isosceles
    Sca // scalene
)

// KindFromSides should have a comment documenting it.
func KindFromSides(a, b, c float64) Kind {
	// Write some code here to pass the test suite.
	// Then remove all the stock comments.
	// They're here to help you get started but they only clutter a finished solution.
	// If you leave them in, reviewers may protest!
	var k Kind
	return k
}

Fix package and method names in comments


/*
Copyright IBM Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package common

import "testing"

func TestNoop(t *testing.T) {
	// This is just to make this package included in the code-coverage statistics
}

/*
Copyright IBM Corp. All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package common

import (
	"testing"

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

func TestIsNotSame(t *testing.T) {
	id := PKIidType("1")
	assert.True(t, id.IsNotSameFilter(PKIidType("2")))
	assert.False(t, id.IsNotSameFilter(PKIidType("1")))
	assert.False(t, id.IsNotSameFilter(id))
}

Bring gossip/common code coverage back up