Example #1
0
File: ip.go Project: jozan/ip-addr
func main() {

	var printLocal *bool = flag.BoolP("local", "l", false, "Print local IP address")
	var printPublic *bool = flag.BoolP("public", "p", false, "Print public IP address")
	flag.Parse()

	ips := make(chan string, 2)

	go func() {
		ip, _ := localIP()
		ips <- ip
		ips <- externalIP()
	}()

	if !*printPublic && *printLocal {
		fmt.Println(<-ips)
		return
	}

	if *printPublic && !*printLocal {
		<-ips
		fmt.Println(<-ips)
		return
	}

	if *printLocal && *printPublic {
		fmt.Println(<-ips)
		fmt.Println(<-ips)
		return
	}

	fmt.Println("Local IP:", <-ips)
	fmt.Println("Public IP:", <-ips)
}
Example #2
0
func parseArgs() args {
	result := args{}
	pflag.Usage = usage
	pflag.BoolVarP(&result.options.KeepGoing, "keep-going", "k", false, "")
	pflag.BoolVar(&result.options.CheckAll, "check-all", false, "")
	pflag.StringVarP(&result.scriptFile, "file", "f", "", "")
	verbose := pflag.BoolP("verbose", "v", false, "")
	quiet := pflag.BoolP("quiet", "q", false, "")
	topics := pflag.String("debug", "", "")
	pflag.Parse()
	if *topics != "" {
		result.debugTopics = strings.Split(*topics, ",")
	}

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

	result.options.Targets = pflag.Args()
	return result
}
Example #3
0
func main() {
	NAME = path.Base(os.Args[0])
	flags := make(map[string]*bool)

	flag.Usage = usageLong
	flags["version"] = flag.BoolP("version", "v", false,
		"Print version number and exit")
	flags["help"] = flag.BoolP("help", "h", false,
		"Print this help message and exit")
	flags["index"] = flag.BoolP("index", "i", false,
		"Create indexes for the lexicon")

	flag.Parse()

	// Handle -v/--version
	if *flags["version"] {
		fmt.Println(Version)
		os.Exit(0)
	}

	// Handle -h/--help
	if *flags["help"] {
		if strings.Contains(strings.Join(os.Args, " "), "--help") {
			usageLong()
		} else {
			usageShort()
		}
		os.Exit(0)
	}

	// Handle -i/--index
	if *flags["index"] {
		fmt.Println("Creating indexes")
		if err := index.Create(); err != nil {
			fmt.Fprintf(os.Stderr, "Error creating indexes: %v", err)
			os.Exit(1)
		} else {
			fmt.Println("Done")
			os.Exit(0)
		}
	}

	// Handle missing <text> argument
	if flag.NArg() == 0 {
		fmt.Fprintf(os.Stderr, "%s: missing <text> argument\n", NAME)
		usageLong()
		os.Exit(1)
	}

	fmt.Printf("Searching for %q\n", flag.Arg(0))
}
Example #4
0
// Initial setup when the program starts.
func setup() {
	// ensure that zpool/zfs commands do not use localized messages:
	os.Setenv("LC_ALL", "C")

	// command line flags:
	pflag.StringVarP(&cfgFile, "conf", "c", CFGFILE, "configuration file path")
	pflag.BoolVarP(&optDebug, "debug", "d", false, "print debug information to stdout")
	optHashPassword := pflag.BoolP("passwordhash", "P", false, "hash web password")
	optTest := pflag.BoolP("test", "t", false, "test configuration and exit")
	optVersion := pflag.BoolP("version", "v", false, "print version information and exit")

	pflag.Parse()

	if pflag.NArg() > 0 {
		pflag.Usage()
		os.Exit(2)
	}
	if *optVersion {
		version()
		os.Exit(0)
	}
	if *optHashPassword {
		wwwHashPassword()
		os.Exit(0)
	}

	// initialize logging & notification:

	if *optTest {
		optDebug = true
	}

	cfg = getCfg()
	if cfg == nil {
		os.Exit(2)
	}
	notify = setupLog(cfg)

	if *optTest {
		notifyCloseC := notify.Close()
		select { // wait max 1 second for loggers to finish
		case <-notifyCloseC:
		case <-time.After(time.Second):
		}
		os.Exit(0)
	}
}
Example #5
0
func main() {
	versionFlag := flag.BoolP("version", "V", false, "Print version.")
	numberNonblank := flag.BoolP("number-nonblank", "b", false, "Number nonblank lines.")
	flag.Parse()
	version := "0.0.4"

	if *versionFlag {
		println(version)
		os.Exit(0)
	}

	if *numberNonblank {

	}

	file := flag.Arg(0)
	processInputFile(file)
}
Example #6
0
func main() {
	var (
		// general options
		stateDir = pflag.String("statedir", "", "the server state directory")
		help     = pflag.BoolP("help", "h", false, "show this help")

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

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

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

	pflag.Parse()

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

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

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

	os.Exit(runClient(*stateDir, *plugin, *method, pflag.Arg(0), *data, headers.strs, *verbose))
}
Example #7
0
func main() {
	var pathStrings pathSlice
	filePtr := flag.StringP("file", "f", "", "Path to json file")
	jsonPtr := flag.StringP("json", "j", "", "JSON text")
	flag.VarP(&pathStrings, "path", "p", "One or more paths to target in JSON")
	showKeysPtr := flag.BoolP("keys", "k", false, "Print keys & indexes that lead to value")
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "Usage of %s:\n", os.Args[0])
		flag.PrintDefaults()
		fmt.Fprintln(os.Stderr, "Pipe JSON to StdIn by not specifying --file or --json ")
	}
	flag.Parse()

	if len(pathStrings) == 0 {
		fmt.Println("Must specify one or more paths with the --path flag")
		os.Exit(1)
	}

	paths, err := jsonpath.ParsePaths(pathStrings...)
	if err != nil {
		fmt.Println(fmt.Errorf("Failed to parse paths: %q", err.Error()))
		os.Exit(1)
	}

	if filePtr != nil && *filePtr != "" {
		f, err := os.Open(*filePtr)
		if err != nil {
			fmt.Println(fmt.Errorf("Failed to open file: %q", err.Error()))
			os.Exit(1)
		}

		eval, err := jsonpath.EvalPathsInReader(f, paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
		f.Close()

	} else if jsonPtr != nil && *jsonPtr != "" {
		eval, err := jsonpath.EvalPathsInBytes([]byte(*jsonPtr), paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
	} else {
		reader := bufio.NewReader(os.Stdin)
		eval, err := jsonpath.EvalPathsInReader(reader, paths)
		checkAndHandleError(err)
		run(eval, *showKeysPtr)
		checkAndHandleError(eval.Error)
	}
}
Example #8
0
func main() {
	verbose := flag.BoolP("verbose", "v", false, "Verbose mode")
	flag.Parse()

	logger = initLogger(*verbose)

	switch {
	case len(flag.Args()) == 0:
		Serve()
	case len(flag.Args()) >= 1:
		RunCommand(flag.Arg(0), flag.Args()[1:])
	default:
		printUsage()
		os.Exit(2)
	}
}
Example #9
0
File: main.go Project: dawanda/mmsd
func (mmsd *mmsdService) Run() {
	flag.BoolVarP(&mmsd.Verbose, "verbose", "v", mmsd.Verbose, "Set verbosity level")
	flag.IPVar(&mmsd.MarathonIP, "marathon-ip", mmsd.MarathonIP, "Marathon endpoint TCP IP address")
	flag.UintVar(&mmsd.MarathonPort, "marathon-port", mmsd.MarathonPort, "Marathon endpoint TCP port number")
	flag.DurationVar(&mmsd.ReconnectDelay, "reconnect-delay", mmsd.ReconnectDelay, "Marathon reconnect delay")
	flag.StringVar(&mmsd.RunStateDir, "run-state-dir", mmsd.RunStateDir, "Path to directory to keep run-state")
	flag.StringVar(&mmsd.FilterGroups, "filter-groups", mmsd.FilterGroups, "Application group filter")
	flag.IPVar(&mmsd.ManagedIP, "managed-ip", mmsd.ManagedIP, "IP-address to manage for mmsd")
	flag.BoolVar(&mmsd.GatewayEnabled, "enable-gateway", mmsd.GatewayEnabled, "Enables gateway support")
	flag.IPVar(&mmsd.GatewayAddr, "gateway-bind", mmsd.GatewayAddr, "gateway bind address")
	flag.UintVar(&mmsd.GatewayPortHTTP, "gateway-port-http", mmsd.GatewayPortHTTP, "gateway port for HTTP")
	flag.UintVar(&mmsd.GatewayPortHTTPS, "gateway-port-https", mmsd.GatewayPortHTTPS, "gateway port for HTTPS")
	flag.BoolVar(&mmsd.FilesEnabled, "enable-files", mmsd.FilesEnabled, "enables file based service discovery")
	flag.BoolVar(&mmsd.UDPEnabled, "enable-udp", mmsd.UDPEnabled, "enables UDP load balancing")
	flag.BoolVar(&mmsd.TCPEnabled, "enable-tcp", mmsd.TCPEnabled, "enables haproxy TCP load balancing")
	flag.BoolVar(&mmsd.LocalHealthChecks, "enable-health-checks", mmsd.LocalHealthChecks, "Enable local health checks (if available) instead of relying on Marathon health checks alone.")
	flag.StringVar(&mmsd.HaproxyBin, "haproxy-bin", mmsd.HaproxyBin, "path to haproxy binary")
	flag.StringVar(&mmsd.HaproxyTailCfg, "haproxy-cfgtail", mmsd.HaproxyTailCfg, "path to haproxy tail config file")
	flag.IPVar(&mmsd.ServiceAddr, "haproxy-bind", mmsd.ServiceAddr, "haproxy management port")
	flag.UintVar(&mmsd.HaproxyPort, "haproxy-port", mmsd.HaproxyPort, "haproxy management port")
	flag.BoolVar(&mmsd.DnsEnabled, "enable-dns", mmsd.DnsEnabled, "Enables DNS-based service discovery")
	flag.UintVar(&mmsd.DnsPort, "dns-port", mmsd.DnsPort, "DNS service discovery port")
	flag.BoolVar(&mmsd.DnsPushSRV, "dns-push-srv", mmsd.DnsPushSRV, "DNS service discovery to also push SRV on A")
	flag.StringVar(&mmsd.DnsBaseName, "dns-basename", mmsd.DnsBaseName, "DNS service discovery's base name")
	flag.DurationVar(&mmsd.DnsTTL, "dns-ttl", mmsd.DnsTTL, "DNS service discovery's reply message TTL")
	showVersionAndExit := flag.BoolP("version", "V", false, "Shows version and exits")

	flag.Usage = func() {
		showVersion()
		fmt.Fprintf(os.Stderr, "\nUsage: mmsd [flags ...]\n\n")
		flag.PrintDefaults()
		fmt.Fprintf(os.Stderr, "\n")
	}

	flag.Parse()

	if *showVersionAndExit {
		showVersion()
		os.Exit(0)
	}

	mmsd.setupHandlers()
	mmsd.setupEventBusListener()
	mmsd.setupHttpService()

	<-mmsd.quitChannel
}
Example #10
0
func main() {
	pflag.Usage = func() {
		fmt.Fprintf(os.Stderr, USAGE)
	}

	var output = pflag.StringP("output", "o", ".", "output directory")
	var version = pflag.BoolP("version", "", false, "version")
	pflag.Parse()

	if *version {
		fmt.Println(VERSION)
	} else if pflag.NArg() == 1 {
		genRoutes(pflag.Arg(0), *output)
	} else {
		pflag.Usage()
	}
}
Example #11
0
File: main.go Project: dsnet/crypto
func main() {
	// Basic user configuration variables
	force := pflag.BoolP("force", "f", false, "Force output to terminal.")
	count := pflag.StringP("count", "n", "+Inf", "Number of random bytes to generate.")
	procs := pflag.IntP("procs", "p", runtime.NumCPU(), "Maximum number of concurrent workers.")
	pflag.Parse()

	if !(*force) && terminal.IsTerminal(int(os.Stdout.Fd())) {
		fmt.Fprintf(os.Stderr, "Random data not written to terminal.\n\n")
		pflag.Usage()
		os.Exit(1)
	}
	cnt, err := strconv.ParsePrefix(*count, strconv.AutoParse)
	if err != nil || math.IsNaN(cnt) {
		fmt.Fprintf(os.Stderr, "Number of bytes to generate is invalid.\n\n")
		pflag.Usage()
		os.Exit(1)
	}
	if (*procs) < 1 {
		fmt.Fprintf(os.Stderr, "Number of workers must be positive.\n\n")
		pflag.Usage()
		os.Exit(1)
	}

	runtime.GOMAXPROCS(*procs)
	rand.SetNumRoutines(*procs)

	// Copy random data to stdout
	if int64(cnt) < 0 || math.IsInf(cnt, 0) {
		_, err = io.Copy(os.Stdout, rand.Reader)
	} else {
		_, err = io.CopyN(os.Stdout, rand.Reader, int64(cnt))
	}
	if perr, ok := err.(*os.PathError); ok && perr.Err == syscall.EPIPE {
		err = nil // Expected error is for the sink to close the pipe
	} else if err != nil {
		panic(err)
	}
}
Example #12
0
func main() {
	cFlag := flag.BoolP("no-create", "c", false, "do not create file")
	flag.Parse()
	if len(flag.Args()) > 0 {
		for i := 0; i < len(flag.Args()); i++ {
			filename := flag.Arg(i)
			_, err := os.Stat(filename)
			if err == nil {
				now := time.Now()
				os.Chtimes(filename, now, now)
			} else {
				if !(*cFlag) {
					f, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE, 0644)
					f.Close()
					if err != nil {
						log.Fatal(err)
					}
				}
			}
		}
	}
}
Example #13
0
func main() {
	flagAppend := flag.BoolP("append", "a", false, "append to file")
	flag.Parse()
	bytes, _ := ioutil.ReadAll(os.Stdin)
	for i := 0; i < len(flag.Args()); i++ {
		if *flagAppend {
			f, err := os.OpenFile(flag.Args()[i], os.O_WRONLY|os.O_CREATE|os.O_APPEND, 0644)
			if err != nil {
				log.Fatal(err)
			}
			f.Write(bytes)
			f.Close()
		} else {
			f, err := os.OpenFile(flag.Args()[i], os.O_WRONLY|os.O_CREATE, 0644)
			if err != nil {
				log.Fatal(err)
			}
			f.Write(bytes)
			f.Close()
		}
	}
	fmt.Printf("%s", string(bytes))
}
Example #14
0
	Text string
	Time string `json:"created_at"`
}

