<commit_before>package trackello

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/VojtechVitek/go-trello"
	"github.com/klauern/trackello/rest"
	"github.com/spf13/viper"
)

type trelloActivity struct {
	cardsWorkedOn map[string]time.Time
	oldestDate    time.Time
	boardActions  map[string][]trello.Action
}

// Trackello represents the connection to Trello for a specific user.
type Trackello struct {
	token  string
	appKey string
	client trello.Client
}

// Card is both the Trello Card + other stats on the actions in it.
type Card struct {
	card  *trello.Card
	stats statistics
}

// List is both the Trello List + other stats on the actions in it.
type List struct {
	name  string
	cards []Card
	stats statistics
}

// NewTrackello will create a `Trackello` type using your preferences application token and appkey.
func NewTrackello() (*Trackello, error) {
	token := viper.GetString("token")
	appKey := viper.GetString("appkey")

	// New Trello Client
	tr, err := trello.NewAuthClient(appKey, &token)
	if err != nil {
		log.Fatal(err)
		return nil, err
	}

	return &Trackello{
		token:  token,
		appKey: appKey,
		client: *tr,
	}, nil
}

// PrimaryBoard will return a board based on your settings for a primary board.
func (t *Trackello) PrimaryBoard() (trello.Board, error) {
	board, err := t.client.Board(viper.GetString("board"))
	if err != nil {
		log.Fatal(err)
		return *board, err
	}
	return *board, nil
}

// BoardWithId will return the Trello Board given it's ID string.
func (t *Trackello) BoardWithId(id string) (trello.Board, error) {
	board, err := t.client.Board(id)
	if err != nil {
		log.Fatal(err)
		return *board, err
	}
	return *board, nil
}

// Boards will list all of the boards for the authenticated user (i.e. 'me').
func (t *Trackello) Boards() ([]trello.Board, error) {
	member, err := t.client.Member("me")
	if err != nil {
		return make([]trello.Board, 0), err
	}
	boards, err := member.Boards()
	return boards, err
}

// Track pulls all the latest activity from your Trello board given you've set the token, appkey, and preferred board
// ID to use.
func Track(id string) {
	t, err := NewTrackello()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	board, err := t.Board(id)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	args := rest.CreateArgsForBoardActions()
	actions, err := board.Actions(args...)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	allActivity := newTrelloActivity()
	t.mapActionsAndDates(actions, allActivity)
	fmt.Printf("Listing cards worked on \"%s\" for from %s to now:\n", board.Name, allActivity.oldestDate.Format(time.ANSIC))
	printBoardActions(actions, allActivity)
}

func newTrelloActivity() *trelloActivity {
	return &trelloActivity{
		cardsWorkedOn: make(map[string]time.Time),
		oldestDate:    time.Now(),
		boardActions:  make(map[string][]trello.Action),
	}
}

func (t *Trackello) mapActionsAndDates(actions []trello.Action, activities *trelloActivity) {
	for _, action := range actions {
		switch activities.boardActions[action.Data.Card.Name] {
		case nil:
			activities.boardActions[action.Data.Card.Name] = []trello.Action{action}
		default:
			activities.boardActions[action.Data.Card.Name] = append(activities.boardActions[action.Data.Card.Name], action)
		}
		if action.Data.List.Name == "" {
			action.Data.List.Name = t.getListForAction(action)
		}
	}
}

func (t *Trackello) getListForAction(a trello.Action) string {
	if len(a.Data.List.Id) > 0 {
		if list, err := t.client.List(a.Data.List.Id); err == nil {
			return list.Name
		}
	}
	return ""
	//card, err := t.client.Card(a.Data.Card.Id)
	//if err != nil {
	//	return ""
	//}
	//list, err := t.client.List(card.IdList)
	//if err != nil {
	//	return ""
	//}
	//return list.Name
}

func (t *Trackello) getCardForAction(a trello.Action) (*trello.Card, error) {
	fmt.Printf("%+v\n", a)
	//fmt.Printf("action ID is %s\n", a.Data.Card.Id)
	return t.client.Card(a.Data.Card.Id)
}

func printBoardActions(actions []trello.Action, activities *trelloActivity) {
	listActions := make(map[string][]string)
	for k, v := range activities.boardActions {
		for _, vv := range v {
			switch {
			case listActions[vv.Data.List.Name] == nil:
				listActions[vv.Data.List.Name] = []string{k}
			default:
				listActions[vv.Data.List.Name] = append(listActions[vv.Data.List.Name], k)
			}
		}
	}
	//for k, v := range listActions {
	//	if len(k) > 0 {
	//		printList(k, v)
	//	}
	//}
}

func (t *Trackello) MapBoardActions(actions []trello.Action) ([]List, error) {
	listCards := make(map[string]List)
	for _, v := range actions {
		card, err := t.getCardForAction(v)
		if err != nil {
			fmt.Printf("error in getting Cards for Action")
			return nil, err
		}
		list, err := t.client.List(card.IdList)
		if err != nil {
			return nil, err
		}
		lc, ok := listCards[list.Name]
		if !ok {
			listCards[list.Name] = List{
				name:  list.Name,
				cards: []Card{{card:card}},
			}
		} else {
			lc.cards = append(lc.cards, Card{card:card})
		}
	}
	list := make([]List, len(listCards))
	for _, v := range listCards {
		list = append(list, v)
	}
	return list, nil
}

func (l *List) Print() {
	fmt.Printf("%s\n", l.name)
	for _, card := range l.cards {
		fmt.Printf("  * %s\n", card.card.Name)
	}
}

// Board will pull the Trello Board with an ID.  If id is "", it will pull it from the PrimaryBoard configuration setting.
func (t *Trackello) Board(id string) (trello.Board, error) {
	if id == "" {
		return t.PrimaryBoard()
	}
	return t.BoardWithId(id)
}

func BoardActions(id string) ([]trello.Action, error) {
	t, err := NewTrackello()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	board, err := t.Board(id)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	args := rest.CreateArgsForBoardActions()
	actions, err := board.Actions(args...)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
	return actions, err
}
<commit_msg>don't look up card for action if card id is empty<commit_after>package trackello

import (
	"fmt"
	"log"
	"os"
	"time"

	"github.com/VojtechVitek/go-trello"
	"github.com/klauern/trackello/rest"
	"github.com/spf13/viper"
)

type trelloActivity struct {
	cardsWorkedOn map[string]time.Time
	oldestDate    time.Time
	boardActions  map[string][]trello.Action
}

// Trackello represents the connection to Trello for a specific user.
type Trackello struct {
	token  string
	appKey string
	client trello.Client
}

// Card is both the Trello Card + other stats on the actions in it.
type Card struct {
	card  *trello.Card
	stats statistics
}

// List is both the Trello List + other stats on the actions in it.
type List struct {
	name  string
	cards []Card
	stats statistics
}

// NewTrackello will create a `Trackello` type using your preferences application token and appkey.
func NewTrackello() (*Trackello, error) {
	token := viper.GetString("token")
	appKey := viper.GetString("appkey")

	// New Trello Client
	tr, err := trello.NewAuthClient(appKey, &token)
	if err != nil {
		log.Fatal(err)
		return nil, err
	}

	return &Trackello{
		token:  token,
		appKey: appKey,
		client: *tr,
	}, nil
}

// PrimaryBoard will return a board based on your settings for a primary board.
func (t *Trackello) PrimaryBoard() (trello.Board, error) {
	board, err := t.client.Board(viper.GetString("board"))
	if err != nil {
		log.Fatal(err)
		return *board, err
	}
	return *board, nil
}

// BoardWithId will return the Trello Board given it's ID string.
func (t *Trackello) BoardWithId(id string) (trello.Board, error) {
	board, err := t.client.Board(id)
	if err != nil {
		log.Fatal(err)
		return *board, err
	}
	return *board, nil
}

// Boards will list all of the boards for the authenticated user (i.e. 'me').
func (t *Trackello) Boards() ([]trello.Board, error) {
	member, err := t.client.Member("me")
	if err != nil {
		return make([]trello.Board, 0), err
	}
	boards, err := member.Boards()
	return boards, err
}

// Track pulls all the latest activity from your Trello board given you've set the token, appkey, and preferred board
// ID to use.
func Track(id string) {
	t, err := NewTrackello()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	board, err := t.Board(id)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	args := rest.CreateArgsForBoardActions()
	actions, err := board.Actions(args...)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	allActivity := newTrelloActivity()
	t.mapActionsAndDates(actions, allActivity)
	fmt.Printf("Listing cards worked on \"%s\" for from %s to now:\n", board.Name, allActivity.oldestDate.Format(time.ANSIC))
	printBoardActions(actions, allActivity)
}

func newTrelloActivity() *trelloActivity {
	return &trelloActivity{
		cardsWorkedOn: make(map[string]time.Time),
		oldestDate:    time.Now(),
		boardActions:  make(map[string][]trello.Action),
	}
}

func (t *Trackello) mapActionsAndDates(actions []trello.Action, activities *trelloActivity) {
	for _, action := range actions {
		switch activities.boardActions[action.Data.Card.Name] {
		case nil:
			activities.boardActions[action.Data.Card.Name] = []trello.Action{action}
		default:
			activities.boardActions[action.Data.Card.Name] = append(activities.boardActions[action.Data.Card.Name], action)
		}
		if action.Data.List.Name == "" {
			action.Data.List.Name = t.getListForAction(action)
		}
	}
}

func (t *Trackello) getListForAction(a trello.Action) string {
	if len(a.Data.List.Id) > 0 {
		if list, err := t.client.List(a.Data.List.Id); err == nil {
			return list.Name
		}
	}
	return ""
	//card, err := t.client.Card(a.Data.Card.Id)
	//if err != nil {
	//	return ""
	//}
	//list, err := t.client.List(card.IdList)
	//if err != nil {
	//	return ""
	//}
	//return list.Name
}

func (t *Trackello) getCardForAction(a trello.Action) (*trello.Card, error) {
	fmt.Printf("%+v\n", a)
	//fmt.Printf("action ID is %s\n", a.Data.Card.Id)
	return t.client.Card(a.Data.Card.Id)
}

func printBoardActions(actions []trello.Action, activities *trelloActivity) {
	listActions := make(map[string][]string)
	for k, v := range activities.boardActions {
		for _, vv := range v {
			switch {
			case listActions[vv.Data.List.Name] == nil:
				listActions[vv.Data.List.Name] = []string{k}
			default:
				listActions[vv.Data.List.Name] = append(listActions[vv.Data.List.Name], k)
			}
		}
	}
}

func (t *Trackello) MapBoardActions(actions []trello.Action) ([]List, error) {
	listCards := make(map[string]List)
	for _, v := range actions {
		if len(v.Data.Card.Id) > 0 {
			card, err := t.getCardForAction(v)
			if err != nil {
				fmt.Printf("error in getting Cards for Action")
				return nil, err
			}
			list, err := t.client.List(card.IdList)
			if err != nil {
				return nil, err
			}
			lc, ok := listCards[list.Name]
			if !ok {
				listCards[list.Name] = List{
					name:  list.Name,
					cards: []Card{{card: card}},
				}
			} else {
				lc.cards = append(lc.cards, Card{card: card})
			}
		}
	}
	list := make([]List, len(listCards))
	for _, v := range listCards {
		list = append(list, v)
	}
	return list, nil
}

func (l *List) Print() {
	fmt.Printf("%s\n", l.name)
	for _, card := range l.cards {
		fmt.Printf("  * %s\n", card.card.Name)
	}
}

// Board will pull the Trello Board with an ID.  If id is "", it will pull it from the PrimaryBoard configuration setting.
func (t *Trackello) Board(id string) (trello.Board, error) {
	if id == "" {
		return t.PrimaryBoard()
	}
	return t.BoardWithId(id)
}

