walk.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package scanner
  2. import (
  3. "bytes"
  4. "io/ioutil"
  5. "log"
  6. "os"
  7. "path"
  8. "path/filepath"
  9. "strings"
  10. "time"
  11. "code.google.com/p/go.text/unicode/norm"
  12. )
  13. type Walker struct {
  14. // Dir is the base directory for the walk
  15. Dir string
  16. // If FollowSymlinks is true, symbolic links directly under Dir will be followed.
  17. // Symbolic links at deeper levels are never followed regardless of this flag.
  18. FollowSymlinks bool
  19. // BlockSize controls the size of the block used when hashing.
  20. BlockSize int
  21. // If IgnoreFile is not empty, it is the name used for the file that holds ignore patterns.
  22. IgnoreFile string
  23. // If TempNamer is not nil, it is used to ignore tempory files when walking.
  24. TempNamer TempNamer
  25. // If CurrentFiler is not nil, it is queried for the current file before rescanning.
  26. CurrentFiler CurrentFiler
  27. // If Suppressor is not nil, it is queried for supression of modified files.
  28. // Suppressed files will be returned with empty metadata and the Suppressed flag set.
  29. // Requires CurrentFiler to be set.
  30. Suppressor Suppressor
  31. suppressed map[string]bool // file name -> suppression status
  32. }
  33. type TempNamer interface {
  34. // Temporary returns a temporary name for the filed referred to by path.
  35. TempName(path string) string
  36. // IsTemporary returns true if path refers to the name of temporary file.
  37. IsTemporary(path string) bool
  38. }
  39. type Suppressor interface {
  40. // Supress returns true if the update to the named file should be ignored.
  41. Suppress(name string, fi os.FileInfo) bool
  42. }
  43. type CurrentFiler interface {
  44. // CurrentFile returns the file as seen at last scan.
  45. CurrentFile(name string) File
  46. }
  47. // Walk returns the list of files found in the local repository by scanning the
  48. // file system. Files are blockwise hashed.
  49. func (w *Walker) Walk() (files []File, ignore map[string][]string) {
  50. w.lazyInit()
  51. if debug {
  52. dlog.Println("Walk", w.Dir, w.FollowSymlinks, w.BlockSize, w.IgnoreFile)
  53. }
  54. t0 := time.Now()
  55. ignore = make(map[string][]string)
  56. hashFiles := w.walkAndHashFiles(&files, ignore)
  57. filepath.Walk(w.Dir, w.loadIgnoreFiles(w.Dir, ignore))
  58. filepath.Walk(w.Dir, hashFiles)
  59. if w.FollowSymlinks {
  60. d, err := os.Open(w.Dir)
  61. if err != nil {
  62. return
  63. }
  64. defer d.Close()
  65. fis, err := d.Readdir(-1)
  66. if err != nil {
  67. return
  68. }
  69. for _, info := range fis {
  70. if info.Mode()&os.ModeSymlink != 0 {
  71. dir := path.Join(w.Dir, info.Name()) + "/"
  72. filepath.Walk(dir, w.loadIgnoreFiles(dir, ignore))
  73. filepath.Walk(dir, hashFiles)
  74. }
  75. }
  76. }
  77. if debug {
  78. t1 := time.Now()
  79. d := t1.Sub(t0).Seconds()
  80. dlog.Printf("Walk in %.02f ms, %.0f files/s", d*1000, float64(len(files))/d)
  81. }
  82. return
  83. }
  84. // CleanTempFiles removes all files that match the temporary filename pattern.
  85. func (w *Walker) CleanTempFiles() {
  86. filepath.Walk(w.Dir, w.cleanTempFile)
  87. }
  88. func (w *Walker) lazyInit() {
  89. if w.suppressed == nil {
  90. w.suppressed = make(map[string]bool)
  91. }
  92. }
  93. func (w *Walker) loadIgnoreFiles(dir string, ign map[string][]string) filepath.WalkFunc {
  94. return func(p string, info os.FileInfo, err error) error {
  95. if err != nil {
  96. return nil
  97. }
  98. rn, err := filepath.Rel(dir, p)
  99. if err != nil {
  100. return nil
  101. }
  102. if pn, sn := path.Split(rn); sn == w.IgnoreFile {
  103. pn := strings.Trim(pn, "/")
  104. bs, _ := ioutil.ReadFile(p)
  105. lines := bytes.Split(bs, []byte("\n"))
  106. var patterns []string
  107. for _, line := range lines {
  108. if len(line) > 0 {
  109. patterns = append(patterns, string(line))
  110. }
  111. }
  112. ign[pn] = patterns
  113. }
  114. return nil
  115. }
  116. }
  117. func (w *Walker) walkAndHashFiles(res *[]File, ign map[string][]string) filepath.WalkFunc {
  118. return func(p string, info os.FileInfo, err error) error {
  119. if err != nil {
  120. if debug {
  121. dlog.Println("error:", p, info, err)
  122. }
  123. return nil
  124. }
  125. rn, err := filepath.Rel(w.Dir, p)
  126. if err != nil {
  127. if debug {
  128. dlog.Println("rel error:", p, err)
  129. }
  130. return nil
  131. }
  132. // Internally, we always use unicode normalization form C
  133. rn = norm.NFC.String(rn)
  134. if w.TempNamer != nil && w.TempNamer.IsTemporary(rn) {
  135. if debug {
  136. dlog.Println("temporary:", rn)
  137. }
  138. return nil
  139. }
  140. if _, sn := path.Split(rn); sn == w.IgnoreFile {
  141. if debug {
  142. dlog.Println("ignorefile:", rn)
  143. }
  144. return nil
  145. }
  146. if rn != "." && w.ignoreFile(ign, rn) {
  147. if debug {
  148. dlog.Println("ignored:", rn)
  149. }
  150. if info.IsDir() {
  151. return filepath.SkipDir
  152. }
  153. return nil
  154. }
  155. if info.Mode()&os.ModeType == 0 {
  156. if w.CurrentFiler != nil {
  157. cf := w.CurrentFiler.CurrentFile(rn)
  158. if cf.Modified == info.ModTime().Unix() {
  159. if debug {
  160. dlog.Println("unchanged:", rn)
  161. }
  162. *res = append(*res, cf)
  163. return nil
  164. }
  165. if w.Suppressor != nil && w.Suppressor.Suppress(rn, info) {
  166. if debug {
  167. dlog.Println("suppressed:", rn)
  168. }
  169. if !w.suppressed[rn] {
  170. w.suppressed[rn] = true
  171. log.Printf("INFO: Changes to %q are being temporarily suppressed because it changes too frequently.", p)
  172. }
  173. cf.Suppressed = true
  174. *res = append(*res, cf)
  175. } else if w.suppressed[rn] {
  176. log.Printf("INFO: Changes to %q are no longer suppressed.", p)
  177. delete(w.suppressed, rn)
  178. }
  179. }
  180. fd, err := os.Open(p)
  181. if err != nil {
  182. if debug {
  183. dlog.Println("open:", p, err)
  184. }
  185. return nil
  186. }
  187. defer fd.Close()
  188. t0 := time.Now()
  189. blocks, err := Blocks(fd, w.BlockSize)
  190. if err != nil {
  191. if debug {
  192. dlog.Println("hash error:", rn, err)
  193. }
  194. return nil
  195. }
  196. if debug {
  197. t1 := time.Now()
  198. dlog.Println("hashed:", rn, ";", len(blocks), "blocks;", info.Size(), "bytes;", int(float64(info.Size())/1024/t1.Sub(t0).Seconds()), "KB/s")
  199. }
  200. f := File{
  201. Name: rn,
  202. Size: info.Size(),
  203. Flags: uint32(info.Mode()),
  204. Modified: info.ModTime().Unix(),
  205. Blocks: blocks,
  206. }
  207. *res = append(*res, f)
  208. }
  209. return nil
  210. }
  211. }
  212. func (w *Walker) cleanTempFile(path string, info os.FileInfo, err error) error {
  213. if err != nil {
  214. return err
  215. }
  216. if info.Mode()&os.ModeType == 0 && w.TempNamer.IsTemporary(path) {
  217. os.Remove(path)
  218. }
  219. return nil
  220. }
  221. func (w *Walker) ignoreFile(patterns map[string][]string, file string) bool {
  222. first, last := path.Split(file)
  223. for prefix, pats := range patterns {
  224. if len(prefix) == 0 || prefix == first || strings.HasPrefix(first, prefix+"/") {
  225. for _, pattern := range pats {
  226. if match, _ := path.Match(pattern, last); match {
  227. return true
  228. }
  229. }
  230. }
  231. }
  232. return false
  233. }