Package subcommand code
This commit is contained in:
		
							
								
								
									
										121
									
								
								cmd/util/util.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										121
									
								
								cmd/util/util.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,121 @@
 | 
			
		||||
// Common utilities used by various subcommands
 | 
			
		||||
package util
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
	"errors"
 | 
			
		||||
	"sync"
 | 
			
		||||
 | 
			
		||||
	"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/cache"
 | 
			
		||||
	"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/config"
 | 
			
		||||
	"github.com/pterm/pterm"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type Utils struct {
 | 
			
		||||
	ctx    context.Context
 | 
			
		||||
	config *config.Config
 | 
			
		||||
	logger *pterm.Logger
 | 
			
		||||
	cache  *cache.Cache
 | 
			
		||||
	sync.RWMutex
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type UtilOpts struct {
 | 
			
		||||
	Ctx    context.Context
 | 
			
		||||
	Config *config.Config
 | 
			
		||||
	Logger *pterm.Logger
 | 
			
		||||
	Cache  *cache.Cache
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
type utilsCtxKey uint8
 | 
			
		||||
 | 
			
		||||
const UtilsKey utilsCtxKey = iota
 | 
			
		||||
 | 
			
		||||
func AddToCtx(ctx context.Context, u *Utils) context.Context {
 | 
			
		||||
	return context.WithValue(ctx, UtilsKey, u)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func MustFromCtx(ctx context.Context) *Utils {
 | 
			
		||||
	utils, err := FromCtx(ctx)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		panic(err)
 | 
			
		||||
	}
 | 
			
		||||
	return utils
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func FromCtx(ctx context.Context) (*Utils, error) {
 | 
			
		||||
	utils, avail := ctx.Value(UtilsKey).(*Utils)
 | 
			
		||||
	if !avail {
 | 
			
		||||
		return nil, errors.New("invalid util in context")
 | 
			
		||||
	} else if utils == nil {
 | 
			
		||||
		return nil, errors.New("util never set in context")
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return utils, nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) Init(opts *UtilOpts) {
 | 
			
		||||
	u.ctx = opts.Ctx
 | 
			
		||||
	u.SetConfig(opts.Config)
 | 
			
		||||
	u.SetLogger(opts.Logger)
 | 
			
		||||
	u.SetCache(opts.Cache)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) SetCache(c *cache.Cache) {
 | 
			
		||||
	if c == nil {
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	u.Lock()
 | 
			
		||||
	defer u.Unlock()
 | 
			
		||||
	u.cache = c
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) Cache() *cache.Cache {
 | 
			
		||||
	u.RLock()
 | 
			
		||||
	defer u.RUnlock()
 | 
			
		||||
	return u.cache
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) SetLogger(l *pterm.Logger) {
 | 
			
		||||
	if l == nil {
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	u.Lock()
 | 
			
		||||
	defer u.Unlock()
 | 
			
		||||
	u.logger = l
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) Logger() *pterm.Logger {
 | 
			
		||||
	u.RLock()
 | 
			
		||||
	defer u.RUnlock()
 | 
			
		||||
	return u.logger
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) SetConfig(conf *config.Config) {
 | 
			
		||||
	if conf == nil {
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	u.Lock()
 | 
			
		||||
	defer u.Unlock()
 | 
			
		||||
	u.config = conf
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) Config() *config.Config {
 | 
			
		||||
	u.RLock()
 | 
			
		||||
	defer u.RUnlock()
 | 
			
		||||
	return u.config
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) SetContext(c context.Context) {
 | 
			
		||||
	u.Lock()
 | 
			
		||||
	defer u.Unlock()
 | 
			
		||||
	u.ctx = c
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) Context() context.Context {
 | 
			
		||||
	u.RLock()
 | 
			
		||||
	defer u.RUnlock()
 | 
			
		||||
	return u.ctx
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										71
									
								
								cmd/util/util_completion.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										71
									
								
								cmd/util/util_completion.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,71 @@
 | 
			
		||||
package util
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"strconv"
 | 
			
		||||
	"strings"
 | 
			
		||||
 | 
			
		||||
	"github.com/spf13/cobra"
 | 
			
		||||
	"golang.org/x/exp/slices"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func (u *Utils) ValidProjectsFunc(cmd *cobra.Command, args []string, toComplete string) (
 | 
			
		||||
	[]string, cobra.ShellCompDirective,
 | 
			
		||||
) {
 | 
			
		||||
	u.InitProjectCache(cmd, args)
 | 
			
		||||
	return u.Cache().ProjectStrings(toComplete), cobra.ShellCompDirectiveNoFileComp
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) ValidAliasesFunc(cmd *cobra.Command, args []string, toComplete string) (
 | 
			
		||||
	[]string, cobra.ShellCompDirective,
 | 
			
		||||
) {
 | 
			
		||||
	u.InitProjectCache(cmd, args)
 | 
			
		||||
	return u.Cache().AliasStrings(toComplete), cobra.ShellCompDirectiveNoFileComp
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) ValidProjectsOrAliasesFunc(cmd *cobra.Command, args []string, toComplete string) (
 | 
			
		||||
	[]string, cobra.ShellCompDirective,
 | 
			
		||||
) {
 | 
			
		||||
	projectStrings, _ := u.ValidAliasesFunc(cmd, args, toComplete)
 | 
			
		||||
	aliasStrings, _ := u.ValidProjectsFunc(cmd, args, toComplete)
 | 
			
		||||
	return append(projectStrings, aliasStrings...), cobra.ShellCompDirectiveDefault
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) ValidRemotesFunc(_ *cobra.Command, _ []string, toComplete string) (
 | 
			
		||||
	[]string, cobra.ShellCompDirective,
 | 
			
		||||
) {
 | 
			
		||||
	remotes := make([]string, 0, len(u.Config().Remotes))
 | 
			
		||||
	for _, remote := range u.Config().Remotes {
 | 
			
		||||
		if strings.HasPrefix(remote.Host, toComplete) {
 | 
			
		||||
			remotes = append(remotes, remote.Host)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	return remotes, cobra.ShellCompDirectiveNoFileComp
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func ValidLogLevelsFunc(_ *cobra.Command, _ []string, toComplete string) (
 | 
			
		||||
	[]string, cobra.ShellCompDirective,
 | 
			
		||||
) {
 | 
			
		||||
	levels := []string{"info", "warn", "error", "debug"}
 | 
			
		||||
	matchingLevels := make([]string, 0, len(levels))
 | 
			
		||||
	for _, level := range levels {
 | 
			
		||||
		if strings.HasPrefix(level, toComplete) {
 | 
			
		||||
			matchingLevels = append(matchingLevels, level)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	return matchingLevels, cobra.ShellCompDirectiveNoFileComp
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func ValidProjectIdFunc(cmd *cobra.Command, args []string, toComplete string) (
 | 
			
		||||
	[]string, cobra.ShellCompDirective,
 | 
			
		||||
) {
 | 
			
		||||
	u := MustFromCtx(cmd.Context())
 | 
			
		||||
	u.InitProjectCache(cmd, args)
 | 
			
		||||
	matchingIds := make([]string, 0, len(u.Cache().Projects))
 | 
			
		||||
	for _, p := range u.Cache().Projects {
 | 
			
		||||
		idString := strconv.FormatInt(int64(p.ID), 10)
 | 
			
		||||
		if strings.HasPrefix(idString, toComplete) {
 | 
			
		||||
			matchingIds = append(matchingIds, idString)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	return slices.Clip(matchingIds), cobra.ShellCompDirectiveNoFileComp
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										86
									
								
								cmd/util/util_constants.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										86
									
								
								cmd/util/util_constants.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,86 @@
 | 
			
		||||
package util
 | 
			
		||||
 | 
			
		||||
const (
 | 
			
		||||
	// Cobra Flags
 | 
			
		||||
	FlagRemote     = "remote"
 | 
			
		||||
	FlagConfig     = "config"
 | 
			
		||||
	FlagPath       = "projectPath"
 | 
			
		||||
	FlagLogLevel   = "logLevel"
 | 
			
		||||
	FlagProjectID  = "projectID"
 | 
			
		||||
	FlagCacheForce = "force"
 | 
			
		||||
	FlagOwnerOnly  = "ownerOnly"
 | 
			
		||||
	FlagAll        = "all"
 | 
			
		||||
	FlagCurrent    = "current"
 | 
			
		||||
	FlagPrompt     = "prompt"
 | 
			
		||||
	FlagWrite      = "write"
 | 
			
		||||
	FlagSensitive  = "sensitive"
 | 
			
		||||
	FlagDocsPath   = "docsPath"
 | 
			
		||||
 | 
			
		||||
	// Viper config bindings
 | 
			
		||||
	ViperAliasAddPID        = "alias.add.projectID"
 | 
			
		||||
	ViperCacheUnlockForce   = "cache.unlock.force"
 | 
			
		||||
	ViperCacheLoadOwnerOnly = "cache.load.ownerOnly"
 | 
			
		||||
	ViperProjectListAll     = "project.list.all"
 | 
			
		||||
	ViperProjectShowCurrent = "project.show.current"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
const (
 | 
			
		||||
	DefGitlabHost    = "https://gitlab.com"
 | 
			
		||||
	DefLogLevel      = "info"
 | 
			
		||||
	DefConfigPath    = "~/.config/git-project-manager.yaml"
 | 
			
		||||
	ConfigName       = "git-project-manager"
 | 
			
		||||
	LegacyConfigName = "gitlab-project-manager"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
const AliasCmdLong = `Manages project aliases, with options for
 | 
			
		||||
listing, adding, and deleting.`
 | 
			
		||||
 | 
			
		||||
const AliasListCmdLong = `Lists all aliases by project`
 | 
			
		||||
 | 
			
		||||
const AliasAddCmdLong = `Adds a project alias to a project
 | 
			
		||||
project ID can be provided, or will otherwise use fuzzy find`
 | 
			
		||||
 | 
			
		||||
const AliasDeleteCmdLong = `Deletes aliases from projects
 | 
			
		||||
project ID can be provided, or will otherwise use fuzzy find`
 | 
			
		||||
 | 
			
		||||
const CacheCmdLong = `Contains sub-commands for managing project cache.
 | 
			
		||||
The project cache keeps this speedy, without smashing against the Git
 | 
			
		||||
API every time a new project is added / searched for`
 | 
			
		||||
 | 
			
		||||
const RootCmdLong = `Finds Git projects using fuzzy-find, remembering
 | 
			
		||||
your chosen term for the project as an alias, and offers helpful
 | 
			
		||||
shortcuts for moving around in projects and opening your code`
 | 
			
		||||
 | 
			
		||||
const ProjCmdLong = `Switches to a Git project by name or alias
 | 
			
		||||
If not found, will enter fzf mode. If not cloned, will clone
 | 
			
		||||
the project locally.`
 | 
			
		||||
 | 
			
		||||
const ProjGoCmdLong = `Go to a project, searching by alias
 | 
			
		||||
If project is not already cloned, its path will be built and it
 | 
			
		||||
will be cloned from source control.
 | 
			
		||||
 | 
			
		||||
If conf.projects.alwaysPull, a git pull will be ran automatically`
 | 
			
		||||
 | 
			
		||||
const ProjRunCmdLong = `Runs the current project. Tries to detect
 | 
			
		||||
the language and runs accordingly (e.g. go run .)`
 | 
			
		||||
 | 
			
		||||
const ProjListCmdLong = `List locally cloned projects. Optionally
 | 
			
		||||
lists all projects in project cache`
 | 
			
		||||
 | 
			
		||||
const ProjAddCmdLong = `Adds a new project to the local project path
 | 
			
		||||
uses fuzzy find to locate the project`
 | 
			
		||||
 | 
			
		||||
const ProjShowCmdLong = `Shows detail for a particular project
 | 
			
		||||
Will always fuzzy find`
 | 
			
		||||
 | 
			
		||||
const ProjOpenCmdLong = `Opens the given project directory in the editor
 | 
			
		||||
of your choice. Will find certain well-known entrypoints (e.g. main.go).
 | 
			
		||||
 | 
			
		||||
If your editor is set in your config file, it will be used, otherwise
 | 
			
		||||
one will be found in your path from a list of known defaults.`
 | 
			
		||||
 | 
			
		||||
const ConfigCmdLong = `Commands for managing configuration, particulary
 | 
			
		||||
useful for seeding a new config file`
 | 
			
		||||
 | 
			
		||||
const ConfigGenCmdLong = `Produces yaml to stdout that can be used
 | 
			
		||||
to seed the configuration file`
 | 
			
		||||
							
								
								
									
										186
									
								
								cmd/util/util_fzf.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										186
									
								
								cmd/util/util_fzf.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,186 @@
 | 
			
		||||
package util
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"context"
 | 
			
		||||
 | 
			
		||||
	fzf "github.com/ktr0731/go-fuzzyfinder"
 | 
			
		||||
	"golang.org/x/exp/slices"
 | 
			
		||||
 | 
			
		||||
	"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/cache"
 | 
			
		||||
	"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/projects"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
type FzfProjectOpts struct {
 | 
			
		||||
	Ctx           context.Context
 | 
			
		||||
	Search        string
 | 
			
		||||
	MustHaveAlias bool
 | 
			
		||||
	Remotes       []string
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// This will try to find a project by alias if a search term
 | 
			
		||||
// is given, otherwise will fuzzy find by project
 | 
			
		||||
func (u *Utils) FzfFindProject(opts *FzfProjectOpts) *projects.Project {
 | 
			
		||||
	var project *projects.Project
 | 
			
		||||
 | 
			
		||||
	if opts.Search != "" {
 | 
			
		||||
		project = u.FzfSearchProjectAliases(opts)
 | 
			
		||||
	} else {
 | 
			
		||||
		var err error
 | 
			
		||||
		project, err = u.FzfProject(opts)
 | 
			
		||||
		if project == nil || err != nil {
 | 
			
		||||
			return nil
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return project
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// If . is given as a project, will open project from the
 | 
			
		||||
// current working directory. Otherwise, will attempt to fuzzy-find
 | 
			
		||||
// a project given a search term if provided
 | 
			
		||||
func (u *Utils) FzfCwdOrSearchProjectAliases(opts *FzfProjectOpts) *projects.Project {
 | 
			
		||||
	var project *projects.Project
 | 
			
		||||
	if opts.Search == "." {
 | 
			
		||||
		project, _ = u.Cache().GetProjectFromCwd()
 | 
			
		||||
	} else {
 | 
			
		||||
		project = u.FzfSearchProjectAliases(opts)
 | 
			
		||||
	}
 | 
			
		||||
	return project
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// This will fuzzy search only aliases, preferring an exact
 | 
			
		||||
// match if one is given
 | 
			
		||||
func (u *Utils) FzfSearchProjectAliases(opts *FzfProjectOpts) *projects.Project {
 | 
			
		||||
	var project *projects.Project
 | 
			
		||||
	var alias *cache.ProjectAlias
 | 
			
		||||
	if alias = u.Cache().GetAliasByName(opts.Search, opts.Remotes...); alias != nil {
 | 
			
		||||
		project = u.Cache().GetProjectByAlias(alias)
 | 
			
		||||
		u.Logger().Info("Perfect alias match... flawless")
 | 
			
		||||
	} else {
 | 
			
		||||
		// Get fuzzy if we don't have an exact match
 | 
			
		||||
		aliases := u.Cache().FuzzyFindAlias(opts.Search)
 | 
			
		||||
		if len(aliases) > 1 {
 | 
			
		||||
			// If multiple aliases were found, switch over to project
 | 
			
		||||
			// by alias mode with merging
 | 
			
		||||
			// alias = fzfAliasFromAliases(rootCmd.Context(), aliases)
 | 
			
		||||
			project, _ = u.FzfProjectFromAliases(opts, aliases)
 | 
			
		||||
		} else if len(aliases) == 1 {
 | 
			
		||||
			alias = aliases[0]
 | 
			
		||||
			project = u.Cache().GetProjectByAlias(alias)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	return project
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Given a list of aliases, will fuzzy-find and return
 | 
			
		||||
// a single one. Replaced by fzfProjectFromAliases in fzfSearchProjectAliases
 | 
			
		||||
// as merging is preferred, but can be used if it's ever desirable to
 | 
			
		||||
// return a single alias from all aliases
 | 
			
		||||
func (u *Utils) FzfAliasFromAliases(opts *FzfProjectOpts, aliases []*cache.ProjectAlias) *cache.ProjectAlias {
 | 
			
		||||
	var alias *cache.ProjectAlias
 | 
			
		||||
	i, err := fzf.Find(
 | 
			
		||||
		aliases,
 | 
			
		||||
		func(i int) string {
 | 
			
		||||
			return aliases[i].Alias + " -> " + u.Cache().GetProjectByAlias(aliases[i]).PathWithNamespace
 | 
			
		||||
		},
 | 
			
		||||
		fzf.WithContext(opts.Ctx),
 | 
			
		||||
		fzf.WithHeader("Choose an Alias"),
 | 
			
		||||
	)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		u.Logger().Error("Failed to fzf alias slice", u.Logger().Args("error", err))
 | 
			
		||||
	} else {
 | 
			
		||||
		alias = aliases[i]
 | 
			
		||||
	}
 | 
			
		||||
	return alias
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Given a list of aliases, merge them together and use the resulting
 | 
			
		||||
// list of projects to return a project
 | 
			
		||||
func (u *Utils) FzfProjectFromAliases(opts *FzfProjectOpts, aliases []*cache.ProjectAlias) (
 | 
			
		||||
	*projects.Project, error,
 | 
			
		||||
) {
 | 
			
		||||
	mergedProjects := u.projectsFromAliases(aliases)
 | 
			
		||||
	if len(mergedProjects) == 1 {
 | 
			
		||||
		return mergedProjects[0], nil
 | 
			
		||||
	}
 | 
			
		||||
	return u.FzfProjectFromProjects(opts, mergedProjects)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) projectsFromAliases(aliases []*cache.ProjectAlias) []*projects.Project {
 | 
			
		||||
	projects := make([]*projects.Project, 0, len(aliases))
 | 
			
		||||
 | 
			
		||||
	for _, a := range aliases {
 | 
			
		||||
		project := u.Cache().GetProjectByAlias(a)
 | 
			
		||||
		if project != nil && !slices.Contains(projects, project) {
 | 
			
		||||
			projects = append(projects, project)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	return slices.Clip(projects)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// If opts.MustHaveAlias, will only allow selection of projects
 | 
			
		||||
// that have at least one alias defined
 | 
			
		||||
func (u *Utils) FzfProject(opts *FzfProjectOpts) (*projects.Project, error) {
 | 
			
		||||
	var searchableProjects []*projects.Project
 | 
			
		||||
	if opts.MustHaveAlias {
 | 
			
		||||
		searchableProjects = u.Cache().GetProjectsWithAliases()
 | 
			
		||||
	} else {
 | 
			
		||||
		searchableProjects = u.Cache().Projects
 | 
			
		||||
	}
 | 
			
		||||
	// Filter out unwanted remotes if provided
 | 
			
		||||
	searchableProjects = u.FilterProjectsWithRemotes(searchableProjects, opts.Remotes...)
 | 
			
		||||
	return u.FzfProjectFromProjects(opts, searchableProjects)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Takes a list of projects and performs a fuzzyfind
 | 
			
		||||
func (u *Utils) FzfProjectFromProjects(opts *FzfProjectOpts, projects []*projects.Project) (
 | 
			
		||||
	*projects.Project, error,
 | 
			
		||||
) {
 | 
			
		||||
	i, err := fzf.Find(projects,
 | 
			
		||||
		func(i int) string {
 | 
			
		||||
			// Display the project along with its aliases
 | 
			
		||||
			return u.Cache().GetProjectStringWithAliases(projects[i])
 | 
			
		||||
		},
 | 
			
		||||
		fzf.WithPreviewWindow(
 | 
			
		||||
			func(i, width, height int) string {
 | 
			
		||||
				return u.Cache().ProjectString(projects[i])
 | 
			
		||||
			},
 | 
			
		||||
		),
 | 
			
		||||
		fzf.WithContext(opts.Ctx),
 | 
			
		||||
		fzf.WithHeader("Fuzzy find yourself a project"),
 | 
			
		||||
	)
 | 
			
		||||
	if err != nil || i < 0 {
 | 
			
		||||
		return nil, err
 | 
			
		||||
	}
 | 
			
		||||
	return projects[i], nil
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) FzfPreviewWindow(i, _, _ int) string {
 | 
			
		||||
	p := u.Cache().Projects[i]
 | 
			
		||||
	return u.Cache().ProjectString(p)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) FilterProjectsWithRemotes(gitProjects []*projects.Project, remotes ...string) []*projects.Project {
 | 
			
		||||
	filteredProjects := make([]*projects.Project, 0, len(gitProjects))
 | 
			
		||||
	if len(remotes) > 0 {
 | 
			
		||||
		for _, p := range gitProjects {
 | 
			
		||||
			if slices.Contains(remotes, p.Remote) {
 | 
			
		||||
				filteredProjects = append(filteredProjects, p)
 | 
			
		||||
			}
 | 
			
		||||
		}
 | 
			
		||||
	} else {
 | 
			
		||||
		filteredProjects = gitProjects
 | 
			
		||||
	}
 | 
			
		||||
	return filteredProjects
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Nearly useless function that simply returns either an
 | 
			
		||||
// empty string, or a string from the first arg if one is provided
 | 
			
		||||
func (u *Utils) SearchStringFromArgs(args []string) string {
 | 
			
		||||
	var term string
 | 
			
		||||
	if len(args) > 0 {
 | 
			
		||||
		term = args[0]
 | 
			
		||||
	}
 | 
			
		||||
	return term
 | 
			
		||||
}
 | 
			
		||||
							
								
								
									
										163
									
								
								cmd/util/util_init.go
									
									
									
									
									
										Normal file
									
								
							
							
						
						
									
										163
									
								
								cmd/util/util_init.go
									
									
									
									
									
										Normal file
									
								
							@@ -0,0 +1,163 @@
 | 
			
		||||
// This file contains init methods that may be used by
 | 
			
		||||
// multiple sub-commands. For instance, the cach and projects
 | 
			
		||||
// sub-commands both depend on a cache and may both call the initProjectCache
 | 
			
		||||
// func (u *Util) from their PersistentPreRun commands
 | 
			
		||||
package util
 | 
			
		||||
 | 
			
		||||
import (
 | 
			
		||||
	"fmt"
 | 
			
		||||
	"os"
 | 
			
		||||
	"os/user"
 | 
			
		||||
	"path/filepath"
 | 
			
		||||
	"strings"
 | 
			
		||||
 | 
			
		||||
	"github.com/pterm/pterm"
 | 
			
		||||
	"github.com/spf13/cobra"
 | 
			
		||||
	"golang.org/x/sys/unix"
 | 
			
		||||
 | 
			
		||||
	"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/cache"
 | 
			
		||||
	"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/config"
 | 
			
		||||
	"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes"
 | 
			
		||||
	gitearemote "gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/gitea"
 | 
			
		||||
	githubremote "gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/github"
 | 
			
		||||
	gitlabremote "gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/gitlab"
 | 
			
		||||
	"gitea.libretechconsulting.com/rmcguire/git-project-manager/internal/remotes/remote"
 | 
			
		||||
)
 | 
			
		||||
 | 
			
		||||
func InitProjects(cmd *cobra.Command, args []string) {
 | 
			
		||||
	utils, _ := FromCtx(cmd.Context())
 | 
			
		||||
	utils.InitProjectCache(cmd, args)
 | 
			
		||||
	utils.mustHaveProjects(cmd, args)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) mustHaveProjects(cmd *cobra.Command, _ []string) {
 | 
			
		||||
	if len(u.Cache().Projects) == 0 {
 | 
			
		||||
		u.Logger().Fatal("No projects to " + cmd.Name() + ", try running cache load")
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) InitProjectCache(cmd *cobra.Command, _ []string) {
 | 
			
		||||
	var err error
 | 
			
		||||
	u.Logger().Debug("Running pre-run for cacheCmd")
 | 
			
		||||
	u.Config().Cache.File = u.Config().ProjectPath + "/.cache.yaml"
 | 
			
		||||
 | 
			
		||||
	gitRemotes := remotes.NewRemotes()
 | 
			
		||||
	gitRemotes.AddRemotes(*u.GetRemotes(cmd)...)
 | 
			
		||||
 | 
			
		||||
	cacheOpts := &cache.CacheOpts{
 | 
			
		||||
		ProjectsPath: u.Config().ProjectPath,
 | 
			
		||||
		Path:         u.Config().Cache.File,
 | 
			
		||||
		TTL:          u.Config().Cache.Ttl,
 | 
			
		||||
		Logger:       u.Logger(),
 | 
			
		||||
		Remotes:      gitRemotes,
 | 
			
		||||
		Config:       u.Config(),
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	projectCache, err := cache.NewProjectCache(cacheOpts)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		u.Logger().Error("Failed to prepare project cache", u.Logger().Args("error", err))
 | 
			
		||||
		os.Exit(1)
 | 
			
		||||
	}
 | 
			
		||||
	u.SetCache(projectCache)
 | 
			
		||||
 | 
			
		||||
	if err := u.Cache().Read(); err != nil {
 | 
			
		||||
		u.Logger().Error("Cache load failed", u.Logger().Args("error", err))
 | 
			
		||||
		os.Exit(1)
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	u.Logger().Debug("Remotes Loaded", u.Logger().Args("remotes", cacheOpts.Remotes))
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
// Generically loads remotes from info.RemoteInfo in config.Remotes
 | 
			
		||||
func (u *Utils) GetRemotes(cmd *cobra.Command) *remotes.Remotes {
 | 
			
		||||
	gitRemotes := new(remotes.Remotes)
 | 
			
		||||
	*gitRemotes = make([]remote.Remote, 0)
 | 
			
		||||
	for _, r := range u.Config().Remotes {
 | 
			
		||||
		// Create a copy, set context
 | 
			
		||||
		gitRemoteInfo := r
 | 
			
		||||
		gitRemoteInfo.SetContext(cmd.Context())
 | 
			
		||||
		var gitRemote remote.Remote
 | 
			
		||||
		var err error
 | 
			
		||||
		switch r.Type {
 | 
			
		||||
		case "gitlab":
 | 
			
		||||
			gitRemote, err = gitlabremote.NewGitlabRemote(&gitRemoteInfo)
 | 
			
		||||
		case "gitea":
 | 
			
		||||
			gitRemote, err = gitearemote.NewGiteaRemote(&gitRemoteInfo)
 | 
			
		||||
		case "github":
 | 
			
		||||
			gitRemote, err = githubremote.NewGithubRemote(&gitRemoteInfo)
 | 
			
		||||
		}
 | 
			
		||||
		if err != nil {
 | 
			
		||||
			u.Logger().Error("Failed to prepare remote", u.Logger().Args(
 | 
			
		||||
				"error", err,
 | 
			
		||||
				"type", r.Type))
 | 
			
		||||
		} else {
 | 
			
		||||
			*gitRemotes = append(*gitRemotes, gitRemote)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
	return gitRemotes
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func PostProjectCmd(cmd *cobra.Command, args []string) {
 | 
			
		||||
	utils, _ := FromCtx(cmd.Context())
 | 
			
		||||
	utils.PostProjectCache(cmd, args)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) PostProjectCache(_ *cobra.Command, _ []string) {
 | 
			
		||||
	u.Cache().Write()
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func (u *Utils) InitProjectPath(_ *cobra.Command, _ []string) {
 | 
			
		||||
	u.Logger().Debug("Running persistent pre-run for rootCmd")
 | 
			
		||||
	var err error
 | 
			
		||||
	if u.Config().ProjectPath == "" {
 | 
			
		||||
		u.Config().ProjectPath = config.DefaultConfig.ProjectPath
 | 
			
		||||
		return
 | 
			
		||||
	}
 | 
			
		||||
	if u.Config().ProjectPath, err = ResolvePath(u.Config().ProjectPath); err != nil {
 | 
			
		||||
		u.Logger().Error("Failed to determine project path", u.Logger().Args("error", err))
 | 
			
		||||
		os.Exit(1)
 | 
			
		||||
	}
 | 
			
		||||
	_, err = os.Stat(u.Config().ProjectPath)
 | 
			
		||||
	if err != nil {
 | 
			
		||||
		u.Logger().Error("Failed to stat project path, trying to create", u.Logger().Args("error", err))
 | 
			
		||||
		if err = os.MkdirAll(u.Config().ProjectPath, 0o750); err != nil {
 | 
			
		||||
			u.Logger().Error("Failed to create project path", u.Logger().Args("error", err))
 | 
			
		||||
			os.Exit(1)
 | 
			
		||||
		}
 | 
			
		||||
		u.Logger().Info("Project path created", u.Logger().Args("path", u.Config().ProjectPath))
 | 
			
		||||
	} else {
 | 
			
		||||
		if err = unix.Access(u.Config().ProjectPath, unix.W_OK); err != nil {
 | 
			
		||||
			u.Logger().Error("Unable to write to project path", u.Logger().Args(
 | 
			
		||||
				"path", u.Config().ProjectPath,
 | 
			
		||||
				"error", err))
 | 
			
		||||
			os.Exit(1)
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func ResolvePath(path string) (string, error) {
 | 
			
		||||
	if strings.HasPrefix(path, "~/") {
 | 
			
		||||
		usr, _ := user.Current()
 | 
			
		||||
		path = filepath.Join(usr.HomeDir, path[2:])
 | 
			
		||||
	}
 | 
			
		||||
	return filepath.Abs(path)
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
func GetConfigName(configPath string) string {
 | 
			
		||||
	// Check existing config
 | 
			
		||||
	for _, ext := range []string{"yml", "yaml"} {
 | 
			
		||||
		configFile := fmt.Sprintf("%s/%s.%s", configPath, ConfigName, ext)
 | 
			
		||||
		legacyConfigFile := fmt.Sprintf("%s/%s.%s", configPath, LegacyConfigName, ext)
 | 
			
		||||
 | 
			
		||||
		if _, err := os.Stat(configFile); err == nil {
 | 
			
		||||
			return ConfigName
 | 
			
		||||
		} else if _, err := os.Stat(legacyConfigFile); err == nil {
 | 
			
		||||
			pterm.DefaultLogger.WithWriter(os.Stderr).
 | 
			
		||||
				Warn(fmt.Sprintf("using legacy config path, suggest using %s/%s.yaml", configPath, ConfigName))
 | 
			
		||||
			return LegacyConfigName
 | 
			
		||||
		}
 | 
			
		||||
	}
 | 
			
		||||
 | 
			
		||||
	// Nothing found, do what we want
 | 
			
		||||
	return ConfigName
 | 
			
		||||
}
 | 
			
		||||
		Reference in New Issue
	
	Block a user