func BoardActions(id string) ([]trello.Action, error) {
	t, err := NewTrackello()
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	board, err := t.Board(id)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}

	args := rest.CreateArgsForBoardActions()
	actions, err := board.Actions(args...)
	if err != nil {
		log.Fatal(err)
		os.Exit(1)
	}
	return actions, err
}
<|endoftext|>


<commit_before>package tros

import (
	"reflect"
	"testing"
)

func TestSort(t *testing.T) {
	type s struct {
		A, B string
	}
	for _, c := range []struct {
		ss  []s
		fn  string
		exp []s
	}{{
		[]s{{"a", "c"}, {"b", "b"}, {"c", "a"}},
		"B",
		[]s{{"c", "a"}, {"b", "b"}, {"a", "c"}},
	}, {
		[]s{{"c", "a"}, {"b", "b"}, {"a", "c"}},
		"A",
		[]s{{"a", "c"}, {"b", "b"}, {"c", "a"}},
	}, {
		[]s{{"a", "c"}, {"b", "b"}, {"c", "a"}},
		"A",
		[]s{{"a", "c"}, {"b", "b"}, {"c", "a"}},
	}} {
		if err := Sort(c.ss, c.fn); err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if !reflect.DeepEqual(c.ss, c.exp) {
			t.Errorf("unexpected result\n got %v\nwant %v", c.ss, c.exp)
		}
	}
}

func TestSort_Bool(t *testing.T) {
	type e struct {
		A bool
	}
	l := []e{e{true}, e{true}, e{false}, e{true}, e{false}}
	if err := Sort(l, "A"); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if got, want := l, []e{e{false}, e{false}, e{true}, e{true}, e{true}}; !reflect.DeepEqual(got, want) {
		t.Errorf("unexpected result, got %v want %v", got, want)
	}
}

func TestSort_Struct(t *testing.T) {
	for _, c := range []struct {
		s, exp []container
	}{{
		[]container{
			container{lenLesser{"aaa"}},
			container{lenLesser{"a"}},
			container{lenLesser{"aaaaa"}},
			container{lenLesser{"aa"}},
			container{lenLesser{"a"}},
		},
		[]container{
			container{lenLesser{"a"}},
			container{lenLesser{"a"}},
			container{lenLesser{"aa"}},
			container{lenLesser{"aaa"}},
			container{lenLesser{"aaaaa"}},
		},
	}} {
		if err := Sort(c.s, "A"); err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if !reflect.DeepEqual(c.s, c.exp) {
			t.Errorf("unexpected result\n got %v\nwant %v", c.s, c.exp)
		}
	}
}

type container struct {
	A lenLesser
}

// Implements Less by comparing lengths, resulting in strings sorted by length
// but nothing else meaningful.
type lenLesser struct {
	val string
}

func (l lenLesser) Less(o Lesser) bool {
	ol, ok := o.(lenLesser)
	if !ok {
		panic("other is not lenLesser")
	}
	return len(l.val) < len(ol.val)
}
<commit_msg>improve tests by making sure the values are sorted by length and not by string comparison<commit_after>package tros

import (
	"reflect"
	"testing"
)

func TestSort(t *testing.T) {
	type s struct {
		A, B string
	}
	for _, c := range []struct {
		ss  []s
		fn  string
		exp []s
	}{{
		[]s{{"a", "c"}, {"b", "b"}, {"c", "a"}},
		"B",
		[]s{{"c", "a"}, {"b", "b"}, {"a", "c"}},
	}, {
		[]s{{"c", "a"}, {"b", "b"}, {"a", "c"}},
		"A",
		[]s{{"a", "c"}, {"b", "b"}, {"c", "a"}},
	}, {
		[]s{{"a", "c"}, {"b", "b"}, {"c", "a"}},
		"A",
		[]s{{"a", "c"}, {"b", "b"}, {"c", "a"}},
	}} {
		if err := Sort(c.ss, c.fn); err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if !reflect.DeepEqual(c.ss, c.exp) {
			t.Errorf("unexpected result\n got %v\nwant %v", c.ss, c.exp)
		}
	}
}

func TestSort_Bool(t *testing.T) {
	type e struct {
		A bool
	}
	l := []e{e{true}, e{true}, e{false}, e{true}, e{false}}
	if err := Sort(l, "A"); err != nil {
		t.Errorf("unexpected error: %v", err)
	}
	if got, want := l, []e{e{false}, e{false}, e{true}, e{true}, e{true}}; !reflect.DeepEqual(got, want) {
		t.Errorf("unexpected result, got %v want %v", got, want)
	}
}

func TestSort_Struct(t *testing.T) {
	for _, c := range []struct {
		s, exp []container
	}{{
		[]container{
			container{lenLesser{"xxx"}},
			container{lenLesser{"z"}},
			container{lenLesser{"wwwww"}},
			container{lenLesser{"yy"}},
			container{lenLesser{"z"}},
		},
		[]container{
			container{lenLesser{"z"}},
			container{lenLesser{"z"}},
			container{lenLesser{"yy"}},
			container{lenLesser{"xxx"}},
			container{lenLesser{"wwwww"}},
		},
	}} {
		if err := Sort(c.s, "A"); err != nil {
			t.Errorf("unexpected error: %v", err)
		}
		if !reflect.DeepEqual(c.s, c.exp) {
			t.Errorf("unexpected result\n got %v\nwant %v", c.s, c.exp)
		}
	}
}

type container struct {
	A lenLesser
}

// Implements Less by comparing lengths, resulting in strings sorted by length
// but nothing else meaningful.
type lenLesser struct {
	val string
}

func (l lenLesser) Less(o Lesser) bool {
	ol, ok := o.(lenLesser)
	if !ok {
		panic("other is not lenLesser")
	}
	return len(l.val) < len(ol.val)
}
<|endoftext|>


<commit_before>package mouryou

import (
	"../apache"
	"time"
)

type virtualMachine struct {
	Name string
	Host string
	HV   *hypervisor
}

func (vm virtualMachine) operatingRatio() float64 {
	board, err := apache.Scoreboard(vm.Host)

	if err != nil {
		switch err.Error() {
		case "apache: no response":
			return 1.0
		case "apache: request timeout":
			return 1.0
		}
	}

	return apache.OperatingRatio(board)
}

func (vm virtualMachine) create(sleep time.Duration) {
	conn, err := vm.HV.connect()
	checkError(err)
	defer conn.CloseConnection()

	dom, err := conn.LookupDomainByName(vm.Name)
	checkError(err)

	dom.Create()
	time.Sleep(sleep * time.Second)

	o := readOperating()
	writeOperating(o - 1)

	powerCh <- "created"
}

func (vm virtualMachine) shutdown(sleep time.Duration) {
	conn, err := vm.HV.connect()
	checkError(err)
	defer conn.CloseConnection()

	dom, err := conn.LookupDomainByName(vm.Name)
	checkError(err)

	time.Sleep(sleep * time.Second)
	dom.Shutdown()

	o := readOperating()
	writeOperating(o - 1)
}
<commit_msg>起動・停止の再試行を実装 / 起動時のHTTP確認を実装<commit_after>package mouryou

import (
	"../apache"
	"time"
)

type virtualMachine struct {
	Name string
	Host string
	HV   *hypervisor
}

func (vm virtualMachine) operatingRatio() float64 {
	board, err := apache.Scoreboard(vm.Host)

	if err != nil {
		switch err.Error() {
		case "apache: no response":
			return 1.0
		case "apache: request timeout":
			return 1.0
		}
	}

	return apache.OperatingRatio(board)
}

func (vm virtualMachine) create(sleep time.Duration) {
	conn, err := vm.HV.connect()
	checkError(err)
	defer conn.CloseConnection()

	dom, err := conn.LookupDomainByName(vm.Name)
	checkError(err)

	if sleep > 0 {
		for {
			err = dom.Create()
			if err == nil {
				break
			} else {
				time.Sleep(time.Second)
			}
		}
	}
	time.Sleep(sleep * time.Second)

	for {
		_, err := apache.Scoreboard(vm.Host)
		if err == nil {
			break
		} else {
			time.Sleep(time.Second)
		}
	}

	o := readOperating()
	writeOperating(o - 1)

	powerCh <- "created"
}

func (vm virtualMachine) shutdown(sleep time.Duration) {
	conn, err := vm.HV.connect()
	checkError(err)
	defer conn.CloseConnection()

	dom, err := conn.LookupDomainByName(vm.Name)
	checkError(err)

	time.Sleep(sleep * time.Second)
	if sleep > 0 {
		for {
			err = dom.Shutdown()
			if err == nil {
				break
			} else {
				time.Sleep(time.Second)
			}
		}
	}

	o := readOperating()
	writeOperating(o - 1)
}
<|endoftext|>


<commit_before>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package time_test

import (
	"errors"
	"fmt"
	"runtime"
	"sort"
	"sync/atomic"
	"testing"
	. "time"
)

func TestSleep(t *testing.T) {
	const delay = 100 * Millisecond
	go func() {
		Sleep(delay / 2)
		Interrupt()
	}()
	start := Now()
	Sleep(delay)
	duration := Now().Sub(start)
	if duration < delay {
		t.Fatalf("Sleep(%s) slept for only %s", delay, duration)
	}
}

// Test the basic function calling behavior. Correct queueing
// behavior is tested elsewhere, since After and AfterFunc share
// the same code.
func TestAfterFunc(t *testing.T) {
	i := 10
	c := make(chan bool)
	var f func()
	f = func() {
		i--
		if i >= 0 {
			AfterFunc(0, f)
			Sleep(1 * Second)
		} else {
			c <- true
		}
	}

	AfterFunc(0, f)
	<-c
}

func TestAfterStress(t *testing.T) {
	stop := uint32(0)
	go func() {
		for atomic.LoadUint32(&stop) == 0 {
			runtime.GC()
			// Yield so that the OS can wake up the timer thread,
			// so that it can generate channel sends for the main goroutine,
			// which will eventually set stop = 1 for us.
			Sleep(Nanosecond)
		}
	}()
	c := Tick(1)
	for i := 0; i < 100; i++ {
		<-c
	}
	atomic.StoreUint32(&stop, 1)
}

func BenchmarkAfterFunc(b *testing.B) {
	i := b.N
	c := make(chan bool)
	var f func()
	f = func() {
		i--
		if i >= 0 {
			AfterFunc(0, f)
		} else {
			c <- true
		}
	}

	AfterFunc(0, f)
	<-c
}

func BenchmarkAfter(b *testing.B) {
	for i := 0; i < b.N; i++ {
		<-After(1)
	}
}

func BenchmarkStop(b *testing.B) {
	for i := 0; i < b.N; i++ {
		NewTimer(1 * Second).Stop()
	}
}

func TestAfter(t *testing.T) {
	const delay = 100 * Millisecond
	start := Now()
	end := <-After(delay)
	if duration := Now().Sub(start); duration < delay {
		t.Fatalf("After(%s) slept for only %d ns", delay, duration)
	}
	if min := start.Add(delay); end.Before(min) {
		t.Fatalf("After(%s) expect >= %s, got %s", delay, min, end)
	}
}

func TestAfterTick(t *testing.T) {
	const Count = 10
	Delta := 100 * Millisecond
	if testing.Short() {
		Delta = 10 * Millisecond
	}
	t0 := Now()
	for i := 0; i < Count; i++ {
		<-After(Delta)
	}
	t1 := Now()
	d := t1.Sub(t0)
	target := Delta * Count
	if d < target*9/10 {
		t.Fatalf("%d ticks of %s too fast: took %s, expected %s", Count, Delta, d, target)
	}
	if !testing.Short() && d > target*30/10 {
		t.Fatalf("%d ticks of %s too slow: took %s, expected %s", Count, Delta, d, target)
	}
}

func TestAfterStop(t *testing.T) {
	AfterFunc(100*Millisecond, func() {})
	t0 := NewTimer(50 * Millisecond)
	c1 := make(chan bool, 1)
	t1 := AfterFunc(150*Millisecond, func() { c1 <- true })
	c2 := After(200 * Millisecond)
	if !t0.Stop() {
		t.Fatalf("failed to stop event 0")
	}
	if !t1.Stop() {
		t.Fatalf("failed to stop event 1")
	}
	<-c2
	select {
	case <-t0.C:
		t.Fatalf("event 0 was not stopped")
	case <-c1:
		t.Fatalf("event 1 was not stopped")
	default:
	}
	if t1.Stop() {
		t.Fatalf("Stop returned true twice")
	}
}

func TestAfterQueuing(t *testing.T) {
	// This test flakes out on some systems,
	// so we'll try it a few times before declaring it a failure.
	const attempts = 3
	err := errors.New("!=nil")
	for i := 0; i < attempts && err != nil; i++ {
		if err = testAfterQueuing(t); err != nil {
			t.Logf("attempt %v failed: %v", i, err)
		}
	}
	if err != nil {
		t.Fatal(err)
	}
}

var slots = []int{5, 3, 6, 6, 6, 1, 1, 2, 7, 9, 4, 8, 0}

type afterResult struct {
	slot int
	t    Time
}

func await(slot int, result chan<- afterResult, ac <-chan Time) {
	result <- afterResult{slot, <-ac}
}

func testAfterQueuing(t *testing.T) error {
	Delta := 100 * Millisecond
	if testing.Short() {
		Delta = 20 * Millisecond
	}
	// make the result channel buffered because we don't want
	// to depend on channel queueing semantics that might
	// possibly change in the future.
	result := make(chan afterResult, len(slots))

	t0 := Now()
	for _, slot := range slots {
		go await(slot, result, After(Duration(slot)*Delta))
	}
	sort.Ints(slots)
	for _, slot := range slots {
		r := <-result
		if r.slot != slot {
			return fmt.Errorf("after slot %d, expected %d", r.slot, slot)
		}
		dt := r.t.Sub(t0)
		target := Duration(slot) * Delta
		if dt < target-Delta/2 || dt > target+Delta*10 {
			return fmt.Errorf("After(%s) arrived at %s, expected [%s,%s]", target, dt, target-Delta/2, target+Delta*10)
		}
	}
	return nil
}

func TestTimerStopStress(t *testing.T) {
	if testing.Short() {
		return
	}
	for i := 0; i < 100; i++ {
		go func(i int) {
			timer := AfterFunc(2*Second, func() {
				t.Fatalf("timer %d was not stopped", i)
			})
			Sleep(1 * Second)
			timer.Stop()
		}(i)
	}
	Sleep(3 * Second)
}

func TestSleepZeroDeadlock(t *testing.T) {
	// Sleep(0) used to hang, the sequence of events was as follows.
	// Sleep(0) sets G's status to Gwaiting, but then immediately returns leaving the status.
	// Then the goroutine calls e.g. new and falls down into the scheduler due to pending GC.
	// After the GC nobody wakes up the goroutine from Gwaiting status.
	defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(4))
	c := make(chan bool)
	go func() {
		for i := 0; i < 100; i++ {
			runtime.GC()
		}
		c <- true
	}()
	for i := 0; i < 100; i++ {
		Sleep(0)
		tmp := make(chan bool, 1)
		tmp <- true
		<-tmp
	}
	<-c
}

func testReset(d Duration) error {
	t0 := NewTimer(2 * d)
	Sleep(d)
	if t0.Reset(3*d) != true {
		return errors.New("resetting unfired timer returned false")
	}
	Sleep(2 * d)
	select {
	case <-t0.C:
		return errors.New("timer fired early")
	default:
	}
	Sleep(2 * d)
	select {
	case <-t0.C:
	default:
		return errors.New("reset timer did not fire")
	}

	if t0.Reset(50*Millisecond) != false {
		return errors.New("resetting expired timer returned true")
	}
	return nil
}

func TestReset(t *testing.T) {
	// We try to run this test with increasingly larger multiples
	// until one works so slow, loaded hardware isn't as flaky,
	// but without slowing down fast machines unnecessarily.
	const unit = 25 * Millisecond
	tries := []Duration{
		1 * unit,
		3 * unit,
		7 * unit,
		15 * unit,
	}
	var err error
	for _, d := range tries {
		err = testReset(d)
		if err == nil {
			t.Logf("passed using duration %v", d)
			return
		}
	}
	t.Error(err)
}

// Test that sleeping for an interval so large it overflows does not
// result in a short sleep duration.
func TestOverflowSleep(t *testing.T) {
	const timeout = 25 * Millisecond
	const big = Duration(int64(1<<63 - 1))
	select {
	case <-After(big):
		t.Fatalf("big timeout fired")
	case <-After(timeout):
		// OK
	}
	const neg = Duration(-1 << 63)
	select {
	case <-After(neg):
		// OK
	case <-After(timeout):
		t.Fatalf("negative timeout didn't fire")
	}
}
<commit_msg>time: stop 1ns timer in test<commit_after>// Copyright 2009 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package time_test

import (
	"errors"
	"fmt"
	"runtime"
	"sort"
	"sync/atomic"
	"testing"
	. "time"
)

func TestSleep(t *testing.T) {
	const delay = 100 * Millisecond
	go func() {
		Sleep(delay / 2)
		Interrupt()
	}()
	start := Now()
	Sleep(delay)
	duration := Now().Sub(start)
	if duration < delay {
		t.Fatalf("Sleep(%s) slept for only %s", delay, duration)
	}
}

// Test the basic function calling behavior. Correct queueing
// behavior is tested elsewhere, since After and AfterFunc share
// the same code.
func TestAfterFunc(t *testing.T) {
	i := 10
	c := make(chan bool)
	var f func()
	f = func() {
		i--
		if i >= 0 {
			AfterFunc(0, f)
			Sleep(1 * Second)
		} else {
			c <- true
		}
	}

	AfterFunc(0, f)
	<-c
}

func TestAfterStress(t *testing.T) {
	stop := uint32(0)
	go func() {
		for atomic.LoadUint32(&stop) == 0 {
			runtime.GC()
			// Yield so that the OS can wake up the timer thread,
			// so that it can generate channel sends for the main goroutine,
			// which will eventually set stop = 1 for us.
			Sleep(Nanosecond)
		}
	}()
	ticker := NewTicker(1)
	for i := 0; i < 100; i++ {
		<-ticker.C
	}
	ticker.Stop()
	atomic.StoreUint32(&stop, 1)
}

func BenchmarkAfterFunc(b *testing.B) {
	i := b.N
	c := make(chan bool)
	var f func()
	f = func() {
		i--
		if i >= 0 {
			AfterFunc(0, f)
		} else {
			c <- true
		}
	}

	AfterFunc(0, f)
	<-c
}

func BenchmarkAfter(b *testing.B) {
	for i := 0; i < b.N; i++ {
		<-After(1)
	}
}

func BenchmarkStop(b *testing.B) {
	for i := 0; i < b.N; i++ {
		NewTimer(1 * Second).Stop()
	}
}

func TestAfter(t *testing.T) {
	const delay = 100 * Millisecond
	start := Now()
	end := <-After(delay)
	if duration := Now().Sub(start); duration < delay {
		t.Fatalf("After(%s) slept for only %d ns", delay, duration)
	}
	if min := start.Add(delay); end.Before(min) {
		t.Fatalf("After(%s) expect >= %s, got %s", delay, min, end)
	}
}

func TestAfterTick(t *testing.T) {
	const Count = 10
	Delta := 100 * Millisecond
	if testing.Short() {
		Delta = 10 * Millisecond
	}
	t0 := Now()
	for i := 0; i < Count; i++ {
		<-After(Delta)
	}
	t1 := Now()
	d := t1.Sub(t0)
	target := Delta * Count
	if d < target*9/10 {
		t.Fatalf("%d ticks of %s too fast: took %s, expected %s", Count, Delta, d, target)
	}
	if !testing.Short() && d > target*30/10 {
		t.Fatalf("%d ticks of %s too slow: took %s, expected %s", Count, Delta, d, target)
	}
}

func TestAfterStop(t *testing.T) {
	AfterFunc(100*Millisecond, func() {})
	t0 := NewTimer(50 * Millisecond)
	c1 := make(chan bool, 1)
	t1 := AfterFunc(150*Millisecond, func() { c1 <- true })
	c2 := After(200 * Millisecond)
	if !t0.Stop() {
		t.Fatalf("failed to stop event 0")
	}
	if !t1.Stop() {
		t.Fatalf("failed to stop event 1")
	}
	<-c2
	select {
	case <-t0.C:
		t.Fatalf("event 0 was not stopped")
	case <-c1:
		t.Fatalf("event 1 was not stopped")
	default:
	}
	if t1.Stop() {
		t.Fatalf("Stop returned true twice")
	}
}

func TestAfterQueuing(t *testing.T) {
	// This test flakes out on some systems,
	// so we'll try it a few times before declaring it a failure.
	const attempts = 3
	err := errors.New("!=nil")
	for i := 0; i < attempts && err != nil; i++ {
		if err = testAfterQueuing(t); err != nil {
			t.Logf("attempt %v failed: %v", i, err)
		}
	}
	if err != nil {
		t.Fatal(err)
	}
}

var slots = []int{5, 3, 6, 6, 6, 1, 1, 2, 7, 9, 4, 8, 0}

type afterResult struct {
	slot int
	t    Time
}

func await(slot int, result chan<- afterResult, ac <-chan Time) {
	result <- afterResult{slot, <-ac}
}

func testAfterQueuing(t *testing.T) error {
	Delta := 100 * Millisecond
	if testing.Short() {
		Delta = 20 * Millisecond
	}
	// make the result channel buffered because we don't want
	// to depend on channel queueing semantics that might
	// possibly change in the future.
	result := make(chan afterResult, len(slots))

	t0 := Now()
	for _, slot := range slots {
		go await(slot, result, After(Duration(slot)*Delta))
	}
	sort.Ints(slots)
	for _, slot := range slots {
		r := <-result
		if r.slot != slot {
			return fmt.Errorf("after slot %d, expected %d", r.slot, slot)
		}
		dt := r.t.Sub(t0)
		target := Duration(slot) * Delta
		if dt < target-Delta/2 || dt > target+Delta*10 {
			return fmt.Errorf("After(%s) arrived at %s, expected [%s,%s]", target, dt, target-Delta/2, target+Delta*10)
		}
	}
	return nil
}

func TestTimerStopStress(t *testing.T) {
	if testing.Short() {
		return
	}
	for i := 0; i < 100; i++ {
		go func(i int) {
			timer := AfterFunc(2*Second, func() {
				t.Fatalf("timer %d was not stopped", i)
			})
			Sleep(1 * Second)
			timer.Stop()
		}(i)
	}
	Sleep(3 * Second)
}

func TestSleepZeroDeadlock(t *testing.T) {
	// Sleep(0) used to hang, the sequence of events was as follows.
	// Sleep(0) sets G's status to Gwaiting, but then immediately returns leaving the status.
	// Then the goroutine calls e.g. new and falls down into the scheduler due to pending GC.
	// After the GC nobody wakes up the goroutine from Gwaiting status.
	defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(4))
	c := make(chan bool)
	go func() {
		for i := 0; i < 100; i++ {
			runtime.GC()
		}
		c <- true
	}()
	for i := 0; i < 100; i++ {
		Sleep(0)
		tmp := make(chan bool, 1)
		tmp <- true
		<-tmp
	}
	<-c
}

func testReset(d Duration) error {
	t0 := NewTimer(2 * d)
	Sleep(d)
	if t0.Reset(3*d) != true {
		return errors.New("resetting unfired timer returned false")
	}
	Sleep(2 * d)
	select {
	case <-t0.C:
		return errors.New("timer fired early")
	default:
	}
	Sleep(2 * d)
	select {
	case <-t0.C:
	default:
		return errors.New("reset timer did not fire")
	}

	if t0.Reset(50*Millisecond) != false {
		return errors.New("resetting expired timer returned true")
	}
	return nil
}