type twmeta struct {
	RefreshUrl string `json:"refresh_url"`
}
type twitresp struct {
	Statuses []twstatus
	Meta     twmeta `json:"search_metadata"`
}

const twSearchBase = "https://api.twitter.com/1.1/search/tweets.json"

var resnum = flag.IntP("number", "n", 20, "number of items to return")
var reverse = flag.BoolP("reverse", "r", false, "reverse order")
var retweets = flag.BoolP("retweets", "R", false, "include retweeets")
var follow = flag.BoolP("follow", "f", false, "follow mode")
var followDelay = flag.DurationP("followdelay", "F", time.Minute, "refresh delay in follow mode")

var fixes = strings.NewReplacer(
	"\n", ` \n `, // spaces to make c&p easier
	"‘", `'`,
	"’", `'`,
	"“", `"`,
	"”", `"`,
	"—", "-",
	"&amp;", "&",
	"&lt;", "<",
	"&gt;", ">",
	"&quot;", `"`,
Example #15
0
Go coreutils home page: <https://www.github.com/EricLagerg/go-coreutils/>
`

	Version = `
	uptime (Go coreutils) 1.0
Copyright (C) 2015 Eric Lagergren
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
`

	delim = " "
)

var (
	version = flag.BoolP("version", "v", false, "")

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

func printUptime(us []utmp.Utmp) {

	var (
		bootTime int32
		entries  int64
		now      utmp.TimeVal

		days, hours, mins int
		uptime            float64
	)
	flag "github.com/ogier/pflag"
	gutenberg "gutenberg.org"
	"gutenberg.org/config"
	"gutenberg.org/plugins"
	"io/ioutil"
	"log"
	"os"
	"path/filepath"
	"strings"
	"text/template"
	"time"
)

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

type Process struct {
	// Process is done
	Done chan bool
	// Source directory for the book
	Source string
	// Started
	Started bool
Example #17
0
	"github.com/golang/glog"
	"github.com/ogier/pflag"
	"io/ioutil"
	"net/http"
	"os"
	"os/signal"
	"os/user"
	"strconv"
	"strings"
	"syscall"
)

// The command line flags available
var (
	// Log related flags
	logToStderr  = pflag.BoolP("logtostderr", "e", true, "log to stderr instead of to files")
	logThreshold = pflag.StringP("logthreshold", "o", "INFO", "Log events at or above this severity are logged to standard error as well as to files. Possible values: INFO, WARNING, ERROR and FATAL")
	logdir       = pflag.StringP("logpath", "l", "./logs", "The log files will be written in this directory/path")

	flushInterval = pflag.Int64P("flushinterval", "f", 59, "The interval between the PUT of batches of mac-addresses")
	iface         = pflag.StringP("interface", "i", "mon0", "The capture interface to listen on")
	pcap          = pflag.StringP("pcap", "p", "", "Use a pcap file instead of live capturing")
	server        = pflag.StringP("server", "s", "http://localhost:3000/sessions.json", "Server to PUT macs to")
	authToken     = pflag.StringP("token", "t", "", "API-token. (Required)")
	printResponse = pflag.BoolP("printresponse", "r", false, "Print response from backend")
	hitCount      uint64
)

func init() {
	pflag.Parse()
Example #18
0
Written by Eric Lagergren
Inspired by David MacKenzie.`
	HELP = `Usage: tty [OPTION]...
Print the file name of the terminal connected to standard input.

  -s, --silent, --quiet   print nothing, only return an exit status
      --help     display this help and exit
      --version  output version information and exit

Report uname bugs to [email protected]
Go coreutils home page: <https://www.github.com/EricLagergren/go-coreutils/>`
)

