1package moxio
2
3import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "testing"
8
9 "github.com/mjl-/mox/mlog"
10)
11
12func tcheckf(t *testing.T, err error, format string, args ...any) {
13 if err != nil {
14 t.Helper()
15 t.Fatalf("%s: %s", fmt.Sprintf(format, args...), err)
16 }
17}
18
19func TestLinkOrCopy(t *testing.T) {
20 log := mlog.New("linkorcopy", nil)
21
22 // link in same directory. file exists error. link to file in non-existent
23 // directory (exists error). link to file in system temp dir (hopefully other file
24 // system).
25 src := "linkorcopytest-src.txt"
26 f, err := os.Create(src)
27 tcheckf(t, err, "creating test file")
28 defer os.Remove(src)
29 defer f.Close()
30 err = LinkOrCopy(log, "linkorcopytest-dst.txt", src, nil, false)
31 tcheckf(t, err, "linking file")
32 err = os.Remove("linkorcopytest-dst.txt")
33 tcheckf(t, err, "remove dst")
34
35 err = LinkOrCopy(log, "bogus/linkorcopytest-dst.txt", src, nil, false)
36 if err == nil || !os.IsNotExist(err) {
37 t.Fatalf("expected is not exist, got %v", err)
38 }
39
40 // Try with copying the file. This can currently only really happen on systems that
41 // don't support hardlinking. Because other code and tests already use os.Rename on
42 // similar files, which will fail for being cross-filesystem (and we do want
43 // users/admins to have the mox temp dir on the same file system as the account
44 // files).
45 dst := filepath.Join(os.TempDir(), "linkorcopytest-dst.txt")
46 err = LinkOrCopy(log, dst, src, nil, true)
47 tcheckf(t, err, "copy file")
48 err = os.Remove(dst)
49 tcheckf(t, err, "removing dst")
50
51 // Copy based on open file.
52 _, err = f.Seek(0, 0)
53 tcheckf(t, err, "seek to start")
54 err = LinkOrCopy(log, dst, src, f, true)
55 tcheckf(t, err, "copy file from reader")
56 err = os.Remove(dst)
57 tcheckf(t, err, "removing dst")
58}
59