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

package utils

import (
	"github.com/juju/errors"

	"github.com/juju/juju/instance"
	provcommon "github.com/juju/juju/provider/common"
	"github.com/juju/juju/state"
)

// AvailabilityZone returns the availability zone associated with
// an instance ID.
func AvailabilityZone(st *state.State, instID instance.Id) (string, error) {
	// Get the provider.
	env, err := GetEnvironment(st)
	if err != nil {
		return "", errors.Trace(err)
	}
	zenv, ok := env.(provcommon.ZonedEnviron)
	if !ok {
		return "", errors.NotSupportedf("zones for provider %v", env)
	}

	// Request the zone.
	zones, err := zenv.InstanceAvailabilityZoneNames([]instance.Id{instID})
	if err != nil {
		return "", errors.Trace(err)
	}
	if len(zones) != 1 {
		return "", errors.Errorf("received invalid zones: expected 1, got %d", len(zones))
	}

	return zones[0], nil
}

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

package utils

import (
	"github.com/juju/errors"

	"github.com/juju/juju/instance"
	provcommon "github.com/juju/juju/provider/common"
	"github.com/juju/juju/state"
)

// AvailabilityZone returns the availability zone associated with
// an instance ID.
func AvailabilityZone(st *state.State, instID instance.Id) (string, error) {
	// Get the provider.
	env, err := GetEnvironment(st)
	if err != nil {
		return "", errors.Trace(err)
	}
	zenv, ok := env.(provcommon.ZonedEnviron)
	if !ok {
		return "", errors.NotSupportedf(`zones for provider "%T"`, env)
	}

	// Request the zone.
	zones, err := zenv.InstanceAvailabilityZoneNames([]instance.Id{instID})
	if err != nil {
		return "", errors.Trace(err)
	}
	if len(zones) != 1 {
		return "", errors.Errorf("received invalid zones: expected 1, got %d", len(zones))
	}

	return zones[0], nil
}

Clean up an error message.


package main

import (
	"testing"

	"github.com/fmi/go-homework/geom"
)

func TestSampleSimpleOperations(t *testing.T) {
	var prim geom.Intersectable

	a, b, c := geom.NewVector(-1, -1, 0), geom.NewVector(1, -1, 0), geom.NewVector(0, 1, 0)
	prim = NewTriangle(a, b, c)
	ray := geom.NewRay(geom.NewVector(0, 0, -1), geom.NewVector(0, 0, 1))

	if !prim.Intersect(ray) {
		t.Errorf("Expected ray %#v to intersect triangle %#v but it did not.", ray, prim)
	}
}

func TestSampleIntersectableImplementations(t *testing.T) {
	var prim geom.Intersectable

	a, b, c, d := geom.NewVector(-1, -1, 0),
		geom.NewVector(1, -1, 0),
		geom.NewVector(0, 1, 0),
		geom.NewVector(1, 1, 0)

	prim = NewTriangle(a, b, c)
	prim = NewQuad(a, b, c, d)
	prim = NewSphere(a, 5)

	_ = prim
}

package main

import (
	"testing"

	"github.com/fmi/go-homework/geom"
)

func TestSampleSimpleOperations(t *testing.T) {
	var prim geom.Intersectable

	a, b, c := geom.NewVector(-1, -1, 0), geom.NewVector(1, -1, 0), geom.NewVector(0, 1, 0)
	prim = NewTriangle(a, b, c)
	ray := geom.NewRay(geom.NewVector(0, 0, -1), geom.NewVector(0, 0, 1))

	if !prim.Intersect(ray) {
		t.Errorf("Expected ray %#v to intersect triangle %#v but it did not.", ray, prim)
	}
}

func TestSampleIntersectableImplementations(t *testing.T) {
	var prim geom.Intersectable

	a, b, c, d := geom.NewVector(-1, -1, 0),
		geom.NewVector(1, -1, 0),
		geom.NewVector(0, 1, 0),
		geom.NewVector(-1, 1, 0)

	prim = NewTriangle(a, b, c)
	prim = NewQuad(a, b, c, d)
	prim = NewSphere(a, 5)

	_ = prim
}

Fix a wrong point in the task 03 sample test


package util

import "log"

type SomaUtil struct {
	Log *log.Logger
}

func (u *SomaUtil) SetLog(l *log.Logger) {
	u.Log = l
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix

package util

import "log"

type SomaUtil struct {
	Log *log.Logger
}

// vim: ts=4 sw=4 sts=4 noet fenc=utf-8 ffs=unix

Kill last old logger function


package instance

import (
	bosherr "github.com/cloudfoundry/bosh-utils/errors"

	"bosh-google-cpi/api"
	"bosh-google-cpi/util"
)

func (i GoogleInstanceService) Reboot(id string) error {
	instance, found, err := i.Find(id, "")
	if err != nil {
		return err
	}
	if !found {
		return api.NewVMNotFoundError(id)
	}

	i.logger.Debug(googleInstanceServiceLogTag, "Rebooting Google Instance '%s'", id)
	operation, err := i.computeService.Instances.Reset(i.project, util.ResourceSplitter(instance.Zone), id).Do()
	if err != nil {
		return bosherr.WrapErrorf(err, "Failed to reboot Google Instance '%s'", id)
	}

	if _, err = i.operationService.Waiter(operation, instance.Zone, ""); err != nil {
		return bosherr.WrapErrorf(err, "Failed to reboot Google Instance '%s'", id)
	}

	return nil
}

package instance

import (
	bosherr "github.com/cloudfoundry/bosh-utils/errors"

	"bosh-google-cpi/api"
	"bosh-google-cpi/util"
)

const (
	STATUS_RUNNING    = "RUNNING"
	STATUS_TERMINATED = "TERMINATED"
)

func (i GoogleInstanceService) Reboot(id string) error {
	instance, found, err := i.Find(id, "")
	if err != nil {
		return err
	}
	if !found {
		return api.NewVMNotFoundError(id)
	}

	switch instance.Status {
	default:
		return bosherr.Errorf("Can not reboot instance in state %q", instance.Status)
	case STATUS_RUNNING:
		i.logger.Debug(googleInstanceServiceLogTag, "Rebooting running Google Instance %q via reset API", id)
		operation, err := i.computeService.Instances.Reset(i.project, util.ResourceSplitter(instance.Zone), id).Do()
		if err != nil {
			return bosherr.WrapErrorf(err, "Failed to reboot Google Instance '%s'", id)
		}
		if _, err = i.operationService.Waiter(operation, instance.Zone, ""); err != nil {
			return bosherr.WrapErrorf(err, "Failed to reboot Google Instance '%s'", id)
		}
		return nil
	case STATUS_TERMINATED:
		i.logger.Debug(googleInstanceServiceLogTag, "Rebooting terminated Google Instance %q via start API", id)
		operation, err := i.computeService.Instances.Start(i.project, util.ResourceSplitter(instance.Zone), id).Do()
		if err != nil {
			return bosherr.WrapErrorf(err, "Failed to reboot Google Instance '%s'", id)
		}
		if _, err = i.operationService.Waiter(operation, instance.Zone, ""); err != nil {
			return bosherr.WrapErrorf(err, "Failed to reboot Google Instance '%s'", id)
		}
		return nil
	}
}

Support reboot of TERMINATED VMs


package main

import (
	"flag"
	"path"

	"github.com/skia-dev/glog"
	"go.skia.org/infra/go/auth"
	"go.skia.org/infra/go/buildbucket"
	"go.skia.org/infra/go/common"
)

var (
	id      = flag.String("id", "", "ID of the build to retrieve.")
	workdir = flag.String("workdir", "workdir", "Working directory to use.")
)

func main() {
	defer common.LogPanic()
	common.Init()

	if *id == "" {
		glog.Fatal("ID is required.")
	}

	// Initialize the BuildBucket client.
	c, err := auth.NewClient(true, path.Join(*workdir, "oauth_token_cache"), buildbucket.DEFAULT_SCOPES...)
	if err != nil {
		glog.Fatal(err)
	}
	bb := buildbucket.NewClient(c)

	// Retrieve the build.
	build, err := bb.GetBuild(*id)
	if err != nil {
		glog.Fatal(err)
	}
	glog.Infof("Build: %s\n%v", build.Url, build)
}

package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"path"

	"github.com/skia-dev/glog"
	"go.skia.org/infra/go/auth"
	"go.skia.org/infra/go/buildbucket"
	"go.skia.org/infra/go/common"
)

var (
	id      = flag.String("id", "", "ID of the build to retrieve.")
	workdir = flag.String("workdir", "workdir", "Working directory to use.")
)

func main() {
	defer common.LogPanic()
	common.Init()

	if *id == "" {
		glog.Fatal("ID is required.")
	}

	// Initialize the BuildBucket client.
	c, err := auth.NewClient(true, path.Join(*workdir, "oauth_token_cache"), buildbucket.DEFAULT_SCOPES...)
	if err != nil {
		glog.Fatal(err)
	}
	bb := buildbucket.NewClient(c)

	// Retrieve the build.
	build, err := bb.GetBuild(*id)
	if err != nil {
		glog.Fatal(err)
	}

	// Pretty print the build.
	b, err := json.Marshal(build)
	if err != nil {
		glog.Fatal(err)
	}
	var out bytes.Buffer
	if err := json.Indent(&out, b, "", "\t"); err != nil {
		glog.Fatal(err)
	}
	glog.Infof("Build: %s\n%s", build.Url, out.String())
}

Make get_build print nice(r) JSON output


package main

import (
	"flag"
	"github.com/MaximeD/gost/conf"
	"github.com/MaximeD/gost/gist"
)

var baseUrl string = "https://api.github.com/"

// get command line arguments
var gistDescriptionFlag = flag.String("description", "", "Description of the gist")
var gistPrivateFlag = flag.Bool("private", false, "Tells if the gist is private")
var listGistsFlag = flag.String("list", "", "List gists for a user")

func init() {
	flag.StringVar(gistDescriptionFlag, "d", "", "description")
	flag.BoolVar(gistPrivateFlag, "p", false, "private")
	flag.StringVar(listGistsFlag, "l", "", "list")
}

func main() {
	flag.Parse()
	isPublic := !*gistPrivateFlag

	if *listGistsFlag != "" {
		username := *listGistsFlag
		url := baseUrl + "users/" + username + "/gists"
		Gist.List(url)
	} else {
		token := Configuration.GetToken()
		filesName := flag.Args()
		Gist.Post(baseUrl, token, isPublic, filesName, *gistDescriptionFlag)
	}
}

package main

import (
	"flag"
	"fmt"
	"github.com/MaximeD/gost/conf"
	"github.com/MaximeD/gost/gist"
	"os"
)

var baseUrl string = "https://api.github.com/"

// get command line arguments
var gistDescriptionFlag = flag.String("description", "", "Description of the gist")
var gistPrivateFlag = flag.Bool("private", false, "Set gist to private")
var listGistsFlag = flag.String("list", "", "List gists for a user")

func init() {
	flag.StringVar(gistDescriptionFlag, "d", "", "Description of the gist")
	flag.BoolVar(gistPrivateFlag, "p", false, "Set gist to private")
	flag.StringVar(listGistsFlag, "l", "", "List gists for a user")
}

func main() {
	flag.Parse()
	isPublic := !*gistPrivateFlag

	// if nothing was given write message
	if (flag.NFlag() == 0) && (len(flag.Args()) == 0) {
		fmt.Println("No arguments or files given!")
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
		os.Exit(2)
	}

	if *listGistsFlag != "" {
		username := *listGistsFlag
		url := baseUrl + "users/" + username + "/gists"
		Gist.List(url)
	} else {
		filesName := flag.Args()
		if len(filesName) == 0 {
			fmt.Println("No files given!")
			os.Exit(2)
		}
		token := Configuration.GetToken()
		Gist.Post(baseUrl, token, isPublic, filesName, *gistDescriptionFlag)
	}
}

ADD usage informations on command line


package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"github.com/gorilla/handlers"
)

const VERSION = "0.1.0"

var clientDir string

func init() {
	clientEnv := os.Getenv("CLIENT")
	flag.StringVar(&clientDir, "client", clientEnv, "the directory where the client data is stored")
}

