// +build !noglobals

package inj

//////////////////////////////////////////////
// Interface definitions
//////////////////////////////////////////////

// A Grapher is anything that can represent an application graph
type Grapher interface {
	Provide(inputs ...interface{}) error
	Inject(fn interface{}, args ...interface{})
	Assert() (valid bool, errors []string)
}

//////////////////////////////////////////////
// The one true global variable
//////////////////////////////////////////////

// A default grapher to use in the public API
var graph Grapher = NewGraph()

// Fetch the current grapher instance
func GetGrapher() Grapher {
	return graph
}

// Set a specific grapher instance
func SetGrapher(g Grapher) {
	graph = g
}

//////////////////////////////////////////////
// Public API
//////////////////////////////////////////////

// Insert a set of arbitrary objects into the
// application graph
func Provide(inputs ...interface{}) error {
	return graph.Provide(inputs...)
}

// Given a function, call it with arguments assigned
// from the graph. Additional arguments can be provided
// for the sake of utility.
func Inject(fn interface{}, args ...interface{}) {
	graph.Inject(fn, args...)
}

// Make sure that all provided dependencies have their
// requirements met, and return a list of errors if they
// don't.
func Assert() (valid bool, errors []string) {
	return graph.Assert()
}

// +build !noglobals

package inj

//////////////////////////////////////////////
// Interface definitions
//////////////////////////////////////////////

// A Grapher is anything that can represent an application graph
type Grapher interface {
	Provide(inputs ...interface{}) error
	Inject(fn interface{}, args ...interface{})
	Assert() (valid bool, errors []string)
	AddDatasource(...interface{}) error
}

//////////////////////////////////////////////
// The one true global variable
//////////////////////////////////////////////

// A default grapher to use in the public API
var graph Grapher = NewGraph()

// Fetch the current grapher instance
func GetGrapher() Grapher {
	return graph
}

// Set a specific grapher instance
func SetGrapher(g Grapher) {
	graph = g
}

//////////////////////////////////////////////
// Public API
//////////////////////////////////////////////

// Insert a set of arbitrary objects into the
// application graph
func Provide(inputs ...interface{}) error {
	return graph.Provide(inputs...)
}

// Given a function, call it with arguments assigned
// from the graph. Additional arguments can be provided
// for the sake of utility.
func Inject(fn interface{}, args ...interface{}) {
	graph.Inject(fn, args...)
}

// Make sure that all provided dependencies have their
// requirements met, and return a list of errors if they
// don't.
func Assert() (valid bool, errors []string) {
	return graph.Assert()
}

// Add zero or more datasources to the global graph
func AddDatasource(ds ...interface{}) error {
	return graph.AddDatasource(ds)
}

Update API to support datasources


package entity

import (
	"github.com/jinzhu/gorm"
)

// Tag is a descriptive identifier given to ease searchability
type Tag struct {
	gorm.Model

	Value string  `sql:"type:text" gorm:"unique;not null"`
	Flags []*Flag `gorm:"many2many:flags_tags"`
}

package entity

import (
	"github.com/jinzhu/gorm"
)

// Tag is a descriptive identifier given to ease searchability
type Tag struct {
	gorm.Model

	Value string  `sql:"type:varchar(64);unique_index:idx_tag_value"`
	Flags []*Flag `gorm:"many2many:flags_tags;"`
}

Fix integration issue with mysql


package main

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

func main() {
	r := gin.Default()
	r.GET("/ping", func(c *gin.Context) {
		c.JSON(200, gin.H{
			"message": "pong",
		})
	})
	r.Run() // listen and server on 0.0.0.0:8080
}

package main

import (
	"github.com/gin-gonic/gin"
	"strconv"
	"strings"
)

func leftPad(str string, ch string, len int) string {
	return strings.Repeat(ch, len) + str
}

func main() {
	r := gin.Default()
	r.GET("/", func(c *gin.Context) {

		str := c.DefaultQuery("str", "")
		len := c.DefaultQuery("len", "0")
		ch := c.DefaultQuery("ch", " ")

		lenInt, err := strconv.Atoi(len)

		if err != nil {
			lenInt = 0
		}

		c.JSON(200, gin.H{
			"str": leftPad(str, ch, lenInt),
		})
	})
	r.Run(":3000")
}

Add preliminary left padding functionality


package autocmd

import (
	"nvim-go/commands"
	"nvim-go/config"

	"github.com/garyburd/neovim-go/vim"
	"github.com/garyburd/neovim-go/vim/plugin"
)

func init() {
	plugin.HandleAutocmd("BufWritePre",
		&plugin.AutocmdOptions{Pattern: "*.go", Group: "nvim-go", Eval: "[getcwd(), expand('%:p')]"}, autocmdBufWritePre)
}

type bufwritepreEval struct {
	Cwd  string `msgpack:",array"`
	File string
}

func autocmdBufWritePre(v *vim.Vim, eval bufwritepreEval) error {
	if config.IferrAutosave {
		var env = commands.CmdIferrEval{
			Cwd:  eval.Cwd,
			File: eval.File,
		}
		go commands.Iferr(v, env)
	}

	if config.MetalinterAutosave {
		go commands.Metalinter(v, eval.Cwd)
	}

	if config.FmtAsync {
		go commands.Fmt(v, eval.Cwd)
	} else {
		return commands.Fmt(v, eval.Cwd)
	}
	return nil
}

package autocmd

import (
	"nvim-go/commands"
	"nvim-go/config"

	"github.com/garyburd/neovim-go/vim"
	"github.com/garyburd/neovim-go/vim/plugin"
)

func init() {
	plugin.HandleAutocmd("BufWritePre",
		&plugin.AutocmdOptions{Pattern: "*.go", Group: "nvim-go", Eval: "[getcwd(), expand('%:p:h'), expand('%:p')]"}, autocmdBufWritePre)
}

type bufwritepreEval struct {
	Cwd  string `msgpack:",array"`
	Dir  string
	File string
}

func autocmdBufWritePre(v *vim.Vim, eval bufwritepreEval) error {
	if config.IferrAutosave {
		var env = commands.CmdIferrEval{
			Cwd:  eval.Cwd,
			File: eval.File,
		}
		go commands.Iferr(v, env)
	}

	if config.MetalinterAutosave {
		go commands.Metalinter(v, eval.Cwd)
	}

	if config.FmtAsync {
		go commands.Fmt(v, eval.Dir)
	} else {
		return commands.Fmt(v, eval.Dir)
	}

	return nil
}

Fix Eval to use current buffer path for GoFmt


package foo

import (
	"io"
)

func Foo(c io.Closer) {
	c.Close()
}

func FooArgs(rc io.ReadCloser) {
	var b []byte
	rc.Read(b)
	rc.Close()
}

func FooArgsMake(rc io.ReadCloser) {
	b := make([]byte, 10)
	rc.Read(b)
	rc.Close()
}

Make sure that we also work with make


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

package process

import (
	"gopkg.in/juju/charm.v6-unstable"
)

// Status represents the status of a worload process.
type Status string

// Status values specific to workload processes.
const (
	StatusPending Status = "pending"
	StatusActive  Status = "active"
	StatusFailed  Status = "failed"
	StatusStopped Status = "stopped"
)

// ProcessInfo holds information about a process that Juju needs.
type ProcessInfo struct {
	charm.Process

	// Status is the overall Juju status of the workload process.
	Status Status

	// Space is the networking space with which the process was started.
	Space string

	// EnvVars is the set of environment variables with which the
	// process was started.
	EnvVars map[string]string

	// Details is the information about the process which the plugin provided.
	Details ProcessDetails
}

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

package process

import (
	"gopkg.in/juju/charm.v6-unstable"
)

// Status values specific to workload processes.
const (
	StatusPending Status = iota
	StatusActive
	StatusFailed
	StatusStopped
)

// Status represents the status of a worload process.
type Status string

// String implements fmt.Stringer.
func (s Status) String() string {
	switch status {
	case StatusPending:
		return "pending"
	case StatusActive:
		return "active"
	case StatusFailed:
		return "failed"
	case StatusStopped:
		return "stopped"
	}
	return "Unknown"
}

// ProcessInfo holds information about a process that Juju needs.
type ProcessInfo struct {
	charm.Process

	// Status is the overall Juju status of the workload process.
	Status Status

	// Space is the networking space with which the process was started.
	Space string

	// EnvVars is the set of environment variables with which the
	// process was started.
	EnvVars map[string]string

	// Details is the information about the process which the plugin provided.
	Details ProcessDetails
}

Change Status to an int (with a String method).


package gerrit

import (
	"fmt"
	"net/url"
)

// GetCommit retrieves a commit of a project.
// The commit must be visible to the caller.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-commit
func (s *ProjectsService) GetCommit(projectName, commitID string) (*CommitInfo, *Response, error) {
	u := fmt.Sprintf("projects/%s/commits/%s", url.QueryEscape(projectName), commitID)

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

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

	return v, resp, err
}

// GetCommitContent gets the content of a file from the HEAD revision of a certain branch.
// The content is returned as base64 encoded string.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-content
func (s *ProjectsService) GetCommitContent(projectName, branchID, fileID string) (string, *Response, error) {
	u := fmt.Sprintf("projects/%s/branches/%s/files/%s/content", url.QueryEscape(projectName), branchID, fileID)
	return getStringResponseWithoutOptions(s.client, u)
}

package gerrit

import (
	"fmt"
	"net/url"
)

// GetCommit retrieves a commit of a project.
// The commit must be visible to the caller.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html#get-commit
func (s *ProjectsService) GetCommit(projectName, commitID string) (*CommitInfo, *Response, error) {
	u := fmt.Sprintf("projects/%s/commits/%s", url.QueryEscape(projectName), commitID)

	req, err := s.client.NewRequest("GET", u, nil)
	if err != nil {
		return nil, nil, err
	}

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

	return v, resp, err
}

// GetCommitContent gets the content of a file from a certain commit.
// The content is returned as base64 encoded string.
//
// Gerrit API docs: https://gerrit-review.googlesource.com/Documentation/rest-api-projects.html##get-content-from-commit
func (s *ProjectsService) GetCommitContent(projectName, commitID, fileID string) (string, *Response, error) {
	u := fmt.Sprintf("projects/%s/commits/%s/files/%s/content", url.QueryEscape(projectName), commitID, fileID)
	return getStringResponseWithoutOptions(s.client, u)
}

Fix GetCommitContent to actually get commit content


package limio

import (
	"io"
	"time"
)

type LimitManager struct {
	rmap map[Limiter]<-chan uint64
}

func (rm *LimitManager) run() {
}

func NewReadManager() *LimitManager {
	rm := LimitManager{
		rmap: make(map[Limiter]<-chan uint64),
	}

	return &rm
}

func (rm *LimitManager) NewReader(r io.Reader) *Reader {
	lr := NewReader(r)

	ch := make(chan uint64)
	lr.LimitChan(ch)

	rm.rmap[lr] = ch

	//When lr closes, close the channel and remove it from the map
	go func() {
		lr.Close()
		close(ch)
		delete(rm.rmap, lr)
	}()

	return nil
}

func (rm *LimitManager) Limit(n uint64, t time.Duration) {
}

func (rm *LimitManager) LimitChan(<-chan uint64) {
}

func (rm *LimitManager) Manage(Limiter) {
}

package limio

import (
	"io"
	"time"
)

//An EqualLimiter is itself a limiter and will evenly distribute the limits
//it is given across all its managed Limiters.
type EqualLimiter struct {
	rmap   map[Limiter]chan uint64
	rate   <-chan uint64
	remain uint64
}

func (rm *EqualLimiter) run() {
	for {
		lim := <-rm.rate

		perChan := uint64(float64(lim) / float64(len(rm.rmap)))

		for _, c := range rm.rmap {
			go func() {
				c <- perChan
			}()
		}
	}
}

func NewEqualLimiter() *EqualLimiter {
	rm := EqualLimiter{
		rmap: make(map[Limiter]chan uint64),
	}

	return &rm
}

//NewReader is a convenience that will automatically wrap an io.Reader with the
//internal Limiter implementation.
func (rm *EqualLimiter) NewReader(r io.Reader) *Reader {
	lr := NewReader(r)
	rm.ManageLimiter(lr)

	ch := make(chan uint64)
	lr.LimitChan(ch)

	rm.rmap[lr] = ch

	//When lr closes, close the channel and remove it from the map
	go func() {
		lr.Close()
		close(ch)
		delete(rm.rmap, lr)
	}()

	return lr
}

func (rm *EqualLimiter) Limit(n uint64, t time.Duration) {
}

func (rm *EqualLimiter) LimitChan(<-chan uint64) {
}

//ManageLimiter accepts a Limiter to be managed under the new "scope"
//established by this parent Limiter.
func (rm *EqualLimiter) ManageLimiter(lr Limiter) {
	return
}

