diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 1c17657..417caee 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -19,3 +19,14 @@ jobs: - name: Build run: dotnet build Symlinker/Symlinker.csproj --configuration Release + + - name: Test (fails below 100% coverage) + run: dotnet test --project Symlinker.Tests/Symlinker.Tests.csproj --configuration Release + + - name: Upload coverage report + if: always() + uses: actions/upload-artifact@v4 + with: + name: coverage + path: TestResults/*.cobertura.xml + if-no-files-found: ignore diff --git a/.gitignore b/.gitignore index b18996e..45b4178 100644 --- a/.gitignore +++ b/.gitignore @@ -204,6 +204,7 @@ pip-log.txt # Unit test / coverage reports .coverage +TestResults/ .tox #Translations diff --git a/CLAUDE.md b/CLAUDE.md index f789d5f..9eda43b 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -28,6 +28,18 @@ dotnet run --project "Symlinker/Symlinker.csproj" The app starts unelevated. It only asks for administrator rights when a symbolic link needs them (see "Administrator rights" below). +### Running the Tests + +```powershell +dotnet test --project Symlinker.Tests +``` + +- xUnit v3 on Microsoft.Testing.Platform (opted in through [global.json](global.json)), with coverage from `coverlet.MTP` +- Every run collects coverage for the `Symlinker` assembly and **fails below 100% line, branch or method coverage**. The Cobertura report lands in `TestResults/` +- Tests use the real file system under `%TEMP%`. Symbolic link tests need Developer Mode or an elevated prompt (GitHub's Windows runners are elevated) +- Code that needs a live window, UAC or native calls (`MainWindow`, `App`, `Program`, `MetroDialogService`, `InputError`, `ElevatedLinker.StartAsync`, `Elevation.GetShieldIcon`) is marked `[ExcludeFromCodeCoverage]`. Keep logic out of those and put it in a tested class instead +- The elevated helper's pipe protocol is tested in-process: the test plays the window's end of the pipe and runs `ElevatedLinker.RunHelper` on a background thread, so no UAC prompt is involved + ### Publishing - `./release.ps1` builds and publishes the ClickOnce installer to the `gh-pages` branch (`-OnlyBuild` skips deployment). It reads the Git tag for the version (`v1.2.3` becomes `1.2.3.0`). @@ -35,32 +47,39 @@ The app starts unelevated. It only asks for administrator rights when a symbolic ## Architecture +The window is view glue. Logic lives in plain classes that the tests drive with fake dialogs and a fake mklink. + ### Key Components 1. **Program.cs**: Entry point. Parses command-line options (`LaunchOptions`) and opens the main window. It does not elevate. With `--link-helper` it runs the hidden elevated helper instead (see "Administrator rights"). 2. **App.xaml / App.xaml.cs**: Loads MahApps.Metro styles and syncs the theme (light/dark and accent color) with Windows. 3. **MainWindow.xaml**: The whole UI. Two cards (link location, target), pill toggles for folder/file mode and link type, and a footer with the About button, an inline error line and the Create link button. Styles live in `Window.Resources`. -4. **MainWindow.xaml.cs**: Mode switching, link name auto-fill, file pickers, drag and drop, and link creation (`CreateLink()`, `SendCommand()`, the move-and-link flow, and `RunMklinkAsync()`). -5. **MainWindow.Inputs.cs**: Field validation with inline errors (`InputError.HasError` attached property plus the footer message), theme-dependent brushes, restoring launch options, the up-front admin notice, and starting the elevated helper on demand (`ElevateIfNeededAsync()`). +4. **MainWindow.xaml.cs**: Mode switching, link name auto-fill, file pickers, drag and drop. Hands link creation to `LinkCreator`. +5. **MainWindow.Inputs.cs**: Inline errors (`InputError.HasError` attached property plus the footer message), theme-dependent brushes, restoring launch options, and the up-front admin notice. 6. **Elevation.cs**: `LaunchOptions` (command-line parsing) and `Elevation` (admin check, symbolic link privilege probe, the UAC shield icon). -7. **LinkCommand.cs**: `LinkRequest`/`LinkResult` and `LinkCommand.RunAsync()`, which runs `cmd.exe /c mklink`. Used by the window and by the elevated helper. -8. **ElevatedLinker.cs**: Starts `Symlinker.exe --link-helper` as administrator and sends it link requests over a named pipe. -9. **LinkMover.cs**: File system helpers for moving an existing file or folder to the target before linking. +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. +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. +13. **Dialogs.cs**: `IDialogService` / `IProgressDialog`, and `MetroDialogService`, which shows them in the window. +14. **UiHelpers.cs**: Path name extraction, picker start folders, byte formatting, app version, `LinkNameAutoFill`. ### Link Creation Flow 1. User picks folder or file mode (pills) and a link type. Junction is folder-only, hard link is file-only. 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 bad fields inline. +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. `CreateLink()` handles an existing item at the link path (delete it, or move it to the target), then `SendCommand()` runs mklink and shows the result. `ElevateIfNeededAsync()` 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. `ILinkRunner.PrepareAsync()` is called before the first change on disk. ### Administrator rights - Junctions and hard links never need admin. Symbolic links need admin unless Windows Developer Mode is on. - `Elevation.CanCreateSymbolicLinks()` probes by creating a throwaway symlink in the temp folder. - The probe runs when the window loads (again on activation while admin is needed, and on Create link). If symbolic links need admin, Create link shows the UAC shield and the footer says Windows will ask for permission, so the user knows before filling in the form. Field errors take the same footer spot and hide the notice. -- The window never restarts or elevates itself, so drag and drop keeps working. When a symbolic link needs admin, `ElevateIfNeededAsync()` starts `Symlinker.exe --link-helper ` with `runas` (one UAC prompt). The helper has no window: it connects back over the named pipe and creates each link it is sent with mklink. It stays up until the window closes (or it is ended, then the next symbolic link starts a new one), so the user approves UAC once per session. While it runs, the shield and the footer notice are hidden. Only symbolic links that need admin go through it; junctions and hard links always run unelevated. +- The window never restarts or elevates itself, so drag and drop keeps working. When a symbolic link needs admin, `LinkRunner.PrepareAsync()` starts `Symlinker.exe --link-helper ` with `runas` (one UAC prompt). The helper has no window: it connects back over the named pipe and creates each link it is sent with mklink. It stays up until the window closes (or it is ended, then the next symbolic link starts a new one), so the user approves UAC once per session. While it runs, the shield and the footer notice are hidden. Only symbolic links that need admin go through it; junctions and hard links always run unelevated. - Elevation happens before anything on disk changes (deleting an existing item, or the move-and-link flow), so declining the UAC prompt (Win32 error 1223) quietly stops and leaves everything as it was. - Both ends check the other's process ID on the pipe (`GetNamedPipeClientProcessId` / `GetNamedPipeServerProcessId`), and `LinkCommand` rejects paths with quotes or line breaks, so the helper only ever runs a single mklink. - Command-line options (`--mode`, `--type`, `--location`, `--name`, `--target`) still prefill the form. The old `--engage` flag is still accepted and ignored. @@ -76,6 +95,7 @@ Managed via Central Package Management ([Directory.Packages.props](Directory.Pac - **MahApps.Metro**: Window chrome, dialogs, theming - **MahApps.Metro.IconPacks.Material**: Icons +- **xunit.v3**, **coverlet.MTP**: Tests and coverage ## Project Structure @@ -84,12 +104,17 @@ Symlinker/ ├── Symlinker/ │ ├── App.xaml(.cs) # Application, theme sync │ ├── MainWindow.xaml # UI and styles -│ ├── MainWindow.xaml.cs # Core window logic and link creation -│ ├── MainWindow.Inputs.cs # Validation, inline errors, admin notice +│ ├── MainWindow.xaml.cs # Window glue +│ ├── MainWindow.Inputs.cs # Inline errors, admin notice │ ├── Elevation.cs # LaunchOptions, symlink probe, UAC shield +│ ├── LinkCreator.cs # Link workflow +│ ├── LinkRunner.cs # Unelevated or elevated mklink │ ├── LinkCommand.cs # Runs mklink │ ├── ElevatedLinker.cs # Elevated link helper over a named pipe -│ ├── LinkMover.cs # Move-and-link file system helpers +│ ├── LinkMover.cs # Move/copy/delete helpers +│ ├── InputValidator.cs # Field checks, accent contrast +│ ├── Dialogs.cs # Dialog abstraction + MahApps implementation +│ ├── UiHelpers.cs # Small UI helpers │ ├── Program.cs # Entry point │ ├── Properties/ │ │ ├── Resources.resx # English strings @@ -98,8 +123,10 @@ Symlinker/ │ │ └── app.manifest # asInvoker, PerMonitorV2 DPI │ ├── icon.ico │ └── Symlinker.csproj +├── Symlinker.Tests/ # xUnit tests, 100% coverage gate ├── Symlinker.sln ├── Directory.Packages.props +├── global.json # Opts dotnet test into Microsoft.Testing.Platform ├── release.ps1 # ClickOnce build/publish ├── build-portable.ps1 # Portable ZIP for Scoop └── .github/workflows/ # ci.yml, release.yml diff --git a/Directory.Packages.props b/Directory.Packages.props index 621c1a2..19e7640 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -8,4 +8,8 @@ + + + + \ No newline at end of file diff --git a/Symlinker.Tests/ElevatedLinkerTests.cs b/Symlinker.Tests/ElevatedLinkerTests.cs new file mode 100644 index 0000000..3758828 --- /dev/null +++ b/Symlinker.Tests/ElevatedLinkerTests.cs @@ -0,0 +1,181 @@ +namespace Symlinker.Tests +{ + using System; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.IO.Pipes; + using System.Text; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// + /// 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. + /// + public sealed class ElevatedLinkerTests : IDisposable + { + private const int Timeout = 5000; + private static readonly string ThisProcess = Environment.ProcessId.ToString(CultureInfo.InvariantCulture); + + private readonly TempDir temp = new(); + + public void Dispose() => temp.Dispose(); + + private static NamedPipeServerStream CreateServer(out string name) + { + name = "Symlinker-test-" + Guid.NewGuid().ToString("N"); + return new NamedPipeServerStream(name, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, PipeOptions.Asynchronous); + } + + /// Starts the helper loop and waits until it has connected. + private static async Task<(NamedPipeServerStream Pipe, Task Helper)> StartHelperAsync(string parentId = null) + { + var pipe = CreateServer(out var name); + var helper = Task.Run(() => ElevatedLinker.RunHelper(new[] { ElevatedLinker.HelperArg, name, parentId ?? ThisProcess }, Timeout)); + await pipe.WaitForConnectionAsync(TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromMilliseconds(Timeout), TestContext.Current.CancellationToken); + return (pipe, helper); + } + + private static LinkRequest Junction(string link, string target) => new() { Type = "junction", Link = link, Target = target, Directory = true }; + + [Fact] + public async Task Helper_CreatesEachLinkItIsSent_UntilTheWindowCloses() + { + var target = temp.Dir("target"); + var (pipe, helper) = await StartHelperAsync(); + var linker = new ElevatedLinker(pipe, Process.GetCurrentProcess()); + + Assert.True(linker.IsAlive); + + var first = await linker.CreateLinkAsync(Junction(temp.PathOf("first"), target)); + var second = await linker.CreateLinkAsync(Junction(temp.PathOf("second"), target)); + var refused = await linker.CreateLinkAsync(Junction(temp.PathOf("bad\"name"), target)); + + 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)); + + linker.Dispose(); + Assert.Equal(0, await helper.WaitAsync(TimeSpan.FromMilliseconds(Timeout), TestContext.Current.CancellationToken)); + } + + [Fact] + public async Task Helper_AnswersRequestsItCantRead_WithAnError() + { + var (pipe, helper) = await StartHelperAsync(); + using (pipe) + { + var writer = new StreamWriter(pipe, new UTF8Encoding(false), 1024, leaveOpen: true) { AutoFlush = true }; + var reader = new StreamReader(pipe, new UTF8Encoding(false), false, 1024, leaveOpen: true); + + await writer.WriteLineAsync("this is not json"); + var reply = System.Text.Json.JsonSerializer.Deserialize(await reader.ReadLineAsync(TestContext.Current.CancellationToken)); + + Assert.False(reply.Success); + Assert.NotEmpty(reply.Message); + } + + await helper.WaitAsync(TimeSpan.FromMilliseconds(Timeout), TestContext.Current.CancellationToken); + } + + [Fact] + public async Task Helper_RefusesAWindowItWasNotStartedFor() + { + // Started for another process, so the pipe's owner doesn't match + var (pipe, helper) = await StartHelperAsync(parentId: "4"); + using (pipe) + Assert.Equal(3, await helper.WaitAsync(TimeSpan.FromMilliseconds(Timeout), TestContext.Current.CancellationToken)); + } + + [Theory] + [InlineData("")] + [InlineData(ElevatedLinker.HelperArg + " pipe")] + [InlineData(ElevatedLinker.HelperArg + " pipe not-a-process-id")] + public void Helper_RejectsBadArguments(string commandLine) + { + var args = commandLine.Split(' ', StringSplitOptions.RemoveEmptyEntries); + + Assert.Equal(2, ElevatedLinker.RunHelper(args)); + } + + [Fact] + public void Helper_GivesUp_WhenTheWindowIsGone() + { + var args = new[] { ElevatedLinker.HelperArg, "Symlinker-test-missing-" + Guid.NewGuid().ToString("N"), ThisProcess }; + + Assert.Equal(1, ElevatedLinker.RunHelper(args, connectTimeoutMs: 100)); + } + + [Fact] + public async Task CreateLink_Throws_WhenTheHelperClosesWithoutAnswering() + { + var linker = await ConnectToFakeHelperAsync(reply: null); + + var error = await Assert.ThrowsAsync(() => linker.CreateLinkAsync(Junction(@"C:\a", @"C:\b"))); + Assert.Contains("closed", error.Message); + + // The broken pipe shows the helper is gone + Assert.False(linker.IsAlive); + } + + [Fact] + public async Task CreateLink_Throws_OnAnEmptyAnswer() + { + var linker = await ConnectToFakeHelperAsync(reply: "null"); + + var error = await Assert.ThrowsAsync(() => linker.CreateLinkAsync(Junction(@"C:\a", @"C:\b"))); + Assert.Contains("empty", error.Message); + } + + [Fact] + public async Task IsAlive_IsFalse_OnceTheHelperProcessHasExited() + { + using var exited = Process.Start(new ProcessStartInfo("cmd", "/c exit") { CreateNoWindow = true, UseShellExecute = false }); + await exited.WaitForExitAsync(TestContext.Current.CancellationToken); + var (pipe, helper) = await StartHelperAsync(); + + using (var linker = new ElevatedLinker(pipe, exited)) + Assert.False(linker.IsAlive); + + await helper.WaitAsync(TimeSpan.FromMilliseconds(Timeout), TestContext.Current.CancellationToken); + } + + [Fact] + public async Task IsAlive_IsFalse_WhenTheProcessCantBeChecked() + { + var process = Process.GetCurrentProcess(); + process.Dispose(); + var (pipe, helper) = await StartHelperAsync(); + + using (var linker = new ElevatedLinker(pipe, process)) + Assert.False(linker.IsAlive); + + await helper.WaitAsync(TimeSpan.FromMilliseconds(Timeout), TestContext.Current.CancellationToken); + } + + /// A helper that reads one request, sends (or nothing) and hangs up. + private static async Task ConnectToFakeHelperAsync(string reply) + { + var pipe = CreateServer(out var name); + _ = Task.Run(() => + { + using var client = new NamedPipeClientStream(".", name, PipeDirection.InOut); + client.Connect(Timeout); + var reader = new StreamReader(client, new UTF8Encoding(false), false, 1024, leaveOpen: true); + reader.ReadLine(); + if (reply != null) + { + var writer = new StreamWriter(client, new UTF8Encoding(false), 1024, leaveOpen: true) { AutoFlush = true }; + writer.WriteLine(reply); + client.WaitForPipeDrain(); + } + }); + + await pipe.WaitForConnectionAsync(TestContext.Current.CancellationToken).WaitAsync(TimeSpan.FromMilliseconds(Timeout), TestContext.Current.CancellationToken); + return new ElevatedLinker(pipe, Process.GetCurrentProcess()); + } + } +} diff --git a/Symlinker.Tests/ElevationTests.cs b/Symlinker.Tests/ElevationTests.cs new file mode 100644 index 0000000..2737933 --- /dev/null +++ b/Symlinker.Tests/ElevationTests.cs @@ -0,0 +1,90 @@ +namespace Symlinker.Tests +{ + using System; + using System.IO; + + public sealed class ElevationTests + { + // ERROR_PRIVILEGE_NOT_HELD as an HRESULT + private const int PrivilegeNotHeld = unchecked((int)0x80070522); + + [Fact] + public void Parse_ReadsEveryOption() + { + var options = LaunchOptions.Parse(new[] + { + "--mode", "file", "--type", "hard", "--location", @"C:\links", "--name", "my link", "--target", @"D:\data.txt", + }); + + Assert.Equal("file", options.Mode); + Assert.Equal("hard", options.LinkType); + Assert.Equal(@"C:\links", options.LinkLocation); + Assert.Equal("my link", options.LinkName); + Assert.Equal(@"D:\data.txt", options.Target); + } + + [Fact] + public void Parse_IgnoresUnknownAndIncompleteArguments() + { + var options = LaunchOptions.Parse(new[] { "--engage", "--name", "link", "--target" }); + + Assert.Equal("link", options.LinkName); + Assert.Null(options.Target); + Assert.Null(options.Mode); + } + + [Theory] + [InlineData("folder", true)] + [InlineData("FOLDER", true)] + [InlineData("file", false)] + [InlineData("disk", null)] + [InlineData(null, null)] + public void IsFolderMode_ReadsTheMode(string mode, bool? expected) + { + Assert.Equal(expected, new LaunchOptions { Mode = mode }.IsFolderMode); + } + + [Theory] + [InlineData("symbolic", "Symbolic")] + [InlineData("Hard", "Hard")] + [InlineData("junction", "Junction")] + [InlineData("shortcut", null)] + [InlineData(null, null)] + public void Kind_ReadsTheLinkType(string linkType, string expected) + { + Assert.Equal(expected, new LaunchOptions { LinkType = linkType }.Kind?.ToString()); + } + + [Fact] + public void CanCreateSymbolicLinks_IsTrue_WhenElevated() + { + Assert.True(Elevation.CanCreateSymbolicLinks(true, (_, _) => throw new InvalidOperationException("not probed"))); + } + + [Fact] + public void CanCreateSymbolicLinks_IsTrue_WhenTheProbeWorks() + { + Assert.True(Elevation.CanCreateSymbolicLinks(false, (_, _) => null)); + } + + [Fact] + public void CanCreateSymbolicLinks_IsFalse_WithoutThePrivilege() + { + Assert.False(Elevation.CanCreateSymbolicLinks(false, (_, _) => throw new IOException("A required privilege is not held by the client.", PrivilegeNotHeld))); + } + + [Fact] + public void CanCreateSymbolicLinks_IsTrue_WhenTheProbeFailsForOtherReasons() + { + // Let mklink try and report its own error + Assert.True(Elevation.CanCreateSymbolicLinks(false, (_, _) => throw new IOException("disk full", unchecked((int)0x80070070)))); + Assert.True(Elevation.CanCreateSymbolicLinks(false, (_, _) => throw new UnauthorizedAccessException())); + } + + [Fact] + public void CanCreateSymbolicLinks_ProbesForReal() + { + Assert.Equal(SymlinkSupport.Available, Elevation.CanCreateSymbolicLinks()); + } + } +} diff --git a/Symlinker.Tests/InputValidatorTests.cs b/Symlinker.Tests/InputValidatorTests.cs new file mode 100644 index 0000000..4b25eba --- /dev/null +++ b/Symlinker.Tests/InputValidatorTests.cs @@ -0,0 +1,141 @@ +namespace Symlinker.Tests +{ + using System; + using System.Linq; + using System.Windows.Media; + + using Res = Symlinker.Properties.Resources; + + public sealed class InputValidatorTests : IDisposable + { + private readonly TempDir temp = new(); + + public InputValidatorTests() + { + temp.Dir("links"); + temp.Dir("target-folder"); + temp.File("target.txt"); + temp.Dir(@"links\taken-folder"); + temp.File(@"links\taken-file"); + } + + public void Dispose() => temp.Dispose(); + + private string[] Validate(string name, string location, string target, bool isFolder = true) => + InputValidator.Validate(name, Resolve(location), Resolve(target), isFolder) + .Select(error => $"{error.Field}: {error.Message}") + .ToArray(); + + // Names starting with "@" are paths inside the temp folder + private string Resolve(string value) => value.StartsWith('@') ? temp.PathOf(value[1..]) : value; + + [Fact] + public void Validate_AcceptsAGoodFolderLink() + { + Assert.Empty(Validate(" name ", "@links", "@target-folder")); + } + + [Fact] + public void Validate_AcceptsAGoodFileLink() + { + Assert.Empty(Validate("name.txt", "@links", "@target.txt", isFolder: false)); + } + + [Fact] + public void Validate_ListsEveryProblemInScreenOrder() + { + Assert.Equal( + new[] + { + $"LinkName: {Res.ErrorLinkNameMissing}", + $"LinkLocation: {Res.ErrorLinkLocationMissing}", + $"Target: {Res.ErrorTargetFolderMissing}", + }, + Validate(" ", string.Empty, " ")); + } + + [Theory] + [InlineData("a|b", "LinkName", nameof(Res.ErrorLinkNameInvalid))] + [InlineData("a:b", "LinkName", nameof(Res.ErrorLinkNameInvalid))] + public void Validate_RejectsBadNames(string name, string field, string resource) + { + Assert.Equal(new[] { $"{field}: {Res.ResourceManager.GetString(resource)}" }, Validate(name, "@links", "@target-folder")); + } + + [Theory] + [InlineData("links\"", nameof(Res.InvalidQuoteInPath))] + [InlineData("@missing", nameof(Res.ErrorLinkLocationNotFound))] + public void Validate_RejectsBadLocations(string location, string resource) + { + Assert.Equal(new[] { $"LinkLocation: {Res.ResourceManager.GetString(resource)}" }, Validate("name", location, "@target-folder")); + } + + [Theory] + [InlineData(true, "", nameof(Res.ErrorTargetFolderMissing))] + [InlineData(false, "", nameof(Res.ErrorTargetFileMissing))] + [InlineData(true, "\"quoted\"", nameof(Res.InvalidQuoteInPath))] + [InlineData(true, "@target.txt", nameof(Res.ErrorTargetIsFile))] + [InlineData(false, "@target-folder", nameof(Res.ErrorTargetIsFolder))] + [InlineData(true, "@missing", nameof(Res.ErrorTargetFolderNotFound))] + [InlineData(false, "@missing.txt", nameof(Res.ErrorTargetFileNotFound))] + public void Validate_RejectsBadTargets(bool isFolder, string target, string resource) + { + Assert.Equal(new[] { $"Target: {Res.ResourceManager.GetString(resource)}" }, Validate("name", "@links", target, isFolder)); + } + + [Theory] + [InlineData("taken-folder", true)] + [InlineData("taken-file", false)] + public void Validate_AllowsAMissingTarget_WhenSomethingIsAtTheLinkPath(string name, bool isFolder) + { + // Link creation offers to move the existing item to the target + Assert.Empty(Validate(name, "@links", "@missing", isFolder)); + } + + [Fact] + public void Validate_ReportsAMissingTarget_WhenTheLinkPathCantBeChecked() + { + Assert.Contains($"Target: {Res.ErrorTargetFolderNotFound}", Validate(string.Empty, "@links", "@missing")); + Assert.Contains($"Target: {Res.ErrorTargetFolderNotFound}", Validate("taken-folder", string.Empty, "@missing")); + } + + [Fact] + public void TargetFitsMode_ChecksTheTargetMatchesTheMode() + { + Assert.False(InputValidator.TargetFitsMode(" ", folderMode: true)); + Assert.True(InputValidator.TargetFitsMode(temp.PathOf("target-folder"), folderMode: true)); + Assert.False(InputValidator.TargetFitsMode(temp.PathOf("target.txt"), folderMode: true)); + Assert.True(InputValidator.TargetFitsMode($" {temp.PathOf("target.txt")} ", folderMode: false)); + Assert.False(InputValidator.TargetFitsMode(temp.PathOf("target-folder"), folderMode: false)); + } + + [Fact] + public void ContrastRatio_FollowsWcag() + { + Assert.Equal(21, ColorContrast.ContrastRatio(Colors.Black, Colors.White), 3); + Assert.Equal(21, ColorContrast.ContrastRatio(Colors.White, Colors.Black), 3); + Assert.Equal(1, ColorContrast.ContrastRatio(Colors.Gray, Colors.Gray), 3); + + // Very dark channels use the linear part of the sRGB curve + Assert.Equal(1.061, ColorContrast.ContrastRatio(Color.FromRgb(10, 10, 10), Colors.Black), 3); + } + + [Fact] + public void Blend_MixesByAlpha() + { + Assert.Equal(Colors.Red, ColorContrast.Blend(Colors.Red, Colors.Blue)); + Assert.Equal(Colors.Blue, ColorContrast.Blend(Color.FromArgb(0, 255, 0, 0), Colors.Blue)); + Assert.Equal(Color.FromRgb(128, 128, 128), ColorContrast.Blend(Color.FromArgb(128, 255, 255, 255), Colors.Black)); + } + + [Fact] + public void TextOn_PicksTheMoreReadableColor() + { + Assert.Equal(Colors.White, ColorContrast.TextOn(Color.FromRgb(0, 90, 158), null)); + Assert.Equal(Colors.Black, ColorContrast.TextOn(Color.FromRgb(255, 200, 60), null)); + + // A faint dark accent over a white page looks light + Assert.Equal(Colors.Black, ColorContrast.TextOn(Color.FromArgb(40, 0, 90, 158), Colors.White)); + } + } +} diff --git a/Symlinker.Tests/LinkCommandTests.cs b/Symlinker.Tests/LinkCommandTests.cs new file mode 100644 index 0000000..83de0fd --- /dev/null +++ b/Symlinker.Tests/LinkCommandTests.cs @@ -0,0 +1,126 @@ +namespace Symlinker.Tests +{ + using System; + using System.IO; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + public sealed class LinkCommandTests : IDisposable + { + private readonly TempDir temp = new(); + + public void Dispose() => temp.Dispose(); + + private static LinkRequest Request(string type = "symbolic", string link = @"C:\links\a", string target = @"D:\target", bool directory = true) => + new() { Type = type, Link = link, Target = target, Directory = directory }; + + [Theory] + [InlineData("symbolic", true, "/c mklink /D \"C:\\links\\a\" \"D:\\target\"")] + [InlineData("junction", true, "/c mklink /D /J \"C:\\links\\a\" \"D:\\target\"")] + [InlineData("symbolic", false, "/c mklink \"C:\\links\\a\" \"D:\\target\"")] + [InlineData("hard", false, "/c mklink /H \"C:\\links\\a\" \"D:\\target\"")] + public void BuildArguments_MatchesTheLinkType(string type, bool directory, string expected) + { + Assert.Equal(expected, LinkCommand.BuildArguments(Request(type, directory: directory))); + } + + [Theory] + [InlineData("shortcut", @"C:\links\a", @"D:\target")] + [InlineData("Symbolic", @"C:\links\a", @"D:\target")] + [InlineData(null, @"C:\links\a", @"D:\target")] + [InlineData("symbolic", " ", @"D:\target")] + [InlineData("symbolic", @"C:\links\a", "")] + [InlineData("symbolic", "C:\\links\\a\" & del x", @"D:\target")] + [InlineData("symbolic", @"C:\links\a", "D:\\target\r\nrd /s C:\\")] + [InlineData("symbolic", @"C:\links\a", "D:\\target\n")] + [InlineData("symbolic", "C:\\links\\a\0", @"D:\target")] + public void BuildArguments_RefusesAnythingThatCouldBreakOutOfTheCommand(string type, string link, string target) + { + // The elevated helper runs whatever it is sent, so only exact, quote-safe requests pass + Assert.Null(LinkCommand.BuildArguments(Request(type, link, target))); + } + + [Fact] + public void BuildArguments_RefusesAMissingRequest() + { + Assert.Null(LinkCommand.BuildArguments(null)); + } + + [Fact] + 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)); + } + + [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)); + } + + [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) + { + // 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); + + Assert.Equal((success, message ?? Res.LinkSuccessfullyCreated), (result.Success, result.Message)); + } + + [Fact] + public async Task RunAsync_CreatesARealJunction() + { + var target = temp.Dir("target"); + temp.File(@"target\inside.txt"); + var link = temp.PathOf("link"); + + var result = await LinkCommand.RunAsync(Request("junction", link, target)); + + Assert.True(result.Success, result.Message); + Assert.True(LinkMover.IsLink(new DirectoryInfo(link))); + Assert.True(File.Exists(Path.Combine(link, "inside.txt"))); + } + + [Fact] + public async Task RunAsync_ReportsMklinkErrors() + { + var target = temp.Dir("target"); + var link = temp.Dir("taken"); + + var result = await LinkCommand.RunAsync(Request("junction", link, target)); + + Assert.False(result.Success); + Assert.NotEmpty(result.Message); + } + + [Theory] + [InlineData("Symbolic", "symbolic")] + [InlineData("Hard", "hard")] + [InlineData("Junction", "junction")] + public void LinkKinds_RoundTripNames(string kind, string name) + { + var linkKind = Enum.Parse(kind); + + Assert.Equal(name, LinkKinds.ToName(linkKind)); + Assert.Equal(linkKind, LinkKinds.Parse(name.ToUpperInvariant())); + } + + [Fact] + public void LinkKinds_Parse_ReturnsNull_ForUnknownNames() + { + Assert.Null(LinkKinds.Parse("shortcut")); + Assert.Null(LinkKinds.Parse(null)); + } + } +} diff --git a/Symlinker.Tests/LinkCreatorTests.cs b/Symlinker.Tests/LinkCreatorTests.cs new file mode 100644 index 0000000..f1808b2 --- /dev/null +++ b/Symlinker.Tests/LinkCreatorTests.cs @@ -0,0 +1,556 @@ +namespace Symlinker.Tests +{ + using System; + using System.Globalization; + using System.IO; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// + /// Runs the link workflow against the real file system, with fake dialogs and a fake link runner. + /// + public sealed class LinkCreatorTests : IDisposable + { + private readonly TempDir temp = new(); + private readonly FakeDialogs dialogs = new(); + private readonly FakeLinkRunner runner = new(); + private readonly LinkCreator creator; + + public LinkCreatorTests() + { + creator = new LinkCreator(dialogs, runner); + } + + public void Dispose() => temp.Dispose(); + + private string Links => temp.PathOf("links"); + + private static string Format(string format, params object[] args) => + string.Format(CultureInfo.CurrentUICulture, format, args); + + private Task Create(string linkName, string destination, bool isFolder = true, LinkKind kind = LinkKind.Symbolic, string linkLocation = null) => + creator.CreateAsync(new LinkInput(linkLocation ?? Links, linkName, destination, isFolder, kind)); + + private void AssertLinked(string type, string link, string target, bool directory) + { + var request = Assert.Single(runner.Calls); + Assert.Equal((type, link, target, directory), (request.Type, request.Link, request.Target, request.Directory)); + + // Administrator rights are settled for the same link before it is created + Assert.Equal(request, Assert.Single(runner.Prepared)); + } + + private void UseCopyMove(TimeSpan? progressInterval = null) + { + creator.IsSameVolume = (_, _) => false; + creator.ProgressInterval = progressInterval ?? TimeSpan.Zero; + } + + // ---- Validation ---- + + [Theory] + [InlineData("", "name", "target")] + [InlineData("links", " ", "target")] + [InlineData("links", "name", "")] + public async Task Create_AsksToFillBlanks(string location, string name, string destination) + { + await creator.CreateAsync(new LinkInput(location, name, destination, true, LinkKind.Symbolic)); + + Assert.Equal((Res.MessageBoxErrorTitle, Res.FillBlanks), dialogs.Last); + Assert.Empty(runner.Calls); + } + + [Theory] + [InlineData("links\"", "name", "target")] + [InlineData("links", "na\"me", "target")] + [InlineData("links", "name", "\"target\"")] + public async Task Create_RejectsQuotes(string location, string name, string destination) + { + await creator.CreateAsync(new LinkInput(location, name, destination, true, LinkKind.Symbolic)); + + Assert.Equal((Res.MessageBoxErrorTitle, Res.InvalidQuoteInPath), dialogs.Last); + Assert.Empty(runner.Calls); + } + + [Theory] + [InlineData(true, "missing-location", "target-folder")] + [InlineData(false, "missing-location", "target.txt")] + [InlineData(true, "links", "missing")] + [InlineData(false, "links", "missing.txt")] + [InlineData(true, "links", "target.txt")] + [InlineData(false, "links", "target-folder")] + [InlineData(false, "links", "relative")] + public async Task Create_ReportsMissingOrMismatchedPaths(bool isFolder, string location, string destination) + { + temp.Dir("links"); + temp.Dir("target-folder"); + temp.File("target.txt"); + var fullDestination = destination == "relative" ? destination : temp.PathOf(destination); + + await Create("name", fullDestination, isFolder, linkLocation: temp.PathOf(location)); + + Assert.Equal((Res.MessageBoxErrorTitle, Res.FilesOrFolderNotExists), dialogs.Last); + Assert.Empty(runner.Calls); + } + + // ---- Plain link creation ---- + + [Fact] + public async Task Create_FolderLink_RunsMklinkWithTrimmedPaths() + { + temp.Dir("links"); + var target = temp.Dir("target"); + + await creator.CreateAsync(new LinkInput($" {Links} ", " name ", $" {target} ", true, LinkKind.Junction)); + + AssertLinked("junction", $@"{Links}\name", target, directory: true); + Assert.Equal((Res.MessageBoxSuccessTitle, "created"), dialogs.Last); + Assert.Empty(dialogs.Questions); + } + + [Fact] + public async Task Create_FileLink_RunsMklink() + { + temp.Dir("links"); + var target = temp.File("target.txt"); + + await Create("name.txt", target, isFolder: false, kind: LinkKind.Hard); + + AssertLinked("hard", $@"{Links}\name.txt", target, directory: false); + } + + [Fact] + public async Task Create_ShowsMklinkErrors() + { + temp.Dir("links"); + var target = temp.Dir("target"); + runner.Handler = _ => LinkResult.Failed("access denied"); + + await Create("name", target); + + Assert.Equal((Res.MessageBoxErrorTitle, "access denied"), dialogs.Last); + } + + [Fact] + public async Task Create_StopsQuietly_WhenAdminRightsAreDeclined() + { + temp.Dir("links"); + var target = temp.Dir("target"); + runner.PrepareResult = false; + + await Create("name", target); + + Assert.Equal("symbolic", Assert.Single(runner.Prepared).Type); + Assert.Empty(runner.Calls); + Assert.Empty(dialogs.Messages); + } + + // ---- Replacing an existing entry ---- + + [Fact] + public async Task Create_ReplacesAnExistingFolder_WhenConfirmed() + { + temp.File(@"links\Name\old.txt"); + var target = temp.Dir("target"); + temp.File(@"target\inside.txt"); + + await Create("name", target); + + var question = Assert.Single(dialogs.Questions); + Assert.Equal((Res.DialogFolderExistsDialog, Res.DialogFolderExists), (question.Title, question.Message)); + Assert.False(Directory.Exists(temp.PathOf("links", "Name"))); + Assert.Single(runner.Calls); + } + + [Fact] + public async Task Create_KeepsAnExistingFolder_WhenDeclined() + { + temp.File(@"links\name\old.txt"); + var target = temp.Dir("target"); + temp.File(@"target\inside.txt"); + dialogs.Answer = false; + + await Create("name", target); + + Assert.Equal((Res.LinkCreationAbortedWarning, Res.LinkCreationAborted), dialogs.Last); + Assert.True(File.Exists(temp.PathOf("links", "name", "old.txt"))); + Assert.Empty(runner.Calls); + } + + [Fact] + public async Task Create_AsksForAdminRights_BeforeReplacing() + { + var existing = temp.PathOf("links", "name"); + temp.File(@"links\name\old.txt"); + var target = temp.Dir("target"); + temp.File(@"target\inside.txt"); + var existedWhenAsked = false; + runner.OnPrepare = () => existedWhenAsked = Directory.Exists(existing); + runner.PrepareResult = false; + + await Create("name", target); + + Assert.Single(dialogs.Questions); + Assert.True(existedWhenAsked); + Assert.True(Directory.Exists(existing)); + Assert.Empty(runner.Calls); + Assert.Empty(dialogs.Messages); + } + + [Fact] + public async Task Create_ReplacesAnExistingFile_WhenConfirmed() + { + temp.File(@"links\name.txt"); + var target = temp.File("target.txt"); + + await Create("name.txt", target, isFolder: false); + + var question = Assert.Single(dialogs.Questions); + Assert.Equal((Res.DialogDeleteFileWarning, Res.DialogDeleteFile), (question.Title, question.Message)); + Assert.False(File.Exists(temp.PathOf("links", "name.txt"))); + Assert.Single(runner.Calls); + } + + [Fact] + public async Task Create_KeepsAnExistingFile_WhenDeclined() + { + temp.File(@"links\name.txt"); + var target = temp.File("target.txt"); + dialogs.Answer = false; + + await Create("name.txt", target, isFolder: false); + + Assert.Equal((Res.LinkCreationAbortedWarning, Res.LinkCreationAborted), dialogs.Last); + Assert.True(File.Exists(temp.PathOf("links", "name.txt"))); + Assert.Empty(runner.Calls); + } + + [Fact] + public async Task Create_TreatsAnExistingLinkAsReplaceable_NotMovable() + { + temp.Dir("links"); + temp.Junction(temp.PathOf("links", "name"), temp.Dir("old-target")); + var target = temp.Dir("empty-target"); + dialogs.Answer = false; + + await Create("name", target); + + Assert.Equal(Res.DialogFolderExistsDialog, Assert.Single(dialogs.Questions).Title); + } + + [Fact] + public async Task Create_ReportsUnexpectedErrors() + { + var locked = temp.File(@"links\name\locked.txt"); + var target = temp.Dir("target"); + temp.File(@"target\inside.txt"); + + using (new FileStream(locked, FileMode.Open, FileAccess.Read, FileShare.None)) + await Create("name", target); + + Assert.Equal(Res.MessageBoxErrorTitle, dialogs.Last.Title); + Assert.StartsWith(Res.MessageBoxExceptionOcurred + "\n", dialogs.Last.Message); + Assert.Empty(runner.Calls); + } + + // ---- Offering to move an existing entry ---- + + [Fact] + public async Task Move_DoesNothing_WhenDeclined() + { + temp.File(@"links\name\data.txt"); + var target = temp.PathOf("target"); + dialogs.Answer = false; + + await Create("name", target); + + var question = Assert.Single(dialogs.Questions); + Assert.Equal(Res.DialogMoveTitle, question.Title); + Assert.Equal(Format(Res.DialogMoveFolder, "name", target), question.Message); + Assert.Equal((Res.ButtonMoveAndLink, Res.ButtonCancel), (question.Yes, question.No)); + Assert.Equal((Res.LinkCreationAbortedWarning, Res.LinkCreationAborted), dialogs.Last); + Assert.True(File.Exists(temp.PathOf("links", "name", "data.txt"))); + Assert.Empty(runner.Calls); + } + + [Fact] + public async Task Move_AsksForAdminRights_BeforeMovingAnything() + { + temp.File(@"links\name\data.txt"); + var target = temp.PathOf("target"); + var movingWhenAsked = true; + runner.OnPrepare = () => movingWhenAsked = creator.IsMoving; + runner.PrepareResult = false; + + await Create("name", target); + + Assert.Equal(("symbolic", target), (Assert.Single(runner.Prepared).Type, runner.Prepared[0].Target)); + Assert.False(movingWhenAsked); + Assert.True(File.Exists(temp.PathOf("links", "name", "data.txt"))); + Assert.False(Directory.Exists(target)); + Assert.Empty(runner.Calls); + Assert.Empty(dialogs.Messages); + } + + [Fact] + public async Task Move_Folder_OnTheSameDrive_RenamesAndLinks() + { + temp.File(@"links\name\data.txt", "data"); + var target = temp.PathOf("new", "parent", "target"); + var movingDuringLink = false; + runner.Handler = _ => + { + movingDuringLink = creator.IsMoving; + return FakeLinkRunner.Created; + }; + + await Create("name", target); + + AssertLinked("symbolic", $@"{Links}\name", target, directory: true); + Assert.Equal("data", File.ReadAllText(Path.Combine(target, "data.txt"))); + Assert.False(Directory.Exists(temp.PathOf("links", "name"))); + Assert.Equal((Res.MessageBoxSuccessTitle, Format(Res.MoveSucceeded, "name", target)), dialogs.Last); + Assert.True(movingDuringLink); + Assert.False(creator.IsMoving); + Assert.Null(dialogs.Progress.Shown); + } + + [Fact] + public async Task Move_File_IntoAnEmptyFolderTarget_IsRefused() + { + // An empty folder is only a free target for folders + temp.File(@"links\name.txt"); + var target = temp.Dir("empty"); + + await Create("name.txt", target, isFolder: false); + + Assert.Empty(dialogs.Questions); + Assert.Equal((Res.MessageBoxErrorTitle, Res.FilesOrFolderNotExists), dialogs.Last); + } + + [Fact] + public async Task Move_File_OnTheSameDrive_RenamesAndLinks() + { + temp.File(@"links\name.txt", "data"); + var target = temp.PathOf("moved.txt"); + + await Create("name.txt", target, isFolder: false); + + Assert.Equal(Format(Res.DialogMoveFile, "name.txt", target), Assert.Single(dialogs.Questions).Message); + Assert.Equal("data", File.ReadAllText(target)); + Assert.False(File.Exists(temp.PathOf("links", "name.txt"))); + Assert.Equal(Res.MessageBoxSuccessTitle, dialogs.Last.Title); + } + + [Fact] + public async Task Move_IntoAnEmptyFolder_ReplacesIt() + { + temp.File(@"links\name\data.txt"); + var target = temp.Dir("empty-target"); + + await Create("name", target); + + Assert.True(File.Exists(Path.Combine(target, "data.txt"))); + Assert.Equal(Res.MessageBoxSuccessTitle, dialogs.Last.Title); + } + + [Fact] + public async Task Move_IsRefused_WhenTheTargetIsInsideTheSource() + { + temp.File(@"links\name\data.txt"); + + await Create("name", temp.PathOf("links", "name", "inner")); + + Assert.Equal((Res.MessageBoxErrorTitle, Res.MoveTargetInsideSource), dialogs.Last); + Assert.True(File.Exists(temp.PathOf("links", "name", "data.txt"))); + Assert.Empty(runner.Calls); + } + + [Fact] + public async Task Move_Folder_ToAnotherDrive_CopiesWithProgressThenRemovesTheOriginal() + { + temp.File(@"links\name\a.txt", "aaa"); + temp.File(@"links\name\nested\b.txt", "bb"); + var target = temp.PathOf("target"); + UseCopyMove(); + + await Create("name", target); + + Assert.Equal("aaa", File.ReadAllText(Path.Combine(target, "a.txt"))); + Assert.Equal("bb", File.ReadAllText(Path.Combine(target, "nested", "b.txt"))); + Assert.False(Directory.Exists(temp.PathOf("links", "name"))); + Assert.False(Directory.Exists(temp.PathOf("links", "name.symlinker-move"))); + Assert.Equal((Res.MessageBoxSuccessTitle, Format(Res.MoveSucceeded, "name", target)), dialogs.Last); + + var progress = dialogs.Progress; + Assert.Equal((Res.ProgressMoveTitle, Res.ProgressMovePreparing, Res.ButtonCancel), progress.Shown); + Assert.True(progress.Indeterminate); + Assert.True(progress.Closed); + Assert.Contains(0, progress.Values); + Assert.Contains(Format(Res.ProgressMoveMessage, UiHelpers.FormatBytes(0), UiHelpers.FormatBytes(5)), progress.ShownMessages); + } + + [Fact] + public async Task Move_File_ToAnotherDrive_CopiesIt() + { + temp.File(@"links\name.txt", "data"); + var target = temp.PathOf("moved.txt"); + + // Never reports progress mid-copy + UseCopyMove(TimeSpan.MaxValue); + + await Create("name.txt", target, isFolder: false); + + Assert.Equal("data", File.ReadAllText(target)); + Assert.False(File.Exists(temp.PathOf("links", "name.txt"))); + Assert.Equal(Res.MessageBoxSuccessTitle, dialogs.Last.Title); + Assert.Equal(new[] { 0d }, dialogs.Progress.Values); + } + + [Fact] + public async Task Move_EmptyFolder_ToAnotherDrive_ShowsFullProgress() + { + temp.Dir(@"links\name"); + var target = temp.PathOf("target"); + UseCopyMove(); + + await Create("name", target); + + Assert.True(Directory.Exists(target)); + Assert.Equal(new[] { 1d }, dialogs.Progress.Values); + } + + [Fact] + public async Task Move_Canceled_PutsEverythingBack() + { + temp.File(@"links\name\data.txt"); + var target = temp.Dir("empty-target"); + UseCopyMove(); + dialogs.Progress.BeforeCopy = dialogs.Progress.Cancel; + + await Create("name", target); + + Assert.Equal((Res.LinkCreationAbortedWarning, Res.MoveCanceled), dialogs.Last); + Assert.True(File.Exists(temp.PathOf("links", "name", "data.txt"))); + Assert.True(Directory.Exists(target)); + Assert.Empty(Directory.EnumerateFileSystemEntries(target)); + Assert.Empty(runner.Calls); + } + + [Fact] + public async Task Move_CopyFailure_PutsEverythingBack() + { + temp.File(@"links\name\data.txt"); + var target = temp.PathOf("target"); + UseCopyMove(); + + // A file appears where the target folder should be created + dialogs.Progress.BeforeCopy = () => File.WriteAllText(target, "in the way"); + + await Create("name", target); + + Assert.Equal(Res.MessageBoxErrorTitle, dialogs.Last.Title); + Assert.StartsWith(Format(Res.MoveFailed, string.Empty), dialogs.Last.Message); + Assert.True(File.Exists(temp.PathOf("links", "name", "data.txt"))); + Assert.False(File.Exists(target)); + Assert.False(Directory.Exists(target)); + Assert.Empty(runner.Calls); + } + + [Fact] + public async Task Move_LinkFailure_OnTheSameDrive_PutsEverythingBack() + { + temp.File(@"links\name\data.txt"); + var target = temp.Dir("empty-target"); + runner.Handler = _ => LinkResult.Failed("no rights"); + + await Create("name", target); + + Assert.Equal((Res.MessageBoxErrorTitle, Format(Res.MoveFailed, "no rights")), dialogs.Last); + Assert.True(File.Exists(temp.PathOf("links", "name", "data.txt"))); + Assert.True(Directory.Exists(target)); + Assert.Empty(Directory.EnumerateFileSystemEntries(target)); + } + + [Fact] + public async Task Move_LinkFailure_ToAnotherDrive_RemovesTheCopy() + { + temp.File(@"links\name\data.txt"); + var target = temp.PathOf("target"); + UseCopyMove(); + runner.Handler = _ => LinkResult.Failed("no rights"); + + await Create("name", target); + + Assert.Equal((Res.MessageBoxErrorTitle, Format(Res.MoveFailed, "no rights")), dialogs.Last); + Assert.True(File.Exists(temp.PathOf("links", "name", "data.txt"))); + Assert.False(Directory.Exists(target)); + Assert.False(Directory.Exists(temp.PathOf("links", "name.symlinker-move"))); + } + + [Fact] + public async Task Move_RollbackFailure_SaysWhereTheFilesAre() + { + temp.File(@"links\name\data.txt"); + var target = temp.PathOf("target"); + + // Something takes the original's place before it can be put back + runner.Handler = _ => + { + File.WriteAllText(temp.PathOf("links", "name"), "in the way"); + return LinkResult.Failed("no rights"); + }; + + await Create("name", target); + + Assert.Equal((Res.MessageBoxErrorTitle, Format(Res.MoveRollbackFailed, target)), dialogs.Last); + Assert.True(File.Exists(Path.Combine(target, "data.txt"))); + } + + [Fact] + public async Task Move_CleanupFailure_StillReportsSuccess() + { + temp.File(@"links\name\data.txt"); + var target = temp.PathOf("target"); + var staging = temp.PathOf("links", "name.symlinker-move"); + UseCopyMove(); + FileStream lockedFile = null; + + // Something holds a file open in the old copy, so it can't be removed + runner.Handler = _ => + { + lockedFile = new FileStream(Path.Combine(staging, "data.txt"), FileMode.Open, FileAccess.Read, FileShare.None); + return FakeLinkRunner.Created; + }; + + try + { + await Create("name", target); + } + finally + { + lockedFile?.Dispose(); + } + + Assert.Equal((Res.MessageBoxSuccessTitle, Format(Res.MoveCleanupFailed, staging)), dialogs.Last); + Assert.True(File.Exists(Path.Combine(target, "data.txt"))); + } + + [Fact] + public async Task Move_ThatFailsToStart_LeavesTheOriginalInPlace() + { + var original = temp.File(@"links\name.txt", "data"); + var target = temp.PathOf("moved.txt"); + + using (new FileStream(original, FileMode.Open, FileAccess.Read, FileShare.None)) + await Create("name.txt", target, isFolder: false); + + Assert.Equal(Res.MessageBoxErrorTitle, dialogs.Last.Title); + Assert.StartsWith(Format(Res.MoveFailed, string.Empty), dialogs.Last.Message); + Assert.Equal("data", File.ReadAllText(original)); + Assert.False(File.Exists(target)); + Assert.Empty(runner.Calls); + } + } +} diff --git a/Symlinker.Tests/LinkMoverTests.cs b/Symlinker.Tests/LinkMoverTests.cs new file mode 100644 index 0000000..b2cc8a8 --- /dev/null +++ b/Symlinker.Tests/LinkMoverTests.cs @@ -0,0 +1,260 @@ +namespace Symlinker.Tests +{ + using System; + using System.IO; + using System.Threading; + + /// + /// Runs against the real file system. Folder links are junctions, which need no special rights; + /// tests with symbolic links need Developer Mode or an elevated prompt and are skipped without them. + /// + public sealed class LinkMoverTests : IDisposable + { + private static readonly DateTime OldTime = new(2020, 1, 2, 3, 4, 5, DateTimeKind.Utc); + + private readonly TempDir temp = new(); + + public void Dispose() => temp.Dispose(); + + [Fact] + public void IsLink_IsFalse_ForRegularAndMissingEntries() + { + Assert.False(LinkMover.IsLink(new DirectoryInfo(temp.Dir("folder")))); + Assert.False(LinkMover.IsLink(new FileInfo(temp.File("file.txt")))); + Assert.False(LinkMover.IsLink(new DirectoryInfo(temp.PathOf("missing")))); + Assert.False(LinkMover.IsLink(new FileInfo(temp.PathOf("missing", "file.txt")))); + } + + [Fact] + public void IsLink_IsTrue_ForJunctions() + { + Assert.True(LinkMover.IsLink(temp.Junction(temp.PathOf("folder-link"), temp.Dir("folder")))); + } + + [Fact] + public void IsLink_IsTrue_ForSymbolicLinks() + { + SymlinkSupport.Require(); + var folderLink = Directory.CreateSymbolicLink(temp.PathOf("folder-link"), temp.Dir("folder")); + var fileLink = File.CreateSymbolicLink(temp.PathOf("file-link"), temp.File("file.txt")); + + Assert.True(LinkMover.IsLink(folderLink)); + Assert.True(LinkMover.IsLink(fileLink)); + } + + [Theory] + [InlineData(@"C:\data", @"C:\data", true)] + [InlineData(@"C:\Data\", @"c:\data", true)] + [InlineData(@"C:\data\inner\file", @"C:\data", true)] + [InlineData(@"C:\database", @"C:\data", false)] + [InlineData(@"C:\data", @"C:\data\inner", false)] + [InlineData(@"D:\data", @"C:\data", false)] + public void IsSameOrInside_ComparesWholePathParts(string path, string parent, bool expected) + { + Assert.Equal(expected, LinkMover.IsSameOrInside(path, parent)); + } + + [Theory] + [InlineData(@"C:\a", @"c:\b\c", true)] + [InlineData(@"C:\a", @"D:\a", false)] + public void IsSameVolume_ComparesDrives(string first, string second, bool expected) + { + Assert.Equal(expected, LinkMover.IsSameVolume(first, second)); + } + + [Fact] + public void GetUnusedPath_NumbersPathsThatAreTaken() + { + var path = temp.PathOf("item"); + Assert.Equal(path, LinkMover.GetUnusedPath(path)); + + temp.File("item"); + Assert.Equal(path + "2", LinkMover.GetUnusedPath(path)); + + temp.Dir("item2"); + Assert.Equal(path + "3", LinkMover.GetUnusedPath(path)); + } + + [Fact] + public void Rename_MovesFilesAndFolders() + { + temp.File(@"folder\inside.txt"); + temp.File("file.txt"); + + LinkMover.Rename(temp.PathOf("folder"), temp.PathOf("folder-moved")); + LinkMover.Rename(temp.PathOf("file.txt"), temp.PathOf("file-moved.txt")); + + Assert.True(File.Exists(temp.PathOf("folder-moved", "inside.txt"))); + Assert.True(File.Exists(temp.PathOf("file-moved.txt"))); + Assert.False(Directory.Exists(temp.PathOf("folder"))); + Assert.False(File.Exists(temp.PathOf("file.txt"))); + } + + [Fact] + public void GetTotalBytes_CountsFilesButNotNestedLinks() + { + var file = temp.File(@"source\a.txt", "12345"); + var hidden = temp.File(@"source\nested\hidden.txt", "123"); + File.SetAttributes(hidden, FileAttributes.Hidden); + temp.File(@"elsewhere\big.txt", new string('x', 1000)); + temp.Junction(temp.PathOf("source", "link"), temp.PathOf("elsewhere")); + + Assert.Equal(5, LinkMover.GetTotalBytes(new FileInfo(file))); + Assert.Equal(8, LinkMover.GetTotalBytes(new DirectoryInfo(temp.PathOf("source")))); + } + + [Fact] + public void Copy_File_KeepsContentTimesAndAttributes() + { + var source = temp.File("source.txt", "hello"); + File.SetCreationTimeUtc(source, OldTime); + File.SetLastWriteTimeUtc(source, OldTime); + File.SetAttributes(source, FileAttributes.ReadOnly | FileAttributes.Hidden); + long copied = 0; + + LinkMover.Copy(new FileInfo(source), temp.PathOf("copy.txt"), bytes => copied += bytes, CancellationToken.None); + + var copy = new FileInfo(temp.PathOf("copy.txt")); + Assert.Equal("hello", File.ReadAllText(copy.FullName)); + Assert.Equal(5, copied); + Assert.Equal(OldTime, copy.CreationTimeUtc); + Assert.Equal(OldTime, copy.LastWriteTimeUtc); + Assert.Equal(FileAttributes.ReadOnly | FileAttributes.Hidden, copy.Attributes); + } + + [Fact] + public void Copy_File_WithoutAttributes_IsNormal() + { + var source = temp.File("source.txt"); + File.SetAttributes(source, FileAttributes.Normal); + + LinkMover.Copy(new FileInfo(source), temp.PathOf("copy.txt"), _ => { }, CancellationToken.None); + + Assert.Equal(FileAttributes.Normal, File.GetAttributes(temp.PathOf("copy.txt"))); + } + + [Fact] + public void Copy_Folder_CopiesEverything() + { + temp.File(@"source\a.txt", "aaa"); + var hidden = temp.File(@"source\nested\hidden.txt", "bb"); + File.SetAttributes(hidden, FileAttributes.Hidden); + temp.Dir(@"source\empty"); + + var source = new DirectoryInfo(temp.PathOf("source")); + source.Attributes |= FileAttributes.ReadOnly; + source.CreationTimeUtc = OldTime; + source.LastWriteTimeUtc = OldTime; + long copied = 0; + + LinkMover.Copy(source, temp.PathOf("copy"), bytes => copied += bytes, CancellationToken.None); + + var copy = new DirectoryInfo(temp.PathOf("copy")); + Assert.Equal("aaa", File.ReadAllText(temp.PathOf("copy", "a.txt"))); + Assert.Equal("bb", File.ReadAllText(temp.PathOf("copy", "nested", "hidden.txt"))); + Assert.True(File.GetAttributes(temp.PathOf("copy", "nested", "hidden.txt")).HasFlag(FileAttributes.Hidden)); + Assert.True(Directory.Exists(temp.PathOf("copy", "empty"))); + Assert.Equal(5, copied); + Assert.Equal(OldTime, copy.CreationTimeUtc); + Assert.Equal(OldTime, copy.LastWriteTimeUtc); + Assert.True(copy.Attributes.HasFlag(FileAttributes.ReadOnly)); + } + + [Fact] + public void Copy_Folder_RecreatesNestedLinks() + { + SymlinkSupport.Require(); + var linkedFolder = temp.Dir("linked-folder"); + var linkedFile = temp.File("linked.txt"); + temp.Dir("source"); + temp.Junction(temp.PathOf("source", "junction"), linkedFolder); + Directory.CreateSymbolicLink(temp.PathOf("source", "folder-link"), linkedFolder); + File.CreateSymbolicLink(temp.PathOf("source", "file-link.txt"), linkedFile); + + LinkMover.Copy(new DirectoryInfo(temp.PathOf("source")), temp.PathOf("copy"), _ => { }, CancellationToken.None); + + Assert.Equal(linkedFolder, new DirectoryInfo(temp.PathOf("copy", "junction")).LinkTarget); + Assert.Equal(linkedFolder, new DirectoryInfo(temp.PathOf("copy", "folder-link")).LinkTarget); + Assert.Equal(linkedFile, new FileInfo(temp.PathOf("copy", "file-link.txt")).LinkTarget); + } + + [Fact] + public void Copy_StopsWhenCanceled() + { + var file = temp.File(@"source\a.txt"); + using var canceled = new CancellationTokenSource(); + canceled.Cancel(); + + Assert.Throws( + () => LinkMover.Copy(new FileInfo(file), temp.PathOf("file-copy"), _ => { }, canceled.Token)); + Assert.Throws( + () => LinkMover.Copy(new DirectoryInfo(temp.PathOf("source")), temp.PathOf("folder-copy"), _ => { }, canceled.Token)); + } + + [Fact] + public void Delete_IgnoresMissingPaths() + { + LinkMover.Delete(temp.PathOf("missing")); + } + + [Fact] + public void Delete_RemovesReadOnlyFiles() + { + var file = temp.File("file.txt"); + File.SetAttributes(file, FileAttributes.ReadOnly); + + LinkMover.Delete(file); + + Assert.False(File.Exists(file)); + } + + [Fact] + public void Delete_OnALink_KeepsWhatItPointsTo() + { + var target = temp.Dir("target"); + temp.File(@"target\keep.txt"); + var link = temp.PathOf("link"); + temp.Junction(link, target); + + LinkMover.Delete(link); + + Assert.False(Directory.Exists(link)); + Assert.True(File.Exists(Path.Combine(target, "keep.txt"))); + } + + [Fact] + public void Delete_RemovesReadOnlyContentButNotLinkedFolders() + { + var linkedFolder = temp.Dir("linked-folder"); + var kept = temp.File(@"linked-folder\keep.txt"); + + var readOnly = temp.File(@"folder\nested\read-only.txt"); + File.SetAttributes(readOnly, FileAttributes.ReadOnly); + temp.File(@"folder\plain.txt"); + var readOnlyFolder = new DirectoryInfo(temp.Dir(@"folder\read-only-folder")); + readOnlyFolder.Attributes |= FileAttributes.ReadOnly; + temp.Junction(temp.PathOf("folder", "folder-link"), linkedFolder); + var folder = new DirectoryInfo(temp.PathOf("folder")); + folder.Attributes |= FileAttributes.ReadOnly; + + LinkMover.Delete(folder.FullName); + + Assert.False(Directory.Exists(folder.FullName)); + Assert.True(File.Exists(kept)); + } + + [Fact] + public void Delete_KeepsFilesBehindNestedFileLinks() + { + SymlinkSupport.Require(); + var linkedFile = temp.File("linked.txt"); + temp.Dir("folder"); + File.CreateSymbolicLink(temp.PathOf("folder", "file-link.txt"), linkedFile); + + LinkMover.Delete(temp.PathOf("folder")); + + Assert.False(Directory.Exists(temp.PathOf("folder"))); + Assert.True(File.Exists(linkedFile)); + } + } +} diff --git a/Symlinker.Tests/LinkRunnerTests.cs b/Symlinker.Tests/LinkRunnerTests.cs new file mode 100644 index 0000000..e111a60 --- /dev/null +++ b/Symlinker.Tests/LinkRunnerTests.cs @@ -0,0 +1,160 @@ +namespace Symlinker.Tests +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + public sealed class LinkRunnerTests + { + private readonly FakeDialogs dialogs = new(); + private readonly List started = new(); + private readonly List unelevated = new(); + + private bool symlinksNeedAdmin = true; + private int helperChanges; + + // What the next start returns: a running helper by default, null for a declined prompt + private Func nextHelper = () => new FakeLinkHelper(); + + private LinkRunner CreateRunner() => new( + dialogs, + () => symlinksNeedAdmin, + () => + { + var helper = nextHelper(); + if (helper != null) + started.Add(helper); + return Task.FromResult(helper); + }, + request => + { + unelevated.Add(request); + return Task.FromResult(new LinkResult { Success = true, Message = "unelevated" }); + }, + () => helperChanges++); + + private static LinkRequest Request(string type) => new() { Type = type, Link = @"C:\links\a", Target = @"D:\target", Directory = true }; + + [Theory] + [InlineData("junction", true)] + [InlineData("hard", true)] + [InlineData("symbolic", false)] + public async Task Prepare_DoesNotAsk_WhenTheLinkNeedsNoAdminRights(string type, bool needAdmin) + { + symlinksNeedAdmin = needAdmin; + using var runner = CreateRunner(); + + Assert.True(await runner.PrepareAsync(Request(type))); + Assert.Empty(started); + Assert.False(runner.HelperRunning); + Assert.Equal(0, helperChanges); + } + + [Fact] + public async Task Prepare_StartsTheHelperOnce_ForSymbolicLinksThatNeedAdmin() + { + using var runner = CreateRunner(); + + Assert.True(await runner.PrepareAsync(Request("symbolic"))); + Assert.True(await runner.PrepareAsync(Request("symbolic"))); + + Assert.Single(started); + Assert.True(runner.HelperRunning); + Assert.Equal(1, helperChanges); + } + + [Fact] + public async Task Prepare_ReplacesAHelperThatStopped() + { + using var runner = CreateRunner(); + await runner.PrepareAsync(Request("symbolic")); + started[0].IsAlive = false; + + Assert.False(runner.HelperRunning); + Assert.True(await runner.PrepareAsync(Request("symbolic"))); + + Assert.Equal(2, started.Count); + Assert.True(started[0].Disposed); + Assert.True(runner.HelperRunning); + } + + [Fact] + public async Task Prepare_StopsQuietly_WhenThePromptIsDeclined() + { + nextHelper = () => null; + using var runner = CreateRunner(); + + Assert.False(await runner.PrepareAsync(Request("symbolic"))); + + Assert.False(runner.HelperRunning); + Assert.Empty(dialogs.Messages); + } + + [Fact] + public async Task Prepare_ShowsAnError_WhenTheHelperCantStart() + { + nextHelper = () => throw new InvalidOperationException("helper broke"); + using var runner = CreateRunner(); + + Assert.False(await runner.PrepareAsync(Request("symbolic"))); + + Assert.Equal((Res.MessageBoxErrorTitle, Res.MessageBoxExceptionOcurred + "\nhelper broke"), dialogs.Last); + Assert.Equal(0, helperChanges); + } + + [Fact] + public async Task Run_SendsSymbolicLinksThatNeedAdmin_ToTheHelper() + { + using var runner = CreateRunner(); + await runner.PrepareAsync(Request("symbolic")); + + var symbolic = await runner.RunAsync(Request("symbolic")); + var junction = await runner.RunAsync(Request("junction")); + + Assert.Equal("elevated", symbolic.Message); + Assert.Equal("unelevated", junction.Message); + Assert.Single(started[0].Calls); + Assert.Equal("junction", Assert.Single(unelevated).Type); + } + + [Fact] + public async Task Run_StaysUnelevated_WithoutAHelper_OrOnceAdminIsNoLongerNeeded() + { + using var runner = CreateRunner(); + await runner.RunAsync(Request("symbolic")); + + await runner.PrepareAsync(Request("symbolic")); + symlinksNeedAdmin = false; + await runner.RunAsync(Request("symbolic")); + + Assert.Equal(2, unelevated.Count); + Assert.Empty(started[0].Calls); + } + + [Fact] + public async Task Run_ReportsErrors_AsAFailedLink() + { + var runner = new LinkRunner(dialogs, () => false, () => Task.FromResult(null), _ => throw new IOException("pipe broke"), () => { }); + + var result = await runner.RunAsync(Request("junction")); + + Assert.Equal((false, Res.MessageBoxExceptionOcurred + "\npipe broke"), (result.Success, result.Message)); + } + + [Fact] + public async Task Dispose_ClosesTheHelper() + { + var runner = CreateRunner(); + runner.Dispose(); + + await runner.PrepareAsync(Request("symbolic")); + runner.Dispose(); + + Assert.True(started[0].Disposed); + Assert.False(runner.HelperRunning); + } + } +} diff --git a/Symlinker.Tests/Symlinker.Tests.csproj b/Symlinker.Tests/Symlinker.Tests.csproj new file mode 100644 index 0000000..b46a2b8 --- /dev/null +++ b/Symlinker.Tests/Symlinker.Tests.csproj @@ -0,0 +1,31 @@ + + + net10.0-windows + Exe + true + false + true + Symlinker.Tests + + + + + $(TestingPlatformCommandLineArguments) --coverlet --coverlet-include "[Symlinker]*" --coverlet-exclude-by-attribute GeneratedCodeAttribute --coverlet-output-format cobertura --coverlet-threshold 100 --coverlet-threshold-type line --coverlet-threshold-type branch --coverlet-threshold-type method + + + + + + + + + + + + + + + diff --git a/Symlinker.Tests/TestSupport.cs b/Symlinker.Tests/TestSupport.cs new file mode 100644 index 0000000..df36bbb --- /dev/null +++ b/Symlinker.Tests/TestSupport.cs @@ -0,0 +1,229 @@ +namespace Symlinker.Tests +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + using System.Diagnostics; + using System.IO; + using System.Threading; + using System.Threading.Tasks; + + /// A fresh folder under %TEMP%, removed with everything in it when the test ends. + internal sealed class TempDir : IDisposable + { + public TempDir() + { + Root = Path.Combine(Path.GetTempPath(), "Symlinker.Tests", Guid.NewGuid().ToString("N")); + Directory.CreateDirectory(Root); + } + + public string Root { get; } + + public string PathOf(params string[] parts) => Path.Combine(Root, Path.Combine(parts)); + + public string Dir(params string[] parts) => Directory.CreateDirectory(PathOf(parts)).FullName; + + public string File(string relativePath, string content = "content") + { + var path = PathOf(relativePath); + Directory.CreateDirectory(Path.GetDirectoryName(path)); + System.IO.File.WriteAllText(path, content); + return path; + } + + /// Creates a junction (a folder link that never needs administrator rights). + public DirectoryInfo Junction(string linkPath, string target) + { + using var process = Process.Start(new ProcessStartInfo("cmd", $"/c mklink /J \"{linkPath}\" \"{target}\"") + { + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardOutput = true, + }); + process.StandardOutput.ReadToEnd(); + process.WaitForExit(); + if (process.ExitCode != 0) + throw new IOException($"mklink /J failed for {linkPath}"); + + return new DirectoryInfo(linkPath); + } + + public void Dispose() + { + try + { + ClearReadOnly(new DirectoryInfo(Root)); + Directory.Delete(Root, recursive: true); + } + catch (IOException) + { + // Best effort; a leftover temp folder must not fail a test + } + catch (UnauthorizedAccessException) + { + } + } + + private static void ClearReadOnly(DirectoryInfo directory) + { + directory.Attributes &= ~FileAttributes.ReadOnly; + foreach (var entry in directory.EnumerateFileSystemInfos("*", new EnumerationOptions { AttributesToSkip = 0 })) + { + entry.Attributes &= ~FileAttributes.ReadOnly; + if (entry is DirectoryInfo subdirectory && !entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) + ClearReadOnly(subdirectory); + } + } + } + + /// + /// Whether this process may create symbolic links (Developer Mode or elevation). + /// Tests that need them are skipped otherwise, which also drops coverage below the gate. + /// + internal static class SymlinkSupport + { + public const string SkipReason = "Symbolic links need Developer Mode or an elevated prompt."; + + private static readonly Lazy Probe = new(() => + { + var path = Path.Combine(Path.GetTempPath(), "symlinker-tests-probe-" + Guid.NewGuid().ToString("N")); + try + { + File.CreateSymbolicLink(path, path + "-target"); + File.Delete(path); + return true; + } + catch (IOException) + { + return false; + } + }); + + public static bool Available => Probe.Value; + + public static void Require() => Assert.SkipUnless(Available, SkipReason); + } + + /// Records dialogs instead of showing them, and answers questions with . + internal sealed class FakeDialogs : IDialogService + { + public List<(string Title, string Message)> Messages { get; } = new(); + + public List<(string Title, string Message, string Yes, string No)> Questions { get; } = new(); + + public bool Answer { get; set; } = true; + + public FakeProgressDialog Progress { get; } = new(); + + public (string Title, string Message) Last => Messages[^1]; + + public Task ShowMessageAsync(string title, string message) + { + Messages.Add((title, message)); + return Task.CompletedTask; + } + + public Task ConfirmAsync(string title, string message, string affirmativeText = null, string negativeText = null) + { + Questions.Add((title, message, affirmativeText, negativeText)); + return Task.FromResult(Answer); + } + + public Task ShowProgressAsync(string title, string message, string cancelText) + { + Progress.Shown = (title, message, cancelText); + return Task.FromResult(Progress); + } + } + + internal sealed class FakeProgressDialog : IProgressDialog + { + private int messageCount; + + public event EventHandler Canceled; + + public (string Title, string Message, string CancelText)? Shown { get; set; } + + public bool Indeterminate { get; private set; } + + public bool Closed { get; private set; } + + public ConcurrentQueue Values { get; } = new(); + + public ConcurrentQueue ShownMessages { get; } = new(); + + /// Runs once, when the first progress message is shown (after the size is known, before copying). + public Action BeforeCopy { get; set; } + + public void Cancel() => Canceled?.Invoke(this, EventArgs.Empty); + + public void SetIndeterminate() => Indeterminate = true; + + public void SetProgress(double value) => Values.Enqueue(value); + + public void SetMessage(string message) + { + ShownMessages.Enqueue(message); + if (Interlocked.Increment(ref messageCount) == 1) + BeforeCopy?.Invoke(); + } + + public Task CloseAsync() + { + Closed = true; + return Task.CompletedTask; + } + } + + /// + /// Records link requests instead of running mklink. answers the + /// administrator rights step, and decides each link's result. + /// + internal sealed class FakeLinkRunner : ILinkRunner + { + public static LinkResult Created => new() { Success = true, Message = "created" }; + + public List Prepared { get; } = new(); + + public List Calls { get; } = new(); + + /// False acts like a declined UAC prompt. + public bool PrepareResult { get; set; } = true; + + /// Runs when the administrator rights step is reached, before its answer. + public Action OnPrepare { get; set; } + + public Func Handler { get; set; } = _ => Created; + + public Task PrepareAsync(LinkRequest request) + { + Prepared.Add(request); + OnPrepare?.Invoke(); + return Task.FromResult(PrepareResult); + } + + public Task RunAsync(LinkRequest request) + { + Calls.Add(request); + return Task.FromResult(Handler(request)); + } + } + + /// A stand-in for the elevated helper process. + internal sealed class FakeLinkHelper : ILinkHelper + { + public bool IsAlive { get; set; } = true; + + public bool Disposed { get; private set; } + + public List Calls { get; } = new(); + + public Task CreateLinkAsync(LinkRequest request) + { + Calls.Add(request); + return Task.FromResult(new LinkResult { Success = true, Message = "elevated" }); + } + + public void Dispose() => Disposed = true; + } +} diff --git a/Symlinker.Tests/UiHelpersTests.cs b/Symlinker.Tests/UiHelpersTests.cs new file mode 100644 index 0000000..ef16ec1 --- /dev/null +++ b/Symlinker.Tests/UiHelpersTests.cs @@ -0,0 +1,127 @@ +namespace Symlinker.Tests +{ + using System; + using System.Globalization; + using System.IO; + + public sealed class UiHelpersTests : IDisposable + { + private readonly TempDir temp = new(); + + public void Dispose() => temp.Dispose(); + + [Theory] + [InlineData(@"C:\a\b", "b")] + [InlineData(@"C:\a\b\", "b")] + [InlineData("C:/a/b//", "b")] + [InlineData("name", "name")] + [InlineData(@"D:\", "D:")] + public void GetName_ReturnsLastPart(string path, string expected) + { + Assert.Equal(expected, UiHelpers.GetName(path)); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("bad\0path")] + public void GetExistingDirectory_ReturnsNull_ForEmptyOrInvalidPaths(string path) + { + Assert.Null(UiHelpers.GetExistingDirectory(path, useParent: false)); + } + + [Fact] + public void GetExistingDirectory_ReturnsThePath_WhenItExists() + { + var folder = temp.Dir("folder"); + + Assert.Equal(folder, UiHelpers.GetExistingDirectory(" " + folder + " ", useParent: false)); + } + + [Fact] + public void GetExistingDirectory_ReturnsNull_WhenThePathIsMissing() + { + Assert.Null(UiHelpers.GetExistingDirectory(temp.PathOf("missing"), useParent: false)); + } + + [Fact] + public void GetExistingDirectory_WithParent_ReturnsTheContainingFolder() + { + var file = temp.File(@"folder\file.txt"); + + Assert.Equal(Path.GetDirectoryName(file), UiHelpers.GetExistingDirectory(file, useParent: true)); + Assert.Equal(temp.Root, UiHelpers.GetExistingDirectory(temp.PathOf("folder") + @"\", useParent: true)); + } + + [Fact] + public void GetExistingDirectory_WithParent_FallsBackToTheDriveRoot() + { + var root = Path.GetPathRoot(temp.Root); + + Assert.Equal(root, UiHelpers.GetExistingDirectory(root, useParent: true)); + } + + [Theory] + [InlineData(0, "0 B")] + [InlineData(1023, "1023 B")] + [InlineData(1536, "1.5 KB")] + [InlineData(5L * 1024 * 1024, "5.0 MB")] + [InlineData(3L * 1024 * 1024 * 1024, "3.0 GB")] + [InlineData(2048L * 1024 * 1024 * 1024 * 1024, "2048.0 TB")] + public void FormatBytes_PicksTheLargestFittingUnit(long bytes, string expected) + { + var previous = CultureInfo.CurrentUICulture; + CultureInfo.CurrentUICulture = CultureInfo.InvariantCulture; + try + { + Assert.Equal(expected, UiHelpers.FormatBytes(bytes)); + } + finally + { + CultureInfo.CurrentUICulture = previous; + } + } + + [Fact] + public void GetAppVersion_PrefersTheClickOnceVersion() + { + const string Variable = "ClickOnce_CurrentVersion"; + var previous = Environment.GetEnvironmentVariable(Variable); + try + { + Environment.SetEnvironmentVariable(Variable, "9.8.7.6"); + Assert.Equal("9.8.7.6", UiHelpers.GetAppVersion()); + + Environment.SetEnvironmentVariable(Variable, null); + Assert.Equal(typeof(UiHelpers).Assembly.GetName().Version.ToString(), UiHelpers.GetAppVersion()); + } + finally + { + Environment.SetEnvironmentVariable(Variable, previous); + } + } + + [Fact] + public void LinkNameAutoFill_FollowsTheTargetUntilTheUserTypes() + { + var autoFill = new LinkNameAutoFill(); + + Assert.Equal("first", autoFill.Update(string.Empty, "first")); + + // Still the name we filled in, so it keeps following the target + Assert.Equal("second", autoFill.Update("first", "second")); + + // The user typed their own name, so it is left alone + Assert.Null(autoFill.Update("mine", "third")); + } + + [Fact] + public void LinkNameAutoFill_SkipsNamesThatCantBeLinkNames() + { + var autoFill = new LinkNameAutoFill(); + + Assert.Equal(string.Empty, autoFill.Update(string.Empty, "D:")); + Assert.Equal("data", autoFill.Update(string.Empty, "data")); + } + } +} diff --git a/Symlinker.sln b/Symlinker.sln index 59dd23c..7691c97 100644 --- a/Symlinker.sln +++ b/Symlinker.sln @@ -11,16 +11,42 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Directory.Packages.props = Directory.Packages.props EndProjectSection EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Symlinker.Tests", "Symlinker.Tests\Symlinker.Tests.csproj", "{DAC0A2C2-B84B-4986-B966-F143962A8F8A}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Debug|Any CPU.Build.0 = Debug|Any CPU + {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Debug|x64.ActiveCfg = Debug|Any CPU + {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Debug|x64.Build.0 = Debug|Any CPU + {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Debug|x86.ActiveCfg = Debug|Any CPU + {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Debug|x86.Build.0 = Debug|Any CPU {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Release|Any CPU.ActiveCfg = Release|Any CPU {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Release|Any CPU.Build.0 = Release|Any CPU + {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Release|x64.ActiveCfg = Release|Any CPU + {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Release|x64.Build.0 = Release|Any CPU + {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Release|x86.ActiveCfg = Release|Any CPU + {B92A15F1-D627-40C3-9BEA-CE8977435DE9}.Release|x86.Build.0 = Release|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Debug|Any CPU.Build.0 = Debug|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Debug|x64.ActiveCfg = Debug|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Debug|x64.Build.0 = Debug|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Debug|x86.ActiveCfg = Debug|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Debug|x86.Build.0 = Debug|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Release|Any CPU.ActiveCfg = Release|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Release|Any CPU.Build.0 = Release|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Release|x64.ActiveCfg = Release|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Release|x64.Build.0 = Release|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Release|x86.ActiveCfg = Release|Any CPU + {DAC0A2C2-B84B-4986-B966-F143962A8F8A}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/Symlinker/App.xaml.cs b/Symlinker/App.xaml.cs index 7ebbe96..1a6cb81 100644 --- a/Symlinker/App.xaml.cs +++ b/Symlinker/App.xaml.cs @@ -1,9 +1,11 @@ namespace Symlinker { + using System.Diagnostics.CodeAnalysis; using System.Windows; using ControlzEx.Theming; + [ExcludeFromCodeCoverage(Justification = "WPF startup; syncs the theme with Windows.")] public partial class App : Application { protected override void OnStartup(StartupEventArgs e) diff --git a/Symlinker/Dialogs.cs b/Symlinker/Dialogs.cs new file mode 100644 index 0000000..6120092 --- /dev/null +++ b/Symlinker/Dialogs.cs @@ -0,0 +1,99 @@ +namespace Symlinker +{ + using System; + using System.Diagnostics.CodeAnalysis; + using System.Threading.Tasks; + + using MahApps.Metro.Controls; + using MahApps.Metro.Controls.Dialogs; + + /// The dialogs the link logic needs, so it can run without a window. + internal interface IDialogService + { + Task ShowMessageAsync(string title, string message); + + /// Asks a yes/no question. Returns true when the user picks the affirmative button. + Task ConfirmAsync(string title, string message, string affirmativeText = null, string negativeText = null); + + Task ShowProgressAsync(string title, string message, string cancelText); + } + + /// An open, cancelable progress dialog. + internal interface IProgressDialog + { + event EventHandler Canceled; + + void SetIndeterminate(); + + void SetProgress(double value); + + void SetMessage(string message); + + Task CloseAsync(); + } + + /// Shows dialogs inside a MahApps window. + [ExcludeFromCodeCoverage(Justification = "Thin wrapper over MahApps dialogs, which need a live window.")] + internal sealed class MetroDialogService : IDialogService + { + private readonly MetroWindow window; + + public MetroDialogService(MetroWindow window) + { + this.window = window; + } + + public Task ShowMessageAsync(string title, string message) => + window.ShowMessageAsync(title, message, settings: CreateSettings()); + + public async Task ConfirmAsync(string title, string message, string affirmativeText = null, string negativeText = null) + { + var settings = CreateSettings(); + if (affirmativeText != null) + settings.AffirmativeButtonText = affirmativeText; + if (negativeText != null) + settings.NegativeButtonText = negativeText; + + var answer = await window.ShowMessageAsync(title, message, MessageDialogStyle.AffirmativeAndNegative, settings); + return answer == MessageDialogResult.Affirmative; + } + + public async Task ShowProgressAsync(string title, string message, string cancelText) + { + var settings = CreateSettings(); + settings.NegativeButtonText = cancelText; + var controller = await window.ShowProgressAsync(title, message, isCancelable: true, settings: settings); + return new MetroProgressDialog(controller); + } + + private static MetroDialogSettings CreateSettings() => new() + { + AnimateShow = false, + AnimateHide = false, + }; + + private sealed class MetroProgressDialog : IProgressDialog + { + private readonly ProgressDialogController controller; + + public MetroProgressDialog(ProgressDialogController controller) + { + this.controller = controller; + } + + public event EventHandler Canceled + { + add => controller.Canceled += value; + remove => controller.Canceled -= value; + } + + public void SetIndeterminate() => controller.SetIndeterminate(); + + public void SetProgress(double value) => controller.SetProgress(value); + + public void SetMessage(string message) => controller.SetMessage(message); + + public Task CloseAsync() => controller.CloseAsync(); + } + } +} diff --git a/Symlinker/ElevatedLinker.cs b/Symlinker/ElevatedLinker.cs index 3275161..ea92b5c 100644 --- a/Symlinker/ElevatedLinker.cs +++ b/Symlinker/ElevatedLinker.cs @@ -3,6 +3,7 @@ namespace Symlinker using System; using System.ComponentModel; using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Pipes; @@ -20,7 +21,7 @@ namespace Symlinker /// on a named pipe for link requests until disposed, so a caller can elevate before changing /// anything on disk, create the link later, and keep using it for more links. /// - internal sealed class ElevatedLinker : IDisposable + internal sealed class ElevatedLinker : ILinkHelper { /// Command line switch that runs Symlinker as the helper instead of opening the window. public const string HelperArg = "--link-helper"; @@ -35,7 +36,8 @@ internal sealed class ElevatedLinker : IDisposable private readonly StreamReader reader; private readonly StreamWriter writer; - private ElevatedLinker(NamedPipeServerStream pipe, Process process) + /// Wraps a connected pipe and the helper process on its other end. + internal ElevatedLinker(NamedPipeServerStream pipe, Process process) { this.pipe = pipe; this.process = process; @@ -47,6 +49,7 @@ private ElevatedLinker(NamedPipeServerStream pipe, Process process) /// Starts the helper as administrator. Returns null when the user cancels the UAC prompt. /// Throws when the helper starts but can't be reached. /// + [ExcludeFromCodeCoverage(Justification = "Shows the UAC prompt and starts an elevated process.")] public static async Task StartAsync() { var pipeName = "Symlinker-" + Guid.NewGuid().ToString("N"); @@ -139,7 +142,10 @@ public void Dispose() /// Runs in the elevated copy: connects back to the window that started it and creates /// each link it is sent, until the window closes the connection. Returns the exit code. /// - public static int RunHelper(string[] args) + public static int RunHelper(string[] args) => RunHelper(args, HelperConnectTimeoutMs); + + /// The helper loop, with a connect timeout that tests can shorten. + internal static int RunHelper(string[] args, int connectTimeoutMs) { if (args.Length != 3 || !uint.TryParse(args[2], NumberStyles.None, CultureInfo.InvariantCulture, out var parentId)) return 2; @@ -147,10 +153,10 @@ public static int RunHelper(string[] args) try { using var pipe = new NamedPipeClientStream(".", args[1], PipeDirection.InOut); - pipe.Connect(HelperConnectTimeoutMs); + pipe.Connect(connectTimeoutMs); // Only take requests from the window that asked for elevation - if (!GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var serverId) || serverId != parentId) + if (GetServerProcessId(pipe) != parentId) return 3; // Not disposed: the window closing the pipe is the normal way to finish, and @@ -183,6 +189,11 @@ public static int RunHelper(string[] args) } } + /// The process on the server end of the pipe, or null when Windows can't tell. + [ExcludeFromCodeCoverage(Justification = "Native lookup whose failure can't be triggered in a test.")] + private static uint? GetServerProcessId(PipeStream pipe) => + GetNamedPipeServerProcessId(pipe.SafePipeHandle, out var serverId) ? serverId : null; + [DllImport("kernel32.dll", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] private static extern bool GetNamedPipeClientProcessId(Microsoft.Win32.SafeHandles.SafePipeHandle pipe, out uint clientProcessId); diff --git a/Symlinker/Elevation.cs b/Symlinker/Elevation.cs index 1b29be7..f8597a4 100644 --- a/Symlinker/Elevation.cs +++ b/Symlinker/Elevation.cs @@ -1,6 +1,7 @@ namespace Symlinker { using System; + using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.InteropServices; using System.Security.Principal; @@ -30,6 +31,15 @@ internal sealed class LaunchOptions public string Target { get; set; } + /// True for folder mode, false for file mode, null when not given or not recognized. + public bool? IsFolderMode => + string.Equals(Mode, "folder", StringComparison.OrdinalIgnoreCase) ? true + : string.Equals(Mode, "file", StringComparison.OrdinalIgnoreCase) ? false + : null; + + /// The link type, or null when not given or not recognized. + public LinkKind? Kind => LinkKinds.Parse(LinkType); + /// Reads options from the command line. Unknown arguments (like the old --engage) are ignored. public static LaunchOptions Parse(string[] args) { @@ -76,16 +86,19 @@ public static bool IsElevated /// or Windows Developer Mode allows it without elevation. /// Junctions and hard links never need this. /// - public static bool CanCreateSymbolicLinks() + public static bool CanCreateSymbolicLinks() => CanCreateSymbolicLinks(IsElevated, File.CreateSymbolicLink); + + /// The check behind , with the link creation replaceable in tests. + internal static bool CanCreateSymbolicLinks(bool isElevated, Func createSymbolicLink) { - if (IsElevated) + if (isElevated) return true; // Try for real: a throwaway link in the temp folder, pointing nowhere var probe = Path.Combine(Path.GetTempPath(), "symlinker-probe-" + Guid.NewGuid().ToString("N")); try { - File.CreateSymbolicLink(probe, probe + "-target"); + createSymbolicLink(probe, probe + "-target"); File.Delete(probe); return true; } @@ -104,6 +117,7 @@ public static bool CanCreateSymbolicLinks() /// The Windows UAC shield (small size), shown on actions that need administrator rights. /// Returns null if Windows doesn't provide it. /// + [ExcludeFromCodeCoverage(Justification = "Native shell icon; the failure path can't be triggered.")] public static ImageSource GetShieldIcon() { var info = new StockIconInfo { Size = (uint)Marshal.SizeOf() }; diff --git a/Symlinker/InputValidator.cs b/Symlinker/InputValidator.cs new file mode 100644 index 0000000..de1221c --- /dev/null +++ b/Symlinker/InputValidator.cs @@ -0,0 +1,120 @@ +namespace Symlinker +{ + using System; + using System.Collections.Generic; + using System.IO; + using System.Windows.Media; + + using Res = Symlinker.Properties.Resources; + + /// The window's text fields, in the order they appear on screen. + internal enum InputField + { + LinkName, + LinkLocation, + Target, + } + + /// Checks what the user entered before a link is created. + internal static class InputValidator + { + /// + /// Returns the problem with each bad field, in screen order (name, location, target). + /// An empty list means everything is fine. + /// + public static List<(InputField Field, string Message)> Validate(string linkName, string linkLocation, string target, bool isFolder) + { + var errors = new List<(InputField, string)>(); + + var name = linkName.Trim(); + var location = linkLocation.Trim(); + target = target.Trim(); + + if (name.Length == 0) + errors.Add((InputField.LinkName, Res.ErrorLinkNameMissing)); + else if (name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) + errors.Add((InputField.LinkName, Res.ErrorLinkNameInvalid)); + + if (location.Length == 0) + errors.Add((InputField.LinkLocation, Res.ErrorLinkLocationMissing)); + else if (location.Contains('"')) + errors.Add((InputField.LinkLocation, Res.InvalidQuoteInPath)); + else if (!Directory.Exists(location)) + errors.Add((InputField.LinkLocation, Res.ErrorLinkLocationNotFound)); + + if (target.Length == 0) + errors.Add((InputField.Target, isFolder ? Res.ErrorTargetFolderMissing : Res.ErrorTargetFileMissing)); + else if (target.Contains('"')) + errors.Add((InputField.Target, Res.InvalidQuoteInPath)); + else if (isFolder && File.Exists(target)) + errors.Add((InputField.Target, Res.ErrorTargetIsFile)); + else if (!isFolder && Directory.Exists(target)) + errors.Add((InputField.Target, Res.ErrorTargetIsFolder)); + else if (!TargetFitsMode(target, isFolder) && !LinkPathInUse(location, name)) + errors.Add((InputField.Target, isFolder ? Res.ErrorTargetFolderNotFound : Res.ErrorTargetFileNotFound)); + + return errors; + } + + /// Whether the target path still makes sense in folder or file mode (an existing folder or file). + public static bool TargetFitsMode(string target, bool folderMode) + { + target = target.Trim(); + if (target.Length == 0) + return false; + + return folderMode ? Directory.Exists(target) : File.Exists(target); + } + + /// + /// Whether something already exists where the link would go. Link creation decides what + /// to do then, so a missing target isn't reported. + /// + private static bool LinkPathInUse(string location, string name) + { + if (location.Length == 0 || name.Length == 0) + return false; + + var path = Path.Combine(location, name); + return Directory.Exists(path) || File.Exists(path); + } + } + + /// Color math for text that has to stay readable on the user's accent color. + internal static class ColorContrast + { + /// Black or white, whichever reads better on drawn over . + public static Color TextOn(Color accent, Color? background) + { + // The accent is partly transparent, so judge the color actually seen on screen + if (background is Color behind) + accent = Blend(accent, behind); + + return ContrastRatio(accent, Colors.Black) > ContrastRatio(accent, Colors.White) ? Colors.Black : Colors.White; + } + + /// The opaque color seen when is drawn over . + public static Color Blend(Color top, Color bottom) + { + var a = top.A / 255.0; + byte Mix(byte t, byte b) => (byte)Math.Round((t * a) + (b * (1 - a))); + return Color.FromRgb(Mix(top.R, bottom.R), Mix(top.G, bottom.G), Mix(top.B, bottom.B)); + } + + /// WCAG contrast ratio between two colors (1 to 21). + public static double ContrastRatio(Color a, Color b) + { + static double Channel(byte value) + { + var c = value / 255.0; + return c <= 0.03928 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4); + } + + static double Luminance(Color c) => (0.2126 * Channel(c.R)) + (0.7152 * Channel(c.G)) + (0.0722 * Channel(c.B)); + + var la = Luminance(a); + var lb = Luminance(b); + return (Math.Max(la, lb) + 0.05) / (Math.Min(la, lb) + 0.05); + } + } +} diff --git a/Symlinker/LinkCommand.cs b/Symlinker/LinkCommand.cs index 091ca39..f0adeb7 100644 --- a/Symlinker/LinkCommand.cs +++ b/Symlinker/LinkCommand.cs @@ -7,6 +7,32 @@ namespace Symlinker using Res = Symlinker.Properties.Resources; + /// The kinds of link mklink can create. + internal enum LinkKind + { + Symbolic, + Hard, + Junction, + } + + /// The names used for on the command line and in . + internal static class LinkKinds + { + public static string ToName(LinkKind kind) => kind switch + { + LinkKind.Hard => "hard", + LinkKind.Junction => "junction", + _ => "symbolic", + }; + + /// Reads a link type name (any case). Returns null when it isn't one. + public static LinkKind? Parse(string name) => + string.Equals(name, "symbolic", StringComparison.OrdinalIgnoreCase) ? LinkKind.Symbolic + : string.Equals(name, "hard", StringComparison.OrdinalIgnoreCase) ? LinkKind.Hard + : string.Equals(name, "junction", StringComparison.OrdinalIgnoreCase) ? LinkKind.Junction + : null; + } + /// One link to create. Sent to the elevated helper as JSON, so it only holds plain values. internal sealed class LinkRequest { @@ -36,7 +62,10 @@ internal sealed class LinkResult /// Creates links with mklink. Used by the window and by the elevated helper. internal static class LinkCommand { - public static async Task RunAsync(LinkRequest request) + public static Task RunAsync(LinkRequest request) => RunAsync(request, "cmd"); + + /// Runs mklink through , which tests replace to check a missing shell. + internal static async Task RunAsync(LinkRequest request, string shell) { var arguments = BuildArguments(request); if (arguments == null) @@ -46,7 +75,7 @@ public static async Task RunAsync(LinkRequest request) { var startInfo = new ProcessStartInfo { - FileName = "cmd", + FileName = shell, Arguments = arguments, UseShellExecute = false, CreateNoWindow = true, @@ -78,7 +107,7 @@ public static async Task RunAsync(LinkRequest request) /// Builds the cmd.exe arguments. Returns null for anything that could break out of the /// quotes, since the elevated helper runs whatever it is sent. /// - private static string BuildArguments(LinkRequest request) + internal static string BuildArguments(LinkRequest request) { if (request == null || string.IsNullOrWhiteSpace(request.Link) || string.IsNullOrWhiteSpace(request.Target)) return null; diff --git a/Symlinker/LinkCreator.cs b/Symlinker/LinkCreator.cs new file mode 100644 index 0000000..ba61a9f --- /dev/null +++ b/Symlinker/LinkCreator.cs @@ -0,0 +1,369 @@ +namespace Symlinker +{ + using System; + using System.Diagnostics; + using System.Globalization; + using System.IO; + using System.Linq; + using System.Threading; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// What the user entered in the window. + internal sealed record LinkInput(string LinkLocation, string LinkName, string Destination, bool IsFolder, LinkKind Kind); + + /// + /// Creates links from what the user entered: validates it, asks before replacing anything, + /// and offers to move an existing file or folder to the target and leave a link behind. + /// + internal sealed class LinkCreator + { + private readonly IDialogService dialogs; + private readonly ILinkRunner runner; + + public LinkCreator(IDialogService dialogs, ILinkRunner runner) + { + this.dialogs = dialogs; + this.runner = runner; + } + + /// True while files are being moved, so the window can't be closed halfway through. + public bool IsMoving { get; private set; } + + /// Whether two paths are on the same drive, so a move is a rename instead of a copy. + internal Func IsSameVolume { get; set; } = LinkMover.IsSameVolume; + + /// Minimum time between progress updates while copying. + internal TimeSpan ProgressInterval { get; set; } = TimeSpan.FromMilliseconds(100); + + public async Task CreateAsync(LinkInput request) + { + try + { + request = request with + { + LinkLocation = request.LinkLocation.Trim(), + LinkName = request.LinkName.Trim(), + Destination = request.Destination.Trim(), + }; + + var linkLocation = request.LinkLocation; + var linkName = request.LinkName; + var destination = request.Destination; + + if (string.IsNullOrWhiteSpace(linkLocation) || string.IsNullOrWhiteSpace(linkName) || string.IsNullOrWhiteSpace(destination)) + { + await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.FillBlanks); + return; + } + + if (linkName.Contains('"') || linkLocation.Contains('"') || destination.Contains('"')) + { + await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.InvalidQuoteInPath); + return; + } + + // Full path: the administrator helper runs in a different working folder + var linkPath = Path.GetFullPath(Path.Combine(linkLocation, linkName)); + + // A real file or folder already sits where the link goes and the target is free: + // offer to move it to the target and leave a link behind (#33) + if (Directory.Exists(linkLocation) && Path.IsPathFullyQualified(destination)) + { + FileSystemInfo existing = request.IsFolder ? new DirectoryInfo(linkPath) : new FileInfo(linkPath); + if (existing.Exists && !LinkMover.IsLink(existing) && IsFreeMoveTarget(destination, request.IsFolder)) + { + await OfferMoveAsync(request, existing, linkPath, Path.GetFullPath(destination)); + return; + } + } + + if (request.IsFolder && Directory.Exists(linkLocation) && Directory.Exists(destination)) + { + await ReplaceOrCreateAsync( + request, + linkPath, + Directory.GetDirectories(linkLocation), + Res.DialogFolderExistsDialog, + Res.DialogFolderExists, + path => Directory.Delete(path, true)); + } + else if (!request.IsFolder && Directory.Exists(linkLocation) && File.Exists(destination)) + { + await ReplaceOrCreateAsync( + request, + linkPath, + Directory.GetFiles(linkLocation), + Res.DialogDeleteFileWarning, + Res.DialogDeleteFile, + File.Delete); + } + else + { + await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.FilesOrFolderNotExists); + } + } + catch (Exception exception) + { + await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MessageBoxExceptionOcurred + "\n" + exception.Message); + } + } + + /// + /// Whether the target path is free to receive a moved item: it doesn't exist yet, + /// or (in folder mode) it is an empty folder. + /// + private static bool IsFreeMoveTarget(string destination, bool isFolder) + { + if (File.Exists(destination)) + return false; + + if (!Directory.Exists(destination)) + return true; + + return isFolder && !Directory.EnumerateFileSystemEntries(destination).Any(); + } + + /// + /// Creates the link, first asking to delete an entry with the same name from . + /// + private async Task ReplaceOrCreateAsync(LinkInput request, string linkPath, string[] siblings, string title, string question, Action delete) + { + var existing = siblings.FirstOrDefault(e => Path.GetFileName(e).Equals(request.LinkName, StringComparison.OrdinalIgnoreCase)); + if (existing != null && !await dialogs.ConfirmAsync(title, question)) + { + await dialogs.ShowMessageAsync(Res.LinkCreationAbortedWarning, Res.LinkCreationAborted); + return; + } + + // Ask for administrator rights before deleting anything; a declined prompt quietly stops here + var linkRequest = ToLinkRequest(request, linkPath, request.Destination); + if (!await runner.PrepareAsync(linkRequest)) + return; + + if (existing != null) + delete(existing); + + var result = await runner.RunAsync(linkRequest); + await dialogs.ShowMessageAsync(result.Success ? Res.MessageBoxSuccessTitle : Res.MessageBoxErrorTitle, result.Message); + } + + private static LinkRequest ToLinkRequest(LinkInput input, string linkPath, string target) => new() + { + Type = LinkKinds.ToName(input.Kind), + Link = linkPath, + Target = target, + Directory = input.IsFolder, + }; + + private async Task OfferMoveAsync(LinkInput request, FileSystemInfo existing, string linkPath, string target) + { + var message = string.Format( + CultureInfo.CurrentUICulture, + request.IsFolder ? Res.DialogMoveFolder : Res.DialogMoveFile, + existing.Name, + target); + + if (!await dialogs.ConfirmAsync(Res.DialogMoveTitle, message, Res.ButtonMoveAndLink, Res.ButtonCancel)) + { + await dialogs.ShowMessageAsync(Res.LinkCreationAbortedWarning, Res.LinkCreationAborted); + return; + } + + // Ask for administrator rights before moving anything, so a declined prompt + // never leaves files moved without a link + var linkRequest = ToLinkRequest(request, linkPath, target); + if (!await runner.PrepareAsync(linkRequest)) + return; + + IsMoving = true; + try + { + await MoveAndLinkAsync(request.IsFolder, existing, linkRequest); + } + finally + { + IsMoving = false; + } + } + + /// + /// Moves to the link's target and creates the link where it was. + /// Any failure before the link exists puts everything back the way it was. + /// + private async Task MoveAndLinkAsync(bool isFolder, FileSystemInfo source, LinkRequest linkRequest) + { + var target = linkRequest.Target; + var originalPath = source.FullName; + + // The target is free (missing or an empty folder), so the source can't be inside it; + // only the other way around needs checking + if (LinkMover.IsSameOrInside(target, originalPath)) + { + await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MoveTargetInsideSource); + return; + } + + var targetWasEmptyFolder = Directory.Exists(target); + + // Where the original currently lives; it only leaves originalPath once we start moving + var currentPath = originalPath; + var copiedToTarget = false; + + try + { + // Creates the folder that holds the target (a no-op when the target is a drive root) + Directory.CreateDirectory(Path.GetFullPath(Path.Combine(target, ".."))); + + // Only ever an empty folder here (checked before offering the move) + if (targetWasEmptyFolder) + Directory.Delete(target); + + if (IsSameVolume(originalPath, target)) + { + // Same drive: a rename, instant and atomic + LinkMover.Rename(originalPath, target); + currentPath = target; + } + else + { + // Different drive: set the original aside first. This fails right away if + // something has its files open, before any time is spent copying. + var staging = LinkMover.GetUnusedPath(originalPath + ".symlinker-move"); + LinkMover.Rename(originalPath, staging); + currentPath = staging; + + copiedToTarget = true; + FileSystemInfo staged = isFolder ? new DirectoryInfo(staging) : new FileInfo(staging); + var copyError = await CopyWithProgressAsync(staged, target); + if (copyError != null) + { + var title = copyError == Res.MoveCanceled ? Res.LinkCreationAbortedWarning : Res.MessageBoxErrorTitle; + await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, copyError, title); + return; + } + } + + var linked = await runner.RunAsync(linkRequest); + if (!linked.Success) + { + await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, linked.Message)); + return; + } + + if (currentPath != target) + { + try + { + LinkMover.Delete(currentPath); + } + catch (Exception) + { + await dialogs.ShowMessageAsync( + Res.MessageBoxSuccessTitle, + string.Format(CultureInfo.CurrentUICulture, Res.MoveCleanupFailed, currentPath)); + return; + } + } + + await dialogs.ShowMessageAsync( + Res.MessageBoxSuccessTitle, + string.Format(CultureInfo.CurrentUICulture, Res.MoveSucceeded, source.Name, target)); + } + catch (Exception exception) + { + await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, exception.Message)); + } + } + + /// Puts the original back where it was and removes any partial copy, then explains what happened. + private async Task RollBackMoveAsync(string originalPath, string currentPath, string target, bool copiedToTarget, bool targetWasEmptyFolder, string message, string title = null) + { + title ??= Res.MessageBoxErrorTitle; + + try + { + // Only remove the target when it is our own copy, never the only copy of the files + // (a copy only happens after the original was set aside, so it's never at the target) + if (copiedToTarget) + LinkMover.Delete(target); + + if (currentPath != originalPath) + LinkMover.Rename(currentPath, originalPath); + + if (targetWasEmptyFolder) + Directory.CreateDirectory(target); + } + catch (Exception) + { + // Tell the user where their files are now; this is the original path if they never left it + message = string.Format(CultureInfo.CurrentUICulture, Res.MoveRollbackFailed, currentPath); + title = Res.MessageBoxErrorTitle; + } + + await dialogs.ShowMessageAsync(title, message); + } + + /// + /// Copies with a cancelable progress dialog. Returns null when the copy finished, + /// otherwise the message to show the user. + /// + private async Task CopyWithProgressAsync(FileSystemInfo source, string target) + { + var progressDialog = await dialogs.ShowProgressAsync(Res.ProgressMoveTitle, Res.ProgressMovePreparing, Res.ButtonCancel); + progressDialog.SetIndeterminate(); + + using var cancellation = new CancellationTokenSource(); + progressDialog.Canceled += (s, e) => cancellation.Cancel(); + + try + { + var total = await Task.Run(() => LinkMover.GetTotalBytes(source), cancellation.Token); + + void Show(long done) + { + progressDialog.SetProgress(total == 0 ? 1 : Math.Min(1, (double)done / total)); + progressDialog.SetMessage(string.Format(CultureInfo.CurrentUICulture, Res.ProgressMoveMessage, UiHelpers.FormatBytes(done), UiHelpers.FormatBytes(total))); + } + + Show(0); + IProgress progress = new Progress(Show); + var interval = ProgressInterval; + var stopwatch = Stopwatch.StartNew(); + var lastReport = TimeSpan.Zero; + long copied = 0; + + await Task.Run( + () => LinkMover.Copy( + source, + target, + bytes => + { + copied += bytes; + if (stopwatch.Elapsed - lastReport >= interval) + { + lastReport = stopwatch.Elapsed; + progress.Report(copied); + } + }, + cancellation.Token), + cancellation.Token); + + return null; + } + catch (OperationCanceledException) + { + return Res.MoveCanceled; + } + catch (Exception exception) + { + return string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, exception.Message); + } + finally + { + await progressDialog.CloseAsync(); + } + } + } +} diff --git a/Symlinker/LinkMover.cs b/Symlinker/LinkMover.cs index a7646a3..b7f706f 100644 --- a/Symlinker/LinkMover.cs +++ b/Symlinker/LinkMover.cs @@ -31,8 +31,12 @@ internal static class LinkMover }; /// Whether the entry is a symbolic link or junction (not a regular file or folder). + /// + /// The attribute check skips the slower link lookup for regular entries. A missing entry + /// reports every attribute, but has no link target, so it is not a link either. + /// public static bool IsLink(FileSystemInfo info) => - info.Exists && info.Attributes.HasFlag(FileAttributes.ReparsePoint) && info.LinkTarget != null; + info.Attributes.HasFlag(FileAttributes.ReparsePoint) && info.LinkTarget != null; /// Whether is itself or somewhere inside it. public static bool IsSameOrInside(string path, string parent) diff --git a/Symlinker/LinkRunner.cs b/Symlinker/LinkRunner.cs new file mode 100644 index 0000000..13eed2d --- /dev/null +++ b/Symlinker/LinkRunner.cs @@ -0,0 +1,111 @@ +namespace Symlinker +{ + using System; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// Creates links for , asking for administrator rights first when a link needs them. + internal interface ILinkRunner + { + /// + /// Gets ready to create : shows the UAC prompt if this link needs + /// administrator rights and they weren't granted yet. Call it before anything on disk changes. + /// Returns false when link creation should stop: the prompt was declined (nothing is shown) + /// or the administrator helper couldn't start (an error is shown). + /// + Task PrepareAsync(LinkRequest request); + + Task RunAsync(LinkRequest request); + } + + /// A running copy of Symlinker with administrator rights that creates links on request. + internal interface ILinkHelper : IDisposable + { + bool IsAlive { get; } + + Task CreateLinkAsync(LinkRequest request); + } + + /// + /// Runs mklink unelevated, except symbolic links while they need administrator rights: those go + /// through an elevated helper, started on the first one (one UAC prompt) and kept until disposed. + /// + internal sealed class LinkRunner : ILinkRunner, IDisposable + { + private readonly IDialogService dialogs; + private readonly Func symlinksNeedAdmin; + private readonly Func> startHelper; + private readonly Func> runUnelevated; + private readonly Action helperChanged; + + private ILinkHelper helper; + + /// Shows an error when the helper can't start. + /// Whether symbolic links currently need administrator rights. + /// Starts the helper (with a UAC prompt). Returns null when the prompt is declined. + /// Creates a link in this process. + /// Called after a helper starts, e.g. to hide the UAC shield. + public LinkRunner( + IDialogService dialogs, + Func symlinksNeedAdmin, + Func> startHelper, + Func> runUnelevated, + Action helperChanged) + { + this.dialogs = dialogs; + this.symlinksNeedAdmin = symlinksNeedAdmin; + this.startHelper = startHelper; + this.runUnelevated = runUnelevated; + this.helperChanged = helperChanged; + } + + /// Whether administrator rights were granted and the helper is still running, so no prompt would show. + public bool HelperRunning => helper?.IsAlive == true; + + public async Task PrepareAsync(LinkRequest request) + { + if (!NeedsAdmin(request) || HelperRunning) + return true; + + // The helper went away (e.g. ended from Task Manager); start a new one + Dispose(); + + try + { + helper = await startHelper(); + } + catch (Exception exception) + { + await dialogs.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MessageBoxExceptionOcurred + "\n" + exception.Message); + return false; + } + + helperChanged(); + return helper != null; + } + + public async Task RunAsync(LinkRequest request) + { + try + { + return helper != null && NeedsAdmin(request) + ? await helper.CreateLinkAsync(request) + : await runUnelevated(request); + } + catch (Exception exception) + { + return LinkResult.Failed(Res.MessageBoxExceptionOcurred + "\n" + exception.Message); + } + } + + /// Closes the helper, if one is running. + public void Dispose() + { + helper?.Dispose(); + helper = null; + } + + private bool NeedsAdmin(LinkRequest request) => request.Type == LinkKinds.ToName(LinkKind.Symbolic) && symlinksNeedAdmin(); + } +} diff --git a/Symlinker/MainWindow.Inputs.cs b/Symlinker/MainWindow.Inputs.cs index 750e0d3..f2cfbfd 100644 --- a/Symlinker/MainWindow.Inputs.cs +++ b/Symlinker/MainWindow.Inputs.cs @@ -2,7 +2,7 @@ namespace Symlinker { using System; using System.Collections.Generic; - using System.IO; + using System.Diagnostics.CodeAnalysis; using System.Linq; using System.Threading.Tasks; using System.Windows; @@ -18,6 +18,7 @@ namespace Symlinker using Res = Symlinker.Properties.Resources; /// Marks a text field as holding a bad value, so its template can highlight it. + [ExcludeFromCodeCoverage(Justification = "WPF attached property plumbing.")] public static class InputError { /// Identifies the HasError attached property. @@ -31,7 +32,7 @@ public static class InputError public static void SetHasError(DependencyObject element, bool value) => element.SetValue(HasErrorProperty, value); } - /// Input checks, inline errors, launch options and administrator rights for symbolic links. + /// Inline errors, launch options and the administrator rights notice. The checks live in . public partial class MainWindow { private const string ErrorBrushKey = "Symlinker.Brushes.Error"; @@ -50,9 +51,6 @@ public partial class MainWindow private bool symlinksNeedAdmin; private bool checkingSymlinkAccess; - // Administrator helper, started on the first symbolic link that needs it and kept until the window closes - private ElevatedLinker elevatedLinker; - private void InitializeInputs() { // The app theme is applied after the window is created, so refresh again once loaded @@ -82,7 +80,7 @@ private void InitializeInputs() }; // The administrator helper stays up for the whole session; closing the window ends it - Closed += (s, e) => StopElevatedLinker(); + Closed += (s, e) => linkRunner.Dispose(); } private async void RefreshSymlinkAccess() @@ -109,9 +107,6 @@ private async void RefreshSymlinkAccess() UpdateAdminNotice(); } - /// Whether the selected link is a symbolic link that needs administrator rights. - private bool LinkNeedsAdmin => symlinksNeedAdmin && symLinkRadio?.IsChecked == true; - /// /// Shows the UAC shield and the footer notice while creating the link would show a UAC /// prompt. Once the user has approved it for this session, neither is needed. @@ -121,7 +116,7 @@ private void UpdateAdminNotice() if (adminPanel == null || createLinkShield == null || symLinkRadio == null) return; - var wouldPrompt = LinkNeedsAdmin && elevatedLinker?.IsAlive != true; + var wouldPrompt = symlinksNeedAdmin && symLinkRadio.IsChecked == true && !linkRunner.HelperRunning; createLinkShield.Visibility = wouldPrompt && createLinkShield.Source != null ? Visibility.Visible : Visibility.Collapsed; adminNoticeShield.Visibility = adminNoticeShield.Source != null ? Visibility.Visible : Visibility.Collapsed; @@ -140,14 +135,7 @@ private void UpdateThemeBrushes() // Text on the accent color: black or white, whichever reads better on the user's // Windows accent (MahApps' IdealForeground is white even on light accents) if (TryFindResource("MahApps.Colors.Accent") is Color accent) - { - // The accent is partly transparent, so judge the color actually seen on screen - if (TryFindResource("MahApps.Colors.ThemeBackground") is Color background) - accent = Blend(accent, background); - - var onAccent = ContrastRatio(accent, Colors.Black) > ContrastRatio(accent, Colors.White) ? Colors.Black : Colors.White; - Resources[OnAccentBrushKey] = Frozen(onAccent); - } + Resources[OnAccentBrushKey] = Frozen(ColorContrast.TextOn(accent, TryFindResource("MahApps.Colors.ThemeBackground") as Color?)); } private static SolidColorBrush Frozen(Color color) @@ -157,29 +145,6 @@ private static SolidColorBrush Frozen(Color color) return brush; } - private static Color Blend(Color top, Color bottom) - { - var a = top.A / 255.0; - byte Mix(byte t, byte b) => (byte)Math.Round((t * a) + (b * (1 - a))); - return Color.FromRgb(Mix(top.R, bottom.R), Mix(top.G, bottom.G), Mix(top.B, bottom.B)); - } - - /// WCAG contrast ratio between two colors (1 to 21). - private static double ContrastRatio(Color a, Color b) - { - static double Channel(byte value) - { - var c = value / 255.0; - return c <= 0.03928 ? c / 12.92 : Math.Pow((c + 0.055) / 1.055, 2.4); - } - - static double Luminance(Color c) => (0.2126 * Channel(c.R)) + (0.7152 * Channel(c.G)) + (0.0722 * Channel(c.B)); - - var la = Luminance(a); - var lb = Luminance(b); - return (Math.Max(la, lb) + 0.05) / (Math.Min(la, lb) + 0.05); - } - /// Fills the form from the command line. private void ApplyLaunchOptions() { @@ -189,14 +154,12 @@ private void ApplyLaunchOptions() return; // Mode first: switching it may clear a target that doesn't fit - if (string.Equals(options.Mode, "file", StringComparison.OrdinalIgnoreCase)) - fileTypeRadio.IsChecked = true; - else if (string.Equals(options.Mode, "folder", StringComparison.OrdinalIgnoreCase)) - folderTypeRadio.IsChecked = true; + if (options.IsFolderMode is bool folderMode) + (folderMode ? folderTypeRadio : fileTypeRadio).IsChecked = true; - if (string.Equals(options.LinkType, "hard", StringComparison.OrdinalIgnoreCase) && !isFolder) + if (options.Kind == LinkKind.Hard && !isFolder) hardLinkRadio.IsChecked = true; - else if (string.Equals(options.LinkType, "junction", StringComparison.OrdinalIgnoreCase) && isFolder) + else if (options.Kind == LinkKind.Junction && isFolder) junctionRadio.IsChecked = true; if (options.LinkLocation != null) @@ -223,76 +186,20 @@ private void RefreshSymlinkAccessNow() UpdateAdminNotice(); } - /// - /// Starts the administrator helper if this link needs it and it isn't running yet. That - /// shows one UAC prompt; the helper then stays up until the window closes, so later links - /// don't ask again. Call it before anything on disk changes, so a declined prompt leaves - /// everything as it was. Returns false when link creation should stop: the user canceled - /// the prompt (nothing is shown then) or the helper couldn't start (an error is shown). - /// - private async Task ElevateIfNeededAsync() - { - if (!LinkNeedsAdmin) - return true; - - if (elevatedLinker?.IsAlive == true) - return true; - - // The helper went away (e.g. ended from Task Manager); start a new one - StopElevatedLinker(); - - try - { - elevatedLinker = await ElevatedLinker.StartAsync(); - } - catch (Exception exception) - { - await this.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MessageBoxExceptionOcurred + "\n" + exception.Message, settings: FastDialog); - return false; - } - - UpdateAdminNotice(); - return elevatedLinker != null; - } - - /// Closes the administrator helper, if one is running. - private void StopElevatedLinker() - { - elevatedLinker?.Dispose(); - elevatedLinker = null; - } - /// Checks every field, marks the bad ones and shows what's wrong. Returns true when all are fine. private bool ValidateInputs() { inputErrors.Clear(); - var name = linkNameTextBox.Text.Trim(); - var location = linkLocationTextBox.Text.Trim(); - var target = destinationLocationTextBox.Text.Trim(); - - if (name.Length == 0) - AddInputError(linkNameTextBox, Res.ErrorLinkNameMissing); - else if (name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) - AddInputError(linkNameTextBox, Res.ErrorLinkNameInvalid); - - if (location.Length == 0) - AddInputError(linkLocationTextBox, Res.ErrorLinkLocationMissing); - else if (location.Contains('"')) - AddInputError(linkLocationTextBox, Res.InvalidQuoteInPath); - else if (!Directory.Exists(location)) - AddInputError(linkLocationTextBox, Res.ErrorLinkLocationNotFound); - - if (target.Length == 0) - AddInputError(destinationLocationTextBox, isFolder ? Res.ErrorTargetFolderMissing : Res.ErrorTargetFileMissing); - else if (target.Contains('"')) - AddInputError(destinationLocationTextBox, Res.InvalidQuoteInPath); - else if (isFolder && File.Exists(target)) - AddInputError(destinationLocationTextBox, Res.ErrorTargetIsFile); - else if (!isFolder && Directory.Exists(target)) - AddInputError(destinationLocationTextBox, Res.ErrorTargetIsFolder); - else if (!(isFolder ? Directory.Exists(target) : File.Exists(target)) && !LinkPathInUse(location, name)) - AddInputError(destinationLocationTextBox, isFolder ? Res.ErrorTargetFolderNotFound : Res.ErrorTargetFileNotFound); + var boxes = new Dictionary + { + [InputField.LinkName] = linkNameTextBox, + [InputField.LinkLocation] = linkLocationTextBox, + [InputField.Target] = destinationLocationTextBox, + }; + + foreach (var (field, message) in InputValidator.Validate(linkNameTextBox.Text, linkLocationTextBox.Text, destinationLocationTextBox.Text, isFolder)) + AddInputError(boxes[field], message); ShowInputErrors(); if (inputErrors.Count != 0) @@ -301,26 +208,6 @@ private bool ValidateInputs() return inputErrors.Count == 0; } - /// - /// Whether something already exists where the link would go. Link creation decides what - /// to do then, so a missing target isn't reported here. - /// - private static bool LinkPathInUse(string location, string name) - { - if (location.Length == 0 || name.Length == 0) - return false; - - try - { - var path = Path.Combine(location, name); - return Directory.Exists(path) || File.Exists(path); - } - catch (ArgumentException) - { - return false; - } - } - private void AddInputError(TextBox box, string message) => inputErrors.Add(new KeyValuePair(box, message)); private void ClearInputErrors() @@ -369,15 +256,5 @@ private void UpdateTargetBrowseLabel() targetBrowseButton.ToolTip = label; AutomationProperties.SetName(targetBrowseButton, label); } - - /// Whether the target path still makes sense after switching between folder and file mode. - private static bool TargetFitsMode(string target, bool folderMode) - { - target = target.Trim(); - if (target.Length == 0) - return false; - - return folderMode ? Directory.Exists(target) : File.Exists(target); - } } } diff --git a/Symlinker/MainWindow.xaml.cs b/Symlinker/MainWindow.xaml.cs index 46d1a34..ae3b976 100644 --- a/Symlinker/MainWindow.xaml.cs +++ b/Symlinker/MainWindow.xaml.cs @@ -2,26 +2,22 @@ namespace Symlinker { using System; using System.ComponentModel; - using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; - using System.Linq; - using System.Reflection; using System.Runtime.InteropServices; - using System.Threading; - using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Interop; using MahApps.Metro.Controls; - using MahApps.Metro.Controls.Dialogs; using MahApps.Metro.IconPacks; using Res = Symlinker.Properties.Resources; - /// Main application window. + /// Main application window. Only view glue lives here; the logic is in tested classes. + [ExcludeFromCodeCoverage(Justification = "WPF view glue; needs a live window and user input.")] public partial class MainWindow : MetroWindow { private const int DWMWA_WINDOW_CORNER_PREFERENCE = 33; @@ -33,24 +29,25 @@ public partial class MainWindow : MetroWindow private const string PlaceholderBrushKey = "MahApps.Brushes.Gray2"; private const string PrimaryTextBrushKey = "MahApps.Brushes.ThemeForeground"; - private bool isFolder = true; - - // Last link name filled in from the target, so user-typed names are never overwritten - private string autoFilledLinkName = string.Empty; - - // True while files are being moved, so the window can't be closed halfway through - private bool isMoving; + private readonly LinkNameAutoFill linkNameAutoFill = new(); + private readonly IDialogService dialogs; + private readonly LinkRunner linkRunner; + private readonly LinkCreator linkCreator; - private static readonly MetroDialogSettings FastDialog = new() - { - AnimateShow = false, - AnimateHide = false, - }; + private bool isFolder = true; internal MainWindow(LaunchOptions options = null) { launchOptions = options; InitializeComponent(); + dialogs = new MetroDialogService(this); + linkRunner = new LinkRunner( + dialogs, + () => symlinksNeedAdmin, + async () => await ElevatedLinker.StartAsync(), + LinkCommand.RunAsync, + UpdateAdminNotice); + linkCreator = new LinkCreator(dialogs, linkRunner); InitializeInputs(); Loaded += OnLoaded; } @@ -98,7 +95,7 @@ private void UpdateMode() ClearInputErrors(); // Keep the target when it still fits the new mode (an existing folder or file) - if (!TargetFitsMode(destinationLocationTextBox.Text, isFolder)) + if (!InputValidator.TargetFitsMode(destinationLocationTextBox.Text, isFolder)) destinationLocationTextBox.Text = string.Empty; if (destinationLocationTextBox.Text.Length == 0) @@ -112,12 +109,10 @@ private void ShowTargetPlaceholder() destinationFolderName.SetResourceReference(ForegroundProperty, PlaceholderBrushKey); } - private string GetLinkType() - { - if (hardLinkRadio.IsChecked == true) return "hard"; - if (junctionRadio.IsChecked == true) return "junction"; - return "symbolic"; - } + private LinkKind SelectedKind => + hardLinkRadio.IsChecked == true ? LinkKind.Hard + : junctionRadio.IsChecked == true ? LinkKind.Junction + : LinkKind.Symbolic; private void DestinationPath_TextChanged(object sender, TextChangedEventArgs e) { @@ -129,438 +124,24 @@ private void DestinationPath_TextChanged(object sender, TextChangedEventArgs e) return; } - var trimmed = path.TrimEnd('\\', '/'); - var lastSep = trimmed.LastIndexOfAny(new[] { '\\', '/' }); - var name = lastSep >= 0 ? trimmed[(lastSep + 1)..] : trimmed; + var name = UiHelpers.GetName(path); destinationFolderName.Text = name; destinationFolderName.FontStyle = FontStyles.Normal; destinationFolderName.SetResourceReference(ForegroundProperty, PrimaryTextBrushKey); AutoFillLinkName(name); } - /// - /// Keeps the link name in sync with the target's name until the user types their own. - /// private void AutoFillLinkName(string targetName) { - var current = linkNameTextBox.Text; - var userEdited = current.Length != 0 && current != autoFilledLinkName; - if (userEdited) - return; - - // Skip names that can't be used as a link name, like a drive root ("D:") - if (targetName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) - targetName = string.Empty; - - autoFilledLinkName = targetName; - linkNameTextBox.Text = targetName; - } - - private async Task CreateLink() - { - try - { - var linkLocation = linkLocationTextBox.Text.Trim(); - var linkName = linkNameTextBox.Text.Trim(); - var destination = destinationLocationTextBox.Text.Trim(); - - if (string.IsNullOrWhiteSpace(linkLocation) || string.IsNullOrWhiteSpace(linkName) || string.IsNullOrWhiteSpace(destination)) - { - await this.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.FillBlanks, settings: FastDialog); - return; - } - - if (linkName.Contains('"') || linkLocation.Contains('"') || destination.Contains('"')) - { - await this.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.InvalidQuoteInPath, settings: FastDialog); - return; - } - - // Full path: the administrator helper runs in a different working folder - var link = Path.GetFullPath(Path.Combine(linkLocation, linkName)); - - // A real file or folder already sits where the link goes and the target is free: - // offer to move it to the target and leave a link behind (#33) - if (Directory.Exists(linkLocation) && Path.IsPathFullyQualified(destination)) - { - var linkPath = Path.Combine(linkLocation, linkName); - FileSystemInfo existing = isFolder ? new DirectoryInfo(linkPath) : new FileInfo(linkPath); - if (existing.Exists && !LinkMover.IsLink(existing) && IsFreeMoveTarget(destination)) - { - await OfferMoveAsync(existing, link, Path.GetFullPath(destination)); - return; - } - } - - if (isFolder && Directory.Exists(linkLocation) && Directory.Exists(destination)) - { - var directories = Directory.GetDirectories(linkLocation); - - if (directories.Any(e => Path.GetFileName(e).Equals(linkName, StringComparison.OrdinalIgnoreCase))) - { - var answer = await this.ShowMessageAsync( - Res.DialogFolderExistsDialog, - Res.DialogFolderExists, - MessageDialogStyle.AffirmativeAndNegative, - FastDialog); - if (answer == MessageDialogResult.Affirmative) - { - // Ask for administrator rights before deleting anything - if (!await ElevateIfNeededAsync()) - return; - - var dir2Delete = directories.First(e => Path.GetFileName(e).Equals(linkName, StringComparison.OrdinalIgnoreCase)); - Directory.Delete(dir2Delete, true); - await SendCommand(link, destination); - return; - } - - await this.ShowMessageAsync(Res.LinkCreationAbortedWarning, Res.LinkCreationAborted, settings: FastDialog); - } - else - { - await SendCommand(link, destination); - } - } - else if (!isFolder && Directory.Exists(linkLocation) && File.Exists(destination)) - { - var files = Directory.GetFiles(linkLocation); - if (files.Any(e => Path.GetFileName(e).Equals(linkName, StringComparison.OrdinalIgnoreCase))) - { - var answer = await this.ShowMessageAsync( - Res.DialogDeleteFileWarning, - Res.DialogDeleteFile, - MessageDialogStyle.AffirmativeAndNegative, - FastDialog); - if (answer == MessageDialogResult.Affirmative) - { - // Ask for administrator rights before deleting anything - if (!await ElevateIfNeededAsync()) - return; - - var file2Delete = files.First(e => Path.GetFileName(e).Equals(linkName, StringComparison.OrdinalIgnoreCase)); - File.Delete(file2Delete); - await SendCommand(link, destination); - return; - } - await this.ShowMessageAsync(Res.LinkCreationAbortedWarning, Res.LinkCreationAborted, settings: FastDialog); - } - else - { - await SendCommand(link, destination); - } - } - else - { - await this.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.FilesOrFolderNotExists, settings: FastDialog); - } - } - catch (Exception exception) - { - await this.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MessageBoxExceptionOcurred + "\n" + exception.Message, settings: FastDialog); - } - } - - private async Task SendCommand(string link, string destination) - { - // A declined UAC prompt quietly stops here - if (!await ElevateIfNeededAsync()) - return; - - var (success, message) = await RunMklinkAsync(link, destination); - await this.ShowMessageAsync( - success ? Res.MessageBoxSuccessTitle : Res.MessageBoxErrorTitle, - message, - settings: FastDialog); - } - - /// - /// Runs mklink and returns whether it worked, with the message to show the user. - /// Symbolic links that need administrator rights go through the helper started by - /// ; everything else runs unelevated. - /// - private async Task<(bool Success, string Message)> RunMklinkAsync(string link, string destination) - { - var request = new LinkRequest - { - Type = GetLinkType(), - Link = link, - Target = destination, - Directory = isFolder, - }; - - LinkResult result; - try - { - result = elevatedLinker != null && LinkNeedsAdmin - ? await elevatedLinker.CreateLinkAsync(request) - : await LinkCommand.RunAsync(request); - } - catch (Exception exception) - { - result = LinkResult.Failed(Res.MessageBoxExceptionOcurred + "\n" + exception.Message); - } - - return (result.Success, result.Message); - } - - /// - /// Whether the target path is free to receive a moved item: it doesn't exist yet, - /// or (in folder mode) it is an empty folder. - /// - private bool IsFreeMoveTarget(string destination) - { - if (File.Exists(destination)) - return false; - - if (!Directory.Exists(destination)) - return true; - - return isFolder && !Directory.EnumerateFileSystemEntries(destination).Any(); - } - - private async Task OfferMoveAsync(FileSystemInfo existing, string link, string target) - { - var settings = new MetroDialogSettings - { - AnimateShow = false, - AnimateHide = false, - AffirmativeButtonText = Res.ButtonMoveAndLink, - NegativeButtonText = Res.ButtonCancel, - }; - - var message = string.Format( - CultureInfo.CurrentUICulture, - isFolder ? Res.DialogMoveFolder : Res.DialogMoveFile, - existing.Name, - target); - - var answer = await this.ShowMessageAsync(Res.DialogMoveTitle, message, MessageDialogStyle.AffirmativeAndNegative, settings); - if (answer != MessageDialogResult.Affirmative) - { - await this.ShowMessageAsync(Res.LinkCreationAbortedWarning, Res.LinkCreationAborted, settings: FastDialog); - return; - } - - // Ask for administrator rights before moving anything, so a declined prompt - // never leaves files moved without a link - if (!await ElevateIfNeededAsync()) - return; - - isMoving = true; - try - { - await MoveAndLinkAsync(existing, link, target); - } - finally - { - isMoving = false; - } - } - - /// - /// Moves to and creates the link where it was. - /// Any failure before the link exists puts everything back the way it was. - /// - private async Task MoveAndLinkAsync(FileSystemInfo source, string link, string target) - { - var originalPath = source.FullName; - - if (LinkMover.IsSameOrInside(target, originalPath) || LinkMover.IsSameOrInside(originalPath, target)) - { - await this.ShowMessageAsync(Res.MessageBoxErrorTitle, Res.MoveTargetInsideSource, settings: FastDialog); - return; - } - - var targetWasEmptyFolder = Directory.Exists(target); - - // Where the original currently lives; it only leaves originalPath once we start moving - var currentPath = originalPath; - var copiedToTarget = false; - - try - { - var targetParent = Path.GetDirectoryName(target); - if (targetParent != null) - Directory.CreateDirectory(targetParent); - - // Only ever an empty folder here (checked before offering the move) - if (targetWasEmptyFolder) - Directory.Delete(target); - - if (LinkMover.IsSameVolume(originalPath, target)) - { - // Same drive: a rename, instant and atomic - LinkMover.Rename(originalPath, target); - currentPath = target; - } - else - { - // Different drive: set the original aside first. This fails right away if - // something has its files open, before any time is spent copying. - var staging = LinkMover.GetUnusedPath(originalPath + ".symlinker-move"); - LinkMover.Rename(originalPath, staging); - currentPath = staging; - - copiedToTarget = true; - FileSystemInfo staged = isFolder ? new DirectoryInfo(staging) : new FileInfo(staging); - var copyError = await CopyWithProgressAsync(staged, target); - if (copyError != null) - { - var title = copyError == Res.MoveCanceled ? Res.LinkCreationAbortedWarning : Res.MessageBoxErrorTitle; - await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, copyError, title); - return; - } - } - - var (linked, linkMessage) = await RunMklinkAsync(link, target); - if (!linked) - { - await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, linkMessage)); - return; - } - - if (currentPath != target) - { - try - { - LinkMover.Delete(currentPath); - } - catch (Exception) - { - await this.ShowMessageAsync( - Res.MessageBoxSuccessTitle, - string.Format(CultureInfo.CurrentUICulture, Res.MoveCleanupFailed, currentPath), - settings: FastDialog); - return; - } - } - - await this.ShowMessageAsync( - Res.MessageBoxSuccessTitle, - string.Format(CultureInfo.CurrentUICulture, Res.MoveSucceeded, source.Name, target), - settings: FastDialog); - } - catch (Exception exception) - { - await RollBackMoveAsync(originalPath, currentPath, target, copiedToTarget, targetWasEmptyFolder, string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, exception.Message)); - } - } - - /// Puts the original back where it was and removes any partial copy, then explains what happened. - private async Task RollBackMoveAsync(string originalPath, string currentPath, string target, bool copiedToTarget, bool targetWasEmptyFolder, string message, string title = null) - { - title ??= Res.MessageBoxErrorTitle; - - try - { - // Only remove the target when it is our own copy, never the only copy of the files - if (copiedToTarget && currentPath != target) - LinkMover.Delete(target); - - if (currentPath != originalPath) - LinkMover.Rename(currentPath, originalPath); - - if (targetWasEmptyFolder) - Directory.CreateDirectory(target); - } - catch (Exception) - { - if (currentPath != originalPath) - { - message = string.Format(CultureInfo.CurrentUICulture, Res.MoveRollbackFailed, currentPath); - title = Res.MessageBoxErrorTitle; - } - } - - await this.ShowMessageAsync(title, message, settings: FastDialog); - } - - /// - /// Copies with a cancelable progress dialog. Returns null when the copy finished, - /// otherwise the message to show the user. - /// - private async Task CopyWithProgressAsync(FileSystemInfo source, string target) - { - var settings = new MetroDialogSettings - { - AnimateShow = false, - AnimateHide = false, - NegativeButtonText = Res.ButtonCancel, - }; - - var controller = await this.ShowProgressAsync(Res.ProgressMoveTitle, Res.ProgressMovePreparing, isCancelable: true, settings: settings); - controller.SetIndeterminate(); - - using var cancellation = new CancellationTokenSource(); - controller.Canceled += (s, e) => cancellation.Cancel(); - - try - { - var total = await Task.Run(() => LinkMover.GetTotalBytes(source), cancellation.Token); - - void Show(long done) - { - controller.SetProgress(total == 0 ? 1 : Math.Min(1, (double)done / total)); - controller.SetMessage(string.Format(CultureInfo.CurrentUICulture, Res.ProgressMoveMessage, FormatBytes(done), FormatBytes(total))); - } - - Show(0); - IProgress progress = new Progress(Show); - var stopwatch = Stopwatch.StartNew(); - long copied = 0; - long lastReport = 0; - - await Task.Run( - () => LinkMover.Copy( - source, - target, - bytes => - { - copied += bytes; - if (stopwatch.ElapsedMilliseconds - lastReport >= 100) - { - lastReport = stopwatch.ElapsedMilliseconds; - progress.Report(copied); - } - }, - cancellation.Token), - cancellation.Token); - - return null; - } - catch (OperationCanceledException) - { - return Res.MoveCanceled; - } - catch (Exception exception) - { - return string.Format(CultureInfo.CurrentUICulture, Res.MoveFailed, exception.Message); - } - finally - { - await controller.CloseAsync(); - } - } - - private static string FormatBytes(long bytes) - { - string[] units = { "B", "KB", "MB", "GB", "TB" }; - double size = bytes; - var unit = 0; - while (size >= 1024 && unit < units.Length - 1) - { - size /= 1024; - unit++; - } - - return string.Format(CultureInfo.CurrentUICulture, unit == 0 ? "{0:0} {1}" : "{0:0.0} {1}", size, units[unit]); + var name = linkNameAutoFill.Update(linkNameTextBox.Text, targetName); + if (name != null) + linkNameTextBox.Text = name; } /// Keeps the window open while files are being moved, so a move is never cut off halfway. protected override void OnClosing(CancelEventArgs e) { - if (isMoving) + if (linkCreator.IsMoving) e.Cancel = true; base.OnClosing(e); @@ -571,7 +152,7 @@ private void ExploreButton1_Click(object sender, RoutedEventArgs e) var dialog = new Microsoft.Win32.OpenFolderDialog(); // Start in the folder already entered so consecutive links don't need re-navigating - var current = GetExistingDirectory(linkLocationTextBox.Text, useParent: false); + var current = UiHelpers.GetExistingDirectory(linkLocationTextBox.Text, useParent: false); if (current != null) dialog.InitialDirectory = current; @@ -582,7 +163,7 @@ private void ExploreButton1_Click(object sender, RoutedEventArgs e) private void ExploreButton2_Click(object sender, RoutedEventArgs e) { // Start next to the current target so sibling folders/files are one click away - var current = GetExistingDirectory(destinationLocationTextBox.Text, useParent: true); + var current = UiHelpers.GetExistingDirectory(destinationLocationTextBox.Text, useParent: true); if (isFolder) { @@ -602,32 +183,6 @@ private void ExploreButton2_Click(object sender, RoutedEventArgs e) } } - /// - /// Returns an existing directory to open a picker in, based on a path typed by the user. - /// With , returns the folder that contains the path instead. - /// Returns null when nothing usable exists. - /// - private static string GetExistingDirectory(string path, bool useParent) - { - try - { - path = path.Trim(); - if (string.IsNullOrEmpty(path)) - return null; - - var full = Path.GetFullPath(path); - var candidate = useParent ? Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(full)) : full; - - // Fall back to the path itself when it has no parent (e.g. a drive root) - candidate ??= full; - return Directory.Exists(candidate) ? candidate : null; - } - catch (Exception) - { - return null; - } - } - private async void CreateLink_Click(object sender, RoutedEventArgs e) { createLinkButton.IsEnabled = false; @@ -636,7 +191,12 @@ private async void CreateLink_Click(object sender, RoutedEventArgs e) if (ValidateInputs()) { RefreshSymlinkAccessNow(); - await CreateLink(); + await linkCreator.CreateAsync(new LinkInput( + linkLocationTextBox.Text, + linkNameTextBox.Text, + destinationLocationTextBox.Text, + isFolder, + SelectedKind)); } } finally @@ -647,18 +207,9 @@ private async void CreateLink_Click(object sender, RoutedEventArgs e) private async void AboutButton_Click(object sender, RoutedEventArgs e) { - var version = Environment.GetEnvironmentVariable("ClickOnce_CurrentVersion"); - if (string.IsNullOrEmpty(version)) - { - var assembly = Assembly.GetExecutingAssembly(); - var fvi = FileVersionInfo.GetVersionInfo(assembly.Location); - version = fvi.FileVersion; - } - - await this.ShowMessageAsync( + await dialogs.ShowMessageAsync( Res.MessageBoxAboutTitle, - string.Format(CultureInfo.CurrentUICulture, Res.AboutDescription, version, DateTime.Now.Year), - settings: FastDialog); + string.Format(CultureInfo.CurrentUICulture, Res.AboutDescription, UiHelpers.GetAppVersion(), DateTime.Now.Year)); } private void TextBox_DragOver(object sender, DragEventArgs e) diff --git a/Symlinker/Program.cs b/Symlinker/Program.cs index ac766e2..3ae973d 100644 --- a/Symlinker/Program.cs +++ b/Symlinker/Program.cs @@ -1,7 +1,9 @@ namespace Symlinker { using System; + using System.Diagnostics.CodeAnalysis; + [ExcludeFromCodeCoverage(Justification = "Entry point that starts the WPF application.")] internal static class Program { [STAThread] diff --git a/Symlinker/Symlinker.csproj b/Symlinker/Symlinker.csproj index cd5c097..5115006 100644 --- a/Symlinker/Symlinker.csproj +++ b/Symlinker/Symlinker.csproj @@ -57,6 +57,9 @@ + + + diff --git a/Symlinker/UiHelpers.cs b/Symlinker/UiHelpers.cs new file mode 100644 index 0000000..f7ff453 --- /dev/null +++ b/Symlinker/UiHelpers.cs @@ -0,0 +1,95 @@ +namespace Symlinker +{ + using System; + using System.Diagnostics; + using System.Globalization; + using System.IO; + + /// Small helpers behind the window's text boxes and pickers. + internal static class UiHelpers + { + /// The last part of a path (the file or folder name), ignoring trailing separators. + public static string GetName(string path) + { + var trimmed = path.TrimEnd('\\', '/'); + var lastSep = trimmed.LastIndexOfAny(new[] { '\\', '/' }); + return lastSep >= 0 ? trimmed[(lastSep + 1)..] : trimmed; + } + + /// + /// Returns an existing directory to open a picker in, based on a path typed by the user. + /// With , returns the folder that contains the path instead. + /// Returns null when nothing usable exists. + /// + public static string GetExistingDirectory(string path, bool useParent) + { + try + { + path = path.Trim(); + if (string.IsNullOrEmpty(path)) + return null; + + var full = Path.GetFullPath(path); + var candidate = useParent ? Path.GetDirectoryName(Path.TrimEndingDirectorySeparator(full)) : full; + + // Fall back to the path itself when it has no parent (e.g. a drive root) + candidate ??= full; + return Directory.Exists(candidate) ? candidate : null; + } + catch (Exception) + { + return null; + } + } + + /// A byte count in the largest unit that keeps it at or above 1, like "1.5 MB". + public static string FormatBytes(long bytes) + { + string[] units = { "B", "KB", "MB", "GB", "TB" }; + double size = bytes; + var unit = 0; + while (size >= 1024 && unit < units.Length - 1) + { + size /= 1024; + unit++; + } + + return string.Format(CultureInfo.CurrentUICulture, unit == 0 ? "{0:0} {1}" : "{0:0.0} {1}", size, units[unit]); + } + + /// The version shown in the About dialog: the ClickOnce version when installed, else the file version. + public static string GetAppVersion() + { + var version = Environment.GetEnvironmentVariable("ClickOnce_CurrentVersion"); + if (string.IsNullOrEmpty(version)) + version = FileVersionInfo.GetVersionInfo(typeof(UiHelpers).Assembly.Location).FileVersion; + return version; + } + } + + /// + /// Keeps the link name in sync with the target's name until the user types their own. + /// + internal sealed class LinkNameAutoFill + { + // Last link name filled in from the target, so user-typed names are never overwritten + private string lastFilled = string.Empty; + + /// + /// Returns the link name to show for a new target name, or null to keep + /// because the user typed it. + /// + public string Update(string currentName, string targetName) + { + if (currentName.Length != 0 && currentName != lastFilled) + return null; + + // Skip names that can't be used as a link name, like a drive root ("D:") + if (targetName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) + targetName = string.Empty; + + lastFilled = targetName; + return targetName; + } + } +} diff --git a/global.json b/global.json new file mode 100644 index 0000000..3140116 --- /dev/null +++ b/global.json @@ -0,0 +1,5 @@ +{ + "test": { + "runner": "Microsoft.Testing.Platform" + } +}