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
8 changes: 6 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,9 @@ The window is view glue. Logic lives in plain classes that the tests drive with
6. **Elevation.cs**: `LaunchOptions` (command-line parsing) and `Elevation` (admin check, symbolic link privilege probe, the UAC shield icon).
7. **LinkCreator.cs**: The link workflow: replace-existing prompts, and moving an existing file or folder to the target (rename on the same drive, copy with progress across drives, rollback on failure).
8. **LinkRunner.cs**: `ILinkRunner`, which `LinkCreator` uses to create links. `LinkRunner` runs mklink unelevated, except symbolic links that need admin, which go through the elevated helper. `PrepareAsync()` starts the helper (one UAC prompt) before anything on disk changes.
9. **LinkCommand.cs**: `LinkKind`, `LinkRequest`/`LinkResult` and `LinkCommand.RunAsync()`, which runs `cmd.exe /c mklink`. Used unelevated and by the elevated helper.
9. **LinkCommand.cs**: `LinkKind`, `LinkRequest`/`LinkResult` and `LinkCommand.RunAsync()`, which runs `cmd.exe /c mklink`. Used unelevated and by the elevated helper. Success comes from the exit code plus `LinkCheck.IsCreated()` on disk, never from mklink's text (it is in the language of Windows). A failure carries a `LinkError` code from `LinkCheck.Diagnose()`, which travels over the helper's pipe as a number.
- **LinkCheck.cs**: checks on disk that a link exists and leads to its target, and works out why mklink failed (link path taken, hard link across drives, junction to a network folder, no symbolic link privilege, folder access denied).
- **LinkResultMessage.cs**: turns a request and its `LinkResult` into the localized dialog title and text. `Reason()` gives one failure line, for reuse in a list of results. Long paths are shortened in the middle (`CompactPath`).
10. **ElevatedLinker.cs**: Starts `Symlinker.exe --link-helper` as administrator and sends it link requests over a named pipe. `RunHelper()` is the helper's side.
11. **LinkMover.cs**: File system helpers for moving: copy that keeps attributes and recreates nested links, delete that never follows links.
12. **InputValidator.cs**: Field checks behind the inline errors, and `ColorContrast` for text on the accent color.
Expand All @@ -97,7 +99,7 @@ The window is view glue. Logic lives in plain classes that the tests drive with
2. User fills in the link location, link name and target (typing, browsing, or drag and drop).
3. Create link (or Enter, it is the default button) runs `ValidateInputs()`, which marks the fields `InputValidator` flags.
4. `RefreshSymlinkAccessNow()` probes again whether a symbolic link needs administrator rights.
5. `LinkCreator.CreateAsync()` handles an existing item at the link path (replace it, or move it to the target), then runs mklink and shows the result. `ILinkRunner.PrepareAsync()` is called before the first change on disk.
5. `LinkCreator.CreateAsync()` handles an existing item at the link path (replace it, or move it to the target), then runs mklink and shows the result through `LinkResultMessage`. `ILinkRunner.PrepareAsync()` is called before the first change on disk.

### Administrator rights

Expand Down Expand Up @@ -135,6 +137,8 @@ Symlinker/
│ ├── LinkCreator.cs # Link workflow
│ ├── LinkRunner.cs # Unelevated or elevated mklink
│ ├── LinkCommand.cs # Runs mklink
│ ├── LinkCheck.cs # Verifies links on disk, diagnoses failures
│ ├── LinkResultMessage.cs # Localized result dialog text
│ ├── ElevatedLinker.cs # Elevated link helper over a named pipe
│ ├── LinkMover.cs # Move/copy/delete helpers
│ ├── InputValidator.cs # Field checks, accent contrast
Expand Down
9 changes: 6 additions & 3 deletions Symlinker.Tests/ElevatedLinkerTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,6 @@ namespace Symlinker.Tests
using System.Text;
using System.Threading.Tasks;

using Res = Symlinker.Properties.Resources;

