package main

import (
	"github.com/pachyderm/pachyderm/src/cmd/pachctl/cmd"
	"github.com/spf13/cobra/doc"
	"go.pedge.io/env"
)

type appEnv struct {
	OutputDir string `env:"OUTPUT_DIR,default=./doc/pachctl"`
}

func main() {
	env.Main(do, &appEnv{})
}

func do(appEnvObj interface{}) error {
	appEnv := appEnvObj.(*appEnv)
	// passing empty addresses for pfsd and ppsd, that's fine because we're not
	// going to execute the command but print docs with it
	rootCmd, err := cmd.PachctlCmd("", "")
	if err != nil {
		return err
	}
	doc.GenMarkdownTree(rootCmd, appEnv.OutputDir)
}

package main

import (
	"github.com/pachyderm/pachyderm/src/cmd/pachctl/cmd"
	"github.com/spf13/cobra/doc"
	"go.pedge.io/env"
)

type appEnv struct {
	OutputDir string `env:"OUTPUT_DIR,default=./doc/pachctl"`
}

func main() {
	env.Main(do, &appEnv{})
}

func do(appEnvObj interface{}) error {
	appEnv := appEnvObj.(*appEnv)
	// passing empty addresses for pfsd and ppsd, that's fine because we're not
	// going to execute the command but print docs with it
	rootCmd, err := cmd.PachctlCmd("", "")
	if err != nil {
		return err
	}
	doc.GenMarkdownTree(rootCmd, appEnv.OutputDir)
	return nil
}

Return nil so it compiles.


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

// nvim-go is a msgpack remote plugin for Neovim
package main

import (
	"log"
	_ "net/http/pprof"
	"os"

	_ "nvim-go/autocmd"
	_ "nvim-go/commands"
	_ "nvim-go/config"
	_ "nvim-go/context"
	_ "nvim-go/nvim"

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

func init() {
	if lf := os.Getenv("NEOVIM_GO_LOG_FILE"); lf != "" {
		f, err := os.OpenFile(lf, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0666)
		if err != nil {
			log.Fatal(err)
		}

		log.SetOutput(f)
	}
}

func main() {
	plugin.Main()
}

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

// nvim-go is a msgpack remote plugin for Neovim
package main

import (
	_ "net/http/pprof"

	_ "nvim-go/autocmd"
	_ "nvim-go/commands"
	_ "nvim-go/config"
	_ "nvim-go/context"
	_ "nvim-go/nvim"

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

func main() {
	plugin.Main()
}

Remove unnecessary log package settings


package cmd

import (
	"syscall"

	"github.com/spf13/cobra"
)

var daemonStopCmd = &cobra.Command{
	Use:   "stop",
	Short: "Stop a daemon",
	Long:  "",
	RunE: func(cmd *cobra.Command, args []string) error {

		syscall.Kill(syscall.Getpid(), syscall.SIGTERM)

		return nil
	},
}

func init() {
	daemon.AddCommand()
}

package cmd

import (
	"github.com/spf13/cobra"
)

var daemonStopCmd = &cobra.Command{
	Use:   "stop",
	Short: "Stop a daemon",
	Long:  "",
	RunE: func(cmd *cobra.Command, args []string) error {
		_, err := restClient.R().Post("/api/v1/stop")
		return err
	},
}

func init() {
	daemon.AddCommand(daemonStopCmd)
}

Add command to stop the daemon


package getter

import (
	"testing"
)

func TestSourceDirSubdir(t *testing.T) {
	cases := []struct {
		Input    string
		Dir, Sub string
	}{
		{
			"hashicorp.com",
			"hashicorp.com", "",
		},
		{
			"hashicorp.com//foo",
			"hashicorp.com", "foo",
		},
		{
			"hashicorp.com//foo?bar=baz",
			"hashicorp.com?bar=baz", "foo",
		},
		{
			"file://foo//bar",
			"file://foo", "bar",
		},
	}

	for i, tc := range cases {
		adir, asub := SourceDirSubdir(tc.Input)
		if adir != tc.Dir {
			t.Fatalf("%d: bad dir: %#v", i, adir)
		}
		if asub != tc.Sub {
			t.Fatalf("%d: bad sub: %#v", i, asub)
		}
	}
}

package getter

import (
	"testing"
)

func TestSourceDirSubdir(t *testing.T) {
	cases := []struct {
		Input    string
		Dir, Sub string
	}{
		{
			"hashicorp.com",
			"hashicorp.com", "",
		},
		{
			"hashicorp.com//foo",
			"hashicorp.com", "foo",
		},
		{
			"hashicorp.com//foo?bar=baz",
			"hashicorp.com?bar=baz", "foo",
		},
		{
			"https://hashicorp.com/path//*?archive=foo",
			"https://hashicorp.com/path?archive=foo", "*",
		},
		{
			"file://foo//bar",
			"file://foo", "bar",
		},
	}

	for i, tc := range cases {
		adir, asub := SourceDirSubdir(tc.Input)
		if adir != tc.Dir {
			t.Fatalf("%d: bad dir: %#v", i, adir)
		}
		if asub != tc.Sub {
			t.Fatalf("%d: bad sub: %#v", i, asub)
		}
	}
}

Test to validate the SourceDirSubdir works as expected with globs


package scanner

func (fs *FileSystem) rebuildPointers() {
	fs.Directory.rebuildPointers(fs)
}

func (directory *Directory) rebuildPointers(fs *FileSystem) {
	for _, file := range directory.FileList {
		file.rebuildPointers(fs)
	}
	for _, dir := range directory.DirectoryList {
		dir.rebuildPointers(fs)
	}
}

func (file *File) rebuildPointers(fs *FileSystem) {
	file.inode = fs.InodeTable[file.InodeNumber]
}

package scanner

func (fs *FileSystem) rebuildPointers() {
	fs.Directory.rebuildPointers(fs)
}

func (directory *Directory) rebuildPointers(fs *FileSystem) {
	for _, file := range directory.RegularFileList {
		file.rebuildPointers(fs)
	}
	for _, file := range directory.FileList {
		file.rebuildPointers(fs)
	}
	for _, dir := range directory.DirectoryList {
		dir.rebuildPointers(fs)
	}
}

func (file *RegularFile) rebuildPointers(fs *FileSystem) {
	file.inode = fs.RegularInodeTable[file.InodeNumber]
}

func (file *File) rebuildPointers(fs *FileSystem) {
	file.inode = fs.InodeTable[file.InodeNumber]
}

Rebuild pointers for regular files.


package cache

type SubsetMatcher struct {
}

func NewSubsetMatcher() *SubsetMatcher {
	return &SubsetMatcher{}
}

func (sm *SubsetMatcher) Match(servers []*ForkServer, imports []string) (*ForkServer, []string, bool) {
	best_fs := servers[0]
	best_score := 0
	best_toCache := imports
	for i := 1; i < len(servers); i++ {
		matched := 0
		toCache := make([]string, 0, 0)
		for j := 0; j < len(imports); j++ {
			if servers[i].Imports[imports[j]] {
				matched += 1
			} else {
				toCache = append(toCache, imports[j])
			}
		}

		// constrain to subset
		if matched > best_score && len(servers[i].Imports) <= matched {
			best_fs = servers[i]
			best_score = matched
			best_toCache = toCache
		}
	}

	return best_fs, best_toCache, best_score != 0
}

package cache

type SubsetMatcher struct {
}

func NewSubsetMatcher() *SubsetMatcher {
	return &SubsetMatcher{}
}

func (sm *SubsetMatcher) Match(servers []*ForkServer, imports []string) (*ForkServer, []string, bool) {
	best_fs := servers[0]
	best_score := -1
	best_toCache := imports
	for i := 1; i < len(servers); i++ {
		matched := 0
		toCache := make([]string, 0, 0)
		for j := 0; j < len(imports); j++ {
			if servers[i].Imports[imports[j]] {
				matched += 1
			} else {
				toCache = append(toCache, imports[j])
			}
		}

		// constrain to subset
		if matched > best_score && len(servers[i].Imports) <= matched {
			best_fs = servers[i]
			best_score = matched
			best_toCache = toCache
		}
	}

	return best_fs, best_toCache, best_score != -1
}

Fix import hit count with 0-package handlers


package main

import (
	"log"
	"os"

	"github.com/Sirupsen/logrus"
)

func init() {
	logrus.SetLevel(logrus.DebugLevel)
}

func main() {
	args := os.Args[1:]
	if len(args) == 0 {
		args = []string{os.Getenv("SHELL")}
	}
	c := &Container{
		Args: args,
		Uid:  os.Getuid(),
		Gid:  os.Getgid(),
	}
	if err := c.Start(); err != nil {
		log.Fatalf("Container start failed: %v", err)
	}
}

package main

import (
	"os"

	log "github.com/Sirupsen/logrus"
)

func init() {
	log.SetLevel(log.DebugLevel)
}

func main() {
	args := os.Args[1:]
	if len(args) == 0 {
		args = []string{os.Getenv("SHELL")}
	}
	c := &Container{
		Args: args,
		Uid:  os.Getuid(),
		Gid:  os.Getgid(),
	}
	if err := c.Start(); err != nil {
		log.Fatalf("Container start failed: %v", err)
	}
}

Use logrus for logging, instead a mix of loggers


package main

import (
	"flag"
	"io/ioutil"
	"log"
	"os"
	"fmt"
)

func main() {
	var version bool
	flag.BoolVar(&version, "v", false, "version string")
	flag.Parse()
	if version {
		fmt.Println("Header: perly.c,v 1.0 87/12/18 15:53:31 root Exp\nPatch level: 0")
		os.Exit(0)
	}

	var sourcetext string
	if len(os.Args) < 2 {
		buf, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			log.Fatal(err)
		}
		sourcetext = string(buf)
	} else {
		buf, err := ioutil.ReadFile(os.Args[1])
		if err != nil {
			fmt.Printf("Perl script \"%v\" doesn't seem to exist.\n", os.Args[1])
			log.Fatal(err)
		}
		sourcetext = string(buf)
	}

	gparser := &Gunie{Buffer: sourcetext}
	gparser.Init()
	err := gparser.Parse()
	if err != nil {
		log.Fatal(err)
	}
	gparser.PrintSyntaxTree()

}

package main

import (
	"flag"
	"io/ioutil"
	"log"
	"os"
	"fmt"
)

func main() {
	var version bool
	flag.BoolVar(&version, "v", false, "version string")
	flag.Parse()
	if version {
		fmt.Println("Header: perly.c,v 1.0 87/12/18 15:53:31 root Exp\nPatch level: 0")
		os.Exit(0)
	}

	var sourcetext string
	if len(os.Args) < 2 {
		buf, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			log.Fatal(err)
		}
		sourcetext = string(buf)
	} else {
		buf, err := ioutil.ReadFile(os.Args[1])
		if err != nil {
			fmt.Printf("Perl script \"%v\" doesn't seem to exist.\n", os.Args[1])
			log.Fatal(err)
		}
		sourcetext = string(buf)
	}

	gparser := &Gunie{Buffer: sourcetext}
	gparser.Init()
	err := gparser.Parse()
	if err != nil {
	        gparser.PrintSyntaxTree()
		log.Fatal(err)
	}
	gparser.PrintSyntaxTree()

}

Print out syntax tree on parse failure, to make it easier to debug where the failure happened.


package preprocess

import (
	"testing"

	"fmt"
	"io"

	localtests "github.com/practicum/sandbox/testing"
)

// reflectionToy is a dummy type created in the preprocess package as a trick to
// retrieve the package name. http://stackoverflow.com/a/25263604/10278
type reflectionToy struct{}

func TestScan(t *testing.T) {
	datapath := localtests.DataAssetFullPath("january.txt", reflectionToy{})
	iterator := NewContentIterator(datapath)

	line, err := iterator()

	for err == nil {
		line, err = iterator()
		fmt.Println(line)
	}

	if err != io.EOF {
		t.Error(err)
	}
}

package preprocess

import (
	"testing"

	"fmt"
	"io"

	localtests "github.com/practicum/sandbox/testing"
)

var sampleTxtFilepath string = localtests.
	DataAssetFullPath("january.txt", reflectionToy{})

// reflectionToy is a dummy type created in the preprocess package as a trick to
// retrieve the package name. http://stackoverflow.com/a/25263604/10278
type reflectionToy struct{}

func TestScan(t *testing.T) {
	datapath := localtests.DataAssetFullPath("january.txt", reflectionToy{})
	iterator := NewContentIterator(datapath)

	_, err := iterator()

	for err == nil {
		_, err = iterator()
	}

	if err != io.EOF {
		t.Error(err)
	}
}

func ExampleNewContentIterator() {
	iterator := NewContentIterator(sampleTxtFilepath)

	line, err := iterator()

	for err == nil {
		fmt.Println(line)
		line, err = iterator()
	}

	if err != io.EOF {
		panic(fmt.Sprintf("Error while iterating over %s.", sampleTxtFilepath))
	}
}

Add an Example func to tests that shows up in godoc.


package main

import (
  "github.com/ricallinson/forgery"
)

func CreateUser(req *f.Request, res *f.Response, next func()) {
  // res.Send("Not implemented yet.")
  res.Send("Unknown error while trying to register user", 400)
}

func Login(req *f.Request, res *f.Response, next func()) {
  res.Send("Not implemented yet.")
}

func UpdateUser(req *f.Request, res *f.Response, next func()) {
  res.Send("Not implemented yet.")
}

package main

import (
  "github.com/ricallinson/forgery"
  "github.com/spacedock-io/index/couch/models"
)

func CreateUser(req *f.Request, res *f.Response, next func()) {
  username, email, password := req.Body["username"], req.Body["email"], req.Body["password"]

  // @TODO: Validate email format

  if len(password) < 5 {
    res.Send("Password too short", 400)
  } else if len(username) < 4 {
    res.Send("Username too short", 400)
  } else if len(username) > 30 {
    res.Send("Username too long", 400)
  } else {
    // put user in couch, send confirm email
    u := models.NewUser()

    u.Username = username
    u.Email = email

    e := models.CreateUser(u, password)
    if (e != nil) {
      // @TODO: Don't just send the whole error here
      res.Send(e, 400)
    }
    res.Send("User created successfully", 200)
    // later on, send an async email
    //go ConfirmEmail()
  }

  res.Send("Unknown error while trying to register user", 400)
}

func Login(req *f.Request, res *f.Response, next func()) {
  // Because of middleware, execution only gets here on success.
  res.Send("OK", 200)
}

func UpdateUser(req *f.Request, res *f.Response, next func()) {
  res.Send("Not implemented yet.")
}

Implement basic signup and login routes


package fizzbuzz

import (
	"fmt"
	"log"
)

func Generate(count int) ([]string, error) {
	if count <= 0 {
		return nil, fmt.Errorf("fizzbuzz: Negative fizzbuzz count provided")
	}

	fizzbuzz := make([]string, count)

	var output string
	for i := 1; i <= count; i++ {
		switch {
		case i%15 == 0:
			output = "FizzBuzz"
		case i%3 == 0:
			output = "Fizz"
		case i%5 == 0:
			output = "Buzz"
		default:
			output = string(i)
		}
		fizzbuzz[i] = output
	}

	return fizzbuzz, nil
}

func Print(count int) {
	fizzbuzz, err := Generate(count)
	if err != nil {
		log.Fatal(err)
	}

	for _, entry := range fizzbuzz {
		fmt.Println(entry)
	}
}

package fizzbuzz

import (
	"fmt"
	"log"
)

func Generate(count int) ([]string, error) {
	if count <= 0 {
		return nil, fmt.Errorf("fizzbuzz: Negative fizzbuzz count provided")
	}

	fizzbuzz := make([]string, count)

	var output string
	for i := 1; i <= count; i++ {
		switch {
		case i%15 == 0:
			output = "FizzBuzz"
		case i%3 == 0:
			output = "Fizz"
		case i%5 == 0:
			output = "Buzz"
		default:
			output = fmt.Sprintf("%d", i)
		}
		fizzbuzz[i-1] = output
	}

	return fizzbuzz, nil
}

func Print(count int) {
	fizzbuzz, err := Generate(count)
	if err != nil {
		log.Fatal(err)
	}

	for _, entry := range fizzbuzz {
		fmt.Println(entry)
	}
}

Fix off by one and string conversion


// Copyright (c) 2010 The Grumble Authors
// The use of this source code is goverened by a BSD-style
// license that can be found in the LICENSE-file.

package main

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

var help *bool = flag.Bool("help", false, "Show this help")
var port *int = flag.Int("port", 64738, "Default port to listen on")
var host *string = flag.String("host", "0.0.0.0", "Default host to listen on")

func usage() {
	fmt.Fprintf(os.Stderr, "usage: grumble [options]\n")
	flag.PrintDefaults()
}

func main() {
	flag.Parse()
	if *help == true {
		usage()
		return
	}

	// Create our default server
	m, err := NewServer(*host, *port)
	if err != nil {
		return
	}

	// And launch it.
	go m.ListenAndMurmur()

	// Listen forever
	sleeper := make(chan int)
	zzz := <-sleeper
	if zzz > 0 {
	}
}

// Copyright (c) 2010 The Grumble Authors
// The use of this source code is goverened by a BSD-style
// license that can be found in the LICENSE-file.

package main

import (
	"flag"
	"fmt"
	"os"
	"log"
	"mumbleproto"
	"goprotobuf.googlecode.com/hg/proto"
)

var help *bool = flag.Bool("help", false, "Show this help")
var port *int = flag.Int("port", 64738, "Default port to listen on")
var host *string = flag.String("host", "0.0.0.0", "Default host to listen on")

func usage() {
	fmt.Fprintf(os.Stderr, "usage: grumble [options]\n")
	flag.PrintDefaults()
}

// Check that we're using a version of goprotobuf that is able to
// correctly encode empty byte slices.
func checkProtoLib() {
	us := &mumbleproto.UserState{}
	us.Texture = []byte{}
	d, _ := proto.Marshal(us)
	nus := &mumbleproto.UserState{}
	proto.Unmarshal(d, nus)
	if nus.Texture == nil {
		log.Exitf("Unpatched version of goprotobuf. Grumble is refusing to run.")
	}
}

func main() {
	flag.Parse()
	if *help == true {
		usage()
		return
	}

	checkProtoLib()

	// Create our default server
	m, err := NewServer(*host, *port)
	if err != nil {
		return
	}

	// And launch it.
	go m.ListenAndMurmur()

	// Listen forever
	sleeper := make(chan int)
	zzz := <-sleeper
	if zzz > 0 {
	}
}

Add checks for buggy goprotobuf.


package main

import (
	"fmt"

	"github.com/caelifer/data-structures-in-go/btree/tree"
)

type IntNode int

func (n IntNode) Less(other tree.Node) bool {
	// TODO: need to handle type assertion error
	return n < other.(IntNode)
}

type StringNode string

func (n StringNode) Less(other tree.Node) bool {
	// TODO: need to handle type assertion error
	return n < other.(StringNode)
}

func main() {
	intBT := tree.New()
	intBT.Insert(IntNode(5))
	intBT.Insert(IntNode(1))
	intBT.Insert(IntNode(7))
	intBT.Insert(IntNode(2))
	intBT.Insert(IntNode(4))
	intBT.Insert(IntNode(6))
	intBT.Insert(IntNode(3))
	intBT.Walk(func(n tree.Node) {
		fmt.Println(n)
	})

	stringBT := tree.New()
	stringBT.Insert(StringNode("ello"))
	stringBT.Insert(StringNode("der"))
	stringBT.Insert(StringNode("ost"))
	stringBT.Insert(StringNode("a"))
	stringBT.Insert(StringNode("cy"))
	stringBT.Insert(StringNode("z"))
	stringBT.Insert(StringNode("j"))
	stringBT.Walk(func(n tree.Node) {
		fmt.Println(n)
	})
}

package main

import (
	"fmt"

	"github.com/caelifer/data-structures-in-go/btree/tree"
)

type IntNode int

func (n IntNode) Less(other tree.Node) bool {
	// TODO: need to handle type assertion error
	return n < other.(IntNode)
}

type StringNode string

func (n StringNode) Less(other tree.Node) bool {
	// TODO: need to handle type assertion error
	return n < other.(StringNode)
}

func Println(n tree.Node) {
	fmt.Println(n)
}

func main() {
	intBT := tree.New()
	intBT.Insert(IntNode(5))
	intBT.Insert(IntNode(1))
	intBT.Insert(IntNode(7))
	intBT.Insert(IntNode(2))
	intBT.Insert(IntNode(4))
	intBT.Insert(IntNode(6))
	intBT.Insert(IntNode(3))
	intBT.Walk(Println)

	stringBT := tree.New()
	stringBT.Insert(StringNode("ello"))
	stringBT.Insert(StringNode("der"))
	stringBT.Insert(StringNode("ost"))
	stringBT.Insert(StringNode("a"))
	stringBT.Insert(StringNode("cy"))
	stringBT.Insert(StringNode("z"))
	stringBT.Insert(StringNode("j"))
	stringBT.Walk(Println)
}

Use function reference as a lambda in tree.Walk() argument


package lifecycle

var defaultManager *Manager

func init() {
	defaultManager = NewManager()
}

// Register registers the argument to the global default one.
func Register(f func()) *Manager {
	return defaultManager.Register(f)
}

// RegisterChannel registers the argument to the global default one.
func RegisterChannel(in chan<- interface{}, out <-chan interface{}) *Manager {
	return defaultManager.RegisterChannel(in, out)
}

// Stop stops the global default one.
func Stop() {
	defaultManager.Stop()
}

// GetDefaultManager returns the default global Manager.
func GetDefaultManager() *Manager {
	return defaultManager
}

// IsStop returns true if the default global manager, or false.
func IsStop() bool {
	return defaultManager.IsStop()
}

Add IsStop to the global lifecycle manager


package pow

// TODO: Unwrap recursion
func Mod(x, p, n int) int {
	switch {
	case p == 0:
		return 1
	case p == 1:
		return x % n
	case p%2 == 0:
		return Mod((x*x)%n, p/2, n)
	}
	return (x * Mod((x*x)%n, (p-1)/2, n)) % n
}

package pow

// TODO: Unwrap recursion
func Mod(x, p, n int) int {
	switch {
	case p == 0:
		return 1
	case p == 1:
		return x % n
	case p%2 == 0:
		return Mod((x*x)%n, p/2, n) % n
	}
	return (x * Mod((x*x)%n, (p-1)/2, n)) % n
}

Fix a mistake with large mods.


package binary

import "testing"

type binaryTest struct {
	binary   string
	expected int
}

var binaryTests = []binaryTest{
	{"1", 1}, {"10", 2}, {"11", 3},
	{"100", 4}, {"1001", 9}, {"10001101000", 1128},
	{"12", 0},
}

func TestBinary(t *testing.T) {
	for _, test := range binaryTests {
		actual := ToDecimal(test.binary)
		if actual != test.expected {
			t.Errorf("ToDecimal(%d): expected %d, actual %d", test.binary, test.expected, actual)
		}
	}
}

package binary

import "testing"

var testCases = []struct {
	binary   string
	expected int
}{
	{"1", 1},
	{"10", 2},
	{"11", 3},
	{"100", 4},
	{"1001", 9},
	{"10001101000", 1128},
	{"12", 0},
}

func TestBinary(t *testing.T) {
	for _, tt := range testCases {
		actual := ToDecimal(tt.binary)
		if actual != tt.expected {
			t.Fatalf("ToDecimal(%d): expected %d, actual %d", tt.binary, tt.expected, actual)
		}
	}
}

Simplify table tests in Go 'binary' exercise.


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

package cmd

import (
	"github.com/spf13/cobra"

	"github.com/swarmdotmarket/perigord/migration"
	perigord "github.com/swarmdotmarket/perigord/perigord/cmd"
)

var migrateCmd = &cobra.Command{
	Use: "migrate",
	Run: func(cmd *cobra.Command, args []string) {
		if err := migration.RunMigrations(); err != nil {
			perigord.Fatal(err)
		}
	},
}

func init() {
	RootCmd.AddCommand(migrateCmd)
}

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

package cmd

import (
	"context"

	"github.com/spf13/cobra"

	"github.com/swarmdotmarket/perigord/migration"
	perigord "github.com/swarmdotmarket/perigord/perigord/cmd"
)

var migrateCmd = &cobra.Command{
	Use: "migrate",
	Run: func(cmd *cobra.Command, args []string) {
		if err := migration.RunMigrations(context.Background()); err != nil {
			perigord.Fatal(err)
		}
	},
}

func init() {
	RootCmd.AddCommand(migrateCmd)
}

Fix compilation issue in stub


// +build !windows

package main

import (
	"os"
	"syscall"
	"time"
)

func restart() {
	syscall.Kill(os.Getpid(), syscall.SIGHUP)
	time.Sleep(10 * time.Millisecond)
}

// +build !windows

package main

import (
	"os"
	"syscall"
	"time"
)

func restart() {
	syscall.Kill(os.Getpid(), syscall.SIGHUP)
	time.Sleep(100 * time.Millisecond)
}

Extend wait duration to stabilize tests.


// Code from my dotGo.eu 2014 presentation
//
// Copyright (c) 2014 John Graham-Cumming
//
// Implement a factory and a task. Call run() on your factory.

package main

import (
	"bufio"
	"log"
	"os"
	"sync"
)

type task interface {
	process()
	print()
}

type factory interface {
	make(line string) task
}

func run(f factory) {
	var wg sync.WaitGroup

	in := make(chan task)

	wg.Add(1)
	go func() {
		s := bufio.NewScanner(os.Stdin)
		for s.Scan() {
			in <- f.make(s.Text())
		}
		if s.Err() != nil {
			log.Fatalf("Error reading STDIN: %s", s.Err())
		}
		close(in)
		wg.Done()
	}()

	out := make(chan task)

	go func() {
		for t := range out {
			t.print()
		}
	}()

	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			for t := range in {
				t.process()
				out <- t
			}
			wg.Done()
		}()
	}

	wg.Wait()
	close(out)
}

func main() {
	// run(&myFactory{})
}

// Code from my dotGo.eu 2014 presentation
//
// Copyright (c) 2014 John Graham-Cumming
//
// Implement a factory and a task. Call run() on your factory.

package main

import (
	"bufio"
	"log"
	"os"
	"sync"
)

type task interface {
	process()
	print()
}

type factory interface {
	make(line string) task
}

