Skip to content

Commit 30cd133

Browse files
committed
feat(land): cache GitHub branch rules and merge methods for 24h
1 parent 6fb9b82 commit 30cd133

5 files changed

Lines changed: 366 additions & 9 deletions

File tree

‎AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ Tree-sitter resolves; LSP **verifies** declaration-only extent (doc comment stri
5858

5959
## State
6060

61-
No persistent state beyond land's caches under `$XDG_CACHE_HOME` (default `~/.cache`): `land/` and `land-branch/` (gate logs, `flakes.tsv`) and `land-rules/` (last known branch rules). Creates only `rgit-commit.lock` in the git directory (`commit --only`'s OS lock), a `rgit-only-*` system-temp directory holding `commit --only`'s private index, a short-lived `rgit-index-*` copy beside the index (plus git's own `index.lock`) while staging, and, for LSP, the socket, its spawn lock, and the spawned daemon's pidfile under UID-scoped `rgit-<uid>` in `$XDG_RUNTIME_DIR` (or system temp), `0700`, owner-verified before dial (`internal/lsp/dial.go`). Repository state is git's alone.
61+
No persistent state beyond land's caches under `$XDG_CACHE_HOME` (default `~/.cache`): `land/` and `land-branch/` (gate logs, `flakes.tsv`) and `land-rules/` (last known branch rules), and `rgit/github-settings.json` under `os.UserCacheDir()` (branch rules and merge methods, 24 h). Creates only `rgit-commit.lock` in the git directory (`commit --only`'s OS lock), a `rgit-only-*` system-temp directory holding `commit --only`'s private index, a short-lived `rgit-index-*` copy beside the index (plus git's own `index.lock`) while staging, and, for LSP, the socket, its spawn lock, and the spawned daemon's pidfile under UID-scoped `rgit-<uid>` in `$XDG_RUNTIME_DIR` (or system temp), `0700`, owner-verified before dial (`internal/lsp/dial.go`). Repository state is git's alone.
6262

6363
## Self-hosting
6464

‎CHANGELOG.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ Notable changes to `rgit`. The format follows
99
### Added
1010

1111
- `rgit doctor` reports whether `gh` is authenticated.
12+
- `rgit land` caches GitHub branch rules and allowed merge methods for 24 hours, and drops a repo's entries when a push or PR is refused over changed settings.
1213

1314
### Changed
1415

‎internal/app/land.go‎

Lines changed: 20 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -257,8 +257,11 @@ func (g *ghCLI) mergePR(dir, head string, auto bool, strategy string) error {
257257
if strategy != "" {
258258
args = append(args, strategy)
259259
}
260-
_, err := g.runFn(dir, args...)
261-
return err
260+
out, err := g.runFn(dir, args...)
261+
if err != nil {
262+
return fmt.Errorf("%s: %w", strings.TrimSpace(out), err)
263+
}
264+
return nil
262265
}
263266

