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

/*
	The netchan package implements type-safe networked channels:
	it allows the two ends of a channel to appear on different
	computers connected by a network.  It does this by transporting
	data sent to a channel on one machine so it can be recovered
	by a receive of a channel of the same type on the other.

	An exporter publishes a set of channels by name.  An importer
	connects to the exporting machine and imports the channels
	by name. After importing the channels, the two machines can
	use the channels in the usual way.

	Networked channels are not synchronized; they always behave
	as if they are buffered channels of at least one element.
*/
package netchan

// BUG: can't use range clause to receive when using ImportNValues to limit the count.

import (
	"log"
	"net"
	"os"
	"reflect"
	"sync"
)

// Export

// expLog is a logging convenience function.  The first argument must be a string.
func expLog(args ...interface{}) {
	args[0] = "netchan export: " + args[0].(string)
	log.Stderr(args...)
}

// An Exporter allows a set of channels to be published on a single
// network port.  A single machine may have multiple Exporters
// but they must use different ports.
type Exporter struct {
	*clientSet
	listener net.Listener
}

type expClient struct {
	*encDec
	exp     *Exporter
	mu      sync.Mutex // protects remaining fields
	errored bool       // client has been sent an error
	seqNum  int64      // sequences messages sent to client; has value of highest sent
	ackNum  int64      // highest sequence number acknowledged
}

func newClient(exp *Exporter, conn net.Conn) *expClient {
	client := new(expClient)
	client.exp = exp
	client.encDec = newEncDec(conn)
	client.seqNum = 0
	client.ackNum = 0
	return client

}

func (client *expClient) sendError(hdr *header, err string) {
	error := &error{err}
	expLog("sending error to client:", error.error)
	client.encode(hdr, payError, error) // ignore any encode error, hope client gets it
	client.mu.Lock()
	client.errored = true
	client.mu.Unlock()
}

func (client *expClient) getChan(hdr *header, dir Dir) *chanDir {
	exp := client.exp
	exp.mu.Lock()
	ech, ok := exp.chans[hdr.name]
	exp.mu.Unlock()
	if !ok {
		client.sendError(hdr, "no such channel: "+hdr.name)
		return nil
	}
	if ech.dir != dir {
		client.sendError(hdr, "wrong direction for channel: "+hdr.name)
		return nil
	}
	return ech
}

// The function run manages sends and receives for a single client.  For each
// (client Recv) request, this will launch a serveRecv goroutine to deliver
// the data for that channel, while (client Send) requests are handled as
// data arrives from the client.
func (client *expClient) run() {
	hdr := new(header)
	hdrValue := reflect.NewValue(hdr)
	req := new(request)
	reqValue := reflect.NewValue(req)
	error := new(error)
	for {
		*hdr = header{}
		if err := client.decode(hdrValue); err != nil {
			expLog("error decoding client header:", err)
			break
		}
		switch hdr.payloadType {
		case payRequest:
			if err := client.decode(reqValue); err != nil {
				expLog("error decoding client request:", err)
				break
			}
			switch req.dir {
			case Recv:
				go client.serveRecv(*hdr, req.count)
			case Send:
				// Request to send is clear as a matter of protocol
				// but not actually used by the implementation.
				// The actual sends will have payload type payData.
				// TODO: manage the count?
			default:
				error.error = "request: can't handle channel direction"
				expLog(error.error, req.dir)
				client.encode(hdr, payError, error)
			}
		case payData:
			client.serveSend(*hdr)
		case payClosed:
			client.serveClosed(*hdr)
		case payAck:
			client.mu.Lock()
			if client.ackNum != hdr.seqNum-1 {
				// Since the sequence number is incremented and the message is sent
				// in a single instance of locking client.mu, the messages are guaranteed
				// to be sent in order.  Therefore receipt of acknowledgement N means
				// all messages <=N have been seen by the recipient.  We check anyway.
				expLog("sequence out of order:", client.ackNum, hdr.seqNum)
			}
			if client.ackNum < hdr.seqNum { // If there has been an error, don't back up the count.
				client.ackNum = hdr.seqNum
			}
			client.mu.Unlock()
		default:
			log.Exit("netchan export: unknown payload type", hdr.payloadType)
		}
	}
	client.exp.delClient(client)
}

// Send all the data on a single channel to a client asking for a Recv.
// The header is passed by value to avoid issues of overwriting.
func (client *expClient) serveRecv(hdr header, count int64) {
	ech := client.getChan(&hdr, Send)
	if ech == nil {
		return
	}
	for {
		val := ech.ch.Recv()
		if ech.ch.Closed() {
			if err := client.encode(&hdr, payClosed, nil); err != nil {
				expLog("error encoding server closed message:", err)
			}
			break
		}
		// We hold the lock during transmission to guarantee messages are
		// sent in sequence number order.  Also, we increment first so the
		// value of client.seqNum is the value of the highest used sequence
		// number, not one beyond.
		client.mu.Lock()
		client.seqNum++
		hdr.seqNum = client.seqNum
		err := client.encode(&hdr, payData, val.Interface())
		client.mu.Unlock()
		if err != nil {
			expLog("error encoding client response:", err)
			client.sendError(&hdr, err.String())
			break
		}
		// Negative count means run forever.
		if count >= 0 {
			if count--; count <= 0 {
				break
			}
		}
	}
}

// Receive and deliver locally one item from a client asking for a Send
// The header is passed by value to avoid issues of overwriting.
func (client *expClient) serveSend(hdr header) {
	ech := client.getChan(&hdr, Recv)
	if ech == nil {
		return
	}
	// Create a new value for each received item.
	val := reflect.MakeZero(ech.ch.Type().(*reflect.ChanType).Elem())
	if err := client.decode(val); err != nil {
		expLog("value decode:", err)
		return
	}
	ech.ch.Send(val)
}

// Report that client has closed the channel that is sending to us.
// The header is passed by value to avoid issues of overwriting.
func (client *expClient) serveClosed(hdr header) {
	ech := client.getChan(&hdr, Recv)
	if ech == nil {
		return
	}
	ech.ch.Close()
}

func (client *expClient) unackedCount() int64 {
	client.mu.Lock()
	n := client.seqNum - client.ackNum
	client.mu.Unlock()
	return n
}

func (client *expClient) seq() int64 {
	client.mu.Lock()
	n := client.seqNum
	client.mu.Unlock()
	return n
}

func (client *expClient) ack() int64 {
	client.mu.Lock()
	n := client.seqNum
	client.mu.Unlock()
	return n
}

// Wait for incoming connections, start a new runner for each
func (exp *Exporter) listen() {
	for {
		conn, err := exp.listener.Accept()
		if err != nil {
			expLog("listen:", err)
			break
		}
		client := exp.addClient(conn)
		go client.run()
	}
}

// NewExporter creates a new Exporter to export channels
// on the network and local address defined as in net.Listen.
func NewExporter(network, localaddr string) (*Exporter, os.Error) {
	listener, err := net.Listen(network, localaddr)
	if err != nil {
		return nil, err
	}
	e := &Exporter{
		listener: listener,
		clientSet: &clientSet{
			chans:   make(map[string]*chanDir),
			clients: make(map[unackedCounter]bool),
		},
	}
	go e.listen()
	return e, nil
}

// addClient creates a new expClient and records its existence
func (exp *Exporter) addClient(conn net.Conn) *expClient {
	client := newClient(exp, conn)
	exp.clients[client] = true
	exp.mu.Unlock()
	return client
}

// delClient forgets the client existed
func (exp *Exporter) delClient(client *expClient) {
	exp.mu.Lock()
	exp.clients[client] = false, false
	exp.mu.Unlock()
}

// Drain waits until all messages sent from this exporter/importer, including
// those not yet sent to any client and possibly including those sent while
// Drain was executing, have been received by the importer.  In short, it
// waits until all the exporter's messages have been received by a client.
// If the timeout (measured in nanoseconds) is positive and Drain takes
// longer than that to complete, an error is returned.
func (exp *Exporter) Drain(timeout int64) os.Error {
	// This wrapper function is here so the method's comment will appear in godoc.
	return exp.clientSet.drain(timeout)
}

// Sync waits until all clients of the exporter have received the messages
// that were sent at the time Sync was invoked.  Unlike Drain, it does not
// wait for messages sent while it is running or messages that have not been
// dispatched to any client.  If the timeout (measured in nanoseconds) is
// positive and Sync takes longer than that to complete, an error is
// returned.
func (exp *Exporter) Sync(timeout int64) os.Error {
	// This wrapper function is here so the method's comment will appear in godoc.
	return exp.clientSet.sync(timeout)
}

// Addr returns the Exporter's local network address.
func (exp *Exporter) Addr() net.Addr { return exp.listener.Addr() }

func checkChan(chT interface{}, dir Dir) (*reflect.ChanValue, os.Error) {
	chanType, ok := reflect.Typeof(chT).(*reflect.ChanType)
	if !ok {
		return nil, os.ErrorString("not a channel")
	}
	if dir != Send && dir != Recv {
		return nil, os.ErrorString("unknown channel direction")
	}
	switch chanType.Dir() {
	case reflect.BothDir:
	case reflect.SendDir:
		if dir != Recv {
			return nil, os.ErrorString("to import/export with Send, must provide <-chan")
		}
	case reflect.RecvDir:
		if dir != Send {
			return nil, os.ErrorString("to import/export with Recv, must provide chan<-")
		}
	}
	return reflect.NewValue(chT).(*reflect.ChanValue), nil
}

// Export exports a channel of a given type and specified direction.  The
// channel to be exported is provided in the call and may be of arbitrary
// channel type.
// Despite the literal signature, the effective signature is
//	Export(name string, chT chan T, dir Dir)
func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error {
	ch, err := checkChan(chT, dir)
	if err != nil {
		return err
	}
	exp.mu.Lock()
	defer exp.mu.Unlock()
	_, present := exp.chans[name]
	if present {
		return os.ErrorString("channel name already being exported:" + name)
	}
	exp.chans[name] = &chanDir{ch, dir}
	return nil
}
<commit_msg>netchan: zero out request to ensure correct gob decoding. Gob decoding does not overwrite fields which are zero in the encoder. Fixes issue 1174.<commit_after>// Copyright 2010 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

/*
	The netchan package implements type-safe networked channels:
	it allows the two ends of a channel to appear on different
	computers connected by a network.  It does this by transporting
	data sent to a channel on one machine so it can be recovered
	by a receive of a channel of the same type on the other.

	An exporter publishes a set of channels by name.  An importer
	connects to the exporting machine and imports the channels
	by name. After importing the channels, the two machines can
	use the channels in the usual way.

	Networked channels are not synchronized; they always behave
	as if they are buffered channels of at least one element.
*/
package netchan

// BUG: can't use range clause to receive when using ImportNValues to limit the count.

import (
	"log"
	"net"
	"os"
	"reflect"
	"sync"
)

// Export

// expLog is a logging convenience function.  The first argument must be a string.
func expLog(args ...interface{}) {
	args[0] = "netchan export: " + args[0].(string)
	log.Stderr(args...)
}

// An Exporter allows a set of channels to be published on a single
// network port.  A single machine may have multiple Exporters
// but they must use different ports.
type Exporter struct {
	*clientSet
	listener net.Listener
}

type expClient struct {
	*encDec
	exp     *Exporter
	mu      sync.Mutex // protects remaining fields
	errored bool       // client has been sent an error
	seqNum  int64      // sequences messages sent to client; has value of highest sent
	ackNum  int64      // highest sequence number acknowledged
}

