Add cache maintenance locking

This commit is contained in:
Ryan McGuire 2023-12-10 00:05:39 -05:00
parent 78662b3e09
commit 5d2ca40d04
4 changed files with 36 additions and 4 deletions

View File

@ -1,5 +1,9 @@
# GitLab Project Manager
## TODO
- Fix NPE when cache is reset or project for whatever reason leaves an orphaned alias
## Purpose
The goal of this utility is to provide a fuzzy-find method of locating, cloning,

View File

@ -23,8 +23,7 @@ func runListAliasCmd(cmd *cobra.Command, args []string) {
WithBoxStyle(&pterm.Style{pterm.FgLightBlue}).
WithTitle(pterm.Bold.Sprint(pterm.LightGreen("Aliases by Project"))).
Print("\n" + cache.AliasesByProjectString())
fmt.Println("\n")
// fmt.Print("\n" + cache.AliasesByProjectString() + "\n")
fmt.Print("\n\n")
}
func init() {

View File

@ -14,16 +14,18 @@ var cacheCmd = &cobra.Command{
Use: "cache",
Short: "Manage GitLab project cache",
Long: cacheCmdLong,
PersistentPreRun: initCacheCmd,
PersistentPreRun: runCacheCmd,
PersistentPostRun: postCacheCmd,
}
func initCacheCmd(cmd *cobra.Command, args []string) {
func runCacheCmd(cmd *cobra.Command, args []string) {
initProjectCache(cmd, args)
cache.LockCache()
}
func postCacheCmd(cmd *cobra.Command, args []string) {
postProjectCache(cmd, args)
cache.UnlockCache()
}
func init() {

View File

@ -51,6 +51,33 @@ func (c *Cache) Load() error {
return err
}
func (c *Cache) UnlockCache() {
c.log.Info("Unlocking cache")
if err := os.Remove(c.file + ".lock"); err != nil {
c.log.Fatal("Failed unlocking cache, manual rm may be necessary",
c.log.Args("error", err, "lockFile", c.file+".lock"),
)
}
}
func (c *Cache) LockCache() {
c.log.Info("Attempting to lock cache")
c.checkLock()
file, err := os.OpenFile(c.file+".lock", os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0640)
defer file.Close()
if err != nil {
c.log.Fatal("Failed to lock cache", c.log.Args("error", err))
}
}
func (c *Cache) checkLock() {
if _, err := os.Stat(c.file + ".lock"); err == nil {
c.log.Fatal("Can't manage cache, already locked")
}
}
// Saves the current state of the cache to disk
func (c *Cache) write() {
file, err := os.OpenFile(c.file, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0640)