Repository navigation
Expand file tree
/
Copy pathvisitor.go
More file actions
52 lines (43 loc) · 1.67 KB
/
Copy pathvisitor.go
File metadata and controls
52 lines (43 loc) · 1.67 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
// Package visitor adds operations to a file tree without putting each operation
// on every node type. Traversal is safe to share only when the tree is immutable
// and each traversal uses its own visitor (or a synchronized visitor).
package visitor
// Node accepts an operation. Children and visitors must be non-nil.
type Node interface{ Accept(Visitor) error }
// Visitor defines the operations supported for each concrete node type.
type Visitor interface {
VisitFile(File) error
VisitDirectory(Directory) error
}
// File is a leaf carrying a name and a size in bytes.
type File struct {
Name string
Size int64
}
// Accept dispatches the operation to VisitFile.
func (f File) Accept(v Visitor) error { return v.VisitFile(f) }
// Directory groups ordered child nodes. An empty directory is valid.
type Directory struct {
Name string
Children []Node
}
// Accept visits the directory, then its descendants in depth-first order.
// The first visitor error stops traversal and is returned unchanged.
func (d Directory) Accept(v Visitor) error {
if err := v.VisitDirectory(d); err != nil {
return err
}
for _, child := range d.Children {
if err := child.Accept(v); err != nil {
return err
}
}
return nil
}
// SizeVisitor accumulates file sizes across all accepted trees. Its zero value
// starts at zero; callers may reset Bytes before reusing it.
type SizeVisitor struct{ Bytes int64 }
// VisitFile adds the file's size to the accumulated total.
func (v *SizeVisitor) VisitFile(f File) error { v.Bytes += f.Size; return nil }
// VisitDirectory leaves the total unchanged; directories have no stored size.
func (v *SizeVisitor) VisitDirectory(Directory) error { return nil }