func newClient(exp *Exporter, conn net.Conn) *expClient {
	client := new(expClient)
	client.exp = exp
	client.encDec = newEncDec(conn)
	client.seqNum = 0
	client.ackNum = 0
	return client

}

func (client *expClient) sendError(hdr *header, err string) {
	error := &error{err}
	expLog("sending error to client:", error.error)
	client.encode(hdr, payError, error) // ignore any encode error, hope client gets it
	client.mu.Lock()
	client.errored = true
	client.mu.Unlock()
}

func (client *expClient) getChan(hdr *header, dir Dir) *chanDir {
	exp := client.exp
	exp.mu.Lock()
	ech, ok := exp.chans[hdr.name]
	exp.mu.Unlock()
	if !ok {
		client.sendError(hdr, "no such channel: "+hdr.name)
		return nil
	}
	if ech.dir != dir {
		client.sendError(hdr, "wrong direction for channel: "+hdr.name)
		return nil
	}
	return ech
}

// The function run manages sends and receives for a single client.  For each
// (client Recv) request, this will launch a serveRecv goroutine to deliver
// the data for that channel, while (client Send) requests are handled as
// data arrives from the client.
func (client *expClient) run() {
	hdr := new(header)
	hdrValue := reflect.NewValue(hdr)
	req := new(request)
	reqValue := reflect.NewValue(req)
	error := new(error)
	for {
		*hdr = header{}
		if err := client.decode(hdrValue); err != nil {
			expLog("error decoding client header:", err)
			break
		}
		switch hdr.payloadType {
		case payRequest:
			*req = request{}
			if err := client.decode(reqValue); err != nil {
				expLog("error decoding client request:", err)
				break
			}
			switch req.dir {
			case Recv:
				go client.serveRecv(*hdr, req.count)
			case Send:
				// Request to send is clear as a matter of protocol
				// but not actually used by the implementation.
				// The actual sends will have payload type payData.
				// TODO: manage the count?
			default:
				error.error = "request: can't handle channel direction"
				expLog(error.error, req.dir)
				client.encode(hdr, payError, error)
			}
		case payData:
			client.serveSend(*hdr)
		case payClosed:
			client.serveClosed(*hdr)
		case payAck:
			client.mu.Lock()
			if client.ackNum != hdr.seqNum-1 {
				// Since the sequence number is incremented and the message is sent
				// in a single instance of locking client.mu, the messages are guaranteed
				// to be sent in order.  Therefore receipt of acknowledgement N means
				// all messages <=N have been seen by the recipient.  We check anyway.
				expLog("sequence out of order:", client.ackNum, hdr.seqNum)
			}
			if client.ackNum < hdr.seqNum { // If there has been an error, don't back up the count.
				client.ackNum = hdr.seqNum
			}
			client.mu.Unlock()
		default:
			log.Exit("netchan export: unknown payload type", hdr.payloadType)
		}
	}
	client.exp.delClient(client)
}

// Send all the data on a single channel to a client asking for a Recv.
// The header is passed by value to avoid issues of overwriting.
func (client *expClient) serveRecv(hdr header, count int64) {
	ech := client.getChan(&hdr, Send)
	if ech == nil {
		return
	}
	for {
		val := ech.ch.Recv()
		if ech.ch.Closed() {
			if err := client.encode(&hdr, payClosed, nil); err != nil {
				expLog("error encoding server closed message:", err)
			}
			break
		}
		// We hold the lock during transmission to guarantee messages are
		// sent in sequence number order.  Also, we increment first so the
		// value of client.seqNum is the value of the highest used sequence
		// number, not one beyond.
		client.mu.Lock()
		client.seqNum++
		hdr.seqNum = client.seqNum
		err := client.encode(&hdr, payData, val.Interface())
		client.mu.Unlock()
		if err != nil {
			expLog("error encoding client response:", err)
			client.sendError(&hdr, err.String())
			break
		}
		// Negative count means run forever.
		if count >= 0 {
			if count--; count <= 0 {
				break
			}
		}
	}
}

// Receive and deliver locally one item from a client asking for a Send
// The header is passed by value to avoid issues of overwriting.
func (client *expClient) serveSend(hdr header) {
	ech := client.getChan(&hdr, Recv)
	if ech == nil {
		return
	}
	// Create a new value for each received item.
	val := reflect.MakeZero(ech.ch.Type().(*reflect.ChanType).Elem())
	if err := client.decode(val); err != nil {
		expLog("value decode:", err)
		return
	}
	ech.ch.Send(val)
}

// Report that client has closed the channel that is sending to us.
// The header is passed by value to avoid issues of overwriting.
func (client *expClient) serveClosed(hdr header) {
	ech := client.getChan(&hdr, Recv)
	if ech == nil {
		return
	}
	ech.ch.Close()
}

func (client *expClient) unackedCount() int64 {
	client.mu.Lock()
	n := client.seqNum - client.ackNum
	client.mu.Unlock()
	return n
}

func (client *expClient) seq() int64 {
	client.mu.Lock()
	n := client.seqNum
	client.mu.Unlock()
	return n
}

func (client *expClient) ack() int64 {
	client.mu.Lock()
	n := client.seqNum
	client.mu.Unlock()
	return n
}

// Wait for incoming connections, start a new runner for each
func (exp *Exporter) listen() {
	for {
		conn, err := exp.listener.Accept()
		if err != nil {
			expLog("listen:", err)
			break
		}
		client := exp.addClient(conn)
		go client.run()
	}
}

// NewExporter creates a new Exporter to export channels
// on the network and local address defined as in net.Listen.
func NewExporter(network, localaddr string) (*Exporter, os.Error) {
	listener, err := net.Listen(network, localaddr)
	if err != nil {
		return nil, err
	}
	e := &Exporter{
		listener: listener,
		clientSet: &clientSet{
			chans:   make(map[string]*chanDir),
			clients: make(map[unackedCounter]bool),
		},
	}
	go e.listen()
	return e, nil
}

// addClient creates a new expClient and records its existence
func (exp *Exporter) addClient(conn net.Conn) *expClient {
	client := newClient(exp, conn)
	exp.clients[client] = true
	exp.mu.Unlock()
	return client
}

// delClient forgets the client existed
func (exp *Exporter) delClient(client *expClient) {
	exp.mu.Lock()
	exp.clients[client] = false, false
	exp.mu.Unlock()
}

// Drain waits until all messages sent from this exporter/importer, including
// those not yet sent to any client and possibly including those sent while
// Drain was executing, have been received by the importer.  In short, it
// waits until all the exporter's messages have been received by a client.
// If the timeout (measured in nanoseconds) is positive and Drain takes
// longer than that to complete, an error is returned.
func (exp *Exporter) Drain(timeout int64) os.Error {
	// This wrapper function is here so the method's comment will appear in godoc.
	return exp.clientSet.drain(timeout)
}

// Sync waits until all clients of the exporter have received the messages
// that were sent at the time Sync was invoked.  Unlike Drain, it does not
// wait for messages sent while it is running or messages that have not been
// dispatched to any client.  If the timeout (measured in nanoseconds) is
// positive and Sync takes longer than that to complete, an error is
// returned.
func (exp *Exporter) Sync(timeout int64) os.Error {
	// This wrapper function is here so the method's comment will appear in godoc.
	return exp.clientSet.sync(timeout)
}

// Addr returns the Exporter's local network address.
func (exp *Exporter) Addr() net.Addr { return exp.listener.Addr() }

func checkChan(chT interface{}, dir Dir) (*reflect.ChanValue, os.Error) {
	chanType, ok := reflect.Typeof(chT).(*reflect.ChanType)
	if !ok {
		return nil, os.ErrorString("not a channel")
	}
	if dir != Send && dir != Recv {
		return nil, os.ErrorString("unknown channel direction")
	}
	switch chanType.Dir() {
	case reflect.BothDir:
	case reflect.SendDir:
		if dir != Recv {
			return nil, os.ErrorString("to import/export with Send, must provide <-chan")
		}
	case reflect.RecvDir:
		if dir != Send {
			return nil, os.ErrorString("to import/export with Recv, must provide chan<-")
		}
	}
	return reflect.NewValue(chT).(*reflect.ChanValue), nil
}

// Export exports a channel of a given type and specified direction.  The
// channel to be exported is provided in the call and may be of arbitrary
// channel type.
// Despite the literal signature, the effective signature is
//	Export(name string, chT chan T, dir Dir)
func (exp *Exporter) Export(name string, chT interface{}, dir Dir) os.Error {
	ch, err := checkChan(chT, dir)
	if err != nil {
		return err
	}
	exp.mu.Lock()
	defer exp.mu.Unlock()
	_, present := exp.chans[name]
	if present {
		return os.ErrorString("channel name already being exported:" + name)
	}
	exp.chans[name] = &chanDir{ch, dir}
	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"bufio"
	"flag"
	"fmt"
	"math"
	"os"
	"strconv"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/gizak/termui"
)

var (
	colorForeground = termui.ColorWhite
)

// TODO:
// - Different chart types
// - Check sizing

func drawTermChart(label []string, data []int) {
	// Determine width of chart
	dataPoints := len(data)
	barWidth := 4
	barGap := 1
	width := (barWidth * dataPoints) + (barGap * (dataPoints - 2))
	termWidth := termui.TermWidth()
	termHeight := termui.TermHeight()

	// If we can fit it all in one screen
	if width < termWidth {
		bc := termui.NewBarChart()
		bc.Data = data
		bc.Height = termHeight
		bc.Width = termWidth
		bc.BarWidth = barWidth
		bc.BarGap = barGap
		bc.DataLabels = label
		bc.TextColor = colorForeground
		bc.BarColor = termui.ColorBlue
		bc.NumColor = colorForeground
		termui.Body.AddRows(
			termui.NewRow(
				termui.NewCol(12, 0, bc),
			))
	} else {
		requiredCharts := int(math.Ceil(float64(width) / 200.0))
		var datas = make([][]int, requiredCharts)
		var labels = make([][]string, requiredCharts)
		// Split the data
		for i := 0; i < dataPoints; i++ {
			chartNo := (i % requiredCharts)
			datas[chartNo] = append(datas[chartNo], data[i])
			labels[chartNo] = append(labels[chartNo], label[i])
		}
		// Create the charts
		barCharts := make([]termui.Bufferer, requiredCharts)
		for z := 0; z < requiredCharts; z++ {
			bc := termui.NewBarChart()
			bclabels := labels[z]
			bc.Data = datas[z]
			bc.Height = termHeight / requiredCharts
			bc.BarWidth = int(float64(barWidth) * 1.5)
			bc.BarGap = barGap
			bc.DataLabels = bclabels
			bc.TextColor = colorForeground
			bc.BarColor = termui.ColorBlue
			bc.NumColor = colorForeground
			bc.SetY(z * 30)
			barCharts[z] = bc
			termui.Body.AddRows(
				termui.NewRow(
					termui.NewCol(12, 0, bc),
				),
			)
		}
	}
	termui.Body.Align()
	termui.Render(termui.Body)

}

func tryDetectDelimeter(l string) string {
	var bd string
	md := 0
	ds := []string{",", "|", "\t", "."}
	for _, d := range ds {
		c := strings.Split(l, d)
		if len(c) > md {
			md = len(c)
			bd = d
		}
	}
	return bd
}

func tryDetectColTypes(l string, d string) []string {
	cols := strings.Split(l, d)
	colTypes := make([]string, len(cols))
	for i, col := range cols {
		_, err := strconv.ParseInt(col, 10, 64)
		if err == nil {
			colTypes[i] = "int"
			continue
		}
		_, err = strconv.ParseFloat(col, 10)
		if err == nil {
			colTypes[i] = "float"
			continue
		}
		_, err = strconv.ParseBool(col)
		if err == nil {
			colTypes[i] = "bool"
			continue
		}
		colTypes[i] = "string"
	}
	return colTypes
}

