Skip to content

Commit

Permalink
fix: handling of duplicate directory
Browse files Browse the repository at this point in the history
  • Loading branch information
tukaelu committed Oct 21, 2023
1 parent cbfd71c commit 6585e9e
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 1 deletion.
1 change: 1 addition & 0 deletions cmd/subcommand/cmd_host.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ func (c *hostCommand) run(ctx *cli.Context) error {

metricNames, err := c.client.ListHostMetricNames(c.host)
if err != nil {
fileutil.RemoveDir(exportDir)
return err
}

Expand Down
1 change: 1 addition & 0 deletions cmd/subcommand/cmd_service.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func (c *serviceCommand) run(ctx *cli.Context) error {
}

if len(metricNames) == 0 {
fileutil.RemoveDir(exportDir)
return fmt.Errorf("There was no service metric available for export.")
}

Expand Down
22 changes: 21 additions & 1 deletion internal/fileutil/fileutil.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"os"
"path/filepath"
"time"

"github.com/tukaelu/sabadashi/internal/exporter"
)
Expand All @@ -21,11 +22,30 @@ func CreateExportDir(name, from, to string) (string, error) {
return "", err
}
} else {
return "", fmt.Errorf("Directory '%s' is already exists. Please try again after making a backup", dirPath)
now := time.Now().Format("20060102T150405")
renameTo := filepath.Join(
cwd,
name,
fmt.Sprintf("%s_%s_%s", from, to, now),
)
if err := os.Rename(dirPath, renameTo); err != nil {
return "", fmt.Errorf("Failed to rename an already existing directory. ('%s' to '%s')", dirPath, renameTo)
}
fmt.Printf("Renamed an already existing directory to '%s'.\n", renameTo)

if err := os.MkdirAll(dirPath, 0755); err != nil {
return "", err
}
}
return dirPath, nil
}

func RemoveDir(exportDir string) {
if err := os.Remove(exportDir); err != nil {
fmt.Printf("Failed to delete directory. (path: %s)", exportDir)
}
}

func GetExportFilePath(dir, name, ext string) string {
return filepath.Join(
dir,
Expand Down

0 comments on commit 6585e9e

Please sign in to comment.