<commit_before>package main

import (
    "bufio"
    "crypto/sha256"
    "crypto/sha512"
    "flag"
    "fmt"
    "hash"
    "os"
)

func main() {
    var length int

    flag.IntVar(&length, "l", 256, "specify the length of sha. 256, 384, 512")
    flag.Parse()

    var digest hash.Hash

    if length == 256 {
        digest = sha256.New()
    } else if length == 384 {
        digest = sha512.New384()
    } else if length == 512 {
        digest = sha512.New()
    } else {
        fmt.Fprintf(os.Stderr, "Unrecognized algorithm: %d\n", length)
        flag.PrintDefaults()
        os.Exit(1)
    }

    reader := bufio.NewReader(os.Stdin)
    buf := make([]byte, 1024)

    for {
        len, err := reader.Read(buf)
        if len == 0 {
            break;
        }
        if err != nil {
			fmt.Fprintf(os.Stderr, "read error: %v\n", err)
			os.Exit(1)
        }
        digest.Write(buf[:len])
    }
    fmt.Printf("%x\n", digest.Sum(nil))
}
<commit_msg>Modified main.go.<commit_after>package main

import (
    "bufio"
    "crypto/sha256"
    "crypto/sha512"
    "flag"
    "fmt"
    "hash"
    "os"
)

func main() {
    var length int

    flag.IntVar(&length, "l", 256, "specify the length of sha. 256, 384, 512")
    flag.Parse()

    var hash hash.Hash

    if length == 256 {
        hash = sha256.New()
    } else if length == 384 {
        hash = sha512.New384()
    } else if length == 512 {
        hash = sha512.New()
    } else {
        fmt.Fprintf(os.Stderr, "Unrecognized algorithm: %d\n", length)
        flag.PrintDefaults()
        os.Exit(1)
    }

    reader := bufio.NewReader(os.Stdin)
    buf := make([]byte, 1024)

    for {
        len, err := reader.Read(buf)
        if len == 0 {
            break;
        }
        if err != nil {
			fmt.Fprintf(os.Stderr, "read error: %v\n", err)
			os.Exit(1)
        }
        hash.Write(buf[:len])
    }
    fmt.Printf("%x\n", hash.Sum(nil))
}
<|endoftext|>


<commit_before>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://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 integrationtest

import (
	"context"
	"net"
	"os"
	"testing"

	"github.com/stretchr/testify/require"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/component/componenttest"
	"google.golang.org/genproto/googleapis/api/metric"
	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/types/known/emptypb"

	"github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/collector"
)

type MetricsTestServer struct {
	// Address where the gRPC server is listening
	Endpoint string

	createMetricDescriptorChan <-chan *monitoringpb.CreateMetricDescriptorRequest
	createTimeSeriesChan       <-chan *monitoringpb.CreateTimeSeriesRequest
	lis                        net.Listener
	srv                        *grpc.Server
}

func (m *MetricsTestServer) Shutdown() {
	// this will close mts.lis
	m.srv.GracefulStop()
}

// Pops out the CreateMetricDescriptorRequests which the test server has received so far
func (m *MetricsTestServer) CreateMetricDescriptorRequests() []*monitoringpb.CreateMetricDescriptorRequest {
	reqs := []*monitoringpb.CreateMetricDescriptorRequest{}
	for {
		select {
		case req := <-m.createMetricDescriptorChan:
			reqs = append(reqs, req)
		default:
			return reqs
		}
	}
}

// Pops out the CreateTimeSeriesRequests which the test server has received so far
func (m *MetricsTestServer) CreateTimeSeriesRequests() []*monitoringpb.CreateTimeSeriesRequest {
	reqs := []*monitoringpb.CreateTimeSeriesRequest{}
	for {
		select {
		case req := <-m.createTimeSeriesChan:
			reqs = append(reqs, req)
		default:
			return reqs
		}
	}
}

func (m *MetricsTestServer) Serve() error {
	return m.srv.Serve(m.lis)
}

type fakeMetricServiceServer struct {
	monitoringpb.UnimplementedMetricServiceServer
	createMetricDescriptorChan chan<- *monitoringpb.CreateMetricDescriptorRequest
	createTimeSeriesChan       chan<- *monitoringpb.CreateTimeSeriesRequest
}

func (f *fakeMetricServiceServer) CreateTimeSeries(
	ctx context.Context,
	req *monitoringpb.CreateTimeSeriesRequest,
) (*emptypb.Empty, error) {
	go func() { f.createTimeSeriesChan <- req }()
	return &emptypb.Empty{}, nil
}

func (f *fakeMetricServiceServer) CreateMetricDescriptor(
	ctx context.Context,
	req *monitoringpb.CreateMetricDescriptorRequest,
) (*metric.MetricDescriptor, error) {
	go func() { f.createMetricDescriptorChan <- req }()
	return &metric.MetricDescriptor{}, nil
}

func NewMetricTestServer() (*MetricsTestServer, error) {
	srv := grpc.NewServer()
	lis, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		return nil, err
	}
	createMetricDescriptorCh := make(chan *monitoringpb.CreateMetricDescriptorRequest, 10)
	createTimeSeriesCh := make(chan *monitoringpb.CreateTimeSeriesRequest, 10)
	monitoringpb.RegisterMetricServiceServer(
		srv,
		&fakeMetricServiceServer{
			createMetricDescriptorChan: createMetricDescriptorCh,
			createTimeSeriesChan:       createTimeSeriesCh,
		},
	)

	testServer := &MetricsTestServer{
		Endpoint:                   lis.Addr().String(),
		createMetricDescriptorChan: createMetricDescriptorCh,
		createTimeSeriesChan:       createTimeSeriesCh,
		lis:                        lis,
		srv:                        srv,
	}

	return testServer, nil
}

func CreateConfig(factory component.ExporterFactory) *collector.Config {
	cfg := factory.CreateDefaultConfig().(*collector.Config)
	// If not set it will use ADC
	cfg.ProjectID = os.Getenv("PROJECT_ID")
	// Disable queued retries as there is no way to flush them
	cfg.RetrySettings.Enabled = false
	cfg.QueueSettings.Enabled = false
	return cfg
}