Add more implementation for EqualLimiter


// +build linux freebsd solaris

package builtin

import (
	"fmt"

	"github.com/docker/libnetwork/datastore"
	"github.com/docker/libnetwork/ipam"
	"github.com/docker/libnetwork/ipamapi"
	"github.com/docker/libnetwork/ipamutils"
)

// Init registers the built-in ipam service with libnetwork
func Init(ic ipamapi.Callback, l, g interface{}) error {
	var (
		ok                bool
		localDs, globalDs datastore.DataStore
	)

	if l != nil {
		if localDs, ok = l.(datastore.DataStore); !ok {
			return fmt.Errorf("incorrect local datastore passed to built-in ipam init")
		}
	}

	if g != nil {
		if globalDs, ok = g.(datastore.DataStore); !ok {
			return fmt.Errorf("incorrect global datastore passed to built-in ipam init")
		}
	}

	ipamutils.InitNetworks()

	a, err := ipam.NewAllocator(localDs, globalDs)
	if err != nil {
		return err
	}

	return ic.RegisterIpamDriver(ipamapi.DefaultIPAM, a)
}

// +build linux freebsd solaris darwin

package builtin

import (
	"fmt"

	"github.com/docker/libnetwork/datastore"
	"github.com/docker/libnetwork/ipam"
	"github.com/docker/libnetwork/ipamapi"
	"github.com/docker/libnetwork/ipamutils"
)

// Init registers the built-in ipam service with libnetwork
func Init(ic ipamapi.Callback, l, g interface{}) error {
	var (
		ok                bool
		localDs, globalDs datastore.DataStore
	)

	if l != nil {
		if localDs, ok = l.(datastore.DataStore); !ok {
			return fmt.Errorf("incorrect local datastore passed to built-in ipam init")
		}
	}

	if g != nil {
		if globalDs, ok = g.(datastore.DataStore); !ok {
			return fmt.Errorf("incorrect global datastore passed to built-in ipam init")
		}
	}

	ipamutils.InitNetworks()

	a, err := ipam.NewAllocator(localDs, globalDs)
	if err != nil {
		return err
	}

	return ic.RegisterIpamDriver(ipamapi.DefaultIPAM, a)
}

Fix ipams builtin package for darwin


package discord

import (
	"strings"

	"github.com/bwmarrin/discordgo"
)

type dsMessage struct {
	*discordgo.Message
	session *discordgo.Session
}

func (d dsMessage) GroupID() string {
	return d.ChannelID
}

func (d dsMessage) UserName() string {
	return d.Author.Username
}

func (d dsMessage) UserID() string {
	return d.Author.ID
}

func (d dsMessage) MessageID() string {
	return d.ID
}

func (d dsMessage) Text() string {
	modifiedText := d.Content
	for _, mention := range d.Mentions {
		replaceStr := "<@" + mention.ID + ">"
		modifiedText = strings.Replace(modifiedText, replaceStr, "@"+mention.Username, -1)
	}
	return modifiedText
}

func (d dsMessage) UserType() string {
	if d.Type == discordgo.MessageTypeDefault {
		return "user"
	} else {
		return "other"
	}
}

package discord

import (
	"strings"

	"github.com/bwmarrin/discordgo"
)

type dsMessage struct {
	*discordgo.Message
	session *discordgo.Session
}

func (d dsMessage) GroupID() string {
	return "discord"
}

func (d dsMessage) UserName() string {
	return d.Author.Username
}

func (d dsMessage) UserID() string {
	return d.Author.ID
}

func (d dsMessage) MessageID() string {
	return d.ID
}

func (d dsMessage) Text() string {
	modifiedText := d.Content
	for _, mention := range d.Mentions {
		replaceStr := "<@" + mention.ID + ">"
		modifiedText = strings.Replace(modifiedText, replaceStr, "@"+mention.Username, -1)
	}
	return modifiedText
}

func (d dsMessage) UserType() string {
	if d.Type == discordgo.MessageTypeDefault {
		return "user"
	} else {
		return "other"
	}
}

Change to generic discord user to support N chats


package srtp

import "github.com/pion/rtp"

// cipher represents a implementation of one
// of the SRTP Specific ciphers
type srtpCipher interface {
	authTagLen() int
	aeadAuthTagLen() int
	getRTCPIndex([]byte) uint32

	encryptRTP([]byte, *rtp.Header, []byte, uint32) ([]byte, error)
	encryptRTCP([]byte, []byte, uint32, uint32) ([]byte, error)

	decryptRTP([]byte, []byte, *rtp.Header, uint32) ([]byte, error)
	decryptRTCP([]byte, []byte, uint32, uint32) ([]byte, error)
}

package srtp

import "github.com/pion/rtp"

// cipher represents a implementation of one
// of the SRTP Specific ciphers
type srtpCipher interface {
	// authTagLen returns auth key length of the cipher.
	// See the note below.
	authTagLen() int
	// aeadAuthTagLen returns AEAD auth key length of the cipher.
	// See the note below.
	aeadAuthTagLen() int
	getRTCPIndex([]byte) uint32

	encryptRTP([]byte, *rtp.Header, []byte, uint32) ([]byte, error)
	encryptRTCP([]byte, []byte, uint32, uint32) ([]byte, error)

	decryptRTP([]byte, []byte, *rtp.Header, uint32) ([]byte, error)
	decryptRTCP([]byte, []byte, uint32, uint32) ([]byte, error)
}

/*
NOTE: Auth tag and AEAD auth tag are placed at the different position in SRTCP

In non-AEAD cipher, the authentication tag is placed *after* the ESRTCP word
(Encrypted-flag and SRTCP index).

> AES_128_CM_HMAC_SHA1_80
> | RTCP Header | Encrypted payload |E| SRTCP Index | Auth tag |
>                                   ^               |----------|
>                                   |                ^
>                                   |                authTagLen=10
>                                   aeadAuthTagLen=0

In AEAD cipher, the AEAD authentication tag is embedded in the ciphertext.
It is *before* the ESRTCP word (Encrypted-flag and SRTCP index).

> AEAD_AES_128_GCM
> | RTCP Header | Encrypted payload | AEAD auth tag |E| SRTCP Index |
>                                   |---------------|               ^
>                                    ^                              authTagLen=0
>                                    aeadAuthTagLen=16

See https://tools.ietf.org/html/rfc7714 for the full specifications.
*/

Add note about AEAD auth tag in SRTCP


package taptun

import (
	"bytes"
	"os"
	"syscall"
	"unsafe"
)

type ifreq struct {
	name  [syscall.IFNAMSIZ]byte // c string
	flags uint16                 // c short
	_pad  [24 - unsafe.Sizeof(uint16(0))]byte
}

func createInterface(flags uint16) (string, *os.File, error) {
	f, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0600)
	if err != nil {
		return "", nil, err
	}

	fd := f.Fd()

	ifr := ifreq{flags: flags}
	if err := ioctl(fd, syscall.TUNSETIFF, unsafe.Pointer(&ifr)); err != nil {
		return "", nil, err
	}
	return cstringToGoString(ifr.name[:]), f, nil
}

func destroyInterface(name string) error {
	return nil
}

func openTun() (string, *os.File, error) {
	return createInterface(syscall.IFF_TUN | syscall.IFF_NO_PI)
}

func openTap() (string, *os.File, error) {
	return createInterface(syscall.IFF_TAP | syscall.IFF_NO_PI)
}

package taptun

import (
	"os"
	"syscall"
	"unsafe"
)

type ifreq struct {
	name  [syscall.IFNAMSIZ]byte // c string
	flags uint16                 // c short
	_pad  [24 - unsafe.Sizeof(uint16(0))]byte
}

func createInterface(flags uint16) (string, *os.File, error) {
	f, err := os.OpenFile("/dev/net/tun", os.O_RDWR, 0600)
	if err != nil {
		return "", nil, err
	}

	fd := f.Fd()

	ifr := ifreq{flags: flags}
	if err := ioctl(fd, syscall.TUNSETIFF, unsafe.Pointer(&ifr)); err != nil {
		return "", nil, err
	}
	return cstringToGoString(ifr.name[:]), f, nil
}

func destroyInterface(name string) error {
	return nil
}

func openTun() (string, *os.File, error) {
	return createInterface(syscall.IFF_TUN | syscall.IFF_NO_PI)
}

func openTap() (string, *os.File, error) {
	return createInterface(syscall.IFF_TAP | syscall.IFF_NO_PI)
}

Fix Linux build by removing unused import


// +build linux darwin

package logging

import (
	slog "log/syslog"

	log "gopkg.in/inconshreveable/log15.v2"
)

// getSystemHandler on Linux writes messages to syslog.
func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler {
	// SyslogHandler
	if syslog != "" {
		if !debug {
			return log.LvlFilterHandler(
				log.LvlInfo,
				log.Must.SyslogHandler(slog.LOG_INFO, syslog, format),
			)
		}

		return log.Must.SyslogHandler(slog.LOG_INFO, syslog, format)
	}

	return nil
}

// +build linux darwin

package logging

import (
	log "gopkg.in/inconshreveable/log15.v2"
)

// getSystemHandler on Linux writes messages to syslog.
func getSystemHandler(syslog string, debug bool, format log.Format) log.Handler {
	// SyslogHandler
	if syslog != "" {
		if !debug {
			return log.LvlFilterHandler(
				log.LvlInfo,
				log.Must.SyslogHandler(syslog, format),
			)
		}

		return log.Must.SyslogHandler(syslog, format)
	}

	return nil
}

Revert "Temporary workaround for log15 API breakage"


// +build !windows

package player

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

	"github.com/aws/aws-sdk-go/service/polly"
)

func Play(resp *polly.SynthesizeSpeechOutput, logger *log.Logger) error {
	cmd := exec.Command("play", "-t", "mp3", "-")
	wr, err := cmd.StdinPipe()
	if err != nil {
		return err
	}

	err = cmd.Start()
	if err != nil {
		logger.Println(err)
	}
	go func() {
		io.Copy(wr, resp.AudioStream)
		wr.Close()
	}()
	cmd.Wait()
	return nil
}

Fix depending OS build error


package helper

var guessExecutableName = "openvpn"
var guessExecutablePaths = []string{
	"/Applications/Tunnelblick.app/Contents/Resources/openvpn/default",
}
var guessExecutableSuggestions = `
If you use Homebrew, you can install the openvpn formula...

    brew install openvpn

Alternatively, the following applications will also install openvpn...

 * Tunnelblick (https://tunnelblick.net/)
 * Shimo (https://www.shimovpn.com/)
 * Viscosity (https://www.sparklabs.com/viscosity/)
`

package helper

var guessExecutableName = "openvpn"
var guessExecutablePaths = []string{
	"/Applications/Tunnelblick.app/Contents/Resources/openvpn/default",
	"/Applications/Shimo.app/Contents/MacOS/openvpn",
	"/Applications/Viscosity.app/Contents/MacOS/openvpn",
}
var guessExecutableSuggestions = `
If you use Homebrew, you can install the openvpn formula...

    brew install openvpn

Alternatively, the following applications will also install openvpn...

 * Tunnelblick (https://tunnelblick.net/)
 * Shimo (https://www.shimovpn.com/)
 * Viscosity (https://www.sparklabs.com/viscosity/)
`

Add Viscosity/Shimo embedded openvpn paths


// Module objects

package py

import (
	"fmt"
)

var (
	// Registry of installed modules
	modules = make(map[string]*Module)
	// Builtin module
	Builtins *Module
)

// A python Module object
type Module struct {
	Name    string
	Doc     string
	Globals StringDict
	//	dict Dict
}

var ModuleType = NewType("module", "module object")

// Type of this object
func (o *Module) Type() *Type {
	return ModuleType
}

// Define a new module
func NewModule(name, doc string, methods []*Method, globals StringDict) *Module {
	m := &Module{
		Name:    name,
		Doc:     doc,
		Globals: globals.Copy(),
	}
	// Insert the methods into the module dictionary
	for _, method := range methods {
		m.Globals[method.Name] = method
	}
	// Register the module
	modules[name] = m
	// Make a note of the builtin module
	if name == "builtins" {
		Builtins = m
	}
	fmt.Printf("Registering module %q\n", name)
	return m
}

// Module objects

package py

import (
	"fmt"
)

var (
	// Registry of installed modules
	modules = make(map[string]*Module)
	// Builtin module
	Builtins *Module
)

// A python Module object
type Module struct {
	Name    string
	Doc     string
	Globals StringDict
	//	dict Dict
}

var ModuleType = NewType("module", "module object")

// Type of this object
func (o *Module) Type() *Type {
	return ModuleType
}