var (
	version = flag.Bool("version", false, "print version")
	quiet1  = flag.BoolP("silent", "s", false, "no output")
	quiet2  = flag.Bool("quiet", false, "no output")
)

func main() {
	flag.Usage = func() {
		fmt.Fprintf(os.Stderr, "%s\n", HELP)
		return
	}
	flag.Parse()

	if *version {
		fmt.Printf("%s\n", VERSION)
		return
	}
Example #19
0
	sparseUnused = iota
	sparseNever
	sparseAuto
	sparseAlways
)

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

var (
	archive           = flag.BoolP("archive", "a", false, "")
	attrOnly          = flag.Bool("attributes-only", false, "")
	backup            = flag.String("backup", "", "")
	backup2           = flag.Bool("b", false, "")
	copyContents      = flag.Bool("copy-contents", false, "")
	ndrpl             = flag.Bool("d", false, "")
	dereference       = flag.BoolP("dereference", "L", false, "")
	force             = flag.BoolP("force", "f", false, "")
	hopt              = flag.Bool("H", false, "")
	interactive       = flag.BoolP("interactive", "i", false, "")
	link              = flag.BoolP("link", "l", false, "")
	noClobber         = flag.BoolP("no-clobber", "n", false, "")
	noDereference     = flag.BoolP("no-dereference", "P", false, "")
	noPreserve        = flag.String("no-preserve", "", "")
	noTargetDir       = flag.BoolP("no-target-directory", "T", false, "")
	oneFS             = flag.BoolP("one-file-system", "x", false, "")
Example #20
0
the formal base64 alphabet.  Use --ignore-garbage to attempt to recover
from any other non-alphabet bytes in the encoded stream.

`
	Version = `
base64 (Go coreutils) 0.1
Copyright (C) 2015 Robert Deusser
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

`
)

var (
	decode  = flag.BoolP("decode", "d", false, "")
	ignore  = flag.BoolP("ignore-garbage", "i", false, "")
	wrap    = flag.IntP("wrap", "w", 76, "")
	version = flag.BoolP("version", "v", false, "")
)

func base64Encode(src []byte) []byte {
	return []byte(base64.StdEncoding.EncodeToString(src))
}

func base64Decode(src []byte) ([]byte, error) {
	return base64.StdEncoding.DecodeString(string(src))
}

func readData(reader io.Reader) ([]byte, error) {
	return ioutil.ReadAll(reader)
Example #21
0
    -l, --length       stop after <len> octets.
    -p, --ps           output in postscript plain hexdump style.
    -r, --reverse      reverse operation: convert (or patch) hexdump into ASCII output.
                       * reversing non-hexdump formats require -r<flag> (i.e. -rb, -ri, -rp).
    -s, --seek         start at <seek> bytes/bits in file. Byte/bit postfixes can be used.
    		       * byte/bit postfix units are multiples of 1024.
    		       * bits (kb, mb, etc.) will be rounded down to nearest byte.
    -u, --uppercase    use upper case hex letters.
    -v, --version      show version.`

	Version = `xxd v2.0 2014-17-01 by Felix Geisendörfer and Eric Lagergren`
)

