Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
187 changes: 187 additions & 0 deletions cmd/client-fs-mirror_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
// Copyright (c) 2026 Chen Shi
//
// This file is part of PGSTY SILO mcli
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.

package cmd

import (
"bytes"
"context"
"os"
"path/filepath"
"slices"
"strings"
"testing"

checkv1 "gopkg.in/check.v1"
)

func (s *TestSuite) TestMirrorListsEmptyDirectoriesAndFiles(c *checkv1.C) {
sourceRoot, err := os.MkdirTemp(os.TempDir(), "mirror-source-")
c.Assert(err, checkv1.IsNil)
defer os.RemoveAll(sourceRoot)

targetRoot, err := os.MkdirTemp(os.TempDir(), "mirror-target-")
c.Assert(err, checkv1.IsNil)
defer os.RemoveAll(targetRoot)

emptyDir := filepath.Join(sourceRoot, "empty")
nestedEmptyDir := filepath.Join(sourceRoot, "parent", "nested-empty")
nonEmptyDir := filepath.Join(sourceRoot, "non-empty")
for _, dir := range []string{emptyDir, nestedEmptyDir, nonEmptyDir} {
c.Assert(os.MkdirAll(dir, 0o755), checkv1.IsNil)
}
for _, file := range []string{
filepath.Join(sourceRoot, "empty-file"),
filepath.Join(nonEmptyDir, "nested-empty-file"),
} {
c.Assert(os.WriteFile(file, nil, 0o644), checkv1.IsNil)
}
targetOnlyDir := filepath.Join(targetRoot, "target-only-empty")
c.Assert(os.MkdirAll(targetOnlyDir, 0o755), checkv1.IsNil)

source, fsErr := fsNew(sourceRoot + string(filepath.Separator))
c.Assert(fsErr, checkv1.IsNil)
target, fsErr := fsNew(targetRoot + string(filepath.Separator))
c.Assert(fsErr, checkv1.IsNil)

directories := make(map[string]bool)
files := make(map[string]int64)
for content := range source.List(globalContext, ListOptions{
Recursive: true,
ShowDir: DirNone,
IncludeEmptyDirs: true,
}) {
c.Assert(content.Err, checkv1.IsNil)
if content.Type.IsDir() {
directories[content.URL.Path] = true
continue
}
if content.Type.IsRegular() {
files[filepath.Clean(content.URL.Path)] = content.Size
}
}
c.Assert(directories, checkv1.DeepEquals, map[string]bool{
emptyDir + string(filepath.Separator): true,
nestedEmptyDir + string(filepath.Separator): true,
})
c.Assert(files, checkv1.DeepEquals, map[string]int64{
filepath.Join(sourceRoot, "empty-file"): 0,
filepath.Join(nonEmptyDir, "nested-empty-file"): 0,
})

first := make(map[string]bool)
second := make(map[string]bool)
for diff := range objectDifference(context.Background(), source, target, mirrorOptions{includeEmptyDirs: true}) {
c.Assert(diff.Error, checkv1.IsNil)
switch diff.Diff {
case differInFirst:
first[diff.FirstURL] = true
case differInSecond:
second[diff.SecondURL] = true
default:
c.Fatalf("unexpected mirror difference: %v", diff.Diff)
}
}
c.Assert(first, checkv1.DeepEquals, map[string]bool{
emptyDir + string(filepath.Separator): true,
nestedEmptyDir + string(filepath.Separator): true,
filepath.Join(sourceRoot, "empty-file"): true,
filepath.Join(nonEmptyDir, "nested-empty-file"): true,
})
c.Assert(second, checkv1.DeepEquals, map[string]bool{
targetOnlyDir + string(filepath.Separator): true,
})
}

func TestMirrorRemoveWithDirectorySymlink(t *testing.T) {
source, target := t.TempDir(), t.TempDir()
if err := os.Symlink(t.TempDir(), filepath.Join(source, "a")); err != nil {
t.Skipf("directory symlinks unavailable: %v", err)
}
for _, dir := range []string{source, target} {
if err := os.WriteFile(filepath.Join(dir, "a.txt"), []byte("same"), 0o600); err != nil {
t.Fatal(err)
}
}
if err := os.Mkdir(filepath.Join(target, "a"), 0o700); err != nil {
t.Fatal(err)
}
result := runChecksumVerifyCLI(t, "http://localhost", nil, "--json", "mirror", "--remove", "--max-workers", "1", source, target)
if result.exitCode != 0 || bytes.Contains(result.stdout, []byte("a.txt")) {
t.Fatalf("mirror must leave the matching file alone: exit=%d stdout=%s stderr=%s", result.exitCode, result.stdout, result.stderr)
}
data, err := os.ReadFile(filepath.Join(target, "a.txt"))
if err != nil || string(data) != "same" {
t.Fatalf("a.txt after mirror: %q, %v", data, err)
}
}

