<commit_before>package readline

import (
	"bytes"
	"fmt"
	"strings"
	"unicode"

	"github.com/zetamatta/go-getch"
)

func KeyFuncIncSearch(this *Buffer) Result {
	var searchBuf bytes.Buffer
	foundStr := ""
	searchStr := ""
	lastDrawWidth := 0
	lastFoundPos := this.History.Len() - 1
	Backspace(this.Cursor - this.ViewStart)

	update := func() {
		for i := this.History.Len() - 1; ; i-- {
			if i < 0 {
				foundStr = ""
				break
			}
			line := this.History.At(i)
			if strings.Contains(line, searchStr) {
				foundStr = line
				lastFoundPos = i
				break
			}
		}
	}
	for {
		drawStr := fmt.Sprintf("(i-search)[%s]:%s", searchStr, foundStr)
		drawWidth := 0
		for _, ch := range drawStr {
			w1 := GetCharWidth(ch)
			if drawWidth+w1 >= this.ViewWidth() {
				break
			}
			PutRune(ch)
			drawWidth += w1
		}
		if lastDrawWidth > drawWidth {
			n := lastDrawWidth - drawWidth
			PutRunes(' ', n)
			Backspace(n)
		}
		lastDrawWidth = drawWidth
		fmt.Fprint(Console, CURSOR_ON)
		charcode := getch.Rune()
		fmt.Fprint(Console, CURSOR_OFF)
		Backspace(drawWidth)
		switch charcode {
		case '\b':
			searchBuf.Reset()
			// chop last char
			var lastchar rune
			for i, c := range searchStr {
				if i > 0 {
					searchBuf.WriteRune(lastchar)
				}
				lastchar = c
			}
			searchStr = searchBuf.String()
			update()
		case '\r': // ENTER
			this.ViewStart = 0
			this.Length = 0
			this.Cursor = 0
			this.ReplaceAndRepaint(0, foundStr)
			return CONTINUE
		case rune('c' & 0x1F), rune('g' & 0x1F), rune(0x1B):
			w := 0
			var i int
			for i = this.ViewStart; i < this.Cursor; i++ {
				w += GetCharWidth(this.Buffer[i])
				PutRune(this.Buffer[i])
			}
			bs := 0
			for {
				if i >= this.Length {
					if drawWidth > w {
						PutRunes(' ', drawWidth-w)
						bs += (drawWidth - w)
					}
					break
				}
				w1 := GetCharWidth(this.Buffer[i])
				if w+w1 >= this.ViewWidth() {
					break
				}
				PutRune(this.Buffer[i])
				w += w1
				bs += w1
				i++
			}
			Backspace(bs)
			return CONTINUE
		case rune('r' & 0x1F):
			for i := lastFoundPos - 1; ; i-- {
				if i < 0 {
					i = this.History.Len() - 1
				}
				if i == lastFoundPos {
					break
				}
				line := this.History.At(i)
				if strings.Contains(line, searchStr) && foundStr != line {
					foundStr = line
					lastFoundPos = i
					break
				}
			}
		default:
			if unicode.IsControl(charcode) {
				break
			}
			searchBuf.WriteRune(charcode)
			searchStr = searchBuf.String()
			update()
		}
	}
}
<commit_msg>On incremental search, support Ctrl-S for backward search.<commit_after>package readline

import (
	"bytes"
	"fmt"
	"strings"
	"unicode"

	"github.com/zetamatta/go-getch"
)

func KeyFuncIncSearch(this *Buffer) Result {
	var searchBuf bytes.Buffer
	foundStr := ""
	searchStr := ""
	lastDrawWidth := 0
	lastFoundPos := this.History.Len() - 1
	Backspace(this.Cursor - this.ViewStart)

	update := func() {
		for i := this.History.Len() - 1; ; i-- {
			if i < 0 {
				foundStr = ""
				break
			}
			line := this.History.At(i)
			if strings.Contains(line, searchStr) {
				foundStr = line
				lastFoundPos = i
				break
			}
		}
	}
	for {
		drawStr := fmt.Sprintf("(i-search)[%s]:%s", searchStr, foundStr)
		drawWidth := 0
		for _, ch := range drawStr {
			w1 := GetCharWidth(ch)
			if drawWidth+w1 >= this.ViewWidth() {
				break
			}
			PutRune(ch)
			drawWidth += w1
		}
		if lastDrawWidth > drawWidth {
			n := lastDrawWidth - drawWidth
			PutRunes(' ', n)
			Backspace(n)
		}
		lastDrawWidth = drawWidth
		fmt.Fprint(Console, CURSOR_ON)
		charcode := getch.Rune()
		fmt.Fprint(Console, CURSOR_OFF)
		Backspace(drawWidth)
		switch charcode {
		case '\b':
			searchBuf.Reset()
			// chop last char
			var lastchar rune
			for i, c := range searchStr {
				if i > 0 {
					searchBuf.WriteRune(lastchar)
				}
				lastchar = c
			}
			searchStr = searchBuf.String()
			update()
		case '\r': // ENTER
			this.ViewStart = 0
			this.Length = 0
			this.Cursor = 0
			this.ReplaceAndRepaint(0, foundStr)
			return CONTINUE
		case rune('c' & 0x1F), rune('g' & 0x1F), rune(0x1B):
			w := 0
			var i int
			for i = this.ViewStart; i < this.Cursor; i++ {
				w += GetCharWidth(this.Buffer[i])
				PutRune(this.Buffer[i])
			}
			bs := 0
			for {
				if i >= this.Length {
					if drawWidth > w {
						PutRunes(' ', drawWidth-w)
						bs += (drawWidth - w)
					}
					break
				}
				w1 := GetCharWidth(this.Buffer[i])
				if w+w1 >= this.ViewWidth() {
					break
				}
				PutRune(this.Buffer[i])
				w += w1
				bs += w1
				i++
			}
			Backspace(bs)
			return CONTINUE
		case rune('r' & 0x1F):
			for i := lastFoundPos - 1; ; i-- {
				if i < 0 {
					i = this.History.Len() - 1
				}
				if i == lastFoundPos {
					break
				}
				line := this.History.At(i)
				if strings.Contains(line, searchStr) && foundStr != line {
					foundStr = line
					lastFoundPos = i
					break
				}
			}
		case rune('s' & 0x1F):
			for i := lastFoundPos + 1; ; i++ {
				if i >= this.History.Len() {
					i = 0
					break
				}
				if i == lastFoundPos {
					break
				}
				line := this.History.At(i)
				if strings.Contains(line, searchStr) && foundStr != line {
					foundStr = line
					lastFoundPos = i
					break
				}
			}
		default:
			if unicode.IsControl(charcode) {
				break
			}
			searchBuf.WriteRune(charcode)
			searchStr = searchBuf.String()
			update()
		}
	}
}
<|endoftext|>


<commit_before>package tests

import "testing"

func TestSinkTS(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTest.go"}, 1}
	td := []*testDataStruct{t1}
	check(td, t)
}

func TestFieldSensitiv(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTestV2.go"}, 0}
	td := []*testDataStruct{t1}
	check(td, t)
}

func TestAssignTSToNewVariable(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTestV4.go"}, 2}
	td := []*testDataStruct{t1}
	check(td, t)
}

func TestPointerAsParameterSignature(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTestV3Ref.go"}, 2}
	t2 := &testDataStruct{[]string{"./exampleCode/structTestV3RefSimple.go"}, 1}
	td := []*testDataStruct{t1, t2}
	check(td, t)
}

func TestPointerAsParameterCall(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTestV3Val.go"}, 1}
	td := []*testDataStruct{t1}
	check(td, t)
}

func TestFunctionAsParameter(t *testing.T) {
	// TODO implement feature such that the tool can handle functions as a parameter tool
	//	t1 := &testDataStruct{[]string{"./exampleCode/pointerToFunc.go"}, 1}
	t1 := &testDataStruct{[]string{"./exampleCode/pointerToFunc.go"}, 0}
	testData := []*testDataStruct{t1}
	check(testData, t)
}

func TestAliasingThroughFields(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/aliasingThroughFields.go"}, 2}
	t2 := &testDataStruct{[]string{"./exampleCode/aliasingThroughFields2.go"}, 2}
	testData := []*testDataStruct{t1, t2}
	check(testData, t)
}
<commit_msg>Correct spelling<commit_after>package tests

import "testing"

func TestSinkTS(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTest.go"}, 1}
	td := []*testDataStruct{t1}
	check(td, t)
}

func TestFieldSensitiv(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTestV2.go"}, 0}
	td := []*testDataStruct{t1}
	check(td, t)
}

func TestAssignTSToNewVariable(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTestV4.go"}, 2}
	td := []*testDataStruct{t1}
	check(td, t)
}

func TestPointerAsParameterSignature(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTestV3Ref.go"}, 2}
	t2 := &testDataStruct{[]string{"./exampleCode/structTestV3RefSimple.go"}, 1}
	td := []*testDataStruct{t1, t2}
	check(td, t)
}

func TestPointerAsParameterCall(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/structTestV3Val.go"}, 1}
	td := []*testDataStruct{t1}
	check(td, t)
}

func TestFunctionAsParameter(t *testing.T) {
	// TODO implement feature such that the tool can handle functions as a parameter too
	//	t1 := &testDataStruct{[]string{"./exampleCode/pointerToFunc.go"}, 1}
	t1 := &testDataStruct{[]string{"./exampleCode/pointerToFunc.go"}, 0}
	testData := []*testDataStruct{t1}
	check(testData, t)
}

func TestAliasingThroughFields(t *testing.T) {
	t1 := &testDataStruct{[]string{"./exampleCode/aliasingThroughFields.go"}, 2}
	t2 := &testDataStruct{[]string{"./exampleCode/aliasingThroughFields2.go"}, 2}
	testData := []*testDataStruct{t1, t2}
	check(testData, t)
}
<|endoftext|>


<commit_before>package chat

// Map keeps all sessions and actions
type Map struct {
	Sessions map[string]*Session
	actions  chan func()
}

// NewMap creates new map of sessions and start processing actions on them
func NewMap() *Map {
	m := &Map{
		Sessions: make(map[string]*Session),
		actions:  make(chan func()),
	}

	go func() {
		for action := range m.actions {
			action()
		}
	}()

	return m
}

// Set assigns session to the sessions map
func (m *Map) Set(id string, session *Session) {
	m.actions <- func() {
		m.Sessions[id] = session
	}
}

// Get gets session from the sessions map
func (m *Map) Get(id string) (session *Session) {
	wait := make(chan bool)
	m.actions <- func() {
		session = m.Sessions[id]
		wait <- true
	}
	<-wait
	return
}

// GetReadyIdsByRegion gets sessions that are ready for chat in given region
func (m *Map) GetReadyIdsByRegion(region string) (sessions map[string]bool) {
	sessions = make(map[string]bool)

	wait := make(chan bool)
	m.actions <- func() {
		for key := range m.Sessions {
			session := m.Sessions[key]
			if session.Region == region && session.IsReady {
				sessions[session.ID] = true
			}
		}
		wait <- true
	}
	<-wait
	return
}

// GetReadyIds gets sessions that are ready to chat
func (m *Map) GetReadyIds() (sessions map[string]bool) {
	sessions = make(map[string]bool)

	wait := make(chan bool)
	m.actions <- func() {
		for key := range m.Sessions {
			session := m.Sessions[key]
			if session.IsReady {
				sessions[session.ID] = true
			}
		}
		wait <- true
	}
	<-wait
	return
}

// GetNumberOfReadyAndChatting gets number of sessions ready and already chatting
func (m *Map) GetNumberOfReadyAndChatting() (ready int, chatting int) {
	wait := make(chan bool)

	m.actions <- func() {
		for key := range m.Sessions {
			session := m.Sessions[key]
			if session.IsReady {
				ready++
			}
			if session.Room != nil {
				chatting++
			}
		}
		wait <- true
	}

	<-wait
	return
}

// Close closes defined session
func (m *Map) Close(id string) {
	m.actions <- func() {
		delete(m.Sessions, id)
	}
}

// Action sends action to be perform on the sessions
func (m *Map) Action(fn func()) {
	wait := make(chan bool)
	m.actions <- func() {
		fn()
		wait <- true
	}
	<-wait
}
<commit_msg>Map small refactor<commit_after>package chat

// Map keeps all sessions and actions
type Map struct {
	Sessions map[string]*Session
	actions  chan func()
}

// NewMap creates new map of sessions and start processing actions on them
func NewMap() *Map {
	m := &Map{
		Sessions: make(map[string]*Session),
		actions:  make(chan func()),
	}

	go func() {
		for action := range m.actions {
			action()
		}
	}()

	return m
}

// Set assigns session to the sessions map
func (m *Map) Set(id string, session *Session) {
	m.Action(func() {
		m.Sessions[id] = session
	})
}

// Get gets session from the sessions map
func (m *Map) Get(id string) (session *Session) {
	m.Action(func() {
		session = m.Sessions[id]
	})
	return
}

// GetReadyIdsByRegion gets sessions that are ready for chat in given region
func (m *Map) GetReadyIdsByRegion(region string) (sessions map[string]bool) {
	sessions = make(map[string]bool)

	m.Action(func() {
		for key := range m.Sessions {
			session := m.Sessions[key]
			if session.Region == region && session.IsReady {
				sessions[session.ID] = true
			}
		}
	})
	return
}

// GetReadyIds gets sessions that are ready to chat
func (m *Map) GetReadyIds() (sessions map[string]bool) {
	sessions = make(map[string]bool)

	m.Action(func() {
		for key := range m.Sessions {
			session := m.Sessions[key]
			if session.IsReady {
				sessions[session.ID] = true
			}
		}
	})
	return
}