// Define a new module
func NewModule(name, doc string, methods []*Method, globals StringDict) *Module {
	m := &Module{
		Name:    name,
		Doc:     doc,
		Globals: globals.Copy(),
	}
	// Insert the methods into the module dictionary
	for _, method := range methods {
		m.Globals[method.Name] = method
	}
	// Set some module globals
	m.Globals["__name__"] = String(name)
	m.Globals["__doc__"] = String(doc)
	m.Globals["__package__"] = None
	// Register the module
	modules[name] = m
	// Make a note of the builtin module
	if name == "builtins" {
		Builtins = m
	}
	fmt.Printf("Registering module %q\n", name)
	return m
}

Set __name__, __doc__ and __package__ in Module


/*
Copyright 2021 The Kubernetes Authors.

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

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

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

package api

import (
	"io"
)

// TODO(api): Populate interface
// TODO(api): Mock interface
type File interface {
	Parse(io.Reader) (Document, error)
}

// TODO(api): Populate interface
// TODO(api): Mock interface
// Document is an interface satisfied by the following types:
// - `Proposal` (KEP)
// - `PRRApproval`
// - `Receipt` (coming soon)
type Document interface {
	Validate() error
}

type Parser struct {
	Groups       []string
	PRRApprovers []string

	Errors []error
}

/*
Copyright 2021 The Kubernetes Authors.

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

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

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

package api

import (
	"io"
)

//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate

//counterfeiter:generate . File

// TODO(api): Populate interface and regenerate mocks
type File interface {
	Parse(io.Reader) (Document, error)
}

//counterfeiter:generate . Document

// Document is an interface satisfied by the following types:
// - `Proposal` (KEP)
// - `PRRApproval`
// - `Receipt` (coming soon)
// TODO(api): Populate interface and regenerate mocks
type Document interface {
	Validate() error
}

type Parser struct {
	Groups       []string
	PRRApprovers []string

	Errors []error
}

Add interface directives for counterfeiter


package sss

import (
	"testing"
)

func TestRoundtrip(t *testing.T) {
	n := 30
	k := 2

	expected := "well hello there!"
	shares, err := Split(n, k, []byte(expected))
	if err != nil {
		t.Error(err)
	}

	subset := make(map[int][]byte, k)
	for x, y := range shares {
		subset[x] = y
		if len(subset) == k {
			break
		}
	}

	actual := string(Combine(subset))
	if actual != expected {
		t.Errorf("Expected %v but was %v", expected, actual)
	}
}

package sss

import (
	"fmt"
)

func Example() {
	// split into 30 shares, of which only 2 are required to combine
	n := 30
	k := 2

	secret := "well hello there!"
	shares, err := Split(n, k, []byte(secret))
	if err != nil {
		fmt.Println(err)
	}

	// select a random subset of the total shares
	subset := make(map[int][]byte, k)
	for x, y := range shares {
		subset[x] = y
		if len(subset) == k {
			break
		}
	}

	fmt.Println(string(Combine(subset)))
	// Output: well hello there!
}

Change round-trip test to an example.


/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package main

import (
	"fmt"
	"github.com/codedust/go-httpserve"
	"net/http"
)

func main() {
	http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "<!DOCTYPE html>
It works!
")
	})

	// add authentication
	salt, err := httpserve.RandomString(32)
	if err != nil {
		panic("could not generate salt")
	}

	handleAuth := httpserve.BasicAuthHandler(http.DefaultServeMux, "user", httpserve.Sha512Sum("pass"+salt), salt)

  httpserve.CreateCertificateIfNotExist("./cert.pem", "./key.pem", "localhost", 3072)
  httpserve.ListenAndUpgradeTLS(":8080", "./cert.pem", "./key.pem", handleAuth)
}

Add MPL header to examples/forceHTTPs.go


package main

import (
	"os"
	"time"

	"github.com/hybridgroup/gobot"
	"github.com/hybridgroup/gobot/platforms/ble"
)

func main() {
	gbot := gobot.NewGobot()

	bleAdaptor := ble.NewBLEClientAdaptor("ble", os.Args[1])
	ollie := ble.NewSpheroOllieDriver(bleAdaptor, "ollie")

	work := func() {
		ollie.SetRGB(255, 0, 255)
		gobot.Every(3*time.Second, func() {
			ollie.Roll(30, uint16(gobot.Rand(360)))
		})
	}

	robot := gobot.NewRobot("ollieBot",
		[]gobot.Connection{bleAdaptor},
		[]gobot.Device{ollie},
		work,
	)

	gbot.AddRobot(robot)

	gbot.Start()
}

package main

import (
	"os"
	"time"

	"github.com/hybridgroup/gobot"
	"github.com/hybridgroup/gobot/platforms/ble"
)

func main() {
	gbot := gobot.NewGobot()

	bleAdaptor := ble.NewBLEClientAdaptor("ble", os.Args[1])
	ollie := ble.NewSpheroOllieDriver(bleAdaptor, "ollie")

	work := func() {
		ollie.SetRGB(255, 0, 255)
		gobot.Every(3*time.Second, func() {
			ollie.Roll(40, uint16(gobot.Rand(360)))
		})
	}

	robot := gobot.NewRobot("ollieBot",
		[]gobot.Connection{bleAdaptor},
		[]gobot.Device{ollie},
		work,
	)

	gbot.AddRobot(robot)

	gbot.Start()
}

Speed up Ollie example roll speed


package model

import (
	"encoding/json"
	"fmt"
)

type Reference struct {
	ObjectId *ObjectID `json:",omitempty"`
	Id       string    `json:",omitempty"`
	Type     string    `json:",omitempty"`
}

func NewReference(objectId ObjectID) *Reference {
	return &Reference{ObjectId: &objectId}
}

func (reference *Reference) GetSha1() string {
	return reference.ObjectId.HashValue()
}

func (reference *Reference) Getformat(ref, value string) string {
	allRef := make(map[string]string)
	loc := ""

	if ref != "OperatorRef" {
		loc = "LOC"
	}
	allRef["PlaceRef"] = "StopPoint:Q:"
	allRef["OriginRef"] = "StopPoint:Q:"
	allRef["DestinationRef"] = "StopPoint:Q:"
	allRef["JourneyPatternRef"] = "JourneyPattern::"
	allRef["RouteRef"] = "Route::"
	allRef["DatedVehicleJourneyRef"] = "VehiculeJourney::"
	allRef["OperatorRef"] = "Operator::"

	formated := fmt.Sprintf("RATPDev:%s%s:%s", allRef[ref], value, loc)

	return formated
}

func (reference *Reference) UnmarshalJSON(data []byte) error {
	type Alias Reference
	aux := &struct {
		*Alias
	}{
		Alias: (*Alias)(reference),
	}

	err := json.Unmarshal(data, aux)
	if err != nil {
		return err
	}

	return nil
}

package model

import "encoding/json"

type Reference struct {
	ObjectId *ObjectID `json:",omitempty"`
	Id       string    `json:",omitempty"`
	Type     string    `json:",omitempty"`
}

func NewReference(objectId ObjectID) *Reference {
	return &Reference{ObjectId: &objectId}
}

func (reference *Reference) GetSha1() string {
	return reference.ObjectId.HashValue()
}

func (reference *Reference) UnmarshalJSON(data []byte) error {
	type Alias Reference
	aux := &struct {
		*Alias
	}{
		Alias: (*Alias)(reference),
	}

	err := json.Unmarshal(data, aux)
	if err != nil {
		return err
	}

	return nil
}

Remove unused method in Reference


package command

import (
	"fmt"
	"time"

	"github.com/igungor/tlbot"
)

func init() {
	register(cmdToday)
}

var cmdToday = &Command{
	Name:      "bugun",
	ShortLine: "bugün günlerden ne?",
	Run:       runToday,
}

type weekday time.Weekday

var days = [...]string{
	"pazar",
	"pazartesi",
	"sali",
	"carsamba",
	"persembe",
	"cuma",
	"cumartesi",
}

func (w weekday) String() string {
	return days[w]
}

func runToday(b *tlbot.Bot, msg *tlbot.Message) {
	txt := fmt.Sprintf("bugün %v", weekday(time.Now().Weekday()).String())
	b.SendMessage(msg.Chat, txt, tlbot.ModeNone, false, nil)
}

package command

import (
	"fmt"
	"time"

	"github.com/igungor/tlbot"
)

func init() {
	register(cmdToday)
}

var cmdToday = &Command{
	Name:      "bugun",
	ShortLine: "bugün günlerden ne?",
	Run:       runToday,
}

type weekday time.Weekday

var days = [...]string{
	"pazar",
	"pazartesi",
	"salı",
	"çarşamba",
	"perşembe",
	"cuma",
	"cumartesi",
}

func (w weekday) String() string {
	return days[w]
}

func runToday(b *tlbot.Bot, msg *tlbot.Message) {
	txt := fmt.Sprintf("bugün %v", weekday(time.Now().Weekday()).String())
	b.SendMessage(msg.Chat, txt, tlbot.ModeNone, false, nil)
}

Use proper turkish words for days


package transaction

import (
	"runtime"
	"testing"
)

// Tests we can start/stop a transaction manager repeatedly on the same port.
func TestStop(t *testing.T) {
	loops := 5
	goroutines := runtime.NumGoroutine()
	for i := 0; i < loops; i++ {
		m, err := NewManager("tcp", "localhost:12345")
		if err != nil {
			t.Fatalf("Failed to start manager on loop %v: %v\n", i, err)
		}

		m.Stop()

		// Check no goroutines still running.
		n := runtime.NumGoroutine()
		if n != goroutines {
			t.Errorf("%v goroutines still running after manager closed on loop %v.", n, i)
		}
	}
	trace := make([]byte, 8192)
	count := runtime.Stack(trace, true)
	t.Log(string(trace[:count]))
}

package transaction

import (
	"testing"
	"time"
)

// Tests we can start/stop a transaction manager repeatedly on the same port.
func TestStop(t *testing.T) {
	loops := 5
	for i := 0; i < loops; i++ {
		m, err := NewManager("tcp", "localhost:12345")
		if err != nil {
			t.Fatalf("Failed to start manager on loop %v: %v\n", i, err)
		}

		<-time.After(10 * time.Millisecond)
		m.Stop()
	}
}

Remove goroutine check from manager test, it's not consistent


package engine

import (
	"github.com/coreos/coreinit/machine"
	"github.com/coreos/coreinit/registry"
)

type Engine struct {
	dispatcher *Dispatcher
	watcher    *JobWatcher
	registry   *registry.Registry
	machine    *machine.Machine
}

func New(reg *registry.Registry, events *registry.EventStream, mach *machine.Machine) *Engine {
	scheduler := NewScheduler()
	watcher := NewJobWatcher(reg, scheduler, mach)
	dispatcher := NewDispatcher(reg, events, watcher, mach)
	return &Engine{dispatcher, watcher, reg, mach}
}

func (engine *Engine) Run() {
	engine.dispatcher.Listen()

	engine.watcher.StartHeartbeatThread()
	engine.watcher.StartRefreshThread()
}

package engine

import (
	"github.com/coreos/coreinit/machine"
	"github.com/coreos/coreinit/registry"
)

type Engine struct {
	dispatcher *Dispatcher
	watcher    *JobWatcher
	registry   *registry.Registry
	machine    *machine.Machine
}

func New(reg *registry.Registry, events *registry.EventStream, mach *machine.Machine) *Engine {
	scheduler := NewScheduler()
	watcher := NewJobWatcher(reg, scheduler, mach)
	dispatcher := NewDispatcher(reg, events, watcher, mach)
	return &Engine{dispatcher, watcher, reg, mach}
}

func (engine *Engine) Run() {
	engine.watcher.StartHeartbeatThread()
	engine.watcher.StartRefreshThread()

	engine.dispatcher.Listen()
}

Call Dispatcher.Listen last in Engine.Run


/* netcheck: check whether a given network or address overlaps with any existing routes */
package main

import (
	"fmt"
	"net"
	"os"

	weavenet "github.com/weaveworks/weave/net"
)

func fatal(err error) {
	fmt.Println(err)
	os.Exit(1)
}

func main() {
	if len(os.Args) <= 1 {
		os.Exit(0)
	}

	cidrStr := os.Args[1]
	addr, ipnet, err := net.ParseCIDR(cidrStr)
	if err != nil {
		fatal(err)
	}
	if ipnet.IP.Equal(addr) {
		err = weavenet.CheckNetworkFree(ipnet)
	} else {
		err = weavenet.CheckAddressOverlap(addr)
	}
	if err != nil {
		fatal(err)
	}
	os.Exit(0)
}

/* netcheck: check whether a given network or address overlaps with any existing routes */
package main

import (
	"fmt"
	"net"
	"os"

	weavenet "github.com/weaveworks/weave/net"
)

func fatal(err error) {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(1)
}

