Пример #1
0
func main() {
	app := kingpin.New("minicdn", "Master node which manage slaves")
	app.Flag("cachedir", "Cache file directory").Short('d').Default("cache").ExistingDirVar(&mOpts.CacheDir) //.StringVar(&mOpts.CacheDir)
	app.Flag("secret", "Secret key for server").Short('s').Default("sandy mandy").StringVar(&mOpts.Secret)

	ma := app.Command("master", "CDN Master")
	ma.Flag("addr", "Listen address").Default(":7010").StringVar(&mOpts.ListenAddr)
	ma.Flag("log", "Log file, - for stdout").Short('l').Default("-").StringVar(&mOpts.LogFile)
	ma.Flag("mirror", "Mirror http address, ex: http://t.co/").Required().URLVar(&mOpts.MirrorAddr)

	sa := app.Command("slave", "Slave node")
	sa.Flag("addr", "Listen address").Default(":7020").StringVar(&sOpts.ListenAddr)
	sa.Flag("maddr", "Master server address, ex: localhost:7010").Short('m').Required().URLVar(&sOpts.MasterAddr)

	app.Version(VERSION).Author("codeskyblue")
	app.HelpFlag.Short('h')
	app.VersionFlag.Short('v')
	kingpin.CommandLine.Help = "The very simple and mini CDN"

	// parse command line
	cmdName := kingpin.MustParse(app.Parse(os.Args[1:]))

	sOpts.CacheDir = mOpts.CacheDir
	sOpts.Secret = mOpts.Secret

	switch cmdName {
	case ma.FullCommand():
		runMaster(mOpts)
	case sa.FullCommand():
		runSlave(sOpts)
	default:
		log.Fatalf("Unknown command: %s", cmdName)
	}
}
Пример #2
0
func New(info info.Info, client api.Client, out io.Writer, err io.Writer) (c Command) {
	c.Client = client
	c.Out = out
	c.Error = err

	c.Application = kingpin.New("qiitactl", "Command line interface to manage the posts in Qiita.")
	c.Application.Version(info.Version)
	c.Application.Author(info.Author)
	c.GlobalOptions = GlobalOptions{
		Debug: c.Application.Flag("debug", "Enable debug mode.").Bool(),
	}

	c.Generate = c.Application.Command("generate", "Generate something in your local.")
	c.GenerateFile = c.Generate.Command("file", "Generate a new markdown file for a new post.")
	c.GenerateFileRunner = GenerateFileRunner{
		Title: c.GenerateFile.Arg("title", "The title of a new post.").Required().String(),
		Team:  c.GenerateFile.Flag("team", "The name of a team, when you post to the team.").Short('t').String(),
	}

	c.Create = c.Application.Command("create", "Create resources from current working directory to Qiita.")
	c.CreatePost = c.Create.Command("post", "Create a post in Qiita.")
	c.CreatePostRunner = CreatePostRunner{
		File:  c.CreatePost.Arg("filename", "The filename of the post to be created").Required().File(),
		Tweet: c.CreatePost.Flag("tweet", "Tweet the created post in Twitter.").Short('t').Bool(),
		Gist:  c.CreatePost.Flag("gist", "Post codes in the created post to GitHub Gist.").Short('g').Bool(),
	}

	c.Show = c.Application.Command("show", "Display resources.")
	c.ShowPost = c.Show.Command("post", "Display detail of a post in Qiita.")
	c.ShowPostRunner = ShowPostRunner{
		ID:   c.ShowPost.Flag("id", "The ID of the post to be printed detail.").Short('i').String(),
		File: c.ShowPost.Flag("filename", "The filename of the post to be created.").Short('f').File(),
	}
	c.ShowPosts = c.Show.Command("posts", "Display posts in Qiita.")
	c.ShowPostsRunner = ShowPostsRunner{}

	c.Fetch = c.Application.Command("fetch", "Download resources from Qiita to current working directory.")
	c.FetchPost = c.Fetch.Command("post", "Download a post as a file.")
	c.FetchPostRunner = FetchPostRunner{
		ID:   c.FetchPost.Flag("id", "The ID of the post to be downloaded.").Short('i').String(),
		File: c.FetchPost.Flag("filename", "The filename of the post to be created.").Short('f').File(),
	}
	c.FetchPosts = c.Fetch.Command("posts", "Download posts as files.")
	c.FetchPostsRunner = FetchPostsRunner{}

	c.Update = c.Application.Command("update", "Update resources from current working directory to Qiita.")
	c.UpdatePost = c.Update.Command("post", "Update a post in Qiita.")
	c.UpdatePostRunner = UpdatePostRunner{
		File: c.UpdatePost.Arg("filename", "The filename of the post to be updated.").Required().File(),
	}

	c.Delete = c.Application.Command("delete", "Delete resources from current working directory to Qiita.")
	c.DeletePost = c.Delete.Command("post", "Delete a post in Qiita.")
	c.DeletePostRunner = DeletePostRunner{
		File: c.DeletePost.Arg("filename", "The filename of the post to be deleted.").Required().File(),
	}

	return
}
Пример #3
0
func get(root, cwd client.Fid, cmdline string) (client.Fid, error) {
	args, err := parseCommandLine(cmdline)
	if err != nil {
		return cwd, err
	}
	cmd := kingpin.New("get", "")
	remote := cmd.Arg("remote", "remote filename").Required().String()
	local := cmd.Arg("local", "local filename").Required().String()
	_, err = cmd.Parse(args)
	if err != nil {
		return cwd, err
	}

	remotepath, absolute := parsepath(*remote)
	lf, err := os.Create(*local)
	if err != nil {
		return cwd, err
	}

	f := cwd
	if absolute {
		f = root
	}
	f, _, err = f.Walk(remotepath)
	if err != nil {
		return cwd, err
	}
	defer f.Clunk()

	stat, err := f.Stat()
	if err != nil {
		return cwd, err
	}
	if stat.Mode&qp.DMDIR != 0 {
		return cwd, errors.New("file is a directory")
	}
	_, _, err = f.Open(qp.OREAD)
	if err != nil {
		return cwd, err
	}

	fmt.Fprintf(os.Stderr, "Downloading: %s to %s [%dB]", *remote, *local, stat.Length)
	wf := client.WrappedFid{Fid: f}
	strs, err := wf.ReadAll()
	if err != nil {
		return cwd, err
	}
	fmt.Fprintf(os.Stderr, " - Downloaded %dB.\n", len(strs))
	for len(strs) > 0 {
		n, err := lf.Write(strs)
		if err != nil {
			return cwd, err
		}
		strs = strs[n:]
	}

	return cwd, nil
}
Пример #4
0
func main() {
	app := kingpin.New("Cache", "A generic cache control system")

	configureCmdList(app)
	configureCmdRestore(app)
	configureCmdSnapshot(app)

	kingpin.MustParse(app.Parse(os.Args[1:]))
}
Пример #5
0
func put(root, cwd client.Fid, cmdline string) (client.Fid, error) {
	args, err := parseCommandLine(cmdline)
	if err != nil {
		return cwd, err
	}
	cmd := kingpin.New("put", "")
	local := cmd.Arg("local", "local filename").Required().String()
	remote := cmd.Arg("remote", "remote filename").Required().String()
	_, err = cmd.Parse(args)
	if err != nil {
		return cwd, err
	}

	strs, err := ioutil.ReadFile(*local)
	if err != nil {
		return cwd, err
	}

	remotepath, absolute := parsepath(*remote)
	if len(remotepath) == 0 {
		return cwd, errors.New("need a destination")
	}
	f := cwd
	if absolute {
		f = root
	}
	f, _, err = f.Walk(remotepath[:len(remotepath)-1])
	if err != nil {
		return cwd, err
	}
	defer f.Clunk()

	_, _, err = f.Create(remotepath[len(remotepath)-1], 0666, qp.OWRITE)
	if err != nil {
		f, _, err = f.Walk(remotepath[len(remotepath)-1:])
		if err != nil {
			return cwd, err
		}
		defer f.Clunk()

		_, _, err := f.Open(qp.OTRUNC | qp.OWRITE)
		if err != nil {
			return cwd, err
		}
	}

	wf := &client.WrappedFid{Fid: f}
	fmt.Fprintf(os.Stderr, "Uploading: %s to %s [%dB]", *local, *remote, len(strs))
	_, err = wf.WriteAt(strs, 0)
	if err != nil {
		return cwd, err
	}

	return cwd, nil
}
Пример #6
0
func main() {
	app := kingpin.New("completion", "My application with bash completion.")
	app.Flag("flag-1", "").String()
	app.Flag("flag-2", "").HintOptions("opt1", "opt2").String()

	configureNetcatCommand(app)

	// Add some additional top level commands
	addSubCommand(app, "ls", "Additional top level command to show command completion")
	addSubCommand(app, "ping", "Additional top level command to show command completion")
	addSubCommand(app, "nmap", "Additional top level command to show command completion")

	kingpin.MustParse(app.Parse(os.Args[1:]))
}
Пример #7
0
func New(args []string) (o Options, err error) {
	app := kingpin.New("presigner", "Publisher of signed URLs to upload files directly to Google Cloud Storage")
	i := app.Flag("id", "Google Access ID").Short('i').OverrideDefaultFromEnvar("GOOGLE_ACCESS_ID").Required().String()
	k := app.Flag("key", "Path to private key").Short('k').OverrideDefaultFromEnvar("PRIVATE_KEY_PATH").Required().String()
	b := app.Flag("buckets", "Allowed buckets").Short('b').Default("*").OverrideDefaultFromEnvar("BUCKETS").String()
	p := app.Flag("port", "Listening port").Short('p').Default("80").OverrideDefaultFromEnvar("PORT").Int()
	d := app.Flag("duration", "Available duration of published signature").Short('d').Default("1m").Duration()
	_, err = app.Parse(args)
	if err != nil {
		return
	}

	o.GoogleAccessID = *i
	o.PrivateKeyPath = *k
	o.Buckets = NewBuckets(*b)
	o.Port = *p
	o.Duration = *d
	return
}
Пример #8
0
func New(args []string) (o Options, err error) {
	app := kingpin.New("policies", "Publisher of POST policies to upload files directly to Amazon S3")
	i := app.Flag("id", "AWS access key ID").Short('i').OverrideDefaultFromEnvar("AWS_ACCESS_KEY_ID").Required().String()
	s := app.Flag("secret", "AWS secret access key").Short('s').OverrideDefaultFromEnvar("AWS_SECRET_ACCESS_KEY").Required().String()
	r := app.Flag("region", "AWS region").Short('r').OverrideDefaultFromEnvar("AWS_REGION").Required().String()
	b := app.Flag("bucket", "AWS S3 bucket name").Short('b').OverrideDefaultFromEnvar("AWS_BUCKET").Required().String()
	p := app.Flag("port", "Listening port").Short('p').Default("80").Int()
	d := app.Flag("duration", "Available duration of published signature").Short('d').Default("1m").Duration()
	_, err = app.Parse(args)
	if err != nil {
		return
	}

	o.AccessKeyID = *i
	o.SecretAccessKey = *s
	o.Region = *r
	o.Bucket = *b
	o.Port = *p
	o.Duration = *d
	return
}
Пример #9
0
func New(args []string) (o Options, err error) {
	app := kingpin.New("resizer", "Image resizing processor.")

	ProjectID := app.Flag("id", "Project ID of Google Cloud Platform").OverrideDefaultFromEnvar("RESIZER_PROJECT_ID").Required().String()
	Bucket := app.Flag("bucket", "Bucket of Google Cloud Storage").OverrideDefaultFromEnvar("RESIZER_BUCKET").Required().String()
	JSON := app.Flag("json", "Path to json of service account for Google Cloud Platform").OverrideDefaultFromEnvar("RESIZER_JSON").Required().String()
	DBUser := app.Flag("dbuser", "Database user name").OverrideDefaultFromEnvar("RESIZER_DB_USER").Required().String()
	DBPassword := app.Flag("dbpassword", "Database password").OverrideDefaultFromEnvar("RESIZER_DB_PASSWORD").Default("").String()
	DBProtocol := app.Flag("dbprotocol", "Database access protocol").OverrideDefaultFromEnvar("RESIZER_DB_PROTOCOL").Required().String()
	DBAddress := app.Flag("dbaddress", "Database address").OverrideDefaultFromEnvar("RESIZER_DB_ADDRESS").Required().String()
	DBName := app.Flag("dbname", "Database name").OverrideDefaultFromEnvar("RESIZER_DB_NAME").Required().String()
	FlagHosts := app.Flag("host", "Allowed host").Strings()
	MaxConn := app.Flag("maxconn", "Max number of current connections").OverrideDefaultFromEnvar("RESIZER_MAX_CONNECTION").Default("10").Int()

	_, err = app.Parse(args)
	if err != nil {
		return
	}

	var Hosts *[]string
	if *FlagHosts == nil {
		SplitedHosts := strings.Split(os.Getenv("RESIZER_HOSTS"), ",")
		Hosts = &SplitedHosts
	} else {
		Hosts = FlagHosts
	}

	return Options{
		ProjectID:  *ProjectID,
		Bucket:     *Bucket,
		JSON:       *JSON,
		DBUser:     *DBUser,
		DBPassword: *DBPassword,
		DBProtocol: *DBProtocol,
		DBAddress:  *DBAddress,
		DBName:     *DBName,
		Hosts:      *Hosts,
		MaxConn:    *MaxConn,
	}, nil
}
Пример #10
0
func stuff(root, cwd client.Fid, cmdline string) (client.Fid, error) {
	args, err := parseCommandLine(cmdline)
	if err != nil {
		return cwd, err
	}

	cmd := kingpin.New("stuff", "")
	content := cmd.Arg("content", "the string to stuff").Required().String()
	target := cmd.Arg("target", "the file to stuff it into").Required().String()
	_, err = cmd.Parse(args)
	if err != nil {
		return cwd, err
	}

	remotepath, absolute := parsepath(*target)
	if len(remotepath) == 0 {
		return cwd, errors.New("need a destination")
	}

	f := cwd
	if absolute {
		f = root
	}
	f, _, err = f.Walk(remotepath)
	if err != nil {
		return cwd, err
	}
	defer f.Clunk()

	_, _, err = f.Open(qp.OWRITE)
	if err != nil {
		return cwd, err
	}

	wf := &client.WrappedFid{Fid: f}
	_, err = wf.WriteAt([]byte(*content), 0)

	return cwd, err
}
Пример #11
0
Файл: cli.go Проект: bivas/crane
import (
	"fmt"
	"os"
	"strings"

	"github.com/alecthomas/kingpin"
)