func main() {
	flag.Parse()
	fmt.Printf("resolutionizerd %s starting...\n", VERSION)
	fmt.Printf("listening on port %s\n", os.Getenv("PORT"))

	if clientDir == "" {
		clientDir = os.Getenv("CLIENT")
	}

	fmt.Printf("client root: %s\n", clientDir)

	if _, err := os.Stat(clientDir); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	http.Handle("/", handlers.CombinedLoggingHandler(os.Stdout, http.FileServer(http.Dir(clientDir))))

	if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

package main

import (
	"flag"
	"fmt"
	"io"
	"net/http"
	"os"
)

const VERSION = "0.1.0"

var clientDir string

func init() {
	clientEnv := os.Getenv("CLIENT")
	flag.StringVar(&clientDir, "client", clientEnv, "the directory where the client data is stored")
}

func main() {
	flag.Parse()
	fmt.Printf("resolutionizerd %s starting...\n", VERSION)
	fmt.Printf("listening on port %s\n", os.Getenv("PORT"))

	if clientDir == "" {
		clientDir = os.Getenv("CLIENT")
	}

	fmt.Printf("client root: %s\n", clientDir)

	if _, err := os.Stat(clientDir); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	http.Handle("/", LoggingHandler(os.Stdout, http.FileServer(http.Dir(clientDir))))

	if err := http.ListenAndServe(":"+os.Getenv("PORT"), nil); err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
}

type loggingHandler struct {
	writer  io.Writer
	handler http.Handler
}

func (h loggingHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	fmt.Fprintf(h.writer, "%s %s %s", r.Method, r.RequestURI, r.Header.Get("User-Agent"))
	h.handler.ServeHTTP(w, r)
}

func LoggingHandler(w io.Writer, h http.Handler) http.Handler {
	return loggingHandler{w, h}
}

Use a custom logging handler.


package main

import (
	"flag"

	"github.com/litl/galaxy/log"
)

var (
	// Location of the default config.
	// This will not be overwritten by shuttle.
	defaultConfig string

	// Location of the live config which is updated on every state change.
	// The default config is loaded if this file does not exist.
	stateConfig string

	// Listen address for the http server.
	listenAddr string

	// Debug logging
	debug bool
)

func init() {
	flag.StringVar(&listenAddr, "http", "127.0.0.1:9090", "http server address")
	flag.StringVar(&defaultConfig, "config", "", "default config file")
	flag.StringVar(&stateConfig, "state", "", "updated config which reflects the internal state")
	flag.BoolVar(&debug, "debug", false, "verbose logging")

	flag.Parse()
}

func main() {
	if debug {
		log.DefaultLogger.Level = log.DEBUG
	}

	loadConfig()
	startHTTPServer()
}

package main

import (
	"flag"

	"github.com/litl/galaxy/log"
)

var (
	// Location of the default config.
	// This will not be overwritten by shuttle.
	defaultConfig string

	// Location of the live config which is updated on every state change.
	// The default config is loaded if this file does not exist.
	stateConfig string

	// Listen address for the http server.
	listenAddr string

	// Debug logging
	debug bool

	// version flags
	version      bool
	buildVersion string
)

func init() {
	flag.StringVar(&listenAddr, "http", "127.0.0.1:9090", "http server address")
	flag.StringVar(&defaultConfig, "config", "", "default config file")
	flag.StringVar(&stateConfig, "state", "", "updated config which reflects the internal state")
	flag.BoolVar(&debug, "debug", false, "verbose logging")
	flag.BoolVar(&version, "v", false, "display version")

	flag.Parse()
}

func main() {
	if debug {
		log.DefaultLogger.Level = log.DEBUG
	}

	if version {
		println(buildVersion)
		return
	}

	loadConfig()
	startHTTPServer()
}

Add a build version to executables


package main

import (
	"os"
	"os/signal"
	"warcluster/config"
	"warcluster/entities/db"
	"warcluster/server"
)

var cfg config.Config

func main() {
	go final()
	defer final()

	cfg.Load("config/config.gcfg")
	db.Connect(cfg.Database.Network, cfg.Database.Host, cfg.Database.Port)
	server.Start(cfg.Server.Host, cfg.Server.Port)
}

func final() {
	sigtermchan := make(chan os.Signal, 1)
	signal.Notify(sigtermchan, os.Interrupt)
	<-sigtermchan

	db.Finalize()
	server.Stop()
	os.Exit(0)
}

package main

import (
	"os"
	"os/signal"
	"warcluster/config"
	"warcluster/entities/db"
	"warcluster/server"
	"syscall"
)

var cfg config.Config

func main() {
	go final()

	cfg.Load("config/config.gcfg")
	db.Connect(cfg.Database.Network, cfg.Database.Host, cfg.Database.Port)
	server.Start(cfg.Server.Host, cfg.Server.Port)
}

func final() {
	exit_chan := make(chan os.Signal, 1)
	signal.Notify(exit_chan, syscall.SIGINT)
	signal.Notify(exit_chan, syscall.SIGKILL)
	signal.Notify(exit_chan, syscall.SIGTERM)
	<-exit_chan

	db.Finalize()
	server.Stop()
	os.Exit(0)
}

Exit safely from most of the signals


package main

import (
	"fmt"
	"net/http"
	"os"
	"runtime"

	"bitbucket.org/tebeka/nrsc"
	"github.com/alexcesaro/log"
	"github.com/alexcesaro/log/golog"
)

var logger *golog.Logger

var storage storageHandler

func requestLog(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		logger.Infof("%s %s", r.Method, r.URL)
		handler.ServeHTTP(rw, r)
	})
}

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	logger = golog.New(os.Stdout, log.Info)

	var err error
	if storage, err = newMongoHandler(); err != nil {
		os.Exit(1)
	}
}

func main() {
	// Static assets
	nrsc.Handle("/static/")

	// RESTful API
	http.Handle("/", newRouter())

	// Banner and launcher
	fmt.Println("\n\t:-:-: perfkeeper :-:-:\t\t\tserving http://0.0.0.0:8080/\n")
	logger.Critical(http.ListenAndServe("0.0.0.0:8080", requestLog(http.DefaultServeMux)))
}

package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"runtime"

	"bitbucket.org/tebeka/nrsc"
	"github.com/alexcesaro/log"
	"github.com/alexcesaro/log/golog"
)

var logger *golog.Logger

var address *string

var storage storageHandler

func requestLog(handler http.Handler) http.Handler {
	return http.HandlerFunc(func(rw http.ResponseWriter, r *http.Request) {
		logger.Infof("%s %s", r.Method, r.URL)
		handler.ServeHTTP(rw, r)
	})
}

func init() {
	runtime.GOMAXPROCS(runtime.NumCPU())

	address = flag.String("address", "127.0.0.1:8080", "serve requests to this host[:port]")
	flag.Parse()

	logger = golog.New(os.Stdout, log.Info)

	var err error
	if storage, err = newMongoHandler(); err != nil {
		os.Exit(1)
	}
}

func main() {
	// Static assets
	nrsc.Handle("/static/")

	// RESTful API
	http.Handle("/", newRouter())

	// Banner and launcher
	banner := fmt.Sprintf("\n\t:-:-: perfkeeper :-:-:\t\t\tserving http://%s/\n", *address)
	fmt.Println(banner)
	logger.Critical(http.ListenAndServe(*address, requestLog(http.DefaultServeMux)))
}

Allow to specify custom host and port


package multierror

// Append is a helper function that will append more errors
// onto an Error in order to create a larger multi-error.
//
// If err is not a multierror.Error, then it will be turned into
// one. If any of the errs are multierr.Error, they will be flattened
// one level into err.
func Append(err error, errs ...error) *Error {
	if err == nil {
		err = new(Error)
	}

	switch err := err.(type) {
	case *Error:
		if err == nil {
			err = new(Error)
		}

		err.Errors = append(err.Errors, errs...)
		return err
	default:
		newErrs := make([]error, len(errs)+1)
		newErrs[0] = err
		copy(newErrs[1:], errs)
		return &Error{
			Errors: newErrs,
		}
	}
}

package multierror

// Append is a helper function that will append more errors
// onto an Error in order to create a larger multi-error.
//
// If err is not a multierror.Error, then it will be turned into
// one. If any of the errs are multierr.Error, they will be flattened
// one level into err.
func Append(err error, errs ...error) *Error {
	if err == nil {
		err = new(Error)
	}

	switch err := err.(type) {
	case *Error:
		err.Errors = append(err.Errors, errs...)
		return err
	default:
		newErrs := make([]error, len(errs)+1)
		newErrs[0] = err
		copy(newErrs[1:], errs)
		return &Error{
			Errors: newErrs,
		}
	}
}

Remove unneeded nil check in Append


package main

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

  "github.com/gmcnaughton/gofindhdr/findhdr"
)

func main() {
  inpath := "/Users/gmcnaughton/Pictures/Photos Library.photoslibrary/Masters/2017/02"
  // inpath := "./test"
  outpath := "./out"
  optlink := true

  // Create output folder
  _ = os.Mkdir(outpath, 0755)

  count := 0

  findhdr.Find(inpath, func(hdr *findhdr.Hdr) {
    for _, image := range hdr.Images() {
      count++

      link := filepath.Join(outpath, image.Info.Name())

      if optlink {
        fmt.Println("Linking", link)
        err := os.Link(image.Path, link)
        if os.IsExist(err) {
          fmt.Printf("Skipping %s (file exists)\n", link)
        } else if err != nil {
          fmt.Printf("Error linking %s\n", link)
          fmt.Println(err)
        }
      } else {
        fmt.Println(hdr)
      }
    }
    fmt.Println()
  })

  fmt.Printf("Found %d hdrs.\n", count)
}

package main

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

  "github.com/gmcnaughton/gofindhdr/findhdr"
)

func main() {
  // inpath := "/Users/gmcnaughton/Pictures/Photos Library.photoslibrary/Masters/2017/02"
  inpath := "./test"
  outpath := "./out"
  optlink := false

  // Create output folder
  if optlink {
    err := os.Mkdir(outpath, 0755)
    if err != nil && !os.IsExist(err) {
      fmt.Println("Error creating out directory", err)
    }
  }

  count := 0

  findhdr.Find(inpath, func(hdr *findhdr.Hdr) {
    count++

    if optlink {
      for _, image := range hdr.Images() {
        link := filepath.Join(outpath, image.Info.Name())
        fmt.Println("Linking", link)
        err := os.Link(image.Path, link)
        if os.IsExist(err) {
          fmt.Println("Skipping", err)
        } else if err != nil {
          fmt.Println("Error linking", err)
        }
      }
    } else {
      fmt.Println(hdr)
    }
  })

  fmt.Printf("Found %d hdrs.\n", count)
}

Support preview mode (don't link, just print matches found)


package main

import (
	log "github.com/Sirupsen/logrus"
	"github.com/helphone/importer/job"
	"github.com/robfig/cron"
)

func refresh() {
	job.PullRepo()
	job.Refresh()
}

func main() {
	log.Info("Importer stared")

	c := cron.New()
	c.AddFunc("@every 1m", refresh)
	c.Start()

	refresh()

	select {}
}

package main

import (
	log "github.com/Sirupsen/logrus"
	"github.com/helphone/importer/job"
	"github.com/robfig/cron"
)

func refresh() {
	job.PullRepo()
	job.Refresh()
}

func main() {
	log.Info("Importer stared")

	c := cron.New()
	c.AddFunc("@every 1h", refresh)
	c.Start()

	refresh()

	select {}
}

Stop refreshing every minutes to hours


package main

import (
	"flag"
	"fmt"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)

func main() {
	var apply bool
	var dryrun bool

	flag.BoolVar(&apply, "apply", false, "apply to CloudWatch Events")
	flag.BoolVar(&dryrun, "dry-run", false, "dry-run")
	flag.Parse()

	fmt.Println(apply)
	fmt.Println(dryrun)

	sess := session.Must(session.NewSessionWithOptions(session.Options{
		SharedConfigState: session.SharedConfigEnable,
	}))

	cwe := cloudwatchevents.New(sess)
	result, err := cwe.ListRules(nil)

	if err != nil {
		fmt.Println("Error", err)

	} else {
		fmt.Println("Success")
		fmt.Println(result)
	}
}

package main

import (
	"flag"
	"fmt"

	"github.com/aws/aws-sdk-go/aws/session"
	"github.com/aws/aws-sdk-go/service/cloudwatchevents"
)

func main() {
	var apply bool
	var dryrun bool

	flag.BoolVar(&apply, "apply", false, "apply to CloudWatch Events")
	flag.BoolVar(&dryrun, "dry-run", false, "dry-run")
	flag.Parse()

	fmt.Println(apply)
	fmt.Println(dryrun)

	sess, err := session.NewSession(nil)
	if err != nil {
		fmt.Errorf("Error %v", err)
	}

	cwe := cloudwatchevents.New(sess)
	result, err := cwe.ListRules(nil)

	if err != nil {
		fmt.Println("Error", err)

	} else {
		fmt.Println("Success")
		fmt.Println(result)
	}
}

Create session (catch the error)


package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
)

func main() {
	// Read in the config file
	confText, err := ioutil.ReadFile("gologgen.conf")
	if err != nil {
		return
	}

	// Unmarshal the JSON into a map
	var cd map[string]string
	err2 := json.Unmarshal(confText, &cd)
	if err2 != nil {
		return
	}

	// Test post, please ignore
	var tester = []byte("Test post, please ignore")
	//c := bufio.Reader.ReadString(tester)
	//copy(c, tester)
	resp, err := http.Post(cd["httpLoc"], "text/plain", bytes.NewBuffer(tester))
	defer resp.Body.Close()
	fmt.Println(resp)
}

package main

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
)

func main() {
	// Read in the config file
	confText, err := ioutil.ReadFile("gologgen.conf")
	if err != nil {
		return
	}

	// Unmarshal the JSON into a map
	var cd map[string]string
	err2 := json.Unmarshal(confText, &cd)
	if err2 != nil {
		return
	}

	// Test post, please ignore
	var tester = []byte("Test post, please ignore")
	resp, err := http.Post(cd["httpLoc"], "text/plain", bytes.NewBuffer(tester))
	defer resp.Body.Close()
	log.Print(resp)
}

Use the logger instead of printing to console


package main

import (
	"log"
	"github.com/gorilla/websocket"
	"github.com/markbates/goth"
)

// Message emitted by a client and broadcasted to the channel
type Message struct {
	User string `json:"user"`
	Content string `json:"content"`
}

// Client is a middleman between the WebSocket connection and the Hub
type Client struct {
	hub *Hub
	conn *websocket.Conn
	send chan Message
	user goth.User
}

// read pumps messages from the WebSocket to the Hub
func (c *Client) read() {
	defer func() {
		c.hub.unregister <- c
		c.conn.Close()
	}()

	for {
		var msg Message
		err := c.conn.ReadJSON(&msg)
		if err != nil {
			log.Printf("Error: %v", err)
			break
		}
		msg.User = c.user.Name
		c.hub.broadcast <- msg
	}
}

// write pumps messages from the Hub to the WebSocket
func (c *Client) write() {
	defer func() {
		c.conn.Close()
	}()

	for {
		msg := <- c.send
		err := c.conn.WriteJSON(msg)
		if err != nil {
			log.Printf("Error: %v", err)
			return
		}
	}
}

package main

import (
	"log"
	"github.com/gorilla/websocket"
	"github.com/markbates/goth"
)

// Message emitted by a client and broadcasted to the channel
type Message struct {
	UserID string `json:"id"`
	UserName string `json:"user"`
	UserAvatar string `json:"avatar"`
	Content string `json:"content"`
}

// Client is a middleman between the WebSocket connection and the Hub
type Client struct {
	hub *Hub
	conn *websocket.Conn
	send chan Message
	user goth.User
}

