/*
Copyright 2016 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.
*/

// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=k8s.io/kubernetes/federation/apis/federation

package v1beta1 // import "k8s.io/kubernetes/federation/apis/federation/v1beta1"

/*
Copyright 2016 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.
*/

// +k8s:deepcopy-gen=package,register
// +k8s:conversion-gen=k8s.io/kubernetes/federation/apis/federation
// +k8s:openapi-gen=true
package v1beta1 // import "k8s.io/kubernetes/federation/apis/federation/v1beta1"

Add +k8s:openapi-gen tag to API types


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

package main

import (
       "flag"
	"log"
	"syscall"
)

var (
	RO = flag.Bool("r", false, "Read only mount")
	fsType = flag.String("t", "", "File system type")
)

func main() {
	// The need for this conversion is not clear to me, but we get an overflow error
	// on ARM without it.
	flags := uintptr(syscall.MS_MGC_VAL)
	flag.Parse()
	a := flag.Args()
	if len(a) < 2 {
		log.Fatalf("Usage: mount [-r] [-t fstype] dev path")
	}
	dev := a[0]
	path := a[1]
	if *RO {
		flags |= syscall.MS_RDONLY
	}
	if err := syscall.Mount(a[0], a[1], *fsType, uintptr(flags), ""); err != nil {
		log.Fatalf("Mount :%s: on :%s: type :%s: flags %x: %v\n", dev, path, fsType, flags, err)
	}
}

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

import (
	"flag"
	"golang.org/x/sys/unix"
	"log"
)

var (
	RO     = flag.Bool("r", false, "Read only mount")
	fsType = flag.String("t", "", "File system type")
)

func main() {
	// The need for this conversion is not clear to me, but we get an overflow error
	// on ARM without it.
	flags := uintptr(unix.MS_MGC_VAL)
	flag.Parse()
	a := flag.Args()
	if len(a) < 2 {
		log.Fatalf("Usage: mount [-r] [-t fstype] dev path")
	}
	dev := a[0]
	path := a[1]
	if *RO {
		flags |= unix.MS_RDONLY
	}
	if err := unix.Mount(a[0], a[1], *fsType, flags, ""); err != nil {
		log.Fatalf("Mount :%s: on :%s: type :%s: flags %x: %v\n", dev, path, *fsType, flags, err)
	}
}

Use golang.org/x/sys/unix package instead of syscall


package qemuengine

import (
	"fmt"

	"github.com/taskcluster/taskcluster-worker/runtime"
	"github.com/taskcluster/taskcluster-worker/runtime/fetcher"
)

// A fetcher for downloading images.
var imageFetcher = fetcher.Combine(
	// Allow fetching images from URL
	fetcher.URL,
	// Allow fetching images from queue artifacts
	fetcher.Artifact,
	// Allow fetching images from queue referenced by index namespace
	fetcher.Index,
)

type fetchImageContext struct {
	*runtime.TaskContext
}

func (c fetchImageContext) Progress(description string, percent float64) {
	c.Log(fmt.Sprintf("Fetching image: %s - %.0f %%", description, percent*100))
}

package qemuengine

import (
	"fmt"

	"github.com/taskcluster/taskcluster-worker/runtime"
	"github.com/taskcluster/taskcluster-worker/runtime/fetcher"
)

// A fetcher for downloading images.
var imageFetcher = fetcher.Combine(
	// Allow fetching images from URL
	fetcher.URL,
	// Allow fetching images from queue artifacts
	fetcher.Artifact,
	// Allow fetching images from queue referenced by index namespace
	fetcher.Index,
	// Allow fetching images from URL + hash
	fetcher.URLHash,
)

type fetchImageContext struct {
	*runtime.TaskContext
}

func (c fetchImageContext) Progress(description string, percent float64) {
	c.Log(fmt.Sprintf("Fetching image: %s - %.0f %%", description, percent*100))
}

Use URLHash for fetching QEMU images


package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Initializing Octave CPU...")

    file, err := os.Open("hello.bin")

    if err != nil {
        return
    }

    defer file.Close()

    stat, err := file.Stat()

    if err != nil {
        return
    }

    bs := make([]byte, stat.Size())
    _, err = file.Read(bs)

    if err != nil {
        return
    }

    for _, instruction := range bs {
        decode(instruction)
    }
}

func decode(instruction byte) {
    switch instruction >> 5 {
        case 1:
            fmt.Println("MEM")
        case 2:
            fmt.Println("LOADI")
        case 3:
            fmt.Println("STACK")
        case 4:
            fmt.Println("JMP")
        case 5:
            fmt.Println("MATH")
        case 6:
            fmt.Println("LOGIC")
        case 7:
            fmt.Println("IN")
        case 8:
            fmt.Println("OUT")
    }
}

package main

import (
    "fmt"
    "os"
)

func main() {
    fmt.Println("Initializing Octave CPU...")

    file, err := os.Open(os.Args[1])

    if err != nil {
        return
    }

    defer file.Close()

    stat, err := file.Stat()

    if err != nil {
        return
    }

    bs := make([]byte, stat.Size())
    _, err = file.Read(bs)

    if err != nil {
        return
    }

    for _, instruction := range bs {
        decode(instruction)
    }
}

func decode(instruction byte) {
    switch instruction >> 5 {
        case 1:
            fmt.Println("MEM")
        case 2:
            fmt.Println("LOADI")
        case 3:
            fmt.Println("STACK")
        case 4:
            fmt.Println("JMP")
        case 5:
            fmt.Println("MATH")
        case 6:
            fmt.Println("LOGIC")
        case 7:
            fmt.Println("IN")
        case 8:
            fmt.Println("OUT")
    }
}

Read bin from command line arg


package maas

import (
	"launchpad.net/juju-core/environs"
	"launchpad.net/juju-core/environs/config"
	"launchpad.net/juju-core/log"
)

type maasEnvironProvider struct{}

var _ environs.EnvironProvider = (*maasEnvironProvider)(nil)

var providerInstance maasEnvironProvider

func init() {
	environs.RegisterProvider("maas", &providerInstance)
}

func (*maasEnvironProvider) Open(cfg *config.Config) (environs.Environ, error) {
	log.Printf("environs/maas: opening environment %q.", cfg.Name())
	return NewEnviron(cfg)
}

// BoilerplateConfig is specified in the EnvironProvider interface.
func (*maasEnvironProvider) BoilerplateConfig() string {
	panic("Not implemented.")
}

// SecretAttrs is specified in the EnvironProvider interface.
func (*maasEnvironProvider) SecretAttrs(*config.Config) (map[string]interface{}, error) {
	panic("Not implemented.")
}

// PublicAddress is specified in the EnvironProvider interface.
func (*maasEnvironProvider) PublicAddress() (string, error) {
	panic("Not implemented.")
}

// PrivateAddress is specified in the EnvironProvider interface.
func (*maasEnvironProvider) PrivateAddress() (string, error) {
	panic("Not implemented.")
}

// InstanceId is specified in the EnvironProvider interface.
func (*maasEnvironProvider) InstanceId() (state.InstanceId, error) {
	panic("Not implemented.")
}

Add InstanceId, also added to EnvironProvider while we were implementing.


package verstr

import (
	"testing"
)

func TestLess(t *testing.T) {
	var tests = []struct {
		left, right string
		want        bool
	}{
		{"file.0.ext", "file.1.ext", true},
		{"file.1.ext", "file.0.ext", false},
		{"file.1.ext", "file.10.ext", true},
		{"file.10.ext", "file.1.ext", false},
		{"sparse", "sparse.0", true},
		{"sparse.0", "sparse", false},
	}
	for _, test := range tests {
		if got := Less(test.left, test.right); got != test.want {
			t.Errorf("Less(%q, %q) = %v", test.left, test.right, got)
		}
	}
}

package verstr

import (
	"testing"
)

func TestLess(t *testing.T) {
	var tests = []struct {
		left, right string
		want        bool
	}{
		{"file.0.ext", "file.1.ext", true},
		{"file.1.ext", "file.0.ext", false},
		{"file.1.ext", "file.10.ext", true},
		{"file.10.ext", "file.1.ext", false},
		{"file.9.ext", "file.10.ext", true},
		{"file.10.ext", "file.9.ext", false},
		{"sparse", "sparse.0", true},
		{"sparse.0", "sparse", false},
	}
	for _, test := range tests {
		if got := Less(test.left, test.right); got != test.want {
			t.Errorf("Less(%q, %q) = %v", test.left, test.right, got)
		}
	}
}

Add yet another pair to test for lib/verstr.Less().


package handlers

import (
	"encoding/json"
	"net/http"

	"github.com/sirupsen/logrus"

	"github.com/ivan1993spb/snake-server/connections"
)

const URLRouteGetCapacity = "/capacity"

const MethodGetCapacity = http.MethodGet

type responseGetCapacityHandler struct {
	Capacity float32 `json:"capacity"`
}

type getCapacityHandler struct {
	logger       logrus.FieldLogger
	groupManager *connections.ConnectionGroupManager
}

type ErrGetCapacityHandler string

func (e ErrGetCapacityHandler) Error() string {
	return "get capacity handler error: " + string(e)
}

func NewGetCapacityHandler(logger logrus.FieldLogger, groupManager *connections.ConnectionGroupManager) http.Handler {
	return &getCapacityHandler{
		logger:       logger,
		groupManager: groupManager,
	}
}

func (h *getCapacityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json; charset=utf-8")

	err := json.NewEncoder(w).Encode(responseGetCapacityHandler{
		Capacity: h.groupManager.Capacity(),
	})
	if err != nil {
		h.logger.Error(ErrGetGameHandler(err.Error()))
		http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
		return
	}
}

package handlers

import (
	"encoding/json"
	"net/http"

	"github.com/sirupsen/logrus"

	"github.com/ivan1993spb/snake-server/connections"
)

const URLRouteGetCapacity = "/capacity"

const MethodGetCapacity = http.MethodGet

type responseGetCapacityHandler struct {
	Capacity float32 `json:"capacity"`
}

type getCapacityHandler struct {
	logger       logrus.FieldLogger
	groupManager *connections.ConnectionGroupManager
}

type ErrGetCapacityHandler string

func (e ErrGetCapacityHandler) Error() string {
	return "get capacity handler error: " + string(e)
}

func NewGetCapacityHandler(logger logrus.FieldLogger, groupManager *connections.ConnectionGroupManager) http.Handler {
	return &getCapacityHandler{
		logger:       logger,
		groupManager: groupManager,
	}
}

func (h *getCapacityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.Header().Set("X-Content-Type-Options", "nosniff")

	err := json.NewEncoder(w).Encode(responseGetCapacityHandler{
		Capacity: h.groupManager.Capacity(),
	})
	if err != nil {
		h.logger.Error(ErrGetGameHandler(err.Error()))
	}
}

Fix getCapacityHandler: write response status code and add nosniff header


package helpers_test

import (
	"crypto/rand"
	"errors"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotal-cf-experimental/bosh-bootloader/fakes"
	"github.com/pivotal-cf-experimental/bosh-bootloader/helpers"
)

var _ = Describe("EnvIDGenerator", func() {
	Describe("Generate", func() {
		It("generates a env id with a lake and timestamp", func() {
			generator := helpers.NewEnvIDGenerator(rand.Reader)

			envID, err := generator.Generate()
			Expect(err).NotTo(HaveOccurred())
			Expect(envID).To(MatchRegexp(`bbl-env-[a-z]+-\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`))
		})

		Context("when there are errors", func() {
			It("it returns the error", func() {
				anError := errors.New("banana")
				badReader := fakes.Reader{}
				badReader.ReadCall.Returns.Error = anError

				generator := helpers.NewEnvIDGenerator(&badReader)

				_, err := generator.Generate()
				Expect(err).To(Equal(anError))
			})
		})
	})
})