func main() {
	if len(os.Args) <= 1 {
		os.Exit(0)
	}

	cidrStr := os.Args[1]
	addr, ipnet, err := net.ParseCIDR(cidrStr)
	if err != nil {
		fatal(err)
	}
	if ipnet.IP.Equal(addr) {
		err = weavenet.CheckNetworkFree(ipnet)
	} else {
		err = weavenet.CheckAddressOverlap(addr)
	}
	if err != nil {
		fatal(err)
	}
	os.Exit(0)
}

Send error message to stderr


package middlewares

import (
	"net/http"
	"time"

	"github.com/freeusd/solebtc/Godeps/_workspace/src/github.com/gin-gonic/gin"
	"github.com/freeusd/solebtc/errors"
	"github.com/freeusd/solebtc/models"
)

type authRequiredDependencyGetAuthToken func(authTokenString string) (models.AuthToken, *errors.Error)

// AuthRequired checks if user is authorized
func AuthRequired(
	getAuthToken authRequiredDependencyGetAuthToken,
	authTokenLifetime time.Duration,
) gin.HandlerFunc {
	return func(c *gin.Context) {
		authToken, err := getAuthToken(c.Request.Header.Get("Auth-Token"))

		if err != nil && err.ErrCode != errors.ErrCodeNotFound {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		if authToken.CreatedAt.Add(authTokenLifetime).Before(time.Now()) {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		c.Set("auth_token", authToken)
		c.Next()
	}
}

package middlewares

import (
	"net/http"
	"time"

	"github.com/freeusd/solebtc/Godeps/_workspace/src/github.com/gin-gonic/gin"
	"github.com/freeusd/solebtc/errors"
	"github.com/freeusd/solebtc/models"
)

type authRequiredDependencyGetAuthToken func(authTokenString string) (models.AuthToken, *errors.Error)

// AuthRequired checks if user is authorized
func AuthRequired(
	getAuthToken authRequiredDependencyGetAuthToken,
	authTokenLifetime time.Duration,
) gin.HandlerFunc {
	return func(c *gin.Context) {
		authTokenHeader := c.Request.Header.Get("Auth-Token")
		if authTokenHeader == "" {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		authToken, err := getAuthToken(authTokenHeader)
		if err != nil && err.ErrCode != errors.ErrCodeNotFound {
			c.AbortWithError(http.StatusInternalServerError, err)
			return
		}

		if authToken.CreatedAt.Add(authTokenLifetime).Before(time.Now()) {
			c.AbortWithStatus(http.StatusUnauthorized)
			return
		}

		c.Set("auth_token", authToken)
		c.Next()
	}
}

Check AuthToken header if empty before query database


/*
Copyright 2014 Google Inc. All rights reserved.

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

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

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

package healthz

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestInstallHandler(t *testing.T) {
	mux := http.NewServeMux()
	InstallHandler(mux)
	req, err := http.NewRequest("GET", "http://example.com/healthz", nil)
	if err != nil {
		t.Errorf("Unexpected error: %v", err)
	}
	w := httptest.NewRecorder()
	mux.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Errorf("Expected %v, got %v", http.StatusOK, w.Code)
	}
	if w.Body.String() != "ok" {
		t.Errorf("Expected %v, got %v", "ok", w.Body.String())
	}
}

/*
Copyright 2014 Google Inc. All rights reserved.

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

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

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

package healthz

import (
	"net/http"
	"net/http/httptest"
	"testing"
)

func TestInstallHandler(t *testing.T) {
	mux := http.NewServeMux()
	InstallHandler(mux)
	req, err := http.NewRequest("GET", "http://example.com/healthz", nil)
	if err != nil {
		t.Fatalf("Unexpected error: %v", err)
	}
	w := httptest.NewRecorder()
	mux.ServeHTTP(w, req)
	if w.Code != http.StatusOK {
		t.Errorf("Expected %v, got %v", http.StatusOK, w.Code)
	}
	if w.Body.String() != "ok" {
		t.Errorf("Expected %v, got %v", "ok", w.Body.String())
	}
}

Fix healthz test error handling


package main

import (
	"log"
	"time"

	"github.com/ecc1/medtronic"
	"github.com/ecc1/medtronic/packet"
)

const (
	verbose = true
)

func main() {
	if verbose {
		log.SetFlags(log.Ltime | log.Lmicroseconds | log.LUTC)
	}
	pump := medtronic.Open()
	defer pump.Close()
	for pump.Error() == nil {
		p, rssi := pump.Radio.Receive(time.Hour)
		if pump.Error() != nil {
			log.Print(pump.Error())
			pump.SetError(nil)
			continue
		}
		if verbose {
			log.Printf("raw data: % X (RSSI = %d)", p, rssi)
		}
		data, err := packet.Decode(p)
		if err != nil {
			log.Print(err)
			continue
		}
		if verbose {
			log.Printf("decoded:  % X", data)
		} else {
			log.Printf("% X (RSSI = %d)", data, rssi)
		}

	}
	log.Fatal(pump.Error())
}

package main

import (
	"log"
	"time"

	"github.com/ecc1/medtronic"
	"github.com/ecc1/medtronic/packet"
)

const (
	verbose = true
)

func main() {
	if verbose {
		log.SetFlags(log.Ltime | log.Lmicroseconds | log.LUTC)
	}
	pump := medtronic.Open()
	defer pump.Close()
	for pump.Error() == nil {
		p, rssi := pump.Radio.Receive(time.Hour)
		if pump.Error() != nil {
			log.Print(pump.Error())
			pump.SetError(nil)
			continue
		}
		if verbose {
			log.Printf("raw data: % X (%d bytes, RSSI = %d)", p, len(p), rssi)
		}
		data, err := packet.Decode(p)
		if err != nil {
			log.Print(err)
			continue
		}
		if verbose {
			log.Printf("decoded:  % X", data)
		} else {
			log.Printf("% X (%d bytes, RSSI = %d)", data, len(data), rssi)
		}

	}
	log.Fatal(pump.Error())
}

Print packet lengths in sniff


// Package pairwise implements utilities to evaluate pairwise distances or inner product (via kernel).
package pairwise

import (
	"github.com/gonum/matrix/mat64"
)

type PairwiseDistanceFunc interface {
	Distance(vectorX *mat64.Dense, vectorY *mat64.Dense) float64
}

Add distanceFunc interface to metrics.


/*
Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".
*/

package main

import (
	"fmt"
)

func main() {
	tests := [][]string{{"", ""}, {" ", " "}, {"   ", "   "}, {"a", "a"}, {"ab", "ba"}, {"hello", "olleh"}, {"Hello, 世界!", "!界世 ,olleH"}}

	for _, test := range tests {
		if reverseString(test[0]) == test[1] {
			fmt.Println("PASS")
		} else {
			fmt.Println("FAIL")
			fmt.Println("\t", test)
		}
	}
}

func reverseString(s string) string {
	// transform input string into rune (unicode char) slice for convenient manipulation
	s_runes := []rune(s)

	// reverse characters
	for i := 0; i < len(s_runes)/2; i++ {
		temp := s_runes[i]
		s_runes[i] = s_runes[len(s_runes)-i-1]
		s_runes[len(s_runes)-i-1] = temp
	}

	return string(s_runes)
}

/*
Write a function that takes a string as input and returns the string reversed.

Example:
Given s = "hello", return "olleh".
*/

package main

import (
	"fmt"
)

func main() {
	tests := [][]string{{"", ""}, {" ", " "}, {"   ", "   "}, {"a", "a"}, {"ab", "ba"}, {"hello", "olleh"}, {"Hello, 世界!", "!界世 ,olleH"}}

	for _, test := range tests {
		if reverseString(test[0]) == test[1] {
			fmt.Println("PASS")
		} else {
			fmt.Println("FAIL")
			fmt.Println("\t", test)
		}
	}
}

func reverseString(s string) string {
	// transform input string into rune (unicode char) slice for convenient manipulation
	s_runes := []rune(s)

	// reverse characters
	for i := 0; i < len(s_runes)/2; i++ {
		s_runes[i], s_runes[len(s_runes)-i-1] = s_runes[len(s_runes)-i-1], s_runes[i]
	}

	return string(s_runes)
}

Update char swap operation without temp character


//go:build !windows && !plan9 && !js

package shell

import (
	"strings"
	"syscall"
	"testing"

	"src.elv.sh/pkg/must"
	. "src.elv.sh/pkg/prog/progtest"
	"src.elv.sh/pkg/testutil"
)

func TestSignal_USR1(t *testing.T) {
	Test(t, &Program{},
		ThatElvish("-c", "kill -USR1 $pid").WritesStderrContaining("src.elv.sh/pkg/shell"))
}

func TestSignal_Ignored(t *testing.T) {
	testutil.InTempDir(t)

	Test(t, &Program{},
		ThatElvish("-log", "logCHLD", "-c", "kill -CHLD $pid").DoesNothing())

	wantLogCHLD := "signal " + syscall.SIGCHLD.String()
	if logCHLD := must.ReadFileString("logCHLD"); !strings.Contains(logCHLD, wantLogCHLD) {
		t.Errorf("want log when getting SIGCHLD to contain %q; got:\n%s", wantLogCHLD, logCHLD)
	}
}

//go:build !windows && !plan9 && !js

package shell

import (
	"fmt"
	"strings"
	"syscall"
	"testing"
	"time"

	"src.elv.sh/pkg/must"
	. "src.elv.sh/pkg/prog/progtest"
	"src.elv.sh/pkg/testutil"
)

func TestSignal_USR1(t *testing.T) {
	Test(t, &Program{},
		ThatElvish("-c", killCmd("USR1")).WritesStderrContaining("src.elv.sh/pkg/shell"))
}

func TestSignal_Ignored(t *testing.T) {
	testutil.InTempDir(t)

	Test(t, &Program{},
		ThatElvish("-log", "logCHLD", "-c", killCmd("CHLD")).DoesNothing())

	wantLogCHLD := "signal " + syscall.SIGCHLD.String()
	if logCHLD := must.ReadFileString("logCHLD"); !strings.Contains(logCHLD, wantLogCHLD) {
		t.Errorf("want log when getting SIGCHLD to contain %q; got:\n%s", wantLogCHLD, logCHLD)
	}
}

func killCmd(name string) string {
	// Add a delay after kill to ensure that the signal is handled.
	return fmt.Sprintf("kill -%v $pid; sleep %v", name, testutil.Scaled(10*time.Millisecond))
}

Add a short delay in signal handling test.


package main

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

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

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

package main

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

func main() {
	config := server.NewConfig()
	config.ListenHost = *flag.String("host", ":9000", "host to listen")
	config.FileServerHost = *flag.String("file_host", ":9000", "host to server files")
	config.FileServerPath = *flag.String("file_path", "/files", "query file path to access files")
	config.FileServerFolder = *flag.String("file_folder", "./", "storage folder")
	flag.Parse()

	args := flag.Args()
	if len(args) > 0 && args[0] == "--help" {
		flag.PrintDefaults()
		return
	}

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

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

Add flag params for server


package util

import (
	"net/http"

	"github.com/rs/cors"
)

// NewCorsHandler creates a new http.Handler to support CORS
func NewCorsHandler(handler http.Handler, allowOrigins []string) http.Handler {
	mw := cors.New(cors.Options{
		AllowedOrigins:   allowOrigins,
		AllowCredentials: true,
		AllowedMethods:   []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
		AllowedHeaders:   []string{"Access-Control-Allow-Origin", "Content-Type", "Accept"},
		Debug:            false,
	})

	return mw.Handler(handler)
}

package util

import (
	"net/http"

	"github.com/rs/cors"
)

// NewCorsHandler creates a new http.Handler to support CORS
func NewCorsHandler(handler http.Handler, allowOrigins []string) http.Handler {
	mw := cors.New(cors.Options{
		AllowedOrigins:   allowOrigins,
		AllowCredentials: true,
		AllowedMethods:   []string{"GET", "POST", "PUT", "PATCH", "DELETE"},
		AllowedHeaders:   []string{"Access-Control-Allow-Origin", "Content-Type", "Accept", "Authorization"},
		Debug:            false,
	})

	return mw.Handler(handler)
}

Add authorization header to accepted headers


// Copyright 2017 Mathew Robinson <mrobinson@praelatus.io>. All rights reserved.
// Use of this source code is governed by the AGPLv3 license that can be found in
// the LICENSE file.

// Package middleware contains the HTTP middleware used in the api as
// well as utility functions for interacting with them
package middleware

import (
	"net/http"

	"github.com/praelatus/praelatus/repo"
)

// Cache is the global SessionCache
var Cache repo.Cache

func headers(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		h.ServeHTTP(w, r)
	})
}

// LoadMw will wrap the given http.Handler in the DefaultMiddleware
func LoadMw(handler http.Handler) http.Handler {
	h := handler

	for _, m := range DefaultMiddleware {
		h = m(h)
	}

	return h
}

// DefaultMiddleware is the default middleware stack for Praelatus
var DefaultMiddleware = []func(http.Handler) http.Handler{
	headers,
	Logger,
}

// Copyright 2017 Mathew Robinson <mrobinson@praelatus.io>. All rights reserved.
// Use of this source code is governed by the AGPLv3 license that can be found in
// the LICENSE file.

// Package middleware contains the HTTP middleware used in the api as
// well as utility functions for interacting with them
package middleware

import (
	"net/http"

	"github.com/praelatus/praelatus/repo"
)

// Cache is the global SessionCache
var Cache repo.Cache

// ContentHeaders will set the content-type header for the API to application/json
func ContentHeaders(next http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		if r.URL.Path[len("/api"):] == "/api" {
			w.Header().Set("Content-Type", "application/json")
		}

		next.ServeHTTP(w, r)
	})
}