// read pumps messages from the WebSocket to the Hub
func (c *Client) read() {
	defer func() {
		c.hub.unregister <- c
		c.conn.Close()
	}()

	for {
		var msg Message
		err := c.conn.ReadJSON(&msg)
		if err != nil {
			log.Printf("Error: %v", err)
			break
		}

		msg.UserID = c.user.UserID
		msg.UserName = c.user.Name
		msg.UserAvatar = c.user.AvatarURL

		c.hub.broadcast <- msg
	}
}

// write pumps messages from the Hub to the WebSocket
func (c *Client) write() {
	defer func() {
		c.conn.Close()
	}()

	for {
		msg := <- c.send
		err := c.conn.WriteJSON(msg)
		if err != nil {
			log.Printf("Error: %v", err)
			return
		}
	}
}

Send ID and avatar URL with each Message


package executor

func (e *UniversalExecutor) LaunchSyslogServer(ctx *ExecutorContext) (*SyslogServerState, error) {
	return nil, nil
}

package executor

import (
	"os/exec"
	"time"

	"golang.org/x/sys/windows"
)

func (e *UniversalExecutor) LaunchSyslogServer(ctx *ExecutorContext) (*SyslogServerState, error) {
	return nil, nil
}

func (e *UniversalExecutor) wait() {
	defer close(e.processExited)
	err := e.cmd.Wait()
	ic := &cstructs.IsolationConfig{Cgroup: e.groups, CgroupPaths: e.cgPaths}
	if err == nil {
		e.exitState = &ProcessState{Pid: 0, ExitCode: 0, IsolationConfig: ic, Time: time.Now()}
		return
	}
	exitCode := 1
	var signal int
	if exitErr, ok := err.(*exec.ExitError); ok {
		if status, ok := exitErr.Sys().(windows.WaitStatus); ok {
			exitCode = status.ExitStatus()
			if status.Signaled() {
				signal = int(status.Signal())
				exitCode = 128 + signal
			}
		}
	} else {
		e.logger.Printf("[DEBUG] executor: unexpected Wait() error type: %v", err)
	}

	e.exitState = &ProcessState{Pid: 0, ExitCode: exitCode, Signal: signal, IsolationConfig: ic, Time: time.Now()}
}

Implement a Windows-specific UniversalExecutor `wait()`


package git

import (
	"errors"
	"regexp"
)

type GitRemote struct {
	Name string
	URL  string
}

func Remotes() ([]GitRemote, error) {
	r := regexp.MustCompile("(.+)\t(.+github.com.+) \\(push\\)")
	output, err := execGitCmd("remote", "-v")
	if err != nil {
		return nil, errors.New("Can't load git remote")
	}

	remotes := make([]GitRemote, 0)
	for _, o := range output {
		if r.MatchString(o) {
			match := r.FindStringSubmatch(o)
			remotes = append(remotes, GitRemote{Name: match[1], URL: match[2]})
		}
	}

	if len(remotes) == 0 {
		return nil, errors.New("Can't find git remote (push)")
	}

	return remotes, nil
}

func OriginRemote() (*GitRemote, error) {
	remotes, err := Remotes()
	if err != nil {
		return nil, err
	}

	for _, r := range remotes {
		if r.Name == "origin" {
			return &r, nil
		}
	}

	return nil, errors.New("Can't find git remote orign (push)")
}

package git

import (
	"errors"
	"regexp"
)

type GitRemote struct {
	Name string
	URL  string
}

func Remotes() ([]*GitRemote, error) {
	r := regexp.MustCompile("(.+)\t(.+github.com.+) \\(push\\)")
	output, err := execGitCmd("remote", "-v")
	if err != nil {
		return nil, errors.New("Can't load git remote")
	}

	remotes := make([]*GitRemote, 0)
	for _, o := range output {
		if r.MatchString(o) {
			match := r.FindStringSubmatch(o)
			remotes = append(remotes, &GitRemote{Name: match[1], URL: match[2]})
		}
	}

	if len(remotes) == 0 {
		return nil, errors.New("Can't find git remote (push)")
	}

	return remotes, nil
}

func OriginRemote() (*GitRemote, error) {
	remotes, err := Remotes()
	if err != nil {
		return nil, err
	}

	for _, r := range remotes {
		if r.Name == "origin" {
			return r, nil
		}
	}

	return nil, errors.New("Can't find git remote orign (push)")
}

Use pointers to be more efficient


package main

import "testing"

func TestDockerize(*testing.T) {
	const expected = "/c/users/Foo"

	var dockerized string
	dockerized, err := dockerize(`C:\users\Foo`)

	if err != nil {
		t.Error("Unexpected error: ", err)
	}

	if dockerized != expected {
		t.Error("Expected '", expected, "', got '", dockerized, "'")
	}
}

package main

import "testing"

func TestDockerize(t *testing.T) {
	const expected = "/c/users/Foo"

	var dockerized string
	dockerized, err := dockerize(`C:\users\Foo`)

	if err != nil {
		t.Error("Unexpected error: ", err)
	}

	if dockerized != expected {
		t.Error("Expected '", expected, "', got '", dockerized, "'")
	}
}

Fix Windows Docker path test (missing param)


package inspect

