2023-11-27 22:53:02 +01:00
|
|
|
package sync
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/pkg/errors"
|
|
|
|
"github.com/sirupsen/logrus"
|
2023-11-27 23:31:13 +01:00
|
|
|
"os"
|
2023-11-27 22:53:02 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
func Synchronize(src, dst Target) error {
|
|
|
|
srcTree, err := src.Inventory()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "error creating source inventory")
|
|
|
|
}
|
|
|
|
|
|
|
|
dstTree, err := dst.Inventory()
|
|
|
|
if err != nil {
|
|
|
|
return errors.Wrap(err, "error creating destination inventory")
|
|
|
|
}
|
|
|
|
|
|
|
|
dstIndex := make(map[string]*Object)
|
|
|
|
for _, f := range dstTree {
|
|
|
|
dstIndex[f.Path] = f
|
|
|
|
}
|
|
|
|
|
|
|
|
var copyList []*Object
|
|
|
|
for _, srcF := range srcTree {
|
|
|
|
if dstF, found := dstIndex[srcF.Path]; found {
|
2023-11-28 03:11:19 +01:00
|
|
|
if dstF.Size != srcF.Size || dstF.Modified.UTC() != srcF.Modified.UTC() {
|
2023-11-27 22:53:02 +01:00
|
|
|
copyList = append(copyList, srcF)
|
|
|
|
}
|
|
|
|
} else {
|
|
|
|
copyList = append(copyList, srcF)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-12-15 18:10:35 +01:00
|
|
|
for _, copyPath := range copyList {
|
|
|
|
ss, err := src.ReadStream(copyPath.Path)
|
2023-11-27 23:31:13 +01:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2023-12-15 18:10:35 +01:00
|
|
|
if err := dst.WriteStream(copyPath.Path, ss, os.ModePerm); err != nil {
|
2023-11-27 23:31:13 +01:00
|
|
|
return err
|
|
|
|
}
|
2023-12-15 18:10:35 +01:00
|
|
|
if err := dst.SetModificationTime(copyPath.Path, copyPath.Modified); err != nil {
|
2023-11-28 03:11:19 +01:00
|
|
|
return err
|
|
|
|
}
|
2023-12-15 18:10:35 +01:00
|
|
|
logrus.Infof("=> %v", copyPath.Path)
|
2023-11-27 22:53:02 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|