GitLabgitlab-org

cli

main
ply9 git calls303 ms101 KiB6 cachedprotocol v2
351 lines11 KiBRaw
1// Package claudehooks provides shared constants and utilities for managing
2// Claude Code lifecycle hooks.
3package claudehooks
5import (
6 "bytes"
7 "encoding/json"
8 "errors"
9 "fmt"
10 "io/fs"
11 "os"
12 "path/filepath"
13 "slices"
16const (
17 // SettingsFile is the path to the Claude Code settings file relative to the home directory.
18 SettingsFile = ".claude/settings.json"
20 // StopHookCommand fires after every Claude Code turn.
21 StopHookCommand = "glab minder audit sync --silent >/dev/null 2>&1 &"
23 // SessionEndHookCommand fires when a Claude Code session ends.
24 SessionEndHookCommand = "glab minder audit sync --silent --complete >/dev/null 2>&1 &"
26 // legacyStopHookCommand and legacySessionEndHookCommand are the hooks that
27 // glab versions before the rename to glab minder installed. They still run,
28 // through the hidden glab govern command, until setup replaces them.
29 legacyStopHookCommand = "glab govern audit sync --silent >/dev/null 2>&1 &"
30 legacySessionEndHookCommand = "glab govern audit sync --silent --complete >/dev/null 2>&1 &"
33// hookCommands maps each hook event to the command setup installs for it, and
34// the command that earlier glab versions installed.
35var hookCommands = map[string]struct{ current, legacy string }{
36 "Stop": {StopHookCommand, legacyStopHookCommand},
37 "SessionEnd": {SessionEndHookCommand, legacySessionEndHookCommand},
40// HookEntry mirrors the Claude Code hook entry format.
41type HookEntry struct {
42 Type string `json:"type"`
43 Command string `json:"command"`
44 Timeout int `json:"timeout,omitempty"`
45 // unknown keeps fields glab does not model, such as "if" and
46 // "statusMessage". Dropping "if" would widen the hook's scope.
47 unknown map[string]json.RawMessage
50func (e *HookEntry) UnmarshalJSON(data []byte) error {
51 type known HookEntry
52 var k known
53 unknown, err := splitUnknown(data, &k)
54 if err != nil {
55 return err
56 }
57 *e = HookEntry(k)
58 e.unknown = unknown
59 return nil
62func (e HookEntry) MarshalJSON() ([]byte, error) {
63 type known HookEntry
64 return joinUnknown(known(e), e.unknown)
67// HookGroup mirrors the Claude Code hook group format.
68type HookGroup struct {
69 // Matcher is optional and scopes the hook to specific tools.
70 // It must be preserved to avoid widening hook scope.
71 Matcher string `json:"matcher,omitempty"`
72 Hooks []HookEntry `json:"hooks"`
73 unknown map[string]json.RawMessage
76func (g *HookGroup) UnmarshalJSON(data []byte) error {
77 type known HookGroup
78 var k known
79 unknown, err := splitUnknown(data, &k)
80 if err != nil {
81 return err
82 }
83 *g = HookGroup(k)
84 g.unknown = unknown
85 return nil
88func (g HookGroup) MarshalJSON() ([]byte, error) {
89 type known HookGroup
90 return joinUnknown(known(g), g.unknown)
93// splitUnknown decodes data into known and returns the fields that known
94// does not write back. A known field left at its zero value is omitted when
95// encoded, so it is kept here verbatim and written back unchanged.
96func splitUnknown(data []byte, known any) (map[string]json.RawMessage, error) {
97 if err := json.Unmarshal(data, known); err != nil {
98 return nil, err
99 }
100 var fields map[string]json.RawMessage
101 if err := json.Unmarshal(data, &fields); err != nil {
102 return nil, err
103 }
104 encoded, err := marshal(known)
105 if err != nil {
106 return nil, err
107 }
108 var written map[string]json.RawMessage
109 if err := json.Unmarshal(encoded, &written); err != nil {
110 return nil, err
111 }
112 for key := range written {
113 delete(fields, key)
114 }
115 if len(fields) == 0 {
116 return nil, nil
117 }
118 return fields, nil
121func joinUnknown(known any, unknown map[string]json.RawMessage) ([]byte, error) {
122 encoded, err := marshal(known)
123 if err != nil || len(unknown) == 0 {
124 return encoded, err
125 }
126 var fields map[string]json.RawMessage
127 if err := json.Unmarshal(encoded, &fields); err != nil {
128 return nil, err
129 }
130 for key, value := range unknown {
131 if _, ok := fields[key]; !ok {
132 fields[key] = value
133 }
134 }
135 return marshal(fields)
138// marshal encodes v without HTML escaping, so shell characters such as > and
139// & in hook commands stay readable in the settings file.
140func marshal(v any) ([]byte, error) {
141 buf := &bytes.Buffer{}
142 encoder := json.NewEncoder(buf) //nolint:forbidigo // serializing to disk, not stdout
143 encoder.SetEscapeHTML(false)
144 if err := encoder.Encode(v); err != nil {
145 return nil, err
146 }
147 return bytes.TrimSuffix(buf.Bytes(), []byte("\n")), nil
150// MarshalHooks encodes hooks for the "hooks" key of the settings file.
151func MarshalHooks(hooks map[string][]HookGroup) (json.RawMessage, error) {
152 return marshal(hooks)
155// SettingsPath returns the absolute path to the Claude Code settings file.
156func SettingsPath() (string, error) {
157 home, err := os.UserHomeDir()
158 if err != nil {
159 return "", fmt.Errorf("could not find home directory: %w", err)
160 }
161 return filepath.Join(home, SettingsFile), nil
164// LoadRawSettings reads the Claude Code settings file as a raw JSON map,
165// preserving all unknown keys. Returns an empty map if the file does not exist.
166func LoadRawSettings(path string) (map[string]json.RawMessage, error) {
167 raw := make(map[string]json.RawMessage)
168 data, err := os.ReadFile(path)
169 switch {
170 case err == nil:
171 if err := json.Unmarshal(data, &raw); err != nil {
172 return nil, fmt.Errorf("could not parse %s: %w", path, err)
173 }
174 case errors.Is(err, fs.ErrNotExist):
175 // File does not exist -- start with an empty map
176 default:
177 return nil, fmt.Errorf("could not read %s: %w", path, err)
178 }
179 return raw, nil
182// HooksFromRaw extracts the hooks map from a raw settings map.
183// Returns an empty map if the hooks key is absent or malformed.
184func HooksFromRaw(raw map[string]json.RawMessage) (map[string][]HookGroup, error) {
185 hooks := make(map[string][]HookGroup)
186 if raw["hooks"] == nil {
187 return hooks, nil
188 }
189 if err := json.Unmarshal(raw["hooks"], &hooks); err != nil {
190 return nil, fmt.Errorf("could not parse hooks: %w", err)
191 }
192 return hooks, nil
195// WriteSettings writes the settings map back to disk atomically using a
196// temp file + rename, preserving all keys including unknown ones.
197// SetEscapeHTML(false) keeps shell characters like > and & readable.
198func WriteSettings(path string, raw map[string]json.RawMessage) error {
199 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
200 return fmt.Errorf("could not create directory: %w", err)
201 }
203 buf := &bytes.Buffer{}
204 encoder := json.NewEncoder(buf) //nolint:forbidigo // serializing to disk, not stdout
205 encoder.SetEscapeHTML(false)
206 encoder.SetIndent("", " ")
207 if err := encoder.Encode(raw); err != nil {
208 return fmt.Errorf("could not serialise settings: %w", err)
209 }
211 // Preserve existing file permissions, default to 0644 for new files
212 perm := os.FileMode(0o644)
213 if info, err := os.Stat(path); err == nil {
214 perm = info.Mode()
215 }
217 // Write atomically via temp file + rename to avoid corruption on crash
218 tmp, err := os.CreateTemp(filepath.Dir(path), ".claude-settings-*.json")
219 if err != nil {
220 return fmt.Errorf("could not create temp file: %w", err)
221 }
222 tmpName := tmp.Name()
223 defer func() { _ = os.Remove(tmpName) }()
225 if _, err := tmp.Write(buf.Bytes()); err != nil {
226 return errors.Join(fmt.Errorf("could not write temp file: %w", err), tmp.Close())
227 }
228 if err := tmp.Close(); err != nil {
229 return fmt.Errorf("could not close temp file: %w", err)
230 }
231 if err := os.Chmod(tmpName, perm); err != nil {
232 return fmt.Errorf("could not set file permissions: %w", err)
233 }
234 if err := os.Rename(tmpName, path); err != nil {
235 return fmt.Errorf("could not rename temp file: %w", err)
236 }
238 return nil
241// HookPresent reports whether a hook with the given command exists for the given event
242// in the provided hooks map.
243func HookPresent(hooks map[string][]HookGroup, event, command string) bool {
244 groups, ok := hooks[event]
245 if !ok {
246 return false
247 }
248 for _, group := range groups {
249 for _, hook := range group.Hooks {
250 if hook.Command == command {
251 return true
252 }
253 }
254 }
255 return false
258// AddHook adds a hook for the given event if not already present.
259// It mutates the hooks map in place and returns whether anything changed.
260func AddHook(hooks map[string][]HookGroup, event, command string) bool {
261 if HookPresent(hooks, event, command) {
262 return false
263 }
264 hooks[event] = append(hooks[event], HookGroup{
265 Hooks: []HookEntry{{Type: "command", Command: command}},
266 })
267 return true
270// SyncHookInstalled reports whether the glab Stop hook, current or legacy, is
271// present in the Claude Code settings file at path.
272func SyncHookInstalled(path string) (bool, error) {
273 raw, err := LoadRawSettings(path)
274 if err != nil {
275 return false, err
276 }
277 hooks, err := HooksFromRaw(raw)
278 if err != nil {
279 return false, fmt.Errorf("%s: %w", path, err)
280 }
281 return GlabHookPresent(hooks, "Stop"), nil
284// GlabHookPresent reports whether glab's hook for event, current or legacy,
285// is present in hooks.
286func GlabHookPresent(hooks map[string][]HookGroup, event string) bool {
287 commands := hookCommands[event]
288 return HookPresent(hooks, event, commands.current) || HookPresent(hooks, event, commands.legacy)
291// LegacyHookPresent reports whether hooks still has a hook that an earlier glab
292// version installed, which runs glab govern instead of glab minder.
293func LegacyHookPresent(hooks map[string][]HookGroup) bool {
294 for event, commands := range hookCommands {
295 if HookPresent(hooks, event, commands.legacy) {
296 return true
297 }
298 }
299 return false
302// InstallGlabHooks adds glab's hooks to hooks and removes the legacy ones they
303// replace, so that a session is not synced twice. It mutates hooks in place
304// and returns whether anything changed.
305func InstallGlabHooks(hooks map[string][]HookGroup) bool {
306 changed := false
307 for event, commands := range hookCommands {
308 changed = RemoveHook(hooks, event, commands.legacy) || changed
309 changed = AddHook(hooks, event, commands.current) || changed
310 }
311 return changed
314// RemoveGlabHooks removes glab's hooks, current and legacy, from hooks. It
315// mutates hooks in place and returns whether anything changed.
316func RemoveGlabHooks(hooks map[string][]HookGroup) bool {
317 changed := false
318 for event, commands := range hookCommands {
319 changed = RemoveHook(hooks, event, commands.current) || changed
320 changed = RemoveHook(hooks, event, commands.legacy) || changed
321 }
322 return changed
325// RemoveHook removes every hook for event that runs command. Groups left
326// without hooks are dropped, and so is the event when no groups remain.
327// It mutates hooks in place and returns whether anything changed.
328func RemoveHook(hooks map[string][]HookGroup, event, command string) bool {
329 changed := false
330 var kept []HookGroup
331 for _, group := range hooks[event] {
332 entries := slices.DeleteFunc(slices.Clone(group.Hooks), func(e HookEntry) bool {
333 return e.Command == command
334 })
335 if len(entries) != len(group.Hooks) {
336 changed = true
337 }
338 if len(entries) > 0 {
339 group.Hooks = entries
340 kept = append(kept, group)
341 }
342 }
343 switch {
344 case !changed:
345 case len(kept) == 0:
346 delete(hooks, event)
347 default:
348 hooks[event] = kept
349 }
350 return changed
Diagnostics9 git calls · 303 ms
CallStatusSizeTime0303 ms
discover200185 B3 ms
git.upload-pack discover
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=4
git.response.bytes=185
git.server.agent=git/2.56.g1891de4-Linux
git.server.object_format=sha1
git.server.caps=agent ls-refs fetch server-option object-format
git.server.fetch=shallow wait-for-done filter
git.protocol.version=2
git.pkt.frames=9
git.pkt.data=7
git.pkt.flush=2
git.pkt.delim=0
git.pkt.bytes=185
git.pkt.payload.max=35
ls-refs20058 KiB2 ms
git.upload-pack ls-refs
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=ls-refs
git.upstream.dur_ms=2
git.response.bytes=59849
git.response.cache=UPDATING
git.response.duration_ms=2
git.protocol.version=2
git.pkt.frames=731
git.pkt.data=730
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=59849
git.pkt.payload.max=143
git.ls_refs.count=730
git.ls_refs.head=refs/heads/main
fetchcombine:blob:none+tree:2 · deepen 12004.2 KiB · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=4273
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=combine:blob:none+tree:2
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=1
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=7
git.pkt.data=5
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=4273
git.pkt.payload.max=4173
git.sideband.band1.bytes=4173
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=11
git.pack.bytes=4173
git.fetch.wide.objects=11
git.fetch.wide.extra_bytes=3930
git.fetch.wide.blobs=0
fetchtree:0 · deepen 1020032 KiB · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=2
git.response.bytes=32926
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=tree:0
git.fetch.wants=0dd7574dce9e385c5c30540e6c15657adc6bdce9
git.fetch.haves.count=0
git.fetch.deepen=10
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=22
git.pkt.data=20
git.pkt.flush=1
git.pkt.delim=1
git.pkt.bytes=32926
git.pkt.payload.max=32046
git.sideband.band1.bytes=32046
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=80
git.pack.bytes=32046
git.pack.ofs_delta=36
git.pack.ref_delta=0
git.pack.chain.max=2
git.pack.trailer=cb0bad5d7ffc514895d8b21c4dd470327f90bc91
git.pack.full=44
Open pack map
fetchtree:02001.8 KiB · hit2 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=4
git.response.bytes=1857
git.response.cache=HIT
git.response.duration_ms=2
git.fetch.filter=tree:0
git.fetch.wants=dce174ff8c632a19d17eea99c8a9b7c37fb2b592
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=1857
git.pkt.payload.max=1830
git.sideband.band1.bytes=1830
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=1830
git.pack.trailer=fb03183b7909876778f740d196d7516811003517
Open pack map
fetchtree:0200261 B · hit4 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=261
git.response.cache=HIT
git.response.duration_ms=4
git.fetch.filter=tree:0
git.fetch.wants=3bb9946301aa8c0dc8d202b83bc9f84bf0400f6d
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=261
git.pkt.payload.max=234
git.sideband.band1.bytes=234
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=234
git.pack.trailer=e0a52f164f79506da6b0dcc275ed62911f5383bf
Open pack map
fetchtree:0200273 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=3
git.response.bytes=273
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=5fa160737ad30857ff606d64de1d596bb211ac3d
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=273
git.pkt.payload.max=246
git.sideband.band1.bytes=246
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=246
git.pack.trailer=06dd39b7545811625e04a7645a0a64c9a62c99c6
Open pack map
fetchtree:0200172 B · hit3 ms
git.upload-pack fetch
http.response.status_code=200
git.upstream.cf_ray=-
git.upstream.phase=fetch
git.upstream.dur_ms=285
git.response.bytes=172
git.response.cache=HIT
git.response.duration_ms=3
git.fetch.filter=tree:0
git.fetch.wants=fad6a354864efa1f4e58b0ebf3a892d3e063d43c
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=172
git.pkt.payload.max=145
git.sideband.band1.bytes=145
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0
git.pack.objects=1
git.pack.bytes=145
git.pack.trailer=e56fd3e20c405e8a9d9512bc4e8366864e9111b7
Open pack map
fetch2003.2 KiB285 ms
git.upload-pack fetch
http.response.status_code=200
git.response.bytes=3306
git.response.cache=MISS
git.response.duration_ms=285
git.fetch.wants=fd5bca56ab4af7ae814b8d70033603af2a27a8d1
git.fetch.haves.count=0
git.fetch.deepen=0
git.fetch.thin_pack=false
git.fetch.ofs_delta=true
git.protocol.version=2
git.pkt.frames=4
git.pkt.data=3
git.pkt.flush=1
git.pkt.delim=0
git.pkt.bytes=3306
git.pkt.payload.max=3279
git.sideband.band1.bytes=3279
git.sideband.band2.bytes=0
git.sideband.band3.bytes=0

Each row is one HTTP round trip ply made to the git server for this page, on one timeline. discover asks what the server speaks, ls-refs lists branch tips, fetch brings objects by id. A hit was served by Workers Cache. Tap a row for its wire details.

Remote
https://gitlab.com/gitlab-org/cli
Ref
refs/heads/main
Commit
0dd7574dce9e385c5c30540e6c15657adc6bdce9
cf-ray
a5e323a4bb865aae
Request
1314c27f…
Protocol
v2 · sha1
Agent
git/2.56.g1891de4-Linux
Filter
advertised
Fetch
shallow wait-for-done filter
Capabilities
agent ls-refs fetch server-option object-format