func CreateMetricsTestServerExporter(
	ctx context.Context,
	t testing.TB,
	testServer *MetricsTestServer,
) component.MetricsExporter {
	factory := collector.NewFactory()
	cfg := CreateConfig(factory)
	cfg.Endpoint = testServer.Endpoint
	cfg.UseInsecure = true
	cfg.ProjectID = "fakeprojectid"

	exporter, err := factory.CreateMetricsExporter(
		ctx,
		componenttest.NewNopExporterCreateSettings(),
		cfg,
	)
	require.NoError(t, err)
	require.NoError(t, exporter.Start(ctx, componenttest.NewNopHost()))
	t.Logf("Collector MetricsTestServer exporter started, pointing at %v", cfg.Endpoint)
	return exporter
}
<commit_msg>Fix bug where test gRPC server channels were buffering (#232)<commit_after>// Copyright 2021 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      https://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 integrationtest

import (
	"context"
	"net"
	"os"
	"sync"
	"testing"

	"github.com/stretchr/testify/require"
	"go.opentelemetry.io/collector/component"
	"go.opentelemetry.io/collector/component/componenttest"
	"google.golang.org/genproto/googleapis/api/metric"
	monitoringpb "google.golang.org/genproto/googleapis/monitoring/v3"
	"google.golang.org/grpc"
	"google.golang.org/protobuf/types/known/emptypb"

	"github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/collector"
)

type MetricsTestServer struct {
	// Address where the gRPC server is listening
	Endpoint string

	createMetricDescriptorReqs []*monitoringpb.CreateMetricDescriptorRequest
	createTimeSeriesReqs       []*monitoringpb.CreateTimeSeriesRequest

	lis net.Listener
	srv *grpc.Server
	mu  sync.Mutex
}

func (m *MetricsTestServer) Shutdown() {
	// this will close mts.lis
	m.srv.GracefulStop()
}

// Pops out the CreateMetricDescriptorRequests which the test server has received so far
func (m *MetricsTestServer) CreateMetricDescriptorRequests() []*monitoringpb.CreateMetricDescriptorRequest {
	m.mu.Lock()
	defer m.mu.Unlock()
	reqs := m.createMetricDescriptorReqs
	m.createMetricDescriptorReqs = nil
	return reqs
}

// Pops out the CreateTimeSeriesRequests which the test server has received so far
func (m *MetricsTestServer) CreateTimeSeriesRequests() []*monitoringpb.CreateTimeSeriesRequest {
	m.mu.Lock()
	defer m.mu.Unlock()
	reqs := m.createTimeSeriesReqs
	m.createTimeSeriesReqs = nil
	return reqs
}

func (m *MetricsTestServer) appendCreateMetricDescriptorReq(req *monitoringpb.CreateMetricDescriptorRequest) {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.createMetricDescriptorReqs = append(m.createMetricDescriptorReqs, req)
}
func (m *MetricsTestServer) appendCreateTimeSeriesReq(req *monitoringpb.CreateTimeSeriesRequest) {
	m.mu.Lock()
	defer m.mu.Unlock()
	m.createTimeSeriesReqs = append(m.createTimeSeriesReqs, req)
}

func (m *MetricsTestServer) Serve() error {
	return m.srv.Serve(m.lis)
}

type fakeMetricServiceServer struct {
	monitoringpb.UnimplementedMetricServiceServer
	appendCreateMetricDescriptorReq func(*monitoringpb.CreateMetricDescriptorRequest)
	appendCreateTimeSeriesReq       func(*monitoringpb.CreateTimeSeriesRequest)
}

func (f *fakeMetricServiceServer) CreateTimeSeries(
	ctx context.Context,
	req *monitoringpb.CreateTimeSeriesRequest,
) (*emptypb.Empty, error) {
	f.appendCreateTimeSeriesReq(req)
	return &emptypb.Empty{}, nil
}

func (f *fakeMetricServiceServer) CreateMetricDescriptor(
	ctx context.Context,
	req *monitoringpb.CreateMetricDescriptorRequest,
) (*metric.MetricDescriptor, error) {
	f.appendCreateMetricDescriptorReq(req)
	return &metric.MetricDescriptor{}, nil
}

func NewMetricTestServer() (*MetricsTestServer, error) {
	srv := grpc.NewServer()
	lis, err := net.Listen("tcp", "localhost:0")
	if err != nil {
		return nil, err
	}
	testServer := &MetricsTestServer{
		Endpoint: lis.Addr().String(),
		lis:      lis,
		srv:      srv,
	}

	monitoringpb.RegisterMetricServiceServer(
		srv,
		&fakeMetricServiceServer{
			appendCreateMetricDescriptorReq: testServer.appendCreateMetricDescriptorReq,
			appendCreateTimeSeriesReq:       testServer.appendCreateTimeSeriesReq,
		},
	)

	return testServer, nil
}

func CreateConfig(factory component.ExporterFactory) *collector.Config {
	cfg := factory.CreateDefaultConfig().(*collector.Config)
	// If not set it will use ADC
	cfg.ProjectID = os.Getenv("PROJECT_ID")
	// Disable queued retries as there is no way to flush them
	cfg.RetrySettings.Enabled = false
	cfg.QueueSettings.Enabled = false
	return cfg
}

func CreateMetricsTestServerExporter(
	ctx context.Context,
	t testing.TB,
	testServer *MetricsTestServer,
) component.MetricsExporter {
	factory := collector.NewFactory()
	cfg := CreateConfig(factory)
	cfg.Endpoint = testServer.Endpoint
	cfg.UseInsecure = true
	cfg.ProjectID = "fakeprojectid"

	exporter, err := factory.CreateMetricsExporter(
		ctx,
		componenttest.NewNopExporterCreateSettings(),
		cfg,
	)
	require.NoError(t, err)
	require.NoError(t, exporter.Start(ctx, componenttest.NewNopHost()))
	t.Logf("Collector MetricsTestServer exporter started, pointing at %v", cfg.Endpoint)
	return exporter
}
<|endoftext|>


<commit_before>package binny

import (
	"bufio"
	"bytes"
	"encoding"
	"encoding/binary"
	"encoding/gob"
	"errors"
	"io"
	"reflect"
	"unsafe"
)

var (
	// ErrNoPointer gets returned if the user passes a non-pointer to Decode
	ErrNoPointer = errors.New("can't decode to a non-pointer")
)

const DefaultDecoderBufferSize = 4096

// Unmarshaler is the interface implemented by objects that can unmarshal a binary representation of themselves.
// Implementing this bypasses reflection and is generally faster.
type Unmarshaler interface {
	UnmarshalBinny(dec *Decoder) error
}

// A Decoder reads binary data from an input stream, it also does a little bit of buffering.
type Decoder struct {
	r *bufio.Reader

	buf [16]byte
}

// NewDecoder is an alias for NewDecoder(r, DefaultDecoderBufferSize)
func NewDecoder(r io.Reader) *Decoder {
	return NewDecoderSize(r, DefaultDecoderBufferSize)
}

// NewDecoder returns a new decoder that reads from r with specific buffer size.
//
// The decoder introduces its own buffering and may
// read data from r beyond the requested values.
func NewDecoderSize(r io.Reader, sz int) *Decoder {
	if sz < 16 {
		sz = 16
	}

	return &Decoder{
		r: bufio.NewReaderSize(r, sz),
	}
}

// Reset discards any buffered data, resets all state, and switches
// the buffered reader to read from r.
func (dec *Decoder) Reset(r io.Reader) {
	dec.r.Reset(r)
}

func (dec *Decoder) readType() (Type, error) {
	b, err := dec.r.ReadByte()
	return Type(b), err
}

func (dec *Decoder) peekType() (Type, error) {
	b, err := dec.r.ReadByte()
	dec.r.UnreadByte()
	if err != nil {
		return 0, err
	}
	return Type(b), err
}

func (dec *Decoder) expectType(et Type) error {
	if t, _ := dec.readType(); t != et {
		return DecoderTypeError{et.String(), t}
	}
	return nil
}

// ReadBool returns a bool or an error.
func (dec *Decoder) ReadBool() (bool, error) {
	ft, _ := dec.readType()
	switch ft {
	case BoolTrue:
		return true, nil
	case BoolFalse:
		return false, nil
	}
	return false, DecoderTypeError{"Bool", ft}
}

func (dec *Decoder) readInt8() (int64, uint8, error) {
	b, err := dec.r.ReadByte()
	return int64(int8(b)), 8, err
}

func (dec *Decoder) readInt16() (int64, uint8, error) {
	buf := dec.buf[:2]
	_, err := dec.Read(buf)
	return int64(*(*int16)(unsafe.Pointer(&buf[0]))), 16, err
}

func (dec *Decoder) readInt32() (int64, uint8, error) {
	buf := dec.buf[:4]
	_, err := dec.Read(buf)
	return int64(*(*int32)(unsafe.Pointer(&buf[0]))), 32, err
}

func (dec *Decoder) readInt64() (int64, uint8, error) {
	buf := dec.buf[:8]
	_, err := dec.Read(buf)
	return int64(*(*int64)(unsafe.Pointer(&buf[0]))), 32, err
}

func (dec *Decoder) readVarInt() (int64, uint8, error) {
	v, err := binary.ReadVarint(dec.r)
	return v, 64, err
}

// ReadInt retruns an int/varint value and the size of it (8, 16, 32, 64) or an error.
func (dec *Decoder) ReadInt() (int64, uint8, error) {
	ft, err := dec.readType()
	if err != nil {
		return 0, 0, err
	}
	switch ft {
	case Int8:
		return dec.readInt8()
	case Int16:
		return dec.readInt16()
	case Int32:
		return dec.readInt32()
	case Int64:
		return dec.readInt64()
	case VarInt:
		return dec.readVarInt()
	}
	return 0, 0, DecoderTypeError{"int", ft}
}

func (dec *Decoder) readUint8() (uint64, uint8, error) {
	b, err := dec.r.ReadByte()
	return uint64(b), 8, err
}

func (dec *Decoder) readUint16() (uint64, uint8, error) {
	buf := dec.buf[:2]
	_, err := dec.Read(buf)
	return uint64(*(*uint16)(unsafe.Pointer(&buf[0]))), 16, err
}

func (dec *Decoder) readUint32() (uint64, uint8, error) {
	buf := dec.buf[:4]
	_, err := dec.Read(buf)
	return uint64(*(*uint32)(unsafe.Pointer(&buf[0]))), 32, err
}

func (dec *Decoder) readUint64() (uint64, uint8, error) {
	buf := dec.buf[:8]
	_, err := dec.Read(buf)
	return *(*uint64)(unsafe.Pointer(&buf[0])), 32, err
}

func (dec *Decoder) readVarUint() (uint64, uint8, error) {
	v, err := binary.ReadUvarint(dec.r)
	return v, 64, err
}

// ReadUint retruns an uint/varuint value and the size of it (8, 16, 32, 64) or an error.
func (dec *Decoder) ReadUint() (v uint64, sz uint8, err error) {
	ft, err := dec.readType()
	if err != nil {
		return 0, 0, err
	}
	switch ft {
	case Uint8:
		return dec.readUint8()
	case Uint16:
		return dec.readUint16()
	case Uint32:
		return dec.readUint32()
	case Uint64:
		return dec.readUint64()
	case VarUint:
		return dec.readVarUint()
	}
	return 0, 0, DecoderTypeError{"uint", ft}
}

// ReadFloat32 returns a float32 or an error.
func (dec *Decoder) ReadFloat32() (float32, error) {
	if err := dec.expectType(Float32); err != nil {
		return 0, err
	}
	buf := dec.buf[:4]
	_, err := dec.Read(buf)
	return *(*float32)(unsafe.Pointer(&buf[0])), err
}

// ReadFloat64 returns a float64 or an error.
func (dec *Decoder) ReadFloat64() (float64, error) {
	if err := dec.expectType(Float64); err != nil {
		return 0, err
	}
	buf := dec.buf[:8]
	_, err := dec.Read(buf)
	return *(*float64)(unsafe.Pointer(&buf[0])), err
}

// ReadComplex64 returns a complex64 or an error.
func (dec *Decoder) ReadComplex64() (complex64, error) {
	if err := dec.expectType(Complex64); err != nil {
		return 0, err
	}

	buf := dec.buf[:8]
	_, err := dec.Read(buf)
	return *(*complex64)(unsafe.Pointer(&buf[0])), err
}

// ReadComplex128 returns a complex128 or an error.
func (dec *Decoder) ReadComplex128() (complex128, error) {
	if err := dec.expectType(Complex128); err != nil {
		return 0, err
	}
	buf := dec.buf[:16]
	_, err := dec.Read(buf)
	return *(*complex128)(unsafe.Pointer(&buf[0])), err
}

func (dec *Decoder) readBytes(exp Type) ([]byte, error) {
	if err := dec.expectType(exp); err != nil {
		return nil, err
	}

	sz, _, err := dec.ReadUint()
	if err != nil || sz == 0 {
		return nil, err
	}

	buf := make([]byte, sz)
	_, err = io.ReadFull(dec.r, buf)
	return buf, err
}

// ReadBytes returns a byte slice.
func (dec *Decoder) ReadBytes() ([]byte, error) {
	return dec.readBytes(ByteSlice)
}

// ReadBytes returns a string.
func (dec *Decoder) ReadString() (string, error) {
	b, err := dec.readBytes(String)
	return string(b), err
}

// ReadBinary decodes and reads an object that implements the `encoding.BinaryUnmarshaler` interface.
func (dec *Decoder) ReadBinary(v encoding.BinaryUnmarshaler) error {
	b, err := dec.readBytes(Binary)
	if err != nil {
		return err
	}
	return v.UnmarshalBinary(b)
}

// ReadGob decodes and reads an object that implements the `gob.GobDecoder` interface.
func (dec *Decoder) ReadGob(v gob.GobDecoder) error {
	b, err := dec.readBytes(Gob)
	if err != nil {
		return err
	}
	return v.GobDecode(b)
}

// Decode reads the next binny-encoded value from its
// input and stores it in the value pointed to by v.
func (dec *Decoder) Decode(v interface{}) (err error) {
	switch v := v.(type) {
	case Unmarshaler:
		return v.UnmarshalBinny(dec)
	case encoding.BinaryUnmarshaler:
		return dec.ReadBinary(v)
	case gob.GobDecoder:
		return dec.ReadGob(v)
	case *string:
		*v, err = dec.ReadString()
		return
	case *[]byte:
		*v, err = dec.ReadBytes()
		return
	case *int64:
		*v, _, err = dec.ReadInt()
		return
	case *int32:
		var i int64
		i, _, err = dec.ReadInt()
		*v = int32(i)
		return
	case *int16:
		var i int64
		i, _, err = dec.ReadInt()
		*v = int16(i)
		return
	case *int8:
		var i int64
		i, _, err = dec.ReadInt()
		*v = int8(i)
		return
	case *int:
		var i int64
		i, _, err = dec.ReadInt()
		*v = int(i)
		return
	case *uint64:
		*v, _, err = dec.ReadUint()
		return
	case *uint32:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uint32(i)
		return
	case *uint16:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uint16(i)
		return
	case *uint8:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uint8(i)
		return
	case *uint:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uint(i)
		return
	case *uintptr:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uintptr(i)
		return
	case *float32:
		*v, err = dec.ReadFloat32()
		return
	case *float64:
		*v, err = dec.ReadFloat64()
		return
	case *complex64:
		*v, err = dec.ReadComplex64()
		return
	case *complex128:
		*v, err = dec.ReadComplex128()
		return
	case *bool:
		*v, err = dec.ReadBool()
		return
	}
	return dec.decodeValue(reflect.ValueOf(v))
}

func (dec *Decoder) decodeValue(v reflect.Value) error {
	if v.Kind() != reflect.Ptr || !v.Elem().CanSet() {
		return ErrNoPointer
	}
	fn := typeDecoder(v.Type())
	return fn(dec, v)
}

// Read allows the Decoder to be used as an io.Reader, note that internally this calls io.ReadFull().
func (dec *Decoder) Read(p []byte) (int, error) {
	return io.ReadFull(dec.r, p)
}

// Unmarshal is an alias for (sync.Pool'ed) NewDecoder(bytes.NewReader(b)).Decode(v)
func Unmarshal(b []byte, v interface{}) error {
	dec := getDec(bytes.NewReader(b))
	err := dec.Decode(v)
	putDec(dec)
	return err
}
<commit_msg>expose Write*Int*() funcs<commit_after>package binny

import (
	"bufio"
	"bytes"
	"encoding"
	"encoding/binary"
	"encoding/gob"
	"errors"
	"io"
	"reflect"
	"unsafe"
)

var (
	// ErrNoPointer gets returned if the user passes a non-pointer to Decode
	ErrNoPointer = errors.New("can't decode to a non-pointer")
)

const DefaultDecoderBufferSize = 4096

// Unmarshaler is the interface implemented by objects that can unmarshal a binary representation of themselves.
// Implementing this bypasses reflection and is generally faster.
type Unmarshaler interface {
	UnmarshalBinny(dec *Decoder) error
}

// A Decoder reads binary data from an input stream, it also does a little bit of buffering.
type Decoder struct {
	r *bufio.Reader

	buf [16]byte
}

// NewDecoder is an alias for NewDecoder(r, DefaultDecoderBufferSize)
func NewDecoder(r io.Reader) *Decoder {
	return NewDecoderSize(r, DefaultDecoderBufferSize)
}

// NewDecoder returns a new decoder that reads from r with specific buffer size.
//
// The decoder introduces its own buffering and may
// read data from r beyond the requested values.
func NewDecoderSize(r io.Reader, sz int) *Decoder {
	if sz < 16 {
		sz = 16
	}

	return &Decoder{
		r: bufio.NewReaderSize(r, sz),
	}
}

// Reset discards any buffered data, resets all state, and switches
// the buffered reader to read from r.
func (dec *Decoder) Reset(r io.Reader) {
	dec.r.Reset(r)
}

func (dec *Decoder) readType() (Type, error) {
	b, err := dec.r.ReadByte()
	return Type(b), err
}

func (dec *Decoder) peekType() Type {
	b, _ := dec.r.ReadByte()
	dec.r.UnreadByte()
	return Type(b)
}

func (dec *Decoder) expectType(et Type) error {
	if t, _ := dec.readType(); t != et {
		return DecoderTypeError{et.String(), t}
	}
	return nil
}

// ReadBool returns a bool or an error.
func (dec *Decoder) ReadBool() (bool, error) {
	ft, _ := dec.readType()
	switch ft {
	case BoolTrue:
		return true, nil
	case BoolFalse:
		return false, nil
	}
	return false, DecoderTypeError{"Bool", ft}
}

func (dec *Decoder) ReadInt8() (int8, error) {
	if err := dec.expectType(Int8); err != nil {
		return 0, err
	}
	b, err := dec.r.ReadByte()
	return int8(b), err
}

func (dec *Decoder) ReadInt16() (int16, error) {
	if err := dec.expectType(Int16); err != nil {
		return 0, err
	}
	buf := dec.buf[:2]
	_, err := dec.Read(buf)
	return *(*int16)(unsafe.Pointer(&buf[0])), err
}

func (dec *Decoder) ReadInt32() (int32, error) {
	if err := dec.expectType(Int32); err != nil {
		return 0, err
	}
	buf := dec.buf[:4]
	_, err := dec.Read(buf)
	return *(*int32)(unsafe.Pointer(&buf[0])), err
}

func (dec *Decoder) ReadInt64() (int64, error) {
	if err := dec.expectType(Int64); err != nil {
		return 0, err
	}
	buf := dec.buf[:8]
	_, err := dec.Read(buf)
	return *(*int64)(unsafe.Pointer(&buf[0])), err
}

func (dec *Decoder) ReadVarInt() (int64, error) {
	if err := dec.expectType(VarInt); err != nil {
		return 0, err
	}
	return binary.ReadVarint(dec.r)
}

// ReadInt retruns an int/varint value and the size of it (8, 16, 32, 64) or an error.
func (dec *Decoder) ReadInt() (int64, uint8, error) {
	ft := dec.peekType()
	switch ft {
	case Int8:
		v, err := dec.ReadInt8()
		return int64(v), 8, err
	case Int16:
		v, err := dec.ReadInt16()
		return int64(v), 16, err
	case Int32:
		v, err := dec.ReadInt32()
		return int64(v), 32, err
	case Int64:
		v, err := dec.ReadInt64()
		return v, 64, err
	case VarInt:
		v, err := dec.ReadVarInt()
		return v, 64, err
	}
	return 0, 0, DecoderTypeError{"int", ft}
}

func (dec *Decoder) ReadUint8() (uint8, error) {
	if err := dec.expectType(Uint8); err != nil {
		return 0, err
	}
	return dec.r.ReadByte()
}

func (dec *Decoder) ReadUint16() (uint16, error) {
	if err := dec.expectType(Uint16); err != nil {
		return 0, err
	}
	buf := dec.buf[:2]
	_, err := dec.Read(buf)
	return *(*uint16)(unsafe.Pointer(&buf[0])), err
}

func (dec *Decoder) ReadUint32() (uint32, error) {
	if err := dec.expectType(Uint32); err != nil {
		return 0, err
	}
	buf := dec.buf[:4]
	_, err := dec.Read(buf)
	return *(*uint32)(unsafe.Pointer(&buf[0])), err
}

func (dec *Decoder) ReadUint64() (uint64, error) {
	if err := dec.expectType(Uint64); err != nil {
		return 0, err
	}
	buf := dec.buf[:8]
	_, err := dec.Read(buf)
	return *(*uint64)(unsafe.Pointer(&buf[0])), err
}

func (dec *Decoder) ReadVarUint() (uint64, error) {
	if err := dec.expectType(VarUint); err != nil {
		return 0, err
	}
	return binary.ReadUvarint(dec.r)
}

// ReadUint retruns an uint/varuint value and the size of it (8, 16, 32, 64) or an error.
func (dec *Decoder) ReadUint() (v uint64, sz uint8, err error) {
	ft := dec.peekType()
	switch ft {
	case Uint8:
		v, err := dec.ReadUint8()
		return uint64(v), 8, err
	case Uint16:
		v, err := dec.ReadUint16()
		return uint64(v), 16, err
	case Uint32:
		v, err := dec.ReadUint32()
		return uint64(v), 32, err
	case Uint64:
		v, err := dec.ReadUint64()
		return v, 64, err
	case VarUint:
		v, err := dec.ReadVarUint()
		return v, 64, err
	}
	return 0, 0, DecoderTypeError{"uint", ft}
}

// ReadFloat32 returns a float32 or an error.
func (dec *Decoder) ReadFloat32() (float32, error) {
	if err := dec.expectType(Float32); err != nil {
		return 0, err
	}
	buf := dec.buf[:4]
	_, err := dec.Read(buf)
	return *(*float32)(unsafe.Pointer(&buf[0])), err
}

// ReadFloat64 returns a float64 or an error.
func (dec *Decoder) ReadFloat64() (float64, error) {
	if err := dec.expectType(Float64); err != nil {
		return 0, err
	}
	buf := dec.buf[:8]
	_, err := dec.Read(buf)
	return *(*float64)(unsafe.Pointer(&buf[0])), err
}

// ReadComplex64 returns a complex64 or an error.
func (dec *Decoder) ReadComplex64() (complex64, error) {
	if err := dec.expectType(Complex64); err != nil {
		return 0, err
	}

	buf := dec.buf[:8]
	_, err := dec.Read(buf)
	return *(*complex64)(unsafe.Pointer(&buf[0])), err
}

// ReadComplex128 returns a complex128 or an error.
func (dec *Decoder) ReadComplex128() (complex128, error) {
	if err := dec.expectType(Complex128); err != nil {
		return 0, err
	}
	buf := dec.buf[:16]
	_, err := dec.Read(buf)
	return *(*complex128)(unsafe.Pointer(&buf[0])), err
}

func (dec *Decoder) readBytes(exp Type) ([]byte, error) {
	if err := dec.expectType(exp); err != nil {
		return nil, err
	}

	sz, _, err := dec.ReadUint()
	if err != nil || sz == 0 {
		return nil, err
	}

	buf := make([]byte, sz)
	_, err = io.ReadFull(dec.r, buf)
	return buf, err
}

// ReadBytes returns a byte slice.
func (dec *Decoder) ReadBytes() ([]byte, error) {
	return dec.readBytes(ByteSlice)
}

// ReadBytes returns a string.
func (dec *Decoder) ReadString() (string, error) {
	b, err := dec.readBytes(String)
	return string(b), err
}

// ReadBinary decodes and reads an object that implements the `encoding.BinaryUnmarshaler` interface.
func (dec *Decoder) ReadBinary(v encoding.BinaryUnmarshaler) error {
	b, err := dec.readBytes(Binary)
	if err != nil {
		return err
	}
	return v.UnmarshalBinary(b)
}

// ReadGob decodes and reads an object that implements the `gob.GobDecoder` interface.
func (dec *Decoder) ReadGob(v gob.GobDecoder) error {
	b, err := dec.readBytes(Gob)
	if err != nil {
		return err
	}
	return v.GobDecode(b)
}

// Decode reads the next binny-encoded value from its
// input and stores it in the value pointed to by v.
func (dec *Decoder) Decode(v interface{}) (err error) {
	switch v := v.(type) {
	case Unmarshaler:
		return v.UnmarshalBinny(dec)
	case encoding.BinaryUnmarshaler:
		return dec.ReadBinary(v)
	case gob.GobDecoder:
		return dec.ReadGob(v)
	case *string:
		*v, err = dec.ReadString()
		return
	case *[]byte:
		*v, err = dec.ReadBytes()
		return
	case *int64:
		*v, _, err = dec.ReadInt()
		return
	case *int32:
		var i int64
		i, _, err = dec.ReadInt()
		*v = int32(i)
		return
	case *int16:
		var i int64
		i, _, err = dec.ReadInt()
		*v = int16(i)
		return
	case *int8:
		var i int64
		i, _, err = dec.ReadInt()
		*v = int8(i)
		return
	case *int:
		var i int64
		i, _, err = dec.ReadInt()
		*v = int(i)
		return
	case *uint64:
		*v, _, err = dec.ReadUint()
		return
	case *uint32:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uint32(i)
		return
	case *uint16:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uint16(i)
		return
	case *uint8:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uint8(i)
		return
	case *uint:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uint(i)
		return
	case *uintptr:
		var i uint64
		i, _, err = dec.ReadUint()
		*v = uintptr(i)
		return
	case *float32:
		*v, err = dec.ReadFloat32()
		return
	case *float64:
		*v, err = dec.ReadFloat64()
		return
	case *complex64:
		*v, err = dec.ReadComplex64()
		return
	case *complex128:
		*v, err = dec.ReadComplex128()
		return
	case *bool:
		*v, err = dec.ReadBool()
		return
	}
	return dec.decodeValue(reflect.ValueOf(v))
}

func (dec *Decoder) decodeValue(v reflect.Value) error {
	if v.Kind() != reflect.Ptr || !v.Elem().CanSet() {
		return ErrNoPointer
	}
	fn := typeDecoder(v.Type())
	return fn(dec, v)
}

// Read allows the Decoder to be used as an io.Reader, note that internally this calls io.ReadFull().
func (dec *Decoder) Read(p []byte) (int, error) {
	return io.ReadFull(dec.r, p)
}

// Unmarshal is an alias for (sync.Pool'ed) NewDecoder(bytes.NewReader(b)).Decode(v)
func Unmarshal(b []byte, v interface{}) error {
	dec := getDec(bytes.NewReader(b))
	err := dec.Decode(v)
	putDec(dec)
	return err
}
<|endoftext|>


<commit_before>// Copyright (c) 2018 Cisco and/or its affiliates.
//
// 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 vpp-agent-ctl implements the vpp-agent-ctl test tool for testing
// VPP Agent plugins. In addition to testing, the vpp-agent-ctl tool can
// be used to demonstrate the usage of VPP Agent plugins and their APIs.
package main

import (
	"bytes"
	"os"
	"strconv"

	"github.com/ligato/cn-infra/logging/logrus"
	"golang.org/x/crypto/bcrypt"
)

// A simple utility to help with password hashing. Hashed password can be stored as
// user password in config file. Always provide two parameters; password and cost.

func main() {
	// Read args
	args := os.Args
	if len(args) != 3 {
		usage()
		return
	}

	pass := args[1]
	cost, err := strconv.Atoi(args[2])
	if err != nil {
		logrus.DefaultLogger().Errorf("invalid cost format: %v", err)
		os.Exit(1)
	}
	if cost < 4 || cost > 31 {
		logrus.DefaultLogger().Errorf("invalid cost value %d, set it in interval 4-31", cost)
		os.Exit(1)
	}
	hash, err := bcrypt.GenerateFromPassword([]byte(pass), cost)
	if err != nil {
		logrus.DefaultLogger().Errorf("failed to hash password: %v", err)
		os.Exit(1)
	}

	logrus.DefaultLogger().Print(string(hash))
}

// Show info
func usage() {
	var buffer bytes.Buffer
	// Crud operation
	buffer.WriteString(`

	Simple password hasher. Since the user credentials
	can be stored in the config file, this utility helps
	to hash the password and store it as such.

	./password-hasher <password> <cost>

	The cost value has to match the one in the config file.
	Allowed interval is 4-31. Note that the high number
	takes a lot of time to process.

	Please do not use your bank account password.
	We didn't spend much time securing it.
	`)

	logrus.DefaultLogger().Print(buffer.String())
}
<commit_msg>Removed invalid section from header (#407)<commit_after>// Copyright (c) 2018 Cisco and/or its affiliates.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main

import (
	"bytes"
	"os"
	"strconv"

	"github.com/ligato/cn-infra/logging/logrus"
	"golang.org/x/crypto/bcrypt"
)

// A simple utility to help with password hashing. Hashed password can be stored as
// user password in config file. Always provide two parameters; password and cost.

func main() {
	// Read args
	args := os.Args
	if len(args) != 3 {
		usage()
		return
	}

	pass := args[1]
	cost, err := strconv.Atoi(args[2])
	if err != nil {
		logrus.DefaultLogger().Errorf("invalid cost format: %v", err)
		os.Exit(1)
	}
	if cost < 4 || cost > 31 {
		logrus.DefaultLogger().Errorf("invalid cost value %d, set it in interval 4-31", cost)
		os.Exit(1)
	}
	hash, err := bcrypt.GenerateFromPassword([]byte(pass), cost)
	if err != nil {
		logrus.DefaultLogger().Errorf("failed to hash password: %v", err)
		os.Exit(1)
	}

	logrus.DefaultLogger().Print(string(hash))
}

// Show info
func usage() {
	var buffer bytes.Buffer
	// Crud operation
	buffer.WriteString(`

	Simple password hasher. Since the user credentials
	can be stored in the config file, this utility helps
	to hash the password and store it as such.

	./password-hasher <password> <cost>

	The cost value has to match the one in the config file.
	Allowed interval is 4-31. Note that the high number
	takes a lot of time to process.

	Please do not use your bank account password.
	We didn't spend much time securing it.
	`)

	logrus.DefaultLogger().Print(buffer.String())
}
<|endoftext|>


<commit_before>package app

import (
	"cf/api"
	"cf/commands"
	"cf/configuration"
	"cf/requirements"
	"cf/terminal"
	"fmt"
	"github.com/codegangsta/cli"
	"os"
)

func New() (app *cli.App, err error) {
	cli.AppHelpTemplate = `NAME:
   {{.Name}} - {{.Usage}}

USAGE:
   [environment variables] {{.Name}} [global options] command [command options] [arguments...]

VERSION:
   {{.Version}}

COMMANDS:
   {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Description}}
   {{end}}
GLOBAL OPTIONS:
   {{range .Flags}}{{.}}
   {{end}}
ENVIRONMENT VARIABLES:
   CF_TRACE=true - will output HTTP requests and responses during command
   HTTP_PROXY=http://proxy.example.com:8080 - set to your proxy
`

	cli.CommandHelpTemplate = `NAME:
   {{.Name}} - {{.Description}}

USAGE:
   {{.Usage}}{{with .Flags}}

OPTIONS:
   {{range .}}{{.}}
   {{end}}{{else}}
{{end}}`

	termUI := new(terminal.TerminalUI)
	configRepo := configuration.NewConfigurationDiskRepository()
	config, err := configRepo.Get()
	if err != nil {
		termUI.Failed(fmt.Sprintf("Error loading config. Please reset target (%s) and log in (%s).", terminal.Yellow("cf target"), terminal.Yellow("cf login")), nil)
		configRepo.Delete()
		os.Exit(1)
		return
	}

	repoLocator := api.NewRepositoryLocator(config)
	cmdFactory := commands.NewFactory(termUI, repoLocator)
	reqFactory := requirements.NewFactory(termUI, repoLocator)
	cmdRunner := commands.NewRunner(reqFactory)

	app = cli.NewApp()
	app.Name = "cf"
	app.Usage = "A command line tool to interact with Cloud Foundry"
	app.Version = "1.0.0.alpha"
	app.Commands = []cli.Command{
		{
			Name:        "target",
			ShortName:   "t",
			Description: "Set or view the target",
			Usage:       "cf target <target> --o <organization> --s <space>",
			Flags: []cli.Flag{
				cli.StringFlag{"o", "", "organization"},
				cli.StringFlag{"s", "", "space"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewTarget()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "login",
			ShortName:   "l",
			Description: "Log user in",
			Usage:       "cf login [username]",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewLogin()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "set-env",
			ShortName:   "se",
			Description: "Set an environment variable for an application",
			Usage:       "cf set-env <application> <variable> <value>",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewSetEnv()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "logout",
			ShortName:   "lo",
			Description: "Log user out",
			Usage:       "cf logout",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewLogout()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "push",
			ShortName:   "p",
			Description: "Push an application",
			Usage: "cf push --name <application> [--domain <domain>] [--host <hostname>] [--instances <num>]\n" +
				"                                [--memory <memory>] [--buildpack <url>] [--no-start] [--path <path to app>]\n" +
				"                                [--stack <stack>]",
			Flags: []cli.Flag{
				cli.StringFlag{"name", "", "name of the application"},
				cli.StringFlag{"domain", "", "domain (for example: cfapps.io)"},
				cli.StringFlag{"host", "", "hostname (for example: my-subdomain)"},
				cli.IntFlag{"instances", 1, "number of instances"},
				cli.StringFlag{"memory", "128", "memory limit (for example: 256, 1G, 1024M)"},
				cli.StringFlag{"buildpack", "", "custom buildpack URL (for example: https://github.com/heroku/heroku-buildpack-play.git)"},
				cli.BoolFlag{"no-start", "do not start an application after pushing"},
				cli.StringFlag{"path", "", "path of application directory or zip file"},
				cli.StringFlag{"stack", "", "stack to use"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewPush()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "apps",
			ShortName:   "a",
			Description: "List all applications in the currently selected space",
			Usage:       "cf apps",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewApps()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "delete",
			ShortName:   "d",
			Description: "Delete an application",
			Usage:       "cf delete -f <application>",
			Flags: []cli.Flag{
				cli.BoolFlag{"f", "force deletion without confirmation"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewDelete()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "start",
			ShortName:   "s",
			Description: "Start applications",
			Usage:       "cf start <application>",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewStart()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "stop",
			ShortName:   "st",
			Description: "Stop applications",
			Usage:       "cf stop <application>",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewStop()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "create-service",
			ShortName:   "cs",
			Description: "Create service instance",
			Usage: "cf create-service --offering <offering> --plan <plan> --name <service instance name>\n" +
				"   cf create-service --offering user-provided --name <service name> --parameters \"<comma separated parameter list>\"",
			Flags: []cli.Flag{
				cli.StringFlag{"name", "", "name of the service instance"},
				cli.StringFlag{"offering", "", "name of the service offering to use"},
				cli.StringFlag{"plan", "", "name of the service plan to use"},
				cli.StringFlag{"parameters", "", "parameters to use for user-provided services"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewCreateService()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "bind-service",
			ShortName:   "bs",
			Description: "Bind a service instance to an application",
			Usage:       "cf bind-service --app <application name> --service <service instance name>",
			Flags: []cli.Flag{
				cli.StringFlag{"app", "", "name of the application"},
				cli.StringFlag{"service", "", "name of the service instance to bind to the application"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewBindService()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "unbind-service",
			ShortName:   "us",
			Description: "Unbind a service instance from an application",
			Usage:       "cf unbind-service --app <application name> --service <service instance name>",
			Flags: []cli.Flag{
				cli.StringFlag{"app", "", "name of the application"},
				cli.StringFlag{"service", "", "name of the service instance to unbind from the application"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewUnbindService()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "delete-service",
			ShortName:   "ds",
			Description: "Delete a service instance",
			Usage:       "cf delete-service <service instance name>",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewDeleteService()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "routes",
			ShortName:   "r",
			Description: "List all routes",
			Usage:       "cf routes",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewRoutes()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "services",
			ShortName:   "sv",
			Description: "List all services in the currently selected space",
			Usage:       "cf services [--marketplace]",
			Flags: []cli.Flag{
				cli.BoolFlag{"marketplace", "use to list available offerings on the marketplace"},
			},
			Action: func(c *cli.Context) {
				var cmd commands.Command
				cmd = cmdFactory.NewServices()

				if c.Bool("marketplace") {
					cmd = cmdFactory.NewMarketplaceServices()
				}

				cmdRunner.Run(cmd, c)
			},
		},
	}
	return
}
<commit_msg>Updated help text for create-service<commit_after>package app

import (
	"cf/api"
	"cf/commands"
	"cf/configuration"
	"cf/requirements"
	"cf/terminal"
	"fmt"
	"github.com/codegangsta/cli"
	"os"
)

func New() (app *cli.App, err error) {
	cli.AppHelpTemplate = `NAME:
   {{.Name}} - {{.Usage}}

USAGE:
   [environment variables] {{.Name}} [global options] command [command options] [arguments...]

VERSION:
   {{.Version}}

COMMANDS:
   {{range .Commands}}{{.Name}}{{with .ShortName}}, {{.}}{{end}}{{ "\t" }}{{.Description}}
   {{end}}
GLOBAL OPTIONS:
   {{range .Flags}}{{.}}
   {{end}}
ENVIRONMENT VARIABLES:
   CF_TRACE=true - will output HTTP requests and responses during command
   HTTP_PROXY=http://proxy.example.com:8080 - set to your proxy
`

	cli.CommandHelpTemplate = `NAME:
   {{.Name}} - {{.Description}}

USAGE:
   {{.Usage}}{{with .Flags}}

OPTIONS:
   {{range .}}{{.}}
   {{end}}{{else}}
{{end}}`

	termUI := new(terminal.TerminalUI)
	configRepo := configuration.NewConfigurationDiskRepository()
	config, err := configRepo.Get()
	if err != nil {
		termUI.Failed(fmt.Sprintf("Error loading config. Please reset target (%s) and log in (%s).", terminal.Yellow("cf target"), terminal.Yellow("cf login")), nil)
		configRepo.Delete()
		os.Exit(1)
		return
	}

	repoLocator := api.NewRepositoryLocator(config)
	cmdFactory := commands.NewFactory(termUI, repoLocator)
	reqFactory := requirements.NewFactory(termUI, repoLocator)
	cmdRunner := commands.NewRunner(reqFactory)

	app = cli.NewApp()
	app.Name = "cf"
	app.Usage = "A command line tool to interact with Cloud Foundry"
	app.Version = "1.0.0.alpha"
	app.Commands = []cli.Command{
		{
			Name:        "target",
			ShortName:   "t",
			Description: "Set or view the target",
			Usage:       "cf target <target> --o <organization> --s <space>",
			Flags: []cli.Flag{
				cli.StringFlag{"o", "", "organization"},
				cli.StringFlag{"s", "", "space"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewTarget()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "login",
			ShortName:   "l",
			Description: "Log user in",
			Usage:       "cf login [username]",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewLogin()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "set-env",
			ShortName:   "se",
			Description: "Set an environment variable for an application",
			Usage:       "cf set-env <application> <variable> <value>",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewSetEnv()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "logout",
			ShortName:   "lo",
			Description: "Log user out",
			Usage:       "cf logout",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewLogout()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "push",
			ShortName:   "p",
			Description: "Push an application",
			Usage: "cf push --name <application> [--domain <domain>] [--host <hostname>] [--instances <num>]\n" +
				"                                [--memory <memory>] [--buildpack <url>] [--no-start] [--path <path to app>]\n" +
				"                                [--stack <stack>]",
			Flags: []cli.Flag{
				cli.StringFlag{"name", "", "name of the application"},
				cli.StringFlag{"domain", "", "domain (for example: cfapps.io)"},
				cli.StringFlag{"host", "", "hostname (for example: my-subdomain)"},
				cli.IntFlag{"instances", 1, "number of instances"},
				cli.StringFlag{"memory", "128", "memory limit (for example: 256, 1G, 1024M)"},
				cli.StringFlag{"buildpack", "", "custom buildpack URL (for example: https://github.com/heroku/heroku-buildpack-play.git)"},
				cli.BoolFlag{"no-start", "do not start an application after pushing"},
				cli.StringFlag{"path", "", "path of application directory or zip file"},
				cli.StringFlag{"stack", "", "stack to use"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewPush()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "apps",
			ShortName:   "a",
			Description: "List all applications in the currently selected space",
			Usage:       "cf apps",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewApps()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "delete",
			ShortName:   "d",
			Description: "Delete an application",
			Usage:       "cf delete -f <application>",
			Flags: []cli.Flag{
				cli.BoolFlag{"f", "force deletion without confirmation"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewDelete()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "start",
			ShortName:   "s",
			Description: "Start applications",
			Usage:       "cf start <application>",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewStart()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "stop",
			ShortName:   "st",
			Description: "Stop applications",
			Usage:       "cf stop <application>",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewStop()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "create-service",
			ShortName:   "cs",
			Description: "Create service instance",
			Usage: "cf create-service --offering <offering> --plan <plan> --name <service instance name>\n" +
				"   cf create-service --offering user-provided --name <service name> --parameters \"<comma separated parameter names>\"",
			Flags: []cli.Flag{
				cli.StringFlag{"name", "", "name of the service instance"},
				cli.StringFlag{"offering", "", "name of the service offering to use"},
				cli.StringFlag{"plan", "", "name of the service plan to use"},
				cli.StringFlag{"parameters", "", "list of comma parameter names to use for user-provided services (eg. \"n1,n2\")"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewCreateService()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "bind-service",
			ShortName:   "bs",
			Description: "Bind a service instance to an application",
			Usage:       "cf bind-service --app <application name> --service <service instance name>",
			Flags: []cli.Flag{
				cli.StringFlag{"app", "", "name of the application"},
				cli.StringFlag{"service", "", "name of the service instance to bind to the application"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewBindService()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "unbind-service",
			ShortName:   "us",
			Description: "Unbind a service instance from an application",
			Usage:       "cf unbind-service --app <application name> --service <service instance name>",
			Flags: []cli.Flag{
				cli.StringFlag{"app", "", "name of the application"},
				cli.StringFlag{"service", "", "name of the service instance to unbind from the application"},
			},
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewUnbindService()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "delete-service",
			ShortName:   "ds",
			Description: "Delete a service instance",
			Usage:       "cf delete-service <service instance name>",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewDeleteService()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "routes",
			ShortName:   "r",
			Description: "List all routes",
			Usage:       "cf routes",
			Action: func(c *cli.Context) {
				cmd := cmdFactory.NewRoutes()
				cmdRunner.Run(cmd, c)
			},
		},
		{
			Name:        "services",
			ShortName:   "sv",
			Description: "List all services in the currently selected space",
			Usage:       "cf services [--marketplace]",
			Flags: []cli.Flag{
				cli.BoolFlag{"marketplace", "use to list available offerings on the marketplace"},
			},
			Action: func(c *cli.Context) {
				var cmd commands.Command
				cmd = cmdFactory.NewServices()

				if c.Bool("marketplace") {
					cmd = cmdFactory.NewMarketplaceServices()
				}

				cmdRunner.Run(cmd, c)
			},
		},
	}
	return
}
<|endoftext|>


<commit_before>// +build !solaris

package main

import (
	"fmt"
	"os"
	"syscall"
	"unsafe"
)

// NewConsole returns an initialized console that can be used within a container by copying bytes
// from the master side to the slave that is attached as the tty for the container's init process.
func newConsole(uid, gid int) (*os.File, string, error) {
	master, err := os.OpenFile("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0)
	if err != nil {
		return nil, "", err
	}
	console, err := ptsname(master)
	if err != nil {
		return nil, "", err
	}
	if err := unlockpt(master); err != nil {
		return nil, "", err
	}
	if err := os.Chmod(console, 0600); err != nil {
		return nil, "", err
	}
	if err := os.Chown(console, uid, gid); err != nil {
		return nil, "", err
	}
	return master, console, nil
}

func ioctl(fd uintptr, flag, data uintptr) error {
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, flag, data); err != 0 {
		return err
	}
	return nil
}

// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.
// unlockpt should be called before opening the slave side of a pty.
func unlockpt(f *os.File) error {
	var u int32
	return ioctl(f.Fd(), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))
}

// ptsname retrieves the name of the first available pts for the given master.
func ptsname(f *os.File) (string, error) {
	var n int32
	if err := ioctl(f.Fd(), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))); err != nil {
		return "", err
	}
	return fmt.Sprintf("/dev/pts/%d", n), nil
}
<commit_msg>io: stop screwing with \n in console output<commit_after>// +build !solaris

package main

import (
	"fmt"
	"os"
	"syscall"
	"unsafe"
)

// NewConsole returns an initialized console that can be used within a container by copying bytes
// from the master side to the slave that is attached as the tty for the container's init process.
func newConsole(uid, gid int) (*os.File, string, error) {
	master, err := os.OpenFile("/dev/ptmx", syscall.O_RDWR|syscall.O_NOCTTY|syscall.O_CLOEXEC, 0)
	if err != nil {
		return nil, "", err
	}
	if err = saneTerminal(master); err != nil {
		return nil, "", err
	}
	console, err := ptsname(master)
	if err != nil {
		return nil, "", err
	}
	if err := unlockpt(master); err != nil {
		return nil, "", err
	}
	if err := os.Chmod(console, 0600); err != nil {
		return nil, "", err
	}
	if err := os.Chown(console, uid, gid); err != nil {
		return nil, "", err
	}
	return master, console, nil
}

// saneTerminal sets the necessary tty_ioctl(4)s to ensure that a pty pair
// created by us acts normally. In particular, a not-very-well-known default of
// Linux unix98 ptys is that they have +onlcr by default. While this isn't a
// problem for terminal emulators, because we relay data from the terminal we
// also relay that funky line discipline.
func saneTerminal(terminal *os.File) error {
	// Go doesn't have a wrapper for any of the termios ioctls.
	var termios syscall.Termios

	if err := ioctl(terminal.Fd(), syscall.TCGETS, uintptr(unsafe.Pointer(&termios))); err != nil {
		return fmt.Errorf("ioctl(tty, tcgets): %s", err.Error())
	}

	// Set -onlcr so we don't have to deal with \r.
	termios.Oflag &^= syscall.ONLCR

	if err := ioctl(terminal.Fd(), syscall.TCSETS, uintptr(unsafe.Pointer(&termios))); err != nil {
		return fmt.Errorf("ioctl(tty, tcsets): %s", err.Error())
	}

	return nil
}

func ioctl(fd uintptr, flag, data uintptr) error {
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd, flag, data); err != 0 {
		return err
	}
	return nil
}

// unlockpt unlocks the slave pseudoterminal device corresponding to the master pseudoterminal referred to by f.
// unlockpt should be called before opening the slave side of a pty.
func unlockpt(f *os.File) error {
	var u int32
	return ioctl(f.Fd(), syscall.TIOCSPTLCK, uintptr(unsafe.Pointer(&u)))
}

// ptsname retrieves the name of the first available pts for the given master.
func ptsname(f *os.File) (string, error) {
	var n int32
	if err := ioctl(f.Fd(), syscall.TIOCGPTN, uintptr(unsafe.Pointer(&n))); err != nil {
		return "", err
	}
	return fmt.Sprintf("/dev/pts/%d", n), nil
}
<|endoftext|>


<commit_before>package cmd

import (
	"fmt"

	"github.com/exoscale/egoscale"
	"github.com/spf13/cobra"
)

func init() {
	firewallRemoveCmd.Flags().BoolP("force", "f", false, "Attempt to remove firewall rule without prompting for confirmation")
	firewallRemoveCmd.Flags().BoolP("ipv6", "6", false, "Remove rule with any IPv6 source")
	firewallRemoveCmd.Flags().BoolP("my-ip", "m", false, "Remove rule with my IP as a source")
	firewallRemoveCmd.Flags().BoolP("all", "", false, "Remove all rules")
	firewallCmd.AddCommand(firewallRemoveCmd)
}

// removeCmd represents the remove command
var firewallRemoveCmd = &cobra.Command{
	Use:     "remove <security group name | id> <rule id | default rule name> [flags]\n  exo firewall remove <security group name | id> [flags]",
	Short:   "Remove a rule from a security group",
	Aliases: gRemoveAlias,
	RunE: func(cmd *cobra.Command, args []string) error {

		deleteAll, err := cmd.Flags().GetBool("all")
		if err != nil {
			return err
		}

		force, err := cmd.Flags().GetBool("force")
		if err != nil {
			return err
		}

		sgName := args[0]

		if len(args) == 1 && deleteAll {
			sg, errGet := getSecurityGroupByNameOrID(sgName)
			if errGet != nil {
				return errGet
			}
			count := len(sg.IngressRule) + len(sg.EgressRule)
			if !force {
				if !askQuestion(fmt.Sprintf("Are you sure you want to delete all %d firewall rule(s) from %s", count, sgName)) {
					return nil
				}
			}
			return removeAllRules(sgName)
		}

		if len(args) < 2 {
			return cmd.Usage()
		}

		if !force {
			if !askQuestion(fmt.Sprintf("Are your sure you want to delete the %q firewall rule from %s", args[1], sgName)) {
				return nil
			}
		}

		isMyIP, err := cmd.Flags().GetBool("my-ip")
		if err != nil {
			return err
		}

		isIpv6, err := cmd.Flags().GetBool("ipv6")
		if err != nil {
			return err
		}

		var cidr *egoscale.CIDR
		if isMyIP {
			c, errGet := getMyCIDR(isIpv6)
			if errGet != nil {
				return errGet
			}
			cidr = c
		}

		r, err := getDefaultRule(args[1], isIpv6)
		if err == nil {
			ru := &egoscale.IngressRule{
				CIDR:      &r.CIDRList[0],
				StartPort: r.StartPort,
				EndPort:   r.EndPort,
				Protocol:  r.Protocol,
			}
			return removeDefault(args[0], args[1], ru, cidr, isIpv6)
		}

		return removeRule(args[0], args[1])
	},
}

func removeAllRules(sgName string) error {
	sg, err := getSecurityGroupByNameOrID(sgName)
	if err != nil {
		return err
	}

	tasks := []task{}

	for _, in := range sg.IngressRule {
		tasks = append(tasks, task{&egoscale.RevokeSecurityGroupIngress{ID: in.RuleID}, fmt.Sprintf("Remove %q", in.RuleID)})
	}
	for _, eg := range sg.EgressRule {
		tasks = append(tasks, task{&egoscale.RevokeSecurityGroupEgress{ID: eg.RuleID}, fmt.Sprintf("Remove %q", eg.RuleID)})
	}

	_, errs := asyncTasks(tasks)

	if len(errs) > 0 {
		return errs[0]
	}
	return nil
}

func removeRule(name, ruleID string) error {
	sg, err := getSecurityGroupByNameOrID(name)
	if err != nil {
		return err
	}

	id, err := egoscale.ParseUUID(ruleID)
	if err != nil {
		return err
	}

	in, eg := sg.RuleByID(*id)

	if in != nil {
		err = cs.BooleanRequestWithContext(gContext, &egoscale.RevokeSecurityGroupIngress{ID: in.RuleID})
	} else if eg != nil {
		err = cs.BooleanRequestWithContext(gContext, &egoscale.RevokeSecurityGroupEgress{ID: eg.RuleID})
	} else {
		err = fmt.Errorf("rule with id %q is not ingress or egress rule", ruleID)
	}

	if err != nil {
		return err
	}

	_, err = fmt.Println(ruleID)
	return err
}

func isDefaultRule(rule, defaultRule *egoscale.IngressRule, isIpv6 bool, myCidr *egoscale.CIDR) bool {
	cidr := defaultCIDR
	if isIpv6 {
		cidr = defaultCIDR6
	}

	if myCidr != nil {
		cidr = myCidr
	}

	return (rule.StartPort == defaultRule.StartPort &&
		rule.EndPort == defaultRule.EndPort &&
		rule.CIDR == cidr &&
		rule.Protocol == defaultRule.Protocol)
}

func removeDefault(sgName, ruleName string, rule *egoscale.IngressRule, cidr *egoscale.CIDR, isIpv6 bool) error {
	sg, err := getSecurityGroupByNameOrID(sgName)
	if err != nil {
		return err
	}

	for _, in := range sg.IngressRule {
		if !isDefaultRule(&in, rule, isIpv6, cidr) {
			// Rule not found
			continue
		}

		err := cs.BooleanRequestWithContext(gContext, &egoscale.RevokeSecurityGroupIngress{ID: in.RuleID})
		if err != nil {
			return err
		}

		fmt.Println(in.RuleID)
		return nil
	}
	return fmt.Errorf("missing rule %q", ruleName)
}
<commit_msg>exo: fix firewall rm panic<commit_after>package cmd

import (
	"fmt"

	"github.com/exoscale/egoscale"
	"github.com/spf13/cobra"
)

func init() {
	firewallRemoveCmd.Flags().BoolP("force", "f", false, "Attempt to remove firewall rule without prompting for confirmation")
	firewallRemoveCmd.Flags().BoolP("ipv6", "6", false, "Remove rule with any IPv6 source")
	firewallRemoveCmd.Flags().BoolP("my-ip", "m", false, "Remove rule with my IP as a source")
	firewallRemoveCmd.Flags().BoolP("all", "", false, "Remove all rules")
	firewallCmd.AddCommand(firewallRemoveCmd)
}

// removeCmd represents the remove command
var firewallRemoveCmd = &cobra.Command{
	Use:     "remove <security group name | id> <rule id | default rule name> [flags]\n  exo firewall remove <security group name | id> [flags]",
	Short:   "Remove a rule from a security group",
	Aliases: gRemoveAlias,
	RunE: func(cmd *cobra.Command, args []string) error {
		if len(args) < 1 {
			return cmd.Usage()
		}

		deleteAll, err := cmd.Flags().GetBool("all")
		if err != nil {
			return err
		}

		force, err := cmd.Flags().GetBool("force")
		if err != nil {
			return err
		}

		sgName := args[0]

		if len(args) == 1 && deleteAll {
			sg, errGet := getSecurityGroupByNameOrID(sgName)
			if errGet != nil {
				return errGet
			}
			count := len(sg.IngressRule) + len(sg.EgressRule)
			if !force {
				if !askQuestion(fmt.Sprintf("Are you sure you want to delete all %d firewall rule(s) from %s", count, sgName)) {
					return nil
				}
			}
			return removeAllRules(sgName)
		}

		if len(args) < 2 {
			return cmd.Usage()
		}

		if !force {
			if !askQuestion(fmt.Sprintf("Are your sure you want to delete the %q firewall rule from %s", args[1], sgName)) {
				return nil
			}
		}

		isMyIP, err := cmd.Flags().GetBool("my-ip")
		if err != nil {
			return err
		}

		isIpv6, err := cmd.Flags().GetBool("ipv6")
		if err != nil {
			return err
		}

		var cidr *egoscale.CIDR
		if isMyIP {
			c, errGet := getMyCIDR(isIpv6)
			if errGet != nil {
				return errGet
			}
			cidr = c
		}

		r, err := getDefaultRule(args[1], isIpv6)
		if err == nil {
			ru := &egoscale.IngressRule{
				CIDR:      &r.CIDRList[0],
				StartPort: r.StartPort,
				EndPort:   r.EndPort,
				Protocol:  r.Protocol,
			}
			return removeDefault(args[0], args[1], ru, cidr, isIpv6)
		}

		return removeRule(args[0], args[1])
	},
}

func removeAllRules(sgName string) error {
	sg, err := getSecurityGroupByNameOrID(sgName)
	if err != nil {
		return err
	}

	tasks := []task{}

	for _, in := range sg.IngressRule {
		tasks = append(tasks, task{&egoscale.RevokeSecurityGroupIngress{ID: in.RuleID}, fmt.Sprintf("Remove %q", in.RuleID)})
	}
	for _, eg := range sg.EgressRule {
		tasks = append(tasks, task{&egoscale.RevokeSecurityGroupEgress{ID: eg.RuleID}, fmt.Sprintf("Remove %q", eg.RuleID)})
	}

	_, errs := asyncTasks(tasks)

	if len(errs) > 0 {
		return errs[0]
	}
	return nil
}

func removeRule(name, ruleID string) error {
	sg, err := getSecurityGroupByNameOrID(name)
	if err != nil {
		return err
	}

	id, err := egoscale.ParseUUID(ruleID)
	if err != nil {
		return err
	}

	in, eg := sg.RuleByID(*id)

	if in != nil {
		err = cs.BooleanRequestWithContext(gContext, &egoscale.RevokeSecurityGroupIngress{ID: in.RuleID})
	} else if eg != nil {
		err = cs.BooleanRequestWithContext(gContext, &egoscale.RevokeSecurityGroupEgress{ID: eg.RuleID})
	} else {
		err = fmt.Errorf("rule with id %q is not ingress or egress rule", ruleID)
	}

	if err != nil {
		return err
	}

	_, err = fmt.Println(ruleID)
	return err
}

func isDefaultRule(rule, defaultRule *egoscale.IngressRule, isIpv6 bool, myCidr *egoscale.CIDR) bool {
	cidr := defaultCIDR
	if isIpv6 {
		cidr = defaultCIDR6
	}

	if myCidr != nil {
		cidr = myCidr
	}

	return (rule.StartPort == defaultRule.StartPort &&
		rule.EndPort == defaultRule.EndPort &&
		rule.CIDR == cidr &&
		rule.Protocol == defaultRule.Protocol)
}

func removeDefault(sgName, ruleName string, rule *egoscale.IngressRule, cidr *egoscale.CIDR, isIpv6 bool) error {
	sg, err := getSecurityGroupByNameOrID(sgName)
	if err != nil {
		return err
	}

	for _, in := range sg.IngressRule {
		if !isDefaultRule(&in, rule, isIpv6, cidr) {
			// Rule not found
			continue
		}

		err := cs.BooleanRequestWithContext(gContext, &egoscale.RevokeSecurityGroupIngress{ID: in.RuleID})
		if err != nil {
			return err
		}

		fmt.Println(in.RuleID)
		return nil
	}
	return fmt.Errorf("missing rule %q", ruleName)
}
<|endoftext|>


<commit_before>package c4_test

import (
	"fmt"
	"io"
	"strings"
	"testing"

	"github.com/cheekybits/is"
	"github.com/etcenter/c4go"
)

var _ io.Writer = (*c4.IDEncoder)(nil)
var _ fmt.Stringer = (*c4.ID)(nil)

func TestIDEncoder(t *testing.T) {
	is := is.New(t)
	e := c4.NewIDEncoder()
	is.OK(e)
	_, err := io.Copy(e, strings.NewReader(`This is a pretend asset file, for testing asset id generation.
`))
	is.NoErr(err)

	id := e.ID()
	is.OK(id)
	is.Equal(id.String(), `c43UBJqUTjQyrcRv43pgt1UWqysgNud7a7Kohjp1Z4w1gD8LGv4p1FK48kC8ufPPRpbEtc8inVhxuFQ453GcfRFE9d`)

}

func TestParseBytesID(t *testing.T) {
	is := is.New(t)
	e := c4.NewIDEncoder()
	is.OK(e)
	_, err := io.Copy(e, strings.NewReader(`This is a pretend asset file, for testing asset id generation.
`))
	is.NoErr(err)

	id, err := c4.ParseBytesID([]byte(`c43UBJqUTjQyrcRv43pgt1UWqysgNud7a7Kohjp1Z4w1gD8LGv4p1FK48kC8ufPPRpbEtc8inVhxuFQ453GcfRFE9d`))
	is.NoErr(err)
	is.Equal(id, e.ID())

	id2, err := c4.ParseID(`c43UBJqUTjQyrcRv43pgt1UWqysgNud7a7Kohjp1Z4w1gD8LGv4p1FK48kC8ufPPRpbEtc8inVhxuFQ453GcfRFE9d`)
	is.NoErr(err)
	is.Equal(id2, e.ID())
}
<commit_msg>added edge tests<commit_after>package c4_test

import (
	"fmt"
	"io"
	"math/big"
	"strings"
	"testing"

	"github.com/cheekybits/is"
	"github.com/etcenter/c4go"
)

var _ io.Writer = (*c4.IDEncoder)(nil)
var _ fmt.Stringer = (*c4.ID)(nil)

func encode(src io.Reader) *c4.ID {
	e := c4.NewIDEncoder()
	_, err := io.Copy(e, strings.NewReader(`This is a pretend asset file, for testing asset id generation.
`))
	if err != nil {
		panic(err)
	}
	return e.ID()
}

func TestEncoding(t *testing.T) {
	is := is.New(t)

	for _, test := range []struct {
		In  io.Reader
		Exp string
	}{
		{
			In:  strings.NewReader(``),
			Exp: "c43UBJqUTjQyrcRv43pgt1UWqysgNud7a7Kohjp1Z4w1gD8LGv4p1FK48kC8ufPPRpbEtc8inVhxuFQ453GcfRFE9d",
		},
	} {

		actual := encode(test.In)
		is.Equal(actual.String(), test.Exp)

	}

}

func TestAllFFFF(t *testing.T) {
	is := is.New(t)
	var b []byte
	for i := 0; i < 64; i++ {
		b = append(b, 0xFF)
	}
	bignum := big.NewInt(0)
	bignum = bignum.SetBytes(b)
	id := c4.ID(*bignum)
	is.Equal(id.String(), `c467RPWkcUr5dga8jgywjSup7CMoA9FNqkNjEFgAkEpF9vNktFnx77e2Js11EDL3BNu9MaKFUbacZRt1HYym4b8RNp`)

	id2, err := c4.ParseID(`c467RPWkcUr5dga8jgywjSup7CMoA9FNqkNjEFgAkEpF9vNktFnx77e2Js11EDL3BNu9MaKFUbacZRt1HYym4b8RNp`)
	is.NoErr(err)
	bignum2 := big.Int(*id2)
	b = (&bignum2).Bytes()
	for _, bb := range b {
		is.Equal(bb, 0xFF)
	}

}

func TestIDEncoder(t *testing.T) {
	is := is.New(t)
	e := c4.NewIDEncoder()
	is.OK(e)
	_, err := io.Copy(e, strings.NewReader(`This is a pretend asset file, for testing asset id generation.
`))
	is.NoErr(err)

	id := e.ID()
	is.OK(id)
	is.Equal(id.String(), `c43UBJqUTjQyrcRv43pgt1UWqysgNud7a7Kohjp1Z4w1gD8LGv4p1FK48kC8ufPPRpbEtc8inVhxuFQ453GcfRFE9d`)
}

func TestParseBytesID(t *testing.T) {
	is := is.New(t)
	e := c4.NewIDEncoder()
	is.OK(e)
	_, err := io.Copy(e, strings.NewReader(`This is a pretend asset file, for testing asset id generation.
`))
	is.NoErr(err)

	id, err := c4.ParseBytesID([]byte(`c43UBJqUTjQyrcRv43pgt1UWqysgNud7a7Kohjp1Z4w1gD8LGv4p1FK48kC8ufPPRpbEtc8inVhxuFQ453GcfRFE9d`))
	is.NoErr(err)
	is.Equal(id, e.ID())

	id2, err := c4.ParseID(`c43UBJqUTjQyrcRv43pgt1UWqysgNud7a7Kohjp1Z4w1gD8LGv4p1FK48kC8ufPPRpbEtc8inVhxuFQ453GcfRFE9d`)
	is.NoErr(err)
	is.Equal(id2, e.ID())
}
<|endoftext|>


<commit_before>/*
Copyright 2020 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 cmd

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

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"k8s.io/release/pkg/command"
	"k8s.io/release/pkg/git"
	"k8s.io/release/pkg/github"
	"k8s.io/release/pkg/release"
	"k8s.io/release/pkg/util"
)

const (
	k8sioRepo             = "k8s.io"
	promotionBranchSuffix = "-image-promotion"
)

// promoteCommand is the krel subcommand to promote conainer images
var imagePromoteCommand = &cobra.Command{
	Use:   "promote-images",
	Short: "Starts an image promotion for a tag of kubernetes images",
	Long: `krel promote

The 'promote' subcommand of krel updates the image promoter manifests
ans creates a PR in kubernetes/k8s.io`,
	SilenceUsage:  true,
	SilenceErrors: true,
	RunE: func(cmd *cobra.Command, args []string) error {
		// Run the PR creation function
		return runPromote(promoteOpts)
	},
}

type promoteOptions struct {
	userFork        string
	tag             string
	interactiveMode bool
}

func (o *promoteOptions) Validate() error {
	if o.tag == "" {
		return errors.New("cannot start promotion --tag is required")
	}
	if o.userFork == "" {
		return errors.New("cannot start promotion --fork is required")
	}

	// Check the fork slug
	if _, _, err := git.ParseRepoSlug(o.userFork); err != nil {
		return errors.Wrap(err, "checking user's fork")
	}

	// Verify we got a valid tag
	if _, err := util.TagStringToSemver(o.tag); err != nil {
		return errors.Wrapf(err, "verifying tag: %s", o.tag)
	}

	// Check that the GitHub token is set
	token, isset := os.LookupEnv(github.TokenEnvKey)
	if !isset || token == "" {
		return errors.New("cannot promote images if GitHub token is not set")
	}
	return nil
}

var promoteOpts = &promoteOptions{}

func init() {
	imagePromoteCommand.PersistentFlags().StringVarP(
		&promoteOpts.tag,
		"tag",
		"t",
		"",
		"version tag of the images we will promote",
	)

	imagePromoteCommand.PersistentFlags().StringVar(
		&promoteOpts.userFork,
		"fork",
		"",
		"the user's fork of kubernetes/k8s.io",
	)

	imagePromoteCommand.PersistentFlags().BoolVarP(
		&promoteOpts.interactiveMode,
		"interactive",
		"i",
		false,
		"interactive mode, asks before every step",
	)

	for _, flagName := range []string{"tag", "fork"} {
		if err := imagePromoteCommand.MarkPersistentFlagRequired(flagName); err != nil {
			logrus.Error(errors.Wrapf(err, "marking tag %s as required", flagName))
		}
	}

	rootCmd.AddCommand(imagePromoteCommand)
}

func runPromote(opts *promoteOptions) error {
	// Validate options
	branchname := opts.tag + promotionBranchSuffix

	// Check the cmd line opts
	if err := opts.Validate(); err != nil {
		return errors.Wrap(err, "checking command line options")
	}

	// Get the github org and repo from the fork slug
	userForkOrg, userForkRepo, err := git.ParseRepoSlug(opts.userFork)
	if err != nil {
		return errors.Wrap(err, "parsing user's fork")
	}
	if userForkRepo == "" {
		userForkRepo = k8sioRepo
	}

	// Check Environment
	gh := github.New()

	// Check for the cip-mm binary
	cipmm, err := exec.LookPath("cip-mm")
	if err != nil {
		return errors.Wrap(err, "while looking for cip-mm in your path")
	}

	// Verify the repository is a fork of k8s.io
	if err = verifyFork(
		branchname, userForkOrg, userForkRepo, git.DefaultGithubOrg, k8sioRepo,
	); err != nil {
		return errors.Wrapf(err, "while checking fork of %s/%s ", git.DefaultGithubOrg, k8sioRepo)
	}

	// Clone k8s.io
	repo, err := prepareFork(branchname, git.DefaultGithubOrg, k8sioRepo, userForkOrg, userForkRepo)
	if err != nil {
		return errors.Wrap(err, "while preparing k/k8s.io fork")
	}

	defer func() {
		if mustRun(opts, "Clean fork directory?") {
			err = repo.Cleanup()
		} else {
			logrus.Infof("All modified files will be left untouched in %s", repo.Dir())
		}
	}()

	// Path to the promoter image list
	imagesListPath := filepath.Join(
		release.GCRIOPathProd,
		"images",
		filepath.Base(release.GCRIOPathStaging),
		"images.yaml",
	)

	// Read the current manifest to check later if new images come up
	oldlist := make([]byte, 0)
	if util.Exists(filepath.Join(repo.Dir(), imagesListPath)) {
		logrus.Debug("Reading the current image promoter manifest (image list)")
		oldlist, err = ioutil.ReadFile(filepath.Join(repo.Dir(), imagesListPath))
		if err != nil {
			return errors.Wrap(err, "while reading the current promoter image list")
		}
	}

	// Run cip-mm
	if mustRun(opts, "Update the Image Promoter manifest with cip-mm?") {
		if err := command.New(
			cipmm,
			fmt.Sprintf("--base_dir=%s", filepath.Join(repo.Dir(), release.GCRIOPathProd)),
			fmt.Sprintf("--staging_repo=%s", release.GCRIOPathStaging),
			fmt.Sprintf("--filter_tag=%s", opts.tag),
		).RunSuccess(); err != nil {
			return errors.Wrap(err, "running cip-mm install in kubernetes-sigs/release-notes")
		}
	}

	// Re-write the image list without the mock images
	rawImageList, err := release.NewPromoterImageListFromFile(filepath.Join(repo.Dir(), imagesListPath))
	if err != nil {
		return errors.Wrap(err, "parsing the current manifest")
	}

	// Create a new imagelist to copy the non-mock images
	newImageList := &release.ImagePromoterImages{}

	// Copy all non mock-images:
	for _, imageData := range *rawImageList {
		if !strings.Contains(imageData.Name, "mock/") {
			*newImageList = append(*newImageList, imageData)
		}
	}

	// Write the modified manifest
	if err := newImageList.Write(filepath.Join(repo.Dir(), imagesListPath)); err != nil {
		return errors.Wrap(err, "while writing the promoter image list")
	}

	// Check if the image list was modified
	if len(oldlist) > 0 {
		logrus.Debug("Checking if the image list was modified")
		// read the newly modified manifest
		newlist, err := ioutil.ReadFile(filepath.Join(repo.Dir(), imagesListPath))
		if err != nil {
			return errors.Wrap(err, "while reading the modified manifest images list")
		}

		// If the manifest was not modified, exit now
		if string(newlist) == string(oldlist) {
			logrus.Info("No changes detected in the promoter images list, exiting without changes")
			return nil
		}
	}

	// add the modified manifest to staging
	logrus.Debugf("Adding %s to staging area", imagesListPath)
	if err := repo.Add(imagesListPath); err != nil {
		return errors.Wrap(err, "adding image manifest to staging area")
	}

	commitMessage := fmt.Sprintf("releng: Image promotion for %s", opts.tag)

	// Commit files
	logrus.Debug("Creating commit")
	if err := repo.UserCommit(commitMessage); err != nil {
		return errors.Wrapf(err, "Error creating commit in %s/%s", git.DefaultGithubOrg, k8sioRepo)
	}

	// Push to fork
	if mustRun(opts, fmt.Sprintf("Push changes to user's fork at %s/%s?", userForkOrg, userForkRepo)) {
		logrus.Infof("Pushing manifest changes to %s/%s", userForkOrg, userForkRepo)
		if err := repo.PushToRemote(userForkName, branchname); err != nil {
			return errors.Wrapf(err, "pushing %s to %s/%s", userForkName, userForkOrg, userForkRepo)
		}
	} else {
		// Exit if no push was made

		logrus.Infof("Exiting without creating a PR since changes were not pushed to %s/%s", userForkOrg, userForkRepo)
		return nil
	}

	prBody := fmt.Sprintf("Image promotion for Kubernetes %s\n", opts.tag)
	prBody += "This is an automated PR generated from `krel The Kubernetes Release Toolbox`\n\n"

	// Create the Pull Request
	if mustRun(opts, "Create pull request?") {
		pr, err := gh.CreatePullRequest(
			git.DefaultGithubOrg, k8sioRepo, git.DefaultBranch,
			fmt.Sprintf("%s:%s", userForkOrg, branchname),
			commitMessage, prBody,
		)
		if err != nil {
			return errors.Wrap(err, "creating the pull request in k/k8s.io")
		}
		logrus.Infof(
			"Successfully created PR: %s%s/%s/pull/%d",
			github.GitHubURL, git.DefaultGithubOrg, k8sioRepo, pr.GetNumber(),
		)
	}

	// Success!
	return nil
}

// mustRun avoids running when a users chooses n in interactive mode
func mustRun(opts *promoteOptions, question string) bool {
	if !opts.interactiveMode {
		return true
	}
	_, success, err := util.Ask(fmt.Sprintf("%s (Y/n)", question), "y:Y:yes|n:N:no|y", 10)
	if err != nil {
		logrus.Error(err)
		if err.(util.UserInputError).IsCtrlC() {
			os.Exit(1)
		}
		return false
	}
	if success {
		return true
	}
	return false
}
<commit_msg>Add /hold and mention releng in image promotion PR body<commit_after>/*
Copyright 2020 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 cmd

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

	"github.com/pkg/errors"
	"github.com/sirupsen/logrus"
	"github.com/spf13/cobra"
	"k8s.io/release/pkg/command"
	"k8s.io/release/pkg/git"
	"k8s.io/release/pkg/github"
	"k8s.io/release/pkg/release"
	"k8s.io/release/pkg/util"
)

const (
	k8sioRepo             = "k8s.io"
	promotionBranchSuffix = "-image-promotion"
)

// promoteCommand is the krel subcommand to promote conainer images
var imagePromoteCommand = &cobra.Command{
	Use:   "promote-images",
	Short: "Starts an image promotion for a tag of kubernetes images",
	Long: `krel promote

The 'promote' subcommand of krel updates the image promoter manifests
ans creates a PR in kubernetes/k8s.io`,
	SilenceUsage:  true,
	SilenceErrors: true,
	RunE: func(cmd *cobra.Command, args []string) error {
		// Run the PR creation function
		return runPromote(promoteOpts)
	},
}

type promoteOptions struct {
	userFork        string
	tag             string
	interactiveMode bool
}

func (o *promoteOptions) Validate() error {
	if o.tag == "" {
		return errors.New("cannot start promotion --tag is required")
	}
	if o.userFork == "" {
		return errors.New("cannot start promotion --fork is required")
	}

	// Check the fork slug
	if _, _, err := git.ParseRepoSlug(o.userFork); err != nil {
		return errors.Wrap(err, "checking user's fork")
	}

	// Verify we got a valid tag
	if _, err := util.TagStringToSemver(o.tag); err != nil {
		return errors.Wrapf(err, "verifying tag: %s", o.tag)
	}

	// Check that the GitHub token is set
	token, isset := os.LookupEnv(github.TokenEnvKey)
	if !isset || token == "" {
		return errors.New("cannot promote images if GitHub token is not set")
	}
	return nil
}

var promoteOpts = &promoteOptions{}

func init() {
	imagePromoteCommand.PersistentFlags().StringVarP(
		&promoteOpts.tag,
		"tag",
		"t",
		"",
		"version tag of the images we will promote",
	)

	imagePromoteCommand.PersistentFlags().StringVar(
		&promoteOpts.userFork,
		"fork",
		"",
		"the user's fork of kubernetes/k8s.io",
	)

	imagePromoteCommand.PersistentFlags().BoolVarP(
		&promoteOpts.interactiveMode,
		"interactive",
		"i",
		false,
		"interactive mode, asks before every step",
	)

	for _, flagName := range []string{"tag", "fork"} {
		if err := imagePromoteCommand.MarkPersistentFlagRequired(flagName); err != nil {
			logrus.Error(errors.Wrapf(err, "marking tag %s as required", flagName))
		}
	}

	rootCmd.AddCommand(imagePromoteCommand)
}

func runPromote(opts *promoteOptions) error {
	// Validate options
	branchname := opts.tag + promotionBranchSuffix

	// Check the cmd line opts
	if err := opts.Validate(); err != nil {
		return errors.Wrap(err, "checking command line options")
	}

	// Get the github org and repo from the fork slug
	userForkOrg, userForkRepo, err := git.ParseRepoSlug(opts.userFork)
	if err != nil {
		return errors.Wrap(err, "parsing user's fork")
	}
	if userForkRepo == "" {
		userForkRepo = k8sioRepo
	}

	// Check Environment
	gh := github.New()

	// Check for the cip-mm binary
	cipmm, err := exec.LookPath("cip-mm")
	if err != nil {
		return errors.Wrap(err, "while looking for cip-mm in your path")
	}

	// Verify the repository is a fork of k8s.io
	if err = verifyFork(
		branchname, userForkOrg, userForkRepo, git.DefaultGithubOrg, k8sioRepo,
	); err != nil {
		return errors.Wrapf(err, "while checking fork of %s/%s ", git.DefaultGithubOrg, k8sioRepo)
	}

	// Clone k8s.io
	repo, err := prepareFork(branchname, git.DefaultGithubOrg, k8sioRepo, userForkOrg, userForkRepo)
	if err != nil {
		return errors.Wrap(err, "while preparing k/k8s.io fork")
	}

	defer func() {
		if mustRun(opts, "Clean fork directory?") {
			err = repo.Cleanup()
		} else {
			logrus.Infof("All modified files will be left untouched in %s", repo.Dir())
		}
	}()

	// Path to the promoter image list
	imagesListPath := filepath.Join(
		release.GCRIOPathProd,
		"images",
		filepath.Base(release.GCRIOPathStaging),
		"images.yaml",
	)

	// Read the current manifest to check later if new images come up
	oldlist := make([]byte, 0)
	if util.Exists(filepath.Join(repo.Dir(), imagesListPath)) {
		logrus.Debug("Reading the current image promoter manifest (image list)")
		oldlist, err = ioutil.ReadFile(filepath.Join(repo.Dir(), imagesListPath))
		if err != nil {
			return errors.Wrap(err, "while reading the current promoter image list")
		}
	}

	// Run cip-mm
	if mustRun(opts, "Update the Image Promoter manifest with cip-mm?") {
		if err := command.New(
			cipmm,
			fmt.Sprintf("--base_dir=%s", filepath.Join(repo.Dir(), release.GCRIOPathProd)),
			fmt.Sprintf("--staging_repo=%s", release.GCRIOPathStaging),
			fmt.Sprintf("--filter_tag=%s", opts.tag),
		).RunSuccess(); err != nil {
			return errors.Wrap(err, "running cip-mm install in kubernetes-sigs/release-notes")
		}
	}

	// Re-write the image list without the mock images
	rawImageList, err := release.NewPromoterImageListFromFile(filepath.Join(repo.Dir(), imagesListPath))
	if err != nil {
		return errors.Wrap(err, "parsing the current manifest")
	}

	// Create a new imagelist to copy the non-mock images
	newImageList := &release.ImagePromoterImages{}

	// Copy all non mock-images:
	for _, imageData := range *rawImageList {
		if !strings.Contains(imageData.Name, "mock/") {
			*newImageList = append(*newImageList, imageData)
		}
	}

	// Write the modified manifest
	if err := newImageList.Write(filepath.Join(repo.Dir(), imagesListPath)); err != nil {
		return errors.Wrap(err, "while writing the promoter image list")
	}

	// Check if the image list was modified
	if len(oldlist) > 0 {
		logrus.Debug("Checking if the image list was modified")
		// read the newly modified manifest
		newlist, err := ioutil.ReadFile(filepath.Join(repo.Dir(), imagesListPath))
		if err != nil {
			return errors.Wrap(err, "while reading the modified manifest images list")
		}

		// If the manifest was not modified, exit now
		if string(newlist) == string(oldlist) {
			logrus.Info("No changes detected in the promoter images list, exiting without changes")
			return nil
		}
	}

	// add the modified manifest to staging
	logrus.Debugf("Adding %s to staging area", imagesListPath)
	if err := repo.Add(imagesListPath); err != nil {
		return errors.Wrap(err, "adding image manifest to staging area")
	}

	commitMessage := fmt.Sprintf("releng: Image promotion for %s", opts.tag)

	// Commit files
	logrus.Debug("Creating commit")
	if err := repo.UserCommit(commitMessage); err != nil {
		return errors.Wrapf(err, "Error creating commit in %s/%s", git.DefaultGithubOrg, k8sioRepo)
	}

	// Push to fork
	if mustRun(opts, fmt.Sprintf("Push changes to user's fork at %s/%s?", userForkOrg, userForkRepo)) {
		logrus.Infof("Pushing manifest changes to %s/%s", userForkOrg, userForkRepo)
		if err := repo.PushToRemote(userForkName, branchname); err != nil {
			return errors.Wrapf(err, "pushing %s to %s/%s", userForkName, userForkOrg, userForkRepo)
		}
	} else {
		// Exit if no push was made

		logrus.Infof("Exiting without creating a PR since changes were not pushed to %s/%s", userForkOrg, userForkRepo)
		return nil
	}

	prBody := fmt.Sprintf("Image promotion for Kubernetes %s\n", opts.tag)
	prBody += "This is an automated PR generated from `krel The Kubernetes Release Toolbox`\n\n"
	prBody += "/hold\ncc: @kubernetes/release-engineering\n"

	// Create the Pull Request
	if mustRun(opts, "Create pull request?") {
		pr, err := gh.CreatePullRequest(
			git.DefaultGithubOrg, k8sioRepo, git.DefaultBranch,
			fmt.Sprintf("%s:%s", userForkOrg, branchname),
			commitMessage, prBody,
		)
		if err != nil {
			return errors.Wrap(err, "creating the pull request in k/k8s.io")
		}
		logrus.Infof(
			"Successfully created PR: %s%s/%s/pull/%d",
			github.GitHubURL, git.DefaultGithubOrg, k8sioRepo, pr.GetNumber(),
		)
	}

	// Success!
	return nil
}

// mustRun avoids running when a users chooses n in interactive mode
func mustRun(opts *promoteOptions, question string) bool {
	if !opts.interactiveMode {
		return true
	}
	_, success, err := util.Ask(fmt.Sprintf("%s (Y/n)", question), "y:Y:yes|n:N:no|y", 10)
	if err != nil {
		logrus.Error(err)
		if err.(util.UserInputError).IsCtrlC() {
			os.Exit(1)
		}
		return false
	}
	if success {
		return true
	}
	return false
}
<|endoftext|>


<commit_before>/*
Copyright 2019 The Skaffold 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 cmd

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"

	"github.com/spf13/cobra"

	"github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/flags"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner"
	latest_v1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1"
)

var (
	showBuild                 bool
	renderOutputPath          string
	renderFromBuildOutputFile flags.BuildOutputFileFlag
	offline                   bool
)

// NewCmdRender describes the CLI command to build artifacts render Kubernetes manifests.
func NewCmdRender() *cobra.Command {
	return NewCmd("render").
		WithDescription("[alpha] Perform all image builds, and output rendered Kubernetes manifests").
		WithExample("Hydrate Kubernetes manifests without building the images, using digest resolved from tag in remote registry ", "render --digest-source=remote").
		WithCommonFlags().
		WithFlags([]*Flag{
			{Value: &showBuild, Name: "loud", DefValue: false, Usage: "Show the build logs and output", IsEnum: true},
			{Value: &renderFromBuildOutputFile, Name: "build-artifacts", Shorthand: "a", Usage: "File containing build result from a previous 'skaffold build --file-output'"},
			{Value: &offline, Name: "offline", DefValue: false, Usage: `Do not connect to Kubernetes API server for manifest creation and validation. This is helpful when no Kubernetes cluster is available (e.g. GitOps model). No metadata.namespace attribute is injected in this case - the manifest content does not get changed.`, IsEnum: true},
			{Value: &renderOutputPath, Name: "output", Shorthand: "o", DefValue: "", Usage: "file to write rendered manifests to"},
			{Value: &opts.DigestSource, Name: "digest-source", DefValue: "local", Usage: "Set to 'local' to build images locally and use digests from built images; Set to 'remote' to resolve the digest of images by tag from the remote registry; Set to 'none' to use tags directly from the Kubernetes manifests. Set to 'tag' to use tags directly from the build.", IsEnum: true},
		}).
		WithHouseKeepingMessages().
		NoArgs(doRender)
}

func doRender(ctx context.Context, out io.Writer) error {
	buildOut := ioutil.Discard
	if showBuild {
		buildOut = out
	}

	return withRunner(ctx, out, func(r runner.Runner, configs []*latest_v1.SkaffoldConfig) error {
		var bRes []graph.Artifact

		if renderFromBuildOutputFile.String() != "" {
			bRes = renderFromBuildOutputFile.BuildArtifacts()
		} else {
			var err error
			bRes, err = r.Build(ctx, buildOut, targetArtifacts(opts, configs))
			if err != nil {
				return fmt.Errorf("executing build: %w", err)
			}
		}

		if err := r.Render(ctx, out, bRes, offline, renderOutputPath); err != nil {
			return fmt.Errorf("rendering manifests: %w", err)
		}
		return nil
	})
}
<commit_msg>disbale housekeeping messages for render (#5770)<commit_after>/*
Copyright 2019 The Skaffold 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 cmd

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"

	"github.com/spf13/cobra"

	"github.com/GoogleContainerTools/skaffold/cmd/skaffold/app/flags"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/graph"
	"github.com/GoogleContainerTools/skaffold/pkg/skaffold/runner"
	latest_v1 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/schema/latest/v1"
)

var (
	showBuild                 bool
	renderOutputPath          string
	renderFromBuildOutputFile flags.BuildOutputFileFlag
	offline                   bool
)

// NewCmdRender describes the CLI command to build artifacts render Kubernetes manifests.
func NewCmdRender() *cobra.Command {
	return NewCmd("render").
		WithDescription("[alpha] Perform all image builds, and output rendered Kubernetes manifests").
		WithExample("Hydrate Kubernetes manifests without building the images, using digest resolved from tag in remote registry ", "render --digest-source=remote").
		WithCommonFlags().
		WithFlags([]*Flag{
			{Value: &showBuild, Name: "loud", DefValue: false, Usage: "Show the build logs and output", IsEnum: true},
			{Value: &renderFromBuildOutputFile, Name: "build-artifacts", Shorthand: "a", Usage: "File containing build result from a previous 'skaffold build --file-output'"},
			{Value: &offline, Name: "offline", DefValue: false, Usage: `Do not connect to Kubernetes API server for manifest creation and validation. This is helpful when no Kubernetes cluster is available (e.g. GitOps model). No metadata.namespace attribute is injected in this case - the manifest content does not get changed.`, IsEnum: true},
			{Value: &renderOutputPath, Name: "output", Shorthand: "o", DefValue: "", Usage: "file to write rendered manifests to"},
			{Value: &opts.DigestSource, Name: "digest-source", DefValue: "local", Usage: "Set to 'local' to build images locally and use digests from built images; Set to 'remote' to resolve the digest of images by tag from the remote registry; Set to 'none' to use tags directly from the Kubernetes manifests. Set to 'tag' to use tags directly from the build.", IsEnum: true},
		}).
		NoArgs(doRender)
}

func doRender(ctx context.Context, out io.Writer) error {
	buildOut := ioutil.Discard
	if showBuild {
		buildOut = out
	}

	return withRunner(ctx, out, func(r runner.Runner, configs []*latest_v1.SkaffoldConfig) error {
		var bRes []graph.Artifact

		if renderFromBuildOutputFile.String() != "" {
			bRes = renderFromBuildOutputFile.BuildArtifacts()
		} else {
			var err error
			bRes, err = r.Build(ctx, buildOut, targetArtifacts(opts, configs))
			if err != nil {
				return fmt.Errorf("executing build: %w", err)
			}
		}

		if err := r.Render(ctx, out, bRes, offline, renderOutputPath); err != nil {
			return fmt.Errorf("rendering manifests: %w", err)
		}
		return nil
	})
}
<|endoftext|>