| 1 | package gitrepo |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "os" |
| 7 | "path/filepath" |
| 8 | "sort" |
| 9 | "strings" |
| 10 | |
| 11 | "gitlab.com/Timfa/bluegit/internal/access" |
| 12 | "gitlab.com/Timfa/bluegit/internal/i18n" |
| 13 | ) |
| 14 | |
| 15 | // SuggestionEdit vervangt de regels Start t/m End (1-based, inclusief) |
| 16 | // als die nog gelijk zijn aan Base. |
| 17 | type SuggestionEdit struct { |
| 18 | Path, Base, Replacement string |
| 19 | Start, End int |
| 20 | } |
| 21 | |
| 22 | // ParseSuggestion haalt de eerste ```suggestion-blok uit een reactie. |
| 23 | // De tekst is zonder de afsluitende newline van het blok. |
| 24 | func ParseSuggestion(body string) (string, bool) { |
| 25 | body = strings.ReplaceAll(body, "\r\n", "\n") |
| 26 | const open = "```suggestion" |
| 27 | i := strings.Index(body, open) |
| 28 | if i < 0 { |
| 29 | return "", false |
| 30 | } |
| 31 | rest := body[i+len(open):] |
| 32 | nl := strings.IndexByte(rest, '\n') |
| 33 | if nl < 0 { |
| 34 | return "", false |
| 35 | } |
| 36 | rest = rest[nl+1:] |
| 37 | end := strings.Index(rest, "```") |
| 38 | if end < 0 { |
| 39 | return "", false |
| 40 | } |
| 41 | return strings.TrimSuffix(rest[:end], "\n"), true |
| 42 | } |
| 43 | |
| 44 | // SplitLines splitst een bestand op newlines. Een afsluitende newline telt niet als lege regel. |
| 45 | func SplitLines(s string) []string { |
| 46 | if s == "" { |
| 47 | return nil |
| 48 | } |
| 49 | s = strings.TrimSuffix(s, "\n") |
| 50 | return strings.Split(s, "\n") |
| 51 | } |
| 52 | |
| 53 | // ApplySuggestions past alle edits toe. Bij een conflict of overlap verandert er niets. |
| 54 | func ApplySuggestions(files map[string]string, edits []SuggestionEdit) (map[string]string, error) { |
| 55 | byPath := map[string][]SuggestionEdit{} |
| 56 | for _, e := range edits { |
| 57 | byPath[e.Path] = append(byPath[e.Path], e) |
| 58 | } |
| 59 | out := map[string]string{} |
| 60 | changed := false |
| 61 | for path, group := range byPath { |
| 62 | raw, ok := files[path] |
| 63 | if !ok { |
| 64 | return nil, i18n.E("err.sugFile") |
| 65 | } |
| 66 | sort.Slice(group, func(i, j int) bool { return group[i].Start < group[j].Start }) |
| 67 | for i := 1; i < len(group); i++ { |
| 68 | if group[i].Start <= group[i-1].End { |
| 69 | return nil, i18n.E("err.sugOverlap", path) |
| 70 | } |
| 71 | } |
| 72 | lines := SplitLines(raw) |
| 73 | nl := strings.HasSuffix(raw, "\n") || raw == "" |
| 74 | sort.Slice(group, func(i, j int) bool { return group[i].Start > group[j].Start }) |
| 75 | for _, e := range group { |
| 76 | if e.Start < 1 || e.End < e.Start || e.End > len(lines) { |
| 77 | return nil, i18n.E("err.sugConflict", path, e.Start, e.End) |
| 78 | } |
| 79 | base := strings.Join(lines[e.Start-1:e.End], "\n") |
| 80 | if base != e.Base { |
| 81 | return nil, i18n.E("err.sugConflict", path, e.Start, e.End) |
| 82 | } |
| 83 | var mid []string |
| 84 | if e.Replacement != "" { |
| 85 | mid = strings.Split(e.Replacement, "\n") |
| 86 | } |
| 87 | next := append([]string{}, lines[:e.Start-1]...) |
| 88 | next = append(next, mid...) |
| 89 | next = append(next, lines[e.End:]...) |
| 90 | lines = next |
| 91 | } |
| 92 | next := "" |
| 93 | if len(lines) > 0 { |
| 94 | next = strings.Join(lines, "\n") |
| 95 | if nl { |
| 96 | next += "\n" |
| 97 | } |
| 98 | } |
| 99 | if next != raw { |
| 100 | changed = true |
| 101 | out[path] = next |
| 102 | } |
| 103 | } |
| 104 | if !changed { |
| 105 | return nil, i18n.E("err.sugSame") |
| 106 | } |
| 107 | return out, nil |
| 108 | } |
| 109 | |
| 110 | // CommitOnBranch schrijft files op branch en pusht één commit. |
| 111 | // De push loopt door de hook, met role en de beschermde patronen. |
| 112 | // Een repository zonder commits krijgt deze branch als eerste commit, zonder parent. |
| 113 | // Git draait met een eigen HOME en TMPDIR onder work, niet met die van het proces: |
| 114 | // ProtectHome maakt de homedirectory onleesbaar en /tmp is niet de werkmap. |
| 115 | func CommitOnBranch(ctx context.Context, gitBin, bare, work, branch, author, email, title, description string, files map[string]string, role access.Role, patterns []string) error { |
| 116 | return CommitChanges(ctx, gitBin, bare, work, branch, author, email, title, description, files, nil, role, patterns) |
| 117 | } |
| 118 | |
| 119 | // CommitChanges schrijft files, verwijdert paden en pusht één commit. |
| 120 | func CommitChanges(ctx context.Context, gitBin, bare, work, branch, author, email, title, description string, files map[string]string, deletes []string, role access.Role, patterns []string) error { |
| 121 | if len(files) == 0 && len(deletes) == 0 { |
| 122 | return i18n.E("err.commitEmpty") |
| 123 | } |
| 124 | repo, env, err := prepareWork(work, author, email) |
| 125 | if err != nil { |
| 126 | return classifyGit(err) |
| 127 | } |
| 128 | if _, err := run(ctx, gitBin, env, "clone", bare, repo); err != nil { |
| 129 | return classifyGit(err) |
| 130 | } |
| 131 | if _, err := run(ctx, gitBin, env, "-C", repo, "rev-parse", "--verify", "--quiet", "HEAD"); err != nil { |
| 132 | if _, err := run(ctx, gitBin, env, "-C", repo, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil { |
| 133 | return classifyGit(err) |
| 134 | } |
| 135 | } else if _, err := run(ctx, gitBin, env, "-C", repo, "checkout", branch); err != nil { |
| 136 | return classifyGit(err) |
| 137 | } |
| 138 | var paths []string |
| 139 | for path, body := range files { |
| 140 | if !safeWorkPath(path) { |
| 141 | return i18n.E("err.sugFile") |
| 142 | } |
| 143 | dst := filepath.Join(repo, filepath.FromSlash(path)) |
| 144 | if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { |
| 145 | return classifyGit(err) |
| 146 | } |
| 147 | if err := os.WriteFile(dst, []byte(body), 0o644); err != nil { |
| 148 | return classifyGit(err) |
| 149 | } |
| 150 | paths = append(paths, path) |
| 151 | } |
| 152 | sort.Strings(paths) |
| 153 | if len(paths) > 0 { |
| 154 | args := append([]string{"-C", repo, "add", "--"}, paths...) |
| 155 | if _, err := run(ctx, gitBin, env, args...); err != nil { |
| 156 | return classifyGit(err) |
| 157 | } |
| 158 | } |
| 159 | for _, path := range deletes { |
| 160 | if !safeWorkPath(path) { |
| 161 | return i18n.E("err.sugFile") |
| 162 | } |
| 163 | if _, err := run(ctx, gitBin, env, "-C", repo, "rm", "-f", "--ignore-unmatch", "--", path); err != nil { |
| 164 | return classifyGit(err) |
| 165 | } |
| 166 | } |
| 167 | commit := []string{"-C", repo, "-c", "commit.gpgsign=false", "commit", "-m", title} |
| 168 | if strings.TrimSpace(description) != "" { |
| 169 | commit = append(commit, "-m", description) |
| 170 | } |
| 171 | if _, err := run(ctx, gitBin, env, commit...); err != nil { |
| 172 | return classifyGit(err) |
| 173 | } |
| 174 | pushEnv := append(append([]string{}, env...), PushEnv(role, patterns, nil)...) |
| 175 | if _, err := run(ctx, gitBin, pushEnv, "-C", repo, "push", "origin", "HEAD:"+branch); err != nil { |
| 176 | return classifyGit(err) |
| 177 | } |
| 178 | return nil |
| 179 | } |
| 180 | |
| 181 | // CommandEnv is de omgeving voor elke git-aanroep die een commit maakt. |
| 182 | // HOME en TMPDIR wijzen naar mappen die het proces zelf mag schrijven. |
| 183 | // Naam en e-mail staan expliciet, zodat een lege of afgeschermde identiteit niet meetelt. |
| 184 | func CommandEnv(author, email, home, tmp string) []string { |
| 185 | env := make([]string, 0, len(os.Environ())+8) |
| 186 | for _, e := range os.Environ() { |
| 187 | if strings.HasPrefix(e, "GIT_AUTHOR_") || strings.HasPrefix(e, "GIT_COMMITTER_") || strings.HasPrefix(e, "GIT_CONFIG") { |
| 188 | continue |
| 189 | } |
| 190 | if strings.HasPrefix(e, "HOME=") || strings.HasPrefix(e, "TMPDIR=") { |
| 191 | continue |
| 192 | } |
| 193 | env = append(env, e) |
| 194 | } |
| 195 | return append(env, |
| 196 | "HOME="+home, |
| 197 | "TMPDIR="+tmp, |
| 198 | "GIT_CONFIG_GLOBAL=/dev/null", |
| 199 | "GIT_CONFIG_SYSTEM=/dev/null", |
| 200 | "GIT_AUTHOR_NAME="+author, |
| 201 | "GIT_AUTHOR_EMAIL="+email, |
| 202 | "GIT_COMMITTER_NAME="+author, |
| 203 | "GIT_COMMITTER_EMAIL="+email, |
| 204 | ) |
| 205 | } |
| 206 | |
| 207 | // prepareWork maakt work leeg en zet er een eigen home en tmp in. |
| 208 | // De kloon komt in work/repo, zodat die mappen geen deel van de tree zijn. |
| 209 | func prepareWork(work, author, email string) (string, []string, error) { |
| 210 | if err := os.RemoveAll(work); err != nil { |
| 211 | return "", nil, err |
| 212 | } |
| 213 | if err := os.MkdirAll(work, 0o755); err != nil { |
| 214 | return "", nil, err |
| 215 | } |
| 216 | home := filepath.Join(work, "home") |
| 217 | tmp := filepath.Join(work, "tmp") |
| 218 | if err := os.MkdirAll(home, 0o700); err != nil { |
| 219 | return "", nil, err |
| 220 | } |
| 221 | if err := os.MkdirAll(tmp, 0o700); err != nil { |
| 222 | return "", nil, err |
| 223 | } |
| 224 | return filepath.Join(work, "repo"), CommandEnv(author, email, home, tmp), nil |
| 225 | } |
| 226 | |
| 227 | // Cause koppelt een vertaalbare melding aan de ruwe git-tekst. |
| 228 | // Error() is de git-tekst voor het journal. Unwrap levert de vertaling. |
| 229 | func Cause(key, git string, args ...any) error { |
| 230 | return gitCause{git: git, err: i18n.E(key, args...)} |
| 231 | } |
| 232 | |
| 233 | type gitCause struct { |
| 234 | git string |
| 235 | err error |
| 236 | } |
| 237 | |
| 238 | func (g gitCause) Error() string { return g.git } |
| 239 | func (g gitCause) Unwrap() error { return g.err } |
| 240 | |
| 241 | func classifyGit(err error) error { |
| 242 | if err == nil { |
| 243 | return nil |
| 244 | } |
| 245 | var ie i18n.Error |
| 246 | if errors.As(err, &ie) { |
| 247 | return err |
| 248 | } |
| 249 | low := strings.ToLower(err.Error()) |
| 250 | switch { |
| 251 | case strings.Contains(low, "nothing to commit") || strings.Contains(low, "nothing added"): |
| 252 | return Cause("edit.same", err.Error()) |
| 253 | case strings.Contains(low, "protected") || strings.Contains(low, "beschermd") || strings.Contains(low, "geschützt") || strings.Contains(low, "protégée"): |
| 254 | return Cause("edit.protected", err.Error()) |
| 255 | case strings.Contains(low, "author identity") || strings.Contains(low, "user.email") || strings.Contains(low, "user.name") || strings.Contains(low, "tell me who you are"): |
| 256 | return Cause("edit.failIdentity", err.Error()) |
| 257 | case strings.Contains(low, "permission denied") || strings.Contains(low, "read-only") || strings.Contains(low, "unable to access") || strings.Contains(low, "operation not permitted"): |
| 258 | return Cause("edit.failWrite", err.Error()) |
| 259 | default: |
| 260 | return Cause("edit.failGit", err.Error()) |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | func safeWorkPath(p string) bool { |
| 265 | if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, `\`) || strings.Contains(p, "..") { |
| 266 | return false |
| 267 | } |
| 268 | return true |
| 269 | } |