func run(f factory) {
	var wg sync.WaitGroup

	in := make(chan task)

	wg.Add(1)
	go func() {
		s := bufio.NewScanner(os.Stdin)
		for s.Scan() {
			in <- f.make(s.Text())
		}
		if s.Err() != nil {
			log.Fatalf("Error reading STDIN: %s", s.Err())
		}
		close(in)
		wg.Done()
	}()

	out := make(chan task)

	for i := 0; i < 1000; i++ {
		wg.Add(1)
		go func() {
			for t := range in {
				t.process()
				out <- t
			}
			wg.Done()
		}()
	}

	go func() {
		wg.Wait()
		close(out)
	}()

	for t := range out {
		t.print()
	}
}

func main() {
	// run(&myFactory{})
}

Add improvement from eneff that makes program terminate more cleanly


package main

import (
	"errors"
	"fmt"
)

var cmdRemove = &Command{
	Run:       runRemove,
	UsageLine: "remove NAME",
	Short:     "Remove saved password",
	Long:      `Remove saved password by input name.`,
}

func runRemove(ctx context, args []string) error {
	if len(args) == 0 {
		return errors.New("item name required")
	}
	cfg, err := GetConfig()
	if err != nil {
		return err
	}
	Initialize(cfg)
	is, err := LoadItems(cfg.DataFile)
	if err != nil {
		return err
	}

	name := args[0]
	fit := is.Find(name)
	if fit == nil {
		return fmt.Errorf("item not found: %s", name)
	}

	nis := Items(make([]Item, len(is)-1))
	for _, it := range is {
		if it.Name != fit.Name {
			nis = append(nis, it)
		}
	}
	nis.Save(cfg.DataFile)
	fmt.Fprintln(ctx.out, fmt.Sprintf("password of '%s' is removed successfully", name))
	return nil
}

package main

import (
	"errors"
	"fmt"
)

var cmdRemove = &Command{
	Run:       runRemove,
	UsageLine: "remove NAME",
	Short:     "Remove saved password",
	Long:      `Remove saved password by input name.`,
}

func runRemove(ctx context, args []string) error {
	if len(args) == 0 {
		return errors.New("item name required")
	}
	cfg, err := GetConfig()
	if err != nil {
		return err
	}
	Initialize(cfg)
	is, err := LoadItems(cfg.DataFile)
	if err != nil {
		return err
	}

	name := args[0]
	fit := is.Find(name)
	if fit == nil {
		return fmt.Errorf("item not found: %s", name)
	}

	nis := Items([]Item{})
	for _, it := range is {
		if it.Name != fit.Name {
			nis = append(nis, it)
		}
	}
	nis.Save(cfg.DataFile)
	fmt.Fprintln(ctx.out, fmt.Sprintf("password of '%s' is removed successfully", name))
	return nil
}

Fix create empty item on remove


package main

import (
	"fmt"
	"net/http"

	"github.com/codegangsta/negroni"
	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		fmt.Fprint(rw, "hello")
	})

	// Middleware stack
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
	)

	n.UseHandler(r)

	n.Run(":3000")
}

package main

import (
	"fmt"
	"net/http"

	"github.com/codegangsta/negroni"
	"github.com/gorilla/mux"
)

func main() {
	r := mux.NewRouter()
	r.HandleFunc("/", func(rw http.ResponseWriter, r *http.Request) {
		fmt.Fprint(rw, "hello")
	})

	// Middleware stack
	n := negroni.New(
		negroni.NewRecovery(),
		negroni.NewLogger(),
	)

	n.UseHandler(r)

	n.Run(":8080")
}

Change server port to 8080 to use gin Because gin's default port is 3000


package isogram

import "strings"

// IsIsogram returns whether the provided string is an isogram.
// In other words, whether the string does not contain any duplicate characters.
func IsIsogram(s string) bool {
	parsed := strings.ToLower(removeWhitespaceAndHyphens(s))
	seen := make(map[rune]bool)
	for _, c := range parsed {
		if (seen[c]) == true {
			return false
		}
		seen[c] = true
	}
	return true
}

func removeWhitespaceAndHyphens(s string) string {
	return strings.Map(func(r rune) rune {
		if r == ' ' || r == '-' {
			return -1
		}
		return r
	}, s)
}

package isogram

import (
	"strings"
	"unicode"
)

// IsIsogram returns whether the provided string is an isogram.
// In other words, whether the string does not contain any duplicate characters.
func IsIsogram(s string) bool {
	parsed := strings.ToLower(preserveOnlyLetters(s))
	seen := make(map[rune]bool)
	for _, c := range parsed {
		if (seen[c]) == true {
			return false
		}
		seen[c] = true
	}
	return true
}

func preserveOnlyLetters(s string) string {
	return strings.Map(func(r rune) rune {
		if unicode.IsLetter(r) {
			return r
		}
		return -1
	}, s)
}

Modify solution to preserve letters


package graval

import (
	. "github.com/smartystreets/goconvey/convey"
	"os"
	"testing"
	"time"
)

type TestFileInfo struct{}

func (t *TestFileInfo) Name() string {
	return "file1.txt"
}

func (t *TestFileInfo) Size() int64 {
	return 99
}

func (t *TestFileInfo) Mode() os.FileMode {
	return os.ModeSymlink
}

func (t *TestFileInfo) IsDir() bool {
	return false
}

func (t *TestFileInfo) ModTime() time.Time {
	return time.Now()
}

func (t *TestFileInfo) Sys() interface{} {
	return nil
}

var files []os.FileInfo = []os.FileInfo{
	&TestFileInfo{}, &TestFileInfo{},
}

func TestShortFormat(t *testing.T) {
	formatter := newListFormatter(files)
	Convey("The Short listing format", t, func() {
		Convey("Will display correctly", func() {
			So(formatter.Short(), ShouldEqual, "file1.txt\r\nfile1.txt\r\n\r\n")
		})
	})
}

package graval

import (
	. "github.com/smartystreets/goconvey/convey"
	"os"
	"testing"
	"time"
)

type TestFileInfo struct{}

func (t *TestFileInfo) Name() string {
	return "file1.txt"
}

func (t *TestFileInfo) Size() int64 {
	return 99
}

func (t *TestFileInfo) Mode() os.FileMode {
	return os.ModeSymlink
}

func (t *TestFileInfo) IsDir() bool {
	return false
}

func (t *TestFileInfo) ModTime() time.Time {
	return time.Unix(1, 0)
}

func (t *TestFileInfo) Sys() interface{} {
	return nil
}

var files []os.FileInfo = []os.FileInfo{
	&TestFileInfo{}, &TestFileInfo{},
}

func TestShortFormat(t *testing.T) {
	formatter := newListFormatter(files)
	Convey("The Short listing format", t, func() {
		Convey("Will display correctly", func() {
			So(formatter.Short(), ShouldEqual, "file1.txt\r\nfile1.txt\r\n\r\n")
		})
	})
}

func TestDetailedFormat(t *testing.T) {
	formatter := newListFormatter(files)
	Convey("The Detailed listing format", t, func() {
		Convey("Will display correctly", func() {
			So(formatter.Detailed(), ShouldEqual, "L--------- 1 owner group           99 Jan 01 10:00 file1.txt\r\nL--------- 1 owner group           99 Jan 01 10:00 file1.txt\r\n\r\n")
		})
	})
}

Add test for detailed listformatter.


package process

import (
	"os/exec"

	"github.com/gonuts/go-shlex"
	"github.com/yosisa/pave/template"
)

type Command struct {
	Template    string
	PrepareFunc func(*exec.Cmd)
	Cmd         *exec.Cmd
}

func NewCommand(cmd string) *Command {
	return &Command{Template: cmd}
}

func (c *Command) Start() error {
	command := template.Render("", c.Template)
	args, err := shlex.Split(command)
	if err != nil {
		return err
	}

	c.Cmd = exec.Command(args[0], args[1:]...)
	if c.PrepareFunc != nil {
		c.PrepareFunc(c.Cmd)
	}

	return c.Cmd.Start()
}

func (c *Command) Wait() error {
	return c.Cmd.Wait()
}

package process

import (
	"os/exec"

	"code.google.com/p/go-shlex"
	"github.com/yosisa/pave/template"
)

type Command struct {
	Template    string
	PrepareFunc func(*exec.Cmd)
	Cmd         *exec.Cmd
}

func NewCommand(cmd string) *Command {
	return &Command{Template: cmd}
}

func (c *Command) Start() error {
	command := template.Render("", c.Template)
	args, err := shlex.Split(command)
	if err != nil {
		return err
	}

	c.Cmd = exec.Command(args[0], args[1:]...)
	if c.PrepareFunc != nil {
		c.PrepareFunc(c.Cmd)
	}

	return c.Cmd.Start()
}

func (c *Command) Wait() error {
	return c.Cmd.Wait()
}

Use another version of go-shlex


package integration_test

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

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

	bmtestutils "github.com/cloudfoundry/bosh-micro-cli/testutils"
)

var testCpiFilePath string

func TestIntegration(t *testing.T) {
	RegisterFailHandler(Fail)
	BeforeSuite(func() {
		err := bmtestutils.BuildExecutable()
		Expect(err).NotTo(HaveOccurred())

		testCpiFilePath, err = bmtestutils.DownloadTestCpiRelease(os.Getenv("CPI_RELEASE_URL"))
		Expect(err).NotTo(HaveOccurred())
	})

	var (
		homePath string
		oldHome  string
	)
	BeforeEach(func() {
		oldHome = os.Getenv("HOME")

		var err error
		homePath, err = ioutil.TempDir("", "micro-bosh-cli-integration")
		Expect(err).NotTo(HaveOccurred())
		os.Setenv("HOME", homePath)
	})

	AfterEach(func() {
		os.Setenv("HOME", oldHome)
		os.RemoveAll(homePath)
	})

	AfterSuite(func() {
		os.Remove(testCpiFilePath)
	})

	RunSpecs(t, "bosh-micro-cli Integration Suite")
}

package integration_test

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

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

	bmtestutils "github.com/cloudfoundry/bosh-micro-cli/testutils"
)

var testCpiFilePath string

func TestIntegration(t *testing.T) {
	RegisterFailHandler(Fail)
	BeforeSuite(func() {
		err := bmtestutils.BuildExecutable()
		Expect(err).NotTo(HaveOccurred())

		testCpiFilePath, err = bmtestutils.DownloadTestCpiRelease("")
		Expect(err).NotTo(HaveOccurred())
	})

	var (
		homePath string
		oldHome  string
	)
	BeforeEach(func() {
		oldHome = os.Getenv("HOME")

		var err error
		homePath, err = ioutil.TempDir("", "micro-bosh-cli-integration")
		Expect(err).NotTo(HaveOccurred())
		os.Setenv("HOME", homePath)
	})

	AfterEach(func() {
		os.Setenv("HOME", oldHome)
		os.RemoveAll(homePath)
	})

	AfterSuite(func() {
		os.Remove(testCpiFilePath)
	})

	RunSpecs(t, "bosh-micro-cli Integration Suite")
}

Remove environment variable in integration test suit


package main

import (
	"hash/fnv"
	"io"
)

// FetchWebsiteChecksum downloads the resource at url,
// and returns an fnv hash of its content.
func FetchWebsiteChecksum(FetchWebsiteChecksum Fetcher, url string) (uint64, error) {
	website, err := FetchWebsiteChecksum.Fetch(url)
	if err != nil {
		return 0, err
	}
	defer website.Close()

	hash := fnv.New64()
	_, err = io.Copy(hash, website)
	if err != nil {
		return 0, err
	}

	return hash.Sum64(), nil
}

// WebsiteChangeAgent records when the content of a
// website has changed.
type WebsiteChangeAgent struct {
	lastChecksum uint64
}

package main

import (
	"hash/fnv"
	"io"
)

// FetchWebsiteChecksum downloads the resource at url,
// and returns an fnv hash of its content.
func FetchWebsiteChecksum(fetcher Fetcher, url string) (uint64, error) {
	website, err := fetcher.Fetch(url)
	if err != nil {
		return 0, err
	}
	defer website.Close()

	hash := fnv.New64()
	_, err = io.Copy(hash, website)
	if err != nil {
		return 0, err
	}

	return hash.Sum64(), nil
}

// WebsiteChangeAgent records when the content of a
// website has changed.
type WebsiteChangeAgent struct {
	lastChecksum uint64
}

Fix name of FetchWebsiteChecksum parameter


package server

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

	"github.com/gorilla/mux"
)

var hostname = flag.String("hostname", "localhost", "The hostname - defaults to localhost")

func Serve() {
	fmt.Println("Starting webserver on :80")
	fmt.Println(*hostname)
	r := mux.NewRouter()
	s := r.Host(*hostname).Subrouter()
	s.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
	s = r.Host("blog." + *hostname).Subrouter()
	s.PathPrefix("/").Handler(http.FileServer(http.Dir("./blog/static/")))
	http.Handle("/", r)
	http.ListenAndServe(":80", nil)
}

package server

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

	"github.com/gorilla/mux"
)

var hostname = flag.String("hostname", "localhost", "The hostname to use for routing.")

func Serve() {
	flag.Parse()

	r := mux.NewRouter()
	s := r.Host(*hostname).Subrouter()
	s.PathPrefix("/").Handler(http.FileServer(http.Dir("./static/")))
	s = r.Host("blog." + *hostname).Subrouter()
	s.PathPrefix("/").Handler(http.FileServer(http.Dir("./blog/static/")))
	http.Handle("/", r)

	fmt.Println("Starting webserver on :80")
	http.ListenAndServe(":80", nil)
}

Add flag parsing, remove debug line.


package main

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

