diff --git a/.github/dependabot.yml b/.github/dependabot.yml index 0fbdbdc..54ceced 100644 --- a/.github/dependabot.yml +++ b/.github/dependabot.yml @@ -14,7 +14,7 @@ updates: target-branch: "main" - package-ecosystem: "nuget" - directory: "/Parallel.Desktop" + directory: "/Parallel.Gui" schedule: interval: "daily" target-branch: "main" diff --git a/.github/workflows/dotnet-release.yml b/.github/workflows/dotnet-release.yml index 031118a..93f709c 100644 --- a/.github/workflows/dotnet-release.yml +++ b/.github/workflows/dotnet-release.yml @@ -73,7 +73,9 @@ jobs: } $projects = @( - @{ name="cmd"; path="Parallel.Cli/Parallel.Cli.csproj" } + @{ name="cmd"; path="Parallel.Cli/Parallel.Cli.csproj"; extra=@() }, + # The desktop app ships its native Avalonia/Skia libraries inside the single file. + @{ name="desktop"; path="Parallel.Gui/Parallel.Gui.csproj"; extra=@("--self-contained", "/p:IncludeNativeLibrariesForSelfExtract=true") } ) $distRoot = Join-Path $env:GITHUB_WORKSPACE "dist" @@ -83,7 +85,10 @@ jobs: $outputDir = Join-Path $env:GITHUB_WORKSPACE "dist/$($proj.name)/$os/$arch" New-Item -ItemType Directory -Force -Path $outputDir - dotnet publish $proj.path -c Release -r $rid /p:PublishSingleFile=true /p:DebugType=None /p:DebugSymbols=false /p:PublishDir=$outputDir + dotnet publish $proj.path -c Release -r $rid /p:PublishSingleFile=true /p:DebugType=None /p:DebugSymbols=false /p:PublishDir=$outputDir @($proj.extra) + + # SkiaSharp/HarfBuzz ship ~100 MB of native .pdb files next to the exe; they aren't needed to run. + Remove-Item "$outputDir/*.pdb" -ErrorAction SilentlyContinue $repoName = $repoName = "${{ github.event.repository.name }}" $zipName = "$repoName-$version-$($proj.name)-$osName-$arch.zip" diff --git a/Parallel.Cli/Commands/BackupCommand.cs b/Parallel.Cli/Commands/BackupCommand.cs new file mode 100644 index 0000000..8b5d906 --- /dev/null +++ b/Parallel.Cli/Commands/BackupCommand.cs @@ -0,0 +1,113 @@ +// Copyright 2026 Entex Interactive + +using System.ComponentModel; +using Parallel.Core.Config; +using Parallel.Cli.Infrastructure; +using Parallel.Core.Engine; +using Parallel.Core.Repository; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace Parallel.Cli.Commands +{ + public sealed class BackupSettings : VaultSettings + { + [CommandOption("-p|--path ")] + [Description("Back up only these paths (repeatable) instead of the configured sources.")] + public string[] Paths { get; init; } = []; + + [CommandOption("--rehash")] + [Description("Read every file again instead of trusting size and modification time.")] + public bool Rehash { get; init; } + + [CommandOption("--no-vss")] + [Description("Windows: do not use a Volume Shadow Copy.")] + public bool NoVss { get; init; } + + [CommandOption("--one-file-system")] + [Description("Do not cross into other mounted file systems.")] + public bool OneFileSystem { get; init; } + + [CommandOption("--tag ")] + [Description("Label the snapshot (repeatable). A tagged backup is always saved, even if nothing changed.")] + public string[] Tags { get; init; } = []; + + [CommandOption("--force")] + [Description("Save a new snapshot even if nothing changed since the last one.")] + public bool Force { get; init; } + + [CommandOption("--verbose")] + [Description("List every new or changed file.")] + public bool Verbose { get; init; } + } + + [Description("Backs up the folders chosen with 'parallel backup add' into a new snapshot (skipped if nothing changed).")] + public sealed class BackupCommand(AppConfig config) : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, BackupSettings s, CancellationToken ct) + { + int exitCode = 0; + foreach (VaultConfig vault in VaultAccess.Select(config, s.Vault)) + { + List sources = s.Paths.Length > 0 ? s.Paths.Select(PathMap.Normalize).ToList() : vault.Sources; + if (sources.Count == 0) + { + AnsiConsole.MarkupLine($"[yellow]{Markup.Escape(vault.Name)}: nothing to back up. Add folders with 'parallel backup add '.[/]"); + exitCode = Math.Max(exitCode, 1); + continue; + } + + exitCode = Math.Max(exitCode, await RunAsync(vault, config.ExcludesFor(vault), sources, s, s.Verbose, ct)); + } + + return exitCode; + } + + /// Runs one backup. Returns 0 on success, 3 when the snapshot was saved but some items had errors. + public static async Task RunAsync(VaultConfig vault, IReadOnlyList excludes, IReadOnlyList sources, BackupSettings s, bool verbose, CancellationToken ct) + { + AnsiConsole.MarkupLine($"[bold]{Markup.Escape(vault.Name)}[/]: backing up {sources.Count} path(s) to {Markup.Escape(vault.Describe())}"); + await using Repository repo = await VaultAccess.OpenAsync(vault, s.PasswordFile, ct); + + ConsoleProgress progress = new(verbose); + BackupOptions options = new() + { + Sources = sources, + Excludes = excludes, + Rehash = s.Rehash, + OneFileSystem = s.OneFileSystem || vault.OneFileSystem, + UseVss = vault.UseVss && !s.NoVss, + Tags = s.Tags, + AlwaysSnapshot = s.Force || s.Tags.Length > 0, + Progress = progress, + }; + + BackupResult result = await progress.RunAsync("Backing up", () => new BackupEngine(repo, options, AppConfig.Directory).RunAsync(ct)); + Print(result); + return result.Errors.Count == 0 ? 0 : 3; + } + + private static void Print(BackupResult result) + { + var sum = result.Snapshot.Summary; + Grid grid = new Grid().AddColumn().AddColumn(); + grid.AddRow("Snapshot", result.Skipped ? $"none (nothing changed since [bold]{result.SnapshotId[..8]}[/])" : $"[bold]{result.SnapshotId[..8]}[/]"); + grid.AddRow("Files", $"{sum.Files:N0} ({sum.FilesNew:N0} new, {sum.FilesChanged:N0} changed, {sum.FilesUnchanged:N0} unchanged)"); + grid.AddRow("Folders", $"{sum.Directories:N0}"); + grid.AddRow("Size", Format.Bytes(sum.Bytes)); + grid.AddRow("Stored", $"{Format.Bytes(sum.BytesAdded)} added to the vault"); + grid.AddRow("Time", Format.Duration(TimeSpan.FromSeconds(sum.Seconds))); + AnsiConsole.Write(grid); + + if (result.Errors.Count == 0) + { + AnsiConsole.MarkupLine(result.Skipped ? "[green]Nothing changed; the latest snapshot is already up to date.[/]" : "[green]Backup complete.[/]"); + return; + } + + AnsiConsole.MarkupLine($"[yellow]Backup saved, but {result.Errors.Count:N0} item(s) could not be read. Their previous versions (if any) were kept in this snapshot:[/]"); + foreach (EngineError error in result.Errors.Take(20)) AnsiConsole.MarkupLine($" [yellow]{Markup.Escape(error.Path)}[/]: {Markup.Escape(error.Message)}"); + if (result.Errors.Count > 20) AnsiConsole.MarkupLine($" ... and {result.Errors.Count - 20:N0} more (see the log in {Markup.Escape(AppConfig.LogDirectory)})"); + } + } +} diff --git a/Parallel.Cli/Commands/CleanCommand.cs b/Parallel.Cli/Commands/CleanCommand.cs deleted file mode 100644 index 9355249..0000000 --- a/Parallel.Cli/Commands/CleanCommand.cs +++ /dev/null @@ -1,125 +0,0 @@ -// Copyright 2026 Entex Interactive - -using System.CommandLine; -using Parallel.Cli.Utils; -using Parallel.Core.IO.Scanning; -using Parallel.Core.Settings; -using Parallel.Core.Utils; - -namespace Parallel.Cli.Commands -{ - public class CleanCommand : Command - { - private long _freedBytes = 0; - private int _filesCount = 0; - private int _dirsCount = 0; - - private readonly Option _sourceOpt = new(["--path", "-p"], "The source path to clean."); - private readonly Option _daysOpt = new(["--days", "-d"], "The amount of days to hang onto files."); - private readonly Option _recursiveOpt = new(["--recursive", "-R"], "If to include subdirectories."); - private readonly Option _verboseOpt = new(["--verbose", "-v"], "Shows verbose output."); - - public CleanCommand() : base("clean", "Cleans up the file system by removing old files.") - { - this.AddOption(_sourceOpt); - this.AddOption(_daysOpt); - this.AddOption(_recursiveOpt); - this.AddOption(_verboseOpt); - this.SetHandler(async (path, days, recursive, verbose) => - { - ParallelConfig config = ParallelConfig.Load(); - if (days <= config.RetentionPeriod) days = config.RetentionPeriod; - CommandLine.WriteLine($"Scanning for cleanable files older than {days:N0} days old...", ConsoleColor.DarkGray); - - if (string.IsNullOrEmpty(path)) - { - await CleanSystemAsync(config, days, recursive, verbose); - } - else - { - await CleanDirectoryAsync(config, path, days, recursive, verbose); - } - - CommandLine.WriteLine($"Successfully cleaned {_filesCount:N0} files and {_dirsCount:N0} directories, ({Formatter.FromBytes(_freedBytes)} removed)", ConsoleColor.Green); - }, _sourceOpt, _daysOpt, _recursiveOpt, _verboseOpt); - } - - private async Task CleanSystemAsync(ParallelConfig config, int days, bool recursive, bool verbose) - { - await System.Threading.Tasks.Parallel.ForEachAsync(config.CleanDirectories, ParallelConfig.Options, async (path, ct) => - { - await CleanDirectoryAsync(config, path, days, recursive, verbose); - }); - } - - private async Task CleanDirectoryAsync(ParallelConfig config, string path, int days, bool recursive, bool verbose) - { - if (!Directory.Exists(path)) - { - CommandLine.WriteLine($"Unable to find path: '{path}'", ConsoleColor.Yellow); - return; - } - - UnixTime minTime = UnixTime.FromMilliseconds(UnixTime.Now.TotalMilliseconds - (days * UnixTime.Day)); - IEnumerable cleanableFiles = FileScanner.GetCleanableFiles(path, minTime, recursive); - if (cleanableFiles.Any()) - { - await System.Threading.Tasks.Parallel.ForEachAsync(cleanableFiles, ParallelConfig.Options, (fi, ct) => - { - if (fi.Exists) - { - try - { - _freedBytes += fi.Length; - _filesCount++; - fi.Delete(); - } - catch (Exception ex) - { - CommandLine.WriteLine($"Unable to remove file: {fi.FullName}", ConsoleColor.Yellow); - Log.Warning($"{ex.GetBaseException().Message}"); - } - } - - return ValueTask.CompletedTask; - }); - } - - IEnumerable directories = FileScanner.GetEmptyDirectories(path, recursive); - if (!directories.Any()) - { - System.Threading.Tasks.Parallel.ForEach(directories, ParallelConfig.Options, (di) => - { - if (di.Exists && !di.EnumerateFiles().Any()) - { - try - { - Log.Debug($"Removing empty directory: {di?.FullName}"); - di?.Delete(true); - } - catch (Exception ex) - { - Log.Error($"{ex.GetBaseException().Message}"); - } - } - }); - - DirectoryInfo currentDir = new DirectoryInfo(path); - SearchOption option = recursive ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly; - if (!currentDir.EnumerateFiles("*", option).Any()) - { - try - { - Log.Debug($"Removing empty directory: {currentDir.FullName}"); - currentDir.Delete(true); - _dirsCount++; - } - catch (Exception ex) - { - Log.Warning($"{ex.GetBaseException().Message}"); - } - } - } - } - } -} \ No newline at end of file diff --git a/Parallel.Cli/Commands/DuplicatesCommand.cs b/Parallel.Cli/Commands/DuplicatesCommand.cs deleted file mode 100644 index 363f891..0000000 --- a/Parallel.Cli/Commands/DuplicatesCommand.cs +++ /dev/null @@ -1,47 +0,0 @@ -// Copyright 2026 Entex Interactive - -using System.CommandLine; -using Parallel.Cli.Utils; -using Parallel.Core.IO; -using Parallel.Core.IO.Scanning; -using Parallel.Core.Models; -using Parallel.Core.Utils; - -namespace Parallel.Cli.Commands -{ - public class DuplicatesCommand : Command - { - private readonly Argument sourceArg = new("path", "The directory to scan."); - - public DuplicatesCommand() : base("duplicates", "Scans a directory for duplicate files.") - { - this.AddArgument(sourceArg); - this.SetHandler(async (path) => - { - await ScanForDuplicateFiles(path); - }, sourceArg); - } - - private async Task ScanForDuplicateFiles(string path) - { - CommandLine.WriteLine($"Scanning for duplicate files in {path}...", ConsoleColor.DarkGray); - Dictionary duplicates = FileScanner.GetDuplicateFiles(path); - Dictionary result = duplicates.ToDictionary(k => k.Key, v => v.Value.Select(l => l.Fullname).ToArray()); - long length = duplicates.Sum(kv => kv.Value.Sum(l => l.LocalSize)); - - List lines = new List(); - foreach (string key in result.Keys) - { - string[] paths = result[key]; - lines.Add($"{key} ({paths.Length:N0} items):"); - lines.AddRange(paths.Select(value => $" - {value}")); - } - - string fileName = PathBuilder.TempFile; - await File.WriteAllLinesAsync(fileName, lines); - - CommandLine.WriteLine($"Scan found {duplicates.Count(kv => kv.Value.Length > 1):N0} duplicate files. ({Formatter.FromBytes(length)})", ConsoleColor.Green); - CommandLine.WriteLine($"A detailed list can be found here: {fileName}", ConsoleColor.DarkGray); - } - } -} \ No newline at end of file diff --git a/Parallel.Cli/Commands/FetchCommand.cs b/Parallel.Cli/Commands/FetchCommand.cs deleted file mode 100644 index a5a8305..0000000 --- a/Parallel.Cli/Commands/FetchCommand.cs +++ /dev/null @@ -1,46 +0,0 @@ -// Copyright 2026 Entex Interactive - -using System.CommandLine; -using Parallel.Cli.Utils; -using Parallel.Core.IO.Syncing; -using Parallel.Core.Settings; - -namespace Parallel.Cli.Commands -{ - public class FetchCommand : Command - { - private readonly Option _configOpt = new(["--config", "-c"], "The vault configuration to use."); - - public FetchCommand() : base("fetch", "Fetches information from a vault.") - { - this.AddOption(_configOpt); - this.SetHandler(HandleFetchAsync, _configOpt); - } - - private async Task HandleFetchAsync(string config) - { - LocalVaultConfig? localVault = ParallelConfig.GetVault(config); - if (localVault != null) - { - await FetchVaultAsync(localVault); - return; - } - - await Program.Settings.ForEachVaultAsync(FetchVaultAsync); - } - - private async Task FetchVaultAsync(LocalVaultConfig localVault) - { - CommandLine.WriteLine($"Retrieving vault information...", ConsoleColor.DarkGray); - ISyncManager? syncManager = SyncManager.CreateNew(localVault); - if (syncManager == null || !await syncManager.ConnectAsync(true)) - { - CommandLine.WriteLine(localVault, "Failed to connect to vault!", ConsoleColor.Red); - return; - } - - CommandLine.WriteLine(syncManager.LocalVault, $"Successfully fetched vault data for: '{localVault.Name}'", ConsoleColor.Green); - await syncManager.DisconnectAsync(); - } - } -} \ No newline at end of file diff --git a/Parallel.Cli/Commands/HistoryCommand.cs b/Parallel.Cli/Commands/HistoryCommand.cs deleted file mode 100644 index 0a3cfc9..0000000 --- a/Parallel.Cli/Commands/HistoryCommand.cs +++ /dev/null @@ -1,129 +0,0 @@ -// Copyright 2026 Entex Interactive - -using System.CommandLine; -using Parallel.Cli.Utils; -using Parallel.Core.Database; -using Parallel.Core.IO.Syncing; -using Parallel.Core.Models; -using Parallel.Core.Settings; -using Parallel.Core.Utils; - -namespace Parallel.Cli.Commands -{ - public class HistoryCommand : Command - { - private const int _limit = 25; - - private readonly Command _archiveCmd = new("archive", "Shows the history related to file deletions."); - private readonly Command _cleanCmd = new("clean", "Shows the history related to file cleaning."); - private readonly Command _cloneCmd = new("clone", "Shows the history related to file cloning."); - private readonly Command _syncCmd = new("sync", "Shows the history related to file syncing."); - private readonly Command _restoreCmd = new("pull", "Shows the history related to file restoring."); - private readonly Command _pruneCmd = new("prune", "Shows the history related to file pruning."); - - private readonly Option _sourceOpt = new(["--path", "-p"], "The source path to push."); - private readonly Option _configOpt = new(["--config", "-c"], "The vault configuration to use."); - private readonly Option _limitOpt = new(["--limit", "-l"], "The number of entries to show."); - - public HistoryCommand() : base("history", "Displays the history of a vault.") - { - this.AddCommand(_archiveCmd); - this.AddCommand(_cleanCmd); - this.AddCommand(_cloneCmd); - this.AddCommand(_syncCmd); - this.AddCommand(_restoreCmd); - this.AddCommand(_pruneCmd); - this.AddOption(_sourceOpt); - this.AddOption(_configOpt); - this.AddOption(_limitOpt); - this.SetHandler(async (path, config, limit) => - { - await DisplayHistoryAsync(null, path, config, limit); - }, _sourceOpt, _configOpt, _limitOpt); - - _archiveCmd.AddOption(_sourceOpt); - _archiveCmd.AddOption(_configOpt); - _archiveCmd.AddOption(_limitOpt); - _archiveCmd.SetHandler(async (path, config, limit) => - { - await DisplayHistoryAsync(HistoryType.Archived, path, config, limit); - }, _sourceOpt, _configOpt, _limitOpt); - - _cleanCmd.AddOption(_sourceOpt); - _cleanCmd.AddOption(_configOpt); - _cleanCmd.AddOption(_limitOpt); - _cleanCmd.SetHandler(async (path, config, limit) => - { - await DisplayHistoryAsync(HistoryType.Cleaned, path, config, limit); - }, _sourceOpt, _configOpt, _limitOpt); - - _cloneCmd.AddOption(_sourceOpt); - _cloneCmd.AddOption(_configOpt); - _cloneCmd.AddOption(_limitOpt); - _cloneCmd.SetHandler(async (path, config, limit) => - { - await DisplayHistoryAsync(HistoryType.Cloned, path, config, limit); - }, _sourceOpt, _configOpt, _limitOpt); - - _syncCmd.AddOption(_sourceOpt); - _syncCmd.AddOption(_configOpt); - _syncCmd.AddOption(_limitOpt); - _syncCmd.SetHandler(async (path, config, limit) => - { - await DisplayHistoryAsync(HistoryType.Synced, path, config, limit); - }, _sourceOpt, _configOpt, _limitOpt); - - _restoreCmd.AddOption(_sourceOpt); - _restoreCmd.AddOption(_configOpt); - _restoreCmd.AddOption(_limitOpt); - _restoreCmd.SetHandler(async (path, config, limit) => - { - await DisplayHistoryAsync(HistoryType.Restored, path, config, limit); - }, _sourceOpt, _configOpt, _limitOpt); - - _pruneCmd.AddOption(_sourceOpt); - _pruneCmd.AddOption(_configOpt); - _pruneCmd.AddOption(_limitOpt); - _pruneCmd.SetHandler(async (path, config, limit) => - { - await DisplayHistoryAsync(HistoryType.Pruned, path, config, limit); - }, _sourceOpt, _configOpt, _limitOpt); - } - - private async Task DisplayHistoryAsync(HistoryType? type, string path, string config, int limit) - { - if (limit == 0) limit = _limit; - LocalVaultConfig? vault = ParallelConfig.Load().Vaults.FirstOrDefault(v => v.Enabled); - if (!string.IsNullOrEmpty(config)) vault = ParallelConfig.GetVault(config); - if (vault == null) - { - CommandLine.WriteLine($"No vault was found!", ConsoleColor.Yellow); - return; - } - - ISyncManager? syncManager = SyncManager.CreateNew(vault); - if (syncManager == null || !await syncManager.ConnectAsync()) - { - CommandLine.WriteLine(vault, $"Failed to connect to vault!", ConsoleColor.Red); - return; - } - - Task>? historyTask = type == null ? syncManager.Database?.GetHistoryAsync(path) : syncManager.Database?.GetHistoryAsync(path, type); - IReadOnlyList historyList = await (historyTask ?? Task.FromResult>([])); - if (!historyList.Any()) CommandLine.WriteLine("No history was found!", ConsoleColor.Yellow); - - int display = Math.Min(limit, historyList.Count); - for (int i = 0; i < display; i++) - { - HistoryEvent historyEvent = historyList[i]; - CommandLine.WriteLine($"[{Formatter.FromDateTime(historyEvent.CreatedAt.ToLocalTime())}] {historyEvent.Type}: {historyEvent.Fullname}"); - } - - int remaining = historyList.Count - display; - if (remaining > 0) - { - CommandLine.WriteLine($"{remaining:N0} entr{(remaining == 1 ? "y" : "ies")} remaining...", ConsoleColor.DarkGray); - } - } - } -} \ No newline at end of file diff --git a/Parallel.Cli/Commands/IgnoreCommand.cs b/Parallel.Cli/Commands/IgnoreCommand.cs deleted file mode 100644 index 7c9a1b1..0000000 --- a/Parallel.Cli/Commands/IgnoreCommand.cs +++ /dev/null @@ -1,96 +0,0 @@ -// Copyright 2026 Entex Interactive - -using System.CommandLine; -using Parallel.Cli.Utils; -using Parallel.Core.IO.Syncing; -using Parallel.Core.Settings; - -namespace Parallel.Cli.Commands -{ - public class IgnoreCommand : Command - { - private readonly Argument _sourceArg = new("path", "The path to add or remove."); - private readonly Option _configOpt = new(["--config", "-c"], "The vault configuration to use."); - - private readonly Command addCmd = new("add", "Adds a new directory to the backup list."); - private readonly Command listCmd = new("list", "Shows all directories in the backup list."); - private readonly Command removeCmd = new("remove", "Removes a directory from the backup list."); - - public IgnoreCommand() : base("ignore", "Ignores files and folders") - { - this.AddCommand(addCmd); - addCmd.AddArgument(_sourceArg); - addCmd.AddOption(_configOpt); - addCmd.SetHandler(HandleAddAsync, _sourceArg, _configOpt); - - this.AddCommand(removeCmd); - removeCmd.AddArgument(_sourceArg); - removeCmd.AddOption(_configOpt); - removeCmd.SetHandler(HandleRemoveAsync, _sourceArg, _configOpt); - } - - private async Task HandleAddAsync(string path, string? config) - { - LocalVaultConfig? localVault = string.IsNullOrEmpty(config) ? ParallelConfig.Load().Vaults.FirstOrDefault(v => v.Enabled) : ParallelConfig.GetVault(config); - if (!string.IsNullOrEmpty(config) && localVault != null) - { - await AddPathAsync(localVault, path); - } - else - { - await Program.Settings.ForEachVaultAsync(vault => AddPathAsync(vault, path)); - } - } - - private async Task AddPathAsync(LocalVaultConfig vault, string path) - { - ISyncManager? syncManager = SyncManager.CreateNew(vault); - if (syncManager == null || !await syncManager.ConnectAsync()) - { - CommandLine.WriteLine(vault, "Failed to connect to vault!", ConsoleColor.Red); - return; - } - - if (!syncManager.RemoteVault.IgnoreDirectories.Add(path)) - { - CommandLine.WriteLine(vault, $"Unable to add path: '{path}'", ConsoleColor.Yellow); - return; - } - - CommandLine.WriteLine(vault, $"Successfully ignored '{path}'", ConsoleColor.Green); - await syncManager.DisconnectAsync(); - } - - private async Task HandleRemoveAsync(string path, string? config) - { - LocalVaultConfig? localVault = string.IsNullOrEmpty(config) ? ParallelConfig.Load().Vaults.FirstOrDefault(v => v.Enabled) : ParallelConfig.GetVault(config); - if (!string.IsNullOrEmpty(config) && localVault != null) - { - await RemovePathAsync(localVault, path); - } - else - { - await Program.Settings.ForEachVaultAsync(vault => RemovePathAsync(vault, path)); - } - } - - private async Task RemovePathAsync(LocalVaultConfig vault, string path) - { - ISyncManager? syncManager = SyncManager.CreateNew(vault); - if (syncManager == null || !await syncManager.ConnectAsync()) - { - CommandLine.WriteLine(vault, "Failed to connect to vault!", ConsoleColor.Red); - return; - } - - if (!syncManager.RemoteVault.IgnoreDirectories.Remove(path)) - { - CommandLine.WriteLine(vault, $"Unable to remove path: '{path}'", ConsoleColor.Yellow); - return; - } - - CommandLine.WriteLine(vault, $"Successfully included '{path}'", ConsoleColor.Green); - await syncManager.DisconnectAsync(); - } - } -} \ No newline at end of file diff --git a/Parallel.Cli/Commands/ListCommands.cs b/Parallel.Cli/Commands/ListCommands.cs new file mode 100644 index 0000000..f48b493 --- /dev/null +++ b/Parallel.Cli/Commands/ListCommands.cs @@ -0,0 +1,187 @@ +// Copyright 2026 Entex Interactive + +using System.ComponentModel; +using Parallel.Core.Config; +using Parallel.Cli.Infrastructure; +using Parallel.Core.Engine; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace Parallel.Cli.Commands +{ + public class ListEditSettings : VaultSettings + { + [CommandArgument(0, "")] + public string Value { get; init; } = string.Empty; + } + + public sealed class ListShowSettings : VaultSettings + { + } + + public sealed class IgnoreEditSettings : ListEditSettings + { + [CommandOption("-g|--global")] + [Description("Change the global ignore rules, which apply to every vault (and to the desktop app's duplicates and cleaner).")] + public bool Global { get; init; } + } + + /// Shared logic for editing a per-vault list (sources, excludes). + public abstract class ListCommandBase(AppConfig config) + { + protected AppConfig Config { get; } = config; + + protected abstract string Noun { get; } + + protected abstract List Items(VaultConfig vault); + + protected virtual string Normalize(string value) => value; + + protected int Add(VaultSettings s, string value) + { + string normalized = Normalize(value); + foreach (VaultConfig vault in VaultAccess.Select(Config, s.Vault)) + { + List items = Items(vault); + if (items.Contains(normalized, PathMap.Comparer)) + { + AnsiConsole.MarkupLine($"[grey]{Markup.Escape(vault.Name)}: already has {Markup.Escape(normalized)}[/]"); + continue; + } + + items.Add(normalized); + AnsiConsole.MarkupLine($"{Markup.Escape(vault.Name)}: added {Noun} [bold]{Markup.Escape(normalized)}[/]"); + } + + Config.Save(); + return 0; + } + + protected int Remove(VaultSettings s, string value) + { + string normalized = Normalize(value); + bool any = false; + foreach (VaultConfig vault in VaultAccess.Select(Config, s.Vault)) + { + int removed = Items(vault).RemoveAll(i => i.Equals(normalized, PathMap.Comparison) || i.Equals(value, PathMap.Comparison)); + if (removed > 0) + { + any = true; + AnsiConsole.MarkupLine($"{Markup.Escape(vault.Name)}: removed {Noun} {Markup.Escape(normalized)}"); + } + } + + if (!any) throw new CliException($"'{value}' is not in the {Noun} list."); + Config.Save(); + return 0; + } + + protected int Show(VaultSettings s) + { + foreach (VaultConfig vault in VaultAccess.Select(Config, s.Vault)) + { + AnsiConsole.MarkupLine($"[bold]{Markup.Escape(vault.Name)}[/]"); + List items = Items(vault); + if (items.Count == 0) AnsiConsole.MarkupLine(" [grey](none)[/]"); + foreach (string item in items) AnsiConsole.MarkupLine($" {Markup.Escape(item)}"); + } + + return 0; + } + } + + public sealed class SourcesLogic(AppConfig config) : ListCommandBase(config) + { + protected override string Noun => "source"; + + protected override List Items(VaultConfig vault) => vault.Sources; + + protected override string Normalize(string value) + { + string full = PathMap.Normalize(value); + if (!Directory.Exists(full) && !File.Exists(full)) throw new CliException($"Path not found: {full}"); + return full; + } + + public int DoAdd(VaultSettings s, string v) => Add(s, v); + public int DoRemove(VaultSettings s, string v) => Remove(s, v); + public int DoShow(VaultSettings s) => Show(s); + } + + public sealed class ExcludesLogic(AppConfig config) : ListCommandBase(config) + { + protected override string Noun => "exclude pattern"; + + protected override List Items(VaultConfig vault) => vault.Excludes; + + public int DoAdd(IgnoreEditSettings s, string v) + { + if (!s.Global) return Add(s, v); + if (Config.Ignore.Contains(v, PathMap.Comparer)) + { + AnsiConsole.MarkupLine($"[grey]Global ignore rules already have {Markup.Escape(v)}[/]"); + return 0; + } + + Config.Ignore.Add(v); + Config.Save(); + AnsiConsole.MarkupLine($"Added global ignore rule [bold]{Markup.Escape(v)}[/]"); + return 0; + } + + public int DoRemove(IgnoreEditSettings s, string v) + { + if (!s.Global) return Remove(s, v); + if (Config.Ignore.RemoveAll(i => i.Equals(v, PathMap.Comparison)) == 0) throw new CliException($"'{v}' is not a global ignore rule."); + Config.Save(); + AnsiConsole.MarkupLine($"Removed global ignore rule {Markup.Escape(v)}"); + return 0; + } + + public int DoShow(VaultSettings s) + { + AnsiConsole.MarkupLine("[bold]Global[/] [grey](every vault)[/]"); + if (Config.Ignore.Count == 0) AnsiConsole.MarkupLine(" [grey](none)[/]"); + foreach (string item in Config.Ignore) AnsiConsole.MarkupLine($" {Markup.Escape(item)}"); + Show(s); + AnsiConsole.MarkupLine($"[grey]Always excluded on this system: {Markup.Escape(string.Join(" ", Excludes.Defaults))}[/]"); + return 0; + } + } + + [Description("Adds a file or folder to back up.")] + public sealed class SourcesAddCommand(SourcesLogic logic) : Command + { + public override int Execute(CommandContext c, ListEditSettings s, CancellationToken ct) => logic.DoAdd(s, s.Value); + } + + [Description("Stops backing up a file or folder. Existing snapshots keep it.")] + public sealed class SourcesRemoveCommand(SourcesLogic logic) : Command + { + public override int Execute(CommandContext c, ListEditSettings s, CancellationToken ct) => logic.DoRemove(s, s.Value); + } + + [Description("Shows what is backed up.")] + public sealed class SourcesListCommand(SourcesLogic logic) : Command + { + public override int Execute(CommandContext c, ListShowSettings s, CancellationToken ct) => logic.DoShow(s); + } + + [Description("Adds an exclude pattern: 'name/' (folders), '*.tmp' (names), or an absolute path ('**' spans folders). --global applies it to every vault.")] + public sealed class IgnoreAddCommand(ExcludesLogic logic) : Command + { + public override int Execute(CommandContext c, IgnoreEditSettings s, CancellationToken ct) => logic.DoAdd(s, s.Value); + } + + [Description("Removes an exclude pattern.")] + public sealed class IgnoreRemoveCommand(ExcludesLogic logic) : Command + { + public override int Execute(CommandContext c, IgnoreEditSettings s, CancellationToken ct) => logic.DoRemove(s, s.Value); + } + + [Description("Shows exclude patterns.")] + public sealed class IgnoreListCommand(ExcludesLogic logic) : Command + { + public override int Execute(CommandContext c, ListShowSettings s, CancellationToken ct) => logic.DoShow(s); + } +} diff --git a/Parallel.Cli/Commands/MaintenanceCommands.cs b/Parallel.Cli/Commands/MaintenanceCommands.cs new file mode 100644 index 0000000..13dc3c3 --- /dev/null +++ b/Parallel.Cli/Commands/MaintenanceCommands.cs @@ -0,0 +1,199 @@ +// Copyright 2026 Entex Interactive + +using System.ComponentModel; +using System.Security.Cryptography; +using Parallel.Core.Config; +using Parallel.Cli.Infrastructure; +using Parallel.Core.Engine; +using Parallel.Core.Model; +using Parallel.Core.Repository; +using Spectre.Console; +using Spectre.Console.Cli; +using Tree = Parallel.Core.Model.Tree; + +namespace Parallel.Cli.Commands +{ + public sealed class PruneSettings : VaultSettings + { + [CommandOption("--dry-run")] + [Description("Only show what would be removed.")] + public bool DryRun { get; init; } + } + + [Description("Frees space by deleting data that no snapshot uses. Never touches data a snapshot still needs.")] + public sealed class PruneCommand(AppConfig config) : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, PruneSettings s, CancellationToken ct) + { + foreach (VaultConfig vault in VaultAccess.Select(config, s.Vault)) + { + AnsiConsole.MarkupLine($"[bold]{Markup.Escape(vault.Name)}[/]"); + await using Repository repo = await VaultAccess.OpenAsync(vault, s.PasswordFile, ct); + await RunAsync(repo, s.DryRun, ct); + } + + return 0; + } + + public static async Task RunAsync(Repository repo, bool dryRun, CancellationToken ct) + { + ConsoleProgress progress = new(false); + PruneResult r = await progress.RunAsync(dryRun ? "Planning prune" : "Pruning", () => new PruneEngine(repo, new PruneOptions { DryRun = dryRun, Progress = progress }).RunAsync(ct)); + string verb = dryRun ? "Would free" : "Freed"; + AnsiConsole.MarkupLine($"{r.Snapshots:N0} snapshot(s) use {r.UsedBlobs:N0} blobs. {verb} {Format.Bytes(r.BytesFreed)}: " + + $"{r.PacksDeleted:N0} unused packs, {r.PacksRepacked:N0} repacked ({Format.Bytes(r.BytesRepacked)} copied), {r.OrphanPacks:N0} left by interrupted backups."); + } + } + + public sealed class CheckSettings : VaultSettings + { + [CommandOption("--read-data")] + [Description("Download and verify all stored data, not only the structure.")] + public bool ReadData { get; init; } + + [CommandOption("--subset ")] + [Description("With --read-data: verify a random percentage of the data (for example 10).")] + public double? Subset { get; init; } + } + + [Description("Verifies the vault. Reports problems; never changes anything.")] + public sealed class CheckCommand(AppConfig config) : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, CheckSettings s, CancellationToken ct) + { + int exit = 0; + foreach (VaultConfig vault in VaultAccess.Select(config, s.Vault)) + { + AnsiConsole.MarkupLine($"[bold]{Markup.Escape(vault.Name)}[/]"); + await using Repository repo = await VaultAccess.OpenAsync(vault, s.PasswordFile, ct); + ConsoleProgress progress = new(false); + CheckOptions options = new() { ReadData = s.ReadData || s.Subset != null, SubsetPercent = s.Subset ?? 100, Progress = progress }; + CheckResult r = await progress.RunAsync("Checking", () => new CheckEngine(repo, options).RunAsync(ct)); + + string read = options.ReadData ? $", read and verified {r.PacksRead:N0} packs" : " (structure only; add --read-data to verify the data itself)"; + AnsiConsole.MarkupLine($"{r.Snapshots:N0} snapshots, {r.Trees:N0} folder listings, {r.DataBlobs:N0} data chunks, {r.Packs:N0} packs{read}."); + if (r.Ok) + { + AnsiConsole.MarkupLine("[green]No problems found.[/]"); + } + else + { + AnsiConsole.MarkupLine($"[red]{r.Errors.Count:N0} problem(s) found.[/] Snapshots that use the damaged data cannot be fully restored. Nothing was changed; keep a second vault for anything you cannot lose."); + exit = 3; + } + } + + return exit; + } + } + + public sealed class HistorySettings : VaultSettings + { + [CommandArgument(0, "")] + [Description("The file's path as it was on the machine that backed it up, e.g. C:\\Users\\me\\notes.txt or /home/me/notes.txt.")] + public string File { get; init; } = string.Empty; + + [CommandOption("--host ")] + [Description("Only snapshots of this machine (default: all machines).")] + public string? Host { get; init; } + } + + [Description("Shows every stored version of a file or folder: when it changed, was deleted or was freed up.")] + public sealed class HistoryCommand(AppConfig config) : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, HistorySettings s, CancellationToken ct) + { + VaultConfig vault = VaultAccess.SelectOne(config, s.Vault); + await using Repository repo = await VaultAccess.OpenAsync(vault, s.PasswordFile, ct); + + FileHistoryResult history = await FileHistory.GetVersionsAsync(repo, s.File, s.Host, ct); + foreach (string warning in history.Warnings) AnsiConsole.MarkupLineInterpolated($"[yellow]{warning}[/]"); + if (history.Versions.Count == 0) throw new CliException($"'{s.File}' is not in any snapshot."); + + Grid table = Grids.Create(">Version", "What", "Modified", ">Size", "From", "Until", "Snapshot", "Restore points"); + foreach (FileVersion v in history.Versions) + { + string modified = v.Node == null ? "" : new DateTime(v.Node.ModifiedTicks, DateTimeKind.Utc).ToLocalTime().ToString("yyyy-MM-dd HH:mm"); + string size = v.Node is { Type: NodeType.File } ? Format.Bytes(v.Node.Size) : ""; + table.AddRow(v.Number.ToString(), v.Kind.ToString(), modified, size, + v.FirstSeen.ToLocalTime().ToString("yyyy-MM-dd HH:mm"), v.LastSeen.ToLocalTime().ToString("yyyy-MM-dd HH:mm"), + v.SnapshotId[..8], string.Join(", ", v.RestorePoints)); + } + + AnsiConsole.Write(table); + AnsiConsole.MarkupLine("[grey]Restore a version with: parallel restore --path \"\" [[--target ]][/]"); + return 0; + } + } + + public sealed class DuplicatesSettings : CommandSettings + { + [CommandArgument(0, "")] + public string Folder { get; init; } = string.Empty; + } + + [Description("Finds files with identical content in a folder (read-only).")] + public sealed class DuplicatesCommand : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, DuplicatesSettings s, CancellationToken ct) + { + string root = Path.GetFullPath(s.Folder); + if (!Directory.Exists(root)) throw new CliException($"Folder not found: {root}"); + + EnumerationOptions options = new() { RecurseSubdirectories = true, IgnoreInaccessible = true, AttributesToSkip = FileAttributes.ReparsePoint }; + List> sameSize = new DirectoryInfo(root).EnumerateFiles("*", options).Where(f => f.Length > 0).GroupBy(f => f.Length).Where(g => g.Count() > 1).ToList(); + + List<(string Hash, List Files)> groups = new(); + await AnsiConsole.Status().StartAsync("Hashing candidates...", async _ => + { + foreach (IGrouping group in sameSize) + { + Dictionary> byHash = new(); + foreach (FileInfo file in group) + { + try + { + await using FileStream stream = file.OpenRead(); + string hash = Convert.ToHexStringLower(await SHA256.HashDataAsync(stream, ct)); + if (!byHash.TryGetValue(hash, out List? list)) byHash[hash] = list = new(); + list.Add(file); + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + // Skip unreadable files. + } + } + + groups.AddRange(byHash.Where(kv => kv.Value.Count > 1).Select(kv => (kv.Key, kv.Value))); + } + }); + + long wasted = 0; + foreach ((string _, List files) in groups.OrderByDescending(g => g.Files[0].Length * (g.Files.Count - 1))) + { + wasted += files[0].Length * (files.Count - 1); + AnsiConsole.MarkupLine($"[bold]{Format.Bytes(files[0].Length)}[/] x {files.Count}"); + foreach (FileInfo f in files) AnsiConsole.MarkupLine($" {Markup.Escape(f.FullName)}"); + } + + AnsiConsole.MarkupLine($"{groups.Count:N0} sets of duplicates, {Format.Bytes(wasted)} could be reclaimed. Nothing was changed."); + return 0; + } + } + + [Description("Removes lock files left behind by crashed processes.")] + public sealed class UnlockCommand(AppConfig config) : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, VaultSettings s, CancellationToken ct) + { + foreach (VaultConfig vault in VaultAccess.Select(config, s.Vault)) + { + await using Repository repo = await VaultAccess.OpenAsync(vault, s.PasswordFile, ct); + int removed = await VaultLock.RemoveStaleAsync(repo, ct); + AnsiConsole.MarkupLine($"{Markup.Escape(vault.Name)}: removed {removed} stale lock(s)."); + } + + return 0; + } + } +} diff --git a/Parallel.Cli/Commands/PruneCommand.cs b/Parallel.Cli/Commands/PruneCommand.cs deleted file mode 100644 index e328c21..0000000 --- a/Parallel.Cli/Commands/PruneCommand.cs +++ /dev/null @@ -1,245 +0,0 @@ -// Copyright 2026 Entex Interactive - -using System.CommandLine; -using System.Diagnostics; -using Parallel.Cli.Utils; -using Parallel.Core.IO; -using Parallel.Core.IO.Syncing; -using Parallel.Core.Models; -using Parallel.Core.Settings; -using Parallel.Core.Utils; - -namespace Parallel.Cli.Commands -{ - public class PruneCommand : Command - { - private Stopwatch _sw = new Stopwatch(); - - private readonly Argument _sourceArg = new("path", "The path to add or remove."); - private readonly Option _sourceOpt = new(["--path", "-p"], "The source path to prune."); - private readonly Option _configOpt = new(["--config", "-c"], "The vault configuration to use."); - private readonly Option _beforeOpt = new(["--before"], "Specified timestamp as the pruning reference point."); - private readonly Option _daysOpt = new(["--days", "-d"], "Specified number of days before the reference point."); - private readonly Option _forceOpt = new(["--force", "-f"], "Forces pruning, bypassing safe guards."); - private readonly Option _dryRunOpt = new(["--dry-run"], "Previews the command without executing it."); - private readonly Option _verboseOpt = new(["--verbose", "-v"], "Shows verbose output."); - - private readonly Command addCmd = new("add", "Adds a new path to the prune list."); - private readonly Command listCmd = new("list", "Shows all directories in the prune list."); - private readonly Command removeCmd = new("remove", "Removes a directory from the prune list."); - - public PruneCommand() : base("prune", "Prunes the oldest files from vaults.") - { - this.AddOption(_sourceOpt); - this.AddOption(_configOpt); - this.AddOption(_beforeOpt); - this.AddOption(_daysOpt); - this.AddOption(_forceOpt); - this.AddOption(_dryRunOpt); - this.SetHandler(HandlePruneAsync, _sourceOpt, _configOpt, _beforeOpt, _daysOpt, _forceOpt, _dryRunOpt); - - this.AddCommand(addCmd); - addCmd.AddArgument(_sourceArg); - addCmd.AddOption(_configOpt); - addCmd.SetHandler(HandleAddAsync, _sourceArg, _configOpt); - - this.AddCommand(removeCmd); - removeCmd.AddArgument(_sourceArg); - removeCmd.AddOption(_configOpt); - removeCmd.SetHandler(HandleRemoveAsync, _sourceArg, _configOpt); - } - - #region Pruning - - private async Task HandlePruneAsync(string? path, string? config, DateTime before, int days, bool force, bool dryRun) - { - _sw = Stopwatch.StartNew(); - LocalVaultConfig? localVault = ParallelConfig.GetVault(config); - if (localVault != null) - { - if (!string.IsNullOrEmpty(path)) - { - await PrunePathAsync(localVault, path, before, days, force, dryRun); - } - else - { - await PruneSystemAsync(localVault, before, days, force, dryRun); - } - } - else - { - if (!string.IsNullOrEmpty(path)) - { - await Program.Settings.ForEachVaultAsync(vault => PrunePathAsync(vault, path, before, days, force, dryRun)); - } - else - { - await Program.Settings.ForEachVaultAsync(vault => PruneSystemAsync(vault, before, days, force, dryRun)); - } - } - } - - private DateTime GetPruneDateTime(int prunePeriod, DateTime before, int days) - { - DateTime timestamp = before > DateTime.MinValue ? before : DateTime.Now; - return days > 0 ? timestamp.AddDays(-days) : timestamp.AddDays(-prunePeriod); - } - - private async Task PruneSystemAsync(LocalVaultConfig vault, DateTime before, int days, bool force, bool dryRun) - { - ISyncManager? syncManager = SyncManager.CreateNew(vault); - if (syncManager == null || !await syncManager.ConnectAsync()) - { - CommandLine.WriteLine(vault, "Failed to connect to vault!", ConsoleColor.Red); - return; - } - - DateTime timestamp = GetPruneDateTime(syncManager.RemoteVault.PrunePeriod, before, days); - HashSet directories = syncManager.RemoteVault.PruneDirectories; - if (directories.Count == 0) - { - CommandLine.WriteLine($"No prunable directories have been set!", ConsoleColor.Yellow); - return; - } - - foreach (string path in directories) - { - await PruneInternalAsync(syncManager, path, timestamp, force, dryRun); - } - } - - private async Task PrunePathAsync(LocalVaultConfig vault, string path, DateTime before, int days, bool force, bool dryRun) - { - ISyncManager? syncManager = SyncManager.CreateNew(vault); - if (syncManager == null || !await syncManager.ConnectAsync()) - { - CommandLine.WriteLine(vault, "Failed to connect to vault!", ConsoleColor.Red); - return; - } - - DateTime timestamp = GetPruneDateTime(syncManager.RemoteVault.PrunePeriod, before, days); - Log.Debug($"Pruning files before {timestamp}"); - - await PruneInternalAsync(syncManager, path, timestamp, force, dryRun); - } - - private async Task PruneInternalAsync(ISyncManager syncManager, string path, DateTime timestamp, bool force, bool dryRun) - { - CommandLine.WriteLine(syncManager.RemoteVault, $"Scanning for files in {path}...", ConsoleColor.DarkGray); - IReadOnlyList files; - if (force) - { - files = await (syncManager.Database?.GetFilesAsync(path, timestamp) ?? Task.FromResult>([])); - } - else - { - files = await (syncManager.Database?.GetFilesAsync(path, timestamp, true) ?? Task.FromResult>([])); - } - - if (files.Count == 0) - { - CommandLine.WriteLine($"No prunable files were found!", ConsoleColor.Yellow); - return; - } - - if (!force && !dryRun) - { - CommandLine.WriteLine($"This will permanently delete {files.Count:N0} files!", ConsoleColor.Yellow); - if (!CommandLine.ReadBool("Do you wish to continue? [yes/no]", false)) - { - CommandLine.WriteLine($"Successfully cancelled operation.", ConsoleColor.Green); - return; - } - } - - if (dryRun) - { - string fileName = PathBuilder.TempFile; - await File.WriteAllLinesAsync(fileName, files.Select(f => f.Fullname).OrderBy(f => f)); - CommandLine.WriteLine($"This operation will prune {files.Count:N0} files ({Formatter.FromBytes(files.Sum(f => f.LocalSize))})", ConsoleColor.Green); - CommandLine.WriteLine($"A detailed list can be found here: {fileName}", ConsoleColor.DarkGray); - } - else - { - CommandLine.WriteLine(syncManager.RemoteVault, $"Pruning {files.Count:N0} files...", ConsoleColor.DarkGray); - int prunedFiles = await syncManager.PruneFilesAsync(files, new ProgressReporter(syncManager.RemoteVault, files.Count)); - CommandLine.WriteLine(syncManager.RemoteVault, $"Successfully pruned {prunedFiles:N0} files in {_sw.Elapsed}.", ConsoleColor.Green); - await syncManager.DisconnectAsync(); - } - } - - #endregion - - #region Add - - private async Task HandleAddAsync(string path, string? config) - { - LocalVaultConfig? localVault = string.IsNullOrEmpty(config) ? ParallelConfig.Load().Vaults.FirstOrDefault(v => v.Enabled) : ParallelConfig.GetVault(config); - if (!string.IsNullOrEmpty(config) && localVault != null) - { - await AddPathAsync(localVault, path); - } - else - { - await Program.Settings.ForEachVaultAsync(vault => AddPathAsync(vault, path)); - } - } - - private async Task AddPathAsync(LocalVaultConfig vault, string path) - { - ISyncManager? syncManager = SyncManager.CreateNew(vault); - if (syncManager == null || !await syncManager.ConnectAsync()) - { - CommandLine.WriteLine(vault, "Failed to connect to vault!", ConsoleColor.Red); - return; - } - - if (!syncManager.RemoteVault.PruneDirectories.Add(path)) - { - CommandLine.WriteLine(vault, $"Unable to add path: '{path}'", ConsoleColor.Yellow); - return; - } - - CommandLine.WriteLine(vault, $"Successfully added '{path}'", ConsoleColor.Green); - await syncManager.DisconnectAsync(); - } - - #endregion - - #region Remove - - private async Task HandleRemoveAsync(string path, string? config) - { - LocalVaultConfig? localVault = string.IsNullOrEmpty(config) ? ParallelConfig.Load().Vaults.FirstOrDefault(v => v.Enabled) : ParallelConfig.GetVault(config); - if (!string.IsNullOrEmpty(config) && localVault != null) - { - await RemovePathAsync(localVault, path); - } - else - { - await Program.Settings.ForEachVaultAsync(vault => RemovePathAsync(vault, path)); - } - } - - private async Task RemovePathAsync(LocalVaultConfig vault, string path) - { - ISyncManager? syncManager = SyncManager.CreateNew(vault); - if (syncManager == null || !await syncManager.ConnectAsync()) - { - CommandLine.WriteLine(vault, "Failed to connect to vault!", ConsoleColor.Red); - return; - } - - if (!syncManager.RemoteVault.PruneDirectories.Remove(path)) - { - CommandLine.WriteLine(vault, $"Unable to remove path: '{path}'", ConsoleColor.Yellow); - return; - } - - CommandLine.WriteLine(vault, $"Successfully removed '{path}'", ConsoleColor.Green); - await syncManager.DisconnectAsync(); - } - - #endregion - } -} \ No newline at end of file diff --git a/Parallel.Cli/Commands/RecoveryCommand.cs b/Parallel.Cli/Commands/RecoveryCommand.cs new file mode 100644 index 0000000..46aa85a --- /dev/null +++ b/Parallel.Cli/Commands/RecoveryCommand.cs @@ -0,0 +1,43 @@ +// Copyright 2026 Entex Interactive + +using System.ComponentModel; +using Parallel.Core.Config; +using Parallel.Cli.Infrastructure; +using Parallel.Core.Repository; +using Spectre.Console; +using Spectre.Console.Cli; + +namespace Parallel.Cli.Commands +{ + public sealed class RecoverySettings : VaultNameSettings + { + [CommandOption("--out ")] + [Description("Also write the sheet to this file (then print it and store it away from this computer).")] + public string? Out { get; init; } + } + + /// + /// Prints what is needed to restore after this machine is lost: where the vault is, how to log in to it, and the passphrase. + /// Everything it shows is otherwise only saved on this machine. + /// + [Description("Prints a recovery sheet: everything needed to restore this vault's backups on a new machine.")] + public sealed class RecoveryCommand(AppConfig config) : AsyncCommand + { + public override async Task ExecuteAsync(CommandContext context, RecoverySettings s, CancellationToken ct) + { + VaultConfig vault = config.Find(s.Name) ?? throw new CliException($"No vault named '{s.Name}'. See 'parallel vaults list'."); + + string sheet = await RecoverySheet.BuildAsync(vault, ct); + AnsiConsole.WriteLine(sheet); + if (s.Out != null) + { + string path = System.IO.Path.GetFullPath(s.Out); + await File.WriteAllTextAsync(path, sheet, ct); + if (!OperatingSystem.IsWindows()) File.SetUnixFileMode(path, UnixFileMode.UserRead | UnixFileMode.UserWrite); + AnsiConsole.MarkupLine($"[yellow]Written to {Markup.Escape(path)}. It contains secrets: print it or move it off this computer, then delete it.[/]"); + } + + return 0; + } + } +} diff --git a/Parallel.Cli/Commands/RestoreCommand.cs b/Parallel.Cli/Commands/RestoreCommand.cs index e481121..a928006 100644 --- a/Parallel.Cli/Commands/RestoreCommand.cs +++ b/Parallel.Cli/Commands/RestoreCommand.cs @@ -1,147 +1,226 @@ -// Copyright 2026 Entex Interactive - -using System.Collections.Concurrent; -using System.CommandLine; -using System.Diagnostics; -using Newtonsoft.Json.Linq; -using Parallel.Cli.Utils; -using Parallel.Core.Diagnostics; -using Parallel.Core.IO; -using Parallel.Core.IO.Scanning; -using Parallel.Core.IO.Syncing; -using Parallel.Core.Models; -using Parallel.Core.Settings; -using Parallel.Core.Utils; +// Copyright 2026 Entex Interactive + +using System.ComponentModel; +using Parallel.Core.Config; +using Parallel.Cli.Infrastructure; +using Parallel.Core.Engine; +using Parallel.Core.Model; +using Parallel.Core.Repository; +using Spectre.Console; +using Spectre.Console.Cli; namespace Parallel.Cli.Commands { - public class RestoreCommand : Command + public class SnapshotPickSettings : VaultSettings { - private Stopwatch _sw = new Stopwatch(); - - private readonly Argument _sourceArg = new("path", "The path to add or remove."); - private readonly Option _sourceOpt = new(["--path", "-p"], "The source path to pull."); - private readonly Option _configOpt = new(["--config", "-c"], "The vault configuration to use."); - private readonly Option _beforeOpt = new(["--before"], "Pulls files before a certain timestamp."); - private readonly Option _destOpt = new(["--destination"], "The new directory to map pulled files to."); - private readonly Option _archiveOpt = new(["--archive", "-a"], "Pulls only archived files."); - private readonly Option _forceOpt = new(["--force", "-f"], "Forces pulling, bypassing safe guards."); - private readonly Option _dryRunOpt = new(["--dry-run"], "Previews the command without executing it."); - private readonly Option _verboseOpt = new(["--verbose", "-v"], "Shows verbose output."); - - private readonly Command addCmd = new("add", "Adds a new directory to the backup list."); - private readonly Command listCmd = new("list", "Shows all directories in the backup list."); - private readonly Command removeCmd = new("remove", "Removes a directory from the backup list."); - - public RestoreCommand() : base("restore", "Pulls files a vault.") - { - this.AddOption(_sourceOpt); - this.AddOption(_configOpt); - this.AddOption(_beforeOpt); - this.AddOption(_destOpt); - this.AddOption(_archiveOpt); - this.AddOption(_forceOpt); - this.AddOption(_dryRunOpt); - this.AddOption(_verboseOpt); - this.SetHandler(HandlePullAsync, _sourceOpt, _configOpt, _beforeOpt, _destOpt, _archiveOpt, _forceOpt, _verboseOpt, _dryRunOpt); - } + [CommandArgument(0, "[SNAPSHOT]")] + [Description("Snapshot ID (or prefix). Default: the latest snapshot of this machine.")] + public string? Snapshot { get; init; } + + [CommandOption("--at|--before