package main

import (
	"fmt"
	"os"

	"github.com/blixt/go-starbound/starbound"
	"golang.org/x/exp/mmap"
)

func main() {
	file, err := mmap.Open("../../test.world")
	if err != nil {
		fmt.Printf("failed to open world: %v\n", err)
		os.Exit(1)
	}
	db, err := starbound.NewBTreeDB5(file)
	if err != nil {
		fmt.Printf("failed to open world: %v\n", err)
		os.Exit(1)
	}
	value, err := db.Get([]byte("\x00\x00\x00\x00\x00"))
	fmt.Printf("metadata size: %d\n", len(value))
}

package main

import (
	"fmt"
	"os"

	"github.com/blixt/go-starbound/starbound"
	"golang.org/x/exp/mmap"
)

func main() {
	file, err := mmap.Open("../../test.world")
	if err != nil {
		fmt.Printf("failed to open world: %v\n", err)
		os.Exit(1)
	}
	w, err := starbound.NewWorld(file)
	if err != nil {
		fmt.Printf("failed to open world: %v\n", err)
		os.Exit(1)
	}
	t, err := w.GetRegion(30, 21)
	if err != nil {
		fmt.Printf("failed to get region: %v\n", err)
		os.Exit(1)
	}
	fmt.Println("region:", t)
}

Use GetRegion in dummy command line tool


package redis

import (
	"log"
	"time"

	redis "github.com/go-redis/redis"
	try "github.com/matryer/try"
)

// ConnectToClient Connects to a Redis server
func ConnectToClient(ip string, port string, config Config) *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr: ip + ":" + port,
	})

	return client
}

// IsWorkingInstance Checks that a registered IP is up and running. Blocking
func IsWorkingInstance(client *redis.Client) (bool, error) {
	err := try.Do(func(attempt int) (bool, error) {
		pong, err := client.Ping().Result()
		if err != nil && pong != "PONG" {
			log.Printf("Client (%s) not ready, will retry", client.Options().Addr)
		} else {
			log.Printf("Client (%s) ready", client.Options().Addr)
		}

		if err != nil {
			time.Sleep(2 * time.Second)
		}

		return true, err // infinite retry
	})

	if err != nil {
		return true, err
	}

	return false, err
}

package redis

import (
	"log"
	"time"

	redis "github.com/go-redis/redis"
	try "github.com/matryer/try"
)

// ConnectToClient Connects to a Redis server
func ConnectToClient(ip string, port string, config Config) *redis.Client {
	client := redis.NewClient(&redis.Options{
		Addr: ip + ":" + port,
	})

	return client
}

// IsWorkingInstance Checks that a registered IP is up and running. Blocking
func IsWorkingInstance(client *redis.Client) (bool, error) {
	err := try.Do(func(attempt int) (bool, error) {
		pong, err := client.Ping().Result()
		if err != nil && pong != "PONG" {
			log.Printf("Client (%s) not ready, will retry", client.Options().Addr)
		} else {
			log.Printf("Client (%s) ready", client.Options().Addr)
		}

		if err != nil {
			time.Sleep(2 * time.Second)
		}

		return attempt < 10, err
	})

	if err == nil {
		return true, err
	}

	return false, err
}

Fix logic around what constitutes a connection failure


package main

import (
	"fmt"
	"github.com/localghost/packer-pp/parser"
	"os"
	"encoding/json"
)

func main() {
	templatePath := os.Args[1]
	result, err := parser.ParseFile(templatePath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
	}
	json.NewEncoder(os.Stdout).Encode(result)
}

package main

import (
	"fmt"
	"github.com/localghost/ppp/parser"
	"os"
	"encoding/json"
)

func main() {
	templatePath := os.Args[1]
	result, err := parser.ParseFile(templatePath)
	if err != nil {
		fmt.Fprintf(os.Stderr, "Error: %s\n", err.Error())
	}
	json.NewEncoder(os.Stdout).Encode(result)
}

Fix path to parser package.


package hdfs

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

// Walk walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root. All errors that arise visiting files
// and directories are filtered by walkFn. The files are walked in lexical
// order, which makes the output deterministic but means that for very large
// directories Walk can be inefficient. Walk does not follow symbolic links.
func (c *Client) Walk(root string, walkFn filepath.WalkFunc) error {
	return c.walk(root, walkFn)
}

func (c *Client) walk(path string, walkFn filepath.WalkFunc) error {
	file, err := c.Open(path)
	var info os.FileInfo
	if file != nil {
		info = file.Stat()
	}

	err = walkFn(path, info, err)
	if err != nil {
		if info.IsDir() && err == filepath.SkipDir {
			return nil
		}

		return err
	}

	if info == nil || !info.IsDir() {
		return nil
	}

	names, err := file.Readdirnames(0)
	if err != nil {
		return walkFn(path, info, err)
	}

	sort.Strings(names)
	for _, name := range names {
		err = c.walk(filepath.Join(path, name), walkFn)
		if err != nil {
			return err
		}
	}

	return nil
}

package hdfs

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

// Walk walks the file tree rooted at root, calling walkFn for each file or
// directory in the tree, including root. All errors that arise visiting files
// and directories are filtered by walkFn. The files are walked in lexical
// order, which makes the output deterministic but means that for very large
// directories Walk can be inefficient. Walk does not follow symbolic links.
func (c *Client) Walk(root string, walkFn filepath.WalkFunc) error {
	return c.walk(root, walkFn)
}

func (c *Client) walk(path string, walkFn filepath.WalkFunc) error {
	file, err := c.Open(path)
	var info os.FileInfo
	if file != nil {
		info = file.Stat()
	}

	err = walkFn(path, info, err)
	if err != nil {
		if info.IsDir() && err == filepath.SkipDir {
			return nil
		}

		return err
	}

	if info == nil || !info.IsDir() {
		return nil
	}

	names, err := file.Readdirnames(0)
	if err != nil {
		return walkFn(path, info, err)
	}

	sort.Strings(names)
	for _, name := range names {
		err = c.walk(filepath.ToSlash(filepath.Join(path, name)), walkFn)
		if err != nil {
			return err
		}
	}

	return nil
}

Join using regular separators on the client, not OS-specific ones


package sack

import (
	"fmt"
	"io/ioutil"
	"path"
	"strings"
)

func checkState() {}

func splitLine(s string) []string {
	arr := strings.SplitN(s, ":", 3)
	return arr
}

func check(e error) {
	if e != nil {
		fmt.Printf("\n----\nError: %#v\n----\n", e)
		panic(e)
	}
}

func content() []string {
	filePath := path.Join(home, shortcutFilename)
	dat, err := ioutil.ReadFile(filePath)
	check(err)
	lines := strings.Split(string(dat), "\n")
	return lines[0 : len(lines)-1]
}

package sack

import (
	"fmt"
	"io/ioutil"
	"path"
	"strings"
)

func checkState() {}

func splitLine(s string) []string {
	arr := strings.SplitN(s, ":", 3)
	return arr
}

func check(e error) {
	if e != nil {
		fmt.Printf("\n----\nError: %#v\n----\n", e)
		panic(e)
	}
}

func content() []string {
	filePath := path.Join(home, shortcutFilename)
	dat, err := ioutil.ReadFile(filePath)
	if err != nil {
		fmt.Println("Unable to open shortcut file. Try doing a search.")
		panic(1)
	}
	lines := strings.Split(string(dat), "\n")
	return lines[0 : len(lines)-1]
}

Improve error message for no shortcut file


package interfaces

import (
	"time"
)

type WriteRequest struct {
	Timeseries []*Timeseries
}

type Operation int

const (
	EqualOperation Operation = iota
	NotEqualOperation
	GreaterThanOperation
	GreaterThanOrEqualOperation
	LessThanOperation
	LessThanOrEqualOperation
)

type Condition interface {
	IsCondition()
}

type CombineOperation int

// definition of combining operators with order of precedence
const (
	NotOperation CombineOperation = iota // First has to be nil
	AndOperation
	OrOperation
)

type CombiningCondition struct {
	First     *Condition
	CombineOp CombineOperation
	Second    *Condition
}

type ComparisonCondition struct {
	FieldName string
	Op        Operation
	Value     interface{}
}

// TODO: applying functions and joining time series
type ReadRequest struct {
	Timeseries   string
	IsRegex      bool // is the timeseries name a regex?
	StartTime    time.Time
	EndTime      time.Time
	IsContinuous bool
	Conditions   []*Condition
}

type StorageEngineProcessingI interface {
	WritePoints(request *WriteRequest) error
	ReadPoints(request *ReadRequest, yield func(pts []*Point) error) error
}

type StorageEngineConsensusI interface {
	// TODO: figure out the requirements of this interface. Probably the following
	// 1. Transfer part(s) of the ring to other node(s)
	// 2. Give up ownership of part(s) of the ring
	// 3. Take ownership of part(s) of the ring
}

package interfaces

import (
	"protocol"
	"time"
)

type WriteRequest struct {
	Timeseries []*protocol.Series
}

type Operation int

const (
	EqualOperation Operation = iota
	NotEqualOperation
	GreaterThanOperation
	GreaterThanOrEqualOperation
	LessThanOperation
	LessThanOrEqualOperation
)

type Condition interface {
	IsCondition()
}

type CombineOperation int

// definition of combining operators with order of precedence
const (
	NotOperation CombineOperation = iota // First has to be nil
	AndOperation
	OrOperation
)

type CombiningCondition struct {
	First     *Condition
	CombineOp CombineOperation
	Second    *Condition
}

type ComparisonCondition struct {
	FieldName string
	Op        Operation
	Value     interface{}
}

// TODO: applying functions and joining time series
type ReadRequest struct {
	Timeseries   string
	IsRegex      bool // is the timeseries name a regex?
	StartTime    time.Time
	EndTime      time.Time
	IsContinuous bool
	Conditions   []*Condition
}

type StorageEngineProcessingI interface {
	WritePoints(request *WriteRequest) error
	ReadPoints(request *ReadRequest, yield func(pts []*protocol.Point) error) error
}

type StorageEngineConsensusI interface {
	// TODO: figure out the requirements of this interface. Probably the following
	// 1. Transfer part(s) of the ring to other node(s)
	// 2. Give up ownership of part(s) of the ring
	// 3. Take ownership of part(s) of the ring
}

Fix the storage engine interface to build with things in protocol


package config

import (
	"github.com/ghthor/gospec"
	. "github.com/ghthor/gospec"
	"testing"
)

func TestUnitSpecs(t *testing.T) {
	r := gospec.NewRunner()

	r.AddSpec(DescribeConfigLoading)

	gospec.MainGoTest(r, t)
}

func DescribeConfigLoading(c gospec.Context) {
	c.Specify("Config can be parsed from json file", func() {
		expectedConfig := Config{
			"a/path/to/a/git/directory",
		}

		config, err := ReadFromFile("config.example.json")
		c.Assume(err, IsNil)
		c.Expect(config, Equals, expectedConfig)
	})
}

package config

import (
	"github.com/ghthor/gospec"
	. "github.com/ghthor/gospec"
	"testing"
)

func TestSpecs(t *testing.T) {
	r := gospec.NewRunner()

	r.AddSpec(DescribeConfigLoading)

	gospec.MainGoTest(r, t)
}

func DescribeConfigLoading(c gospec.Context) {
	c.Specify("Config can be parsed from json file", func() {
		expectedConfig := Config{
			"a/path/to/a/git/directory",
		}

		config, err := ReadFromFile("config.example.json")
		c.Assume(err, IsNil)
		c.Expect(config, Equals, expectedConfig)
	})
}

Change the name the test's are closer to integration | But they are both unit+integration cause the package is so simple


// Copyright (c) 2016, Janoš Guljaš <janos@resenje.org>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package httputils // import "resenje.org/httputils"

import "net/http"

// ChainHandlers executes each function from the arguments with handler
// from the next function to construct a chan fo callers.
func ChainHandlers(handlers ...func(http.Handler) http.Handler) (h http.Handler) {
	for i := len(handlers) - 1; i >= 0; i-- {
		h = handlers[i](h)
	}
	return
}

// FinalHandler is a helper function to wrap the last http.Handler element
// in the ChainHandlers function.
func FinalHandler(h http.Handler) func(h http.Handler) http.Handler {
	return func(_ http.Handler) http.Handler {
		return h
	}
}

// FinalHandler is a helper function to wrap the last function with signature
// func(w http.ResponseWriter, r *http.Request) in the ChainHandlers function.
func FinalHandlerFunc(h func(w http.ResponseWriter, r *http.Request)) func(h http.Handler) http.Handler {
	return func(_ http.Handler) http.Handler {
		return http.HandlerFunc(h)
	}
}

// Copyright (c) 2016, Janoš Guljaš <janos@resenje.org>
// All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package httputils // import "resenje.org/httputils"

import "net/http"

// ChainHandlers executes each function from the arguments with handler
// from the next function to construct a chan fo callers.
func ChainHandlers(handlers ...func(http.Handler) http.Handler) (h http.Handler) {
	for i := len(handlers) - 1; i >= 0; i-- {
		h = handlers[i](h)
	}
	return
}

