| 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 | repo, env, err := prepareWork(work, author, email) |
| 117 | if err != nil { |
| 118 | return classifyGit(err) |
| 119 | } |
| 120 | if _, err := run(ctx, gitBin, env, "clone", bare, repo); err != nil { |
| 121 | return classifyGit(err) |
| 122 | } |
| 123 | if _, err := run(ctx, gitBin, env, "-C", repo, "rev-parse", "--verify", "--quiet", "HEAD"); err != nil { |
| 124 | if _, err := run(ctx, gitBin, env, "-C", repo, "symbolic-ref", "HEAD", "refs/heads/"+branch); err != nil { |
| 125 | return classifyGit(err) |
| 126 | } |
| 127 | } else if _, err := run(ctx, gitBin, env, "-C", repo, "checkout", branch); err != nil { |
| 128 | return classifyGit(err) |
| 129 | } |
| 130 | var paths []string |
| 131 | for path, body := range files { |
| 132 | if !safeWorkPath(path) { |
| 133 | return i18n.E("err.sugFile") |
| 134 | } |
| 135 | dst := filepath.Join(repo, filepath.FromSlash(path)) |
| 136 | if err := os.MkdirAll(filepath.Dir(dst), 0o755); err != nil { |
| 137 | return classifyGit(err) |
| 138 | } |
| 139 | if err := os.WriteFile(dst, []byte(body), 0o644); err != nil { |
| 140 | return classifyGit(err) |
| 141 | } |
| 142 | paths = append(paths, path) |
| 143 | } |
| 144 | sort.Strings(paths) |
| 145 | args := append([]string{"-C", repo, "add", "--"}, paths...) |
| 146 | if _, err := run(ctx, gitBin, env, args...); err != nil { |
| 147 | return classifyGit(err) |
| 148 | } |
| 149 | commit := []string{"-C", repo, "-c", "commit.gpgsign=false", "commit", "-m", title} |
| 150 | if strings.TrimSpace(description) != "" { |
| 151 | commit = append(commit, "-m", description) |
| 152 | } |
| 153 | if _, err := run(ctx, gitBin, env, commit...); err != nil { |
| 154 | return classifyGit(err) |
| 155 | } |
| 156 | pushEnv := append(append([]string{}, env...), PushEnv(role, patterns, nil)...) |
| 157 | if _, err := run(ctx, gitBin, pushEnv, "-C", repo, "push", "origin", "HEAD:"+branch); err != nil { |
| 158 | return classifyGit(err) |
| 159 | } |
| 160 | return nil |
| 161 | } |
| 162 | |
| 163 | // CommandEnv is de omgeving voor elke git-aanroep die een commit maakt. |
| 164 | // HOME en TMPDIR wijzen naar mappen die het proces zelf mag schrijven. |
| 165 | // Naam en e-mail staan expliciet, zodat een lege of afgeschermde identiteit niet meetelt. |
| 166 | func CommandEnv(author, email, home, tmp string) []string { |
| 167 | env := make([]string, 0, len(os.Environ())+8) |
| 168 | for _, e := range os.Environ() { |
| 169 | if strings.HasPrefix(e, "GIT_AUTHOR_") || strings.HasPrefix(e, "GIT_COMMITTER_") || strings.HasPrefix(e, "GIT_CONFIG") { |
| 170 | continue |
| 171 | } |
| 172 | if strings.HasPrefix(e, "HOME=") || strings.HasPrefix(e, "TMPDIR=") { |
| 173 | continue |
| 174 | } |
| 175 | env = append(env, e) |
| 176 | } |
| 177 | return append(env, |
| 178 | "HOME="+home, |
| 179 | "TMPDIR="+tmp, |
| 180 | "GIT_CONFIG_GLOBAL=/dev/null", |
| 181 | "GIT_CONFIG_SYSTEM=/dev/null", |
| 182 | "GIT_AUTHOR_NAME="+author, |
| 183 | "GIT_AUTHOR_EMAIL="+email, |
| 184 | "GIT_COMMITTER_NAME="+author, |
| 185 | "GIT_COMMITTER_EMAIL="+email, |
| 186 | ) |
| 187 | } |
| 188 | |
| 189 | // prepareWork maakt work leeg en zet er een eigen home en tmp in. |
| 190 | // De kloon komt in work/repo, zodat die mappen geen deel van de tree zijn. |
| 191 | func prepareWork(work, author, email string) (string, []string, error) { |
| 192 | if err := os.RemoveAll(work); err != nil { |
| 193 | return "", nil, err |
| 194 | } |
| 195 | if err := os.MkdirAll(work, 0o755); err != nil { |
| 196 | return "", nil, err |
| 197 | } |
| 198 | home := filepath.Join(work, "home") |
| 199 | tmp := filepath.Join(work, "tmp") |
| 200 | if err := os.MkdirAll(home, 0o700); err != nil { |
| 201 | return "", nil, err |
| 202 | } |
| 203 | if err := os.MkdirAll(tmp, 0o700); err != nil { |
| 204 | return "", nil, err |
| 205 | } |
| 206 | return filepath.Join(work, "repo"), CommandEnv(author, email, home, tmp), nil |
| 207 | } |
| 208 | |
| 209 | // Cause koppelt een vertaalbare melding aan de ruwe git-tekst. |
| 210 | // Error() is de git-tekst voor het journal. Unwrap levert de vertaling. |
| 211 | func Cause(key, git string, args ...any) error { |
| 212 | return gitCause{git: git, err: i18n.E(key, args...)} |
| 213 | } |
| 214 | |
| 215 | type gitCause struct { |
| 216 | git string |
| 217 | err error |
| 218 | } |
| 219 | |
| 220 | func (g gitCause) Error() string { return g.git } |
| 221 | func (g gitCause) Unwrap() error { return g.err } |
| 222 | |
| 223 | func classifyGit(err error) error { |
| 224 | if err == nil { |
| 225 | return nil |
| 226 | } |
| 227 | var ie i18n.Error |
| 228 | if errors.As(err, &ie) { |
| 229 | return err |
| 230 | } |
| 231 | low := strings.ToLower(err.Error()) |
| 232 | switch { |
| 233 | case strings.Contains(low, "nothing to commit") || strings.Contains(low, "nothing added"): |
| 234 | return Cause("edit.same", err.Error()) |
| 235 | case strings.Contains(low, "protected") || strings.Contains(low, "beschermd") || strings.Contains(low, "geschützt") || strings.Contains(low, "protégée"): |
| 236 | return Cause("edit.protected", err.Error()) |
| 237 | case strings.Contains(low, "author identity") || strings.Contains(low, "user.email") || strings.Contains(low, "user.name") || strings.Contains(low, "tell me who you are"): |
| 238 | return Cause("edit.failIdentity", err.Error()) |
| 239 | case strings.Contains(low, "permission denied") || strings.Contains(low, "read-only") || strings.Contains(low, "unable to access") || strings.Contains(low, "operation not permitted"): |
| 240 | return Cause("edit.failWrite", err.Error()) |
| 241 | default: |
| 242 | return Cause("edit.failGit", err.Error()) |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | func safeWorkPath(p string) bool { |
| 247 | if p == "" || strings.HasPrefix(p, "/") || strings.Contains(p, `\`) || strings.Contains(p, "..") { |
| 248 | return false |
| 249 | } |
| 250 | return true |
| 251 | } |