func TestReset(t *testing.T) {
	// We try to run this test with increasingly larger multiples
	// until one works so slow, loaded hardware isn't as flaky,
	// but without slowing down fast machines unnecessarily.
	const unit = 25 * Millisecond
	tries := []Duration{
		1 * unit,
		3 * unit,
		7 * unit,
		15 * unit,
	}
	var err error
	for _, d := range tries {
		err = testReset(d)
		if err == nil {
			t.Logf("passed using duration %v", d)
			return
		}
	}
	t.Error(err)
}

// Test that sleeping for an interval so large it overflows does not
// result in a short sleep duration.
func TestOverflowSleep(t *testing.T) {
	const timeout = 25 * Millisecond
	const big = Duration(int64(1<<63 - 1))
	select {
	case <-After(big):
		t.Fatalf("big timeout fired")
	case <-After(timeout):
		// OK
	}
	const neg = Duration(-1 << 63)
	select {
	case <-After(neg):
		// OK
	case <-After(timeout):
		t.Fatalf("negative timeout didn't fire")
	}
}
<|endoftext|>


<commit_before>package main

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

func counter() {
	slice := make([]int, 0)
	c := 1
	for i := 0; i < 100000; i++ {
		c = i + 1 + 2 + 3 + 4 + 5
		slice = append(slice, c)
	}
}

func workForever() {
	for {
		go counter()
		time.Sleep(time.Second)
	}
}

func httpGet(w http.ResponseWriter, r *http.Request) {
	counter()
}

func main() {
	go workForever()
	http.HandleFunc("/get", httpGet)
	http.ListenAndServe("localhost:8000", nil)
}
<commit_msg>update<commit_after>package main

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

func counter() {
	slice := make([]int, 0)
	c := 1
	for i := 0; i < 100000; i++ {
		c = i + 1 + 2 + 3 + 4 + 5
		slice = append(slice, c)
	}
}

func workForever() {
	for {
		go counter()
		time.Sleep(time.Second)
	}
}

func httpGet(w http.ResponseWriter, r *http.Request) {
	counter()
}

func main() {
	go workForever()
	http.HandleFunc("/get", httpGet)
	http.ListenAndServe(":8000", nil)
}
<|endoftext|>


<commit_before>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package types

import (
	"go/token"
	"sync"
)

// TODO(rfindley) Clean up Named struct below; specifically the fromRHS field (can we use underlying?).

// A Named represents a named (defined) type.
type Named struct {
	check      *Checker
	info       typeInfo    // for cycle detection
	obj        *TypeName   // corresponding declared object
	orig       *Named      // original, uninstantiated type
	fromRHS    Type        // type (on RHS of declaration) this *Named type is derived of (for cycle reporting)
	underlying Type        // possibly a *Named during setup; never a *Named once set up completely
	instance   *instance   // syntactic information for lazy instantiation
	tparams    *TypeParams // type parameters, or nil
	targs      []Type      // type arguments (after instantiation), or nil
	methods    []*Func     // methods declared for this type (not the method set of this type); signatures are type-checked lazily

	resolve func(*Named) ([]*TypeName, Type, []*Func)
	once    sync.Once
}

// NewNamed returns a new named type for the given type name, underlying type, and associated methods.
// If the given type name obj doesn't have a type yet, its type is set to the returned named type.
// The underlying type must not be a *Named.
func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
	if _, ok := underlying.(*Named); ok {
		panic("types.NewNamed: underlying type must not be *Named")
	}
	return (*Checker)(nil).newNamed(obj, nil, underlying, nil, methods)
}

func (t *Named) load() *Named {
	// If t is an instantiated type, it derives its methods and tparams from its
	// base type. Since we expect type parameters and methods to be set after a
	// call to load, we must load the base and copy here.
	//
	// underlying is set when t is expanded.
	//
	// By convention, a type instance is loaded iff its tparams are set.
	if len(t.targs) > 0 && t.tparams == nil {
		t.orig.load()
		t.tparams = t.orig.tparams
		t.methods = t.orig.methods
	}
	if t.resolve == nil {
		return t
	}

	t.once.Do(func() {
		// TODO(mdempsky): Since we're passing t to resolve anyway
		// (necessary because types2 expects the receiver type for methods
		// on defined interface types to be the Named rather than the
		// underlying Interface), maybe it should just handle calling
		// SetTParams, SetUnderlying, and AddMethod instead?  Those
		// methods would need to support reentrant calls though.  It would
		// also make the API more future-proof towards further extensions
		// (like SetTParams).

		tparams, underlying, methods := t.resolve(t)

		switch underlying.(type) {
		case nil, *Named:
			panic("invalid underlying type")
		}

		t.tparams = bindTParams(tparams)
		t.underlying = underlying
		t.methods = methods
	})
	return t
}

// newNamed is like NewNamed but with a *Checker receiver and additional orig argument.
func (check *Checker) newNamed(obj *TypeName, orig *Named, underlying Type, tparams *TypeParams, methods []*Func) *Named {
	typ := &Named{check: check, obj: obj, orig: orig, fromRHS: underlying, underlying: underlying, tparams: tparams, methods: methods}
	if typ.orig == nil {
		typ.orig = typ
	}
	if obj.typ == nil {
		obj.typ = typ
	}
	// Ensure that typ is always expanded, at which point the check field can be
	// nilled out.
	//
	// Note that currently we cannot nil out check inside typ.under(), because
	// it's possible that typ is expanded multiple times.
	//
	// TODO(rFindley): clean this up so that under is the only function mutating
	//                 named types.
	if check != nil {
		check.later(func() {
			switch typ.under().(type) {
			case *Named:
				panic("internal error: unexpanded underlying type")
			}
			typ.check = nil
		})
	}
	return typ
}

// Obj returns the type name for the named type t.
func (t *Named) Obj() *TypeName { return t.obj }

// _Orig returns the original generic type an instantiated type is derived from.
// If t is not an instantiated type, the result is t.
func (t *Named) _Orig() *Named { return t.orig }

// TODO(gri) Come up with a better representation and API to distinguish
//           between parameterized instantiated and non-instantiated types.

// TParams returns the type parameters of the named type t, or nil.
// The result is non-nil for an (originally) parameterized type even if it is instantiated.
func (t *Named) TParams() *TypeParams { return t.load().tparams }

// SetTParams sets the type parameters of the named type t.
func (t *Named) SetTParams(tparams []*TypeName) { t.load().tparams = bindTParams(tparams) }

// TArgs returns the type arguments after instantiation of the named type t, or nil if not instantiated.
func (t *Named) TArgs() []Type { return t.targs }

// SetTArgs sets the type arguments of the named type t.
func (t *Named) SetTArgs(args []Type) { t.targs = args }

// NumMethods returns the number of explicit methods whose receiver is named type t.
func (t *Named) NumMethods() int { return len(t.load().methods) }

// Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
func (t *Named) Method(i int) *Func { return t.load().methods[i] }

// SetUnderlying sets the underlying type and marks t as complete.
func (t *Named) SetUnderlying(underlying Type) {
	if underlying == nil {
		panic("types.Named.SetUnderlying: underlying type must not be nil")
	}
	if _, ok := underlying.(*Named); ok {
		panic("types.Named.SetUnderlying: underlying type must not be *Named")
	}
	t.load().underlying = underlying
}

// AddMethod adds method m unless it is already in the method list.
func (t *Named) AddMethod(m *Func) {
	t.load()
	if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
		t.methods = append(t.methods, m)
	}
}

func (t *Named) Underlying() Type { return t.load().underlying }
func (t *Named) String() string   { return TypeString(t, nil) }

// ----------------------------------------------------------------------------
// Implementation

// under returns the expanded underlying type of n0; possibly by following
// forward chains of named types. If an underlying type is found, resolve
// the chain by setting the underlying type for each defined type in the
// chain before returning it. If no underlying type is found or a cycle
// is detected, the result is Typ[Invalid]. If a cycle is detected and
// n0.check != nil, the cycle is reported.
func (n0 *Named) under() Type {
	n0.expand()

	u := n0.Underlying()

	if u == Typ[Invalid] {
		return u
	}

	// If the underlying type of a defined type is not a defined
	// (incl. instance) type, then that is the desired underlying
	// type.
	switch u.(type) {
	case nil:
		return Typ[Invalid]
	default:
		// common case
		return u
	case *Named:
		// handled below
	}

	if n0.check == nil {
		panic("internal error: Named.check == nil but type is incomplete")
	}

	// Invariant: after this point n0 as well as any named types in its
	// underlying chain should be set up when this function exits.
	check := n0.check

	// If we can't expand u at this point, it is invalid.
	n := asNamed(u)
	if n == nil {
		n0.underlying = Typ[Invalid]
		return n0.underlying
	}

	// Otherwise, follow the forward chain.
	seen := map[*Named]int{n0: 0}
	path := []Object{n0.obj}
	for {
		u = n.Underlying()
		if u == nil {
			u = Typ[Invalid]
			break
		}
		var n1 *Named
		switch u1 := u.(type) {
		case *Named:
			u1.expand()
			n1 = u1
		}
		if n1 == nil {
			break // end of chain
		}

		seen[n] = len(seen)
		path = append(path, n.obj)
		n = n1

		if i, ok := seen[n]; ok {
			// cycle
			check.cycleError(path[i:])
			u = Typ[Invalid]
			break
		}
	}

	for n := range seen {
		// We should never have to update the underlying type of an imported type;
		// those underlying types should have been resolved during the import.
		// Also, doing so would lead to a race condition (was issue #31749).
		// Do this check always, not just in debug mode (it's cheap).
		if n.obj.pkg != check.pkg {
			panic("internal error: imported type with unresolved underlying type")
		}
		n.underlying = u
	}

	return u
}

func (n *Named) setUnderlying(typ Type) {
	if n != nil {
		n.underlying = typ
	}
}

// instance holds position information for use in lazy instantiation.
//
// TODO(rfindley): come up with a better name for this type, now that its usage
// has changed.
type instance struct {
	pos     token.Pos   // position of type instantiation; for error reporting only
	posList []token.Pos // position of each targ; for error reporting only
}

// expand ensures that the underlying type of n is instantiated.
// The underlying type will be Typ[Invalid] if there was an error.
// TODO(rfindley): expand would be a better name for this method, but conflicts
// with the existing concept of lazy expansion. Need to reconcile this.
func (n *Named) expand() {
	if n.instance != nil {
		// n must be loaded before instantiation, in order to have accurate
		// tparams. This is done implicitly by the call to n.TParams, but making it
		// explicit is harmless: load is idempotent.
		n.load()
		inst := n.check.instantiate(n.instance.pos, n.orig.underlying, n.TParams().list(), n.targs, n.instance.posList)
		n.underlying = inst
		n.fromRHS = inst
		n.instance = nil
	}
}

// expand expands uninstantiated named types and leaves all other types alone.
// expand does not recurse.
func expand(typ Type) Type {
	if t, _ := typ.(*Named); t != nil {
		t.expand()
	}
	return typ
}
<commit_msg>[dev.typeparams] go/types: switch the TArgs API to NumTArgs/TArg<commit_after>// Copyright 2011 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

package types

import (
	"go/token"
	"sync"
)

// TODO(rfindley) Clean up Named struct below; specifically the fromRHS field (can we use underlying?).

// A Named represents a named (defined) type.
type Named struct {
	check      *Checker
	info       typeInfo    // for cycle detection
	obj        *TypeName   // corresponding declared object
	orig       *Named      // original, uninstantiated type
	fromRHS    Type        // type (on RHS of declaration) this *Named type is derived of (for cycle reporting)
	underlying Type        // possibly a *Named during setup; never a *Named once set up completely
	instance   *instance   // syntactic information for lazy instantiation
	tparams    *TypeParams // type parameters, or nil
	targs      []Type      // type arguments (after instantiation), or nil
	methods    []*Func     // methods declared for this type (not the method set of this type); signatures are type-checked lazily

	resolve func(*Named) ([]*TypeName, Type, []*Func)
	once    sync.Once
}