// LoadMw will wrap the given http.Handler in the DefaultMiddleware
func LoadMw(handler http.Handler) http.Handler {
	h := handler

	for _, m := range DefaultMiddleware {
		h = m(h)
	}

	return h
}

// DefaultMiddleware is the default middleware stack for Praelatus
var DefaultMiddleware = []func(http.Handler) http.Handler{
	ContentHeaders,
	Logger,
}

Rename headers and add doc comment


package storage

import (
	"bytes"
	"errors"
	"io"
)

type Storage struct {
	data map[string][]byte
}

func (storage *Storage) CopyObjectToWriter(w io.Writer, bucket string, object string) error {
	// TODO synchronize access
	// get object
	key := bucket + ":" + object
	if val, ok := storage.data[key]; ok {
		objectBuffer := bytes.NewBuffer(val)
		_, err := io.Copy(w, objectBuffer)
		return err
	} else {
		return errors.New("Not Found")
	}
}

func (storage *Storage) StoreObject(bucket string, object string, data io.Reader) {
	key := bucket + ":" + object
	var bytesBuffer bytes.Buffer
	if _, ok := io.Copy(&bytesBuffer, data); ok == nil {
		storage.data[key] = bytesBuffer.Bytes()
	}
}

func Start() (chan<- string, <-chan error, *Storage) {
	ctrlChannel := make(chan string)
	errorChannel := make(chan error)
	go start(ctrlChannel, errorChannel)
	return ctrlChannel, errorChannel, &Storage{}
}

func start(ctrlChannel <-chan string, errorChannel chan<- error) {
	errorChannel <- errors.New("STORAGE MSG")
	errorChannel <- errors.New("STORAGE MSG")
	errorChannel <- errors.New("STORAGE MSG")
	close(errorChannel)
}

package storage

import (
	"bytes"
	"errors"
	"io"
)

type Storage struct {
	data map[string][]byte
}

func (storage *Storage) CopyObjectToWriter(w io.Writer, bucket string, object string) error {
	// TODO synchronize access
	// get object
	key := bucket + ":" + object
	if val, ok := storage.data[key]; ok {
		objectBuffer := bytes.NewBuffer(val)
		_, err := io.Copy(w, objectBuffer)
		return err
	} else {
		return errors.New("Not Found")
	}
}

func (storage *Storage) StoreObject(bucket string, object string, data io.Reader) {
	key := bucket + ":" + object
	var bytesBuffer bytes.Buffer
	if _, ok := io.Copy(&bytesBuffer, data); ok == nil {
		storage.data[key] = bytesBuffer.Bytes()
	}
}

func Start() (chan<- string, <-chan error, *Storage) {
	ctrlChannel := make(chan string)
	errorChannel := make(chan error)
	go start(ctrlChannel, errorChannel)
	return ctrlChannel, errorChannel, &Storage{
		data: make(map[string][]byte),
	}
}

func start(ctrlChannel <-chan string, errorChannel chan<- error) {
	errorChannel <- errors.New("STORAGE MSG")
	errorChannel <- errors.New("STORAGE MSG")
	errorChannel <- errors.New("STORAGE MSG")
	close(errorChannel)
}

Store objects in memory map


/*
Copyright 2016 Mirantis

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 integration

var (
	imageUrl = "ftp.ps.pl/pub/Linux/fedora-linux/releases/24/CloudImages/x86_64/images/Fedora-Cloud-Base-24-1.2.x86_64.qcow2"
)

/*
Copyright 2016 Mirantis

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 integration

var (
	imageUrl = "download.cirros-cloud.net/0.3.4/cirros-0.3.4-x86_64-disk.img"
)

Use CirrOS image for integration tests


package checker

import (
	"gokogiri/xpath"
	"butler/null"
	tp "tritium/proto"
)

func (result *CheckResult) CheckXpath(script *tp.ScriptObject) {
	iterate(script, func(ins *tp.Instruction) {
		if *ins.Type == tp.Instruction_FUNCTION_CALL {
			name := null.GetString(ins.Value)
			if name == "$" || name == "select" {
				if ins.Arguments != nil {
					test_xpath := null.GetString(ins.Arguments[0].Value)
					err := xpath.Check(test_xpath)
					if err != nil {
						result.AddXpathWarning(script, ins, name + "(\"" + test_xpath + "\") " + err.Error())
					}
				}
			}
		}
	})
}

package checker

import (
	"gokogiri/xpath"
	"butler/null"
	tp "tritium/proto"
)

func (result *CheckResult) CheckXpath(script *tp.ScriptObject) {
	iterate(script, func(ins *tp.Instruction) {
		if *ins.Type == tp.Instruction_FUNCTION_CALL {
			name := null.GetString(ins.Value)
			if name == "$" || name == "select" || name == "fetch" {
				if ins.Arguments != nil {
					test_xpath := null.GetString(ins.Arguments[0].Value)
					err := xpath.Check(test_xpath)
					if err != nil {
						result.AddXpathWarning(script, ins, err.Error())
					}
				}
			}
		}
	})
}

Include fetch and better error message format


package serialize

import (
	"encoding/json"
	"encoding/xml"
	"net/http"
	"strconv"
)

type Serializer int

const (
	Json Serializer = iota
	Xml
)

func Write(w http.ResponseWriter, value interface{}, s Serializer) (int, error) {
	var contentType string
	var data []byte
	var err error
	if s == Json {
		data, err = json.Marshal(value)
		contentType = "application/json"
	} else if s == Xml {
		data, err = xml.Marshal(value)
		contentType = "application/xml"
	}
	if err != nil {
		return 0, err
	}
	total := len(data)
	header := w.Header()
	header.Set("Content-Type", contentType)
	header.Set("Content-Length", strconv.Itoa(total))
	for c := 0; c < total; {
		n, err := w.Write(data)
		c += n
		if err != nil {
			return c, err
		}
	}
	return total, nil
}

package serialize

import (
	"encoding/json"
	"encoding/xml"
	"io"
	"net/http"
	"strconv"
)

type SerializationFormat int

const (
	Json SerializationFormat = iota
	Xml
)

func Write(w io.Writer, value interface{}, f SerializationFormat) (int, error) {
	var contentType string
	var data []byte
	var err error
	switch f {
	case Json:
		data, err = json.Marshal(value)
		contentType = "application/json"
	case Xml:
		data, err = xml.Marshal(value)
		contentType = "application/xml"
	default:
		panic("Invalid serialization format")
	}
	if err != nil {
		return 0, err
	}
	total := len(data)
	if rw, ok := w.(http.ResponseWriter); ok {
		header := rw.Header()
		header.Set("Content-Type", contentType)
		header.Set("Content-Length", strconv.Itoa(total))
	}
	for c := 0; c < total; {
		n, err := w.Write(data)
		c += n
		if err != nil {
			return c, err
		}
	}
	return total, nil
}

func WriteJson(w io.Writer, value interface{}) (int, error) {
	return Write(w, value, Json)
}

func WriteXml(w io.Writer, value interface{}) (int, error) {
	return Write(w, value, Xml)
}

Allow serialization to an io.Writer


package ActiveObject

import (
	"errors"
	"time"
)

//ActiveObjectWithInterval implements IActiveObject with behavior running in a specified interval
type ActiveObjectWithInterval struct {
	ticker      *time.Ticker
	doneChannel chan bool

	ActiveObjectRunningOnce
}

func NewActiveObjectWithInterval(duration time.Duration, workerFunction func(param interface{})) *ActiveObjectWithInterval {

	activeObject := &ActiveObjectWithInterval{}

	activeObject.duration = duration
	activeObject.workerFunction = workerFunction
	activeObject.doneChannel = make(chan bool)

	return activeObject
}

func (activeObject *ActiveObjectWithInterval) Run(param interface{}) error {
	if activeObject.ticker != nil {
		return errors.New("Already running")
	}

	activeObject.ticker = time.NewTicker(activeObject.duration)

	go func() {
		for {
			select {
			case <-activeObject.ticker.C:
				activeObject.workerFunction(param)

			case <-activeObject.doneChannel:
				activeObject.ticker.Stop()
				return
			}
		}
	}()

	return nil
}

func (activeObject *ActiveObjectWithInterval) ForceStop() {

	activeObject.doneChannel <- true

}

package ActiveObject

import (
	"errors"
	"time"
)

//ActiveObjectWithInterval implements IActiveObject with behavior running in a specified interval
type ActiveObjectWithInterval struct {
	ticker      *time.Ticker
	doneChannel chan bool

	ActiveObjectRunningOnce
}

func NewActiveObjectWithInterval(duration time.Duration, workerFunction func(param interface{})) *ActiveObjectWithInterval {

	activeObject := &ActiveObjectWithInterval{}

	activeObject.duration = duration
	activeObject.workerFunction = workerFunction
	activeObject.doneChannel = make(chan bool)

	return activeObject
}

func (activeObject *ActiveObjectWithInterval) Run(param interface{}) error {
	if activeObject.ticker != nil {
		return errors.New("Already running")
	}

	activeObject.ticker = time.NewTicker(activeObject.duration)

	activeObject.isStopped = false
	go func() {
		for {
			select {
			case <-activeObject.ticker.C:
				activeObject.workerFunction(param)

			case <-activeObject.doneChannel:
				activeObject.ticker.Stop()
				return
			}
		}
	}()

	return nil
}

func (activeObject *ActiveObjectWithInterval) ForceStop() {

	activeObject.isStopped = true
	activeObject.doneChannel <- true

}

Make sure the isStopped always set correctly in running once active object


/*
Package consts implements constants for the entire project
*/
package consts

// ConfigurationFileName is the configuration file name of Goyave
const ConfigurationFileName = ".goyave"

// GitFileName is the name of the git directory, in a git repository
const GitFileName = ".git"

Add the name of a Git directory


package main

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

func main() {
	var input string

	flag.StringVar(&input, "input", "", "input file")
	flag.Parse()

	if input == "" {
		flag.Usage()
		os.Exit(1)
	}

	var err error

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

	p := NewParser(f)

	col, err := p.Parse()
	if err != nil {
		panic(err)
	}

	fmt.Println("Read", len(col.Games), "games")
}

package main

import (
	"crypto/md5"
	"crypto/sha1"
	"encoding/hex"
	"encoding/json"
	"flag"
	"fmt"
	"io"
	"os"
	"strings"
)

func main() {
	var (
		input  string
		datset string
	)

	flag.StringVar(&input, "f", "", "input file")
	flag.StringVar(&datset, "d", "", "datset")
	flag.Parse()

	if input == "" || datset == "" {
		flag.Usage()
		os.Exit(1)
	}

	var err error

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

	h1, h2 := md5.New(), sha1.New()

	io.Copy(io.MultiWriter(h1, h2), in)

	md5hash := strings.ToUpper(hex.EncodeToString(h1.Sum(nil)))
	sha1hash := strings.ToUpper(hex.EncodeToString(h2.Sum(nil)))

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

	p := NewParser(f)

	col, err := p.Parse()
	if err != nil {
		panic(err)
	}

	for _, g := range col.Games {
		if g.ROM.MD5 != md5hash && g.ROM.SHA1 != sha1hash {
			continue
		}

		b, err := json.MarshalIndent(g, "", "  ")
		if err != nil {
			panic(err)
		}

		fmt.Printf("Found matching ROM:\n%s\n", b)
	}
}

Add flag to check if file is in datset


package main

import (
  "os"
  "time"

  tm "github.com/buger/goterm"
)

func main() {
  command := os.Args[1:]
  tm.Clear()
  loop(1*time.Second, func() {
    render(command)
  })
}

func render(command []string) {
  tm.MoveCursor(0,0)
  tm.Println(command)
  tm.Flush()
}

func loop(d time.Duration, fn func()) {
  time.After(d)
  fn()
  loop(d, fn)
}

package main