/// <summary>
/// Tests the pipe protocol between the window and the elevated helper, in one process and
/// without UAC: the test holds the window's end, and the helper loop runs on a background thread.
Expand Down Expand Up @@ -56,7 +54,12 @@ public async Task Helper_CreatesEachLinkItIsSent_UntilTheWindowCloses()
Assert.True(first.Success, first.Message);
Assert.True(second.Success, second.Message);
Assert.True(LinkMover.IsLink(new DirectoryInfo(temp.PathOf("second"))));
Assert.Equal((false, Res.InvalidQuoteInPath), (refused.Success, refused.Message));
Assert.Equal((false, LinkError.InvalidPath), (refused.Success, refused.Error));

// The reason comes back over the pipe, with mklink's own text as a detail
var taken = await linker.CreateLinkAsync(Junction(temp.PathOf("first"), target));
Assert.Equal((false, LinkError.LinkExists), (taken.Success, taken.Error));
Assert.NotEmpty(taken.Message);

linker.Dispose();
Assert.Equal(0, await helper.WaitAsync(TimeSpan.FromMilliseconds(Timeout), TestContext.Current.CancellationToken));
Expand Down
178 changes: 178 additions & 0 deletions Symlinker.Tests/LinkCheckTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
namespace Symlinker.Tests
{
using System;
using System.IO;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading.Tasks;

public sealed class LinkCheckTests : IDisposable
{
private readonly TempDir temp = new();

public void Dispose() => temp.Dispose();

private static LinkRequest Request(string type, string link, string target, bool directory = true) =>
new() { Type = type, Link = link, Target = target, Directory = directory };

// ---- IsCreated ----

[Fact]
public void IsCreated_AcceptsAJunctionToTheTarget_WithOrWithoutATrailingSeparator()
{
var target = temp.Dir("target");
var link = temp.Junction(temp.PathOf("link"), target).FullName;

Assert.True(LinkCheck.IsCreated(Request("junction", link, target)));
Assert.True(LinkCheck.IsCreated(Request("junction", link, target + "\\")));
}

[Fact]
public void IsCreated_RejectsALinkThatPointsSomewhereElse()
{
var target = temp.Dir("target");
var link = temp.Junction(temp.PathOf("link"), temp.Dir("other")).FullName;

Assert.False(LinkCheck.IsCreated(Request("junction", link, target)));
}

[Fact]
public void IsCreated_RejectsAPlainFolderOrNothing()
{
var target = temp.Dir("target");

Assert.False(LinkCheck.IsCreated(Request("junction", temp.Dir("plain"), target)));
Assert.False(LinkCheck.IsCreated(Request("symbolic", temp.PathOf("missing"), target)));
}

[Fact]
public void IsCreated_ResolvesARelativeSymbolicLinkTarget_AgainstTheLinksFolder()
{
SymlinkSupport.Require();
temp.File(@"files\target.txt");
var link = temp.PathOf("links", "link.txt");
Directory.CreateDirectory(temp.PathOf("links"));
File.CreateSymbolicLink(link, @"..\files\target.txt");

Assert.True(LinkCheck.IsCreated(Request("symbolic", link, @"..\files\target.txt", directory: false)));
Assert.False(LinkCheck.IsCreated(Request("symbolic", link, @"..\files\other.txt", directory: false)));
}

[Fact]
public async Task IsCreated_AcceptsAHardLinkToTheSameFile_Only()
{
var target = temp.File("target.txt");
var link = temp.PathOf("link.txt");
Assert.True((await LinkCommand.RunAsync(Request("hard", link, target, directory: false))).Success);
var other = temp.File("other.txt");

Assert.True(LinkCheck.IsCreated(Request("hard", link, target, directory: false)));
Assert.False(LinkCheck.IsCreated(Request("hard", other, target, directory: false)));
Assert.False(LinkCheck.IsCreated(Request("hard", temp.PathOf("missing.txt"), target, directory: false)));
}

[Fact]
public void IsSameFile_AssumesYes_WhenAFileCantBeOpened()
{
var target = temp.File("target.txt");
var other = temp.File("other.txt");

using (new FileStream(other, FileMode.Open, FileAccess.Read, FileShare.None))
Assert.True(LinkCheck.IsSameFile(target, other));

Assert.False(LinkCheck.IsSameFile(target, other));
}

// ---- Diagnose ----

private static LinkError Diagnose(LinkRequest request, bool existedBefore = false, bool canCreateSymlinks = true, bool canWrite = true) =>
LinkCheck.Diagnose(request, existedBefore, () => canCreateSymlinks, _ => canWrite);

[Fact]
public void Diagnose_ReportsAnExistingLinkPathFirst()
{
Assert.Equal(LinkError.LinkExists, Diagnose(Request("hard", @"C:\a\link", @"D:\b\target"), existedBefore: true, canWrite: false));
}

[Theory]
[InlineData(@"D:\b\target", nameof(LinkError.HardLinkAcrossDrives))]
[InlineData(@"C:\b\target", nameof(LinkError.Unknown))]
public void Diagnose_ChecksHardLinksAreOnTheTargetsDrive(string target, string expected)
{
Assert.Equal(Enum.Parse<LinkError>(expected), Diagnose(Request("hard", @"C:\a\link", target, directory: false)));
}

[Theory]
[InlineData(@"\\server\share\folder", nameof(LinkError.JunctionNeedsLocalFolder))]
[InlineData(@"C:\folder", nameof(LinkError.Unknown))]
public void Diagnose_ChecksJunctionsPointToALocalFolder(string target, string expected)
{
Assert.Equal(Enum.Parse<LinkError>(expected), Diagnose(Request("junction", @"C:\a\link", target)));
}

[Theory]
[InlineData(false, nameof(LinkError.NeedsAdmin))]
[InlineData(true, nameof(LinkError.Unknown))]
public void Diagnose_ChecksTheSymbolicLinkPrivilege(bool canCreateSymlinks, string expected)
{
Assert.Equal(Enum.Parse<LinkError>(expected), Diagnose(Request("symbolic", @"C:\a\link", @"\\server\share"), canCreateSymlinks: canCreateSymlinks));
}

[Fact]
public void Diagnose_ChecksTheLinksFolderCanBeWritten()
{
string folder = null;
var error = LinkCheck.Diagnose(Request("junction", @"C:\a\link", @"C:\b"), false, () => true, f =>
{
folder = f;
return false;
});

Assert.Equal((LinkError.AccessDenied, @"C:\a"), (error, folder));
}

// ---- Helpers ----

[Fact]
public void CanWriteTo_IsTrue_ForAWritableFolder_AndLeavesNothingBehind()
{
var folder = temp.Dir("open");

Assert.True(LinkCheck.CanWriteTo(folder));
Assert.Empty(Directory.GetFileSystemEntries(folder));
}

[Fact]
public void CanWriteTo_IsTrue_WhenTheProblemIsNotAccess()
{
Assert.True(LinkCheck.CanWriteTo(temp.PathOf("missing")));
}

[Fact]
public void CanWriteTo_IsFalse_WhenCreatingFilesIsDenied()
{
var folder = new DirectoryInfo(temp.Dir("locked"));
var security = folder.GetAccessControl();
var deny = new FileSystemAccessRule(WindowsIdentity.GetCurrent().User, FileSystemRights.CreateFiles, AccessControlType.Deny);
security.AddAccessRule(deny);
folder.SetAccessControl(security);
try
{
Assert.False(LinkCheck.CanWriteTo(folder.FullName));
}
finally
{
security.RemoveAccessRule(deny);
folder.SetAccessControl(security);
}
}

[Theory]
[InlineData(@"\\server\share\folder", true)]
[InlineData(@"C:\folder", false)]
public void IsNetworkPath_SpotsShares(string path, bool expected)
{
Assert.Equal(expected, LinkCheck.IsNetworkPath(path));
}
}
}
73 changes: 59 additions & 14 deletions Symlinker.Tests/LinkCommandTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,6 @@ namespace Symlinker.Tests
using System.IO;
using System.Threading.Tasks;

