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

Commit

Permalink
Divide functions with cmd and core (#14)
Browse files Browse the repository at this point in the history
  • Loading branch information
kachick committed Jul 7, 2023
1 parent e3705c9 commit 49b4514
Show file tree
Hide file tree
Showing 6 changed files with 184 additions and 172 deletions.
5 changes: 3 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,8 @@
# Go workspace file
go.work

# Binary
nix-headbump
# Binary when not used goreleaser
/nix-headbump

# goreleaser generates to
dist/
1 change: 1 addition & 0 deletions .goreleaser.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ before:
builds:
- env:
- CGO_ENABLED=0
main: ./cmd/nix-headbump
goos:
- linux
# - windows
Expand Down
92 changes: 92 additions & 0 deletions cmd/nix-headbump/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package main

import (
"errors"
"flag"
"fmt"
"log"
"os"

nhb "nix-headbump"
)

var (
version = "dev"
commit = "none"
date = "unknown"
)

func main() {
usageError := errors.New("expected 'bump' or 'detect' subcommands")

detectCmd := flag.NewFlagSet("detect", flag.ExitOnError)
bumpCmd := flag.NewFlagSet("bump", flag.ExitOnError)
versionFlag := flag.Bool("version", false, "print the version of this program")
currentFlag := detectCmd.Bool("current", false, "print current nixpath without bumping")
lastFlag := detectCmd.Bool("last", false, "print git head ref without bumping")
target := detectCmd.Bool("target", false, "print which file will be bumped")
flag.Parse()
if *versionFlag {
revision := commit[:7]
fmt.Printf("%s\n", "nix-headbump"+" "+version+" "+"("+revision+") # "+date)
return
}

if len(os.Args) < 2 {
fmt.Println(usageError.Error())
os.Exit(1)
}

path, err := nhb.GetTargetPath()
if err != nil {
log.Fatalf("Failed to get target files: %s", err.Error())
}
if path == "" {
log.Fatalln("Both default.nix and shell.nix are not found")
}

switch os.Args[1] {
case "detect":
err := detectCmd.Parse(os.Args[2:])
if err != nil {
fmt.Println(usageError.Error())
}
if *target {
fmt.Println(path)
return
}
if *currentFlag {
current, err := nhb.GetCurrentVersion(path)
if err != nil {
log.Fatalf("Getting the current version has been failed: %s", err.Error())
}
fmt.Println(current)
return
}
last, err := nhb.GetLastVersion()
if err != nil {
log.Fatalf("Getting the last version has been failed: %s", err.Error())
}
if *lastFlag {
fmt.Println(last)
return
}

detectCmd.PrintDefaults()
case "bump":
err := bumpCmd.Parse(os.Args[2:])
if err != nil {
fmt.Println(usageError.Error())
}
last, err := nhb.GetLastVersion()
if err != nil {
log.Fatalf("Getting the last version has been failed: %s", err.Error())
}
if err = nhb.Bump(path, last); err != nil {
log.Fatalf("Bumping the version has been failed: %s", err.Error())
}
default:
fmt.Println(usageError.Error())
os.Exit(1)
}
}
84 changes: 84 additions & 0 deletions core.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package core

import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"regexp"
)

var (
re = regexp.MustCompile(`(?s)(import\s+\(fetchTarball\s+"https://github.com/NixOS/nixpkgs/archive/)([^"]+?)(\.tar\.gz"\))`)
)

func Bump(path string, last string) error {
origin, err := os.ReadFile(path)
if err != nil {
return err
}
replaced := re.ReplaceAll(origin, []byte("${1}"+last+"${3}"))
if bytes.Equal(origin, replaced) {
return nil
}

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 {
return "", err
}
matches := re.FindStringSubmatch(string(origin))
return matches[2], nil
}

func GetLastVersion() (string, error) {
type commit struct {
Sha string `json:"sha"`
}

type response struct {
Commit commit `json:"commit"`
}

// https://docs.github.com/en/rest/branches/branches?apiVersion=2022-11-28#get-a-branch
req, _ := http.NewRequest("GET", "https://api.github.com/repos/NixOS/nixpkgs/branches/master", nil)
// May be necessary to set "Authorization" header if frequent requests are needed.
// -H "Authorization: Bearer <YOUR-TOKEN>"\
req.Header.Set("Accept", "application/vnd.github+json")
req.Header.Set("X-GitHub-Api-Version", "2022-11-28")
client := new(http.Client)
res, err := client.Do(req)
if err != nil {
return "", err
}
defer res.Body.Close()
body, err := io.ReadAll(res.Body)
if err != nil {
return "", err
}
jsonRes := &response{}
if json.Unmarshal(body, jsonRes) != nil {
return "", err
}
return jsonRes.Commit.Sha, nil
}
8 changes: 4 additions & 4 deletions nix-headbump_test.go → core_test.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
package main
package core

import "testing"

func TestGetCurrentVersion(t *testing.T) {
got, err := getCurrentVersion("default.nix")
got, err := GetCurrentVersion("default.nix")
if err != nil {
t.Fatalf("Getting the version has been failed: %s", err.Error())
}
Expand All @@ -16,7 +16,7 @@ func TestGetCurrentVersion(t *testing.T) {

// Calling actual GitHub API, May be necessary to stub or disabling in CI
func TestGetLastVersion(t *testing.T) {
got, err := getLastVersion()
got, err := GetLastVersion()
if err != nil {
t.Fatalf("Getting the last version has been failed: %s", err.Error())
}
Expand All @@ -28,7 +28,7 @@ func TestGetLastVersion(t *testing.T) {
}

func TestTargetPath(t *testing.T) {
got, err := getTargetPath()
got, err := GetTargetPath()
if err != nil {
t.Fatalf("Failed to get target files: %s", err.Error())
}
Expand Down
166 changes: 0 additions & 166 deletions nix-headbump.go

This file was deleted.

0 comments on commit 49b4514

Please sign in to comment.