func TestDiffIgnoresLocalEmptyDirectories(t *testing.T) {
source, target := t.TempDir(), t.TempDir()
if err := os.Mkdir(filepath.Join(source, "empty"), 0o700); err != nil {
t.Fatal(err)
}
result := runChecksumVerifyCLI(t, "http://localhost", nil, "--json", "diff", source, target)
if result.exitCode != 0 || len(bytes.TrimSpace(result.stdout)) != 0 {
t.Fatalf("diff exit=%d stdout=%s stderr=%s", result.exitCode, result.stdout, result.stderr)
}
}

func TestMirrorDirectoryKeyOrder(t *testing.T) {
root := t.TempDir()
for _, name := range []string{"a", "a.b", "a0"} {
if err := os.Mkdir(filepath.Join(root, name), 0o700); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(root, "a.txt"), nil, 0o600); err != nil {
t.Fatal(err)
}
client, err := fsNew(filepath.ToSlash(root) + "/")
if err != nil {
t.Fatal(err)
}
var keys []string
for entry := range client.List(t.Context(), ListOptions{Recursive: true, IncludeEmptyDirs: true}) {
if entry.Err != nil {
t.Fatal(entry.Err)
}
keys = append(keys, filepath.ToSlash(strings.TrimPrefix(entry.URL.Path, client.GetURL().Path)))
}
if want := []string{"a.b/", "a.txt", "a/", "a0/"}; !slices.Equal(keys, want) {
t.Fatalf("keys in merge order: got %v, want %v", keys, want)
}
}