using Res = Symlinker.Properties.Resources;

public sealed class LinkCommandTests : IDisposable
{
private readonly TempDir temp = new();
Expand Down Expand Up @@ -52,30 +50,52 @@ public async Task RunAsync_ReportsARefusedRequest_WithoutRunningAnything()
{
var result = await LinkCommand.RunAsync(Request(target: "D:\\\"x"), temp.PathOf("no-such-shell.exe"));

Assert.Equal((false, Res.InvalidQuoteInPath), (result.Success, result.Message));
Assert.Equal((false, LinkError.InvalidPath), (result.Success, result.Error));
}

[Fact]
public async Task RunAsync_ReportsAMissingShell()
{
var result = await LinkCommand.RunAsync(Request(), temp.PathOf("no-such-shell.exe"));

Assert.Equal((false, Res.CmdNotFound), (result.Success, result.Message));
Assert.Equal((false, LinkError.CommandNotFound), (result.Success, result.Error));
}

[Theory]
[InlineData("@echo hello", "hello")]
[InlineData("@exit 0", "")]
public async Task RunAsync_ChecksThatTheLinkIsThere_EvenWhenTheShellSaysItWorked(string script, string output)
{
// A stand-in for cmd.exe that ignores the mklink arguments, so no link appears
var shell = temp.File("shell.cmd", script);

var result = await LinkCommand.RunAsync(Request("junction", temp.PathOf("link"), temp.Dir("target")), shell);

Assert.Equal((false, LinkError.NotCreated, output), (result.Success, result.Error, result.Message));
}

[Fact]
public async Task RunAsync_Succeeds_WhenTheShellWorkedAndTheLinkIsThere()
{
var target = temp.Dir("target");
var link = temp.Junction(temp.PathOf("link"), target).FullName;
var shell = temp.File("shell.cmd", "@echo made it");

var result = await LinkCommand.RunAsync(Request("junction", link, target), shell);

Assert.Equal((true, LinkError.None, "made it"), (result.Success, result.Error, result.Message));
}

[Theory]
[InlineData("@echo hello", true, "hello")]
[InlineData("@exit 0", true, null)]
[InlineData("@echo oops 1>&2\r\n@exit 3", false, "oops")]
[InlineData("@echo plain\r\n@exit 2", false, "plain")]
public async Task RunAsync_UsesTheShellsOutput(string script, bool success, string message)
[InlineData("@echo oops 1>&2\r\n@exit 3", "oops")]
[InlineData("@echo plain\r\n@exit 2", "plain")]
public async Task RunAsync_KeepsTheShellsErrorText_WhenTheReasonIsUnknown(string script, string message)
{
// A stand-in for cmd.exe that ignores the mklink arguments
var shell = temp.File("shell.cmd", script);

var result = await LinkCommand.RunAsync(Request(), shell);
var result = await LinkCommand.RunAsync(Request("junction", temp.PathOf("link"), temp.Dir("target")), shell);

Assert.Equal((success, message ?? Res.LinkSuccessfullyCreated), (result.Success, result.Message));
Assert.Equal((false, LinkError.Unknown, message), (result.Success, result.Error, result.Message));
}

[Fact]
Expand All @@ -88,22 +108,47 @@ public async Task RunAsync_CreatesARealJunction()
var result = await LinkCommand.RunAsync(Request("junction", link, target));

Assert.True(result.Success, result.Message);
Assert.Equal(LinkError.None, result.Error);
Assert.True(LinkMover.IsLink(new DirectoryInfo(link)));
Assert.True(File.Exists(Path.Combine(link, "inside.txt")));
}

[Fact]
public async Task RunAsync_ReportsMklinkErrors()
public async Task RunAsync_ReportsAnExistingLinkPath_WithMklinksText()
{
var target = temp.Dir("target");
var link = temp.Dir("taken");

var result = await LinkCommand.RunAsync(Request("junction", link, target));

Assert.False(result.Success);
Assert.Equal((false, LinkError.LinkExists), (result.Success, result.Error));
Assert.NotEmpty(result.Message);
}

[Fact]
public async Task RunAsync_CreatesARealHardLink()
{
var target = temp.File("target.txt", "same");
var link = temp.PathOf("link.txt");

var result = await LinkCommand.RunAsync(Request("hard", link, target, directory: false));

Assert.True(result.Success, result.Message);
Assert.Equal("same", File.ReadAllText(link));
}

[Fact]
public async Task RunAsync_CreatesARealSymbolicLink()
{
SymlinkSupport.Require();
var target = temp.Dir("target");
var link = temp.PathOf("link");

var result = await LinkCommand.RunAsync(Request("symbolic", link, target));

Assert.True(result.Success, result.Message);
}

[Theory]
[InlineData("Symbolic", "symbolic")]
[InlineData("Hard", "hard")]
Expand Down
Loading
Loading