コード例 #1
0
ファイル: config.go プロジェクト: longbai/tsunami-udp-go
/*------------------------------------------------------------------------
 * void process_options();
 *
 * Processes the command-line options and sets the protocol parameters
 * as appropriate.
 *------------------------------------------------------------------------*/
func ProcessOptions() *Parameter {
	parameter := NewParameter()

	opt.BoolVarLong(&parameter.verbose, "verbose", 'v',
		"turns on verbose output mode, deafult off")
	opt.BoolVarLong(&parameter.transcript, "transcript", 't',
		"turns on transcript mode for statistics recording, deafult off")
	opt.BoolVarLong(&parameter.ipv6, "v6", '6',
		"operates using IPv6 instead of (not in addition to!) IPv4")
	deafultHelp := fmt.Sprintf(
		"specifies which TCP port on which to listen to incoming connections, default %d",
		tsunami.TS_TCP_PORT)
	port := opt.Uint16Long("port", 'p', tsunami.TS_TCP_PORT, deafultHelp)
	secret := opt.StringLong("secret", 's', tsunami.DEFAULT_SECRET,
		"specifies the shared secret for the client and server")

	deafultHelp = fmt.Sprintf(
		"specifies the desired size for UDP socket send buffer (in bytes), default %d",
		DEFAULT_UDP_BUFFER)
	buffer := opt.Uint32Long("buffer", 'b', DEFAULT_UDP_BUFFER, deafultHelp)

	deafultHelp = fmt.Sprintf(
		"specifies the timeout in seconds for disconnect after client heartbeat lost, default %d",
		DEFAULT_HEARTBEAT_TIMEOUT)
	hbtimeout := opt.Uint16Long("hbtimeout", 'h', DEFAULT_HEARTBEAT_TIMEOUT, deafultHelp)
	opt.StringVarLong(&parameter.client, "client", 'c',
		"specifies an alternate client IP or host where to send data")
	opt.StringVarLong(&parameter.finishhook, "finishhook", 'f',
		"run command on transfer completion, file name is appended automatically")
	opt.StringVarLong(&parameter.allhook, "allhook", 'a',
		"run command on 'get *' to produce a custom file list for client downloads")
	opt.Parse()

	parameter.tcp_port = *port
	parameter.secret = *secret
	parameter.udp_buffer = *buffer
	parameter.hb_timeout = *hbtimeout

	files := opt.Args()
	parameter.file_names = files
	parameter.file_sizes = make([]uint64, len(files))
	parameter.total_files = uint16(len(files))
	for i, v := range files {
		stat, err := os.Stat(v)
		if err != nil {
			fmt.Fprintln(os.Stderr, v, err)
		} else {
			size := stat.Size()
			parameter.file_sizes[i] = uint64(size)
			fmt.Fprintf(os.Stderr, " %3d)   %-20s  %d bytes\n", i+1, v, size)
		}
	}

	parameter.VerboseArg("")
	return parameter
}
コード例 #2
0
ファイル: indexer.go プロジェクト: cardi/timefind
func main() {
	getopt.ListVarLong(&configPaths, "config", 'c',
		"REQUIRED: Path to configuration file (can be used multiple times)", "PATH")
	getopt.BoolVarLong(&verbose, "verbose", 'v', "Verbose progress indicators and messages")
	help := getopt.BoolLong("help", 'h', "Show this help message and exit")
	getopt.SetParameters("")
	getopt.Parse()

	if *help {
		getopt.Usage()
		os.Exit(0)
	}

	if len(configPaths) == 0 {
		log.Printf("no configuration (-c/--config) found")
		getopt.Usage()
		os.Exit(1)
	}

	log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile)

	// set parallelism (automatic in Go 1.6+)
	if runtime.GOMAXPROCS(0) < runtime.NumCPU() {
		runtime.GOMAXPROCS(runtime.NumCPU())
		log.Printf("setting GOMAXPROCS = NumCPU = %d\n", runtime.NumCPU())
	}

	for _, configPath := range configPaths {

		cfg, err := config.NewConfiguration(configPath)
		if err != nil {
			log.Fatal(err)
			continue
		}

		idx, err := index.NewIndex(cfg)
		if err != nil {
			log.Print(err)
			return
		}

		if err := idx.Update(); err != nil {
			log.Print(err)
			return
		}

		if err := idx.WriteOut(); err != nil {
			log.Print(err)
			return
		}
	}
}
コード例 #3
0
ファイル: main.go プロジェクト: gnomix/weave
func main() {
	var (
		justVersion bool
		logLevel    = "info"
		c           = proxy.Config{ListenAddrs: defaultListenAddrs}
	)

	c.Version = version
	getopt.BoolVarLong(&justVersion, "version", 0, "print version and exit")
	getopt.StringVarLong(&logLevel, "log-level", 0, "logging level (debug, info, warning, error)", "info")
	getopt.ListVar(&c.ListenAddrs, 'H', fmt.Sprintf("address on which to listen (default %s)", defaultListenAddrs))
	getopt.BoolVarLong(&c.NoDefaultIPAM, "no-default-ipalloc", 0, "do not automatically allocate addresses for containers without a WEAVE_CIDR")
	getopt.BoolVarLong(&c.NoDefaultIPAM, "no-default-ipam", 0, "do not automatically allocate addresses for containers without a WEAVE_CIDR (deprecated; please use --no-default-ipalloc")
	getopt.StringVarLong(&c.TLSConfig.CACert, "tlscacert", 0, "Trust certs signed only by this CA")
	getopt.StringVarLong(&c.TLSConfig.Cert, "tlscert", 0, "Path to TLS certificate file")
	getopt.BoolVarLong(&c.TLSConfig.Enabled, "tls", 0, "Use TLS; implied by --tlsverify")
	getopt.StringVarLong(&c.TLSConfig.Key, "tlskey", 0, "Path to TLS key file")
	getopt.BoolVarLong(&c.TLSConfig.Verify, "tlsverify", 0, "Use TLS and verify the remote")
	getopt.BoolVarLong(&c.WithDNS, "with-dns", 'w', "instruct created containers to always use weaveDNS as their nameserver")
	getopt.BoolVarLong(&c.WithoutDNS, "without-dns", 0, "instruct created containers to never use weaveDNS as their nameserver")
	getopt.Parse()

	if justVersion {
		fmt.Printf("weave proxy %s\n", version)
		os.Exit(0)
	}

	if c.WithDNS && c.WithoutDNS {
		Log.Fatalf("Cannot use both '--with-dns' and '--without-dns' flags")
	}

	SetLogLevel(logLevel)

	Log.Infoln("weave proxy", version)
	Log.Infoln("Command line arguments:", strings.Join(os.Args[1:], " "))

	p, err := proxy.NewProxy(c)
	if err != nil {
		Log.Fatalf("Could not start proxy: %s", err)
	}

	p.ListenAndServe()
}
コード例 #4
0
func GetOptions() ([]string, string) {

	var files []string

	// parse option, move outside main
	optDebug = getopt.Bool('d', "debug", "Display debug info")
	optEcho = getopt.Bool('e', "echo", "Display processing in stdout")
	optHelp := getopt.Bool('h', "help", "Help")
	optAll = getopt.Bool('a', "all", "Process all parameters")
	optVersion := getopt.BoolLong("version", 'v', "Show version, then exit.")
	optCfgfile := getopt.StringLong("config", 'c', fileconfig, "Name of the configuration file to use.")
	//	optCycleMesure := getopt.StringLong("cycle_mesure", 'm', "", "Name of cycle_mesure")
	optFiles := getopt.StringLong("files", 'f', "", "files to process ex: data/fr25*.cnv")

	// parse options line argument
	getopt.Parse()

	// process bloc when option is set
	if *optHelp {
		getopt.Usage()
		os.Exit(0)
	}
	if *optVersion {
		fmt.Println(cfg.Progname + ": v" + cfg.Progversion)
		fmt.Printf("Environnement variable OCEANO2OCEANSITES: %s\n", os.Getenv("OCEANO2OCEANSITES"))
		fmt.Printf("Environnement variable ROSCOP: %s\n", os.Getenv("ROSCOP"))
		fmt.Printf("Configuration file: %s\n", fileconfig)
		fmt.Printf("Code ROSCOP file: %s\n", cfg.Roscopfile)
		fmt.Printf("GOPATH: %s\n", os.Getenv("GOPATH"))
		fmt.Printf("GOBIN: %s\n", os.Getenv("GOBIN"))
		os.Exit(0)
	}
	if *optDebug {
		debug = os.Stdout
	}
	if *optEcho {
		echo = os.Stdout
	}

	if *optAll {
		prefixAll = "-all"
	}
	// get files list from argument line
	// Args returns the non-option arguments.
	// see https://code.google.com/p/getopt/source/browse/set.go#27
	if *optFiles == "" {
		files = getopt.Args()
	} else {
		files, _ = filepath.Glob(*optFiles)
	}
	// if no files supplied for arg list, test if files is empty
	if len(files) == 0 {
		getopt.Usage()
		fmt.Println("\nPlease, specify files to process or define --files options")
		os.Exit(0)
	}
	//	if *optCycleMesure != "" {
	//		fmt.Println(*optCycleMesure)
	//		nc.Attributes["cycle_mesure"] = *optCycleMesure
	//	}
	fmt.Fprintln(debug, "Arg files list: ", files)
	return files, *optCfgfile
}
コード例 #5
0
ファイル: yang.go プロジェクト: padmini-m/goyang
func main() {
	format := "tree"
	formats := make([]string, 0, len(formatters))
	for k := range formatters {
		formats = append(formats, k)
	}
	sort.Strings(formats)

	var traceP string
	var help bool
	getopt.CommandLine.ListVarLong(&yang.Path, "path", 0, "comma separated list of directories to add to PATH")
	getopt.CommandLine.StringVarLong(&format, "format", 0, "format to display: "+strings.Join(formats, ", "))
	getopt.CommandLine.StringVarLong(&traceP, "trace", 0, "file to write trace into")
	getopt.CommandLine.BoolVarLong(&help, "help", '?', "display help")

	getopt.Parse()

	if traceP != "" {
		fp, err := os.Create(traceP)
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
		trace.Start(fp)
		stop = func(c int) { trace.Stop(); os.Exit(c) }
		defer func() { trace.Stop() }()
	}

	if help {
		getopt.CommandLine.PrintUsage(os.Stderr)
		fmt.Fprintf(os.Stderr, "\nFormats:\n")
		for _, fn := range formats {
			f := formatters[fn]
			fmt.Fprintf(os.Stderr, "    %s - %s\n", f.name, f.help)
		}
		stop(0)
	}

	if _, ok := formatters[format]; !ok {
		fmt.Fprintf(os.Stderr, "%s: invalid format.  Choices are %s\n", format, strings.Join(formats, ", "))
		stop(1)

	}

	files := getopt.Args()

	if len(files) > 0 && !strings.HasSuffix(files[0], ".yang") {
		e, errs := yang.GetModule(files[0], files[1:]...)
		exitIfError(errs)
		Write(os.Stdout, e)
		return
	}

	// Okay, either there are no arguments and we read stdin, or there
	// is one or more file names listed.  Read them in and display them.

	ms := yang.NewModules()

	if len(files) == 0 {
		data, err := ioutil.ReadAll(os.Stdin)
		if err == nil {
			err = ms.Parse(string(data), "<STDIN>")
		}
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			stop(1)
		}
	}

	for _, name := range files {
		if err := ms.Read(name); err != nil {
			fmt.Fprintln(os.Stderr, err)
			continue
		}
	}

	// Process the read files, exiting if any errors were found.
	exitIfError(ms.Process())

	// Keep track of the top level modules we read in.
	// Those are the only modules we want to print below.
	mods := map[string]*yang.Module{}
	var names []string

	for _, m := range ms.Modules {
		if mods[m.Name] == nil {
			mods[m.Name] = m
			names = append(names, m.Name)
		}
	}
	sort.Strings(names)
	entries := make([]*yang.Entry, len(names))
	for x, n := range names {
		entries[x] = yang.ToEntry(mods[n])
	}

	formatters[format].f(os.Stdout, entries)
}
コード例 #6
0
ファイル: main.go プロジェクト: saymedia/terraform-s3-dir
func main() {
	getopt.SetParameters("<root dir> <bucket name>")
	getopt.Parse()
	if *help {
		getopt.PrintUsage(os.Stdout)
		return
	}

	args := getopt.Args()
	if len(args) != 2 {
		getopt.PrintUsage(os.Stderr)
		os.Exit(1)
	}

	rootDir := args[0]
	bucketName := args[1]

	resourcesMap := map[string]interface{}{}
	result := map[string]interface{}{
		"resource": map[string]interface{}{
			"aws_s3_bucket_object": resourcesMap,
		},
	}

	filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error reading %s: %s\n", path, err)
			// Skip stuff we can't read.
			return nil
		}

		relPath, err := filepath.Rel(rootDir, path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed make %s relative: %s\n", path, err)
			return nil
		}

		path, err = filepath.EvalSymlinks(path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to resolve symlink %s: %s\n", path, err)
			return nil
		}

		if info.IsDir() {
			// Don't need to create directories since they are implied
			// by the files within.
			return nil
		}

		for _, pattern := range *exclude {
			var toMatch []string
			if strings.ContainsRune(pattern, filepath.Separator) {
				toMatch = append(toMatch, relPath)
			} else {
				// If the pattern does not include a path separator
				// then we apply it to all segments of the path
				// individually.
				toMatch = strings.Split(relPath, string(filepath.Separator))
			}

			for _, matchPath := range toMatch {
				matched, _ := filepath.Match(pattern, matchPath)
				if matched {
					return nil
				}
			}
		}

		// We use the initial bytes of the file to infer a MIME type
		file, err := os.Open(path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error opening %s: %s\n", path, err)
			return nil
		}
		hasher := sha1.New()
		fileBytes := make([]byte, 1024*1024)
		contentType := ""
		_, err = file.Read(fileBytes)
		// If we got back and error and it isn't the end of file then
		// skip it.  This does "something" with 0 length files.  It is
		// likely we should really be categorizing those based on file
		// extension.
		if err != nil && err != io.EOF {
			fmt.Fprintf(os.Stderr, "Error reading %s: %s\n", path, err)
			return nil
		}
		if strings.HasSuffix(relPath, ".svg") {
			// If we start to need a set of overrides for DetectContentType
			// then we need to find a different way to do this.
			contentType = "image/svg+xml"
		} else {
			contentType = http.DetectContentType(fileBytes)
		}

		// Resource name is a hash of the path, so it should stay consistent
		// for a given file path as long as the relative path to the target
		// directory is always the same across runs.
		hasher.Write([]byte(relPath))
		resourceName := fmt.Sprintf("%x", hasher.Sum(nil))

		resourcesMap[resourceName] = map[string]interface{}{
			"bucket":       bucketName,
			"key":          relPath,
			"source":       path,
			"etag":         fmt.Sprintf("${md5(file(%q))}", path),
			"content_type": contentType,
		}

		return nil
	})

	encoder := json.NewEncoder(os.Stdout)
	encoder.Encode(result)
}
コード例 #7
0
ファイル: ipscan.go プロジェクト: traveller42/ipscan
func main() {
	// Uncomment the following lines if you need to time the options parsing
	//log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
	//log.Println(": Program started")

	// Configure Command Line Options
	var useUDP, quiet, debug bool
	var maxRTT time.Duration
	var numPing int
	getopt.BoolVarLong(&useUDP, "udp", 'u', "use UDP instead of ICMP")
	getopt.BoolVarLong(&quiet, "quiet", 'q', "only display host data")
	getopt.BoolVarLong(&debug, "debug", 'v', "print additional messages")
	maxRTT = defaultMaxRTT
	getopt.DurationVarLong(&maxRTT, "rtt", 't', "max RTT for each ping")
	numPing = defaultPingCount
	getopt.IntVarLong(&numPing, "count", 'n', "max number of pings per target")
	getopt.SetParameters("startIP endIP")
	getopt.Parse()

	// Verify arguments
	if getopt.NArgs() != 2 {
		log.Println("Incorrect number of arguments!")
		getopt.PrintUsage(os.Stderr)
		os.Exit(1)
	}
	startIPString := getopt.Arg(0)
	endIPString := getopt.Arg(1)

	// Test for incompatible options
	if quiet && debug {
		log.Println("`quiet` and `debug` are incompatible")
		getopt.PrintUsage(os.Stderr)
		os.Exit(1)
	}

	if debug {
		log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
		log.Println(": Command Line Parsing complete")
	}

	// Convert to IP object
	startIP := net.ParseIP(startIPString)
	if startIP == nil {
		log.Fatal("Start IP,", startIPString, ", is not a valid IP address")
	}
	if debug {
		log.Println(": Start IP\t", startIPString)
	}
	endIP := net.ParseIP(endIPString)
	if endIP == nil {
		log.Fatal("End IP,", endIPString, ", is not a valid IP address")
	}
	if debug {
		log.Println(": End IP  \t", endIPString)
	}

	netProto := "ip4:icmp"
	if strings.Index(startIPString, ":") != -1 {
		netProto = "ip6:ipv6-icmp"
	}

	p := fastping.NewPinger()
	p.MaxRTT = maxRTT
	p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
		var device resultData
		device.PingResult = addr.String() + "\t" + roundDuration(baseRTT+rtt, time.Millisecond).String()
		ips = append(ips, device)
		p.RemoveIPAddr(addr)
	}

	currentIP := make(net.IP, len(startIP))
	for copy(currentIP, startIP); bytes.Compare(currentIP, endIP) <= 0; inc(currentIP) {
		ra, err := net.ResolveIPAddr(netProto, currentIP.String())
		if err != nil {
			log.Fatal(err)
		}
		p.AddIPAddr(ra)
	}

	if useUDP {
		p.Network("udp")
	}

	if debug {
		log.Println(": Start Scan")
	}

	for index := 0; index < numPing; index++ {
		baseRTT = time.Duration(index) * maxRTT
		err := p.Run()
		if err != nil {
			log.Fatal("Pinger returns error: ", err)
		}
	}

	if debug {
		log.Println(": Scan complete")
	}

	if !quiet {
		fmt.Println()
		fmt.Printf("%d devices found\n", len(ips))
		fmt.Println()
	}

	if debug {
		log.Println(": Start Host Lookup")
	}

	// Query DNS for the name of each device found by the ping scan
	var ipAndTime []string
	var hostname string
	var wg sync.WaitGroup
	for index, ip := range ips {
		ipAndTime = strings.SplitN(ip.PingResult, "\t", 2)
		wg.Add(1)
		go func(ipString string, localIndex int) {
			hosts, err := net.LookupAddr(ipString)
			if err != nil {
				hostname = "Error: " + err.Error()
			} else {
				hostname = strings.Join(hosts, ", ")
			}
			ips[localIndex].HostResult = hostname
			wg.Done()
		}(ipAndTime[0], index)
	}
	wg.Wait()

	if debug {
		log.Println(": DNS complete")
	}

	sort.Sort(byIP(ips))

	if debug {
		log.Println(": Sort complete")
	}

	for _, ip := range ips {
		fmt.Printf("%-25s\t--> %s\n", ip.PingResult, ip.HostResult)
	}

	if !quiet {
		fmt.Println()
	}

	if debug {
		log.Println(": Program complete")
	}
}
コード例 #8
0
ファイル: main.go プロジェクト: tahoemph/terraform-s3-dir
func main() {
	getopt.SetParameters("<root dir> <bucket name>")
	getopt.Parse()
	if *help {
		getopt.PrintUsage(os.Stdout)
		return
	}

	args := getopt.Args()
	if len(args) != 2 {
		getopt.PrintUsage(os.Stderr)
		os.Exit(1)
	}

	rootDir := args[0]
	bucketName := args[1]

	resourcesMap := map[string]interface{}{}
	result := map[string]interface{}{
		"resource": map[string]interface{}{
			"aws_s3_bucket_object": resourcesMap,
		},
	}

	filepath.Walk(rootDir, func(path string, info os.FileInfo, err error) error {
		if err != nil {
			fmt.Fprintf(os.Stderr, "Error reading %s: %s\n", path, err)
			// Skip stuff we can't read.
			return nil
		}

		relPath, err := filepath.Rel(rootDir, path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed make %s relative: %s\n", path, err)
			return nil
		}

		path, err = filepath.EvalSymlinks(path)
		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to resolve symlink %s: %s\n", path, err)
			return nil
		}

		if info.IsDir() {
			// Don't need to create directories since they are implied
			// by the files within.
			return nil
		}

		for _, pattern := range *exclude {
			var toMatch []string
			if strings.ContainsRune(pattern, filepath.Separator) {
				toMatch = append(toMatch, relPath)
			} else {
				// If the pattern does not include a path separator
				// then we apply it to all segments of the path
				// individually.
				toMatch = strings.Split(relPath, string(filepath.Separator))
			}

			for _, matchPath := range toMatch {
				matched, _ := filepath.Match(pattern, matchPath)
				if matched {
					return nil
				}
			}
		}

		resourceNameBytes := sha1.Sum([]byte(relPath))
		resourceName := fmt.Sprintf("%x", resourceNameBytes)

		resourcesMap[resourceName] = map[string]interface{}{
			"bucket": bucketName,
			"key":    relPath,
			"source": path,
		}

		return nil
	})

	encoder := json.NewEncoder(os.Stdout)
	encoder.Encode(result)
}
コード例 #9
0
ファイル: gssh.go プロジェクト: phalaaxx/gssh
// main program
func main() {
	// local variables
	var err error

	// parse commandline argiments
	getopt.Parse()

	// show help screen and exit in case of -h or --help option
	if *fHelp {
		getopt.Usage()
		os.Exit(1)
	}

	// look for mandatory positional arguments
	if getopt.NArgs() < 1 {
		log.Fatal("Nothing to do. Use -h for help.")
	}

	// by default, read server list from stdin
	ServerListFile := os.Stdin

	// read server names from file if a file name is supplied
	if *fFile != "" {
		ServerListFile, err = os.Open(*fFile)
		if err != nil {
			log.Fatal(fmt.Sprintf("ServerListFile: Error: %v", err))
		}
		defer ServerListFile.Close()
	}
	AddrPadding, ServerList := LoadServerList(ServerListFile)

	// command to run on servers
	fCommand = getopt.Arg(0)

	// make new group
	group := &SshGroup{
		Active:   0,
		Total:    len(ServerList),
		Complete: 0,
	}

	// no point to display more processes than
	if *fProcs > group.Total {
		*fProcs = group.Total
	}

	// print heading text
	fmt.Fprintln(os.Stderr, "gssh - group ssh, ver. 0.6")
	fmt.Fprintln(os.Stderr, "(c)2014 Bozhin Zafirov <*****@*****.**>")
	fmt.Fprintln(os.Stderr)
	fmt.Fprintf(os.Stderr, "  [*] read (%d) hosts from the list\n", group.Total)
	fmt.Fprintf(os.Stderr, "  [*] executing '%s' as user '%s'\n", fCommand, *fUser)
	fmt.Fprintf(os.Stderr, "  [*] spawning %d parallel ssh sessions\n\n", *fProcs)

	// spawn ssh processes
	for i, Server := range ServerList {
		ssh := &SshServer{
			Username: *fUser,
			Address:  Server,
		}
		group.Servers = append(group.Servers, ssh)
		// run command
		group.mu.Lock()
		group.Active++
		group.mu.Unlock()
		go group.Command(ssh, AddrPadding, fCommand)
		// show progless after new process spawn
		group.UpdateProgress()
		if i < group.Total {
			// time delay and max procs wait between spawn
			time.Sleep(time.Duration(*fDelay) * time.Millisecond)
			group.Wait(*fProcs)
		}
	}
	// wait for ssh processes to exit
	group.Wait(0)
	group.mu.Lock()
	group.ClearProgress()
	group.mu.Unlock()

	// calculate stats
	var StdoutServersCount int
	var StderrServersCount int
	var AllServersCount int
	var StdoutLinesCount int
	var StderrLinesCount int
	var AllLinesCount int
	for _, ssh := range group.Servers {
		if ssh.StdoutLineCount > 0 {
			StdoutLinesCount += ssh.StdoutLineCount
			StdoutServersCount++
		}
		if ssh.StderrLineCount > 0 {
			StderrLinesCount += ssh.StderrLineCount
			StderrServersCount++
		}
		if ssh.StdoutLineCount > 0 || ssh.StderrLineCount > 0 {
			AllLinesCount += ssh.StdoutLineCount + ssh.StderrLineCount
			AllServersCount++
		}
	}

	fmt.Fprintln(os.Stderr)
	fmt.Fprintf(os.Stderr, "  Done. Processed: %d / Output: %d (%d) / \033[01;32m->\033[0m %d (%d) / \033[01;31m=>\033[0m %d (%d)\n",
		group.Total,
		AllServersCount,
		AllLinesCount,
		StdoutServersCount,
		StdoutLinesCount,
		StderrServersCount,
		StderrLinesCount,
	)
}
コード例 #10
0
ファイル: yang.go プロジェクト: krousey/goyang
func main() {
	format := "tree"
	getopt.CommandLine.ListVarLong(&yang.Path, "path", 0, "comma separated list of directories to add to PATH")
	getopt.CommandLine.StringVarLong(&format, "format", 0, "format to display: tree, proto, types")

	getopt.Parse()
	files := getopt.Args()

	if len(files) > 0 && !strings.HasSuffix(files[0], ".yang") {
		e, errs := yang.GetModule(files[0], files[1:]...)
		exitIfError(errs)
		Write(os.Stdout, e)
		return
	}

	// Okay, either there are no arguments and we read stdin, or there
	// is one or more file names listed.  Read them in and display them.

	ms := yang.NewModules()

	if len(files) == 0 {
		data, err := ioutil.ReadAll(os.Stdin)
		if err == nil {
			err = ms.Parse(string(data), "<STDIN>")
		}
		if err != nil {
			fmt.Fprintln(os.Stderr, err)
			os.Exit(1)
		}
	}

	for _, name := range files {
		if err := ms.Read(name); err != nil {
			fmt.Fprintln(os.Stderr, err)
			continue
		}
	}

	// Keep track of the top level modules we read in.
	// Those are the only modules we want to print below.
	mods := map[string]*yang.Module{}
	var names []string

	for _, m := range ms.Modules {
		if mods[m.Name] == nil {
			mods[m.Name] = m
			names = append(names, m.Name)
		}
	}
	sort.Strings(names)

	// Print any errors found in the tree.  This will return false if
	// there were no errors.
	exitIfError(ms.Process())

	switch format {
	case "tree":
		for _, n := range names {
			Write(os.Stdout, yang.ToEntry(mods[n]))
		}
	case "proto":
		for _, n := range names {
			for _, e := range flatten(yang.ToEntry(mods[n])) {
				FormatNode(os.Stdout, e)
			}
		}
	case "types":
		types := Types{}
		for _, n := range names {
			types.AddEntry(yang.ToEntry(mods[n]))
		}

		for t := range types {
			YTPrint(os.Stdout, t)
		}
	default:
		fmt.Fprintf(os.Stderr, "unknown format: %s\n", format)
		os.Exit(1)
	}
}