package helpers_test

import (
	"crypto/rand"
	"errors"

	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
	"github.com/pivotal-cf-experimental/bosh-bootloader/fakes"
	"github.com/pivotal-cf-experimental/bosh-bootloader/helpers"
)

var _ = Describe("EnvIDGenerator", func() {
	Describe("Generate", func() {
		It("generates a env id with a lake and timestamp", func() {
			generator := helpers.NewEnvIDGenerator(rand.Reader)

			envID, err := generator.Generate()
			Expect(err).NotTo(HaveOccurred())
			Expect(envID).To(MatchRegexp(`bbl-env-([a-z]+-{1}){1,2}\d{4}-\d{2}-\d{2}T\d{2}:\d{2}Z`))
		})

		Context("when there are errors", func() {
			It("it returns the error", func() {
				anError := errors.New("banana")
				badReader := fakes.Reader{}
				badReader.ReadCall.Returns.Error = anError

				generator := helpers.NewEnvIDGenerator(&badReader)

				_, err := generator.Generate()
				Expect(err).To(Equal(anError))
			})
		})
	})
})

Update env id generator test to handle hypenated lake names


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"
}

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"
}

Support --v and --vmodule silently


package defaults

var (
	PodTestImage        = "rancher/systemd-node:v0.0.2"
	SomeK8sVersion      = "v1.21.1-rc1+k3s1"
	WatchTimeoutSeconds = int64(60 * 10)
	CommonClusterConfig = map[string]interface{}{
		"service-cidr": "10.45.0.0/16",
		"cluster-cidr": "10.44.0.0/16",
		"garbage":      "value",
	}

	One   = int32(1)
	Two   = int32(2)
	Three = int32(3)
)

package defaults

var (
	PodTestImage        = "rancher/systemd-node:v0.0.2"
	SomeK8sVersion      = "v1.21.1+k3s1"
	WatchTimeoutSeconds = int64(60 * 10)
	CommonClusterConfig = map[string]interface{}{
		"service-cidr": "10.45.0.0/16",
		"cluster-cidr": "10.44.0.0/16",
		"garbage":      "value",
	}

	One   = int32(1)
	Two   = int32(2)
	Three = int32(3)
)

Change provisioning tests to use v1.21.1+k3s1


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

package utils

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

	"launchpad.net/juju-core/juju/osenv"
)

// NormalizePath replaces a leading ~ with $HOME, and removes any .. or . path
// elements.
func NormalizePath(dir string) string {
	if strings.HasPrefix(dir, "~/") {
		dir = filepath.Join(osenv.Home(), dir[2:])
	}
	return filepath.Clean(dir)
}

// JoinServerPath joins any number of path elements into a single path, adding
// a path separator (based on the current juju server OS) if necessary. The
// result is Cleaned; in particular, all empty strings are ignored.
func JoinServerPath(elem ...string) string {
	return path.Join(elem...)
}

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

package utils

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

	"launchpad.net/juju-core/juju/osenv"
)

// NormalizePath replaces a leading ~ with $HOME, and removes any .. or . path
// elements.
func NormalizePath(dir string) string {
	if strings.HasPrefix(dir, "~/") {
		dir = filepath.Join(osenv.Home(), dir[2:])
	}
	return filepath.Clean(dir)
}

// JoinServerPath joins any number of path elements into a single path, adding
// a path separator (based on the current juju server OS) if necessary. The
// result is Cleaned; in particular, all empty strings are ignored.
func JoinServerPath(elem ...string) string {
	return path.Join(elem...)
}

// UniqueDirectory returns "path/name" if that directory doesn't exist.  If it
// does, the method starts appending .1, .2, etc until a unique name is found.
func UniqueDirectory(path, name string) (string, error) {
	dir := filepath.Join(path, name)
	_, err := os.Stat(dir)
	if os.IsNotExist(err) {
		return dir, nil
	}
	for i := 1; ; i++ {
		dir := filepath.Join(path, fmt.Sprintf("%s.%d", name, i))
		_, err := os.Stat(dir)
		if os.IsNotExist(err) {
			return dir, nil
		} else if err != nil {
			return "", err
		}
	}
}

Move the UniqueDirectory function into utils package.


// +build linux darwin freebsd

package pb

import (
	"runtime"
	"syscall"
	"unsafe"
)

const (
	TIOCGWINSZ     = 0x5413
	TIOCGWINSZ_OSX = 1074295912
)

func bold(str string) string {
	return "\033[1m" + str + "\033[0m"
}

func terminalWidth() (int, error) {
	w := new(window)
	tio := syscall.TIOCGWINSZ
	if runtime.GOOS == "darwin" {
		tio = TIOCGWINSZ_OSX
	}
	res, _, err := syscall.Syscall(syscall.SYS_IOCTL,
		uintptr(syscall.Stdin),
		uintptr(tio),
		uintptr(unsafe.Pointer(w)),
	)
	if int(res) == -1 {
		return 0, err
	}
	return int(w.Col), nil
}

// +build !windows

package pb

import (
	"runtime"
	"syscall"
	"unsafe"
)

const (
	TIOCGWINSZ     = 0x5413
	TIOCGWINSZ_OSX = 1074295912
)

func bold(str string) string {
	return "\033[1m" + str + "\033[0m"
}

func terminalWidth() (int, error) {
	w := new(window)
	tio := syscall.TIOCGWINSZ
	if runtime.GOOS == "darwin" {
		tio = TIOCGWINSZ_OSX
	}
	res, _, err := syscall.Syscall(syscall.SYS_IOCTL,
		uintptr(syscall.Stdin),
		uintptr(tio),
		uintptr(unsafe.Pointer(w)),
	)
	if int(res) == -1 {
		return 0, err
	}
	return int(w.Col), nil
}

Build for all non-windows platforms


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
}

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
}

Add comments to value object methods


package main

import (
	"database/sql"
	"fmt"
	_ "github.com/lib/pq"
	"log"
	"time"
)

func connectToDatabase() {
	var err error
	driver := "postgres"

	connect := fmt.Sprintf("dbname='%s' user='%s' password='%s' host='%s' port='%s' sslmode='%s' connect_timeout='%s'",
		SomaCfg.Database.Name,
		SomaCfg.Database.User,
		SomaCfg.Database.Pass,
		SomaCfg.Database.Host,
		SomaCfg.Database.Port,
		SomaCfg.TlsMode,
		SomaCfg.Timeout,
	)

	conn, err = sql.Open(driver, connect)
	if err != nil {
		log.Fatal(err)
	}
	log.Print("Connected to database")
}

func pingDatabase() {
	ticker := time.NewTicker(time.Second).C

	for {
		<-ticker
		err := conn.Ping()
		if err != nil {
			log.Print(err)
		}
	}
}

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

package main

import (
	"database/sql"
	"fmt"
	_ "github.com/lib/pq"
	"log"
	"time"
)

func connectToDatabase() {
	var err error
	driver := "postgres"

	connect := fmt.Sprintf("dbname='%s' user='%s' password='%s' host='%s' port='%s' sslmode='%s' connect_timeout='%s'",
		SomaCfg.Database.Name,
		SomaCfg.Database.User,
		SomaCfg.Database.Pass,
		SomaCfg.Database.Host,
		SomaCfg.Database.Port,
		SomaCfg.TlsMode,
		SomaCfg.Timeout,
	)

	conn, err = sql.Open(driver, connect)
	if err != nil {
		log.Fatal(err)
	}
	log.Print("Connected to database")
	conn.Exec(`SET TIME ZONE 'UTC';`)
}

func pingDatabase() {
	ticker := time.NewTicker(time.Second).C

	for {
		<-ticker
		err := conn.Ping()
		if err != nil {
			log.Print(err)
		}
	}
}

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

Set database session to UTC


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

package id3v2

import (
	"io"

	"github.com/bogem/id3v2/util"
)

// UnknownFrame is used for frames, which id3v2 so far doesn't know how to
// parse and write it. It just contains an unparsed byte body of the frame.
type UnknownFrame struct {
	Body []byte
}

func (uk UnknownFrame) Size() int {
	return len(uk.Body)
}

func (uk UnknownFrame) WriteTo(w io.Writer) (n int64, err error) {
	var i int
	i, err = w.Write(uk.Body)
	return int64(i), err
}

func parseUnknownFrame(rd io.Reader) (Framer, error) {
	body, err := util.ReadAll(rd)
	return UnknownFrame{Body: body}, err
}

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

package id3v2

import (
	"io"

	"github.com/bogem/id3v2/util"
)

// UnknownFrame is used for frames, which id3v2 so far doesn't know how to
// parse and write it. It just contains an unparsed byte body of the frame.
type UnknownFrame struct {
	Body []byte
}

func (uf UnknownFrame) Size() int {
	return len(uf.Body)
}

func (uf UnknownFrame) WriteTo(w io.Writer) (n int64, err error) {
	var i int
	i, err = w.Write(uf.Body)
	return int64(i), err
}

func parseUnknownFrame(rd io.Reader) (Framer, error) {
	body, err := util.ReadAll(rd)
	return UnknownFrame{Body: body}, err
}

Rename uk to uf in UnknownFrame


package renderer_test

import (
	"testing"

	"github.com/diyan/assimilator/testutil/fixture"
	"github.com/stretchr/testify/assert"
)

func TestServerSideTemplateRenderer_Get(t *testing.T) {
	client, factory := fixture.Setup(t)
	defer fixture.TearDown(t)

	factory.SaveOrganization(factory.MakeOrganization())

	res, bodyStr, errs := client.Get("http://example.com//acme-team/").End()
	assert.Nil(t, errs)
	assert.Equal(t, 200, res.StatusCode)
	assert.Contains(t, res.Header.Get("Content-Type"), "text/html")
	assert.Contains(t, bodyStr, "<title>Sentry</title>", "Title should be rendered from sentry/layout.html template")
	assert.Contains(t, bodyStr, "Sentry.routes", "React routes should be rendered from sentry/bases/react.html")
	assert.InDelta(t, 3000, res.ContentLength, 1000, "server-side rendered page should be ~3KB in size")
}

package renderer_test

import (
	"testing"

	"github.com/diyan/assimilator/testutil/fixture"
	"github.com/stretchr/testify/assert"
)

func TestServerSideRenderer_Get(t *testing.T) {
	client, factory := fixture.Setup(t)
	defer fixture.TearDown(t)

	factory.SaveOrganization(factory.MakeOrganization())

	res, bodyStr, errs := client.Get("http://example.com/acme-team/").End()
	assert.Nil(t, errs)
	assert.Equal(t, 200, res.StatusCode)
	assert.Contains(t, res.Header.Get("Content-Type"), "text/html")
	assert.Contains(t, bodyStr, "<title>Sentry</title>", "Title should be rendered from sentry/layout.html template")
	assert.Contains(t, bodyStr, "Sentry.routes", "React routes should be rendered from sentry/bases/react.html")
	assert.InDelta(t, 3000, res.ContentLength, 1000, "server-side rendered page should be ~3KB in size")
}

Fix typo in renderer test


package main

import (
  "encoding/json"
  "fmt"
  "github.com/gwwfps/lolconf-probe/display"
  "github.com/natefinch/npipe"
  "log"
  "net/http"
)

type handler func(http.ResponseWriter, *http.Request)
type inner func() (interface{}, error)

func wrapHandler(h inner) handler {
  return func(w http.ResponseWriter, r *http.Request) {
    result, handlerError := h()
    if handlerError != nil {
      writeError(w, handlerError)
      return
    }

    serialized, marshalError := json.Marshal(result)
    if marshalError != nil {
      writeError(w, marshalError)
      return
    }

    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    fmt.Fprint(w, string(serialized))
  }
}

