示例#1
0
文件: file.go 项目: dchest/hesfic
// Save stores file from disk at the given path and returns its metadata.
func saveFile(path string) (entry *Entry, err error) {
	fi, err := os.Stat(path)
	if err != nil {
		return
	}
	f, err := os.Open(path)
	if err != nil {
		return
	}
	defer f.Close()

	w := block.NewWriter()
	_, err = io.Copy(w, f)
	if err != nil {
		return
	}
	ref, err := w.Finish()
	if err != nil {
		return
	}
	entry = &Entry{
		Name:    fi.Name(),
		Size:    fi.Size(),
		ModTime: fi.ModTime(),
		Mode:    fi.Mode(),
		Ref:     ref,
	}
	log.Printf("[%d] stored file %s", w.BlockCount(), path)
	return
}
示例#2
0
文件: file.go 项目: dchest/hesfic
func SaveDirectory(dirpath string) (entry *Entry, err error) {
	fi, err := os.Stat(dirpath)
	if err != nil {
		return
	}
	dir, err := os.Open(dirpath)
	if err != nil {
		return
	}
	defer dir.Close()
	fis, err := dir.Readdir(0)
	if err != nil {
		return
	}
	entries := make([]*Entry, 0)
	// Save files and subdirectories.
	for _, fi := range fis {
		fullpath := filepath.Join(dirpath, fi.Name())
		var e *Entry
		if fi.IsDir() {
			e, err = SaveDirectory(fullpath)
		} else {
			e, err = saveFile(fullpath)
		}
		if err != nil {
			return
		}
		entries = append(entries, e)
	}
	// Save directory index.
	w := block.NewWriter()
	enc := json.NewEncoder(w)
	err = enc.Encode(entries)
	if err != nil {
		return
	}
	ref, err := w.Finish()
	if err != nil {
		return
	}
	log.Printf("[%d] stored directory %s at %s", w.BlockCount(), dirpath, ref)
	entry = &Entry{
		Name:    fi.Name(),
		Size:    fi.Size(),
		ModTime: fi.ModTime(),
		Mode:    fi.Mode(),
		Ref:     ref,
	}
	return
}