// cli flags
var (
	autoskip   = flag.BoolP("autoskip", "a", false, "toggle autoskip (* replaces nul lines")
	bars       = flag.BoolP("bars", "B", false, "print |ascii| instead of ascii")
	binary     = flag.BoolP("binary", "b", false, "binary dump, incompatible with -ps, -i, -r")
	columns    = flag.IntP("cols", "c", -1, "format <cols> octets per line")
	ebcdic     = flag.BoolP("ebcdic", "E", false, "use EBCDIC instead of ASCII")
	group      = flag.IntP("group", "g", -1, "num of octets per group")
	cfmt       = flag.BoolP("include", "i", false, "output in C include format")
	length     = flag.Int64P("len", "l", -1, "stop after len octets")
	postscript = flag.BoolP("ps", "p", false, "output in postscript plain hd style")
	reverse    = flag.BoolP("reverse", "r", false, "convert hex to binary")
	offset     = flag.Int("off", 0, "revert with offset")
	seek       = flag.StringP("seek", "s", "", "start at seek bytes abs")
	upper      = flag.BoolP("uppercase", "u", false, "use uppercase hex letters")
	version    = flag.BoolP("version", "v", false, "print version")
)
Example #22
0
File: main.go Project: nsabine/hugo
	flag "github.com/ogier/pflag"
	"github.com/spf13/hugo/hugolib"
	"log"
	"net/http"
	"os"
	"path/filepath"
	"runtime/pprof"
	"sync"
	"time"
)