func mustParseFlags() {
	var theme string
	flag.StringVar(&theme, "theme", "dark", "color theme to use; one of: light, dark")
	flag.Parse()
	if theme != "light" && theme != "dark" {
		log.WithFields(log.Fields{"value": theme}).Fatal("unsupported theme name")
	}

	if theme == "light" {
		colorForeground = termui.ColorBlack
	}
}

func main() {
	log.SetFormatter(&log.JSONFormatter{})
	var (
		data   []int
		labels []string
		delim  string
		rows   int
	)
	mustParseFlags()
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()
		if line == "" {
			break
		}
		if rows == 0 {
			delim = tryDetectDelimeter(line)
		}
		values := strings.Split(line, delim)
		intVal, err := strconv.ParseInt(values[1], 10, 64)
		if err != nil {
			log.WithField("value", values[1]).Fatal("Failed to convert input data to int")
		}
		labels = append(labels, values[0])
		data = append(data, int(intVal))
		rows++
	}
	if err := termui.Init(); err != nil {
		log.WithField("value", err).Fatal("Failed to start termui")
	}
	defer termui.Close()

	termui.Handle("/sys/kbd/q", func(termui.Event) {
		fmt.Println("Trying to kill")
		termui.StopLoop()
	})
	drawTermChart(labels, data)
	termui.Loop()

}
<commit_msg>Adding handlers to kill termchart based on C-x/d/c<commit_after>package main

import (
	"bufio"
	"flag"
	"math"
	"os"
	"strconv"
	"strings"

	log "github.com/Sirupsen/logrus"
	"github.com/gizak/termui"
)

var (
	colorForeground = termui.ColorWhite
)

// TODO:
// - Different chart types
// - Check sizing

func drawTermChart(label []string, data []int) {
	// Determine width of chart
	dataPoints := len(data)
	barWidth := 4
	barGap := 1
	width := (barWidth * dataPoints) + (barGap * (dataPoints - 2))
	termWidth := termui.TermWidth()
	termHeight := termui.TermHeight()

	// If we can fit it all in one screen
	if width < termWidth {
		bc := termui.NewBarChart()
		bc.Data = data
		bc.Height = termHeight
		bc.Width = termWidth
		bc.BarWidth = barWidth
		bc.BarGap = barGap
		bc.DataLabels = label
		bc.TextColor = colorForeground
		bc.BarColor = termui.ColorBlue
		bc.NumColor = colorForeground
		termui.Body.AddRows(
			termui.NewRow(
				termui.NewCol(12, 0, bc),
			))
	} else {
		requiredCharts := int(math.Ceil(float64(width) / 200.0))
		var datas = make([][]int, requiredCharts)
		var labels = make([][]string, requiredCharts)
		// Split the data
		for i := 0; i < dataPoints; i++ {
			chartNo := (i % requiredCharts)
			datas[chartNo] = append(datas[chartNo], data[i])
			labels[chartNo] = append(labels[chartNo], label[i])
		}
		// Create the charts
		barCharts := make([]termui.Bufferer, requiredCharts)
		for z := 0; z < requiredCharts; z++ {
			bc := termui.NewBarChart()
			bclabels := labels[z]
			bc.Data = datas[z]
			bc.Height = termHeight / requiredCharts
			bc.BarWidth = int(float64(barWidth) * 1.5)
			bc.BarGap = barGap
			bc.DataLabels = bclabels
			bc.TextColor = colorForeground
			bc.BarColor = termui.ColorBlue
			bc.NumColor = colorForeground
			bc.SetY(z * 30)
			barCharts[z] = bc
			termui.Body.AddRows(
				termui.NewRow(
					termui.NewCol(12, 0, bc),
				),
			)
		}
	}
	termui.Body.Align()
	termui.Render(termui.Body)

}

func tryDetectDelimeter(l string) string {
	var bd string
	md := 0
	ds := []string{",", "|", "\t", "."}
	for _, d := range ds {
		c := strings.Split(l, d)
		if len(c) > md {
			md = len(c)
			bd = d
		}
	}
	return bd
}

func tryDetectColTypes(l string, d string) []string {
	cols := strings.Split(l, d)
	colTypes := make([]string, len(cols))
	for i, col := range cols {
		_, err := strconv.ParseInt(col, 10, 64)
		if err == nil {
			colTypes[i] = "int"
			continue
		}
		_, err = strconv.ParseFloat(col, 10)
		if err == nil {
			colTypes[i] = "float"
			continue
		}
		_, err = strconv.ParseBool(col)
		if err == nil {
			colTypes[i] = "bool"
			continue
		}
		colTypes[i] = "string"
	}
	return colTypes
}

func mustParseFlags() {
	var theme string
	flag.StringVar(&theme, "theme", "dark", "color theme to use; one of: light, dark")
	flag.Parse()
	if theme != "light" && theme != "dark" {
		log.WithFields(log.Fields{"value": theme}).Fatal("unsupported theme name")
	}

	if theme == "light" {
		colorForeground = termui.ColorBlack
	}
}

func main() {
	log.SetFormatter(&log.JSONFormatter{})
	var (
		data   []int
		labels []string
		delim  string
		rows   int
	)
	mustParseFlags()
	scanner := bufio.NewScanner(os.Stdin)
	for scanner.Scan() {
		line := scanner.Text()
		if line == "" {
			break
		}
		if rows == 0 {
			delim = tryDetectDelimeter(line)
		}
		values := strings.Split(line, delim)
		intVal, err := strconv.ParseInt(values[1], 10, 64)
		if err != nil {
			log.WithField("value", values[1]).Fatal("Failed to convert input data to int")
		}
		labels = append(labels, values[0])
		data = append(data, int(intVal))
		rows++
	}
	if err := termui.Init(); err != nil {
		log.WithField("value", err).Fatal("Failed to start termui")
	}
	defer termui.Close()

	// Handlers
	termui.Handle("/sys/kbd/q", func(termui.Event) {
		termui.StopLoop()
	})

	termui.Handle("/sys/kbd/C-c", func(termui.Event) {
		termui.StopLoop()
	})

	termui.Handle("/sys/kbd/C-d", func(termui.Event) {
		termui.StopLoop()
	})
	termui.Handle("/sys/kbd/C-x", func(termui.Event) {
		termui.StopLoop()
	})
	termui.Handle("/sys/wnd/resize", func(e termui.Event) {
		termui.Body.Width = termui.TermWidth()
		termui.Body.Align()
		termui.Clear()
		termui.Render(termui.Body)
	})

	drawTermChart(labels, data)
	termui.Loop()

}
<|endoftext|>


<commit_before>package server

import (
	"fmt"
	"time"
)

type CreateReq struct {
	Name                   string `valid:"required"`
	Description            string `json:",omitempty"`
	GroupId                string
	GroupName              string `json:",omitempty"`
	SourceServerId         string
	TemplateId             string
	TemplateName           string           `json:",omitempty"`
	IsManagedOS            bool             `json:",omitempty"`
	PrimaryDns             string           `json:",omitempty"`
	SecondaryDns           string           `json:",omitempty"`
	NetworkId              string           `json:",omitempty"`
	IpAddress              string           `json:",omitempty"`
	RootPassword           string           `json:",omitempty"`
	SourceServerPassword   string           `json:",omitempty"`
	Cpu                    int64            `valid:"required"`
	CpuAutoscalePolicyId   string           `json:",omitempty"`
	MemoryGB               int64            `valid:"required"`
	Type                   string           `valid:"required" oneOf:"standard,hyperscale,bareMetal"`
	StorageType            string           `json:",omitempty" oneOf:"standard,premium,hyperscale"`
	AntiAffinityPolicyId   string           `json:",omitempty"`
	AntiAffinityPolicyName string           `json:",omitempty"`
	CustomFields           []CustomFieldDef `json:",omitempty"`
	AdditionalDisks        []AddDiskRequest `json:",omitempty"`
	Ttl                    time.Time        `json:",omitempty"`
	Packages               []PackageDef     `json:",omitempty"`
	ConfigurationId        string           `json:",omitempty"`
	OsType                 string           `json:",omitempty"`
}

func (c *CreateReq) Validate() error {
	serverIdValues := []string{c.SourceServerId, c.TemplateId, c.TemplateName}
	numNonEmpty := 0
	for _, item := range serverIdValues {
		if item != "" {
			numNonEmpty++
		}
	}
	if numNonEmpty > 1 || numNonEmpty == 0 {
		return fmt.Errorf("Exactly one parameter from the following: source-server-id, source-server-name, template-id, template-name must be specified.")
	}

	if (c.GroupName == "") == (c.GroupId == "") {
		return fmt.Errorf("Exactly one parameter from the following: group-id, group-name must be specified.")
	}

	if c.Type == "bareMetal" {
		if c.ConfigurationId == "" {
			return fmt.Errorf("ConfigurationId: required for bare metal servers.")
		}
		if c.OsType == "" {
			return fmt.Errorf("OsType: required for bare metal servers.")
		}
	}

	return nil
}

func (c *CreateReq) ApplyDefaultBehaviour() error {
	if c.TemplateId != "" {
		c.SourceServerId = c.TemplateId
	}
	return nil
	//TODO: implement searching templates by name
	//TODO: implement searching groups by names
}
<commit_msg>Add some hacks to pass over the time marshalling problem<commit_after>package server

import (
	"fmt"
	"time"
)

const (
	timeFormat = "2006-01-02 15:04:05"
)

type CreateReq struct {
	Name                   string `valid:"required"`
	Description            string `json:",omitempty"`
	GroupId                string
	GroupName              string `json:",omitempty"`
	SourceServerId         string
	TemplateId             string
	TemplateName           string           `json:",omitempty"`
	IsManagedOS            bool             `json:",omitempty"`
	PrimaryDns             string           `json:",omitempty"`
	SecondaryDns           string           `json:",omitempty"`
	NetworkId              string           `json:",omitempty"`
	IpAddress              string           `json:",omitempty"`
	RootPassword           string           `json:",omitempty"`
	SourceServerPassword   string           `json:",omitempty"`
	Cpu                    int64            `valid:"required"`
	CpuAutoscalePolicyId   string           `json:",omitempty"`
	MemoryGB               int64            `valid:"required"`
	Type                   string           `valid:"required" oneOf:"standard,hyperscale,bareMetal"`
	StorageType            string           `json:",omitempty" oneOf:"standard,premium,hyperscale"`
	AntiAffinityPolicyId   string           `json:",omitempty"`
	AntiAffinityPolicyName string           `json:",omitempty"`
	CustomFields           []CustomFieldDef `json:",omitempty"`
	AdditionalDisks        []AddDiskRequest `json:",omitempty"`
	Ttl                    time.Time        `json:"-"`
	TtlString              string           `json:"Ttl,omitempty"`
	Packages               []PackageDef     `json:",omitempty"`
	ConfigurationId        string           `json:",omitempty"`
	OsType                 string           `json:",omitempty"`
}