// Version for crane
const Version = "v2.8.0"

var cfg Config
var allowed []string

var (
	app         = kingpin.New("crane", "Lift containers with ease").Interspersed(false).DefaultEnvars()
	verboseFlag = app.Flag("verbose", "Enable verbose output.").Short('v').Bool()
	configFlag  = app.Flag(
		"config",
		"Location of config file.",
	).Short('c').PlaceHolder("~/crane.yaml").String()
	prefixFlag = app.Flag(
		"prefix",
		"Container prefix.",
	).Short('p').String()
	excludeFlag = app.Flag(
		"exclude",
		"Exclude group or container. Can be repeated.",
	).Short('e').PlaceHolder("container|group").Strings()
	onlyFlag = app.Flag(
		"only",
Пример #12
0
	"reflect"
	"regexp"
	"strconv"
	"strings"

	"github.com/alecthomas/kingpin"
	"github.com/inconshreveable/log15"
	"github.com/mattn/go-colorable"
	"github.com/rightscale/rsc/cm15"
	"github.com/rightscale/rsc/httpclient"
	"github.com/rightscale/rsc/log"
	"github.com/rightscale/rsc/rsapi"
)

var (
	app        = kingpin.New("right_st", "A command-line application for managing RightScripts")
	debug      = app.Flag("debug", "Debug mode").Short('d').Bool()
	configFile = app.Flag("config", "Set the config file path.").Short('c').Default(DefaultConfigFile()).String()
	account    = app.Flag("account", "RightScale account name to use").Short('a').String()

	// ----- ServerTemplates -----
	stCmd = app.Command("st", "ServerTemplate")

	stShowCmd        = stCmd.Command("show", "Show a single ServerTemplate")
	stShowNameOrHref = stShowCmd.Arg("name|href|id", "ServerTemplate Name or HREF or Id").Required().String()

	stUploadCmd    = stCmd.Command("upload", "Upload a ServerTemplate specified by a YAML document")
	stUploadPaths  = stUploadCmd.Arg("path", "File or directory containing script files to upload").Required().ExistingFilesOrDirs()
	stUploadPrefix = stUploadCmd.Flag("prefix", "Create dev/test version by adding prefix to name of all ServerTemplate and RightScripts uploaded").Short('x').String()

	stDeleteCmd    = stCmd.Command("delete", "Delete dev/test ServerTemplates and RightScripts with a prefix")
Пример #13
0
func main() {
	// Define the command-line structure using Kingpin
	var versionString = fmt.Sprintf("ceftools v%v.%v (C) 2015 Sten Linnarsson <http://linnarssonlab.org/>", ceftools.MajorVersion, ceftools.MinorVersion)

	var app = kingpin.New("cef", versionString)
	var app_bycol = app.Flag("bycol", "Apply command by columns instead of by rows").Short('c').Bool()
	var app_profile = app.Flag("profile", "Run with CPU profiling, output to the given file").String()

	var info = app.Command("info", "Show a summary of the file contents")
	var test = app.Command("test", "Perform an internal test")
	var transpose = app.Command("transpose", "Transpose rows and columns")
	var cmdimport = app.Command("import", "Import from a legacy format")
	var import_format = cmdimport.Flag("format", "The file format to expect ('strt')").Required().Short('f').String()

	var rename = app.Command("rename", "Rename attribute")
	var rename_attr = rename.Flag("attr", "The attribute to rename ('old=new')").Required().Short('c').String()

	var drop = app.Command("drop", "Remove attributes")
	var drop_attrs = drop.Flag("attrs", "Row attribute(s) to remove (case-sensitive, comma-separated)").Short('a').String()
	var drop_headers = drop.Flag("headers", "Headers to remove (case-sensitive, comma-separated)").Short('h').String()
	var drop_except = drop.Flag("except", "Keep the given attributes instead of dropping them ").Bool()

	var add = app.Command("add", "Add header or row attribute")
	var add_header = add.Flag("header", "Header to add, in the form 'name=value'").Short('h').String()
	var add_attr = add.Flag("attr", "Attribute to add, in the form 'name=value' (value can be '(row)')").Short('a').String()

	var cmdselect = app.Command("select", "Select rows that match criteria (and drop the rest)")
	var select_range = cmdselect.Flag("range", "Select a range of rows (like '10:90')").String()
	var select_where = cmdselect.Flag("where", "Select rows with specific value for attribute ('attr=value')").String()
	var select_except = cmdselect.Flag("except", "Invert selection").Bool()

	var rescale = app.Command("rescale", "Rescale values by rows")
	var rescale_method = rescale.Flag("method", "Method to use (log, tpm or rpkm)").Short('m').Required().Enum("log", "tpm", "rpkm")
	var rescale_length = rescale.Flag("length", "Indicate the name of the attribute that gives gene length (for RPKM)").String()

	var join = app.Command("join", "Join two files based on given attributes")
	var join_other = join.Flag("with", "The file to which the input should be joined").Required().String()
	var join_on = join.Flag("on", "The attributes on which to join, of form 'attr1=attr2'").Required().String()

	var sort = app.Command("sort", "Sort by row attribute or by specific column")
	var sort_by = sort.Flag("by", "The attribute or column ('column=value') to sort by").String()
	var sort_reverse = sort.Flag("reverse", "Sort in reverse order").Short('r').Bool()
	var sort_numerical = sort.Flag("numerical", "Numerical sort (default: alphabetical)").Short('n').Bool()
	var sort_spin = sort.Flag("spin", "Sort by SPIN").Bool()
	var sort_corrfile = sort.Flag("corrfile", "Optional filename where to write the sorted correlation matrix").String()

	var aggregate = app.Command("aggregate", "Calculate aggregate statistics per row")
	var aggregate_cv = aggregate.Flag("cv", "Calculate coefficient of variation (CV)").Bool()
	var aggregate_mean = aggregate.Flag("mean", "Calculate mean").Bool()
	var aggregate_stdev = aggregate.Flag("stdev", "Calculate standard deviation").Bool()
	var aggregate_max = aggregate.Flag("max", "Calculate max value").Bool()
	var aggregate_min = aggregate.Flag("min", "Calculate min value").Bool()
	var aggregate_noise = aggregate.Flag("noise", "Calculate noise (CV-vs-mean offset)").Required().Enum("std", "bands")

	var view = app.Command("view", "View the file content interactively")

	// Parse the command line
	var parsed, err = app.Parse(os.Args[1:])
	if err != nil {
		app.Usage(os.Stderr)
		return
	}

	if *app_profile != "" {
		f, err := os.Create(*app_profile)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		pprof.StartCPUProfile(f)
		defer pprof.StopCPUProfile()

	}

	// Handle the sub-commands
	switch kingpin.MustParse(parsed, nil) {
	case view.FullCommand():
		if err = ceftools.Viewer(*app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case aggregate.FullCommand():
		if err = ceftools.CmdAggregate(*aggregate_mean, *aggregate_cv, *aggregate_stdev, *aggregate_max, *aggregate_min, *aggregate_noise, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case rename.FullCommand():
		if err = ceftools.CmdRename(*rename_attr, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case add.FullCommand():
		if err = ceftools.CmdAdd(*add_attr, *add_header, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case sort.FullCommand():
		if *sort_spin {
			if err = ceftools.CmdSPIN(*sort_corrfile, *app_bycol); err != nil {
				fmt.Fprintln(os.Stderr, err)
			}
		} else {
			if err = ceftools.CmdSort(*sort_by, *sort_numerical, *sort_reverse, *app_bycol); err != nil {
				fmt.Fprintln(os.Stderr, err)
			}
		}
		return
	case join.FullCommand():
		if err = ceftools.CmdJoin(*join_other, *join_on, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case cmdimport.FullCommand():
		if *import_format == "strt" {
			if err = ceftools.CmdImportStrt(); err != nil {
				fmt.Fprintln(os.Stderr, err)
			}
		} else {
			fmt.Fprintln(os.Stderr, "Unknown format (only valid format is 'strt')")
		}
		return
	case cmdselect.FullCommand():
		if *select_range != "" {
			if *select_where != "" {
				fmt.Fprintln(os.Stderr, "Cannot select using --range and --where simultaneously (use a pipe)")
				return
			}
			temp := strings.Split(*select_range, ":")
			if len(temp) != 2 {
				fmt.Fprintln(os.Stderr, "Invalid range specification (should be like '1:10', ':20', or '100:')")
				return
			}
			from := 1
			if temp[0] != "" {
				from, err = strconv.Atoi(temp[0])
				if err != nil {
					fmt.Fprintln(os.Stderr, "Invalid range specification (should be like '1:10', ':20', or '100:')")
					return
				}
			}
			to := -1
			if temp[1] != "" {
				to, err = strconv.Atoi(temp[1])
				if err != nil {
					fmt.Fprintln(os.Stderr, "Invalid range specification (should be like '1:10', ':20', or '100:')")
					return
				}
			}
			if err := ceftools.CmdSelectRange(from, to, *app_bycol, *select_except); err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
			}
			return
		}
		if *select_where != "" {
			if err := ceftools.CmdSelect(*select_where, *app_bycol, *select_except); err != nil {
				fmt.Fprintln(os.Stderr, err.Error())
			}
			return
		}
	case transpose.FullCommand():
		// Read the input
		var cef, err = ceftools.Read(os.Stdin, true)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			return
		}
		// Write the CEF file
		if err := ceftools.Write(cef, os.Stdout, false); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case drop.FullCommand():
		if err = ceftools.CmdDrop(*drop_attrs, *drop_headers, *drop_except, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return
	case rescale.FullCommand():
		if err = ceftools.CmdRescale(*rescale_method, *rescale_length, *app_bycol); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return

	// Perform test
	case test.FullCommand():
		var cef = new(ceftools.Cef)
		cef.Columns = 5
		cef.Rows = 10
		cef.Headers = make([]ceftools.Header, 2)
		cef.Headers[0].Name = "Tissue"
		cef.Headers[0].Value = "Amygdala"
		cef.Headers[1].Name = "Species"
		cef.Headers[1].Value = "Mouse"
		cef.ColumnAttributes = make([]ceftools.Attribute, 2)
		cef.ColumnAttributes[0].Name = "CellID"
		cef.ColumnAttributes[0].Values = []string{"A", "B", "C", "D", "E"}
		cef.ColumnAttributes[1].Name = "Well"
		cef.ColumnAttributes[1].Values = []string{"A01", "B03", "C09", "D12", "E21"}
		cef.RowAttributes = make([]ceftools.Attribute, 3)
		cef.RowAttributes[0].Name = "Gene"
		cef.RowAttributes[0].Values = []string{"Actb", "Gapdh", "Synpr", "Pou3f2", "Bdnf", "Ngf", "Sox11", "Olig1", "Olig2", "Foxj1"}
		cef.RowAttributes[1].Name = "Chromosome"
		cef.RowAttributes[1].Values = []string{"Chr0", "Chr1", "Chr2", "Chr3", "Chr4", "Chr5", "Chr6", "Chr7", "Chr8", "Chr9"}
		cef.RowAttributes[2].Name = "Length"
		cef.RowAttributes[2].Values = []string{"1200", "1300", "1400", "1700", "1920", "130", "800", "7800", "1100", "200"}
		cef.Matrix = make([]float32, 10*5)
		cef.Set(0, 0, 0)
		cef.Set(1, 0, 1)
		cef.Set(2, 0, 2)
		cef.Set(3, 0, 3)
		cef.Set(4, 0, 4)
		cef.Set(5, 0, 5)
		cef.Set(6, 0, 6)
		cef.Set(7, 0, 7)
		cef.Set(8, 0, 8)
		cef.Set(9, 0, 9)
		ceftools.Permute(cef, []int{0, 4, 2, 3, 1, 5, 6, 7, 8, 9}, []int{4, 3, 0, 1, 2})
		if err := ceftools.Write(cef, os.Stdout, false); err != nil {
			fmt.Fprintln(os.Stderr, err)
		}
		return

	// Show info
	case info.FullCommand():
		var cef, err = ceftools.Read(os.Stdin, *app_bycol)
		if err != nil {
			fmt.Fprintln(os.Stderr, err.Error())
			return
		}
		fmt.Fprintf(os.Stderr, "          Columns: %v\n", cef.Columns)
		fmt.Fprintf(os.Stderr, "             Rows: %v\n", cef.Rows)
		fmt.Fprintf(os.Stderr, "            Flags: %v\n", cef.Flags)
		fmt.Fprintln(os.Stderr, "          Headers:")
		for i := 0; i < len(cef.Headers); i++ {
			fmt.Fprint(os.Stderr, "                   ")
			fmt.Fprint(os.Stderr, cef.Headers[i].Name)
			fmt.Fprint(os.Stderr, " = ")
			fmt.Fprintf(os.Stderr, cef.Headers[i].Value)
			fmt.Fprint(os.Stderr, "\n")
		}
		fmt.Fprint(os.Stderr, "\n")
		fmt.Fprint(os.Stderr, "Column attributes: ")
		for i := 0; i < len(cef.ColumnAttributes); i++ {
			fmt.Fprint(os.Stderr, cef.ColumnAttributes[i].Name)
			if i != (len(cef.ColumnAttributes) - 1) {
				fmt.Fprint(os.Stderr, ", ")
			}
		}
		fmt.Fprint(os.Stderr, "\n")
		fmt.Fprint(os.Stderr, "   Row attributes: ")
		for i := 0; i < len(cef.RowAttributes); i++ {
			fmt.Fprint(os.Stderr, cef.RowAttributes[i].Name)
			if i != (len(cef.RowAttributes) - 1) {
				fmt.Fprint(os.Stderr, ", ")
			}
		}
		fmt.Fprintln(os.Stderr, "")
		return
	default:
		kingpin.Usage()
	}
}
Пример #14
0
Файл: bnp.go Проект: pmezard/bnp
package main

import (
	"fmt"
	"os"

	"github.com/alecthomas/kingpin"
)

var (
	app = kingpin.New("apec", "BNP Paribas reports crawler and charter")
)

func dispatch() error {
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))
	switch cmd {
	case parseCmd.FullCommand():
		return parseFn()
	case webCmd.FullCommand():
		return webFn()
	}
	return nil
}

func main() {
	err := dispatch()
	if err != nil {
		fmt.Fprintf(os.Stderr, "error: %s\n", err)
		os.Exit(1)
	}
}
Пример #15
0
package main

import (
	"log"
	"os"
	"runtime"
	"runtime/pprof"

	"github.com/alecthomas/kingpin"
)

var (
	app     = kingpin.New("pcorr", "A command-line application for correlation calculation.")
	debug   = app.Flag("debug", "Enable debug mode.").Bool()
	ncpu    = app.Flag("ncpu", "number of CPUs for using").Default("1").Int()
	profile = app.Flag("profile", "cpu and heap profile file").Default("").String()

	pileupApp       = app.Command("pileup", "pileup reads")
	pileupMinBQ     = pileupApp.Flag("min-BQ", "minimum base quality").Short('Q').Default("13").Int()
	pileupMinMQ     = pileupApp.Flag("min-MQ", "minimum mapping quality").Short('q').Default("0").Int()
	pileupOutFile   = pileupApp.Flag("outfile", "output file").Short('o').Default("").String()
	pileupFastaFile = pileupApp.Flag("fastafile", "genome fasta file").Short('f').Default("").String()
	pileupBamFile   = pileupApp.Arg("bamfile", "bam file of reads").Required().String()

	piApp         = app.Command("pi", "calculate pi")
	piMinBQ       = piApp.Flag("min-BQ", "minimum base quality").Short('Q').Default("13").Int()
	piMinCoverage = piApp.Flag("min-coverage", "minimum base coverage").Short('c').Default("10").Int()
	piFormat      = piApp.Flag("pileup-formate", "pileup formate").Short('F').Default("tab").String()
	piOutFile     = piApp.Flag("output", "output file").Short('o').Default("").String()
	piRegionStart = piApp.Flag("region-start", "region start").Short('S').Default("0").Int()
	piRegionEnd   = piApp.Flag("region-end", "region end").Short('E').Default("0").Int()
Пример #16
0
package main

import (
	"bufio"
	"fmt"
	"math/rand"

	"os"

	"github.com/alecthomas/kingpin"
	"github.com/couchbaselabs/logg"
	"github.com/tleyden/open-ocr-client"
)

var (
	app           = kingpin.New("open-ocr-client", "A command-line chat application.")
	stress        = app.Command("stress", "Do a stress test")
	upload        = app.Command("upload", "Upload a file to ocr")
	ocrUrl        = app.Flag("openOcrUrl", "URL where OpenOCR endpoint located").Default("http://api.openocr.net").String()
	ocrPort       = app.Flag("openOcrPort", "Port where OpenOCR endpoint located").Default("8080").Int()
	ocrFile       = upload.Flag("file", "File to ocr").Default("ocr_test.png").String()
	numIterations = stress.Arg("numIterations", "how many OCR jobs should each goroutine create?").Default("5").Int()
	numGoroutines = stress.Arg("numGoroutines", "how many goroutines should be launched?").Default("1").Int()

	numTestImages = 7
)

func init() {
	logg.LogKeys["CLI"] = true
	logg.LogKeys["OCRCLIENT"] = true
}
Пример #17
0
)

const (
	appName    = "gjoa"
	appVersion = "0.1"
	timeLayout = time.RFC3339
)

var (
	props      *Properties
	logDir     *string
	modelTypes = []string{"Gaussian", "GMM", "HMM"}
)

var (
	app         = kingpin.New(appName, "Gjøa statistical modeling command-line tool. (https://github.com/akualab/gjoa)")
	debug       = app.Flag("debug", "Enable debug mode.").Bool()
	logToStderr = app.Flag("log-stderr", "Logs are written to standard error instead of files.").Default("true").Bool()
	vLevel      = app.Flag("log-level", "Enable V-leveled logging at the specified level.").Default("0").Short('v').String()
	//	modelType   = app.Flag("model", "Model type.").Short('m').Enum(modelTypes...)
	inputModel = app.Flag("input-model", "An input model file.").Short('i').File()
	dataFile   = app.Flag("data", "Data file. See manual for format details.").File()
	dataDir    = app.Flag("dir", "Data dir. See manual for format details.").ExistingDir()
	dim        = app.Flag("dim", "Dimension of the feature vectors.").Int()
	modelName  = app.Flag("model-name", "Name of the model.").String()
	dictFile   = app.Flag("dict", "Dictionary file maps transcription names to model names.").File()

	config    = app.Command("config", "Updates fields in properties file.")
	configMap = config.Arg("properties", "Set properties.").StringMap()

	rand     = app.Command("rand", "Generate random data using model.")
Пример #18
0
}

// IsCumulative specifies S3List as a cumulative argument
func (s *s3List) IsCumulative() bool {
	return true
}

// S3List creates a new S3List kingpin setting
func S3List(s kingpin.Settings) (target *[]string) {
	target = new([]string)
	s.SetValue((*s3List)(target))
	return
}

var (
	app = kingpin.New("fasts3", "Multi-threaded s3 utility")

	ls            = app.Command("ls", "List s3 prefixes.")
	lsS3Uri       = ls.Arg("s3uri", "paritial s3 uri to list, ex: s3://mary/had/a/little/lamb/").Required().String()
	lsRecurse     = ls.Flag("recursive", "Get all keys for this prefix.").Short('r').Bool()
	lsSearchDepth = ls.Flag("search-depth", "search depth to search for work.").Default("0").Int()
	humanReadable = ls.Flag("human-readable", "human readable key size.").Short('H').Bool()
	withDate      = ls.Flag("with-date", "include the last modified date.").Short('d').Bool()

	del            = app.Command("del", "Delete s3 keys")
	delPrefixes    = S3List(del.Arg("prefixes", "1 or more partial s3 uris to delete delimited by space"))
	delRecurse     = del.Flag("recursive", "Delete all keys with prefix").Short('r').Bool()
	delSearchDepth = del.Flag("search-depth", "search depth to search for work.").Default("0").Int()

	get            = app.Command("get", "Fetch files from s3")
	getS3Uris      = S3List(get.Arg("prefixes", "list of prefixes or s3Uris to retrieve"))
Пример #19
0
package main

import (
	"fmt"
	"github.com/alecthomas/kingpin"
	"os"
	"runtime"
	"sync"
)

var (
	app          = kingpin.New("gosync", "A tool to sync a directory over a high-speed network.")
	mainPort     = app.Flag("port", "port number to listen or connect to when syncing").Short('p').Default("32011").Uint64()
	bufferSize   = app.Flag("buffer", "The size (in kB) of the buffer for sending/receiving.").Short('b').Default("131072").Int()
	hostCommand  = app.Command("host", "Make a directory available on the network.")
	hostPath     = hostCommand.Arg("path", "The directory to host.").Default(".").ExistingDir()
	hostHttp     = hostCommand.Flag("http", "Host the directory via http in addition to gosync.").Default("true").Bool()
	hostHttpAddr = hostCommand.Flag("http-addr", "The address to start the http server on").Default(":32080").String()
	recvCommand  = app.Command("recv", "Sync a directory from the network, locally.")
	recvPath     = recvCommand.Arg("path", "The directory to sync into.").Default(".").File()
	recvHost     = recvCommand.Flag("host", "Specify a direct address to connect to.").String()
)

func StartHost() {
	var wg sync.WaitGroup
	if *hostHttp {
		wg.Add(1)
		go func() {
			HostHTTP(*hostPath, *hostHttpAddr)
			wg.Done()
		}()
Пример #20
0
func main() {
	app := kingpin.New("modular", "My modular application.")
	configureLsCommand(app)
	kingpin.MustParse(app.Parse(os.Args[1:]))
}
Пример #21
0
	"os"
	"path"
	"path/filepath"
	"strings"

	"github.com/alecthomas/kingpin"
	"github.com/couchbaselabs/logg"
	et "github.com/tleyden/elastic-thought"
)

/*
Tool for converting input data from one form to another
*/

var (
	app         = kingpin.New("data converter", "A command-line tool for converting data.")
	flat2folder = app.Command("flat2folder", "Take a flat list of files + an index and convert to folder labels")

	sourceDir  = flat2folder.Flag("sourceDir", "Directory with source files").String()
	labelIndex = flat2folder.Flag("labelIndex", "File with file -> label mapping").String()
	destDir    = flat2folder.Flag("destDir", "Destination directory for output folders").String()
)

func init() {
	logg.LogKeys["DATA_CONVERTER"] = true
}

func main() {
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	case "flat2folder":
		logg.LogTo("DATA_CONVERTER", "do flat2folder")
Пример #22
0
package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"

	"gopkg.in/inconshreveable/log15.v2"

	"github.com/alecthomas/kingpin"
	"github.com/yuin/gopher-lua"
)

var (
	app            = kingpin.New("listless", "A simple, lua-scripted discussion/mailing list driver over IMAP/SMTP")
	loopMode       = app.Command("loop", "Run the mailing list from a lua configuration file.")
	loopConfigfile = loopMode.Arg("configfile", "Location of config file.").Required().String()

	execMode       = app.Command("exec", "Execute a lua script in the context of a (separate) lua configuration file.")
	execConfigfile = execMode.Arg("configfile", "Location of config file.").Required().String()
	execScript     = execMode.Arg("script", "Location of lua script to execute.").Required().String()

	subMode = app.Command("sub", "Without another command, print subscriber list")

	subListMode    = subMode.Command("list", "List subscribers")
	subLConfigFile = subListMode.Arg("configfile", "Location of config file.").Required().String()

	subUpdateAction = subMode.Command("update", "Add or edit a subscriber")
	subUConfigFile  = subUpdateAction.Arg("configfile", "Location of config file").Required().String()
	subUEmail       = subUpdateAction.Flag("email", "Email address to add or update details for").Required().String()
Пример #23
0
package main

import (
	"blob"
	"errors"
	"fmt"
	"os"

	"github.com/alecthomas/kingpin"
)

var (
	cli        = kingpin.New("blobstore", "file storage api")
	version    = cli.Version("0.0.1")
	verbose    = cli.Flag("verbose", "Verbose mode.").Short('v').Bool()
	secretKey  = cli.Flag("secret", "Secret key used during authentication").Default("").String()
	clientAddr = cli.Flag("endpoint", "Address and port to connect to when in client mode").Default("http://blobstore.kiloe.net").String()

	server             = cli.Command("start", "Start HTTP API service")
	serverAddr         = server.Flag("listen", "Address and port to listen on").Default(":7000").String()
	serverStateDir     = server.Flag("state", "Path to state dir where blobs will be stored").Default("/var/state").ExistingDir()
	serverMaxUploadMem = server.Flag("max-memory", "Megabytes allowed for file uploads before buffering to disk").Default("32").Int64()
	serverMaxBlobSize  = server.Flag("max-size", "Megabyte limit on blob size").Default("128").Int64()

	put      = cli.Command("put", "Store file in the blobstore")
	putFiles = put.Arg("files", "Path to upload to blobstore").Required().ExistingFile()

	get   = cli.Command("get", "Fetch blob data by ID")
	getID = get.Arg("id", "ID of blob to fetch").Required().String()

	info   = cli.Command("info", "Fetch blob info by ID")
Пример #24
0
package main

import (
	"os"
	"strings"

	"github.com/alecthomas/kingpin"
)

var (
	app      = kingpin.New("chat", "A command-line chat application.")
	debug    = app.Flag("debug", "Enable debug mode.").Bool()
	serverIP = app.Flag("server", "Server address.").Default("127.0.0.1").IP()

	register     = app.Command("register", "Register a new user.")
	registerNick = register.Arg("nick", "Nickname for user.").Required().String()
	registerName = register.Arg("name", "Name of user.").Required().String()

	post        = app.Command("post", "Post a message to a channel.")
	postImage   = post.Flag("image", "Image to post.").File()
	postChannel = post.Arg("channel", "Channel to post to.").Required().String()
	postText    = post.Arg("text", "Text to post.").Strings()
)

func main() {
	switch kingpin.MustParse(app.Parse(os.Args[1:])) {
	// Register user
	case register.FullCommand():
		println(*registerNick)

	// Post message
Пример #25
0
package crane

import (
	"fmt"
	"os"
	"strings"

	"github.com/alecthomas/kingpin"
)

var cfg Config
var excluded []string

var (
	app          = kingpin.New("crane", "Lift containers with ease")
	interspersed = app.Interspersed(false)
	verboseFlag  = app.Flag("verbose", "Enable verbose output.").Short('v').Bool()
	configFlag   = app.Flag(
		"config",
		"Location of config file.",
	).Short('c').OverrideDefaultFromEnvar("CRANE_CONFIG").PlaceHolder("~/crane.yaml").String()
	prefixFlag = app.Flag(
		"prefix",
		"Container prefix.",
	).Short('p').OverrideDefaultFromEnvar("CRANE_PREFIX").String()
	excludeFlag = app.Flag(
		"exclude",
		"Exclude group or container",
	).Short('e').OverrideDefaultFromEnvar("CRANE_EXCLUDE").String()

	liftCommand = app.Command(
Пример #26
0
func main() {
	// Load htraced configuration
	cnf := common.LoadApplicationConfig()

	// Parse argv
	app := kingpin.New(os.Args[0], USAGE)
	app.Flag("Dmy.key", "Set configuration key 'my.key' to 'my.value'.  Replace 'my.key' "+
		"with any key you want to set.").Default("my.value").String()
	addr := app.Flag("addr", "Server address.").String()
	verbose = app.Flag("verbose", "Verbose.").Default("false").Bool()
	version := app.Command("version", "Print the version of this program.")
	serverInfo := app.Command("serverInfo", "Print information retrieved from an htraced server.")
	serverStats := app.Command("serverStats", "Print statistics retrieved from the htraced server.")
	serverStatsJson := serverStats.Flag("json", "Display statistics as raw JSON.").Default("false").Bool()
	findSpan := app.Command("findSpan", "Print information about a trace span with a given ID.")
	findSpanId := findSpan.Arg("id", "Span ID to find. Example: be305e54-4534-2110-a0b2-e06b9effe112").Required().String()
	findChildren := app.Command("findChildren", "Print out the span IDs that are children of a given span ID.")
	parentSpanId := findChildren.Arg("id", "Span ID to print children for. Example: be305e54-4534-2110-a0b2-e06b9effe112").
		Required().String()
	childLim := findChildren.Flag("lim", "Maximum number of child IDs to print.").Default("20").Int()
	loadFile := app.Command("loadFile", "Write whitespace-separated JSON spans from a file to the server.")
	loadFilePath := loadFile.Arg("path",
		"A file containing whitespace-separated span JSON.").Required().String()
	loadJson := app.Command("load", "Write JSON spans from the command-line to the server.")
	loadJsonArg := loadJson.Arg("json", "A JSON span to write to the server.").Required().String()
	dumpAll := app.Command("dumpAll", "Dump all spans from the htraced daemon.")
	dumpAllOutPath := dumpAll.Arg("path", "The path to dump the trace spans to.").Default("-").String()
	dumpAllLim := dumpAll.Flag("lim", "The number of spans to transfer from the server at once.").
		Default("100").Int()
	graph := app.Command("graph", "Visualize span JSON as a graph.")
	graphJsonFile := graph.Arg("input", "The JSON file to load").Required().String()
	graphDotFile := graph.Flag("output",
		"The path to write a GraphViz dotfile to.  This file can be used as input to "+
			"GraphViz, in order to generate a pretty picture.  See graphviz.org for more "+
			"information about generating pictures of graphs.").Default("-").String()
	query := app.Command("query", "Send a query to htraced.")
	queryLim := query.Flag("lim", "Maximum number of spans to retrieve.").Default("20").Int()
	queryArg := query.Arg("query", "The query string to send.  Query strings have the format "+
		"[TYPE] [OPERATOR] [CONST], joined by AND statements.").Required().String()
	rawQuery := app.Command("rawQuery", "Send a raw JSON query to htraced.")
	rawQueryArg := query.Arg("json", "The query JSON to send.").Required().String()
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))

	// Add the command-line settings into the configuration.
	if *addr != "" {
		cnf = cnf.Clone(conf.HTRACE_WEB_ADDRESS, *addr)
	}

	// Handle commands that don't require an HTrace client.
	switch cmd {
	case version.FullCommand():
		os.Exit(printVersion())
	case graph.FullCommand():
		err := jsonSpanFileToDotFile(*graphJsonFile, *graphDotFile)
		if err != nil {
			fmt.Printf("graphing error: %s\n", err.Error())
			os.Exit(EXIT_FAILURE)
		}
		os.Exit(EXIT_SUCCESS)
	}

	// Create HTrace client
	hcl, err := htrace.NewClient(cnf)
	if err != nil {
		fmt.Printf("Failed to create HTrace client: %s\n", err.Error())
		os.Exit(EXIT_FAILURE)
	}

	// Handle commands that require an HTrace client.
	switch cmd {
	case version.FullCommand():
		os.Exit(printVersion())
	case serverInfo.FullCommand():
		os.Exit(printServerInfo(hcl))
	case serverStats.FullCommand():
		if *serverStatsJson {
			os.Exit(printServerStatsJson(hcl))
		} else {
			os.Exit(printServerStats(hcl))
		}
	case findSpan.FullCommand():
		var id *common.SpanId
		id.FromString(*findSpanId)
		os.Exit(doFindSpan(hcl, *id))
	case findChildren.FullCommand():
		var id *common.SpanId
		id.FromString(*parentSpanId)
		os.Exit(doFindChildren(hcl, *id, *childLim))
	case loadJson.FullCommand():
		os.Exit(doLoadSpanJson(hcl, *loadJsonArg))
	case loadFile.FullCommand():
		os.Exit(doLoadSpanJsonFile(hcl, *loadFilePath))
	case dumpAll.FullCommand():
		err := doDumpAll(hcl, *dumpAllOutPath, *dumpAllLim)
		if err != nil {
			fmt.Printf("dumpAll error: %s\n", err.Error())
			os.Exit(EXIT_FAILURE)
		}
		os.Exit(EXIT_SUCCESS)
	case query.FullCommand():
		err := doQueryFromString(hcl, *queryArg, *queryLim)
		if err != nil {
			fmt.Printf("query error: %s\n", err.Error())
			os.Exit(EXIT_FAILURE)
		}
		os.Exit(EXIT_SUCCESS)
	case rawQuery.FullCommand():
		err := doRawQuery(hcl, *rawQueryArg)
		if err != nil {
			fmt.Printf("raw query error: %s\n", err.Error())
			os.Exit(EXIT_FAILURE)
		}
		os.Exit(EXIT_SUCCESS)
	}

	app.UsageErrorf(os.Stderr, "You must supply a command to run.")
}
Пример #27
0
package main

import (
	"fmt"
	"os"
	"path/filepath"

	"github.com/alecthomas/kingpin"
	"github.com/pkg/profile"
)

var (
	app     = kingpin.New("apec", "APEC crawler, indexer and query tool")
	dataDir = app.Flag("data", "data directory").Default("offers").String()
	prof    = app.Flag("profile", "enable profiling").Bool()
)

type Config struct {
	RootDir string
}

func NewConfig(rootDir string) *Config {
	return &Config{
		RootDir: rootDir,
	}
}

func (d *Config) Store() string {
	return filepath.Join(d.RootDir, "offers")
}
Пример #28
0
package main

import (
	"github.com/alecthomas/kingpin"
	"github.com/bmatsuo/lmdb-go/lmdb"
	"os"
	"runtime"
)

var (
	app   = kingpin.New("pileup", "A command-line application for reading pileup file.")
	debug = app.Flag("debug", "Enable debug mode.").Bool()
	ncpu  = app.Flag("ncpu", "number of CPUs for using.").Default("0").Int()

	filterApp       = app.Command("filter", "filter reads.")
	filterFeatureDB = filterApp.Arg("feature_db_path", "feature db path.").Required().String()
	filterBam       = filterApp.Arg("bam_file", "bam file.").Required().String()
	filterOut       = filterApp.Arg("out_file", "out file.").Required().String()
	filterMaxDist   = filterApp.Flag("max_dist", "max distance.").Default("0.05").Float64()
	filterMapQ      = filterApp.Flag("mapQ", "min mapQ").Default("30").Int()

	featApp = app.Command("feat", "read and load genome sequence and features into a LMDB.")
	featDir = featApp.Arg("genome_dir", "genome directory").Required().String()
	featOut = featApp.Arg("feature_db_path", "feature db path").Required().String()

	readApp      = app.Command("read", "read samtools mpileup results.")
	pileupFile   = readApp.Arg("pileup_file", "pileup file.").Required().String()
	readFeature  = readApp.Arg("feature_db_path", "feature db path").Required().String()
	readOut      = readApp.Arg("results_db_path", "results db path").Required().String()
	readMinDepth = readApp.Flag("min_depth", "min depth").Default("5").Int()
	readMinCover = readApp.Flag("min_coverage", "min coverage").Default("0.8").Float64()
Пример #29
0
/* TODO:
 * Enable server restarts without dropping connections
 * Server should properly route streams destined for a specific user
 */
package main

import (
	"fmt"
	"github.com/alecthomas/kingpin"
	"os"
	"time"
)

var (
	app     = kingpin.New("server", "DVAP Bridge Server")
	debug   = app.Flag("debug", "Enable debug mode").Short('d').Bool()
	logfile = app.Flag("logfile", "Log data to file").Short('l').String()
)

func Printf(format string, a ...interface{}) {
	fmt.Printf("[%s] ", time.Now().Format(time.RFC822Z))
	fmt.Printf(format, a...)
}

func main() {
	kingpin.MustParse(app.Parse(os.Args[1:]))
	server := NewServer()

	if *logfile != "" {
		server.SetLogfile(*logfile)
Пример #30
0
func main() {
	// Load the htraced configuration.
	// This also parses the -Dfoo=bar command line arguments and removes them
	// from os.Argv.
	cnf, cnfLog := conf.LoadApplicationConfig("htraced.")

	// Parse the remaining command-line arguments.
	app := kingpin.New(os.Args[0], USAGE)
	version := app.Command("version", "Print server version and exit.")
	cmd := kingpin.MustParse(app.Parse(os.Args[1:]))

	// Handle the "version" command-line argument.
	if cmd == version.FullCommand() {
		fmt.Printf("Running htraced %s [%s].\n", RELEASE_VERSION, GIT_VERSION)
		os.Exit(0)
	}

	// Open the HTTP port.
	// We want to do this first, before initializing the datastore or setting up
	// logging.  That way, if someone accidentally starts two daemons with the
	// same config file, the second invocation will exit with a "port in use"
	// error rather than potentially disrupting the first invocation.
	rstListener, listenErr := net.Listen("tcp", cnf.Get(conf.HTRACE_WEB_ADDRESS))
	if listenErr != nil {
		fmt.Fprintf(os.Stderr, "Error opening HTTP port: %s\n",
			listenErr.Error())
		os.Exit(1)
	}

	// Print out the startup banner and information about the daemon
	// configuration.
	lg := common.NewLogger("main", cnf)
	defer lg.Close()
	lg.Infof("*** Starting htraced %s [%s]***\n", RELEASE_VERSION, GIT_VERSION)
	scanner := bufio.NewScanner(cnfLog)
	for scanner.Scan() {
		lg.Infof(scanner.Text() + "\n")
	}
	common.InstallSignalHandlers(cnf)
	if runtime.GOMAXPROCS(0) == 1 {
		ncpu := runtime.NumCPU()
		runtime.GOMAXPROCS(ncpu)
		lg.Infof("setting GOMAXPROCS=%d\n", ncpu)
	} else {
		lg.Infof("GOMAXPROCS=%d\n", runtime.GOMAXPROCS(0))
	}
	lg.Infof("leveldb version=%d.%d\n",
		levigo.GetLevelDBMajorVersion(), levigo.GetLevelDBMinorVersion())

	// Initialize the datastore.
	store, err := CreateDataStore(cnf, nil)
	if err != nil {
		lg.Errorf("Error creating datastore: %s\n", err.Error())
		os.Exit(1)
	}
	var rsv *RestServer
	rsv, err = CreateRestServer(cnf, store, rstListener)
	if err != nil {
		lg.Errorf("Error creating REST server: %s\n", err.Error())
		os.Exit(1)
	}
	var hsv *HrpcServer
	if cnf.Get(conf.HTRACE_HRPC_ADDRESS) != "" {
		hsv, err = CreateHrpcServer(cnf, store, nil)
		if err != nil {
			lg.Errorf("Error creating HRPC server: %s\n", err.Error())
			os.Exit(1)
		}
	} else {
		lg.Infof("Not starting HRPC server because no value was given for %s.\n",
			conf.HTRACE_HRPC_ADDRESS)
	}
	naddr := cnf.Get(conf.HTRACE_STARTUP_NOTIFICATION_ADDRESS)
	if naddr != "" {
		notif := StartupNotification{
			HttpAddr:  rsv.Addr().String(),
			ProcessId: os.Getpid(),
		}
		if hsv != nil {
			notif.HrpcAddr = hsv.Addr().String()
		}
		err = sendStartupNotification(naddr, &notif)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to send startup notification: "+
				"%s\n", err.Error())
			os.Exit(1)
		}
	}
	for {
		time.Sleep(time.Duration(10) * time.Hour)
	}
}