// FinalHandler is a helper function to wrap the last http.Handler element
// in the ChainHandlers function.
func FinalHandler(h http.Handler) func(http.Handler) http.Handler {
	return func(_ http.Handler) http.Handler {
		return h
	}
}

// FinalHandler is a helper function to wrap the last function with signature
// func(w http.ResponseWriter, r *http.Request) in the ChainHandlers function.
func FinalHandlerFunc(h func(w http.ResponseWriter, r *http.Request)) func(http.Handler) http.Handler {
	return func(_ http.Handler) http.Handler {
		return http.HandlerFunc(h)
	}
}

Remove unused variable from FinalHandler and FinalHandlerFunc


package kala

import (
	"math/big"
	"net"
)

func MacAddressToWorkerId(mac string) (int64, error) {
	hw, err := net.ParseMAC(mac)
	if err != nil {
		return 0, err
	}

	workerId := new(big.Int).SetBytes([]byte(hw)).Int64()

	return workerId, nil
}

package kala

import (
	"math/big"
	"net"
)

func MacAddressToWorkerId(mac string) (uint64, error) {
	hw, err := net.ParseMAC(mac)
	if err != nil {
		return 0, err
	}

	workerId := new(big.Int).SetBytes([]byte(hw)).Uint64()

	return workerId, nil
}

Return worker id as uint when converting from mac address


package main

import (
	"net/http"

	"github.com/Felamande/filesync/syncer"
)

func main() {
	syncer.New().Run()
	http.ListenAndServe(":8070", nil)
}

package main

import (
	"net/http"

	"github.com/Felamande/filesync/log"
	"github.com/go-martini/martini"

	"github.com/Felamande/filesync/syncer"
)

func main() {
	s := syncer.New()
	m := martini.Classic()
	l := log.NewFileLogger("./.log/http.log")
	m.Map(s)
	m.Map(l)
	m.Post("/new", NewPair)
	m.Get("/new", HelloNewPair)
	go s.Run()
	http.ListenAndServe(":20000", m)

}

func NewPair(logger *log.FileLogger, s *syncer.Syncer, w http.ResponseWriter, r *http.Request) int {
	r.ParseForm()
	_, lExist := r.Form["left"]
	_, rExist := r.Form["right"]

	if !lExist || !rExist {
		return 400

	}
	return 200

}

func HelloNewPair() string {
	return "Hello"
}

Test http server powered by martini


package main

import (
	"reflect"
)

func walkStruct(s interface{}, f func(string, reflect.Value) error) error {
	var inner func(v reflect.Value, p string) error
	inner = func(v reflect.Value, p string) error {
		t := v.Type()
		for i := 0; i < v.NumField(); i++ {
			name := t.Field(i).Name
			if (name[0] < 'A') || (name[0] > 'Z') {
				continue
			}

			var err error
			switch field := reflect.Indirect(v.Field(i)); field.Kind() {
			case reflect.Struct:
				err = inner(field, p+name+".")
			default:
				err = f(p+name, field)
			}
			if err != nil {
				return err
			}
		}

		return nil
	}

	return inner(reflect.Indirect(reflect.ValueOf(s)), "")
}

package main

import (
	"reflect"
)

// walkStruct walks through a struct and all sub-structs recustively,
// calling f on all 'leaf' fields. The first argument to f is the name
// of the field in the form parent.field, and the second argument is
// the field itself. If any call to f returns non-nil error,
// walkStruct stops and returns that error.
func walkStruct(s interface{}, f func(string, reflect.Value) error) error {
	var inner func(v reflect.Value, p string) error
	inner = func(v reflect.Value, p string) error {
		t := v.Type()
		for i := 0; i < v.NumField(); i++ {
			name := t.Field(i).Name
			if (name[0] < 'A') || (name[0] > 'Z') {
				continue
			}

			var err error
			switch field := reflect.Indirect(v.Field(i)); field.Kind() {
			case reflect.Struct:
				err = inner(field, p+name+".")
			default:
				err = f(p+name, field)
			}
			if err != nil {
				return err
			}
		}

		return nil
	}

	return inner(reflect.Indirect(reflect.ValueOf(s)), "")
}

Add godoc comment to walkStruct().


package main

import (
	"fmt"
	"github.com/minaguib/berlingo"
	"math/rand"
)

/*
This example mimicks the functionality in the berlin-ai demo ruby gem at:
https://github.com/thirdside/berlin-ai/
*/

type AI1 struct{}

func (ai *AI1) GameStart(game *berlingo.Game) {
}

func (ai *AI1) Turn(game *berlingo.Game) {
	for _, node := range game.Map.ControlledNodes() {
		for _, other_node := range node.Paths_Outbound {
			soldiers := rand.Intn(node.Available_Soldiers)
			fmt.Println("Moving", soldiers, "soldiers from node", node.Id, "to node", other_node.Id)
			if err := game.AddMove(node, other_node, soldiers); err != nil {
				fmt.Println("Error moving:", err)
			}
		}
	}
}

func (ai *AI1) GameOver(game *berlingo.Game) {
}

func (ai *AI1) Ping(game *berlingo.Game) {
}

package main

import (
	"fmt"
	"github.com/minaguib/berlingo"
	"math/rand"
)

/*
This example mimicks the functionality in the berlin-ai demo ruby gem at:
https://github.com/thirdside/berlin-ai/
*/

type AI1 struct{}

func (ai *AI1) GameStart(game *berlingo.Game) {
}

func (ai *AI1) Turn(game *berlingo.Game) {
	for _, node := range game.Map.ControlledNodes() {
		for _, other_node := range node.Paths_Outbound {
			if node.Available_Soldiers < 1 {
				continue
			}
			soldiers := rand.Intn(node.Available_Soldiers)
			fmt.Println("Moving", soldiers, "soldiers from node", node.Id, "to node", other_node.Id)
			if err := game.AddMove(node, other_node, soldiers); err != nil {
				fmt.Println("Error moving:", err)
			}
		}
	}
}

func (ai *AI1) GameOver(game *berlingo.Game) {
}

func (ai *AI1) Ping(game *berlingo.Game) {
}

Fix occasional crash due to calling rand.Intn(0)


package storage

import (
	"github.com/rafaeljusto/toglacier/internal/archive"
	"github.com/rafaeljusto/toglacier/internal/cloud"
)

// Backup stores the cloud location of the backup and some extra information
// about the files of the backup.
type Backup struct {
	Backup cloud.Backup
	Info   archive.Info
}

// Backups represents a sorted list of backups that are ordered by creation
// date. It has the necessary methods so you could use the sort package of the
// standard library.
type Backups []Backup

// Len returns the number of backups.
func (b Backups) Len() int { return len(b) }

// Less compares two positions of the slice and verifies the preference. They
// are ordered from the newest backup to the oldest.
func (b Backups) Less(i, j int) bool { return b[i].Backup.CreatedAt.After(b[j].Backup.CreatedAt) }

// Swap change the backups position inside the slice.
func (b Backups) Swap(i, j int) { b[i], b[j] = b[j], b[i] }

// Storage represents all commands to manage backups information locally. After
// the backup is uploaded we must keep track of them locally to speed up
// recovery and cloud cleanup (remove old ones).
type Storage interface {
	// Save a backup information.
	Save(Backup) error

	// List all backup informations in the storage.
	List() (Backups, error)

	// Remove a specific backup information from the storage.
	Remove(id string) error
}

package storage

import (
	"github.com/rafaeljusto/toglacier/internal/archive"
	"github.com/rafaeljusto/toglacier/internal/cloud"
)

// Backup stores the cloud location of the backup and some extra information
// about the files of the backup.
type Backup struct {
	Backup cloud.Backup // TODO: rename this attribute?
	Info   archive.Info
}

// Backups represents a sorted list of backups that are ordered by creation
// date. It has the necessary methods so you could use the sort package of the
// standard library.
type Backups []Backup

// Len returns the number of backups.
func (b Backups) Len() int { return len(b) }

// Less compares two positions of the slice and verifies the preference. They
// are ordered from the newest backup to the oldest.
func (b Backups) Less(i, j int) bool { return b[i].Backup.CreatedAt.After(b[j].Backup.CreatedAt) }

// Swap change the backups position inside the slice.
func (b Backups) Swap(i, j int) { b[i], b[j] = b[j], b[i] }

// Storage represents all commands to manage backups information locally. After
// the backup is uploaded we must keep track of them locally to speed up
// recovery and cloud cleanup (remove old ones).
type Storage interface {
	// Save a backup information.
	Save(Backup) error

	// List all backup informations in the storage.
	List() (Backups, error)

	// Remove a specific backup information from the storage.
	Remove(id string) error
}

Add reminder to improve the code


package funk

import "reflect"

func equal(expected, actual interface{}) bool {
	if expected == nil || actual == nil {
		return expected == actual
	}

	return reflect.DeepEqual(expected, actual)

}

func sliceElem(rtype reflect.Type) reflect.Type {
	if rtype.Kind() == reflect.Slice || rtype.Kind() == reflect.Array {
		return sliceElem(rtype.Elem())
	}

	return rtype
}

func redirectValue(value reflect.Value) reflect.Value {
	for {
		if !value.IsValid() || value.Kind() != reflect.Ptr {
			return value
		}

		value = value.Elem()
	}
}

func makeSlice(value reflect.Value, values ...int) reflect.Value {
	sliceType := sliceElem(value.Type())

	size := value.Len()
	cap := size

	if len(values) > 0 {
		size = values[0]
	}

	if len(values) > 1 {
		cap = values[1]
	}

	return reflect.MakeSlice(reflect.SliceOf(sliceType), size, cap)
}

package funk

import "reflect"

func equal(expected, actual interface{}) bool {
	if expected == nil || actual == nil {
		return expected == actual
	}

	return reflect.DeepEqual(expected, actual)

}

func sliceElem(rtype reflect.Type) reflect.Type {
	for {
		if rtype.Kind() != reflect.Slice && rtype.Kind() != reflect.Array {
			return rtype
		}

		rtype = rtype.Elem()
	}
}

func redirectValue(value reflect.Value) reflect.Value {
	for {
		if !value.IsValid() || value.Kind() != reflect.Ptr {
			return value
		}

		res := reflect.Indirect(value)

		// Test for a circular type.
		if res.Kind() == reflect.Ptr && value.Pointer() == res.Pointer() {
			return value
		}

		value = res
	}
}

func makeSlice(value reflect.Value, values ...int) reflect.Value {
	sliceType := sliceElem(value.Type())

	size := value.Len()
	cap := size

	if len(values) > 0 {
		size = values[0]
	}

	if len(values) > 1 {
		cap = values[1]
	}

	return reflect.MakeSlice(reflect.SliceOf(sliceType), size, cap)
}

Fix redirectValue for circular type


package feeds

import (
	"net/http"

	"github.com/gorilla/mux"
	"github.com/rs/cors"
	"google.golang.org/appengine"
)

func Run() {
	dao := datastoreFeedsDao{}
	router := mux.NewRouter()

	router.Handle("/feeds", cors.Default().Handler(getFeedsHandler{dao})).
		Methods(http.MethodGet)

	getHandler := cors.Default().Handler(getFeedHandler{dao})
	router.Handle("/feeds/{feedId}", getHandler).
		Methods(http.MethodGet)

	postHandler := cors.Default().Handler(postHttpHandler{appengine.NewContext, fetchRssWithUrlFetch, dao})
	router.Handle("/feeds", postHandler).
		Methods(http.MethodPost).
		Headers("Content-Type", "application/json")

	http.Handle("/", cors.Default().Handler(router))
}

package feeds

import (
	"net/http"

	"github.com/gorilla/mux"
	"github.com/rs/cors"
	"google.golang.org/appengine"
)

func Run() {
	dao := datastoreFeedsDao{}
	router := mux.NewRouter()

	corsHandler := cors.New(cors.Options{
		AllowedHeaders:{"Location"},
	})
	router.Handle("/feeds", corsHandler(getFeedsHandler{dao})).
		Methods(http.MethodGet)

	getHandler := corsHandler(getFeedHandler{dao})
	router.Handle("/feeds/{feedId}", getHandler).
		Methods(http.MethodGet)

	postHandler := corsHandler(postHttpHandler{appengine.NewContext, fetchRssWithUrlFetch, dao})
	router.Handle("/feeds", postHandler).
		Methods(http.MethodPost).
		Headers("Content-Type", "application/json")

	http.Handle("/", corsHandler(router))
}

Add CORS handler for Location header


package app

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

type dfScreenEventHandler struct {
	baseEventHandler
}

func (h *dfScreenEventHandler) handle(event termbox.Event) {
	h.setFocus(true)
}

package app

import (
	"github.com/moncho/dry/appui"
	termbox "github.com/nsf/termbox-go"
)

const (
	confirmation = `WARNING! This will remove all unused data. Are you sure you want to continue? [y/N]`
)

type diskUsageScreenEventHandler struct {
	baseEventHandler
}

