From 8608eb4760f0fee2274503bc10a7b4dd6a61722b Mon Sep 17 00:00:00 2001 From: Michael Yang Date: Tue, 26 Sep 2023 17:28:14 -0700 Subject: [PATCH] prune empty directories --- cmd/cmd.go | 9 +++++++++ server/images.go | 33 +++++++++++++++++++++++++++++++++ server/routes.go | 12 ++++++++++++ 3 files changed, 54 insertions(+) diff --git a/cmd/cmd.go b/cmd/cmd.go index ee5b753e..d6b0fb1e 100644 --- a/cmd/cmd.go +++ b/cmd/cmd.go @@ -721,6 +721,15 @@ func RunServer(cmd *cobra.Command, _ []string) error { if err := server.PruneLayers(); err != nil { return err } + + manifestsPath, err := server.GetManifestPath() + if err != nil { + return err + } + + if err := server.PruneDirectory(manifestsPath); err != nil { + return err + } } return server.Serve(ln, origins) diff --git a/server/images.go b/server/images.go index 57e78631..43deed1b 100644 --- a/server/images.go +++ b/server/images.go @@ -1005,6 +1005,39 @@ func PruneLayers() error { return nil } +func PruneDirectory(path string) error { + info, err := os.Lstat(path) + if err != nil { + return err + } + + if info.IsDir() && info.Mode()&os.ModeSymlink == 0 { + entries, err := os.ReadDir(path) + if err != nil { + return err + } + + for _, entry := range entries { + if err := PruneDirectory(filepath.Join(path, entry.Name())); err != nil { + return err + } + } + + entries, err = os.ReadDir(path) + if err != nil { + return err + } + + if len(entries) > 0 { + return nil + } + + return os.Remove(path) + } + + return nil +} + func DeleteModel(name string) error { mp := ParseModelPath(name) manifest, _, err := GetManifest(mp) diff --git a/server/routes.go b/server/routes.go index 62fd806b..5bc06739 100644 --- a/server/routes.go +++ b/server/routes.go @@ -378,6 +378,18 @@ func DeleteModelHandler(c *gin.Context) { } return } + + manifestsPath, err := GetManifestPath() + if err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + + if err := PruneDirectory(manifestsPath); err != nil { + c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()}) + return + } + c.JSON(http.StatusOK, nil) }