Skip to content

Instantly share code, notes, and snippets.

@athurg
Created December 1, 2017 07:50
Show Gist options
  • Save athurg/987e136e4b75e873e6025a42beaabfab to your computer and use it in GitHub Desktop.
Save athurg/987e136e4b75e873e6025a42beaabfab to your computer and use it in GitHub Desktop.
遍历go-git内存文件系统的工作区
package main
import (
"fmt"
"io/ioutil"
"os"
"gopkg.in/src-d/go-billy.v3"
"gopkg.in/src-d/go-billy.v3/memfs"
"gopkg.in/src-d/go-git.v4"
"gopkg.in/src-d/go-git.v4/storage/memory"
)
func main() {
fs := memfs.New()
cloneOptions := git.CloneOptions{URL: "file:///tmp/docloud/.git", Progress: os.Stdout}
_, err := git.Clone(memory.NewStorage(), fs, &cloneOptions)
if err != nil {
fmt.Println("Clone error ", err)
return
}
err = walk(fs, "/", handle)
if err != nil {
fmt.Println("遍历错误:", err)
}
}
type walkCallback func(billy.Filesystem, string, os.FileInfo) error
func handle(fs billy.Filesystem, fullpath string, fileInfo os.FileInfo) error {
if fileInfo.IsDir() {
fmt.Printf("d %-60s\n", fullpath)
return nil
}
file, err := fs.Open(fullpath)
if err != nil {
return fmt.Errorf("Fail to open %s : %s", fullpath, err)
}
d, err := ioutil.ReadAll(file)
if err != nil {
return fmt.Errorf("Fail to read %s : %s", fullpath, err)
}
if fileInfo.Size() == int64(len(d)) {
fmt.Printf("f %-60s Size: %d Bytes\n", fullpath, fileInfo.Size())
} else {
fmt.Printf("f %-60s Size: %d != %d Bytes\n", fullpath, fileInfo.Size(), len(d))
}
return nil
}
//递归遍历文件系统中path指定的路径下,所有的目录、文件,针对遍历到的文件调用callback处理
//遍历过程中遇到错误即终止返回,不再继续遍历后续项
//callback如果返回错误,也会终止返回,不再继续遍历
func walk(fs billy.Filesystem, path string, callback walkCallback) error {
fileInfo, err := fs.Stat(path)
if err != nil {
return fmt.Errorf("Fail to stat %s ", path, err)
}
err = callback(fs, path, fileInfo)
if err != nil {
return err
}
if fileInfo.IsDir() {
subFileInfos, _ := fs.ReadDir(path)
for _, subFileInfo := range subFileInfos {
subPath := fs.Join(path, subFileInfo.Name())
err := walk(fs, subPath, callback)
if err != nil {
return err
}
}
}
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment