From 69143fa84be070593e9f194b67de1bfc4c3b7ea9 Mon Sep 17 00:00:00 2001 From: Kyle Ebbinga <26614720+TheGuitarleader@users.noreply.github.com> Date: Mon, 30 Nov 2026 19:55:08 -0600 Subject: [PATCH 1/3] Rework of application --- .github/dependabot.yml | 2 +- .github/workflows/dotnet-build.yml | 3 + .github/workflows/dotnet-release.yml | 9 +- Parallel.Cli/Commands/BackupCommand.cs | 113 +++ Parallel.Cli/Commands/CleanCommand.cs | 125 --- Parallel.Cli/Commands/DuplicatesCommand.cs | 47 -- Parallel.Cli/Commands/FetchCommand.cs | 46 - Parallel.Cli/Commands/HistoryCommand.cs | 129 --- Parallel.Cli/Commands/IgnoreCommand.cs | 96 --- Parallel.Cli/Commands/ListCommands.cs | 187 ++++ Parallel.Cli/Commands/MaintenanceCommands.cs | 199 +++++ Parallel.Cli/Commands/PruneCommand.cs | 245 ------ Parallel.Cli/Commands/RecoveryCommand.cs | 43 + Parallel.Cli/Commands/RestoreCommand.cs | 305 ++++--- Parallel.Cli/Commands/ScrubCommand.cs | 112 --- Parallel.Cli/Commands/SnapshotCommands.cs | 192 +++++ Parallel.Cli/Commands/SnapshotsCommand.cs | 158 ---- Parallel.Cli/Commands/StatsCommand.cs | 167 ++++ Parallel.Cli/Commands/SyncCommand.cs | 231 ----- Parallel.Cli/Commands/UnzipCommand.cs | 75 -- Parallel.Cli/Commands/VaultCommands.cs | 291 +++++++ Parallel.Cli/Commands/VaultsCommand.cs | 183 ---- Parallel.Cli/Commands/VersionCommands.cs | 215 +++++ Parallel.Cli/Commands/ZipCommand.cs | 66 -- .../Infrastructure/ConsoleProgress.cs | 243 ++++++ Parallel.Cli/Infrastructure/Grids.cs | 43 + Parallel.Cli/Infrastructure/TypeRegistrar.cs | 38 + Parallel.Cli/Infrastructure/VaultAccess.cs | 64 ++ Parallel.Cli/Parallel.Cli.csproj | 25 +- Parallel.Cli/Program.cs | 173 +++- Parallel.Cli/Services/BaseSyncService.cs | 77 -- Parallel.Cli/Services/CleanService.cs | 18 - Parallel.Cli/Services/LifetimeService.cs | 55 -- Parallel.Cli/Services/PruneService.cs | 18 - Parallel.Cli/Services/RunCommand.cs | 45 - Parallel.Cli/Services/TaskService.cs | 22 - Parallel.Cli/Services/WatcherSyncService.cs | 74 -- Parallel.Cli/Utils/CommandLine.cs | 189 ----- Parallel.Cli/Utils/MarkdownGenerator.cs | 89 -- Parallel.Cli/Utils/ProgressReporter.cs | 44 - Parallel.Cli/Utils/TextWriter.cs | 52 -- Parallel.Core/Backends/IBackend.cs | 122 +++ Parallel.Core/Backends/LocalBackend.cs | 121 +++ Parallel.Core/Backends/MemoryBackend.cs | 66 ++ Parallel.Core/Backends/RetryBackend.cs | 79 ++ Parallel.Core/Backends/S3Backend.cs | 132 +++ Parallel.Core/Backends/SftpBackend.cs | 268 ++++++ Parallel.Core/Chunking/FastCdc.cs | 116 +++ Parallel.Core/Config/AppConfig.cs | 225 +++++ Parallel.Core/Config/RecoverySheet.cs | 99 +++ Parallel.Core/Config/VaultConnector.cs | 156 ++++ Parallel.Core/Config/VaultJobs.cs | 110 +++ Parallel.Core/Crypto/KeyFile.cs | 100 +++ Parallel.Core/Crypto/MasterKey.cs | 88 ++ Parallel.Core/Data/FileTypes.cs | 165 ---- .../Database/Contexts/SemaphoreContext.cs | 78 -- .../Database/Contexts/SqliteContext.cs | 220 ----- Parallel.Core/Database/IDatabase.cs | 168 ---- .../Diagnostics/IProgressReporter.cs | 31 - .../Diagnostics/LoggingProgressReporter.cs | 33 - Parallel.Core/Engine/BackupEngine.cs | 618 ++++++++++++++ Parallel.Core/Engine/BackupStatus.cs | 166 ++++ Parallel.Core/Engine/ChangeWatcher.cs | 171 ++++ Parallel.Core/Engine/CheckEngine.cs | 213 +++++ Parallel.Core/Engine/Excludes.cs | 101 +++ Parallel.Core/Engine/FileHistory.cs | 302 +++++++ Parallel.Core/Engine/FileMeta.cs | 227 +++++ Parallel.Core/Engine/NameMapper.cs | 90 ++ Parallel.Core/Engine/Offload.cs | 312 +++++++ Parallel.Core/Engine/PathFilter.cs | 61 ++ Parallel.Core/Engine/PathMap.cs | 73 ++ Parallel.Core/Engine/Progress.cs | 47 ++ Parallel.Core/Engine/PruneEngine.cs | 189 +++++ Parallel.Core/Engine/RestoreEngine.cs | 566 +++++++++++++ Parallel.Core/Engine/Retention.cs | 94 +++ Parallel.Core/Engine/SnapshotPaths.cs | 138 +++ Parallel.Core/Engine/Trash.cs | 32 + Parallel.Core/Engine/VssSession.cs | 109 +++ Parallel.Core/Events/LocalFileEventArgs.cs | 19 - .../Events/MessageRecievedEventArgs.cs | 15 - .../Events/TransferFailedEventArgs.cs | 20 - .../Events/TransferUpdateEventArgs.cs | 33 - .../Extensions/Json/UnixTimeConverter.cs | 49 -- .../Files/Cleaning/CleanerLocation.cs | 165 ++++ Parallel.Core/Files/Cleaning/CleanerRule.cs | 45 + .../Files/Cleaning/CleanerRuleProvider.cs | 244 ++++++ Parallel.Core/Files/Cleaning/PathRule.cs | 151 ++++ .../Files/Cleaning/WindowsRecycleBinRule.cs | 50 ++ .../Files/Duplicates/DuplicateFinder.cs | 209 +++++ Parallel.Core/Files/Formatting/ByteSize.cs | 27 + Parallel.Core/Files/Formatting/TimeFormat.cs | 8 + .../Files/Operations/DeletionService.cs | 102 +++ .../Files/Operations/FileOperations.cs | 307 +++++++ .../Operations/FreedesktopTrashService.cs | 162 ++++ .../Files/Operations/ITrashService.cs | 31 + .../Files/Operations/MacTrashService.cs | 90 ++ Parallel.Core/Files/Operations/PathNames.cs | 43 + Parallel.Core/Files/Operations/Results.cs | 27 + .../Files/Operations/WindowsTrashService.cs | 73 ++ Parallel.Core/Files/Platform/DriveList.cs | 50 ++ .../Files/Platform/ShellIntegration.cs | 40 + .../Files/Scanning/DirectoryScanner.cs | 189 +++++ .../Files/Scanning/ExtensionStats.cs | 31 + Parallel.Core/Files/Scanning/FsNode.cs | 86 ++ .../Files/Treemap/SquarifiedTreemap.cs | 94 +++ Parallel.Core/Files/Treemap/TreemapBuilder.cs | 80 ++ Parallel.Core/IO/PathBuilder.cs | 229 ----- Parallel.Core/IO/ScanFileSystemResult.cs | 25 - Parallel.Core/IO/Scanning/FileScanner.cs | 351 -------- Parallel.Core/IO/SnapshotManager.cs | 24 - Parallel.Core/IO/Syncing/BaseSyncManager.cs | 139 --- Parallel.Core/IO/Syncing/FileSyncManager.cs | 228 ----- Parallel.Core/IO/Syncing/ISyncManager.cs | 84 -- Parallel.Core/IO/Syncing/SyncManager.cs | 22 - Parallel.Core/Model/Model.cs | 209 +++++ Parallel.Core/Models/HistoryEvent.cs | 21 - Parallel.Core/Models/LocalFile.cs | 243 ------ Parallel.Core/Models/PullRecord.cs | 37 - Parallel.Core/Models/RemoteFile.cs | 59 -- Parallel.Core/Models/SnapshotRecord.cs | 52 -- Parallel.Core/Parallel.Core.csproj | 19 +- Parallel.Core/Repository/Codec.cs | 52 ++ Parallel.Core/Repository/Errors.cs | 45 + Parallel.Core/Repository/MasterIndex.cs | 39 + Parallel.Core/Repository/Repository.cs | 684 +++++++++++++++ Parallel.Core/Repository/TreeCache.cs | 49 ++ Parallel.Core/Repository/VaultLock.cs | 161 ++++ Parallel.Core/Security/Encryption.cs | 86 -- Parallel.Core/Security/HashGenerator.cs | 100 --- Parallel.Core/Settings/LocalVaultConfig.cs | 66 -- Parallel.Core/Settings/ParallelConfig.cs | 147 ---- Parallel.Core/Settings/RemoteVaultConfig.cs | 120 --- Parallel.Core/Settings/StorageCredentials.cs | 53 -- Parallel.Core/Storage/IStorageProvider.cs | 84 -- Parallel.Core/Storage/LocalStorageProvider.cs | 190 ----- Parallel.Core/Storage/S3StorageProvider.cs | 174 ---- Parallel.Core/Storage/SshStorageProvider.cs | 166 ---- Parallel.Core/Storage/StorageConnection.cs | 49 -- Parallel.Core/Tasks/EnqueuedTask.cs | 41 - Parallel.Core/Tasks/TaskQueueExecutor.cs | 44 - Parallel.Core/Tasks/TaskQueueOptions.cs | 9 - Parallel.Core/Tasks/TaskQueuer.cs | 84 -- Parallel.Core/Utils/Converter.cs | 52 -- Parallel.Core/Utils/Formatter.cs | 86 -- Parallel.Core/Utils/HashStream.cs | 109 --- Parallel.Core/Utils/LogEventTracker.cs | 38 - Parallel.Core/Utils/UnixTime.cs | 305 ------- Parallel.Gui/App.axaml | 30 + Parallel.Gui/App.axaml.cs | 100 +++ Parallel.Gui/Assets/parallel.ico | Bin 0 -> 180837 bytes Parallel.Gui/Assets/parallel.png | Bin 0 -> 18959 bytes Parallel.Gui/Controls/TreemapControl.cs | 235 ++++++ Parallel.Gui/Converters/ByteSizeConverter.cs | 21 + Parallel.Gui/Icons.cs | 43 + Parallel.Gui/Parallel.Gui.csproj | 66 ++ Parallel.Gui/Program.cs | 42 + Parallel.Gui/Services/BackupStatusService.cs | 265 ++++++ .../Services/ContinuousVersionService.cs | 211 +++++ Parallel.Gui/Services/DialogService.Backup.cs | 381 +++++++++ .../Services/DialogService.Versions.cs | 45 + Parallel.Gui/Services/DialogService.cs | 344 ++++++++ Parallel.Gui/Services/ErrorText.cs | 23 + Parallel.Gui/Services/GuiProgress.cs | 99 +++ Parallel.Gui/Services/NavigationService.cs | 12 + .../Services/RangeObservableCollection.cs | 46 + Parallel.Gui/Services/VaultSession.cs | 99 +++ Parallel.Gui/Services/VaultStore.cs | 105 +++ Parallel.Gui/Settings/GuiSettings.cs | 106 +++ Parallel.Gui/Styles/AppStyles.axaml | 350 ++++++++ Parallel.Gui/Styles/Theme.axaml | 292 +++++++ Parallel.Gui/ViewLocator.cs | 37 + Parallel.Gui/ViewModels/BackupViewModel.cs | 232 +++++ .../ViewModels/BrowserTabViewModel.Vault.cs | 575 +++++++++++++ .../ViewModels/BrowserTabViewModel.cs | 797 ++++++++++++++++++ Parallel.Gui/ViewModels/BrowserViewModel.cs | 158 ++++ Parallel.Gui/ViewModels/CleanerViewModel.cs | 339 ++++++++ Parallel.Gui/ViewModels/DiskUsageRows.cs | 72 ++ Parallel.Gui/ViewModels/DiskUsageViewModel.cs | 369 ++++++++ .../ViewModels/DuplicatesViewModel.cs | 298 +++++++ Parallel.Gui/ViewModels/MainViewModel.cs | 85 ++ .../ViewModels/MaintenanceViewModel.cs | 200 +++++ Parallel.Gui/ViewModels/PageViewModel.cs | 20 + Parallel.Gui/ViewModels/SettingsViewModel.cs | 118 +++ Parallel.Gui/ViewModels/SnapshotsViewModel.cs | 308 +++++++ Parallel.Gui/ViewModels/VaultPageViewModel.cs | 143 ++++ Parallel.Gui/ViewModels/VaultsViewModel.cs | 189 +++++ .../ViewModels/VersionHistoryViewModel.cs | 143 ++++ Parallel.Gui/ViewModels/ViewModelBase.cs | 7 + Parallel.Gui/Views/BackupView.axaml | 213 +++++ Parallel.Gui/Views/BackupView.axaml.cs | 11 + Parallel.Gui/Views/BrowserPaneView.axaml | 52 ++ Parallel.Gui/Views/BrowserPaneView.axaml.cs | 17 + Parallel.Gui/Views/BrowserTabView.axaml | 270 ++++++ Parallel.Gui/Views/BrowserTabView.axaml.cs | 86 ++ Parallel.Gui/Views/BrowserView.axaml | 58 ++ Parallel.Gui/Views/BrowserView.axaml.cs | 29 + Parallel.Gui/Views/CleanerView.axaml | 140 +++ Parallel.Gui/Views/CleanerView.axaml.cs | 19 + Parallel.Gui/Views/DiskUsageView.axaml | 264 ++++++ Parallel.Gui/Views/DiskUsageView.axaml.cs | 38 + Parallel.Gui/Views/DuplicatesView.axaml | 147 ++++ Parallel.Gui/Views/DuplicatesView.axaml.cs | 17 + Parallel.Gui/Views/MainWindow.axaml | 63 ++ Parallel.Gui/Views/MainWindow.axaml.cs | 11 + Parallel.Gui/Views/MaintenanceView.axaml | 131 +++ Parallel.Gui/Views/MaintenanceView.axaml.cs | 11 + Parallel.Gui/Views/Parts/NoVaultCard.axaml | 22 + Parallel.Gui/Views/Parts/NoVaultCard.axaml.cs | 8 + .../Views/Parts/OperationStatus.axaml | 26 + .../Views/Parts/OperationStatus.axaml.cs | 8 + Parallel.Gui/Views/SettingsView.axaml | 151 ++++ Parallel.Gui/Views/SettingsView.axaml.cs | 11 + Parallel.Gui/Views/SnapshotsView.axaml | 115 +++ Parallel.Gui/Views/SnapshotsView.axaml.cs | 19 + Parallel.Gui/Views/VaultsView.axaml | 97 +++ Parallel.Gui/Views/VaultsView.axaml.cs | 11 + Parallel.Gui/app.manifest | 18 + Parallel.Tests/BackupStatusTests.cs | 134 +++ Parallel.Tests/ConfigTests.cs | 105 +++ Parallel.Tests/CrossOsTests.cs | 208 +++++ Parallel.Tests/FileHistoryTests.cs | 148 ++++ Parallel.Tests/Files/CleanerTests.cs | 194 +++++ Parallel.Tests/Files/DuplicateFinderTests.cs | 68 ++ Parallel.Tests/Files/OperationsTests.cs | 126 +++ Parallel.Tests/Files/ScannerTests.cs | 73 ++ Parallel.Tests/Files/TempDir.cs | 48 ++ Parallel.Tests/Files/TreemapTests.cs | 78 ++ Parallel.Tests/Parallel.Tests.csproj | 26 + Parallel.Tests/PassphraseTests.cs | 76 ++ Parallel.Tests/TestVault.cs | 124 +++ Parallel.Tests/UnitTests.cs | 328 +++++++ Parallel.Tests/VaultTests.cs | 538 ++++++++++++ Parallel.Tests/VersionsTests.cs | 206 +++++ Parallel.sln | 76 +- README.md | 212 ++++- 235 files changed, 22674 insertions(+), 6771 deletions(-) create mode 100644 Parallel.Cli/Commands/BackupCommand.cs delete mode 100644 Parallel.Cli/Commands/CleanCommand.cs delete mode 100644 Parallel.Cli/Commands/DuplicatesCommand.cs delete mode 100644 Parallel.Cli/Commands/FetchCommand.cs delete mode 100644 Parallel.Cli/Commands/HistoryCommand.cs delete mode 100644 Parallel.Cli/Commands/IgnoreCommand.cs create mode 100644 Parallel.Cli/Commands/ListCommands.cs create mode 100644 Parallel.Cli/Commands/MaintenanceCommands.cs delete mode 100644 Parallel.Cli/Commands/PruneCommand.cs create mode 100644 Parallel.Cli/Commands/RecoveryCommand.cs delete mode 100644 Parallel.Cli/Commands/ScrubCommand.cs create mode 100644 Parallel.Cli/Commands/SnapshotCommands.cs delete mode 100644 Parallel.Cli/Commands/SnapshotsCommand.cs create mode 100644 Parallel.Cli/Commands/StatsCommand.cs delete mode 100644 Parallel.Cli/Commands/SyncCommand.cs delete mode 100644 Parallel.Cli/Commands/UnzipCommand.cs create mode 100644 Parallel.Cli/Commands/VaultCommands.cs delete mode 100644 Parallel.Cli/Commands/VaultsCommand.cs create mode 100644 Parallel.Cli/Commands/VersionCommands.cs delete mode 100644 Parallel.Cli/Commands/ZipCommand.cs create mode 100644 Parallel.Cli/Infrastructure/ConsoleProgress.cs create mode 100644 Parallel.Cli/Infrastructure/Grids.cs create mode 100644 Parallel.Cli/Infrastructure/TypeRegistrar.cs create mode 100644 Parallel.Cli/Infrastructure/VaultAccess.cs delete mode 100644 Parallel.Cli/Services/BaseSyncService.cs delete mode 100644 Parallel.Cli/Services/CleanService.cs delete mode 100644 Parallel.Cli/Services/LifetimeService.cs delete mode 100644 Parallel.Cli/Services/PruneService.cs delete mode 100644 Parallel.Cli/Services/RunCommand.cs delete mode 100644 Parallel.Cli/Services/TaskService.cs delete mode 100644 Parallel.Cli/Services/WatcherSyncService.cs delete mode 100644 Parallel.Cli/Utils/CommandLine.cs delete mode 100644 Parallel.Cli/Utils/MarkdownGenerator.cs delete mode 100644 Parallel.Cli/Utils/ProgressReporter.cs delete mode 100644 Parallel.Cli/Utils/TextWriter.cs create mode 100644 Parallel.Core/Backends/IBackend.cs create mode 100644 Parallel.Core/Backends/LocalBackend.cs create mode 100644 Parallel.Core/Backends/MemoryBackend.cs create mode 100644 Parallel.Core/Backends/RetryBackend.cs create mode 100644 Parallel.Core/Backends/S3Backend.cs create mode 100644 Parallel.Core/Backends/SftpBackend.cs create mode 100644 Parallel.Core/Chunking/FastCdc.cs create mode 100644 Parallel.Core/Config/AppConfig.cs create mode 100644 Parallel.Core/Config/RecoverySheet.cs create mode 100644 Parallel.Core/Config/VaultConnector.cs create mode 100644 Parallel.Core/Config/VaultJobs.cs create mode 100644 Parallel.Core/Crypto/KeyFile.cs create mode 100644 Parallel.Core/Crypto/MasterKey.cs delete mode 100644 Parallel.Core/Data/FileTypes.cs delete mode 100644 Parallel.Core/Database/Contexts/SemaphoreContext.cs delete mode 100644 Parallel.Core/Database/Contexts/SqliteContext.cs delete mode 100644 Parallel.Core/Database/IDatabase.cs delete mode 100644 Parallel.Core/Diagnostics/IProgressReporter.cs delete mode 100644 Parallel.Core/Diagnostics/LoggingProgressReporter.cs create mode 100644 Parallel.Core/Engine/BackupEngine.cs create mode 100644 Parallel.Core/Engine/BackupStatus.cs create mode 100644 Parallel.Core/Engine/ChangeWatcher.cs create mode 100644 Parallel.Core/Engine/CheckEngine.cs create mode 100644 Parallel.Core/Engine/Excludes.cs create mode 100644 Parallel.Core/Engine/FileHistory.cs create mode 100644 Parallel.Core/Engine/FileMeta.cs create mode 100644 Parallel.Core/Engine/NameMapper.cs create mode 100644 Parallel.Core/Engine/Offload.cs create mode 100644 Parallel.Core/Engine/PathFilter.cs create mode 100644 Parallel.Core/Engine/PathMap.cs create mode 100644 Parallel.Core/Engine/Progress.cs create mode 100644 Parallel.Core/Engine/PruneEngine.cs create mode 100644 Parallel.Core/Engine/RestoreEngine.cs create mode 100644 Parallel.Core/Engine/Retention.cs create mode 100644 Parallel.Core/Engine/SnapshotPaths.cs create mode 100644 Parallel.Core/Engine/Trash.cs create mode 100644 Parallel.Core/Engine/VssSession.cs delete mode 100644 Parallel.Core/Events/LocalFileEventArgs.cs delete mode 100644 Parallel.Core/Events/MessageRecievedEventArgs.cs delete mode 100644 Parallel.Core/Events/TransferFailedEventArgs.cs delete mode 100644 Parallel.Core/Events/TransferUpdateEventArgs.cs delete mode 100644 Parallel.Core/Extensions/Json/UnixTimeConverter.cs create mode 100644 Parallel.Core/Files/Cleaning/CleanerLocation.cs create mode 100644 Parallel.Core/Files/Cleaning/CleanerRule.cs create mode 100644 Parallel.Core/Files/Cleaning/CleanerRuleProvider.cs create mode 100644 Parallel.Core/Files/Cleaning/PathRule.cs create mode 100644 Parallel.Core/Files/Cleaning/WindowsRecycleBinRule.cs create mode 100644 Parallel.Core/Files/Duplicates/DuplicateFinder.cs create mode 100644 Parallel.Core/Files/Formatting/ByteSize.cs create mode 100644 Parallel.Core/Files/Formatting/TimeFormat.cs create mode 100644 Parallel.Core/Files/Operations/DeletionService.cs create mode 100644 Parallel.Core/Files/Operations/FileOperations.cs create mode 100644 Parallel.Core/Files/Operations/FreedesktopTrashService.cs create mode 100644 Parallel.Core/Files/Operations/ITrashService.cs create mode 100644 Parallel.Core/Files/Operations/MacTrashService.cs create mode 100644 Parallel.Core/Files/Operations/PathNames.cs create mode 100644 Parallel.Core/Files/Operations/Results.cs create mode 100644 Parallel.Core/Files/Operations/WindowsTrashService.cs create mode 100644 Parallel.Core/Files/Platform/DriveList.cs create mode 100644 Parallel.Core/Files/Platform/ShellIntegration.cs create mode 100644 Parallel.Core/Files/Scanning/DirectoryScanner.cs create mode 100644 Parallel.Core/Files/Scanning/ExtensionStats.cs create mode 100644 Parallel.Core/Files/Scanning/FsNode.cs create mode 100644 Parallel.Core/Files/Treemap/SquarifiedTreemap.cs create mode 100644 Parallel.Core/Files/Treemap/TreemapBuilder.cs delete mode 100644 Parallel.Core/IO/PathBuilder.cs delete mode 100644 Parallel.Core/IO/ScanFileSystemResult.cs delete mode 100644 Parallel.Core/IO/Scanning/FileScanner.cs delete mode 100644 Parallel.Core/IO/SnapshotManager.cs delete mode 100644 Parallel.Core/IO/Syncing/BaseSyncManager.cs delete mode 100644 Parallel.Core/IO/Syncing/FileSyncManager.cs delete mode 100644 Parallel.Core/IO/Syncing/ISyncManager.cs delete mode 100644 Parallel.Core/IO/Syncing/SyncManager.cs create mode 100644 Parallel.Core/Model/Model.cs delete mode 100644 Parallel.Core/Models/HistoryEvent.cs delete mode 100644 Parallel.Core/Models/LocalFile.cs delete mode 100644 Parallel.Core/Models/PullRecord.cs delete mode 100644 Parallel.Core/Models/RemoteFile.cs delete mode 100644 Parallel.Core/Models/SnapshotRecord.cs create mode 100644 Parallel.Core/Repository/Codec.cs create mode 100644 Parallel.Core/Repository/Errors.cs create mode 100644 Parallel.Core/Repository/MasterIndex.cs create mode 100644 Parallel.Core/Repository/Repository.cs create mode 100644 Parallel.Core/Repository/TreeCache.cs create mode 100644 Parallel.Core/Repository/VaultLock.cs delete mode 100644 Parallel.Core/Security/Encryption.cs delete mode 100644 Parallel.Core/Security/HashGenerator.cs delete mode 100644 Parallel.Core/Settings/LocalVaultConfig.cs delete mode 100644 Parallel.Core/Settings/ParallelConfig.cs delete mode 100644 Parallel.Core/Settings/RemoteVaultConfig.cs delete mode 100644 Parallel.Core/Settings/StorageCredentials.cs delete mode 100644 Parallel.Core/Storage/IStorageProvider.cs delete mode 100644 Parallel.Core/Storage/LocalStorageProvider.cs delete mode 100644 Parallel.Core/Storage/S3StorageProvider.cs delete mode 100644 Parallel.Core/Storage/SshStorageProvider.cs delete mode 100644 Parallel.Core/Storage/StorageConnection.cs delete mode 100644 Parallel.Core/Tasks/EnqueuedTask.cs delete mode 100644 Parallel.Core/Tasks/TaskQueueExecutor.cs delete mode 100644 Parallel.Core/Tasks/TaskQueueOptions.cs delete mode 100644 Parallel.Core/Tasks/TaskQueuer.cs delete mode 100644 Parallel.Core/Utils/Converter.cs delete mode 100644 Parallel.Core/Utils/Formatter.cs delete mode 100644 Parallel.Core/Utils/HashStream.cs delete mode 100644 Parallel.Core/Utils/LogEventTracker.cs delete mode 100644 Parallel.Core/Utils/UnixTime.cs create mode 100644 Parallel.Gui/App.axaml create mode 100644 Parallel.Gui/App.axaml.cs create mode 100644 Parallel.Gui/Assets/parallel.ico create mode 100644 Parallel.Gui/Assets/parallel.png create mode 100644 Parallel.Gui/Controls/TreemapControl.cs create mode 100644 Parallel.Gui/Converters/ByteSizeConverter.cs create mode 100644 Parallel.Gui/Icons.cs create mode 100644 Parallel.Gui/Parallel.Gui.csproj create mode 100644 Parallel.Gui/Program.cs create mode 100644 Parallel.Gui/Services/BackupStatusService.cs create mode 100644 Parallel.Gui/Services/ContinuousVersionService.cs create mode 100644 Parallel.Gui/Services/DialogService.Backup.cs create mode 100644 Parallel.Gui/Services/DialogService.Versions.cs create mode 100644 Parallel.Gui/Services/DialogService.cs create mode 100644 Parallel.Gui/Services/ErrorText.cs create mode 100644 Parallel.Gui/Services/GuiProgress.cs create mode 100644 Parallel.Gui/Services/NavigationService.cs create mode 100644 Parallel.Gui/Services/RangeObservableCollection.cs create mode 100644 Parallel.Gui/Services/VaultSession.cs create mode 100644 Parallel.Gui/Services/VaultStore.cs create mode 100644 Parallel.Gui/Settings/GuiSettings.cs create mode 100644 Parallel.Gui/Styles/AppStyles.axaml create mode 100644 Parallel.Gui/Styles/Theme.axaml create mode 100644 Parallel.Gui/ViewLocator.cs create mode 100644 Parallel.Gui/ViewModels/BackupViewModel.cs create mode 100644 Parallel.Gui/ViewModels/BrowserTabViewModel.Vault.cs create mode 100644 Parallel.Gui/ViewModels/BrowserTabViewModel.cs create mode 100644 Parallel.Gui/ViewModels/BrowserViewModel.cs create mode 100644 Parallel.Gui/ViewModels/CleanerViewModel.cs create mode 100644 Parallel.Gui/ViewModels/DiskUsageRows.cs create mode 100644 Parallel.Gui/ViewModels/DiskUsageViewModel.cs create mode 100644 Parallel.Gui/ViewModels/DuplicatesViewModel.cs create mode 100644 Parallel.Gui/ViewModels/MainViewModel.cs create mode 100644 Parallel.Gui/ViewModels/MaintenanceViewModel.cs create mode 100644 Parallel.Gui/ViewModels/PageViewModel.cs create mode 100644 Parallel.Gui/ViewModels/SettingsViewModel.cs create mode 100644 Parallel.Gui/ViewModels/SnapshotsViewModel.cs create mode 100644 Parallel.Gui/ViewModels/VaultPageViewModel.cs create mode 100644 Parallel.Gui/ViewModels/VaultsViewModel.cs create mode 100644 Parallel.Gui/ViewModels/VersionHistoryViewModel.cs create mode 100644 Parallel.Gui/ViewModels/ViewModelBase.cs create mode 100644 Parallel.Gui/Views/BackupView.axaml create mode 100644 Parallel.Gui/Views/BackupView.axaml.cs create mode 100644 Parallel.Gui/Views/BrowserPaneView.axaml create mode 100644 Parallel.Gui/Views/BrowserPaneView.axaml.cs create mode 100644 Parallel.Gui/Views/BrowserTabView.axaml create mode 100644 Parallel.Gui/Views/BrowserTabView.axaml.cs create mode 100644 Parallel.Gui/Views/BrowserView.axaml create mode 100644 Parallel.Gui/Views/BrowserView.axaml.cs create mode 100644 Parallel.Gui/Views/CleanerView.axaml create mode 100644 Parallel.Gui/Views/CleanerView.axaml.cs create mode 100644 Parallel.Gui/Views/DiskUsageView.axaml create mode 100644 Parallel.Gui/Views/DiskUsageView.axaml.cs create mode 100644 Parallel.Gui/Views/DuplicatesView.axaml create mode 100644 Parallel.Gui/Views/DuplicatesView.axaml.cs create mode 100644 Parallel.Gui/Views/MainWindow.axaml create mode 100644 Parallel.Gui/Views/MainWindow.axaml.cs create mode 100644 Parallel.Gui/Views/MaintenanceView.axaml create mode 100644 Parallel.Gui/Views/MaintenanceView.axaml.cs create mode 100644 Parallel.Gui/Views/Parts/NoVaultCard.axaml create mode 100644 Parallel.Gui/Views/Parts/NoVaultCard.axaml.cs create mode 100644 Parallel.Gui/Views/Parts/OperationStatus.axaml create mode 100644 Parallel.Gui/Views/Parts/OperationStatus.axaml.cs create mode 100644 Parallel.Gui/Views/SettingsView.axaml create mode 100644 Parallel.Gui/Views/SettingsView.axaml.cs create mode 100644 Parallel.Gui/Views/SnapshotsView.axaml create mode 100644 Parallel.Gui/Views/SnapshotsView.axaml.cs create mode 100644 Parallel.Gui/Views/VaultsView.axaml create mode 100644 Parallel.Gui/Views/VaultsView.axaml.cs create mode 100644 Parallel.Gui/app.manifest create mode 100644 Parallel.Tests/BackupStatusTests.cs create mode 100644 Parallel.Tests/ConfigTests.cs create mode 100644 Parallel.Tests/CrossOsTests.cs create mode 100644 Parallel.Tests/FileHistoryTests.cs create mode 100644 Parallel.Tests/Files/CleanerTests.cs create mode 100644 Parallel.Tests/Files/DuplicateFinderTests.cs create mode 100644 Parallel.Tests/Files/OperationsTests.cs create mode 100644 Parallel.Tests/Files/ScannerTests.cs create mode 100644 Parallel.Tests/Files/TempDir.cs create mode 100644 Parallel.Tests/Files/TreemapTests.cs create mode 100644 Parallel.Tests/Parallel.Tests.csproj create mode 100644 Parallel.Tests/PassphraseTests.cs create mode 100644 Parallel.Tests/TestVault.cs create mode 100644 Parallel.Tests/UnitTests.cs create mode 100644 Parallel.Tests/VaultTests.cs create mode 100644 Parallel.Tests/VersionsTests.cs 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-build.yml b/.github/workflows/dotnet-build.yml index f31a5d9..ac10023 100644 --- a/.github/workflows/dotnet-build.yml +++ b/.github/workflows/dotnet-build.yml @@ -28,3 +28,6 @@ jobs: - name: Build Release run: dotnet build --configuration Release --no-restore + + - name: Test + run: dotnet test --configuration Release --no-restore --verbosity normal 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