package fhttp

import (
	"github.com/jung-kurt/gofpdf"
	"net/http"
)

// RegisterRemoteImage registers a remote image. Downloading the image from the
// provided URL and adding it to the PDF but not adding it to the page. Use
// Image() with the same URL to add the image to the page.
func RegisterRemoteImage(f *gofpdf.Fpdf, urlStr, tp string) (info *gofpdf.ImageInfoType) {
	resp, err := http.Get(urlStr)

	if err != nil {
		f.SetError(err)
		return
	}

	defer resp.Body.Close()

	if tp == "" {
		tp = f.ImageTypeFromMime(resp.Header["Content-Type"][0])
	}

	return f.RegisterImageReader(urlStr, tp, resp.Body)
}

package fhttp

import (
	"github.com/jung-kurt/gofpdf"
	"net/http"
)

// RegisterRemoteImage registers a remote image. Downloading the image from the
// provided URL and adding it to the PDF but not adding it to the page. Use
// Image() with the same URL to add the image to the page.
func RegisterRemoteImage(f *gofpdf.Fpdf, urlStr, tp string) (info *gofpdf.ImageInfoType) {
	info = f.GetImageInfo(urlStr)

	if info != nil {
		return
	}

	resp, err := http.Get(urlStr)

	if err != nil {
		f.SetError(err)
		return
	}

	defer resp.Body.Close()

	if tp == "" {
		tp = f.ImageTypeFromMime(resp.Header["Content-Type"][0])
	}

	return f.RegisterImageReader(urlStr, tp, resp.Body)
}

Use `GetImageInfo` to see if the image is already registered.


package crypto

import (
	"encoding/base64"
	"strings"

	"github.com/pborman/uuid"
)

// SecureToken creates a new random token
func SecureToken() string {
	token := uuid.NewRandom()
	return removePadding(base64.URLEncoding.EncodeToString([]byte(token)))
}

func removePadding(token string) string {
	return strings.TrimRight(token, "=")
}

package crypto

import (
	"crypto/rand"
	"encoding/base64"
	"io"
	"strings"
)

// SecureToken creates a new random token
func SecureToken() string {
	b := make([]byte, 16)
	if _, err := io.ReadFull(rand.Reader, b); err != nil {
		panic(err.Error()) // rand should never fail
	}
	return removePadding(base64.URLEncoding.EncodeToString(b))
}

func removePadding(token string) string {
	return strings.TrimRight(token, "=")
}

Use rand.Reader directly instead of relying upon uuid


// Package chalk lets you colour you
// terminal string styles
package chalk

// Black colours your string black
func Black(s string) string {
	return "\033[30m" + s + "\033[0m"
}

// Red colours your string red
func Red(s string) string {
	return "\033[31m" + s + "\033[0m"
}

// Yellow colours your string yellow
func Yellow(s string) string {
	return "\033[32m" + s + "\033[0m"
}

// Green colours your string green
func Green(s string) string {
	return "\033[33m" + s + "\033[0m"
}

// Blue colours your string blue
func Blue(s string) string {
	return "\033[34m" + s + "\033[0m"
}

// Magenta colours your string magenta
func Magenta(s string) string {
	return "\033[35m" + s + "\033[0m"
}

// Cyan colours your string cyan
func Cyan(s string) string {
	return "\033[36m" + s + "\033[0m"
}

// White colours your string white
func White(s string) string {
	return "\033[37m" + s + "\033[0m"
}

// Package chalk lets you colour you
// terminal string styles
package chalk

// Black colours your string black
func Black(s string) string {
	return "\033[30m" + s + "\033[0m"
}

// Red colours your string red
func Red(s string) string {
	return "\033[31m" + s + "\033[0m"
}

// Green colours your string green
func Green(s string) string {
	return "\033[32m" + s + "\033[0m"
}

// Yellow colours your string yellow
func Yellow(s string) string {
	return "\033[33m" + s + "\033[0m"
}

// Blue colours your string blue
func Blue(s string) string {
	return "\033[34m" + s + "\033[0m"
}

// Magenta colours your string magenta
func Magenta(s string) string {
	return "\033[35m" + s + "\033[0m"
}

// Cyan colours your string cyan
func Cyan(s string) string {
	return "\033[36m" + s + "\033[0m"
}

// White colours your string white
func White(s string) string {
	return "\033[37m" + s + "\033[0m"
}

Fix green and yellow being opposites


package sink

import (
	"fmt"
	"os"
)

// GetSink ...
func GetSink() (Sink, error) {
	sinkType := os.Getenv("SINK_TYPE")
	if sinkType == "" {
		return nil, fmt.Errorf("Missing SINK_TYPE: amqp, kafka,kinesis or stdout")
	}

	switch sinkType {
	case "amqp":
		fallthrough
	case "rabbitmq":
		return NewRabbitmq()
	case "kafka":
		return NewKafka()
	case "kinesis":
		return NewKinesis()
	case "stdout":
		return NewStdout()
	default:
		return nil, fmt.Errorf("Invalid SINK_TYPE: %s, Valid values: amqp, kafka, kinesis or stdout",sinkType)
	}
}

package sink

import (
	"fmt"
	"os"
)

// GetSink ...
func GetSink() (Sink, error) {
	sinkType := os.Getenv("SINK_TYPE")
	if sinkType == "" {
		return nil, fmt.Errorf("Missing SINK_TYPE: amqp, kafka, kinesis, nsq or stdout")
	}

	switch sinkType {
	case "amqp":
		fallthrough
	case "rabbitmq":
		return NewRabbitmq()
	case "kafka":
		return NewKafka()
	case "kinesis":
		return NewKinesis()
	case "stdout":
		return NewStdout()
	case "nsq":
		return NewNSQ()
	default:
		return nil, fmt.Errorf("Invalid SINK_TYPE: %s, Valid values: amqp, kafka, kinesis, nsq or stdout", sinkType)
	}
}

Add the new NSQ sink to the sink list


package wol

// WARNING: Auto generated version file. Do not edit this file by hand.
// WARNING: go get github.com/sabhiram/gover to manage this file.
// Version: 1.0.4

const (
    Major = 1
    Minor = 0
    Patch = 4

    Version = "1.0.4"
)

Fix gofmt on generated version file


package codeutilsShared

import (
	"os"
	"os/exec"
	"strings"
)

// ExecCommand executes a utility with args and returning the stringified output
func ExecCommand(utility string, args []string, liveOutput bool) string {
	var output []byte
	runner := exec.Command(utility, args...)

	if liveOutput { // If we should immediately output the results of the command
		runner.Stdout = os.Stdout
		runner.Stderr = os.Stderr
		runner.Start()
	} else { // If we should redirect output to var
		output, _ = runner.CombinedOutput() // Combine the output of stderr and stdout
	}

	return string(output[:])
}

// ExecutableExists checks if an executable exists
func ExecutableExists(executableName string) bool {
	var emptyFlags []string
	executableCommandMessage := ExecCommand("which " + executableName, emptyFlags, false) // Generate an empty call to the executable
	return strings.Contains(executableCommandMessage, executableName + " not found") // If executable does not exist
}

package codeutilsShared

import (
	"os"
	"os/exec"
	"strings"
)

// ExecCommand executes a utility with args and returning the stringified output
func ExecCommand(utility string, args []string, liveOutput bool) string {
	var output []byte
	runner := exec.Command(utility, args...)

	if liveOutput { // If we should immediately output the results of the command
		runner.Stdout = os.Stdout
		runner.Stderr = os.Stderr
		runner.Start()
	} else { // If we should redirect output to var
		output, _ = runner.CombinedOutput() // Combine the output of stderr and stdout
	}

	return string(output[:])
}

// ExecutableExists checks if an executable exists
func ExecutableExists(executableName string) bool {
	var emptyFlags []string
	executableCommandMessage := ExecCommand("which "+executableName, emptyFlags, false) // Generate an empty call to the executable
	return !strings.Contains(executableCommandMessage, executableName+" not found")     // If executable does not exist
}

Return inverse boolean of contains for ExecutableExists.


/* This is a FLEXible file which can be used by both client and daemon.
 * Teehee.
 */
package lxd

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

var Version = "0.0.1"

/*
 * Please increment the api compat number every time you change the API.
 *
 * Version 1.0: ping
 */
var APICompat = 1
var APIVersion = "1.0"

// VarPath returns the provided path elements joined by a slash and
// appended to the end of $LXD_DIR, which defaults to /var/lib/lxd.
func VarPath(path ...string) string {
	varDir := os.Getenv("LXD_DIR")
	if varDir == "" {
		varDir = "/var/lib/lxd"
	}
	items := []string{varDir}
	items = append(items, path...)
	return filepath.Join(items...)
}

func ReadStdin() ([]byte, error) {
	buf := bufio.NewReader(os.Stdin)
	line, _, err := buf.ReadLine()
	if err != nil {
		return nil, err
	}
	return line, nil
}

/* This is a FLEXible file which can be used by both client and daemon.
 * Teehee.
 */
package lxd

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

var Version = "0.0"

/*
 * Please increment the api compat number every time you change the API.
 *
 * Version 1.0: ping
 */
var APICompat = 1
var APIVersion = "1.0"

// VarPath returns the provided path elements joined by a slash and
// appended to the end of $LXD_DIR, which defaults to /var/lib/lxd.
func VarPath(path ...string) string {
	varDir := os.Getenv("LXD_DIR")
	if varDir == "" {
		varDir = "/var/lib/lxd"
	}
	items := []string{varDir}
	items = append(items, path...)
	return filepath.Join(items...)
}

func ReadStdin() ([]byte, error) {
	buf := bufio.NewReader(os.Stdin)
	line, _, err := buf.ReadLine()
	if err != nil {
		return nil, err
	}
	return line, nil
}

Use 0.0 as our version


package main

