package cmd import ( "fmt" "strings" "github.com/pterm/pterm" "github.com/spf13/cobra" "github.com/spf13/viper" "gitlab.sweetwater.com/it/devops/tools/gitlab-project-manager/internal/gitlab" "gitlab.sweetwater.com/it/devops/tools/gitlab-project-manager/internal/projects" ) var aliasAddCmd = &cobra.Command{ Use: "add", Short: "Add a project alias", Args: cobra.ArbitraryArgs, Long: aliasAddCmdLong, Run: runAddAliasCmd, } func runAddAliasCmd(cmd *cobra.Command, args []string) { var project *gitlab.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(args[0]) } // Collect by fzf if project == nil { var err error project, err = fzfProject(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); 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 *gitlab.Project) []string { aliases := cache.GetProjectAliases(p) if len(aliases) > 0 { plog.Info("Adding aliases to project", plog.Args( "project", p.String(), "existingAliases", projects.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") viper.BindPFlag("alias.add.projectID", aliasAddCmd.Flag("projectID")) }