func (c *CreateReq) Validate() error {
	serverIdValues := []string{c.SourceServerId, c.TemplateId, c.TemplateName}
	numNonEmpty := 0
	for _, item := range serverIdValues {
		if item != "" {
			numNonEmpty++
		}
	}
	if numNonEmpty > 1 || numNonEmpty == 0 {
		return fmt.Errorf("Exactly one parameter from the following: source-server-id, source-server-name, template-id, template-name must be specified.")
	}

	if (c.GroupName == "") == (c.GroupId == "") {
		return fmt.Errorf("Exactly one parameter from the following: group-id, group-name must be specified.")
	}

	if c.Type == "bareMetal" {
		if c.ConfigurationId == "" {
			return fmt.Errorf("ConfigurationId: required for bare metal servers.")
		}
		if c.OsType == "" {
			return fmt.Errorf("OsType: required for bare metal servers.")
		}
	}

	return nil
}

func (c *CreateReq) ApplyDefaultBehaviour() error {
	if c.TemplateId != "" {
		c.SourceServerId = c.TemplateId
	}

	zeroTime := time.Time{}
	if c.Ttl != zeroTime {
		c.TtlString = c.Ttl.Format(timeFormat)
	}
	return nil

	//TODO: implement searching templates by name
	//TODO: implement searching groups by names
}
<|endoftext|>


<commit_before>// Copyright 2014 mqant Author. All Rights Reserved.
//
// 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 mqtt

import (
	"bufio"
	"fmt"
	"github.com/juju/errors"
	"github.com/liangdas/mqant/conf"
	"github.com/liangdas/mqant/log"
	"github.com/liangdas/mqant/network"
	"runtime"
	"time"
)

// Tcp write queue
type PackQueue struct {
	conf conf.Mqtt
	// The last error in the tcp connection
	writeError error
	// Notice read the error
	errorChan chan error
	noticeFin chan byte
	writeChan chan *packAndType
	readChan  chan<- *packAndErr
	// Pack connection
	r *bufio.Reader
	w *bufio.Writer

	conn network.Conn

	alive int
}

type packAndErr struct {
	pack *Pack
	err  error
}

// 1 is delay, 0 is no delay, 2 is just flush.
const (
	NO_DELAY = iota
	DELAY
	FLUSH
)

type packAndType struct {
	pack *Pack
	typ  byte
}

// Init a pack queue
func NewPackQueue(conf conf.Mqtt, r *bufio.Reader, w *bufio.Writer, conn network.Conn, readChan chan<- *packAndErr, alive int) *PackQueue {
	if alive < 1 {
		alive = conf.ReadTimeout
	}
	alive = int(float32(alive)*1.5 + 1)
	return &PackQueue{
		conf:      conf,
		alive:     alive,
		r:         r,
		w:         w,
		conn:      conn,
		noticeFin: make(chan byte, 2),
		writeChan: make(chan *packAndType, conf.WirteLoopChanNum),
		readChan:  readChan,
		errorChan: make(chan error, 1),
	}
}

// Start a pack write queue
// It should run in a new grountine
func (queue *PackQueue) writeLoop() {
	defer func() {
		if r := recover(); r != nil {
			buf := make([]byte, 1024)
			l := runtime.Stack(buf, false)
			errstr := string(buf[:l])
			queue.writeError = errors.New(errstr)
			queue.errorChan <- errors.New(errstr)
			queue.noticeFin <- 0
		}

	}()
	var err error
loop:
	for {
		select {
		case pt, ok := <-queue.writeChan:
			if !ok {
				break loop
			}
			if pt == nil {
				break loop
			}
			if queue.conf.WriteTimeout > 0 {
				queue.conn.SetWriteDeadline(time.Now().Add(time.Second * time.Duration(queue.conf.WriteTimeout)))
			}
			switch pt.typ {
			case NO_DELAY:
				err = WritePack(pt.pack, queue.w)
			case DELAY:
				err = DelayWritePack(pt.pack, queue.w)
			case FLUSH:
				err = queue.w.Flush()
			}

			if err != nil {
				// Tell listener the error
				// Notice the read
				queue.writeError = err
				queue.errorChan <- err
				queue.noticeFin <- 0
				break loop
			}
		}
	}
}

// Write a pack , and get the last error
func (queue *PackQueue) WritePack(pack *Pack) error {
	if queue.writeError != nil {
		return queue.writeError
	}
	select {
	case queue.writeChan <- &packAndType{pack: pack}:
		//do nothing
	default:
		//warnning!
		return fmt.Errorf("write_channel is full!")
	}
	return nil
}

func (queue *PackQueue) WriteDelayPack(pack *Pack) error {
	if queue.writeError != nil {
		return queue.writeError
	}
	queue.writeChan <- &packAndType{
		pack: pack,
		typ:  DELAY,
	}
	return nil
}

func (queue *PackQueue) SetAlive(alive int) error {
	if alive < 1 {
		alive = queue.conf.ReadTimeout
	}
	alive = int(float32(alive)*1.5 + 1)
	queue.alive = alive
	return nil
}

func (queue *PackQueue) Flush() error {
	if queue.writeError != nil {
		return queue.writeError
	}
	queue.writeChan <- &packAndType{typ: FLUSH}
	return nil
}

// Read a pack and retuen the write queue error
//func (queue *PackQueue) ReadPack() (pack *mqtt.Pack, err error) {
//	ch := make(chan *packAndErr, 1)
//	go func() {
//		p := new(packAndErr)
//		if Conf.ReadTimeout > 0 {
//			queue.conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(Conf.ReadTimeout)))
//		}
//		p.pack, p.err = mqtt.ReadPack(queue.r)
//		ch <- p
//	}()
//	select {
//	case err = <-queue.errorChan:
//		// Hava an error
//		// pass
//	case pAndErr := <-ch:
//		pack = pAndErr.pack
//		err = pAndErr.err
//	}
//	return
//}

// Get a read pack queue
// Only call once
func (queue *PackQueue) ReadPackInLoop() {

	go func() {
		// defer recover()
		is_continue := true
		p := new(packAndErr)
	loop:
		for {
			if queue.alive > 0 {
				queue.conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(int(float64(queue.alive)*1.5))))
			} else {
				queue.conn.SetReadDeadline(time.Now().Add(time.Second * 90))
			}
			if is_continue {
				p.pack, p.err = ReadPack(queue.r)
				if p.err != nil {
					is_continue = false
					break loop
				}
				select {
				case queue.readChan <- p:
					// Without anything to do
				case <-queue.noticeFin:
					//queue.Close()
					log.Info("Queue FIN")
					break loop
				}
			} else {
				<-queue.noticeFin
				//
				log.Info("Queue not continue")
				break loop
			}

			p = new(packAndErr)
		}
		queue.Close()
	}()
}

// Close the all of queue's channels
func (queue *PackQueue) Close() error {
	close(queue.writeChan)
	close(queue.readChan)
	close(queue.errorChan)
	close(queue.noticeFin)
	return nil
}

// Buffer
type buffer struct {
	index int
	data  []byte
}

func newBuffer(data []byte) *buffer {
	return &buffer{
		data:  data,
		index: 0,
	}
}
func (b *buffer) readString(length int) (s string, err error) {
	if (length + b.index) > len(b.data) {
		err = fmt.Errorf("Out of range error:%v", length)
		return
	}
	s = string(b.data[b.index:(length + b.index)])
	b.index += length
	return
}
func (b *buffer) readByte() (c byte, err error) {
	if (1 + b.index) > len(b.data) {
		err = fmt.Errorf("Out of range error")
		return
	}
	c = b.data[b.index]
	b.index++
	return
}
<commit_msg>=v1.8.0<commit_after>// Copyright 2014 mqant Author. All Rights Reserved.
//
// 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 mqtt

import (
	"bufio"
	"fmt"
	"github.com/juju/errors"
	"github.com/liangdas/mqant/conf"
	"github.com/liangdas/mqant/log"
	"github.com/liangdas/mqant/network"
	"runtime"
	"time"
)

// Tcp write queue
type PackQueue struct {
	conf conf.Mqtt
	// The last error in the tcp connection
	writeError error
	// Notice read the error
	errorChan chan error
	noticeFin chan byte
	writeChan chan *packAndType
	readChan  chan<- *packAndErr
	// Pack connection
	r *bufio.Reader
	w *bufio.Writer

	conn network.Conn

	alive int
}

type packAndErr struct {
	pack *Pack
	err  error
}

// 1 is delay, 0 is no delay, 2 is just flush.
const (
	NO_DELAY = iota
	DELAY
	FLUSH
)

type packAndType struct {
	pack *Pack
	typ  byte
}

// Init a pack queue
func NewPackQueue(conf conf.Mqtt, r *bufio.Reader, w *bufio.Writer, conn network.Conn, readChan chan<- *packAndErr, alive int) *PackQueue {
	if alive < 1 {
		alive = conf.ReadTimeout
	}
	alive = int(float32(alive)*1.5 + 1)
	return &PackQueue{
		conf:      conf,
		alive:     alive,
		r:         r,
		w:         w,
		conn:      conn,
		noticeFin: make(chan byte, 2),
		writeChan: make(chan *packAndType, conf.WirteLoopChanNum),
		readChan:  readChan,
		errorChan: make(chan error, 1),
	}
}

// Start a pack write queue
// It should run in a new grountine
func (queue *PackQueue) writeLoop() {
	defer func() {
		if r := recover(); r != nil {
			buf := make([]byte, 1024)
			l := runtime.Stack(buf, false)
			errstr := string(buf[:l])
			queue.writeError = errors.New(errstr)
			queue.errorChan <- errors.New(errstr)
			queue.noticeFin <- 0
		}

	}()
	var err error
loop:
	for {
		select {
		case pt, ok := <-queue.writeChan:
			if !ok {
				break loop
			}
			if pt == nil {
				break loop
			}
			if queue.conf.WriteTimeout > 0 {
				queue.conn.SetWriteDeadline(time.Now().Add(time.Second * time.Duration(queue.conf.WriteTimeout)))
			}
			switch pt.typ {
			case NO_DELAY:
				err = WritePack(pt.pack, queue.w)
			case DELAY:
				err = DelayWritePack(pt.pack, queue.w)
			case FLUSH:
				err = queue.w.Flush()
			}

			if err != nil {
				// Tell listener the error
				// Notice the read
				queue.writeError = err
				queue.errorChan <- err
				queue.noticeFin <- 0
				break loop
			}
		}
	}
	log.Info("write_loop Groutine will esc.")
}

// Write a pack , and get the last error
func (queue *PackQueue) WritePack(pack *Pack) error {
	if queue.writeError != nil {
		return queue.writeError
	}
	select {
	case queue.writeChan <- &packAndType{pack: pack}:
		//do nothing
	default:
		//warnning!
		return fmt.Errorf("write_channel is full!")
	}
	return nil
}

func (queue *PackQueue) WriteDelayPack(pack *Pack) error {
	if queue.writeError != nil {
		return queue.writeError
	}
	queue.writeChan <- &packAndType{
		pack: pack,
		typ:  DELAY,
	}
	return nil
}

func (queue *PackQueue) SetAlive(alive int) error {
	if alive < 1 {
		alive = queue.conf.ReadTimeout
	}
	alive = int(float32(alive)*1.5 + 1)
	queue.alive = alive
	return nil
}

func (queue *PackQueue) Flush() error {
	if queue.writeError != nil {
		return queue.writeError
	}
	queue.writeChan <- &packAndType{typ: FLUSH}
	return nil
}

// Read a pack and retuen the write queue error
//func (queue *PackQueue) ReadPack() (pack *mqtt.Pack, err error) {
//	ch := make(chan *packAndErr, 1)
//	go func() {
//		p := new(packAndErr)
//		if Conf.ReadTimeout > 0 {
//			queue.conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(Conf.ReadTimeout)))
//		}
//		p.pack, p.err = mqtt.ReadPack(queue.r)
//		ch <- p
//	}()
//	select {
//	case err = <-queue.errorChan:
//		// Hava an error
//		// pass
//	case pAndErr := <-ch:
//		pack = pAndErr.pack
//		err = pAndErr.err
//	}
//	return
//}

