<commit_before>package errors

import (
	"fmt"

	"go.uber.org/zap/zapcore"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var mapGrpcCode = map[int]codes.Code{
	400: 3,
	401: 16,
	403: 7,
	404: 5,
	441: 4,
	500: 13,
	501: 12,
	503: 14,
	520: 2,
}

type HTTPError struct {
	status  int
	Code    string `json:"error"`
	Message string `json:"error_description"`
	cause   error
}

func (e *HTTPError) Error() string { return e.Message }
func (e *HTTPError) Cause() error  { return e.cause }
func (e *HTTPError) WithCause(err error) *HTTPError {
	e.cause = err
	return e
}

func (e *HTTPError) MarshalLogObject(enc zapcore.ObjectEncoder) error {
	enc.AddString("error_code", e.Code)
	enc.AddString("error_description", e.Message)
	if e.cause != nil {
		enc.AddString("error_cause", e.cause.Error())
	}

	return nil
}

func Error(status int, code, msg string) *HTTPError {
	return &HTTPError{status, code, msg, nil}
}

func Errorf(status int, code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{status, code, fmt.Sprintf(format, v...), nil}
}

func BadRequest(code, msg string) *HTTPError {
	return &HTTPError{400, code, msg, nil}
}

func BadRequestf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{400, code, fmt.Sprintf(format, v...), nil}
}

func Unauthorized(code, msg string) *HTTPError {
	return &HTTPError{401, code, msg, nil}
}

func Unauthorizedf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{401, code, fmt.Sprintf(format, v...), nil}
}

func Forbidden(code, msg string) *HTTPError {
	return &HTTPError{403, code, msg, nil}
}

func Forbiddenf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{403, code, fmt.Sprintf(format, v...), nil}
}

func NotFound(code, msg string) *HTTPError {
	return &HTTPError{400, code, msg, nil}
}

func NotFoundf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{404, code, fmt.Sprintf(format, v...), nil}
}

func InternalError(code, msg string) *HTTPError {
	return &HTTPError{400, code, msg, nil}
}

func InternalErrorf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{500, code, fmt.Sprintf(format, v...), nil}
}

func Timeout(code, msg string) *HTTPError {
	return &HTTPError{441, code, msg, nil}
}

func Timeoutf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{441, code, fmt.Sprintf(format, v...), nil}
}

func NotImplement(code, msg string) *HTTPError {
	return &HTTPError{501, code, msg, nil}
}

func NotImplementf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{501, code, fmt.Sprintf(format, v...), nil}
}

func Unavailable(code, msg string) *HTTPError {
	return &HTTPError{503, code, msg, nil}
}

func Unavailablef(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{503, code, fmt.Sprintf(format, v...), nil}
}

func UnknownError(code, msg string) *HTTPError {
	return &HTTPError{520, code, msg, nil}
}

func UnknownErrorf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{520, code, fmt.Sprintf(format, v...), nil}
}

func Cause(err error) error {
	herr, ok := err.(*HTTPError)
	if !ok {
		return err
	}

	return herr.Cause()
}

func FromError(err error) (*HTTPError, bool) {
	herr, ok := err.(*HTTPError)
	return herr, ok
}

func ToGRPC(err error) error {
	herr, ok := err.(*HTTPError)
	if !ok {
		return status.Error(2, err.Error())
	}

	c := mapGrpcCode[herr.status]
	return status.Errorf(c, "error=%s error_description=%s", herr.Code, herr.Message)
}

func errStatus(err error) int {
	herr, ok := err.(*HTTPError)
	if !ok {
		return 0
	}

	return herr.status
}

func IsNotFound(err error) bool {
	return err != nil && errStatus(err) == 404
}

func IsInternalError(err error) bool {
	return err != nil && errStatus(err) == 500
}

func IsBadRequest(err error) bool {
	return err != nil && errStatus(err) == 400
}

func IsUnauthorized(err error) bool {
	return err != nil && errStatus(err) == 401
}

func IsForbidden(err error) bool {
	return err != nil && errStatus(err) == 403
}
<commit_msg>add wrap<commit_after>package errors

import (
	"fmt"

	"go.uber.org/zap/zapcore"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
)

var mapGrpcCode = map[int]codes.Code{
	400: 3,
	401: 16,
	403: 7,
	404: 5,
	441: 4,
	500: 13,
	501: 12,
	503: 14,
	520: 2,
}

type HTTPError struct {
	status  int
	Code    string `json:"error"`
	Message string `json:"error_description"`
	cause   error
}

func (e *HTTPError) Error() string { return e.Message }
func (e *HTTPError) Cause() error  { return e.cause }
func (e *HTTPError) WithCause(err error) *HTTPError {
	e.cause = err
	return e
}

func (e *HTTPError) MarshalLogObject(enc zapcore.ObjectEncoder) error {
	enc.AddString("error_code", e.Code)
	enc.AddString("error_description", e.Message)
	if e.cause != nil {
		enc.AddString("error_cause", e.cause.Error())
	}

	return nil
}

func Wrap(err error, httpError *HTTPError) error {
	if err != nil {
		return nil
	}

	return httpError.WithCause(err)
}

func Error(status int, code, msg string) *HTTPError {
	return &HTTPError{status, code, msg, nil}
}

func Errorf(status int, code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{status, code, fmt.Sprintf(format, v...), nil}
}

func BadRequest(code, msg string) *HTTPError {
	return &HTTPError{400, code, msg, nil}
}

func BadRequestf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{400, code, fmt.Sprintf(format, v...), nil}
}

func Unauthorized(code, msg string) *HTTPError {
	return &HTTPError{401, code, msg, nil}
}

func Unauthorizedf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{401, code, fmt.Sprintf(format, v...), nil}
}

func Forbidden(code, msg string) *HTTPError {
	return &HTTPError{403, code, msg, nil}
}

func Forbiddenf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{403, code, fmt.Sprintf(format, v...), nil}
}

func NotFound(code, msg string) *HTTPError {
	return &HTTPError{400, code, msg, nil}
}

func NotFoundf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{404, code, fmt.Sprintf(format, v...), nil}
}

func InternalError(code, msg string) *HTTPError {
	return &HTTPError{400, code, msg, nil}
}

func InternalErrorf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{500, code, fmt.Sprintf(format, v...), nil}
}

func Timeout(code, msg string) *HTTPError {
	return &HTTPError{441, code, msg, nil}
}

func Timeoutf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{441, code, fmt.Sprintf(format, v...), nil}
}

func NotImplement(code, msg string) *HTTPError {
	return &HTTPError{501, code, msg, nil}
}

func NotImplementf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{501, code, fmt.Sprintf(format, v...), nil}
}

func Unavailable(code, msg string) *HTTPError {
	return &HTTPError{503, code, msg, nil}
}

func Unavailablef(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{503, code, fmt.Sprintf(format, v...), nil}
}

func UnknownError(code, msg string) *HTTPError {
	return &HTTPError{520, code, msg, nil}
}

func UnknownErrorf(code, format string, v ...interface{}) *HTTPError {
	return &HTTPError{520, code, fmt.Sprintf(format, v...), nil}
}

func Cause(err error) error {
	herr, ok := err.(*HTTPError)
	if !ok {
		return err
	}

	return herr.Cause()
}

func FromError(err error) (*HTTPError, bool) {
	herr, ok := err.(*HTTPError)
	return herr, ok
}

func ToGRPC(err error) error {
	herr, ok := err.(*HTTPError)
	if !ok {
		return status.Error(2, err.Error())
	}

	c := mapGrpcCode[herr.status]
	return status.Errorf(c, "error=%s error_description=%s", herr.Code, herr.Message)
}

func errStatus(err error) int {
	herr, ok := err.(*HTTPError)
	if !ok {
		return 0
	}

	return herr.status
}

func IsNotFound(err error) bool {
	return err != nil && errStatus(err) == 404
}

func IsInternalError(err error) bool {
	return err != nil && errStatus(err) == 500
}

func IsBadRequest(err error) bool {
	return err != nil && errStatus(err) == 400
}

func IsUnauthorized(err error) bool {
	return err != nil && errStatus(err) == 401
}

func IsForbidden(err error) bool {
	return err != nil && errStatus(err) == 403
}
<|endoftext|>


<commit_before>package cpio

import (
	"bytes"
	"io"
	"os"
	"strconv"
	"time"
)

const (
	svr4MaxNameSize = 4096 // MAX_PATH
	svr4MaxFileSize = 4294967295
)

func readHex(s string) int64 {
	// errors are ignored and 0 returned
	i, _ := strconv.ParseInt(s, 16, 64)
	return i
}

func readSVR4Header(r io.Reader) (*Header, error) {
	var buf [110]byte
	if _, err := r.Read(buf[:]); err != nil {
		return nil, err
	}

	// TODO: check endianness

	// check magic
	hasCRC := false
	if !bytes.HasPrefix(buf[:], []byte{0x30, 0x37, 0x30, 0x37, 0x30}) { // 07070
		return nil, ErrHeader
	}
	if buf[5] == 0x32 { // '2'
		hasCRC = true
	} else if buf[5] != 0x31 { // '1'
		return nil, ErrHeader
	}

	asc := string(buf[:])
	hdr := &Header{}

	hdr.Inode = readHex(asc[6:14])
	hdr.Mode = os.FileMode(readHex(asc[14:22]))
	hdr.UID = int(readHex(asc[22:30]))
	hdr.GID = int(readHex(asc[30:38]))
	hdr.Links = int(readHex(asc[38:46]))
	hdr.ModTime = time.Unix(readHex(asc[46:54]), 0)
	hdr.Size = readHex(asc[54:62])
	if hdr.Size > svr4MaxFileSize {
		return nil, ErrHeader
	}
	nameSize := readHex(asc[94:102])
	if nameSize > svr4MaxNameSize {
		return nil, ErrHeader
	}
	hdr.Checksum = Checksum(readHex(asc[102:110]))
	if !hasCRC && hdr.Checksum != 0 {
		return nil, ErrHeader
	}

	name := make([]byte, nameSize)
	if _, err := io.ReadFull(r, name); err != nil {
		return nil, err
	}
	if bytes.Equal(name, headerEOF) {
		return nil, io.EOF
	}
	hdr.Name = string(name[:nameSize-1])

	// padding between end of file and next header
	hdr.pad = (4 - (hdr.Size % 4)) % 4

	// skip to end of header/start of file
	pad := (4 - (len(buf)+len(name))%4) % 4
	if pad > 0 {
		if _, err := io.ReadFull(r, buf[:pad]); err != nil {
			return nil, nil
		}
	}

	return hdr, nil
}
<commit_msg>Fixed potential under-read<commit_after>package cpio

import (
	"bytes"
	"io"
	"os"
	"strconv"
	"time"
)

const (
	svr4MaxNameSize = 4096 // MAX_PATH
	svr4MaxFileSize = 4294967295
)

func readHex(s string) int64 {
	// errors are ignored and 0 returned
	i, _ := strconv.ParseInt(s, 16, 64)
	return i
}

