github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/cf/appfiles/cf_ignore.go (about)

     1  package appfiles
     2  
     3  import (
     4  	"path"
     5  	"strings"
     6  
     7  	"code.cloudfoundry.org/cli/util/glob"
     8  )
     9  
    10  //go:generate counterfeiter . CfIgnore
    11  
    12  type CfIgnore interface {
    13  	FileShouldBeIgnored(path string) bool
    14  }
    15  
    16  func NewCfIgnore(text string) CfIgnore {
    17  	patterns := []ignorePattern{}
    18  	lines := strings.Split(text, "\n")
    19  	lines = append(defaultIgnoreLines, lines...)
    20  
    21  	for _, line := range lines {
    22  		line = strings.TrimSpace(line)
    23  		if line == "" {
    24  			continue
    25  		}
    26  
    27  		ignore := true
    28  		if strings.HasPrefix(line, "!") {
    29  			line = line[1:]
    30  			ignore = false
    31  		}
    32  
    33  		for _, p := range globsForPattern(path.Clean(line)) {
    34  			patterns = append(patterns, ignorePattern{ignore, p})
    35  		}
    36  	}
    37  
    38  	return cfIgnore(patterns)
    39  }
    40  
    41  func (ignore cfIgnore) FileShouldBeIgnored(path string) bool {
    42  	result := false
    43  
    44  	for _, pattern := range ignore {
    45  		if strings.HasPrefix(pattern.glob.String(), "/") && !strings.HasPrefix(path, "/") {
    46  			path = "/" + path
    47  		}
    48  
    49  		if pattern.glob.Match(path) {
    50  			result = pattern.exclude
    51  		}
    52  	}
    53  
    54  	return result
    55  }
    56  
    57  func globsForPattern(pattern string) (globs []glob.Glob) {
    58  	globs = append(globs, glob.MustCompileGlob(pattern))
    59  	globs = append(globs, glob.MustCompileGlob(path.Join(pattern, "*")))
    60  	globs = append(globs, glob.MustCompileGlob(path.Join(pattern, "**", "*")))
    61  
    62  	if !strings.HasPrefix(pattern, "/") {
    63  		globs = append(globs, glob.MustCompileGlob(path.Join("**", pattern)))
    64  		globs = append(globs, glob.MustCompileGlob(path.Join("**", pattern, "*")))
    65  		globs = append(globs, glob.MustCompileGlob(path.Join("**", pattern, "**", "*")))
    66  	}
    67  
    68  	return
    69  }
    70  
    71  type ignorePattern struct {
    72  	exclude bool
    73  	glob    glob.Glob
    74  }
    75  
    76  type cfIgnore []ignorePattern
    77  
    78  var defaultIgnoreLines = []string{
    79  	".cfignore",
    80  	"/manifest.yml",
    81  	".gitignore",
    82  	".git",
    83  	".hg",
    84  	".svn",
    85  	"_darcs",
    86  	".DS_Store",
    87  }