ftp/walker.go

99 lines
2.1 KiB
Go
Raw Permalink Normal View History

package ftp
import (
2020-04-25 18:27:59 +02:00
"path"
)
// Walker traverses the directory tree of a remote FTP server
type Walker struct {
serverConn *ServerConn
root string
2020-04-25 18:27:59 +02:00
cur *item
stack []*item
descend bool
}
type item struct {
path string
2020-04-25 18:27:59 +02:00
entry *Entry
err error
}
// Next advances the Walker to the next file or directory,
// which will then be available through the Path, Stat, and Err methods.
// It returns false when the walk stops at the end of the tree.
func (w *Walker) Next() bool {
// check if we need to init cur, maybe this should be inside Walk
2020-04-25 18:27:59 +02:00
if w.cur == nil {
w.cur = &item{
path: w.root,
entry: &Entry{
Type: EntryTypeFolder,
},
2020-04-25 18:27:59 +02:00
}
}
if w.descend && w.cur.entry.Type == EntryTypeFolder {
entries, err := w.serverConn.List(w.cur.path)
2020-04-25 18:27:59 +02:00
// an error occurred, drop out and stop walking
if err != nil {
w.cur.err = err
2020-04-25 18:27:59 +02:00
return false
}
for _, entry := range entries {
if entry.Name == "." || entry.Name == ".." {
2020-04-25 18:27:59 +02:00
continue
}
item := &item{
path: path.Join(w.cur.path, entry.Name),
entry: entry,
}
2020-04-25 18:27:59 +02:00
w.stack = append(w.stack, item)
}
}
if len(w.stack) == 0 {
return false
}
2020-04-25 18:27:59 +02:00
// update cur
i := len(w.stack) - 1
w.cur = w.stack[i]
w.stack = w.stack[:i]
// reset SkipDir
w.descend = true
2020-04-25 18:27:59 +02:00
return true
}
2022-01-10 03:14:34 +01:00
// SkipDir tells the Next function to skip the currently processed directory
func (w *Walker) SkipDir() {
w.descend = false
}
2022-01-10 03:14:34 +01:00
// Err returns the error, if any, for the most recent attempt by Next to
// visit a file or a directory. If a directory has an error, the walker
// will not descend in that directory
func (w *Walker) Err() error {
return w.cur.err
}
// Stat returns info for the most recent file or directory
// visited by a call to Next.
2020-04-25 18:27:59 +02:00
func (w *Walker) Stat() *Entry {
return w.cur.entry
}
// Path returns the path to the most recent file or directory
// visited by a call to Next. It contains the argument to Walk
// as a prefix; that is, if Walk is called with "dir", which is
// a directory containing the file "a", Path will return "dir/a".
func (w *Walker) Path() string {
return w.cur.path
}