2023-08-22 18:05:32 -04:00
|
|
|
package ignorefile
|
2017-04-17 18:08:24 -04:00
|
|
|
|
|
|
|
import (
|
|
|
|
"bufio"
|
|
|
|
"bytes"
|
|
|
|
"io"
|
|
|
|
"path/filepath"
|
|
|
|
"strings"
|
|
|
|
)
|
|
|
|
|
2023-08-22 18:05:32 -04:00
|
|
|
// ReadAll reads an ignore file from a reader and returns the list of file
|
|
|
|
// patterns to ignore, applying the following rules:
|
|
|
|
//
|
|
|
|
// - An UTF8 BOM header (if present) is stripped.
|
|
|
|
// - Lines starting with "#" are considered comments and are skipped.
|
|
|
|
//
|
|
|
|
// For remaining lines:
|
|
|
|
//
|
|
|
|
// - Leading and trailing whitespace is removed from each ignore pattern.
|
|
|
|
// - It uses [filepath.Clean] to get the shortest/cleanest path for
|
|
|
|
// ignore patterns.
|
|
|
|
// - Leading forward-slashes ("/") are removed from ignore patterns,
|
|
|
|
// so "/some/path" and "some/path" are considered equivalent.
|
2017-04-17 18:08:24 -04:00
|
|
|
func ReadAll(reader io.Reader) ([]string, error) {
|
|
|
|
if reader == nil {
|
|
|
|
return nil, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var excludes []string
|
|
|
|
currentLine := 0
|
|
|
|
utf8bom := []byte{0xEF, 0xBB, 0xBF}
|
2023-08-22 18:05:32 -04:00
|
|
|
|
|
|
|
scanner := bufio.NewScanner(reader)
|
2017-04-17 18:08:24 -04:00
|
|
|
for scanner.Scan() {
|
|
|
|
scannedBytes := scanner.Bytes()
|
|
|
|
// We trim UTF8 BOM
|
|
|
|
if currentLine == 0 {
|
|
|
|
scannedBytes = bytes.TrimPrefix(scannedBytes, utf8bom)
|
|
|
|
}
|
|
|
|
pattern := string(scannedBytes)
|
|
|
|
currentLine++
|
|
|
|
// Lines starting with # (comments) are ignored before processing
|
|
|
|
if strings.HasPrefix(pattern, "#") {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
pattern = strings.TrimSpace(pattern)
|
|
|
|
if pattern == "" {
|
|
|
|
continue
|
|
|
|
}
|
2017-05-15 17:13:34 -04:00
|
|
|
// normalize absolute paths to paths relative to the context
|
|
|
|
// (taking care of '!' prefix)
|
|
|
|
invert := pattern[0] == '!'
|
|
|
|
if invert {
|
|
|
|
pattern = strings.TrimSpace(pattern[1:])
|
|
|
|
}
|
|
|
|
if len(pattern) > 0 {
|
|
|
|
pattern = filepath.Clean(pattern)
|
|
|
|
pattern = filepath.ToSlash(pattern)
|
|
|
|
if len(pattern) > 1 && pattern[0] == '/' {
|
|
|
|
pattern = pattern[1:]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if invert {
|
|
|
|
pattern = "!" + pattern
|
|
|
|
}
|
|
|
|
|
2017-04-17 18:08:24 -04:00
|
|
|
excludes = append(excludes, pattern)
|
|
|
|
}
|
|
|
|
if err := scanner.Err(); err != nil {
|
2023-08-22 18:05:32 -04:00
|
|
|
return nil, err
|
2017-04-17 18:08:24 -04:00
|
|
|
}
|
|
|
|
return excludes, nil
|
|
|
|
}
|