zk/core/file/diff.go

96 lines
2.4 KiB
Go
Raw Normal View History

2021-01-03 16:09:10 +00:00
package file
2021-01-02 21:25:39 +00:00
// DiffChange represents a file change made in a directory.
2021-01-02 21:25:39 +00:00
type DiffChange struct {
Path string
2021-01-02 21:25:39 +00:00
Kind DiffKind
}
// DiffKind represents a type of file change made in a directory.
2021-01-02 21:25:39 +00:00
type DiffKind int
const (
DiffAdded DiffKind = iota + 1
DiffModified
DiffRemoved
)
// Diff compares two sources of file.Metadata and report the file changes, using
2021-01-03 16:09:10 +00:00
// the file modification date.
2021-01-02 21:25:39 +00:00
//
// Warning: The file.Metadata have to be sorted by their Path for the diffing to
2021-01-02 21:25:39 +00:00
// work properly.
2021-01-03 16:09:10 +00:00
func Diff(source, target <-chan Metadata, callback func(DiffChange) error) error {
var err error
2021-01-03 16:09:10 +00:00
var sourceFile, targetFile Metadata
var sourceOpened, targetOpened bool = true, true
pair := diffPair{}
2021-01-02 21:25:39 +00:00
for err == nil && (sourceOpened || targetOpened) {
if pair.source == nil {
sourceFile, sourceOpened = <-source
if sourceOpened {
pair.source = &sourceFile
2021-01-02 21:25:39 +00:00
}
}
if pair.target == nil {
targetFile, targetOpened = <-target
if targetOpened {
pair.target = &targetFile
2021-01-02 21:25:39 +00:00
}
}
change := pair.diff()
if change != nil {
err = callback(*change)
}
}
return err
2021-01-02 21:25:39 +00:00
}
// diffPair holds the current two files to be diffed.
type diffPair struct {
2021-01-03 16:09:10 +00:00
source *Metadata
target *Metadata
2021-01-02 21:25:39 +00:00
}
// diff compares the source and target files in the current pair.
//
// If the source and target file are at the same path, we check for any change.
// If the files are different, that means that either the source file was
// added, or the target file was removed.
func (p *diffPair) diff() *DiffChange {
var change *DiffChange
switch {
case p.source == nil && p.target == nil: // Both channels are closed
break
case p.source == nil && p.target != nil: // Source channel is closed
change = &DiffChange{p.target.Path, DiffRemoved}
p.target = nil
case p.source != nil && p.target == nil: // Target channel is closed
change = &DiffChange{p.source.Path, DiffAdded}
p.source = nil
case p.source.Path == p.target.Path: // Same files, compare their modification date.
if p.source.Modified != p.target.Modified {
change = &DiffChange{p.source.Path, DiffModified}
}
p.source = nil
p.target = nil
default: // Different files, one has been added or removed.
if p.source.Path < p.target.Path {
2021-01-02 21:25:39 +00:00
change = &DiffChange{p.source.Path, DiffAdded}
p.source = nil
} else {
change = &DiffChange{p.target.Path, DiffRemoved}
p.target = nil
}
}
return change
}