var (
	baseUrl     = flag.StringP("base-url", "b", "", "hostname (and path) to the root eg. http://spf13.com/")
	cfgfile     = flag.String("config", "", "config file (default is path/config.yaml|json|toml)")
	checkMode   = flag.Bool("check", false, "analyze content and provide feedback")
	draft       = flag.BoolP("build-drafts", "D", false, "include content marked as draft")
	help        = flag.BoolP("help", "h", false, "show this help")
	source      = flag.StringP("source", "s", "", "filesystem path to read files relative from")
	destination = flag.StringP("destination", "d", "", "filesystem path to write files to")
	verbose     = flag.BoolP("verbose", "v", false, "verbose output")
	version     = flag.Bool("version", false, "which version of hugo")
	cpuprofile  = flag.Int("profile", 0, "Number of times to create the site and profile it")
	watchMode   = flag.BoolP("watch", "w", false, "watch filesystem for changes and recreate as needed")
	server      = flag.BoolP("server", "S", false, "run a (very) simple web server")
	port        = flag.String("port", "1313", "port to run web server on, default :1313")
	uglyUrls    = flag.Bool("uglyurls", false, "use /filename.html instead of /filename/ ")
)

func usage() {
	PrintErr("usage: hugo [flags]", "")
	flag.PrintDefaults()
Example #23
0
	"fmt"
	"net"
	"os"
	"strconv"
	"text/tabwriter"
)

