package asset

// DefaultImages are the defualt images bootkube components use.
var DefaultImages = ImageVersions{
	Etcd:            "quay.io/coreos/etcd:v3.1.8",
	Flannel:         "quay.io/coreos/flannel:v0.10.0-amd64",
	FlannelCNI:      "quay.io/coreos/flannel-cni:v0.3.0",
	Calico:          "quay.io/calico/node:v3.0.3",
	CalicoCNI:       "quay.io/calico/cni:v2.0.0",
	CoreDNS:         "k8s.gcr.io/coredns:1.2.4",
	Hyperkube:       "k8s.gcr.io/hyperkube:v1.12.1",
	PodCheckpointer: "quay.io/coreos/pod-checkpointer:018007e77ccd61e8e59b7e15d7fc5e318a5a2682",
}

package asset

// DefaultImages are the defualt images bootkube components use.
var DefaultImages = ImageVersions{
	Etcd:            "quay.io/coreos/etcd:v3.1.8",
	Flannel:         "quay.io/coreos/flannel:v0.10.0-amd64",
	FlannelCNI:      "quay.io/coreos/flannel-cni:v0.3.0",
	Calico:          "quay.io/calico/node:v3.0.3",
	CalicoCNI:       "quay.io/calico/cni:v2.0.0",
	CoreDNS:         "k8s.gcr.io/coredns:1.2.4",
	Hyperkube:       "k8s.gcr.io/hyperkube:v1.12.1",
	PodCheckpointer: "quay.io/coreos/pod-checkpointer:83e25e5968391b9eb342042c435d1b3eeddb2be1",
}

Update pod-checkpointer image to try secureClient first


package gop

import (
	"fmt"
	"os"

	"github.com/segmentio/go-loggly"
)

// A timber.LogWriter for the loggly service.

// LogglyWriter is a Timber writer to send logging to the loggly
// service. See: https://loggly.com.
type LogglyWriter struct {
	c *loggly.Client
}

// NewLogEntriesWriter creates a new writer for sending logging to logentries.
func NewLogglyWriter(token string, tags ...string) (*LogglyWriter, error) {
	return &LogglyWriter{c: loggly.New(token, tags...)}, nil
}

// LogWrite the message to the logenttries server async. Satifies the timber.LogWrite interface.
func (w *LogglyWriter) LogWrite(msg string) {
	// using type for the message string is how the Info etc methods on the
	// loggly client work.
	// TODO: Add a "level" key for info, error..., proper timestamp etc
	// Buffers the message for async send
	// TODO - Stat for the bytes written return?
	if _, err := w.c.Write([]byte(msg)); err != nil {
		// TODO: What is best todo here as if we log it will loop?
		fmt.Fprintf(os.Stderr, "loggly send error: %s\n", err.Error())
	}
}

// Close the write. Satifies the timber.LogWriter interface.
func (w *LogglyWriter) Close() {
	w.c.Flush()
}

package gop

import (
	"fmt"
	"os"

	"github.com/cocoonlife/go-loggly"
)

// A timber.LogWriter for the loggly service.

// LogglyWriter is a Timber writer to send logging to the loggly
// service. See: https://loggly.com.
type LogglyWriter struct {
	c *loggly.Client
}

// NewLogEntriesWriter creates a new writer for sending logging to logentries.
func NewLogglyWriter(token string, tags ...string) (*LogglyWriter, error) {
	return &LogglyWriter{c: loggly.New(token, tags...)}, nil
}

// LogWrite the message to the logenttries server async. Satifies the timber.LogWrite interface.
func (w *LogglyWriter) LogWrite(msg string) {
	// using type for the message string is how the Info etc methods on the
	// loggly client work.
	// TODO: Add a "level" key for info, error..., proper timestamp etc
	// Buffers the message for async send
	// TODO - Stat for the bytes written return?
	if _, err := w.c.Write([]byte(msg)); err != nil {
		// TODO: What is best todo here as if we log it will loop?
		fmt.Fprintf(os.Stderr, "loggly send error: %s\n", err.Error())
	}
}

// Close the write. Satifies the timber.LogWriter interface.
func (w *LogglyWriter) Close() {
	w.c.Flush()
	close(w.c.ShutdownChan)
}

Fix goroutine leak when replacing LogglyWriter instance


package main

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

type Request struct {
	Filename string
	Content  string
	Command  string
	Image    string
	Format   string
}

var FilenameRegexp = regexp.MustCompile(`\A([a-z\d\-\_]+)\.[a-z]{1,6}\z`)

func normalizeString(val string) string {
	return strings.ToLower(strings.TrimSpace(val))
}

func ParseRequest(r *http.Request) (*Request, error) {
	req := Request{
		Filename: normalizeString(r.FormValue("filename")),
		Command:  normalizeString(r.FormValue("command")),
		Content:  r.FormValue("content"),
	}

	if req.Filename == "" {
		return nil, fmt.Errorf("Filename is required")
	}

	if !FilenameRegexp.Match([]byte(req.Filename)) {
		return nil, fmt.Errorf("Invalid filename")
	}

	if req.Content == "" {
		return nil, fmt.Errorf("Content is required")
	}

	lang, err := GetLanguageConfig(req.Filename)
	if err != nil {
		return nil, err
	}

	req.Image = lang.Image
	req.Format = lang.Format

	if req.Command == "" {
		req.Command = fmt.Sprintf(lang.Command, req.Filename)
	}

	return &req, nil
}

package main

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

type Request struct {
	Filename string
	Content  string
	Command  string
	Image    string
	Format   string
}

var FilenameRegexp = regexp.MustCompile(`\A([a-z\d\-\_]+)\.[a-z]{1,6}\z`)

func normalizeString(val string) string {
	return strings.ToLower(strings.TrimSpace(val))
}

func ParseRequest(r *http.Request) (*Request, error) {
	req := Request{
		Filename: normalizeString(r.FormValue("filename")),
		Command:  normalizeString(r.FormValue("command")),
		Content:  r.FormValue("content"),
		Image:    r.FormValue("image"),
	}

	if req.Filename == "" {
		return nil, fmt.Errorf("Filename is required")
	}

	if !FilenameRegexp.Match([]byte(req.Filename)) {
		return nil, fmt.Errorf("Invalid filename")
	}

	if req.Content == "" {
		return nil, fmt.Errorf("Content is required")
	}

	lang, err := GetLanguageConfig(req.Filename)
	if err != nil {
		return nil, err
	}

	req.Format = lang.Format

	// Override default image
	if req.Image == "" {
		req.Image = lang.Image
	}

	// Override default command
	if req.Command == "" {
		req.Command = fmt.Sprintf(lang.Command, req.Filename)
	}

	return &req, nil
}

Add ability to override image


package systime

import (
	"github.com/Symantec/tricorder/go/tricorder"
	"github.com/Symantec/tricorder/go/tricorder/units"
)

func register(dir *tricorder.DirectorySpec) *prober {
	p := new(prober)
	p.dir = dir
	// TODO(rgooch): Consider dividing this by the number of CPUs before
	//               exporting.
	//if err := dir.RegisterMetric("idle-time", &p.idleTime, units.Second,
	//	"idle time since last boot"); err != nil {
	//	panic(err)
	//}
	if err := dir.RegisterMetric("time", &p.probeTime, units.Second,
		"time of last probe"); err != nil {
		panic(err)
	}
	if err := dir.RegisterMetric("uptime", &p.upTime, units.Second,
		"time since last boot"); err != nil {
		panic(err)
	}
	return p
}

package systime

import (
	"github.com/Symantec/tricorder/go/tricorder"
	"github.com/Symantec/tricorder/go/tricorder/units"
)

func register(dir *tricorder.DirectorySpec) *prober {
	p := new(prober)
	p.dir = dir
	// TODO(rgooch): Consider dividing this by the number of CPUs before
	//               exporting.
	//if err := dir.RegisterMetric("idle-time", &p.idleTime, units.Second,
	//	"idle time since last boot"); err != nil {
	//	panic(err)
	//}
	if err := dir.RegisterMetric("time", &p.probeTime, units.None,
		"time of last probe"); err != nil {
		panic(err)
	}
	if err := dir.RegisterMetric("uptime", &p.upTime, units.Second,
		"time since last boot"); err != nil {
		panic(err)
	}
	return p
}

Switch to unit None for time metric.


package unit

type Subject struct {
	assert *Assertion
	name   string
}

func NewSubject(assert *Assertion) *Subject {
	return &Subject{
		assert: assert,
		name:   "",
	}
}

func (subject *Subject) FailWithMessage(message string) {
	subject.assert.t.Error(message)
}

func (subject *Subject) Named(name string) {
	subject.name = name
}

func (subject *Subject) DisplayString(value string) string {
	if len(value) == 0 {
		value = "unknown"
	}
	if len(subject.name) == 0 {
		return "<" + value + ">"
	}
	return subject.name + "(<" + value + ">)"
}

package unit

import (
	"bytes"
	"fmt"
	"runtime"
	"strings"
)

type Subject struct {
	assert *Assertion
	name   string
}

func NewSubject(assert *Assertion) *Subject {
	return &Subject{
		assert: assert,
		name:   "",
	}
}

// decorate prefixes the string with the file and line of the call site
// and inserts the final newline if needed and indentation tabs for formatting.
func decorate(s string) string {
	_, file, line, ok := runtime.Caller(4) // decorate + log + public function.
	if ok {
		// Truncate file name at last file name separator.
		if index := strings.LastIndex(file, "/"); index >= 0 {
			file = file[index+1:]
		} else if index = strings.LastIndex(file, "\\"); index >= 0 {
			file = file[index+1:]
		}
	} else {
		file = "???"
		line = 1
	}
	buf := new(bytes.Buffer)
	// Every line is indented at least one tab.
	buf.WriteString("  ")
	fmt.Fprintf(buf, "%s:%d: ", file, line)
	lines := strings.Split(s, "\n")
	if l := len(lines); l > 1 && lines[l-1] == "" {
		lines = lines[:l-1]
	}
	for i, line := range lines {
		if i > 0 {
			// Second and subsequent lines are indented an extra tab.
			buf.WriteString("\n\t\t")
		}
		buf.WriteString(line)
	}
	buf.WriteByte('\n')
	return buf.String()
}

func (subject *Subject) FailWithMessage(message string) {
	fmt.Println(decorate(message))
	subject.assert.t.Fail()
}

func (subject *Subject) Named(name string) {
	subject.name = name
}

func (subject *Subject) DisplayString(value string) string {
	if len(value) == 0 {
		value = "unknown"
	}
	if len(subject.name) == 0 {
		return "<" + value + ">"
	}
	return subject.name + "(<" + value + ">)"
}

Print out the correct point of error


package services

import (
	"database/sql"
	"encoding/json"
	"log"

	"cjdavis.me/elysium/db"
	"cjdavis.me/elysium/models"
)

type IProfileService interface {
	GetProfile() *models.Profile
}

type ProfileService struct {
}

func NewProfileService() *ProfileService {
	return &ProfileService{}
}

func (s *ProfileService) GetProfile() *models.Profile {
	profile := models.Profile{}
	jsonRow := json.RawMessage{}

	err := db.AppDB().QueryRow(`
SELECT data FROM profile
ORDER BY data->>'id' ASC
LIMIT 1
`).Scan((*[]byte)(&jsonRow))
	if err != nil {
		if err != sql.ErrNoRows {
			log.Println("Error retrieving profile: " + err.Error())
			return &profile
		}
	}

	err = json.Unmarshal(jsonRow, &profile)
	if err != nil {
		if err != sql.ErrNoRows {
			log.Println("Error unmarshalling json: " + err.Error())
			return &profile
		}
	}

	return &profile
}

package services

import (
	"log"

	"cjdavis.me/elysium/models"
	"cjdavis.me/elysium/repositories"
)

type IProfileService interface {
	GetProfile() *models.Profile
}

type ProfileService struct {
}

func NewProfileService() *ProfileService {
	return &ProfileService{}
}

func (s *ProfileService) GetProfile() *models.Profile {
	profile, err := repositories.GetProfileRepository().GetProfile()
	if err != nil {
		log.Println(err)
	}

	return profile
}

Call the profile repository from the profile service


package main

import (
	"github.com/grsakea/kappastat/backend"
)

func main() {
	launchBackend()
	launchFrontend()
}

func launchBackend() *backend.Controller {
	c := backend.SetupController("twitch")
	go c.Loop()
	return c
}

package main

func main() {
	launchFrontend()
}

Remove launch backend from frontend


// +build !pango_1_10,!pango_1_12,!pango_1_14

package cairo

// #include <stdlib.h>
// #include <cairo.h>
// #include <cairo-gobject.h>
import "C"
import (
	"unsafe"
)

// GetVariations is a wrapper around cairo_font_options_get_variations().
func (o *FontOptions) GetVariations() string {
	return C.GoString(C.cairo_font_options_get_variations(o.native))
}

// SetVariations is a wrapper around cairo_font_options_set_variations().
func (o *FontOptions) SetVariations(variations string) {
	var cvariations *C.char
	if variations != "" {
		cvariations = C.CString(variations)
		// Cairo will call strdup on its own.
		defer C.free(unsafe.Pointer(cvariations))
	}

	C.cairo_font_options_set_variations(o.native, cvariations)
}