func writeError(w http.ResponseWriter, e error) {
  w.WriteHeader(http.StatusInternalServerError)
  fmt.Fprint(w, e.Error())
}

func main() {
  http.HandleFunc("/resolutions", wrapHandler(display.ListAvailableResolutions))
  l, e := npipe.Listen(`\\.\pipe\lolconf`)
  if e != nil {
    log.Fatal("Error listening on pipe: ", e)
  }
  serveError := http.Serve(l, nil)
  if serveError != nil {
    log.Fatal("Http serve error: ", serveError)
  }
}

package main

import (
  "encoding/json"
  "fmt"
  "github.com/gwwfps/lolconf-probe/display"
  "log"
  "net/http"
)

type handler func(http.ResponseWriter, *http.Request)
type inner func() (interface{}, error)

func wrapHandler(h inner) handler {
  return func(w http.ResponseWriter, r *http.Request) {
    result, handlerError := h()
    if handlerError != nil {
      writeError(w, handlerError)
      return
    }

    serialized, marshalError := json.Marshal(result)
    if marshalError != nil {
      writeError(w, marshalError)
      return
    }

    w.Header().Set("Content-Type", "application/json; charset=utf-8")
    fmt.Fprint(w, string(serialized))
  }
}

func writeError(w http.ResponseWriter, e error) {
  w.WriteHeader(http.StatusInternalServerError)
  fmt.Fprint(w, e.Error())
}

func main() {
  http.HandleFunc("/resolutions", wrapHandler(display.ListAvailableResolutions))
  e := http.ListenAndServe("127.0.0.1:5532", nil)
  if e != nil {
    log.Fatal("ListenAndServe: ", e)
  }
}

Revert "switched to using npipe instead of socket"


package router

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

func testRequest(targetUrl string, expectedResponse string) {
	resp, err := http.Get(targetUrl)
	if (err != nil) {
		log.Panic("failed make get request")
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if (err != nil) {
		log.Panic("failed to read response")
	}

	bodyStr := string(body)
	log.Printf("Server responded with %v", bodyStr)
	if (bodyStr != expectedResponse) {
		log.Panic("Unexpected response")
	}
}

package router

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

func testRequest(targetUrl string, expectedResponse string) {
	resp, err := http.Get(targetUrl)
	if (err != nil) {
		log.Panicf("failed to make get request: %v", err)
	}
	defer resp.Body.Close()

	if (resp.StatusCode != 200) {
		log.Panicf("response status: %v", resp.StatusCode)
	}

	body, err := ioutil.ReadAll(resp.Body)
	if (err != nil) {
		log.Panic("failed to read response")
	}

	bodyStr := string(body)
	log.Printf("Server responded with %v", bodyStr)
	if (bodyStr != expectedResponse) {
		log.Panic("Unexpected response")
	}
}

Verify request success while testing http requests


// +build !linux !cgo !seccomp

package patchbpf

import (
	"errors"

	"github.com/opencontainers/runc/libcontainer/configs"

	libseccomp "github.com/seccomp/libseccomp-golang"
)

func PatchAndLoad(config *configs.Seccomp, filter *libseccomp.ScmpFilter) error {
	if config != nil {
		return errors.New("cannot patch and load seccomp filter without runc seccomp support")
	}
	return nil
}

Remove "PatchAndLoad" stub as it's not used without seccomp enabled


package sh

import "testing"

func TestFunctionsClosures(t *testing.T) {
	for _, test := range []execTestCase{
		{
			desc: "simpleClosure",
			execStr: `
				fn func(a) {
					fn closure() {
						print($a)
					}
					return $closure
				}

				x <= func("1")
				y <= func("2")
				$x()
				$y()
			`,
			expectedStdout: "12",
		},
		//{
		//desc: "closuresSharingState",
		//execStr: `
		//fn func() {
		//a = ()
		//fn add(elem) {
		//a <= append($a, $elem)
		//}
		//fn dump() {
		//print($a)
		//}
		//return $add, $dump
		//}

		//add, dump <= func()
		//$add("1")
		//$add("3")
		//$dump()
		//`,
		//expectedStdout: "1 3",
		//},
	} {
		t.Run(test.desc, func(t *testing.T) {
			testExec(t, test)
		})
	}
}

package sh

import "testing"

func TestFunctionsClosures(t *testing.T) {
	for _, test := range []execTestCase{
		{
			desc: "simpleClosure",
			execStr: `
				fn func(a) {
					fn closure() {
						print($a)
					}
					return $closure
				}

				x <= func("1")
				y <= func("2")
				$x()
				$y()
			`,
			expectedStdout: "12",
		},
		{
			desc: "closuresSharingState",
			execStr: `
				fn func() {
					a = ()
					fn add(elem) {
						a <= append($a, $elem)
					}
					fn view() {
						print($a)
					}
					return $add, $view
				}

				add, view <= func()
				$add("1")
				$add("3")
				$view()
			`,
			expectedStdout: "1 3",
		},
	} {
		t.Run(test.desc, func(t *testing.T) {
			testExec(t, test)
		})
	}
}

Add closures with shared state example


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

package hugolib

import (
	"testing"

	"github.com/spf13/hugo/tpl/tplimpl"
)

const (
	win_base = "c:\\a\\windows\\path\\layout"
	win_path = "c:\\a\\windows\\path\\layout\\sub1\\index.html"
)

func TestTemplatePathSeparator(t *testing.T) {
	t.Parallel()
	tmpl := new(tpl.GoHTMLTemplate)
	if name := tplimpl.GenerateTemplateNameFrom(win_base, win_path); name != "sub1/index.html" {
		t.Fatalf("Template name incorrect. got %s but expected %s", name, "sub1/index.html")
	}
}

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

package hugolib

import (
	"testing"

	"github.com/spf13/hugo/tpl/tplimpl"
)

const (
	win_base = "c:\\a\\windows\\path\\layout"
	win_path = "c:\\a\\windows\\path\\layout\\sub1\\index.html"
)

func TestTemplatePathSeparator(t *testing.T) {
	t.Parallel()
	tmpl := new(tplimpl.GoHTMLTemplate)
	if name := tplimpl.GenerateTemplateNameFrom(win_base, win_path); name != "sub1/index.html" {
		t.Fatalf("Template name incorrect. got %s but expected %s", name, "sub1/index.html")
	}
}

Fix Windows build failure, take 2


package uniq

import "sort"

type Interface sort.Interface

func Ue(data Interface) int {
	len := data.Len()
	i, j := 0, 1
	// find the first duplicate
	for j < len && data.Less(i, j) {
		i++
		j++
	}
	// this loop is simpler after the first duplicate is found
	for ; j < len; j++ {
		if data.Less(i, j) {
			i++
			data.Swap(i, j)
		}
	}
	return i + 1
}

package uniq

import "sort"

type Interface sort.Interface

func Ue(data Interface) int {
	len := data.Len()
	if len == 0 {
		return 0
	}
	i, j := 0, 1
	// find the first duplicate
	for j < len && data.Less(i, j) {
		i++
		j++
	}
	// this loop is simpler after the first duplicate is found
	for ; j < len; j++ {
		if data.Less(i, j) {
			i++
			data.Swap(i, j)
		}
	}
	return i + 1
}

Fix Len() == 0 bug


package ehttp

import (
	"net/http"
	"sync/atomic"
)

// ResponseWriter wraps http.ResponseWriter and holds
// a flag to know if the headers have been sent as well has
// the http code sent.
type ResponseWriter struct {
	http.ResponseWriter
	code *int32
}

// NewResponseWriter instantiates a new ehttp ResponseWriter.
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter {
	return &ResponseWriter{
		ResponseWriter: w,
		code:           new(int32),
	}
}

// Code return the http code stored in the response writer.
func (w ResponseWriter) Code() int {
	return int(atomic.LoadInt32(w.code))
}

// WriteHeader wraps underlying WriteHeader
// - flag that the headers have been sent
// - store the sent code
func (w *ResponseWriter) WriteHeader(code int) {
	atomic.CompareAndSwapInt32(w.code, 0, int32(code))
	w.ResponseWriter.WriteHeader(code)
}

// Write wraps the underlying Write and flag that the headers have been sent.
func (w *ResponseWriter) Write(buf []byte) (int, error) {
	atomic.CompareAndSwapInt32(w.code, 0, int32(http.StatusOK))
	return w.ResponseWriter.Write(buf)
}

package ehttp

import (
	"bufio"
	"fmt"
	"net"
	"net/http"
	"sync/atomic"
)

// ResponseWriter wraps http.ResponseWriter and holds
// a flag to know if the headers have been sent as well has
// the http code sent.
type ResponseWriter struct {
	http.ResponseWriter
	code *int32
}

// NewResponseWriter instantiates a new ehttp ResponseWriter.
func NewResponseWriter(w http.ResponseWriter) *ResponseWriter {
	return &ResponseWriter{
		ResponseWriter: w,
		code:           new(int32),
	}
}

// Code return the http code stored in the response writer.
func (w ResponseWriter) Code() int {
	return int(atomic.LoadInt32(w.code))
}

// WriteHeader wraps underlying WriteHeader
// - flag that the headers have been sent
// - store the sent code
func (w *ResponseWriter) WriteHeader(code int) {
	atomic.CompareAndSwapInt32(w.code, 0, int32(code))
	w.ResponseWriter.WriteHeader(code)
}

// Write wraps the underlying Write and flag that the headers have been sent.
func (w *ResponseWriter) Write(buf []byte) (int, error) {
	atomic.CompareAndSwapInt32(w.code, 0, int32(http.StatusOK))
	return w.ResponseWriter.Write(buf)
}

// Hijack wraps the underlying Hijack if available.
func (w *ResponseWriter) Hijack() (net.Conn, *bufio.ReadWriter, error) {
	hijacker, ok := w.ResponseWriter.(http.Hijacker)
	if !ok {
		return nil, nil, fmt.Errorf("not a hijacker")
	}
	return hijacker.Hijack()
}

Add better support for hijack


package api

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

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

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

package api

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

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

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

Allow API to return health response when in a custom state


package isolated

import (
	helpers "code.cloudfoundry.org/cli/integration/helpers"
	"code.cloudfoundry.org/cli/util/configv3"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Config", func() {
	Describe("Version Management", func() {
		var oldConfig *configv3.Config

		BeforeEach(func() {
			oldConfig = helpers.GetConfig()
		})
		AfterEach(func() {
			helpers.SetConfig(func(config *configv3.Config) {
				config.ConfigFile = oldConfig.ConfigFile
			})
		})

		It("reset config to default if version mismatch", func() {
			helpers.SetConfig(func(config *configv3.Config) {
				config.ConfigFile.ConfigVersion = configv3.CurrentConfigVersion - 1
				config.ConfigFile.Target = "api.my-target"
			})
			helpers.LoginCF()
			config := helpers.GetConfig()
			Expect(config.ConfigFile.ConfigVersion).To(Equal(configv3.CurrentConfigVersion))
			Expect(config.ConfigFile.Target).To(Equal(""))
		})
	})
})

package isolated

import (
	helpers "code.cloudfoundry.org/cli/integration/helpers"
	"code.cloudfoundry.org/cli/util/configv3"
	. "github.com/onsi/ginkgo"
	. "github.com/onsi/gomega"
)