// TODO implement the following flags
//       -x: extended hostnames view
//       -r src | dst | src-port | dst-port | state : sort connections
//       -N: display NAT box connection information (only valid with SNAT & DNAT)

var Version = "0.1.0"

var onlySNAT = flag.BoolP("snat", "S", false, "Display only SNAT connections")
var onlyDNAT = flag.BoolP("dnat", "D", false, "Display only DNAT connections")
var onlyLocal = flag.BoolP("local", "L", false, "Display only local connections (originating from or going to the router)")
var onlyRouted = flag.BoolP("routed", "R", false, "Display only connections routed through the router")
var noResolve = flag.BoolP("no-resolve", "n", false, "Do not resolve hostnames") // TODO resolve port names as well
var noHeader = flag.BoolP("no-header", "o", false, "Strip output header")
var protocol = flag.StringP("protocol", "p", "", "Filter connections by protocol")
var sourceHost = flag.StringP("source", "s", "", "Filter by source IP")
var destinationHost = flag.StringP("destination", "d", "", "Filter by destination IP")
var displayVersion = flag.BoolP("version", "v", false, "Print version")

func main() {
	flag.Parse()

	if *displayVersion {
		fmt.Println("Version " + Version)
Example #24
0
import (
	"fmt"
	"net"
	"os"

	flag "github.com/ogier/pflag"
)

const (
	tokenEnvName = "DO_API_TOKEN"
)

var (
	token = flag.StringP("token", "t", tokenEnvName, "DigitialOcean APIv2 token")
	v4opt = flag.BoolP("v4", "4", false, "Update IPv4 A record")
	v6opt = flag.BoolP("v6", "6", false, "Update IPv6 AAAA record")
)

func errorOut(msg string, err error) {
	fmt.Fprintf(os.Stderr, "Error %s: %v\n", msg, err)
	os.Exit(1)
}

func main() {
	flag.Parse()

	if *token == tokenEnvName {
		*token = os.Getenv(tokenEnvName)
	}
Example #25
0
import (
	"encoding/csv"
	"fmt"
	"io"
	"os"
	"strconv"
	"unicode/utf8"

	flag "github.com/ogier/pflag"
)

const programVersion = "0.0.1"

var (
	ignore = flag.BoolP("ignore", "i", false, "ignore invalid numbers")
	behead = flag.BoolP("behead", "b", false,
		"remove the first line (head) from calculations. Useful to ignore column names")
	separator = flag.StringP("separator", "s", " ",
		"define the SEPARATOR to use instead of whitespace for column separator")
	column  = flag.IntP("column", "c", 1, "calculate stats based on the specified COLUMN")
	version = flag.BoolP("version", "v", false, "print version information and exit")
)

func fail(format string, v ...interface{}) {
	fmt.Fprintf(os.Stderr, format, v...)
	os.Exit(1)
}

func calculate(s *Stats) {
	if len(flag.Args()) == 0 {
Example #26
0
	"strings"
	"sync"
	"time"
	"wp/sss"
)

const concurrency = 100
const sseKey string = "server-side-encryption"

var sseValue = []string{"AES256"}

var meta = map[string][]string{}
var node string
var bucket = flag.StringP("bucket", "b", "", "Use the named bucket")
var prefix = flag.StringP("prefix", "x", "", "Set upload path prefix. i.e., '-x location/'. NB: Add a slash if you want it!")
var public = flag.BoolP("public", "p", false, "Makes the uploaded files publicly visible")
var force = flag.BoolP("force", "f", false, "Force upload regardless of existance or mtime")
var sse = flag.BoolP("sse", "e", false, "Use server side encryption")
var mimetype = flag.StringP("mimetype", "m", "binary/octet-stream", "Set a fallback/default mimetype string.")

// XXX: Should this always be true? I think so.
var newer = flag.BoolP("newer", "n", false, "Upload if file time is newer than Last-modified")
var newermetamtime = flag.BoolP("newermetamtime", "N", false, "Upload if file is newer than x-amz-meta-last-modified")

// var recursive = flag.BoolP("recursive", "r", false, "Upload everything resursively from the path")
// verify sums?
// add a flag to use text/html as the default/fallback mime type instead of binary/octet-stream

type FileUpload struct {
	ContentType string
	Path        string
Example #27
0
import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"os/user"

	"github.com/Unknwon/goconfig"
	"github.com/ogier/pflag"
)

// CLI flags
var _host = pflag.StringP("host", "h", "some.hostname.com", "The DRAC host (or IP)")
var _username = pflag.StringP("username", "u", "", "The DRAC username")
var _password = pflag.BoolP("password", "p", false, "Prompt for password (optional, will use 'calvin' if not present)")
var javaws = pflag.StringP("javaws", "j", "/usr/bin/javaws", "The path to javaws binary")

func promptPassword() string {
	var pass string
	fmt.Print("Password: "******"Unable to read password from CLI")
	}
	return pass
}

func main() {
	var host string
	var username = "******"
func main() {

	var name *string = flag.StringP("name", "n", "", "Only run the instruction with this name")
	var project *string = flag.StringP("project", "p", "", "Only run the instruction that are apart of this project")
	var force_deploy *bool = flag.BoolP("force", "f", false, "Force a redeploy of everything in the conductor.yml file")
	flag.Parse()

	cd := []ConductorDirections{}

	data, _ := ioutil.ReadFile("conductor.yml")
	err := yaml.Unmarshal(data, &cd)
	if err != nil {
		panic(err)
	}

	for _, instr := range cd {
		if *name != "" {
			if instr.Name != *name {
				continue
			}
		}
		if *project != "" {
			if instr.Project != *project {
				continue
			}
		}
		// fmt.Printf("--- m:\n%v\n\n", instr)
		for _, host := range instr.Hosts {

			docker_ctrl := conductor.New(host)
			container := docker_ctrl.FindContainer(instr.Container.Name)
			host_log := log.New("\t\t\t\t[host]", host, "[container]", instr.Container.Name)

			if instr.Healthcheck != "" {
				health := healthcheck.New(host_log, instr.Healthcheck, host)
				health.Check()
			}

			host_log.Info("[ ] pulling image")
			pulled_image, err := docker_ctrl.PullImage(instr.Container.Image + ":latest")
			if err != nil {
				host_log.Error("Error pulling image: " + err.Error())
			}
			host_log.Info("[x] finished pulling image")

			if container.Container != nil {
				if pulled_image == container.Container.Image && *force_deploy == false {
					host_log.Info("skipping, container running latest image : " + pulled_image)
					continue
				}

				if container.ID() != "" {
					if err := docker_ctrl.RemoveContainer(container.ID()); err != nil {
						host_log.Error(err.Error())
					}
				}
			}

			host_log.Info("[ ] creating container")
			docker_ctrl.CreateAndStartContainer(conductor.ConductorContainerConfig{
				Name:        instr.Container.Name,
				Image:       instr.Container.Image,
				PortMap:     instr.Container.Ports,
				Environment: instr.Container.Environment,
				Volumes:     instr.Container.Volumes,
				Dns:         instr.Container.Dns,
			})
			host_log.Info("[x] finished creating container")
		}

	}

}
Example #29
0
	// Our cumulative number of lines, words, chars, and bytes.
	totalLines    int64
	totalWords    int64
	totalChars    int64
	totalBytes    int64
	maxLineLength int64

	// For pretty printing.
	numberWidth int
	printOne    bool

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

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

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

type fstatus struct {
Example #30
0
	Version = `who (Go coreutils) 1.0
Copyright (C) 2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>.
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

Written by Eric Lagergren`
)

var (
	dev = []byte("/dev/")
	bt  int32
)

var (
	all       = flag.BoolP("all", "a", false, "")
	boot      = flag.BoolP("boot", "b", false, "")
	dead      = flag.BoolP("dead", "d", false, "")
	heading   = flag.BoolP("heading", "H", false, "")
	ips       = flag.Bool("ips", false, "")
	login     = flag.BoolP("login", "l", false, "")
	cur       = flag.Bool("m", false, "")
	proc      = flag.BoolP("process", "p", false, "")
	count     = flag.BoolP("count", "q", false, "")
	rlvl      = flag.BoolP("runlevel", "r", false, "")
	short     = flag.BoolP("short", "s", false, "")
	clock     = flag.BoolP("time", "t", false, "")
	users     = flag.BoolP("users", "u", false, "")
	mesg      = flag.BoolP("mesg", "T", false, "")
	mesgTwo   = flag.BoolP("message", "w", false, "")
	mesgThree = flag.Bool("writable", false, "")