// Get a read pack queue
// Only call once
func (queue *PackQueue) ReadPackInLoop() {

	go func() {
		// defer recover()
		is_continue := true
		p := new(packAndErr)
	loop:
		for {
			if queue.alive > 0 {
				queue.conn.SetReadDeadline(time.Now().Add(time.Second * time.Duration(int(float64(queue.alive)*1.5))))
			} else {
				queue.conn.SetReadDeadline(time.Now().Add(time.Second * 90))
			}
			if is_continue {
				p.pack, p.err = ReadPack(queue.r)
				if p.err != nil {
					is_continue = false
					break loop
				}
				select {
				case queue.readChan <- p:
					// Without anything to do
				case <-queue.noticeFin:
					//queue.Close()
					break loop
				}
			} else {
				<-queue.noticeFin
				break loop
			}

			p = new(packAndErr)
		}
		queue.Close()
		log.Info("read_loop Groutine will esc.")
	}()
}

// Close the all of queue's channels
func (queue *PackQueue) Close() error {
	close(queue.writeChan)
	close(queue.readChan)
	close(queue.errorChan)
	close(queue.noticeFin)
	return nil
}

// Buffer
type buffer struct {
	index int
	data  []byte
}

func newBuffer(data []byte) *buffer {
	return &buffer{
		data:  data,
		index: 0,
	}
}
func (b *buffer) readString(length int) (s string, err error) {
	if (length + b.index) > len(b.data) {
		err = fmt.Errorf("Out of range error:%v", length)
		return
	}
	s = string(b.data[b.index:(length + b.index)])
	b.index += length
	return
}
func (b *buffer) readByte() (c byte, err error) {
	if (1 + b.index) > len(b.data) {
		err = fmt.Errorf("Out of range error")
		return
	}
	c = b.data[b.index]
	b.index++
	return
}
<|endoftext|>


<commit_before>// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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 gcsutil

import (
	"strings"

	"github.com/jacobsa/gcloud/gcs"
	"golang.org/x/net/context"
)

// Create an object with the supplied contents in the given bucket with the
// given name.
func CreateObject(
	ctx context.Context,
	bucket gcs.Bucket,
	name string,
	contents string) (*Object, error) {
	req := &gcs.CreateObjectRequest{
		Name:     name,
		Contents: strings.NewReader(contents),
	}

	return bucket.CreateObject(ctx, req)
}
<commit_msg>Fixed create_object.go.<commit_after>// Copyright 2015 Google Inc. All Rights Reserved.
//
// 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 gcsutil

import (
	"strings"

	"github.com/jacobsa/gcloud/gcs"
	"golang.org/x/net/context"
)

// Create an object with the supplied contents in the given bucket with the
// given name.
func CreateObject(
	ctx context.Context,
	bucket gcs.Bucket,
	name string,
	contents string) (*gcs.Object, error) {
	req := &gcs.CreateObjectRequest{
		Name:     name,
		Contents: strings.NewReader(contents),
	}

	return bucket.CreateObject(ctx, req)
}
<|endoftext|>


<commit_before>package template

import (
	"strings"

	. "github.com/dave/jennifer/jen"
	"github.com/devimteam/microgen/util"
	"github.com/vetcher/godecl/types"
)

const (
	PackagePathGoKitEndpoint      = "github.com/go-kit/kit/endpoint"
	PackagePathContext            = "context"
	PackagePathGoKitLog           = "github.com/go-kit/kit/log"
	PackagePathTime               = "time"
	PackagePathGoogleGRPC         = "google.golang.org/grpc"
	PackagePathGoogleGRPCCodes    = "google.golang.org/grpc/codes"
	PackagePathNetContext         = "golang.org/x/net/context"
	PackagePathGoKitTransportGRPC = "github.com/go-kit/kit/transport/grpc"
	PackagePathHttp               = "net/http"
	PackagePathGoKitTransportHTTP = "github.com/go-kit/kit/transport/http"
	PackagePathBytes              = "bytes"
	PackagePathJson               = "encoding/json"
	PackagePathIOUtil             = "io/ioutil"
	PackagePathStrings            = "strings"
	PackagePathUrl                = "net/url"
	PackagePathEmptyProtobuf      = "github.com/golang/protobuf/ptypes/empty"
	PackagePathFmt                = "fmt"
	PackagePathOs                 = "os"
	PackagePathOsSignal           = "os/signal"
	PackagePathSyscall            = "syscall"
	PackagePathErrors             = "errors"
	PackagePathNet                = "net"

	TagMark         = "// @"
	MicrogenMainTag = "microgen"
	ForceTag        = "force"

	Version    = "0.6.0-alpha"
	FileHeader = `This file was automatically generated by "microgen ` + Version + `" utility.`
)

const (
	MiddlewareTag        = "middleware"
	LoggingMiddlewareTag = "logging"
	RecoverMiddlewareTag = "recover"
	HttpTag              = "http"
	HttpServerTag        = "http-server"
	HttpClientTag        = "http-client"
	GrpcTag              = "grpc"
	GrpcServerTag        = "grpc-server"
	GrpcClientTag        = "grpc-client"
	MainTag              = "main"
)

type WriteStrategyState int

const (
	FileStrat WriteStrategyState = iota + 1
	AppendStrat
)

type GenerationInfo struct {
	ServiceImportPackageName string
	Iface                    *types.Interface
	ServiceImportPath        string
	Force                    bool
	AbsOutPath               string
	SourceFilePath           string

	ProtobufPackage string
	GRPCRegAddr     string
}

func (info GenerationInfo) Copy() *GenerationInfo {
	return &GenerationInfo{
		Iface: info.Iface,
		Force: info.Force,
		ServiceImportPackageName: info.ServiceImportPackageName,
		ServiceImportPath:        info.ServiceImportPath,
		AbsOutPath:               info.AbsOutPath,
		SourceFilePath:           info.SourceFilePath,

		GRPCRegAddr:     info.GRPCRegAddr,
		ProtobufPackage: info.ProtobufPackage,
	}
}

func structFieldName(field *types.Variable) *Statement {
	return Id(util.ToUpperFirst(field.Name))
}

// Remove from function fields context if it is first in slice
func removeContextIfFirst(fields []types.Variable) []types.Variable {
	if IsContextFirst(fields) {
		return fields[1:]
	}
	return fields
}

func IsContextFirst(fields []types.Variable) bool {
	name := types.TypeName(fields[0].Type)
	return name != nil && len(fields) > 0 &&
		types.TypeImport(fields[0].Type) != nil &&
		types.TypeImport(fields[0].Type).Package == PackagePathContext &&
		*name == "Context"
}

// Remove from function fields error if it is last in slice
func removeErrorIfLast(fields []types.Variable) []types.Variable {
	if IsErrorLast(fields) {
		return fields[:len(fields)-1]
	}
	return fields
}

func IsErrorLast(fields []types.Variable) bool {
	name := types.TypeName(fields[len(fields)-1].Type)
	return name != nil && len(fields) > 0 &&
		types.TypeImport(fields[len(fields)-1].Type) == nil &&
		*name == "error"
}

// Return name of error, if error is last result, else return `err`
func nameOfLastResultError(fn *types.Function) string {
	if IsErrorLast(fn.Results) {
		return fn.Results[len(fn.Results)-1].Name
	}
	return "err"
}

// Renders struct field.
//
//  	Visit *entity.Visit `json:"visit"`
//
func structField(field *types.Variable) *Statement {
	s := structFieldName(field)
	s.Add(fieldType(field.Type, false))
	s.Tag(map[string]string{"json": util.ToSnakeCase(field.Name)})
	if types.IsEllipsis(field.Type) {
		s.Comment("This field was defined with ellipsis (...).")
	}
	return s
}

// Renders func params for definition.
//
//  	visit *entity.Visit, err error
//
func funcDefinitionParams(fields []types.Variable) *Statement {
	c := &Statement{}
	c.ListFunc(func(g *Group) {
		for _, field := range fields {
			g.Id(util.ToLowerFirst(field.Name)).Add(fieldType(field.Type, true))
		}
	})
	return c
}

// Renders field type for given func field.
//
//  	*repository.Visit
//
func fieldType(field types.Type, useEllipsis bool) *Statement {
	c := &Statement{}
	for field != nil {
		switch f := field.(type) {
		case types.TImport:
			if f.Import != nil {
				c.Qual(f.Import.Package, "")
			}
			field = f.Next
		case types.TName:
			c.Id(f.TypeName)
			field = nil
		case types.TArray:
			if f.IsSlice {
				c.Index()
			} else if f.ArrayLen > 0 {
				c.Index(Lit(f.ArrayLen))
			}
			field = f.Next
		case types.TMap:
			return c.Map(fieldType(f.Key, false)).Add(fieldType(f.Value, false))
		case types.TPointer:
			c.Op(strings.Repeat("*", f.NumberOfPointers))
			field = f.Next
		case types.TInterface:
			mhds := interfaceType(f.Interface)
			return c.Interface(mhds...)
		case types.TEllipsis:
			if useEllipsis {
				c.Op("...")
			} else {
				c.Index()
			}
			field = f.Next
		default:
			return c
		}
	}
	return c
}

func interfaceType(p *types.Interface) (code []Code) {
	for _, x := range p.Methods {
		code = append(code, functionDefinition(x))
	}
	return
}

// Renders key/value pairs wrapped in Dict for provided fields.
//
//		Err:    err,
//		Result: result,
//
func dictByVariables(fields []types.Variable) Dict {
	return DictFunc(func(d Dict) {
		for _, field := range fields {
			d[structFieldName(&field)] = Id(util.ToLowerFirst(field.Name))
		}
	})
}

// Render list of function receivers by signature.Result.
//
//		Ans1, ans2, AnS3 -> ans1, ans2, anS3
//
func paramNames(fields []types.Variable) *Statement {
	var list []Code
	for _, field := range fields {
		v := Id(util.ToLowerFirst(field.Name))
		if types.IsEllipsis(field.Type) {
			v.Op("...")
		}
		list = append(list, v)
	}
	return List(list...)
}

// Render full method definition with receiver, method name, args and results.
//
//		func (e *Endpoints) Count(ctx context.Context, text string, symbol string) (count int)
//
func methodDefinition(obj string, signature *types.Function) *Statement {
	return Func().
		Params(Id(util.LastUpperOrFirst(obj)).Op("*").Id(obj)).
		Add(functionDefinition(signature))
}

// Render full method definition with receiver, method name, args and results.
//
//		func Count(ctx context.Context, text string, symbol string) (count int)
//
func functionDefinition(signature *types.Function) *Statement {
	return Id(signature.Name).
		Params(funcDefinitionParams(signature.Args)).
		Params(funcDefinitionParams(signature.Results))
}

// Remove from generating functions that already in existing.
func removeAlreadyExistingFunctions(existing []types.Function, generating *[]*types.Function, nameFormer func(*types.Function) string) {
	x := (*generating)[:0]
	for _, fn := range *generating {
		if f := util.FindFunctionByName(existing, nameFormer(fn)); f == nil {
			x = append(x, fn)
		}
	}
	*generating = x
}
<commit_msg>set version 0.6.0<commit_after>package template

import (
	"strings"

	. "github.com/dave/jennifer/jen"
	"github.com/devimteam/microgen/util"
	"github.com/vetcher/godecl/types"
)