var _ = Describe("Config", func() {
	Describe("Version Management", func() {
		var oldTarget string
		var oldVersion int

		BeforeEach(func() {
			config := helpers.GetConfig()
			oldTarget = config.Target()
			oldVersion = config.ConfigFile.ConfigVersion
		})
		AfterEach(func() {
			helpers.SetConfig(func(config *configv3.Config) {
				config.ConfigFile.ConfigVersion = oldVersion
				config.ConfigFile.Target = oldTarget
			})
		})

		It("reset config to default if version mismatch", func() {
			helpers.SetConfig(func(config *configv3.Config) {
				config.ConfigFile.ConfigVersion = configv3.CurrentConfigVersion - 1
				config.ConfigFile.Target = "api.my-target"
			})
			helpers.LoginCF()
			config := helpers.GetConfig()
			Expect(config.ConfigFile.ConfigVersion).To(Equal(configv3.CurrentConfigVersion))
			Expect(config.ConfigFile.Target).To(Equal(""))
		})
	})
})

Clear config on configVersion change:


package lib

import "testing"

func TestReverse(t *testing.T) {
	var got, expect string
	got = Reverse("asdf")
	expect = "fdsa"
	if got != expect {
		t.Error("Expected ", expect, ", got ", got)
	}
}

package lib

import (
	"fmt"
	"testing"
)

func TestReverse(t *testing.T) {
	m := map[string]string{
		"asdf":        "fdsa",
		"vU _!12 ?3P": "P3? 21!_ Uv",
		"":            "",
	}
	for in, out := range m {
		got := Reverse(in)
		if got != out {
			t.Error("fn(", in, ") =>", got, "!=", out)
		} else {
			fmt.Println("PASS: fn(", in, ") =>", got, "==", out)
		}
	}

}

Update test code for example


package cf_http

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

var config Config

type Config struct {
	Timeout time.Duration
}

func Initialize(timeout time.Duration) {
	config.Timeout = timeout
}

func NewClient() *http.Client {
	return newClient(5*time.Second, 0*time.Second, config.Timeout)
}

func NewStreamingClient() *http.Client {
	return newClient(5*time.Second, 30*time.Second, 0*time.Second)
}

func newClient(dialTimeout, keepAliveTimeout, timeout time.Duration) *http.Client {
	return &http.Client{
		Transport: &http.Transport{
			Dial: (&net.Dialer{
				Timeout:   dialTimeout,
				KeepAlive: keepAliveTimeout,
			}).Dial,
		},
		Timeout: timeout,
	}
}

package cf_http

import (
	"crypto/tls"
	"crypto/x509"
	"errors"
	"io/ioutil"
	"net"
	"net/http"
	"time"
)

var config Config

type Config struct {
	Timeout time.Duration
}

func Initialize(timeout time.Duration) {
	config.Timeout = timeout
}

func NewClient() *http.Client {
	return newClient(5*time.Second, 0*time.Second, config.Timeout)
}

func NewStreamingClient() *http.Client {
	return newClient(5*time.Second, 30*time.Second, 0*time.Second)
}

func newClient(dialTimeout, keepAliveTimeout, timeout time.Duration) *http.Client {
	return &http.Client{
		Transport: &http.Transport{
			Dial: (&net.Dialer{
				Timeout:   dialTimeout,
				KeepAlive: keepAliveTimeout,
			}).Dial,
		},
		Timeout: timeout,
	}
}

func NewTLSConfig(certFile, keyFile, caCertFile string) (*tls.Config, error) {
	tlsCert, err := tls.LoadX509KeyPair(certFile, keyFile)
	if err != nil {
		return nil, err
	}

	tlsConfig := &tls.Config{
		Certificates:       []tls.Certificate{tlsCert},
		InsecureSkipVerify: false,
	}

	certBytes, err := ioutil.ReadFile(caCertFile)
	if err != nil {
		return nil, err
	}

	if caCertFile != "" {
		caCertPool := x509.NewCertPool()
		if ok := caCertPool.AppendCertsFromPEM(certBytes); !ok {
			return nil, errors.New("Unable to load caCert")
		}
		tlsConfig.RootCAs = caCertPool
	}

	return tlsConfig, nil
}

Add support to generate TLS config


package setup

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/mholt/caddy/config/parse"
	"github.com/mholt/caddy/middleware"
	"github.com/mholt/caddy/server"
)

// NewTestController creates a new *Controller for
// the input specified, with a filename of "Testfile"
func NewTestController(input string) *Controller {
	return &Controller{
		Config:    &server.Config{},
		Dispenser: parse.NewDispenser("Testfile", strings.NewReader(input)),
	}
}

// EmptyNext is a no-op function that can be passed into
// middleware.Middleware functions so that the assignment
// to the Next field of the Handler can be tested.
var EmptyNext = middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
	return 0, nil
})

// SameNext does a pointer comparison between next1 and next2.
func SameNext(next1, next2 middleware.Handler) bool {
	return fmt.Sprintf("%p", next1) == fmt.Sprintf("%p", next2)
}

package setup

import (
	"fmt"
	"net/http"
	"strings"

	"github.com/mholt/caddy/config/parse"
	"github.com/mholt/caddy/middleware"
	"github.com/mholt/caddy/server"
)

// NewTestController creates a new *Controller for
// the input specified, with a filename of "Testfile"
func NewTestController(input string) *Controller {
	return &Controller{
		Config:    &server.Config{},
		Dispenser: parse.NewDispenser("Testfile", strings.NewReader(input)),
	}
}

// EmptyNext is a no-op function that can be passed into
// middleware.Middleware functions so that the assignment
// to the Next field of the Handler can be tested.
var EmptyNext = middleware.HandlerFunc(func(w http.ResponseWriter, r *http.Request) (int, error) {
	return 0, nil
})

// SameNext does a pointer comparison between next1 and next2.
func SameNext(next1, next2 middleware.Handler) bool {
	return fmt.Sprintf("%v", next1) == fmt.Sprintf("%v", next2)
}

Use %v instead of %p to calm vet


package main

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

type Result struct {
	Domain       string
	Availability string
}

type SearchResults struct {
	Query   string
	Results []Result
}

func main() {

	if len(os.Args) < 2 {
		log.Fatal("Missing search query. Specify a string to search domainr for.")
	}

	var query string = os.Args[1]

	httpResponse, _ := http.Get("https://domai.nr/api/json/search?client_id=domainr_command_line_app&q=" + query)

	defer httpResponse.Body.Close()
	body, _ := ioutil.ReadAll(httpResponse.Body)

	var sr SearchResults

	// Decode json string into custom structs.
	json.Unmarshal(body, &sr)

	// Print results to stdout
	fmt.Printf("\n Results for \"%s\"\n\n", sr.Query)
	for _, result := range sr.Results {
		var available string
		switch result.Availability {
		case "available":
			available = "✔"
		default:
			available = "✘"
		}
		fmt.Printf("     %s %s\n", available, result.Domain)
	}
	fmt.Printf("\n")
}

package main

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

const (
	apiURL = "https://domai.nr/api/json/search?client_id=domainr_command_line_app&q="
)

type Result struct {
	Domain       string
	Availability string
}

type SearchResults struct {
	Query   string
	Results []Result
}

func main() {

	if len(os.Args) < 2 {
		fmt.Println("Missing search query. Specify a string to search domainr for.")
		os.Exit(1)
	}

	var query string = os.Args[1]

	httpResponse, err := http.Get(apiURL + query)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	defer httpResponse.Body.Close()
	body, err := ioutil.ReadAll(httpResponse.Body)
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	var sr SearchResults

	// Decode json string into custom structs.
	json.Unmarshal(body, &sr)

	// Print results to stdout
	fmt.Printf("\n Results for \"%s\"\n\n", sr.Query)
	for _, result := range sr.Results {
		var available string
		switch result.Availability {
		case "available":
			available = "✔"
		default:
			available = "✘"
		}
		fmt.Printf("     %s %s\n", available, result.Domain)
	}
	fmt.Printf("\n")
}

Print and exit on error.


package router

import (
	"github.com/micro/go-micro/v2/api/resolver"
	"github.com/micro/go-micro/v2/registry"
)

type Options struct {
	Handler  string
	Registry registry.Registry
	Resolver resolver.Resolver
}

type Option func(o *Options)

func NewOptions(opts ...Option) Options {
	options := Options{
		Handler:  "meta",
		Registry: registry.DefaultRegistry,
	}

	for _, o := range opts {
		o(&options)
	}

	return options
}

func WithHandler(h string) Option {
	return func(o *Options) {
		o.Handler = h
	}
}

func WithRegistry(r registry.Registry) Option {
	return func(o *Options) {
		o.Registry = r
	}
}

func WithResolver(r resolver.Resolver) Option {
	return func(o *Options) {
		o.Resolver = r
	}
}

package router

import (
	"github.com/micro/go-micro/v2/api/resolver"
	"github.com/micro/go-micro/v2/api/resolver/vpath"
	"github.com/micro/go-micro/v2/registry"
)

type Options struct {
	Handler  string
	Registry registry.Registry
	Resolver resolver.Resolver
}

type Option func(o *Options)

func NewOptions(opts ...Option) Options {
	options := Options{
		Handler:  "meta",
		Registry: registry.DefaultRegistry,
	}

	for _, o := range opts {
		o(&options)
	}

	if options.Resolver == nil {
		options.Resolver = vpath.NewResolver(
			resolver.WithHandler(options.Handler),
		)
	}

	return options
}

func WithHandler(h string) Option {
	return func(o *Options) {
		o.Handler = h
	}
}

func WithRegistry(r registry.Registry) Option {
	return func(o *Options) {
		o.Registry = r
	}
}

func WithResolver(r resolver.Resolver) Option {
	return func(o *Options) {
		o.Resolver = r
	}
}

Add default resolver to api router


package polynomial

import (
	"fmt"
	"math/big"
	"strings"
)

type Point struct {
	x, y *big.Int
}

type Points []Point

func (p Point) String() string {
	return fmt.Sprintf("(%v, %v)", p.x, p.y)
}

func (ps Points) String() string {
	strs := make([]string, len(ps))
	for i, p := range ps {
		strs[i] = fmt.Sprintf("Point #%v %v", i+1, p)
	}
	return strings.Join(strs, "\n")
}

package polynomial

import (
	"fmt"
	"math/big"
	"strings"
)

// Point type represents a coordinate (x, y) where x and y are big integers
type Point struct {
	x, y *big.Int
}

// Points type represents a set of Point type
type Points []Point

func (p Point) String() string {
	return fmt.Sprintf("(%v, %v)", p.x, p.y)
}

func (ps Points) String() string {
	strs := make([]string, len(ps))
	for i, p := range ps {
		strs[i] = fmt.Sprintf("Point #%v %v", i+1, p)
	}
	return strings.Join(strs, "\n")
}

Add comments for type Point & Points


// Copyright © 2009--2013 The Web.go Authors
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package web

import (
	"encoding/json"
	"encoding/xml"
	"io"
)

// Encode arbitrary data to a response
type Encoder interface {
	Encode(data interface{}) error
}

type MimeEncoder func(w io.Writer) Encoder

var encoders = map[string]MimeEncoder{
	"application/json": encodeJSON,
	"application/xml":  encodeXML,
	"text/xml":         encodeXML,
}

// Register a new mimetype and how it should be encoded
func RegisterMimeParser(mimetype string, enc MimeEncoder) {
	encoders[mimetype] = enc
}

func encodeJSON(w io.Writer) Encoder {
	return Encoder(json.NewEncoder(w))
}

func encodeXML(w io.Writer) Encoder {
	return Encoder(xml.NewEncoder(w))
}

// Copyright © 2009--2013 The Web.go Authors
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.

package web

import (
	"encoding/json"
	"encoding/xml"
	"io"
)

// Encode arbitrary data to a response
type Encoder interface {
	Encode(data interface{}) error
}

type MimeEncoder func(w io.Writer) Encoder

var encoders = map[string]MimeEncoder{
	"application/json": encodeJSON,
	"application/xml":  encodeXML,
	"text/xml":         encodeXML,
}