import (
  "bytes"
  "fmt"
  "io"
  "log"
  "os"
  "os/exec"
  "time"

  tm "github.com/buger/goterm"
)

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

  tm.Clear()
  tm.MoveCursor(0,0)

  loop(1*time.Second, func() {

    output, err := run(command)
    safe(err)

    render(output)

  })
}

func run(command []string) (bytes.Buffer, error) {
  name := command[0]
  args := command[1:]
  cmd  := exec.Command(name, args...)

  cmdPipe, err := cmd.StdoutPipe()
  if err != nil {
    return bytes.Buffer{}, err;
  }

  if err := cmd.Start(); err != nil {
    return bytes.Buffer{}, err;
  }

  pipeReader, pipeWriter := io.Pipe()

  go func() {
    _, err := io.Copy(pipeWriter, cmdPipe)
    // fixme: return error through a channel
    safe(err)
    pipeWriter.Close()
  } ()

  var buf bytes.Buffer
  _, err2 := io.Copy(&buf, pipeReader)
  safe(err2)

  return buf, nil
}

func l (s string) { fmt.Println(s) }

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

func render(output bytes.Buffer) {
  tm.Println(output.String())
  tm.Flush()
}

func loop(d time.Duration, fn func()) {
  time.After(d)
  fn()
  loop(d, fn)
}

Print output on each run by copying buffers around


package cmd

import (
	"io"
	"log"
	"net/url"
	"os"

	"github.com/bkittelmann/pinboard-checker/pinboard"
	"github.com/spf13/cobra"
)

func init() {
	exportCmd.Flags().StringP("token", "t", "", "The pinboard API token")
	exportCmd.Flags().String("endpoint", pinboard.DefaultEndpoint.String(), "URL of pinboard API endpoint")

	RootCmd.AddCommand(exportCmd)
}

var exportCmd = &cobra.Command{
	Use:   "export",
	Short: "Download your bookmarks",
	Long:  "...",

	Run: func(cmd *cobra.Command, args []string) {
		token, _ := cmd.Flags().GetString("token")
		endpoint, _ := cmd.Flags().GetString("endpoint")
		endpointUrl, _ := url.Parse(endpoint)

		client := pinboard.NewClient(token, endpointUrl)

		readCloser, err := client.DownloadBookmarks()
		if err != nil {
			log.Fatal(err)
		}
		io.Copy(os.Stdout, readCloser)
		readCloser.Close()
	},
}

package cmd

import (
	"fmt"
	"io"
	"log"
	"net/url"
	"os"

	"github.com/bkittelmann/pinboard-checker/pinboard"
	"github.com/spf13/cobra"
)

func init() {
	exportCmd.Flags().StringP("token", "t", "", "The pinboard API token")
	exportCmd.Flags().String("endpoint", pinboard.DefaultEndpoint.String(), "URL of pinboard API endpoint")

	RootCmd.AddCommand(exportCmd)
}

var exportCmd = &cobra.Command{
	Use:   "export",
	Short: "Download your bookmarks",
	Long:  "...",

	Run: func(cmd *cobra.Command, args []string) {
		token, _ := cmd.Flags().GetString("token")
		if len(token) == 0 {
			fmt.Println("ERROR: Token flag is mandatory for export command")
			os.Exit(1)
		}

		endpoint, _ := cmd.Flags().GetString("endpoint")
		endpointUrl, _ := url.Parse(endpoint)

		client := pinboard.NewClient(token, endpointUrl)

		readCloser, err := client.DownloadBookmarks()
		if err != nil {
			log.Fatal(err)
		}
		io.Copy(os.Stdout, readCloser)
		readCloser.Close()
	},
}

Validate that token parameter is set and abort program if it is not


package clean

import (
	"fmt"
	"os"
	"path/filepath"
	"strings"

	"github.com/littledot/mockhiato/lib"
	"github.com/littledot/mockhiato/lib/plugin/github.com/stretchr/testify"
)

// Run executes the command.
func Run(config lib.Config) {
	projectPath, err := filepath.Abs(config.ProjectPath)
	if err != nil {
		panic(err)
	}

	formatter := testify.NewTestifyFormatter(config)
	err = filepath.Walk(projectPath, func(filePath string, info os.FileInfo, err error) error {
		if err != nil { // Something wrong? Skip
			return nil
		}
		if !strings.HasSuffix(filePath, ".go") { // Not Go source? Skip
			return nil
		}

		file, err := os.Open(filePath)
		if err != nil {
			return nil
		}
		defer file.Close()
		if formatter.IsMockFile(file) { // Formatter says its a mock? Remove
			fmt.Println("Removing", filePath)
			if err := os.Remove(filePath); err != nil {
				panic(err)
			}
		}
		return nil
	})
	if err != nil {
		panic(err)
	}
}

package clean

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

	"github.com/littledot/mockhiato/lib"
	"github.com/littledot/mockhiato/lib/plugin/github.com/stretchr/testify"
	log "github.com/sirupsen/logrus"
)

// Run executes the command.
func Run(config lib.Config) {
	projectPath, err := filepath.Abs(config.ProjectPath)
	if err != nil {
		panic(err)
	}

	formatter := testify.NewTestifyFormatter(config)
	err = filepath.Walk(projectPath, func(filePath string, info os.FileInfo, err error) error {
		if err != nil { // Something wrong? Skip
			return nil
		}
		if !strings.HasSuffix(filePath, ".go") { // Not Go source? Skip
			return nil
		}

		file, err := os.Open(filePath)
		if err != nil {
			return nil
		}
		defer file.Close()
		if formatter.IsMockFile(file) { // Formatter says its a mock? Remove
			log.Infof("Remove %s", filePath)
			if err := os.Remove(filePath); err != nil {
				panic(err)
			}
		}
		return nil
	})
	if err != nil {
		panic(err)
	}
}

Replace `fmt` with `log` in clean.


package geoip

import (
	"fmt"
	. "launchpad.net/gocheck"
	"testing"
)

// Hook up gocheck into the gotest runner.
func Test(t *testing.T) { TestingT(t) }

type GeoIPSuite struct {
}

var _ = Suite(&GeoIPSuite{})

func (s *GeoIPSuite) Testv4(c *C) {
	gi, err := Open()
	if gi == nil || err != nil {
		fmt.Printf("Could not open GeoIP database: %s\n", err)
	}

	c.Check(gi, NotNil)

	country, netmask := gi.GetCountry("207.171.7.51")
	c.Check(country, Equals, "US")
	c.Check(netmask, Equals, 15)

	country, netmask = gi.GetCountry("64.235.248.1")
	c.Check(country, Equals, "US")
	c.Check(netmask, Equals, 20)
}

package geoip

import (
	"fmt"
	. "launchpad.net/gocheck"
	"testing"
)

// Hook up gocheck into the gotest runner.
func Test(t *testing.T) { TestingT(t) }

type GeoIPSuite struct {
}

var _ = Suite(&GeoIPSuite{})

func (s *GeoIPSuite) Testv4(c *C) {
	gi, err := Open()
	if gi == nil || err != nil {
		fmt.Printf("Could not open GeoIP database: %s\n", err)
	}

	c.Check(gi, NotNil)

	country, netmask := gi.GetCountry("207.171.7.51")
	c.Check(country, Equals, "US")
	c.Check(netmask, Equals, 15)

	country, netmask = gi.GetCountry("149.20.64.42")
	c.Check(country, Equals, "US")
	c.Check(netmask, Equals, 13)
}

Update netmask test to something that GeoIP and GeoLite (hopefully) agrees on


// Copyright © 2015 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

// Package log provides some handy types and method to activate and deactivate specific log
// behavior within files in a transparent way.
package log

import (
	"fmt"
)

// Logger is a minimalist interface to represent logger
type Logger interface {
	Log(format string, a ...interface{})
}

// DebugLogger can be used in development to display loglines in the console
type DebugLogger struct {
	Tag string
}

// Log implements the Logger interface
func (l DebugLogger) Log(format string, a ...interface{}) {
	fmt.Printf("[ %v ]  ", l.Tag)
	fmt.Printf(format, a...)
}

// VoidLogger can be used to deactivate logs by displaying nothing
type VoidLogger struct{}

// Log implements the Logger interface
func (l VoidLogger) Log(format string, a ...interface{}) {}

// Copyright © 2015 The Things Network
// Use of this source code is governed by the MIT license that can be found in the LICENSE file.

// Package log provides some handy types and method to activate and deactivate specific log
// behavior within files in a transparent way.
package log

import (
	"fmt"
	"testing"
)

// Logger is a minimalist interface to represent logger
type Logger interface {
	Log(format string, a ...interface{})
}

// DebugLogger can be used in development to display loglines in the console
type DebugLogger struct {
	Tag string
}

// Log implements the Logger interface
func (l DebugLogger) Log(format string, a ...interface{}) {
	fmt.Printf("\033[33m[ %s ]\033[0m ", l.Tag) // Tag printed in yellow
	fmt.Printf(format, a...)
	fmt.Print("\n")
}

// TestLogger can be used in a test environnement to display log only on failure
type TestLogger struct {
	Tag string
	T   *testing.T
}

// Log implements the Logger interface
func (l TestLogger) Log(format string, a ...interface{}) {
	l.T.Logf("\033[33m[ %s ]\033[0m %s", l.Tag, fmt.Sprintf(format, a...)) // Tag printed in yellow
}

// VoidLogger can be used to deactivate logs by displaying nothing
type VoidLogger struct{}

// Log implements the Logger interface
func (l VoidLogger) Log(format string, a ...interface{}) {}

Create a new Logger that goes well with the test environment


package initialize

import (
	"testing"
)

func TestParseHeaderCRLF(t *testing.T) {
	configs := []string{
		"#cloud-config\nfoo: bar",
		"#cloud-config\r\nfoo: bar",
	}

	for i, config := range configs {
		_, err := ParseUserData(config)
		if err != nil {
			t.Errorf("Failed parsing config %d: %v", i, err)
		}
	}

	scripts := []string{
		"#!bin/bash\necho foo",
		"#!bin/bash\r\necho foo",
	}

	for i, script := range scripts {
		_, err := ParseUserData(script)
		if err != nil {
			t.Errorf("Failed parsing script %d: %v", i, err)
		}
	}
}

func TestParseConfigCRLF(t *testing.T) {
	contents := "#cloud-config\r\nhostname: foo\r\nssh_authorized_keys:\r\n  - foobar\r\n"
	ud, err := ParseUserData(contents)
	if err != nil {
		t.Fatalf("Failed parsing config: %v", err)
	}

	cfg := ud.(CloudConfig)

	if cfg.Hostname != "foo" {
		t.Error("Failed parsing hostname from config")
	}

	if len(cfg.SSHAuthorizedKeys) != 1 {
		t.Error("Parsed incorrect number of SSH keys")
	}
}

Add test that parses user-data with carriage returns


package api

func (c *Sys) Health() (*HealthResponse, error) {
	r := c.c.NewRequest("GET", "/v1/sys/health")
	// If the code is 400 or above it will automatically turn into an error,
	// but the sys/health API defaults to returning 5xx when not sealed or
	// inited, so we force this code to be something else so we parse correctly
	r.Params.Add("sealedcode", "299")
	r.Params.Add("uninitcode", "299")
	resp, err := c.c.RawRequest(r)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result HealthResponse
	err = resp.DecodeJSON(&result)
	return &result, err
}

type HealthResponse struct {
	Initialized   bool   `json:"initialized"`
	Sealed        bool   `json:"sealed"`
	Standby       bool   `json:"standby"`
	ServerTimeUTC int64  `json:"server_time_utc"`
	Version       string `json:"version"`
	ClusterName   string `json:"cluster_name,omitempty"`
	ClusterID     string `json:"cluster_id,omitempty"`
}

package api

func (c *Sys) Health() (*HealthResponse, error) {
	r := c.c.NewRequest("GET", "/v1/sys/health")
	// If the code is 400 or above it will automatically turn into an error,
	// but the sys/health API defaults to returning 5xx when not sealed or
	// inited, so we force this code to be something else so we parse correctly
	r.Params.Add("sealedcode", "299")
	r.Params.Add("uninitcode", "299")
	resp, err := c.c.RawRequest(r)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result HealthResponse
	err = resp.DecodeJSON(&result)
	return &result, err
}

type HealthResponse struct {
	Initialized         bool   `json:"initialized"`
	Sealed              bool   `json:"sealed"`
	Standby             bool   `json:"standby"`
	ReplicationPerfMode string `json:"replication_perf_mode"`
	ReplicationDRMode   string `json:"replication_dr_mode"`
	ServerTimeUTC       int64  `json:"server_time_utc"`
	Version             string `json:"version"`
	ClusterName         string `json:"cluster_name,omitempty"`
	ClusterID           string `json:"cluster_id,omitempty"`
}

