Exemple #1
0
func main() {
	var config Config
	flag.BoolVar(&DEBUG, "debug", false, "enable debug logging")
	flag.BoolVar(&QUIET, "quiet", false, "disable output")
	flag.StringVar(&config.FieldSep, "csv-fields-terminated-by", "\t", "field separator")
	flag.StringVar(&config.RowSep, "csv-records-terminated-by", "\n", "row separator")
	flag.StringVar(&config.NullString, "csv-null-string", "\\N", "output string for NULL values")
	flag.BoolVar(&config.DateEpoch, "epoch", true, "output datetime as epoch instead of RFC3339")
	defaults_file := flag.String("defaults-file", "my.cnf", "defaults file")
	defaults_group_suffix := flag.String("defaults-group-suffix", "", "defaults group suffix")
	format := flag.String("format", "json", "output format 'json' or 'csv'")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: mysqlcsvdump [options] database table > output.json\n\n")
		fmt.Fprintf(os.Stderr, "Reads connection info from ./my.cnf. Use '-' for table to send query in stdin\n\n")
		flag.PrintDefaults()
	}
	flag.Parse()

	args := flag.Args()
	if len(args) < 2 {
		flag.Usage()
		os.Exit(1)
	}
	dsn := getDSN(*defaults_file, "client"+*defaults_group_suffix, args[0])
	rows := getRows(dsn, args[1])
	if *format == "json" {
		NewJsonWriter(&config).WriteRows(rows)
	} else {
		NewCsvWriter(&config).WriteRows(rows)
	}
}
Exemple #2
0
func parseArgs() args {
	result := args{}
	pflag.Usage = usage
	pflag.BoolVarP(&result.options.KeepGoing, "keep-going", "k", false, "")
	pflag.BoolVar(&result.options.CheckAll, "check-all", false, "")
	pflag.StringVarP(&result.scriptFile, "file", "f", "", "")
	verbose := pflag.BoolP("verbose", "v", false, "")
	quiet := pflag.BoolP("quiet", "q", false, "")
	topics := pflag.String("debug", "", "")
	pflag.Parse()
	if *topics != "" {
		result.debugTopics = strings.Split(*topics, ",")
	}

	// argh: really, we just want a callback for each occurence of -q
	// or -v, which decrements or increments verbosity
	if *quiet {
		result.verbosity = 0
	} else if *verbose {
		result.verbosity = 2
	} else {
		result.verbosity = 1
	}

	result.options.Targets = pflag.Args()
	return result
}
Exemple #3
0
func main() {
	var (
		// general options
		stateDir = pflag.String("statedir", "", "the server state directory")
		help     = pflag.BoolP("help", "h", false, "show this help")

		// server options
		server = pflag.BoolP("server", "s", false, "run the server in the foreground")
		port   = pflag.IntP("port", "p", 40000, "server port to listen on")

		// client options
		method  = pflag.StringP("method", "X", "GET", "client method")
		plugin  = pflag.String("plugin", "", "client plugin")
		data    = pflag.StringP("data", "d", "", "client body")
		headers = &repString{[]string{}}
		verbose = pflag.BoolP("verbose", "v", false, "show full http response")
	)

	pflag.VarP(headers, "header", "H", "client request header")

	pflag.Parse()

	if *help {
		os.Exit(runHelp())
	}

	if *server {
		os.Exit(runServer(*port, *stateDir))
	}

	if pflag.NArg() < 1 {
		fmt.Fprintln(os.Stderr, "must pass in path to make api call")
		runHelp()
		os.Exit(1)
	}

	os.Exit(runClient(*stateDir, *plugin, *method, pflag.Arg(0), *data, headers.strs, *verbose))
}
Exemple #4
0
func main() {

	var cluster *string = flag.String("cluster", "default", "Name of cluster")

	flag.Parse()

	if flag.NArg() < 2 {
		fmt.Println("Usage:\n\taws-rollout [service] [image]")
		return
	}

	var service string = flag.Arg(0)
	var image string = flag.Arg(1)

	svc := ecs.New(session.New())

	clusterArn, err := findClusterArn(svc, *cluster)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	serviceArn, err := findServiceArn(svc, clusterArn, service)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	taskArn, err := findTaskArn(svc, clusterArn, serviceArn)
	newTaskArn, err := setImage(svc, taskArn, image)
	params := &ecs.UpdateServiceInput{
		Service:        aws.String(serviceArn),
		Cluster:        aws.String(clusterArn),
		TaskDefinition: aws.String(newTaskArn),
	}
	serv, err := svc.UpdateService(params)
	if err != nil {
		fmt.Println(err.Error())
		return
	}
	fmt.Printf("Deployed %s %d", newTaskArn, *serv.Service.PendingCount)
}
Exemple #5
0
	sparseAuto
	sparseAlways
)

