Exemplo n.º 1
0
func cliSetup() *cliOptions {

	options := newCliOptions()

	var httpVerb = goopt.StringWithLabel([]string{"-X", "--command"}, options.httpVerb,
		"COMMAND", fmt.Sprintf("HTTP verb for request: %s", HttpVerbs))
	var httpHeaders = goopt.Strings([]string{"-H", "--header"},
		"KEY:VALUE", "Custom HTTP Headers to be sent with request (can pass multiple times)")
	var postData = goopt.StringWithLabel([]string{"-d", "--data"}, options.postData,
		"DATA", "HTTP Data for POST")
	var timeOut = goopt.IntWithLabel([]string{"-t", "--timeout"}, options.timeout,
		"TIMEOUT", "Timeout in seconds for request")
	var shouldRedirect = goopt.Flag([]string{"-r", "--redirect"}, []string{}, "Follow redirects", "")
	var isVerbose = goopt.Flag([]string{"-v", "--verbose"}, []string{}, "Verbose output", "")
	var hasColor = goopt.Flag([]string{"-c", "--color"}, []string{}, "Colored output", "")
	var isInsecureSSL = goopt.Flag([]string{"-k", "--insecure"}, []string{}, "Allow insecure https connections", "")

	goopt.Summary = "Golang based http client program"
	goopt.Parse(nil)

	options.httpVerb = *httpVerb
	options.httpHeaders = *httpHeaders
	options.postData = *postData
	options.timeout = *timeOut
	options.verbose = *isVerbose
	options.redirect = *shouldRedirect
	options.color = *hasColor
	options.sslInsecure = *isInsecureSSL
	options.arguments = goopt.Args

	exitWithMessageIfNonZero(validateOptions(options))
	exitWithMessageIfNonZero(validateArguments(options))

	return options
}
Exemplo n.º 2
0
func main() {
	var no_cog = goopt.Flag([]string{"-C", "--no-cog"}, []string{"-c", "--cog"},
		"skip opening in cog", "open in cog")
	var no_delete = goopt.Flag([]string{"-D", "--no-delete"}, []string{"-d", "--delete"},
		"skip deleting original zip", "delete original zip")
	goopt.Parse(nil)

	boomkat(goopt.Args[0], *no_cog, *no_delete)

}
Exemplo n.º 3
0
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Rmdir"
	goopt.Summary = "Remove each DIRECTORY if it is empty"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... DIRECTORY...\n", os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	ignorefail := goopt.Flag([]string{"--ignore-fail-on-non-empty"}, nil,
		"Ignore each failure that is from a directory not being empty", "")
	parents := goopt.Flag([]string{"-p", "--parents"}, nil, "Remove DIRECTORY and ancestors if ancestors become empty", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each directory as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	for i := range goopt.Args {
		filelisting, err := ioutil.ReadDir(goopt.Args[i])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to remove %s: %v\n", os.Args[i+1], err)
			defer os.Exit(1)
			continue
		}
		if !*ignorefail && len(filelisting) > 0 {
			fmt.Fprintf(os.Stderr, "Failed to remove '%s' directory is non-empty\n", goopt.Args[i])
			defer os.Exit(1)
			continue
		}
		if *verbose {
			fmt.Printf("Removing directory %s\n", goopt.Args[i])
		}
		err = os.Remove(goopt.Args[i])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to remove %s: %v\n", goopt.Args[i], err)
			defer os.Exit(1)
			continue
		}
		if !*parents {
			continue
		}
		dir := goopt.Args[i]
		if dir[len(dir)-1] == '/' {
			dir = filepath.Dir(dir)
		}
		if removeEmptyParents(dir, *verbose, *ignorefail) {
			defer os.Exit(1)
		}
	}
	return
}
Exemplo n.º 4
0
func main() {
	atime = time.Now()
	mtime = time.Now()
	goopt.Author = "William Pearson"
	goopt.Version = "Touch"
	goopt.Summary = "Change access or modification time of each FILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... FILE...\n", os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	access := goopt.Flag([]string{"-a"}, nil, "Only change access time", "")
	modify := goopt.Flag([]string{"-m"}, nil, "Only change modification time", "")
	create := goopt.Flag([]string{"-c"}, nil, "Only change modification time", "")
	Nodereference = goopt.Flag([]string{"-h", "--no-dereference"}, []string{"--derference"}, "Affect symbolic links directly instead of dereferencing them", "Dereference symbolic links before operating on them (This is default)")
	goopt.OptArg([]string{"-r", "--reference"}, "RFILE", "Use RFILE's owner and group", fromReference)
	goopt.OptArg([]string{"-t"}, "STAMP", "Use [[CC]YY]MMDDhhmm[.ss] instead of now. Note hh is interpreted as from 00 to 23", fromStamp)
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	coreutils.Noderef = *Nodereference
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	if !*access && !*modify {
		*access, *modify = true, true
	}
	for i := range goopt.Args {
		if !*access {
			atime, _ = GetAtimeMtime(goopt.Args[i], *Nodereference)
		}
		if !*modify {
			_, mtime = GetAtimeMtime(goopt.Args[i], *Nodereference)
		}
		if err := os.Chtimes(goopt.Args[i], atime, mtime); err != nil {
			if os.IsNotExist(err) {
				var err error
				if !*create {
					f, err := os.Create(goopt.Args[i])
					if err == nil {
						f.Close()
					}
				}
				if err == nil {
					continue
				}
			}
			fmt.Fprintf(os.Stderr, "Error touching file '%s': %v\n", goopt.Args[i], err)
		}
	}
	return
}
Exemplo n.º 5
0
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Chmod"
	goopt.Summary = "Change file mode of each FILE to MODE\nWith reference, change file mode of each FILE to that of RFILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... [MODE] FILE...\n or:\t%s [OPTION]... --reference=RFILE FILE...\n", os.Args[0], os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	silent := goopt.Flag([]string{"-f", "--silent", "--quiet"}, nil, "Suppress most error messages", "")
	/*changes := goopt.Flag([]string{"-c", "--changes"}, nil, "Like verbose but only report changes", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")*/
	nodereference := goopt.Flag([]string{"-h", "--no-dereference"}, []string{"--derference"}, "Affect symbolic links directly instead of dereferencing them", "Dereference symbolic links before operating on them (This is default)")
	preserveroot := goopt.Flag([]string{"--preserve-root"}, []string{"--no-preserve-root"}, "Don't recurse on '/'", "Treat '/' normally (This is default)")
	goopt.OptArg([]string{"--reference"}, "RFILE", "Use RFILE's owner and group", fromReference)
	recurse := goopt.Flag([]string{"-R", "--recursive"}, nil, "Operate recursively on files and directories", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	coreutils.Noderef = *nodereference
	coreutils.Preserveroot = *preserveroot
	if !usingreference {
		coreutils.ParseMode(goopt.Args[0])
	}
	var filestomod []string
	for i := range goopt.Args[1:] {
		filestomod = append(filestomod, goopt.Args[i+1])
		if *recurse && (!*preserveroot || goopt.Args[i+1] != "/") {
			if coreutils.Recurse(&filestomod) {
				defer os.Exit(1)
			}
		}
	}
	for i := range filestomod {
		err := os.Chmod(filestomod[i], coreutils.Mode)
		if err != nil && !*silent {
			fmt.Fprintf(os.Stderr, "Error changing mode for file '%s': %v\n", filestomod[i], err)
			defer os.Exit(1)
			continue
		}
	}
	return
}
Exemplo n.º 6
0
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Echo"
	goopt.Summary = "Echo ARGs to stdout."
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [SHORT-OPTION] ARGS...\n or:\t%s LONG-OPTION\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nValid backslash escape sequences go here."
	}
	goopt.NoArg([]string{"-v", "--version"}, "outputs version information and exits", coreutils.Version)
	newline := goopt.Flag([]string{"-n"}, nil, "Don't print out a newline after ARGS", "")
	backslashescape := goopt.Flag([]string{"-e"}, []string{"-E"}, "Enable interpretation of backslash escapes", "Disable interpretation of backslash escapes")

	goopt.Parse(nil)
	argstring := strings.Join(goopt.Args, " ")
	if *backslashescape {
		argstring = fmt.Sprintf("%q", argstring)
		argstring = strings.Replace(argstring, "\\\\", "\\", -1)
		validEscapeSeqs := "\\abcefnrtv0x"
		for i := 0; i < len(argstring); i++ {
			if argstring[i] != '\\' {
				continue
			}
			if !strings.Contains(validEscapeSeqs, string(argstring[i+1])) {
				argstring = argstring[:i] + "\\" + argstring[i:]
			}
			i++
		}
		backslashstring, err := strconv.Unquote(argstring)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error encountered when interpreting escape sequences: %v\n", err)
			os.Exit(1)
		}
		argstring = backslashstring
	}
	nl := "\n"
	if *newline {
		nl = ""
	}
	fmt.Printf("%s%s", argstring, nl)
	return
}
Exemplo n.º 7
0
func main() {
	coreutils.Mode = 1<<31 | coreutils.Mode
	goopt.Author = "William Pearson"
	goopt.Version = "Mkdir"
	goopt.Summary = "Create each DIRECTORY, if it does not already exist."
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... DIRECTORY...\n", os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	goopt.OptArg([]string{"-m", "--mode"}, "MODE", "Set file mode permissions", coreutils.ParseMode)
	parents := goopt.Flag([]string{"-p", "--parents"}, nil, "Make parent directories as needed, no error if existing", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each directory as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	for i := range goopt.Args {
		if *parents {
			if createParents(goopt.Args[i], *verbose) {
				defer os.Exit(1)
			}
			continue
		}
		if *verbose {
			fmt.Printf("Creating directory %s\n", goopt.Args[i])
		}
		err := os.Mkdir(goopt.Args[i], coreutils.Mode)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error creating direction %s: %v\n", goopt.Args[i], err)
			defer os.Exit(1)
		}
	}
	return
}
Exemplo n.º 8
0
func init() {
	format = goopt.String([]string{"--fmt", "--format"}, "",
		"Log format (e.g. '$remote_addr [$time_local] \"$request\"')")
	nginxConfig = goopt.String([]string{"--nginx"}, "",
		"Nginx config to look for 'log_format' directive. You also should specify --nginx-format")
	nginxFormat = goopt.String([]string{"--nginx-format"}, "",
		"Name of nginx 'log_format', should be passed with --nginx option")
	aggField = goopt.String([]string{"-a", "--aggregate"}, "request_time",
		"Nginx access log variable to aggregate")
	groupBy = goopt.String([]string{"-g", "--group-by"}, "request",
		"Nginx access log variable to group by")
	groupByRegexp = goopt.String([]string{"-r", "--regexp"}, "",
		"You can specify regular expression to extract exact data from group by data. "+
			"For example, you might want to group by a path inside $request, so you should "+
			"set this option to '^\\S+\\s(.*)(?:\\?.*)?$'.")
	groupByGeneralize = goopt.String([]string{"--generalize"}, "",
		"Regular expression to generalize data. For example to make /foo/123 and /foo/234 equal")
	debug = goopt.Flag([]string{"--debug"}, []string{"--no-debug"},
		"Log debug information", "Do not log debug information")
	jsonOutput = goopt.String([]string{"-o", "--json"}, "",
		"Save result as json encoded file")
}
Exemplo n.º 9
0
func main() {
	var progname = os.Args[0][strings.LastIndex(os.Args[0], "/")+1:]

	var algorithm = goopt.StringWithLabel([]string{"-a", "--algorithm"}, algorithms[0],
		"ALG", fmt.Sprintf("Hashing algorithm: %s", algorithms))
	var version = goopt.Flag([]string{"-V", "--version"}, []string{}, "Display version", "")

	goopt.Summary = fmt.Sprintf("%s [OPTIONS] FILENAME\n\nMessage digest calculator with various hashing algorithms.\n\nArguments:\n  FILENAME                 File(s) to hash\n", progname)
	goopt.Parse(nil)

	var files []string = goopt.Args

	if *version {
		fmt.Printf("%s version %s\n", progname, Version)
		os.Exit(0)
	}

	validateAlgorithm(goopt.Usage(), *algorithm)
	valildateFiles(goopt.Usage(), files)

	calculateDigest(files, *algorithm)

	os.Exit(0)
}
Exemplo n.º 10
0
func init() {
	goopt.Description = func() string {
		return "conchk v" + goopt.Version
	}
	goopt.Author = "Bruce Fitzsimons <*****@*****.**>"
	goopt.Version = "0.3"
	goopt.Summary = "conchk is an IP connectivity test tool designed to validate that all configured IP connectivity actually works\n " +
		"It reads a list of tests and executes them, in a parallel manner, based on the contents of each line" +
		"conchk supports tcp and udp based tests (IPv4 and IPv6), at this time.\n\n" +
		"==Notes==\n" +
		"* The incuded Excel sheet is a useful way to create and maintain the tests\n" +
		"* testing a range of supports is supported. In this case the rules for a successful test are somewhat different\n" +
		"** If one of the ports gets a successful connect, and the rest are refused (connection refused) as nothing is listening\n" +
		"\tthen this is considered to be a successful test of the range. This is the most common scenario in our experience;\n" +
		"\tthe firewalls and routing are demonstrably working, and at least one destination service is ok. If you need all ports to work\n" +
		"\tthen consider using individual tests\n" +
		"* If all tests for this host pass, then conchk will exit(0). Otherwise it will exit(1)\n" +
		"* conchk will use the current hostname, or the commandline parameter, to find the tests approprate to execute - matches on field 3.\n" +
		"\tThis means all the tests for a system, or project can be placed in one file\n" +
		"* The .csv output option will write a file much like the input file, but with two additional columns and without any comments\n" +
		"\t This file can be fed back into conchk without error.\n\n" +
		"See http://bwooce.github.io/conchk/ for more information.\n\n(c)2013 Bruce Fitzsimons.\n\n"

	Hostname, _ := os.Hostname()

	params.Debug = goopt.Flag([]string{"-d", "--debug"}, []string{}, "additional debugging output", "")
	params.TestsFile = goopt.String([]string{"-T", "--tests"}, "./tests.conchk", "test file to load")
	params.OutputFile = goopt.String([]string{"-O", "--outputcsv"}, "", "name of results .csv file to write to. A pre-existing file will be overwritten.")
	params.MyHost = goopt.String([]string{"-H", "--host"}, Hostname, "Hostname to use for config lookup")
	params.MaxStreams = goopt.Int([]string{"--maxstreams"}, 8, "Maximum simultaneous checks")
	params.Timeout = goopt.String([]string{"--timeout"}, "5s", "TCP connectivity timeout, UDP delay for ICMP responses")

	semStreams = make(semaphore, *params.MaxStreams)
	runtime.GOMAXPROCS(runtime.NumCPU())

}
Exemplo n.º 11
0
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Du"
	goopt.Summary = "Estimate file sizes"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... [FILE]...\n or:\t%s [OPTION]... --files0-from=F\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	null := goopt.Flag([]string{"-0", "--null"}, nil, "End output with \\0 instead of \\n", "")
	all := goopt.Flag([]string{"-a", "--all"}, nil, "Write counts for all files instead of only directories", "")
	goopt.OptArg([]string{"-B", "--block-size"}, "SIZE", "Set the block size that is used when printing.", setBlockSize)
	/*bytes := goopt.Flag([]string{"-b", "--bytes"}, nil, "Equivalent to --block-size=1", "")*/
	/*total := goopt.Flag([]string{"-c", "--total"}, nil, "Add up all the sizes to create a total", "")*/
	derefargs := goopt.Flag([]string{"-D", "--dereference-args", "-H"}, nil, "Dereference symlinks if they are a commandline argument", "")
	goopt.OptArg([]string{"-d", "--max-depth"}, "N", "Print total for directory that is N or fewer levels deep", setMaxDepth)
	goopt.OptArg([]string{"--files0-from"}, "F", "Use \\0 terminated file names from file F as commandline arguments", setFile0From)
	human = goopt.Flag([]string{"-h", "--human-readable"}, nil, "Output using human readable suffices", "")
	/*kilo := goopt.Flag([]string{"-k"}, nil, "Equivalent to --block-size=1K", "")*/
	dereference := goopt.Flag([]string{"-L", "--dereference"}, []string{"-P", "--no-dereference"}, "Dereference symbolic links", "Do not dereference any symbolic links (this is default)")
	separate := goopt.Flag([]string{"-S", "--separate-dirs"}, nil, "Do not add subdirectories to a directory's size", "")
	summarize := goopt.Flag([]string{"-s", "--summarize"}, nil, "Display totals only for each argument", "")
	goopt.OptArg([]string{"-t", "--threshold"}, "SIZE", "Only include entries whose size is greater than or equal to SIZE", setThreshold)
	/* Time and Exclude options go here */
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if *null {
		lastchar = "\0000"
	}
	if len(goopt.Args) == 0 {
		goopt.Args = append([]string{}, ".")
	}
	if *all && *summarize {
		fmt.Fprintf(os.Stderr, "Cannot both summarize and display all. Pick ONE.\n")
		coreutils.PrintUsage()
	}
	sysblocksize := int64(1)
	kiloconst := int64(1)
	for i := range goopt.Args {
		fileinfo := Stat(goopt.Args[i], *dereference, *derefargs, true)
		if sysblocksize == 1 && fileinfo.Mode < 32768 {
			sizeperblock := int64(fileinfo.Size) / int64(fileinfo.Blocks)
			sysblocksize := int64(1)
			for sysblocksize < sizeperblock {
				sysblocksize *= 2
			}
			if sysblocksize < 1024 {
				kiloconst = 1024 / sysblocksize
			}
		}
		deeper := append([]string{}, goopt.Args[i])
		coreutils.Recurse(&deeper)
		orig := true
		startdepth := len(strings.Split(goopt.Args[i], string(os.PathSeparator)))
		foldertosize := make(map[string]int64)
		deepest := startdepth
		maxdepth += startdepth
		for j := range deeper {
			foldertosize[filepath.Dir(filepath.Clean(deeper[j]))] = 0
			if len(strings.Split(deeper[j], string(os.PathSeparator))) > deepest {
				deepest = len(strings.Split(deeper[j], string(os.PathSeparator)))
			}
		}
		for deepest >= startdepth {
			for j := range deeper {
				if len(strings.Split(deeper[j], string(os.PathSeparator))) != deepest {
					continue
				}
				fileinfo = Stat(deeper[j], *dereference, *derefargs, orig)
				if fileinfo.Mode > 32768 {
					foldertosize[filepath.Dir(filepath.Clean(deeper[j]))] += fileinfo.Blocks / kiloconst
					if maxdepth != startdepth && maxdepth < deepest {
						continue
					}
					if *all {
						fmt.Printf("%s\t%s%s", fmtSize(fileinfo.Blocks/2), deeper[j], lastchar)
					}
				} else {
					foldertosize[filepath.Clean(deeper[j])] += fileinfo.Blocks / kiloconst
					if !*separate && filepath.Dir(filepath.Clean(deeper[j])) != filepath.Clean(deeper[j]) {
						foldertosize[filepath.Dir(filepath.Clean(deeper[j]))] += foldertosize[filepath.Clean(deeper[j])]
					}
					if *summarize || (maxdepth < deepest && maxdepth != startdepth) {
						continue
					}
					fmt.Printf("%s\t%s%s", fmtSize(foldertosize[filepath.Clean(deeper[j])]), deeper[j], lastchar)
				}
			}
			deepest--
		}
		if *summarize {
			fmt.Printf("%s\t%s%s", fmtSize(foldertosize[filepath.Dir(filepath.Clean(goopt.Args[i]))]), goopt.Args[i], lastchar)
		}
	}
	return
}
Exemplo n.º 12
0
	"encoding/json"
	"fmt"
	goopt "github.com/droundy/goopt"
	"net/http"
	"path/filepath"
	"strings"
)

