Merge pull request #427 from runkids/runkids/420-junction-cross-volume

fix(trash): keep junctions as junctions when moving across volumes
This commit is contained in:
Willie
2026-10-06 09:24:36 +08:00
committed by GitHub
11 changed files with 225 additions and 30 deletions
+3 -2
View File
@@ -488,13 +488,12 @@ internal/trash/trash.go RestoreAgent os.Rename srcPath, destPath agents
internal/trash/trash.go RestoreAgent os.WriteFile destPath agents
internal/trash/trash.go cleanEmptyParents os.Remove dir trash
internal/trash/trash.go copyDir os.MkdirAll dst source-unmigrated
internal/trash/trash.go copyDir os.Symlink target, dstPath source-unmigrated
internal/trash/trash.go copyFile os.OpenFile dst source-unmigrated
internal/trash/trash.go moveLink os.Remove dst source-unmigrated
internal/trash/trash.go moveLink os.Remove src source-checked
internal/trash/trash.go moveLink os.Symlink target, dst source-unmigrated
internal/trash/trash.go moveToTrash os.MkdirAll filepath.Dir(trashPath) trash
internal/trash/trash.go moveToTrash os.RemoveAll srcPath source-checked
internal/trash/trash.go recreateLink os.Symlink target, dst source-unmigrated
internal/trash/trash.go restore os.RemoveAll entry.Path trash
internal/uidist/uidist.go ClearCache os.RemoveAll dir config
internal/uidist/uidist.go ClearVersion os.RemoveAll dir config
@@ -510,6 +509,8 @@ internal/uidist/uidist.go extractTarGz os.OpenFile target config
internal/utils/frontmatter_write.go SetFrontmatterList os.WriteFile filePath source-unmigrated
internal/utils/frontmatter_write.go ToggleFrontmatterFlag os.WriteFile filePath source-unmigrated
internal/utils/frontmatter_write.go ToggleFrontmatterFlag os.WriteFile filePath source-unmigrated
internal/utils/link_windows.go CreateJunction os.Mkdir linkPath source-unmigrated
internal/utils/link_windows.go CreateJunction os.Remove linkPath source-unmigrated
internal/version/check.go ClearCache os.Remove getCachePath() config
internal/version/check.go cleanupLegacyCache os.Remove legacyPath config
internal/version/check.go cleanupLegacyCache os.Remove parentDir config
Can't render this file because it contains an unexpected character in line 23 and column 89.
+1 -1
View File
@@ -243,7 +243,7 @@ func putBackExtraRestorePoint(path string) error {
case fileExists(filepath.Join(dir, attachRestoreJunction)):
dest, err := os.ReadFile(filepath.Join(dir, attachRestoreJunction))
if err == nil {
err = createJunction(path, string(dest))
err = utils.CreateJunction(path, string(dest))
}
if err != nil {
return fmt.Errorf("failed to restore %s: %w", path, err)
+1 -1
View File
@@ -200,7 +200,7 @@ func RestoreFileBackup(path, id string, unlink bool) (string, error) {
return saved, err
}
if v.junction {
err = createJunction(path, v.LinkTo)
err = utils.CreateJunction(path, v.LinkTo)
} else {
err = os.Symlink(v.LinkTo, path)
}
-6
View File
@@ -3,7 +3,6 @@
package sync
import (
"fmt"
"os"
"path/filepath"
)
@@ -43,8 +42,3 @@ func isJunctionOrSymlink(path string) bool {
}
return info.Mode()&os.ModeSymlink != 0
}
// createJunction cannot recreate a Windows junction on another platform.
func createJunction(linkPath, sourcePath string) error {
return fmt.Errorf("cannot restore Windows junction %s to %s on this platform", linkPath, sourcePath)
}
+1 -16
View File
@@ -3,13 +3,10 @@
package sync
import (
"bytes"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"strings"
gosync "sync"
"skillshare/internal/utils"
@@ -64,7 +61,7 @@ func createLink(linkPath, sourcePath string, relative bool, sourceRoot ...string
}
// Try junction (no admin required, but requires absolute paths)
junctionErr := createJunction(absTarget, absSource)
junctionErr := utils.CreateJunction(absTarget, absSource)
if junctionErr == nil {
return nil
}
@@ -81,18 +78,6 @@ func createLink(linkPath, sourcePath string, relative bool, sourceRoot ...string
return errors.New(errMsg)
}
// createJunction is also used to restore an original junction exactly, without
// requiring symlink privileges or falling back to a different link kind.
func createJunction(linkPath, sourcePath string) error {
var stderr bytes.Buffer
cmd := exec.Command("cmd", "/c", "mklink", "/J", linkPath, sourcePath)
cmd.Stderr = &stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("mklink /J: %w: %s", err, strings.TrimSpace(stderr.String()))
}
return nil
}
// canCreateRelativeLink probes whether the OS can create relative symlinks.
// On Windows this requires Developer Mode; without it createLink falls back
// to junctions which are always absolute.
+13 -3
View File
@@ -469,7 +469,7 @@ func moveLink(src, dst string, rename func(string, string) error) error {
return err
}
}
if err := os.Symlink(target, dst); err != nil {
if err := recreateLink(src, target, dst); err != nil {
return err
}
if err := os.Remove(src); err != nil {
@@ -480,6 +480,16 @@ func moveLink(src, dst string, rename func(string, string) error) error {
return nil
}
// recreateLink creates at dst a link to target of the same kind as the one at
// src. A junction stays a junction: a symlink would need Developer Mode or
// elevation on Windows, which the junction was chosen to avoid.
func recreateLink(src, target, dst string) error {
if utils.IsJunction(src) {
return utils.CreateJunction(dst, target)
}
return os.Symlink(target, dst)
}
// RestoreAgent restores agent files from a trashed directory back to the agent source.
// Unlike Restore (which moves the whole directory), this copies individual files
// from the trashed directory to destDir (since agents are file-based, not directory-based).
@@ -601,7 +611,7 @@ func copyDir(src, dst string) error {
}
// Preserve link text without copying the target. Junctions may need
// ResolveLinkTarget, as in moveLink, then a symlink fallback.
// ResolveLinkTarget, as in moveLink, and are recreated as junctions.
if utils.IsLinkMode(srcPath, info.Mode()) {
target, err := os.Readlink(srcPath)
if err != nil {
@@ -610,7 +620,7 @@ func copyDir(src, dst string) error {
if err != nil {
return err
}
if err := os.Symlink(target, dstPath); err != nil {
if err := recreateLink(srcPath, target, dstPath); err != nil {
return err
}
continue
@@ -0,0 +1,66 @@
//go:build windows
package trash
import (
"fmt"
"os"
"path/filepath"
"testing"
"skillshare/internal/utils"
)
func crossDevice(string, string) error { return fmt.Errorf("cross-device rename") }
func TestMoveJunctionAcrossVolumesStaysJunction(t *testing.T) {
base := t.TempDir()
target := filepath.Join(base, "checkout")
source := filepath.Join(base, "source")
os.MkdirAll(target, 0755)
os.MkdirAll(source, 0755)
link := filepath.Join(source, "_dev-skills")
if err := utils.CreateJunction(link, target); err != nil {
t.Skip(err)
}
trashed, err := moveToTrash(link, "_dev-skills", filepath.Join(base, "trash"), crossDevice)
if err != nil {
t.Fatal(err)
}
if !utils.IsJunction(trashed) {
t.Fatalf("trashed entry is not a junction")
}
items := List(filepath.Join(base, "trash"))
if len(items) != 1 {
t.Fatalf("list = %+v", items)
}
if err := restore(&items[0], source, crossDevice); err != nil {
t.Fatal(err)
}
if !utils.IsJunction(link) {
t.Fatalf("restored entry is not a junction")
}
if got, err := utils.ResolveLinkTarget(link); err != nil || got != target {
t.Fatalf("restored target = %q, %v; want %q", got, err, target)
}
}
func TestMoveJunctionFailureKeepsOriginal(t *testing.T) {
base := t.TempDir()
target := filepath.Join(base, "checkout")
os.MkdirAll(target, 0755)
link := filepath.Join(base, "link")
if err := utils.CreateJunction(link, target); err != nil {
t.Skip(err)
}
dst := filepath.Join(base, "occupied")
os.WriteFile(dst, nil, 0644) // mklink /J refuses an existing destination
if err := moveLink(link, dst, crossDevice); err == nil {
t.Fatal("expected an error")
}
if !utils.IsJunction(link) {
t.Fatal("original junction was not kept")
}
}
+7
View File
@@ -26,6 +26,13 @@ func IsLinkMode(path string, m fs.FileMode) bool {
return m&fs.ModeIrregular != 0 && isJunction(path)
}
// IsJunction reports whether path is a Windows junction, as opposed to a symlink.
// With GODEBUG=winsymlink=0 Go reports a junction as ModeSymlink, so check both.
func IsJunction(path string) bool {
info, err := os.Lstat(path)
return err == nil && info.Mode()&(fs.ModeIrregular|fs.ModeSymlink) != 0 && isJunction(path)
}
// isJunction reports whether path is a Windows junction (mount point).
// A variable so tests on other platforms can simulate one.
var isJunction = platformIsJunction
+7
View File
@@ -2,5 +2,12 @@
package utils
import "fmt"
// platformIsJunction returns false: junctions exist only on Windows.
func platformIsJunction(string) bool { return false }
// CreateJunction cannot recreate a Windows junction on another platform.
func CreateJunction(linkPath, sourcePath string) error {
return fmt.Errorf("cannot restore Windows junction %s to %s on this platform", linkPath, sourcePath)
}
+74 -1
View File
@@ -2,7 +2,13 @@
package utils
import "syscall"
import (
"fmt"
"os"
"path/filepath"
"strings"
"syscall"
)
// ioReparseTagMountPoint is the reparse tag of a junction (IO_REPARSE_TAG_MOUNT_POINT).
const ioReparseTagMountPoint = 0xA0000003
@@ -23,3 +29,70 @@ func platformIsJunction(path string) bool {
// For a reparse point, FindFirstFile reports its tag in Reserved0.
return data.FileAttributes&syscall.FILE_ATTRIBUTE_REPARSE_POINT != 0 && data.Reserved0 == ioReparseTagMountPoint
}
// fsctlSetReparsePoint is FSCTL_SET_REPARSE_POINT.
const fsctlSetReparsePoint = 0x000900A4
// CreateJunction creates a directory junction (no admin required) through the
// reparse-point API, so no shell ever parses the paths. It never falls back to
// a symlink, so callers can restore a junction exactly. Like mklink /J it fails
// when linkPath already exists.
func CreateJunction(linkPath, sourcePath string) error {
target, err := filepath.Abs(sourcePath)
if err != nil {
return fmt.Errorf("create junction %s: %w", linkPath, err)
}
// Like mklink /J, refuse a network path: a junction cannot point at one.
if strings.HasPrefix(target, `\\`) && !strings.HasPrefix(target, `\\?\`) {
return fmt.Errorf("create junction %s: a junction cannot target the network path %s", linkPath, target)
}
if err := os.Mkdir(linkPath, 0777); err != nil {
return err
}
if err := setJunctionTarget(linkPath, target); err != nil {
os.Remove(linkPath)
return fmt.Errorf("create junction %s: %w", linkPath, err)
}
return nil
}
func setJunctionTarget(linkPath, target string) error {
name, err := syscall.UTF16PtrFromString(linkPath)
if err != nil {
return err
}
h, err := syscall.CreateFile(name, syscall.GENERIC_WRITE, 0, nil, syscall.OPEN_EXISTING,
syscall.FILE_FLAG_BACKUP_SEMANTICS|syscall.FILE_FLAG_OPEN_REPARSE_POINT, 0)
if err != nil {
return err
}
defer syscall.CloseHandle(h)
// The substitute name is an NT path: \??\C:\x. A Win32 extended path such
// as \\?\C:\x or \\?\Volume{GUID}\x only needs its prefix swapped.
display := strings.TrimPrefix(target, `\\?\`)
sub, err := syscall.UTF16FromString(`\??\` + display)
if err != nil {
return err
}
print, err := syscall.UTF16FromString(display)
if err != nil {
return err
}
// sub and print include their NUL terminators; the name lengths exclude them.
subBytes, printBytes := (len(sub)-1)*2, (len(print)-1)*2
pathBytes := len(sub)*2 + len(print)*2
buf := make([]byte, 16+pathBytes)
put16 := func(off int, v int) { buf[off], buf[off+1] = byte(v), byte(v>>8) }
buf[0], buf[1], buf[2], buf[3] = 0x03, 0x00, 0x00, 0xA0 // IO_REPARSE_TAG_MOUNT_POINT
put16(4, 8+pathBytes) // ReparseDataLength
put16(8, 0) // SubstituteNameOffset
put16(10, subBytes)
put16(12, len(sub)*2) // PrintNameOffset
put16(14, printBytes)
for i, c := range append(append([]uint16{}, sub...), print...) {
put16(16+i*2, int(c))
}
var returned uint32
return syscall.DeviceIoControl(h, fsctlSetReparsePoint, &buf[0], uint32(len(buf)), nil, 0, &returned, nil)
}
+52
View File
@@ -0,0 +1,52 @@
//go:build windows
package utils
import (
"os"
"path/filepath"
"testing"
)
func TestCreateJunctionPathWithCmdMetacharacters(t *testing.T) {
base := t.TempDir()
target := filepath.Join(base, "target&more%TEMP%")
os.MkdirAll(target, 0755)
link := filepath.Join(base, "link&echo%TEMP%")
if err := CreateJunction(link, target); err != nil {
t.Fatal(err)
}
if !IsJunction(link) {
t.Fatal("link is not a junction")
}
if got, err := ResolveLinkTarget(link); err != nil || got != target {
t.Fatalf("target = %q, %v; want %q", got, err, target)
}
}
func TestCreateJunctionExtendedPathTarget(t *testing.T) {
base := t.TempDir()
target := filepath.Join(base, "target")
os.MkdirAll(target, 0755)
os.WriteFile(filepath.Join(target, "marker"), []byte("x"), 0644)
link := filepath.Join(base, "link")
if err := CreateJunction(link, `\\?\`+target); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(filepath.Join(link, "marker")); err != nil {
t.Fatalf("cannot read through the junction: %v", err)
}
}
func TestCreateJunctionRefusesNetworkPath(t *testing.T) {
link := filepath.Join(t.TempDir(), "link")
if err := CreateJunction(link, `\\localhost\C$\Users`); err == nil {
t.Fatal("expected an error for a UNC target")
}
if _, err := os.Lstat(link); !os.IsNotExist(err) {
t.Fatalf("link was left behind: %v", err)
}
}