import (
    "compress/gzip"
    "io"
    "log"
    "os"

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

func main() {
    file, err := os.Open("upload_file.tar")
    if err != nil {
        log.Fatal("Failed to open file", err)
    }

    // Not required, but you could zip the file before uploading it
    // using io.Pipe read/writer to stream gzip'd file contents.
    reader, writer := io.Pipe()
    go func() {
        gw := gzip.NewWriter(writer)
        io.Copy(gw, file)

        file.Close()
        gw.Close()
        writer.Close()
    }()
    uploader := s3manager.NewUploader(session.New(&aws.Config{Region: aws.String("us-west-1")}))
    result, err := uploader.Upload(&s3manager.UploadInput{
        Body:   reader,
        Bucket: aws.String("myBucket"),
        Key:    aws.String("myKey"),
    })
    if err != nil {
        log.Fatalln("Failed to upload", err)
    }

    log.Println("Successfully uploaded to", result.Location)
}

package main

import (
    "compress/gzip"
    "io"
    "log"
    "os"

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

var key = "secretKey"
var bucket = "theBucket"

func main() {
    file, err := os.Open("upload_file.tar")
    if err != nil {
        log.Fatal("Failed to open file", err)
    }

    // Not required, but you could zip the file before uploading it
    // using io.Pipe read/writer to stream gzip'd file contents.
    reader, writer := io.Pipe()
    go func() {
        gw := gzip.NewWriter(writer)
        io.Copy(gw, file)

        file.Close()
        gw.Close()
        writer.Close()
    }()
    uploader := s3manager.NewUploader(session.New(&aws.Config{Region: aws.String("us-west-1")}))
    result, err := uploader.Upload(&s3manager.UploadInput{
        Body:   reader,
        Bucket: aws.String(bucket),
        Key:    aws.String(key),
    })
    if err != nil {
        log.Fatalln("Failed to upload", err)
    }

    log.Println("Successfully uploaded to", result.Location)
}

Move key and bucket strings into variables


package dnsp

import (
	"fmt"
	"strings"
)

type HostEntry struct {
	IP   string
	Host string
}

func (h *HostEntry) String() string {
	return fmt.Sprintf("%v @ %v", h.Host, h.IP)
}

func ParseHostLine(line string) HostEntry {
	result := HostEntry{}

	if len(line) > 0 {
		parts := strings.Fields(line)

		// TODO: More validation might be smart
		if parts[0] != "#" && len(parts) >= 2 {
			result.IP = parts[0]
			result.Host = parts[1]
		}
	}

	return result
}

package dnsp

import (
	"fmt"
	"strings"
)

type HostEntry struct {
	IP   string
	Host string
}

func (h *HostEntry) String() string {
	return fmt.Sprintf("%v @ %v", h.Host, h.IP)
}

func ParseHostLine(line string) *HostEntry {
	result := HostEntry{}

	if len(line) > 0 {
		parts := strings.Fields(line)

		// TODO: More validation might be smart
		if parts[0] != "#" && len(parts) >= 2 {
			result.IP = parts[0]
			result.Host = parts[1]
		}
	}

	return &result
}

Return a pointer from ParseHostLine


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

// mkfifo creates a named pipe.
//
// Synopsis:
//     mkfifo [OPTIONS] NAME...
//
// Options:
//     -m: mode (default 0600)
//
package main

import (
	"flag"
	"log"
	"os"
	"syscall"

	"golang.org/x/sys/unix"
)

const (
	defaultMode = 0660 | unix.S_IFIFO
	cmd         = "mkfifo [-m] NAME..."
)

var mode = flag.Int("mode", defaultMode, "Mode to create fifo")

func init() {
	defUsage := flag.Usage
	flag.Usage = func() {
		os.Args[0] = cmd
		defUsage()
	}
	flag.Parse()
}

func main() {
	flag.Parse()

	if flag.NArg() < 1 {
		log.Fatal("please provide a path, or multiple, to create a fifo")
	}

	for _, path := range flag.Args() {
		if err := syscall.Mkfifo(path, uint32(*mode)); err != nil {
			log.Fatalf("Error while creating fifo, %v", err)
		}
	}
}

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

// mkfifo creates a named pipe.
//
// Synopsis:
//     mkfifo [OPTIONS] NAME...
//
// Options:
//     -m: mode (default 0600)
//
package main

import (
	"flag"
	"log"
	"os"

	"golang.org/x/sys/unix"
)

const (
	defaultMode = 0660 | unix.S_IFIFO
	cmd         = "mkfifo [-m] NAME..."
)

var mode = flag.Int("mode", defaultMode, "Mode to create fifo")

func init() {
	defUsage := flag.Usage
	flag.Usage = func() {
		os.Args[0] = cmd
		defUsage()
	}
	flag.Parse()
}

func main() {
	flag.Parse()

	if flag.NArg() < 1 {
		log.Fatal("please provide a path, or multiple, to create a fifo")
	}

	for _, path := range flag.Args() {
		if err := unix.Mkfifo(path, uint32(*mode)); err != nil {
			log.Fatalf("Error while creating fifo, %v", err)
		}
	}
}

Remove syscall package in favor of unix package


package dna

// Histogram is a mapping from nucleotide to its count in given DNA.
type Histogram map[rune]int

type DNA string

// Counts generates a histogram of valid nucleotides in the given DNA.
// Returns an error if d contains an invalid nucleotide.
func (d DNA) Counts() (Histogram, error) {
	h := Histogram{
		'A': 0,
		'C': 0,
		'G': 0,
		'T': 0,
	}
	for _, r := range d {
		h[r] += 1
	}
	return h, nil
}

package dna

import "fmt"

// Histogram is a mapping from nucleotide to its count in given DNA.
type Histogram map[rune]int

type DNA string

// Counts generates a histogram of valid nucleotides in the given DNA.
// Returns an error if d contains an invalid nucleotide.
func (d DNA) Counts() (Histogram, error) {
	if !d.isValid() {
		return Histogram{}, fmt.Errorf("DNA stand %s contains invalid nucleotides", d)
	}
	h := Histogram{
		'A': 0,
		'C': 0,
		'G': 0,
		'T': 0,
	}
	for _, r := range d {
		h[r] += 1
	}
	return h, nil
}

func (d DNA) isValid() bool {
	for _, r := range d {
		if r == 'A' || r == 'C' || r == 'G' || r == 'T' {
			continue
		} else {
			return false
		}
	}
	return true
}

Throw error if DNA strand is invalid


package gedcom

// Individual represents an individual record in a node structure with links to
// other individuals.
type Individual struct {
	Node   *Node
	Father *Individual
	Mother *Individual
}

// GetName returns the name of the individual. If there is no name attached to
// the individual, an empty string is returned instead.
func (i *Individual) GetName() string {
	name, err := i.Node.GetAttribute("NAME")
	if err != nil {
		return ""
	}

	return name
}

Add a GetName function that's a wrapper around Node.GetAttribute("NAME")


package lifecycle

import (
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/version"
)

// NetworkLoadBalancerAction represents a lifecycle event action for network load balancers.
type NetworkLoadBalancerAction string

// All supported lifecycle events for network forwards.
const (
	NetworkLoadBalancerCreated = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerCreated)
	NetworkLoadBalancerDeleted = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerDeleted)
	NetworkLoadBalancerUpdated = NetworkForwardAction(api.EventLifecycleNetworkLoadBalancerUpdated)
)

// Event creates the lifecycle event for an action on a network forward.
func (a NetworkLoadBalancerAction) Event(n network, listenAddress string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle {
	u := api.NewURL().Path(version.APIVersion, "networks", n.Name(), "load-balancers", listenAddress).Project(n.Project())
	return api.EventLifecycle{
		Action:    string(a),
		Source:    u.String(),
		Context:   ctx,
		Requestor: requestor,
	}
}

package lifecycle

import (
	"github.com/lxc/lxd/shared/api"
	"github.com/lxc/lxd/shared/version"
)

// NetworkLoadBalancerAction represents a lifecycle event action for network load balancers.
type NetworkLoadBalancerAction string

// All supported lifecycle events for network load balancers.
const (
	NetworkLoadBalancerCreated = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerCreated)
	NetworkLoadBalancerDeleted = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerDeleted)
	NetworkLoadBalancerUpdated = NetworkLoadBalancerAction(api.EventLifecycleNetworkLoadBalancerUpdated)
)

// Event creates the lifecycle event for an action on a network load balancer.
func (a NetworkLoadBalancerAction) Event(n network, listenAddress string, requestor *api.EventLifecycleRequestor, ctx map[string]any) api.EventLifecycle {
	u := api.NewURL().Path(version.APIVersion, "networks", n.Name(), "load-balancers", listenAddress).Project(n.Project())
	return api.EventLifecycle{
		Action:    string(a),
		Source:    u.String(),
		Context:   ctx,
		Requestor: requestor,
	}
}

Fix load balancer lifecycle types


package fileserver

// FileServer serves web resources from files.
type FileServer struct {
	// ContentRoot is the folder containing the content
	ContentRoot string
	Getters     []Getter
}

// NewFileServer creates a new instance with default cacheServ & fileServ
func NewFileServer(contentRoot string) (fs FileServer) {
	fs.Getters = []Getter{
		cacheServ{},
		fileServ{},
	}
	fs.ContentRoot = contentRoot
	return
}

// Get retrieves content for the specifie path.
func (fs FileServer) Get(path string) (content []byte, err error) {
	for i, getter := range fs.Getters {
		content, err = getter.Get(path)
		if err == nil {
			return content, nil
		}
		if i == len(fs.Getters)-1 { // All getters returned errors
			return nil, ErrInvalidContentPath{path}
		}
	}
	return
}

package fileserver

// FileServer serves web resources from files.
type FileServer struct {
	// ContentRoot is the folder containing the content
	ContentRoot string
	Getters     []Getter
}

// NewFileServer creates a new instance with default cacheServ & fileServ Getters
func NewFileServer(contentRoot string) (fs FileServer) {
	fs = FileServer{
		ContentRoot: contentRoot,
		Getters: []Getter{
			cacheServ{},
			fileServ{},
		},
	}
	return
}

// Get retrieves content for the specifie path.
func (fs FileServer) Get(path string) (content []byte, err error) {
	for i, getter := range fs.Getters {
		content, err = getter.Get(path)
		if err == nil {
			return content, nil
		}
		if i == len(fs.Getters)-1 { // All getters returned errors
			return nil, ErrInvalidContentPath{path}
		}
	}
	return
}

Use constructor rather than object.Param = syntax


package blorg

import (
	"fmt"
	"io/ioutil"
	"os/exec"
	"strings"
	"testing"
)

func TestBlorg(t *testing.T) {
	config, err := ReadConfig("testdata/blorg.org")
	if err != nil {
		t.Errorf("Could not read config: %s", err)
		return
	}
	commitedHashBs, err := ioutil.ReadFile("testdata/public.md5")
	if err != nil {
		t.Errorf("Could not read hash bytes: %s", err)
		return
	}
	if err := config.Render(); err != nil {
		t.Errorf("Could not render: %s", err)
		return
	}
	renderedHashBs, err := exec.Command("bash", "-c", fmt.Sprintf("find %s -type f | sort -u | xargs cat | md5sum", config.PublicDir)).Output()
	if err != nil {
		t.Errorf("Could not hash PublicDir: %s", err)
		return
	}
	rendered, committed := strings.TrimSpace(string(renderedHashBs)), strings.TrimSpace(string(commitedHashBs))
	if rendered != committed {
		t.Errorf("PublicDir hashes do not match: '%s' -> '%s'", committed, rendered)
		return
	}
}

package blorg

import (
	"fmt"
	"io/ioutil"
	"os/exec"
	"strings"
	"testing"
)

func TestBlorg(t *testing.T) {
	config, err := ReadConfig("testdata/blorg.org")
	if err != nil {
		t.Errorf("Could not read config: %s", err)
		return
	}
	committedHashBs, err := ioutil.ReadFile("testdata/public.md5")
	if err != nil {
		t.Errorf("Could not read hash bytes: %s", err)
		return
	}
	if err := config.Render(); err != nil {
		t.Errorf("Could not render: %s", err)
		return
	}
	renderedHashBs, err := exec.Command("bash", "-c", fmt.Sprintf("find %s -type f | sort -u | xargs cat | md5sum", config.PublicDir)).Output()
	if err != nil {
		t.Errorf("Could not hash PublicDir: %s", err)
		return
	}
	rendered, committed := strings.TrimSpace(string(renderedHashBs)), strings.TrimSpace(string(committedHashBs))
	if rendered != committed {
		t.Errorf("PublicDir hashes do not match: '%s' -> '%s'", committed, rendered)
		return
	}
}

Fix a typo in blorg test


package cache

import (
	"fmt"
	"strings"
	"testing"
)

func TestLruCache_Get(t *testing.T) {
	l := NewLRUCache(1024 * 1024)
	for idx := 0; idx < 100000; idx++ {
		l.Set(strings.Repeat(fmt.Sprintf("%016d", idx), 16))
	}

	if l.Size() > 2*1024*1024 {
		t.Fatal(l.Size())
	}

	if l.Count() > 5000 {
		t.Fatal(l.Size())
	}
}

package cache

import (
	"fmt"
	"strings"
	"testing"
)

func TestLruCache_Get(t *testing.T) {
	format := func(idx int) string {
		return strings.Repeat(fmt.Sprintf("%016d", idx), 16)
	}

	l := NewLRUCache(1024 * 1024)
	for idx := 0; idx < 100000; idx++ {
		l.Set(format(idx))
	}

	if l.Size() > 2*1024*1024 {
		t.Fatal(l.Size())
	}

	if l.Count() > 5000 {
		t.Fatal(l.Size())
	}

	for idx := 99000; idx < 100000; idx++ {
		if l.Get(format(idx)) == "" {
			t.Fatal("Item should be in the cache: " + format(idx))
		}
	}
}

Add a test for the LRU implementation


package main

import (
	"atlantis/router/lb"
	"flag"
)

var servers string

func main() {
	flag.StringVar(&servers, "zk", "localhost:2181", "zookeeper connection string")
	balancer := lb.New(servers)
	balancer.Run()
}

package main

import (
	"atlantis/router/lb"
	"flag"
	"log"
	"log/syslog"
)

var servers string

func main() {
	// Logging to syslog is more performant, which matters.
	w, err := syslog.New(syslog.LOG_INFO, "atlantis-router")
	if err != nil {
		log.Println("[ERROR] cannot log to syslog!")
	} else {
		log.SetOutput(w)
		log.SetFlags(0)
	}

	flag.StringVar(&servers, "zk", "localhost:2181", "zookeeper connection string")
	balancer := lb.New(servers)
	balancer.Run()
}

Switch logging to syslog for performance.


package fm_test

import (
	"go/ast"
	"testing"

	"github.com/enocom/fm/lib"
)

func TestConvertBuildsAddsSpyToTypeSpecName(t *testing.T) {
	converter := &fm.SpyStructConverter{}

	typeSpec := converter.Convert(
		&ast.TypeSpec{
			Name: ast.NewIdent("Tester"),
		},
		&ast.InterfaceType{
			Methods: &ast.FieldList{List: make([]*ast.Field, 0)},
		},
	)

	want := "SpyTester"
	got := typeSpec.Name.Name

	if want != got {
		t.Errorf("want %v, got %v", want, got)
	}
}

package fm_test

import (
	"go/ast"
	"testing"

	"github.com/enocom/fm/lib"
)

func TestConvertBuildsAddsSpyToTypeSpecName(t *testing.T) {
	converter := &fm.SpyStructConverter{}

	typeSpec := converter.Convert(
		&ast.TypeSpec{Name: ast.NewIdent("Tester")},
		&ast.InterfaceType{
			Methods: &ast.FieldList{List: make([]*ast.Field, 0)},
		},
	)

	want := "SpyTester"
	got := typeSpec.Name.Name

	if want != got {
		t.Errorf("want %v, got %v", want, got)
	}
}