import (
	"fmt"
	"testing"

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

func TestFormat(t *testing.T) {
	m := []typeStats{{
		Name:  "msg",
		Sum:   1,
		Count: 2,
	}}
	info := OutputFormat{
		Meta: &MetadataInfo{
			ID:      "one",
			Size:    2,
			Index:   3,
			Term:    4,
			Version: 1,
		},
		Stats:     m,
		TotalSize: 1,
	}

	formatters := map[string]Formatter{
		"pretty": newPrettyFormatter(),
		// the JSON formatter ignores the showMeta
		"json": newJSONFormatter(),
	}

	for fmtName, formatter := range formatters {
		t.Run(fmtName, func(t *testing.T) {
			actual, err := formatter.Format(&info)
			require.NoError(t, err)

			gName := fmt.Sprintf("%s", fmtName)

			expected := golden(t, gName, actual)
			require.Equal(t, expected, actual)
		})
	}
}

package inspect

import (
	"fmt"
	"testing"

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

func TestFormat(t *testing.T) {
	m := []typeStats{{
		Name:  "msg",
		Sum:   1,
		Count: 2,
	}}
	mkv := []typeStats{{
		Name:  "msgKV",
		Sum:   1,
		Count: 2,
	}}
	info := OutputFormat{
		Meta: &MetadataInfo{
			ID:      "one",
			Size:    2,
			Index:   3,
			Term:    4,
			Version: 1,
		},
		Stats:       m,
		StatsKV:     mkv,
		TotalSize:   1,
		TotalSizeKV: 1,
	}
	detailed := false

	formatters := map[string]Formatter{
		"pretty": newPrettyFormatter(),
		// the JSON formatter ignores the showMeta
		"json": newJSONFormatter(),
	}

	for fmtName, formatter := range formatters {
		t.Run(fmtName, func(t *testing.T) {
			actual, err := formatter.Format(&info, detailed)
			require.NoError(t, err)

			gName := fmt.Sprintf("%s", fmtName)

			expected := golden(t, gName, actual)
			require.Equal(t, expected, actual)
		})
	}
}

Update snapshot inspect formatter test


package graph

import (
//	"os"
)

type Invitation struct {
	Name string
	ID   string
	// rsvp_status, not_replied, attending, unsure or declined
	RSVPStatus string
}
/*
func GetInvitations(URL string) (invs []Invitation, err os.Error) {
	// TODO: Check for valid ID
	b, err := fetchPage(URL)
	m, err := getJsonMap(b)
	data, ok := m["data"].([]interface{})
	if !ok {
		err = os.NewError("GetInvitations: data could not be found.")
		return
	}
	for i, v := range data {
		invs[i].parseData(v.(map[string]interface{}))
	}
	return
}
*/
func (i *Invitation) parseData(value map[string]interface{}) {
	i.Name = value["name"].(string)
	i.ID = value["id"].(string)
	i.RSVPStatus = value["rsvp_status"].(string)
	return
}

package graph

import (
	"os"
)

type Invitation struct {
	Name string
	ID   string
	// rsvp_status, not_replied, attending, unsure or declined
	RSVPStatus string
}

func getInvitations(url string) (invs []Invitation, err os.Error) {
	data, err := getData(url)
	if err != nil {
		return
	}
	for i, v := range data {
		invs[i] = parseInvitation(v.(map[string]interface{}))
	}
	return
}

func parseInvitation(value map[string]interface{}) (invi Invitation) {
	invi.Name = value["name"].(string)
	invi.ID = value["id"].(string)
	invi.RSVPStatus = value["rsvp_status"].(string)
	return
}

Change Invitation to the new OO design.


package handler

import (
	"github.com/materials-commons/config/cfg"
)

type loaderHandler struct {
	handler cfg.Handler
	loader  cfg.Loader
}

// Loader returns a handler that reads the keys in from a loader.
func Loader(loader cfg.Loader) cfg.Handler {
	return &loaderHandler{
		handler: Map(),
		loader:  loader,
	}
}

// Init loads the keys by calling the loader.
func (h *loaderHandler) Init() error {
	m := h.handler.(*mapHandler)
	if err := h.loader.Load(&m.values); err != nil {
		return err
	}
	return nil
}

// Get retrieves keys loaded from the loader.
func (h *loaderHandler) Get(key string, args ...interface{}) (interface{}, error) {
	return h.handler.Get(key, args...)
}

// Set sets the value of keys. You can create new keys, or modify existing ones.
// Values are not persisted across runs.
func (h *loaderHandler) Set(key string, value interface{}, args ...interface{}) error {
	return h.handler.Set(key, value, args...)
}

// Args returns false. This handler doesn't accept additional arguments.
func (h *loaderHandler) Args() bool {
	return false
}

package handler

import (
	"github.com/materials-commons/config/cfg"
)

type loaderHandler struct {
	handler cfg.Handler
	loader  cfg.Loader
}

// Loader returns a handler that reads the keys in from a loader.
func Loader(loader cfg.Loader) cfg.Handler {
	return &loaderHandler{
		loader: loader,
	}
}

// Init loads the keys by calling the loader.
func (h *loaderHandler) Init() error {
	var m = make(map[string]interface{})
	if err := h.loader.Load(&m); err != nil {
		return err
	}
	h.handler = MapUse(m)
	return h.handler.Init()
}

// Get retrieves keys loaded from the loader.
func (h *loaderHandler) Get(key string, args ...interface{}) (interface{}, error) {
	return h.handler.Get(key, args...)
}

// Set sets the value of keys. You can create new keys, or modify existing ones.
// Values are not persisted across runs.
func (h *loaderHandler) Set(key string, value interface{}, args ...interface{}) error {
	return h.handler.Set(key, value, args...)
}

// Args returns false. This handler doesn't accept additional arguments.
func (h *loaderHandler) Args() bool {
	return false
}

Update the Loader handler to use the new MapUse handler.


package medtronic

import (
	"fmt"
	"log"
)

const (
	maxBolus = 25000 // milliUnits
)

// Bolus delivers the given amount of insulin as a bolus.
func (pump *Pump) Bolus(amount Insulin) {
	if amount < 0 {
		pump.SetError(fmt.Errorf("bolus amount (%d) is negative", amount))
	}
	if amount > maxBolus {
		pump.SetError(fmt.Errorf("bolus amount (%d) is too large", amount))
	}
	family := pump.Family()
	d := milliUnitsPerStroke(family)
	strokes := amount / d
	actual := strokes * d
	if actual != amount {
		log.Printf("rounding bolus from %v to %v", amount, actual)
	}
	if family <= 22 {
		pump.Execute(bolus, uint8(strokes))
	} else {
		pump.Execute(bolus, marshalUint16(uint16(strokes))...)
	}
}

package medtronic

import (
	"fmt"
	"log"
)

const (
	maxBolus = 25000 // milliUnits
)

// Bolus delivers the given amount of insulin as a bolus.
func (pump *Pump) Bolus(amount Insulin) {
	if amount < 0 {
		pump.SetError(fmt.Errorf("bolus amount (%d) is negative", amount))
	}
	if amount > maxBolus {
		pump.SetError(fmt.Errorf("bolus amount (%d) is too large", amount))
	}
	if pump.Error() != nil {
		return
	}
	family := pump.Family()
	d := milliUnitsPerStroke(family)
	strokes := amount / d
	actual := strokes * d
	if actual != amount {
		log.Printf("rounding bolus from %v to %v", amount, actual)
	}
	if family <= 22 {
		pump.Execute(bolus, uint8(strokes))
	} else {
		pump.Execute(bolus, marshalUint16(uint16(strokes))...)
	}
}

Return early if an error occurred


package termite

import (
	"fmt"
	"http"
	"sync"
	"sync/atomic"
	"time"
)

type masterStats struct {
	counterMutex sync.Mutex
	received     *MultiResolutionCounter

	running int32
}

func newMasterStats() *masterStats {
	return &masterStats{
		received: NewMultiResolutionCounter(1, time.Seconds(), []int{60, 10}),
	}
}

func (me *masterStats) MarkReceive() {
	me.counterMutex.Lock()
	defer me.counterMutex.Unlock()
	me.received.Add(time.Seconds(), 1)
	atomic.AddInt32(&me.running, 1)
}

func (me *masterStats) MarkReturn() {
	atomic.AddInt32(&me.running, -1)
}

func (me *masterStats) writeHttp(w http.ResponseWriter) {
	me.counterMutex.Lock()
	defer me.counterMutex.Unlock()
	me.received.Add(time.Seconds(), 0)
	fmt.Fprintf(w, "
Received (sec/min/10min): %v", me.received.Read())

	r := atomic.AddInt32(&me.running, 0)
	fmt.Fprintf(w, "
Jobs in receive status: %d "+
		"(measure the maximum parallelism of the job", r)
}

package termite

import (
	"fmt"
	"http"
	"sync"
	"sync/atomic"
	"time"
)

type masterStats struct {
	counterMutex sync.Mutex
	received     *MultiResolutionCounter

	running int32
}

func newMasterStats() *masterStats {
	return &masterStats{
		received: NewMultiResolutionCounter(1, time.Seconds(), []int{60, 10}),
	}
}

func (me *masterStats) MarkReceive() {
	me.counterMutex.Lock()
	defer me.counterMutex.Unlock()
	me.received.Add(time.Seconds(), 1)
	atomic.AddInt32(&me.running, 1)
}

func (me *masterStats) MarkReturn() {
	atomic.AddInt32(&me.running, -1)
}

func (me *masterStats) writeHttp(w http.ResponseWriter) {
	me.counterMutex.Lock()
	defer me.counterMutex.Unlock()
	me.received.Add(time.Seconds(), 0)
	fmt.Fprintf(w, "
Received (sec/min/10min): %v", me.received.Read())

	r := atomic.AddInt32(&me.running, 0)
	fmt.Fprintf(w, "
Jobs in receive status: %d "+
		"(parallelism of the job)", r)
}

Fix typo in HTML page.


package openzwave

import "fmt"

// A logger interface. Modelled on github.com/juju/loggo so that can be used substituted by default.
type Logger interface {
	// Log an info message.
	Infof(message string, args ...interface{})
	// Log a warning message.
	Warningf(message string, args ...interface{})
	// Log an error message.
	Errorf(message string, args ...interface{})
	// Log a debug message.
	Debugf(message string, args ...interface{})
	// Log a trace message.
	Tracef(message string, args ...interface{})
}

type defaultLogger struct {
}

func (defaultLogger) Infof(message string, args ...interface{}) {
	fmt.Printf(message, args...)
}

func (defaultLogger) Warningf(message string, args ...interface{}) {
	fmt.Printf(message, args...)
}

func (defaultLogger) Errorf(message string, args ...interface{}) {
	fmt.Printf(message, args...)
}

func (defaultLogger) Debugf(message string, args ...interface{}) {
	fmt.Printf(message, args...)
}

func (defaultLogger) Tracef(message string, args ...interface{}) {
	fmt.Printf(message, args...)
}

package openzwave

import "log"

// A logger interface. Modelled on github.com/juju/loggo so that can be used substituted by default.
type Logger interface {
	// Log an info message.
	Infof(message string, args ...interface{})
	// Log a warning message.
	Warningf(message string, args ...interface{})
	// Log an error message.
	Errorf(message string, args ...interface{})
	// Log a debug message.
	Debugf(message string, args ...interface{})
	// Log a trace message.
	Tracef(message string, args ...interface{})
}

type defaultLogger struct {
}

func (defaultLogger) Infof(message string, args ...interface{}) {
	log.Printf(message, args...)
}

func (defaultLogger) Warningf(message string, args ...interface{}) {
	log.Printf(message, args...)
}

func (defaultLogger) Errorf(message string, args ...interface{}) {
	log.Printf(message, args...)
}

func (defaultLogger) Debugf(message string, args ...interface{}) {
	log.Printf(message, args...)
}

func (defaultLogger) Tracef(message string, args ...interface{}) {
	log.Printf(message, args...)
}

Use log, rather than printf.


package testutil

import "sync/atomic"

var nextPort uint32 = 40000

// UniquePort generates a likely unique port, so that multiple servers can run
// concurrently. Note that it does not actually check that the port is free,
// but uses atomics and a fairly highly port range to maximize the likelihood
// that the port is available.
func UniquePort() uint16 {
	port := uint16(atomic.AddUint32(&nextPort, 1))

	if port == 0 {
		panic("ran out of ports!")
	}

	return port
}

package testutil

import "sync/atomic"

var nextPort uint32 = 41300

// UniquePort generates a likely unique port, so that multiple servers can run
// concurrently. Note that it does not actually check that the port is free,
// but uses atomics and a fairly highly port range to maximize the likelihood
// that the port is available.
func UniquePort() uint16 {
	port := uint16(atomic.AddUint32(&nextPort, 1))

	if port == 0 {
		panic("ran out of ports!")
	}

	return port
}

Revert "Revert "Up the test port range""


package main

import (
	"github.com/nightlyone/lockfile"
	"os"
	"path/filepath"
)

// Get name of lock file, which is derived from the monitoring event name
func getLockfileName() string {
	return filepath.Join(os.TempDir(), monitoringEvent, monitoringEvent+".lock")
}

// Create a new lock file
func createLock() (lockfile.Lockfile, error) {
	filename := getLockfileName()
	os.Mkdir(filepath.Dir(filename), 0700)
	return lockfile.New(filename)
}

package main

import (
	"github.com/nightlyone/lockfile"
	"os"
	"path/filepath"
)

// Create a new lock file
func createLock() (lockfile.Lockfile, error) {
	filename := filepath.Join(os.TempDir(), "periodicnoise", monitoringEvent, monitoringEvent+".lock")

	if err := os.MkdirAll(filepath.Dir(filename), 0700); err != nil {
		return lockfile.Lockfile(""), err
	}

	return lockfile.New(filename)
}

Add "periodicnoise" to lock filename


package opts

import (
	"fmt"
	"net"
)

// IPOpt holds an IP. It is used to store values from CLI flags.
type IPOpt struct {
	*net.IP
}

// NewIPOpt creates a new IPOpt from a reference net.IP and a
// string representation of an IP. If the string is not a valid
// IP it will fallback to the specified reference.
func NewIPOpt(ref *net.IP, defaultVal string) *IPOpt {
	o := &IPOpt{
		IP: ref,
	}
	o.Set(defaultVal)
	return o
}

// Set sets an IPv4 or IPv6 address from a given string. If the given
// string is not parseable as an IP address it returns an error.
func (o *IPOpt) Set(val string) error {
	ip := net.ParseIP(val)
	if ip == nil {
		return fmt.Errorf("%s is not an ip address", val)
	}
	*o.IP = ip
	return nil
}

// String returns the IP address stored in the IPOpt. If stored IP is a
// nil pointer, it returns an empty string.
func (o *IPOpt) String() string {
	if *o.IP == nil {
		return ""
	}
	return o.IP.String()
}

// Type returns the type of the option
func (o *IPOpt) Type() string {
	return "ip"
}

Convert dockerd to use cobra and pflag


package main

import "github.com/nsf/termbox-go"
import "time"
import "flag"

func main() {
	loops := flag.Int("loops", 0, "number of times to loop (default: infinite)")
	flag.Parse()

	err := termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	event_queue := make(chan termbox.Event)
	go func() {
		for {
			event_queue <- termbox.PollEvent()
		}
	}()

	termbox.SetOutputMode(termbox.Output256)

	loop_index := 0
	draw()

loop:
	for {
		select {
		case ev := <-event_queue:
			if ev.Type == termbox.EventKey && ev.Key == termbox.KeyEsc {
				break loop
			}
		default:
			loop_index++
			if *loops > 0 && (loop_index/9) >= *loops {
				break loop
			}
			draw()
			time.Sleep(75 * time.Millisecond)
		}
	}
}

package main

import "github.com/nsf/termbox-go"
import "time"
import "flag"

func main() {
	loops := flag.Int("loops", 0, "number of times to loop (default: infinite)")
	flag.Parse()

	err := termbox.Init()
	if err != nil {
		panic(err)
	}
	defer termbox.Close()

	event_queue := make(chan termbox.Event)
	go func() {
		for {
			event_queue <- termbox.PollEvent()
		}
	}()

	termbox.SetOutputMode(termbox.Output256)

	loop_index := 0
	draw()

loop:
	for {
		select {
		case ev := <-event_queue:
			if ev.Type == termbox.EventKey && (ev.Key == termbox.KeyEsc || ev.Key == termbox.KeyCtrlC) {
				break loop
			}
		default:
			loop_index++
			if *loops > 0 && (loop_index/9) >= *loops {
				break loop
			}
			draw()
			time.Sleep(75 * time.Millisecond)
		}
	}
}

Add ctrl-c support to quit.


package main

import "fmt"

var (
	name   string = "Чочко"
	age    uint8  = 27
	p_name *string
)

func main() {
	p_name = &name
	fmt.Printf("name е на адрес %p и има стойност %s\n", p_name, name)
	fmt.Printf("age е на адрес %p и има стойност %d\n", &age, age)
}

package main

import "fmt"

var (
	name   string = "Чочко"
	age    uint8  = 27
	pName *string
)

func main() {
	pName = &name
	fmt.Printf("name е на адрес %p и има стойност %s\n", pName, name)
	fmt.Printf("age е на адрес %p и има стойност %d\n", &age, age)
}

Use camel case instead of snake case


package events

import (
	"gpio"
	"time"
)

type EdgeEvent struct {
	BeforeEvent int
	AfterEvent int
	Timestamp time.Time
}

func edgeTrigger(pin gpio.GPIO, eventCh chan EdgeEvent, ctrlCh chan bool) (error) {
	lastState, err := pin.ReadValue()
	if err != nil {
		panic(err) // improve
	}

	for true {
		select {
		case <-ctrlCh:
			return nil
		default:
			newState, err := pin.ReadValue()
			if err != nil {
				panic(err)  // improve
			}

			if newState != lastState {
				lastState = newState
				eventCh <- EdgeEvent{BeforeEvent: lastState,
					AfterEvent: newState,
					Timestamp: time.Now()}
			}
		}
	}
	return nil
}

func StartEdgeTrigger(pin gpio.GPIO) (chan EdgeEvent, chan bool) {
	eventCh := make(chan EdgeEvent) // this should have a buffer
	ctrlCh := make(chan bool)

	go edgeTrigger(pin, eventCh, ctrlCh)

	return eventCh, ctrlCh
}

func StopEdgeTrigger(ctrlCh chan bool) {
	ctrlCh <- true
}

package events

import (
	"gpio"
	"time"
)

type EdgeEvent struct {
	BeforeEvent int
	AfterEvent int
	Timestamp time.Time
}

func edgeTrigger(pin gpio.GPIO, eventCh chan EdgeEvent, ctrlCh chan bool) (error) {
	lastState, err := pin.ReadValue()
	if err != nil {
		panic(err) // improve
	}

	for true {
		select {
		case <-ctrlCh:
			return nil
		default:
			newState, err := pin.ReadValue()
			if err != nil {
				panic(err)  // improve
			}

			if newState != lastState {
				eventCh <- EdgeEvent{BeforeEvent: lastState,
					AfterEvent: newState,
					Timestamp: time.Now()}
				lastState = newState
			}
		}
	}
	return nil
}

func StartEdgeTrigger(pin gpio.GPIO) (chan EdgeEvent, chan bool) {
	eventCh := make(chan EdgeEvent) // this should have a buffer
	ctrlCh := make(chan bool)

	go edgeTrigger(pin, eventCh, ctrlCh)

	return eventCh, ctrlCh
}

func StopEdgeTrigger(ctrlCh chan bool) {
	ctrlCh <- true
}

Correct minor snafu * SNAFU: Situation Normal. All Fucked Up.


package telegraph

import (
	gojson "encoding/json"
	"errors"
	"fmt"
	"net/url"

	json "github.com/pquerna/ffjson/ffjson"
	http "github.com/valyala/fasthttp"
)

// Response represents a response from the Telegram API with the result stored raw. If ok equals true,
// the request was successful, and the result of the query can be found in the result field. In case of
// an unsuccessful request, ok equals false, and the error is explained in the error field (e.g.
// SHORT_NAME_REQUIRED).
type Response struct {
	Ok     bool               `json:"ok"`
	Error  string             `json:"error"`
	Result *gojson.RawMessage `json:"result"`
}

func request(method, path string, args *http.Args) (*Response, error) {
	requestURI := &url.URL{
		Scheme: "https",
		Host:   "api.telegra.ph",
		Path:   method,
	}

	if path != "" {
		requestURI.Path += fmt.Sprint("/", path)
	}

	_, body, err := http.Post(nil, requestURI.String(), args)
	if err != nil {
		return nil, err
	}

	var resp Response
	if err := json.Unmarshal(body, &resp); err != nil {
		return nil, err
	}

	if !resp.Ok {
		return nil, errors.New(resp.Error)
	}

	return &resp, nil
}

package telegraph

import (
	gojson "encoding/json"
	"errors"
	"fmt"
	"net/url"

	json "github.com/pquerna/ffjson/ffjson"
	http "github.com/valyala/fasthttp"
)

// response represents a response from the Telegram API with the result stored raw. If ok equals true,
// the request was successful, and the result of the query can be found in the result field. In case of
// an unsuccessful request, ok equals false, and the error is explained in the error field (e.g.
// SHORT_NAME_REQUIRED).
type response struct {
	Ok     bool               `json:"ok"`
	Error  string             `json:"error"`
	Result *gojson.RawMessage `json:"result"`
}

func request(method, path string, args *http.Args) (*response, error) {
	requestURI := &url.URL{
		Scheme: "https",
		Host:   "api.telegra.ph",
		Path:   method,
	}

	if path != "" {
		requestURI.Path += fmt.Sprint("/", path)
	}

	_, body, err := http.Post(nil, requestURI.String(), args)
	if err != nil {
		return nil, err
	}

	var resp response
	if err := json.Unmarshal(body, &resp); err != nil {
		return nil, err
	}

	if !resp.Ok {
		return nil, errors.New(resp.Error)
	}

	return &resp, nil
}

Hide Response structure because it is not publicly used anywhere


package hub

import (
	"sync"

	"github.com/gorilla/websocket"
)

var mutex sync.Mutex

type WSClient struct {
	ID      string
	Channel string
	Conn    *websocket.Conn
}

var (
	pool map[string]map[string]*WSClient
)

func init() {
	pool = map[string]map[string]*WSClient{}
}

func Add(ID, channel string, conn *websocket.Conn) *WSClient {
	mutex.Lock()
	defer mutex.Unlock()

	c := &WSClient{ID: ID, Channel: channel, Conn: conn}

	if pool[c.Channel] == nil {
		pool[c.Channel] = map[string]*WSClient{}
	}
	pool[c.Channel][c.ID] = c

	return c
}

func Remove(channel, ID string) {
	mutex.Lock()
	defer mutex.Unlock()
	delete(pool[channel], ID)
}

func Send(channel string, message *Message) (err error) {
	for ID := range pool[channel] {
		err = pool[channel][ID].Conn.WriteJSON(message)
	}

	return
}

package hub

import (
	"sync"

	"github.com/gorilla/websocket"
)

var mutex sync.Mutex

type WSClient struct {
	ID      string
	Channel string
	Conn    *websocket.Conn
}

var (
	pool map[string]map[string]*WSClient
)

func init() {
	pool = map[string]map[string]*WSClient{}
}

func Add(ID, channel string, conn *websocket.Conn) *WSClient {
	mutex.Lock()
	defer mutex.Unlock()

	c := &WSClient{ID: ID, Channel: channel, Conn: conn}

	if pool[c.Channel] == nil {
		pool[c.Channel] = map[string]*WSClient{}
	}
	pool[c.Channel][c.ID] = c

	return c
}

func Remove(channel, ID string) {
	mutex.Lock()
	defer mutex.Unlock()
	delete(pool[channel], ID)
}

func Send(channel string, message *Message) (err error) {
	mutex.Lock()
	defer mutex.Unlock()

	for ID := range pool[channel] {
		err = pool[channel][ID].Conn.WriteJSON(message)
	}

	return
}

Fix concurrency write to websocket channels


// +build windows

package loader

import (
	"os"
	"path/filepath"
)

// On windows, an executable can be any file with any extension. To avoid
// introspecting the file, here we skip executability checks on windows systems
// and simply check for the convention of an `exe` extension.
func executable(path string, s os.FileInfo) bool {
	return filepath.Ext(path) == "exe"
}

// +build windows

package loader

import (
	"os"
	"path/filepath"
)

// On windows, an executable can be any file with any extension. To avoid
// introspecting the file, here we skip executability checks on windows systems
// and simply check for the convention of an `.exe` extension.
func executable(path string, s os.FileInfo) bool {
	return filepath.Ext(path) == ".exe"
}

Fix executable check on windows


package pd1_test

import (
	// "math/rand"
	// "reflect"
	"testing"
	"time"

	// "github.com/influxdb/influxdb/tsdb/engine/pd1"
)

func TestEncoding_FloatBlock(t *testing.T) {
	// valueCount := 100
	// times := getTimes(valueCount, 60, time.Second)
	// values := make([]Value, len(times))
	// for i, t := range times {
	// 	values[i] = pd1.NewValue(t, rand.Float64())
	// }

	// b := pd1.EncodeFloatBlock(nil, values)

	// decodedValues, err := pd1.DecodeFloatBlock(b)
	// if err != nil {
	// 	t.Fatalf("error decoding: %s", err.Error)
	// }

	// if !reflect.DeepEqual(decodedValues, values) {
	// 	t.Fatalf("unexpected results:\n\tgot: %v\n\texp: %v\n", decodedValues, values)
	// }
}

func getTimes(n, step int, precision time.Duration) []time.Time {
	t := time.Now().Round(precision)
	a := make([]time.Time, n)
	for i := 0; i < n; i++ {
		a[i] = t.Add(60 * precision)
	}
	return a
}

package pd1_test

import (
	// "math/rand"
	"fmt"
	"reflect"
	"testing"
	"time"

	"github.com/influxdb/influxdb/tsdb/engine/pd1"
)

func TestEncoding_FloatBlock(t *testing.T) {
	valueCount := 1000
	times := getTimes(valueCount, 60, time.Second)
	values := make(pd1.Values, len(times))
	for i, t := range times {
		values[i] = pd1.NewValue(t, float64(i))
	}

	b := values.Encode(nil)
	fmt.Println("**** ", len(b))

	decodedValues := values.DecodeSameTypeBlock(b)

	if !reflect.DeepEqual(decodedValues, values) {
		t.Fatalf("unexpected results:\n\tgot: %v\n\texp: %v\n", decodedValues, values)
	}
}

func getTimes(n, step int, precision time.Duration) []time.Time {
	t := time.Now().Round(precision)
	a := make([]time.Time, n)
	for i := 0; i < n; i++ {
		a[i] = t.Add(60 * precision)
	}
	return a
}

Update encoding test to work with new interface.


/* Unmarshal
 */

package main

import (
    "go/bandersnatch"
	"encoding/xml"
	"fmt"
	"os"
	//"strings"
)

type Person struct {
	XMLName Name    `xml:"person"`
	Name    Name    `xml:"name"`
	Email   []Email `xml:"email"`
}

type Name struct {
	Family   string `xml:"family"`
	Personal string `xml:"personal"`
}

type Email struct {
	Type    string `xml:"type,attr"`
	Address string `xml:",chardata"`
}

func main() {
	str := `<?xml version="1.0" encoding="utf-8"?>
<person>
  <name>
    <family> Newmarch </family>
    <personal> Jan </personal>
  </name>
  <email type="personal">
    jan@newmarch.name
  </email>
  <email type="work">
    j.newmarch@boxhill.edu.au
  </email>
</person>`

	var person Person

	err := xml.Unmarshal([]byte(str), &person)
	checkError(err)

	// now use the person structure e.g.
	fmt.Println("Family name: \"" + person.Name.Family + "\"")
	fmt.Println("Second email address: \"" + person.Email[1].Address + "\"")
}

func checkError(err error) {
	if err != nil {
		fmt.Println("Fatal error ", err.Error())
		os.Exit(1)
	}
}

package main

import (
    "bandersnatch"
    "fmt"
)

func main() {
    boardGames := bandersnatch.GetBoardGame(30000)

    fmt.Printf("%+v", boardGames)
}

Make it a proper library


package logrus

import (
	"bytes"
	"errors"

	"testing"
)

func TestQuoting(t *testing.T) {
	tf := new(TextFormatter)

	checkQuoting := func(q bool, value interface{}) {
		b, _ := tf.Format(WithField("test", value))
		idx := bytes.LastIndex(b, []byte{'='})
		cont := bytes.Contains(b[idx:], []byte{'"'})
		if cont != q {
			if q {
				t.Errorf("quoting expected for: %#v", value)
			} else {
				t.Errorf("quoting not expected for: %#v", value)
			}
		}
	}

	checkQuoting(false, "abcd")
	checkQuoting(false, "v1.0")
	checkQuoting(true, "/foobar")
	checkQuoting(true, "x y")
	checkQuoting(true, "x,y")
	checkQuoting(false, errors.New("invalid"))
	checkQuoting(true, errors.New("invalid argument"))
}

package logrus

import (
	"bytes"
	"errors"

	"testing"
)

func TestQuoting(t *testing.T) {
	tf := &TextFormatter{DisableColors: true}

	checkQuoting := func(q bool, value interface{}) {
		b, _ := tf.Format(WithField("test", value))
		idx := bytes.Index(b, ([]byte)("test="))
		cont := bytes.Contains(b[idx+5:], []byte{'"'})
		if cont != q {
			if q {
				t.Errorf("quoting expected for: %#v", value)
			} else {
				t.Errorf("quoting not expected for: %#v", value)
			}
		}
	}

	checkQuoting(false, "abcd")
	checkQuoting(false, "v1.0")
	checkQuoting(true, "/foobar")
	checkQuoting(true, "x y")
	checkQuoting(true, "x,y")
	checkQuoting(false, errors.New("invalid"))
	checkQuoting(true, errors.New("invalid argument"))
}

Make the test more robust


package integration

import (
	"os"

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

const previousKismaticVersion = "v1.2.0"

// Test a specific released version of Kismatic
var _ = Describe("Installing with previous version of Kismatic", func() {
	BeforeEach(func() {
		// setup previous version of Kismatic
		tmp := setupTestWorkingDirWithVersion(previousKismaticVersion)
		os.Chdir(tmp)
	})

	installOpts := installOptions{
		allowPackageInstallation: true,
	}

	Context("using Ubuntu 16.04 LTS", func() {
		ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) {
			WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, Ubuntu1604LTS, aws, func(nodes provisionedNodes, sshKey string) {
				err := installKismatic(nodes, installOpts, sshKey)
				Expect(err).ToNot(HaveOccurred())
			})
		})
	})

	Context("using CentOS", func() {
		ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) {
			WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, CentOS7, aws, func(nodes provisionedNodes, sshKey string) {
				err := installKismatic(nodes, installOpts, sshKey)
				Expect(err).ToNot(HaveOccurred())
			})
		})
	})
})

