package xlsx

import (
	"testing"
)

func TestMacExcel(t *testing.T) {
	xlsxFile, error := OpenFile("macExcelTest.xlsx")
	if error != nil {
		t.Error(error.Error())
		return
	}
	if xlsxFile == nil {
		t.Error("OpenFile returned nil FileInterface without generating an os.Error")
		return
	}
	s := xlsxFile.Sheets[0].Cell(0, 0).String()
	if s != "编号" {
		t.Errorf("[TestMacExcel] xlsxFile.Sheets[0].Cell(0,0).String():'%s'", s)
		return
	}
}

package xlsx

import (
	"testing"
)

// Test that we can successfully read an XLSX file generated by
// Microsoft Excel for Mac.  In particular this requires that we
// respect the contents of workbook.xml.rels, which maps the sheet IDs
// to their internal file names.
func TestMacExcel(t *testing.T) {
	xlsxFile, error := OpenFile("macExcelTest.xlsx")
	if error != nil {
		t.Error(error.Error())
		return
	}
	if xlsxFile == nil {
		t.Error("OpenFile returned nil FileInterface without generating an os.Error")
		return
	}
	s := xlsxFile.Sheets[0].Cell(0, 0).String()
	if s != "编号" {
		t.Errorf("[TestMacExcel] xlsxFile.Sheets[0].Cell(0,0).String():'%s'", s)
		return
	}
}

Add docstring to TestMacExcel test function.


// +build !linux

/*
Copyright 2017 Gravitational, Inc.

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 monitoring

// NewOSChecker returns a new checker to verify OS distribution
// against the list of supported releases.
//
// The checker only supports Linux.
func NewOSChecker(releases ...OSRelease) noopChecker {
	return noopChecker{}
}

// OSRelease describes an OS distribution.
// It only supports Linux.
type OSRelease struct {
	// ID identifies the distributor: ubuntu, redhat/centos, etc.
	ID string
	// VersionID is the release version i.e. 16.04 for Ubuntu
	VersionID string
	// Like specifies the list of root OS distributions this
	// distribution is a descendant of
	Like []string
}

// GetOSRelease deteremines the OS distribution release information.
//
// It only supports Linux.
func GetOSRelease() (*OSRelease, error) {
	return nil, trace.BadParameter("not implemented")
}

// +build !linux

/*
Copyright 2017 Gravitational, Inc.

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 monitoring

import "github.com/gravitational/trace"

// NewOSChecker returns a new checker to verify OS distribution
// against the list of supported releases.
//
// The checker only supports Linux.
func NewOSChecker(releases ...OSRelease) noopChecker {
	return noopChecker{}
}

// OSRelease describes an OS distribution.
// It only supports Linux.
type OSRelease struct {
	// ID identifies the distributor: ubuntu, redhat/centos, etc.
	ID string
	// VersionID is the release version i.e. 16.04 for Ubuntu
	VersionID string
	// Like specifies the list of root OS distributions this
	// distribution is a descendant of
	Like []string
}

// GetOSRelease deteremines the OS distribution release information.
//
// It only supports Linux.
func GetOSRelease() (*OSRelease, error) {
	return nil, trace.BadParameter("not implemented")
}

Add missing dependency on darwin


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

// +build go1.3

package lxdclient

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

// Client is a high-level wrapper around the LXD API client.
type Client struct {
	raw       rawClientWrapper
	namespace string
}

// Connect opens an API connection to LXD and returns a high-level
// Client wrapper around that connection.
func Connect(cfg Config) (*Client, error) {
	if err := cfg.Apply(); err != nil {
		return nil, errors.Trace(err)
	}

	raw, err := newRawClient(cfg.Remote)
	if err != nil {
		return nil, errors.Trace(err)
	}

	conn := &Client{
		raw:       raw,
		namespace: cfg.Namespace,
	}
	return conn, nil
}

func newRawClient(remote Remote) (*lxd.Client, error) {
	cfg, err := lxd.LoadConfig()
	if err != nil {
		return nil, errors.Trace(err)
	}

	client, err := lxd.NewClient(cfg, remote.ID())
	if err != nil {
		return nil, errors.Trace(err)
	}

	return client, nil
}

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

// +build go1.3

package lxdclient

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

// Client is a high-level wrapper around the LXD API client.
type Client struct {
	raw       rawClientWrapper
	namespace string
	remote    string
}

// Connect opens an API connection to LXD and returns a high-level
// Client wrapper around that connection.
func Connect(cfg Config) (*Client, error) {
	if err := cfg.Apply(); err != nil {
		return nil, errors.Trace(err)
	}
	remote := cfg.Remote.ID()

	raw, err := newRawClient(remote)
	if err != nil {
		return nil, errors.Trace(err)
	}

	conn := &Client{
		raw:       raw,
		namespace: cfg.Namespace,
		remote:    remote,
	}
	return conn, nil
}

func newRawClient(remote string) (*lxd.Client, error) {
	logger.Debugf("loading LXD client config from %q", lxd.ConfigDir)

	cfg, err := lxd.LoadConfig()
	if err != nil {
		return nil, errors.Trace(err)
	}

	logger.Debugf("using LXD remote %q", remote)
	client, err := lxd.NewClient(cfg, remote)
	if err != nil {
		return nil, errors.Trace(err)
	}

	return client, nil
}

Add "remote" field to lxdclient.Config.


// Copyright 2011 Google Inc. All Rights Reserved.
// This file is available under the Apache license.

// +build gofuzz

package vm

import (
	"bytes"
)

func Fuzz(data []byte) int {
	if _, err := Compile("fuzz", bytes.NewReader(data), false, false, false, nil); err != nil {
		return 0
	}
	return 1
}

// Copyright 2011 Google Inc. All Rights Reserved.
// This file is available under the Apache license.

// +build gofuzz

package vm

import (
	"bytes"
)

func Fuzz(data []byte) int {
	// We need to successfully parse flags to initialize the glog logger used
	// by the compiler, but the fuzzer gets called with flags captured by the
	// libfuzzer main, which we don't want to intercept here.
	flag.Commandline = flag.NewFlagSet("", flag.ContinueOnError)
	flag.Parse()
	if _, err := Compile("fuzz", bytes.NewReader(data), false, false, false, nil); err != nil {
		return 0
	}
	return 1
}

Initialize the flags so that the glogger doesn't log that we haven't done so, but try to avoid intercepting the libFuzzer main's flags.


package generator

import (
	"strconv"

	"github.com/adam-hanna/randomstrings"
	"github.com/onsi/ginkgo/config"
)

func randomName() string {
	str, err := randomstrings.GenerateRandomString(20)
	if err != nil {
		panic(err)
	}

	return str
}

func PrefixedRandomName(prefixName, resourceName string) string {
	return prefixName + "-" + strconv.Itoa(config.GinkgoConfig.ParallelNode) + "-" + resourceName + "-" + randomName()
}

package generator

import (
	"strconv"

	uuid "github.com/nu7hatch/gouuid"
	"github.com/onsi/ginkgo/config"
)

func randomName() string {
	guid, err := uuid.NewV4()
	if err != nil {
		panic(err)
	}

	return guid.String()
}

func PrefixedRandomName(prefixName, resourceName string) string {
	return prefixName + "-" + strconv.Itoa(config.GinkgoConfig.ParallelNode) + "-" + resourceName + "-" + randomName()
}

Revert "Use a better random string generator"


package romannumerals

import "errors"

func ToRomanNumeral(input int) (string, error) {
	if input <= 0 {
		return "", errors.New("input must be greater than 0")
	} else if input > 3000 {
		return "", errors.New("input must be less than or equal to 3000")
	}
	output := convertDigitToRomanNumeral(input)
	return output, nil
}

func convertDigitToRomanNumeral(digit int) string {
	digitToRomanNumeral := map[int]string{
		1: "I",
		2: "II",
		3: "III",
		4: "IV",
		5: "V",
		6: "VI",
		7: "VII",
		8: "VIII",
		9: "IX",
	}
	return digitToRomanNumeral[digit]
}

package romannumerals

import (
	"errors"
)

func ToRomanNumeral(input int) (output string, err error) {
	if input <= 0 {
		return "", errors.New("input must be greater than 0")
	} else if input > 3000 {
		return "", errors.New("input must be less than or equal to 3000")
	}

	numerator := input
	denominator := 1000
	for numerator != 0 {
		quotient, remainder := divmod(numerator, denominator)

		output += convertToNumeral(quotient * denominator)

		numerator = remainder
		denominator = denominator / 10
	}
	return output, nil
}

func convertToNumeral(number int) string {
	numberToNumeral := map[int]string{
		1:    "I",
		2:    "II",
		3:    "III",
		4:    "IV",
		5:    "V",
		6:    "VI",
		7:    "VII",
		8:    "VIII",
		9:    "IX",
		10:   "X",
		20:   "XX",
		30:   "XXX",
		40:   "XL",
		50:   "L",
		60:   "LX",
		70:   "LXX",
		80:   "LXXX",
		90:   "IC",
		100:  "C",
		500:  "D",
		1000: "M",
	}
	return numberToNumeral[number]
}

func divmod(numerator int, denominator int) (quotient, remainder int) {
	quotient = numerator / denominator // integer division, decimals are truncated
	remainder = numerator % denominator
	return quotient, remainder
}

Use divmod to determine the significance of each digit


// Copyright 2015 The Prometheus 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.

// +build !nointerrupts

package collector

import "github.com/prometheus/client_golang/prometheus"

type interruptsCollector struct {
	metric *prometheus.CounterVec
}

func init() {
	Factories["interrupts"] = NewInterruptsCollector
}

// Takes a prometheus registry and returns a new Collector exposing
// interrupts stats
func NewInterruptsCollector() (Collector, error) {
	return &interruptsCollector{
		metric: prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: Namespace,
				Name:      "interrupts",
				Help:      "Interrupt details.",
			},
			interruptLabelNames,
		),
	}, nil
}

// Copyright 2015 The Prometheus 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.

// +build !nointerrupts
// +build !darwin

package collector

import "github.com/prometheus/client_golang/prometheus"

type interruptsCollector struct {
	metric *prometheus.CounterVec
}

func init() {
	Factories["interrupts"] = NewInterruptsCollector
}

// Takes a prometheus registry and returns a new Collector exposing
// interrupts stats
func NewInterruptsCollector() (Collector, error) {
	return &interruptsCollector{
		metric: prometheus.NewCounterVec(
			prometheus.CounterOpts{
				Namespace: Namespace,
				Name:      "interrupts",
				Help:      "Interrupt details.",
			},
			interruptLabelNames,
		),
	}, nil
}

Fix compilation on OS X


package server

import (
	"errors"
	"sync"
	"time"
)

type LanguagePool struct {
	mutex     sync.RWMutex
	languages map[string]*Language
}

func NewLanguagePool() *LanguagePool {
	p := new(LanguagePool)
	p.languages = make(map[string]*Language)
	return p
}

func (lp *LanguagePool) Add(l *Language) error {
	lp.mutex.Lock()
	defer lp.mutex.Unlock()

	if _, ok := lp.languages[l.Name]; ok {
		return errors.New("Language with this name already exists")
	}

	lp.languages[l.Name] = l
	return nil
}

func (lp *LanguagePool) Remove(l *Language) {
	lp.mutex.Lock()
	defer lp.mutex.Unlock()

	delete(lp.languages, l.Name)
}

func (lp *LanguagePool) Get(name string) *Language {
	language, ok := lp.languages[name]
	if !ok {
		language = NewLanguage(name)
		languages.Add(language)
	}
	return language
}

func (lp *LanguagePool) Broadcast(sender *Client, message []byte) {
	now := time.Now()
	for _, language := range lp.languages {
		language.Send(sender, now, message)
	}
}

package server

import (
	"sync"
	"time"
)

type LanguagePool struct {
	mutex     sync.Mutex
	languages map[string]*Language
}

func NewLanguagePool() *LanguagePool {
	p := new(LanguagePool)
	p.languages = make(map[string]*Language)
	return p
}

func (lp *LanguagePool) Remove(l *Language) {
	lp.mutex.Lock()
	defer lp.mutex.Unlock()

	delete(lp.languages, l.Name)
}

func (lp *LanguagePool) Get(name string) *Language {
	lp.mutex.Lock()
	defer lp.mutex.Unlock()

	language, ok := lp.languages[name]
	if !ok {
		language = NewLanguage(name)
		lp.languages[language.Name] = language
	}
	return language
}

func (lp *LanguagePool) Broadcast(sender *Client, message []byte) {
	lp.mutex.Lock()
	defer lp.mutex.Unlock()

	now := time.Now()
	for _, language := range lp.languages {
		language.Send(sender, now, message)
	}
}

Use mutex instead of RWMutex in language


package sodium

import "fmt"
import "unsafe"

// #include <stdio.h>
// #include <sodium.h>
import "C"

func MemZero(buff1 []byte) {
	if len(buff1) > 0 {
		C.sodium_memzero(unsafe.Pointer(&buff1[0]), C.size_t(len(buff1)))
	}
}

func MemCmp(buff1, buff2 []byte, length int) int {
	if length >= len(buff1) || length >= len(buff2) {
		panic(fmt.Sprintf("Attempt to compare more bytes (%d) than provided " +
			"(%d, %d)", length, len(buff1), len(buff2)))
	}
	return int(C.sodium_memcmp(unsafe.Pointer(&buff1[0]),
		unsafe.Pointer(&buff2[0]),
		C.size_t(length)))
}

func Bin2hex(bin []byte) string {
	maxlen := len(bin) * 2
	binPtr := (*C.uchar)(unsafe.Pointer(&bin[0]))
	buf := (*C.char)(C.malloc(C.size_t(maxlen)))
	defer C.free(unsafe.Pointer(buf))

	C.sodium_bin2hex(buf, C.size_t(maxlen), binPtr, C.size_t(len(bin)))

	return C.GoString(buf)
}

package sodium

import "fmt"
import "unsafe"

// #include <stdio.h>
// #include <sodium.h>
import "C"

func MemZero(buff1 []byte) {
	if len(buff1) > 0 {
		C.sodium_memzero(unsafe.Pointer(&buff1[0]), C.size_t(len(buff1)))
	}
}

func MemCmp(buff1, buff2 []byte, length int) int {
	if length >= len(buff1) || length >= len(buff2) {
		panic(fmt.Sprintf("Attempt to compare more bytes (%d) than provided " +
			"(%d, %d)", length, len(buff1), len(buff2)))
	}
	return int(C.sodium_memcmp(unsafe.Pointer(&buff1[0]),
		unsafe.Pointer(&buff2[0]),
		C.size_t(length)))
}

func Bin2hex(bin []byte) string {
	maxlen := len(bin) * 2 + 1
	binPtr := (*C.uchar)(unsafe.Pointer(&bin[0]))
	buf := (*C.char)(C.malloc(C.size_t(maxlen)))
	defer C.free(unsafe.Pointer(buf))

	C.sodium_bin2hex(buf, C.size_t(maxlen), binPtr, C.size_t(len(bin)))

	return C.GoString(buf)
}

Fix Bin2hex: the length has to include the trailing \0


package all

import (
	_ "github.com/SpirentOrion/metrics-service/telegraf/plugins/inputs/cloudstress_agent_consumer"
	_ "github.com/SpirentOrion/metrics-service/telegraf/plugins/inputs/cloudstress_host_consumer"
)

package all

import (
	_ "github.com/SpirentOrion/metrics-service/telegraf/plugins/inputs/cloudstress_agent_consumer"
	_ "github.com/SpirentOrion/metrics-service/telegraf/plugins/inputs/host_agent_consumer"
)

Rename cloudstress agent consumer plugin to host agent consumer plugin


// Copyright 2018 The Ebiten 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 devicescale

import (
	"syscall/js"
)

func impl(x, y int) float64 {
	window := js.Global().Get("window")
	if !window.Truthy() {
		return 1
	}
	ratio := window.Get("devicePixelRatio").Float()
	if ratio == 0 {
		ratio = 1
	}
	return ratio
}

// Copyright 2018 The Ebiten 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 devicescale

import (
	"syscall/js"
)

func impl(x, y int) float64 {
	if go2cpp := js.Global().Get("go2cpp"); go2cpp.Truthy() {
		return go2cpp.Get("devicePixelRatio").Float()
	}

	window := js.Global().Get("window")
	if !window.Truthy() {
		return 1
	}
	ratio := window.Get("devicePixelRatio").Float()
	if ratio == 0 {
		ratio = 1
	}
	return ratio
}

Use devicePixelRatio property for go2cpp


package search_test

import (
	"testing"

	"github.com/wasanx25/sreq/search"
)

func TestNew(t *testing.T) {
	actual := search.New("testK", "testS")
	if actual.Keyword != "testK" {
		t.Errorf("expected=%q, got=%q", "testK", actual.Keyword)
	}

	if actual.Sort != "testS" {
		t.Errorf("expected=%q, got=%q", "testS", actual.Sort)
	}
}

func TestExec(t *testing.T) {
	s := search.New("testK", "testS")
	t.Run("return content", func(t *testing.T) {
		actualC, actualE := s.Exec()
		expectedContents := []*search.Content{}
		var expectedError *error

		if actualC != expectedContents {
			t.Errorf("expected=%q, got=%q", expectedContents, actualC)
		}

		if actualE != expectedError {
			t.Errorf("expected=%q, got=%q", expectedError, actualE)
		}
	})
}

package search_test

import (
	"testing"

	"github.com/wasanx25/sreq/search"
)

func TestNew(t *testing.T) {
	actual := search.New("testK", "testS")
	if actual.Keyword != "testK" {
		t.Errorf("expected=%q, got=%q", "testK", actual.Keyword)
	}

	if actual.Sort != "testS" {
		t.Errorf("expected=%q, got=%q", "testS", actual.Sort)
	}
}

func TestGetURL(t *testing.T) {
	s := search.New("testK", "testS")
	expectedURL := "https://qiita.com/search?pagenation=0&q=testK&sort=testS"
	actual := s.GetURL()

	if actual != expectedURL {
		t.Errorf("expected=%q, got=%q", expectedURL, actual)
	}
}

func TestExec(t *testing.T) {
	s := search.New("testK", "testS")
	t.Run("return content", func(t *testing.T) {
		actualC, actualE := s.Exec()
		expectedContents := []*search.Content{}
		var expectedError *error

		if actualC != expectedContents {
			t.Errorf("expected=%q, got=%q", expectedContents, actualC)
		}

		if actualE != expectedError {
			t.Errorf("expected=%q, got=%q", expectedError, actualE)
		}
	})
}

Add search get url test


package core

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

var (
	// HTTP stuff
	tr     *http.Transport
	client *http.Client
)

// Custom dial for Docker unix socket
func unixSocketDial(proto, addr string) (conn net.Conn, err error) {
	return net.Dial("unix", DGConfig.Docker.UnixSocketPath)
}

/*
	Initialize API Client
*/
func InitAPIClient() {
	tr = &http.Transport{
		Dial: unixSocketDial,
	}
	client = &http.Client{Transport: tr}

}

