// main defines the cfssl usage and registers all defined commands and flags.
430494
func main() {
	// Add command names to cfssl usage
	flag.Usage = nil // this is set to nil for testabilty
	// Register commands.
	cmds := map[string]*cli.Command{
		"bundle":         bundle.Command,
		"certinfo":       certinfo.Command,
		"crl":            crl.Command,
		"sign":           sign.Command,
		"serve":          serve.Command,
		"version":        version.Command,
		"genkey":         genkey.Command,
		"gencert":        gencert.Command,
		"gencsr":         gencsr.Command,
		"gencrl":         gencrl.Command,
		"ocspdump":       ocspdump.Command,
		"ocsprefresh":    ocsprefresh.Command,
		"ocspsign":       ocspsign.Command,
		"ocspserve":      ocspserve.Command,
		"selfsign":       selfsign.Command,
		"scan":           scan.Command,
		"info":           info.Command,
		"print-defaults": printdefaults.Command,
		"revoke":         revoke.Command,
	}

	// If the CLI returns an error, exit with an appropriate status
	// code.
	err := cli.Start(cmds)
	if err != nil {
		os.Exit(1)
	}
}
978088
func main() {
	// Imports the hello component declared above in order to make it loadable
	// in a page or usable in other components.
	//
	// Imported component can be used as URL or html tags by referencing them by
	// their lowercased names.
	// E.g:
	//  Hello   => hello
	//  foo.Bar => foo.bar
	app.Import(&Hello{})

	// Defines the component to load when an URL without path is loaded.
	app.DefaultPath = "/hello"

	// Runs the app in the browser.
	if err := app.Run(); err != nil {
		log.Print(err)
	}
}
923497
func main() {
	request := []string{"Hello world"}
	reply := []string{}
	var err error

	endpoints := len(os.Args) - 1
	if endpoints == 0 {
		fmt.Printf("I: syntax: %s <endpoint> ...\n", os.Args[0])
	} else if endpoints == 1 {
		//  For one endpoint, we retry N times
		for retries := 0; retries < MAX_RETRIES; retries++ {
			endpoint := os.Args[1]
			reply, err = try_request(endpoint, request)
			if err == nil {
				break //  Successful
			}
			fmt.Printf("W: no response from %s, retrying...\n", endpoint)
		}
	} else {
		//  For multiple endpoints, try each at most once
		for endpoint_nbr := 0; endpoint_nbr < endpoints; endpoint_nbr++ {
			endpoint := os.Args[endpoint_nbr+1]
			reply, err = try_request(endpoint, request)
			if err == nil {
				break //  Successful
			}
			fmt.Println("W: no response from", endpoint)
		}
	}
	if len(reply) > 0 {
		fmt.Printf("Service is running OK: %q\n", reply)
	}
}
384765
func main() {
	app := cli.NewApp()
	app.Usage = "runs methods against the Slack API and returns the result"
	app.Author = "Bobby Tables <me@bobbytables.io>"
	app.Name = "slacker"
	app.Commands = []cli.Command{slackMethod()}

	app.Run(os.Args)
}
765735
func main() {
	var (
		settings         []Option
		settingsTemplate = createTemplate("templates/query_params.go.tmpl")
		filepath         = "../../search/query_params.go"
	)

	for _, opt := range options {
		if isSearch(opt.Kind) {
			settings = append(settings, opt)
		}
	}

	generateFile(settingsTemplate, settings, filepath)
}
273082
func Main(args []string) {
	ctx, err := cmd.DefaultContext()
	if err != nil {
		cmd.WriteError(os.Stderr, err)
		os.Exit(2)
	}
	if err := juju.InitJujuXDGDataHome(); err != nil {
		cmd.WriteError(ctx.Stderr, err)
		os.Exit(2)
	}
	os.Exit(cmd.Main(NewSuperCommand(), ctx, args[1:]))
}
76497
func main() {
	// os.Setenv("IS_ENABLED", "asdf")
	c := &Config{}
	if err := env.Process(c); err != nil {
		fmt.Println("error:", err)
		return
		// panic(err)
	}
	fmt.Printf("name: %s, port: %d, adapter: %s, enabled: %v\n", c.Name, c.Port, c.Adapter, c.Enabled)
}
519390
func main() {
	if len(os.Args) < 2 {
		processes()
		return
	}

	cmd := os.Args[1]

	// See if it is a PID.
	pid, err := strconv.Atoi(cmd)
	if err == nil {
		processInfo(pid)
		return
	}

	if cmd == "help" {
		usage("")
	}

	if cmd == "tree" {
		displayProcessTree()
		return
	}

	fn, ok := cmds[cmd]
	if !ok {
		usage("unknown subcommand")
	}
	if len(os.Args) < 3 {
		usage("Missing PID or address.")
		os.Exit(1)
	}
	addr, err := targetToAddr(os.Args[2])
	if err != nil {
		fmt.Fprintf(os.Stderr, "Couldn't resolve addr or pid %v to TCPAddress: %v\n", os.Args[2], err)
		os.Exit(1)
	}
	var params []string
	if len(os.Args) > 3 {
		params = append(params, os.Args[3:]...)
	}
	if err := fn(*addr, params); err != nil {
		fmt.Fprintf(os.Stderr, "%v\n", err)
		os.Exit(1)
	}
}
117515
func main() {
	var debug bool
	var redisConfigPath string

	// init example flags
	flag.BoolVar(&debug, "debug", false, "Enable debugging")
	flag.StringVar(&redisConfigPath, "redis-config", "", "Redis configuration file path")
	flag.Parse()

	log := logrus.DefaultLogger()
	if debug {
		log.SetLevel(logging.DebugLevel)
	}
	// load redis config file
	redisConfig, err := redis.LoadConfig(redisConfigPath)
	if err != nil {
		log.Errorf("Failed to load Redis config file %s: %v", redisConfigPath, err)
		return
	}

	airport := &Airport{
		log:             log,
		airlines:        []string{"AA", "DL", "SW", "UA"},
		flightRadar:     make(map[string]struct{}),
		arrivalPrefix:   "/redis/airport/arrival",
		departurePrefix: "/redis/airport/departure",
		hangarPrefix:    "/redis/airport/hangar",
		motions:         []string{" ->", "<- "},
		respChan:        make(chan keyval.BytesWatchResp, 10),
		closeChan:       make(chan string),
	}
	doneChan := make(chan struct{})
	if err := airport.init(redisConfig, doneChan); err != nil {
		airport.log.Errorf("airport example error: %v", err)
	} else {
		airport.start()
	}
}
926432
func Main() {
	logR, logW, err := newSocketPair("log")
	if err != nil {
		os.Exit(70)
	}
	go debugStackPrinter(logW)

	config := &Config{}
	data, err := ioutil.ReadFile("/.containerconfig")
	if err != nil {
		os.Exit(70)
	}
	if err := json.Unmarshal(data, config); err != nil {
		os.Exit(70)
	}

	logger = log15.New("component", "containerinit")
	logger.SetHandler(log15.LvlFilterHandler(config.LogLevel, log15.StreamHandler(logW, log15.LogfmtFormat())))

	// Propagate the plugin-specific container env variable
	config.Env["container"] = os.Getenv("container")

	if err := containerInitApp(config, logR); err != nil {
		os.Exit(70)
	}
}
782809
func main() {
	// Create a new cli program.
	p := cli.NewProgram()
	p.Name = "reg"
	p.Description = "Docker registry v2 client"
	// Set the GitCommit and Version.
	p.GitCommit = version.GITCOMMIT
	p.Version = version.VERSION

	// Build the list of available commands.
	p.Commands = []cli.Command{
		&digestCommand{},
		&layerCommand{},
		&listCommand{},
		&manifestCommand{},
		&removeCommand{},
		&serverCommand{},
		&tagsCommand{},
		&vulnsCommand{},
	}

	// Setup the global flags.
	p.FlagSet = flag.NewFlagSet("global", flag.ExitOnError)
	p.FlagSet.BoolVar(&insecure, "insecure", false, "do not verify tls certificates")
	p.FlagSet.BoolVar(&insecure, "k", false, "do not verify tls certificates")

	p.FlagSet.BoolVar(&forceNonSSL, "force-non-ssl", false, "force allow use of non-ssl")
	p.FlagSet.BoolVar(&forceNonSSL, "f", false, "force allow use of non-ssl")

	p.FlagSet.BoolVar(&skipPing, "skip-ping", false, "skip pinging the registry while establishing connection")

	p.FlagSet.DurationVar(&timeout, "timeout", time.Minute, "timeout for HTTP requests")

	p.FlagSet.StringVar(&authURL, "auth-url", "", "alternate URL for registry authentication (ex. auth.docker.io)")

	p.FlagSet.StringVar(&username, "username", "", "username for the registry")
	p.FlagSet.StringVar(&username, "u", "", "username for the registry")

	p.FlagSet.StringVar(&password, "password", "", "password for the registry")
	p.FlagSet.StringVar(&password, "p", "", "password for the registry")

	p.FlagSet.BoolVar(&debug, "d", false, "enable debug logging")

	// Set the before function.
	p.Before = func(ctx context.Context) error {
		// On ^C, or SIGTERM handle exit.
		signals := make(chan os.Signal)
		signal.Notify(signals, os.Interrupt)
		signal.Notify(signals, syscall.SIGTERM)
		_, cancel := context.WithCancel(ctx)
		go func() {
			for sig := range signals {
				cancel()
				logrus.Infof("Received %s, exiting.", sig.String())
				os.Exit(0)
			}
		}()

		// Set the log level.
		if debug {
			logrus.SetLevel(logrus.DebugLevel)
		}

		return nil
	}

	// Run our program.
	p.Run()
}
1247588
func main() {
	CheckArgs("<path>")
	path := os.Args[1]

	// We instanciate a new repository targeting the given path (the .git folder)
	r, err := git.PlainOpen(path)
	CheckIfError(err)

	// Length of the HEAD history
	Info("git rev-list HEAD --count")

	// ... retrieving the HEAD reference
	ref, err := r.Head()
	CheckIfError(err)

	// ... retrieves the commit history
	cIter, err := r.Log(&git.LogOptions{From: ref.Hash()})
	CheckIfError(err)

	// ... just iterates over the commits
	var cCount int
	err = cIter.ForEach(func(c *object.Commit) error {
		cCount++

		return nil
	})
	CheckIfError(err)

	fmt.Println(cCount)
}
868977
func main() {
	//  Start child threads
	go publisher_thread()
	go subscriber_thread()
	go listener_thread()

	time.Sleep(100 * time.Millisecond)

	subscriber, _ := zmq.NewSocket(zmq.XSUB)
	subscriber.Connect("tcp://localhost:6000")
	publisher, _ := zmq.NewSocket(zmq.XPUB)
	publisher.Bind("tcp://*:6001")
	listener, _ := zmq.NewSocket(zmq.PAIR)
	listener.Connect("inproc://pipe")
	zmq.Proxy(subscriber, publisher, listener)

	fmt.Println("interrupted")
}
542154
func (t *Tool) Main(args []string, f Generator) {
	c := gologger.StdConfig.Use(context.Background())
	t.ParseArgs(args)

	if err := t.Run(c, f); err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}
	os.Exit(0)
}
550708
func main() {
	g := generator.New()

	data, err := ioutil.ReadAll(os.Stdin)
	if err != nil {
		failWithError(err, "reading input")
	}

	if err := proto.Unmarshal(data, g.Request); err != nil {
		failWithError(err, "parsing input proto")
	}

	if len(g.Request.FileToGenerate) == 0 {
		fail("no files to generate")
	}

	g.CommandLineParameters(g.Request.GetParameter())

	if val, ok := g.Param["logtostderr"]; ok && val == "true" {
		logtostderr = true
	}

	tree := buildTree(g.Request.GetProtoFile())

	packageLocations := make(map[string]string)
	for _, file := range g.Request.GetProtoFile() {
		loc := file.GetName()[:strings.LastIndex(file.GetName(), "/")]
		packageLocations[file.GetPackage()] = loc
	}

	selectedServices := make(map[string]string)
	for k, v := range g.Param {
		switch {
		case k == "logtostderr":
			if v == "true" {
				logtostderr = true
			}
		case strings.HasPrefix(k, "."):
			selectedServices[k] = v
		}
	}

	for serviceKey := range selectedServices {
		service, ok := tree.services[serviceKey]
		if !ok {
			fail("Service", serviceKey, "unknown")
		}

		usedMessages := make(map[string]*message)
		usedEnums := make(map[string]*enum)

		content := new(bytes.Buffer)

		fmt.Fprintf(content, "# %s API Reference\n\n", service.GetName())
		if service.comment != "" {
			fmt.Fprintf(content, "%s\n\n", service.comment)
		}

		if len(service.methods) > 0 {
			fmt.Fprint(content, "## Methods\n\n")

			for _, method := range service.methods {
				fmt.Fprintf(content, "### `%s`\n\n", method.GetName())
				if method.comment != "" {
					fmt.Fprintf(content, "%s\n\n", method.comment)
				}
				if method.inputStream {
					fmt.Fprintf(content, "- Client stream of [`%s`](#%s)\n", method.input.GetName(), heading(method.input.key))
				} else {
					fmt.Fprintf(content, "- Request: [`%s`](#%s)\n", method.input.GetName(), heading(method.input.key))
				}
				useMessage(tree, method.input, usedMessages, usedEnums)
				if method.outputStream {
					fmt.Fprintf(content, "- Server stream of [`%s`](#%s)\n", method.output.GetName(), heading(method.input.key))
				} else {
					fmt.Fprintf(content, "- Response: [`%s`](#%s)\n", method.output.GetName(), heading(method.input.key))
				}
				useMessage(tree, method.output, usedMessages, usedEnums)

				fmt.Fprintln(content)

				if len(method.endpoints) != 0 {
					if len(method.endpoints) == 1 {
						fmt.Fprint(content, "#### HTTP Endpoint\n\n")
					} else {
						fmt.Fprint(content, "#### HTTP Endpoints\n\n")
					}
					for _, endpoint := range method.endpoints {
						fmt.Fprintf(content, "- `%s` `%s`", endpoint.method, endpoint.url)
						var params []string
						for _, match := range regexp.MustCompile(`\{([a-z_]+)\}`).FindAllStringSubmatch(endpoint.url, -1) {
							if match != nil && len(match) == 2 && match[1] != "" {
								params = append(params, fmt.Sprintf("`%s`", match[1]))
							}
						}
						if len(params) > 0 {
							fmt.Fprintf(content, "(%s can be left out of the request body)", strings.Join(params, ", "))
						}
						fmt.Fprintln(content)
					}
					fmt.Fprintln(content)

					fmt.Fprint(content, "#### JSON Request Format\n\n")
					fmt.Fprintf(content, "```json\n%s\n```\n\n", method.input.JSONExample(tree))

					fmt.Fprint(content, "#### JSON Response Format\n\n")
					fmt.Fprintf(content, "```json\n%s\n```\n\n", method.output.JSONExample(tree))
				}
			}
		}

		if len(usedMessages) > 0 {
			fmt.Fprint(content, "## Messages\n\n")

			var messageKeys []string
			for key := range usedMessages {
				messageKeys = append(messageKeys, key)
			}
			sort.Strings(messageKeys)

			for _, messageKey := range messageKeys {
				message := usedMessages[messageKey]
				fmt.Fprintf(content, "### `%s`\n\n", message.key)
				if strings.HasPrefix(messageKey, ".google") {
					fmt.Fprintf(content, "%s\n\n", strings.SplitAfter(message.comment, ".")[0])
				} else if message.comment != "" {
					fmt.Fprintf(content, "%s\n\n", message.comment)
				}
				if len(message.fields) > 0 {
					fmt.Fprintln(content, "| Field Name | Type | Description |")
					fmt.Fprintln(content, "| ---------- | ---- | ----------- |")
					for idx, field := range message.fields {
						if field.isOneOf {
							if idx == 0 || !message.fields[idx-1].isOneOf || message.fields[idx-1].GetOneofIndex() != field.GetOneofIndex() {
								oneof := message.GetOneof(field.GetOneofIndex())
								if len(oneof.fields) > 1 {
									fmt.Fprintf(content, "| **%s** | **oneof %d** | one of the following %d |\n", oneof.GetName(), len(oneof.fields), len(oneof.fields))
								}
							}
						} else {
							if idx > 0 && message.fields[idx-1].isOneOf {
								oneof := message.GetOneof(message.fields[idx-1].GetOneofIndex())
								if len(oneof.fields) > 1 {
									fmt.Fprintf(content, "| **%s** | **end oneof %d** |  |\n", oneof.GetName(), len(oneof.fields))
								}
							}
						}

						var fieldType string
						if field.repeated {
							fieldType += "_repeated_ "
						}
						typ := strings.ToLower(strings.TrimPrefix(field.GetType().String(), "TYPE_"))
						switch typ {
						case "message":
							friendlyType := field.GetTypeName()[strings.LastIndex(field.GetTypeName(), ".")+1:]
							fieldType += fmt.Sprintf("[`%s`](#%s)", friendlyType, heading(field.GetTypeName()))
						case "enum":
							// TODO(htdvisser): test this
							if enum, ok := tree.enums[field.GetTypeName()]; ok {
								usedEnums[field.GetTypeName()] = enum
							}
							friendlyType := field.GetTypeName()[strings.LastIndex(field.GetTypeName(), ".")+1:]
							fieldType += fmt.Sprintf("[`%s`](#%s)", friendlyType, heading(field.GetTypeName()))
						default:
							fieldType += fmt.Sprintf("`%s`", typ)
						}
						fmt.Fprintf(content, "| `%s` | %s | %s |\n", field.GetName(), fieldType, strings.Replace(field.comment, "\n", " ", -1))
					}
					fmt.Fprintln(content)
				}
			}
		}

		if len(usedEnums) > 0 {
			fmt.Fprint(content, "## Used Enums\n\n")

			var enumKeys []string
			for key := range usedEnums {
				enumKeys = append(enumKeys, key)
			}
			sort.Strings(enumKeys)

			for _, enumKey := range enumKeys {
				enum := usedEnums[enumKey]

				fmt.Fprintf(content, "### `%s`\n\n", enum.key)
				if enum.comment != "" {
					fmt.Fprintf(content, "%s\n\n", enum.comment)
				}

				if len(enum.values) > 0 {
					fmt.Fprintln(content, "| Value | Description |")
					fmt.Fprintln(content, "| ----- | ----------- |")
					for _, value := range enum.values {
						fmt.Fprintf(content, "| `%s` | %s |\n", value.GetName(), strings.Replace(value.comment, "\n", " ", -1))
					}
					fmt.Fprintln(content)
				}
			}
		}

		packageService := strings.TrimPrefix(service.key, ".")
		packageName := packageService[:strings.Index(packageService, ".")]
		location, ok := packageLocations[packageName]
		if !ok {
			fail("Could not find location of package", packageName)
		}
		fileName := path.Join(location, service.GetName()+".md")
		contentString := content.String()
		g.Response.File = append(g.Response.File, &plugin.CodeGeneratorResponse_File{
			Name:    &fileName,
			Content: &contentString,
		})
	}

	// Send back the results.
	data, err = proto.Marshal(g.Response)
	if err != nil {
		failWithError(err, "failed to marshal output proto")
	}
	_, err = os.Stdout.Write(data)
	if err != nil {
		failWithError(err, "failed to write output proto")
	}
}
508752
func main() {
	buildInfo := &BuildInfo{}
	OptionsParser := flags.NewParser(&options, flags.PassAfterNonOption|flags.HelpFlag)
	OptionsParser.ShortDescription = "DOSA CLI - The command-line tool for your DOSA client"
	OptionsParser.LongDescription = `
dosa manages your schema both in production and development scopes`

	c, _ := OptionsParser.AddCommand("version", "display build info", "display build info", &BuildInfo{})

	c, _ = OptionsParser.AddCommand("scope", "commands to manage scope", "create, drop, or truncate development scopes", &ScopeOptions{})
	_, _ = c.AddCommand("create", "Create scope", "creates a new scope", newScopeCreate(provideAdminClient))
	_, _ = c.AddCommand("drop", "Drop scope", "drops a scope", newScopeDrop(provideAdminClient))
	_, _ = c.AddCommand("truncate", "Truncate scope", "truncates a scope", newScopeTruncate(provideAdminClient))

	_, _ = c.AddCommand("list", "List scopes", "lists scopes", newScopeList(provideMDClient))
	_, _ = c.AddCommand("show", "Show scope MD", "show scope metadata", newScopeShow(provideMDClient))

	c, _ = OptionsParser.AddCommand("schema", "commands to manage schemas", "check or update schemas", &SchemaOptions{})
	_, _ = c.AddCommand("check", "Check schema", "check the schema", newSchemaCheck(provideAdminClient))
	_, _ = c.AddCommand("upsert", "Upsert schema", "insert or update the schema", newSchemaUpsert(provideAdminClient))
	_, _ = c.AddCommand("dump", "Dump schema", "display the schema in a given format", &SchemaDump{})
	_, _ = c.AddCommand("status", "Check schema status", "Check application status of schema", newSchemaStatus(provideAdminClient))

	c, _ = OptionsParser.AddCommand("query", "commands to do query", "fetch one or multiple rows", &QueryOptions{})
	_, _ = c.AddCommand("read", "Read query", "read a row by primary keys", newQueryRead(provideShellQueryClient))
	_, _ = c.AddCommand("range", "Range query", "read rows with range of primary keys and indexes", newQueryRange(provideShellQueryClient))

	// TODO: implement admin subcommand
	// c, _ = OptionsParser.AddCommand("admin", "commands to administrate", "", &AdminOptions{})

	_, err := OptionsParser.Parse()

	if options.Version {
		_, _ = fmt.Fprintf(os.Stdout, "%s\n", buildInfo.String())
		options.Version = false // for tests, we leak state between runs
		exit(0)
	}

	if err != nil {
		_, _ = fmt.Fprintf(os.Stderr, "Error: %s\n", err)
		exit(1)
		return
	}

	exit(0)
}
1215181
func main() {
	rootCmd := cmds.NewCmdOsm()
	dir := runtime.GOPath() + "/src/github.com/appscode/osm/docs/reference"
	fmt.Printf("Generating cli markdown tree in: %v\n", dir)
	err := os.RemoveAll(dir)
	if err != nil {
		log.Fatalln(err)
	}
	err = os.MkdirAll(dir, 0755)
	if err != nil {
		log.Fatalln(err)
	}

	filePrepender := func(filename string) string {
		name := filepath.Base(filename)
		base := strings.TrimSuffix(name, path.Ext(name))
		data := struct {
			ID      string
			Name    string
			Version string
			RootCmd bool
		}{
			strings.Replace(base, "_", "-", -1),
			strings.Title(strings.Replace(base, "_", " ", -1)),
			version,
			!strings.ContainsRune(base, '_'),
		}
		var buf bytes.Buffer
		if err := tplFrontMatter.ExecuteTemplate(&buf, "cmd", data); err != nil {
			log.Fatalln(err)
		}
		return buf.String()
	}

	linkHandler := func(name string) string {
		return "/docs/reference/" + name
	}
	doc.GenMarkdownTreeCustom(rootCmd, dir, filePrepender, linkHandler)

	index := filepath.Join(dir, "_index.md")
	f, err := os.OpenFile(index, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644)
	if err != nil {
		log.Fatalln(err)
	}
	err = tplFrontMatter.ExecuteTemplate(f, "index", struct{ Version string }{version})
	if err != nil {
		log.Fatalln(err)
	}
	if err := f.Close(); err != nil {
		log.Fatalln(err)
	}
}