// +build !cairo_1_10,!cairo_1_12,!cairo_1_14

package cairo

// #include <stdlib.h>
// #include <cairo.h>
// #include <cairo-gobject.h>
import "C"
import (
	"unsafe"
)

// GetVariations is a wrapper around cairo_font_options_get_variations().
func (o *FontOptions) GetVariations() string {
	return C.GoString(C.cairo_font_options_get_variations(o.native))
}

// SetVariations is a wrapper around cairo_font_options_set_variations().
func (o *FontOptions) SetVariations(variations string) {
	var cvariations *C.char
	if variations != "" {
		cvariations = C.CString(variations)
		// Cairo will call strdup on its own.
		defer C.free(unsafe.Pointer(cvariations))
	}

	C.cairo_font_options_set_variations(o.native, cvariations)
}

Build constraints for cairo packages should be based on cairo-naming, not use pango-naming.


package slack

import (
	"crypto/sha256"
	"encoding/hex"
)

type UserID struct {
	UserID string
	TeamID string
}

type SecureID struct {
	HashSum string
}

/*
Notice that user IDs are not guaranteed to be globally unique across all Slack users.
The combination of user ID and team ID, on the other hand, is guaranteed to be globally unique.

- Slack API documentation
*/
func (id UserID) Equals(o UserID) bool {
	return id.UserID == o.UserID && id.TeamID == o.TeamID
}

func (id UserID) Empty() bool {
	return id.UserID == "" && id.TeamID == ""
}

func (id UserID) Secure() SecureID {
	concat := id.TeamID + "." + id.UserID

	h := sha256.New()
	h.Write([]byte(concat))

	s := hex.EncodeToString(h.Sum(nil))

	return SecureID{
		HashSum: s,
	}
}

func (id SecureID) Equals(o SecureID) bool {
	return id.HashSum == o.HashSum
}

func (id SecureID) Empty() bool {
	return id.HashSum == ""
}

package slack

import (
	"crypto/sha256"
	"encoding/hex"
)

type UserID struct {
	UserID string
	TeamID string
}

type SecureID struct {
	HashSum string
}

/*
Notice that user IDs are not guaranteed to be globally unique across all Slack users.
The combination of user ID and team ID, on the other hand, is guaranteed to be globally unique.

- Slack API documentation
*/
func (id UserID) Equals(o UserID) bool {
	return id.UserID == o.UserID && id.TeamID == o.TeamID
}

func (id UserID) Empty() bool {
	return id.UserID == "" && id.TeamID == ""
}

func (id UserID) Secure() SecureID {
	concat := id.TeamID + "." + id.UserID

	h := sha256.New()
	h.Write([]byte(concat))

	s := hex.EncodeToString(h.Sum(nil))

	return SecureID{
		HashSum: s,
	}
}

func (id SecureID) Equals(o SecureID) bool {
	return id.HashSum == o.HashSum
}

func (id *SecureID) Empty() bool {
	return id.HashSum == ""
}

Change method receiver to pointer


package phonenumber

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

func Number(phoneNumber string) (number string, e error) {
	for _, character := range phoneNumber {
		if unicode.IsDigit(character) {
			number += string(character)
		}
	}
	if len(number) == 11 && number[0] == '1' {
		// trim leading 1
		number = number[1:]
	}
	if len(number) != 10 {
		return "", fmt.Errorf("phone number %v must have 10 digits", number)
	}
	_, err := AreaCode(number)
	if err != nil {
		return "", err
	}
	return number, nil
}

func AreaCode(phoneNumber string) (areaCode string, e error) {
	areaCode = phoneNumber[0:3]
	if strings.HasPrefix(areaCode, "0") || strings.HasPrefix(areaCode, "1") {
		return "", fmt.Errorf("area code %v can not start with 0", areaCode)
	}
	return areaCode, nil
}

func Format(phoneNumber string) (string, error) {
	panic("Please implement the Format function")
}

package phonenumber

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

func Number(phoneNumber string) (number string, e error) {
	for _, character := range phoneNumber {
		if unicode.IsDigit(character) {
			number += string(character)
		}
	}
	if len(number) == 11 && number[0] == '1' {
		// trim leading 1
		number = number[1:]
	}
	if len(number) != 10 {
		return "", fmt.Errorf("phone number %v must have 10 digits", number)
	}
	_, err := AreaCode(number)
	if err != nil {
		return "", err
	}
	_, err = exchangeCode(number)
	if err != nil {
		return "", err
	}
	return number, nil
}

func AreaCode(phoneNumber string) (areaCode string, e error) {
	areaCode = phoneNumber[0:3]
	if strings.HasPrefix(areaCode, "0") || strings.HasPrefix(areaCode, "1") {
		return "", fmt.Errorf("area code %v can not start with 0 or 1", areaCode)
	}
	return areaCode, nil
}

func exchangeCode(phoneNumber string) (exchangeCode string, e error) {
	exchangeCode = phoneNumber[3:6]
	if strings.HasPrefix(exchangeCode, "0") || strings.HasPrefix(exchangeCode, "1") {
		return "", fmt.Errorf("exchange code %v can not start with 0 or 1", exchangeCode)
	}
	return exchangeCode, nil
}

func Format(phoneNumber string) (string, error) {
	panic("Please implement the Format function")
}

Throw error if exchange code starts with 0 or 1


// Challenge 31 - Implement and break HMAC-SHA1 with an artificial timing leak
// http://cryptopals.com/sets/4/challenges/31

package cryptopals

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

type challenge32 struct {
}

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

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

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

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

			elapsed := time.Since(start)

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

		sig[i] = valBest
	}

	return sig
}

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

package cryptopals

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

type challenge32 struct {
}

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

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

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

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

			elapsed := time.Since(start)

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

		sig[i] = valBest
	}

	return sig
}

Update file header with proper challenge name and link


package arrays

// Strings allows us to limit our filter to just arrays of strings
type Strings struct{}

// Filter filters an array of strings.
func (s Strings) Filter(in []string, keep func(item string) bool) []string {
	var out []string
	for _, item := range in {
		if keep(item) {
			out = append(out, item)
		}
	}

	return out
}

package arrays

// Strings allows us to limit our filter to just arrays of strings
type strings struct{}

// Strings allows easy access to the functions that operate on a list of strings
var Strings strings

// Filter filters an array of strings.
func (s strings) Filter(in []string, keep func(item string) bool) []string {
	var out []string
	for _, item := range in {
		if keep(item) {
			out = append(out, item)
		}
	}

	return out
}

// Remove filters an array by removing all matching items
func (s strings) Remove(in []string, remove ...string) []string {
	return s.Filter(in, func(item string) bool {
		found := false
		for _, removeItem := range remove {
			if removeItem == item {
				found = true
			}
		}
		return !found
	})
}

Add Remove and refactor to allow for multiple types and easy access.


package main

import (
	"github.com/kataras/go-template/html"
	"gopkg.in/kataras/iris.v6"
)

type page struct {
	Title string
}

func main() {
	iris.UseTemplate(html.New()).Directory("./templates/web/default", ".html")
	iris.OnError(iris.StatusForbidden, func(ctx *iris.Context) {
		ctx.HTML(iris.StatusForbidden, "<h1> You are not allowed here </h1>")
	})
	// http://localhost:8080/css/bootstrap.min.css
	iris.StaticWeb("/css", "./resources/css")
	// http://localhost:8080/js/jquery-2.1.1.js
	iris.StaticWeb("/js", "./resources/js")

	iris.Get("/", func(ctx *iris.Context) {
		ctx.MustRender("something.html", page{Title: "Home"})
	})

	iris.Listen(":8080")
}

package main

import (
	"gopkg.in/kataras/iris.v6"
	"gopkg.in/kataras/iris.v6/adaptors/httprouter"
	"gopkg.in/kataras/iris.v6/adaptors/view"
)

type page struct {
	Title string
}

func main() {

	app := iris.New()
	app.Adapt(
		iris.DevLogger(),
		httprouter.New(),
		view.HTML("./templates", ".html"),
	)

	app.OnError(iris.StatusForbidden, func(ctx *iris.Context) {
		ctx.HTML(iris.StatusForbidden, "<h1> You are not allowed here </h1>")
	})
	// http://localhost:8080/css/bootstrap.min.css
	app.StaticWeb("/css", "./resources/css")
	// http://localhost:8080/js/jquery-2.1.1.js
	app.StaticWeb("/js", "./resources/js")

	app.Get("/", func(ctx *iris.Context) {
		ctx.MustRender("something.html", page{Title: "Home"})
	})

	app.Listen("localhost:8080")
}

Update static files example for v6


package util

import (
	"os/exec"
	"sort"
	"strings"
	"syscall"
)

func ls(dir string) []string {
	cmd := exec.Command("cmd")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		CmdLine: "cmd /C dir /A /B " + dir,
	}
	output, err := cmd.Output()
	mustOK(err)
	names := strings.Split(strings.Trim(string(output), "\r\n"), "\r\n")
	for i := range names {
		names[i] = dir + names[i]
	}
	sort.Strings(names)
	return names
}

package util

import (
	"os/exec"
	"sort"
	"strings"
	"syscall"
)

func ls(dir string) []string {
	cmd := exec.Command("cmd")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		CmdLine: "cmd /C dir /A /B " + dir,
	}
	output, err := cmd.Output()
	mustOK(err)
	names := strings.Split(strings.Trim(string(output), "\r\n"), "\r\n")
	for i := range names {
		names[i] = dir + names[i]
	}
	// Remove filenames that start with ".".
	// XXX: This behavior only serves to make current behavior of FullNames,
	// which always treat dotfiles as hidden, legal; the validness of this
	// behavior is quetionable. However, since FullNames is also depended by the
	// glob package for testing, changing FullNames requires changing the
	// behavior of globbing as well.
	filtered := make([]string, 0, len(names))
	for _, name := range names {
		if !strings.HasPrefix(name, dir+".") {
			filtered = append(filtered, name)
		}
	}
	sort.Strings(filtered)
	return filtered
}

Make test pass on Windows.


package cli

import (
	"os"
	"os/signal"
	"syscall"

	"github.com/99designs/aws-vault/v6/server"
	"github.com/alecthomas/kingpin"
)

func ConfigureProxyCommand(app *kingpin.Application, a *AwsVault) {
	stop := false

	cmd := app.Command("proxy", "Start a proxy for the ec2 instance role server locally").
		Alias("server").
		Hidden()

	cmd.Flag("stop", "Stop the proxy").
		BoolVar(&stop)

	cmd.Action(func(*kingpin.ParseContext) error {
		if stop {
			server.StopProxy()
			return nil
		} else {
			handleSigTerm()
			return server.StartProxy()
		}
	})
}

func handleSigTerm() {
	// shutdown
	c := make(chan os.Signal)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		server.Shutdown()
		os.Exit(1)
	}()
}

package cli

import (
	"os"
	"os/signal"
	"syscall"

	"github.com/99designs/aws-vault/v6/server"
	"github.com/alecthomas/kingpin"
)

func ConfigureProxyCommand(app *kingpin.Application, a *AwsVault) {
	stop := false

	cmd := app.Command("proxy", "Start a proxy for the ec2 instance role server locally").
		Alias("server").
		Hidden()

	cmd.Flag("stop", "Stop the proxy").
		BoolVar(&stop)

	cmd.Action(func(*kingpin.ParseContext) error {
		if stop {
			server.StopProxy()
			return nil
		} else {
			handleSigTerm()
			return server.StartProxy()
		}
	})
}

func handleSigTerm() {
	// shutdown
	c := make(chan os.Signal, 1)
	signal.Notify(c, os.Interrupt, syscall.SIGTERM)
	go func() {
		<-c
		server.Shutdown()
		os.Exit(1)
	}()
}

Use buffered channel for signals to fix go vet


// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

// +build !darwin,!android

package libkb

func NewSecretStoreAll(g *GlobalContext) SecretStoreAll {
	return NewSecretStoreFile(g.Env.GetDataDir())
}

// Copyright 2015 Keybase, Inc. All rights reserved. Use of
// this source code is governed by the included BSD license.

// +build !darwin,!android

package libkb

import "os"

func NewSecretStoreAll(g *GlobalContext) SecretStoreAll {
	// In order to not break production build releases, only
	// use the SecretStoreFile on windows and linux if this
	// environment variable is set.
	if os.Getenv("KEYBASE_SECRET_STORE_FILE") != "1" {
		return nil
	}
	return NewSecretStoreFile(g.Env.GetDataDir())
}

Add env flag to enable SecretStoreFile


package checkers

import (
	"fmt"
	"math"
)

type Point struct {
	X, Y int
}

func (p Point) Add(q Point) Point {
	return Point{p.X + q.X, p.Y + q.Y}
}

func (p Point) Sub(q Point) Point {
	return Point{p.X - q.X, p.Y - q.Y}
}

func (p Point) Equal(q Point) bool {
	if p.X == q.X && p.Y == q.Y {
		return true
	}
	return false
}

func (p Point) String() string {
	return fmt.Sprintf("(%d,%d)", p.X, p.Y)
}

