<commit_before>/*
Copyright 2019 The Kubernetes Authors.

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

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

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

package apihelpers

import (
	"sort"

	flowcontrol "k8s.io/api/flowcontrol/v1beta2"
)

// SetFlowSchemaCondition sets conditions.
func SetFlowSchemaCondition(flowSchema *flowcontrol.FlowSchema, newCondition flowcontrol.FlowSchemaCondition) {
	existingCondition := GetFlowSchemaConditionByType(flowSchema, newCondition.Type)
	if existingCondition == nil {
		flowSchema.Status.Conditions = append(flowSchema.Status.Conditions, newCondition)
		return
	}

	if existingCondition.Status != newCondition.Status {
		existingCondition.Status = newCondition.Status
		existingCondition.LastTransitionTime = newCondition.LastTransitionTime
	}

	existingCondition.Reason = newCondition.Reason
	existingCondition.Message = newCondition.Message
}

// GetFlowSchemaConditionByType gets conditions.
func GetFlowSchemaConditionByType(flowSchema *flowcontrol.FlowSchema, conditionType flowcontrol.FlowSchemaConditionType) *flowcontrol.FlowSchemaCondition {
	for i := range flowSchema.Status.Conditions {
		if flowSchema.Status.Conditions[i].Type == conditionType {
			return &flowSchema.Status.Conditions[i]
		}
	}
	return nil
}

// SetPriorityLevelConfigurationCondition sets conditions.
func SetPriorityLevelConfigurationCondition(priorityLevel *flowcontrol.PriorityLevelConfiguration, newCondition flowcontrol.PriorityLevelConfigurationCondition) {
	existingCondition := GetPriorityLevelConfigurationConditionByType(priorityLevel, newCondition.Type)
	if existingCondition == nil {
		priorityLevel.Status.Conditions = append(priorityLevel.Status.Conditions, newCondition)
		return
	}

	if existingCondition.Status != newCondition.Status {
		existingCondition.Status = newCondition.Status
		existingCondition.LastTransitionTime = newCondition.LastTransitionTime
	}

	existingCondition.Reason = newCondition.Reason
	existingCondition.Message = newCondition.Message
}

// GetPriorityLevelConfigurationConditionByType gets conditions.
func GetPriorityLevelConfigurationConditionByType(priorityLevel *flowcontrol.PriorityLevelConfiguration, conditionType flowcontrol.PriorityLevelConfigurationConditionType) *flowcontrol.PriorityLevelConfigurationCondition {
	for i := range priorityLevel.Status.Conditions {
		if priorityLevel.Status.Conditions[i].Type == conditionType {
			return &priorityLevel.Status.Conditions[i]
		}
	}
	return nil
}

var _ sort.Interface = FlowSchemaSequence{}

// FlowSchemaSequence holds sorted set of pointers to FlowSchema objects.
// FlowSchemaSequence implements `sort.Interface`
type FlowSchemaSequence []*flowcontrol.FlowSchema

func (s FlowSchemaSequence) Len() int {
	return len(s)
}

func (s FlowSchemaSequence) Less(i, j int) bool {
	// the flow-schema w/ lower matching-precedence is prior
	if ip, jp := s[i].Spec.MatchingPrecedence, s[j].Spec.MatchingPrecedence; ip != jp {
		return ip < jp
	}
	// sort alphabetically
	return s[i].Name < s[j].Name
}

func (s FlowSchemaSequence) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
<commit_msg>apiserver: update apf tests to use v1beta3<commit_after>/*
Copyright 2019 The Kubernetes Authors.

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

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

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

package apihelpers

import (
	"sort"

	flowcontrol "k8s.io/api/flowcontrol/v1beta3"
)

// SetFlowSchemaCondition sets conditions.
func SetFlowSchemaCondition(flowSchema *flowcontrol.FlowSchema, newCondition flowcontrol.FlowSchemaCondition) {
	existingCondition := GetFlowSchemaConditionByType(flowSchema, newCondition.Type)
	if existingCondition == nil {
		flowSchema.Status.Conditions = append(flowSchema.Status.Conditions, newCondition)
		return
	}

	if existingCondition.Status != newCondition.Status {
		existingCondition.Status = newCondition.Status
		existingCondition.LastTransitionTime = newCondition.LastTransitionTime
	}

	existingCondition.Reason = newCondition.Reason
	existingCondition.Message = newCondition.Message
}

// GetFlowSchemaConditionByType gets conditions.
func GetFlowSchemaConditionByType(flowSchema *flowcontrol.FlowSchema, conditionType flowcontrol.FlowSchemaConditionType) *flowcontrol.FlowSchemaCondition {
	for i := range flowSchema.Status.Conditions {
		if flowSchema.Status.Conditions[i].Type == conditionType {
			return &flowSchema.Status.Conditions[i]
		}
	}
	return nil
}

// SetPriorityLevelConfigurationCondition sets conditions.
func SetPriorityLevelConfigurationCondition(priorityLevel *flowcontrol.PriorityLevelConfiguration, newCondition flowcontrol.PriorityLevelConfigurationCondition) {
	existingCondition := GetPriorityLevelConfigurationConditionByType(priorityLevel, newCondition.Type)
	if existingCondition == nil {
		priorityLevel.Status.Conditions = append(priorityLevel.Status.Conditions, newCondition)
		return
	}

	if existingCondition.Status != newCondition.Status {
		existingCondition.Status = newCondition.Status
		existingCondition.LastTransitionTime = newCondition.LastTransitionTime
	}

	existingCondition.Reason = newCondition.Reason
	existingCondition.Message = newCondition.Message
}

// GetPriorityLevelConfigurationConditionByType gets conditions.
func GetPriorityLevelConfigurationConditionByType(priorityLevel *flowcontrol.PriorityLevelConfiguration, conditionType flowcontrol.PriorityLevelConfigurationConditionType) *flowcontrol.PriorityLevelConfigurationCondition {
	for i := range priorityLevel.Status.Conditions {
		if priorityLevel.Status.Conditions[i].Type == conditionType {
			return &priorityLevel.Status.Conditions[i]
		}
	}
	return nil
}

var _ sort.Interface = FlowSchemaSequence{}

// FlowSchemaSequence holds sorted set of pointers to FlowSchema objects.
// FlowSchemaSequence implements `sort.Interface`
type FlowSchemaSequence []*flowcontrol.FlowSchema

func (s FlowSchemaSequence) Len() int {
	return len(s)
}

func (s FlowSchemaSequence) Less(i, j int) bool {
	// the flow-schema w/ lower matching-precedence is prior
	if ip, jp := s[i].Spec.MatchingPrecedence, s[j].Spec.MatchingPrecedence; ip != jp {
		return ip < jp
	}
	// sort alphabetically
	return s[i].Name < s[j].Name
}

func (s FlowSchemaSequence) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}
<|endoftext|>


<commit_before>package usecases

import (
	"testing"

	"github.com/declantraynor/go-events-service/domain"
)

type StubEventStore struct{}

func (stub *StubEventStore) Put(event domain.Event) error {
	return nil
}

func TestAddEventSucceeds(t *testing.T) {
	interactor := EventInteractor{Store: new(StubEventStore)}
	if err := interactor.Add("test-event", "2015-02-11T15:01:00+00:00"); err != nil {
		t.Fail()
	}
}

func TestAddEventChecksForISOTimestamp(t *testing.T) {
	interactor := EventInteractor{Store: new(StubEventStore)}
	err := interactor.Add("test-event", "2015/02/01 15:01")

	if err == nil || err.Error() != "timestamps must conform to ISO8601" {
		t.Fail()
	}
}

func TestAddEventChecksForUTCTimestamp(t *testing.T) {
	interactor := EventInteractor{Store: new(StubEventStore)}
	err := interactor.Add("test-event", "2015-02-11T15:01:00-05:00")

	if err == nil || err.Error() != "timestamps must be UTC" {
		t.Fail()
	}
}
<commit_msg>test add event use case against event store failure<commit_after>package usecases

import (
	"errors"
	"testing"

	"github.com/declantraynor/go-events-service/domain"
)

type PassingEventStore struct{}

func (stub *PassingEventStore) Put(event domain.Event) error {
	return nil
}

type FailingEventStore struct{}

func (stub *FailingEventStore) Put(event domain.Event) error {
	return errors.New("error from EventStore->Put")
}

func TestAddSucceeds(t *testing.T) {
	interactor := EventInteractor{Store: new(PassingEventStore)}
	if err := interactor.Add("test-event", "2015-02-11T15:01:00+00:00"); err != nil {
		t.Fail()
	}
}

func TestAddChecksForISOTimestamp(t *testing.T) {
	interactor := EventInteractor{Store: new(PassingEventStore)}
	err := interactor.Add("test-event", "2015/02/01 15:01")

	if err == nil || err.Error() != "timestamps must conform to ISO8601" {
		t.Fail()
	}
}

func TestAddChecksForUTCTimestamp(t *testing.T) {
	interactor := EventInteractor{Store: new(PassingEventStore)}
	err := interactor.Add("test-event", "2015-02-11T15:01:00-05:00")

	if err == nil || err.Error() != "timestamps must be UTC" {
		t.Fail()
	}
}

func TestAddEncountersEventStoreError(t *testing.T) {
	interactor := EventInteractor{Store: new(FailingEventStore)}
	if err := interactor.Add("test-event", "2015-02-11T15:01:00+00:00"); err == nil {
		t.Fail()
	}
}
<|endoftext|>


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

// +build example jsgo

package main

import (
	"image/color"
	"log"

	"github.com/hajimehoshi/ebiten"
	"github.com/hajimehoshi/ebiten/vector"
)

const (
	screenWidth  = 640
	screenHeight = 480
)

func update(screen *ebiten.Image) error {
	if ebiten.IsDrawingSkipped() {
		return nil
	}

	var path vector.Path
	path.MoveTo(20, 20)
	path.LineTo(30, 50)

	op := &vector.DrawPathOptions{}
	op.LineWidth = 4
	op.StrokeColor = color.White
	path.Draw(screen, op)

	return nil
}

func main() {
	if err := ebiten.Run(update, screenWidth, screenHeight, 1, "Vector (Ebiten Demo)"); err != nil {
		log.Fatal(err)
	}
}
<commit_msg>examples/vector: Render more texts<commit_after>// Copyright 2019 The Ebiten Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

// +build example jsgo

package main

import (
	"image/color"
	"log"

	"github.com/hajimehoshi/ebiten"
	"github.com/hajimehoshi/ebiten/vector"
)

const (
	screenWidth  = 640
	screenHeight = 480
)

func update(screen *ebiten.Image) error {
	if ebiten.IsDrawingSkipped() {
		return nil
	}

	var path vector.Path

	// E
	path.MoveTo(20, 20)
	path.LineTo(20, 60)
	path.MoveTo(20, 20)
	path.LineTo(60, 20)
	path.MoveTo(20, 40)
	path.LineTo(60, 40)
	path.MoveTo(20, 60)
	path.LineTo(60, 60)

	// B
	path.MoveTo(80, 20)
	path.LineTo(80, 60)
	path.LineTo(110, 60)
	path.LineTo(120, 50)
	path.LineTo(110, 40)
	path.LineTo(120, 30)
	path.LineTo(110, 20)
	path.LineTo(80, 20)
	path.MoveTo(80, 40)
	path.LineTo(110, 40)

	// I
	path.MoveTo(140, 20)
	path.LineTo(140, 60)

	// T
	path.MoveTo(160, 20)
	path.LineTo(200, 20)
	path.MoveTo(180, 20)
	path.LineTo(180, 60)

	// E
	path.MoveTo(220, 20)
	path.LineTo(220, 60)
	path.MoveTo(220, 20)
	path.LineTo(260, 20)
	path.MoveTo(220, 40)
	path.LineTo(260, 40)
	path.MoveTo(220, 60)
	path.LineTo(260, 60)

	// N
	path.MoveTo(280, 60)
	path.LineTo(280, 20)
	path.LineTo(320, 60)
	path.LineTo(320, 20)

	op := &vector.DrawPathOptions{}
	op.LineWidth = 4
	op.StrokeColor = color.White
	path.Draw(screen, op)

	return nil
}

func main() {
	if err := ebiten.Run(update, screenWidth, screenHeight, 1, "Vector (Ebiten Demo)"); err != nil {
		log.Fatal(err)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"github.com/yvasiyarov/newrelic_platform_go"
)

type WaveMetrica struct {
	sawtoothMax     int
	sawtoothCounter int
}

func (metrica WaveMetrica) GetName() string {
	return "Wave_Metrica"
}
func (metrica WaveMetrica) GetUnits() string {
	return "Queries/Second"
}
func (metrica WaveMetrica) GetValue() (float64, error) {
	metrica.sawtoothCounter = metrica.sawtoothCounter + 1
	if metrica.sawtoothCounter > metrica.sawtoothMax {
		metrica.sawtoothCounter = 0
	}
	return float64(metrica.sawtoothCounter), nil
}

type SquareWaveMetrica struct {
	squarewaveMax     int
	squarewaveCounter int
}

func (metrica SquareWaveMetrica) GetName() string {
	return "SquareWave_Metrica"
}
func (metrica SquareWaveMetrica) GetUnits() string {
	return "Queries/Second"
}
func (metrica SquareWaveMetrica) GetValue() (float64, error) {
	returnValue := 0
	metrica.squarewaveCounter = metrica.squarewaveCounter + 1
	if metrica.squarewaveCounter < (metrica.squarewaveMax / 2) {
		returnValue = 0
	} else {
		returnValue = metrica.squarewaveMax
	}

	if metrica.squarewaveCounter > metrica.squarewaveMax {
		metrica.squarewaveCounter = 0
	}
	return float64(returnValue), nil
}

func main() {
	plugin := newrelic_platform_go.NewNewrelicPlugin("0.0.1", "7bceac019c7dcafae1ef95be3e3a3ff8866de246", 60)
	component := newrelic_platform_go.NewPluginComponent("Wave component", "com.exmaple.plugin.gowave")
	plugin.AddComponent(component)

	m := WaveMetrica{
		sawtoothMax:     10,
		sawtoothCounter: 5,
	}
	component.AddMetrica(m)

	m1 := SquareWaveMetrica{
		squarewaveMax:     14,
		squarewaveCounter: 7,
	}
	component.AddMetrica(m1)

	plugin.Verbose = true
	plugin.Run()
}
<commit_msg>Wave plugin is fixed<commit_after>package main

import (
	"github.com/yvasiyarov/newrelic_platform_go"
)

type WaveMetrica struct {
	sawtoothMax     int
	sawtoothCounter int
}

func (metrica *WaveMetrica) GetName() string {
	return "Wave_Metrica"
}
func (metrica *WaveMetrica) GetUnits() string {
	return "Queries/Second"
}
func (metrica *WaveMetrica) GetValue() (float64, error) {
	metrica.sawtoothCounter++
	if metrica.sawtoothCounter > metrica.sawtoothMax {
		metrica.sawtoothCounter = 0
	}
	return float64(metrica.sawtoothCounter), nil
}

type SquareWaveMetrica struct {
	squarewaveMax     int
	squarewaveCounter int
}

func (metrica *SquareWaveMetrica) GetName() string {
	return "SquareWave_Metrica"
}
func (metrica *SquareWaveMetrica) GetUnits() string {
	return "Queries/Second"
}
func (metrica *SquareWaveMetrica) GetValue() (float64, error) {
	returnValue := 0
	metrica.squarewaveCounter++

	if metrica.squarewaveCounter < (metrica.squarewaveMax / 2) {
		returnValue = 0
	} else {
		returnValue = metrica.squarewaveMax
	}

	if metrica.squarewaveCounter > metrica.squarewaveMax {
		metrica.squarewaveCounter = 0
	}
	return float64(returnValue), nil
}

func main() {
	plugin := newrelic_platform_go.NewNewrelicPlugin("0.0.1", "7bceac019c7dcafae1ef95be3e3a3ff8866de246", 60)
	component := newrelic_platform_go.NewPluginComponent("Wave component", "com.exmaple.plugin.gowave")
	plugin.AddComponent(component)

	m := &WaveMetrica{
		sawtoothMax:     10,
		sawtoothCounter: 5,
	}
	component.AddMetrica(m)

	m1 := &SquareWaveMetrica{
		squarewaveMax:     4,
		squarewaveCounter: 1,
	}
	component.AddMetrica(m1)

	plugin.Verbose = true
	plugin.Run()
}
<|endoftext|>


<commit_before>package main

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"

	. "github.com/franela/goblin"
	"github.com/gin-gonic/gin"
	"github.com/prashantv/gostub"
	"github.com/rlmcpherson/s3gof3r"
)

// create body writer POST
func postForm(uri string, params map[string]string) (*http.Request, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}

	defer writer.Close()

	req, err := http.NewRequest("POST", uri, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())
	return req, err
}

// Creates a new file upload http request with optional extra params
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, filepath.Base(path))
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(part, file)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", uri, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())
	return req, err
}

func Test(t *testing.T) {
	g := Goblin(t)
	g.Describe("Request Specs:", func() {
		g.Before(func() {
			gin.SetMode(gin.ReleaseMode)
		})
		g.Describe("/:", func() {
			g.It("route / should have proper body", func() {

				req, err := http.NewRequest("GET", "/", nil)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				g.Assert(resp.Code).Equal(200)
				g.Assert(resp.Body.String()).Equal("{\"url\":\"hello\"}\n")
			})
		})
		g.Describe("/upload:", func() {
			g.It("route /upload should return the 200/file on s3 upload success", func() {
				// stubs
				uuidStub := gostub.Stub(&uuidGenerator, func() string {
					return "test"
				})
				defer uuidStub.Reset()
				s3Stub := gostub.Stub(&s3Uploader, func(bucket *s3gof3r.Bucket, filename string, file multipart.File, c *gin.Context) error {
					return nil
				})
				defer s3Stub.Reset()

				extraParams := map[string]string{}
				req, err := newfileUploadRequest("/upload", extraParams, "file", "test.png")
				if err != nil {
					fmt.Println(err)
				}

				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert filename
				g.Assert(resp.Body.String()).Equal("{\"file\":\"test.png\"}\n")
				// assert 200
				g.Assert(resp.Code).Equal(200)
			})
			g.It("route /upload should return 500/error on s3 upload error", func() {
				// stubs
				uuidStub := gostub.Stub(&uuidGenerator, func() string {
					return "test"
				})
				defer uuidStub.Reset()
				s3Stub := gostub.Stub(&s3Uploader, func(bucket *s3gof3r.Bucket, filename string, file multipart.File, c *gin.Context) error {
					return errors.New("cannot upload to s3")
				})
				defer s3Stub.Reset()

				extraParams := map[string]string{}
				req, err := newfileUploadRequest("/upload", extraParams, "file", "test.png")
				if err != nil {
					fmt.Println(err)
				}

				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"there was an error uploading\"}\n")
				// assert 500
				g.Assert(resp.Code).Equal(500)
			})
			g.It("route /upload should return 400/error on no file", func() {
				extraParams := map[string]string{}
				req, err := newfileUploadRequest("/upload", extraParams, "test", "test.png")
				if err != nil {
					fmt.Println(err)
				}

				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"you need to provide a file to upload\"}\n")
				// assert 500
				g.Assert(resp.Code).Equal(400)
			})
		})
		g.Describe("/download:", func() {
			g.It("route /download should return 400/error on no file", func() {
				params := map[string]string{
					"test": "test.png",
				}
				req, err := postForm("/download", params)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"you must provide a file to download\"}\n")
				// assert 400
				g.Assert(resp.Code).Equal(400)
			})
			g.It("route /download should return 500/error on s3 error", func() {
				// stubs
				s3DownloadStub := gostub.Stub(&s3Downloader, func(bucket *s3gof3r.Bucket, filename string) (*bytes.Buffer, error) {
					return new(bytes.Buffer), errors.New("cannot download from s3")
				})
				defer s3DownloadStub.Reset()
				params := map[string]string{
					"file": "test.png",
				}
				req, err := postForm("/download", params)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"there was an error downloading\"}\n")
				// assert 500
				g.Assert(resp.Code).Equal(500)
			})
			g.It("route /download should return 500/error on mimeType error", func() {
				// stubs
				s3DownloadStub := gostub.Stub(&s3Downloader, func(bucket *s3gof3r.Bucket, filename string) (*bytes.Buffer, error) {
					return new(bytes.Buffer), nil
				})
				defer s3DownloadStub.Reset()
				getMimeTypeStub := gostub.Stub(&getMimeTyper, func(s3Buffer *bytes.Buffer) (string, error) {
					return "", errors.New("mime type reading failed")
				})
				defer getMimeTypeStub.Reset()
				params := map[string]string{
					"file": "test.png",
				}
				req, err := postForm("/download", params)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"there was an error reading the mime type\"}\n")
				// assert 500
				g.Assert(resp.Code).Equal(500)
			})
			g.It("route /download should return 200/file on success", func() {
				// stubs
				s3DownloadStub := gostub.Stub(&s3Downloader, func(bucket *s3gof3r.Bucket, filename string) (*bytes.Buffer, error) {
					return new(bytes.Buffer), nil
				})
				defer s3DownloadStub.Reset()
				getMimeTypeStub := gostub.Stub(&getMimeTyper, func(s3Buffer *bytes.Buffer) (string, error) {
					return "image/png", nil
				})
				defer getMimeTypeStub.Reset()
				params := map[string]string{
					"file": "test.png",
				}
				req, err := postForm("/download", params)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert file stream
				g.Assert(resp.Body).Equal(new(bytes.Buffer))
				// assert 200
				g.Assert(resp.Code).Equal(200)
			})
		})
	})
}
<commit_msg>hide logs in test<commit_after>package main

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"mime/multipart"
	"net/http"
	"net/http/httptest"
	"os"
	"path/filepath"
	"testing"

	. "github.com/franela/goblin"
	"github.com/gin-gonic/gin"
	"github.com/prashantv/gostub"
	"github.com/rlmcpherson/s3gof3r"
)

// create body writer POST
func postForm(uri string, params map[string]string) (*http.Request, error) {
	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}

	defer writer.Close()

	req, err := http.NewRequest("POST", uri, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())
	return req, err
}

// Creates a new file upload http request with optional extra params
func newfileUploadRequest(uri string, params map[string]string, paramName, path string) (*http.Request, error) {
	file, err := os.Open(path)
	if err != nil {
		return nil, err
	}
	defer file.Close()

	body := &bytes.Buffer{}
	writer := multipart.NewWriter(body)
	part, err := writer.CreateFormFile(paramName, filepath.Base(path))
	if err != nil {
		return nil, err
	}
	_, err = io.Copy(part, file)

	for key, val := range params {
		_ = writer.WriteField(key, val)
	}
	err = writer.Close()
	if err != nil {
		return nil, err
	}

	req, err := http.NewRequest("POST", uri, body)
	req.Header.Add("Content-Type", writer.FormDataContentType())
	return req, err
}

func Test(t *testing.T) {
	g := Goblin(t)
	g.Describe("Request Specs:", func() {
		g.Before(func() {
			// set to release mode to hide debug warning
			gin.SetMode(gin.ReleaseMode)
			// disable logging in test
			log.SetOutput(ioutil.Discard)
		})
		g.Describe("/:", func() {
			g.It("route / should have proper body", func() {

				req, err := http.NewRequest("GET", "/", nil)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				g.Assert(resp.Code).Equal(200)
				g.Assert(resp.Body.String()).Equal("{\"url\":\"hello\"}\n")
			})
		})
		g.Describe("/upload:", func() {
			g.It("route /upload should return the 200/file on s3 upload success", func() {
				// stubs
				uuidStub := gostub.Stub(&uuidGenerator, func() string {
					return "test"
				})
				defer uuidStub.Reset()
				s3Stub := gostub.Stub(&s3Uploader, func(bucket *s3gof3r.Bucket, filename string, file multipart.File, c *gin.Context) error {
					return nil
				})
				defer s3Stub.Reset()

				extraParams := map[string]string{}
				req, err := newfileUploadRequest("/upload", extraParams, "file", "test.png")
				if err != nil {
					fmt.Println(err)
				}

				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert filename
				g.Assert(resp.Body.String()).Equal("{\"file\":\"test.png\"}\n")
				// assert 200
				g.Assert(resp.Code).Equal(200)
			})
			g.It("route /upload should return 500/error on s3 upload error", func() {
				// stubs
				uuidStub := gostub.Stub(&uuidGenerator, func() string {
					return "test"
				})
				defer uuidStub.Reset()
				s3Stub := gostub.Stub(&s3Uploader, func(bucket *s3gof3r.Bucket, filename string, file multipart.File, c *gin.Context) error {
					return errors.New("cannot upload to s3")
				})
				defer s3Stub.Reset()

				extraParams := map[string]string{}
				req, err := newfileUploadRequest("/upload", extraParams, "file", "test.png")
				if err != nil {
					fmt.Println(err)
				}

				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"there was an error uploading\"}\n")
				// assert 500
				g.Assert(resp.Code).Equal(500)
			})
			g.It("route /upload should return 400/error on no file", func() {
				extraParams := map[string]string{}
				req, err := newfileUploadRequest("/upload", extraParams, "test", "test.png")
				if err != nil {
					fmt.Println(err)
				}

				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"you need to provide a file to upload\"}\n")
				// assert 500
				g.Assert(resp.Code).Equal(400)
			})
		})
		g.Describe("/download:", func() {
			g.It("route /download should return 400/error on no file", func() {
				params := map[string]string{
					"test": "test.png",
				}
				req, err := postForm("/download", params)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				// router and upload
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"you must provide a file to download\"}\n")
				// assert 400
				g.Assert(resp.Code).Equal(400)
			})
			g.It("route /download should return 500/error on s3 error", func() {
				// stubs
				s3DownloadStub := gostub.Stub(&s3Downloader, func(bucket *s3gof3r.Bucket, filename string) (*bytes.Buffer, error) {
					return new(bytes.Buffer), errors.New("cannot download from s3")
				})
				defer s3DownloadStub.Reset()
				params := map[string]string{
					"file": "test.png",
				}
				req, err := postForm("/download", params)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"there was an error downloading\"}\n")
				// assert 500
				g.Assert(resp.Code).Equal(500)
			})
			g.It("route /download should return 500/error on mimeType error", func() {
				// stubs
				s3DownloadStub := gostub.Stub(&s3Downloader, func(bucket *s3gof3r.Bucket, filename string) (*bytes.Buffer, error) {
					return new(bytes.Buffer), nil
				})
				defer s3DownloadStub.Reset()
				getMimeTypeStub := gostub.Stub(&getMimeTyper, func(s3Buffer *bytes.Buffer) (string, error) {
					return "", errors.New("mime type reading failed")
				})
				defer getMimeTypeStub.Reset()
				params := map[string]string{
					"file": "test.png",
				}
				req, err := postForm("/download", params)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert error
				g.Assert(resp.Body.String()).Equal("{\"error\":\"there was an error reading the mime type\"}\n")
				// assert 500
				g.Assert(resp.Code).Equal(500)
			})
			g.It("route /download should return 200/file on success", func() {
				// stubs
				s3DownloadStub := gostub.Stub(&s3Downloader, func(bucket *s3gof3r.Bucket, filename string) (*bytes.Buffer, error) {
					return new(bytes.Buffer), nil
				})
				defer s3DownloadStub.Reset()
				getMimeTypeStub := gostub.Stub(&getMimeTyper, func(s3Buffer *bytes.Buffer) (string, error) {
					return "image/png", nil
				})
				defer getMimeTypeStub.Reset()
				params := map[string]string{
					"file": "test.png",
				}
				req, err := postForm("/download", params)
				if err != nil {
					fmt.Println(err)
				}
				resp := httptest.NewRecorder()
				testRouter := GinEngine()
				testRouter.ServeHTTP(resp, req)
				// assert file stream
				g.Assert(resp.Body).Equal(new(bytes.Buffer))
				// assert 200
				g.Assert(resp.Code).Equal(200)
			})
		})
	})
}
<|endoftext|>


<commit_before>package trevor

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"
)

func TestRun(t *testing.T) {
	server := NewServer(Config{
		Plugins:  dummyPlugins(),
		Port:     8888,
		Endpoint: "get_data",
	})

	go func() {
		server.Run()
	}()

	time.Sleep(5 * time.Millisecond)

	jsonStr := []byte(`{"text":"how are you?"}`)
	req, err := http.NewRequest("POST", "http://0.0.0.0:8888/get_data", bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()

	if resp.Status != "200 OK" {
		t.Errorf("expected status 200, got %s", resp.Status)
	}

	body, _ := ioutil.ReadAll(resp.Body)
	if strings.TrimSpace(string(body)) != `{"data":"fine, and you?","error":false,"type":"salute"}` {
		t.Error("invalid response got")
	}
}
<commit_msg>More code coverage<commit_after>package trevor

import (
	"bytes"
	"io/ioutil"
	"net/http"
	"strings"
	"testing"
	"time"
)

func makeRequest(text string) (string, string) {
	server := NewServer(Config{
		Plugins:  dummyPlugins(),
		Port:     8888,
		Endpoint: "get_data",
	})

	go func() {
		server.Run()
	}()

	time.Sleep(5 * time.Millisecond)

	jsonStr := []byte(text)
	req, err := http.NewRequest("POST", "http://0.0.0.0:8888/get_data", bytes.NewBuffer(jsonStr))
	if err != nil {
		panic(err)
	}
	req.Header.Set("Content-Type", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		panic(err)
	}
	defer resp.Body.Close()
	body, _ := ioutil.ReadAll(resp.Body)

	return string(body), resp.Status
}

func TestRun(t *testing.T) {
	body, status := makeRequest(`{"text":"how are you?"}`)

	if status != "200 OK" {
		t.Errorf("expected status 200, got %s", status)
	}

	if strings.TrimSpace(body) != `{"data":"fine, and you?","error":false,"type":"salute"}` {
		t.Error("invalid response got")
	}
}

func TestRunNoText(t *testing.T) {
	_, status := makeRequest(`{"foo":"bar"}`)

	if status != "400 Bad Request" {
		t.Errorf("expected status 400, got %s", status)
	}
}

func TestRunTextEmpty(t *testing.T) {
	_, status := makeRequest(`{"text":""}`)

	if status != "400 Bad Request" {
		t.Errorf("expected status 400, got %s", status)
	}
}
<|endoftext|>


<commit_before>package revel

import (
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"reflect"
	"strings"
	"testing"
)

// A copy of the hotel struct from the sample app.
type Hotel struct {
	HotelId          int
	Name, Address    string
	City, State, Zip string
	Country          string
	Price            int
}

type Hotels struct {
	*Controller
}

func (c Hotels) Show(id int) Result {
	title := "View Hotel"
	hotel := &Hotel{id, "A Hotel", "300 Main St.", "New York", "NY", "10010", "USA", 300}
	return c.Render(title, hotel)
}

// This tries to benchmark the usual request-serving pipeline to get an overall
// performance metric.
//
// Each iteration runs one mock request to display a hotel's detail page by id,
// and 10 static requests for a file, sized 7k.
//
// Contributing parts:
// - Routing
// - Controller lookup / invocation
// - Parameter binding
// - Session, flash, i18n cookies
// - Render() call magic
// - Validation magic
// - Template rendering
func BenchmarkRevel(b *testing.B) {
	Init("", "github.com/robfig/revel/samples/booking", "")

	TRACE = log.New(ioutil.Discard, "", 0)
	INFO = TRACE
	WARN = TRACE
	ERROR = TRACE

	MainRouter = NewRouter("")
	routesFile, _ := ioutil.ReadFile(filepath.Join(BasePath, "conf", "routes"))
	MainRouter.parse(string(routesFile), false)
	MainTemplateLoader = NewTemplateLoader([]string{ViewsPath})
	MainTemplateLoader.Refresh()

	RegisterController((*Hotels)(nil),
		[]*MethodType{
			&MethodType{
				Name: "Show",
				Args: []*MethodArg{
					{"id", reflect.TypeOf((*int)(nil))},
				},
				RenderArgNames: map[int][]string{30: []string{"title", "hotel"}},
			},
		})

	plugins.OnAppStart()

	showRequest, _ := http.NewRequest("GET", "/hotels/3", nil)
	staticRequest, _ := http.NewRequest("GET", "/public/js/sessvars.js", nil)

	resp := httptest.NewRecorder()

	// First, test that the expected responses are actually generated
	handle(resp, showRequest)
	if !strings.Contains(resp.Body.String(), "300 Main St.") {
		b.Errorf("Failed to find hotel address in action response:\n%s", resp.Body)
		b.FailNow()
	}
	resp.Body.Reset()

	handle(resp, staticRequest)
	if resp.Body.Len() != 6712 {
		b.Errorf("Expected sessvars.js to have 6712 bytes, got %d:\n%s", resp.Body.Len(), resp.Body)
		b.FailNow()
	}

	resp.Body = nil
	b.ResetTimer()

	// Each iteration, run 1 action and 10 static requests.
	for i := 0; i < b.N; i++ {
		handle(resp, showRequest)
		for j := 0; j < 10; j++ {
			handle(resp, staticRequest)
		}
	}
}
<commit_msg>Break the server benchmarks into Action and Static cases.<commit_after>package revel

import (
	"io/ioutil"
	"log"
	"net/http"
	"net/http/httptest"
	"path/filepath"
	"reflect"
	"strings"
	"testing"
)

// A copy of the hotel struct from the sample app.
type Hotel struct {
	HotelId          int
	Name, Address    string
	City, State, Zip string
	Country          string
	Price            int
}

type Hotels struct {
	*Controller
}

func (c Hotels) Show(id int) Result {
	title := "View Hotel"
	hotel := &Hotel{id, "A Hotel", "300 Main St.", "New York", "NY", "10010", "USA", 300}
	return c.Render(title, hotel)
}

// This tries to benchmark the usual request-serving pipeline to get an overall
// performance metric.
//
// Each iteration runs one mock request to display a hotel's detail page by id.
//
// Contributing parts:
// - Routing
// - Controller lookup / invocation
// - Parameter binding
// - Session, flash, i18n cookies
// - Render() call magic
// - Template rendering
func BenchmarkServeAction(b *testing.B) {
	benchmarkRequest(b, showRequest)
}

// This tries to benchmark the static serving overhead when serving an "average
// size" 7k file.
func BenchmarkServeStatic(b *testing.B) {
	benchmarkRequest(b, staticRequest)
}

func benchmarkRequest(b *testing.B, req *http.Request) {
	resp := httptest.NewRecorder()
	startFakeBookingApp(b)
	for i := 0; i < b.N; i++ {
		handle(resp, req)
	}
}

var (
	showRequest, _   = http.NewRequest("GET", "/hotels/3", nil)
	staticRequest, _ = http.NewRequest("GET", "/public/js/sessvars.js", nil)
)

func startFakeBookingApp(b *testing.B) {
	Init("", "github.com/robfig/revel/samples/booking", "")

	// Disable logging.
	TRACE = log.New(ioutil.Discard, "", 0)
	INFO = TRACE
	WARN = TRACE
	ERROR = TRACE

	MainRouter = NewRouter("")
	routesFile, _ := ioutil.ReadFile(filepath.Join(BasePath, "conf", "routes"))
	MainRouter.parse(string(routesFile), false)
	MainTemplateLoader = NewTemplateLoader([]string{ViewsPath})
	MainTemplateLoader.Refresh()

	RegisterController((*Hotels)(nil),
		[]*MethodType{
			&MethodType{
				Name: "Show",
				Args: []*MethodArg{
					{"id", reflect.TypeOf((*int)(nil))},
				},
				RenderArgNames: map[int][]string{30: []string{"title", "hotel"}},
			},
		})

	plugins.OnAppStart()

	resp := httptest.NewRecorder()

	// First, test that the expected responses are actually generated
	handle(resp, showRequest)
	if !strings.Contains(resp.Body.String(), "300 Main St.") {
		b.Errorf("Failed to find hotel address in action response:\n%s", resp.Body)
		b.FailNow()
	}
	resp.Body.Reset()

	handle(resp, staticRequest)
	if resp.Body.Len() != 6712 {
		b.Errorf("Expected sessvars.js to have 6712 bytes, got %d:\n%s", resp.Body.Len(), resp.Body)
		b.FailNow()
	}

	resp.Body = nil
	b.ResetTimer()
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

const ucdFileName = "UnicodeData.txt"
const ucdBaseUrl = "http://www.unicode.org/Public/UCD/latest/ucd/"

func progress(done *bool) {
	for !*done {
		fmt.Print(".")
		time.Sleep(200 * time.Millisecond)
	}
	fmt.Println()
}

func getUcdFile(fileName string) {
	url := ucdBaseUrl + ucdFileName
	fmt.Printf("%s not found\nretrieving from %s\n", ucdFileName, url)
	done := false
	go progress(&done)
	defer func() {
		done = true
	}()
	response, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	file, err := os.Create(fileName)
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(file, response.Body)
	if err != nil {
		panic(err)
	}
	file.Close()
}

func loadIndex(fileName string) (map[string][]rune, map[rune]string) {
	if _, err := os.Stat(fileName); os.IsNotExist(err) {
		getUcdFile(fileName)
	}
	content, err := ioutil.ReadFile(fileName)
	if err != nil {
		panic(err)
	}

	lines := strings.Split(string(content), "\n")

	index := make(map[string][]rune)
	names := make(map[rune]string)

	for _, line := range lines {
		var uchar rune
		fields := strings.Split(line, ";")
		if len(fields) >= 2 {
			code64, _ := strconv.ParseInt(fields[0], 16, 0)
			uchar = rune(code64)
			names[uchar] = fields[1]
			for _, word := range strings.Split(fields[1], " ") {
				var entries []rune
				if len(index[word]) < 1 {
					entries = make([]rune, 0)
				} else {
					entries = index[word]
				}
				index[word] = append(entries, uchar)
			}
		}

	}
	return index, names
}

func main() {
	dir, _ := os.Getwd()
	path := path.Join(dir, ucdFileName)
	index, names := loadIndex(path)
	if len(os.Args) != 2 {
		fmt.Println("Usage:  runefinder <word>\texample: runefinder cat")
		os.Exit(1)
	}

	word := strings.ToUpper(os.Args[1])
	for _, uchar := range index[word] {
		fmt.Printf("U+%-5X %c \t%s\n", uchar, uchar, names[uchar])
	}

}
<commit_msg>renamed function progress to progressDisplay<commit_after>package main

import (
	"fmt"
	"io"
	"io/ioutil"
	"net/http"
	"os"
	"path"
	"strconv"
	"strings"
	"time"
)

const ucdFileName = "UnicodeData.txt"
const ucdBaseUrl = "http://www.unicode.org/Public/UCD/latest/ucd/"

func progressDisplay(done *bool) {
	for !*done {
		fmt.Print(".")
		time.Sleep(150 * time.Millisecond)
	}
	fmt.Println()
}

func getUcdFile(fileName string) {
	url := ucdBaseUrl + ucdFileName
	fmt.Printf("%s not found\nretrieving from %s\n", ucdFileName, url)
	done := false
	go progressDisplay(&done)
	defer func() {
		done = true
	}()
	response, err := http.Get(url)
	if err != nil {
		panic(err)
	}
	defer response.Body.Close()
	file, err := os.Create(fileName)
	if err != nil {
		panic(err)
	}
	_, err = io.Copy(file, response.Body)
	if err != nil {
		panic(err)
	}
	file.Close()
}

func loadIndex(fileName string) (map[string][]rune, map[rune]string) {
	if _, err := os.Stat(fileName); os.IsNotExist(err) {
		getUcdFile(fileName)
	}
	content, err := ioutil.ReadFile(fileName)
	if err != nil {
		panic(err)
	}

	lines := strings.Split(string(content), "\n")

	index := make(map[string][]rune)
	names := make(map[rune]string)

	for _, line := range lines {
		var uchar rune
		fields := strings.Split(line, ";")
		if len(fields) >= 2 {
			code64, _ := strconv.ParseInt(fields[0], 16, 0)
			uchar = rune(code64)
			names[uchar] = fields[1]
			for _, word := range strings.Split(fields[1], " ") {
				var entries []rune
				if len(index[word]) < 1 {
					entries = make([]rune, 0)
				} else {
					entries = index[word]
				}
				index[word] = append(entries, uchar)
			}
		}

	}
	return index, names
}

func main() {
	dir, _ := os.Getwd()
	path := path.Join(dir, ucdFileName)
	index, names := loadIndex(path)
	if len(os.Args) != 2 {
		fmt.Println("Usage:  runefinder <word>\texample: runefinder cat")
		os.Exit(1)
	}

	word := strings.ToUpper(os.Args[1])
	for _, uchar := range index[word] {
		fmt.Printf("U+%-5X %c \t%s\n", uchar, uchar, names[uchar])
	}

}
<|endoftext|>


<commit_before>package instructions // import "github.com/docker/docker/builder/dockerfile/instructions"

import (
	"errors"

	"strings"

	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/strslice"
)

// KeyValuePair represent an arbitrary named value (useful in slice insted of map[string] string to preserve ordering)
type KeyValuePair struct {
	Key   string
	Value string
}

func (kvp *KeyValuePair) String() string {
	return kvp.Key + "=" + kvp.Value
}

// Command is implemented by every command present in a dockerfile
type Command interface {
	Name() string
}

// KeyValuePairs is a slice of KeyValuePair
type KeyValuePairs []KeyValuePair

// withNameAndCode is the base of every command in a Dockerfile (String() returns its source code)
type withNameAndCode struct {
	code string
	name string
}

func (c *withNameAndCode) String() string {
	return c.code
}

// Name of the command
func (c *withNameAndCode) Name() string {
	return c.name
}

func newWithNameAndCode(req parseRequest) withNameAndCode {
	return withNameAndCode{code: strings.TrimSpace(req.original), name: req.command}
}

// SingleWordExpander is a provider for variable expansion where 1 word => 1 output
type SingleWordExpander func(word string) (string, error)

// SupportsSingleWordExpansion interface marks a command as supporting variable expansion
type SupportsSingleWordExpansion interface {
	Expand(expander SingleWordExpander) error
}

// PlatformSpecific adds platform checks to a command
type PlatformSpecific interface {
	CheckPlatform(platform string) error
}

func expandKvp(kvp KeyValuePair, expander SingleWordExpander) (KeyValuePair, error) {
	key, err := expander(kvp.Key)
	if err != nil {
		return KeyValuePair{}, err
	}
	value, err := expander(kvp.Value)
	if err != nil {
		return KeyValuePair{}, err
	}
	return KeyValuePair{Key: key, Value: value}, nil
}
func expandKvpsInPlace(kvps KeyValuePairs, expander SingleWordExpander) error {
	for i, kvp := range kvps {
		newKvp, err := expandKvp(kvp, expander)
		if err != nil {
			return err
		}
		kvps[i] = newKvp
	}
	return nil
}

func expandSliceInPlace(values []string, expander SingleWordExpander) error {
	for i, v := range values {
		newValue, err := expander(v)
		if err != nil {
			return err
		}
		values[i] = newValue
	}
	return nil
}

// EnvCommand : ENV key1 value1 [keyN valueN...]
type EnvCommand struct {
	withNameAndCode
	Env KeyValuePairs // kvp slice instead of map to preserve ordering
}

// Expand variables
func (c *EnvCommand) Expand(expander SingleWordExpander) error {
	return expandKvpsInPlace(c.Env, expander)
}

// MaintainerCommand : MAINTAINER maintainer_name
type MaintainerCommand struct {
	withNameAndCode
	Maintainer string
}

// LabelCommand : LABEL some json data describing the image
//
// Sets the Label variable foo to bar,
//
type LabelCommand struct {
	withNameAndCode
	Labels KeyValuePairs // kvp slice instead of map to preserve ordering
}

// Expand variables
func (c *LabelCommand) Expand(expander SingleWordExpander) error {
	return expandKvpsInPlace(c.Labels, expander)
}

// SourcesAndDest represent a list of source files and a destination
type SourcesAndDest []string

// Sources list the source paths
func (s SourcesAndDest) Sources() []string {
	res := make([]string, len(s)-1)
	copy(res, s[:len(s)-1])
	return res
}

// Dest path of the operation
func (s SourcesAndDest) Dest() string {
	return s[len(s)-1]
}

// AddCommand : ADD foo /path
//
// Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
// exist here. If you do not wish to have this automatic handling, use COPY.
//
type AddCommand struct {
	withNameAndCode
	SourcesAndDest
	Chown string
}

// Expand variables
func (c *AddCommand) Expand(expander SingleWordExpander) error {
	return expandSliceInPlace(c.SourcesAndDest, expander)
}

// CopyCommand : COPY foo /path
//
// Same as 'ADD' but without the tar and remote url handling.
//
type CopyCommand struct {
	withNameAndCode
	SourcesAndDest
	From  string
	Chown string
}

// Expand variables
func (c *CopyCommand) Expand(expander SingleWordExpander) error {
	return expandSliceInPlace(c.SourcesAndDest, expander)
}

// OnbuildCommand : ONBUILD <some other command>
type OnbuildCommand struct {
	withNameAndCode
	Expression string
}

// WorkdirCommand : WORKDIR /tmp
//
// Set the working directory for future RUN/CMD/etc statements.
//
type WorkdirCommand struct {
	withNameAndCode
	Path string
}

// Expand variables
func (c *WorkdirCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.Path)
	if err != nil {
		return err
	}
	c.Path = p
	return nil
}

// ShellDependantCmdLine represents a cmdline optionaly prepended with the shell
type ShellDependantCmdLine struct {
	CmdLine      strslice.StrSlice
	PrependShell bool
}

// RunCommand : RUN some command yo
//
// run a command and commit the image. Args are automatically prepended with
// the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
// Windows, in the event there is only one argument The difference in processing:
//
// RUN echo hi          # sh -c echo hi       (Linux)
// RUN echo hi          # cmd /S /C echo hi   (Windows)
// RUN [ "echo", "hi" ] # echo hi
//
type RunCommand struct {
	withNameAndCode
	ShellDependantCmdLine
}

// CmdCommand : CMD foo
//
// Set the default command to run in the container (which may be empty).
// Argument handling is the same as RUN.
//
type CmdCommand struct {
	withNameAndCode
	ShellDependantCmdLine
}

// HealthCheckCommand : HEALTHCHECK foo
//
// Set the default healthcheck command to run in the container (which may be empty).
// Argument handling is the same as RUN.
//
type HealthCheckCommand struct {
	withNameAndCode
	Health *container.HealthConfig
}

// EntrypointCommand : ENTRYPOINT /usr/sbin/nginx
//
// Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
// to /usr/sbin/nginx. Uses the default shell if not in JSON format.
//
// Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
// is initialized at newBuilder time instead of through argument parsing.
//
type EntrypointCommand struct {
	withNameAndCode
	ShellDependantCmdLine
}

// ExposeCommand : EXPOSE 6667/tcp 7000/tcp
//
// Expose ports for links and port mappings. This all ends up in
// req.runConfig.ExposedPorts for runconfig.
//
type ExposeCommand struct {
	withNameAndCode
	Ports []string
}

// UserCommand : USER foo
//
// Set the user to 'foo' for future commands and when running the
// ENTRYPOINT/CMD at container run time.
//
type UserCommand struct {
	withNameAndCode
	User string
}

// Expand variables
func (c *UserCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.User)
	if err != nil {
		return err
	}
	c.User = p
	return nil
}

// VolumeCommand : VOLUME /foo
//
// Expose the volume /foo for use. Will also accept the JSON array form.
//
type VolumeCommand struct {
	withNameAndCode
	Volumes []string
}

// Expand variables
func (c *VolumeCommand) Expand(expander SingleWordExpander) error {
	return expandSliceInPlace(c.Volumes, expander)
}

// StopSignalCommand : STOPSIGNAL signal
//
// Set the signal that will be used to kill the container.
type StopSignalCommand struct {
	withNameAndCode
	Signal string
}

// Expand variables
func (c *StopSignalCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.Signal)
	if err != nil {
		return err
	}
	c.Signal = p
	return nil
}

// CheckPlatform checks that the command is supported in the target platform
func (c *StopSignalCommand) CheckPlatform(platform string) error {
	if platform == "windows" {
		return errors.New("The daemon on this platform does not support the command stopsignal")
	}
	return nil
}

// ArgCommand : ARG name[=value]
//
// Adds the variable foo to the trusted list of variables that can be passed
// to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
// Dockerfile author may optionally set a default value of this variable.
type ArgCommand struct {
	withNameAndCode
	Key   string
	Value *string
}

// Expand variables
func (c *ArgCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.Key)
	if err != nil {
		return err
	}
	c.Key = p
	if c.Value != nil {
		p, err = expander(*c.Value)
		if err != nil {
			return err
		}
		c.Value = &p
	}
	return nil
}

// ShellCommand : SHELL powershell -command
//
// Set the non-default shell to use.
type ShellCommand struct {
	withNameAndCode
	Shell strslice.StrSlice
}

// Stage represents a single stage in a multi-stage build
type Stage struct {
	Name       string
	Commands   []Command
	BaseName   string
	SourceCode string
}

// AddCommand to the stage
func (s *Stage) AddCommand(cmd Command) {
	// todo: validate cmd type
	s.Commands = append(s.Commands, cmd)
}

// IsCurrentStage check if the stage name is the current stage
func IsCurrentStage(s []Stage, name string) bool {
	if len(s) == 0 {
		return false
	}
	return s[len(s)-1].Name == name
}

// CurrentStage return the last stage in a slice
func CurrentStage(s []Stage) (*Stage, error) {
	if len(s) == 0 {
		return nil, errors.New("No build stage in current context")
	}
	return &s[len(s)-1], nil
}

// HasStage looks for the presence of a given stage name
func HasStage(s []Stage, name string) (int, bool) {
	for i, stage := range s {
		if stage.Name == name {
			return i, true
		}
	}
	return -1, false
}
<commit_msg>Fix typos in builder and client<commit_after>package instructions // import "github.com/docker/docker/builder/dockerfile/instructions"

import (
	"errors"

	"strings"

	"github.com/docker/docker/api/types/container"
	"github.com/docker/docker/api/types/strslice"
)

// KeyValuePair represent an arbitrary named value (useful in slice instead of map[string] string to preserve ordering)
type KeyValuePair struct {
	Key   string
	Value string
}

func (kvp *KeyValuePair) String() string {
	return kvp.Key + "=" + kvp.Value
}

// Command is implemented by every command present in a dockerfile
type Command interface {
	Name() string
}

// KeyValuePairs is a slice of KeyValuePair
type KeyValuePairs []KeyValuePair

// withNameAndCode is the base of every command in a Dockerfile (String() returns its source code)
type withNameAndCode struct {
	code string
	name string
}

func (c *withNameAndCode) String() string {
	return c.code
}

// Name of the command
func (c *withNameAndCode) Name() string {
	return c.name
}

func newWithNameAndCode(req parseRequest) withNameAndCode {
	return withNameAndCode{code: strings.TrimSpace(req.original), name: req.command}
}

// SingleWordExpander is a provider for variable expansion where 1 word => 1 output
type SingleWordExpander func(word string) (string, error)

// SupportsSingleWordExpansion interface marks a command as supporting variable expansion
type SupportsSingleWordExpansion interface {
	Expand(expander SingleWordExpander) error
}

// PlatformSpecific adds platform checks to a command
type PlatformSpecific interface {
	CheckPlatform(platform string) error
}

func expandKvp(kvp KeyValuePair, expander SingleWordExpander) (KeyValuePair, error) {
	key, err := expander(kvp.Key)
	if err != nil {
		return KeyValuePair{}, err
	}
	value, err := expander(kvp.Value)
	if err != nil {
		return KeyValuePair{}, err
	}
	return KeyValuePair{Key: key, Value: value}, nil
}
func expandKvpsInPlace(kvps KeyValuePairs, expander SingleWordExpander) error {
	for i, kvp := range kvps {
		newKvp, err := expandKvp(kvp, expander)
		if err != nil {
			return err
		}
		kvps[i] = newKvp
	}
	return nil
}

func expandSliceInPlace(values []string, expander SingleWordExpander) error {
	for i, v := range values {
		newValue, err := expander(v)
		if err != nil {
			return err
		}
		values[i] = newValue
	}
	return nil
}

// EnvCommand : ENV key1 value1 [keyN valueN...]
type EnvCommand struct {
	withNameAndCode
	Env KeyValuePairs // kvp slice instead of map to preserve ordering
}

// Expand variables
func (c *EnvCommand) Expand(expander SingleWordExpander) error {
	return expandKvpsInPlace(c.Env, expander)
}

// MaintainerCommand : MAINTAINER maintainer_name
type MaintainerCommand struct {
	withNameAndCode
	Maintainer string
}

// LabelCommand : LABEL some json data describing the image
//
// Sets the Label variable foo to bar,
//
type LabelCommand struct {
	withNameAndCode
	Labels KeyValuePairs // kvp slice instead of map to preserve ordering
}

// Expand variables
func (c *LabelCommand) Expand(expander SingleWordExpander) error {
	return expandKvpsInPlace(c.Labels, expander)
}

// SourcesAndDest represent a list of source files and a destination
type SourcesAndDest []string

// Sources list the source paths
func (s SourcesAndDest) Sources() []string {
	res := make([]string, len(s)-1)
	copy(res, s[:len(s)-1])
	return res
}

// Dest path of the operation
func (s SourcesAndDest) Dest() string {
	return s[len(s)-1]
}

// AddCommand : ADD foo /path
//
// Add the file 'foo' to '/path'. Tarball and Remote URL (git, http) handling
// exist here. If you do not wish to have this automatic handling, use COPY.
//
type AddCommand struct {
	withNameAndCode
	SourcesAndDest
	Chown string
}

// Expand variables
func (c *AddCommand) Expand(expander SingleWordExpander) error {
	return expandSliceInPlace(c.SourcesAndDest, expander)
}

// CopyCommand : COPY foo /path
//
// Same as 'ADD' but without the tar and remote url handling.
//
type CopyCommand struct {
	withNameAndCode
	SourcesAndDest
	From  string
	Chown string
}

// Expand variables
func (c *CopyCommand) Expand(expander SingleWordExpander) error {
	return expandSliceInPlace(c.SourcesAndDest, expander)
}

// OnbuildCommand : ONBUILD <some other command>
type OnbuildCommand struct {
	withNameAndCode
	Expression string
}

// WorkdirCommand : WORKDIR /tmp
//
// Set the working directory for future RUN/CMD/etc statements.
//
type WorkdirCommand struct {
	withNameAndCode
	Path string
}

// Expand variables
func (c *WorkdirCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.Path)
	if err != nil {
		return err
	}
	c.Path = p
	return nil
}

// ShellDependantCmdLine represents a cmdline optionally prepended with the shell
type ShellDependantCmdLine struct {
	CmdLine      strslice.StrSlice
	PrependShell bool
}

// RunCommand : RUN some command yo
//
// run a command and commit the image. Args are automatically prepended with
// the current SHELL which defaults to 'sh -c' under linux or 'cmd /S /C' under
// Windows, in the event there is only one argument The difference in processing:
//
// RUN echo hi          # sh -c echo hi       (Linux)
// RUN echo hi          # cmd /S /C echo hi   (Windows)
// RUN [ "echo", "hi" ] # echo hi
//
type RunCommand struct {
	withNameAndCode
	ShellDependantCmdLine
}

// CmdCommand : CMD foo
//
// Set the default command to run in the container (which may be empty).
// Argument handling is the same as RUN.
//
type CmdCommand struct {
	withNameAndCode
	ShellDependantCmdLine
}

// HealthCheckCommand : HEALTHCHECK foo
//
// Set the default healthcheck command to run in the container (which may be empty).
// Argument handling is the same as RUN.
//
type HealthCheckCommand struct {
	withNameAndCode
	Health *container.HealthConfig
}

// EntrypointCommand : ENTRYPOINT /usr/sbin/nginx
//
// Set the entrypoint to /usr/sbin/nginx. Will accept the CMD as the arguments
// to /usr/sbin/nginx. Uses the default shell if not in JSON format.
//
// Handles command processing similar to CMD and RUN, only req.runConfig.Entrypoint
// is initialized at newBuilder time instead of through argument parsing.
//
type EntrypointCommand struct {
	withNameAndCode
	ShellDependantCmdLine
}

// ExposeCommand : EXPOSE 6667/tcp 7000/tcp
//
// Expose ports for links and port mappings. This all ends up in
// req.runConfig.ExposedPorts for runconfig.
//
type ExposeCommand struct {
	withNameAndCode
	Ports []string
}

// UserCommand : USER foo
//
// Set the user to 'foo' for future commands and when running the
// ENTRYPOINT/CMD at container run time.
//
type UserCommand struct {
	withNameAndCode
	User string
}

// Expand variables
func (c *UserCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.User)
	if err != nil {
		return err
	}
	c.User = p
	return nil
}

// VolumeCommand : VOLUME /foo
//
// Expose the volume /foo for use. Will also accept the JSON array form.
//
type VolumeCommand struct {
	withNameAndCode
	Volumes []string
}

// Expand variables
func (c *VolumeCommand) Expand(expander SingleWordExpander) error {
	return expandSliceInPlace(c.Volumes, expander)
}

// StopSignalCommand : STOPSIGNAL signal
//
// Set the signal that will be used to kill the container.
type StopSignalCommand struct {
	withNameAndCode
	Signal string
}

// Expand variables
func (c *StopSignalCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.Signal)
	if err != nil {
		return err
	}
	c.Signal = p
	return nil
}

// CheckPlatform checks that the command is supported in the target platform
func (c *StopSignalCommand) CheckPlatform(platform string) error {
	if platform == "windows" {
		return errors.New("The daemon on this platform does not support the command stopsignal")
	}
	return nil
}

// ArgCommand : ARG name[=value]
//
// Adds the variable foo to the trusted list of variables that can be passed
// to builder using the --build-arg flag for expansion/substitution or passing to 'run'.
// Dockerfile author may optionally set a default value of this variable.
type ArgCommand struct {
	withNameAndCode
	Key   string
	Value *string
}

// Expand variables
func (c *ArgCommand) Expand(expander SingleWordExpander) error {
	p, err := expander(c.Key)
	if err != nil {
		return err
	}
	c.Key = p
	if c.Value != nil {
		p, err = expander(*c.Value)
		if err != nil {
			return err
		}
		c.Value = &p
	}
	return nil
}

// ShellCommand : SHELL powershell -command
//
// Set the non-default shell to use.
type ShellCommand struct {
	withNameAndCode
	Shell strslice.StrSlice
}

// Stage represents a single stage in a multi-stage build
type Stage struct {
	Name       string
	Commands   []Command
	BaseName   string
	SourceCode string
}

// AddCommand to the stage
func (s *Stage) AddCommand(cmd Command) {
	// todo: validate cmd type
	s.Commands = append(s.Commands, cmd)
}

// IsCurrentStage check if the stage name is the current stage
func IsCurrentStage(s []Stage, name string) bool {
	if len(s) == 0 {
		return false
	}
	return s[len(s)-1].Name == name
}

// CurrentStage return the last stage in a slice
func CurrentStage(s []Stage) (*Stage, error) {
	if len(s) == 0 {
		return nil, errors.New("No build stage in current context")
	}
	return &s[len(s)-1], nil
}

// HasStage looks for the presence of a given stage name
func HasStage(s []Stage, name string) (int, bool) {
	for i, stage := range s {
		if stage.Name == name {
			return i, true
		}
	}
	return -1, false
}
<|endoftext|>


<commit_before>// Package activation implements primitives for systemd socket activation.
package activation

import (
	"os"
	"strconv"
	"syscall"
)

// based on: https://gist.github.com/alberts/4640792
const (
	listenFdsStart = 3
)

func Files(unsetEnv bool) []*os.File {

	if unsetEnv {
		// there is no way to unset env in golang os package for now
		// https://code.google.com/p/go/issues/detail?id=6423
		defer os.Setenv("LISTEN_PID", "")
		defer os.Setenv("LISTEN_FDS", "")
	}

	pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
	if err != nil || pid != os.Getpid() {
		return nil
	}
	nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
	if err != nil || nfds == 0 {
		return nil
	}
	files := []*os.File(nil)
	for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
		syscall.CloseOnExec(fd)
		files = append(files, os.NewFile(uintptr(fd), "LISTEN_FD_"+strconv.Itoa(fd)))
	}
	return files
}
<commit_msg>fix(activation): cleanup variable definition<commit_after>// Package activation implements primitives for systemd socket activation.
package activation

import (
	"os"
	"strconv"
	"syscall"
)

// based on: https://gist.github.com/alberts/4640792
const (
	listenFdsStart = 3
)

func Files(unsetEnv bool) []*os.File {

	if unsetEnv {
		// there is no way to unset env in golang os package for now
		// https://code.google.com/p/go/issues/detail?id=6423
		defer os.Setenv("LISTEN_PID", "")
		defer os.Setenv("LISTEN_FDS", "")
	}

	pid, err := strconv.Atoi(os.Getenv("LISTEN_PID"))
	if err != nil || pid != os.Getpid() {
		return nil
	}
	nfds, err := strconv.Atoi(os.Getenv("LISTEN_FDS"))
	if err != nil || nfds == 0 {
		return nil
	}
	var files []*os.File
	for fd := listenFdsStart; fd < listenFdsStart+nfds; fd++ {
		syscall.CloseOnExec(fd)
		files = append(files, os.NewFile(uintptr(fd), "LISTEN_FD_"+strconv.Itoa(fd)))
	}
	return files
}
<|endoftext|>


<commit_before>package main

import (
	"fmt"
	"github.com/zachlatta/go-github/github"
	"io/ioutil"
	"os"
)

var usage = `Gitignorer makes creating .gitignore files easy.

Usage:

  gitignorer command [arguments]

The commands are:

  create    create a .gitignore file
  list      list the available templates
`

var client = github.NewClient(nil)

func main() {
	args := os.Args

	if len(args) <= 1 {
		fmt.Println(usage)
		return
	}

	switch args[1] {
	case "create":
		create(args[2:])
	case "list":
		list()
	default:
		fmt.Println(usage)
	}
}

func create(templates []string) {
	if _, err := os.Stat(".gitignore"); err == nil {
		fmt.Println("Error: A .gitignore file already exists.")
	} else {
		var fileContents string
		for _, v := range templates {
			gitignore, _, err := client.Gitignores.Get(v)
			if err != nil {
				fmt.Println(err)
				return
			}

			fileContents += *gitignore.Source
		}

		err := ioutil.WriteFile(".gitignore", []byte(fileContents), 0644)
		if err != nil {
			fmt.Println("Error writing .gitignore file!")
		}
	}
}

func list() {
	templates, _, err := client.Gitignores.List()
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, t := range *templates {
		fmt.Println(t)
	}
}
<commit_msg>Improve UX.<commit_after>package main

import (
	"fmt"
	"github.com/zachlatta/go-github/github"
	"io/ioutil"
	"os"
	"strings"
)

var usage = `Gitignorer makes creating .gitignore files easy.

Usage:

  gitignorer command [arguments]

The commands are:

  create    create a .gitignore file
  list      list the available templates
`

var client = github.NewClient(nil)

func main() {
	args := os.Args

	if len(args) <= 1 {
		fmt.Println(usage)
		return
	}

	switch args[1] {
	case "create":
		create(args[2:])
	case "list":
		list()
	default:
		fmt.Println(usage)
	}
}

func create(templates []string) {
	if _, err := os.Stat(".gitignore"); err == nil {
		fmt.Println("Error: A .gitignore file already exists.")
	} else {
		var fileContents string
		for _, v := range templates {
			fmt.Println("Fetching template for " + v + "...")
			gitignore, _, err := client.Gitignores.Get(v)
			if err != nil {
				fmt.Println(err)
				return
			}

			header := header(v)
			fileContents += header + "\n\n" + *gitignore.Source + "\n\n"
		}

		fileContents = strings.TrimSpace(fileContents)

		fmt.Println("Writing .gitignore file...")
		err := ioutil.WriteFile(".gitignore", []byte(fileContents), 0644)
		if err != nil {
			fmt.Println("Error writing .gitignore file!")
		}
		fmt.Println("Done!")
	}
}

// Returns something akin to the following:
//
// ##########
// #   Go   #
// ##########
func header(name string) string {
	line := strings.Repeat("#", len(name)+8)
	mid := "#   " + name + "   #"
	return line + "\n" + mid + "\n" + line
}

func list() {
	templates, _, err := client.Gitignores.List()
	if err != nil {
		fmt.Println(err)
		return
	}

	for _, t := range *templates {
		fmt.Println(t)
	}
}
<|endoftext|>


<commit_before>package main

import (
	"errors"
	"fmt"
	"os"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/api/types/versions"
	"github.com/docker/docker/cli"
	"github.com/docker/docker/cli/command"
	"github.com/docker/docker/cli/command/commands"
	cliconfig "github.com/docker/docker/cli/config"
	"github.com/docker/docker/cli/debug"
	cliflags "github.com/docker/docker/cli/flags"
	"github.com/docker/docker/dockerversion"
	"github.com/docker/docker/pkg/term"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
	"strings"
)

func newDockerCommand(dockerCli *command.DockerCli) *cobra.Command {
	opts := cliflags.NewClientOptions()
	var flags *pflag.FlagSet

	cmd := &cobra.Command{
		Use:              "docker [OPTIONS] COMMAND [ARG...]",
		Short:            "A self-sufficient runtime for containers",
		SilenceUsage:     true,
		SilenceErrors:    true,
		TraverseChildren: true,
		Args:             noArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			if opts.Version {
				showVersion()
				return nil
			}
			return dockerCli.ShowHelp(cmd, args)
		},
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			// daemon command is special, we redirect directly to another binary
			if cmd.Name() == "daemon" {
				return nil
			}
			// flags must be the top-level command flags, not cmd.Flags()
			opts.Common.SetDefaultOptions(flags)
			dockerPreRun(opts)
			if err := dockerCli.Initialize(opts); err != nil {
				return err
			}
			return isSupported(cmd, dockerCli.Client().ClientVersion(), dockerCli.HasExperimental())
		},
	}
	cli.SetupRootCommand(cmd)

	cmd.SetHelpFunc(func(ccmd *cobra.Command, args []string) {
		if dockerCli.Client() == nil { // when using --help, PersistenPreRun is not called, so initialization is needed.
			// flags must be the top-level command flags, not cmd.Flags()
			opts.Common.SetDefaultOptions(flags)
			dockerPreRun(opts)
			dockerCli.Initialize(opts)
		}

		if err := isSupported(ccmd, dockerCli.Client().ClientVersion(), dockerCli.HasExperimental()); err != nil {
			ccmd.Println(err)
			return
		}

		hideUnsupportedFeatures(ccmd, dockerCli.Client().ClientVersion(), dockerCli.HasExperimental())

		if err := ccmd.Help(); err != nil {
			ccmd.Println(err)
		}
	})

	flags = cmd.Flags()
	flags.BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
	flags.StringVar(&opts.ConfigDir, "config", cliconfig.Dir(), "Location of client config files")
	opts.Common.InstallFlags(flags)

	cmd.SetOutput(dockerCli.Out())
	cmd.AddCommand(newDaemonCommand())
	commands.AddCommands(cmd, dockerCli)

	return cmd
}

func noArgs(cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return nil
	}
	return fmt.Errorf(
		"docker: '%s' is not a docker command.\nSee 'docker --help'", args[0])
}

func main() {
	// Set terminal emulation based on platform as required.
	stdin, stdout, stderr := term.StdStreams()
	logrus.SetOutput(stderr)

	dockerCli := command.NewDockerCli(stdin, stdout, stderr)
	cmd := newDockerCommand(dockerCli)

	if err := cmd.Execute(); err != nil {
		if sterr, ok := err.(cli.StatusError); ok {
			if sterr.Status != "" {
				fmt.Fprintln(stderr, sterr.Status)
			}
			// StatusError should only be used for errors, and all errors should
			// have a non-zero exit status, so never exit with 0
			if sterr.StatusCode == 0 {
				os.Exit(1)
			}
			os.Exit(sterr.StatusCode)
		}
		fmt.Fprintln(stderr, err)
		os.Exit(1)
	}
}

func showVersion() {
	fmt.Printf("Docker version %s, build %s\n", dockerversion.Version, dockerversion.GitCommit)
}

func dockerPreRun(opts *cliflags.ClientOptions) {
	cliflags.SetLogLevel(opts.Common.LogLevel)

	if opts.ConfigDir != "" {
		cliconfig.SetDir(opts.ConfigDir)
	}

	if opts.Common.Debug {
		debug.Enable()
	}
}

func hideUnsupportedFeatures(cmd *cobra.Command, clientVersion string, hasExperimental bool) {
	cmd.Flags().VisitAll(func(f *pflag.Flag) {
		// hide experimental flags
		if !hasExperimental {
			if _, ok := f.Annotations["experimental"]; ok {
				f.Hidden = true
			}
		}

		// hide flags not supported by the server
		if !isFlagSupported(f, clientVersion) {
			f.Hidden = true
		}

	})

	for _, subcmd := range cmd.Commands() {
		// hide experimental subcommands
		if !hasExperimental {
			if _, ok := subcmd.Tags["experimental"]; ok {
				subcmd.Hidden = true
			}
		}

		// hide subcommands not supported by the server
		if subcmdVersion, ok := subcmd.Tags["version"]; ok && versions.LessThan(clientVersion, subcmdVersion) {
			subcmd.Hidden = true
		}
	}
}

func isSupported(cmd *cobra.Command, clientVersion string, hasExperimental bool) error {
	if !hasExperimental {
		if _, ok := cmd.Tags["experimental"]; ok {
			return errors.New("only supported on a Docker daemon with experimental features enabled")
		}
	}

	if cmdVersion, ok := cmd.Tags["version"]; ok && versions.LessThan(clientVersion, cmdVersion) {
		return fmt.Errorf("requires API version %s, but the Docker daemon API version is %s", cmdVersion, clientVersion)
	}

	errs := []string{}

	cmd.Flags().VisitAll(func(f *pflag.Flag) {
		if f.Changed {
			if !isFlagSupported(f, clientVersion) {
				errs = append(errs, fmt.Sprintf("\"--%s\" requires API version %s, but the Docker daemon API version is %s", f.Name, getFlagVersion(f), clientVersion))
				return
			}
			if _, ok := f.Annotations["experimental"]; ok && !hasExperimental {
				errs = append(errs, fmt.Sprintf("\"--%s\" is only supported on a Docker daemon with experimental features enabled", f.Name))
			}
		}
	})
	if len(errs) > 0 {
		return errors.New(strings.Join(errs, "\n"))
	}

	return nil
}

func getFlagVersion(f *pflag.Flag) string {
	if flagVersion, ok := f.Annotations["version"]; ok && len(flagVersion) == 1 {
		return flagVersion[0]
	}
	return ""
}

func isFlagSupported(f *pflag.Flag, clientVersion string) bool {
	if v := getFlagVersion(f); v != "" {
		return versions.GreaterThanOrEqualTo(clientVersion, v)
	}
	return true
}
<commit_msg>review code about cmd/* and fix some easy typos :D<commit_after>package main

import (
	"errors"
	"fmt"
	"os"
	"strings"

	"github.com/Sirupsen/logrus"
	"github.com/docker/docker/api/types/versions"
	"github.com/docker/docker/cli"
	"github.com/docker/docker/cli/command"
	"github.com/docker/docker/cli/command/commands"
	cliconfig "github.com/docker/docker/cli/config"
	"github.com/docker/docker/cli/debug"
	cliflags "github.com/docker/docker/cli/flags"
	"github.com/docker/docker/dockerversion"
	"github.com/docker/docker/pkg/term"
	"github.com/spf13/cobra"
	"github.com/spf13/pflag"
)

func newDockerCommand(dockerCli *command.DockerCli) *cobra.Command {
	opts := cliflags.NewClientOptions()
	var flags *pflag.FlagSet

	cmd := &cobra.Command{
		Use:              "docker [OPTIONS] COMMAND [ARG...]",
		Short:            "A self-sufficient runtime for containers",
		SilenceUsage:     true,
		SilenceErrors:    true,
		TraverseChildren: true,
		Args:             noArgs,
		RunE: func(cmd *cobra.Command, args []string) error {
			if opts.Version {
				showVersion()
				return nil
			}
			return dockerCli.ShowHelp(cmd, args)
		},
		PersistentPreRunE: func(cmd *cobra.Command, args []string) error {
			// daemon command is special, we redirect directly to another binary
			if cmd.Name() == "daemon" {
				return nil
			}
			// flags must be the top-level command flags, not cmd.Flags()
			opts.Common.SetDefaultOptions(flags)
			dockerPreRun(opts)
			if err := dockerCli.Initialize(opts); err != nil {
				return err
			}
			return isSupported(cmd, dockerCli.Client().ClientVersion(), dockerCli.HasExperimental())
		},
	}
	cli.SetupRootCommand(cmd)

	cmd.SetHelpFunc(func(ccmd *cobra.Command, args []string) {
		if dockerCli.Client() == nil { // when using --help, PersistentPreRun is not called, so initialization is needed.
			// flags must be the top-level command flags, not cmd.Flags()
			opts.Common.SetDefaultOptions(flags)
			dockerPreRun(opts)
			dockerCli.Initialize(opts)
		}

		if err := isSupported(ccmd, dockerCli.Client().ClientVersion(), dockerCli.HasExperimental()); err != nil {
			ccmd.Println(err)
			return
		}

		hideUnsupportedFeatures(ccmd, dockerCli.Client().ClientVersion(), dockerCli.HasExperimental())

		if err := ccmd.Help(); err != nil {
			ccmd.Println(err)
		}
	})

	flags = cmd.Flags()
	flags.BoolVarP(&opts.Version, "version", "v", false, "Print version information and quit")
	flags.StringVar(&opts.ConfigDir, "config", cliconfig.Dir(), "Location of client config files")
	opts.Common.InstallFlags(flags)

	cmd.SetOutput(dockerCli.Out())
	cmd.AddCommand(newDaemonCommand())
	commands.AddCommands(cmd, dockerCli)

	return cmd
}

func noArgs(cmd *cobra.Command, args []string) error {
	if len(args) == 0 {
		return nil
	}
	return fmt.Errorf(
		"docker: '%s' is not a docker command.\nSee 'docker --help'", args[0])
}

func main() {
	// Set terminal emulation based on platform as required.
	stdin, stdout, stderr := term.StdStreams()
	logrus.SetOutput(stderr)

	dockerCli := command.NewDockerCli(stdin, stdout, stderr)
	cmd := newDockerCommand(dockerCli)

	if err := cmd.Execute(); err != nil {
		if sterr, ok := err.(cli.StatusError); ok {
			if sterr.Status != "" {
				fmt.Fprintln(stderr, sterr.Status)
			}
			// StatusError should only be used for errors, and all errors should
			// have a non-zero exit status, so never exit with 0
			if sterr.StatusCode == 0 {
				os.Exit(1)
			}
			os.Exit(sterr.StatusCode)
		}
		fmt.Fprintln(stderr, err)
		os.Exit(1)
	}
}

func showVersion() {
	fmt.Printf("Docker version %s, build %s\n", dockerversion.Version, dockerversion.GitCommit)
}

func dockerPreRun(opts *cliflags.ClientOptions) {
	cliflags.SetLogLevel(opts.Common.LogLevel)

	if opts.ConfigDir != "" {
		cliconfig.SetDir(opts.ConfigDir)
	}

	if opts.Common.Debug {
		debug.Enable()
	}
}

func hideUnsupportedFeatures(cmd *cobra.Command, clientVersion string, hasExperimental bool) {
	cmd.Flags().VisitAll(func(f *pflag.Flag) {
		// hide experimental flags
		if !hasExperimental {
			if _, ok := f.Annotations["experimental"]; ok {
				f.Hidden = true
			}
		}

		// hide flags not supported by the server
		if !isFlagSupported(f, clientVersion) {
			f.Hidden = true
		}

	})

	for _, subcmd := range cmd.Commands() {
		// hide experimental subcommands
		if !hasExperimental {
			if _, ok := subcmd.Tags["experimental"]; ok {
				subcmd.Hidden = true
			}
		}

		// hide subcommands not supported by the server
		if subcmdVersion, ok := subcmd.Tags["version"]; ok && versions.LessThan(clientVersion, subcmdVersion) {
			subcmd.Hidden = true
		}
	}
}

func isSupported(cmd *cobra.Command, clientVersion string, hasExperimental bool) error {
	if !hasExperimental {
		if _, ok := cmd.Tags["experimental"]; ok {
			return errors.New("only supported on a Docker daemon with experimental features enabled")
		}
	}

	if cmdVersion, ok := cmd.Tags["version"]; ok && versions.LessThan(clientVersion, cmdVersion) {
		return fmt.Errorf("requires API version %s, but the Docker daemon API version is %s", cmdVersion, clientVersion)
	}

	errs := []string{}

	cmd.Flags().VisitAll(func(f *pflag.Flag) {
		if f.Changed {
			if !isFlagSupported(f, clientVersion) {
				errs = append(errs, fmt.Sprintf("\"--%s\" requires API version %s, but the Docker daemon API version is %s", f.Name, getFlagVersion(f), clientVersion))
				return
			}
			if _, ok := f.Annotations["experimental"]; ok && !hasExperimental {
				errs = append(errs, fmt.Sprintf("\"--%s\" is only supported on a Docker daemon with experimental features enabled", f.Name))
			}
		}
	})
	if len(errs) > 0 {
		return errors.New(strings.Join(errs, "\n"))
	}

	return nil
}

func getFlagVersion(f *pflag.Flag) string {
	if flagVersion, ok := f.Annotations["version"]; ok && len(flagVersion) == 1 {
		return flagVersion[0]
	}
	return ""
}

func isFlagSupported(f *pflag.Flag, clientVersion string) bool {
	if v := getFlagVersion(f); v != "" {
		return versions.GreaterThanOrEqualTo(clientVersion, v)
	}
	return true
}
<|endoftext|>


<commit_before>package stringutil

import (
	"regexp"
	"strings"

	"gopkgs.com/unidecode.v1"
)

var (
	slugRegexp = regexp.MustCompile("\\W+")
)

// Slug returns a slugified version of the given string, which
// consists in transliterating unicode characters to ascii
// (e.g. ó becomes o and â becomes a), replacing all sequences of
// whitespaces with '-' and converting to lowercase. Very useful
// for making arbitrary strings, like a post title, part of URLs.
func Slug(s string) string {
	decoded := unidecode.Unidecode(s)
	spaceless := slugRegexp.ReplaceAllString(decoded, "-")
	return strings.ToLower(strings.Trim(spaceless, "-"))
}

// SlugN works like Slug, but returns at string with, at
// most n characters. If n is <= 0, it works exactly
// like Slug.
func SlugN(s string, n int) string {
	slug := Slug(s)
	if n > 0 && len(slug) > n {
		slug = strings.Trim(slug[:n], "-")
	}
	return slug
}
<commit_msg>Import unidecode directly from github<commit_after>package stringutil

import (
	"regexp"
	"strings"

	"github.com/rainycape/unidecode"
)

var (
	slugRegexp = regexp.MustCompile("\\W+")
)

// Slug returns a slugified version of the given string, which
// consists in transliterating unicode characters to ascii
// (e.g. ó becomes o and â becomes a), replacing all sequences of
// whitespaces with '-' and converting to lowercase. Very useful
// for making arbitrary strings, like a post title, part of URLs.
func Slug(s string) string {
	decoded := unidecode.Unidecode(s)
	spaceless := slugRegexp.ReplaceAllString(decoded, "-")
	return strings.ToLower(strings.Trim(spaceless, "-"))
}

// SlugN works like Slug, but returns at string with, at
// most n characters. If n is <= 0, it works exactly
// like Slug.
func SlugN(s string, n int) string {
	slug := Slug(s)
	if n > 0 && len(slug) > n {
		slug = strings.Trim(slug[:n], "-")
	}
	return slug
}
<|endoftext|>