// GetNumberOfReadyAndChatting gets number of sessions ready and already chatting
func (m *Map) GetNumberOfReadyAndChatting() (ready int, chatting int) {
	m.Action(func() {
		for key := range m.Sessions {
			session := m.Sessions[key]
			if session.IsReady {
				ready++
			}
			if session.Room != nil {
				chatting++
			}
		}
	})

	return
}

// Close closes defined session
func (m *Map) Close(id string) {
	m.Action(func() {
		delete(m.Sessions, id)
	})
}

// Action sends action to be perform on the sessions
func (m *Map) Action(fn func()) {
	wait := make(chan bool)
	m.actions <- func() {
		fn()
		wait <- true
	}
	<-wait
}
<|endoftext|>


<commit_before>package checksum

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

const fileChunk = 8192 //8K

func createHash(method crypto.Hash) (hash.Hash, error) {
	var h hash.Hash

	switch method {
	case crypto.MD5:
		h = md5.New()
	case crypto.SHA1:
		h = sha1.New()
	case crypto.SHA224:
		h = sha256.New224()
	case crypto.SHA256:
		h = sha256.New()
	case crypto.SHA384:
		h = sha512.New384()
	case crypto.SHA512:
		h = sha512.New()
	default:
		return h, errors.New("Unsupported hashing method")
	}
	return h, nil
}