Add replication mode sys health information to Go API


package configuration

import (
	"flag"
	"log"

	"github.com/FogCreek/mini"
)

type iagoConfiguration struct {
	Hostname string
	Protocol string
	Port     string
	Path     string
}

var (
	Iago iagoConfiguration
)

func Process() {
	path := flag.String("config", "/etc/miloud.ini", "Configuration file path")
	flag.Parse()

	config, err := mini.LoadConfiguration(*path)

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

	Iago.Hostname = config.StringFromSection("Iago", "Hostname", "")
	Iago.Protocol = config.StringFromSection("Iago", "Protocol", "http")
	Iago.Path = config.StringFromSection("Iago", "Path", "/")
	Iago.Port = config.IntegerFromSection("Iago", "Port", 0)

	if Iago.Port == 0 {
		if Iago.Protocol == "http" {
			Iago.Port = 80
		} else if Iago.Protocol == "https" {
			Iago.Port = 443
		}
	}
}

package configuration

import (
	"flag"
	"log"

	"github.com/FogCreek/mini"
)

type iagoConfiguration struct {
	Hostname string
	Protocol string
	Port     string
	Path     string
}

var (
	Iago iagoConfiguration
)

func Process() {
	path := flag.String("config", "/etc/miloud.ini", "Configuration file path")
	flag.Parse()

	config, err := mini.LoadConfiguration(*path)

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

	Iago.Hostname = config.StringFromSection("Iago", "Hostname", "localhost")
	Iago.Protocol = config.StringFromSection("Iago", "Protocol", "http")
	Iago.Path = config.StringFromSection("Iago", "Path", "/")
	Iago.Port = config.IntegerFromSection("Iago", "Port", 0)

	if Iago.Port == 0 {
		if Iago.Protocol == "http" {
			Iago.Port = 80
		} else if Iago.Protocol == "https" {
			Iago.Port = 443
		}
	}
}

Set the default Iago hostname to localhost


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

// +build !amd64,!s390x

package aes12

// newCipher calls the newCipherGeneric function
// directly. Platforms with hardware accelerated
// implementations of AES should implement their
// own version of newCipher (which may then call
// newCipherGeneric if needed).
func newCipher(key []byte) (Block, error) {
	return newCipherGeneric(key)
}

// expandKey is used by BenchmarkExpand and should
// call an assembly implementation if one is available.
func expandKey(key []byte, enc, dec []uint32) {
	expandKeyGo(key, enc, dec)
}

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

// +build !amd64

package aes12

// newCipher calls the newCipherGeneric function
// directly. Platforms with hardware accelerated
// implementations of AES should implement their
// own version of newCipher (which may then call
// newCipherGeneric if needed).
func newCipher(key []byte) (Block, error) {
	return newCipherGeneric(key)
}

// expandKey is used by BenchmarkExpand and should
// call an assembly implementation if one is available.
func expandKey(key []byte, enc, dec []uint32) {
	expandKeyGo(key, enc, dec)
}

Use generic implementation for s390x


// +build !windows

package fzf

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

// +build !windows

package fzf

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

Add -L flag to the default find command


// +build windows

package util

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

// ExecCommand executes the given command with cmd
func ExecCommand(command string) *exec.Cmd {
	return ExecCommandWith("cmd", command)
}

// ExecCommandWith executes the given command with cmd. _shell parameter is
// ignored on Windows.
func ExecCommandWith(_shell string, command string) *exec.Cmd {
	cmd := exec.Command("cmd")
	cmd.SysProcAttr = &syscall.SysProcAttr{
	    HideWindow: false,
	    CmdLine: fmt.Sprintf(` /s /c "%s"`, command),
	    CreationFlags: 0,
	}
	return cmd
}

// IsWindows returns true on Windows
func IsWindows() bool {
	return true
}

// SetNonBlock executes syscall.SetNonblock on file descriptor
func SetNonblock(file *os.File, nonblock bool) {
	syscall.SetNonblock(syscall.Handle(file.Fd()), nonblock)
}

// Read executes syscall.Read on file descriptor
func Read(fd int, b []byte) (int, error) {
	return syscall.Read(syscall.Handle(fd), b)
}

// +build windows

package util

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

// ExecCommand executes the given command with cmd
func ExecCommand(command string) *exec.Cmd {
	return ExecCommandWith("cmd", command)
}

// ExecCommandWith executes the given command with cmd. _shell parameter is
// ignored on Windows.
func ExecCommandWith(_shell string, command string) *exec.Cmd {
	cmd := exec.Command("cmd")
	cmd.SysProcAttr = &syscall.SysProcAttr{
		HideWindow:    false,
		CmdLine:       fmt.Sprintf(` /s /c "%s"`, command),
		CreationFlags: 0,
	}
	return cmd
}

// IsWindows returns true on Windows
func IsWindows() bool {
	return true
}

// SetNonBlock executes syscall.SetNonblock on file descriptor
func SetNonblock(file *os.File, nonblock bool) {
	syscall.SetNonblock(syscall.Handle(file.Fd()), nonblock)
}

// Read executes syscall.Read on file descriptor
func Read(fd int, b []byte) (int, error) {
	return syscall.Read(syscall.Handle(fd), b)
}

Fix compilation error of Windows binary


package app

import (
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"sync"

	"github.com/stevenjack/cig/output"
	"github.com/stevenjack/cig/repo"
)

func Handle(repoList map[string]string, projectTypeToCheck string, filter string, output_channel chan output.Payload) {
	var wg sync.WaitGroup

	for projectType, path := range repoList {
		if projectTypeToCheck == "" || projectTypeToCheck == projectType {
			output_channel <- output.Print(fmt.Sprintf("\nChecking '%s' (%s) repos...", projectType, path))

			visit := func(visitedPath string, info os.FileInfo, err error) error {
				matched, _ := regexp.MatchString(filter, visitedPath)
				if info.IsDir() && (filter == "" || matched) {
					wg.Add(1)
					go repo.Check(path, visitedPath, output_channel, &wg)
				}
				return nil
			}

			err := filepath.Walk(path, visit)
			if err != nil {
				output_channel <- output.FatalError(err.Error())
			}
		}

		wg.Wait()
	}
	wg.Wait()
}

package app

import (
	"fmt"
	"os"
	"path/filepath"
	"regexp"
	"sync"

	"github.com/stevenjack/cig/output"
	"github.com/stevenjack/cig/repo"
)

func Handle(repoList map[string]string, projectTypeToCheck string, filter string, output_channel chan output.Payload) {
	var wg sync.WaitGroup

	for projectType, path := range repoList {
		if projectTypeToCheck == "" || projectTypeToCheck == projectType {
			output_channel <- output.Print(fmt.Sprintf("\nChecking '%s' (%s) repos...", projectType, path))

			visit := func(visitedPath string, info os.FileInfo, err error) error {
				if err != nil {
					output_channel <- output.Error(fmt.Sprintf("- %s", err.Error()))
					return nil
				}
				matched, _ := regexp.MatchString(filter, visitedPath)
				if info.IsDir() && (filter == "" || matched) {
					wg.Add(1)
					go repo.Check(path, visitedPath, output_channel, &wg)
				}
				return nil
			}

			err := filepath.Walk(path, visit)
			if err != nil {
				output_channel <- output.FatalError(err.Error())
			}
		}

		wg.Wait()
	}
	wg.Wait()
}

Fix crash/panic when in wrong directory.


// 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())
}

// 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())
}

Remove env flag around NewSecretStoreFile


package lexer

type Lexer struct {
	input        string
	position     int  // current position in input (points to current char)
	readPosition int  // current reading position in input (after current char)
	ch           byte // current char being looked at
}

func New(input string) *Lexer {
	l := &Lexer{input: input}
	return l
}

func (l *Lexer) readChar() {
	if l.readPosition >= len(l.input) {
		l.ch = 0 // return 0 byte if EOF
	} else {
		l.ch = l.input[l.readPosition]
	}
	l.position = l.readPosition
	l.readPosition += 1
}

package lexer

import "gadget/token"

type Lexer struct {
	input        string
	position     int  // current position in input (points to current char)
	readPosition int  // current reading position in input (after current char)
	ch           byte // current char being looked at
}

func New(input string) *Lexer {
	l := &Lexer{input: input}
	l.readChar()
	return l
}

func (l *Lexer) readChar() {
	if l.readPosition >= len(l.input) {
		l.ch = 0 // return 0 byte if EOF
	} else {
		l.ch = l.input[l.readPosition]
	}
	l.position = l.readPosition
	l.readPosition += 1
}

func (l *Lexer) NextToken() token.Token {
	var tok token.Token

	switch l.ch {
	case '=':
		tok = newToken(token.ASSIGN, l.ch)
	case ';':
		tok = newToken(token.SEMICOLON, l.ch)
	case '(':
		tok = newToken(token.LPAREN, l.ch)
	case ')':
		tok = newToken(token.RPAREN, l.ch)
	case ',':
		tok = newToken(token.COMMA, l.ch)
	case '+':
		tok = newToken(token.PLUS, l.ch)
	case '{':
		tok = newToken(token.LBRACE, l.ch)
	case '}':
		tok = newToken(token.RBRACE, l.ch)
	case 0:
		tok.Literal = ""
		tok.Type = token.EOF
	}

	l.readChar()
	return tok
}

func newToken(tokenType token.TokenType, ch byte) token.Token {
	return token.Token{Type: tokenType, Literal: string(ch)}
}

Implement remaining Lexer functions for tests to pass.


package fakes

import boshsys "github.com/cloudfoundry/bosh-utils/system"

type FakePSRunner struct {
	RunCommands   []boshsys.PSCommand
	RunCommandErr error
}

func NewFakePSRunner() *FakePSRunner {
	return &FakePSRunner{
		RunCommands: []boshsys.PSCommand{},
	}
}

func (r *FakePSRunner) RunCommand(cmd boshsys.PSCommand) (string, string, error) {
	r.RunCommands = append(r.RunCommands, cmd)
	return "", "", r.RunCommandErr
}

package fakes

import (
	"fmt"

	boshsys "github.com/cloudfoundry/bosh-utils/system"
)

type FakePSRunner struct {
	RunCommands      []boshsys.PSCommand
	RunCommandErr    error
	runCommandErrors map[string]error
}

func NewFakePSRunner() *FakePSRunner {
	return &FakePSRunner{
		RunCommands:      []boshsys.PSCommand{},
		runCommandErrors: map[string]error{},
	}
}

func (r *FakePSRunner) RunCommand(cmd boshsys.PSCommand) (string, string, error) {
	r.RunCommands = append(r.RunCommands, cmd)
	if err := r.runCommandErrors[cmd.Script]; err != nil {
		return "", "", err
	}
	return "", "", r.RunCommandErr
}

func (r *FakePSRunner) RegisterRunCommandError(script string, err error) {
	if _, ok := r.runCommandErrors[script]; ok {
		panic(fmt.Sprintf("RunCommand error is already set for command: %s", script))
	}
	r.runCommandErrors[script] = err
}

Add a way to trigger specific errors on the PSRunner


package locket