func (h *diskUsageScreenEventHandler) handle(event termbox.Event) {
	handled := false
	ignored := false
	switch event.Key {
	case termbox.KeyArrowUp | termbox.KeyArrowDown:
		//To avoid that the base handler handles this
		ignored = true
		handled = true

	case termbox.KeyCtrlP: //prune
		handled = true
		if confirmation, err := appui.ReadLine(confirmation); err == nil {
			h.screen.ClearAndFlush()
			if confirmation == "Y" || confirmation == "y" {
				h.dry.Prune()
			}
		}
	}
	if handled {
		h.setFocus(true)
		if !ignored {
			h.renderChan <- struct{}{}
		}
	} else {
		h.baseEventHandler.handle(event)
	}

}

Add event handler for df screen


package xmpp

import (
	"fmt"
	"net"
)

const (
	// Standard port for XMPP clients to connect to.
	XMPP_CLIENT_PORT = 5222
)

// Perform a DNS SRV lookup and return an ordered list of "host:port" TCP
// addresses for the JID's home server. If no SRV records are found then assume
// the JID's domain is also the home server.
func HomeServerAddrs(jid JID) (addr []string, err error) {

	// DNS lookup.
	_, addrs, _ := net.LookupSRV("xmpp-client", "tcp", jid.Domain)

	// If there's nothing in DNS then assume the JID's domain and the standard
	// port will work.
	if len(addrs) == 0 {
		addr = []string{fmt.Sprintf("%s:%d", jid.Domain, XMPP_CLIENT_PORT)}
		return
	}

	// Build list of "host:port" strings.
	for _, a := range addrs {
		target := parseTargetDomainName(a.Target)
		addr = append(addr, fmt.Sprintf("%s:%d", target, a.Port))
	}
	return
}

// Remove the last dot in the domain name if exist
func parseTargetDomainName(domainName string) (ret string) {
	if domainName[len(domainName)-1] == '.' {
		ret = parseTargetDomainName(domainName[:len(domainName)-1])
	} else {
		ret = domainName
	}
	return
}

package xmpp

import (
	"fmt"
	"net"
	"strings"
)

const (
	// Standard port for XMPP clients to connect to.
	XMPP_CLIENT_PORT = 5222
)

// Perform a DNS SRV lookup and return an ordered list of "host:port" TCP
// addresses for the JID's home server. If no SRV records are found then assume
// the JID's domain is also the home server.
func HomeServerAddrs(jid JID) (addr []string, err error) {

	// DNS lookup.
	_, addrs, _ := net.LookupSRV("xmpp-client", "tcp", jid.Domain)

	// If there's nothing in DNS then assume the JID's domain and the standard
	// port will work.
	if len(addrs) == 0 {
		addr = []string{fmt.Sprintf("%s:%d", jid.Domain, XMPP_CLIENT_PORT)}
		return
	}

	// Build list of "host:port" strings.
	for _, a := range addrs {
		target := strings.TrimRight(a.Target, ".")
		addr = append(addr, fmt.Sprintf("%s:%d", target, a.Port))
	}
	return
}

Remove useless function that already exist in strings pakage.


package bitbucket

import (
	"code.cloudfoundry.org/lager"
	api "github.com/SHyx0rmZ/go-bitbucket/bitbucket"
	"github.com/concourse/atc/auth/verifier"
	"net/http"
)

type UserVerifier struct {
	users  []string
	client api.Client
}

func NewUserVerifier(client api.Client, users []string) verifier.Verifier {
	return UserVerifier{
		users: users,
	}
}

func (verifier UserVerifier) Verify(logger lager.Logger, c *http.Client) (bool, error) {
	currentUser, err := verifier.client.CurrentUser()
	if err != nil {
		logger.Error("failed-to-get-current-user", err)
		return false, err
	}

	for _, user := range verifier.users {
		if user == currentUser {
			return true, nil
		}
	}

	logger.Info("not-validated-user", lager.Data{
		"have": currentUser,
		"want": verifier.users,
	})

	return false, nil
}

package bitbucket

import (
	"code.cloudfoundry.org/lager"
	api "github.com/SHyx0rmZ/go-bitbucket/bitbucket"
	"github.com/concourse/atc/auth/verifier"
	"net/http"
)

type UserVerifier struct {
	users  []string
	client api.Client
}

func NewUserVerifier(client api.Client, users []string) verifier.Verifier {
	return UserVerifier{
		users:  users,
		client: client,
	}
}

func (verifier UserVerifier) Verify(logger lager.Logger, c *http.Client) (bool, error) {
	verifier.client.SetHTTPClient(c)

	currentUser, err := verifier.client.CurrentUser()
	if err != nil {
		logger.Error("failed-to-get-current-user", err)
		return false, err
	}

	for _, user := range verifier.users {
		if user == currentUser {
			return true, nil
		}
	}

	logger.Info("not-validated-user", lager.Data{
		"have": currentUser,
		"want": verifier.users,
	})

	return false, nil
}

Set HTTP client in UserVerifier


package randomword_test

