git-project-manager/cmd/alias/alias_add.go

107 lines
2.9 KiB
Go

package alias
import (
"fmt"
"strings"
"github.com/pterm/pterm"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/cache"
"gitea.libretechconsulting.com/rmcguire/git-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: util.AliasAddCmdLong,
Run: runAddAliasCmd,
}
func runAddAliasCmd(cmd *cobra.Command, args []string) {
var project *projects.Project
// Check by flag
if projectID := viper.GetInt(util.ViperAliasAddPID); projectID > 0 {
utils.Logger().Debug(fmt.Sprintf("Adding for inbound project ID %d", projectID))
project = utils.Cache().GetProjectByID(projectID)
}
// Check by arg
if len(args) > 0 {
project = utils.FzfFindProject(&util.FzfProjectOpts{Ctx: cmd.Context(), Search: utils.SearchStringFromArgs(args)})
}
// Collect by fzf
if project == nil {
var err error
project, err = utils.FzfProject(&util.FzfProjectOpts{Ctx: cmd.Context()})
if err != nil || project == nil {
utils.Logger().Fatal("No project to alias, nothing to do", utils.Logger().Args("error", err))
}
}
addNewAliases(project.ID)
}
func addNewAliases(projectID int) {
project := utils.Cache().GetProjectByID(projectID)
if project == nil {
utils.Logger().Error("Failed to find project to alias", utils.Logger().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 := utils.Cache().AddAlias(a, project.ID, project.Remote); err != nil {
utils.Logger().Debug("Skipping alias add", utils.Logger().Args(
"error", err,
"alias", a,
))
} else {
utils.Logger().Info("Successfully added alias to project", utils.Logger().Args(
"project", project.String(),
"alias", a,
))
}
}
}
func promptAliasesForProject(p *projects.Project) []string {
aliases := utils.Cache().GetProjectAliases(p)
if len(aliases) > 0 {
utils.Logger().Info("Adding aliases to project", utils.Logger().Args(
"project", p.String(),
"existingAliases", cache.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() {
aliasAddCmd.PersistentFlags().Int(util.FlagProjectID, 0, "Specify a project by ID")
aliasAddCmd.RegisterFlagCompletionFunc(util.FlagProjectID, util.ValidProjectIdFunc)
viper.BindPFlag(util.ViperAliasAddPID, aliasAddCmd.Flag(util.FlagProjectID))
}