var Version = "0.1"

var Summary = `gostatic path/to/config

Build a site.
`

var showVersion = goopt.Flag([]string{"-V", "--version"}, []string{},
	"show version and exit", "")
var showProcessors = goopt.Flag([]string{"--processors"}, []string{},
	"show internal processors", "")
var showSummary = goopt.Flag([]string{"--summary"}, []string{},
	"print everything on stdout", "")
var showConfig = goopt.Flag([]string{"--show-config"}, []string{},
	"dump config as JSON on stdout", "")
var doWatch = goopt.Flag([]string{"-w", "--watch"}, []string{},
	"watch for changes and serve them as http", "")
var port = goopt.String([]string{"-p", "--port"}, "8000",
	"port to serve on")
var verbose = goopt.Flag([]string{"-v", "--verbose"}, []string{},
	"enable verbose output", "")

// used in Page.Changed()
var force = goopt.Flag([]string{"-f", "--force"}, []string{},
Exemplo n.º 13
0
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Rm"
	goopt.Summary = "Remove each FILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... FILE...\n", os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	force = goopt.Flag([]string{"-f", "--force"}, nil, "Ignore nonexistent files, don't prompt user", "")
	prompteach = goopt.Flag([]string{"-i"}, nil, "Prompt before each removal", "")
	promptonce = goopt.Flag([]string{"-I"}, nil, "Prompt before removing multiple files at once", "")
	goopt.OptArg([]string{"--interactive"}, "WHEN", "Prompt according to WHEN", setPrompt)
	/*onefs := goopt.Flag([]string{"--one-file-system"}, nil, "When -r is specified, skip directories on different filesystems", "")*/
	nopreserveroot := goopt.Flag([]string{"--no-preserve-root"}, []string{"--preserve-root"}, "Do not treat '/' specially", "Do not remove '/' (This is default)")
	recurse := goopt.Flag([]string{"-r", "-R", "--recursive"}, nil, "Recursively remove directories and their contents", "")
	emptydir := goopt.Flag([]string{"-d", "--dir"}, nil, "Remove empty directories", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	promptno := true
	var filenames []string
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	coreutils.Preserveroot = !*nopreserveroot
	coreutils.Silent = *force
	coreutils.Prompt = *prompteach || *promptonce
	coreutils.PromptFunc = func(filename string, remove bool) bool {
		var prompt string
		if remove {
			prompt = "Remove " + filename + "?"
		} else {
			prompt = "Recurse into " + filename + "?"
		}
		var response string
		trueresponse := "yes"
		falseresponse := "no"
		for {
			fmt.Print(prompt)
			fmt.Scanln(&response)
			response = strings.ToLower(response)
			if strings.Contains(trueresponse, response) {
				return true
			} else if strings.Contains(falseresponse, response) || response == "" {
				return false
			}
		}
	}
	for i := range goopt.Args {
		_, err := os.Lstat(goopt.Args[i])
		if *force && os.IsNotExist(err) {
			continue
		}
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error getting file info for '%s': %v\n", goopt.Args[i], err)
			defer os.Exit(1)
			continue
		}
		filenames = append(filenames, goopt.Args[i])
		if *recurse {
			if coreutils.Recurse(&filenames) {
				defer os.Exit(1)
			}
		}
	}
	sort.Strings(filenames)
	l := len(filenames) - 1
	for i := range filenames {
		fileinfo, err := os.Lstat(filenames[l-i])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error getting file info for '%s': %v\n", filenames[l-i], err)
			defer os.Exit(1)
			continue
		}
		isadir := fileinfo.IsDir()
		if *prompteach || *promptonce && (l-i)%3 == 1 {
			promptno = coreutils.PromptFunc(filenames[l-i], true)
		}
		if !promptno {
			continue
		}
		if !*emptydir && !*recurse && isadir {
			fmt.Fprintf(os.Stderr, "Could not remove '%s': Is a directory\n", filenames[l-i])
			defer os.Exit(1)
			continue
		}
		if *verbose {
			fmt.Printf("Removing '%s'\n", filenames[l-i])
		}
		err = os.Remove(filenames[l-i])
		if err != nil && !(*force && os.IsNotExist(err)) {
			fmt.Fprintf(os.Stderr, "Could not remove '%s': %v\n", filenames[l-i], err)
			defer os.Exit(1)
		}
	}
	return
}
Exemplo n.º 14
0
	"metrics.txt",
	"the name of the file that contains the list of metric names")