import (
	"time"

	. "code.cloudfoundry.org/cli/util/randomword"

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

var _ = Describe("Generator", func() {
	var gen Generator

	BeforeEach(func() {
		gen = Generator{}
	})

	Describe("RandomAdjective", func() {
		It("generates a random adjective each time it is called", func() {
			adj := gen.RandomAdjective()
			// We wait for 1 millisecond because the seed we use to generate the randomness has a unit of 1 nanosecond
			time.Sleep(1)
			Expect(adj).ToNot(Equal(gen.RandomAdjective()))
		})
	})

	Describe("RandomNoun", func() {
		It("generates a random noun each time it is called", func() {
			noun := gen.RandomNoun()
			// We wait for 1 millisecond because the seed we use to generate the randomness has a unit of 1 nanosecond
			time.Sleep(1)
			Expect(noun).ToNot(Equal(gen.RandomNoun()))
		})
	})

	Describe("Babble", func() {
		It("generates a random adjective noun pair each time it is called", func() {
			wordPair := gen.Babble()
			Expect(wordPair).To(MatchRegexp("^\\w+-\\w+$"))
		})
	})
})

package randomword_test

import (
	"time"

	. "code.cloudfoundry.org/cli/util/randomword"

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

var _ = Describe("Generator", func() {
	var gen Generator

	BeforeEach(func() {
		gen = Generator{}
	})

	Describe("RandomAdjective", func() {
		It("generates a random adjective each time it is called", func() {
			adj := gen.RandomAdjective()
			// We wait for 3 millisecond because the seed we use to generate the
			// randomness has a unit of 1 nanosecond plus random test flakiness
			time.Sleep(3)
			Expect(adj).ToNot(Equal(gen.RandomAdjective()))
		})
	})

	Describe("RandomNoun", func() {
		It("generates a random noun each time it is called", func() {
			noun := gen.RandomNoun()
			// We wait for 3 millisecond because the seed we use to generate the
			// randomness has a unit of 1 nanosecond plus random test flakiness
			time.Sleep(3)
			Expect(noun).ToNot(Equal(gen.RandomNoun()))
		})
	})

	Describe("Babble", func() {
		It("generates a random adjective noun pair each time it is called", func() {
			wordPair := gen.Babble()
			Expect(wordPair).To(MatchRegexp("^\\w+-\\w+$"))
		})
	})
})

Fix flakiness from random seed generator


package services

import (
	"os"
	"fmt"
	"net/http"
	"encoding/json"
	"github.com/jmoiron/jsonq"
	"strconv"
)

const (
	slackUserListURL = "https://slack.com/api/users.list"
)

func SlackUserList() (map[string]string, error){
	token := os.Getenv("SLACK_API_TOKEN")
	if token == "" {
		return nil, fmt.Errorf("You need to pass SLACK_API_TOKEN as environment variable")
	}
	requestURL := slackUserListURL + "?token=" + token
	resp, err := http.Get(requestURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	data := map[string]interface{}{}
	dec := json.NewDecoder(resp.Body)
	dec.Decode(&data)
	jq := jsonq.NewQuery(data)
	arr, err := jq.Array("members")

	users := make(map[string]string)
	for i := 0; i < len(arr); i++ {
		id, _ := jq.String("members", strconv.Itoa(i), "id")
		name, _ := jq.String("members", strconv.Itoa(i), "name")
		users[name] = id
	}
	return users, err
}

package services

import (
	"os"
	"fmt"
	"net/http"
	"encoding/json"
	"strconv"

	"github.com/jmoiron/jsonq"
)

const (
	slackUserListURL = "https://slack.com/api/users.list"
)

func SlackUserList() (map[string]string, error){
	token := os.Getenv("SLACK_API_TOKEN")
	if token == "" {
		return nil, fmt.Errorf("You need to pass SLACK_API_TOKEN as environment variable")
	}
	requestURL := slackUserListURL + "?token=" + token
	resp, err := http.Get(requestURL)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	data := map[string]interface{}{}
	dec := json.NewDecoder(resp.Body)
	dec.Decode(&data)
	jq := jsonq.NewQuery(data)
	arr, err := jq.Array("members")

	users := make(map[string]string)
	for i := 0; i < len(arr); i++ {
		id, _ := jq.String("members", strconv.Itoa(i), "id")
		name, _ := jq.String("members", strconv.Itoa(i), "name")
		users[name] = id
	}
	return users, err
}

Reorder import in slack service


package command

// A CommandCallback takes the name of the player invoking the command, any
// text supplied after the trigger for the command, and an interface via which
// game-wide 'actions' can be taken.
type CommandCallback func(string, string, ICommandHandler)

type Command struct {
	Trigger     string          // The initial text eg. "give".
	Description string          // A description of what the command does.
	Usage       string          // A usage string for the command.
	Callback    CommandCallback // This function will be called if a Message begins with the CommandPrefix and the Trigger.
}

func NewCommand(trigger, desc, usage string, callback CommandCallback) *Command {
	return &Command{Trigger: trigger, Description: desc, Usage: usage, Callback: callback}
}

package command

// A CommandCallback takes the name of the player invoking the command, any
// text supplied after the trigger for the command, and an interface via which
// game-wide 'actions' can be taken.
type CommandCallback func(playerName string, args string, handler ICommandHandler)

type Command struct {
	Trigger     string          // The initial text eg. "give".
	Description string          // A description of what the command does.
	Usage       string          // A usage string for the command.
	Callback    CommandCallback // This function will be called if a Message begins with the CommandPrefix and the Trigger.
}

func NewCommand(trigger, desc, usage string, callback CommandCallback) *Command {
	return &Command{Trigger: trigger, Description: desc, Usage: usage, Callback: callback}
}

Add parameter names to CommandCallback


package resources

import (
	"fmt"

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

func init() {
	register("CloudWatchEventsRule", ListCloudWatchEventsRules)
}

func ListCloudWatchEventsRules(sess *session.Session) ([]Resource, error) {
	svc := cloudwatchevents.New(sess)

	resp, err := svc.ListRules(nil)
	if err != nil {
		return nil, err
	}
	resources := make([]Resource, 0)
	for _, rule := range resp.Rules {
		resources = append(resources, &CloudWatchEventsRule{
			svc:  svc,
			name: rule.Name,
		})

	}
	return resources, nil
}

type CloudWatchEventsRule struct {
	svc  *cloudwatchevents.CloudWatchEvents
	name *string
}

func (rule *CloudWatchEventsRule) Remove() error {
	_, err := rule.svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{
		Name: rule.name,
	})
	return err
}

func (rule *CloudWatchEventsRule) String() string {
	return fmt.Sprintf("Rule: %s", *rule.name)
}

package resources

import (
	"fmt"

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

func init() {
	register("CloudWatchEventsRule", ListCloudWatchEventsRules)
}

func ListCloudWatchEventsRules(sess *session.Session) ([]Resource, error) {
	svc := cloudwatchevents.New(sess)

	resp, err := svc.ListRules(nil)
	if err != nil {
		return nil, err
	}
	resources := make([]Resource, 0)
	for _, rule := range resp.Rules {
		resources = append(resources, &CloudWatchEventsRule{
			svc:  svc,
			name: rule.Name,
		})

	}
	return resources, nil
}

type CloudWatchEventsRule struct {
	svc  *cloudwatchevents.CloudWatchEvents
	name *string
}

func (rule *CloudWatchEventsRule) Remove() error {
	_, err := rule.svc.DeleteRule(&cloudwatchevents.DeleteRuleInput{
		Name: rule.name,
		Force: aws.Bool(true),
	})
	return err
}

func (rule *CloudWatchEventsRule) String() string {
	return fmt.Sprintf("Rule: %s", *rule.name)
}

Add Force flag to CW events rule deletion


package turnservicecli

// CredentialsResponse defines a REST response containing TURN data.
type CredentialsResponse struct {
	Success bool             `json:"success"`
	Nonce   string           `json:"nonce"`
	Turn    *CredentialsData `json:"turn"`
	Session string           `json:"session,omitempty"`
}

// CredentialsData defines TURN credentials with servers.
type CredentialsData struct {
	TTL      int64         `json:"ttl"`
	Username string        `json:"username"`
	Password string        `json:"password"`
	Servers  []*URNsWithID `json:"servers,omitempty"`
	GeoURI   string        `json:"geo_uri,omitempty"`
}

// URNsWithID defines TURN servers groups with ID.
type URNsWithID struct {
	ID    string            `json:"id"`
	URNs  []string          `json:"urns"`
	Prio  int               `json:"prio"`
	Label string            `json:"label,omitempty"`
	I18N  map[string]string `json:"i18n,omitempty"`
}

// GeoResponse defines a REST response containing TURN geo.
type GeoResponse struct {
	Success bool     `json:"success"`
	Nonce   string   `json:"nonce"`
	Geo     *GeoData `json:"geo,omitempty"`
}

// GeoData defines ordered TURN IDs.
type GeoData struct {
	Prefer []string `json:"prefer"`
}

package turnservicecli

import (
	"time"
)

// CredentialsResponse defines a REST response containing TURN data.
type CredentialsResponse struct {
	Success bool             `json:"success"`
	Nonce   string           `json:"nonce"`
	Expires *time.Time       `json:"expires,omitempty"`
	Turn    *CredentialsData `json:"turn"`
	Session string           `json:"session,omitempty"`
}

// CredentialsData defines TURN credentials with servers.
type CredentialsData struct {
	TTL      int64         `json:"ttl"`
	Username string        `json:"username"`
	Password string        `json:"password"`
	Servers  []*URNsWithID `json:"servers,omitempty"`
	GeoURI   string        `json:"geo_uri,omitempty"`
}

// URNsWithID defines TURN servers groups with ID.
type URNsWithID struct {
	ID    string            `json:"id"`
	URNs  []string          `json:"urns"`
	Prio  int               `json:"prio"`
	Label string            `json:"label,omitempty"`
	I18N  map[string]string `json:"i18n,omitempty"`
}

// GeoResponse defines a REST response containing TURN geo.
type GeoResponse struct {
	Success bool     `json:"success"`
	Nonce   string   `json:"nonce"`
	Geo     *GeoData `json:"geo,omitempty"`
}

// GeoData defines ordered TURN IDs.
type GeoData struct {
	Prefer []string `json:"prefer"`
}

Return optional field when access token / client id will expire.


package slack

import (
	"errors"
	"net/url"
)

type oAuthResponseFull struct {
	AccessToken string `json:"access_token"`
	Scope       string `json:"scope"`
	SlackResponse
}

// GetOAuthToken retrieves an AccessToken
func GetOAuthToken(clientID, clientSecret, code, redirectURI string, debug bool) (accessToken string, scope string, err error) {
	values := url.Values{
		"client_id":     {clientID},
		"client_secret": {clientSecret},
		"code":          {code},
		"redirect_uri":  {redirectURI},
	}
	response := &oAuthResponseFull{}
	err = post("oauth.access", values, response, debug)
	if err != nil {
		return "", "", err
	}
	if !response.Ok {
		return "", "", errors.New(response.Error)
	}
	return response.AccessToken, response.Scope, nil
}

package slack

import (
	"errors"
	"net/url"
)

type OAuthResponseIncomingWebhook struct {
	URL              string `json:"url"`
	Channel          string `json:"channel"`
	ConfigurationURL string `json:"configuration_url"`
}

type OAuthResponseBot struct {
	BotUserID      string `json:"bot_user_id"`
	BotAccessToken string `json:"bot_access_token"`
}

type OAuthResponse struct {
	AccessToken     string                       `json:"access_token"`
	Scope           string                       `json:"scope"`
	TeamName        string                       `json:"team_name"`
	TeamID          string                       `json:"team_id"`
	IncomingWebhook OAuthResponseIncomingWebhook `json:"incoming_webhook"`
	Bot             OAuthResponseBot             `json:"bot"`
	SlackResponse
}

// GetOAuthToken retrieves an AccessToken
func GetOAuthToken(clientID, clientSecret, code, redirectURI string, debug bool) (accessToken string, scope string, err error) {
	response, err := GetOAuthResponse(clientID, clientSecret, code, redirectURI, debug)
	if err != nil {
		return "", "", err
	}
	return response.AccessToken, response.Scope, nil
}

func GetOAuthResponse(clientID, clientSecret, code, redirectURI string, debug bool) (resp *OAuthResponse, err error) {
	values := url.Values{
		"client_id":     {clientID},
		"client_secret": {clientSecret},
		"code":          {code},
		"redirect_uri":  {redirectURI},
	}
	response := &OAuthResponse{}
	err = post("oauth.access", values, response, debug)
	if err != nil {
		return nil, err
	}
	if !response.Ok {
		return nil, errors.New(response.Error)
	}
	return response, nil
}

Support full OAauth response (for adding hooks and bot users via OAuth)


package commands

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

var outCmd = &cobra.Command{
	Use:   "out",
	Short: "Write a file based on key data.",
	Long:  `out is for writing a file based on a Consul key.`,
	Run:   outRun,
}

func outRun(cmd *cobra.Command, args []string) {
	checkFlags()
}

func checkFlags() {
	if KeyLocation == "" {
		fmt.Println("Need a key location in -k")
	}
	if FiletoWrite == "" {
		fmt.Println("Need a file to write in -f")
	}
}

var KeyLocation string
var FiletoWrite string
var MinFileLength int

func init() {
	RootCmd.AddCommand(outCmd)
	outCmd.Flags().StringVarP(&KeyLocation, "key", "k", "", "key to pull data from")
	outCmd.Flags().StringVarP(&FiletoWrite, "file", "f", "", "where to write the data")
	outCmd.Flags().IntVarP(&MinFileLength, "length", "l", 10, "minimum amount of lines in the file")
}

package commands

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

var outCmd = &cobra.Command{
	Use:   "out",
	Short: "Write a file based on key data.",
	Long:  `out is for writing a file based on a Consul key.`,
	Run:   outRun,
}

func outRun(cmd *cobra.Command, args []string) {
	checkFlags()
}

func checkFlags() {
	if KeyLocation == "" {
		fmt.Println("Need a key location in -k")
		os.Exit(1)
	}
	if FiletoWrite == "" {
		fmt.Println("Need a file to write in -f")
		os.Exit(1)
	}
}

var KeyLocation string
var FiletoWrite string
var MinFileLength int

func init() {
	RootCmd.AddCommand(outCmd)
	outCmd.Flags().StringVarP(&KeyLocation, "key", "k", "", "key to pull data from")
	outCmd.Flags().StringVarP(&FiletoWrite, "file", "f", "", "where to write the data")
	outCmd.Flags().IntVarP(&MinFileLength, "length", "l", 10, "minimum amount of lines in the file")
}

Exit the command if it doesn't have the right flags.


package main

import (
	"flag"
	"log"
)

type AppConfig struct {
	verbose     bool
	newRelicKey string
	database    string
	interval    int
	user        string
	host        string
}

func HandleUserOptions() AppConfig {

	var config AppConfig

	flag.BoolVar(&config.verbose, "verbose", false, "Verbose mode")
	flag.StringVar(&config.newRelicKey, "key", "", "Newrelic license key (required)")
	flag.StringVar(&config.database, "database", "", "Database name (required)")
	flag.IntVar(&config.interval, "interval", 1, "Sampling interval [min]")
	flag.StringVar(&config.user, "user", "postgres", "Database user name")
	flag.StringVar(&config.host, "host", "localhost:5432", "Database host")

	flag.Parse()

	if config.newRelicKey == "" ||
		config.database == "" {
		flag.PrintDefaults()
		log.Fatal("Required parameter missing.")
	}

	return config
}

package main

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

// build number set on during linking
var minversion string

type AppConfig struct {
	verbose     bool
	newRelicKey string
	database    string
	interval    int
	user        string
	host        string
	version     bool
}

func HandleUserOptions() AppConfig {

	var config AppConfig

	flag.BoolVar(&config.verbose, "verbose", false, "Verbose mode")
	flag.StringVar(&config.newRelicKey, "key", "", "Newrelic license key (required)")
	flag.StringVar(&config.database, "database", "", "Database name (required)")
	flag.IntVar(&config.interval, "interval", 1, "Sampling interval [min]")
	flag.StringVar(&config.user, "user", "postgres", "Database user name")
	flag.StringVar(&config.host, "host", "localhost:5432", "Database host")
	flag.BoolVar(&config.version, "version", false, "Print version")

	flag.Parse()

	if config.version {
		fmt.Printf("Build: %s\n", minversion)
		os.Exit(0)
	}

	if config.newRelicKey == "" ||
		config.database == "" {
		flag.PrintDefaults()
		log.Fatal("Required parameter missing.")
	}

	return config
}

Add version option for printing build number


package main

import (
	"fmt"
	"time"

	"github.com/miquella/ask"

	"github.com/miquella/vaulted/lib"
)

type Spawn struct {
	SessionOptions

	Command       []string
	DisplayStatus bool
}

func (s *Spawn) Run(store vaulted.Store) error {
	session, err := GetSessionWithOptions(store, &s.SessionOptions)
	if err != nil {
		return err
	}

	timeRemaining := session.Expiration.Sub(time.Now())
	timeRemaining = time.Second * time.Duration(timeRemaining.Seconds())
	if s.DisplayStatus {
		ask.Print(fmt.Sprintf("%s — expires: %s (%s remaining)\n", session.Name, session.Expiration.Format("2 Jan 2006 15:04 MST"), timeRemaining))
	}

	code, err := session.Spawn(s.Command)
	if err != nil {
		return ErrorWithExitCode{err, 2}
	} else if *code != 0 {
		return ErrorWithExitCode{ErrNoError, *code}
	}

	return nil
}

Replace non-breaking space with regular space


package main

import (
	"fmt"
	"net"
	"os"

	flags "github.com/jessevdk/go-flags"
)

const version = "1.0.0"

var opts struct {
	Version bool `short:"v" long:"version" description:"Show version"`
}

func main() {
	parser := flags.NewParser(&opts, flags.Default)
	parser.Usage = "HOSTNAME [OPTIONS]"
	args, _ := parser.Parse()

	if len(args) == 0 {
		if opts.Version {
			fmt.Println("ptrhost version", version)
		}
		os.Exit(1)
	}

	hostname := args[0]
	addr, _ := net.LookupHost(hostname)
	for _, v := range addr {
		ptrAddr, _ := net.LookupAddr(v)
		fmt.Println(v, "->", ptrAddr[0])
	}
}

package main

import (
	"fmt"
	"net"
	"os"

	flags "github.com/jessevdk/go-flags"
)

const version = "1.0.0"

var opts struct {
	Version bool `short:"v" long:"version" description:"Show version"`
}

func main() {
	parser := flags.NewParser(&opts, flags.Default)
	parser.Usage = "HOSTNAME [OPTIONS]"
	args, _ := parser.Parse()

	if len(args) == 0 {
		if opts.Version {
			fmt.Println("ptrhost version", version)
		}
		os.Exit(1)
	}

	hostname := args[0]
	addr, _ := net.LookupHost(hostname)
	for _, v := range addr {
		resolvedHost, err := net.LookupAddr(v)
		if err == nil {
			fmt.Println(v, "->", resolvedHost[0])
		} else {
			fmt.Println(v, "->", err.(*net.DNSError).Err)
		}
	}
}

Fix crash when none resolved hostname


package main

import (
	"os"
	"fmt"

	"github.com/urfave/cli"
)

// Called when thaum is actually run.
func onRun(c *cli.Context) error {
	template := c.Args().Get(0)
	name := c.Args().Get(1)

	if len(c.Args()) == 0 {
		cli.ShowAppHelp(c)
		return nil
	}

	if name == "" {
		ErrorLog(fmt.Sprintf("Thaum requires a name for your %q template.", template))
		return nil
	}

	compile(template, name)

	return nil
}

func main() {
	cli.AppHelpTemplate = HELP_TEMPLATE

	app := cli.NewApp()
	app.Name = "thaum"
	app.Usage = "Generate micro-boilerplates"
	app.Action = onRun
	app.Version = "0.1.0"

	app.Run(os.Args)
}

package main

import (
	"os"
	"fmt"

	"github.com/urfave/cli"
)

// Called when thaum is actually run.
func onRun(c *cli.Context) error {
	template := c.Args().Get(0)
	name := c.Args().Get(1)

	if len(c.Args()) == 0 {
		cli.ShowAppHelp(c)
		return nil
	}

	if name == "" {
		ErrorLog(fmt.Sprintf("Thaum requires a name for your %q template. Example: \n\n $ thaum <template> <name> ", template))
		return nil
	}

	compile(template, name)

	return nil
}

func main() {
	cli.AppHelpTemplate = HELP_TEMPLATE

	app := cli.NewApp()
	app.Name = "thaum"
	app.Usage = "Generate micro-boilerplates"
	app.Action = onRun
	app.Version = "0.1.0"

	app.Run(os.Args)
}

Edit "name for template" error message to include example


package main

import (
	"fmt"
	"net/url"
)

func validateAndGetURLHost(urlSample string) (string, error) {

	parsed, err := url.ParseRequestURI(urlSample)

	if err != nil {
		fmt.Printf("Unable to parse URL '%s' to get the host\n", urlSample)
		return "", err
	}

	// return parsed.Scheme + "://" + parsed.Host
	return parsed.Host, nil
}

func printVersion() {

	fmt.Printf("%s\n", version)
}

package main

import (
	"fmt"
	"net/url"
	"strings"
)

func validateAndGetURLHost(urlSample string) (string, error) {

	// cheat a little by checking if we have :// in the string.
	// if we dont, its probably a hostname already
	if !strings.Contains("://", urlSample) {

		s := strings.TrimSpace(urlSample)
		return s, nil
	}

	// otherwise, if there is a ://, try and extract the hostname
	parsed, err := url.ParseRequestURI(urlSample)

	if err != nil {
		fmt.Printf("Unable to parse URL '%s' to get the host\n", urlSample)
		return "", err
	}

	// return parsed.Scheme + "://" + parsed.Host
	return parsed.Host, nil
}

func printVersion() {

	fmt.Printf("%s\n", version)
}

Allow hostnames to be submitted along with urls


package main

import (
	"github.com/sean-duffy/xlsx"
	"strconv"
)

func main() {

	c := []xlsx.Column{
		xlsx.Column{Name: "Col1", Width: 10},
		xlsx.Column{Name: "Col2", Width: 10},
	}

	sh := xlsx.NewSheetWithColumns(c)
	sh.Title = "MySheet"

	for i := 0; i < 10; i++ {

		r := sh.NewRow()

		r.Cells[0] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: strconv.Itoa(i + 1),
		}
		r.Cells[1] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: "1",
		}

		sh.AppendRow(r)
	}

	err := sh.SaveToFile("test.xlsx")
	_ = err
}

package main

import (
	"bufio"
	"github.com/sean-duffy/xlsx"
	"os"
	"strconv"
)

func main() {

	outputfile, err := os.Create("test.xlsx")

	w := bufio.NewWriter(outputfile)
	ww := xlsx.NewWorkbookWriter(w)

	c := []xlsx.Column{
		xlsx.Column{Name: "Col1", Width: 10},
		xlsx.Column{Name: "Col2", Width: 10},
	}

	sh := xlsx.NewSheetWithColumns(c)
	sh.Title = "MySheet"

	sw, err := ww.NewSheetWriter(&sh)

	for i := 0; i < 1000000; i++ {

		r := sh.NewRow()

		r.Cells[0] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: strconv.Itoa(i + 1),
		}
		r.Cells[1] = xlsx.Cell{
			Type:  xlsx.CellTypeNumber,
			Value: "1",
		}

		err = sw.WriteRows([]xlsx.Row{r})
	}

	err = ww.Close()
	defer w.Flush()

	if err != nil {
		panic(err)
	}
}

Change large example to use streaming


package formatters

import (
	"io"
	"os"
	"strconv"

	"github.com/mrtazz/checkmake/rules"
	"github.com/olekukonko/tablewriter"
)

// DefaultFormatter is the formatter used by default for CLI output
type DefaultFormatter struct {
	out io.Writer
}

// NewDefaultFormatter returns a DefaultFormatter struct
func NewDefaultFormatter() *DefaultFormatter {
	return &DefaultFormatter{out: os.Stdout}
}

// Format is the function to call to get the formatted output
func (f *DefaultFormatter) Format(violations rules.RuleViolationList) {

	data := make([][]string, len(violations))

	for idx, val := range violations {
		data[idx] = []string{val.Rule,
			val.Violation,
			strconv.Itoa(val.LineNumber)}
	}

	table := tablewriter.NewWriter(f.out)

	table.SetHeader([]string{"Rule", "Description", "Line Number"})

	table.SetCenterSeparator(" ")
	table.SetColumnSeparator(" ")
	table.SetRowSeparator(" ")
	table.SetAutoWrapText(true)

	table.AppendBulk(data)
	table.Render()
}

package formatters

import (
	"io"
	"os"
	"strconv"

	"github.com/mrtazz/checkmake/rules"
	"github.com/olekukonko/tablewriter"
)

// DefaultFormatter is the formatter used by default for CLI output
type DefaultFormatter struct {
	out io.Writer
}

// NewDefaultFormatter returns a DefaultFormatter struct
func NewDefaultFormatter() *DefaultFormatter {
	return &DefaultFormatter{out: os.Stdout}
}

// Format is the function to call to get the formatted output
func (f *DefaultFormatter) Format(violations rules.RuleViolationList) {
	data := make([][]string, len(violations))

	for idx, val := range violations {
		data[idx] = []string{val.Rule,
			val.Violation,
			strconv.Itoa(val.LineNumber)}
	}

	table := tablewriter.NewWriter(f.out)

	table.SetHeader([]string{"Rule", "Description", "Line Number"})

	table.SetCenterSeparator(" ")
	table.SetColumnSeparator(" ")
	table.SetRowSeparator(" ")
	table.SetBorder(false)
	table.SetAutoWrapText(true)

	table.AppendBulk(data)
	table.Render()
}

Disable borders to remove start/end newlines


package main

import (
	"github.com/henrylee2cn/pholcus/exec"
	_ "github.com/pholcus/spider_lib"     // 此为公开维护的spider规则库
	_ "github.com/pholcus/spider_lib_pte" // 同样你也可以自由添加自己的规则库
)

func main() {
	// 设置运行时默认操作界面，并开始运行
	// 运行软件前，可设置 -a_ui 参数为"web"、"gui"或"cmd"，指定本次运行的操作界面
	// 其中"gui"仅支持Windows系统
	exec.DefaultRun("web")
}

package main

import (
	"github.com/henrylee2cn/pholcus/exec"
	_ "github.com/pholcus/spider_lib" // 此为公开维护的spider规则库
	// _ "github.com/pholcus/spider_lib_pte" // 同样你也可以自由添加自己的规则库
)

func main() {
	// 设置运行时默认操作界面，并开始运行
	// 运行软件前，可设置 -a_ui 参数为"web"、"gui"或"cmd"，指定本次运行的操作界面
	// 其中"gui"仅支持Windows系统
	exec.DefaultRun("web")
}

Comment out the private library connection


// Submitted by Christopher Milan (christopherm99)

package main

import (
	"fmt"
	"math/rand"
	"time"
)

func shuffle(a []int) []int {
	rand.Seed(time.Now().UnixNano())
	for i := len(a) - 1; i > 0; i-- {
		j := rand.Intn(i + 1)
		a[i], a[j] = a[j], a[i]
	}
	return a
}

func is_sorted(a []int) bool {
	for i := 0; i < len(a)-1; i++ {
		if a[i+1] < a[i] {
			return false
		}
	}
	return true
}

func bogo_sort(a *[]int) {
	for !is_sorted(*a) {
		*a = shuffle(*a)
	}
}

func main() {
	a := []int{1, 3, 4, 2}
	bogo_sort(&a)
	fmt.Println(a)
}

// Submitted by Christopher Milan (christopherm99)

package main

import (
    "fmt"
    "math/rand"
    "time"
)

func shuffle(a *[]int) {
    for i := len(*a) - 1; i > 0; i-- {
        j := rand.Intn(i + 1)
        (*a)[i], (*a)[j] = (*a)[j], (*a)[i]
	}
}

func isSorted(a []int) bool {
    for i := 0; i < len(a)-1; i++ {
        if a[i+1] < a[i] {
            return false
        }
    }
    return true
}

func bogoSort(a *[]int) {
    for !isSorted(*a) {
        shuffle(a)
    }
}

func main() {
    rand.Seed(time.Now().UnixNano())
    a := []int{1, 3, 4, 2}
    bogoSort(&a)
    fmt.Println(a)
}

Resolve Liikt's PR review comments.


package api

type AuthScope int
type AuthScopes map[AuthScope]string

type ServiceMethod int
type EventKey string

type ObjectFactory func() interface{}

type HttpMethod string
type QueryDefault interface{}
type UrlQueries map[string]QueryDefault
type HttpHeaders map[string]string

var (
	GET       HttpMethod = HttpMethod("GET")
	POST      HttpMethod = HttpMethod("POST")
	PUT       HttpMethod = HttpMethod("PUT")
	DELETE    HttpMethod = HttpMethod("DELETE")
	MULTIPART HttpMethod = HttpMethod("POST")
)

type MethodSpec struct {
	Doc                  string
	UrlRoute             string
	HttpHeaders          HttpHeaders
	HttpMethod           HttpMethod
	UrlQueries           UrlQueries
	ContentTypes         []string
	RequestBody          ObjectFactory
	ResponseBody         ObjectFactory
	CallbackEvent        EventKey
	CallbackBodyTemplate string
	AuthScope            string
}

type ServiceMethods map[ServiceMethod]MethodSpec

package api

import (
	"net/http"
)

type AuthScope int
type AuthScopes map[AuthScope]string

type ServiceMethod int
type EventKey string

type ObjectFactory func(*http.Request) interface{}

type HttpMethod string
type QueryDefault interface{}
type UrlQueries map[string]QueryDefault
type HttpHeaders map[string]string

var (
	GET       HttpMethod = HttpMethod("GET")
	POST      HttpMethod = HttpMethod("POST")
	PUT       HttpMethod = HttpMethod("PUT")
	DELETE    HttpMethod = HttpMethod("DELETE")
	MULTIPART HttpMethod = HttpMethod("POST")
)

type MethodSpec struct {
	Doc                  string
	UrlRoute             string
	HttpHeaders          HttpHeaders
	HttpMethod           HttpMethod
	UrlQueries           UrlQueries
	ContentTypes         []string
	RequestBody          ObjectFactory
	ResponseBody         ObjectFactory
	CallbackEvent        EventKey
	CallbackBodyTemplate string
	AuthScope            string
}

type ServiceMethods map[ServiceMethod]MethodSpec

Change in API RequestBody/ ObjectFactory signature to allow different prototype objects based on http request (content-type)


package main

import (
	"bufio"
	"fmt"
	"log"
	"os"

	"github.com/griffithsh/sql-squish/database"
)

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

	var concatted string
	for scanner.Scan() {
		concatted = concatted + scanner.Text()
	}
	d, err := database.FromString(concatted)
	if err != nil {
		log.Fatal(err)
	}
	for _, t := range d.Tables {
		fmt.Println(t.String())
	}
	// files, err := db.AsSQL()
	// if err != nil {
	// 	log.Fatal(err)
	// }
	// for file := range files {
	// 	fmt.Print(file)
	// }
}