package integration

import (
	"os"

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

const previousKismaticVersion = "v1.3.0"

// Test a specific released version of Kismatic
var _ = Describe("Installing with previous version of Kismatic", func() {
	BeforeEach(func() {
		// setup previous version of Kismatic
		tmp := setupTestWorkingDirWithVersion(previousKismaticVersion)
		os.Chdir(tmp)
	})

	installOpts := installOptions{
		allowPackageInstallation: true,
	}

	Context("using Ubuntu 16.04 LTS", func() {
		ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) {
			WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, Ubuntu1604LTS, aws, func(nodes provisionedNodes, sshKey string) {
				err := installKismatic(nodes, installOpts, sshKey)
				Expect(err).ToNot(HaveOccurred())
			})
		})
	})

	Context("using CentOS", func() {
		ItOnAWS("should install successfully [slow]", func(aws infrastructureProvisioner) {
			WithInfrastructure(NodeCount{1, 1, 1, 0, 0}, CentOS7, aws, func(nodes provisionedNodes, sshKey string) {
				err := installKismatic(nodes, installOpts, sshKey)
				Expect(err).ToNot(HaveOccurred())
			})
		})
	})
})

Update released_test to use v1.3.0


package helpers

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

type Assets struct {
	ServiceBroker      string
	SecurityRules      string
	EmptySecurityRules string
}

func NewAssets() Assets {
	pwd, err := os.Getwd()
	if err != nil {
		panic(err.Error())
	}
	return Assets{
		ServiceBroker:      filepath.ToSlash(path.Join(pwd, "../../assets/service_broker")),
		SecurityRules:      filepath.ToSlash(path.Join(pwd, "../../assets/security_groups/security-rules.json")),
		EmptySecurityRules: filepath.ToSlash(path.Join(pwd, "../../assets/security_groups/empty-security-rules.json")),
	}
}

package helpers

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

type Assets struct {
	ServiceBroker      string
	SecurityRules      string
	EmptySecurityRules string
}

func NewAssets() Assets {
	pwd, err := os.Getwd()
	if err != nil {
		panic(err.Error())
	}
	return Assets{
		ServiceBroker:      filepath.FromSlash(path.Join(pwd, "../../assets/service_broker")),
		SecurityRules:      filepath.FromSlash(path.Join(pwd, "../../assets/security_groups/security-rules.json")),
		EmptySecurityRules: filepath.FromSlash(path.Join(pwd, "../../assets/security_groups/empty-security-rules.json")),
	}
}

Change from ToSlash to FromSlash.


package gocipher

import (
	"fmt"
	"testing"
)

func TestVigenere(t *testing.T) {
	text := "TKSYMWRJGHKBPTEIKCYRWXIELQUPSUTLLGYFIKYIAVFNRLQFKVVSMBMJOCZGILSEAPZRGCVVHTVQYKXJSHARVIPCOGHXGZCGLQNEEXLPDQVXWBLVKCTRSVXYWUORPNEJKVYBROGIQRABKZEGZAAJSMQRANLAGZCGLKVATZSUMEAFQICYSXLNPUSJLVORWIQVMULEMVXVJHHPIGIKGPLVWAITMTLJLQPVLJLBXPIIHGYZMBWVSXLFHZSGHKUTEKSDHCYVWWRTZCYGQICJMINRWBXYSVAJSXVFYTHZWPEMWUPZMTEIXGHGYZIJSNAUSCKYGPLUEAKRHKUTWMGLJKALLWPVKYOVPMXYWQAUIZHFWUUGEVIOHGYVIVGVVEYLTBSXJCWUIZGRFVLYPBLVVKMSIZIEUGZBGIRRLJPRJ"
	key, err := VigenereCrack(text, 8)
	if err != nil {
		t.Fatal(err)
	}
	v := NewVigenere(key)
	plain := v.Decrypt(text)
	fmt.Printf("key: %v\nplaintext: %s\n", key, plain)
	cipher := v.Encrypt(plain)
	if cipher != text {
		t.Errorf("roundtrip not equal: %s", cipher)
	}
}

package gocipher

import (
	"fmt"
	"testing"
)

func TestVigenere(t *testing.T) {
	text := "TKSYMWRJGHKBPTEIKCYRWXIELQUPSUTLLGYFIKYIAVFNRLQFKVVSMBMJOCZGILSEAPZRGCVVHTVQYKXJSHARVIPCOGHXGZCGLQNEEXLPDQVXWBLVKCTRSVXYWUORPNEJKVYBROGIQRABKZEGZAAJSMQRANLAGZCGLKVATZSUMEAFQICYSXLNPUSJLVORWIQVMULEMVXVJHHPIGIKGPLVWAITMTLJLQPVLJLBXPIIHGYZMBWVSXLFHZSGHKUTEKSDHCYVWWRTZCYGQICJMINRWBXYSVAJSXVFYTHZWPEMWUPZMTEIXGHGYZIJSNAUSCKYGPLUEAKRHKUTWMGLJKALLWPVKYOVPMXYWQAUIZHFWUUGEVIOHGYVIVGVVEYLTBSXJCWUIZGRFVLYPBLVVKMSIZIEUGZBGIRRLJPRJ"
	key := VigenereCrack(text, 8)
	v := NewVigenere(key)
	plain := v.Decrypt(text)
	fmt.Printf("key: %v\nplaintext: %s\n", key, plain)
	cipher := v.Encrypt(plain)
	if cipher != text {
		t.Errorf("roundtrip not equal: %s", cipher)
	}
}

Fix test to use changed retvals


package model

type File struct {
	ID       string
	Filename string
	Content  []byte
}

type Entry struct {
	ID        string `json:"id"`
	Title     string `json:"title"`
	Timestamp int64  `json:"timestamp"`
	Markdown  string // the entry contents
}

package model

type File struct {
	ID       string
	Filename string
	Content  []byte
}

type Entry struct {
	ID        string `json:"id"`
	Title     string `json:"title"`
	Timestamp int64  `json:"timestamp"`
    Markdown  string `json:"-"` // the entry contents
}

