Skip to content
This repository has been archived by the owner on Aug 6, 2023. It is now read-only.

Commit

Permalink
Extract to detect targets as a option
Browse files Browse the repository at this point in the history
  • Loading branch information
kachick committed Jun 19, 2023
1 parent 07a0503 commit 5397040
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 8 deletions.
32 changes: 24 additions & 8 deletions nix-headbump.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ func main() {
versionFlag := flag.Bool("version", false, "print the version of this program")
currentFlag := flag.Bool("current", false, "print current nixpath without bumping")
lastFlag := flag.Bool("last", false, "print git head ref without bumping")
printTargetFlag := flag.Bool("print-target", false, "detect and print which file will be bumped")
flag.Parse()

if *versionFlag {
Expand All @@ -32,16 +33,16 @@ func main() {
return
}

path := "default.nix"
isNixFileExist := true
if _, err := os.Stat(path); os.IsNotExist(err) {
path = "shell.nix"
if _, err := os.Stat(path); os.IsNotExist(err) {
isNixFileExist = false
}
path, err := getTargetPath()
if err != nil {
log.Fatalf("Failed to get target files: %s", err.Error())
}

if isNixFileExist {
if path != "" {
if *printTargetFlag {
fmt.Println(path)
return
}
if *currentFlag {
current, err := getCurrentVersion(path)
if err != nil {
Expand Down Expand Up @@ -80,6 +81,21 @@ func bump(path string, last string) error {
return os.WriteFile(path, replaced, os.ModePerm)
}

func getTargetPath() (string, error) {
paths := [2]string{"default.nix", "shell.nix"}
for _, path := range paths {
_, err := os.Stat(path)
if err == nil {
return path, nil
}

if !os.IsNotExist(err) {
return "", fmt.Errorf("Can not open %s: %w", path, err)
}
}
return "", fmt.Errorf("%v are not found", paths)
}

func getCurrentVersion(path string) (string, error) {
origin, err := os.ReadFile(path)
if err != nil {
Expand Down
12 changes: 12 additions & 0 deletions nix-headbump_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,3 +26,15 @@ func TestGetLastVersion(t *testing.T) {
t.Errorf("got %q, wanted %q", got, "a string that have 40 length")
}
}

func TestTargetPath(t *testing.T) {
got, err := getTargetPath()
if err != nil {
t.Fatalf("Failed to get target files: %s", err.Error())
}
want := "default.nix"

if got != want {
t.Errorf("got %q, wanted %q", got, want)
}
}

0 comments on commit 5397040

Please sign in to comment.