// Register a new mimetype and how it should be encoded
func RegisterMimeEncoder(mimetype string, enc MimeEncoder) {
	encoders[mimetype] = enc
}

func encodeJSON(w io.Writer) Encoder {
	return Encoder(json.NewEncoder(w))
}

func encodeXML(w io.Writer) Encoder {
	return Encoder(xml.NewEncoder(w))
}

Fix name of register mime encoder function


package extension

import (
	"fmt"
	"github.com/kayex/sirius"
	"golang.org/x/net/context"
	"googlemaps.github.io/maps"
)

type Geocode struct {
	APIKey string
}

func (x *Geocode) Run(m sirius.Message, cfg sirius.ExtensionConfig) (sirius.MessageAction, error) {
	cmd, match := m.Command("geocode")

	if !match {
		return sirius.NoAction(), nil
	}

	c, err := maps.NewClient(maps.WithAPIKey(x.APIKey))

	if err != nil {
		return nil, err
	}

	r := &maps.GeocodingRequest{
		Address: cmd.Args[0],
	}

	res, err := c.Geocode(context.Background(), r)

	if err != nil {
		return nil, err
	}

	pos := res[0]
	location := pos.Geometry.Location
	formatted := fmt.Sprintf("*%v*\n`(%.6f, %.6f)`", pos.FormattedAddress, location.Lat, location.Lng)

	edit := m.EditText().ReplaceWith(formatted)

	return edit, nil
}

package extension

import (
	"fmt"
	"github.com/kayex/sirius"
	"golang.org/x/net/context"
	"googlemaps.github.io/maps"
)

type Geocode struct {
	APIKey string
}

func (x *Geocode) Run(m sirius.Message, cfg sirius.ExtensionConfig) (sirius.MessageAction, error) {
	cmd, match := m.Command("address")

	if !match {
		return sirius.NoAction(), nil
	}

	c, err := maps.NewClient(maps.WithAPIKey(x.APIKey))

	if err != nil {
		return nil, err
	}

	r := &maps.GeocodingRequest{
		Address: cmd.Args[0],
	}

	res, err := c.Geocode(context.Background(), r)

	if err != nil {
		return nil, err
	}

	pos := res[0]
	location := pos.Geometry.Location
	formatted := fmt.Sprintf("*%v*\n`(%.6f, %.6f)`", pos.FormattedAddress, location.Lat, location.Lng)

	edit := m.EditText().ReplaceWith(formatted)

	return edit, nil
}

Change back extension command name


// Copyright © 2009-2010 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package gospec

import (
	"fmt"
	filepath "path"
	"runtime"
)

type Location struct {
	File string
	Line int
}

func currentLocation() *Location {
	return newLocation(1)
}

func callerLocation() *Location {
	return newLocation(2)
}

func newLocation(n int) *Location {
	if _, file, line, ok := runtime.Caller(n + 1); ok {
		return &Location{filename(file), line}
	}
	return nil
}

func filename(path string) string {
	_, file := filepath.Split(path)
	return file
}

func (this *Location) equals(that *Location) bool {
	return this.File == that.File &&
	       this.Line == that.Line
}

func (this *Location) String() string {
	if this == nil {
		return "Unknown File"
	}
	return fmt.Sprintf("%v:%v", this.File, this.Line)
}

// Copyright © 2009-2010 Esko Luontola <www.orfjackal.net>
// This software is released under the Apache License 2.0.
// The license text is at http://www.apache.org/licenses/LICENSE-2.0

package gospec

import (
	"fmt"
	filepath "path"
	"runtime"
)

type Location struct {
	File string
	Line int
}

func currentLocation() *Location {
	return newLocation(1)
}

func callerLocation() *Location {
	return newLocation(2)
}

func newLocation(n int) *Location {
	if _, file, line, ok := runtime.Caller(n + 2); ok { // TODO: is the change from n+1 to n+2 a bug in runtime.Caller or not?
		return &Location{filename(file), line}
	}
	return nil
}

func filename(path string) string {
	_, file := filepath.Split(path)
	return file
}

func (this *Location) equals(that *Location) bool {
	return this.File == that.File &&
	       this.Line == that.Line
}

func (this *Location) String() string {
	if this == nil {
		return "Unknown File"
	}
	return fmt.Sprintf("%v:%v", this.File, this.Line)
}

Fix bug in runtime.Caller() introduced by release.2010-03-30


package main

import (
	"fmt"

	"github.com/urfave/cli"
)

var (
	rmiDescription = "Removes one or more locally stored images."
	rmiCommand     = cli.Command{
		Name:        "rmi",
		Usage:       "Removes one or more images from local storage",
		Description: rmiDescription,
		Action:      rmiCmd,
		ArgsUsage:   "IMAGE-NAME-OR-ID [...]",
	}
)

func rmiCmd(c *cli.Context) error {
	args := c.Args()
	if len(args) == 0 {
		return fmt.Errorf("container ID must be specified")
	}

	store, err := getStore(c)
	if err != nil {
		return err
	}

	for _, id := range args {
		_, err := store.DeleteImage(id, true)
		if err != nil {
			return fmt.Errorf("error removing image %q: %v", id, err)
		}
		fmt.Printf("%s\n", id)
	}

	return nil
}

package main

import (
	"fmt"

	"github.com/urfave/cli"
)

var (
	rmiDescription = "Removes one or more locally stored images."
	rmiCommand     = cli.Command{
		Name:        "rmi",
		Usage:       "Removes one or more images from local storage",
		Description: rmiDescription,
		Action:      rmiCmd,
		ArgsUsage:   "IMAGE-NAME-OR-ID [...]",
	}
)

func rmiCmd(c *cli.Context) error {
	args := c.Args()
	if len(args) == 0 {
		return fmt.Errorf("image ID must be specified")
	}

	store, err := getStore(c)
	if err != nil {
		return err
	}

	for _, id := range args {
		_, err := store.DeleteImage(id, true)
		if err != nil {
			return fmt.Errorf("error removing image %q: %v", id, err)
		}
		fmt.Printf("%s\n", id)
	}

	return nil
}

Fix copy and paste error on container-image


package main

import (
	"flag"

	"github.com/sirupsen/logrus"
)

var (
	configPath string
)

func init() {
	flag.StringVar(
		&configPath,
		"config",
		"config.toml",
		"path to configuration file; supported formats are JSON, YAML, and TOML",
	)
	flag.Parse()
}

func main() {
	v, err := parseConfig(configPath)
	if err != nil {
		logrus.Fatalf("could not parse config file (%s): %s", configPath, err)
	}
	s, err := setupGRPCServer(v)
	if err != nil {
		logrus.Fatalf("failed to initialize GRPC server: %s", err)
	}
	l, err := setupNetListener(v)
	if err != nil {
		logrus.Fatalf("failed to create net.Listener: %s", err)
	}
	logrus.Infof("attempting to start server on: %s", l.Addr().String())
	if err := s.Serve(l); err != nil {
		logrus.Fatalf("server shut down due to error: %s", err)
	}
	logrus.Info("server shutting down cleanly")
}

package main

import (
	"flag"

	"github.com/sirupsen/logrus"
)

var (
	configPath string
)

func init() {
	flag.StringVar(
		&configPath,
		"config",
		"config.toml",
		"path to configuration file; supported formats are JSON, YAML, and TOML",
	)
}

func main() {
	flag.Parse()
	v, err := parseConfig(configPath)
	if err != nil {
		logrus.Fatalf("could not parse config file (%s): %s", configPath, err)
	}
	s, err := setupGRPCServer(v)
	if err != nil {
		logrus.Fatalf("failed to initialize GRPC server: %s", err)
	}
	l, err := setupNetListener(v)
	if err != nil {
		logrus.Fatalf("failed to create net.Listener: %s", err)
	}
	logrus.Infof("attempting to start server on: %s", l.Addr().String())
	if err := s.Serve(l); err != nil {
		logrus.Fatalf("server shut down due to error: %s", err)
	}
	logrus.Info("server shutting down cleanly")
}

Fix "make test" broken on Go 1.13


package gowrapmx4j

import "sync"

var registry = make(map[string]*MX4JMetric)
var reglock = &sync.RWMutex{}

func RegistrySet(mm MX4JMetric, mb *MBean) {
	reglock.Lock()
	defer reglock.Unlock()

	mm.MBean = mb
	registry[mm.HumanName] = &mm
}

func RegistryGet(humanName string) *MX4JMetric {
	reglock.RLock()
	defer reglock.RUnlock()

	return registry[humanName]
}

func RegistryBeans() map[string]*MBean {
	reglock.RLock()
	defer reglock.RUnlock()

	beans := make(map[string]*MBean)
	for hname, mm := range registry {
		beans[hname] = mm.MBean
	}
	return beans
}

func RegistryGetAll() []MX4JMetric {
	reglock.RLock()
	defer reglock.RUnlock()
	metrics := make([]MX4JMetric, 0, 0)
	for _, mm := range registry {
		metrics = append(metrics, *mm)
	}
	return metrics
}

// Return a map of MX4JMetric structs keyed by their human readable name field.
func RegistryGetHRMap() map[string]MX4JMetric {
	reglock.RLock()
	defer reglock.RUnlock()

	metrics := make(map[string]MX4JMetric)
	for _, mm := range registry {
		metrics[mm.HumanName] = *mm
	}
	return metrics
}

Return a map of human MBeans keyed by their human readable names


// Copyright 2020 Georg Großberger <contact@grossberger-ge.org>
// This is free software; it is provided under the terms of the MIT License
// See the file LICENSE or <https://opensource.org/licenses/MIT> for details

package browser

var files = []string{
	"chromium.exe",
	"chrome.exe",
}

