|
| 1 | +package ignorefile |
| 2 | + |
| 3 | +import ( |
| 4 | + "bufio" |
| 5 | + "bytes" |
| 6 | + "io" |
| 7 | + "path/filepath" |
| 8 | + "strings" |
| 9 | +) |
| 10 | + |
| 11 | +// ReadAll reads an ignore file from a reader and returns the list of file |
| 12 | +// patterns to ignore, applying the following rules: |
| 13 | +// |
| 14 | +// - An UTF8 BOM header (if present) is stripped. |
| 15 | +// - Lines starting with "#" are considered comments and are skipped. |
| 16 | +// |
| 17 | +// For remaining lines: |
| 18 | +// |
| 19 | +// - Leading and trailing whitespace is removed from each ignore pattern. |
| 20 | +// - It uses [filepath.Clean] to get the shortest/cleanest path for |
| 21 | +// ignore patterns. |
| 22 | +// - Leading forward-slashes ("/") are removed from ignore patterns, |
| 23 | +// so "/some/path" and "some/path" are considered equivalent. |
| 24 | +func ReadAll(reader io.Reader) ([]string, error) { |
| 25 | + if reader == nil { |
| 26 | + return nil, nil |
| 27 | + } |
| 28 | + |
| 29 | + var excludes []string |
| 30 | + currentLine := 0 |
| 31 | + utf8bom := []byte{0xEF, 0xBB, 0xBF} |
| 32 | + |
| 33 | + scanner := bufio.NewScanner(reader) |
| 34 | + for scanner.Scan() { |
| 35 | + scannedBytes := scanner.Bytes() |
| 36 | + // We trim UTF8 BOM |
| 37 | + if currentLine == 0 { |
| 38 | + scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom) |
| 39 | + } |
| 40 | + pattern := string(scannedBytes) |
| 41 | + currentLine++ |
| 42 | + // Lines starting with # (comments) are ignored before processing |
| 43 | + if strings.HasPrefix(pattern, "#") { |
| 44 | + continue |
| 45 | + } |
| 46 | + pattern = strings.TrimSpace(pattern) |
| 47 | + if pattern == "" { |
| 48 | + continue |
| 49 | + } |
| 50 | + // normalize absolute paths to paths relative to the context |
| 51 | + // (taking care of '!' prefix) |
| 52 | + invert := pattern[0] == '!' |
| 53 | + if invert { |
| 54 | + pattern = strings.TrimSpace(pattern[1:]) |
| 55 | + } |
| 56 | + if len(pattern) > 0 { |
| 57 | + pattern = filepath.Clean(pattern) |
| 58 | + pattern = filepath.ToSlash(pattern) |
| 59 | + if len(pattern) > 1 && pattern[0] == '/' { |
| 60 | + pattern = pattern[1:] |
| 61 | + } |
| 62 | + } |
| 63 | + if invert { |
| 64 | + pattern = "!" + pattern |
| 65 | + } |
| 66 | + |
| 67 | + excludes = append(excludes, pattern) |
| 68 | + } |
| 69 | + if err := scanner.Err(); err != nil { |
| 70 | + return nil, err |
| 71 | + } |
| 72 | + return excludes, nil |
| 73 | +} |
0 commit comments