|
| 1 | +// Copyright 2024 The Gitea Authors. All rights reserved. |
| 2 | +// SPDX-License-Identifier: MIT |
| 3 | + |
| 4 | +package git |
| 5 | + |
| 6 | +import ( |
| 7 | + "bytes" |
| 8 | + "fmt" |
| 9 | + "strconv" |
| 10 | + "strings" |
| 11 | + |
| 12 | + "code.gitea.io/gitea/modules/optional" |
| 13 | +) |
| 14 | + |
| 15 | +var sepSpace = []byte{' '} |
| 16 | + |
| 17 | +type LsTreeEntry struct { |
| 18 | + ID ObjectID |
| 19 | + EntryMode EntryMode |
| 20 | + Name string |
| 21 | + Size optional.Option[int64] |
| 22 | +} |
| 23 | + |
| 24 | +func parseLsTreeLine(line []byte) (*LsTreeEntry, error) { |
| 25 | + // expect line to be of the form: |
| 26 | + // <mode> <type> <sha> <space-padded-size>\t<filename> |
| 27 | + // <mode> <type> <sha>\t<filename> |
| 28 | + |
| 29 | + var err error |
| 30 | + posTab := bytes.IndexByte(line, '\t') |
| 31 | + if posTab == -1 { |
| 32 | + return nil, fmt.Errorf("invalid ls-tree output (no tab): %q", line) |
| 33 | + } |
| 34 | + |
| 35 | + entry := new(LsTreeEntry) |
| 36 | + |
| 37 | + entryAttrs := line[:posTab] |
| 38 | + entryName := line[posTab+1:] |
| 39 | + |
| 40 | + entryMode, entryAttrs, _ := bytes.Cut(entryAttrs, sepSpace) |
| 41 | + _ /* entryType */, entryAttrs, _ = bytes.Cut(entryAttrs, sepSpace) // the type is not used, the mode is enough to determine the type |
| 42 | + entryObjectID, entryAttrs, _ := bytes.Cut(entryAttrs, sepSpace) |
| 43 | + if len(entryAttrs) > 0 { |
| 44 | + entrySize := entryAttrs // the last field is the space-padded-size |
| 45 | + size, _ := strconv.ParseInt(strings.TrimSpace(string(entrySize)), 10, 64) |
| 46 | + entry.Size = optional.Some(size) |
| 47 | + } |
| 48 | + |
| 49 | + switch string(entryMode) { |
| 50 | + case "100644": |
| 51 | + entry.EntryMode = EntryModeBlob |
| 52 | + case "100755": |
| 53 | + entry.EntryMode = EntryModeExec |
| 54 | + case "120000": |
| 55 | + entry.EntryMode = EntryModeSymlink |
| 56 | + case "160000": |
| 57 | + entry.EntryMode = EntryModeCommit |
| 58 | + case "040000", "040755": // git uses 040000 for tree object, but some users may get 040755 for unknown reasons |
| 59 | + entry.EntryMode = EntryModeTree |
| 60 | + default: |
| 61 | + return nil, fmt.Errorf("unknown type: %v", string(entryMode)) |
| 62 | + } |
| 63 | + |
| 64 | + entry.ID, err = NewIDFromString(string(entryObjectID)) |
| 65 | + if err != nil { |
| 66 | + return nil, fmt.Errorf("invalid ls-tree output (invalid object id): %q, err: %w", line, err) |
| 67 | + } |
| 68 | + |
| 69 | + if len(entryName) > 0 && entryName[0] == '"' { |
| 70 | + entry.Name, err = strconv.Unquote(string(entryName)) |
| 71 | + if err != nil { |
| 72 | + return nil, fmt.Errorf("invalid ls-tree output (invalid name): %q, err: %w", line, err) |
| 73 | + } |
| 74 | + } else { |
| 75 | + entry.Name = string(entryName) |
| 76 | + } |
| 77 | + return entry, nil |
| 78 | +} |
0 commit comments