From cdb0d97b60a936b1b2a112c7c25487d1d367c786 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 12:57:32 +0900 Subject: [PATCH 01/45] Rework loop prevent off-by-one errors and potentially dropped errors --- src/CCVTAC.Main/Orchestrator.fs | 30 ++++++++++++++++++------------ 1 file changed, 18 insertions(+), 12 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 4b5f59e4..f9d6b12a 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -258,26 +258,32 @@ module Orchestrator = (nextAction', settings', index) | input :: remainingInputs when nextAction' = Continue -> let processResult = processInput input.Category input.Text index - batchResults.RegisterResult(input.Text, processResult) - // Deleting the files here might make debugging issues a bit tougher. - match deleteLeftoverFiles settings.WorkingDirectory with + // Report processing errors before cleanup so they are not lost if cleanup fails. + match processResult with + | Error err -> printer.Error err + | Ok _ -> () + + let cleanupResult = + if input.Category.IsUrl + then deleteLeftoverFiles settings.WorkingDirectory + else Ok None + + match cleanupResult with | Error errMsg -> printer.Error errMsg - (QuitDueToErrors, settings', index) + (QuitDueToErrors, settings', index + 1) | Ok message -> message |> Option.iter printer.Debug + if List.isNotEmpty remainingInputs then printSleep input.Category + match processResult with - | Error err -> - printer.Error err - if List.isNotEmpty remainingInputs then printSleep input.Category + | Error _ -> loop remainingInputs settings' nextAction' (index + 1) - | Ok processResult -> - if List.isNotEmpty remainingInputs then printSleep input.Category - let newSettings = defaultArg processResult.UpdatedSettings settings' - let newNextAction = processResult.NextAction - loop remainingInputs newSettings newNextAction (index + 1) + | Ok result -> + let newSettings = defaultArg result.UpdatedSettings settings' + loop remainingInputs newSettings result.NextAction (index + 1) | _ -> (nextAction', settings', index) From a6e17c71db06ca9831df44fe52db42fae9268ccd Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:44:17 +0900 Subject: [PATCH 02/45] Prefer Result.iterError over simple 'match' --- src/CCVTAC.Main/Orchestrator.fs | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index f9d6b12a..b6ecca25 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -9,6 +9,7 @@ open CCVTAC.Main.Settings.Settings open CCVTAC.Main.Settings.Settings.LiveUpdating open CCFSharpUtils.Collections open CCFSharpUtils.Text +open FSharpPlus open Startwatch.Library open System open System.Globalization @@ -260,10 +261,7 @@ module Orchestrator = let processResult = processInput input.Category input.Text index batchResults.RegisterResult(input.Text, processResult) - // Report processing errors before cleanup so they are not lost if cleanup fails. - match processResult with - | Error err -> printer.Error err - | Ok _ -> () + processResult |> Result.iterError printer.Error let cleanupResult = if input.Category.IsUrl @@ -277,7 +275,6 @@ module Orchestrator = | Ok message -> message |> Option.iter printer.Debug if List.isNotEmpty remainingInputs then printSleep input.Category - match processResult with | Error _ -> loop remainingInputs settings' nextAction' (index + 1) From 1fd642dd91a1d48b8fe58196dc003cba213d5d80 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 14:52:54 +0900 Subject: [PATCH 03/45] Don't both print and return error message --- src/CCVTAC.Main/Orchestrator.fs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index b6ecca25..481cc934 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -66,10 +66,8 @@ module Orchestrator = let jobWatch = Watch() match Downloading.mediaTypeWithIds url with - | Error e -> - let errorMsg = $"URL parse error: %s{e}" - printer.Error errorMsg - Error errorMsg + | Error errMsg -> + Error $"URL parse error: %s{errMsg}" | Ok mediaType -> printer.Info $"%s{mediaType.GetType().Name} URL '%s{url}' detected." history.Append(url, urlInputTime, printer) From 94892f6ac1840a296be7c383159c7b32a31549d2 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:03:57 +0900 Subject: [PATCH 04/45] Return NextAction from orchestrator for more accurate error codes --- src/CCVTAC.Main/Orchestrator.fs | 8 ++++++-- src/CCVTAC.Main/Program.fs | 6 ++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 481cc934..370140c0 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -319,8 +319,10 @@ module Orchestrator = printer.Info "Aborting..." false - let start (printer: Printer) (settings: UserSettings) : unit = - if isWorkingDirectoryReady printer settings.WorkingDirectory then + let start (printer: Printer) (settings: UserSettings) : NextAction = + if not (isWorkingDirectoryReady printer settings.WorkingDirectory) then + QuitDueToErrors + else let results = ResultTracker printer let history = History(settings.HistoryFile, settings.HistoryDisplayCount) let mutable nextAction = Continue @@ -346,3 +348,5 @@ module Orchestrator = | None -> () results.PrintSessionSummary() + nextAction + diff --git a/src/CCVTAC.Main/Program.fs b/src/CCVTAC.Main/Program.fs index 4bd4db16..bc66d7cd 100644 --- a/src/CCVTAC.Main/Program.fs +++ b/src/CCVTAC.Main/Program.fs @@ -1,6 +1,7 @@ namespace CCVTAC.Main open CCVTAC.Main.IoUtilities +open CCVTAC.Main.Orchestrator open CCVTAC.Main.Settings open CCVTAC.Main.Settings.Settings open Settings.IO @@ -68,8 +69,9 @@ module Program = registerCancelHandler printer settings.WorkingDirectory try - Orchestrator.start printer settings - int ExitCodes.Success + match Orchestrator.start printer settings with + | QuitDueToErrors -> int ExitCodes.OperationError + | _ -> int ExitCodes.Success with exn -> printer.Critical $"Fatal error: {exn.Message}" AnsiConsole.WriteException exn From cc42ca094e3406a77057d8ea3ba8c981974d6bb2 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 15:44:17 +0900 Subject: [PATCH 05/45] Prevent settings shadowing causing stale settings --- src/CCVTAC.Main/Orchestrator.fs | 24 +++++++++++------------- 1 file changed, 11 insertions(+), 13 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 370140c0..dfc3d337 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -222,7 +222,7 @@ module Orchestrator = let batchWatch = Watch() let batchResults = ResultTracker printer - let printSleep (category: InputCategory) = + let printSleep settings (category: InputCategory) = if category.IsUrl then let seconds = settings.SleepSecondsBetweenURLs let secondsMsg secs = String.plur' "second" S secs @@ -234,7 +234,7 @@ module Orchestrator = printer.Info $"{String.nl}{sleptMsg}" printer.EmptyLine() - let processInput category text index : Result = + let processInput settings category text index : Result = match category with | Command -> processCommand printer text settings history | Url -> processUrl printer text settings resultTracker history inputTime inputs.Length index @@ -251,36 +251,34 @@ module Orchestrator = | Error deletionError -> Error $"Error deleting leftover files after download: {deletionError}" - let rec loop inputs settings' nextAction' index : NextAction * UserSettings * int = + let rec loop inputs currentSettings nextAction' index : NextAction * UserSettings * int = match inputs with - | [] -> - (nextAction', settings', index) + | [] -> (nextAction', currentSettings, index) | input :: remainingInputs when nextAction' = Continue -> - let processResult = processInput input.Category input.Text index + let processResult = processInput currentSettings input.Category input.Text index batchResults.RegisterResult(input.Text, processResult) - processResult |> Result.iterError printer.Error let cleanupResult = if input.Category.IsUrl - then deleteLeftoverFiles settings.WorkingDirectory + then deleteLeftoverFiles currentSettings.WorkingDirectory else Ok None match cleanupResult with | Error errMsg -> printer.Error errMsg - (QuitDueToErrors, settings', index + 1) + (QuitDueToErrors, currentSettings, index + 1) | Ok message -> message |> Option.iter printer.Debug - if List.isNotEmpty remainingInputs then printSleep input.Category + if List.isNotEmpty remainingInputs then printSleep currentSettings input.Category match processResult with | Error _ -> - loop remainingInputs settings' nextAction' (index + 1) + loop remainingInputs currentSettings nextAction' (index + 1) | Ok result -> - let newSettings = defaultArg result.UpdatedSettings settings' + let newSettings = defaultArg result.UpdatedSettings currentSettings loop remainingInputs newSettings result.NextAction (index + 1) | _ -> - (nextAction', settings', index) + (nextAction', currentSettings, index) let (finalNextAction, finalSettings, processedCount) = loop inputs settings Continue 1 From d83d1cadc118f02e5c99a34d9c6c34cee3aae8a1 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:12:47 +0900 Subject: [PATCH 06/45] Heavy Orchestrator refactor --- src/CCVTAC.Main/Orchestrator.fs | 357 +++++++++--------- .../PostProcessing/PostProcessing.fs | 4 +- 2 files changed, 189 insertions(+), 172 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index dfc3d337..1af72999 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -22,6 +22,27 @@ module Orchestrator = { NextAction: NextAction UpdatedSettings: UserSettings option } + /// Distinguishes input-level failures (skip and continue) from failures + /// that should halt the batch. + type ProcessError = + | Recoverable of string + | Fatal of string + + type ToggleSpec = + { Triggers: string list + Label: string + Toggle: UserSettings -> UserSettings + Read: UserSettings -> bool + AfterToggle: UserSettings -> unit } + + [] + let private maxLeftoverFilesToShow = 10 + + let private errorText (error: ProcessError) : string = + match error with + | Recoverable msg + | Fatal msg -> msg + let summarizeInput (printer: Printer) (inputs: CategorizedInput list) @@ -53,12 +74,11 @@ module Orchestrator = (urlInputTime: DateTime) (batchSize: int) (urlIndex: int) - : Result = + : Result = - match Directories.warnIfAnyFiles 10 settings.WorkingDirectory with + match Directories.warnIfAnyFiles maxLeftoverFilesToShow settings.WorkingDirectory with | Error err -> - printer.Error err - Ok { NextAction = QuitDueToErrors; UpdatedSettings = None } + Error (Fatal err) | Ok () -> if batchSize > 1 then printer.Info $"Processing item %d{urlIndex} of %d{batchSize}..." @@ -67,7 +87,7 @@ module Orchestrator = match Downloading.mediaTypeWithIds url with | Error errMsg -> - Error $"URL parse error: %s{errMsg}" + Error (Recoverable $"URL parse error: %s{errMsg}") | Ok mediaType -> printer.Info $"%s{mediaType.GetType().Name} URL '%s{url}' detected." history.Append(url, urlInputTime, printer) @@ -77,10 +97,11 @@ module Orchestrator = match downloadResult with | Error errs -> - errs - |> List.map (sprintf "Media download error: %s") - |> String.concat String.nl - |> Error + let msg = + errs + |> List.map (sprintf "Media download error: %s") + |> String.concat String.nl + Error (Recoverable msg) | Ok message -> printer.Debug "Download successful." if String.hasText message then printer.Info message @@ -94,137 +115,123 @@ module Orchestrator = printer.Info $"Processed '%s{url}'%s{groupClause} in %s{jobWatch.ElapsedFriendly}." Ok { NextAction = Continue; UpdatedSettings = None } - let summarizeToggle settingName setting = - sprintf "%s toggled to %s for this session." settingName (if setting then "ON" else "OFF") + let summarizeToggle (settingName: string) (setting: bool) : string = + let state = if setting then "ON" else "OFF" + $"%s{settingName} toggled to %s{state} for this session." - let summarizeUpdate settingName setting = - sprintf "%s updated to \"%s\" for this session." settingName setting + let summarizeUpdate (settingName: string) (setting: string) : string = + $"%s{settingName} updated to \"%s{setting}\" for this session." let private extractValue (prefix: string) (command: string) : string = command.Substring(prefix.Length).Trim() - let processCommand - (printer: Printer) - (command: string) - (settings: UserSettings) - (history: History) - : Result = - + let private toggleSpecs (printer: Printer) : ToggleSpec list = + [ { Triggers = Commands.splitChapterToggles + Label = "Split Chapters" + Toggle = toggleSplitChapters + Read = _.SplitChapters + AfterToggle = ignore } + + { Triggers = Commands.embedImagesToggles + Label = "Embed Images" + Toggle = toggleEmbedImages + Read = _.EmbedImages + AfterToggle = ignore } + + { Triggers = Commands.quietModeToggles + Label = "Quiet Mode" + Toggle = toggleQuietMode + Read = _.QuietMode + AfterToggle = fun s -> printer.ShowDebug(not s.QuietMode) } ] + + let processCommand printer command settings (history: History) : Result = let checkCommand = List.containsIgnoreCase command + let toggle = toggleSpecs printer |> List.tryFind (fun spec -> checkCommand spec.Triggers) - // Help - if String.equalIgnoreCase Commands.helpCommand command then - for kvp in Commands.summary do - printer.Info kvp.Key - printer.Info $" %s{kvp.Value}" - Ok { NextAction = Continue; UpdatedSettings = None } - - // Quit - elif checkCommand Commands.quitCommands then - Ok { NextAction = QuitAtUserRequest; UpdatedSettings = None } - - // History - elif checkCommand Commands.history then - history.ShowRecent printer - Ok { NextAction = Continue; UpdatedSettings = None } - - // Update media downloader - elif checkCommand Commands.updateDownloader then - Updater.run printer settings - Ok { NextAction = Continue; UpdatedSettings = None } - - // Settings summary - elif checkCommand Commands.settingsSummary then - Settings.toTable settings |> printer.PrintTable - Ok { NextAction = Continue; UpdatedSettings = None } - - // Toggle split chapters - elif checkCommand Commands.splitChapterToggles then - let newSettings = toggleSplitChapters settings - printer.Info(summarizeToggle "Split Chapters" newSettings.SplitChapters) + match toggle with + | Some spec -> + let newSettings = spec.Toggle settings + printer.Info(summarizeToggle spec.Label (spec.Read newSettings)) + spec.AfterToggle newSettings Ok { NextAction = Continue; UpdatedSettings = Some newSettings } - // Toggle embed images - elif checkCommand Commands.embedImagesToggles then - let newSettings = toggleEmbedImages settings - printer.Info(summarizeToggle "Embed Images" newSettings.EmbedImages) - Ok { NextAction = Continue; UpdatedSettings = Some newSettings } + | None -> + if String.equalIgnoreCase Commands.helpCommand command then + for kvp in Commands.summary do + printer.Info kvp.Key + printer.Info $" %s{kvp.Value}" + Ok { NextAction = Continue; UpdatedSettings = None } - // Toggle quiet mode - elif checkCommand Commands.quietModeToggles then - let newSettings = toggleQuietMode settings - printer.Info(summarizeToggle "Quiet Mode" newSettings.QuietMode) - printer.ShowDebug(not newSettings.QuietMode) - Ok { NextAction = Continue; UpdatedSettings = Some newSettings } + elif checkCommand Commands.quitCommands then + Ok { NextAction = QuitAtUserRequest; UpdatedSettings = None } - // Update audio formats - elif command |> String.startsWithIgnoreCase Commands.updateAudioFormatPrefix then - let format = - command - |> extractValue Commands.updateAudioFormatPrefix - |> _.ToLowerInvariant() + elif checkCommand Commands.history then + history.ShowRecent printer + Ok { NextAction = Continue; UpdatedSettings = None } - if String.hasNoText format then - Error "You must append one or more supported audio formats separated by commas (e.g., \"m4a,opus,best\")." - else - let updateResult = updateAudioFormat settings format - match updateResult with - | Error err -> - Error err - | Ok newSettings -> - let audioFormats = String.Join(", ", newSettings.AudioFormats) - printer.Info <| summarizeUpdate "Audio Formats" audioFormats - Ok { NextAction = Continue; UpdatedSettings = Some newSettings } - - // Update audio quality - elif command |> String.startsWithIgnoreCase Commands.updateAudioQualityPrefix then - let inputQuality = extractValue Commands.updateAudioQualityPrefix command - let rangeRule = "Audio quality must be between 10 (lowest) and 0 (highest)." - - if String.hasNoText inputQuality then - Error rangeRule - else - match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with - | true, quality when quality <= 10uy -> - match updateAudioQuality settings quality with + elif checkCommand Commands.updateDownloader then + Updater.run printer settings + Ok { NextAction = Continue; UpdatedSettings = None } + + elif checkCommand Commands.settingsSummary then + Settings.toTable settings |> printer.PrintTable + Ok { NextAction = Continue; UpdatedSettings = None } + + elif command |> String.startsWithIgnoreCase Commands.updateAudioFormatPrefix then + let format = + command + |> extractValue Commands.updateAudioFormatPrefix + |> _.ToLowerInvariant() + + if String.hasNoText format then + Error "You must append one or more supported audio formats separated by commas (e.g., \"m4a,opus,best\")." + else + match updateAudioFormat settings format with | Error err -> Error err - | Ok updatedSettings -> - let updatedQuality = updatedSettings.AudioQuality.ToString() - printer.Info <| summarizeUpdate "Audio Quality" updatedQuality - Ok { NextAction = Continue - UpdatedSettings = Some updatedSettings } - | true, _ -> - Error rangeRule - | _ -> - Error $"\"%s{inputQuality}\" is an invalid quality value. %s{rangeRule}" + | Ok newSettings -> + let audioFormats = String.Join(", ", newSettings.AudioFormats) + printer.Info <| summarizeUpdate "Audio Formats" audioFormats + Ok { NextAction = Continue; UpdatedSettings = Some newSettings } - // Unknown command - else - Error <| - sprintf "\"%s\" is not a valid command. Enter \"%s\" to see a list of commands." - command - $"""{(string Commands.prefix)}help""" + elif command |> String.startsWithIgnoreCase Commands.updateAudioQualityPrefix then + let inputQuality = extractValue Commands.updateAudioQualityPrefix command + let rangeRule = "Audio quality must be between 10 (lowest) and 0 (highest)." + + if String.hasNoText inputQuality then + Error rangeRule + else + match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with + | true, quality when quality <= 10uy -> + match updateAudioQuality settings quality with + | Error err -> + Error err + | Ok updatedSettings -> + let updatedQuality = updatedSettings.AudioQuality.ToString() + printer.Info <| summarizeUpdate "Audio Quality" updatedQuality + Ok { NextAction = Continue + UpdatedSettings = Some updatedSettings } + | true, _ -> + Error rangeRule + | _ -> + Error $"\"%s{inputQuality}\" is an invalid quality value. %s{rangeRule}" + else + Error $"\"%s{command}\" is not a valid command. Enter \"%c{Commands.prefix}help\" to see a list of commands." /// Processes a single user request, from input to downloading and file post-processing. /// Returns the next action the application should take (e.g., continue or quit). - let processBatch - (printer: Printer) - (inputs: CategorizedInput list) - (categoryCounts: CategoryCounts) - (settings: UserSettings) - (resultTracker: ResultTracker) - (history: History) - : BatchResults = + let processBatch printer (inputs: CategorizedInput list) (categoryCounts: CategoryCounts) + settings resultTracker history + : BatchResults = let inputTime = DateTime.Now let batchWatch = Watch() let batchResults = ResultTracker printer - let printSleep settings (category: InputCategory) = - if category.IsUrl then - let seconds = settings.SleepSecondsBetweenURLs + let printSleep currentSettings (inputCategory: InputCategory) = + if inputCategory.IsUrl then + let seconds = currentSettings.SleepSecondsBetweenURLs let secondsMsg secs = String.plur' "second" S secs let sleptMsg = sleep @@ -234,51 +241,62 @@ module Orchestrator = printer.Info $"{String.nl}{sleptMsg}" printer.EmptyLine() - let processInput settings category text index : Result = - match category with - | Command -> processCommand printer text settings history - | Url -> processUrl printer text settings resultTracker history inputTime inputs.Length index + let processInput currentSettings inputCategory text index : Result = + match inputCategory with + | Command -> + processCommand printer text currentSettings history + |> Result.mapError Recoverable + | Url -> + processUrl printer text currentSettings resultTracker history inputTime inputs.Length index - let deleteLeftoverFiles dirName : Result = - match Directories.warnIfAnyFiles 10 dirName with + let deleteLeftoverFiles dirName : Result = + match Directories.warnIfAnyFiles maxLeftoverFilesToShow dirName with | Ok () -> Ok None - | Error filesFoundErr -> - printer.Error filesFoundErr // Might not need this. - Directories.deleteAllFiles dirName |> function - | Ok results -> + | Error msg -> + printer.Warning msg + Directories.deleteAllFiles dirName + |> Result.map (fun results -> Directories.printDeletionResults printer results - Ok (Some "Files deleted successfully.") - | Error deletionError -> - Error $"Error deleting leftover files after download: {deletionError}" + Some "Files deleted successfully.") + |> Result.mapError (sprintf "Error deleting leftover files after download: %s") - let rec loop inputs currentSettings nextAction' index : NextAction * UserSettings * int = + let rec loop inputs settings nextAction' index : NextAction * UserSettings * int = match inputs with - | [] -> (nextAction', currentSettings, index) | input :: remainingInputs when nextAction' = Continue -> - let processResult = processInput currentSettings input.Category input.Text index - batchResults.RegisterResult(input.Text, processResult) - processResult |> Result.iterError printer.Error - - let cleanupResult = - if input.Category.IsUrl - then deleteLeftoverFiles currentSettings.WorkingDirectory - else Ok None - - match cleanupResult with - | Error errMsg -> - printer.Error errMsg - (QuitDueToErrors, currentSettings, index + 1) - | Ok message -> - message |> Option.iter printer.Debug - if List.isNotEmpty remainingInputs then printSleep currentSettings input.Category - match processResult with - | Error _ -> - loop remainingInputs currentSettings nextAction' (index + 1) - | Ok result -> - let newSettings = defaultArg result.UpdatedSettings currentSettings - loop remainingInputs newSettings result.NextAction (index + 1) + let processResult = processInput settings input.Category input.Text index + + batchResults.RegisterResult(input.Text, processResult |> Result.mapError errorText) + processResult |> Result.iterError (errorText >> printer.Error) + + match processResult with + | Error (Fatal errMsg) -> + printer.Error errMsg // TODO: This might not be needed. Remove if not. + // The item was not processed, so `index` (not index + 1) keeps it in the unprocessed list. + (QuitDueToErrors, settings, index) + | _ -> + let cleanupResult = + if input.Category.IsUrl + then deleteLeftoverFiles settings.WorkingDirectory + else Ok None + + match cleanupResult with + | Error errMsg -> + printer.Error errMsg + (QuitDueToErrors, settings, index + 1) + | Ok message -> + message |> Option.iter printer.Debug + if List.isNotEmpty remainingInputs then printSleep settings input.Category + + let updatedSettings, nextAction = + match processResult with + | Ok result -> + defaultArg result.UpdatedSettings settings, result.NextAction + | Error _ -> + settings, nextAction' + + loop remainingInputs updatedSettings nextAction (index + 1) | _ -> - (nextAction', currentSettings, index) + (nextAction', settings, index) let (finalNextAction, finalSettings, processedCount) = loop inputs settings Continue 1 @@ -303,7 +321,7 @@ module Orchestrator = UpdatedSettings = Some finalSettings } let private isWorkingDirectoryReady (printer: Printer) dirName : bool = - match Directories.warnIfAnyFiles 10 dirName with + match Directories.warnIfAnyFiles maxLeftoverFilesToShow dirName with | Ok () -> true | Error err -> @@ -317,34 +335,33 @@ module Orchestrator = printer.Info "Aborting..." false - let start (printer: Printer) (settings: UserSettings) : NextAction = + let start printer settings : NextAction = if not (isWorkingDirectoryReady printer settings.WorkingDirectory) then QuitDueToErrors else let results = ResultTracker printer let history = History(settings.HistoryFile, settings.HistoryDisplayCount) - let mutable nextAction = Continue - let mutable currentSettings = settings - while nextAction = Continue do + let rec repl (currentSettings: UserSettings) : NextAction = let input = printer.GetInput prompt - let splitInputs = splitInputText input - - match splitInputs with + match splitInputText input with | [] -> printer.Error $"Invalid input. Enter only URLs or commands beginning with \"%c{Commands.prefix}\"." - | _ -> + repl currentSettings + | splitInputs -> let categorizedInputs = categorizeInputs splitInputs let categoryCounts = countCategories categorizedInputs summarizeInput printer categorizedInputs categoryCounts - let batchResult = processBatch printer categorizedInputs categoryCounts currentSettings results history - nextAction <- batchResult.NextAction + let batchResult = + processBatch printer categorizedInputs categoryCounts currentSettings results history - match batchResult.UpdatedSettings with - | Some newSettings -> currentSettings <- newSettings - | None -> () + let nextSettings = defaultArg batchResult.UpdatedSettings currentSettings - results.PrintSessionSummary() - nextAction + match batchResult.NextAction with + | Continue -> repl nextSettings + | action -> + results.PrintSessionSummary() + action + repl settings diff --git a/src/CCVTAC.Main/PostProcessing/PostProcessing.fs b/src/CCVTAC.Main/PostProcessing/PostProcessing.fs index 2f041e4d..4f3fc0ba 100644 --- a/src/CCVTAC.Main/PostProcessing/PostProcessing.fs +++ b/src/CCVTAC.Main/PostProcessing/PostProcessing.fs @@ -46,8 +46,8 @@ module PostProcessor = let taggingSets = createSets <| Directory.GetFiles dir match taggingSets with | Ok ts -> Ok ts - | Error msgs -> - $"Error(s) creating tagging sets in working directory \"%s{dir}\"" :: msgs + | Error errMsgs -> + $"Error(s) creating tagging sets in working directory \"%s{dir}\"" :: errMsgs |> String.concat String.nl |> Error with exn -> From 75c3d0f7fe529d4629070dbe909cbfc8a4b60a78 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:49:29 +0900 Subject: [PATCH 07/45] Minor tweaks --- src/CCVTAC.Main/Orchestrator.fs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 1af72999..7ccc75cd 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -151,7 +151,7 @@ module Orchestrator = match toggle with | Some spec -> let newSettings = spec.Toggle settings - printer.Info(summarizeToggle spec.Label (spec.Read newSettings)) + printer.Info <| summarizeToggle spec.Label (spec.Read newSettings) spec.AfterToggle newSettings Ok { NextAction = Continue; UpdatedSettings = Some newSettings } @@ -174,7 +174,7 @@ module Orchestrator = Ok { NextAction = Continue; UpdatedSettings = None } elif checkCommand Commands.settingsSummary then - Settings.toTable settings |> printer.PrintTable + printer.PrintTable (toTable settings) Ok { NextAction = Continue; UpdatedSettings = None } elif command |> String.startsWithIgnoreCase Commands.updateAudioFormatPrefix then @@ -184,7 +184,7 @@ module Orchestrator = |> _.ToLowerInvariant() if String.hasNoText format then - Error "You must append one or more supported audio formats separated by commas (e.g., \"m4a,opus,best\")." + Error "Append one or more supported audio formats separated by commas (e.g., \"m4a,opus,best\")." else match updateAudioFormat settings format with | Error err -> @@ -220,7 +220,6 @@ module Orchestrator = Error $"\"%s{command}\" is not a valid command. Enter \"%c{Commands.prefix}help\" to see a list of commands." /// Processes a single user request, from input to downloading and file post-processing. - /// Returns the next action the application should take (e.g., continue or quit). let processBatch printer (inputs: CategorizedInput list) (categoryCounts: CategoryCounts) settings resultTracker history : BatchResults = From 19fab237364b473f72c06f32c0a9cf86917c3cc4 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 17:59:26 +0900 Subject: [PATCH 08/45] Remove duplicated error message --- src/CCVTAC.Main/Orchestrator.fs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 7ccc75cd..0bb917a6 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -268,8 +268,7 @@ module Orchestrator = processResult |> Result.iterError (errorText >> printer.Error) match processResult with - | Error (Fatal errMsg) -> - printer.Error errMsg // TODO: This might not be needed. Remove if not. + | Error (Fatal _) -> // The item was not processed, so `index` (not index + 1) keeps it in the unprocessed list. (QuitDueToErrors, settings, index) | _ -> From a6be704ecc1c95357775a44f805f1a22eaf390ed Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:00:02 +0900 Subject: [PATCH 09/45] Delete RegisterResult string overload --- src/CCVTAC.Main/ResultTracker.fs | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/CCVTAC.Main/ResultTracker.fs b/src/CCVTAC.Main/ResultTracker.fs index 10de2b54..664f882b 100644 --- a/src/CCVTAC.Main/ResultTracker.fs +++ b/src/CCVTAC.Main/ResultTracker.fs @@ -11,15 +11,6 @@ type ResultTracker<'a>(printer: Printer) = let failures = Dictionary() - /// Logs the result for a specific corresponding input. - member _.RegisterResult(input: string, result: Result<'a, string>) : unit = - match result with - | Ok _ -> - successCount <- successCount + 1UL - | Error e -> - if not (failures.TryAdd(input, e)) then - failures[input] <- e - /// Logs the result for a specific corresponding input. member _.RegisterResult(input: string, result: Result<'a, string list>) : unit = match result with From 755e8b7c2fa4458164e1f0c66875e8d1cd7d5a9c Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:01:01 +0900 Subject: [PATCH 10/45] Delete superfluous ResultTracker --- src/CCVTAC.Main/Orchestrator.fs | 23 +++++++++++++++++------ 1 file changed, 17 insertions(+), 6 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 0bb917a6..fb9652bb 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -220,13 +220,17 @@ module Orchestrator = Error $"\"%s{command}\" is not a valid command. Enter \"%c{Commands.prefix}help\" to see a list of commands." /// Processes a single user request, from input to downloading and file post-processing. - let processBatch printer (inputs: CategorizedInput list) (categoryCounts: CategoryCounts) - settings resultTracker history - : BatchResults = + let processBatch + (printer: Printer) + (inputs: CategorizedInput list) + (categoryCounts: CategoryCounts) + (settings: UserSettings) + (resultTracker: ResultTracker) + (history: History) + : BatchResults = let inputTime = DateTime.Now let batchWatch = Watch() - let batchResults = ResultTracker printer let printSleep currentSettings (inputCategory: InputCategory) = if inputCategory.IsUrl then @@ -264,7 +268,14 @@ module Orchestrator = | input :: remainingInputs when nextAction' = Continue -> let processResult = processInput settings input.Category input.Text index - batchResults.RegisterResult(input.Text, processResult |> Result.mapError errorText) + // TODO: Resolve this nasty, temporary workaround. + let processResult' = + processResult + |> Result.map _.ToString() + |> Result.mapError (fun err -> List.cons (errorText err) []) + + resultTracker.RegisterResult(input.Text, processResult') + processResult |> Result.iterError (errorText >> printer.Error) match processResult with @@ -306,7 +317,7 @@ module Orchestrator = categoryCounts[Url] batchWatch.ElapsedFriendly ) - batchResults.PrintBatchFailures() + resultTracker.PrintBatchFailures() if processedCount <= inputs.Length then let unprocessedInputs = From c080b4d21d0f14b5cdc892bbbbf890afb3c0590a Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 13 Nov 2026 21:12:49 +0900 Subject: [PATCH 11/45] RegisterResult() accepts any success type --- src/CCVTAC.Main/Orchestrator.fs | 16 ++++++---------- src/CCVTAC.Main/ResultTracker.fs | 7 ++++--- 2 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index fb9652bb..c2ea4c8c 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -69,7 +69,7 @@ module Orchestrator = (printer: Printer) (url: string) (settings: UserSettings) - (resultTracker: ResultTracker) + (resultTracker: ResultTracker) (history: History) (urlInputTime: DateTime) (batchSize: int) @@ -225,7 +225,7 @@ module Orchestrator = (inputs: CategorizedInput list) (categoryCounts: CategoryCounts) (settings: UserSettings) - (resultTracker: ResultTracker) + (resultTracker: ResultTracker) (history: History) : BatchResults = @@ -268,13 +268,9 @@ module Orchestrator = | input :: remainingInputs when nextAction' = Continue -> let processResult = processInput settings input.Category input.Text index - // TODO: Resolve this nasty, temporary workaround. - let processResult' = - processResult - |> Result.map _.ToString() - |> Result.mapError (fun err -> List.cons (errorText err) []) - - resultTracker.RegisterResult(input.Text, processResult') + resultTracker.RegisterResult( + input.Text, + processResult |> Result.mapError (fun err -> List.cons (errorText err) [])) processResult |> Result.iterError (errorText >> printer.Error) @@ -348,7 +344,7 @@ module Orchestrator = if not (isWorkingDirectoryReady printer settings.WorkingDirectory) then QuitDueToErrors else - let results = ResultTracker printer + let results = ResultTracker printer let history = History(settings.HistoryFile, settings.HistoryDisplayCount) let rec repl (currentSettings: UserSettings) : NextAction = diff --git a/src/CCVTAC.Main/ResultTracker.fs b/src/CCVTAC.Main/ResultTracker.fs index 664f882b..32690c4e 100644 --- a/src/CCVTAC.Main/ResultTracker.fs +++ b/src/CCVTAC.Main/ResultTracker.fs @@ -5,14 +5,14 @@ open CCFSharpUtils.Text open System open System.Collections.Generic -type ResultTracker<'a>(printer: Printer) = +type ResultTracker(printer: Printer) = let mutable successCount : uint64 = 0UL - let failures = Dictionary() + let failures = Dictionary() /// Logs the result for a specific corresponding input. - member _.RegisterResult(input: string, result: Result<'a, string list>) : unit = + member _.RegisterResult<'T>(input: string, result: Result<'T, string list>) : unit = match result with | Ok _ -> successCount <- successCount + 1UL @@ -21,6 +21,7 @@ type ResultTracker<'a>(printer: Printer) = if not (failures.TryAdd(input, msg)) then failures[input] <- msg + /// Prints any failures for the current batch. member _.PrintBatchFailures() : unit = if Num.isZero failures.Count then From 908fc6dfcbb1463713b477f5d9d3b28a84dd63d7 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:49:57 +0900 Subject: [PATCH 12/45] Rename variable --- src/CCVTAC.Main/Orchestrator.fs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index c2ea4c8c..da8a988c 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -97,11 +97,11 @@ module Orchestrator = match downloadResult with | Error errs -> - let msg = + let groupedErrs = errs |> List.map (sprintf "Media download error: %s") |> String.concat String.nl - Error (Recoverable msg) + Error (Recoverable groupedErrs) | Ok message -> printer.Debug "Download successful." if String.hasText message then printer.Info message From c0c82278f2bd15e0f1bfc97e35aa9042fed7eaa4 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 10:52:20 +0900 Subject: [PATCH 13/45] Rename func to extractValueFromCommand --- src/CCVTAC.Main/Orchestrator.fs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index da8a988c..fbba1e9f 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -115,14 +115,14 @@ module Orchestrator = printer.Info $"Processed '%s{url}'%s{groupClause} in %s{jobWatch.ElapsedFriendly}." Ok { NextAction = Continue; UpdatedSettings = None } - let summarizeToggle (settingName: string) (setting: bool) : string = + let summarizeToggle settingName setting : string = let state = if setting then "ON" else "OFF" $"%s{settingName} toggled to %s{state} for this session." - let summarizeUpdate (settingName: string) (setting: string) : string = + let summarizeUpdate settingName setting : string = $"%s{settingName} updated to \"%s{setting}\" for this session." - let private extractValue (prefix: string) (command: string) : string = + let private extractValueFromCommand (prefix: string) (command: string) : string = command.Substring(prefix.Length).Trim() let private toggleSpecs (printer: Printer) : ToggleSpec list = @@ -180,7 +180,7 @@ module Orchestrator = elif command |> String.startsWithIgnoreCase Commands.updateAudioFormatPrefix then let format = command - |> extractValue Commands.updateAudioFormatPrefix + |> extractValueFromCommand Commands.updateAudioFormatPrefix |> _.ToLowerInvariant() if String.hasNoText format then @@ -195,7 +195,7 @@ module Orchestrator = Ok { NextAction = Continue; UpdatedSettings = Some newSettings } elif command |> String.startsWithIgnoreCase Commands.updateAudioQualityPrefix then - let inputQuality = extractValue Commands.updateAudioQualityPrefix command + let inputQuality = extractValueFromCommand Commands.updateAudioQualityPrefix command let rangeRule = "Audio quality must be between 10 (lowest) and 0 (highest)." if String.hasNoText inputQuality then From 73cf675e1520fcb5cfeb4e24f98c2d2b59c94888 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:02:16 +0900 Subject: [PATCH 14/45] Tweak audio-quality block --- src/CCVTAC.Main/Orchestrator.fs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index fbba1e9f..0cb739ba 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -196,13 +196,14 @@ module Orchestrator = elif command |> String.startsWithIgnoreCase Commands.updateAudioQualityPrefix then let inputQuality = extractValueFromCommand Commands.updateAudioQualityPrefix command - let rangeRule = "Audio quality must be between 10 (lowest) and 0 (highest)." + let limit = 10uy + let rangeMsg = $"Audio quality must be between %d{limit} (lowest) and 0 (highest)." if String.hasNoText inputQuality then - Error rangeRule + Error rangeMsg else match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with - | true, quality when quality <= 10uy -> + | true, quality when quality <= limit -> match updateAudioQuality settings quality with | Error err -> Error err @@ -212,9 +213,9 @@ module Orchestrator = Ok { NextAction = Continue UpdatedSettings = Some updatedSettings } | true, _ -> - Error rangeRule + Error rangeMsg | _ -> - Error $"\"%s{inputQuality}\" is an invalid quality value. %s{rangeRule}" + Error $"\"%s{inputQuality}\" is an invalid quality value. %s{rangeMsg}" else Error $"\"%s{command}\" is not a valid command. Enter \"%c{Commands.prefix}help\" to see a list of commands." From 42376271f3d0e81b1a9b7c2aee0dc8b90a81a019 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:18:08 +0900 Subject: [PATCH 15/45] Use Result.map in update-quality block --- src/CCVTAC.Main/Orchestrator.fs | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 0cb739ba..3e017b7f 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -204,14 +204,10 @@ module Orchestrator = else match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with | true, quality when quality <= limit -> - match updateAudioQuality settings quality with - | Error err -> - Error err - | Ok updatedSettings -> - let updatedQuality = updatedSettings.AudioQuality.ToString() - printer.Info <| summarizeUpdate "Audio Quality" updatedQuality - Ok { NextAction = Continue - UpdatedSettings = Some updatedSettings } + updateAudioQuality settings quality + |> Result.map (fun newSettings -> + printer.Info <| summarizeUpdate "Audio Quality" (newSettings.AudioQuality.ToString()) + { NextAction = Continue; UpdatedSettings = Some newSettings }) | true, _ -> Error rangeMsg | _ -> From 6d990727e2c5dad255b39e3497ad8dc2e0b18bbd Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:29:12 +0900 Subject: [PATCH 16/45] Replace Result.map with monad CE --- src/CCVTAC.Main/Orchestrator.fs | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 3e017b7f..ded97506 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -204,10 +204,11 @@ module Orchestrator = else match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with | true, quality when quality <= limit -> - updateAudioQuality settings quality - |> Result.map (fun newSettings -> + monad { + let! newSettings = updateAudioQuality settings quality printer.Info <| summarizeUpdate "Audio Quality" (newSettings.AudioQuality.ToString()) - { NextAction = Continue; UpdatedSettings = Some newSettings }) + { NextAction = Continue; UpdatedSettings = Some newSettings } + } | true, _ -> Error rangeMsg | _ -> From d8d7d6afc24e5795f17acce4fa2c0e5a42896f46 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:34:25 +0900 Subject: [PATCH 17/45] Remove unneeded audio-quality error branch --- src/CCVTAC.Main/Orchestrator.fs | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index ded97506..64e99128 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -197,7 +197,7 @@ module Orchestrator = elif command |> String.startsWithIgnoreCase Commands.updateAudioQualityPrefix then let inputQuality = extractValueFromCommand Commands.updateAudioQualityPrefix command let limit = 10uy - let rangeMsg = $"Audio quality must be between %d{limit} (lowest) and 0 (highest)." + let rangeMsg = $"Audio quality must be a number between %d{limit} (lowest) and 0 (highest)." if String.hasNoText inputQuality then Error rangeMsg @@ -209,11 +209,7 @@ module Orchestrator = printer.Info <| summarizeUpdate "Audio Quality" (newSettings.AudioQuality.ToString()) { NextAction = Continue; UpdatedSettings = Some newSettings } } - | true, _ -> - Error rangeMsg - | _ -> - Error $"\"%s{inputQuality}\" is an invalid quality value. %s{rangeMsg}" - + | _ -> Error rangeMsg else Error $"\"%s{command}\" is not a valid command. Enter \"%c{Commands.prefix}help\" to see a list of commands." From 83c76f10525faa58cd5e006ac80e34812450a245 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:40:08 +0900 Subject: [PATCH 18/45] Remove superfluous empty-string check --- src/CCVTAC.Main/Orchestrator.fs | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 64e99128..6adde29b 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -199,17 +199,14 @@ module Orchestrator = let limit = 10uy let rangeMsg = $"Audio quality must be a number between %d{limit} (lowest) and 0 (highest)." - if String.hasNoText inputQuality then - Error rangeMsg - else - match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with - | true, quality when quality <= limit -> - monad { - let! newSettings = updateAudioQuality settings quality - printer.Info <| summarizeUpdate "Audio Quality" (newSettings.AudioQuality.ToString()) - { NextAction = Continue; UpdatedSettings = Some newSettings } - } - | _ -> Error rangeMsg + match Byte.TryParse(inputQuality, NumberStyles.None, CultureInfo.InvariantCulture) with + | true, quality when quality <= limit -> + monad { + let! newSettings = updateAudioQuality settings quality + printer.Info <| summarizeUpdate "Audio Quality" (newSettings.AudioQuality.ToString()) + { NextAction = Continue; UpdatedSettings = Some newSettings } + } + | _ -> Error rangeMsg else Error $"\"%s{command}\" is not a valid command. Enter \"%c{Commands.prefix}help\" to see a list of commands." From 7edb2bbf41597d47e9e172f49aafdc2dc82854d0 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:48:39 +0900 Subject: [PATCH 19/45] Use monad CE in audio-format updating too --- src/CCVTAC.Main/Orchestrator.fs | 15 +++++++-------- 1 file changed, 7 insertions(+), 8 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 6adde29b..6a801198 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -122,7 +122,7 @@ module Orchestrator = let summarizeUpdate settingName setting : string = $"%s{settingName} updated to \"%s{setting}\" for this session." - let private extractValueFromCommand (prefix: string) (command: string) : string = + let private extractCommandValue (prefix: string) (command: string) : string = command.Substring(prefix.Length).Trim() let private toggleSpecs (printer: Printer) : ToggleSpec list = @@ -180,22 +180,21 @@ module Orchestrator = elif command |> String.startsWithIgnoreCase Commands.updateAudioFormatPrefix then let format = command - |> extractValueFromCommand Commands.updateAudioFormatPrefix + |> extractCommandValue Commands.updateAudioFormatPrefix |> _.ToLowerInvariant() if String.hasNoText format then Error "Append one or more supported audio formats separated by commas (e.g., \"m4a,opus,best\")." else - match updateAudioFormat settings format with - | Error err -> - Error err - | Ok newSettings -> + monad { + let! newSettings = updateAudioFormat settings format let audioFormats = String.Join(", ", newSettings.AudioFormats) printer.Info <| summarizeUpdate "Audio Formats" audioFormats - Ok { NextAction = Continue; UpdatedSettings = Some newSettings } + { NextAction = Continue; UpdatedSettings = Some newSettings } + } elif command |> String.startsWithIgnoreCase Commands.updateAudioQualityPrefix then - let inputQuality = extractValueFromCommand Commands.updateAudioQualityPrefix command + let inputQuality = extractCommandValue Commands.updateAudioQualityPrefix command let limit = 10uy let rangeMsg = $"Audio quality must be a number between %d{limit} (lowest) and 0 (highest)." From dc6c9f5b4f295b4f01def18b3e040a0abba15aac Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 11:48:56 +0900 Subject: [PATCH 20/45] Improve 'invalid audio format' error message --- src/CCVTAC.Main/Settings/Settings.fs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CCVTAC.Main/Settings/Settings.fs b/src/CCVTAC.Main/Settings/Settings.fs index 9a71d56a..9f0ac448 100644 --- a/src/CCVTAC.Main/Settings/Settings.fs +++ b/src/CCVTAC.Main/Settings/Settings.fs @@ -157,7 +157,7 @@ module Settings = | { AudioFormats = fmt } when not (fmt |> List.forall validAudioFormat) -> let formats = String.Join(", ", fmt) let approved = supportedAudioFormats |> String.concat ", " - Error $"Audio formats (\"%s{formats}\") include an unsupported audio format.{String.nl}Only the following supported formats: {approved}." + Error $"Unsupported audio format(s) (\"%s{formats}\") found. Supported formats: {approved}." | _ -> Ok settings From dcd66e930202f9fdfb906aa03e5959c922af7888 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:07:07 +0900 Subject: [PATCH 21/45] Rename currentSettings params to settings --- src/CCVTAC.Main/Orchestrator.fs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 6a801198..4326f37d 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -234,13 +234,13 @@ module Orchestrator = printer.Info $"{String.nl}{sleptMsg}" printer.EmptyLine() - let processInput currentSettings inputCategory text index : Result = + let processInput settings inputCategory text index : Result = match inputCategory with | Command -> - processCommand printer text currentSettings history + processCommand printer text settings history |> Result.mapError Recoverable | Url -> - processUrl printer text currentSettings resultTracker history inputTime inputs.Length index + processUrl printer text settings resultTracker history inputTime inputs.Length index let deleteLeftoverFiles dirName : Result = match Directories.warnIfAnyFiles maxLeftoverFilesToShow dirName with @@ -337,21 +337,21 @@ module Orchestrator = let results = ResultTracker printer let history = History(settings.HistoryFile, settings.HistoryDisplayCount) - let rec repl (currentSettings: UserSettings) : NextAction = + let rec repl (settings: UserSettings) : NextAction = let input = printer.GetInput prompt match splitInputText input with | [] -> printer.Error $"Invalid input. Enter only URLs or commands beginning with \"%c{Commands.prefix}\"." - repl currentSettings + repl settings | splitInputs -> let categorizedInputs = categorizeInputs splitInputs let categoryCounts = countCategories categorizedInputs summarizeInput printer categorizedInputs categoryCounts let batchResult = - processBatch printer categorizedInputs categoryCounts currentSettings results history + processBatch printer categorizedInputs categoryCounts settings results history - let nextSettings = defaultArg batchResult.UpdatedSettings currentSettings + let nextSettings = defaultArg batchResult.UpdatedSettings settings match batchResult.NextAction with | Continue -> repl nextSettings From 881875617f6d3657d7183a7827270cd987eace0b Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:22:48 +0900 Subject: [PATCH 22/45] Minor code formatting --- src/CCVTAC.Main/Orchestrator.fs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 4326f37d..1eb2e5d1 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -297,12 +297,12 @@ module Orchestrator = loop inputs settings Continue 1 if categoryCounts[Url] > 1 then - printer.Info( + printer.Info <| sprintf "%sFinished with batch of %d URLs in %s." String.nl categoryCounts[Url] batchWatch.ElapsedFriendly - ) + resultTracker.PrintBatchFailures() if processedCount <= inputs.Length then From b489ae5a55993620fd2ae8123607d5110eb9ab6a Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 15:24:03 +0900 Subject: [PATCH 23/45] Unify int casts --- src/CCVTAC.Main/Program.fs | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/src/CCVTAC.Main/Program.fs b/src/CCVTAC.Main/Program.fs index bc66d7cd..50a5e229 100644 --- a/src/CCVTAC.Main/Program.fs +++ b/src/CCVTAC.Main/Program.fs @@ -52,15 +52,15 @@ module Program = match writeDefaultFile settingsFile with | Ok msg -> printer.Info msg - int ExitCodes.Success + ExitCodes.Success | Error err -> printer.Error err - int ExitCodes.OperationError + ExitCodes.OperationError else match read settingsFile with | Error err -> printer.Error err - int ExitCodes.ArgError + ExitCodes.ArgError | Ok settings -> printer.Info "Settings loaded OK." printer.PrintTable (toTable settings) @@ -70,13 +70,14 @@ module Program = try match Orchestrator.start printer settings with - | QuitDueToErrors -> int ExitCodes.OperationError - | _ -> int ExitCodes.Success + | QuitDueToErrors -> ExitCodes.OperationError + | _ -> ExitCodes.Success with exn -> printer.Critical $"Fatal error: {exn.Message}" AnsiConsole.WriteException exn printer.Info "Please help improve this tool by reporting this error and any relevant data (URLs, etc.) at https://github.com/codeconscious/ccvtac/issues." - int ExitCodes.OperationError + ExitCodes.OperationError + |> int [] let main args : int = From 1836383526b0519132f2fa060b6d6b90a989bbb2 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:17:18 +0900 Subject: [PATCH 24/45] Add and use Printer.Info() overload --- src/CCVTAC.Main/Orchestrator.fs | 8 ++++---- src/CCVTAC.Main/Printer.fs | 3 +++ 2 files changed, 7 insertions(+), 4 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 1eb2e5d1..97977243 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -297,12 +297,12 @@ module Orchestrator = loop inputs settings Continue 1 if categoryCounts[Url] > 1 then - printer.Info <| - sprintf "%sFinished with batch of %d URLs in %s." - String.nl + let batchDoneMsg = + sprintf "Finished with batch of %d URLs in %s." categoryCounts[Url] batchWatch.ElapsedFriendly - + let printOptions = { PrintOptions.Default with PrependLines = 1uy } + printer.Info(batchDoneMsg, printOptions) resultTracker.PrintBatchFailures() if processedCount <= inputs.Length then diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index f0ec2cd4..9a84fabe 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -124,6 +124,9 @@ type Printer(showDebug: bool) = member this.Info(message) = print Level.Info message None + member this.Info(message, options) = + print Level.Info message (Some options) + member this.Debug(message) = print Level.Debug message None From dc98df6d54e8376718b636c11d818b2ad65f3255 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:22:44 +0900 Subject: [PATCH 25/45] Shorten func name --- src/CCVTAC.Main/Orchestrator.fs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 97977243..8f73da41 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -315,7 +315,7 @@ module Orchestrator = { NextAction = finalNextAction UpdatedSettings = Some finalSettings } - let private isWorkingDirectoryReady (printer: Printer) dirName : bool = + let private isWorkingDirReady (printer: Printer) dirName = match Directories.warnIfAnyFiles maxLeftoverFilesToShow dirName with | Ok () -> true @@ -331,7 +331,7 @@ module Orchestrator = false let start printer settings : NextAction = - if not (isWorkingDirectoryReady printer settings.WorkingDirectory) then + if not (isWorkingDirReady printer settings.WorkingDirectory) then QuitDueToErrors else let results = ResultTracker printer From 5895fef5c2b4253eeff9357286c257b5a47180d1 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:31:13 +0900 Subject: [PATCH 26/45] Delete unused ResultTracker instance --- src/CCVTAC.Main/Orchestrator.fs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 8f73da41..a236927e 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -69,7 +69,6 @@ module Orchestrator = (printer: Printer) (url: string) (settings: UserSettings) - (resultTracker: ResultTracker) (history: History) (urlInputTime: DateTime) (batchSize: int) @@ -93,7 +92,6 @@ module Orchestrator = history.Append(url, urlInputTime, printer) let downloadResult = Downloader.run printer mediaType settings - resultTracker.RegisterResult(url, downloadResult) match downloadResult with | Error errs -> @@ -240,7 +238,7 @@ module Orchestrator = processCommand printer text settings history |> Result.mapError Recoverable | Url -> - processUrl printer text settings resultTracker history inputTime inputs.Length index + processUrl printer text settings history inputTime inputs.Length index let deleteLeftoverFiles dirName : Result = match Directories.warnIfAnyFiles maxLeftoverFilesToShow dirName with From b1b4781ae941f95eca869d79f6142a1ae520873c Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 16:59:18 +0900 Subject: [PATCH 27/45] Only sleep between URL inputs --- src/CCVTAC.Main/Orchestrator.fs | 26 ++++++++++++++------------ src/CCVTAC.Main/Printer.fs | 4 ++-- 2 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index a236927e..7f223183 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -220,17 +220,16 @@ module Orchestrator = let inputTime = DateTime.Now let batchWatch = Watch() - let printSleep currentSettings (inputCategory: InputCategory) = - if inputCategory.IsUrl then - let seconds = currentSettings.SleepSecondsBetweenURLs - let secondsMsg secs = String.plur' "second" S secs - let sleptMsg = - sleep - (fun remainingSeconds -> $"Sleeping for {secondsMsg remainingSeconds}...") - (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") - seconds - printer.Info $"{String.nl}{sleptMsg}" - printer.EmptyLine() + let printSleepCountdown currentSettings = + let seconds = currentSettings.SleepSecondsBetweenURLs + let secondsMsg secs = String.plur' "second" S secs + let sleptMsg = + sleep + (fun remainingSeconds -> $"Sleeping for {secondsMsg remainingSeconds}...") + (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") + seconds + let printOptions = { PrintOptions.Default with PrependLines = 1uy; AppendLines = 1uy } + printer.Info(sleptMsg, printOptions) let processInput settings inputCategory text index : Result = match inputCategory with @@ -278,7 +277,10 @@ module Orchestrator = (QuitDueToErrors, settings, index + 1) | Ok message -> message |> Option.iter printer.Debug - if List.isNotEmpty remainingInputs then printSleep settings input.Category + + let isNextUrl = remainingInputs |> tryHead |> exists _.Category.IsUrl + if input.Category.IsUrl && isNextUrl then + printSleepCountdown settings let updatedSettings, nextAction = match processResult with diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index 9a84fabe..d40c68b3 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -115,8 +115,8 @@ type Printer(showDebug: bool) = member this.Error(message) = print Level.Error message None - member this.Error(message, printOptions) = - print Level.Error message (Some printOptions) + member this.Error(message, options) = + print Level.Error message (Some options) member this.Warning(message) = print Level.Warning message None From ec1476c2654f2e6ac468880b15344160b950d00a Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 17:03:41 +0900 Subject: [PATCH 28/45] Add and use Printer.Warning() overload --- src/CCVTAC.Main/Downloading/Updater.fs | 13 +++++++------ src/CCVTAC.Main/Printer.fs | 3 +++ 2 files changed, 10 insertions(+), 6 deletions(-) diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index 3b212432..1ee2a4e5 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -18,14 +18,15 @@ module Updater = let executionResult = Runner.runTool printer toolSettings [] + let printOptions = { PrintOptions.Default with AppendLines = 1uy } + match executionResult with | Ok details -> if details.ExitCode <> successExitCode then - match details.Error with - | Some errMsg -> $"Update completed with minor issues: {errMsg}" - | None -> "Update completed with minor unspecified issues." - |> printer.Warning - printer.EmptyLine() + let msg = + match details.Error with + | Some errMsg -> $"Update completed with minor issues: {errMsg}" + | None -> "Update completed with minor unspecified issues." + printer.Warning(msg, printOptions) | Error msg -> - let printOptions = { PrintOptions.Default with AppendLines = 1uy } printer.Error($"Failure updating: {msg}", printOptions) diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index d40c68b3..bf70424b 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -121,6 +121,9 @@ type Printer(showDebug: bool) = member this.Warning(message) = print Level.Warning message None + member this.Warning(message, options) = + print Level.Warning message (Some options) + member this.Info(message) = print Level.Info message None From cef343a84a4253b2f844d60a47857368f172fd05 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:04:17 +0900 Subject: [PATCH 29/45] Update packages --- src/CCVTAC.Main/CCVTAC.Main.fsproj | 4 ++-- src/CCVTAC.Main/IoUtilities/Files.fs | 2 +- src/CCVTAC.Main/Orchestrator.fs | 4 ++-- src/CCVTAC.Tests/CCVTAC.Tests.fsproj | 6 +++--- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/CCVTAC.Main/CCVTAC.Main.fsproj b/src/CCVTAC.Main/CCVTAC.Main.fsproj index 864d6480..06eab378 100644 --- a/src/CCVTAC.Main/CCVTAC.Main.fsproj +++ b/src/CCVTAC.Main/CCVTAC.Main.fsproj @@ -40,12 +40,12 @@ - + - + diff --git a/src/CCVTAC.Main/IoUtilities/Files.fs b/src/CCVTAC.Main/IoUtilities/Files.fs index 442dea51..1d25e6a2 100644 --- a/src/CCVTAC.Main/IoUtilities/Files.fs +++ b/src/CCVTAC.Main/IoUtilities/Files.fs @@ -14,7 +14,7 @@ module Files = let imageFileExts = [".jpg"; ".jpeg"] - let filterByExt ext fs = fs |> List.filter (String.endsWithIgnoreCase ext) + let filterByExt ext fs = fs |> List.filter (String.endsWith' ext) let readAllText (filePath: string) : Result = ofTry (fun _ -> File.ReadAllText filePath) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 7f223183..6b77936a 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -175,7 +175,7 @@ module Orchestrator = printer.PrintTable (toTable settings) Ok { NextAction = Continue; UpdatedSettings = None } - elif command |> String.startsWithIgnoreCase Commands.updateAudioFormatPrefix then + elif command |> String.startsWith' Commands.updateAudioFormatPrefix then let format = command |> extractCommandValue Commands.updateAudioFormatPrefix @@ -191,7 +191,7 @@ module Orchestrator = { NextAction = Continue; UpdatedSettings = Some newSettings } } - elif command |> String.startsWithIgnoreCase Commands.updateAudioQualityPrefix then + elif command |> String.startsWith' Commands.updateAudioQualityPrefix then let inputQuality = extractCommandValue Commands.updateAudioQualityPrefix command let limit = 10uy let rangeMsg = $"Audio quality must be a number between %d{limit} (lowest) and 0 (highest)." diff --git a/src/CCVTAC.Tests/CCVTAC.Tests.fsproj b/src/CCVTAC.Tests/CCVTAC.Tests.fsproj index c0b0cd20..42de9407 100644 --- a/src/CCVTAC.Tests/CCVTAC.Tests.fsproj +++ b/src/CCVTAC.Tests/CCVTAC.Tests.fsproj @@ -14,8 +14,8 @@ - - + + runtime; build; native; contentfiles; analyzers; buildtransitive @@ -25,7 +25,7 @@ runtime; build; native; contentfiles; analyzers; buildtransitive all - + From db5808dc93d63bbf6ed0e2e213022a09524aea8e Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:06:37 +0900 Subject: [PATCH 30/45] Rename variable --- src/CCVTAC.Main/Orchestrator.fs | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 6b77936a..370dc04f 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -4,7 +4,6 @@ open CCVTAC.Main.Downloading open CCVTAC.Main.InputHelper open CCVTAC.Main.IoUtilities open CCVTAC.Main.PostProcessing -open CCVTAC.Main.Settings open CCVTAC.Main.Settings.Settings open CCVTAC.Main.Settings.Settings.LiveUpdating open CCFSharpUtils.Collections @@ -155,9 +154,9 @@ module Orchestrator = | None -> if String.equalIgnoreCase Commands.helpCommand command then - for kvp in Commands.summary do - printer.Info kvp.Key - printer.Info $" %s{kvp.Value}" + for pair in Commands.summary do + printer.Info pair.Key + printer.Info $" %s{pair.Value}" Ok { NextAction = Continue; UpdatedSettings = None } elif checkCommand Commands.quitCommands then From a3017c6c1123698e053154b087ba4090a58a85c0 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sat, 14 Nov 2026 22:27:47 +0900 Subject: [PATCH 31/45] Use List.singleton over List.cons --- src/CCVTAC.Main/Orchestrator.fs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 370dc04f..b8a93d7a 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -256,7 +256,7 @@ module Orchestrator = resultTracker.RegisterResult( input.Text, - processResult |> Result.mapError (fun err -> List.cons (errorText err) [])) + processResult |> Result.mapError (errorText >> List.singleton)) processResult |> Result.iterError (errorText >> printer.Error) From 8dd1d7ce346f5ff3d56561da917697b469617464 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sun, 15 Nov 2026 17:52:19 +0900 Subject: [PATCH 32/45] Improve display of URL indexes in messages AI comment: Misleading progress numbers. processUrl receives inputs.Length as batchSize and the loop's index counts commands as well as URLs. A batch such as URL, :quiet, URL reports "item 3 of 3" for the second URL. Consider counting only URL inputs, or using categoryCounts[Url] for the denominator. --- src/CCVTAC.Main/Orchestrator.fs | 29 +++++++++++++++++++---------- 1 file changed, 19 insertions(+), 10 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index b8a93d7a..6375f52d 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -79,7 +79,9 @@ module Orchestrator = Error (Fatal err) | Ok () -> if batchSize > 1 then - printer.Info $"Processing item %d{urlIndex} of %d{batchSize}..." + let options = { PrintOptions.Default with PrependLines = 1uy } + let message = $"Processing URL %d{urlIndex} of %d{batchSize}..." + printer.Info(message, options) let jobWatch = Watch() @@ -148,8 +150,12 @@ module Orchestrator = match toggle with | Some spec -> let newSettings = spec.Toggle settings - printer.Info <| summarizeToggle spec.Label (spec.Read newSettings) + + let options = { PrintOptions.Default with PrependLines = 1uy } + let message = summarizeToggle spec.Label (spec.Read newSettings) + printer.Info(message, options) spec.AfterToggle newSettings + Ok { NextAction = Continue; UpdatedSettings = Some newSettings } | None -> @@ -230,13 +236,13 @@ module Orchestrator = let printOptions = { PrintOptions.Default with PrependLines = 1uy; AppendLines = 1uy } printer.Info(sleptMsg, printOptions) - let processInput settings inputCategory text index : Result = + let processInput settings inputCategory text urlPosition : Result = match inputCategory with | Command -> processCommand printer text settings history |> Result.mapError Recoverable | Url -> - processUrl printer text settings history inputTime inputs.Length index + processUrl printer text settings history inputTime categoryCounts[Url] urlPosition let deleteLeftoverFiles dirName : Result = match Directories.warnIfAnyFiles maxLeftoverFilesToShow dirName with @@ -249,10 +255,10 @@ module Orchestrator = Some "Files deleted successfully.") |> Result.mapError (sprintf "Error deleting leftover files after download: %s") - let rec loop inputs settings nextAction' index : NextAction * UserSettings * int = + let rec loop inputs settings nextAction' index urlPosition : NextAction * UserSettings * int = match inputs with | input :: remainingInputs when nextAction' = Continue -> - let processResult = processInput settings input.Category input.Text index + let processResult = processInput settings input.Category input.Text urlPosition resultTracker.RegisterResult( input.Text, @@ -262,7 +268,6 @@ module Orchestrator = match processResult with | Error (Fatal _) -> - // The item was not processed, so `index` (not index + 1) keeps it in the unprocessed list. (QuitDueToErrors, settings, index) | _ -> let cleanupResult = @@ -288,12 +293,16 @@ module Orchestrator = | Error _ -> settings, nextAction' - loop remainingInputs updatedSettings nextAction (index + 1) + // Advance the URL position only when the input was a URL. + let nextUrlPosition = + if input.Category.IsUrl then urlPosition + 1 else urlPosition + + loop remainingInputs updatedSettings nextAction (index + 1) nextUrlPosition | _ -> (nextAction', settings, index) - let (finalNextAction, finalSettings, processedCount) = - loop inputs settings Continue 1 + let finalNextAction, finalSettings, processedCount = + loop inputs settings Continue 1 1 if categoryCounts[Url] > 1 then let batchDoneMsg = From c7cfb8b16f3f8c42de57a3cda9040698e0ddfda9 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:16:45 +0900 Subject: [PATCH 33/45] Adjust empty lines; rename Printer type's methods --- src/CCVTAC.Main/Downloading/Updater.fs | 12 ++++-------- src/CCVTAC.Main/Orchestrator.fs | 11 +++++------ src/CCVTAC.Main/Printer.fs | 14 ++++++-------- src/CCVTAC.Main/Program.fs | 3 ++- src/CCVTAC.Main/ResultTracker.fs | 3 ++- 5 files changed, 19 insertions(+), 24 deletions(-) diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index 1ee2a4e5..51c31cdd 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -11,22 +11,18 @@ module Updater = let run (printer: Printer) userSettings : unit = if String.hasNoText userSettings.DownloaderUpdateCommand then - printer.Info "No downloader update command provided, so will skip." + printer.Info "No downloader update command provided, so will skip the update." else let toolSettings = ToolSettings.create userSettings.DownloaderUpdateCommand userSettings.WorkingDirectory - let executionResult = Runner.runTool printer toolSettings [] - - let printOptions = { PrintOptions.Default with AppendLines = 1uy } - - match executionResult with + match Runner.runTool printer toolSettings [] with | Ok details -> if details.ExitCode <> successExitCode then let msg = match details.Error with | Some errMsg -> $"Update completed with minor issues: {errMsg}" | None -> "Update completed with minor unspecified issues." - printer.Warning(msg, printOptions) + printer.Warning msg | Error msg -> - printer.Error($"Failure updating: {msg}", printOptions) + printer.Error $"Failure updating: {msg}" diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 6375f52d..ecbf6e29 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -62,8 +62,6 @@ module Orchestrator = for input in inputs do printer.Info $" • %s{input.Text}" - printer.EmptyLine() - let processUrl (printer: Printer) (url: string) @@ -79,7 +77,7 @@ module Orchestrator = Error (Fatal err) | Ok () -> if batchSize > 1 then - let options = { PrintOptions.Default with PrependLines = 1uy } + let options = { PrintOptions.Default with LinesBefore = 1uy } let message = $"Processing URL %d{urlIndex} of %d{batchSize}..." printer.Info(message, options) @@ -151,9 +149,10 @@ module Orchestrator = | Some spec -> let newSettings = spec.Toggle settings - let options = { PrintOptions.Default with PrependLines = 1uy } let message = summarizeToggle spec.Label (spec.Read newSettings) + let options = { PrintOptions.Default with LinesBefore = 1uy } printer.Info(message, options) + spec.AfterToggle newSettings Ok { NextAction = Continue; UpdatedSettings = Some newSettings } @@ -233,7 +232,7 @@ module Orchestrator = (fun remainingSeconds -> $"Sleeping for {secondsMsg remainingSeconds}...") (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") seconds - let printOptions = { PrintOptions.Default with PrependLines = 1uy; AppendLines = 1uy } + let printOptions = { PrintOptions.Default with LinesBefore = 1uy } printer.Info(sleptMsg, printOptions) let processInput settings inputCategory text urlPosition : Result = @@ -309,7 +308,7 @@ module Orchestrator = sprintf "Finished with batch of %d URLs in %s." categoryCounts[Url] batchWatch.ElapsedFriendly - let printOptions = { PrintOptions.Default with PrependLines = 1uy } + let printOptions = { PrintOptions.Default with LinesBefore = 1uy } printer.Info(batchDoneMsg, printOptions) resultTracker.PrintBatchFailures() diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index bf70424b..4e81a810 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -21,14 +21,14 @@ type private Colors = type PrintOptions = { AppendLineBreak: bool - PrependLines: byte - AppendLines: byte + LinesBefore: byte + LinesAfter: byte ProcessMarkup: bool } static member Default = { AppendLineBreak = true - PrependLines = 0uy - AppendLines = 0uy + LinesBefore = 0uy + LinesAfter = 0uy ProcessMarkup = true } type Printer(showDebug: bool) = @@ -87,7 +87,7 @@ type Printer(showDebug: bool) = if String.hasNoText message then raise (ArgumentException(nameof(message), "Message cannot be empty.")) - printEmptyLines printOptions.PrependLines + printEmptyLines printOptions.LinesBefore let escapedMessage = escapeText message @@ -100,7 +100,7 @@ type Printer(showDebug: bool) = if printOptions.AppendLineBreak then AnsiConsole.WriteLine() - printEmptyLines printOptions.AppendLines + printEmptyLines printOptions.LinesAfter /// Toggle showing or hiding debug messages. member this.ShowDebug(shouldEnable) = @@ -133,8 +133,6 @@ type Printer(showDebug: bool) = member this.Debug(message) = print Level.Debug message None - member this.EmptyLine() = printEmptyLines 1uy - member this.GetInput(prompt) : string = printEmptyLines 1uy AnsiConsole.Ask($"[skyblue1]{prompt}[/]") diff --git a/src/CCVTAC.Main/Program.fs b/src/CCVTAC.Main/Program.fs index 50a5e229..f5c1501d 100644 --- a/src/CCVTAC.Main/Program.fs +++ b/src/CCVTAC.Main/Program.fs @@ -37,7 +37,8 @@ module Program = let private registerCancelHandler (printer: Printer) workingDirectory = Console.CancelKeyPress.Add(fun _ -> - printer.Warning $"{String.nl}Quitting at user's request." + let options = { PrintOptions.Default with LinesBefore = 1uy } + printer.Warning($"Quitting at user's request.", options) match Directories.warnIfAnyFiles 10 workingDirectory with | Ok () -> () diff --git a/src/CCVTAC.Main/ResultTracker.fs b/src/CCVTAC.Main/ResultTracker.fs index 32690c4e..f045e9da 100644 --- a/src/CCVTAC.Main/ResultTracker.fs +++ b/src/CCVTAC.Main/ResultTracker.fs @@ -37,7 +37,8 @@ type ResultTracker(printer: Printer) = let successSummary = String.plur' "success" Es successCount let failureSummary = String.plur' "failure" S failures.Count - printer.Info $"Quitting with %s{successSummary} and %s{failureSummary}." + let options = { PrintOptions.Default with LinesBefore = 1uy } + printer.Info($"Quitting with %s{successSummary} and %s{failureSummary}.", options) for pair in failures do printer.Warning $"- %s{pair.Key}: %s{pair.Value}" From e34f85e48f238f58bc72089b381ddcc5a89cd019 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sun, 15 Nov 2026 22:31:53 +0900 Subject: [PATCH 34/45] Minor code layout tweaks --- src/CCVTAC.Main/Orchestrator.fs | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index ecbf6e29..9446e8c4 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -15,7 +15,10 @@ open System.Globalization module Orchestrator = - type NextAction = Continue | QuitAtUserRequest | QuitDueToErrors + type NextAction = + | Continue + | QuitAtUserRequest + | QuitDueToErrors type BatchResults = { NextAction: NextAction @@ -37,7 +40,7 @@ module Orchestrator = [] let private maxLeftoverFilesToShow = 10 - let private errorText (error: ProcessError) : string = + let private errorText error : string = match error with | Recoverable msg | Fatal msg -> msg @@ -49,7 +52,7 @@ module Orchestrator = : unit = if List.hasMultiple inputs then - let urlSummary = String.plur' "URL" S counts[Url] + let urlSummary = String.plur' "URL" S counts[Url] let cmdSummary = String.plur' "command" S counts[Command] printer.Info <| From baecc08e8f10883df1769524e6d74263de50de69 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:47:07 +0900 Subject: [PATCH 35/45] Remove unneeded parens --- src/CCVTAC.Main/Printer.fs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index 4e81a810..004368ae 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -104,7 +104,7 @@ type Printer(showDebug: bool) = /// Toggle showing or hiding debug messages. member this.ShowDebug(shouldEnable) = - minimumLogLevel <- (if shouldEnable then Level.Debug else Level.Info) + minimumLogLevel <- if shouldEnable then Level.Debug else Level.Info member this.PrintTable(table: Table) = AnsiConsole.Write table From 8cd32aea65dd4254ab438b72cd1b20321897507d Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:59:26 +0900 Subject: [PATCH 36/45] Add PrintOptions.DefaultWithLineBefore --- src/CCVTAC.Main/Orchestrator.fs | 18 +++++++++--------- src/CCVTAC.Main/Printer.fs | 3 +++ 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 9446e8c4..69e06390 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -15,9 +15,9 @@ open System.Globalization module Orchestrator = - type NextAction = - | Continue - | QuitAtUserRequest + type NextAction = + | Continue + | QuitAtUserRequest | QuitDueToErrors type BatchResults = @@ -80,7 +80,7 @@ module Orchestrator = Error (Fatal err) | Ok () -> if batchSize > 1 then - let options = { PrintOptions.Default with LinesBefore = 1uy } + let options = PrintOptions.DefaultWithLineBefore let message = $"Processing URL %d{urlIndex} of %d{batchSize}..." printer.Info(message, options) @@ -153,7 +153,7 @@ module Orchestrator = let newSettings = spec.Toggle settings let message = summarizeToggle spec.Label (spec.Read newSettings) - let options = { PrintOptions.Default with LinesBefore = 1uy } + let options = PrintOptions.DefaultWithLineBefore printer.Info(message, options) spec.AfterToggle newSettings @@ -235,8 +235,8 @@ module Orchestrator = (fun remainingSeconds -> $"Sleeping for {secondsMsg remainingSeconds}...") (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") seconds - let printOptions = { PrintOptions.Default with LinesBefore = 1uy } - printer.Info(sleptMsg, printOptions) + let options = PrintOptions.DefaultWithLineBefore + printer.Info(sleptMsg, options) let processInput settings inputCategory text urlPosition : Result = match inputCategory with @@ -311,8 +311,8 @@ module Orchestrator = sprintf "Finished with batch of %d URLs in %s." categoryCounts[Url] batchWatch.ElapsedFriendly - let printOptions = { PrintOptions.Default with LinesBefore = 1uy } - printer.Info(batchDoneMsg, printOptions) + let options = PrintOptions.DefaultWithLineBefore + printer.Info(batchDoneMsg, options) resultTracker.PrintBatchFailures() if processedCount <= inputs.Length then diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index 004368ae..7da1cd89 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -31,6 +31,9 @@ type PrintOptions = LinesAfter = 0uy ProcessMarkup = true } + static member DefaultWithLineBefore = + { PrintOptions.Default with LinesBefore = 1uy } + type Printer(showDebug: bool) = let colorMap: Map = From cf2aebcd2d6d5f76527cca8f7a83b08e09742152 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Mon, 16 Nov 2026 20:34:32 +0900 Subject: [PATCH 37/45] Use Option.ofPair with TryParse --- src/CCVTAC.Main/History.fs | 7 ++++--- src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs | 6 +++--- 2 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/CCVTAC.Main/History.fs b/src/CCVTAC.Main/History.fs index d16c6cf0..c3c04bad 100644 --- a/src/CCVTAC.Main/History.fs +++ b/src/CCVTAC.Main/History.fs @@ -6,6 +6,7 @@ open CCFSharpUtils.Text open System open System.IO open System.Text.Json +open FSharpPlus open Spectre.Console type History(filePath: string, displayCount: int) = @@ -39,9 +40,9 @@ type History(filePath: string, displayCount: int) = |> Seq.choose (fun line -> match line.Split separator with | [| dateText; url |] -> - match DateTime.TryParse dateText with - | true, date -> Some (date, url) - | _ -> None + DateTime.TryParse dateText + |> Option.ofPair + |> Option.map (fun date -> (date, url)) | _ -> None) |> Seq.groupBy fst |> Seq.map (fun (dt, pairs) -> dt, pairs |> Seq.map snd |> Seq.toList) diff --git a/src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs b/src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs index e1dba8dc..57b462d3 100644 --- a/src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs +++ b/src/CCVTAC.Main/PostProcessing/Tagging/Tagger.fs @@ -7,6 +7,7 @@ open CCVTAC.Main.PostProcessing.Tagging open CCVTAC.Main.Downloading.Downloading open CCFSharpUtils.Collections open CCFSharpUtils.Text +open FSharpPlus open Startwatch.Library open MetadataUtilities open System @@ -66,9 +67,8 @@ module Tagger = elif videoMetadata.UploadDate.Length <> 4 then None else - match UInt32.TryParse(videoMetadata.UploadDate.Substring(0, 4)) with - | true, parsed -> Some parsed - | _ -> None + UInt32.TryParse(videoMetadata.UploadDate.Substring(0, 4)) + |> Option.ofPair let private tagSingleFile (printer: Printer) From 1c4324c64e379c49ecb83c2c42292028655f092a Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:14:22 +0900 Subject: [PATCH 38/45] Remove PrintOptions.LineAfter --- src/CCVTAC.Main/Printer.fs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index 7da1cd89..c6b2bdeb 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -22,13 +22,11 @@ type private Colors = type PrintOptions = { AppendLineBreak: bool LinesBefore: byte - LinesAfter: byte ProcessMarkup: bool } static member Default = { AppendLineBreak = true LinesBefore = 0uy - LinesAfter = 0uy ProcessMarkup = true } static member DefaultWithLineBefore = @@ -103,8 +101,6 @@ type Printer(showDebug: bool) = if printOptions.AppendLineBreak then AnsiConsole.WriteLine() - printEmptyLines printOptions.LinesAfter - /// Toggle showing or hiding debug messages. member this.ShowDebug(shouldEnable) = minimumLogLevel <- if shouldEnable then Level.Debug else Level.Info From 91e41e0993cac3c1546e2eb8db11a52e0358bd5d Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:00:30 +0900 Subject: [PATCH 39/45] Heavy rework of temp file confirmation and deletion; etc. --- src/CCVTAC.Main/IoUtilities/Directories.fs | 14 +++--- src/CCVTAC.Main/Orchestrator.fs | 46 ++++++++++--------- .../PostProcessing/PostProcessing.fs | 2 +- src/CCVTAC.Main/Printer.fs | 1 + src/CCVTAC.Main/Program.fs | 20 +++----- src/CCVTAC.Main/ResultTracker.fs | 2 +- src/CCVTAC.Main/Shared.fs | 2 + 7 files changed, 44 insertions(+), 43 deletions(-) diff --git a/src/CCVTAC.Main/IoUtilities/Directories.fs b/src/CCVTAC.Main/IoUtilities/Directories.fs index b077743b..59ae8c67 100644 --- a/src/CCVTAC.Main/IoUtilities/Directories.fs +++ b/src/CCVTAC.Main/IoUtilities/Directories.fs @@ -11,6 +11,9 @@ module Directories = [] let private allFilesSearchPattern = "*" + [] + let maxFilesToShow = 10 + /// Counts the number of audio files in a directory. let audioFileCount dirName includedExtensions = DirectoryInfo(dirName).EnumerateFiles() @@ -46,10 +49,9 @@ module Directories = |> Result.map delete /// Ask the user to confirm the deletion of files in the specified directory. - let askToDeleteAllFiles (printer: Printer) dirName = - if printer.AskToBool("Delete all temporary files?", "Yes", "No") - then deleteAllFiles dirName - else Error "Will not delete the files." + let confirmDeleteFiles (printer: Printer) : YesNoAnswer = + let answer = printer.AskToBool("Delete all temporary files?", "Yes", "No") + if answer then Yes else No (Some "Temporary file deletion was declined.") let printDeletionResults (printer: Printer) (results: ResultMessages) : unit = printer.Info $"Deleted %s{String.fileLabel results.Successes.Length}." @@ -66,12 +68,12 @@ module Directories = if Array.isEmpty fileNames then Ok () else - SB($"Unexpectedly found {String.fileLabel fileNames.Length} in working directory \"{dirName}\":{String.nl}") + SB($"""Found {String.plur' "leftover file" S fileNames.Length} leftover in working directory \"{dirName}\":{String.nl}""") .AppendLine (fileNames |> Array.truncate showMax |> Array.map (sprintf "• %s") - |> String.concat String.nl) + |> String.concatNL) |> fun sb -> if fileNames.Length > showMax then sb.AppendLine $"... plus {fileNames.Length - showMax} more." diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 69e06390..f8a84930 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -37,9 +37,6 @@ module Orchestrator = Read: UserSettings -> bool AfterToggle: UserSettings -> unit } - [] - let private maxLeftoverFilesToShow = 10 - let private errorText error : string = match error with | Recoverable msg @@ -75,7 +72,7 @@ module Orchestrator = (urlIndex: int) : Result = - match Directories.warnIfAnyFiles maxLeftoverFilesToShow settings.WorkingDirectory with + match Directories.warnIfAnyFiles Directories.maxFilesToShow settings.WorkingDirectory with | Error err -> Error (Fatal err) | Ok () -> @@ -100,7 +97,7 @@ module Orchestrator = let groupedErrs = errs |> List.map (sprintf "Media download error: %s") - |> String.concat String.nl + |> String.concatNL Error (Recoverable groupedErrs) | Ok message -> printer.Debug "Download successful." @@ -247,7 +244,7 @@ module Orchestrator = processUrl printer text settings history inputTime categoryCounts[Url] urlPosition let deleteLeftoverFiles dirName : Result = - match Directories.warnIfAnyFiles maxLeftoverFilesToShow dirName with + match Directories.warnIfAnyFiles Directories.maxFilesToShow dirName with | Ok () -> Ok None | Error msg -> printer.Warning msg @@ -319,31 +316,36 @@ module Orchestrator = let unprocessedInputs = inputs[processedCount-1..] |> List.map (fun x -> $"• {x.Text}") - |> String.concat String.nl + |> String.concatNL printer.Warning $"Some inputs were not yet processed: {String.nl}{unprocessedInputs}" { NextAction = finalNextAction UpdatedSettings = Some finalSettings } - let private isWorkingDirReady (printer: Printer) dirName = - match Directories.warnIfAnyFiles maxLeftoverFilesToShow dirName with - | Ok () -> - true + let private isWorkingDirReady (printer: Printer) dirName : Result = + let emptyDirAndReport dirName = + match Directories.deleteAllFiles dirName with + | Ok results -> + Directories.printDeletionResults printer results + printer.Debug "Files deleted." + Ok () + | Error deletionError -> Error deletionError + + match Directories.warnIfAnyFiles Directories.maxFilesToShow dirName with + | Ok () -> Ok () | Error err -> printer.Error err - match Directories.askToDeleteAllFiles printer dirName with - | Ok results -> - Directories.printDeletionResults printer results - true - | Error deletionError -> - printer.Error deletionError - printer.Info "Aborting..." - false + match Directories.confirmDeleteFiles printer with + | No reason -> Error (defaultArg reason $"File deletion declined for \"{dirName}\".") + | Yes -> emptyDirAndReport dirName let start printer settings : NextAction = - if not (isWorkingDirReady printer settings.WorkingDirectory) then - QuitDueToErrors - else + match isWorkingDirReady printer settings.WorkingDirectory with + | Error err -> + printer.Error err + printer.Error "Cannot continue until the working directory is emptied. Quitting..." + QuitDueToErrors // TODO: Modify QuitDueToErrors type to include optional errors? + | Ok () -> let results = ResultTracker printer let history = History(settings.HistoryFile, settings.HistoryDisplayCount) diff --git a/src/CCVTAC.Main/PostProcessing/PostProcessing.fs b/src/CCVTAC.Main/PostProcessing/PostProcessing.fs index 4f3fc0ba..09457dfd 100644 --- a/src/CCVTAC.Main/PostProcessing/PostProcessing.fs +++ b/src/CCVTAC.Main/PostProcessing/PostProcessing.fs @@ -48,7 +48,7 @@ module PostProcessor = | Ok ts -> Ok ts | Error errMsgs -> $"Error(s) creating tagging sets in working directory \"%s{dir}\"" :: errMsgs - |> String.concat String.nl + |> String.concatNL |> Error with exn -> Error $"Error reading working files in \"{dir}\" for tagging set creation: %s{exn.Message}" diff --git a/src/CCVTAC.Main/Printer.fs b/src/CCVTAC.Main/Printer.fs index c6b2bdeb..338f0106 100644 --- a/src/CCVTAC.Main/Printer.fs +++ b/src/CCVTAC.Main/Printer.fs @@ -138,3 +138,4 @@ type Printer(showDebug: bool) = member this.AskToBool(question, yesAnswer, noAnswer) : bool = (ask question [ yesAnswer; noAnswer ]) = yesAnswer + diff --git a/src/CCVTAC.Main/Program.fs b/src/CCVTAC.Main/Program.fs index f5c1501d..b146e70b 100644 --- a/src/CCVTAC.Main/Program.fs +++ b/src/CCVTAC.Main/Program.fs @@ -35,18 +35,10 @@ module Program = | _ -> ShowHelp - let private registerCancelHandler (printer: Printer) workingDirectory = + let private registerCancelHandler (printer: Printer) : unit = + // Exits with error code 130, meaning termination by SIGINT (Ctrl‑C). Console.CancelKeyPress.Add(fun _ -> - let options = { PrintOptions.Default with LinesBefore = 1uy } - printer.Warning($"Quitting at user's request.", options) - - match Directories.warnIfAnyFiles 10 workingDirectory with - | Ok () -> () - | Error warnResult -> - printer.Error warnResult - match Directories.askToDeleteAllFiles printer workingDirectory with - | Error err -> printer.Error err - | Ok results -> Directories.printDeletionResults printer results) + printer.Warning("Quitting by request.", PrintOptions.DefaultWithLineBefore)) let private run (printer: Printer) (settingsFile: FileInfo) : int = if not settingsFile.Exists then @@ -67,7 +59,7 @@ module Program = printer.PrintTable (toTable settings) printer.ShowDebug(not settings.QuietMode) - registerCancelHandler printer settings.WorkingDirectory + registerCancelHandler printer try match Orchestrator.start printer settings with @@ -76,7 +68,9 @@ module Program = with exn -> printer.Critical $"Fatal error: {exn.Message}" AnsiConsole.WriteException exn - printer.Info "Please help improve this tool by reporting this error and any relevant data (URLs, etc.) at https://github.com/codeconscious/ccvtac/issues." + printer.Info "Please help improve this tool by reporting this error \ + with any relevant data (URLs, settings, etc.) at \ + https://github.com/codeconscious/ccvtac/issues." ExitCodes.OperationError |> int diff --git a/src/CCVTAC.Main/ResultTracker.fs b/src/CCVTAC.Main/ResultTracker.fs index f045e9da..66b71f9f 100644 --- a/src/CCVTAC.Main/ResultTracker.fs +++ b/src/CCVTAC.Main/ResultTracker.fs @@ -37,7 +37,7 @@ type ResultTracker(printer: Printer) = let successSummary = String.plur' "success" Es successCount let failureSummary = String.plur' "failure" S failures.Count - let options = { PrintOptions.Default with LinesBefore = 1uy } + let options = PrintOptions.DefaultWithLineBefore printer.Info($"Quitting with %s{successSummary} and %s{failureSummary}.", options) for pair in failures do diff --git a/src/CCVTAC.Main/Shared.fs b/src/CCVTAC.Main/Shared.fs index 5a26f1a8..e505b532 100644 --- a/src/CCVTAC.Main/Shared.fs +++ b/src/CCVTAC.Main/Shared.fs @@ -23,3 +23,5 @@ module Shared = |> loop seconds) doneMsgFn seconds + + type YesNoAnswer = Yes | No of Reason: string option From ed9b77a0a4b45eac39e31a2b4a065ae522a05900 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:34:58 +0900 Subject: [PATCH 40/45] Rename YesNoAnswer to ConfirmationAnswer, and remove 'option' --- src/CCVTAC.Main/IoUtilities/Directories.fs | 4 ++-- src/CCVTAC.Main/Orchestrator.fs | 4 ++-- src/CCVTAC.Main/Shared.fs | 2 +- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/CCVTAC.Main/IoUtilities/Directories.fs b/src/CCVTAC.Main/IoUtilities/Directories.fs index 59ae8c67..b89ad9bf 100644 --- a/src/CCVTAC.Main/IoUtilities/Directories.fs +++ b/src/CCVTAC.Main/IoUtilities/Directories.fs @@ -49,9 +49,9 @@ module Directories = |> Result.map delete /// Ask the user to confirm the deletion of files in the specified directory. - let confirmDeleteFiles (printer: Printer) : YesNoAnswer = + let confirmDeleteFiles (printer: Printer) : ConfirmationAnswer = let answer = printer.AskToBool("Delete all temporary files?", "Yes", "No") - if answer then Yes else No (Some "Temporary file deletion was declined.") + if answer then Proceed else Decline "Temporary file deletion was declined." let printDeletionResults (printer: Printer) (results: ResultMessages) : unit = printer.Info $"Deleted %s{String.fileLabel results.Successes.Length}." diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index f8a84930..272b0d0a 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -336,8 +336,8 @@ module Orchestrator = | Error err -> printer.Error err match Directories.confirmDeleteFiles printer with - | No reason -> Error (defaultArg reason $"File deletion declined for \"{dirName}\".") - | Yes -> emptyDirAndReport dirName + | Proceed -> emptyDirAndReport dirName + | Decline reason -> Error reason let start printer settings : NextAction = match isWorkingDirReady printer settings.WorkingDirectory with diff --git a/src/CCVTAC.Main/Shared.fs b/src/CCVTAC.Main/Shared.fs index e505b532..5b59d549 100644 --- a/src/CCVTAC.Main/Shared.fs +++ b/src/CCVTAC.Main/Shared.fs @@ -24,4 +24,4 @@ module Shared = doneMsgFn seconds - type YesNoAnswer = Yes | No of Reason: string option + type ConfirmationAnswer = Proceed | Decline of Reason: string From 712bae4c470086c4919980ed0716cb5753ae7c33 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Wed, 18 Nov 2026 21:47:43 +0900 Subject: [PATCH 41/45] Refactor isWorkingDirReady --- src/CCVTAC.Main/IoUtilities/Directories.fs | 2 +- src/CCVTAC.Main/Orchestrator.fs | 10 ++++------ 2 files changed, 5 insertions(+), 7 deletions(-) diff --git a/src/CCVTAC.Main/IoUtilities/Directories.fs b/src/CCVTAC.Main/IoUtilities/Directories.fs index b89ad9bf..40a7d903 100644 --- a/src/CCVTAC.Main/IoUtilities/Directories.fs +++ b/src/CCVTAC.Main/IoUtilities/Directories.fs @@ -68,7 +68,7 @@ module Directories = if Array.isEmpty fileNames then Ok () else - SB($"""Found {String.plur' "leftover file" S fileNames.Length} leftover in working directory \"{dirName}\":{String.nl}""") + SB($"""Found {String.plur' "leftover file" S fileNames.Length} in working directory "{dirName}":{String.nl}""") .AppendLine (fileNames |> Array.truncate showMax diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 272b0d0a..6d89e779 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -324,12 +324,10 @@ module Orchestrator = let private isWorkingDirReady (printer: Printer) dirName : Result = let emptyDirAndReport dirName = - match Directories.deleteAllFiles dirName with - | Ok results -> - Directories.printDeletionResults printer results - printer.Debug "Files deleted." - Ok () - | Error deletionError -> Error deletionError + Directories.deleteAllFiles dirName + |> map (fun results -> + Directories.printDeletionResults printer results + printer.Debug "Files deleted.") match Directories.warnIfAnyFiles Directories.maxFilesToShow dirName with | Ok () -> Ok () From 48ea4be15cc880a3953ba122fd591b0b4b799770 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:43:01 +0900 Subject: [PATCH 42/45] Tweak message --- src/CCVTAC.Main/Downloading/Updater.fs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index 51c31cdd..bf246a3b 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -11,7 +11,7 @@ module Updater = let run (printer: Printer) userSettings : unit = if String.hasNoText userSettings.DownloaderUpdateCommand then - printer.Info "No downloader update command provided, so will skip the update." + printer.Info "No downloader update command provided, so will skip updating." else let toolSettings = ToolSettings.create userSettings.DownloaderUpdateCommand userSettings.WorkingDirectory From e1fe555ab0cb4892a1cd855b4111af6c1e121e94 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 20 Nov 2026 12:44:22 +0900 Subject: [PATCH 43/45] Minor code tweaks --- src/CCVTAC.Main/Downloading/Updater.fs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index bf246a3b..0759ae41 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -19,10 +19,9 @@ module Updater = match Runner.runTool printer toolSettings [] with | Ok details -> if details.ExitCode <> successExitCode then - let msg = + printer.Warning <| match details.Error with | Some errMsg -> $"Update completed with minor issues: {errMsg}" | None -> "Update completed with minor unspecified issues." - printer.Warning msg | Error msg -> - printer.Error $"Failure updating: {msg}" + printer.Error $"Update failure: {msg}" From 5f2f4e308eb12020a41fcf084fba43d9e58edbfc Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:25:41 +0900 Subject: [PATCH 44/45] Minor code tweaks --- src/CCVTAC.Main/Orchestrator.fs | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 6d89e779..7883c352 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -287,10 +287,8 @@ module Orchestrator = let updatedSettings, nextAction = match processResult with - | Ok result -> - defaultArg result.UpdatedSettings settings, result.NextAction - | Error _ -> - settings, nextAction' + | Ok result -> defaultArg result.UpdatedSettings settings, result.NextAction + | Error _ -> settings, nextAction' // Advance the URL position only when the input was a URL. let nextUrlPosition = @@ -325,8 +323,8 @@ module Orchestrator = let private isWorkingDirReady (printer: Printer) dirName : Result = let emptyDirAndReport dirName = Directories.deleteAllFiles dirName - |> map (fun results -> - Directories.printDeletionResults printer results + |> Result.map (fun msgs -> + Directories.printDeletionResults printer msgs printer.Debug "Files deleted.") match Directories.warnIfAnyFiles Directories.maxFilesToShow dirName with @@ -358,8 +356,7 @@ module Orchestrator = let categoryCounts = countCategories categorizedInputs summarizeInput printer categorizedInputs categoryCounts - let batchResult = - processBatch printer categorizedInputs categoryCounts settings results history + let batchResult = processBatch printer categorizedInputs categoryCounts settings results history let nextSettings = defaultArg batchResult.UpdatedSettings settings From 3065eb27a5ccaf6c049865fae0eed3319d6eecf4 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 20 Nov 2026 17:29:31 +0900 Subject: [PATCH 45/45] Minor code layout --- src/CCVTAC.Main/Shared.fs | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/CCVTAC.Main/Shared.fs b/src/CCVTAC.Main/Shared.fs index 5b59d549..7a777ed5 100644 --- a/src/CCVTAC.Main/Shared.fs +++ b/src/CCVTAC.Main/Shared.fs @@ -6,7 +6,13 @@ open Spectre.Console [] module Shared = - type ResultMessages = { Successes: string list; Failures: string list } + type ResultMessages = + { Successes: string list + Failures: string list } + + type ConfirmationAnswer = + | Proceed + | Decline of Reason: string let sleep workingMsgFn doneMsgFn seconds : string = let rec loop remaining (ctx: StatusContext) = @@ -24,4 +30,3 @@ module Shared = doneMsgFn seconds - type ConfirmationAnswer = Proceed | Decline of Reason: string