import (
	"code.cloudfoundry.org/cfhttp"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/locket/models"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

type ClientLocketConfig struct {
	LocketAddress        string `json:"locket_address,omitempty"`
	LocketCACertFile     string `json:"locket_ca_cert_file,omitempty"`
	LocketClientCertFile string `json:"locket_client_cert_file,omitempty"`
	LocketClientKeyFile  string `json:"locket_client_key_file,omitempty"`
}

func NewClient(logger lager.Logger, config ClientLocketConfig) (models.LocketClient, error) {
	locketTLSConfig, err := cfhttp.NewTLSConfig(config.LocketClientCertFile, config.LocketClientKeyFile, config.LocketCACertFile)
	if err != nil {
		return nil, err
	}

	conn, err := grpc.Dial(config.LocketAddress, grpc.WithTransportCredentials(credentials.NewTLS(locketTLSConfig)))
	if err != nil {
		return nil, err
	}
	return models.NewLocketClient(conn), nil
}

package locket

import (
	"code.cloudfoundry.org/cfhttp"
	"code.cloudfoundry.org/lager"
	"code.cloudfoundry.org/locket/models"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials"
)

type ClientLocketConfig struct {
	LocketAddress        string `json:"locket_address,omitempty" yaml:"locket_address,omitempty"`
	LocketCACertFile     string `json:"locket_ca_cert_file,omitempty" yaml:"locket_ca_cert_file,omitempty"`
	LocketClientCertFile string `json:"locket_ca_cert_file,omitempty" yaml:"locket_client_cert_file,omitempty"`
	LocketClientKeyFile  string `json:"locket_client_key_file,omitempty" yaml:"locket_client_key_file,omitempty"`
}

func NewClient(logger lager.Logger, config ClientLocketConfig) (models.LocketClient, error) {
	locketTLSConfig, err := cfhttp.NewTLSConfig(config.LocketClientCertFile, config.LocketClientKeyFile, config.LocketCACertFile)
	if err != nil {
		return nil, err
	}

	conn, err := grpc.Dial(config.LocketAddress, grpc.WithTransportCredentials(credentials.NewTLS(locketTLSConfig)))
	if err != nil {
		return nil, err
	}
	return models.NewLocketClient(conn), nil
}

Add YAML serialization to ClientLocketConfig


// The version package provides a location to set the release versions for all
// packages to consume, without creating import cycles.
//
// This package should not import any other terraform packages.
package version

import (
	"fmt"

	version "github.com/hashicorp/go-version"
)

// The main version number that is being run at the moment.
const Version = "0.12.0"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
var Prerelease = "dev"

// SemVer is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVer = version.Must(version.NewVersion(Version))

// Header is the header name used to send the current terraform version
// in http requests.
const Header = "Terraform-Version"

// String returns the complete version string, including prerelease
func String() string {
	if Prerelease != "" {
		return fmt.Sprintf("%s-%s", Version, Prerelease)
	}
	return Version
}

// The version package provides a location to set the release versions for all
// packages to consume, without creating import cycles.
//
// This package should not import any other terraform packages.
package version

import (
	"fmt"

	version "github.com/hashicorp/go-version"
)

// The main version number that is being run at the moment.
var Version = "0.12.0"

// A pre-release marker for the version. If this is "" (empty string)
// then it means that it is a final release. Otherwise, this is a pre-release
// such as "dev" (in development), "beta", "rc1", etc.
var Prerelease = "dev"

// SemVer is an instance of version.Version. This has the secondary
// benefit of verifying during tests and init time that our version is a
// proper semantic version, which should always be the case.
var SemVer *version.Version

func init() {
	SemVer = version.Must(version.NewVersion(Version))
}

// Header is the header name used to send the current terraform version
// in http requests.
const Header = "Terraform-Version"

// String returns the complete version string, including prerelease
func String() string {
	if Prerelease != "" {
		return fmt.Sprintf("%s-%s", Version, Prerelease)
	}
	return Version
}

Fix the Filesystem state manager tests


package turbulence

import "github.com/pivotal-cf-experimental/destiny/ops"

type ConfigV2 struct {
	Name             string
	AZs              []string
	DirectorHost     string
	DirectorUsername string
	DirectorPassword string
	DirectorCACert   string
}

func NewManifestV2(config ConfigV2) (string, error) {
	return ops.ApplyOps(manifestV2, []ops.Op{
		{"replace", "/name", config.Name},
		{"replace", "/instance_groups/name=api/azs", config.AZs},
		{"replace", "/instance_groups/name=api/properties/director/host", config.DirectorHost},
		{"replace", "/instance_groups/name=api/properties/director/client", config.DirectorUsername},
		{"replace", "/instance_groups/name=api/properties/director/client_secret", config.DirectorPassword},
		{"replace", "/instance_groups/name=api/properties/director/ca_cert", config.DirectorCACert},
	})
}

package turbulence

import "github.com/pivotal-cf-experimental/destiny/ops"

type ConfigV2 struct {
	Name             string
	AZs              []string
	DirectorHost     string
	DirectorUsername string
	DirectorPassword string
	DirectorCACert   string
}

func NewManifestV2(config ConfigV2) (string, error) {
	return ops.ApplyOps(manifestV2, []ops.Op{
		{"replace", "/name", config.Name},
		{"replace", "/instance_groups/name=api/azs", config.AZs},
		{"replace", "/instance_groups/name=api/properties/director/host", config.DirectorHost},
		{"replace", "/instance_groups/name=api/properties/director/client", config.DirectorUsername},
		{"replace", "/instance_groups/name=api/properties/director/client_secret", config.DirectorPassword},
		{"replace", "/instance_groups/name=api/properties/director/cert/ca", config.DirectorCACert},
	})
}

Fix ops file for turbulence manifest


package main

import (
	"context"
	"runtime"

	stub "github.com/banzaicloud/bank-vaults/operator/pkg/stub"
	sdk "github.com/operator-framework/operator-sdk/pkg/sdk"
	sdkVersion "github.com/operator-framework/operator-sdk/version"

	"github.com/sirupsen/logrus"
)

func printVersion() {
	logrus.Infof("Go Version: %s", runtime.Version())
	logrus.Infof("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH)
	logrus.Infof("operator-sdk Version: %v", sdkVersion.Version)
}

func main() {
	printVersion()
	sdk.Watch("vault.banzaicloud.com/v1alpha1", "Vault", "", 5)
	sdk.Handle(stub.NewHandler())
	sdk.Run(context.TODO())
}

package main

import (
	"context"
	"os"
	"runtime"

	stub "github.com/banzaicloud/bank-vaults/operator/pkg/stub"
	sdk "github.com/operator-framework/operator-sdk/pkg/sdk"
	sdkVersion "github.com/operator-framework/operator-sdk/version"

	"github.com/sirupsen/logrus"
)

const operatorNamespace = "OPERATOR_NAMESPACE"

func printVersion(namespace string) {
	logrus.Infof("Go Version: %s", runtime.Version())
	logrus.Infof("Go OS/Arch: %s/%s", runtime.GOOS, runtime.GOARCH)
	logrus.Infof("operator-sdk Version: %v", sdkVersion.Version)
	logrus.Infof("operator namespace: %s", namespace)
}

func main() {
	ns := os.Getenv(operatorNamespace)
	printVersion(ns)
	sdk.Watch("vault.banzaicloud.com/v1alpha1", "Vault", ns, 5)
	sdk.Handle(stub.NewHandler())
	sdk.Run(context.TODO())
}

Configure the operator namespace over an environment variable


package backends

type FileStore interface {
	// create new file at path
	CreateFile(path string, content []byte) (err error)

	// update existing file at path
	UpdateFile(path string, content []byte) (err error)

	// create dir at path
	CreateDir(path string) (err error)

	// read content of file at path
	ReadFile(path string) (content []byte, err error)

	// list direct child paths within dir at path
	ReadDir(path string) (paths []string, err error)

	// move file or dir at path
	Move(path string, newPath string) (err error)

	// delete file or dir at path
	Delete(path string) (err error)
}

package backends

type FileStore interface {
	// create new file at path
	CreateFile(path string, content []byte) (err error)

	// update existing file at path
	UpdateFile(path string, content []byte) (err error)

	// create dir at path
	CreateDir(path string) (err error)

	// read content of file at path
	ReadFile(path string) (content []byte, err error)

	// list direct child paths within dir at path
	ReadDir(path string) (paths []string, err error)

	// list direct and indirect child paths within dir at path for a given depth
	// depth -1 means unlimited depth
	ReadDirTree(path string, depth int) (paths []string, err error)

	// move file or dir at path
	Move(path string, newPath string) (err error)

	// delete file or dir at path
	Delete(path string) (err error)
}

Add ReadDirTree to file store interface.


package main

import (
	"github.com/codegangsta/martini"
	"github.com/codegangsta/martini-contrib/render"
)

func main() {
    m := martini.Classic()
    m.Use(render.Renderer())

    m.Get("/", func() string {
        return "Merry Christmas!"
    })

    m.Get("/wishes", func(r render.Render) {
        r.HTML(200, "list", nil)
    })

    m.Run()
}

package main

import (
	"github.com/codegangsta/martini"
    "github.com/codegangsta/martini-contrib/binding"
	"github.com/codegangsta/martini-contrib/render"
    "gopkg.in/mgo.v2"
)

type Wish struct {
    Name string `form:"name"`
    Description string `form:"name"`
}

// DB Returns a martini.Handler
func DB() martini.Handler {
    session, err := mgo.Dial("mongodb://localhost")
    if err != nil {
        panic(err)
    }

    return func(c martini.Context) {
        s := session.Clone()
        c.Map(s.DB("advent"))
        defer s.Close()
        c.Next()
    }
}

// GetAll returns all Wishes in the database
func GetAll(db *mgo.Database) []Wish {
    var wishlist []Wish
    db.C("wishes").Find(nil).All(&wishlist)
    return wishlist
}

func main() {
    m := martini.Classic()
    m.Use(render.Renderer())
    m.Use(DB())

    m.Get("/", func() string {
        return "Merry Christmas!"
    })

    m.Get("/wishes", func(r render.Render) {
        r.HTML(200, "list", nil)
    })

    m.Post("/wishes", binding.Form(Wish{}), func(wish Wish, r render.Render, db *mgo.Database) {
        db.C("wishes").Insert(wish)
        r.HTML(200, "list", GetAll(db))
    })

    m.Run()
}

Add MongoDB + post route handling


// Code generated by protoc-gen-gogo.
// source: uuid.proto
// DO NOT EDIT!

package events

import proto "github.com/gogo/protobuf/proto"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf

// / Type representing a 128-bit UUID.
type UUID struct {
	Low              *uint64 `protobuf:"varint,1,req,name=low" json:"low,omitempty"`
	High             *uint64 `protobuf:"varint,2,req,name=high" json:"high,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

func (m *UUID) Reset()         { *m = UUID{} }
func (m *UUID) String() string { return proto.CompactTextString(m) }
func (*UUID) ProtoMessage()    {}

func (m *UUID) GetLow() uint64 {
	if m != nil && m.Low != nil {
		return *m.Low
	}
	return 0
}

func (m *UUID) GetHigh() uint64 {
	if m != nil && m.High != nil {
		return *m.High
	}
	return 0
}

func init() {
}

// Code generated by protoc-gen-gogo.
// source: uuid.proto
// DO NOT EDIT!

package events

import proto "github.com/gogo/protobuf/proto"
import math "math"

// Reference imports to suppress errors if they are not otherwise used.
var _ = proto.Marshal
var _ = math.Inf

// / Type representing a 128-bit UUID.
//
// The bytes of the UUID should be packed in little-endian **byte** (not bit) order. For example, the UUID `f47ac10b-58cc-4372-a567-0e02b2c3d479` should be encoded as `UUID{ low: 0x7243cc580bc17af4, high: 0x79d4c3b2020e67a5 }`
type UUID struct {
	Low              *uint64 `protobuf:"varint,1,req,name=low" json:"low,omitempty"`
	High             *uint64 `protobuf:"varint,2,req,name=high" json:"high,omitempty"`
	XXX_unrecognized []byte  `json:"-"`
}

func (m *UUID) Reset()         { *m = UUID{} }
func (m *UUID) String() string { return proto.CompactTextString(m) }
func (*UUID) ProtoMessage()    {}

func (m *UUID) GetLow() uint64 {
	if m != nil && m.Low != nil {
		return *m.Low
	}
	return 0
}

func (m *UUID) GetHigh() uint64 {
	if m != nil && m.High != nil {
		return *m.High
	}
	return 0
}

func init() {
}

Update dropsonde-protocol to revision 9057f01


package TF2RconWrapper

type Player struct {
	UserID   string
	Username string
	SteamID  string
	Ping     int
	State    string
	Ip       string
}

package TF2RconWrapper

type Player struct {
	UserID   string
	Username string
	SteamID  string
	//Ping     int
	//State    string
	Ip string
}

Comment out ping and state fields (for now)


// Package go-oui provides functions to work with MAC and OUI's
package ouitools

import (
	"fmt"
	"log"
	"testing"
)

func Test(*testing.T) {
	d := &OuiDb{}
	err := d.Load("oui.txt")

	if err != nil {
		log.Fatal("Error %v", err)
	}

	address, _ := ParseMAC("60:03:08:a0:ec:a6")
	block := d.Lookup(address)

	fmt.Println("bla %v", block)

	address, _ = ParseMAC("00:25:9c:42:c2:62")
	block = d.Lookup(address)

	fmt.Println("Bla %v", block)

	address, _ = ParseMAC("00:16:e0:3d:f4:4c")
	block = d.Lookup(address)

	fmt.Println("Bla %v", block)

}

// Package go-oui provides functions to work with MAC and OUI's
package ouidb

import (
	"fmt"
	"log"
	"testing"
)

func Test(*testing.T) {
	d := &OuiDb{}
	err := d.Load("oui.txt")

	if err != nil {
		log.Fatal("Error %v", err)
	}

	address, _ := ParseMAC("60:03:08:a0:ec:a6")
	block := d.Lookup(address)

	fmt.Println("bla %v", block)

	address, _ = ParseMAC("00:25:9c:42:c2:62")
	block = d.Lookup(address)

	fmt.Println("Bla %v", block)

	address, _ = ParseMAC("00:16:e0:3d:f4:4c")
	block = d.Lookup(address)

	fmt.Println("Bla %v", block)

}

Change test file package to match main package name