var paths = []string{
	`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
	`C:\Users\${USER_HOME}\AppData\Local\Google\Chrome\Application\chrome.exe`,
}

// Copyright 2020 Georg Großberger <contact@grossberger-ge.org>
// This is free software; it is provided under the terms of the MIT License
// See the file LICENSE or <https://opensource.org/licenses/MIT> for details

package browser

var files = []string{
	"chromium.exe",
	"chrome.exe",
}

var paths = []string{
	`C:\Program Files\Google\Chrome\Application\chrome.exe`,
	`C:\Program Files (x86)\Google\Chrome\Application\chrome.exe`,
	`C:\Users\${USER_HOME}\AppData\Local\Google\Chrome\Application\chrome.exe`,
}

Add newer Program Files path to lookup on windows


package kata

import "testing"

func TestGutterGame(t *testing.T) {
	var game Game = Game {0}
	for i := 0; i < 20; i++ {
		game.roll(0)
	}
	if game.score() != 0 {
		t.Errorf("Game.score() for a 0 pins game expect 0, got %d", game.score())
	}
}

func TestAllOnes(t *testing.T) {
        var game Game = Game {0}
        for i := 0; i < 20; i++ {
                game.roll(1)
        }
        if game.score() != 20 {
                t.Errorf("Game.score() for all 1 pins rolls expect 20, got %d", game.score())
        }
}

package kata

import "testing"

var game Game

func setUp() {
	game = Game{}
}

func rollMany(n, pins int) {
	for i := 0; i < n; i++ {
		game.roll(pins)
	}
}

func TestGutterGame(t *testing.T) {
	setUp()
	rollMany(20, 0)
	if game.score() != 0 {
		t.Errorf("Game.score() for a 0 pins game expect 0, got %d", game.score())
	}
}

func TestAllOnes(t *testing.T) {
	setUp()
	rollMany(20, 1)
	if game.score() != 20 {
		t.Errorf("Game.score() for all 1 pins rolls expect 20, got %d", game.score())
	}
}

Refactor test in small partial functions


package main

import (
	"flag"
	"github.com/reveliant/dirtyci/server"
)

func main() {
	var mode = "release"
	var help = flag.Bool("h", false, "Show this help message")
	var debug = flag.Bool("d", false, "Enable debug mode")
	var filename = flag.String("c", "config.toml", "Configuration file path")
	flag.Parse()

	if *help {
		flag.PrintDefaults()
		return
	}

	if *debug {
		mode = "debug"
	}
	server.SetMode(mode)

	var router = server.NewRouter()
	router.LoadConfig(*filename)
	router.LoadPlugins()
	router.Home(server.Redirect("https://github.com/reveliant/dirty-ci"))
	router.Run()
}

package main

import (
	"fmt"
	"flag"
	"github.com/reveliant/dirtyci/server"
)

func main() {
	var mode = "release"
	var help = flag.Bool("h", false, "Show this help message")
	var debug = flag.Bool("d", false, "Enable debug mode")
	var host = flag.String("host", "127.0.0.1", "Hostname to listen on")
	var port = flag.Int("port", 26979, "Port number")
	var filename = flag.String("c", "config.toml", "Configuration file path")
	flag.Parse()

	if *help {
		flag.PrintDefaults()
		return
	}

	if *debug {
		mode = "debug"
	}
	server.SetMode(mode)

	var router = server.NewRouter()
	router.LoadConfig(*filename)
	router.LoadPlugins()
	router.Home(server.Redirect("https://github.com/reveliant/dirty-ci"))
	router.Run(fmt.Sprintf("%s:%d", *host, *port))
}

Add address and port binding customization


package main

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

var (
	flHelp bool
)

func main() {
	flag.BoolVar(&flHelp, "h", false, "Print this message and quit")
	flag.BoolVar(&flHelp, "-help", false, "Print this message and quit")
	flag.Parse()

	if flHelp {
		showHelp()
		os.Exit(0)
	}
}

func showHelp() {
	fmt.Fprintf(os.Stderr, helpText)
}

const helpText = `md2ghost - Convert a markdown files into Ghost posts.

Usage: md2ghost [option] <file|directory>

Options:

  -o, --output  Specify an output directory for Ghost posts
  -h, --help    Print this message and quit
  -v, --version Print version information and quit

Example:

  $ md2ghost .
  $ md2ghost -o path/to/output_directory path/to/your_directory
`

package main

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

var (
	flHelp bool
)

func main() {
	flag.BoolVar(&flHelp, "h", false, "Print this message and quit")
	flag.BoolVar(&flHelp, "help", false, "Print this message and quit")
	flag.Parse()

	if flHelp {
		showHelp()
		os.Exit(0)
	}
}

func showHelp() {
	fmt.Fprintf(os.Stderr, helpText)
}

const helpText = `md2ghost - Convert a markdown files into Ghost posts.

Usage: md2ghost [option] <file|directory>

Options:

  -o, --output  Specify an output directory for Ghost posts
  -h, --help    Print this message and quit
  -v, --version Print version information and quit

Example:

  $ md2ghost .
  $ md2ghost -o path/to/output_directory path/to/your_directory
`

Change command line option for --help


package MySQLProtocol

type Context struct {
	capability uint64
}

package MySQLProtocol

type Context struct {
    capability uint64
    prepared_statements map[uint32]Packet_COM_STMT_PREPARE_OK
}

Add in the session prepared_statements into the context object


package fnlog_test

import (
	"github.com/northbright/fnlog"
	"log"
)

func Example() {
	iLog := fnlog.New("i")
	wLog := fnlog.New("w")
	eLog := fnlog.New("e")
	var noTagLog *log.Logger = fnlog.New("")

	iLog.Printf("print infos")
	wLog.Printf("print warnnings")
	eLog.Printf("print errors")
	noTagLog.Printf("print messages without tag")

	// Output:
	//
}

func init() {
}

Remove init() to see if Example() works


// Copyright 2014 Arne Roomann-Kurrik
//
// 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 twodee

import ()

type Point struct {
	X float32
	Y float32
}

func Pt(x, y float32) Point {
	return Point{x, y}
}

type Rectangle struct {
	Min Point
	Max Point
}

func Rect(x1, y1, x2, y2 float32) Rectangle {
	return Rectangle{
		Min: Pt(x1, y1),
		Max: Pt(x2, y2),
	}
}

// Copyright 2014 Arne Roomann-Kurrik
//
// 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 twodee

type Point struct {
	X float32
	Y float32
}

func Pt(x, y float32) Point {
	return Point{x, y}
}

type Rectangle struct {
	Min Point
	Max Point
}

func Rect(x1, y1, x2, y2 float32) Rectangle {
	return Rectangle{
		Min: Pt(x1, y1),
		Max: Pt(x2, y2),
	}
}

func (r Rectangle) Overlaps(s Rectangle) bool {
	return s.Min.X < r.Max.X && s.Max.X > r.Min.X &&
		s.Min.Y < r.Max.Y && s.Max.Y > r.Min.Y
}

Add an Overlaps function to Rectangle.


package nuget

const Description = "Run NuGet."

var Usage = []string{`jfrog rt nuget [command options] <nuget args> <source repository name>`}

const Arguments string = `	nuget args
		Arguments to run with NuGet command.

	source repository name
		The source NuGet repository. Can be a local, remote or virtual NuGet repository.`

package nuget

const Description = "Run NuGet."

var Usage = []string{`jfrog rt nuget [command options] <nuget args> <source repository name>`}

const Arguments string = `	nuget command
		The nuget command to run. For example, restore.

	source repository name
		The source NuGet repository. Can be a local, remote or virtual NuGet repository.`

Support for NuGet build info.


package formatter

import (
	"fmt"
	"strings"

	"github.com/docker/docker/api/types/swarm"
)

//FormatPorts returns the string representation of the given PortConfig
func FormatPorts(ports []swarm.PortConfig) string {
	result := []string{}
	for _, pConfig := range ports {
		result = append(result, fmt.Sprintf("*:%d->%d/%s",
			pConfig.PublishedPort,
			pConfig.TargetPort,
			pConfig.Protocol,
		))
	}
	return strings.Join(result, ",")
}

//FormatSwarmNetworks returns the string representation of the given slice of NetworkAttachmentConfig
func FormatSwarmNetworks(networks []swarm.NetworkAttachmentConfig) string {
	result := []string{}
	for _, network := range networks {
		result = append(result, network.Target)
	}
	return strings.Join(result, ",")
}

Add formatter for Swarm network specs


// Copyright 2018 The gVisor 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 filter defines all syscalls the gofer is allowed to make, and
// installs seccomp filters to prevent prohibited syscalls in case it's
// compromised.
package filter

import (
	"gvisor.dev/gvisor/pkg/seccomp"
)

// Install installs seccomp filters.
func Install() error {
	// Set of additional filters used by -race and -msan. Returns empty
	// when not enabled.
	allowedSyscalls.Merge(instrumentationFilters())

	return seccomp.Install(allowedSyscalls)
}

// InstallUDSFilters installs the seccomp filters required to let the gofer connect
// to a host UDS.
func InstallUDSFilters() {
	// Add additional filters required for connecting to the host's sockets.
	allowedSyscalls.Merge(udsSyscalls)
}

// Copyright 2018 The gVisor 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 filter defines all syscalls the gofer is allowed to make, and
// installs seccomp filters to prevent prohibited syscalls in case it's
// compromised.
package filter

import (
	"gvisor.dev/gvisor/pkg/seccomp"
)

// Install installs seccomp filters.
func Install() error {
	// Set of additional filters used by -race and -msan. Returns empty
	// when not enabled.
	allowedSyscalls.Merge(instrumentationFilters())

	return seccomp.Install(allowedSyscalls)
}

// InstallUDSFilters extends the allowed syscalls to include those necessary for
// connecting to a host UDS.
func InstallUDSFilters() {
	// Add additional filters required for connecting to the host's sockets.
	allowedSyscalls.Merge(udsSyscalls)
}

Update InstallUDSFilters documentation to be accurate to functionality.


// Copyright 2012 Apcera Inc. All rights reserved.

package nats

import (
	"encoding/json"
)

// A JSON Encoder implementation for EncodedConn
// This encoder will use the builtin encoding/json to Marshal
// and Unmarshal most types, including structs.
type JsonEncoder struct {
	// Empty
}

func (je *JsonEncoder) Encode(subject string, v interface{}) ([]byte, error) {
	b, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}
	return b, nil
}

func (je *JsonEncoder) Decode(subject string, data []byte, vPtr interface{}) error {
	return json.Unmarshal(data, vPtr)
}

// Copyright 2012 Apcera Inc. All rights reserved.

package nats

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

// A JSON Encoder implementation for EncodedConn
// This encoder will use the builtin encoding/json to Marshal
// and Unmarshal most types, including structs.
type JsonEncoder struct {
	// Empty
}

func (je *JsonEncoder) Encode(subject string, v interface{}) ([]byte, error) {
	b, err := json.Marshal(v)
	if err != nil {
		return nil, err
	}
	return b, nil
}

func (je *JsonEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error) {
	switch arg := vPtr.(type) {
	case *string:
		// If they want a string and it is a JSON string, strip quotes
		// This allows someone to send a struct but receive as a plain string if
		// need be..
		str := *(*string)(unsafe.Pointer(&data))
		if strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`) {
			*arg = str[1:len(str)-1]
		} else {
			*arg = str
		}
	case *[]byte:
		*arg = data
	default:
		err = json.Unmarshal(data, arg)
	}
	return
}

Allow string and []byte decoding


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

package entity

import (
	"gopkg.in/goyy/goyy.v0/util/bytes"
)

type String struct {
	base
	value []byte
}

func (me *String) Value() string {
	return string(me.value)
}

func (me *String) ValuePtr() *[]byte {
	return &me.value
}

func (me *String) SetValue(v string) {
	me.value = []byte(v)
	me.field.SetModified(true)
}

func (me *String) SetDefault(v string) error {
	me.value = []byte(v)
	return nil
}

func (me *String) SetString(v string) error {
	if err := me.SetDefault(v); err != nil {
		return err
	} else {
		me.field.SetModified(true)
		return nil
	}
}

func (me *String) String() string {
	out := bytes.TrimRightNul(me.value)
	return string(out)
}

func (me *String) Name() string {
	return "string"
}

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

package entity

import (
	"gopkg.in/goyy/goyy.v0/util/bytes"
)

type String struct {
	base
	value []byte
}

func (me *String) Value() string {
	if me.value == nil || len(me.value) == 0 {
		return ""
	}
	return string(me.value)
}

func (me *String) ValuePtr() *[]byte {
	return &me.value
}

func (me *String) SetValue(v string) {
	me.value = []byte(v)
	me.field.SetModified(true)
}

func (me *String) SetDefault(v string) error {
	me.value = []byte(v)
	return nil
}

func (me *String) SetString(v string) error {
	if err := me.SetDefault(v); err != nil {
		return err
	} else {
		me.field.SetModified(true)
		return nil
	}
}

func (me *String) String() string {
	out := bytes.TrimRightNul(me.value)
	return string(out)
}

func (me *String) Name() string {
	return "string"
}

Add whether to empty judgments


package main

func main() {
    for {
        spin()
    }
}

func spin() {
    sum := 0
    for i:=0;i<9999999;i++ {
        sum += i
        sum -= i
    }
}

package main

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

import "expvar"
import _ "net/http/pprof"

var spinCount = expvar.NewInt("SpinCount")

func main() {

    go func() {
        log.Println("Starting HTTP")
        log.Println(http.ListenAndServe("localhost:6060", nil))
    }()

    log.Println("Starting spin")
    for {
        spin()
        spinCount.Add(1)
        time.Sleep(0)
    }
}