/*
	Do HTTP request on API
*/
func HTTPReq(path string) (int, string) {
	var resp *http.Response // Docker API response
	var body []byte         // Docker API response body
	var err error           // Error handling

	// HTTP Get request on the docker unix socket
	resp, err = client.Get("http://docker" + path)
	if err != nil {
		l.Error("Error: http request:", err)
		return 400, ""
	}

	// Read the body
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		l.Error("Error: http response body:", err)
		return 400, ""
	}

	l.Debug("Docker API response body:", "\n"+string(body))

	// Return HTTP status code + body
	return resp.StatusCode, string(body)
}

package core

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

var (
	// HTTP stuff
	tr     *http.Transport
	client *http.Client
)

// Custom dial for Docker unix socket
func unixSocketDial(proto, addr string) (conn net.Conn, err error) {
	return net.Dial("unix", DGConfig.Docker.UnixSocketPath)
}

/*
	Initialize API Client
*/
func InitAPIClient() {
	tr = &http.Transport{
		Dial: unixSocketDial,
	}
	client = &http.Client{Transport: tr}

}

/*
	Do HTTP request on API
*/
func HTTPReq(path string) (int, string) {
	var resp *http.Response // Docker API response
	var body []byte         // Docker API response body
	var err error           // Error handling

	// HTTP Get request on the docker unix socket
	resp, err = client.Get("http://docker" + path)
	if err != nil {
		l.Error("Error: http request:", err)
		return 400, ""
	}

	// Read the body
	body, err = ioutil.ReadAll(resp.Body)
	if err != nil {
		l.Error("Error: http response body:", err)
		return 400, ""
	}

	l.Silly("Docker API response body:", "\n"+string(body))

	// Return HTTP status code + body
	return resp.StatusCode, string(body)
}

Change http client request body verbose level