func (p Point) Manhattan() int {
	return int(math.Abs(float64(0-p.X)) + math.Abs(float64(0-p.Y)))
}

func (p Point) ManhattanTo(q Point) int {
	return int(math.Abs(float64(p.X-q.X)) + math.Abs(float64(p.Y-q.Y)))
}

func (p *Point) Scale(factor int) *Point {
	p.X *= factor
	p.Y *= factor
	return p
}

func (p Point) Scaled(factor int) Point {
	return Point{p.X * factor, p.Y * factor}
}

package checkers

import (
	"fmt"
	"math"
)

type Point struct {
	X, Y int
}

func (p Point) Add(q Point) Point {
	return Point{p.X + q.X, p.Y + q.Y}
}

func (p Point) Sub(q Point) Point {
	return Point{p.X - q.X, p.Y - q.Y}
}

func (p Point) Equal(q Point) bool {
	return p.X == q.X && p.Y == q.Y
}

func (p Point) Less(q Point) bool {
	return p.X < q.X || (p.Y < q.Y && p.X == q.X)
}

func (p Point) String() string {
	return fmt.Sprintf("(%d,%d)", p.X, p.Y)
}

func (p Point) Manhattan() int {
	return int(math.Abs(float64(0-p.X)) + math.Abs(float64(0-p.Y)))
}

func (p Point) ManhattanTo(q Point) int {
	return int(math.Abs(float64(p.X-q.X)) + math.Abs(float64(p.Y-q.Y)))
}

func (p *Point) Scale(factor int) *Point {
	p.X *= factor
	p.Y *= factor
	return p
}

func (p Point) Scaled(factor int) Point {
	return Point{p.X * factor, p.Y * factor}
}

Refactor equality function and add less function


package sigctx

import (
	"context"
	"os"
	"os/signal"
	"sync"
	"syscall"

	"github.com/SentimensRG/ctx"
)

var (
	c    ctx.C
	once sync.Once
)

// New signal-bound ctx.C that terminates when either SIGINT or SIGTERM
// is caught.
func New() ctx.C {
	once.Do(func() {
		dc := make(chan struct{})
		c = dc

		ch := make(chan os.Signal, 1)
		signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)

		go func() {
			select {
			case <-ch:
				close(dc)
			case <-c.Done():
			}
		}()
	})

	return c
}

// NewContext calls New and wraps the result in a context.Context.  The result
// is a context that fires when either SIGINT or SIGTERM is caught.
func NewContext() context.Context {
	return ctx.AsContext(New())
}

package sigctx

import (
	"os"
	"os/signal"
	"sync"
	"syscall"

	"github.com/SentimensRG/ctx"
)

var (
	c    ctx.C
	once sync.Once
)

// New signal-bound ctx.C that terminates when either SIGINT or SIGTERM
// is caught.
func New() ctx.C {
	once.Do(func() {
		dc := make(chan struct{})
		c = dc

		ch := make(chan os.Signal, 1)
		signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)

		go func() {
			select {
			case <-ch:
				close(dc)
			case <-c.Done():
			}
		}()
	})

	return c
}

Remove functions that work on context.Context. Users should use ctx.AsContext


package docker

import (
	"time"

	dockerClient "github.com/fsouza/go-dockerclient"
	"github.com/rancherio/os/config"
)

const (
	MAX_WAIT = 30000
	INTERVAL = 100
)

func NewClient(cfg *config.Config) (*dockerClient.Client, error) {
	client, err := dockerClient.NewClient(cfg.DockerEndpoint)
	if err != nil {
		return nil, err
	}

	for i := 0; i < (MAX_WAIT / INTERVAL); i++ {
		_, err = client.Info()
		if err == nil {
			break
		}

		time.Sleep(INTERVAL * time.Millisecond)
	}

	if err != nil {
		return nil, err
	}

	return client, nil
}

package docker

import (
	"time"

	dockerClient "github.com/fsouza/go-dockerclient"
	"github.com/rancherio/os/config"
)

const (
	MAX_WAIT = 30000
	INTERVAL = 100
)

func NewClient(cfg *config.Config) (*dockerClient.Client, error) {
	endpoint := "unix:///var/run/docker.sock"
	if cfg != nil {
		endpoint = cfg.DockerEndpoint
	}
	client, err := dockerClient.NewClient(endpoint)
	if err != nil {
		return nil, err
	}

	for i := 0; i < (MAX_WAIT / INTERVAL); i++ {
		_, err = client.Info()
		if err == nil {
			break
		}

		time.Sleep(INTERVAL * time.Millisecond)
	}

	if err != nil {
		return nil, err
	}

	return client, nil
}

Support nil cfg for NewClient


package svnwatch

import (
	"encoding/xml"
	"fmt"
	"os"
	"os/exec"

	shellwords "github.com/mattn/go-shellwords"
	"github.com/pkg/errors"
)

type Command struct {
	XMLName xml.Name `xml:"command"`
	Command string   `xml:",chardata"`
}

func (c Command) Execute(repo Repository) error {
	pieces, err := shellwords.Parse(c.Command)

	if err != nil {
		return errors.Wrapf(err, "failed to parse %s", c.Command)
	}

	cmd := exec.Command(pieces[0], pieces[1:]...)
	cmd.Env = os.Environ()

	cmd.Env = append(
		os.Environ(),
		fmt.Sprintf("SVN_URL=%s", repo.URL),
		fmt.Sprintf("SVN_REVISION=%d", repo.Revision),
	)

	if err := cmd.Run(); err != nil {
		return errors.Wrapf(err, "failed to execute %s", c.Command)
	}

	return nil
}

package svnwatch

import (
	"encoding/xml"
	"fmt"
	"os"
	"os/exec"
	"strconv"

	shellwords "github.com/mattn/go-shellwords"
	"github.com/pkg/errors"
)

type Command struct {
	XMLName      xml.Name `xml:"command"`
	ArgumentType *string  `xml:"pass-type,attr,omitempty"`
	Command      string   `xml:",chardata"`
}

func (c Command) Execute(repo Repository) error {
	pieces, err := shellwords.Parse(c.Command)

	if err != nil {
		return errors.Wrapf(err, "failed to parse %s", c.Command)
	}

	cmd := exec.Command(pieces[0], pieces[1:]...)
	cmd.Env = os.Environ()

	if c.ArgumentType == nil || *c.ArgumentType == "normal" {
		cmd.Args = append(cmd.Args, repo.URL, strconv.Itoa(repo.Revision))
	} else if *c.ArgumentType == "env" {
		cmd.Env = append(
			os.Environ(),
			fmt.Sprintf("SVN_URL=%s", repo.URL),
			fmt.Sprintf("SVN_REVISION=%d", repo.Revision),
		)
	} else {
		return fmt.Errorf("invalid argument type %s for %s", *c.ArgumentType, c.Command)
	}

	if err := cmd.Run(); err != nil {
		return errors.Wrapf(err, "failed to execute %s", c.Command)
	}

	return nil
}

Allow repository information to be passed as arguments


package main

import (
	log "github.com/sirupsen/logrus"
	"github.com/urfave/cli"
	"time"
)

func RunPeriodically(c *cli.Context) error {

	log.SetFormatter(_makeFormatter(c.String("format")))

	log.WithFields(log.Fields{
		"appName": c.App.Name,
	}).Info("Running periodically")

	period := time.Duration(c.Int("period")) * time.Second

	for {
		go func() {
			PrintHeartbeat()
		}()

		time.Sleep(period)
	}

	return nil
}

func PrintHeartbeat() {
	log.WithFields(log.Fields{
		"type": "heartbeat",
	}).Info("Every heartbeat bears your name")
}

func _makeFormatter(format string) log.Formatter {
	switch format {
	case "text":
		return &log.TextFormatter{DisableColors: true}
	case "json":
		return &log.JSONFormatter{}
	default:
		return &log.JSONFormatter{}
	}
}

package main

import (
	log "github.com/sirupsen/logrus"
	"github.com/urfave/cli"
	"time"
)

func RunPeriodically(c *cli.Context) error {

	log.SetFormatter(_makeFormatter(c.String("format")))

	log.WithFields(log.Fields{
		"appName": c.App.Name,
	}).Info("Running periodically")

	period := time.Duration(c.Int("period")) * time.Second

	for {
		go func() {
			PrintHeartbeat()
		}()

		time.Sleep(period)
	}

}

func PrintHeartbeat() {
	log.WithFields(log.Fields{
		"type": "heartbeat",
	}).Info("Every heartbeat bears your name")
}

func _makeFormatter(format string) log.Formatter {
	switch format {
	case "text":
		return &log.TextFormatter{DisableColors: true}
	case "json":
		return &log.JSONFormatter{}
	default:
		return &log.JSONFormatter{}
	}
}

Remove unreachable code per `go vet`


package run_test

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/influxdata/influxdb/cmd/influxd/run"
)