var maxMetrics = goopt.Int([]string{"-x", "--maxmetrics"},
	5000,
	"the maximum number of metric names that will be used. if the number exceeds the number of names in the metric file the max in the file will be used")
var target = goopt.Alternatives(
	[]string{"-t", "--target"},
	[]string{TARGET_MONGO, TARGET_ZMQ, TARGET_TSDB},
	"sets the destination of metrics generated, default is mongo")
var sendMode = goopt.Alternatives(
	[]string{"-m", "--sendmode"},
	[]string{MODE_CONNECT, MODE_BIND},
	"mode used when sending requests over ZeroMQ, default is connect")
var doBatching = goopt.Flag(
	[]string{"--batch"},
	[]string{"--nobatch"},
	"inserts into the database will be batched",
	"inserts into the database will not be batched")
var batchSize = goopt.Int(
	[]string{"-z", "--size", "--batchsize"},
	1000,
	"sets the size of batches when inserting into the database")

// Connects to a mongo database and sends a continuous stream of metric updates
// (inserts) to the server for a specified amount of time (default 60 seconds).
// At the end of the cycle the number of metrics inserted is displayed.
func main() {
	goopt.Description = func() string {
		return "Go test writer program for MongoDB."
	}
	goopt.Version = "1.0"
Exemplo n.º 15
0
package promptcommit

import (
	"github.com/droundy/goopt"
	"../git/git"
	"../git/plumbing"
	"../util/out"
	"../util/error"
	"../util/exit"
	"../util/debug"
	box "./gotgo/box(git.CommitHash,git.Commitish)"
)

// To make --all the default, set *prompt.All to true.
var All = goopt.Flag([]string{"-a","--all"}, []string{"--interactive"},
	"verb all commits", "prompt for commits interactively")

var Dryrun = goopt.Flag([]string{"--dry-run"}, []string{},
	"just show commits that would be verbed", "xxxs")

var Verbose = goopt.Flag([]string{"-v","--verbose"}, []string{"-q","--quiet"},
	"output commits that are verbed", "don't output commits that are verbed")

func Select(since, upto git.Commitish) (outh git.CommitHash) {
	hs,e := plumbing.RevListDifference([]git.Commitish{upto}, []git.Commitish{since})
	error.FailOn(e)
	if len(hs) == 0 {
		out.Println(goopt.Expand("No commits to verb!"))
		exit.Exit(0)
	}
	if *Dryrun {
Exemplo n.º 16
0
	if err != 0 {
		return 0, err1
	}

	// Handle exception for darwin
	if darwin && r2 == 1 {
		r1 = 0
	}

	return r1, 0

}

var config_file = goopt.String([]string{"-c", "--config"}, "/etc/ranger.conf", "config file")
var install_api_key = goopt.String([]string{"-i", "--install-api-key"}, "", "install api key")
var amForeground = goopt.Flag([]string{"--foreground"}, []string{"--background"}, "run foreground", "run background")

func setup_logger() {
	filename := "/var/log/ranger/ranger.log"

	// Create a default logger that is logging messages of FINE or higher to filename, no rotation
	//    log.AddFilter("file", l4g.FINE, l4g.NewFileLogWriter(filename, false))

	// =OR= Can also specify manually via the following: (these are the defaults, this is equivalent to above)
	flw := l4g.NewFileLogWriter(filename, false)
	if flw == nil {
		fmt.Printf("No permission to write to %s, going to switch to stdout only\n", filename)
	} else {
		flw.SetFormat("[%D %T] [%L] (%S) %M")
		flw.SetRotate(false)
		flw.SetRotateSize(0)
Exemplo n.º 17
0
import goopt "github.com/droundy/goopt"

import config "github.com/kless/goconfig/config"

var version = "0.1"

///////////////////////////////////
//
//		Taken form goopt example
//
///////////////////////////////////

// The Flag function creates a boolean flag, possibly with a negating
// alternative.  Note that you can specify either long or short flags
// naturally in the same list.
var amVerbose = goopt.Flag([]string{"-v", "--verbose"}, []string{"--quiet"},
	"output verbosely this will also show the graphite data", "be quiet, instead")

// This is just a logging function that uses the verbosity flags to
// decide whether or not to log anything.
func log(x ...interface{}) {
	if *amVerbose {
		fmt.Println(x...)
	}
}

///////////////////////////////////
///////////////////////////////////

func exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
Exemplo n.º 18
0
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Cp"
	goopt.Summary = "Copy each SOURCE to DEST"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... SOURCE(...) DEST\n or:\t%s [OPTION]... -t DEST SOURCE\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	backup := goopt.Flag([]string{"-b", "--backup"}, nil, "Backup files before overwriting", "")
	prompt := goopt.Flag([]string{"-i", "--interactive"}, nil, "Prompt before an overwrite. Override -f and -n.", "")
	noclobber := goopt.Flag([]string{"-n", "--no-clobber"}, []string{"-f", "--force"}, "Do not overwrite", "Never prompt before an overwrite")
	hardlink := goopt.Flag([]string{"-l", "--link"}, nil, "Make hard links instead of copying", "")
	nodereference := goopt.Flag([]string{"-P", "--no-dereference"}, []string{"-L", "--dereference"}, "Never follow symlinks", "Always follow symlinks")
	/*preserve := goopt.Flag([]string{"-p", "--preserve"}, nil, "Preserve mode, ownership and timestamp attributes", "")*/
	recurse := goopt.Flag([]string{"-r", "-R", "--recurse"}, nil, "Recursively copy files from SOURCE to TARGET", "")
	goopt.OptArg([]string{"-S", "--suffix"}, "SUFFIX", "Override the usual backup suffix", setBackupSuffix)
	symlink := goopt.Flag([]string{"-s", "--symbolic-link"}, nil, "Make symlinks instead of copying", "")
	goopt.OptArg([]string{"-t", "--target"}, "TARGET", "Set the target with a flag instead of at the end", setTarget)
	update := goopt.Flag([]string{"-u", "--update"}, nil, "Move only when DEST is missing or older than SOURCE", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) < 2 {
		coreutils.PrintUsage()
	}
	coreutils.Noderef = *nodereference
	j := 0
	if target == "" {
		target = goopt.Args[len(goopt.Args)-1]
		j = 1
	}
	var sources []string
	for i := range goopt.Args[j:] {
		sources = append(sources, goopt.Args[i])
		if *recurse {
			if coreutils.Recurse(&sources) {
				defer os.Exit(1)
			}
		}
	}
	destinfo, err := coreutils.Stat(target)
	if err != nil && !os.IsNotExist(err) {
		fmt.Fprintf(os.Stderr, "Error trying to get info to check if DEST is a directory: %v\n", err)
		os.Exit(1)
	}
	isadir := err == nil && destinfo.IsDir()
	if (len(goopt.Args) > 2 || (target != goopt.Args[len(goopt.Args)-1] && len(goopt.Args) > 1)) && !isadir {
		fmt.Fprintf(os.Stderr, "Too many arguments for non-directory destination")
		os.Exit(1)
	}
	for i := range sources {
		dest := target
		if sources[i] == "" {
			continue
		}
		destinfo, err := coreutils.Stat(target)
		exist := !os.IsNotExist(err)
		if err != nil && exist {
			fmt.Fprintf(os.Stderr, "Error trying to get info on target: %v\n", err)
			os.Exit(1)
		}
		srcinfo, err := coreutils.Stat(sources[i])
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error trying to get mod time on SRC: %v\n", err)
			os.Exit(1)
		}
		mkdir := false
		if srcinfo.IsDir() {
			if isadir {
				dest = dest + string(os.PathSeparator) + sources[i]
			}
			if !*recurse {
				fmt.Printf("Skipping directory %s\n", sources[i])
				continue
			}
			mkdir = true
		} else if isadir {
			dest = dest + string(os.PathSeparator) + filepath.Base(sources[i])
		}
		newer := true
		if *update && exist {
			newer = srcinfo.ModTime().After(destinfo.ModTime())
		}
		if !newer {
			continue
		}
		promptres := true
		if exist {
			promptres = !*noclobber
			if *prompt {
				promptres = coreutils.PromptFunc(dest, false)
			}
			if promptres && *backup {
				if err = os.Rename(dest, dest+backupsuffix); err != nil {
					fmt.Fprintf(os.Stderr, "Error while backing up '%s' to '%s': %v\n", dest, dest+backupsuffix, err)
					defer os.Exit(1)
					continue
				}
			}
		}
		if !promptres {
			continue
		}
		switch {
		case mkdir:
			if err = os.Mkdir(dest, coreutils.Mode); err != nil {
				fmt.Fprintf(os.Stderr, "Error while making directory '%s': %v\n", dest, err)
				defer os.Exit(1)
				continue
			}
			if *verbose {
				fmt.Printf("Copying directory '%s' to '%s'\n", sources[i], dest)
			}
		case *hardlink:
			if err := os.Link(sources[i], dest); err != nil {
				fmt.Fprintf(os.Stderr, "Error while linking '%s' to '%s': %v\n", dest, sources[i], err)
				defer os.Exit(1)
				continue
			}
			if *verbose {
				fmt.Printf("Linked '%s' to '%s'\n", dest, sources[i])
			}
		case *symlink:
			if err := os.Symlink(sources[i], dest); err != nil {
				fmt.Fprintf(os.Stderr, "Error while linking '%s' to '%s': %v\n", dest, sources[i], err)
				defer os.Exit(1)
				continue
			}
			if *verbose {
				fmt.Printf("Symlinked '%s' to '%s'\n", dest, sources[i])
			}
		default:
			source, err := os.Open(sources[i])
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error while opening source file '%s': %v\n", sources[i], err)
				defer os.Exit(1)
				continue
			}
			filebuf, err := ioutil.ReadAll(source)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error while reading source file, '%s', for copying: %v\n", sources[i], err)
				defer os.Exit(1)
				continue
			}
			destfile, err := os.Create(dest)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error while creating destination file, '%s': %v\n", dest, err)
				defer os.Exit(1)
				continue
			}
			destfile.Write(filebuf)
			if *verbose {
				fmt.Printf("'%s' copied to '%s'\n", sources[i], dest)
			}
		}
	}
	return
}
Exemplo n.º 19
0
import (
	"bytes"
	"log"
	"net"
	"os/exec"
	"regexp"
	"strings"
	"time"

	"github.com/droundy/goopt"
)