const (
	PackagePathGoKitEndpoint      = "github.com/go-kit/kit/endpoint"
	PackagePathContext            = "context"
	PackagePathGoKitLog           = "github.com/go-kit/kit/log"
	PackagePathTime               = "time"
	PackagePathGoogleGRPC         = "google.golang.org/grpc"
	PackagePathGoogleGRPCCodes    = "google.golang.org/grpc/codes"
	PackagePathNetContext         = "golang.org/x/net/context"
	PackagePathGoKitTransportGRPC = "github.com/go-kit/kit/transport/grpc"
	PackagePathHttp               = "net/http"
	PackagePathGoKitTransportHTTP = "github.com/go-kit/kit/transport/http"
	PackagePathBytes              = "bytes"
	PackagePathJson               = "encoding/json"
	PackagePathIOUtil             = "io/ioutil"
	PackagePathStrings            = "strings"
	PackagePathUrl                = "net/url"
	PackagePathEmptyProtobuf      = "github.com/golang/protobuf/ptypes/empty"
	PackagePathFmt                = "fmt"
	PackagePathOs                 = "os"
	PackagePathOsSignal           = "os/signal"
	PackagePathSyscall            = "syscall"
	PackagePathErrors             = "errors"
	PackagePathNet                = "net"

	TagMark         = "// @"
	MicrogenMainTag = "microgen"
	ForceTag        = "force"

	Version    = "0.6.0"
	FileHeader = `This file was automatically generated by "microgen ` + Version + `" utility.`
)

const (
	MiddlewareTag        = "middleware"
	LoggingMiddlewareTag = "logging"
	RecoverMiddlewareTag = "recover"
	HttpTag              = "http"
	HttpServerTag        = "http-server"
	HttpClientTag        = "http-client"
	GrpcTag              = "grpc"
	GrpcServerTag        = "grpc-server"
	GrpcClientTag        = "grpc-client"
	MainTag              = "main"
)

type WriteStrategyState int

const (
	FileStrat WriteStrategyState = iota + 1
	AppendStrat
)

type GenerationInfo struct {
	ServiceImportPackageName string
	Iface                    *types.Interface
	ServiceImportPath        string
	Force                    bool
	AbsOutPath               string
	SourceFilePath           string

	ProtobufPackage string
	GRPCRegAddr     string
}

func (info GenerationInfo) Copy() *GenerationInfo {
	return &GenerationInfo{
		Iface: info.Iface,
		Force: info.Force,
		ServiceImportPackageName: info.ServiceImportPackageName,
		ServiceImportPath:        info.ServiceImportPath,
		AbsOutPath:               info.AbsOutPath,
		SourceFilePath:           info.SourceFilePath,

		GRPCRegAddr:     info.GRPCRegAddr,
		ProtobufPackage: info.ProtobufPackage,
	}
}

func structFieldName(field *types.Variable) *Statement {
	return Id(util.ToUpperFirst(field.Name))
}

// Remove from function fields context if it is first in slice
func removeContextIfFirst(fields []types.Variable) []types.Variable {
	if IsContextFirst(fields) {
		return fields[1:]
	}
	return fields
}

func IsContextFirst(fields []types.Variable) bool {
	name := types.TypeName(fields[0].Type)
	return name != nil && len(fields) > 0 &&
		types.TypeImport(fields[0].Type) != nil &&
		types.TypeImport(fields[0].Type).Package == PackagePathContext &&
		*name == "Context"
}

// Remove from function fields error if it is last in slice
func removeErrorIfLast(fields []types.Variable) []types.Variable {
	if IsErrorLast(fields) {
		return fields[:len(fields)-1]
	}
	return fields
}

func IsErrorLast(fields []types.Variable) bool {
	name := types.TypeName(fields[len(fields)-1].Type)
	return name != nil && len(fields) > 0 &&
		types.TypeImport(fields[len(fields)-1].Type) == nil &&
		*name == "error"
}

// Return name of error, if error is last result, else return `err`
func nameOfLastResultError(fn *types.Function) string {
	if IsErrorLast(fn.Results) {
		return fn.Results[len(fn.Results)-1].Name
	}
	return "err"
}

// Renders struct field.
//
//  	Visit *entity.Visit `json:"visit"`
//
func structField(field *types.Variable) *Statement {
	s := structFieldName(field)
	s.Add(fieldType(field.Type, false))
	s.Tag(map[string]string{"json": util.ToSnakeCase(field.Name)})
	if types.IsEllipsis(field.Type) {
		s.Comment("This field was defined with ellipsis (...).")
	}
	return s
}

// Renders func params for definition.
//
//  	visit *entity.Visit, err error
//
func funcDefinitionParams(fields []types.Variable) *Statement {
	c := &Statement{}
	c.ListFunc(func(g *Group) {
		for _, field := range fields {
			g.Id(util.ToLowerFirst(field.Name)).Add(fieldType(field.Type, true))
		}
	})
	return c
}

// Renders field type for given func field.
//
//  	*repository.Visit
//
func fieldType(field types.Type, useEllipsis bool) *Statement {
	c := &Statement{}
	for field != nil {
		switch f := field.(type) {
		case types.TImport:
			if f.Import != nil {
				c.Qual(f.Import.Package, "")
			}
			field = f.Next
		case types.TName:
			c.Id(f.TypeName)
			field = nil
		case types.TArray:
			if f.IsSlice {
				c.Index()
			} else if f.ArrayLen > 0 {
				c.Index(Lit(f.ArrayLen))
			}
			field = f.Next
		case types.TMap:
			return c.Map(fieldType(f.Key, false)).Add(fieldType(f.Value, false))
		case types.TPointer:
			c.Op(strings.Repeat("*", f.NumberOfPointers))
			field = f.Next
		case types.TInterface:
			mhds := interfaceType(f.Interface)
			return c.Interface(mhds...)
		case types.TEllipsis:
			if useEllipsis {
				c.Op("...")
			} else {
				c.Index()
			}
			field = f.Next
		default:
			return c
		}
	}
	return c
}

func interfaceType(p *types.Interface) (code []Code) {
	for _, x := range p.Methods {
		code = append(code, functionDefinition(x))
	}
	return
}

// Renders key/value pairs wrapped in Dict for provided fields.
//
//		Err:    err,
//		Result: result,
//
func dictByVariables(fields []types.Variable) Dict {
	return DictFunc(func(d Dict) {
		for _, field := range fields {
			d[structFieldName(&field)] = Id(util.ToLowerFirst(field.Name))
		}
	})
}

// Render list of function receivers by signature.Result.
//
//		Ans1, ans2, AnS3 -> ans1, ans2, anS3
//
func paramNames(fields []types.Variable) *Statement {
	var list []Code
	for _, field := range fields {
		v := Id(util.ToLowerFirst(field.Name))
		if types.IsEllipsis(field.Type) {
			v.Op("...")
		}
		list = append(list, v)
	}
	return List(list...)
}

// Render full method definition with receiver, method name, args and results.
//
//		func (e *Endpoints) Count(ctx context.Context, text string, symbol string) (count int)
//
func methodDefinition(obj string, signature *types.Function) *Statement {
	return Func().
		Params(Id(util.LastUpperOrFirst(obj)).Op("*").Id(obj)).
		Add(functionDefinition(signature))
}

// Render full method definition with receiver, method name, args and results.
//
//		func Count(ctx context.Context, text string, symbol string) (count int)
//
func functionDefinition(signature *types.Function) *Statement {
	return Id(signature.Name).
		Params(funcDefinitionParams(signature.Args)).
		Params(funcDefinitionParams(signature.Results))
}

// Remove from generating functions that already in existing.
func removeAlreadyExistingFunctions(existing []types.Function, generating *[]*types.Function, nameFormer func(*types.Function) string) {
	x := (*generating)[:0]
	for _, fn := range *generating {
		if f := util.FindFunctionByName(existing, nameFormer(fn)); f == nil {
			x = append(x, fn)
		}
	}
	*generating = x
}
<|endoftext|>


<commit_before>package revel

import (
	"github.com/shaoshing/train"
	"strings"
)

// Server /assets with [train]
// https://github.com/shaoshing/train
var AssetsFilter = func(c *Controller, fc []Filter) {
	path := c.Request.URL.Path
	if strings.HasPrefix(path, "/assets") {
		train.ServeRequest(c.Response.Out, c.Request.Request)
	} else {
		fc[0](c, fc[1:])
	}
}

func init() {
	train.ConfigureHttpHandler(nil)
	train.Config.SASS.DebugInfo = DevMode
	train.Config.Verbose = DevMode
	train.Config.BundleAssets = !DevMode
}
<commit_msg>Fix assets pipeline, now can work will.<commit_after>package revel

import (
	_ "fmt"
	"github.com/huacnlee/train"
	"strings"
)

// Server /assets with [train]
// https://github.com/shaoshing/train

var AssetsFilter = func(c *Controller, fc []Filter) {
	checkInitAssetsPipeline()
	path := c.Request.URL.Path
	if strings.HasPrefix(path, "/assets") {
		train.ServeRequest(c.Response.Out, c.Request.Request)
	} else {
		fc[0](c, fc[1:])
	}
}

var asssetInited bool

func checkInitAssetsPipeline() {
	if asssetInited {
		return
	}

	train.Config.AssetsPath = AppPath + "/assets"
	train.Config.SASS.DebugInfo = false
	train.Config.Verbose = DevMode
	train.Config.BundleAssets = true
	train.ConfigureHttpHandler(nil)

	asssetInited = true
}

func init() {
	TemplateFuncs["javascript_include_tag"] = train.JavascriptTag
	TemplateFuncs["stylesheet_link_tag"] = train.StylesheetTag
}
<|endoftext|>


<commit_before>package printer

import (
	"fmt"
	"io"
	"strconv"
	"strings"
)

const (
	NIL  = "nil"
	NULL = "NULL"
	IOTA = "iota"
)

//
// C implement the Printer interface for C programs
//
type CPrinter struct {
	Printer

	level    int
	sameline bool
	w        io.Writer

	iota int // incremented when 'const n = iota' or 'const n' - XXX: need to add a way to reset it
}

func (p *CPrinter) SetWriter(w io.Writer) {
	p.w = w
}

func (p *CPrinter) UpdateLevel(delta int) {
	p.level += delta
}

func (p *CPrinter) SameLine() {
	p.sameline = true
}

func (p *CPrinter) indent() string {
	if p.sameline {
		p.sameline = false
		return ""
	}

	return strings.Repeat("  ", p.level)
}

func (p *CPrinter) Print(values ...string) {
	fmt.Fprint(p.w, strings.Join(values, " "))
}

func (p *CPrinter) PrintLevel(values ...string) {
	fmt.Fprint(p.w, p.indent(), strings.Join(values, " "))
}

func (p *CPrinter) PrintLevelIn(values ...string) {
	p.level -= 1
	fmt.Fprint(p.w, p.indent(), strings.Join(values, " "))
	p.level += 1
}

func (p *CPrinter) PrintPackage(name string) {
	p.PrintLevel("//package", name, "\n")
	p.PrintLevel("#include <map>\n")
	p.PrintLevel("#include <tuple>\n")
}

func (p *CPrinter) PrintImport(name, path string) {
	switch path {
	case `"strings"`:
		p.PrintLevel("#include <string>\n")
	default:
		p.PrintLevel("//import", name, path, "\n")
	}

}

func (p *CPrinter) PrintType(name, typedef string) {
	p.PrintLevel("typedef", typedef, name, ";\n")
}

