syncthing/model/walk.go

140 lines
2.4 KiB
Go
Raw Normal View History

package model
2013-12-15 11:43:31 +01:00
import (
"fmt"
"log"
2013-12-15 11:43:31 +01:00
"os"
"path"
"path/filepath"
"strings"
)
const BlockSize = 128 * 1024
type File struct {
Name string
Flags uint32
Modified int64
Blocks []Block
2013-12-15 11:43:31 +01:00
}
2013-12-30 15:30:29 +01:00
func (f File) Size() (bytes int) {
for _, b := range f.Blocks {
bytes += int(b.Length)
}
return
}
2013-12-15 11:43:31 +01:00
func isTempName(name string) bool {
return strings.HasPrefix(path.Base(name), ".syncthing.")
}
func tempName(name string, modified int64) string {
tdir := path.Dir(name)
tname := fmt.Sprintf(".syncthing.%s.%d", path.Base(name), modified)
return path.Join(tdir, tname)
}
func (m *Model) genWalker(res *[]File) filepath.WalkFunc {
2013-12-15 11:43:31 +01:00
return func(p string, info os.FileInfo, err error) error {
if err != nil {
return nil
2013-12-15 11:43:31 +01:00
}
if isTempName(p) {
return nil
}
if info.Mode()&os.ModeType == 0 {
rn, err := filepath.Rel(m.dir, p)
2013-12-15 11:43:31 +01:00
if err != nil {
return nil
2013-12-15 11:43:31 +01:00
}
fi, err := os.Stat(p)
if err != nil {
return nil
2013-12-15 11:43:31 +01:00
}
modified := fi.ModTime().Unix()
m.RLock()
hf, ok := m.local[rn]
m.RUnlock()
2013-12-15 11:43:31 +01:00
if ok && hf.Modified == modified {
// No change
*res = append(*res, hf)
} else {
if m.trace["file"] {
log.Printf("FILE: Hash %q", p)
2013-12-15 11:43:31 +01:00
}
fd, err := os.Open(p)
if err != nil {
return nil
2013-12-15 11:43:31 +01:00
}
defer fd.Close()
blocks, err := Blocks(fd, BlockSize)
if err != nil {
return nil
2013-12-15 11:43:31 +01:00
}
f := File{
Name: rn,
Flags: uint32(info.Mode()),
Modified: modified,
Blocks: blocks,
}
*res = append(*res, f)
}
}
return nil
}
}
// Walk returns the list of files found in the local repository by scanning the
// file system. Files are blockwise hashed.
func (m *Model) Walk(followSymlinks bool) []File {
2013-12-15 11:43:31 +01:00
var files []File
fn := m.genWalker(&files)
filepath.Walk(m.dir, fn)
2013-12-15 21:20:50 +01:00
if followSymlinks {
d, err := os.Open(m.dir)
2013-12-15 21:20:50 +01:00
if err != nil {
return files
}
2013-12-31 01:30:59 +01:00
defer d.Close()
2013-12-15 21:20:50 +01:00
fis, err := d.Readdir(-1)
if err != nil {
return files
}
2013-12-31 01:30:59 +01:00
2013-12-15 21:20:50 +01:00
for _, fi := range fis {
if fi.Mode()&os.ModeSymlink != 0 {
filepath.Walk(path.Join(m.dir, fi.Name())+"/", fn)
2013-12-15 21:20:50 +01:00
}
}
}
2013-12-15 11:43:31 +01:00
return files
}
func (m *Model) cleanTempFile(path string, info os.FileInfo, err error) error {
2013-12-15 11:43:31 +01:00
if err != nil {
return err
}
if info.Mode()&os.ModeType == 0 && isTempName(path) {
if m.trace["file"] {
log.Printf("FILE: Remove %q", path)
2013-12-15 11:43:31 +01:00
}
os.Remove(path)
}
return nil
}
func (m *Model) cleanTempFiles() {
filepath.Walk(m.dir, m.cleanTempFile)
2013-12-15 11:43:31 +01:00
}