func readSVR4Header(r io.Reader) (*Header, error) {
	var buf [110]byte
	if _, err := io.ReadFull(r, buf[:]); err != nil {
		return nil, err
	}

	// TODO: check endianness

	// check magic
	hasCRC := false
	if !bytes.HasPrefix(buf[:], []byte{0x30, 0x37, 0x30, 0x37, 0x30}) { // 07070
		return nil, ErrHeader
	}
	if buf[5] == 0x32 { // '2'
		hasCRC = true
	} else if buf[5] != 0x31 { // '1'
		return nil, ErrHeader
	}

	asc := string(buf[:])
	hdr := &Header{}

	hdr.Inode = readHex(asc[6:14])
	hdr.Mode = os.FileMode(readHex(asc[14:22]))
	hdr.UID = int(readHex(asc[22:30]))
	hdr.GID = int(readHex(asc[30:38]))
	hdr.Links = int(readHex(asc[38:46]))
	hdr.ModTime = time.Unix(readHex(asc[46:54]), 0)
	hdr.Size = readHex(asc[54:62])
	if hdr.Size > svr4MaxFileSize {
		return nil, ErrHeader
	}
	nameSize := readHex(asc[94:102])
	if nameSize > svr4MaxNameSize {
		return nil, ErrHeader
	}
	hdr.Checksum = Checksum(readHex(asc[102:110]))
	if !hasCRC && hdr.Checksum != 0 {
		return nil, ErrHeader
	}

	name := make([]byte, nameSize)
	if _, err := io.ReadFull(r, name); err != nil {
		return nil, err
	}
	if bytes.Equal(name, headerEOF) {
		return nil, io.EOF
	}
	hdr.Name = string(name[:nameSize-1])

	// padding between end of file and next header
	hdr.pad = (4 - (hdr.Size % 4)) % 4

	// skip to end of header/start of file
	pad := (4 - (len(buf)+len(name))%4) % 4
	if pad > 0 {
		if _, err := io.ReadFull(r, buf[:pad]); err != nil {
			return nil, nil
		}
	}

	return hdr, nil
}
<|endoftext|>


<commit_before>package tasker

import (
	"errors"
	"time"

	"github.com/NoneBorder/dora"
	"github.com/astaxie/beego/orm"
)

const (
	TaskStatPending = "pending"
	TaskStatRunning = "running"
	TaskStatRetry   = "retry"
	TaskStatFailed  = "failed"
	TaskStatSuccess = "success"
)

// Task is the core object for tasker package.
type Task struct {
	Id       int
	Topic    string
	Status   string
	Timeout  int // 超时ms
	Retry    int
	Input    string `orm:"type(text)"`
	WorkerId uint64
	Created  time.Time `orm:"auto_now_add"`
	Updated  time.Time `orm:"auto_now"`
	Log      string    `orm:"type(text)"`
}

// ConsumeFn represents consume func definition.
type ConsumeFn func(Input string, WorkerID uint64) (err error)

func (self *Task) TableIndex() [][]string {
	return [][]string{
		[]string{"Topic", "Status"},
	}
}

func (self *Task) TableEngine() string {
	return "INNODB"
}

// NewSimpleTask is new task with default settings.
func NewSimpleTask(topic, input string) *Task {
	return &Task{
		Topic:    topic,
		Status:   TaskStatPending,
		Timeout:  5000,
		Retry:    3,
		Input:    input,
		WorkerId: 0,
	}
}

// Publish Task to Msg Queue.
func (self *Task) Publish() (err error) {
	o := orm.NewOrm()
	if _, err = o.Insert(self); err == nil {
		Stat(self.Topic, TaskStatPending, time.Duration(0))
	}
	return
}

func (self *Task) exec(fn ConsumeFn) (err error) {
	errC := make(chan error)
	go func() {
		errC <- fn(self.Input, self.WorkerId)
	}()

	select {
	case err = <-errC:
	case <-time.After(time.Duration(self.Timeout) * time.Millisecond):
		err = errors.New("execute task timeout")
	}

	return
}

func (self *Task) consume(fn ConsumeFn) bool {
	startT := time.Now().Local()

	err := self.exec(fn)
	success := err == nil

	if !success {
		// failed
		self.Log += err.Error() + "\n"
		self.Status = TaskStatFailed
		self.Retry -= 1
		if self.Retry > 0 {
			self.Status = TaskStatRetry
		}
	} else {
		self.Status = TaskStatSuccess
	}

	// stat task exec
	Stat(self.Topic, self.Status, time.Since(startT))

	// update db record
	self.WorkerId = 0
	o := orm.NewOrm()
	for i := 0; i < 3; i++ {
		if _, err := o.Update(self); err != nil {
			dora.Error("set task state failed: err=%s, task=%s", err.Error(), self)
		} else {
			break
		}
	}

	return success
}

// Consume a topic task.
func Consume(topic string, fn ConsumeFn, concurency ...int) (int, error) {
	concurency = append(concurency, 1)

	workerID, err := UniqID.NextID()
	if err != nil {
		return 0, err
	}
	o := orm.NewOrm()

	_, err = o.Raw(`UPDATE task SET status=?, worker_id=0 WHERE topic=? AND status=?
		AND TIMESTAMPDIFF(SECOND, updated, now())*1000-5000>timeout`,
		TaskStatPending, topic, TaskStatRunning,
	).Exec()
	if err != nil {
		dora.Error("update dead running task to waiting failed: %s", err.Error())
	}

	res, err := o.Raw(`UPDATE task SET status=?, worker_id=? WHERE
		topic=? AND worker_id=0 AND status IN (?,?) LIMIT ?`,
		TaskStatRunning, workerID, topic, TaskStatPending, TaskStatRetry, concurency[0],
	).Exec()
	if err != nil {
		// not update db
		return 0, err
	}

	num, _ := res.RowsAffected()
	if num == 0 {
		// no task for consume
		return 0, nil
	}

	tasks := []*Task{}
	_, err = o.Raw("SELECT * FROM task WHERE `topic`=? AND `status`=? AND `worker_id`=?",
		topic, TaskStatRunning, workerID,
	).QueryRows(&tasks)
	if len(tasks) == 0 || err != nil {
		return 0, err
	}

	waitChannel := make(chan bool)
	for _, t := range tasks {
		go func(t *Task) {
			waitChannel <- t.consume(fn)
		}(t)
	}

	successTasks := 0
	for _ = range tasks {
		if <-waitChannel {
			successTasks += 1
		}
	}

	return successTasks, nil
}
<commit_msg>仅在 master 上对已经僵死的 task 进行重置，减轻 DB 压力<commit_after>package tasker

import (
	"errors"
	"time"

	"github.com/NoneBorder/dora"
	"github.com/NoneBorder/tasker"
	"github.com/astaxie/beego/orm"
)

const (
	TaskStatPending = "pending"
	TaskStatRunning = "running"
	TaskStatRetry   = "retry"
	TaskStatFailed  = "failed"
	TaskStatSuccess = "success"
)

// Task is the core object for tasker package.
type Task struct {
	Id       int
	Topic    string
	Status   string
	Timeout  int // 超时ms
	Retry    int
	Input    string `orm:"type(text)"`
	WorkerId uint64
	Created  time.Time `orm:"auto_now_add"`
	Updated  time.Time `orm:"auto_now"`
	Log      string    `orm:"type(text)"`
}

// ConsumeFn represents consume func definition.
type ConsumeFn func(Input string, WorkerID uint64) (err error)

func (self *Task) TableIndex() [][]string {
	return [][]string{
		[]string{"Topic", "Status"},
	}
}

func (self *Task) TableEngine() string {
	return "INNODB"
}

// NewSimpleTask is new task with default settings.
func NewSimpleTask(topic, input string) *Task {
	return &Task{
		Topic:    topic,
		Status:   TaskStatPending,
		Timeout:  5000,
		Retry:    3,
		Input:    input,
		WorkerId: 0,
	}
}

// Publish Task to Msg Queue.
func (self *Task) Publish() (err error) {
	o := orm.NewOrm()
	if _, err = o.Insert(self); err == nil {
		Stat(self.Topic, TaskStatPending, time.Duration(0))
	}
	return
}

func (self *Task) exec(fn ConsumeFn) (err error) {
	errC := make(chan error)
	go func() {
		errC <- fn(self.Input, self.WorkerId)
	}()

	select {
	case err = <-errC:
	case <-time.After(time.Duration(self.Timeout) * time.Millisecond):
		err = errors.New("execute task timeout")
	}

	return
}

func (self *Task) consume(fn ConsumeFn) bool {
	startT := time.Now().Local()

	err := self.exec(fn)
	success := err == nil

	if !success {
		// failed
		self.Log += err.Error() + "\n"
		self.Status = TaskStatFailed
		self.Retry -= 1
		if self.Retry > 0 {
			self.Status = TaskStatRetry
		}
	} else {
		self.Status = TaskStatSuccess
	}

	// stat task exec
	Stat(self.Topic, self.Status, time.Since(startT))

	// update db record
	self.WorkerId = 0
	o := orm.NewOrm()
	for i := 0; i < 3; i++ {
		if _, err := o.Update(self); err != nil {
			dora.Error("set task state failed: err=%s, task=%s", err.Error(), self)
		} else {
			break
		}
	}

	return success
}

// Consume a topic task.
func Consume(topic string, fn ConsumeFn, concurency ...int) (int, error) {
	concurency = append(concurency, 1)

	workerID, err := UniqID.NextID()
	if err != nil {
		return 0, err
	}
	o := orm.NewOrm()

	if tasker.IsMaster {
		// 仅在 master 上对已经僵死的 task 进行重置，减轻 DB 压力
		_, err = o.Raw(`UPDATE task SET status=?, worker_id=0 WHERE topic=? AND status=?
		AND TIMESTAMPDIFF(SECOND, updated, now())*1000-5000>timeout`,
			TaskStatPending, topic, TaskStatRunning,
		).Exec()
		if err != nil {
			dora.Error("update dead running task to waiting failed: %s", err.Error())
		}
	}

	res, err := o.Raw(`UPDATE task SET status=?, worker_id=? WHERE
		topic=? AND worker_id=0 AND status IN (?,?) LIMIT ?`,
		TaskStatRunning, workerID, topic, TaskStatPending, TaskStatRetry, concurency[0],
	).Exec()
	if err != nil {
		// not update db
		return 0, err
	}

	num, _ := res.RowsAffected()
	if num == 0 {
		// no task for consume
		return 0, nil
	}

	tasks := []*Task{}
	_, err = o.Raw("SELECT * FROM task WHERE `topic`=? AND `status`=? AND `worker_id`=?",
		topic, TaskStatRunning, workerID,
	).QueryRows(&tasks)
	if len(tasks) == 0 || err != nil {
		return 0, err
	}

	waitChannel := make(chan bool)
	for _, t := range tasks {
		go func(t *Task) {
			waitChannel <- t.consume(fn)
		}(t)
	}

	successTasks := 0
	for _ = range tasks {
		if <-waitChannel {
			successTasks += 1
		}
	}

	return successTasks, nil
}
<|endoftext|>


<commit_before>// Copyright 2016 Stefan Nyman.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package hellosign

import (
	"errors"
	"net/http"
)

type TeamAPI struct {
	*hellosign
}

func NewTeamAPI(apiKey string) *TeamAPI {
	return &TeamAPI{newHellosign(apiKey)}
}