264267
func (g *ghCLI) prNumber(dir, head string) (int, error) {
@@ -342,7 +345,7 @@ func defaultLandDeps(ctx context.Context, stdout, stderr io.Writer) landDeps {
342345
ctx: ctx,
343346
step: step,
344347
git: execGit{ctx: ctx, step: step},
345-
gh: newGHCLI(ctx, step),
348+
gh: newGHSettingsCache(newGHCLI(ctx, step), githubSettingsPath()),
346349
clock: realClock{ctx},
347350
gate: func(dir string, failedOnly, pushFollows bool) (string, error) {
348351
setLandStep(step, "gate")
@@ -1065,6 +1068,8 @@ type landPushOpts struct {
10651068
logRange string
10661069
// afterGate words the origin-moved error for a push that follows a gate.
10671070
afterGate bool
1071+
// slug is the GitHub slug of the push's remote, so a refusal can drop its cached settings.
1072+
slug string
10681073
}
10691074

10701075
func landByRules(repo, def string, d landDeps, opts landPushOpts) landResult {
@@ -1089,6 +1094,7 @@ func landByRules(repo, def string, d landDeps, opts landPushOpts) landResult {
10891094
origin := strings.TrimSpace(mustGit(repo, d, "config", "--get", "remote."+remote+".url"))
10901095
slug := slugFromOrigin(origin)
10911096
res.Slug = slug
1097+
opts.slug = slug
10921098
var rules []string
10931099
if slug != "" {
10941100
rules = lookupRules(slug, def, d)
@@ -1110,6 +1116,7 @@ func landByRules(repo, def string, d landDeps, opts landPushOpts) landResult {
11101116
}
11111117
pushOut, err := d.git.run(repo, "push", "--recurse-submodules=check", "-u", remote, br)
11121118
if err != nil {
1119+
dropSettingsOnHint(d.gh, slug, pushOut)
11131120
res.Kind = landRed
11141121
res.Lines = []string{summaryRed(repo, pushOut)}
11151122
return res
@@ -1118,6 +1125,7 @@ func landByRules(repo, def string, d landDeps, opts landPushOpts) landResult {
11181125
defer func() { _, _ = d.git.run(repo, "branch", "-D", br) }()
11191126
url, err := d.gh.createPR(repo, br, subj)
11201127
if err != nil {
1128+
dropSettingsOnHint(d.gh, slug, err.Error())
11211129
res.Kind = landRed
11221130
res.Lines = []string{summaryRed(repo, err.Error())}
11231131
return res
@@ -1129,11 +1137,12 @@ func landByRules(repo, def string, d landDeps, opts landPushOpts) landResult {
11291137
}
11301138
// Plain merge first: with no required checks GitHub treats the PR as
11311139
// mergeable now, so --auto only warns and queues nothing.
1132-
_ = d.gh.mergePR(repo, br, false, "")
1133-
if mergeQueue {
1134-
_ = d.gh.mergePR(repo, br, true, "")
1135-
} else {
1136-
_ = d.gh.mergePR(repo, br, true, strategy)
1140+
if err := d.gh.mergePR(repo, br, false, ""); err != nil {
1141+
dropSettingsOnHint(d.gh, slug, err.Error())
1142+
}
1143+
// strategy is empty for a merge queue, so the queued request names no merge method.
1144+
if err := d.gh.mergePR(repo, br, true, strategy); err != nil {
1145+
dropSettingsOnHint(d.gh, slug, err.Error())
11371146
}
11381147
num, _ := d.gh.prNumber(repo, br)
11391148
res.PRNumber = num
@@ -1674,6 +1683,9 @@ func pushDirect(repo, pushDir, remote string, d landDeps, opts landPushOpts, res
16741683
out, err = pushOnce(pushDir, remote, opts.pushTo, d)
16751684
pushed = strings.TrimSpace(mustGit(pushDir, d, "rev-parse", "HEAD"))
16761685
}
1686+
if err != nil {
1687+
dropSettingsOnHint(d.gh, opts.slug, out)
1688+
}
16771689
switch {
16781690
case err == nil || remoteHolds(pushDir, d, remote, pushed, opts.pushTo):
16791691
res.Kind = landPushed
Lines changed: 215 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,215 @@
1+
package app
2+
3+
import (
4+
"encoding/json"
5+
"os"
6+
"path/filepath"
7+
"strings"
8+
"time"
9+
)
10+
11+
// settingsTTL is how long a GitHub answer that rarely changes (branch rules, allowed merge methods) is reused.
12+
const settingsTTL = 24 * time.Hour
13+
14+
// githubSettingsPath is where land keeps those answers; empty when there is no user cache dir, which turns caching off.
15+
func githubSettingsPath() string {
16+
dir, err := os.UserCacheDir()
17+
if err != nil {
18+
return ""
19+
}
20+
return filepath.Join(dir, "rgit", "github-settings.json")
21+
}
22+
23+
// settingsHintMarkers are refusal texts that say a repo's branch rules or merge methods changed.
24+
var settingsHintMarkers = []string{
25+
"gh006", "gh013", "repository rule violations", "protected branch", "merge method",
26+
"squash merges are not allowed", "merge commits are not allowed",
27+
}
28+
29+
func settingsHint(out string) bool {
30+
lower := strings.ToLower(out)
31+
for _, m := range settingsHintMarkers {
32+
if strings.Contains(lower, m) {
33+
return true
34+
}
35+
}
36+
return false
37+
}
38+
39+
// dropSettingsOnHint forgets slug's cached settings when a refused push, PR or merge says they changed.
40+
func dropSettingsOnHint(gh gitHub, slug, out string) {
41+
c, ok := gh.(*ghSettingsCache)
42+
if !ok || slug == "" || !settingsHint(out) {
43+
return
44+
}
45+
c.forget(slug)
46+
}
47+
48+
// ghSettingsCache is a gitHub decorator that keeps branch rules and merge-method answers on disk for
49+
// settingsTTL. Only successful answers are stored. An empty path turns the cache off.
50+
type ghSettingsCache struct {
51+
inner gitHub
52+
path string
53+
now func() time.Time
54+
}
55+
56+
func newGHSettingsCache(inner gitHub, path string) *ghSettingsCache {
57+
return &ghSettingsCache{inner: inner, path: path, now: time.Now}
58+
}
59+
60+
type ghSettingsFile struct {
61+
Repos map[string]*ghRepoSettings `json:"repos"`
62+
}
63+
64+
type ghRepoSettings struct {
65+
Rules map[string]ghRulesEntry `json:"rules,omitempty"`
66+
SquashMerge *ghFlagEntry `json:"squashMerge,omitempty"`
67+
MergeCommit *ghFlagEntry `json:"mergeCommit,omitempty"`
68+
}
69+
70+
type ghRulesEntry struct {
71+
Read time.Time `json:"read"`
72+
Types []string `json:"types"`
73+
}
74+
75+
type ghFlagEntry struct {
76+
Read time.Time `json:"read"`
77+
Allowed bool `json:"allowed"`
78+
}
79+
80+
// load reads the cache file; a missing or unreadable file is empty.
81+
func (c *ghSettingsCache) load() ghSettingsFile {
82+
var f ghSettingsFile
83+
if c.path == "" {
84+
return f
85+
}
86+
b, err := os.ReadFile(c.path)
87+
if err != nil || json.Unmarshal(b, &f) != nil {
88+
return ghSettingsFile{}
89+
}
90+
return f
91+
}
92+
93+
// save writes f through a temp file and a rename, so a concurrent land never reads a partial file.
94+
// A failed write only costs a later re-read.
95+
func (c *ghSettingsCache) save(f ghSettingsFile) {
96+
if c.path == "" {
97+
return
98+
}
99+
b, err := json.Marshal(f)
100+
if err != nil {
101+
return
102+
}
103+
dir := filepath.Dir(c.path)
104+
if err := os.MkdirAll(dir, 0o750); err != nil {
105+
return
106+
}
107+
tmp, err := os.CreateTemp(dir, ".github-settings-*.json")
108+
if err != nil {
109+
return
110+
}
111+
_, werr := tmp.Write(b)
112+
cerr := tmp.Close()
113+
if werr != nil || cerr != nil || os.Rename(tmp.Name(), c.path) != nil {
114+
_ = os.Remove(tmp.Name())
115+
}
116+
}
117+
118+
func (c *ghSettingsCache) fresh(read time.Time) bool {
119+
age := c.now().Sub(read)
120+
return age >= 0 && age < settingsTTL
121+
}
122+
123+
// update applies mutate to slug's settings, reading the file fresh so other keys survive.
124+
func (c *ghSettingsCache) update(slug string, mutate func(*ghRepoSettings)) {
125+
f := c.load()
126+
if f.Repos == nil {
127+
f.Repos = map[string]*ghRepoSettings{}
128+
}
129+
rs := f.Repos[slug]
130+
if rs == nil {
131+
rs = &ghRepoSettings{}
132+
f.Repos[slug] = rs
133+
}
134+
mutate(rs)
135+
c.save(f)
136+
}
137+
138+
// forget drops slug's cached answers so the next land reads them again.
139+
func (c *ghSettingsCache) forget(slug string) {
140+
f := c.load()
141+
if _, ok := f.Repos[slug]; !ok {
142+
return
143+
}
144+
delete(f.Repos, slug)
145+
c.save(f)
146+
}
147+
148+
func (c *ghSettingsCache) branchRuleTypes(slug, branch string) ([]string, error) {
149+
if rs := c.load().Repos[slug]; rs != nil {
150+
if e, ok := rs.Rules[branch]; ok && c.fresh(e.Read) {
151+
return e.Types, nil
152+
}
153+
}
154+
types, err := c.inner.branchRuleTypes(slug, branch)
155+
if err != nil {
156+
return nil, err
157+
}
158+
c.update(slug, func(rs *ghRepoSettings) {
159+
if rs.Rules == nil {
160+
rs.Rules = map[string]ghRulesEntry{}
161+
}
162+
rs.Rules[branch] = ghRulesEntry{Read: c.now(), Types: types}
163+
})
164+
return types, nil
165+
}
166+
167+
func (c *ghSettingsCache) squashMergeAllowed(slug string) (bool, error) {
168+
if rs := c.load().Repos[slug]; rs != nil && rs.SquashMerge != nil && c.fresh(rs.SquashMerge.Read) {
169+
return rs.SquashMerge.Allowed, nil
170+
}
171+
ok, err := c.inner.squashMergeAllowed(slug)
172+
if err != nil {
173+
return false, err
174+
}
175+
c.update(slug, func(rs *ghRepoSettings) {
176+
rs.SquashMerge = &ghFlagEntry{Read: c.now(), Allowed: ok}
177+
})
178+
return ok, nil
179+
}
180+
181+
func (c *ghSettingsCache) mergeCommitAllowed(slug string) (bool, error) {
182+
if rs := c.load().Repos[slug]; rs != nil && rs.MergeCommit != nil && c.fresh(rs.MergeCommit.Read) {
183+
return rs.MergeCommit.Allowed, nil
184+
}
185+
ok, err := c.inner.mergeCommitAllowed(slug)
186+
if err != nil {
187+
return false, err
188+
}
189+
c.update(slug, func(rs *ghRepoSettings) {
190+
rs.MergeCommit = &ghFlagEntry{Read: c.now(), Allowed: ok}
191+
})
192+
return ok, nil
193+
}
194+
195+
// The rest is live state and passes straight through.
196+
197+
func (c *ghSettingsCache) createPR(dir, head, body string) (string, error) {
198+
return c.inner.createPR(dir, head, body)
199+
}
200+
201+
func (c *ghSettingsCache) mergePR(dir, head string, auto bool, strategy string) error {
202+
return c.inner.mergePR(dir, head, auto, strategy)
203+
}
204+
205+
func (c *ghSettingsCache) prNumber(dir, head string) (int, error) {
206+
return c.inner.prNumber(dir, head)
207+
}
208+
209+
func (c *ghSettingsCache) pullRequest(owner, repo string, number int) (prInfo, error) {
210+
return c.inner.pullRequest(owner, repo, number)
211+
}
212+
213+
func (c *ghSettingsCache) latestWorkflowRun(owner, repo, branch, sha string) (workflowRun, error) {
214+
return c.inner.latestWorkflowRun(owner, repo, branch, sha)
215+
}

0 commit comments

Comments
 (0)