// NewNamed returns a new named type for the given type name, underlying type, and associated methods.
// If the given type name obj doesn't have a type yet, its type is set to the returned named type.
// The underlying type must not be a *Named.
func NewNamed(obj *TypeName, underlying Type, methods []*Func) *Named {
	if _, ok := underlying.(*Named); ok {
		panic("types.NewNamed: underlying type must not be *Named")
	}
	return (*Checker)(nil).newNamed(obj, nil, underlying, nil, methods)
}

func (t *Named) load() *Named {
	// If t is an instantiated type, it derives its methods and tparams from its
	// base type. Since we expect type parameters and methods to be set after a
	// call to load, we must load the base and copy here.
	//
	// underlying is set when t is expanded.
	//
	// By convention, a type instance is loaded iff its tparams are set.
	if len(t.targs) > 0 && t.tparams == nil {
		t.orig.load()
		t.tparams = t.orig.tparams
		t.methods = t.orig.methods
	}
	if t.resolve == nil {
		return t
	}

	t.once.Do(func() {
		// TODO(mdempsky): Since we're passing t to resolve anyway
		// (necessary because types2 expects the receiver type for methods
		// on defined interface types to be the Named rather than the
		// underlying Interface), maybe it should just handle calling
		// SetTParams, SetUnderlying, and AddMethod instead?  Those
		// methods would need to support reentrant calls though.  It would
		// also make the API more future-proof towards further extensions
		// (like SetTParams).

		tparams, underlying, methods := t.resolve(t)

		switch underlying.(type) {
		case nil, *Named:
			panic("invalid underlying type")
		}

		t.tparams = bindTParams(tparams)
		t.underlying = underlying
		t.methods = methods
	})
	return t
}

// newNamed is like NewNamed but with a *Checker receiver and additional orig argument.
func (check *Checker) newNamed(obj *TypeName, orig *Named, underlying Type, tparams *TypeParams, methods []*Func) *Named {
	typ := &Named{check: check, obj: obj, orig: orig, fromRHS: underlying, underlying: underlying, tparams: tparams, methods: methods}
	if typ.orig == nil {
		typ.orig = typ
	}
	if obj.typ == nil {
		obj.typ = typ
	}
	// Ensure that typ is always expanded, at which point the check field can be
	// nilled out.
	//
	// Note that currently we cannot nil out check inside typ.under(), because
	// it's possible that typ is expanded multiple times.
	//
	// TODO(rFindley): clean this up so that under is the only function mutating
	//                 named types.
	if check != nil {
		check.later(func() {
			switch typ.under().(type) {
			case *Named:
				panic("internal error: unexpanded underlying type")
			}
			typ.check = nil
		})
	}
	return typ
}

// Obj returns the type name for the named type t.
func (t *Named) Obj() *TypeName { return t.obj }

// _Orig returns the original generic type an instantiated type is derived from.
// If t is not an instantiated type, the result is t.
func (t *Named) _Orig() *Named { return t.orig }

// TODO(gri) Come up with a better representation and API to distinguish
//           between parameterized instantiated and non-instantiated types.

// TParams returns the type parameters of the named type t, or nil.
// The result is non-nil for an (originally) parameterized type even if it is instantiated.
func (t *Named) TParams() *TypeParams { return t.load().tparams }

// SetTParams sets the type parameters of the named type t.
func (t *Named) SetTParams(tparams []*TypeName) { t.load().tparams = bindTParams(tparams) }

// NumTArgs returns the number of type arguments used to instantiate the named
// type t, or 0 if t is not an instantiated type.
func (t *Named) NumTArgs() int { return len(t.targs) }

// TArgs returns the i'th type argument of the named type t for 0 <= i < t.NumTArgs().
func (t *Named) TArg(i int) Type { return t.targs[i] }

// SetTArgs sets the type arguments of the named type t.
func (t *Named) SetTArgs(args []Type) { t.targs = args }

// NumMethods returns the number of explicit methods whose receiver is named type t.
func (t *Named) NumMethods() int { return len(t.load().methods) }

// Method returns the i'th method of named type t for 0 <= i < t.NumMethods().
func (t *Named) Method(i int) *Func { return t.load().methods[i] }

// SetUnderlying sets the underlying type and marks t as complete.
func (t *Named) SetUnderlying(underlying Type) {
	if underlying == nil {
		panic("types.Named.SetUnderlying: underlying type must not be nil")
	}
	if _, ok := underlying.(*Named); ok {
		panic("types.Named.SetUnderlying: underlying type must not be *Named")
	}
	t.load().underlying = underlying
}

// AddMethod adds method m unless it is already in the method list.
func (t *Named) AddMethod(m *Func) {
	t.load()
	if i, _ := lookupMethod(t.methods, m.pkg, m.name); i < 0 {
		t.methods = append(t.methods, m)
	}
}

func (t *Named) Underlying() Type { return t.load().underlying }
func (t *Named) String() string   { return TypeString(t, nil) }

// ----------------------------------------------------------------------------
// Implementation

// under returns the expanded underlying type of n0; possibly by following
// forward chains of named types. If an underlying type is found, resolve
// the chain by setting the underlying type for each defined type in the
// chain before returning it. If no underlying type is found or a cycle
// is detected, the result is Typ[Invalid]. If a cycle is detected and
// n0.check != nil, the cycle is reported.
func (n0 *Named) under() Type {
	n0.expand()

	u := n0.Underlying()

	if u == Typ[Invalid] {
		return u
	}

	// If the underlying type of a defined type is not a defined
	// (incl. instance) type, then that is the desired underlying
	// type.
	switch u.(type) {
	case nil:
		return Typ[Invalid]
	default:
		// common case
		return u
	case *Named:
		// handled below
	}

	if n0.check == nil {
		panic("internal error: Named.check == nil but type is incomplete")
	}

	// Invariant: after this point n0 as well as any named types in its
	// underlying chain should be set up when this function exits.
	check := n0.check

	// If we can't expand u at this point, it is invalid.
	n := asNamed(u)
	if n == nil {
		n0.underlying = Typ[Invalid]
		return n0.underlying
	}

	// Otherwise, follow the forward chain.
	seen := map[*Named]int{n0: 0}
	path := []Object{n0.obj}
	for {
		u = n.Underlying()
		if u == nil {
			u = Typ[Invalid]
			break
		}
		var n1 *Named
		switch u1 := u.(type) {
		case *Named:
			u1.expand()
			n1 = u1
		}
		if n1 == nil {
			break // end of chain
		}

		seen[n] = len(seen)
		path = append(path, n.obj)
		n = n1

		if i, ok := seen[n]; ok {
			// cycle
			check.cycleError(path[i:])
			u = Typ[Invalid]
			break
		}
	}

	for n := range seen {
		// We should never have to update the underlying type of an imported type;
		// those underlying types should have been resolved during the import.
		// Also, doing so would lead to a race condition (was issue #31749).
		// Do this check always, not just in debug mode (it's cheap).
		if n.obj.pkg != check.pkg {
			panic("internal error: imported type with unresolved underlying type")
		}
		n.underlying = u
	}

	return u
}

func (n *Named) setUnderlying(typ Type) {
	if n != nil {
		n.underlying = typ
	}
}

// instance holds position information for use in lazy instantiation.
//
// TODO(rfindley): come up with a better name for this type, now that its usage
// has changed.
type instance struct {
	pos     token.Pos   // position of type instantiation; for error reporting only
	posList []token.Pos // position of each targ; for error reporting only
}

// expand ensures that the underlying type of n is instantiated.
// The underlying type will be Typ[Invalid] if there was an error.
// TODO(rfindley): expand would be a better name for this method, but conflicts
// with the existing concept of lazy expansion. Need to reconcile this.
func (n *Named) expand() {
	if n.instance != nil {
		// n must be loaded before instantiation, in order to have accurate
		// tparams. This is done implicitly by the call to n.TParams, but making it
		// explicit is harmless: load is idempotent.
		n.load()
		inst := n.check.instantiate(n.instance.pos, n.orig.underlying, n.TParams().list(), n.targs, n.instance.posList)
		n.underlying = inst
		n.fromRHS = inst
		n.instance = nil
	}
}

// expand expands uninstantiated named types and leaves all other types alone.
// expand does not recurse.
func expand(typ Type) Type {
	if t, _ := typ.(*Named); t != nil {
		t.expand()
	}
	return typ
}
<|endoftext|>


<commit_before>package cri_test

import (
	"testing"

	"github.com/bmizerany/assert"
	"github.com/weaveworks/scope/probe/cri"
)

func TestParseHttpEndpointUrl(t *testing.T) {
	_, err := cri.NewCRIClient("http://xyz.com")

	assert.Equal(t, "protocol \"http\" not supported", err.Error())
}

func TestParseTcpEndpointUrl(t *testing.T) {
	client, err := cri.NewCRIClient("127.0.0.1")

	assert.Equal(t, nil, err)
	assert.NotEqual(t, nil, client)
}
<commit_msg>Add tests for probe/cri/registry<commit_after>package cri_test

import (
	"testing"

	"github.com/bmizerany/assert"
	"github.com/weaveworks/scope/probe/cri"
)

var nonUnixSocketsTest = []struct {
	endpoint     string
	errorMessage string
}{
	{"http://xyz.com", "protocol \"http\" not supported"},
	{"tcp://var/unix.sock", "endpoint was not unix socket tcp"},
	{"http://[fe80::%31]/", "parse http://[fe80::%31]/: invalid URL escape \"%31\""},
}

func TestParseNonUnixEndpointUrl(t *testing.T) {
	for _, tt := range nonUnixSocketsTest {
		_, err := cri.NewCRIClient(tt.endpoint)

		assert.Equal(t, tt.errorMessage, err.Error())
	}
}

var unixSocketsTest = []string{
	"127.0.0.1", // tests the fallback endpoint
	"unix://127.0.0.1",
	"unix///var/run/dockershim.sock",
	"var/run/dockershim.sock",
}

func TestParseUnixEndpointUrl(t *testing.T) {
	for _, tt := range unixSocketsTest {
		client, err := cri.NewCRIClient(tt)

		assert.Equal(t, nil, err)
		assert.NotEqual(t, nil, client)
	}

}
<|endoftext|>


<commit_before>package rabbit

import (
	"context"
	"fmt"

	"github.com/ottogiron/ferrariworker/processor"
	"github.com/streadway/amqp"
)

const (
	uriKey         = "uri"
	routingKey     = "binding-key"
	bindingWaitKey = "binding-wait"
	//Queue Arguments
	queueNameKey           = "queue-name"
	queueDurableKey        = "queue-durable"
	queueDeleteWhenUsedKey = "queue-delete-when-used"
	queueExclusiveKey      = "queue-exclusive"
	queueNoWaitKey         = "queue-no-wait"
	queuArgumentsKey       = "queue-arguments"
	//Consumer arguments
	consumerTagKey       = "consumer-tag"
	consumerAutoAckKey   = "consumer-auto-ack"
	consumerExclusiveKey = "consumer-exclusive"
	consumerNoLocalKey   = "consumer-no-local"
	consumerNoWaitKey    = "consumer-no-wait"
	consumerArgsKey      = "consumer-args"
	//Exchange configurations
	exchangeNameKey               = "exchange"
	exchangeTypeKey               = "exchange-type"
	exchangeDurableKey            = "exchange-durable"
	exchangeDeleteWhenCompleteKey = "exchange-delete-when-complete"
	exchangeInternalKey           = "exchange-internal"
	exchangeNowaitKey             = "exchange-no-wait"
)

type factory struct{}

func (f *factory) New(config processor.AdapterConfig) processor.Adapter {
	return newRabbitProcessorAdapter(config)
}

func init() {
	processor.RegisterAdapterFactory(&factory{}, schema)
}

type rabbitProcessorAdapter struct {
	config     processor.AdapterConfig
	connection *amqp.Connection
}