package main

import (
	"log"

	"github.com/griffithsh/sql-squish/database"
)

func main() {
	concatted, err := inputStdin()

	if err != nil {
		log.Fatal(err)
	}
	d, err := database.FromString(concatted)
	if err != nil {
		log.Fatal(err)
	}

	outputStdout(d)
}

Use input and output functions in sqlite-squish


package stun

import (
	"encoding/binary"

	"github.com/pkg/errors"
)

type ChannelData struct {
	ChannelNumber uint16
	Data          []byte
}

func NewChannelData(packet []byte) (*ChannelData, error) {
	cn, err := getChannelNumber(packet)
	if err != nil {
		return nil, err
	}

	return &ChannelData{
		ChannelNumber: cn,
		Data:          packet,
	}, nil
}

//  0b01: ChannelData message (since the channel number is the first
//  field in the ChannelData message and channel numbers fall in the
//  range 0x4000 - 0x7FFF).
func getChannelNumber(header []byte) (uint16, error) {
	cn := binary.BigEndian.Uint16(header)
	if cn < 0x4000 || cn > 0x7FFF {
		return 0, errors.Errorf("ChannelNumber is out of range: %d", cn)
	}
	return cn, nil
}

package stun

import (
	"encoding/binary"

	"github.com/pkg/errors"
)

type ChannelData struct {
	ChannelNumber uint16
	Length        uint16
	Data          []byte
}

func NewChannelData(packet []byte) (*ChannelData, error) {
	cn, err := getChannelNumber(packet)
	if err != nil {
		return nil, err
	}

	return &ChannelData{
		ChannelNumber: cn,
		Length:        getChannelLength(packet),
		Data:          packet[4:],
	}, nil
}

//  0b01: ChannelData message (since the channel number is the first
//  field in the ChannelData message and channel numbers fall in the
//  range 0x4000 - 0x7FFF).
func getChannelNumber(header []byte) (uint16, error) {
	cn := binary.BigEndian.Uint16(header)
	if cn < 0x4000 || cn > 0x7FFF {
		return 0, errors.Errorf("ChannelNumber is out of range: %d", cn)
	}
	return cn, nil
}

func getChannelLength(header []byte) uint16 {
	return binary.BigEndian.Uint16(header[2:])
}

Add ChannelData length to struct


package filu

import "time"

// An Event is an immutable fact that happened at a single moment in time.
type Event interface {
	HappenedAt() time.Time
}

// A Time is a single moment in time. It is used by Implementors
// of the Event interface to avoid reimplementation of the HappenedAt()
// method.
type Time struct {
	moment time.Time
}

func (e Time) HappenedAt() time.Time {
	return e.moment
}

package filu

import "time"

// An Event is an immutable fact that happened at a single moment in time.
type Event interface {
	HappenedAt() time.Time
}

// A Time is a single moment in time. It is used by Implementors
// of the Event interface to avoid reimplementation of the HappenedAt()
// method.
type Time struct {
	moment time.Time
}

func Now() Time {
	return Time{time.Now()}
}

func (e Time) HappenedAt() time.Time {
	return e.moment
}

Add function to produce time.Now() as filu.Time


package testhelpers

import(
	. "github.com/onsi/gomega"
	"bytes"
  "io"
	"os"
  "strings"
  "wall_street"
)