func (p *CPrinter) PrintValue(vtype, names, typedef, value string) {
	if vtype == "var" {
		vtype = ""
	} else if vtype == "const" && len(value) == 0 {
		value = p.FormatIdent(IOTA)
	}

	if len(typedef) == 0 {
		typedef, value = GuessType(value)
	}

	p.PrintLevel(vtype, typedef, names)

	if len(value) > 0 {
		p.Print(" =", value)
	}
	p.Print(";\n")
}

func (p *CPrinter) PrintStmt(stmt, expr string) {
	if stmt == "return" && IsMultiValue(expr) {
		expr = fmt.Sprintf("make_tuple(%s)", expr)
	}

	p.PrintLevel(stmt, expr, ";\n")
}

func (p *CPrinter) PrintFunc(receiver, name, params, results string) {
	if len(results) == 0 {
		results = "void"
	} else if IsMultiValue(results) {
		results = fmt.Sprintf("tuple<%s>", results)
	}

	if len(receiver) > 0 {
		parts := strings.SplitN(receiver, " ", 2)
		receiver = "/* " + parts[1] + " */ " + parts[0]
	}

	fmt.Fprintf(p.w, "%s %s::%s(%s) ", results, receiver, name, params)
}

func (p *CPrinter) PrintFor(init, cond, post string) {
	onlycond := len(init) == 0 && len(post) == 0

	if len(cond) == 0 {
		cond = "true"
	}

	if onlycond {
		// make it a while
		p.PrintLevel("while (", cond)
	} else {
		p.PrintLevel("for (")
		if len(init) > 0 {
			p.Print(init)
		}
		p.Print("; ", cond, "; ")
		if len(post) > 0 {
			p.Print(post)
		}

	}
	p.Print(") ")
}

func (p *CPrinter) PrintRange(key, value, expr string) {
	p.PrintLevel("for", key)

	if len(value) > 0 {
		p.Print(",", value)
	}

	p.Print(" := range", expr)

}

func (p *CPrinter) PrintSwitch(init, expr string) {
	p.PrintLevel("switch ")
	if len(init) > 0 {
		p.Print(init + "; ")
	}
	p.Print(expr)
}

func (p *CPrinter) PrintCase(expr string) {
	if len(expr) > 0 {
		p.PrintLevel("case", expr+":\n")
	} else {
		p.PrintLevel("default:\n")
	}
}

func (p *CPrinter) PrintIf(init, cond string) {
	if len(init) > 0 {
		p.PrintLevel(init + " if ")
	} else {
		p.PrintLevel("if ")
	}
	p.Print("(", cond, ") ")
}

func (p *CPrinter) PrintElse() {
	p.Print(" else ")
}

func (p *CPrinter) PrintEmpty() {
	p.PrintLevel(";\n")
}

func (p *CPrinter) PrintAssignment(lhs, op, rhs string) {
	if op == ":=" {
		// := means there are new variables to be declared (but of course I don't know the real type)
		rtype, rvalue := GuessType(rhs)
		lhs = rtype + " " + lhs
		rhs = rvalue
		op = "="
	}

	if IsMultiValue(lhs) {
		lhs = fmt.Sprintf("tie(%s)", lhs)
	}

	p.PrintLevel(lhs, op, rhs, ";\n")
}

func (p *CPrinter) PrintSend(ch, value string) {
	p.PrintLevel(fmt.Sprintf("Channel::Send(%s, %s)", ch, value))
}

func (p *CPrinter) FormatIdent(id string) (ret string) {
	switch id {
	case NIL:
		return NULL

	case IOTA:
		ret = strconv.Itoa(p.iota)
		p.iota += 1

	default:
		ret = id
	}

	return
}

func (p *CPrinter) FormatLiteral(lit string) string {
	if len(lit) == 0 {
		return lit
	}

	if lit[0] == '`' {
		lit = strings.Replace(lit[1:len(lit)-1], `"`, `\\"`, -1)
		lit = strings.Replace(lit, "\n", "\\n", -1)
		lit = `"` + lit + `"`
	}

	return lit
}

func (p *CPrinter) FormatUnary(op, operand string) string {
	if op == "<-" {
		return fmt.Sprintf("Channel::Receive(%s)", operand)
	}

	return fmt.Sprintf("%s%s", op, operand)
}

func (p *CPrinter) FormatBinary(lhs, op, rhs string) string {
	return fmt.Sprintf("%s %s %s", lhs, op, rhs)
}

func (p *CPrinter) FormatPair(v Pair, t FieldType) string {
	name, value := v.Name(), v.Value()

	if strings.HasPrefix(value, "[") {
		i := strings.LastIndex(value, "]")
		if i < 0 {
			// it should be an error

		} else {
			arr := value[:i+1]
			value = value[i+1:]

			if len(name) > 0 {
				name += arr
			} else {
				value += arr
			}
		}
	}

	/*
		if strings.HasPrefix(value, "*") {
			for i, c := range value {
				if c != '*' {
					name = value[:i] + name
					value = value[i:]
					break
				}
			}
		}
	*/

	if strings.HasPrefix(value, "*") {
		i := strings.LastIndex(value, "*") + 1
		value = value[i:] + value[0:i]
	}

	if t == METHOD {
		return "virtual " + fmt.Sprintf(value, name)
	} else if t == RESULT && len(name) > 0 {
		return fmt.Sprintf("%s /* %s */", value, name)
	} else if len(name) > 0 && len(value) > 0 {
		return value + " " + name
	} else {
		return value + name
	}
}

func (p *CPrinter) FormatArray(len, elt string) string {
	return fmt.Sprintf("[%s]%s", len, elt)
}

func (p *CPrinter) FormatArrayIndex(array, index string) string {
	return fmt.Sprintf("%s[%s]", array, index)
}

func (p *CPrinter) FormatSlice(slice, low, high, max string) string {
	if max == "" {
		return fmt.Sprintf("%s[%s:%s]", slice, low, high)
	} else {
		return fmt.Sprintf("%s[%s:%s:%s]", slice, low, high, max)
	}
}

func (p *CPrinter) FormatMap(key, elt string) string {
	return fmt.Sprintf("std::map<%s, %s>", key, elt)
}

func (p *CPrinter) FormatKeyValue(key, value string) string {
	return fmt.Sprintf("{%s, %s}", key, value)
}

func (p *CPrinter) FormatStruct(fields string) string {
	if len(fields) > 0 {
		return fmt.Sprintf("struct {\n%s%s\n%s}", p.indent(), fields, p.indent())
	} else {
		return fmt.Sprintf("struct{}")
	}
}

func (p *CPrinter) FormatInterface(methods string) string {
	if len(methods) > 0 {
		return fmt.Sprintf("struct {\n%s%s\n%s}", p.indent(), methods, p.indent())
	} else {
		return fmt.Sprintf("struct{}")
	}
}

func (p *CPrinter) FormatChan(chdir, mtype string) string {
	var chtype string

	switch chdir {
	case CHAN_BIDI:
		chtype = "Channel::Chan"
	case CHAN_SEND:
		chtype = "Channel::SendChan"
	case CHAN_RECV:
		chtype = "Channel::ReceiveChan"
	}

	return fmt.Sprintf("%s<%s>", chtype, mtype)
}

func (p *CPrinter) FormatCall(fun, args string) string {
	switch fun {
	case "fmt.Printf":
		fun = "printf"
	case "fmt.Sprintf":
		fun = "sprintf"
	case "fmt.Fprintf":
		fun = "fprintf"
	case "fmt.Println":
		fun = "fprintf"
		args = `"%s\n", ` + args
	case "os.Open":
		fun = "open"
	}

	return fmt.Sprintf("%s(%s)", fun, args)
}

func (p *CPrinter) FormatFuncType(params, results string) string {
	if len(results) == 0 {
		results = "void"
	} else if IsMultiValue(results) {
		results = fmt.Sprintf("tuple<%s>", results)
	}

	return fmt.Sprintf("%s %%s(%s)", results, params)
}

func (p *CPrinter) FormatFuncLit(ftype, body string) string {
	return fmt.Sprintf(ftype+" %s", "func", body)
}

//
// Guess type and return type and new value
//
func GuessType(value string) (string, string) {
	vtype := "void"

	if len(value) == 0 {
		return vtype, value
	}

	switch value[0] {
	case '[':
		// array or map declaration
		i := strings.Index(value, "{")
		if i >= 0 {
			vtype = value[:i]
			value = value[i:]
		}
	case '\'':
		vtype = "char"
	case '"':
		vtype = "string"

	case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		vtype = "int"

	default:
		switch value {
		case "true", "false":
			vtype = "bool"

		case NIL, NULL:
			vtype = "void*"
		}
	}

	return vtype, value
}

func IsPublic(name string) bool {
	return name[0] >= 'A' && name[0] <= 'Z'
}

func IsMultiValue(expr string) bool {
	return strings.Contains(expr, ",")
}
<commit_msg>Adding mutex/conditions (for sync package) and a few std::<commit_after>package printer

import (
	"fmt"
	"io"
	"strconv"
	"strings"
)

const (
	NIL  = "nil"
	NULL = "NULL"
	IOTA = "iota"
)

//
// C implement the Printer interface for C programs
//
type CPrinter struct {
	Printer

	level    int
	sameline bool
	w        io.Writer

	iota int // incremented when 'const n = iota' or 'const n' - XXX: need to add a way to reset it
}

func (p *CPrinter) SetWriter(w io.Writer) {
	p.w = w
}

func (p *CPrinter) UpdateLevel(delta int) {
	p.level += delta
}

func (p *CPrinter) SameLine() {
	p.sameline = true
}

func (p *CPrinter) indent() string {
	if p.sameline {
		p.sameline = false
		return ""
	}

	return strings.Repeat("  ", p.level)
}

func (p *CPrinter) Print(values ...string) {
	fmt.Fprint(p.w, strings.Join(values, " "))
}

func (p *CPrinter) PrintLevel(values ...string) {
	fmt.Fprint(p.w, p.indent(), strings.Join(values, " "))
}

func (p *CPrinter) PrintLevelIn(values ...string) {
	p.level -= 1
	fmt.Fprint(p.w, p.indent(), strings.Join(values, " "))
	p.level += 1
}

func (p *CPrinter) PrintPackage(name string) {
	p.PrintLevel("//package", name, "\n")
	p.PrintLevel("#include <map>\n")
	p.PrintLevel("#include <tuple>\n")
}

func (p *CPrinter) PrintImport(name, path string) {
	switch path {
	case `"strings"`:
		p.PrintLevel("#include <string>\n")
	case `"sync"`:
		p.PrintLevel("#include <mutex>\n")
		p.PrintLevel("#include <condition_variable>\n")
	default:
		p.PrintLevel("//import", name, path, "\n")
	}

}

func (p *CPrinter) PrintType(name, typedef string) {
	p.PrintLevel("typedef", typedef, name, ";\n")
}

func (p *CPrinter) PrintValue(vtype, names, typedef, value string) {
	if vtype == "var" {
		vtype = ""
	} else if vtype == "const" && len(value) == 0 {
		value = p.FormatIdent(IOTA)
	}

	if len(typedef) == 0 {
		typedef, value = GuessType(value)
	}

	p.PrintLevel(vtype, typedef, names)

	if len(value) > 0 {
		p.Print(" =", value)
	}
	p.Print(";\n")
}

func (p *CPrinter) PrintStmt(stmt, expr string) {
	if stmt == "return" && IsMultiValue(expr) {
		expr = fmt.Sprintf("std::make_tuple(%s)", expr)
	}

	p.PrintLevel(stmt, expr, ";\n")
}

