Add a mutex to guard access to the ticks map.

The need to do this became apparent once compiling with go 1.6 which
it now does more aggressive race condition checks.

Signed-off-by: Jon Seymour <44f878afe53efc66b76772bd845eb65944ed8232@wildducktheories.com>

--- logger/stats.go
+++ logger/stats.go
@@ -4,6 +4,7 @@
 	"fmt"
 	"sort"
 	"time"
+	"sync"
 )

 var tickLog = GetLogger("stats")
@@ -12,6 +13,7 @@
 var ReportInterval = time.Second * 5

 var ticks = make(map[string]int)
+var mu = sync.Mutex{}

 func init() {
 	go func() {
@@ -24,18 +26,22 @@

 			ticks2 := make(map[string]int)

+			mu.Lock()
 			keys := make([]string, 0, len(ticks))
 			for key := range ticks {
 				keys = append(keys, key)
 			}
+			mu.Unlock()
 			sort.Strings(keys)

 			var msg string
+			mu.Lock()
 			for _, name := range keys {
 				ticks2[name] = 0
 				count := ticks[name]
 				msg += fmt.Sprintf("[%s: %.f/sec] ", name, float64(count)/(float64(ReportInterval)/float64(time.Second)))
 			}
+			mu.Unlock()

 			ticks = ticks2

@@ -50,6 +56,9 @@
 }

 func TickN(name string, number int) {
+	mu.Lock()
+	defer mu.Unlock()
+
 	if _, ok := ticks[name]; !ok {
 		ticks[name] = 0
 	}

<|original_code|>
package logger

import (
	"fmt"
	"sort"
	"time"
)

var tickLog = GetLogger("stats")

// The interval between logging the number of actions/sec
var ReportInterval = time.Second * 5

var ticks = make(map[string]int)

func init() {
	go func() {
		for {
			time.Sleep(ReportInterval)

			if len(ticks) == 0 {
				continue
			}

			ticks2 := make(map[string]int)

			keys := make([]string, 0, len(ticks))
			for key := range ticks {
				keys = append(keys, key)
			}
			sort.Strings(keys)

			var msg string
			for _, name := range keys {
				ticks2[name] = 0
				count := ticks[name]
				msg += fmt.Sprintf("[%s: %.f/sec] ", name, float64(count)/(float64(ReportInterval)/float64(time.Second)))
			}

			ticks = ticks2

			tickLog.Infof(msg)
		}

	}()
}

func Tick(name string) {
	TickN(name, 1)
}

func TickN(name string, number int) {
	if _, ok := ticks[name]; !ok {
		ticks[name] = 0
	}
	ticks[name] += number
}

<|edits_diff|>
--- logger/stats.go
+++ logger/stats.go
@@ -4,6 +4,7 @@
 	"fmt"
 	"sort"
 	"time"
+	"sync"
 )

 var tickLog = GetLogger("stats")
@@ -12,6 +13,7 @@
 var ReportInterval = time.Second * 5

 var ticks = make(map[string]int)
+var mu = sync.Mutex{}

 func init() {
 	go func() {
@@ -24,18 +26,22 @@

 			ticks2 := make(map[string]int)

+			mu.Lock()
 			keys := make([]string, 0, len(ticks))
 			for key := range ticks {
 				keys = append(keys, key)
 			}
+			mu.Unlock()
 			sort.Strings(keys)

 			var msg string
+			mu.Lock()
 			for _, name := range keys {
 				ticks2[name] = 0
 				count := ticks[name]
 				msg += fmt.Sprintf("[%s: %.f/sec] ", name, float64(count)/(float64(ReportInterval)/float64(time.Second)))
 			}
+			mu.Unlock()

 			ticks = ticks2

<|current_version|>
package logger

import (
	"fmt"
	"sort"
	"time"
	"sync"
)

var tickLog = GetLogger("stats")

// The interval between logging the number of actions/sec
var ReportInterval = time.Second * 5

var ticks = make(map[string]int)
var mu = sync.Mutex{}

func init() {
	go func() {
		for {
			time.Sleep(ReportInterval)

			if len(ticks) == 0 {
				continue
			}

			ticks2 := make(map[string]int)

			mu.Lock()
			keys := make([]string, 0, len(ticks))
			for key := range ticks {
				keys = append(keys, key)
			}
			mu.Unlock()
			sort.Strings(keys)

			var msg string
			mu.Lock()
			for _, name := range keys {
				ticks2[name] = 0
				count := ticks[name]
				msg += fmt.Sprintf("[%s: %.f/sec] ", name, float64(count)/(float64(ReportInterval)/float64(time.Second)))
			}
			mu.Unlock()

			ticks = ticks2

			tickLog.Infof(msg)
		}

	}()
}

func Tick(name string) {
	TickN(name, 1)
}

func TickN(name string, number int) {
	if _, ok := ticks[name]; !ok {
		ticks[name] = 0
	}
	ticks[name] += number
}

<|next_version|>
package logger

import (
	"fmt"
	"sort"
	"time"
	"sync"
)

var tickLog = GetLogger("stats")

// The interval between logging the number of actions/sec
var ReportInterval = time.Second * 5

var ticks = make(map[string]int)
var mu = sync.Mutex{}

func init() {
	go func() {
		for {
			time.Sleep(ReportInterval)

			if len(ticks) == 0 {
				continue
			}

			ticks2 := make(map[string]int)

			mu.Lock()
			keys := make([]string, 0, len(ticks))
			for key := range ticks {
				keys = append(keys, key)
			}
			mu.Unlock()
			sort.Strings(keys)

			var msg string
			mu.Lock()
			for _, name := range keys {
				ticks2[name] = 0
				count := ticks[name]
				msg += fmt.Sprintf("[%s: %.f/sec] ", name, float64(count)/(float64(ReportInterval)/float64(time.Second)))
			}
			mu.Unlock()

			ticks = ticks2

			tickLog.Infof(msg)
		}

	}()
}

func Tick(name string) {
	TickN(name, 1)
}

func TickN(name string, number int) {
	mu.Lock()
	defer mu.Unlock()

	if _, ok := ticks[name]; !ok {
		ticks[name] = 0
	}
	ticks[name] += number
}


Fix test breakage in db

Fix test breakage in db

--- db/query_account_by_address.go
+++ db/query_account_by_address.go
@@ -19,10 +19,16 @@
 	ctlq := CoreTrustlinesByAddressQuery{q.Core, q.Address}

 	if err := Get(ctx, haq, &result.HistoryAccountRecord); err != nil {
+		if err == ErrNoResults {
+			err = nil
+		}
 		return nil, err
 	}

 	if err := Get(ctx, caq, &result.CoreAccountRecord); err != nil {
+		if err == ErrNoResults {
+			err = nil
+		}
 		return nil, err
 	}
 	if err := Select(ctx, ctlq, &result.Trustlines); err != nil {

<|original_code|>
package db

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

// AccountByAddressQuery represents a query that retrieves a composite
// of the CoreAccount and the HistoryAccount associated with an address.
type AccountByAddressQuery struct {
	History SqlQuery
	Core    SqlQuery
	Address string
}

// Get executes the query, returning any results found
func (q AccountByAddressQuery) Get(ctx context.Context) ([]interface{}, error) {
	var result AccountRecord

	haq := HistoryAccountByAddressQuery{q.History, q.Address}
	caq := CoreAccountByAddressQuery{q.Core, q.Address}
	ctlq := CoreTrustlinesByAddressQuery{q.Core, q.Address}

	if err := Get(ctx, haq, &result.HistoryAccountRecord); err != nil {
		return nil, err
	}

	if err := Get(ctx, caq, &result.CoreAccountRecord); err != nil {
		return nil, err
	}
	if err := Select(ctx, ctlq, &result.Trustlines); err != nil {
		return nil, err
	}

	return []interface{}{result}, nil
}

// IsComplete returns true when the query considers itself finished.
func (q AccountByAddressQuery) IsComplete(ctx context.Context, alreadyDelivered int) bool {
	return alreadyDelivered > 0
}

<|edits_diff|>
--- db/query_account_by_address.go
+++ db/query_account_by_address.go
@@ -19,6 +19,9 @@
 	ctlq := CoreTrustlinesByAddressQuery{q.Core, q.Address}

 	if err := Get(ctx, haq, &result.HistoryAccountRecord); err != nil {
+		if err == ErrNoResults {
+			err = nil
+		}
 		return nil, err
 	}

<|current_version|>
package db

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

// AccountByAddressQuery represents a query that retrieves a composite
// of the CoreAccount and the HistoryAccount associated with an address.
type AccountByAddressQuery struct {
	History SqlQuery
	Core    SqlQuery
	Address string
}

// Get executes the query, returning any results found
func (q AccountByAddressQuery) Get(ctx context.Context) ([]interface{}, error) {
	var result AccountRecord

	haq := HistoryAccountByAddressQuery{q.History, q.Address}
	caq := CoreAccountByAddressQuery{q.Core, q.Address}
	ctlq := CoreTrustlinesByAddressQuery{q.Core, q.Address}

	if err := Get(ctx, haq, &result.HistoryAccountRecord); err != nil {
		if err == ErrNoResults {
			err = nil
		}
		return nil, err
	}

	if err := Get(ctx, caq, &result.CoreAccountRecord); err != nil {
		return nil, err
	}
	if err := Select(ctx, ctlq, &result.Trustlines); err != nil {
		return nil, err
	}

	return []interface{}{result}, nil
}

// IsComplete returns true when the query considers itself finished.
func (q AccountByAddressQuery) IsComplete(ctx context.Context, alreadyDelivered int) bool {
	return alreadyDelivered > 0
}

<|next_version|>
package db

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

// AccountByAddressQuery represents a query that retrieves a composite
// of the CoreAccount and the HistoryAccount associated with an address.
type AccountByAddressQuery struct {
	History SqlQuery
	Core    SqlQuery
	Address string
}

// Get executes the query, returning any results found
func (q AccountByAddressQuery) Get(ctx context.Context) ([]interface{}, error) {
	var result AccountRecord

	haq := HistoryAccountByAddressQuery{q.History, q.Address}
	caq := CoreAccountByAddressQuery{q.Core, q.Address}
	ctlq := CoreTrustlinesByAddressQuery{q.Core, q.Address}

	if err := Get(ctx, haq, &result.HistoryAccountRecord); err != nil {
		if err == ErrNoResults {
			err = nil
		}
		return nil, err
	}

	if err := Get(ctx, caq, &result.CoreAccountRecord); err != nil {
		if err == ErrNoResults {
			err = nil
		}
		return nil, err
	}
	if err := Select(ctx, ctlq, &result.Trustlines); err != nil {
		return nil, err
	}

	return []interface{}{result}, nil
}

// IsComplete returns true when the query considers itself finished.
func (q AccountByAddressQuery) IsComplete(ctx context.Context, alreadyDelivered int) bool {
	return alreadyDelivered > 0
}


Add real-wolrd JSON check tests

Add real-wolrd JSON check tests

A (almost) real JSON response from an Amazon autocompletion AJAX call
Only a few empty structs have been deleted from the response of
http://completion.amazon.co.uk/search/complete?q=jo%20nesbo&search-alias=aps&mkt=4&fb=1&xcat=0

--- json_test.go
+++ json_test.go
@@ -9,9 +9,16 @@
 )

 var jr = Response{BodyBytes: []byte(`{"foo": 5, "bar": [1,2,3]}`)}
+var ar = Response{BodyBytes: []byte(`["jo nesbo",["jo nesbo","jo nesbo harry hole","jo nesbo sohn","jo nesbo koma","jo nesbo hörbuch","jo nesbo headhunter","jo nesbo pupspulver","jo nesbo leopard","jo nesbo schneemann","jo nesbo the son"],[{"nodes":[{"name":"Bücher","alias":"stripbooks"},{"name":"Trade-In","alias":"tradein-aps"},{"name":"Kindle-Shop","alias":"digital-text"}]},{}],[]]`)}
+
 var jsonTests = []TC{
 	{jr, &JSON{Expression: "(.foo == 5) && ($len(.bar)==3) && (.bar[1]==2)"}, nil},
 	{jr, &JSON{Expression: ".foo == 3"}, someError},
+	{ar, &JSON{Expression: "$len(.) > 3"}, nil},
+	{ar, &JSON{Expression: "$len(.) == 4"}, nil},
+	{ar, &JSON{Expression: ".[0] == \"jo nesbo\""}, nil},
+	{ar, &JSON{Expression: "$len(.[1]) == 10"}, nil},
+	{ar, &JSON{Expression: ".[1][6] == \"jo nesbo pupspulver\""}, nil},
 }

 func TestJSON(t *testing.T) {

<|original_code|>
// Copyright 2014 Volker Dobler.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ht

import (
	"testing"
)

var jr = Response{BodyBytes: []byte(`{"foo": 5, "bar": [1,2,3]}`)}
var jsonTests = []TC{
	{jr, &JSON{Expression: "(.foo == 5) && ($len(.bar)==3) && (.bar[1]==2)"}, nil},
	{jr, &JSON{Expression: ".foo == 3"}, someError},
}

func TestJSON(t *testing.T) {
	for i, tc := range jsonTests {
		runTest(t, i, tc)
	}
}

<|edits_diff|>
--- json_test.go
+++ json_test.go
@@ -9,6 +9,8 @@
 )

 var jr = Response{BodyBytes: []byte(`{"foo": 5, "bar": [1,2,3]}`)}
+var ar = Response{BodyBytes: []byte(`["jo nesbo",["jo nesbo","jo nesbo harry hole","jo nesbo sohn","jo nesbo koma","jo nesbo hörbuch","jo nesbo headhunter","jo nesbo pupspulver","jo nesbo leopard","jo nesbo schneemann","jo nesbo the son"],[{"nodes":[{"name":"Bücher","alias":"stripbooks"},{"name":"Trade-In","alias":"tradein-aps"},{"name":"Kindle-Shop","alias":"digital-text"}]},{}],[]]`)}
+
 var jsonTests = []TC{
 	{jr, &JSON{Expression: "(.foo == 5) && ($len(.bar)==3) && (.bar[1]==2)"}, nil},
 	{jr, &JSON{Expression: ".foo == 3"}, someError},
<|current_version|>
// Copyright 2014 Volker Dobler.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ht

import (
	"testing"
)

var jr = Response{BodyBytes: []byte(`{"foo": 5, "bar": [1,2,3]}`)}
var ar = Response{BodyBytes: []byte(`["jo nesbo",["jo nesbo","jo nesbo harry hole","jo nesbo sohn","jo nesbo koma","jo nesbo hörbuch","jo nesbo headhunter","jo nesbo pupspulver","jo nesbo leopard","jo nesbo schneemann","jo nesbo the son"],[{"nodes":[{"name":"Bücher","alias":"stripbooks"},{"name":"Trade-In","alias":"tradein-aps"},{"name":"Kindle-Shop","alias":"digital-text"}]},{}],[]]`)}

var jsonTests = []TC{
	{jr, &JSON{Expression: "(.foo == 5) && ($len(.bar)==3) && (.bar[1]==2)"}, nil},
	{jr, &JSON{Expression: ".foo == 3"}, someError},
}

func TestJSON(t *testing.T) {
	for i, tc := range jsonTests {
		runTest(t, i, tc)
	}
}

<|next_version|>
// Copyright 2014 Volker Dobler.  All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package ht

import (
	"testing"
)

var jr = Response{BodyBytes: []byte(`{"foo": 5, "bar": [1,2,3]}`)}
var ar = Response{BodyBytes: []byte(`["jo nesbo",["jo nesbo","jo nesbo harry hole","jo nesbo sohn","jo nesbo koma","jo nesbo hörbuch","jo nesbo headhunter","jo nesbo pupspulver","jo nesbo leopard","jo nesbo schneemann","jo nesbo the son"],[{"nodes":[{"name":"Bücher","alias":"stripbooks"},{"name":"Trade-In","alias":"tradein-aps"},{"name":"Kindle-Shop","alias":"digital-text"}]},{}],[]]`)}

var jsonTests = []TC{
	{jr, &JSON{Expression: "(.foo == 5) && ($len(.bar)==3) && (.bar[1]==2)"}, nil},
	{jr, &JSON{Expression: ".foo == 3"}, someError},
	{ar, &JSON{Expression: "$len(.) > 3"}, nil},
	{ar, &JSON{Expression: "$len(.) == 4"}, nil},
	{ar, &JSON{Expression: ".[0] == \"jo nesbo\""}, nil},
	{ar, &JSON{Expression: "$len(.[1]) == 10"}, nil},
	{ar, &JSON{Expression: ".[1][6] == \"jo nesbo pupspulver\""}, nil},
}

func TestJSON(t *testing.T) {
	for i, tc := range jsonTests {
		runTest(t, i, tc)
	}
}


Disable colours when the output is not a terminal

--- beanstool.go
+++ beanstool.go
@@ -3,11 +3,17 @@
 import (
 	"os"

+	"github.com/agtorre/gocolorize"
 	"github.com/jessevdk/go-flags"
 	"github.com/src-d/beanstool/cli"
+	"golang.org/x/crypto/ssh/terminal"
 )

 func main() {
+	if !terminal.IsTerminal(int(os.Stdout.Fd())) {
+		gocolorize.SetPlain(true)
+	}
+
 	parser := flags.NewNamedParser("beanstool", flags.Default)
 	parser.AddCommand("stats", "print stats on all tubes", "", &cli.StatsCommand{})
 	parser.AddCommand("tail", "tails a tube and prints his content", "", &cli.TailCommand{})

<|original_code|>
package main

import (
	"os"

	"github.com/jessevdk/go-flags"
	"github.com/src-d/beanstool/cli"
)

func main() {
	parser := flags.NewNamedParser("beanstool", flags.Default)
	parser.AddCommand("stats", "print stats on all tubes", "", &cli.StatsCommand{})
	parser.AddCommand("tail", "tails a tube and prints his content", "", &cli.TailCommand{})
	parser.AddCommand("peek", "peeks a job from a queue", "", &cli.PeekCommand{})
	parser.AddCommand("delete", "delete a job from a queue", "", &cli.DeleteCommand{})
	parser.AddCommand("kick", "kicks jobs from buried back into ready", "", &cli.KickCommand{})
	parser.AddCommand("put", "put a job into a tube", "", &cli.PutCommand{})
	parser.AddCommand("bury", "bury existing jobs from ready state", "", &cli.BuryCommand{})

	_, err := parser.Parse()
	if err != nil {
		if _, ok := err.(*flags.Error); ok {
			parser.WriteHelp(os.Stdout)
		}

		os.Exit(1)
	}
}

<|edits_diff|>
--- beanstool.go
+++ beanstool.go
@@ -3,8 +3,10 @@
 import (
 	"os"

+	"github.com/agtorre/gocolorize"
 	"github.com/jessevdk/go-flags"
 	"github.com/src-d/beanstool/cli"
+	"golang.org/x/crypto/ssh/terminal"
 )

 func main() {
<|current_version|>
package main

import (
	"os"

	"github.com/agtorre/gocolorize"
	"github.com/jessevdk/go-flags"
	"github.com/src-d/beanstool/cli"
	"golang.org/x/crypto/ssh/terminal"
)

func main() {
	parser := flags.NewNamedParser("beanstool", flags.Default)
	parser.AddCommand("stats", "print stats on all tubes", "", &cli.StatsCommand{})
	parser.AddCommand("tail", "tails a tube and prints his content", "", &cli.TailCommand{})
	parser.AddCommand("peek", "peeks a job from a queue", "", &cli.PeekCommand{})
	parser.AddCommand("delete", "delete a job from a queue", "", &cli.DeleteCommand{})
	parser.AddCommand("kick", "kicks jobs from buried back into ready", "", &cli.KickCommand{})
	parser.AddCommand("put", "put a job into a tube", "", &cli.PutCommand{})
	parser.AddCommand("bury", "bury existing jobs from ready state", "", &cli.BuryCommand{})

	_, err := parser.Parse()
	if err != nil {
		if _, ok := err.(*flags.Error); ok {
			parser.WriteHelp(os.Stdout)
		}

		os.Exit(1)
	}
}

<|next_version|>
package main

import (
	"os"

	"github.com/agtorre/gocolorize"
	"github.com/jessevdk/go-flags"
	"github.com/src-d/beanstool/cli"
	"golang.org/x/crypto/ssh/terminal"
)

func main() {
	if !terminal.IsTerminal(int(os.Stdout.Fd())) {
		gocolorize.SetPlain(true)
	}

	parser := flags.NewNamedParser("beanstool", flags.Default)
	parser.AddCommand("stats", "print stats on all tubes", "", &cli.StatsCommand{})
	parser.AddCommand("tail", "tails a tube and prints his content", "", &cli.TailCommand{})
	parser.AddCommand("peek", "peeks a job from a queue", "", &cli.PeekCommand{})
	parser.AddCommand("delete", "delete a job from a queue", "", &cli.DeleteCommand{})
	parser.AddCommand("kick", "kicks jobs from buried back into ready", "", &cli.KickCommand{})
	parser.AddCommand("put", "put a job into a tube", "", &cli.PutCommand{})
	parser.AddCommand("bury", "bury existing jobs from ready state", "", &cli.BuryCommand{})

	_, err := parser.Parse()
	if err != nil {
		if _, ok := err.(*flags.Error); ok {
			parser.WriteHelp(os.Stdout)
		}

		os.Exit(1)
	}
}


Add test for json tag on embedded field

Add test for json tag on embedded field

--- output_tests/struct_tags/fieldname/types.go
+++ output_tests/struct_tags/fieldname/types.go
@@ -1,4 +1,8 @@
 package test
+
+type E struct {
+	E1 string
+}

 type T struct {
 	F1 string `json:"F1"`
@@ -7,4 +11,5 @@
 	F4 string `json:"-,"`
 	F5 string `json:","`
 	F6 string `json:""`
+	E  `json:"e"`
 }

<|original_code|>
package test

type T struct {
	F1 string `json:"F1"`
	F2 string `json:"f2"`
	F3 string `json:"-"`
	F4 string `json:"-,"`
	F5 string `json:","`
	F6 string `json:""`
}

<|edits_diff|>
--- output_tests/struct_tags/fieldname/types.go
+++ output_tests/struct_tags/fieldname/types.go
@@ -1,4 +1,8 @@
 package test
+
+type E struct {
+	E1 string
+}

 type T struct {
 	F1 string `json:"F1"`
<|current_version|>
package test

type E struct {
	E1 string
}

type T struct {
	F1 string `json:"F1"`
	F2 string `json:"f2"`
	F3 string `json:"-"`
	F4 string `json:"-,"`
	F5 string `json:","`
	F6 string `json:""`
}

<|next_version|>
package test

type E struct {
	E1 string
}

type T struct {
	F1 string `json:"F1"`
	F2 string `json:"f2"`
	F3 string `json:"-"`
	F4 string `json:"-,"`
	F5 string `json:","`
	F6 string `json:""`
	E  `json:"e"`
}


Add close to DataSource interface.

Add close to DataSource interface.

--- db/datasource.go
+++ db/datasource.go
@@ -9,6 +9,9 @@

 	// Returns copy of data source (may be copy of session as well)
 	Copy() DataSource
+
+	// Closes data source (it will be runtime error to use it after close)
+	Close()
 }

 // Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
@@ -30,3 +33,8 @@
 func (d MongoDatabase) Copy() DataSource {
 	return MongoDatabase{d.With(d.Session.Copy())}
 }
+
+// Closes current session with mongo db
+func (d MongoDatabase) Close() {
+	d.Database.Session.Close()
+}

<|original_code|>
package db

import "gopkg.in/mgo.v2"

// Interface for generic data source (e.g. database).
type DataSource interface {
	// Returns collection by name
	C(name string) Collection

	// Returns copy of data source (may be copy of session as well)
	Copy() DataSource
}

// Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
func (s MongoSession) Source(name string) DataSource {
	return &MongoDatabase{Database: s.Session.DB(name)}
}

// Wrapper around *mgo.DataSource.
type MongoDatabase struct {
	*mgo.Database
}

// Override C method of mgo.DataSource to return wrapper around *mgo.Collection
func (d MongoDatabase) C(name string) Collection {
	return &MongoCollection{Collection: d.Database.C(name)}
}

// Returns database associated with copied session
func (d MongoDatabase) Copy() DataSource {
	return MongoDatabase{d.With(d.Session.Copy())}
}

<|edits_diff|>
--- db/datasource.go
+++ db/datasource.go
@@ -9,6 +9,9 @@

 	// Returns copy of data source (may be copy of session as well)
 	Copy() DataSource
+
+	// Closes data source (it will be runtime error to use it after close)
+	Close()
 }

 // Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
<|current_version|>
package db

import "gopkg.in/mgo.v2"

// Interface for generic data source (e.g. database).
type DataSource interface {
	// Returns collection by name
	C(name string) Collection

	// Returns copy of data source (may be copy of session as well)
	Copy() DataSource

	// Closes data source (it will be runtime error to use it after close)
	Close()
}

// Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
func (s MongoSession) Source(name string) DataSource {
	return &MongoDatabase{Database: s.Session.DB(name)}
}

// Wrapper around *mgo.DataSource.
type MongoDatabase struct {
	*mgo.Database
}

// Override C method of mgo.DataSource to return wrapper around *mgo.Collection
func (d MongoDatabase) C(name string) Collection {
	return &MongoCollection{Collection: d.Database.C(name)}
}

// Returns database associated with copied session
func (d MongoDatabase) Copy() DataSource {
	return MongoDatabase{d.With(d.Session.Copy())}
}

<|next_version|>
package db

import "gopkg.in/mgo.v2"

// Interface for generic data source (e.g. database).
type DataSource interface {
	// Returns collection by name
	C(name string) Collection

	// Returns copy of data source (may be copy of session as well)
	Copy() DataSource

	// Closes data source (it will be runtime error to use it after close)
	Close()
}

// Override Source method of mgo.Session to return wrapper around *mgo.DataSource.
func (s MongoSession) Source(name string) DataSource {
	return &MongoDatabase{Database: s.Session.DB(name)}
}

// Wrapper around *mgo.DataSource.
type MongoDatabase struct {
	*mgo.Database
}

// Override C method of mgo.DataSource to return wrapper around *mgo.Collection
func (d MongoDatabase) C(name string) Collection {
	return &MongoCollection{Collection: d.Database.C(name)}
}

// Returns database associated with copied session
func (d MongoDatabase) Copy() DataSource {
	return MongoDatabase{d.With(d.Session.Copy())}
}

// Closes current session with mongo db
func (d MongoDatabase) Close() {
	d.Database.Session.Close()
}


Add godoc string and debug flag parsing

Add godoc string and debug flag parsing

--- main.go
+++ main.go
@@ -1,6 +1,8 @@
+// This is gotify, a lightweight Spotify player written in Go
 package main

 import (
+	"flag"
 	"fmt"
 	"github.com/adrien-f/gotify/config"
 	sp "github.com/op/go-libspotify"
@@ -18,9 +20,11 @@

 var (
 	configuration *config.Configuration
+	debug         = flag.Bool("debug", false, "debug output")
 )

 func main() {
+	flag.Parse()
 	Ascii()
 	configuration = config.LoadConfig()
 }

<|original_code|>
package main

import (
	"fmt"
	"github.com/adrien-f/gotify/config"
	sp "github.com/op/go-libspotify"
)

func Ascii() {
	fmt.Println("             _   _  __")
	fmt.Println("  __ _  ___ | |_(_)/ _|_   _")
	fmt.Println(" / _` |/ _ \\| __| | |_| | | |")
	fmt.Println("| (_| | (_) | |_| |  _| |_| |")
	fmt.Println(" \\__, |\\___/ \\__|_|_|  \\__, |")
	fmt.Println(" |___/                 |___/")
	fmt.Println("\ngotify version 1.2 - libspotify", sp.BuildId())
}

var (
	configuration *config.Configuration
)

func main() {
	Ascii()
	configuration = config.LoadConfig()
}

<|edits_diff|>
--- main.go
+++ main.go
@@ -1,6 +1,8 @@
+// This is gotify, a lightweight Spotify player written in Go
 package main

 import (
+	"flag"
 	"fmt"
 	"github.com/adrien-f/gotify/config"
 	sp "github.com/op/go-libspotify"
@@ -18,6 +20,7 @@

 var (
 	configuration *config.Configuration
+	debug         = flag.Bool("debug", false, "debug output")
 )

 func main() {
<|current_version|>
// This is gotify, a lightweight Spotify player written in Go
package main

import (
	"flag"
	"fmt"
	"github.com/adrien-f/gotify/config"
	sp "github.com/op/go-libspotify"
)

func Ascii() {
	fmt.Println("             _   _  __")
	fmt.Println("  __ _  ___ | |_(_)/ _|_   _")
	fmt.Println(" / _` |/ _ \\| __| | |_| | | |")
	fmt.Println("| (_| | (_) | |_| |  _| |_| |")
	fmt.Println(" \\__, |\\___/ \\__|_|_|  \\__, |")
	fmt.Println(" |___/                 |___/")
	fmt.Println("\ngotify version 1.2 - libspotify", sp.BuildId())
}

var (
	configuration *config.Configuration
	debug         = flag.Bool("debug", false, "debug output")
)

func main() {
	Ascii()
	configuration = config.LoadConfig()
}

<|next_version|>
// This is gotify, a lightweight Spotify player written in Go
package main

import (
	"flag"
	"fmt"
	"github.com/adrien-f/gotify/config"
	sp "github.com/op/go-libspotify"
)

func Ascii() {
	fmt.Println("             _   _  __")
	fmt.Println("  __ _  ___ | |_(_)/ _|_   _")
	fmt.Println(" / _` |/ _ \\| __| | |_| | | |")
	fmt.Println("| (_| | (_) | |_| |  _| |_| |")
	fmt.Println(" \\__, |\\___/ \\__|_|_|  \\__, |")
	fmt.Println(" |___/                 |___/")
	fmt.Println("\ngotify version 1.2 - libspotify", sp.BuildId())
}

var (
	configuration *config.Configuration
	debug         = flag.Bool("debug", false, "debug output")
)

func main() {
	flag.Parse()
	Ascii()
	configuration = config.LoadConfig()
}


Support user-defined convenience package names

--- app.go
+++ app.go
@@ -23,7 +23,9 @@
 		w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
 	}
 	r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
+	r.HandleFunc("/{username}/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
 	r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
+	r.HandleFunc("/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
 	r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
 	http.Handle("/", r)
 }

<|original_code|>
package gogist

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

const t = `
<html>
  <head>
    <meta name="go-import" content="%s git https://gist.github.com/%s.git" />
    <script>window.location='https://github.com/ImJasonH/go-gist/';</script>
  </head>
</html>
`

func init() {
	r := mux.NewRouter()
	h := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
	}
	r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
	r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
	r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
	http.Handle("/", r)
}

<|edits_diff|>
--- app.go
+++ app.go
@@ -23,6 +23,7 @@
 		w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
 	}
 	r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
+	r.HandleFunc("/{username}/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
 	r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
 	r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
 	http.Handle("/", r)
<|current_version|>
package gogist

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

const t = `
<html>
  <head>
    <meta name="go-import" content="%s git https://gist.github.com/%s.git" />
    <script>window.location='https://github.com/ImJasonH/go-gist/';</script>
  </head>
</html>
`

func init() {
	r := mux.NewRouter()
	h := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
	}
	r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
	r.HandleFunc("/{username}/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
	r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
	r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
	http.Handle("/", r)
}

<|next_version|>
package gogist

import (
	"fmt"
	"net/http"

	"github.com/gorilla/mux"
)

const t = `
<html>
  <head>
    <meta name="go-import" content="%s git https://gist.github.com/%s.git" />
    <script>window.location='https://github.com/ImJasonH/go-gist/';</script>
  </head>
</html>
`

func init() {
	r := mux.NewRouter()
	h := func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "text/html")
		w.Write([]byte(fmt.Sprintf(t, r.URL.Host+r.URL.Path, mux.Vars(r)["gistID"])))
	}
	r.HandleFunc("/{username}/{gistID:[0-9]+}", h).Methods("GET")
	r.HandleFunc("/{username}/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
	r.HandleFunc("/{gistID:[0-9]+}", h).Methods("GET")
	r.HandleFunc("/{gistID:[0-9]+}/{package:[a-zA-Z0-9]+}", h).Methods("GET")
	r.Handle("/", http.RedirectHandler("https://github.com/ImJasonH/go-gist", http.StatusSeeOther))
	http.Handle("/", r)
}


Add Unwrap() methods to error types

Add Unwrap() methods to error types

To support errors.Is() and errors.As()

--- errors.go
+++ errors.go
@@ -21,6 +21,10 @@
 	return fmt.Sprintf("rmq.ConsumeError (%d): %s", e.Count, e.RedisErr.Error())
 }

+func (e *ConsumeError) Unwrap() error {
+	return e.RedisErr
+}
+
 type HeartbeatError struct {
 	RedisErr error
 	Count    int // number of consecutive errors
@@ -28,6 +32,10 @@

 func (e *HeartbeatError) Error() string {
 	return fmt.Sprintf("rmq.HeartbeatError (%d): %s", e.Count, e.RedisErr.Error())
+}
+
+func (e *HeartbeatError) Unwrap() error {
+	return e.RedisErr
 }

 type DeliveryError struct {
@@ -39,3 +47,7 @@
 func (e *DeliveryError) Error() string {
 	return fmt.Sprintf("rmq.DeliveryError (%d): %s", e.Count, e.RedisErr.Error())
 }
+
+func (e *DeliveryError) Unwrap() error {
+	return e.RedisErr
+}

<|original_code|>
package rmq

import (
	"errors"
	"fmt"
)

var (
	ErrorNotFound         = errors.New("entity not found") // entitify being connection/queue/delivery
	ErrorAlreadyConsuming = errors.New("must not call StartConsuming() multiple times")
	ErrorNotConsuming     = errors.New("must call StartConsuming() before adding consumers")
	ErrorConsumingStopped = errors.New("consuming stopped")
)

type ConsumeError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *ConsumeError) Error() string {
	return fmt.Sprintf("rmq.ConsumeError (%d): %s", e.Count, e.RedisErr.Error())
}

type HeartbeatError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *HeartbeatError) Error() string {
	return fmt.Sprintf("rmq.HeartbeatError (%d): %s", e.Count, e.RedisErr.Error())
}

type DeliveryError struct {
	Delivery Delivery
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *DeliveryError) Error() string {
	return fmt.Sprintf("rmq.DeliveryError (%d): %s", e.Count, e.RedisErr.Error())
}

<|edits_diff|>
--- errors.go
+++ errors.go
@@ -21,6 +21,10 @@
 	return fmt.Sprintf("rmq.ConsumeError (%d): %s", e.Count, e.RedisErr.Error())
 }

+func (e *ConsumeError) Unwrap() error {
+	return e.RedisErr
+}
+
 type HeartbeatError struct {
 	RedisErr error
 	Count    int // number of consecutive errors
@@ -28,6 +32,10 @@

 func (e *HeartbeatError) Error() string {
 	return fmt.Sprintf("rmq.HeartbeatError (%d): %s", e.Count, e.RedisErr.Error())
+}
+
+func (e *HeartbeatError) Unwrap() error {
+	return e.RedisErr
 }

 type DeliveryError struct {
<|current_version|>
package rmq

import (
	"errors"
	"fmt"
)

var (
	ErrorNotFound         = errors.New("entity not found") // entitify being connection/queue/delivery
	ErrorAlreadyConsuming = errors.New("must not call StartConsuming() multiple times")
	ErrorNotConsuming     = errors.New("must call StartConsuming() before adding consumers")
	ErrorConsumingStopped = errors.New("consuming stopped")
)

type ConsumeError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *ConsumeError) Error() string {
	return fmt.Sprintf("rmq.ConsumeError (%d): %s", e.Count, e.RedisErr.Error())
}

func (e *ConsumeError) Unwrap() error {
	return e.RedisErr
}

type HeartbeatError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *HeartbeatError) Error() string {
	return fmt.Sprintf("rmq.HeartbeatError (%d): %s", e.Count, e.RedisErr.Error())
}

func (e *HeartbeatError) Unwrap() error {
	return e.RedisErr
}

type DeliveryError struct {
	Delivery Delivery
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *DeliveryError) Error() string {
	return fmt.Sprintf("rmq.DeliveryError (%d): %s", e.Count, e.RedisErr.Error())
}

<|next_version|>
package rmq

import (
	"errors"
	"fmt"
)

var (
	ErrorNotFound         = errors.New("entity not found") // entitify being connection/queue/delivery
	ErrorAlreadyConsuming = errors.New("must not call StartConsuming() multiple times")
	ErrorNotConsuming     = errors.New("must call StartConsuming() before adding consumers")
	ErrorConsumingStopped = errors.New("consuming stopped")
)

type ConsumeError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *ConsumeError) Error() string {
	return fmt.Sprintf("rmq.ConsumeError (%d): %s", e.Count, e.RedisErr.Error())
}

func (e *ConsumeError) Unwrap() error {
	return e.RedisErr
}

type HeartbeatError struct {
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *HeartbeatError) Error() string {
	return fmt.Sprintf("rmq.HeartbeatError (%d): %s", e.Count, e.RedisErr.Error())
}

func (e *HeartbeatError) Unwrap() error {
	return e.RedisErr
}

type DeliveryError struct {
	Delivery Delivery
	RedisErr error
	Count    int // number of consecutive errors
}

func (e *DeliveryError) Error() string {
	return fmt.Sprintf("rmq.DeliveryError (%d): %s", e.Count, e.RedisErr.Error())
}

func (e *DeliveryError) Unwrap() error {
	return e.RedisErr
}


Add keypad and New comment

Add keypad and New comment

--- emu/core.go
+++ emu/core.go
@@ -17,10 +17,13 @@
 	V      []uint8
 	memory []uint8
 	vram   []uint8
+	keypad []uint8
 	delayt uint8
 	soundt uint8
 }

+// New initializes basic Chip8 data, but the emulator won't be in a runnable
+// state until something is loaded.
 func New() Chip8 {
 	return Chip8{
 		0,
@@ -30,6 +33,7 @@
 		make([]uint8, registersNumber, registersNumber),
 		make([]uint8, memorySize, memorySize),
 		make([]uint8, vramSize, vramSize),
+		make([]uint8, 16, 16),
 		0,
 		0,
 	}

<|original_code|>
package emu

const (
	memorySize      = 4096
	vramSize        = 64 * 32
	registersNumber = 16
	stackSize       = 16
)

// Chip8 is the main struct holding all data relevant to the emulator.
// This includes registers (V0 to VF, PC, etc.), ram and framebuffer.
type Chip8 struct {
	I      uint16
	pc     uint16
	sp     uint16
	stack  []uint16
	V      []uint8
	memory []uint8
	vram   []uint8
	delayt uint8
	soundt uint8
}

func New() Chip8 {
	return Chip8{
		0,
		0,
		0,
		make([]uint16, stackSize, stackSize),
		make([]uint8, registersNumber, registersNumber),
		make([]uint8, memorySize, memorySize),
		make([]uint8, vramSize, vramSize),
		0,
		0,
	}
}

<|edits_diff|>
--- emu/core.go
+++ emu/core.go
@@ -17,10 +17,13 @@
 	V      []uint8
 	memory []uint8
 	vram   []uint8
+	keypad []uint8
 	delayt uint8
 	soundt uint8
 }

+// New initializes basic Chip8 data, but the emulator won't be in a runnable
+// state until something is loaded.
 func New() Chip8 {
 	return Chip8{
 		0,
<|current_version|>
package emu

const (
	memorySize      = 4096
	vramSize        = 64 * 32
	registersNumber = 16
	stackSize       = 16
)

// Chip8 is the main struct holding all data relevant to the emulator.
// This includes registers (V0 to VF, PC, etc.), ram and framebuffer.
type Chip8 struct {
	I      uint16
	pc     uint16
	sp     uint16
	stack  []uint16
	V      []uint8
	memory []uint8
	vram   []uint8
	keypad []uint8
	delayt uint8
	soundt uint8
}

// New initializes basic Chip8 data, but the emulator won't be in a runnable
// state until something is loaded.
func New() Chip8 {
	return Chip8{
		0,
		0,
		0,
		make([]uint16, stackSize, stackSize),
		make([]uint8, registersNumber, registersNumber),
		make([]uint8, memorySize, memorySize),
		make([]uint8, vramSize, vramSize),
		0,
		0,
	}
}

<|next_version|>
package emu

const (
	memorySize      = 4096
	vramSize        = 64 * 32
	registersNumber = 16
	stackSize       = 16
)

// Chip8 is the main struct holding all data relevant to the emulator.
// This includes registers (V0 to VF, PC, etc.), ram and framebuffer.
type Chip8 struct {
	I      uint16
	pc     uint16
	sp     uint16
	stack  []uint16
	V      []uint8
	memory []uint8
	vram   []uint8
	keypad []uint8
	delayt uint8
	soundt uint8
}

// New initializes basic Chip8 data, but the emulator won't be in a runnable
// state until something is loaded.
func New() Chip8 {
	return Chip8{
		0,
		0,
		0,
		make([]uint16, stackSize, stackSize),
		make([]uint8, registersNumber, registersNumber),
		make([]uint8, memorySize, memorySize),
		make([]uint8, vramSize, vramSize),
		make([]uint8, 16, 16),
		0,
		0,
	}
}


Add commentary to linear search.

Add commentary to linear search.

--- search/lsearch.go
+++ search/lsearch.go
@@ -1,11 +1,18 @@
 package algoholic

+// Linear Search - Given an input slice and a sought value, return the index of that value in
+// the slice or -1 if it can't be found.
+
+// Linear Search, O(n) worst-case.
 func LinearSearch(ns []int, n int) int {
+	// Simply iterate through every item in the slice, short-circuiting and returning should we
+	// find the saught value.
 	for i, m := range ns {
 		if m == n {
 			return i
 		}
 	}

+	// We haven't found the value.
 	return -1
 }

<|original_code|>
package algoholic

func LinearSearch(ns []int, n int) int {
	for i, m := range ns {
		if m == n {
			return i
		}
	}

	return -1
}

<|edits_diff|>
--- search/lsearch.go
+++ search/lsearch.go
@@ -1,6 +1,12 @@
 package algoholic

+// Linear Search - Given an input slice and a sought value, return the index of that value in
+// the slice or -1 if it can't be found.
+
+// Linear Search, O(n) worst-case.
 func LinearSearch(ns []int, n int) int {
+	// Simply iterate through every item in the slice, short-circuiting and returning should we
+	// find the saught value.
 	for i, m := range ns {
 		if m == n {
 			return i
<|current_version|>
package algoholic

// Linear Search - Given an input slice and a sought value, return the index of that value in
// the slice or -1 if it can't be found.

// Linear Search, O(n) worst-case.
func LinearSearch(ns []int, n int) int {
	// Simply iterate through every item in the slice, short-circuiting and returning should we
	// find the saught value.
	for i, m := range ns {
		if m == n {
			return i
		}
	}

	return -1
}

<|next_version|>
package algoholic

// Linear Search - Given an input slice and a sought value, return the index of that value in
// the slice or -1 if it can't be found.

// Linear Search, O(n) worst-case.
func LinearSearch(ns []int, n int) int {
	// Simply iterate through every item in the slice, short-circuiting and returning should we
	// find the saught value.
	for i, m := range ns {
		if m == n {
			return i
		}
	}

	// We haven't found the value.
	return -1
}


Add a couple of comments

Add a couple of comments

--- watcher/lib/util.go
+++ watcher/lib/util.go
@@ -8,6 +8,7 @@
 	"github.com/gravitational/trace"
 )

+// OneOf returns true if the value is present in the list of values
 func OneOf(value string, values []string) bool {
 	for _, v := range values {
 		if v == value {
@@ -17,7 +18,9 @@
 	return false
 }

+// APIClient defines generic interface for an API client
 type APIClient interface {
+	// Health checks the API readiness
 	Health() error
 }

<|original_code|>
package lib

import (
	"context"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/gravitational/trace"
)

func OneOf(value string, values []string) bool {
	for _, v := range values {
		if v == value {
			return true
		}
	}
	return false
}

type APIClient interface {
	Health() error
}

// WaitForAPI spins until the API can be reached successfully or the provided context is cancelled
func WaitForAPI(ctx context.Context, client APIClient) error {
	for {
		select {
		case <-time.After(PollInterval):
			err := client.Health()
			if err != nil {
				log.Infof("API is not ready: %v", trace.DebugReport(err))
			} else {
				return nil
			}
		case <-ctx.Done():
			return trace.Errorf("API is not ready")
		}
	}
}

<|edits_diff|>
--- watcher/lib/util.go
+++ watcher/lib/util.go
@@ -8,6 +8,7 @@
 	"github.com/gravitational/trace"
 )

+// OneOf returns true if the value is present in the list of values
 func OneOf(value string, values []string) bool {
 	for _, v := range values {
 		if v == value {
@@ -17,6 +18,7 @@
 	return false
 }

+// APIClient defines generic interface for an API client
 type APIClient interface {
 	Health() error
 }
<|current_version|>
package lib

import (
	"context"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/gravitational/trace"
)

// OneOf returns true if the value is present in the list of values
func OneOf(value string, values []string) bool {
	for _, v := range values {
		if v == value {
			return true
		}
	}
	return false
}

// APIClient defines generic interface for an API client
type APIClient interface {
	Health() error
}

// WaitForAPI spins until the API can be reached successfully or the provided context is cancelled
func WaitForAPI(ctx context.Context, client APIClient) error {
	for {
		select {
		case <-time.After(PollInterval):
			err := client.Health()
			if err != nil {
				log.Infof("API is not ready: %v", trace.DebugReport(err))
			} else {
				return nil
			}
		case <-ctx.Done():
			return trace.Errorf("API is not ready")
		}
	}
}

<|next_version|>
package lib

import (
	"context"
	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/gravitational/trace"
)

// OneOf returns true if the value is present in the list of values
func OneOf(value string, values []string) bool {
	for _, v := range values {
		if v == value {
			return true
		}
	}
	return false
}

// APIClient defines generic interface for an API client
type APIClient interface {
	// Health checks the API readiness
	Health() error
}

// WaitForAPI spins until the API can be reached successfully or the provided context is cancelled
func WaitForAPI(ctx context.Context, client APIClient) error {
	for {
		select {
		case <-time.After(PollInterval):
			err := client.Health()
			if err != nil {
				log.Infof("API is not ready: %v", trace.DebugReport(err))
			} else {
				return nil
			}
		case <-ctx.Done():
			return trace.Errorf("API is not ready")
		}
	}
}


Add some output to let users know what is about to be scraped.

--- gophers.go
+++ gophers.go
@@ -26,13 +26,16 @@
 	}

 	if strings.Contains(githubURL, "/orgs/") {
+		fmt.Println("Organization URL. Beginning to scrape.")
 		scrapeOrganization(doc, githubURL)
 	} else if strings.Contains(githubURL, "/search?") {
+		fmt.Println("Search URL. Beginning to scrape.")
 		scrapeSearch(doc, githubURL)
 	} else if strings.Contains(githubURL, "/stargazers") {
 		fmt.Println("Stargazer URL. Beginning to scrape.")
 		scrapeStarGazers(doc, githubURL)
 	} else {
+		fmt.Println("Single profile URL. Beginning to scrape.")
 		scrapeProfile(doc)
 	}
 }

<|original_code|>
package main

import (
	"flag"
	"fmt"
	"log"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type user struct {
	name     string
	email    string
	url      string
	username string
}

func main() {
	url := flag.String("github_url", "", "github url you want to scrape")
	flag.Parse()
	githubURL := *url
	doc, err := goquery.NewDocument(githubURL)
	if err != nil {
		log.Fatal(err)
	}

	if strings.Contains(githubURL, "/orgs/") {
		scrapeOrganization(doc, githubURL)
	} else if strings.Contains(githubURL, "/search?") {
		scrapeSearch(doc, githubURL)
	} else if strings.Contains(githubURL, "/stargazers") {
		fmt.Println("Stargazer URL. Beginning to scrape.")
		scrapeStarGazers(doc, githubURL)
	} else {
		scrapeProfile(doc)
	}
}

<|edits_diff|>
--- gophers.go
+++ gophers.go
@@ -26,8 +26,10 @@
 	}

 	if strings.Contains(githubURL, "/orgs/") {
+		fmt.Println("Organization URL. Beginning to scrape.")
 		scrapeOrganization(doc, githubURL)
 	} else if strings.Contains(githubURL, "/search?") {
+		fmt.Println("Search URL. Beginning to scrape.")
 		scrapeSearch(doc, githubURL)
 	} else if strings.Contains(githubURL, "/stargazers") {
 		fmt.Println("Stargazer URL. Beginning to scrape.")
<|current_version|>
package main

import (
	"flag"
	"fmt"
	"log"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type user struct {
	name     string
	email    string
	url      string
	username string
}

func main() {
	url := flag.String("github_url", "", "github url you want to scrape")
	flag.Parse()
	githubURL := *url
	doc, err := goquery.NewDocument(githubURL)
	if err != nil {
		log.Fatal(err)
	}

	if strings.Contains(githubURL, "/orgs/") {
		fmt.Println("Organization URL. Beginning to scrape.")
		scrapeOrganization(doc, githubURL)
	} else if strings.Contains(githubURL, "/search?") {
		fmt.Println("Search URL. Beginning to scrape.")
		scrapeSearch(doc, githubURL)
	} else if strings.Contains(githubURL, "/stargazers") {
		fmt.Println("Stargazer URL. Beginning to scrape.")
		scrapeStarGazers(doc, githubURL)
	} else {
		scrapeProfile(doc)
	}
}

<|next_version|>
package main

import (
	"flag"
	"fmt"
	"log"
	"strings"

	"github.com/PuerkitoBio/goquery"
)

type user struct {
	name     string
	email    string
	url      string
	username string
}

func main() {
	url := flag.String("github_url", "", "github url you want to scrape")
	flag.Parse()
	githubURL := *url
	doc, err := goquery.NewDocument(githubURL)
	if err != nil {
		log.Fatal(err)
	}

	if strings.Contains(githubURL, "/orgs/") {
		fmt.Println("Organization URL. Beginning to scrape.")
		scrapeOrganization(doc, githubURL)
	} else if strings.Contains(githubURL, "/search?") {
		fmt.Println("Search URL. Beginning to scrape.")
		scrapeSearch(doc, githubURL)
	} else if strings.Contains(githubURL, "/stargazers") {
		fmt.Println("Stargazer URL. Beginning to scrape.")
		scrapeStarGazers(doc, githubURL)
	} else {
		fmt.Println("Single profile URL. Beginning to scrape.")
		scrapeProfile(doc)
	}
}


Disable logging for the tests

Disable logging for the tests

--- github_review_helper_suite_test.go
+++ github_review_helper_suite_test.go
@@ -1,6 +1,9 @@
 package main_test

 import (
+	"io/ioutil"
+	"log"
+
 	. "github.com/onsi/ginkgo"
 	. "github.com/onsi/gomega"

@@ -9,5 +12,6 @@

 func TestGithubReviewHelper(t *testing.T) {
 	RegisterFailHandler(Fail)
+	log.SetOutput(ioutil.Discard)
 	RunSpecs(t, "GithubReviewHelper Suite")
 }

<|original_code|>
package main_test

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

	"testing"
)

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

<|edits_diff|>
--- github_review_helper_suite_test.go
+++ github_review_helper_suite_test.go
@@ -1,6 +1,9 @@
 package main_test

 import (
+	"io/ioutil"
+	"log"
+
 	. "github.com/onsi/ginkgo"
 	. "github.com/onsi/gomega"

<|current_version|>
package main_test

import (
	"io/ioutil"
	"log"

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

	"testing"
)

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

<|next_version|>
package main_test

import (
	"io/ioutil"
	"log"

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

	"testing"
)

func TestGithubReviewHelper(t *testing.T) {
	RegisterFailHandler(Fail)
	log.SetOutput(ioutil.Discard)
	RunSpecs(t, "GithubReviewHelper Suite")
}


Add more logging in example

Add more logging in example

--- example/main.go
+++ example/main.go
@@ -4,6 +4,7 @@
 	"fmt"
 	"log"
 	"net/http"
+	"net/url"
 	"time"
 )

@@ -18,6 +19,7 @@
 }

 func helloWorld(w http.ResponseWriter, r *http.Request) {
+	log.Print(url.QueryEscape("Hello, World"))
 	fmt.Fprint(w, "Hello, world!\n")
 }

<|original_code|>
package main

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

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

func helloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, world!\n")
}

func main() {
	helloWorldHandler := http.HandlerFunc(helloWorld)
	http.Handle("/hello", loggingMiddleware(helloWorldHandler))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

<|edits_diff|>
--- example/main.go
+++ example/main.go
@@ -4,6 +4,7 @@
 	"fmt"
 	"log"
 	"net/http"
+	"net/url"
 	"time"
 )

<|current_version|>
package main

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

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

func helloWorld(w http.ResponseWriter, r *http.Request) {
	fmt.Fprint(w, "Hello, world!\n")
}

func main() {
	helloWorldHandler := http.HandlerFunc(helloWorld)
	http.Handle("/hello", loggingMiddleware(helloWorldHandler))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}

<|next_version|>
package main

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

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

func helloWorld(w http.ResponseWriter, r *http.Request) {
	log.Print(url.QueryEscape("Hello, World"))
	fmt.Fprint(w, "Hello, world!\n")
}

func main() {
	helloWorldHandler := http.HandlerFunc(helloWorld)
	http.Handle("/hello", loggingMiddleware(helloWorldHandler))
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal(err)
	}
}


Implement Stringer for anonymous function

--- src/lib/ast/anonymous_function.go
+++ src/lib/ast/anonymous_function.go
@@ -1,4 +1,6 @@
 package ast
+
+import "fmt"

 // AnonymousFunction represents a anonymous function as an expression.
 type AnonymousFunction struct {
@@ -20,3 +22,7 @@
 func (f AnonymousFunction) Body() interface{} {
 	return f.body
 }
+
+func (f AnonymousFunction) String() string {
+	return fmt.Sprintf("(\\ (%v) %v)", f.signature, f.body)
+}

<|original_code|>
package ast

// AnonymousFunction represents a anonymous function as an expression.
type AnonymousFunction struct {
	signature Signature
	body      interface{}
}

// NewAnonymousFunction creates a anonymous function.
func NewAnonymousFunction(s Signature, b interface{}) AnonymousFunction {
	return AnonymousFunction{s, b}
}

// Signature returns a signature of an anonymous function.
func (f AnonymousFunction) Signature() Signature {
	return f.signature
}

// Body returns a body expression of an anonymous function.
func (f AnonymousFunction) Body() interface{} {
	return f.body
}

<|edits_diff|>
--- src/lib/ast/anonymous_function.go
+++ src/lib/ast/anonymous_function.go
@@ -1,4 +1,6 @@
 package ast
+
+import "fmt"

 // AnonymousFunction represents a anonymous function as an expression.
 type AnonymousFunction struct {
<|current_version|>
package ast

import "fmt"

// AnonymousFunction represents a anonymous function as an expression.
type AnonymousFunction struct {
	signature Signature
	body      interface{}
}

// NewAnonymousFunction creates a anonymous function.
func NewAnonymousFunction(s Signature, b interface{}) AnonymousFunction {
	return AnonymousFunction{s, b}
}

// Signature returns a signature of an anonymous function.
func (f AnonymousFunction) Signature() Signature {
	return f.signature
}

// Body returns a body expression of an anonymous function.
func (f AnonymousFunction) Body() interface{} {
	return f.body
}

<|next_version|>
package ast

import "fmt"

// AnonymousFunction represents a anonymous function as an expression.
type AnonymousFunction struct {
	signature Signature
	body      interface{}
}

// NewAnonymousFunction creates a anonymous function.
func NewAnonymousFunction(s Signature, b interface{}) AnonymousFunction {
	return AnonymousFunction{s, b}
}

// Signature returns a signature of an anonymous function.
func (f AnonymousFunction) Signature() Signature {
	return f.signature
}

// Body returns a body expression of an anonymous function.
func (f AnonymousFunction) Body() interface{} {
	return f.body
}

func (f AnonymousFunction) String() string {
	return fmt.Sprintf("(\\ (%v) %v)", f.signature, f.body)
}


Add godoc to Base64EncodeFileName and Base64Encode

--- helper.go
+++ helper.go
@@ -6,6 +6,7 @@
 	"os"
 )

+// Base64EncodeFileName returns the base64 data URI format string of the file with the file name.
 func Base64EncodeFileName(filename string) (string, error) {
 	file, err := os.Open(filename)
 	if err != nil {
@@ -16,6 +17,7 @@
 	return Base64Encode(file)
 }

+// Base64Encode returns the base64 data URI format string of the file.
 func Base64Encode(file *os.File) (string, error) {
 	fi, err := file.Stat()
 	if err != nil {

<|original_code|>
package mastodon

import (
	"encoding/base64"
	"net/http"
	"os"
)

func Base64EncodeFileName(filename string) (string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer file.Close()

	return Base64Encode(file)
}

func Base64Encode(file *os.File) (string, error) {
	fi, err := file.Stat()
	if err != nil {
		return "", err
	}

	d := make([]byte, fi.Size())
	_, err = file.Read(d)
	if err != nil {
		return "", err
	}

	return "data:" + http.DetectContentType(d) +
		";base64," + base64.StdEncoding.EncodeToString(d), nil
}

// String is a helper function to get the pointer value of a string.
func String(v string) *string { return &v }

<|edits_diff|>
--- helper.go
+++ helper.go
@@ -6,6 +6,7 @@
 	"os"
 )

+// Base64EncodeFileName returns the base64 data URI format string of the file with the file name.
 func Base64EncodeFileName(filename string) (string, error) {
 	file, err := os.Open(filename)
 	if err != nil {
<|current_version|>
package mastodon

import (
	"encoding/base64"
	"net/http"
	"os"
)

// Base64EncodeFileName returns the base64 data URI format string of the file with the file name.
func Base64EncodeFileName(filename string) (string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer file.Close()

	return Base64Encode(file)
}

func Base64Encode(file *os.File) (string, error) {
	fi, err := file.Stat()
	if err != nil {
		return "", err
	}

	d := make([]byte, fi.Size())
	_, err = file.Read(d)
	if err != nil {
		return "", err
	}

	return "data:" + http.DetectContentType(d) +
		";base64," + base64.StdEncoding.EncodeToString(d), nil
}

// String is a helper function to get the pointer value of a string.
func String(v string) *string { return &v }

<|next_version|>
package mastodon

import (
	"encoding/base64"
	"net/http"
	"os"
)

// Base64EncodeFileName returns the base64 data URI format string of the file with the file name.
func Base64EncodeFileName(filename string) (string, error) {
	file, err := os.Open(filename)
	if err != nil {
		return "", err
	}
	defer file.Close()

	return Base64Encode(file)
}

// Base64Encode returns the base64 data URI format string of the file.
func Base64Encode(file *os.File) (string, error) {
	fi, err := file.Stat()
	if err != nil {
		return "", err
	}

	d := make([]byte, fi.Size())
	_, err = file.Read(d)
	if err != nil {
		return "", err
	}

	return "data:" + http.DetectContentType(d) +
		";base64," + base64.StdEncoding.EncodeToString(d), nil
}

// String is a helper function to get the pointer value of a string.
func String(v string) *string { return &v }


Add matchings for Lawndale High and South High.

--- misc/schools.go
+++ misc/schools.go
@@ -17,6 +17,10 @@
 		"hmsa",
 		"hms",
 	},
+	"Lawndale High School": []string{
+		"lawndale",
+		"lawndale high",
+	},
 	"North High School": []string{
 		"north high",
 		"north",
@@ -32,6 +36,9 @@
 		"samohi",
 		"smhs",
 	},
+	"South High School": []string{
+		"south high school",
+	},
 	"South Pasadena High School": []string{
 		"sphs",
 		"south pasadena high school",

<|original_code|>
package misc

var Schools = map[string][]string{
	"Da Vinci Communications": []string{
		"davinci communications",
	},
	"El Segundo High School": []string{
		"es",
		"eshs",
		"el segundo",
		"gundo",
	},
	"Harbor Teacher Preparation Academy": []string{
		"htpa",
	},
	"Hawthorne Math and Science Academy": []string{
		"hmsa",
		"hms",
	},
	"North High School": []string{
		"north high",
		"north",
	},
	"Palos Verdes High School": []string{
		"pv",
		"palos verdes hs",
	},
	"Palos Verdes Peninsula High School": []string{
		"pvphs",
	},
	"Santa Monica High School": []string{
		"samohi",
		"smhs",
	},
	"South Pasadena High School": []string{
		"sphs",
		"south pasadena high school",
	},
	"Torrance High School": []string{
		"torrance high",
	},
	"West High School": []string{
		"west",
		"west torrance high school",
		"west high sko",
	},
}

<|edits_diff|>
--- misc/schools.go
+++ misc/schools.go
@@ -16,6 +16,10 @@
 	"Hawthorne Math and Science Academy": []string{
 		"hmsa",
 		"hms",
+	},
+	"Lawndale High School": []string{
+		"lawndale",
+		"lawndale high",
 	},
 	"North High School": []string{
 		"north high",
<|current_version|>
package misc

var Schools = map[string][]string{
	"Da Vinci Communications": []string{
		"davinci communications",
	},
	"El Segundo High School": []string{
		"es",
		"eshs",
		"el segundo",
		"gundo",
	},
	"Harbor Teacher Preparation Academy": []string{
		"htpa",
	},
	"Hawthorne Math and Science Academy": []string{
		"hmsa",
		"hms",
	},
	"Lawndale High School": []string{
		"lawndale",
		"lawndale high",
	},
	"North High School": []string{
		"north high",
		"north",
	},
	"Palos Verdes High School": []string{
		"pv",
		"palos verdes hs",
	},
	"Palos Verdes Peninsula High School": []string{
		"pvphs",
	},
	"Santa Monica High School": []string{
		"samohi",
		"smhs",
	},
	"South Pasadena High School": []string{
		"sphs",
		"south pasadena high school",
	},
	"Torrance High School": []string{
		"torrance high",
	},
	"West High School": []string{
		"west",
		"west torrance high school",
		"west high sko",
	},
}

<|next_version|>
package misc

var Schools = map[string][]string{
	"Da Vinci Communications": []string{
		"davinci communications",
	},
	"El Segundo High School": []string{
		"es",
		"eshs",
		"el segundo",
		"gundo",
	},
	"Harbor Teacher Preparation Academy": []string{
		"htpa",
	},
	"Hawthorne Math and Science Academy": []string{
		"hmsa",
		"hms",
	},
	"Lawndale High School": []string{
		"lawndale",
		"lawndale high",
	},
	"North High School": []string{
		"north high",
		"north",
	},
	"Palos Verdes High School": []string{
		"pv",
		"palos verdes hs",
	},
	"Palos Verdes Peninsula High School": []string{
		"pvphs",
	},
	"Santa Monica High School": []string{
		"samohi",
		"smhs",
	},
	"South High School": []string{
		"south high school",
	},
	"South Pasadena High School": []string{
		"sphs",
		"south pasadena high school",
	},
	"Torrance High School": []string{
		"torrance high",
	},
	"West High School": []string{
		"west",
		"west torrance high school",
		"west high sko",
	},
}


Add ping results to ring buffer

Add ping results to ring buffer

--- main.go
+++ main.go
@@ -1,6 +1,7 @@
 package main

 import (
+	"container/ring"
 	"log"
 	"os"
 	"os/signal"
@@ -9,6 +10,8 @@
 )

 func main() {
+	ring := ring.New(10)
+
 	ticker := time.NewTicker(10 * time.Second)
 	go func() {
 		for _ = range ticker.C {
@@ -17,6 +20,8 @@
 			if err != nil {
 				log.Fatal(err)
 			}
+			ring.Value = res
+			ring.Next()
 			log.Printf("Min: %f ms\n", res.Min)
 			log.Printf("Avg: %f ms\n", res.Avg)
 			log.Printf("Max: %f ms\n", res.Max)

<|original_code|>
package main

import (
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	ticker := time.NewTicker(10 * time.Second)
	go func() {
		for _ = range ticker.C {
			log.Println("ping google.com -c 5")
			res, err := ping("google.com", 5)
			if err != nil {
				log.Fatal(err)
			}
			log.Printf("Min: %f ms\n", res.Min)
			log.Printf("Avg: %f ms\n", res.Avg)
			log.Printf("Max: %f ms\n", res.Max)
			log.Printf("Mdev: %f ms\n", res.Mdev)
		}
	}()

	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Printf("Received signal: %v\n", <-ch)
	log.Println("Shutting down")
	ticker.Stop()
}

<|edits_diff|>
--- main.go
+++ main.go
@@ -1,6 +1,7 @@
 package main

 import (
+	"container/ring"
 	"log"
 	"os"
 	"os/signal"
@@ -9,6 +10,8 @@
 )

 func main() {
+	ring := ring.New(10)
+
 	ticker := time.NewTicker(10 * time.Second)
 	go func() {
 		for _ = range ticker.C {
<|current_version|>
package main

import (
	"container/ring"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	ring := ring.New(10)

	ticker := time.NewTicker(10 * time.Second)
	go func() {
		for _ = range ticker.C {
			log.Println("ping google.com -c 5")
			res, err := ping("google.com", 5)
			if err != nil {
				log.Fatal(err)
			}
			log.Printf("Min: %f ms\n", res.Min)
			log.Printf("Avg: %f ms\n", res.Avg)
			log.Printf("Max: %f ms\n", res.Max)
			log.Printf("Mdev: %f ms\n", res.Mdev)
		}
	}()

	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Printf("Received signal: %v\n", <-ch)
	log.Println("Shutting down")
	ticker.Stop()
}

<|next_version|>
package main

import (
	"container/ring"
	"log"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	ring := ring.New(10)

	ticker := time.NewTicker(10 * time.Second)
	go func() {
		for _ = range ticker.C {
			log.Println("ping google.com -c 5")
			res, err := ping("google.com", 5)
			if err != nil {
				log.Fatal(err)
			}
			ring.Value = res
			ring.Next()
			log.Printf("Min: %f ms\n", res.Min)
			log.Printf("Avg: %f ms\n", res.Avg)
			log.Printf("Max: %f ms\n", res.Max)
			log.Printf("Mdev: %f ms\n", res.Mdev)
		}
	}()

	ch := make(chan os.Signal)
	signal.Notify(ch, syscall.SIGINT, syscall.SIGTERM)
	log.Printf("Received signal: %v\n", <-ch)
	log.Println("Shutting down")
	ticker.Stop()
}


Add a build version to executables

Add a build version to executables

Use -v to print version info.

--- main.go
+++ main.go
@@ -20,6 +20,10 @@

 	// Debug logging
 	debug bool
+
+	// version flags
+	version      bool
+	buildVersion string
 )

 func init() {
@@ -27,6 +31,7 @@
 	flag.StringVar(&defaultConfig, "config", "", "default config file")
 	flag.StringVar(&stateConfig, "state", "", "updated config which reflects the internal state")
 	flag.BoolVar(&debug, "debug", false, "verbose logging")
+	flag.BoolVar(&version, "v", false, "display version")

 	flag.Parse()
 }
@@ -36,6 +41,11 @@
 		log.DefaultLogger.Level = log.DEBUG
 	}

+	if version {
+		println(buildVersion)
+		return
+	}
+
 	loadConfig()
 	startHTTPServer()
 }

<|original_code|>
package main

import (
	"flag"

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

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

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

	// Listen address for the http server.
	listenAddr string

	// Debug logging
	debug bool
)

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

	flag.Parse()
}

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

	loadConfig()
	startHTTPServer()
}

<|edits_diff|>
--- main.go
+++ main.go
@@ -20,6 +20,10 @@

 	// Debug logging
 	debug bool
+
+	// version flags
+	version      bool
+	buildVersion string
 )

 func init() {
@@ -27,6 +31,7 @@
 	flag.StringVar(&defaultConfig, "config", "", "default config file")
 	flag.StringVar(&stateConfig, "state", "", "updated config which reflects the internal state")
 	flag.BoolVar(&debug, "debug", false, "verbose logging")
+	flag.BoolVar(&version, "v", false, "display version")

 	flag.Parse()
 }
<|current_version|>
package main

import (
	"flag"

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

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

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

	// Listen address for the http server.
	listenAddr string

	// Debug logging
	debug bool

	// version flags
	version      bool
	buildVersion string
)

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

	flag.Parse()
}

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

	loadConfig()
	startHTTPServer()
}

<|next_version|>
package main

import (
	"flag"

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

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

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

	// Listen address for the http server.
	listenAddr string

	// Debug logging
	debug bool

	// version flags
	version      bool
	buildVersion string
)

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

	flag.Parse()
}

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

	if version {
		println(buildVersion)
		return
	}

	loadConfig()
	startHTTPServer()
}


Add comments explaining Foo tags

Add comments explaining Foo tags

--- magic_table_test.go
+++ magic_table_test.go
@@ -8,10 +8,15 @@
 )

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

<|original_code|>
package magicsql

import (
	"strings"
	"testing"

	"./assert"
)

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

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

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

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

<|edits_diff|>
--- magic_table_test.go
+++ magic_table_test.go
@@ -8,9 +8,13 @@
 )

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

import (
	"strings"
	"testing"

	"./assert"
)

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

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

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

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

<|next_version|>
package magicsql

import (
	"strings"
	"testing"

	"./assert"
)

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

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

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

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


Support --v and --vmodule silently

Support --v and --vmodule silently

Allows compatibility with Kubernetes invocation directly

--- pkg/cmd/flagtypes/glog.go
+++ pkg/cmd/flagtypes/glog.go
@@ -14,10 +14,18 @@
 		level := flag.Value.(*glog.Level)
 		levelPtr := (*int32)(level)
 		flags.Int32Var(levelPtr, "loglevel", 0, "Set the level of log output (0-10)")
+		if flags.Lookup("v") == nil {
+			flags.Int32Var(levelPtr, "v", 0, "Set the level of log output (0-10)")
+		}
+		flags.Lookup("v").Hidden = true
 	}
 	if flag := from.Lookup("vmodule"); flag != nil {
 		value := flag.Value
 		flags.Var(pflagValue{value}, "logspec", "Set per module logging with file|pattern=LEVEL,...")
+		if flags.Lookup("vmodule") == nil {
+			flags.Var(pflagValue{value}, "vmodule", "Set per module logging with file|pattern=LEVEL,...")
+		}
+		flags.Lookup("vmodule").Hidden = true
 	}
 }

<|original_code|>
package flagtypes

import (
	"flag"

	"github.com/golang/glog"
	"github.com/spf13/pflag"
)

// GLog binds the log flags from the default Google "flag" package into a pflag.FlagSet.
func GLog(flags *pflag.FlagSet) {
	from := flag.CommandLine
	if flag := from.Lookup("v"); flag != nil {
		level := flag.Value.(*glog.Level)
		levelPtr := (*int32)(level)
		flags.Int32Var(levelPtr, "loglevel", 0, "Set the level of log output (0-10)")
	}
	if flag := from.Lookup("vmodule"); flag != nil {
		value := flag.Value
		flags.Var(pflagValue{value}, "logspec", "Set per module logging with file|pattern=LEVEL,...")
	}
}

type pflagValue struct {
	flag.Value
}

func (pflagValue) Type() string {
	return "string"
}

<|edits_diff|>
--- pkg/cmd/flagtypes/glog.go
+++ pkg/cmd/flagtypes/glog.go
@@ -14,6 +14,10 @@
 		level := flag.Value.(*glog.Level)
 		levelPtr := (*int32)(level)
 		flags.Int32Var(levelPtr, "loglevel", 0, "Set the level of log output (0-10)")
+		if flags.Lookup("v") == nil {
+			flags.Int32Var(levelPtr, "v", 0, "Set the level of log output (0-10)")
+		}
+		flags.Lookup("v").Hidden = true
 	}
 	if flag := from.Lookup("vmodule"); flag != nil {
 		value := flag.Value
<|current_version|>
package flagtypes

import (
	"flag"

	"github.com/golang/glog"
	"github.com/spf13/pflag"
)

// GLog binds the log flags from the default Google "flag" package into a pflag.FlagSet.
func GLog(flags *pflag.FlagSet) {
	from := flag.CommandLine
	if flag := from.Lookup("v"); flag != nil {
		level := flag.Value.(*glog.Level)
		levelPtr := (*int32)(level)
		flags.Int32Var(levelPtr, "loglevel", 0, "Set the level of log output (0-10)")
		if flags.Lookup("v") == nil {
			flags.Int32Var(levelPtr, "v", 0, "Set the level of log output (0-10)")
		}
		flags.Lookup("v").Hidden = true
	}
	if flag := from.Lookup("vmodule"); flag != nil {
		value := flag.Value
		flags.Var(pflagValue{value}, "logspec", "Set per module logging with file|pattern=LEVEL,...")
	}
}

type pflagValue struct {
	flag.Value
}

func (pflagValue) Type() string {
	return "string"
}

<|next_version|>
package flagtypes

import (
	"flag"

	"github.com/golang/glog"
	"github.com/spf13/pflag"
)

// GLog binds the log flags from the default Google "flag" package into a pflag.FlagSet.
func GLog(flags *pflag.FlagSet) {
	from := flag.CommandLine
	if flag := from.Lookup("v"); flag != nil {
		level := flag.Value.(*glog.Level)
		levelPtr := (*int32)(level)
		flags.Int32Var(levelPtr, "loglevel", 0, "Set the level of log output (0-10)")
		if flags.Lookup("v") == nil {
			flags.Int32Var(levelPtr, "v", 0, "Set the level of log output (0-10)")
		}
		flags.Lookup("v").Hidden = true
	}
	if flag := from.Lookup("vmodule"); flag != nil {
		value := flag.Value
		flags.Var(pflagValue{value}, "logspec", "Set per module logging with file|pattern=LEVEL,...")
		if flags.Lookup("vmodule") == nil {
			flags.Var(pflagValue{value}, "vmodule", "Set per module logging with file|pattern=LEVEL,...")
		}
		flags.Lookup("vmodule").Hidden = true
	}
}

type pflagValue struct {
	flag.Value
}

func (pflagValue) Type() string {
	return "string"
}


Add comments to value object methods

Add comments to value object methods

--- cmd/user/internal/domain/user/models.go
+++ cmd/user/internal/domain/user/models.go
@@ -10,6 +10,7 @@
 // EmailAddress is an email address value object
 type EmailAddress string

+// UnmarshalJSON implements Unmarshal interface
 func (e *EmailAddress) UnmarshalJSON(b []byte) error {
 	var value string

@@ -24,6 +25,7 @@
 	return e.IsValid()
 }

+// IsValid returns error if value object is not valid
 func (e EmailAddress) IsValid() error {
 	if !govalidator.IsEmail(string(e)) {
 		return errors.New(errors.INTERNAL, "Invalid email address")

<|original_code|>
package user

import (
	"encoding/json"

	"github.com/asaskevich/govalidator"
	"github.com/vardius/go-api-boilerplate/internal/errors"
)

// EmailAddress is an email address value object
type EmailAddress string

func (e *EmailAddress) UnmarshalJSON(b []byte) error {
	var value string

	err := json.Unmarshal(b, &value)
	if err != nil {
		return errors.Wrap(err, errors.INTERNAL, "Unmarshal error")
	}

	//noinspection GoAssignmentToReceiver
	e = (*EmailAddress)(&value)

	return e.IsValid()
}

func (e EmailAddress) IsValid() error {
	if !govalidator.IsEmail(string(e)) {
		return errors.New(errors.INTERNAL, "Invalid email address")
	}

	return nil
}

<|edits_diff|>
--- cmd/user/internal/domain/user/models.go
+++ cmd/user/internal/domain/user/models.go
@@ -10,6 +10,7 @@
 // EmailAddress is an email address value object
 type EmailAddress string

+// UnmarshalJSON implements Unmarshal interface
 func (e *EmailAddress) UnmarshalJSON(b []byte) error {
 	var value string

<|current_version|>
package user

import (
	"encoding/json"

	"github.com/asaskevich/govalidator"
	"github.com/vardius/go-api-boilerplate/internal/errors"
)

// EmailAddress is an email address value object
type EmailAddress string

// UnmarshalJSON implements Unmarshal interface
func (e *EmailAddress) UnmarshalJSON(b []byte) error {
	var value string

	err := json.Unmarshal(b, &value)
	if err != nil {
		return errors.Wrap(err, errors.INTERNAL, "Unmarshal error")
	}

	//noinspection GoAssignmentToReceiver
	e = (*EmailAddress)(&value)

	return e.IsValid()
}

func (e EmailAddress) IsValid() error {
	if !govalidator.IsEmail(string(e)) {
		return errors.New(errors.INTERNAL, "Invalid email address")
	}

	return nil
}

<|next_version|>
package user

import (
	"encoding/json"

	"github.com/asaskevich/govalidator"
	"github.com/vardius/go-api-boilerplate/internal/errors"
)

// EmailAddress is an email address value object
type EmailAddress string

// UnmarshalJSON implements Unmarshal interface
func (e *EmailAddress) UnmarshalJSON(b []byte) error {
	var value string

	err := json.Unmarshal(b, &value)
	if err != nil {
		return errors.Wrap(err, errors.INTERNAL, "Unmarshal error")
	}

	//noinspection GoAssignmentToReceiver
	e = (*EmailAddress)(&value)

	return e.IsValid()
}

// IsValid returns error if value object is not valid
func (e EmailAddress) IsValid() error {
	if !govalidator.IsEmail(string(e)) {
		return errors.New(errors.INTERNAL, "Invalid email address")
	}

	return nil
}


Allow for .yml files in vendored code

Allow for .yml files in vendored code

--- config/tests/lint/config_lint_test.go
+++ config/tests/lint/config_lint_test.go
@@ -24,8 +24,19 @@

 var configPath = "../../../config/"

+var exemptPaths = []string{
+	"prow/cluster/monitoring/mixins/vendor",
+}
+
 func Test_ForbidYmlExtension(t *testing.T) {
+	exempt := map[string]bool{}
+	for _, path := range exemptPaths {
+		exempt[filepath.Join(configPath, path)] = true
+	}
 	err := filepath.Walk(configPath, func(path string, info os.FileInfo, err error) error {
+		if _, ok := exempt[path]; ok {
+			return filepath.SkipDir
+		}
 		if filepath.Ext(path) == ".yml" {
 			t.Errorf("*.yml extension not allowed in this repository's configuration; use *.yaml instead (at %s)", path)
 		}

<|original_code|>
/*
Copyright 2019 The Kubernetes Authors.

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

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

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

package tests

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

var configPath = "../../../config/"

func Test_ForbidYmlExtension(t *testing.T) {
	err := filepath.Walk(configPath, func(path string, info os.FileInfo, err error) error {
		if filepath.Ext(path) == ".yml" {
			t.Errorf("*.yml extension not allowed in this repository's configuration; use *.yaml instead (at %s)", path)
		}
		return nil
	})

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

<|edits_diff|>
--- config/tests/lint/config_lint_test.go
+++ config/tests/lint/config_lint_test.go
@@ -24,7 +24,15 @@

 var configPath = "../../../config/"

+var exemptPaths = []string{
+	"prow/cluster/monitoring/mixins/vendor",
+}
+
 func Test_ForbidYmlExtension(t *testing.T) {
+	exempt := map[string]bool{}
+	for _, path := range exemptPaths {
+		exempt[filepath.Join(configPath, path)] = true
+	}
 	err := filepath.Walk(configPath, func(path string, info os.FileInfo, err error) error {
 		if filepath.Ext(path) == ".yml" {
 			t.Errorf("*.yml extension not allowed in this repository's configuration; use *.yaml instead (at %s)", path)
<|current_version|>
/*
Copyright 2019 The Kubernetes Authors.

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

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

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

package tests

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

var configPath = "../../../config/"

var exemptPaths = []string{
	"prow/cluster/monitoring/mixins/vendor",
}

func Test_ForbidYmlExtension(t *testing.T) {
	exempt := map[string]bool{}
	for _, path := range exemptPaths {
		exempt[filepath.Join(configPath, path)] = true
	}
	err := filepath.Walk(configPath, func(path string, info os.FileInfo, err error) error {
		if filepath.Ext(path) == ".yml" {
			t.Errorf("*.yml extension not allowed in this repository's configuration; use *.yaml instead (at %s)", path)
		}
		return nil
	})

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

<|next_version|>
/*
Copyright 2019 The Kubernetes Authors.

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

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

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

package tests

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

var configPath = "../../../config/"

var exemptPaths = []string{
	"prow/cluster/monitoring/mixins/vendor",
}

func Test_ForbidYmlExtension(t *testing.T) {
	exempt := map[string]bool{}
	for _, path := range exemptPaths {
		exempt[filepath.Join(configPath, path)] = true
	}
	err := filepath.Walk(configPath, func(path string, info os.FileInfo, err error) error {
		if _, ok := exempt[path]; ok {
			return filepath.SkipDir
		}
		if filepath.Ext(path) == ".yml" {
			t.Errorf("*.yml extension not allowed in this repository's configuration; use *.yaml instead (at %s)", path)
		}
		return nil
	})

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


Fix panic when treeish not passed to git diff-index

--- cmd/diffindex.go
+++ cmd/diffindex.go
@@ -2,6 +2,7 @@

 import (
 	"flag"
+	"fmt"

 	"github.com/driusan/dgit/git"
 )
@@ -13,6 +14,10 @@
 	flags.BoolVar(&options.Cached, "cached", false, "Do not compare the filesystem, only the index")

 	args, err := parseCommonDiffFlags(c, &options.DiffCommonOptions, flags, args)
+
+	if len(args) < 1 {
+		return fmt.Errorf("Must provide a treeish to git diff-index")
+	}

 	treeish, err := git.RevParseCommit(c, &git.RevParseOptions{}, args[0])
 	if err != nil {

<|original_code|>
package cmd

import (
	"flag"

	"github.com/driusan/dgit/git"
)

func DiffIndex(c *git.Client, args []string) error {
	flags := flag.NewFlagSet("diff-index", flag.ExitOnError)

	options := git.DiffIndexOptions{}
	flags.BoolVar(&options.Cached, "cached", false, "Do not compare the filesystem, only the index")

	args, err := parseCommonDiffFlags(c, &options.DiffCommonOptions, flags, args)

	treeish, err := git.RevParseCommit(c, &git.RevParseOptions{}, args[0])
	if err != nil {
		return err
	}
	diffs, err := git.DiffIndex(c, &options, treeish, args[1:])
	if err != nil {
		return err
	}

	printDiffs(c, options.DiffCommonOptions, diffs)
	return nil
}

<|edits_diff|>
--- cmd/diffindex.go
+++ cmd/diffindex.go
@@ -2,6 +2,7 @@

 import (
 	"flag"
+	"fmt"

 	"github.com/driusan/dgit/git"
 )
<|current_version|>
package cmd

import (
	"flag"
	"fmt"

	"github.com/driusan/dgit/git"
)

func DiffIndex(c *git.Client, args []string) error {
	flags := flag.NewFlagSet("diff-index", flag.ExitOnError)

	options := git.DiffIndexOptions{}
	flags.BoolVar(&options.Cached, "cached", false, "Do not compare the filesystem, only the index")

	args, err := parseCommonDiffFlags(c, &options.DiffCommonOptions, flags, args)

	treeish, err := git.RevParseCommit(c, &git.RevParseOptions{}, args[0])
	if err != nil {
		return err
	}
	diffs, err := git.DiffIndex(c, &options, treeish, args[1:])
	if err != nil {
		return err
	}

	printDiffs(c, options.DiffCommonOptions, diffs)
	return nil
}

<|next_version|>
package cmd

import (
	"flag"
	"fmt"

	"github.com/driusan/dgit/git"
)

func DiffIndex(c *git.Client, args []string) error {
	flags := flag.NewFlagSet("diff-index", flag.ExitOnError)

	options := git.DiffIndexOptions{}
	flags.BoolVar(&options.Cached, "cached", false, "Do not compare the filesystem, only the index")

	args, err := parseCommonDiffFlags(c, &options.DiffCommonOptions, flags, args)

	if len(args) < 1 {
		return fmt.Errorf("Must provide a treeish to git diff-index")
	}

	treeish, err := git.RevParseCommit(c, &git.RevParseOptions{}, args[0])
	if err != nil {
		return err
	}
	diffs, err := git.DiffIndex(c, &options, treeish, args[1:])
	if err != nil {
		return err
	}

	printDiffs(c, options.DiffCommonOptions, diffs)
	return nil
}


Add test command (*It can be tested with `go install` to get local test cli)

--- commands.go
+++ commands.go
@@ -3,6 +3,7 @@
 import (
 	"log"
 	"os"
+	"fmt"

 	"github.com/codegangsta/cli"
 )
@@ -50,6 +51,7 @@
 }

 func doAll(c *cli.Context) {
+	fmt.Printf("print all")
 }

 func doBiz(c *cli.Context) {

<|original_code|>
package main

import (
	"log"
	"os"

	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

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

func doAll(c *cli.Context) {
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

<|edits_diff|>
--- commands.go
+++ commands.go
@@ -3,6 +3,7 @@
 import (
 	"log"
 	"os"
+	"fmt"

 	"github.com/codegangsta/cli"
 )
<|current_version|>
package main

import (
	"log"
	"os"
	"fmt"

	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

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

func doAll(c *cli.Context) {
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}

<|next_version|>
package main

import (
	"log"
	"os"
	"fmt"

	"github.com/codegangsta/cli"
)

var Commands = []cli.Command{
	commandAll,
	commandBiz,
	commandHack,
}

var commandAll = cli.Command{
	Name:  "all",
	Usage: "",
	Description: `
`,
	Action: doAll,
}

var commandBiz = cli.Command{
	Name:  "biz",
	Usage: "",
	Description: `
`,
	Action: doBiz,
}

var commandHack = cli.Command{
	Name:  "hack",
	Usage: "",
	Description: `
`,
	Action: doHack,
}

func debug(v ...interface{}) {
	if os.Getenv("DEBUG") != "" {
		log.Println(v...)
	}
}

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

func doAll(c *cli.Context) {
	fmt.Printf("print all")
}

func doBiz(c *cli.Context) {
}

func doHack(c *cli.Context) {
}


changed: Enable `referers` as parameter of GenerateSecuredAPIKey

--- algoliasearch/check_key.go
+++ algoliasearch/check_key.go
@@ -6,6 +6,7 @@
 		"restrictSources",
 		"userToken",
 		"validUntil",
+		"referers",
 	); err != nil {
 		return err
 	}
@@ -20,6 +21,11 @@
 		case "validUntil":
 			if _, ok := v.(int); !ok {
 				return invalidType(k, "int")
+			}
+
+		case "referers":
+			if _, ok := v.([]string); !ok {
+				return invalidType(k, "[]string")
 			}

 		default:

<|original_code|>
package algoliasearch

func checkGenerateSecuredAPIKey(params Map) error {
	if err := checkQuery(params,
		"restrictIndices",
		"restrictSources",
		"userToken",
		"validUntil",
	); err != nil {
		return err
	}

	for k, v := range params {
		switch k {
		case "restrictIndices", "restrictSources", "userToken":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "validUntil":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		default:
			// OK
		}
	}

	return nil
}

func checkKey(params Map) error {
	for k, v := range params {
		switch k {
		case "acl", "indexes", "referers":
			if _, ok := v.([]string); !ok {
				return invalidType(k, "[]string")
			}

		case "description", "queryParameters":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "maxHitsPerQuery", "maxQueriesPerIPPerHour", "validity":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		default:
			// OK
		}
	}

	return nil
}

<|edits_diff|>
--- algoliasearch/check_key.go
+++ algoliasearch/check_key.go
@@ -6,6 +6,7 @@
 		"restrictSources",
 		"userToken",
 		"validUntil",
+		"referers",
 	); err != nil {
 		return err
 	}
<|current_version|>
package algoliasearch

func checkGenerateSecuredAPIKey(params Map) error {
	if err := checkQuery(params,
		"restrictIndices",
		"restrictSources",
		"userToken",
		"validUntil",
		"referers",
	); err != nil {
		return err
	}

	for k, v := range params {
		switch k {
		case "restrictIndices", "restrictSources", "userToken":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "validUntil":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		default:
			// OK
		}
	}

	return nil
}

func checkKey(params Map) error {
	for k, v := range params {
		switch k {
		case "acl", "indexes", "referers":
			if _, ok := v.([]string); !ok {
				return invalidType(k, "[]string")
			}

		case "description", "queryParameters":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "maxHitsPerQuery", "maxQueriesPerIPPerHour", "validity":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		default:
			// OK
		}
	}

	return nil
}

<|next_version|>
package algoliasearch

func checkGenerateSecuredAPIKey(params Map) error {
	if err := checkQuery(params,
		"restrictIndices",
		"restrictSources",
		"userToken",
		"validUntil",
		"referers",
	); err != nil {
		return err
	}

	for k, v := range params {
		switch k {
		case "restrictIndices", "restrictSources", "userToken":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "validUntil":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		case "referers":
			if _, ok := v.([]string); !ok {
				return invalidType(k, "[]string")
			}

		default:
			// OK
		}
	}

	return nil
}

func checkKey(params Map) error {
	for k, v := range params {
		switch k {
		case "acl", "indexes", "referers":
			if _, ok := v.([]string); !ok {
				return invalidType(k, "[]string")
			}

		case "description", "queryParameters":
			if _, ok := v.(string); !ok {
				return invalidType(k, "string")
			}

		case "maxHitsPerQuery", "maxQueriesPerIPPerHour", "validity":
			if _, ok := v.(int); !ok {
				return invalidType(k, "int")
			}

		default:
			// OK
		}
	}

	return nil
}


Add documentation example for Size()

Add documentation example for Size()

--- size_test.go
+++ size_test.go
@@ -1,9 +1,15 @@
 package gstrings

 import (
+	"fmt"
 	"github.com/wallclockbuilder/testify/assert"
 	"testing"
 )
+
+func ExampleSize(){
+	fmt.Println(Size("hello"))
+	// Output: 5
+}

 func TestSize(t *testing.T) {
 	assert := assert.New(t)

<|original_code|>
package gstrings

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

func TestSize(t *testing.T) {
	assert := assert.New(t)
	assert.Equal(5, Size("hello"))
}

<|edits_diff|>
--- size_test.go
+++ size_test.go
@@ -1,6 +1,7 @@
 package gstrings

 import (
+	"fmt"
 	"github.com/wallclockbuilder/testify/assert"
 	"testing"
 )
<|current_version|>
package gstrings

import (
	"fmt"
	"github.com/wallclockbuilder/testify/assert"
	"testing"
)

func TestSize(t *testing.T) {
	assert := assert.New(t)
	assert.Equal(5, Size("hello"))
}

<|next_version|>
package gstrings

import (
	"fmt"
	"github.com/wallclockbuilder/testify/assert"
	"testing"
)

func ExampleSize(){
	fmt.Println(Size("hello"))
	// Output: 5
}

func TestSize(t *testing.T) {
	assert := assert.New(t)
	assert.Equal(5, Size("hello"))
}


Add comments to public functions

Add comments to public functions

--- pull/releasepull.go
+++ pull/releasepull.go
@@ -10,10 +10,12 @@
 	"github.com/mitchellh/ioprogress"
 )

+// NewRelease creates a new Release instance
 func NewRelease(cache string) *Release {
 	return &Release{CacheDir: cache}
 }

+// Release is a BOSH release with a configurable cache dir
 type Release struct {
 	CacheDir string
 }

<|original_code|>
package pull

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path"

	"github.com/mitchellh/ioprogress"
)

func NewRelease(cache string) *Release {
	return &Release{CacheDir: cache}
}

type Release struct {
	CacheDir string
}

// Pull downloads the specified Release to the local cache dir
func (s *Release) Pull(url string) (filename string, err error) {

	name := path.Base(url)
	filename = s.CacheDir + "/" + name

	if _, err = os.Stat(filename); os.IsNotExist(err) {
		fmt.Println("Could not find release in local cache. Downloading now.")
		var out *os.File
		out, err = os.Create(filename)
		if err != nil {
			return
		}
		var resp *http.Response
		resp, err = http.Get(url)
		if err != nil {
			return
		}
		defer func() {
			if cerr := resp.Body.Close(); cerr != nil {
				err = cerr
			}
		}()

		progressR := &ioprogress.Reader{
			Reader: resp.Body,
			Size:   resp.ContentLength,
		}
		_, err = io.Copy(out, progressR)
	}
	return
}

<|edits_diff|>
--- pull/releasepull.go
+++ pull/releasepull.go
@@ -10,6 +10,7 @@
 	"github.com/mitchellh/ioprogress"
 )

+// NewRelease creates a new Release instance
 func NewRelease(cache string) *Release {
 	return &Release{CacheDir: cache}
 }
<|current_version|>
package pull

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path"

	"github.com/mitchellh/ioprogress"
)

// NewRelease creates a new Release instance
func NewRelease(cache string) *Release {
	return &Release{CacheDir: cache}
}

type Release struct {
	CacheDir string
}

// Pull downloads the specified Release to the local cache dir
func (s *Release) Pull(url string) (filename string, err error) {

	name := path.Base(url)
	filename = s.CacheDir + "/" + name

	if _, err = os.Stat(filename); os.IsNotExist(err) {
		fmt.Println("Could not find release in local cache. Downloading now.")
		var out *os.File
		out, err = os.Create(filename)
		if err != nil {
			return
		}
		var resp *http.Response
		resp, err = http.Get(url)
		if err != nil {
			return
		}
		defer func() {
			if cerr := resp.Body.Close(); cerr != nil {
				err = cerr
			}
		}()

		progressR := &ioprogress.Reader{
			Reader: resp.Body,
			Size:   resp.ContentLength,
		}
		_, err = io.Copy(out, progressR)
	}
	return
}

<|next_version|>
package pull

import (
	"fmt"
	"io"
	"net/http"
	"os"
	"path"

	"github.com/mitchellh/ioprogress"
)

// NewRelease creates a new Release instance
func NewRelease(cache string) *Release {
	return &Release{CacheDir: cache}
}

// Release is a BOSH release with a configurable cache dir
type Release struct {
	CacheDir string
}

// Pull downloads the specified Release to the local cache dir
func (s *Release) Pull(url string) (filename string, err error) {

	name := path.Base(url)
	filename = s.CacheDir + "/" + name

	if _, err = os.Stat(filename); os.IsNotExist(err) {
		fmt.Println("Could not find release in local cache. Downloading now.")
		var out *os.File
		out, err = os.Create(filename)
		if err != nil {
			return
		}
		var resp *http.Response
		resp, err = http.Get(url)
		if err != nil {
			return
		}
		defer func() {
			if cerr := resp.Body.Close(); cerr != nil {
				err = cerr
			}
		}()

		progressR := &ioprogress.Reader{
			Reader: resp.Body,
			Size:   resp.ContentLength,
		}
		_, err = io.Copy(out, progressR)
	}
	return
}


Add trace to examples worker1

Add trace to examples worker1

--- examples/workers1.go
+++ examples/workers1.go
@@ -2,6 +2,8 @@

 import (
 	"fmt"
+	"os"
+	"runtime/trace"
 	"sync"
 	"time"
 )
@@ -35,8 +37,10 @@
 }

 func main() {
+	trace.Start(os.Stderr)
 	var wg sync.WaitGroup
 	wg.Add(36)
 	go pool(&wg, 36, 36)
 	wg.Wait()
+	trace.Stop()
 }

<|original_code|>
package main

import (
	"fmt"
	"sync"
	"time"
)

func worker(ch <-chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	for {
		task, ok := <-ch
		if !ok {
			return
		}
		time.Sleep(1 * time.Millisecond)
		fmt.Println("processing task", task)
	}
}

func pool(wg *sync.WaitGroup, workers, tasks int) {
	ch := make(chan int)

	for i := 0; i < workers; i++ {
		time.Sleep(1 * time.Millisecond)
		go worker(ch, wg)
	}

	for i := 0; i < tasks; i++ {
		time.Sleep(10 * time.Millisecond)
		ch <- i
	}

	close(ch)
}

func main() {
	var wg sync.WaitGroup
	wg.Add(36)
	go pool(&wg, 36, 36)
	wg.Wait()
}

<|edits_diff|>
--- examples/workers1.go
+++ examples/workers1.go
@@ -2,6 +2,8 @@

 import (
 	"fmt"
+	"os"
+	"runtime/trace"
 	"sync"
 	"time"
 )
@@ -35,6 +37,7 @@
 }

 func main() {
+	trace.Start(os.Stderr)
 	var wg sync.WaitGroup
 	wg.Add(36)
 	go pool(&wg, 36, 36)
<|current_version|>
package main

import (
	"fmt"
	"os"
	"runtime/trace"
	"sync"
	"time"
)

func worker(ch <-chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	for {
		task, ok := <-ch
		if !ok {
			return
		}
		time.Sleep(1 * time.Millisecond)
		fmt.Println("processing task", task)
	}
}

func pool(wg *sync.WaitGroup, workers, tasks int) {
	ch := make(chan int)

	for i := 0; i < workers; i++ {
		time.Sleep(1 * time.Millisecond)
		go worker(ch, wg)
	}

	for i := 0; i < tasks; i++ {
		time.Sleep(10 * time.Millisecond)
		ch <- i
	}

	close(ch)
}

func main() {
	trace.Start(os.Stderr)
	var wg sync.WaitGroup
	wg.Add(36)
	go pool(&wg, 36, 36)
	wg.Wait()
}

<|next_version|>
package main

import (
	"fmt"
	"os"
	"runtime/trace"
	"sync"
	"time"
)

func worker(ch <-chan int, wg *sync.WaitGroup) {
	defer wg.Done()
	for {
		task, ok := <-ch
		if !ok {
			return
		}
		time.Sleep(1 * time.Millisecond)
		fmt.Println("processing task", task)
	}
}

func pool(wg *sync.WaitGroup, workers, tasks int) {
	ch := make(chan int)

	for i := 0; i < workers; i++ {
		time.Sleep(1 * time.Millisecond)
		go worker(ch, wg)
	}

	for i := 0; i < tasks; i++ {
		time.Sleep(10 * time.Millisecond)
		ch <- i
	}

	close(ch)
}

func main() {
	trace.Start(os.Stderr)
	var wg sync.WaitGroup
	wg.Add(36)
	go pool(&wg, 36, 36)
	wg.Wait()
	trace.Stop()
}