var connect = goopt.String([]string{"-s", "--server"}, "127.0.0.1", "Server to connect to (and listen if listening)")
var port = goopt.Int([]string{"-p", "--port"}, 2222, "Port to connect to (and listen to if listening)")

var listen = goopt.Flag([]string{"-l", "--listen"}, []string{}, "Create a listening TFO socket", "")

func main() {

	goopt.Parse(nil)

	// IPv4 only for no real reason, could be v6 by adjusting the sizes
	// here and where it's used
	var serverAddr [4]byte

	IP := net.ParseIP(*connect)
	if IP == nil {
		log.Fatal("Unable to process IP: ", *connect)
	}

	copy(serverAddr[:], IP[12:16])
Exemplo n.º 20
0
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Chown"
	goopt.Summary = "Change owner or group of each FILE to OWNER or GROUP\nWith reference, change owner and group of each FILE to the owner and group of RFILE"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... [OWNER][:[GROUP]] FILE...\n or:\t%s [OPTION]... --reference=RFILE FILE...\n", os.Args[0], os.Args[0], os.Args[0]) +
			goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	changes := goopt.Flag([]string{"-c", "--changes"}, nil, "Like verbose but only report changes", "")
	silent := goopt.Flag([]string{"-f", "--silent", "--quiet"}, nil, "Suppress most error messages", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	nodereference := goopt.Flag([]string{"-h", "--no-dereference"}, []string{"--derference"}, "Affect symbolic links directly instead of dereferencing them", "Dereference symbolic links before operating on them (This is default)")
	preserveroot := goopt.Flag([]string{"--preserve-root"}, []string{"--no-preserve-root"}, "Don't recurse on '/'", "Treat '/' normally (This is default)")
	goopt.OptArg([]string{"--reference"}, "RFILE", "Use RFILE's owner and group", fromReference)
	recurse := goopt.Flag([]string{"-R", "--recursive"}, nil, "Operate recursively on files and directories", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) == 0 {
		coreutils.PrintUsage()
	}
	if !usingreference {
		usergroup := strings.Split(goopt.Args[0], ":")
		owner, err := user.Lookup(usergroup[0])
		if err != nil {
			uid = -1
		} else {
			uid, err = strconv.Atoi(owner.Uid)
			if err != nil && !*silent {

			}
			/* hack until Go matures */
			gid, err = strconv.Atoi(owner.Gid)
			if err != nil && !*silent {
				/* stuff */
			}
		}
	}
	for j := range goopt.Args[1:] {
		filenames := []string{goopt.Args[j+1]}
		for h := 0; h < len(filenames); h++ {
			/* Fix to only print when changes occur for *changes */
			if *changes || *verbose {
				fmt.Printf("Modifying ownership of %s\n", filenames[h])
			}
			if *nodereference {
				os.Lchown(filenames[h], uid, gid)
			} else {
				os.Chown(filenames[h], uid, gid)
			}
			if *recurse && (!*preserveroot || filenames[h] != "/") {
				filelisting, err := ioutil.ReadDir(filenames[h])
				if err != nil {
					fmt.Fprintf(os.Stderr, "Could not recurse into '%s'\n", filenames[h])
					defer os.Exit(1)
					continue
				}
				for g := range filelisting {
					filenames = append(filenames, filelisting[g].Name())
				}
			}
		}
	}
	return
}
Exemplo n.º 21
0
package prompt

import (
	"github.com/droundy/goopt"
	"strings"
	"./core"
	"../git/color"
	"../util/out"
	"../util/error"
	"../util/debug"
	"../util/patience"
	ss "../util/slice(string)"
)

// To make --all the default, set *prompt.All to true.
var All = goopt.Flag([]string{"-a","--all"}, []string{"--interactive"},
	"verb all patches", "prompt for patches interactively")

func Run(ds []core.FileDiff, f func(core.FileDiff)) {
	if *All {
		for _,d := range ds {
			f(d)
		}
	} else {
	  files: for _,d := range ds {
			for {
				if !d.HasChange() {
					continue files
				}
				// Just keep asking until we get a reasonable answer...
				c,e := out.PromptForChar(goopt.Expand("Verb changes to %s? "), d.Name)
				error.FailOn(e)
Exemplo n.º 22
0
Arquivo: main.go Projeto: rhettg/ftl
import "fmt"
import "os"

import (
	goopt "github.com/droundy/goopt"
	"github.com/rhettg/ftl/ftl"
	"launchpad.net/goamz/aws"
	"path/filepath"
	"strings"
)

const DOWNLOAD_WORKERS = 4

const Version = "0.2.6"

var amVerbose = goopt.Flag([]string{"-v", "--verbose"}, []string{"--quiet"},
	"output verbosely", "be quiet, instead")

var amMaster = goopt.Flag([]string{"--master"}, nil, "Execute against master repository", "")

var amVersion = goopt.Flag([]string{"--version"}, nil, "Display current version", "")

func optToRegion(regionName string) (region aws.Region) {
	region = aws.USEast

	switch regionName {
	case "us-east":
		region = aws.USEast
	case "us-west-1":
		region = aws.USWest
	case "us-west-2":
		region = aws.USWest2
Exemplo n.º 23
0
package main

import (
	"fmt"
	goopt "github.com/droundy/goopt"
	"github.com/xaviershay/erg"
	"os"
	"strconv"
)

var port = goopt.Int([]string{"-p", "--port"}, 8080, "Port to connect to. Can also be set with RANGE_PORT environment variable.")
var host = goopt.String([]string{"-h", "--host"}, "localhost", "Host to connect to. Can also be set with RANGE_HOST environment variable.")
var ssl = goopt.Flag([]string{"-s", "--ssl"}, []string{"--no-ssl"},
	"Don't use SSL", "Use SSL. Can also be set with RANGE_SSL environment variable.")
var expand = goopt.Flag([]string{"-e", "--expand"}, []string{"--no-expand"},
	"Do not compress results", "Compress results (default)")

func main() {
	if envHost := os.Getenv("RANGE_HOST"); len(envHost) > 0 {
		*host = envHost
	}

	if envSsl := os.Getenv("RANGE_SSL"); len(envSsl) > 0 {
		*ssl = true
	}

	if envPort := os.Getenv("RANGE_PORT"); len(envPort) > 0 {
		x, err := strconv.Atoi(envPort)
		if err == nil {
			*port = x
		} else {
Exemplo n.º 24
0
func main() {
	goopt.Summary = "Command line tool to merge minimaps from custom clients in Hafen."
	var sessionFodler = goopt.StringWithLabel([]string{"-d", "--sessions-dir"}, "sessions", "<path>",
		"Specify input folder (instead of default \"sessions\")")
	var mode = goopt.Alternatives([]string{"-m", "--mode"}, []string{"merger", "zoomer", "picture"},
		"Specify mode (instead of default \"merger\")")
	var zoomPath = goopt.StringWithLabel([]string{"-z", "--zoom"}, "", "<session>",
		"Create zoom layers for specific <session> and place them into \"zoommap\" folder")
	var zoomSize = goopt.IntWithLabel([]string{"--zoom-tile-size"}, 100, "<size>",
		"Specify generated tiles size (instead of default 100)")
	var zoomMax = goopt.IntWithLabel([]string{"--zoom-max"}, 5, "<num>",
		"Specify zoom max (instead of default 5)")
	var zoomMin = goopt.IntWithLabel([]string{"--zoom-min"}, 1, "<num>",
		"Specify zoom min (instead of default 1)")
	var picturePath = goopt.StringWithLabel([]string{"-p", "--picture"}, "", "<session>",
		"Create single map picture for specific <session>")
	var outputFodler = goopt.StringWithLabel([]string{"-o", "--output-dir"}, "zoommap", "<path>",
		"Specify output folder for zoom mode (instead of default \"zoommap\")")
	var trimSessions = goopt.IntWithLabel([]string{"-t", "--trim"}, -1, "<count>",
		"Remove sessions with tiles < <count> from result (good for removing cave sessions)")
	var removeNonStandard = goopt.Flag([]string{"-c", "--clean-non-standard"}, []string{},
		"Remove all non-standard maps (size != 100x100)", "")
	var hashCode = goopt.Alternatives([]string{"--hash-method"}, []string{"simple", "border"},
		"Specify hash method (instead of default \"simple\")")

	// Parse CMD
	goopt.Parse(nil)

	// Force change mode for backward compatibility
	if *picturePath != "" && *mode == "merger" {
		*mode = "picture"
	}
	if *zoomPath != "" && *mode == "merger" {
		*mode = "zoomer"
	}

	SESSION_FOLDER = *sessionFodler

	var hashMethod HashMethod
	switch *hashCode {
	case "simple":
		hashMethod = HashMethod{CodeName: *hashCode, Func: generateSimpleHash}
		break
	case "border":
		hashMethod = HashMethod{CodeName: *hashCode, Func: generateBorderHash}
		break
	default:
		panic("Unrecognized hash method!") // this should never happen!
	}

	workingDirectory, _ := filepath.Abs(SESSION_FOLDER)

	if *zoomSize%100 != 0 {
		fmt.Println("Tile size must be in multiples of 100")
		return
	}
	var composeCount = int(*zoomSize / 100)

	// Generate zoom levels for specific session
	if *mode == "zoomer" {
		generateTiles(workingDirectory, *zoomPath, *outputFodler, composeCount, hashMethod, *zoomMin, *zoomMax)
		return
	}

	// Generate single picture for specific session
	if *mode == "picture" {
		generatePicture(workingDirectory, *picturePath)
		return
	}

	// Otherwise, let's make cross-merge
	files, _ := ioutil.ReadDir(workingDirectory)
	if len(files) < 2 {
		fmt.Println("No folders found")
		return
	}

	if *removeNonStandard == true {
		// Remove all sessions with tile size != 100x100
		for j := 0; j < len(files); j++ {
			tiles, _ := ioutil.ReadDir(filepath.Join(workingDirectory, files[j].Name()))
			for i := 0; i < len(tiles); i++ {
				if strings.Contains(tiles[i].Name(), "tile_") {
					sx, sy := getImageDimension(filepath.Join(workingDirectory, files[j].Name(), tiles[i].Name()))
					if sx != 100 || sy != 100 {
						fmt.Printf("Old session removed: %s\n", files[j].Name())
						os.RemoveAll(filepath.Join(workingDirectory, files[j].Name()))
					}
					break
				}
			}
		}
	}

	files, _ = ioutil.ReadDir(workingDirectory)
	if len(files) < 2 {
		fmt.Println("No folders found")
		return
	}
	for j := 0; j < len(files); j++ {
		info, err := os.Stat(filepath.Join(workingDirectory, files[j].Name()))
		if err != nil {
			continue
		}
		if info.IsDir() == false {
			continue
		}

		coreFolder := files[j]
		for i := 1; i < len(files); i++ {
			if i == j {
				continue
			}
			dirInfo, err := os.Stat(filepath.Join(workingDirectory, files[i].Name()))
			if err != nil {
				continue
			}
			if dirInfo.IsDir() == false {
				continue
			}

			res := mergeFolders(filepath.Join(workingDirectory, files[i].Name()), filepath.Join(workingDirectory, coreFolder.Name()), hashMethod)
			if res == true {
				fmt.Printf("Merged (%s, %s)\n", coreFolder.Name(), files[i].Name())
			} else {
				fmt.Printf("Sessions are not mergeable (%s, %s)\n", coreFolder.Name(), files[i].Name())
			}
		}
	}
	files, _ = ioutil.ReadDir(workingDirectory)
	var sessionsJS string = "var sessionsJS = ["
	for j := 0; j < len(files); j++ {
		tiles, _ := ioutil.ReadDir(filepath.Join(workingDirectory, files[j].Name()))
		if *trimSessions > 0 {
			if len(tiles) < *trimSessions {
				err := os.RemoveAll(filepath.Join(workingDirectory, files[j].Name()))
				if err != nil {
					fmt.Printf("Cannot trim session %s: %s\n", files[j].Name(), err.Error())
					continue
				} else {
					fmt.Printf("Trimmed session %s\n", files[j].Name())
					continue
				}
			}
		}
		sessionsJS += "\"" + SESSION_FOLDER + "/" + files[j].Name() + "\", "
	}
	sessionsJS += "];"
	ioutil.WriteFile("session.js", []byte(sessionsJS), 0777)
}
Exemplo n.º 25
0
	"fmt"
	"github.com/droundy/goopt"
	"github.com/wsxiaoys/terminal/color"
	"os"
	"path/filepath"
	"regexp"
)

var (
	Author  = "Alexander Solovyov"
	Version = "0.4.3"
	Summary = "gr [OPTS] string-to-search\n"

	byteNewLine []byte = []byte("\n")

	ignoreCase = goopt.Flag([]string{"-i", "--ignore-case"}, []string{},
		"ignore pattern case", "")
	onlyName = goopt.Flag([]string{"-n", "--filename"}, []string{},
		"print only filenames", "")
	ignoreFiles = goopt.Strings([]string{"-x", "--exclude"}, "RE",
		"exclude files that match the regexp from search")
	singleline = goopt.Flag([]string{"-s", "--singleline"}, []string{},
		"match on a single line (^/$ will be beginning/end of line)", "")
	plaintext = goopt.Flag([]string{"-p", "--plain"}, []string{},
		"search plain text", "")
	replace = goopt.String([]string{"-r", "--replace"}, "",
		"replace found substrings with this string")
	force = goopt.Flag([]string{"--force"}, []string{},
		"force replacement in binary files", "")
	showVersion = goopt.Flag([]string{"-V", "--version"}, []string{},
		"show version and exit", "")
	noIgnoresGlobal = goopt.Flag([]string{"-I", "--no-autoignore"}, []string{},
Exemplo n.º 26
0
func main() {
	goopt.Author = "William Pearson"
	goopt.Version = "Mv"
	goopt.Summary = "Move (rename) each SOURCE to DEST"
	goopt.Usage = func() string {
		return fmt.Sprintf("Usage:\t%s [OPTION]... SOURCE(...) DEST\n or:\t%s [OPTION]... -t DEST SOURCE\n", os.Args[0], os.Args[0]) + goopt.Summary + "\n\n" + goopt.Help()
	}
	goopt.Description = func() string {
		return goopt.Summary + "\n\nUnless --help or --version is passed."
	}
	prompt := goopt.Flag([]string{"-i", "--interactive"}, nil, "Prompt before an overwrite. Override -f and -n.", "")
	noclobber := goopt.Flag([]string{"-n", "--no-clobber"}, []string{"-f", "--force"}, "Do not overwrite", "Never prompt before an overwrite")
	backup := goopt.Flag([]string{"-b", "--backup"}, nil, "Backup files before overwriting", "")
	goopt.OptArg([]string{"-S", "--suffix"}, "SUFFIX", "Override the usual backup suffix", coreutils.SetBackupSuffix)
	goopt.OptArg([]string{"-t", "--target"}, "TARGET", "Set the target with a flag instead of at the end", coreutils.SetTarget)
	update := goopt.Flag([]string{"-u", "--update"}, nil, "Move only when DEST is missing or older than SOURCE", "")
	verbose := goopt.Flag([]string{"-v", "--verbose"}, nil, "Output each file as it is processed", "")
	goopt.NoArg([]string{"--version"}, "outputs version information and exits", coreutils.Version)
	goopt.Parse(nil)
	if len(goopt.Args) < 2 {
		coreutils.PrintUsage()
	}
	if coreutils.Target == "" {
		coreutils.Target = goopt.Args[len(goopt.Args)-1]
	}
	destinfo, err := os.Lstat(coreutils.Target)
	if err != nil && !os.IsNotExist(err) {
		fmt.Fprintf(os.Stderr, "Error trying to get info to check if DEST is a directory: %v\n", err)
		os.Exit(1)
	}
	isadir := err == nil && destinfo.IsDir()
	if (len(goopt.Args) > 2 || (coreutils.Target != goopt.Args[len(goopt.Args)-1] && len(goopt.Args) > 1)) && !isadir {
		fmt.Fprintf(os.Stderr, "Too many arguments for non-directory destination")
		os.Exit(1)
	}
	for i := range goopt.Args[1:] {
		dest := coreutils.Target
		if isadir {
			dest = dest + string(os.PathSeparator) + filepath.Base(goopt.Args[i])
		}
		destinfo, err := os.Lstat(dest)
		exist := !os.IsNotExist(err)
		newer := true
		if err != nil && exist {
			fmt.Fprintf(os.Stderr, "Error trying to get info on target: %v\n", err)
			os.Exit(1)
		}
		if *update && exist {
			srcinfo, err := os.Lstat(goopt.Args[i])
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error trying to get mod time on SRC: %v\n", err)
				os.Exit(1)
			}
			newer = srcinfo.ModTime().After(destinfo.ModTime())
		}
		if !newer {
			continue
		}
		promptres := true
		if exist {
			promptres = !*noclobber
			if *prompt {
				promptres = coreutils.PromptFunc(dest, false)
			}
			if promptres && *backup {
				coreutils.Backup(dest)
			}
		}
		if promptres {
			err = os.Rename(goopt.Args[i], dest)
			if err != nil {
				fmt.Fprintf(os.Stderr, "Error while moving '%s' to '%s': %v\n", goopt.Args[i], dest, err)
				defer os.Exit(1)
				continue
			}
			if *verbose {
				fmt.Printf("%s -> %s\n", goopt.Args[i], dest)
			}

		}
	}
	return
}
Exemplo n.º 27
0
package main

import (
	"exec"
	"fmt"
	"github.com/droundy/go-crazy/parser"
	"github.com/droundy/goopt"
	"go/printer"
	"os"
)

var just_translate = goopt.Flag([]string{"--just-translate"}, []string{},
	"just build the -compiled.go file", "build and compile and link")

var toinline = goopt.Strings([]string{"--inline"}, "FUNC", "specify function to inline")

func panicon(err os.Error) {
	if err != nil {
		panic(err)
	}
}

func archnum() string {
	switch os.Getenv("GOARCH") {
	case "386":
		return "8"
	case "amd64":
		return "6"
		// what was the other one called?
	}
	return "5"
Exemplo n.º 28
0
package main

// test out the goopt package...

import (
	"fmt"
	goopt "github.com/droundy/goopt"
	"strings"
)

var amVerbose = goopt.Flag([]string{"--verbose"}, []string{},
	"output verbosely", "")
var amHappy = goopt.Flag([]string{"-h", "--happy"}, []string{"-u", "--unhappy", "--sad"}, "be happy", "be unhappy")

var foo = goopt.String([]string{"--name"}, "anonymous", "pick your name")
var bar = goopt.String([]string{"-b"}, "BOO!", "pick your scary sound")
var baz = goopt.String([]string{"-o"}, "", "test whether a silent default works")
var speed = goopt.Alternatives([]string{"--speed", "--velocity"},
	[]string{"slow", "medium", "fast"},
	"set the speed")

var words = goopt.Strings([]string{"--word", "--saying", "-w", "-s"}, "word",
	"specify a word to speak")

var width = goopt.Int([]string{"-l", "--length"}, 1, "number of ?s")

func main() {
	goopt.Summary = "silly test program"
	goopt.Parse(nil)
	if *amVerbose {
		fmt.Println("I am verbose.")
Exemplo n.º 29
0
  limitations under the License.
*/

package main

import (
	"fmt"
	goopt "github.com/droundy/goopt"
	"os"
	"strconv"
	"strings"
	"time"
)

// Actions
var addFlag = goopt.Flag([]string{"-a", "--add"}, nil, "add a task", "")
var editFlag = goopt.Flag([]string{"-e", "--edit"}, nil, "edit a task, replacing its text", "")
var markDoneFlag = goopt.Flag([]string{"-d", "--done"}, nil, "mark the given tasks as done", "")
var markNotDoneFlag = goopt.Flag([]string{"-D", "--not-done"}, nil, "mark the given tasks as not done", "")
var removeFlag = goopt.Flag([]string{"--remove"}, nil, "remove the given tasks", "")
var reparentFlag = goopt.Flag([]string{"-R", "--reparent"}, nil, "reparent task A below task B", "")
var titleFlag = goopt.Flag([]string{"--title"}, nil, "set the task list title", "")
var versionFlag = goopt.Flag([]string{"--version"}, nil, "show version", "")
var infoFlag = goopt.Flag([]string{"-i", "--info"}, nil, "show information on a task", "")
var importFlag = goopt.Flag([]string{"--import"}, nil, "import and synchronise TODO items from source code", "")

// Options
var priorityFlag = goopt.String([]string{"-p", "--priority"}, "medium", "priority of newly created tasks (veryhigh,high,medium,low,verylow)")
var graftFlag = goopt.String([]string{"-g", "--graft"}, "root", "task to graft new tasks to")
var fileFlag = goopt.String([]string{"--file"}, ".todo2", "file to load task lists from")
var legacyFileFlag = goopt.String([]string{"--legacy-file"}, ".todo", "file to load legacy task lists from")
Exemplo n.º 30
0
Arquivo: zmqc.go Projeto: jhawk28/zmqc
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */

package main

import (
	"bufio"
	"fmt"
	flag "github.com/droundy/goopt"
	zmq "github.com/pebbe/zmq4"
	"os"
)

var null = flag.Flag([]string{"-0"}, []string{}, "Separate messages on input/output should be ", "")

var mode = flag.Flag([]string{"-c", "--connect"},
	[]string{"-b", "--bind"},
	"Connect to the specified address(es).",
	"Bind to the specified address(es).")

var number = flag.Int([]string{"-n"}, -1, "Receive/send only NUM messages. By default, zmqc "+
	"lives forever in 'read' mode, or until the end of input "+
	"in 'write' mode.")

var socket_type = flag.Alternatives([]string{"-s"},
	[]string{"PUSH", "PULL", "PUB", "SUB", "REQ", "REP", "PAIR"},
	"Which type of socket to create. Must be one of 'PUSH', 'PULL', "+
		"'PUB', 'SUB', 'REQ', 'REP' or 'PAIR'. See `man zmq_socket` for an "+
		"explanation of the different types. 'DEALER' and 'ROUTER' sockets are "+