func TestCommand_PIDFile(t *testing.T) {
	tmpdir, err := ioutil.TempDir(os.TempDir(), "influxd-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	pidFile := filepath.Join(tmpdir, "influxdb.pid")

	cmd := run.NewCommand()
	if err := cmd.Run("-pidfile", pidFile); err != nil {
		t.Fatalf("unexpected error: %s", err)
	}

	if _, err := os.Stat(pidFile); err != nil {
		t.Fatalf("could not stat pid file: %s", err)
	}
	go cmd.Close()

	timeout := time.NewTimer(100 * time.Millisecond)
	select {
	case <-timeout.C:
		t.Fatal("unexpected timeout")
	case <-cmd.Closed:
		timeout.Stop()
	}

	if _, err := os.Stat(pidFile); err == nil {
		t.Fatal("expected pid file to be removed")
	}
}

package run_test

import (
	"io/ioutil"
	"os"
	"path/filepath"
	"testing"
	"time"

	"github.com/influxdata/influxdb/cmd/influxd/run"
)

func TestCommand_PIDFile(t *testing.T) {
	tmpdir, err := ioutil.TempDir(os.TempDir(), "influxd-test")
	if err != nil {
		t.Fatal(err)
	}
	defer os.RemoveAll(tmpdir)

	pidFile := filepath.Join(tmpdir, "influxdb.pid")

	cmd := run.NewCommand()
	cmd.Getenv = func(key string) string {
		switch key {
		case "INFLUXDB_BIND_ADDRESS", "INFLUXDB_HTTP_BIND_ADDRESS":
			return "127.0.0.1:0"
		default:
			return os.Getenv(key)
		}
	}
	if err := cmd.Run("-pidfile", pidFile); err != nil {
		t.Fatalf("unexpected error: %s", err)
	}

	if _, err := os.Stat(pidFile); err != nil {
		t.Fatalf("could not stat pid file: %s", err)
	}
	go cmd.Close()

	timeout := time.NewTimer(100 * time.Millisecond)
	select {
	case <-timeout.C:
		t.Fatal("unexpected timeout")
	case <-cmd.Closed:
		timeout.Stop()
	}

	if _, err := os.Stat(pidFile); err == nil {
		t.Fatal("expected pid file to be removed")
	}
}

Use random port in PID file test


package main

import (
	"fmt"
	"github.com/ant0ine/go-json-rest/rest"
	"log"
	"net/http"
	"time"
)

func main() {

	router, err := rest.MakeRouter(
		&rest.Route{"GET", "/stream", StreamThings},
	)
	if err != nil {
		log.Fatal(err)
	}

	api := rest.NewApi(router)
	api.Use(&rest.AccessLogApacheMiddleware{})
	api.Use(&rest.TimerMiddleware{})
	api.Use(&rest.RecorderMiddleware{})
	api.Use(&rest.RecoverMiddleware{})

	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}

type Thing struct {
	Name string
}

func StreamThings(w rest.ResponseWriter, r *rest.Request) {
	cpt := 0
	for {
		cpt++
		w.WriteJson(
			&Thing{
				Name: fmt.Sprintf("thing #%d", cpt),
			},
		)
		w.(http.ResponseWriter).Write([]byte("\n"))
		// Flush the buffer to client
		w.(http.Flusher).Flush()
		// wait 3 seconds
		time.Sleep(time.Duration(3) * time.Second)
	}
}

package main

import (
	"fmt"
	"github.com/ant0ine/go-json-rest/rest"
	"log"
	"net/http"
	"time"
)

func main() {
	router, err := rest.MakeRouter(
		&rest.Route{"GET", "/stream", StreamThings},
	)
	if err != nil {
		log.Fatal(err)
	}

	api := rest.NewApi(router)
	api.Use(&rest.AccessLogApacheMiddleware{})
	api.Use(rest.DefaultCommonStack...)
	log.Fatal(http.ListenAndServe(":8080", api.MakeHandler()))
}

type Thing struct {
	Name string
}

func StreamThings(w rest.ResponseWriter, r *rest.Request) {
	cpt := 0
	for {
		cpt++
		w.WriteJson(
			&Thing{
				Name: fmt.Sprintf("thing #%d", cpt),
			},
		)
		w.(http.ResponseWriter).Write([]byte("\n"))
		// Flush the buffer to client
		w.(http.Flusher).Flush()
		// wait 3 seconds
		time.Sleep(time.Duration(3) * time.Second)
	}
}

Make use of the common stack


package types

// ContainerCreateResponse contains the information returned to a client on the
// creation of a new container.
type ContainerCreateResponse struct {
	// ID is the ID of the created container.
	ID string `json:"Id"`

	// Warnings are any warnings encountered during the creation of the container.
	Warnings []string `json:"Warnings"`
}

// POST /containers/{name:.*}/exec
type ContainerExecCreateResponse struct {
	// ID is the exec ID.
	ID string `json:"Id"`

	// Warnings are any warnings encountered during the execution of the command.
	Warnings []string `json:"Warnings"`
}

// POST /auth
type AuthResponse struct {
	// Status is the authentication status
	Status string `json:"Status"`
}

// POST "/containers/"+containerID+"/wait"
type ContainerWaitResponse struct {
	// StatusCode is the status code of the wait job
	StatusCode int `json:"StatusCode"`
}

// POST "/commit?container="+containerID
type ContainerCommitResponse struct {
	ID string `json:"Id"`
}

Use ContainerCommitResponse struct for Commit cmd


package search

import "testing"

func TestSubset(t *testing.T) {
	var (
		a = &Asset{
			VideoID: "video-id-123",
			Type:    "movie",
		}

		s = &Series{
			BrandID: "brand-id-345",
			Type:    "series",
		}
	)

	t.Run("Asset", func(t *testing.T) {
		sub := Hit(a).Subset()

		if got, want := sub.ID, a.VideoID; got != want {
			t.Fatalf("sub.ID = %q, want %q", got, want)
		}

		if got, want := sub.Type, a.Type; got != want {
			t.Fatalf("sub.Type = %q, want %q", got, want)
		}
	})

	t.Run("Series", func(t *testing.T) {
		sub := Hit(s).Subset()

		if got, want := sub.ID, s.BrandID; got != want {
			t.Fatalf("sub.ID = %q, want %q", got, want)
		}

		if got, want := sub.Type, s.Type; got != want {
			t.Fatalf("sub.Type = %q, want %q", got, want)
		}
	})
}

package search

import "testing"

func TestSubset(t *testing.T) {
	t.Run("Asset", func(t *testing.T) {
		a := &Asset{
			VideoID: "video-id-123",
			Type:    "movie",
		}

		sub := Hit(a).Subset()

		if got, want := sub.ID, a.VideoID; got != want {
			t.Fatalf("sub.ID = %q, want %q", got, want)
		}

		if got, want := sub.Type, a.Type; got != want {
			t.Fatalf("sub.Type = %q, want %q", got, want)
		}
	})

	t.Run("Series", func(t *testing.T) {
		s := &Series{
			BrandID: "brand-id-345",
			Type:    "series",
		}

		sub := Hit(s).Subset()

		if got, want := sub.ID, s.BrandID; got != want {
			t.Fatalf("sub.ID = %q, want %q", got, want)
		}

		if got, want := sub.Type, s.Type; got != want {
			t.Fatalf("sub.Type = %q, want %q", got, want)
		}
	})
}

Move test data into the scope where it is used


package metastore

import "github.com/deejross/dep-registry/models"

// MetaStore represents a metadata store.
type MetaStore interface {
	// AddUpdateImport adds or updates an Import.
	AddUpdateImport(m *models.Import) error

	// AddVersion adds a Version to an import.
	AddVersion(v *models.Version) error

	// GetImport gets an Import.
	GetImport(url string) (*models.Import, error)

	// GetVersions gets a list of Versions for an Import.
	GetVersions(m *models.Import) ([]*models.Version, error)
}

package metastore

import "github.com/deejross/dep-registry/models"

// MetaStore represents a metadata store.
type MetaStore interface {
	// AddUpdateImport adds an Import if it doesn't exist.
	AddImportIfNotExists(m *models.Import) error

	// UpdateImport updates an import.
	UpdateImport(m *models.Import) error

	// AddVersion adds a Version to an import.
	AddVersion(v *models.Version) error

	// GetImport gets an Import.
	GetImport(url string) (*models.Import, error)

	// GetVersions gets a list of Versions for an Import.
	GetVersions(m *models.Import) ([]*models.Version, error)
}

Split Add and Update in Import interface


package apparmor_test

import (
	"github.com/cri-o/cri-o/internal/config/apparmor"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

// The actual test suite
var _ = t.Describe("Config", func() {
	var sut *apparmor.Config

	BeforeEach(func() {
		sut = apparmor.New()
		Expect(sut).NotTo(BeNil())

		if !sut.IsEnabled() {
			Skip("AppArmor is disabled")
		}
	})

	t.Describe("IsEnabled", func() {
		It("should be true per default", func() {
			// Given
			// When
			res := sut.IsEnabled()

			// Then
			Expect(res).To(BeTrue())
		})
	})

	t.Describe("LoadProfile", func() {
		It("should succeed with unconfied", func() {
			// Given
			// When
			err := sut.LoadProfile("unconfied")

			// Then
			Expect(err).To(BeNil())
		})
	})
})

package apparmor_test

import (
	"github.com/cri-o/cri-o/internal/config/apparmor"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

// The actual test suite
var _ = t.Describe("Config", func() {
	var sut *apparmor.Config

	BeforeEach(func() {
		sut = apparmor.New()
		Expect(sut).NotTo(BeNil())

		if !sut.IsEnabled() {
			Skip("AppArmor is disabled")
		}
	})

	t.Describe("IsEnabled", func() {
		It("should be true per default", func() {
			// Given
			// When
			res := sut.IsEnabled()

			// Then
			Expect(res).To(BeTrue())
		})
	})

	t.Describe("LoadProfile", func() {
		It("should succeed with unconfined", func() {
			// Given
			// When
			err := sut.LoadProfile("unconfined")

			// Then
			Expect(err).To(BeNil())
		})
	})
})

Fix typo in apparmor tests


package stripe

import "encoding/json"

// LoginLinkParams is the set of parameters that can be used when creating a login_link.
// For more details see https://stripe.com/docs/api#create_login_link.
type LoginLinkParams struct {
	Params
	Account string
}

// LoginLink is the resource representing a login link for Express accounts.
// For more details see https://stripe.com/docs/api#login_link_object
type LoginLink struct {
	Created  int64  `json:"created"`
	Url      string `json:"url"`
}

Call go fmt to fix the build


package main

// Copyright (c) 2016, crasm <crasm@vczf.io>
// This code is open source under the ISC license. See LICENSE for details.

import "os"

const DefaultPerm = 0644

// True if at most one is true. All can be false.
func isMutuallyExclusive(bools ...bool) bool {
	found := 0
	for _, b := range bools {
		if b {
			found++
		}
	}
	return found <= 1
}

// Creates the file at the given location. If opt.Force is set, the existing
// file is clobbered.
func createFile(path string, force bool) (*os.File, error) {
	callopt := os.O_CREATE | os.O_RDWR
	if force {
		callopt |= os.O_TRUNC
	} else {
		callopt |= os.O_EXCL
	}

	return os.OpenFile(path, callopt, DefaultPerm)
}

package main

// Copyright (c) 2016, crasm <crasm@vczf.io>
// This code is open source under the ISC license. See LICENSE for details.

import "os"

const DefaultPerm = 0644

// True if at most one is true. All can be false.
func isMutuallyExclusive(bools ...bool) bool {
	found := 0
	for _, b := range bools {
		if b {
			found++
		}
	}
	return found <= 1
}

// Creates the file at the given location. If force is set, the existing
// file is clobbered.
func createFile(path string, force bool) (*os.File, error) {
	callopt := os.O_CREATE | os.O_RDWR
	if force {
		callopt |= os.O_TRUNC
	} else {
		callopt |= os.O_EXCL
	}

	return os.OpenFile(path, callopt, DefaultPerm)
}

Fix comment to reflect not depending on opt.Force


package resource

import (
	"time"
)

// RetryFunc is the function retried until it succeeds.
type RetryFunc func() error

// Retry is a basic wrapper around StateChangeConf that will just retry
// a function until it no longer returns an error.
func Retry(timeout time.Duration, f RetryFunc) error {
	var err error
	c := &StateChangeConf{
		Pending:    []string{"error"},
		Target:     "success",
		Timeout:    timeout,
		MinTimeout: 500 * time.Millisecond,
		Refresh: func() (interface{}, string, error) {
			err = f()
			if err == nil {
				return 42, "success", nil
			}

			if rerr, ok := err.(RetryError); ok {
				err = rerr.Err
				return nil, "quit", err
			}

			return 42, "error", nil
		},
	}

	c.WaitForState()
	return err
}

// RetryError, if returned, will quit the retry immediately with the
// Err.
type RetryError struct {
	Err error
}

func (e RetryError) Error() string {
	return e.Err.Error()
}

package resource

import (
	"time"
)

// RetryFunc is the function retried until it succeeds.
type RetryFunc func() error

// Retry is a basic wrapper around StateChangeConf that will just retry
// a function until it no longer returns an error.
func Retry(timeout time.Duration, f RetryFunc) error {
	c := &StateChangeConf{
		Pending:    []string{"error"},
		Target:     "success",
		Timeout:    timeout,
		MinTimeout: 500 * time.Millisecond,
		Refresh: func() (interface{}, string, error) {
			err := f()
			if err == nil {
				return 42, "success", nil
			}

			if rerr, ok := err.(RetryError); ok {
				err = rerr.Err
				return nil, "quit", err
			}

			return 42, "error", nil
		},
	}

	_, err := c.WaitForState()
	return err
}

// RetryError, if returned, will quit the retry immediately with the
// Err.
type RetryError struct {
	Err error
}

func (e RetryError) Error() string {
	return e.Err.Error()
}

Fix data race in resource.Retry


package utils

import (
	"fmt"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
)

func TestDB() *gorm.DB {
	dbuser, dbpwd, dbname := "qor", "qor", "qor_test"

	if os.Getenv("TEST_ENV") == "CI" {
		dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD")
	}

	var db gorm.DB
	var err error

	if os.Getenv("TEST_DB") == "postgres" {
		db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", dbuser, dbpwd, dbname))
	} else {
		db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname))
	}

	if err != nil {
		panic(err)
	}

	return &db
}

package utils

import (
	"fmt"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
)

func TestDB() *gorm.DB {
	dbuser, dbpwd, dbname := "qor", "qor", "qor_test"

	if os.Getenv("TEST_ENV") == "CI" {
		dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD")
	}

	var db gorm.DB
	var err error

	if os.Getenv("TEST_DB") == "postgres" {
		db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", dbuser, dbpwd, dbname))
	} else {
		// CREATE USER 'qor'@'localhost' IDENTIFIED BY 'qor';
		// CREATE DATABASE qor_test;
		// GRANT ALL ON qor_test.* TO 'qor'@'localhost';
		db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname))
	}

	if err != nil {
		panic(err)
	}

	return &db
}

Add guide for how to create test db for mysql


package nodes

// NewHeaderNode creates a new HeaderNode with optional content nodes n.
func NewHeaderNode(level int, n ...Node) *HeaderNode {
	return &HeaderNode{
		node:    node{typ: NodeHeader},
		Level:   level,
		Content: NewListNode(n...),
	}
}

// HeaderNode is any regular header, a checklist header, or an FAQ header.
type HeaderNode struct {
	node
	Level   int
	Content *ListNode
}

// Empty returns true if header content is empty.
func (hn *HeaderNode) Empty() bool {
	return hn.Content.Empty()
}

// IsHeader returns true if t is one of header types.
func IsHeader(t NodeType) bool {
	return t&(NodeHeader|NodeHeaderCheck|NodeHeaderFAQ) != 0
}

func (hn *HeaderNode) MutateType(t NodeType) {
	if IsHeader(t) {
		hn.typ = t
	}
}

package nodes

// NewHeaderNode creates a new HeaderNode with optional content nodes n.
func NewHeaderNode(level int, n ...Node) *HeaderNode {
	return &HeaderNode{
		node:    node{typ: NodeHeader},
		Level:   level,
		Content: NewListNode(n...),
	}
}

// HeaderNode is any regular header, a checklist header, or an FAQ header.
type HeaderNode struct {
	node
	Level   int
	Content *ListNode
}

// Empty returns true if header content is empty.
func (hn *HeaderNode) Empty() bool {
	return hn.Content.Empty()
}

// IsHeader returns true if t is one of header types.
func IsHeader(t NodeType) bool {
	return t&(NodeHeader|NodeHeaderCheck|NodeHeaderFAQ) != 0
}

// MutateType sets the header's node type if the given type is a header type.
func (hn *HeaderNode) MutateType(t NodeType) {
	if IsHeader(t) {
		hn.typ = t
	}
}

Add comment to HeaderNode's MutateType.


package main

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

func init() {
	log.SetOutput(os.Stdout)
}

func handler(w http.ResponseWriter, r *http.Request) {
	log.Println("Got", r.Method, "to:", r.URL)

	var keys []string
	for k := range r.Header {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	log.Println("Request Headers:")
	for _, k := range keys {
		log.Println("  ", k, ":", r.Header[k])
	}

	log.Println("Body:")
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(-1)
	}
	log.Println(string(body))
	log.Println("---End Body---")

	fmt.Fprintln(w, "Logged request.")
}

func main() {
	http.HandleFunc("/", handler)
	log.Println("Listening on port 6000...")
	http.ListenAndServe(":6000", nil)
}

