Skip to content

Commit

Permalink
expand tilde in CacheFile (#72)
Browse files Browse the repository at this point in the history
* feat expand tilde in CacheFile

* add unit test

* refactor

* fix CompletionFilePath

---------

Co-authored-by: yokomotod <yokomotod@gmail.com>
  • Loading branch information
paihu and yokomotod authored Dec 21, 2024
1 parent 2bfa226 commit 709697d
Show file tree
Hide file tree
Showing 2 changed files with 74 additions and 0 deletions.
29 changes: 29 additions & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import (
"fmt"
"os"
"path"
"path/filepath"
"strings"

"github.com/mitchellh/go-homedir"
"github.com/rs/zerolog"
Expand Down Expand Up @@ -71,6 +73,20 @@ func initConfig() {
os.Exit(1)
}

realCacheFile, err := realPath(config.CacheFile)
if err != nil {
fmt.Println("Failed to expand Cache File Path:", config.CacheFile)
os.Exit(1)
}
config.CacheFile = realCacheFile

realCompletionFilePath, err := realPath(config.CompletionFilePath)
if err != nil {
fmt.Println("Failed to expand Completion File Path:", config.CompletionFilePath)
os.Exit(1)
}
config.CompletionFilePath = realCompletionFilePath

logOutput() // set log level
}

Expand All @@ -84,6 +100,19 @@ func logOutput() {
}
}

func realPath(filename string) (string, error) {
if !strings.HasPrefix(filename, "~/") {
return filename, nil
}

userDir, err := os.UserHomeDir()
if err != nil {
return "", err
}

return filepath.Join(userDir, filename[2:]), nil
}

func init() {
cobra.OnInitialize(initConfig)
rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.bqiam.toml)")
Expand Down
45 changes: 45 additions & 0 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
package cmd

import (
"os"
"path"
"testing"
)

func TestRealPath(t *testing.T) {
homeDir, err := os.UserHomeDir()
if err != nil {
t.Fatalf("failed to get home directory: %v", err)
}

cases := []struct {
name string
input string
want string
}{
{
name: "tilda",
input: "~/.bqiam-cache-file.toml",
want: path.Join(homeDir, ".bqiam-cache-file.toml"),
},
{
name: "relative",
input: ".bqiam-cache-file.toml",
want: ".bqiam-cache-file.toml",
},
}

for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
got, err := realPath(c.input)

if err != nil {
t.Fatalf("unexpected error: %v", err)
}

if got != c.want {
t.Errorf("got: %s, want: %s", got, c.want)
}
})
}
}

0 comments on commit 709697d

Please sign in to comment.