package cmd import ( "fmt" "strings" "github.com/pterm/pterm" "github.com/spf13/cobra" "github.com/spf13/viper" cacheProjects "gitlab.sweetwater.com/it/devops/tools/gitlab-project-manager/internal/projects" "gitlab.sweetwater.com/it/devops/tools/gitlab-project-manager/internal/remotes/projects" ) var aliasAddCmd = &cobra.Command{ Use: "add", Aliases: []string{"set", "a", "s"}, Short: "Add a project alias", Args: cobra.ArbitraryArgs, Long: aliasAddCmdLong, Run: runAddAliasCmd, } func runAddAliasCmd(cmd *cobra.Command, args []string) { var project *projects.Project // Check by flag if projectID := viper.GetInt("alias.add.projectid"); projectID > 0 { plog.Debug(fmt.Sprintf("Adding for inbound project ID %d", projectID)) project = cache.GetProjectByID(projectID) } // Check by arg if len(args) > 0 { project = fzfFindProject(&fzfProjectOpts{Ctx: cmd.Context(), Search: searchStringFromArgs(args)}) } // Collect by fzf if project == nil { var err error project, err = fzfProject(&fzfProjectOpts{Ctx: cmd.Context()}) if err != nil || project == nil { plog.Fatal("No project to alias, nothing to do", plog.Args("error", err)) } } addNewAliases(project.ID) } func addNewAliases(projectID int) { project := cache.GetProjectByID(projectID) if project == nil { plog.Error("Failed to find project to alias", plog.Args("projectID", projectID)) return } // Collect the aliases aliases := promptAliasesForProject(project) // Add aliases for _, a := range aliases { a = strings.Trim(a, " '\"%<>|`") if a == "" { continue } if err := cache.AddAlias(a, project.ID, project.Remote); err != nil { plog.Debug("Skipping alias add", plog.Args( "error", err, "alias", a, )) } else { plog.Info("Successfully added alias to project", plog.Args( "project", project.String(), "alias", a, )) } } } func promptAliasesForProject(p *projects.Project) []string { aliases := cache.GetProjectAliases(p) if len(aliases) > 0 { plog.Info("Adding aliases to project", plog.Args( "project", p.String(), "existingAliases", cacheProjects.ProjectAliasesString(aliases), )) } else { pterm.Info.Printfln("Adding aliases to %s", p.Name) } response, _ := pterm.DefaultInteractiveTextInput. WithMultiLine(false). WithDefaultValue(p.Path + " "). Show("Enter aliases separated by space") return strings.Split(response, " ") } func init() { aliasCmd.AddCommand(aliasAddCmd) aliasAddCmd.PersistentFlags().Int("projectID", 0, "Specify a project by ID") aliasAddCmd.RegisterFlagCompletionFunc("projectID", validProjectIdFunc) viper.BindPFlag("alias.add.projectID", aliasAddCmd.Flag("projectID")) }