From c4808d2fc682d1fd08305a39d67ff629ad3b8639 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 17:25:57 +0100 Subject: [PATCH 01/34] Windows Terminal portable mode support --- Bootstrappers/Bookgen.Win/InstallDetector.cs | 9 ++------- Setup/cdfiles.iss | 16 ++++++++-------- Setup/version.iss | 2 +- 3 files changed, 11 insertions(+), 16 deletions(-) diff --git a/Bootstrappers/Bookgen.Win/InstallDetector.cs b/Bootstrappers/Bookgen.Win/InstallDetector.cs index 362c2cf2..83c2168d 100644 --- a/Bootstrappers/Bookgen.Win/InstallDetector.cs +++ b/Bootstrappers/Bookgen.Win/InstallDetector.cs @@ -12,15 +12,10 @@ public static class InstallDetector { public static bool IsWindowsTerminalPortalbeInstalled(out string portablePath) { - string[] searchPaths = new[] - { - Path.Combine(AppContext.BaseDirectory, "terminal", Constants.WindowsTerminal), - Path.Combine(AppContext.BaseDirectory, "wt", Constants.WindowsTerminal), - }; - + string[] searchPaths = Directory.GetDirectories(AppContext.BaseDirectory, "*.*", SearchOption.TopDirectoryOnly); foreach (var searchPath in searchPaths) { - if (File.Exists(searchPath)) + if (File.Exists(Path.Combine(searchPath, Constants.WindowsTerminal))) { portablePath = searchPath; return true; diff --git a/Setup/cdfiles.iss b/Setup/cdfiles.iss index 71d44389..86b815c1 100644 --- a/Setup/cdfiles.iss +++ b/Setup/cdfiles.iss @@ -2,6 +2,7 @@ Source: "{src}\BookGen.exe"; DestDir: "{app}\"; Flags: ignoreversion external Source: "{src}\BookGen.Launcher.exe"; DestDir: "{app}\"; Flags: ignoreversion external Source: "{src}\Bookgen.Win.dll"; DestDir: "{app}\"; Flags: ignoreversion external +Source: "{src}\Documents.html"; DestDir: "{app}\"; Flags: ignoreversion external Source: "{src}\data\Accessibility.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\AngleSharp.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\bookgen-bg.png"; DestDir: "{app}\data"; Flags: ignoreversion external @@ -56,11 +57,6 @@ Source: "{src}\data\BookGen.ShellHelper.dll"; DestDir: "{app}\data"; Flags: igno Source: "{src}\data\BookGen.ShellHelper.exe"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\BookGen.ShellHelper.pdb"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\BookGen.ShellHelper.runtimeconfig.json"; DestDir: "{app}\data"; Flags: ignoreversion external -Source: "{src}\data\BookGen.Update.deps.json"; DestDir: "{app}\data"; Flags: ignoreversion external -Source: "{src}\data\BookGen.Update.dll"; DestDir: "{app}\data"; Flags: ignoreversion external -Source: "{src}\data\BookGen.Update.exe"; DestDir: "{app}\data"; Flags: ignoreversion external -Source: "{src}\data\BookGen.Update.pdb"; DestDir: "{app}\data"; Flags: ignoreversion external -Source: "{src}\data\BookGen.Update.runtimeconfig.json"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\BookGenShell.ps1"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\Cdg.deps.json"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\Cdg.dll"; DestDir: "{app}\data"; Flags: ignoreversion external @@ -84,9 +80,7 @@ Source: "{src}\data\coreclr.dll"; DestDir: "{app}\data"; Flags: ignoreversion ex Source: "{src}\data\createdump.exe"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\D3DCompiler_47_cor3.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\DirectWriteForwarder.dll"; DestDir: "{app}\data"; Flags: ignoreversion external -Source: "{src}\data\dotnet-Microsoft.XmlSerializer.Generator.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\ExCSS.dll"; DestDir: "{app}\data"; Flags: ignoreversion external -Source: "{src}\data\Fizzler.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\getting-started.mdr"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\HarfBuzzSharp.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\hostfxr.dll"; DestDir: "{app}\data"; Flags: ignoreversion external @@ -112,7 +106,7 @@ Source: "{src}\data\Microsoft.Win32.Registry.AccessControl.dll"; DestDir: "{app} Source: "{src}\data\Microsoft.Win32.Registry.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\Microsoft.Win32.SystemEvents.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\Microsoft.Xaml.Behaviors.dll"; DestDir: "{app}\data"; Flags: ignoreversion external -Source: "{src}\data\mscordaccore_amd64_amd64_8.0.23.41904.dll"; DestDir: "{app}\data"; Flags: ignoreversion external +Source: "{src}\data\mscordaccore_amd64_amd64_8.0.23.53103.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\mscordaccore.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\mscordbi.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\mscorlib.dll"; DestDir: "{app}\data"; Flags: ignoreversion external @@ -348,6 +342,12 @@ Source: "{src}\data\WebView2Loader.dll"; DestDir: "{app}\data"; Flags: ignorever Source: "{src}\data\WindowsBase.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\WindowsFormsIntegration.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\wpfgfx_cor3.dll"; DestDir: "{app}\data"; Flags: ignoreversion external +Source: "{src}\data\Www.deps.json"; DestDir: "{app}\data"; Flags: ignoreversion external +Source: "{src}\data\Www.dll"; DestDir: "{app}\data"; Flags: ignoreversion external +Source: "{src}\data\Www.exe"; DestDir: "{app}\data"; Flags: ignoreversion external +Source: "{src}\data\Www.pdb"; DestDir: "{app}\data"; Flags: ignoreversion external +Source: "{src}\data\Www.runtimeconfig.json"; DestDir: "{app}\data"; Flags: ignoreversion external +Source: "{src}\data\WwwConfig.xml"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\XmlDocMarkdown.Core.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\YamlDotNet.dll"; DestDir: "{app}\data"; Flags: ignoreversion external Source: "{src}\data\cs\Microsoft.CodeAnalysis.CSharp.resources.dll"; DestDir: "{app}\data\cs"; Flags: ignoreversion external diff --git a/Setup/version.iss b/Setup/version.iss index efe31dd5..e9d891cd 100644 --- a/Setup/version.iss +++ b/Setup/version.iss @@ -1 +1 @@ -#define MyAppVersion "2023.09.25" +#define MyAppVersion "2023.11.23" From 22f30df14b42a167282161c15be1b491997ee9fb Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 18:01:41 +0100 Subject: [PATCH 02/34] API Project cleanup --- Libs/BookGen.Api/BookGen.Api.csproj | 37 +++++++---------------------- 1 file changed, 9 insertions(+), 28 deletions(-) diff --git a/Libs/BookGen.Api/BookGen.Api.csproj b/Libs/BookGen.Api/BookGen.Api.csproj index 07854d83..8b2751b6 100644 --- a/Libs/BookGen.Api/BookGen.Api.csproj +++ b/Libs/BookGen.Api/BookGen.Api.csproj @@ -1,34 +1,15 @@ - - net8.0 - ..\..\bin\$(Configuration)\ - enable + + net8.0 + ..\..\bin\$(Configuration)\ + enable enable - BookGen - Copyright © Ruzsinzki Gábor 2019 - Ruzsinszki Gábor - - https://github.com/webmaster442/BookGen - https://github.com/webmaster442/BookGen - git - 18.0 - 18.0 - C# scripting API references for BookGen scripting - true - static site,api,cshap,scripting,bookgen - true - LICENCE - 18.0 - false + 18.0 + 18.0 + 18.0 + false ..\..\bin\$(Configuration)\BookGen.Api.xml - - - - - True - - - + From 17ecb220d3a2386c5244da4ffdc2d85f4c9b49eb Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 18:11:51 +0100 Subject: [PATCH 03/34] API Cleanup step 1 --- Libs/BookGen.Api/Api.cd | 96 ------------------- Libs/BookGen.Api/BookGen.Api.csproj | 10 +- Libs/BookGen.Api/ExitCode.cs | 42 -------- Libs/BookGen.Api/IScript.cs | 27 ------ Libs/BookGen.Api/IScriptHost.cs | 36 ------- Libs/{BookGen.Api => BookGen.Domain}/Link.cs | 0 .../Configuration/IReadOnlyAsset.cs | 0 .../Configuration/IReadOnlyBuildConfig.cs | 0 .../Configuration/IReadOnlyConfig.cs | 0 .../Configuration/IReadOnlyMetadata.cs | 0 .../Configuration/IReadOnlyTemplateOptions.cs | 0 .../Configuration/IReadOnlyTranslations.cs | 0 .../Configuration/IReadOnylStyleClasses.cs | 0 .../Configuration/IReadonlyImageOptions.cs | 0 .../ITableOfContents.cs | 4 +- 15 files changed, 4 insertions(+), 211 deletions(-) delete mode 100644 Libs/BookGen.Api/Api.cd delete mode 100644 Libs/BookGen.Api/ExitCode.cs delete mode 100644 Libs/BookGen.Api/IScript.cs delete mode 100644 Libs/BookGen.Api/IScriptHost.cs rename Libs/{BookGen.Api => BookGen.Domain}/Link.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/Configuration/IReadOnlyAsset.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/Configuration/IReadOnlyBuildConfig.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/Configuration/IReadOnlyConfig.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/Configuration/IReadOnlyMetadata.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/Configuration/IReadOnlyTemplateOptions.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/Configuration/IReadOnlyTranslations.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/Configuration/IReadOnylStyleClasses.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/Configuration/IReadonlyImageOptions.cs (100%) rename Libs/{BookGen.Api => BookGen.Interfaces}/ITableOfContents.cs (93%) diff --git a/Libs/BookGen.Api/Api.cd b/Libs/BookGen.Api/Api.cd deleted file mode 100644 index ad273891..00000000 --- a/Libs/BookGen.Api/Api.cd +++ /dev/null @@ -1,96 +0,0 @@ - - - - - - AAAAAIAAQAAAAAAAgAAAgAAAAAAAAIAACAAACAAAAiA= - Link.cs - - - - - - - AAAIAAAAAAAAAAAAAAAAABAAAAgAAAAAAAAAAEAACAA= - ILog.cs - - - - - - AAAAAACAAAAAAAAAAAAAAAAAAAAAIAAAAAAAAAAAAAA= - IScript.cs - - - - - - AAAAAAAAAAAAAAAAAgAACAAAAAgIAAAAgAAAAAAAAAA= - IScriptHost.cs - - - - - - AABAAAAABAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAIA= - ITableOfContents.cs - - - - - - AAAAAAAAAgAAAAAAAAAAACAAAAAAAAAAAAAAAAAAAAA= - Configuration\IReadOnlyAsset.cs - - - - - - AAgAAAACAAAAAAAAAAAgCAAAAAAAAAAAAAAAAAAAAIA= - Configuration\IReadOnlyBuildConfig.cs - - - - - - 4AAAAAAAAIAAAACCgAgAAAAAIAAAAAAAAAEAIAAEAAQ= - Configuration\IReadOnlyConfig.cs - - - - - - AAAAAAAAAAAAAEAAgAAAAAAAAAAAAAABAAAAAAAAAAA= - Configuration\IReadOnlyMetadata.cs - - - - - - AIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - Configuration\IReadOnlyTemplateOptions.cs - - - - - - AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA= - Configuration\IReadOnlyTranslations.cs - - - - - - AAAAAAgAAABAAAAAAQAgQBAAAAAAGBAAAAAAQAACAQA= - Configuration\IReadOnylStyleClasses.cs - - - - - - AAAIAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAAAEAACAA= - LogLevel.cs - - - - \ No newline at end of file diff --git a/Libs/BookGen.Api/BookGen.Api.csproj b/Libs/BookGen.Api/BookGen.Api.csproj index 8b2751b6..fa71b7ae 100644 --- a/Libs/BookGen.Api/BookGen.Api.csproj +++ b/Libs/BookGen.Api/BookGen.Api.csproj @@ -1,15 +1,9 @@ - + net8.0 - ..\..\bin\$(Configuration)\ - enable enable - 18.0 - 18.0 - 18.0 - false - ..\..\bin\$(Configuration)\BookGen.Api.xml + enable diff --git a/Libs/BookGen.Api/ExitCode.cs b/Libs/BookGen.Api/ExitCode.cs deleted file mode 100644 index d4bb2f55..00000000 --- a/Libs/BookGen.Api/ExitCode.cs +++ /dev/null @@ -1,42 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2019-2021 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -namespace BookGen.Api -{ - /// - /// BookGen Exit codes - /// - public enum ExitCode - { - /// - /// Success - /// - Succes = 0, - /// - /// Uncaught exception happened - /// - Exception = -1, - /// - /// Unknown command - /// - UnknownCommand = 1, - /// - /// Bad parameters for command - /// - BadParameters = 2, - /// - /// Bad config - /// - BadConfiguration = 3, - /// - /// Folder contains a bookgen.lock - /// - FolderLocked = 4, - /// - /// Not supported on executing platform - /// - PlatformNotSupported = 5, - } -} diff --git a/Libs/BookGen.Api/IScript.cs b/Libs/BookGen.Api/IScript.cs deleted file mode 100644 index c9e55776..00000000 --- a/Libs/BookGen.Api/IScript.cs +++ /dev/null @@ -1,27 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -namespace BookGen.Api -{ - /// - /// Interface for scripts. - /// Every Script must implement this interface. - /// - public interface IScript - { - /// - /// Script name. Later you can reference the script as a shorcode with this name. - /// - string InvokeName { get; } - - /// - /// The main entrypoint of the script. It gets executed when parsing the shortcode. - /// - /// Current script host - /// Arguments for the script - /// Markdown string - string ScriptMain(IScriptHost host, IArguments arguments); - } -} diff --git a/Libs/BookGen.Api/IScriptHost.cs b/Libs/BookGen.Api/IScriptHost.cs deleted file mode 100644 index bc50abf3..00000000 --- a/Libs/BookGen.Api/IScriptHost.cs +++ /dev/null @@ -1,36 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using BookGen.Api.Configuration; - -namespace BookGen.Api -{ - /// - /// Interface for accesing the current script runtime - /// - public interface IScriptHost - { - /// - /// Source directory of input files - /// - string SourceDirectory { get; } - /// - /// Current configuration in read-only mode. - /// - IReadOnlyConfig Configuration { get; } - /// - /// Currently processed book table of contents - /// - ITableOfContents TableOfContents { get; } - /// - /// Currently active build configuration - /// - IReadOnlyBuildConfig CurrentBuildConfig { get; } - /// - /// Script host log - /// - ILog Log { get; } - } -} diff --git a/Libs/BookGen.Api/Link.cs b/Libs/BookGen.Domain/Link.cs similarity index 100% rename from Libs/BookGen.Api/Link.cs rename to Libs/BookGen.Domain/Link.cs diff --git a/Libs/BookGen.Api/Configuration/IReadOnlyAsset.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyAsset.cs similarity index 100% rename from Libs/BookGen.Api/Configuration/IReadOnlyAsset.cs rename to Libs/BookGen.Interfaces/Configuration/IReadOnlyAsset.cs diff --git a/Libs/BookGen.Api/Configuration/IReadOnlyBuildConfig.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyBuildConfig.cs similarity index 100% rename from Libs/BookGen.Api/Configuration/IReadOnlyBuildConfig.cs rename to Libs/BookGen.Interfaces/Configuration/IReadOnlyBuildConfig.cs diff --git a/Libs/BookGen.Api/Configuration/IReadOnlyConfig.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyConfig.cs similarity index 100% rename from Libs/BookGen.Api/Configuration/IReadOnlyConfig.cs rename to Libs/BookGen.Interfaces/Configuration/IReadOnlyConfig.cs diff --git a/Libs/BookGen.Api/Configuration/IReadOnlyMetadata.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyMetadata.cs similarity index 100% rename from Libs/BookGen.Api/Configuration/IReadOnlyMetadata.cs rename to Libs/BookGen.Interfaces/Configuration/IReadOnlyMetadata.cs diff --git a/Libs/BookGen.Api/Configuration/IReadOnlyTemplateOptions.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyTemplateOptions.cs similarity index 100% rename from Libs/BookGen.Api/Configuration/IReadOnlyTemplateOptions.cs rename to Libs/BookGen.Interfaces/Configuration/IReadOnlyTemplateOptions.cs diff --git a/Libs/BookGen.Api/Configuration/IReadOnlyTranslations.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyTranslations.cs similarity index 100% rename from Libs/BookGen.Api/Configuration/IReadOnlyTranslations.cs rename to Libs/BookGen.Interfaces/Configuration/IReadOnlyTranslations.cs diff --git a/Libs/BookGen.Api/Configuration/IReadOnylStyleClasses.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnylStyleClasses.cs similarity index 100% rename from Libs/BookGen.Api/Configuration/IReadOnylStyleClasses.cs rename to Libs/BookGen.Interfaces/Configuration/IReadOnylStyleClasses.cs diff --git a/Libs/BookGen.Api/Configuration/IReadonlyImageOptions.cs b/Libs/BookGen.Interfaces/Configuration/IReadonlyImageOptions.cs similarity index 100% rename from Libs/BookGen.Api/Configuration/IReadonlyImageOptions.cs rename to Libs/BookGen.Interfaces/Configuration/IReadonlyImageOptions.cs diff --git a/Libs/BookGen.Api/ITableOfContents.cs b/Libs/BookGen.Interfaces/ITableOfContents.cs similarity index 93% rename from Libs/BookGen.Api/ITableOfContents.cs rename to Libs/BookGen.Interfaces/ITableOfContents.cs index 66b0b3e6..e821f58a 100644 --- a/Libs/BookGen.Api/ITableOfContents.cs +++ b/Libs/BookGen.Interfaces/ITableOfContents.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api +namespace BookGen.Interfaces { /// /// Interface for accesing the table of contents From 75efcf00598689719d957ca1810942ba4e6e4a20 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 18:26:48 +0100 Subject: [PATCH 04/34] New API & Scrpt running progress --- Libs/BookGen.Domain/Configuration/Asset.cs | 4 ++-- Libs/BookGen.Domain/Configuration/BuildConfig.cs | 5 +++-- Libs/BookGen.Domain/Configuration/Config.cs | 5 +++-- Libs/BookGen.Domain/Configuration/ImageOptions.cs | 4 ++-- Libs/BookGen.Domain/Configuration/Metadata.cs | 4 ++-- Libs/BookGen.Domain/Configuration/StyleClasses.cs | 4 ++-- Libs/BookGen.Domain/Configuration/TemplateOptions.cs | 5 ++--- Libs/BookGen.Domain/Configuration/Translations.cs | 5 ++--- Libs/BookGen.Domain/RuntimeSettings.cs | 4 ++-- Libs/BookGen.Domain/TOC.cs | 4 ++-- Libs/BookGen.DomainServices/Markdown/PipelineHelpers.cs | 4 ++-- Libs/BookGen.DomainServices/MarkdownUtils.cs | 4 +++- Libs/BookGen.DomainServices/MetaExtensions.cs | 4 ++-- Libs/BookGen.Interfaces/Configuration/IReadOnlyAsset.cs | 4 ++-- .../Configuration/IReadOnlyBuildConfig.cs | 4 ++-- Libs/BookGen.Interfaces/Configuration/IReadOnlyConfig.cs | 4 ++-- Libs/BookGen.Interfaces/Configuration/IReadOnlyMetadata.cs | 4 ++-- .../Configuration/IReadOnlyTemplateOptions.cs | 4 ++-- .../Configuration/IReadOnlyTranslations.cs | 4 ++-- .../Configuration/IReadOnylStyleClasses.cs | 4 ++-- .../Configuration/IReadonlyImageOptions.cs | 4 ++-- Libs/BookGen.Interfaces/IReadonlyRuntimeSettings.cs | 3 +-- Libs/{BookGen.Domain => BookGen.Interfaces}/Link.cs | 6 +++--- Prog/BookGen/Framework/Shortcodes/Translate.cs | 2 +- Prog/BookGen/GeneratorSteps/GenerateSearchPage.cs | 4 ++-- Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs | 2 +- Prog/BookGen/ShortCodeLoader.cs | 4 ++-- 27 files changed, 55 insertions(+), 54 deletions(-) rename Libs/{BookGen.Domain => BookGen.Interfaces}/Link.cs (92%) diff --git a/Libs/BookGen.Domain/Configuration/Asset.cs b/Libs/BookGen.Domain/Configuration/Asset.cs index bcf91149..766171cd 100644 --- a/Libs/BookGen.Domain/Configuration/Asset.cs +++ b/Libs/BookGen.Domain/Configuration/Asset.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; namespace BookGen.Domain.Configuration { diff --git a/Libs/BookGen.Domain/Configuration/BuildConfig.cs b/Libs/BookGen.Domain/Configuration/BuildConfig.cs index e089a5e3..deed322d 100644 --- a/Libs/BookGen.Domain/Configuration/BuildConfig.cs +++ b/Libs/BookGen.Domain/Configuration/BuildConfig.cs @@ -1,11 +1,12 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; using System.Text.Json.Serialization; +using BookGen.Interfaces.Configuration; + namespace BookGen.Domain.Configuration { public sealed class BuildConfig : IReadOnlyBuildConfig diff --git a/Libs/BookGen.Domain/Configuration/Config.cs b/Libs/BookGen.Domain/Configuration/Config.cs index a15cc094..2458d5d1 100644 --- a/Libs/BookGen.Domain/Configuration/Config.cs +++ b/Libs/BookGen.Domain/Configuration/Config.cs @@ -1,13 +1,14 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; using System.ComponentModel.DataAnnotations; using System.Globalization; using System.Text.Json.Serialization; +using BookGen.Interfaces.Configuration; + namespace BookGen.Domain.Configuration { public sealed class Config : IReadOnlyConfig diff --git a/Libs/BookGen.Domain/Configuration/ImageOptions.cs b/Libs/BookGen.Domain/Configuration/ImageOptions.cs index 690fa4e0..7e7f196d 100644 --- a/Libs/BookGen.Domain/Configuration/ImageOptions.cs +++ b/Libs/BookGen.Domain/Configuration/ImageOptions.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; namespace BookGen.Domain.Configuration { diff --git a/Libs/BookGen.Domain/Configuration/Metadata.cs b/Libs/BookGen.Domain/Configuration/Metadata.cs index 61b4cf21..55583f5b 100644 --- a/Libs/BookGen.Domain/Configuration/Metadata.cs +++ b/Libs/BookGen.Domain/Configuration/Metadata.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; namespace BookGen.Domain.Configuration { diff --git a/Libs/BookGen.Domain/Configuration/StyleClasses.cs b/Libs/BookGen.Domain/Configuration/StyleClasses.cs index 358ef897..fc5504eb 100644 --- a/Libs/BookGen.Domain/Configuration/StyleClasses.cs +++ b/Libs/BookGen.Domain/Configuration/StyleClasses.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; namespace BookGen.Domain.Configuration { diff --git a/Libs/BookGen.Domain/Configuration/TemplateOptions.cs b/Libs/BookGen.Domain/Configuration/TemplateOptions.cs index 2ee11b9c..bffb68a9 100644 --- a/Libs/BookGen.Domain/Configuration/TemplateOptions.cs +++ b/Libs/BookGen.Domain/Configuration/TemplateOptions.cs @@ -1,10 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; -using System.Runtime.Serialization; +using BookGen.Interfaces.Configuration; namespace BookGen.Domain.Configuration { diff --git a/Libs/BookGen.Domain/Configuration/Translations.cs b/Libs/BookGen.Domain/Configuration/Translations.cs index 380afb13..c91fd694 100644 --- a/Libs/BookGen.Domain/Configuration/Translations.cs +++ b/Libs/BookGen.Domain/Configuration/Translations.cs @@ -1,10 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; -using System.Runtime.Serialization; +using BookGen.Interfaces.Configuration; namespace BookGen.Domain.Configuration { diff --git a/Libs/BookGen.Domain/RuntimeSettings.cs b/Libs/BookGen.Domain/RuntimeSettings.cs index da9681cb..bdd3f65d 100644 --- a/Libs/BookGen.Domain/RuntimeSettings.cs +++ b/Libs/BookGen.Domain/RuntimeSettings.cs @@ -1,10 +1,10 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using BookGen.Api; -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; using BookGen.Domain.Configuration; using BookGen.Interfaces; using System.Collections.Concurrent; diff --git a/Libs/BookGen.Domain/TOC.cs b/Libs/BookGen.Domain/TOC.cs index cbb732f2..9c2b3e8a 100644 --- a/Libs/BookGen.Domain/TOC.cs +++ b/Libs/BookGen.Domain/TOC.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api; +using BookGen.Interfaces; namespace BookGen.Domain { diff --git a/Libs/BookGen.DomainServices/Markdown/PipelineHelpers.cs b/Libs/BookGen.DomainServices/Markdown/PipelineHelpers.cs index 0a91a52b..dd83b431 100644 --- a/Libs/BookGen.DomainServices/Markdown/PipelineHelpers.cs +++ b/Libs/BookGen.DomainServices/Markdown/PipelineHelpers.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; using BookGen.Interfaces; using Markdig.Parsers; using Markdig.Renderers; diff --git a/Libs/BookGen.DomainServices/MarkdownUtils.cs b/Libs/BookGen.DomainServices/MarkdownUtils.cs index ec3f25d0..693a9b26 100644 --- a/Libs/BookGen.DomainServices/MarkdownUtils.cs +++ b/Libs/BookGen.DomainServices/MarkdownUtils.cs @@ -1,10 +1,12 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using BookGen.Api; using BookGen.Domain; +using BookGen.Interfaces; + using Markdig; using Markdig.Extensions.AutoIdentifiers; using Markdig.Syntax; diff --git a/Libs/BookGen.DomainServices/MetaExtensions.cs b/Libs/BookGen.DomainServices/MetaExtensions.cs index a637ee1f..c69f49d7 100644 --- a/Libs/BookGen.DomainServices/MetaExtensions.cs +++ b/Libs/BookGen.DomainServices/MetaExtensions.cs @@ -1,12 +1,12 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using System.Text; using System.Web; -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; using BookGen.Domain; namespace BookGen.DomainServices diff --git a/Libs/BookGen.Interfaces/Configuration/IReadOnlyAsset.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyAsset.cs index 2d6a67fd..a252227f 100644 --- a/Libs/BookGen.Interfaces/Configuration/IReadOnlyAsset.cs +++ b/Libs/BookGen.Interfaces/Configuration/IReadOnlyAsset.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor +// (c) 2020-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api.Configuration +namespace BookGen.Interfaces.Configuration { /// /// Represents an asset that needs to be coppied to the output directory diff --git a/Libs/BookGen.Interfaces/Configuration/IReadOnlyBuildConfig.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyBuildConfig.cs index 4c7a8459..c120a947 100644 --- a/Libs/BookGen.Interfaces/Configuration/IReadOnlyBuildConfig.cs +++ b/Libs/BookGen.Interfaces/Configuration/IReadOnlyBuildConfig.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor +// (c) 2020-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api.Configuration +namespace BookGen.Interfaces.Configuration { /// /// Current build configuration diff --git a/Libs/BookGen.Interfaces/Configuration/IReadOnlyConfig.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyConfig.cs index 8fd8b6d3..feacae13 100644 --- a/Libs/BookGen.Interfaces/Configuration/IReadOnlyConfig.cs +++ b/Libs/BookGen.Interfaces/Configuration/IReadOnlyConfig.cs @@ -1,11 +1,11 @@ //----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor +// (c) 2020-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using System.Globalization; -namespace BookGen.Api.Configuration +namespace BookGen.Interfaces.Configuration { /// /// Provides acces the current configuration diff --git a/Libs/BookGen.Interfaces/Configuration/IReadOnlyMetadata.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyMetadata.cs index aa320c1c..aee4b522 100644 --- a/Libs/BookGen.Interfaces/Configuration/IReadOnlyMetadata.cs +++ b/Libs/BookGen.Interfaces/Configuration/IReadOnlyMetadata.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor +// (c) 2020-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api.Configuration +namespace BookGen.Interfaces.Configuration { /// /// Metadata informations diff --git a/Libs/BookGen.Interfaces/Configuration/IReadOnlyTemplateOptions.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyTemplateOptions.cs index 326df4c3..83686e2c 100644 --- a/Libs/BookGen.Interfaces/Configuration/IReadOnlyTemplateOptions.cs +++ b/Libs/BookGen.Interfaces/Configuration/IReadOnlyTemplateOptions.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor +// (c) 2020-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api.Configuration +namespace BookGen.Interfaces.Configuration { /// /// Template options. diff --git a/Libs/BookGen.Interfaces/Configuration/IReadOnlyTranslations.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnlyTranslations.cs index b439c737..d1d4a8a8 100644 --- a/Libs/BookGen.Interfaces/Configuration/IReadOnlyTranslations.cs +++ b/Libs/BookGen.Interfaces/Configuration/IReadOnlyTranslations.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor +// (c) 2020-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api.Configuration +namespace BookGen.Interfaces.Configuration { /// /// a Dictionary of key - value paris that can be used for translating diff --git a/Libs/BookGen.Interfaces/Configuration/IReadOnylStyleClasses.cs b/Libs/BookGen.Interfaces/Configuration/IReadOnylStyleClasses.cs index d11c61fb..80172caf 100644 --- a/Libs/BookGen.Interfaces/Configuration/IReadOnylStyleClasses.cs +++ b/Libs/BookGen.Interfaces/Configuration/IReadOnylStyleClasses.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor +// (c) 2020-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api.Configuration +namespace BookGen.Interfaces.Configuration { /// /// Additional style classes that will be aplied to html elements diff --git a/Libs/BookGen.Interfaces/Configuration/IReadonlyImageOptions.cs b/Libs/BookGen.Interfaces/Configuration/IReadonlyImageOptions.cs index 8d99e86b..f99dd7a7 100644 --- a/Libs/BookGen.Interfaces/Configuration/IReadonlyImageOptions.cs +++ b/Libs/BookGen.Interfaces/Configuration/IReadonlyImageOptions.cs @@ -1,9 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor +// (c) 2020 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api.Configuration +namespace BookGen.Interfaces.Configuration { /// /// Image pipeline options diff --git a/Libs/BookGen.Interfaces/IReadonlyRuntimeSettings.cs b/Libs/BookGen.Interfaces/IReadonlyRuntimeSettings.cs index cbd6b800..901a51c3 100644 --- a/Libs/BookGen.Interfaces/IReadonlyRuntimeSettings.cs +++ b/Libs/BookGen.Interfaces/IReadonlyRuntimeSettings.cs @@ -3,8 +3,7 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api; -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; namespace BookGen.Interfaces { diff --git a/Libs/BookGen.Domain/Link.cs b/Libs/BookGen.Interfaces/Link.cs similarity index 92% rename from Libs/BookGen.Domain/Link.cs rename to Libs/BookGen.Interfaces/Link.cs index ac527472..3affb105 100644 --- a/Libs/BookGen.Domain/Link.cs +++ b/Libs/BookGen.Interfaces/Link.cs @@ -1,14 +1,14 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Api +namespace BookGen.Interfaces { /// /// Represents a link in the Markdown Table of Contents. /// - public sealed class Link + public sealed record class Link { /// /// Link text, that will be displayed. diff --git a/Prog/BookGen/Framework/Shortcodes/Translate.cs b/Prog/BookGen/Framework/Shortcodes/Translate.cs index 8beb9e6a..6110a514 100644 --- a/Prog/BookGen/Framework/Shortcodes/Translate.cs +++ b/Prog/BookGen/Framework/Shortcodes/Translate.cs @@ -5,7 +5,7 @@ using System.ComponentModel.Composition; -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; namespace BookGen.Framework.Shortcodes; diff --git a/Prog/BookGen/GeneratorSteps/GenerateSearchPage.cs b/Prog/BookGen/GeneratorSteps/GenerateSearchPage.cs index dd9f4dd7..d5141c60 100644 --- a/Prog/BookGen/GeneratorSteps/GenerateSearchPage.cs +++ b/Prog/BookGen/GeneratorSteps/GenerateSearchPage.cs @@ -1,12 +1,12 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api.Configuration; using BookGen.Domain.Configuration; using BookGen.DomainServices.Markdown; using BookGen.Framework; +using BookGen.Interfaces.Configuration; using BookGen.Resources; namespace BookGen.GeneratorSteps; diff --git a/Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs b/Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs index 9ea434b7..03c2030a 100644 --- a/Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs +++ b/Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs @@ -5,7 +5,7 @@ using System.Diagnostics; -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; using BookGen.Domain.Configuration; using BookGen.Domain.Wordpress; using BookGen.DomainServices.Markdown; diff --git a/Prog/BookGen/ShortCodeLoader.cs b/Prog/BookGen/ShortCodeLoader.cs index 717cd838..2ce6678c 100644 --- a/Prog/BookGen/ShortCodeLoader.cs +++ b/Prog/BookGen/ShortCodeLoader.cs @@ -1,12 +1,12 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; -using BookGen.Api.Configuration; +using BookGen.Interfaces.Configuration; namespace BookGen; From a134f2e54bccceefc1fe69a7fc4392814d256d06 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 18:40:02 +0100 Subject: [PATCH 05/34] New API & Scrpt running progress --- Libs/BookGen.Domain/Constants.cs | 4 +- Libs/BookGen.Interfaces/ITemplateShortCode.cs | 15 ++- Prog/BookGen/Framework/GeneratorStepRunner.cs | 11 +- Prog/BookGen/Framework/Scripts/Compiler.cs | 108 ---------------- .../Framework/Scripts/CsharpScriptHandler.cs | 112 ---------------- Prog/BookGen/Framework/Scripts/NodeHost.cs | 120 ------------------ Prog/BookGen/Framework/Scripts/NodeJs.cs | 42 ------ Prog/BookGen/Framework/Scripts/Php.cs | 42 ------ .../Framework/Scripts/ProcessInterop.cs | 58 --------- Prog/BookGen/Framework/Scripts/Python.cs | 42 ------ Prog/BookGen/Framework/Scripts/ScriptHost.cs | 30 ----- .../Framework/Scripts/ScriptProcess.cs | 57 --------- .../Framework/Server/PreviewRenderHandler.cs | 3 +- Prog/BookGen/Framework/ShortCodeParser.cs | 13 +- .../Shortcodes/CookieWarnIfEnabledInTarget.cs | 10 +- Prog/BookGen/GeneratorRunner.cs | 22 +--- .../EpubGeneratorStepRunner.cs | 7 +- .../PostProcessGenreratorStepRunner.cs | 8 +- .../PrintGeneratorStepRunner.cs | 7 +- .../WebsiteGeneratorStepRunner.cs | 7 +- .../WordpressGeneratorStepRunner.cs | 7 +- Prog/BookGen/GeneratorSteps/ImageProcessor.cs | 6 +- Prog/BookGen/Infrastructure/Extensions.cs | 2 +- 23 files changed, 55 insertions(+), 678 deletions(-) delete mode 100644 Prog/BookGen/Framework/Scripts/Compiler.cs delete mode 100644 Prog/BookGen/Framework/Scripts/CsharpScriptHandler.cs delete mode 100644 Prog/BookGen/Framework/Scripts/NodeHost.cs delete mode 100644 Prog/BookGen/Framework/Scripts/NodeJs.cs delete mode 100644 Prog/BookGen/Framework/Scripts/Php.cs delete mode 100644 Prog/BookGen/Framework/Scripts/ProcessInterop.cs delete mode 100644 Prog/BookGen/Framework/Scripts/Python.cs delete mode 100644 Prog/BookGen/Framework/Scripts/ScriptHost.cs delete mode 100644 Prog/BookGen/Framework/Scripts/ScriptProcess.cs diff --git a/Libs/BookGen.Domain/Constants.cs b/Libs/BookGen.Domain/Constants.cs index c89ab96c..26bdf3dd 100644 --- a/Libs/BookGen.Domain/Constants.cs +++ b/Libs/BookGen.Domain/Constants.cs @@ -9,8 +9,10 @@ public static class Constants { public const int Succes = 0; public const int ArgumentsError = 1; + public const int ConfigError = 2; + public const int FolderLocked = 3; public const int GeneralError = int.MaxValue; - public const int UpdateError = int.MinValue; + public const int UpdateError = int.MinValue; public const string WikiUrl = "https://github.com/webmaster442/BookGen/wiki"; diff --git a/Libs/BookGen.Interfaces/ITemplateShortCode.cs b/Libs/BookGen.Interfaces/ITemplateShortCode.cs index 348ab745..8aeae65d 100644 --- a/Libs/BookGen.Interfaces/ITemplateShortCode.cs +++ b/Libs/BookGen.Interfaces/ITemplateShortCode.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2019 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -9,8 +9,21 @@ namespace BookGen.Interfaces { public interface ITemplateShortCode { + /// + /// ShortCode activator tag + /// string Tag { get; } + + /// + /// ShortCode main entry point + /// + /// Arguments passed to the short code + /// Generated string output string Generate(IArguments arguments); + + /// + /// If true, then the shortCode result is cached and not run every time + /// bool CanCacheResult { get; } } } diff --git a/Prog/BookGen/Framework/GeneratorStepRunner.cs b/Prog/BookGen/Framework/GeneratorStepRunner.cs index 37b1151b..8c76d43b 100644 --- a/Prog/BookGen/Framework/GeneratorStepRunner.cs +++ b/Prog/BookGen/Framework/GeneratorStepRunner.cs @@ -1,11 +1,10 @@ //----------------------------------------------------------------------------- -// (c) 2019-2021 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using System.Diagnostics; -using BookGen.Framework.Scripts; using BookGen.Gui; namespace BookGen.Framework; @@ -13,7 +12,6 @@ namespace BookGen.Framework; internal abstract class GeneratorStepRunner : IDisposable { private readonly List _steps; - private readonly CsharpScriptHandler _scriptHandler; private readonly StaticTemplateContent _staticContent; private readonly List _redirectedLogMessages; private bool _logListen; @@ -27,8 +25,7 @@ internal abstract class GeneratorStepRunner : IDisposable protected GeneratorStepRunner(RuntimeSettings settings, ILog log, - ShortCodeLoader shortCodeLoader, - CsharpScriptHandler scriptHandler) + ShortCodeLoader shortCodeLoader) { Settings = settings; _redirectedLogMessages = new List(); @@ -36,9 +33,6 @@ protected GeneratorStepRunner(RuntimeSettings settings, _loader = shortCodeLoader; _loader.LoadAll(); - _scriptHandler = scriptHandler; - scriptHandler.SetHostFromRuntimeSettings(Settings); - _steps = new List(); _log = log; _log.OnLogWritten += OnLogWritten; @@ -62,7 +56,6 @@ private TemplateProcessor CreateTemplateProcessor() { return new TemplateProcessor(Settings.Configuration, new ShortCodeParser(_loader.Imports, - _scriptHandler, Settings.Configuration.Translations, _log), _staticContent); diff --git a/Prog/BookGen/Framework/Scripts/Compiler.cs b/Prog/BookGen/Framework/Scripts/Compiler.cs deleted file mode 100644 index 349c9c60..00000000 --- a/Prog/BookGen/Framework/Scripts/Compiler.cs +++ /dev/null @@ -1,108 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.Reflection; -using System.Runtime.Loader; - -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Emit; - -namespace BookGen.Framework.Scripts; - -/// -/// Compiles C# script files into Assembly -/// Compilation uses Roslyn API & the generated assembly is only in memory -/// -internal class Compiler -{ - private readonly HashSet _references; - private readonly ILog _log; - private readonly CSharpCompilationOptions _compilerOptions; - - public Compiler(ILog log) - { - _references = new HashSet(); - _log = log; - ReferenceNetStandard(); - AddTypeReference(); - _compilerOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) - .WithPlatform(Platform.AnyCpu) - .WithNullableContextOptions(NullableContextOptions.Enable) - .WithOverflowChecks(true) - .WithOptimizationLevel(OptimizationLevel.Release); - } - - private void ReferenceNetStandard() - { - if (!(AppContext.GetData("TRUSTED_PLATFORM_ASSEMBLIES") is string trusted)) - throw new DependencyException("Can't locate Trusted platform assemblies"); - - string[]? trustedAssembliesPaths = trusted.Split(Path.PathSeparator); - - string[]? neededAssemblies = new[] - { - "System.Runtime", - "netstandard", - }; - IEnumerable? references = trustedAssembliesPaths - .Where(p => neededAssemblies.Contains(Path.GetFileNameWithoutExtension(p))) - .Select(p => MetadataReference.CreateFromFile(p)); - - foreach (PortableExecutableReference? reference in references) - { - _references.Add(reference); - } - } - - public void AddTypeReference() - { - string location = typeof(TType).GetTypeInfo().Assembly.Location; - _references.Add(MetadataReference.CreateFromFile(location)); - } - - public IEnumerable ParseToSyntaxTree(IEnumerable files) - { - foreach (FsPath? file in files) - { - string content = file.ReadFile(_log); - SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(content, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest)); - yield return tree; - } - } - - public IEnumerable ParseToSyntaxTree(string source) - { - SyntaxTree tree = SyntaxFactory.ParseSyntaxTree(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Latest)); - yield return tree; - } - - public Assembly? CompileToAssembly(IEnumerable syntaxTrees) - { - string? timestamp = $"{DateTime.Now.Hour}{DateTime.Now.Minute}{DateTime.Now.Second}{DateTime.Now.Millisecond}"; - CSharpCompilation compiler = CSharpCompilation.Create($"scripts_{timestamp}.dll") - .WithOptions(_compilerOptions) - .AddReferences(_references.ToArray()) - .AddSyntaxTrees(syntaxTrees); - - using (var compiled = new MemoryStream(32 * 1024)) - { - EmitResult emitResult = compiler.Emit(compiled); - if (emitResult.Success) - { - compiled.Seek(0, SeekOrigin.Begin); - return AssemblyLoadContext.Default.LoadFromStream(compiled); - } - else - { - _log.Warning("Error Compiling scripts. Use verbose log to see details"); - string? details = string.Join('\n', emitResult.Diagnostics); - _log.Detail(details); - } - } - - return null; - } -} \ No newline at end of file diff --git a/Prog/BookGen/Framework/Scripts/CsharpScriptHandler.cs b/Prog/BookGen/Framework/Scripts/CsharpScriptHandler.cs deleted file mode 100644 index 3ae41ae5..00000000 --- a/Prog/BookGen/Framework/Scripts/CsharpScriptHandler.cs +++ /dev/null @@ -1,112 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.Reflection; - -namespace BookGen.Framework.Scripts; - -/// -/// Handles script loading, compiling, and executing -/// -internal class CsharpScriptHandler -{ - private readonly ILog _log; - private IScriptHost? _host; - private readonly Compiler _compiler; - private readonly List _scripts; - private readonly HashSet _scriptNames; - - - public CsharpScriptHandler(ILog log) - { - _log = log; - _compiler = new Compiler(log); - _compiler.AddTypeReference>(); - _compiler.AddTypeReference(); - _compiler.AddTypeReference(); - _scripts = new List(); - _scriptNames = new HashSet(); - } - - public int LoadScripts(FsPath scriptsDir) - { - try - { - IEnumerable? files = scriptsDir.GetAllFiles(true, "*.cs"); - IEnumerable trees = _compiler.ParseToSyntaxTree(files); - - Assembly? assembly = _compiler.CompileToAssembly(trees); - if (assembly != null) - { - int count = SearchAndAddTypes(assembly); - return count; - } - - return 0; - } - catch (Exception ex) - { - _log.Warning(ex); - return 0; - } - - } - - public bool IsKnownScript(string name) - { - return _scriptNames.Contains(name); - } - - public void SetHostFromRuntimeSettings(IReadonlyRuntimeSettings runtimeSettings) - { - _host = new ScriptHost(runtimeSettings, _log); - } - - public string ExecuteScript(string name, IArguments arguments) - { - if (_host == null) - throw new DependencyException(nameof(_host)); - - try - { - IScript? script = _scripts.FirstOrDefault(s => string.Compare(s.InvokeName, name, true) == 0); - if (script == null) - { - _log.Warning("Script not found: {0}", name); - return string.Empty; - } - - return script.ScriptMain(_host, arguments); - } - catch (Exception ex) - { - _log.Warning(ex); - return string.Empty; - } - } - - private int SearchAndAddTypes(Assembly assembly) - { - Type? iscript = typeof(IScript); - int loaded = 0; - foreach (Type? IScriptType in assembly.GetTypes().Where(x => iscript.IsAssignableFrom(x))) - { - try - { - if (Activator.CreateInstance(IScriptType) is IScript instance) - { - _scripts.Add(instance); - _scriptNames.Add(instance.InvokeName); - ++loaded; - } - } - catch (Exception ex) - { - _log.Warning(ex); - } - } - return loaded; - } -} diff --git a/Prog/BookGen/Framework/Scripts/NodeHost.cs b/Prog/BookGen/Framework/Scripts/NodeHost.cs deleted file mode 100644 index a64e33fb..00000000 --- a/Prog/BookGen/Framework/Scripts/NodeHost.cs +++ /dev/null @@ -1,120 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020-2022 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.Diagnostics; - -namespace BookGen.Framework.Scripts; - -internal class NodeHost -{ - private readonly ILog _log; - private readonly IAppSetting _appSettings; - - public NodeHost(ILog log, IAppSetting appSettings) - { - _log = log; - _appSettings = appSettings; - } - - internal static string EncodeForCmdLine(string arg) - { - var stringBuilder = new StringBuilder(arg.Length); - int slashSequenceLength = 0; - for (int i = 0; i < arg.Length; i++) - { - char currentChar = arg[i]; - - if (currentChar == '\\') - { - slashSequenceLength++; - - // If the last character in the argument is \, it must be escaped, together with any \ that immediately preceed it. - // This prevents situations like: SomeExecutable.exe "SomeArg\", where the quote meant to demarcate the end of the - // argument gets escaped. - if (i == arg.Length - 1) - { - for (int j = 0; j < slashSequenceLength; j++) - { - stringBuilder. - Append('\\'). - Append('\\'); - } - } - } - else if (currentChar == '"') - { - // Every \ or sequence of \ that preceed a " must be escaped. - for (int j = 0; j < slashSequenceLength; j++) - { - stringBuilder. - Append('\\'). - Append('\\'); - } - slashSequenceLength = 0; - - stringBuilder. - Append('\\'). - Append('"'); - } - else - { - for (int j = 0; j < slashSequenceLength; j++) - { - stringBuilder.Append('\\'); - } - slashSequenceLength = 0; - - stringBuilder.Append(currentChar); - } - } - - return stringBuilder.ToString(); - } - - - public async Task Evaluate(string script) - { - _log.Detail("Executing Nodejs script..."); - string program = ProcessInterop.AppendExecutableExtension("node"); - string? programPath = ProcessInterop.ResolveProgramFullPath(program, _appSettings.NodeJsPath); - - if (programPath == null) - { - _log.Warning("Script run failed. Program not found: {0}", program); - return $"{program} not found to execute"; - } - - string output = ""; - - try - { - using (var process = new Process()) - { - process.StartInfo = new ProcessStartInfo - { - CreateNoWindow = true, - RedirectStandardInput = true, - RedirectStandardOutput = true, - UseShellExecute = false, - RedirectStandardError = true, - FileName = programPath, - Arguments = $"-e \"{EncodeForCmdLine(script)}\"" - }; - - process.Start(); - output = await process.StandardOutput.ReadToEndAsync(); - process.WaitForExit(_appSettings.NodeJsTimeout * 1000); - - } - return output; - } - catch (Exception ex) - { - _log.Warning("Script run failed with Exception: {0}", ex.Message); - _log.Detail("Stack Trace: {0}", ex.StackTrace ?? ""); - return $"Script run failed with Exception: {ex.Message}"; - } - } -} diff --git a/Prog/BookGen/Framework/Scripts/NodeJs.cs b/Prog/BookGen/Framework/Scripts/NodeJs.cs deleted file mode 100644 index 6a6e10c9..00000000 --- a/Prog/BookGen/Framework/Scripts/NodeJs.cs +++ /dev/null @@ -1,42 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020-2022 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.ComponentModel.Composition; - -namespace BookGen.Framework.Scripts; - -[Export(typeof(ITemplateShortCode))] -internal class NodeJs : ScriptProcess, ITemplateShortCode -{ - private readonly IReadonlyRuntimeSettings _settings; - private readonly IAppSetting _appSetting; - - [ImportingConstructor] - public NodeJs(ILog log, IReadonlyRuntimeSettings settings, IAppSetting appSetting) : base(log) - { - _settings = settings; - _appSetting = appSetting; - } - - public string Tag => "NodeJs"; - - public bool CanCacheResult => false; - - public string Generate(IArguments arguments) - { - string? file = arguments.GetArgumentOrThrow("file"); - _log.Info("Trying to execute NoseJs script: {0} ...", file); - - return ExecuteScriptProcess("node", _appSetting.NodeJsPath, file, _appSetting.NodeJsTimeout); - } - - protected override void SerializeHostInfo(string scriptPath) - { - var hostinfo = new FsPath(scriptPath, "hostinfo.js"); - var host = new ScriptHost(_settings, _log); - string content = JsonInliner.InlineJs(nameof(host), host); - hostinfo.WriteFile(_log, content); - } -} diff --git a/Prog/BookGen/Framework/Scripts/Php.cs b/Prog/BookGen/Framework/Scripts/Php.cs deleted file mode 100644 index ac93316a..00000000 --- a/Prog/BookGen/Framework/Scripts/Php.cs +++ /dev/null @@ -1,42 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020-2022 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.ComponentModel.Composition; - -namespace BookGen.Framework.Scripts; - -[Export(typeof(ITemplateShortCode))] -internal class Php : ScriptProcess, ITemplateShortCode -{ - private readonly IReadonlyRuntimeSettings _settings; - private readonly IAppSetting _appSetting; - - [ImportingConstructor] - public Php(ILog log, IReadonlyRuntimeSettings settings, IAppSetting appSetting) : base(log) - { - _settings = settings; - _appSetting = appSetting; - } - - public string Tag => "Php"; - - public bool CanCacheResult => false; - - public string Generate(IArguments arguments) - { - string? file = arguments.GetArgumentOrThrow("file"); - _log.Info("Trying to execute PHP CGI script: {0} ...", file); - - return ExecuteScriptProcess("php-cgi", _appSetting.PhpPath, file, _appSetting.PhpTimeout); - } - - protected override void SerializeHostInfo(string scriptPath) - { - var hostinfo = new FsPath(scriptPath, "hostinfo.php"); - var host = new ScriptHost(_settings, _log); - string? content = JsonInliner.InlinePhp(nameof(host), host); - hostinfo.WriteFile(_log, content); - } -} diff --git a/Prog/BookGen/Framework/Scripts/ProcessInterop.cs b/Prog/BookGen/Framework/Scripts/ProcessInterop.cs deleted file mode 100644 index ac277a26..00000000 --- a/Prog/BookGen/Framework/Scripts/ProcessInterop.cs +++ /dev/null @@ -1,58 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020-2022 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.Runtime.InteropServices; - -namespace BookGen.Framework.Scripts; - -internal static class ProcessInterop -{ - public static string? ResolveProgramFullPath(string programName, string additional = "") - { - string? pathVar = Environment.GetEnvironmentVariable("path"); - - if (pathVar == null) - return null; - - var searchFolders = new List(20); - - if (AppDomain.CurrentDomain.BaseDirectory != null) - searchFolders.Add(AppDomain.CurrentDomain.BaseDirectory); - - searchFolders.AddRange(pathVar.Split(';')); - - if (!string.IsNullOrEmpty(additional)) - searchFolders.Add(additional); - - foreach (string folder in searchFolders) - { - string programFile = Path.Combine(folder, programName); - - if (File.Exists(programFile)) - { - return programFile; - } - } - - return null; - } - - internal static string AppendExecutableExtension(string file) - { - if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) - || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) - { - return file; - } - else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) - { - return $"{file}.exe"; - } - else - { - throw new InvalidOperationException("Unknown host operating system"); - } - } -} diff --git a/Prog/BookGen/Framework/Scripts/Python.cs b/Prog/BookGen/Framework/Scripts/Python.cs deleted file mode 100644 index 551c0878..00000000 --- a/Prog/BookGen/Framework/Scripts/Python.cs +++ /dev/null @@ -1,42 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020-2022 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.ComponentModel.Composition; - -namespace BookGen.Framework.Scripts; - -[Export(typeof(ITemplateShortCode))] -internal class Python : ScriptProcess, ITemplateShortCode -{ - private readonly IReadonlyRuntimeSettings _settings; - private readonly IAppSetting _appSetting; - - [ImportingConstructor] - public Python(ILog log, IReadonlyRuntimeSettings settings, IAppSetting appSetting) : base(log) - { - _settings = settings; - _appSetting = appSetting; - } - - public string Tag => "Python"; - - public bool CanCacheResult => false; - - public string Generate(IArguments arguments) - { - string? file = arguments.GetArgumentOrThrow("file"); - _log.Info("Trying to execute Python script: {0} ...", file); - - return ExecuteScriptProcess("python", _appSetting.PythonPath, file, _appSetting.PythonTimeout); - } - - protected override void SerializeHostInfo(string scriptPath) - { - var hostinfo = new FsPath(scriptPath, "hostinfo.php"); - var host = new ScriptHost(_settings, _log); - string? content = JsonInliner.InlinePython(nameof(host), host); - hostinfo.WriteFile(_log, content); - } -} diff --git a/Prog/BookGen/Framework/Scripts/ScriptHost.cs b/Prog/BookGen/Framework/Scripts/ScriptHost.cs deleted file mode 100644 index 35e20aae..00000000 --- a/Prog/BookGen/Framework/Scripts/ScriptHost.cs +++ /dev/null @@ -1,30 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using BookGen.Api.Configuration; - -namespace BookGen.Framework.Scripts; - -internal class ScriptHost : IScriptHost -{ - public string SourceDirectory { get; } - - public IReadOnlyConfig Configuration { get; } - - public IReadOnlyBuildConfig CurrentBuildConfig { get; } - - public ILog Log { get; } - - public ITableOfContents TableOfContents { get; } - - public ScriptHost(IReadonlyRuntimeSettings runtimeSettings, ILog log) - { - SourceDirectory = runtimeSettings.SourceDirectory.ToString(); - Configuration = runtimeSettings.Configuration; - CurrentBuildConfig = runtimeSettings.CurrentBuildConfig; - TableOfContents = runtimeSettings.TocContents; - Log = log; - } -} diff --git a/Prog/BookGen/Framework/Scripts/ScriptProcess.cs b/Prog/BookGen/Framework/Scripts/ScriptProcess.cs deleted file mode 100644 index 15bf0b6a..00000000 --- a/Prog/BookGen/Framework/Scripts/ScriptProcess.cs +++ /dev/null @@ -1,57 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020-2022 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -namespace BookGen.Framework.Scripts; - -public abstract class ScriptProcess -{ - protected ILog _log; - - protected ScriptProcess(ILog log) - { - _log = log; - } - - protected string ExecuteScriptProcess(string programWithoutExtension, string searchPath, string fileToExecute, int timeout) - { - string program = ProcessInterop.AppendExecutableExtension(programWithoutExtension); - string? programPath = ProcessInterop.ResolveProgramFullPath(program, searchPath); - - if (programPath == null) - { - _log.Warning("{0} was not found on path.", program); - return $"{program} was not found on path"; - } - - string? scriptPath = Path.GetDirectoryName(fileToExecute); - - if (scriptPath != null) - SerializeHostInfo(scriptPath); - - try - { - (int exitcode, string output) = ProcessRunner.RunProcess(programPath, fileToExecute, timeout); - - if (exitcode != 0) - { - _log.Warning("Script run failed. Exit code: {0}", exitcode); - _log.Detail("Script output: {0}", output); - return $"Script run failed: {fileToExecute}"; - } - else - { - return output; - } - } - catch (Exception ex) - { - _log.Warning("Script run failed with Exception: {0}", ex.Message); - _log.Detail("Stack Trace: {0}", ex.StackTrace ?? ""); - return $"Script run failed with Exception: {ex.Message}"; - } - } - - protected abstract void SerializeHostInfo(string scriptPath); -} diff --git a/Prog/BookGen/Framework/Server/PreviewRenderHandler.cs b/Prog/BookGen/Framework/Server/PreviewRenderHandler.cs index 6b294897..7a116f83 100644 --- a/Prog/BookGen/Framework/Server/PreviewRenderHandler.cs +++ b/Prog/BookGen/Framework/Server/PreviewRenderHandler.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2021-2022 Ruzsinszki Gábor +// (c) 2021-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -32,7 +32,6 @@ public PreviewRenderHandler(string directory, ILog log) _processor = new TemplateProcessor(new Config(), new ShortCodeParser(new List(), - new Scripts.CsharpScriptHandler(_log), new Translations(), _log), new StaticTemplateContent()); diff --git a/Prog/BookGen/Framework/ShortCodeParser.cs b/Prog/BookGen/Framework/ShortCodeParser.cs index f2da4e5b..02599716 100644 --- a/Prog/BookGen/Framework/ShortCodeParser.cs +++ b/Prog/BookGen/Framework/ShortCodeParser.cs @@ -1,10 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using BookGen.Domain.Configuration; -using BookGen.Framework.Scripts; using BookGen.Framework.Shortcodes; namespace BookGen.Framework; @@ -14,7 +13,6 @@ internal sealed partial class ShortCodeParser private readonly Dictionary _shortCodesIndex; private readonly Dictionary _codeResultCache; private readonly Translations _translations; - private readonly CsharpScriptHandler _scriptHandler; private readonly ILog _log; private const string shortCodeStart = ""; + private const string ShortCodeStart = ""; [GeneratedRegex("()")] private partial Regex TranslateRegex(); @@ -61,12 +61,12 @@ private static string GetTagKey(string value) if (parts.Length == 1) { //value is eg. - int len = value.Length - shortCodeStart.Length - shortCodeEnd.Length; - return value.Substring(shortCodeStart.Length, len); + int len = value.Length - ShortCodeStart.Length - ShortCodeEnd.Length; + return value.Substring(ShortCodeStart.Length, len); } else { - return parts[0][shortCodeStart.Length..].Trim(); + return parts[0][ShortCodeStart.Length..].Trim(); } } @@ -82,7 +82,7 @@ private string AdditionalTranslate(string input) foreach (Match? match in matches) { if (match == null) continue; - string? key = match.Value.Replace($"{shortCodeStart}? ", "").Replace(shortCodeEnd, ""); + string? key = match.Value.Replace($"{ShortCodeStart}? ", "").Replace(ShortCodeEnd, ""); string? text = Translate.DoTranslateForKey(_translations, key); @@ -114,7 +114,7 @@ private static ShortCodeArguments GetArguments(string value) } else { - results.TryAdd(pair[0].Replace(shortCodeEnd, ""), string.Empty); + results.TryAdd(pair[0].Replace(ShortCodeEnd, ""), string.Empty); } } } @@ -124,10 +124,10 @@ private static ShortCodeArguments GetArguments(string value) private static string RemoveStartingSpaceAndEndTags(string input) { //input string will be in following format: "Assets/bootstrap.min.css"}--> - if (input.StartsWith("\"") && input.EndsWith("\"}-->")) + if (input.StartsWith('"') && input.EndsWith("\"}-->")) { //need to retgurn only: Assets/bootstrap.min.css - return input.Substring(1, input.Length - (shortCodeEnd.Length + 2)); + return input.Substring(1, input.Length - (ShortCodeEnd.Length + 2)); } return input; } @@ -141,15 +141,14 @@ public string Parse(string content) if (match != null) { string? tagKey = GetTagKey(match.Value); - if (_codeResultCache.ContainsKey(match.Value)) + if (_codeResultCache.TryGetValue(match.Value, out string? value)) { //Cache has it stored, so simply lookup and replace - result.Replace(match.Value, _codeResultCache[match.Value]); + result.Replace(match.Value, value); } - else if (_shortCodesIndex.ContainsKey(tagKey)) + else if (_shortCodesIndex.TryGetValue(tagKey, out ITemplateShortCode? shortcode)) { //It is a known shortcode, so run it - ITemplateShortCode? shortcode = _shortCodesIndex[tagKey]; string? generated = shortcode.Generate(GetArguments(match.Value)); result.Replace(match.Value, generated); //For next iteration of it's occurance cache it if it's cacheable diff --git a/Prog/BookGen/GeneratorRunner.cs b/Prog/BookGen/GeneratorRunner.cs index 7cd47c11..90ae449b 100644 --- a/Prog/BookGen/GeneratorRunner.cs +++ b/Prog/BookGen/GeneratorRunner.cs @@ -27,7 +27,7 @@ internal class GeneratorRunner private readonly IAppSetting _appSettings; private readonly ProgramInfo _programInfo; - public FsPath ConfigFile { get; private set; } + public FsPath ConfigFile { get; } public string WorkDirectory { @@ -99,7 +99,6 @@ public bool Initialize() Log.Info("Os: {0}", Environment.OSVersion.VersionString); Log.Info("---------------------------------------------------------"); - bool ret = _projectLoader.LoadProject(); if (!ret && !NoWait) diff --git a/Prog/BookGen/GeneratorSteps/ImageProcessor.cs b/Prog/BookGen/GeneratorSteps/ImageProcessor.cs index 9f3b5910..5008ec43 100644 --- a/Prog/BookGen/GeneratorSteps/ImageProcessor.cs +++ b/Prog/BookGen/GeneratorSteps/ImageProcessor.cs @@ -28,7 +28,7 @@ public void RunStep(IReadonlyRuntimeSettings settings, ILog log) }); } - private void ProcessImage(FsPath file, IReadonlyRuntimeSettings settings, FsPath targetdir, ILog log) + private static void ProcessImage(FsPath file, IReadonlyRuntimeSettings settings, FsPath targetdir, ILog log) { IReadonlyImageOptions? options = settings.CurrentBuildConfig.ImageOptions; @@ -82,7 +82,12 @@ private void ProcessImage(FsPath file, IReadonlyRuntimeSettings settings, FsPath } } - private void InlineOrSave(FsPath file, FsPath targetdir, ILog log, IReadonlyRuntimeSettings settings, SKData data, string? extensionOverride = null) + private static void InlineOrSave(FsPath file, + FsPath targetdir, + ILog log, + IReadonlyRuntimeSettings settings, + SKData data, + string? extensionOverride = null) { if (data.Size < settings.CurrentBuildConfig.ImageOptions.InlineImageSizeLimit) { @@ -111,7 +116,7 @@ private static void InlineImage(FsPath file, IReadonlyRuntimeSettings settings, settings.InlineImgCache.TryAdd(key, $"data:{mime};base64,{base64}"); } - private void SaveImage(FsPath file, FsPath targetdir, ILog log, SKData data, string? extensionOverride) + private static void SaveImage(FsPath file, FsPath targetdir, ILog log, SKData data, string? extensionOverride) { FsPath target = targetdir.Combine(file.Filename); if (extensionOverride != null) diff --git a/Prog/BookGen/ShortCodeLoader.cs b/Prog/BookGen/ShortCodeLoader.cs index 2ce6678c..062d8867 100644 --- a/Prog/BookGen/ShortCodeLoader.cs +++ b/Prog/BookGen/ShortCodeLoader.cs @@ -41,7 +41,7 @@ public ShortCodeLoader(ILog log, IReadonlyRuntimeSettings settings, IAppSetting typeof(IReadonlyRuntimeSettings), typeof(IAppSetting))); catalog.Catalogs.Add(new AssemblyCatalog(typeof(ShortCodeLoader).Assembly)); - Imports = new List(); + Imports = []; _container = new CompositionContainer(catalog); } diff --git a/Test/BookGen.TestsSystem/SystemTestBase.cs b/Test/BookGen.TestsSystem/SystemTestBase.cs index 8860eaba..dbc0e6f8 100644 --- a/Test/BookGen.TestsSystem/SystemTestBase.cs +++ b/Test/BookGen.TestsSystem/SystemTestBase.cs @@ -28,7 +28,7 @@ protected SystemTestBase(string workDir) { _workDir = Path.Combine(AppContext.BaseDirectory, workDir); Environment = new TestEnvironment(_workDir); - LastLog = new List(); + LastLog = []; } protected void EnsureRunWithoutException(int expectedExitCode, string commandLine) @@ -62,11 +62,11 @@ private static List GetLog(string output) options.Converters.Add(new JsonStringEnumConverter()); List? list = JsonSerializer.Deserialize>(output, options); - return list ?? new List(); + return list ?? []; } catch (Exception) { - return new List(); + return []; } } From 0963cacac0aad36a677f300566085fef81ffa433 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 18:58:14 +0100 Subject: [PATCH 08/34] ITemplateShortCode: Part of API now --- Libs/{BookGen.Interfaces => BookGen.Api}/ITemplateShortCode.cs | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Libs/{BookGen.Interfaces => BookGen.Api}/ITemplateShortCode.cs (100%) diff --git a/Libs/BookGen.Interfaces/ITemplateShortCode.cs b/Libs/BookGen.Api/ITemplateShortCode.cs similarity index 100% rename from Libs/BookGen.Interfaces/ITemplateShortCode.cs rename to Libs/BookGen.Api/ITemplateShortCode.cs From 37fe9bbf9d302b63bb14722061a1109c4a2047d1 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 19:11:36 +0100 Subject: [PATCH 09/34] Moved shortcodes --- BookGen.sln | 7 +++++++ Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj | 12 ++++++++++++ .../BookGen.ShortCodes}/BuildTime.cs | 0 .../CookieWarnIfEnabledInTarget.cs | 0 .../BookGen.ShortCodes}/DelegateShortCode.cs | 0 .../BookGen.ShortCodes}/InlineFile.cs | 0 .../BookGen.ShortCodes}/JSPageToc.cs | 0 .../BookGen.ShortCodes}/SriDependency.cs | 0 .../BookGen.ShortCodes}/Translate.cs | 0 9 files changed, 19 insertions(+) create mode 100644 Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj rename {Prog/BookGen/Framework/Shortcodes => Libs/BookGen.ShortCodes}/BuildTime.cs (100%) rename {Prog/BookGen/Framework/Shortcodes => Libs/BookGen.ShortCodes}/CookieWarnIfEnabledInTarget.cs (100%) rename {Prog/BookGen/Framework/Shortcodes => Libs/BookGen.ShortCodes}/DelegateShortCode.cs (100%) rename {Prog/BookGen/Framework/Shortcodes => Libs/BookGen.ShortCodes}/InlineFile.cs (100%) rename {Prog/BookGen/Framework/Shortcodes => Libs/BookGen.ShortCodes}/JSPageToc.cs (100%) rename {Prog/BookGen/Framework/Shortcodes => Libs/BookGen.ShortCodes}/SriDependency.cs (100%) rename {Prog/BookGen/Framework/Shortcodes => Libs/BookGen.ShortCodes}/Translate.cs (100%) diff --git a/BookGen.sln b/BookGen.sln index fe31f17a..abf6c65b 100644 --- a/BookGen.sln +++ b/BookGen.sln @@ -62,6 +62,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BookGen.Native", "Libs\Book EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Www", "Prog\Www\Www.csproj", "{F9BB566F-AC41-4028-A00C-0200EC53E1D7}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "BookGen.ShortCodes", "Libs\BookGen.ShortCodes\BookGen.ShortCodes.csproj", "{079B77CD-3380-4947-BDE8-E0E774FD8E6F}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -144,6 +146,10 @@ Global {F9BB566F-AC41-4028-A00C-0200EC53E1D7}.Debug|Any CPU.Build.0 = Debug|Any CPU {F9BB566F-AC41-4028-A00C-0200EC53E1D7}.Release|Any CPU.ActiveCfg = Release|Any CPU {F9BB566F-AC41-4028-A00C-0200EC53E1D7}.Release|Any CPU.Build.0 = Release|Any CPU + {079B77CD-3380-4947-BDE8-E0E774FD8E6F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {079B77CD-3380-4947-BDE8-E0E774FD8E6F}.Debug|Any CPU.Build.0 = Debug|Any CPU + {079B77CD-3380-4947-BDE8-E0E774FD8E6F}.Release|Any CPU.ActiveCfg = Release|Any CPU + {079B77CD-3380-4947-BDE8-E0E774FD8E6F}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -168,6 +174,7 @@ Global {5F49A217-883B-499C-BEBD-22BC02E5EC8F} = {05B69A0E-343B-4E7C-B77B-24E84B57D5D2} {8A1FEF90-2B8F-4849-B7C9-63EDE7F120E0} = {9C47BBFF-ACD8-40D8-9FB1-A3FA524B27C4} {F9BB566F-AC41-4028-A00C-0200EC53E1D7} = {05B69A0E-343B-4E7C-B77B-24E84B57D5D2} + {079B77CD-3380-4947-BDE8-E0E774FD8E6F} = {9C47BBFF-ACD8-40D8-9FB1-A3FA524B27C4} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {772515BA-79D4-4C5D-AF16-29DE649EC13E} diff --git a/Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj b/Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj new file mode 100644 index 00000000..4ed6398a --- /dev/null +++ b/Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj @@ -0,0 +1,12 @@ + + + + net8.0 + BookGen + ..\..\bin\$(Configuration)\ + enable + enable + false + + + diff --git a/Prog/BookGen/Framework/Shortcodes/BuildTime.cs b/Libs/BookGen.ShortCodes/BuildTime.cs similarity index 100% rename from Prog/BookGen/Framework/Shortcodes/BuildTime.cs rename to Libs/BookGen.ShortCodes/BuildTime.cs diff --git a/Prog/BookGen/Framework/Shortcodes/CookieWarnIfEnabledInTarget.cs b/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs similarity index 100% rename from Prog/BookGen/Framework/Shortcodes/CookieWarnIfEnabledInTarget.cs rename to Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs diff --git a/Prog/BookGen/Framework/Shortcodes/DelegateShortCode.cs b/Libs/BookGen.ShortCodes/DelegateShortCode.cs similarity index 100% rename from Prog/BookGen/Framework/Shortcodes/DelegateShortCode.cs rename to Libs/BookGen.ShortCodes/DelegateShortCode.cs diff --git a/Prog/BookGen/Framework/Shortcodes/InlineFile.cs b/Libs/BookGen.ShortCodes/InlineFile.cs similarity index 100% rename from Prog/BookGen/Framework/Shortcodes/InlineFile.cs rename to Libs/BookGen.ShortCodes/InlineFile.cs diff --git a/Prog/BookGen/Framework/Shortcodes/JSPageToc.cs b/Libs/BookGen.ShortCodes/JSPageToc.cs similarity index 100% rename from Prog/BookGen/Framework/Shortcodes/JSPageToc.cs rename to Libs/BookGen.ShortCodes/JSPageToc.cs diff --git a/Prog/BookGen/Framework/Shortcodes/SriDependency.cs b/Libs/BookGen.ShortCodes/SriDependency.cs similarity index 100% rename from Prog/BookGen/Framework/Shortcodes/SriDependency.cs rename to Libs/BookGen.ShortCodes/SriDependency.cs diff --git a/Prog/BookGen/Framework/Shortcodes/Translate.cs b/Libs/BookGen.ShortCodes/Translate.cs similarity index 100% rename from Prog/BookGen/Framework/Shortcodes/Translate.cs rename to Libs/BookGen.ShortCodes/Translate.cs From 55c4924828fab73840e0bfa9afbe28cf3d64725b Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 19:19:36 +0100 Subject: [PATCH 10/34] Shortcode project adaptation --- Libs/BookGen.Api/ITemplateShortCode.cs | 4 +--- Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj | 12 ++++++++++++ Libs/BookGen.ShortCodes/BuildTime.cs | 4 +--- .../CookieWarnIfEnabledInTarget.cs | 3 +-- Libs/BookGen.ShortCodes/DelegateShortCode.cs | 2 +- Libs/BookGen.ShortCodes/InlineFile.cs | 10 +++------- Libs/BookGen.ShortCodes/JSPageToc.cs | 6 ++++-- Libs/BookGen.ShortCodes/SriDependency.cs | 8 ++++---- Libs/BookGen.ShortCodes/Translate.cs | 3 ++- Libs/BookGen.ShortCodes/usings.cs | 3 +++ 10 files changed, 32 insertions(+), 23 deletions(-) create mode 100644 Libs/BookGen.ShortCodes/usings.cs diff --git a/Libs/BookGen.Api/ITemplateShortCode.cs b/Libs/BookGen.Api/ITemplateShortCode.cs index cab7a363..b5d43b54 100644 --- a/Libs/BookGen.Api/ITemplateShortCode.cs +++ b/Libs/BookGen.Api/ITemplateShortCode.cs @@ -3,9 +3,7 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api; - -namespace BookGen.Interfaces +namespace BookGen.Api { public interface ITemplateShortCode { diff --git a/Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj b/Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj index 4ed6398a..988c1ca5 100644 --- a/Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj +++ b/Libs/BookGen.ShortCodes/BookGen.ShortCodes.csproj @@ -9,4 +9,16 @@ false + + + + + + + + + + + + diff --git a/Libs/BookGen.ShortCodes/BuildTime.cs b/Libs/BookGen.ShortCodes/BuildTime.cs index 282e29f6..a08ee50b 100644 --- a/Libs/BookGen.ShortCodes/BuildTime.cs +++ b/Libs/BookGen.ShortCodes/BuildTime.cs @@ -1,10 +1,8 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using System.ComponentModel.Composition; - namespace BookGen.Framework.Shortcodes; [Export(typeof(ITemplateShortCode))] diff --git a/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs b/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs index 99f3747e..6f8e564a 100644 --- a/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs +++ b/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs @@ -3,9 +3,8 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using System.ComponentModel.Composition; - using BookGen.Domain.Configuration; +using BookGen.Interfaces; using BookGen.Interfaces.Configuration; using BookGen.Resources; diff --git a/Libs/BookGen.ShortCodes/DelegateShortCode.cs b/Libs/BookGen.ShortCodes/DelegateShortCode.cs index 1873af1e..100d7257 100644 --- a/Libs/BookGen.ShortCodes/DelegateShortCode.cs +++ b/Libs/BookGen.ShortCodes/DelegateShortCode.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- diff --git a/Libs/BookGen.ShortCodes/InlineFile.cs b/Libs/BookGen.ShortCodes/InlineFile.cs index 5efd1136..c341023c 100644 --- a/Libs/BookGen.ShortCodes/InlineFile.cs +++ b/Libs/BookGen.ShortCodes/InlineFile.cs @@ -1,10 +1,8 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using System.ComponentModel.Composition; - namespace BookGen.Framework.Shortcodes; [Export(typeof(ITemplateShortCode))] @@ -26,10 +24,8 @@ public string Generate(IArguments arguments) { string? name = arguments.GetArgumentOrThrow("file"); - var file = new FsPath(name); - - _log.Detail("Inlineing {0}...", file); + _log.Detail("Inlineing {0}...", name); - return file.ReadFile(_log); + return File.ReadAllText(name); } } diff --git a/Libs/BookGen.ShortCodes/JSPageToc.cs b/Libs/BookGen.ShortCodes/JSPageToc.cs index d005d1b4..1bbd80d0 100644 --- a/Libs/BookGen.ShortCodes/JSPageToc.cs +++ b/Libs/BookGen.ShortCodes/JSPageToc.cs @@ -1,9 +1,11 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using System.ComponentModel.Composition; +using System.Text; + +using BookGen.DomainServices; using BookGen.Resources; diff --git a/Libs/BookGen.ShortCodes/SriDependency.cs b/Libs/BookGen.ShortCodes/SriDependency.cs index c42556f3..c94147c1 100644 --- a/Libs/BookGen.ShortCodes/SriDependency.cs +++ b/Libs/BookGen.ShortCodes/SriDependency.cs @@ -1,9 +1,10 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using System.ComponentModel.Composition; +using BookGen.DomainServices; +using BookGen.Interfaces; namespace BookGen.Framework.Shortcodes; @@ -27,8 +28,7 @@ public SriDependency(ILog log, IReadonlyRuntimeSettings settings) private string ComputeSRI(FsPath filePath) { _log.Detail("Computing SRI and caching results for {0}...", filePath); - string sri = CryptoUitils.GetSRI(filePath); - return sri; + return CryptoUitils.GetSRI(filePath); } public string Generate(IArguments arguments) diff --git a/Libs/BookGen.ShortCodes/Translate.cs b/Libs/BookGen.ShortCodes/Translate.cs index ae2bbddb..f269591c 100644 --- a/Libs/BookGen.ShortCodes/Translate.cs +++ b/Libs/BookGen.ShortCodes/Translate.cs @@ -3,8 +3,9 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using System.ComponentModel.Composition; +using System.Text.RegularExpressions; +using BookGen.Domain; using BookGen.Interfaces.Configuration; namespace BookGen.Framework.Shortcodes; diff --git a/Libs/BookGen.ShortCodes/usings.cs b/Libs/BookGen.ShortCodes/usings.cs new file mode 100644 index 00000000..10cfa1f4 --- /dev/null +++ b/Libs/BookGen.ShortCodes/usings.cs @@ -0,0 +1,3 @@ +global using System.ComponentModel.Composition; + +global using BookGen.Api; From 1a435ca2e617f54fffb3ab25fb1d455d3c497223 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 19:59:17 +0100 Subject: [PATCH 11/34] Adapted Shortcdes --- Libs/BookGen.ShortCodes/BuildTime.cs | 3 ++- Libs/BookGen.ShortCodes/BuiltInShortCodeAttribute.cs | 6 ++++++ Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs | 3 ++- Libs/BookGen.ShortCodes/DelegateShortCode.cs | 3 ++- Libs/BookGen.ShortCodes/InlineFile.cs | 3 ++- Libs/BookGen.ShortCodes/JSPageToc.cs | 3 ++- Libs/BookGen.ShortCodes/SriDependency.cs | 3 ++- Libs/BookGen.ShortCodes/Translate.cs | 3 ++- 8 files changed, 20 insertions(+), 7 deletions(-) create mode 100644 Libs/BookGen.ShortCodes/BuiltInShortCodeAttribute.cs diff --git a/Libs/BookGen.ShortCodes/BuildTime.cs b/Libs/BookGen.ShortCodes/BuildTime.cs index a08ee50b..87d05f32 100644 --- a/Libs/BookGen.ShortCodes/BuildTime.cs +++ b/Libs/BookGen.ShortCodes/BuildTime.cs @@ -3,9 +3,10 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Framework.Shortcodes; +namespace BookGen.ShortCodes; [Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] public sealed class BuildTime : ITemplateShortCode { public string Tag => nameof(BuildTime); diff --git a/Libs/BookGen.ShortCodes/BuiltInShortCodeAttribute.cs b/Libs/BookGen.ShortCodes/BuiltInShortCodeAttribute.cs new file mode 100644 index 00000000..7e347822 --- /dev/null +++ b/Libs/BookGen.ShortCodes/BuiltInShortCodeAttribute.cs @@ -0,0 +1,6 @@ +namespace BookGen.ShortCodes; + +[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)] +public sealed class BuiltInShortCodeAttribute : Attribute +{ +} diff --git a/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs b/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs index 6f8e564a..dbc8386e 100644 --- a/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs +++ b/Libs/BookGen.ShortCodes/CookieWarnIfEnabledInTarget.cs @@ -8,9 +8,10 @@ using BookGen.Interfaces.Configuration; using BookGen.Resources; -namespace BookGen.Framework.Shortcodes; +namespace BookGen.ShortCodes; [Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] public sealed class CookieWarnIfEnabledInTarget : ITemplateShortCode { private readonly ILog _log; diff --git a/Libs/BookGen.ShortCodes/DelegateShortCode.cs b/Libs/BookGen.ShortCodes/DelegateShortCode.cs index 100d7257..6842e30f 100644 --- a/Libs/BookGen.ShortCodes/DelegateShortCode.cs +++ b/Libs/BookGen.ShortCodes/DelegateShortCode.cs @@ -3,8 +3,9 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Framework.Shortcodes; +namespace BookGen.ShortCodes; +[BuiltInShortCode] public sealed class DelegateShortCode : ITemplateShortCode { private readonly Func _generator; diff --git a/Libs/BookGen.ShortCodes/InlineFile.cs b/Libs/BookGen.ShortCodes/InlineFile.cs index c341023c..84e400e0 100644 --- a/Libs/BookGen.ShortCodes/InlineFile.cs +++ b/Libs/BookGen.ShortCodes/InlineFile.cs @@ -3,9 +3,10 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -namespace BookGen.Framework.Shortcodes; +namespace BookGen.ShortCodes; [Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] public sealed class InlineFile : ITemplateShortCode { private readonly ILog _log; diff --git a/Libs/BookGen.ShortCodes/JSPageToc.cs b/Libs/BookGen.ShortCodes/JSPageToc.cs index 1bbd80d0..64fd5b25 100644 --- a/Libs/BookGen.ShortCodes/JSPageToc.cs +++ b/Libs/BookGen.ShortCodes/JSPageToc.cs @@ -9,9 +9,10 @@ using BookGen.Resources; -namespace BookGen.Framework.Shortcodes; +namespace BookGen.ShortCodes; [Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] public sealed class JSPageToc : ITemplateShortCode { public string Tag => nameof(JSPageToc); diff --git a/Libs/BookGen.ShortCodes/SriDependency.cs b/Libs/BookGen.ShortCodes/SriDependency.cs index c94147c1..f3b8620f 100644 --- a/Libs/BookGen.ShortCodes/SriDependency.cs +++ b/Libs/BookGen.ShortCodes/SriDependency.cs @@ -6,9 +6,10 @@ using BookGen.DomainServices; using BookGen.Interfaces; -namespace BookGen.Framework.Shortcodes; +namespace BookGen.ShortCodes; [Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] public sealed class SriDependency : ITemplateShortCode { private readonly ILog _log; diff --git a/Libs/BookGen.ShortCodes/Translate.cs b/Libs/BookGen.ShortCodes/Translate.cs index f269591c..fe2dea12 100644 --- a/Libs/BookGen.ShortCodes/Translate.cs +++ b/Libs/BookGen.ShortCodes/Translate.cs @@ -8,9 +8,10 @@ using BookGen.Domain; using BookGen.Interfaces.Configuration; -namespace BookGen.Framework.Shortcodes; +namespace BookGen.ShortCodes; [Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] public sealed partial class Translate : ITemplateShortCode { private readonly IReadOnlyTranslations _translations; From 97ff6d27b0b07e65667f0f0b13f6dc1385a6d3cc Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 20:13:51 +0100 Subject: [PATCH 12/34] Shortcode loader: plugin support --- Libs/BookGen.Contents/BookGen.Contents.csproj | 3 ++ Libs/BookGen.Contents/ShortCodes/Readme.txt | 8 ++++ Prog/BookGen/BookGen.csproj | 1 + Prog/BookGen/Framework/ShortCodeParser.cs | 8 +--- Prog/BookGen/Framework/TemplateProcessor.cs | 2 +- Prog/BookGen/ShortCodeLoader.cs | 40 ++++++++++++++++++- Test/BookGen.Tests/GlobalUsings.cs | 2 +- 7 files changed, 55 insertions(+), 9 deletions(-) create mode 100644 Libs/BookGen.Contents/ShortCodes/Readme.txt diff --git a/Libs/BookGen.Contents/BookGen.Contents.csproj b/Libs/BookGen.Contents/BookGen.Contents.csproj index 277388bf..7baf2cb3 100644 --- a/Libs/BookGen.Contents/BookGen.Contents.csproj +++ b/Libs/BookGen.Contents/BookGen.Contents.csproj @@ -15,6 +15,9 @@ PreserveNewest + + PreserveNewest + PreserveNewest diff --git a/Libs/BookGen.Contents/ShortCodes/Readme.txt b/Libs/BookGen.Contents/ShortCodes/Readme.txt new file mode 100644 index 00000000..14641b3e --- /dev/null +++ b/Libs/BookGen.Contents/ShortCodes/Readme.txt @@ -0,0 +1,8 @@ +Shortcodes + +Place your custom implemented Shortcodes in this folder. + +1. Create a C# project +2. Add reference to BookGen.Api assembly +3. Implement the ITemplateShortCode interface +4. Place compiled dll to this folder. \ No newline at end of file diff --git a/Prog/BookGen/BookGen.csproj b/Prog/BookGen/BookGen.csproj index 1806d0fb..3b2b7ac3 100644 --- a/Prog/BookGen/BookGen.csproj +++ b/Prog/BookGen/BookGen.csproj @@ -59,6 +59,7 @@ + diff --git a/Prog/BookGen/Framework/ShortCodeParser.cs b/Prog/BookGen/Framework/ShortCodeParser.cs index c00e65af..0d807dbd 100644 --- a/Prog/BookGen/Framework/ShortCodeParser.cs +++ b/Prog/BookGen/Framework/ShortCodeParser.cs @@ -4,7 +4,7 @@ //----------------------------------------------------------------------------- using BookGen.Domain.Configuration; -using BookGen.Framework.Shortcodes; +using BookGen.ShortCodes; namespace BookGen.Framework; @@ -37,11 +37,7 @@ public ShortCodeParser(IList shortCodes, public void AddShortcodeToLookupIndex(ITemplateShortCode shortCode) { - if (!_shortCodesIndex.ContainsKey(shortCode.Tag)) - { - _shortCodesIndex.Add(shortCode.Tag, shortCode); - } - else + if (!_shortCodesIndex.TryAdd(shortCode.Tag, shortCode)) { _log.Warning("Shortcode has allready been registered: {0}. Duplicate entries cause unexpected behaviour.", shortCode.Tag); } diff --git a/Prog/BookGen/Framework/TemplateProcessor.cs b/Prog/BookGen/Framework/TemplateProcessor.cs index c70f2667..43ff39a5 100644 --- a/Prog/BookGen/Framework/TemplateProcessor.cs +++ b/Prog/BookGen/Framework/TemplateProcessor.cs @@ -4,7 +4,7 @@ //----------------------------------------------------------------------------- using BookGen.Domain.Configuration; -using BookGen.Framework.Shortcodes; +using BookGen.ShortCodes; namespace BookGen.Framework; diff --git a/Prog/BookGen/ShortCodeLoader.cs b/Prog/BookGen/ShortCodeLoader.cs index 062d8867..09d4b9ee 100644 --- a/Prog/BookGen/ShortCodeLoader.cs +++ b/Prog/BookGen/ShortCodeLoader.cs @@ -6,7 +6,9 @@ using System.ComponentModel.Composition; using System.ComponentModel.Composition.Hosting; +using BookGen.ShortCodes; using BookGen.Interfaces.Configuration; +using System.Reflection; namespace BookGen; @@ -40,11 +42,47 @@ public ShortCodeLoader(ILog log, IReadonlyRuntimeSettings settings, IAppSetting catalog.Catalogs.Add(new TypeCatalog(typeof(ILog), typeof(IReadonlyRuntimeSettings), typeof(IAppSetting))); - catalog.Catalogs.Add(new AssemblyCatalog(typeof(ShortCodeLoader).Assembly)); + + catalog.Catalogs.Add(new AssemblyCatalog(typeof(BuiltInShortCodeAttribute).Assembly)); + foreach (var plugin in LoadPlugins(_log)) + { + catalog.Catalogs.Add(plugin); + } + Imports = []; _container = new CompositionContainer(catalog); } + private static List LoadPlugins(ILog log) + { + log.Detail("Searching for plugins..."); + var folder = Path.Combine(AppContext.BaseDirectory, "ShortCodes"); + if (!Directory.Exists(folder)) + { + log.Warning("ShortCodes folder doesn't exist. Skipping custom shortcode loading"); + return []; + } + + string[] files = Directory.GetFiles(folder, "*.dll", SearchOption.TopDirectoryOnly); + + List catalogs = new(files.Length); + foreach (var file in files) + { + log.Detail("Loading {0}...", file); + try + { + var assembly = Assembly.LoadFile(file); + catalogs.Add(new AssemblyCatalog(assembly)); + } + catch (Exception ex) + { + log.Warning("Load failed: {0}", ex.Message); + } + } + + return catalogs; + } + public void LoadAll() { try diff --git a/Test/BookGen.Tests/GlobalUsings.cs b/Test/BookGen.Tests/GlobalUsings.cs index 10865747..eb4ae95b 100644 --- a/Test/BookGen.Tests/GlobalUsings.cs +++ b/Test/BookGen.Tests/GlobalUsings.cs @@ -6,7 +6,7 @@ global using BookGen.Api; global using BookGen.Domain.Configuration; global using BookGen.DomainServices; -global using BookGen.Framework.Shortcodes; +global using BookGen.ShortCodes; global using BookGen.Interfaces; global using BookGen.Tests.Environment; global using NSubstitute; From e587393c9df962d64087da412ba74cb426574748 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 20:33:24 +0100 Subject: [PATCH 13/34] Introduced time abstraction --- Libs/BookGen.Cli/SimpleIoC.cs | 8 ++++---- Libs/BookGen.ShortCodes/BuildTime.cs | 10 +++++++++- Prog/BookGen/GeneratorRunner.cs | 7 +++++-- Prog/BookGen/Infrastructure/ModuleApi.cs | 12 +++++++++--- .../Infrastructure/TimeProviderImplementation.cs | 5 +++++ Prog/BookGen/Program.cs | 6 +++++- Prog/BookGen/ShortCodeLoader.cs | 10 ++++++++-- 7 files changed, 45 insertions(+), 13 deletions(-) create mode 100644 Prog/BookGen/Infrastructure/TimeProviderImplementation.cs diff --git a/Libs/BookGen.Cli/SimpleIoC.cs b/Libs/BookGen.Cli/SimpleIoC.cs index 65b3be79..602af139 100644 --- a/Libs/BookGen.Cli/SimpleIoC.cs +++ b/Libs/BookGen.Cli/SimpleIoC.cs @@ -83,11 +83,11 @@ public void Build() public object Resolve(Type type) { - if (_instanceTypes.ContainsKey(type)) - return CreateInstance(_instanceTypes[type]); + if (_instanceTypes.TryGetValue(type, out Type? foundType)) + return CreateInstance(foundType); - if (_singletons.ContainsKey(type)) - return _singletons[type]; + if (_singletons.TryGetValue(type, out object? instance)) + return instance; throw new InvalidOperationException($"Don't know how to resolve: {type.FullName}"); } diff --git a/Libs/BookGen.ShortCodes/BuildTime.cs b/Libs/BookGen.ShortCodes/BuildTime.cs index 87d05f32..a797289e 100644 --- a/Libs/BookGen.ShortCodes/BuildTime.cs +++ b/Libs/BookGen.ShortCodes/BuildTime.cs @@ -9,12 +9,20 @@ namespace BookGen.ShortCodes; [BuiltInShortCode] public sealed class BuildTime : ITemplateShortCode { + private readonly TimeProvider _timeProvider; + + [ImportingConstructor] + public BuildTime(TimeProvider timeProvider) + { + _timeProvider = timeProvider; + } + public string Tag => nameof(BuildTime); public bool CanCacheResult => false; public string Generate(IArguments arguments) { - return DateTime.Now.ToString("yy-MM-dd hh:mm:ss"); + return _timeProvider.GetLocalNow().ToString("yy-MM-dd hh:mm:ss"); } } diff --git a/Prog/BookGen/GeneratorRunner.cs b/Prog/BookGen/GeneratorRunner.cs index 90ae449b..41ea14f0 100644 --- a/Prog/BookGen/GeneratorRunner.cs +++ b/Prog/BookGen/GeneratorRunner.cs @@ -26,6 +26,7 @@ internal class GeneratorRunner private readonly IModuleApi _moduleApi; private readonly IAppSetting _appSettings; private readonly ProgramInfo _programInfo; + private readonly TimeProvider _timeProvider; public FsPath ConfigFile { get; } @@ -45,6 +46,7 @@ public GeneratorRunner(ILog log, IModuleApi moduleApi, IAppSetting appSettings, ProgramInfo programInfo, + TimeProvider timeProvider, string workDir) { ServerLog = serverLog; @@ -52,6 +54,7 @@ public GeneratorRunner(ILog log, Log = log; _appSettings = appSettings; _programInfo = programInfo; + _timeProvider = timeProvider; _projectLoader = new ProjectLoader(workDir, log, programInfo); _projectLoadSuccess = _projectLoader.LoadProject(); WorkDirectory = workDir; @@ -120,7 +123,7 @@ public void DoClean() private void RunSteps(Func builderCreator, RuntimeSettings settings) where TBuilder : BookGen.Framework.GeneratorStepRunner { - using (var loader = new ShortCodeLoader(Log, settings, _appSettings)) + using (var loader = new ShortCodeLoader(Log, settings, _appSettings, _timeProvider)) { using (TBuilder instance = builderCreator(loader)) { @@ -195,7 +198,7 @@ public void DoTest() RuntimeSettings? settings = _projectLoader.CreateRuntimeSettings(_projectLoader.Configuration.TargetWeb); - using (var loader = new ShortCodeLoader(Log, settings, _appSettings)) + using (var loader = new ShortCodeLoader(Log, settings, _appSettings, _timeProvider)) { var builder = new WebsiteGeneratorStepRunner(settings, Log, loader); TimeSpan runTime = builder.Run(); diff --git a/Prog/BookGen/Infrastructure/ModuleApi.cs b/Prog/BookGen/Infrastructure/ModuleApi.cs index e2b9c242..ddc270cc 100644 --- a/Prog/BookGen/Infrastructure/ModuleApi.cs +++ b/Prog/BookGen/Infrastructure/ModuleApi.cs @@ -7,19 +7,25 @@ namespace BookGen.Infrastructure; -internal class ModuleApi : IModuleApi +internal sealed class ModuleApi : IModuleApi { private readonly ILog _log; private readonly IServerLog _serverLog; private readonly IAppSetting _setting; private readonly ProgramInfo _programInfo; + private readonly TimeProvider _timeProvider; - public ModuleApi(ILog log, IServerLog serverLog, IAppSetting setting, ProgramInfo programInfo) + public ModuleApi(ILog log, + IServerLog serverLog, + IAppSetting setting, + ProgramInfo programInfo, + TimeProvider timeProvider) { _log = log; _serverLog = serverLog; _setting = setting; _programInfo = programInfo; + _timeProvider = timeProvider; } public Action? OnExecuteModule { get; set; } @@ -53,6 +59,6 @@ public void Wait(string exitString) public GeneratorRunner CreateRunner(bool verbose, string workDir) { _log.LogLevel = verbose ? LogLevel.Detail : LogLevel.Info; - return new GeneratorRunner(_log, _serverLog, this, _setting, _programInfo, workDir); + return new GeneratorRunner(_log, _serverLog, this, _setting, _programInfo, _timeProvider, workDir); } } \ No newline at end of file diff --git a/Prog/BookGen/Infrastructure/TimeProviderImplementation.cs b/Prog/BookGen/Infrastructure/TimeProviderImplementation.cs new file mode 100644 index 00000000..46fd1f67 --- /dev/null +++ b/Prog/BookGen/Infrastructure/TimeProviderImplementation.cs @@ -0,0 +1,5 @@ +namespace BookGen.Infrastructure; + +internal sealed class TimeProviderImplementation : TimeProvider +{ +} diff --git a/Prog/BookGen/Program.cs b/Prog/BookGen/Program.cs index df1a8740..09c83c6b 100644 --- a/Prog/BookGen/Program.cs +++ b/Prog/BookGen/Program.cs @@ -22,8 +22,11 @@ (ILog log, IServerLog serverLog) = ProgramConfigurator.ConfigureLog(argumentList); ProgramInfo info = new(); + +var timeProvider = new TimeProviderImplementation(); + AppSetting settings = AppSettingHandler.LoadAppSettings() ?? new AppSetting(); -var api = new ModuleApi(log, serverLog, settings, info); +var api = new ModuleApi(log, serverLog, settings, info, timeProvider); SimpleIoC ioc = new(); ioc.RegisterSingleton(); @@ -33,6 +36,7 @@ ioc.RegisterSingleton(settings); ioc.RegisterSingleton(settings); ioc.RegisterSingleton(api); +ioc.RegisterSingleton(timeProvider); ioc.Register(); ioc.Build(); diff --git a/Prog/BookGen/ShortCodeLoader.cs b/Prog/BookGen/ShortCodeLoader.cs index 09d4b9ee..e5cda3cb 100644 --- a/Prog/BookGen/ShortCodeLoader.cs +++ b/Prog/BookGen/ShortCodeLoader.cs @@ -9,6 +9,7 @@ using BookGen.ShortCodes; using BookGen.Interfaces.Configuration; using System.Reflection; +using System; namespace BookGen; @@ -29,19 +30,24 @@ internal sealed class ShortCodeLoader : IDisposable [Export(typeof(IAppSetting))] private readonly IAppSetting _appSetting; + [Export(typeof(TimeProvider))] + private readonly TimeProvider _timeProvider; + private CompositionContainer? _container; - public ShortCodeLoader(ILog log, IReadonlyRuntimeSettings settings, IAppSetting appSetting) + public ShortCodeLoader(ILog log, IReadonlyRuntimeSettings settings, IAppSetting appSetting, TimeProvider timeProvider) { _log = log; _settings = settings; _tranlsations = settings.Configuration.Translations; _appSetting = appSetting; + _timeProvider = timeProvider; var catalog = new AggregateCatalog(); catalog.Catalogs.Add(new TypeCatalog(typeof(ILog), typeof(IReadonlyRuntimeSettings), - typeof(IAppSetting))); + typeof(IAppSetting), + typeof(TimeProvider))); catalog.Catalogs.Add(new AssemblyCatalog(typeof(BuiltInShortCodeAttribute).Assembly)); foreach (var plugin in LoadPlugins(_log)) From ba0f73c1ca4438c29c1ff0d1ff4f5ac2b483e9f8 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 21:00:57 +0100 Subject: [PATCH 14/34] Dependencies updated --- Libs/BookGen.Cli/SimpleIoC.cs | 12 +++++------- .../BookGen.DomainServices.csproj | 2 +- Libs/BookGen.Gui/BookGen.Gui.csproj | 4 ++-- Prog/BookGen/BookGen.csproj | 5 ++--- Prog/BookGen/Framework/TemplateProcessor.cs | 10 ++++------ Prog/Cdg/Cdg.csproj | 4 ++-- Prog/Www/Www.csproj | 4 ++-- Test/BookGen.Tests/UT_BuildTime.cs | 14 +++++++++++--- Test/BookGen.Tests/UT_ShortCodeLoader.cs | 11 ++++++++--- 9 files changed, 37 insertions(+), 29 deletions(-) diff --git a/Libs/BookGen.Cli/SimpleIoC.cs b/Libs/BookGen.Cli/SimpleIoC.cs index 602af139..766c8c89 100644 --- a/Libs/BookGen.Cli/SimpleIoC.cs +++ b/Libs/BookGen.Cli/SimpleIoC.cs @@ -15,9 +15,9 @@ public sealed class SimpleIoC : IResolver public SimpleIoC() { - _instanceTypes = new Dictionary(); - _singletonTypes = new Dictionary(); - _singletons = new Dictionary(); + _instanceTypes = []; + _singletonTypes = []; + _singletons = []; } public void Register() @@ -54,10 +54,8 @@ public bool CanResolve(Type type) private object CreateInstance(Type value) { - var ctorToCall = DependencyComparer.GetConstructor(value); - - if (ctorToCall == null) - throw new InvalidOperationException($"{value.FullName} doesn't have a public constructor"); + var ctorToCall = DependencyComparer.GetConstructor(value) + ?? throw new InvalidOperationException($"{value.FullName} doesn't have a public constructor"); var parameters = ctorToCall.GetParameters(); object[] parameterInstances = new object[parameters.Length]; diff --git a/Libs/BookGen.DomainServices/BookGen.DomainServices.csproj b/Libs/BookGen.DomainServices/BookGen.DomainServices.csproj index 71f37bbc..c4bf52f6 100644 --- a/Libs/BookGen.DomainServices/BookGen.DomainServices.csproj +++ b/Libs/BookGen.DomainServices/BookGen.DomainServices.csproj @@ -20,7 +20,7 @@ - + diff --git a/Libs/BookGen.Gui/BookGen.Gui.csproj b/Libs/BookGen.Gui/BookGen.Gui.csproj index 409420b9..5f4e5421 100644 --- a/Libs/BookGen.Gui/BookGen.Gui.csproj +++ b/Libs/BookGen.Gui/BookGen.Gui.csproj @@ -11,9 +11,9 @@ - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Prog/BookGen/BookGen.csproj b/Prog/BookGen/BookGen.csproj index 3b2b7ac3..0a749624 100644 --- a/Prog/BookGen/BookGen.csproj +++ b/Prog/BookGen/BookGen.csproj @@ -35,12 +35,11 @@ - - + - + diff --git a/Prog/BookGen/Framework/TemplateProcessor.cs b/Prog/BookGen/Framework/TemplateProcessor.cs index 43ff39a5..7be5e0af 100644 --- a/Prog/BookGen/Framework/TemplateProcessor.cs +++ b/Prog/BookGen/Framework/TemplateProcessor.cs @@ -15,10 +15,10 @@ internal sealed class TemplateProcessor : ITemplateProcessor public string TemplateContent { get; set; } - private static readonly HashSet _protectedNames = new() - { + private static readonly HashSet _protectedNames = + [ "toc", "title", "content", "host", "metadata", "precompiledheader", - }; + ]; public TemplateProcessor(Config cfg, ShortCodeParser shortCodeParser, StaticTemplateContent? staticContent = null) { @@ -36,9 +36,7 @@ public TemplateProcessor(Config cfg, ShortCodeParser shortCodeParser, StaticTemp _parser.AddShortcodesToLookupIndex(CreateInternalsList()); } - - - private IList CreateInternalsList() + private List CreateInternalsList() { var internals = new List(_table.Count); foreach (KeyValuePair item in _table) diff --git a/Prog/Cdg/Cdg.csproj b/Prog/Cdg/Cdg.csproj index 7efd5976..6010fdc8 100644 --- a/Prog/Cdg/Cdg.csproj +++ b/Prog/Cdg/Cdg.csproj @@ -17,8 +17,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Prog/Www/Www.csproj b/Prog/Www/Www.csproj index 4e901357..f58f17fa 100644 --- a/Prog/Www/Www.csproj +++ b/Prog/Www/Www.csproj @@ -17,8 +17,8 @@ - - + + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Test/BookGen.Tests/UT_BuildTime.cs b/Test/BookGen.Tests/UT_BuildTime.cs index 75a73d2a..e04084f0 100644 --- a/Test/BookGen.Tests/UT_BuildTime.cs +++ b/Test/BookGen.Tests/UT_BuildTime.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -8,10 +8,18 @@ namespace BookGen.Tests [TestFixture] public class UT_BuildTime { + private TimeProvider _timeProvider; + + [SetUp] + public void Setup() + { + _timeProvider = Substitute.For(); + } + [Test] public void EnsureThat_BuildTime_ReturnsCorrectString() { - var sut = new BuildTime(); + var sut = new BuildTime(_timeProvider); string expected = DateTime.Now.ToString("yy-MM-dd hh:mm:ss"); @@ -23,7 +31,7 @@ public void EnsureThat_BuildTime_ReturnsCorrectString() [Test] public void EnsureThat_BuildTime_Tag_MatchesClassName() { - var sut = new BuildTime(); + var sut = new BuildTime(_timeProvider); const string expected = nameof(BuildTime); diff --git a/Test/BookGen.Tests/UT_ShortCodeLoader.cs b/Test/BookGen.Tests/UT_ShortCodeLoader.cs index 1d41ad77..5c38791d 100644 --- a/Test/BookGen.Tests/UT_ShortCodeLoader.cs +++ b/Test/BookGen.Tests/UT_ShortCodeLoader.cs @@ -10,12 +10,17 @@ public class UT_ShortCodeLoader { private ShortCodeLoader _sut; private ILog _logMock; + private TimeProvider _timeProvider; [SetUp] public void Setup() { + _timeProvider = Substitute.For(); _logMock = Substitute.For(); - _sut = new ShortCodeLoader(_logMock, TestEnvironment.GetMockedSettings(), TestEnvironment.GetMockedAppSettings()); + _sut = new ShortCodeLoader(_logMock, + TestEnvironment.GetMockedSettings(), + TestEnvironment.GetMockedAppSettings(), + _timeProvider); _sut.LoadAll(); } @@ -29,14 +34,14 @@ public void TearDown() [Test] public void EnsureThat_ShortCodeLoaderLoadsShortCodes() { - Assert.IsTrue(_sut.Imports.Count > 0); + Assert.That(_sut.Imports, Is.Not.Empty); } [Test] public void EnsureThat_ShortCodeLoader_SatisfiesLogImport() { ITemplateShortCode sri = _sut.Imports.FirstOrDefault(s => s.Tag == nameof(SriDependency)); - Assert.IsNotNull(sri); + Assert.That(sri, Is.Not.Null); } } } From 7d629941f754872f5accabbc03b7bdff005a87bd Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 24 Nov 2023 21:18:28 +0100 Subject: [PATCH 15/34] Javascript console interface definition --- Libs/BookGen.Interfaces/IJavascriptConsole.cs | 47 +++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Libs/BookGen.Interfaces/IJavascriptConsole.cs diff --git a/Libs/BookGen.Interfaces/IJavascriptConsole.cs b/Libs/BookGen.Interfaces/IJavascriptConsole.cs new file mode 100644 index 00000000..e02a99bf --- /dev/null +++ b/Libs/BookGen.Interfaces/IJavascriptConsole.cs @@ -0,0 +1,47 @@ +namespace BookGen.Interfaces; + +/// +/// https://developer.mozilla.org/en-US/docs/Web/API/Console_API +/// +public interface IJavascriptConsole +{ + public static abstract void Clear(); + + public static abstract void Assert(bool assertation, object obj1); + public static abstract void Assert(bool assertation, object obj1, object obj2); + public static abstract void Assert(bool assertation, params object[] objects); + public static abstract void Assert(bool assertation, string msg); + public static abstract void Assert(bool assertation, string msg, params object[] substitutions); + + public static abstract void CountReset(); + public static abstract void CountReset(string label); + + public static abstract void Count(); + public static abstract void Count(string label); + + public static abstract void Debug(params object[] objects); + public static abstract void Debug(string msg, params object[] substitutions); + + public static abstract void Dir(object o); + public static abstract void DirXml(object o); + + public static abstract void Error(params object[] objects); + public static abstract void Error(string msg); + public static abstract void Error(string msg, params object[] objects); + + public static abstract void Exception(params object[] objects); + public static abstract void Exception(string msg); + public static abstract void Exception(string msg, params object[] objects); + + public static abstract void Info(params object[] objects); + public static abstract void Info(string msg); + public static abstract void Info(string msg, params object[] objects); + + public static abstract void Log(params object[] objects); + public static abstract void Log(string msg); + public static abstract void Log(string msg, params object[] objects); + + public static abstract void Warn(params object[] objects); + public static abstract void Warn(string msg); + public static abstract void Warn(string msg, params object[] objects); +} From d2607a8cee7187f5c0626989ee58a2c22857f868 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sat, 25 Nov 2023 18:45:52 +0100 Subject: [PATCH 16/34] Javascript console trashed --- Libs/BookGen.Interfaces/IJavascriptConsole.cs | 47 ------------------- 1 file changed, 47 deletions(-) delete mode 100644 Libs/BookGen.Interfaces/IJavascriptConsole.cs diff --git a/Libs/BookGen.Interfaces/IJavascriptConsole.cs b/Libs/BookGen.Interfaces/IJavascriptConsole.cs deleted file mode 100644 index e02a99bf..00000000 --- a/Libs/BookGen.Interfaces/IJavascriptConsole.cs +++ /dev/null @@ -1,47 +0,0 @@ -namespace BookGen.Interfaces; - -/// -/// https://developer.mozilla.org/en-US/docs/Web/API/Console_API -/// -public interface IJavascriptConsole -{ - public static abstract void Clear(); - - public static abstract void Assert(bool assertation, object obj1); - public static abstract void Assert(bool assertation, object obj1, object obj2); - public static abstract void Assert(bool assertation, params object[] objects); - public static abstract void Assert(bool assertation, string msg); - public static abstract void Assert(bool assertation, string msg, params object[] substitutions); - - public static abstract void CountReset(); - public static abstract void CountReset(string label); - - public static abstract void Count(); - public static abstract void Count(string label); - - public static abstract void Debug(params object[] objects); - public static abstract void Debug(string msg, params object[] substitutions); - - public static abstract void Dir(object o); - public static abstract void DirXml(object o); - - public static abstract void Error(params object[] objects); - public static abstract void Error(string msg); - public static abstract void Error(string msg, params object[] objects); - - public static abstract void Exception(params object[] objects); - public static abstract void Exception(string msg); - public static abstract void Exception(string msg, params object[] objects); - - public static abstract void Info(params object[] objects); - public static abstract void Info(string msg); - public static abstract void Info(string msg, params object[] objects); - - public static abstract void Log(params object[] objects); - public static abstract void Log(string msg); - public static abstract void Log(string msg, params object[] objects); - - public static abstract void Warn(params object[] objects); - public static abstract void Warn(string msg); - public static abstract void Warn(string msg, params object[] objects); -} From d4e4da542d0fc4b8e4e10dae25dd5c829d78d9ca Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sat, 25 Nov 2023 18:56:53 +0100 Subject: [PATCH 17/34] Test cleanup & fixes --- Test/BookGen.Tests/BookGen.Tests.csproj | 27 ++++--------------- Test/BookGen.Tests/Environment/LongNodeJs.js | 13 --------- .../BookGen.Tests/Environment/SimpleNodeJs.js | 1 - Test/BookGen.Tests/UT_BuildTime.cs | 7 ++++- 4 files changed, 11 insertions(+), 37 deletions(-) delete mode 100644 Test/BookGen.Tests/Environment/LongNodeJs.js delete mode 100644 Test/BookGen.Tests/Environment/SimpleNodeJs.js diff --git a/Test/BookGen.Tests/BookGen.Tests.csproj b/Test/BookGen.Tests/BookGen.Tests.csproj index 3d55ea8b..523e1a45 100644 --- a/Test/BookGen.Tests/BookGen.Tests.csproj +++ b/Test/BookGen.Tests/BookGen.Tests.csproj @@ -1,4 +1,4 @@ - + net8.0 @@ -10,10 +10,6 @@ true - - - - @@ -31,7 +27,6 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - @@ -44,19 +39,11 @@ PreserveNewest - - - PreserveNewest - - - PreserveNewest - - - PreserveNewest - - + PreserveNewest - + + PreserveNewest + PreserveNewest @@ -65,8 +52,4 @@ - - - - diff --git a/Test/BookGen.Tests/Environment/LongNodeJs.js b/Test/BookGen.Tests/Environment/LongNodeJs.js deleted file mode 100644 index b357985e..00000000 --- a/Test/BookGen.Tests/Environment/LongNodeJs.js +++ /dev/null @@ -1,13 +0,0 @@ -function sleep(ms) { - return new Promise(resolve => setTimeout(resolve, ms)); -} - -async function main() { - let i = 0; - for (; i < 10; i++) { - console.log(i); - await sleep(200); - } -} - -main(); \ No newline at end of file diff --git a/Test/BookGen.Tests/Environment/SimpleNodeJs.js b/Test/BookGen.Tests/Environment/SimpleNodeJs.js deleted file mode 100644 index 645e1d63..00000000 --- a/Test/BookGen.Tests/Environment/SimpleNodeJs.js +++ /dev/null @@ -1 +0,0 @@ -console.log("Hello from nodeJS"); \ No newline at end of file diff --git a/Test/BookGen.Tests/UT_BuildTime.cs b/Test/BookGen.Tests/UT_BuildTime.cs index e04084f0..f2932a0f 100644 --- a/Test/BookGen.Tests/UT_BuildTime.cs +++ b/Test/BookGen.Tests/UT_BuildTime.cs @@ -9,11 +9,16 @@ namespace BookGen.Tests public class UT_BuildTime { private TimeProvider _timeProvider; + private DateTimeOffset _expected; [SetUp] public void Setup() { + _expected = new DateTimeOffset(new DateTime(1, 1, 1, 11, 11, 11)); _timeProvider = Substitute.For(); + _timeProvider.LocalTimeZone.Returns(TimeZoneInfo.Utc); + _timeProvider.GetUtcNow().Returns(_expected); + } [Test] @@ -21,7 +26,7 @@ public void EnsureThat_BuildTime_ReturnsCorrectString() { var sut = new BuildTime(_timeProvider); - string expected = DateTime.Now.ToString("yy-MM-dd hh:mm:ss"); + string expected = _expected.ToString("yy-MM-dd hh:mm:ss"); string result = sut.Generate(null); From 114baf39e480db18b87c4a9505447b7737b5c3f1 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sat, 25 Nov 2023 19:12:34 +0100 Subject: [PATCH 18/34] Scripting interaction shortCodes --- Changelog.md | 1 + Libs/BookGen.ShortCodes/NodeJs.cs | 33 ++++++++ Libs/BookGen.ShortCodes/Php.cs | 28 +++++++ Libs/BookGen.ShortCodes/Python.cs | 33 ++++++++ Libs/BookGen.ShortCodes/ScriptProcess.cs | 96 ++++++++++++++++++++++++ 5 files changed, 191 insertions(+) create mode 100644 Libs/BookGen.ShortCodes/NodeJs.cs create mode 100644 Libs/BookGen.ShortCodes/Php.cs create mode 100644 Libs/BookGen.ShortCodes/Python.cs create mode 100644 Libs/BookGen.ShortCodes/ScriptProcess.cs diff --git a/Changelog.md b/Changelog.md index 28d32f71..46e354fa 100644 --- a/Changelog.md +++ b/Changelog.md @@ -10,6 +10,7 @@ * New: Terminal output renderer, when building markdown * New: CDG program can handle a path argument, to specify where to start from * New: WWW program that can perform web searches easily +* Change: API cleanup & removed C# scripting support * Change: StockSearch command functionality has been integrated to the WWW command * Change: Removed auto updater (hard to maintain) * Change: Removed ZIP format release diff --git a/Libs/BookGen.ShortCodes/NodeJs.cs b/Libs/BookGen.ShortCodes/NodeJs.cs new file mode 100644 index 00000000..8bdec217 --- /dev/null +++ b/Libs/BookGen.ShortCodes/NodeJs.cs @@ -0,0 +1,33 @@ +//----------------------------------------------------------------------------- +// (c) 2020-2023 Ruzsinszki Gábor +// This code is licensed under MIT license (see LICENSE for details) +//----------------------------------------------------------------------------- + +using BookGen.Interfaces; + +namespace BookGen.ShortCodes; + +[Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] +public sealed class NodeJs : ScriptProcess, ITemplateShortCode +{ + private readonly IAppSetting _appSetting; + + [ImportingConstructor] + public NodeJs(ILog log, IAppSetting appSetting) : base(log) + { + _appSetting = appSetting; + } + + public string Tag => "NodeJs"; + + public bool CanCacheResult => false; + + public string Generate(IArguments arguments) + { + string? file = arguments.GetArgumentOrThrow("file"); + _log.Info("Trying to execute NoseJs script: {0} ...", file); + + return ExecuteScriptProcess("node", _appSetting.NodeJsPath, file, _appSetting.NodeJsTimeout); + } +} diff --git a/Libs/BookGen.ShortCodes/Php.cs b/Libs/BookGen.ShortCodes/Php.cs new file mode 100644 index 00000000..d2a3d620 --- /dev/null +++ b/Libs/BookGen.ShortCodes/Php.cs @@ -0,0 +1,28 @@ +using BookGen.Interfaces; + +namespace BookGen.ShortCodes; + +[Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] +public sealed class Php : ScriptProcess, ITemplateShortCode +{ + private readonly IAppSetting _appSetting; + + [ImportingConstructor] + public Php(ILog log, IAppSetting appSetting) : base(log) + { + _appSetting = appSetting; + } + + public string Tag => "Php"; + + public bool CanCacheResult => false; + + public string Generate(IArguments arguments) + { + string? file = arguments.GetArgumentOrThrow("file"); + _log.Info("Trying to execute PHP CGI script: {0} ...", file); + + return ExecuteScriptProcess("php-cgi", _appSetting.PhpPath, file, _appSetting.PhpTimeout); + } +} \ No newline at end of file diff --git a/Libs/BookGen.ShortCodes/Python.cs b/Libs/BookGen.ShortCodes/Python.cs new file mode 100644 index 00000000..21243ae3 --- /dev/null +++ b/Libs/BookGen.ShortCodes/Python.cs @@ -0,0 +1,33 @@ +//----------------------------------------------------------------------------- +// (c) 2020-2023 Ruzsinszki Gábor +// This code is licensed under MIT license (see LICENSE for details) +//----------------------------------------------------------------------------- + +using BookGen.Interfaces; + +namespace BookGen.ShortCodes; + +[Export(typeof(ITemplateShortCode))] +[BuiltInShortCode] +public sealed class Python : ScriptProcess, ITemplateShortCode +{ + private readonly IAppSetting _appSetting; + + [ImportingConstructor] + public Python(ILog log, IAppSetting appSetting) : base(log) + { + _appSetting = appSetting; + } + + public string Tag => "Python"; + + public bool CanCacheResult => false; + + public string Generate(IArguments arguments) + { + string? file = arguments.GetArgumentOrThrow("file"); + _log.Info("Trying to execute Python script: {0} ...", file); + + return ExecuteScriptProcess("python", _appSetting.PythonPath, file, _appSetting.PythonTimeout); + } +} diff --git a/Libs/BookGen.ShortCodes/ScriptProcess.cs b/Libs/BookGen.ShortCodes/ScriptProcess.cs new file mode 100644 index 00000000..4af90f11 --- /dev/null +++ b/Libs/BookGen.ShortCodes/ScriptProcess.cs @@ -0,0 +1,96 @@ +using System.Runtime.InteropServices; + +using BookGen.DomainServices; + +namespace BookGen.ShortCodes; + +public abstract class ScriptProcess +{ + protected readonly ILog _log; + + protected ScriptProcess(ILog log) + { + _log = log; + } + + private static string? ResolveProgramFullPath(string programName, string additional = "") + { + string? pathVar = Environment.GetEnvironmentVariable("path"); + + if (pathVar == null) + return null; + + var searchFolders = new List(20); + + if (AppDomain.CurrentDomain.BaseDirectory != null) + searchFolders.Add(AppDomain.CurrentDomain.BaseDirectory); + + searchFolders.AddRange(pathVar.Split(';')); + + if (!string.IsNullOrEmpty(additional)) + searchFolders.Add(additional); + + foreach (string folder in searchFolders) + { + string programFile = Path.Combine(folder, programName); + + if (File.Exists(programFile)) + { + return programFile; + } + } + + return null; + } + + private static string AppendExecutableExtension(string file) + { + if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) + || RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) + { + return file; + } + else if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) + { + return $"{file}.exe"; + } + else + { + throw new InvalidOperationException("Unknown host operating system"); + } + } + + protected string ExecuteScriptProcess(string programWithoutExtension, string searchPath, string fileToExecute, int timeout) + { + string program = AppendExecutableExtension(programWithoutExtension); + string? programPath = ResolveProgramFullPath(program, searchPath); + + if (programPath == null) + { + _log.Warning("{0} was not found on path.", program); + return $"{program} was not found on path"; + } + + try + { + (int exitcode, string output) = ProcessRunner.RunProcess(programPath, fileToExecute, timeout); + + if (exitcode != 0) + { + _log.Warning("Script run failed. Exit code: {0}", exitcode); + _log.Detail("Script output: {0}", output); + return $"Script run failed: {fileToExecute}"; + } + else + { + return output; + } + } + catch (Exception ex) + { + _log.Warning("Script run failed with Exception: {0}", ex.Message); + _log.Detail("Stack Trace: {0}", ex.StackTrace ?? ""); + return $"Script run failed with Exception: {ex.Message}"; + } + } +} From f6809caac3493053a4da5e697f3da24ed1bf42e9 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Wed, 29 Nov 2023 20:24:25 +0100 Subject: [PATCH 19/34] Remove IServerLogger interface --- Libs/BookGen.Api/ILog.cs | 16 +------ Libs/BookGen.Api/LogLevel.cs | 8 +--- Libs/BookGen.Gui/TerminalLog.cs | 19 ++------ Libs/BookGen.Resources/ResourceHandler.cs | 3 +- .../Domain/IRequestHandler.cs | 6 ++- .../Handlers/FaviconHandler.cs | 11 ++++- .../Handlers/FileServeHandler.cs | 8 ++-- .../Handlers/JsonApiGetHandler.cs | 8 ++-- .../Handlers/JsonPostApiHandler.cs | 9 ++-- .../Handlers/QrCodeLinkHandler.cs | 4 +- .../HttpServer.cs | 8 ++-- .../IServerLog.cs | 48 ------------------- .../Webmaster442.HttpServerFramework.csproj | 6 ++- Prog/BookGen/Commands/PreviewCommand.cs | 6 +-- Prog/BookGen/Commands/ServeCommand.cs | 6 +-- Prog/BookGen/Framework/JsonLog.cs | 14 +----- .../Framework/Server/HttpServerFactory.cs | 8 ++-- .../Framework/Server/PreviewRenderHandler.cs | 2 +- .../Framework/Server/PreviewStaticHandler.cs | 4 +- Prog/BookGen/GeneratorRunner.cs | 5 +- Prog/BookGen/Infrastructure/ModuleApi.cs | 7 +-- .../Infrastructure/ProgramConfigurator.cs | 16 +++---- Prog/BookGen/Program.cs | 5 +- Test/BookGen.Tests/UT_TestServer.cs | 6 +-- 24 files changed, 79 insertions(+), 154 deletions(-) delete mode 100644 Libs/Webmaster442.HttpServerFramework/IServerLog.cs diff --git a/Libs/BookGen.Api/ILog.cs b/Libs/BookGen.Api/ILog.cs index 70099f6c..0886b5d3 100644 --- a/Libs/BookGen.Api/ILog.cs +++ b/Libs/BookGen.Api/ILog.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -38,19 +38,7 @@ void Flush() void Log(LogLevel logLevel, string format, params object[] args); /// - /// Print a string, without formatting - /// - /// string to print - void PrintLine(string str); - - /// - /// Print an object - /// - /// object to print - void PrintLine(object obj); - - /// - /// Log a Critical error. + /// Log a Critical error. /// Critcal error is an error that causes the program to stop working /// /// Message, a fomat string that can be handled by the String.Format method diff --git a/Libs/BookGen.Api/LogLevel.cs b/Libs/BookGen.Api/LogLevel.cs index 1d2f394e..f58d3a48 100644 --- a/Libs/BookGen.Api/LogLevel.cs +++ b/Libs/BookGen.Api/LogLevel.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -23,12 +23,8 @@ public enum LogLevel /// Info = 2, /// - /// Detailed info messages. Only visible when verbose + /// Detailed info messages. Only visible when verbose /// Detail = 3, - /// - /// The Logger interface PrintLine method was called - /// - PrintLine = 255 } } diff --git a/Libs/BookGen.Gui/TerminalLog.cs b/Libs/BookGen.Gui/TerminalLog.cs index 55dee0f1..4f148ce7 100644 --- a/Libs/BookGen.Gui/TerminalLog.cs +++ b/Libs/BookGen.Gui/TerminalLog.cs @@ -3,14 +3,15 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- +using System.Diagnostics; + using BookGen.Api; + using Spectre.Console; -using System.Diagnostics; -using Webmaster442.HttpServerFramework; namespace BookGen.Gui; -public sealed class TerminalLog : IServerLog, ILog +public sealed class TerminalLog : ILog { private readonly TextWriter? _logFile; @@ -79,16 +80,4 @@ void ILog.Critical(Exception ex) AnsiConsole.WriteLine(""); AnsiConsole.WriteException(ex); } - - void IServerLog.Critical(Exception ex) - { - AnsiConsole.WriteLine(""); - AnsiConsole.WriteException(ex); - } - - void IServerLog.Info(string format, params object[] args) - => Log(LogLevel.Info, format, args); - - void IServerLog.Warning(string format, params object[] args) - => Log(LogLevel.Warning, format, args); } diff --git a/Libs/BookGen.Resources/ResourceHandler.cs b/Libs/BookGen.Resources/ResourceHandler.cs index ad1e85f2..22098d63 100644 --- a/Libs/BookGen.Resources/ResourceHandler.cs +++ b/Libs/BookGen.Resources/ResourceHandler.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2019-2020 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -24,7 +24,6 @@ private static string TranslateResourcePath(string path) string? resourceName = resources.First(s => s.EndsWith(TranslateResourcePath(resource), StringComparison.CurrentCultureIgnoreCase)); return assembly.GetManifestResourceStream(resourceName); - } private static string GetResourceFile(string file) diff --git a/Libs/Webmaster442.HttpServerFramework/Domain/IRequestHandler.cs b/Libs/Webmaster442.HttpServerFramework/Domain/IRequestHandler.cs index 4279d318..b517500b 100644 --- a/Libs/Webmaster442.HttpServerFramework/Domain/IRequestHandler.cs +++ b/Libs/Webmaster442.HttpServerFramework/Domain/IRequestHandler.cs @@ -1,8 +1,10 @@ // ------------------------------------------------------------------------------------------------ -// Copyright (c) 2021-2022 Ruzsinszki Gábor +// Copyright (c) 2021-2023 Ruzsinszki Gábor // This is free software under the terms of the MIT License. https://opensource.org/licenses/MIT // ----------------------------------------------------------------------------------------------- +using BookGen.Api; + namespace Webmaster442.HttpServerFramework.Domain; /// @@ -17,5 +19,5 @@ public interface IRequestHandler /// Request /// Response to the request /// true, if the request is handled - Task Handle(IServerLog? log, HttpRequest request, HttpResponse response); + Task Handle(ILog? log, HttpRequest request, HttpResponse response); } diff --git a/Libs/Webmaster442.HttpServerFramework/Handlers/FaviconHandler.cs b/Libs/Webmaster442.HttpServerFramework/Handlers/FaviconHandler.cs index 5a3ac11c..2d46ed93 100644 --- a/Libs/Webmaster442.HttpServerFramework/Handlers/FaviconHandler.cs +++ b/Libs/Webmaster442.HttpServerFramework/Handlers/FaviconHandler.cs @@ -1,4 +1,11 @@ -using Webmaster442.HttpServerFramework.Domain; +// ------------------------------------------------------------------------------------------------ +// Copyright (c) 2021-2023 Ruzsinszki Gábor +// This is free software under the terms of the MIT License. https://opensource.org/licenses/MIT +// ----------------------------------------------------------------------------------------------- + +using BookGen.Api; + +using Webmaster442.HttpServerFramework.Domain; namespace Webmaster442.HttpServerFramework.Handlers; @@ -28,7 +35,7 @@ public void Dispose() } /// - public async Task Handle(IServerLog? log, HttpRequest request, HttpResponse response) + public async Task Handle(ILog? log, HttpRequest request, HttpResponse response) { if (request.Method != RequestMethod.Get || request.Url != "/favicon.ico") diff --git a/Libs/Webmaster442.HttpServerFramework/Handlers/FileServeHandler.cs b/Libs/Webmaster442.HttpServerFramework/Handlers/FileServeHandler.cs index bf278a21..04de42c9 100644 --- a/Libs/Webmaster442.HttpServerFramework/Handlers/FileServeHandler.cs +++ b/Libs/Webmaster442.HttpServerFramework/Handlers/FileServeHandler.cs @@ -1,8 +1,10 @@ // ------------------------------------------------------------------------------------------------ -// Copyright (c) 2021-2022 Ruzsinszki Gábor +// Copyright (c) 2021-2023 Ruzsinszki Gábor // This is free software under the terms of the MIT License. https://opensource.org/licenses/MIT // ----------------------------------------------------------------------------------------------- +using BookGen.Api; + using Webmaster442.HttpServerFramework.Domain; using Webmaster442.HttpServerFramework.Internal; @@ -68,7 +70,7 @@ private string GetIndexFile(string _path) /// - public async Task Handle(IServerLog? log, HttpRequest request, HttpResponse response) + public async Task Handle(ILog? log, HttpRequest request, HttpResponse response) { if (request.Method != RequestMethod.Get) { @@ -112,7 +114,7 @@ public async Task Handle(IServerLog? log, HttpRequest request, HttpRespons return false; } - private async ValueTask RenderFolder(string folder, string url, IServerLog? log, HttpResponse response) + private async ValueTask RenderFolder(string folder, string url, ILog? log, HttpResponse response) { log?.Info("Rendering file list for: {0}...", folder); string title = $"Index of {url}"; diff --git a/Libs/Webmaster442.HttpServerFramework/Handlers/JsonApiGetHandler.cs b/Libs/Webmaster442.HttpServerFramework/Handlers/JsonApiGetHandler.cs index 77887206..db156178 100644 --- a/Libs/Webmaster442.HttpServerFramework/Handlers/JsonApiGetHandler.cs +++ b/Libs/Webmaster442.HttpServerFramework/Handlers/JsonApiGetHandler.cs @@ -1,8 +1,10 @@ // ------------------------------------------------------------------------------------------------ -// Copyright (c) 2021-2022 Ruzsinszki Gábor +// Copyright (c) 2021-2023 Ruzsinszki Gábor // This is free software under the terms of the MIT License. https://opensource.org/licenses/MIT // ----------------------------------------------------------------------------------------------- +using BookGen.Api; + using Webmaster442.HttpServerFramework.Domain; namespace Webmaster442.HttpServerFramework.Handlers; @@ -29,7 +31,7 @@ public JsonApiGetHandler(RequestMethod supportedMethod) } /// - public async Task Handle(IServerLog? log, HttpRequest request, HttpResponse response) + public async Task Handle(ILog? log, HttpRequest request, HttpResponse response) { if (!CanProcess(request.Url)) { @@ -56,7 +58,7 @@ public async Task Handle(IServerLog? log, HttpRequest request, HttpRespons /// Request parameters /// Response object that will be JSON serialized /// True, if processing was succesfull, false if not - protected abstract Task TryProcessRequest(IServerLog? log, string url, IReadOnlyDictionary parameters, out TResponse responseObject); + protected abstract Task TryProcessRequest(ILog? log, string url, IReadOnlyDictionary parameters, out TResponse responseObject); /// /// Determines if the specified url can be processed by this handler diff --git a/Libs/Webmaster442.HttpServerFramework/Handlers/JsonPostApiHandler.cs b/Libs/Webmaster442.HttpServerFramework/Handlers/JsonPostApiHandler.cs index 4a553872..a66d41ce 100644 --- a/Libs/Webmaster442.HttpServerFramework/Handlers/JsonPostApiHandler.cs +++ b/Libs/Webmaster442.HttpServerFramework/Handlers/JsonPostApiHandler.cs @@ -1,9 +1,12 @@ // ------------------------------------------------------------------------------------------------ -// Copyright (c) 2021-2022 Ruzsinszki Gábor +// Copyright (c) 2021-2023 Ruzsinszki Gábor // This is free software under the terms of the MIT License. https://opensource.org/licenses/MIT // ----------------------------------------------------------------------------------------------- using System.Text.Json; + +using BookGen.Api; + using Webmaster442.HttpServerFramework.Domain; namespace Webmaster442.HttpServerFramework.Handlers @@ -40,7 +43,7 @@ public JsonPostApiHandler(RequestMethod supportedMethod, string url) } /// - public async Task Handle(IServerLog? log, HttpRequest request, HttpResponse response) + public async Task Handle(ILog? log, HttpRequest request, HttpResponse response) { if (request.Url != Url) { @@ -71,6 +74,6 @@ public async Task Handle(IServerLog? log, HttpRequest request, HttpRespons /// Request JSON deserialized object /// Response object that will be JSON serialized /// True, if processing was succesfull, false if not - protected abstract Task TryProcessRequest(IServerLog? log, TRequest requestObject, out TResponse responseObject); + protected abstract Task TryProcessRequest(ILog? log, TRequest requestObject, out TResponse responseObject); } } diff --git a/Libs/Webmaster442.HttpServerFramework/Handlers/QrCodeLinkHandler.cs b/Libs/Webmaster442.HttpServerFramework/Handlers/QrCodeLinkHandler.cs index cab97773..677e58ae 100644 --- a/Libs/Webmaster442.HttpServerFramework/Handlers/QrCodeLinkHandler.cs +++ b/Libs/Webmaster442.HttpServerFramework/Handlers/QrCodeLinkHandler.cs @@ -8,6 +8,8 @@ using System.Net.Sockets; using System.Web; +using BookGen.Api; + using Webmaster442.HttpServerFramework.Domain; using Webmaster442.HttpServerFramework.Internal; @@ -51,7 +53,7 @@ private IPAddress GetLocalNetworkAdress() } /// - public async Task Handle(IServerLog? log, HttpRequest request, HttpResponse response) + public async Task Handle(ILog? log, HttpRequest request, HttpResponse response) { if (request.Method != RequestMethod.Get || request.Url != "/qrcodelink") diff --git a/Libs/Webmaster442.HttpServerFramework/HttpServer.cs b/Libs/Webmaster442.HttpServerFramework/HttpServer.cs index 3834eb76..f08376fd 100644 --- a/Libs/Webmaster442.HttpServerFramework/HttpServer.cs +++ b/Libs/Webmaster442.HttpServerFramework/HttpServer.cs @@ -1,10 +1,12 @@ // ------------------------------------------------------------------------------------------------ -// Copyright (c) 2021-2022 Ruzsinszki Gábor +// Copyright (c) 2021-2023 Ruzsinszki Gábor // This is free software under the terms of the MIT License. https://opensource.org/licenses/MIT // ----------------------------------------------------------------------------------------------- using System.Net.Sockets; +using BookGen.Api; + using Webmaster442.HttpServerFramework.Domain; using Webmaster442.HttpServerFramework.Internal; @@ -15,7 +17,7 @@ namespace Webmaster442.HttpServerFramework; /// public sealed class HttpServer : IDisposable { - private readonly IServerLog? _log; + private readonly ILog? _log; private readonly HttpServerConfiguration _configuration; private readonly List _handlers; @@ -34,7 +36,7 @@ public sealed class HttpServer : IDisposable /// /// Server configuration /// logger to use - public HttpServer(HttpServerConfiguration configuration, IServerLog? log = null) + public HttpServer(HttpServerConfiguration configuration, ILog? log = null) { ConfigurationValidator.ValidateAndTrhowExceptions(configuration); diff --git a/Libs/Webmaster442.HttpServerFramework/IServerLog.cs b/Libs/Webmaster442.HttpServerFramework/IServerLog.cs deleted file mode 100644 index e767865b..00000000 --- a/Libs/Webmaster442.HttpServerFramework/IServerLog.cs +++ /dev/null @@ -1,48 +0,0 @@ -// ------------------------------------------------------------------------------------------------ -// Copyright (c) 2021-2022 Ruzsinszki Gábor -// This is free software under the terms of the MIT License. https://opensource.org/licenses/MIT -// ----------------------------------------------------------------------------------------------- - -using System.Diagnostics; - -namespace Webmaster442.HttpServerFramework; - -/// -/// Logging interface for the server -/// -public interface IServerLog -{ - /// - /// Log a critical exception. - /// - /// Exception to log - void Critical(Exception ex) - { - Debug.WriteLine("Critical:"); - Debug.WriteLine(ex); - Debug.WriteLine(ex.StackTrace); - } - - /// - /// Log an iformational message. - /// Informations give the user feedback about what is happening. - /// - /// Message, a fomat string that can be handled by the String.Format method - /// Arguments for formatting - void Info(string format, params object[] args) - { - Debug.WriteLine("Info:"); - Debug.WriteLine(format, args); - } - - /// - /// Log a warning message - /// - /// Message, a fomat string that can be handled by the String.Format method - /// Arguments for formatting - void Warning(string format, params object[] args) - { - Debug.WriteLine("Warning:"); - Debug.WriteLine(format, args); - } -} diff --git a/Libs/Webmaster442.HttpServerFramework/Webmaster442.HttpServerFramework.csproj b/Libs/Webmaster442.HttpServerFramework/Webmaster442.HttpServerFramework.csproj index e2483a0c..12d6b517 100644 --- a/Libs/Webmaster442.HttpServerFramework/Webmaster442.HttpServerFramework.csproj +++ b/Libs/Webmaster442.HttpServerFramework/Webmaster442.HttpServerFramework.csproj @@ -13,7 +13,11 @@ - + + + + + diff --git a/Prog/BookGen/Commands/PreviewCommand.cs b/Prog/BookGen/Commands/PreviewCommand.cs index b90e52f6..0565e624 100644 --- a/Prog/BookGen/Commands/PreviewCommand.cs +++ b/Prog/BookGen/Commands/PreviewCommand.cs @@ -14,13 +14,11 @@ namespace BookGen.Commands; internal class PreviewCommand : Command { private readonly ILog _log; - private readonly IServerLog _serverlog; private readonly IAppSetting _appSettings; - public PreviewCommand(ILog log, IServerLog serverLog, IAppSetting appSettings) + public PreviewCommand(ILog log, IAppSetting appSettings) { _log = log; - _serverlog = serverLog; _appSettings = appSettings; } @@ -28,7 +26,7 @@ public override int Execute(BookGenArgumentBase arguments, string[] context) { const string url = "http://localhost:8082/"; - using (HttpServer? server = HttpServerFactory.CreateServerForPreview(_log, _serverlog, arguments.Directory)) + using (HttpServer? server = HttpServerFactory.CreateServerForPreview(_log, arguments.Directory)) { server.Start(); _log.Info("-------------------------------------------------"); diff --git a/Prog/BookGen/Commands/ServeCommand.cs b/Prog/BookGen/Commands/ServeCommand.cs index b8ef3fda..e667fcc6 100644 --- a/Prog/BookGen/Commands/ServeCommand.cs +++ b/Prog/BookGen/Commands/ServeCommand.cs @@ -15,12 +15,10 @@ namespace BookGen.Commands; internal class ServeCommand : Command { private readonly ILog _log; - private readonly IServerLog _serverLog; - public ServeCommand(ILog log, IServerLog serverLog) + public ServeCommand(ILog log) { _log = log; - _serverLog = serverLog; } public override int Execute(BookGenArgumentBase arguments, string[] context) @@ -29,7 +27,7 @@ public override int Execute(BookGenArgumentBase arguments, string[] context) _log.CheckLockFileExistsAndExitWhenNeeded(arguments.Directory); - using (HttpServer? server = HttpServerFactory.CreateServerForServModule(_serverLog, arguments.Directory)) + using (HttpServer? server = HttpServerFactory.CreateServerForServModule(_log, arguments.Directory)) { server.Start(); _log.Info("Serving: {0}", arguments.Directory); diff --git a/Prog/BookGen/Framework/JsonLog.cs b/Prog/BookGen/Framework/JsonLog.cs index 9bf71a7e..f6bc60be 100644 --- a/Prog/BookGen/Framework/JsonLog.cs +++ b/Prog/BookGen/Framework/JsonLog.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2021 Ruzsinszki Gábor +// (c) 2021-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -10,7 +10,7 @@ namespace BookGen.Framework; -internal sealed class JsonLog : ILog, IServerLog +internal sealed class JsonLog : ILog { private readonly List _entries; private readonly JsonSerializerOptions _options; @@ -45,14 +45,4 @@ public void Log(LogLevel logLevel, string format, params object[] args) }); OnLogWritten?.Invoke(this, new LogEventArgs(logLevel, string.Format(format, args))); } - - public void PrintLine(string str) - { - Log(LogLevel.PrintLine, str, Array.Empty()); - } - - public void PrintLine(object obj) - { - Log(LogLevel.PrintLine, obj.ToString() ?? string.Empty, Array.Empty()); - } } diff --git a/Prog/BookGen/Framework/Server/HttpServerFactory.cs b/Prog/BookGen/Framework/Server/HttpServerFactory.cs index 40da504e..f8078a8d 100644 --- a/Prog/BookGen/Framework/Server/HttpServerFactory.cs +++ b/Prog/BookGen/Framework/Server/HttpServerFactory.cs @@ -12,7 +12,7 @@ namespace BookGen.Framework.Server; internal static class HttpServerFactory { - public static HttpServer CreateServerForTest(IServerLog log, string folder) + public static HttpServer CreateServerForTest(ILog log, string folder) { bool debug = false; #if DEBUG @@ -35,7 +35,7 @@ public static HttpServer CreateServerForTest(IServerLog log, string folder) return server; } - public static HttpServer CreateServerForServModule(IServerLog log, string folder) + public static HttpServer CreateServerForServModule(ILog log, string folder) { bool debug = false; #if DEBUG @@ -58,7 +58,7 @@ public static HttpServer CreateServerForServModule(IServerLog log, string folder return server; } - public static HttpServer CreateServerForPreview(ILog log, IServerLog serverlog, string directory) + public static HttpServer CreateServerForPreview(ILog log, string directory) { bool debug = false; #if DEBUG @@ -70,7 +70,7 @@ public static HttpServer CreateServerForPreview(ILog log, IServerLog serverlog, DebugMode = debug, Port = 8082, EnableLastAccesTime = false, - }, serverlog); + }, log); server diff --git a/Prog/BookGen/Framework/Server/PreviewRenderHandler.cs b/Prog/BookGen/Framework/Server/PreviewRenderHandler.cs index bf6b9006..718ef440 100644 --- a/Prog/BookGen/Framework/Server/PreviewRenderHandler.cs +++ b/Prog/BookGen/Framework/Server/PreviewRenderHandler.cs @@ -66,7 +66,7 @@ public void Dispose() } } - public async Task Handle(IServerLog? log, HttpRequest request, HttpResponse response) + public async Task Handle(ILog? log, HttpRequest request, HttpResponse response) { response.Headers.Add("Cache-Control", "no-store"); response.ContentType = "text/html"; diff --git a/Prog/BookGen/Framework/Server/PreviewStaticHandler.cs b/Prog/BookGen/Framework/Server/PreviewStaticHandler.cs index ca80b0ae..0301e1eb 100644 --- a/Prog/BookGen/Framework/Server/PreviewStaticHandler.cs +++ b/Prog/BookGen/Framework/Server/PreviewStaticHandler.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2021-2022 Ruzsinszki Gábor +// (c) 2021-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -31,7 +31,7 @@ private bool CanServe(string AbsoluteUri) return _table.ContainsKey(AbsoluteUri); } - public async Task Handle(IServerLog? log, HttpRequest request, HttpResponse response) + public async Task Handle(ILog? log, HttpRequest request, HttpResponse response) { if (CanServe(request.Url)) { diff --git a/Prog/BookGen/GeneratorRunner.cs b/Prog/BookGen/GeneratorRunner.cs index 41ea14f0..d0319102 100644 --- a/Prog/BookGen/GeneratorRunner.cs +++ b/Prog/BookGen/GeneratorRunner.cs @@ -36,20 +36,17 @@ public string WorkDirectory } public ILog Log { get; } - public IServerLog ServerLog { get; } public bool NoWait { get; internal set; } public bool IsBookGenFolder => _projectLoader.IsBookGenFolder; public GeneratorRunner(ILog log, - IServerLog serverLog, IModuleApi moduleApi, IAppSetting appSettings, ProgramInfo programInfo, TimeProvider timeProvider, string workDir) { - ServerLog = serverLog; _moduleApi = moduleApi; Log = log; _appSettings = appSettings; @@ -203,7 +200,7 @@ public void DoTest() var builder = new WebsiteGeneratorStepRunner(settings, Log, loader); TimeSpan runTime = builder.Run(); - using (HttpServer? server = HttpServerFactory.CreateServerForTest(ServerLog, Path.Combine(WorkDirectory, _projectLoader.Configuration.TargetWeb.OutPutDirectory))) + using (HttpServer? server = HttpServerFactory.CreateServerForTest(Log, Path.Combine(WorkDirectory, _projectLoader.Configuration.TargetWeb.OutPutDirectory))) { server.Start(); Log.Info("-------------------------------------------------"); diff --git a/Prog/BookGen/Infrastructure/ModuleApi.cs b/Prog/BookGen/Infrastructure/ModuleApi.cs index ddc270cc..b36b373e 100644 --- a/Prog/BookGen/Infrastructure/ModuleApi.cs +++ b/Prog/BookGen/Infrastructure/ModuleApi.cs @@ -10,19 +10,16 @@ namespace BookGen.Infrastructure; internal sealed class ModuleApi : IModuleApi { private readonly ILog _log; - private readonly IServerLog _serverLog; private readonly IAppSetting _setting; private readonly ProgramInfo _programInfo; private readonly TimeProvider _timeProvider; public ModuleApi(ILog log, - IServerLog serverLog, IAppSetting setting, ProgramInfo programInfo, TimeProvider timeProvider) { _log = log; - _serverLog = serverLog; _setting = setting; _programInfo = programInfo; _timeProvider = timeProvider; @@ -39,7 +36,7 @@ public void ExecuteModule(string module, string[] arguments) public string[] GetAutoCompleteItems(string commandName) { - return OnGetAutocompleteItems?.Invoke(commandName) ?? Array.Empty(); + return OnGetAutocompleteItems?.Invoke(commandName) ?? []; } public IEnumerable GetCommandNames() @@ -59,6 +56,6 @@ public void Wait(string exitString) public GeneratorRunner CreateRunner(bool verbose, string workDir) { _log.LogLevel = verbose ? LogLevel.Detail : LogLevel.Info; - return new GeneratorRunner(_log, _serverLog, this, _setting, _programInfo, _timeProvider, workDir); + return new GeneratorRunner(_log, this, _setting, _programInfo, _timeProvider, workDir); } } \ No newline at end of file diff --git a/Prog/BookGen/Infrastructure/ProgramConfigurator.cs b/Prog/BookGen/Infrastructure/ProgramConfigurator.cs index d9d4af1a..779d7c76 100644 --- a/Prog/BookGen/Infrastructure/ProgramConfigurator.cs +++ b/Prog/BookGen/Infrastructure/ProgramConfigurator.cs @@ -82,24 +82,22 @@ public static void WaitForDebugger(IList arguments) } } - internal static (ILog, IServerLog) ConfigureLog(IList arguments) + internal static ILog ConfigureLog(IList arguments) { if (GetSwitch(arguments, JsonLogShort, JsonLogLong)) { - var logImplementation = new JsonLog(); - return (logImplementation, logImplementation); + return new JsonLog(); } bool logFile = GetSwitch(arguments, LogFileShort, LogFileLong); - var log = new TerminalLog(logFile); - return (log, log); + return new TerminalLog(logFile); } - internal static ProgramInfo ConfigureState(IList arguments) { - ProgramInfo state = new(); - state.NoWaitForExit = GetSwitch(arguments, NoWait, NoWait); - return state; + return new() + { + NoWaitForExit = GetSwitch(arguments, NoWait, NoWait) + }; } } diff --git a/Prog/BookGen/Program.cs b/Prog/BookGen/Program.cs index 09c83c6b..91d37577 100644 --- a/Prog/BookGen/Program.cs +++ b/Prog/BookGen/Program.cs @@ -20,18 +20,17 @@ ProgramConfigurator.WaitForDebugger(argumentList); -(ILog log, IServerLog serverLog) = ProgramConfigurator.ConfigureLog(argumentList); +ILog log = ProgramConfigurator.ConfigureLog(argumentList); ProgramInfo info = new(); var timeProvider = new TimeProviderImplementation(); AppSetting settings = AppSettingHandler.LoadAppSettings() ?? new AppSetting(); -var api = new ModuleApi(log, serverLog, settings, info, timeProvider); +var api = new ModuleApi(log, settings, info, timeProvider); SimpleIoC ioc = new(); ioc.RegisterSingleton(); ioc.RegisterSingleton(log); -ioc.RegisterSingleton(serverLog); ioc.RegisterSingleton(info); ioc.RegisterSingleton(settings); ioc.RegisterSingleton(settings); diff --git a/Test/BookGen.Tests/UT_TestServer.cs b/Test/BookGen.Tests/UT_TestServer.cs index 7d079619..55a99ea6 100644 --- a/Test/BookGen.Tests/UT_TestServer.cs +++ b/Test/BookGen.Tests/UT_TestServer.cs @@ -14,7 +14,7 @@ namespace BookGen.Tests public class UT_TestServer { private HttpServer _server; - private IServerLog _log; + private ILog _log; private class TestHandler : IRequestHandler { @@ -23,7 +23,7 @@ private static bool CanServe(string AbsoluteUri) return AbsoluteUri == "/testme"; } - public async Task Handle(IServerLog log, HttpRequest request, HttpResponse response) + public async Task Handle(ILog log, HttpRequest request, HttpResponse response) { if (CanServe(request.Url)) { @@ -40,7 +40,7 @@ public async Task Handle(IServerLog log, HttpRequest request, HttpResponse [SetUp] public void Setup() { - _log = Substitute.For(); + _log = Substitute.For(); _server = new HttpServer(new HttpServerConfiguration { Port = 8080, From b2314a782a388fbace77f8889bad3ba00ab9a40f Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Wed, 29 Nov 2023 20:29:59 +0100 Subject: [PATCH 20/34] Command build warnings resolved --- .../ViewModels/Commands/CommandBase.cs | 25 +++++++++++++++++++ .../ViewModels/Commands/ProcessCommandBase.cs | 15 +++-------- .../ViewModels/Commands/TaskRunnerCommand.cs | 12 ++------- 3 files changed, 31 insertions(+), 21 deletions(-) create mode 100644 Prog/BookGen.Launcher/ViewModels/Commands/CommandBase.cs diff --git a/Prog/BookGen.Launcher/ViewModels/Commands/CommandBase.cs b/Prog/BookGen.Launcher/ViewModels/Commands/CommandBase.cs new file mode 100644 index 00000000..bdc2c53a --- /dev/null +++ b/Prog/BookGen.Launcher/ViewModels/Commands/CommandBase.cs @@ -0,0 +1,25 @@ +//----------------------------------------------------------------------------- +// (c) 2023 Ruzsinszki Gábor +// This code is licensed under MIT license (see LICENSE for details) +//----------------------------------------------------------------------------- + +using System.Windows.Input; + +namespace BookGen.Launcher.ViewModels.Commands; + +internal abstract class CommandBase : ICommand +{ + public event EventHandler? CanExecuteChanged; + + public void OnCanExecuteChanged() + { + CanExecuteChanged?.Invoke(this, EventArgs.Empty); + } + + public virtual bool CanExecute(object? parameter) + { + return true; + } + + public abstract void Execute(object? parameter); +} diff --git a/Prog/BookGen.Launcher/ViewModels/Commands/ProcessCommandBase.cs b/Prog/BookGen.Launcher/ViewModels/Commands/ProcessCommandBase.cs index 94d8fbe3..56eae545 100644 --- a/Prog/BookGen.Launcher/ViewModels/Commands/ProcessCommandBase.cs +++ b/Prog/BookGen.Launcher/ViewModels/Commands/ProcessCommandBase.cs @@ -1,10 +1,9 @@ //----------------------------------------------------------------------------- -// (c) 2021-2022 Ruzsinszki Gábor +// (c) 2021-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using System.Diagnostics; -using System.Windows.Input; using BookGen.Domain.Terminal; using BookGen.DomainServices; @@ -12,9 +11,8 @@ namespace BookGen.Launcher.ViewModels.Commands; -internal abstract class ProcessCommandBase : ICommand +internal abstract class ProcessCommandBase : CommandBase { - public event EventHandler? CanExecuteChanged; protected InstallStatus InstallStatus; protected const string PowershellExe = "powershell.exe"; @@ -24,7 +22,7 @@ protected ProcessCommandBase() InstallStatus = InstallDetector.GetInstallStatus(); } - public bool CanExecute(object? parameter) + public override bool CanExecute(object? parameter) { return CanExecute(parameter as string); } @@ -34,7 +32,7 @@ public virtual bool CanExecute(string? folder) return Directory.Exists(folder); } - public void Execute(object? parameter) + public override void Execute(object? parameter) { Execute(parameter as string); if (Settings.Default.AutoExitLauncher) @@ -44,11 +42,6 @@ public void Execute(object? parameter) } } - public void OnCanExecuteChanged() - { - CanExecuteChanged?.Invoke(this, EventArgs.Empty); - } - protected static void Message(string text, MessageBoxImage icon) { Dialog.ShowMessageBox(text, icon.ToString(), MessageBoxButton.OK, icon); diff --git a/Prog/BookGen.Launcher/ViewModels/Commands/TaskRunnerCommand.cs b/Prog/BookGen.Launcher/ViewModels/Commands/TaskRunnerCommand.cs index b9b8a37c..9d9b9987 100644 --- a/Prog/BookGen.Launcher/ViewModels/Commands/TaskRunnerCommand.cs +++ b/Prog/BookGen.Launcher/ViewModels/Commands/TaskRunnerCommand.cs @@ -4,15 +4,12 @@ //----------------------------------------------------------------------------- using System.Diagnostics; -using System.Windows.Input; using BookGen.Launcher.ViewModels.FileBrowser; namespace BookGen.Launcher.ViewModels.Commands; -internal class TaskRunnerCommand : ICommand +internal class TaskRunnerCommand : CommandBase { - public event EventHandler? CanExecuteChanged; - public string Folder { get; set; } public TaskRunnerCommand() @@ -20,12 +17,7 @@ public TaskRunnerCommand() Folder = Environment.CurrentDirectory; } - public bool CanExecute(object? parameter) - { - return true; - } - - public void Execute(object? parameter) + public override void Execute(object? parameter) { if (parameter is not BookGenTask task) return; From 3ac45124685a72ac8f69cdd143af3669c4bf68f6 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Wed, 29 Nov 2023 20:31:09 +0100 Subject: [PATCH 21/34] SVG.Skia update --- Libs/BookGen.DomainServices/BookGen.DomainServices.csproj | 2 +- Prog/BookGen/BookGen.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Libs/BookGen.DomainServices/BookGen.DomainServices.csproj b/Libs/BookGen.DomainServices/BookGen.DomainServices.csproj index c4bf52f6..8d1b0c6d 100644 --- a/Libs/BookGen.DomainServices/BookGen.DomainServices.csproj +++ b/Libs/BookGen.DomainServices/BookGen.DomainServices.csproj @@ -20,7 +20,7 @@ - + diff --git a/Prog/BookGen/BookGen.csproj b/Prog/BookGen/BookGen.csproj index 0a749624..be99a9aa 100644 --- a/Prog/BookGen/BookGen.csproj +++ b/Prog/BookGen/BookGen.csproj @@ -39,7 +39,7 @@ - + From 5fe951f234503be2615a00026d720c40e90dcd65 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Wed, 29 Nov 2023 20:35:15 +0100 Subject: [PATCH 22/34] Nunit: 4.0 --- Test/BookGen.Tests/BookGen.Tests.csproj | 4 ++-- Test/BookGen.Tests/UT_HtmlTidy.cs | 2 +- Test/BookGen.Tests/UT_XmlDocValidator.cs | 4 ++-- Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj | 4 ++-- Test/BookGen.TestsSystem/ST_Build.cs | 4 ++-- Test/BookGen.TestsSystem/ST_Md2HTMl.cs | 6 +++--- Test/BookGen.TestsSystem/TestEnvironment.cs | 7 +++++-- 7 files changed, 17 insertions(+), 14 deletions(-) diff --git a/Test/BookGen.Tests/BookGen.Tests.csproj b/Test/BookGen.Tests/BookGen.Tests.csproj index 523e1a45..7d3333b3 100644 --- a/Test/BookGen.Tests/BookGen.Tests.csproj +++ b/Test/BookGen.Tests/BookGen.Tests.csproj @@ -17,9 +17,9 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Test/BookGen.Tests/UT_HtmlTidy.cs b/Test/BookGen.Tests/UT_HtmlTidy.cs index 7794eb54..b6a1d51e 100644 --- a/Test/BookGen.Tests/UT_HtmlTidy.cs +++ b/Test/BookGen.Tests/UT_HtmlTidy.cs @@ -33,7 +33,7 @@ public void EnsureThat_HtmlTidy_ConvertHtml5TagsToXhtmlCompatible_Correct(string } [Test] - [Timeout(3000)] + [CancelAfter(3000)] public void EnsureThat_HtmlTidy_HtmlToXhtml_ReturnsText() { var file = TestEnvironment.GetFile("full.html"); diff --git a/Test/BookGen.Tests/UT_XmlDocValidator.cs b/Test/BookGen.Tests/UT_XmlDocValidator.cs index 7b461d61..5f894b6a 100644 --- a/Test/BookGen.Tests/UT_XmlDocValidator.cs +++ b/Test/BookGen.Tests/UT_XmlDocValidator.cs @@ -22,14 +22,14 @@ public void Setup() public void EnsureThatValidXmlResultsTrue() { bool result = XmlDocValidator.ValidateXml(new FsPath(TestEnvironment.GetFile("test.xml")), _logMock); - Assert.IsTrue(result); + Assert.That(result, Is.True); } [Test] public void EnsureThatInvalidXmlResultsFalse() { bool result = XmlDocValidator.ValidateXml(new FsPath(TestEnvironment.GetFile("test.js")), _logMock); - Assert.False(result); + Assert.That(result, Is.False); } } } diff --git a/Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj b/Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj index 4e67f364..04b12f50 100644 --- a/Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj +++ b/Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj @@ -20,9 +20,9 @@ - + - + all runtime; build; native; contentfiles; analyzers; buildtransitive diff --git a/Test/BookGen.TestsSystem/ST_Build.cs b/Test/BookGen.TestsSystem/ST_Build.cs index d41c21e2..4b1d6f90 100644 --- a/Test/BookGen.TestsSystem/ST_Build.cs +++ b/Test/BookGen.TestsSystem/ST_Build.cs @@ -12,14 +12,14 @@ public ST_Build() : base("book") { } - [Test, Timeout(3000)] + [Test, CancelAfter(3000)] public void Test_Build_Print() { EnsureRunWithoutException(Constants.Succes, "Build -a BuildPrint -n"); Environment.AssertFileExistsAndHasContents("output", "print", "print.html"); } - [Test, Timeout(3000)] + [Test, CancelAfter(3000)] public void Test_Build_Website() { EnsureRunWithoutException(Constants.Succes, "Build -a BuildWeb -n"); diff --git a/Test/BookGen.TestsSystem/ST_Md2HTMl.cs b/Test/BookGen.TestsSystem/ST_Md2HTMl.cs index cb7b173c..c468fb09 100644 --- a/Test/BookGen.TestsSystem/ST_Md2HTMl.cs +++ b/Test/BookGen.TestsSystem/ST_Md2HTMl.cs @@ -16,7 +16,7 @@ public ST_Md2HTML() : base("Book") { } - [Test, Timeout(3000)] + [Test, CancelAfter(3000)] public void Test_NoSyntax_Raw() { EnsureRunWithoutException(Constants.Succes, "md2html -i Testpage.md -ns -r -o nsr.html -nw"); @@ -29,7 +29,7 @@ public void Test_NoSyntax_Raw() }); } - [Test, Timeout(3000)] + [Test, CancelAfter(3000)] public void Test_Syntax_Raw() { EnsureRunWithoutException(Constants.Succes, "md2html -i Testpage.md -r -o r.html -nw"); @@ -46,7 +46,7 @@ public void Test_Syntax_Raw() }); } - [Test, Timeout(3000)] + [Test, CancelAfter(3000)] public void Test_Full() { EnsureRunWithoutException(Constants.Succes, "md2html -i Testpage.md -o full.html -nw"); diff --git a/Test/BookGen.TestsSystem/TestEnvironment.cs b/Test/BookGen.TestsSystem/TestEnvironment.cs index 186e5250..9581b46e 100644 --- a/Test/BookGen.TestsSystem/TestEnvironment.cs +++ b/Test/BookGen.TestsSystem/TestEnvironment.cs @@ -17,8 +17,11 @@ public void AssertFileExistsAndHasContents(params string[] file) { var filePath = Path.Combine(file); var f = new FileInfo(Path.Combine(_workDir, filePath)); - Assert.IsTrue(f.Exists); - Assert.IsTrue(f.Length > 0); + Assert.Multiple(() => + { + Assert.That(f.Exists, Is.True); + Assert.That(f.Length, Is.GreaterThan(0)); + }); } public string ReadFileContents(string file) From 85b291fce9a4ddd1e10eb1f6af2e17f4490107e9 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Thu, 30 Nov 2023 20:13:33 +0100 Subject: [PATCH 23/34] Some infrastructure changes --- Libs/BookGen.Domain/TOC.cs | 14 ++++++++++++++ Libs/BookGen.Interfaces/ITableOfContents.cs | 2 +- Prog/BookGen/Infrastructure/ModuleApi.cs | 2 -- Prog/BookGen/Infrastructure/ProgramConfigurator.cs | 2 -- Prog/BookGen/ProjectHandling/ProjectLoader.cs | 6 +++--- Prog/BookGen/ProjectHandling/Steps/TocValidate.cs | 1 - 6 files changed, 18 insertions(+), 9 deletions(-) diff --git a/Libs/BookGen.Domain/TOC.cs b/Libs/BookGen.Domain/TOC.cs index 45a82780..7738e77b 100644 --- a/Libs/BookGen.Domain/TOC.cs +++ b/Libs/BookGen.Domain/TOC.cs @@ -3,6 +3,8 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- +using System.Collections; + using BookGen.Interfaces; namespace BookGen.Domain @@ -61,6 +63,18 @@ public IEnumerable GetLinksForChapter(string? chapter = null) } } + public IEnumerator GetEnumerator() + { + return _tocContents + .SelectMany(x => x.Value) + .GetEnumerator(); + } + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } + public IEnumerable Files { get diff --git a/Libs/BookGen.Interfaces/ITableOfContents.cs b/Libs/BookGen.Interfaces/ITableOfContents.cs index e821f58a..587266b6 100644 --- a/Libs/BookGen.Interfaces/ITableOfContents.cs +++ b/Libs/BookGen.Interfaces/ITableOfContents.cs @@ -8,7 +8,7 @@ namespace BookGen.Interfaces /// /// Interface for accesing the table of contents /// - public interface ITableOfContents + public interface ITableOfContents : IEnumerable { /// /// A flat list of chapters without hierarchy diff --git a/Prog/BookGen/Infrastructure/ModuleApi.cs b/Prog/BookGen/Infrastructure/ModuleApi.cs index b36b373e..12d97930 100644 --- a/Prog/BookGen/Infrastructure/ModuleApi.cs +++ b/Prog/BookGen/Infrastructure/ModuleApi.cs @@ -3,8 +3,6 @@ // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using Webmaster442.HttpServerFramework; - namespace BookGen.Infrastructure; internal sealed class ModuleApi : IModuleApi diff --git a/Prog/BookGen/Infrastructure/ProgramConfigurator.cs b/Prog/BookGen/Infrastructure/ProgramConfigurator.cs index 779d7c76..293ce996 100644 --- a/Prog/BookGen/Infrastructure/ProgramConfigurator.cs +++ b/Prog/BookGen/Infrastructure/ProgramConfigurator.cs @@ -9,8 +9,6 @@ using BookGen.Framework; using BookGen.Gui; -using Webmaster442.HttpServerFramework; - namespace BookGen.Infrastructure; internal static class ProgramConfigurator diff --git a/Prog/BookGen/ProjectHandling/ProjectLoader.cs b/Prog/BookGen/ProjectHandling/ProjectLoader.cs index 56f17c91..0785f161 100644 --- a/Prog/BookGen/ProjectHandling/ProjectLoader.cs +++ b/Prog/BookGen/ProjectHandling/ProjectLoader.cs @@ -19,8 +19,8 @@ public ProjectLoader(string workDir, ILog log, ProgramInfo programInfo) { _state = new LoadState(workDir, programInfo.ConfigVersion); _log = log; - _loadSteps = new LoadStep[] - { + _loadSteps = + [ new MigrateProjectIfOldStyle(_state, _log), new ConfigLoad(_state, _log), new ConfigUpgrade(_state, _log), @@ -28,7 +28,7 @@ public ProjectLoader(string workDir, ILog log, ProgramInfo programInfo) new TocLoad(_state, _log), new TocValidate(_state, _log), new TagsLoad(_state, _log), - }; + ]; } public Config Configuration diff --git a/Prog/BookGen/ProjectHandling/Steps/TocValidate.cs b/Prog/BookGen/ProjectHandling/Steps/TocValidate.cs index 230e49d1..a4559df6 100644 --- a/Prog/BookGen/ProjectHandling/Steps/TocValidate.cs +++ b/Prog/BookGen/ProjectHandling/Steps/TocValidate.cs @@ -32,6 +32,5 @@ public override bool Execute() Log.Info("TOC file doesn't contain any errors"); return true; - } } From 88b8882125af4091a82e995291f303997a1de5d9 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Thu, 30 Nov 2023 20:23:50 +0100 Subject: [PATCH 24/34] Restored verbose logging option --- Prog/BookGen/Commands/BuildCommand.cs | 1 - Prog/BookGen/Commands/DownloadCommand.cs | 3 +++ Prog/BookGen/Commands/PackCommand.cs | 7 +++++-- Prog/BookGen/Commands/PreviewCommand.cs | 3 +++ Prog/BookGen/Commands/TagsCommand.cs | 3 +-- Prog/BookGen/Commands/TasksCommand.cs | 3 +++ Prog/BookGen/Infrastructure/Extensions.cs | 9 ++++++++- 7 files changed, 23 insertions(+), 6 deletions(-) diff --git a/Prog/BookGen/Commands/BuildCommand.cs b/Prog/BookGen/Commands/BuildCommand.cs index 6b5ed9a3..c5257c89 100644 --- a/Prog/BookGen/Commands/BuildCommand.cs +++ b/Prog/BookGen/Commands/BuildCommand.cs @@ -24,7 +24,6 @@ public override int Execute(BuildArguments arguments, string[] context) { _log.CheckLockFileExistsAndExitWhenNeeded(arguments.Directory); - GeneratorRunner? runner = _moduleApi.CreateRunner(arguments.Verbose, arguments.Directory); runner.NoWait = arguments.NoWaitForExit; diff --git a/Prog/BookGen/Commands/DownloadCommand.cs b/Prog/BookGen/Commands/DownloadCommand.cs index dc8f7132..c1ffb65b 100644 --- a/Prog/BookGen/Commands/DownloadCommand.cs +++ b/Prog/BookGen/Commands/DownloadCommand.cs @@ -1,4 +1,5 @@ using BookGen.CommandArguments; +using BookGen.Infrastructure; namespace BookGen.Commands; @@ -14,6 +15,8 @@ public DownloadCommand(ILog log) public override async Task Execute(DownloadArguments arguments, string[] context) { + _log.EnableVerboseLogingIfRequested(arguments); + using (var client = new BookGenHttpClient()) { try diff --git a/Prog/BookGen/Commands/PackCommand.cs b/Prog/BookGen/Commands/PackCommand.cs index 272f9436..63a69bf0 100644 --- a/Prog/BookGen/Commands/PackCommand.cs +++ b/Prog/BookGen/Commands/PackCommand.cs @@ -8,6 +8,7 @@ using BookGen.CommandArguments; using BookGen.Framework; using BookGen.Gui; +using BookGen.Infrastructure; using BookGen.ProjectHandling; namespace BookGen.Commands; @@ -26,9 +27,11 @@ public PackCommand(ILog log, ProgramInfo programInfo) public override int Execute(PackArguments arguments, string[] context) { - ProjectLoader loader = new ProjectLoader(arguments.Directory, _log, _programInfo); + _log.EnableVerboseLogingIfRequested(arguments); - List filesToPack = new List(); + ProjectLoader loader = new(arguments.Directory, _log, _programInfo); + + List filesToPack = []; if (!loader.LoadProject()) { diff --git a/Prog/BookGen/Commands/PreviewCommand.cs b/Prog/BookGen/Commands/PreviewCommand.cs index 0565e624..67e45364 100644 --- a/Prog/BookGen/Commands/PreviewCommand.cs +++ b/Prog/BookGen/Commands/PreviewCommand.cs @@ -5,6 +5,7 @@ using BookGen.CommandArguments; using BookGen.Framework.Server; +using BookGen.Infrastructure; using Webmaster442.HttpServerFramework; @@ -26,6 +27,8 @@ public override int Execute(BookGenArgumentBase arguments, string[] context) { const string url = "http://localhost:8082/"; + _log.EnableVerboseLogingIfRequested(arguments); + using (HttpServer? server = HttpServerFactory.CreateServerForPreview(_log, arguments.Directory)) { server.Start(); diff --git a/Prog/BookGen/Commands/TagsCommand.cs b/Prog/BookGen/Commands/TagsCommand.cs index afb9edd2..08feb4e6 100644 --- a/Prog/BookGen/Commands/TagsCommand.cs +++ b/Prog/BookGen/Commands/TagsCommand.cs @@ -25,8 +25,7 @@ public TagsCommand(ILog log, ProgramInfo programInfo) public override int Execute(TagsArguments arguments, string[] context) { - _log.LogLevel = arguments.Verbose ? Api.LogLevel.Detail : Api.LogLevel.Info; - + _log.EnableVerboseLogingIfRequested(arguments); _log.CheckLockFileExistsAndExitWhenNeeded(arguments.Directory); var loader = new ProjectLoader(arguments.Directory, _log, _programInfo); diff --git a/Prog/BookGen/Commands/TasksCommand.cs b/Prog/BookGen/Commands/TasksCommand.cs index 0ddd8fc7..43978a1c 100644 --- a/Prog/BookGen/Commands/TasksCommand.cs +++ b/Prog/BookGen/Commands/TasksCommand.cs @@ -8,6 +8,7 @@ using BookGen.CommandArguments; using BookGen.ConsoleUi; using BookGen.Domain.TaskRunner; +using BookGen.Infrastructure; using BookGen.ProjectHandling; namespace BookGen.Commands; @@ -26,6 +27,8 @@ public TasksCommand(BookGenTaskRunner taskRunner, ILog log) public override async Task Execute(TasksArgument arguments, string[] context) { + _log.EnableVerboseLogingIfRequested(arguments); + ProjectFiles files = ProjectFilesLocator.Locate(new FsPath(arguments.Directory)); if (!files.TasksXml.IsExisting) { diff --git a/Prog/BookGen/Infrastructure/Extensions.cs b/Prog/BookGen/Infrastructure/Extensions.cs index 8fc7fad7..8e7d4229 100644 --- a/Prog/BookGen/Infrastructure/Extensions.cs +++ b/Prog/BookGen/Infrastructure/Extensions.cs @@ -1,4 +1,5 @@ -using BookGen.Framework; +using BookGen.CommandArguments; +using BookGen.Framework; namespace BookGen.Infrastructure; @@ -13,4 +14,10 @@ public static void CheckLockFileExistsAndExitWhenNeeded(this ILog log, string fo Environment.Exit(Constants.FolderLocked); } } + + public static void EnableVerboseLogingIfRequested(this ILog log, BookGenArgumentBase argumentBase) + { + if (argumentBase.Verbose) + log.LogLevel = LogLevel.Detail; + } } From 992ef0899f79c98869bb91fbe88ab48e830783a8 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 1 Dec 2023 22:31:09 +0100 Subject: [PATCH 25/34] Progress on TOC command --- Libs/BookGen.DomainServices/TocUtils.cs | 49 +++++++++++++++++++++++++ Prog/BookGen/Commands/TocCommand.cs | 38 +++++++++++++++++++ 2 files changed, 87 insertions(+) create mode 100644 Libs/BookGen.DomainServices/TocUtils.cs create mode 100644 Prog/BookGen/Commands/TocCommand.cs diff --git a/Libs/BookGen.DomainServices/TocUtils.cs b/Libs/BookGen.DomainServices/TocUtils.cs new file mode 100644 index 00000000..338cb990 --- /dev/null +++ b/Libs/BookGen.DomainServices/TocUtils.cs @@ -0,0 +1,49 @@ +using System.Diagnostics.CodeAnalysis; + +using BookGen.Api; +using BookGen.Interfaces; + +namespace BookGen.DomainServices; +public static class TocUtils +{ + public static IEnumerable GetLinks(FsPath directory, ILog log) + { + var contents = directory.GetAllFiles(true, "*.md"); + foreach (var file in contents) + { + var content = file.ReadFile(log); + var title = MarkdownUtils.GetDocumentTitle(content, log); + yield return new Link(title, file.GetRelativePathRelativeTo(directory).ToString().Replace(@"\", "/")); + } + } + + public static readonly IEqualityComparer LinkTargetComparer = new LinkByUrlEqualityComparer(); + + public static readonly IEqualityComparer LinkTitleComparer = new LinkByTitleComparer(); + + private class LinkByTitleComparer : IEqualityComparer + { + public bool Equals(Link? x, Link? y) + { + return x?.Text == y?.Text; + } + + public int GetHashCode([DisallowNull] Link obj) + { + return obj.Text.GetHashCode(); + } + } + + private class LinkByUrlEqualityComparer : IEqualityComparer + { + public bool Equals(Link? x, Link? y) + { + return x?.Url == y?.Url; + } + + public int GetHashCode([DisallowNull] Link obj) + { + return obj.Url.GetHashCode(); + } + } +} diff --git a/Prog/BookGen/Commands/TocCommand.cs b/Prog/BookGen/Commands/TocCommand.cs new file mode 100644 index 00000000..57d02422 --- /dev/null +++ b/Prog/BookGen/Commands/TocCommand.cs @@ -0,0 +1,38 @@ +using BookGen.CommandArguments; +using BookGen.Infrastructure; +using BookGen.ProjectHandling; + +namespace BookGen.Commands; + +[CommandName("toc")] +internal sealed class TocCommand : Command +{ + private readonly ILog _log; + private readonly ProgramInfo _programInfo; + + public TocCommand(ILog log, ProgramInfo programInfo) + { + _log = log; + _programInfo = programInfo; + } + + public override int Execute(BookGenArgumentBase arguments, string[] context) + { + _log.EnableVerboseLogingIfRequested(arguments); + + ProjectLoader loader = new(arguments.Directory, _log, _programInfo); + if (!loader.LoadProject()) + { + return Constants.GeneralError; + } + + var files = TocUtils.GetLinks(new FsPath(arguments.Directory), _log); + + HashSet tocLinks = new HashSet(loader.Toc, TocUtils.LinkTargetComparer); + HashSet fileLinks = new HashSet(files, TocUtils.LinkTargetComparer); + + var items = fileLinks.Except(tocLinks, TocUtils.LinkTargetComparer).ToArray(); + + return Constants.GeneralError; + } +} From 46d7873c408ad069e13569e5e20d99c7caa858a8 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 1 Dec 2023 22:33:51 +0100 Subject: [PATCH 26/34] Work on Toc command --- Libs/BookGen.Gui/ITerminal.cs | 1 + Libs/BookGen.Gui/Terminal.cs | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/Libs/BookGen.Gui/ITerminal.cs b/Libs/BookGen.Gui/ITerminal.cs index 3df382e1..08173f5e 100644 --- a/Libs/BookGen.Gui/ITerminal.cs +++ b/Libs/BookGen.Gui/ITerminal.cs @@ -7,4 +7,5 @@ public interface ITerminal void Header(string title); void Table(IDictionary rows, string keyColumnName = "", string valueColumnName = ""); void Table(IEnumerable rows); + bool Confirm(string message); } \ No newline at end of file diff --git a/Libs/BookGen.Gui/Terminal.cs b/Libs/BookGen.Gui/Terminal.cs index d1f2fd86..a7376126 100644 --- a/Libs/BookGen.Gui/Terminal.cs +++ b/Libs/BookGen.Gui/Terminal.cs @@ -86,4 +86,10 @@ public void Header(string title) AnsiConsole.WriteLine("".PadLeft(Console.WindowWidth, '-')); AnsiConsole.WriteLine(); } + + public bool Confirm(string message) + { + var prompt = new ConfirmationPrompt(message); + return prompt.Show(AnsiConsole.Console); + } } From ca515a3a1134d8b34ff839c890b770aa213a6225 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Fri, 1 Dec 2023 22:38:46 +0100 Subject: [PATCH 27/34] Title finder usability improvements --- Libs/BookGen.Cli/CommandRunner.cs | 3 +-- Libs/BookGen.DomainServices/MarkdownUtils.cs | 4 ++-- Libs/BookGen.DomainServices/TocUtils.cs | 2 +- Libs/BookGen.Interfaces/FsPath.cs | 5 +---- Prog/BookGen/GeneratorSteps/CreatePages.cs | 2 +- Prog/BookGen/GeneratorSteps/Epub/CreateEpubPages.cs | 2 +- Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs | 2 +- Test/BookGen.Tests/UT_MarkdownUtils.cs | 2 +- 8 files changed, 9 insertions(+), 13 deletions(-) diff --git a/Libs/BookGen.Cli/CommandRunner.cs b/Libs/BookGen.Cli/CommandRunner.cs index c73bb067..fc281b0f 100644 --- a/Libs/BookGen.Cli/CommandRunner.cs +++ b/Libs/BookGen.Cli/CommandRunner.cs @@ -48,8 +48,7 @@ private static SupportedOs GetCurrentOs() var parameter = method ?.GetParameters() - .Where(p => p.ParameterType.IsAssignableTo(typeof(ArgumentsBase))) - .FirstOrDefault() + .FirstOrDefault(p => p.ParameterType.IsAssignableTo(typeof(ArgumentsBase))) ?.ParameterType; return parameter; diff --git a/Libs/BookGen.DomainServices/MarkdownUtils.cs b/Libs/BookGen.DomainServices/MarkdownUtils.cs index 693a9b26..311a3fce 100644 --- a/Libs/BookGen.DomainServices/MarkdownUtils.cs +++ b/Libs/BookGen.DomainServices/MarkdownUtils.cs @@ -66,7 +66,7 @@ private static void InsertChapter(ToC toc, ref string? currentchapter, ref List< /// /// markdown content /// Title of page - public static string GetDocumentTitle(string markDownContent, ILog log) + public static string GetDocumentTitle(string markDownContent, ILog log, FsPath fileName) { using (var reader = new StringReader(markDownContent)) { @@ -105,7 +105,7 @@ public static string GetDocumentTitle(string markDownContent, ILog log) } } - log.Warning("Found no document title :("); + log.Warning("Found no document title : {0}", fileName); return string.Empty; } } diff --git a/Libs/BookGen.DomainServices/TocUtils.cs b/Libs/BookGen.DomainServices/TocUtils.cs index 338cb990..34bc8593 100644 --- a/Libs/BookGen.DomainServices/TocUtils.cs +++ b/Libs/BookGen.DomainServices/TocUtils.cs @@ -12,7 +12,7 @@ public static IEnumerable GetLinks(FsPath directory, ILog log) foreach (var file in contents) { var content = file.ReadFile(log); - var title = MarkdownUtils.GetDocumentTitle(content, log); + var title = MarkdownUtils.GetDocumentTitle(content, log, file); yield return new Link(title, file.GetRelativePathRelativeTo(directory).ToString().Replace(@"\", "/")); } } diff --git a/Libs/BookGen.Interfaces/FsPath.cs b/Libs/BookGen.Interfaces/FsPath.cs index 32d02b2c..90ad3e35 100644 --- a/Libs/BookGen.Interfaces/FsPath.cs +++ b/Libs/BookGen.Interfaces/FsPath.cs @@ -68,10 +68,7 @@ public override string ToString() return _path; } - public static FsPath Empty - { - get { return new FsPath(); } - } + public static readonly FsPath Empty = new(); public bool IsConsole { diff --git a/Prog/BookGen/GeneratorSteps/CreatePages.cs b/Prog/BookGen/GeneratorSteps/CreatePages.cs index 3d0997d3..a1bd9fd7 100644 --- a/Prog/BookGen/GeneratorSteps/CreatePages.cs +++ b/Prog/BookGen/GeneratorSteps/CreatePages.cs @@ -40,7 +40,7 @@ public void RunStep(IReadonlyRuntimeSettings settings, ILog log) string? inputContent = input.ReadFile(log); - result.title = MarkdownUtils.GetDocumentTitle(inputContent, log); + result.title = MarkdownUtils.GetDocumentTitle(inputContent, log, input); if (string.IsNullOrEmpty(result.title)) { diff --git a/Prog/BookGen/GeneratorSteps/Epub/CreateEpubPages.cs b/Prog/BookGen/GeneratorSteps/Epub/CreateEpubPages.cs index cbb1aea6..79c8ea04 100644 --- a/Prog/BookGen/GeneratorSteps/Epub/CreateEpubPages.cs +++ b/Prog/BookGen/GeneratorSteps/Epub/CreateEpubPages.cs @@ -52,7 +52,7 @@ public void RunStep(IReadonlyRuntimeSettings settings, ILog log) string? inputContent = input.ReadFile(log); - Content.Title = MarkdownUtils.GetDocumentTitle(inputContent, log); + Content.Title = MarkdownUtils.GetDocumentTitle(inputContent, log, input); Content.Content = pipeline.RenderMarkdown(inputContent); tidyCache.Add(target, Template.Render()); diff --git a/Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs b/Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs index 03c2030a..ab418f49 100644 --- a/Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs +++ b/Prog/BookGen/GeneratorSteps/Wordpress/CreateWpPages.cs @@ -176,7 +176,7 @@ public void RunStep(IReadonlyRuntimeSettings settings, ILog log) string? raw = input.ReadFile(log); Content.Content = pipeline.RenderMarkdown(raw); - string? title = MarkdownUtils.GetDocumentTitle(raw, log); + string? title = MarkdownUtils.GetDocumentTitle(raw, log, input); string subpath = $"{host}{EncodeTitle(chapter)}/{EncodeTitle(title)}"; diff --git a/Test/BookGen.Tests/UT_MarkdownUtils.cs b/Test/BookGen.Tests/UT_MarkdownUtils.cs index 70e814c9..5c6f8156 100644 --- a/Test/BookGen.Tests/UT_MarkdownUtils.cs +++ b/Test/BookGen.Tests/UT_MarkdownUtils.cs @@ -13,7 +13,7 @@ public class UT_MarkdownUtils [TestCase("### C# Test", "C# Test")] public void EnsureThat_MarkdownUtils_GetTitleWorksCorrectly(string input, string expected) { - string result = MarkdownUtils.GetDocumentTitle(input, TestEnvironment.GetMockedLog()); + string result = MarkdownUtils.GetDocumentTitle(input, TestEnvironment.GetMockedLog(), FsPath.Empty); Assert.That(result, Is.EqualTo(expected)); } } From 09366fb639ffb616accc18558cf265cdd54fadcf Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sat, 2 Dec 2023 09:47:51 +0100 Subject: [PATCH 28/34] Core Api changes --- Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs | 2 +- Libs/BookGen.AssemblyDocumenter/XmlDocumenter.cs | 2 +- Libs/BookGen.DomainServices/FsUtils.cs | 11 +++++++++-- Libs/BookGen.DomainServices/MarkdownUtils.cs | 10 +++++----- 4 files changed, 16 insertions(+), 9 deletions(-) diff --git a/Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs b/Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs index 59f5efc3..b2048ce3 100644 --- a/Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs +++ b/Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs @@ -20,7 +20,7 @@ public static bool ValidateXml(FsPath xml, ILog log) { var schema = new XmlSchemaSet(); schema.Add(LoadXsd()); - using (System.IO.FileStream? stream = xml.OpenStream()) + using (FileStream? stream = xml.OpenStreamRead()) { using (var rd = XmlReader.Create(stream)) { diff --git a/Libs/BookGen.AssemblyDocumenter/XmlDocumenter.cs b/Libs/BookGen.AssemblyDocumenter/XmlDocumenter.cs index 816900dd..50266965 100644 --- a/Libs/BookGen.AssemblyDocumenter/XmlDocumenter.cs +++ b/Libs/BookGen.AssemblyDocumenter/XmlDocumenter.cs @@ -23,7 +23,7 @@ public sealed class XmlDocumenter : IConverter /// The assembly file public XmlDocumenter(FsPath xml, FsPath assembly) { - using (var stream = xml.OpenStream()) + using (var stream = xml.OpenStreamRead()) { Assembly loadedAssembly = Assembly.LoadFrom(assembly.ToString()); _converter = new Converter(XDocument.Load(stream), loadedAssembly); diff --git a/Libs/BookGen.DomainServices/FsUtils.cs b/Libs/BookGen.DomainServices/FsUtils.cs index c80cd787..6902570f 100644 --- a/Libs/BookGen.DomainServices/FsUtils.cs +++ b/Libs/BookGen.DomainServices/FsUtils.cs @@ -154,9 +154,16 @@ public static FileStream CreateStream(this FsPath target, ILog log) return File.Create(target.ToString()); } - public static FileStream OpenStream(this FsPath source) + public static StreamWriter CreateStreamWriter(this FsPath target, ILog log) { - return File.OpenRead(source.ToString()); + string? dir = Path.GetDirectoryName(target.ToString()) ?? string.Empty; + if (!Directory.Exists(dir)) + { + log.Detail("Creating directory: {0}", dir); + Directory.CreateDirectory(dir); + } + + return File.CreateText(target.ToString()); } public static bool CreateBackup(this FsPath source, ILog log) diff --git a/Libs/BookGen.DomainServices/MarkdownUtils.cs b/Libs/BookGen.DomainServices/MarkdownUtils.cs index 311a3fce..b1680640 100644 --- a/Libs/BookGen.DomainServices/MarkdownUtils.cs +++ b/Libs/BookGen.DomainServices/MarkdownUtils.cs @@ -79,27 +79,27 @@ public static string GetDocumentTitle(string markDownContent, ILog log, FsPath f } else if (line.StartsWith("## ")) { - log.Warning("Found 2nd level title as the document title: {0}", line); + log.Warning("Found 2nd level title as the document title: {0}, File: {1}", line, fileName); return line[3..]; } else if (line.StartsWith("### ")) { - log.Warning("Found 3rd level title as the document title: {0}", line); + log.Warning("Found 3rd level title as the document title: {0}, File: {1}", line, fileName); return line[4..]; } else if (line.StartsWith("#### ")) { - log.Warning("Found 4th level title as the document title: {0}", line); + log.Warning("Found 4th level title as the document title: {0}, File: {1}", line, fileName); return line[5..]; } else if (line.StartsWith("##### ")) { - log.Warning("Found 5th level title as the document title: {0}", line); + log.Warning("Found 5th level title as the document title: {0}, File: {1}", line, fileName); return line[6..]; } else if (line.StartsWith("###### ")) { - log.Warning("Found 6th level title as the document title: {0}", line); + log.Warning("Found 6th level title as the document title: {0}, File: {1}", line, fileName); return line[7..]; } } From 0bf407d4886019ed251d1c3c61a68987fb86bb95 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sat, 2 Dec 2023 09:56:21 +0100 Subject: [PATCH 29/34] Initial version of Toc Command --- Commands.md | 18 ++++++ .../XmlDocValidator.cs | 2 +- Libs/BookGen.DomainServices/FsUtils.cs | 10 ++-- Libs/BookGen.DomainServices/TocUtils.cs | 5 ++ Prog/BookGen/Commands/TocCommand.cs | 58 ++++++++++++++++--- 5 files changed, 80 insertions(+), 13 deletions(-) diff --git a/Commands.md b/Commands.md index 194ba029..a0608a46 100644 --- a/Commands.md +++ b/Commands.md @@ -437,6 +437,24 @@ Arguments: Without arguments, performs terminal profile install. +# Toc + +Scans the folder and the configuration for markdown conent files +and writes out the missing Table of content entries to a file, +so the Table of conents can be easily updated. + +`BookGen Toc {-v} {-d [directory]}` +`BookGen Toc {--verbose} {--dir [directory]}` + +Arguments: + +-d, --dir: + Optional argument. Specifies work directory. If not specified, then + the current directory will be used as working directory. + +-v, --verbose: + Optional argument, turns on detailed logging. Usefull for locating issues + # Version Print the current program and config API version diff --git a/Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs b/Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs index b2048ce3..df4ce1cf 100644 --- a/Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs +++ b/Libs/BookGen.AssemblyDocumenter/XmlDocValidator.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2021 Ruzsinszki Gábor +// (c) 2021-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- diff --git a/Libs/BookGen.DomainServices/FsUtils.cs b/Libs/BookGen.DomainServices/FsUtils.cs index 6902570f..bc016535 100644 --- a/Libs/BookGen.DomainServices/FsUtils.cs +++ b/Libs/BookGen.DomainServices/FsUtils.cs @@ -1,17 +1,17 @@ //----------------------------------------------------------------------------- -// (c) 2019-2021 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- -using BookGen.Api; -using BookGen.Interfaces; - -using System; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Unicode; using System.Xml.Serialization; + +using BookGen.Api; +using BookGen.Interfaces; + using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; diff --git a/Libs/BookGen.DomainServices/TocUtils.cs b/Libs/BookGen.DomainServices/TocUtils.cs index 34bc8593..618a8aaf 100644 --- a/Libs/BookGen.DomainServices/TocUtils.cs +++ b/Libs/BookGen.DomainServices/TocUtils.cs @@ -21,6 +21,11 @@ public static IEnumerable GetLinks(FsPath directory, ILog log) public static readonly IEqualityComparer LinkTitleComparer = new LinkByTitleComparer(); + public static string ToMarkdownLink(Link link) + { + return $"[{link.Text}]({link.Url})"; + } + private class LinkByTitleComparer : IEqualityComparer { public bool Equals(Link? x, Link? y) diff --git a/Prog/BookGen/Commands/TocCommand.cs b/Prog/BookGen/Commands/TocCommand.cs index 57d02422..7250a437 100644 --- a/Prog/BookGen/Commands/TocCommand.cs +++ b/Prog/BookGen/Commands/TocCommand.cs @@ -1,4 +1,9 @@ -using BookGen.CommandArguments; +//----------------------------------------------------------------------------- +// (c) 2023 Ruzsinszki Gábor +// This code is licensed under MIT license (see LICENSE for details) +//----------------------------------------------------------------------------- + +using BookGen.CommandArguments; using BookGen.Infrastructure; using BookGen.ProjectHandling; @@ -21,18 +26,57 @@ public override int Execute(BookGenArgumentBase arguments, string[] context) _log.EnableVerboseLogingIfRequested(arguments); ProjectLoader loader = new(arguments.Directory, _log, _programInfo); + bool hasToc = true; + if (!loader.LoadProject()) { - return Constants.GeneralError; + hasToc = false; + _log.Warning("Bookgen project load failed, defaulting to file based search"); } - var files = TocUtils.GetLinks(new FsPath(arguments.Directory), _log); + var filePath = new FsPath(arguments.Directory, "toc_scratch.md"); + + IEnumerable files = TocUtils.GetLinks(new FsPath(arguments.Directory), _log); + + if (hasToc) + { + HashSet tocLinks = new HashSet(loader.Toc, TocUtils.LinkTargetComparer); + HashSet fileLinks = new HashSet(files, TocUtils.LinkTargetComparer); + + IEnumerable byTarget = fileLinks + .Except(tocLinks, TocUtils.LinkTargetComparer) + .OrderBy(l => l.Url); + + IEnumerable byTitle = fileLinks + .Except(tocLinks, TocUtils.LinkTitleComparer) + .OrderBy(l => l.Url); - HashSet tocLinks = new HashSet(loader.Toc, TocUtils.LinkTargetComparer); - HashSet fileLinks = new HashSet(files, TocUtils.LinkTargetComparer); + using (var stream = filePath.CreateStreamWriter(_log)) + { + _log.Info("Writing toc Info to: {0}", filePath); + WriteItems(stream, byTarget, "Not found in toc:"); + WriteItems(stream, byTitle, "Found, but with differtent title"); + } + } + else + { + using (var stream = filePath.CreateStreamWriter(_log)) + { + _log.Info("Writing toc Info to: {0}", filePath); + WriteItems(stream, files, "Not found in toc:"); + } + } - var items = fileLinks.Except(tocLinks, TocUtils.LinkTargetComparer).ToArray(); + return Constants.Succes; + } - return Constants.GeneralError; + private static void WriteItems(StreamWriter stream, IEnumerable items, string title) + { + stream.WriteLine(title); + stream.WriteLine(); + foreach (var item in items) + { + stream.WriteLine(TocUtils.ToMarkdownLink(item)); + } } } From 21b0cfe64122be83f36be28878428386ed626409 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sat, 2 Dec 2023 19:52:59 +0100 Subject: [PATCH 30/34] Work on ToC command --- Prog/BookGen/Commands/TocCommand.cs | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/Prog/BookGen/Commands/TocCommand.cs b/Prog/BookGen/Commands/TocCommand.cs index 7250a437..1ee64b18 100644 --- a/Prog/BookGen/Commands/TocCommand.cs +++ b/Prog/BookGen/Commands/TocCommand.cs @@ -54,8 +54,8 @@ public override int Execute(BookGenArgumentBase arguments, string[] context) using (var stream = filePath.CreateStreamWriter(_log)) { _log.Info("Writing toc Info to: {0}", filePath); - WriteItems(stream, byTarget, "Not found in toc:"); - WriteItems(stream, byTitle, "Found, but with differtent title"); + WriteItems(stream, byTarget, _log, "Not found in toc:"); + WriteItems(stream, byTitle, _log, "Found, but with differtent title"); } } else @@ -63,20 +63,26 @@ public override int Execute(BookGenArgumentBase arguments, string[] context) using (var stream = filePath.CreateStreamWriter(_log)) { _log.Info("Writing toc Info to: {0}", filePath); - WriteItems(stream, files, "Not found in toc:"); + WriteItems(stream, files, _log, "Not found in toc:"); } } return Constants.Succes; } - private static void WriteItems(StreamWriter stream, IEnumerable items, string title) + private static void WriteItems(StreamWriter stream, + IEnumerable items, + ILog _log, + string title) { + int count = 0; stream.WriteLine(title); stream.WriteLine(); foreach (var item in items) { stream.WriteLine(TocUtils.ToMarkdownLink(item)); + ++count; } + _log.Info("Wrote {0} items into file", count); } } From 1ba62d20ecfa559785f8530ce4bf9b0d538ea52b Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sat, 2 Dec 2023 19:54:02 +0100 Subject: [PATCH 31/34] NuGet update --- Test/BookGen.Tests/BookGen.Tests.csproj | 2 +- Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/Test/BookGen.Tests/BookGen.Tests.csproj b/Test/BookGen.Tests/BookGen.Tests.csproj index 7d3333b3..348bb3e4 100644 --- a/Test/BookGen.Tests/BookGen.Tests.csproj +++ b/Test/BookGen.Tests/BookGen.Tests.csproj @@ -17,7 +17,7 @@ all runtime; build; native; contentfiles; analyzers; buildtransitive - + all diff --git a/Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj b/Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj index 04b12f50..a3e47aad 100644 --- a/Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj +++ b/Test/BookGen.TestsSystem/BookGen.TestsSystem.csproj @@ -20,7 +20,7 @@ - + all From a356cb78821079652c15af867afa0c964e6d7724 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sun, 3 Dec 2023 10:35:37 +0100 Subject: [PATCH 32/34] Fixes bug in renderer --- Libs/BookGen.Gui/Renderer.cs | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/Libs/BookGen.Gui/Renderer.cs b/Libs/BookGen.Gui/Renderer.cs index f2f76b93..c1bc01bd 100644 --- a/Libs/BookGen.Gui/Renderer.cs +++ b/Libs/BookGen.Gui/Renderer.cs @@ -90,9 +90,8 @@ public Task Confirm(string message) private static int GetPageSize() { - var (_, top) = Console.GetCursorPosition(); - var height = Console.WindowHeight; - return height - top - 5; + int calculated = Console.WindowHeight - 5; + return calculated >= 3 ? calculated : 3; } public async Task SelectionMenu(string title, IEnumerable selectionItems) From feec6872a7cf8cab7b88e8a9e6c820ca9841f5c6 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sun, 3 Dec 2023 10:54:36 +0100 Subject: [PATCH 33/34] Fixes HTMLTidy running and encoding --- Libs/BookGen.DomainServices/ProcessRunner.cs | 3 +++ .../BookGen/GeneratorSteps/Print/CreateInlinedXhtml.cs | 10 +++++----- 2 files changed, 8 insertions(+), 5 deletions(-) diff --git a/Libs/BookGen.DomainServices/ProcessRunner.cs b/Libs/BookGen.DomainServices/ProcessRunner.cs index 14ab5768..6aaa97bb 100644 --- a/Libs/BookGen.DomainServices/ProcessRunner.cs +++ b/Libs/BookGen.DomainServices/ProcessRunner.cs @@ -4,6 +4,7 @@ //----------------------------------------------------------------------------- using System.Diagnostics; +using System.Text; using BookGen.Api; @@ -90,6 +91,8 @@ public static string GetCommandOutput(string program, string[] arguments, string process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardInput = true; process.StartInfo.CreateNoWindow = true; + process.StartInfo.StandardInputEncoding = Encoding.UTF8; + process.StartInfo.StandardOutputEncoding = Encoding.UTF8; Task timeout = Task.Delay(timeoutSeconds * 1000); process.Start(); diff --git a/Prog/BookGen/GeneratorSteps/Print/CreateInlinedXhtml.cs b/Prog/BookGen/GeneratorSteps/Print/CreateInlinedXhtml.cs index 3cf07cd2..986768c3 100644 --- a/Prog/BookGen/GeneratorSteps/Print/CreateInlinedXhtml.cs +++ b/Prog/BookGen/GeneratorSteps/Print/CreateInlinedXhtml.cs @@ -1,5 +1,5 @@ //----------------------------------------------------------------------------- -// (c) 2022 Ruzsinszki Gábor +// (c) 2022-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- @@ -9,20 +9,20 @@ internal sealed class CreateInlinedXhtml : IGeneratorStep { public void RunStep(IReadonlyRuntimeSettings settings, ILog log) { - log.Info("Reading generated html5..."); + log.Info("Creating XHTML version of render..."); + + log.Detail("Reading generated html5..."); FsPath source = settings.OutputDirectory.Combine("print.html"); string content = source.ReadFile(log); - log.Info("Inlining CSS..."); + log.Detail("Inlining CSS..."); var htmlTidy = new HtmlTidy(); var xhtml = htmlTidy.HtmlToXhtml(content); var result = PreMailer.Net.PreMailer.MoveCssInline(xhtml, removeStyleElements: true); - - log.Info("Writing target file..."); FsPath target = settings.OutputDirectory.Combine("print_xhtml.html"); target.WriteFile(log, result.Html); From 94714e6a174da77cd3b740c89a442435a161bd95 Mon Sep 17 00:00:00 2001 From: webmaster442 Date: Sun, 3 Dec 2023 12:21:33 +0100 Subject: [PATCH 34/34] Updates to initializer methods --- Libs/BookGen.Domain/CsProj/ItemGroup.cs | 16 ----- Libs/BookGen.Domain/CsProj/Project.cs | 20 ------- Libs/BookGen.Domain/CsProj/PropertyGroup.cs | 18 ------ Libs/BookGen.Domain/CsProj/Reference.cs | 18 ------ Libs/BookGen.Gui/MenuEnums/InitMenuAction.cs | 2 - .../Properties/Resources.Designer.cs | 9 --- Libs/BookGen.Gui/Properties/Resources.resx | 3 - .../BookGen.Resources.csproj | 5 -- Libs/BookGen.Resources/Etc/ScriptTemplate.cs | 16 ----- Libs/BookGen.Resources/KnownFile.cs | 1 - Libs/BookGen.Resources/KnownFileMap.cs | 1 - Prog/BookGen/Commands/InitCommand.cs | 4 +- Prog/BookGen/ConsoleUi/InitMenu.cs | 14 ++--- Prog/BookGen/InitializerMethods.cs | 59 ++++--------------- 14 files changed, 20 insertions(+), 166 deletions(-) delete mode 100644 Libs/BookGen.Domain/CsProj/ItemGroup.cs delete mode 100644 Libs/BookGen.Domain/CsProj/Project.cs delete mode 100644 Libs/BookGen.Domain/CsProj/PropertyGroup.cs delete mode 100644 Libs/BookGen.Domain/CsProj/Reference.cs delete mode 100644 Libs/BookGen.Resources/Etc/ScriptTemplate.cs diff --git a/Libs/BookGen.Domain/CsProj/ItemGroup.cs b/Libs/BookGen.Domain/CsProj/ItemGroup.cs deleted file mode 100644 index cf5703c8..00000000 --- a/Libs/BookGen.Domain/CsProj/ItemGroup.cs +++ /dev/null @@ -1,16 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.Xml.Serialization; - -namespace BookGen.Domain.CsProj -{ - [XmlRoot(ElementName = "ItemGroup")] - public record ItemGroup - { - [XmlElement(ElementName = "Reference")] - public Reference? Reference { get; set; } - } -} diff --git a/Libs/BookGen.Domain/CsProj/Project.cs b/Libs/BookGen.Domain/CsProj/Project.cs deleted file mode 100644 index 773c4099..00000000 --- a/Libs/BookGen.Domain/CsProj/Project.cs +++ /dev/null @@ -1,20 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.Xml.Serialization; - -namespace BookGen.Domain.CsProj -{ - [XmlRoot(ElementName = "Project")] - public record Project - { - [XmlElement(ElementName = "PropertyGroup")] - public PropertyGroup? PropertyGroup { get; set; } - [XmlElement(ElementName = "ItemGroup")] - public ItemGroup? ItemGroup { get; set; } - [XmlAttribute(AttributeName = "Sdk")] - public string? Sdk { get; set; } - } -} diff --git a/Libs/BookGen.Domain/CsProj/PropertyGroup.cs b/Libs/BookGen.Domain/CsProj/PropertyGroup.cs deleted file mode 100644 index b7778974..00000000 --- a/Libs/BookGen.Domain/CsProj/PropertyGroup.cs +++ /dev/null @@ -1,18 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.Xml.Serialization; - -namespace BookGen.Domain.CsProj -{ - [XmlRoot(ElementName = "PropertyGroup")] - public record PropertyGroup - { - [XmlElement(ElementName = "TargetFramework")] - public string? TargetFramework { get; set; } - [XmlElement(ElementName = "Nullable")] - public string? Nullable { get; set; } - } -} diff --git a/Libs/BookGen.Domain/CsProj/Reference.cs b/Libs/BookGen.Domain/CsProj/Reference.cs deleted file mode 100644 index 6952979a..00000000 --- a/Libs/BookGen.Domain/CsProj/Reference.cs +++ /dev/null @@ -1,18 +0,0 @@ -//----------------------------------------------------------------------------- -// (c) 2020 Ruzsinszki Gábor -// This code is licensed under MIT license (see LICENSE for details) -//----------------------------------------------------------------------------- - -using System.Xml.Serialization; - -namespace BookGen.Domain.CsProj -{ - [XmlRoot(ElementName = "Reference")] - public record Reference - { - [XmlElement(ElementName = "HintPath")] - public string? HintPath { get; set; } - [XmlAttribute(AttributeName = "Include")] - public string? Include { get; set; } - } -} diff --git a/Libs/BookGen.Gui/MenuEnums/InitMenuAction.cs b/Libs/BookGen.Gui/MenuEnums/InitMenuAction.cs index e2eb7776..63e0d423 100644 --- a/Libs/BookGen.Gui/MenuEnums/InitMenuAction.cs +++ b/Libs/BookGen.Gui/MenuEnums/InitMenuAction.cs @@ -11,8 +11,6 @@ public enum InitMenuAction CreateMdFiles, [Text("ID_CreateTemplates")] CreateTemplates, - [Text("ID_CreateScripts")] - CreateScripts, [Text("ID_CreateConfig")] CreateConfig, } diff --git a/Libs/BookGen.Gui/Properties/Resources.Designer.cs b/Libs/BookGen.Gui/Properties/Resources.Designer.cs index c5b6e0bc..3db503b7 100644 --- a/Libs/BookGen.Gui/Properties/Resources.Designer.cs +++ b/Libs/BookGen.Gui/Properties/Resources.Designer.cs @@ -159,15 +159,6 @@ internal static string ID_CreateMdFiles { } } - /// - /// Looks up a localized string similar to Create/overwrite script file and script project?. - /// - internal static string ID_CreateScripts { - get { - return ResourceManager.GetString("ID_CreateScripts", resourceCulture); - } - } - /// /// Looks up a localized string similar to Extract/overwrite templates for customization?. /// diff --git a/Libs/BookGen.Gui/Properties/Resources.resx b/Libs/BookGen.Gui/Properties/Resources.resx index 4417af61..9dd01794 100644 --- a/Libs/BookGen.Gui/Properties/Resources.resx +++ b/Libs/BookGen.Gui/Properties/Resources.resx @@ -150,9 +150,6 @@ Create summary.md/overwrite and index.md files? - - Create/overwrite script file and script project? - Extract/overwrite templates for customization? diff --git a/Libs/BookGen.Resources/BookGen.Resources.csproj b/Libs/BookGen.Resources/BookGen.Resources.csproj index 88344fe6..b38d8a3e 100644 --- a/Libs/BookGen.Resources/BookGen.Resources.csproj +++ b/Libs/BookGen.Resources/BookGen.Resources.csproj @@ -15,10 +15,6 @@ - - - - @@ -56,7 +52,6 @@ - diff --git a/Libs/BookGen.Resources/Etc/ScriptTemplate.cs b/Libs/BookGen.Resources/Etc/ScriptTemplate.cs deleted file mode 100644 index a4c3b7f6..00000000 --- a/Libs/BookGen.Resources/Etc/ScriptTemplate.cs +++ /dev/null @@ -1,16 +0,0 @@ -using BookGen.Api; -using System.Collections.Generic; - -namespace Script -{ - public class Script1 : IScript - { - public string InvokeName => "Script1"; - - public string ScriptMain(IScriptHost host, IReadOnlyDictionary arguments) - { - host.Log.Detail("Executing Script1..."); - return string.Empty; - } - } -} diff --git a/Libs/BookGen.Resources/KnownFile.cs b/Libs/BookGen.Resources/KnownFile.cs index cd0a9b9f..c1df9d78 100644 --- a/Libs/BookGen.Resources/KnownFile.cs +++ b/Libs/BookGen.Resources/KnownFile.cs @@ -22,7 +22,6 @@ public enum KnownFile PrismCss, PrismJs, PrismPrintCss, - ScriptTemplateCs, SearchformHtml, SinglePageCss, SummaryMd, diff --git a/Libs/BookGen.Resources/KnownFileMap.cs b/Libs/BookGen.Resources/KnownFileMap.cs index 752f02be..437fa79e 100644 --- a/Libs/BookGen.Resources/KnownFileMap.cs +++ b/Libs/BookGen.Resources/KnownFileMap.cs @@ -36,7 +36,6 @@ internal static class KnownFileMap //etc { KnownFile.IndexMd, "/Etc/index.md" }, - { KnownFile.ScriptTemplateCs, "/Etc/ScriptTemplate.cs" }, { KnownFile.SummaryMd, "/Etc/summary.md" }, //Png diff --git a/Prog/BookGen/Commands/InitCommand.cs b/Prog/BookGen/Commands/InitCommand.cs index e6521474..609af476 100644 --- a/Prog/BookGen/Commands/InitCommand.cs +++ b/Prog/BookGen/Commands/InitCommand.cs @@ -24,9 +24,9 @@ public InitCommand(ILog log, ProgramInfo programInfo) public override async Task Execute(BookGenArgumentBase arguments, string[] context) { - _log.LogLevel = arguments.Verbose ? Api.LogLevel.Detail : Api.LogLevel.Info; - + _log.EnableVerboseLogingIfRequested(arguments); _log.CheckLockFileExistsAndExitWhenNeeded(arguments.Directory); + _initMenu = new InitMenu(_log, new FsPath(arguments.Directory), _programInfo); await _initMenu.Run(); return Constants.Succes; diff --git a/Prog/BookGen/ConsoleUi/InitMenu.cs b/Prog/BookGen/ConsoleUi/InitMenu.cs index 0dd1b244..aacd93b4 100644 --- a/Prog/BookGen/ConsoleUi/InitMenu.cs +++ b/Prog/BookGen/ConsoleUi/InitMenu.cs @@ -1,4 +1,9 @@ -using BookGen.Gui; +//----------------------------------------------------------------------------- +// (c) 2023 Ruzsinszki Gábor +// This code is licensed under MIT license (see LICENSE for details) +//----------------------------------------------------------------------------- + +using BookGen.Gui; using BookGen.Gui.MenuEnums; namespace BookGen.ConsoleUi; @@ -34,7 +39,6 @@ private void Init(ISet options, InitConfigFormat configFormat, R bool createConfig = options.Contains(InitMenuAction.CreateConfig); bool createMdFiles = options.Contains(InitMenuAction.CreateMdFiles); bool createTemplates = options.Contains(InitMenuAction.CreateTemplates); - bool createScripts = options.Contains(InitMenuAction.CreateScripts); if (createMdFiles) { @@ -46,11 +50,6 @@ private void Init(ISet options, InitConfigFormat configFormat, R renderer.PrintText("Extracting templates..."); InitializerMethods.ExtractTemplates(_log, _workDir); } - if (createScripts) - { - renderer.PrintText("Creating Script project..."); - InitializerMethods.CreateScriptProject(_log, _workDir, _programInfo.ProgramDirectory); - } if (createConfig) { renderer.PrintText("Creating and configuring config file..."); @@ -61,7 +60,6 @@ private void Init(ISet options, InitConfigFormat configFormat, R configInYaml, createMdFiles, createTemplates, - createScripts, _programInfo.ConfigVersion); } } diff --git a/Prog/BookGen/InitializerMethods.cs b/Prog/BookGen/InitializerMethods.cs index 7f2c6c72..38c168fc 100644 --- a/Prog/BookGen/InitializerMethods.cs +++ b/Prog/BookGen/InitializerMethods.cs @@ -1,46 +1,42 @@ //----------------------------------------------------------------------------- -// (c) 2019-2022 Ruzsinszki Gábor +// (c) 2019-2023 Ruzsinszki Gábor // This code is licensed under MIT license (see LICENSE for details) //----------------------------------------------------------------------------- using BookGen.Domain.Configuration; -using BookGen.Domain.CsProj; -using BookGen.Framework; using BookGen.Resources; namespace BookGen; internal static class InitializerMethods { - private const string EpubTemplateLocation = "Templates\\TemplateEpub.html"; - private const string PrintTemplateLocation = "Templates\\TemplatePrint.html"; - private const string WebTemplate = "Templates\\TemplateWeb.html"; - private const string ScriptProject = "Scripts\\ScriptProject.csproj"; + private const string EpubTemplateLocation = ".bookgen\\Templates\\TemplateEpub.html"; + private const string PrintTemplateLocation = ".bookgen\\Templates\\TemplatePrint.html"; + private const string WebTemplate = ".bookgen\\Templates\\TemplateWeb.html"; internal static void CreateConfig(ILog log, FsPath workDir, bool configInYaml, bool createMdFiles, bool createTemplates, - bool createScripts, int configVersion) { - Config createdConfig = MakeConfigStructure(createMdFiles, createTemplates, createScripts, configVersion); + Config createdConfig = MakeConfigStructure(createMdFiles, createTemplates, configVersion); if (configInYaml) { - FsPath? file = workDir.Combine("bookgen.yml"); + FsPath? file = workDir.Combine(".bookgen\\bookgen.yml"); file.SerializeYaml(createdConfig, log); } else { - FsPath? file = workDir.Combine("bookgen.json"); + FsPath? file = workDir.Combine(".bookgen\\bookgen.json"); file.SerializeJson(createdConfig, log, true); } } - private static Config MakeConfigStructure(bool createdmdFiles, bool extractedTemplate, bool createdScript, int configVersion) + private static Config MakeConfigStructure(bool createdmdFiles, bool extractedTemplate, int configVersion) { var configuration = Config.CreateDefault(configVersion); @@ -50,11 +46,6 @@ private static Config MakeConfigStructure(bool createdmdFiles, bool extractedTem configuration.TOCFile = "summary.md"; } - if (createdScript) - { - configuration.ScriptsDirectory = "Scripts"; - } - if (extractedTemplate) { configuration.TargetEpub.TemplateFile = EpubTemplateLocation; @@ -64,12 +55,12 @@ private static Config MakeConfigStructure(bool createdmdFiles, bool extractedTem { new Asset { - Source = "Templates\\Assets\\prism.css", + Source = ".bookgen\\Templates\\Assets\\prism.css", Target = "Assets\\prism.css" }, new Asset { - Source = "Templates\\Assets\\prism.js", + Source = ".bookgen\\Templates\\Assets\\prism.js", Target = "Assets\\prism.js" } }; @@ -87,36 +78,10 @@ public static void DoCreateMdFiles(ILog log, FsPath workdir) ResourceHandler.ExtractKnownFile(KnownFile.SummaryMd, workdir.ToString(), log); } - public static void CreateScriptProject(ILog log, FsPath workdir, string ApiReferencePath) - { - log.Info("Creating scripts project..."); - var p = new Project - { - Sdk = "Microsoft.NET.Sdk", - PropertyGroup = new PropertyGroup - { - Nullable = "enable", - TargetFramework = "netstandard2.1" - }, - ItemGroup = new ItemGroup - { - Reference = new Reference - { - Include = "BookGen.Api", - HintPath = Path.Combine(ApiReferencePath, "BookGen.Api.dll") - } - } - }; - FsPath csProj = workdir.Combine(ScriptProject); - csProj.SerializeXml(p, log); - - ResourceHandler.ExtractKnownFile(KnownFile.ScriptTemplateCs, workdir.Combine("Scripts").ToString(), log); - } - public static void ExtractTemplates(ILog log, FsPath workdir) { - string? templatedir = workdir.Combine("Templates").ToString(); - string? assetsdir = workdir.Combine("Templates\\Assets").ToString(); + string? templatedir = workdir.Combine(".bookgen\\Templates").ToString(); + string? assetsdir = workdir.Combine(".bookgen\\Templates\\Assets").ToString(); ResourceHandler.ExtractKnownFile(KnownFile.TemplateEpubHtml, templatedir, log); ResourceHandler.ExtractKnownFile(KnownFile.TemplatePrintHtml, templatedir, log);