github.com/henvic/wedeploycli@v1.7.6-0.20200319005353-3630f582f284/deployment/transport/gogit/ignore.go (about) 1 package gogit 2 3 import ( 4 "fmt" 5 "os" 6 "path/filepath" 7 "strings" 8 9 "github.com/hashicorp/errwrap" 10 "github.com/henvic/wedeploycli/deployment/internal/ignore" 11 "github.com/henvic/wedeploycli/verbose" 12 "gopkg.in/src-d/go-billy.v4/osfs" 13 git "gopkg.in/src-d/go-git.v4" 14 "gopkg.in/src-d/go-git.v4/plumbing/format/gitignore" 15 ) 16 17 type file struct { 18 path string 19 isDir bool 20 } 21 22 type ignoreChecker struct { 23 path string 24 files []file 25 } 26 27 // ignoreChecker gets what file should be ignored. 28 func (i *ignoreChecker) Process() (map[string]struct{}, error) { 29 var ps, err = gitignore.ReadPatterns(osfs.New(i.path), nil) 30 31 if err != nil { 32 return nil, errwrap.Wrapf("error processing .gitignore: {{err}}", err) 33 } 34 35 var files = []file{} 36 37 if err = filepath.Walk(i.path, i.walkIgnored); err != nil { 38 return nil, err 39 } 40 41 var ignored = map[string]struct{}{} 42 43 for _, pattern := range ps { 44 for _, f := range files { 45 if _, is := ignored[f.path]; is { 46 continue 47 } 48 49 status := pattern.Match(strings.Split(f.path, string(filepath.Separator)), f.isDir) 50 51 if status == gitignore.Exclude { 52 ignored[f.path] = struct{}{} 53 } 54 } 55 } 56 57 if len(ignored) != 0 { 58 verbose.Debug(fmt.Sprintf( 59 "Ignoring %d files and directories found on .gitignore files", 60 len(ignored))) 61 62 } 63 64 return ignored, nil 65 } 66 67 func (i *ignoreChecker) walkIgnored(path string, info os.FileInfo, err error) error { 68 if err != nil { 69 return err 70 } 71 72 path = strings.TrimPrefix(path, i.path+string(os.PathSeparator)) 73 74 if info.Name() == git.GitDirName || ignore.Match(info.Name()) { 75 if info.IsDir() { 76 return filepath.SkipDir 77 } 78 79 return nil 80 } 81 82 i.files = append(i.files, file{ 83 path, 84 info.IsDir(), 85 }) 86 87 return nil 88 }