type JsonData struct {
  Name string `json:"name"`
  Struct struct {
    Integer int `json:"integer"`
  } `json:"struce"`
}

func main() {
  http.HandleFunc("/", hello)
  http.ListenAndServe(":8001", nil)
}

func hello(writer http.ResponseWriter, reader *http.Request) {
  file, err := ioutil.ReadFile("simple-http.json")
  if err != nil {
    fmt.Println(err)
  }

  var data JsonData

  decoder := json.NewDecoder(file)

  decoded := decoder.Decode(&data)

  writer.Write(decoded)
}

package main

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

type JsonData struct {
	Name   string `json:"name"`
	Struct struct {
		Integer int `json:"integer"`
	} `json:"struce"`
}

func main() {
	http.HandleFunc("/", hello)
	http.ListenAndServe(":8001", nil)
}

func hello(w http.ResponseWriter, r *http.Request) {
	file, err := ioutil.ReadFile("simple-http.json")
	if err != nil {
		fmt.Println(err)
	}

	var data JsonData

	json.Unmarshal(file, &data)

	w.Write(data)
}

Format and update http example


package mc

type ProjectDB interface {
	Project() *Project
	UpdateProject(project *Project) error
	InsertDirectory(dir *Directory) (*Directory, error)
	UpdateDirectory(dir *Directory) error
	Directories() []Directory
	Ls(dir Directory) []File
	InsertFile(f *File) (*File, error)
	FindFile(fileName string, dirID int64) (*File, error)
	UpdateFile(f *File) error
	FindDirectory(path string) (*Directory, error)
	Clone() ProjectDB
}

type ProjectDBSpec struct {
	Name      string
	ProjectID string
	Path      string
}

type ProjectOpenFlags int

type ProjectDBOpener interface {
	CreateProjectDB(dbSpec ProjectDBSpec) (ProjectDB, error)
	OpenProjectDB(name string) (ProjectDB, error)
	PathToName(path string) string
}

type ProjectDBLister interface {
	// All returns a list of the known ProjectDBs. The ProjectDBs
	// are open.
	All() ([]ProjectDB, error)

	// Create will create a new local project and populate
	// the default database entries. The returned ProjectDB
	// has already been opened.
	Create(dbSpec ProjectDBSpec) (ProjectDB, error)
}

type Configer interface {
	APIKey() string
	ConfigDir() string
	ConfigFile() string
}

package mc

type ProjectDB interface {
	Project() *Project
	UpdateProject(project *Project) error
	InsertDirectory(dir *Directory) (*Directory, error)
	UpdateDirectory(dir *Directory) error
	Directories() []Directory
	Ls(dir Directory) []File
	InsertFile(f *File) (*File, error)
	FindFile(fileName string, dirID int64) (*File, error)
	UpdateFile(f *File) error
	FindDirectory(path string) (*Directory, error)
	Clone() ProjectDB
}

type ProjectDBSpec struct {
	Name      string
	ProjectID string
	Path      string
}

type ProjectOpenFlags int

type ProjectDBOpener interface {
	CreateProjectDB(dbSpec ProjectDBSpec) (ProjectDB, error)
	OpenProjectDB(name string) (ProjectDB, error)
	ProjectExists(name string) bool
	PathToName(path string) string
}

type ProjectDBLister interface {
	// All returns a list of the known ProjectDBs. The ProjectDBs
	// are open.
	All() ([]ProjectDB, error)

	// Create will create a new local project and populate
	// the default database entries. The returned ProjectDB
	// has already been opened.
	Create(dbSpec ProjectDBSpec) (ProjectDB, error)
}

type Configer interface {
	APIKey() string
	ConfigDir() string
	ConfigFile() string
}

Add ProjectExists to ProjectDBOpener interface.


package main

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

func optionsOk(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("access-control-allow-origin", "*")
		w.Header().Set("access-control-allow-methods", "GET, POST, PATCH, DELETE")
		w.Header().Set("access-control-allow-headers", "accept, content-type")
		if r.Method == "OPTIONS" {
			return // Preflight sets headers and we're done
		}
		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func contentTypeJsonHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func loggingHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		t1 := time.Now()
		next.ServeHTTP(w, r)
		t2 := time.Now()
		log.Printf("[%s] %q %v\n", r.Method, r.URL.String(), t2.Sub(t1))
	}

	return http.HandlerFunc(fn)
}

func commonHandlers(next http.HandlerFunc) http.Handler {
	return loggingHandler(contentTypeJsonHandler(optionsOk(next)))
}

package main

import (
	"net/http"
)