package main

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

func init() {
	log.SetOutput(os.Stdout)
}

func handler(w http.ResponseWriter, r *http.Request) {
	log.Println("Got", r.Method, "to:", r.URL)

	var keys []string
	for k := range r.Header {
		keys = append(keys, k)
	}
	sort.Strings(keys)

	log.Println("Request Headers:")
	for _, k := range keys {
		log.Println("  ", k, ":", r.Header[k])
	}

	log.Println("Body:")
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		panic(-1)
	}
	log.Println(string(body))
	log.Println("---End Body---")

	fmt.Fprintln(w, "Logged request.")
}

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

	port := "6000"
	if os.Getenv("PORT") != "" {
		port = os.Getenv("PORT")
	}
	log.Println("Listening on port", port, "...")
	http.ListenAndServe(":"+port, nil)
}

Use port from environment variable if specified


package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"github.com/Symantec/Dominator/lib/srpc"
	"io/ioutil"
	"os"
)

func setupTls() {
	if *caFile == "" || *certFile == "" || *keyFile == "" {
		return
	}
	caData, err := ioutil.ReadFile(*caFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to load CA file\t%s\n",
			err)
		os.Exit(1)
	}
	caCertPool := x509.NewCertPool()
	if !caCertPool.AppendCertsFromPEM(caData) {
		fmt.Fprintln(os.Stderr, "Unable to parse CA file")
		os.Exit(1)
	}
	serverConfig := new(tls.Config)
	serverConfig.ClientAuth = tls.RequireAndVerifyClientCert
	serverConfig.ClientCAs = caCertPool
	cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to load keypair\t%s\n",
			err)
		os.Exit(1)
	}
	serverConfig.Certificates = append(serverConfig.Certificates, cert)
	srpc.RegisterServerTlsConfig(serverConfig, false)
}

package main

import (
	"crypto/tls"
	"crypto/x509"
	"fmt"
	"github.com/Symantec/Dominator/lib/srpc"
	"io/ioutil"
	"os"
)

func setupTls() {
	if *caFile == "" || *certFile == "" || *keyFile == "" {
		return
	}
	caData, err := ioutil.ReadFile(*caFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to load CA file\t%s\n",
			err)
		os.Exit(1)
	}
	caCertPool := x509.NewCertPool()
	if !caCertPool.AppendCertsFromPEM(caData) {
		fmt.Fprintln(os.Stderr, "Unable to parse CA file")
		os.Exit(1)
	}
	serverConfig := new(tls.Config)
	serverConfig.ClientAuth = tls.RequireAndVerifyClientCert
	serverConfig.MinVersion = tls.VersionTLS12
	serverConfig.ClientCAs = caCertPool
	cert, err := tls.LoadX509KeyPair(*certFile, *keyFile)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Unable to load keypair\t%s\n",
			err)
		os.Exit(1)
	}
	serverConfig.Certificates = append(serverConfig.Certificates, cert)
	srpc.RegisterServerTlsConfig(serverConfig, false)
}

Change subd to require TLS v1.2 or greater.


package main

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

	"github.com/anacrolix/torrent/metainfo"
)

func main() {
	name := flag.Bool("name", false, "print name")
	flag.Parse()
	for _, filename := range flag.Args() {
		metainfo, err := metainfo.LoadFromFile(filename)
		if err != nil {
			log.Print(err)
			continue
		}
		if *name {
			fmt.Printf("%s\n", metainfo.Info.Name)
			continue
		}
		d := map[string]interface{}{
			"Name":      metainfo.Info.Name,
			"NumPieces": metainfo.Info.NumPieces(),
		}
		b, _ := json.MarshalIndent(d, "", "  ")
		os.Stdout.Write(b)
	}
	if !*name {
		os.Stdout.WriteString("\n")
	}
}

package main

import (
	"encoding/hex"
	"encoding/json"
	"fmt"
	"log"
	"os"

	"github.com/anacrolix/tagflag"
	"github.com/bradfitz/iter"

	"github.com/anacrolix/torrent/metainfo"
)

var flags struct {
	JustName    bool
	PieceHashes bool
	tagflag.StartPos
	TorrentFiles []string
}

func main() {
	tagflag.Parse(&flags)
	for _, filename := range flags.TorrentFiles {
		metainfo, err := metainfo.LoadFromFile(filename)
		if err != nil {
			log.Print(err)
			continue
		}
		info := &metainfo.Info.Info
		if flags.JustName {
			fmt.Printf("%s\n", metainfo.Info.Name)
			continue
		}
		d := map[string]interface{}{
			"Name":        info.Name,
			"NumPieces":   info.NumPieces(),
			"PieceLength": info.PieceLength,
		}
		if flags.PieceHashes {
			d["PieceHashes"] = func() (ret []string) {
				for i := range iter.N(info.NumPieces()) {
					ret = append(ret, hex.EncodeToString(info.Pieces[i*20:(i+1)*20]))
				}
				return
			}()
		}
		b, _ := json.MarshalIndent(d, "", "  ")
		os.Stdout.Write(b)
	}
	if !flags.JustName {
		os.Stdout.WriteString("\n")
	}
}

Switch to tagflag for argument parsing


package editor

import (
	"context"
	"strings"
	"testing"
)

func BenchmarkNormal(b *testing.B) {
	for i := 0; i < b.N; i++ {
		command := "hjkl"
		ed := normal{
			streamSet: streamSet{in: NewReaderContext(context.TODO(), strings.NewReader(command))},
			editor:    newEditor(),
		}
		for range command {
			_, _, err := ed.Run()
			if err != nil {
				b.Errorf("normal: %v", err)
			}
		}
	}
}

package editor

import (
	"context"
	"strings"
	"testing"
)

func BenchmarkNormal(b *testing.B) {
	for i := 0; i < b.N; i++ {
		command := strings.Repeat("hjkl", 100)
		ed := normal{
			streamSet: streamSet{in: NewReaderContext(context.TODO(), strings.NewReader(command))},
			editor:    newEditor(),
		}
		for range command {
			_, _, err := ed.Run()
			if err != nil {
				b.Errorf("normal: %v", err)
			}
		}
	}
}

Use a longer command to measure performance properly


// +build linux,cgo

package term

import (
	"syscall"
	"unsafe"
)

// #include <termios.h>
import "C"

type Termios syscall.Termios

// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd uintptr) (*State, error) {
	var oldState State
	if err := tcget(fd, &oldState.termios); err != 0 {
		return nil, err
	}

	newState := oldState.termios

	C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState)))
	if err := tcset(fd, &newState); err != 0 {
		return nil, err
	}
	return &oldState, nil
}

func tcget(fd uintptr, p *Termios) syscall.Errno {
	ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p)))
	if ret != 0 {
		return err.(syscall.Errno)
	}
	return 0
}

func tcset(fd uintptr, p *Termios) syscall.Errno {
	ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p)))
	if ret != 0 {
		return err.(syscall.Errno)
	}
	return 0
}

// +build linux,cgo

package term

import (
	"syscall"
	"unsafe"
)

// #include <termios.h>
import "C"

type Termios syscall.Termios

// MakeRaw put the terminal connected to the given file descriptor into raw
// mode and returns the previous state of the terminal so that it can be
// restored.
func MakeRaw(fd uintptr) (*State, error) {
	var oldState State
	if err := tcget(fd, &oldState.termios); err != 0 {
		return nil, err
	}

	newState := oldState.termios

	C.cfmakeraw((*C.struct_termios)(unsafe.Pointer(&newState)))
	newState.Oflag = newState.Oflag | C.OPOST
	if err := tcset(fd, &newState); err != 0 {
		return nil, err
	}
	return &oldState, nil
}

func tcget(fd uintptr, p *Termios) syscall.Errno {
	ret, err := C.tcgetattr(C.int(fd), (*C.struct_termios)(unsafe.Pointer(p)))
	if ret != 0 {
		return err.(syscall.Errno)
	}
	return 0
}

func tcset(fd uintptr, p *Termios) syscall.Errno {
	ret, err := C.tcsetattr(C.int(fd), C.TCSANOW, (*C.struct_termios)(unsafe.Pointer(p)))
	if ret != 0 {
		return err.(syscall.Errno)
	}
	return 0
}

Fix weird terminal output format


package main

import (
	"fmt"
	"github.com/sdegutis/go.fsevents"
	"log"
	"os"
	"os/exec"
)

func main() {
	if len(os.Args) < 3 {
		fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY|FILE COMMAND [ARGS…]")
		os.Exit(1)
	}

	ch := fsevents.WatchPaths([]string{os.Args[1]})

	var cmd *exec.Cmd

	go func() {
		for _ = range ch {
			log.Println("Changes detected, restarting")
			cmd.Process.Signal(os.Interrupt)
		}
	}()

	for {
		cmd = exec.Command(os.Args[2])
		cmd.Args = os.Args[2:]
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
		err := cmd.Run()
		if err != nil {
			if _, ok := err.(*exec.ExitError); !ok {
				log.Fatal(err)
			}
		}
	}
}

package main

import (
	"fmt"
	"github.com/sdegutis/go.fsevents"
	"log"
	"os"
	"os/exec"
	"time"
)

func main() {
	if len(os.Args) < 3 {
		fmt.Fprintln(os.Stderr, "Usage: aroc DIRECTORY|FILE COMMAND [ARGS…]")
		os.Exit(1)
	}

	ch := fsevents.WatchPaths([]string{os.Args[1]})

	var cmd *exec.Cmd

	go func() {
		for _ = range ch {

		WAIT:
			// Wait 1 second in case multiple events occur in quick succession
			for {
				select {
				case <-ch:
				case <-time.After(1 * time.Second):
					break WAIT
				}
			}

			log.Println("Changes detected, restarting")
			cmd.Process.Signal(os.Interrupt)
		}
	}()

	for {
		cmd = exec.Command(os.Args[2])
		cmd.Args = os.Args[2:]
		cmd.Stdout, cmd.Stderr = os.Stdout, os.Stderr
		err := cmd.Run()
		if err != nil {
			if _, ok := err.(*exec.ExitError); !ok {
				log.Fatal(err)
			}
		}
	}
}

Add wait of 1 second waiting for further events


package model