func TestMirrorRemoveKeepsParentOfIncomingFile(t *testing.T) {
source, target := t.TempDir(), t.TempDir()
for _, root := range []string{source, target} {
if err := os.Mkdir(filepath.Join(root, "parent"), 0o750); err != nil {
t.Fatal(err)
}
}
if err := os.WriteFile(filepath.Join(source, "parent", "child"), []byte("data"), 0o600); err != nil {
t.Fatal(err)
}
result := runChecksumVerifyCLI(t, "http://localhost", nil, "--json", "mirror", "--remove", "--max-workers", "1", source, target)
if result.exitCode != 0 || bytes.Contains(result.stdout, []byte(`"source":""`)) {
t.Fatalf("unexpected removal: exit=%d stdout=%s stderr=%s", result.exitCode, result.stdout, result.stderr)
}
if data, err := os.ReadFile(filepath.Join(target, "parent", "child")); err != nil || string(data) != "data" {
t.Fatalf("child after mirror: %q, %v", data, err)
}
}
76 changes: 63 additions & 13 deletions cmd/client-fs.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ func fsNew(path string) (Client, *probe.Error) {
// filepath.Abs removes the trailing slash in a path
// but we still need it because fsClient.List() does not
// traverse a directory without a trailing slash in the name
if path[len(path)-1] == filepath.Separator {
if os.IsPathSeparator(path[len(path)-1]) && !os.IsPathSeparator(absPath[len(absPath)-1]) {
absPath += string(filepath.Separator)
}
return &fsClient{
Expand Down Expand Up @@ -819,7 +819,7 @@ func (f *fsClient) List(_ context.Context, opts ListOptions) <-chan *ClientConte

if opts.Recursive {
if opts.ShowDir == DirNone {
go f.listRecursiveInRoutine(contentCh)
go f.listRecursiveInRoutine(contentCh, opts.IncludeEmptyDirs)
} else {
go f.listDirOpt(contentCh, opts.Incomplete, opts.WithMetadata, opts.ShowDir)
}
Expand Down Expand Up @@ -857,17 +857,15 @@ type byDirName []os.FileInfo

func (f byDirName) Len() int { return len(f) }
func (f byDirName) Less(i, j int) bool {
// For directory add an ending separator fortrue lexical
// order.
if f[i].Mode().IsDir() {
return f[i].Name()+string(filepath.Separator) < f[j].Name()
// Object keys use a slash on every platform.
left, right := f[i].Name(), f[j].Name()
if f[i].IsDir() {
left += "/"
}
// For directory add an ending separator for true lexical
// order.
if f[j].Mode().IsDir() {
return f[i].Name() < f[j].Name()+string(filepath.Separator)
if f[j].IsDir() {
right += "/"
}
return f[i].Name() < f[j].Name()
return left < right
}
func (f byDirName) Swap(i, j int) { f[i], f[j] = f[j], f[i] }

Expand All @@ -878,11 +876,11 @@ func readDir(dirname string) ([]os.FileInfo, error) {
if e != nil {
return nil, e
}
defer f.Close()
list, e := f.Readdir(-1)
if e != nil {
return nil, e
}
defer f.Close()
sort.Sort(byDirName(list))
return list, nil
}
Expand Down Expand Up @@ -1088,9 +1086,61 @@ func (f *fsClient) listDirOpt(contentCh chan *ClientContent, isIncomplete, _ boo
}
}

func (f *fsClient) listRecursiveInRoutine(contentCh chan *ClientContent) {
// listMirrorDir emits regular files and empty leaf directories in object-key order.
// The root maps to the destination itself and has no marker of its own.
func (f *fsClient) listMirrorDir(dir, prefix string, info os.FileInfo, out chan<- *ClientContent) *probe.Error {
entries, err := readDir(dir)
if err != nil {
if info == nil && os.IsNotExist(err) {
return nil // A new local mirror destination has no entries yet.
}
return f.toClientError(err, dir)
}

empty := true
for _, entry := range entries {
if !strings.HasPrefix(entry.Name(), prefix) {
continue
}
name := filepath.Join(dir, entry.Name())
if entry.IsDir() {
empty = false
if err := f.listMirrorDir(name, "", entry, out); err != nil {
return err
}
continue
}
if isIgnoredFile(entry.Name()) {
continue
}
empty = false
if entry.Mode()&os.ModeSymlink != 0 {
// Recursive filesystem listings follow links to regular files only.
entry, err = os.Stat(name)
if err != nil {
continue
}
}
if entry.Mode().IsRegular() {
out <- &ClientContent{URL: *newClientURL(name), Time: entry.ModTime(), Size: entry.Size(), Type: entry.Mode()}
}
}
if empty && info != nil && !isIgnoredFile(info.Name()) {
out <- &ClientContent{URL: *newClientURL(dir + string(filepath.Separator)), Time: info.ModTime(), Type: os.ModeDir}
}
return nil
}

func (f *fsClient) listRecursiveInRoutine(contentCh chan *ClientContent, includeEmptyDirs bool) {
// close channels upon return.
defer close(contentCh)
if includeEmptyDirs {
dir, prefix := filepath.Split(filepath.FromSlash(f.PathURL.Path))
if err := f.listMirrorDir(dir, prefix, nil, contentCh); err != nil {
contentCh <- &ClientContent{Err: err}
}
return
}
var dirName string
var filePrefix string
pathURL := *f.PathURL
Expand Down
1 change: 1 addition & 0 deletions cmd/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,7 @@ type ListOptions struct {
TimeRef time.Time
ShowDir DirOpt
Count int
IncludeEmptyDirs bool
}

// CopyOptions holds options for copying operation
Expand Down
37 changes: 26 additions & 11 deletions cmd/common-methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -352,8 +352,12 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
metadata[http.CanonicalHeaderKey(k)] = v
}

// A local empty directory represents a zero-byte marker. A remote key
// ending in '/' can carry both object data and metadata.
localDirMarker := sourceURL.Type == fileSystem && length == 0 && uploadOpts.urls.SourceContent.Type.IsDir()

// Optimize for server side copy if the host is same.
if sourceAlias == targetAlias && !uploadOpts.isZip && !uploadOpts.urls.checksum.IsSet() {
if !localDirMarker && sourceAlias == targetAlias && !uploadOpts.isZip && !uploadOpts.urls.checksum.IsSet() {
// preserve new metadata and save existing ones.
if uploadOpts.preserve {
currentMetadata, err := getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, uploadOpts.urls)
Expand Down Expand Up @@ -421,16 +425,27 @@ func uploadSourceToTargetURL(ctx context.Context, uploadOpts uploadSourceToTarge
reader io.ReadCloser
)

reader, content, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), getSourceOpts{
GetOptions: GetOptions{
VersionID: sourceVersion,
SSE: srcSSE,
Zip: uploadOpts.isZip,
Preserve: uploadOpts.preserve,
},
})
if err != nil {
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
if localDirMarker {
content = uploadOpts.urls.SourceContent
if uploadOpts.preserve {
content.Metadata, err = getAllMetadata(ctx, sourceAlias, sourceURL.String(), srcSSE, uploadOpts.urls)
if err != nil {
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
}
}
reader = io.NopCloser(strings.NewReader(""))
} else {
reader, content, err = getSourceStream(ctx, sourceAlias, sourceURL.String(), getSourceOpts{
GetOptions: GetOptions{
VersionID: sourceVersion,
SSE: srcSSE,
Zip: uploadOpts.isZip,
Preserve: uploadOpts.preserve,
},
})
if err != nil {
return uploadOpts.urls.WithError(err.Trace(sourceURL.String()))
}
}
defer reader.Close()

Expand Down
Loading