func optionsOk(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("access-control-allow-origin", "*")
		w.Header().Set("access-control-allow-methods", "GET, POST, PATCH, DELETE")
		w.Header().Set("access-control-allow-headers", "accept, content-type")
		if r.Method == "OPTIONS" {
			return // Preflight sets headers and we're done
		}
		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func contentTypeJsonHandler(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json; charset=UTF-8")
		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}

func commonHandlers(next http.HandlerFunc) http.Handler {
	return contentTypeJsonHandler(optionsOk(next))
}

Remove the logging handler since heroku's log is good enough


// A facebook graph api client in go.
// https://github.com/huandu/facebook/
//
// Copyright 2012 - 2015, Huan Du
// Licensed under the MIT license
// https://github.com/huandu/facebook/blob/master/LICENSE

package facebook

// Error represents Facebook API error.
type Error struct {
	Message      string
	Type         string
	Code         int
	ErrorSubcode int // subcode for authentication related errors.
}

// Error returns error string.
func (e *Error) Error() string {
	return e.Message
}

// A facebook graph api client in go.
// https://github.com/huandu/facebook/
//
// Copyright 2012 - 2015, Huan Du
// Licensed under the MIT license
// https://github.com/huandu/facebook/blob/master/LICENSE

package facebook

// Error represents Facebook API error.
type Error struct {
	Message      string
	Type         string
	Code         int
	ErrorSubcode int // subcode for authentication related errors.
	UserTitle    string `json:"error_user_title"`
	UserMessage  string `json:"error_user_msg"`
	IsTransient  string `json:"is_transient"`
	TraceID      string `json:"fbtrace_id"`
}

// Error returns error string.
func (e *Error) Error() string {
	return e.Message
}

Extend Error to add Marketing/Insights API fields


/*
This package is just a collection of test cases
 */
package main

import (
    "fmt"
    "os"
    "ripe-atlas"
)

func main() {
	p, err := atlas.GetProbe(14037)
	if err != nil {
		fmt.Printf("err: %v", err)
		os.Exit(1)
	}
	fmt.Printf("p: %#v\n", p)

	q, err := atlas.GetProbes()
	if err != nil {
		fmt.Printf("err: %v", err)
		os.Exit(1)
	}
	fmt.Printf("q: %#v\n", q)

}

/*
This package is just a collection of test cases
*/
package main

import (
	"fmt"
	"github.com/codegangsta/cli"
	"os"
	"ripe-atlas"
	"strconv"
)

// set args for examples sake

func main() {
	app := cli.NewApp()
	app.Name = "atlas"
	app.Commands = []cli.Command{
		{
			Name:        "probes",
			Aliases:     []string{"p"},
			Usage:       "use it to see a description",
			Description: "This is how we describe hello the function",
			Subcommands: []cli.Command{
				{
					Name:        "list",
					Aliases:     []string{"ls"},
					Usage:       "lists all probes",
					Description: "greets someone in english",
					Action: func(c *cli.Context) error {
						q, err := atlas.GetProbes()
						if err != nil {
							fmt.Printf("err: %v", err)
							os.Exit(1)
						}
						fmt.Printf("q: %#v\n", q)

						return nil
					},
				},
				{
					Name:        "info",
					Usage:       "info for one probe",
					Description: "gives info for one probe",
					Flags: []cli.Flag{
						cli.IntFlag{
							Name:  "id",
							Value: 0,
							Usage: "id of the probe",
						},
					},
					Action: func(c *cli.Context) error {
						args := c.Args()
						id, _ := strconv.ParseInt(args[0], 10, 32)

						p, err := atlas.GetProbe(int(id))
						if err != nil {
							fmt.Printf("err: %v", err)
							os.Exit(1)
						}
						fmt.Printf("p: %#v\n", p)

						return nil
					},
				},
			},
		},
	}
	app.Run(os.Args)

}

Move to cli to manage flags/cmd/subcmd.


package main

import (
	"bytes"
	"flag"
	"fmt"
	"github.com/cadena-monde/slackbot"
	"os"
	"strings"
)

var (
	channel, message string
	stdin            bool
	slackURL         = os.Getenv("SLACKBOT_URL")
	token            = os.Getenv("SLACKBOT_TOKEN")
)

func main() {
	parseFlags()
	if stdin {
		readFromStdin()
	}
	postMessage()
}

func readFromStdin() {
	input := bytes.NewBuffer([]byte{})
	input.ReadFrom(os.Stdin)

	inputString := input.String()
	if inputString != "" {
		message = fmt.Sprintf("%s\n```%s```", message, input.String())
		message = strings.Replace(message, "\r", "", -1)
	}
}

func parseFlags() {
	flag.StringVar(&channel, "channel", "", "Channel. Ex: #random")
	flag.StringVar(&message, "message", "", "Message to be sent to the channel")
	flag.BoolVar(&stdin, "stdin", false, "Read message from stdin")
	flag.Parse()

	if channel == "" || (message == "" && !stdin) {
		flag.Usage()
		os.Exit(1)
	}
}

func postMessage() {
	b := slackbot.New(slackURL, token)
	b.PostMessage(channel, message)
}

package main

import (
	"bytes"
	"flag"
	"fmt"
	"github.com/cadena-monde/slackbot"
	"os"
	"strings"
)

var (
	channel, message string
	stdin            bool
	slackURL         = os.Getenv("SLACKBOT_URL")
	token            = os.Getenv("SLACKBOT_TOKEN")
)

func main() {
	parseFlags()
	if stdin {
		readFromStdin()
	}
	postMessage()
}

func readFromStdin() {
	input := bytes.NewBuffer([]byte{})
	input.ReadFrom(os.Stdin)

	inputString := input.String()
	if inputString != "" {
		message = fmt.Sprintf("%s\n```%s```", message, inputString)
		message = strings.Replace(message, "\r", "", -1)
	}
}

func parseFlags() {
	flag.StringVar(&channel, "channel", "", "Channel. Ex: #random")
	flag.StringVar(&message, "message", "", "Message to be sent to the channel")
	flag.BoolVar(&stdin, "stdin", false, "Read message from stdin")
	flag.Parse()

	if channel == "" || (message == "" && !stdin) {
		flag.Usage()
		os.Exit(1)
	}
}

func postMessage() {
	b := slackbot.New(slackURL, token)
	b.PostMessage(channel, message)
}

Read input from variable, not from buffer again


package retrystrategy

import (
	"time"

	boshlog "github.com/cloudfoundry/bosh-utils/logger"
)

type attemptRetryStrategy struct {
	maxAttempts int
	delay       time.Duration
	retryable   Retryable
	logger      boshlog.Logger
	logTag      string
}

func NewAttemptRetryStrategy(
	maxAttempts int,
	delay time.Duration,
	retryable Retryable,
	logger boshlog.Logger,
) RetryStrategy {
	return &attemptRetryStrategy{
		maxAttempts: maxAttempts,
		delay:       delay,
		retryable:   retryable,
		logger:      logger,
		logTag:      "attemptRetryStrategy",
	}
}

func (s *attemptRetryStrategy) Try() error {
	var err error
	var isRetryable bool

	for i := 0; i < s.maxAttempts; i++ {
		s.logger.Debug(s.logTag, "Making attempt #%d", i)

		isRetryable, err = s.retryable.Attempt()
		if err == nil {
			return nil
		}

		if !isRetryable {
			return err
		}

		time.Sleep(s.delay)
	}

	return err
}

package retrystrategy

import (
	"reflect"
	"time"

	boshlog "github.com/cloudfoundry/bosh-utils/logger"
)

type attemptRetryStrategy struct {
	maxAttempts int
	delay       time.Duration
	retryable   Retryable
	logger      boshlog.Logger
	logTag      string
}

func NewAttemptRetryStrategy(
	maxAttempts int,
	delay time.Duration,
	retryable Retryable,
	logger boshlog.Logger,
) RetryStrategy {
	return &attemptRetryStrategy{
		maxAttempts: maxAttempts,
		delay:       delay,
		retryable:   retryable,
		logger:      logger,
		logTag:      "attemptRetryStrategy",
	}
}

func (s *attemptRetryStrategy) Try() error {
	var err error
	var isRetryable bool

	for i := 0; i < s.maxAttempts; i++ {
		s.logger.Debug(s.logTag, "Making attempt #%d for %s", i, reflect.TypeOf(s.retryable))

		isRetryable, err = s.retryable.Attempt()
		if err == nil {
			return nil
		}

		if !isRetryable {
			return err
		}

		time.Sleep(s.delay)
	}

	return err
}

Enhance debug output for retry strategies


package main

import (
	"flag"
	"log"
	"net/http"

	"github.com/gorilla/mux"
	"github.com/miraclesu/keywords-filter"
	"github.com/miraclesu/keywords-filter/listener/http.listen"
	"github.com/miraclesu/keywords-filter/loader/http.load"
)

var (
	Port      = flag.String("p", ":7520", "serve's port")
	Threshold = flag.Int("t", 100, "Threshold of filter")

	Filter *filter.Filter
)

func main() {
	flag.Parse()

	var err error
	Filter, err = filter.New(*Threshold, &load.Loader{})
	if err != nil {
		log.Println(err.Error())
		return
	}

	Filter.StartListen(listen.NewListener())

	r := mux.NewRouter()
	r.HandleFunc("/filter", filterHandler).
		Methods("POST")
	log.Println("serve listen on", *Port)
	http.ListenAndServe(*Port, r)
}

func filterHandler(w http.ResponseWriter, r *http.Request) {

}

package main

import (
	"flag"
	"log"
	"net/http"

	"github.com/julienschmidt/httprouter"

	"github.com/miraclesu/keywords-filter"
	"github.com/miraclesu/keywords-filter/listener/http.listen"
	"github.com/miraclesu/keywords-filter/loader/http.load"
)

var (
	Port      = flag.String("p", ":7520", "serve's port")
	Threshold = flag.Int("t", 100, "Threshold of filter")

	Filter *filter.Filter
)

func main() {
	flag.Parse()

	var err error
	Filter, err = filter.New(*Threshold, &load.Loader{})
	if err != nil {
		log.Println(err.Error())
		return
	}

	Filter.StartListen(listen.NewListener())

	router := httprouter.New()
	router.POST("/filter", filterHandler)
	log.Println("serve listen on", *Port)
	http.ListenAndServe(*Port, router)
}

func filterHandler(w http.ResponseWriter, r *http.Request, _ httprouter.Params) {

}

Change httprouter from mux to httprouter


package core

type functionType struct {
	signature Signature
	function  func(...*Thunk) Value
}

func (f functionType) call(args Arguments) Value {
	ts, err := f.signature.Bind(args)

	if err != nil {
		return err
	}

	return f.function(ts...)
}

func NewLazyFunction(s Signature, f func(...*Thunk) Value) *Thunk {
	return Normal(functionType{
		signature: s,
		function:  f,
	})
}

func NewStrictFunction(s Signature, f func(...Value) Value) *Thunk {
	return NewLazyFunction(s, func(ts ...*Thunk) Value {
		for _, t := range ts {
			go t.Eval()
		}

		vs := make([]Value, len(ts))

		for i, t := range ts {
			vs[i] = t.Eval()

			if err, ok := vs[i].(ErrorType); ok {
				return err
			}
		}

		return f(vs...)
	})
}

func (f functionType) string() Value {
	return StringType("<function>")
}

package core

type functionType struct {
	signature Signature
	function  func(...*Thunk) Value
}

func (f functionType) call(args Arguments) Value {
	ts, err := f.signature.Bind(args)

	if err != nil {
		return err
	}

	return f.function(ts...)
}

// NewLazyFunction creates a function whose arguments are evaluated lazily.
func NewLazyFunction(s Signature, f func(...*Thunk) Value) *Thunk {
	return Normal(functionType{
		signature: s,
		function:  f,
	})
}

// NewStrictFunction creates a function whose arguments are evaluated strictly.
func NewStrictFunction(s Signature, f func(...Value) Value) *Thunk {
	return NewLazyFunction(s, func(ts ...*Thunk) Value {
		for _, t := range ts {
			go t.Eval()
		}

		vs := make([]Value, len(ts))

		for i, t := range ts {
			vs[i] = t.Eval()

			if err, ok := vs[i].(ErrorType); ok {
				return err
			}
		}

		return f(vs...)
	})
}

func (f functionType) string() Value {
	return StringType("<function>")
}

Add documentation on NewLazyFunction and NewStrictFunction


/*
Copyright 2018 The Jetstack cert-manager contributors.

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

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

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

package main

import (
	"github.com/jetstack/cert-manager/pkg/apis/certmanager/validation/webhooks"
	"github.com/openshift/generic-admission-server/pkg/cmd"
)

var certHook cmd.ValidatingAdmissionHook = &webhooks.CertificateAdmissionHook{}
var issuerHook cmd.ValidatingAdmissionHook = &webhooks.IssuerAdmissionHook{}
var clusterIssuerHook cmd.ValidatingAdmissionHook = &webhooks.ClusterIssuerAdmissionHook{}

func main() {
	cmd.RunAdmissionServer(
		certHook,
		issuerHook,
		clusterIssuerHook,
	)
}

/*
Copyright 2018 The Jetstack cert-manager contributors.

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

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

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

package main

import (
	"flag"

	"github.com/jetstack/cert-manager/pkg/apis/certmanager/validation/webhooks"
	"github.com/openshift/generic-admission-server/pkg/cmd"
)

var certHook cmd.ValidatingAdmissionHook = &webhooks.CertificateAdmissionHook{}
var issuerHook cmd.ValidatingAdmissionHook = &webhooks.IssuerAdmissionHook{}
var clusterIssuerHook cmd.ValidatingAdmissionHook = &webhooks.ClusterIssuerAdmissionHook{}

func main() {
	// Avoid "logging before flag.Parse" errors from glog
	flag.CommandLine.Parse([]string{})

	cmd.RunAdmissionServer(
		certHook,
		issuerHook,
		clusterIssuerHook,
	)
}

Fix "logging before flag.Parse" errors


package ttl_hash_set_test

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

	"testing"
)

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

package ttl_hash_set_test

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

	"testing"
)

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

Rename test suite to follow with the object name of `TTLHashSet`


package http

import (
	"net/http"
	"strings"
)

func FixupCORSHeaders(downstream http.ResponseWriter, upstream *http.Response) {
	hasCORSHeaders := false
	for name := range upstream.Header {
		if strings.HasPrefix(name, "Access-Control-") {
			hasCORSHeaders = true
			break
		}
	}

	if !hasCORSHeaders {
		return
	}

	// Upstream has provided CORS header; upstream will manage all CORS headers
	// Remove existing CORS headers from response to downstream
	headers := downstream.Header()
	for name := range headers {
		if strings.HasPrefix(name, "Access-Control-") {
			headers.Del(name)
		}
	}
}

package http

import (
	"net/http"
	"strings"
)

func parseVaryHeaders(values []string) []string {
	var headers []string
	for _, v := range values {
		for _, h := range strings.Split(v, ",") {
			h = strings.TrimSpace(h)
			if h != "" {
				headers = append(headers, h)
			}
		}
	}
	return headers
}

func FixupCORSHeaders(downstream http.ResponseWriter, upstream *http.Response) {
	hasCORSHeaders := false
	for name, values := range upstream.Header {
		if strings.HasPrefix(name, "Access-Control-") {
			hasCORSHeaders = true
			break
		}
		if name == "Vary" {
			varyHeaders := parseVaryHeaders(values)
			for _, h := range varyHeaders {
				if http.CanonicalHeaderKey(h) == "Origin" {
					hasCORSHeaders = true
				}
			}
		}
	}

	if !hasCORSHeaders {
		return
	}

	// Upstream has provided CORS header; upstream will manage all CORS headers
	// Remove existing CORS headers from response to downstream
	headers := downstream.Header()
	for name, values := range headers {
		if strings.HasPrefix(name, "Access-Control-") {
			headers.Del(name)
		}
		// Delete 'Vary: Origin' header
		if name == "Vary" {
			varyHeaders := parseVaryHeaders(values)
			n := 0
			for _, h := range varyHeaders {
				if http.CanonicalHeaderKey(h) != "Origin" {
					varyHeaders[n] = h
					n++
				}
			}
			varyHeaders = varyHeaders[:n]
			if len(varyHeaders) > 0 {
				headers[name] = []string{strings.Join(varyHeaders, ",")}
			} else {
				delete(headers, name)
			}
		}
	}
}

Handle CORS fixup for Vary header


package atlas

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

var TestForm = map[string]string{
	"Type":        "foo",
	"AF":          "1",
	"InWifiGroup": "true",
	"Spread":      "1",
}

func TestFillDefinition(t *testing.T) {
	err := FillDefinition(nil, TestForm)

	assert.NoError(t, err)
}

func TestFillDefinition2(t *testing.T) {
	d := &Definition{}
	err := FillDefinition(d, TestForm)

	assert.NoError(t, err)
	assert.Equal(t, "foo", d.Type)
	assert.Equal(t, 1, d.AF)
	assert.True(t, d.InWifiGroup)
}

package atlas

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

var TestForm = map[string]string{
	"Type":        "foo",
	"AF":          "1",
	"InWifiGroup": "true",
	"Spread":      "1",
}

var TestForm1 = map[string]string{
	"Tags": "foo,bar",
}

func TestFillDefinition(t *testing.T) {
	err := FillDefinition(nil, TestForm)

	assert.NoError(t, err)
}

func TestFillDefinition2(t *testing.T) {
	d := &Definition{}
	err := FillDefinition(d, TestForm)

	assert.NoError(t, err)
	assert.Equal(t, "foo", d.Type)
	assert.Equal(t, 1, d.AF)
	assert.True(t, d.InWifiGroup)
}

func TestFillDefinition3(t *testing.T) {
	d := &Definition{}
	err := FillDefinition(d, TestForm1)

	assert.NoError(t, err)
	assert.NotEmpty(t, d.Tags)
	assert.EqualValues(t, []string{"foo", "bar"}, d.Tags)
}

Add tests for the new "slice" type in FillDefinition().


package main

import (
	"fmt"

	"os"

	"github.com/jvikstedt/alarm-bot/configuration"
	"github.com/jvikstedt/alarm-bot/mailer"
	"github.com/jvikstedt/alarm-bot/tracker"
)

var mail *mailer.Mailer
var conf *configuration.Configuration

func init() {
	setupConf()
	setupMailer()
}

func main() {
	for _, c := range conf.TestObjects {
		trackResult, err := tracker.Perform(c.URL, c.MatchString, c.Status)
		if err != nil {
			fmt.Print(err)
			mail.Send("AlarmBot Error @ "+trackResult.TargetURL, err.Error(), c.MailTo)
		} else {
			fmt.Print(trackResult)
		}
	}
}

func setupConf() {
	confName := os.Getenv("ALARM_BOT_CONFIG")
	if confName == "" {
		confName = "./config.json"
	}
	conf = configuration.NewConfiguration(confName)
}

func setupMailer() {
	mail = mailer.NewMailer(conf.MailSetting.Host, conf.MailSetting.From, conf.MailSetting.Password, conf.MailSetting.Port)
}

package main

import (
	"fmt"

	"os"

	"github.com/jvikstedt/alarm-bot/configuration"
	"github.com/jvikstedt/alarm-bot/mailer"
	"github.com/jvikstedt/alarm-bot/tracker"
)

var mail *mailer.Mailer
var conf *configuration.Configuration

func init() {
	setupConf()
	setupMailer()
}

func main() {
	for _, c := range conf.TestObjects {
		trackResult, err := tracker.Perform(c.URL, c.MatchString, c.Status)
		if err != nil {
			fmt.Println(err)
			mail.Send("AlarmBot Error @ "+trackResult.TargetURL, err.Error(), c.MailTo)
		} else {
			fmt.Println(trackResult)
		}
	}
}

func setupConf() {
	confName := os.Getenv("ALARM_BOT_CONFIG")
	if confName == "" {
		confName = "./config.json"
	}
	conf = configuration.NewConfiguration(confName)
}

func setupMailer() {
	mail = mailer.NewMailer(conf.MailSetting.Host, conf.MailSetting.From, conf.MailSetting.Password, conf.MailSetting.Port)
}

Add line break when printing to fmt


// +build windows

package edgectl

import (
	"github.com/pkg/errors"
	"github.com/spf13/cobra"

	"github.com/datawire/ambassador/pkg/supervisor"
)

// GuessRunAsInfo attempts to construct a RunAsInfo for the user logged in at
// the primary display
func GuessRunAsInfo(_ *supervisor.Process) (*RunAsInfo, error) {
	return nil, errors.New("Not implemented on this platform")
}

func launchDaemon(_ *cobra.Command, _ []string) error {
	return errors.New("Not implemented on this platform")
}

// GetFreePort asks the kernel for a free open port that is ready to use.
// Similar to telepresence.utilities.find_free_port()
func GetFreePort() (int, error) {
	return 0, errors.New("Not implemented on this platform")
}

// DaemonWorks returns whether the daemon can function on this platform
func DaemonWorks() bool {
	return false
}

// +build windows

package edgectl

import (
	"github.com/pkg/errors"
	"github.com/spf13/cobra"

	"github.com/datawire/ambassador/pkg/supervisor"
)

// GuessRunAsInfo attempts to construct a RunAsInfo for the user logged in at
// the primary display
func GuessRunAsInfo(_ *supervisor.Process) (*RunAsInfo, error) {
	return nil, errors.New("Not implemented on this platform")
}

func LaunchDaemon(_ *cobra.Command, _ []string) error {
	return errors.New("Not implemented on this platform")
}

// GetFreePort asks the kernel for a free open port that is ready to use.
// Similar to telepresence.utilities.find_free_port()
func GetFreePort() (int, error) {
	return 0, errors.New("Not implemented on this platform")
}

// DaemonWorks returns whether the daemon can function on this platform
func DaemonWorks() bool {
	return false
}

Change private->public name for Windows


package activitystreams

type Person struct {
	BaseObject
	Inbox             string    `json:"inbox"`
	Outbox            string    `json:"outbox"`
	PreferredUsername string    `json:"preferredUsername"`
	URL               string    `json:"url"`
	Name              string    `json:"name"`
	Icon              Image     `json:"icon"`
	Following         string    `json:"following"`
	Followers         string    `json:"followers"`
	Summary           string    `json:"summary"`
	PublicKey         PublicKey `json:"publicKey"`
}

func NewPerson(accountRoot string) *Person {
	p := Person{
		BaseObject: BaseObject{
			Type: "Person",
			Context: []string{
				"https://www.w3.org/ns/activitystreams",
			},
			ID: accountRoot,
		},
		URL:       accountRoot,
		Following: accountRoot + "/following",
		Followers: accountRoot + "/followers",
		Inbox:     accountRoot + "/inbox",
		Outbox:    accountRoot + "/outbox",
	}

	return &p
}

func (p *Person) AddPubKey(k []byte) {
	p.Context = append(p.Context, "https://w3id.org/security/v1")
	p.PublicKey = PublicKey{
		ID:           p.ID + "#main-key",
		Owner:        p.ID,
		PublicKeyPEM: string(k),
	}
}

Add support for including a public key on a Person


package response

import (
	"github.com/Vladimiroff/vec2d"

	"warcluster/entities"
)

type LoginSuccess struct {
	baseResponse
	Username   string
	Position   *vec2d.Vector
	HomePlanet struct {
		Name     string
		Position *vec2d.Vector
	}
}

type LoginFailed struct {
	baseResponse
}

type LoginInformation struct {
	baseResponse
}

func NewLoginSuccess(player *entities.Player, homePlanet *entities.Planet) *LoginSuccess {
	r := new(LoginSuccess)
	r.Command = "login_success"
	r.Username = player.Username
	r.Position = player.ScreenPosition
	r.HomePlanet.Name = homePlanet.Name
	r.HomePlanet.Position = homePlanet.Position
	return r
}

func NewLoginFailed() *LoginFailed {
	r := new(LoginFailed)
	r.Command = "login_failed"
	return r
}

func NewLoginInformation() *LoginInformation {
	r := new(LoginInformation)
	r.Command = "request_setup_params"
	return r
}

func (l *LoginSuccess) Sanitize(*entities.Player)     {}
func (l *LoginFailed) Sanitize(*entities.Player)      {}
func (l *LoginInformation) Sanitize(*entities.Player) {}

package response

import (
	"github.com/Vladimiroff/vec2d"

	"warcluster/entities"
)

type Fraction struct {
	Id    uint16
	Color entities.Color
	Name  string
}

type LoginSuccess struct {
	baseResponse
	Username   string
	Position   *vec2d.Vector
	Fraction   Fraction
	HomePlanet struct {
		Name     string
		Position *vec2d.Vector
	}
}

type LoginFailed struct {
	baseResponse
}

type LoginInformation struct {
	baseResponse
}

func NewLoginSuccess(player *entities.Player, homePlanet *entities.Planet) *LoginSuccess {
	r := new(LoginSuccess)
	r.Command = "login_success"
	r.Username = player.Username
	r.Fraction = Fraction{player.Race.ID, player.Race.Color(), player.Race.Name()}
	r.Position = player.ScreenPosition
	r.HomePlanet.Name = homePlanet.Name
	r.HomePlanet.Position = homePlanet.Position
	return r
}

func NewLoginFailed() *LoginFailed {
	r := new(LoginFailed)
	r.Command = "login_failed"
	return r
}

func NewLoginInformation() *LoginInformation {
	r := new(LoginInformation)
	r.Command = "request_setup_params"
	return r
}

func (l *LoginSuccess) Sanitize(*entities.Player)     {}
func (l *LoginFailed) Sanitize(*entities.Player)      {}
func (l *LoginInformation) Sanitize(*entities.Player) {}

Update connection protocol for Login success


package targets

import "path"
import "os"
import "os/exec"
import "runtime"
import "errors"

type Go struct {}

func (Go) Compile(mainFile string) error {
	compile := exec.Command("go", "build", "-tags", "example", "-o",  path.Base(mainFile[:len(mainFile)-2])+".gob")
	compile.Stdout = os.Stdout
	compile.Stderr = os.Stderr
	return compile.Run()
}
func (Go) Run(mainFile string) error {
	run := exec.Command("./"+path.Base(mainFile[:len(mainFile)-2])+".gob")
	run.Stdout = os.Stdout
	run.Stderr = os.Stderr
	return run.Run()
}
func (Go) Export(mainFile string) error {
	if runtime.GOOS == "linux" ||  runtime.GOOS == "darwin" {

		return os.Rename(path.Base(mainFile[:len(mainFile)-2])+".gob", "../"+path.Base(mainFile[:len(mainFile)-2]))

	//TODO support exe on windows.
	} else {
		return errors.New("Cannot export on "+runtime.GOOS+ " systems!")
	}
}

func init() {
	RegisterTarget("go", Go{})
}

package targets

import "path"
import "os"
import "os/exec"
import "runtime"
import "errors"

type Go struct {}

func (Go) Compile(mainFile string) error {
	compile := exec.Command("go", "build", "-tags", "example", "-o",  path.Base(mainFile[:len(mainFile)-2])+".gob")
	compile.Stdout = os.Stdout
	compile.Stderr = os.Stderr
	return compile.Run()
}
func (Go) Run(mainFile string) error {
	run := exec.Command("./"+path.Base(mainFile[:len(mainFile)-2])+".gob")
	run.Stdout = os.Stdout
	run.Stderr = os.Stderr
	return run.Run()
}
func (Go) Export(mainFile string) error {
	if runtime.GOOS == "linux" ||  runtime.GOOS == "darwin" {

		return os.Rename(path.Base(mainFile[:len(mainFile)-2])+".gob", "../"+path.Base(mainFile[:len(mainFile)-2]))

	} else if runtime.GOOS == "windows" {

		return os.Rename(path.Base(mainFile[:len(mainFile)-2])+".gob", "../"+path.Base(mainFile[:len(mainFile)-2])+".exe")

	} else {
		return errors.New("Cannot export on "+runtime.GOOS+ " systems!")
	}
}

func init() {
	RegisterTarget("go", Go{})
}

Support Go export on windows.


// Copyright 2016 Tom Thorogood. All rights reserved.
// Use of this source code is governed by a
// Modified BSD License license that can be found in
// the LICENSE file.

package shm

import (
	"os"

	"github.com/tmthrgd/go-shm"
)

// Unlink removes the previously created blocker.
//
// Taken from shm_unlink(3):
// 	The  operation  of shm_unlink() is analogous to unlink(2): it removes a
// 	shared memory object name, and, once all processes  have  unmapped  the
// 	object, de-allocates and destroys the contents of the associated memory
// 	region.  After a successful shm_unlink(),  attempts  to  shm_open()  an
// 	object  with  the same name will fail (unless O_CREAT was specified, in
// 	which case a new, distinct object is created).
func Unlink(name string) error {
	return shm.Unlink(name)
}

// Copyright 2016 Tom Thorogood. All rights reserved.
// Use of this source code is governed by a
// Modified BSD License license that can be found in
// the LICENSE file.

package shm

import "github.com/tmthrgd/go-shm"

// Unlink removes the previously created blocker.
//
// Taken from shm_unlink(3):
// 	The  operation  of shm_unlink() is analogous to unlink(2): it removes a
// 	shared memory object name, and, once all processes  have  unmapped  the
// 	object, de-allocates and destroys the contents of the associated memory
// 	region.  After a successful shm_unlink(),  attempts  to  shm_open()  an
// 	object  with  the same name will fail (unless O_CREAT was specified, in
// 	which case a new, distinct object is created).
func Unlink(name string) error {
	return shm.Unlink(name)
}

Remove unused import (missing from 0f00944)


package stl

import (
	"fmt"
	"io"
)

// Write writes the triangle mesh to the writer using ASCII STL codec.
zfunc Write(w io.Writer, t []Triangle) error {
	var err error

	printf := func(format string, a ...interface{}) {
		if err != nil {
			return
		}
		_, err = fmt.Fprintf(w, format, a...)
	}
	printf("solid object\n")
	for _, tt := range t {
		if err != nil {
			return err
		}
		printf("facet normal %f %f %f\n", tt.N[0], tt.N[1], tt.N[2])
		printf("  outer loop\n")
		for _, v := range tt.V {
			printf("    vertex %f %f %f\n", v[0], v[1], v[2])
		}
		printf("  endloop\n")
		printf("endfacet\n")
	}
	printf("endsolid object\n")
	return nil
}

package stl

import (
	"fmt"
	"io"
)

// Write writes the triangle mesh to the writer using ASCII STL codec.
func Write(w io.Writer, t []Triangle) error {
	var err error

	printf := func(format string, a ...interface{}) {
		if err != nil {
			return
		}
		_, err = fmt.Fprintf(w, format, a...)
	}
	printf("solid object\n")
	for _, tt := range t {
		if err != nil {
			return err
		}
		printf("facet normal %f %f %f\n", tt.N[0], tt.N[1], tt.N[2])
		printf("  outer loop\n")
		for _, v := range tt.V {
			printf("    vertex %f %f %f\n", v[0], v[1], v[2])
		}
		printf("  endloop\n")
		printf("endfacet\n")
	}
	printf("endsolid object\n")
	return nil
}

Fix build to test goci


package main

import (
	"net/http"
	"path"
	"strconv"

	log "github.com/Sirupsen/logrus"
	"github.com/brandur/sorg"
	"github.com/joeshaw/envdecode"
)

// Conf contains configuration information for the command.
type Conf struct {
	// Port is the port on which the command will serve the site over HTTP.
	Port int `env:"PORT,default=5001"`

	// TargetDir is the target location where the site was built to.
	TargetDir string `env:"TARGET_DIR,default=./public"`
}

func main() {
	sorg.InitLog(false)

	var conf Conf
	err := envdecode.Decode(&conf)
	if err != nil {
		log.Fatal(err)
	}

	err = sorg.CreateOutputDirs(conf.TargetDir)
	if err != nil {
		log.Fatal(err)
	}

	err = serve(conf.TargetDir, conf.Port)
	if err != nil {
		log.Fatal(err)
	}
}

func serve(targetDir string, port int) error {
	log.Infof("Serving '%v' on port %v", path.Clean(targetDir), port)
	log.Infof("Open browser to: http://localhost:%v/", port)
	handler := http.FileServer(http.Dir(targetDir))
	return http.ListenAndServe(":"+strconv.Itoa(port), handler)
}

package main

import (
	"net/http"
	"path"
	"strconv"

	log "github.com/Sirupsen/logrus"
	"github.com/brandur/sorg"
	"github.com/joeshaw/envdecode"
)

// Conf contains configuration information for the command.
type Conf struct {
	// Port is the port on which the command will serve the site over HTTP.
	Port int `env:"PORT,default=5001"`

	// TargetDir is the target location where the site was built to.
	TargetDir string `env:"TARGET_DIR,default=./public"`
}

// Left as a global for now for the sake of convenience, but it's not used in
// very many places and can probably be refactored as a local if desired.
var conf Conf

func main() {
	sorg.InitLog(false)

	err := envdecode.Decode(&conf)
	if err != nil {
		log.Fatal(err)
	}

	err = sorg.CreateOutputDirs(conf.TargetDir)
	if err != nil {
		log.Fatal(err)
	}

	err = serve(conf.TargetDir, conf.Port)
	if err != nil {
		log.Fatal(err)
	}
}

func serve(targetDir string, port int) error {
	log.Infof("Serving '%v' on port %v", path.Clean(targetDir), port)
	log.Infof("Open browser to: http://localhost:%v/", port)
	handler := http.FileServer(http.Dir(targetDir))
	return http.ListenAndServe(":"+strconv.Itoa(port), handler)
}

Move Conf to a global for consistency with build executable


package compute

type VolumePoolRepository interface {
	List() ([]*VolumePool, error)
}

type VolumePool struct {
	Name string
	Size uint64 // MiB
	Used uint64 // MiB
	Free uint64 // MiB
}

func (pool *VolumePool) UsagePercent() int {
	return int(100 * pool.Used / pool.Free)
}

func (pool *VolumePool) FreeGB() uint64 {
	return pool.Free / 1024
}

func (pool *VolumePool) SizeGb() uint64 {
	return pool.Size / 1024
}

package compute

type VolumePoolRepository interface {
	List() ([]*VolumePool, error)
}

type VolumePool struct {
	Name string
	Size uint64 // MiB
	Used uint64 // MiB
	Free uint64 // MiB
}

func (pool *VolumePool) UsagePercent() int {
	return int(100 * pool.Used / pool.Size)
}

func (pool *VolumePool) FreeGB() uint64 {
	return pool.Free / 1024
}

func (pool *VolumePool) SizeGb() uint64 {
	return pool.Size / 1024
}

Fix pool usage percent calculation


// This file is autogenerated, see packaging/increment_build.sh
package libkb

const Version = "1.0.5"
const Build = 6

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

package libkb

import (
	"fmt"
)

// NOTE: This file is the source of truth for our version number, but we have a
//       script that reads it at packaging/version.sh. If you refactor this
//       file, update that script.

// Version as MAJOR.MINOR.PATCH
const Version = "1.0.5"

// Build number
const Build = "5"

// VersionString returns semantic version string.
func VersionString() string {
	return fmt.Sprintf("%s-%s", Version, Build)
}

Revert "Bumping build number: 1.0.5-6"


package openpgp

import (
	"os"
	"path/filepath"
)

// Gnupg keyrings files
var gPubringFile string = filepath.Join(os.Getenv("HOME"), ".gnupg", "pubring.gpg")
var gSecringFile string = filepath.Join(os.Getenv("HOME"), ".gnupg", "secring.gpg")

// Gnupg trousseau master gpg key id
var gMasterGpgId string = os.Getenv(ENV_MASTER_GPG_ID_KEY)

package openpgp

import (
	"os"
	"path/filepath"
)

// Gnupg keyrings files
var gPubringFile string = func() string {
	envPubring := os.Getenv("GNUPG_PUBRING_PATH")

	if envPubring != "" {
		return envPubring
	}

	return filepath.Join(os.Getenv("HOME"), ".gnupg", "pubring.gpg")
}()

var gSecringFile string = func() string {
	envSecring := os.Getenv("GNUPG_SECRING_PATH")

	if envSecring != "" {
		return envSecring
	}

	return filepath.Join(os.Getenv("HOME"), ".gnupg", "secring.gpg")
}()

// Gnupg trousseau master gpg key id
var gMasterGpgId string = os.Getenv(ENV_MASTER_GPG_ID_KEY)

Allow gnupg keyring files to be selected via sys env


package jsonutil

import (
	"bytes"
	"encoding/json"
	"strings"
)

func Encode(v interface{}) (string, error) {
	var buf bytes.Buffer
    err := json.NewEncoder(&buf).Encode(v)
    if err != nil {
        return "", err
    }
	return strings.TrimRight(buf.String(), "\n"), nil
}

func Decode(s string) (v interface{}, err error) {
	err = json.NewDecoder(bytes.NewReader([]byte(s))).Decode(&v)
	return
}

package jsonutil

import (
	"encoding/json"
)

func Encode(v interface{}) (string, error) {
    bytes, err := json.Marshal(v)
    if err != nil {
        return "", err
    }
	return string(bytes), nil
}

func Decode(s string) (v interface{}, err error) {
	err = json.Unmarshal([]byte(s), &v)
	return
}

Use Marshal and Unmarshal instead of Encode and Decode.


// Copyright (c) 2014 Josh Rickmar.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package main

import (
	"github.com/conformal/gotk3/gtk"
	"runtime"
)

const HomePage HTMLPageDescription = "https://www.duckduckgo.com/lite"

const (
	defaultWinWidth  = 1024
	defaultWinHeight = 768
)

// RunGUI initializes GTK, creates the toplevel window and all child widgets,
// opens the pages for the default session, and runs the Glib main event loop.
// This function blocks until the toplevel window is destroyed and the event
// loop exits.
func RunGUI() {
	gtk.Init(nil)

	window, _ := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	window.Connect("destroy", func() {
		gtk.MainQuit()
	})
	window.SetDefaultGeometry(defaultWinWidth, defaultWinHeight)
	window.Show()

	session := []PageDescription{HomePage}

	pm := NewPageManager(session)
	window.Add(pm)
	pm.Show()

	gtk.Main()
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	RunProfiler("localhost:7070")
	RunGUI()
}

// Copyright (c) 2014 Josh Rickmar.
// Use of this source code is governed by an ISC
// license that can be found in the LICENSE file.

package main

import (
	"runtime"

	"github.com/conformal/gotk3/gtk"
	"github.com/jrick/go-webkit2/wk2"
)

const HomePage HTMLPageDescription = "https://www.duckduckgo.com/lite"

const (
	defaultWinWidth  = 1024
	defaultWinHeight = 768
)

// RunGUI initializes GTK, creates the toplevel window and all child widgets,
// opens the pages for the default session, and runs the Glib main event loop.
// This function blocks until the toplevel window is destroyed and the event
// loop exits.
func RunGUI() {
	gtk.Init(nil)

	window, _ := gtk.WindowNew(gtk.WINDOW_TOPLEVEL)
	window.Connect("destroy", func() {
		gtk.MainQuit()
	})
	window.SetDefaultGeometry(defaultWinWidth, defaultWinHeight)
	window.Show()

	wc := wk2.DefaultWebContext()
	wc.SetProcessModel(wk2.ProcessModelMultipleSecondaryProcesses)

	session := []PageDescription{HomePage}
	pm := NewPageManager(session)
	window.Add(pm)
	pm.Show()

	gtk.Main()
}

func main() {
	runtime.GOMAXPROCS(runtime.NumCPU())
	RunProfiler("localhost:7070")
	RunGUI()
}

Use multiple WebKit web processes.


package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/beard1ess/gauss/parsing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"io/ioutil"
	"reflect"
	"testing"
)

func TestDiff(t *testing.T) {

	var expected, actual parsing.ConsumableDifference

	assert := assert.New(t)
	require := require.New(t)

	testBuffer := bytes.NewBuffer(nil) // A testing writer

	diff(
		"./tests/one.json",
		"./tests/two.json",
		"machine",
		testBuffer,
	)

	result, err := ioutil.ReadAll(testBuffer)
	require.Nil(err, "The test buffer should be readable")

	testData, err := ioutil.ReadFile("./tests/diff.json")
	require.Nil(err, "The test diff should be readable.")

	json.Unmarshal(testData, &expected)
	require.Nil(err, "The test data should be unmarshaled without error.")

	temp, _ := json.Marshal(expected)
	fmt.Println(temp)

	json.Unmarshal(result, &actual)
	assert.Nil(err, "The result should be unmarshaled without error.")

	assert.Equal(
		reflect.DeepEqual(expected, actual),
		true,
		"The diff of one.json and two.json should equal the test diff.",
	)
}

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"github.com/beard1ess/gauss/parsing"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
	"io/ioutil"
	"reflect"
	"testing"
)

func TestDiff(t *testing.T) {

	var expected, actual parsing.ConsumableDifference

	assert := assert.New(t)
	require := require.New(t)

	testBuffer := bytes.NewBuffer(nil) // A testing writer

	diff(
		"./tests/one.json",
		"./tests/two.json",
		"machine",
		testBuffer,
	)

	result, err := ioutil.ReadAll(testBuffer)
	require.Nil(err, "The test buffer should be readable")

	testData, err := ioutil.ReadFile("./tests/diff.json")
	require.Nil(err, "The test diff should be readable.")

	json.Unmarshal(testData, &expected)
	require.Nil(err, "The test data should be unmarshaled without error.")

	temp, _ := json.Marshal(expected)
	fmt.Println(string(temp))

	json.Unmarshal(result, &actual)
	assert.Nil(err, "The result should be unmarshaled without error.")

	assert.Equal(
		reflect.DeepEqual(expected, actual),
		true,
		"The diff of one.json and two.json should equal the test diff.",
	)
}

Fix println statement to write a string


// Package zapadapter provides a logger that writes to a go.uber.org/zap.Logger.
package zapadapter

import (
	"context"

	"github.com/jackc/pgx/v4"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

type Logger struct {
	logger *zap.Logger
}

func NewLogger(logger *zap.Logger) *Logger {
	return &Logger{logger: logger.WithOptions(zap.AddCallerSkip(1))}
}

func (pl *Logger) Log(ctx context.Context, level pgx.LogLevel, msg string, data map[string]interface{}) {
	fields := make([]zapcore.Field, len(data))
	i := 0
	for k, v := range data {
		fields[i] = zap.Reflect(k, v)
		i++
	}

	switch level {
	case pgx.LogLevelTrace:
		pl.logger.Debug(msg, append(fields, zap.Stringer("PGX_LOG_LEVEL", level))...)
	case pgx.LogLevelDebug:
		pl.logger.Debug(msg, fields...)
	case pgx.LogLevelInfo:
		pl.logger.Info(msg, fields...)
	case pgx.LogLevelWarn:
		pl.logger.Warn(msg, fields...)
	case pgx.LogLevelError:
		pl.logger.Error(msg, fields...)
	default:
		pl.logger.Error(msg, append(fields, zap.Stringer("PGX_LOG_LEVEL", level))...)
	}
}

// Package zapadapter provides a logger that writes to a go.uber.org/zap.Logger.
package zapadapter

import (
	"context"

	"github.com/jackc/pgx/v4"
	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
)

type Logger struct {
	logger *zap.Logger
}

func NewLogger(logger *zap.Logger) *Logger {
	return &Logger{logger: logger.WithOptions(zap.AddCallerSkip(1))}
}

func (pl *Logger) Log(ctx context.Context, level pgx.LogLevel, msg string, data map[string]interface{}) {
	fields := make([]zapcore.Field, len(data))
	i := 0
	for k, v := range data {
		fields[i] = zap.Any(k, v)
		i++
	}

	switch level {
	case pgx.LogLevelTrace:
		pl.logger.Debug(msg, append(fields, zap.Stringer("PGX_LOG_LEVEL", level))...)
	case pgx.LogLevelDebug:
		pl.logger.Debug(msg, fields...)
	case pgx.LogLevelInfo:
		pl.logger.Info(msg, fields...)
	case pgx.LogLevelWarn:
		pl.logger.Warn(msg, fields...)
	case pgx.LogLevelError:
		pl.logger.Error(msg, fields...)
	default:
		pl.logger.Error(msg, append(fields, zap.Stringer("PGX_LOG_LEVEL", level))...)
	}
}

Use zap.Any for handling interface{} -> zap.Field conversion


package prgs

// Prg is a Program, with all its data (no behavior)
type Prg struct{}

// PGetter gets programs (from an internal config)
type PGetter interface {
	Get() []*Prg
}

type defaultGetter struct{}

var dg defaultGetter
var getter PGetter

func init() {
	dg = defaultGetter{}
	getter = dg
}
func (df defaultGetter) Get() []*Prg {
	return []*Prg{}
}

func Getter() PGetter {
	return getter
}

package prgs

// Prg is a Program, with all its data (no behavior)
type prg struct {
	name string
}

// Prg defines what kind of service a program has to provide
type Prg interface {
	// Name is the name of a program to install, acts as an id
	Name() string
}

// PGetter gets programs (from an internal config)
type PGetter interface {
	Get() []Prg
}

type defaultGetter struct{}

var dg defaultGetter
var getter PGetter

func init() {
	dg = defaultGetter{}
	getter = dg
}
func (df defaultGetter) Get() []Prg {
	return []Prg{}
}

// Getter returns a object able to get a list of Prgs
func Getter() PGetter {
	return getter
}

func (p *prg) Name() string {
	return p.name
}

Make Prg an interface instead of a struct


package core

import (
	"math"
)

type GeodeticSystem interface {
	ToGeographic(point *Point) *Point
	ToGeodetic(point *Point) *Point
}

type EllipseGeodetic struct {
	ellipseParam *EllipseParameters
}

func (eg *EllipseGeodetic) ToGeographic(point *Point) *Point {

	var lat float64
	var long float64

	if x != 0 {
		long = math.Atan2()
	} else {

	}

	point.x = long
	point.y = lat

	return point
}

package core

import (
	"math"
)

type GeodeticSystem interface {
	ToGeographic(point *Point) *Point
	ToGeodetic(point *Point) *Point
}

type EllipseGeodetic struct {
	ellipseParam *EllipseParameters
}

// This constants are defined for the GeocentricToGeodetic method
const (
	AD_C_Z1 = 1.0026000
	AD_C_Z2 = 1.00092592
	AD_C_Z3 = 0.999250297
	AD_C_Z4 = 0.997523508
)

// GeocentricToGeodetic converts the point's coordintates
// from the cartesian system (geocentric) to a geodetic system defined
// by the ellipse.
//
// This is based on the non iterative method described within paper :
//  'An Improved Algorithm for Geocentric to Geodetic Coordinate Conversion'
//  Ralph Toms, Feb 1996
//
func (eg *EllipseGeodetic) GeocentricToGeodetic(point *Point) *Point {

	var lat float64
	var long float64

	point.x

	long = math.Atan2(point.y, point.x)

	w2 := math.Pow(point.x, 2) + math.Pow(point.y, 2)

	point.x = long
	point.y = lat

	return point
}

Add function for geoentric to geodetic


package main

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

	"github.com/google/go-github/github"
	"golang.org/x/oauth2"
)

var (
	addr = flag.String("addr", "", "Listen address.")
	port = flag.Int("port", 8081, "Listen port.")
)

func main() {
	flag.Parse()

	log.SetOutput(os.Stderr)
	log.SetFlags(log.LstdFlags)

	token := os.Getenv("DOPPELGANGER_GITHUB_TOKEN")
	if token == "" {
		fmt.Fprintln(os.Stderr, "Missing GitHub access token (set DOPPELGANGER_GITHUB_TOKEN environment variable)")
		os.Exit(-1)
	}

	*addr = fmt.Sprintf("%s:%d", *addr, *port)
	log.Printf("doppelganger is listening on %s", *addr)
	http.ListenAndServe(*addr, nil)
}

func newGithubClient(token string) *github.Client {
	tokenSource := oauth2.StaticTokenSource(&oauth2.Token{
		AccessToken: token,
	})
	oauthClient := oauth2.NewClient(oauth2.NoContext, tokenSource)

	return github.NewClient(oauthClient)
}

Build GitHub client from token


package main

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

func main() {
	router := NewRouter()

	// By default, listen to port :9532 (:ykdb)
	fmt.Println("Listening on port 9532...")
	log.Fatal(http.ListenAndServe(":9532", router))
}

package main

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

func main() {
	// Read in the supplied flags from the command line to determine the port.
	// By default, listen to port :9532 (:ykdb)
	var portFlag int
	flag.IntVar(&portFlag, "port", 9532, "Port to listen on for http requests.")
	flag.Parse()
	port := strconv.Itoa(portFlag)

	router := NewRouter()
	fmt.Printf("Listening on port %v...", port)

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

Allow program to listen on user-specified port


package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	utils "github.com/shurcooL/github_flavored_markdown"
)

func main() {
	http.HandleFunc("/", Handler)
	log.Printf("Listening on port %d\n", 8080)
	log.Fatal(http.ListenAndServe(":8080", nil))
}

func Handler(res http.ResponseWriter, req *http.Request) {
	readme, err := GetReadme()
	if err != nil {
		fmt.Fprintf(res, "Something went wrong:\n%s", err)
		return
	}

	fmt.Fprintf(res, string(readme))
}

func GetReadme() ([]byte, error) {
	b, err := ioutil.ReadFile("./README.md")
	if err != nil {
		return nil, err
	}

	return utils.Markdown(b), nil
}

package main

import (
	"flag"
	"fmt"
	"io/ioutil"
	"log"
	"net/http"

	utils "github.com/shurcooL/github_flavored_markdown"
)

var (
	file string
	bind string
)

func init() {
	flag.StringVar(&bind, "bind", ":8080", "interface to bind to, eg. 0.0.0.0:8080")
	flag.StringVar(&file, "file", "README.md", "file to render on web interface")
}

func main() {
	flag.Parse()
	http.HandleFunc("/", Handler)
	log.Printf("Listening on port %s\n", bind)
	log.Fatal(http.ListenAndServe(bind, nil))
}

func Handler(res http.ResponseWriter, req *http.Request) {
	readme, err := GetReadme()
	if err != nil {
		fmt.Fprintf(res, "Something went wrong:\n%s", err)
		return
	}

	fmt.Fprintf(res, string(readme))
}

func GetReadme() ([]byte, error) {
	b, err := ioutil.ReadFile(file)
	if err != nil {
		return nil, err
	}

	return utils.Markdown(b), nil
}

Read binding interface and MD file via flags.


// Copyright 2016 Martijn Croonen. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

package ece

import (
	"crypto/aes"
	"crypto/cipher"
	"errors"
)

// Encrypt encrypts |plaintext| using AEAD_AES_GCM_128 with the keys in |keys|
// adding |paddingLength| bytes of padding.
func Encrypt(plaintext []byte, keys *EncryptionKeys, paddingLength int) ([]byte, error) {
	if paddingLength < 0 || paddingLength > 255 {
		return nil, errors.New("Padding should be between 0 and 256.")
	}

	aes, err := aes.NewCipher(keys.cek)
	if err != nil {
		return nil, err
	}

	aesgcm, err := cipher.NewGCM(aes)
	if err != nil {
		return nil, err
	}

	record := make([]byte, 1+paddingLength+len(plaintext))
	record[0] = byte(paddingLength)
	copy(record[1+paddingLength:], plaintext)

	var auth []byte
	return aesgcm.Seal(nil, keys.nonce, record, auth), nil
}

// Copyright 2016 Martijn Croonen. All rights reserved.
// Use of this source code is governed by the MIT license, a copy of which can
// be found in the LICENSE file.

package ece

import (
	"crypto/aes"
	"crypto/cipher"
	"encoding/binary"
	"errors"
)

// Encrypt encrypts |plaintext| using AEAD_AES_GCM_128 with the keys in |keys|
// adding |paddingLength| bytes of padding.
func Encrypt(plaintext []byte, keys *EncryptionKeys, paddingLength int) ([]byte, error) {
	if paddingLength < 0 || paddingLength > 65535 {
		return nil, errors.New("Padding should be between 0 and 65535.")
	}

	aes, err := aes.NewCipher(keys.cek)
	if err != nil {
		return nil, err
	}

	aesgcm, err := cipher.NewGCM(aes)
	if err != nil {
		return nil, err
	}

	record := make([]byte, 2+paddingLength+len(plaintext))
	binary.BigEndian.PutUint16(record, uint16(paddingLength))
	copy(record[2+paddingLength:], plaintext)

	var auth []byte
	return aesgcm.Seal(nil, keys.nonce, record, auth), nil
}

Use 2 octets to indicate padding length.


package main

// Build a standalone executable with 'go build go-calc'
// Or just do a one time run test with 'go run go-calc 1 / 4'

import "fmt"
import "os" // For ARGV
import "strconv"

func main() {
	var arg_count int = len(os.Args) - 1;

	if (arg_count != 3) {
		fmt.Fprintf(os.Stdout,"Usage: %s [num1] [+-/*] [num2]\n", os.Args[0]);
		os.Exit(3);
	}

	var num1, _ = strconv.ParseFloat(os.Args[1],32);
	var num2, _ = strconv.ParseFloat(os.Args[3],32);
	var operand = os.Args[2];

	var total float64 = 0;

	if (operand == "+") {
		total = num1 + num2;
	} else if (operand == "-") {
		total = num1 - num2;
	} else if (operand == "/") {
		total = num1 / num2;
	} else if (operand == "*") {
		total = num1 * num2;
	} else {
		fmt.Fprintf(os.Stdout, "Unknown operand '%s'\n", operand);
		os.Exit(2);
	}

	fmt.Fprintf(os.Stdout, "%g %s %g = %g\n", num1, operand, num2, total);
}

package main

// Build a standalone executable with 'go build go-calc'
// Or just do a one time run test with 'go run go-calc 1 / 4'

import "fmt"
import "os" // For ARGV
import "strconv"

func main() {
	var arg_count int = len(os.Args) - 1;

	if (arg_count != 3) {
		fmt.Fprintf(os.Stdout,"Usage: %s [num1] [+-/*] [num2]\n", os.Args[0]);
		os.Exit(3);
	}

	var num1, _ = strconv.ParseFloat(os.Args[1],32);
	var num2, _ = strconv.ParseFloat(os.Args[3],32);
	var operand = os.Args[2];

	var total float64 = 0;

	if (operand == "+") {
		total = num1 + num2;
	} else if (operand == "-") {
		total = num1 - num2;
	} else if (operand == "/") {
		// Test for division by zero
		if (num2 == 0) {
			fmt.Fprintf(os.Stdout, "Error: division by zero\n");
			os.Exit(9);
		}

		total = num1 / num2;
	} else if (operand == "*") {
		total = num1 * num2;
	} else {
		fmt.Fprintf(os.Stdout, "Unknown operand '%s'\n", operand);
		os.Exit(2);
	}

	fmt.Fprintf(os.Stdout, "%g %s %g = %g\n", num1, operand, num2, total);
}

Add a check for division by zero


package events

import (
	"encoding/json"
)

type (
	// UserEvent represents the user related segment of an Event within Ion Channel.
	// Action is the specific type of User Event that occurred,
	// Data is information relevant to the type of event, defined by one of the other structs in this file.
	UserEvent struct {
		Action string          `json:"action"`
		Data   json.RawMessage `json:"data"`
	}

	// ProjectFlippedData represents the Data portion of a ProjectFlipped event
	ProjectFlippedData struct {
		Projects []struct {
			ID  string
			URL string
		}
		Email string
	}

	// InviteDetails represents the Data portion of several events related to a user being invited
	InviteDetails struct {
		Email       string
		AcceptLink  string
		UserName    string
		AccountName string
	}

	// AccountCreatedData represents the Data portion of an AccountCreated event
	AccountCreatedData struct {
		InviteDetails
	}

	// UserSignupData represents the Data portion of an UserSignup event
	UserSignupData struct {
		InviteDetails
	}

	// UserSignupStartedData represents the Data portion of an UserSignupStarted event
	UserSignupStartedData struct {
		InviteDetails
	}

	// ForgotPasswordData represents the Data portion of a ForgotPassword event
	ForgotPasswordData struct {
		Email    string
		Username string
		URL      string
	}
)

package events

import (
	"encoding/json"
)

type (
	// UserEvent represents the user related segment of an Event within Ion Channel.
	// Action is the specific type of User Event that occurred,
	// Data is information relevant to the type of event, defined by one of the other structs in this file.
	UserEvent struct {
		Action string          `json:"action"`
		Data   json.RawMessage `json:"data"`
	}

	// ProjectFlippedData represents the Data portion of a ProjectFlipped event
	ProjectFlippedData struct {
		Projects []struct {
			ID  string
			URL string
		}
		Email string
	}

	// InviteDetails represents the Data portion of several events related to a user being invited
	InviteDetails struct {
		Email       string
		AcceptLink  string
		UserName    string
		AccountName string
	}

	// AccountCreatedData represents the Data portion of an AccountCreated event
	AccountCreatedData struct {
		InviteDetails
	}

	// UserSignupData represents the Data portion of an UserSignup event
	UserSignupData struct {
		InviteDetails
	}

	// UserSignupStartedData represents the Data portion of an UserSignupStarted event
	UserSignupStartedData struct {
		InviteDetails
	}

	// ForgotPasswordData represents the Data portion of a ForgotPassword event
	ForgotPasswordData struct {
		Email    string
		Username string
		URL      string
	}

	// PasswordChangedData represents the Data portion of a PasswordChanged event
	PasswordChangedData struct {
		Email    string
		Username string
	}
)

Add PasswordChangedData struct to UserEvents


package config

import "runtime/debug"

// SemVer is the version of mockery at build time.
var SemVer = "v0.0.0-dev"

func GetSemverInfo() string {
	if version, ok := debug.ReadBuildInfo(); ok {
		return version.Main.Version
	}
	return SemVer
}

type Config struct {
	All                  bool
	BuildTags            string `mapstructure:"tags"`
	Case                 string
	Config               string
	Cpuprofile           string
	Dir                  string
	DisableVersionString bool `mapstructure:"disable-version-string"`
	DryRun               bool `mapstructure:"dry-run"`
	Exported             bool `mapstructure:"exported"`
	FileName             string
	InPackage            bool
	KeepTree             bool
	LogLevel             string `mapstructure:"log-level"`
	Name                 string
	Note                 string
	Outpkg               string
	Packageprefix        string
	Output               string
	Print                bool
	Profile              string
	Quiet                bool
	Recursive            bool
	SrcPkg               string
	BoilerplateFile      string `mapstructure:"boilerplate-file"`
	// StructName overrides the name given to the mock struct and should only be nonempty
	// when generating for an exact match (non regex expression in -name).
	StructName     string
	Tags           string
	TestOnly       bool
	UnrollVariadic bool `mapstructure:"unroll-variadic"`
	Version        bool
}

package config

// SemVer is the version of mockery at build time.
var SemVer = "v0.0.0-dev"

func GetSemverInfo() string {
    return SemVer
}

type Config struct {
	All                  bool
	BuildTags            string `mapstructure:"tags"`
	Case                 string
	Config               string
	Cpuprofile           string
	Dir                  string
	DisableVersionString bool `mapstructure:"disable-version-string"`
	DryRun               bool `mapstructure:"dry-run"`
	Exported             bool `mapstructure:"exported"`
	FileName             string
	InPackage            bool
	KeepTree             bool
	LogLevel             string `mapstructure:"log-level"`
	Name                 string
	Note                 string
	Outpkg               string
	Packageprefix        string
	Output               string
	Print                bool
	Profile              string
	Quiet                bool
	Recursive            bool
	SrcPkg               string
	BoilerplateFile      string `mapstructure:"boilerplate-file"`
	// StructName overrides the name given to the mock struct and should only be nonempty
	// when generating for an exact match (non regex expression in -name).
	StructName     string
	Tags           string
	TestOnly       bool
	UnrollVariadic bool `mapstructure:"unroll-variadic"`
	Version        bool
}

Revert "fixed it which mockery's correct version showed."


package vizzini_test

import (
	"strings"

	"code.cloudfoundry.org/bbs/models"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Cells", func() {
	It("should return all cells", func() {
		cells, err := bbsClient.Cells(logger)
		Expect(err).NotTo(HaveOccurred())
		Expect(len(cells)).To(BeNumerically(">=", 1))

		var cell_z1_0 *models.CellPresence
		for _, cell := range cells {
			if strings.HasPrefix(cell.CellId, "cell_z1-0") {
				cell_z1_0 = cell
				break
			}
		}

		Expect(cell_z1_0).NotTo(BeNil())
		Expect(cell_z1_0.CellId).To(HavePrefix("cell_z1-0"))
		Expect(cell_z1_0.Zone).To(Equal("z1"))
		Expect(cell_z1_0.Capacity.MemoryMb).To(BeNumerically(">", 0))
		Expect(cell_z1_0.Capacity.DiskMb).To(BeNumerically(">", 0))
		Expect(cell_z1_0.Capacity.Containers).To(BeNumerically(">", 0))
		Expect(len(cell_z1_0.RootfsProviders)).To(BeNumerically(">", 0))
	})
})

package vizzini_test

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

var _ = Describe("Cells", func() {
	It("should return all cells", func() {
		cells, err := bbsClient.Cells(logger)
		Expect(err).NotTo(HaveOccurred())
		Expect(len(cells)).To(BeNumerically(">=", 1))

		cell0 := cells[0]

		Expect(cell0).NotTo(BeNil())
		Expect(cell0.Capacity.MemoryMb).To(BeNumerically(">", 0))
		Expect(cell0.Capacity.DiskMb).To(BeNumerically(">", 0))
		Expect(cell0.Capacity.Containers).To(BeNumerically(">", 0))
		Expect(len(cell0.RootfsProviders)).To(BeNumerically(">", 0))
	})
})

Remove test for cell name and availability zone.