Skip to content

Commit ba043f8

Browse files
authored
feat: status command (#61)
* feat: status command * fix: lint issues
1 parent a30387d commit ba043f8

15 files changed

Lines changed: 560 additions & 15 deletions

File tree

‎cmd/conductor/main.go‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ func main() {
8484
//• Applypatch Hooks Order: applypatch-msg → pre-applypatch → post-applypatch
8585
}
8686

87+
// run executes a sequence of hook steps with the provided hook data.
8788
func run(data []config.HookStep, hookData string) {
8889
for _, v := range data {
8990
pterm.Info.Println(fmt.Sprintf("Name: %s", v.Name))
@@ -111,10 +112,12 @@ func run(data []config.HookStep, hookData string) {
111112
}
112113
}
113114

115+
// printCurrentHook prints the name of the Git hook currently being executed.
114116
func printCurrentHook(hook string) {
115117
pterm.DefaultSection.Println("Running hook:", hook)
116118
}
117119

120+
// ptermWriter is an io.Writer that routes its output through pterm.
118121
type ptermWriter struct {
119122
printFunc func(...any)
120123
}

‎internal/blueprint/blueprint.go‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ type BluePrint struct {
1717
Data string
1818
}
1919

20-
// NewBluePrint generates a new blueprint to be used for write to the filesystem
20+
// NewBluePrint generates a new blueprint to be used for writing to the filesystem.
2121
func NewBluePrint(name, writePath, data string, values any) *BluePrint {
2222
return &BluePrint{
2323
Name: name,
@@ -27,12 +27,12 @@ func NewBluePrint(name, writePath, data string, values any) *BluePrint {
2727
}
2828
}
2929

30-
// Exists allows you to check if the file within the blueprint exists
30+
// Exists checks if the file specified in the blueprint already exists on the filesystem.
3131
func (b *BluePrint) Exists() (os.FileInfo, error) {
3232
return os.Stat(b.WritePath)
3333
}
3434

35-
// Write takes the BluePrint data then templates it out to the filesystem
35+
// Write renders the BluePrint's template data with its values and writes the result to the filesystem at WritePath.
3636
func (b *BluePrint) Write() error {
3737
tmpl := template.Must(template.New(b.Name).Parse(b.Data))
3838
file, err := os.OpenFile(b.WritePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0o755)

‎internal/blueprint/hooks.go‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
"github.com/devbytes-cloud/freight/internal/validate"
77
)
88

9+
// NewGitHook creates a new BluePrint for a specific Git hook.
910
func NewGitHook(gh *githooks.GitHook) (*BluePrint, error) {
1011
dir, err := validate.CurrentWD()
1112
if err != nil {

‎internal/commands/helpers_test.go‎

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
package commands
2+
3+
import (
4+
"os"
5+
"testing"
6+
7+
"github.com/stretchr/testify/require"
8+
)
9+
10+
func withTempGitDir(t *testing.T) (string, func()) {
11+
t.Helper()
12+
13+
tmpDir, err := os.MkdirTemp("", "freight-test-*")
14+
require.NoError(t, err)
15+
16+
origWd, err := os.Getwd()
17+
require.NoError(t, err)
18+
19+
err = os.Chdir(tmpDir)
20+
require.NoError(t, err)
21+
22+
err = os.MkdirAll(".git/hooks", 0o755)
23+
require.NoError(t, err)
24+
25+
cleanup := func() {
26+
_ = os.Chdir(origWd)
27+
_ = os.RemoveAll(tmpDir)
28+
}
29+
30+
return tmpDir, cleanup
31+
}

‎internal/commands/init_test.go‎

Lines changed: 114 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,114 @@
1+
package commands
2+
3+
import (
4+
"os"
5+
"sort"
6+
"testing"
7+
8+
"github.com/devbytes-cloud/freight/internal/config"
9+
"github.com/stretchr/testify/assert"
10+
"github.com/stretchr/testify/require"
11+
"gopkg.in/yaml.v3"
12+
)
13+
14+
func TestInitMergeAllow(t *testing.T) {
15+
_, cleanup := withTempGitDir(t)
16+
defer cleanup()
17+
18+
fingerprintPath := ".git/hooks/.fingerprint.yaml"
19+
20+
t.Run("Initial init with specific allow", func(t *testing.T) {
21+
cmd := NewRootCmd()
22+
cmd.SetArgs([]string{"init", "--allow", "pre-commit,commit-msg"})
23+
err := cmd.Execute()
24+
require.NoError(t, err)
25+
26+
// Check fingerprint
27+
data, err := os.ReadFile(fingerprintPath)
28+
require.NoError(t, err)
29+
30+
var cfg config.FreightConfig
31+
err = yaml.Unmarshal(data, &cfg)
32+
require.NoError(t, err)
33+
34+
sort.Strings(cfg.Allow)
35+
assert.Equal(t, []string{"commit-msg", "pre-commit"}, cfg.Allow)
36+
})
37+
38+
t.Run("Merge new allow with existing", func(t *testing.T) {
39+
cmd := NewRootCmd()
40+
cmd.SetArgs([]string{"init", "--allow", "post-commit"})
41+
err := cmd.Execute()
42+
require.NoError(t, err)
43+
44+
// Check fingerprint
45+
data, err := os.ReadFile(fingerprintPath)
46+
require.NoError(t, err)
47+
48+
var cfg config.FreightConfig
49+
err = yaml.Unmarshal(data, &cfg)
50+
require.NoError(t, err)
51+
52+
sort.Strings(cfg.Allow)
53+
assert.Equal(t, []string{"commit-msg", "post-commit", "pre-commit"}, cfg.Allow)
54+
})
55+
56+
t.Run("No duplicates when merging", func(t *testing.T) {
57+
cmd := NewRootCmd()
58+
cmd.SetArgs([]string{"init", "--allow", "pre-commit,post-checkout"})
59+
err := cmd.Execute()
60+
require.NoError(t, err)
61+
62+
// Check fingerprint
63+
data, err := os.ReadFile(fingerprintPath)
64+
require.NoError(t, err)
65+
66+
var cfg config.FreightConfig
67+
err = yaml.Unmarshal(data, &cfg)
68+
require.NoError(t, err)
69+
70+
sort.Strings(cfg.Allow)
71+
assert.Equal(t, []string{"commit-msg", "post-checkout", "post-commit", "pre-commit"}, cfg.Allow)
72+
})
73+
74+
t.Run("Only specified hooks are initialized with --allow", func(t *testing.T) {
75+
// Clean up and start fresh
76+
err := os.RemoveAll(".git/hooks")
77+
require.NoError(t, err)
78+
err = os.MkdirAll(".git/hooks", 0o755)
79+
require.NoError(t, err)
80+
81+
// 1. Init with pre-commit
82+
cmd := NewRootCmd()
83+
cmd.SetArgs([]string{"init", "--allow", "pre-commit"})
84+
err = cmd.Execute()
85+
require.NoError(t, err)
86+
87+
require.FileExists(t, ".git/hooks/pre-commit")
88+
_, err = os.Stat(".git/hooks/post-commit")
89+
assert.True(t, os.IsNotExist(err))
90+
91+
// 2. Init with post-commit. It should NOT re-initialize pre-commit (though pre-commit should still exist if it was there)
92+
// To truly test it ONLY runs post-commit, we can delete pre-commit and see if it comes back.
93+
err = os.Remove(".git/hooks/pre-commit")
94+
require.NoError(t, err)
95+
96+
cmd = NewRootCmd()
97+
cmd.SetArgs([]string{"init", "--allow", "post-commit"})
98+
err = cmd.Execute()
99+
require.NoError(t, err)
100+
101+
require.FileExists(t, ".git/hooks/post-commit")
102+
_, err = os.Stat(".git/hooks/pre-commit")
103+
assert.True(t, os.IsNotExist(err), "pre-commit should not have been re-initialized")
104+
105+
// 3. Check fingerprint has BOTH
106+
data, err := os.ReadFile(fingerprintPath)
107+
require.NoError(t, err)
108+
var cfg config.FreightConfig
109+
err = yaml.Unmarshal(data, &cfg)
110+
require.NoError(t, err)
111+
sort.Strings(cfg.Allow)
112+
assert.Equal(t, []string{"post-commit", "pre-commit"}, cfg.Allow)
113+
})
114+
}

‎internal/commands/root.go‎

Lines changed: 66 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"errors"
66
"fmt"
77
"os"
8+
"sort"
89
"strings"
910

1011
"github.com/devbytes-cloud/freight/internal/blueprint"
@@ -14,6 +15,7 @@ import (
1415
"github.com/devbytes-cloud/freight/internal/validate"
1516
"github.com/pterm/pterm"
1617
"github.com/spf13/cobra"
18+
"gopkg.in/yaml.v3"
1719
)
1820

1921
var allowHooks = map[string]struct{}{
@@ -55,7 +57,48 @@ func NewRootCmd() *cobra.Command {
5557
os.Exit(1)
5658
}
5759

58-
validatedAllow, err := validateAllowHooks(userAllow)
60+
fingerprintPath := ".git/hooks/.fingerprint.yaml"
61+
62+
var freightConfig config.FreightConfig
63+
if data, err := os.ReadFile(fingerprintPath); err == nil {
64+
_ = yaml.Unmarshal(data, &freightConfig)
65+
}
66+
67+
var hooksToSetup []string
68+
69+
if len(userAllow) > 0 {
70+
hooksToSetup = userAllow
71+
existingAllow := make(map[string]struct{})
72+
for _, a := range freightConfig.Allow {
73+
existingAllow[a] = struct{}{}
74+
}
75+
for _, a := range userAllow {
76+
existingAllow[a] = struct{}{}
77+
}
78+
var mergedAllow []string
79+
for a := range existingAllow {
80+
mergedAllow = append(mergedAllow, a)
81+
}
82+
sort.Strings(mergedAllow)
83+
freightConfig.Allow = mergedAllow
84+
} else if len(freightConfig.Allow) == 0 {
85+
// If no user allow and no existing allow, use default all hooks
86+
var allHooks []string
87+
for h := range allowHooks {
88+
allHooks = append(allHooks, h)
89+
}
90+
sort.Strings(allHooks)
91+
freightConfig.Allow = allHooks
92+
hooksToSetup = freightConfig.Allow
93+
} else {
94+
// If no user allow but existing allow exists, use existing allow
95+
hooksToSetup = freightConfig.Allow
96+
}
97+
98+
pterm.Debug.Printfln("Effective allow: %v", freightConfig.Allow)
99+
pterm.Debug.Printfln("Hooks to setup: %v", hooksToSetup)
100+
101+
validatedAllow, err := validateAllowHooks(hooksToSetup)
59102
if err != nil {
60103
cmd.PrintErrln(err)
61104
os.Exit(1)
@@ -77,18 +120,36 @@ func NewRootCmd() *cobra.Command {
77120
if err := installBinary(); err != nil {
78121
cmd.PrintErrln(err)
79122
}
123+
124+
// Save fingerprint
125+
freightConfig.Version = Version
126+
data, err := yaml.Marshal(freightConfig)
127+
if err == nil {
128+
pterm.DefaultSection.Println("Writing fingerprint file")
129+
comment := "# This file is managed by Freight. It keeps track of the version and allowed hooks.\n"
130+
finalData := append([]byte(comment), data...)
131+
if err := os.WriteFile(fingerprintPath, finalData, 0o644); err != nil {
132+
pterm.Error.Printfln("✖ Failed to write fingerprint: %v", err)
133+
} else {
134+
pterm.Success.Printfln("✔ Fingerprint .fingerprint.yaml successfully written to .git/hooks")
135+
}
136+
}
137+
138+
pterm.Success.Println("Freight initialized successfully!")
80139
},
81140
}
82141

83142
initCmd.Flags().BoolP("config-force", "c", false, "If you wish to force write the config")
84143
initCmd.Flags().StringSliceP("allow", "a", []string{}, "Specific Git hooks to install (default: all). Valid options: pre-commit, prepare-commit-msg, commit-msg, post-commit, post-checkout")
85144
rootCmd.AddCommand(initCmd)
145+
rootCmd.AddCommand(statusCommand())
86146
rootCmd.AddCommand(versionCommand())
87147

88148
return rootCmd
89149
}
90150

91-
// setupHooks initializes and writes the Git hooks.
151+
// setupHooks initializes and writes the Git hooks to the .git/hooks directory.
152+
// It only writes the hooks that are included in the allowedHooks map.
92153
func setupHooks(allowedHooks map[string]struct{}) error {
93154
pterm.DefaultSection.Println("Generating .git/hooks")
94155
pterm.Debug.Printfln("Allowed hooks: %v", allowedHooks)
@@ -125,7 +186,8 @@ func writeConfig(v *githooks.GitHook) error {
125186
return nil
126187
}
127188

128-
// setupConfig creates and writes the configuration file.
189+
// setupConfig initializes the Railcar configuration file (railcar.json).
190+
// If forceWrite is true, it overwrites any existing configuration.
129191
func setupConfig(forceWrite bool) error {
130192
pterm.DefaultSection.Println("Writing config file")
131193

@@ -151,7 +213,7 @@ func setupConfig(forceWrite bool) error {
151213
return nil
152214
}
153215

154-
// installBinary writes the embedded binary to the filesystem.
216+
// installBinary extracts and writes the embedded Conductor binary to the current directory.
155217
func installBinary() error {
156218
pterm.DefaultSection.Println("Installing Conductor binary")
157219
err := embed.WriteBinary()

0 commit comments

Comments
 (0)