Save markdown only in .txt


package otgrpc

import (
	"strings"

	opentracing "github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	"google.golang.org/grpc/metadata"
)

var (
	// Morally a const:
	gRPCComponentTag = opentracing.Tag{string(ext.Component), "gRPC"}
)

// metadataReaderWriter satisfies both the opentracing.TextMapReader and
// opentracing.TextMapWriter interfaces.
type metadataReaderWriter struct {
	metadata.MD
}

func (w metadataReaderWriter) Set(key, val string) {
	key = strings.ToLower(key)
	w.MD[key] = append(w.MD[key], val)
}

func (w metadataReaderWriter) ForeachKey(handler func(key, val string) error) error {
	for k, vals := range w.MD {
		for _, v := range vals {
			if dk, dv, err := metadata.DecodeKeyValue(k, v); err == nil {
				if err = handler(dk, dv); err != nil {
					return err
				}
			} else {
				return err
			}
		}
	}

	return nil
}

package otgrpc

import (
	"strings"

	opentracing "github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	"google.golang.org/grpc/metadata"
)

var (
	// Morally a const:
	gRPCComponentTag = opentracing.Tag{string(ext.Component), "gRPC"}
)

// metadataReaderWriter satisfies both the opentracing.TextMapReader and
// opentracing.TextMapWriter interfaces.
type metadataReaderWriter struct {
	metadata.MD
}

func (w metadataReaderWriter) Set(key, val string) {
	// The GRPC HPACK implementation rejects any uppercase keys here.
	//
	// As such, since the HTTP_HEADERS format is case-insensitive anyway, we
	// blindly lowercase the key (which is guaranteed to work in the
	// Inject/Extract sense per the OpenTracing spec).
	key = strings.ToLower(key)
	w.MD[key] = append(w.MD[key], val)
}

func (w metadataReaderWriter) ForeachKey(handler func(key, val string) error) error {
	for k, vals := range w.MD {
		for _, v := range vals {
			if dk, dv, err := metadata.DecodeKeyValue(k, v); err == nil {
				if err = handler(dk, dv); err != nil {
					return err
				}
			} else {
				return err
			}
		}
	}

	return nil
}

Clarify the rational for the ToLower(key) call


package parser

import "fmt"

func auto(input []byte) (interface{}, error) {
	for _, name := range parseOrder() {
		if parsed, err := parsers[name].parse(input); err == nil {
			return parsed, err
		}
	}

	return nil, fmt.Errorf("input format could not be identified")
}

func parseOrder() []string {
	order := make([]string, 0, len(parsers))

	tried := make(map[string]bool)

	var tryParser func(string)

	tryParser = func(name string) {
		if tried[name] {
			return
		}

		for _, pref := range parsers[name].prefers {
			tryParser(pref)
		}

		order = append(order, name)
		tried[name] = true
	}

	for name := range parsers {
		if name != "auto" {
			tryParser(name)
		}
	}

	return order
}

func init() {
	parsers["auto"] = parser{
		parse: auto,
	}
}

package parser

import "fmt"

// Identify tries to figure out the format of the structured data passed in
// If the data format could not be identified, an error will be returned
func Identify(input []byte) (string, error) {
	for _, name := range parseOrder() {
		if parsed, err := parsers[name].parse(input); err == nil {
			fmt.Println(name, parsed)

			return name, nil
		}
	}

	return "", fmt.Errorf("input format could not be identified")
}

func auto(input []byte) (interface{}, error) {
	for _, name := range parseOrder() {
		if parsed, err := parsers[name].parse(input); err == nil {
			return parsed, err
		}
	}

	return nil, fmt.Errorf("input format could not be identified")
}

func parseOrder() []string {
	order := make([]string, 0, len(parsers))

	tried := make(map[string]bool)

	var tryParser func(string)

	tryParser = func(name string) {
		if tried[name] {
			return
		}

		for _, pref := range parsers[name].prefers {
			tryParser(pref)
		}

		order = append(order, name)
		tried[name] = true
	}

	for name := range parsers {
		if name != "auto" {
			tryParser(name)
		}
	}

	return order
}

func init() {
	parsers["auto"] = parser{
		parse: auto,
	}
}

Add Identify function to parser


package bitfinex

type CreditsService struct {
	client *Client
}

type Credit struct {
	Id        int
	Currency  string
	Status    string
	Rate      float64
	Period    float64
	Amount    float64
	Timestamp string
}

// Returns an array of Credit
func (c *CreditsService) All() ([]Credit, error) {
	req, err := c.client.newAuthenticatedRequest("GET", "credits", nil)
	if err != nil {
		return nil, err
	}

	credits := make([]Credit, 0)
	_, err = c.client.do(req, &credits)
	if err != nil {
		return nil, err
	}

	return credits, nil
}

package bitfinex

type CreditsService struct {
	client *Client
}

type Credit struct {
	Id        int
	Currency  string
	Status    string
	Rate      float64 `json:",string"`
	Period    float64
	Amount    float64 `json:",string"`
	Timestamp string
}

// Returns an array of Credit
func (c *CreditsService) All() ([]Credit, error) {
	req, err := c.client.newAuthenticatedRequest("GET", "credits", nil)
	if err != nil {
		return nil, err
	}

	credits := make([]Credit, 0)
	_, err = c.client.do(req, &credits)
	if err != nil {
		return nil, err
	}

	return credits, nil
}

Update json tags for Credit to reflect REST response.


/*
package proto defines a set of structures used to negotiate an update between an
an application (the client) and an Equinox update service.
*/
package proto

import "time"

type PatchKind string

const (
	PatchNone   PatchKind = "none"
	PatchBSDiff PatchKind = "bsdiff"
)

type Request struct {
	AppID         string `json:"app_id"`
	Channel       string `json:"channel"`
	OS            string `json:"os"`
	Arch          string `json:"arch"`
	GoARM         string `json:"goarm"`
	TargetVersion string `json:"target_version"`

	CurrentVersion string `json:"current_version"`
	CurrentSHA256  string `json:"current_sha256"`
}

type Response struct {
	Available   bool      `json:"available"`
	DownloadURL string    `json:"download_url"`
	Checksum    string    `json:"checksum"`
	Signature   string    `json:"signature"`
	Patch       PatchKind `json:"patch_type,string"`
	Version     string    `json:"version"`
	Release     Release   `json:"release"`
}

type Release struct {
	Title       string    `json:"title"`
	Version     string    `json:"version"`
	Description string    `json:"description"`
	CreateDate  time.Time `json:"create_date"`
}

/*
package proto defines a set of structures used to negotiate an update between an
an application (the client) and an Equinox update service.
*/
package proto

import "time"

type PatchKind string

const (
	PatchNone   PatchKind = "none"
	PatchBSDiff PatchKind = "bsdiff"
)

type Request struct {
	AppID         string `json:"app_id"`
	Channel       string `json:"channel"`
	OS            string `json:"os"`
	Arch          string `json:"arch"`
	GoARM         string `json:"goarm"`
	TargetVersion string `json:"target_version"`

	CurrentVersion string `json:"current_version"`
	CurrentSHA256  string `json:"current_sha256"`
}

type Response struct {
	Available   bool      `json:"available"`
	DownloadURL string    `json:"download_url"`
	Checksum    string    `json:"checksum"`
	Signature   string    `json:"signature"`
	Patch       PatchKind `json:"patch_type"`
	Version     string    `json:"version"`
	Release     Release   `json:"release"`
}

type Release struct {
	Title       string    `json:"title"`
	Version     string    `json:"version"`
	Description string    `json:"description"`
	CreateDate  time.Time `json:"create_date"`
}

Remove incorrect JSON struct tag


package template

import (
	"bytes"
	"text/template"

	"github.com/Masterminds/sprig"
)

func Apply(contents []byte, variables map[string]string) ([]byte, error) {
	t, err := template.New("template").Funcs(sprig.TxtFuncMap()).Parse(string(contents))
	if err != nil {
		return nil, err
	}

	buf := bytes.Buffer{}
	t.Execute(&buf, map[string]map[string]string{
		"Values": variables,
	})
	return buf.Bytes(), nil
}

package template

import (
	"bytes"
	"strings"
	"text/template"

	"github.com/Masterminds/sprig"
)

func Apply(contents []byte, variables map[string]string) ([]byte, error) {
	// Skip templating if contents begin with '# notemplating'
	trimmedContents := strings.TrimSpace(string(contents))
	if strings.HasPrefix(trimmedContents, "#notemplating") || strings.HasPrefix(trimmedContents, "# notemplating") {
		return contents, nil
	}

	t, err := template.New("template").Funcs(sprig.TxtFuncMap()).Parse(string(contents))
	if err != nil {
		return nil, err
	}

	buf := bytes.Buffer{}
	t.Execute(&buf, map[string]map[string]string{
		"Values": variables,
	})
	return buf.Bytes(), nil
}

Add the ability to skip templating


package main

import ()

type statistics struct {
	inDummy    int
	inMail     int
	inEnc      int
	inRemFoo   int
	outDummy   int
	outMail    int
	outEnc     int
	outLoop    int
	outRandhop int
	outPlain   int
}

func (s *statistics) reset() {
	s.inDummy = 0
	s.inMail = 0
	s.inEnc = 0
	s.inRemFoo = 0
	s.outDummy = 0
	s.outMail = 0
	s.outEnc = 0
	s.outLoop = 0
	s.outRandhop = 0
	s.outPlain = 0
}

func (s *statistics) report() {
	Info.Printf(
		"MailIn=%d, RemFoo=%d, YamnIn=%d, DummyIn=%d",
		s.inMail,
		s.inRemFoo,
		s.inEnc,
		s.inDummy,
	)
	Info.Printf(
		"MailOut=%d, YamnOut=%d, YamnLoop=%d, Randhop=%d,",
		"FinalOut=%d, DummyOut=%d",
		s.outMail,
		s.outEnc,
		s.outLoop,
		s.outRandhop,
		s.outPlain,
		s.outDummy,
	)
}

var stats = new(statistics)

package main

import (
	"fmt"
)

type statistics struct {
	inDummy    int
	inMail     int
	inEnc      int
	inRemFoo   int
	outDummy   int
	outMail    int
	outEnc     int
	outLoop    int
	outRandhop int
	outPlain   int
}

func (s *statistics) reset() {
	s.inDummy = 0
	s.inMail = 0
	s.inEnc = 0
	s.inRemFoo = 0
	s.outDummy = 0
	s.outMail = 0
	s.outEnc = 0
	s.outLoop = 0
	s.outRandhop = 0
	s.outPlain = 0
}

func (s *statistics) report() {
	Info.Printf(
		"MailIn=%d, RemFoo=%d, YamnIn=%d, DummyIn=%d",
		s.inMail,
		s.inRemFoo,
		s.inEnc,
		s.inDummy,
	)
	line1 := fmt.Sprintf(
		"MailOut=%d, YamnOut=%d, YamnLoop=%d, Randhop=%d, ",
		s.outMail,
		s.outEnc,
		s.outLoop,
		s.outRandhop,
	)
	line2 := fmt.Sprintf(
		"FinalOut=%d, DummyOut=%d",
		s.outPlain,
		s.outDummy,
	)
	Info.Printf(line1 + line2)
}

var stats = new(statistics)

Correct a string formatting bug


package stringutils

import (
	"testing"
)