func TestConvertAddsRecordOfFunctionCallAsField(t *testing.T) {
	converter := &fm.SpyStructConverter{}

	typeSpec := converter.Convert(
		&ast.TypeSpec{Name: ast.NewIdent("Tester")},
		&ast.InterfaceType{
			Methods: &ast.FieldList{
				List: []*ast.Field{
					&ast.Field{
						Names: []*ast.Ident{ast.NewIdent("Test")},
						Type: &ast.FuncType{
							Params:  &ast.FieldList{},
							Results: &ast.FieldList{},
						},
					},
				},
			},
		},
	)

	structType, ok := typeSpec.Type.(*ast.StructType)
	if !ok {
		t.Fatal("expected typeSpec to be of type StructType")
	}

	want := 1
	got := len(structType.Fields.List)
	if want != got {
		t.Errorf("want %v, got %v", want, got)
	}

	calledField := structType.Fields.List[0]

	wantName := "Test_Called"
	gotName := calledField.Names[0].Name
	if wantName != gotName {
		t.Errorf("want %v, got %v", wantName, gotName)
	}
}

Add converter test confirming "_Called" field


package metrics

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

var (
	// PodFailure returns counter for pod_errors_total metric
	PodFailure = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "pod_errors_total",
			Help: "Number of failure operation on PODs",
		},
		[]string{"operation"},
	)

	// PodFailure returns counter for pod_successes_total metric
	PodSuccess = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "pod_successes_total",
			Help: "Number of succeed operation on PODs",
		},
		[]string{"operation"},
	)

	// FuncDuration returns summary for controller_function_duration_seconds metric
	FuncDuration = prometheus.NewSummaryVec(
		prometheus.SummaryOpts{
			Name:       "controller_function_duration_seconds",
			Help:       "The runtime of an function.",
			Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
		},
		[]string{"function"},
	)
)

package metrics

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

var (
	// PodFailure returns counter for pod_errors_total metric
	PodFailure = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "pod_errors_total",
			Help: "Number of failure operation on PODs",
		},
		[]string{"operation"},
	)

	// PodSuccess returns counter for pod_successes_total metric
	PodSuccess = prometheus.NewCounterVec(
		prometheus.CounterOpts{
			Name: "pod_successes_total",
			Help: "Number of succeed operation on PODs",
		},
		[]string{"operation"},
	)

	// FuncDuration returns summary for controller_function_duration_seconds metric
	FuncDuration = prometheus.NewSummaryVec(
		prometheus.SummaryOpts{
			Name:       "controller_function_duration_seconds",
			Help:       "The runtime of an function.",
			Objectives: map[float64]float64{0.5: 0.05, 0.9: 0.01, 0.99: 0.001},
		},
		[]string{"function"},
	)
)

Fix typo from comment of a exported type


package opensimplex

import "math/rand"

func Example() {
	noise := New(rand.Int63())

	w, h := 100, 100
	heightmap := make([]float64, w, h)
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			xFloat := float64(x) / float64(w)
			yFloat := float64(y) / float64(h)
			heightmap[(y*w)+x] = noise.Eval2(xFloat, yFloat)
		}
	}
}

package opensimplex

import "math/rand"

func Example() {
	noise := New(rand.Int63())

	w, h := 100, 100
	heightmap := make([]float64, w*h)
	for y := 0; y < h; y++ {
		for x := 0; x < w; x++ {
			xFloat := float64(x) / float64(w)
			yFloat := float64(y) / float64(h)
			heightmap[(y*w)+x] = noise.Eval2(xFloat, yFloat)
		}
	}
}

Fix heightmap := make([]float64, w, h)


package dsbldr

// RunFunc holds the computation that processes the API responses to features
// is sent a JSON string of the response ??as well as a map of data from the features parent features??
// Basically what you do with the run function is take in a string of
// serialized API data (could be in JSON or XML), do parsing on your
// own or using utility functions. You do whatever computations you want and
// then spit it back as an array of strings to read to CSV or JSON
type RunFunc func(response string) []string // parents map[string]string

// Feature in the dataset, on which all other features are based on
type Feature struct {
	Name     string
	Endpoint string // API Endpoint
	RunFunc  RunFunc
}

// NewFeature creates new Feature with defaults
func NewFeature() *Feature {
	return &Feature{}
}

package dsbldr

// RunFunc holds the computation that processes the API responses to features
// is sent a JSON string of the response ??as well as a map of data from the features parent features??
// Basically what you do with the run function is take in a string of
// serialized API data (could be in JSON or XML), do parsing on your
// own or using utility functions. You do whatever computations you want and
// then spit it back as an array of strings to read to CSV or JSON
type RunFunc func(response string) []string // parents map[string]string

// Structs representing RetreiveType
// SingleRetrieve Features only require one request to create the JSON Dump
// that's passed to the RunFunc
// Repeated Retrieve Features require one request per value-set of
// of parent features that are concatenated into a JSON array and then passed
// to the Features RunFunc
// Almost as a given, all dependent features will be of RepeatedRetrieve per
// value sets of their parent features
const (
	SingleRetrieve = iota
	RepeatedRetrieve
)

// Feature Download statuses
const (
	Ready = iota
	NotReady
)

// Feature in the dataset, on which all other features are based on
type Feature struct {
	Name         string
	Endpoint     string // API Endpoint
	RunFunc      RunFunc
	RetrieveType int // Determines if multiple or single requests are made to the api
	noSave       bool
	status       chan int // download status of feature
}

// NewFeature creates new Feature with defaults
func NewFeature() *Feature {
	return &Feature{
		noSave: false,
	}
}

Add RetrieveType, noSave and status fields to Feature struct


package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"

	"github.com/pilu/traffic"
	"github.com/tealeg/xlsx"
)

type ExcelData struct {
	DocumentName string
	Sheets [][][]string
}

func excelResponse(w traffic.ResponseWriter, r *traffic.Request) {
	file, handler, err := r.FormFile("file")
        if err != nil {
                fmt.Println(err)
        }
        data, err := ioutil.ReadAll(file)
        if err != nil {
                fmt.Println(err)
        }
	fmt.Print("Filename: ")
	fmt.Println(handler.Filename)

	xlFile, err := xlsx.OpenBinary(data)
	if err != nil {
		fmt.Println(err)
	}

 	excelData := ExcelData{DocumentName: handler.Filename}
	excelData.Sheets, err = xlFile.ToSlice()
	if err != nil {
		fmt.Println(err)
	}
	enc := json.NewEncoder(w)
	enc.Encode(excelData)
}

func APIHandler(w traffic.ResponseWriter, r *traffic.Request) {
	params := r.URL.Query()
	call := params.Get("call")
	if call == "conversion" {
		excelResponse(w, r);
	}
}

package main

import (
	"encoding/json"
	"fmt"
	"io/ioutil"

	"github.com/pilu/traffic"
	"github.com/tealeg/xlsx"
)

type ExcelData struct {
	DocumentName string
	Sheets [][][]string
}

func excelResponse(w traffic.ResponseWriter, r *traffic.Request) {
	file, handler, err := r.FormFile("file")
        if err != nil {
                fmt.Println(err)
        }
        data, err := ioutil.ReadAll(file)
        if err != nil {
                fmt.Println(err)
        }
	fmt.Print("Filename: ")
	fmt.Println(handler.Filename)

	xlFile, err := xlsx.OpenBinary(data)
	if err != nil {
		fmt.Println(err)
	}

 	excelData := ExcelData{DocumentName: handler.Filename}
	excelData.Sheets, err = xlFile.ToSlice()
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(excelData)
	enc := json.NewEncoder(w)
	enc.Encode(excelData)
}

func APIHandler(w traffic.ResponseWriter, r *traffic.Request) {
	params := r.URL.Query()
	call := params.Get("call")
	if call == "conversion" {
		excelResponse(w, r);
	}
}

Add debugging println to show content of spreadsheet on the console.


// +build !linux,!windows