func SimulatePipes(reader *wall_street.ReadlineReader, input string, block func()) []string {
	in, out, err := os.Pipe()
	Expect(err).NotTo(HaveOccurred())
	reader.SetReadPipe(in)

	go func() {
		defer out.Close()
		out.Write([]byte(input))
	}()

	return CaptureSTDOUT(reader, func() { block() })
}

func CaptureSTDOUT(reader *wall_street.ReadlineReader, block func()) []string {
	in, out, err := os.Pipe()
	Expect(err).ToNot(HaveOccurred())

	reader.SetWritePipe(out)

	block()
	out.Close()

	var buf bytes.Buffer
	io.Copy(&buf, in)
	if len(buf.String()) == 0 {
		return []string{}
	}

	return strings.Split(buf.String(), "\n")
}

package testhelpers

import(
	. "github.com/onsi/gomega"
	"bytes"
  "io"
	"os"
  "strings"
  "wall_street"
)

func SimulatePipes(reader *wall_street.ReadlineReader, input string, block func()) []string {
	in, out, err := os.Pipe()
	Expect(err).NotTo(HaveOccurred())
	reader.SetReadPipe(in)

	go func() {
		defer out.Close()
		out.Write([]byte(input + "\n"))
	}()

	return CaptureSTDOUT(reader, func() { block() })
}

func CaptureSTDOUT(reader *wall_street.ReadlineReader, block func()) []string {
	in, out, err := os.Pipe()
	Expect(err).ToNot(HaveOccurred())

	reader.SetWritePipe(out)

	block()
	out.Close()

	var buf bytes.Buffer
	io.Copy(&buf, in)
	if len(buf.String()) == 0 {
		return []string{}
	}

	return strings.Split(buf.String(), "\n")
}

Add convenient newline to test helpers


// gogl provides a framework for representing and working with graphs.
package gogl

// Constants defining graph capabilities and behaviors.
const (
	E_DIRECTED, EM_DIRECTED = 1 << iota, 1<<iota - 1
	E_UNDIRECTED, EM_UNDIRECTED
	E_WEIGHTED, EM_WEIGHTED
	E_TYPED, EM_TYPED
	E_SIGNED, EM_SIGNED
	E_LOOPS, EM_LOOPS
	E_MULTIGRAPH, EM_MULTIGRAPH
)

type Vertex interface{}

type Edge struct {
	Tail, Head Vertex
}

type Graph interface {
	EachVertex(f func(vertex Vertex))
	EachEdge(f func(edge Edge))
	EachAdjacent(vertex Vertex, f func(adjacent Vertex))
	HasVertex(vertex Vertex) bool
	Order() uint
	Size() uint
	GetSubgraph([]Vertex) Graph
}

type MutableGraph interface {
	Graph
	AddVertex(v interface{}) bool
	RemoveVertex(v interface{}) bool
}

type DirectedGraph interface {
	Graph
	Transpose() DirectedGraph
	IsAcyclic() bool
	GetCycles() [][]interface{}
}

type MutableDirectedGraph interface {
	MutableGraph
	DirectedGraph
	addDirectedEdge(source interface{}, target interface{}) bool
	removeDirectedEdge(source interface{}, target interface{}) bool
}

// gogl provides a framework for representing and working with graphs.
package gogl

// Constants defining graph capabilities and behaviors.
const (
	E_DIRECTED, EM_DIRECTED = 1 << iota, 1<<iota - 1
	E_UNDIRECTED, EM_UNDIRECTED
	E_WEIGHTED, EM_WEIGHTED
	E_TYPED, EM_TYPED
	E_SIGNED, EM_SIGNED
	E_LOOPS, EM_LOOPS
	E_MULTIGRAPH, EM_MULTIGRAPH
)

type Vertex interface{}

type Edge struct {
	Tail, Head Vertex
}

type Graph interface {
	EachVertex(f func(vertex Vertex))
	EachEdge(f func(edge Edge))
	EachAdjacent(vertex Vertex, f func(adjacent Vertex))
	HasVertex(vertex Vertex) bool
	Order() uint
	Size() uint
	AddVertex(v interface{}) bool
	RemoveVertex(v interface{}) bool
}

type DirectedGraph interface {
	Graph
	Transpose() DirectedGraph
	IsAcyclic() bool
	GetCycles() [][]interface{}
	addDirectedEdge(source interface{}, target interface{}) bool
	removeDirectedEdge(source interface{}, target interface{}) bool
}

Fix interfaces so they actually work.


package jiffy

const (
	cancelTTL = iota
	extendTTL
)

var (
	registry *Registry
)

func GetTopic(name string) *Topic {
	return registry.GetTopic(name)
}

func init() {
	registry = CreateRegistry()
}

package jiffy

const (
	cancelTTL = iota
	extendTTL
)

var (
	registry *Registry
)

// Returns a topic from the global registry.
func GetTopic(name string) *Topic {
	return registry.GetTopic(name)
}

func init() {
	registry = CreateRegistry()
}

Comment for main exported fuctions


package operation

type Manifest struct {
	Applications []AppManifest `yaml:"applications"`
}

type AppManifest struct {
	Name                    string              `yaml:"name"`
	Buildpacks              []string            `yaml:"buildpacks,omitempty"`
	Command                 string              `yaml:"command,omitempty"`
	DiskQuota               string              `yaml:"disk_quota,omitempty"`
	Docker                  *AppManifestDocker  `yaml:"docker,omitempty"`
	Env                     map[string]string   `yaml:"env,omitempty"`
	HealthCheckType         string              `yaml:"health-check-type,omitempty"`
	HealthCheckHTTPEndpoint string              `yaml:"health-check-http-endpoint,omitempty"`
	Instances               int                 `yaml:"instances,omitempty"`
	LogRateLimit            string              `yaml:"log-rate-limit,omitempty"`
	Memory                  string              `yaml:"memory,omitempty"`
	NoRoute                 bool                `yaml:"no-route,omitempty"`
	Routes                  []AppManifestRoutes `yaml:"routes,omitempty"`
	Services                []string            `yaml:"services,omitempty"`
	Stack                   string              `yaml:"stack,omitempty"`
	Timeout                 int                 `yaml:"timeout,omitempty"`
}

type AppManifestDocker struct {
	Image    string `yaml:"image,omitempty"`
	Username string `yaml:"username,omitempty"`
}

type AppManifestRoutes struct {
	Route string `yaml:"route,omitempty"`
}

package operation

type Manifest struct {
	Applications []*AppManifest `yaml:"applications"`
}

type AppManifest struct {
	Name                    string              `yaml:"name"`
	Buildpacks              []string            `yaml:"buildpacks,omitempty"`
	Command                 string              `yaml:"command,omitempty"`
	DiskQuota               string              `yaml:"disk_quota,omitempty"`
	Docker                  *AppManifestDocker  `yaml:"docker,omitempty"`
	Env                     map[string]string   `yaml:"env,omitempty"`
	HealthCheckType         string              `yaml:"health-check-type,omitempty"`
	HealthCheckHTTPEndpoint string              `yaml:"health-check-http-endpoint,omitempty"`
	Instances               int                 `yaml:"instances,omitempty"`
	LogRateLimit            string              `yaml:"log-rate-limit,omitempty"`
	Memory                  string              `yaml:"memory,omitempty"`
	NoRoute                 bool                `yaml:"no-route,omitempty"`
	Routes                  []AppManifestRoutes `yaml:"routes,omitempty"`
	Services                []string            `yaml:"services,omitempty"`
	Stack                   string              `yaml:"stack,omitempty"`
	Timeout                 int                 `yaml:"timeout,omitempty"`
}

type AppManifestDocker struct {
	Image    string `yaml:"image,omitempty"`
	Username string `yaml:"username,omitempty"`
}

type AppManifestRoutes struct {
	Route string `yaml:"route,omitempty"`
}

Add pointer type ot apps array


// Copyright 2016 The LUCI Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

package cloud

