|
| 1 | +package common |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "path" |
| 6 | + "path/filepath" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +// ExcludePaths represents a list of paths to exclude in a filesystem listing. |
| 11 | +// Users should do something like filepath.Walk() over the whole filesystem, |
| 12 | +// calling AddExclude() or AddInclude() based on whether they want to include |
| 13 | +// or exclude a particular file. Note that if e.g. /usr is excluded, then |
| 14 | +// everyting underneath is also implicitly excluded. The |
| 15 | +// AddExclude()/AddInclude() methods do the math to figure out what is the |
| 16 | +// correct set of things to exclude or include based on what paths have been |
| 17 | +// previously included or excluded. |
| 18 | +type ExcludePaths struct { |
| 19 | + exclude map[string]bool |
| 20 | + include []string |
| 21 | +} |
| 22 | + |
| 23 | +func NewExcludePaths() *ExcludePaths { |
| 24 | + return &ExcludePaths{ |
| 25 | + exclude: map[string]bool{}, |
| 26 | + include: []string{}, |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +func (eps *ExcludePaths) AddExclude(p string) { |
| 31 | + for _, inc := range eps.include { |
| 32 | + // If /usr/bin/ls has changed but /usr hasn't, we don't want to list |
| 33 | + // /usr in the include paths any more, so let's be sure to only |
| 34 | + // add things which aren't prefixes. |
| 35 | + if strings.HasPrefix(inc, p) { |
| 36 | + return |
| 37 | + } |
| 38 | + } |
| 39 | + eps.exclude[p] = true |
| 40 | +} |
| 41 | + |
| 42 | +func (eps *ExcludePaths) AddInclude(orig string, isDir bool) { |
| 43 | + // First, remove this thing and all its parents from exclude. |
| 44 | + p := orig |
| 45 | + |
| 46 | + // normalize to the first dir |
| 47 | + if !isDir { |
| 48 | + p = path.Dir(p) |
| 49 | + } |
| 50 | + for { |
| 51 | + // our paths are all absolute, so this is a base case |
| 52 | + if p == "/" { |
| 53 | + break |
| 54 | + } |
| 55 | + |
| 56 | + delete(eps.exclude, p) |
| 57 | + p = filepath.Dir(p) |
| 58 | + } |
| 59 | + |
| 60 | + // now add it to the list of includes, so we don't accidentally re-add |
| 61 | + // anything above. |
| 62 | + eps.include = append(eps.include, orig) |
| 63 | +} |
| 64 | + |
| 65 | +func (eps *ExcludePaths) String() (string, error) { |
| 66 | + var buf bytes.Buffer |
| 67 | + for p := range eps.exclude { |
| 68 | + _, err := buf.WriteString(p) |
| 69 | + if err != nil { |
| 70 | + return "", err |
| 71 | + } |
| 72 | + _, err = buf.WriteString("\n") |
| 73 | + if err != nil { |
| 74 | + return "", err |
| 75 | + } |
| 76 | + } |
| 77 | + |
| 78 | + _, err := buf.WriteString("\n") |
| 79 | + if err != nil { |
| 80 | + return "", err |
| 81 | + } |
| 82 | + |
| 83 | + return buf.String(), nil |
| 84 | +} |
0 commit comments