var forwardStrings = [...]string{`Hello`, `The quick brown 狐 jumped over the lazy 犬`, `1234567890`, `~!@#$%^&*()_+|\`}
var backwardStrings = [...]string{`olleH`, `犬 yzal eht revo depmuj 狐 nworb kciuq ehT`, `0987654321`, `\|+_)(*&^%$#@!~`}

func TestReverse(t *testing.T) {
	// iterate through the forwardStrings array
	for i, s := range forwardStrings {
		// reverse the string
		rev := Reverse(s)
		// check if the reversed string matches its mirror array
		if rev == backwardStrings[i] {
			t.Logf("success: '%s'", s)
		} else {
			t.Errorf("fail: forward:'%s' != rev:'%s'", s, rev)
		}
	}
}

package stringutils

import (
	"testing"
)

var forwardStrings = [...]string{`Hello`, `The quick bròwn 狐 jumped over the lazy 犬`, `1234567890`, `~!@#$%^&*()_+|\`, `ápplesareágoodfruit`}
var backwardStrings = [...]string{`olleH`, `犬 yzal eht revo depmuj 狐 nwòrb kciuq ehT`, `0987654321`, `\|+_)(*&^%$#@!~`, `tiurfdoogáeraselppá`}

func TestReverse(t *testing.T) {
	// iterate through the forwardStrings array
	for i, s := range forwardStrings {
		// reverse the string
		rev := Reverse(s)
		// check if the reversed string matches its mirror array
		if rev == backwardStrings[i] {
			t.Logf("success: '%s'", s)
		} else {
			t.Errorf("fail: forward:'%s' != rev:'%s'", s, rev)
		}
	}
}

Add new test case for Reverse


package consul

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

// Test is an RPC endpoint that is only available during `go test` when
// `TestEndpoint` is called. This is not and must not ever be available
// during a real running Consul agent, since it this endpoint bypasses
// critical ACL checks.
type Test struct {
	// srv is a pointer back to the server.
	srv *Server
}

// ConnectCASetRoots sets the current CA roots state.
func (s *Test) ConnectCASetRoots(
	args []*structs.CARoot,
	reply *interface{}) error {

	// Get the highest index
	state := s.srv.fsm.State()
	idx, _, err := state.CARoots(nil)
	if err != nil {
		return err
	}

	// Commit
	resp, err := s.srv.raftApply(structs.ConnectCARequestType, &structs.CARequest{
		Op:    structs.CAOpSet,
		Index: idx,
		Roots: args,
	})
	if err != nil {
		s.srv.logger.Printf("[ERR] consul.test: Apply failed %v", err)
		return err
	}
	if respErr, ok := resp.(error); ok {
		return respErr
	}

	return nil
}

package consul

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

// Test is an RPC endpoint that is only available during `go test` when
// `TestEndpoint` is called. This is not and must not ever be available
// during a real running Consul agent, since it this endpoint bypasses
// critical ACL checks.
type Test struct {
	// srv is a pointer back to the server.
	srv *Server
}

// ConnectCASetRoots sets the current CA roots state.
func (s *Test) ConnectCASetRoots(
	args []*structs.CARoot,
	reply *interface{}) error {

	// Get the highest index
	state := s.srv.fsm.State()
	idx, _, err := state.CARoots(nil)
	if err != nil {
		return err
	}

	// Commit
	resp, err := s.srv.raftApply(structs.ConnectCARequestType, &structs.CARequest{
		Op:    structs.CAOpSetRoots,
		Index: idx,
		Roots: args,
	})
	if err != nil {
		s.srv.logger.Printf("[ERR] consul.test: Apply failed %v", err)
		return err
	}
	if respErr, ok := resp.(error); ok {
		return respErr
	}

	return nil
}

Fix the testing endpoint's root set op


package jsonschema

import (
	"fmt"
	"reflect"
)

// normalizeNumber accepts any input and, if it is a supported number type,
// converts it to either int64 or float64. normalizeNumber raises an error
// if the input is an explicitly unsupported number type.
func normalizeNumber(v interface{}) (n interface{}, err error) {
	switch t := v.(type) {

	case float32:
		n = float64(t)
	case float64:
		n = t

	case int:
		n = int64(t)
	case int8:
		n = int64(t)
	case int16:
		n = int64(t)
	case int32:
		n = int64(t)
	case int64:
		n = t

	case uint8:
		n = int64(t)
	case uint16:
		n = int64(t)
	case uint32:
		n = int64(t)
	case uint64:
		n = t
		err = fmt.Errorf("%s is not a supported type.", reflect.TypeOf(v))

	default:
		n = t
	}

	return
}

package jsonschema

import (
	"encoding/json"
	"fmt"
	"reflect"
	"strings"
)

// normalizeNumber accepts any input and, if it is a supported number type,
// converts it to either int64 or float64. normalizeNumber raises an error
// if the input is an explicitly unsupported number type.
func normalizeNumber(v interface{}) (n interface{}, err error) {
	switch t := v.(type) {

	case json.Number:
		if strings.Contains(t.String(), ".") {
			n, err = t.Float64()
		} else {
			n, err = t.Int64()
		}

	case float32:
		n = float64(t)
	case float64:
		n = t

	case int:
		n = int64(t)
	case int8:
		n = int64(t)
	case int16:
		n = int64(t)
	case int32:
		n = int64(t)
	case int64:
		n = t

	case uint8:
		n = int64(t)
	case uint16:
		n = int64(t)
	case uint32:
		n = int64(t)
	case uint64:
		n = t
		err = fmt.Errorf("%s is not a supported type.", reflect.TypeOf(v))

	default:
		n = t
	}

	return
}

Convert json.Numbers into int64 or float64.


package main

import (
	_ "github.com/gliderlabs/logspout/adapters/raw"
	_ "github.com/gliderlabs/logspout/adapters/syslog"
	_ "github.com/gliderlabs/logspout/httpstream"
	_ "github.com/gliderlabs/logspout/routesapi"
	_ "github.com/gliderlabs/logspout/transports/tcp"
	_ "github.com/gliderlabs/logspout/transports/udp"
	_ "github.com/tbossert/logspout-loggly/loggly"
)

package main

import (
	_ "github.com/gliderlabs/logspout/adapters/raw"
	_ "github.com/gliderlabs/logspout/adapters/syslog"
	_ "github.com/gliderlabs/logspout/httpstream"
	_ "github.com/gliderlabs/logspout/routesapi"
	_ "github.com/gliderlabs/logspout/transports/tcp"
	_ "github.com/gliderlabs/logspout/transports/udp"
	_ "github.com/iamatypeofwalrus/logspout-loggly/loggly"
)

Revert module name to iamatypeofwalrus for pull request


package main

import (
	"os/exec"
	"strings"
	"testing"
)

func TestMakefont(t *testing.T) {
	const expect = "Font definition file successfully generated"
	out, err := exec.Command("./makefont", "--dst=../font", "--embed",
		"--enc=../font/cp1252.map", "../font/calligra.ttf").CombinedOutput()
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(string(out), expect) {
		t.Fatalf("Unexpected output from makefont")
	}
}

package main

import (
	"os/exec"
	"strings"
	"testing"
)

func TestMakefont(t *testing.T) {
	var out []byte
	var err error
	const expect = "Font definition file successfully generated"
	// Make sure makefont utility has been built before generating font definition file
	err = exec.Command("go", "build").Run()
	if err != nil {
		t.Fatal(err)
	}
	out, err = exec.Command("./makefont", "--dst=../font", "--embed",
		"--enc=../font/cp1252.map", "../font/calligra.ttf").CombinedOutput()
	if err != nil {
		t.Fatal(err)
	}
	if !strings.Contains(string(out), expect) {
		t.Fatalf("Unexpected output from makefont")
	}
}

Make sure makefont utility has been built before running test


// +build darwin

package daemon

/*
#define __DARWIN_UNIX03 0
#define KERNEL
#define _DARWIN_USE_64_BIT_INODE
#include <dirent.h>
#include <fcntl.h>
#include <sys/param.h>
*/
import "C"

import (
	"syscall"
	"unsafe"
)

func lockFile(fd uintptr) error {
	err := syscall.Flock(int(fd), syscall.LOCK_EX|syscall.LOCK_NB)
	if err == syscall.EWOULDBLOCK {
		err = ErrWouldBlock
	}
	return err
}

func unlockFile(fd uintptr) error {
	err := syscall.Flock(int(fd), syscall.LOCK_UN)
	if err == syscall.EWOULDBLOCK {
		err = ErrWouldBlock
	}
	return err
}

func getFdName(fd uintptr) (name string, err error) {
	buf := make([]C.char, int(C.MAXPATHLEN)+1)
	_, _, errno := syscall.Syscall(syscall.SYS_FCNTL, fd, syscall.F_GETPATH, uintptr(unsafe.Pointer(&buf[0])))
	if errno == 0 {
		return C.GoString(&buf[0]), nil
	}
	return "", errno
}

// +build darwin

package daemon

import (
	"syscall"
	"unsafe"
)

import "C"

// darwin's MAXPATHLEN
const maxpathlen = 1024

func lockFile(fd uintptr) error {
	err := syscall.Flock(int(fd), syscall.LOCK_EX|syscall.LOCK_NB)
	if err == syscall.EWOULDBLOCK {
		err = ErrWouldBlock
	}
	return err
}

func unlockFile(fd uintptr) error {
	err := syscall.Flock(int(fd), syscall.LOCK_UN)
	if err == syscall.EWOULDBLOCK {
		err = ErrWouldBlock
	}
	return err
}

func getFdName(fd uintptr) (name string, err error) {
	buf := make([]C.char, maxpathlen+1)
	_, _, errno := syscall.Syscall(syscall.SYS_FCNTL, fd, syscall.F_GETPATH, uintptr(unsafe.Pointer(&buf[0])))
	if errno == 0 {
		return C.GoString(&buf[0]), nil
	}
	return "", errno
}

Remove unused imports of .h files from implementaion for darwin


package jump

import "testing"

func TestHashInBucketRange(t *testing.T) {
	h := Hash(1, 1)
	if h != 0 {
		t.Error("expected bucket to be 0, got", h)
	}

	h = Hash(42, 57)
	if h != 43 {
		t.Error("expected bucket to be 43, got", h)
	}

	h = Hash(0xDEAD10CC, 1)
	if h != 0 {
		t.Error("expected bucket to be 0, got", h)
	}

	h = Hash(0xDEAD10CC, 666)
	if h != 361 {
		t.Error("expected bucket to be 361, got", h)
	}

	h = Hash(256, 1024)
	if h != 520 {
		t.Error("expected bucket to be 520, got", h)
	}

}

func TestNegativeBucket(t *testing.T) {
	h := Hash(0, -10)
	if h != 0 {
		t.Error("expected bucket to be 0, got", h)
	}

	h = Hash(0xDEAD10CC, -666)
	if h != 0 {
		t.Error("expected bucket to be 0, got", h)
	}
}

func ExampleHash() {
	Hash(256, 1024)
	// Output: 520
}

Add code example for Godoc.


package downloads

import (
	"github.com/itchio/butler/buse"
	"github.com/itchio/butler/cmd/operate"
)

func DownloadsRetry(rc *buse.RequestContext, params *buse.DownloadsRetryParams) (*buse.DownloadsRetryResult, error) {
	consumer := rc.Consumer

	download := ValidateDownload(rc, params.DownloadID)

	if download.Error == nil {
		consumer.Warnf("No error, can't retry download")
	} else {
		download.Error = nil
		download.Save(rc.DB())

		consumer.Statf("Queued a retry for download for %s", operate.GameToString(download.Game))
	}

	res := &buse.DownloadsRetryResult{}
	return res, nil
}

package downloads

import (
	"github.com/itchio/butler/buse"
	"github.com/itchio/butler/cmd/operate"
)

func DownloadsRetry(rc *buse.RequestContext, params *buse.DownloadsRetryParams) (*buse.DownloadsRetryResult, error) {
	consumer := rc.Consumer

	download := ValidateDownload(rc, params.DownloadID)

	if download.Error == nil {
		consumer.Warnf("No error, can't retry download")
	} else {
		download.Error = nil
		download.FinishedAt = nil
		download.Save(rc.DB())

		consumer.Statf("Queued a retry for download for %s", operate.GameToString(download.Game))
	}

	res := &buse.DownloadsRetryResult{}
	return res, nil
}

Clear FInishedAt when retrying, otherwise it just marks it as done


package magicsql

import (
	"strings"
	"testing"

	"./assert"
)

type Foo struct {
	ONE   string
	TwO   int `sql:",primary"`
	Three bool `sql:"tree"`
	Four  int
	Five  int `sql:"-"`
	six   string
}

func newFoo() interface{} {
	return &Foo{}
}

func TestQueryFields(t *testing.T) {
	var table = NewMagicTable("foos", newFoo)
	assert.Equal("one,two,tree,four", strings.Join(table.FieldNames(), ","), "Full field list", t)
	assert.Equal(4, len(table.sqlFields), "THERE ARE FOUR LIGHTS!  Er, fields....", t)
}

func TestScanStruct(t *testing.T) {
	var table = NewMagicTable("foos", newFoo)
	var foo = &Foo{ONE: "blargh"}
	var ptr = table.ScanStruct(foo)[0].(*NullableField).Value.(*string)
	assert.Equal(foo.ONE, *ptr, "scanStruct properly pokes into the underlying data", t)
	*ptr = "foo"
	assert.Equal("foo", foo.ONE, "yes, this really is a proper pointer", t)
}

package magicsql

import (
	"strings"
	"testing"

	"./assert"
)

type Foo struct {
	// ONE turns into "one" for field name, as we auto-lowercase anything not tagged
	ONE   string
	// TwO is the primary key, but not explicitly given a field name, so it'll be "two"
	TwO   int `sql:",primary"`
	// Three is explicitly set to "tree"
	Three bool `sql:"tree"`
	// Four is just lowercased to "four"
	Four  int
	// Five is explicitly skipped
	Five  int `sql:"-"`
	six   string
}

func newFoo() interface{} {
	return &Foo{}
}

func TestQueryFields(t *testing.T) {
	var table = NewMagicTable("foos", newFoo)
	assert.Equal("one,two,tree,four", strings.Join(table.FieldNames(), ","), "Full field list", t)
	assert.Equal(4, len(table.sqlFields), "THERE ARE FOUR LIGHTS!  Er, fields....", t)
}

func TestScanStruct(t *testing.T) {
	var table = NewMagicTable("foos", newFoo)
	var foo = &Foo{ONE: "blargh"}
	var ptr = table.ScanStruct(foo)[0].(*NullableField).Value.(*string)
	assert.Equal(foo.ONE, *ptr, "scanStruct properly pokes into the underlying data", t)
	*ptr = "foo"
	assert.Equal("foo", foo.ONE, "yes, this really is a proper pointer", t)
}

Add comments explaining Foo tags


package main

import (
	"fmt"
	"net/http"

	"github.com/lohmander/webapi"
)

func handler(rw http.ResponseWriter, req *http.Request) {
	fmt.Fprintf(rw, "Hello there")
}

func main() {
	api := webapi.NewAPI()
	api.Apply(Logger)
	api.Add(`/subscriptions$`, &Subscription{})
	api.Add(`/subscriptions/(?P<id>\d+)$`, &Subscription{}, Teapot)

	http.Handle("/api/", api)
	http.ListenAndServe(":3002", nil)
}

func Logger(handler webapi.Handler) webapi.Handler {
	return func(r *webapi.Request) (int, webapi.Response) {
		code, data := handler(r)
		fmt.Printf("%d %s %s", code, r.Method, r.URL.Path)
		return code, data
	}
}

func Teapot(handler webapi.Handler) webapi.Handler {
	return func(r *webapi.Request) (int, webapi.Response) {
		_, data := handler(r)
		return 418, data
	}
}

type Subscription struct{}

func (s Subscription) Post(request *webapi.Request) (int, webapi.Response) {
	var data interface{} = map[string]string{
		"tipp":  "topp",
		"param": request.Param("id"),
	}

	return 200, webapi.Response{
		Data: &data,
	}
}

package main

import (
	"fmt"
	"net/http"

	"github.com/lohmander/webapi"
)

func main() {
	api := webapi.NewAPI()
	api.Apply(Logger)

	api.Add(`/subscriptions$`, &Subscription{})
	api.Add(`/subscriptions/(?P<id>\d+)$`, &Subscription{}, Teapot)

	http.Handle("/api/", api)
	http.ListenAndServe(":3002", nil)
}

func Logger(handler webapi.Handler) webapi.Handler {
	return func(r *webapi.Request) (int, webapi.Response) {
		code, data := handler(r)
		fmt.Println(code, r.Method, r.URL.Path)
		return code, data
	}
}

func Teapot(handler webapi.Handler) webapi.Handler {
	return func(r *webapi.Request) (int, webapi.Response) {
		_, data := handler(r)
		return 418, data
	}
}

type Subscription struct{}

func (s Subscription) Post(request *webapi.Request) (int, webapi.Response) {
	var data interface{} = map[string]string{
		"tipp":  "topp",
		"param": request.Param("id"),
	}

	return 200, webapi.Response{
		Data: &data,
	}
}

Remove old test handler in example


package http

import stdhttp "net/http"

// HostProvider describes something which can yield hosts for transactions,
// and record transaction success against a yielded host.
type HostProvider interface {
	Get() (host string, err error)
	Put(host string, success bool)
}

// Proxying implements host proxying logic.
func Proxying(p HostProvider, next Client) Client {
	return &proxying{
		p:    p,
		next: next,
	}
}

type proxying struct {
	p    HostProvider
	next Client
}

func (p proxying) Do(req *stdhttp.Request) (*stdhttp.Response, error) {
	host, err := p.p.Get()
	if err != nil {
		return nil, err
	}

	req.Host = host
	resp, err := p.next.Do(req)

	if err == nil {
		p.p.Put(host, true)
	} else {
		p.p.Put(host, false)
	}

	return resp, err
}

package http

import stdhttp "net/http"

// HostProvider describes something which can yield hosts for transactions,
// and record a given host's success/failure.
type HostProvider interface {
	Get() (host string, err error)
	Put(host string, success bool)
}

// Proxying implements host proxying logic.
func Proxying(p HostProvider, next Client) Client {
	return &proxying{
		p:    p,
		next: next,
	}
}

type proxying struct {
	p    HostProvider
	next Client
}

func (p proxying) Do(req *stdhttp.Request) (*stdhttp.Response, error) {
	host, err := p.p.Get()
	if err != nil {
		return nil, err
	}

	req.Host = host
	resp, err := p.next.Do(req)

	if err == nil {
		p.p.Put(host, true)
	} else {
		p.p.Put(host, false)
	}

	return resp, err
}

Fix awkward wording for http.Proxying


package socks5

import (
	"net"
)

// RuleSet is used to provide custom rules to allow or prohibit actions
type RuleSet interface {
	// AllowConnect is used to filter connect requests
	AllowConnect(dstIP *net.IPAddr, dstPort int, srcIP *net.IPAddr, srcPort int) bool

	// AllowBind is used to filter bind requests
	AllowBind(dstIP *net.IPAddr, dstPort int, srcIP *net.IPAddr, srcPort int) bool

	// AllowAssociate is used to filter associate requests
	AllowAssociate(dstIP *net.IPAddr, dstPort int, srcIP *net.IPAddr, srcPort int) bool
}

// PermitAll is an returns a RuleSet which allows all types of connections
func PermitAll() RuleSet {
	return &PermitCommand{true, true, true}
}

// PermitCommand is an implementation of the RuleSet which
// enables filtering supported commands
type PermitCommand struct {
	EnableConnect   bool
	EnableBind      bool
	EnableAssociate bool
}

func (p *PermitCommand) AllowConnect(*net.IPAddr, int, *net.IPAddr, int) bool {
	return p.EnableConnect
}

func (p *PermitCommand) AllowBind(*net.IPAddr, int, *net.IPAddr, int) bool {
	return p.EnableBind
}

func (p *PermitCommand) AllowAssociate(*net.IPAddr, int, *net.IPAddr, int) bool {
	return p.EnableAssociate
}

package socks5

import (
	"net"
)

// RuleSet is used to provide custom rules to allow or prohibit actions
type RuleSet interface {
	// AllowConnect is used to filter connect requests
	AllowConnect(dstIP net.IP, dstPort int, srcIP net.IP, srcPort int) bool

	// AllowBind is used to filter bind requests
	AllowBind(dstIP net.IP, dstPort int, srcIP net.IP, srcPort int) bool

	// AllowAssociate is used to filter associate requests
	AllowAssociate(dstIP net.IP, dstPort int, srcIP net.IP, srcPort int) bool
}

// PermitAll is an returns a RuleSet which allows all types of connections
func PermitAll() RuleSet {
	return &PermitCommand{true, true, true}
}

// PermitCommand is an implementation of the RuleSet which
// enables filtering supported commands
type PermitCommand struct {
	EnableConnect   bool
	EnableBind      bool
	EnableAssociate bool
}

func (p *PermitCommand) AllowConnect(net.IP, int, net.IP, int) bool {
	return p.EnableConnect
}

func (p *PermitCommand) AllowBind(net.IP, int, net.IP, int) bool {
	return p.EnableBind
}

func (p *PermitCommand) AllowAssociate(net.IP, int, net.IP, int) bool {
	return p.EnableAssociate
}

Use net.IP instead of IPAddr


// +build js

package select_menu

import (
	"net/url"
	"strings"

	"github.com/gopherjs/gopherjs/js"
	"github.com/shurcooL/go/gopherjs_http/jsutil"
	"honnef.co/go/js/dom"
)

func init() {
	js.Global.Set("SelectMenuOnInput", jsutil.Wrap(SelectMenuOnInput))
}

func SelectMenuOnInput(event dom.Event, object dom.HTMLElement, defaultOption, queryParameter string) {
	rawQuery := strings.TrimPrefix(dom.GetWindow().Location().Search, "?")
	query, _ := url.ParseQuery(rawQuery)

	selectElement := object.(*dom.HTMLSelectElement)

	selected := selectElement.SelectedOptions()[0].Text

	if selected == defaultOption {
		query.Del(queryParameter)
	} else {
		query.Set(queryParameter, selected)
	}

	dom.GetWindow().Location().Search = "?" + query.Encode()
}

// +build js

package select_menu

import (
	"fmt"
	"net/url"

	"github.com/gopherjs/gopherjs/js"
	"github.com/shurcooL/go/gopherjs_http/jsutil"
	"honnef.co/go/js/dom"
)

func init() {
	js.Global.Set("SelectMenuOnInput", jsutil.Wrap(SelectMenuOnInput))
}

func SelectMenuOnInput(event dom.Event, selElem dom.HTMLElement, defaultOption, queryParameter string) {
	url, err := url.Parse(dom.GetWindow().Location().Href)
	if err != nil {
		// We don't expect this can ever happen, so treat it as an internal error if it does.
		panic(fmt.Errorf("internal error: parsing window.location.href as URL failed: %v", err))
	}
	query := url.Query()
	if selected := selElem.(*dom.HTMLSelectElement).SelectedOptions()[0].Text; selected == defaultOption {
		query.Del(queryParameter)
	} else {
		query.Set(queryParameter, selected)
	}
	url.RawQuery = query.Encode()
	dom.GetWindow().Location().Href = url.String()
}

Remove extraneous "?" when no queries.


// Copyright 2017 Jayson Grace. All rights reserved
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package main

import (
	"fmt"
	"os/exec"
	"regexp"
	"strings"
	"sync"
)

// exeCmd executes an input command.
// Once the command have successfully ben run, it will
// return a string with the output result of the command.
// TODO: Add concurrent operations to speed things up
func exeCmd(cmd string, wg *sync.WaitGroup) string {
	fmt.Println("Running: ", cmd)
	parts := strings.Fields(cmd)
	head := parts[0]
	parts = parts[1:]

	out, err := exec.Command(head, parts...).Output()
	if err != nil {
		errmsg("%s", err)
	}
	warn("%s", out)
	wg.Done()
	return string(out)
}

// strToSlice takes a string and a delimiter in the
// form of a regex. It will use this to split a string
// into a slice, and return it.
func strToSlice(s string, delimiter string) []string {
	r := regexp.MustCompile("[^\\s]+")
	slice := r.FindAllString(s, -1)
	return slice
}

// Copyright 2017 Jayson Grace. All rights reserved
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
package main

import (
	"fmt"
	"os/exec"
	"regexp"
	"strings"
	"sync"
)

// exeCmd executes an input command.
// Once the command have successfully ben run, it will
// return a string with the output result of the command.
// TODO: Add concurrent operations to speed things up
func exeCmd(cmd string, wg *sync.WaitGroup) string {
	fmt.Println("Running: ", cmd)
	parts := strings.Fields(cmd)
	head := parts[0]
	parts = parts[1:]

	out, err := exec.Command(head, parts...).Output()
	if err != nil {
		errmsg("%s", err)
	}
	warn("%s", out)
	wg.Done()
	return string(out)
}

// strToSlice takes a string and a delimiter in the
// form of a regex. It will use this to split a string
// into a slice, and return it.
func strToSlice(s string, delimiter string) []string {
	r := regexp.MustCompile(delimiter)
	slice := r.FindAllString(s, -1)
	return slice
}

Add delimiter param to strToSlice func


package main

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"io/ioutil"
	"os"
)

func generatePrivateKey(file string) (crypto.PrivateKey, error) {

	privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	if err != nil {
		return nil, err
	}

	keyBytes, err := x509.MarshalECPrivateKey(privateKey)
	if err != nil {
		return nil, err
	}

	pemKey := pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}

	certOut, err := os.Create(file)
	if err != nil {
		return nil, err
	}

	pem.Encode(certOut, &pemKey)
	certOut.Close()

	return privateKey, nil
}

