git-project-manager/cmd/init.go

77 lines
2.0 KiB
Go

package cmd
import (
"os"
"os/user"
"path/filepath"
"strings"
"github.com/spf13/cobra"
"gitlab.sweetwater.com/it/devops/tools/gitlab-project-manager/internal/projects"
"golang.org/x/exp/slog"
"golang.org/x/sys/unix"
)
// 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 from their PersistentPreRun commands
func initProjectCache(cmd *cobra.Command, args []string) {
slog.Debug("Running persistent pre-run for cacheCmd")
conf.Cache.File = conf.ProjectPath + "/.cache.json"
var err error
cacheOpts := &projects.CacheOpts{
Path: conf.Cache.File,
TTL: conf.Cache.Ttl,
Logger: slog.Default(),
}
if cache, err = projects.NewProjectCache(cacheOpts); err != nil {
slog.Error("Failed to prepare project cache", "error", err)
os.Exit(1)
}
if err := cache.Load(); err != nil {
slog.Error("Cache load failed", "error", err)
os.Exit(1)
}
}
func postProjectCache(cmd *cobra.Command, args []string) {
cache.Write()
}
func initProjectPath(cmd *cobra.Command, args []string) {
slog.Debug("Running persistent pre-run for rootCmd")
var err error
if conf.ProjectPath, err = resolvePath(conf.ProjectPath); err != nil {
slog.Error("Failed to determine project path", "error", err)
os.Exit(1)
}
_, err = os.Stat(conf.ProjectPath)
if err != nil {
slog.Error("Failed to stat project path, trying to create", "error", err)
if err := os.Mkdir(conf.ProjectPath, 0750); err != nil {
slog.Error("Failed to create project path", "error", err)
os.Exit(1)
}
slog.Info("Project path created", "path", conf.ProjectPath)
} else {
if err = unix.Access(conf.ProjectPath, unix.W_OK); err != nil {
slog.Error("Unable to write to project path",
"path", conf.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)
}