| 1 | package server |
| 2 | |
| 3 | import ( |
| 4 | "bufio" |
| 5 | "bytes" |
| 6 | "context" |
| 7 | "errors" |
| 8 | "fmt" |
| 9 | "html/template" |
| 10 | "io" |
| 11 | "maps" |
| 12 | "net/http" |
| 13 | "net/url" |
| 14 | "slices" |
| 15 | "strconv" |
| 16 | "strings" |
| 17 | "unicode" |
| 18 | "unicode/utf8" |
| 19 | |
| 20 | "the-valley/web/export" |
| 21 | "the-valley/web/markdown" |
| 22 | ) |
| 23 | |
| 24 | // treeURL is the directory at path in commit, under the base of its |
| 25 | // project, /<group>/<project>, escaped. It ends in a slash. |
| 26 | func treeURL(base, commit string, path []string) string { |
| 27 | u := base + "/source/tree/" + commit + "/" |
| 28 | if len(path) > 0 { |
| 29 | u += escapePath(path) + "/" |
| 30 | } |
| 31 | return u |
| 32 | } |
| 33 | |
| 34 | // blobURL is the file at path in commit, under its project's base. |
| 35 | func blobURL(base, commit string, path []string) string { |
| 36 | return base + "/source/blob/" + commit + "/" + escapePath(path) |
| 37 | } |
| 38 | |
| 39 | // logURL is the history that ends at commit, under its project's base. |
| 40 | func logURL(base, commit string) string { |
| 41 | return base + "/source/log/" + commit |
| 42 | } |
| 43 | |
| 44 | func escapePath(path []string) string { |
| 45 | parts := make([]string, len(path)) |
| 46 | for i, s := range path { |
| 47 | parts[i] = url.PathEscape(s) |
| 48 | } |
| 49 | return strings.Join(parts, "/") |
| 50 | } |
| 51 | |
| 52 | // source serves the routes under /<group>/<project>/source/. The project is |
| 53 | // checked first, so everything under a project the export does not hold |
| 54 | // as public answers as a missing project does. A view runs git under the |
| 55 | // request's git context, and gives back its git slot once it renders. |
| 56 | func (q *request) source(project string, rest []string) { |
| 57 | p, ok := q.project(project) |
| 58 | if !ok { |
| 59 | q.notFound() |
| 60 | return |
| 61 | } |
| 62 | repo, ok := q.g.Repo(p.Name) |
| 63 | if !ok { |
| 64 | q.notFound() |
| 65 | return |
| 66 | } |
| 67 | var view func(ctx context.Context) error |
| 68 | switch { |
| 69 | case len(rest) == 0 || len(rest) == 1 && rest[0] == "": |
| 70 | q.redirect(treeURL(q.idx.bases[p.Name], p.SourceTip, nil)) |
| 71 | return |
| 72 | case len(rest) == 2 && rest[0] == "archive" && rest[1] == tipArchive: |
| 73 | q.redirect(archiveURL(q.idx.bases[p.Name], p.SourceTip)) |
| 74 | return |
| 75 | case len(rest) >= 2 && rest[0] == "tree": |
| 76 | path := rest[2:] |
| 77 | if n := len(path); n > 0 && path[n-1] == "" { |
| 78 | path = path[:n-1] |
| 79 | } |
| 80 | if !validPath(path) { |
| 81 | q.notFound() |
| 82 | return |
| 83 | } |
| 84 | view = func(ctx context.Context) error { return q.dir(ctx, p, repo, rest[1], path) } |
| 85 | case len(rest) >= 3 && rest[0] == "blob": |
| 86 | path := rest[2:] |
| 87 | if !validPath(path) { |
| 88 | q.notFound() |
| 89 | return |
| 90 | } |
| 91 | view = func(ctx context.Context) error { return q.file(ctx, p, repo, rest[1], path) } |
| 92 | case len(rest) == 2 && rest[0] == "log": |
| 93 | view = func(ctx context.Context) error { return q.log(ctx, p, repo, rest[1]) } |
| 94 | case len(rest) == 2 && rest[0] == "archive": |
| 95 | commit, ok := strings.CutSuffix(rest[1], archiveSuffix) |
| 96 | if !ok { |
| 97 | q.notFound() |
| 98 | return |
| 99 | } |
| 100 | view = func(ctx context.Context) error { return q.archive(ctx, p, repo, commit) } |
| 101 | default: |
| 102 | q.notFound() |
| 103 | return |
| 104 | } |
| 105 | if q.git == nil { // runsGit admits every route that reaches here |
| 106 | q.fail(errors.New("a source route was served without a git slot")) |
| 107 | return |
| 108 | } |
| 109 | if err := view(q.git); err != nil { |
| 110 | q.fail(err) |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | // validPath is a path a source route may name: at most MaxDepth |
| 115 | // segments, none of them empty, a dot segment, or holding a slash or a |
| 116 | // NUL. |
| 117 | func validPath(path []string) bool { |
| 118 | if len(path) > MaxDepth { |
| 119 | return false |
| 120 | } |
| 121 | for _, s := range path { |
| 122 | if s == "" || s == "." || s == ".." || strings.ContainsAny(s, "/\x00") { |
| 123 | return false |
| 124 | } |
| 125 | } |
| 126 | return true |
| 127 | } |
| 128 | |
| 129 | // commitTree is the tree of commit, when commit is a commit the |
| 130 | // project's published source tip reaches. ok is false for anything else: |
| 131 | // an unreachable commit, another kind of object, or text that is no full |
| 132 | // object ID. |
| 133 | func commitTree(ctx context.Context, p *export.Project, repo, commit string) (tree string, ok bool, err error) { |
| 134 | reachable, err := export.Reachable(ctx, repo, p.SourceTip, commit) |
| 135 | if err != nil || !reachable { |
| 136 | return "", false, err |
| 137 | } |
| 138 | out, err := export.Git(ctx, repo, maxLine, "rev-parse", "--verify", commit+"^{tree}") |
| 139 | if err != nil { |
| 140 | return "", false, err |
| 141 | } |
| 142 | tree = strings.TrimSpace(string(out)) |
| 143 | if !export.ValidObjectID(tree) { |
| 144 | return "", false, fmt.Errorf("the tree of %s is %q", commit, tree) |
| 145 | } |
| 146 | return tree, true, nil |
| 147 | } |
| 148 | |
| 149 | // The bounds on what a page keeps of one record of git's output. |
| 150 | const ( |
| 151 | // maxLine bounds what git prints for one object ID. |
| 152 | maxLine = 1 << 10 |
| 153 | // maxEntryRecord bounds one entry of git ls-tree: its mode, type, |
| 154 | // object ID and size, and its name. git fsck refuses a name longer |
| 155 | // than 4,096 bytes, so the receiver accepts no entry this cuts. |
| 156 | maxEntryRecord = 8 << 10 |
| 157 | // maxLogRecord bounds each of the two records git log gives for one |
| 158 | // commit: its ID and parents, then its date, author and subject. It |
| 159 | // holds a commit's ID and its first MaxParents parents in either |
| 160 | // object format. A page shows maxLogText of the author and subject. |
| 161 | maxLogRecord = 16 << 10 |
| 162 | maxLogText = 1 << 10 |
| 163 | ) |
| 164 | |
| 165 | // The ID and first MaxParents parents of a SHA-256 commit, each followed |
| 166 | // by one byte, fit in maxLogRecord. |
| 167 | const _ = uint(maxLogRecord - 65*(1+MaxParents)) |
| 168 | |
| 169 | // records reads the records of git's output that end in sep, and keeps |
| 170 | // at most max bytes of each. |
| 171 | type records struct { |
| 172 | r *bufio.Reader |
| 173 | sep byte |
| 174 | buf []byte |
| 175 | } |
| 176 | |
| 177 | func newRecords(r io.Reader, sep byte, max int) *records { |
| 178 | return &records{r: bufio.NewReaderSize(r, max), sep: sep} |
| 179 | } |
| 180 | |
| 181 | // next is the next record, without its sep. A record longer than the |
| 182 | // bound is cut to it, with cut set, and the rest of it is read and |
| 183 | // dropped. At the end of the output next fails with io.EOF. On any other |
| 184 | // error, rec is the start of the record the error cut short. |
| 185 | func (rs *records) next() (rec []byte, cut bool, err error) { |
| 186 | line, err := rs.r.ReadSlice(rs.sep) |
| 187 | rs.buf = append(rs.buf[:0], line...) |
| 188 | for err == bufio.ErrBufferFull { |
| 189 | cut = true |
| 190 | _, err = rs.r.ReadSlice(rs.sep) |
| 191 | } |
| 192 | switch { |
| 193 | case err == io.EOF && len(rs.buf) > 0: |
| 194 | return rs.buf, cut, nil // a last record git did not end |
| 195 | case err != nil: |
| 196 | return rs.buf, cut, err |
| 197 | case !cut: |
| 198 | return rs.buf[:len(rs.buf)-1], false, nil |
| 199 | } |
| 200 | return rs.buf, true, nil |
| 201 | } |
| 202 | |
| 203 | // entry is one entry of a tree, as git ls-tree gives it. Size is -1 for |
| 204 | // an entry that is not a blob, and for a blob read without --long. Cut is |
| 205 | // set when the entry's name is longer than a page keeps, and Name is then |
| 206 | // its start alone. |
| 207 | type entry struct { |
| 208 | Mode string |
| 209 | Type string |
| 210 | OID string |
| 211 | Size int64 |
| 212 | Name string |
| 213 | Cut bool |
| 214 | } |
| 215 | |
| 216 | // readTree calls each with the entries of tree, in git's order, until |
| 217 | // each returns false. It reads at most limit bytes of git ls-tree's |
| 218 | // output: complete is false when the listing is longer and was cut there. |
| 219 | // read is how many bytes it read. long gives each blob's size, which git |
| 220 | // looks up for every blob listed, so only a page that shows sizes asks. |
| 221 | func readTree(ctx context.Context, repo, tree string, limit int64, long bool, |
| 222 | each func(entry) bool) (complete bool, read int64, err error) { |
| 223 | complete = true |
| 224 | args := []string{"ls-tree", "-z", tree} |
| 225 | if long { |
| 226 | args = []string{"ls-tree", "-z", "--long", tree} |
| 227 | } |
| 228 | err = export.GitStream(ctx, repo, limit, func(r io.Reader) error { |
| 229 | counted := &counter{r: r} |
| 230 | defer func() { read = counted.n }() |
| 231 | recs := newRecords(counted, 0, maxEntryRecord) |
| 232 | for { |
| 233 | rec, cut, err := recs.next() |
| 234 | switch { |
| 235 | case err == io.EOF: |
| 236 | return nil |
| 237 | case errors.Is(err, export.ErrOutputLimit): |
| 238 | complete = false |
| 239 | return nil |
| 240 | case err != nil: |
| 241 | return err |
| 242 | } |
| 243 | e, err := parseEntry(rec, cut, long) |
| 244 | if err != nil { |
| 245 | return err |
| 246 | } |
| 247 | if !each(e) { |
| 248 | return nil |
| 249 | } |
| 250 | } |
| 251 | }, args...) |
| 252 | return complete, read, err |
| 253 | } |
| 254 | |
| 255 | // counter reads r, and counts the bytes it read. |
| 256 | type counter struct { |
| 257 | r io.Reader |
| 258 | n int64 |
| 259 | } |
| 260 | |
| 261 | func (c *counter) Read(p []byte) (int, error) { |
| 262 | n, err := c.r.Read(p) |
| 263 | c.n += int64(n) |
| 264 | return n, err |
| 265 | } |
| 266 | |
| 267 | // parseEntry is one record of git ls-tree: mode, type, object ID, and, |
| 268 | // when long, size, then a tab and the name. |
| 269 | func parseEntry(rec []byte, cut, long bool) (entry, error) { |
| 270 | meta, name, ok := bytes.Cut(rec, []byte{'\t'}) |
| 271 | f := strings.Fields(string(meta)) |
| 272 | fields := 3 |
| 273 | if long { |
| 274 | fields = 4 |
| 275 | } |
| 276 | if !ok || len(f) != fields || !export.ValidObjectID(f[2]) { |
| 277 | return entry{}, fmt.Errorf("git ls-tree gave %q", rec) |
| 278 | } |
| 279 | e := entry{Mode: f[0], Type: f[1], OID: f[2], Size: -1, Name: string(name), Cut: cut} |
| 280 | if long && f[3] != "-" { |
| 281 | n, err := strconv.ParseInt(f[3], 10, 64) |
| 282 | if err != nil || n < 0 { |
| 283 | return entry{}, fmt.Errorf("git ls-tree gave %q", rec) |
| 284 | } |
| 285 | e.Size = n |
| 286 | } |
| 287 | return e, nil |
| 288 | } |
| 289 | |
| 290 | // resolve walks path down from the tree root, one tree entry at a time, |
| 291 | // and gives the entry it ends at, with its size when it is a blob. ok is |
| 292 | // false when a segment names no entry, or a segment other than the last |
| 293 | // names something that is not a tree. Each directory is read only until |
| 294 | // the segment's entry, without sizes, and all of them together no further |
| 295 | // than MaxRead bytes of git's output. So an entry past MaxRead along the |
| 296 | // path is not found, however the path's directories share it. |
| 297 | func resolve(ctx context.Context, repo, root string, path []string) (e entry, ok bool, err error) { |
| 298 | e = entry{Mode: "040000", Type: "tree", OID: root, Size: -1} |
| 299 | left := int64(MaxRead) |
| 300 | for _, name := range path { |
| 301 | if e.Type != "tree" { |
| 302 | return entry{}, false, nil |
| 303 | } |
| 304 | found := false |
| 305 | _, read, err := readTree(ctx, repo, e.OID, left, false, func(c entry) bool { |
| 306 | if !c.Cut && c.Name == name { |
| 307 | e, found = c, true |
| 308 | } |
| 309 | return !found |
| 310 | }) |
| 311 | if left -= read; err != nil || !found { |
| 312 | return entry{}, false, err |
| 313 | } |
| 314 | } |
| 315 | if e.Type == "blob" { |
| 316 | out, err := export.Git(ctx, repo, maxLine, "cat-file", "-s", e.OID) |
| 317 | if err != nil { |
| 318 | return entry{}, false, err |
| 319 | } |
| 320 | n, err := strconv.ParseInt(strings.TrimSpace(string(out)), 10, 64) |
| 321 | if err != nil || n < 0 { |
| 322 | return entry{}, false, fmt.Errorf("git cat-file -s %s gave %q", e.OID, out) |
| 323 | } |
| 324 | e.Size = n |
| 325 | } |
| 326 | return e, true, nil |
| 327 | } |
| 328 | |
| 329 | // Entry modes git gives for a symbolic link and a submodule. |
| 330 | const ( |
| 331 | modeSymlink = "120000" |
| 332 | modeSubmodule = "160000" |
| 333 | ) |
| 334 | |
| 335 | // shown is how a page shows a blob: its text, or a notice that says why |
| 336 | // it is not shown. A symbolic link is shown as its target and is never |
| 337 | // followed. |
| 338 | func shown(ctx context.Context, repo string, e entry) (text, notice string, err error) { |
| 339 | if e.Size > MaxFile { |
| 340 | return "", fmt.Sprintf("This file is %s, larger than the %s a page shows.", size(e.Size), size(MaxFile)), nil |
| 341 | } |
| 342 | data, err := export.Git(ctx, repo, MaxFile, "cat-file", "blob", e.OID) |
| 343 | if err != nil { |
| 344 | return "", "", err |
| 345 | } |
| 346 | if e.Mode == modeSymlink { |
| 347 | return "", "A symbolic link to " + oneLine(string(data)) + ". It is not followed.", nil |
| 348 | } |
| 349 | if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) { |
| 350 | return "", fmt.Sprintf("This file is binary, %s, and is not shown.", size(e.Size)), nil |
| 351 | } |
| 352 | return string(data), "", nil |
| 353 | } |
| 354 | |
| 355 | // dirPage is one directory of a commit. |
| 356 | type dirPage struct { |
| 357 | Project string |
| 358 | Commit string |
| 359 | Short string |
| 360 | AtTip bool |
| 361 | TipURL string |
| 362 | LogURL string |
| 363 | // ArchiveURL is the commit's archive, which the page links to. |
| 364 | ArchiveURL string |
| 365 | Crumbs []link |
| 366 | Entries []dirEntry |
| 367 | Omitted int |
| 368 | // Partial is set when the directory is larger than a page reads, |
| 369 | // and only its start is listed. |
| 370 | Partial bool |
| 371 | Readme *readme |
| 372 | } |
| 373 | |
| 374 | type dirEntry struct { |
| 375 | Name string |
| 376 | URL string |
| 377 | Kind string |
| 378 | Size string |
| 379 | } |
| 380 | |
| 381 | type readme struct { |
| 382 | Name string |
| 383 | URL string |
| 384 | Text string |
| 385 | Notice string |
| 386 | // Partial is set when the README is longer than a page shows. |
| 387 | Partial bool |
| 388 | // Doc is the README rendered, when it is Markdown. |
| 389 | Doc *document |
| 390 | } |
| 391 | |
| 392 | // document is a Markdown file rendered, and the contents list of a long |
| 393 | // one. |
| 394 | type document struct { |
| 395 | HTML template.HTML |
| 396 | Contents []contentsEntry |
| 397 | } |
| 398 | |
| 399 | type contentsEntry struct { |
| 400 | Text string |
| 401 | URL string |
| 402 | Level int |
| 403 | } |
| 404 | |
| 405 | // isMarkdown reports whether a file's name says it is Markdown: it ends |
| 406 | // in .md or .markdown, in any case. |
| 407 | func isMarkdown(name string) bool { |
| 408 | n := strings.ToLower(name) |
| 409 | return strings.HasSuffix(n, ".md") || strings.HasSuffix(n, ".markdown") |
| 410 | } |
| 411 | |
| 412 | // markdown renders text, a file of dir in commit, with its relative links |
| 413 | // resolved within the project's source at that commit. A document with |
| 414 | // at least four headings at levels 2 to 4 gets a contents list of them. |
| 415 | // The rendered document is at most MaxShown bytes, the most a page spends |
| 416 | // on a file's text, and cut is set when it holds only the start of text. |
| 417 | // |
| 418 | // It waits for a rendering slot while it holds its git slot, and gives |
| 419 | // the git slot back once it has one: rendering runs no git. It renders |
| 420 | // under the request's context. |
| 421 | func (q *request) markdown(text, project, commit string, dir []string) (d *document, cut bool, err error) { |
| 422 | wait := q.ctx |
| 423 | if q.git != nil { |
| 424 | wait = q.git |
| 425 | } |
| 426 | select { |
| 427 | case q.s.renders <- struct{}{}: |
| 428 | case <-wait.Done(): |
| 429 | return nil, false, fmt.Errorf("waiting to render Markdown: %w", wait.Err()) |
| 430 | } |
| 431 | defer func() { <-q.s.renders }() |
| 432 | q.giveSlot() |
| 433 | doc, err := markdown.Render(q.ctx, []byte(text), markdown.Options{ |
| 434 | Resolve: resolver(q.idx.bases[project], commit, dir), MaxOutput: MaxShown}) |
| 435 | if err != nil { |
| 436 | return nil, false, fmt.Errorf("rendering Markdown: %w", err) |
| 437 | } |
| 438 | d = &document{HTML: doc.HTML} |
| 439 | for _, h := range doc.Headings { |
| 440 | if h.Level >= 2 && h.Level <= 4 && h.ID != "" { |
| 441 | d.Contents = append(d.Contents, contentsEntry{oneLine(h.Text), "#" + (&url.URL{Fragment: h.ID}).EscapedFragment(), h.Level}) |
| 442 | } |
| 443 | } |
| 444 | if len(d.Contents) < 4 { |
| 445 | d.Contents = nil |
| 446 | } |
| 447 | return d, doc.Truncated, nil |
| 448 | } |
| 449 | |
| 450 | // resolver resolves a relative link of a document in dir, in commit, to |
| 451 | // the page of its target at the same commit. A path that starts with / |
| 452 | // starts at the repository's root. A fragment is kept, and a link that is |
| 453 | // a fragment alone stays one. A path that climbs above the root, or that |
| 454 | // is no path a source route takes, is refused. The resolver runs no git: |
| 455 | // a link to a directory goes to the blob route, which redirects it to |
| 456 | // the tree route, and one that ends in / goes to the tree route. |
| 457 | func resolver(base, commit string, dir []string) func(string) (string, bool) { |
| 458 | return func(dest string) (string, bool) { |
| 459 | rest, frag, hasFrag := strings.Cut(dest, "#") |
| 460 | if hasFrag { |
| 461 | f, err := url.PathUnescape(frag) |
| 462 | if err != nil { |
| 463 | return "", false |
| 464 | } |
| 465 | frag = "#" + (&url.URL{Fragment: f}).EscapedFragment() |
| 466 | } |
| 467 | rest, _, _ = strings.Cut(rest, "?") |
| 468 | if rest == "" { |
| 469 | return frag, hasFrag |
| 470 | } |
| 471 | path := slices.Clone(dir) |
| 472 | if strings.HasPrefix(rest, "/") { |
| 473 | path, rest = nil, rest[1:] |
| 474 | } |
| 475 | segs := strings.Split(rest, "/") |
| 476 | for i, seg := range segs { |
| 477 | seg, err := url.PathUnescape(seg) |
| 478 | switch { |
| 479 | case err != nil: |
| 480 | return "", false |
| 481 | case seg == "" && i == len(segs)-1, seg == ".": |
| 482 | case seg == "..": |
| 483 | if len(path) == 0 { |
| 484 | return "", false |
| 485 | } |
| 486 | path = path[:len(path)-1] |
| 487 | default: |
| 488 | path = append(path, seg) |
| 489 | } |
| 490 | } |
| 491 | if !validPath(path) { |
| 492 | return "", false |
| 493 | } |
| 494 | if len(path) == 0 || strings.HasSuffix(rest, "/") { |
| 495 | return treeURL(base, commit, path) + frag, true |
| 496 | } |
| 497 | return blobURL(base, commit, path) + frag, true |
| 498 | } |
| 499 | } |
| 500 | |
| 501 | func (q *request) dir(ctx context.Context, p *export.Project, repo, commit string, path []string) error { |
| 502 | root, ok, err := commitTree(ctx, p, repo, commit) |
| 503 | if err != nil || !ok { |
| 504 | q.missing(err) |
| 505 | return nil |
| 506 | } |
| 507 | e, ok, err := resolve(ctx, repo, root, path) |
| 508 | if err == nil && ok && e.Type == "blob" && len(path) > 0 { |
| 509 | q.redirect(blobURL(q.idx.bases[p.Name], commit, path)) // a file, named as a directory |
| 510 | return nil |
| 511 | } |
| 512 | if err != nil || !ok || e.Type != "tree" { |
| 513 | q.missing(err) |
| 514 | return nil |
| 515 | } |
| 516 | // Directories come first, then everything else, each in git's |
| 517 | // order. Keeping MaxEntries of each keeps the first MaxEntries of |
| 518 | // that order, however many entries the tree holds. |
| 519 | var dirs, others []entry |
| 520 | read, rank := 0, -1 |
| 521 | var rm entry |
| 522 | complete, _, err := readTree(ctx, repo, e.OID, MaxRead, true, func(c entry) bool { |
| 523 | read++ |
| 524 | switch { |
| 525 | case c.Type == "tree" && len(dirs) < MaxEntries: |
| 526 | dirs = append(dirs, c) |
| 527 | case c.Type != "tree" && len(others) < MaxEntries: |
| 528 | others = append(others, c) |
| 529 | } |
| 530 | if r := readmeRank(c); r >= 0 && (rank < 0 || r < rank) { |
| 531 | rm, rank = c, r |
| 532 | } |
| 533 | return true |
| 534 | }) |
| 535 | if err != nil { |
| 536 | return err |
| 537 | } |
| 538 | entries := append(dirs, others...) |
| 539 | if len(entries) > MaxEntries { |
| 540 | entries = entries[:MaxEntries] |
| 541 | } |
| 542 | page := dirPage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip, |
| 543 | TipURL: treeURL(q.idx.bases[p.Name], p.SourceTip, nil), LogURL: logURL(q.idx.bases[p.Name], commit), |
| 544 | ArchiveURL: archiveURL(q.idx.bases[p.Name], commit), Crumbs: crumbs(p.Name, q.idx.bases[p.Name], commit, path), |
| 545 | Omitted: read - len(entries), Partial: !complete} |
| 546 | for _, c := range entries { |
| 547 | at := append(append([]string{}, path...), c.Name) |
| 548 | d := dirEntry{Name: oneLine(c.Name)} |
| 549 | switch { |
| 550 | case c.Type == "tree": |
| 551 | d.Kind, d.URL = "directory", treeURL(q.idx.bases[p.Name], commit, at) |
| 552 | case c.Mode == modeSubmodule || c.Type == "commit": |
| 553 | d.Kind = "submodule at " + c.OID[:12] |
| 554 | case c.Mode == modeSymlink: |
| 555 | d.Kind, d.URL = "symbolic link", blobURL(q.idx.bases[p.Name], commit, at) |
| 556 | default: |
| 557 | d.Kind, d.URL, d.Size = "file", blobURL(q.idx.bases[p.Name], commit, at), size(c.Size) |
| 558 | } |
| 559 | if c.Cut { |
| 560 | d.Name += "…" |
| 561 | } |
| 562 | if c.Cut || !validPath(at) { |
| 563 | d.URL = "" // a name no route takes is listed and not linked |
| 564 | } |
| 565 | page.Entries = append(page.Entries, d) |
| 566 | } |
| 567 | if rank >= 0 { |
| 568 | text, notice, err := shown(ctx, repo, rm) |
| 569 | if err != nil { |
| 570 | return err |
| 571 | } |
| 572 | lines, _, partial := excerpt(trimEnd(text), 1) |
| 573 | at := append(append([]string{}, path...), rm.Name) |
| 574 | page.Readme = &readme{Name: oneLine(rm.Name), URL: blobURL(q.idx.bases[p.Name], commit, at), |
| 575 | Text: strings.Join(lines, "\n"), Notice: notice, Partial: partial} |
| 576 | if notice == "" && isMarkdown(rm.Name) { |
| 577 | doc, cut, err := q.markdown(page.Readme.Text, p.Name, commit, path) |
| 578 | if err != nil { |
| 579 | return err |
| 580 | } |
| 581 | page.Readme.Doc = doc |
| 582 | page.Readme.Partial = page.Readme.Partial || cut |
| 583 | } |
| 584 | } |
| 585 | title := p.Name + " at " + commit[:12] |
| 586 | if len(path) > 0 { |
| 587 | title = strings.Join(path, "/") + " · " + title |
| 588 | } |
| 589 | q.page(http.StatusOK, "tree", title, page) |
| 590 | return nil |
| 591 | } |
| 592 | |
| 593 | // readmeRank is how a directory's README is chosen from its entries: |
| 594 | // README.md, README or README.txt, in that order, and otherwise the first |
| 595 | // file whose name is README in any case, with any extension. A lower rank |
| 596 | // is chosen first. It is -1 for an entry that is no README. |
| 597 | func readmeRank(e entry) int { |
| 598 | if e.Type != "blob" || e.Mode == modeSymlink || e.Cut { |
| 599 | return -1 |
| 600 | } |
| 601 | switch e.Name { |
| 602 | case "README.md": |
| 603 | return 0 |
| 604 | case "README": |
| 605 | return 1 |
| 606 | case "README.txt": |
| 607 | return 2 |
| 608 | } |
| 609 | if base, _, _ := strings.Cut(strings.ToLower(e.Name), "."); base == "readme" { |
| 610 | return 3 |
| 611 | } |
| 612 | return -1 |
| 613 | } |
| 614 | |
| 615 | // filePage is one file of a commit. |
| 616 | type filePage struct { |
| 617 | Project string |
| 618 | Commit string |
| 619 | Short string |
| 620 | AtTip bool |
| 621 | TipURL string |
| 622 | LogURL string |
| 623 | Crumbs []link |
| 624 | Name string |
| 625 | Size string |
| 626 | Lines []string |
| 627 | // Partial says where the page stops, when the file is longer than a |
| 628 | // page shows. |
| 629 | Partial string |
| 630 | Notice string |
| 631 | // Doc is the file rendered, when it is Markdown and shown so. Plain |
| 632 | // and Rendered link the file's two views, when it has two. |
| 633 | Doc *document |
| 634 | Plain string |
| 635 | Rendered string |
| 636 | } |
| 637 | |
| 638 | func (q *request) file(ctx context.Context, p *export.Project, repo, commit string, path []string) error { |
| 639 | root, ok, err := commitTree(ctx, p, repo, commit) |
| 640 | if err != nil || !ok { |
| 641 | q.missing(err) |
| 642 | return nil |
| 643 | } |
| 644 | e, ok, err := resolve(ctx, repo, root, path) |
| 645 | if err == nil && ok && e.Type == "tree" { |
| 646 | q.redirect(treeURL(q.idx.bases[p.Name], commit, path)) // a directory, named as a file |
| 647 | return nil |
| 648 | } |
| 649 | if err != nil || !ok || e.Type != "blob" { |
| 650 | q.missing(err) |
| 651 | return nil |
| 652 | } |
| 653 | text, notice, err := shown(ctx, repo, e) |
| 654 | if err != nil { |
| 655 | return err |
| 656 | } |
| 657 | page := filePage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip, |
| 658 | TipURL: treeURL(q.idx.bases[p.Name], p.SourceTip, nil), LogURL: logURL(q.idx.bases[p.Name], commit), |
| 659 | Crumbs: crumbs(p.Name, q.idx.bases[p.Name], commit, path), Name: oneLine(path[len(path)-1]), |
| 660 | Size: size(e.Size), Notice: notice} |
| 661 | if notice == "" { |
| 662 | md := isMarkdown(path[len(path)-1]) |
| 663 | plain := !md || q.r.URL.Query().Get("plain") == "1" |
| 664 | cost := rowCost |
| 665 | if !plain { |
| 666 | cost = 1 |
| 667 | } |
| 668 | lines, total, partial := excerpt(text, cost) |
| 669 | if partial { |
| 670 | page.Partial = fmt.Sprintf("This file is longer than a page shows. The page stops at line %d of %d.", len(lines), total) |
| 671 | } |
| 672 | here := blobURL(q.idx.bases[p.Name], commit, path) |
| 673 | switch { |
| 674 | case plain && md: |
| 675 | page.Lines, page.Rendered = lines, here |
| 676 | case plain: |
| 677 | page.Lines = lines |
| 678 | default: |
| 679 | doc, cut, err := q.markdown(strings.Join(lines, "\n"), p.Name, commit, path[:len(path)-1]) |
| 680 | if err != nil { |
| 681 | return err |
| 682 | } |
| 683 | page.Doc, page.Plain = doc, here+"?plain=1" |
| 684 | if cut { |
| 685 | page.Partial = "This file is longer than a page shows, and only its start is shown." |
| 686 | } |
| 687 | } |
| 688 | } |
| 689 | q.page(http.StatusOK, "blob", strings.Join(path, "/")+" · "+p.Name+" at "+commit[:12], page) |
| 690 | return nil |
| 691 | } |
| 692 | |
| 693 | // crumbs are the links from the project's root down to path. The last is |
| 694 | // the page itself and has no link. |
| 695 | func crumbs(project, base, commit string, path []string) []link { |
| 696 | out := []link{{project, treeURL(base, commit, nil)}} |
| 697 | for i, name := range path { |
| 698 | out = append(out, link{oneLine(name), treeURL(base, commit, path[:i+1])}) |
| 699 | } |
| 700 | out[len(out)-1].URL = "" |
| 701 | return out |
| 702 | } |
| 703 | |
| 704 | // rowCost is what a file page's markup takes for each line it shows, |
| 705 | // besides the line's text: a table row, an anchor and the line number. |
| 706 | // It is an upper bound for line numbers of up to seven digits. |
| 707 | const rowCost = 100 |
| 708 | |
| 709 | // excerpt is the start of text that a page shows: whole lines, at most |
| 710 | // MaxLines of them, while the bytes they take once escaped, with cost |
| 711 | // more for each line, stay within MaxShown. A line that would pass |
| 712 | // MaxShown is cut to fit, and ends the excerpt. total is how many lines |
| 713 | // text holds, and partial is set when the excerpt holds less than all of |
| 714 | // it. |
| 715 | func excerpt(text string, cost int) (lines []string, total int, partial bool) { |
| 716 | text = strings.TrimSuffix(text, "\n") |
| 717 | total = strings.Count(text, "\n") + 1 |
| 718 | budget := MaxShown |
| 719 | for rest := text; len(lines) < MaxLines; { |
| 720 | line, more, found := strings.Cut(rest, "\n") |
| 721 | n := cost + escapedSize(line) |
| 722 | if n > budget { |
| 723 | if room := budget - cost; room > 0 { |
| 724 | lines = append(lines, cutEscaped(line, room)) |
| 725 | } |
| 726 | return lines, total, true |
| 727 | } |
| 728 | budget -= n |
| 729 | lines = append(lines, line) |
| 730 | if !found { |
| 731 | return lines, total, false |
| 732 | } |
| 733 | rest = more |
| 734 | } |
| 735 | return lines, total, true |
| 736 | } |
| 737 | |
| 738 | // escapedSize is an upper bound on the bytes html/template writes for s |
| 739 | // as text: five for each character it escapes, and one for any other |
| 740 | // byte. |
| 741 | func escapedSize(s string) int { |
| 742 | n := len(s) |
| 743 | for i := 0; i < len(s); i++ { |
| 744 | switch s[i] { |
| 745 | case '"', '\'', '&', '+', '<', '>', 0: |
| 746 | n += 4 |
| 747 | } |
| 748 | } |
| 749 | return n |
| 750 | } |
| 751 | |
| 752 | // cutEscaped is the longest start of s that ends on a whole character |
| 753 | // and that escapedSize counts at no more than room bytes. |
| 754 | func cutEscaped(s string, room int) string { |
| 755 | n := 0 |
| 756 | for i := 0; i < len(s); i++ { |
| 757 | if n += escapedSize(s[i : i+1]); n > room { |
| 758 | for i > 0 && !utf8.RuneStart(s[i]) { |
| 759 | i-- |
| 760 | } |
| 761 | return s[:i] |
| 762 | } |
| 763 | } |
| 764 | return s |
| 765 | } |
| 766 | |
| 767 | // clip is s cut to at most n bytes, on a whole character, and marked as |
| 768 | // cut when it is. |
| 769 | func clip(s string, n int) string { |
| 770 | if len(s) <= n { |
| 771 | return s |
| 772 | } |
| 773 | for n > 0 && !utf8.RuneStart(s[n]) { |
| 774 | n-- |
| 775 | } |
| 776 | return s[:n] + "…" |
| 777 | } |
| 778 | |
| 779 | // logPage is one page of the history that ends at a commit. |
| 780 | type logPage struct { |
| 781 | Project string |
| 782 | Commit string |
| 783 | Short string |
| 784 | AtTip bool |
| 785 | Commits []logEntry |
| 786 | // Partial is set when the page's commits are larger than a page |
| 787 | // reads, and the page ends early. |
| 788 | Partial bool |
| 789 | // Crowded is set when the page ends early, before a merge that would |
| 790 | // leave more than MaxLeftToShow commits to show. |
| 791 | Crowded bool |
| 792 | Newest string |
| 793 | Older string |
| 794 | // Others link the history from each commit the page leaves to show |
| 795 | // past the MaxFrontier its Older link starts from. Lines is how many |
| 796 | // it leaves to show in all, when there are others. |
| 797 | Others []link |
| 798 | Lines int |
| 799 | } |
| 800 | |
| 801 | type logEntry struct { |
| 802 | Commit string |
| 803 | Short string |
| 804 | URL string |
| 805 | Subject string |
| 806 | Author string |
| 807 | Date string |
| 808 | // Parents is set when the commit has more than MaxParents parents, |
| 809 | // and says that only the first are followed. |
| 810 | Parents string |
| 811 | } |
| 812 | |
| 813 | // log serves one page of the history that ends at commit: LogPage |
| 814 | // commits, newest first, and none before any of its children, as git log |
| 815 | // --date-order gives them. The first page starts from commit, and an |
| 816 | // older page from the commits its ?from= names, each of which commit must |
| 817 | // reach. |
| 818 | // |
| 819 | // A page's older pages start from what the page leaves to show: the |
| 820 | // commits it started from and the parents of each commit it shows, less |
| 821 | // the commits it shows. Since no page shows a commit before its children, |
| 822 | // those commits reach every commit of the history that no page before |
| 823 | // showed, and none that one did. Each page asks git for LogPage commits |
| 824 | // however old it is. |
| 825 | // |
| 826 | // The Older link starts from at most MaxFrontier of those commits, and |
| 827 | // each of the rest has a link of its own. A page leaves at most |
| 828 | // MaxLeftToShow, and ends early before a merge that would leave more. So |
| 829 | // the links from a page reach every older commit of the history, merges |
| 830 | // and all, along the first MaxParents parents of each commit. A page |
| 831 | // marks a merge that has more. The Older links alone show each commit |
| 832 | // once while no page leaves more than MaxFrontier; the history from each |
| 833 | // other link may show some again. |
| 834 | func (q *request) log(ctx context.Context, p *export.Project, repo, commit string) error { |
| 835 | if _, ok, err := commitTree(ctx, p, repo, commit); err != nil || !ok { |
| 836 | q.missing(err) |
| 837 | return nil |
| 838 | } |
| 839 | page := logPage{Project: p.Name, Commit: commit, Short: commit[:12], AtTip: commit == p.SourceTip} |
| 840 | from := []string{commit} |
| 841 | if query := q.r.URL.Query(); query.Has("from") { |
| 842 | ids, ok := frontier(query["from"]) |
| 843 | if !ok { |
| 844 | q.notFound() |
| 845 | return nil |
| 846 | } |
| 847 | if ok, err := export.Reachable(ctx, repo, commit, ids...); err != nil || !ok { |
| 848 | q.missing(err) |
| 849 | return nil |
| 850 | } |
| 851 | from, page.Newest = ids, logURL(q.idx.bases[p.Name], commit) |
| 852 | } |
| 853 | // older is what the older page starts from. git gives no commit |
| 854 | // before its children, so no parent added is a commit shown already. |
| 855 | older := map[string]bool{} |
| 856 | for _, id := range from { |
| 857 | older[id] = true |
| 858 | } |
| 859 | // git gives two records for each commit, so that a long line of |
| 860 | // parents cuts neither the commit's ID nor its subject. |
| 861 | args := []string{"log", "--date-order", "--no-mailmap", "--no-notes", "--no-show-signature", |
| 862 | "--no-decorate", "--no-color", "-z", "--format=%H%n%P%x00%aI%n%an%n%s", |
| 863 | "--max-count=" + strconv.Itoa(LogPage)} |
| 864 | args = append(append(args, from...), "--") |
| 865 | // A listing cut at MaxRead ends the page at the commit it cut, shown |
| 866 | // as far as it was read once its ID and the parents a page follows |
| 867 | // were read whole. |
| 868 | err := export.GitStream(ctx, repo, MaxRead, func(r io.Reader) error { |
| 869 | recs := newRecords(r, 0, maxLogRecord) |
| 870 | for len(page.Commits) < LogPage { |
| 871 | rec, cut, err := recs.next() |
| 872 | if err == io.EOF { |
| 873 | return nil |
| 874 | } |
| 875 | limited := errors.Is(err, export.ErrOutputLimit) |
| 876 | if err != nil && !limited { |
| 877 | return err |
| 878 | } |
| 879 | id, parents, more, ok := parentsOf(string(rec), !cut && !limited) |
| 880 | if !ok && len(page.Commits) == 0 { |
| 881 | return fmt.Errorf("git log gave a first commit whose ID and parents were not read: %q", clip(string(rec), maxLogText)) |
| 882 | } |
| 883 | if !ok { |
| 884 | page.Partial = true // the older page starts from the commit |
| 885 | return nil |
| 886 | } |
| 887 | if len(page.Commits) > 0 && leftAfter(older, id, parents) > MaxLeftToShow { |
| 888 | page.Crowded = true // the older pages start from the commit |
| 889 | return nil |
| 890 | } |
| 891 | var meta []byte |
| 892 | if !limited { |
| 893 | meta, _, err = recs.next() |
| 894 | if err == io.EOF { |
| 895 | return fmt.Errorf("git log gave no date, author or subject for %s", id) |
| 896 | } |
| 897 | if limited = errors.Is(err, export.ErrOutputLimit); err != nil && !limited { |
| 898 | return err |
| 899 | } |
| 900 | } |
| 901 | e := logEntryOf(q.idx.bases[p.Name], id, string(meta)) |
| 902 | if more { |
| 903 | e.Parents = fmt.Sprintf("This merge has more than %d parents. Older pages follow its first %d.", MaxParents, MaxParents) |
| 904 | } |
| 905 | page.Commits = append(page.Commits, e) |
| 906 | delete(older, id) |
| 907 | for _, parent := range parents { |
| 908 | older[parent] = true |
| 909 | } |
| 910 | if limited { |
| 911 | page.Partial = true |
| 912 | return nil |
| 913 | } |
| 914 | } |
| 915 | return nil |
| 916 | }, args...) |
| 917 | if err != nil { |
| 918 | return err |
| 919 | } |
| 920 | ids := slices.Sorted(maps.Keys(older)) |
| 921 | if len(ids) > MaxFrontier { |
| 922 | for _, id := range ids[MaxFrontier:] { |
| 923 | page.Others = append(page.Others, link{id[:12], logURL(q.idx.bases[p.Name], commit) + "?from=" + id}) |
| 924 | } |
| 925 | ids, page.Lines = ids[:MaxFrontier], len(ids) |
| 926 | } |
| 927 | if len(ids) > 0 { |
| 928 | page.Older = logURL(q.idx.bases[p.Name], commit) + "?from=" + strings.Join(ids, ",") |
| 929 | } |
| 930 | q.page(http.StatusOK, "log", "History of "+p.Name+" at "+commit[:12], page) |
| 931 | return nil |
| 932 | } |
| 933 | |
| 934 | // A page always shows its first commit. That leaves at most the other |
| 935 | // MaxFrontier-1 commits it started from and the commit's MaxParents |
| 936 | // parents, which must be within MaxLeftToShow. |
| 937 | const _ = uint(MaxLeftToShow - (MaxFrontier - 1 + MaxParents)) |
| 938 | |
| 939 | // leftAfter is how many commits a page leaves to show once it shows |
| 940 | // commit, when it leaves left before: commit is no longer left, and its |
| 941 | // parents are. |
| 942 | func leftAfter(left map[string]bool, commit string, parents []string) int { |
| 943 | n := len(left) |
| 944 | if left[commit] { |
| 945 | n-- |
| 946 | } |
| 947 | for _, parent := range parents { |
| 948 | if !left[parent] { |
| 949 | n++ |
| 950 | } |
| 951 | } |
| 952 | return n |
| 953 | } |
| 954 | |
| 955 | // frontier is the commits a ?from= names: one value, of 1 to MaxFrontier |
| 956 | // object IDs, separated by commas, in ascending order and none twice, so |
| 957 | // each page has one address. ok is false for anything else. Whether the |
| 958 | // page's commit reaches each of them is Reachable's to say. |
| 959 | func frontier(values []string) (ids []string, ok bool) { |
| 960 | if len(values) != 1 { |
| 961 | return nil, false |
| 962 | } |
| 963 | ids = strings.Split(values[0], ",") |
| 964 | if len(ids) > MaxFrontier { |
| 965 | return nil, false |
| 966 | } |
| 967 | for i, id := range ids { |
| 968 | if !export.ValidObjectID(id) || i > 0 && ids[i-1] >= id { |
| 969 | return nil, false |
| 970 | } |
| 971 | } |
| 972 | return ids, true |
| 973 | } |
| 974 | |
| 975 | // parentsOf is the first record git log gives for a commit: its ID, then |
| 976 | // its parents on one line. whole is false when the record was cut, and |
| 977 | // its last parent may then be cut too. parents is the commit's first |
| 978 | // MaxParents parents, and more is set when it has others. ok is false |
| 979 | // when the record holds no whole ID, or a parent that is not an ID of |
| 980 | // the commit's length, or when it was cut before the parents a page |
| 981 | // follows. |
| 982 | func parentsOf(rec string, whole bool) (id string, parents []string, more, ok bool) { |
| 983 | id, line, found := strings.Cut(rec, "\n") |
| 984 | if !found || !export.ValidObjectID(id) { |
| 985 | return "", nil, false, false |
| 986 | } |
| 987 | f := strings.Fields(line) |
| 988 | if !whole && len(f) <= MaxParents { |
| 989 | return "", nil, false, false |
| 990 | } |
| 991 | parents, more = f[:min(len(f), MaxParents)], len(f) > MaxParents |
| 992 | for _, parent := range parents { |
| 993 | if len(parent) != len(id) || !export.ValidObjectID(parent) { |
| 994 | return "", nil, false, false |
| 995 | } |
| 996 | } |
| 997 | return id, parents, more, true |
| 998 | } |
| 999 | |
| 1000 | // logEntryOf is a commit's entry on a page: its ID, and the second record |
| 1001 | // git log gives for it, its author date, author and subject, each on a |
| 1002 | // line of its own. A record cut short is shown as far as it goes. |
| 1003 | func logEntryOf(base, id, rec string) logEntry { |
| 1004 | f := strings.SplitN(rec, "\n", 3) |
| 1005 | for len(f) < 3 { |
| 1006 | f = append(f, "") |
| 1007 | } |
| 1008 | return logEntry{Commit: id, Short: id[:12], URL: treeURL(base, id, nil), Date: stampOf(f[0]), |
| 1009 | Author: clip(oneLine(f[1]), maxLogText), Subject: clip(oneLine(f[2]), maxLogText)} |
| 1010 | } |
| 1011 | |
| 1012 | // missing answers a source route whose commit or path names nothing it |
| 1013 | // serves: the one 404, or the one 500 when git failed. |
| 1014 | func (q *request) missing(err error) { |
| 1015 | if err != nil { |
| 1016 | q.fail(err) |
| 1017 | return |
| 1018 | } |
| 1019 | q.notFound() |
| 1020 | } |
| 1021 | |
| 1022 | // oneLine is text from a repository as a page shows it on one line: |
| 1023 | // valid UTF-8, with control and bidirectional formatting characters |
| 1024 | // replaced, so a name cannot reorder or hide the text around it. |
| 1025 | func oneLine(s string) string { |
| 1026 | return strings.Map(func(r rune) rune { |
| 1027 | if unicode.IsControl(r) || unicode.Is(unicode.Bidi_Control, r) { |
| 1028 | return '�' |
| 1029 | } |
| 1030 | return r |
| 1031 | }, strings.ToValidUTF8(s, "�")) |
| 1032 | } |
| 1033 | |
| 1034 | // size is a byte count in words. |
| 1035 | func size(n int64) string { |
| 1036 | switch { |
| 1037 | case n < 0: |
| 1038 | return "" |
| 1039 | case n < 1<<10: |
| 1040 | return count(int(n), "byte") |
| 1041 | case n < 1<<20: |
| 1042 | return fmt.Sprintf("%.1f KiB", float64(n)/(1<<10)) |
| 1043 | case n < 1<<30: |
| 1044 | return fmt.Sprintf("%.1f MiB", float64(n)/(1<<20)) |
| 1045 | } |
| 1046 | return fmt.Sprintf("%.1f GiB", float64(n)/(1<<30)) |
| 1047 | } |