func loadPrivateKey(file string) (crypto.PrivateKey, error) {
	keyBytes, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	keyBlock, _ := pem.Decode(keyBytes)

	switch keyBlock.Type {
	case "RSA PRIVATE KEY":
		x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
	case "EC PRIVATE KEY":
		return x509.ParseECPrivateKey(keyBlock.Bytes)
	}

	return nil, errors.New("Unknown private key type.")
}

package main

import (
	"crypto"
	"crypto/ecdsa"
	"crypto/elliptic"
	"crypto/rand"
	"crypto/x509"
	"encoding/pem"
	"errors"
	"io/ioutil"
	"os"
)

func generatePrivateKey(file string) (crypto.PrivateKey, error) {

	privateKey, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
	if err != nil {
		return nil, err
	}

	keyBytes, err := x509.MarshalECPrivateKey(privateKey)
	if err != nil {
		return nil, err
	}

	pemKey := pem.Block{Type: "EC PRIVATE KEY", Bytes: keyBytes}

	certOut, err := os.Create(file)
	if err != nil {
		return nil, err
	}

	pem.Encode(certOut, &pemKey)
	certOut.Close()

	return privateKey, nil
}

func loadPrivateKey(file string) (crypto.PrivateKey, error) {
	keyBytes, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	keyBlock, _ := pem.Decode(keyBytes)

	switch keyBlock.Type {
	case "RSA PRIVATE KEY":
		return x509.ParsePKCS1PrivateKey(keyBlock.Bytes)
	case "EC PRIVATE KEY":
		return x509.ParseECPrivateKey(keyBlock.Bytes)
	}

	return nil, errors.New("Unknown private key type.")
}

Fix missing return in loadPrivateKey


package util

import (
	"fmt"
	"io"
	"log"
	"os"
)

// Create a logger with the given prefix
func CreateLogger(prefix string) *log.Logger {
	return CreateLoggerWithWriter(os.Stderr, prefix)
	// return log.New(os.Stderr, fmt.Sprintf("[terragrunt] %s", prefix), log.LstdFlags)
}

// CreateLoggerWithWriter Create a lgogger around the given output stream and prefix
func CreateLoggerWithWriter(writer io.Writer, prefix string) *log.Logger {
	if prefix != "" {
		prefix = fmt.Sprintf("[%s] ", prefix)
	}
	return log.New(writer, fmt.Sprintf("[terragrunt] %s", prefix), log.LstdFlags)
}

package util

import (
	"fmt"
	"io"
	"log"
	"os"
)

// Create a logger with the given prefix
func CreateLogger(prefix string) *log.Logger {
	return CreateLoggerWithWriter(os.Stderr, prefix)
}

// CreateLoggerWithWriter Create a lgogger around the given output stream and prefix
func CreateLoggerWithWriter(writer io.Writer, prefix string) *log.Logger {
	if prefix != "" {
		prefix = fmt.Sprintf("[%s] ", prefix)
	}
	return log.New(writer, fmt.Sprintf("[terragrunt] %s", prefix), log.LstdFlags)
}

Remove commented out old logic


/*
Copyright IBM Corp All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package helpers

import (
	"encoding/base32"
	"fmt"
	"strings"

	docker "github.com/fsouza/go-dockerclient"
	"github.com/hyperledger/fabric/common/util"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

func AssertImagesExist(imageNames ...string) {
	dockerClient, err := docker.NewClientFromEnv()
	Expect(err).NotTo(HaveOccurred())

	for _, imageName := range imageNames {
		images, err := dockerClient.ListImages(docker.ListImagesOptions{
			Filter: imageName,
		})
		ExpectWithOffset(1, err).NotTo(HaveOccurred())

		if len(images) != 1 {
			Fail(fmt.Sprintf("missing required image: %s", imageName), 1)
		}
	}
}

// UniqueName generates base-32 enocded UUIDs for container names.
func UniqueName() string {
	name := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(util.GenerateBytesUUID())
	return strings.ToLower(name)
}

/*
Copyright IBM Corp All Rights Reserved.

SPDX-License-Identifier: Apache-2.0
*/

package helpers

import (
	"encoding/base32"
	"fmt"
	"strings"

	docker "github.com/fsouza/go-dockerclient"
	"github.com/hyperledger/fabric/common/util"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

func AssertImagesExist(imageNames ...string) {
	dockerClient, err := docker.NewClientFromEnv()
	Expect(err).NotTo(HaveOccurred())

	for _, imageName := range imageNames {
		images, err := dockerClient.ListImages(docker.ListImagesOptions{
			Filters: map[string][]string{"reference": {imageName}},
		})
		ExpectWithOffset(1, err).NotTo(HaveOccurred())

		if len(images) != 1 {
			Fail(fmt.Sprintf("missing required image: %s", imageName), 1)
		}
	}
}

// UniqueName generates base-32 enocded UUIDs for container names.
func UniqueName() string {
	name := base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(util.GenerateBytesUUID())
	return strings.ToLower(name)
}

Update image filter used by integration tests