func spin() {
    sum := 0
    for i:=0;i<1000;i++ {
        sum += i
        sum -= i
    }
}

Add new spinner go app.


package main

import (
	"log"
	"os/exec"
)

func lastlog() (string, error) {
	users, err := exec.Command("/usr/bin/lastlog", "--time", "365").Output()
	if err != nil {
		log.Fatal(err)
	}
	return string(users), nil
}

package main

import (
	"log"
	"os/exec"
)

func lastlog() (string, error) {
	users := exec.Command("/usr/bin/lastlog", "--time", "365")
	awk := exec.Command("/usr/bin/awk", `{print $1","$3","$4" "$5" "$6" "$7" "$8}`)

	out, err := users.StdoutPipe()
	if err != nil {
		log.Fatal(err)
	}
	users.Start()
	awk.Stdin = out

	users_out, err := awk.Output()
	if err != nil {
		log.Fatal(err)
	}

	return string(users_out), nil
}

Format command using awk (incomplete)


package matchers

import (
	"fmt"

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

type HaveOccurredMatcher struct {
}

func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) {
	// is purely nil?
	if actual == nil {
		return false, nil
	}

	// must be an 'error' type
	if !isError(actual) {
		return false, fmt.Errorf("Expected an error-type.  Got:\n%s", format.Object(actual, 1))
	}

	// must be non-nil (or a pointer to a non-nil)
	return !isNil(actual), nil
}

func (matcher *HaveOccurredMatcher) FailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected an error to have occurred.  Got:\n%s", format.Object(actual, 1))
}

func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected error:\n%s\n%s\n%s", format.Object(actual, 1), format.IndentString(actual.(error).Error(), 1), "not to have occurred")
}

package matchers

import (
	"fmt"

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

type HaveOccurredMatcher struct {
}

func (matcher *HaveOccurredMatcher) Match(actual interface{}) (success bool, err error) {
	// is purely nil?
	if actual == nil {
		return false, nil
	}

	// must be an 'error' type
	if !isError(actual) {
		return false, fmt.Errorf("Expected an error-type.  Got:\n%s", format.Object(actual, 1))
	}

	// must be non-nil (or a pointer to a non-nil)
	return !isNil(actual), nil
}

func (matcher *HaveOccurredMatcher) FailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Expected an error to have occurred.  Got:\n%s", format.Object(actual, 1))
}

func (matcher *HaveOccurredMatcher) NegatedFailureMessage(actual interface{}) (message string) {
	return fmt.Sprintf("Unexpected error:\n%s\n%s\n%s", format.Object(actual, 1), format.IndentString(actual.(error).Error(), 1), "occurred")
}

Clarify message for unexpected errors


package sqlxurl

import (
	"os"
	"fmt"
	"net/url"
	"strings"
	"github.com/jmoiron/sqlx"
)

func Connect() (*sqlx.DB, error) {
	return ConnectToURL(os.Getenv("DATABASE_URL"))
}

func ConnectToURL(s string) (c *sqlx.DB, err error) {
	databaseUrl, err := url.Parse(s)

	if err != nil {
		return
	}

	auth := ""

	if databaseUrl.User != nil {
		auth = databaseUrl.User.String()
		auth = fmt.Sprintf("%s@", auth)
	}

	db := ""

	if len(databaseUrl.Path) > 1 {
		db = strings.TrimPrefix(databaseUrl.Path, "/")
		db = fmt.Sprintf("/%s", db)
	}

	dbDsn := fmt.Sprintf("%stcp(%s)%s", auth, databaseUrl.Host, db)
	c, err = sqlx.Connect(databaseUrl.Scheme, dbDsn)

	if err != nil {
		fmt.Println(err)
		return
	}

	return
}

package sqlxurl

import (
	"os"
	"fmt"
	"net/url"
	"strings"
	"github.com/jmoiron/sqlx"
)

func Connect() (*sqlx.DB, error) {
	return ConnectToURL(os.Getenv("DATABASE_URL"))
}

func ConnectToURL(s string) (c *sqlx.DB, err error) {
	databaseUrl, err := url.Parse(s)

	if err != nil {
		return
	}

	if databaseUrl.Scheme == "" {
		return c, fmt.Errorf("No scheme specified in %v", s)
	}

	auth := ""

	if databaseUrl.User != nil {
		auth = databaseUrl.User.String()
		auth = fmt.Sprintf("%s@", auth)
	}

	db := ""

	if len(databaseUrl.Path) > 1 {
		db = strings.TrimPrefix(databaseUrl.Path, "/")
		db = fmt.Sprintf("/%s", db)
	}

	dbDsn := fmt.Sprintf("%stcp(%s)%s", auth, databaseUrl.Host, db)
	c, err = sqlx.Connect(databaseUrl.Scheme, dbDsn)

	if err != nil {
		fmt.Println(err)
		return
	}

	return
}

Raise an error if no scheme is set


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

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

Allow for .yml files in vendored code


package database

import (
	"github.com/juju/errors"
)

var (
	// ErrNoSuchEntity is returned from a Get operation when there is not a model
	// that matches the query
	ErrNoSuchEntity = errors.New("no such entity found in database")
)

package database

import (
	"github.com/juju/errors"
)

var (
	// ErrNoSuchEntity is returned from a Get operation when there is not a model
	// that matches the query
	ErrNoSuchEntity = errors.NotFoundf("no such entity found in database")
)

Revert "Do not use the NotFound error type because it triggers a 404 error page in the servers; use a default error type."


package main

import (
	"flag"
	"log"
	"net/url"
	"os/exec"
	"runtime"
	"strings"
)

func main() {

	flag.Parse()

	//If the number of arguments is zero, exit the main() function
	if flag.NArg() == 0 {
		println("give a search query, e.g. \"google hello world\" ")
		return
	}

	s := strings.Join(flag.Args(), "+") //Concatenates the args with '+'
	println("let me google", s)

	link, err := url.Parse("https://google.com/#q=" + s)
	if err != nil {
		println("Incorrect url")
		return
	}

	cmd := new(exec.Cmd) //Pointer to newly allocated exec.Cmd type

	switch runtime.GOOS {

	case "linux":
		cmd = exec.Command("xdg-open", link.String())
	case "windows":
		cmd = exec.Command("cmd", "/c", "start", link.String())
	case "darwin":
		cmd = exec.Command("open", link.String())
	default:
		println("I don't know how to google it, on this OS.")
		println("Open an issue at github.com/hariharan-uno/google")

	}

	if err := cmd.Start(); err != nil {
		log.Fatal(err)
	}

}

// Copyright 2014 Hari haran. All rights reserved.
// Use of this source code is governed by a MIT
// license that can be found in the LICENSE file.

package main

import (
	"flag"
	"fmt"
	"log"
	"net/url"
	"os/exec"
	"runtime"
	"strings"
)

func main() {

	flag.Parse()

	// If the number of arguments is zero, exit the main() function.
	if flag.NArg() == 0 {
		fmt.Println(`give a search query, e.g. "google hello world" `)
		return
	}

	s := strings.Join(flag.Args(), "+") // concatenate the args with '+'
	fmt.Println("let me google", s)

	link, err := url.Parse("https://google.com/#q=" + s)
	if err != nil {
		fmt.Printf("url parsing error: %s\n", err)
		return
	}

	cmd := new(exec.Cmd)

	switch runtime.GOOS {
	case "linux":
		cmd = exec.Command("xdg-open", link.String())
	case "windows":
		cmd = exec.Command("cmd", "/c", "start", link.String())
	case "darwin":
		cmd = exec.Command("open", link.String())
	default:
		fmt.Println("I don't know how to open a browser on this OS.")
		fmt.Println("Open an issue at https://github.com/hariharan-uno/google/issues")
	}

	if err := cmd.Start(); err != nil {
		log.Fatal(err)
	}

}

Clean up code, use fmt


package thrift

import (
	"github.com/cyberdelia/statsd"
	"log"
	"os"
)

var (
	Metrics *Metric = NewMetric(os.Getenv("STATSD_URL"))
)

type Metric struct {
	client *statsd.Client
}

func NewMetric(statsdURL string) *Metric {
	var client *statsd.Client
	var err error

	if statsdURL != "" {
		client, err = statsd.Dial(statsdURL)

		if err != nil {
			log.Println(err.Error())

			return nil
		}
	}

	return &Metric{client}
}

func (m *Metric) Incr(metricName string) {
	if m.client != nil {
		m.client.Increment(metricName, 1, 1)
	}
}

func (m *Metric) Timing(metricName string, duration int64) {
	if m.client != nil {
		m.client.Timing(metricName, int(duration/1000000), 1)
	}
}

package thrift

import (
	"log"
	"os"
	"time"

	"github.com/upfluence/goutils/tracing"
	"github.com/upfluence/goutils/tracing/noop"
	"github.com/upfluence/goutils/tracing/statsd"
)

var (
	Metrics *Metric = NewMetric(os.Getenv("STATSD_URL"))
)

type Metric struct {
	tracer tracing.Tracer
}

func NewMetric(statsdURL string) *Metric {
	if statsdURL != "" {
		if t, err := statsd.NewTracer(statsdURL, ""); err != nil {
			log.Println("statsd dial: %s", err.Error())
		} else {
			return &Metric{t}
		}
	}
	return &Metric{&noop.Tracer{}}
}

func (m *Metric) Incr(metricName string) {
	m.tracer.Count(metricName, 1)
}

func (m *Metric) Timing(metricName string, duration time.Duration) {
	m.tracer.Timing(metricName, duration)
}

Use goutis tracer over plain statsd connection


package bagutil

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"errors"
	"fmt"
	"hash"
	"io/ioutil"
	"os"
)

// Takes a filepath as a string and produces a checksum.
func FileChecksum(filepath string, algo string) string {
	hsh, err := newHash(algo)
	if err != nil {
		panic(err)
	}
	file, err := os.Open(filepath)
	if err != nil {
		panic(err)
	}

	fileBytes, err := ioutil.ReadAll(file)
	if err != nil {
		panic(err)
	}
	hsh.Write(fileBytes)
	byteSum := hsh.Sum(nil)
	return fmt.Sprintf("%x", byteSum) // Convert to base16 on formatting.
}

func newHash(algo string) (hash.Hash, error) {
	switch algo {
	case "md5":
		return md5.New(), nil
	case "sha1":
		return sha1.New(), nil
	case "sha256":
		return sha256.New(), nil
	case "sha512":
		return sha512.New(), nil
	}
	return nil, errors.New("Unsupported hash value.")
}

package bagutil

import (
	"crypto/md5"
	"crypto/sha1"
	"crypto/sha256"
	"crypto/sha512"
	"errors"
	"fmt"
	"hash"
	"io"
	"os"
)

// Takes a filepath as a string and produces a checksum.
func FileChecksum(filepath string, algo string) string {
	hsh, err := newHash(algo)
	if err != nil {
		panic(err)
	}
	file, err := os.Open(filepath)
	if err != nil {
		panic(err)
	}

	_, err = io.Copy(hsh, file)
	if err != nil {
		panic(err)
	}
	byteSum := hsh.Sum(nil)
	return fmt.Sprintf("%x", byteSum) // Convert to base16 on formatting.
}

func newHash(algo string) (hash.Hash, error) {
	switch algo {
	case "md5":
		return md5.New(), nil
	case "sha1":
		return sha1.New(), nil
	case "sha256":
		return sha256.New(), nil
	case "sha512":
		return sha512.New(), nil
	}
	return nil, errors.New("Unsupported hash value.")
}

Update to stream bytes to checksum algo.


package main

import (
	"log"
	"path/filepath"
)