/*
Copyright 2017 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 dockershim

import (
	"context"
	"fmt"

	runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
)

// ContainerStats returns stats for a container stats request based on container id.
func (ds *dockerService) ContainerStats(_ context.Context, r *runtimeapi.ContainerStatsRequest) (*runtimeapi.ContainerStatsResponse, error) {
	return nil, fmt.Errorf("not implemented")
}

// ListContainerStats returns stats for a list container stats request based on a filter.
func (ds *dockerService) ListContainerStats(_ context.Context, r *runtimeapi.ListContainerStatsRequest) (*runtimeapi.ListContainerStatsResponse, error) {
	return nil, fmt.Errorf("not implemented")
}

// +build !linux,!windows

/*
Copyright 2017 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 dockershim

import (
	"fmt"

	runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
)

func (ds *dockerService) getContainerStats(containerID string) (*runtimeapi.ContainerStats, error) {
	return nil, fmt.Errorf("not implemented")
}

Fix compile on non windows linux systems


package main

import (
	"bufio"
	"fmt"
	"net"
)

func clientLoop(conn net.Conn, clientId int) {
	clientWriteBytes(conn, motd)
	clientWrite(conn, "\nDragonroar!\nV0026\n")

	reader := bufio.NewReader(conn)
	for {
		incoming, err := reader.ReadString('\n')
		if err != nil {
			break
		}
		if incoming[0] == '"' {
			chanBroadcast <- fmt.Sprintf("Client %d: %s", clientId, incoming[1:])
		} else {
			clientWrite(conn, "\n(That just won't do.)\n")
		}
	}

	chanDeadConns <- conn
}

package main

import (
	"bufio"
	"fmt"
	"net"
)

func clientLoop(conn net.Conn, clientId int) {
	clientWriteBytes(conn, motd)
	clientWrite(conn, "\nDragonroar!\nV0026\n")

	reader := bufio.NewReader(conn)
	for {
		incoming, err := reader.ReadString('\n')
		if err != nil {
			break
		}
		if incoming[0] == '"' {
			chanBroadcast <- fmt.Sprintf("(Client %d: %s", clientId, incoming[1:])
		} else {
			clientWrite(conn, "\n(That just won't do.\n")
		}
	}

	chanDeadConns <- conn
}

Fix not prepending output for text display properly


package main

import (
	"fmt"
	"os"

	"gopkg.in/src-d/go-git.v4"
	. "gopkg.in/src-d/go-git.v4/_examples"
)

// Pull changes from a remote repository
func main() {
	CheckArgs("<path>")
	path := os.Args[1]

	// We instance\iate a new repository targeting the given path (the .git folder)
	r, err := git.PlainOpen(path)
	CheckIfError(err)

	// Get the working directory for the repository
	w, err := r.Worktree()
	CheckIfError(err)

	// Pull the latest changes from the origin remote and merge into the current branch
	Info("git pull origin")
	err = w.Pull(&git.PullOptions{RemoteName: "origin"})
	CheckIfError(err)

	// Print the latest commit that was just pulled
	ref, err := r.Head()
	CheckIfError(err)
	commit, err := r.CommitObject(ref.Hash())
	CheckIfError(err)

	fmt.Println(commit)
}

package main

import (
	"fmt"
	"os"

	"gopkg.in/src-d/go-git.v4"
	. "gopkg.in/src-d/go-git.v4/_examples"
)

// Pull changes from a remote repository
func main() {
	CheckArgs("<path>")
	path := os.Args[1]

	// We instantiate a new repository targeting the given path (the .git folder)
	r, err := git.PlainOpen(path)
	CheckIfError(err)

	// Get the working directory for the repository
	w, err := r.Worktree()
	CheckIfError(err)

	// Pull the latest changes from the origin remote and merge into the current branch
	Info("git pull origin")
	err = w.Pull(&git.PullOptions{RemoteName: "origin"})
	CheckIfError(err)

	// Print the latest commit that was just pulled
	ref, err := r.Head()
	CheckIfError(err)
	commit, err := r.CommitObject(ref.Hash())
	CheckIfError(err)

	fmt.Println(commit)
}

Fix typo on pull example


package main

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

	"gopkg.in/gcfg.v1"
)

var serverConfig = struct {
	Server struct {
		Port string
	}
	Message struct {
		Timeout int
	}
	TLS struct {
		UseHTTPS bool
		Cert     string
		Key      string
	}
	WebSocketAuth struct {
		Username string
		Password string
	}
}{}

func readConfig() {
	log.Println("Reading config")
	filebytes, _ := ioutil.ReadFile("webscripthook.server.ini")
	cfgStr := string(filebytes)
	fmt.Println(cfgStr)
	err := gcfg.ReadStringInto(&serverConfig, cfgStr)
	if err != nil {
		log.Fatalf("Failed to parse gcfg data: %s", err)
	}
}

package main

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

	"gopkg.in/gcfg.v1"
)

var serverConfig = struct {
	Server struct {
		Port string
	}
	Message struct {
		Timeout int
	}
	TLS struct {
		UseHTTPS bool
		Cert     string
		Key      string
	}
}{}

func readConfig() {
	log.Println("Reading config")
	filebytes, _ := ioutil.ReadFile("webscripthook.server.ini")
	cfgStr := string(filebytes)
	fmt.Println(cfgStr)
	err := gcfg.ReadStringInto(&serverConfig, cfgStr)
	if err != nil {
		log.Fatalf("Failed to parse gcfg data: %s", err)
	}
}

Remove auth from server config struct


package lua

import (
	"regexp"
	"testing"
)

// https://github.com/Shopify/go-lua/pull/63
func TestPushFStringPointer(t *testing.T) {
	l := NewState()
	l.PushFString("%p %s", l, "test")

	actual := CheckString(l, -1)
	ok, err := regexp.MatchString("0x[0-9a-f]+ test", actual)
	if !ok {
		t.Error("regex did not match")
	} else if err != nil {
		t.Errorf("regex error: %s", err.Error())
	}
}

package lua

import (
	"fmt"
	"testing"
)

func TestPushFStringPointer(t *testing.T) {
	l := NewState()
	l.PushFString("%p %s", l, "test")

	expected := fmt.Sprintf("%p %s", l, "test")
	actual := CheckString(l, -1)
	if expected != actual {
		t.Errorf("PushFString, expected \"%s\" but found \"%s\"", expected, actual)
	}
}

Use exact string match for PushFString test.


package schema

// CommandType is an enum of the type that can be represented by a schema.
type CommandType int //go:generate stringer -type=CommandType :: manual

const (
	CommandInvalid CommandType = iota
	CommandList
	CommandCreate
	CommandRead
	CommandUpdate
	CommandDelete
	CommandManipulateMulti
	CommandManipulateSingle
	CommandManipulateIDOnly
	CommandCustom
)

func (c CommandType) IsRequiredIDType() bool {
	switch c {
	case CommandRead, CommandUpdate, CommandDelete, CommandManipulateMulti, CommandManipulateSingle, CommandManipulateIDOnly:
		return true
	default:
		return false
	}
}

func (c CommandType) IsNeedSingleIDType() bool {
	return c == CommandManipulateSingle
}

func (c CommandType) IsNeedIDOnlyType() bool {
	return c == CommandManipulateIDOnly
}

func (c CommandType) IsNeedConfirmType() bool {
	switch c {
	case CommandCreate, CommandUpdate, CommandDelete, CommandManipulateMulti, CommandManipulateSingle, CommandManipulateIDOnly, CommandCustom:
		return true
	default:
		return false
	}
}

package schema

// CommandType is an enum of the type that can be represented by a schema.
type CommandType int //go:generate stringer -type=CommandType :: manual

const (
	CommandInvalid CommandType = iota
	CommandList
	CommandCreate
	CommandRead
	CommandUpdate
	CommandDelete
	CommandManipulateMulti
	CommandManipulateSingle
	CommandManipulateIDOnly
	CommandCustom
)

func (c CommandType) IsRequiredIDType() bool {
	switch c {
	case CommandRead, CommandUpdate, CommandDelete, CommandManipulateMulti, CommandManipulateSingle, CommandManipulateIDOnly:
		return true
	default:
		return false
	}
}

func (c CommandType) IsNeedSingleIDType() bool {
	return c == CommandManipulateSingle || c == CommandRead
}

func (c CommandType) IsNeedIDOnlyType() bool {
	return c == CommandManipulateIDOnly
}

func (c CommandType) IsNeedConfirmType() bool {
	switch c {
	case CommandCreate, CommandUpdate, CommandDelete, CommandManipulateMulti, CommandManipulateSingle, CommandManipulateIDOnly, CommandCustom:
		return true
	default:
		return false
	}
}

Make the read command target to only a single resource


package ebay

import "strings"

type ebayErrors []ebayResponseError

func (err ebayErrors) Error() string {
	var errors []string

	for _, e := range err {
		errors = append(errors, e.LongMessage)
	}

	return strings.Join(errors, ",")
}

func (errs ebayErrors) RevisionError() bool {
	for _, err := range errs {
		if err.ErrorCode == 10039 || err.ErrorCode == 10029 || err.ErrorCode == 21916916 {
			return true
		}
	}

	return false
}

func (errs ebayErrors) ListingEnded() bool {
	for _, err := range errs {
		if err.ErrorCode == 291 {
			return true
		}
	}

	return false
}

Add RevisionError and ListingEnded error functions


package logic

import (
	"fmt"
	"testing"
	"time"

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

func TestPauseCommandFromJson(t *testing.T) {

	mapper := NewActionsMapper()
	a := &ActionService{}
	mapper.Load(a)

	if a, ok := a.GetByUuid("actionuuid1").(*action); ok {
		if c, ok := a.Commands[1].(*command_pause); ok {
			fmt.Printf("%v", c.pause)
			assert.Equal(t, time.Duration(10000000), c.pause)
			return
		}
	}

	t.Error("Failed to assert duration of pause command")
}

package logic

import (
	"testing"
	"time"

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

func TestPauseCommandFromJson(t *testing.T) {

	mapper := NewActionsMapper()
	a := &ActionService{}
	mapper.Load(a)

	if a, ok := a.GetByUuid("actionuuid1").(*action); ok {
		if c, ok := a.Commands[1].(*command_pause); ok {
			t.Logf("%v", c.pause)
			assert.Equal(t, time.Duration(10000000), c.pause)
			return
		}
	}

	t.Error("Failed to assert duration of pause command")
}

Fix test issue when using goconvey


package main

import (
	"os"
)

func getBenchmarkInput(filename string) (output []BenchmarkInput, err error) {

	defer func() {
		if r := recover(); r != nil {
			err = r.(error)
		}
	}()

	_ = readRawData(filename)

	return output, err
}

func readRawData(filename string) (output []string) {

	fd, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer fd.Close()

	return output
}

package main

import (
	"bufio"
	"os"
	"strings"
)

func getBenchmarkInput(filename string) (output []BenchmarkInput, err error) {

	defer func() {
		if r := recover(); r != nil {
			err = r.(error)
		}
	}()

	fd, err := os.Open(filename)
	if err != nil {
		panic(err)
	}
	defer fd.Close()

	for scanner := bufio.NewScanner(fd); scanner.Scan(); {
		text := scanner.Text()

		comment := strings.Index(text, "#")
		if comment != -1 {
			text = text[:comment]
		}

		text = strings.TrimSpace(text)
		if text == "" {
			continue
		}
	}

	return output, err
}

Remove comment and whitespace in getBenchmarkInput


// +build windows
// +build !confonly

package tls

import "crypto/x509"

func (c *Config) getCertPool() (*x509.CertPool, error) {
	if c.DisableSystemRoot {
		return c.loadSelfCertPool()
	}

	return nil, nil
}

// +build windows
// +build !confonly

package tls

import "crypto/x509"

func (c *Config) getCertPool() (*x509.CertPool, error) {
	return c.loadSelfCertPool()
}

Fix self-signed certificates on Windows


package filters

import (
	"bones/repositories"
	"bones/web/context"
	"log"
	"net/http"
)

func Params(res http.ResponseWriter, req *http.Request, chain *RequestFilterChain) {
	err := context.InitParams(req)

	if err != nil {
		panic(err)
	}

	chain.next()
}

func Authenticate(res http.ResponseWriter, req *http.Request, chain *RequestFilterChain) {
	session := repositories.Session(res, req)
	value := session.Value("user_id")

	if id, ok := value.(int); ok {
		user, err := repositories.Users.FindById(id)

		if err != nil {
			if err != repositories.NotFoundError {
				log.Println("Error when finding user for authentication:", err)
			}

			redirectToLogin(res, req)

			return
		}

		context.SetCurrentUser(req, user)
		chain.next()
	}

	redirectToLogin(res, req)
}

func redirectToLogin(res http.ResponseWriter, req *http.Request) {
	http.Redirect(res, req, "/login", 302)
}

package filters

import (
	"bones/repositories"
	"bones/web/context"
	"log"
	"net/http"
)

func Params(res http.ResponseWriter, req *http.Request, chain *RequestFilterChain) {
	err := context.InitParams(req)

	if err != nil {
		panic(err)
	}

	chain.next()
}

func Authenticate(res http.ResponseWriter, req *http.Request, chain *RequestFilterChain) {
	session := repositories.Session(res, req)
	value := session.Value("user_id")

	if id, ok := value.(int); ok {
		user, err := repositories.Users.FindById(id)

		if err != nil {
			if err != repositories.NotFoundError {
				log.Println("Error when finding user for authentication:", err)
			}

			redirectToLogin(res, req)

			return
		}

		context.SetCurrentUser(req, user)
		chain.next()
	} else {
		redirectToLogin(res, req)
	}
}

func redirectToLogin(res http.ResponseWriter, req *http.Request) {
	http.Redirect(res, req, "/login", 302)
}

Fix "http: multiple response.WriteHeader calls"


package oak

import (
	"os"
	"testing"

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

func TestDefaultConfig(t *testing.T) {
	err := LoadConf("default.config")
	assert.Nil(t, err)
	assert.Equal(t, conf, SetupConfig)
	f, err := os.Open("default.config")
	assert.Nil(t, err)
	err = LoadConfData(f)
	assert.Nil(t, err)
	SetupConfig = Config{
		Assets:              Assets{"a/", "a/", "i/", "f/"},
		Debug:               Debug{"FILTER", "INFO"},
		Screen:              Screen{0, 0, 240, 320, 2},
		Font:                Font{"hint", 20.0, 36.0, "luxisr.ttf", "green"},
		FrameRate:           30,
		DrawFrameRate:       30,
		Language:            "German",
		Title:               "Some Window",
		BatchLoad:           true,
		GestureSupport:      true,
		LoadBuiltinCommands: true,
	}
	initConf()
	assert.Equal(t, SetupConfig, conf)
	// Failure to load
	err = LoadConf("nota.config")
	assert.NotNil(t, err)
}

package oak

import (
	"os"
	"testing"

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

func TestDefaultConfig(t *testing.T) {
	err := LoadConf("default.config")
	assert.Nil(t, err)
	assert.Equal(t, conf, SetupConfig)
	f, err := os.Open("default.config")
	assert.Nil(t, err)
	err = LoadConfData(f)
	assert.Nil(t, err)
	SetupConfig = Config{
		Assets:              Assets{"a/", "a/", "i/", "f/"},
		Debug:               Debug{"FILTER", "INFO"},
		Screen:              Screen{0, 0, 240, 320, 2, 0, 0},
		Font:                Font{"hint", 20.0, 36.0, "luxisr.ttf", "green"},
		FrameRate:           30,
		DrawFrameRate:       30,
		Language:            "German",
		Title:               "Some Window",
		BatchLoad:           true,
		GestureSupport:      true,
		LoadBuiltinCommands: true,
	}
	initConf()
	assert.Equal(t, SetupConfig, conf)
	// Failure to load
	err = LoadConf("nota.config")
	assert.NotNil(t, err)
}

Update TestDefaultConfig to include target dimensions


package stripe

// Country is the list of supported countries
type Country string

// VerificationFieldsList lists the fields needed for an account verification.
// For more details see https://stripe.com/docs/api#country_spec_object-verification_fields.
type VerificationFieldsList struct {
	AdditionalFields []string `json:"additional"`
	Minimum          []string `json:"minimum"`
}

// CountrySpec is the resource representing the rules required for a Stripe account.
// For more details see https://stripe.com/docs/api/#country_specs.
type CountrySpec struct {
	DefaultCurrency                Currency                                    `json:"default_currency"`
	ID                             string                                      `json:"id"`
	SupportedBankAccountCurrencies map[Currency][]Country                      `json:"supported_bank_account_currencies"`
	SupportedPaymentCurrencies     []Currency                                  `json:"supported_payment_currencies"`
	SupportedPaymentMethods        []string                                    `json:"supported_payment_methods"`
	VerificationFields             map[LegalEntityType]*VerificationFieldsList `json:"verification_fields"`
}

// CountrySpecParams are the parameters allowed during CountrySpec retrieval.
type CountrySpecParams struct {
	Params `form:"*"`
}

// CountrySpecList is a list of country specs as retrieved from a list endpoint.
type CountrySpecList struct {
	ListMeta
	Data []*CountrySpec `json:"data"`
}

// CountrySpecListParams are the parameters allowed during CountrySpec listing.
type CountrySpecListParams struct {
	ListParams `form:"*"`
}

package stripe

// Country is the list of supported countries
type Country string

// VerificationFieldsList lists the fields needed for an account verification.
// For more details see https://stripe.com/docs/api#country_spec_object-verification_fields.
type VerificationFieldsList struct {
	AdditionalFields []string `json:"additional"`
	Minimum          []string `json:"minimum"`
}

// CountrySpec is the resource representing the rules required for a Stripe account.
// For more details see https://stripe.com/docs/api/#country_specs.
type CountrySpec struct {
	DefaultCurrency                Currency                                    `json:"default_currency"`
	ID                             string                                      `json:"id"`
	SupportedBankAccountCurrencies map[Currency][]Country                      `json:"supported_bank_account_currencies"`
	SupportedPaymentCurrencies     []Currency                                  `json:"supported_payment_currencies"`
	SupportedPaymentMethods        []string                                    `json:"supported_payment_methods"`
	SupportedTransferCountries     []string                                    `json:"supported_transfer_countries"`
	VerificationFields             map[LegalEntityType]*VerificationFieldsList `json:"verification_fields"`
}

// CountrySpecParams are the parameters allowed during CountrySpec retrieval.
type CountrySpecParams struct {
	Params `form:"*"`
}

// CountrySpecList is a list of country specs as retrieved from a list endpoint.
type CountrySpecList struct {
	ListMeta
	Data []*CountrySpec `json:"data"`
}

// CountrySpecListParams are the parameters allowed during CountrySpec listing.
type CountrySpecListParams struct {
	ListParams `form:"*"`
}

Add support for `supported_transfer_countries` on CountrySpec


package backend

import (
	"imperial-splendour-bundler/backend/customErrors"
	"os"
)

func (a *API) SelectSourceDir() (string, error) {
	dir := a.dialog.SelectDirectory()

	sourceDir, err := os.Stat(dir)
	if err != nil || !sourceDir.IsDir() {
		return "", customErrors.InvalidDir
	}
	return dir + "/", nil
}

func (a *API) SelectFileListLocation() (string, error) {
	file := a.dialog.SelectFile("Select the file list file", "*.txt")

	fileListFile, err := os.Stat(file)
	if err != nil || fileListFile.IsDir() {
		return "", customErrors.InvalidFile
	}
	return file + "/", nil
}

package backend

import (
	"imperial-splendour-bundler/backend/customErrors"
	"os"
)

func (a *API) SelectSourceDir() (string, error) {
	dir := a.dialog.SelectDirectory()

	sourceDir, err := os.Stat(dir)
	if err != nil || !sourceDir.IsDir() {
		return "", customErrors.InvalidDir
	}
	return dir + "/", nil
}

func (a *API) SelectFileListLocation() (string, error) {
	file := a.dialog.SelectFile("Select the file list file", "*.txt")

	fileListFile, err := os.Stat(file)
	if err != nil || fileListFile.IsDir() {
		return "", customErrors.InvalidFile
	}
	return file, nil
}

Fix broken file list path getter


package turtle

// Version of the turtle library
const Version = "v0.1.0"

// Emojis maps a name to an Emoji
var Emojis = make(map[string]*Emoji)

func init() {
	for _, e := range emojis {
		Emojis[e.Name] = e
	}
}

// Search emojis by a name
func Search(s string) []*Emoji {
	return search(emojis, s)
}

// Keyword filters the emojis by a keyword
func Keyword(k string) []*Emoji {
	return keyword(emojis, k)
}

// Category filters the emojis by a category
func Category(c string) []*Emoji {
	return category(emojis, c)
}

package turtle

// Version of the turtle library
const Version = "v0.1.0"

// Emojis maps a name to an Emoji
var Emojis = make(map[string]*Emoji)

// EmojisByChar maps a character to an Emoji
var EmojisByChar = make(map[string]*Emoji)

func init() {
	for _, e := range emojis {
		Emojis[e.Name] = e
		EmojisByChar[e.Char] = e
	}
}

// Search emojis by a name
func Search(s string) []*Emoji {
	return search(emojis, s)
}

// Keyword filters the emojis by a keyword
func Keyword(k string) []*Emoji {
	return keyword(emojis, k)
}

// Category filters the emojis by a category
func Category(c string) []*Emoji {
	return category(emojis, c)
}

Add new map for emoji characters to emoji


package scamp

import (
	"io/ioutil"
	"testing"
)

var pemPath = "./../fixtures/ticket_verify_public_key.pem"

func TestTicket(t *testing.T) {
	good, err := ioutil.ReadFile("./../fixtures/processor-dispatch.token")
	if err != nil {
		t.Fatalf(err.Error())
	}

	if good == nil {
		t.Fatalf("nil ticket")
	}

	tkt, err := VerifyTicket(string(good), pemPath)
	if err != nil {
		t.Errorf("failed to verify correct ticket: %s", err)
	}
	t.Logf("ok %+v, %+v", tkt, err)

	tkt, err = VerifyTicket(string(good[:len(good)-1]), pemPath)
	if err == nil {
		t.Errorf("bad ticket accepted")
	}
	t.Logf("ok (should fail) %+v, %+v", tkt, err)

	tkt, err = VerifyTicket(string(good[1:]), pemPath)
	if err == nil {
		t.Errorf("bad ticket accepted")
	}
	t.Logf("ok (should fail) %+v, %+v", tkt, err)
}

package scamp

import (
	"io/ioutil"
	"path/filepath"
	"runtime"
	"testing"
)

var (
	// Get root of the project.
	_, base, _, _ = runtime.Caller(0)
	basePath      = filepath.Dir(base)
	fixturesPath  = basePath + "/../fixtures"
	pemPath       = fixturesPath + "/ticket_verify_public_key.pem"
	dispatchPath  = fixturesPath + "/processor-dispatch.token"
)

func TestTicket(t *testing.T) {
	t.Logf("basepath: %v", basePath)
	t.Logf("fixtures path: %v", fixturesPath)
	t.Logf("pem path: %v", pemPath)
	good, err := ioutil.ReadFile(dispatchPath)
	if err != nil {
		t.Fatalf(err.Error())
	}

	if good == nil {
		t.Fatalf("nil ticket")
	}

	tkt, err := VerifyTicket(string(good), pemPath)
	if err != nil {
		t.Errorf("failed to verify correct ticket: %s", err)
	}
	t.Logf("ok %+v, %+v", tkt, err)

	tkt, err = VerifyTicket(string(good[:len(good)-1]), pemPath)
	if err == nil {
		t.Errorf("bad ticket accepted")
	}
	t.Logf("ok (should fail) %+v, %+v", tkt, err)

	tkt, err = VerifyTicket(string(good[1:]), pemPath)
	if err == nil {
		t.Errorf("bad ticket accepted")
	}
	t.Logf("ok (should fail) %+v, %+v", tkt, err)
}

Use project base path to find fixtures


// +build linux,darwin

package github

import (
	"code.google.com/p/go.crypto/ssh/terminal"
)

func isTerminal(fd uintptr) bool {
	return terminal.IsTerminal(int(fd))
}

// +build !windows

package github

import (
	"code.google.com/p/go.crypto/ssh/terminal"
)

func isTerminal(fd uintptr) bool {
	return terminal.IsTerminal(int(fd))
}

Use not windows build tag


package sqlparser

// Magicify runs the SQL passed in, and a table name, throught a customized
// TextQL SQL Parser. This provides the following functionality:
//  - Queries that do not start with SELECT are implictly mapped to SELECT statements
//  - Queries that are missing a FROM, have the FROM inserted with tableName
func Magicify(sql string, tableName string) string {
	if tableName == "" {
		return sql
	}

	statement, err := Parse(sql)

	if err != nil {
		return sql
	}

	switch statement := statement.(type) {
	case *Select:
		if statement.From == nil {
			tableName := &TableName{[]byte(tableName), nil}
			aliasedTableExpr := AliasedTableExpr{tableName, nil, nil}
			tableExprs := TableExprs{&aliasedTableExpr}
			statement.From = &From{Type: AST_FROM, Expr: tableExprs}
		}
		return generateQuery(statement)
	default:
		return sql
	}
}

func generateQuery(statement Statement) string {
	buf := NewTrackedBuffer(nil)
	statement.Format(buf)
	return buf.String()
}

package sqlparser

// Magicify runs the SQL passed in, and a table name, throught a customized
// TextQL SQL Parser. This provides the following functionality:
//  - Queries that do not start with SELECT are implictly mapped to SELECT statements
//  - Queries that are missing a FROM, have the FROM inserted with tableName
func Magicify(sql string, tableName string) string {
	if tableName == "" {
		return sql
	}

	statement, err := Parse(sql)

	if err != nil {
		return sql
	}

	switch statement := statement.(type) {
	case *Select:
		replaceFromInSelect(statement, tableName)
		return generateQuery(statement)
	default:
		return sql
	}
}

func replaceFromInSelect(statement *Select, tableName string) {
	if statement.From == nil {
		tableName := &TableName{[]byte(tableName), nil}
		aliasedTableExpr := AliasedTableExpr{tableName, nil, nil}
		tableExprs := TableExprs{&aliasedTableExpr}
		statement.From = &From{Type: AST_FROM, Expr: tableExprs}
	} else {
		for _, expr := range statement.From.Expr {
			switch expr := expr.(type) {
			case *AliasedTableExpr:
				switch subQuery := expr.Expr.(type) {
				case *Subquery:
					switch selectSubQuery := subQuery.Select.(type) {
					case *Select:
						replaceFromInSelect(selectSubQuery, tableName)
					default:
						return
					}
				default:
					return
				}
			default:
				return
			}
		}
	}
}

func generateQuery(statement Statement) string {
	buf := NewTrackedBuffer(nil)
	statement.Format(buf)
	return buf.String()
}

Fix subselect implict from magic


package lib

// Region on Vultr
type Region struct {
	ID        int    `json:"DCID,string"`
	Name      string `json:"name"`
	Country   string `json:"country"`
	Continent string `json:"continent"`
	State     string `json:"state"`
}

func (c *Client) GetRegions() ([]Region, error) {
	var regionMap map[string]Region
	if err := c.get(`regions/list`, &regionMap); err != nil {
		return nil, err
	}

	var regionList []Region
	for _, os := range regionMap {
		regionList = append(regionList, os)
	}
	return regionList, nil
}

package lib

// Region on Vultr
type Region struct {
	ID        int    `json:"DCID,string"`
	Name      string `json:"name"`
	Country   string `json:"country"`
	Continent string `json:"continent"`
	State     string `json:"state"`
	Ddos      bool   `json:"ddos_protection"`
}

func (c *Client) GetRegions() ([]Region, error) {
	var regionMap map[string]Region
	if err := c.get(`regions/list`, &regionMap); err != nil {
		return nil, err
	}

	var regionList []Region
	for _, os := range regionMap {
		regionList = append(regionList, os)
	}
	return regionList, nil
}

Add ddos_protection field to Region struct


package gotop

import (
	"encoding/json"
	"fmt"
	"testing"
	"time"
)

func TestMemoryUsage(t *testing.T) {
	memInfoChan := make(chan MemInfo)
	go MemoryUsage(memInfoChan, time.Second)
	iterations := 0
	for {
		memInfo, ok := <-memInfoChan
		if ok == false || iterations > 3 {
			break
		}
		a, _ := json.Marshal(memInfo)
		fmt.Println(string(a))
	}
}

package gotop

import (
	"encoding/json"
	"fmt"
	"testing"
	"time"
)

func TestMemoryUsage(t *testing.T) {
	memInfoChan := make(chan MemInfo)
	go MemoryUsage(memInfoChan, time.Second)
	iterations := 0
	for {
		memInfo, ok := <-memInfoChan
		iterations = iterations + 1
		if ok == false || iterations > 3 {
			break
		}
		a, _ := json.Marshal(memInfo)
		fmt.Println(string(a))
	}
}

Fix an issue where TestMemoryUsage() would never finish


package models

import (
	"fmt"
	"golang.org/x/crypto/sha3"
	"time"
)

// Feed is a single source of articles.
type Feed struct {
	ID       int64
	FolderID int64

	Title       string
	Description string
	URL         string
	Latest      time.Time
}

// Hash returns a SHA256 hash of this object.
func (a *Feed) Hash() string {
	h := sha3.New256()
	h.Write([]byte(a.Title))
	h.Write([]byte(a.Description))
	h.Write([]byte(a.URL))
	return fmt.Sprintf("%x", h.Sum(nil))
}

package models

import (
	"fmt"
	"golang.org/x/crypto/sha3"
	"time"
)

// Feed is a single source of articles.
type Feed struct {
	ID       int64
	FolderID int64

	Title       string
	Description string
	URL         string
	Link        string
	Latest      time.Time
}

// Hash returns a SHA256 hash of this object.
func (a *Feed) Hash() string {
	h := sha3.New256()
	h.Write([]byte(a.Title))
	h.Write([]byte(a.Description))
	h.Write([]byte(a.URL))
	h.Write([]byte(a.Link))
	return fmt.Sprintf("%x", h.Sum(nil))
}

Support an additional Link field in the models.Feed object.


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

package testing

import (
	"time"

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

// ShortWait is a reasonable amount of time to block waiting for something that
// shouldn't actually happen. (as in, the test suite will *actually* wait this
// long before continuing)
const ShortWait = 50 * time.Millisecond

// LongWait is used when something should have already happened, or happens
// quickly, but we want to make sure we just haven't missed it. As in, the test
// suite should proceed without sleeping at all, but just in case. It is long
// so that we don't have spurious failures without actually slowing down the
// test suite
const LongWait = 10 * time.Second

var LongAttempt = &utils.AttemptStrategy{
	Total: LongWait,
	Delay: ShortWait,
}

// SupportedSeries lists the series known to Juju.
var SupportedSeries = []string{"precise", "quantal", "raring", "saucy", "trusty"}

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

package testing

import (
	"time"

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

// ShortWait is a reasonable amount of time to block waiting for something that
// shouldn't actually happen. (as in, the test suite will *actually* wait this
// long before continuing)
const ShortWait = 50 * time.Millisecond

// LongWait is used when something should have already happened, or happens
// quickly, but we want to make sure we just haven't missed it. As in, the test
// suite should proceed without sleeping at all, but just in case. It is long
// so that we don't have spurious failures without actually slowing down the
// test suite
const LongWait = 10 * time.Second

var LongAttempt = &utils.AttemptStrategy{
	Total: LongWait,
	Delay: ShortWait,
}

// SupportedSeries lists the series known to Juju.
var SupportedSeries = []string{"precise", "quantal", "raring", "saucy", "trusty", "utopic"}

Add utopic to supported series


// Package datastore implements an App Engine datastore driver
// the Gondola's ORM.
//
// This package is only available when building your application using
// the App Engine Go SDK. To enable the driver, import its package:
//
//  import (
//      _ "gnd.la/orm/driver/datastore"
//  )
//
// Some caveats your need to be aware of:
//
//  - The datastore driver does not support OR nor NEQ queries.
//  - The datastore driver is not relational (no support for foreign keys nor JOINs).
//  - While auto_increment its supported, the numeric IDs won't be sequential, only
//      strictly increasing (i.e. IDs will always increase, but there might be gaps
//      between them).
package datastore

// Package datastore implements an App Engine datastore driver
// the Gondola's ORM.
//
// This package is only available when building your application using
// the App Engine Go SDK. To enable the driver, import its package:
//
//  import (
//      _ "gnd.la/orm/driver/datastore"
//  )
//
// The URL format for this package is:
//
//  datastore://
//
// No driver specific options are supported.
//
// Some caveats your need to be aware of:
//
//  - The datastore driver does not support OR nor NEQ queries.
//  - The datastore driver is not relational (no support for foreign keys nor JOINs).
//  - While auto_increment its supported, the numeric IDs won't be sequential, only
//      strictly increasing (i.e. IDs will always increase, but there might be gaps
//      between them).
package datastore

Add example URL in datastore ORM driver


package tools

import (
	"log"
	"strings"
	"fmt"
)

// UploadFile used to upload file by S3 pre-signed URL
func UploadFile(path, url string) int {
	log.Println("Uploading file from path:", path)
	file, info := prepareFile(path)
	resp := sendRequest(url, &file, info)
	return getStatusOfUpload(resp)
}

// GetFileName returns file name from path string
func GetFileName(path string) string {
	if !strings.Contains(path, "/") {
		return path
	}
	pos := strings.LastIndex(path, "/")
	return string(path[pos+1:])
}

// GenerateReportURL generate URL to test report from ARN
func GenerateReportURL(arn string) string {
	URL := "https://us-west-2.console.aws.amazon.com/devicefarm/home?region=us-west-2#/projects/%s/runs/%s"
	index := strings.Index(arn, ":run:")
	if index == -1 {
		log.Println("Can't generate test report URL from ARN:", arn)
		return ""
	}
	str := arn[index+5:]
	index = strings.Index(str, "/")
	project := str[:index]
	run := str[index+1:]
	return fmt.Sprintf(URL, project, run)
}

package tools

import (
	"fmt"
	"log"
	"strings"
)

// UploadFile used to upload file by S3 pre-signed URL
func UploadFile(path, url string) int {
	log.Println("Uploading file from path:", path)
	file, info := prepareFile(path)
	resp := sendRequest(url, &file, info)
	return getStatusOfUpload(resp)
}

// GetFileName returns file name from path string
func GetFileName(path string) string {
	if !strings.Contains(path, "/") {
		return path
	}
	pos := strings.LastIndex(path, "/")
	return string(path[pos+1:])
}

// GenerateReportURL generate URL to test report from ARN
func GenerateReportURL(arn string) string {
	URL := "https://us-west-2.console.aws.amazon.com/devicefarm/home?region=us-west-2#/projects/%s/runs/%s"
	index := strings.Index(arn, ":run:")
	if index == -1 {
		log.Println("Can't generate test report URL from ARN:", arn)
		return ""
	}
	str := arn[index+5:]
	index = strings.Index(str, "/")
	project := str[:index]
	run := str[index+1:]
	return fmt.Sprintf(URL, project, run)
}

Fix gofmt formating for a file


package image

import (
	"testing"
)

func TestWriteBMP(t *testing.T) {
	filename := "test.bmp"

	var di DcmImage

	di.Columns = 64
	di.Rows = 64
	di.BitsAllocated = 16
	di.BitsStored = 12
	di.HighBit = 11
	err := di.WriteBMP(filename, 8, 0)
	if err != nil {
		t.Errorf("WriteBMP() %s", err.Error())
	}
}

package image

import (
	"testing"
)

func TestWrite8BMP(t *testing.T) {
	filename := "8.bmp"

	var di DcmImage

	di.Columns = 64
	di.Rows = 64
	di.BitsAllocated = 8
	di.BitsStored = 12
	di.HighBit = 11
	err := di.WriteBMP(filename, 8, 0)
	if err != nil {
		t.Errorf("WriteBMP() %s", err.Error())
	}
}

func TestWrite16BMP(t *testing.T) {
	filename := "16.bmp"

	var di DcmImage

	di.Columns = 64
	di.Rows = 64
	di.BitsAllocated = 16
	di.BitsStored = 12
	di.HighBit = 11
	err := di.WriteBMP(filename, 16, 0)
	if err == nil {
		t.Errorf("WriteBMP() %s", err.Error())
	}
}

func TestWrite24BMP(t *testing.T) {
	filename := "24.bmp"

	var di DcmImage

	di.Columns = 64
	di.Rows = 64
	di.BitsAllocated = 24
	di.BitsStored = 12
	di.HighBit = 11
	err := di.WriteBMP(filename, 24, 0)
	if err != nil {
		t.Errorf("WriteBMP() %s", err.Error())
	}
}

func TestWrite32BMP(t *testing.T) {
	filename := "32.bmp"

	var di DcmImage

	di.Columns = 64
	di.Rows = 64
	di.BitsAllocated = 32
	di.BitsStored = 12
	di.HighBit = 11
	err := di.WriteBMP(filename, 32, 0)
	if err != nil {
		t.Errorf("WriteBMP() %s", err.Error())
	}
}

Add more test cases for testing write BMP file.


/*
Copyright 2018 Google LLC

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

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

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

package cmd

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

// completionCmd represents the completion command
var completionCmd = &cobra.Command{
	Use:   "completion",
	Short: "Generate shell completion scripts",
	Long: `To enable command completion run

eval "$(skaffold completion bash)"

To configure bash shell completion for all your sessions, add the following to your
~/.bashrc or ~/.bash_profile:

eval "$(skaffold completion bash)"`,
	Run: func(cmd *cobra.Command, args []string) {
		rootCmd.GenBashCompletion(os.Stdout);
	},
}

func NewCmdCompletion(out io.Writer) *cobra.Command {
	return completionCmd
}

Add newline at the end of file


package collector

import (
	"fullerite/metric"

	l "github.com/Sirupsen/logrus"
)

// NerveHTTPD discovers Apache servers via Nerve config
// and reports metric for them
type NerveHTTPD struct {
	baseCollector
}

func init() {
	RegisterCollector("NerveHTTPD", newNerveHTTPD)
}

func newNerveHTTPD(channel chan metric.Metric, initialInterval int, log *l.Entry) Collector {
	c := new(NerveHTTPD)
	c.channel = channel
	c.interval = initialInterval
	c.log = log

	c.name = collectorName
	return c
}

// Configure the collector
func (c *NerveHTTPD) Configure(configMap map[string]interface{}) {

}

// Collect the metrics
func (c *NerveHTTPD) Collect() {

}

package collector

import (
	"fullerite/metric"
	"time"

	l "github.com/Sirupsen/logrus"
)

// NerveHTTPD discovers Apache servers via Nerve config
// and reports metric for them
type NerveHTTPD struct {
	baseCollector

	configFilePath string
	queryPath      string
	timeout        int
	statusTTL      time.Duration
}

func init() {
	RegisterCollector("NerveHTTPD", newNerveHTTPD)
}

func newNerveHTTPD(channel chan metric.Metric, initialInterval int, log *l.Entry) Collector {
	c := new(NerveHTTPD)
	c.channel = channel
	c.interval = initialInterval
	c.log = log

	c.name = collectorName
	c.configFilePath = "/etc/nerve/nerve.conf.json"
	c.queryPath = "server-status?auto"
	c.timeout = 2
	c.statusTTL = time.Duration(60) * time.Minute

	return c
}

// Configure the collector
func (c *NerveHTTPD) Configure(configMap map[string]interface{}) {
	if val, exists := configMap["queryPath"]; exists {
		c.queryPath = val.(string)
	}
	if val, exists := configMap["configFilePath"]; exists {
		c.configFilePath = val.(string)
	}

	if val, exists := configMap["status_ttl"]; exists {
		if t, ok := val.(int); ok {
			c.statusTTL = time.Duration(t) * time.Second
		}
	}

	c.configureCommonParams(configMap)
}

// Collect the metrics
func (c *NerveHTTPD) Collect() {

}

Add more code for NerveHTTPD collector


package gifs

type Crop struct {
	X float32 `json:"x,omitempty"`
	Y float32 `json:"y,omitempty"`

	Height float32 `json:"height,omitempty"`
	Width  float32 `json:"width,omitempty"`
}

package gifs

// Crop holds the offsets and final dimensions of the
// desired media after cropping. Both X and Y offsets
// will tell us where the top-left corner of the cropped
// media will be. Then Height and Width can determine the
// top-right, bottom-left and bottom-right coordinates.
type Crop struct {
	// X is the horizontal axis offset from the left
	X float32 `json:"x,omitempty"`
	// Y is the vertical axis offset from the top
	Y float32 `json:"y,omitempty"`
	// Height of the desired media after cropping
	Height float32 `json:"height,omitempty"`
	// Width of the desired media after cropping
	Width  float32 `json:"width,omitempty"`
}

Add comments to the Crop struct and fields


package algoholic

import "testing"

const BENCHMARK_LENGTH = 10

func TestFisherYatesShufflesEvenly(t *testing.T) {
	// Set an arbitrary maximum error from expectation - We expect each number to occur within
	// 0.7% of the probability in a list of length 10 after 1e6 iterations.
	// TODO: Determine maximum error mathematically.
	checkShufflesEvenly(t, ShuffleFisherYates, 10, 1e6, 0.007)
}

func TestRandomOrderShuffleShufflesEvenly(t *testing.T) {
	// Set an arbitrary maximum error from expectation - We expect each number to occur within
	// 1% of the probability in a list of length 10 after 1e6 iterations.
	// TODO: Determine maximum error mathematically.
	checkShufflesEvenly(t, ShuffleRandomSort, 10, 1e6, 0.01)
}

func BenchmarkFisherYatesShuffle(b *testing.B) {
	benchmarkShuffle(b, BENCHMARK_LENGTH, ShuffleFisherYates)
}

func BenchmarkRandomSortShuffle(b *testing.B) {
	benchmarkShuffle(b, BENCHMARK_LENGTH, ShuffleRandomSort)
}

package algoholic

import "testing"

const BENCHMARK_LENGTH = 10

func TestFisherYatesShufflesEvenly(t *testing.T) {
	// Set an arbitrary maximum error from expectation - We expect each number to occur within
	// 1% of the probability in a list of length 10 after 1e6 iterations.
	// TODO: Determine maximum error mathematically.
	checkShufflesEvenly(t, ShuffleFisherYates, 10, 1e6, 0.01)
}

func TestRandomOrderShuffleShufflesEvenly(t *testing.T) {
	// Set an arbitrary maximum error from expectation - We expect each number to occur within
	// 1.1% of the probability in a list of length 10 after 1e6 iterations.
	// TODO: Determine maximum error mathematically.
	checkShufflesEvenly(t, ShuffleRandomSort, 10, 1e6, 0.011)
}

func BenchmarkFisherYatesShuffle(b *testing.B) {
	benchmarkShuffle(b, BENCHMARK_LENGTH, ShuffleFisherYates)
}

func BenchmarkRandomSortShuffle(b *testing.B) {
	benchmarkShuffle(b, BENCHMARK_LENGTH, ShuffleRandomSort)
}

Update tests to reflect better seeding.


package opencv

import (
	"testing"
)

func TestLoadImage2(t *testing.T) {
	// t.Errorf("aaa")
}

package opencv

import (
	"testing"
	"fmt"
)

func TestContourArea(t *testing.T){
	img := CreateImage(100,100,IPL_DEPTH_8U,1)
	defer img.Release()
	// Creating object of area 100
	shape := []Point{
		Point{10,10},
		Point{20,10},
		Point{20,20},
		Point{10,20},
		Point{10,10}}
	for i:=0; i<(len(shape)-1); i++{
		Line(img, shape[i], shape[i+1], ScalarAll(255), 1, 8, 0)
	}
	c,n := FindContours(img, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, nil)
	fmt.Printf("Found %d contours\n", n)
	a := ContourArea(c, 0)
	fmt.Printf("Area of contour is %v \n", a)
	p := ArcLength(c,0)
	fmt.Printf("Perimeter of contour is %v \n", p)
}

func TestConvexityDefects(t *testing.T) {
	img := CreateImage(100,100,IPL_DEPTH_8U,1)
	defer img.Release()
	// Object with convex defect of 10 and 3
	shape := []Point{
		Point{10,10},
		Point{20,10},
		Point{20,20},
		Point{30,20},
		Point{30,10},
		Point{40,10},
		Point{40,40},
		Point{30,40},
		Point{30,37},
		Point{20,37},
		Point{20,40},
		Point{10,40},
		Point{10,10}}
	for i:=0; i<(len(shape)-1); i++{
		Line(img, shape[i], shape[i+1], ScalarAll(255), 1, 8, 0)
	}
	c,n := FindContours(img, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE, nil)
	fmt.Printf("Found %d contours\n", n)
	a := ContourArea(c, 0)
	fmt.Printf("Area of contour is %v \n", a)
	p := ArcLength(c,0)
	fmt.Printf("Perimeter of contour is %v \n", p)
	d, n2 := ConvexityDefects(c, 0)
	fmt.Printf("Found %d defects\n", n2)
	for i:=0; i<n2; i++{
		fmt.Printf("Found defect of size %v \n", d[i])
	}
}

Create start of testing of cxcore functions


package main

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

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

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

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

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

package main

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

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

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

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

Test that Add actually works.


package main

import (
	"fmt"
	"testing"
)

func mainTester(t *testing.T) {
	fmt.Println("Howdy buddy")
	t.Log("one test passed.")
}

package main

import (
	"fmt"
	"testing"
)

func mainTester(t *testing.T) {
	fmt.Println("Howdy buddy!!!")
	t.Log("one test passed.")
}

Test after run test main


package main

import (
	"os"
	"testing"
)

func TestMain(m *testing.M) {
	os.Setenv("FAW_ICONS_YAML_PATH", "workflow/icons.yml")
	m.Run()
}

package main

import (
	"os"
	"testing"
)

func TestMain(m *testing.M) {
	os.Setenv("FAW_ICONS_YAML_PATH", "workflow/icons.yml")
	os.Exit(m.Run())
}

Improve TestMain function for exit code


package meta

import "fmt"

// GITCOMMIT indicates which git hash the binary was built off of.
var GITCOMMIT string

// VERSION indicates which version of the binary is running.
var VERSION string

const majorRelease = "0.3.x"

// Version returns the version/commit string.
func Version() string {
	version, commit := VERSION, GITCOMMIT
	if commit == "" && version == "" {
		version, commit = majorRelease, "master"
	}
	return fmt.Sprintf("fsql version %v, built off %v", version, commit)
}

package meta

import "fmt"

// GITCOMMIT indicates which git hash the binary was built off of.
var GITCOMMIT string

// VERSION indicates which version of the binary is running.
var VERSION string

const majorRelease = "0.3.x"

// Version returns the version/commit string.
func Version() string {
	version, commit := VERSION, GITCOMMIT
	if commit == "" || version == "" {
		version, commit = majorRelease, "master"
	}
	return fmt.Sprintf("fsql version %v, built off %v", version, commit)
}

Use fallback if one of commit/version are blank (instead of both)


package main

type DisjoinSet struct {
	parent []int
	rank   []int
}

func NewDisjoinSet() *DisjoinSet {
	return &DisjoinSet{}
}

func (s *DisjoinSet) Make() int {
	s.parent = append(s.parent, -1)
	s.rank = append(s.rank, 0)
	return len(s.parent) - 1
}

func (s *DisjoinSet) Find(x int) int {
	if s.parent[x] == -1 {
		return x
	}
	return s.Find(s.parent[x])
}

func (s *DisjoinSet) Join(x, y int) {
	xRoot := s.Find(x)
	yRoot := s.Find(y)

	switch {
	case s.rank[xRoot] < s.rank[yRoot]:
		s.parent[xRoot] = yRoot
	case s.rank[xRoot] > s.rank[yRoot]:
		s.parent[yRoot] = xRoot
	default:
		s.rank[xRoot]++
		s.parent[yRoot] = xRoot
	}
}

package main

type DisjoinSet struct {
	parent []int
	rank   []int
}

func NewDisjoinSet() *DisjoinSet {
	return &DisjoinSet{}
}

func (s *DisjoinSet) Make() int {
	x := len(s.parent)
	s.parent = append(s.parent, x)
	s.rank = append(s.rank, 0)
	return x
}

func (s *DisjoinSet) Find(x int) int {
	if s.parent[x] == x {
		return x
	}
	return s.Find(s.parent[x])
}

func (s *DisjoinSet) Join(x, y int) {
	xRoot := s.Find(x)
	yRoot := s.Find(y)

	switch {
	case s.rank[xRoot] < s.rank[yRoot]:
		s.parent[xRoot] = yRoot
	case s.rank[xRoot] > s.rank[yRoot]:
		s.parent[yRoot] = xRoot
	default:
		s.rank[xRoot]++
		s.parent[yRoot] = xRoot
	}
}

Use parent[x] == x for root, not -1 as before


package actors

import (
	"github.com/cloudfoundry/cli/cf/i18n"
	goi18n "github.com/nicksnyder/go-i18n/i18n"
)

var T goi18n.TranslateFunc

func init() {
	T = i18n.Init("actors", i18n.GetResourcesPath())
}

Add newline at end of some random file


package utils

func Base62(n uint) string {
	b62 := ""
	if n == 0 {
		return "0"
	}
	for n != 0 {
		r := n % 62
		n = n / 62
		b62 = string("0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[r]) + b62
	}
	return b62
}

package utils

const digits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"

func Base62(n uint) string {
	b62 := ""
	if n == 0 {
		return "0"
	}
	for n != 0 {
		r := n % 62
		n = n / 62
		b62 = string(digits[r]) + b62
	}
	return b62
}

Use a const for base 62 digits.


package uuid_test

import (
	"fmt"

	"github.com/northbright/uuid"
)

func ExampleNew() {
	for i := 0; i < 5; i++ {
		uuid, _ := uuid.New()
		fmt.Printf("%v\n", uuid)
	}
	// Output
}

package uuid_test

import (
	"fmt"

	"github.com/northbright/uuid"
)

func ExampleNew() {
	for i := 0; i < 5; i++ {
		uuid, _ := uuid.New()
		fmt.Printf("%v\n", uuid)
	}
	// Output:
}

Fix no test case issue


package web

import (
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/deferpanic/deferclient/deferstats"
)

var (
	dfs *deferstats.Client
)

// NewLogger configures defer panic error and starts capturing stats.
// It looks for DEFERPANIC_KEY,
// DEVERPANIC_ENVIRONMENT and DEFERPANIC_APPGROUP environment vars
func NewLogger() {
	dfs := deferstats.NewClient(os.Getenv("DEFERPANIC_KEY"))
	dfs.Setenvironment(os.Getenv("DEFERPANIC_ENVIRONMENT"))
	dfs.SetappGroup(os.Getenv("DEFERPANIC_APPGROUP"))
	go dfs.CaptureStats()
}

func logError(msg string) {
	err := errors.New(msg)
	if err != nil {
		dfs.Wrap(err)
		log.Println(err)
	}
}

// LogError passes the error to deferpanic
// and prints the error message to stdout
func LogError(e error) {
	logError(e.Error())
}

// LogErrorf accepts a format string and arguments
// It creates a new error, logs with deferpanic and
// prints the error to stdout
func LogErrorf(format string, a ...interface{}) {
	LogError(fmt.Errorf(format, a...))
}

package web

import (
	"errors"
	"fmt"
	"log"
	"os"

	"github.com/deferpanic/deferclient/deferstats"
)

var (
	dfs *deferstats.Client
)

// NewLogger configures defer panic error and starts capturing stats.
// It looks for DEFERPANIC_KEY,
// DEVERPANIC_ENVIRONMENT and DEFERPANIC_APPGROUP environment vars
func NewLogger() {
	dfs = deferstats.NewClient(os.Getenv("DEFERPANIC_API_KEY"))
	dfs.Setenvironment(os.Getenv("DEFERPANIC_ENVIRONMENT"))
	dfs.SetappGroup(os.Getenv("DEFERPANIC_APPGROUP"))
	go dfs.CaptureStats()
}

func logError(msg string) {
	err := errors.New(msg)
	if err != nil {
		dfs.Wrap(err)
		log.Println(err)
	}
}

// LogError passes the error to deferpanic
// and prints the error message to stdout
func LogError(e error) {
	logError(e.Error())
}

// LogErrorf accepts a format string and arguments
// It creates a new error, logs with deferpanic and
// prints the error to stdout
func LogErrorf(format string, a ...interface{}) {
	LogError(fmt.Errorf(format, a...))
}

Fix bug where global defer stats object was being overwritten


package stacktrace

import "testing"

func captureFunc() Stacktrace {
	return Capture(0)
}

func TestCaptureTestFunc(t *testing.T) {
	stack := captureFunc()

	if len(stack.Frames) == 0 {
		t.Fatal("expected stack frames to be returned")
	}

	// the first frame is the caller
	frame := stack.Frames[0]
	if expected := "captureFunc"; frame.Function != expected {
		t.Fatalf("expteced function %q but recevied %q", expected, frame.Function)
	}
	if expected := "github.com/opencontainers/runc/libcontainer/stacktrace"; frame.Package != expected {
		t.Fatalf("expected package %q but received %q", expected, frame.Package)
	}
	if expected := "capture_test.go"; frame.File != expected {
		t.Fatalf("expected file %q but received %q", expected, frame.File)
	}
}

package stacktrace

import (
	"strings"
	"testing"
)

func captureFunc() Stacktrace {
	return Capture(0)
}

func TestCaptureTestFunc(t *testing.T) {
	stack := captureFunc()

	if len(stack.Frames) == 0 {
		t.Fatal("expected stack frames to be returned")
	}

	// the first frame is the caller
	frame := stack.Frames[0]
	if expected := "captureFunc"; frame.Function != expected {
		t.Fatalf("expteced function %q but recevied %q", expected, frame.Function)
	}
	expected := "github.com/opencontainers/runc/libcontainer/stacktrace"
	if !strings.HasSuffix(frame.Package, expected) {
		t.Fatalf("expected package %q but received %q", expected, frame.Package)
	}
	if expected := "capture_test.go"; frame.File != expected {
		t.Fatalf("expected file %q but received %q", expected, frame.File)
	}
}

Fix to allow for build in different path


package jsonlog

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"time"
)

type JSONLog struct {
	Log     string    `json:"log,omitempty"`
	Stream  string    `json:"stream,omitempty"`
	Created time.Time `json:"time"`
}

func (jl *JSONLog) Format(format string) (string, error) {
	if format == "" {
		return jl.Log, nil
	}
	if format == "json" {
		m, err := json.Marshal(jl)
		return string(m), err
	}
	return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil
}

func WriteLog(src io.Reader, dst io.WriteCloser, format string) error {
	dec := json.NewDecoder(src)
	for {
		l := &JSONLog{}

		if err := dec.Decode(l); err == io.EOF {
			return nil
		} else if err != nil {
			log.Printf("Error streaming logs: %s", err)
			return err
		}
		line, err := l.Format(format)
		if err != nil {
			return err
		}
		fmt.Fprintf(dst, "%s", line)
	}
}

package jsonlog

import (
	"encoding/json"
	"fmt"
	"io"
	"log"
	"time"
)

type JSONLog struct {
	Log     string    `json:"log,omitempty"`
	Stream  string    `json:"stream,omitempty"`
	Created time.Time `json:"time"`
}

func (jl *JSONLog) Format(format string) (string, error) {
	if format == "" {
		return jl.Log, nil
	}
	if format == "json" {
		m, err := json.Marshal(jl)
		return string(m), err
	}
	return fmt.Sprintf("[%s] %s", jl.Created.Format(format), jl.Log), nil
}

func WriteLog(src io.Reader, dst io.Writer, format string) error {
	dec := json.NewDecoder(src)
	for {
		l := &JSONLog{}

		if err := dec.Decode(l); err == io.EOF {
			return nil
		} else if err != nil {
			log.Printf("Error streaming logs: %s", err)
			return err
		}
		line, err := l.Format(format)
		if err != nil {
			return err
		}
		fmt.Fprintf(dst, "%s", line)
	}
}

Change unused WriteCloser to Writer


package svn

import (
	"encoding/xml"

	"github.com/pkg/errors"
)

type Log struct {
	XMLName xml.Name   `xml:"log"`
	Entries []LogEntry `xml:"logentry"`
}

type LogEntry struct {
	*Commit
	XMLName xml.Name `xml:"logentry"`
	Paths   []Path   `xml:"paths>path"`
	Message string   `xml:"msg"`
}

type Path struct {
	XMLName               xml.Name `xml:"path"`
	TextModifications     bool     `xml:"text-mods,attr"`
	Kind                  string   `xml:"kind,attr"`
	CopyFromPath          *string  `xml:"copyfrom-path,attr,omitempty"`
	CopyFromRevision      *int     `xml:"copyfrom-rev,attr,omitempty"`
	Action                string   `xml:"action,attr"`
	PropertyModifications bool     `xml:"prop-mods,attr"`
}

func GetLog(address string) (*Log, error) {
	log := Log{}

	if err := Execute(&log, "log", "--xml", "--verbose", address); err != nil {
		return nil, errors.Wrapf(err, "failed to get log for %s", address)
	}

	return &log, nil
}

package svn

import (
	"encoding/xml"

	"github.com/pkg/errors"
)

type Log struct {
	XMLName xml.Name   `xml:"log"`
	Entries []LogEntry `xml:"logentry"`
}

type LogEntry struct {
	*Commit
	XMLName xml.Name `xml:"logentry"`
	Paths   []Path   `xml:"paths>path"`
	Message string   `xml:"msg"`
}

type Path struct {
	XMLName               xml.Name `xml:"path"`
	TextModifications     bool     `xml:"text-mods,attr"`
	Kind                  string   `xml:"kind,attr"`
	CopyFromPath          *string  `xml:"copyfrom-path,attr,omitempty"`
	CopyFromRevision      *int     `xml:"copyfrom-rev,attr,omitempty"`
	Action                string   `xml:"action,attr"`
	PropertyModifications bool     `xml:"prop-mods,attr"`
	Name                  string   `xml:",chardata"`
}

func GetLog(address string) (*Log, error) {
	log := Log{}

	if err := Execute(&log, "log", "--xml", "--verbose", address); err != nil {
		return nil, errors.Wrapf(err, "failed to get log for %s", address)
	}

	return &log, nil
}

Add missing path name attribute


package main

import (
	"flag"

	"github.com/resumic/schema/cmd/resumic/validate"
)

func main() {
	var doc string
	flag.StringVar(&doc, "doc", "../../examples/invalid/invalid_email.json", "Example file")
	flag.Parse()
	validate.ValidateJSON(doc)
}

package main

import (
	"encoding/json"
	"flag"
	"fmt"
	"log"
	"os"

	"github.com/erbesharat/schema/schema"
	"github.com/resumic/schema/cmd/resumic/validate"
)

func main() {
	var doc string
	var schemaFile string
	flag.StringVar(&doc, "doc", "../../examples/invalid/invalid_email.json", "Example file")
	flag.StringVar(&schemaFile, "schema", "./schema.json", "Generate JSON Schema")
	flag.Parse()

	// Verify that a subcommand has been provided
	if len(flag.Args()) < 1 {
		fmt.Println("subcommand is required")
		os.Exit(1)
	}
	switch flag.Args()[0] {
	case "validate":
		validate.ValidateJSON(doc)
	case "schema":
		schema, err := schema.GetSchema()
		if err != nil {
			log.Fatalf("Couldn't get the schema struct: %s", err)
		}
		json, err := json.Marshal(schema)
		if err != nil {
			log.Fatal("couldn't parse the schema")
		}
		file, err := os.Create(schemaFile)
		defer file.Close()
		if err != nil {
			log.Fatal("couldn't create the schema file")
		}
		_, err = file.Write(json)
		if err != nil {
			log.Fatal("couldn't write the schema content to given the schema file")
		}
		log.Printf("Schema file created successfully: %s", file.Name())
	default:
		log.Fatalf("Unsupported subcommands. Please check --help for commands list")
	}
}

Add subcommand for generating schema.json file


// Copyright 2015 Mathieu MAST. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package container

import (
	"reflect"
)

type Container interface {
	Add(interface{}) error
	GetSize() int
	Search(interface{}) (interface{}, error)
	Remove(interface{}) error
	ToArray() []interface{}
	ToArrayOfType(elementType reflect.Type) interface{}
}

// Copyright 2015 Mathieu MAST. All rights reserved.
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package container

import (
	"reflect"
)

type Container interface {
	Add(interface{}) error
	GetSize() int
	Search(interface{}) (interface{}, error)
	Remove(interface{}) error
	ToArray() []interface{}
	ToArrayOfType(reflect.Type) interface{}
	Visit(func(interface{}, int))
}

Add ToArrayOfType & Visit methods


package main

import (
	"github.com/codegangsta/cli"
	"os"
	"path"
)

type File struct {
	ImdbID   string
	Format   string
	FileName string
	FullPath string
}

func (f *File) IsValid() bool {
	return f.ImdbID != "" && f.Present()
}

// Is the file is present on disk
func (f *File) Present() bool {
	return fileExists(f.FullPath)
}

func NewFile(c *cli.Context) File {
	var fileName, format, id, fullPath string

	if len(c.Args()) == 1 {
		fullPath = c.Args()[0]
		base := path.Base(fullPath)
		format = path.Ext(fullPath)

		fileName = base[:len(base)-len(format)]
		id = c.String("id")
	}
	return File{ImdbID: id, FileName: fileName, Format: format, FullPath: fullPath}
}

func fileExists(path string) bool {
	exists := false
	if _, err := os.Stat(path); err == nil {
		exists = true
	}
	return exists
}

package main

import (
	"github.com/codegangsta/cli"
	"os"
	"path"
)

type File struct {
	ImdbID   string
	Format   string
	FileName string
	FullPath string
}

func (f *File) IsValid() bool {
	return f.ImdbID != "" && f.Present()
}

// Present checks to see if the file is present on disk.
func (f *File) Present() bool {
	return fileExists(f.FullPath)
}

func NewFile(c *cli.Context) File {
	var fileName, format, id, fullPath string

	if len(c.Args()) == 1 {
		fullPath = c.Args()[0]
		base := path.Base(fullPath)
		format = path.Ext(fullPath)

		fileName = base[:len(base)-len(format)]
		id = c.String("id")
	}
	return File{ImdbID: id, FileName: fileName, Format: format, FullPath: fullPath}
}

func fileExists(path string) bool {
	exists := false
	if _, err := os.Stat(path); err == nil {
		exists = true
	}
	return exists
}

Add go doc style comment


package shell

import (
	"bytes"
	"fmt"
	"os"
	"testing"
)

func TestCat(t *testing.T) {
	myShell, err := NewShell()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}

	reader, err := myShell.Cat("QmQLBvJ3ur7U7mzbYDLid7WkaciY84SLpPYpGPHhDNps2Y")
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}

	buf := new(bytes.Buffer)
	buf.ReadFrom(reader)
	output := buf.String()

	expected := "\"The man who makes no mistakes does not make anything.\" - Edward John Phelps\n"

	if output != expected {
		t.FailNow()
	}
}

package shell

import (
	"bytes"
	"fmt"
	"os"
	"testing"
)

func TestCat(t *testing.T) {
	myShell, err := NewShell()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}

	reader, err := myShell.Cat("QmYCvbfNbCwFR45HiNP45rwJgvatpiW38D961L5qAhUM5Y")
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}

	buf := new(bytes.Buffer)
	buf.ReadFrom(reader)
	output := buf.String()

	expected := `Come hang out in our IRC chat room if you have any questions.

Contact the ipfs dev team:
- Bugs: https://github.com/ipfs/go-ipfs/issues
- Help: irc.freenode.org/#ipfs
- Email: dev@ipfs.io
`

	if output != expected {
		t.FailNow()
	}
}

Make getshell test more reliable.


package ec2

import (
	"errors"

	goaws "github.com/aws/aws-sdk-go/aws"
	awsec2 "github.com/aws/aws-sdk-go/service/ec2"
)

type AvailabilityZoneRetriever struct {
	ec2ClientProvider ec2ClientProvider
}

func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever {
	return AvailabilityZoneRetriever{
		ec2ClientProvider: ec2ClientProvider,
	}
}

func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) {
	output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{
		Filters: []*awsec2.Filter{{
			Name:   goaws.String("region-name"),
			Values: []*string{goaws.String(region)},
		}},
	})
	if err != nil {
		return []string{}, err
	}

	azList := []string{}
	for _, az := range output.AvailabilityZones {
		if az == nil {
			return []string{}, errors.New("aws returned nil availability zone")
		}
		if az.ZoneName == nil {
			return []string{}, errors.New("aws returned availability zone with nil zone name")
		}

		if *az.ZoneName != "us-east-1d" {
			azList = append(azList, *az.ZoneName)
		}
	}

	return azList, nil
}

package ec2

import (
	"errors"

	goaws "github.com/aws/aws-sdk-go/aws"
	awsec2 "github.com/aws/aws-sdk-go/service/ec2"
)

type AvailabilityZoneRetriever struct {
	ec2ClientProvider ec2ClientProvider
}

func NewAvailabilityZoneRetriever(ec2ClientProvider ec2ClientProvider) AvailabilityZoneRetriever {
	return AvailabilityZoneRetriever{
		ec2ClientProvider: ec2ClientProvider,
	}
}

func (r AvailabilityZoneRetriever) Retrieve(region string) ([]string, error) {
	output, err := r.ec2ClientProvider.GetEC2Client().DescribeAvailabilityZones(&awsec2.DescribeAvailabilityZonesInput{
		Filters: []*awsec2.Filter{{
			Name:   goaws.String("region-name"),
			Values: []*string{goaws.String(region)},
		}},
	})
	if err != nil {
		return []string{}, err
	}

	azList := []string{}
	for _, az := range output.AvailabilityZones {
		if az == nil {
			return []string{}, errors.New("aws returned nil availability zone")
		}
		if az.ZoneName == nil {
			return []string{}, errors.New("aws returned availability zone with nil zone name")
		}

		azList = append(azList, *az.ZoneName)
	}

	return azList, nil
}

Revert "Fix bbl up for AWS"


package ssh

import (
	"testing"
)

func TestAddPrompterVariablesNoPrompter(t *testing.T) {
	if e, err := addPrompterVariables([]string{"SSH_ASKPASS=someprogram"}, ""); err != nil {
		t.Fatal("failed to set prompter environment variables:", err)
	} else if len(e) != 0 {
		t.Error("SSH_ASKPASS environment variable not removed in absence of prompter")
	}
}

func TestAddPrompterVariables(t *testing.T) {
	if e, err := addPrompterVariables(nil, "prompter-id"); err != nil {
		t.Fatal("failed to set prompter environment variables:", err)
	} else if len(e) != 3 {
		t.Error("unexpected number of environment variables after adding prompter values")
	}
}

package ssh

import (
	"testing"
)

func TestAddPrompterVariablesNoPrompter(t *testing.T) {
	if e, err := setPrompterVariables([]string{"SSH_ASKPASS=someprogram"}, ""); err != nil {
		t.Fatal("failed to set prompter environment variables:", err)
	} else if len(e) != 0 {
		t.Error("SSH_ASKPASS environment variable not removed in absence of prompter")
	}
}

func TestAddPrompterVariables(t *testing.T) {
	if e, err := setPrompterVariables(nil, "prompter-id"); err != nil {
		t.Fatal("failed to set prompter environment variables:", err)
	} else if len(e) != 3 {
		t.Error("unexpected number of environment variables after adding prompter values")
	}
}

Fix rename issue with SSH tests.


package exc

import (
	"testing"

	"github.com/elves/elvish/pkg/eval"
)

var That = eval.That

func TestExc(t *testing.T) {
	setup := func(ev *eval.Evaler) { ev.Global.AddNs("exc", Ns) }
	eval.TestWithSetup(t, setup,
		// Have a simple sanity test that exc:show writes something.
		That(`exc:show ?(fail foo) | > (count (slurp)) 0`).Puts(true),

		That("exc:is-external-cmd-exc ?("+failingExternalCmd+")").Puts(true),
		That("exc:is-external-cmd-exc ?(fail bad)").Puts(false),

		That("exc:is-nonzero-exit ?("+failingExternalCmd+")").Puts(true),
		That("exc:is-nonzero-exit ?(fail bad)").Puts(false),

		// TODO: Test positive case of exc:is-killed
		That("exc:is-killed ?(fail bad)").Puts(false),

		That("exc:is-fail-exc ?(fail bad)").Puts(true),
		That("exc:is-fail-exc ?("+failingExternalCmd+")").Puts(false),
	)
}

package exc

import (
	"testing"

	"github.com/elves/elvish/pkg/eval"
)

var That = eval.That

func TestExc(t *testing.T) {
	setup := func(ev *eval.Evaler) { ev.Global.AddNs("exc", Ns) }
	eval.TestWithSetup(t, setup,
		// Have a simple sanity test that exc:show writes something.
		That(`exc:show ?(fail foo) | > (count (slurp)) 0`).Puts(true),

		That("exc:is-external-cmd-exc ?("+failingExternalCmd+")").Puts(true),
		That("exc:is-external-cmd-exc ?(fail bad)").Puts(false),

		That("exc:is-nonzero-exit ?("+failingExternalCmd+")").Puts(true),
		That("exc:is-nonzero-exit ?(fail bad)").Puts(false),

		// TODO: Test positive case of exc:is-killed
		That("exc:is-killed ?(fail bad)").Puts(false),

		That("exc:is-fail-exc ?(fail bad)").Puts(true),
		That("exc:is-fail-exc ?("+failingExternalCmd+")").Puts(false),

		That("exc:is-pipeline-exc ?(fail bad)").Puts(false),
		That("exc:is-pipeline-exc ?(fail 1 | fail 2)").Puts(true),
	)
}

Add missing unit tests for exc:is-pipeline-exc.