예제 #1
0
파일: org_users.go 프로젝트: nota-ja/cli
func (cmd *OrgUsers) Run(c *cli.Context) {
	org := cmd.orgReq.GetOrganization()
	all := c.Bool("a")

	cmd.ui.Say("Getting users in org %s as %s...",
		terminal.EntityNameColor(org.Name),
		terminal.EntityNameColor(cmd.config.Username()),
	)

	roles := orgRoles
	if all {
		roles = []string{models.ORG_USER}
	}

	for _, role := range roles {
		displayName := orgRoleToDisplayName[role]

		users, apiErr := cmd.userRepo.ListUsersInOrgForRole(org.Guid, role)

		cmd.ui.Say("")
		cmd.ui.Say("%s", terminal.HeaderColor(displayName))

		for _, user := range users {
			cmd.ui.Say("  %s", user.Username)
		}

		if apiErr != nil {
			cmd.ui.Failed("Failed fetching org-users for role %s.\n%s", apiErr.Error(), displayName)
			return
		}
	}
}
예제 #2
0
파일: main.go 프로젝트: sudix/chickenhead
// delete is a subcommand to delete a snippet.
func delete(c *cli.Context) {
	force := c.Bool("f")
	snippetName := c.Args().First()
	if len(snippetName) == 0 {
		log.Fatal("please enter snippet name")
	}

	s := NewSnippet(conf.SnippetDirectory, snippetName)

	if !s.Exists() {
		log.Fatal("This snippet doesn't exists.")
	}

	if !force {
		reader := bufio.NewReader(os.Stdin)
		fmt.Print("sure you want to delete %s [yn]?")
		ret, err := reader.ReadString('\n')
		if err != nil {
			log.Fatal(err)
		}

		if ret != "y\n" {
			return
		}
	}

	if err := s.Delete(); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%s has been deleted.\n", snippetName)
}
예제 #3
0
파일: tlsconf.go 프로젝트: rowhit/os
func generate(c *cli.Context) error {
	generateServer := c.Bool("server")
	outDir := c.String("dir")
	hostnames := c.StringSlice("hostname")

	return Generate(generateServer, outDir, hostnames)
}
예제 #4
0
func (cmd CreateBuildpack) createBuildpack(buildpackName string, c *cli.Context) (buildpack models.Buildpack, apiErr error) {
	position, err := strconv.Atoi(c.Args()[2])
	if err != nil {
		apiErr = errors.NewWithFmt("Invalid position. %s", err.Error())
		return
	}

	enabled := c.Bool("enable")
	disabled := c.Bool("disable")
	if enabled && disabled {
		apiErr = errors.New("Cannot specify both enabled and disabled.")
		return
	}

	var enableOption *bool = nil
	if enabled {
		enableOption = &enabled
	}
	if disabled {
		disabled = false
		enableOption = &disabled
	}

	buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil)

	return
}
예제 #5
0
파일: push.go 프로젝트: ramirito/cli
func (cmd *Push) getAppParamsFromManifest(c *cli.Context) []models.AppParams {
	if c.Bool("no-manifest") {
		return []models.AppParams{}
	}

	var path string
	if c.String("f") != "" {
		path = c.String("f")
	} else {
		var err error
		path, err = os.Getwd()
		if err != nil {
			cmd.ui.Failed(T("Could not determine the current working directory!"), err)
		}
	}

	m, err := cmd.manifestRepo.ReadManifest(path)

	if err != nil {
		if m.Path == "" && c.String("f") == "" {
			return []models.AppParams{}
		} else {
			cmd.ui.Failed(T("Error reading manifest file:\n{{.Err}}", map[string]interface{}{"Err": err.Error()}))
		}
	}

	apps, err := m.Applications()
	if err != nil {
		cmd.ui.Failed("Error reading manifest file:\n%s", err)
	}

	cmd.ui.Say(T("Using manifest file {{.Path}}\n",
		map[string]interface{}{"Path": terminal.EntityNameColor(m.Path)}))
	return apps
}
예제 #6
0
파일: factories.go 프로젝트: atmos/conveyor
func newBuilder(c *cli.Context) builder.Builder {
	db, err := docker.NewBuilderFromEnv()
	if err != nil {
		must(err)
	}
	db.DryRun = c.Bool("dry")
	db.Image = c.String("builder.image")

	g := builder.NewGitHubClient(c.String("github.token"))

	var backend builder.Builder = builder.UpdateGitHubCommitStatus(db, g, fmt.Sprintf(logsURLTemplate, c.String("url")))

	if uri := c.String("stats"); uri != "" {
		u := urlParse(uri)

		switch u.Scheme {
		case "dogstatsd":
			c, err := statsd.New(u.Host)
			must(err)

			backend = datadog.WithStats(
				backend,
				c,
			)
		default:
			must(fmt.Errorf("Unknown stats backend: %v", u.Scheme))
		}
	}

	b := worker.NewBuilder(backend)
	b.Reporter = newReporter(c)

	return b
}
예제 #7
0
파일: secret.go 프로젝트: donny-dont/drone
func secretParseCmd(name string, value string, c *cli.Context) (*model.Secret, error) {
	secret := &model.Secret{}
	secret.Name = name
	secret.Value = value
	secret.Images = c.StringSlice("image")
	secret.Events = c.StringSlice("event")
	secret.SkipVerify = c.Bool("skip-verify")
	secret.Conceal = c.Bool("conceal")

	if len(secret.Images) == 0 {
		return nil, fmt.Errorf("Please specify the --image parameter")
	}

	// TODO(bradrydzewski) below we use an @ sybmol to denote that the secret
	// value should be loaded from a file (inspired by curl). I'd prefer to use
	// a --input flag to explicitly specify a filepath instead.

	if strings.HasPrefix(secret.Value, "@") {
		path := secret.Value[1:]
		out, ferr := ioutil.ReadFile(path)
		if ferr != nil {
			return nil, ferr
		}
		secret.Value = string(out)
	}

	return secret, nil
}
예제 #8
0
func (cmd ListStack) Run(c *cli.Context) {
	stackName := c.Args()[0]

	stack, apiErr := cmd.stacksRepo.FindByName(stackName)

	if c.Bool("guid") {
		cmd.ui.Say(stack.Guid)
	} else {
		if apiErr != nil {
			cmd.ui.Failed(apiErr.Error())
			return
		}

		cmd.ui.Say(T("Getting stack '{{.Stack}}' in org {{.OrganizationName}} / space {{.SpaceName}} as {{.Username}}...",
			map[string]interface{}{"Stack": stackName,
				"OrganizationName": terminal.EntityNameColor(cmd.config.OrganizationFields().Name),
				"SpaceName":        terminal.EntityNameColor(cmd.config.SpaceFields().Name),
				"Username":         terminal.EntityNameColor(cmd.config.Username())}))

		cmd.ui.Ok()
		cmd.ui.Say("")

		table := terminal.NewTable(cmd.ui, []string{T("name"), T("description")})
		table.Add(stack.Name, stack.Description)
		table.Print()
	}
}
예제 #9
0
func run(c *cli.Context) {
	plugin := Plugin{
		Mount:   c.StringSlice("mount"),
		Path:    c.String("path"),
		Repo:    c.String("repo.name"),
		Default: c.String("repo.branch"),
		Branch:  c.String("commit.branch"),
	}

	sftp, err := sftp.New(
		c.String("server"),
		c.String("username"),
		c.String("password"),
		c.String("key"),
	)
	if err != nil {
		log.Fatal(err)
	}
	defer sftp.(io.Closer).Close()

	if c.Bool("rebuild") {
		now := time.Now()
		err = plugin.Rebuild(sftp)
		log.Printf("cache built in %v", time.Since(now))
	}
	if c.Bool("restore") {
		now := time.Now()
		err = plugin.Restore(sftp)
		log.Printf("cache restored in %v", time.Since(now))
	}

	if err != nil {
		log.Println(err) // this plugins does not fail on error
	}
}
예제 #10
0
func RunApp(c *cli.Context) {
	dbUrl := c.String("db-url")

	if dbUrl == "" {
		showErrorAndAbort("you need to provide 'db-url' or $DATABASE_URL needs to be set")
	}

	if c.Bool("debug") {
		logger.SetLevel(loggo.Debug)
	}

	if c.Bool("quiet") {
		logger.SetLevel(loggo.Warning)
	}

	fixturesPaths := GetFixturesDirectories(c.String("fixtures-path"), c.String("env"))
	logger.Debugf("searching for fixtures in: %v", fixturesPaths)

	fixtures, err := LoadDirectories(fixturesPaths)
	if err != nil {
		showErrorAndAbort(err.Error())
	}
	logger.Debugf("found the following fixtures: %+v", fixtures)

	logger.Infof("connecting to DB %s", dbUrl)

	populator, err := NewPopulator(dbUrl)
	if err != nil {
		showErrorAndAbort(err.Error())
	}

	if err := populator.PopulateData(fixtures); err != nil {
		showErrorAndAbort(err.Error())
	}
}
예제 #11
0
파일: images.go 프로젝트: kajali/fish
func images(c *cli.Context) {
	filter := "my_images"
	if c.Bool("global") {
		filter = "global"
	}

	images, err := docli.GetImages(filter)
	if err != nil {
		fatalf(err.Error())
	}

	switch filter {
	case "global":
		fmt.Println("Global Images:")
	default:
		fmt.Println("My Images:")
	}

	for _, i := range images {
		fmt.Printf("%s (slug: %s id: %d)\n",
			i.Name,
			i.Slug,
			i.ID)
	}
}
예제 #12
0
파일: commands.go 프로젝트: kentaro/ghq
func doGet(c *cli.Context) {
	argURL := c.Args().Get(0)
	doUpdate := c.Bool("update")

	if argURL == "" {
		cli.ShowCommandHelp(c, "get")
		os.Exit(1)
	}

	url, err := url.Parse(argURL)
	utils.DieIf(err)

	if !url.IsAbs() {
		url.Scheme = "https"
		url.Host = "github.com"
		if url.Path[0] != '/' {
			url.Path = "/" + url.Path
		}
	}

	remote, err := NewRemoteRepository(url)
	utils.DieIf(err)

	if remote.IsValid() == false {
		utils.Log("error", fmt.Sprintf("Not a valid repository: %s", url))
		os.Exit(1)
	}

	getRemoteRepository(remote, doUpdate)
}
예제 #13
0
func runApp(c *cli.Context) {
	debug := c.Bool("debug")

	if err := validateCLI(c); err != nil {
		log.Println("CLI Validation Error:", err)
		cli.ShowAppHelp(c)
		os.Exit(1)
	}

	if !debug {
		TurnOffLogging()
	}

	var sitemap *domain.Sitemap
	if useSavedResults(c) {
		sitemap = runSitemapLoader(c)
	} else {
		sitemap = runSitemapBuilder(c)
	}

	if sitemap == nil {
		fmt.Println("Could not build Sitemap")
		return
	}

	outputSitemapToConsole(c, sitemap)

	if shouldSaveResults(c) {
		outputSitemapToFile(c, sitemap)
	}
}
예제 #14
0
func runVerify(c *cli.Context) {
	config := common.NewConfig()
	err := config.LoadConfig(c.String("config"))
	if err != nil {
		log.Fatalln(err)
		return
	}

	// verify if runner exist
	runners := []*common.RunnerConfig{}
	for _, runner := range config.Runners {
		if common.VerifyRunner(runner.URL, runner.Token) {
			runners = append(runners, runner)
		}
	}

	if !c.Bool("delete") {
		return
	}

	// check if anything changed
	if len(config.Runners) == len(runners) {
		return
	}

	config.Runners = runners

	// save config file
	err = config.SaveConfig(c.String("config"))
	if err != nil {
		log.Fatalln("Failed to update", c.String("config"), err)
	}
	log.Println("Updated", c.String("config"))
}
예제 #15
0
파일: main.go 프로젝트: pombredanne/pulls
//Assign a pull request to the current user.
// If it's taken, show a message with the "--steal" optional flag.
//If the user doesn't have permissions, add a comment #volunteer
func takeCmd(c *cli.Context) {
	if !c.Args().Present() {
		gordon.Fatalf("usage: take ID")
	}
	number := c.Args()[0]
	pr, err := m.GetPullRequest(number)
	if err != nil {
		gordon.Fatalf("%s", err)
	}
	user, err := m.GetGithubUser()
	if err != nil {
		gordon.Fatalf("%s", err)
	}
	if pr.Assignee != nil && !c.Bool("steal") {
		gordon.Fatalf("Use --steal to steal the PR from %s", pr.Assignee.Login)
	}
	pr.Assignee = user
	patchedPR, err := m.PatchPullRequest(number, pr)
	if err != nil {
		gordon.Fatalf("%s", err)
	}
	if patchedPR.Assignee.Login != user.Login {
		m.AddComment(number, "#volunteer")
		fmt.Printf("No permission to assign. You '%s' was added as #volunteer.\n", user.Login)
	} else {
		m.AddComment(number, fmt.Sprintf("#assignee=%s", patchedPR.Assignee.Login))
		fmt.Printf("Assigned PR %s to %s\n", brush.Green(number), patchedPR.Assignee.Login)
	}
}
func (cmd DeleteServiceAuthTokenFields) Run(c *cli.Context) {
	tokenLabel := c.Args()[0]
	tokenProvider := c.Args()[1]

	if c.Bool("f") == false {
		if !cmd.ui.ConfirmDelete(T("service auth token"), fmt.Sprintf("%s %s", tokenLabel, tokenProvider)) {
			return
		}
	}

	cmd.ui.Say(T("Deleting service auth token as {{.CurrentUser}}",
		map[string]interface{}{
			"CurrentUser": terminal.EntityNameColor(cmd.config.Username()),
		}))
	token, apiErr := cmd.authTokenRepo.FindByLabelAndProvider(tokenLabel, tokenProvider)

	switch apiErr.(type) {
	case nil:
	case *errors.ModelNotFoundError:
		cmd.ui.Ok()
		cmd.ui.Warn(T("Service Auth Token {{.Label}} {{.Provider}} does not exist.", map[string]interface{}{"Label": tokenLabel, "Provider": tokenProvider}))
		return
	default:
		cmd.ui.Failed(apiErr.Error())
	}

	apiErr = cmd.authTokenRepo.Delete(token)
	if apiErr != nil {
		cmd.ui.Failed(apiErr.Error())
		return
	}

	cmd.ui.Ok()
}
예제 #17
0
파일: add.go 프로젝트: bazscsa/envman
func add(c *cli.Context) {
	log.Debugln("[ENVMAN] - Work path:", envman.CurrentEnvStoreFilePath)

	key := c.String(KeyKey)
	expand := !c.Bool(NoExpandKey)
	replace := !c.Bool(AppendKey)

	var value string
	if stdinValue != "" {
		value = stdinValue
	} else if c.IsSet(ValueKey) {
		value = c.String(ValueKey)
	} else if c.String(ValueFileKey) != "" {
		if v, err := loadValueFromFile(c.String(ValueFileKey)); err != nil {
			log.Fatal("[ENVMAN] - Failed to read file value: ", err)
		} else {
			value = v
		}
	}

	if err := addEnv(key, value, expand, replace); err != nil {
		log.Fatal("[ENVMAN] - Failed to add env:", err)
	}

	log.Debugln("[ENVMAN] - Env added")

	if err := logEnvs(); err != nil {
		log.Fatal("[ENVMAN] - Failed to print:", err)
	}
}
예제 #18
0
파일: lint.go 프로젝트: michelleN/helm
func lint(c *cli.Context) {
	home := home(c)

	all := c.Bool("all")

	if all {
		action.LintAll(home)
		return
	}

	minArgs(c, 1, "lint")

	a := c.Args()
	chartNameOrPath := a[0]

	fromHome := util.WorkspaceChartDirectory(home, chartNameOrPath)
	fromAbs := filepath.Clean(chartNameOrPath)

	_, err := os.Stat(fromAbs)

	if err == nil {
		action.Lint(fromAbs)
	} else {
		action.Lint(fromHome)
	}
}
예제 #19
0
파일: cli.go 프로젝트: fbernardo/envman
func before(c *cli.Context) error {
	initLogFormatter()
	initHelpAndVersionFlags()
	initAppHelpTemplate()

	// Log level
	if logLevel, err := log.ParseLevel(c.String(LogLevelKey)); err != nil {
		log.Fatal("[BITRISE_CLI] - Failed to parse log level:", err)
	} else {
		log.SetLevel(logLevel)
	}

	// Befor parsing cli, and running command
	// we need to decide wich path will be used by envman
	envman.CurrentEnvStoreFilePath = c.String(PathKey)
	if envman.CurrentEnvStoreFilePath == "" {
		if path, err := envStorePathInCurrentDir(); err != nil {
			log.Fatal("[ENVMAN] - Failed to set envman work path in current dir:", err)
		} else {
			envman.CurrentEnvStoreFilePath = path
		}
	}

	envman.ToolMode = c.Bool(ToolKey)
	if envman.ToolMode {
		log.Info("[ENVMAN] - Tool mode on")
	}

	if _, err := envman.GetConfigs(); err != nil {
		log.Fatal("[ENVMAN] - Failed to init configs:", err)
	}

	return nil
}
예제 #20
0
파일: curl.go 프로젝트: normalnorman/cli
func (cmd *Curl) Run(c *cli.Context) {
	path := c.Args()[0]
	method := c.String("X")
	headers := c.StringSlice("H")
	body := c.String("d")
	verbose := c.Bool("v")

	reqHeader := strings.Join(headers, "\n")

	if verbose {
		trace.EnableTrace()
	}

	respHeader, respBody, apiResponse := cmd.curlRepo.Request(method, path, reqHeader, body)
	if apiResponse.IsNotSuccessful() {
		cmd.ui.Failed("Error creating request:\n%s", apiResponse.Message)
		return
	}

	if verbose {
		return
	}

	if c.Bool("i") {
		cmd.ui.Say("%s", respHeader)
	}

	cmd.ui.Say("%s", respBody)
	return
}
예제 #21
0
파일: restore.go 프로젝트: imikushin/runc
func restoreContainer(context *cli.Context, spec *specs.Spec, config *configs.Config, imagePath string) (code int, err error) {
	var (
		rootuid = 0
		rootgid = 0
		id      = context.Args().First()
	)
	factory, err := loadFactory(context)
	if err != nil {
		return -1, err
	}
	container, err := factory.Load(id)
	if err != nil {
		container, err = factory.Create(id, config)
		if err != nil {
			return -1, err
		}
	}
	options := criuOptions(context)

	status, err := container.Status()
	if err != nil {
		logrus.Error(err)
	}
	if status == libcontainer.Running {
		fatalf("Container with id %s already running", id)
	}

	setManageCgroupsMode(context, options)

	// ensure that the container is always removed if we were the process
	// that created it.
	detach := context.Bool("detach")
	if !detach {
		defer destroy(container)
	}
	process := &libcontainer.Process{}
	tty, err := setupIO(process, rootuid, rootgid, "", false, detach)
	if err != nil {
		return -1, err
	}
	defer tty.Close()
	handler := newSignalHandler(tty, !context.Bool("no-subreaper"))
	if err := container.Restore(process, options); err != nil {
		return -1, err
	}
	if err := tty.ClosePostStart(); err != nil {
		return -1, err
	}
	if pidFile := context.String("pid-file"); pidFile != "" {
		if err := createPidFile(pidFile, process); err != nil {
			process.Signal(syscall.SIGKILL)
			process.Wait()
			return -1, err
		}
	}
	if detach {
		return 0, nil
	}
	return handler.forward(process)
}
예제 #22
0
func (factory *AppRunnerCommandFactory) updateAppRoutes(c *cli.Context) {
	appName := c.Args().First()
	userDefinedRoutes := c.Args().Get(1)
	noRoutesFlag := c.Bool("no-routes")

	if appName == "" || (userDefinedRoutes == "" && !noRoutesFlag) {
		factory.UI.SayIncorrectUsage("Please enter 'ltc update-routes APP_NAME NEW_ROUTES' or pass '--no-routes' flag.")
		factory.ExitHandler.Exit(exit_codes.InvalidSyntax)
		return
	}

	desiredRoutes := app_runner.RouteOverrides{}
	var err error
	if !noRoutesFlag {
		desiredRoutes, err = factory.ParseRouteOverrides(userDefinedRoutes)
		if err != nil {
			factory.UI.SayLine(err.Error())
			factory.ExitHandler.Exit(exit_codes.InvalidSyntax)
			return
		}
	}

	if err := factory.AppRunner.UpdateAppRoutes(appName, desiredRoutes); err != nil {
		factory.UI.SayLine(fmt.Sprintf("Error updating routes: %s", err))
		factory.ExitHandler.Exit(exit_codes.CommandFailed)
		return
	}

	factory.UI.SayLine(fmt.Sprintf("Updating %s routes. You can check this app's current routes by running 'ltc status %s'", appName, appName))
}
예제 #23
0
파일: push.go 프로젝트: ramirito/cli
func (cmd *Push) Run(c *cli.Context) {
	appSet := cmd.findAndValidateAppsToPush(c)
	_, apiErr := cmd.authRepo.RefreshAuthToken()
	if apiErr != nil {
		cmd.ui.Failed(fmt.Sprintf("Error refreshing auth token.\n%s", apiErr.Error()))
		return
	}

	routeActor := actors.NewRouteActor(cmd.ui, cmd.routeRepo)
	noHostname := c.Bool("no-hostname")

	for _, appParams := range appSet {
		cmd.fetchStackGuid(&appParams)
		app := cmd.createOrUpdateApp(appParams)

		cmd.updateRoutes(routeActor, app, appParams, noHostname)

		cmd.ui.Say(T("Uploading {{.AppName}}...",
			map[string]interface{}{"AppName": terminal.EntityNameColor(app.Name)}))

		apiErr := cmd.appBitsRepo.UploadApp(app.Guid, *appParams.Path, cmd.describeUploadOperation)
		if apiErr != nil {
			cmd.ui.Failed(fmt.Sprintf(T("Error uploading application.\n{{.ApiErr}}",
				map[string]interface{}{"ApiErr": apiErr.Error()})))
			return
		}
		cmd.ui.Ok()

		if appParams.ServicesToBind != nil {
			cmd.bindAppToServices(*appParams.ServicesToBind, app)
		}

		cmd.restart(app, appParams, c)
	}
}
예제 #24
0
func (cmd CreateBuildpack) createBuildpack(buildpackName string, c *cli.Context) (buildpack models.Buildpack, apiErr error) {
	position, err := strconv.Atoi(c.Args()[2])
	if err != nil {
		apiErr = errors.NewWithFmt(T("Invalid position. {{.ErrorDescription}}", map[string]interface{}{"ErrorDescription": err.Error()}))
		return
	}

	enabled := c.Bool("enable")
	disabled := c.Bool("disable")
	if enabled && disabled {
		apiErr = errors.New(T("Cannot specify both {{.Enabled}} and {{.Disabled}}.", map[string]interface{}{
			"Enabled":  "enabled",
			"Disabled": "disabled",
		}))
		return
	}

	var enableOption *bool = nil
	if enabled {
		enableOption = &enabled
	}
	if disabled {
		disabled = false
		enableOption = &disabled
	}

	buildpack, apiErr = cmd.buildpackRepo.Create(buildpackName, &position, enableOption, nil)

	return
}
예제 #25
0
func (cmd CreateBuildpack) createBuildpack(buildpackName string, c *cli.Context) (buildpack cf.Buildpack, apiResponse net.ApiResponse) {
	position, err := strconv.Atoi(c.Args()[2])
	if err != nil {
		apiResponse = net.NewApiResponseWithMessage("Invalid position. %s", err.Error())
		return
	}

	enabled := c.Bool("enable")
	disabled := c.Bool("disable")
	if enabled && disabled {
		apiResponse = net.NewApiResponseWithMessage("Cannot specify both enabled and disabled.")
		return
	}

	var enableOption *bool = nil
	if enabled {
		enableOption = &enabled
	}
	if disabled {
		disabled = false
		enableOption = &disabled
	}

	buildpack, apiResponse = cmd.buildpackRepo.Create(buildpackName, &position, enableOption)

	return
}
예제 #26
0
func InstallAction(c *cli.Context) {
	if c.Bool("debug") {
		log.SetOutputLevel(log.Ldebug)
	}
	if len(c.Args()) < 1 {
		log.Fatal("Need at lease one argument")
	}
	// log.Println(GOBIN)
	pkgName := c.Args().First()
	// TODO: use myname for now
	if len(strings.Split(pkgName, "/")) == 1 {
		pkgName = "gobuild-official/" + pkgName
	}

	prompt("Repository %v", pkgName)
	dest, err := downloadSource(pkgName)
	if err != nil {
		log.Fatal(err)
	}

	err = deployPackage(pkgName, dest, GOBIN)
	if err != nil {
		log.Fatal(err)
	}

	prompt("Program [%s] installed", pkgName)
}
예제 #27
0
파일: main.go 프로젝트: sudix/chickenhead
// add is a subcommand to create a new snippet.
func add(c *cli.Context) {
	snippetName := c.Args().First()
	if len(snippetName) == 0 {
		log.Fatal("please enter snippet name")
	}

	s := NewSnippet(conf.SnippetDirectory, snippetName)

	if s.Exists() {
		log.Fatal("This snippet already exists.")
	}

	stdinFlag := c.Bool("s")
	switch {
	case stdinFlag:
		// read contents from standard input
		buf, err := ioutil.ReadAll(os.Stdin)
		if err != nil {
			log.Fatal(err)
		}

		// write contents to snippet
		s.Write(buf)
	default:
		f, err := s.Create()
		if err != nil {
			log.Fatal(err)
		}
		f.Close()
		openSnippetWithEditor(s)
	}
}
예제 #28
0
func DisplayPullRequests(c *cli.Context, pulls []*gh.PullRequest, notrunc bool) {
	w := newTabwriter()
	fmt.Fprintf(w, "NUMBER\tSHA\tLAST UPDATED\tCONTRIBUTOR\tASSIGNEE\tTITLE")
	if c.Bool("lgtm") {
		fmt.Fprintf(w, "\tLGTM")
	}
	fmt.Fprintf(w, "\n")
	for _, p := range pulls {
		if !notrunc {
			p.Title = truncate(p.Title)
		}
		var assignee string
		if p.Assignee != nil {
			assignee = p.Assignee.Login
		}
		fmt.Fprintf(w, "%d\t%s\t%s\t%s\t%s\t%s", p.Number, p.Head.Sha[:8], HumanDuration(time.Since(p.UpdatedAt)), p.User.Login, assignee, p.Title)
		if c.Bool("lgtm") {
			lgtm := strconv.Itoa(p.ReviewComments)
			if p.ReviewComments >= 2 {
				lgtm = Green(lgtm)
			} else if p.ReviewComments == 0 {
				lgtm = DarkRed(lgtm)
			} else {
				lgtm = DarkYellow(lgtm)
			}
			fmt.Fprintf(w, "\t%s", lgtm)
		}
		fmt.Fprintf(w, "\n")
	}

	if err := w.Flush(); err != nil {
		fmt.Fprintf(os.Stderr, "%s", err)
	}
}
예제 #29
0
func deleteVersion(c *cli.Context) {
	if c.NArg() != 1 {
		cliutils.Exit(cliutils.ExitCodeError, "Wrong number of arguments. "+cliutils.GetDocumentationMessage())
	}
	versionDetails, err := utils.CreateVersionDetails(c.Args().Get(0))
	if err != nil {
		cliutils.Exit(cliutils.ExitCodeError, err.Error())
	}
	bintrayDetails, err := createBintrayDetails(c, true)
	if err != nil {
		cliutils.Exit(cliutils.ExitCodeError, err.Error())
	}

	if !c.Bool("quiet") {
		var confirm string
		fmt.Print("Delete version " + versionDetails.Version +
			" of package " + versionDetails.Package + "? (y/n): ")
		fmt.Scanln(&confirm)
		if !cliutils.ConfirmAnswer(confirm) {
			return
		}
	}
	err = commands.DeleteVersion(versionDetails, bintrayDetails)
	cliutils.ExitOnErr(err)
}
예제 #30
0
func Action(c *cli.Context) {
	if len(c.Args()) != 1 {
		logrus.Fatalf("usage: gotty-client [GoTTY URL]")
	}

	// setting up logrus
	logrus.SetOutput(os.Stderr)
	if c.Bool("debug") {
		logrus.SetLevel(logrus.DebugLevel)
	} else {
		logrus.SetLevel(logrus.InfoLevel)
	}

	// create Client
	url := c.Args()[0]
	client, err := gottyclient.NewClient(url)
	if err != nil {
		logrus.Fatalf("Cannot create client: %v", err)
	}

	if c.Bool("skip-tls-verify") {
		client.SkipTLSVerify = true
	}

	// loop
	if err = client.Loop(); err != nil {
		logrus.Fatalf("Communication error: %v", err)
	}
}