From 936a1feae585f5b0c326da33d17b1b54315a9310 Mon Sep 17 00:00:00 2001 From: Alejandro Mora Date: Fri, 6 Nov 2026 08:05:09 -0500 Subject: [PATCH] test: add xUnit test project with 100% coverage gate Move the link workflow out of MainWindow into testable classes (LinkCreator, Mklink, UiHelpers) behind a small dialog interface, and cover them with tests against the real file system. - dotnet test runs on Microsoft.Testing.Platform (global.json) and fails below 100% line, branch or method coverage (coverlet.MTP) - WPF and UAC glue is marked [ExcludeFromCodeCoverage] - CI runs the tests on pull requests and uploads the coverage report - Remove unreachable branches in the move and rollback paths - Update CLAUDE.md for the WPF layout and testing Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 11 + .gitignore | 1 + CLAUDE.md | 81 ++-- Directory.Packages.props | 4 + Symlinker.Tests/LinkCreatorTests.cs | 494 ++++++++++++++++++++++++ Symlinker.Tests/LinkMoverTests.cs | 230 +++++++++++ Symlinker.Tests/MklinkTests.cs | 79 ++++ Symlinker.Tests/Symlinker.Tests.csproj | 31 ++ Symlinker.Tests/TestSupport.cs | 145 +++++++ Symlinker.Tests/UiHelpersTests.cs | 127 +++++++ Symlinker.sln | 26 ++ Symlinker/App.xaml.cs | 2 + Symlinker/Dialogs.cs | 99 +++++ Symlinker/LinkCreator.cs | 354 +++++++++++++++++ Symlinker/LinkMover.cs | 6 +- Symlinker/MainWindow.xaml.cs | 502 ++----------------------- Symlinker/Mklink.cs | 85 +++++ Symlinker/Program.cs | 2 + Symlinker/Symlinker.csproj | 3 + Symlinker/UiHelpers.cs | 95 +++++ global.json | 5 + 21 files changed, 1867 insertions(+), 515 deletions(-) create mode 100644 Symlinker.Tests/LinkCreatorTests.cs create mode 100644 Symlinker.Tests/LinkMoverTests.cs create mode 100644 Symlinker.Tests/MklinkTests.cs create mode 100644 Symlinker.Tests/Symlinker.Tests.csproj create mode 100644 Symlinker.Tests/TestSupport.cs create mode 100644 Symlinker.Tests/UiHelpersTests.cs create mode 100644 Symlinker/Dialogs.cs create mode 100644 Symlinker/LinkCreator.cs create mode 100644 Symlinker/Mklink.cs create mode 100644 Symlinker/UiHelpers.cs create mode 100644 global.json 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 459bb7f..b21cf43 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co ## Project Overview -Symlinker is a Windows Forms application (.NET 8) that provides a GUI for creating symbolic links, hard links, and directory junctions on Windows. It wraps the Windows `mklink` command with an easy-to-use interface. +Symlinker is a WPF application (.NET 10) that provides a GUI for creating symbolic links, hard links, and directory junctions on Windows. It wraps the Windows `mklink` command with an easy-to-use interface. **Target Platform:** Windows 10+ only (as of 2025 modernization) @@ -43,67 +43,68 @@ The `release.ps1` script: dotnet run --project "Symlinker/Symlinker.csproj" ``` -## Architecture +### Running the Tests -### Key Components +```powershell +dotnet test --project Symlinker.Tests +``` -1. **Program.cs**: Entry point with UAC elevation logic - - Automatically re-launches itself with administrator privileges using the `--engage` flag - - Uses Windows API (`BCM_SETSHIELD`) to display UAC shield icon +- 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 or UAC (`MainWindow`, `App`, `Program`, `MetroDialogService`) is marked `[ExcludeFromCodeCoverage]`. Keep logic out of those and put it in a tested class instead -2. **MainWindow.cs**: Main form and business logic - - Handles UI state for file vs. folder symlink modes - - Manages three link types: Symbolic Link, Hard Link, Directory Junction - - Executes `cmd.exe /c mklink` with appropriate parameters - - Supports drag-and-drop for file/folder paths +## Architecture -3. **MainWindow.Designer.cs**: Auto-generated Windows Forms designer code - - Contains all UI control initialization +WPF app (.NET 10) using MahApps.Metro. The window is thin view glue; the logic lives in plain classes that the tests drive with fake dialogs and a fake mklink. -### Link Creation Flow +### Key Components -1. User selects link type (file/folder) via `typeSelectorComboBox` -2. `Switcher()` method updates UI labels and available link types -3. User inputs link location, link name, and destination -4. `CreateLink()` validates paths and checks for conflicts -5. `SendCommand()` builds and executes mklink command with proper escaping -6. Process output/error handlers display results via MessageBox +1. **Program.cs**: Entry point. Relaunches itself elevated (`runas`) with the `--engage` flag +2. **App.xaml(.cs)**: Loads MahApps styles and syncs the theme with Windows +3. **MainWindow.xaml(.cs)**: View glue: file/folder mode, pickers, drag and drop, link name auto-fill +4. **LinkCreator.cs**: The link workflow: validation, 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) +5. **LinkMover.cs**: File system helpers for moving: copy that keeps attributes and recreates nested links, delete that never follows links +6. **Mklink.cs**: `LinkKind`, mklink argument building, and `CmdMklinkRunner` which runs `cmd /c mklink` +7. **Dialogs.cs**: `IDialogService` / `IProgressDialog`, and `MetroDialogService` which shows them in the window +8. **UiHelpers.cs**: Path name extraction, picker start folders, byte formatting, app version, `LinkNameAutoFill` -### Important Patterns +### Link Type Mapping -- **Command Building**: Uses `string.Format()` with `CultureInfo.InvariantCulture` for mklink command construction -- **Path Handling**: Wraps paths in quotes to support spaces -- **Link Type Mapping**: - - Symbolic Link: `/D` (directory) or empty (file) - - Hard Link: `/H` - - Directory Junction: `/J` (folders only) +- Symbolic Link: `/D` (directory) or empty (file) +- Hard Link: `/H` (files only) +- Directory Junction: `/D /J` (folders only) ### Dependencies Managed via Central Package Management ([Directory.Packages.props](Directory.Packages.props)): -- **Microsoft-WindowsAPICodePack-Core** (1.1.5): Common file dialogs -- **Microsoft-WindowsAPICodePack-Shell** (1.1.5): Shell integration +- **MahApps.Metro**: Window chrome, dialogs, theming +- **MahApps.Metro.IconPacks.Material**: Icons +- **xunit.v3**, **coverlet.MTP**: Tests and coverage ## Project Structure ``` Symlinker/ -├── Symlinker/ # Main project directory -│ ├── MainWindow.cs # Core form logic -│ ├── MainWindow.Designer.cs # UI designer code -│ ├── MainWindow.resx # Form resources +├── Symlinker/ # App +│ ├── LinkCreator.cs # Link workflow (tested) +│ ├── LinkMover.cs # Move/copy/delete helpers (tested) +│ ├── Mklink.cs # mklink arguments and runner (tested) +│ ├── Dialogs.cs # Dialog abstraction + MahApps implementation +│ ├── UiHelpers.cs # Small UI helpers (tested) +│ ├── MainWindow.xaml(.cs) # Window (view glue) +│ ├── App.xaml(.cs) # Application, theme sync │ ├── Program.cs # Entry point with UAC elevation -│ ├── Properties/ -│ │ ├── Resources.Designer.cs # Localized strings -│ │ └── Settings.Designer.cs # App settings -│ ├── icon.ico # Application icon -│ └── Symlinker.csproj -├── Symlinker.sln # Solution file +│ └── Properties/ # Localized resources and settings +├── Symlinker.Tests/ # xUnit tests, 100% coverage gate +├── Symlinker.sln ├── Directory.Packages.props # Central package versions +├── global.json # Opts dotnet test into Microsoft.Testing.Platform ├── release.ps1 # ClickOnce build/publish script └── .github/workflows/ - └── release.yml # GitHub Actions for tagged releases + ├── ci.yml # Build and test on pull requests + └── release.yml # Tagged releases ``` ## Release Process 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/LinkCreatorTests.cs b/Symlinker.Tests/LinkCreatorTests.cs new file mode 100644 index 0000000..64de60c --- /dev/null +++ b/Symlinker.Tests/LinkCreatorTests.cs @@ -0,0 +1,494 @@ +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 mklink. + /// + public sealed class LinkCreatorTests : IDisposable + { + private readonly TempDir temp = new(); + private readonly FakeDialogs dialogs = new(); + private readonly FakeMklink mklink = new(); + private readonly LinkCreator creator; + + public LinkCreatorTests() + { + creator = new LinkCreator(dialogs, mklink); + } + + 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 LinkRequest(linkLocation ?? Links, linkName, destination, isFolder, kind)); + + 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 LinkRequest(location, name, destination, true, LinkKind.Symbolic)); + + Assert.Equal((Res.MessageBoxErrorTitle, Res.FillBlanks), dialogs.Last); + Assert.Empty(mklink.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 LinkRequest(location, name, destination, true, LinkKind.Symbolic)); + + Assert.Equal((Res.MessageBoxErrorTitle, Res.InvalidQuoteInPath), dialogs.Last); + Assert.Empty(mklink.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(mklink.Calls); + } + + // ---- Plain link creation ---- + + [Fact] + public async Task Create_FolderLink_RunsMklinkWithTrimmedPaths() + { + temp.Dir("links"); + var target = temp.Dir("target"); + + await creator.CreateAsync(new LinkRequest($" {Links} ", " name ", $" {target} ", true, LinkKind.Junction)); + + Assert.Equal(Mklink.BuildArguments(true, LinkKind.Junction, $@"{Links}\name", target), Assert.Single(mklink.Calls)); + 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); + + Assert.Equal(Mklink.BuildArguments(false, LinkKind.Hard, $@"{Links}\name.txt", target), Assert.Single(mklink.Calls)); + } + + [Fact] + public async Task Create_ShowsMklinkErrors() + { + temp.Dir("links"); + var target = temp.Dir("target"); + mklink.Handler = _ => (false, "access denied"); + + await Create("name", target); + + Assert.Equal((Res.MessageBoxErrorTitle, "access denied"), dialogs.Last); + } + + // ---- 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(mklink.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(mklink.Calls); + } + + [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(mklink.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(mklink.Calls); + } + + [Fact] + public async Task Create_TreatsAnExistingLinkAsReplaceable_NotMovable() + { + temp.Dir("links"); + Directory.CreateSymbolicLink(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(mklink.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(mklink.Calls); + } + + [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; + mklink.Handler = _ => + { + movingDuringLink = creator.IsMoving; + return (true, "created"); + }; + + await Create("name", target); + + Assert.Equal(Mklink.BuildArguments(true, LinkKind.Symbolic, $@"{Links}\name", target), Assert.Single(mklink.Calls)); + 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(mklink.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(mklink.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(mklink.Calls); + } + + [Fact] + public async Task Move_LinkFailure_OnTheSameDrive_PutsEverythingBack() + { + temp.File(@"links\name\data.txt"); + var target = temp.Dir("empty-target"); + mklink.Handler = _ => (false, "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(); + mklink.Handler = _ => (false, "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 + mklink.Handler = _ => + { + File.WriteAllText(temp.PathOf("links", "name"), "in the way"); + return (false, "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 + mklink.Handler = _ => + { + lockedFile = new FileStream(Path.Combine(staging, "data.txt"), FileMode.Open, FileAccess.Read, FileShare.None); + return (true, "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(mklink.Calls); + } + } +} diff --git a/Symlinker.Tests/LinkMoverTests.cs b/Symlinker.Tests/LinkMoverTests.cs new file mode 100644 index 0000000..a70495f --- /dev/null +++ b/Symlinker.Tests/LinkMoverTests.cs @@ -0,0 +1,230 @@ +namespace Symlinker.Tests +{ + using System; + using System.IO; + using System.Threading; + + /// + /// Runs against the real file system. Symbolic links need Developer Mode or an elevated prompt. + /// + 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_ForSymbolicLinks() + { + 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)); + Directory.CreateSymbolicLink(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_CopiesEverythingAndRecreatesLinks() + { + var linkedFolder = temp.Dir("linked-folder"); + var linkedFile = temp.File("linked.txt"); + + temp.File(@"source\a.txt", "aaa"); + var hidden = temp.File(@"source\nested\hidden.txt", "bb"); + File.SetAttributes(hidden, FileAttributes.Hidden); + temp.Dir(@"source\empty"); + Directory.CreateSymbolicLink(temp.PathOf("source", "folder-link"), linkedFolder); + File.CreateSymbolicLink(temp.PathOf("source", "file-link.txt"), linkedFile); + + 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(linkedFolder, new DirectoryInfo(temp.PathOf("copy", "folder-link")).LinkTarget); + Assert.Equal(linkedFile, new FileInfo(temp.PathOf("copy", "file-link.txt")).LinkTarget); + 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_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"); + Directory.CreateSymbolicLink(link, target); + + LinkMover.Delete(link); + + Assert.False(Directory.Exists(link)); + Assert.True(File.Exists(Path.Combine(target, "keep.txt"))); + } + + [Fact] + public void Delete_RemovesReadOnlyContentButNotLinkedFiles() + { + var linkedFolder = temp.Dir("linked-folder"); + var kept = temp.File(@"linked-folder\keep.txt"); + var linkedFile = temp.File("linked.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; + Directory.CreateSymbolicLink(temp.PathOf("folder", "folder-link"), linkedFolder); + File.CreateSymbolicLink(temp.PathOf("folder", "file-link.txt"), linkedFile); + 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)); + Assert.True(File.Exists(linkedFile)); + } + } +} diff --git a/Symlinker.Tests/MklinkTests.cs b/Symlinker.Tests/MklinkTests.cs new file mode 100644 index 0000000..0f21d68 --- /dev/null +++ b/Symlinker.Tests/MklinkTests.cs @@ -0,0 +1,79 @@ +namespace Symlinker.Tests +{ + using System; + using System.IO; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + public sealed class MklinkTests : IDisposable + { + private readonly TempDir temp = new(); + + public void Dispose() => temp.Dispose(); + + [Theory] + [InlineData(true, nameof(LinkKind.Symbolic), "/c mklink /D \"C:\\links\\a\" \"D:\\target\"")] + [InlineData(true, nameof(LinkKind.Junction), "/c mklink /D /J \"C:\\links\\a\" \"D:\\target\"")] + [InlineData(false, nameof(LinkKind.Symbolic), "/c mklink \"C:\\links\\a\" \"D:\\target\"")] + [InlineData(false, nameof(LinkKind.Hard), "/c mklink /H \"C:\\links\\a\" \"D:\\target\"")] + public void BuildArguments_MatchesTheLinkType(bool isFolder, string kind, string expected) + { + Assert.Equal(expected, Mklink.BuildArguments(isFolder, Enum.Parse(kind), @"C:\links\a", @"D:\target")); + } + + [Fact] + public async Task Runner_ReturnsTheOutput_WhenTheCommandWorks() + { + var result = await new CmdMklinkRunner().RunAsync("/c echo hello"); + + Assert.Equal((true, "hello"), result); + } + + [Fact] + public async Task Runner_ReturnsADefaultMessage_WhenTheCommandPrintsNothing() + { + var result = await new CmdMklinkRunner().RunAsync("/c exit 0"); + + Assert.Equal((true, Res.LinkSuccessfullyCreated), result); + } + + [Fact] + public async Task Runner_ReturnsTheError_WhenTheCommandFails() + { + var result = await new CmdMklinkRunner().RunAsync("/c (echo oops 1>&2) & exit 3"); + + Assert.Equal((false, "oops"), result); + } + + [Fact] + public async Task Runner_FallsBackToTheOutput_WhenAFailedCommandHasNoError() + { + var result = await new CmdMklinkRunner().RunAsync("/c echo plain& exit 2"); + + Assert.Equal((false, "plain"), result); + } + + [Fact] + public async Task Runner_ReportsAMissingShell() + { + var result = await new CmdMklinkRunner(temp.PathOf("no-such-shell.exe")).RunAsync("/c echo hi"); + + Assert.Equal((false, Res.CmdNotFound), result); + } + + [Fact] + public async Task Runner_CreatesARealJunction() + { + var target = temp.Dir("target"); + temp.File(@"target\inside.txt"); + var link = temp.PathOf("link"); + + var (success, _) = await new CmdMklinkRunner().RunAsync(Mklink.BuildArguments(true, LinkKind.Junction, link, target)); + + Assert.True(success); + Assert.True(LinkMover.IsLink(new DirectoryInfo(link))); + Assert.True(File.Exists(Path.Combine(link, "inside.txt"))); + } + } +} 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..7bfd360 --- /dev/null +++ b/Symlinker.Tests/TestSupport.cs @@ -0,0 +1,145 @@ +namespace Symlinker.Tests +{ + using System; + using System.Collections.Concurrent; + using System.Collections.Generic; + 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; + } + + 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); + } + } + } + + /// 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 mklink calls; decides the result. + internal sealed class FakeMklink : IMklinkRunner + { + public List Calls { get; } = new(); + + public Func Handler { get; set; } = _ => (true, "created"); + + public Task<(bool Success, string Message)> RunAsync(string arguments) + { + Calls.Add(arguments); + return Task.FromResult(Handler(arguments)); + } + } +} 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/LinkCreator.cs b/Symlinker/LinkCreator.cs new file mode 100644 index 0000000..6d4f1da --- /dev/null +++ b/Symlinker/LinkCreator.cs @@ -0,0 +1,354 @@ +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 LinkRequest(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 IMklinkRunner mklink; + + public LinkCreator(IDialogService dialogs, IMklinkRunner mklink) + { + this.dialogs = dialogs; + this.mklink = mklink; + } + + /// 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(LinkRequest 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; + } + + var linkPath = $"{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 existingPath = Path.Combine(linkLocation, linkName); + FileSystemInfo existing = request.IsFolder ? new DirectoryInfo(existingPath) : new FileInfo(existingPath); + 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(LinkRequest 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) + { + if (!await dialogs.ConfirmAsync(title, question)) + { + await dialogs.ShowMessageAsync(Res.LinkCreationAbortedWarning, Res.LinkCreationAborted); + return; + } + + delete(existing); + } + + var (success, message) = await RunMklinkAsync(request, linkPath, request.Destination); + await dialogs.ShowMessageAsync(success ? Res.MessageBoxSuccessTitle : Res.MessageBoxErrorTitle, message); + } + + private Task<(bool Success, string Message)> RunMklinkAsync(LinkRequest request, string linkPath, string destination) => + mklink.RunAsync(Mklink.BuildArguments(request.IsFolder, request.Kind, linkPath, destination)); + + private async Task OfferMoveAsync(LinkRequest 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; + } + + IsMoving = true; + try + { + await MoveAndLinkAsync(request, existing, linkPath, 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(LinkRequest request, FileSystemInfo source, string linkPath, string 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 = request.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(request, linkPath, 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 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/MainWindow.xaml.cs b/Symlinker/MainWindow.xaml.cs index 5ca8140..41a1d9e 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,23 +29,17 @@ public partial class MainWindow : MetroWindow private const string PlaceholderBrushKey = "MahApps.Brushes.Gray3"; 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 LinkCreator linkCreator; - private static readonly MetroDialogSettings FastDialog = new() - { - AnimateShow = false, - AnimateHide = false, - }; + private bool isFolder = true; public MainWindow() { InitializeComponent(); + dialogs = new MetroDialogService(this); + linkCreator = new LinkCreator(dialogs, new CmdMklinkRunner()); Loaded += OnLoaded; } @@ -101,12 +91,10 @@ private void UpdateMode() } } - private string GetLinkTypeFlag() - { - if (hardLinkRadio.IsChecked == true) return "/H "; - if (junctionRadio.IsChecked == true) return "/J "; - return string.Empty; - } + private LinkKind SelectedKind => + hardLinkRadio.IsChecked == true ? LinkKind.Hard + : junctionRadio.IsChecked == true ? LinkKind.Junction + : LinkKind.Symbolic; private void DestinationPath_TextChanged(object sender, TextChangedEventArgs e) { @@ -119,427 +107,23 @@ 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.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; - } - - var link = $"\"{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) - { - 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) - { - 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) - { - 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. - private async Task<(bool Success, string Message)> RunMklinkAsync(string link, string destination) - { - try - { - var typeLink = GetLinkTypeFlag(); - var directory = isFolder ? "/D " : string.Empty; - var stringCommand = $"/c mklink {directory}{typeLink}{link} \"{destination}\""; - var processStartInfo = new ProcessStartInfo - { - FileName = "cmd", - Arguments = stringCommand, - UseShellExecute = false, - CreateNoWindow = true, - RedirectStandardError = true, - RedirectStandardOutput = true - }; - - using var process = new Process { StartInfo = processStartInfo }; - process.Start(); - var output = process.StandardOutput.ReadToEndAsync(); - var error = process.StandardError.ReadToEndAsync(); - await process.WaitForExitAsync(); - - var outputText = (await output).Trim(); - var errorText = (await error).Trim(); - - if (process.ExitCode == 0) - return (true, outputText.Length > 0 ? outputText : Res.LinkSuccessfullyCreated); - - return (false, errorText.Length > 0 ? errorText : outputText); - } - catch (Exception) - { - return (false, Res.CmdNotFound); - } - } - - /// - /// 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; - } - - 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); @@ -550,7 +134,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; @@ -561,7 +145,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) { @@ -581,38 +165,17 @@ 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; try { - await CreateLink(); + await linkCreator.CreateAsync(new LinkRequest( + linkLocationTextBox.Text, + linkNameTextBox.Text, + destinationLocationTextBox.Text, + isFolder, + SelectedKind)); } finally { @@ -622,18 +185,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/Mklink.cs b/Symlinker/Mklink.cs new file mode 100644 index 0000000..5bcba6e --- /dev/null +++ b/Symlinker/Mklink.cs @@ -0,0 +1,85 @@ +namespace Symlinker +{ + using System; + using System.Diagnostics; + using System.Threading.Tasks; + + using Res = Symlinker.Properties.Resources; + + /// The kinds of link mklink can create. + internal enum LinkKind + { + Symbolic, + Hard, + Junction, + } + + /// Runs mklink and returns whether it worked, with the message to show the user. + internal interface IMklinkRunner + { + Task<(bool Success, string Message)> RunAsync(string arguments); + } + + /// Builds mklink command lines. + internal static class Mklink + { + /// The cmd.exe arguments that create a link at pointing to . + public static string BuildArguments(bool isFolder, LinkKind kind, string linkPath, string destination) + { + var directory = isFolder ? "/D " : string.Empty; + var type = kind switch + { + LinkKind.Hard => "/H ", + LinkKind.Junction => "/J ", + _ => string.Empty, + }; + + return $"/c mklink {directory}{type}\"{linkPath}\" \"{destination}\""; + } + } + + /// Runs mklink through cmd.exe. + internal sealed class CmdMklinkRunner : IMklinkRunner + { + private readonly string shell; + + public CmdMklinkRunner(string shell = "cmd") + { + this.shell = shell; + } + + public async Task<(bool Success, string Message)> RunAsync(string arguments) + { + try + { + var processStartInfo = new ProcessStartInfo + { + FileName = shell, + Arguments = arguments, + UseShellExecute = false, + CreateNoWindow = true, + RedirectStandardError = true, + RedirectStandardOutput = true, + }; + + using var process = new Process { StartInfo = processStartInfo }; + process.Start(); + var output = process.StandardOutput.ReadToEndAsync(); + var error = process.StandardError.ReadToEndAsync(); + await process.WaitForExitAsync(); + + var outputText = (await output).Trim(); + var errorText = (await error).Trim(); + + if (process.ExitCode == 0) + return (true, outputText.Length > 0 ? outputText : Res.LinkSuccessfullyCreated); + + return (false, errorText.Length > 0 ? errorText : outputText); + } + catch (Exception) + { + return (false, Res.CmdNotFound); + } + } + } +} diff --git a/Symlinker/Program.cs b/Symlinker/Program.cs index 9c9ca57..bf00bf3 100644 --- a/Symlinker/Program.cs +++ b/Symlinker/Program.cs @@ -3,8 +3,10 @@ namespace Symlinker using System; using System.ComponentModel; using System.Diagnostics; + using System.Diagnostics.CodeAnalysis; using System.Linq; + [ExcludeFromCodeCoverage(Justification = "Entry point that relaunches itself elevated through UAC.")] internal static class Program { [STAThread] diff --git a/Symlinker/Symlinker.csproj b/Symlinker/Symlinker.csproj index b86a208..70c395f 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" + } +}