/*
   Copyright The containerd 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 containerd

import (
	"os"
	"path/filepath"
)

const (
	defaultAddress = `\\.\pipe\containerd-containerd-test`
	testImage      = "docker.io/microsoft/nanoserver:latest"
)

var (
	defaultRoot  = filepath.Join(os.Getenv("programfiles"), "containerd", "root-test")
	defaultState = filepath.Join(os.Getenv("programfiles"), "containerd", "state-test")
)

/*
   Copyright The containerd 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 containerd

import (
	"os"
	"path/filepath"
)

const (
	defaultAddress = `\\.\pipe\containerd-containerd-test`
	testImage      = "docker.io/microsoft/nanoserver@sha256:8f78a4a7da4464973a5cd239732626141aec97e69ba3e4023357628630bc1ee2"
)

var (
	defaultRoot  = filepath.Join(os.Getenv("programfiles"), "containerd", "root-test")
	defaultState = filepath.Join(os.Getenv("programfiles"), "containerd", "state-test")
)

Move to sha-specified test image for nanoserver


package stream

import "github.com/synapse-garden/sg-proto/store"

// Removed is a notification Resourcer that can inform a user they have
// been removed from the Stream without informing them of any other
// information about the Stream.
type Removed string

// Resource implements Resourcer.Resource on Removed.
func (Removed) Resource() store.Resource { return "removed" }

// Connected is a notification Resourcer that can inform a user someone
// has joined the Stream.
type Connected string

// Resource implements Resourcer.Resource on Connected.
func (Connected) Resource() store.Resource { return "connected" }

// Disconnected is a notification Resourcer that can inform a user
// someone has left the Stream.
type Disconnected string

// Resource implements Resourcer.Resource on Disconnected.
func (Disconnected) Resource() store.Resource { return "disconnected" }

// Deleted is a notification Resourcer that notifies the user a resource
// has been deleted.
type Deleted string

// Resource implements Resourcer.Resource on Deleted.
func (Deleted) Resource() store.Resource { return "deleted" }

package stream

import "github.com/synapse-garden/sg-proto/store"

// Removed is a notification Resourcer that can inform a user they have
// been removed from the Stream without informing them of any other
// information about the Stream.
type Removed string

// Resource implements Resourcer.Resource on Removed.
func (Removed) Resource() store.Resource { return "stream-removed" }

// ConnectionNotif is a base for stream Resourcers to create notifs.
// Implement store.Resourcer as a method on an alias of ConnectionNotif.
type ConnectionNotif struct {
	UserID   string `json:"userID"`
	StreamID string `json:"streamID"`
}

// Connected is a notification Resourcer that can inform a user someone
// has joined the Stream.
type Connected ConnectionNotif

// Resource implements Resourcer.Resource on Connected.
func (Connected) Resource() store.Resource { return "stream-connected" }

// Disconnected is a notification Resourcer that can inform a user
// someone has left the Stream.
type Disconnected ConnectionNotif

// Resource implements Resourcer.Resource on Disconnected.
func (Disconnected) Resource() store.Resource { return "stream-disconnected" }

// Deleted is a notification Resourcer that notifies the user a resource
// has been deleted.
type Deleted string

// Resource implements Resourcer.Resource on Deleted.
func (Deleted) Resource() store.Resource { return "stream-deleted" }

// Connected is a method on Stream which returns a Resourcer for the
// connection notif.
func (s *Stream) Connected(user string) store.Resourcer {
	return Connected{
		StreamID: s.ID,
		UserID:   user,
	}
}

// Disconnected is a method on Stream which returns a Resourcer for the
// disconnection notif.
func (s *Stream) Disconnected(user string) store.Resourcer {
	return Disconnected{
		StreamID: s.ID,
		UserID:   user,
	}
}

Make stream connection events more specific


package kafka

var codecs = make(map[int8]CompressionCodec)

// RegisterCompressionCodec registers a compression codec so it can be used by a Writer.
func RegisterCompressionCodec(codec func() CompressionCodec) {
	c := codec()
	codecs[c.Code()] = c
}

// CompressionCodec represents a compression codec to encode and decode
// the messages.
// See : https://cwiki.apache.org/confluence/display/KAFKA/Compression
type CompressionCodec interface {
	// Code returns the compression codec code
	Code() int8

	// Encode encodes the src data and writes the result to dst.
	// If ths destination buffer is too small, the function should
	// return the bytes.ErrToolarge error.
	Encode(dst, src []byte) (int, error)

	// Decode decodes the src data and writes the result to dst.
	// If ths destination buffer is too small, the function should
	// return the bytes.ErrToolarge error.
	Decode(dst, src []byte) (int, error)
}

const compressionCodecMask int8 = 0x03
const DefaultCompressionLevel int = -1
const CompressionNoneCode = 0

package kafka

import "sync"

var codecs = make(map[int8]CompressionCodec)
var codecsMutex sync.RWMutex

// RegisterCompressionCodec registers a compression codec so it can be used by a Writer.
func RegisterCompressionCodec(codec func() CompressionCodec) {
	c := codec()
	codecsMutex.Lock()
	codecs[c.Code()] = c
	codecsMutex.Unlock()
}

// CompressionCodec represents a compression codec to encode and decode
// the messages.
// See : https://cwiki.apache.org/confluence/display/KAFKA/Compression
type CompressionCodec interface {
	// Code returns the compression codec code
	Code() int8

	// Encode encodes the src data and writes the result to dst.
	// If ths destination buffer is too small, the function should
	// return the bytes.ErrToolarge error.
	Encode(dst, src []byte) (int, error)

	// Decode decodes the src data and writes the result to dst.
	// If ths destination buffer is too small, the function should
	// return the bytes.ErrToolarge error.
	Decode(dst, src []byte) (int, error)
}

const compressionCodecMask int8 = 0x03
const DefaultCompressionLevel int = -1
const CompressionNoneCode = 0

Add mutex on codecs map


package cmd

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

	"github.com/spf13/cobra"
)

// 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.`,
	Run: func(cmd *cobra.Command, args []string) {
		port := os.Getenv("PORT")
		if len(port) == 0 {
			port = "8080"
		}
		resp, err := http.Get("http://localhost:" + port + "/status")
		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.")
	},
}

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

package cmd

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

	"github.com/spf13/cobra"
)

// 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.`,
	Run: func(cmd *cobra.Command, args []string) {
		port := os.Getenv("PORT")
		if port == "" {
			port = "8080"
		}
		resp, err := http.Get("http://localhost:" + port + "/status")
		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.")
	},
}

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

Use `== ""` instead of `len() == 0`


package suite

import (
	"strings"
	"testing"

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

type CallOrderSuite struct {
	Suite
	callOrder []string
}

func (s *CallOrderSuite) call(method string) {
	//	s.Mutex.Lock()
	// defer s.Mutex.Unlock()

	s.callOrder = append(s.callOrder, method)
}

func TestSuiteCallOrder(t *testing.T) {
	Run(t, new(CallOrderSuite))
}
func (s *CallOrderSuite) SetupSuite() {
	s.call("SetupSuite")
}

func (s *CallOrderSuite) TearDownSuite() {
	s.call("TearDownSuite")
	assert.Equal(s.T(), "SetupSuite;SetupTest;Test A;TearDownTest;TearDownSuite", strings.Join(s.callOrder, ";"))
}
func (s *CallOrderSuite) SetupTest() {
	s.T().Parallel()
	s.call("SetupTest")
}

func (s *CallOrderSuite) TearDownTest() {
	s.call("TearDownTest")
}

func (s *CallOrderSuite) Test_A() {
	s.call("Test A")
}

//func (s *CallOrderSuite) Test_B() {
//	time.Sleep(time.Second)
//	s.call("Test B")
//}

package suite

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

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

type CallOrderSuite struct {
	Suite
	callOrder []string
}

func (s *CallOrderSuite) call(method string) {
	time.Sleep(time.Duration(rand.Intn(300)) * time.Millisecond)
	s.callOrder = append(s.callOrder, method)
}

func TestSuiteCallOrder(t *testing.T) {
	Run(t, new(CallOrderSuite))
}
func (s *CallOrderSuite) SetupSuite() {
	s.call("SetupSuite")
}

func (s *CallOrderSuite) TearDownSuite() {
	s.call("TearDownSuite")
	assert.Equal(s.T(), "SetupSuite;SetupTest;Test A;TearDownTest;SetupTest;Test B;TearDownTest;TearDownSuite", strings.Join(s.callOrder, ";"))
}
func (s *CallOrderSuite) SetupTest() {
	s.call("SetupTest")
}

func (s *CallOrderSuite) TearDownTest() {
	s.call("TearDownTest")
}

func (s *CallOrderSuite) Test_A() {
	s.call("Test A")
}

func (s *CallOrderSuite) Test_B() {
	s.call("Test B")
}

Remove parallel as that makes goroutines deadlock


package clienttest

import (
	check "gopkg.in/check.v1"

	"github.com/radanalyticsio/oshinko-cli/rest/version"
	"github.com/radanalyticsio/oshinko-cli/rest/helpers/info"
	"os"
)

func (s *OshinkoRestTestSuite) TestServerInfo(c *check.C) {
	resp, _ := s.cli.Server.GetServerInfo(nil)

	val := os.Getenv("OSHINKO_CLUSTER_IMAGE")
	os.Setenv("OSHINKO_CLUSTER_IMAGE", "")

	expectedName := version.GetAppName()
	expectedVersion := version.GetVersion()
	expectedImage := info.GetSparkImage()

	observedName := resp.Payload.Application.Name
	observedVersion := resp.Payload.Application.Version
	observedImage := resp.Payload.Application.DefaultClusterImage

	c.Assert(*observedName, check.Equals, expectedName)
	c.Assert(*observedVersion, check.Equals, expectedVersion)
	c.Assert(*observedImage, check.Equals, expectedImage)

	os.Setenv("OSHINKO_CLUSTER_IMAGE", "bobby")
	expectedImage = "bobby"
	resp, _ = s.cli.Server.GetServerInfo(nil)
	observedImage = resp.Payload.Application.DefaultClusterImage
	c.Assert(*observedImage, check.Equals, expectedImage)

	os.Setenv("OSHINKO_CLUSTER_IMAGE", val)
}

package clienttest

import (
	check "gopkg.in/check.v1"

	"github.com/radanalyticsio/oshinko-cli/rest/version"
	"github.com/radanalyticsio/oshinko-cli/rest/helpers/info"
	"os"
)

func (s *OshinkoRestTestSuite) TestServerInfo(c *check.C) {
	val := os.Getenv("OSHINKO_CLUSTER_IMAGE")
	os.Setenv("OSHINKO_CLUSTER_IMAGE", "")

	resp, _ := s.cli.Server.GetServerInfo(nil)

	expectedName := version.GetAppName()
	expectedVersion := version.GetVersion()
	expectedImage := info.GetSparkImage()

	observedName := resp.Payload.Application.Name
	observedVersion := resp.Payload.Application.Version
	observedImage := resp.Payload.Application.DefaultClusterImage

	c.Assert(*observedName, check.Equals, expectedName)
	c.Assert(*observedVersion, check.Equals, expectedVersion)
	c.Assert(*observedImage, check.Equals, expectedImage)

	os.Setenv("OSHINKO_CLUSTER_IMAGE", "bobby")
	expectedImage = "bobby"
	resp, _ = s.cli.Server.GetServerInfo(nil)
	observedImage = resp.Payload.Application.DefaultClusterImage
	c.Assert(*observedImage, check.Equals, expectedImage)

	os.Setenv("OSHINKO_CLUSTER_IMAGE", val)
}

Modify env var before request in server test


package monitor

import (
	"time"

	log "github.com/sirupsen/logrus"
)

func Watch(directory string, deployments chan<- string) {
	done := make(chan bool)
	defer close(done)

	watcher, err := NewBatcher(5 * time.Second)
	if err != nil {
		log.Fatal(err)
	}

	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()
	go func() {
		defer close(deployments)
		for {
			select {
			case event := <-watcher.Events:
				for key, _ := range event {
					deployments <- key
				}
			case err := <-watcher.Errors:
				log.Errorf("error:", err)
			}
		}
	}()

	err = watcher.Add(directory)
	if err != nil {
		log.Fatal(err)
	}

	<-done
}

package monitor

import (
	"time"

	log "github.com/sirupsen/logrus"
)

func Watch(directory string, batchInterval int, deployments chan<- string) {
	done := make(chan bool)
	defer close(done)

	log.Infof("Starting watcher with a batch interval of %ds", batchInterval)

	watcher, err := NewBatcher(time.Duration(batchInterval) * time.Second)
	if err != nil {
		log.Fatal(err)
	}

	if err != nil {
		log.Fatal(err)
	}
	defer watcher.Close()
	go func() {
		defer close(deployments)
		for {
			select {
			case event := <-watcher.Events:
				for key, _ := range event {
					deployments <- key
				}
			case err := <-watcher.Errors:
				log.Errorf("error:", err)
			}
		}
	}()

	err = watcher.Add(directory)
	if err != nil {
		log.Fatal(err)
	}

	<-done
}

Add parameter for batch interval


package amazonebsmock

import (
	"fmt"
	"testing"
)

func TestPrepare(t *testing.T) {
	builder := new(Builder)
	str, _ := builder.Prepare()
	fmt.Println(str)
}

package amazonebsmock

import (
	"github.com/Horgix/packer-builder-amazon-ebs-mock/packer-lib-mock"
	"log"
	"testing"
)

// TODO : This test could be improved, but since this method does absolutely
// nothing except initializing rand, and this is complicated to test, it hasn't
// been done. Feel free to improve it!
func TestPrepare(t *testing.T) {
	builder := new(Builder)
	builder.Prepare()
}

// Check that Run() method notify the user as expected
func TestRun_UiCalls(t *testing.T) {
	// Initialize and Prepare Builder
	builder := new(Builder)
	builder.Prepare()

	// Mock the "ui" part so we can count calls to ui.Say()
	ui := &packermock.MockUi{}

	log.Printf("ui.Say call SayCounter pre Run: %v", ui.SayCount)
	builder.Run(ui, nil, nil)
	log.Printf("ui.Say call SayCounter post Run: %v", ui.SayCount)

	// We should have 4 calls to ui.Say()
	const expectedSayCount = 4
	if ui.SayCount != expectedSayCount {
		t.Errorf("Number of calls to ui.Say() was incorrect, "+
			"got %d but expected %d", ui.SayCount,
			expectedSayCount)
	}
}

Add a first basic test to the Run() method


package binding

import (
	"testing"
	"time"

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

func TestParseTimeErrorParsing(t *testing.T) {
	r := require.New(t)
	_, err := parseTime([]string{"this is sparta"})
	r.Error(err)
}

func TestParseTime(t *testing.T) {
	r := require.New(t)
	tt, err := parseTime([]string{"2017-01-01"})
	r.NoError(err)
	expected := time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC)
	r.Equal(expected, tt)
}

package binding

import (
	"testing"
	"time"

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

func TestParseTimeErrorParsing(t *testing.T) {
	r := require.New(t)
	_, err := parseTime([]string{"this is sparta"})
	r.Error(err)
}

func TestParseTime(t *testing.T) {

	r := require.New(t)

	testCases := []struct {
		input     string
		expected  time.Time
		expectErr bool
	}{
		{
			input:     "2017-01-01",
			expected:  time.Date(2017, time.January, 1, 0, 0, 0, 0, time.UTC),
			expectErr: false,
		},
		{
			input:     "2018-07-13T15:34",
			expected:  time.Date(2018, time.July, 13, 15, 34, 0, 0, time.UTC),
			expectErr: false,
		},
		{
			input:     "2018-20-10T30:15",
			expected:  time.Time{},
			expectErr: true,
		},
	}

	for _, tc := range testCases {
		tt, err := parseTime([]string{tc.input})
		if !tc.expectErr {
			r.NoError(err)
		}
		r.Equal(tc.expected, tt)
	}
}

Add test cases for binding parseTime


/*
Copyright 2014 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 deny

import (
	"testing"

	"k8s.io/apiserver/pkg/admission"
	"k8s.io/kubernetes/pkg/api"
)

func TestAdmission(t *testing.T) {
	handler := NewAlwaysDeny()
	err := handler.Admit(admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, nil))
	if err == nil {
		t.Errorf("Expected error returned from admission handler")
	}
}

/*
Copyright 2014 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 deny

import (
	"testing"

	"k8s.io/apiserver/pkg/admission"
	"k8s.io/kubernetes/pkg/api"
)

func TestAdmission(t *testing.T) {
	handler := NewAlwaysDeny()
	err := handler.Admit(admission.NewAttributesRecord(nil, nil, api.Kind("kind").WithVersion("version"), "namespace", "name", api.Resource("resource").WithVersion("version"), "subresource", admission.Create, nil))
	if err == nil {
		t.Error("Expected error returned from admission handler")
	}
}

func TestHandles(t *testing.T) {
	handler := NewAlwaysDeny()
	tests := []admission.Operation{admission.Create, admission.Connect, admission.Update, admission.Delete}

	for _, test := range tests {
		if !handler.Handles(test) {
			t.Errorf("Expected handling all operations, including: %v", test)
		}
	}
}

Improve the code coverage of /plugin/pkg/admission/deny


package ansicfile

import "testing"

func TestOpen(t *testing.T) {
	fp, err := Open("あ", "w")
	if err == nil {
		Putc(byte('1'), fp)
		Close(fp)
	} else {
		t.Fatalf("NG: Open(\"あ\") Failed by %s", err.Error())
	}
	fp, err = Open("*", "w")
	if err == nil {
		t.Fatalf("NG: Open(\"*\") should failed")
	} else {
		print("OK: Open(\"*\") failed by " + err.Error() + "\n")
	}
}

// vim:set fenc=utf8:

package ansicfile

import "testing"

func TestOpen(t *testing.T) {
	fp, err := Open("あ", "w")
	if err == nil {
		fp.Putc(byte('1'))
		fp.Close()
	} else {
		t.Fatalf("NG: Open(\"あ\") Failed by %s", err.Error())
	}
	fp, err = Open("*", "w")
	if err == nil {
		t.Fatalf("NG: Open(\"*\") should failed")
	} else {
		print("OK: Open(\"*\") failed by " + err.Error() + "\n")
	}
}

// vim:set fenc=utf8:

Update test for last version of ansicfile


package main

import (
	"../../pkg/netutil"
	"flag"
	"log"
	"syscall"
)

var (
	addr string
	conf string
)

func init() {
	flag.StringVar(&addr, "addr", "", "external address to bind (e.g. 'tcp://:80')")
	flag.StringVar(&conf, "conf", "", "path to the process config file")
}

func main() {
	flag.Parse()

	// TODO: If required should not be a flag?
	// TODO: refactor this
	if addr == "" {
		log.Fatal("Missing required flag: addr")
	}
	if conf == "" {
		log.Fatal("Missing required flag: conf")
	}

	socket, err := netutil.BindFile(addr)
	if err != nil {
		log.Fatal("OOPS", err)
	}
	log.Print(socket)

	manager := NewManager(conf, socket)
	go manager.Run()

	go OnSignal(manager.Restart, syscall.SIGHUP)
	go OnSignal(manager.Shutdown, syscall.SIGTERM, syscall.SIGINT)

	manager.OnShutdown.Wait()

	log.Println("Bye!")
}

package main

import (
	"../../pkg/netutil"
	"flag"
	"log"
	"os"
	"syscall"
)

var (
	addr string
	conf string
)

func init() {
	flag.StringVar(&addr, "addr", os.Getenv("CRANK_ADDR"), "external address to bind (e.g. 'tcp://:80')")
	flag.StringVar(&conf, "conf", os.Getenv("CRANK_CONF"), "path to the process config file")
}

func main() {
	flag.Parse()

	// TODO: If required should not be a flag?
	// TODO: refactor this
	if addr == "" {
		log.Fatal("Missing required flag: addr")
	}
	if conf == "" {
		log.Fatal("Missing required flag: conf")
	}

	socket, err := netutil.BindFile(addr)
	if err != nil {
		log.Fatal("OOPS", err)
	}
	log.Print(socket)

	manager := NewManager(conf, socket)
	go manager.Run()

	go OnSignal(manager.Restart, syscall.SIGHUP)
	go OnSignal(manager.Shutdown, syscall.SIGTERM, syscall.SIGINT)

	manager.OnShutdown.Wait()

	log.Println("Bye!")
}

Allow to pass crank opts as environment variables


/*
 * Copyright 2018 the original author or 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 global

import "os"

var CLI_VERSION = "0.0.4"

var RIFF_VERSION = "0.0.4-snapshot"

func init() {
	version := os.Getenv("RIFF_VERSION")
	if version != "" {
		RIFF_VERSION = version
	}
}

/*
 * Copyright 2018 the original author or 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 global

import "os"

var CLI_VERSION = "0.0.4"

var RIFF_VERSION = "latest"

func init() {
	version := os.Getenv("RIFF_VERSION")
	if version != "" {
		RIFF_VERSION = version
	}
}

Use latest for function invoker version


package utils

import (
	"fmt"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
)

// TestDB initialize a db for testing
func TestDB() *gorm.DB {
	dbuser, dbpwd, dbname := "qor", "qor", "qor_test"

	if os.Getenv("TEST_ENV") == "CI" {
		dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD")
	}

	var db gorm.DB
	var err error

	if os.Getenv("TEST_DB") == "postgres" {
		db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", dbuser, dbpwd, dbname))
	} else {
		// CREATE USER 'qor'@'localhost' IDENTIFIED BY 'qor';
		// CREATE DATABASE qor_test;
		// GRANT ALL ON qor_test.* TO 'qor'@'localhost';
		db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname))
	}

	if err != nil {
		panic(err)
	}

	return &db
}

package utils

import (
	"fmt"
	"os"

	_ "github.com/go-sql-driver/mysql"
	"github.com/jinzhu/gorm"
	_ "github.com/lib/pq"
)

// TestDB initialize a db for testing
func TestDB() *gorm.DB {
	dbuser, dbpwd, dbname := "qor", "qor", "qor_test"

	if os.Getenv("TEST_ENV") == "CI" {
		dbuser, dbpwd = os.Getenv("DB_USER"), os.Getenv("DB_PWD")
	}

	var db *gorm.DB
	var err error

	if os.Getenv("TEST_DB") == "postgres" {
		db, err = gorm.Open("postgres", fmt.Sprintf("postgres://%s:%s@localhost/%s?sslmode=disable", dbuser, dbpwd, dbname))
	} else {
		// CREATE USER 'qor'@'localhost' IDENTIFIED BY 'qor';
		// CREATE DATABASE qor_test;
		// GRANT ALL ON qor_test.* TO 'qor'@'localhost';
		db, err = gorm.Open("mysql", fmt.Sprintf("%s:%s@/%s?charset=utf8&parseTime=True&loc=Local", dbuser, dbpwd, dbname))
	}

	if err != nil {
		panic(err)
	}

	return db
}

Fix GORM v1 compile error


package main

import (
	"encoding/json"
	"fmt"
	"github.com/imdario/mergo"
	"io/ioutil"
)

// Configuration is the configuration type
type Configuration struct {
	Environment
	Environments map[string]Environment `json:"environments"`
}

// Load open, read and parse the given configuration file
func Load(filename string) (Configuration, error) {
	var c Configuration

	raw, err := ioutil.ReadFile(filename)
	if err != nil {
		return c, err
	}

	err = json.Unmarshal(raw, &c)
	if err != nil {
		return c, err
	}

	return c, nil
}

// Env return the requested environment from the configuration
func (c Configuration) Env(name string) (Environment, error) {
	environment := c.Environment

	if name == "default" {
		return environment, nil
	}

	overrides, found := c.Environments[name]
	if !found {
		return Environment{}, fmt.Errorf("unknown environment %s", name)
	}

	_ = mergo.Merge(&environment, overrides) // No error can possibly occur here
	return environment, nil
}

package main

import (
	"encoding/json"
	"fmt"
	"github.com/imdario/mergo"
	"io/ioutil"
)

// Configuration is the configuration type
type Configuration struct {
	Environment
	Environments map[string]Environment `json:"environments"`
}

// Load open, read and parse the given configuration file
func Load(filename string) (Configuration, error) {
	var c Configuration

	raw, err := ioutil.ReadFile(filename)
	if err != nil {
		return c, err
	}

	err = json.Unmarshal(raw, &c)
	if err != nil {
		return c, err
	}

	return c, nil
}

// Env return the requested environment from the configuration
func (c Configuration) Env(name string) (Environment, error) {
	if name == "default" {
		return c.Environment, nil
	}

	overrides, found := c.Environments[name]
	if !found {
		return Environment{}, fmt.Errorf("unknown environment %s", name)
	}

	_ = mergo.Merge(&overrides, c.Environment) // No error can possibly occur here
	return overrides, nil
}

Fix the Configuration.Env to follow the breaking-change of the mergo library


package aws

import (
	"testing"

	"github.com/hashicorp/terraform/helper/resource"
)

func TestAccCloudFrontDistribution_importBasic(t *testing.T) {
	resourceName := "aws_cloudfront_distribution.s3_distribution"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckCloudFrontDistributionDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSCloudFrontDistributionS3Config,
			},
			resource.TestStep{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
				// Ignore retain_on_delete since it doesn't come from the AWS
				// API.
				ImportStateVerifyIgnore: []string{"retain_on_delete"},
			},
		},
	})
}

package aws

import (
	"testing"

	"github.com/hashicorp/terraform/helper/resource"
)

func TestAccAWSCloudFrontDistribution_importBasic(t *testing.T) {
	resourceName := "aws_cloudfront_distribution.s3_distribution"

	resource.Test(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckCloudFrontDistributionDestroy,
		Steps: []resource.TestStep{
			resource.TestStep{
				Config: testAccAWSCloudFrontDistributionS3Config,
			},
			resource.TestStep{
				ResourceName:      resourceName,
				ImportState:       true,
				ImportStateVerify: true,
				// Ignore retain_on_delete since it doesn't come from the AWS
				// API.
				ImportStateVerifyIgnore: []string{"retain_on_delete"},
			},
		},
	})
}

Rename the Basic Import test for CloudFront distributions


package main

import (
	"encoding/json"
	"fmt"

	"github.com/spf13/pflag"
	"k8s.io/cloud-provider-gcp/cmd/kubectl-gke-exec-auth-plugin/provider"
	"k8s.io/component-base/version/verflag"
)

func main() {
	pflag.Parse()
	verflag.PrintAndExitIfRequested()

	ec, err := provider.ExecCredential()
	if err != nil {
		msg := fmt.Errorf("unable to retrieve access token for GKE. Error : %v", err)
		panic(msg)
	}
	fmt.Printf("%s", formatToJSON(ec))
}

func formatToJSON(i interface{}) string {
	s, _ := json.MarshalIndent(i, "", "    ")
	return string(s)
}

package main

import (
	"encoding/json"
	"fmt"

	"github.com/spf13/pflag"
	"k8s.io/cloud-provider-gcp/cmd/kubectl-gke-exec-auth-plugin/provider"
	"k8s.io/component-base/version/verflag"
)

func main() {
	pflag.Parse()
	verflag.PrintAndExitIfRequested()

	ec, err := provider.ExecCredential()
	if err != nil {
		msg := fmt.Errorf("unable to retrieve access token for GKE. Error : %v\n", err)
		panic(msg)
	}

	ecStr, err := formatToJSON(ec)
	if err != nil {
		msg := fmt.Errorf("unable to convert ExecCredential object to json format. Error :%v\n", err)
		panic(msg)
	}
	fmt.Printf("%s", ecStr)
}

func formatToJSON(i interface{}) (string, error) {
	s, err := json.MarshalIndent(i, "", "    ")
	if err != nil {
		return "", err
	}
	return string(s), nil
}

Handle error message from json formatting.


/*
Copyright 2019 The Tekton 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 v1alpha1_test

import (
	"testing"

	"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
	"knative.dev/pkg/webhook"
)

func TestTypes(t *testing.T) {
	// Assert that types satisfy webhook interface.
	var _ webhook.GenericCRD = (*v1alpha1.ClusterTask)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.TaskRun)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.PipelineResource)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.Task)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.TaskRun)(nil)
}

/*
Copyright 2019 The Tekton 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 v1alpha1_test

import (
	"testing"

	"github.com/tektoncd/pipeline/pkg/apis/pipeline/v1alpha1"
	"knative.dev/pkg/webhook"
)

func TestTypes(t *testing.T) {
	// Assert that types satisfy webhook interface.
	var _ webhook.GenericCRD = (*v1alpha1.ClusterTask)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.TaskRun)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.PipelineResource)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.Task)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.TaskRun)(nil)
	var _ webhook.GenericCRD = (*v1alpha1.Condition)(nil)
}

Make sure v1alpha1.Condition satisfy webhook.GenericCRD ⚙


package kubeconfig

import "html/template"

const (
	tokenTemplateText = `apiVersion: v1
kind: Config
clusters:
{{- range .Nodes}}
- name: "{{.ClusterName}}"
  cluster:
    server: "{{.Server}}"
{{- if ne .Cert "" }}
    certificate-authority-data: "{{.Cert}}"
{{- end }}
{{- end}}

users:
- name: "{{.User}}"
  user:
    token: "{{.Token}}"

contexts:
{{- range .Nodes}}
- name: "{{.ClusterName}}"
  context:
    user: "{{.User}}"
    cluster: "{{.ClusterName}}"
{{- end}}

current-context: "{{.ClusterName}}"
`

	basicTemplateText = `apiVersion: v1
kind: Config
clusters:
- name: "{{.ClusterName}}"
  cluster:
    server: "https://{{.Host}}"
    api-version: v1

users:
- name: "{{.User}}"
  user:
    username: "{{.Username}}"
    password: "{{.Password}}"

contexts:
- name: "{{.ClusterName}}"
  context:
    user: "{{.User}}"
    cluster: "{{.ClusterName}}"

current-context: "{{.ClusterName}}"
`
)

var (
	basicTemplate = template.Must(template.New("basicTemplate").Parse(basicTemplateText))
	tokenTemplate = template.Must(template.New("tokenTemplate").Parse(tokenTemplateText))
)

package kubeconfig

import "html/template"

const (
	tokenTemplateText = `apiVersion: v1
kind: Config
clusters:
{{- range .Nodes}}
- name: "{{.ClusterName}}"
  cluster:
    server: "{{.Server}}"
{{- if ne .Cert "" }}
    certificate-authority-data: "{{.Cert}}"
{{- end }}
{{- end}}

users:
- name: "{{.ClusterName}}"
  user:
    token: "{{.Token}}"

contexts:
{{- range .Nodes}}
- name: "{{.ClusterName}}"
  context:
    user: "{{.ClusterName}}"
    cluster: "{{.ClusterName}}"
{{- end}}

current-context: "{{.ClusterName}}"
`

	basicTemplateText = `apiVersion: v1
kind: Config
clusters:
- name: "{{.ClusterName}}"
  cluster:
    server: "https://{{.Host}}"
    api-version: v1

users:
- name: "{{.ClusterName}}"
  user:
    username: "{{.Username}}"
    password: "{{.Password}}"

contexts:
- name: "{{.ClusterName}}"
  context:
    user: "{{.ClusterName}}"
    cluster: "{{.ClusterName}}"

current-context: "{{.ClusterName}}"
`
)

var (
	basicTemplate = template.Must(template.New("basicTemplate").Parse(basicTemplateText))
	tokenTemplate = template.Must(template.New("tokenTemplate").Parse(tokenTemplateText))
)

Use ClusterName for KubeConfig User's name


package configeur

import (
	"fmt"
	"testing"
)

func TestFlags(t *testing.T) {
	f := Flag{
		args: []string{"exec", "--x=2", "--y=four five six seven"},
	}

	if v, _ := f.String("x"); v != "2" {
		fmt.Println(v)
		t.Fail()
	}

	if v, _ := f.String("y"); v != "four five six seven" {
		fmt.Println(v)
		t.Fail()
	}
}

package configeur

import (
	"testing"
)

func TestFlagStrings(t *testing.T) {
	f, ff := createFlag(t, "--x=hello", `--z=hello world`, "--y=22")

	test(value(f.String("x")), "hello", ff)
	test(value(f.String("z")), "hello world", ff)
	test(value(f.String("y")), "22", ff)
}

func TestFlagsInts(t *testing.T) {
	f, ff := createFlag(t, "--x=2", "--z=-1")

	test(value(f.Int("x")), 2, ff)
	test(value(f.Int("z")), -1, ff)
}

func TestFlagsBools(t *testing.T) {
	f, ff := createFlag(t, "--x=T", "--z=F")

	test(value(f.Bool("x")), true, ff)
	test(value(f.Bool("z")), false, ff)
}

func createFlag(t *testing.T, args ...string) (Flag, func()) {
	f := Flag{
		args: append([]string{"executable"}, args...),
	}

	ff := normalFailFunc(t)

	return f, ff
}

Add updated testing for Flag using the new suite


package pewpew

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

func runRequest(req http.Request, client *http.Client) (response *http.Response, stat RequestStat) {
	reqStartTime := time.Now()
	response, responseErr := (*client).Do(&req)
	reqEndTime := time.Now()

	if responseErr != nil {
		stat = RequestStat{
			Proto:           req.Proto,
			URL:             req.URL.String(),
			Method:          req.Method,
			StartTime:       reqStartTime,
			EndTime:         reqEndTime,
			Duration:        reqEndTime.Sub(reqStartTime),
			StatusCode:      0,
			Error:           responseErr,
			DataTransferred: 0,
		}
		return
	}

	//get size of request
	reqDump, _ := httputil.DumpRequestOut(&req, true)
	respDump, _ := httputil.DumpResponse(response, true)
	totalSizeSentBytes := len(reqDump)
	totalSizeReceivedBytes := len(respDump)
	totalSizeBytes := totalSizeSentBytes + totalSizeReceivedBytes

	stat = RequestStat{
		Proto:           req.Proto,
		URL:             req.URL.String(),
		Method:          req.Method,
		StartTime:       reqStartTime,
		EndTime:         reqEndTime,
		Duration:        reqEndTime.Sub(reqStartTime),
		StatusCode:      response.StatusCode,
		Error:           responseErr,
		DataTransferred: totalSizeBytes,
	}
	return
}

package pewpew

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

func runRequest(req http.Request, client *http.Client) (response *http.Response, stat RequestStat) {
	reqStartTime := time.Now()
	response, responseErr := (*client).Do(&req)
	reqEndTime := time.Now()

	if responseErr != nil {
		stat = RequestStat{
			Proto:           req.Proto,
			URL:             req.URL.String(),
			Method:          req.Method,
			StartTime:       reqStartTime,
			EndTime:         reqEndTime,
			Duration:        reqEndTime.Sub(reqStartTime),
			StatusCode:      0,
			Error:           responseErr,
			DataTransferred: 0,
		}
		return
	}

	//get size of request
	reqDump, _ := httputil.DumpRequestOut(&req, true)
	respDump, _ := httputil.DumpResponse(response, true)
	totalSizeSentBytes := len(reqDump)
	totalSizeReceivedBytes := len(respDump)
	totalSizeBytes := totalSizeSentBytes + totalSizeReceivedBytes

	stat = RequestStat{
		Proto:           response.Proto,
		URL:             req.URL.String(),
		Method:          req.Method,
		StartTime:       reqStartTime,
		EndTime:         reqEndTime,
		Duration:        reqEndTime.Sub(reqStartTime),
		StatusCode:      response.StatusCode,
		Error:           responseErr,
		DataTransferred: totalSizeBytes,
	}
	return
}

Fix mistake printing wrong HTTP proto


package loggo

import (
	"path"
	"time"
)

// TestLogValues represents a single logging call.
type TestLogValues struct {
	Level     Level
	Module    string
	Filename  string
	Line      int
	Timestamp time.Time
	Message   string
}

// TestWriter is a useful Writer for testing purposes.  Each component of the
// logging message is stored in the Log array.
type TestWriter struct {
	Log []TestLogValues
}

// Write saves the params as members in the TestLogValues struct appended to the Log array.
func (writer *TestWriter) Write(level Level, module, filename string, line int, timestamp time.Time, message string) {
	if writer.Log == nil {
		writer.Log = []TestLogValues{}
	}
	writer.Log = append(writer.Log,
		TestLogValues{level, module, path.Base(filename), line, timestamp, message})
}

// Clear removes any saved log messages.
func (writer *TestWriter) Clear() {
	writer.Log = []TestLogValues{}
}

package loggo

import (
	"path"
	"sync"
	"time"
)

// TestLogValues represents a single logging call.
type TestLogValues struct {
	Level     Level
	Module    string
	Filename  string
	Line      int
	Timestamp time.Time
	Message   string
}

// TestWriter is a useful Writer for testing purposes.  Each component of the
// logging message is stored in the Log array.
type TestWriter struct {
	mu  sync.Mutex
	Log []TestLogValues
}

// Write saves the params as members in the TestLogValues struct appended to the Log array.
func (writer *TestWriter) Write(level Level, module, filename string, line int, timestamp time.Time, message string) {
	writer.mu.Lock()
	defer writer.mu.Unlock()
	if writer.Log == nil {
		writer.Log = []TestLogValues{}
	}
	writer.Log = append(writer.Log,
		TestLogValues{level, module, path.Base(filename), line, timestamp, message})
}

// Clear removes any saved log messages.
func (writer *TestWriter) Clear() {
	writer.mu.Lock()
	defer writer.mu.Unlock()
	writer.Log = []TestLogValues{}
}

Fix data race in test writer


package main

import (
	"flag"
	"testing"
)

func TestDefaultDisco(t *testing.T) {
	v := discoAliases[defaultDisco]
	if v == "" {
		t.Fatalf("alias for %q is zero; all aliases: %v", defaultDisco, discoAliases)
	}
}

func TestDiscoAliasFlag(t *testing.T) {
	tests := []struct {
		a    discoAliasFlag
		args []string
		want string
	}{
		{defaultDisco, []string{"-d", "letsencrypt-staging"}, discoAliases["letsencrypt-staging"]},
		{defaultDisco, []string{"-d", "https://disco"}, "https://disco"},
	}
	for i, test := range tests {
		var a discoAliasFlag = test.a
		fs := flag.NewFlagSet("test", flag.ContinueOnError)
		fs.Var(&a, "d", "")
		if err := fs.Parse(test.args); err != nil {
			t.Errorf("%d: parse(%v): %v", i, test.args, err)
			continue
		}
		if a.String() != test.want {
			t.Errorf("%d: a = %q; want %q", i, a, test.want)
		}
	}
}

package main

import (
	"flag"
	"testing"
)

func TestDefaultDisco(t *testing.T) {
	v := discoAliases[defaultDisco]
	if v == "" {
		t.Fatalf("alias for %q is zero; all aliases: %v", defaultDisco, discoAliases)
	}
}

func TestDiscoAliasFlag(t *testing.T) {
	tests := []struct {
		a    discoAliasFlag
		args []string
		want string
	}{
		{defaultDisco, []string{"-d", "letsencrypt-staging"}, discoAliases["letsencrypt-staging"]},
		{defaultDisco, []string{"-d", "https://disco"}, "https://disco"},
	}
	for i, test := range tests {
		var a = test.a
		fs := flag.NewFlagSet("test", flag.ContinueOnError)
		fs.Var(&a, "d", "")
		if err := fs.Parse(test.args); err != nil {
			t.Errorf("%d: parse(%v): %v", i, test.args, err)
			continue
		}
		if a.String() != test.want {
			t.Errorf("%d: a = %q; want %q", i, a, test.want)
		}
	}
}

Fix golint using type in variable declaration


package data

import (
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Organization struct {
	ID         bson.ObjectId `bson:"_id"`
	Name       string        `bson:"name"`
	OwnerID    bson.ObjectId `bson:"owner_id"`
	CreatorID  bson.ObjectId `bson:"creator_id"`
	CreatedAt  time.Time     `bson:"created_at"`
	ModifiedAt time.Time     `bson:"modified_at"`
}

func GetOraganization(id bson.ObjectId) (*Organization, error) {
	org := Organization{}
	err := sess.DB("").C(organizationC).FindId(id).One(&org)
	if err == mgo.ErrNotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &org, nil
}

func (o *Organization) Put() error {
	o.ModifiedAt = time.Now()

	if o.ID == "" {
		o.ID = bson.NewObjectId()
		o.CreatedAt = o.ModifiedAt
	}
	_, err := sess.DB("").C(organizationC).UpsertId(o.ID, o)
	return err
}

package data

import (
	"time"

	"gopkg.in/mgo.v2"
	"gopkg.in/mgo.v2/bson"
)

type Organization struct {
	ID         bson.ObjectId `bson:"_id"`
	Name       string        `bson:"name"`
	OwnerID    bson.ObjectId `bson:"owner_id"`
	CreatorID  bson.ObjectId `bson:"creator_id"`
	CreatedAt  time.Time     `bson:"created_at"`
	ModifiedAt time.Time     `bson:"modified_at"`
}

func GetOraganization(id bson.ObjectId) (*Organization, error) {
	org := Organization{}
	err := sess.DB("").C(organizationC).FindId(id).One(&org)
	if err == mgo.ErrNotFound {
		return nil, nil
	}
	if err != nil {
		return nil, err
	}
	return &org, nil
}

func ListOraganizationsOwner(ownerID bson.ObjectId, skip, limit int) ([]Organization, error) {
	orgs := []Organization{}
	err := sess.DB("").C(organizationC).
		Find(bson.M{"owner_id": ownerID}).
		Skip(skip).
		Limit(limit).
		Sort("-created_at").
		All(&orgs)
	if err != nil {
		return nil, err
	}
	return orgs, nil
}

func (o *Organization) Put() error {
	o.ModifiedAt = time.Now()

	if o.ID == "" {
		o.ID = bson.NewObjectId()
		o.CreatedAt = o.ModifiedAt
	}
	_, err := sess.DB("").C(organizationC).UpsertId(o.ID, o)
	return err
}

Implement ListOrganizationOwner function in data


package action

import (
	"github.com/Masterminds/glide/godep"
	"github.com/Masterminds/glide/msg"
)

// ImportGodep imports a GPM file.
func ImportGodep(dest string) {
	base := "."
	config := EnsureConfig()
	if !godep.Has(base) {
		msg.Die("No Godep data found.")
	}
	deps, err := godep.Parse(base)
	if err != nil {
		msg.Die("Failed to extract Godeps file: %s", err)
	}
	appendImports(deps, config)
	writeConfigToFileOrStdout(config, dest)
}

package action

import (
	"github.com/Masterminds/glide/godep"
	"github.com/Masterminds/glide/msg"
)

// ImportGodep imports a Godep file.
func ImportGodep(dest string) {
	base := "."
	config := EnsureConfig()
	if !godep.Has(base) {
		msg.Die("No Godep data found.")
	}
	deps, err := godep.Parse(base)
	if err != nil {
		msg.Die("Failed to extract Godeps file: %s", err)
	}
	appendImports(deps, config)
	writeConfigToFileOrStdout(config, dest)
}

Fix a typo in comment


package meta

// SeekTable contains one or more precalculated audio seek points.
//
// ref: https://www.xiph.org/flac/format.html#metadata_block_seektable
type SeekTable struct{}

package meta

// SeekTable contains one or more precalculated audio frame seek points.
//
// ref: https://www.xiph.org/flac/format.html#metadata_block_seektable
type SeekTable struct {
	// One or more seek points.
	Points []SeekPoint
}

// A SeekPoint specifies the byte offset and initial sample number of a given
// target frame.
//
// ref: https://www.xiph.org/flac/format.html#seekpoint
type SeekPoint struct {
	// Sample number of the first sample in the target frame, or
	// 0xFFFFFFFFFFFFFFFF for a placeholder point.
	SampleNum uint64
	// Offset in bytes from the first byte of the first frame header to the first
	// byte of the target frame's header.
	Offset uint64
	// Number of samples in the target frame.
	NSamples uint16
}

Add SeekTable and SeekPoint definitions.


package librariesio

import (
	"fmt"
	"net/http"
)

// Project that holds a name field
type Project struct {
	Name string `json:"name"`
}

// GetProject returns information about a project and it's versions.
// GET https://libraries.io/api/:platform/:name
func (c *Client) GetProject(platform string, name string) (*Project, *http.Response, error) {
	urlStr := fmt.Sprintf("%v/%v", platform, name)

	request, err := c.NewRequest("GET", urlStr, nil)

	if err != nil {
		return nil, nil, err
	}

	project := new(Project)
	response, err := c.Do(request, project)
	if err != nil {
		return nil, response, err
	}

	return project, response, nil
}

package librariesio

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

// Project represents a project on libraries.io
type Project struct {
	Description              string    `json:"description,omitempty"`
	Forks                    int       `json:"forks,omitempty"`
	Homepage                 string    `json:"homepage,omitempty"`
	Keywords                 []string  `json:"keywords,omitempty"`
	Language                 string    `json:"language,omitempty"`
	LatestReleaseNumber      string    `json:"latest_release_number,omitempty"`
	LatestReleasePublishedAt time.Time `json:"latest_release_published_at,omitempty"`
	LatestStableRelease      Release   `json:"latest_stable_release,omitempty"`
	Name                     string    `json:"name,omitempty"`
	NormalizedLicenses       []string  `json:"normalized_licenses,omitempty"`
	PackageManagerURL        string    `json:"package_manager_url,omitempty"`
	Platform                 string    `json:"platform,omitempty"`
	Rank                     int       `json:"rank,omitempty"`
	Stars                    int       `json:"stars,omitempty"`
	Status                   string    `json:"status,omitempty"`
	Versions                 []Release `json:"versions,omitempty"`
}

// Release represents a release of the project
type Release struct {
	Number      string    `json:"number,omitempty"`
	PublishedAt time.Time `json:"published_at,omitempty"`
}

// GetProject returns information about a project and it's versions.
// GET https://libraries.io/api/:platform/:name
func (c *Client) GetProject(platform string, name string) (*Project, *http.Response, error) {
	urlStr := fmt.Sprintf("%v/%v", platform, name)

	request, err := c.NewRequest("GET", urlStr, nil)

	if err != nil {
		return nil, nil, err
	}

	project := new(Project)
	response, err := c.Do(request, project)
	if err != nil {
		return nil, response, err
	}

	return project, response, nil
}

Add other fields to Project struct


package action

import (
	"encoding/gob"
	"fmt"
)

type CreateSchema struct {
	SchemaName string
}

// Register type for gob
func init() {
	gob.Register(&CreateSchema{})
}

func (a *CreateSchema) Execute(c *Context) error {
	_, err := c.Tx.Exec(
		fmt.Sprintf("CREATE SCHEMA IF NOT EXISTS \"%s\";", a.SchemaName),
	)

	return err
}

func (a *CreateSchema) Filter(targetExpression string) bool {
	return IsInTargetExpression(&targetExpression, &a.SchemaName, nil)
}

func (a *CreateSchema) NeedsSeparatedBatch() bool {
	return false
}

package action

import (
	"encoding/gob"
	"fmt"
)

type CreateSchema struct {
	SchemaName string
}

// Register type for gob
func init() {
	gob.Register(&CreateSchema{})
}

func (a *CreateSchema) Execute(c *Context) error {
	_, err := c.Tx.Exec(
		fmt.Sprintf(`
			DO $$
			BEGIN
				IF NOT EXISTS (SELECT 1 FROM pg_namespace WHERE nspname = '%s') THEN
					CREATE SCHEMA %s;
				END IF;
			END
			$$
		`, a.SchemaName, a.SchemaName),
	)

	return err
}

func (a *CreateSchema) Filter(targetExpression string) bool {
	return IsInTargetExpression(&targetExpression, &a.SchemaName, nil)
}

func (a *CreateSchema) NeedsSeparatedBatch() bool {
	return false
}

Fix create schema action on postgres 9.2.


// +build release

package libkb

// Production run mode currently still unsafe.
// This will cause the build to fail for this tag on purpose.
//const DefaultRunMode = ProductionRunMode

// +build release

package libkb

// Production run mode currently...enabled!
const DefaultRunMode = ProductionRunMode

Enable DefaultRunMode for release builds


package letter

// FreqMap records the frequency of each rune in a given text.
type FreqMap map[rune]int

// Frequency counts the frequency of each rune in a given text and returns this
// data as a FreqMap.
func Frequency(s string) FreqMap {
	m := FreqMap{}
	for _, r := range s {
		m[r]++
	}
	return m
}

// ConcurrentFrequency counts the frequency of each rune in texts (concurrently)
// and returns a FreqMap.
func ConcurrentFrequency(texts []string) FreqMap {
	freqMaps := make(chan FreqMap, len(texts))

	for _, text := range texts {
		go writeFrequencyToChan(text, freqMaps)
	}

	result := make(FreqMap)

	// Merge freqMaps into result
	for range texts {
		freqMap := <-freqMaps
		for r, frequency := range freqMap {
			result[r] += frequency
		}
	}

	return result
}

func writeFrequencyToChan(s string, c chan<- FreqMap) {
	c <- Frequency(s)
}

package letter

// FreqMap records the frequency of each rune in a given text.
type FreqMap map[rune]int

// Frequency counts the frequency of each rune in a given text and returns this
// data as a FreqMap.
func Frequency(s string) FreqMap {
	m := FreqMap{}
	for _, r := range s {
		m[r]++
	}
	return m
}

// ConcurrentFrequency counts the frequency of each rune in texts (concurrently)
// and returns a FreqMap.
func ConcurrentFrequency(texts []string) FreqMap {
	freqMaps := make(chan FreqMap, len(texts))

	for _, text := range texts {
		go func(t string, c chan<- FreqMap) {
			c <- Frequency(t)
		}(text, freqMaps)
	}

	result := make(FreqMap)

	// Merge freqMaps into result
	for range texts {
		freqMap := <-freqMaps
		for r, frequency := range freqMap {
			result[r] += frequency
		}
	}

	return result
}

Replace extract func w/ anon func


// Copyright 2019 The Ebiten 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.

//go:build ((ios && arm) || (ios && arm64)) && !ebitengl
// +build ios,arm ios,arm64
// +build !ebitengl

package mobile

import (
	"fmt"

	"github.com/hajimehoshi/ebiten/v2/internal/driver"
	"github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver/metal"
	"github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver/metal/mtl"
)

func (*UserInterface) Graphics() driver.Graphics {
	if _, err := mtl.CreateSystemDefaultDevice(); err != nil {
		panic(fmt.Sprintf("ebiten: mtl.CreateSystemDefaultDevice failed on iOS: %v", err))
	}
	return metal.Get()
}

// Copyright 2019 The Ebiten 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.

//go:build ((ios && arm) || (ios && arm64)) && !ebitengl
// +build ios,arm ios,arm64
// +build !ebitengl

package mobile

import (
	"fmt"

	"github.com/hajimehoshi/ebiten/v2/internal/driver"
	"github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver/metal"
	"github.com/hajimehoshi/ebiten/v2/internal/graphicsdriver/metal/mtl"
)

func (*UserInterface) Graphics() driver.Graphics {
	if _, err := mtl.CreateSystemDefaultDevice(); err != nil {
		panic(fmt.Sprintf("mobile: mtl.CreateSystemDefaultDevice failed on iOS: %v", err))
	}
	return metal.Get()
}

Fix the package name in a panic message


package acme

// ChallengeProvider presents the solution to a challenge available to be solved
// CleanUp will be called by the challenge if Present ends in a non-error state.
type ChallengeProvider interface {
	Present(domain, token, keyAuth string) error
	CleanUp(domain, token, keyAuth string) error
}

package acme

// ChallengeProvider enables implementing a custom challenge
// provider. Present presents the solution to a challenge available to
// be solved. CleanUp will be called by the challenge if Present ends
// in a non-error state.
type ChallengeProvider interface {
	Present(domain, token, keyAuth string) error
	CleanUp(domain, token, keyAuth string) error
}

Improve wording of ChallengeProvider comment


package gitmedia

import (
	".."
	"../queuedir"
	"strings"
)

type QueuesCommand struct {
	*Command
}

func (c *QueuesCommand) Run() {
	err := gitmedia.WalkQueues(func(name string, queue *queuedir.Queue) error {
		gitmedia.Print(name)
		return queue.Walk(func(id string, body []byte) error {
			parts := strings.Split(string(body), ":")
			if len(parts) == 2 {
				gitmedia.Print("  " + parts[1])
			} else {
				gitmedia.Print("  " + parts[0])
			}
			return nil
		})
	})

	if err != nil {
		gitmedia.Panic(err, "Error walking queues")
	}
}

func init() {
	registerCommand("queues", func(c *Command) RunnableCommand {
		return &QueuesCommand{Command: c}
	})
}

package gitmedia

import (
	".."
	"../queuedir"
	"os"
	"path/filepath"
	"strings"
)

type QueuesCommand struct {
	*Command
}

func (c *QueuesCommand) Run() {
	err := gitmedia.WalkQueues(func(name string, queue *queuedir.Queue) error {
		wd, _ := os.Getwd()
		gitmedia.Print(name)
		return queue.Walk(func(id string, body []byte) error {
			parts := strings.Split(string(body), ":")
			if len(parts) == 2 {
				absPath := filepath.Join(gitmedia.LocalWorkingDir, parts[1])
				relPath, _ := filepath.Rel(wd, absPath)
				gitmedia.Print("  " + relPath)
			} else {
				gitmedia.Print("  " + parts[0])
			}
			return nil
		})
	})

	if err != nil {
		gitmedia.Panic(err, "Error walking queues")
	}
}

func init() {
	registerCommand("queues", func(c *Command) RunnableCommand {
		return &QueuesCommand{Command: c}
	})
}

Make queues list output consistent with git status


package main

import (
	"os"
	"testing"

	"github.com/rollbar/rollbar-go"
	"github.com/stretchr/testify/assert"
)

func TestSetupEnv(t *testing.T) {
	setupEnv()
	port := os.Getenv("PORT")
	assert.NotEqual(t, port, "")
}

func TestSetupRollbar(t *testing.T) {
	setupRollbar()
	assert.Equal(t, rollbar.Token(), os.Getenv("ROLLBAR_SERVER_TOKEN"))
	assert.Equal(t, rollbar.Environment(), os.Getenv("ENVIRONMENT"))
}

func TestGetLogger(t *testing.T) {
	origEnv := os.Getenv("ENVIRONMENT")
	defer func() { os.Setenv("ENVIRONMENt", origEnv) }()

	os.Setenv("ENVIRONMENT", "development")
	logger := getLogger()
	assert.NotNil(t, logger)

	os.Setenv("ENVIRONMENT", "production")
	logger = getLogger()
	assert.NotNil(t, logger)
}

package main

import (
	"os"
	"testing"

	"github.com/rollbar/rollbar-go"
	"github.com/stretchr/testify/assert"
	"go.uber.org/goleak"
)

func TestMain(m *testing.M) {
	rollbar.Close()
	goleak.VerifyTestMain(m)
}

func TestSetupEnv(t *testing.T) {
	setupEnv()
	port := os.Getenv("PORT")
	assert.NotEqual(t, port, "")
}

func TestSetupRollbar(t *testing.T) {
	setupRollbar()
	assert.Equal(t, rollbar.Token(), os.Getenv("ROLLBAR_SERVER_TOKEN"))
	assert.Equal(t, rollbar.Environment(), os.Getenv("ENVIRONMENT"))
}

func TestGetLogger(t *testing.T) {
	origEnv := os.Getenv("ENVIRONMENT")
	defer func() { os.Setenv("ENVIRONMENt", origEnv) }()

	os.Setenv("ENVIRONMENT", "development")
	logger := getLogger()
	assert.NotNil(t, logger)

	os.Setenv("ENVIRONMENT", "production")
	logger = getLogger()
	assert.NotNil(t, logger)
}

Add goleak to main package


package sanitized_anchor_name_test

import (
	"fmt"

	"github.com/shurcooL/go/github_flavored_markdown/sanitized_anchor_name"
)

func ExampleCreate() {
	anchorName := sanitized_anchor_name.Create("This is a header")

	fmt.Println(anchorName)

	// Output:
	// this-is-a-header
}

func ExampleCreate2() {
	fmt.Println(sanitized_anchor_name.Create("This is a header"))
	fmt.Println(sanitized_anchor_name.Create("This is also          a header"))
	fmt.Println(sanitized_anchor_name.Create("main.go"))
	fmt.Println(sanitized_anchor_name.Create("Article 123"))
	fmt.Println(sanitized_anchor_name.Create("<- Let's try this, shall we?"))
	fmt.Printf("%q\n", sanitized_anchor_name.Create("        "))
	fmt.Println(sanitized_anchor_name.Create("Hello, 世界"))

	// Output:
	// this-is-a-header
	// this-is-also-a-header
	// main-go
	// article-123
	// let-s-try-this-shall-we
	// ""
	// hello-世界
}

package sanitized_anchor_name_test

import (
	"fmt"

	"github.com/shurcooL/sanitized_anchor_name"
)

func ExampleCreate() {
	anchorName := sanitized_anchor_name.Create("This is a header")

	fmt.Println(anchorName)

	// Output:
	// this-is-a-header
}

func ExampleCreate2() {
	fmt.Println(sanitized_anchor_name.Create("This is a header"))
	fmt.Println(sanitized_anchor_name.Create("This is also          a header"))
	fmt.Println(sanitized_anchor_name.Create("main.go"))
	fmt.Println(sanitized_anchor_name.Create("Article 123"))
	fmt.Println(sanitized_anchor_name.Create("<- Let's try this, shall we?"))
	fmt.Printf("%q\n", sanitized_anchor_name.Create("        "))
	fmt.Println(sanitized_anchor_name.Create("Hello, 世界"))

	// Output:
	// this-is-a-header
	// this-is-also-a-header
	// main-go
	// article-123
	// let-s-try-this-shall-we
	// ""
	// hello-世界
}

Fix test to import moved package.


// Package utils contains common shared code.
package utils

import (
	"math"
	"time"
)

// Backoff holds the number of attempts as well as the min and max backoff delays.
type Backoff struct {
	attempt, Factor float64
	Min, Max        time.Duration
}

// Duration calculates the backoff delay and increments the attempts count.
func (b *Backoff) Duration(attempt float64) time.Duration {
	d := b.SetDuration(b.attempt)
	b.attempt++
	return d
}

// SetDuration calculates the backoff delay and caps it at the maximum delay.
func (b *Backoff) SetDuration(attempt float64) time.Duration {
	if b.Min == 0 {
		b.Min = 100 * time.Millisecond
	}

	if b.Max == 0 {
		b.Max = 10 * time.Second
	}

	// Calculate the wait duration.
	duration := float64(b.Min) * math.Pow(b.Factor, attempt)

	// Cap it at the maximum value.
	if duration > float64(b.Max) {
		return b.Max
	}

	return time.Duration(duration)
}

// Reset clears the number of attempts once the API call has succeeded.
func (b *Backoff) Reset() {
	b.attempt = 0
}

// Attempt returns the number of times the API call has failed.
func (b *Backoff) Attempt() float64 {
	return b.attempt
}

// Package utils contains common shared code.
package utils

import (
	"math"
	"time"
)

// Backoff holds the number of attempts as well as the min and max backoff delays.
type Backoff struct {
	attempt, Factor int
	Min, Max        time.Duration
}

// Duration calculates the backoff delay and increments the attempts count.
func (b *Backoff) Duration(attempt int) time.Duration {
	d := b.CalcDuration(b.attempt)
	b.attempt++
	return d
}

// CalcDuration calculates the backoff delay and caps it at the maximum delay.
func (b *Backoff) CalcDuration(attempt int) time.Duration {
	if b.Min == 0 {
		b.Min = 100 * time.Millisecond
	}

	if b.Max == 0 {
		b.Max = 10 * time.Second
	}

	// Calculate the wait duration.
	duration := float64(b.Min) * math.Pow(float64(b.Factor), float64(attempt))

	// Cap it at the maximum value.
	if duration > float64(b.Max) {
		return b.Max
	}

	return time.Duration(duration)
}

// Reset clears the number of attempts once the API call has succeeded.
func (b *Backoff) Reset() {
	b.attempt = 0
}

// Attempt returns the number of times the API call has failed.
func (b *Backoff) Attempt() int {
	return b.attempt
}

Rename SetDuration to CalcDuration and change attempts and factor to ints.


package test_relate

import (
	"github.com/stephenalexbrowne/zoom"
	. "launchpad.net/gocheck"
	"testing"
)

// Gocheck setup...
func Test(t *testing.T) {
	TestingT(t)
}

type RelateSuite struct{}

var _ = Suite(&RelateSuite{})

func (s *RelateSuite) SetUpSuite(c *C) {

	zoom.Init(&zoom.Configuration{Database: 7})

	err := zoom.Register(&Person{}, "person")
	if err != nil {
		c.Error(err)
	}
}

func (s *RelateSuite) TearDownSuite(c *C) {
	zoom.UnregisterName("person")
	conn := zoom.GetConn()
	_, err := conn.Do("flushdb")
	if err != nil {
		c.Error(err)
	}
	conn.Close()
	zoom.Close()
}

package test_relate

import (
	"github.com/stephenalexbrowne/zoom"
	. "launchpad.net/gocheck"
	"testing"
)

// Gocheck setup...
func Test(t *testing.T) {
	TestingT(t)
}

type RelateSuite struct{}

var _ = Suite(&RelateSuite{})

func (s *RelateSuite) SetUpSuite(c *C) {

	zoom.Init(&zoom.Configuration{Database: 7})

	err := zoom.Register(&Person{}, "person")
	if err != nil {
		c.Error(err)
	}

	err = zoom.Register(&Pet{}, "pet")
	if err != nil {
		c.Error(err)
	}
}

func (s *RelateSuite) TearDownSuite(c *C) {

	zoom.UnregisterName("person")
	zoom.UnregisterName("pet")

	conn := zoom.GetConn()
	_, err := conn.Do("flushdb")
	if err != nil {
		c.Error(err)
	}
	conn.Close()

	zoom.Close()
}

func (s *RelateSuite) TestOneToOne(c *C) {
	person := NewPerson("Alex", 20)
	pet := NewPet("Billy", "barracuda")

	person.Pet = pet
	err := zoom.Save(person)
	if err != nil {
		c.Error(err)
	}

	// result, err := zoom.FindById("person", person.Id)
	// if err != nil {
	// 	c.Error(err)
	// }

	// person2, ok := result.(*Person)
	// if !ok {
	// 	c.Error("Couldn't type assert to *Person: ", person2)
	// }

	// pet2 := person2.Pet
	// c.Assert(pet2, NotNil)
	// c.Assert(pet2.Name, Equals, "Billy")
	// c.Assert(pet2.Kind, Equals, "barracuda")
}

Add some tests for relations


package handler

import (
	"time"

	"github.com/skygeario/skygear-server/pkg/server/skyerr"
)

var timeNow = func() time.Time { return time.Now().UTC() }

type serializedError struct {
	id  string
	err skyerr.Error
}

func newSerializedError(id string, err skyerr.Error) serializedError {
	return serializedError{
		id:  id,
		err: err,
	}
}

package handler

import (
	"encoding/json"
	"strings"
	"time"

	"github.com/skygeario/skygear-server/pkg/server/skyerr"
)

var timeNow = func() time.Time { return time.Now().UTC() }

type serializedError struct {
	id  string
	err skyerr.Error
}

func newSerializedError(id string, err skyerr.Error) serializedError {
	return serializedError{
		id:  id,
		err: err,
	}
}

func (s serializedError) MarshalJSON() ([]byte, error) {
	m := map[string]interface{}{
		"_type":   "error",
		"name":    s.err.Name(),
		"code":    s.err.Code(),
		"message": s.err.Message(),
	}
	if s.id != "" {
		m["_id"] = s.id

		ss := strings.SplitN(s.id, "/", 2)
		if len(ss) == 2 {
			m["_recordType"] = ss[0]
			m["_recordID"] = ss[1]
		}
	}
	if s.err.Info() != nil {
		m["info"] = s.err.Info()
	}

	return json.Marshal(m)
}

Fix record save error not serialized


package identity

import (
	"encoding/json"
	"errors"

	"github.com/google/uuid"
)

// Identity data to be encode in auth token
type Identity struct {
	ID    uuid.UUID `json:"id"`
	Email string    `json:"email"`
	Roles []string  `json:"roles"`
}

// FromGoogleData sets *i to a copy of data.
func (i *Identity) FromGoogleData(data json.RawMessage) error {
	if i == nil {
		return errors.New("auth.Identity: FromGoogleData on nil pointer")
	}
	//todo set props from google data
	return nil
}

// FromFacebookData sets *i to a copy of data.
func (i *Identity) FromFacebookData(data json.RawMessage) error {
	if i == nil {
		return errors.New("auth.Identity: FromFacebookData on nil pointer")
	}
	//todo set props from facebook data
	return nil
}

// New returns a new Identity
func New(id uuid.UUID, email string, roles []string) *Identity {
	return &Identity{id, email, roles}
}

package identity

import (
	"encoding/json"
	"errors"

	"github.com/google/uuid"
)

// Identity data to be encode in auth token
type Identity struct {
	ID    uuid.UUID `json:"id"`
	Email string    `json:"email"`
	Roles []string  `json:"roles"`
}

// FromGoogleData sets *i to a copy of data.
func (i *Identity) FromGoogleData(data json.RawMessage) error {
	if i == nil {
		return errors.New("auth.Identity: FromGoogleData on nil pointer")
	}

	err := json.Unmarshal(data, i)
	if err != nil {
		return err
	}

	id, err := uuid.NewRandom()
	if err != nil {
		return err
	}

	var defaultRoles []string
	i.ID = id
	i.Roles = defaultRoles

	return nil
}

// FromFacebookData sets *i to a copy of data.
func (i *Identity) FromFacebookData(data json.RawMessage) error {
	if i == nil {
		return errors.New("auth.Identity: FromFacebookData on nil pointer")
	}

	err := json.Unmarshal(data, i)
	if err != nil {
		return err
	}

	id, err := uuid.NewRandom()
	if err != nil {
		return err
	}

	var defaultRoles []string
	i.ID = id
	i.Roles = defaultRoles

	return nil
}

// New returns a new Identity
func New(id uuid.UUID, email string, roles []string) *Identity {
	return &Identity{id, email, roles}
}

Implement from social media methods


package distribution

import "net/rpc"

// Waiter is a struct that is returned by Go() method to be able to
// wait for a Node response. It handles the rpc.Call to be able to get
// errors if any.
type Waiter struct {
	Node    *Node
	rpcCall *rpc.Call
	client  *rpc.Client
}

// Wait for the response caller.
func (w *Waiter) Wait() {
	defer func(w *Waiter) {
		w.Node.Count--
		w.client.Close()
	}(w)
	<-w.rpcCall.Done
}

// Error returns the rpc.Call error if any.
func (w *Waiter) Error() error {
	return w.rpcCall.Error
}

package distribution

import (
	"errors"
	"net/rpc"
)

// Waiter is a struct that is returned by Go() method to be able to
// wait for a Node response. It handles the rpc.Call to be able to get
// errors if any.
type Waiter struct {
	Node    *Node
	rpcCall *rpc.Call
	client  *rpc.Client
}

// Wait for the response caller.
func (w *Waiter) Wait() {
	defer func(w *Waiter) {
		w.Node.Count--
		w.client.Close()
	}(w)
	<-w.rpcCall.Done
}

// Error returns the rpc.Call error if any.
func (w *Waiter) Error() error {
	if w.rpcCall == nil {
		return errors.New("RPC client is nil, maybe node " + w.Node.Addr + " is broken")
	}
	return w.rpcCall.Error
}

Handle "no rpcClient" error in Waiter.Error()


package storage

import (
	"net/http"
	"time"

	"github.com/docker/distribution"
	"github.com/docker/distribution/digest"
)

// layerReader implements Layer and provides facilities for reading and
// seeking.
type layerReader struct {
	fileReader

	digest digest.Digest
}

var _ distribution.Layer = &layerReader{}

func (lr *layerReader) Digest() digest.Digest {
	return lr.digest
}

func (lr *layerReader) Length() int64 {
	return lr.size
}

func (lr *layerReader) CreatedAt() time.Time {
	return lr.modtime
}

// Close the layer. Should be called when the resource is no longer needed.
func (lr *layerReader) Close() error {
	return lr.closeWithErr(distribution.ErrLayerClosed)
}

func (lr *layerReader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Docker-Content-Digest", lr.digest.String())

	if url, err := lr.fileReader.driver.URLFor(lr.path, map[string]interface{}{}); err == nil {
		http.Redirect(w, r, url, http.StatusTemporaryRedirect)
	}
	http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr)
}

package storage

import (
	"net/http"
	"time"

	"github.com/docker/distribution"
	"github.com/docker/distribution/digest"
)

// layerReader implements Layer and provides facilities for reading and
// seeking.
type layerReader struct {
	fileReader

	digest digest.Digest
}

var _ distribution.Layer = &layerReader{}

func (lr *layerReader) Digest() digest.Digest {
	return lr.digest
}

func (lr *layerReader) Length() int64 {
	return lr.size
}

func (lr *layerReader) CreatedAt() time.Time {
	return lr.modtime
}

// Close the layer. Should be called when the resource is no longer needed.
func (lr *layerReader) Close() error {
	return lr.closeWithErr(distribution.ErrLayerClosed)
}

func (lr *layerReader) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Docker-Content-Digest", lr.digest.String())

	if url, err := lr.fileReader.driver.URLFor(lr.path, map[string]interface{}{"method": r.Method}); err == nil {
		http.Redirect(w, r, url, http.StatusTemporaryRedirect)
	}
	http.ServeContent(w, r, lr.digest.String(), lr.CreatedAt(), lr)
}

Insert request method option storage driver URLFor


package mesos

import (
	"fmt"
	"strings"

	"github.com/CiscoCloud/mesos-consul/registry"
)

func (sj *StateJSON) GetFollowerById(id string) (string, error) {
	for _, f := range sj.Followers {

		if f.Id == id {
			return f.Hostname, nil
		}
	}

	return "", fmt.Errorf("Follower not found: %s", id)
}

// Task Methods

// GetCheck()
//   Build a Check structure from the Task labels
//
func (t *Task) GetCheck() *registry.Check {
	c := registry.DefaultCheck()

	for _, l := range t.Labels {
		k := strings.ToLower(l.Key)

		switch k {
		case "consul_http_check":
			c.HTTP = l.Value
		case "consul_script_check":
			c.Script = l.Value
		case "consul_ttl_check":
			c.TTL = l.Value
		case "consul_check_interval":
			c.Interval = l.Value
		}
	}

	return c
}

package mesos

import (
	"fmt"
	"strings"

	"github.com/CiscoCloud/mesos-consul/registry"
)

func (sj *StateJSON) GetFollowerById(id string) (string, error) {
	for _, f := range sj.Followers {

		if f.Id == id {
			return f.Hostname, nil
		}
	}

	return "", fmt.Errorf("Follower not found: %s", id)
}

// Task Methods

// GetCheck()
//   Build a Check structure from the Task labels
//
func (t *Task) GetCheck() *registry.Check {
	c := registry.DefaultCheck()

	for _, l := range t.Labels {
		k := strings.ToLower(l.Key)

		switch k {
		case "check_http":
			c.HTTP = l.Value
		case "check_script":
			c.Script = l.Value
		case "check_ttl":
			c.TTL = l.Value
		case "check_interval":
			c.Interval = l.Value
		}
	}

	return c
}

Remove `consul` from the check labels


package tty

import (
	"os"

	"github.com/elves/elvish/util"
	"golang.org/x/sys/windows"
)

const (
	wantedInMode = windows.ENABLE_WINDOW_INPUT |
		windows.ENABLE_MOUSE_INPUT | windows.ENABLE_PROCESSED_INPUT
	wantedOutMode = windows.ENABLE_PROCESSED_OUTPUT |
		windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
)

func setup(in, out *os.File) (func() error, error) {
	hIn := windows.Handle(in.Fd())
	hOut := windows.Handle(out.Fd())

	var oldInMode, oldOutMode uint32
	err := windows.GetConsoleMode(hIn, &oldInMode)
	if err != nil {
		return nil, err
	}
	err = windows.GetConsoleMode(hOut, &oldOutMode)
	if err != nil {
		return nil, err
	}

	errSetIn := windows.SetConsoleMode(hIn, wantedInMode)
	errSetOut := windows.SetConsoleMode(hOut, wantedOutMode)
	errVT := setupVT(out)

	return func() error {
		return util.Errors(
			windows.SetConsoleMode(hIn, oldInMode),
			windows.SetConsoleMode(hOut, oldOutMode),
			restoreVT(out))
	}, util.Errors(errSetIn, errSetOut, errVT)
}

package tty

import (
	"os"

	"github.com/elves/elvish/util"
	"golang.org/x/sys/windows"
)

const (
	wantedInMode = windows.ENABLE_WINDOW_INPUT |
		windows.ENABLE_MOUSE_INPUT | windows.ENABLE_PROCESSED_INPUT
	wantedOutMode = windows.ENABLE_PROCESSED_OUTPUT |
		windows.ENABLE_VIRTUAL_TERMINAL_PROCESSING
)

func setup(in, out *os.File) (func() error, error) {
	hIn := windows.Handle(in.Fd())
	hOut := windows.Handle(out.Fd())

	var oldInMode, oldOutMode uint32
	err := windows.GetConsoleMode(hIn, &oldInMode)
	if err != nil {
		return nil, err
	}
	err = windows.GetConsoleMode(hOut, &oldOutMode)
	if err != nil {
		return nil, err
	}

	errSetIn := windows.SetConsoleMode(hIn, wantedInMode)
	errSetOut := windows.SetConsoleMode(hOut, wantedOutMode)
	errVT := setupVT(out)

	return func() error {
		return util.Errors(
			restoreVT(out),
			windows.SetConsoleMode(hOut, oldOutMode),
			windows.SetConsoleMode(hIn, oldInMode))
	}, util.Errors(errSetIn, errSetOut, errVT)
}

Adjust the order of TTY restoration on Windows.


package model

import "github.com/blevesearch/bleve"

// InitIndex initializes the search index at the specified path
func InitIndex(filepath string) (bleve.Index, error) {
	index, err := bleve.Open(filepath)

	// Doesn't yet exist (or error opening) so create a new one
	if err != nil {
		mapping := bleve.NewIndexMapping()
		index, err = bleve.New(filepath, mapping)
		if err != nil {
			return nil, err
		}
	}
	return index, nil
}

package model

import (
	"github.com/blevesearch/bleve"
	"github.com/blevesearch/bleve/analysis/language/en"
)

// InitIndex initializes the search index at the specified path
func InitIndex(filepath string) (bleve.Index, error) {
	index, err := bleve.Open(filepath)

	// Doesn't yet exist (or error opening) so create a new one
	if err != nil {
		index, err = bleve.New(filepath, buildIndexMapping())
		if err != nil {
			return nil, err
		}
	}
	return index, nil
}

func buildIndexMapping() *bleve.IndexMapping {
	englishTextFieldMapping := bleve.NewTextFieldMapping()
	englishTextFieldMapping.Analyzer = en.AnalyzerName

	starMapping := bleve.NewDocumentMapping()
	starMapping.AddFieldMappingsAt("Name", englishTextFieldMapping)
	starMapping.AddFieldMappingsAt("FullName", englishTextFieldMapping)
	starMapping.AddFieldMappingsAt("Description", englishTextFieldMapping)

	indexMapping := bleve.NewIndexMapping()
	indexMapping.AddDocumentMapping("Star", starMapping)

	return indexMapping
}

Add mapping for name, full name, and description


package api

import (
	"testing"
)

func assertQueryMeta(t *testing.T, qm *QueryMeta) {
	if qm.LastIndex == 0 {
		t.Fatalf("bad index: %d", qm.LastIndex)
	}
	if !qm.KnownLeader {
		t.Fatalf("expected known leader, got none")
	}
}

func assertWriteMeta(t *testing.T, wm *WriteMeta) {
	if wm.LastIndex == 0 {
		t.Fatalf("bad index: %d", wm.LastIndex)
	}
	if wm.RequestTime == 0 {
		t.Fatalf("bad request time: %d", wm.RequestTime)
	}
}

func testJob() *Job {
	task := NewTask("task1", "exec").
		Require(&Resources{MemoryMB: 256})

	group := NewTaskGroup("group1", 1).
		AddTask(task)

	job := NewBatchJob("job1", "redis", "region1", 1).
		AddDatacenter("dc1").
		AddTaskGroup(group)

	return job
}

package api

import (
	"testing"
)

func assertQueryMeta(t *testing.T, qm *QueryMeta) {
	if qm.LastIndex == 0 {
		t.Fatalf("bad index: %d", qm.LastIndex)
	}
	if !qm.KnownLeader {
		t.Fatalf("expected known leader, got none")
	}
}

func assertWriteMeta(t *testing.T, wm *WriteMeta) {
	if wm.LastIndex == 0 {
		t.Fatalf("bad index: %d", wm.LastIndex)
	}
}

func testJob() *Job {
	task := NewTask("task1", "exec").
		Require(&Resources{MemoryMB: 256})

	group := NewTaskGroup("group1", 1).
		AddTask(task)

	job := NewBatchJob("job1", "redis", "region1", 1).
		AddDatacenter("dc1").
		AddTaskGroup(group)

	return job
}

Remove clock granularity sensitive test assertion.