//NewRabbitProcessorAdapter creates a new rabbitStreamAdapter
func newRabbitProcessorAdapter(config processor.AdapterConfig) processor.Adapter {
	return &rabbitProcessorAdapter{
		config: config,
	}
}

func (m *rabbitProcessorAdapter) Open() error {
	queueURL := m.config.GetString(uriKey)
	con, err := amqp.Dial(queueURL)
	if err != nil {
		return fmt.Errorf("Error when dialing to %s %s", queueURL, err)
	}
	m.connection = con
	return nil
}

func (m *rabbitProcessorAdapter) Close() error {
	return m.connection.Close()
}

func (m *rabbitProcessorAdapter) Messages(ctx context.Context) (<-chan processor.Message, error) {

	ch, err := m.connection.Channel()

	if err != nil {
		return nil, fmt.Errorf("Could not open a channel  %s", err)
	}

	if m.config.GetString(exchangeNameKey) != "" {
		err := ch.ExchangeDeclare(
			m.config.GetString(exchangeNameKey),
			m.config.GetString(exchangeTypeKey),
			m.config.GetBoolean(exchangeDurableKey),
			m.config.GetBoolean(exchangeDeleteWhenCompleteKey),
			m.config.GetBoolean(exchangeInternalKey),
			m.config.GetBoolean(exchangeNowaitKey),
			nil,
		)
		if err != nil {
			return nil, fmt.Errorf("Could not create an exchange %s", err)
		}
	}

	q, err := ch.QueueDeclare(
		m.config.GetString(queueNameKey),            // name
		m.config.GetBoolean(queueDurableKey),        // durable
		m.config.GetBoolean(queueDeleteWhenUsedKey), // delete when usused
		m.config.GetBoolean(queueExclusiveKey),      // exclusive
		m.config.GetBoolean(queueNoWaitKey),         // no-wait
		nil, // arguments
	)

	if err != nil {
		return nil, fmt.Errorf("Could not declare the queue %s", err)
	}

	if err = ch.QueueBind(
		m.config.GetString(queueNameKey),    // name of the queue
		m.config.GetString(routingKey),      // bindingKey
		m.config.GetString(exchangeNameKey), // sourceExchange
		m.config.GetBoolean(bindingWaitKey), // noWait
		nil, // arguments
	); err != nil {
		return nil, fmt.Errorf("Queue Bind: %s", err)
	}

	msgs, err := ch.Consume(
		q.Name, // queue
		m.config.GetString(consumerTagKey),        // consumer
		m.config.GetBoolean(consumerAutoAckKey),   // auto-ack
		m.config.GetBoolean(consumerExclusiveKey), // exclusive
		m.config.GetBoolean(consumerNoLocalKey),   // no-local
		m.config.GetBoolean(consumerNoWaitKey),    // no-wait
		nil, // args
	)

	if err != nil {
		return nil, fmt.Errorf("Could not start consuming queue %s", err)
	}

	msgChannel := make(chan processor.Message)
	go func() {
		for {
			select {
			case d := <-msgs:
				msgChannel <- processor.Message{Payload: d.Body, OriginalMessage: d}
			case <-ctx.Done():
				close(msgChannel)
				ch.Close()
				return
			}
		}

	}()
	return msgChannel, nil
}

//RabbitResultHanlder post process when the job is already done
func (m *rabbitProcessorAdapter) ResultHandler(jobResult *processor.JobResult, message processor.Message) error {
	return nil
}
<commit_msg>#12 fix routing key parameter name (from binding key)<commit_after>package rabbit

import (
	"context"
	"fmt"

	"github.com/ottogiron/ferrariworker/processor"
	"github.com/streadway/amqp"
)

const (
	uriKey         = "uri"
	routingKey     = "routing-key"
	bindingWaitKey = "binding-wait"
	//Queue Arguments
	queueNameKey           = "queue-name"
	queueDurableKey        = "queue-durable"
	queueDeleteWhenUsedKey = "queue-delete-when-used"
	queueExclusiveKey      = "queue-exclusive"
	queueNoWaitKey         = "queue-no-wait"
	queuArgumentsKey       = "queue-arguments"
	//Consumer arguments
	consumerTagKey       = "consumer-tag"
	consumerAutoAckKey   = "consumer-auto-ack"
	consumerExclusiveKey = "consumer-exclusive"
	consumerNoLocalKey   = "consumer-no-local"
	consumerNoWaitKey    = "consumer-no-wait"
	consumerArgsKey      = "consumer-args"
	//Exchange configurations
	exchangeNameKey               = "exchange"
	exchangeTypeKey               = "exchange-type"
	exchangeDurableKey            = "exchange-durable"
	exchangeDeleteWhenCompleteKey = "exchange-delete-when-complete"
	exchangeInternalKey           = "exchange-internal"
	exchangeNowaitKey             = "exchange-no-wait"
)

type factory struct{}

func (f *factory) New(config processor.AdapterConfig) processor.Adapter {
	return newRabbitProcessorAdapter(config)
}

func init() {
	processor.RegisterAdapterFactory(&factory{}, schema)
}

type rabbitProcessorAdapter struct {
	config     processor.AdapterConfig
	connection *amqp.Connection
}

//NewRabbitProcessorAdapter creates a new rabbitStreamAdapter
func newRabbitProcessorAdapter(config processor.AdapterConfig) processor.Adapter {
	return &rabbitProcessorAdapter{
		config: config,
	}
}

func (m *rabbitProcessorAdapter) Open() error {
	queueURL := m.config.GetString(uriKey)
	con, err := amqp.Dial(queueURL)
	if err != nil {
		return fmt.Errorf("Error when dialing to %s %s", queueURL, err)
	}
	m.connection = con
	return nil
}

func (m *rabbitProcessorAdapter) Close() error {
	return m.connection.Close()
}

func (m *rabbitProcessorAdapter) Messages(ctx context.Context) (<-chan processor.Message, error) {

	ch, err := m.connection.Channel()

	if err != nil {
		return nil, fmt.Errorf("Could not open a channel  %s", err)
	}

	if m.config.GetString(exchangeNameKey) != "" {
		err := ch.ExchangeDeclare(
			m.config.GetString(exchangeNameKey),
			m.config.GetString(exchangeTypeKey),
			m.config.GetBoolean(exchangeDurableKey),
			m.config.GetBoolean(exchangeDeleteWhenCompleteKey),
			m.config.GetBoolean(exchangeInternalKey),
			m.config.GetBoolean(exchangeNowaitKey),
			nil,
		)
		if err != nil {
			return nil, fmt.Errorf("Could not create an exchange %s", err)
		}
	}

	q, err := ch.QueueDeclare(
		m.config.GetString(queueNameKey),            // name
		m.config.GetBoolean(queueDurableKey),        // durable
		m.config.GetBoolean(queueDeleteWhenUsedKey), // delete when usused
		m.config.GetBoolean(queueExclusiveKey),      // exclusive
		m.config.GetBoolean(queueNoWaitKey),         // no-wait
		nil, // arguments
	)

	if err != nil {
		return nil, fmt.Errorf("Could not declare the queue %s", err)
	}

	if err = ch.QueueBind(
		m.config.GetString(queueNameKey),    // name of the queue
		m.config.GetString(routingKey),      // bindingKey
		m.config.GetString(exchangeNameKey), // sourceExchange
		m.config.GetBoolean(bindingWaitKey), // noWait
		nil, // arguments
	); err != nil {
		return nil, fmt.Errorf("Queue Bind: %s", err)
	}

	msgs, err := ch.Consume(
		q.Name, // queue
		m.config.GetString(consumerTagKey),        // consumer
		m.config.GetBoolean(consumerAutoAckKey),   // auto-ack
		m.config.GetBoolean(consumerExclusiveKey), // exclusive
		m.config.GetBoolean(consumerNoLocalKey),   // no-local
		m.config.GetBoolean(consumerNoWaitKey),    // no-wait
		nil, // args
	)

	if err != nil {
		return nil, fmt.Errorf("Could not start consuming queue %s", err)
	}

	msgChannel := make(chan processor.Message)
	go func() {
		for {
			select {
			case d := <-msgs:
				msgChannel <- processor.Message{Payload: d.Body, OriginalMessage: d}
			case <-ctx.Done():
				close(msgChannel)
				ch.Close()
				return
			}
		}

	}()
	return msgChannel, nil
}

//RabbitResultHanlder post process when the job is already done
func (m *rabbitProcessorAdapter) ResultHandler(jobResult *processor.JobResult, message processor.Message) error {
	return nil
}
<|endoftext|>


<commit_before>package shell

import (
	"context"
	"fmt"
	"io"
	"os"
	"os/signal"
	"syscall"
)

// Stream is the inteface which can read command-line
type Stream interface {
	ReadLine(context.Context) (context.Context, string, error)
	DisableHistory(value bool) bool
}

// NulStream is the null implementation for the interface Stream.
type NulStream struct{}

// ReadLine always returns "" and io.EOF.
func (stream *NulStream) ReadLine(ctx context.Context) (context.Context, string, error) {
	return ctx, "", io.EOF
}

// DisableHistory do nothing.
func (stream *NulStream) DisableHistory(value bool) bool {
	return false
}

func (ses *session) push(lines []string) {
	if lines != nil && len(lines) >= 1 {
		ses.unreadline = append(ses.unreadline, lines...)
	}
}

func (ses *session) pop() (string, bool) {
	if ses.unreadline == nil || len(ses.unreadline) <= 0 {
		return "", false
	}
	line := ses.unreadline[0]
	if len(ses.unreadline) >= 2 {
		ses.unreadline = ses.unreadline[1:]
	} else {
		ses.unreadline = nil
	}
	return line, true
}

// ReadCommand reads completed one command from `stream`.
func (sh *Shell) ReadCommand(ctx context.Context) (context.Context, string, error) {
	stream := sh.Stream
	var line string
	var err error

	line, ok := sh.pop()
	if !ok {
		outputMutex.Lock()
		os.Stderr.Sync()
		os.Stdout.Sync()
		ctx, line, err = stream.ReadLine(ctx)
		outputMutex.Unlock()
		if err != nil {
			return ctx, line, err
		}

		texts := splitToStatement(line)
		line = texts[0]
		sh.push(texts[1:])
	}
	return ctx, line, nil
}

// Loop executes commands from `stream` until any errors are found.
func (sh *Shell) Loop(ctx0 context.Context, stream Stream) (int, error) {
	backup := sh.Stream
	sh.Stream = stream
	defer func() {
		sh.Stream = backup
	}()

	sigint := make(chan os.Signal)
	signal.Notify(sigint, os.Interrupt, syscall.SIGINT)

	defer func() {
		signal.Stop(sigint)
		close(sigint)
	}()

	for {
		ctx, cancel := context.WithCancel(ctx0)

		ctx, line, err := sh.ReadCommand(ctx)
		if err != nil {
			cancel()
			if err == io.EOF {
				return 0, err
			}
			return 1, err
		}

		go func() {
			select {
			case <-sigint:
				cancel()
			case <-ctx.Done():
			}
		}()

		rc, err := sh.Interpret(ctx, line)

		if err != nil {
			if err == io.EOF {
				cancel()
				return rc, err
			}
			if err1, ok := err.(AlreadyReportedError); ok {
				if err1.Err == io.EOF {
					cancel()
					return rc, err
				}
			} else {
				fmt.Fprintln(os.Stderr, err)
			}
		}
		if rc > 0 {
			fmt.Fprintf(os.Stderr, "exit status %d\n", rc)
		}
		cancel()
	}
}

