Skip to content

Commit

Permalink
Automatically determine next adr number based on folder content
Browse files Browse the repository at this point in the history
  • Loading branch information
f-ewald committed May 20, 2022
1 parent f111d2a commit 080cf46
Show file tree
Hide file tree
Showing 3 changed files with 38 additions and 5 deletions.
1 change: 0 additions & 1 deletion commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ func setCommands(app *cli.App) {
Flags: []cli.Flag{},
Action: func(c *cli.Context) error {
currentConfig := getConfig()
currentConfig.CurrentAdr++
updateConfig(currentConfig)
newAdr(currentConfig, c.Args())
return nil
Expand Down
32 changes: 28 additions & 4 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import (
"os"
"os/user"
"path/filepath"
"regexp"
"strconv"
"strings"
"time"
Expand All @@ -17,8 +18,7 @@ import (

// AdrConfig ADR configuration, loaded and used by each sub-command
type AdrConfig struct {
BaseDir string `json:"base_directory"`
CurrentAdr int `json:"current_id"`
BaseDir string `json:"base_directory"`
}

// Adr basic structure
Expand Down Expand Up @@ -67,7 +67,7 @@ func initConfig(baseDir string) {
panic(err)
}
}
config := AdrConfig{baseDir, 0}
config := AdrConfig{BaseDir: baseDir}
bytes, err := json.MarshalIndent(config, "", " ")
if err != nil {
panic(err)
Expand Down Expand Up @@ -122,7 +122,7 @@ func newAdr(config AdrConfig, adrName []string) {
adr := Adr{
Title: strings.Join(adrName, " "),
Date: time.Now().UTC(),
Number: config.CurrentAdr,
Number: findLastNumber(config) + 1,
Status: PROPOSED,
}
tpl, err := template.ParseFiles(adrTemplateFilePath)
Expand All @@ -142,3 +142,27 @@ func newAdr(config AdrConfig, adrName []string) {
_ = f.Close()
color.Green("ADR number " + strconv.Itoa(adr.Number) + " was successfully written to : " + adrFullPath)
}

// findLastNumber returns the highest number that is found in a directory.
// If the directory is empty, 0 is returned.
func findLastNumber(config AdrConfig) int {
var max int
contents, err := os.ReadDir(config.BaseDir)
if err != nil {
panic(err)
}
regex := regexp.MustCompile(`(\d{5,}).*`)
for _, c := range contents {
m := regex.FindSubmatch([]byte(c.Name()))
if m != nil {
n, err := strconv.Atoi(string(m[1]))
if err != nil {
panic(err)
}
if n >= max {
max = n
}
}
}
return max
}
10 changes: 10 additions & 0 deletions helpers_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package main

import "testing"

func TestFindLastNumber(t *testing.T) {
t.Parallel()
cfg := getConfig()
n := findLastNumber(cfg)
_ = n
}

0 comments on commit 080cf46

Please sign in to comment.