//returns a hash for the given string
func String(s string, method crypto.Hash) (string, error) {
	h, err := createHash(method)
	if err != nil {
		return "", err
	}

	io.WriteString(h, s)

	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

//File returns a hash for the given file
func File(path string, method crypto.Hash) (string, error) {
	file, err := os.Open(path)

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

	defer file.Close()

	stat, _ := file.Stat()
	size := stat.Size()
	chunks := uint64(math.Ceil(float64(size) / float64(fileChunk)))

	h, err := createHash(method)
	if err != nil {
		return "", err
	}

	for i := uint64(0); i < chunks; i++ {
		csize := int(math.Min(fileChunk, float64(size-int64(i*fileChunk))))
		buf := make([]byte, csize)

		file.Read(buf)
		io.WriteString(h, string(buf))
	}

	return fmt.Sprintf("%x", h.Sum(nil)), nil
}
<commit_msg>added Bytes function to create checksum of byte array<commit_after>package checksum

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

const fileChunk = 8192 //8K

func createHash(method crypto.Hash) (hash.Hash, error) {
	var h hash.Hash

	switch method {
	case crypto.MD5:
		h = md5.New()
	case crypto.SHA1:
		h = sha1.New()
	case crypto.SHA224:
		h = sha256.New224()
	case crypto.SHA256:
		h = sha256.New()
	case crypto.SHA384:
		h = sha512.New384()
	case crypto.SHA512:
		h = sha512.New()
	default:
		return h, errors.New("Unsupported hashing method")
	}
	return h, nil
}

//String returns a hash for the given string
func String(s string, method crypto.Hash) (string, error) {
	h, err := createHash(method)
	if err != nil {
		return "", err
	}

	io.WriteString(h, s)

	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

//Bytes return a hash for the given bytes
func Bytes(b []byte, method crypto.Hash) (string, error) {
	h, err := createHash(method)
	if err != nil {
		return "", err
	}
	io.WriteString(h, string(b))
	return fmt.Sprintf("%x", h.Sum(nil)), nil
}

//File returns a hash for the given file
func File(path string, method crypto.Hash) (string, error) {
	file, err := os.Open(path)

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

	defer file.Close()

	stat, _ := file.Stat()
	size := stat.Size()
	chunks := uint64(math.Ceil(float64(size) / float64(fileChunk)))

	h, err := createHash(method)
	if err != nil {
		return "", err
	}

	for i := uint64(0); i < chunks; i++ {
		csize := int(math.Min(fileChunk, float64(size-int64(i*fileChunk))))
		buf := make([]byte, csize)

		file.Read(buf)
		io.WriteString(h, string(buf))
	}

	return fmt.Sprintf("%x", h.Sum(nil)), nil
}
<|endoftext|>


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

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"

	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/ThomasRooney/gexpect"
	taas "github.com/coreos/rkt/Godeps/_workspace/src/github.com/endocode/test-aci-auth-server/lib"
	"github.com/coreos/rkt/rkt/config"
)

func TestAuthSanity(t *testing.T) {
	skipDestructive(t)
	removeDataDir(t)
	server := runServer(t, taas.None)
	defer server.Close()
	successfulRunRkt(t, server.URL, "none1")
}

const (
	authSuccessfulDownload = "BANG!"
	authFailedDownload = "error downloading ACI: bad HTTP status code: 401"
)

type genericAuthTest struct {
	name          string
	useServerConf bool
	confDir       string
	line          string
}

func TestAuthBasic(t *testing.T) {
	tests := []genericAuthTest{
		{"basic-no-config", false, "", authFailedDownload},
		{"basic-custom-config", true, config.DefaultCustomPath, authSuccessfulDownload},
		{"basic-vendor-config", true, config.DefaultVendorPath, authSuccessfulDownload},
	}
	testAuthGeneric(t, taas.Basic, tests)
}

func TestAuthOauth(t *testing.T) {
	tests := []genericAuthTest{
		{"oauth-no-config", false, "", authFailedDownload},
		{"oauth-custom-config", true, config.DefaultCustomPath, authSuccessfulDownload},
		{"oauth-vendor-config", true, config.DefaultVendorPath, authSuccessfulDownload},
	}
	testAuthGeneric(t, taas.Oauth, tests)
}

func testAuthGeneric(t *testing.T, auth taas.Type, tests []genericAuthTest) {
	skipDestructive(t)
	removeDataDir(t)
	defer removeAllConfig(t)
	server := runServer(t, auth)
	defer server.Close()
	for _, tt := range tests {
		removeAllConfig(t)
		if tt.useServerConf {
			writeConfig(t, tt.confDir, "test.json", server.Conf)
		}
		expectedRunRkt(t, server.URL, tt.name, tt.line)
	}
}

func TestAuthOverride(t *testing.T) {
	skipDestructive(t)
	removeDataDir(t)
	defer removeAllConfig(t)
	server := runServer(t, taas.Oauth)
	defer server.Close()
	tests := []struct {
		vendorConfig         string
		customConfig         string
		name                 string
		resultBeforeOverride string
		resultAfterOverride  string
	}{
		{server.Conf, getInvalidOAuthConfig(server.Conf), "oauth-vvic", authSuccessfulDownload, authFailedDownload},
		{getInvalidOAuthConfig(server.Conf), server.Conf, "oauth-ivvc", authFailedDownload, authSuccessfulDownload},
	}
	for _, tt := range tests {
		removeAllConfig(t)
		writeVendorConfig(t, "test.json", tt.vendorConfig)
		expectedRunRkt(t, server.URL, tt.name+"-1", tt.resultBeforeOverride)
		writeCustomConfig(t, "test.json", tt.customConfig)
		expectedRunRkt(t, server.URL, tt.name+"-2", tt.resultAfterOverride)
	}
}

func TestAuthIgnore(t *testing.T) {
	skipDestructive(t)
	removeDataDir(t)
	defer removeAllConfig(t)
	server := runServer(t, taas.Oauth)
	defer server.Close()
	testAuthIgnoreBogusFiles(t, server)
	testAuthIgnoreSubdirectories(t, server)
}

func testAuthIgnoreBogusFiles(t *testing.T, server *taas.Server) {
	removeAllConfig(t)
	writeVendorConfig(t, "README", "This is vendor config")
	writeCustomConfig(t, "README", "This is custom config")
	writeVendorConfig(t, "test.notjson", server.Conf)
	writeCustomConfig(t, "test.notjson", server.Conf)
	failedRunRkt(t, server.URL, "oauth-bogus-files")
}

func testAuthIgnoreSubdirectories(t *testing.T, server *taas.Server) {
	removeAllConfig(t)
	customSubdir := filepath.Join(config.DefaultCustomPath, "subdir")
	vendorSubdir := filepath.Join(config.DefaultVendorPath, "subdir")
	writeConfig(t, customSubdir, "test.json", server.Conf)
	writeConfig(t, vendorSubdir, "test.json", server.Conf)
	failedRunRkt(t, server.URL, "oauth-subdirectories")
}

func runServer(t *testing.T, auth taas.Type) *taas.Server {
	goTool := getAbs(t, "go")
	acTool := getAbs(t, "../bin/actool")
	server, err := taas.NewServerWithPaths(auth, 20, acTool, goTool)
	if err != nil {
		t.Fatalf("Could not start server: %v", err)
	}
	go serverHandler(t, server)
	return server
}

func getAbs(t *testing.T, tool string) string {
	baseTool := filepath.Base(tool)
	pathTool, err := exec.LookPath(tool)
	if err != nil {
		t.Fatalf("Could not find %s, required to run server: %v", baseTool, err)
	}
	absTool, err := filepath.Abs(pathTool)
	if err != nil {
		t.Fatalf("Could not get absolute path of %s, required to run server: %v", baseTool, err)
	}
	return absTool
}

func serverHandler(t *testing.T, server *taas.Server) {
	for {
		select {
		case _, ok := <-server.Stop:
			if ok {
				t.Log("Closing server")
				server.Close()
			}
			return
		case msg, ok := <-server.Msg:
			if ok {
				t.Logf("server: %v", msg)
			}
		}
	}
}

func successfulRunRkt(t *testing.T, host, dir string) {
	expectedRunRkt(t, host, dir, authSuccessfulDownload)
}

func failedRunRkt(t *testing.T, host, dir string) {
	expectedRunRkt(t, host, dir, authFailedDownload)
}

func expectedRunRkt(t *testing.T, host, dir, line string) {
	child := runRkt(t, host, dir)
	defer child.Wait()
	if err := child.Expect(line); err != nil {
		t.Fatalf("Didn't receive expected output %q", line)
	}
}

// TODO (krnowak): Use --dir option when we also add
// --vendor-config-dir and --custom-config-dir options. Then we can
// remove destructive tests checks.
func runRkt(t *testing.T, host, dir string) *gexpect.ExpectSubprocess {
	cmd := fmt.Sprintf(`../bin/rkt --debug --insecure-skip-verify run %s/%s/prog.aci`, host, dir)
	t.Logf("Running rkt: %s", cmd)
	child, err := gexpect.Spawn(cmd)
	if err != nil {
		t.Fatalf("Failed to run rkt: %v", err)
	}
	return child
}

func removeAllConfig(t *testing.T) {
	dirs := []string{
		authDir(config.DefaultCustomPath),
		authDir(config.DefaultVendorPath),
	}
	for _, p := range dirs {
		if err := os.RemoveAll(p); err != nil {
			t.Fatalf("Failed to remove config directory %q: %v", p, err)
		}
		if err := os.MkdirAll(p, 0755); err != nil {
			t.Fatalf("Failed to create config directory %q: %v", p, err)
		}
	}
}

func writeCustomConfig(t *testing.T, filename, contents string) {
	writeConfig(t, config.DefaultCustomPath, filename, contents)
}

func writeVendorConfig(t *testing.T, filename, contents string) {
	writeConfig(t, config.DefaultVendorPath, filename, contents)
}

func writeConfig(t *testing.T, baseDir, filename, contents string) {
	dir := authDir(baseDir)
	if err := os.MkdirAll(dir, 0755); err != nil {
		t.Fatalf("Failed to create config directory %q: %v", dir, err)
	}
	path := filepath.Join(dir, filename)
	os.Remove(path)
	if err := ioutil.WriteFile(path, []byte(contents), 0644); err != nil {
		t.Fatalf("Failed to write file %q: %v", path, err)
	}
}

func authDir(confDir string) string {
	return filepath.Join(confDir, "auth.d")
}

func getInvalidOAuthConfig(conf string) string {
	return strings.Replace(conf, "sometoken", "someobviouslywrongtoken", 1)
}
<commit_msg>functional tests: Simplify running the test server<commit_after>// Copyright 2015 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package main

import (
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"strings"
	"testing"

	"github.com/coreos/rkt/Godeps/_workspace/src/github.com/ThomasRooney/gexpect"
	taas "github.com/coreos/rkt/Godeps/_workspace/src/github.com/endocode/test-aci-auth-server/lib"
	"github.com/coreos/rkt/rkt/config"
)

func TestAuthSanity(t *testing.T) {
	skipDestructive(t)
	removeDataDir(t)
	server := runServer(t, taas.None)
	defer server.Close()
	successfulRunRkt(t, server.URL, "none1")
}

const (
	authSuccessfulDownload = "BANG!"
	authFailedDownload = "error downloading ACI: bad HTTP status code: 401"
)

type genericAuthTest struct {
	name          string
	useServerConf bool
	confDir       string
	line          string
}

func TestAuthBasic(t *testing.T) {
	tests := []genericAuthTest{
		{"basic-no-config", false, "", authFailedDownload},
		{"basic-custom-config", true, config.DefaultCustomPath, authSuccessfulDownload},
		{"basic-vendor-config", true, config.DefaultVendorPath, authSuccessfulDownload},
	}
	testAuthGeneric(t, taas.Basic, tests)
}

func TestAuthOauth(t *testing.T) {
	tests := []genericAuthTest{
		{"oauth-no-config", false, "", authFailedDownload},
		{"oauth-custom-config", true, config.DefaultCustomPath, authSuccessfulDownload},
		{"oauth-vendor-config", true, config.DefaultVendorPath, authSuccessfulDownload},
	}
	testAuthGeneric(t, taas.Oauth, tests)
}

func testAuthGeneric(t *testing.T, auth taas.Type, tests []genericAuthTest) {
	skipDestructive(t)
	removeDataDir(t)
	defer removeAllConfig(t)
	server := runServer(t, auth)
	defer server.Close()
	for _, tt := range tests {
		removeAllConfig(t)
		if tt.useServerConf {
			writeConfig(t, tt.confDir, "test.json", server.Conf)
		}
		expectedRunRkt(t, server.URL, tt.name, tt.line)
	}
}

func TestAuthOverride(t *testing.T) {
	skipDestructive(t)
	removeDataDir(t)
	defer removeAllConfig(t)
	server := runServer(t, taas.Oauth)
	defer server.Close()
	tests := []struct {
		vendorConfig         string
		customConfig         string
		name                 string
		resultBeforeOverride string
		resultAfterOverride  string
	}{
		{server.Conf, getInvalidOAuthConfig(server.Conf), "oauth-vvic", authSuccessfulDownload, authFailedDownload},
		{getInvalidOAuthConfig(server.Conf), server.Conf, "oauth-ivvc", authFailedDownload, authSuccessfulDownload},
	}
	for _, tt := range tests {
		removeAllConfig(t)
		writeVendorConfig(t, "test.json", tt.vendorConfig)
		expectedRunRkt(t, server.URL, tt.name+"-1", tt.resultBeforeOverride)
		writeCustomConfig(t, "test.json", tt.customConfig)
		expectedRunRkt(t, server.URL, tt.name+"-2", tt.resultAfterOverride)
	}
}

func TestAuthIgnore(t *testing.T) {
	skipDestructive(t)
	removeDataDir(t)
	defer removeAllConfig(t)
	server := runServer(t, taas.Oauth)
	defer server.Close()
	testAuthIgnoreBogusFiles(t, server)
	testAuthIgnoreSubdirectories(t, server)
}

func testAuthIgnoreBogusFiles(t *testing.T, server *taas.Server) {
	removeAllConfig(t)
	writeVendorConfig(t, "README", "This is vendor config")
	writeCustomConfig(t, "README", "This is custom config")
	writeVendorConfig(t, "test.notjson", server.Conf)
	writeCustomConfig(t, "test.notjson", server.Conf)
	failedRunRkt(t, server.URL, "oauth-bogus-files")
}

func testAuthIgnoreSubdirectories(t *testing.T, server *taas.Server) {
	removeAllConfig(t)
	customSubdir := filepath.Join(config.DefaultCustomPath, "subdir")
	vendorSubdir := filepath.Join(config.DefaultVendorPath, "subdir")
	writeConfig(t, customSubdir, "test.json", server.Conf)
	writeConfig(t, vendorSubdir, "test.json", server.Conf)
	failedRunRkt(t, server.URL, "oauth-subdirectories")
}

func runServer(t *testing.T, auth taas.Type) *taas.Server {
	server, err := taas.NewServerWithPaths(auth, 20, "../bin/actool", "go")
	if err != nil {
		t.Fatalf("Could not start server: %v", err)
	}
	go serverHandler(t, server)
	return server
}

func serverHandler(t *testing.T, server *taas.Server) {
	for {
		select {
		case _, ok := <-server.Stop:
			if ok {
				t.Log("Closing server")
				server.Close()
			}
			return
		case msg, ok := <-server.Msg:
			if ok {
				t.Logf("server: %v", msg)
			}
		}
	}
}

func successfulRunRkt(t *testing.T, host, dir string) {
	expectedRunRkt(t, host, dir, authSuccessfulDownload)
}

func failedRunRkt(t *testing.T, host, dir string) {
	expectedRunRkt(t, host, dir, authFailedDownload)
}

func expectedRunRkt(t *testing.T, host, dir, line string) {
	child := runRkt(t, host, dir)
	defer child.Wait()
	if err := child.Expect(line); err != nil {
		t.Fatalf("Didn't receive expected output %q", line)
	}
}

// TODO (krnowak): Use --dir option when we also add
// --vendor-config-dir and --custom-config-dir options. Then we can
// remove destructive tests checks.
func runRkt(t *testing.T, host, dir string) *gexpect.ExpectSubprocess {
	cmd := fmt.Sprintf(`../bin/rkt --debug --insecure-skip-verify run %s/%s/prog.aci`, host, dir)
	t.Logf("Running rkt: %s", cmd)
	child, err := gexpect.Spawn(cmd)
	if err != nil {
		t.Fatalf("Failed to run rkt: %v", err)
	}
	return child
}

func removeAllConfig(t *testing.T) {
	dirs := []string{
		authDir(config.DefaultCustomPath),
		authDir(config.DefaultVendorPath),
	}
	for _, p := range dirs {
		if err := os.RemoveAll(p); err != nil {
			t.Fatalf("Failed to remove config directory %q: %v", p, err)
		}
		if err := os.MkdirAll(p, 0755); err != nil {
			t.Fatalf("Failed to create config directory %q: %v", p, err)
		}
	}
}

func writeCustomConfig(t *testing.T, filename, contents string) {
	writeConfig(t, config.DefaultCustomPath, filename, contents)
}

func writeVendorConfig(t *testing.T, filename, contents string) {
	writeConfig(t, config.DefaultVendorPath, filename, contents)
}

func writeConfig(t *testing.T, baseDir, filename, contents string) {
	dir := authDir(baseDir)
	if err := os.MkdirAll(dir, 0755); err != nil {
		t.Fatalf("Failed to create config directory %q: %v", dir, err)
	}
	path := filepath.Join(dir, filename)
	os.Remove(path)
	if err := ioutil.WriteFile(path, []byte(contents), 0644); err != nil {
		t.Fatalf("Failed to write file %q: %v", path, err)
	}
}

func authDir(confDir string) string {
	return filepath.Join(confDir, "auth.d")
}

func getInvalidOAuthConfig(conf string) string {
	return strings.Replace(conf, "sometoken", "someobviouslywrongtoken", 1)
}
<|endoftext|>


<commit_before>package forms

import (
	"github.com/kirves/go-form-it/common"
	"github.com/kirves/go-form-it/fields"
	"testing"
	"time"
)

const (
	style = formcommon.BOOTSTRAP
)

var (
	txt, psw, btn fields.FieldInterface
)

func TestFieldRender(t *testing.T) {
	field := fields.TextField("test")
	field.AddClass("test").AddClass("class").SetId("testId").SetParam("param1", "val1").AddCss("css1", "val1").SetStyle(style).Disabled()
	field.AddLabelClass("LABEL")
	field.SetLabel("This is a label")
	field.AddError("ERROR")
	t.Log("Rendered field:", field.Render())
	txt = field
}

func TestPasswordRender(t *testing.T) {
	field := fields.PasswordField("test")
	field.AddClass("test")
	field.AddClass("class")
	field.SetId("testId")
	field.SetStyle(style)
	field.SetValue("asd")
	t.Log("Rendered field:", field.Render())
	psw = field
}

func TestButtonRender(t *testing.T) {
	field := fields.SubmitButton("btn", "Click me!")
	field.SetStyle(style)
	t.Log("Rendered button:", field.Render())
	btn = field
}

func TestRadioButtonRender(t *testing.T) {
	field := fields.RadioField("radio", []fields.InputChoice{
		fields.InputChoice{Id: "choice1", Val: "value1"},
		fields.InputChoice{Id: "choice2", Val: "value2"},
	})
	field.SetStyle(style)
	t.Log("Rendered radio:", field.Render())
}

func TestSelectRender(t *testing.T) {
	field := fields.SelectField("select", map[string][]fields.InputChoice{
		"": []fields.InputChoice{
			fields.InputChoice{"choice1", "value1"},
			fields.InputChoice{"choice2", "value2"},
		},
	}).MultipleChoice().AddSelected("choice1", "choice2").SetLabel("asd")
	field.SetStyle(style).SetValue("choice1")
	t.Log("Rendered select:", field.Render())
}

func TestHiddenRender(t *testing.T) {
	field := fields.HiddenField("hidden")
	field.SetStyle(style)
	t.Log("Rendered hidden:", field.Render())
}

func TestNumberRender(t *testing.T) {
	field := fields.NumberField("number")
	field.SetStyle(style)
	t.Log("Rendered number:", field.Render())
}

func TestFormRender(t *testing.T) {
	form := BootstrapForm(POST, "")
	form.Elements(&FieldSetType{}, txt, psw, btn)
	// form.AddField(psw)
	// form.AddField(btn)
	t.Log("Rendered form:", form.Render())
}

func TestFormFromSimpleModel(t *testing.T) {
	type User struct {
		Username  string
		Password1 string `form_widget:"password" form_label:"Password 1"`
		Password2 string `form_widget:"password" form_label:"Password 2"`
		SkipThis  int    `form_options:"skip"`
	}

	u := User{}

	form := BaseFormFromModel(u, POST, "/action.html")
	t.Log("Rendered form:", form.Render())
}

func TestFormFromModel(t *testing.T) {
	type Model struct {
		User      string    `form_label:"User label test"`
		password  string    `form_widget:"password"`
		Id        int       `form_min:"0" form_max:"5"`
		Ts        time.Time `form_min:"2013-04-22T15:00"`
		RadioTest string    `form_widget:"select" form_choices:"|A|Option A|G1|B|Option B" form_value:"A"`
		BoolTest  bool      //`form_options:"checked"`
	}

	form := BaseFormFromModel(Model{"asd", "lol", 20, time.Now(), "B", false}, POST, "")
	t.Log("Rendered form:", form.Render())
}

func TestBSFormFromModel(t *testing.T) {
	type Model struct {
		User      string    `form_label:"User label test"`
		password  string    `form_widget:"password"`
		Id        int       `form_min:"0" form_max:"5"`
		Ts        time.Time `form_min:"2013-04-22T15:00"`
		RadioTest string    `form_widget:"select" form_choices:"|A|Option A|G1|B|Option B" form_value:"A"`
		BoolTest  bool      //`form_options:"checked"`
	}

	form := BootstrapFormFromModel(Model{"asd", "lol", 20, time.Now(), "B", false}, POST, "")
	t.Log("Rendered form:", form.Render())
}

func TestInlineCreation(t *testing.T) {
	form := BaseForm(POST, "/action.html").Elements(
		fields.TextField("text_field").SetLabel("Username"),
		FieldSet("psw_fieldset",
			fields.PasswordField("psw1").AddClass("password_class").SetLabel("Password 1"),
			fields.PasswordField("psw2").AddClass("password_class").SetLabel("Password 2"),
		),
		fields.SubmitButton("btn1", "Submit"),
	)
	t.Log("Rendered form:", form.Render())
}

func TestPizzaCreation(t *testing.T) {

	type Ingredient struct {
		IngredientId int    `db_key:"true" db_autoincrement:"true"`
		Name         string `db_size:"30"`
	}

	type Pizza struct {
		Id   int    `db_key:"true" db_autoincrement:"true"`
		Name string `db_size:"30"`
		// Ingredients []int
		Price float32 `form_widget:"number" form_min:"0"`

		// Transient
		Ingrs []Ingredient `db_transient:"true" form_options:"skip"`
	}

	form := BootstrapFormFromModel(Pizza{}, POST, "")
	t.Log("Rendered form:", form.Render())
}
<commit_msg>New tests<commit_after>package forms

import (
	"github.com/kirves/go-form-it/common"
	"github.com/kirves/go-form-it/fields"
	"testing"
	"time"
)

const (
	style = formcommon.BOOTSTRAP
)

var (
	txt, psw, btn fields.FieldInterface
)

func TestFieldRender(t *testing.T) {
	field := fields.TextField("test")
	field.AddClass("test").AddClass("class").SetId("testId").SetParam("param1", "val1").AddCss("css1", "val1").SetStyle(style).Disabled()
	field.AddLabelClass("LABEL")
	field.SetLabel("This is a label")
	field.AddError("ERROR")
	t.Log("Rendered field:", field.Render())
	txt = field
}

func TestPasswordRender(t *testing.T) {
	field := fields.PasswordField("test")
	field.AddClass("test")
	field.AddClass("class")
	field.SetId("testId")
	field.SetStyle(style)
	field.SetValue("asd")
	t.Log("Rendered field:", field.Render())
	psw = field
}

func TestButtonRender(t *testing.T) {
	field := fields.SubmitButton("btn", "Click me!")
	field.SetStyle(style)
	t.Log("Rendered button:", field.Render())
	btn = field
}

func TestRadioButtonRender(t *testing.T) {
	field := fields.RadioField("radio", []fields.InputChoice{
		fields.InputChoice{Id: "choice1", Val: "value1"},
		fields.InputChoice{Id: "choice2", Val: "value2"},
	})
	field.SetStyle(style)
	t.Log("Rendered radio:", field.Render())
}

func TestSelectRender(t *testing.T) {
	field := fields.SelectField("select", map[string][]fields.InputChoice{
		"": []fields.InputChoice{
			fields.InputChoice{"choice1", "value1"},
			fields.InputChoice{"choice2", "value2"},
		},
	}).MultipleChoice().SetLabel("asd").AddSelected("choice1", "choice2")
	field.SetStyle(style).SetValue("choice1")
	t.Log("Rendered select:", field.Render())
}

func TestHiddenRender(t *testing.T) {
	field := fields.HiddenField("hidden")
	field.SetStyle(style)
	t.Log("Rendered hidden:", field.Render())
}

func TestNumberRender(t *testing.T) {
	field := fields.NumberField("number")
	field.SetStyle(style)
	t.Log("Rendered number:", field.Render())
}

func TestFormRender(t *testing.T) {
	form := BootstrapForm(POST, "")
	form.Elements(&FieldSetType{}, txt, psw, btn)
	// form.AddField(psw)
	// form.AddField(btn)
	t.Log("Rendered form:", form.Render())
}

func TestFormFromSimpleModel(t *testing.T) {
	type User struct {
		Username  string
		Password1 string `form_widget:"password" form_label:"Password 1"`
		Password2 string `form_widget:"password" form_label:"Password 2"`
		SkipThis  int    `form_options:"skip"`
	}

	u := User{}

	form := BaseFormFromModel(u, POST, "/action.html")
	t.Log("Rendered form:", form.Render())
}

func TestFormFromModel(t *testing.T) {
	type Model struct {
		User      string    `form_label:"User label test"`
		password  string    `form_widget:"password"`
		Id        int       `form_min:"0" form_max:"5"`
		Ts        time.Time `form_min:"2013-04-22T15:00"`
		RadioTest string    `form_widget:"select" form_choices:"|A|Option A|G1|B|Option B" form_value:"A"`
		BoolTest  bool      //`form_options:"checked"`
	}

	form := BaseFormFromModel(Model{"asd", "lol", 20, time.Now(), "B", false}, POST, "")
	t.Log("Rendered form:", form.Render())
}

func TestBSFormFromModel(t *testing.T) {
	type Model struct {
		User      string    `form_label:"User label test"`
		password  string    `form_widget:"password"`
		Id        int       `form_min:"0" form_max:"5"`
		Ts        time.Time `form_min:"2013-04-22T15:00"`
		RadioTest string    `form_widget:"select" form_choices:"|A|Option A|G1|B|Option B" form_value:"A"`
		BoolTest  bool      //`form_options:"checked"`
	}

	form := BootstrapFormFromModel(Model{"asd", "lol", 20, time.Now(), "B", false}, POST, "")
	t.Log("Rendered form:", form.Render())
}

func TestInlineCreation(t *testing.T) {
	form := BaseForm(POST, "/action.html").Elements(
		fields.TextField("text_field").SetLabel("Username"),
		FieldSet("psw_fieldset",
			fields.PasswordField("psw1").AddClass("password_class").SetLabel("Password 1"),
			fields.PasswordField("psw2").AddClass("password_class").SetLabel("Password 2"),
		),
		fields.SubmitButton("btn1", "Submit"),
	)
	t.Log("Rendered form:", form.Render())
}

func TestPizzaCreation(t *testing.T) {

	type Ingredient struct {
		IngredientId int    `db_key:"true" db_autoincrement:"true"`
		Name         string `db_size:"30"`
	}

	type Pizza struct {
		Id   int    `db_key:"true" db_autoincrement:"true"`
		Name string `db_size:"30"`
		// Ingredients []int
		Price float32 `form_widget:"number" form_min:"0"`

		// Transient
		Ingrs []Ingredient `db_transient:"true" form_options:"skip"`
	}

	form := BootstrapFormFromModel(Pizza{Price: 2.2}, POST, "")
	t.Log("Rendered form:", form.Render())
}
<|endoftext|>


<commit_before>package spinner

const (
	clockOneOClock = '\U0001F550'
	clockOneThirty = '\U0001F55C'
)

// CharSets contains the available character sets
var CharSets = map[int][]string{
	0:  {"←", "↖", "↑", "↗", "→", "↘", "↓", "↙"},
	1:  {"▁", "▃", "▄", "▅", "▆", "▇", "█", "▇", "▆", "▅", "▄", "▃", "▁"},
	2:  {"▖", "▘", "▝", "▗"},
	3:  {"┤", "┘", "┴", "└", "├", "┌", "┬", "┐"},
	4:  {"◢", "◣", "◤", "◥"},
	5:  {"◰", "◳", "◲", "◱"},
	6:  {"◴", "◷", "◶", "◵"},
	7:  {"◐", "◓", "◑", "◒"},
	8:  {".", "o", "O", "@", "*"},
	9:  {"|", "/", "-", "\\"},
	10: {"◡◡", "⊙⊙", "◠◠"},
	11: {"⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"},
	12: {">))'>", " >))'>", "  >))'>", "   >))'>", "    >))'>", "   <'((<", "  <'((<", " <'((<"},
	13: {"⠁", "⠂", "⠄", "⡀", "⢀", "⠠", "⠐", "⠈"},
	14: {"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
	15: {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"},
	16: {"▉", "▊", "▋", "▌", "▍", "▎", "▏", "▎", "▍", "▌", "▋", "▊", "▉"},
	17: {"■", "□", "▪", "▫"},
	18: {"←", "↑", "→", "↓"},
	19: {"╫", "╪"},
	20: {"⇐", "⇖", "⇑", "⇗", "⇒", "⇘", "⇓", "⇙"},
	21: {"⠁", "⠁", "⠉", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠤", "⠄", "⠄", "⠤", "⠠", "⠠", "⠤", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋", "⠉", "⠈", "⠈"},
	22: {"⠈", "⠉", "⠋", "⠓", "⠒", "⠐", "⠐", "⠒", "⠖", "⠦", "⠤", "⠠", "⠠", "⠤", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋", "⠉", "⠈"},
	23: {"⠁", "⠉", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠤", "⠄", "⠄", "⠤", "⠴", "⠲", "⠒", "⠂", "⠂", "⠒", "⠚", "⠙", "⠉", "⠁"},
	24: {"⠋", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋"},
	25: {"ｦ", "ｧ", "ｨ", "ｩ", "ｪ", "ｫ", "ｬ", "ｭ", "ｮ", "ｯ", "ｱ", "ｲ", "ｳ", "ｴ", "ｵ", "ｶ", "ｷ", "ｸ", "ｹ", "ｺ", "ｻ", "ｼ", "ｽ", "ｾ", "ｿ", "ﾀ", "ﾁ", "ﾂ", "ﾃ", "ﾄ", "ﾅ", "ﾆ", "ﾇ", "ﾈ", "ﾉ", "ﾊ", "ﾋ", "ﾌ", "ﾍ", "ﾎ", "ﾏ", "ﾐ", "ﾑ", "ﾒ", "ﾓ", "ﾔ", "ﾕ", "ﾖ", "ﾗ", "ﾘ", "ﾙ", "ﾚ", "ﾛ", "ﾜ", "ﾝ"},
	26: {".", "..", "..."},
	27: {"▁", "▂", "▃", "▄", "▅", "▆", "▇", "█", "▉", "▊", "▋", "▌", "▍", "▎", "▏", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█", "▇", "▆", "▅", "▄", "▃", "▂", "▁"},
	28: {".", "o", "O", "°", "O", "o", "."},
	29: {"+", "x"},
	30: {"v", "<", "^", ">"},
	31: {">>--->", " >>--->", "  >>--->", "   >>--->", "    >>--->", "    <---<<", "   <---<<", "  <---<<", " <---<<", "<---<<"},
	32: {"|", "||", "|||", "||||", "|||||", "|||||||", "||||||||", "|||||||", "||||||", "|||||", "||||", "|||", "||", "|"},
	33: {"[          ]", "[=         ]", "[==        ]", "[===       ]", "[====      ]", "[=====     ]", "[======    ]", "[=======   ]", "[========  ]", "[========= ]", "[==========]"},
	34: {"(*---------)", "(-*--------)", "(--*-------)", "(---*------)", "(----*-----)", "(-----*----)", "(------*---)", "(-------*--)", "(--------*-)", "(---------*)"},
	35: {"█▒▒▒▒▒▒▒▒▒", "███▒▒▒▒▒▒▒", "█████▒▒▒▒▒", "███████▒▒▒", "██████████"},
	36: {"[                    ]", "[=>                  ]", "[===>                ]", "[=====>              ]", "[======>             ]", "[========>           ]", "[==========>         ]", "[============>       ]", "[==============>     ]", "[================>   ]", "[==================> ]", "[===================>]"},
	39: {"🌍", "🌎", "🌏"},
}

func init() {
	for i := rune(0); i < 12; i++ {
		CharSets[37] = append(CharSets[37], string([]rune{clockOneOClock + i}))
		CharSets[38] = append(CharSets[38], string([]rune{clockOneOClock + i}), string([]rune{clockOneThirty + i}))
	}
}
<commit_msg>added more spinners<commit_after>package spinner

const (
	clockOneOClock = '\U0001F550'
	clockOneThirty = '\U0001F55C'
)

// CharSets contains the available character sets
var CharSets = map[int][]string{
	0:  {"←", "↖", "↑", "↗", "→", "↘", "↓", "↙"},
	1:  {"▁", "▃", "▄", "▅", "▆", "▇", "█", "▇", "▆", "▅", "▄", "▃", "▁"},
	2:  {"▖", "▘", "▝", "▗"},
	3:  {"┤", "┘", "┴", "└", "├", "┌", "┬", "┐"},
	4:  {"◢", "◣", "◤", "◥"},
	5:  {"◰", "◳", "◲", "◱"},
	6:  {"◴", "◷", "◶", "◵"},
	7:  {"◐", "◓", "◑", "◒"},
	8:  {".", "o", "O", "@", "*"},
	9:  {"|", "/", "-", "\\"},
	10: {"◡◡", "⊙⊙", "◠◠"},
	11: {"⣾", "⣽", "⣻", "⢿", "⡿", "⣟", "⣯", "⣷"},
	12: {">))'>", " >))'>", "  >))'>", "   >))'>", "    >))'>", "   <'((<", "  <'((<", " <'((<"},
	13: {"⠁", "⠂", "⠄", "⡀", "⢀", "⠠", "⠐", "⠈"},
	14: {"⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"},
	15: {"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"},
	16: {"▉", "▊", "▋", "▌", "▍", "▎", "▏", "▎", "▍", "▌", "▋", "▊", "▉"},
	17: {"■", "□", "▪", "▫"},
	18: {"←", "↑", "→", "↓"},
	19: {"╫", "╪"},
	20: {"⇐", "⇖", "⇑", "⇗", "⇒", "⇘", "⇓", "⇙"},
	21: {"⠁", "⠁", "⠉", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠤", "⠄", "⠄", "⠤", "⠠", "⠠", "⠤", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋", "⠉", "⠈", "⠈"},
	22: {"⠈", "⠉", "⠋", "⠓", "⠒", "⠐", "⠐", "⠒", "⠖", "⠦", "⠤", "⠠", "⠠", "⠤", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋", "⠉", "⠈"},
	23: {"⠁", "⠉", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠤", "⠄", "⠄", "⠤", "⠴", "⠲", "⠒", "⠂", "⠂", "⠒", "⠚", "⠙", "⠉", "⠁"},
	24: {"⠋", "⠙", "⠚", "⠒", "⠂", "⠂", "⠒", "⠲", "⠴", "⠦", "⠖", "⠒", "⠐", "⠐", "⠒", "⠓", "⠋"},
	25: {"ｦ", "ｧ", "ｨ", "ｩ", "ｪ", "ｫ", "ｬ", "ｭ", "ｮ", "ｯ", "ｱ", "ｲ", "ｳ", "ｴ", "ｵ", "ｶ", "ｷ", "ｸ", "ｹ", "ｺ", "ｻ", "ｼ", "ｽ", "ｾ", "ｿ", "ﾀ", "ﾁ", "ﾂ", "ﾃ", "ﾄ", "ﾅ", "ﾆ", "ﾇ", "ﾈ", "ﾉ", "ﾊ", "ﾋ", "ﾌ", "ﾍ", "ﾎ", "ﾏ", "ﾐ", "ﾑ", "ﾒ", "ﾓ", "ﾔ", "ﾕ", "ﾖ", "ﾗ", "ﾘ", "ﾙ", "ﾚ", "ﾛ", "ﾜ", "ﾝ"},
	26: {".", "..", "..."},
	27: {"▁", "▂", "▃", "▄", "▅", "▆", "▇", "█", "▉", "▊", "▋", "▌", "▍", "▎", "▏", "▏", "▎", "▍", "▌", "▋", "▊", "▉", "█", "▇", "▆", "▅", "▄", "▃", "▂", "▁"},
	28: {".", "o", "O", "°", "O", "o", "."},
	29: {"+", "x"},
	30: {"v", "<", "^", ">"},
	31: {">>--->", " >>--->", "  >>--->", "   >>--->", "    >>--->", "    <---<<", "   <---<<", "  <---<<", " <---<<", "<---<<"},
	32: {"|", "||", "|||", "||||", "|||||", "|||||||", "||||||||", "|||||||", "||||||", "|||||", "||||", "|||", "||", "|"},
	33: {"[          ]", "[=         ]", "[==        ]", "[===       ]", "[====      ]", "[=====     ]", "[======    ]", "[=======   ]", "[========  ]", "[========= ]", "[==========]"},
	34: {"(*---------)", "(-*--------)", "(--*-------)", "(---*------)", "(----*-----)", "(-----*----)", "(------*---)", "(-------*--)", "(--------*-)", "(---------*)"},
	35: {"█▒▒▒▒▒▒▒▒▒", "███▒▒▒▒▒▒▒", "█████▒▒▒▒▒", "███████▒▒▒", "██████████"},
	36: {"[                    ]", "[=>                  ]", "[===>                ]", "[=====>              ]", "[======>             ]", "[========>           ]", "[==========>         ]", "[============>       ]", "[==============>     ]", "[================>   ]", "[==================> ]", "[===================>]"},
	39: {"🌍", "🌎", "🌏"},
	40: {"◜", "◝", "◞", "◟"},
}

func init() {
	for i := rune(0); i < 12; i++ {
		CharSets[37] = append(CharSets[37], string([]rune{clockOneOClock + i}))
		CharSets[38] = append(CharSets[38], string([]rune{clockOneOClock + i}), string([]rune{clockOneThirty + i}))
	}
}
<|endoftext|>


<commit_before>package device

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

	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/xshellinc/iotit/lib"
	"github.com/xshellinc/iotit/lib/vbox"
	"github.com/xshellinc/tools/constants"
	"github.com/xshellinc/tools/dialogs"
	"github.com/xshellinc/tools/lib/help"
	"github.com/xshellinc/tools/lib/sudo"
)

const (
	baseConf  string = "base-feeds.conf"
	iotdkConf string = "intel-iotdk.conf"

	baseFeeds string = "src/gz all        http://repo.opkg.net/edison/repo/all\n" +
		"src/gz edison     http://repo.opkg.net/edison/repo/edison\n" +
		"src/gz core2-32   http://repo.opkg.net/edison/repo/core2-32\n"

	intelIotdk string = "src intel-all     http://iotdk.intel.com/repos/1.1/iotdk/all\n" +
		"src intel-iotdk   http://iotdk.intel.com/repos/1.1/intelgalactic\n" +
		"src intel-quark   http://iotdk.intel.com/repos/1.1/iotdk/quark\n" +
		"src intel-i586    http://iotdk.intel.com/repos/1.1/iotdk/i586\n" +
		"src intel-x86     http://iotdk.intel.com/repos/1.1/iotdk/x86\n"
)

// Inits vbox, mounts image, copies config files into image, then closes image, copies image into /tmp
// on the host machine, then flashes it onto mounted disk and eject it cleaning up temporary files
func initEdison() error {
	wg := &sync.WaitGroup{}

	ack := dialogs.YesNoDialog("Would you like to flash your device? ")

	if ack {
		vm, _, _, _ := vboxDownloadImage(wg, lib.VBoxTemplateEdison, constants.DEVICE_TYPE_EDISON)

		printWarnMessage()

		for ack {
			ack = !dialogs.YesNoDialog("Please unplug your edison board. Press yes once unpluged? ")
		}

		for {
			script := "flashall.sh"

			args := []string{
				fmt.Sprintf("%s@%s", lib.TemplateUser, lib.TemplateIP),
				"-p",
				lib.TemplateSSHPort,
				constants.TMP_DIR + script,
			}

			if err := help.ExecStandardStd("ssh", args...); err != nil {
				fmt.Println("[-] Cannot find mounted Intel edison device, please mount it manually")

				if !dialogs.YesNoDialog("Press yes once mounted? ") {
					fmt.Println("Exiting with exit status 2 ...")
					os.Exit(2)
				}

				continue
			}

			break
		}

		fmt.Printf("[+] Stopping virtual machine - Name:%s UUID:%s\n", vm.Name, vm.UUID)

		if err := vbox.Stop(vm.UUID); err != nil {
			log.Error(err)
		}

		progress := make(chan bool)
		go func() {
			defer close(progress)
			time.Sleep(120 * time.Second)
		}()

		help.WaitAndSpin("Configuring edison", progress)
		<-progress

	}

	// Config edison
	config := NewSetDevice(constants.DEVICE_TYPE_EDISON)

	help.ExitOnError(config.SetConfig())

	// Info message
	printDoneMessageUsb()

	return nil
}

// Uses ifconfig to setup edison interface to be accessable via 192.168.2.2 ip
func (e *edison) SetConfig() error {
	// get IP

	i := dialogs.SelectOneDialog("Chose the edison's inteface to connect via usb: ", []string{"Default", "Enter IP"})
	fallback := false

	if i == 0 {
		out, err := help.ExecCmd("sh", []string{"-c", "ifconfig | expand | cut -c1-8 | sort | uniq -u | awk -F: '{print $1;}'"})

		if err != nil {
			log.Error(err)
			fmt.Println("[-] ", err.Error())
			fallback = true
		}

		if !fallback {
			arr := strings.Split(out, "\n")

			tmp := -1
			for idx, v := range arr {
				if strings.Contains(v, "usb") || strings.Contains(v, "en") {
					tmp = idx
				}
			}

			arrSel := make([]string, len(arr)-1)
			copy(arrSel, arr)

			if tmp < 0 {
				arr = append(arr, "\x1b[34musb0\x1b[0m")
			} else {
				arrSel[tmp] = "\x1b[34m" + arr[tmp] + "\x1b[0m"
			}

			i = dialogs.SelectOneDialog("Please chose correct interface: ", arrSel)

			if out, err = help.ExecSudo(sudo.InputMaskedPassword, nil, "ifconfig", arr[i], "192.168.2.2"); err != nil {
				fmt.Println("[-] Error running \x1b[34msudo ifconfig ", arrSel[i], " 192.168.2.2\x1b[0m: ", out)
				fallback = true
			}

			e.ip = "192.168.2.15"
		}
	}

	if i == 1 || fallback {
		fmt.Println("NOTE: You might need to run `sudo ifconfig {interface} \x1b[34m192.168.2.2\x1b[0m` in order to access Edison at \x1b[34m192.168.2.15\x1b[0m")
		e.ip = dialogs.GetSingleAnswer("Input Edison board IP Address: ", dialogs.IpAddressValidator)
	}

	if err := deleteHost(filepath.Join((os.Getenv("HOME")), ".ssh", "known_hosts"), e.ip); err != nil {
		log.Error(err)
	}

	time.Sleep(time.Second * 4)

	if err := e.SetInterfaces(*ifaces); err != nil {
		return err
	}

	args := []string{
		"root@" + e.ip,
		"-t",
		"sed -i.bak 's/wireless run configure_edison --password first/wireless run `device config user` first/g' /usr/bin/configure_edison",
	}

	if err := help.ExecStandardStd("ssh", args...); err != nil {
		return err
	}

	base := filepath.Join(constants.TMP_DIR, baseConf)
	baseConf := baseFeeds
	help.WriteToFile(baseConf, base)
	if err := exec.Command("scp", base, fmt.Sprintf("root@%s:%s", e.ip, filepath.Join("/etc", "opkg"))).Run(); err != nil {
		return err
	}
	os.Remove(base)

	iotdk := filepath.Join(constants.TMP_DIR, iotdkConf)
	iotdkConf := intelIotdk
	help.WriteToFile(iotdkConf, iotdk)
	if err := exec.Command("scp", iotdk, fmt.Sprintf("root@%s:%s", e.ip, filepath.Join("/etc", "opkg"))).Run(); err != nil {
		return err
	}
	os.Remove(iotdk)

	if err := help.ExecStandardStd("ssh", "root@"+e.ip, "-t", "configure_edison --wifi"); err != nil {
		return err
	}

	if err := help.ExecStandardStd("ssh", "root@"+e.ip, "-t", "configure_edison --password"); err != nil {
		return err
	}

	return nil

}

// Set up Interface values
func (e *edison) SetInterfaces(i Interfaces) error {

	if dialogs.YesNoDialog("Would you like to assign static IP wlan address for your device?") {

		// assign static ip
		fmt.Println("[+] ********NOTE: ADJUST THESE VALUES ACCORDING TO YOUR LOCAL NETWORK CONFIGURATION********")

		fmt.Printf("[+] Current values are:\n \t[+] Address:%s\n\t [+] Network:%s\n\t [+] Gateway:%s\n\t[+] Netmask:%s\n\t[+] DNS:%s\n",
			i.Address, i.Network, i.Gateway, i.Netmask, i.DNS)

		if dialogs.YesNoDialog("Change values?") {
			setInterfaces(&i)

			args1 := []string{
				"root@" + e.ip,
				"-t",
				fmt.Sprintf("sed -i.bak -e '53 s/.*/ifconfig $IFNAME %s netmask %s/g' /etc/wpa_supplicant/wpa_cli-actions.sh",
					i.Address, i.Netmask),
			}
			args2 := []string{
				"root@" + e.ip,
				"-t",
				fmt.Sprintf("sed -i -e '54i route add default gw %s' /etc/wpa_supplicant/wpa_cli-actions.sh",
					i.Gateway),
			}
			args3 := []string{
				"root@" + e.ip,
				"-t",
				fmt.Sprintf("echo nameserver %s > /etc/%s", i.DNS, e.resolvF),
			}

			if err := help.ExecStandardStd("ssh", args1...); err != nil {
				return err
			}

			if err := help.ExecStandardStd("ssh", args2...); err != nil {
				return err
			}

			if err := help.ExecStandardStd("ssh", args3...); err != nil {
				return err
			}
		}
	}

	return nil
}

func printWarnMessage() {
	fmt.Println(strings.Repeat("*", 100))
	fmt.Println("*\t\t WARNNING!!  \t\t\t\t\t\t\t\t\t   *")
	fmt.Println("*\t\t IF YOUR EDISON BOARD IS CONNECTED TO YOUR MACHINE, PLEASE DISCONNECT IT!  \t   *")
	fmt.Println("*\t\t PLEASE FOLLOW THE INSTRUCTIONS! \t\t\t\t\t\t   *")
	fmt.Println(strings.Repeat("*", 100))
}
<commit_msg>Change Edison interface selection by narrowing it<commit_after>package device

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

	"time"

	log "github.com/Sirupsen/logrus"
	"github.com/xshellinc/iotit/lib"
	"github.com/xshellinc/iotit/lib/vbox"
	"github.com/xshellinc/tools/constants"
	"github.com/xshellinc/tools/dialogs"
	"github.com/xshellinc/tools/lib/help"
	"github.com/xshellinc/tools/lib/sudo"
)

const (
	baseConf  string = "base-feeds.conf"
	iotdkConf string = "intel-iotdk.conf"

	baseFeeds string = "src/gz all        http://repo.opkg.net/edison/repo/all\n" +
		"src/gz edison     http://repo.opkg.net/edison/repo/edison\n" +
		"src/gz core2-32   http://repo.opkg.net/edison/repo/core2-32\n"

	intelIotdk string = "src intel-all     http://iotdk.intel.com/repos/1.1/iotdk/all\n" +
		"src intel-iotdk   http://iotdk.intel.com/repos/1.1/intelgalactic\n" +
		"src intel-quark   http://iotdk.intel.com/repos/1.1/iotdk/quark\n" +
		"src intel-i586    http://iotdk.intel.com/repos/1.1/iotdk/i586\n" +
		"src intel-x86     http://iotdk.intel.com/repos/1.1/iotdk/x86\n"
)

// Inits vbox, mounts image, copies config files into image, then closes image, copies image into /tmp
// on the host machine, then flashes it onto mounted disk and eject it cleaning up temporary files
func initEdison() error {
	wg := &sync.WaitGroup{}

	ack := dialogs.YesNoDialog("Would you like to flash your device? ")

	if ack {
		vm, _, _, _ := vboxDownloadImage(wg, lib.VBoxTemplateEdison, constants.DEVICE_TYPE_EDISON)

		printWarnMessage()

		for ack {
			ack = !dialogs.YesNoDialog("Please unplug your edison board. Press yes once unpluged? ")
		}

		for {
			script := "flashall.sh"

			args := []string{
				fmt.Sprintf("%s@%s", lib.TemplateUser, lib.TemplateIP),
				"-p",
				lib.TemplateSSHPort,
				constants.TMP_DIR + script,
			}

			if err := help.ExecStandardStd("ssh", args...); err != nil {
				fmt.Println("[-] Cannot find mounted Intel edison device, please mount it manually")

				if !dialogs.YesNoDialog("Press yes once mounted? ") {
					fmt.Println("Exiting with exit status 2 ...")
					os.Exit(2)
				}

				continue
			}

			break
		}

		fmt.Printf("[+] Stopping virtual machine - Name:%s UUID:%s\n", vm.Name, vm.UUID)

		if err := vbox.Stop(vm.UUID); err != nil {
			log.Error(err)
		}

		progress := make(chan bool)
		go func() {
			defer close(progress)
			time.Sleep(120 * time.Second)
		}()

		help.WaitAndSpin("Configuring edison", progress)
		<-progress

	}

	// Config edison
	config := NewSetDevice(constants.DEVICE_TYPE_EDISON)

	help.ExitOnError(config.SetConfig())

	// Info message
	printDoneMessageUsb()

	return nil
}

// Uses ifconfig to setup edison interface to be accessable via 192.168.2.2 ip
func (e *edison) SetConfig() error {
	// get IP

	i := dialogs.SelectOneDialog("Chose the edison's inteface to connect via usb: ", []string{"Default", "Enter IP"})
	fallback := false

	if i == 0 {
		ifaces, err := help.LocalIfaces()

		if err != nil || len(ifaces) == 0 {
			log.Error(err)
			fmt.Println("[-] ", err.Error())
			fallback = true
		}

		if !fallback {
			arr := make([]string, len(ifaces))
			arrSel := make([]string, len(ifaces))
			for i, iface := range ifaces {
				arr[i] = iface.Name
				arrSel[i] = iface.Name
				if iface.Ipv4[:4] == "169." {
					arrSel[i] = "\x1b[34m" + iface.Name + "\x1b[0m"
					fmt.Println("[+] The highlighted interface is our heuristic guess")
				}
			}

			i = dialogs.SelectOneDialog("Please chose correct interface: ", arrSel)

			if out, err := help.ExecSudo(sudo.InputMaskedPassword, nil, "ifconfig", arr[i], "192.168.2.2"); err != nil {
				fmt.Println("[-] Error running \x1b[34msudo ifconfig ", arrSel[i], " 192.168.2.2\x1b[0m: ", out)
				fallback = true
			}

			e.ip = "192.168.2.15"
		}
	}

	if i == 1 || fallback {
		fmt.Println("NOTE: You might need to run `sudo ifconfig {interface} \x1b[34m192.168.2.2\x1b[0m` in order to access Edison at \x1b[34m192.168.2.15\x1b[0m")
		e.ip = dialogs.GetSingleAnswer("Input Edison board IP Address: ", dialogs.IpAddressValidator)
	}

	if err := deleteHost(filepath.Join((os.Getenv("HOME")), ".ssh", "known_hosts"), e.ip); err != nil {
		log.Error(err)
	}

	time.Sleep(time.Second * 4)

	if err := e.SetInterfaces(*ifaces); err != nil {
		return err
	}

	args := []string{
		"root@" + e.ip,
		"-t",
		"sed -i.bak 's/wireless run configure_edison --password first/wireless run `device config user` first/g' /usr/bin/configure_edison",
	}

	if err := help.ExecStandardStd("ssh", args...); err != nil {
		return err
	}

	base := filepath.Join(constants.TMP_DIR, baseConf)
	baseConf := baseFeeds
	help.WriteToFile(baseConf, base)
	if err := exec.Command("scp", base, fmt.Sprintf("root@%s:%s", e.ip, filepath.Join("/etc", "opkg"))).Run(); err != nil {
		return err
	}
	os.Remove(base)

	iotdk := filepath.Join(constants.TMP_DIR, iotdkConf)
	iotdkConf := intelIotdk
	help.WriteToFile(iotdkConf, iotdk)
	if err := exec.Command("scp", iotdk, fmt.Sprintf("root@%s:%s", e.ip, filepath.Join("/etc", "opkg"))).Run(); err != nil {
		return err
	}
	os.Remove(iotdk)

	if err := help.ExecStandardStd("ssh", "root@"+e.ip, "-t", "configure_edison --wifi"); err != nil {
		return err
	}

	if err := help.ExecStandardStd("ssh", "root@"+e.ip, "-t", "configure_edison --password"); err != nil {
		return err
	}

	return nil

}

// Set up Interface values
func (e *edison) SetInterfaces(i Interfaces) error {

	if dialogs.YesNoDialog("Would you like to assign static IP wlan address for your device?") {

		// assign static ip
		fmt.Println("[+] ********NOTE: ADJUST THESE VALUES ACCORDING TO YOUR LOCAL NETWORK CONFIGURATION********")

		fmt.Printf("[+] Current values are:\n \t[+] Address:%s\n\t [+] Network:%s\n\t [+] Gateway:%s\n\t[+] Netmask:%s\n\t[+] DNS:%s\n",
			i.Address, i.Network, i.Gateway, i.Netmask, i.DNS)

		if dialogs.YesNoDialog("Change values?") {
			setInterfaces(&i)

			args1 := []string{
				"root@" + e.ip,
				"-t",
				fmt.Sprintf("sed -i.bak -e '53 s/.*/ifconfig $IFNAME %s netmask %s/g' /etc/wpa_supplicant/wpa_cli-actions.sh",
					i.Address, i.Netmask),
			}
			args2 := []string{
				"root@" + e.ip,
				"-t",
				fmt.Sprintf("sed -i -e '54i route add default gw %s' /etc/wpa_supplicant/wpa_cli-actions.sh",
					i.Gateway),
			}
			args3 := []string{
				"root@" + e.ip,
				"-t",
				fmt.Sprintf("echo nameserver %s > /etc/%s", i.DNS, e.resolvF),
			}

			if err := help.ExecStandardStd("ssh", args1...); err != nil {
				return err
			}

			if err := help.ExecStandardStd("ssh", args2...); err != nil {
				return err
			}

			if err := help.ExecStandardStd("ssh", args3...); err != nil {
				return err
			}
		}
	}

	return nil
}

func printWarnMessage() {
	fmt.Println(strings.Repeat("*", 100))
	fmt.Println("*\t\t WARNNING!!  \t\t\t\t\t\t\t\t\t   *")
	fmt.Println("*\t\t IF YOUR EDISON BOARD IS CONNECTED TO YOUR MACHINE, PLEASE DISCONNECT IT!  \t   *")
	fmt.Println("*\t\t PLEASE FOLLOW THE INSTRUCTIONS! \t\t\t\t\t\t   *")
	fmt.Println(strings.Repeat("*", 100))
}
<|endoftext|>


<commit_before>package device

import (
	"strconv"
	"testing"

	"github.com/Comcast/webpa-common/logging"
	"github.com/Comcast/webpa-common/xmetrics/xmetricstest"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func testRegistryAdd(t *testing.T) {
	t.Run("Unlimited", func(t *testing.T) {
		var (
			assert  = assert.New(t)
			require = require.New(t)
			logger  = logging.NewTestLogger(nil, t)

			p = xmetricstest.NewProvider(nil, Metrics)
			r = newRegistry(registryOptions{
				Logger:   logger,
				Measures: NewMeasures(p),
			})
		)

		require.NotNil(r)
		p.Assert(t, DeviceCounter)(xmetricstest.Value(0.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

		for i := 0; i < 10; i++ {
			d := newDevice(deviceOptions{
				ID:     ID(strconv.Itoa(i)),
				Logger: logger,
			})

			require.NoError(r.add(d))
			assert.False(d.Closed())
			p.Assert(t, DeviceCounter)(xmetricstest.Value(float64(i + 1)))
			p.Assert(t, ConnectCounter)(xmetricstest.Value(float64(i + 1)))
			p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
			p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
			p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))
		}

		existing, ok := r.get(ID("0"))
		require.NotNil(existing)
		assert.True(ok)

		duplicate := newDevice(deviceOptions{
			ID:     ID("0"),
			Logger: logger,
		})

		assert.False(existing.Closed())
		assert.False(duplicate.Closed())
		r.add(duplicate)
		p.Assert(t, DeviceCounter)(xmetricstest.Value(10.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(11.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(1.0))

		assert.True(existing.Closed())
		assert.False(duplicate.Closed())
	})

	t.Run("Limited", func(t *testing.T) {
		var (
			assert  = assert.New(t)
			require = require.New(t)
			logger  = logging.NewTestLogger(nil, t)

			p = xmetricstest.NewProvider(nil, Metrics)
			r = newRegistry(registryOptions{
				Logger:   logger,
				Limit:    1,
				Measures: NewMeasures(p),
			})
		)

		require.NotNil(r)
		p.Assert(t, DeviceCounter)(xmetricstest.Value(0.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

		initial := newDevice(deviceOptions{
			ID:     ID("test"),
			Logger: logger,
		})

		assert.NoError(r.add(initial))
		assert.False(initial.Closed())
		p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

		cantAdd := newDevice(deviceOptions{
			ID:     ID("cantAdd"),
			Logger: logger,
		})

		assert.Error(r.add(cantAdd))
		assert.False(initial.Closed())
		assert.True(cantAdd.Closed())
		p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

		duplicate := newDevice(deviceOptions{
			ID:     ID("test"),
			Logger: logger,
		})

		assert.NoError(r.add(duplicate))
		assert.True(initial.Closed())
		assert.False(duplicate.Closed())
		p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(2.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(2.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(1.0))
	})
}

func testRegistryRemove(t *testing.T) {
}

func TestRegistry(t *testing.T) {
	t.Run("Add", testRegistryAdd)
	t.Run("Remove", testRegistryRemove)
}
<commit_msg>Full tests for the registry behavior<commit_after>package device

import (
	"strconv"
	"testing"

	"github.com/Comcast/webpa-common/logging"
	"github.com/Comcast/webpa-common/xmetrics/xmetricstest"
	"github.com/stretchr/testify/assert"
	"github.com/stretchr/testify/require"
)

func testRegistryAdd(t *testing.T) {
	t.Run("Unlimited", func(t *testing.T) {
		var (
			assert  = assert.New(t)
			require = require.New(t)
			logger  = logging.NewTestLogger(nil, t)

			p = xmetricstest.NewProvider(nil, Metrics)
			r = newRegistry(registryOptions{
				Logger:   logger,
				Measures: NewMeasures(p),
			})
		)

		require.NotNil(r)
		p.Assert(t, DeviceCounter)(xmetricstest.Value(0.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

		for i := 0; i < 10; i++ {
			d := newDevice(deviceOptions{
				ID:     ID(strconv.Itoa(i)),
				Logger: logger,
			})

			require.NoError(r.add(d))
			assert.False(d.Closed())
			p.Assert(t, DeviceCounter)(xmetricstest.Value(float64(i + 1)))
			p.Assert(t, ConnectCounter)(xmetricstest.Value(float64(i + 1)))
			p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
			p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
			p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))
		}

		existing, ok := r.get(ID("0"))
		require.NotNil(existing)
		assert.True(ok)

		duplicate := newDevice(deviceOptions{
			ID:     ID("0"),
			Logger: logger,
		})

		assert.False(existing.Closed())
		assert.False(duplicate.Closed())
		r.add(duplicate)
		p.Assert(t, DeviceCounter)(xmetricstest.Value(10.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(11.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(1.0))

		assert.True(existing.Closed())
		assert.False(duplicate.Closed())
	})

	t.Run("Limited", func(t *testing.T) {
		var (
			assert  = assert.New(t)
			require = require.New(t)
			logger  = logging.NewTestLogger(nil, t)

			p = xmetricstest.NewProvider(nil, Metrics)
			r = newRegistry(registryOptions{
				Logger:   logger,
				Limit:    1,
				Measures: NewMeasures(p),
			})
		)

		require.NotNil(r)
		p.Assert(t, DeviceCounter)(xmetricstest.Value(0.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

		initial := newDevice(deviceOptions{
			ID:     ID("test"),
			Logger: logger,
		})

		assert.NoError(r.add(initial))
		assert.False(initial.Closed())
		p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

		cantAdd := newDevice(deviceOptions{
			ID:     ID("cantAdd"),
			Logger: logger,
		})

		assert.Error(r.add(cantAdd))
		assert.False(initial.Closed())
		assert.True(cantAdd.Closed())
		p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

		duplicate := newDevice(deviceOptions{
			ID:     ID("test"),
			Logger: logger,
		})

		assert.NoError(r.add(duplicate))
		assert.True(initial.Closed())
		assert.False(duplicate.Closed())
		p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
		p.Assert(t, ConnectCounter)(xmetricstest.Value(2.0))
		p.Assert(t, DisconnectCounter)(xmetricstest.Value(2.0))
		p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(1.0))
		p.Assert(t, DuplicatesCounter)(xmetricstest.Value(1.0))
	})
}

func testRegistryRemoveAndGet(t *testing.T) {
	var (
		assert  = assert.New(t)
		require = require.New(t)
		logger  = logging.NewTestLogger(nil, t)

		p = xmetricstest.NewProvider(nil, Metrics)
		r = newRegistry(registryOptions{
			Logger:   logger,
			Limit:    1,
			Measures: NewMeasures(p),
		})
	)

	require.NotNil(r)

	initial := newDevice(deviceOptions{
		ID:     ID("test"),
		Logger: logger,
	})

	require.NoError(r.add(initial))
	p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

	existing, ok := r.get(ID("test"))
	assert.True(existing == initial)
	assert.True(ok)
	p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

	existing, ok = r.get(ID("nosuch"))
	assert.Nil(existing)
	assert.False(ok)
	assert.False(initial.Closed())
	p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

	existing, ok = r.remove(ID("nosuch"))
	assert.Nil(existing)
	assert.False(ok)
	assert.False(initial.Closed())
	p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

	existing, ok = r.remove(ID("test"))
	assert.True(existing == initial)
	assert.True(ok)
	assert.True(initial.Closed())
	p.Assert(t, DeviceCounter)(xmetricstest.Value(0.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

	existing, ok = r.get(ID("test"))
	assert.Nil(existing)
	assert.False(ok)
	p.Assert(t, DeviceCounter)(xmetricstest.Value(0.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))
}

func testRegistryRemoveIf(t *testing.T) {
	var (
		assert  = assert.New(t)
		require = require.New(t)
		logger  = logging.NewTestLogger(nil, t)

		p = xmetricstest.NewProvider(nil, Metrics)
		r = newRegistry(registryOptions{
			Logger:   logger,
			Limit:    1,
			Measures: NewMeasures(p),
		})
	)

	require.NotNil(r)

	initial := newDevice(deviceOptions{
		ID:     ID("test"),
		Logger: logger,
	})

	require.NoError(r.add(initial))
	p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

	assert.Equal(
		0,
		r.removeIf(func(*device) bool {
			return false
		}),
	)

	assert.False(initial.Closed())
	p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

	assert.Equal(
		1,
		r.removeIf(func(*device) bool {
			return true
		}),
	)

	assert.True(initial.Closed())
	p.Assert(t, DeviceCounter)(xmetricstest.Value(0.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))
}

func testRegistryVisit(t *testing.T) {
	var (
		assert  = assert.New(t)
		require = require.New(t)
		logger  = logging.NewTestLogger(nil, t)

		p = xmetricstest.NewProvider(nil, Metrics)
		r = newRegistry(registryOptions{
			Logger:   logger,
			Limit:    1,
			Measures: NewMeasures(p),
		})
	)

	require.NotNil(r)

	initial := newDevice(deviceOptions{
		ID:     ID("test"),
		Logger: logger,
	})

	require.NoError(r.add(initial))
	p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))

	visitCalled := false
	assert.Equal(
		1,
		r.visit(func(actual *device) {
			visitCalled = true
			assert.False(actual.Closed())
			assert.True(actual == initial)
		}),
	)

	assert.False(initial.Closed())
	assert.True(visitCalled)
	p.Assert(t, DeviceCounter)(xmetricstest.Value(1.0))
	p.Assert(t, ConnectCounter)(xmetricstest.Value(1.0))
	p.Assert(t, DisconnectCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DeviceLimitReachedCounter)(xmetricstest.Value(0.0))
	p.Assert(t, DuplicatesCounter)(xmetricstest.Value(0.0))
}

func TestRegistry(t *testing.T) {
	t.Run("Add", testRegistryAdd)
	t.Run("RemoveAndGet", testRegistryRemoveAndGet)
	t.Run("RemoveIf", testRegistryRemoveIf)
	t.Run("Visit", testRegistryVisit)
}
<|endoftext|>


<commit_before>package semver

import (
	"testing"

	"github.com/hashicorp/go-version"
)

// This file is a copy of github.com/hashicorp/go-version/constraint_test.go
// with minimal changes to demonstrate differences. Diffing the files should
// illustrate behavior differences in Constraint and version.Constraint.

func TestNewConstraint(t *testing.T) {
	cases := []struct {
		input string
		count int
		err   bool
	}{
		{">= 1.2", 1, false},
		{"1.0", 1, false},
		{">= 1.x", 0, true},
		{">= 1.2, < 1.0", 2, false},

		// Out of bounds
		{"11387778780781445675529500000000000000000", 0, true},

		// Semver only
		{">= 1.0beta1", 0, true},

		// No pessimistic operator
		{"~> 1.0", 0, true},
	}

	for _, tc := range cases {
		v, err := NewConstraint(tc.input)
		if tc.err && err == nil {
			t.Fatalf("expected error for input: %s", tc.input)
		} else if !tc.err && err != nil {
			t.Fatalf("error for input %s: %s", tc.input, err)
		}

		if len(v) != tc.count {
			t.Fatalf("input: %s\nexpected len: %d\nactual: %d",
				tc.input, tc.count, len(v))
		}
	}
}

func TestConstraintCheck(t *testing.T) {
	cases := []struct {
		constraint string
		version    string
		check      bool
	}{
		{">= 1.0, < 1.2", "1.1.5", true},
		{"< 1.0, < 1.2", "1.1.5", false},
		{"= 1.0", "1.1.5", false},
		{"= 1.0", "1.0.0", true},
		{"1.0", "1.0.0", true},

		// Pre-releases are ordered according to Semver v2
		{"> 2.0", "2.1.0-beta", true},
		{"> 2.1.0-a", "2.1.0-beta", true},
		{"> 2.1.0-a", "2.1.1-beta", true},
		{"> 2.0.0", "2.1.0-beta", true},
		{"> 2.1.0-a", "2.1.1", true},
		{"> 2.1.0-a", "2.1.1-beta", true},
		{"> 2.1.0-a", "2.1.0", true},
		{"<= 2.1.0-a", "2.0.0", true},
		{">= 0.6.1", "1.3.0-beta1", true},
		{"> 1.0-beta1", "1.0-rc1", true},

		// Meta components are ignored according to Semver v2
		{">= 0.6.1", "1.3.0-beta1+ent", true},
		{">= 1.3.0-beta1", "1.3.0-beta1+ent", true},
		{"> 1.3.0-beta1+cgo", "1.3.0-beta1+ent", false},
		{"= 1.3.0-beta1+cgo", "1.3.0-beta1+ent", true},
	}

	for _, tc := range cases {
		c, err := NewConstraint(tc.constraint)
		if err != nil {
			t.Fatalf("err: %s", err)
		}

		v, err := version.NewSemver(tc.version)
		if err != nil {
			t.Fatalf("err: %s", err)
		}

		actual := c.Check(v)
		expected := tc.check
		if actual != expected {
			t.Fatalf("Version: %s\nConstraint: %s\nExpected: %#v",
				tc.version, tc.constraint, expected)
		}
	}
}

func TestConstraintsString(t *testing.T) {
	cases := []struct {
		constraint string
		result     string
	}{
		{">= 1.0, < 1.2", ""},
	}

	for _, tc := range cases {
		c, err := NewConstraint(tc.constraint)
		if err != nil {
			t.Fatalf("err: %s", err)
		}

		actual := c.String()
		expected := tc.result
		if expected == "" {
			expected = tc.constraint
		}

		if actual != expected {
			t.Fatalf("Constraint: %s\nExpected: %#v\nActual: %s",
				tc.constraint, expected, actual)
		}
	}
}
<commit_msg>test: assert semvers are *not* compared lexically<commit_after>package semver

import (
	"testing"

	"github.com/hashicorp/go-version"
)

// This file is a copy of github.com/hashicorp/go-version/constraint_test.go
// with minimal changes to demonstrate differences. Diffing the files should
// illustrate behavior differences in Constraint and version.Constraint.

func TestNewConstraint(t *testing.T) {
	cases := []struct {
		input string
		count int
		err   bool
	}{
		{">= 1.2", 1, false},
		{"1.0", 1, false},
		{">= 1.x", 0, true},
		{">= 1.2, < 1.0", 2, false},

		// Out of bounds
		{"11387778780781445675529500000000000000000", 0, true},

		// Semver only
		{">= 1.0beta1", 0, true},

		// No pessimistic operator
		{"~> 1.0", 0, true},
	}

	for _, tc := range cases {
		v, err := NewConstraint(tc.input)
		if tc.err && err == nil {
			t.Fatalf("expected error for input: %s", tc.input)
		} else if !tc.err && err != nil {
			t.Fatalf("error for input %s: %s", tc.input, err)
		}

		if len(v) != tc.count {
			t.Fatalf("input: %s\nexpected len: %d\nactual: %d",
				tc.input, tc.count, len(v))
		}
	}
}

func TestConstraintCheck(t *testing.T) {
	cases := []struct {
		constraint string
		version    string
		check      bool
	}{
		{">= 1.0, < 1.2", "1.1.5", true},
		{"< 1.0, < 1.2", "1.1.5", false},
		{"= 1.0", "1.1.5", false},
		{"= 1.0", "1.0.0", true},
		{"1.0", "1.0.0", true},

		// Assert numbers are *not* compared lexically as in #4729
		{"> 10", "8", false},

		// Pre-releases are ordered according to Semver v2
		{"> 2.0", "2.1.0-beta", true},
		{"> 2.1.0-a", "2.1.0-beta", true},
		{"> 2.1.0-a", "2.1.1-beta", true},
		{"> 2.0.0", "2.1.0-beta", true},
		{"> 2.1.0-a", "2.1.1", true},
		{"> 2.1.0-a", "2.1.1-beta", true},
		{"> 2.1.0-a", "2.1.0", true},
		{"<= 2.1.0-a", "2.0.0", true},
		{">= 0.6.1", "1.3.0-beta1", true},
		{"> 1.0-beta1", "1.0-rc1", true},

		// Meta components are ignored according to Semver v2
		{">= 0.6.1", "1.3.0-beta1+ent", true},
		{">= 1.3.0-beta1", "1.3.0-beta1+ent", true},
		{"> 1.3.0-beta1+cgo", "1.3.0-beta1+ent", false},
		{"= 1.3.0-beta1+cgo", "1.3.0-beta1+ent", true},
	}

	for _, tc := range cases {
		c, err := NewConstraint(tc.constraint)
		if err != nil {
			t.Fatalf("err: %s", err)
		}

		v, err := version.NewSemver(tc.version)
		if err != nil {
			t.Fatalf("err: %s", err)
		}

		actual := c.Check(v)
		expected := tc.check
		if actual != expected {
			t.Fatalf("Version: %s\nConstraint: %s\nExpected: %#v",
				tc.version, tc.constraint, expected)
		}
	}
}

func TestConstraintsString(t *testing.T) {
	cases := []struct {
		constraint string
		result     string
	}{
		{">= 1.0, < 1.2", ""},
	}

	for _, tc := range cases {
		c, err := NewConstraint(tc.constraint)
		if err != nil {
			t.Fatalf("err: %s", err)
		}

		actual := c.String()
		expected := tc.result
		if expected == "" {
			expected = tc.constraint
		}

		if actual != expected {
			t.Fatalf("Constraint: %s\nExpected: %#v\nActual: %s",
				tc.constraint, expected, actual)
		}
	}
}
<|endoftext|>


<commit_before>package logrus_papertrail

import (
	"fmt"
	"testing"

	"github.com/Sirupsen/logrus"
	"github.com/stvp/go-udp-testing"
)

func TestWritingToUDP(t *testing.T) {
	port := 16661
	udp.SetAddr(fmt.Sprintf(":%d", port))

	hook, err := NewPapertrailHook(&Hook{
		Host:     "localhost",
		Port:     port,
		HostName: "test.local",
		AppName:  "test",
	})
	if err != nil {
		t.Errorf("Unable to connect to local UDP server.")
	}

	log := logrus.New()
	log.Hooks.Add(hook)

	udp.ShouldReceive(t, "foo", func() {
		log.Info("foo")
	})
}
<commit_msg>Fix the tests<commit_after>package logrus_papertrail

import (
	"fmt"
	"testing"

	"github.com/Sirupsen/logrus"
	"github.com/stvp/go-udp-testing"
)

func TestWritingToUDP(t *testing.T) {
	port := 16661
	udp.SetAddr(fmt.Sprintf(":%d", port))

	hook, err := NewPapertrailHook(&Hook{
		Host:     "localhost",
		Port:     port,
		Hostname: "test.local",
		Appname:  "test",
	})
	if err != nil {
		t.Errorf("Unable to connect to local UDP server.")
	}

	log := logrus.New()
	log.Hooks.Add(hook)

	udp.ShouldReceive(t, "foo", func() {
		log.Info("foo")
	})
}
<|endoftext|>


<commit_before>package devices

import (
	"fmt"

	"github.com/ninjasphere/go-ninja"
	"github.com/ninjasphere/go-ninja/channels"
	"github.com/ninjasphere/go-ninja/logger"
)

type MediaPlayerDevice struct {
	ApplyTogglePlay   func() error
	ApplyPlayPause    func(playing bool) error
	ApplyStop         func() error
	ApplyPlaylistJump func(delta int) error

	log            *logger.Logger
	bus            *ninja.DeviceBus
	controlChannel *channels.MediaControlChannel
	controlState   channels.MediaControlEvent
}

func (d *MediaPlayerDevice) SetControlState(state channels.MediaControlEvent) error {
	if d.controlChannel == nil {
		return fmt.Errorf("'media-control' channel has not been enabled. Call EnableControlChannel() first")
	}
	if state != d.controlState {
		d.controlState = state
		d.controlChannel.SendState(d.controlState)
	}
	return nil
}

func (d *MediaPlayerDevice) TogglePlay() error {

	if d.ApplyTogglePlay != nil {
		return d.ApplyTogglePlay()
	}

	switch d.controlState {
	case channels.MediaControlEventPlaying, channels.MediaControlEventBuffering, channels.MediaControlEventBusy:
		return d.Pause()
	default:
		return d.Play()
	}

}

func (d *MediaPlayerDevice) Play() error {
	return d.ApplyPlayPause(true)
}

func (d *MediaPlayerDevice) Pause() error {
	return d.ApplyPlayPause(false)
}

func (d *MediaPlayerDevice) Stop() error {
	return d.ApplyStop()
}

func (d *MediaPlayerDevice) Next() error {
	if d.ApplyPlaylistJump == nil {
		return fmt.Errorf("'Next' is not yet supported")
	}
	return d.ApplyPlaylistJump(1)
}

func (d *MediaPlayerDevice) Previous() error {
	if d.ApplyPlaylistJump == nil {
		return fmt.Errorf("'Previous' is not yet supported")
	}
	return d.ApplyPlaylistJump(-1)
}

func (d *MediaPlayerDevice) EnableControlChannel() error {

	d.controlChannel = channels.NewMediaControlChannel(d)

	err := d.bus.AddChannel(d.controlChannel, "control", "media-control")
	if err != nil {
		return fmt.Errorf("Failed to create media-control channel: %s", err)
	}

	return nil
}

func CreateMediaPlayerDevice(name string, bus *ninja.DeviceBus) (*MediaPlayerDevice, error) {

	player := &MediaPlayerDevice{
		bus: bus,
		log: logger.GetLogger("MediaPlayerDevice - " + name),
	}

	player.log.Infof("Created")

	return player, nil
}
<commit_msg>MediaPlayer: Announce supported methods and events in media-control channel<commit_after>package devices

import (
	"fmt"

	"github.com/ninjasphere/go-ninja"
	"github.com/ninjasphere/go-ninja/channels"
	"github.com/ninjasphere/go-ninja/logger"
)

type MediaPlayerDevice struct {
	ApplyTogglePlay   func() error
	ApplyPlayPause    func(playing bool) error
	ApplyStop         func() error
	ApplyPlaylistJump func(delta int) error

	log            *logger.Logger
	bus            *ninja.DeviceBus
	controlChannel *channels.MediaControlChannel
	controlState   channels.MediaControlEvent
}

func (d *MediaPlayerDevice) SetControlState(state channels.MediaControlEvent) error {
	if d.controlChannel == nil {
		return fmt.Errorf("'media-control' channel has not been enabled. Call EnableControlChannel() first")
	}
	if state != d.controlState {
		d.controlState = state
		d.controlChannel.SendState(d.controlState)
	}
	return nil
}

func (d *MediaPlayerDevice) TogglePlay() error {

	if d.ApplyTogglePlay != nil {
		return d.ApplyTogglePlay()
	}

	switch d.controlState {
	case channels.MediaControlEventPlaying, channels.MediaControlEventBuffering, channels.MediaControlEventBusy:
		return d.Pause()
	default:
		return d.Play()
	}

}

func (d *MediaPlayerDevice) Play() error {
	return d.ApplyPlayPause(true)
}

func (d *MediaPlayerDevice) Pause() error {
	return d.ApplyPlayPause(false)
}

func (d *MediaPlayerDevice) Stop() error {
	return d.ApplyStop()
}

func (d *MediaPlayerDevice) Next() error {
	if d.ApplyPlaylistJump == nil {
		return fmt.Errorf("'Next' is not yet supported")
	}
	return d.ApplyPlaylistJump(1)
}

func (d *MediaPlayerDevice) Previous() error {
	if d.ApplyPlaylistJump == nil {
		return fmt.Errorf("'Previous' is not yet supported")
	}
	return d.ApplyPlaylistJump(-1)
}

func (d *MediaPlayerDevice) EnableControlChannel(supportedEvents []string) error {

	d.controlChannel = channels.NewMediaControlChannel(d)

	var supportedMethods []string

	if d.ApplyTogglePlay != nil {
		supportedMethods = append(supportedMethods, "togglePlay")
	}

	if d.ApplyPlayPause != nil {
		supportedMethods = append(supportedMethods, "play", "pause")

		if d.ApplyTogglePlay == nil {
			supportedMethods = append(supportedMethods, "togglePlay")
		}
	}

	if d.ApplyPlaylistJump != nil {
		supportedMethods = append(supportedMethods, "next", "previous")
	}

	if d.ApplyStop != nil {
		supportedMethods = append(supportedMethods, "stop")
	}

	err := d.bus.AddChannelWithSupported(d.controlChannel, "control", "media-control", &supportedMethods, &supportedEvents)
	if err != nil {
		return fmt.Errorf("Failed to create media-control channel: %s", err)
	}

	return nil
}

func CreateMediaPlayerDevice(name string, bus *ninja.DeviceBus) (*MediaPlayerDevice, error) {

	player := &MediaPlayerDevice{
		bus: bus,
		log: logger.GetLogger("MediaPlayerDevice - " + name),
	}

	player.log.Infof("Created")

	return player, nil
}
<|endoftext|>


<commit_before>package main

import (
	commander "code.google.com/p/go-commander"

	"log"
)

var Done *commander.Command = &commander.Command{
	UsageLine: "done",
	Short:     "mark current task as done",
	Long:      `mark the current task (from "next") as done. If you're not actually *done* with this task, use "delay"`,
	Run: func(cmd *commander.Command, args []string) {
		log.Printf("done: %+v\n", args)
	},
}
<commit_msg>finish done<commit_after>package main

import (
	commander "code.google.com/p/go-commander"
	"fmt"
	"github.com/BrianHicks/finch"

	"log"
)

func MarkDone(tdb *finch.TaskDB, args []string) (*finch.Task, error) {
	task, err := tdb.GetNextSelected()
	if err != nil {
		return task, err
	}

	task.Attrs[finch.TagSelected] = false
	task.Attrs[finch.TagPending] = false

	// TODO: callbacks to other programs here?

	err = tdb.PutTasks(task)
	if err != nil {
		return task, err
	}

	return task, nil
}

var Done *commander.Command = &commander.Command{
	UsageLine: "done",
	Short:     "mark current task as done",
	Long:      `mark the current task (from "next") as done. If you're not actually *done* with this task, use "delay"`,
	Run: func(cmd *commander.Command, args []string) {
		tdb, err := getTaskDB()
		defer tdb.Close()
		if err != nil {
			log.Fatalf("Error opening Task database: %s\n", err)
		}

		task, err := MarkDone(tdb, args)
		if err != nil {
			log.Fatalf("Error marking task done: %s\n", err)
		}

		fmt.Printf("Added \"%s\"\n", task.Description)
	},
}
<|endoftext|>


<commit_before>package Server

import (
	//"fmt"
	"log"
	//"runtime"
	//"time"
)

/**
 * I will made use of BoltDB as cache backend. The cache will store information
 * of the engine on the disk.
 */
type CacheManager struct {

	/**
	 * Contain the item
	 */
	entities map[string]Entity

	/**
	 * Channel used to append entity inside the entity map
	 */
	inputEntityChannel chan Entity

	/**
	* Channel used to output entity
	 */
	outputEntityChannel chan struct {
		// The uuid of the entity
		entityUuid string
		// The output channel
		entityOutputChannel chan Entity
	}

	/**
	 * The channel used to remove entities
	 */
	removeEntityChannel chan string

	// stop processing when that variable are set to true...
	abortedByEnvironment chan bool
}

var cacheManager *CacheManager

func (this *Server) GetCacheManager() *CacheManager {
	if cacheManager == nil {
		cacheManager = newCacheManager()
	}
	return cacheManager
}

/**
 * The cacheManager manages the memory and the lifetime of entities.
 */
func newCacheManager() *CacheManager {
	cacheManager := new(CacheManager)

	// The maximum size in memory allowed to the server.
	cacheManager.entities = make(map[string]Entity, 0)

	return cacheManager
}

////////////////////////////////////////////////////////////////////////////////
// Service functions
////////////////////////////////////////////////////////////////////////////////

/**
 * Intilialization of the cacheManager
 */
func (this *CacheManager) initialize() {

	log.Println("--> Initialize CacheManager")
	GetServer().GetConfigurationManager().setServiceConfiguration(this.getId(), -1)
	this.inputEntityChannel = make(chan Entity)
	this.outputEntityChannel = make(chan struct {
		entityUuid          string
		entityOutputChannel chan Entity
	})

	this.removeEntityChannel = make(chan string)
	this.abortedByEnvironment = make(chan bool)
}

func (this *CacheManager) start() {
	log.Println("--> Start CacheManager")
	go this.run()
}

func (this *CacheManager) getId() string {
	return "CacheManager"
}

func (this *CacheManager) stop() {
	log.Println("--> Stop CacheManager")

	// Free the cache
	this.abortedByEnvironment <- true
}

/**
 * Processing message from outside threads
 */
func (this *CacheManager) run() {
	for {
		select {

		case inputEntity := <-this.inputEntityChannel:
			// Append entity to the database.
			if inputEntity.GetTypeName() != "CargoEntities.Error" {
				this.set(inputEntity)
				log.Println("------> append entity: ", inputEntity.GetUuid())
			}

		case outputEntity := <-this.outputEntityChannel:
			outputEntity_ := this.get(outputEntity.entityUuid)
			outputEntity.entityOutputChannel <- outputEntity_

		case entityUuidToRemove := <-this.removeEntityChannel:
			// The entity to remove.
			this.remove(entityUuidToRemove)

		case done := <-this.abortedByEnvironment:
			if done {
				return
			}
		}
	}
}

/**
 * Gets an entity with a given uuid from the entitiesMap
 */
func (this *CacheManager) set(entity Entity) {

	this.entities[entity.GetUuid()] = entity

}

/**
 * Gets an entity with a given uuid from the entitiesMap
 */
func (this *CacheManager) get(uuid string) Entity {
	return this.entities[uuid]
}

/**
 * Gets an entity with a given uuid from the entitiesMap
 */
func (this *CacheManager) remove(uuid string) {
	delete(this.entities, uuid)
}

/**
 * Gets an entity with a given uuid from the entitiesMap
 */
func (this *CacheManager) getEntity(uuid string) Entity {
	outputInfo := new(struct {
		entityUuid          string
		entityOutputChannel chan Entity
	})

	outputInfo.entityOutputChannel = make(chan Entity)
	outputInfo.entityUuid = uuid
	this.outputEntityChannel <- *outputInfo
	entity := <-outputInfo.entityOutputChannel

	defer close(outputInfo.entityOutputChannel)
	return entity
}

/**
 * Determine if the entity exists in the map.
 */
func (this *CacheManager) contains(uuid string) (Entity, bool) {

	entity := this.getEntity(uuid)
	if entity != nil {
		return entity, true
	}

	return nil, false
}

/**
 * Remove an existing entity with a given uuid.
 */
func (this *CacheManager) removeEntity(uuid string) {
	this.removeEntityChannel <- uuid
}

/**
 * Insert entity if it doesn't already exist. Otherwise replace current entity.
 */
func (this *CacheManager) setEntity(entity Entity) {
	this.inputEntityChannel <- entity
}
<commit_msg>Complete the Cache manager. Simple and functional. GC take large amount of memory, but all work correctly.<commit_after>package Server

import (
	"log"
	"time"
)

/**
 * The cache manager is simply a map of Entity accessible via channel and where
 * entity has a limited lifespan of 10 minutes. It main purpose is to back data
 * the time of initislisation, and also for multiple access. The real db is the
 * KV store or the SQL store.
 */
type CacheManager struct {

	/**
	 * Contain the item
	 */
	entities map[string]Entity

	/**
	 * Channel used to append entity inside the entity map
	 */
	inputEntityChannel chan Entity

	/**
	* Channel used to output entity
	 */
	outputEntityChannel chan struct {
		// The uuid of the entity
		entityUuid string
		// The output channel
		entityOutputChannel chan Entity
	}

	/**
	 * The channel used to remove entities
	 */
	removeEntityChannel chan string

	// stop processing when that variable are set to true...
	abortedByEnvironment chan bool
}

var cacheManager *CacheManager

func (this *Server) GetCacheManager() *CacheManager {
	if cacheManager == nil {
		cacheManager = newCacheManager()
	}
	return cacheManager
}

/**
 * The cacheManager manages the memory and the lifetime of entities.
 */
func newCacheManager() *CacheManager {
	cacheManager := new(CacheManager)

	// The maximum size in memory allowed to the server.
	cacheManager.entities = make(map[string]Entity, 0)

	return cacheManager
}

////////////////////////////////////////////////////////////////////////////////
// Service functions
////////////////////////////////////////////////////////////////////////////////

/**
 * Intilialization of the cacheManager
 */
func (this *CacheManager) initialize() {

	log.Println("--> Initialize CacheManager")
	GetServer().GetConfigurationManager().setServiceConfiguration(this.getId(), -1)
	this.inputEntityChannel = make(chan Entity)
	this.outputEntityChannel = make(chan struct {
		entityUuid          string
		entityOutputChannel chan Entity
	})

	this.removeEntityChannel = make(chan string)
	this.abortedByEnvironment = make(chan bool)
}

func (this *CacheManager) start() {
	log.Println("--> Start CacheManager")
	go this.run()
}

func (this *CacheManager) getId() string {
	return "CacheManager"
}

func (this *CacheManager) stop() {
	log.Println("--> Stop CacheManager")

	// Free the cache
	this.abortedByEnvironment <- true
}

/**
 * Processing message from outside threads
 */
func (this *CacheManager) run() {
	for {
		select {

		case inputEntity := <-this.inputEntityChannel:
			// Append entity to the database.
			if inputEntity.GetTypeName() != "CargoEntities.Error" {
				this.set(inputEntity)
				//log.Println("------> append entity: ", inputEntity.GetUuid())
			}

		case outputEntity := <-this.outputEntityChannel:
			outputEntity_ := this.get(outputEntity.entityUuid)
			outputEntity.entityOutputChannel <- outputEntity_

		case entityUuidToRemove := <-this.removeEntityChannel:
			// The entity to remove.
			this.remove(entityUuidToRemove)

		case done := <-this.abortedByEnvironment:
			if done {
				return
			}
		}
	}
}

/**
 * Gets an entity with a given uuid from the entitiesMap
 */
func (this *CacheManager) set(entity Entity) {

	this.entities[entity.GetUuid()] = entity

	go func(uuid string, lifespan time.Duration, removeChannel chan string) {
		timer := time.NewTimer(lifespan * time.Minute)
		<-timer.C
		removeChannel <- uuid
	}(entity.GetUuid(), 10, this.removeEntityChannel)

}

/**
 * Gets an entity with a given uuid from the entitiesMap
 */
func (this *CacheManager) get(uuid string) Entity {
	return this.entities[uuid]
}

/**
 * Gets an entity with a given uuid from the entitiesMap
 */
func (this *CacheManager) remove(uuid string) {
	delete(this.entities, uuid)
}

/**
 * Gets an entity with a given uuid from the entitiesMap
 */
func (this *CacheManager) getEntity(uuid string) Entity {
	outputInfo := new(struct {
		entityUuid          string
		entityOutputChannel chan Entity
	})

	outputInfo.entityOutputChannel = make(chan Entity)
	outputInfo.entityUuid = uuid
	this.outputEntityChannel <- *outputInfo
	entity := <-outputInfo.entityOutputChannel

	defer close(outputInfo.entityOutputChannel)
	return entity
}

/**
 * Determine if the entity exists in the map.
 */
func (this *CacheManager) contains(uuid string) (Entity, bool) {

	entity := this.getEntity(uuid)
	if entity != nil {
		return entity, true
	}

	return nil, false
}

/**
 * Remove an existing entity with a given uuid.
 */
func (this *CacheManager) removeEntity(uuid string) {
	this.removeEntityChannel <- uuid
}

/**
 * Insert entity if it doesn't already exist. Otherwise replace current entity.
 */
func (this *CacheManager) setEntity(entity Entity) {
	this.inputEntityChannel <- entity
}
<|endoftext|>