// ForEver executes commands from `stream` until EOF are found.
func (sh *Shell) ForEver(ctx context.Context, stream Stream) error {
	for {
		_, err := sh.Loop(ctx, stream)
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
	}
}
<commit_msg>(#418) When line ends with ^ or unclosed quotation, continue lineinput<commit_after>package shell

import (
	"context"
	"fmt"
	"io"
	"os"
	"os/signal"
	"strings"
	"syscall"
)

// Stream is the inteface which can read command-line
type Stream interface {
	ReadLine(context.Context) (context.Context, string, error)
	DisableHistory(value bool) bool
}

// NulStream is the null implementation for the interface Stream.
type NulStream struct{}

// ReadLine always returns "" and io.EOF.
func (stream *NulStream) ReadLine(ctx context.Context) (context.Context, string, error) {
	return ctx, "", io.EOF
}

// DisableHistory do nothing.
func (stream *NulStream) DisableHistory(value bool) bool {
	return false
}

func (ses *session) push(lines []string) {
	if lines != nil && len(lines) >= 1 {
		ses.unreadline = append(ses.unreadline, lines...)
	}
}

func (ses *session) pop() (string, bool) {
	if ses.unreadline == nil || len(ses.unreadline) <= 0 {
		return "", false
	}
	line := ses.unreadline[0]
	if len(ses.unreadline) >= 2 {
		ses.unreadline = ses.unreadline[1:]
	} else {
		ses.unreadline = nil
	}
	return line, true
}

// endsWithSep returns
//     false when line does not end with `^`
//     true when line ends with `^`
//     false when line ends with `^^`
//     true when line ends with `^^^`
func endsWithSep(line string, contMark byte) bool {
	markCount := 0
	for len(line) > 0 && line[len(line)-1] == contMark {
		markCount++
		line = line[:len(line)-1]
	}
	return markCount%2 != 0
}

// ReadCommand reads completed one command from `stream`.
func (sh *Shell) ReadCommand(ctx context.Context) (context.Context, string, error) {
	stream := sh.Stream
	var line string
	var err error

	line, ok := sh.pop()
	if !ok {
		for {
			outputMutex.Lock()
			os.Stderr.Sync()
			os.Stdout.Sync()
			var line1 string
			ctx, line1, err = stream.ReadLine(ctx)
			outputMutex.Unlock()
			line += line1
			if err != nil {
				return ctx, line, err
			}
			if endsWithSep(line, '^') {
				line = line[:len(line)-1] + "\r\n"
				continue
			}
			if strings.Count(line, "\"")%2 != 0 {
				line = line + "\r\n"
				continue
			}
			break
		}

		texts := splitToStatement(line)
		line = texts[0]
		sh.push(texts[1:])
	}
	return ctx, line, nil
}

// Loop executes commands from `stream` until any errors are found.
func (sh *Shell) Loop(ctx0 context.Context, stream Stream) (int, error) {
	backup := sh.Stream
	sh.Stream = stream
	defer func() {
		sh.Stream = backup
	}()

	sigint := make(chan os.Signal)
	signal.Notify(sigint, os.Interrupt, syscall.SIGINT)

	defer func() {
		signal.Stop(sigint)
		close(sigint)
	}()

	for {
		ctx, cancel := context.WithCancel(ctx0)

		ctx, line, err := sh.ReadCommand(ctx)
		if err != nil {
			cancel()
			if err == io.EOF {
				return 0, err
			}
			return 1, err
		}

		go func() {
			select {
			case <-sigint:
				cancel()
			case <-ctx.Done():
			}
		}()

		rc, err := sh.Interpret(ctx, line)

		if err != nil {
			if err == io.EOF {
				cancel()
				return rc, err
			}
			if err1, ok := err.(AlreadyReportedError); ok {
				if err1.Err == io.EOF {
					cancel()
					return rc, err
				}
			} else {
				fmt.Fprintln(os.Stderr, err)
			}
		}
		if rc > 0 {
			fmt.Fprintf(os.Stderr, "exit status %d\n", rc)
		}
		cancel()
	}
}

// ForEver executes commands from `stream` until EOF are found.
func (sh *Shell) ForEver(ctx context.Context, stream Stream) error {
	for {
		_, err := sh.Loop(ctx, stream)
		if err == io.EOF {
			return nil
		}
		if err != nil {
			return err
		}
	}
}
<|endoftext|>


<commit_before>/*
Execute shell commands via http server

Install:
	go get github.com/msoap/shell2http
	ln -s $GOPATH/bin/shell2http ~/bin/shell2http

Usage:
	shell2http /path "shell command" /path2 "shell command2" ...

Examples:
	shell2http /top "top -l 1 | head -10"
	shell2http /date date /ps "ps aux"
	shell2http /env 'printenv | sort' /env/path 'echo $PATH' /env/gopath 'echo $GOPATH'
	shell2http /shell_vars_json 'perl -MJSON -E "say to_json(\%ENV)"'
	shell2http /cal_html 'echo "
Calendar
Date: $(date)

$(cal $(date +%Y))
"'

Update:
	go get -u github.com/msoap/shell2http

*/
package main

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

// default port for http-server
const PORT = "8080"

// ------------------------------------------------------------------
const INDEX_HTML = `
<!DOCTYPE html>

	<title>Index shell commands</title>

Index shell commands

		%s

/exit

`

// ------------------------------------------------------------------
// one command type
type t_command struct {
	path string
	cmd  string
}

// ------------------------------------------------------------------
// parse argeuments
func get_handlers() ([]t_command, error) {
	// need >= 2 argeuments and count of it must be even
	if len(os.Args) < 3 || len(os.Args)%2 == 0 {
		return nil, fmt.Errorf(`Usage: shell2http /path "shell command" /path2 "shell command2" ...`)
	}

	cmd_handlers := []t_command{}

	args_i := 1
	for args_i < len(os.Args) {
		path, cmd := os.Args[args_i], os.Args[args_i+1]
		if path[0] != '/' {
			return nil, fmt.Errorf("Error: path %s dont starts with /", path)
		}
		cmd_handlers = append(cmd_handlers, t_command{path: path, cmd: cmd})
		args_i += 2
	}

	return cmd_handlers, nil
}

// ------------------------------------------------------------------
// setup http handlers
func setup_handlers(cmd_handlers []t_command, the_end chan interface{}) {
	index_li_html := ""
	for _, row := range cmd_handlers {
		path, cmd := row.path, row.cmd
		shell_handler := func(rw http.ResponseWriter, req *http.Request) {
			fmt.Println("GET", path)

			shell_out, err := exec.Command("sh", "-c", cmd).Output()
			if err != nil {
				fmt.Println("exec error: ", err)
				fmt.Fprint(rw, "exec error: ", err)
			} else {
				fmt.Fprint(rw, string(shell_out))
			}

			return
		}

		fmt.Printf("register: %s (%s)\n", path, cmd)
		http.HandleFunc(path, shell_handler)
		index_li_html += fmt.Sprintf(`<li><a href="%s">%s</a></li>`, path, path)
	}

	// --------------
	index_html := fmt.Sprintf(INDEX_HTML, index_li_html)
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		fmt.Println("GET /")
		fmt.Fprint(rw, index_html)

		return
	})

	// --------------
	http.HandleFunc("/exit", func(rw http.ResponseWriter, req *http.Request) {
		fmt.Println("GET /exit")
		fmt.Fprint(rw, "Bye...")
		the_end <- nil

		return
	})
}

// ------------------------------------------------------------------
func main() {
	cmd_handlers, err := get_handlers()
	if err != nil {
		fmt.Println(err)
		return
	}
	the_end := make(chan interface{})
	setup_handlers(cmd_handlers, the_end)

	fmt.Println("listen http://localhost:" + PORT + "/")
	go http.ListenAndServe(":"+PORT, nil)
	<-the_end // wait for exit command
}
<commit_msg>Changes from golint<commit_after>/*
Execute shell commands via http server

Install:
	go get github.com/msoap/shell2http
	ln -s $GOPATH/bin/shell2http ~/bin/shell2http

Usage:
	shell2http /path "shell command" /path2 "shell command2" ...

Examples:
	shell2http /top "top -l 1 | head -10"
	shell2http /date date /ps "ps aux"
	shell2http /env 'printenv | sort' /env/path 'echo $PATH' /env/gopath 'echo $GOPATH'
	shell2http /shell_vars_json 'perl -MJSON -E "say to_json(\%ENV)"'
	shell2http /cal_html 'echo "
Calendar
Date: $(date)

$(cal $(date +%Y))
"'

Update:
	go get -u github.com/msoap/shell2http

*/
package main

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

// default port for http-server
const PORT = "8080"

// ------------------------------------------------------------------
const INDEX_HTML = `
<!DOCTYPE html>

	<title>Index shell commands</title>

Index shell commands

		%s

/exit

`

// ------------------------------------------------------------------
// one command type
type t_command struct {
	path string
	cmd  string
}

// ------------------------------------------------------------------
// parse argeuments
func get_handlers() ([]t_command, error) {
	// need >= 2 argeuments and count of it must be even
	if len(os.Args) < 3 || len(os.Args)%2 == 0 {
		return nil, fmt.Errorf(`usage: shell2http /path "shell command" /path2 "shell command2"`)
	}

	cmd_handlers := []t_command{}

	args_i := 1
	for args_i < len(os.Args) {
		path, cmd := os.Args[args_i], os.Args[args_i+1]
		if path[0] != '/' {
			return nil, fmt.Errorf("error: path %s dont starts with /", path)
		}
		cmd_handlers = append(cmd_handlers, t_command{path: path, cmd: cmd})
		args_i += 2
	}

	return cmd_handlers, nil
}

// ------------------------------------------------------------------
// setup http handlers
func setup_handlers(cmd_handlers []t_command, the_end chan interface{}) {
	index_li_html := ""
	for _, row := range cmd_handlers {
		path, cmd := row.path, row.cmd
		shell_handler := func(rw http.ResponseWriter, req *http.Request) {
			fmt.Println("GET", path)

			shell_out, err := exec.Command("sh", "-c", cmd).Output()
			if err != nil {
				fmt.Println("exec error: ", err)
				fmt.Fprint(rw, "exec error: ", err)
			} else {
				fmt.Fprint(rw, string(shell_out))
			}

			return
		}

		fmt.Printf("register: %s (%s)\n", path, cmd)
		http.HandleFunc(path, shell_handler)
		index_li_html += fmt.Sprintf(`<li><a href="%s">%s</a></li>`, path, path)
	}

	// --------------
	index_html := fmt.Sprintf(INDEX_HTML, index_li_html)
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		fmt.Println("GET /")
		fmt.Fprint(rw, index_html)

		return
	})

	// --------------
	http.HandleFunc("/exit", func(rw http.ResponseWriter, req *http.Request) {
		fmt.Println("GET /exit")
		fmt.Fprint(rw, "Bye...")
		the_end <- nil

		return
	})
}

// ------------------------------------------------------------------
func main() {
	cmd_handlers, err := get_handlers()
	if err != nil {
		fmt.Println(err)
		return
	}
	the_end := make(chan interface{})
	setup_handlers(cmd_handlers, the_end)

	fmt.Println("listen http://localhost:" + PORT + "/")
	go http.ListenAndServe(":"+PORT, nil)
	<-the_end // wait for exit command
}
<|endoftext|>


<commit_before>/*
Execute shell commands via http server

Install:
	go get github.com/msoap/shell2http
	ln -s $GOPATH/bin/shell2http ~/bin/shell2http

Usage:
	shell2http [options] /path "shell command" /path2 "shell command2" ...
	options:
		-host="host": host for http server
		-host=      : for bind to all hosts
		-port=NNNN  : port for http server
		-help

Examples:
	shell2http /top "top -l 1 | head -10"
	shell2http /date date /ps "ps aux"
	shell2http /env 'printenv | sort' /env/path 'echo $PATH' /env/gopath 'echo $GOPATH'
	shell2http /shell_vars_json 'perl -MJSON -E "say to_json(\%ENV)"'
	shell2http /cal_html 'echo "
Calendar
Date: $(date)

$(cal $(date +%Y))
"'

Update:
	go get -u github.com/msoap/shell2http

*/
package main

import (
	"flag"
	"fmt"
	"net/http"
	"os"
	"os/exec"
)

// default port for http-server
const PORT = 8080