type Team struct {
	Name     string `json:"name"`
	Accounts []struct {
		AccountID    string `json:"account_id"`
		EmailAddress string `json:"email_address"`
		RoleCode     string `json:"role_code"`
	} `json:"accounts"`
	InvitedAccounts []struct {
		AccountID    string `json:"account_id"`
		EmailAddress string `json:"email_address"`
		RoleCode     string `json:"role_code"`
	} `json:"invited_accounts"`
}

type teamRaw struct {
	Team Team `json:"team"`
}

func (c *TeamAPI) Get() (*Team, error) {
	team := &teamRaw{}
	if err := c.getAndParse("team", nil, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}

func (c *TeamAPI) Create(name string) (*Team, error) {
	team := &teamRaw{}
	if err := c.postFormAndParse("team/create", &struct {
		Name string `form:"name"`
	}{
		Name: name,
	}, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}

func (c *TeamAPI) Update(name string) (*Team, error) {
	team := &teamRaw{}
	if err := c.postFormAndParse("team", &struct {
		Name string `form:"name"`
	}{
		Name: name,
	}, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}

func (c *TeamAPI) Delete() (bool, error) {
	resp, err := c.postForm("team/destroy", nil)
	if err != nil {
		return false, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return false, errors.New(resp.Status)
	}
	return true, nil
}

func (c *TeamAPI) AddUser(accountID, emailAddress *string) (*Team, error) {
	if accountID != nil && emailAddress != nil {
		return nil, errors.New("Specify either account id or email address, both given")
	}
	team := &teamRaw{}
	if err := c.postFormAndParse("team/add_member", &struct {
		AccountID    *string `form:"account_id,omitempty"`
		EmailAddress *string `form:"email_address,omitempty"`
	}{
		AccountID:    accountID,
		EmailAddress: emailAddress,
	}, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}

func (c *TeamAPI) RemoveUser(accountID, emailAddress *string) (*Team, error) {
	if accountID != nil && emailAddress != nil {
		return nil, errors.New("Specify either account id or email address, both given")
	}
	team := &teamRaw{}
	if err := c.postFormAndParse("team/remove_member", &struct {
		AccountID    *string `form:"account_id,omitempty"`
		EmailAddress *string `form:"email_address,omitempty"`
	}{
		AccountID:    accountID,
		EmailAddress: emailAddress,
	}, team);  err != nil {
		return nil, err
	}
	return &team.Team, nil
}
<commit_msg>team: gofmt<commit_after>// Copyright 2016 Stefan Nyman.
// Use of this source code is governed by the MIT
// license that can be found in the LICENSE file.

package hellosign

import (
	"errors"
	"net/http"
)

type TeamAPI struct {
	*hellosign
}

func NewTeamAPI(apiKey string) *TeamAPI {
	return &TeamAPI{newHellosign(apiKey)}
}

type Team struct {
	Name     string `json:"name"`
	Accounts []struct {
		AccountID    string `json:"account_id"`
		EmailAddress string `json:"email_address"`
		RoleCode     string `json:"role_code"`
	} `json:"accounts"`
	InvitedAccounts []struct {
		AccountID    string `json:"account_id"`
		EmailAddress string `json:"email_address"`
		RoleCode     string `json:"role_code"`
	} `json:"invited_accounts"`
}

type teamRaw struct {
	Team Team `json:"team"`
}

func (c *TeamAPI) Get() (*Team, error) {
	team := &teamRaw{}
	if err := c.getAndParse("team", nil, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}

func (c *TeamAPI) Create(name string) (*Team, error) {
	team := &teamRaw{}
	if err := c.postFormAndParse("team/create", &struct {
		Name string `form:"name"`
	}{
		Name: name,
	}, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}

func (c *TeamAPI) Update(name string) (*Team, error) {
	team := &teamRaw{}
	if err := c.postFormAndParse("team", &struct {
		Name string `form:"name"`
	}{
		Name: name,
	}, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}

func (c *TeamAPI) Delete() (bool, error) {
	resp, err := c.postForm("team/destroy", nil)
	if err != nil {
		return false, err
	}
	defer resp.Body.Close()
	if resp.StatusCode != http.StatusOK {
		return false, errors.New(resp.Status)
	}
	return true, nil
}

func (c *TeamAPI) AddUser(accountID, emailAddress *string) (*Team, error) {
	if accountID != nil && emailAddress != nil {
		return nil, errors.New("Specify either account id or email address, both given")
	}
	team := &teamRaw{}
	if err := c.postFormAndParse("team/add_member", &struct {
		AccountID    *string `form:"account_id,omitempty"`
		EmailAddress *string `form:"email_address,omitempty"`
	}{
		AccountID:    accountID,
		EmailAddress: emailAddress,
	}, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}

func (c *TeamAPI) RemoveUser(accountID, emailAddress *string) (*Team, error) {
	if accountID != nil && emailAddress != nil {
		return nil, errors.New("Specify either account id or email address, both given")
	}
	team := &teamRaw{}
	if err := c.postFormAndParse("team/remove_member", &struct {
		AccountID    *string `form:"account_id,omitempty"`
		EmailAddress *string `form:"email_address,omitempty"`
	}{
		AccountID:    accountID,
		EmailAddress: emailAddress,
	}, team); err != nil {
		return nil, err
	}
	return &team.Team, nil
}
<|endoftext|>


<commit_before>// Copyright 2018 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package host

import (
	"time"

	"github.com/google/syzkaller/pkg/csource"
	"github.com/google/syzkaller/pkg/log"
	"github.com/google/syzkaller/pkg/osutil"
	"github.com/google/syzkaller/prog"
)

// DetectSupportedSyscalls returns list on supported and unsupported syscalls on the host.
// For unsupported syscalls it also returns reason as to why it is unsupported.
func DetectSupportedSyscalls(target *prog.Target, sandbox string) (
	map[*prog.Syscall]bool, map[*prog.Syscall]string, error) {
	log.Logf(1, "detecting supported syscalls")
	supported := make(map[*prog.Syscall]bool)
	unsupported := make(map[*prog.Syscall]string)
	// Akaros does not have own host and parasitizes on some other OS.
	if target.OS == "akaros" || target.OS == "test" {
		for _, c := range target.Syscalls {
			supported[c] = true
		}
		return supported, unsupported, nil
	}
	for _, c := range target.Syscalls {
		ok, reason := false, ""
		switch c.CallName {
		case "syz_execute_func":
			ok = true
		default:
			ok, reason = isSupported(c, target, sandbox)
		}
		if ok {
			supported[c] = true
		} else {
			if reason == "" {
				reason = "unknown"
			}
			unsupported[c] = reason
		}
	}
	return supported, unsupported, nil
}

var testFallback = false

const (
	FeatureCoverage = iota
	FeatureComparisons
	FeatureExtraCoverage
	FeatureSandboxSetuid
	FeatureSandboxNamespace
	FeatureSandboxAndroidUntrustedApp
	FeatureFaultInjection
	FeatureLeakChecking
	FeatureNetworkInjection
	FeatureNetworkDevices
	numFeatures
)

type Feature struct {
	Name    string
	Enabled bool
	Reason  string
}

type Features [numFeatures]Feature

var checkFeature [numFeatures]func() string

func unconditionallyEnabled() string { return "" }

// Check detects features supported on the host.
// Empty string for a feature means the feature is supported,
// otherwise the string contains the reason why the feature is not supported.
func Check(target *prog.Target) (*Features, error) {
	const unsupported = "support is not implemented in syzkaller"
	res := &Features{
		FeatureCoverage:                   {Name: "code coverage", Reason: unsupported},
		FeatureComparisons:                {Name: "comparison tracing", Reason: unsupported},
		FeatureExtraCoverage:              {Name: "extra coverage", Reason: unsupported},
		FeatureSandboxSetuid:              {Name: "setuid sandbox", Reason: unsupported},
		FeatureSandboxNamespace:           {Name: "namespace sandbox", Reason: unsupported},
		FeatureSandboxAndroidUntrustedApp: {Name: "Android sandbox", Reason: unsupported},
		FeatureFaultInjection:             {Name: "fault injection", Reason: unsupported},
		FeatureLeakChecking:               {Name: "leak checking", Reason: unsupported},
		FeatureNetworkInjection:           {Name: "net packet injection", Reason: unsupported},
		FeatureNetworkDevices:             {Name: "net device setup", Reason: unsupported},
	}
	if target.OS == "akaros" || target.OS == "test" {
		return res, nil
	}
	for n, check := range checkFeature {
		if check == nil {
			continue
		}
		if reason := check(); reason == "" {
			res[n].Enabled = true
			res[n].Reason = "enabled"
		} else {
			res[n].Reason = reason
		}
	}
	return res, nil
}

// Setup enables and does any one-time setup for the requested features on the host.
// Note: this can be called multiple times and must be idempotent.
func Setup(target *prog.Target, features *Features, featureFlags csource.Features, executor string) error {
	if target.OS == "akaros" {
		return nil
	}
	args := []string{"setup"}
	if features[FeatureLeakChecking].Enabled {
		args = append(args, "leak")
	}
	if features[FeatureFaultInjection].Enabled {
		args = append(args, "fault")
	}
	if target.OS == "linux" && featureFlags["binfmt_misc"].Enabled {
		args = append(args, "binfmt_misc")
	}
	_, err := osutil.RunCmd(time.Minute, "", executor, args...)
	return err
}
<commit_msg>pkg/host: disable syz_execute_func<commit_after>// Copyright 2018 syzkaller project authors. All rights reserved.
// Use of this source code is governed by Apache 2 LICENSE that can be found in the LICENSE file.

package host

import (
	"time"

	"github.com/google/syzkaller/pkg/csource"
	"github.com/google/syzkaller/pkg/log"
	"github.com/google/syzkaller/pkg/osutil"
	"github.com/google/syzkaller/prog"
)

// DetectSupportedSyscalls returns list on supported and unsupported syscalls on the host.
// For unsupported syscalls it also returns reason as to why it is unsupported.
func DetectSupportedSyscalls(target *prog.Target, sandbox string) (
	map[*prog.Syscall]bool, map[*prog.Syscall]string, error) {
	log.Logf(1, "detecting supported syscalls")
	supported := make(map[*prog.Syscall]bool)
	unsupported := make(map[*prog.Syscall]string)
	// Akaros does not have own host and parasitizes on some other OS.
	if target.OS == "akaros" || target.OS == "test" {
		for _, c := range target.Syscalls {
			supported[c] = true
		}
		return supported, unsupported, nil
	}
	for _, c := range target.Syscalls {
		ok, reason := false, ""
		switch c.CallName {
		case "syz_execute_func":
			// syz_execute_func caused multiple problems:
			// 1. First it lead to corpus exploision. The program used existing values in registers
			// to pollute output area. We tried to zero registers (though, not reliably).
			// 2. It lead to explosion again. The exact mechanics are unknown, here is one sample:
			// syz_execute_func(&(0x7f0000000440)="f2af91930f0124eda133fa20430fbafce842f66188d0d4
			//	430fc7f314c1ab5bf9e2f9660f3a0fae5e090000ba023c1fb63ac4817d73d74ec482310d46f44
			//	9f216c863fa438036a91bdbae95aaaa420f383c02c401405c6bfd49d768d768f833fefbab6464
			//	660f38323c8f26dbc1a1fe5ff6f6df0804f4c4efa59c0f01c4288ba6452e000054c4431d5cc100")
			// 3. The code can also execute syscalls (and it is know to), but it's not subject to
			// target.SanitizeCall. As the result it can do things that programs are not supposed to do.
			// 4. Besides linux, corpus explosion also happens on freebsd and is clearly attributable
			// to syz_execute_func based on corpus contents. Mechanics are also not known.
			// It also did not cause finding of any new bugs (at least not that I know of).
			// Let's disable it for now until we figure out how to resolve all these problems.
			ok = false
			reason = "always disabled for now"
		default:
			ok, reason = isSupported(c, target, sandbox)
		}
		if ok {
			supported[c] = true
		} else {
			if reason == "" {
				reason = "unknown"
			}
			unsupported[c] = reason
		}
	}
	return supported, unsupported, nil
}

var testFallback = false

const (
	FeatureCoverage = iota
	FeatureComparisons
	FeatureExtraCoverage
	FeatureSandboxSetuid
	FeatureSandboxNamespace
	FeatureSandboxAndroidUntrustedApp
	FeatureFaultInjection
	FeatureLeakChecking
	FeatureNetworkInjection
	FeatureNetworkDevices
	numFeatures
)

type Feature struct {
	Name    string
	Enabled bool
	Reason  string
}

type Features [numFeatures]Feature

var checkFeature [numFeatures]func() string

func unconditionallyEnabled() string { return "" }

// Check detects features supported on the host.
// Empty string for a feature means the feature is supported,
// otherwise the string contains the reason why the feature is not supported.
func Check(target *prog.Target) (*Features, error) {
	const unsupported = "support is not implemented in syzkaller"
	res := &Features{
		FeatureCoverage:                   {Name: "code coverage", Reason: unsupported},
		FeatureComparisons:                {Name: "comparison tracing", Reason: unsupported},
		FeatureExtraCoverage:              {Name: "extra coverage", Reason: unsupported},
		FeatureSandboxSetuid:              {Name: "setuid sandbox", Reason: unsupported},
		FeatureSandboxNamespace:           {Name: "namespace sandbox", Reason: unsupported},
		FeatureSandboxAndroidUntrustedApp: {Name: "Android sandbox", Reason: unsupported},
		FeatureFaultInjection:             {Name: "fault injection", Reason: unsupported},
		FeatureLeakChecking:               {Name: "leak checking", Reason: unsupported},
		FeatureNetworkInjection:           {Name: "net packet injection", Reason: unsupported},
		FeatureNetworkDevices:             {Name: "net device setup", Reason: unsupported},
	}
	if target.OS == "akaros" || target.OS == "test" {
		return res, nil
	}
	for n, check := range checkFeature {
		if check == nil {
			continue
		}
		if reason := check(); reason == "" {
			res[n].Enabled = true
			res[n].Reason = "enabled"
		} else {
			res[n].Reason = reason
		}
	}
	return res, nil
}

// Setup enables and does any one-time setup for the requested features on the host.
// Note: this can be called multiple times and must be idempotent.
func Setup(target *prog.Target, features *Features, featureFlags csource.Features, executor string) error {
	if target.OS == "akaros" {
		return nil
	}
	args := []string{"setup"}
	if features[FeatureLeakChecking].Enabled {
		args = append(args, "leak")
	}
	if features[FeatureFaultInjection].Enabled {
		args = append(args, "fault")
	}
	if target.OS == "linux" && featureFlags["binfmt_misc"].Enabled {
		args = append(args, "binfmt_misc")
	}
	_, err := osutil.RunCmd(time.Minute, "", executor, args...)
	return err
}
<|endoftext|>


<commit_before>// Copyright 2018 the LinuxBoot 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 lzma implements reading and writing of LZMA compressed files.
//
// This package is specifically designed for the LZMA format used popular UEFI
// implementations. It requires the `lzma` and `unlzma` programs to be
// installed and on the path.
package lzma

import (
	"bytes"
	"io"
	"io/ioutil"

	"github.com/ulikunitz/xz/lzma"
)

// Decode decodes a byte slice of LZMA data.
func Decode(encodedData []byte) ([]byte, error) {
	r, err := lzma.NewReader(bytes.NewBuffer(encodedData))
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(r)
}

// Encode encodes a byte slice with LZMA.
func Encode(decodedData []byte) ([]byte, error) {
	// These options are supported by the xz's LZMA command and EDK2's LZMA.
	// TODO: This does not support the f86 feature used in EDK2.
	wc := lzma.WriterConfig{
		SizeInHeader: true,
		Size:         int64(len(decodedData)),
		EOSMarker:    false,
	}
	if err := wc.Verify(); err != nil {
		return nil, err
	}
	buf := &bytes.Buffer{}
	w, err := wc.NewWriter(buf)
	if err != nil {
		return nil, err
	}
	if _, err := io.Copy(w, bytes.NewBuffer(decodedData)); err != nil {
		return nil, err
	}
	if err := w.Close(); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
<commit_msg>Set DictCap in hopes of getting better compression<commit_after>// Copyright 2018 the LinuxBoot 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 lzma implements reading and writing of LZMA compressed files.
//
// This package is specifically designed for the LZMA format used popular UEFI
// implementations. It requires the `lzma` and `unlzma` programs to be
// installed and on the path.
package lzma

import (
	"bytes"
	"io"
	"io/ioutil"

	"github.com/ulikunitz/xz/lzma"
)

// Mapping from compression level to dictionary size.
var lzmaDictCapExps = []uint{18, 20, 21, 22, 22, 23, 23, 24, 25, 26}
var compressionLevel = 7

// Decode decodes a byte slice of LZMA data.
func Decode(encodedData []byte) ([]byte, error) {
	r, err := lzma.NewReader(bytes.NewBuffer(encodedData))
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(r)
}

// Encode encodes a byte slice with LZMA.
func Encode(decodedData []byte) ([]byte, error) {
	// These options are supported by the xz's LZMA command and EDK2's LZMA.
	// TODO: This does not support the f86 feature used in EDK2.
	wc := lzma.WriterConfig{
		SizeInHeader: true,
		Size:         int64(len(decodedData)),
		EOSMarker:    false,
		Properties:   &lzma.Properties{LC: 3, LP: 0, PB: 2},
		DictCap:      1 << lzmaDictCapExps[compressionLevel],
	}
	if err := wc.Verify(); err != nil {
		return nil, err
	}
	buf := &bytes.Buffer{}
	w, err := wc.NewWriter(buf)
	if err != nil {
		return nil, err
	}
	if _, err := io.Copy(w, bytes.NewBuffer(decodedData)); err != nil {
		return nil, err
	}
	if err := w.Close(); err != nil {
		return nil, err
	}
	return buf.Bytes(), nil
}
<|endoftext|>


<commit_before>package main

type Func func(Request, Response) interface{}

func main() {
	GET("/", func(req Request, res Response) {
		return "Hello"
	})

	DELETE("/", func(req Request, res Response){
		return 200
	})

	PUT("/", func(req Request, res Response){
		return 200
	})

	POST("/", func(req Request, res Response){
		return 200
	})

	OPTIONS("/", func(req Request, res Response){
		return 200
	})

	PATCH("/", func(req Request, res Response){
		return 200
	})
}

func GET(string, Func) {}
func DELETE(string, Func) {}
func PUT(string, Func) {}
func POST(string, Func) {}
func OPTIONS(string, Func) {}
func PATCH(string, Func) {}

type Request struct {
	// Query
	// Cookies
	// Sessions
}

type Response struct {

}

// Functions
func Halt(msg string, code int) {
	// halt(int)
	// halt(msg)
	// halt(int, msg)
}

func HaltWithCode(code int) {

}

func HaltWithMessage(msg string) {

}

func Before() {

}

func After() {

}

<commit_msg>no message<commit_after>package main

type Func func(Request, Response) interface{}

func main() {
	GET("/", func(req Request, res Response) {
		return "Hello"
	})

	DELETE("/", func(req Request, res Response){
		return 200
	})

	PUT("/", func(req Request, res Response){
		return 200
	})

	POST("/", func(req Request, res Response){
		return 200
	})

	OPTIONS("/", func(req Request, res Response){
		return 200
	})

	PATCH("/", func(req Request, res Response){
		return 200
	})
}

func GET(string, Func) {}
func DELETE(string, Func) {}
func PUT(string, Func) {}
func POST(string, Func) {}
func OPTIONS(string, Func) {}
func PATCH(string, Func) {}

type Request struct {
	// Query
	// Cookies
	// Sessions
		// get attribute
		// set attribute
}

type Response struct {
	// redirect

}

// Functions
func Halt(msg string, code int) {
	// halt(int)
	// halt(msg)
	// halt(int, msg)
}

func HaltWithCode(code int) {

}

func HaltWithMessage(msg string) {

}

// Before every method
func BeforeAll(Func) {

}

func Before(pattern string, Func) {

}

// After every methods
func After(pattern string, Func) {

}

func AfterAll(Func) {

}

// Handling Exceptions
func Error(err error, fn Func) {

}<|endoftext|>


<commit_before>package sti

// Request contains essential fields for any request: a base image, source directory,
// and tag
type Request struct {
	BaseImage           string
	DockerSocket        string
	PreserveWorkingDir  bool
	Source              string
	Ref                 string
	Tag                 string
	Clean               bool
	RemovePreviousImage bool
	Environment         map[string]string
	CallbackURL         string
	ScriptsURL          string
	ForcePull           bool

	incremental bool
	workingDir  string
}

// Result includes a flag that indicates whether the build was successful
// and if an image was created, the image ID
type Result struct {
	Success    bool
	Messages   []string
	WorkingDir string
	ImageID    string
}
<commit_msg>Updated types.go with godocs for all the fields.<commit_after>package sti

// Request contains essential fields for any request.
type Request struct {
	// BaseImage describes which image is used for building the result images.
	BaseImage string

	// DockerSocket describes how to access host docker daemon.
	DockerSocket string

	// PreserveWorkingDir describes if working directory should be left after processing.
	PreserveWorkingDir bool

	// Source URL describing the location of sources used to build the result image.
	Source string

	// Ref is a tag/branch to be used for build.
	Ref string

	// Tag is a result image tag name.
	Tag string

	// Clean describes whether to perform full build even if the build is eligible for incremental build.
	Clean bool

	// RemovePreviousImage describes if previous image should be removed after successful build.
	// This applies only to incremental builds.
	RemovePreviousImage bool

	// Environment is a map of environment variables to be passed to the image.
	Environment map[string]string

	// CallbackURL is a URL which is called upon successful build to inform about that fact.
	CallbackURL string

	// ScriptsURL is a URL describing the localization of STI scripts used during build process.
	ScriptsURL string

	// ForcePull describes if the builder should pull the images from registry prior to building.
	ForcePull bool

	// incremental describes incremental status of current build
	incremental bool

	// workingDir describes temporary directory used for downloading sources, scripts and tar operations.
	workingDir string
}

// Result structure contains information from build process.
type Result struct {
	// Success describes whether the build was successful.
	Success bool

	// Messages is a list of messages from build process.
	Messages []string

	// WorkingDir describes temporary directory used for downloading sources, scripts and tar operations.
	WorkingDir string

	// ImageID describes resulting image ID.
	ImageID string
}
<|endoftext|>


<commit_before>package system

import (
	"os"
	"syscall"
	"time"

	"github.com/containers/storage/pkg/mount"
	"github.com/pkg/errors"
)

// EnsureRemoveAll wraps `os.RemoveAll` to check for specific errors that can
// often be remedied.
// Only use `EnsureRemoveAll` if you really want to make every effort to remove
// a directory.
//
// Because of the way `os.Remove` (and by extension `os.RemoveAll`) works, there
// can be a race between reading directory entries and then actually attempting
// to remove everything in the directory.
// These types of errors do not need to be returned since it's ok for the dir to
// be gone we can just retry the remove operation.
//
// This should not return a `os.ErrNotExist` kind of error under any circumstances
func EnsureRemoveAll(dir string) error {
	notExistErr := make(map[string]bool)

	// track retries
	exitOnErr := make(map[string]int)
	maxRetry := 100

	// Attempt to unmount anything beneath this dir first
	mount.RecursiveUnmount(dir)

	for {
		err := os.RemoveAll(dir)
		if err == nil {
			return err
		}

		pe, ok := err.(*os.PathError)
		if !ok {
			return err
		}

		if os.IsNotExist(err) {
			if notExistErr[pe.Path] {
				return err
			}
			notExistErr[pe.Path] = true

			// There is a race where some subdir can be removed but after the parent
			//   dir entries have been read.
			// So the path could be from `os.Remove(subdir)`
			// If the reported non-existent path is not the passed in `dir` we
			// should just retry, but otherwise return with no error.
			if pe.Path == dir {
				return nil
			}
			continue
		}

		if pe.Err != syscall.EBUSY {
			return err
		}

		if mounted, _ := mount.Mounted(pe.Path); mounted {
			if e := mount.Unmount(pe.Path); e != nil {
				if mounted, _ := mount.Mounted(pe.Path); mounted {
					return errors.Wrapf(e, "error while removing %s", dir)
				}
			}
		}

		if exitOnErr[pe.Path] == maxRetry {
			return err
		}
		exitOnErr[pe.Path]++
		time.Sleep(100 * time.Millisecond)
	}
}
<commit_msg>pkg/system.EnsureRemoveAll: don't call Mounted<commit_after>package system

import (
	"os"
	"syscall"
	"time"

	"github.com/containers/storage/pkg/mount"
	"github.com/pkg/errors"
)

// EnsureRemoveAll wraps `os.RemoveAll` to check for specific errors that can
// often be remedied.
// Only use `EnsureRemoveAll` if you really want to make every effort to remove
// a directory.
//
// Because of the way `os.Remove` (and by extension `os.RemoveAll`) works, there
// can be a race between reading directory entries and then actually attempting
// to remove everything in the directory.
// These types of errors do not need to be returned since it's ok for the dir to
// be gone we can just retry the remove operation.
//
// This should not return a `os.ErrNotExist` kind of error under any circumstances
func EnsureRemoveAll(dir string) error {
	notExistErr := make(map[string]bool)

	// track retries
	exitOnErr := make(map[string]int)
	maxRetry := 100

	// Attempt to unmount anything beneath this dir first
	mount.RecursiveUnmount(dir)

	for {
		err := os.RemoveAll(dir)
		if err == nil {
			return err
		}

		pe, ok := err.(*os.PathError)
		if !ok {
			return err
		}

		if os.IsNotExist(err) {
			if notExistErr[pe.Path] {
				return err
			}
			notExistErr[pe.Path] = true

			// There is a race where some subdir can be removed but after the parent
			//   dir entries have been read.
			// So the path could be from `os.Remove(subdir)`
			// If the reported non-existent path is not the passed in `dir` we
			// should just retry, but otherwise return with no error.
			if pe.Path == dir {
				return nil
			}
			continue
		}

		if pe.Err != syscall.EBUSY {
			return err
		}

		if e := mount.Unmount(pe.Path); e != nil {
			return errors.Wrapf(e, "error while removing %s", dir)
		}

		if exitOnErr[pe.Path] == maxRetry {
			return err
		}
		exitOnErr[pe.Path]++
		time.Sleep(100 * time.Millisecond)
	}
}
<|endoftext|>


<commit_before>package player

import (
	"github.com/Joey92/poker-player-deathstar/leanpoker"
	"strings"
)

const VERSION = "Default Go folding player"

func BetRequest(state *leanpoker.Game) int {

	p := state.GetPlayer()

	if p == nil {
		return 1000
	}

	var bet int

	if (state.IsCheckable(bet)) {
		return bet
	}

	if isPair(p.HoleCards) {
		bet += state.CurrentBuyIn * rankHoleCards(p.HoleCards)
	}

	/*if (len(state.CommunityCards) > 0) {
		bet += calcComunityCards(state, bet)
	}*/

	return bet
}

func Showdown(state *leanpoker.Game) {

}

func Version() string {
	return VERSION
}

func isPair(cards []*leanpoker.Card) bool  {
	if len(cards) < 2 {
		return false
	}

	return cards[0].Rank == cards[1].Rank
}

func rankHoleCards(cards []*leanpoker.Card) int {
	if len(cards) < 2 {
		return 0
	}

	card1 := rankCard(cards[0].Rank)
	card2 := rankCard(cards[1].Rank)

	return card1 + card2
}

func rankCard(rank string) int {
	ranks := "12345678910JQKA"
	return strings.Index(ranks, rank) + 1
}

/*func calcComunityCards(g *leanpoker.Game, currentBet) {

}*/

<commit_msg>Fold if buyin is higher than the rank<commit_after>package player

import (
	"github.com/Joey92/poker-player-deathstar/leanpoker"
	"strings"
)

const VERSION = "Default Go folding player"

func BetRequest(state *leanpoker.Game) int {

	p := state.GetPlayer()

	if p == nil {
		return 1000
	}

	var bet int

	if (state.IsCheckable(bet)) {
		return bet
	}

	if isPair(p.HoleCards) {
		bet += state.CurrentBuyIn * rankHoleCards(p.HoleCards)
	}

	if (state.CurrentBuyIn > state.CurrentBuyIn * rankHoleCards(p.HoleCards)) {
		return 0
	}

	/*if (len(state.CommunityCards) > 0) {
		bet += calcComunityCards(state, bet)
	}*/

	return bet
}

func Showdown(state *leanpoker.Game) {

}

func Version() string {
	return VERSION
}

func isPair(cards []*leanpoker.Card) bool  {
	if len(cards) < 2 {
		return false
	}

	return cards[0].Rank == cards[1].Rank
}

func rankHoleCards(cards []*leanpoker.Card) int {
	if len(cards) < 2 {
		return 0
	}

	card1 := rankCard(cards[0].Rank)
	card2 := rankCard(cards[1].Rank)

	return card1 + card2
}

func rankCard(rank string) int {
	ranks := "12345678910JQKA"
	return strings.Index(ranks, rank) + 1
}

/*func calcComunityCards(g *leanpoker.Game, currentBet) {

}*/

<|endoftext|>


<commit_before>// Copyright 2010 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 gf256 implements arithmetic over the Galois Field GF(256).
package gf256

import "strconv"

// A Field represents an instance of GF(256) defined by a specific polynomial.
type Field struct {
	log [256]byte // log[0] is unused
	exp [510]byte
}

// NewField returns a new field corresponding to the polynomial poly
// and generator α.  The Reed-Solomon encoding in QR codes uses
// polynomial 0x11d with generator 2.
func NewField(poly, α int) *Field {
	if poly < 0x100 || poly >= 0x200 || reducible(poly) {
		panic("gf256: invalid polynomial: " + strconv.Itoa(poly))
	}

	// We don't know what the generator is, but we do know
	// that the polynomial is reducible, so half of our choices
	// are generators.  Just try them in order until we find one.
	var f Field
	x := 1
	for i := 0; i < 255; i++ {
		if x == 1 && i != 0 {
			panic("gf256: invalid generator " + strconv.Itoa(α) +
				" for polynomial " + strconv.Itoa(poly))
		}
		f.exp[i] = byte(x)
		f.exp[i+255] = byte(x)
		f.log[x] = byte(i)
		x = mul(x, α, poly)
	}
	f.log[0] = 255
	for i := 0; i < 255; i++ {
		if f.log[f.exp[i]] != byte(i) {
			panic("bad log")
		}
		if f.log[f.exp[i+255]] != byte(i) {
			panic("bad log")
		}
	}
	for i := 1; i < 256; i++ {
		if f.exp[f.log[i]] != byte(i) {
			panic("bad log")
		}
	}

	return &f
}

// nbit returns the number of significant in p.
func nbit(p int) uint {
	n := uint(0)
	for ; p > 0; p >>= 1 {
		n++
	}
	return n
}

// polyDiv divides the polynomial p by q and returns the remainder.
func polyDiv(p, q int) int {
	np := nbit(p)
	nq := nbit(q)
	for ; np >= nq; np-- {
		if p&(1<<(np-1)) != 0 {
			p ^= q << (np - nq)
		}
	}
	return p
}

// mul returns the product x*y mod poly, a GF(256) multiplication.
func mul(x, y, poly int) int {
	z := 0
	for x > 0 {
		if x&1 != 0 {
			z ^= y
		}
		x >>= 1
		y <<= 1
		if y&0x100 != 0 {
			y ^= poly
		}
	}
	return z
}

// reducible reports whether p is reducible.
func reducible(p int) bool {
	// Multiplying n-bit * n-bit produces (2n-1)-bit,
	// so if p is reducible, one of its factors must be
	// of np/2+1 bits or fewer.
	np := nbit(p)
	for q := 2; q < 1<<(np/2+1); q++ {
		if polyDiv(p, q) == 0 {
			return true
		}
	}
	return false
}

// Add returns the sum of x and y in the field.
func (f *Field) Add(x, y byte) byte {
	return x ^ y
}

// Exp returns the base 2 exponential of e in the field.
// If e < 0, Exp returns 0.
func (f *Field) Exp(e int) byte {
	if e < 0 {
		return 0
	}
	return f.exp[e%255]
}

// Log returns the base 2 logarithm of x in the field.
// If x == 0, Log returns -1.
func (f *Field) Log(x byte) int {
	if x == 0 {
		return -1
	}
	return int(f.log[x])
}

// Inv returns the multiplicative inverse of x in the field.
// If x == 0, Inv returns 0.
func (f *Field) Inv(x byte) byte {
	if x == 0 {
		return 0
	}
	return f.exp[255-f.log[x]]
}

// Mul returns the product of x and y in the field.
func (f *Field) Mul(x, y byte) byte {
	if x == 0 || y == 0 {
		return 0
	}
	return f.exp[int(f.log[x])+int(f.log[y])]
}

// An RSEncoder implements Reed-Solomon encoding
// over a given field using a given number of error correction bytes.
type RSEncoder struct {
	f    *Field
	c    int
	gen  []byte
	lgen []byte
	p    []byte
}

func (f *Field) gen(e int) (gen, lgen []byte) {
	// p = 1
	p := make([]byte, e+1)
	p[e] = 1

	for i := 0; i < e; i++ {
		// p *= (x + Exp(i))
		// p[j] = p[j]*Exp(i) + p[j+1].
		c := f.Exp(i)
		for j := 0; j < e; j++ {
			p[j] = f.Mul(p[j], c) ^ p[j+1]
		}
		p[e] = f.Mul(p[e], c)
	}

	// lp = log p.
	lp := make([]byte, e+1)
	for i, c := range p {
		if c == 0 {
			lp[i] = 255
		} else {
			lp[i] = byte(f.Log(c))
		}
	}

	return p, lp
}

// NewRSEncoder returns a new Reed-Solomon encoder
// over the given field and number of error correction bytes.
func NewRSEncoder(f *Field, c int) *RSEncoder {
	gen, lgen := f.gen(c)
	return &RSEncoder{f: f, c: c, gen: gen, lgen: lgen}
}

// ECC writes to check the error correcting code bytes
// for data using the given Reed-Solomon parameters.
func (rs *RSEncoder) ECC(data []byte, check []byte) {
	if len(check) < rs.c {
		panic("gf256: invalid check byte length")
	}
	if rs.c == 0 {
		return
	}

	// The check bytes are the remainder after dividing
	// data padded with c zeros by the generator polynomial.

	// p = data padded with c zeros.
	var p []byte
	n := len(data) + rs.c
	if len(rs.p) >= n {
		p = rs.p
	} else {
		p = make([]byte, n)
	}
	copy(p, data)
	for i := len(data); i < len(p); i++ {
		p[i] = 0
	}

	// Divide p by gen, leaving the remainder in p[len(data):].
	// p[0] is the most significant term in p, and
	// gen[0] is the most significant term in the generator,
	// which is always 1.
	// To avoid repeated work, we store various values as
	// lv, not v, where lv = log[v].
	f := rs.f
	lgen := rs.lgen[1:]
	for i := 0; i < len(data); i++ {
		c := p[i]
		if c == 0 {
			continue
		}
		q := p[i+1:]
		exp := f.exp[f.log[c]:]
		for j, lg := range lgen {
			if lg != 255 { // lgen uses 255 for log 0
				q[j] ^= exp[lg]
			}
		}
	}
	copy(check, p[len(data):])
	rs.p = p
}
<commit_msg>gf256: fix comment<commit_after>// Copyright 2010 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 gf256 implements arithmetic over the Galois Field GF(256).
package gf256

import "strconv"

// A Field represents an instance of GF(256) defined by a specific polynomial.
type Field struct {
	log [256]byte // log[0] is unused
	exp [510]byte
}

// NewField returns a new field corresponding to the polynomial poly
// and generator α.  The Reed-Solomon encoding in QR codes uses
// polynomial 0x11d with generator 2.
func NewField(poly, α int) *Field {
	if poly < 0x100 || poly >= 0x200 || reducible(poly) {
		panic("gf256: invalid polynomial: " + strconv.Itoa(poly))
	}

	var f Field
	x := 1
	for i := 0; i < 255; i++ {
		if x == 1 && i != 0 {
			panic("gf256: invalid generator " + strconv.Itoa(α) +
				" for polynomial " + strconv.Itoa(poly))
		}
		f.exp[i] = byte(x)
		f.exp[i+255] = byte(x)
		f.log[x] = byte(i)
		x = mul(x, α, poly)
	}
	f.log[0] = 255
	for i := 0; i < 255; i++ {
		if f.log[f.exp[i]] != byte(i) {
			panic("bad log")
		}
		if f.log[f.exp[i+255]] != byte(i) {
			panic("bad log")
		}
	}
	for i := 1; i < 256; i++ {
		if f.exp[f.log[i]] != byte(i) {
			panic("bad log")
		}
	}

	return &f
}

// nbit returns the number of significant in p.
func nbit(p int) uint {
	n := uint(0)
	for ; p > 0; p >>= 1 {
		n++
	}
	return n
}

// polyDiv divides the polynomial p by q and returns the remainder.
func polyDiv(p, q int) int {
	np := nbit(p)
	nq := nbit(q)
	for ; np >= nq; np-- {
		if p&(1<<(np-1)) != 0 {
			p ^= q << (np - nq)
		}
	}
	return p
}

// mul returns the product x*y mod poly, a GF(256) multiplication.
func mul(x, y, poly int) int {
	z := 0
	for x > 0 {
		if x&1 != 0 {
			z ^= y
		}
		x >>= 1
		y <<= 1
		if y&0x100 != 0 {
			y ^= poly
		}
	}
	return z
}

// reducible reports whether p is reducible.
func reducible(p int) bool {
	// Multiplying n-bit * n-bit produces (2n-1)-bit,
	// so if p is reducible, one of its factors must be
	// of np/2+1 bits or fewer.
	np := nbit(p)
	for q := 2; q < 1<<(np/2+1); q++ {
		if polyDiv(p, q) == 0 {
			return true
		}
	}
	return false
}

// Add returns the sum of x and y in the field.
func (f *Field) Add(x, y byte) byte {
	return x ^ y
}

// Exp returns the base 2 exponential of e in the field.
// If e < 0, Exp returns 0.
func (f *Field) Exp(e int) byte {
	if e < 0 {
		return 0
	}
	return f.exp[e%255]
}

// Log returns the base 2 logarithm of x in the field.
// If x == 0, Log returns -1.
func (f *Field) Log(x byte) int {
	if x == 0 {
		return -1
	}
	return int(f.log[x])
}

// Inv returns the multiplicative inverse of x in the field.
// If x == 0, Inv returns 0.
func (f *Field) Inv(x byte) byte {
	if x == 0 {
		return 0
	}
	return f.exp[255-f.log[x]]
}

// Mul returns the product of x and y in the field.
func (f *Field) Mul(x, y byte) byte {
	if x == 0 || y == 0 {
		return 0
	}
	return f.exp[int(f.log[x])+int(f.log[y])]
}

// An RSEncoder implements Reed-Solomon encoding
// over a given field using a given number of error correction bytes.
type RSEncoder struct {
	f    *Field
	c    int
	gen  []byte
	lgen []byte
	p    []byte
}

func (f *Field) gen(e int) (gen, lgen []byte) {
	// p = 1
	p := make([]byte, e+1)
	p[e] = 1

	for i := 0; i < e; i++ {
		// p *= (x + Exp(i))
		// p[j] = p[j]*Exp(i) + p[j+1].
		c := f.Exp(i)
		for j := 0; j < e; j++ {
			p[j] = f.Mul(p[j], c) ^ p[j+1]
		}
		p[e] = f.Mul(p[e], c)
	}

	// lp = log p.
	lp := make([]byte, e+1)
	for i, c := range p {
		if c == 0 {
			lp[i] = 255
		} else {
			lp[i] = byte(f.Log(c))
		}
	}

	return p, lp
}

// NewRSEncoder returns a new Reed-Solomon encoder
// over the given field and number of error correction bytes.
func NewRSEncoder(f *Field, c int) *RSEncoder {
	gen, lgen := f.gen(c)
	return &RSEncoder{f: f, c: c, gen: gen, lgen: lgen}
}

// ECC writes to check the error correcting code bytes
// for data using the given Reed-Solomon parameters.
func (rs *RSEncoder) ECC(data []byte, check []byte) {
	if len(check) < rs.c {
		panic("gf256: invalid check byte length")
	}
	if rs.c == 0 {
		return
	}

	// The check bytes are the remainder after dividing
	// data padded with c zeros by the generator polynomial.

	// p = data padded with c zeros.
	var p []byte
	n := len(data) + rs.c
	if len(rs.p) >= n {
		p = rs.p
	} else {
		p = make([]byte, n)
	}
	copy(p, data)
	for i := len(data); i < len(p); i++ {
		p[i] = 0
	}

	// Divide p by gen, leaving the remainder in p[len(data):].
	// p[0] is the most significant term in p, and
	// gen[0] is the most significant term in the generator,
	// which is always 1.
	// To avoid repeated work, we store various values as
	// lv, not v, where lv = log[v].
	f := rs.f
	lgen := rs.lgen[1:]
	for i := 0; i < len(data); i++ {
		c := p[i]
		if c == 0 {
			continue
		}
		q := p[i+1:]
		exp := f.exp[f.log[c]:]
		for j, lg := range lgen {
			if lg != 255 { // lgen uses 255 for log 0
				q[j] ^= exp[lg]
			}
		}
	}
	copy(check, p[len(data):])
	rs.p = p
}
<|endoftext|>


<commit_before>/*
The Ginkgo CLI

The Ginkgo CLI is fully documented [here](http://onsi.github.io/ginkgo/#the_ginkgo_cli)

You can also learn more by running:

	ginkgo help

Here are some of the more commonly used commands:

To install:

	go install github.com/onsi/ginkgo/ginkgo

To run tests:

	ginkgo

To run tests in all subdirectories:

	ginkgo -r

To run tests in particular packages:

	ginkgo <flags> /path/to/package /path/to/another/package

To pass arguments/flags to your tests:

	ginkgo <flags> <packages> -- <pass-throughs>

To run tests in parallel

	ginkgo -p

this will automatically detect the optimal number of nodes to use.  Alternatively, you can specify the number of nodes with:

	ginkgo -nodes=N

(note that you don't need to provide -p in this case).

By default the Ginkgo CLI will spin up a server that the individual test processes send test output to.  The CLI aggregates this output and then presents coherent test output, one test at a time, as each test completes.
An alternative is to have the parallel nodes run and stream interleaved output back.  This useful for debugging, particularly in contexts where tests hang/fail to start.  To get this interleaved output:

	ginkgo -nodes=N -stream=true

On windows, the default value for stream is true.

By default, when running multiple tests (with -r or a list of packages) Ginkgo will abort when a test fails.  To have Ginkgo run subsequent test suites instead you can:

	ginkgo -keepGoing

To monitor packages and rerun tests when changes occur:

	ginkgo watch <-r> </path/to/package>

passing `ginkgo watch` the `-r` flag will recursively detect all test suites under the current directory and monitor them.
`watch` does not detect *new* packages. Moreover, changes in package X only rerun the tests for package X, tests for packages
that depend on X are not rerun.

[OSX only] To receive (desktop) notifications when a test run completes:

	ginkgo -notify

this is particularly useful with `ginkgo watch`.  Notifications are currently only supported on OS X and require that you `brew install terminal-notifier`

Sometimes (to suss out race conditions/flakey tests, for example) you want to keep running a test suite until it fails.  You can do this with:

	ginkgo -untilItFails

To bootstrap a test suite:

	ginkgo bootstrap

To generate a test file:

	ginkgo generate <test_file_name>

To bootstrap/generate test files without using "." imports:

	ginkgo bootstrap --nodot
	ginkgo generate --nodot

this will explicitly export all the identifiers in Ginkgo and Gomega allowing you to rename them to avoid collisions.  When you pull to the latest Ginkgo/Gomega you'll want to run

	ginkgo nodot

to refresh this list and pull in any new identifiers.  In particular, this will pull in any new Gomega matchers that get added.

To convert an existing XUnit style test suite to a Ginkgo-style test suite:

	ginkgo convert .

To unfocus tests:

	ginkgo unfocus

or

	ginkgo blur

To compile a test suite:

	ginkgo build <path-to-package>

will output an executable file named `package.test`.  This can be run directly or by invoking

	ginkgo <path-to-package.test>

To print out Ginkgo's version:

	ginkgo version

To get more help:

	ginkgo help
*/
package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/onsi/ginkgo/config"
	"github.com/onsi/ginkgo/ginkgo/testsuite"
)

const greenColor = "\x1b[32m"
const redColor = "\x1b[91m"
const defaultStyle = "\x1b[0m"
const lightGrayColor = "\x1b[37m"

type Command struct {
	Name                      string
	AltName                   string
	FlagSet                   *flag.FlagSet
	Usage                     []string
	UsageCommand              string
	Command                   func(args []string, additionalArgs []string)
	SuppressFlagDocumentation bool
	FlagDocSubstitute         []string
}

func (c *Command) Matches(name string) bool {
	return c.Name == name || (c.AltName != "" && c.AltName == name)
}

func (c *Command) Run(args []string, additionalArgs []string) {
	c.FlagSet.Parse(args)
	c.Command(c.FlagSet.Args(), additionalArgs)
}

var DefaultCommand *Command
var Commands []*Command

func init() {
	DefaultCommand = BuildRunCommand()
	Commands = append(Commands, BuildWatchCommand())
	Commands = append(Commands, BuildBuildCommand())
	Commands = append(Commands, BuildBootstrapCommand())
	Commands = append(Commands, BuildGenerateCommand())
	Commands = append(Commands, BuildNodotCommand())
	Commands = append(Commands, BuildConvertCommand())
	Commands = append(Commands, BuildUnfocusCommand())
	Commands = append(Commands, BuildVersionCommand())
	Commands = append(Commands, BuildHelpCommand())
}

func main() {
	args := []string{}
	additionalArgs := []string{}

	foundDelimiter := false

	for _, arg := range os.Args[1:] {
		if !foundDelimiter {
			if arg == "--" {
				foundDelimiter = true
				continue
			}
		}

		if foundDelimiter {
			additionalArgs = append(additionalArgs, arg)
		} else {
			args = append(args, arg)
		}
	}

	if len(args) > 0 {
		commandToRun, found := commandMatching(args[0])
		if found {
			commandToRun.Run(args[1:], additionalArgs)
			return
		}
	}

	DefaultCommand.Run(args, additionalArgs)
}

func commandMatching(name string) (*Command, bool) {
	for _, command := range Commands {
		if command.Matches(name) {
			return command, true
		}
	}
	return nil, false
}

func usage() {
	fmt.Fprintf(os.Stderr, "Ginkgo Version %s\n\n", config.VERSION)
	usageForCommand(DefaultCommand, false)
	for _, command := range Commands {
		fmt.Fprintf(os.Stderr, "\n")
		usageForCommand(command, false)
	}
}

func usageForCommand(command *Command, longForm bool) {
	fmt.Fprintf(os.Stderr, "%s\n%s\n", command.UsageCommand, strings.Repeat("-", len(command.UsageCommand)))
	fmt.Fprintf(os.Stderr, "%s\n", strings.Join(command.Usage, "\n"))
	if command.SuppressFlagDocumentation && !longForm {
		fmt.Fprintf(os.Stderr, "%s\n", strings.Join(command.FlagDocSubstitute, "\n  "))
	} else {
		command.FlagSet.PrintDefaults()
	}
}

func complainAndQuit(complaint string) {
	fmt.Fprintf(os.Stderr, "%s\nFor usage instructions:\n\tginkgo help\n", complaint)
	os.Exit(1)
}

func findSuites(args []string, recurse bool, skipPackage string, allowPrecompiled bool) ([]testsuite.TestSuite, []string) {
	suites := []testsuite.TestSuite{}

	if len(args) > 0 {
		for _, arg := range args {
			if allowPrecompiled {
				suite, err := testsuite.PrecompiledTestSuite(arg)
				if err == nil {
					suites = append(suites, suite)
					continue
				}
			}
			suites = append(suites, testsuite.SuitesInDir(arg, recurse)...)
		}
	} else {
		suites = testsuite.SuitesInDir(".", recurse)
	}

	skippedPackages := []string{}
	if skipPackage != "" {
		skipFilters := strings.Split(skipPackage, ",")
		filteredSuites := []testsuite.TestSuite{}
		for _, suite := range suites {
			skip := false
			for _, skipFilter := range skipFilters {
				if strings.Contains(suite.Path, skipFilter) {
					skip = true
					break
				}
			}
			if skip {
				skippedPackages = append(skippedPackages, suite.Path)
			} else {
				filteredSuites = append(filteredSuites, suite)
			}
		}
		suites = filteredSuites
	}

	return suites, skippedPackages
}

func goFmt(path string) {
	err := exec.Command("go", "fmt", path).Run()
	if err != nil {
		complainAndQuit("Could not fmt: " + err.Error())
	}
}

func pluralizedWord(singular, plural string, count int) string {
	if count == 1 {
		return singular
	}
	return plural
}
<commit_msg>mention that notify works on OS X and Linux<commit_after>/*
The Ginkgo CLI

The Ginkgo CLI is fully documented [here](http://onsi.github.io/ginkgo/#the_ginkgo_cli)

You can also learn more by running:

	ginkgo help

Here are some of the more commonly used commands:

To install:

	go install github.com/onsi/ginkgo/ginkgo

To run tests:

	ginkgo

To run tests in all subdirectories:

	ginkgo -r

To run tests in particular packages:

	ginkgo <flags> /path/to/package /path/to/another/package

To pass arguments/flags to your tests:

	ginkgo <flags> <packages> -- <pass-throughs>

To run tests in parallel

	ginkgo -p

this will automatically detect the optimal number of nodes to use.  Alternatively, you can specify the number of nodes with:

	ginkgo -nodes=N

(note that you don't need to provide -p in this case).

By default the Ginkgo CLI will spin up a server that the individual test processes send test output to.  The CLI aggregates this output and then presents coherent test output, one test at a time, as each test completes.
An alternative is to have the parallel nodes run and stream interleaved output back.  This useful for debugging, particularly in contexts where tests hang/fail to start.  To get this interleaved output:

	ginkgo -nodes=N -stream=true

On windows, the default value for stream is true.

By default, when running multiple tests (with -r or a list of packages) Ginkgo will abort when a test fails.  To have Ginkgo run subsequent test suites instead you can:

	ginkgo -keepGoing

To monitor packages and rerun tests when changes occur:

	ginkgo watch <-r> </path/to/package>

passing `ginkgo watch` the `-r` flag will recursively detect all test suites under the current directory and monitor them.
`watch` does not detect *new* packages. Moreover, changes in package X only rerun the tests for package X, tests for packages
that depend on X are not rerun.

[OSX & Linux only] To receive (desktop) notifications when a test run completes:

	ginkgo -notify

this is particularly useful with `ginkgo watch`.  Notifications are currently only supported on OS X and require that you `brew install terminal-notifier`

Sometimes (to suss out race conditions/flakey tests, for example) you want to keep running a test suite until it fails.  You can do this with:

	ginkgo -untilItFails

To bootstrap a test suite:

	ginkgo bootstrap

To generate a test file:

	ginkgo generate <test_file_name>

To bootstrap/generate test files without using "." imports:

	ginkgo bootstrap --nodot
	ginkgo generate --nodot

this will explicitly export all the identifiers in Ginkgo and Gomega allowing you to rename them to avoid collisions.  When you pull to the latest Ginkgo/Gomega you'll want to run

	ginkgo nodot

to refresh this list and pull in any new identifiers.  In particular, this will pull in any new Gomega matchers that get added.

To convert an existing XUnit style test suite to a Ginkgo-style test suite:

	ginkgo convert .

To unfocus tests:

	ginkgo unfocus

or

	ginkgo blur

To compile a test suite:

	ginkgo build <path-to-package>

will output an executable file named `package.test`.  This can be run directly or by invoking

	ginkgo <path-to-package.test>

To print out Ginkgo's version:

	ginkgo version

To get more help:

	ginkgo help
*/
package main

import (
	"flag"
	"fmt"
	"os"
	"os/exec"
	"strings"

	"github.com/onsi/ginkgo/config"
	"github.com/onsi/ginkgo/ginkgo/testsuite"
)

const greenColor = "\x1b[32m"
const redColor = "\x1b[91m"
const defaultStyle = "\x1b[0m"
const lightGrayColor = "\x1b[37m"

type Command struct {
	Name                      string
	AltName                   string
	FlagSet                   *flag.FlagSet
	Usage                     []string
	UsageCommand              string
	Command                   func(args []string, additionalArgs []string)
	SuppressFlagDocumentation bool
	FlagDocSubstitute         []string
}

func (c *Command) Matches(name string) bool {
	return c.Name == name || (c.AltName != "" && c.AltName == name)
}

func (c *Command) Run(args []string, additionalArgs []string) {
	c.FlagSet.Parse(args)
	c.Command(c.FlagSet.Args(), additionalArgs)
}

var DefaultCommand *Command
var Commands []*Command

func init() {
	DefaultCommand = BuildRunCommand()
	Commands = append(Commands, BuildWatchCommand())
	Commands = append(Commands, BuildBuildCommand())
	Commands = append(Commands, BuildBootstrapCommand())
	Commands = append(Commands, BuildGenerateCommand())
	Commands = append(Commands, BuildNodotCommand())
	Commands = append(Commands, BuildConvertCommand())
	Commands = append(Commands, BuildUnfocusCommand())
	Commands = append(Commands, BuildVersionCommand())
	Commands = append(Commands, BuildHelpCommand())
}

func main() {
	args := []string{}
	additionalArgs := []string{}

	foundDelimiter := false

	for _, arg := range os.Args[1:] {
		if !foundDelimiter {
			if arg == "--" {
				foundDelimiter = true
				continue
			}
		}

		if foundDelimiter {
			additionalArgs = append(additionalArgs, arg)
		} else {
			args = append(args, arg)
		}
	}

	if len(args) > 0 {
		commandToRun, found := commandMatching(args[0])
		if found {
			commandToRun.Run(args[1:], additionalArgs)
			return
		}
	}

	DefaultCommand.Run(args, additionalArgs)
}

func commandMatching(name string) (*Command, bool) {
	for _, command := range Commands {
		if command.Matches(name) {
			return command, true
		}
	}
	return nil, false
}

func usage() {
	fmt.Fprintf(os.Stderr, "Ginkgo Version %s\n\n", config.VERSION)
	usageForCommand(DefaultCommand, false)
	for _, command := range Commands {
		fmt.Fprintf(os.Stderr, "\n")
		usageForCommand(command, false)
	}
}

func usageForCommand(command *Command, longForm bool) {
	fmt.Fprintf(os.Stderr, "%s\n%s\n", command.UsageCommand, strings.Repeat("-", len(command.UsageCommand)))
	fmt.Fprintf(os.Stderr, "%s\n", strings.Join(command.Usage, "\n"))
	if command.SuppressFlagDocumentation && !longForm {
		fmt.Fprintf(os.Stderr, "%s\n", strings.Join(command.FlagDocSubstitute, "\n  "))
	} else {
		command.FlagSet.PrintDefaults()
	}
}

func complainAndQuit(complaint string) {
	fmt.Fprintf(os.Stderr, "%s\nFor usage instructions:\n\tginkgo help\n", complaint)
	os.Exit(1)
}

func findSuites(args []string, recurse bool, skipPackage string, allowPrecompiled bool) ([]testsuite.TestSuite, []string) {
	suites := []testsuite.TestSuite{}

	if len(args) > 0 {
		for _, arg := range args {
			if allowPrecompiled {
				suite, err := testsuite.PrecompiledTestSuite(arg)
				if err == nil {
					suites = append(suites, suite)
					continue
				}
			}
			suites = append(suites, testsuite.SuitesInDir(arg, recurse)...)
		}
	} else {
		suites = testsuite.SuitesInDir(".", recurse)
	}

	skippedPackages := []string{}
	if skipPackage != "" {
		skipFilters := strings.Split(skipPackage, ",")
		filteredSuites := []testsuite.TestSuite{}
		for _, suite := range suites {
			skip := false
			for _, skipFilter := range skipFilters {
				if strings.Contains(suite.Path, skipFilter) {
					skip = true
					break
				}
			}
			if skip {
				skippedPackages = append(skippedPackages, suite.Path)
			} else {
				filteredSuites = append(filteredSuites, suite)
			}
		}
		suites = filteredSuites
	}

	return suites, skippedPackages
}

func goFmt(path string) {
	err := exec.Command("go", "fmt", path).Run()
	if err != nil {
		complainAndQuit("Could not fmt: " + err.Error())
	}
}

func pluralizedWord(singular, plural string, count int) string {
	if count == 1 {
		return singular
	}
	return plural
}
<|endoftext|>


<commit_before>package unrolledlinkedlist

import (
	"testing"

	"github.com/zimmski/container/list"
)

func TestRunAllTests(t *testing.T) {
	lt := &list.ListTest{
		New: func(t *testing.T) list.List {
			return New(7)
		},
	}

	lt.Run(t)
}
<commit_msg>test wrong parameters for unrolled linked list<commit_after>package unrolledlinkedlist

import (
	"testing"

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

	"github.com/zimmski/container/list"
	"github.com/zimmski/container/util"
)

func TestRunAllTests(t *testing.T) {
	lt := &list.ListTest{
		New: func(t *testing.T) list.List {
			return New(7)
		},
	}

	lt.Run(t)
}

func TestNewWrongParameters(t *testing.T) {
	True(t, util.Panics(New, -1))
}
<|endoftext|>


<commit_before>/*
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 graph

import (
	"sync/atomic"
)

// Define the running cache mode, memory and/or persisent
const (
	CacheOnlyMode int = iota
	PersistentOnlyMode
	DefaultMode
)

// CachedBackend describes a cache mechanism in memory and/or persistent database
type CachedBackend struct {
	memory     *MemoryBackend
	persistent GraphBackend
	cacheMode  atomic.Value
}

// SetMode set cache mode
func (c *CachedBackend) SetMode(mode int) {
	c.cacheMode.Store(mode)
}

// NodeAdded same the node in the cache
func (c *CachedBackend) NodeAdded(n *Node) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != PersistentOnlyMode {
		r = c.memory.NodeAdded(n)
	}

	if mode != CacheOnlyMode {
		r = c.persistent.NodeAdded(n)
	}

	return r
}

// NodeDeleted Delete the node in the cache
func (c *CachedBackend) NodeDeleted(n *Node) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != PersistentOnlyMode {
		r = c.memory.NodeDeleted(n)
	}

	if mode != CacheOnlyMode {
		r = c.persistent.NodeDeleted(n)
	}

	return r
}

// GetNode retrieve a node from the cache within a time slice
func (c *CachedBackend) GetNode(i Identifier, t GraphContext) []*Node {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetNode(i, t)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetNode(i, t)
	}

	return nil
}

// GetNodeEdges retrieve a list of edges from a node within a time slice, matching metadata
func (c *CachedBackend) GetNodeEdges(n *Node, t GraphContext, m GraphElementMatcher) (edges []*Edge) {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetNodeEdges(n, t, m)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetNodeEdges(n, t, m)
	}

	return edges
}

// EdgeAdded add an edge in the cache
func (c *CachedBackend) EdgeAdded(e *Edge) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != PersistentOnlyMode {
		r = c.memory.EdgeAdded(e)
	}

	if mode != CacheOnlyMode {
		r = c.persistent.EdgeAdded(e)
	}

	return r
}

// EdgeDeleted delete an edge in the cache
func (c *CachedBackend) EdgeDeleted(e *Edge) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != PersistentOnlyMode {
		r = c.memory.EdgeDeleted(e)
	}

	if mode != CacheOnlyMode {
		r = c.persistent.EdgeDeleted(e)
	}

	return r
}

// GetEdge retrieve an edge within a time slice
func (c *CachedBackend) GetEdge(i Identifier, t GraphContext) []*Edge {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetEdge(i, t)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetEdge(i, t)
	}

	return nil
}

// GetEdgeNodes retrieve a list of nodes from an edge within a time slice, matching metadata
func (c *CachedBackend) GetEdgeNodes(e *Edge, t GraphContext, parentMetadata, childMetadata GraphElementMatcher) ([]*Node, []*Node) {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetEdgeNodes(e, t, parentMetadata, childMetadata)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetEdgeNodes(e, t, parentMetadata, childMetadata)
	}

	return nil, nil
}

// MetadataUpdated updates metadata
func (c *CachedBackend) MetadataUpdated(i interface{}) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != CacheOnlyMode {
		r = c.persistent.MetadataUpdated(i)
	}

	if mode != PersistentOnlyMode {
		r = c.memory.MetadataUpdated(i)
	}

	return r
}

// GetNodes returns a list of nodes with a time slice, matching metadata
func (c *CachedBackend) GetNodes(t GraphContext, m GraphElementMatcher) []*Node {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetNodes(t, m)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetNodes(t, m)
	}

	return []*Node{}
}

// GetEdges returns a list of edges with a time slice, matching metadata
func (c *CachedBackend) GetEdges(t GraphContext, m GraphElementMatcher) []*Edge {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetEdges(t, m)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetEdges(t, m)
	}

	return []*Edge{}
}

// IsHistorySupported returns whether the persistent backend supports history
func (c *CachedBackend) IsHistorySupported() bool {
	return c.persistent.IsHistorySupported()
}

// NewCachedBackend creates new graph cache mechanism
func NewCachedBackend(persistent GraphBackend) (*CachedBackend, error) {
	memory, err := NewMemoryBackend()
	if err != nil {
		return nil, err
	}

	sb := &CachedBackend{
		persistent: persistent,
		memory:     memory,
	}

	return sb, nil
}
<commit_msg>graph: set cached backend mode at creation time<commit_after>/*
 * Copyright (C) 2016 Red Hat, Inc.
 *
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 graph

import (
	"sync/atomic"
)

// Define the running cache mode, memory and/or persistent
const (
	CacheOnlyMode int = iota
	PersistentOnlyMode
	DefaultMode
)

// CachedBackend describes a cache mechanism in memory and/or persistent database
type CachedBackend struct {
	memory     *MemoryBackend
	persistent GraphBackend
	cacheMode  atomic.Value
}

// SetMode set cache mode
func (c *CachedBackend) SetMode(mode int) {
	c.cacheMode.Store(mode)
}

// NodeAdded same the node in the cache
func (c *CachedBackend) NodeAdded(n *Node) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != PersistentOnlyMode {
		r = c.memory.NodeAdded(n)
	}

	if mode != CacheOnlyMode {
		r = c.persistent.NodeAdded(n)
	}

	return r
}

// NodeDeleted Delete the node in the cache
func (c *CachedBackend) NodeDeleted(n *Node) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != PersistentOnlyMode {
		r = c.memory.NodeDeleted(n)
	}

	if mode != CacheOnlyMode {
		r = c.persistent.NodeDeleted(n)
	}

	return r
}

// GetNode retrieve a node from the cache within a time slice
func (c *CachedBackend) GetNode(i Identifier, t GraphContext) []*Node {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetNode(i, t)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetNode(i, t)
	}

	return nil
}

// GetNodeEdges retrieve a list of edges from a node within a time slice, matching metadata
func (c *CachedBackend) GetNodeEdges(n *Node, t GraphContext, m GraphElementMatcher) (edges []*Edge) {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetNodeEdges(n, t, m)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetNodeEdges(n, t, m)
	}

	return edges
}

// EdgeAdded add an edge in the cache
func (c *CachedBackend) EdgeAdded(e *Edge) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != PersistentOnlyMode {
		r = c.memory.EdgeAdded(e)
	}

	if mode != CacheOnlyMode {
		r = c.persistent.EdgeAdded(e)
	}

	return r
}

// EdgeDeleted delete an edge in the cache
func (c *CachedBackend) EdgeDeleted(e *Edge) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != PersistentOnlyMode {
		r = c.memory.EdgeDeleted(e)
	}

	if mode != CacheOnlyMode {
		r = c.persistent.EdgeDeleted(e)
	}

	return r
}

// GetEdge retrieve an edge within a time slice
func (c *CachedBackend) GetEdge(i Identifier, t GraphContext) []*Edge {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetEdge(i, t)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetEdge(i, t)
	}

	return nil
}

// GetEdgeNodes retrieve a list of nodes from an edge within a time slice, matching metadata
func (c *CachedBackend) GetEdgeNodes(e *Edge, t GraphContext, parentMetadata, childMetadata GraphElementMatcher) ([]*Node, []*Node) {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetEdgeNodes(e, t, parentMetadata, childMetadata)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetEdgeNodes(e, t, parentMetadata, childMetadata)
	}

	return nil, nil
}

// MetadataUpdated updates metadata
func (c *CachedBackend) MetadataUpdated(i interface{}) bool {
	mode := c.cacheMode.Load()

	r := false
	if mode != CacheOnlyMode {
		r = c.persistent.MetadataUpdated(i)
	}

	if mode != PersistentOnlyMode {
		r = c.memory.MetadataUpdated(i)
	}

	return r
}

// GetNodes returns a list of nodes with a time slice, matching metadata
func (c *CachedBackend) GetNodes(t GraphContext, m GraphElementMatcher) []*Node {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetNodes(t, m)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetNodes(t, m)
	}

	return []*Node{}
}

// GetEdges returns a list of edges with a time slice, matching metadata
func (c *CachedBackend) GetEdges(t GraphContext, m GraphElementMatcher) []*Edge {
	mode := c.cacheMode.Load()

	if t.TimeSlice == nil && mode != PersistentOnlyMode {
		return c.memory.GetEdges(t, m)
	}

	if mode != CacheOnlyMode {
		return c.persistent.GetEdges(t, m)
	}

	return []*Edge{}
}

// IsHistorySupported returns whether the persistent backend supports history
func (c *CachedBackend) IsHistorySupported() bool {
	return c.persistent.IsHistorySupported()
}

// NewCachedBackend creates new graph cache mechanism
func NewCachedBackend(persistent GraphBackend) (*CachedBackend, error) {
	memory, err := NewMemoryBackend()
	if err != nil {
		return nil, err
	}

	sb := &CachedBackend{
		persistent: persistent,
		memory:     memory,
	}

	sb.cacheMode.Store(DefaultMode)

	return sb, nil
}
<|endoftext|>