// globalPluginDirs returns directories that should be searched for
// globally-installed plugins (not specific to the current configuration).
//
// Earlier entries in this slice get priority over later when multiple copies
// of the same plugin version are found, but newer versions always override
// older versions where both satisfy the provider version constraints.
func globalPluginDirs() []string {
	var ret []string
	// Look in ~/.terraform.d/plugins/ , or its equivalent on non-UNIX
	dir, err := ConfigDir()
	if err != nil {
		log.Printf("[ERROR] Error finding global config directory: %s", err)
	} else {
		ret = append(ret, filepath.Join(dir, "plugins"))
	}

	return ret
}

package main

import (
	"fmt"
	"log"
	"path/filepath"
	"runtime"
)

// globalPluginDirs returns directories that should be searched for
// globally-installed plugins (not specific to the current configuration).
//
// Earlier entries in this slice get priority over later when multiple copies
// of the same plugin version are found, but newer versions always override
// older versions where both satisfy the provider version constraints.
func globalPluginDirs() []string {
	var ret []string
	// Look in ~/.terraform.d/plugins/ , or its equivalent on non-UNIX
	dir, err := ConfigDir()
	if err != nil {
		log.Printf("[ERROR] Error finding global config directory: %s", err)
	} else {
		machineDir := fmt.Sprintf("%s_%s", runtime.GOOS, runtime.GOARCH)
		ret = append(ret, filepath.Join(dir, "plugins", machineDir))
	}

	return ret
}

Add missing OS_ARCH dir to global plugin paths


package chat

type (
	TextComponent struct {
		Text string `json:"text"`

		Component
	}

	TranslateComponent struct {
		Translate string   `json:"translate"`
		With      []string `json:"with"`

		Component
	}

	ScoreComponent struct {
		Name      string `json:"name"`
		Objective string `json:"objective"`

		Component
	}

	SelectorComponent struct {
		Selector string   `json:"selector"`
		Args     []string `json:"extra"`

		Component
	}

	Component struct {
		Bold          bool `json:"bold"`
		Italic        bool `json:"italic"`
		Underlined    bool `json:"underlined"`
		Strikethrough bool `json:"obfuscated"`
		Obfuscated    bool `json:"obfuscated"`

		Color Color `json:"color"`

		ClickEvent ClickEvent `json:"clickEvent"`
		HoverEvent HoverEvent `json:"hoverEvent"`

		Insertion string `json:"insertion"`
	}
)

package chat

type (
	TextComponent struct {
		Text string `json:"text"`

		Component
	}

	TranslateComponent struct {
		Translate string   `json:"translate"`
		With      []string `json:"with"`

		Component
	}

	ScoreComponent struct {
		Name      string `json:"name"`
		Objective string `json:"objective"`

		Component
	}

	SelectorComponent struct {
		Selector string   `json:"selector"`
		Args     []string `json:"extra"`

		Component
	}

	Component struct {
		Bold          bool `json:"bold"`
		Italic        bool `json:"italic"`
		Underlined    bool `json:"underlined"`
		Strikethrough bool `json:"strikethrough"`
		Obfuscated    bool `json:"obfuscated"`

		Color Color `json:"color"`

		ClickEvent ClickEvent `json:"clickEvent"`
		HoverEvent HoverEvent `json:"hoverEvent"`

		Insertion string `json:"insertion"`
	}
)

Correct field serialization for Strikethrough param


package conf

import (
	"github.com/namsral/flag"
)

var Port int

func Init() {
	flag.IntVar(&Port, "port", 3000, "port of brandy")
	flag.IntVar(&Port, "p", 3000, "port of brandy")
	flag.Parse()
}

package conf

import (
	"github.com/namsral/flag"
	"log"
	"os"
	"path/filepath"
)

var Dir string
var Port int

func Init() {
	flag.StringVar(&Dir, "dir", "", "dir of brandy")
	flag.IntVar(&Port, "port", 3000, "port of brandy")
	flag.Parse()

	// Get the directory of the currently
	dir, err := filepath.Abs(filepath.Dir(os.Args[0]))
	if err != nil {
		log.Fatal(err)
	}

	if Dir == "" {
		Dir = dir
	}
}

Update conf package Init method.


package cmd

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

	"github.com/cozy/cozy-stack/config"
	"github.com/spf13/cobra"
	"strconv"
)

// statusCmd represents the status command
var statusCmd = &cobra.Command{
	Use:   "status",
	Short: "Check if the HTTP server is running",
	Long:  `Check if the HTTP server has been started and answer 200 for /status.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		if err := Configure(); err != nil {
			return err
		}

		url := &url.URL{
			Scheme: "http",
			Host:   config.GetConfig().Host + ":" + strconv.Itoa(config.GetConfig().Port),
			Path:   "/status",
		}
		resp, err := http.Get(url.String())
		if err != nil {
			fmt.Println("Error the HTTP server is not running:", err)
			os.Exit(1)
		}
		defer resp.Body.Close()
		if resp.StatusCode != 200 {
			fmt.Println("Error, unexpected HTTP status code:", resp.Status)
			os.Exit(1)
		}

		fmt.Println("OK, the HTTP server is ready.")
		return nil
	},
}

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

package cmd

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

	"github.com/cozy/cozy-stack/config"
	"github.com/spf13/cobra"
	"strconv"
)

// statusCmd represents the status command
var statusCmd = &cobra.Command{
	Use:   "status",
	Short: "Check if the HTTP server is running",
	Long:  `Check if the HTTP server has been started and answer 200 for /status.`,
	RunE: func(cmd *cobra.Command, args []string) error {
		if err := Configure(); err != nil {
			return err
		}

		url := &url.URL{
			Scheme: "http",
			Host:   config.GetConfig().Host + ":" + strconv.Itoa(config.GetConfig().Port),
			Path:   "status",
		}
		resp, err := http.Get(url.String())
		if err != nil {
			fmt.Println("Error the HTTP server is not running:", err)
			os.Exit(1)
		}
		defer resp.Body.Close()
		if resp.StatusCode != 200 {
			fmt.Println("Error, unexpected HTTP status code:", resp.Status)
			os.Exit(1)
		}

		fmt.Println("OK, the HTTP server is ready.")
		return nil
	},
}

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

Remove unnecessary "/" in path


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
}

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
}

Fix panic when treeish not passed to git diff-index


package format

import (
	"testing"

	log "github.com/Sirupsen/logrus"

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

func TestSsh(t *testing.T) {
	log.SetLevel(log.DebugLevel)

	keys := map[string][]string{
		"ernoaapa": []string{
			"ssh-rsa AAAAB3NzsshPublicKeyBlah",
		},
	}

	result := ssh(keys)

	assert.Equal(t, "ssh-rsa AAAAB3NzsshPublicKeyBlah ernoaapa\n", result, "Returned invalid ssh output")
}

package format

import (
	"testing"

	log "github.com/Sirupsen/logrus"

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

func TestSsh(t *testing.T) {
	log.SetLevel(log.DebugLevel)

	keys := map[string][]string{
		"ernoaapa": {
			"ssh-rsa AAAAB3NzsshPublicKeyBlah",
		},
	}

	result := ssh(keys)

	assert.Equal(t, "ssh-rsa AAAAB3NzsshPublicKeyBlah ernoaapa\n", result, "Returned invalid ssh output")
}

Fix code style based on feedback from `gofmt -s`


package lexer

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

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

Add Lexer struct and New function for it


package parser

import (
	"bufio"
	"fmt"
	"os"
	"testing"
)

func TestParser(t *testing.T) {
	r, err := os.Open("monitor")
	if err != nil {
		t.Error(err)
	}
	br := bufio.NewReader(r)
	bd := NewBabelDesc()
	err = bd.Fill(br)
	if err != nil {
		t.Error(err)
	}
	fmt.Println("Fill\n", bd)
	err = bd.Fill(br)
	if err != nil {
		t.Error(err)
	}
	fmt.Println("Update\n", bd)
	fmt.Println(bd)
}

package parser

import (
	"bufio"
	"fmt"
	"os"
	"testing"
)

func TestParser(t *testing.T) {
	r, err := os.Open("monitor")
	if err != nil {
		t.Error(err)
	}
	br := bufio.NewReader(r)
	bd := NewBabelDesc()
	err = bd.Fill(br)
	if err != nil {
		t.Error(err)
	}
	if testing.Verbose() {
		fmt.Println("Fill\n", bd)
	}
	err = bd.Fill(br)
	if err != nil {
		t.Error(err)
	}
	if testing.Verbose() {
		fmt.Println("Update\n", bd)
		fmt.Println(bd)
	}
}

Make parser test less verbose by default.


package main

import (
	"log"
	"time"

	"github.com/gchaincl/sqlhooks"
	_ "github.com/mattn/go-sqlite3"
	"github.com/russross/meddler"
)

type Person struct {
	ID      int       `meddler:"id,pk"`
	Name    string    `meddler:"name"`
	Age     int       `meddler:"age"`
	Created time.Time `meddler:"created,localtime"`
}

type MyQueyer struct {
}

func (mq MyQueyer) BeforeQuery(ctx *sqlhooks.Context) error {
	log.Printf("[query#%s] %s %q", ctx.GetID(), ctx.Query, ctx.Args)
	return nil
}

func (mq MyQueyer) AfterQuery(ctx *sqlhooks.Context) error {
	log.Printf("[query#%s] done (err = %v)", ctx.GetID(), ctx.Error)
	return ctx.Error
}

func main() {
	db, err := sqlhooks.Open("sqlite3", ":memory:", &MyQueyer{})
	if err != nil {
		panic(err)
	}

	p := new(Person)
	meddler.Load(db, "person", p, 1)
}

package main

import (
	"log"
	"time"

	"github.com/gchaincl/sqlhooks"
	_ "github.com/mattn/go-sqlite3"
	"github.com/russross/meddler"
)

type Person struct {
	ID      int       `meddler:"id,pk"`
	Name    string    `meddler:"name"`
	Age     int       `meddler:"age"`
	Created time.Time `meddler:"created,localtime"`
}

type MyQueyer struct {
	count int
}

func (mq *MyQueyer) BeforeQuery(ctx *sqlhooks.Context) error {
	mq.count++

	ctx.Set("id", mq.count)
	log.Printf("[query#%d] %s %q", ctx.Get("id").(int), ctx.Query, ctx.Args)
	return nil
}

func (mq MyQueyer) AfterQuery(ctx *sqlhooks.Context) error {
	log.Printf("[query#%d] done (err = %v)", ctx.Get("id").(int), ctx.Error)
	return ctx.Error
}

func main() {
	db, err := sqlhooks.Open("sqlite3", ":memory:", &MyQueyer{})
	if err != nil {
		panic(err)
	}

	p := new(Person)
	meddler.Load(db, "person", p, 1)
}

Remove ID from meddler example


package stdin

import (
	"os"
)

// This is a tricky problem and we have gone through several iterations before
// settling on something that works well for recent golang across windows,
// linux and macos.

func IsReadable() bool {
	fi, err := os.Stdin.Stat()
	if err != nil {
		return false
	}

	// Named pipes on unix/linux indicate a readable stdin, but might not have size yet
	if fi.Mode()&os.ModeNamedPipe != 0 {
		return true
	}

	return fi.Size() > 0
}

package stdin

import (
	"os"
)

// This is a tricky problem and we have gone through several iterations before
// settling on something that works well for recent golang across windows,
// linux and macos.

func IsReadable() bool {
	fi, err := os.Stdin.Stat()
	if err != nil {
		return false
	}

	// Character devices in Linux/Unix are unbuffered devices that have
	// direct access to underlying hardware and don't allow reading single characters at a time
	if (fi.Mode() & os.ModeCharDevice) == os.ModeCharDevice {
		return false
	}

	return true
}

Use os.ModeCharDevice instead of os.ModeNamedPipe