import (
	"google.golang.org/cloud/datastore"

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

// Use installs the cloud services implementation into the supplied Context.
//
// This includes:
//	- github.com/luci/gae/service/info
//	- github.com/luci/gae/service/datastore
//
// This is built around the ability to use cloud datastore.
func Use(c context.Context, client *datastore.Client) context.Context {
	cds := cloudDatastore{
		client: client,
	}

	return cds.use(useInfo(c))
}

// Copyright 2016 The LUCI Authors. All rights reserved.
// Use of this source code is governed under the Apache License, Version 2.0
// that can be found in the LICENSE file.

package cloud

import (
	"google.golang.org/cloud/datastore"

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

// Use installs the cloud services implementation into the supplied Context.
//
// This includes:
//	- github.com/luci/gae/service/info
//	- github.com/luci/gae/service/datastore
//
// This is built around the ability to use cloud datastore.
func Use(c context.Context, client *datastore.Client) context.Context {
	return UseDS(useInfo(c), client)
}

// UseDS installs the cloud datastore implementation into the supplied Context.
func UseDS(c context.Context, client *datastore.Client) context.Context {
	cds := cloudDatastore{
		client: client,
	}
	return cds.use(c)
}

Add an option to install just Cloud Datastore.


package scanner

import (
	"github.com/Symantec/Dominator/lib/filesystem/scanner"
	"github.com/Symantec/Dominator/lib/objectcache"
)

func scanFileSystem(rootDirectoryName string, cacheDirectoryName string,
	configuration *Configuration, oldFS *FileSystem) (*FileSystem, error) {
	var fileSystem FileSystem
	fileSystem.configuration = configuration
	fileSystem.rootDirectoryName = rootDirectoryName
	fileSystem.cacheDirectoryName = cacheDirectoryName
	fs, err := scanner.ScanFileSystem(rootDirectoryName,
		configuration.FsScanContext, configuration.ScanFilter,
		checkScanDisableRequest, nil, &oldFS.FileSystem)
	if err != nil {
		return nil, err
	}
	fileSystem.FileSystem = *fs
	if err = fileSystem.scanObjectCache(); err != nil {
		return nil, err
	}
	return &fileSystem, nil
}

func (fs *FileSystem) scanObjectCache() error {
	if fs.cacheDirectoryName == "" {
		return nil
	}
	var err error
	fs.ObjectCache, err = objectcache.ScanObjectCache(fs.cacheDirectoryName)
	return err
}

package scanner

import (
	"github.com/Symantec/Dominator/lib/filesystem/scanner"
	"github.com/Symantec/Dominator/lib/objectcache"
)

func scanFileSystem(rootDirectoryName string, cacheDirectoryName string,
	configuration *Configuration, oldFS *FileSystem) (*FileSystem, error) {
	var fileSystem FileSystem
	fileSystem.configuration = configuration
	fileSystem.rootDirectoryName = rootDirectoryName
	fileSystem.cacheDirectoryName = cacheDirectoryName
	fs, err := scanner.ScanFileSystem(rootDirectoryName,
		configuration.FsScanContext, configuration.ScanFilter,
		checkScanDisableRequest, scanner.GetSimpleHasher(true),
		&oldFS.FileSystem)
	if err != nil {
		return nil, err
	}
	fileSystem.FileSystem = *fs
	if err = fileSystem.scanObjectCache(); err != nil {
		return nil, err
	}
	return &fileSystem, nil
}

func (fs *FileSystem) scanObjectCache() error {
	if fs.cacheDirectoryName == "" {
		return nil
	}
	var err error
	fs.ObjectCache, err = objectcache.ScanObjectCache(fs.cacheDirectoryName)
	return err
}

Improve handling of scanning of shrinking files in subd: return zero hash.


package golog

var Global *LevelLogger = &LevelLogger{
	&loggerImpl{&defaultLogOuters, flag_minloglevel},
}

func Info(vals ...interface{}) {
	Global.Info(vals...)
}

func Infof(f string, args ...interface{}) {
	Global.Infof(f, args...)
}

func Infoc(closure func() string) {
	Global.Warningc(closure)
}

func Warning(vals ...interface{}) {
	Global.Warning(vals...)
}

func Warningf(f string, args ...interface{}) {
	Global.Warningf(f, args...)
}

func Warningc(closure func() string) {
	Global.Errorc(closure)
}

func Error(vals ...interface{}) {
	Global.Error(vals...)
}

func Errorf(f string, args ...interface{}) {
	Global.Errorf(f, args...)
}

func Errorc(closure func() string) {
	Global.Errorc(closure)
}

func Fatal(vals ...interface{}) {
	Global.Fatal(vals...)
}

func Fatalf(f string, args ...interface{}) {
	Global.Fatalf(f, args...)
}

func Fatalc(closure func() string) {
	Global.Fatalc(closure)
}

func StartTestLogging(t TestController) {
	defaultLogOuters.AddLogOuter("testing", NewTestLogOuter(t))
}

func StopTestLogging() {
	defaultLogOuters.RemoveLogOuter("testing")
}

Add capability to start test logging


package webrtc

// RTCIceTransport allows an application access to information about the ICE
// transport over which packets are sent and received.
type RTCIceTransport struct {
}

package webrtc

// RTCIceTransport allows an application access to information about the ICE
// transport over which packets are sent and received.
type RTCIceTransport struct {
	// Role RTCIceRole
	// Component RTCIceComponent
	// State RTCIceTransportState
	// gatheringState RTCIceGathererState
}

// func (t *RTCIceTransport) GetLocalCandidates() []RTCIceCandidate {
//
// }
//
// func (t *RTCIceTransport) GetRemoteCandidates() []RTCIceCandidate {
//
// }
//
// func (t *RTCIceTransport) GetSelectedCandidatePair() RTCIceCandidatePair {
//
// }
//
// func (t *RTCIceTransport) GetLocalParameters() RTCIceParameters {
//
// }
//
// func (t *RTCIceTransport) GetRemoteParameters() RTCIceParameters {
//
// }

Add RTCIceTransport commented out public API


package imagestore

import (
	"errors"
	"io"
	"io/ioutil"
	"strings"
)

type InMemoryImageStore struct {
	files map[string]string // name -> contents
}

func NewInMemoryImageStore() *InMemoryImageStore {
	return &InMemoryImageStore{
		files: make(map[string]string),
	}
}

func (this *InMemoryImageStore) Exists(obj *StoreObject) (bool, error) {
	_, ok := this.files[obj.Name]

	return ok, nil
}

func (this *InMemoryImageStore) Save(src io.Reader, obj *StoreObject) (*StoreObject, error) {
	data, err := ioutil.ReadAll(src)
	if err != nil {
		return nil, err
	}

	this.files[obj.Name] = string(data)

	return obj, nil
}

func (this *InMemoryImageStore) Get(obj *StoreObject) (io.Reader, error) {
	data, ok := this.files[obj.Name]

	if !ok {
		return nil, errors.New("File doesn't exist")
	}

	return strings.NewReader(data), nil
}

package imagestore

import (
	"errors"
	"io"
	"io/ioutil"
	"strings"
	"sync"
)

type InMemoryImageStore struct {
	files map[string]string // name -> contents
	rw    sync.Mutex
}

func NewInMemoryImageStore() *InMemoryImageStore {
	return &InMemoryImageStore{
		files: make(map[string]string),
		rw:    sync.Mutex{},
	}
}

func (this *InMemoryImageStore) Exists(obj *StoreObject) (bool, error) {
	this.rw.Lock()

	_, ok := this.files[obj.Name]

	this.rw.Unlock()

	return ok, nil
}

func (this *InMemoryImageStore) Save(src io.Reader, obj *StoreObject) (*StoreObject, error) {
	data, err := ioutil.ReadAll(src)
	if err != nil {
		return nil, err
	}

	this.rw.Lock()
	this.files[obj.Name] = string(data)
	this.rw.Unlock()

	return obj, nil
}

func (this *InMemoryImageStore) Get(obj *StoreObject) (io.Reader, error) {
	this.rw.Lock()
	data, ok := this.files[obj.Name]
	this.rw.Unlock()

	if !ok {
		return nil, errors.New("File doesn't exist")
	}

	return strings.NewReader(data), nil
}

Fix race with in-memory store


package utils

import (
	"github.com/gorilla/websocket"
)

type WebSocketManager interface {
	Register(ws *websocket.Conn)

	Write(msg []byte) (n int, e error)
}

type wsManager struct {
	sockets []websocket.Conn
}

func CreateWSManager() WebSocketManager {
	return &wsManager{sockets: make([]websocket.Conn, 0)}
}

func (ws *wsManager) Register(conn *websocket.Conn) {
	ws.sockets = append(ws.sockets, *conn)
}

func (ws *wsManager) Write(msg []byte) (n int, e error) {
	invalid := make([]int, 0)
	for k, v := range ws.sockets {
		err := v.WriteMessage(websocket.TextMessage, msg)
		if err != nil {
			invalid = append(invalid, k)
		}
	}
	if len(invalid) > 0 {
		for b := range invalid {
			ws.sockets = append(ws.sockets[:b], ws.sockets[b+1:]...)
		}
	}
	n = len(msg)
	return
}

package utils

import (
	"github.com/gorilla/websocket"
)

type WebSocketManager interface {
	Register(ws *websocket.Conn)

	Write(msg []byte) (n int, e error)
}

type wsManager struct {
	sockets []websocket.Conn
}

func CreateWSManager() WebSocketManager {
	return &wsManager{sockets: make([]websocket.Conn, 0)}
}

func (ws *wsManager) Register(conn *websocket.Conn) {
	ws.sockets = append(ws.sockets, *conn)
}

func (ws *wsManager) Write(msg []byte) (n int, e error) {
	invalid := make([]int, 0)
	for k, v := range ws.sockets {
		err := v.WriteMessage(websocket.TextMessage, msg)
		if err != nil {
			invalid = append(invalid, k)
		}
	}
	if len(invalid) > 0 {
		for b := range invalid {
			if len(ws.sockets) == 1 {
				ws.sockets = make([]websocket.Conn, 0)
			} else {
				ws.sockets = append(ws.sockets[:b], ws.sockets[b+1:]...)
			}
		}
	}
	n = len(msg)
	return
}

Fix bug when only one websocket was connected


package main

import (
	"bsearch/index"
	"bsearch/ops"
	"fmt"
	"os"
	"flag"
)

func usage() {
	fmt.Fprintf(os.Stderr, "usage: bsearch <path to index blob>\n")
	flag.PrintDefaults()
	os.Exit(1)
}

func main() {
	flag.Parse()
	if flag.NArg() != 1 {
		usage()
	}
	dbname := flag.Arg(0)
	in, err := index.Open(dbname)
	if err != nil {
		fmt.Fprintf(os.Stderr, "bindex.Open: %v\n", err)
		return
	}
	defer in.Close()

	a1 := ops.NewAttr(in, "root:10")
	a2 := ops.NewAttr(in, "magic:boll")
	a3 := ops.NewAttr(in, "status:active")
	q := ops.NewIntersection(ops.NewUnion(a1, a2), a3)
	q.Add(a3)
	var d *index.IbDoc
	for true {
		d = q.NextDoc(d)
		if d == nil {
			break
		}
		fmt.Printf("%v\n", string(in.Docs[d.Id]))
		d = d.Inc()
	}
}

package main

import (
	"bsearch/index"
	"bsearch/ops"
	"fmt"
	"os"
	"flag"
)

func usage() {
	fmt.Fprintf(os.Stderr, "usage: bsearch <path to index blob>\n")
	flag.PrintDefaults()
	os.Exit(1)
}

func main() {
	flag.Parse()
	if flag.NArg() != 1 {
		usage()
	}
	dbname := flag.Arg(0)
	in, err := index.Open(dbname)
	if err != nil {
		fmt.Fprintf(os.Stderr, "bindex.Open: %v\n", err)
		return
	}
	defer in.Close()

	a1 := ops.NewAttr(in, "root:10")
	a2 := ops.NewAttr(in, "magic:boll")
	a3 := ops.NewAttr(in, "status:active")
	q := ops.NewIntersection(ops.NewUnion(a1, a2), a3)
	q.Add(a3)

	fmt.Printf("%v\n", in.Header())

	var d *index.IbDoc
	for true {
		d = q.NextDoc(d)
		if d == nil {
			break
		}
		fmt.Printf("%v\n", string(in.Docs[d.Id]))
		d = d.Inc()
	}
}

Print the header at the right place.


package enemy

import (
	"board"
	"color"
)

type Enemy struct {
	board.Board
	color.Color
	first [8][8]bool
}

func NewEnemy(b board.Board, c color.Color, first [8][8]bool) *Enemy {
	enemy := new(Enemy)
	enemy.Board = b
	enemy.Color = c
	enemy.first = first
	return enemy
}

package enemy

import (
	"board"
	"color"
	"matrix"
)

type Enemy struct {
	matrix.Matrix
	color.Color
	first [8][8]bool
}

func NewEnemy(b *board.Board, c color.Color) *Enemy {
	enemy := new(Enemy)
	enemy.Matrix = b.Matrix
	enemy.Color = c
	for i := 0; i < matrix.SIDE; i++ {
		for j := 0; j < matrix.SIDE; j++ {
			enemy.first[i][j] = b.IsFirst(matrix.Point{i, j})
		}
	}
	return enemy
}

Change Enemy's members and how to get them


// Package trinary implements a function for converting a trinary number to a decimal number.
package trinary

import (
	"fmt"
	"math"
	"strconv"
)

const testVersion = 1

// ParseTrinary converts a trinary number to a decimal number.
// If the input contains invalid characters or overflows int64 an error is returned.
func ParseTrinary(input string) (result int64, err error) {
	for i, digit := range input {
		switch digit {
		case '0', '1', '2':
			digitValue, _ := strconv.Atoi(string(digit))
			value := int64(digitValue) * pow(3, len(input)-1-i)
			if value > math.MaxInt64-result {
				return 0, fmt.Errorf("Cannot parse trinary. Input overflows int64")
			}
			result += value
		default:
			return 0, fmt.Errorf("Cannot parse trinary. Input contains invalid character %q", digit)
		}
	}

	return result, nil
}

func pow(base, exponent int) int64 {
	result := int64(1)
	for i := 0; i < exponent; i++ {
		result *= int64(base)
	}

	return result
}

// Package trinary implements a function for converting a trinary number to a decimal number.
package trinary

import "fmt"

const testVersion = 1

// ParseTrinary converts a trinary number to a decimal number.
// If the input contains invalid characters or overflows int64 an error is returned.
func ParseTrinary(input string) (result int64, err error) {
	for _, digit := range input {
		if digit < '0' || digit > '2' {
			return 0, fmt.Errorf("Cannot parse trinary. Input contains invalid character %q", digit)
		}

		digitValue := digit - '0'
		result = result*3 + int64(digitValue)

		if result < 0 {
			return 0, fmt.Errorf("Cannot parse trinary. Input overflows int64")
		}
	}

	return result, nil
}

Add solutions for go problems


// Copyright 2015-2016, Cyrill @ Schumacher.fm and the CoreStore 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 net provides additional network helper functions and in subpackages
// middleware.
//
// Which http router should I use? CoreStore doesn't care because it uses the
// standard library http API. You can choose nearly any router you like.
//
// TODO(CyS) consider the next items:
// - context Package: https://twitter.com/peterbourgon/status/752022730812317696
// - Sessions: https://github.com/alexedwards/scs
// - Form decoding https://github.com/monoculum/formam
package net

// Copyright 2015-2016, Cyrill @ Schumacher.fm and the CoreStore 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 net provides additional network helper functions and in subpackages
// middleware.
//
// Which http router should I use? CoreStore doesn't care because it uses the
// standard library http API. You can choose nearly any router you like.
//
// TODO(CyS) consider the next items:
// - context Package: https://twitter.com/peterbourgon/status/752022730812317696
// - Sessions: https://github.com/alexedwards/scs
// - Form decoding https://github.com/monoculum/formam
// - Kerberos github.com/jcmturner/gokrb5
package net

Add todo to implement kerberos


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

package main

import (
	"flag"
	"fmt"
	"github.com/pblcache/pblcache/src/cache"
)

func main() {
	fmt.Print("Hello\n")

	flag.Parse()
	c := cache.NewIoCacheKvDB(102400, 1024, true /* writethrough */, 1024)
	c.Close()

	fmt.Print("Goodbye\n")
}

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

package main

import (
	"flag"
	"fmt"
	"github.com/pblcache/pblcache/src/cache"
)

func main() {
	fmt.Print("Hello\n")

	/*
		flag.Parse()
		c := cache.NewIoCacheKvDB(102400, 1024, true , 1024)
		c.Close()
	*/

	fmt.Print("Goodbye\n")
}

Remove call to cache while we work on it


package apps

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/vito/cmdtest/matchers"

	. "github.com/pivotal-cf-experimental/cf-acceptance-tests/helpers"
)

var _ = Describe("An application being staged", func() {
	BeforeEach(func() {
		AppName = RandomName()
	})

	AfterEach(func() {
		Expect(Cf("delete", AppName, "-f")).To(Say("OK"))
	})

	It("has its staging log streamed during a push", func() {
		push := Cf("push", AppName, "-p", doraPath)

		Expect(push).To(Say("Installing dependencies"))
		Expect(push).To(Say("Uploading droplet"))
		Expect(push).To(Say("App started"))
	})
})

package apps

import (
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	. "github.com/vito/cmdtest/matchers"

	. "github.com/pivotal-cf-experimental/cf-acceptance-tests/helpers"
)

var _ = Describe("An application being staged", func() {
	BeforeEach(func() {
		AppName = RandomName()
	})

	AfterEach(func() {
		Expect(Cf("delete", AppName, "-f")).To(Say("OK"))
	})

	It("has its staging log streamed during a push", func() {
		push := Cf("push", AppName, "-p", doraPath)

		// Expect(push).To(Say("Installing dependencies"))
		Expect(push).To(Say("Uploading droplet"))
		Expect(push).To(Say("App started"))
	})
})

Disable check that fails due to known race condition


package wsmaterials

import (
	"fmt"
	"github.com/emicklei/go-restful"
	"net/http"
)

type JsonpResponseWriter struct {
	writer   http.ResponseWriter
	callback string
}

func (j *JsonpResponseWriter) Header() http.Header {
	return j.writer.Header()
}

func (j *JsonpResponseWriter) WriteHeader(status int) {
	j.writer.WriteHeader(status)
}

func (j *JsonpResponseWriter) Write(bytes []byte) (int, error) {
	if j.callback != "" {
		bytes = []byte(fmt.Sprintf("%s(%s)", j.callback, bytes))
	}
	return j.writer.Write(bytes)
}

func NewJsonpResponseWriter(httpWriter http.ResponseWriter, callback string) *JsonpResponseWriter {
	jsonpResponseWriter := new(JsonpResponseWriter)
	jsonpResponseWriter.writer = httpWriter
	jsonpResponseWriter.callback = callback
	return jsonpResponseWriter
}

func JsonpFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	callback := req.Request.FormValue("callback")
	jsonpResponseWriter := NewJsonpResponseWriter(resp.ResponseWriter, callback)
	resp.ResponseWriter = jsonpResponseWriter
	chain.ProcessFilter(req, resp)
}