// default host for bind
const HOST = "localhost"

// ------------------------------------------------------------------
const INDEX_HTML = `
<!DOCTYPE html>

	<title>Index shell commands</title>

Index shell commands

		%s

/exit

`

// ------------------------------------------------------------------
// one command type
type t_command struct {
	path string
	cmd  string
}

// ------------------------------------------------------------------
// parse arguments
func get_config() (cmd_handlers []t_command, host string, port int, err error) {
	flag.IntVar(&port, "port", PORT, "port for http server")
	flag.StringVar(&host, "host", HOST, "host for http server")
	usage_str := fmt.Sprintf(`usage: %s [options] /path "shell command" /path2 "shell command2"`, os.Args[0])
	flag.Usage = func() {
		fmt.Println(usage_str)
		flag.PrintDefaults()
		os.Exit(0)
	}
	flag.Parse()

	// need >= 2 arguments and count of it must be even
	args := flag.Args()
	if len(args) < 2 || len(args)%2 == 1 {
		return nil, host, port, fmt.Errorf(usage_str)
	}

	args_i := 0
	for args_i < len(args) {
		path, cmd := args[args_i], args[args_i+1]
		if path[0] != '/' {
			return nil, host, port, fmt.Errorf("error: path %s dont starts with /", path)
		}
		cmd_handlers = append(cmd_handlers, t_command{path: path, cmd: cmd})
		args_i += 2
	}

	return cmd_handlers, host, port, nil
}

// ------------------------------------------------------------------
// setup http handlers
func setup_handlers(cmd_handlers []t_command) {
	index_li_html := ""
	for _, row := range cmd_handlers {
		path, cmd := row.path, row.cmd
		shell_handler := func(rw http.ResponseWriter, req *http.Request) {
			fmt.Println("GET", path)

			shell_out, err := exec.Command("sh", "-c", cmd).Output()
			if err != nil {
				fmt.Println("exec error: ", err)
				fmt.Fprint(rw, "exec error: ", err)
			} else {
				fmt.Fprint(rw, string(shell_out))
			}

			return
		}

		fmt.Printf("register: %s (%s)\n", path, cmd)
		http.HandleFunc(path, shell_handler)
		index_li_html += fmt.Sprintf(`<li><a href="%s">%s</a></li>`, path, path)
	}

	// --------------
	index_html := fmt.Sprintf(INDEX_HTML, index_li_html)
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		fmt.Println("GET /")
		fmt.Fprint(rw, index_html)

		return
	})

	// --------------
	http.HandleFunc("/exit", func(rw http.ResponseWriter, req *http.Request) {
		fmt.Println("GET /exit")
		fmt.Fprint(rw, "Bye...")
		go os.Exit(0)

		return
	})
}

// ------------------------------------------------------------------
func main() {
	cmd_handlers, host, port, err := get_config()
	if err != nil {
		fmt.Println(err)
		return
	}
	setup_handlers(cmd_handlers)

	adress := fmt.Sprintf("%s:%d", host, port)
	fmt.Printf("listen http://%s/\n", adress)
	err = http.ListenAndServe(adress, nil)
	if err != nil {
		fmt.Println(err)
		return
	}
}
<commit_msg>Use log instead fmt for logging<commit_after>/*
Execute shell commands via http server

Install:
	go get github.com/msoap/shell2http
	ln -s $GOPATH/bin/shell2http ~/bin/shell2http

Usage:
	shell2http [options] /path "shell command" /path2 "shell command2" ...
	options:
		-host="host": host for http server
		-host=      : for bind to all hosts
		-port=NNNN  : port for http server
		-help

Examples:
	shell2http /top "top -l 1 | head -10"
	shell2http /date date /ps "ps aux"
	shell2http /env 'printenv | sort' /env/path 'echo $PATH' /env/gopath 'echo $GOPATH'
	shell2http /shell_vars_json 'perl -MJSON -E "say to_json(\%ENV)"'
	shell2http /cal_html 'echo "
Calendar
Date: $(date)

$(cal $(date +%Y))
"'

Update:
	go get -u github.com/msoap/shell2http

*/
package main

import (
	"flag"
	"fmt"
	"log"
	"net/http"
	"os"
	"os/exec"
)

// default port for http-server
const PORT = 8080

// default host for bind
const HOST = "localhost"

// ------------------------------------------------------------------
const INDEX_HTML = `
<!DOCTYPE html>

	<title>Index shell commands</title>

Index shell commands

		%s

/exit

`

// ------------------------------------------------------------------
// one command type
type t_command struct {
	path string
	cmd  string
}

// ------------------------------------------------------------------
// parse arguments
func get_config() (cmd_handlers []t_command, host string, port int, err error) {
	flag.IntVar(&port, "port", PORT, "port for http server")
	flag.StringVar(&host, "host", HOST, "host for http server")
	flag.Usage = func() {
		fmt.Printf("usage: %s [options] /path \"shell command\" /path2 \"shell command2\"\n", os.Args[0])
		flag.PrintDefaults()
		os.Exit(0)
	}
	flag.Parse()

	// need >= 2 arguments and count of it must be even
	args := flag.Args()
	if len(args) < 2 || len(args)%2 == 1 {
		return nil, host, port, fmt.Errorf("error: need pairs of path and shell command")
	}

	args_i := 0
	for args_i < len(args) {
		path, cmd := args[args_i], args[args_i+1]
		if path[0] != '/' {
			return nil, host, port, fmt.Errorf("error: path %s dont starts with /", path)
		}
		cmd_handlers = append(cmd_handlers, t_command{path: path, cmd: cmd})
		args_i += 2
	}

	return cmd_handlers, host, port, nil
}

// ------------------------------------------------------------------
// setup http handlers
func setup_handlers(cmd_handlers []t_command) {
	index_li_html := ""
	for _, row := range cmd_handlers {
		path, cmd := row.path, row.cmd
		shell_handler := func(rw http.ResponseWriter, req *http.Request) {
			log.Println("GET", path)

			shell_out, err := exec.Command("sh", "-c", cmd).Output()
			if err != nil {
				log.Println("exec error: ", err)
				fmt.Fprint(rw, "exec error: ", err)
			} else {
				fmt.Fprint(rw, string(shell_out))
			}

			return
		}

		log.Printf("register: %s (%s)\n", path, cmd)
		http.HandleFunc(path, shell_handler)
		index_li_html += fmt.Sprintf(`<li><a href="%s">%s</a></li>`, path, path)
	}

	// --------------
	index_html := fmt.Sprintf(INDEX_HTML, index_li_html)
	http.HandleFunc("/", func(rw http.ResponseWriter, req *http.Request) {
		log.Println("GET /")
		fmt.Fprint(rw, index_html)

		return
	})

	// --------------
	http.HandleFunc("/exit", func(rw http.ResponseWriter, req *http.Request) {
		log.Println("GET /exit")
		fmt.Fprint(rw, "Bye...")
		go os.Exit(0)

		return
	})
}

// ------------------------------------------------------------------
func main() {
	cmd_handlers, host, port, err := get_config()
	if err != nil {
		log.Println(err)
		return
	}
	setup_handlers(cmd_handlers)

	adress := fmt.Sprintf("%s:%d", host, port)
	log.Printf("listen http://%s/\n", adress)
	err = http.ListenAndServe(adress, nil)
	if err != nil {
		log.Println(err)
		return
	}
}
<|endoftext|>


<commit_before>package gist

import (
	"code.google.com/p/goauth2/oauth"
	"github.com/google/go-github/github"
	"io/ioutil"
)

type GistStorage struct {
	connexion *github.Client
	transport *oauth.Transport

	Token string
	User  string
}

func NewGistStorage(user, token string) *GistStorage {
	transport := &oauth.Transport{
		Token: &oauth.Token{AccessToken: token},
	}

	return &GistStorage{
		transport: transport,
		Token:     token,
		User:      user,
	}
}

func (gs *GistStorage) Connect() {
	gs.connexion = github.NewClient(gs.transport.Client())
}

// Push exports the local encrypted trousseau data store to
// a Github private gist
func (gs *GistStorage) Push(localPath, remotePath string) (err error) {
	var public bool = false

	// Read the encrypted data store content
	fileBytes, err := ioutil.ReadFile(localPath)
	if err != nil {
		return err
	}
	fileContent := string(fileBytes)

	// Build a Gist file store
	files := map[github.GistFilename]github.GistFile{
		github.GistFilename(remotePath): github.GistFile{
			Content: &fileContent,
		},
	}

	// Create a gist representation ready to be
	// pushed over network
	gist := &github.Gist{
		Public: &public,
		Files:  files,
	}

	// Push the gist to github
	_, _, err = gs.connexion.Gists.Create(gist)
	if err != nil {
		return err
	}

	return nil
}

// Pull imports the encrypted trousseau data store from
// a Github gist
func (gs *GistStorage) Pull(remotePath, localPath string) (err error) {
	var gist *github.Gist

	// Fetch the user's gists list
	gists, _, err := gs.connexion.Gists.List(gs.User, nil)
	if err != nil {
		return err
	}

	// Find a gist containing trousseau data store
	for _, g := range gists {
		for k, _ := range g.Files {
			if string(k) == remotePath {
				gist = &g
				break
			}
		}

		if gist != nil {
			break
		}
	}

	// Download the gist file content
	gist, _, err = gs.connexion.Gists.Get(*gist.ID)

	// Write the downloaded file content to the local trousseau
	// data store file
	fileContent := []byte(*gist.Files[github.GistFilename(remotePath)].Content)
	err = ioutil.WriteFile(localPath, fileContent, 0600)
	if err != nil {
		return err
	}

	return nil
}
<commit_msg>Refresh goauth2/oauth dependency<commit_after>package gist

import (
	"golang.org/x/oauth2"
	"github.com/google/go-github/github"
	"io/ioutil"
)

type GistStorage struct {
	connexion *github.Client
	transport *oauth.Transport

	Token string
	User  string
}

func NewGistStorage(user, token string) *GistStorage {
	transport := &oauth.Transport{
		Token: &oauth.Token{AccessToken: token},
	}

	return &GistStorage{
		transport: transport,
		Token:     token,
		User:      user,
	}
}

func (gs *GistStorage) Connect() {
	gs.connexion = github.NewClient(gs.transport.Client())
}

// Push exports the local encrypted trousseau data store to
// a Github private gist
func (gs *GistStorage) Push(localPath, remotePath string) (err error) {
	var public bool = false

	// Read the encrypted data store content
	fileBytes, err := ioutil.ReadFile(localPath)
	if err != nil {
		return err
	}
	fileContent := string(fileBytes)

	// Build a Gist file store
	files := map[github.GistFilename]github.GistFile{
		github.GistFilename(remotePath): github.GistFile{
			Content: &fileContent,
		},
	}

	// Create a gist representation ready to be
	// pushed over network
	gist := &github.Gist{
		Public: &public,
		Files:  files,
	}

	// Push the gist to github
	_, _, err = gs.connexion.Gists.Create(gist)
	if err != nil {
		return err
	}

	return nil
}

// Pull imports the encrypted trousseau data store from
// a Github gist
func (gs *GistStorage) Pull(remotePath, localPath string) (err error) {
	var gist *github.Gist

	// Fetch the user's gists list
	gists, _, err := gs.connexion.Gists.List(gs.User, nil)
	if err != nil {
		return err
	}

	// Find a gist containing trousseau data store
	for _, g := range gists {
		for k, _ := range g.Files {
			if string(k) == remotePath {
				gist = &g
				break
			}
		}

		if gist != nil {
			break
		}
	}

	// Download the gist file content
	gist, _, err = gs.connexion.Gists.Get(*gist.ID)

	// Write the downloaded file content to the local trousseau
	// data store file
	fileContent := []byte(*gist.Files[github.GistFilename(remotePath)].Content)
	err = ioutil.WriteFile(localPath, fileContent, 0600)
	if err != nil {
		return err
	}

	return nil
}
<|endoftext|>