func (p *CPrinter) PrintFunc(receiver, name, params, results string) {
	if len(results) == 0 {
		results = "void"
	} else if IsMultiValue(results) {
		results = fmt.Sprintf("std::tuple<%s>", results)
	}

	if len(receiver) > 0 {
		parts := strings.SplitN(receiver, " ", 2)
		receiver = "/* " + parts[1] + " */ " + parts[0]
	}

	fmt.Fprintf(p.w, "%s %s::%s(%s) ", results, receiver, name, params)
}

func (p *CPrinter) PrintFor(init, cond, post string) {
	onlycond := len(init) == 0 && len(post) == 0

	if len(cond) == 0 {
		cond = "true"
	}

	if onlycond {
		// make it a while
		p.PrintLevel("while (", cond)
	} else {
		p.PrintLevel("for (")
		if len(init) > 0 {
			p.Print(init)
		}
		p.Print("; ", cond, "; ")
		if len(post) > 0 {
			p.Print(post)
		}

	}
	p.Print(") ")
}

func (p *CPrinter) PrintRange(key, value, expr string) {
	p.PrintLevel("for", key)

	if len(value) > 0 {
		p.Print(",", value)
	}

	p.Print(" := range", expr)

}

func (p *CPrinter) PrintSwitch(init, expr string) {
	p.PrintLevel("switch ")
	if len(init) > 0 {
		p.Print(init + "; ")
	}
	p.Print(expr)
}

func (p *CPrinter) PrintCase(expr string) {
	if len(expr) > 0 {
		p.PrintLevel("case", expr+":\n")
	} else {
		p.PrintLevel("default:\n")
	}
}

func (p *CPrinter) PrintIf(init, cond string) {
	if len(init) > 0 {
		p.PrintLevel(init + " if ")
	} else {
		p.PrintLevel("if ")
	}
	p.Print("(", cond, ") ")
}

func (p *CPrinter) PrintElse() {
	p.Print(" else ")
}

func (p *CPrinter) PrintEmpty() {
	p.PrintLevel(";\n")
}

func (p *CPrinter) PrintAssignment(lhs, op, rhs string) {
	if op == ":=" {
		// := means there are new variables to be declared (but of course I don't know the real type)
		rtype, rvalue := GuessType(rhs)
		lhs = rtype + " " + lhs
		rhs = rvalue
		op = "="
	}

	if IsMultiValue(lhs) {
		lhs = fmt.Sprintf("std::tie(%s)", lhs)
	}

	p.PrintLevel(lhs, op, rhs, ";\n")
}

func (p *CPrinter) PrintSend(ch, value string) {
	p.PrintLevel(fmt.Sprintf("Channel::Send(%s, %s)", ch, value))
}

func (p *CPrinter) FormatIdent(id string) (ret string) {
	switch id {
	case NIL:
		return NULL

	case IOTA:
		ret = strconv.Itoa(p.iota)
		p.iota += 1

	default:
		ret = id
	}

	return
}

func (p *CPrinter) FormatLiteral(lit string) string {
	if len(lit) == 0 {
		return lit
	}

	if lit[0] == '`' {
		lit = strings.Replace(lit[1:len(lit)-1], `"`, `\\"`, -1)
		lit = strings.Replace(lit, "\n", "\\n", -1)
		lit = `"` + lit + `"`
	}

	return lit
}

func (p *CPrinter) FormatUnary(op, operand string) string {
	if op == "<-" {
		return fmt.Sprintf("Channel::Receive(%s)", operand)
	}

	return fmt.Sprintf("%s%s", op, operand)
}

func (p *CPrinter) FormatBinary(lhs, op, rhs string) string {
	return fmt.Sprintf("%s %s %s", lhs, op, rhs)
}

func (p *CPrinter) FormatPair(v Pair, t FieldType) string {
	name, value := v.Name(), v.Value()

	if strings.HasPrefix(value, "[") {
		i := strings.LastIndex(value, "]")
		if i < 0 {
			// it should be an error

		} else {
			arr := value[:i+1]
			value = value[i+1:]

			if len(name) > 0 {
				name += arr
			} else {
				value += arr
			}
		}
	}

	/*
		if strings.HasPrefix(value, "*") {
			for i, c := range value {
				if c != '*' {
					name = value[:i] + name
					value = value[i:]
					break
				}
			}
		}
	*/

	if strings.HasPrefix(value, "*") {
		i := strings.LastIndex(value, "*") + 1
		value = value[i:] + value[0:i]
	}

	if t == METHOD {
		return "virtual " + fmt.Sprintf(value, name)
	} else if t == RESULT && len(name) > 0 {
		return fmt.Sprintf("%s /* %s */", value, name)
	} else if len(name) > 0 && len(value) > 0 {
		return value + " " + name
	} else {
		return value + name
	}
}

func (p *CPrinter) FormatArray(len, elt string) string {
	return fmt.Sprintf("[%s]%s", len, elt)
}

func (p *CPrinter) FormatArrayIndex(array, index string) string {
	return fmt.Sprintf("%s[%s]", array, index)
}

func (p *CPrinter) FormatSlice(slice, low, high, max string) string {
	if max == "" {
		return fmt.Sprintf("%s[%s:%s]", slice, low, high)
	} else {
		return fmt.Sprintf("%s[%s:%s:%s]", slice, low, high, max)
	}
}

func (p *CPrinter) FormatMap(key, elt string) string {
	return fmt.Sprintf("std::map<%s, %s>", key, elt)
}

func (p *CPrinter) FormatKeyValue(key, value string) string {
	return fmt.Sprintf("{%s, %s}", key, value)
}

func (p *CPrinter) FormatStruct(fields string) string {
	if len(fields) > 0 {
		return fmt.Sprintf("struct {\n%s%s\n%s}", p.indent(), fields, p.indent())
	} else {
		return fmt.Sprintf("struct{}")
	}
}

func (p *CPrinter) FormatInterface(methods string) string {
	if len(methods) > 0 {
		return fmt.Sprintf("struct {\n%s%s\n%s}", p.indent(), methods, p.indent())
	} else {
		return fmt.Sprintf("struct{}")
	}
}

func (p *CPrinter) FormatChan(chdir, mtype string) string {
	var chtype string

	switch chdir {
	case CHAN_BIDI:
		chtype = "Channel::Chan"
	case CHAN_SEND:
		chtype = "Channel::SendChan"
	case CHAN_RECV:
		chtype = "Channel::ReceiveChan"
	}

	return fmt.Sprintf("%s<%s>", chtype, mtype)
}

func (p *CPrinter) FormatCall(fun, args string) string {
	switch fun {
	case "fmt.Printf":
		fun = "printf"
	case "fmt.Sprintf":
		fun = "sprintf"
	case "fmt.Fprintf":
		fun = "fprintf"
	case "fmt.Println":
		fun = "fprintf"
		args = `"%s\n", ` + args
	case "os.Open":
		fun = "open"
	}

	return fmt.Sprintf("%s(%s)", fun, args)
}

func (p *CPrinter) FormatFuncType(params, results string) string {
	if len(results) == 0 {
		results = "void"
	} else if IsMultiValue(results) {
		results = fmt.Sprintf("tuple<%s>", results)
	}

	return fmt.Sprintf("%s %%s(%s)", results, params)
}

func (p *CPrinter) FormatFuncLit(ftype, body string) string {
	return fmt.Sprintf(ftype+" %s", "func", body)
}

//
// Guess type and return type and new value
//
func GuessType(value string) (string, string) {
	vtype := "void"

	if len(value) == 0 {
		return vtype, value
	}

	switch value[0] {
	case '[':
		// array or map declaration
		i := strings.Index(value, "{")
		if i >= 0 {
			vtype = value[:i]
			value = value[i:]
		}
	case '\'':
		vtype = "char"
	case '"':
		vtype = "string"

	case '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
		vtype = "int"

	default:
		switch value {
		case "true", "false":
			vtype = "bool"

		case NIL, NULL:
			vtype = "void*"
		}
	}

	return vtype, value
}

func IsPublic(name string) bool {
	return name[0] >= 'A' && name[0] <= 'Z'
}

func IsMultiValue(expr string) bool {
	return strings.Contains(expr, ",")
}
<|endoftext|>


<commit_before>// Copyright 2019 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.

// [START cloud_tasks_appengine_create_task]

// Command create_task constructs and adds a task to an App Engine Queue.
package main

import (
	"context"
	"fmt"

	cloudtasks "cloud.google.com/go/cloudtasks/apiv2"
	taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2"
)

// createTask creates a new task in your App Engine queue.
func createTask(projectID, locationID, queueID, message string) (*taskspb.Task, error) {
	// Create a new Cloud Tasks client instance.
	// See https://godoc.org/cloud.google.com/go/cloudtasks/apiv2
	ctx := context.Background()
	client, err := cloudtasks.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %v", err)
	}

	// Build the Task queue path.
	queuePath := fmt.Sprintf("projects/%s/locations/%s/queues/%s", projectID, locationID, queueID)

	// Build the Task payload.
	// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#CreateTaskRequest
	req := &taskspb.CreateTaskRequest{
		Parent: queuePath,
		Task: &taskspb.Task{
			// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#AppEngineHttpRequest
			MessageType: &taskspb.Task_AppEngineHttpRequest{
				AppEngineHttpRequest: &taskspb.AppEngineHttpRequest{
					HttpMethod:  taskspb.HttpMethod_POST,
					RelativeUri: "/task_handler",
				},
			},
		},
	}

	// Add a payload message if one is present.
	req.Task.GetAppEngineHttpRequest().Body = []byte(message)

	createdTask, err := client.CreateTask(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("cloudtasks.CreateTask: %v", err)
	}

	return createdTask, nil
}

// [END cloud_tasks_appengine_create_task]
<commit_msg>appengine: added closure of client to avoid memory spike (#1183)<commit_after>// Copyright 2019 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.

// [START cloud_tasks_appengine_create_task]

// Command create_task constructs and adds a task to an App Engine Queue.
package main

import (
	"context"
	"fmt"

	cloudtasks "cloud.google.com/go/cloudtasks/apiv2"
	taskspb "google.golang.org/genproto/googleapis/cloud/tasks/v2"
)

// createTask creates a new task in your App Engine queue.
func createTask(projectID, locationID, queueID, message string) (*taskspb.Task, error) {
	// Create a new Cloud Tasks client instance.
	// See https://godoc.org/cloud.google.com/go/cloudtasks/apiv2
	ctx := context.Background()
	client, err := cloudtasks.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("NewClient: %v", err)
	}
	defer client.Close()

	// Build the Task queue path.
	queuePath := fmt.Sprintf("projects/%s/locations/%s/queues/%s", projectID, locationID, queueID)

	// Build the Task payload.
	// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#CreateTaskRequest
	req := &taskspb.CreateTaskRequest{
		Parent: queuePath,
		Task: &taskspb.Task{
			// https://godoc.org/google.golang.org/genproto/googleapis/cloud/tasks/v2#AppEngineHttpRequest
			MessageType: &taskspb.Task_AppEngineHttpRequest{
				AppEngineHttpRequest: &taskspb.AppEngineHttpRequest{
					HttpMethod:  taskspb.HttpMethod_POST,
					RelativeUri: "/task_handler",
				},
			},
		},
	}

	// Add a payload message if one is present.
	req.Task.GetAppEngineHttpRequest().Body = []byte(message)

	createdTask, err := client.CreateTask(ctx, req)
	if err != nil {
		return nil, fmt.Errorf("cloudtasks.CreateTask: %v", err)
	}

	return createdTask, nil
}

// [END cloud_tasks_appengine_create_task]
<|endoftext|>