package wsmaterials

import (
	"fmt"
	"github.com/emicklei/go-restful"
	"net/http"
)

type jsonpResponseWriter struct {
	writer   http.ResponseWriter
	callback string
}

func (j *jsonpResponseWriter) Header() http.Header {
	return j.writer.Header()
}

func (j *jsonpResponseWriter) WriteHeader(status int) {
	j.writer.WriteHeader(status)
}

func (j *jsonpResponseWriter) Write(bytes []byte) (int, error) {
	if j.callback != "" {
		bytes = []byte(fmt.Sprintf("%s(%s)", j.callback, bytes))
	}
	return j.writer.Write(bytes)
}

func newJsonpResponseWriter(httpWriter http.ResponseWriter, callback string) *jsonpResponseWriter {
	jsonpResponseWriter := new(jsonpResponseWriter)
	jsonpResponseWriter.writer = httpWriter
	jsonpResponseWriter.callback = callback
	return jsonpResponseWriter
}

func JsonpFilter(req *restful.Request, resp *restful.Response, chain *restful.FilterChain) {
	callback := req.Request.FormValue("callback")
	jsonpResponseWriter := newJsonpResponseWriter(resp.ResponseWriter, callback)
	resp.ResponseWriter = jsonpResponseWriter
	chain.ProcessFilter(req, resp)
}

Remove some definitions and methods from the public space (lowercase their name)


package main

import (
	"log"
	"net/http"
)

func main() {
	router := NewRouter()
	err := http.ListenAndServe(":8080", router)
	if err != nil {
		log.Fatal("ListenAndServe Error: ", err)
	}
}

package main

import (
	"log"
	"net/http"
)

func main() {
	router := NewRouter()
	err := http.ListenAndServe(":" + os.Getenv("PORT"), router)
	if err != nil {
		log.Fatal("ListenAndServe Error: ", err)
	}
}

Make http port into env var


package types

const (
	ZigbeeCertificationType string = "zigbee"
	MatterCertificationType string = "matter"
	FullCertificationType   string = "Full"
	CbSCertificationType    string = "CbS" // CbS - Certification by Similarity
	CTPCertificationType    string = "CTP" // CTP - Certification Transfer Program
	PFCCertificationType    string = "PFC" // PFC - Product Family Certification
)

//	List of Certification Types
type CertificationTypes []string

var CertificationTypesList = CertificationTypes{
	ZigbeeCertificationType, MatterCertificationType, FullCertificationType,
	CbSCertificationType, CTPCertificationType, PFCCertificationType,
}

func IsValidCertificationType(certificationType string) bool {
	for _, i := range CertificationTypesList {
		if i == certificationType {
			return true
		}
	}

	return false
}

const (
	CodeProvisional uint32 = 1
	CodeCertified   uint32 = 2
	CodeRevoked     uint32 = 3
)

package types

const (
	ZigbeeCertificationType string = "zigbee"
	MatterCertificationType string = "matter"
)

//	List of Certification Types
type CertificationTypes []string

var CertificationTypesList = CertificationTypes{ZigbeeCertificationType, MatterCertificationType}

func IsValidCertificationType(certificationType string) bool {
	for _, i := range CertificationTypesList {
		if i == certificationType {
			return true
		}
	}

	return false
}

const (
	CodeProvisional uint32 = 1
	CodeCertified   uint32 = 2
	CodeRevoked     uint32 = 3
)

Remove incorrect CertificationType default values


/*
Copyright 2014 GoPivotal (UK) Limited.

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 gerror_test

import (
	"github.com/cf-guardian/guardian/gerror"
	"os"
)

type ErrorId int

const (
	ErrExample ErrorId = iota
	ErrInvalidPort
	ErrInvalidPath
)

func ExampleNew() error {
	return gerror.New(ErrExample, "Example error message")
}

func ExampleNewf(portNum int) error {
	return gerror.Newf(ErrInvalidPort, "Invalid port: %d", portNum)
}

func ExampleNewFromError(filePath string) (file *os.File, err error) {
	file, err = os.Open(filePath)
	if err != nil {
		return file, gerror.NewFromError(ErrInvalidPath, err)
	}
	return file, nil
}

/*
Copyright 2014 GoPivotal (UK) Limited.

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 gerror_test

import (
	"github.com/cf-guardian/guardian/gerror"
	"os"
)

func ExampleNew() error {
	return gerror.New(ErrExample, "Example error message")
}

func ExampleNewf(portNum int) error {
	return gerror.Newf(ErrInvalidPort, "Invalid port: %d", portNum)
}

func ExampleNewFromError(filePath string) (file *os.File, err error) {
	file, err = os.Open(filePath)
	if err != nil {
		return file, gerror.NewFromError(ErrInvalidPath, err)
	}
	return file, nil
}

Remove duplicate declarations from examples


package http

var (
	debugMode = false
)

func setDebug(debug bool) {
	debugMode = debug
}

type Error struct {
	Error      string `json:"error,omitempty"`
	StatusCode int    `json:"statusCode,omitempty"`
	HttpCode   int    `json:"httpCode,omitempty"`
}

func NewError(err error, statusCode, httpCode int) *Error {
	return &Error{err.Error(), statusCode, httpCode}
}

package http

var (
	debugMode = false
)

func SetDebug(debug bool) {
	debugMode = debug
}

type Error struct {
	Error      string `json:"error,omitempty"`
	StatusCode int    `json:"statusCode,omitempty"`
	HttpCode   int    `json:"httpCode,omitempty"`
}

func NewError(err error, statusCode, httpCode int) *Error {
	return &Error{err.Error(), statusCode, httpCode}
}

Put the SetDebug function on public


package libcontainer

type Factory interface {
	// Creates a new container in the given path. A unique ID is generated for the container and
	// starts the initial process inside the container.
	//
	// Returns the new container with a running process.
	//
	// Errors:
	// Path already exists
	// Config or initialConfig is invalid
	// System error
	//
	// On error, any partially created container parts are cleaned up (the operation is atomic).
	Create(id string, config *Config) (Container, error)

	// Load takes an ID for an existing container and reconstructs the container
	// from the state.
	//
	// Errors:
	// Path does not exist
	// Container is stopped
	// System error
	Load(id string) (Container, error)
}

package libcontainer

type Factory interface {

	// Creates a new container with the given id and starts the initial process inside it.
	// id must be a string containing only letters, digits and underscores and must contain
	// between 1 and 1024 characters, inclusive.
	//
	// The id must not already be in use by an existing container. Containers created using
	// a factory with the same path (and file system) must have distinct ids.
	//
	// Returns the new container with a running process.
	//
	// Errors:
	// id is already in use by a container
	// id has incorrect format
	// config is invalid
	// System error
	//
	// On error, any partially created container parts are cleaned up (the operation is atomic).
	Create(id string, config *Config) (Container, error)

	// Load takes an ID for an existing container and reconstructs the container
	// from the state.
	//
	// Errors:
	// Path does not exist
	// Container is stopped
	// System error
	Load(id string) (Container, error)
}

Remove erroneous reference to `path` in description and error list; add format description for `id` string; add "invalid format" error for `id` string; remove initial capitals on references to parameter names; remove reference to `initialConfig`; add description of id checking.


package missinggo

import "reflect"

func Max(_less interface{}, vals ...interface{}) interface{} {
	ret := reflect.ValueOf(vals[0])
	less := reflect.ValueOf(_less)
	for _, _v := range vals[1:] {
		v := reflect.ValueOf(_v)
		out := less.Call([]reflect.Value{ret, v})
		if out[0].Bool() {
			ret = v
		}
	}
	return ret.Interface()
}

func MinInt(first interface{}, rest ...interface{}) int64 {
	ret := reflect.ValueOf(first).Int()
	for _, _i := range rest {
		i := reflect.ValueOf(_i).Int()
		if i < ret {
			ret = i
		}
	}
	return ret
}

package missinggo

import "reflect"

func Max(_less interface{}, vals ...interface{}) interface{} {
	ret := reflect.ValueOf(vals[0])
	retType := ret.Type()
	less := reflect.ValueOf(_less)
	for _, _v := range vals[1:] {
		v := reflect.ValueOf(_v).Convert(retType)
		out := less.Call([]reflect.Value{ret, v})
		if out[0].Bool() {
			ret = v
		}
	}
	return ret.Interface()
}

func MaxInt(first int64, rest ...interface{}) int64 {
	return Max(func(l, r interface{}) bool {
		return l.(int64) < r.(int64)
	}, append([]interface{}{first}, rest...)...).(int64)
}

func MinInt(first interface{}, rest ...interface{}) int64 {
	ret := reflect.ValueOf(first).Int()
	for _, _i := range rest {
		i := reflect.ValueOf(_i).Int()
		if i < ret {
			ret = i
		}
	}
	return ret
}

Add MaxInt, and ensure the return type of Max matches the type of the first value


package web

import (
	"html/template"
	"net/http"

	"code.cloudfoundry.org/lager"
)

type templateData struct{}

type handler struct {
	logger   lager.Logger
	template *template.Template
}

func NewHandler(logger lager.Logger) (http.Handler, error) {
	tfuncs := &templateFuncs{
		assetIDs: map[string]string{},
	}

	funcs := template.FuncMap{
		"asset": tfuncs.asset,
	}

	src, err := Asset("index.html")
	if err != nil {
		return nil, err
	}

	t, err := template.New("index").Funcs(funcs).Parse(string(src))
	if err != nil {
		return nil, err
	}

	return &handler{
		logger:   logger,
		template: t,
	}, nil
}

func (h *handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	log := h.logger.Session("index")

	err := h.template.Execute(w, templateData{})
	if err != nil {
		log.Fatal("failed-to-build-template", err, lager.Data{})
		w.WriteHeader(http.StatusInternalServerError)
	}
}

Add X- headers for security


package main

import (
	"bytes"
)

// Stack is a stack of matrices
type Stack struct {
	stack []*Matrix
}

// NewStack returns a new stack
func NewStack() *Stack {
	return &Stack{
		stack: make([]*Matrix, 0, 100),
	}
}

// Pop returns and removes the top matrix in the stack
func (s *Stack) Pop() *Matrix {
	if s.IsEmpty() {
		return nil
	}
	length := len(s.stack)
	ret := s.stack[length-1]
	s.stack = s.stack[:length-1]
	return ret
}

// Push pushes a new matrix onto the stack
func (s *Stack) Push(m *Matrix) {
	s.stack = append(s.stack, m)
}

// Peek returns the top matrix in the stack
func (s *Stack) Peek() *Matrix {
	if s.IsEmpty() {
		return nil
	}
	length := len(s.stack)
	return s.stack[length-1]
}

// IsEmpty returns true if the stack is empty, false otherwise
func (s *Stack) IsEmpty() bool {
	return len(s.stack) == 0
}

func (s *Stack) String() string {
	var buffer bytes.Buffer
	length := len(s.stack)
	for i := length - 1; i >= 0; i-- {
		buffer.WriteString(s.stack[i].String())
	}
	return buffer.String()
}

package main

import (
	"bytes"
)

// Stack is a stack of matrices
type Stack struct {
	stack []*Matrix
}

// NewStack returns a new stack
func NewStack() *Stack {
	return &Stack{
		stack: make([]*Matrix, 0, 10),
	}
}

// Pop returns and removes the top matrix in the stack
func (s *Stack) Pop() *Matrix {
	if s.IsEmpty() {
		return nil
	}
	length := len(s.stack)
	ret := s.stack[length-1]
	s.stack = s.stack[:length-1]
	return ret
}

// Push pushes a new matrix onto the stack
func (s *Stack) Push(m *Matrix) {
	s.stack = append(s.stack, m)
}

// Peek returns the top matrix in the stack
func (s *Stack) Peek() *Matrix {
	if s.IsEmpty() {
		return nil
	}
	length := len(s.stack)
	return s.stack[length-1]
}

// IsEmpty returns true if the stack is empty, false otherwise
func (s *Stack) IsEmpty() bool {
	return len(s.stack) == 0
}

func (s *Stack) String() string {
	var buffer bytes.Buffer
	length := len(s.stack)
	for i := length - 1; i >= 0; i-- {
		buffer.WriteString(s.stack[i].String())
	}
	return buffer.String()
}

Reduce initial size of Stack