Package subcommand code

This commit is contained in:
Ryan McGuire 2024-12-30 15:50:31 -05:00
parent 96378d047e
commit b9d7d5a4f2
51 changed files with 357 additions and 295 deletions

10
.vscode/launch.json vendored
View File

@ -14,6 +14,16 @@
"https://gitea.libretechconsulting.com" "https://gitea.libretechconsulting.com"
] ]
}, },
{
"name": "List Aliases",
"type": "delve",
"request": "launch",
"program": "${workspaceFolder}",
"args": [
"alias",
"ls"
]
},
{ {
"name": "Generate Docs", "name": "Generate Docs",
"type": "delve", "type": "delve",

View File

@ -1,8 +1,9 @@
package alias package alias
import ( import (
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var AliasCmd = &cobra.Command{ var AliasCmd = &cobra.Command{
@ -23,7 +24,7 @@ func aliasCmdPreRun(cmd *cobra.Command, args []string) {
} }
func mustHaveAliases(cmd *cobra.Command, args []string) { func mustHaveAliases(cmd *cobra.Command, args []string) {
utils := util.MustFromCtx(cmd.Context()) utils = util.MustFromCtx(cmd.Context())
if len(utils.Cache().Aliases) == 0 { if len(utils.Cache().Aliases) == 0 {
utils.Logger().Fatal("No aliases set, nothing to " + cmd.Name()) utils.Logger().Fatal("No aliases set, nothing to " + cmd.Name())

View File

@ -45,18 +45,19 @@ func runAddAliasCmd(cmd *cobra.Command, args []string) {
} }
} }
addNewAliases(project.ID) AddNewAliases(cmd, project.ID)
} }
func addNewAliases(projectID int) { func AddNewAliases(cmd *cobra.Command, projectID int) {
project := utils.Cache().GetProjectByID(projectID) u := util.MustFromCtx(cmd.Context())
project := u.Cache().GetProjectByID(projectID)
if project == nil { if project == nil {
utils.Logger().Error("Failed to find project to alias", utils.Logger().Args("projectID", projectID)) u.Logger().Error("Failed to find project to alias", u.Logger().Args("projectID", projectID))
return return
} }
// Collect the aliases // Collect the aliases
aliases := promptAliasesForProject(project) aliases := PromptAliasesForProject(cmd, project)
// Add aliases // Add aliases
for _, a := range aliases { for _, a := range aliases {
@ -64,13 +65,13 @@ func addNewAliases(projectID int) {
if a == "" { if a == "" {
continue continue
} }
if err := utils.Cache().AddAlias(a, project.ID, project.Remote); err != nil { if err := u.Cache().AddAlias(a, project.ID, project.Remote); err != nil {
utils.Logger().Debug("Skipping alias add", utils.Logger().Args( u.Logger().Debug("Skipping alias add", u.Logger().Args(
"error", err, "error", err,
"alias", a, "alias", a,
)) ))
} else { } else {
utils.Logger().Info("Successfully added alias to project", utils.Logger().Args( u.Logger().Info("Successfully added alias to project", u.Logger().Args(
"project", project.String(), "project", project.String(),
"alias", a, "alias", a,
)) ))
@ -78,10 +79,11 @@ func addNewAliases(projectID int) {
} }
} }
func promptAliasesForProject(p *projects.Project) []string { func PromptAliasesForProject(cmd *cobra.Command, p *projects.Project) []string {
aliases := utils.Cache().GetProjectAliases(p) u := util.MustFromCtx(cmd.Context())
aliases := u.Cache().GetProjectAliases(p)
if len(aliases) > 0 { if len(aliases) > 0 {
utils.Logger().Info("Adding aliases to project", utils.Logger().Args( u.Logger().Info("Adding aliases to project", u.Logger().Args(
"project", p.String(), "project", p.String(),
"existingAliases", cache.ProjectAliasesString(aliases), "existingAliases", cache.ProjectAliasesString(aliases),
)) ))

View File

@ -20,15 +20,11 @@ var aliasListCmd = &cobra.Command{
} }
func runListAliasCmd(cmd *cobra.Command, args []string) { func runListAliasCmd(cmd *cobra.Command, args []string) {
remotes := viper.GetStringSlice(FlagRemote) remotes := viper.GetStringSlice(util.FlagRemote)
pterm.DefaultBox. pterm.DefaultBox.
WithLeftPadding(5).WithRightPadding(5). WithLeftPadding(5).WithRightPadding(5).
WithBoxStyle(&pterm.Style{pterm.FgLightBlue}). WithBoxStyle(&pterm.Style{pterm.FgLightBlue}).
WithTitle(pterm.Bold.Sprint(pterm.LightGreen("Aliases by Project"))). WithTitle(pterm.Bold.Sprint(pterm.LightGreen("Aliases by Project"))).
Print("\n" + projectCache.AliasesByProjectString(remotes...)) Print("\n" + utils.Cache().AliasesByProjectString(remotes...))
fmt.Print("\n\n") fmt.Print("\n\n")
} }
func init() {
aliasCmd.AddCommand(aliasListCmd)
}

31
cmd/cache/cache.go vendored
View File

@ -1,34 +1,43 @@
package cmd package cache
import ( import (
"time" "time"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var cacheCmd = &cobra.Command{ var CacheCmd = &cobra.Command{
Use: "cache", Use: "cache",
Aliases: []string{"a", "ln"}, Aliases: []string{"a", "ln"},
Short: "Manage Git project cache", Short: "Manage Git project cache",
Long: cacheCmdLong, Long: util.CacheCmdLong,
} }
var utils *util.Utils
func runCacheCmd(cmd *cobra.Command, args []string) { func runCacheCmd(cmd *cobra.Command, args []string) {
initProjectCache(cmd, args) utils = util.MustFromCtx(cmd.Context())
projectCache.LockCache()
utils.InitProjectCache(cmd, args)
utils.Cache().LockCache()
} }
func postCacheCmd(cmd *cobra.Command, args []string) { func postCacheCmd(cmd *cobra.Command, args []string) {
postProjectCache(cmd, args) utils.PostProjectCache(cmd, args)
projectCache.UnlockCache() utils.Cache().UnlockCache()
} }
func init() { func init() {
rootCmd.AddCommand(cacheCmd) CacheCmd.PersistentFlags().Duration("ttl", 48*time.Hour,
cacheCmd.PersistentFlags().Duration("ttl", 48*time.Hour,
"Duration before cache is re-built in go time.Duration format") "Duration before cache is re-built in go time.Duration format")
viper.BindPFlags(cacheCmd.Flags()) viper.BindPFlags(CacheCmd.Flags())
CacheCmd.AddCommand(clearCmd)
CacheCmd.AddCommand(dumpCmd)
CacheCmd.AddCommand(loadCmd)
CacheCmd.AddCommand(unlockCmd)
} }

View File

@ -1,4 +1,4 @@
package cmd package cache
import ( import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
@ -21,11 +21,10 @@ var clearCmd = &cobra.Command{
func clearCache(cmd *cobra.Command, args []string) { func clearCache(cmd *cobra.Command, args []string) {
slog.Debug("Preparing to clear local cache") slog.Debug("Preparing to clear local cache")
projectCache.Clear(conf.Cache.Clear.ClearAliases) utils.Cache().Clear(utils.Config().Cache.Clear.ClearAliases)
} }
func init() { func init() {
cacheCmd.AddCommand(clearCmd)
clearCmd.Flags().Bool("clearAliases", false, "Will also clear aliases from the cache, use with caution") clearCmd.Flags().Bool("clearAliases", false, "Will also clear aliases from the cache, use with caution")
viper.BindPFlag("cache.clear.clearAliases", clearCmd.LocalFlags().Lookup("clearAliases")) viper.BindPFlag("cache.clear.clearAliases", clearCmd.LocalFlags().Lookup("clearAliases"))
} }

View File

@ -1,10 +1,12 @@
package cmd package cache
import ( import (
"fmt" "fmt"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var dumpCmd = &cobra.Command{ var dumpCmd = &cobra.Command{
@ -17,16 +19,15 @@ var dumpCmd = &cobra.Command{
} }
func runCacheDunpCmd(cmd *cobra.Command, args []string) { func runCacheDunpCmd(cmd *cobra.Command, args []string) {
remotes := viper.GetStringSlice(FlagRemote) remotes := viper.GetStringSlice(util.FlagRemote)
if conf.Dump.Full { if utils.Config().Dump.Full {
fmt.Println(projectCache.DumpString(true, searchStringFromArgs(args), remotes...)) fmt.Println(utils.Cache().DumpString(true, utils.SearchStringFromArgs(args), remotes...))
} else { } else {
plog.Info(projectCache.String()) utils.Logger().Info(utils.Cache().String())
} }
} }
func init() { func init() {
cacheCmd.AddCommand(dumpCmd)
dumpCmd.PersistentFlags().BoolP("full", "f", false, "Dumps entire cache") dumpCmd.PersistentFlags().BoolP("full", "f", false, "Dumps entire cache")
viper.BindPFlag("dump.full", dumpCmd.LocalFlags().Lookup("full")) viper.BindPFlag("dump.full", dumpCmd.LocalFlags().Lookup("full"))
} }

View File

@ -1,8 +1,10 @@
package cmd package cache
import ( import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var loadCmd = &cobra.Command{ var loadCmd = &cobra.Command{
@ -17,15 +19,13 @@ wants to find a new project.`,
} }
func loadCache(cmd *cobra.Command, args []string) { func loadCache(cmd *cobra.Command, args []string) {
remotes := viper.GetStringSlice(FlagRemote) remotes := viper.GetStringSlice(util.FlagRemote)
projectCache.Refresh(remotes...) utils.Cache().Refresh(remotes...)
} }
func init() { func init() {
cacheCmd.AddCommand(loadCmd) loadCmd.PersistentFlags().Bool(util.FlagOwnerOnly, true,
loadCmd.PersistentFlags().Bool(FlagOwnerOnly, true,
"Only load projects that you are owner of") "Only load projects that you are owner of")
viper.BindPFlag(ViperCacheLoadOwnerOnly, loadCmd.Flag(FlagOwnerOnly)) viper.BindPFlag(util.ViperCacheLoadOwnerOnly, loadCmd.Flag(util.FlagOwnerOnly))
} }

View File

@ -1,9 +1,11 @@
package cmd package cache
import ( import (
"github.com/pterm/pterm" "github.com/pterm/pterm"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var unlockCmd = &cobra.Command{ var unlockCmd = &cobra.Command{
@ -11,21 +13,21 @@ var unlockCmd = &cobra.Command{
Short: "unlock Git project cache", Short: "unlock Git project cache",
Long: `unlocks cache to display`, Long: `unlocks cache to display`,
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
initProjectCache(cmd, args) utils = util.MustFromCtx(cmd.Context())
if viper.GetBool(ViperCacheUnlockForce) { utils.InitProjectCache(cmd, args)
projectCache.UnlockCache() if viper.GetBool(util.ViperCacheUnlockForce) {
utils.Cache().UnlockCache()
} else if yes, _ := pterm.DefaultInteractiveConfirm. } else if yes, _ := pterm.DefaultInteractiveConfirm.
WithDefaultValue(false). WithDefaultValue(false).
Show("Are you sure you want to manually unlock?"); yes { Show("Are you sure you want to manually unlock?"); yes {
projectCache.UnlockCache() utils.Cache().UnlockCache()
} else { } else {
plog.Error("You failed to confirm cache unlock") utils.Logger().Error("You failed to confirm cache unlock")
} }
}, },
} }
func init() { func init() {
cacheCmd.AddCommand(unlockCmd) unlockCmd.PersistentFlags().BoolP(util.FlagCacheForce, "f", false, "force unlocks cache (don't ask)")
unlockCmd.PersistentFlags().BoolP(FlagCacheForce, "f", false, "force unlocks cache (don't ask)") viper.BindPFlag(util.ViperCacheUnlockForce, unlockCmd.LocalFlags().Lookup(util.FlagCacheForce))
viper.BindPFlag(ViperCacheUnlockForce, unlockCmd.LocalFlags().Lookup(FlagCacheForce))
} }

View File

@ -1,16 +0,0 @@
package cmd
import (
"github.com/spf13/cobra"
)
var configCmd = &cobra.Command{
Use: "config",
Short: "Git Project Manager Configuration",
Aliases: []string{"conf"},
Long: configCmdLong,
}
func init() {
rootCmd.AddCommand(configCmd)
}

26
cmd/config/config.go Normal file
View File

@ -0,0 +1,26 @@
package cmd
import (
"github.com/spf13/cobra"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
)
var ConfigCmd = &cobra.Command{
Use: "config",
Short: "Git Project Manager Configuration",
Aliases: []string{"conf"},
Long: util.ConfigCmdLong,
PersistentPreRun: configCmdPreRun,
}
var utils *util.Utils
func configCmdPreRun(cmd *cobra.Command, args []string) {
utils = util.MustFromCtx(cmd.Context())
}
func init() {
ConfigCmd.AddCommand(configGenerateCmd)
ConfigCmd.AddCommand(configShowCmd)
}

View File

@ -10,6 +10,7 @@ import (
"github.com/spf13/viper" "github.com/spf13/viper"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/config" "gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/config"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/info" "gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/info"
) )
@ -18,7 +19,7 @@ var configGenerateCmd = &cobra.Command{
Use: "generate", Use: "generate",
Short: "Generate a default configuration", Short: "Generate a default configuration",
Aliases: []string{"gen", "new", "default"}, Aliases: []string{"gen", "new", "default"},
Long: configGenCmdLong, Long: util.ConfigGenCmdLong,
Run: runConfigGenerateCmd, Run: runConfigGenerateCmd,
} }
@ -27,34 +28,34 @@ func runConfigGenerateCmd(cmd *cobra.Command, args []string) {
if viper.ConfigFileUsed() != "" { if viper.ConfigFileUsed() != "" {
configFile = viper.ConfigFileUsed() configFile = viper.ConfigFileUsed()
} else { } else {
configFile = defConfigPath configFile = util.DefConfigPath
} }
plog.Debug("Using config file " + configFile) utils.Logger().Debug("Using config file " + configFile)
configFile, _ = resolvePath(configFile) configFile, _ = util.ResolvePath(configFile)
newConf := promptConfigSettings(&conf) newConf := promptConfigSettings(utils.Config())
if write, _ := cmd.Flags().GetBool(FlagWrite); write { if write, _ := cmd.Flags().GetBool(util.FlagWrite); write {
write, _ := pterm.DefaultInteractiveContinue. write, _ := pterm.DefaultInteractiveContinue.
WithDefaultText("Really write config file?"). WithDefaultText("Really write config file?").
WithOptions([]string{"yes", "no"}). WithOptions([]string{"yes", "no"}).
Show() Show()
if write != "yes" { if write != "yes" {
plog.Fatal("Aborting config file write") utils.Logger().Fatal("Aborting config file write")
} }
writeConfigFile(newConf, configFile) writeConfigFile(newConf, configFile)
plog.Info("Wrote config to file", utils.Logger().Info("Wrote config to file",
plog.Args("file", configFile)) utils.Logger().Args("file", configFile))
} else { } else {
var c bytes.Buffer var c bytes.Buffer
enc := yaml.NewEncoder(&c) enc := yaml.NewEncoder(&c)
enc.SetIndent(2) enc.SetIndent(2)
enc.Encode(newConf) enc.Encode(newConf)
plog.Info("Suggest running with --write or redirect (> " + configFile + ")") utils.Logger().Info("Suggest running with --write or redirect (> " + configFile + ")")
fmt.Print(c.String()) fmt.Print(c.String())
} }
} }
@ -62,11 +63,11 @@ func runConfigGenerateCmd(cmd *cobra.Command, args []string) {
func writeConfigFile(c *config.Config, path string) { func writeConfigFile(c *config.Config, path string) {
file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o640) file, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o640)
if err != nil { if err != nil {
plog.Error("Failed to prepare config for writing", plog.Args("error", err)) utils.Logger().Error("Failed to prepare config for writing", utils.Logger().Args("error", err))
} }
enc := yaml.NewEncoder(file) enc := yaml.NewEncoder(file)
if err := enc.Encode(c); err != nil { if err := enc.Encode(c); err != nil {
plog.Fatal("Failed writing config file", plog.Args("file", path)) utils.Logger().Fatal("Failed writing config file", utils.Logger().Args("file", path))
} }
} }
@ -149,7 +150,6 @@ func promptConfigSettings(c *config.Config) *config.Config {
} }
func init() { func init() {
configCmd.AddCommand(configGenerateCmd) configGenerateCmd.PersistentFlags().Bool(util.FlagPrompt, false, "Prompt for settings")
configGenerateCmd.PersistentFlags().Bool(FlagPrompt, false, "Prompt for settings") configGenerateCmd.PersistentFlags().Bool(util.FlagWrite, false, "Write config to file")
configGenerateCmd.PersistentFlags().Bool(FlagWrite, false, "Write config to file")
} }

View File

@ -6,6 +6,8 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gopkg.in/yaml.v3" "gopkg.in/yaml.v3"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var configShowCmd = &cobra.Command{ var configShowCmd = &cobra.Command{
@ -16,16 +18,16 @@ var configShowCmd = &cobra.Command{
} }
func runConfigShowCmd(cmd *cobra.Command, args []string) { func runConfigShowCmd(cmd *cobra.Command, args []string) {
c := conf c := *utils.Config()
showSensitive, _ := cmd.Flags().GetBool(FlagSensitive) showSensitive, _ := cmd.Flags().GetBool(util.FlagSensitive)
if !showSensitive { if !showSensitive {
plog.Info("Sensitive fields hidden, do not use unreviewed as config") utils.Logger().Info("Sensitive fields hidden, do not use unreviewed as config")
for _, r := range c.Remotes { for _, r := range c.Remotes {
r.Token = strings.Repeat("*", len(r.Token)) r.Token = strings.Repeat("*", len(r.Token))
} }
} else { } else {
plog.Warn("Displaying sensitive fields!") utils.Logger().Warn("Displaying sensitive fields!")
} }
enc := yaml.NewEncoder(os.Stdout) enc := yaml.NewEncoder(os.Stdout)
@ -34,6 +36,5 @@ func runConfigShowCmd(cmd *cobra.Command, args []string) {
} }
func init() { func init() {
configCmd.AddCommand(configShowCmd) configShowCmd.Flags().BoolP(util.FlagSensitive, "s", false, "Set to show sensitive fields")
configShowCmd.Flags().BoolP(FlagSensitive, "s", false, "Set to show sensitive fields")
} }

View File

@ -5,6 +5,8 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/cobra/doc" "github.com/spf13/cobra/doc"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var docsCmd = &cobra.Command{ var docsCmd = &cobra.Command{
@ -17,9 +19,9 @@ var docsCmd = &cobra.Command{
} }
func runDocsCmd(cmd *cobra.Command, args []string) { func runDocsCmd(cmd *cobra.Command, args []string) {
outDir, err := cmd.Flags().GetString(FlagDocsPath) outDir, err := cmd.Flags().GetString(util.FlagDocsPath)
if err != nil { if err != nil {
plog.Error("missing docs path") utils.Logger().Error("missing docs path")
} }
prepareDocsDir(cmd, outDir) prepareDocsDir(cmd, outDir)
@ -35,10 +37,10 @@ func runDocsCmd(cmd *cobra.Command, args []string) {
case "yaml": case "yaml":
err = doc.GenYamlTree(cmd.Root(), outDir) err = doc.GenYamlTree(cmd.Root(), outDir)
default: default:
plog.Error("invalid docs type", plog.Args("type", args[0])) utils.Logger().Error("invalid docs type", utils.Logger().Args("type", args[0]))
} }
plog.Info("docs generation complete", plog.Args( utils.Logger().Info("docs generation complete", utils.Logger().Args(
"type", args[0], "docsDir", outDir, "err", err)) "type", args[0], "docsDir", outDir, "err", err))
} }
@ -47,14 +49,14 @@ func prepareDocsDir(_ *cobra.Command, outDir string) {
if err != nil { if err != nil {
err = os.Mkdir(outDir, 0o755) err = os.Mkdir(outDir, 0o755)
if err != nil { if err != nil {
plog.Error("failed to create docs path", plog.Args( utils.Logger().Error("failed to create docs path", utils.Logger().Args(
"error", err.Error(), "docsDir", outDir)) "error", err.Error(), "docsDir", outDir))
} }
} }
} }
func init() { func init() {
docsCmd.PersistentFlags().StringP(FlagDocsPath, "d", "./docs", "specify output directory for documentation") docsCmd.PersistentFlags().StringP(util.FlagDocsPath, "d", "./docs", "specify output directory for documentation")
rootCmd.AddCommand(docsCmd) rootCmd.AddCommand(docsCmd)
} }

View File

@ -1,54 +0,0 @@
package cmd
import (
"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 projectCmd = &cobra.Command{
Use: "project [fuzzy alias search]",
Short: "Use a Git project",
Aliases: []string{"proj", "projects", "p"},
Args: cobra.MaximumNArgs(1),
ArgAliases: []string{"alias"},
Long: projCmdLong,
PersistentPreRun: initProjects,
PersistentPostRun: postProjectCmd,
// Run: projectGoCmdRun,
}
func getProject(args []string) *projects.Project {
remotes := viper.GetStringSlice(util.FlagRemote)
fzfOpts := &util.FzfProjectOpts{
Ctx: rootCmd.Context(),
Search: utils.SearchStringFromArgs(args),
Remotes: remotes,
}
project := fzfFindProject(fzfOpts)
if project == nil {
plog.Fatal("Failed to find a project, nothing to do")
} else {
plog.Debug("Houston, we have a project", plog.Args(
"project", project.String(),
"aliases", cache.ProjectAliasesString(
projectCache.GetProjectAliases(project)),
))
}
if len(projectCache.GetProjectAliases(project)) == 0 {
plog.Info("New project, set aliases or press enter for default")
addNewAliases(project.ID)
}
return project
}
func init() {
rootCmd.AddCommand(projectCmd)
}

66
cmd/project/project.go Normal file
View File

@ -0,0 +1,66 @@
package project
import (
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/alias"
"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 ProjectCmd = &cobra.Command{
Use: "project [fuzzy alias search]",
Short: "Use a Git project",
Aliases: []string{"proj", "projects", "p"},
Args: cobra.MaximumNArgs(1),
ArgAliases: []string{"alias"},
Long: util.ProjCmdLong,
PersistentPreRun: projectCmdPreRun,
PersistentPostRun: util.PostProjectCmd,
// Run: projectGoCmdRun,
}
var utils *util.Utils
func projectCmdPreRun(cmd *cobra.Command, args []string) {
utils = util.MustFromCtx(cmd.Context())
util.InitProjects(cmd, args)
}
func getProject(cmd *cobra.Command, args []string) *projects.Project {
remotes := viper.GetStringSlice(util.FlagRemote)
fzfOpts := &util.FzfProjectOpts{
Ctx: cmd.Context(),
Search: utils.SearchStringFromArgs(args),
Remotes: remotes,
}
project := utils.FzfFindProject(fzfOpts)
if project == nil {
utils.Logger().Fatal("Failed to find a project, nothing to do")
} else {
utils.Logger().Debug("Houston, we have a project", utils.Logger().Args(
"project", project.String(),
"aliases", cache.ProjectAliasesString(
utils.Cache().GetProjectAliases(project)),
))
}
if len(utils.Cache().GetProjectAliases(project)) == 0 {
utils.Logger().Info("New project, set aliases or press enter for default")
alias.AddNewAliases(cmd, project.ID)
}
return project
}
func init() {
ProjectCmd.AddCommand(projectAddCmd)
ProjectCmd.AddCommand(projectGoCmd)
ProjectCmd.AddCommand(projectListCmd)
ProjectCmd.AddCommand(projectOpenCmd)
ProjectCmd.AddCommand(projectRunCmd)
ProjectCmd.AddCommand(projectShowCmd)
}

View File

@ -1,21 +1,19 @@
package cmd package project
import ( import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var projectAddCmd = &cobra.Command{ var projectAddCmd = &cobra.Command{
Use: "add", Use: "add",
Short: "Add a new Git project", Short: "Add a new Git project",
Aliases: []string{"a", "alias"}, Aliases: []string{"a", "alias"},
Long: projAddCmdLong, Long: util.ProjAddCmdLong,
Run: projectAddCmdRun, Run: projectAddCmdRun,
} }
func projectAddCmdRun(cmd *cobra.Command, args []string) { func projectAddCmdRun(cmd *cobra.Command, args []string) {
getProject(args) getProject(cmd, args)
}
func init() {
projectCmd.AddCommand(projectAddCmd)
} }

View File

@ -1,4 +1,4 @@
package cmd package project
import ( import (
"fmt" "fmt"
@ -7,6 +7,8 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var projectGoCmd = &cobra.Command{ var projectGoCmd = &cobra.Command{
@ -15,30 +17,30 @@ var projectGoCmd = &cobra.Command{
Aliases: []string{"goto", "cd"}, Aliases: []string{"goto", "cd"},
Args: cobra.MaximumNArgs(1), Args: cobra.MaximumNArgs(1),
ArgAliases: []string{"project"}, ArgAliases: []string{"project"},
ValidArgsFunction: validAliasesFunc, ValidArgsFunction: util.ValidAliasesFunc,
Long: projGoCmdLong, Long: util.ProjGoCmdLong,
Run: projectGoCmdRun, Run: projectGoCmdRun,
} }
func projectGoCmdRun(cmd *cobra.Command, args []string) { func projectGoCmdRun(cmd *cobra.Command, args []string) {
remotes := viper.GetStringSlice(FlagRemote) remotes := viper.GetStringSlice(util.FlagRemote)
fzfOpts := &fzfProjectOpts{ fzfOpts := &util.FzfProjectOpts{
Ctx: cmd.Context(), Ctx: cmd.Context(),
Search: searchStringFromArgs(args), Search: utils.SearchStringFromArgs(args),
MustHaveAlias: true, MustHaveAlias: true,
Remotes: remotes, Remotes: remotes,
} }
project := fzfSearchProjectAliases(fzfOpts) project := utils.FzfSearchProjectAliases(fzfOpts)
if project == nil { if project == nil {
plog.Fatal("No project selected, nowhere to go") utils.Logger().Fatal("No project selected, nowhere to go")
} }
projectCache.GoTo(project) utils.Cache().GoTo(project)
project.SetRepo(projectCache.OpenProject(cmd.Context(), project)) project.SetRepo(utils.Cache().OpenProject(cmd.Context(), project))
plog.Debug("Project ready", plog.Args( utils.Logger().Debug("Project ready", utils.Logger().Args(
"path", projectCache.GetProjectPath(project), "path", utils.Cache().GetProjectPath(project),
"project", project, "project", project,
)) ))
@ -46,10 +48,6 @@ func projectGoCmdRun(cmd *cobra.Command, args []string) {
// This should be read by any source command, for instance // This should be read by any source command, for instance
// `cd "$(git-project-manager projects cd somealias)"` // `cd "$(git-project-manager projects cd somealias)"`
fmt.Println(projectCache.GetProjectPath(project)) fmt.Println(utils.Cache().GetProjectPath(project))
exec.Command("cd", projectCache.GetProjectPath(project)).Run() exec.Command("cd", utils.Cache().GetProjectPath(project)).Run()
}
func init() {
projectCmd.AddCommand(projectGoCmd)
} }

View File

@ -0,0 +1,28 @@
package project
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
)
var projectListCmd = &cobra.Command{
Use: "list",
Short: "List Git Projects",
Aliases: []string{"ls", "l"},
Long: util.ProjListCmdLong,
Run: projectListCmdRun,
}
func projectListCmdRun(cmd *cobra.Command, args []string) {
remotes := viper.GetStringSlice(util.FlagRemote)
fmt.Println(utils.Cache().DumpString(viper.GetBool(util.ViperProjectListAll), utils.SearchStringFromArgs(args), remotes...))
}
func init() {
projectListCmd.PersistentFlags().Bool(util.FlagAll, false, "List all, not just cloned locally")
viper.BindPFlag(util.ViperProjectListAll, projectListCmd.Flag(util.FlagAll))
}

View File

@ -1,6 +1,7 @@
package cmd package project
import ( import (
"context"
"errors" "errors"
"os" "os"
"os/exec" "os/exec"
@ -8,6 +9,8 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var projectOpenCmd = &cobra.Command{ var projectOpenCmd = &cobra.Command{
@ -15,8 +18,8 @@ var projectOpenCmd = &cobra.Command{
Short: "Open project in your IDE", Short: "Open project in your IDE",
Aliases: []string{"goto", "cd"}, Aliases: []string{"goto", "cd"},
Args: cobra.OnlyValidArgs, Args: cobra.OnlyValidArgs,
ValidArgsFunction: validAliasesFunc, ValidArgsFunction: util.ValidAliasesFunc,
Long: projOpenCmdLong, Long: util.ProjOpenCmdLong,
Run: projectOpenCmdRun, Run: projectOpenCmdRun,
} }
@ -48,47 +51,47 @@ func projectOpenCmdRun(cmd *cobra.Command, args []string) {
// Find an editor // Find an editor
editor := findEditor() editor := findEditor()
if editor == "" { if editor == "" {
plog.Fatal("No usable editor found") utils.Logger().Fatal("No usable editor found")
} }
remotes := viper.GetStringSlice(FlagRemote) remotes := viper.GetStringSlice(util.FlagRemote)
fzfOpts := &fzfProjectOpts{ fzfOpts := &util.FzfProjectOpts{
Ctx: cmd.Context(), Ctx: cmd.Context(),
Search: searchStringFromArgs(args), Search: utils.SearchStringFromArgs(args),
Remotes: remotes, Remotes: remotes,
} }
project := fzfCwdOrSearchProjectAliases(fzfOpts) project := utils.FzfCwdOrSearchProjectAliases(fzfOpts)
if project == nil { if project == nil {
plog.Fatal("No project to open, nothing to do") utils.Logger().Fatal("No project to open, nothing to do")
} }
// Check the project // Check the project
path := projectCache.GetProjectPath(project) path := utils.Cache().GetProjectPath(project)
if _, err := os.Stat(path); err != nil { if _, err := os.Stat(path); err != nil {
plog.Fatal("Unable to open project", plog.Args("error", err)) utils.Logger().Fatal("Unable to open project", utils.Logger().Args("error", err))
} }
// Open the project with the editor // Open the project with the editor
file := getEntrypointFile(path) file := getEntrypointFile(path)
openEditor(editor, path+"/"+file) openEditor(cmd.Context(), editor, path+"/"+file)
} }
func openEditor(editor string, path string) { func openEditor(ctx context.Context, editor string, path string) {
// Compile arguments // Compile arguments
args := make([]string, 0, 1) args := make([]string, 0, 1)
if conf.Editor.OpenFlags != "" { if utils.Config().Editor.OpenFlags != "" {
args = append(args, conf.Editor.OpenFlags) args = append(args, utils.Config().Editor.OpenFlags)
} }
args = append(args, path) args = append(args, path)
// Launch editor // Launch editor
cmd := exec.CommandContext(rootCmd.Context(), editor, args...) cmd := exec.CommandContext(ctx, editor, args...)
cmd.Dir = filepath.Dir(path) cmd.Dir = filepath.Dir(path)
cmd.Stdout = os.Stdout cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil { if err := cmd.Run(); err != nil {
plog.Error("Failed to open project", plog.Args( utils.Logger().Error("Failed to open project", utils.Logger().Args(
"error", err.Error(), "error", err.Error(),
"command", cmd.String(), "command", cmd.String(),
)) ))
@ -100,7 +103,7 @@ func openEditor(editor string, path string) {
func getEntrypointFile(projectPath string) string { func getEntrypointFile(projectPath string) string {
if err := os.Chdir(projectPath); err != nil { if err := os.Chdir(projectPath); err != nil {
return "" return ""
} else if conf.Editor.OpenDirectory { } else if utils.Config().Editor.OpenDirectory {
return "." return "."
} }
@ -119,10 +122,10 @@ func findEditor() string {
var err error var err error
// First try configured editor // First try configured editor
if conf.Editor.Binary != "" { if utils.Config().Editor.Binary != "" {
editor, err = getEditor(conf.Editor.Binary) editor, err = getEditor(utils.Config().Editor.Binary)
if err != nil || editor == "" { if err != nil || editor == "" {
plog.Error("Configured editor is not usable, finding others", plog.Args( utils.Logger().Error("Configured editor is not usable, finding others", utils.Logger().Args(
"error", err, "error", err,
)) ))
} }
@ -130,7 +133,7 @@ func findEditor() string {
// Then try to find a known editor // Then try to find a known editor
if editor == "" || err != nil { if editor == "" || err != nil {
conf.Editor.OpenFlags = "" utils.Config().Editor.OpenFlags = ""
for _, e := range knownEditors { for _, e := range knownEditors {
path, err := getEditor(e) path, err := getEditor(e)
if err == nil && path != "" { if err == nil && path != "" {
@ -140,9 +143,9 @@ func findEditor() string {
} }
} }
plog.Debug("Editor found for open", plog.Args( utils.Logger().Debug("Editor found for open", utils.Logger().Args(
"editor", editor, "editor", editor,
"command", editor+" "+conf.Editor.OpenFlags, "command", editor+" "+utils.Config().Editor.OpenFlags,
)) ))
return editor return editor
@ -164,7 +167,7 @@ func getEditorPath(editor string) (string, error) {
editor, _ = exec.LookPath(editor) editor, _ = exec.LookPath(editor)
} }
return resolvePath(editor) return util.ResolvePath(editor)
} }
func isEditorExecutable(editor string) bool { func isEditorExecutable(editor string) bool {
@ -180,7 +183,6 @@ func isEditorExecutable(editor string) bool {
} }
func init() { func init() {
projectCmd.AddCommand(projectOpenCmd)
projectOpenCmd.PersistentFlags().String("displayName", "", "Set display name of editor (meant for config file)") projectOpenCmd.PersistentFlags().String("displayName", "", "Set display name of editor (meant for config file)")
projectOpenCmd.PersistentFlags().String("binary", "", "Path to editor binary") projectOpenCmd.PersistentFlags().String("binary", "", "Path to editor binary")
projectOpenCmd.PersistentFlags().String("openFlags", "", "Optional flags when opening project (e.g. --reuse-window)") projectOpenCmd.PersistentFlags().String("openFlags", "", "Optional flags when opening project (e.g. --reuse-window)")

View File

@ -1,4 +1,4 @@
package cmd package project
import ( import (
"fmt" "fmt"
@ -7,35 +7,37 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
) )
var projectRunCmd = &cobra.Command{ var projectRunCmd = &cobra.Command{
Use: "run", Use: "run",
Short: "Run the project (e.g. go run .)", Short: "Run the project (e.g. go run .)",
Aliases: []string{"exec", "r"}, Aliases: []string{"exec", "r"},
Long: projRunCmdLong, Long: util.ProjRunCmdLong,
Run: projectRunCmdRun, Run: projectRunCmdRun,
} }
func projectRunCmdRun(cmd *cobra.Command, args []string) { func projectRunCmdRun(cmd *cobra.Command, args []string) {
remotes := viper.GetStringSlice(FlagRemote) remotes := viper.GetStringSlice(util.FlagRemote)
fzfOpts := &fzfProjectOpts{ fzfOpts := &util.FzfProjectOpts{
Ctx: cmd.Context(), Ctx: cmd.Context(),
Search: searchStringFromArgs(args), Search: utils.SearchStringFromArgs(args),
Remotes: remotes, Remotes: remotes,
} }
project := fzfCwdOrSearchProjectAliases(fzfOpts) project := utils.FzfCwdOrSearchProjectAliases(fzfOpts)
if project == nil { if project == nil {
plog.Fatal("No project selected, nothing to open") utils.Logger().Fatal("No project selected, nothing to open")
} }
lang := project.GetLanguage() lang := project.GetLanguage()
if lang == nil { if lang == nil {
plog.Fatal("Git remote isn't sure what language this project is... can't run.") utils.Logger().Fatal("Git remote isn't sure what language this project is... can't run.")
} }
plog.Debug(fmt.Sprintf("Project is written in %s, %.2f%% coverage", lang.Name, lang.Percentage)) utils.Logger().Debug(fmt.Sprintf("Project is written in %s, %.2f%% coverage", lang.Name, lang.Percentage))
switch lang.Name { switch lang.Name {
case "Go": case "Go":
@ -50,5 +52,5 @@ func projectRunCmdRun(cmd *cobra.Command, args []string) {
} }
func init() { func init() {
projectCmd.AddCommand(projectRunCmd) ProjectCmd.AddCommand(projectRunCmd)
} }

View File

@ -1,4 +1,4 @@
package cmd package project
import ( import (
"fmt" "fmt"
@ -8,6 +8,7 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/projects" "gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/projects"
) )
@ -16,7 +17,7 @@ var projectShowCmd = &cobra.Command{
Short: "Show detail for a Git project", Short: "Show detail for a Git project",
Aliases: []string{"cat", "s"}, Aliases: []string{"cat", "s"},
Args: cobra.ArbitraryArgs, Args: cobra.ArbitraryArgs,
Long: projShowCmdLong, Long: util.ProjShowCmdLong,
Run: projectShowCmdRun, Run: projectShowCmdRun,
} }
@ -24,24 +25,24 @@ func projectShowCmdRun(cmd *cobra.Command, args []string) {
var project *projects.Project var project *projects.Project
var inCwd bool var inCwd bool
remotes := viper.GetStringSlice(FlagRemote) remotes := viper.GetStringSlice(util.FlagRemote)
fzfOpts := &fzfProjectOpts{ fzfOpts := &util.FzfProjectOpts{
Ctx: cmd.Context(), Ctx: cmd.Context(),
Search: searchStringFromArgs(args), Search: utils.SearchStringFromArgs(args),
Remotes: remotes, Remotes: remotes,
} }
// Try to find project from current directory // Try to find project from current directory
if viper.GetBool(ViperProjectShowCurrent) { if viper.GetBool(util.ViperProjectShowCurrent) {
var err error var err error
project, err = projectCache.GetProjectFromCwd() project, err = utils.Cache().GetProjectFromCwd()
if err != nil { if err != nil {
// Not an error because we're still going to try to find a project // Not an error because we're still going to try to find a project
plog.Warn("Failed to get project from current directory", plog.Args( utils.Logger().Warn("Failed to get project from current directory", utils.Logger().Args(
"error", err, "error", err,
)) ))
} else if project == nil { } else if project == nil {
plog.Warn("Failed to use --current flag, project not found in current path") utils.Logger().Warn("Failed to use --current flag, project not found in current path")
} else { } else {
inCwd = true inCwd = true
} }
@ -49,15 +50,15 @@ func projectShowCmdRun(cmd *cobra.Command, args []string) {
// Otherwise find from the given search string // Otherwise find from the given search string
if project == nil { if project == nil {
project = fzfFindProject(fzfOpts) project = utils.FzfFindProject(fzfOpts)
} }
// Do a full fuzzy find if all else fails // Do a full fuzzy find if all else fails
if project == nil { if project == nil {
var err error var err error
project, err = fzfProject(fzfOpts) project, err = utils.FzfProject(fzfOpts)
if err != nil || project == nil { if err != nil || project == nil {
plog.Fatal("Failed to find project, nothing to show", plog.Args( utils.Logger().Fatal("Failed to find project, nothing to show", utils.Logger().Args(
"error", err, "error", err,
)) ))
} }
@ -68,17 +69,17 @@ func projectShowCmdRun(cmd *cobra.Command, args []string) {
WithLeftPadding(5).WithRightPadding(5). WithLeftPadding(5).WithRightPadding(5).
WithBoxStyle(&pterm.Style{pterm.FgLightBlue}). WithBoxStyle(&pterm.Style{pterm.FgLightBlue}).
WithTitle(pterm.Bold.Sprint(pterm.LightGreen("Project Information"))). WithTitle(pterm.Bold.Sprint(pterm.LightGreen("Project Information"))).
Println(projectCache.ProjectString(project)) Println(utils.Cache().ProjectString(project))
fmt.Println() fmt.Println()
if inCwd { if inCwd {
project.SetRepo(projectCache.OpenProject(cmd.Context(), project)) project.SetRepo(utils.Cache().OpenProject(cmd.Context(), project))
fmt.Fprintln(os.Stderr, project.GetGitInfo()+"\n") fmt.Fprintln(os.Stderr, project.GetGitInfo()+"\n")
} }
} }
func init() { func init() {
projectCmd.AddCommand(projectShowCmd) ProjectCmd.AddCommand(projectShowCmd)
projectShowCmd.PersistentFlags().Bool(FlagCurrent, false, "Use project in CWD rather than fuzzy find") projectShowCmd.PersistentFlags().Bool(util.FlagCurrent, false, "Use project in CWD rather than fuzzy find")
viper.BindPFlag(ViperProjectShowCurrent, projectShowCmd.Flag(FlagCurrent)) viper.BindPFlag(util.ViperProjectShowCurrent, projectShowCmd.Flag(util.FlagCurrent))
} }

View File

@ -1,27 +0,0 @@
package cmd
import (
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var projectListCmd = &cobra.Command{
Use: "list",
Short: "List Git Projects",
Aliases: []string{"ls", "l"},
Long: projListCmdLong,
Run: projectListCmdRun,
}
func projectListCmdRun(cmd *cobra.Command, args []string) {
remotes := viper.GetStringSlice(FlagRemote)
fmt.Println(projectCache.DumpString(viper.GetBool(ViperProjectListAll), searchStringFromArgs(args), remotes...))
}
func init() {
projectCmd.AddCommand(projectListCmd)
projectListCmd.PersistentFlags().Bool(FlagAll, false, "List all, not just cloned locally")
viper.BindPFlag(ViperProjectListAll, projectListCmd.Flag(FlagAll))
}

View File

@ -12,6 +12,10 @@ import (
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/alias"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/cache"
conf "gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/config"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/project"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util" "gitea.libretechconsulting.com/rmcguire/git-project-manager/cmd/util"
"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/config" "gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/config"
) )
@ -32,6 +36,7 @@ var (
// Hook traversal is enabled, so this will be run for all // Hook traversal is enabled, so this will be run for all
// sub-commands regardless of their registered pre-hooks // sub-commands regardless of their registered pre-hooks
func initRootCmd(cmd *cobra.Command, args []string) { func initRootCmd(cmd *cobra.Command, args []string) {
cmd.SetContext(util.AddToCtx(cmd.Context(), utils))
utils.InitProjectPath(cmd, args) utils.InitProjectPath(cmd, args)
} }
@ -41,9 +46,6 @@ func Execute() {
ctx, cncl := signal.NotifyContext(context.Background(), os.Kill, os.Interrupt) ctx, cncl := signal.NotifyContext(context.Background(), os.Kill, os.Interrupt)
defer cncl() defer cncl()
// Store provided util.Utils in context
ctx = util.AddToCtx(ctx, utils)
err := rootCmd.ExecuteContext(ctx) err := rootCmd.ExecuteContext(ctx)
if err != nil { if err != nil {
pterm.Error.Printfln("%s", pterm.LightYellow("Command failed, "+err.Error())) pterm.Error.Printfln("%s", pterm.LightYellow("Command failed, "+err.Error()))
@ -67,11 +69,17 @@ func init() {
rootCmd.PersistentFlags().StringSlice(util.FlagRemote, []string{}, rootCmd.PersistentFlags().StringSlice(util.FlagRemote, []string{},
"Specify remotes by host for any sub-command. Provide multiple times or comma delimited.") "Specify remotes by host for any sub-command. Provide multiple times or comma delimited.")
viper.BindPFlags(rootCmd.PersistentFlags())
// Flag autocompletion // Flag autocompletion
rootCmd.RegisterFlagCompletionFunc(util.FlagLogLevel, util.ValidLogLevelsFunc) rootCmd.RegisterFlagCompletionFunc(util.FlagLogLevel, util.ValidLogLevelsFunc)
rootCmd.RegisterFlagCompletionFunc(util.FlagRemote, utils.ValidRemotesFunc) rootCmd.RegisterFlagCompletionFunc(util.FlagRemote, util.ValidRemotesFunc)
viper.BindPFlags(rootCmd.PersistentFlags()) // Subcommands
rootCmd.AddCommand(alias.AliasCmd)
rootCmd.AddCommand(cache.CacheCmd)
rootCmd.AddCommand(conf.ConfigCmd)
rootCmd.AddCommand(project.ProjectCmd)
} }
// initConfig reads in config file and ENV variables if set. // initConfig reads in config file and ENV variables if set.
@ -112,6 +120,8 @@ func getInitConfigFunc(utils *util.Utils) func() {
plog.Error("Failed loading config", plog.Args("err", err)) plog.Error("Failed loading config", plog.Args("err", err))
} }
utils.SetConfig(conf)
if len(os.Args) > 0 && configExemptCommands.Match([]byte(os.Args[1])) { if len(os.Args) > 0 && configExemptCommands.Match([]byte(os.Args[1])) {
plog.Debug("Permitting missing config for config sub-command") plog.Debug("Permitting missing config for config sub-command")
return return

View File

@ -8,31 +8,34 @@ import (
"golang.org/x/exp/slices" "golang.org/x/exp/slices"
) )
func (u *Utils) ValidProjectsFunc(cmd *cobra.Command, args []string, toComplete string) ( func ValidProjectsFunc(cmd *cobra.Command, args []string, toComplete string) (
[]string, cobra.ShellCompDirective, []string, cobra.ShellCompDirective,
) { ) {
u := MustFromCtx(cmd.Context())
u.InitProjectCache(cmd, args) u.InitProjectCache(cmd, args)
return u.Cache().ProjectStrings(toComplete), cobra.ShellCompDirectiveNoFileComp return u.Cache().ProjectStrings(toComplete), cobra.ShellCompDirectiveNoFileComp
} }
func (u *Utils) ValidAliasesFunc(cmd *cobra.Command, args []string, toComplete string) ( func ValidAliasesFunc(cmd *cobra.Command, args []string, toComplete string) (
[]string, cobra.ShellCompDirective, []string, cobra.ShellCompDirective,
) { ) {
u.InitProjectCache(cmd, args) utils := MustFromCtx(cmd.Context())
return u.Cache().AliasStrings(toComplete), cobra.ShellCompDirectiveNoFileComp utils.InitProjectCache(cmd, args)
return utils.Cache().AliasStrings(toComplete), cobra.ShellCompDirectiveNoFileComp
} }
func (u *Utils) ValidProjectsOrAliasesFunc(cmd *cobra.Command, args []string, toComplete string) ( func (u *Utils) ValidProjectsOrAliasesFunc(cmd *cobra.Command, args []string, toComplete string) (
[]string, cobra.ShellCompDirective, []string, cobra.ShellCompDirective,
) { ) {
projectStrings, _ := u.ValidAliasesFunc(cmd, args, toComplete) projectStrings, _ := ValidAliasesFunc(cmd, args, toComplete)
aliasStrings, _ := u.ValidProjectsFunc(cmd, args, toComplete) aliasStrings, _ := ValidProjectsFunc(cmd, args, toComplete)
return append(projectStrings, aliasStrings...), cobra.ShellCompDirectiveDefault return append(projectStrings, aliasStrings...), cobra.ShellCompDirectiveDefault
} }
func (u *Utils) ValidRemotesFunc(_ *cobra.Command, _ []string, toComplete string) ( func ValidRemotesFunc(cmd *cobra.Command, _ []string, toComplete string) (
[]string, cobra.ShellCompDirective, []string, cobra.ShellCompDirective,
) { ) {
u := MustFromCtx(cmd.Context())
remotes := make([]string, 0, len(u.Config().Remotes)) remotes := make([]string, 0, len(u.Config().Remotes))
for _, remote := range u.Config().Remotes { for _, remote := range u.Config().Remotes {
if strings.HasPrefix(remote.Host, toComplete) { if strings.HasPrefix(remote.Host, toComplete) {

View File

@ -27,4 +27,4 @@ shortcuts for moving around in projects and opening your code
* [git-project-manager docs](git-project-manager_docs.md) - Generate documentation for git-project-manager * [git-project-manager docs](git-project-manager_docs.md) - Generate documentation for git-project-manager
* [git-project-manager project](git-project-manager_project.md) - Use a Git project * [git-project-manager project](git-project-manager_project.md) - Use a Git project
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -29,4 +29,4 @@ listing, adding, and deleting.
* [git-project-manager alias delete](git-project-manager_alias_delete.md) - Delete a project alias * [git-project-manager alias delete](git-project-manager_alias_delete.md) - Delete a project alias
* [git-project-manager alias list](git-project-manager_alias_list.md) - List Aliases * [git-project-manager alias list](git-project-manager_alias_list.md) - List Aliases
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -31,4 +31,4 @@ git-project-manager alias add [flags]
* [git-project-manager alias](git-project-manager_alias.md) - Manage project aliases * [git-project-manager alias](git-project-manager_alias.md) - Manage project aliases
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -31,4 +31,4 @@ git-project-manager alias delete [fuzzy project or alias] [flags]
* [git-project-manager alias](git-project-manager_alias.md) - Manage project aliases * [git-project-manager alias](git-project-manager_alias.md) - Manage project aliases
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -29,4 +29,4 @@ git-project-manager alias list [flags]
* [git-project-manager alias](git-project-manager_alias.md) - Manage project aliases * [git-project-manager alias](git-project-manager_alias.md) - Manage project aliases
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -32,4 +32,4 @@ API every time a new project is added / searched for
* [git-project-manager cache load](git-project-manager_cache_load.md) - Load Git Project Cache * [git-project-manager cache load](git-project-manager_cache_load.md) - Load Git Project Cache
* [git-project-manager cache unlock](git-project-manager_cache_unlock.md) - unlock Git project cache * [git-project-manager cache unlock](git-project-manager_cache_unlock.md) - unlock Git project cache
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -33,4 +33,4 @@ git-project-manager cache clear [flags]
* [git-project-manager cache](git-project-manager_cache.md) - Manage Git project cache * [git-project-manager cache](git-project-manager_cache.md) - Manage Git project cache
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -31,4 +31,4 @@ git-project-manager cache dump [flags]
* [git-project-manager cache](git-project-manager_cache.md) - Manage Git project cache * [git-project-manager cache](git-project-manager_cache.md) - Manage Git project cache
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -33,4 +33,4 @@ git-project-manager cache load [flags]
* [git-project-manager cache](git-project-manager_cache.md) - Manage Git project cache * [git-project-manager cache](git-project-manager_cache.md) - Manage Git project cache
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -31,4 +31,4 @@ git-project-manager cache unlock [flags]
* [git-project-manager cache](git-project-manager_cache.md) - Manage Git project cache * [git-project-manager cache](git-project-manager_cache.md) - Manage Git project cache
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -31,4 +31,4 @@ See each sub-command's help for details on how to use the generated script.
* [git-project-manager completion powershell](git-project-manager_completion_powershell.md) - Generate the autocompletion script for powershell * [git-project-manager completion powershell](git-project-manager_completion_powershell.md) - Generate the autocompletion script for powershell
* [git-project-manager completion zsh](git-project-manager_completion_zsh.md) - Generate the autocompletion script for zsh * [git-project-manager completion zsh](git-project-manager_completion_zsh.md) - Generate the autocompletion script for zsh
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -50,4 +50,4 @@ git-project-manager completion bash
* [git-project-manager completion](git-project-manager_completion.md) - Generate the autocompletion script for the specified shell * [git-project-manager completion](git-project-manager_completion.md) - Generate the autocompletion script for the specified shell
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -41,4 +41,4 @@ git-project-manager completion fish [flags]
* [git-project-manager completion](git-project-manager_completion.md) - Generate the autocompletion script for the specified shell * [git-project-manager completion](git-project-manager_completion.md) - Generate the autocompletion script for the specified shell
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -38,4 +38,4 @@ git-project-manager completion powershell [flags]
* [git-project-manager completion](git-project-manager_completion.md) - Generate the autocompletion script for the specified shell * [git-project-manager completion](git-project-manager_completion.md) - Generate the autocompletion script for the specified shell
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -52,4 +52,4 @@ git-project-manager completion zsh [flags]
* [git-project-manager completion](git-project-manager_completion.md) - Generate the autocompletion script for the specified shell * [git-project-manager completion](git-project-manager_completion.md) - Generate the autocompletion script for the specified shell
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -28,4 +28,4 @@ useful for seeding a new config file
* [git-project-manager config generate](git-project-manager_config_generate.md) - Generate a default configuration * [git-project-manager config generate](git-project-manager_config_generate.md) - Generate a default configuration
* [git-project-manager config show](git-project-manager_config_show.md) - Show Git Project Manager Configuration * [git-project-manager config show](git-project-manager_config_show.md) - Show Git Project Manager Configuration
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -32,4 +32,4 @@ git-project-manager config generate [flags]
* [git-project-manager config](git-project-manager_config.md) - Git Project Manager Configuration * [git-project-manager config](git-project-manager_config.md) - Git Project Manager Configuration
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -26,4 +26,4 @@ git-project-manager config show [flags]
* [git-project-manager config](git-project-manager_config.md) - Git Project Manager Configuration * [git-project-manager config](git-project-manager_config.md) - Git Project Manager Configuration
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -26,4 +26,4 @@ git-project-manager docs [flags]
* [git-project-manager](git-project-manager.md) - Find and use Git projects locally * [git-project-manager](git-project-manager.md) - Find and use Git projects locally
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -31,6 +31,8 @@ the project locally.
* [git-project-manager project list](git-project-manager_project_list.md) - List Git Projects * [git-project-manager project list](git-project-manager_project_list.md) - List Git Projects
* [git-project-manager project open](git-project-manager_project_open.md) - Open project in your IDE * [git-project-manager project open](git-project-manager_project_open.md) - Open project in your IDE
* [git-project-manager project run](git-project-manager_project_run.md) - Run the project (e.g. go run .) * [git-project-manager project run](git-project-manager_project_run.md) - Run the project (e.g. go run .)
* [git-project-manager project run](git-project-manager_project_run.md) - Run the project (e.g. go run .)
* [git-project-manager project show](git-project-manager_project_show.md) - Show detail for a Git project
* [git-project-manager project show](git-project-manager_project_show.md) - Show detail for a Git project * [git-project-manager project show](git-project-manager_project_show.md) - Show detail for a Git project
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -30,4 +30,4 @@ git-project-manager project add [flags]
* [git-project-manager project](git-project-manager_project.md) - Use a Git project * [git-project-manager project](git-project-manager_project.md) - Use a Git project
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -33,4 +33,4 @@ git-project-manager project go [fuzzy alias search] [flags]
* [git-project-manager project](git-project-manager_project.md) - Use a Git project * [git-project-manager project](git-project-manager_project.md) - Use a Git project
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -31,4 +31,4 @@ git-project-manager project list [flags]
* [git-project-manager project](git-project-manager_project.md) - Use a Git project * [git-project-manager project](git-project-manager_project.md) - Use a Git project
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -36,4 +36,4 @@ git-project-manager project open [fuzzy alias search] [flags]
* [git-project-manager project](git-project-manager_project.md) - Use a Git project * [git-project-manager project](git-project-manager_project.md) - Use a Git project
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -30,4 +30,4 @@ git-project-manager project run [flags]
* [git-project-manager project](git-project-manager_project.md) - Use a Git project * [git-project-manager project](git-project-manager_project.md) - Use a Git project
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024

View File

@ -31,4 +31,4 @@ git-project-manager project show [fuzzy alias search] [flags]
* [git-project-manager project](git-project-manager_project.md) - Use a Git project * [git-project-manager project](git-project-manager_project.md) - Use a Git project
###### Auto generated by spf13/cobra on 27-Dec-2024 ###### Auto generated by spf13/cobra on 30-Dec-2024