From 426b08a8f6f6ca4ed073becd447c818a49b83d6e Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:03:15 +0900 Subject: [PATCH 01/13] Initial refactoring for ToolSettings model change This was an LLM-powered update. Tests are passing, so I will commit this and work on further tweaks and cleanup. --- src/CCVTAC.Main/Downloading/Downloader.fs | 100 ++++++++++-------- src/CCVTAC.Main/Downloading/Updater.fs | 20 +++- src/CCVTAC.Main/ExternalTools/Runner.fs | 79 ++++++++------ src/CCVTAC.Main/ExternalTools/ToolSettings.fs | 23 ++-- .../PostProcessing/ImageProcessor.fs | 24 ++++- 5 files changed, 159 insertions(+), 87 deletions(-) diff --git a/src/CCVTAC.Main/Downloading/Downloader.fs b/src/CCVTAC.Main/Downloading/Downloader.fs index 78c112ae..bc90516c 100644 --- a/src/CCVTAC.Main/Downloading/Downloader.fs +++ b/src/CCVTAC.Main/Downloading/Downloader.fs @@ -15,44 +15,64 @@ module Downloader = let maximumFormatPasses = 3 - let generateDownloadArgs audioFormat userSettings (mediaType: MediaType option) additionalArgs : string = + /// Splits a user-supplied option string on spaces, discarding empty entries. + /// Quoted values containing spaces are not supported here. + let private splitOnSpaces (s: string) : string list = + s.Split([| ' ' |], StringSplitOptions.RemoveEmptyEntries) |> List.ofArray + + /// Builds the downloader's argument list. Each element is a single argv entry, + /// so flags and their values are kept as separate elements. + let generateDownloadArgs audioFormat userSettings (mediaType: MediaType option) additionalArgs : string list = let writeJsonArg = "--write-info-json" - let trimFileNamesArg = "--trim-filenames 250" - let formatArg = + let formatArgs = match audioFormat with | None | Some "best" -> [] - | Some format -> [$"-f {format}"] + | Some format -> [ "-f"; format ] let args = match mediaType with | None -> - [ "--flat-playlist"; writeJsonArg; trimFileNamesArg ] + [ "--flat-playlist"; writeJsonArg; "--trim-filenames"; "250" ] | Some _ -> - [ "--extract-audio" ] @ formatArg - @ [ $"--audio-quality {userSettings.AudioQuality}" + [ "--extract-audio" ] + @ formatArgs + @ [ "--audio-quality"; string userSettings.AudioQuality "--write-thumbnail" - "--convert-thumbnails jpg" + "--convert-thumbnails"; "jpg" writeJsonArg - trimFileNamesArg - "--retries 3" ] - - let args' = - args - @ (if userSettings.QuietMode then [ "--quiet"; "--no-warnings" ] else []) - @ Option.toList userSettings.DownloaderAdditionalOptions - @ (match mediaType with - | None -> [] - | Some mt -> - [ if userSettings.SplitChapters then "--split-chapters" - if isMultiVideo mt then - $"--sleep-interval {userSettings.SleepSecondsBetweenDownloads}" - if isMultiVideo mt && mt.IsStandardPlaylist then - """-o "%(uploader).80B - %(playlist).80B - %(playlist_autonumber)s - %(title).150B [%(id)s].%(ext)s" --playlist-reverse""" ]) - @ defaultArg additionalArgs [] - - String.Join(" ", args') + "--trim-filenames"; "250" + "--retries"; "3" ] + + let quietArgs = + if userSettings.QuietMode then [ "--quiet"; "--no-warnings" ] else [] + + let additionalOptionArgs = + userSettings.DownloaderAdditionalOptions + |> Option.map splitOnSpaces + |> Option.defaultValue [] + + let mediaSpecificArgs = + match mediaType with + | None -> [] + | Some mt -> + (if userSettings.SplitChapters then [ "--split-chapters" ] else []) + @ (if isMultiVideo mt then + [ "--sleep-interval"; string userSettings.SleepSecondsBetweenDownloads ] + else []) + @ (if isMultiVideo mt && mt.IsStandardPlaylist then + [ "-o" + "%(uploader).80B - %(playlist).80B - %(playlist_autonumber)s - %(title).150B [%(id)s].%(ext)s" + "--playlist-reverse" ] + else []) + + args @ quietArgs @ additionalOptionArgs @ mediaSpecificArgs @ defaultArg additionalArgs [] + + /// Creates the tool settings for the configured downloader and runs it. + let private runDownloader (printer: Printer) userSettings args : Result = + ToolSettings.create userSettings.DownloaderCommand args userSettings.WorkingDirectory + |> Result.bind (fun settings -> runTool printer settings [ 1 ]) let wrapUrlInMediaType url : Result = mediaTypeWithIds url @@ -67,11 +87,8 @@ module Downloader = err :: Option.toList maybeSndErr let attemptAudioFormat format previousErrors = - let args = generateDownloadArgs (Some format) userSettings (Some mediaType) (Some [url]) - let commandWithArgs = $"{userSettings.DownloaderCommand} {args}" - let downloadSettings = ToolSettings.create commandWithArgs userSettings.WorkingDirectory - - let downloadResult = runTool printer downloadSettings [1] + let args = generateDownloadArgs (Some format) userSettings (Some mediaType) (Some [ url ]) + let downloadResult = runDownloader printer userSettings args let anyFilesDownloaded = Num.isPos <| audioFileCount Files.audioFileExts userSettings.WorkingDirectory match downloadResult, anyFilesDownloaded with @@ -79,7 +96,7 @@ module Downloader = Ok <| $"Successfully downloaded the \"{format}\" format." :: match result.Error with - | Some err -> [$"However, a minor issue was reported: {err}"] + | Some err -> [ $"However, a minor issue was reported: {err}" ] | None -> [] | Ok result, false -> let msg = $"While the downloader finished successfully, no audio files were downloaded in the \"{format}\" format." @@ -89,13 +106,13 @@ module Downloader = Error (previousErrors @ buildErrMsg msg (Some err)) | Error err, false -> let msg = $"A download error was reported for the \"{format}\" format, and no audio files were downloaded. {err}" - Error (previousErrors @ [msg]) + Error (previousErrors @ [ msg ]) let rec retryLoop errors passesRemaining formatsRemaining = if Num.isZero passesRemaining then Error <| errors - @ [$"Gave up after {maximumFormatPasses} passes through the configured audio formats."] + @ [ $"Gave up after {maximumFormatPasses} passes through the configured audio formats." ] else match formatsRemaining with | [] -> @@ -107,21 +124,18 @@ module Downloader = | Error errs -> retryLoop errs passesRemaining remainingFormats match userSettings.AudioFormats with - | [] -> Error ["No audio formats are configured."] + | [] -> Error [ "No audio formats are configured." ] | formats -> retryLoop [] maximumFormatPasses formats let downloadMetadata (printer: Printer) userSettings (SupplementaryUrl url) : Result = match url with | None -> Ok "No supplementary metadata link found." | Some url' -> - let args = generateDownloadArgs None userSettings None (Some [url']) - let commandWithArgs = $"{userSettings.DownloaderCommand} {args}" - let downloadSettings = ToolSettings.create commandWithArgs userSettings.WorkingDirectory - let metadataDownloadResult = runTool printer downloadSettings [1] - - match metadataDownloadResult with - | Ok _ -> Ok "Supplementary metadata download completed OK." - | Error err -> Error [$"Supplementary metadata download failed: {err}"] + let args = generateDownloadArgs None userSettings None (Some [ url' ]) + + match runDownloader printer userSettings args with + | Ok _ -> Ok "Supplementary metadata download completed OK." + | Error err -> Error [ $"Supplementary metadata download failed: {err}" ] let run (printer: Printer) (mediaType: MediaType) userSettings : Result = monad { diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index 0759ae41..b77e0957 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -4,24 +4,36 @@ open CCVTAC.Main open CCVTAC.Main.ExternalTools open CCVTAC.Main.Settings.Settings open CCFSharpUtils.Text +open System module Updater = let successExitCode = 0 + /// Splits the configured update command into its tool name and arguments. + /// Empty entries are removed, so repeated spaces are harmless. + let private splitCommand (command: string) : string list = + command.Split([| ' ' |], StringSplitOptions.RemoveEmptyEntries) + |> List.ofArray + let run (printer: Printer) userSettings : unit = if String.hasNoText userSettings.DownloaderUpdateCommand then printer.Info "No downloader update command provided, so will skip updating." else - let toolSettings = ToolSettings.create userSettings.DownloaderUpdateCommand - userSettings.WorkingDirectory + let outcome = + match splitCommand userSettings.DownloaderUpdateCommand with + | tool :: args -> + ToolSettings.create tool args userSettings.WorkingDirectory + |> Result.bind (fun settings -> Runner.runTool printer settings []) + | [] -> + Error "No downloader update command could be parsed." - match Runner.runTool printer toolSettings [] with + match outcome with | Ok details -> if details.ExitCode <> successExitCode then printer.Warning <| match details.Error with | Some errMsg -> $"Update completed with minor issues: {errMsg}" - | None -> "Update completed with minor unspecified issues." + | None -> "Update completed with minor unspecified issues." | Error msg -> printer.Error $"Update failure: {msg}" diff --git a/src/CCVTAC.Main/ExternalTools/Runner.fs b/src/CCVTAC.Main/ExternalTools/Runner.fs index 435837fe..51fb6f83 100644 --- a/src/CCVTAC.Main/ExternalTools/Runner.fs +++ b/src/CCVTAC.Main/ExternalTools/Runner.fs @@ -1,10 +1,11 @@ namespace CCVTAC.Main.ExternalTools +open System.IO open CCVTAC.Main -open CCFSharpUtils.Collections open CCFSharpUtils.Text open Startwatch.Library open System +open System.ComponentModel open System.Diagnostics module Runner = @@ -12,46 +13,64 @@ module Runner = type ToolResult = { ExitCode: int; Error: string option } [] - let private authenticSuccessExitCode = 0 + let private successExitCode = 0 let private isSuccessExitCode (otherSuccessExitCodes: int list) (exitCode: int) = - List.contains exitCode (authenticSuccessExitCode :: otherSuccessExitCodes) + List.contains exitCode (successExitCode :: otherSuccessExitCodes) + + let private buildStartInfo (toolSettings: ToolSettings) = + let psi = ProcessStartInfo(ToolSettings.tool toolSettings) + + for arg in ToolSettings.args toolSettings do + psi.ArgumentList.Add arg + + psi.WorkingDirectory <- ToolSettings.workingDirectory toolSettings + psi.UseShellExecute <- false + psi.RedirectStandardOutput <- false + psi.RedirectStandardError <- true + psi.CreateNoWindow <- true + psi + + let private tryStart (psi: ProcessStartInfo) : Result = + try + match Process.Start psi with + | Null -> Error $"Could not start {psi.FileName}." + | NonNull proc -> Ok proc + with + | :? Win32Exception as ex -> + Error $"Could not locate or start {psi.FileName}: {ex.Message}" + | :? DirectoryNotFoundException as ex -> + Error $"Working directory for {psi.FileName} does not exist: {ex.Message}" /// Calls an external application. - /// Tool settings for execution - /// Additional exit codes, other than 0, that can be treated as non-failures - /// - let runTool (printer: Printer) toolSettings otherSuccessExitCodes : Result = + /// Receives progress information about the tool's execution. + /// Settings governing the tool, its arguments, and its working directory. + /// Additional exit codes, other than 0, that can be treated as non-failures. + let runTool + (printer: Printer) + (toolSettings: ToolSettings) + (otherSuccessExitCodes: int list) + : Result = + let watch = Watch() - printer.Info $"Running {toolSettings.CommandWithArgs}..." - - let command = - toolSettings.CommandWithArgs.Split([|' '|], 2) - |> fun arr -> {| Tool = arr[0] - Args = if Array.hasMultiple arr then arr[1] else String.Empty |} - - let processStartInfo = ProcessStartInfo command.Tool - processStartInfo.Arguments <- command.Args - processStartInfo.RedirectStandardOutput <- false - processStartInfo.RedirectStandardError <- true - processStartInfo.CreateNoWindow <- true - processStartInfo.WorkingDirectory <- toolSettings.WorkingDirectory - - match Process.Start processStartInfo with - | Null -> - Error $"Could not locate or start {command.Tool}." - | NonNull proc -> - let error = proc.StandardError.ReadToEnd() + let tool = ToolSettings.tool toolSettings + printer.Info $"Running {tool}..." + + buildStartInfo toolSettings + |> tryStart + |> Result.bind (fun proc -> + use _ = proc + let rawError = proc.StandardError.ReadToEnd() proc.WaitForExit() - printer.Info $"{command.Tool} finished in {watch.ElapsedFriendly}." + printer.Info $"{tool} finished in {watch.ElapsedFriendly}." - let maybeError = String.toOption error + let maybeError = String.toOption rawError if isSuccessExitCode otherSuccessExitCodes proc.ExitCode then Ok { ExitCode = proc.ExitCode Error = maybeError } else match maybeError with - | Some err -> Error $"%s{command.Tool} exited with code %d{proc.ExitCode}: %s{err}." - | None -> Error $"%s{command.Tool} exited with code %d{proc.ExitCode}." + | Some err -> Error $"%s{tool} exited with code %d{proc.ExitCode}: %s{err}." + | None -> Error $"%s{tool} exited with code %d{proc.ExitCode}.") diff --git a/src/CCVTAC.Main/ExternalTools/ToolSettings.fs b/src/CCVTAC.Main/ExternalTools/ToolSettings.fs index 208c5f3c..020b188b 100644 --- a/src/CCVTAC.Main/ExternalTools/ToolSettings.fs +++ b/src/CCVTAC.Main/ExternalTools/ToolSettings.fs @@ -1,13 +1,22 @@ namespace CCVTAC.Main.ExternalTools /// Settings to govern the behavior of an external program. -type ToolSettings = private { - CommandWithArgs: string - WorkingDirectory: string -} +type ToolSettings = + private + { Tool: string + Args: string list + WorkingDirectory: string } module ToolSettings = - let create commandWithArgs workingDirectory = - { CommandWithArgs = commandWithArgs - WorkingDirectory = workingDirectory } + // Accessors + let tool t = t.Tool + let args t = t.Args + let workingDirectory t = t.WorkingDirectory + let create tool args workingDirectory : Result = + if System.String.IsNullOrWhiteSpace tool then + Error "Tool name must not be empty." + else + Ok { Tool = tool + Args = args + WorkingDirectory = workingDirectory } diff --git a/src/CCVTAC.Main/PostProcessing/ImageProcessor.fs b/src/CCVTAC.Main/PostProcessing/ImageProcessor.fs index d8a901f1..7455e4bf 100644 --- a/src/CCVTAC.Main/PostProcessing/ImageProcessor.fs +++ b/src/CCVTAC.Main/PostProcessing/ImageProcessor.fs @@ -1,11 +1,29 @@ namespace CCVTAC.Main.PostProcessing +open CCVTAC.Main open CCVTAC.Main.ExternalTools +open System.IO module ImageProcessor = let private programName = "mogrify" - let run printer workingDirectory : unit = - let toolSettings = workingDirectory |> ToolSettings.create $"{programName} -trim -fuzz 10%% *.jpg" - Runner.runTool printer toolSettings [] |> ignore + let run (printer: Printer) workingDirectory : unit = + if not (Directory.Exists workingDirectory) then + printer.Error $"Working directory does not exist: {workingDirectory}" + else + let jpgFiles = + Directory.GetFiles(workingDirectory, "*.jpg") + |> Array.map Path.GetFileName + |> List.ofArray + +#nowarn FS3261 // For IDEs only, which emit a null warning in createValidated, though compilation itself is fine. + if List.isEmpty jpgFiles then + printer.Error $"No JPG files found in {workingDirectory}." + else + let args = [ "-trim"; "-fuzz"; "10%" ] @ jpgFiles + + match ToolSettings.create programName args workingDirectory with + | Ok settings -> Runner.runTool printer settings |> ignore + | Error msg -> printer.Error msg +#warnon FS3261 From 8c015356a2ff8450ce3eace49c6dbc25165272d5 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:27:01 +0900 Subject: [PATCH 02/13] Use >>=; other cleanup --- src/CCVTAC.Main/Downloading/Downloader.fs | 12 +++++------- src/CCVTAC.Main/Downloading/Updater.fs | 11 ++++++----- src/CCVTAC.Main/ExternalTools/Runner.fs | 12 ++++++------ 3 files changed, 17 insertions(+), 18 deletions(-) diff --git a/src/CCVTAC.Main/Downloading/Downloader.fs b/src/CCVTAC.Main/Downloading/Downloader.fs index bc90516c..21bf6b40 100644 --- a/src/CCVTAC.Main/Downloading/Downloader.fs +++ b/src/CCVTAC.Main/Downloading/Downloader.fs @@ -49,9 +49,7 @@ module Downloader = if userSettings.QuietMode then [ "--quiet"; "--no-warnings" ] else [] let additionalOptionArgs = - userSettings.DownloaderAdditionalOptions - |> Option.map splitOnSpaces - |> Option.defaultValue [] + option splitOnSpaces [] userSettings.DownloaderAdditionalOptions let mediaSpecificArgs = match mediaType with @@ -72,7 +70,7 @@ module Downloader = /// Creates the tool settings for the configured downloader and runs it. let private runDownloader (printer: Printer) userSettings args : Result = ToolSettings.create userSettings.DownloaderCommand args userSettings.WorkingDirectory - |> Result.bind (fun settings -> runTool printer settings [ 1 ]) + >>= fun settings -> runTool printer settings [ 1 ] let wrapUrlInMediaType url : Result = mediaTypeWithIds url @@ -120,8 +118,8 @@ module Downloader = retryLoop errors (passesRemaining - 1) userSettings.AudioFormats | format :: remainingFormats -> match attemptAudioFormat format errors with - | Ok msgs -> Ok msgs - | Error errs -> retryLoop errs passesRemaining remainingFormats + | Ok messages -> Ok messages + | Error errors -> retryLoop errors passesRemaining remainingFormats match userSettings.AudioFormats with | [] -> Error [ "No audio formats are configured." ] @@ -137,7 +135,7 @@ module Downloader = | Ok _ -> Ok "Supplementary metadata download completed OK." | Error err -> Error [ $"Supplementary metadata download failed: {err}" ] - let run (printer: Printer) (mediaType: MediaType) userSettings : Result = + let run (printer: Printer) mediaType userSettings : Result = monad { let rawUrls = generateDownloadUrl mediaType let urls = diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index b77e0957..fde3e422 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -4,6 +4,7 @@ open CCVTAC.Main open CCVTAC.Main.ExternalTools open CCVTAC.Main.Settings.Settings open CCFSharpUtils.Text +open FSharpPlus open System module Updater = @@ -24,7 +25,7 @@ module Updater = match splitCommand userSettings.DownloaderUpdateCommand with | tool :: args -> ToolSettings.create tool args userSettings.WorkingDirectory - |> Result.bind (fun settings -> Runner.runTool printer settings []) + >>= fun settings -> Runner.runTool printer settings [] | [] -> Error "No downloader update command could be parsed." @@ -33,7 +34,7 @@ module Updater = if details.ExitCode <> successExitCode then printer.Warning <| match details.Error with - | Some errMsg -> $"Update completed with minor issues: {errMsg}" - | None -> "Update completed with minor unspecified issues." - | Error msg -> - printer.Error $"Update failure: {msg}" + | Some message -> $"Update completed with minor issues: {message}" + | None -> "Update completed with unspecified minor issues." + | Error message -> + printer.Error $"Update failure: {message}" diff --git a/src/CCVTAC.Main/ExternalTools/Runner.fs b/src/CCVTAC.Main/ExternalTools/Runner.fs index 51fb6f83..53a7c51d 100644 --- a/src/CCVTAC.Main/ExternalTools/Runner.fs +++ b/src/CCVTAC.Main/ExternalTools/Runner.fs @@ -1,12 +1,12 @@ namespace CCVTAC.Main.ExternalTools open System.IO +open System.ComponentModel +open System.Diagnostics open CCVTAC.Main open CCFSharpUtils.Text open Startwatch.Library -open System -open System.ComponentModel -open System.Diagnostics +open FSharpPlus module Runner = @@ -15,7 +15,7 @@ module Runner = [] let private successExitCode = 0 - let private isSuccessExitCode (otherSuccessExitCodes: int list) (exitCode: int) = + let private isSuccessExitCode otherSuccessExitCodes exitCode = List.contains exitCode (successExitCode :: otherSuccessExitCodes) let private buildStartInfo (toolSettings: ToolSettings) = @@ -58,7 +58,7 @@ module Runner = buildStartInfo toolSettings |> tryStart - |> Result.bind (fun proc -> + >>= fun proc -> use _ = proc let rawError = proc.StandardError.ReadToEnd() @@ -73,4 +73,4 @@ module Runner = else match maybeError with | Some err -> Error $"%s{tool} exited with code %d{proc.ExitCode}: %s{err}." - | None -> Error $"%s{tool} exited with code %d{proc.ExitCode}.") + | None -> Error $"%s{tool} exited with code %d{proc.ExitCode}." From 8b3335dc8028752814d1d53fb1f8e76147a6fe85 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Sun, 29 Nov 2026 17:59:32 +0900 Subject: [PATCH 03/13] TaggingSet cleanup --- .../PostProcessing/Tagging/TaggingSet.fs | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs b/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs index 3e82d836..8d22c3ab 100644 --- a/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs +++ b/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs @@ -27,7 +27,7 @@ module TaggingSet = t.AudioFiles @ [t.JsonFile; t.ImageFile] // Regex group 0 is the full filename, and group 1 contains the video ID. - let hasVideoIdRgx = + let videoIdRgx = Regex(@".+\[([\w\-]{11})\](?:.*)?\.(\w+)", RegexOptions.Compiled) let private create v a j i = @@ -41,15 +41,16 @@ module TaggingSet = #nowarn FS3261 // For IDEs only, which emit a null warning in createValidated, though compilation itself is fine. let hasSupportedAudioExt (fileName: string) = match Path.GetExtension fileName with - | ext when String.hasText ext -> Files.audioFileExts |> List.containsIgnoreCase ext - | _ -> false + | ext when String.hasText ext -> + Files.audioFileExts |> List.containsIgnoreCase ext + | _ -> + false #warnon FS3261 let audioFiles = fileNames |> List.filter hasSupportedAudioExt let jsonFiles = fileNames |> Files.filterByExt Files.jsonFileExt - let imageFiles = - Files.imageFileExts - |> List.collect (fun ext -> fileNames |> Files.filterByExt ext) + let imageFiles = Files.imageFileExts + |> List.collect (fun ext -> fileNames |> Files.filterByExt ext) applicative { let! a = List.ensureNotEmptyV audioFiles @@ -67,11 +68,11 @@ module TaggingSet = /// Irrelevant files are ignored. Validation errors are accumulated and returned in an Error. let createSets filePaths : Result = if Seq.isEmpty filePaths then - Error ["No file paths to create a tagging set were provided."] + Error [ "No file paths to create a tagging set were provided." ] else let relevantFileInfo fileName = fileName - |> Rgx.trySuccessMatch hasVideoIdRgx + |> Rgx.trySuccessMatch videoIdRgx |> Option.map (fun m -> {| FileName = m.Groups[0].Value VideoId = m.Groups[1].Value |} ) @@ -88,7 +89,7 @@ module TaggingSet = results |> List.collect (function | Failure errs -> NonEmptyList.toList errs - | Success _ -> []) + | Success _ -> []) if List.isEmpty errors then Ok (results |> List.choose (function Success ts -> Some ts | Failure _ -> None)) From 83963a4df009f07e22c95a6530e36ba9823bfd3b Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Mon, 30 Nov 2026 22:17:33 +0900 Subject: [PATCH 04/13] Code layout tweak --- src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs b/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs index 8d22c3ab..ccc70052 100644 --- a/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs +++ b/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs @@ -73,9 +73,8 @@ module TaggingSet = let relevantFileInfo fileName = fileName |> Rgx.trySuccessMatch videoIdRgx - |> Option.map (fun m -> - {| FileName = m.Groups[0].Value - VideoId = m.Groups[1].Value |} ) + |> Option.map (fun m -> {| FileName = m.Groups[0].Value + VideoId = m.Groups[1].Value |} ) let results = filePaths @@ -95,4 +94,3 @@ module TaggingSet = Ok (results |> List.choose (function Success ts -> Some ts | Failure _ -> None)) else Error errors - From 517167b69d921b416ff3029bafad6220054091cb Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Tue, 1 Dec 2026 16:41:20 +0900 Subject: [PATCH 05/13] Code layout tweaks --- src/CCVTAC.Main/Orchestrator.fs | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/CCVTAC.Main/Orchestrator.fs b/src/CCVTAC.Main/Orchestrator.fs index 7c3be5de..63a831cf 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -89,7 +89,10 @@ module Orchestrator = | Error errMsg -> Error (Recoverable $"URL parse error: %s{errMsg}") | Ok mediaType -> - printer.Info $"%s{typeName mediaType} URL '%s{url}' detected." + printer.Info( + $"%s{typeName mediaType} URL '%s{url}' detected.", + PrintOptions.DefaultWithLineBefore) + history.Append(url, urlInputTime, printer) let downloadResult = Downloader.run printer mediaType settings @@ -143,9 +146,13 @@ module Orchestrator = Read = _.QuietMode AfterToggle = fun s -> printer.ShowDebug(not s.QuietMode) } ] - let processCommand printer command settings (history: History) : Result = + let processCommand printer command settings (history: History) + : Result = + let checkCommand = List.containsIgnoreCase command - let toggle = toggleSpecs printer |> List.tryFind (fun spec -> checkCommand spec.Triggers) + + let toggle = toggleSpecs printer + |> List.tryFind (fun spec -> checkCommand spec.Triggers) match toggle with | Some spec -> From 66e4e253862ea1e10055ce56f64d2b665412b253 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Wed, 2 Dec 2026 21:15:53 +0900 Subject: [PATCH 06/13] Use String.splitOnSpaces --- src/CCVTAC.Main/CCVTAC.Main.fsproj | 2 +- src/CCVTAC.Main/Downloading/Downloader.fs | 9 ++------- src/CCVTAC.Main/Downloading/Updater.fs | 8 +------- src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs | 2 +- src/CCVTAC.Main/Shared.fs | 3 +++ src/CCVTAC.Tests/CCVTAC.Tests.fsproj | 2 +- 6 files changed, 9 insertions(+), 17 deletions(-) diff --git a/src/CCVTAC.Main/CCVTAC.Main.fsproj b/src/CCVTAC.Main/CCVTAC.Main.fsproj index 00f1f1c0..96a1ab8a 100644 --- a/src/CCVTAC.Main/CCVTAC.Main.fsproj +++ b/src/CCVTAC.Main/CCVTAC.Main.fsproj @@ -40,7 +40,7 @@ - + diff --git a/src/CCVTAC.Main/Downloading/Downloader.fs b/src/CCVTAC.Main/Downloading/Downloader.fs index 21bf6b40..aec2d488 100644 --- a/src/CCVTAC.Main/Downloading/Downloader.fs +++ b/src/CCVTAC.Main/Downloading/Downloader.fs @@ -8,18 +8,13 @@ open CCVTAC.Main.Downloading.Downloading open CCVTAC.Main.ExternalTools open CCVTAC.Main.Settings.Settings open CCFSharpUtils +open CCFSharpUtils.Text open FSharpPlus -open System module Downloader = let maximumFormatPasses = 3 - /// Splits a user-supplied option string on spaces, discarding empty entries. - /// Quoted values containing spaces are not supported here. - let private splitOnSpaces (s: string) : string list = - s.Split([| ' ' |], StringSplitOptions.RemoveEmptyEntries) |> List.ofArray - /// Builds the downloader's argument list. Each element is a single argv entry, /// so flags and their values are kept as separate elements. let generateDownloadArgs audioFormat userSettings (mediaType: MediaType option) additionalArgs : string list = @@ -49,7 +44,7 @@ module Downloader = if userSettings.QuietMode then [ "--quiet"; "--no-warnings" ] else [] let additionalOptionArgs = - option splitOnSpaces [] userSettings.DownloaderAdditionalOptions + option String.splitOnSpaces [] userSettings.DownloaderAdditionalOptions let mediaSpecificArgs = match mediaType with diff --git a/src/CCVTAC.Main/Downloading/Updater.fs b/src/CCVTAC.Main/Downloading/Updater.fs index fde3e422..f9f60341 100644 --- a/src/CCVTAC.Main/Downloading/Updater.fs +++ b/src/CCVTAC.Main/Downloading/Updater.fs @@ -11,18 +11,12 @@ module Updater = let successExitCode = 0 - /// Splits the configured update command into its tool name and arguments. - /// Empty entries are removed, so repeated spaces are harmless. - let private splitCommand (command: string) : string list = - command.Split([| ' ' |], StringSplitOptions.RemoveEmptyEntries) - |> List.ofArray - let run (printer: Printer) userSettings : unit = if String.hasNoText userSettings.DownloaderUpdateCommand then printer.Info "No downloader update command provided, so will skip updating." else let outcome = - match splitCommand userSettings.DownloaderUpdateCommand with + match String.splitOnSpaces userSettings.DownloaderUpdateCommand with | tool :: args -> ToolSettings.create tool args userSettings.WorkingDirectory >>= fun settings -> Runner.runTool printer settings [] diff --git a/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs b/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs index ccc70052..ede8239b 100644 --- a/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs +++ b/src/CCVTAC.Main/PostProcessing/Tagging/TaggingSet.fs @@ -72,7 +72,7 @@ module TaggingSet = else let relevantFileInfo fileName = fileName - |> Rgx.trySuccessMatch videoIdRgx + |> Rgx.tryMatch videoIdRgx |> Option.map (fun m -> {| FileName = m.Groups[0].Value VideoId = m.Groups[1].Value |} ) diff --git a/src/CCVTAC.Main/Shared.fs b/src/CCVTAC.Main/Shared.fs index b8a3e6c8..ab322fd9 100644 --- a/src/CCVTAC.Main/Shared.fs +++ b/src/CCVTAC.Main/Shared.fs @@ -5,6 +5,7 @@ open Spectre.Console [] module Shared = + open System type ConfirmationAnswer = | Proceed @@ -29,3 +30,5 @@ module Shared = doneMsgFn seconds + let private splitOnSpaces (text: string) : string list = + text.Split([| ' ' |], StringSplitOptions.RemoveEmptyEntries) |> List.ofArray diff --git a/src/CCVTAC.Tests/CCVTAC.Tests.fsproj b/src/CCVTAC.Tests/CCVTAC.Tests.fsproj index 6cd6b896..a04ee3b3 100644 --- a/src/CCVTAC.Tests/CCVTAC.Tests.fsproj +++ b/src/CCVTAC.Tests/CCVTAC.Tests.fsproj @@ -14,7 +14,7 @@ - + From a9fc6735d2c214e43ef20eaea0b59a7f6c35b9d8 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 4 Dec 2026 09:56:13 +0900 Subject: [PATCH 07/13] Show toolname with args --- src/CCVTAC.Main/ExternalTools/Runner.fs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/CCVTAC.Main/ExternalTools/Runner.fs b/src/CCVTAC.Main/ExternalTools/Runner.fs index 53a7c51d..91ce431d 100644 --- a/src/CCVTAC.Main/ExternalTools/Runner.fs +++ b/src/CCVTAC.Main/ExternalTools/Runner.fs @@ -54,7 +54,8 @@ module Runner = let watch = Watch() let tool = ToolSettings.tool toolSettings - printer.Info $"Running {tool}..." + let args = ToolSettings.args toolSettings |> String.concat " " + printer.Info $"Running {tool} using `{tool} {args}`..." buildStartInfo toolSettings |> tryStart From 36fa1dbe2ac3b9d396484f87b737bf9caf4e8f42 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 4 Dec 2026 11:01:45 +0900 Subject: [PATCH 08/13] ToolSettings: Add more accessors; minor tweaks --- src/CCVTAC.Main/ExternalTools/Runner.fs | 21 +++++++------------ src/CCVTAC.Main/ExternalTools/ToolSettings.fs | 18 +++++++++------- 2 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/CCVTAC.Main/ExternalTools/Runner.fs b/src/CCVTAC.Main/ExternalTools/Runner.fs index 91ce431d..45bff9d8 100644 --- a/src/CCVTAC.Main/ExternalTools/Runner.fs +++ b/src/CCVTAC.Main/ExternalTools/Runner.fs @@ -24,7 +24,7 @@ module Runner = for arg in ToolSettings.args toolSettings do psi.ArgumentList.Add arg - psi.WorkingDirectory <- ToolSettings.workingDirectory toolSettings + psi.WorkingDirectory <- ToolSettings.workingDir toolSettings psi.UseShellExecute <- false psi.RedirectStandardOutput <- false psi.RedirectStandardError <- true @@ -46,16 +46,11 @@ module Runner = /// Receives progress information about the tool's execution. /// Settings governing the tool, its arguments, and its working directory. /// Additional exit codes, other than 0, that can be treated as non-failures. - let runTool - (printer: Printer) - (toolSettings: ToolSettings) - (otherSuccessExitCodes: int list) - : Result = - + let runTool (printer: Printer) toolSettings otherSuccessExitCodes : Result = let watch = Watch() - let tool = ToolSettings.tool toolSettings - let args = ToolSettings.args toolSettings |> String.concat " " - printer.Info $"Running {tool} using `{tool} {args}`..." + + let toolName = ToolSettings.toolName toolSettings + printer.Info <| ToolSettings.runSummary toolSettings buildStartInfo toolSettings |> tryStart @@ -64,7 +59,7 @@ module Runner = let rawError = proc.StandardError.ReadToEnd() proc.WaitForExit() - printer.Info $"{tool} finished in {watch.ElapsedFriendly}." + printer.Info $"{toolName} finished in {watch.ElapsedFriendly}." let maybeError = String.toOption rawError @@ -73,5 +68,5 @@ module Runner = Error = maybeError } else match maybeError with - | Some err -> Error $"%s{tool} exited with code %d{proc.ExitCode}: %s{err}." - | None -> Error $"%s{tool} exited with code %d{proc.ExitCode}." + | Some err -> Error $"%s{toolName} exited with code %d{proc.ExitCode}: %s{err}." + | None -> Error $"%s{toolName} exited with code %d{proc.ExitCode}." diff --git a/src/CCVTAC.Main/ExternalTools/ToolSettings.fs b/src/CCVTAC.Main/ExternalTools/ToolSettings.fs index 020b188b..c526bca0 100644 --- a/src/CCVTAC.Main/ExternalTools/ToolSettings.fs +++ b/src/CCVTAC.Main/ExternalTools/ToolSettings.fs @@ -5,18 +5,22 @@ type ToolSettings = private { Tool: string Args: string list - WorkingDirectory: string } + WorkingDir: string } module ToolSettings = - // Accessors - let tool t = t.Tool - let args t = t.Args - let workingDirectory t = t.WorkingDirectory + open System.IO - let create tool args workingDirectory : Result = + let tool t = t.Tool + let toolName t = t.Tool |> Path.GetFileName + let args t = t.Args + let argText t = t.Args |> String.concat " " + let workingDir t = t.WorkingDir + let runSummary t = $"Running %s{toolName t} using `%s{tool t} %s{argText t}`." + + let create tool args workingDir : Result = if System.String.IsNullOrWhiteSpace tool then Error "Tool name must not be empty." else Ok { Tool = tool Args = args - WorkingDirectory = workingDirectory } + WorkingDir = workingDir } From d8265099ef2d44b26129f738d1cde17694328697 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 4 Dec 2026 16:39:26 +0900 Subject: [PATCH 09/13] Use String.hasNoText --- src/CCVTAC.Main/ExternalTools/ToolSettings.fs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/CCVTAC.Main/ExternalTools/ToolSettings.fs b/src/CCVTAC.Main/ExternalTools/ToolSettings.fs index c526bca0..9026a22f 100644 --- a/src/CCVTAC.Main/ExternalTools/ToolSettings.fs +++ b/src/CCVTAC.Main/ExternalTools/ToolSettings.fs @@ -1,5 +1,7 @@ namespace CCVTAC.Main.ExternalTools +open CCFSharpUtils.Text + /// Settings to govern the behavior of an external program. type ToolSettings = private @@ -18,7 +20,7 @@ module ToolSettings = let runSummary t = $"Running %s{toolName t} using `%s{tool t} %s{argText t}`." let create tool args workingDir : Result = - if System.String.IsNullOrWhiteSpace tool then + if String.hasNoText tool then Error "Tool name must not be empty." else Ok { Tool = tool From b56cc2978ba0d085100671b9bc6cf5689d4834c3 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:36:24 +0900 Subject: [PATCH 10/13] Refactor isSuccessExitCode --- src/CCVTAC.Main/ExternalTools/Runner.fs | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/src/CCVTAC.Main/ExternalTools/Runner.fs b/src/CCVTAC.Main/ExternalTools/Runner.fs index 45bff9d8..863a6cbc 100644 --- a/src/CCVTAC.Main/ExternalTools/Runner.fs +++ b/src/CCVTAC.Main/ExternalTools/Runner.fs @@ -12,11 +12,10 @@ module Runner = type ToolResult = { ExitCode: int; Error: string option } - [] - let private successExitCode = 0 - - let private isSuccessExitCode otherSuccessExitCodes exitCode = - List.contains exitCode (successExitCode :: otherSuccessExitCodes) + let private isSuccessExitCode customSuccessCodes actualCode = + let normalSuccessCode = 0 + let allSuccessCodes = normalSuccessCode :: customSuccessCodes + allSuccessCodes |> List.contains actualCode let private buildStartInfo (toolSettings: ToolSettings) = let psi = ProcessStartInfo(ToolSettings.tool toolSettings) @@ -42,11 +41,7 @@ module Runner = | :? DirectoryNotFoundException as ex -> Error $"Working directory for {psi.FileName} does not exist: {ex.Message}" - /// Calls an external application. - /// Receives progress information about the tool's execution. - /// Settings governing the tool, its arguments, and its working directory. - /// Additional exit codes, other than 0, that can be treated as non-failures. - let runTool (printer: Printer) toolSettings otherSuccessExitCodes : Result = + let runTool (printer: Printer) toolSettings customSuccessCodes : Result = let watch = Watch() let toolName = ToolSettings.toolName toolSettings @@ -63,7 +58,7 @@ module Runner = let maybeError = String.toOption rawError - if isSuccessExitCode otherSuccessExitCodes proc.ExitCode then + if isSuccessExitCode customSuccessCodes proc.ExitCode then Ok { ExitCode = proc.ExitCode Error = maybeError } else From fb0d5ec45224646002c7815f89c82631364e4fa7 Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:43:23 +0900 Subject: [PATCH 11/13] Code layout --- 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 63a831cf..8b02d759 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -146,9 +146,7 @@ module Orchestrator = Read = _.QuietMode AfterToggle = fun s -> printer.ShowDebug(not s.QuietMode) } ] - let processCommand printer command settings (history: History) - : Result = - + let processCommand printer command settings (history: History) : Result = let checkCommand = List.containsIgnoreCase command let toggle = toggleSpecs printer From 90c1a6d1840cd5c3a9bb6e54b1b81355acb3a1da Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 4 Dec 2026 17:44:01 +0900 Subject: [PATCH 12/13] Remove unused func --- src/CCVTAC.Main/Shared.fs | 4 ---- 1 file changed, 4 deletions(-) diff --git a/src/CCVTAC.Main/Shared.fs b/src/CCVTAC.Main/Shared.fs index ab322fd9..a36539f5 100644 --- a/src/CCVTAC.Main/Shared.fs +++ b/src/CCVTAC.Main/Shared.fs @@ -5,7 +5,6 @@ open Spectre.Console [] module Shared = - open System type ConfirmationAnswer = | Proceed @@ -29,6 +28,3 @@ module Shared = |> loop seconds) doneMsgFn seconds - - let private splitOnSpaces (text: string) : string list = - text.Split([| ' ' |], StringSplitOptions.RemoveEmptyEntries) |> List.ofArray From 48608b888c646c08575e0a15f66411ecd62db70b Mon Sep 17 00:00:00 2001 From: CodeConscious <50596087+codeconscious@users.noreply.github.com> Date: Fri, 4 Dec 2026 22:31:19 +0900 Subject: [PATCH 13/13] Code layout tweak --- 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 8b02d759..fe510bad 100644 --- a/src/CCVTAC.Main/Orchestrator.fs +++ b/src/CCVTAC.Main/Orchestrator.fs @@ -237,7 +237,7 @@ module Orchestrator = let sleptMsg = sleep (fun remainingSeconds -> $"Sleeping for {secondsMsg remainingSeconds}...") - (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") + (fun totalSeconds -> $"Slept for {secondsMsg totalSeconds}.") seconds let options = PrintOptions.DefaultWithLineBefore printer.Info(sleptMsg, options)