// backup enum
const (
	noBackups = iota
	simpleBackups
	numberedExistingBackups
	numberedBackups
)

var (
	archive           = flag.BoolP("archive", "a", false, "")
	attrOnly          = flag.Bool("attributes-only", false, "")
	backup            = flag.String("backup", "", "")
	backup2           = flag.Bool("b", false, "")
	copyContents      = flag.Bool("copy-contents", false, "")
	ndrpl             = flag.Bool("d", false, "")
	dereference       = flag.BoolP("dereference", "L", false, "")
	force             = flag.BoolP("force", "f", false, "")
	hopt              = flag.Bool("H", false, "")
	interactive       = flag.BoolP("interactive", "i", false, "")
	link              = flag.BoolP("link", "l", false, "")
	noClobber         = flag.BoolP("no-clobber", "n", false, "")
	noDereference     = flag.BoolP("no-dereference", "P", false, "")
	noPreserve        = flag.String("no-preserve", "", "")
	noTargetDir       = flag.BoolP("no-target-directory", "T", false, "")
	oneFS             = flag.BoolP("one-file-system", "x", false, "")
	parents           = flag.Bool("parents", false, "")
	path              = flag.Bool("path", false, "")
import (
	"fmt"
	log "github.com/alecthomas/log4go"
	"github.com/alecthomas/tuplespace"
	"github.com/alecthomas/tuplespace/server"
	"github.com/alecthomas/tuplespace/store"
	"github.com/codegangsta/martini"
	"github.com/ogier/pflag"
	"net/http"
	"os"
	"runtime"
	"time"
)

var (
	bindFlag         = pflag.String("bind", "127.0.0.1:2619", "bind address")
	readTimeoutFlag  = pflag.Duration("read-timeout", 30*time.Second, "HTTP server read timeout")
	writeTimeoutFlag = pflag.Duration("write-timeout", 30*time.Second, "HTTP server write timeout")
	ncpuFlag         = pflag.Int("ncpu", runtime.NumCPU(), "number of cpus to use")
	logLevelFlag     = pflag.String("log-level", "info", "log level (finest, fine, debug, info, warning, error, critical)")

	logLevels = map[string]log.Level{
		"finest":   log.FINEST,
		"fine":     log.FINE,
		"debug":    log.DEBUG,
		"info":     log.INFO,
		"warning":  log.WARNING,
		"error":    log.ERROR,
		"critical": log.CRITICAL,
	}
)
Exemple #7
0
func readConfig(parse bool) {
	var err error
	// Set defaults
	ConfigYAML.UDPServiceAddress = defaultUDPServiceAddress
	ConfigYAML.TCPServiceAddress = defaultTCPServiceAddress
	ConfigYAML.MaxUDPPacketSize = maxUDPPacket
	ConfigYAML.BackendType = defaultBackendType
	ConfigYAML.PostFlushCmd = "stdout"
	ConfigYAML.GraphiteAddress = defaultGraphiteAddress
	ConfigYAML.OpenTSDBAddress = defaultOpenTSDBAddress
	ConfigYAML.FlushInterval = flushInterval
	ConfigYAML.LogLevel = "error"
	ConfigYAML.ShowVersion = false
	ConfigYAML.DeleteGauges = true
	ConfigYAML.ResetCounters = true
	ConfigYAML.PersistCountKeys = 0
	ConfigYAML.StatsPrefix = statsPrefixName
	ConfigYAML.StoreDb = dbPath
	ConfigYAML.Prefix = ""
	ConfigYAML.ExtraTags = ""
	ConfigYAML.PercentThreshold = Percentiles{}
	// Percentiles{{Float: 50.0, Str: "50"}, {Float: 80.0, Str: "80"}, {Float: 90.0, Str: "90"}, {Float: 95.0, Str: "95"}}
	ConfigYAML.PrintConfig = false
	ConfigYAML.LogName = "stdout"
	ConfigYAML.LogToSyslog = true
	ConfigYAML.SyslogUDPAddress = "localhost:514"

	Config = ConfigYAML

	os.Setenv("CONFIGOR_ENV_PREFIX", "SD")

	configFile = flag.String("config", "", "Configuration file name (warning not error if not exists). Standard: "+configPath)
	flag.StringVar(&Config.UDPServiceAddress, "udp-addr", ConfigYAML.UDPServiceAddress, "UDP listen service address")
	flag.StringVar(&Config.TCPServiceAddress, "tcp-addr", ConfigYAML.TCPServiceAddress, "TCP listen service address, if set")
	flag.Int64Var(&Config.MaxUDPPacketSize, "max-udp-packet-size", ConfigYAML.MaxUDPPacketSize, "Maximum UDP packet size")
	flag.StringVar(&Config.BackendType, "backend-type", ConfigYAML.BackendType, "MANDATORY: Backend to use: graphite, opentsdb, external, dummy")
	flag.StringVar(&Config.PostFlushCmd, "post-flush-cmd", ConfigYAML.PostFlushCmd, "Command to run on each flush")
	flag.StringVar(&Config.GraphiteAddress, "graphite", ConfigYAML.GraphiteAddress, "Graphite service address")
	flag.StringVar(&Config.OpenTSDBAddress, "opentsdb", ConfigYAML.OpenTSDBAddress, "OpenTSDB service address")
	flag.Int64Var(&Config.FlushInterval, "flush-interval", ConfigYAML.FlushInterval, "Flush interval (seconds)")
	flag.StringVar(&Config.LogLevel, "log-level", ConfigYAML.LogLevel, "Set log level (debug,info,warn,error,fatal)")
	flag.BoolVar(&Config.ShowVersion, "version", ConfigYAML.ShowVersion, "Print version string")
	flag.BoolVar(&Config.DeleteGauges, "delete-gauges", ConfigYAML.DeleteGauges, "Don't send values to graphite for inactive gauges, as opposed to sending the previous value")
	flag.BoolVar(&Config.ResetCounters, "reset-counters", ConfigYAML.ResetCounters, "Reset counters after sending value to backend (send rate) or  send cumulated value (artificial counter - eg. for OpenTSDB & Grafana)")
	flag.Int64Var(&Config.PersistCountKeys, "persist-count-keys", ConfigYAML.PersistCountKeys, "Number of flush-intervals to persist count keys")
	flag.StringVar(&Config.StatsPrefix, "stats-prefix", ConfigYAML.StatsPrefix, "Name for internal application metrics (no prefix prepended)")
	flag.StringVar(&Config.StoreDb, "store-db", ConfigYAML.StoreDb, "Name of database for permanent counters storage (for conversion from rate to counter)")
	flag.StringVar(&Config.Prefix, "prefix", ConfigYAML.Prefix, "Prefix for all stats")
	flag.StringVar(&Config.ExtraTags, "extra-tags", ConfigYAML.ExtraTags, "Default tags added to all measures in format: tag1=value1 tag2=value2")
	flag.Var(&Config.PercentThreshold, "percent-threshold", "Percentile calculation for timers (0-100, may be given multiple times)")
	flag.BoolVar(&Config.PrintConfig, "print-config", ConfigYAML.PrintConfig, "Print config in YAML format")
	flag.StringVar(&Config.LogName, "log-name", ConfigYAML.LogName, "Name of file to log into. If \"stdout\" than logs to stdout.If empty logs go to /dev/null")
	flag.BoolVar(&Config.LogToSyslog, "log-to-syslopg", ConfigYAML.LogToSyslog, "Log to syslog")
	flag.StringVar(&Config.SyslogUDPAddress, "syslog-udp-address", ConfigYAML.SyslogUDPAddress, "Syslog address with port number eg. localhost:514. If empty log to unix socket")
	if parse {
		flag.Parse()
	}

	if len(*configFile) > 0 {
		if _, err = os.Stat(*configFile); os.IsNotExist(err) {
			fmt.Printf("# Warning: No config file: %s\n", *configFile)
			*configFile = ""
		}

		if len(*configFile) > 0 {
			err = configor.Load(&ConfigYAML, *configFile)
			if err != nil {
				fmt.Printf("Error loading config file: %s\n", err)
			} else {
				// set configs read form YAML file

				// save 2 flags
				tmpConfig := Config
				// Overwites flags
				Config = ConfigYAML
				// restore 2 flags
				Config.ShowVersion = tmpConfig.ShowVersion
				Config.PrintConfig = tmpConfig.PrintConfig

			}
		}

		// visitor := func(a *flag.Flag) {
		// 	fmt.Println(">", a.Name, "value=", a.Value)
		// 	switch a.Name {
		// 	case "print-config", "version":
		// 		break
		// 	case "udp-addr":
		// 		ConfigYAML.UDPServiceAddress = a.Value.(string)
		// 	default:
		// 		fmt.Printf("Internal Config Error - unknown variable: %s\n", a.Name)
		// 		os.Exit(1)
		// 	}
		//
		// }
		// flag.Visit(visitor)
	}

	// Normalize prefix
	Config.Prefix = normalizeDot(Config.Prefix, true)

	// Normalize internal metrics name
	Config.StatsPrefix = normalizeDot(Config.StatsPrefix, true)

	// calculate extraFlags hash
	Config.ExtraTagsHash, err = parseExtraTags(Config.ExtraTags)
	if err != nil {
		fmt.Printf("Extra Tags: \"%s\" - %s\n", Config.ExtraTags, err)
		os.Exit(1)
	}

	// Set InternalLogLevel
	Config.InternalLogLevel, err = log.ParseLevel(Config.LogLevel)
	if err != nil {
		fmt.Printf("Invalid log level: \"%s\"\n", Config.LogLevel)
		os.Exit(1)
	}

}
Exemple #8
0
func main() {
	rootLog.Info("Started")

	// For each registered protocol, we add the corresponding flags for its
	// destination.
	protocolFlags := make(map[string]*string)
	for name, _ := range protocols {
		protocolFlags[name] = flag.String(name+"-destination", "",
			"destination to forward "+name+" traffic to")
	}

	// Parse all flags.
	flag.Parse()

	// First off, handle flags that cause us to exit instead of actually listening
	checkExitFlags()
	validateFlags()

	// Find out what we've got enabled
	enabledProtocols := []Protocol{}
	protoDestinations := make(map[string]*net.TCPAddr)
	descString := ""
	for name, flag := range protocolFlags {
		if len(*flag) > 0 {
			// Validate that we can parse this address
			addr, err := net.ResolveTCPAddr("tcp", *flag)
			if err != nil {
				log.Crit("Invalid TCP address",
					"addr", *flag,
					"err", err,
				)
				return
			}

			protoDestinations[name] = addr
			enabledProtocols = append(enabledProtocols, protocols[name])
			descString += name + ","
		}
	}

	if len(enabledProtocols) == 0 {
		rootLog.Crit("No protocols were enabled")
		return
	}

	log.Debug("Enabled protocols: " + descString[0:len(descString)-1])

	// Start listening
	addr := fmt.Sprintf("%s:%d", flagListenHost, flagListenPort)
	l, err := net.Listen("tcp", addr)
	if err != nil {
		rootLog.Crit("Could not open listener", "err", err)
		return
	}
	defer l.Close()

	rootLog.Info("Started listening", "addr", addr)
	for {
		conn, err := l.Accept()
		if err != nil {
			rootLog.Error("Error accepting connection", "err", err)
			continue
		}

		p := NewProxy(conn, rootLog)
		p.EnabledProtocols = enabledProtocols
		p.ProtoDestinations = protoDestinations
		go p.Start()
	}
}
Exemple #9
0
type ContainersMsg struct {
	Left  *ListData
	Right *ListData
}

var (
	drawChan            chan bool
	newContainerChan    chan goDocker.Container
	removeContainerChan chan string
	doneChan            chan bool
	uiEventChan         chan view.UIEvent
	drawStatsChan       chan docklistener.StatsMsg
)

var logFileFlag = flag.String("log-file", "", "Path to log file")
var dockerEndpoint = flag.String("docker-endpoint", "", "Docker connection endpoint")
var helpFlag = flag.Bool("help", false, "help")
var versionFlag = flag.Bool("version", false, "print version")

func init() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage: dockdash [options]\n\n")
		flag.PrintDefaults()
	}

	flag.Parse()

	if *helpFlag {
		flag.Usage()
		os.Exit(1)
Exemple #10
0
import (
    "github.com/alecthomas/gobundle"
)

var {{ .Bundle | ToTitle }}Bundle = gobundle.NewBuilder("{{ .Bundle }}"){{if .Compressed}}.Compressed(){{ if .RetainUncompressed }}.RetainUncompressed(){{ end }}{{ if .UncompressOnInit }}.UncompressOnInit(){{ end }}{{end}}`
	// FileTemplate contains the file template output.
	FileTemplate = `.Add(
    "{{ .Name }}", {{ .Content }},
)`
	// FooterTemplate contains the footer template output.
	FooterTemplate = `.Build()
`
)

var (
	targetFlag             = flag.String("target", "", "target bundle filename to generate")
	pkgFlag                = flag.String("package", "", "target package name (inferred from --target if not provided)")
	bundleFlag             = flag.String("bundle", "", "bundle name (inferred from --package if not provided)")
	excludeFlag            = flag.String("exclude", "", "list of globs to exclude from")
	recurseFlag            = flag.BoolP("recursive", "r", false, "recursively add files")
	compressFlag           = flag.BoolP("compress", "c", false, "compress files before encoding")
	retainUncompressedFlag = flag.BoolP("retain_uncompressed", "u", false, "whether to retain the uncompressed copy on initial access")
	uncompressOnInitFlag   = flag.BoolP("uncompress_on_init", "i", false, "whether to uncompress files on package init()")
	encodeAsBytesFlag      = flag.BoolP("encode_as_bytes", "b", false, "whether to encode as bytes or the default, escaped strings")

	funcMap = map[string]interface{}{"ToTitle": strings.Title}
	usage   = template.Must(template.New("usage").Parse(Usage))
	header  = template.Must(template.New("header").Funcs(funcMap).Parse(HeaderTemplate))
	file    = template.Must(template.New("file").Parse(FileTemplate))
	footer  = template.Must(template.New("footer").Parse(FooterTemplate))
)
Exemple #11
0
			} else {
				return "", nil
			}
		} else {
			basePathFound = basePath
			break
		}
	}

	return basePathFound, nil
}

var Environment = getEnv("ENVIRONMENT", "development")
var Version = "master"
var templateBase = pflag.String("templates",
	"",
	"templates path")
var assetBase = pflag.String("assets",
	fmt.Sprintf("https://cdn.rawgit.com/klingtnet/gol/%s/assets", Version),
	"assets path")
var ssl = pflag.String("ssl",
	"",
	"enable ssl (give server.crt,server.key as value)")
var storageUrl = pflag.String("storage",
	"json://posts.json",
	"the storage to connect to")
var authUrl = pflag.String("authentication",
	"",
	"the authentication method to use")

func init() {
// license that can be found in the LICENSE file.

// These examples demonstrate more intricate uses of the flag package.
package pflag_test

import (
	"errors"
	"fmt"
	"strings"
	"time"

	flag "github.com/ogier/pflag"
)

// Example 1: A single string flag called "species" with default value "gopher".
var species = flag.String("species", "gopher", "the species we are studying")

// Example 2: A flag with a shorthand letter.
var gopherType = flag.StringP("gopher_type", "g", "pocket", "the variety of gopher")

// Example 3: A user-defined flag type, a slice of durations.
type interval []time.Duration

// String is the method to format the flag's value, part of the flag.Value interface.
// The String method's output will be used in diagnostics.
func (i *interval) String() string {
	return fmt.Sprint(*i)
}

func (i *interval) Type() string {
	return "interval"
)

var (
	config = replicator.Config{}

	metricFlags = metrics.RegisterMetricFlags(pflag.CommandLine)

	glogFlags struct {
		logToStderr     string
		alsoLogToStderr string
		verbosity       string
		vmodule         string
		logBacktraceAt  string
	}

	fleetDriver   = pflag.String("fleet-driver", "http", "The driver to use for connections to fleet. (http, etcd)")
	fleetEndpoint = pflag.String("fleet-peers", "unix:///var/run/fleet.sock", "List of peers for the fleet client (comma separated).")
	dryRun        = pflag.Bool("dry-run", true, "Do not write to fleet.")
)

func init() {
	pflag.DurationVar(&config.TickerTime, "ticker-time", 60*time.Second, "Ticker time.")
	pflag.DurationVar(&config.DeleteTime, "delete-time", 60*time.Minute, "Time before deleting undesired units.")
	pflag.DurationVar(&config.UpdateCooldownTime, "update-cooldown-time", 15*time.Minute, "Time between updates of changed units.")

	pflag.StringVar(&config.MachineTag, "machine-tag", "", "The machine-tag to filter for.")
	pflag.StringVar(&config.UnitTemplate, "unit-template", "", "The template to render for new units. Prefix with @ to load from a file.")
	pflag.StringVar(&config.UnitPrefix, "unit-prefix", "", "The prefix for the units to identify.")

	pflag.StringVar(&glogFlags.logToStderr, "logtostderr", "true", "log to standard error instead of files")
	pflag.StringVar(&glogFlags.alsoLogToStderr, "alsologtostderr", "false", "log to standard error as well as files")
Exemple #14
0
	maxLineLength int64

	// For pretty printing.
	numberWidth int
	printOne    bool

	// For getFileStatus.
	errNoStat = errors.New("No stat.")

	// Our cli args
	printLines      = flag.BoolP("lines", "l", false, "")
	printWords      = flag.BoolP("words", "w", false, "")
	printChars      = flag.BoolP("chars", "m", false, "")
	printBytes      = flag.BoolP("bytes", "c", false, "")
	printLineLength = flag.BoolP("max-line-length", "L", false, "")
	filesFrom       = flag.String("files0-from", "", "")
	tabWidth        = flag.Int64P("tab", "t", 8, "")
	constVersion    = flag.BoolP("unicode-version", "u", false, "")
	version         = flag.BoolP("version", "v", false, "")

	// fatal.Fatal helper
	//fatal = log.New(os.Stderr, "", log.Lshortfile)
	fatal = log.New(os.Stderr, "", 0)
)

type fstatus struct {
	failed error
	stat   os.FileInfo
}

func count(s []byte, delim byte) int64 {
Exemple #15
0
package main

import (
	"encoding/json"
	"fmt"
	log "github.com/alecthomas/log4go"
	"github.com/alecthomas/tuplespace"
	"github.com/alecthomas/tuplespace/client"
	"github.com/ogier/pflag"
	"os"
	"runtime"
	"time"
)

var (
	serverFlag  = pflag.String("server", "http://127.0.0.1:2619/tuplespace/", "tuplespace server address")
	timeoutFlag = pflag.Duration("timeout", time.Second*60, "tuplespace operation timeout")
	copiesFlag  = pflag.Int("copies", 1, "number of copies of the tuple to send")
	silentFlag  = pflag.Bool("silent", false, "don't display received tuples")
)

func fatalf(f string, args ...interface{}) {
	fmt.Fprintf(os.Stderr, "error: "+f+"\n", args...)
	os.Exit(1)
}

func parseTuple(arg string) (tuple tuplespace.Tuple) {
	err := json.Unmarshal([]byte(arg), &tuple)
	if err != nil {
		fatalf("invalid tuple (%s)", err.Error())
	}
	"fmt"
	flag "github.com/ogier/pflag"
	gutenberg "gutenberg.org"
	"gutenberg.org/config"
	"gutenberg.org/plugins"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

var (
	cfgfile   = flag.String("config", "", "config file (default is path/config.json)")
	help      = flag.BoolP("help", "h", false, "show this help")
	source    = flag.StringP("source", "s", "", "filesystem path to read files relative from")
	watchMode = flag.BoolP("watch", "w", false, "watch filesystem for changes and recreate as needed")
	server    = flag.BoolP("server", "S", false, "run a (very) simple web server")
	port      = flag.String("port", "1313", "port to run web server on, default :1313")
	interval  = flag.Int64P("interval", "i", 1000, "pooling interval for watching")
	rebuild   = flag.BoolP("rebuild", "r", false, "rebuild entire book on restart")
)

type Process struct {
	// Process is done
	Done chan bool
	// Source directory for the book
	Source string
	// Started
Exemple #17
0
func main() {
	flagAppend := flag.BoolP("append", "a", false, "append to file")
	timeFormat := flag.String("format", "%Y-%m-%d %H:%M:%S", "time format, compatible with strftime(3)")
	flag.Parse()

	var outStreams []*os.File = []*os.File{os.Stdout}
	for i := 0; i < len(flag.Args()); i++ {
		if *flagAppend {
			f, _ := os.OpenFile(flag.Args()[i], os.O_WRONLY | os.O_CREATE | os.O_APPEND, 0644)
			outStreams = append(outStreams, f)
		} else {
			f, _ := os.OpenFile(flag.Args()[i], os.O_WRONLY | os.O_CREATE | os.O_TRUNC, 0644)
			outStreams = append(outStreams, f)
		}
	}

	const kBufferSize = 1
	inputBuffer := make([]byte, kBufferSize)
	outputBuffer := make([]byte, kBufferSize)
	var outputBufferSize int = 0

	kSeparator := []byte{' '}
	const kLF byte = '\x0a'

	AppendBuffer := func(buffer []byte) {
		var remaining int = len(buffer)
		var offset int = 0
		for remaining > 0 {
			amount := remaining
			if outputBufferSize + amount > kBufferSize {
				amount = kBufferSize - outputBufferSize
			}
			for i := 0; i < amount; i++ {
				outputBuffer[outputBufferSize] = buffer[i + offset]
				outputBufferSize++
			}
			if outputBufferSize == kBufferSize {
				for _, stream := range outStreams {
					stream.Write(outputBuffer)
				}
				outputBufferSize = 0
			}
			remaining -= amount
			offset += amount
		}
	}

	PrintTime := func() {
		AppendBuffer([]byte(strftime.Format(*timeFormat, time.Now())))
		AppendBuffer(kSeparator)
	}

	var printTime bool = true

	for true {
		size, _ := os.Stdin.Read(inputBuffer)

		if size == 0 {
			break;
		}

		for i := 0; i < size; i++ {
			if printTime {
				PrintTime()
				printTime = false
			}

			if inputBuffer[i] == kLF {
				printTime = true
			}
			AppendBuffer(inputBuffer[i:i + 1])
		}
	}

	for _, stream := range outStreams {
		stream.Write(outputBuffer[0:outputBufferSize])
		stream.Close()
	}
}