import (
	"testing"

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

func TestFindOrCreateTagByNameShouldCreateTag(t *testing.T) {
	tag, _, err := FindOrCreateTagByName(db, "my-tag")
	assert.Nil(t, err)
	assert.NotNil(t, tag)
	assert.Equal(t, "my-tag", tag.Name)

	var check Tag
	db.Where("name = ?", "my-tag").First(&check)
	assert.Equal(t, "my-tag", check.Name)
}

package model

import (
	"testing"

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

func TestFindOrCreateTagByNameShouldCreateTag(t *testing.T) {
	tag, created, err := FindOrCreateTagByName(db, "my-tag")
	assert.Nil(t, err)
	assert.NotNil(t, tag)
	assert.True(t, created)
	assert.Equal(t, "my-tag", tag.Name)

	var check Tag
	db.Where("name = ?", "my-tag").First(&check)
	assert.Equal(t, "my-tag", check.Name)
}

func TestFindOrCreateTagShouldNotCreateDuplicateNames(t *testing.T) {
	tag, created, err := FindOrCreateTagByName(db, "foo")
	assert.Nil(t, err)
	assert.NotNil(t, tag)
	assert.True(t, created)
	assert.Equal(t, "foo", tag.Name)

	tag, created, err = FindOrCreateTagByName(db, "foo")
	assert.Nil(t, err)
	assert.NotNil(t, tag)
	assert.False(t, created)
	assert.Equal(t, "foo", tag.Name)

	var tags []Tag
	db.Where("name = ?", "foo").Find(&tags)
	assert.Equal(t, 1, len(tags))
}

Add test for no duplicate tags


package execext

import (
	"context"
	"errors"
	"io"
	"strings"

	"github.com/mvdan/sh/interp"
	"github.com/mvdan/sh/syntax"
)

// RunCommandOptions is the options for the RunCommand func
type RunCommandOptions struct {
	Context context.Context
	Command string
	Dir     string
	Env     []string
	Stdin   io.Reader
	Stdout  io.Writer
	Stderr  io.Writer
}

var (
	// ErrNilOptions is returned when a nil options is given
	ErrNilOptions = errors.New("execext: nil options given")
)

// RunCommand runs a shell command
func RunCommand(opts *RunCommandOptions) error {
	if opts == nil {
		return ErrNilOptions
	}

	p, err := syntax.Parse(strings.NewReader(opts.Command), "", 0)
	if err != nil {
		return err
	}

	r := interp.Runner{
		Context: opts.Context,
		File:    p,
		Dir:     opts.Dir,
		Env:     opts.Env,
		Stdin:   opts.Stdin,
		Stdout:  opts.Stdout,
		Stderr:  opts.Stderr,
	}
	if err = r.Run(); err != nil {
		return err
	}
	return nil
}

package execext

import (
	"context"
	"errors"
	"io"
	"strings"

	"github.com/mvdan/sh/interp"
	"github.com/mvdan/sh/syntax"
)

// RunCommandOptions is the options for the RunCommand func
type RunCommandOptions struct {
	Context context.Context
	Command string
	Dir     string
	Env     []string
	Stdin   io.Reader
	Stdout  io.Writer
	Stderr  io.Writer
}

var (
	// ErrNilOptions is returned when a nil options is given
	ErrNilOptions = errors.New("execext: nil options given")

	parser = syntax.NewParser()
)

// RunCommand runs a shell command
func RunCommand(opts *RunCommandOptions) error {
	if opts == nil {
		return ErrNilOptions
	}

	p, err := parser.Parse(strings.NewReader(opts.Command), "")
	if err != nil {
		return err
	}

	r := interp.Runner{
		Context: opts.Context,
		File:    p,
		Dir:     opts.Dir,
		Env:     opts.Env,
		Stdin:   opts.Stdin,
		Stdout:  opts.Stdout,
		Stderr:  opts.Stderr,
	}
	if err = r.Run(); err != nil {
		return err
	}
	return nil
}

Fix build after update of dependency


package matchers

import (
	"fmt"
	"reflect"
)

type AssignableToMatcher struct {
	Expected interface{}
}

func (matcher *AssignableToMatcher) Match(actual interface{}) (success bool, message string, err error) {
	if actual == nil || matcher.Expected == nil {
		return false, "", fmt.Errorf("Refusing to compare <nil> to <nil>.")
	}

	actualType := reflect.TypeOf(actual)
	expectedType := reflect.TypeOf(matcher.Expected)

	if actualType.AssignableTo(expectedType) {
		return true, formatMessage(actual, "not fitting type", matcher.Expected), nil
	} else {
		return false, formatMessage(actual, "fitting type", matcher.Expected), nil
	}
}

package matchers

import (
	"fmt"
	"reflect"
)

type AssignableToMatcher struct {
	Expected interface{}
}

func (matcher *AssignableToMatcher) Match(actual interface{}) (success bool, message string, err error) {
	if actual == nil || matcher.Expected == nil {
		return false, "", fmt.Errorf("Refusing to compare <nil> to <nil>.")
	}

	actualType := reflect.TypeOf(actual)
	expectedType := reflect.TypeOf(matcher.Expected)

	if actualType.AssignableTo(expectedType) {
		return true, formatMessage(actual, fmt.Sprintf("not to be assignable to the type: %T", matcher.Expected)), nil
	} else {
		return false, formatMessage(actual, fmt.Sprintf("to be assignable to the type: %T", matcher.Expected)), nil
	}
}

Update error messages to reflect semantics


package reporters

import (
	"os/exec"

	"github.com/approvals/go-approval-tests/utils"
)

// NewFrontLoadedReporter creates the default front loaded reporter.
func NewFrontLoadedReporter() *Reporter {
	tmp := NewFirstWorkingReporter(
		NewContinuousIntegrationReporter(),
	)

	return &tmp
}

// NewDiffReporter creates the default diff reporter.
func NewDiffReporter() *Reporter {
	tmp := NewFirstWorkingReporter(
		NewBeyondCompareReporter(),
		NewIntelliJReporter(),
		NewPrintSupportedDiffProgramsReporter(),
		NewQuietReporter(),
		NewGoGlandReporter(),
	)

	return &tmp
}

func launchProgram(programName, approved string, args ...string) bool {
	if !utils.DoesFileExist(programName) {
		return false
	}

	utils.EnsureExists(approved)

	cmd := exec.Command(programName, args...)
	cmd.Start()
	return true
}

package reporters

import (
	"os/exec"

	"github.com/approvals/go-approval-tests/utils"
)

// NewFrontLoadedReporter creates the default front loaded reporter.
func NewFrontLoadedReporter() *Reporter {
	tmp := NewFirstWorkingReporter(
		NewContinuousIntegrationReporter(),
	)

	return &tmp
}

// NewDiffReporter creates the default diff reporter.
func NewDiffReporter() *Reporter {
	tmp := NewFirstWorkingReporter(
		NewBeyondCompareReporter(),
		NewIntelliJReporter(),
		NewGoGlandReporter(),
		NewPrintSupportedDiffProgramsReporter(),
		NewQuietReporter(),
	)

	return &tmp
}

func launchProgram(programName, approved string, args ...string) bool {
	if !utils.DoesFileExist(programName) {
		return false
	}

	utils.EnsureExists(approved)

	cmd := exec.Command(programName, args...)
	cmd.Start()
	return true
}

Move Gogland report higher up list because it couldn’t be used.


package jobs

import (
	"fmt"
	"time"
)

// WorkersList is a map associating a worker type with its acutal
// configuration.
type WorkersList map[string]*WorkerConfig

// WorkersList is the list of available workers with their associated Do
// function.
var workersList WorkersList

func init() {
	workersList = WorkersList{
		"print": {
			Concurrency: 4,
			WorkerFunc: func(m *Message, _ <-chan time.Time) error {
				var msg string
				if err := m.Unmarshal(&msg); err != nil {
					return err
				}
				_, err := fmt.Println(msg)
				return err
			},
		},
		"timeout": {
			Concurrency: 4,
			Timeout:     1 * time.Second,
			WorkerFunc: func(_ *Message, timeout <-chan time.Time) error {
				<-timeout
				return ErrTimedOut
			},
		},
	}
}

// GetWorkersList returns a globally defined worker config list
func GetWorkersList() WorkersList {
	return workersList
}

package jobs

import (
	"fmt"
	"time"
)

// WorkersList is a map associating a worker type with its acutal
// configuration.
type WorkersList map[string]*WorkerConfig

// WorkersList is the list of available workers with their associated Do
// function.
var workersList WorkersList

func init() {
	workersList = WorkersList{
		"print": {
			Concurrency: 4,
			WorkerFunc: func(m *Message, _ <-chan time.Time) error {
				var msg string
				if err := m.Unmarshal(&msg); err != nil {
					return err
				}
				_, err := fmt.Println(msg)
				return err
			},
		},
		"timeout": {
			Concurrency: 4,
			Timeout:     10 * time.Second,
			WorkerFunc: func(_ *Message, timeout <-chan time.Time) error {
				<-timeout
				return ErrTimedOut
			},
		},
	}
}

// GetWorkersList returns a globally defined worker config list
func GetWorkersList() WorkersList {
	return workersList
}

Increase timeout for timeout job


package resources

import "github.com/cloudfoundry/cli/cf/models"

type PaginatedSpaceQuotaResources struct {
	Resources []SpaceQuotaResource
}

type SpaceQuotaResource struct {
	Resource
	Entity models.SpaceQuota
}

func (resource SpaceQuotaResource) ToModel() models.SpaceQuota {
	entity := resource.Entity

	return models.SpaceQuota{
		Guid:                    resource.Metadata.Guid,
		Name:                    entity.Name,
		MemoryLimit:             entity.MemoryLimit,
		RoutesLimit:             entity.RoutesLimit,
		ServicesLimit:           entity.ServicesLimit,
		NonBasicServicesAllowed: entity.NonBasicServicesAllowed,
		OrgGuid:                 entity.OrgGuid,
	}
}

package resources

import "github.com/cloudfoundry/cli/cf/models"

type PaginatedSpaceQuotaResources struct {
	Resources []SpaceQuotaResource
}

type SpaceQuotaResource struct {
	Resource
	Entity models.SpaceQuota
}

func (resource SpaceQuotaResource) ToModel() models.SpaceQuota {
	entity := resource.Entity

	return models.SpaceQuota{
		Guid:                    resource.Metadata.Guid,
		Name:                    entity.Name,
		MemoryLimit:             entity.MemoryLimit,
		InstanceMemoryLimit:     entity.InstanceMemoryLimit,
		RoutesLimit:             entity.RoutesLimit,
		ServicesLimit:           entity.ServicesLimit,
		NonBasicServicesAllowed: entity.NonBasicServicesAllowed,
		OrgGuid:                 entity.OrgGuid,
	}
}

Fix instance memory output for space-quota(s).


/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements. See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership. The ASF licenses this file
 * to you 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 thrift

import (
	"testing"
)

func TestReadWriteBinaryProtocol(t *testing.T) {
	ReadWriteProtocolTest(t, NewTBinaryProtocolFactoryDefault())
}

func BenchmarkBinaryReadString(b *testing.B) {
	var (
		trans = NewTMemoryBuffer()
		p     = NewTBinaryProtocolTransport(trans)
	)

	b.ResetTimer()

	for i := 0; i < b.N; i++ {
		ReadWriteString(b, p, trans)
	}
}

Add a ReadString Benchmark for the binary protocol


// Copyright 2016 the <project> 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 "fmt"

func main() {
	sum := 0
	for i := 1; i < 1000; i++ {
		if i%3 == 0 || i%5 == 0 {
			sum += i
		}
	}

	fmt.Println(sum)
}

Remove useless space from Go solution problem 1


package sys

type MockExecutor struct {
	Exec chan string
	Args chan []string

	OutStr chan string
	OutErr chan error
}

func NewMockExecutor() *MockExecutor {
	return &MockExecutor{
		Exec: make(chan string, 1),
		Args: make(chan []string, 1),

		OutStr: make(chan string, 1),
		OutErr: make(chan error, 1),
	}
}

func (me *MockExecutor) Execute(exec string, args ...string) (string, error) {
	me.Exec <- exec
	me.Args <- args

	return <-me.OutStr, <-me.OutErr
}

type StubExecutor struct {
	Exec chan string
	Args chan []string

	out string
	err error
}

func NewStubExecutor(out string, err error) *StubExecutor {
	return &StubExecutor{
		Exec: make(chan string, 1),
		Args: make(chan []string, 1),

		out: out,
		err: err,
	}
}

func (se *StubExecutor) Execute(exec string, args ...string) (string, error) {
	se.Exec <- exec
	se.Args <- args

	return se.out, se.err
}

type funcExecutor func(string, ...string) (string, error)

func (f funcExecutor) Execute(cmd string, args ...string) (string, error) {
	return f(cmd, args...)
}

func NewFuncExecutor(fn func(string, ...string) (string, error)) Executor {
	var exec funcExecutor = fn

	return exec
}

Add stub sys.Executor constructor from a func


package ginkgomon

import (
	"fmt"
	"os"

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

func Invoke(runner ifrit.Runner) ifrit.Process {
	process := ifrit.Background(runner)

	select {
	case <-process.Ready():
	case err := <-process.Wait():
		ginkgo.Fail(fmt.Sprintf("process failed to start: %s", err))
	}

	return process
}

func Interrupt(process ifrit.Process, intervals ...interface{}) {
	process.Signal(os.Interrupt)
	Eventually(process.Wait(), intervals...).Should(Receive(), "interrupted ginkgomon process failed to exit in time")
}

func Kill(process ifrit.Process, intervals ...interface{}) {
	if process != nil {
		process.Signal(os.Kill)
		Eventually(process.Wait(), intervals...).Should(Receive(), "killed ginkgomon process failed to exit in time")
	}
}

package ginkgomon

import (
	"fmt"
	"os"

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

func Invoke(runner ifrit.Runner) ifrit.Process {
	process := ifrit.Background(runner)

	select {
	case <-process.Ready():
	case err := <-process.Wait():
		ginkgo.Fail(fmt.Sprintf("process failed to start: %s", err))
	}

	return process
}

func Interrupt(process ifrit.Process, intervals ...interface{}) {
	if process != nil {
		process.Signal(os.Interrupt)
		Eventually(process.Wait(), intervals...).Should(Receive(), "interrupted ginkgomon process failed to exit in time")
	}
}

func Kill(process ifrit.Process, intervals ...interface{}) {
	if process != nil {
		process.Signal(os.Kill)
		Eventually(process.Wait(), intervals...).Should(Receive(), "killed ginkgomon process failed to exit in time")
	}
}

Add same check for Interrupt that exists for Kill


// Copyright 2018 the u-root 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 sh

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

func RunOrDie(arg0 string, args ...string) {
	cmd := exec.Command(arg0, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	if err := cmd.Run(); err != nil {
		log.Fatal(err)
	}
}

// Copyright 2018 the u-root 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 sh

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

// Run runs a command with stdin, stdout and stderr.
func Run(arg0 string, args ...string) error {
	cmd := exec.Command(arg0, args...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr
	return cmd.Run()
}

// RunOrDie runs a commands with stdin, stdout and stderr. If there is a an
// error, it is fatally logged.
func RunOrDie(arg0 string, args ...string) {
	if err := Run(arg0, args...); err != nil {
		log.Fatal(err)
	}
}

Add sh.Run function and documentation


package auth

import (
	"testing"
)

func TestHeaderParsing(t *testing.T) {
	// Basic admin:password
	authorization := "Basic YWRtaW46cGFzc3dvcmQ="

	auth, err := parseAuthHeader(authorization)
	if err != nil {
		t.Error(err)
	}

	if auth.Name != "admin" {
		t.Errorf("Detected name does not match: '%s'", auth.Name)
	}
	if auth.Pass != "password" {
		t.Errorf("Detected password does not match: '%s'", auth.Pass)
	}
}

func TestEmptyHeader(t *testing.T) {
	if _, err := parseAuthHeader(""); err == nil {
		t.Errorf("Empty headers should generate errors")
	}
}

Add test for empty auth headers


package mint

import (
	"os"

	"github.com/bouk/monkey"
)

// Exit ...
func (testee *Testee) Exit(expectedCode int) Result {

	fun, ok := testee.actual.(func())
	if !ok {
		panic("mint error: Exit only can be called for func type value")
	}

	var actualCode int
	patch := monkey.Patch(os.Exit, func(code int) {
		actualCode = code
	})
	fun()
	patch.Unpatch()

	testee.actual = actualCode
	if judge(actualCode, expectedCode, testee.not, testee.deeply) {
		return testee.result
	}
	testee.expected = expectedCode
	return testee.failed(failExitCode)
}

package mint

import (
	"os"

	"bou.ke/monkey"
)

// Exit ...
func (testee *Testee) Exit(expectedCode int) Result {

	fun, ok := testee.actual.(func())
	if !ok {
		panic("mint error: Exit only can be called for func type value")
	}

	var actualCode int
	patch := monkey.Patch(os.Exit, func(code int) {
		actualCode = code
	})
	fun()
	patch.Unpatch()

	testee.actual = actualCode
	if judge(actualCode, expectedCode, testee.not, testee.deeply) {
		return testee.result
	}
	testee.expected = expectedCode
	return testee.failed(failExitCode)
}

Use "bou.ke/monkey" instead of "github.com/bouk/monkey"


package transcode

import (
	"errors"
)

var (
	// ErrInvalidCodec is returned when an invalid transcoder codec is selected
	ErrInvalidCodec = errors.New("transcode: no such transcoder codec")
	// ErrInvalidQuality is returned when an invalid quality is selected for a given codec
	ErrInvalidQuality = errors.New("transcode: invalid quality for transcoder codec")
)

// Enabled determines whether transcoding is available and enabled for wavepipe
var Enabled bool

// FFmpegPath is the path to the ffmpeg binary detected by the transcode manager
var FFmpegPath string

// Transcoder represents a transcoding operation, and the methods which must be defined
// for a transcoder
type Transcoder interface {
	Codec() string
	Quality() string
}

// Factory generates a new Transcoder depending on the input parameters
func Factory(codec string, quality string) (Transcoder, error) {
	// Check for a valid codec
	switch codec {
	// MP3
	case "mp3", "MP3":
		return NewMP3Transcoder(quality)
	// Invalid choice
	default:
		return nil, ErrInvalidCodec
	}
}

package transcode

import (
	"errors"

	"github.com/mdlayher/wavepipe/data"
)

var (
	// ErrInvalidCodec is returned when an invalid transcoder codec is selected
	ErrInvalidCodec = errors.New("transcode: no such transcoder codec")
	// ErrInvalidQuality is returned when an invalid quality is selected for a given codec
	ErrInvalidQuality = errors.New("transcode: invalid quality for transcoder codec")
)

// Enabled determines whether transcoding is available and enabled for wavepipe
var Enabled bool

// FFmpegPath is the path to the ffmpeg binary detected by the transcode manager
var FFmpegPath string

// Transcoder represents a transcoding operation, and the methods which must be defined
// for a transcoder
type Transcoder interface {
	Codec() string
	FFmpeg() *FFmpeg
	MIMEType() string
	SetSong(*data.Song)
	Quality() string
}

// Factory generates a new Transcoder depending on the input parameters
func Factory(codec string, quality string) (Transcoder, error) {
	// Check for a valid codec
	switch codec {
	// MP3
	case "mp3", "MP3":
		return NewMP3Transcoder(quality)
	// Invalid choice
	default:
		return nil, ErrInvalidCodec
	}
}

Add more necessary methods to Transcoder interface


package paths

import (
	"testing"

	. "github.com/VonC/godbg"
	. "github.com/smartystreets/goconvey/convey"
)

func TestArchive(t *testing.T) {

	Convey("Tests for Uncompress", t, func() {

		Convey("Uncompress fails if p is a folder", func() {
			p := NewPath(".")
			SetBuffers(nil)
			b := p.Uncompress(nil)
			So(b, ShouldBeFalse)
			So(OutString(), ShouldBeEmpty)
			So(ErrString(), ShouldEqualNL, `  [*Path.Uncompress] (func)
    Error while opening zip '.\' for '<nil>'
'read .\: The handle is invalid.'`)
		})
	})
}

package paths

import (
	"testing"

	. "github.com/VonC/godbg"
	. "github.com/smartystreets/goconvey/convey"
)

func TestArchive(t *testing.T) {

	Convey("Tests for Uncompress", t, func() {

		Convey("Uncompress fails if p is a folder", func() {
			p := NewPath(".")
			SetBuffers(nil)
			b := p.Uncompress(nil)
			So(b, ShouldBeFalse)
			So(OutString(), ShouldBeEmpty)
			So(ErrString(), ShouldEqualNL, `  [*Path.Uncompress] (func)
    Error while opening zip '.\' for '<nil>'
'read .\: The handle is invalid.'`)
		})

		Convey("Uncompress fails if p is not a zip file", func() {
			p := NewPath("paths.go")
			SetBuffers(nil)
			b := p.Uncompress(nil)
			So(b, ShouldBeFalse)
			So(OutString(), ShouldBeEmpty)
			So(ErrString(), ShouldEqualNL, `  [*Path.Uncompress] (func)
    Error while opening zip 'paths.go' for '<nil>'
'zip: not a valid zip file'`)
		})
	})
}

Test Path.Uncompress when p is not a zip file.


/*
	List of all task types.
*/

package task_types

import (
	"go.skia.org/infra/ct/go/ctfe/admin_tasks"
	"go.skia.org/infra/ct/go/ctfe/capture_skps"
	"go.skia.org/infra/ct/go/ctfe/chromium_analysis"
	"go.skia.org/infra/ct/go/ctfe/chromium_builds"
	"go.skia.org/infra/ct/go/ctfe/chromium_perf"
	"go.skia.org/infra/ct/go/ctfe/lua_scripts"
	"go.skia.org/infra/ct/go/ctfe/task_common"
)

// Slice of all tasks supported by CTFE.
func Prototypes() []task_common.Task {
	return []task_common.Task{
		&chromium_analysis.DBTask{},
		&chromium_perf.DBTask{},
		&capture_skps.DBTask{},
		&lua_scripts.DBTask{},
		&chromium_builds.DBTask{},
		&admin_tasks.RecreatePageSetsDBTask{},
		&admin_tasks.RecreateWebpageArchivesDBTask{},
	}
}

/*
	List of all task types.
*/

package task_types

import (
	"go.skia.org/infra/ct/go/ctfe/admin_tasks"
	"go.skia.org/infra/ct/go/ctfe/capture_skps"
	"go.skia.org/infra/ct/go/ctfe/chromium_analysis"
	"go.skia.org/infra/ct/go/ctfe/chromium_builds"
	"go.skia.org/infra/ct/go/ctfe/chromium_perf"
	"go.skia.org/infra/ct/go/ctfe/lua_scripts"
	"go.skia.org/infra/ct/go/ctfe/pixel_diff"
	"go.skia.org/infra/ct/go/ctfe/task_common"
)

// Slice of all tasks supported by CTFE.
func Prototypes() []task_common.Task {
	return []task_common.Task{
		&chromium_analysis.DBTask{},
		&chromium_perf.DBTask{},
		&pixel_diff.DBTask{},
		&capture_skps.DBTask{},
		&lua_scripts.DBTask{},
		&chromium_builds.DBTask{},
		&admin_tasks.RecreatePageSetsDBTask{},
		&admin_tasks.RecreateWebpageArchivesDBTask{},
	}
}

Add pixel diff to list of recognized tasks


package main

import (
  "os"
  "io/ioutil"
  "github.com/hashicorp/hcl/json/parser"
  "github.com/hashicorp/hcl/hcl/printer"
)

func main() {
  input, _ := ioutil.ReadAll(os.Stdin)

  ast, err := parser.Parse([]byte(input))
  if err != nil {
    panic(err)
  }

  err = printer.Fprint(os.Stdout, ast)
  if err != nil {
    panic(err)
  }
}

package main

import (
	"fmt"
	"io/ioutil"
	"os"

	"github.com/hashicorp/hcl/hcl/printer"
	"github.com/hashicorp/hcl/json/parser"
)

func main() {
	if err := convert(); err != nil {
		fmt.Fprintln(os.Stderr, err)
		os.Exit(1)
	}
}

func convert() error {
	input, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		return fmt.Errorf("unable to read from stdin: %s", err)
	}

	ast, err := parser.Parse([]byte(input))
	if err != nil {
		return fmt.Errorf("unable to parse JSON: %s", err)
	}

	err = printer.Fprint(os.Stdout, ast)
	if err != nil {
		return fmt.Errorf("unable to print HCL: %s", err)
	}

	return nil
}

Implement proper error handling and output


package main

import (
	"os"
	"strings"
	"time"
)

func main() {

	clients := strings.Split(os.Getenv("XLANG_CLIENTS"), ",")
	servers := strings.Split(os.Getenv("XLANG_SERVERS"), ",")
	behaviors := strings.Split(os.Getenv("XLANG_BEHAVIORS"), ",")

	matrix := Matrix{
		Clients:   clients,
		Servers:   servers,
		Behaviors: behaviors,
	}

	time.Sleep(1 * time.Second)

	results := BeginMatrixTest(matrix)

	OutputResults(results)
}

package main

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

func main() {

	clients := strings.Split(os.Getenv("XLANG_CLIENTS"), ",")
	servers := strings.Split(os.Getenv("XLANG_SERVERS"), ",")
	behaviors := strings.Split(os.Getenv("XLANG_BEHAVIORS"), ",")

	matrix := Matrix{
		Clients:   clients,
		Servers:   servers,
		Behaviors: behaviors,
	}

	fmt.Println("Waiting 1 second for test clients to come online")
	time.Sleep(1 * time.Second)

	fmt.Println("Begining matrix of tests")
	results := BeginMatrixTest(matrix)

	OutputResults(results)
}

Add messages around synchronizing clients


package compiler

type Expression struct {
	Name Translatable
	OnScan func(*Compiler) Type

	Detect func(*Compiler) *Type
}

func (c *Compiler) scanExpression() Type {
	var token = c.Scan()

	for _, expression := range c.Expressions {
		if expression.Name[c.Language] == token {
			return expression.OnScan(c)
		}
	}

	for _, expression := range c.Expressions {
		if expression.Detect != nil {
			if t := expression.Detect(c); t != nil {
				return *t
			}
		}
	}

	return Type{Name: NoTranslation(c.Token()), Fake: true}
}

func (c *Compiler) ScanExpression() Type {
	var result = c.Shunt(c.scanExpression(), 0)

	if result.Fake {
		c.RaiseError(Translatable{
				English: "Unknown Expression: "+result.Name[c.Language],
		})
	}

	return result
}

package compiler

type Expression struct {
	Name Translatable
	OnScan func(*Compiler) Type

	Detect func(*Compiler) *Type
}

func (c *Compiler) Expression() Type {
	var token = c.Scan()

	for _, expression := range c.Expressions {
		if expression.Name[c.Language] == token {
			return expression.OnScan(c)
		}
	}

	for _, expression := range c.Expressions {
		if expression.Detect != nil {
			if t := expression.Detect(c); t != nil {
				return *t
			}
		}
	}

	return Type{Name: NoTranslation(c.Token()), Fake: true}
}

func (c *Compiler) ScanExpression() Type {
	var result = c.Shunt(c.Expression(), 0)

	if result.Fake {
		c.RaiseError(Translatable{
				English: "Unknown Expression: "+result.Name[c.Language],
		})
	}

	return result
}

Allow Expression to be called as a Shuntless alternative to ScanExpression


package request

import (
	"github.com/franela/goblin"
	"testing"
)

func Test(t *testing.T) {
	g := goblin.Goblin(t)

	g.Describe("Get", func() {
		g.It("Errors when connection refused", func() {
			_, err := Get("http://localhost", map[string]string{
				"foo": "bar",
			})
			g.Assert(err.Error()).Equal("Get http://localhost: dial tcp 127.0.0.1:80: connection refused")
		})
	})
}

package request

import (
	"github.com/franela/goblin"
	"testing"
)

func Test(t *testing.T) {
	g := goblin.Goblin(t)

	g.Describe("Get", func() {
		g.It("Errors when connection refused", func() {
			_, err := Get("http://localhost:8000", map[string]string{
				"foo": "bar",
			})
			g.Assert(err.Error()).Equal("Get http://localhost:8000: dial tcp 127.0.0.1:8000: connection refused")
		})
	})
}

Adjust port so that test doesn't fail on my local machine 😄


package mc

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

	"testing"
)

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

package mc

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

	"os"
	"testing"
)

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

var _ = BeforeSuite(func() {
	os.RemoveAll(".materialscommons")
	os.RemoveAll("/tmp/mcdir")
})

var _ = AfterSuite(func() {
	//	os.RemoveAll(".materialscommons")
	//	os.RemoveAll("/tmp/mcdir")
})

Add Before and After Suite calls to clean up items.


package main

import (
	"log"
	"net/http"
)

func main() {
	router := NewRouter()

	log.Fatal(http.ListenAndServe(":80", router))
}

package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"strconv"
)

func main() {
	router := NewRouter()

	port := flag.Int("port", 8080, "Port to run on")
	flag.Parse()

	if *port < 1 || *port > 65536 {
		log.Fatal(string(*port) + " is not a valid port number. Exiting.")
	}

	portString := ":" + strconv.Itoa(*port)

	fmt.Printf("Starting server on port %s", portString)

	log.Fatal(http.ListenAndServe(portString, router))
}

Support specifying port as command-line flag on startup


/*
 * Copyright 2016 Frank Wessels <fwessels@xs4all.nl>
 *
 * 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 s3git

import (
	"errors"
)

// Get the full size unique hash for a given prefix.
// Return error in case none or multiple candidates are found
func (repo Repository) MakeUnique(prefix string) (string, error) {

	list, errList := repo.List(prefix)
	if errList != nil {
		return "", errList
	}

	err := errors.New("Not found (be less specific)")
	hash := ""
	for elem := range list {
		if len(hash) == 0 {
			hash, err = elem, nil
		} else {
			err = errors.New("More than one possiblity found (be more specific)")
		}
	}

	return hash, err
}

/*
 * Copyright 2016 Frank Wessels <fwessels@xs4all.nl>
 *
 * 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 s3git

import (
	"errors"
)

// Get the full size unique hash for a given prefix.
// Return error in case none or multiple candidates are found
func (repo Repository) MakeUnique(prefix string) (string, error) {

	list, errList := repo.List(prefix)
	if errList != nil {
		return "", errList
	}

	return getUnique(list)
}

func getUnique(list <-chan string) (string, error) {

	err := errors.New("Not found (be less specific)")
	hash := ""
	for elem := range list {
		if len(hash) == 0 {
			hash, err = elem, nil
		} else {
			err = errors.New("More than one possiblity found (be more specific)")
		}
	}

	return hash, err
}

Split MakeUnique function (to allow for more generic use, eg. commits as well)


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

package main

import (
	"github.com/hashicorp/terraform-plugin-sdk/v2/plugin"
	"github.com/sacloud/terraform-provider-sakuracloud/sakuracloud"
)

func main() {
	plugin.Serve(&plugin.ServeOpts{
		ProviderFunc: sakuracloud.Provider,
	})
}

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

package main

import (
	"context"
	"flag"
	"log"

	"github.com/hashicorp/terraform-plugin-sdk/v2/plugin"
	"github.com/sacloud/terraform-provider-sakuracloud/sakuracloud"
)

func main() {
	var debugMode bool

	flag.BoolVar(&debugMode, "debuggable", false, "set to true to run the provider with support for debuggers like delve")
	flag.Parse()

	if debugMode {
		err := plugin.Debug(context.Background(), "registry.terraform.io/sacloud/sakuracloud",
			&plugin.ServeOpts{
				ProviderFunc: sakuracloud.Provider,
			})
		if err != nil {
			log.Println(err.Error())
		}
	} else {
		plugin.Serve(&plugin.ServeOpts{
			ProviderFunc: sakuracloud.Provider})
	}
}

Support for Debuggable Provider Binaries - added -debuggable flag


package internal_test

import (
	"testing"
	"time"

	"github.com/instana/go-sensor/autoprofile/internal"
	"github.com/stretchr/testify/assert"
)

func TestTimer_Restart(t *testing.T) {
	var fired int
	timer := internal.NewTimer(0, 20*time.Millisecond, func() {
		fired++
	})

	time.Sleep(30 * time.Millisecond)
	timer.Stop()

	assert.Equal(t, 1, fired)

	time.Sleep(50 * time.Millisecond)
	assert.Equal(t, 1, fired)
}

func TestTimer_Sleep(t *testing.T) {
	var fired int
	timer := internal.NewTimer(20*time.Millisecond, 0, func() {
		fired++
	})

	time.Sleep(30 * time.Millisecond)
	timer.Stop()

	assert.Equal(t, 1, fired)
}

func TestTimer_Sleep_Stopped(t *testing.T) {
	var fired int
	timer := internal.NewTimer(20*time.Millisecond, 0, func() {
		fired++
	})

	timer.Stop()
	time.Sleep(30 * time.Millisecond)

	assert.Equal(t, 0, fired)
}

package internal_test

import (
	"sync/atomic"
	"testing"
	"time"

	"github.com/instana/go-sensor/autoprofile/internal"
	"github.com/stretchr/testify/assert"
)

func TestTimer_Restart(t *testing.T) {
	var fired int64
	timer := internal.NewTimer(0, 20*time.Millisecond, func() {
		atomic.AddInt64(&fired, 1)
	})

	time.Sleep(30 * time.Millisecond)
	timer.Stop()

	assert.EqualValues(t, 1, atomic.LoadInt64(&fired))

	time.Sleep(50 * time.Millisecond)
	assert.EqualValues(t, 1, atomic.LoadInt64(&fired))
}

func TestTimer_Sleep(t *testing.T) {
	var fired int64
	timer := internal.NewTimer(0, 20*time.Millisecond, func() {
		atomic.AddInt64(&fired, 1)
	})

	time.Sleep(30 * time.Millisecond)
	timer.Stop()

	assert.EqualValues(t, 1, atomic.LoadInt64(&fired))
}

func TestTimer_Sleep_Stopped(t *testing.T) {
	timer := internal.NewTimer(20*time.Millisecond, 0, func() {
		t.Error("stopped timer has fired")
	})

	timer.Stop()
	time.Sleep(30 * time.Millisecond)
}

Fix data races in internal.Timer tests


package main

import (
	"fmt"
)

func handleMessages(in <-chan Message) {
	for {
		msg := <-in
		fmt.Println("Got message\n", msg, "\n")
	}
}

func main() {
	messages := make(chan Message)
	server := NewServer(messages, SMTPConfig{
		Ip4address:      "127.0.0.1",
		Ip4port:         25,
		Domain:          "local",
		AllowedHosts:    "localhost",
		TrustedHosts:    "127.0.0.1",
		MaxRecipients:   100,
		MaxIdleSeconds:  300,
		MaxClients:      500,
		MaxMessageBytes: 20480000,
		PubKey:          "",
		PrvKey:          "",
		Debug:           false,
		DebugPath:       "",
		SpamRegex:       "",
	})
	server.Start()
	server.Drain()
}

package main

import (
	"fmt"
)

func handleMessages(in <-chan Message) {
	for {
		msg := <-in
		fmt.Println("Got message\n", msg, "\n")
	}
}

func main() {
	messages := make(chan Message)
	server := NewServer(messages, SMTPConfig{
		Ip4address:      "127.0.0.1",
		Ip4port:         25,
		Domain:          "local",
		AllowedHosts:    "localhost",
		TrustedHosts:    "127.0.0.1",
		MaxRecipients:   100,
		MaxIdleSeconds:  300,
		MaxClients:      500,
		MaxMessageBytes: 20480000,
		PubKey:          "",
		PrvKey:          "",
		Debug:           false,
		DebugPath:       "",
	})
	server.Start()
	server.Drain()
}

Remove the stupid fake spam detection crap why is this even here holy fuuuuuuuuu


package config

import (
	"io/ioutil"

	"github.com/cloudfoundry-incubator/candiedyaml"
)

type RoutingAPIConfig struct {
	URI          string `yaml:"uri"`
	Port         int    `yaml:"port"`
	AuthDisabled bool   `yaml:"auth_disabled"`
}

type OAuthConfig struct {
	TokenEndpoint     string `yaml:"token_endpoint"`
	Port              int    `yaml:"port"`
	SkipSSLValidation bool   `yaml:"skip_ssl_validation"`
	ClientName        string `yaml:"client_name"`
	ClientSecret      string `yaml:"client_secret"`
	CACerts           string `yaml:"ca_certs"`
}

type Config struct {
	OAuth      OAuthConfig      `yaml:"oauth"`
	RoutingAPI RoutingAPIConfig `yaml:"routing_api"`
}

func New(path string) (*Config, error) {
	c := &Config{}
	err := c.initConfigFromFile(path)
	if err != nil {
		return nil, err
	}
	return c, nil
}

func (c *Config) initConfigFromFile(path string) error {
	var e error

	b, e := ioutil.ReadFile(path)
	if e != nil {
		return e
	}

	return candiedyaml.Unmarshal(b, &c)
}

package config

import (
	"io/ioutil"

	"gopkg.in/yaml.v2"
)

type RoutingAPIConfig struct {
	URI          string `yaml:"uri"`
	Port         int    `yaml:"port"`
	AuthDisabled bool   `yaml:"auth_disabled"`
}

type OAuthConfig struct {
	TokenEndpoint     string `yaml:"token_endpoint"`
	Port              int    `yaml:"port"`
	SkipSSLValidation bool   `yaml:"skip_ssl_validation"`
	ClientName        string `yaml:"client_name"`
	ClientSecret      string `yaml:"client_secret"`
	CACerts           string `yaml:"ca_certs"`
}

type Config struct {
	OAuth      OAuthConfig      `yaml:"oauth"`
	RoutingAPI RoutingAPIConfig `yaml:"routing_api"`
}

func New(path string) (*Config, error) {
	c := &Config{}
	err := c.initConfigFromFile(path)
	if err != nil {
		return nil, err
	}
	return c, nil
}

func (c *Config) initConfigFromFile(path string) error {
	var e error

	b, e := ioutil.ReadFile(path)
	if e != nil {
		return e
	}

	return yaml.Unmarshal(b, &c)
}

Switch to go-yaml library from candiedyaml


package gopass

import (
	"os"
)

// getPasswd returns the input read from terminal.
// If masked is true, typing will be matched by asterisks on the screen.
// Otherwise, typing will echo nothing.
func getPasswd(masked bool) []byte {
	var pass, bs, mask []byte
	if masked {
		bs = []byte("\b \b")
		mask = []byte("*")
	}

	for {
		if v := getch(); v == 127 || v == 8 {
			if l := len(pass); l > 0 {
				pass = pass[:l-1]
				os.Stdout.Write(bs)
			}
		} else if v == 13 || v == 10 {
			break
		} else {
			pass = append(pass, v)
			os.Stdout.Write(mask)
		}
	}
	println()
	return pass
}

// GetPasswd returns the password read from the terminal without echoing input.
// The returned byte array does not include end-of-line characters.
func GetPasswd() []byte {
	return getPasswd(false)
}

// GetPasswdMasked returns the password read from the terminal, echoing asterisks.
// The returned byte array does not include end-of-line characters.
func GetPasswdMasked() []byte {
	return getPasswd(true)
}

package gopass

import (
	"os"
)

// getPasswd returns the input read from terminal.
// If masked is true, typing will be matched by asterisks on the screen.
// Otherwise, typing will echo nothing.
func getPasswd(masked bool) []byte {
	var pass, bs, mask []byte
	if masked {
		bs = []byte("\b \b")
		mask = []byte("*")
	}

	for {
		if v := getch(); v == 127 || v == 8 {
			if l := len(pass); l > 0 {
				pass = pass[:l-1]
				os.Stdout.Write(bs)
			}
		} else if v == 13 || v == 10 {
			break
		} else if v != 0 {
			pass = append(pass, v)
			os.Stdout.Write(mask)
		}
	}
	println()
	return pass
}

// GetPasswd returns the password read from the terminal without echoing input.
// The returned byte array does not include end-of-line characters.
func GetPasswd() []byte {
	return getPasswd(false)
}

// GetPasswdMasked returns the password read from the terminal, echoing asterisks.
// The returned byte array does not include end-of-line characters.
func GetPasswdMasked() []byte {
	return getPasswd(true)
}

Fix issue where some how NUL (0 byte) is returned from getch on windows.


// Package main is used for testing of generated 'views' listing.
// There is no way to include a new import dynamically, thus
// we are running this test from generate_test.go
// as a new command using exec package.
package main

import (
	"../assets/views"

	"github.com/anonx/sunplate/log"
)

func main() {
	if l := len(views.Context); l != 2 {
		log.Error.Fatalf("Length of views.Context expected to be equal to 2, it is %d instead.", l)
	}

	//
	// Make sure templates are presented in the format we expect.
	//
	for k, v := range expectedValues {
		if views.Context[k] != v {
			log.Error.Fatalf("'%s' wasn't found in %#v.", k, views.Context)
		}
	}
}

var expectedValues = map[string]string{
	"testdata/views/test1.template": "testdata/views/test1.template",
	"testdata/views/test2.template": "testdata/views/test2.template",
}

// Package main is used for testing of generated 'views' listing.
// There is no way to include a new import dynamically, thus
// we are running this test from generate_test.go
// as a new command using exec package.
package main

import (
	"../assets/views"

	"github.com/anonx/sunplate/log"
)

func main() {
	if l := len(views.Context); l != 2 {
		log.Error.Fatalf("Length of views.Context expected to be equal to 2, it is %d instead.", l)
	}

	//
	// Make sure templates are presented in the format we expect.
	//
	for k, v := range expectedValues {
		if views.Context[k] != v {
			log.Error.Fatalf("'%s' wasn't found in %#v.", k, views.Context)
		}
	}
}

var expectedValues = map[string]string{
	"test1.template": "testdata/views/test1.template",
	"test2.template": "testdata/views/test2.template",
}

Update expected results of generated liting