From 5702d4f9b8405a4a03b00c3904ef8c32125b854e Mon Sep 17 00:00:00 2001 From: "D. Moonfire" Date: Tue, 5 Mar 2024 23:15:03 -0600 Subject: [PATCH] chore: switching to mfgames-project-setup-flake + reformat --- .editorconfig | 234 ++--- .gitignore | 3 +- CODE-OF-CONDUCT.md | 30 +- CODE_OF_CONDUCT.md | 133 +++ DCO.md | 33 + MfGames.sln.DotSettings | 3 +- docs/index.md | 4 +- examples/NitrideCopyFiles/CopyFilesModule.cs | 25 +- .../NitrideCopyFiles/CopyFilesPipeline.cs | 171 ++-- examples/NitrideCopyFiles/CopyFilesProgram.cs | 66 +- .../NitridePipelinesModule.cs | 24 +- .../NitridePipelinesProgram.cs | 33 +- .../Pipelines/DelayPipeline1.cs | 48 +- .../Pipelines/InputPipeline1.cs | 56 +- .../Pipelines/InputPipeline2.cs | 60 +- .../Pipelines/OutputPipeline1.cs | 49 +- .../Pipelines/OutputPipeline2.cs | 48 +- examples/SampleTool/Commands/ConfigCommand.cs | 107 +- examples/SampleTool/Commands/CrashCommand.cs | 50 +- examples/SampleTool/Commands/LogCommand.cs | 135 ++- .../SampleTool/Commands/SpectreCommand.cs | 108 +- examples/SampleTool/Commands/TableCommand.cs | 72 +- examples/SampleTool/Program.cs | 30 +- examples/SampleTool/SampleToolModule.cs | 66 +- flake.lock | 771 ++++++-------- flake.nix | 66 +- nix/common/configs.nix | 262 ----- nix/common/shells.nix | 45 - src/MfGames.Crypto/ByteStringFormat.cs | 24 +- .../Extensions/CryptoByteArrayExtensions.cs | 109 +- .../Extensions/CryptoStringExtensions.cs | 91 +- src/MfGames.Crypto/Hashes/HashType.cs | 32 +- .../Hashes/HashTypeExtensions.cs | 44 +- src/MfGames.Gallium/Entity.cs | 896 ++++++++--------- src/MfGames.Gallium/JoinEntityExtensions.cs | 39 +- .../SelectComponentExtensions.cs | 73 +- .../SelectComponentOrDefaultExtensions.cs | 75 +- src/MfGames.Gallium/SelectEntityExtensions.cs | 525 +++++----- .../SelectManyEntityExtensions.cs | 256 ++--- .../SplitEntityEnumerations.cs | 20 +- src/MfGames.Gallium/SplitEntityExtensions.cs | 509 +++++----- src/MfGames.Gallium/WhereEntityExtensions.cs | 68 +- .../WhereEntityHasExtensions.cs | 40 +- .../WhereEntityNotHasExtensions.cs | 42 +- .../Extensions/AssemblyExtensions.cs | 38 +- .../Extensions/CryptoFileInfoExtensions.cs | 64 +- .../Extensions/DirectoryInfoExtensions.cs | 279 +++--- .../Extensions/FileInfoExtensions.cs | 79 +- src/MfGames.IO/Extensions/TypeExtensions.cs | 36 +- src/MfGames.Locking/NestableReadLock.cs | 64 +- .../NestableUpgradableReadLock.cs | 61 +- src/MfGames.Locking/NestableWriteLock.cs | 58 +- src/MfGames.Locking/ReadLock.cs | 30 +- src/MfGames.Locking/UpgradableLock.cs | 36 +- src/MfGames.Locking/WriteLock.cs | 36 +- .../Extensions/GemtextPipeTableExtension.cs | 83 +- .../Extensions/GemtextPipeTableOptions.cs | 19 +- .../Extensions/GemtextSmartyPantsExtension.cs | 66 +- .../Extensions/HtmlAsCodeBlocks.cs | 23 +- .../IncreaseHeaderDepthsAfterFirst.cs | 34 +- .../Extensions/SetBlockLinkHandling.cs | 84 +- .../Extensions/SetInlineFormatting.cs | 57 +- .../MarkdownGemtext.cs | 109 +- .../Renderers/BlockLinkHandling.cs | 44 +- .../Renderers/EndLinkInlineFormatting.cs | 20 +- .../Gemtext/Blocks/CodeBlockRenderer.cs | 46 +- .../Gemtext/Blocks/CustomContainerRenderer.cs | 20 +- .../Gemtext/Blocks/HeadingRenderer.cs | 76 +- .../Gemtext/Blocks/HtmlBlockRenderer.cs | 38 +- .../Renderers/Gemtext/Blocks/ListRenderer.cs | 38 +- .../Blocks/MarkdownDocumentRenderer.cs | 26 +- .../Gemtext/Blocks/ParagraphRenderer.cs | 54 +- .../Gemtext/Blocks/QuoteBlockRenderer.cs | 16 +- .../Renderers/Gemtext/Blocks/TableRenderer.cs | 201 ++-- .../Gemtext/Blocks/ThematicBreakRenderer.cs | 15 +- .../Gemtext/GemtextObjectRenderer.cs | 6 +- .../Gemtext/Inlines/CodeInlineRenderer.cs | 30 +- .../Inlines/DelimiterInlineRenderer.cs | 15 +- .../Gemtext/Inlines/EmphasisInlineRenderer.cs | 32 +- .../Inlines/GemtextSmartyPantRenderer.cs | 45 +- .../Inlines/HtmlEntityInlineRenderer.cs | 13 +- .../Inlines/LineBreakInlineRenderer.cs | 37 +- .../Gemtext/Inlines/LinkInlineRenderer.cs | 186 ++-- .../Gemtext/Inlines/LiteralInlineRenderer.cs | 46 +- .../Renderers/Gemtext/MarkdigExtensions.cs | 42 +- .../Renderers/GemtextRenderer.cs | 292 +++--- .../Renderers/HtmlBlockFormatting.cs | 18 +- .../Renderers/InlineFormatting.cs | 20 +- src/MfGames.Markdown/Extensions/WikiLink.cs | 8 +- .../Extensions/WikiLinkExtension.cs | 53 +- .../Extensions/WikiLinkInlineParser.cs | 165 ++- .../Extensions/WikiLinkOptions.cs | 40 +- src/MfGames.Markdown/README.md | 10 +- .../CreateCalendarValidator.cs | 15 +- .../CreateCalender.cs | 139 ++- src/MfGames.Nitride.Calendar/IsCalendar.cs | 4 +- .../NitrideCalendarBuilderExtensions.cs | 27 +- .../NitrideCalendarModule.cs | 15 +- src/MfGames.Nitride.Exec/ExecOperation.cs | 163 ++- .../Setup/NitrideExecBuilderExtensions.cs | 26 +- .../Setup/NitrideExecModule.cs | 14 +- .../Validators/ExecOperationValidator.cs | 17 +- src/MfGames.Nitride.Feeds/CreateAtomFeed.cs | 182 ++-- .../CreateAtomFeedValidator.cs | 15 +- src/MfGames.Nitride.Feeds/HasFeed.cs | 6 +- src/MfGames.Nitride.Feeds/IsFeed.cs | 4 +- .../Setup/NitrideFeedsBuilderExtensions.cs | 26 +- .../Setup/NitrideFeedsModule.cs | 15 +- .../Structure/AtomAuthor.cs | 48 +- .../Structure/AtomCategory.cs | 74 +- .../Structure/AtomEntry.cs | 192 ++-- .../Structure/AtomFeed.cs | 154 +-- .../Structure/AtomHelper.cs | 36 +- .../Structure/XmlConstants.cs | 18 +- src/MfGames.Nitride.Gemtext/IsGemtext.cs | 4 +- .../NitrideGemtextBuilderExtensions.cs | 26 +- .../NitrideGemtextModule.cs | 6 +- .../ClassAttributeReference.cs | 24 +- .../ClassAttributeSourceGeneratorBase.cs | 97 +- .../ClassAttributeSyntaxReceiverBase.cs | 164 +-- .../CodeAnalysisExtensions.cs | 275 +++-- src/MfGames.Nitride.Generators/MessageCode.cs | 2 +- .../SingletonComponentSourceGenerator.cs | 139 +-- .../SingletonComponentSyntaxReceiver.cs | 9 +- .../WithPropertiesSourceGenerator.cs | 162 +-- .../WithPropertiesSyntaxReceiver.cs | 8 +- .../ApplyStyleTemplate.cs | 85 +- .../ApplyStyleTemplateValidator.cs | 15 +- .../FileSystemHandlebarsTemplateLoader.cs | 36 +- .../Configuration/ForEachHandlebarsBlock.cs | 150 ++- .../Configuration/HandlebarsBlockBase.cs | 35 +- .../Configuration/IHandlebarsLoader.cs | 10 +- .../HandlebarsTemplateCache.cs | 88 +- .../HasHandlebarsTemplate.cs | 2 +- .../IdentifyHandlebarsFromComponent.cs | 39 +- ...dentifyHandlebarsFromComponentValidator.cs | 11 +- .../IdentifyHandlebarsFromContent.cs | 35 +- .../NitrideHandlebarsBuilderExtensions.cs | 62 +- .../NitrideHandlebarsModule.cs | 50 +- .../RenderContentTemplate.cs | 73 +- .../RenderContentTemplateValidator.cs | 12 +- .../ConvertHtmlEntitiesToUnicode.cs | 30 +- src/MfGames.Nitride.Html/IdentifyHtml.cs | 92 +- .../IdentifyHtmlFromPath.cs | 33 +- src/MfGames.Nitride.Html/IsHtml.cs | 4 +- .../NitrideHtmlBuilderExtensions.cs | 26 +- src/MfGames.Nitride.Html/NitrideHtmlModule.cs | 12 +- .../Validators/IdentifyHtmlValidator.cs | 9 +- .../Contents/FileEntryBinaryContent.cs | 31 +- .../Contents/FileEntryTextContent.cs | 37 +- src/MfGames.Nitride.IO/Contents/ReadFiles.cs | 158 +-- .../Contents/ReadFilesValidator.cs | 12 +- src/MfGames.Nitride.IO/Contents/WriteFiles.cs | 402 ++++---- .../Contents/WriteFilesValidator.cs | 18 +- .../Directories/ClearDirectory.cs | 130 ++- .../Directories/ClearDirectoryValidator.cs | 15 +- .../NitrideIOEnumerableEntityExtensions.cs | 132 +-- .../FileSystemOperationBase.cs | 20 +- .../FileSystemWatchablePipelineBase.cs | 123 ++- src/MfGames.Nitride.IO/IfFoundOutput.cs | 16 +- src/MfGames.Nitride.IO/Paths/AddPathPrefix.cs | 56 +- .../Paths/AddPathPrefixValidator.cs | 9 +- .../Paths/ChangePathExtension.cs | 52 +- .../Paths/ChangePathExtensionValidator.cs | 12 +- .../Paths/DirectChildEntityList.cs | 14 +- .../Paths/DirectChildPathScanner.cs | 52 +- .../Paths/LinkDirectChildren.cs | 59 +- .../Paths/MoveToIndexPath.cs | 124 ++- .../Paths/MoveToIndexPathValidator.cs | 9 +- .../Paths/RemovePathPrefix.cs | 66 +- .../Paths/RemovePathPrefixValidator.cs | 9 +- src/MfGames.Nitride.IO/Paths/ReplacePath.cs | 64 +- .../Paths/ReplacePathValidator.cs | 9 +- .../Paths/UPathExtensions.cs | 55 +- src/MfGames.Nitride.IO/README.md | 6 +- .../Setup/DefaultRootDirectoryHandling.cs | 28 +- .../Setup/DirectoryService.cs | 186 ++-- .../Setup/NitrideIOBuilderExtensions.cs | 75 +- .../Setup/NitrideIOConfiguration.cs | 29 +- .../Setup/NitrideIOModule.cs | 34 +- .../Setup/RootDirectoryCommandLineOption.cs | 51 +- src/MfGames.Nitride.Json/IsJson.cs | 4 +- .../NitrideJsonBuilderExtensions.cs | 26 +- .../NitrideJsonEntityExtensions.cs | 113 +-- src/MfGames.Nitride.Json/NitrideJsonModule.cs | 12 +- .../ConvertMarkdownToBase.cs | 80 +- .../ConvertMarkdownToGemtext.cs | 62 +- .../ConvertMarkdownToHtml.cs | 66 +- .../IdentifyMarkdown.cs | 92 +- .../IdentifyMarkdownFromPath.cs | 33 +- src/MfGames.Nitride.Markdown/IsMarkdown.cs | 4 +- .../MakeSingleLinkListItems.cs | 145 ++- .../NitrideMarkdownBuilderExtensions.cs | 26 +- .../NitrideMarkdownModule.cs | 12 +- .../ConvertMarkdownToBaseValidator.cs | 12 +- .../Validators/IdentifyMarkdownValidator.cs | 9 +- src/MfGames.Nitride.Slugs/ISlugConverter.cs | 12 +- .../NitrideSlugsBuilderExtensions.cs | 46 +- .../NitrideSlugsModule.cs | 4 +- .../SimpleSlugConverter.cs | 133 ++- .../UnicodeNormalizingSlugConverter.cs | 63 +- .../NitrideSpectreConsoleModule.cs | 159 ++- .../Observers/ProgressRemainingColumn.cs | 40 +- .../Observers/SpectreDisplayMode.cs | 26 +- .../Observers/StatusPipelineObserver.cs | 391 ++++---- .../NitrideSpectreConsoleConfiguration.cs | 20 +- .../Setup/StatusPipelineCommandLineOption.cs | 49 +- .../ApplySchedules.cs | 124 ++- .../ISchedule.cs | 34 +- .../IndexedPathRegexSchedule.cs | 66 +- .../IndexedSchedule.cs | 103 +- .../PathRegexScheduleBase.cs | 163 ++- .../PeriodicPathRegexSchedule.cs | 113 +-- .../README.md | 114 +-- ...trideTemporalSchedulesBuilderExtensions.cs | 37 +- .../Setup/NitrideTemporalSchedulesModule.cs | 15 +- .../SimplePathSchedule.cs | 55 +- .../TimeSpanHelper.cs | 42 +- .../Validators/ApplySchedulesValidator.cs | 12 +- src/MfGames.Nitride.Temporal/CanExpire.cs | 4 +- .../CreateDateIndexes.cs | 254 +++-- src/MfGames.Nitride.Temporal/DateIndex.cs | 59 +- .../FilterOutExpiredInstant.cs | 58 +- .../FilterOutFutureInstant.cs | 35 +- .../SetInstantFromComponent.cs | 138 ++- .../SetInstantFromPath.cs | 83 +- .../Setup/DatePipelineCommandOption.cs | 77 +- .../Setup/ExpiresPipelineCommandOption.cs | 98 +- .../Setup/NitrideTemporalBuilderExtensions.cs | 121 +-- .../Setup/NitrideTemporalConfiguration.cs | 95 +- .../Setup/NitrideTemporalModule.cs | 25 +- src/MfGames.Nitride.Temporal/TimeService.cs | 193 ++-- .../Validators/CreateDateIndexesValidator.cs | 15 +- .../FilterOutExpiredInstantValidator.cs | 12 +- .../FilterOutFutureInstantValidator.cs | 12 +- .../SetInstantFromComponentValidator.cs | 13 +- .../Validators/SetInstantFromPathValidator.cs | 9 +- src/MfGames.Nitride.Yaml/HasYamlModel.cs | 2 +- src/MfGames.Nitride.Yaml/IsYaml.cs | 4 +- .../NitrideYamlBuilderExtensions.cs | 26 +- .../NitrideYamlEntityExtensions.cs | 118 ++- src/MfGames.Nitride.Yaml/NitrideYamlModule.cs | 15 +- src/MfGames.Nitride.Yaml/ParseYamlHeader.cs | 291 +++--- .../ParseYamlHeaderErrorHandling.cs | 16 +- src/MfGames.Nitride/AsyncOperationBase.cs | 9 +- src/MfGames.Nitride/Commands/BuildCommand.cs | 99 +- .../Commands/IPipelineCommandOption.cs | 18 +- src/MfGames.Nitride/Commands/WatchCommand.cs | 173 ++-- .../Contents/ByteArrayBinaryContent.cs | 22 +- .../Contents/CryptoContentExtensions.cs | 122 ++- .../Contents/EntityBinaryContentExtensions.cs | 66 +- .../Contents/EntityContentExtensions.cs | 83 +- .../Contents/EntityTextContentExtensions.cs | 101 +- .../Contents/FileBinaryContent.cs | 50 +- .../Contents/FileTextContent.cs | 55 +- .../Contents/IBinaryContent.cs | 16 +- .../Contents/IBinaryContentConvertable.cs | 10 +- src/MfGames.Nitride/Contents/IContent.cs | 4 +- src/MfGames.Nitride/Contents/ITextContent.cs | 16 +- .../Contents/ITextContentConvertable.cs | 10 +- .../Contents/StringTextContent.cs | 32 +- .../Contents/TextContentExtensions.cs | 66 +- .../Entities/CreateOrUpdateIndex.cs | 162 ++- .../Entities/CreateOrUpdateIndexValidator.cs | 18 +- src/MfGames.Nitride/Entities/EntityScanner.cs | 226 +++-- .../Entities/EntityScannerValidator.cs | 9 +- .../Entities/EntitySequence.cs | 30 +- .../Entities/LinkEntitySequence.cs | 82 +- .../Entities/LinkEntitySequenceValidator.cs | 12 +- src/MfGames.Nitride/ExpressionHelper.cs | 90 +- .../Generators/SingletonComponentAttribute.cs | 4 +- .../Generators/WithPropertiesAttribute.cs | 4 +- src/MfGames.Nitride/IAsyncOperation.cs | 19 +- src/MfGames.Nitride/IOperation.cs | 19 +- src/MfGames.Nitride/IOperationBuilder.cs | 4 +- src/MfGames.Nitride/IResolvingOperation.cs | 4 +- src/MfGames.Nitride/NitrideBuilder.cs | 237 +++-- src/MfGames.Nitride/NitrideModule.cs | 159 ++- .../NitrideModuleExtensions.cs | 39 +- .../NitrideOperationExtensions.cs | 64 +- src/MfGames.Nitride/OperationBase.cs | 9 +- src/MfGames.Nitride/Pipelines/IPipeline.cs | 33 +- .../Pipelines/IWatchablePipeline.cs | 12 +- .../Pipelines/Observers/IPipelineObserver.cs | 36 +- .../Observers/LoggingPipelineObserver.cs | 213 ++-- .../Observers/PipelineObserverManager.cs | 216 ++-- src/MfGames.Nitride/Pipelines/PipelineBase.cs | 69 +- .../Pipelines/PipelineManager.cs | 276 +++--- .../Pipelines/PipelineRunner.cs | 836 ++++++++-------- .../Pipelines/PipelineRunnerStale.cs | 16 +- .../Pipelines/PipelineRunnerState.cs | 64 +- .../Pipelines/PipelineRunnerTrigger.cs | 16 +- .../Pipelines/WatchablePipelineBase.cs | 4 +- src/MfGames.Nitride/ROADMAP.md | 10 +- .../Setup/LogPipelineCommandLineOption.cs | 36 +- .../Setup/NitrideConfiguration.cs | 12 +- .../ExpressionSpectreConsoleSink.cs | 938 +++++++++--------- .../ExpressionSpectreConsoleSinkExtensions.cs | 73 +- src/MfGames.TestSetup/TestBase.cs | 51 +- src/MfGames.TestSetup/TestContext.cs | 80 +- .../TableFormatType.cs | 48 +- .../TableToolService.cs | 863 ++++++++-------- .../ToolBuilderTablesModule.cs | 13 +- .../Config/ConfigToolService.cs | 251 +++-- .../Config/ConfigToolServiceExtensions.cs | 46 +- .../Extensions/ParseResultExtensions.cs | 34 +- .../Extensions/StringCliExtensions.cs | 219 ++-- src/MfGames.ToolBuilder/GlobalOptionHelper.cs | 50 +- src/MfGames.ToolBuilder/ITopCommand.cs | 4 +- .../Logging/LogContextFormat.cs | 24 +- .../Logging/LoggingToolService.cs | 317 +++--- src/MfGames.ToolBuilder/ToolBox.cs | 60 +- src/MfGames.ToolBuilder/ToolBoxBuilder.cs | 342 ++++--- src/MfGames.ToolBuilder/ToolBuilderModule.cs | 19 +- src/MfGames.ToolBuilder/ToolException.cs | 82 +- .../CryptoStringExtensionsTests.cs | 111 +-- tests/MfGames.Gallium.Tests/EntityTests.cs | 381 ++++--- .../EnumerableEntityTests.cs | 360 ++++--- .../MfGames.Gallium.Tests/GalliumTestsBase.cs | 7 +- .../MfGames.Gallium.Tests/ITestComponent3.cs | 4 +- tests/MfGames.Gallium.Tests/TestComponent1.cs | 4 +- tests/MfGames.Gallium.Tests/TestComponent2.cs | 4 +- .../MfGames.Gallium.Tests/TestComponent3a.cs | 4 +- .../MfGames.Gallium.Tests/TestComponent3b.cs | 4 +- .../AssemblyExtensionsTests.cs | 30 +- tests/MfGames.IO.Tests/CryptoFileInfoTests.cs | 50 +- tests/MfGames.IO.Tests/GitRootTests.cs | 18 +- tests/MfGames.Locking.Tests/LockAction.cs | 6 +- tests/MfGames.Locking.Tests/LockTests.cs | 355 ++++--- .../CodeInlineTests.cs | 47 +- .../CustomContainerTests.cs | 50 +- .../HeaderTests.cs | 147 ++- .../ImageLinkTests.cs | 32 +- .../IncreaseHeaderDepthsAfterFirstTests.cs | 134 +-- .../LinkTests.cs | 80 +- .../ListTests.cs | 24 +- .../ParagraphLinkHandlingTests.cs | 281 +++--- .../PlainTextTests.cs | 81 +- .../PythonInspired/BaseUrlPythonTests.cs | 32 +- .../PythonInspired/CodeBlockPythonTests.cs | 122 ++- .../PythonInspired/ListPythonTests.cs | 60 +- .../PythonInspired/PlainTextPythonTests.cs | 152 ++- .../PythonInspired/StripHtmlPythonTests.cs | 148 ++- .../QuoteTests.cs | 44 +- .../TableTests.cs | 178 ++-- .../WikiLinkTest.cs | 60 +- tests/MfGames.Markdown.Tests/WikiLinkTest.cs | 277 +++--- .../ExecOperationTests.cs | 116 +-- .../NitrideExecTestBase.cs | 7 +- .../NitrideExecTestContext.cs | 13 +- .../NitrideCopyFilesTests.cs | 118 +-- .../NitrideIOTestBase.cs | 7 +- .../NitrideIOTestContext.cs | 20 +- .../Paths/AddPathPrefixTest.cs | 60 +- .../Paths/DirectChildPathScannerTests.cs | 98 +- .../Paths/GetEntityByPathTests.cs | 174 ++-- .../Paths/LinkDirectChildrenTests.cs | 118 +-- .../Paths/MoveToIndexPathsTest.cs | 126 +-- .../Paths/RemovePathPrefixTest.cs | 64 +- .../Paths/WhereNotIgnoredTests.cs | 66 +- .../MfGames.Nitride.IO.Tests/ReadFilesTest.cs | 142 ++- .../WriteFilesTest.cs | 86 +- .../TextContentJsonTests.cs | 64 +- .../MakeSingleLinkListItemsTests.cs | 124 +-- .../MarkdownTestContext.cs | 20 +- .../UnicodeNormalizingSlugConverterTest.cs | 83 +- .../IndexedPathRegexScheduleTest.cs | 411 ++++---- .../PeriodicPathRegexScheduleTest.cs | 438 ++++---- .../TemporalSchedulesTestBase.cs | 10 +- .../TemporalSchedulesTestContext.cs | 15 +- .../CreateDateIndexesTests.cs | 473 ++++----- .../FilterOutFutureInstantTests.cs | 102 +- .../TemporalTestBase.cs | 7 +- .../TemporalTestContext.cs | 13 +- .../Entities/CreateOrUpdateIndexTests.cs | 367 +++---- .../Entities/LinkEntitySequenceTests.cs | 82 +- .../EntityContentTest.cs | 95 +- .../MfGames.Nitride.Tests/NitrideTestBase.cs | 7 +- .../NitrideTestContext.cs | 13 +- tests/MfGames.Nitride.Tests/TestHelper.cs | 61 +- .../ParseYamlHeaderTests.cs | 155 ++- .../TextContentYamlTests.cs | 64 +- .../SampleToolTests.cs | 137 ++- .../TableToolServiceTests.cs | 226 ++--- .../ToolBuilderTestContext.cs | 15 +- 385 files changed, 15399 insertions(+), 17472 deletions(-) create mode 100644 CODE_OF_CONDUCT.md create mode 100644 DCO.md delete mode 100644 nix/common/configs.nix delete mode 100644 nix/common/shells.nix diff --git a/.editorconfig b/.editorconfig index 51b994c..b8193cc 100644 --- a/.editorconfig +++ b/.editorconfig @@ -1,121 +1,123 @@ -root=true +root = true +["*"] +charset = "utf-8" +csharp_new_line_before_members_in_object_initializers = false +csharp_preferred_modifier_order = "public, override, protected, internal, file, new, virtual, abstract, private, sealed, readonly, static, extern, unsafe, volatile, async, required:suggestion" +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = false +csharp_space_after_cast = false +csharp_style_var_elsewhere = "false:hint" +csharp_style_var_for_built_in_types = "false:hint" +csharp_style_var_when_type_is_apparent = "true:hint" +curly_bracket_next_line = true +dotnet_style_predefined_type_for_locals_parameters_members = "true:hint" +dotnet_style_predefined_type_for_member_access = "true:hint" +dotnet_style_qualification_for_event = "true:hint" +dotnet_style_qualification_for_field = "true:hint" +dotnet_style_qualification_for_method = "true:hint" +dotnet_style_qualification_for_property = "true:hint" +dotnet_style_require_accessibility_modifiers = "for_non_interface_members:hint" +end_of_line = "lf" +indent_brace_style = "K&R" +indent_size = 4 +indent_style = "space" +insert_final_newline = true +max_line_length = 80 +resharper_alignment_tab_fill_style = "optimal_fill" +resharper_apply_on_completion = true +resharper_blank_lines_after_control_transfer_statements = 1 +resharper_blank_lines_around_single_line_auto_property = 1 +resharper_blank_lines_around_single_line_property = 1 +resharper_blank_lines_before_block_statements = 1 +resharper_blank_lines_before_control_transfer_statements = 1 +resharper_blank_lines_before_single_line_comment = 1 +resharper_blank_lines_between_using_groups = 1 +resharper_braces_for_for = "required" +resharper_braces_for_foreach = "required" +resharper_braces_for_ifelse = "required" +resharper_braces_for_while = "required" +resharper_can_use_global_alias = false +resharper_check_namespace_highlighting = "none" +resharper_convert_to_auto_property_highlighting = "none" +resharper_csharp_blank_lines_around_single_line_field = 1 +resharper_csharp_blank_lines_around_single_line_invocable = 1 +resharper_csharp_empty_block_style = "together_same_line" +resharper_csharp_indent_style = "tab" +resharper_csharp_insert_final_newline = true +resharper_csharp_keep_blank_lines_in_code = 1 +resharper_csharp_keep_blank_lines_in_declarations = 1 +resharper_csharp_max_line_length = 100 +resharper_csharp_new_line_before_while = true +resharper_csharp_use_indent_invocation_rpar = true +resharper_csharp_wrap_extends_list_style = "chop_if_long" +resharper_csharp_wrap_parameters_style = "chop_if_long" +resharper_css_insert_final_newline = false +resharper_enforce_line_ending_style = true +resharper_html_insert_final_newline = false +resharper_indent_nested_fixed_stmt = true +resharper_js_indent_style = "spaces" +resharper_js_insert_final_newline = true +resharper_js_keep_blank_lines_in_code = 1 +resharper_js_stick_comment = false +resharper_js_use_indent_from_vs = false +resharper_js_wrap_before_binary_opsign = true +resharper_js_wrap_chained_method_calls = "chop_if_long" +resharper_keep_blank_lines_between_declarations = 1 +resharper_localizable_element_highlighting = "none" +resharper_min_blank_lines_after_imports = 1 +resharper_place_attribute_on_same_line = false +resharper_place_constructor_initializer_on_same_line = false +resharper_place_expr_property_on_single_line = true +resharper_place_simple_initializer_on_single_line = false +resharper_place_type_constraints_on_same_line = false +resharper_protobuf_insert_final_newline = false +resharper_qualified_using_at_nested_scope = true +resharper_redundant_comma_in_attribute_list_highlighting = "none" +resharper_redundant_comma_in_enum_declaration_highlighting = "none" +resharper_redundant_comma_in_initializer_highlighting = "none" +resharper_resx_insert_final_newline = false +resharper_space_within_single_line_array_initializer_braces = true +resharper_string_compare_to_is_culture_specific_highlighting = "none" +resharper_string_index_of_is_culture_specific_1_highlighting = "none" +resharper_use_indents_from_main_language_in_file = false +resharper_use_null_propagation_highlighting = "none" +resharper_use_object_or_collection_initializer_highlighting = "hint" +resharper_use_string_interpolation_highlighting = "hint" +resharper_vb_insert_final_newline = false +resharper_wrap_after_declaration_lpar = true +resharper_wrap_after_invocation_lpar = true +resharper_wrap_before_extends_colon = true +resharper_wrap_before_first_type_parameter_constraint = true +resharper_wrap_before_type_parameter_langle = true +resharper_xml_insert_final_newline = false +resharper_xmldoc_indent_child_elements = "ZeroIndent" +resharper_xmldoc_indent_text = "ZeroIndent" +resharper_xmldoc_insert_final_newline = false +tab_width = 4 +trim_trailing_whitespace = true -[*] -charset=utf-8 -csharp_new_line_before_members_in_object_initializers=false -csharp_preferred_modifier_order=public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion -csharp_preserve_single_line_blocks=true -csharp_preserve_single_line_statements=false -csharp_space_after_cast=false -csharp_style_var_elsewhere=false:hint -csharp_style_var_for_built_in_types=false:hint -csharp_style_var_when_type_is_apparent=true:hint -curly_bracket_next_line=true -dotnet_style_predefined_type_for_locals_parameters_members=true:hint -dotnet_style_predefined_type_for_member_access=true:hint -dotnet_style_qualification_for_event=true:hint -dotnet_style_qualification_for_field=true:hint -dotnet_style_qualification_for_method=true:hint -dotnet_style_qualification_for_property=true:hint -dotnet_style_require_accessibility_modifiers=for_non_interface_members:hint -end_of_line=lf -indent_brace_style=K&R -indent_size=4 -indent_style=space -insert_final_newline=true -max_line_length=80 -resharper_alignment_tab_fill_style=optimal_fill -resharper_apply_on_completion=true -resharper_blank_lines_after_control_transfer_statements=1 -resharper_blank_lines_around_single_line_auto_property=1 -resharper_blank_lines_around_single_line_property=1 -resharper_blank_lines_before_single_line_comment=1 -resharper_blank_lines_between_using_groups=1 -resharper_braces_for_for=required -resharper_braces_for_foreach=required -resharper_braces_for_ifelse=required -resharper_braces_for_while=required -resharper_can_use_global_alias=false -resharper_check_namespace_highlighting=none -resharper_convert_to_auto_property_highlighting=none -resharper_csharp_blank_lines_around_single_line_field=1 -resharper_csharp_blank_lines_around_single_line_invocable=1 -resharper_csharp_indent_style=tab -resharper_csharp_insert_final_newline=true -resharper_csharp_keep_blank_lines_in_code=1 -resharper_csharp_keep_blank_lines_in_declarations=1 -resharper_csharp_new_line_before_while=true -resharper_csharp_use_indent_from_vs=false -resharper_csharp_wrap_arguments_style=chop_if_long -resharper_csharp_wrap_extends_list_style=chop_if_long -resharper_csharp_wrap_parameters_style=chop_if_long -resharper_css_insert_final_newline=false -resharper_enforce_line_ending_style=true -resharper_html_insert_final_newline=false -resharper_indent_nested_fixed_stmt=true -resharper_js_indent_style=tab -resharper_js_insert_final_newline=true -resharper_js_keep_blank_lines_in_code=1 -resharper_js_stick_comment=false -resharper_js_use_indent_from_vs=false -resharper_js_wrap_before_binary_opsign=true -resharper_js_wrap_chained_method_calls=chop_if_long -resharper_keep_blank_lines_between_declarations=1 -resharper_localizable_element_highlighting=none -resharper_min_blank_lines_after_imports=1 -resharper_place_attribute_on_same_line=false -resharper_place_constructor_initializer_on_same_line=false -resharper_place_type_constraints_on_same_line=false -resharper_protobuf_insert_final_newline=false -resharper_qualified_using_at_nested_scope=true -resharper_redundant_comma_in_attribute_list_highlighting=none -resharper_redundant_comma_in_enum_declaration_highlighting=none -resharper_redundant_comma_in_initializer_highlighting=none -resharper_resx_insert_final_newline=false -resharper_space_within_single_line_array_initializer_braces=true -resharper_string_compare_to_is_culture_specific_highlighting=none -resharper_string_index_of_is_culture_specific_1_highlighting=none -resharper_use_indents_from_main_language_in_file=false -resharper_use_null_propagation_highlighting=none -resharper_use_object_or_collection_initializer_highlighting=hint -resharper_use_string_interpolation_highlighting=hint -resharper_vb_insert_final_newline=false -resharper_wrap_after_declaration_lpar=true -resharper_wrap_after_invocation_lpar=true -resharper_wrap_before_extends_colon=true -resharper_wrap_before_first_type_parameter_constraint=true -resharper_wrap_before_type_parameter_langle=true -resharper_xml_insert_final_newline=false -resharper_xmldoc_indent_child_elements=ZeroIndent -resharper_xmldoc_indent_text=ZeroIndent -resharper_xmldoc_insert_final_newline=false -tab_width=4 -trim_trailing_whitespace=true +["*.cs"] +indent_size = 4 +indent_style = "space" +tab_width = 4 -[*.md] -max_line_length=off -trim_trailing_whitespace=false +["*.md"] +max_line_length = "off" -[*.{appxmanifest,build,config,csproj,dbml,discomap,dtd,jsproj,lsproj,njsproj,nuspec,proj,props,resw,resx,StyleCop,targets,tasks,vbproj,xml,xsd}] -indent_size=2 -indent_style=space -tab_width=2 +["*.{appxmanifest,build,config,csproj,dbml,discomap,dtd,jsproj,lsproj,njsproj,nuspec,proj,props,resw,resx,StyleCop,targets,tasks,vbproj,xml,xsd}]"] +indent_size = 2 +indent_style = "space" +tab_width = 2 -[*.{diff,patch}] -end_of_line=unset -indent_size=unset -insert_final_newline=unset -trim_trailing_whitespace=unset +["package.json"] +indent_size = 2 +indent_style = "space" +tab_width = 2 -[package.json] -indent_size=2 -indent_style=space -tab_width=2 - -[{LICENSES/**,LICENSE}] -charset=unset -end_of_line=unset -indent_size=unset -indent_style=unset -insert_final_newline=unset -trim_trailing_whitespace=unset +["{LICENSES/**,LICENSE}"] +charset = "unset" +end_of_line = "unset" +indent_size = "unset" +indent_style = "unset" +insert_final_newline = "unset" +trim_trailing_whitespace = "unset" diff --git a/.gitignore b/.gitignore index 9420dd7..fd5caa0 100644 --- a/.gitignore +++ b/.gitignore @@ -23,6 +23,7 @@ TestResults/ tests/artifacts/ # nixago: ignore-linked-files +/.prettierrc.json /lefthook.yml /.conform.yaml -/treefmt.toml +/treefmt.toml \ No newline at end of file diff --git a/CODE-OF-CONDUCT.md b/CODE-OF-CONDUCT.md index 5aa66ee..88c4db8 100644 --- a/CODE-OF-CONDUCT.md +++ b/CODE-OF-CONDUCT.md @@ -17,24 +17,24 @@ diverse, inclusive, and healthy community. Examples of behavior that contributes to a positive environment for our community include: -- Demonstrating empathy and kindness toward other people -- Being respectful of differing opinions, viewpoints, and experiences -- Giving and gracefully accepting constructive feedback -- Accepting responsibility and apologizing to those affected by our mistakes, - and learning from the experience -- Focusing on what is best not just for us as individuals, but for the overall - community +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall + community Examples of unacceptable behavior include: -- The use of sexualized language or imagery, and sexual attention or advances of - any kind -- Trolling, insulting or derogatory comments, and personal or political attacks -- Public or private harassment -- Publishing others' private information, such as a physical or email address, - without their explicit permission -- Other conduct which could reasonably be considered inappropriate in a - professional setting +- The use of sexualized language or imagery, and sexual attention or advances of + any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, + without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting ## Enforcement Responsibilities diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..ffa5dc9 --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,133 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment for our +community include: + +- Demonstrating empathy and kindness toward other people +- Being respectful of differing opinions, viewpoints, and experiences +- Giving and gracefully accepting constructive feedback +- Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +- Focusing on what is best not just for us as individuals, but for the overall + community + +Examples of unacceptable behavior include: + +- The use of sexualized language or imagery, and sexual attention or advances of + any kind +- Trolling, insulting or derogatory comments, and personal or political attacks +- Public or private harassment +- Publishing others' private information, such as a physical or email address, + without their explicit permission +- Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +Community leaders are responsible for clarifying and enforcing our standards of +acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +Community leaders have the right and responsibility to remove, edit, or reject +comments, commits, code, wiki edits, issues, and other contributions that are +not aligned to this Code of Conduct, and will communicate reasons for moderation +decisions when appropriate. + +## Scope + +This Code of Conduct applies within all community spaces, and also applies when +an individual is officially representing the community in public spaces. +Examples of representing our community include using an official email address, +posting via an official social media account, or acting as an appointed +representative at an online or offline event. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the community leaders responsible for enforcement at +contact@mfgames.com. + +All complaints will be reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +Community leaders will follow these Community Impact Guidelines in determining +the consequences for any action they deem in violation of this Code of Conduct: + +### 1. Correction + +**Community Impact**: Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence**: A private, written warning from community leaders, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact**: A violation through a single incident or series of +actions. + +**Consequence**: A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact**: A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence**: A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact**: Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence**: A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by [Mozilla's code of conduct +enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/DCO.md b/DCO.md new file mode 100644 index 0000000..c3782f6 --- /dev/null +++ b/DCO.md @@ -0,0 +1,33 @@ +Developer Certificate of Origin +Version 1.1 + +Copyright (C) 2004, 2006 The Linux Foundation and its contributors. + +Everyone is permitted to copy and distribute verbatim copies of this +license document, but changing it is not allowed. + +Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +(a) The contribution was created in whole or in part by me and I +have the right to submit it under the open source license +indicated in the file; or + +(b) The contribution is based upon previous work that, to the best +of my knowledge, is covered under an appropriate open source +license and I have the right under that license to submit that +work with modifications, whether created in whole or in part +by me, under the same open source license (unless I am +permitted to submit under a different license), as indicated +in the file; or + +(c) The contribution was provided directly to me by some other +person who certified (a), (b) or (c) and I have not modified +it. + +(d) I understand and agree that this project and the contribution +are public and that a record of the contribution (including all +personal information I submit with it, including my sign-off) is +maintained indefinitely and may be redistributed consistent with +this project or the open source license(s) involved. diff --git a/MfGames.sln.DotSettings b/MfGames.sln.DotSettings index 3fc229d..102460c 100644 --- a/MfGames.sln.DotSettings +++ b/MfGames.sln.DotSettings @@ -539,7 +539,7 @@ II.2.12 <HandlesEvent /> UseVarWhenEvident UseVarWhenEvident True - + False @@ -663,6 +663,7 @@ II.2.12 <HandlesEvent /> LIVE_MONITOR DO_NOTHING LIVE_MONITOR + True True True True diff --git a/docs/index.md b/docs/index.md index 3976d88..3293fb3 100644 --- a/docs/index.md +++ b/docs/index.md @@ -2,5 +2,5 @@ ## Libraries -- [Gallium](./gallium/) -- [Nitride](./nitride/) +- [Gallium](./gallium/) +- [Nitride](./nitride/) diff --git a/examples/NitrideCopyFiles/CopyFilesModule.cs b/examples/NitrideCopyFiles/CopyFilesModule.cs index 1eefa30..2ddf202 100644 --- a/examples/NitrideCopyFiles/CopyFilesModule.cs +++ b/examples/NitrideCopyFiles/CopyFilesModule.cs @@ -4,17 +4,16 @@ namespace NitrideCopyFiles; public class CopyFilesModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - // This just registers all the non-static classes as singletons - // within the system. We use lifetimes in other components depending - // on how they are used, but in this case, we don't need it. - builder.RegisterAssemblyTypes( - this.GetType() - .Assembly) - .AsSelf() - .AsImplementedInterfaces() - .SingleInstance(); - } + /// + protected override void Load(ContainerBuilder builder) + { + // This just registers all the non-static classes as singletons + // within the system. We use lifetimes in other components depending + // on how they are used, but in this case, we don't need it. + builder + .RegisterAssemblyTypes(this.GetType().Assembly) + .AsSelf() + .AsImplementedInterfaces() + .SingleInstance(); + } } diff --git a/examples/NitrideCopyFiles/CopyFilesPipeline.cs b/examples/NitrideCopyFiles/CopyFilesPipeline.cs index 7cb06cf..448f2a9 100644 --- a/examples/NitrideCopyFiles/CopyFilesPipeline.cs +++ b/examples/NitrideCopyFiles/CopyFilesPipeline.cs @@ -1,7 +1,6 @@ using System.Collections.Generic; using System.Linq; using System.Threading; - using MfGames.Gallium; using MfGames.Nitride; using MfGames.Nitride.IO.Contents; @@ -16,97 +15,99 @@ namespace NitrideCopyFiles; /// public class CopyFilesPipeline : PipelineBase { - private readonly AddPathPrefix addPathPrefix; + private readonly AddPathPrefix addPathPrefix; - private readonly ClearDirectory clearDirectory; + private readonly ClearDirectory clearDirectory; - private readonly ReadFiles readFiles; + private readonly ReadFiles readFiles; - private readonly RemovePathPrefix removePathPrefix; + private readonly RemovePathPrefix removePathPrefix; - private readonly WriteFiles writeFiles; + private readonly WriteFiles writeFiles; - public CopyFilesPipeline( - ReadFiles readFiles, - ClearDirectory clearDirectory, - WriteFiles writeFiles, - RemovePathPrefix removePathPrefix, - AddPathPrefix addPathPrefix) - { - // While we can configure these during runtime, it seems cleaner to - // build them up during the constructor to call out the ones that - // require runtime data. - this.readFiles = readFiles.WithPattern("/input/**/*.txt"); - this.clearDirectory = clearDirectory.WithPath("/output"); - this.writeFiles = writeFiles; - this.removePathPrefix = removePathPrefix.WithPathPrefix("/input"); - this.addPathPrefix = addPathPrefix.WithPathPrefix("/output"); - } + public CopyFilesPipeline( + ReadFiles readFiles, + ClearDirectory clearDirectory, + WriteFiles writeFiles, + RemovePathPrefix removePathPrefix, + AddPathPrefix addPathPrefix + ) + { + // While we can configure these during runtime, it seems cleaner to + // build them up during the constructor to call out the ones that + // require runtime data. + this.readFiles = readFiles.WithPattern("/input/**/*.txt"); + this.clearDirectory = clearDirectory.WithPath("/output"); + this.writeFiles = writeFiles; + this.removePathPrefix = removePathPrefix.WithPathPrefix("/input"); + this.addPathPrefix = addPathPrefix.WithPathPrefix("/output"); + } - /// - public override IAsyncEnumerable RunAsync( - IEnumerable _, - CancellationToken cancellationToken = default) - { - // We don't care about the incoming entities which means we can - // ignore them and use the entities from the ReadFiles operation - // or we can union the entities pass in with the ReadFiles in case - // we want to merge them. - // - // This will read all the files of the given pattern and return them - // as an IEnumerable with the Zio components (UPath and - // binary contents) set. As a note, this doesn't actually read the - // file, just create a pointer to where the file could be read from. - // - // The path component will always be the relative path to the root, - // so `/input/a.txt` in this case since we only have one file. - IEnumerable entities = this.readFiles.Run(); + /// + public override IAsyncEnumerable RunAsync( + IEnumerable _, + CancellationToken cancellationToken = default + ) + { + // We don't care about the incoming entities which means we can + // ignore them and use the entities from the ReadFiles operation + // or we can union the entities pass in with the ReadFiles in case + // we want to merge them. + // + // This will read all the files of the given pattern and return them + // as an IEnumerable with the Zio components (UPath and + // binary contents) set. As a note, this doesn't actually read the + // file, just create a pointer to where the file could be read from. + // + // The path component will always be the relative path to the root, + // so `/input/a.txt` in this case since we only have one file. + IEnumerable entities = this.readFiles.Run(); - // Change the path. The path (Zio.UPath component) stays with the - // entity which is why there is no root directory in the writeFiles - // operation. Instead, we need to remove the `/input` and replace it - // with the `/output`. - // - // We can do that with a RemovePathPrefix followed by an - // AddPathPrefix, or use the more complex version of ChangePaths. - // In this case, we are going for easy to learn, so we'll do the - // pair. - // - // We are going to use the chain extension to make it easier to - // read. Coming out of this, we will have one entity that fulfills: - // - // entity.Get == "/output/a.txt" - entities = entities - .Run(this.removePathPrefix, cancellationToken) - .Run(this.addPathPrefix, cancellationToken); + // Change the path. The path (Zio.UPath component) stays with the + // entity which is why there is no root directory in the writeFiles + // operation. Instead, we need to remove the `/input` and replace it + // with the `/output`. + // + // We can do that with a RemovePathPrefix followed by an + // AddPathPrefix, or use the more complex version of ChangePaths. + // In this case, we are going for easy to learn, so we'll do the + // pair. + // + // We are going to use the chain extension to make it easier to + // read. Coming out of this, we will have one entity that fulfills: + // + // entity.Get == "/output/a.txt" + entities = entities + .Run(this.removePathPrefix, cancellationToken) + .Run(this.addPathPrefix, cancellationToken); - // Then we write out the files to the output. First we make sure we - // clear out the output. This operation performs an action when it - // it is first entered, but otherwise passes all the inputs through. - // - // We can call the clear directory in three ways. The first is to call - // the operation with: - // - // this.clearDirectory.Run() - // - // The other is to pass in the entities and get a new list of - // modified ones out. In this case, clear doesn't make any changes, - // but Entity objects are immutable, so we always work on the list - // returned. - // - // entities = this.clearDirectory.Run(entity) - // - // The third way is to use an extension on entities which lets us - // chain calls, ala Gulp's pipelines. The below code does this along - // with writing the files to the output. - entities = entities - .Run(this.clearDirectory, cancellationToken) - .Run(this.writeFiles, cancellationToken); + // Then we write out the files to the output. First we make sure we + // clear out the output. This operation performs an action when it + // it is first entered, but otherwise passes all the inputs through. + // + // We can call the clear directory in three ways. The first is to call + // the operation with: + // + // this.clearDirectory.Run() + // + // The other is to pass in the entities and get a new list of + // modified ones out. In this case, clear doesn't make any changes, + // but Entity objects are immutable, so we always work on the list + // returned. + // + // entities = this.clearDirectory.Run(entity) + // + // The third way is to use an extension on entities which lets us + // chain calls, ala Gulp's pipelines. The below code does this along + // with writing the files to the output. + entities = entities + .Run(this.clearDirectory, cancellationToken) + .Run(this.writeFiles, cancellationToken); - // If we are chaining this pipeline into another, we return the - // entities. Otherwise, we can just return an empty list. The - // pipeline is async, so it is wrapped in a task, but most - // operations are not (or are both). - return entities.ToAsyncEnumerable(); - } + // If we are chaining this pipeline into another, we return the + // entities. Otherwise, we can just return an empty list. The + // pipeline is async, so it is wrapped in a task, but most + // operations are not (or are both). + return entities.ToAsyncEnumerable(); + } } diff --git a/examples/NitrideCopyFiles/CopyFilesProgram.cs b/examples/NitrideCopyFiles/CopyFilesProgram.cs index ba00b3f..8da01a3 100644 --- a/examples/NitrideCopyFiles/CopyFilesProgram.cs +++ b/examples/NitrideCopyFiles/CopyFilesProgram.cs @@ -1,8 +1,6 @@ using System.IO; using System.Threading.Tasks; - using Autofac; - using MfGames.IO.Extensions; using MfGames.Nitride; using MfGames.Nitride.IO.Setup; @@ -15,41 +13,41 @@ namespace NitrideCopyFiles; /// public static class CopyFilesProgram { - public static async Task Main(string[] args) - { - // All of the builder methods are fluent in that they return the - // builder to allow them to be chained. However, for documentation - // purposes, we are going to split them apart to explain the details. - var builder = new NitrideBuilder(args, ConfigureNitride); + public static async Task Main(string[] args) + { + // All of the builder methods are fluent in that they return the + // builder to allow them to be chained. However, for documentation + // purposes, we are going to split them apart to explain the details. + var builder = new NitrideBuilder(args, ConfigureNitride); - // Filesystem access is provided by Zio, which allows for mutliple - // folders to be combined together into a single unified file - // system. At the moment, we set the "root" directory which will - // contains all the paths, both input and output. - // - // Like Serilog, we use a number of extension methods on the builder - // to inject functionality such as plugins and extensions. In this - // case, we only need the Nitride.IO module so we use the `UseIO` - // to inject the requisite modules and configure it. - DirectoryInfo rootDir = typeof(CopyFilesProgram) - .GetDirectory()! - .FindGitRoot()! - .GetDirectory("examples/NitrideCopyFiles"); + // Filesystem access is provided by Zio, which allows for mutliple + // folders to be combined together into a single unified file + // system. At the moment, we set the "root" directory which will + // contains all the paths, both input and output. + // + // Like Serilog, we use a number of extension methods on the builder + // to inject functionality such as plugins and extensions. In this + // case, we only need the Nitride.IO module so we use the `UseIO` + // to inject the requisite modules and configure it. + DirectoryInfo rootDir = typeof(CopyFilesProgram) + .GetDirectory()! + .FindGitRoot()! + .GetDirectory("examples/NitrideCopyFiles"); - builder.UseIO(rootDir); + builder.UseIO(rootDir); - // We use Autofac for the bulk of our registration handling. This - // was mainly because we are more comfortable with Autofac, but it - // also has a clean interface for handling some of the more esoteric - // problems we've encountered. - builder.ConfigureContainer(x => x.RegisterModule()); + // We use Autofac for the bulk of our registration handling. This + // was mainly because we are more comfortable with Autofac, but it + // also has a clean interface for handling some of the more esoteric + // problems we've encountered. + builder.ConfigureContainer(x => x.RegisterModule()); - // Finally, we build the site generator object and run it. - return await builder.RunAsync(); - } + // Finally, we build the site generator object and run it. + return await builder.RunAsync(); + } - private static void ConfigureNitride(NitrideConfiguration config) - { - config.AddLogPipelineCommandLineOption = true; - } + private static void ConfigureNitride(NitrideConfiguration config) + { + config.AddLogPipelineCommandLineOption = true; + } } diff --git a/examples/NitridePipelines/NitridePipelinesModule.cs b/examples/NitridePipelines/NitridePipelinesModule.cs index 21b6eb6..eb34e8e 100644 --- a/examples/NitridePipelines/NitridePipelinesModule.cs +++ b/examples/NitridePipelines/NitridePipelinesModule.cs @@ -4,16 +4,16 @@ namespace NitridePipelines; public class NitridePipelinesModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - // This just registers all the non-static classes as singletons - // within the system. We use lifetimes in other components depending - // on how they are used, but in this case, we don't need it. - builder - .RegisterAssemblyTypes(this.GetType().Assembly) - .AsSelf() - .AsImplementedInterfaces() - .SingleInstance(); - } + /// + protected override void Load(ContainerBuilder builder) + { + // This just registers all the non-static classes as singletons + // within the system. We use lifetimes in other components depending + // on how they are used, but in this case, we don't need it. + builder + .RegisterAssemblyTypes(this.GetType().Assembly) + .AsSelf() + .AsImplementedInterfaces() + .SingleInstance(); + } } diff --git a/examples/NitridePipelines/NitridePipelinesProgram.cs b/examples/NitridePipelines/NitridePipelinesProgram.cs index 14b28a5..f541823 100644 --- a/examples/NitridePipelines/NitridePipelinesProgram.cs +++ b/examples/NitridePipelines/NitridePipelinesProgram.cs @@ -1,8 +1,6 @@ using System.IO; using System.Threading.Tasks; - using Autofac; - using MfGames.IO.Extensions; using MfGames.Nitride; using MfGames.Nitride.IO.Setup; @@ -15,22 +13,21 @@ namespace NitridePipelines; /// public static class NitridePipelinesProgram { - public static async Task Main(string[] args) - { - DirectoryInfo rootDir = typeof(NitridePipelinesProgram) - .GetDirectory()! - .FindGitRoot()! - .GetDirectory("examples/NitridePipelines"); + public static async Task Main(string[] args) + { + DirectoryInfo rootDir = typeof(NitridePipelinesProgram) + .GetDirectory()! + .FindGitRoot()! + .GetDirectory("examples/NitridePipelines"); - return await new NitrideBuilder(args, ConfigureNitride) - .UseIO(rootDir) - .ConfigureContainer( - x => x.RegisterModule()) - .RunAsync(); - } + return await new NitrideBuilder(args, ConfigureNitride) + .UseIO(rootDir) + .ConfigureContainer(x => x.RegisterModule()) + .RunAsync(); + } - private static void ConfigureNitride(NitrideConfiguration config) - { - config.AddLogPipelineCommandLineOption = true; - } + private static void ConfigureNitride(NitrideConfiguration config) + { + config.AddLogPipelineCommandLineOption = true; + } } diff --git a/examples/NitridePipelines/Pipelines/DelayPipeline1.cs b/examples/NitridePipelines/Pipelines/DelayPipeline1.cs index 8a37fbc..e39a57e 100644 --- a/examples/NitridePipelines/Pipelines/DelayPipeline1.cs +++ b/examples/NitridePipelines/Pipelines/DelayPipeline1.cs @@ -2,46 +2,38 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; - using MfGames.Gallium; using MfGames.Nitride.Pipelines; - using Serilog; - using Zio; namespace NitridePipelines.Pipelines; public class DelayPipeline1 : PipelineBase { - private readonly ILogger logger; + private readonly ILogger logger; - public DelayPipeline1( - ILogger logger, - InputPipeline1 input1) - { - this.logger = logger.ForContext(); - this.AddDependency(input1); - } + public DelayPipeline1(ILogger logger, InputPipeline1 input1) + { + this.logger = logger.ForContext(); + this.AddDependency(input1); + } - /// - public override IAsyncEnumerable RunAsync( - IEnumerable entities, - CancellationToken cancellationToken = default) - { - entities = entities - .Select( - entity => - { - Task.Delay(1000, cancellationToken).Wait(cancellationToken); + /// + public override IAsyncEnumerable RunAsync( + IEnumerable entities, + CancellationToken cancellationToken = default + ) + { + entities = entities.Select(entity => + { + Task.Delay(1000, cancellationToken).Wait(cancellationToken); - this.logger.Information( - "Delayed {Value}", - entity.Get()); + this.logger.Information("Delayed {Value}", entity.Get()); - return entity; - }); + return entity; + }); - return entities.ToAsyncEnumerable(); - } + return entities.ToAsyncEnumerable(); + } } diff --git a/examples/NitridePipelines/Pipelines/InputPipeline1.cs b/examples/NitridePipelines/Pipelines/InputPipeline1.cs index ea4e8a9..d762641 100644 --- a/examples/NitridePipelines/Pipelines/InputPipeline1.cs +++ b/examples/NitridePipelines/Pipelines/InputPipeline1.cs @@ -2,53 +2,43 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; - using MfGames.Gallium; using MfGames.Nitride.IO; using MfGames.Nitride.IO.Contents; - using Serilog; - using Zio; namespace NitridePipelines.Pipelines; public class InputPipeline1 : FileSystemWatchablePipelineBase { - private readonly ReadFiles readFiles; + private readonly ReadFiles readFiles; - public InputPipeline1( - ILogger logger, - IFileSystem fileSystem, - ReadFiles readFiles) - : base(logger, fileSystem) - { - this.readFiles = readFiles - .WithPattern("/input/input1/*.txt"); - } + public InputPipeline1(ILogger logger, IFileSystem fileSystem, ReadFiles readFiles) + : base(logger, fileSystem) + { + this.readFiles = readFiles.WithPattern("/input/input1/*.txt"); + } - /// - protected override UPath WatchPath => "/input/input1"; + /// + protected override UPath WatchPath => "/input/input1"; - /// - public override IAsyncEnumerable RunAsync( - IEnumerable _, - CancellationToken cancellationToken = default) - { - IEnumerable entities = this.readFiles - .Run() - .Select( - entity => - { - Task.Delay(1000, cancellationToken).Wait(cancellationToken); + /// + public override IAsyncEnumerable RunAsync( + IEnumerable _, + CancellationToken cancellationToken = default + ) + { + IEnumerable entities = this.readFiles.Run() + .Select(entity => + { + Task.Delay(1000, cancellationToken).Wait(cancellationToken); - this.Logger.Information( - "Read {Value}", - entity.Get()); + this.Logger.Information("Read {Value}", entity.Get()); - return entity; - }); + return entity; + }); - return entities.ToAsyncEnumerable(); - } + return entities.ToAsyncEnumerable(); + } } diff --git a/examples/NitridePipelines/Pipelines/InputPipeline2.cs b/examples/NitridePipelines/Pipelines/InputPipeline2.cs index 80fe839..d7e5bd1 100644 --- a/examples/NitridePipelines/Pipelines/InputPipeline2.cs +++ b/examples/NitridePipelines/Pipelines/InputPipeline2.cs @@ -2,56 +2,46 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; - using MfGames.Gallium; using MfGames.Nitride.IO; using MfGames.Nitride.IO.Contents; - using Serilog; - using Zio; namespace NitridePipelines.Pipelines; public class InputPipeline2 : FileSystemWatchablePipelineBase { - private readonly ILogger logger; + private readonly ILogger logger; - private readonly ReadFiles readFiles; + private readonly ReadFiles readFiles; - public InputPipeline2( - ILogger logger, - IFileSystem fileSystem, - ReadFiles readFiles) - : base(logger, fileSystem) - { - this.logger = logger.ForContext(); - this.readFiles = readFiles - .WithPattern("/input/input2/*.txt"); - } + public InputPipeline2(ILogger logger, IFileSystem fileSystem, ReadFiles readFiles) + : base(logger, fileSystem) + { + this.logger = logger.ForContext(); + this.readFiles = readFiles.WithPattern("/input/input2/*.txt"); + } - /// - protected override UPath WatchPath => "/input/input2"; + /// + protected override UPath WatchPath => "/input/input2"; - /// - public override IAsyncEnumerable RunAsync( - IEnumerable _, - CancellationToken cancellationToken = default) - { - IEnumerable entities = this.readFiles - .Run() - .Select( - entity => - { - Task.Delay(1000, cancellationToken).Wait(cancellationToken); + /// + public override IAsyncEnumerable RunAsync( + IEnumerable _, + CancellationToken cancellationToken = default + ) + { + IEnumerable entities = this.readFiles.Run() + .Select(entity => + { + Task.Delay(1000, cancellationToken).Wait(cancellationToken); - this.logger.Information( - "Read {Value}", - entity.Get()); + this.logger.Information("Read {Value}", entity.Get()); - return entity; - }); + return entity; + }); - return entities.ToAsyncEnumerable(); - } + return entities.ToAsyncEnumerable(); + } } diff --git a/examples/NitridePipelines/Pipelines/OutputPipeline1.cs b/examples/NitridePipelines/Pipelines/OutputPipeline1.cs index ef485c8..1e55083 100644 --- a/examples/NitridePipelines/Pipelines/OutputPipeline1.cs +++ b/examples/NitridePipelines/Pipelines/OutputPipeline1.cs @@ -2,47 +2,38 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; - using MfGames.Gallium; using MfGames.Nitride.Pipelines; - using Serilog; - using Zio; namespace NitridePipelines.Pipelines; public class OutputPipeline1 : PipelineBase { - private readonly ILogger logger; + private readonly ILogger logger; - public OutputPipeline1( - ILogger logger, - DelayPipeline1 delay1, - InputPipeline2 input2) - { - this.logger = logger.ForContext(); - this.AddDependency(delay1, input2); - } + public OutputPipeline1(ILogger logger, DelayPipeline1 delay1, InputPipeline2 input2) + { + this.logger = logger.ForContext(); + this.AddDependency(delay1, input2); + } - /// - public override IAsyncEnumerable RunAsync( - IEnumerable entities, - CancellationToken cancellationToken = default) - { - entities = entities - .Select( - entity => - { - Task.Delay(1000, cancellationToken).Wait(cancellationToken); + /// + public override IAsyncEnumerable RunAsync( + IEnumerable entities, + CancellationToken cancellationToken = default + ) + { + entities = entities.Select(entity => + { + Task.Delay(1000, cancellationToken).Wait(cancellationToken); - this.logger.Information( - "Pretended to write {Value}", - entity.Get()); + this.logger.Information("Pretended to write {Value}", entity.Get()); - return entity; - }); + return entity; + }); - return entities.ToAsyncEnumerable(); - } + return entities.ToAsyncEnumerable(); + } } diff --git a/examples/NitridePipelines/Pipelines/OutputPipeline2.cs b/examples/NitridePipelines/Pipelines/OutputPipeline2.cs index e05863b..4974937 100644 --- a/examples/NitridePipelines/Pipelines/OutputPipeline2.cs +++ b/examples/NitridePipelines/Pipelines/OutputPipeline2.cs @@ -2,46 +2,38 @@ using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; - using MfGames.Gallium; using MfGames.Nitride.Pipelines; - using Serilog; - using Zio; namespace NitridePipelines.Pipelines; public class OutputPipeline2 : PipelineBase { - private readonly ILogger logger; + private readonly ILogger logger; - public OutputPipeline2( - ILogger logger, - InputPipeline2 input2) - { - this.logger = logger.ForContext(); - this.AddDependency(input2); - } + public OutputPipeline2(ILogger logger, InputPipeline2 input2) + { + this.logger = logger.ForContext(); + this.AddDependency(input2); + } - /// - public override IAsyncEnumerable RunAsync( - IEnumerable entities, - CancellationToken cancellationToken = default) - { - entities = entities - .Select( - entity => - { - Task.Delay(1000, cancellationToken).Wait(cancellationToken); + /// + public override IAsyncEnumerable RunAsync( + IEnumerable entities, + CancellationToken cancellationToken = default + ) + { + entities = entities.Select(entity => + { + Task.Delay(1000, cancellationToken).Wait(cancellationToken); - this.logger.Information( - "Pretended to write {Value}", - entity.Get()); + this.logger.Information("Pretended to write {Value}", entity.Get()); - return entity; - }); + return entity; + }); - return entities.ToAsyncEnumerable(); - } + return entities.ToAsyncEnumerable(); + } } diff --git a/examples/SampleTool/Commands/ConfigCommand.cs b/examples/SampleTool/Commands/ConfigCommand.cs index 9b729fa..c2e57ec 100644 --- a/examples/SampleTool/Commands/ConfigCommand.cs +++ b/examples/SampleTool/Commands/ConfigCommand.cs @@ -2,88 +2,77 @@ using System; using System.CommandLine; using System.CommandLine.Invocation; using System.Threading.Tasks; - using MfGames.ToolBuilder; using MfGames.ToolBuilder.Config; - using Microsoft.Extensions.Logging; - using Newtonsoft.Json; namespace SampleTool.Commands; public class ConfigCommand : Command, ICommandHandler, ITopCommand { - private readonly ILogger logger; + private readonly ILogger logger; - private readonly ConfigToolService service; + private readonly ConfigToolService service; - private readonly Option setOption; + private readonly Option setOption; - /// - public ConfigCommand( - ILoggerFactory loggerFactory, - ConfigToolService service) - : base( - "config", - "Sets and displays the configuration settings") - { - this.logger = loggerFactory.CreateLogger(); - this.service = service; - this.Handler = this; + /// + public ConfigCommand(ILoggerFactory loggerFactory, ConfigToolService service) + : base("config", "Sets and displays the configuration settings") + { + this.logger = loggerFactory.CreateLogger(); + this.service = service; + this.Handler = this; - this.setOption = new Option( - "--set", - "Sets the text value in the setting"); + this.setOption = new Option("--set", "Sets the text value in the setting"); - this.AddOption(this.setOption); - } + this.AddOption(this.setOption); + } - /// - public int Invoke(InvocationContext context) - { - return this.InvokeAsync(context).Result; - } + /// + public int Invoke(InvocationContext context) + { + return this.InvokeAsync(context).Result; + } - /// - public Task InvokeAsync(InvocationContext context) - { - // Get the settings and report that it was being created. - ConfigCommandSettings settings = - this.service.ReadDefaultConfigFile(); + /// + public Task InvokeAsync(InvocationContext context) + { + // Get the settings and report that it was being created. + ConfigCommandSettings settings = + this.service.ReadDefaultConfigFile(); - if (settings == null) - { - this.logger.LogInformation("Creating configuration file"); - settings = new ConfigCommandSettings(); - } + if (settings == null) + { + this.logger.LogInformation("Creating configuration file"); + settings = new ConfigCommandSettings(); + } - // If we have a set command, then provide it. - string value = context.ParseResult - .GetValueForOption(this.setOption); + // If we have a set command, then provide it. + string value = context.ParseResult.GetValueForOption(this.setOption); - if (value != null) - { - settings.Value = value; - } + if (value != null) + { + settings.Value = value; + } - // Increment the counter. - settings.TimesRead++; + // Increment the counter. + settings.TimesRead++; - // Report the values. - Console.WriteLine( - JsonConvert.SerializeObject(settings, Formatting.Indented)); + // Report the values. + Console.WriteLine(JsonConvert.SerializeObject(settings, Formatting.Indented)); - // Write out the settings. - this.service.WriteDefaultConfigFile(settings); + // Write out the settings. + this.service.WriteDefaultConfigFile(settings); - return Task.FromResult(0); - } + return Task.FromResult(0); + } - private class ConfigCommandSettings - { - public int TimesRead { get; set; } + private class ConfigCommandSettings + { + public int TimesRead { get; set; } - public string Value { get; set; } - } + public string Value { get; set; } + } } diff --git a/examples/SampleTool/Commands/CrashCommand.cs b/examples/SampleTool/Commands/CrashCommand.cs index 22a82a9..bdc37c0 100644 --- a/examples/SampleTool/Commands/CrashCommand.cs +++ b/examples/SampleTool/Commands/CrashCommand.cs @@ -2,42 +2,40 @@ using System; using System.CommandLine; using System.CommandLine.Invocation; using System.Threading.Tasks; - using MfGames.ToolBuilder; namespace SampleTool.Commands; public class CrashCommand : Command, ICommandHandler, ITopCommand { - private readonly Option messyOption; + private readonly Option messyOption; - /// - public CrashCommand() - : base("crash", "Crash the application with an exception") - { - this.Handler = this; - this.messyOption = new Option("--messy"); + /// + public CrashCommand() + : base("crash", "Crash the application with an exception") + { + this.Handler = this; + this.messyOption = new Option("--messy"); - this.AddOption(this.messyOption); - } + this.AddOption(this.messyOption); + } - /// - public int Invoke(InvocationContext context) - { - return this.InvokeAsync(context).Result; - } + /// + public int Invoke(InvocationContext context) + { + return this.InvokeAsync(context).Result; + } - /// - public Task InvokeAsync(InvocationContext context) - { - bool messy = context.ParseResult.GetValueForOption(this.messyOption); + /// + public Task InvokeAsync(InvocationContext context) + { + bool messy = context.ParseResult.GetValueForOption(this.messyOption); - if (messy) - { - throw new Exception( - "This command crashed messily as requested."); - } + if (messy) + { + throw new Exception("This command crashed messily as requested."); + } - throw new ToolException("This command crashed as requested."); - } + throw new ToolException("This command crashed as requested."); + } } diff --git a/examples/SampleTool/Commands/LogCommand.cs b/examples/SampleTool/Commands/LogCommand.cs index ed6e17a..df41d5c 100644 --- a/examples/SampleTool/Commands/LogCommand.cs +++ b/examples/SampleTool/Commands/LogCommand.cs @@ -1,97 +1,84 @@ using System.CommandLine; using System.CommandLine.Invocation; using System.Threading.Tasks; - using MfGames.ToolBuilder; - using Microsoft.Extensions.Logging; - using ILogger = Serilog.ILogger; namespace SampleTool.Commands; public class LogCommand : Command, ICommandHandler, ITopCommand { - private readonly ILogger extensionLogger; + private readonly ILogger extensionLogger; - private readonly ILogger serilogContextLogger; + private readonly ILogger serilogContextLogger; - private readonly ILogger serilogLogger; + private readonly ILogger serilogLogger; - /// - public LogCommand( - ILoggerFactory loggerFactory, - ILogger serilogLogger) - : base( - "log", - "Shows various logging messages using Serilog and Microsoft") - { - this.serilogLogger = serilogLogger; - this.serilogContextLogger = serilogLogger.ForContext(); - this.extensionLogger = loggerFactory.CreateLogger(); - this.Handler = this; - } + /// + public LogCommand(ILoggerFactory loggerFactory, ILogger serilogLogger) + : base("log", "Shows various logging messages using Serilog and Microsoft") + { + this.serilogLogger = serilogLogger; + this.serilogContextLogger = serilogLogger.ForContext(); + this.extensionLogger = loggerFactory.CreateLogger(); + this.Handler = this; + } - /// - public int Invoke(InvocationContext context) - { - return this.InvokeAsync(context).Result; - } + /// + public int Invoke(InvocationContext context) + { + return this.InvokeAsync(context).Result; + } - /// - public Task InvokeAsync(InvocationContext context) - { - // Show the serilog logging. - this.serilogLogger.Verbose("Serilog Verbose()"); - this.serilogLogger.Debug("Serilog Debug()"); - this.serilogLogger.Information("Serilog Information()"); - this.serilogLogger.Warning("Serilog Warning()"); - this.serilogLogger.Error("Serilog Error()"); - this.serilogLogger.Fatal("Serilog Fatal()"); + /// + public Task InvokeAsync(InvocationContext context) + { + // Show the serilog logging. + this.serilogLogger.Verbose("Serilog Verbose()"); + this.serilogLogger.Debug("Serilog Debug()"); + this.serilogLogger.Information("Serilog Information()"); + this.serilogLogger.Warning("Serilog Warning()"); + this.serilogLogger.Error("Serilog Error()"); + this.serilogLogger.Fatal("Serilog Fatal()"); - // Show serilog with context. - this.serilogContextLogger.Information( - "Serilog Information() with context"); + // Show serilog with context. + this.serilogContextLogger.Information("Serilog Information() with context"); - // Show the extension logging. - this.extensionLogger.LogTrace( - "System.Extension.Logging LogTrace"); - this.extensionLogger.LogDebug( - "System.Extension.Logging LogDebug"); - this.extensionLogger.LogInformation( - "System.Extension.Logging LogInformation"); - this.extensionLogger.LogWarning( - "System.Extension.Logging LogWarning"); - this.extensionLogger.LogError( - "System.Extension.Logging LogError"); - this.extensionLogger.LogCritical( - "System.Extension.Logging LogCritical"); + // Show the extension logging. + this.extensionLogger.LogTrace("System.Extension.Logging LogTrace"); + this.extensionLogger.LogDebug("System.Extension.Logging LogDebug"); + this.extensionLogger.LogInformation("System.Extension.Logging LogInformation"); + this.extensionLogger.LogWarning("System.Extension.Logging LogWarning"); + this.extensionLogger.LogError("System.Extension.Logging LogError"); + this.extensionLogger.LogCritical("System.Extension.Logging LogCritical"); - // Show Serilog working through logging extensions. - var hash = new - { - Number = 1, - String = "String", - Inner = new { Nested = true } - }; + // Show Serilog working through logging extensions. + var hash = new + { + Number = 1, + String = "String", + Inner = new { Nested = true } + }; - this.serilogLogger.Information( - "Serilog Contextual parameters {Name} and {Quotes:l}", - "extension logger", - "without quotes"); - this.serilogLogger.Information( - "Serilog Contextual nested object {@Nested}", - hash); + this.serilogLogger.Information( + "Serilog Contextual parameters {Name} and {Quotes:l}", + "extension logger", + "without quotes" + ); + this.serilogLogger.Information("Serilog Contextual nested object {@Nested}", hash); - this.extensionLogger.LogInformation( - "System.Extension.Logging parameters {Name} and {Quotes:l}", - "extension logger", - "without quotes"); - this.extensionLogger.LogInformation( - "System.Extension.Logging nested object {@Nested}", - hash); + this.extensionLogger.LogInformation( + "System.Extension.Logging parameters {Name} and {Quotes:l}", + "extension logger", + "without quotes" + ); + this.extensionLogger.LogInformation( + "System.Extension.Logging nested object {@Nested}", + hash + ); - // We're good. - return Task.FromResult(0); - } + // We're good. + return Task.FromResult(0); + } } diff --git a/examples/SampleTool/Commands/SpectreCommand.cs b/examples/SampleTool/Commands/SpectreCommand.cs index 5c24e55..577e239 100644 --- a/examples/SampleTool/Commands/SpectreCommand.cs +++ b/examples/SampleTool/Commands/SpectreCommand.cs @@ -11,81 +11,77 @@ using System.CommandLine; using System.CommandLine.Invocation; using System.Threading; using System.Threading.Tasks; - using MfGames.ToolBuilder; - using Microsoft.Extensions.Logging; - using Spectre.Console; namespace SampleTool.Commands; public class SpectreCommand : Command, ICommandHandler, ITopCommand { - private readonly ILogger logger; + private readonly ILogger logger; - /// - public SpectreCommand(ILoggerFactory loggerFactory) - : base("spectre", "Shows various SpectreConsole features") - { - this.logger = loggerFactory.CreateLogger(); - this.Handler = this; - } + /// + public SpectreCommand(ILoggerFactory loggerFactory) + : base("spectre", "Shows various SpectreConsole features") + { + this.logger = loggerFactory.CreateLogger(); + this.Handler = this; + } - /// - public int Invoke(InvocationContext context) - { - return this.InvokeAsync(context).Result; - } + /// + public int Invoke(InvocationContext context) + { + return this.InvokeAsync(context).Result; + } - /// - public async Task InvokeAsync(InvocationContext context) - { - // Display a message ahead of this. - this.logger.LogInformation("Before things happened."); + /// + public async Task InvokeAsync(InvocationContext context) + { + // Display a message ahead of this. + this.logger.LogInformation("Before things happened."); - // Show a progress bar. - CancellationToken cancellationToken = context.GetCancellationToken(); - DateTime last = DateTime.UtcNow; + // Show a progress bar. + CancellationToken cancellationToken = context.GetCancellationToken(); + DateTime last = DateTime.UtcNow; - await AnsiConsole.Progress() - .AutoClear(true) - .StartAsync( - async ctx => - { - ProgressTask task1 = ctx.AddTask("[green]Fast Task[/]"); - ProgressTask task2 = ctx.AddTask("[green]Slow Task[/]"); + await AnsiConsole + .Progress() + .AutoClear(true) + .StartAsync(async ctx => + { + ProgressTask task1 = ctx.AddTask("[green]Fast Task[/]"); + ProgressTask task2 = ctx.AddTask("[green]Slow Task[/]"); - while (!ctx.IsFinished) - { - // See if we're cancelled. - if (cancellationToken.IsCancellationRequested) - { - break; - } + while (!ctx.IsFinished) + { + // See if we're cancelled. + if (cancellationToken.IsCancellationRequested) + { + break; + } - // Simulate some work - await Task.Delay(25, cancellationToken); + // Simulate some work + await Task.Delay(25, cancellationToken); - if (DateTime.UtcNow - last - > TimeSpan.FromMilliseconds(500)) - { - this.logger.LogWarning("Working..."); - last = DateTime.UtcNow; - } + if (DateTime.UtcNow - last > TimeSpan.FromMilliseconds(500)) + { + this.logger.LogWarning("Working..."); + last = DateTime.UtcNow; + } - await Task.Delay(25, cancellationToken); + await Task.Delay(25, cancellationToken); - // Increment - task1.Increment(2.0); - task2.Increment(1.0); - } - }); + // Increment + task1.Increment(2.0); + task2.Increment(1.0); + } + }); - // Report we're done. - this.logger.LogInformation("Done"); + // Report we're done. + this.logger.LogInformation("Done"); - return 0; - } + return 0; + } } #endif diff --git a/examples/SampleTool/Commands/TableCommand.cs b/examples/SampleTool/Commands/TableCommand.cs index 4633905..961e481 100644 --- a/examples/SampleTool/Commands/TableCommand.cs +++ b/examples/SampleTool/Commands/TableCommand.cs @@ -3,7 +3,6 @@ using System.CommandLine; using System.CommandLine.Invocation; using System.Data; using System.Threading.Tasks; - using MfGames.ToolBuilder; using MfGames.ToolBuilder.Tables; @@ -11,49 +10,46 @@ namespace SampleTool.Commands; public class TableCommand : Command, ICommandHandler, ITopCommand { - private readonly DataTable table; + private readonly DataTable table; - private readonly TableToolService tableService; + private readonly TableToolService tableService; - /// - public TableCommand(TableToolService.Factory tableService) - : base("table", "Display a Markdown table") - { - // Create the table structure. - this.table = new DataTable(); - this.table.Columns.Add("DefaultString", typeof(string)); - this.table.Columns.Add("DefaultInt32", typeof(int)); - this.table.Columns.Add("HiddenString", typeof(string)); + /// + public TableCommand(TableToolService.Factory tableService) + : base("table", "Display a Markdown table") + { + // Create the table structure. + this.table = new DataTable(); + this.table.Columns.Add("DefaultString", typeof(string)); + this.table.Columns.Add("DefaultInt32", typeof(int)); + this.table.Columns.Add("HiddenString", typeof(string)); - // Create the table service for formatting and displaying results. - this.tableService = tableService( - this.table, - new List - { - "DefaultString", - "DefaultInt32", - }) - .Attach(this); + // Create the table service for formatting and displaying results. + this.tableService = tableService( + this.table, + new List { "DefaultString", "DefaultInt32", } + ) + .Attach(this); - // This class handles the command. - this.Handler = this; - } + // This class handles the command. + this.Handler = this; + } - /// - public int Invoke(InvocationContext context) - { - return this.InvokeAsync(context).Result; - } + /// + public int Invoke(InvocationContext context) + { + return this.InvokeAsync(context).Result; + } - /// - public Task InvokeAsync(InvocationContext context) - { - this.table.Rows.Add("Row 1", 1, "Hidden 1"); - this.table.Rows.Add("Row 2", 10, "Hidden 2"); - this.table.Rows.Add("Row 3", 100, "Hidden 3"); + /// + public Task InvokeAsync(InvocationContext context) + { + this.table.Rows.Add("Row 1", 1, "Hidden 1"); + this.table.Rows.Add("Row 2", 10, "Hidden 2"); + this.table.Rows.Add("Row 3", 100, "Hidden 3"); - this.tableService.Write(context); + this.tableService.Write(context); - return Task.FromResult(0); - } + return Task.FromResult(0); + } } diff --git a/examples/SampleTool/Program.cs b/examples/SampleTool/Program.cs index 77b4634..34fb7f4 100644 --- a/examples/SampleTool/Program.cs +++ b/examples/SampleTool/Program.cs @@ -1,7 +1,5 @@ using System.Threading.Tasks; - using Autofac; - using MfGames.ToolBuilder; using MfGames.ToolBuilder.Config; using MfGames.ToolBuilder.Tables; @@ -10,19 +8,19 @@ namespace SampleTool; public static class Program { - public static async Task Main(string[] args) - { - return await ToolBoxBuilder - .Create(args) - .UseUserConfiguration("mfgames-toolbuilder-sample") - .ConfigureContainer(ConfigureContainer) - .Build() - .RunAsync(); - } + public static async Task Main(string[] args) + { + return await ToolBoxBuilder + .Create(args) + .UseUserConfiguration("mfgames-toolbuilder-sample") + .ConfigureContainer(ConfigureContainer) + .Build() + .RunAsync(); + } - private static void ConfigureContainer(ContainerBuilder builder) - { - builder.RegisterModule(); - builder.RegisterModule(); - } + private static void ConfigureContainer(ContainerBuilder builder) + { + builder.RegisterModule(); + builder.RegisterModule(); + } } diff --git a/examples/SampleTool/SampleToolModule.cs b/examples/SampleTool/SampleToolModule.cs index 4a428fc..a80e9c2 100644 --- a/examples/SampleTool/SampleToolModule.cs +++ b/examples/SampleTool/SampleToolModule.cs @@ -2,9 +2,7 @@ using System; using System.Collections.Generic; using System.CommandLine; using System.Linq; - using Autofac; - using MfGames.ToolBuilder; namespace SampleTool; @@ -14,44 +12,38 @@ namespace SampleTool; /// public class SampleToolModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - builder - .RegisterAssemblyTypes(this.GetType().Assembly) - .AsSelf() - .AsImplementedInterfaces(); + /// + protected override void Load(ContainerBuilder builder) + { + builder.RegisterAssemblyTypes(this.GetType().Assembly).AsSelf().AsImplementedInterfaces(); - builder - .Register( - c => - { - // Create the top-level command. - var root = new RootCommand - { - Name = "sample-tool", - Description = - "A sample tool that demonstrates functionality", - }; + builder + .Register(c => + { + // Create the top-level command. + var root = new RootCommand + { + Name = "sample-tool", + Description = "A sample tool that demonstrates functionality", + }; - // Add in the top-level commands. - var commandList = c.Resolve>() - .Cast() - .ToList(); + // Add in the top-level commands. + var commandList = c.Resolve>().Cast().ToList(); - if (commandList.Count == 0) - { - throw new InvalidOperationException( - "Cannot create a tool without at least one command extending System.CommandLine.Command"); - } + if (commandList.Count == 0) + { + throw new InvalidOperationException( + "Cannot create a tool without at least one command extending System.CommandLine.Command" + ); + } - foreach (Command command in commandList) - { - root.AddCommand(command); - } + foreach (Command command in commandList) + { + root.AddCommand(command); + } - return root; - }) - .AsSelf(); - } + return root; + }) + .AsSelf(); + } } diff --git a/flake.lock b/flake.lock index 2df02ca..c91662a 100644 --- a/flake.lock +++ b/flake.lock @@ -1,136 +1,12 @@ { "nodes": { - "blank": { - "locked": { - "lastModified": 1625557891, - "narHash": "sha256-O8/MWsPBGhhyPoPLHZAuoZiiHo9q6FLlEeIDEXuj6T4=", - "owner": "divnix", - "repo": "blank", - "rev": "5a5d2684073d9f563072ed07c871d577a6c614a8", - "type": "github" - }, - "original": { - "owner": "divnix", - "repo": "blank", - "type": "github" - } - }, - "crane": { - "inputs": { - "flake-compat": "flake-compat", - "flake-utils": "flake-utils_2", - "nixpkgs": [ - "std", - "paisano-mdbook-preprocessor", - "nixpkgs" - ], - "rust-overlay": "rust-overlay" - }, - "locked": { - "lastModified": 1676162383, - "narHash": "sha256-krUCKdz7ebHlFYm/A7IbKDnj2ZmMMm3yIEQcooqm7+E=", - "owner": "ipetkov", - "repo": "crane", - "rev": "6fb400ec631b22ccdbc7090b38207f7fb5cfb5f2", - "type": "github" - }, - "original": { - "owner": "ipetkov", - "repo": "crane", - "type": "github" - } - }, - "devshell": { - "inputs": { - "flake-utils": [ - "std", - "flake-utils" - ], - "nixpkgs": [ - "std", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1682700442, - "narHash": "sha256-qjaAAcCYgp1pBBG7mY9z95ODUBZMtUpf0Qp3Gt/Wha0=", - "owner": "numtide", - "repo": "devshell", - "rev": "fb6673fe9fe4409e3f43ca86968261e970918a83", - "type": "github" - }, - "original": { - "owner": "numtide", - "repo": "devshell", - "type": "github" - } - }, - "dmerge": { - "inputs": { - "haumea": "haumea", - "nixlib": "nixlib", - "yants": [ - "std", - "yants" - ] - }, - "locked": { - "lastModified": 1686862774, - "narHash": "sha256-ojGtRQ9pIOUrxsQEuEPerUkqIJEuod9hIflfNkY+9CE=", - "owner": "divnix", - "repo": "dmerge", - "rev": "9f7f7a8349d33d7bd02e0f2b484b1f076e503a96", - "type": "github" - }, - "original": { - "owner": "divnix", - "ref": "0.2.1", - "repo": "dmerge", - "type": "github" - } - }, - "fenix": { - "inputs": { - "nixpkgs": "nixpkgs_2", - "rust-analyzer-src": "rust-analyzer-src" - }, - "locked": { - "lastModified": 1677306201, - "narHash": "sha256-VZ9x7qdTosFvVsrpgFHrtYfT6PU3yMIs7NRYn9ELapI=", - "owner": "nix-community", - "repo": "fenix", - "rev": "0923f0c162f65ae40261ec940406049726cfeab4", - "type": "github" - }, - "original": { - "owner": "nix-community", - "repo": "fenix", - "type": "github" - } - }, - "flake-compat": { - "flake": false, - "locked": { - "lastModified": 1673956053, - "narHash": "sha256-4gtG9iQuiKITOjNQQeQIpoIB6b16fm+504Ch3sNKLd8=", - "owner": "edolstra", - "repo": "flake-compat", - "rev": "35bb57c0c8d8b62bbfd284272c928ceb64ddbde9", - "type": "github" - }, - "original": { - "owner": "edolstra", - "repo": "flake-compat", - "type": "github" - } - }, "flake-utils": { "locked": { - "lastModified": 1659877975, - "narHash": "sha256-zllb8aq3YO3h8B/U0/J1WBgAL8EX5yWf5pMj3G0NAmc=", + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", "owner": "numtide", "repo": "flake-utils", - "rev": "c0e246b9b83f637f4681389ecabcb2681b4f3af0", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", "type": "github" }, "original": { @@ -141,11 +17,11 @@ }, "flake-utils_2": { "locked": { - "lastModified": 1667395993, - "narHash": "sha256-nuEHfE/LcWyuSWnS8t12N1wc105Qtau+/OdUAjtQ0rA=", + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", "owner": "numtide", "repo": "flake-utils", - "rev": "5aed5285a952e0b949eb3ba02c12fa4fcfef535f", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", "type": "github" }, "original": { @@ -154,97 +30,296 @@ "type": "github" } }, - "haumea": { - "inputs": { - "nixpkgs": [ - "std", - "dmerge", - "nixlib" - ] - }, + "flake-utils_3": { "locked": { - "lastModified": 1685133229, - "narHash": "sha256-FePm/Gi9PBSNwiDFq3N+DWdfxFq0UKsVVTJS3cQPn94=", - "owner": "nix-community", - "repo": "haumea", - "rev": "34dd58385092a23018748b50f9b23de6266dffc2", + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", "type": "github" }, "original": { - "owner": "nix-community", - "ref": "v0.2.2", - "repo": "haumea", + "owner": "numtide", + "repo": "flake-utils", "type": "github" } }, - "incl": { - "inputs": { - "nixlib": [ - "std", - "dmerge", - "nixlib" - ] - }, + "flake-utils_4": { "locked": { - "lastModified": 1669263024, - "narHash": "sha256-E/+23NKtxAqYG/0ydYgxlgarKnxmDbg6rCMWnOBqn9Q=", - "owner": "divnix", - "repo": "incl", - "rev": "ce7bebaee048e4cd7ebdb4cee7885e00c4e2abca", + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", "type": "github" }, "original": { - "owner": "divnix", - "repo": "incl", + "owner": "numtide", + "repo": "flake-utils", "type": "github" } }, - "n2c": { - "inputs": { - "flake-utils": [ - "std", - "flake-utils" - ], - "nixpkgs": [ - "std", - "nixpkgs" - ] - }, + "flake-utils_5": { "locked": { - "lastModified": 1685771919, - "narHash": "sha256-3lVKWrhNXjHJB6QkZ2SJaOs4X/mmYXtY6ovPVpDMOHc=", - "owner": "nlewo", - "repo": "nix2container", - "rev": "95e2220911874064b5d809f8d35f7835184c4ddf", + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", "type": "github" }, "original": { - "owner": "nlewo", - "repo": "nix2container", + "owner": "numtide", + "repo": "flake-utils", "type": "github" } }, + "flake-utils_6": { + "locked": { + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_7": { + "locked": { + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_8": { + "locked": { + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "flake-utils_9": { + "locked": { + "lastModified": 1653893745, + "narHash": "sha256-0jntwV3Z8//YwuOjzhV2sgJJPt+HY6KhU7VZUL0fKZQ=", + "owner": "numtide", + "repo": "flake-utils", + "rev": "1ed9fb1935d260de5fe1c2f7ee0ebaae17ed2fa1", + "type": "github" + }, + "original": { + "owner": "numtide", + "repo": "flake-utils", + "type": "github" + } + }, + "mfgames-project-setup": { + "inputs": { + "nixago": "nixago", + "nixago-exts": "nixago-exts_3", + "nixpkgs": "nixpkgs" + }, + "locked": { + "lastModified": 1709701991, + "narHash": "sha256-aioBatPisIMfmVUq50g9M74GidTqgRpA+PVXuL6NYAo=", + "ref": "refs/heads/main", + "rev": "9c50fe4984c346cec825c2875e1ba81ec385f5b1", + "revCount": 15, + "type": "git", + "url": "https://src.mfgames.com/nixos-contrib/mfgames-project-setup-flake.git" + }, + "original": { + "type": "git", + "url": "https://src.mfgames.com/nixos-contrib/mfgames-project-setup-flake.git" + } + }, "nixago": { "inputs": { - "flake-utils": [ - "std", - "flake-utils" - ], - "nixago-exts": [ - "std", - "blank" - ], + "flake-utils": "flake-utils", + "nixago-exts": "nixago-exts", "nixpkgs": [ - "std", + "mfgames-project-setup", "nixpkgs" ] }, "locked": { - "lastModified": 1683210100, - "narHash": "sha256-bhGDOlkWtlhVECpoOog4fWiFJmLCpVEg09a40aTjCbw=", + "lastModified": 1687381756, + "narHash": "sha256-IUMIlYfrvj7Yli4H2vvyig8HEPpfCeMaE6+kBGPzFyk=", + "owner": "jmgilman", + "repo": "nixago", + "rev": "dacceb10cace103b3e66552ec9719fa0d33c0dc9", + "type": "github" + }, + "original": { + "owner": "jmgilman", + "repo": "nixago", + "type": "github" + } + }, + "nixago-exts": { + "inputs": { + "flake-utils": "flake-utils_2", + "nixago": "nixago_2", + "nixpkgs": [ + "mfgames-project-setup", + "nixago", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1676070308, + "narHash": "sha256-QaJ65oc2l8iwQIGWUJ0EKjCeSuuCM/LqR8RauxZUUkc=", + "owner": "nix-community", + "repo": "nixago-extensions", + "rev": "e5380cb0456f4ea3c86cf94e3039eb856bf07d0b", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixago-extensions", + "type": "github" + } + }, + "nixago-exts_2": { + "inputs": { + "flake-utils": "flake-utils_4", + "nixago": "nixago_3", + "nixpkgs": [ + "mfgames-project-setup", + "nixago", + "nixago-exts", + "nixago", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1655508669, + "narHash": "sha256-BDDdo5dZQMmwNH/GNacy33nPBnCpSIydWFPZs0kkj/g=", + "owner": "nix-community", + "repo": "nixago-extensions", + "rev": "3022a932ce109258482ecc6568c163e8d0b426aa", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixago-extensions", + "type": "github" + } + }, + "nixago-exts_3": { + "inputs": { + "flake-utils": "flake-utils_6", + "nixago": "nixago_4", + "nixpkgs": [ + "mfgames-project-setup", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1676070308, + "narHash": "sha256-QaJ65oc2l8iwQIGWUJ0EKjCeSuuCM/LqR8RauxZUUkc=", + "owner": "nix-community", + "repo": "nixago-extensions", + "rev": "e5380cb0456f4ea3c86cf94e3039eb856bf07d0b", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixago-extensions", + "type": "github" + } + }, + "nixago-exts_4": { + "inputs": { + "flake-utils": "flake-utils_8", + "nixago": "nixago_5", + "nixpkgs": [ + "mfgames-project-setup", + "nixago-exts", + "nixago", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1655508669, + "narHash": "sha256-BDDdo5dZQMmwNH/GNacy33nPBnCpSIydWFPZs0kkj/g=", + "owner": "nix-community", + "repo": "nixago-extensions", + "rev": "3022a932ce109258482ecc6568c163e8d0b426aa", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixago-extensions", + "type": "github" + } + }, + "nixago_2": { + "inputs": { + "flake-utils": "flake-utils_3", + "nixago-exts": "nixago-exts_2", + "nixpkgs": [ + "mfgames-project-setup", + "nixago", + "nixago-exts", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1676070010, + "narHash": "sha256-iYzJIWptE1EUD8VINAg66AAMUajizg8JUYN3oBmb8no=", "owner": "nix-community", "repo": "nixago", - "rev": "1da60ad9412135f9ed7a004669fdcf3d378ec630", + "rev": "d480ba6c0c16e2c5c0bd2122852d6a0c9ad1ed0e", + "type": "github" + }, + "original": { + "owner": "nix-community", + "ref": "rename-config-data", + "repo": "nixago", + "type": "github" + } + }, + "nixago_3": { + "inputs": { + "flake-utils": "flake-utils_5", + "nixpkgs": [ + "mfgames-project-setup", + "nixago", + "nixago-exts", + "nixago", + "nixago-exts", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1655405483, + "narHash": "sha256-Crd49aZWNrpczlRTOwWGfwBMsTUoG9vlHDKQC7cx264=", + "owner": "nix-community", + "repo": "nixago", + "rev": "e6a9566c18063db5b120e69e048d3627414e327d", "type": "github" }, "original": { @@ -253,284 +328,88 @@ "type": "github" } }, - "nixlib": { + "nixago_4": { + "inputs": { + "flake-utils": "flake-utils_7", + "nixago-exts": "nixago-exts_4", + "nixpkgs": [ + "mfgames-project-setup", + "nixago-exts", + "nixpkgs" + ] + }, "locked": { - "lastModified": 1681001314, - "narHash": "sha256-5sDnCLdrKZqxLPK4KA8+f4A3YKO/u6ElpMILvX0g72c=", + "lastModified": 1676070010, + "narHash": "sha256-iYzJIWptE1EUD8VINAg66AAMUajizg8JUYN3oBmb8no=", "owner": "nix-community", - "repo": "nixpkgs.lib", - "rev": "367c0e1086a4eb4502b24d872cea2c7acdd557f4", + "repo": "nixago", + "rev": "d480ba6c0c16e2c5c0bd2122852d6a0c9ad1ed0e", "type": "github" }, "original": { "owner": "nix-community", - "repo": "nixpkgs.lib", + "ref": "rename-config-data", + "repo": "nixago", + "type": "github" + } + }, + "nixago_5": { + "inputs": { + "flake-utils": "flake-utils_9", + "nixpkgs": [ + "mfgames-project-setup", + "nixago-exts", + "nixago", + "nixago-exts", + "nixpkgs" + ] + }, + "locked": { + "lastModified": 1655405483, + "narHash": "sha256-Crd49aZWNrpczlRTOwWGfwBMsTUoG9vlHDKQC7cx264=", + "owner": "nix-community", + "repo": "nixago", + "rev": "e6a9566c18063db5b120e69e048d3627414e327d", + "type": "github" + }, + "original": { + "owner": "nix-community", + "repo": "nixago", "type": "github" } }, "nixpkgs": { "locked": { - "lastModified": 1693565476, - "narHash": "sha256-ya00zHt7YbPo3ve/wNZ/6nts61xt7wK/APa6aZAfey0=", - "owner": "NixOS", - "repo": "nixpkgs", - "rev": "aa8aa7e2ea35ce655297e8322dc82bf77a31d04b", - "type": "github" + "lastModified": 1706098335, + "narHash": "sha256-r3dWjT8P9/Ah5m5ul4WqIWD8muj5F+/gbCdjiNVBKmU=", + "rev": "a77ab169a83a4175169d78684ddd2e54486ac651", + "revCount": 554858, + "type": "tarball", + "url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.2311.554858%2Brev-a77ab169a83a4175169d78684ddd2e54486ac651/018d46f0-798f-71dc-a8c5-4689c46f7d12/source.tar.gz" }, "original": { - "id": "nixpkgs", - "ref": "nixos-unstable", - "type": "indirect" + "type": "tarball", + "url": "https://flakehub.com/f/NixOS/nixpkgs/%2A.tar.gz" } }, "nixpkgs_2": { "locked": { - "lastModified": 1677063315, - "narHash": "sha256-qiB4ajTeAOVnVSAwCNEEkoybrAlA+cpeiBxLobHndE8=", - "owner": "nixos", - "repo": "nixpkgs", - "rev": "988cc958c57ce4350ec248d2d53087777f9e1949", - "type": "github" + "lastModified": 1709569716, + "narHash": "sha256-iOR44RU4jQ+YPGrn+uQeYAp7Xo7Z/+gT+wXJoGxxLTY=", + "rev": "617579a787259b9a6419492eaac670a5f7663917", + "revCount": 556422, + "type": "tarball", + "url": "https://api.flakehub.com/f/pinned/NixOS/nixpkgs/0.2311.556422%2Brev-617579a787259b9a6419492eaac670a5f7663917/018e0df2-b0f7-7a27-af1a-04150ef0f2c7/source.tar.gz" }, "original": { - "owner": "nixos", - "ref": "nixos-unstable", - "repo": "nixpkgs", - "type": "github" - } - }, - "nosys": { - "locked": { - "lastModified": 1668010795, - "narHash": "sha256-JBDVBnos8g0toU7EhIIqQ1If5m/nyBqtHhL3sicdPwI=", - "owner": "divnix", - "repo": "nosys", - "rev": "feade0141487801c71ff55623b421ed535dbdefa", - "type": "github" - }, - "original": { - "owner": "divnix", - "repo": "nosys", - "type": "github" - } - }, - "paisano": { - "inputs": { - "nixpkgs": [ - "std", - "nixpkgs" - ], - "nosys": "nosys", - "yants": [ - "std", - "yants" - ] - }, - "locked": { - "lastModified": 1686862844, - "narHash": "sha256-m8l/HpRBJnZ3c0F1u0IyQ3nYGWE0R9V5kfORuqZPzgk=", - "owner": "paisano-nix", - "repo": "core", - "rev": "6674b3d3577212c1eeecd30d62d52edbd000e726", - "type": "github" - }, - "original": { - "owner": "paisano-nix", - "ref": "0.1.1", - "repo": "core", - "type": "github" - } - }, - "paisano-actions": { - "inputs": { - "nixpkgs": [ - "std", - "paisano-mdbook-preprocessor", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1677306424, - "narHash": "sha256-H9/dI2rGEbKo4KEisqbRPHFG2ajF8Tm111NPdKGIf28=", - "owner": "paisano-nix", - "repo": "actions", - "rev": "65ec4e080b3480167fc1a748c89a05901eea9a9b", - "type": "github" - }, - "original": { - "owner": "paisano-nix", - "repo": "actions", - "type": "github" - } - }, - "paisano-mdbook-preprocessor": { - "inputs": { - "crane": "crane", - "fenix": "fenix", - "nixpkgs": [ - "std", - "nixpkgs" - ], - "paisano-actions": "paisano-actions", - "std": [ - "std" - ] - }, - "locked": { - "lastModified": 1680654400, - "narHash": "sha256-Qdpio+ldhUK3zfl22Mhf8HUULdUOJXDWDdO7MIK69OU=", - "owner": "paisano-nix", - "repo": "mdbook-paisano-preprocessor", - "rev": "11a8fc47f574f194a7ae7b8b98001f6143ba4cf1", - "type": "github" - }, - "original": { - "owner": "paisano-nix", - "repo": "mdbook-paisano-preprocessor", - "type": "github" - } - }, - "paisano-tui": { - "inputs": { - "nixpkgs": [ - "std", - "blank" - ], - "std": [ - "std" - ] - }, - "locked": { - "lastModified": 1681847764, - "narHash": "sha256-mdd7PJW1BZvxy0cIKsPfAO+ohVl/V7heE5ZTAHzTdv8=", - "owner": "paisano-nix", - "repo": "tui", - "rev": "3096bad91cae73ab8ab3367d31f8a143d248a244", - "type": "github" - }, - "original": { - "owner": "paisano-nix", - "ref": "0.1.1", - "repo": "tui", - "type": "github" + "type": "tarball", + "url": "https://flakehub.com/f/NixOS/nixpkgs/%2A.tar.gz" } }, "root": { "inputs": { - "nixpkgs": "nixpkgs", - "std": "std" - } - }, - "rust-analyzer-src": { - "flake": false, - "locked": { - "lastModified": 1677221702, - "narHash": "sha256-1M+58rC4eTCWNmmX0hQVZP20t3tfYNunl9D/PrGUyGE=", - "owner": "rust-lang", - "repo": "rust-analyzer", - "rev": "f5401f620699b26ed9d47a1d2e838143a18dbe3b", - "type": "github" - }, - "original": { - "owner": "rust-lang", - "ref": "nightly", - "repo": "rust-analyzer", - "type": "github" - } - }, - "rust-overlay": { - "inputs": { - "flake-utils": [ - "std", - "paisano-mdbook-preprocessor", - "crane", - "flake-utils" - ], - "nixpkgs": [ - "std", - "paisano-mdbook-preprocessor", - "crane", - "nixpkgs" - ] - }, - "locked": { - "lastModified": 1675391458, - "narHash": "sha256-ukDKZw922BnK5ohL9LhwtaDAdCsJL7L6ScNEyF1lO9w=", - "owner": "oxalica", - "repo": "rust-overlay", - "rev": "383a4acfd11d778d5c2efcf28376cbd845eeaedf", - "type": "github" - }, - "original": { - "owner": "oxalica", - "repo": "rust-overlay", - "type": "github" - } - }, - "std": { - "inputs": { - "arion": [ - "std", - "blank" - ], - "blank": "blank", - "devshell": "devshell", - "dmerge": "dmerge", - "flake-utils": "flake-utils", - "incl": "incl", - "makes": [ - "std", - "blank" - ], - "microvm": [ - "std", - "blank" - ], - "n2c": "n2c", - "nixago": "nixago", - "nixpkgs": [ - "nixpkgs" - ], - "paisano": "paisano", - "paisano-mdbook-preprocessor": "paisano-mdbook-preprocessor", - "paisano-tui": "paisano-tui", - "yants": "yants" - }, - "locked": { - "lastModified": 1686877329, - "narHash": "sha256-A/SU8KqlLP2MBuhi9wmt6gDhXyp+chCeDZ4OBxfSWBI=", - "owner": "divnix", - "repo": "std", - "rev": "aa6d423b82b7b7c2a4545693dea9ed1db14676e7", - "type": "github" - }, - "original": { - "owner": "divnix", - "ref": "v0.23.2", - "repo": "std", - "type": "github" - } - }, - "yants": { - "inputs": { - "nixpkgs": [ - "std", - "dmerge", - "nixlib" - ] - }, - "locked": { - "lastModified": 1686863218, - "narHash": "sha256-kooxYm3/3ornWtVBNHM3Zh020gACUyFX2G0VQXnB+mk=", - "owner": "divnix", - "repo": "yants", - "rev": "8f0da0dba57149676aa4817ec0c880fbde7a648d", - "type": "github" - }, - "original": { - "owner": "divnix", - "repo": "yants", - "type": "github" + "mfgames-project-setup": "mfgames-project-setup", + "nixpkgs": "nixpkgs_2" } } }, diff --git a/flake.nix b/flake.nix index 5b47c7e..82da4fd 100644 --- a/flake.nix +++ b/flake.nix @@ -1,26 +1,52 @@ { - description = "A variety of .NET core libraries used for development"; - inputs = { - std.url = "github:divnix/std/v0.23.2"; - std.inputs.nixpkgs.follows = "nixpkgs"; - nixpkgs.url = "nixpkgs/nixos-unstable"; + nixpkgs.url = "https://flakehub.com/f/NixOS/nixpkgs/*.tar.gz"; + mfgames-project-setup.url = "git+https://src.mfgames.com/nixos-contrib/mfgames-project-setup-flake.git"; }; - outputs = inputs @ { - self, - std, - ... - }: - std.growOn { - inherit inputs; - systems = ["x86_64-linux"]; - cellsFrom = ./nix; - cellBlocks = with std.blockTypes; [ - (devshells "shells") - (nixago "configs") - ]; - } { - devShells = std.harvest self ["common" "shells"]; + outputs = inputs @ { self, nixpkgs, mfgames-project-setup, ... }: + let + # Helpers for producing system-specific outputs + supportedSystems = [ "x86_64-linux" ]; + forEachSupportedSystem = f: nixpkgs.lib.genAttrs supportedSystems (system: f { + inherit system; + pkgs = import nixpkgs { inherit system; }; + }); + in + rec + { + # Set up the developer shell. + devShells = forEachSupportedSystem ({ system, pkgs }: + let + project-config = mfgames-project-setup.lib.mkConfig { + inherit system pkgs; + contributorCovenant.enable = true; + contributorCovenant.contact = "contact@mfgames.com"; + developerCertificateOfOrigin.enable = true; + dotnet.enable = true; + }; + in + { + # Shell + default = pkgs.mkShell { + packages = [ + pkgs.gnugrep + pkgs.gawk + pkgs.diffutils + pkgs.fd + pkgs.just + pkgs.lefthook + pkgs.jq + pkgs.dotnet-sdk + pkgs.git + ] + ++ project-config.packages; + + shellHook = project-config.shellHook; + }; + }); + + # Formatting for the Nix files + formatter = forEachSupportedSystem ({ pkgs, ... }: pkgs.nixpkgs-fmt); }; } diff --git a/nix/common/configs.nix b/nix/common/configs.nix deleted file mode 100644 index 3da1bf9..0000000 --- a/nix/common/configs.nix +++ /dev/null @@ -1,262 +0,0 @@ -{ - inputs, - cell, -}: let - inherit (inputs) nixpkgs; - inherit (inputs.cells) std presets; - l = nixpkgs.lib // builtins; -in { - conform = { - data = { - commit = { - header = {length = 89;}; - conventional = { - # Only allow these types of conventional commits (inspired by Angular) - types = [ - "build" - "chore" - "ci" - "docs" - "feat" - "fix" - "perf" - "refactor" - "style" - "test" - ]; - }; - }; - }; - }; - - editorconfig = { - hook.mode = "copy"; # already useful before entering the devshell - data = { - root = true; - - "*" = { - # Common - end_of_line = "lf"; - insert_final_newline = true; - trim_trailing_whitespace = true; - charset = "utf-8"; - indent_style = "space"; - indent_size = 4; - indent_brace_style = "K&R"; - max_line_length = 80; - tab_width = 4; - curly_bracket_next_line = true; - - # Microsoft .NET properties - csharp_new_line_before_members_in_object_initializers = false; - csharp_preferred_modifier_order = "public, private, protected, internal, new, abstract, virtual, sealed, override, static, readonly, extern, unsafe, volatile, async:suggestion"; - csharp_space_after_cast = false; - csharp_style_var_elsewhere = "false:hint"; - csharp_style_var_for_built_in_types = "false:hint"; - csharp_style_var_when_type_is_apparent = "true:hint"; - csharp_preserve_single_line_statements = false; - csharp_preserve_single_line_blocks = true; - dotnet_style_predefined_type_for_locals_parameters_members = "true:hint"; - dotnet_style_predefined_type_for_member_access = "true:hint"; - dotnet_style_qualification_for_event = "true:hint"; - dotnet_style_qualification_for_field = "true:hint"; - dotnet_style_qualification_for_method = "true:hint"; - dotnet_style_qualification_for_property = "true:hint"; - dotnet_style_require_accessibility_modifiers = "for_non_interface_members:hint"; - - # ReSharper properties - resharper_alignment_tab_fill_style = "optimal_fill"; - resharper_apply_on_completion = true; - resharper_blank_lines_after_control_transfer_statements = 1; - resharper_blank_lines_around_single_line_auto_property = 1; - resharper_blank_lines_around_single_line_property = 1; - resharper_blank_lines_before_single_line_comment = 1; - resharper_blank_lines_between_using_groups = 1; - resharper_braces_for_for = "required"; - resharper_braces_for_foreach = "required"; - resharper_braces_for_ifelse = "required"; - resharper_braces_for_while = "required"; - resharper_can_use_global_alias = false; - resharper_csharp_blank_lines_around_single_line_field = 1; - resharper_csharp_blank_lines_around_single_line_invocable = 1; - resharper_csharp_indent_style = "tab"; - resharper_csharp_insert_final_newline = true; - resharper_csharp_keep_blank_lines_in_code = 1; - resharper_csharp_keep_blank_lines_in_declarations = 1; - resharper_csharp_new_line_before_while = true; - resharper_csharp_use_indent_from_vs = false; - resharper_csharp_wrap_arguments_style = "chop_if_long"; - resharper_csharp_wrap_extends_list_style = "chop_if_long"; - resharper_csharp_wrap_parameters_style = "chop_if_long"; - resharper_css_insert_final_newline = false; - resharper_enforce_line_ending_style = true; - resharper_html_insert_final_newline = false; - resharper_indent_nested_fixed_stmt = true; - resharper_js_indent_style = "tab"; - resharper_js_insert_final_newline = true; - resharper_js_keep_blank_lines_in_code = 1; - resharper_js_stick_comment = false; - resharper_js_use_indent_from_vs = false; - resharper_js_wrap_before_binary_opsign = true; - resharper_js_wrap_chained_method_calls = "chop_if_long"; - resharper_keep_blank_lines_between_declarations = 1; - resharper_min_blank_lines_after_imports = 1; - resharper_place_attribute_on_same_line = false; - resharper_place_constructor_initializer_on_same_line = false; - resharper_place_type_constraints_on_same_line = false; - resharper_protobuf_insert_final_newline = false; - resharper_qualified_using_at_nested_scope = true; - resharper_resx_insert_final_newline = false; - resharper_space_within_single_line_array_initializer_braces = true; - resharper_use_indents_from_main_language_in_file = false; - resharper_vb_insert_final_newline = false; - resharper_wrap_after_declaration_lpar = true; - resharper_wrap_after_invocation_lpar = true; - resharper_wrap_before_extends_colon = true; - resharper_wrap_before_first_type_parameter_constraint = true; - resharper_wrap_before_type_parameter_langle = true; - resharper_xmldoc_indent_child_elements = "ZeroIndent"; - resharper_xmldoc_indent_text = "ZeroIndent"; - resharper_xmldoc_insert_final_newline = false; - resharper_xml_insert_final_newline = false; - - # ReSharper inspection severities - resharper_check_namespace_highlighting = "none"; - resharper_convert_to_auto_property_highlighting = "none"; - resharper_localizable_element_highlighting = "none"; - resharper_redundant_comma_in_attribute_list_highlighting = "none"; - resharper_redundant_comma_in_enum_declaration_highlighting = "none"; - resharper_redundant_comma_in_initializer_highlighting = "none"; - resharper_string_compare_to_is_culture_specific_highlighting = "none"; - resharper_string_index_of_is_culture_specific_1_highlighting = "none"; - resharper_use_null_propagation_highlighting = "none"; - resharper_use_object_or_collection_initializer_highlighting = "hint"; - resharper_use_string_interpolation_highlighting = "hint"; - }; - - "*.{diff,patch}" = { - end_of_line = "unset"; - insert_final_newline = "unset"; - trim_trailing_whitespace = "unset"; - indent_size = "unset"; - }; - - "*.md" = { - max_line_length = "off"; - trim_trailing_whitespace = false; - }; - - "package.json" = { - indent_style = "space"; - indent_size = 2; - tab_width = 2; - }; - - "*.{appxmanifest,build,config,csproj,dbml,discomap,dtd,jsproj,lsproj,njsproj,nuspec,proj,props,resw,resx,StyleCop,targets,tasks,vbproj,xml,xsd}" = { - indent_style = "space"; - indent_size = 2; - tab_width = 2; - }; - - "{LICENSES/**,LICENSE}" = { - end_of_line = "unset"; - insert_final_newline = "unset"; - trim_trailing_whitespace = "unset"; - charset = "unset"; - indent_style = "unset"; - indent_size = "unset"; - }; - }; - }; - - lefthook = { - data = { - commit-msg = { - commands = { - # Runs conform on commit-msg hook to ensure commit messages are - # compliant. - conform = { - run = "${nixpkgs.conform}/bin/conform enforce --commit-msg-file {1}"; - }; - }; - }; - pre-commit = { - commands = { - # Runs treefmt on pre-commit hook to ensure checked-in source code is - # properly formatted. - treefmt = { - run = "${nixpkgs.treefmt}/bin/treefmt {staged_files}"; - }; - }; - }; - }; - }; - - prettier = { - data = { - printWidth = 80; - proseWrap = "always"; - }; - output = ".prettierrc"; - format = "json"; - }; - - treefmt = { - data = { - formatter = { - dotnet = { - command = "dotnet"; - options = ["jb" "cleanupcode"]; - includes = ["*.cs"]; - }; - - nix = { - command = "alejandra"; - includes = ["*.nix" "*.nix.hbs"]; - }; - - prettier = { - command = "prettier"; - # 2023-09-02 DREM: Removed "--plugin" "prettier-plugin-toml" - options = ["--write"]; - includes = [ - "*.css" - "*.html" - "*.js" - "*.json" - "*.jsx" - "*.md" - "*.mdx" - "*.scss" - "*.ts" - "*.yaml" - #"*.toml" - ]; - }; - - shell = { - command = "shfmt"; - options = ["-i" "4" "-s" "-w"]; - includes = ["*.sh"]; - }; - - # We mainly use it here to format the Markdown in our README. - prettier = { - excludes = ["**.min.js"]; - }; - }; - }; - - packages = [ - nixpkgs.alejandra - nixpkgs.nodePackages.prettier - nixpkgs.nodePackages.prettier-plugin-toml - nixpkgs.shfmt - nixpkgs.go - ]; - - #devshell.startup.prettier-plugin-toml = l.stringsWithDeps.noDepEntry '' - # export NODE_PATH=${nixpkgs.nodePackages.prettier-plugin-toml}/lib/node_modules:$NODE_PATH - #''; - }; -} diff --git a/nix/common/shells.nix b/nix/common/shells.nix deleted file mode 100644 index bea2b86..0000000 --- a/nix/common/shells.nix +++ /dev/null @@ -1,45 +0,0 @@ -{ - inputs, - cell, -}: let - inherit (inputs.std) std lib; - inherit (inputs) nixpkgs; - inherit (inputs.cells) cli; - - l = nixpkgs.lib // builtins; - - dev = lib.dev.mkShell { - packages = [ - # Linux - nixpkgs.gnugrep - nixpkgs.gawk - nixpkgs.diffutils - nixpkgs.fd - - # Building - nixpkgs.just - nixpkgs.lefthook - nixpkgs.jq - - # .NET - nixpkgs.dotnet-sdk - - # Nix - nixpkgs.nixfmt - nixpkgs.alejandra - - # Git - nixpkgs.git - ]; - - nixago = [ - (lib.cfg.conform cell.configs.conform) - (lib.cfg.treefmt cell.configs.treefmt) - (lib.cfg.editorconfig cell.configs.editorconfig) - (lib.cfg.lefthook cell.configs.lefthook) - ]; - }; -in { - inherit dev; - default = dev; -} diff --git a/src/MfGames.Crypto/ByteStringFormat.cs b/src/MfGames.Crypto/ByteStringFormat.cs index cbe086a..10cdca7 100644 --- a/src/MfGames.Crypto/ByteStringFormat.cs +++ b/src/MfGames.Crypto/ByteStringFormat.cs @@ -2,18 +2,18 @@ namespace MfGames.Crypto; public enum ByteStringFormat { - /// - /// Indicates that the format should be lowercase hex characters. - /// - LowercaseHex, + /// + /// Indicates that the format should be lowercase hex characters. + /// + LowercaseHex, - /// - /// Indicates that the format should be uppercase hex characters. - /// - UppercaseHex, + /// + /// Indicates that the format should be uppercase hex characters. + /// + UppercaseHex, - /// - /// Indicates that the format should be Base64. - /// - Base64, + /// + /// Indicates that the format should be Base64. + /// + Base64, } diff --git a/src/MfGames.Crypto/Extensions/CryptoByteArrayExtensions.cs b/src/MfGames.Crypto/Extensions/CryptoByteArrayExtensions.cs index 3605529..83bc5f4 100644 --- a/src/MfGames.Crypto/Extensions/CryptoByteArrayExtensions.cs +++ b/src/MfGames.Crypto/Extensions/CryptoByteArrayExtensions.cs @@ -7,67 +7,62 @@ namespace MfGames.Crypto.Extensions; /// public static class CryptoByteArrayExtensions { - /// - /// Converts the input into a hash string, such as hex or base64. - /// - /// - /// - /// - public static string? ToByteString( - this byte[]? input, - ByteStringFormat format = ByteStringFormat.LowercaseHex) - { - if (input == null) - { - return null; - } + /// + /// Converts the input into a hash string, such as hex or base64. + /// + /// + /// + /// + public static string? ToByteString( + this byte[]? input, + ByteStringFormat format = ByteStringFormat.LowercaseHex + ) + { + if (input == null) + { + return null; + } - switch (format) - { - case ByteStringFormat.LowercaseHex: - return Convert.ToHexString(input).ToLowerInvariant(); + switch (format) + { + case ByteStringFormat.LowercaseHex: + return Convert.ToHexString(input).ToLowerInvariant(); - case ByteStringFormat.UppercaseHex: - return Convert.ToHexString(input); + case ByteStringFormat.UppercaseHex: + return Convert.ToHexString(input); - case ByteStringFormat.Base64: - return Convert.ToBase64String(input); + case ByteStringFormat.Base64: + return Convert.ToBase64String(input); - default: - throw new ArgumentOutOfRangeException( - nameof(format), - format, - null); - } - } + default: + throw new ArgumentOutOfRangeException(nameof(format), format, null); + } + } - /// - /// Hashes the given input and returns the results. - /// - /// A byte array or null. - /// The type of hash requested. - /// Null if input is null, otherwise the hash value. - public static byte[]? ToHashBytes( - this byte[]? input, - HashType hash = HashType.Sha512) - { - return input == null - ? null - : hash.CreateHash().ComputeHash(input); - } + /// + /// Hashes the given input and returns the results. + /// + /// A byte array or null. + /// The type of hash requested. + /// Null if input is null, otherwise the hash value. + public static byte[]? ToHashBytes(this byte[]? input, HashType hash = HashType.Sha512) + { + return input == null ? null : hash.CreateHash().ComputeHash(input); + } - /// - /// Hashes the given input and returns the results as a string. - /// - /// A byte array or null. - /// The type of hash requested. - /// The format of the requested string. - /// Null if input is null, otherwise the hash value. - public static string? ToHashString( - this byte[]? input, - HashType hash = HashType.Sha512, - ByteStringFormat format = ByteStringFormat.LowercaseHex) - { - return input?.ToHashBytes(hash)?.ToByteString(format); - } + /// + /// Hashes the given input and returns the results as a string. + /// + /// A byte array or null. + /// The type of hash requested. + /// The format of the requested string. + /// Null if input is null, otherwise the hash value. + public static string? ToHashString( + this byte[]? input, + HashType hash = HashType.Sha512, + ByteStringFormat format = ByteStringFormat.LowercaseHex + ) + { + return input?.ToHashBytes(hash)?.ToByteString(format); + } } diff --git a/src/MfGames.Crypto/Extensions/CryptoStringExtensions.cs b/src/MfGames.Crypto/Extensions/CryptoStringExtensions.cs index 1d601e1..5862fbe 100644 --- a/src/MfGames.Crypto/Extensions/CryptoStringExtensions.cs +++ b/src/MfGames.Crypto/Extensions/CryptoStringExtensions.cs @@ -1,5 +1,4 @@ using System.Text; - using MfGames.Crypto.Hashes; namespace MfGames.Crypto.Extensions; @@ -9,54 +8,50 @@ namespace MfGames.Crypto.Extensions; /// public static class CryptoStringExtensions { - /// - /// Gets the encoded byte array of the given string. - /// - /// The input string or null. - /// The encoding to use, defaults to UTF-8. - /// Null if the input was null, otherwise the byte array. - public static byte[]? ToBytes( - this string? input, - Encoding? encoding = null) - { - encoding ??= Encoding.UTF8; + /// + /// Gets the encoded byte array of the given string. + /// + /// The input string or null. + /// The encoding to use, defaults to UTF-8. + /// Null if the input was null, otherwise the byte array. + public static byte[]? ToBytes(this string? input, Encoding? encoding = null) + { + encoding ??= Encoding.UTF8; - return input == null - ? null - : encoding.GetBytes(input); - } + return input == null ? null : encoding.GetBytes(input); + } - /// - /// Hashes the given input and returns the results. - /// - /// A byte array or null. - /// The type of hash requested. - /// The encoding to use, defaults to UTF-8. - /// Null if input is null, otherwise the hash value. - public static byte[]? ToHashBytes( - this string? input, - HashType hash = HashType.Sha512, - Encoding? encoding = null) - { - return input == null - ? null - : hash.CreateHash().ComputeHash(input.ToBytes(encoding)!); - } + /// + /// Hashes the given input and returns the results. + /// + /// A byte array or null. + /// The type of hash requested. + /// The encoding to use, defaults to UTF-8. + /// Null if input is null, otherwise the hash value. + public static byte[]? ToHashBytes( + this string? input, + HashType hash = HashType.Sha512, + Encoding? encoding = null + ) + { + return input == null ? null : hash.CreateHash().ComputeHash(input.ToBytes(encoding)!); + } - /// - /// Hashes the given input and returns the results as a string. - /// - /// A byte array or null. - /// The type of hash requested. - /// The format of the requested string. - /// The encoding to use, defaults to UTF-8. - /// Null if input is null, otherwise the hash value. - public static string? ToHashString( - this string? input, - HashType hash = HashType.Sha512, - ByteStringFormat format = ByteStringFormat.LowercaseHex, - Encoding? encoding = null) - { - return input?.ToHashBytes(hash, encoding)?.ToByteString(format); - } + /// + /// Hashes the given input and returns the results as a string. + /// + /// A byte array or null. + /// The type of hash requested. + /// The format of the requested string. + /// The encoding to use, defaults to UTF-8. + /// Null if input is null, otherwise the hash value. + public static string? ToHashString( + this string? input, + HashType hash = HashType.Sha512, + ByteStringFormat format = ByteStringFormat.LowercaseHex, + Encoding? encoding = null + ) + { + return input?.ToHashBytes(hash, encoding)?.ToByteString(format); + } } diff --git a/src/MfGames.Crypto/Hashes/HashType.cs b/src/MfGames.Crypto/Hashes/HashType.cs index fda0b79..67d237a 100644 --- a/src/MfGames.Crypto/Hashes/HashType.cs +++ b/src/MfGames.Crypto/Hashes/HashType.cs @@ -5,23 +5,23 @@ namespace MfGames.Crypto.Hashes; /// public enum HashType { - /// - /// Indicates a SHA-512 hash. - /// - Sha512, + /// + /// Indicates a SHA-512 hash. + /// + Sha512, - /// - /// Indicates a SHA-256 hash. - /// - Sha256, + /// + /// Indicates a SHA-256 hash. + /// + Sha256, - /// - /// Indicates a SHA-1 hash. - /// - Sha1, + /// + /// Indicates a SHA-1 hash. + /// + Sha1, - /// - /// Indicates a MD5 hash. - /// - Md5, + /// + /// Indicates a MD5 hash. + /// + Md5, } diff --git a/src/MfGames.Crypto/Hashes/HashTypeExtensions.cs b/src/MfGames.Crypto/Hashes/HashTypeExtensions.cs index 81c692e..581a35d 100644 --- a/src/MfGames.Crypto/Hashes/HashTypeExtensions.cs +++ b/src/MfGames.Crypto/Hashes/HashTypeExtensions.cs @@ -4,30 +4,30 @@ namespace MfGames.Crypto.Hashes; public static class HashTypeExtensions { - /// - /// Constructs a hash of the given type. - /// - /// The type of hash to create. - /// A hash algorithm of the given type. - /// - public static HashAlgorithm CreateHash(this HashType type) - { - switch (type) - { - case HashType.Sha512: - return SHA512.Create(); + /// + /// Constructs a hash of the given type. + /// + /// The type of hash to create. + /// A hash algorithm of the given type. + /// + public static HashAlgorithm CreateHash(this HashType type) + { + switch (type) + { + case HashType.Sha512: + return SHA512.Create(); - case HashType.Sha256: - return SHA256.Create(); + case HashType.Sha256: + return SHA256.Create(); - case HashType.Sha1: - return SHA1.Create(); + case HashType.Sha1: + return SHA1.Create(); - case HashType.Md5: - return MD5.Create(); + case HashType.Md5: + return MD5.Create(); - default: - throw new ArgumentOutOfRangeException(nameof(type), type, null); - } - } + default: + throw new ArgumentOutOfRangeException(nameof(type), type, null); + } + } } diff --git a/src/MfGames.Gallium/Entity.cs b/src/MfGames.Gallium/Entity.cs index c15bc9d..704f910 100644 --- a/src/MfGames.Gallium/Entity.cs +++ b/src/MfGames.Gallium/Entity.cs @@ -7,517 +7,497 @@ namespace MfGames.Gallium; /// public record Entity { - public Entity() - : this(Interlocked.Increment(ref nextId)) - { - } + public Entity() + : this(Interlocked.Increment(ref nextId)) { } - private Entity(int id) - { - this.Id = id; - this.Components = ImmutableDictionary.Create(); - } + private Entity(int id) + { + this.Id = id; + this.Components = ImmutableDictionary.Create(); + } - /// - /// Gets or sets the optional formatting for an entity. This is used to - /// override the ToString functionality to provide additional information. - /// If this is null, then the default "ToString" will be called. - /// - /// - /// This must be a thread-safe function. - /// - public static Func? ToStringFormatter { get; set; } + /// + /// Gets or sets the optional formatting for an entity. This is used to + /// override the ToString functionality to provide additional information. + /// If this is null, then the default "ToString" will be called. + /// + /// + /// This must be a thread-safe function. + /// + public static Func? ToStringFormatter { get; set; } - /// - public virtual bool Equals(Entity? other) - { - if (ReferenceEquals(null, other)) - { - return false; - } + /// + public virtual bool Equals(Entity? other) + { + if (ReferenceEquals(null, other)) + { + return false; + } - if (ReferenceEquals(this, other)) - { - return true; - } + if (ReferenceEquals(this, other)) + { + return true; + } - return this.Id == other.Id; - } + return this.Id == other.Id; + } - /// - public override int GetHashCode() - { - return this.Id.GetHashCode(); - } + /// + public override int GetHashCode() + { + return this.Id.GetHashCode(); + } - private ImmutableDictionary Components { get; init; } + private ImmutableDictionary Components { get; init; } - /// - /// The internal ID to ensure the entities are unique. Since we are not - /// worried about serialization or using the identifiers from one call - /// to another, we can use a simple interlocked identifier instead of - /// a factory or provider method. - /// - private static int nextId; + /// + /// The internal ID to ensure the entities are unique. Since we are not + /// worried about serialization or using the identifiers from one call + /// to another, we can use a simple interlocked identifier instead of + /// a factory or provider method. + /// + private static int nextId; - /// - /// Gets a value indicating whether the entity has a specific type of - /// component registered. - /// - /// The component type. - /// True if the type exists, otherwise false. - public bool Has() - { - return this.Has(typeof(T1)); - } + /// + /// Gets a value indicating whether the entity has a specific type of + /// component registered. + /// + /// The component type. + /// True if the type exists, otherwise false. + public bool Has() + { + return this.Has(typeof(T1)); + } - /// - /// Gets a value indicating whether the entity has components of the given types - /// registered. - /// - /// The first component type. - /// The second component type. - /// - /// True if there are components of the given type exists, otherwise - /// false. - /// - public bool HasAll() - { - return this.HasAll(typeof(T1), typeof(T2)); - } + /// + /// Gets a value indicating whether the entity has components of the given types + /// registered. + /// + /// The first component type. + /// The second component type. + /// + /// True if there are components of the given type exists, otherwise + /// false. + /// + public bool HasAll() + { + return this.HasAll(typeof(T1), typeof(T2)); + } - /// - /// Gets a value indicating whether the entity has components of the given types - /// registered. - /// - /// The first component type. - /// The second component type. - /// The third component type. - /// - /// True if there are components of the given type exists, otherwise - /// false. - /// - public bool HasAll() - { - return this.HasAll(typeof(T1), typeof(T2), typeof(T3)); - } + /// + /// Gets a value indicating whether the entity has components of the given types + /// registered. + /// + /// The first component type. + /// The second component type. + /// The third component type. + /// + /// True if there are components of the given type exists, otherwise + /// false. + /// + public bool HasAll() + { + return this.HasAll(typeof(T1), typeof(T2), typeof(T3)); + } - /// - /// Gets a value indicating whether the entity has components of the given types - /// registered. - /// - /// The first component type. - /// The second component type. - /// The third component type. - /// The third component type. - /// - /// True if there are components of the given type exists, otherwise - /// false. - /// - public bool HasAll() - { - return this.HasAll(typeof(T1), typeof(T2), typeof(T3), typeof(T4)); - } + /// + /// Gets a value indicating whether the entity has components of the given types + /// registered. + /// + /// The first component type. + /// The second component type. + /// The third component type. + /// The third component type. + /// + /// True if there are components of the given type exists, otherwise + /// false. + /// + public bool HasAll() + { + return this.HasAll(typeof(T1), typeof(T2), typeof(T3), typeof(T4)); + } - /// - /// Gets a value indicating whether the entity has a specific type of - /// component registered. - /// - /// The component type. - /// True if the type exists, otherwise false. - public bool Has(Type type) - { - return this.Components.ContainsKey(type); - } + /// + /// Gets a value indicating whether the entity has a specific type of + /// component registered. + /// + /// The component type. + /// True if the type exists, otherwise false. + public bool Has(Type type) + { + return this.Components.ContainsKey(type); + } - /// - /// Gets a value indicating whether the entity has components for all the given - /// types. - /// - /// The component type. - /// The component type. - /// True if the type exists, otherwise false. - public bool HasAll( - Type t1, - Type t2) - { - return this.Has(t1) && this.Components.ContainsKey(t2); - } + /// + /// Gets a value indicating whether the entity has components for all the given + /// types. + /// + /// The component type. + /// The component type. + /// True if the type exists, otherwise false. + public bool HasAll(Type t1, Type t2) + { + return this.Has(t1) && this.Components.ContainsKey(t2); + } - /// - /// Gets a value indicating whether the entity has components for all the given - /// types. - /// - /// The component type. - /// The component type. - /// The component type. - /// True if the type exists, otherwise false. - public bool HasAll( - Type t1, - Type t2, - Type t3) - { - return this.HasAll(t1, t2) && this.Components.ContainsKey(t3); - } + /// + /// Gets a value indicating whether the entity has components for all the given + /// types. + /// + /// The component type. + /// The component type. + /// The component type. + /// True if the type exists, otherwise false. + public bool HasAll(Type t1, Type t2, Type t3) + { + return this.HasAll(t1, t2) && this.Components.ContainsKey(t3); + } - /// - /// Gets a value indicating whether the entity has components for all the given - /// types. - /// - /// The component type. - /// The component type. - /// The component type. - /// The component type. - /// True if the type exists, otherwise false. - public bool HasAll( - Type t1, - Type t2, - Type t3, - Type t4) - { - return this.HasAll(t1, t2, t3) && this.Components.ContainsKey(t4); - } + /// + /// Gets a value indicating whether the entity has components for all the given + /// types. + /// + /// The component type. + /// The component type. + /// The component type. + /// The component type. + /// True if the type exists, otherwise false. + public bool HasAll(Type t1, Type t2, Type t3, Type t4) + { + return this.HasAll(t1, t2, t3) && this.Components.ContainsKey(t4); + } - /// - /// Retrieves a registered component of the given type. - /// - /// The component type. - /// The registered object. - public TType Get() - { - return (TType)this.Components[typeof(TType)]; - } + /// + /// Retrieves a registered component of the given type. + /// + /// The component type. + /// The registered object. + public TType Get() + { + return (TType)this.Components[typeof(TType)]; + } - /// - /// Retrieves a registered component of the given type and casts it to - /// TType. - /// - /// The component key. - /// The component type. - /// The registered object. - public TType Get(Type type) - { - return (TType)this.Components[type]; - } + /// + /// Retrieves a registered component of the given type and casts it to + /// TType. + /// + /// The component key. + /// The component type. + /// The registered object. + public TType Get(Type type) + { + return (TType)this.Components[type]; + } - /// - /// Gets the number of components registered in the entity. - /// - public int Count => this.Components.Count; + /// + /// Gets the number of components registered in the entity. + /// + public int Count => this.Components.Count; - /// - /// Gets the given component type if inside the entity, otherwise the - /// default value. - /// - /// The component type. - /// The found component or default (typically null). - public TType? GetOptional() - { - return this.Has() ? this.Get() : default; - } + /// + /// Gets the given component type if inside the entity, otherwise the + /// default value. + /// + /// The component type. + /// The found component or default (typically null). + public TType? GetOptional() + { + return this.Has() ? this.Get() : default; + } - /// - /// Attempts to get the value, if present. If not, this returns false - /// and the value is undefined. Otherwise, this method returns true - /// and the actual value inside that variable. - /// - /// The value if contained in the entity. - /// The component type. - /// True if found, otherwise false. - public bool TryGet(out T1 value) - { - if (this.Has()) - { - value = this.Get(); + /// + /// Attempts to get the value, if present. If not, this returns false + /// and the value is undefined. Otherwise, this method returns true + /// and the actual value inside that variable. + /// + /// The value if contained in the entity. + /// The component type. + /// True if found, otherwise false. + public bool TryGet(out T1 value) + { + if (this.Has()) + { + value = this.Get(); - return true; - } + return true; + } - value = default!; + value = default!; - return false; - } + return false; + } - /// - /// Attempts to get the values, if present. If not, this returns false - /// and the value is undefined. Otherwise, this method returns true - /// and the actual value inside that variable. - /// - /// The value if contained in the entity. - /// The value if contained in the entity. - /// The first component type. - /// The second component type. - /// True if found, otherwise false. - public bool TryGet( - out T1 value1, - out T2 value2) - { - if (this.HasAll()) - { - value1 = this.Get(); - value2 = this.Get(); + /// + /// Attempts to get the values, if present. If not, this returns false + /// and the value is undefined. Otherwise, this method returns true + /// and the actual value inside that variable. + /// + /// The value if contained in the entity. + /// The value if contained in the entity. + /// The first component type. + /// The second component type. + /// True if found, otherwise false. + public bool TryGet(out T1 value1, out T2 value2) + { + if (this.HasAll()) + { + value1 = this.Get(); + value2 = this.Get(); - return true; - } + return true; + } - value1 = default!; - value2 = default!; + value1 = default!; + value2 = default!; - return false; - } + return false; + } - /// - /// Attempts to get the values, if present. If not, this returns false - /// and the value is undefined. Otherwise, this method returns true - /// and the actual value inside that variable. - /// - /// The value if contained in the entity. - /// The value if contained in the entity. - /// The value if contained in the entity. - /// The first component type. - /// The second component type. - /// The third component type. - /// True if found, otherwise false. - public bool TryGet( - out T1 value1, - out T2 value2, - out T3 value3) - { - if (this.HasAll()) - { - value1 = this.Get(); - value2 = this.Get(); - value3 = this.Get(); + /// + /// Attempts to get the values, if present. If not, this returns false + /// and the value is undefined. Otherwise, this method returns true + /// and the actual value inside that variable. + /// + /// The value if contained in the entity. + /// The value if contained in the entity. + /// The value if contained in the entity. + /// The first component type. + /// The second component type. + /// The third component type. + /// True if found, otherwise false. + public bool TryGet(out T1 value1, out T2 value2, out T3 value3) + { + if (this.HasAll()) + { + value1 = this.Get(); + value2 = this.Get(); + value3 = this.Get(); - return true; - } + return true; + } - value1 = default!; - value2 = default!; - value3 = default!; + value1 = default!; + value2 = default!; + value3 = default!; - return false; - } + return false; + } - /// - /// Attempts to get the values, if present. If not, this returns false - /// and the value is undefined. Otherwise, this method returns true - /// and the actual value inside that variable. - /// - /// The value if contained in the entity. - /// The value if contained in the entity. - /// The value if contained in the entity. - /// The value if contained in the entity. - /// The first component type. - /// The second component type. - /// The third component type. - /// The fourth component type. - /// True if found, otherwise false. - public bool TryGet( - out T1 value1, - out T2 value2, - out T3 value3, - out T4 value4) - { - if (this.HasAll()) - { - value1 = this.Get(); - value2 = this.Get(); - value3 = this.Get(); - value4 = this.Get(); + /// + /// Attempts to get the values, if present. If not, this returns false + /// and the value is undefined. Otherwise, this method returns true + /// and the actual value inside that variable. + /// + /// The value if contained in the entity. + /// The value if contained in the entity. + /// The value if contained in the entity. + /// The value if contained in the entity. + /// The first component type. + /// The second component type. + /// The third component type. + /// The fourth component type. + /// True if found, otherwise false. + public bool TryGet(out T1 value1, out T2 value2, out T3 value3, out T4 value4) + { + if (this.HasAll()) + { + value1 = this.Get(); + value2 = this.Get(); + value3 = this.Get(); + value4 = this.Get(); - return true; - } + return true; + } - value1 = default!; - value2 = default!; - value3 = default!; - value4 = default!; + value1 = default!; + value2 = default!; + value3 = default!; + value4 = default!; - return false; - } + return false; + } - /// - /// Sets the component in the entity, regardless if there was a - /// component already registered. - /// - /// The component to register. - /// The component type. - /// The entity for chaining. - /// - public Entity Set(T1 component) - { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } + /// + /// Sets the component in the entity, regardless if there was a + /// component already registered. + /// + /// The component to register. + /// The component type. + /// The entity for chaining. + /// + public Entity Set(T1 component) + { + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } - if (this.Components.TryGetValue(typeof(T1), out object? value) - && value is T1 - && value.Equals(component)) - { - return this; - } + if ( + this.Components.TryGetValue(typeof(T1), out object? value) + && value is T1 + && value.Equals(component) + ) + { + return this; + } - return this with - { - Components = this.Components.SetItem(typeof(T1), component), - }; - } + return this with + { + Components = this.Components.SetItem(typeof(T1), component), + }; + } - /// - /// Sets zero or more components into an entity in a single call. This does - /// not allow for specifying the data type; each item will be added with - /// the result of `component.GetType()`. - /// - /// - /// The components to add to the entity. Any null objects - /// will be ignored. - /// - /// - /// A new Entity with the modified component collection if there is at - /// least one component to set, otherwise the same entity. - /// - public Entity SetAll(params object?[] components) - { - if (components.Length == 0) - { - return this; - } + /// + /// Sets zero or more components into an entity in a single call. This does + /// not allow for specifying the data type; each item will be added with + /// the result of `component.GetType()`. + /// + /// + /// The components to add to the entity. Any null objects + /// will be ignored. + /// + /// + /// A new Entity with the modified component collection if there is at + /// least one component to set, otherwise the same entity. + /// + public Entity SetAll(params object?[] components) + { + if (components.Length == 0) + { + return this; + } - ImmutableDictionary collection = this.Components; + ImmutableDictionary collection = this.Components; - foreach (object? component in components) - { - if (component != null) - { - collection = collection.SetItem(component.GetType(), component); - } - } + foreach (object? component in components) + { + if (component != null) + { + collection = collection.SetItem(component.GetType(), component); + } + } - return this with - { - Components = collection, - }; - } + return this with + { + Components = collection, + }; + } - /// - /// Adds a component to the entity. - /// - /// The component to register. - /// The component type. - /// - /// The same entity if the component is already registered, otherwise a - /// cloned entity with the new component. - /// - /// - public Entity Add(T1 component) - { - if (component == null) - { - throw new ArgumentNullException(nameof(component)); - } + /// + /// Adds a component to the entity. + /// + /// The component to register. + /// The component type. + /// + /// The same entity if the component is already registered, otherwise a + /// cloned entity with the new component. + /// + /// + public Entity Add(T1 component) + { + if (component == null) + { + throw new ArgumentNullException(nameof(component)); + } - if (this.Has()) - { - throw new ArgumentException( - "An element with the same type (" - + typeof(T1).FullName - + ") already exists.", - nameof(component)); - } + if (this.Has()) + { + throw new ArgumentException( + "An element with the same type (" + typeof(T1).FullName + ") already exists.", + nameof(component) + ); + } - if (this.Components.TryGetValue(typeof(T1), out object? value) - && value is T1 - && value.Equals(component)) - { - return this; - } + if ( + this.Components.TryGetValue(typeof(T1), out object? value) + && value is T1 + && value.Equals(component) + ) + { + return this; + } - return this with - { - Components = this.Components.Add(typeof(T1), component) - }; - } + return this with + { + Components = this.Components.Add(typeof(T1), component) + }; + } - /// - /// Removes a component to the entity. - /// - /// The component type. - /// - /// The same entity if the component is already removed, otherwise a - /// cloned entity without the new component. - /// - /// - public Entity Remove() - { - return this.Remove(typeof(TType)); - } + /// + /// Removes a component to the entity. + /// + /// The component type. + /// + /// The same entity if the component is already removed, otherwise a + /// cloned entity without the new component. + /// + /// + public Entity Remove() + { + return this.Remove(typeof(TType)); + } - /// - /// Removes a component to the entity. - /// - /// - /// The same entity if the component is already removed, otherwise a - /// cloned entity without the new component. - /// - /// The component type to remove. - public Entity Remove(Type type) - { - if (!this.Has(type)) - { - return this; - } + /// + /// Removes a component to the entity. + /// + /// + /// The same entity if the component is already removed, otherwise a + /// cloned entity without the new component. + /// + /// The component type to remove. + public Entity Remove(Type type) + { + if (!this.Has(type)) + { + return this; + } - return this with - { - Components = this.Components.Remove(type) - }; - } + return this with + { + Components = this.Components.Remove(type) + }; + } - /// - /// Gets the identifier of the entity. This should be treated as an - /// opaque field. - /// - public int Id { get; private init; } + /// + /// Gets the identifier of the entity. This should be treated as an + /// opaque field. + /// + public int Id { get; private init; } - /// - /// Creates a copy of the entity, including copying the identifier. - /// - /// - public Entity ExactCopy() - { - return this with { }; - } + /// + /// Creates a copy of the entity, including copying the identifier. + /// + /// + public Entity ExactCopy() + { + return this with { }; + } - /// - /// Creates a copy of the entity, including components, but with a new - /// identifier. - /// - /// - public Entity Copy() - { - return this with - { - Id = Interlocked.Increment(ref nextId) - }; - } + /// + /// Creates a copy of the entity, including components, but with a new + /// identifier. + /// + /// + public Entity Copy() + { + return this with { Id = Interlocked.Increment(ref nextId) }; + } - /// - /// Retrieves a list of the component types currently registered in the - /// Entity. - /// - /// An enumerable of the various component keys. - public IEnumerable GetComponentTypes() - { - return this.Components.Keys; - } + /// + /// Retrieves a list of the component types currently registered in the + /// Entity. + /// + /// An enumerable of the various component keys. + public IEnumerable GetComponentTypes() + { + return this.Components.Keys; + } - /// - public override string ToString() - { - return ToStringFormatter == null - ? $"Entity {this.Id} (Components {this.Components.Count:N0})" - : ToStringFormatter(this); - } + /// + public override string ToString() + { + return ToStringFormatter == null + ? $"Entity {this.Id} (Components {this.Components.Count:N0})" + : ToStringFormatter(this); + } } diff --git a/src/MfGames.Gallium/JoinEntityExtensions.cs b/src/MfGames.Gallium/JoinEntityExtensions.cs index 1053e41..ec4b25e 100644 --- a/src/MfGames.Gallium/JoinEntityExtensions.cs +++ b/src/MfGames.Gallium/JoinEntityExtensions.cs @@ -2,23 +2,24 @@ namespace MfGames.Gallium; public static class JoinEntityExtensions { - /// - /// Merges two sets of entities using the identifier to determine which - /// entities are the same. The `merge` function takes both of the - /// entities with the Entity from the `input` first and the one from - /// `other` second. The returning entity is put into the collection. If - /// an entity from the input is not found in other, then it is just - /// passed on. - /// - /// The enumerable of entities to merge to. - /// The collection of entities to merge from. - /// The callback to merge the two. - /// An sequence of entities, merged and unmerged. - public static IEnumerable JoinEntity( - this IEnumerable input, - ICollection other, - Func merge) - { - return input.Join(other, a => a.Id, a => a.Id, merge); - } + /// + /// Merges two sets of entities using the identifier to determine which + /// entities are the same. The `merge` function takes both of the + /// entities with the Entity from the `input` first and the one from + /// `other` second. The returning entity is put into the collection. If + /// an entity from the input is not found in other, then it is just + /// passed on. + /// + /// The enumerable of entities to merge to. + /// The collection of entities to merge from. + /// The callback to merge the two. + /// An sequence of entities, merged and unmerged. + public static IEnumerable JoinEntity( + this IEnumerable input, + ICollection other, + Func merge + ) + { + return input.Join(other, a => a.Id, a => a.Id, merge); + } } diff --git a/src/MfGames.Gallium/SelectComponentExtensions.cs b/src/MfGames.Gallium/SelectComponentExtensions.cs index fcf3126..1c1323c 100644 --- a/src/MfGames.Gallium/SelectComponentExtensions.cs +++ b/src/MfGames.Gallium/SelectComponentExtensions.cs @@ -5,43 +5,40 @@ namespace MfGames.Gallium; /// public static class SelectComponentExtensions { - /// - /// Retrieves a component from an entity and return it. If the entity does not have - /// the component, it will be - /// filtered out. - /// - /// The entities to process. - /// The component type being searched. - /// A sequence of T1. - public static IEnumerable SelectComponent( - this IEnumerable entities) - { - foreach (Entity entity in entities) - { - if (entity.TryGet(out T1 v1)) - { - yield return v1; - } - } - } + /// + /// Retrieves a component from an entity and return it. If the entity does not have + /// the component, it will be + /// filtered out. + /// + /// The entities to process. + /// The component type being searched. + /// A sequence of T1. + public static IEnumerable SelectComponent(this IEnumerable entities) + { + foreach (Entity entity in entities) + { + if (entity.TryGet(out T1 v1)) + { + yield return v1; + } + } + } - /// - /// Retrieves a component from an entity and return it. If the entity does not have - /// the component, it will be filtered out. - /// - /// The entities to process. - /// The component type being searched. - /// A sequence of T1. - public static IEnumerable SelectComponent( - IEnumerable entities, - Type t1) - { - foreach (Entity entity in entities) - { - if (entity.Has(t1)) - { - yield return entity.Get(t1); - } - } - } + /// + /// Retrieves a component from an entity and return it. If the entity does not have + /// the component, it will be filtered out. + /// + /// The entities to process. + /// The component type being searched. + /// A sequence of T1. + public static IEnumerable SelectComponent(IEnumerable entities, Type t1) + { + foreach (Entity entity in entities) + { + if (entity.Has(t1)) + { + yield return entity.Get(t1); + } + } + } } diff --git a/src/MfGames.Gallium/SelectComponentOrDefaultExtensions.cs b/src/MfGames.Gallium/SelectComponentOrDefaultExtensions.cs index 958b3f4..0267681 100644 --- a/src/MfGames.Gallium/SelectComponentOrDefaultExtensions.cs +++ b/src/MfGames.Gallium/SelectComponentOrDefaultExtensions.cs @@ -5,46 +5,43 @@ namespace MfGames.Gallium; /// public static class SelectComponentOrDefaultExtensions { - /// - /// Retrieves a component from an entity and return it. If the entity does not have - /// the component, then null will be returned. - /// - /// The entities to process. - /// The component type being searched. - /// A sequence of T1 or nulls. - public static IEnumerable SelectComponent( - IEnumerable entities, - Type t1) - { - foreach (Entity entity in entities) - { - if (entity.Has(t1)) - { - yield return entity.Get(t1); - } + /// + /// Retrieves a component from an entity and return it. If the entity does not have + /// the component, then null will be returned. + /// + /// The entities to process. + /// The component type being searched. + /// A sequence of T1 or nulls. + public static IEnumerable SelectComponent(IEnumerable entities, Type t1) + { + foreach (Entity entity in entities) + { + if (entity.Has(t1)) + { + yield return entity.Get(t1); + } - yield return null; - } - } + yield return null; + } + } - /// - /// Retrieves a component from an entity and return it. If the entity does not have - /// the component, then the default value will be returned. - /// - /// The entities to process. - /// The component type being searched. - /// A sequence of T1. - public static IEnumerable SelectComponentOrDefault( - this IEnumerable entities) - { - foreach (Entity entity in entities) - { - if (entity.TryGet(out T1 v1)) - { - yield return v1; - } + /// + /// Retrieves a component from an entity and return it. If the entity does not have + /// the component, then the default value will be returned. + /// + /// The entities to process. + /// The component type being searched. + /// A sequence of T1. + public static IEnumerable SelectComponentOrDefault(this IEnumerable entities) + { + foreach (Entity entity in entities) + { + if (entity.TryGet(out T1 v1)) + { + yield return v1; + } - yield return default; - } - } + yield return default; + } + } } diff --git a/src/MfGames.Gallium/SelectEntityExtensions.cs b/src/MfGames.Gallium/SelectEntityExtensions.cs index 95f22bf..0d0c193 100644 --- a/src/MfGames.Gallium/SelectEntityExtensions.cs +++ b/src/MfGames.Gallium/SelectEntityExtensions.cs @@ -2,276 +2,279 @@ namespace MfGames.Gallium; public static class SelectEntityExtensions { - /// - /// Selects an entity from the given list, filtering on entities with - /// the given components. - /// - /// The entities to parse. - /// - /// The transformation function for the entity and selected components. If this - /// returns null, then the entity - /// will be filtered out. - /// - /// - /// If true, then entities without all the components are included. Otherwise, they - /// are excluded. - /// - /// The type of the first component. - /// An enumeration of transformed entities. - public static IEnumerable SelectEntity( - this IEnumerable entities, - Func selectWithComponents, - bool includeEntitiesWithoutComponents = true) - { - return entities.SelectEntity( - selectWithComponents, - includeEntitiesWithoutComponents ? a => a : a => null); - } + /// + /// Selects an entity from the given list, filtering on entities with + /// the given components. + /// + /// The entities to parse. + /// + /// The transformation function for the entity and selected components. If this + /// returns null, then the entity + /// will be filtered out. + /// + /// + /// If true, then entities without all the components are included. Otherwise, they + /// are excluded. + /// + /// The type of the first component. + /// An enumeration of transformed entities. + public static IEnumerable SelectEntity( + this IEnumerable entities, + Func selectWithComponents, + bool includeEntitiesWithoutComponents = true + ) + { + return entities.SelectEntity( + selectWithComponents, + includeEntitiesWithoutComponents ? a => a : a => null + ); + } - /// - /// Selects an entity from the given list, filtering on entities with - /// the given components. - /// - /// The entities to parse. - /// - /// The transformation function for the entity and selected components. If this - /// returns null, then the entity - /// will be filtered out. - /// - /// - /// If true, then entities without all the components are included. Otherwise, they - /// are excluded. - /// - /// The type of the first component. - /// The type of the second component. - /// An enumeration of transformed entities. - public static IEnumerable SelectEntity( - this IEnumerable entities, - Func selectWithComponents, - bool includeEntitiesWithoutComponents = true) - { - return entities.SelectEntity( - selectWithComponents, - includeEntitiesWithoutComponents ? a => a : a => null); - } + /// + /// Selects an entity from the given list, filtering on entities with + /// the given components. + /// + /// The entities to parse. + /// + /// The transformation function for the entity and selected components. If this + /// returns null, then the entity + /// will be filtered out. + /// + /// + /// If true, then entities without all the components are included. Otherwise, they + /// are excluded. + /// + /// The type of the first component. + /// The type of the second component. + /// An enumeration of transformed entities. + public static IEnumerable SelectEntity( + this IEnumerable entities, + Func selectWithComponents, + bool includeEntitiesWithoutComponents = true + ) + { + return entities.SelectEntity( + selectWithComponents, + includeEntitiesWithoutComponents ? a => a : a => null + ); + } - /// - /// Selects an entity from the given list, filtering on entities with - /// the given components. - /// - /// The entities to parse. - /// - /// The transformation function for the entity and selected components. If this - /// returns null, then the entity - /// will be filtered out. - /// - /// - /// If true, then entities without all the components are included. Otherwise, they - /// are excluded. - /// - /// The type of the first component. - /// The type of the second component. - /// The type of the third component. - /// An enumeration of transformed entities. - public static IEnumerable SelectEntity( - this IEnumerable entities, - Func selectWithComponents, - bool includeEntitiesWithoutComponents = true) - { - return entities.SelectEntity( - selectWithComponents, - includeEntitiesWithoutComponents ? a => a : a => null); - } + /// + /// Selects an entity from the given list, filtering on entities with + /// the given components. + /// + /// The entities to parse. + /// + /// The transformation function for the entity and selected components. If this + /// returns null, then the entity + /// will be filtered out. + /// + /// + /// If true, then entities without all the components are included. Otherwise, they + /// are excluded. + /// + /// The type of the first component. + /// The type of the second component. + /// The type of the third component. + /// An enumeration of transformed entities. + public static IEnumerable SelectEntity( + this IEnumerable entities, + Func selectWithComponents, + bool includeEntitiesWithoutComponents = true + ) + { + return entities.SelectEntity( + selectWithComponents, + includeEntitiesWithoutComponents ? a => a : a => null + ); + } - /// - /// Selects an entity from the given list, filtering on entities with - /// the given components. - /// - /// The entities to parse. - /// - /// The transformation function for the entity and selected components. If this - /// returns null, then the entity - /// will be filtered out. - /// - /// - /// If true, then entities without all the components are included. Otherwise, they - /// are excluded. - /// - /// The type of the first component. - /// The type of the second component. - /// The type of the third component. - /// The type of the fourth component. - /// An enumeration of transformed entities. - public static IEnumerable SelectEntity( - this IEnumerable entities, - Func selectWithComponents, - bool includeEntitiesWithoutComponents = true) - { - return entities.SelectEntity( - selectWithComponents, - includeEntitiesWithoutComponents ? a => a : a => null); - } + /// + /// Selects an entity from the given list, filtering on entities with + /// the given components. + /// + /// The entities to parse. + /// + /// The transformation function for the entity and selected components. If this + /// returns null, then the entity + /// will be filtered out. + /// + /// + /// If true, then entities without all the components are included. Otherwise, they + /// are excluded. + /// + /// The type of the first component. + /// The type of the second component. + /// The type of the third component. + /// The type of the fourth component. + /// An enumeration of transformed entities. + public static IEnumerable SelectEntity( + this IEnumerable entities, + Func selectWithComponents, + bool includeEntitiesWithoutComponents = true + ) + { + return entities.SelectEntity( + selectWithComponents, + includeEntitiesWithoutComponents ? a => a : a => null + ); + } - /// - /// Selects an entity from the given list, filtering on entities with - /// the given components. - /// - /// The entities to parse. - /// - /// The transformation function for the entity and selected components. If this - /// returns null, then the entity - /// will be filtered out. - /// - /// - /// The optional transformation function for entities that do not have all the - /// components. If returns null, - /// then the entity will not be included. - /// - /// The type of the first component. - /// An enumeration of transformed entities. - public static IEnumerable SelectEntity( - this IEnumerable entities, - Func selectWithComponents, - Func selectWithoutComponents) - { - foreach (Entity entity in entities) - { - Entity? result = entity.TryGet(out T1 value1) - ? selectWithComponents?.Invoke(entity, value1) - : selectWithoutComponents?.Invoke(entity); + /// + /// Selects an entity from the given list, filtering on entities with + /// the given components. + /// + /// The entities to parse. + /// + /// The transformation function for the entity and selected components. If this + /// returns null, then the entity + /// will be filtered out. + /// + /// + /// The optional transformation function for entities that do not have all the + /// components. If returns null, + /// then the entity will not be included. + /// + /// The type of the first component. + /// An enumeration of transformed entities. + public static IEnumerable SelectEntity( + this IEnumerable entities, + Func selectWithComponents, + Func selectWithoutComponents + ) + { + foreach (Entity entity in entities) + { + Entity? result = entity.TryGet(out T1 value1) + ? selectWithComponents?.Invoke(entity, value1) + : selectWithoutComponents?.Invoke(entity); - if (result != null) - { - yield return result; - } - } - } + if (result != null) + { + yield return result; + } + } + } - /// - /// Selects an entity from the given list, filtering on entities with - /// the given components. - /// - /// The entities to parse. - /// - /// The transformation function for the entity and selected components. If this - /// returns null, then the entity - /// will be filtered out. - /// - /// - /// The optional transformation function for entities that do not have all the - /// components. If returns null, - /// then the entity will not be included. - /// - /// The type of the first component. - /// The type of the second component. - /// An enumeration of transformed entities. - public static IEnumerable SelectEntity( - this IEnumerable entities, - Func selectWithComponents, - Func selectWithoutComponents) - { - foreach (Entity entity in entities) - { - Entity? result = entity.TryGet(out T1 value1) - && entity.TryGet(out T2 value2) - ? selectWithComponents?.Invoke(entity, value1, value2) - : selectWithoutComponents?.Invoke(entity); + /// + /// Selects an entity from the given list, filtering on entities with + /// the given components. + /// + /// The entities to parse. + /// + /// The transformation function for the entity and selected components. If this + /// returns null, then the entity + /// will be filtered out. + /// + /// + /// The optional transformation function for entities that do not have all the + /// components. If returns null, + /// then the entity will not be included. + /// + /// The type of the first component. + /// The type of the second component. + /// An enumeration of transformed entities. + public static IEnumerable SelectEntity( + this IEnumerable entities, + Func selectWithComponents, + Func selectWithoutComponents + ) + { + foreach (Entity entity in entities) + { + Entity? result = + entity.TryGet(out T1 value1) && entity.TryGet(out T2 value2) + ? selectWithComponents?.Invoke(entity, value1, value2) + : selectWithoutComponents?.Invoke(entity); - if (result != null) - { - yield return result; - } - } - } + if (result != null) + { + yield return result; + } + } + } - /// - /// Selects an entity from the given list, filtering on entities with - /// the given components. - /// - /// The entities to parse. - /// - /// The transformation function for the entity and selected components. If this - /// returns null, then the entity - /// will be filtered out. - /// - /// - /// The optional transformation function for entities that do not have all the - /// components. If returns null, - /// then the entity will not be included. - /// - /// The type of the first component. - /// The type of the second component. - /// The type of the third component. - /// An enumeration of transformed entities. - public static IEnumerable SelectEntity( - this IEnumerable entities, - Func selectWithComponents, - Func selectWithoutComponents) - { - foreach (Entity entity in entities) - { - Entity? result = - entity.TryGet(out T1 value1) - && entity.TryGet(out T2 value2) - && entity.TryGet(out T3 value3) - ? selectWithComponents?.Invoke( - entity, - value1, - value2, - value3) - : selectWithoutComponents?.Invoke(entity); + /// + /// Selects an entity from the given list, filtering on entities with + /// the given components. + /// + /// The entities to parse. + /// + /// The transformation function for the entity and selected components. If this + /// returns null, then the entity + /// will be filtered out. + /// + /// + /// The optional transformation function for entities that do not have all the + /// components. If returns null, + /// then the entity will not be included. + /// + /// The type of the first component. + /// The type of the second component. + /// The type of the third component. + /// An enumeration of transformed entities. + public static IEnumerable SelectEntity( + this IEnumerable entities, + Func selectWithComponents, + Func selectWithoutComponents + ) + { + foreach (Entity entity in entities) + { + Entity? result = + entity.TryGet(out T1 value1) + && entity.TryGet(out T2 value2) + && entity.TryGet(out T3 value3) + ? selectWithComponents?.Invoke(entity, value1, value2, value3) + : selectWithoutComponents?.Invoke(entity); - if (result != null) - { - yield return result; - } - } - } + if (result != null) + { + yield return result; + } + } + } - /// - /// Selects an entity from the given list, filtering on entities with - /// the given components. - /// - /// The entities to parse. - /// - /// The transformation function for the entity and selected components. If this - /// returns null, then the entity - /// will be filtered out. - /// - /// - /// The optional transformation function for entities that do not have all the - /// components. If returns null, - /// then the entity will not be included. - /// - /// The type of the first component. - /// The type of the second component. - /// The type of the third component. - /// The type of the third component. - /// An enumeration of transformed entities. - public static IEnumerable SelectEntity( - this IEnumerable entities, - Func selectWithComponents, - Func selectWithoutComponents) - { - foreach (Entity entity in entities) - { - Entity? result = - entity.TryGet(out T1 value1) - && entity.TryGet(out T2 value2) - && entity.TryGet(out T3 value3) - && entity.TryGet(out T4 value4) - ? selectWithComponents?.Invoke( - entity, - value1, - value2, - value3, - value4) - : selectWithoutComponents?.Invoke(entity); + /// + /// Selects an entity from the given list, filtering on entities with + /// the given components. + /// + /// The entities to parse. + /// + /// The transformation function for the entity and selected components. If this + /// returns null, then the entity + /// will be filtered out. + /// + /// + /// The optional transformation function for entities that do not have all the + /// components. If returns null, + /// then the entity will not be included. + /// + /// The type of the first component. + /// The type of the second component. + /// The type of the third component. + /// The type of the third component. + /// An enumeration of transformed entities. + public static IEnumerable SelectEntity( + this IEnumerable entities, + Func selectWithComponents, + Func selectWithoutComponents + ) + { + foreach (Entity entity in entities) + { + Entity? result = + entity.TryGet(out T1 value1) + && entity.TryGet(out T2 value2) + && entity.TryGet(out T3 value3) + && entity.TryGet(out T4 value4) + ? selectWithComponents?.Invoke(entity, value1, value2, value3, value4) + : selectWithoutComponents?.Invoke(entity); - if (result != null) - { - yield return result; - } - } - } + if (result != null) + { + yield return result; + } + } + } } diff --git a/src/MfGames.Gallium/SelectManyEntityExtensions.cs b/src/MfGames.Gallium/SelectManyEntityExtensions.cs index 3ab5860..604b796 100644 --- a/src/MfGames.Gallium/SelectManyEntityExtensions.cs +++ b/src/MfGames.Gallium/SelectManyEntityExtensions.cs @@ -9,141 +9,145 @@ namespace MfGames.Gallium; /// public static class SelectManyEntityExtensions { - /// - /// Pulls out all the entities that match the given components into an enumeration, - /// passes it into the callback - /// function, and then optionally merges the entities that did not match before - /// returning. - /// - /// The entities to process - /// - /// The callback function to manipulate the list of - /// entities. - /// - /// - /// If true, the include entities - /// without components. - /// - /// The type of the first component. - /// An enumeration of entities. - public static IEnumerable SelectManyEntity( - this IEnumerable entities, - Func, IEnumerable> selectMany, - bool includeEntitiesWithoutComponents = true) - { - SplitEntityEnumerations split = entities.SplitEntity(); - IEnumerable results = selectMany(split.HasAll); + /// + /// Pulls out all the entities that match the given components into an enumeration, + /// passes it into the callback + /// function, and then optionally merges the entities that did not match before + /// returning. + /// + /// The entities to process + /// + /// The callback function to manipulate the list of + /// entities. + /// + /// + /// If true, the include entities + /// without components. + /// + /// The type of the first component. + /// An enumeration of entities. + public static IEnumerable SelectManyEntity( + this IEnumerable entities, + Func, IEnumerable> selectMany, + bool includeEntitiesWithoutComponents = true + ) + { + SplitEntityEnumerations split = entities.SplitEntity(); + IEnumerable results = selectMany(split.HasAll); - if (includeEntitiesWithoutComponents) - { - results = results.Union(split.NotHasAll); - } + if (includeEntitiesWithoutComponents) + { + results = results.Union(split.NotHasAll); + } - return results; - } + return results; + } - /// - /// Pulls out all the entities that match the given components into an enumeration, - /// passes it into the callback - /// function, and then optionally merges the entities that did not match before - /// returning. - /// - /// The entities to process - /// - /// The callback function to manipulate the list of - /// entities. - /// - /// - /// If true, the include entities - /// without components. - /// - /// The type of the first component. - /// The type of the second component. - /// An enumeration of entities. - public static IEnumerable SelectManyEntity( - this IEnumerable entities, - Func, IEnumerable> selectMany, - bool includeEntitiesWithoutComponents = true) - { - SplitEntityEnumerations split = entities.SplitEntity(); - IEnumerable results = selectMany(split.HasAll); + /// + /// Pulls out all the entities that match the given components into an enumeration, + /// passes it into the callback + /// function, and then optionally merges the entities that did not match before + /// returning. + /// + /// The entities to process + /// + /// The callback function to manipulate the list of + /// entities. + /// + /// + /// If true, the include entities + /// without components. + /// + /// The type of the first component. + /// The type of the second component. + /// An enumeration of entities. + public static IEnumerable SelectManyEntity( + this IEnumerable entities, + Func, IEnumerable> selectMany, + bool includeEntitiesWithoutComponents = true + ) + { + SplitEntityEnumerations split = entities.SplitEntity(); + IEnumerable results = selectMany(split.HasAll); - if (includeEntitiesWithoutComponents) - { - results = results.Union(split.NotHasAll); - } + if (includeEntitiesWithoutComponents) + { + results = results.Union(split.NotHasAll); + } - return results; - } + return results; + } - /// - /// Pulls out all the entities that match the given components into an enumeration, - /// passes it into the callback - /// function, and then optionally merges the entities that did not match before - /// returning. - /// - /// The entities to process - /// - /// The callback function to manipulate the list of - /// entities. - /// - /// - /// If true, the include entities - /// without components. - /// - /// The type of the first component. - /// The type of the second component. - /// The type of the second component. - /// An enumeration of entities. - public static IEnumerable SelectManyEntity( - this IEnumerable entities, - Func, IEnumerable> selectMany, - bool includeEntitiesWithoutComponents = true) - { - SplitEntityEnumerations split = entities.SplitEntity(); - IEnumerable results = selectMany(split.HasAll); + /// + /// Pulls out all the entities that match the given components into an enumeration, + /// passes it into the callback + /// function, and then optionally merges the entities that did not match before + /// returning. + /// + /// The entities to process + /// + /// The callback function to manipulate the list of + /// entities. + /// + /// + /// If true, the include entities + /// without components. + /// + /// The type of the first component. + /// The type of the second component. + /// The type of the second component. + /// An enumeration of entities. + public static IEnumerable SelectManyEntity( + this IEnumerable entities, + Func, IEnumerable> selectMany, + bool includeEntitiesWithoutComponents = true + ) + { + SplitEntityEnumerations split = entities.SplitEntity(); + IEnumerable results = selectMany(split.HasAll); - if (includeEntitiesWithoutComponents) - { - results = results.Union(split.NotHasAll); - } + if (includeEntitiesWithoutComponents) + { + results = results.Union(split.NotHasAll); + } - return results; - } + return results; + } - /// - /// Pulls out all the entities that match the given components into an enumeration, - /// passes it into the callback - /// function, and then optionally merges the entities that did not match before - /// returning. - /// - /// The entities to process - /// - /// The callback function to manipulate the list of - /// entities. - /// - /// - /// If true, the include entities - /// without components. - /// - /// The type of the first component. - /// The type of the second component. - /// The type of the second component. - /// The type of the second component. - /// An enumeration of entities. - public static IEnumerable SelectManyEntity( - this IEnumerable entities, - Func, IEnumerable> selectMany, - bool includeEntitiesWithoutComponents = true) - { - SplitEntityEnumerations split = entities.SplitEntity(); - IEnumerable results = selectMany(split.HasAll); + /// + /// Pulls out all the entities that match the given components into an enumeration, + /// passes it into the callback + /// function, and then optionally merges the entities that did not match before + /// returning. + /// + /// The entities to process + /// + /// The callback function to manipulate the list of + /// entities. + /// + /// + /// If true, the include entities + /// without components. + /// + /// The type of the first component. + /// The type of the second component. + /// The type of the second component. + /// The type of the second component. + /// An enumeration of entities. + public static IEnumerable SelectManyEntity( + this IEnumerable entities, + Func, IEnumerable> selectMany, + bool includeEntitiesWithoutComponents = true + ) + { + SplitEntityEnumerations split = entities.SplitEntity(); + IEnumerable results = selectMany(split.HasAll); - if (includeEntitiesWithoutComponents) - { - results = results.Union(split.NotHasAll); - } + if (includeEntitiesWithoutComponents) + { + results = results.Union(split.NotHasAll); + } - return results; - } + return results; + } } diff --git a/src/MfGames.Gallium/SplitEntityEnumerations.cs b/src/MfGames.Gallium/SplitEntityEnumerations.cs index 21340fb..3e363b7 100644 --- a/src/MfGames.Gallium/SplitEntityEnumerations.cs +++ b/src/MfGames.Gallium/SplitEntityEnumerations.cs @@ -1,16 +1,14 @@ namespace MfGames.Gallium; -public record SplitEntityEnumerations( - IEnumerable HasAll, - IEnumerable NotHasAll) +public record SplitEntityEnumerations(IEnumerable HasAll, IEnumerable NotHasAll) { - /// - /// Gets a sequence of all entities that have all the given components. - /// - public IEnumerable HasAll { get; } = HasAll; + /// + /// Gets a sequence of all entities that have all the given components. + /// + public IEnumerable HasAll { get; } = HasAll; - /// - /// Gets the sequence of all entities that do not have all the given components. - /// - public IEnumerable NotHasAll { get; } = NotHasAll; + /// + /// Gets the sequence of all entities that do not have all the given components. + /// + public IEnumerable NotHasAll { get; } = NotHasAll; } diff --git a/src/MfGames.Gallium/SplitEntityExtensions.cs b/src/MfGames.Gallium/SplitEntityExtensions.cs index 23b0373..2dbb5dc 100644 --- a/src/MfGames.Gallium/SplitEntityExtensions.cs +++ b/src/MfGames.Gallium/SplitEntityExtensions.cs @@ -7,290 +7,259 @@ namespace MfGames.Gallium; /// public static class SplitEntityExtensions { - /// - /// Splits the enumeration of entities into two separate enumerations, ones that - /// have the given generic components - /// and those which do not. - /// - /// The entities to split into two lists. - /// - /// An additional test function to determine if the entity is - /// included in the has list. If null, then entities with all the components will - /// be included. - /// - /// - /// A component to require to be in included in the first - /// list. - /// - /// A pair of enumerations, ones with the components and ones without. - public static SplitEntityEnumerations SplitEntity - ( - this IEnumerable entities, - Func? test = null) - { - test ??= ( - e, - v1) => true; + /// + /// Splits the enumeration of entities into two separate enumerations, ones that + /// have the given generic components + /// and those which do not. + /// + /// The entities to split into two lists. + /// + /// An additional test function to determine if the entity is + /// included in the has list. If null, then entities with all the components will + /// be included. + /// + /// + /// A component to require to be in included in the first + /// list. + /// + /// A pair of enumerations, ones with the components and ones without. + public static SplitEntityEnumerations SplitEntity( + this IEnumerable entities, + Func? test = null + ) + { + test ??= (e, v1) => true; - return entities.SplitEntity( - typeof(T1), - ( - e, - v1) => test(e, (T1)v1)); - } + return entities.SplitEntity(typeof(T1), (e, v1) => test(e, (T1)v1)); + } - /// - /// Splits the enumeration of entities into two separate enumerations, ones that - /// have the given generic components - /// and those which do not. - /// - /// The entities to split into two lists. - /// - /// An additional test function to determine if the entity is - /// included in the has list. If null, then entities with all the components will - /// be included. - /// - /// - /// A component to require to be in included in the first list. - /// - /// - /// A component to require to be in included in the first list. - /// - /// A pair of enumerations, ones with the components and ones without. - public static SplitEntityEnumerations SplitEntity - ( - this IEnumerable entities, - Func? test = null) - { - test ??= ( - e, - v1, - v2) => true; + /// + /// Splits the enumeration of entities into two separate enumerations, ones that + /// have the given generic components + /// and those which do not. + /// + /// The entities to split into two lists. + /// + /// An additional test function to determine if the entity is + /// included in the has list. If null, then entities with all the components will + /// be included. + /// + /// + /// A component to require to be in included in the first list. + /// + /// + /// A component to require to be in included in the first list. + /// + /// A pair of enumerations, ones with the components and ones without. + public static SplitEntityEnumerations SplitEntity( + this IEnumerable entities, + Func? test = null + ) + { + test ??= (e, v1, v2) => true; - return entities.SplitEntity( - typeof(T1), - typeof(T2), - ( - e, - v1, - v2) => test(e, (T1)v1, (T2)v2)); - } + return entities.SplitEntity(typeof(T1), typeof(T2), (e, v1, v2) => test(e, (T1)v1, (T2)v2)); + } - /// - /// Splits the enumeration of entities into two separate enumerations, ones that - /// have the given generic components - /// and those which do not. - /// - /// The entities to split into two lists. - /// - /// An additional test function to determine if the entity is - /// included in the has list. If null, then entities with all the components will - /// be included. - /// - /// - /// A component to require to be in included in the first list. - /// - /// - /// A component to require to be in included in the first list. - /// - /// - /// A component to require to be in included in the first list. - /// - /// A pair of enumerations, ones with the components and ones without. - public static SplitEntityEnumerations SplitEntity - ( - this IEnumerable entities, - Func? test = null) - { - test ??= ( - e, - v1, - v2, - v3) => true; + /// + /// Splits the enumeration of entities into two separate enumerations, ones that + /// have the given generic components + /// and those which do not. + /// + /// The entities to split into two lists. + /// + /// An additional test function to determine if the entity is + /// included in the has list. If null, then entities with all the components will + /// be included. + /// + /// + /// A component to require to be in included in the first list. + /// + /// + /// A component to require to be in included in the first list. + /// + /// + /// A component to require to be in included in the first list. + /// + /// A pair of enumerations, ones with the components and ones without. + public static SplitEntityEnumerations SplitEntity( + this IEnumerable entities, + Func? test = null + ) + { + test ??= (e, v1, v2, v3) => true; - return entities.SplitEntity( - typeof(T1), - typeof(T2), - typeof(T3), - ( - e, - v1, - v2, - v3) => test(e, (T1)v1, (T2)v2, (T3)v3)); - } + return entities.SplitEntity( + typeof(T1), + typeof(T2), + typeof(T3), + (e, v1, v2, v3) => test(e, (T1)v1, (T2)v2, (T3)v3) + ); + } - /// - /// Splits the enumeration of entities into two separate enumerations, ones that - /// have the given generic components - /// and those which do not. - /// - /// The entities to split into two lists. - /// - /// An additional test function to determine if the entity is - /// included in the has list. If null, then entities with all the components will - /// be included. - /// - /// - /// A component to require to be in included in the first list. - /// - /// - /// A component to require to be in included in the first list. - /// - /// - /// A component to require to be in included in the first list. - /// - /// - /// A component to require to be in included in the first list. - /// - /// A pair of enumerations, ones with the components and ones without. - public static SplitEntityEnumerations SplitEntity - ( - this IEnumerable entities, - Func? test = null) - { - test ??= ( - e, - v1, - v2, - v3, - v4) => true; + /// + /// Splits the enumeration of entities into two separate enumerations, ones that + /// have the given generic components + /// and those which do not. + /// + /// The entities to split into two lists. + /// + /// An additional test function to determine if the entity is + /// included in the has list. If null, then entities with all the components will + /// be included. + /// + /// + /// A component to require to be in included in the first list. + /// + /// + /// A component to require to be in included in the first list. + /// + /// + /// A component to require to be in included in the first list. + /// + /// + /// A component to require to be in included in the first list. + /// + /// A pair of enumerations, ones with the components and ones without. + public static SplitEntityEnumerations SplitEntity( + this IEnumerable entities, + Func? test = null + ) + { + test ??= (e, v1, v2, v3, v4) => true; - return entities.SplitEntity( - typeof(T1), - typeof(T2), - typeof(T3), - typeof(T4), - ( - e, - v1, - v2, - v3, - v4) => test(e, (T1)v1, (T2)v2, (T3)v3, (T4)v4)); - } + return entities.SplitEntity( + typeof(T1), + typeof(T2), + typeof(T3), + typeof(T4), + (e, v1, v2, v3, v4) => test(e, (T1)v1, (T2)v2, (T3)v3, (T4)v4) + ); + } - /// - /// Splits the enumeration of entities into two separate enumerations, ones that - /// have the given component types and those which do not. - /// - /// The entities to split into two lists. - /// The type of a required component. - /// - /// An additional test function to determine if the entity is - /// included in the has list. If null, then entities with all the components will - /// be included. - /// - /// A pair of enumerations, ones with the components and ones without. - public static SplitEntityEnumerations SplitEntity( - this IEnumerable entities, - Type t1, - Func test) - { - return SplitEntity( - entities, - a => a.Has(t1) && test(a, a.Get(t1))); - } + /// + /// Splits the enumeration of entities into two separate enumerations, ones that + /// have the given component types and those which do not. + /// + /// The entities to split into two lists. + /// The type of a required component. + /// + /// An additional test function to determine if the entity is + /// included in the has list. If null, then entities with all the components will + /// be included. + /// + /// A pair of enumerations, ones with the components and ones without. + public static SplitEntityEnumerations SplitEntity( + this IEnumerable entities, + Type t1, + Func test + ) + { + return SplitEntity(entities, a => a.Has(t1) && test(a, a.Get(t1))); + } - /// - /// Splits the enumeration of entities into two separate enumerations, ones that - /// have the given component types and those which do not. - /// - /// The entities to split into two lists. - /// The type of a required component. - /// The type of a required component. - /// - /// An additional test function to determine if the entity is - /// included in the has list. If null, then entities with all the components will - /// be included. - /// - /// A pair of enumerations, ones with the components and ones without. - public static SplitEntityEnumerations SplitEntity( - this IEnumerable entities, - Type t1, - Type t2, - Func test) - { - return SplitEntity(entities, a => a.HasAll(t1, t2)); - } + /// + /// Splits the enumeration of entities into two separate enumerations, ones that + /// have the given component types and those which do not. + /// + /// The entities to split into two lists. + /// The type of a required component. + /// The type of a required component. + /// + /// An additional test function to determine if the entity is + /// included in the has list. If null, then entities with all the components will + /// be included. + /// + /// A pair of enumerations, ones with the components and ones without. + public static SplitEntityEnumerations SplitEntity( + this IEnumerable entities, + Type t1, + Type t2, + Func test + ) + { + return SplitEntity(entities, a => a.HasAll(t1, t2)); + } - /// - /// Splits the enumeration of entities into two separate enumerations, ones that - /// have the given component types and those which do not. - /// - /// The entities to split into two lists. - /// The type of a required component. - /// The type of a required component. - /// The type of a required component. - /// - /// An additional test function to determine if the entity is - /// included in the has list. If null, then entities with all the components will - /// be included. - /// - /// A pair of enumerations, ones with the components and ones without. - public static SplitEntityEnumerations SplitEntity( - this IEnumerable entities, - Type t1, - Type t2, - Type t3, - Func test) - { - return SplitEntity(entities, a => a.HasAll(t1, t2, t3)); - } + /// + /// Splits the enumeration of entities into two separate enumerations, ones that + /// have the given component types and those which do not. + /// + /// The entities to split into two lists. + /// The type of a required component. + /// The type of a required component. + /// The type of a required component. + /// + /// An additional test function to determine if the entity is + /// included in the has list. If null, then entities with all the components will + /// be included. + /// + /// A pair of enumerations, ones with the components and ones without. + public static SplitEntityEnumerations SplitEntity( + this IEnumerable entities, + Type t1, + Type t2, + Type t3, + Func test + ) + { + return SplitEntity(entities, a => a.HasAll(t1, t2, t3)); + } - /// - /// Splits the enumeration of entities into two separate enumerations, ones that - /// have the given component types and those which do not. - /// - /// The entities to split into two lists. - /// The type of a required component. - /// The type of a required component. - /// The type of a required component. - /// The type of a required component. - /// - /// An additional test function to determine if the entity is - /// included in the has list. If null, then entities with all the components will - /// be included. - /// - /// A pair of enumerations, ones with the components and ones without. - public static SplitEntityEnumerations SplitEntity( - this IEnumerable entities, - Type t1, - Type t2, - Type t3, - Type t4, - Func test) - { - return SplitEntity( - entities, - a => a.HasAll(t1, t2, t3, t4) - && test( - a, - a.Get(t1), - a.Get(t2), - a.Get(t3), - a.Get(t4))); - } + /// + /// Splits the enumeration of entities into two separate enumerations, ones that + /// have the given component types and those which do not. + /// + /// The entities to split into two lists. + /// The type of a required component. + /// The type of a required component. + /// The type of a required component. + /// The type of a required component. + /// + /// An additional test function to determine if the entity is + /// included in the has list. If null, then entities with all the components will + /// be included. + /// + /// A pair of enumerations, ones with the components and ones without. + public static SplitEntityEnumerations SplitEntity( + this IEnumerable entities, + Type t1, + Type t2, + Type t3, + Type t4, + Func test + ) + { + return SplitEntity( + entities, + a => + a.HasAll(t1, t2, t3, t4) + && test( + a, + a.Get(t1), + a.Get(t2), + a.Get(t3), + a.Get(t4) + ) + ); + } - private static SplitEntityEnumerations SplitEntity( - IEnumerable entities, - Func keySelector) - { - if (entities == null) - { - throw new ArgumentNullException(nameof(entities)); - } + private static SplitEntityEnumerations SplitEntity( + IEnumerable entities, + Func keySelector + ) + { + if (entities == null) + { + throw new ArgumentNullException(nameof(entities)); + } - IEnumerable> group = entities - .GroupBy(keySelector, a => a) - .ToList(); + IEnumerable> group = entities.GroupBy(keySelector, a => a).ToList(); - IEnumerable? has = group - .Where(a => a.Key) - .SelectMany(a => a); + IEnumerable? has = group.Where(a => a.Key).SelectMany(a => a); - IEnumerable? hasNot = group - .Where(a => !a.Key) - .SelectMany(a => a); + IEnumerable? hasNot = group.Where(a => !a.Key).SelectMany(a => a); - return new SplitEntityEnumerations(has, hasNot); - } + return new SplitEntityEnumerations(has, hasNot); + } } diff --git a/src/MfGames.Gallium/WhereEntityExtensions.cs b/src/MfGames.Gallium/WhereEntityExtensions.cs index fb46690..27f7ee5 100644 --- a/src/MfGames.Gallium/WhereEntityExtensions.cs +++ b/src/MfGames.Gallium/WhereEntityExtensions.cs @@ -2,42 +2,40 @@ namespace MfGames.Gallium; public static class WhereEntityExtensions { - public static IEnumerable WhereEntity( - this IEnumerable entities, - Func include) - { - return entities.Where(x => x.Has() && include(x, x.Get())); - } + public static IEnumerable WhereEntity( + this IEnumerable entities, + Func include + ) + { + return entities.Where(x => x.Has() && include(x, x.Get())); + } - public static IEnumerable WhereEntity( - this IEnumerable entities, - Func include) - { - return entities.Where( - x => x.HasAll() - && include(x, x.Get(), x.Get())); - } + public static IEnumerable WhereEntity( + this IEnumerable entities, + Func include + ) + { + return entities.Where(x => x.HasAll() && include(x, x.Get(), x.Get())); + } - public static IEnumerable WhereEntity( - this IEnumerable entities, - Func include) - { - return entities.Where( - x => x.HasAll() - && include(x, x.Get(), x.Get(), x.Get())); - } + public static IEnumerable WhereEntity( + this IEnumerable entities, + Func include + ) + { + return entities.Where(x => + x.HasAll() && include(x, x.Get(), x.Get(), x.Get()) + ); + } - public static IEnumerable WhereEntity( - this IEnumerable entities, - Func include) - { - return entities.Where( - x => x.HasAll() - && include( - x, - x.Get(), - x.Get(), - x.Get(), - x.Get())); - } + public static IEnumerable WhereEntity( + this IEnumerable entities, + Func include + ) + { + return entities.Where(x => + x.HasAll() + && include(x, x.Get(), x.Get(), x.Get(), x.Get()) + ); + } } diff --git a/src/MfGames.Gallium/WhereEntityHasExtensions.cs b/src/MfGames.Gallium/WhereEntityHasExtensions.cs index 0d8f273..652a836 100644 --- a/src/MfGames.Gallium/WhereEntityHasExtensions.cs +++ b/src/MfGames.Gallium/WhereEntityHasExtensions.cs @@ -2,27 +2,27 @@ namespace MfGames.Gallium; public static class WhereEntityHasExtensions { - public static IEnumerable WhereEntityHas( - this IEnumerable entities) - { - return entities.Where(x => x.Has()); - } + public static IEnumerable WhereEntityHas(this IEnumerable entities) + { + return entities.Where(x => x.Has()); + } - public static IEnumerable WhereEntityHasAll - (this IEnumerable entities) - { - return entities.Where(x => x.HasAll()); - } + public static IEnumerable WhereEntityHasAll(this IEnumerable entities) + { + return entities.Where(x => x.HasAll()); + } - public static IEnumerable WhereEntityHasAll - (this IEnumerable entities) - { - return entities.Where(x => x.HasAll()); - } + public static IEnumerable WhereEntityHasAll( + this IEnumerable entities + ) + { + return entities.Where(x => x.HasAll()); + } - public static IEnumerable WhereEntityHasAll - (this IEnumerable entities) - { - return entities.Where(x => x.HasAll()); - } + public static IEnumerable WhereEntityHasAll( + this IEnumerable entities + ) + { + return entities.Where(x => x.HasAll()); + } } diff --git a/src/MfGames.Gallium/WhereEntityNotHasExtensions.cs b/src/MfGames.Gallium/WhereEntityNotHasExtensions.cs index 719ebe9..8f6f114 100644 --- a/src/MfGames.Gallium/WhereEntityNotHasExtensions.cs +++ b/src/MfGames.Gallium/WhereEntityNotHasExtensions.cs @@ -2,27 +2,29 @@ namespace MfGames.Gallium; public static class WhereEntityNotHasExtensions { - public static IEnumerable WhereEntityNotHas( - this IEnumerable entities) - { - return entities.Where(x => !x.Has()); - } + public static IEnumerable WhereEntityNotHas(this IEnumerable entities) + { + return entities.Where(x => !x.Has()); + } - public static IEnumerable WhereEntityNotHasAll - (this IEnumerable entities) - { - return entities.Where(x => !x.HasAll()); - } + public static IEnumerable WhereEntityNotHasAll( + this IEnumerable entities + ) + { + return entities.Where(x => !x.HasAll()); + } - public static IEnumerable WhereEntityNotHasAll - (this IEnumerable entities) - { - return entities.Where(x => !x.HasAll()); - } + public static IEnumerable WhereEntityNotHasAll( + this IEnumerable entities + ) + { + return entities.Where(x => !x.HasAll()); + } - public static IEnumerable WhereEntityNotHasAll - (this IEnumerable entities) - { - return entities.Where(x => !x.HasAll()); - } + public static IEnumerable WhereEntityNotHasAll( + this IEnumerable entities + ) + { + return entities.Where(x => !x.HasAll()); + } } diff --git a/src/MfGames.IO/Extensions/AssemblyExtensions.cs b/src/MfGames.IO/Extensions/AssemblyExtensions.cs index a59277f..678a7bf 100644 --- a/src/MfGames.IO/Extensions/AssemblyExtensions.cs +++ b/src/MfGames.IO/Extensions/AssemblyExtensions.cs @@ -7,25 +7,23 @@ namespace MfGames.IO.Extensions; /// public static class AssemblyExtensions { - /// - /// Gets the directory for a given assembly. - /// - /// The assembly to get the directory. - /// The directory or null if the assembly or location is null. - public static DirectoryInfo? GetDirectory(this Assembly? assembly) - { - return assembly.GetFile()?.Directory; - } + /// + /// Gets the directory for a given assembly. + /// + /// The assembly to get the directory. + /// The directory or null if the assembly or location is null. + public static DirectoryInfo? GetDirectory(this Assembly? assembly) + { + return assembly.GetFile()?.Directory; + } - /// - /// Gets the file for a given assembly. - /// - /// The assembly to get the directory. - /// The directory or null if the assembly or location is null. - public static FileInfo? GetFile(this Assembly? assembly) - { - return assembly?.Location == null - ? null - : new FileInfo(assembly.Location); - } + /// + /// Gets the file for a given assembly. + /// + /// The assembly to get the directory. + /// The directory or null if the assembly or location is null. + public static FileInfo? GetFile(this Assembly? assembly) + { + return assembly?.Location == null ? null : new FileInfo(assembly.Location); + } } diff --git a/src/MfGames.IO/Extensions/CryptoFileInfoExtensions.cs b/src/MfGames.IO/Extensions/CryptoFileInfoExtensions.cs index 163e8a1..dfc4f66 100644 --- a/src/MfGames.IO/Extensions/CryptoFileInfoExtensions.cs +++ b/src/MfGames.IO/Extensions/CryptoFileInfoExtensions.cs @@ -9,41 +9,37 @@ namespace MfGames.IO.Extensions; /// public static class CryptoFileInfoExtensions { - /// - /// Hashes the given input and returns the results. - /// - /// The FileInfo object or null. - /// The type of hash requested. - /// Null if input is null, otherwise the hash value. - public static byte[]? ToHashBytes( - this FileInfo? file, - HashType hash = HashType.Sha512) - { - if (file == null) - { - return null; - } + /// + /// Hashes the given input and returns the results. + /// + /// The FileInfo object or null. + /// The type of hash requested. + /// Null if input is null, otherwise the hash value. + public static byte[]? ToHashBytes(this FileInfo? file, HashType hash = HashType.Sha512) + { + if (file == null) + { + return null; + } - using FileStream stream = file.Open( - FileMode.Open, - FileAccess.Read, - FileShare.Read); + using FileStream stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read); - return hash.CreateHash().ComputeHash(stream); - } + return hash.CreateHash().ComputeHash(stream); + } - /// - /// Hashes the given input and returns the results as a string. - /// - /// The FileInfo object or null. - /// The type of hash requested. - /// The format of the requested string. - /// Null if input is null, otherwise the hash value. - public static string? ToHashString( - this FileInfo? file, - HashType hash = HashType.Sha512, - ByteStringFormat format = ByteStringFormat.LowercaseHex) - { - return file?.ToHashBytes(hash).ToByteString(format); - } + /// + /// Hashes the given input and returns the results as a string. + /// + /// The FileInfo object or null. + /// The type of hash requested. + /// The format of the requested string. + /// Null if input is null, otherwise the hash value. + public static string? ToHashString( + this FileInfo? file, + HashType hash = HashType.Sha512, + ByteStringFormat format = ByteStringFormat.LowercaseHex + ) + { + return file?.ToHashBytes(hash).ToByteString(format); + } } diff --git a/src/MfGames.IO/Extensions/DirectoryInfoExtensions.cs b/src/MfGames.IO/Extensions/DirectoryInfoExtensions.cs index 20c9d66..9ca49ee 100644 --- a/src/MfGames.IO/Extensions/DirectoryInfoExtensions.cs +++ b/src/MfGames.IO/Extensions/DirectoryInfoExtensions.cs @@ -5,166 +5,157 @@ namespace MfGames.IO.Extensions; /// public static class DirectoryInfoExtensions { - /// - /// Makes sure a directory exists, creating it and any parents above it - /// as needed. - /// - /// - /// The directory passed in. - public static DirectoryInfo? CreateIfMissing(this DirectoryInfo? directory) - { - // Ignore blanks. - if (directory == null) - { - return null; - } + /// + /// Makes sure a directory exists, creating it and any parents above it + /// as needed. + /// + /// + /// The directory passed in. + public static DirectoryInfo? CreateIfMissing(this DirectoryInfo? directory) + { + // Ignore blanks. + if (directory == null) + { + return null; + } - // Check the parent first. We don't have to worry about null because - // we check that coming in. - directory.Parent.CreateIfMissing(); + // Check the parent first. We don't have to worry about null because + // we check that coming in. + directory.Parent.CreateIfMissing(); - // If the directory doesn't exist, create it. - if (!Directory.Exists(directory.FullName)) - { - directory.Create(); - } + // If the directory doesn't exist, create it. + if (!Directory.Exists(directory.FullName)) + { + directory.Create(); + } - return directory; - } + return directory; + } - /// - /// Searches for the Git root starting at the given directory. - /// - /// The directory to start searching. - /// The directory containing `.git`, otherwise null. - public static DirectoryInfo? FindGitRoot(this DirectoryInfo? directory) - { - return directory.FindSelfOrParent(IsGitRoot); - } + /// + /// Searches for the Git root starting at the given directory. + /// + /// The directory to start searching. + /// The directory containing `.git`, otherwise null. + public static DirectoryInfo? FindGitRoot(this DirectoryInfo? directory) + { + return directory.FindSelfOrParent(IsGitRoot); + } - /// - /// Searches for a parent that matches the given `match` method. This - /// will not compare the given directory to see if it matches. - /// - /// The directory to start searching. - /// The function that takes a directory to determine a match. - /// A parent directory that matches, otherwise null. - public static DirectoryInfo? FindParent( - this DirectoryInfo? directory, - Func match) - { - return directory == null - ? null - : FindSelfOrParent(directory.Parent, match); - } + /// + /// Searches for a parent that matches the given `match` method. This + /// will not compare the given directory to see if it matches. + /// + /// The directory to start searching. + /// The function that takes a directory to determine a match. + /// A parent directory that matches, otherwise null. + public static DirectoryInfo? FindParent( + this DirectoryInfo? directory, + Func match + ) + { + return directory == null ? null : FindSelfOrParent(directory.Parent, match); + } - /// - /// Searches the given directory and parents for the first one that - /// matches (moving up the directory tree). If this does not find - /// anything, then a null will be returned. - /// - /// The directory to start searching. - /// The function that takes a directory to determine a match. - /// A parent directory that matches, otherwise null. - public static DirectoryInfo? FindSelfOrParent( - this DirectoryInfo? directory, - Func match) - { - while (true) - { - // Validate our inputs. - if (match == null) - { - throw new ArgumentNullException(nameof(match)); - } + /// + /// Searches the given directory and parents for the first one that + /// matches (moving up the directory tree). If this does not find + /// anything, then a null will be returned. + /// + /// The directory to start searching. + /// The function that takes a directory to determine a match. + /// A parent directory that matches, otherwise null. + public static DirectoryInfo? FindSelfOrParent( + this DirectoryInfo? directory, + Func match + ) + { + while (true) + { + // Validate our inputs. + if (match == null) + { + throw new ArgumentNullException(nameof(match)); + } - // If the directory is null, just return null. Same with - // non-existing directories. We don't use directory.Exists here - // because it seems to be cached and we get incorrect data. - if (directory == null || !Directory.Exists(directory.FullName)) - { - return null; - } + // If the directory is null, just return null. Same with + // non-existing directories. We don't use directory.Exists here + // because it seems to be cached and we get incorrect data. + if (directory == null || !Directory.Exists(directory.FullName)) + { + return null; + } - // Check this directory for a match, otherwise move up. - if (match(directory)) - { - return directory; - } + // Check this directory for a match, otherwise move up. + if (match(directory)) + { + return directory; + } - directory = directory.Parent; - } - } + directory = directory.Parent; + } + } - /// - /// Gets a DirectoryInfo by combining the path components with the - /// directory full path. - /// - /// The directory to get the root path. - /// Additional child paths. - /// A DirectoryInfo of the given path. - public static DirectoryInfo GetDirectory( - this DirectoryInfo directory, - params string[] paths) - { - if (directory == null) - { - throw new ArgumentNullException(nameof(directory)); - } + /// + /// Gets a DirectoryInfo by combining the path components with the + /// directory full path. + /// + /// The directory to get the root path. + /// Additional child paths. + /// A DirectoryInfo of the given path. + public static DirectoryInfo GetDirectory(this DirectoryInfo directory, params string[] paths) + { + if (directory == null) + { + throw new ArgumentNullException(nameof(directory)); + } - if (paths == null) - { - throw new ArgumentNullException(nameof(paths)); - } + if (paths == null) + { + throw new ArgumentNullException(nameof(paths)); + } - string[] parts = new[] { directory.FullName } - .Union(paths) - .ToArray(); - string path = Path.Combine(parts); - var info = new DirectoryInfo(path); + string[] parts = new[] { directory.FullName }.Union(paths).ToArray(); + string path = Path.Combine(parts); + var info = new DirectoryInfo(path); - return info; - } + return info; + } - /// - /// Gets a FileInfo by combining the path components with the directory - /// full path. - /// - /// The directory to get the root path. - /// Additional child paths. - /// A FileInfo of the given path. - public static FileInfo GetFile( - this DirectoryInfo directory, - params string[] paths) - { - if (directory == null) - { - throw new ArgumentNullException(nameof(directory)); - } + /// + /// Gets a FileInfo by combining the path components with the directory + /// full path. + /// + /// The directory to get the root path. + /// Additional child paths. + /// A FileInfo of the given path. + public static FileInfo GetFile(this DirectoryInfo directory, params string[] paths) + { + if (directory == null) + { + throw new ArgumentNullException(nameof(directory)); + } - if (paths == null) - { - throw new ArgumentNullException(nameof(paths)); - } + if (paths == null) + { + throw new ArgumentNullException(nameof(paths)); + } - string[] parts = new[] { directory.FullName } - .Union(paths) - .ToArray(); - string path = Path.Combine(parts); - var info = new FileInfo(path); + string[] parts = new[] { directory.FullName }.Union(paths).ToArray(); + string path = Path.Combine(parts); + var info = new FileInfo(path); - return info; - } + return info; + } - /// - /// Determines if the given directory contains a ".git" folder. If given - /// a null, this will always return false. - /// - /// The directory to inspect. - /// True if the directory contains ".git", otherwise false. - public static bool IsGitRoot(this DirectoryInfo? directory) - { - return directory != null - && directory.GetDirectories(".git").Length > 0; - } + /// + /// Determines if the given directory contains a ".git" folder. If given + /// a null, this will always return false. + /// + /// The directory to inspect. + /// True if the directory contains ".git", otherwise false. + public static bool IsGitRoot(this DirectoryInfo? directory) + { + return directory != null && directory.GetDirectories(".git").Length > 0; + } } diff --git a/src/MfGames.IO/Extensions/FileInfoExtensions.cs b/src/MfGames.IO/Extensions/FileInfoExtensions.cs index 479eb33..187e2fa 100644 --- a/src/MfGames.IO/Extensions/FileInfoExtensions.cs +++ b/src/MfGames.IO/Extensions/FileInfoExtensions.cs @@ -7,48 +7,45 @@ namespace MfGames.IO.Extensions; /// public static class FileInfoExtensions { - /// - /// Reads all the text from a FileInfo object. - /// - /// The file to read from. - /// The text contents. - public static string ReadAllText(this FileInfo file) - { - return File.ReadAllText(file.FullName); - } + /// + /// Reads all the text from a FileInfo object. + /// + /// The file to read from. + /// The text contents. + public static string ReadAllText(this FileInfo file) + { + return File.ReadAllText(file.FullName); + } - /// - /// Reads all the text from a FileInfo object. - /// - /// The file to read from. - /// The encoding to use. - /// The text contents. - public static string ReadAllText(this FileInfo file, Encoding encoding) - { - return File.ReadAllText(file.FullName, encoding); - } + /// + /// Reads all the text from a FileInfo object. + /// + /// The file to read from. + /// The encoding to use. + /// The text contents. + public static string ReadAllText(this FileInfo file, Encoding encoding) + { + return File.ReadAllText(file.FullName, encoding); + } - /// - /// Writes out all the text to the given file. - /// - /// The file to write to. - /// The text to write out. - public static void WriteAllText(this FileInfo file, string text) - { - File.WriteAllText(file.FullName, text); - } + /// + /// Writes out all the text to the given file. + /// + /// The file to write to. + /// The text to write out. + public static void WriteAllText(this FileInfo file, string text) + { + File.WriteAllText(file.FullName, text); + } - /// - /// Writes out all the text to the given file. - /// - /// The file to write to. - /// The text to write out. - /// The encoding to use. - public static void WriteAllText( - this FileInfo file, - string text, - Encoding encoding) - { - File.WriteAllText(file.FullName, text, encoding); - } + /// + /// Writes out all the text to the given file. + /// + /// The file to write to. + /// The text to write out. + /// The encoding to use. + public static void WriteAllText(this FileInfo file, string text, Encoding encoding) + { + File.WriteAllText(file.FullName, text, encoding); + } } diff --git a/src/MfGames.IO/Extensions/TypeExtensions.cs b/src/MfGames.IO/Extensions/TypeExtensions.cs index 6c096e2..435a51c 100644 --- a/src/MfGames.IO/Extensions/TypeExtensions.cs +++ b/src/MfGames.IO/Extensions/TypeExtensions.cs @@ -5,23 +5,23 @@ namespace MfGames.IO.Extensions; /// public static class TypeExtensions { - /// - /// Gets the directory for a given type. - /// - /// The type assembly to get the directory. - /// The directory or null if the assembly or location is null. - public static DirectoryInfo? GetDirectory(this Type? type) - { - return type?.Assembly.GetDirectory(); - } + /// + /// Gets the directory for a given type. + /// + /// The type assembly to get the directory. + /// The directory or null if the assembly or location is null. + public static DirectoryInfo? GetDirectory(this Type? type) + { + return type?.Assembly.GetDirectory(); + } - /// - /// Gets the file for a given type's assembly. - /// - /// The type assembly to get the directory. - /// The directory or null if the assembly or location is null. - public static FileInfo? GetFile(this Type? type) - { - return type?.Assembly.GetFile(); - } + /// + /// Gets the file for a given type's assembly. + /// + /// The type assembly to get the directory. + /// The directory or null if the assembly or location is null. + public static FileInfo? GetFile(this Type? type) + { + return type?.Assembly.GetFile(); + } } diff --git a/src/MfGames.Locking/NestableReadLock.cs b/src/MfGames.Locking/NestableReadLock.cs index 668d5cf..b491a44 100644 --- a/src/MfGames.Locking/NestableReadLock.cs +++ b/src/MfGames.Locking/NestableReadLock.cs @@ -5,39 +5,41 @@ /// public class NestableReadLock : IDisposable { - private readonly bool lockAcquired; + private readonly bool lockAcquired; - private readonly ReaderWriterLockSlim readerWriterLockSlim; + private readonly ReaderWriterLockSlim readerWriterLockSlim; - /// - /// Initializes a new instance of the class. - /// - /// The reader writer lock slim. - public NestableReadLock(ReaderWriterLockSlim readerWriterLockSlim) - { - // Keep track of the lock since we'll need it to release the lock. - this.readerWriterLockSlim = readerWriterLockSlim; + /// + /// Initializes a new instance of the class. + /// + /// The reader writer lock slim. + public NestableReadLock(ReaderWriterLockSlim readerWriterLockSlim) + { + // Keep track of the lock since we'll need it to release the lock. + this.readerWriterLockSlim = readerWriterLockSlim; - // If we already have a read or write lock, we don't do anything. - if (readerWriterLockSlim.IsReadLockHeld - || readerWriterLockSlim.IsUpgradeableReadLockHeld - || readerWriterLockSlim.IsWriteLockHeld) - { - this.lockAcquired = false; - } - else - { - readerWriterLockSlim.EnterReadLock(); - this.lockAcquired = true; - } - } + // If we already have a read or write lock, we don't do anything. + if ( + readerWriterLockSlim.IsReadLockHeld + || readerWriterLockSlim.IsUpgradeableReadLockHeld + || readerWriterLockSlim.IsWriteLockHeld + ) + { + this.lockAcquired = false; + } + else + { + readerWriterLockSlim.EnterReadLock(); + this.lockAcquired = true; + } + } - /// - public void Dispose() - { - if (this.lockAcquired) - { - this.readerWriterLockSlim.ExitReadLock(); - } - } + /// + public void Dispose() + { + if (this.lockAcquired) + { + this.readerWriterLockSlim.ExitReadLock(); + } + } } diff --git a/src/MfGames.Locking/NestableUpgradableReadLock.cs b/src/MfGames.Locking/NestableUpgradableReadLock.cs index cb2f30a..0632c1b 100644 --- a/src/MfGames.Locking/NestableUpgradableReadLock.cs +++ b/src/MfGames.Locking/NestableUpgradableReadLock.cs @@ -5,39 +5,38 @@ /// public class NestableUpgradableReadLock : IDisposable { - private readonly bool lockAcquired; + private readonly bool lockAcquired; - private readonly ReaderWriterLockSlim readerWriterLockSlim; + private readonly ReaderWriterLockSlim readerWriterLockSlim; - /// - /// Initializes a new instance of the - /// class. - /// - /// The reader writer lock slim. - public NestableUpgradableReadLock(ReaderWriterLockSlim readerWriterLockSlim) - { - // Keep track of the lock since we'll need it to release the lock. - this.readerWriterLockSlim = readerWriterLockSlim; + /// + /// Initializes a new instance of the + /// class. + /// + /// The reader writer lock slim. + public NestableUpgradableReadLock(ReaderWriterLockSlim readerWriterLockSlim) + { + // Keep track of the lock since we'll need it to release the lock. + this.readerWriterLockSlim = readerWriterLockSlim; - // If we already have a read or write lock, we don't do anything. - if (readerWriterLockSlim.IsUpgradeableReadLockHeld - || readerWriterLockSlim.IsWriteLockHeld) - { - this.lockAcquired = false; - } - else - { - readerWriterLockSlim.EnterUpgradeableReadLock(); - this.lockAcquired = true; - } - } + // If we already have a read or write lock, we don't do anything. + if (readerWriterLockSlim.IsUpgradeableReadLockHeld || readerWriterLockSlim.IsWriteLockHeld) + { + this.lockAcquired = false; + } + else + { + readerWriterLockSlim.EnterUpgradeableReadLock(); + this.lockAcquired = true; + } + } - /// - public void Dispose() - { - if (this.lockAcquired) - { - this.readerWriterLockSlim.ExitUpgradeableReadLock(); - } - } + /// + public void Dispose() + { + if (this.lockAcquired) + { + this.readerWriterLockSlim.ExitUpgradeableReadLock(); + } + } } diff --git a/src/MfGames.Locking/NestableWriteLock.cs b/src/MfGames.Locking/NestableWriteLock.cs index 53b2397..d2fcfc2 100644 --- a/src/MfGames.Locking/NestableWriteLock.cs +++ b/src/MfGames.Locking/NestableWriteLock.cs @@ -5,37 +5,37 @@ /// public class NestableWriteLock : IDisposable { - private readonly bool lockAcquired; + private readonly bool lockAcquired; - private readonly ReaderWriterLockSlim readerWriterLockSlim; + private readonly ReaderWriterLockSlim readerWriterLockSlim; - /// - /// Initializes a new instance of the class. - /// - /// The reader writer lock slim. - public NestableWriteLock(ReaderWriterLockSlim readerWriterLockSlim) - { - // Keep track of the lock since we'll need it to release the lock. - this.readerWriterLockSlim = readerWriterLockSlim; + /// + /// Initializes a new instance of the class. + /// + /// The reader writer lock slim. + public NestableWriteLock(ReaderWriterLockSlim readerWriterLockSlim) + { + // Keep track of the lock since we'll need it to release the lock. + this.readerWriterLockSlim = readerWriterLockSlim; - // If we already have a read or write lock, we don't do anything. - if (readerWriterLockSlim.IsWriteLockHeld) - { - this.lockAcquired = false; - } - else - { - readerWriterLockSlim.EnterWriteLock(); - this.lockAcquired = true; - } - } + // If we already have a read or write lock, we don't do anything. + if (readerWriterLockSlim.IsWriteLockHeld) + { + this.lockAcquired = false; + } + else + { + readerWriterLockSlim.EnterWriteLock(); + this.lockAcquired = true; + } + } - /// - public void Dispose() - { - if (this.lockAcquired) - { - this.readerWriterLockSlim.ExitWriteLock(); - } - } + /// + public void Dispose() + { + if (this.lockAcquired) + { + this.readerWriterLockSlim.ExitWriteLock(); + } + } } diff --git a/src/MfGames.Locking/ReadLock.cs b/src/MfGames.Locking/ReadLock.cs index 3f0c46b..00bc4e5 100644 --- a/src/MfGames.Locking/ReadLock.cs +++ b/src/MfGames.Locking/ReadLock.cs @@ -6,21 +6,21 @@ /// public class ReadLock : IDisposable { - private readonly ReaderWriterLockSlim readerWriterLockSlim; + private readonly ReaderWriterLockSlim readerWriterLockSlim; - /// - /// Initializes a new instance of the class. - /// - /// The reader writer lock slim. - public ReadLock(ReaderWriterLockSlim readerWriterLockSlim) - { - this.readerWriterLockSlim = readerWriterLockSlim; - readerWriterLockSlim.EnterReadLock(); - } + /// + /// Initializes a new instance of the class. + /// + /// The reader writer lock slim. + public ReadLock(ReaderWriterLockSlim readerWriterLockSlim) + { + this.readerWriterLockSlim = readerWriterLockSlim; + readerWriterLockSlim.EnterReadLock(); + } - /// - public void Dispose() - { - this.readerWriterLockSlim.ExitReadLock(); - } + /// + public void Dispose() + { + this.readerWriterLockSlim.ExitReadLock(); + } } diff --git a/src/MfGames.Locking/UpgradableLock.cs b/src/MfGames.Locking/UpgradableLock.cs index 5a74d4a..ddaa7a6 100644 --- a/src/MfGames.Locking/UpgradableLock.cs +++ b/src/MfGames.Locking/UpgradableLock.cs @@ -5,24 +5,24 @@ namespace MfGames.Locking; /// public class UpgradableLock : IDisposable { - private readonly ReaderWriterLockSlim readerWriterLockSlim; + private readonly ReaderWriterLockSlim readerWriterLockSlim; - /// - /// Initializes a new instance of the class. - /// - /// The reader writer lock slim. - public UpgradableLock(ReaderWriterLockSlim readerWriterLockSlim) - { - this.readerWriterLockSlim = readerWriterLockSlim; - readerWriterLockSlim.EnterUpgradeableReadLock(); - } + /// + /// Initializes a new instance of the class. + /// + /// The reader writer lock slim. + public UpgradableLock(ReaderWriterLockSlim readerWriterLockSlim) + { + this.readerWriterLockSlim = readerWriterLockSlim; + readerWriterLockSlim.EnterUpgradeableReadLock(); + } - /// - /// Performs application-defined tasks associated with freeing, releasing, or - /// resetting unmanaged resources. - /// - public void Dispose() - { - this.readerWriterLockSlim.ExitUpgradeableReadLock(); - } + /// + /// Performs application-defined tasks associated with freeing, releasing, or + /// resetting unmanaged resources. + /// + public void Dispose() + { + this.readerWriterLockSlim.ExitUpgradeableReadLock(); + } } diff --git a/src/MfGames.Locking/WriteLock.cs b/src/MfGames.Locking/WriteLock.cs index 8e3a4fc..7c122ee 100644 --- a/src/MfGames.Locking/WriteLock.cs +++ b/src/MfGames.Locking/WriteLock.cs @@ -5,24 +5,24 @@ namespace MfGames.Locking; /// public class WriteLock : IDisposable { - private readonly ReaderWriterLockSlim readerWriterLockSlim; + private readonly ReaderWriterLockSlim readerWriterLockSlim; - /// - /// Initializes a new instance of the class. - /// - /// The reader writer lock slim. - public WriteLock(ReaderWriterLockSlim readerWriterLockSlim) - { - this.readerWriterLockSlim = readerWriterLockSlim; - readerWriterLockSlim.EnterWriteLock(); - } + /// + /// Initializes a new instance of the class. + /// + /// The reader writer lock slim. + public WriteLock(ReaderWriterLockSlim readerWriterLockSlim) + { + this.readerWriterLockSlim = readerWriterLockSlim; + readerWriterLockSlim.EnterWriteLock(); + } - /// - /// Performs application-defined tasks associated with freeing, releasing, or - /// resetting unmanaged resources. - /// - public void Dispose() - { - this.readerWriterLockSlim.ExitWriteLock(); - } + /// + /// Performs application-defined tasks associated with freeing, releasing, or + /// resetting unmanaged resources. + /// + public void Dispose() + { + this.readerWriterLockSlim.ExitWriteLock(); + } } diff --git a/src/MfGames.Markdown.Gemtext/Extensions/GemtextPipeTableExtension.cs b/src/MfGames.Markdown.Gemtext/Extensions/GemtextPipeTableExtension.cs index 506caf9..a476a97 100644 --- a/src/MfGames.Markdown.Gemtext/Extensions/GemtextPipeTableExtension.cs +++ b/src/MfGames.Markdown.Gemtext/Extensions/GemtextPipeTableExtension.cs @@ -2,7 +2,6 @@ using Markdig; using Markdig.Extensions.Tables; using Markdig.Parsers.Inlines; using Markdig.Renderers; - using MfGames.Markdown.Gemtext.Renderers; using MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; @@ -14,52 +13,52 @@ namespace MfGames.Markdown.Gemtext.Extensions; /// public class GemtextPipeTableExtension : IMarkdownExtension { - /// - /// Initializes a new instance of the - /// class. - /// - /// The options. - public GemtextPipeTableExtension(GemtextPipeTableOptions? options = null) - { - this.Options = options ?? new GemtextPipeTableOptions(); - } + /// + /// Initializes a new instance of the + /// class. + /// + /// The options. + public GemtextPipeTableExtension(GemtextPipeTableOptions? options = null) + { + this.Options = options ?? new GemtextPipeTableOptions(); + } - /// - /// Gets the options. - /// - public GemtextPipeTableOptions Options { get; } + /// + /// Gets the options. + /// + public GemtextPipeTableOptions Options { get; } - /// - public void Setup(MarkdownPipelineBuilder pipeline) - { - pipeline.PreciseSourceLocation = true; + /// + public void Setup(MarkdownPipelineBuilder pipeline) + { + pipeline.PreciseSourceLocation = true; - if (!pipeline.BlockParsers.Contains()) - { - pipeline.BlockParsers.Insert(0, new PipeTableBlockParser()); - } + if (!pipeline.BlockParsers.Contains()) + { + pipeline.BlockParsers.Insert(0, new PipeTableBlockParser()); + } - LineBreakInlineParser? lineBreakParser = - pipeline.InlineParsers.FindExact(); + LineBreakInlineParser? lineBreakParser = + pipeline.InlineParsers.FindExact(); - if (!pipeline.InlineParsers.Contains()) - { - pipeline.InlineParsers.InsertBefore( - new PipeTableParser(lineBreakParser!, this.Options)); - } - } + if (!pipeline.InlineParsers.Contains()) + { + pipeline.InlineParsers.InsertBefore( + new PipeTableParser(lineBreakParser!, this.Options) + ); + } + } - /// - public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) - { - if (renderer is not GemtextRenderer gemtext) - { - return; - } + /// + public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) + { + if (renderer is not GemtextRenderer gemtext) + { + return; + } - gemtext.ObjectRenderers.Add( - new TableRenderer( - this.Options.OmitPreformatLines, - this.Options.ConfigureTableBuilder)); - } + gemtext.ObjectRenderers.Add( + new TableRenderer(this.Options.OmitPreformatLines, this.Options.ConfigureTableBuilder) + ); + } } diff --git a/src/MfGames.Markdown.Gemtext/Extensions/GemtextPipeTableOptions.cs b/src/MfGames.Markdown.Gemtext/Extensions/GemtextPipeTableOptions.cs index cab0a42..2af5499 100644 --- a/src/MfGames.Markdown.Gemtext/Extensions/GemtextPipeTableOptions.cs +++ b/src/MfGames.Markdown.Gemtext/Extensions/GemtextPipeTableOptions.cs @@ -1,19 +1,18 @@ using ConsoleTableExt; - using Markdig.Extensions.Tables; namespace MfGames.Markdown.Gemtext.Extensions; public class GemtextPipeTableOptions : PipeTableOptions { - /// - /// Gets or sets the table builder to control formatting. - /// - public Action? ConfigureTableBuilder { get; set; } + /// + /// Gets or sets the table builder to control formatting. + /// + public Action? ConfigureTableBuilder { get; set; } - /// - /// Gets or sets a value whether the preformat (backticks) fence should - /// not be emitted. - /// - public bool OmitPreformatLines { get; set; } + /// + /// Gets or sets a value whether the preformat (backticks) fence should + /// not be emitted. + /// + public bool OmitPreformatLines { get; set; } } diff --git a/src/MfGames.Markdown.Gemtext/Extensions/GemtextSmartyPantsExtension.cs b/src/MfGames.Markdown.Gemtext/Extensions/GemtextSmartyPantsExtension.cs index 1a758b6..05b9798 100644 --- a/src/MfGames.Markdown.Gemtext/Extensions/GemtextSmartyPantsExtension.cs +++ b/src/MfGames.Markdown.Gemtext/Extensions/GemtextSmartyPantsExtension.cs @@ -2,7 +2,6 @@ using Markdig; using Markdig.Extensions.SmartyPants; using Markdig.Parsers.Inlines; using Markdig.Renderers; - using MfGames.Markdown.Gemtext.Renderers; using MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; @@ -13,42 +12,39 @@ namespace MfGames.Markdown.Gemtext.Extensions; /// public class GemtextSmartyPantsExtension : IMarkdownExtension { - /// - /// Initializes a new instance of the class. - /// - /// The options. - public GemtextSmartyPantsExtension(SmartyPantOptions? options) - { - this.Options = options ?? new SmartyPantOptions(); - } + /// + /// Initializes a new instance of the class. + /// + /// The options. + public GemtextSmartyPantsExtension(SmartyPantOptions? options) + { + this.Options = options ?? new SmartyPantOptions(); + } - /// - /// Gets the options. - /// - public SmartyPantOptions Options { get; } + /// + /// Gets the options. + /// + public SmartyPantOptions Options { get; } - public void Setup(MarkdownPipelineBuilder pipeline) - { - if (!pipeline.InlineParsers.Contains()) - { - // Insert the parser after the code span parser - pipeline.InlineParsers.InsertAfter( - new SmartyPantsInlineParser()); - } - } + public void Setup(MarkdownPipelineBuilder pipeline) + { + if (!pipeline.InlineParsers.Contains()) + { + // Insert the parser after the code span parser + pipeline.InlineParsers.InsertAfter(new SmartyPantsInlineParser()); + } + } - public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) - { - if (renderer is not GemtextRenderer gemtextRenderer) - { - return; - } + public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) + { + if (renderer is not GemtextRenderer gemtextRenderer) + { + return; + } - if (!gemtextRenderer.ObjectRenderers - .Contains()) - { - gemtextRenderer.ObjectRenderers.Add( - new GemtextSmartyPantRenderer(this.Options)); - } - } + if (!gemtextRenderer.ObjectRenderers.Contains()) + { + gemtextRenderer.ObjectRenderers.Add(new GemtextSmartyPantRenderer(this.Options)); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Extensions/HtmlAsCodeBlocks.cs b/src/MfGames.Markdown.Gemtext/Extensions/HtmlAsCodeBlocks.cs index 3afb637..1b82c58 100644 --- a/src/MfGames.Markdown.Gemtext/Extensions/HtmlAsCodeBlocks.cs +++ b/src/MfGames.Markdown.Gemtext/Extensions/HtmlAsCodeBlocks.cs @@ -1,6 +1,5 @@ using Markdig; using Markdig.Renderers; - using MfGames.Markdown.Gemtext.Renderers; namespace MfGames.Markdown.Gemtext.Extensions; @@ -12,17 +11,15 @@ namespace MfGames.Markdown.Gemtext.Extensions; /// public class HtmlAsCodeBlocks : IMarkdownExtension { - /// - public void Setup(MarkdownPipelineBuilder pipeline) - { - } + /// + public void Setup(MarkdownPipelineBuilder pipeline) { } - /// - public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) - { - if (renderer is GemtextRenderer gemtext) - { - gemtext.HtmlBlockFormatting = HtmlBlockFormatting.CodeBlock; - } - } + /// + public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) + { + if (renderer is GemtextRenderer gemtext) + { + gemtext.HtmlBlockFormatting = HtmlBlockFormatting.CodeBlock; + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Extensions/IncreaseHeaderDepthsAfterFirst.cs b/src/MfGames.Markdown.Gemtext/Extensions/IncreaseHeaderDepthsAfterFirst.cs index 071b540..5ec2830 100644 --- a/src/MfGames.Markdown.Gemtext/Extensions/IncreaseHeaderDepthsAfterFirst.cs +++ b/src/MfGames.Markdown.Gemtext/Extensions/IncreaseHeaderDepthsAfterFirst.cs @@ -1,6 +1,5 @@ using Markdig; using Markdig.Renderers; - using MfGames.Markdown.Gemtext.Renderers; using MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; @@ -14,25 +13,22 @@ namespace MfGames.Markdown.Gemtext.Extensions; /// public class IncreaseHeaderDepthsAfterFirst : IMarkdownExtension { - /// - public void Setup(MarkdownPipelineBuilder pipeline) - { - } + /// + public void Setup(MarkdownPipelineBuilder pipeline) { } - /// - public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) - { - if (renderer is not GemtextRenderer gemtext) - { - return; - } + /// + public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) + { + if (renderer is not GemtextRenderer gemtext) + { + return; + } - HeadingRenderer? heading = - gemtext.ObjectRenderers.Find(); + HeadingRenderer? heading = gemtext.ObjectRenderers.Find(); - if (heading != null) - { - heading.IncreaseHeaderDepthAfterFirst = true; - } - } + if (heading != null) + { + heading.IncreaseHeaderDepthAfterFirst = true; + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Extensions/SetBlockLinkHandling.cs b/src/MfGames.Markdown.Gemtext/Extensions/SetBlockLinkHandling.cs index 8b38449..2d7b8ef 100644 --- a/src/MfGames.Markdown.Gemtext/Extensions/SetBlockLinkHandling.cs +++ b/src/MfGames.Markdown.Gemtext/Extensions/SetBlockLinkHandling.cs @@ -1,6 +1,5 @@ using Markdig; using Markdig.Renderers; - using MfGames.Markdown.Gemtext.Renderers; namespace MfGames.Markdown.Gemtext.Extensions; @@ -11,53 +10,50 @@ namespace MfGames.Markdown.Gemtext.Extensions; /// public class SetBlockLinkHandling : IMarkdownExtension { - public SetBlockLinkHandling( - BlockLinkHandling? blockLinkHandling = null, - EndLinkInlineFormatting? endLinkInlineFormatting = null, - int? nextFootnoteNumber = null) - { - this.BlockLinkHandling = blockLinkHandling; - this.EndLinkInlineFormatting = endLinkInlineFormatting; - this.NextFootnoteNumber = nextFootnoteNumber; - } + public SetBlockLinkHandling( + BlockLinkHandling? blockLinkHandling = null, + EndLinkInlineFormatting? endLinkInlineFormatting = null, + int? nextFootnoteNumber = null + ) + { + this.BlockLinkHandling = blockLinkHandling; + this.EndLinkInlineFormatting = endLinkInlineFormatting; + this.NextFootnoteNumber = nextFootnoteNumber; + } - /// - /// Gets or sets how block links are handled. If this is null, then no - /// change is made to the current renderer. - /// - public BlockLinkHandling? BlockLinkHandling { get; set; } + /// + /// Gets or sets how block links are handled. If this is null, then no + /// change is made to the current renderer. + /// + public BlockLinkHandling? BlockLinkHandling { get; set; } - /// - /// Gets or sets how links are formatted if they are gathered to the - /// end of the paragraph or document. If this is null, then no change - /// will be made. - /// - public EndLinkInlineFormatting? EndLinkInlineFormatting { get; set; } + /// + /// Gets or sets how links are formatted if they are gathered to the + /// end of the paragraph or document. If this is null, then no change + /// will be made. + /// + public EndLinkInlineFormatting? EndLinkInlineFormatting { get; set; } - /// - /// Gets or sets the next footnote number. If this is null, then no - /// change will be made. - /// - public int? NextFootnoteNumber { get; set; } + /// + /// Gets or sets the next footnote number. If this is null, then no + /// change will be made. + /// + public int? NextFootnoteNumber { get; set; } - /// - public void Setup(MarkdownPipelineBuilder pipeline) - { - } + /// + public void Setup(MarkdownPipelineBuilder pipeline) { } - /// - public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) - { - if (renderer is not GemtextRenderer gemtext) - { - return; - } + /// + public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) + { + if (renderer is not GemtextRenderer gemtext) + { + return; + } - gemtext.BlockLinkHandling = this.BlockLinkHandling - ?? gemtext.BlockLinkHandling; - gemtext.EndLinkInlineFormatting = this.EndLinkInlineFormatting - ?? gemtext.EndLinkInlineFormatting; - gemtext.NextFootnoteNumber = this.NextFootnoteNumber - ?? gemtext.NextFootnoteNumber; - } + gemtext.BlockLinkHandling = this.BlockLinkHandling ?? gemtext.BlockLinkHandling; + gemtext.EndLinkInlineFormatting = + this.EndLinkInlineFormatting ?? gemtext.EndLinkInlineFormatting; + gemtext.NextFootnoteNumber = this.NextFootnoteNumber ?? gemtext.NextFootnoteNumber; + } } diff --git a/src/MfGames.Markdown.Gemtext/Extensions/SetInlineFormatting.cs b/src/MfGames.Markdown.Gemtext/Extensions/SetInlineFormatting.cs index f9b5f93..41609c2 100644 --- a/src/MfGames.Markdown.Gemtext/Extensions/SetInlineFormatting.cs +++ b/src/MfGames.Markdown.Gemtext/Extensions/SetInlineFormatting.cs @@ -1,6 +1,5 @@ using Markdig; using Markdig.Renderers; - using MfGames.Markdown.Gemtext.Renderers; namespace MfGames.Markdown.Gemtext.Extensions; @@ -12,38 +11,36 @@ namespace MfGames.Markdown.Gemtext.Extensions; /// public class SetInlineFormatting : IMarkdownExtension { - /// - /// Gets or sets the override formatting for code lines - /// (backtick) spans. - /// - public InlineFormatting? Code { get; set; } + /// + /// Gets or sets the override formatting for code lines + /// (backtick) spans. + /// + public InlineFormatting? Code { get; set; } - /// - /// Sets or sets the override formatting for all inlines. - /// - public InlineFormatting? Default { get; set; } + /// + /// Sets or sets the override formatting for all inlines. + /// + public InlineFormatting? Default { get; set; } - /// - /// Gets or sets the override formatting for emphasis (italic - /// and bold) spans. - /// - public InlineFormatting? Emphasis { get; set; } + /// + /// Gets or sets the override formatting for emphasis (italic + /// and bold) spans. + /// + public InlineFormatting? Emphasis { get; set; } - /// - public void Setup(MarkdownPipelineBuilder pipeline) - { - } + /// + public void Setup(MarkdownPipelineBuilder pipeline) { } - /// - public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) - { - if (renderer is not GemtextRenderer gemtext) - { - return; - } + /// + public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) + { + if (renderer is not GemtextRenderer gemtext) + { + return; + } - gemtext.InlineFormatting = this.Default ?? gemtext.InlineFormatting; - gemtext.EmphasisFormatting = this.Emphasis; - gemtext.CodeFormatting = this.Code; - } + gemtext.InlineFormatting = this.Default ?? gemtext.InlineFormatting; + gemtext.EmphasisFormatting = this.Emphasis; + gemtext.CodeFormatting = this.Code; + } } diff --git a/src/MfGames.Markdown.Gemtext/MarkdownGemtext.cs b/src/MfGames.Markdown.Gemtext/MarkdownGemtext.cs index 8598bd4..501a8f7 100644 --- a/src/MfGames.Markdown.Gemtext/MarkdownGemtext.cs +++ b/src/MfGames.Markdown.Gemtext/MarkdownGemtext.cs @@ -1,7 +1,6 @@ using Markdig; using Markdig.Parsers; using Markdig.Syntax; - using MfGames.Markdown.Gemtext.Renderers; namespace MfGames.Markdown.Gemtext; @@ -13,69 +12,69 @@ namespace MfGames.Markdown.Gemtext; /// public static class MarkdownGemtext { - private static readonly MarkdownPipeline DefaultPipeline; + private static readonly MarkdownPipeline DefaultPipeline; - static MarkdownGemtext() - { - DefaultPipeline = new MarkdownPipelineBuilder() - .Build(); - } + static MarkdownGemtext() + { + DefaultPipeline = new MarkdownPipelineBuilder().Build(); + } - /// - /// Converts the given Markdown - /// - /// A Markdown text. - /// The pipeline used for the conversion. - /// A parser context used for the parsing. - /// The result of the conversion - public static string ToGemtext( - string markdown, - MarkdownPipeline? pipeline = null, - MarkdownParserContext? context = null) - { - if (markdown == null) - { - throw new ArgumentNullException(nameof(markdown)); - } + /// + /// Converts the given Markdown + /// + /// A Markdown text. + /// The pipeline used for the conversion. + /// A parser context used for the parsing. + /// The result of the conversion + public static string ToGemtext( + string markdown, + MarkdownPipeline? pipeline = null, + MarkdownParserContext? context = null + ) + { + if (markdown == null) + { + throw new ArgumentNullException(nameof(markdown)); + } - pipeline ??= DefaultPipeline; + pipeline ??= DefaultPipeline; - MarkdownDocument document = MarkdownParser - .Parse(markdown, pipeline, context); + MarkdownDocument document = MarkdownParser.Parse(markdown, pipeline, context); - return ToGemtext(document, pipeline); - } + return ToGemtext(document, pipeline); + } - /// - /// Converts a Markdown document to HTML. - /// - /// A Markdown document. - /// The pipeline used for the conversion. - /// The result of the conversion - /// if markdown document variable is null - public static string ToGemtext( - this MarkdownDocument document, - MarkdownPipeline? pipeline = null) - { - // Make sure we have sane parameters. - if (document == null) - { - throw new ArgumentNullException(nameof(document)); - } + /// + /// Converts a Markdown document to HTML. + /// + /// A Markdown document. + /// The pipeline used for the conversion. + /// The result of the conversion + /// if markdown document variable is null + public static string ToGemtext( + this MarkdownDocument document, + MarkdownPipeline? pipeline = null + ) + { + // Make sure we have sane parameters. + if (document == null) + { + throw new ArgumentNullException(nameof(document)); + } - pipeline ??= DefaultPipeline; + pipeline ??= DefaultPipeline; - // Set up the writer to contain the markdown and the Gemtext - // renderer. - var writer = new StringWriter(); - GemtextRenderer renderer = new(writer); + // Set up the writer to contain the markdown and the Gemtext + // renderer. + var writer = new StringWriter(); + GemtextRenderer renderer = new(writer); - pipeline.Setup(renderer); + pipeline.Setup(renderer); - // Render the Markdown into Gemtext and re turn the results. - renderer.Render(document); - renderer.Writer.Flush(); + // Render the Markdown into Gemtext and re turn the results. + renderer.Render(document); + renderer.Writer.Flush(); - return renderer.Writer.ToString() ?? string.Empty; - } + return renderer.Writer.ToString() ?? string.Empty; + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/BlockLinkHandling.cs b/src/MfGames.Markdown.Gemtext/Renderers/BlockLinkHandling.cs index 3c6489e..72d5db9 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/BlockLinkHandling.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/BlockLinkHandling.cs @@ -5,29 +5,29 @@ namespace MfGames.Markdown.Gemtext.Renderers; /// public enum BlockLinkHandling { - /// - /// Indicates that the paragraph should be broken apart and the link - /// included on its own line in the middle of the paragraph. - /// - InsertLine, + /// + /// Indicates that the paragraph should be broken apart and the link + /// included on its own line in the middle of the paragraph. + /// + InsertLine, - /// - /// Indicates that all the links in a paragraph should be gathered - /// and then emitted at the end of the paragraph. The text of the link - /// will be left in the paragraph. - /// - ParagraphEnd, + /// + /// Indicates that all the links in a paragraph should be gathered + /// and then emitted at the end of the paragraph. The text of the link + /// will be left in the paragraph. + /// + ParagraphEnd, - /// - /// Indicates that all the links in the document should be gathered - /// and then emitted at the end of the document. The text of the link - /// will be left in the paragraph. - /// - DocumentEnd, + /// + /// Indicates that all the links in the document should be gathered + /// and then emitted at the end of the document. The text of the link + /// will be left in the paragraph. + /// + DocumentEnd, - /// - /// Indicates that the links themselves should be removed and just the - /// text included in the paragraph. - /// - Remove, + /// + /// Indicates that the links themselves should be removed and just the + /// text included in the paragraph. + /// + Remove, } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/EndLinkInlineFormatting.cs b/src/MfGames.Markdown.Gemtext/Renderers/EndLinkInlineFormatting.cs index c7089e6..d691445 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/EndLinkInlineFormatting.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/EndLinkInlineFormatting.cs @@ -7,15 +7,15 @@ namespace MfGames.Markdown.Gemtext.Renderers; /// public enum EndLinkInlineFormatting { - /// - /// Indicates that a footnote notation (`[1]`) will be insert into the - /// text and then the link will be displayed with the URL when gathered. - /// - Footnote, + /// + /// Indicates that a footnote notation (`[1]`) will be insert into the + /// text and then the link will be displayed with the URL when gathered. + /// + Footnote, - /// - /// Indicates that the text is put in as-is into the gathered link with - /// no footnote given in the block. - /// - Text, + /// + /// Indicates that the text is put in as-is into the gathered link with + /// no footnote given in the block. + /// + Text, } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/CodeBlockRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/CodeBlockRenderer.cs index 8610006..3a162eb 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/CodeBlockRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/CodeBlockRenderer.cs @@ -9,30 +9,30 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// public class CodeBlockRenderer : GemtextObjectRenderer { - protected override void Write(GemtextRenderer renderer, CodeBlock obj) - { - // We need to have two lines above this. - renderer.EnsureTwoLines(); + protected override void Write(GemtextRenderer renderer, CodeBlock obj) + { + // We need to have two lines above this. + renderer.EnsureTwoLines(); - // Code blocks are always fenced, but we allow for additional text - // at the end of them which is only in `FencedCodeBlock`. - if (obj is FencedCodeBlock fenced) - { - renderer.WriteLine("```" + fenced.Info); - } - else - { - renderer.WriteLine("```"); - } + // Code blocks are always fenced, but we allow for additional text + // at the end of them which is only in `FencedCodeBlock`. + if (obj is FencedCodeBlock fenced) + { + renderer.WriteLine("```" + fenced.Info); + } + else + { + renderer.WriteLine("```"); + } - renderer.WriteLeafRawLines(obj, true); - renderer.Write("```"); + renderer.WriteLeafRawLines(obj, true); + renderer.Write("```"); - // If we aren't at the end of the container, then add some spacing. - if (!renderer.IsLastInContainer) - { - renderer.WriteLine(); - renderer.WriteLine(); - } - } + // If we aren't at the end of the container, then add some spacing. + if (!renderer.IsLastInContainer) + { + renderer.WriteLine(); + renderer.WriteLine(); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/CustomContainerRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/CustomContainerRenderer.cs index 0422474..abf5933 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/CustomContainerRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/CustomContainerRenderer.cs @@ -8,15 +8,15 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// public class CustomContainerRenderer : GemtextObjectRenderer { - protected override void Write(GemtextRenderer renderer, CustomContainer obj) - { - renderer.EnsureTwoLines(); - renderer.WriteChildren(obj); + protected override void Write(GemtextRenderer renderer, CustomContainer obj) + { + renderer.EnsureTwoLines(); + renderer.WriteChildren(obj); - if (!renderer.IsLastInContainer) - { - renderer.WriteLine(); - renderer.WriteLine(); - } - } + if (!renderer.IsLastInContainer) + { + renderer.WriteLine(); + renderer.WriteLine(); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/HeadingRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/HeadingRenderer.cs index 65c81e6..fc2dbd9 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/HeadingRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/HeadingRenderer.cs @@ -8,48 +8,46 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// public class HeadingRenderer : GemtextObjectRenderer { - private int currentHeading; + private int currentHeading; - /// - /// Gets or sets a value indicating whether the header depths are - /// increased after the first one. - /// - public bool IncreaseHeaderDepthAfterFirst { get; set; } + /// + /// Gets or sets a value indicating whether the header depths are + /// increased after the first one. + /// + public bool IncreaseHeaderDepthAfterFirst { get; set; } - protected override void Write( - GemtextRenderer renderer, - HeadingBlock obj) - { - // Figure out the level we should be processing. - int level = obj.Level; + protected override void Write(GemtextRenderer renderer, HeadingBlock obj) + { + // Figure out the level we should be processing. + int level = obj.Level; - if (this.currentHeading++ > 0 && this.IncreaseHeaderDepthAfterFirst) - { - // Check the second header we see. If this header is H2 or - // higher, then we assume that the file has been already updated - // to handle the heading and we stop processing. - if (this.currentHeading == 2 && level != 1) - { - this.IncreaseHeaderDepthAfterFirst = false; - } - else - { - // We are bumping the heading levels up. - level++; - } - } + if (this.currentHeading++ > 0 && this.IncreaseHeaderDepthAfterFirst) + { + // Check the second header we see. If this header is H2 or + // higher, then we assume that the file has been already updated + // to handle the heading and we stop processing. + if (this.currentHeading == 2 && level != 1) + { + this.IncreaseHeaderDepthAfterFirst = false; + } + else + { + // We are bumping the heading levels up. + level++; + } + } - // Write out the prefix of the header. - string prefix = level switch - { - 1 => "# ", - 2 => "## ", - 3 => "### ", - _ => "", - }; + // Write out the prefix of the header. + string prefix = level switch + { + 1 => "# ", + 2 => "## ", + 3 => "### ", + _ => "", + }; - renderer.EnsureTwoLines(); - renderer.Write(prefix); - renderer.WriteLeafInline(obj); - } + renderer.EnsureTwoLines(); + renderer.Write(prefix); + renderer.WriteLeafInline(obj); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/HtmlBlockRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/HtmlBlockRenderer.cs index 28b1799..6d35e37 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/HtmlBlockRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/HtmlBlockRenderer.cs @@ -8,25 +8,25 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// public class HtmlBlockRenderer : GemtextObjectRenderer { - protected override void Write(GemtextRenderer renderer, HtmlBlock obj) - { - // If we are stripping out HTML blocks (default), then nothing to - // do with rendering. - if (renderer.HtmlBlockFormatting == HtmlBlockFormatting.Remove) - { - return; - } + protected override void Write(GemtextRenderer renderer, HtmlBlock obj) + { + // If we are stripping out HTML blocks (default), then nothing to + // do with rendering. + if (renderer.HtmlBlockFormatting == HtmlBlockFormatting.Remove) + { + return; + } - // Otherwise, we treat this as a fenced code block. - renderer.EnsureTwoLines(); - renderer.WriteLine("```html"); - renderer.WriteLeafRawLines(obj, true); - renderer.WriteLine("```"); + // Otherwise, we treat this as a fenced code block. + renderer.EnsureTwoLines(); + renderer.WriteLine("```html"); + renderer.WriteLeafRawLines(obj, true); + renderer.WriteLine("```"); - // If we aren't at the end of the container, then add some spacing. - if (!renderer.IsLastInContainer) - { - renderer.WriteLine(); - } - } + // If we aren't at the end of the container, then add some spacing. + if (!renderer.IsLastInContainer) + { + renderer.WriteLine(); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ListRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ListRenderer.cs index dfc248f..c0e997a 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ListRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ListRenderer.cs @@ -8,27 +8,25 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// public class ListRenderer : GemtextObjectRenderer { - protected override void Write( - GemtextRenderer renderer, - ListBlock listBlock) - { - // Lists need to be separated from the rest. - renderer.EnsureTwoLines(); + protected override void Write(GemtextRenderer renderer, ListBlock listBlock) + { + // Lists need to be separated from the rest. + renderer.EnsureTwoLines(); - // Go through each list item and write them out. - foreach (Block? item in listBlock) - { - // If the list only contains a link, then we just render the - // link instead. - var listItem = (ListItemBlock)item; + // Go through each list item and write them out. + foreach (Block? item in listBlock) + { + // If the list only contains a link, then we just render the + // link instead. + var listItem = (ListItemBlock)item; - if (!listItem.OnlyHasSingleLink()) - { - renderer.EnsureLine(); - renderer.Write("* "); - } + if (!listItem.OnlyHasSingleLink()) + { + renderer.EnsureLine(); + renderer.Write("* "); + } - renderer.WriteChildren(listItem); - } - } + renderer.WriteChildren(listItem); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/MarkdownDocumentRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/MarkdownDocumentRenderer.cs index 75a0194..08e1c36 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/MarkdownDocumentRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/MarkdownDocumentRenderer.cs @@ -1,5 +1,4 @@ using Markdig.Syntax; - using MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; @@ -8,20 +7,17 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// A Gemtext renderer for a . /// /// -public class MarkdownDocumentRenderer - : GemtextObjectRenderer +public class MarkdownDocumentRenderer : GemtextObjectRenderer { - protected override void Write( - GemtextRenderer renderer, - MarkdownDocument obj) - { - // Simply write out the contents. - renderer.WriteChildren(obj); + protected override void Write(GemtextRenderer renderer, MarkdownDocument obj) + { + // Simply write out the contents. + renderer.WriteChildren(obj); - // If we get to the end of the document and we have gathered links, - // and we are in DocumentEnd mode, then write out the links. We - // don't test for the mode here because if there are links, we - // should write them out. - LinkInlineRenderer.WriteGatheredLinks(renderer); - } + // If we get to the end of the document and we have gathered links, + // and we are in DocumentEnd mode, then write out the links. We + // don't test for the mode here because if there are links, we + // should write them out. + LinkInlineRenderer.WriteGatheredLinks(renderer); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ParagraphRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ParagraphRenderer.cs index e66b824..a423a0b 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ParagraphRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ParagraphRenderer.cs @@ -1,5 +1,4 @@ using Markdig.Syntax; - using MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; @@ -10,34 +9,31 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// public class ParagraphRenderer : GemtextObjectRenderer { - protected override void Write( - GemtextRenderer renderer, - ParagraphBlock obj) - { - // If we aren't the first in the container, we need to break apart - // the lines to make it easier to read. - if (!renderer.IsFirstInContainer) - { - renderer.EnsureTwoLines(); - } + protected override void Write(GemtextRenderer renderer, ParagraphBlock obj) + { + // If we aren't the first in the container, we need to break apart + // the lines to make it easier to read. + if (!renderer.IsFirstInContainer) + { + renderer.EnsureTwoLines(); + } - // We need to save the state of the link rendering while handling - // this block. - if (obj.OnlyHasSingleLink()) - { - renderer.WriteLeafInline(obj); - } - else - { - renderer.WhileLinkInsideBlock( - () => renderer.WriteLeafInline(obj)); - } + // We need to save the state of the link rendering while handling + // this block. + if (obj.OnlyHasSingleLink()) + { + renderer.WriteLeafInline(obj); + } + else + { + renderer.WhileLinkInsideBlock(() => renderer.WriteLeafInline(obj)); + } - // If we get to the end of the paragraph and we have gathered links, - // and we are in ParagraphEnd mode, then write out the links. - if (renderer.BlockLinkHandling == BlockLinkHandling.ParagraphEnd) - { - LinkInlineRenderer.WriteGatheredLinks(renderer); - } - } + // If we get to the end of the paragraph and we have gathered links, + // and we are in ParagraphEnd mode, then write out the links. + if (renderer.BlockLinkHandling == BlockLinkHandling.ParagraphEnd) + { + LinkInlineRenderer.WriteGatheredLinks(renderer); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/QuoteBlockRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/QuoteBlockRenderer.cs index 67fdf05..e662c33 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/QuoteBlockRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/QuoteBlockRenderer.cs @@ -8,13 +8,13 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// public class QuoteBlockRenderer : GemtextObjectRenderer { - protected override void Write(GemtextRenderer renderer, QuoteBlock obj) - { - string quoteIndent = obj.QuoteChar + " "; + protected override void Write(GemtextRenderer renderer, QuoteBlock obj) + { + string quoteIndent = obj.QuoteChar + " "; - renderer.EnsureTwoLines(); - renderer.PushIndent(quoteIndent); - renderer.WriteChildren(obj); - renderer.PopIndent(); - } + renderer.EnsureTwoLines(); + renderer.PushIndent(quoteIndent); + renderer.WriteChildren(obj); + renderer.PopIndent(); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/TableRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/TableRenderer.cs index 4bc1dc0..627661d 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/TableRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/TableRenderer.cs @@ -1,131 +1,126 @@ using ConsoleTableExt; - using Markdig.Extensions.Tables; namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; public class TableRenderer : GemtextObjectRenderer { - private readonly Action? configureTableBuilder; + private readonly Action? configureTableBuilder; - private readonly bool omitPreformat; + private readonly bool omitPreformat; - public TableRenderer( - bool omitPreformat, - Action? configureTableBuilder) - { - this.omitPreformat = omitPreformat; - this.configureTableBuilder = configureTableBuilder; - } + public TableRenderer(bool omitPreformat, Action? configureTableBuilder) + { + this.omitPreformat = omitPreformat; + this.configureTableBuilder = configureTableBuilder; + } - protected override void Write(GemtextRenderer renderer, Table table) - { - // Since Gemtext doesn't have a table format per-se, we are going - // to use ConsoleTableEx to make a nicely-formatted table and emit - // the lines directly. That should produce the desired result. + protected override void Write(GemtextRenderer renderer, Table table) + { + // Since Gemtext doesn't have a table format per-se, we are going + // to use ConsoleTableEx to make a nicely-formatted table and emit + // the lines directly. That should produce the desired result. - // Gather up information about the data since that is where the - // builder starts with. - bool hasHeader = false; - List header = new(); - List> data = new(); - Dictionary align = new(); + // Gather up information about the data since that is where the + // builder starts with. + bool hasHeader = false; + List header = new(); + List> data = new(); + Dictionary align = new(); - foreach (TableRow row in table.OfType()) - { - // If we haven't seen a header, then we include that. - if (!hasHeader && row.IsHeader) - { - header = GetCellValues(row); - SetAlignments(table, align, row); - continue; - } + foreach (TableRow row in table.OfType()) + { + // If we haven't seen a header, then we include that. + if (!hasHeader && row.IsHeader) + { + header = GetCellValues(row); + SetAlignments(table, align, row); + continue; + } - // Otherwise, we treat it as a row and go through the columns. - List cells = GetCellValues(row); + // Otherwise, we treat it as a row and go through the columns. + List cells = GetCellValues(row); - data.Add(cells); - } + data.Add(cells); + } - // Set up the table. - ConsoleTableBuilder builder = ConsoleTableBuilder - .From(data) - .WithColumn(header.OfType().ToArray()) - .WithHeaderTextAlignment(align) - .WithTextAlignment(align); + // Set up the table. + ConsoleTableBuilder builder = ConsoleTableBuilder + .From(data) + .WithColumn(header.OfType().ToArray()) + .WithHeaderTextAlignment(align) + .WithTextAlignment(align); - this.configureTableBuilder?.Invoke(builder); + this.configureTableBuilder?.Invoke(builder); - // Format the final table. - string formatted = builder.Export().ToString().TrimEnd(); + // Format the final table. + string formatted = builder.Export().ToString().TrimEnd(); - // Write out the table including making sure two lines are above it. - renderer.EnsureTwoLines(); + // Write out the table including making sure two lines are above it. + renderer.EnsureTwoLines(); - if (!this.omitPreformat) - { - renderer.WriteLine("```"); - } + if (!this.omitPreformat) + { + renderer.WriteLine("```"); + } - renderer.WriteLine(formatted); + renderer.WriteLine(formatted); - if (!this.omitPreformat) - { - renderer.WriteLine("```"); - renderer.WriteLine(); - } - } + if (!this.omitPreformat) + { + renderer.WriteLine("```"); + renderer.WriteLine(); + } + } - private static List GetCellValues(TableRow row) - { - List cells = new(); + private static List GetCellValues(TableRow row) + { + List cells = new(); - foreach (TableCell cell in row.OfType()) - { - // Write out to a text since we can't have a callback while - // rendering the table cells. - using var writer = new StringWriter(); - var innerRenderer = new GemtextRenderer(writer); + foreach (TableCell cell in row.OfType()) + { + // Write out to a text since we can't have a callback while + // rendering the table cells. + using var writer = new StringWriter(); + var innerRenderer = new GemtextRenderer(writer); - innerRenderer.Render(cell); - cells.Add(writer.ToString()); - } + innerRenderer.Render(cell); + cells.Add(writer.ToString()); + } - return cells; - } + return cells; + } - private static void SetAlignments( - Table table, - Dictionary align, - TableRow row) - { - for (int i = 0; i < row.Count; i++) - { - // Copied from Markdig's version. - var cell = (TableCell)row[i]; - int columnIndex = cell.ColumnIndex < 0 - || cell.ColumnIndex >= - table.ColumnDefinitions.Count - ? i - : cell.ColumnIndex; - columnIndex = - columnIndex >= table.ColumnDefinitions.Count - ? table.ColumnDefinitions.Count - 1 - : columnIndex; - TableColumnAlign? alignment = table - .ColumnDefinitions[columnIndex] - .Alignment; + private static void SetAlignments( + Table table, + Dictionary align, + TableRow row + ) + { + for (int i = 0; i < row.Count; i++) + { + // Copied from Markdig's version. + var cell = (TableCell)row[i]; + int columnIndex = + cell.ColumnIndex < 0 || cell.ColumnIndex >= table.ColumnDefinitions.Count + ? i + : cell.ColumnIndex; + columnIndex = + columnIndex >= table.ColumnDefinitions.Count + ? table.ColumnDefinitions.Count - 1 + : columnIndex; + TableColumnAlign? alignment = table.ColumnDefinitions[columnIndex].Alignment; - if (alignment.HasValue) - { - align[columnIndex] = alignment.Value switch - { - TableColumnAlign.Center => TextAligntment.Center, - TableColumnAlign.Left => TextAligntment.Left, - TableColumnAlign.Right => TextAligntment.Right, - _ => TextAligntment.Left, - }; - } - } - } + if (alignment.HasValue) + { + align[columnIndex] = alignment.Value switch + { + TableColumnAlign.Center => TextAligntment.Center, + TableColumnAlign.Left => TextAligntment.Left, + TableColumnAlign.Right => TextAligntment.Right, + _ => TextAligntment.Left, + }; + } + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ThematicBreakRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ThematicBreakRenderer.cs index 3886a04..92b5c21 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ThematicBreakRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Blocks/ThematicBreakRenderer.cs @@ -6,14 +6,11 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; /// A Gemtext renderer for a . /// /// -public class ThematicBreakRenderer - : GemtextObjectRenderer +public class ThematicBreakRenderer : GemtextObjectRenderer { - protected override void Write( - GemtextRenderer renderer, - ThematicBreakBlock obj) - { - renderer.EnsureTwoLines(); - renderer.WriteLine("---"); - } + protected override void Write(GemtextRenderer renderer, ThematicBreakBlock obj) + { + renderer.EnsureTwoLines(); + renderer.WriteLine("---"); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/GemtextObjectRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/GemtextObjectRenderer.cs index f568333..3175a0b 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/GemtextObjectRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/GemtextObjectRenderer.cs @@ -11,7 +11,5 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext; /// The type of the object. /// public abstract class GemtextObjectRenderer - : MarkdownObjectRenderer - where TObject : MarkdownObject -{ -} + : MarkdownObjectRenderer + where TObject : MarkdownObject { } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/CodeInlineRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/CodeInlineRenderer.cs index 81c3bb8..faa3d5c 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/CodeInlineRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/CodeInlineRenderer.cs @@ -8,22 +8,22 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; /// public class CodeInlineRenderer : GemtextObjectRenderer { - protected override void Write(GemtextRenderer renderer, CodeInline obj) - { - const string Delimiter = "`"; - InlineFormatting formatting = renderer.CodeFormattingResolved; - bool normalize = formatting == InlineFormatting.Normalize; + protected override void Write(GemtextRenderer renderer, CodeInline obj) + { + const string Delimiter = "`"; + InlineFormatting formatting = renderer.CodeFormattingResolved; + bool normalize = formatting == InlineFormatting.Normalize; - if (normalize) - { - renderer.Write(Delimiter); - } + if (normalize) + { + renderer.Write(Delimiter); + } - renderer.Write(obj.Content); + renderer.Write(obj.Content); - if (normalize) - { - renderer.Write(Delimiter); - } - } + if (normalize) + { + renderer.Write(Delimiter); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/DelimiterInlineRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/DelimiterInlineRenderer.cs index 1356874..f724c42 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/DelimiterInlineRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/DelimiterInlineRenderer.cs @@ -6,14 +6,11 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; /// A Gemtext renderer for a . /// /// -public class DelimiterInlineRenderer - : GemtextObjectRenderer +public class DelimiterInlineRenderer : GemtextObjectRenderer { - protected override void Write( - GemtextRenderer renderer, - DelimiterInline obj) - { - renderer.Write(obj.ToLiteral()); - renderer.WriteChildren(obj); - } + protected override void Write(GemtextRenderer renderer, DelimiterInline obj) + { + renderer.Write(obj.ToLiteral()); + renderer.WriteChildren(obj); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/EmphasisInlineRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/EmphasisInlineRenderer.cs index b77689b..52fcf36 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/EmphasisInlineRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/EmphasisInlineRenderer.cs @@ -8,24 +8,22 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; /// public class EmphasisInlineRenderer : GemtextObjectRenderer { - protected override void Write( - GemtextRenderer renderer, - EmphasisInline obj) - { - InlineFormatting formatting = renderer.EmphasisFormattingResolved; - bool normalize = formatting == InlineFormatting.Normalize; - string delimiter = new string('*', obj.DelimiterCount); + protected override void Write(GemtextRenderer renderer, EmphasisInline obj) + { + InlineFormatting formatting = renderer.EmphasisFormattingResolved; + bool normalize = formatting == InlineFormatting.Normalize; + string delimiter = new string('*', obj.DelimiterCount); - if (normalize) - { - renderer.Write(delimiter); - } + if (normalize) + { + renderer.Write(delimiter); + } - renderer.WriteChildren(obj); + renderer.WriteChildren(obj); - if (normalize) - { - renderer.Write(delimiter); - } - } + if (normalize) + { + renderer.Write(delimiter); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/GemtextSmartyPantRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/GemtextSmartyPantRenderer.cs index f25be71..3ac4ddc 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/GemtextSmartyPantRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/GemtextSmartyPantRenderer.cs @@ -1,5 +1,4 @@ using System.Net; - using Markdig.Extensions.SmartyPants; namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; @@ -8,33 +7,31 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; /// A Gemtext renderer for a . /// /// -public class GemtextSmartyPantRenderer - : GemtextObjectRenderer +public class GemtextSmartyPantRenderer : GemtextObjectRenderer { - private static readonly SmartyPantOptions DefaultOptions = new(); + private static readonly SmartyPantOptions DefaultOptions = new(); - private readonly SmartyPantOptions options; + private readonly SmartyPantOptions options; - /// - /// Initializes a new instance of the class. - /// - /// The options. - /// - public GemtextSmartyPantRenderer(SmartyPantOptions? options) - { - this.options = options - ?? throw new ArgumentNullException(nameof(options)); - } + /// + /// Initializes a new instance of the class. + /// + /// The options. + /// + public GemtextSmartyPantRenderer(SmartyPantOptions? options) + { + this.options = options ?? throw new ArgumentNullException(nameof(options)); + } - protected override void Write(GemtextRenderer renderer, SmartyPant obj) - { - if (!this.options.Mapping.TryGetValue(obj.Type, out string? text)) - { - DefaultOptions.Mapping.TryGetValue(obj.Type, out text); - } + protected override void Write(GemtextRenderer renderer, SmartyPant obj) + { + if (!this.options.Mapping.TryGetValue(obj.Type, out string? text)) + { + DefaultOptions.Mapping.TryGetValue(obj.Type, out text); + } - string? unicode = WebUtility.HtmlDecode(text); + string? unicode = WebUtility.HtmlDecode(text); - renderer.Write(unicode); - } + renderer.Write(unicode); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/HtmlEntityInlineRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/HtmlEntityInlineRenderer.cs index f003e3f..ea21093 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/HtmlEntityInlineRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/HtmlEntityInlineRenderer.cs @@ -6,13 +6,10 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; /// A Gemtext renderer for a . /// /// -public class HtmlEntityInlineRenderer - : GemtextObjectRenderer +public class HtmlEntityInlineRenderer : GemtextObjectRenderer { - protected override void Write( - GemtextRenderer renderer, - HtmlEntityInline obj) - { - renderer.Write(obj.Transcoded); - } + protected override void Write(GemtextRenderer renderer, HtmlEntityInline obj) + { + renderer.Write(obj.Transcoded); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LineBreakInlineRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LineBreakInlineRenderer.cs index 3e449c3..7ed1772 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LineBreakInlineRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LineBreakInlineRenderer.cs @@ -6,26 +6,23 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; /// A Gemtext renderer for a . /// /// -public class LineBreakInlineRenderer - : GemtextObjectRenderer +public class LineBreakInlineRenderer : GemtextObjectRenderer { - /// - /// Gets or sets a value indicating whether to render this softline break as a - /// Gemtext hardline break tag (<br />) - /// - public bool RenderAsHardlineBreak { get; set; } + /// + /// Gets or sets a value indicating whether to render this softline break as a + /// Gemtext hardline break tag (<br />) + /// + public bool RenderAsHardlineBreak { get; set; } - protected override void Write( - GemtextRenderer renderer, - LineBreakInline obj) - { - if (obj.IsHard || this.RenderAsHardlineBreak) - { - renderer.EnsureTwoLines(); - } - else - { - renderer.Write(" "); - } - } + protected override void Write(GemtextRenderer renderer, LineBreakInline obj) + { + if (obj.IsHard || this.RenderAsHardlineBreak) + { + renderer.EnsureTwoLines(); + } + else + { + renderer.Write(" "); + } + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LinkInlineRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LinkInlineRenderer.cs index ff8f44d..64a7fd2 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LinkInlineRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LinkInlineRenderer.cs @@ -8,116 +8,110 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; /// public class LinkInlineRenderer : GemtextObjectRenderer { - /// - /// Writes out any gathered links in a block. - /// - /// The renderer being used. - public static void WriteGatheredLinks(GemtextRenderer renderer) - { - // If we have no gathered links, then there is nothing to do. - if (renderer.GatheredLinks.Count <= 0) - { - return; - } + /// + /// Writes out any gathered links in a block. + /// + /// The renderer being used. + public static void WriteGatheredLinks(GemtextRenderer renderer) + { + // If we have no gathered links, then there is nothing to do. + if (renderer.GatheredLinks.Count <= 0) + { + return; + } - // Put some space between the previous object and this one, then - // write out each link which is already formatted. - renderer.WriteLine(); + // Put some space between the previous object and this one, then + // write out each link which is already formatted. + renderer.WriteLine(); - foreach (string? link in renderer.GatheredLinks) - { - renderer.WriteLine(); - renderer.Write(link); - } + foreach (string? link in renderer.GatheredLinks) + { + renderer.WriteLine(); + renderer.Write(link); + } - // Clear out the list of links. - renderer.GatheredLinks.Clear(); - } + // Clear out the list of links. + renderer.GatheredLinks.Clear(); + } - protected override void Write(GemtextRenderer renderer, LinkInline link) - { - // Figure out the various states we have. - bool outside = !renderer.LinkInsideBlock; - bool insert = !outside - && renderer.BlockLinkHandling == - BlockLinkHandling.InsertLine; - bool gather = !outside - && renderer.BlockLinkHandling switch - { - BlockLinkHandling.DocumentEnd => true, - BlockLinkHandling.ParagraphEnd => true, - _ => false, - }; - bool hasText = link.FirstChild != null; - bool footnotes = renderer.EndLinkInlineFormatting - == EndLinkInlineFormatting.Footnote; + protected override void Write(GemtextRenderer renderer, LinkInline link) + { + // Figure out the various states we have. + bool outside = !renderer.LinkInsideBlock; + bool insert = !outside && renderer.BlockLinkHandling == BlockLinkHandling.InsertLine; + bool gather = + !outside + && renderer.BlockLinkHandling switch + { + BlockLinkHandling.DocumentEnd => true, + BlockLinkHandling.ParagraphEnd => true, + _ => false, + }; + bool hasText = link.FirstChild != null; + bool footnotes = renderer.EndLinkInlineFormatting == EndLinkInlineFormatting.Footnote; - // Bare links and ones where we insert into the paragraph have - // their own line. - string? url = link.GetDynamicUrl != null - ? link.GetDynamicUrl() ?? link.Url - : link.Url; + // Bare links and ones where we insert into the paragraph have + // their own line. + string? url = link.GetDynamicUrl != null ? link.GetDynamicUrl() ?? link.Url : link.Url; - if (outside || insert) - { - // Make sure we are at the beginning of the line before - // rendering the link. - renderer.EnsureLine(); - renderer.Write("=> "); - renderer.Write(url); + if (outside || insert) + { + // Make sure we are at the beginning of the line before + // rendering the link. + renderer.EnsureLine(); + renderer.Write("=> "); + renderer.Write(url); - // If we have text, we need a space after the URL and before - // the text. - if (hasText) - { - renderer.Write(" "); - } - } + // If we have text, we need a space after the URL and before + // the text. + if (hasText) + { + renderer.Write(" "); + } + } - // Render the text for the link if we have it. - if (hasText) - { - renderer.WriteChildren(link); - } + // Render the text for the link if we have it. + if (hasText) + { + renderer.WriteChildren(link); + } - // If we are gathering, then write out a footnote. - if (gather) - { - int footnoteNumber = renderer.NextFootnoteNumber++; - string linkText = footnotes - ? footnoteNumber + ": " + url - : GetLinkText(link); + // If we are gathering, then write out a footnote. + if (gather) + { + int footnoteNumber = renderer.NextFootnoteNumber++; + string linkText = footnotes ? footnoteNumber + ": " + url : GetLinkText(link); - if (footnotes) - { - renderer.Write($"[{footnoteNumber}]"); - } + if (footnotes) + { + renderer.Write($"[{footnoteNumber}]"); + } - renderer.GatheredLinks.Add("=> " + url + " " + linkText); - } + renderer.GatheredLinks.Add("=> " + url + " " + linkText); + } - // If we are inserting a line in the paragraph, we need a final - // newline so the text of the paragraph continues on the next - // line. - if (insert) - { - renderer.WriteLine(); - } - } + // If we are inserting a line in the paragraph, we need a final + // newline so the text of the paragraph continues on the next + // line. + if (insert) + { + renderer.WriteLine(); + } + } - private static string GetLinkText(LinkInline link) - { - // This little bit of nasty code basically spins up a new renderer - // to get the text of the link by itself. Then we return that - // directly so it can be rendered as a link. - StringWriter writer = new(); - GemtextRenderer renderer = new(writer); + private static string GetLinkText(LinkInline link) + { + // This little bit of nasty code basically spins up a new renderer + // to get the text of the link by itself. Then we return that + // directly so it can be rendered as a link. + StringWriter writer = new(); + GemtextRenderer renderer = new(writer); - renderer.WriteChildren(link); - writer.Close(); + renderer.WriteChildren(link); + writer.Close(); - string text = writer.ToString(); + string text = writer.ToString(); - return text; - } + return text; + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LiteralInlineRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LiteralInlineRenderer.cs index e84d298..73a8551 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LiteralInlineRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/Inlines/LiteralInlineRenderer.cs @@ -8,31 +8,29 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; /// public class LiteralInlineRenderer : GemtextObjectRenderer { - protected override void Write( - GemtextRenderer renderer, - LiteralInline obj) - { - // If we are inside a paragraph and we are doing inline formatting, - // then we need to trim the text if we are before or after a link. - string content = obj.Content.ToString(); - BlockLinkHandling handling = renderer.BlockLinkHandling; - bool isInsert = handling == BlockLinkHandling.InsertLine; - bool inBlock = renderer.LinkInsideBlock; + protected override void Write(GemtextRenderer renderer, LiteralInline obj) + { + // If we are inside a paragraph and we are doing inline formatting, + // then we need to trim the text if we are before or after a link. + string content = obj.Content.ToString(); + BlockLinkHandling handling = renderer.BlockLinkHandling; + bool isInsert = handling == BlockLinkHandling.InsertLine; + bool inBlock = renderer.LinkInsideBlock; - if (inBlock && isInsert) - { - if (obj.PreviousSibling is LinkInline) - { - content = content.TrimStart(); - } + if (inBlock && isInsert) + { + if (obj.PreviousSibling is LinkInline) + { + content = content.TrimStart(); + } - if (obj.NextSibling is LinkInline) - { - content = content.TrimEnd(); - } - } + if (obj.NextSibling is LinkInline) + { + content = content.TrimEnd(); + } + } - // Write out the manipulated content. - renderer.Write(content); - } + // Write out the manipulated content. + renderer.Write(content); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/MarkdigExtensions.cs b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/MarkdigExtensions.cs index 07cdb5e..b17a9c7 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/MarkdigExtensions.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/Gemtext/MarkdigExtensions.cs @@ -8,27 +8,25 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext; /// public static class MarkdigExtensions { - /// - /// Determines if the paragraph only contains a link. - /// - /// The object to inspect. - /// True if there is only a link in the paragraph. - public static bool OnlyHasSingleLink(this ParagraphBlock obj) - { - return obj.Inline != null - && obj.Inline.Count() == 1 - && obj.Inline.FirstChild is LinkInline; - } + /// + /// Determines if the paragraph only contains a link. + /// + /// The object to inspect. + /// True if there is only a link in the paragraph. + public static bool OnlyHasSingleLink(this ParagraphBlock obj) + { + return obj.Inline != null && obj.Inline.Count() == 1 && obj.Inline.FirstChild is LinkInline; + } - /// - /// Determines if the list item only contains a link. - /// - /// The object to inspect. - /// True if there is only a link in the paragraph. - public static bool OnlyHasSingleLink(this ListItemBlock obj) - { - return obj.Count == 1 - && obj.LastChild is ParagraphBlock paragraphBlock - && paragraphBlock.OnlyHasSingleLink(); - } + /// + /// Determines if the list item only contains a link. + /// + /// The object to inspect. + /// True if there is only a link in the paragraph. + public static bool OnlyHasSingleLink(this ListItemBlock obj) + { + return obj.Count == 1 + && obj.LastChild is ParagraphBlock paragraphBlock + && paragraphBlock.OnlyHasSingleLink(); + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/GemtextRenderer.cs b/src/MfGames.Markdown.Gemtext/Renderers/GemtextRenderer.cs index a340a3d..49a1d08 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/GemtextRenderer.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/GemtextRenderer.cs @@ -1,7 +1,6 @@ using Markdig.Helpers; using Markdig.Renderers; using Markdig.Syntax; - using MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks; using MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines; @@ -9,175 +8,172 @@ namespace MfGames.Markdown.Gemtext.Renderers; public class GemtextRenderer : TextRendererBase { - /// - public GemtextRenderer(TextWriter writer) - : base(writer) - { - // Set up our default values. - this.NextFootnoteNumber = 1; - this.GatheredLinks = new List(); + /// + public GemtextRenderer(TextWriter writer) + : base(writer) + { + // Set up our default values. + this.NextFootnoteNumber = 1; + this.GatheredLinks = new List(); - // Default block renderers. - this.ObjectRenderers.Add(new CustomContainerRenderer()); - this.ObjectRenderers.Add(new CodeBlockRenderer()); - this.ObjectRenderers.Add(new HeadingRenderer()); - this.ObjectRenderers.Add(new HtmlBlockRenderer()); - this.ObjectRenderers.Add(new ListRenderer()); - this.ObjectRenderers.Add(new MarkdownDocumentRenderer()); - this.ObjectRenderers.Add(new ParagraphRenderer()); - this.ObjectRenderers.Add(new QuoteBlockRenderer()); - this.ObjectRenderers.Add(new ThematicBreakRenderer()); + // Default block renderers. + this.ObjectRenderers.Add(new CustomContainerRenderer()); + this.ObjectRenderers.Add(new CodeBlockRenderer()); + this.ObjectRenderers.Add(new HeadingRenderer()); + this.ObjectRenderers.Add(new HtmlBlockRenderer()); + this.ObjectRenderers.Add(new ListRenderer()); + this.ObjectRenderers.Add(new MarkdownDocumentRenderer()); + this.ObjectRenderers.Add(new ParagraphRenderer()); + this.ObjectRenderers.Add(new QuoteBlockRenderer()); + this.ObjectRenderers.Add(new ThematicBreakRenderer()); - // Default inline renderers. - this.ObjectRenderers.Add(new CodeInlineRenderer()); - this.ObjectRenderers.Add(new DelimiterInlineRenderer()); - this.ObjectRenderers.Add(new EmphasisInlineRenderer()); - this.ObjectRenderers.Add(new HtmlEntityInlineRenderer()); - this.ObjectRenderers.Add(new LineBreakInlineRenderer()); - this.ObjectRenderers.Add(new LinkInlineRenderer()); - this.ObjectRenderers.Add(new LiteralInlineRenderer()); - } + // Default inline renderers. + this.ObjectRenderers.Add(new CodeInlineRenderer()); + this.ObjectRenderers.Add(new DelimiterInlineRenderer()); + this.ObjectRenderers.Add(new EmphasisInlineRenderer()); + this.ObjectRenderers.Add(new HtmlEntityInlineRenderer()); + this.ObjectRenderers.Add(new LineBreakInlineRenderer()); + this.ObjectRenderers.Add(new LinkInlineRenderer()); + this.ObjectRenderers.Add(new LiteralInlineRenderer()); + } - /// - /// Gets or sets how to handle links inside paragraphs and other blocks. - /// - public BlockLinkHandling BlockLinkHandling { get; set; } + /// + /// Gets or sets how to handle links inside paragraphs and other blocks. + /// + public BlockLinkHandling BlockLinkHandling { get; set; } - /// - /// Gets or sets the optional formatting for code inlines (backticks). - /// If this is unset, then `InlineFormatting` will be used. - /// - public InlineFormatting? CodeFormatting { get; set; } + /// + /// Gets or sets the optional formatting for code inlines (backticks). + /// If this is unset, then `InlineFormatting` will be used. + /// + public InlineFormatting? CodeFormatting { get; set; } - /// - /// Gets the actual formatting for code inlines (backticks) which - /// is either `CodeInlineFormatting` or `InlineFormatting` if that - /// is not set. - /// - public InlineFormatting CodeFormattingResolved => - this.CodeFormatting ?? this.InlineFormatting; + /// + /// Gets the actual formatting for code inlines (backticks) which + /// is either `CodeInlineFormatting` or `InlineFormatting` if that + /// is not set. + /// + public InlineFormatting CodeFormattingResolved => this.CodeFormatting ?? this.InlineFormatting; - /// - /// Gets or sets the optional formatting for emphasis (which includes - /// italics and bolds). If this is unset, then `InlineFormatting` - /// will be used. - /// - public InlineFormatting? EmphasisFormatting { get; set; } + /// + /// Gets or sets the optional formatting for emphasis (which includes + /// italics and bolds). If this is unset, then `InlineFormatting` + /// will be used. + /// + public InlineFormatting? EmphasisFormatting { get; set; } - /// - /// Gets the actual formatting for emphasis which is either - /// `EmphasisFormatting` or `InlineFormatting` if that isn't set. - /// - public InlineFormatting EmphasisFormattingResolved => - this.EmphasisFormatting ?? this.InlineFormatting; + /// + /// Gets the actual formatting for emphasis which is either + /// `EmphasisFormatting` or `InlineFormatting` if that isn't set. + /// + public InlineFormatting EmphasisFormattingResolved => + this.EmphasisFormatting ?? this.InlineFormatting; - /// - /// Gets or sets the formatting for how links that are gathered at the - /// end of a paragraph or document are formatted inside the paragraph. - /// - public EndLinkInlineFormatting EndLinkInlineFormatting { get; set; } + /// + /// Gets or sets the formatting for how links that are gathered at the + /// end of a paragraph or document are formatted inside the paragraph. + /// + public EndLinkInlineFormatting EndLinkInlineFormatting { get; set; } - /// - /// Gets the current list of formatted links that have been gathered - /// up to this point for rendering. - /// - public List GatheredLinks { get; } + /// + /// Gets the current list of formatted links that have been gathered + /// up to this point for rendering. + /// + public List GatheredLinks { get; } - /// - /// Gets or sets the formatting rule for HTML blocks. - /// - public HtmlBlockFormatting HtmlBlockFormatting { get; set; } + /// + /// Gets or sets the formatting rule for HTML blocks. + /// + public HtmlBlockFormatting HtmlBlockFormatting { get; set; } - /// - /// Gets or sets the default formatting for all inlines. - /// - public InlineFormatting InlineFormatting { get; set; } + /// + /// Gets or sets the default formatting for all inlines. + /// + public InlineFormatting InlineFormatting { get; set; } - /// - /// An internal processing flag that determines if the rendered link - /// is inside a block or not to trigger extra handling. - /// - public bool LinkInsideBlock { get; set; } + /// + /// An internal processing flag that determines if the rendered link + /// is inside a block or not to trigger extra handling. + /// + public bool LinkInsideBlock { get; set; } - /// - /// Gets or sets the next footnote while rendering links. - /// - public int NextFootnoteNumber { get; set; } + /// + /// Gets or sets the next footnote while rendering links. + /// + public int NextFootnoteNumber { get; set; } - /// - /// Ensures there are two blank lines before an element. - /// - /// - public GemtextRenderer EnsureTwoLines() - { - if (this.previousWasLine) - { - return this; - } + /// + /// Ensures there are two blank lines before an element. + /// + /// + public GemtextRenderer EnsureTwoLines() + { + if (this.previousWasLine) + { + return this; + } - this.WriteLine(); - this.WriteLine(); + this.WriteLine(); + this.WriteLine(); - return this; - } + return this; + } - /// - /// A wrapper method to push the state of LinkInsideBlock while - /// performing an action. - /// - /// The action to perform. - public void WhileLinkInsideBlock(Action action) - { - bool oldState = this.LinkInsideBlock; - this.LinkInsideBlock = true; - action(); - this.LinkInsideBlock = oldState; - } + /// + /// A wrapper method to push the state of LinkInsideBlock while + /// performing an action. + /// + /// The action to perform. + public void WhileLinkInsideBlock(Action action) + { + bool oldState = this.LinkInsideBlock; + this.LinkInsideBlock = true; + action(); + this.LinkInsideBlock = oldState; + } - /// - /// Writes the lines of a - /// - /// The leaf block. - /// if set to true write end of lines. - /// This instance - public GemtextRenderer WriteLeafRawLines( - LeafBlock leafBlock, - bool writeEndOfLines) - { - // Make sure we have sane input. - if (leafBlock == null) - { - throw new ArgumentNullException(nameof(leafBlock)); - } + /// + /// Writes the lines of a + /// + /// The leaf block. + /// if set to true write end of lines. + /// This instance + public GemtextRenderer WriteLeafRawLines(LeafBlock leafBlock, bool writeEndOfLines) + { + // Make sure we have sane input. + if (leafBlock == null) + { + throw new ArgumentNullException(nameof(leafBlock)); + } - // If we have nothing to write, then don't do anything. Even though - // Markdig says this can't be null, `leafBlock.Lines` may be null - // according to the comments. - // ReSharper disable once ConditionIsAlwaysTrueOrFalse - if (leafBlock.Lines.Lines == null) - { - return this; - } + // If we have nothing to write, then don't do anything. Even though + // Markdig says this can't be null, `leafBlock.Lines` may be null + // according to the comments. + // ReSharper disable once ConditionIsAlwaysTrueOrFalse + if (leafBlock.Lines.Lines == null) + { + return this; + } - // Go through the block and write out each of the lines. - StringLineGroup lines = leafBlock.Lines; - StringLine[] slices = lines.Lines; + // Go through the block and write out each of the lines. + StringLineGroup lines = leafBlock.Lines; + StringLine[] slices = lines.Lines; - for (int i = 0; i < lines.Count; i++) - { - if (!writeEndOfLines && i > 0) - { - this.WriteLine(); - } + for (int i = 0; i < lines.Count; i++) + { + if (!writeEndOfLines && i > 0) + { + this.WriteLine(); + } - this.Write(ref slices[i].Slice); + this.Write(ref slices[i].Slice); - if (writeEndOfLines) - { - this.WriteLine(); - } - } + if (writeEndOfLines) + { + this.WriteLine(); + } + } - return this; - } + return this; + } } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/HtmlBlockFormatting.cs b/src/MfGames.Markdown.Gemtext/Renderers/HtmlBlockFormatting.cs index 36dd530..31dca8b 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/HtmlBlockFormatting.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/HtmlBlockFormatting.cs @@ -5,14 +5,14 @@ namespace MfGames.Markdown.Gemtext.Renderers; /// public enum HtmlBlockFormatting { - /// - /// Indicates that HTML code blocks should just be removed. - /// - Remove, + /// + /// Indicates that HTML code blocks should just be removed. + /// + Remove, - /// - /// Indicates that HTML code blocks should be treated as blocks with - /// "html" as the type. - /// - CodeBlock, + /// + /// Indicates that HTML code blocks should be treated as blocks with + /// "html" as the type. + /// + CodeBlock, } diff --git a/src/MfGames.Markdown.Gemtext/Renderers/InlineFormatting.cs b/src/MfGames.Markdown.Gemtext/Renderers/InlineFormatting.cs index 565a41a..6983f63 100644 --- a/src/MfGames.Markdown.Gemtext/Renderers/InlineFormatting.cs +++ b/src/MfGames.Markdown.Gemtext/Renderers/InlineFormatting.cs @@ -6,15 +6,15 @@ namespace MfGames.Markdown.Gemtext.Renderers; /// public enum InlineFormatting { - /// - /// Indicates that the inline should be remove and only the text - /// rendered. - /// - Remove, + /// + /// Indicates that the inline should be remove and only the text + /// rendered. + /// + Remove, - /// - /// Indicates that the inline should be left in place in a normalized - /// form (such as converting `_italics_` into `*italics*`). - /// - Normalize, + /// + /// Indicates that the inline should be left in place in a normalized + /// form (such as converting `_italics_` into `*italics*`). + /// + Normalize, } diff --git a/src/MfGames.Markdown/Extensions/WikiLink.cs b/src/MfGames.Markdown/Extensions/WikiLink.cs index eaed4af..4f86161 100644 --- a/src/MfGames.Markdown/Extensions/WikiLink.cs +++ b/src/MfGames.Markdown/Extensions/WikiLink.cs @@ -4,8 +4,8 @@ namespace MfGames.Markdown.Extensions; public class WikiLink : LinkInline { - public WikiLink() - { - this.IsClosed = false; - } + public WikiLink() + { + this.IsClosed = false; + } } diff --git a/src/MfGames.Markdown/Extensions/WikiLinkExtension.cs b/src/MfGames.Markdown/Extensions/WikiLinkExtension.cs index 45347d8..26d0596 100644 --- a/src/MfGames.Markdown/Extensions/WikiLinkExtension.cs +++ b/src/MfGames.Markdown/Extensions/WikiLinkExtension.cs @@ -9,39 +9,34 @@ namespace MfGames.Markdown.Extensions; /// public class WikiLinkExtension : IMarkdownExtension { - public WikiLinkExtension() - : this(null) - { - } + public WikiLinkExtension() + : this(null) { } - public WikiLinkExtension(WikiLinkOptions? options) - { - this.Options = options ?? new WikiLinkOptions(); - } + public WikiLinkExtension(WikiLinkOptions? options) + { + this.Options = options ?? new WikiLinkOptions(); + } - public WikiLinkOptions Options { get; set; } + public WikiLinkOptions Options { get; set; } - /// - public void Setup(MarkdownPipelineBuilder pipeline) - { - WikiLinkInlineParser? parser = pipeline.InlineParsers - .FindExact(); + /// + public void Setup(MarkdownPipelineBuilder pipeline) + { + WikiLinkInlineParser? parser = pipeline.InlineParsers.FindExact(); - if (parser != null) - { - return; - } + if (parser != null) + { + return; + } - parser = new WikiLinkInlineParser(this.Options); - pipeline.InlineParsers.InsertBefore(parser); - } + parser = new WikiLinkInlineParser(this.Options); + pipeline.InlineParsers.InsertBefore(parser); + } - /// - public void Setup( - MarkdownPipeline pipeline, - IMarkdownRenderer renderer) - { - // No setup needed here because we're using LinkInline which does the - // bulk of the work. - } + /// + public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer) + { + // No setup needed here because we're using LinkInline which does the + // bulk of the work. + } } diff --git a/src/MfGames.Markdown/Extensions/WikiLinkInlineParser.cs b/src/MfGames.Markdown/Extensions/WikiLinkInlineParser.cs index 61050f7..677cce9 100644 --- a/src/MfGames.Markdown/Extensions/WikiLinkInlineParser.cs +++ b/src/MfGames.Markdown/Extensions/WikiLinkInlineParser.cs @@ -6,105 +6,98 @@ namespace MfGames.Markdown.Extensions; public class WikiLinkInlineParser : InlineParser { - private readonly WikiLinkOptions options; + private readonly WikiLinkOptions options; - public WikiLinkInlineParser(WikiLinkOptions options) - { - this.options = options; - this.OpeningCharacters = new[] { '[' }; - } + public WikiLinkInlineParser(WikiLinkOptions options) + { + this.options = options; + this.OpeningCharacters = new[] { '[' }; + } - /// - public override bool Match( - InlineProcessor processor, - ref StringSlice slice) - { - // We are looking for the `[[` opening for the tag and that the first - // one isn't escaped. - if (IsNotDelimiter(slice, '[')) - { - return false; - } + /// + public override bool Match(InlineProcessor processor, ref StringSlice slice) + { + // We are looking for the `[[` opening for the tag and that the first + // one isn't escaped. + if (IsNotDelimiter(slice, '[')) + { + return false; + } - // We need to loop over the entire link, including the `[[` and `]]` - // while keeping track since we'll swallow additional characters beyond - // the link. - int linkStart = slice.Start; - int linkEnd = slice.Start; + // We need to loop over the entire link, including the `[[` and `]]` + // while keeping track since we'll swallow additional characters beyond + // the link. + int linkStart = slice.Start; + int linkEnd = slice.Start; - slice.Start += 2; + slice.Start += 2; - // Our content starts after the double '[['. - int contentStart = slice.Start; + // Our content starts after the double '[['. + int contentStart = slice.Start; - // We need to find the end of the link (the `]]`). - while (IsNotDelimiter(slice, ']')) - { - slice.NextChar(); - linkEnd = slice.Start; - } + // We need to find the end of the link (the `]]`). + while (IsNotDelimiter(slice, ']')) + { + slice.NextChar(); + linkEnd = slice.Start; + } - // Pull out the components before we adjust for the ']]' for the end. - int contentEnd = linkEnd; + // Pull out the components before we adjust for the ']]' for the end. + int contentEnd = linkEnd; - // Finish skipping over the `]]`. - slice.NextChar(); - slice.NextChar(); + // Finish skipping over the `]]`. + slice.NextChar(); + slice.NextChar(); - // Format the label and the URL. - string content = slice.Text.Substring( - contentStart, - contentEnd - contentStart); - string[] contentParts = content.Split('|', 2); - string label = contentParts.Last(); - string url = this.options.GetUrl(contentParts.First()); + // Format the label and the URL. + string content = slice.Text.Substring(contentStart, contentEnd - contentStart); + string[] contentParts = content.Split('|', 2); + string label = contentParts.Last(); + string url = this.options.GetUrl(contentParts.First()); - // Add in any trailing components. This merges the `'s` from - // `[[Dale]]'s` into the label. - while (this.options.IsTrailingLink(slice.CurrentChar)) - { - label += slice.CurrentChar; - slice.NextChar(); - linkEnd++; - } + // Add in any trailing components. This merges the `'s` from + // `[[Dale]]'s` into the label. + while (this.options.IsTrailingLink(slice.CurrentChar)) + { + label += slice.CurrentChar; + slice.NextChar(); + linkEnd++; + } - // Create the link that we're replacing. - WikiLink link = new() - { - Span = - { - Start = processor.GetSourcePosition( - linkStart, - out int line, - out int column), - }, - Line = line, - Column = column, - Url = url, - IsClosed = true, - }; + // Create the link that we're replacing. + WikiLink link = + new() + { + Span = + { + Start = processor.GetSourcePosition(linkStart, out int line, out int column), + }, + Line = line, + Column = column, + Url = url, + IsClosed = true, + }; - link.AppendChild( - new LiteralInline() - { - Line = line, - Column = column, - Content = new StringSlice(label), - IsClosed = true, - }); + link.AppendChild( + new LiteralInline() + { + Line = line, + Column = column, + Content = new StringSlice(label), + IsClosed = true, + } + ); - // Replace the inline and then indicate we have a match. - processor.Inline = link; + // Replace the inline and then indicate we have a match. + processor.Inline = link; - return true; - } + return true; + } - private static bool IsNotDelimiter( - StringSlice slice, - char delimiter) - { - return slice.CurrentChar != delimiter - || slice.PeekChar() != delimiter - || slice.PeekCharExtra(-1) == '\\'; - } + private static bool IsNotDelimiter(StringSlice slice, char delimiter) + { + return slice.CurrentChar != delimiter + || slice.PeekChar() != delimiter + || slice.PeekCharExtra(-1) == '\\'; + } } diff --git a/src/MfGames.Markdown/Extensions/WikiLinkOptions.cs b/src/MfGames.Markdown/Extensions/WikiLinkOptions.cs index 46493b9..af8cf7e 100644 --- a/src/MfGames.Markdown/Extensions/WikiLinkOptions.cs +++ b/src/MfGames.Markdown/Extensions/WikiLinkOptions.cs @@ -4,26 +4,26 @@ namespace MfGames.Markdown.Extensions; public class WikiLinkOptions { - public WikiLinkOptions() - { - this.GetUrl = a => a; - this.IsTrailingLink = a => a.IsAlpha() || a == '\''; - } + public WikiLinkOptions() + { + this.GetUrl = a => a; + this.IsTrailingLink = a => a.IsAlpha() || a == '\''; + } - /// - /// The callback to determine the link from the given wiki link. This does - /// not include trailing additions or use the label (e.g., `(ab|cd)` would - /// get `ab` as the parameters of this function. - /// - public Func GetUrl { get; set; } + /// + /// The callback to determine the link from the given wiki link. This does + /// not include trailing additions or use the label (e.g., `(ab|cd)` would + /// get `ab` as the parameters of this function. + /// + public Func GetUrl { get; set; } - /// - /// - /// A callback to determine if the text after the link should be merged - /// with the link label. This allows links such as [[Dale]]'s to be turned - /// into "Dale's" but pointing to "Dale" as a page. - /// - /// The default is to include any character or the apostrophe. - /// - public Func IsTrailingLink { get; set; } + /// + /// + /// A callback to determine if the text after the link should be merged + /// with the link label. This allows links such as [[Dale]]'s to be turned + /// into "Dale's" but pointing to "Dale" as a page. + /// + /// The default is to include any character or the apostrophe. + /// + public Func IsTrailingLink { get; set; } } diff --git a/src/MfGames.Markdown/README.md b/src/MfGames.Markdown/README.md index a05b7d8..f6788a8 100644 --- a/src/MfGames.Markdown/README.md +++ b/src/MfGames.Markdown/README.md @@ -5,9 +5,9 @@ in [MarkDig](https://github.com/xoofx/markdig), an extensible library for conver The library includes the following: -- An extension for converting wiki links, such as `[[MfGames]]` into a link based on the title. This is for both HTML - and Gemtext. -- A output library for using MarkDig to generate Gemtext for Gemini pods. +- An extension for converting wiki links, such as `[[MfGames]]` into a link based on the title. This is for both HTML + and Gemtext. +- A output library for using MarkDig to generate Gemtext for Gemini pods. The documentation is rather light at the moment, but the tests can show various ways of using the libraries. @@ -37,5 +37,5 @@ repository. The two libraries are: -- MfGames.Markdown -- MfGames.Markdown.Gemtext +- MfGames.Markdown +- MfGames.Markdown.Gemtext diff --git a/src/MfGames.Nitride.Calendar/CreateCalendarValidator.cs b/src/MfGames.Nitride.Calendar/CreateCalendarValidator.cs index 66522d2..d931d4c 100644 --- a/src/MfGames.Nitride.Calendar/CreateCalendarValidator.cs +++ b/src/MfGames.Nitride.Calendar/CreateCalendarValidator.cs @@ -4,15 +4,12 @@ namespace MfGames.Nitride.Calendar; public class CreateCalendarValidator : AbstractValidator { - public CreateCalendarValidator() - { - this.RuleFor(x => x.Path) - .NotNull(); + public CreateCalendarValidator() + { + this.RuleFor(x => x.Path).NotNull(); - this.RuleFor(x => x.GetEventSummary) - .NotNull(); + this.RuleFor(x => x.GetEventSummary).NotNull(); - this.RuleFor(x => x.GetEventUrl) - .NotNull(); - } + this.RuleFor(x => x.GetEventUrl).NotNull(); + } } diff --git a/src/MfGames.Nitride.Calendar/CreateCalender.cs b/src/MfGames.Nitride.Calendar/CreateCalender.cs index 905a4fc..f29b4b8 100644 --- a/src/MfGames.Nitride.Calendar/CreateCalender.cs +++ b/src/MfGames.Nitride.Calendar/CreateCalender.cs @@ -1,16 +1,12 @@ using FluentValidation; - using Ical.Net.CalendarComponents; using Ical.Net.DataTypes; using Ical.Net.Serialization; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Generators; using MfGames.Nitride.Temporal; - using NodaTime; - using Zio; namespace MfGames.Nitride.Calendar; @@ -23,91 +19,88 @@ namespace MfGames.Nitride.Calendar; [WithProperties] public partial class CreateCalender : OperationBase { - private readonly TimeService clock; + private readonly TimeService clock; - private readonly IValidator validator; + private readonly IValidator validator; - public CreateCalender( - IValidator validator, - TimeService clock) - { - this.validator = validator; - this.clock = clock; - } + public CreateCalender(IValidator validator, TimeService clock) + { + this.validator = validator; + this.clock = clock; + } - /// - /// Gets or sets a callback to get the summary of the event representing - /// the entity. - /// - public Func? GetEventSummary { get; set; } + /// + /// Gets or sets a callback to get the summary of the event representing + /// the entity. + /// + public Func? GetEventSummary { get; set; } - /// - /// Gets or sets a callback to get the optional URL of an event for - /// the entity. - /// - public Func? GetEventUrl { get; set; } + /// + /// Gets or sets a callback to get the optional URL of an event for + /// the entity. + /// + public Func? GetEventUrl { get; set; } - /// - /// Gets or sets the file system path for the resulting calendar. - /// - public UPath? Path { get; set; } + /// + /// Gets or sets the file system path for the resulting calendar. + /// + public UPath? Path { get; set; } - /// - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + /// + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - SplitEntityEnumerations split = input.SplitEntity(); - IEnumerable datedAndCalendars = - this.CreateCalendarEntity(split.HasAll); + SplitEntityEnumerations split = input.SplitEntity(); + IEnumerable datedAndCalendars = this.CreateCalendarEntity(split.HasAll); - return datedAndCalendars.Union(split.NotHasAll); - } + return datedAndCalendars.Union(split.NotHasAll); + } - private IEnumerable CreateCalendarEntity( - IEnumerable entities) - { - // Create the calendar in the same time zone as the rest of the system. - var calendar = new Ical.Net.Calendar(); + private IEnumerable CreateCalendarEntity(IEnumerable entities) + { + // Create the calendar in the same time zone as the rest of the system. + var calendar = new Ical.Net.Calendar(); - calendar.TimeZones.Add(new VTimeZone(this.clock.DateTimeZone.Id)); + calendar.TimeZones.Add(new VTimeZone(this.clock.DateTimeZone.Id)); - // Go through the events and add all of them. - var input = entities.ToList(); - IEnumerable events = - input.Select(this.CreateCalendarEvent); + // Go through the events and add all of them. + var input = entities.ToList(); + IEnumerable events = input.Select(this.CreateCalendarEvent); - calendar.Events.AddRange(events); + calendar.Events.AddRange(events); - // Create the iCalendar file. - var serializer = new CalendarSerializer(); - string serializedCalendar = serializer.SerializeToString(calendar); + // Create the iCalendar file. + var serializer = new CalendarSerializer(); + string serializedCalendar = serializer.SerializeToString(calendar); - // Create the calendar entity and populate everything. - Entity calendarEntity = new Entity().Set(IsCalendar.Instance) - .Set(this.Path!.Value) - .SetTextContent(serializedCalendar); + // Create the calendar entity and populate everything. + Entity calendarEntity = new Entity() + .Set(IsCalendar.Instance) + .Set(this.Path!.Value) + .SetTextContent(serializedCalendar); - // Return the results along with the new calendar. - return input.Union(new[] { calendarEntity }); - } + // Return the results along with the new calendar. + return input.Union(new[] { calendarEntity }); + } - private CalendarEvent CreateCalendarEvent(Entity entity) - { - Instant instant = entity.Get(); - var when = this.clock.ToDateTime(instant); - string summary = this.GetEventSummary!(entity); - Uri? url = this.GetEventUrl?.Invoke(entity); + private CalendarEvent CreateCalendarEvent(Entity entity) + { + Instant instant = entity.Get(); + var when = this.clock.ToDateTime(instant); + string summary = this.GetEventSummary!(entity); + Uri? url = this.GetEventUrl?.Invoke(entity); - var calendarEvent = new CalendarEvent - { - Summary = summary, - Start = new CalDateTime(when), - Url = url, - }; + var calendarEvent = new CalendarEvent + { + Summary = summary, + Start = new CalDateTime(when), + Url = url, + }; - return calendarEvent; - } + return calendarEvent; + } } diff --git a/src/MfGames.Nitride.Calendar/IsCalendar.cs b/src/MfGames.Nitride.Calendar/IsCalendar.cs index d9c190b..fb4bab1 100644 --- a/src/MfGames.Nitride.Calendar/IsCalendar.cs +++ b/src/MfGames.Nitride.Calendar/IsCalendar.cs @@ -6,6 +6,4 @@ namespace MfGames.Nitride.Calendar; /// A marker component for identifying an entity that represents a calendar. /// [SingletonComponent] -public partial class IsCalendar -{ -} +public partial class IsCalendar { } diff --git a/src/MfGames.Nitride.Calendar/NitrideCalendarBuilderExtensions.cs b/src/MfGames.Nitride.Calendar/NitrideCalendarBuilderExtensions.cs index 81fd5fd..9e57db1 100644 --- a/src/MfGames.Nitride.Calendar/NitrideCalendarBuilderExtensions.cs +++ b/src/MfGames.Nitride.Calendar/NitrideCalendarBuilderExtensions.cs @@ -1,26 +1,23 @@ using Autofac; - using MfGames.Nitride.Temporal.Setup; namespace MfGames.Nitride.Calendar; public static class NitrideCalendarBuilderExtensions { - private static bool loaded; + private static bool loaded; - public static NitrideBuilder UseCalendar(this NitrideBuilder builder) - { - // If we've already loaded, then we have a problem. - if (loaded) - { - throw new InvalidOperationException( - "Cannot use UseCalendar() more than once."); - } + public static NitrideBuilder UseCalendar(this NitrideBuilder builder) + { + // If we've already loaded, then we have a problem. + if (loaded) + { + throw new InvalidOperationException("Cannot use UseCalendar() more than once."); + } - loaded = true; + loaded = true; - // Get the configuration so we can set the various options. - return builder - .ConfigureContainer(x => x.RegisterModule()); - } + // Get the configuration so we can set the various options. + return builder.ConfigureContainer(x => x.RegisterModule()); + } } diff --git a/src/MfGames.Nitride.Calendar/NitrideCalendarModule.cs b/src/MfGames.Nitride.Calendar/NitrideCalendarModule.cs index d3a7ae9..e5b1a28 100644 --- a/src/MfGames.Nitride.Calendar/NitrideCalendarModule.cs +++ b/src/MfGames.Nitride.Calendar/NitrideCalendarModule.cs @@ -1,16 +1,15 @@ using Autofac; - using MfGames.Nitride.Temporal.Setup; namespace MfGames.Nitride.Calendar; public class NitrideCalendarModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - builder.RegisterModule(); - builder.RegisterOperators(this); - builder.RegisterValidators(this); - } + /// + protected override void Load(ContainerBuilder builder) + { + builder.RegisterModule(); + builder.RegisterOperators(this); + builder.RegisterValidators(this); + } } diff --git a/src/MfGames.Nitride.Exec/ExecOperation.cs b/src/MfGames.Nitride.Exec/ExecOperation.cs index efd4d3d..d451704 100644 --- a/src/MfGames.Nitride.Exec/ExecOperation.cs +++ b/src/MfGames.Nitride.Exec/ExecOperation.cs @@ -1,13 +1,9 @@ using System.Runtime.CompilerServices; - using CliWrap; using CliWrap.Buffered; - using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Generators; - using Serilog; // ReSharper disable ClassNeverInstantiated.Global @@ -20,102 +16,97 @@ namespace MfGames.Nitride.Exec; [WithProperties] public partial class ExecOperation : AsyncOperationBase { - private readonly ILogger logger; + private readonly ILogger logger; - private readonly IValidator validator; + private readonly IValidator validator; - public ExecOperation( - ILogger logger, - IValidator validator) - { - this.logger = logger.ForContext(); - this.validator = validator; - } + public ExecOperation(ILogger logger, IValidator validator) + { + this.logger = logger.ForContext(); + this.validator = validator; + } - /// - /// Gets or sets the command associated with this operation. - /// - public Func? CreateCommand { get; set; } + /// + /// Gets or sets the command associated with this operation. + /// + public Func? CreateCommand { get; set; } - /// - /// Gets or sets a callback to process the buffered output. - /// - /// - /// This is mutually exclusive with OnResult. - /// - public Func>? OnBufferedResult - { - get; - set; - } + /// + /// Gets or sets a callback to process the buffered output. + /// + /// + /// This is mutually exclusive with OnResult. + /// + public Func>? OnBufferedResult { get; set; } - /// - /// Gets or sets a callback to process the output. - /// - /// - /// This is mutually exclusive with OnBufferedResult. - /// - public Func>? OnResult { get; set; } + /// + /// Gets or sets a callback to process the output. + /// + /// + /// This is mutually exclusive with OnBufferedResult. + /// + public Func>? OnResult { get; set; } - /// - public override async IAsyncEnumerable RunAsync( - IAsyncEnumerable input, - [EnumeratorCancellation] CancellationToken cancellationToken = default) - { - // Make sure everything is validated. - await this.validator.ValidateAndThrowAsync(this, cancellationToken); + /// + public override async IAsyncEnumerable RunAsync( + IAsyncEnumerable input, + [EnumeratorCancellation] CancellationToken cancellationToken = default + ) + { + // Make sure everything is validated. + await this.validator.ValidateAndThrowAsync(this, cancellationToken); - // Drain the inputs. - await foreach (Entity item in input.WithCancellation(cancellationToken)) - { - yield return item; - } + // Drain the inputs. + await foreach (Entity item in input.WithCancellation(cancellationToken)) + { + yield return item; + } - // Create the command from the input, then execute it as a buffered - // output if we have a buffered result callback, otherwise as a command - // result. - Command command = this.CreateCommand!(); + // Create the command from the input, then execute it as a buffered + // output if we have a buffered result callback, otherwise as a command + // result. + Command command = this.CreateCommand!(); - if (this.OnBufferedResult != null) - { - BufferedCommandResult result = await command - .ExecuteBufferedAsync(cancellationToken); + if (this.OnBufferedResult != null) + { + BufferedCommandResult result = await command.ExecuteBufferedAsync(cancellationToken); - this.logger.Debug( - "Execute buffered: {Command} {Arguments} = {ExitCode}", - command.TargetFilePath, - command.Arguments, - result.ExitCode); + this.logger.Debug( + "Execute buffered: {Command} {Arguments} = {ExitCode}", + command.TargetFilePath, + command.Arguments, + result.ExitCode + ); - IEnumerable list = this.OnBufferedResult(result); + IEnumerable list = this.OnBufferedResult(result); - foreach (Entity item in list) - { - yield return item; - } - } - else - { - CommandResult result = await command - .ExecuteAsync(cancellationToken); + foreach (Entity item in list) + { + yield return item; + } + } + else + { + CommandResult result = await command.ExecuteAsync(cancellationToken); - this.logger.Debug( - "Execute: {Command} {Arguments} = {ExitCode}", - command.TargetFilePath, - command.Arguments, - result.ExitCode); + this.logger.Debug( + "Execute: {Command} {Arguments} = {ExitCode}", + command.TargetFilePath, + command.Arguments, + result.ExitCode + ); - IEnumerable? list = this.OnResult?.Invoke(result); + IEnumerable? list = this.OnResult?.Invoke(result); - if (list == null) - { - yield break; - } + if (list == null) + { + yield break; + } - foreach (Entity item in list) - { - yield return item; - } - } - } + foreach (Entity item in list) + { + yield return item; + } + } + } } diff --git a/src/MfGames.Nitride.Exec/Setup/NitrideExecBuilderExtensions.cs b/src/MfGames.Nitride.Exec/Setup/NitrideExecBuilderExtensions.cs index 61c619a..445cd4e 100644 --- a/src/MfGames.Nitride.Exec/Setup/NitrideExecBuilderExtensions.cs +++ b/src/MfGames.Nitride.Exec/Setup/NitrideExecBuilderExtensions.cs @@ -2,21 +2,19 @@ namespace MfGames.Nitride.Exec.Setup; public static class NitrideExecBuilderExtensions { - private static bool loaded; + private static bool loaded; - public static NitrideBuilder UseExec(this NitrideBuilder builder) - { - // If we've already loaded, then we have a problem. - if (loaded) - { - throw new InvalidOperationException( - "Cannot use UseExec() more than once."); - } + public static NitrideBuilder UseExec(this NitrideBuilder builder) + { + // If we've already loaded, then we have a problem. + if (loaded) + { + throw new InvalidOperationException("Cannot use UseExec() more than once."); + } - loaded = true; + loaded = true; - // Get the configuration so we can set the various options. - return builder - .UseModule(); - } + // Get the configuration so we can set the various options. + return builder.UseModule(); + } } diff --git a/src/MfGames.Nitride.Exec/Setup/NitrideExecModule.cs b/src/MfGames.Nitride.Exec/Setup/NitrideExecModule.cs index c00a3da..46211a8 100644 --- a/src/MfGames.Nitride.Exec/Setup/NitrideExecModule.cs +++ b/src/MfGames.Nitride.Exec/Setup/NitrideExecModule.cs @@ -4,11 +4,11 @@ namespace MfGames.Nitride.Exec.Setup; public class NitrideExecModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - // Add in the operators and validators. - builder.RegisterOperators(this); - builder.RegisterValidators(this); - } + /// + protected override void Load(ContainerBuilder builder) + { + // Add in the operators and validators. + builder.RegisterOperators(this); + builder.RegisterValidators(this); + } } diff --git a/src/MfGames.Nitride.Exec/Validators/ExecOperationValidator.cs b/src/MfGames.Nitride.Exec/Validators/ExecOperationValidator.cs index 6072b5b..25c3648 100644 --- a/src/MfGames.Nitride.Exec/Validators/ExecOperationValidator.cs +++ b/src/MfGames.Nitride.Exec/Validators/ExecOperationValidator.cs @@ -4,17 +4,12 @@ namespace MfGames.Nitride.Exec.Validators; public class ExecOperationValidator : AbstractValidator { - public ExecOperationValidator() - { - this.RuleFor(x => x.CreateCommand) - .NotNull(); + public ExecOperationValidator() + { + this.RuleFor(x => x.CreateCommand).NotNull(); - this.RuleFor(x => x.OnBufferedResult) - .Null() - .When(x => x.OnResult != null); + this.RuleFor(x => x.OnBufferedResult).Null().When(x => x.OnResult != null); - this.RuleFor(x => x.OnResult) - .Null() - .When(x => x.OnBufferedResult != null); - } + this.RuleFor(x => x.OnResult).Null().When(x => x.OnBufferedResult != null); + } } diff --git a/src/MfGames.Nitride.Feeds/CreateAtomFeed.cs b/src/MfGames.Nitride.Feeds/CreateAtomFeed.cs index 85180d6..2126391 100644 --- a/src/MfGames.Nitride.Feeds/CreateAtomFeed.cs +++ b/src/MfGames.Nitride.Feeds/CreateAtomFeed.cs @@ -1,14 +1,10 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Feeds.Structure; using MfGames.Nitride.Generators; - using NodaTime; - using Serilog; - using Zio; namespace MfGames.Nitride.Feeds; @@ -19,112 +15,112 @@ namespace MfGames.Nitride.Feeds; [WithProperties] public partial class CreateAtomFeed : OperationBase { - private readonly ILogger logger; + private readonly ILogger logger; - private readonly IValidator validator; + private readonly IValidator validator; - public CreateAtomFeed( - ILogger logger, - IValidator validator) - { - this.logger = logger; - this.validator = validator; - this.GetAlternateMimeType = _ => "text/html"; - } + public CreateAtomFeed(ILogger logger, IValidator validator) + { + this.logger = logger; + this.validator = validator; + this.GetAlternateMimeType = _ => "text/html"; + } - /// - /// Gets or sets the base URL for all the links. - /// - public string? BaseUrl { get; set; } + /// + /// Gets or sets the base URL for all the links. + /// + public string? BaseUrl { get; set; } - /// - /// Gets or sets the alternate MIME type. - /// - public Func GetAlternateMimeType { get; set; } + /// + /// Gets or sets the alternate MIME type. + /// + public Func GetAlternateMimeType { get; set; } - /// - /// Gets or sets the alternate URL associated with the feed. - /// - public Func? GetAlternateUrl { get; set; } + /// + /// Gets or sets the alternate URL associated with the feed. + /// + public Func? GetAlternateUrl { get; set; } - /// - /// Gets or sets the callback to get the author for the feed. - /// - public Func? GetAuthor { get; set; } + /// + /// Gets or sets the callback to get the author for the feed. + /// + public Func? GetAuthor { get; set; } - /// - /// Gets or sets the callback to get the entries associated with the - /// feed. - /// - public Func>? GetEntries { get; set; } + /// + /// Gets or sets the callback to get the entries associated with the + /// feed. + /// + public Func>? GetEntries { get; set; } - /// - /// Gets or sets the identifier (typically a URL) of the feed. - /// - public Func? GetId { get; set; } + /// + /// Gets or sets the identifier (typically a URL) of the feed. + /// + public Func? GetId { get; set; } - /// - /// Gets or sets the callback to get the path of the generated feed. - /// - public Func? GetPath { get; set; } + /// + /// Gets or sets the callback to get the path of the generated feed. + /// + public Func? GetPath { get; set; } - /// - /// Gets or sets the rights (license) of the feed. - /// - public Func? GetRights { get; set; } + /// + /// Gets or sets the rights (license) of the feed. + /// + public Func? GetRights { get; set; } - /// - /// A callback that gets the title of the feed from the given entity. - /// - public Func? GetTitle { get; set; } + /// + /// A callback that gets the title of the feed from the given entity. + /// + public Func? GetTitle { get; set; } - /// - /// Gets or sets the updated timestamp for the feed. - /// - public Func? GetUpdated { get; set; } + /// + /// Gets or sets the updated timestamp for the feed. + /// + public Func? GetUpdated { get; set; } - /// - /// Gets or sets the URL associated with the feed. - /// - public Func? GetUrl { get; set; } + /// + /// Gets or sets the URL associated with the feed. + /// + public Func? GetUrl { get; set; } - /// - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + /// + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return input.SelectMany(this.CreateEntityFeed); - } + return input.SelectMany(this.CreateEntityFeed); + } - private IEnumerable CreateEntityFeed(Entity entity) - { - // Create the top-level feed. All the nullable callbacks were - // verified in the function that calls this. - var feed = new AtomFeed - { - Title = this.GetTitle?.Invoke(entity), - Id = this.GetId?.Invoke(entity), - Rights = this.GetRights?.Invoke(entity), - Updated = this.GetUpdated?.Invoke(entity), - Url = this.GetUrl?.Invoke(entity), - AlternateUrl = this.GetAlternateUrl?.Invoke(entity), - AlternateMimeType = this.GetAlternateMimeType.Invoke(entity), - Author = this.GetAuthor?.Invoke(entity), - }.ToXElement(); + private IEnumerable CreateEntityFeed(Entity entity) + { + // Create the top-level feed. All the nullable callbacks were + // verified in the function that calls this. + var feed = new AtomFeed + { + Title = this.GetTitle?.Invoke(entity), + Id = this.GetId?.Invoke(entity), + Rights = this.GetRights?.Invoke(entity), + Updated = this.GetUpdated?.Invoke(entity), + Url = this.GetUrl?.Invoke(entity), + AlternateUrl = this.GetAlternateUrl?.Invoke(entity), + AlternateMimeType = this.GetAlternateMimeType.Invoke(entity), + Author = this.GetAuthor?.Invoke(entity), + }.ToXElement(); - // Go through all the items inside the feed and add them. - foreach (AtomEntry? entry in this.GetEntries!(entity)) - { - feed.Add(entry.ToXElement()); - } + // Go through all the items inside the feed and add them. + foreach (AtomEntry? entry in this.GetEntries!(entity)) + { + feed.Add(entry.ToXElement()); + } - // Create the feed entity and return both objects. - Entity feedEntity = new Entity().Set(IsFeed.Instance) - .Set(this.GetPath!(entity)) - .SetTextContent(feed + "\n"); + // Create the feed entity and return both objects. + Entity feedEntity = new Entity() + .Set(IsFeed.Instance) + .Set(this.GetPath!(entity)) + .SetTextContent(feed + "\n"); - return new[] { entity, feedEntity }; - } + return new[] { entity, feedEntity }; + } } diff --git a/src/MfGames.Nitride.Feeds/CreateAtomFeedValidator.cs b/src/MfGames.Nitride.Feeds/CreateAtomFeedValidator.cs index 6fc2789..f29ea75 100644 --- a/src/MfGames.Nitride.Feeds/CreateAtomFeedValidator.cs +++ b/src/MfGames.Nitride.Feeds/CreateAtomFeedValidator.cs @@ -4,15 +4,12 @@ namespace MfGames.Nitride.Feeds; public class CreateAtomFeedValidator : AbstractValidator { - public CreateAtomFeedValidator() - { - this.RuleFor(x => x.GetEntries) - .NotNull(); + public CreateAtomFeedValidator() + { + this.RuleFor(x => x.GetEntries).NotNull(); - this.RuleFor(x => x.GetPath) - .NotNull(); + this.RuleFor(x => x.GetPath).NotNull(); - this.RuleFor(x => x.GetTitle) - .NotNull(); - } + this.RuleFor(x => x.GetTitle).NotNull(); + } } diff --git a/src/MfGames.Nitride.Feeds/HasFeed.cs b/src/MfGames.Nitride.Feeds/HasFeed.cs index c1d8b1b..5ad6436 100644 --- a/src/MfGames.Nitride.Feeds/HasFeed.cs +++ b/src/MfGames.Nitride.Feeds/HasFeed.cs @@ -6,9 +6,7 @@ namespace MfGames.Nitride.Feeds; /// public class HasFeed { - public HasFeed() - { - } + public HasFeed() { } - public static HasFeed Instance { get; } = new(); + public static HasFeed Instance { get; } = new(); } diff --git a/src/MfGames.Nitride.Feeds/IsFeed.cs b/src/MfGames.Nitride.Feeds/IsFeed.cs index 95056c9..edf3a26 100644 --- a/src/MfGames.Nitride.Feeds/IsFeed.cs +++ b/src/MfGames.Nitride.Feeds/IsFeed.cs @@ -6,6 +6,4 @@ namespace MfGames.Nitride.Feeds; /// A marker component that indicates this page is a feed. /// [SingletonComponent] -public partial class IsFeed -{ -} +public partial class IsFeed { } diff --git a/src/MfGames.Nitride.Feeds/Setup/NitrideFeedsBuilderExtensions.cs b/src/MfGames.Nitride.Feeds/Setup/NitrideFeedsBuilderExtensions.cs index 2416a95..ea63dcd 100644 --- a/src/MfGames.Nitride.Feeds/Setup/NitrideFeedsBuilderExtensions.cs +++ b/src/MfGames.Nitride.Feeds/Setup/NitrideFeedsBuilderExtensions.cs @@ -4,21 +4,19 @@ namespace MfGames.Nitride.Feeds.Setup; public static class NitrideFeedsBuilderExtensions { - private static bool loaded; + private static bool loaded; - public static NitrideBuilder UseFeeds(this NitrideBuilder builder) - { - // If we've already loaded, then we have a problem. - if (loaded) - { - throw new InvalidOperationException( - "Cannot use UseFeeds() more than once."); - } + public static NitrideBuilder UseFeeds(this NitrideBuilder builder) + { + // If we've already loaded, then we have a problem. + if (loaded) + { + throw new InvalidOperationException("Cannot use UseFeeds() more than once."); + } - loaded = true; + loaded = true; - // Get the configuration so we can set the various options. - return builder - .ConfigureContainer(x => x.RegisterModule()); - } + // Get the configuration so we can set the various options. + return builder.ConfigureContainer(x => x.RegisterModule()); + } } diff --git a/src/MfGames.Nitride.Feeds/Setup/NitrideFeedsModule.cs b/src/MfGames.Nitride.Feeds/Setup/NitrideFeedsModule.cs index b038048..9eb11e7 100644 --- a/src/MfGames.Nitride.Feeds/Setup/NitrideFeedsModule.cs +++ b/src/MfGames.Nitride.Feeds/Setup/NitrideFeedsModule.cs @@ -1,16 +1,15 @@ using Autofac; - using MfGames.Nitride.Temporal.Setup; namespace MfGames.Nitride.Feeds.Setup; public class NitrideFeedsModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - builder.RegisterModule(); - builder.RegisterOperators(this); - builder.RegisterValidators(this); - } + /// + protected override void Load(ContainerBuilder builder) + { + builder.RegisterModule(); + builder.RegisterOperators(this); + builder.RegisterValidators(this); + } } diff --git a/src/MfGames.Nitride.Feeds/Structure/AtomAuthor.cs b/src/MfGames.Nitride.Feeds/Structure/AtomAuthor.cs index 3ee94c8..ba1509d 100644 --- a/src/MfGames.Nitride.Feeds/Structure/AtomAuthor.cs +++ b/src/MfGames.Nitride.Feeds/Structure/AtomAuthor.cs @@ -1,5 +1,4 @@ using System.Xml.Linq; - using MfGames.Nitride.Generators; namespace MfGames.Nitride.Feeds.Structure; @@ -10,33 +9,30 @@ namespace MfGames.Nitride.Feeds.Structure; [WithProperties] public partial class AtomAuthor { - /// - /// Gets or sets the name of the author. - /// - public string? Name { get; set; } + /// + /// Gets or sets the name of the author. + /// + public string? Name { get; set; } - /// - /// Creates an XML element out of the feed along with all items inside - /// the feed. - /// - /// - public XElement? ToXElement() - { - if (this.Name == null) - { - return null; - } + /// + /// Creates an XML element out of the feed along with all items inside + /// the feed. + /// + /// + public XElement? ToXElement() + { + if (this.Name == null) + { + return null; + } - var author = new XElement(XmlConstants.AtomNamespace + "author"); + var author = new XElement(XmlConstants.AtomNamespace + "author"); - if (!string.IsNullOrEmpty(this.Name)) - { - author.Add( - new XElement( - XmlConstants.AtomNamespace + "name", - new XText(this.Name))); - } + if (!string.IsNullOrEmpty(this.Name)) + { + author.Add(new XElement(XmlConstants.AtomNamespace + "name", new XText(this.Name))); + } - return author; - } + return author; + } } diff --git a/src/MfGames.Nitride.Feeds/Structure/AtomCategory.cs b/src/MfGames.Nitride.Feeds/Structure/AtomCategory.cs index 1f25f5b..4d0e81a 100644 --- a/src/MfGames.Nitride.Feeds/Structure/AtomCategory.cs +++ b/src/MfGames.Nitride.Feeds/Structure/AtomCategory.cs @@ -1,5 +1,4 @@ using System.Xml.Linq; - using MfGames.Nitride.Generators; namespace MfGames.Nitride.Feeds.Structure; @@ -10,47 +9,48 @@ namespace MfGames.Nitride.Feeds.Structure; [WithProperties] public partial class AtomCategory { - /// - /// Gets or sets the label associated with the category. - /// - public string? Label { get; set; } + /// + /// Gets or sets the label associated with the category. + /// + public string? Label { get; set; } - /// - /// Gets or sets the scheme associated with the category. - /// - public Uri? Scheme { get; set; } + /// + /// Gets or sets the scheme associated with the category. + /// + public Uri? Scheme { get; set; } - /// - /// Gets or sets the term of the category. - /// - public string? Term { get; set; } + /// + /// Gets or sets the term of the category. + /// + public string? Term { get; set; } - /// - /// Creates an XML element out of the feed along with all items inside - /// the feed. - /// - /// - public XElement ToXElement() - { - if (this.Term == null) - { - throw new NullReferenceException("Category term cannot be null."); - } + /// + /// Creates an XML element out of the feed along with all items inside + /// the feed. + /// + /// + public XElement ToXElement() + { + if (this.Term == null) + { + throw new NullReferenceException("Category term cannot be null."); + } - var elem = new XElement( - XmlConstants.AtomNamespace + "category", - new XAttribute("term", this.Term)); + var elem = new XElement( + XmlConstants.AtomNamespace + "category", + new XAttribute("term", this.Term) + ); - if (this.Scheme != null) - { - elem.Add(new XAttribute("scheme", this.Scheme.ToString())); - } + if (this.Scheme != null) + { + elem.Add(new XAttribute("scheme", this.Scheme.ToString())); + } - if (!string.IsNullOrEmpty(this.Label)) - { - elem.Add(new XAttribute("label", this.Label)); - } + if (!string.IsNullOrEmpty(this.Label)) + { + elem.Add(new XAttribute("label", this.Label)); + } - return elem; - } + return elem; + } } diff --git a/src/MfGames.Nitride.Feeds/Structure/AtomEntry.cs b/src/MfGames.Nitride.Feeds/Structure/AtomEntry.cs index 5e62ea7..a4f3a35 100644 --- a/src/MfGames.Nitride.Feeds/Structure/AtomEntry.cs +++ b/src/MfGames.Nitride.Feeds/Structure/AtomEntry.cs @@ -1,9 +1,6 @@ using System.Xml.Linq; - using MfGames.Nitride.Generators; - using NodaTime; - using static MfGames.Nitride.Feeds.Structure.XmlConstants; namespace MfGames.Nitride.Feeds.Structure; @@ -14,115 +11,118 @@ namespace MfGames.Nitride.Feeds.Structure; [WithProperties] public partial class AtomEntry { - /// - /// Gets or sets the author for the feed. - /// - public AtomAuthor? Author { get; set; } + /// + /// Gets or sets the author for the feed. + /// + public AtomAuthor? Author { get; set; } - /// - /// Gets or sets the categories associated with this entry. - /// - public IEnumerable? Categories { get; set; } + /// + /// Gets or sets the categories associated with this entry. + /// + public IEnumerable? Categories { get; set; } - /// - /// Gets or sets the content of the entry. - /// - public string? Content { get; set; } + /// + /// Gets or sets the content of the entry. + /// + public string? Content { get; set; } - /// - /// Gets or sets the type of content (text, html) of the content. - /// - public string ContentType { get; set; } = "html"; + /// + /// Gets or sets the type of content (text, html) of the content. + /// + public string ContentType { get; set; } = "html"; - /// - /// Gets or sets the ID of the feed. - /// - public string? Id { get; set; } + /// + /// Gets or sets the ID of the feed. + /// + public string? Id { get; set; } - /// - /// Gets or sets when the entry was first published. - /// - public Instant? Published { get; set; } + /// + /// Gets or sets when the entry was first published. + /// + public Instant? Published { get; set; } - /// - /// Gets or sets the summary of the entry. - /// - public string? Summary { get; set; } + /// + /// Gets or sets the summary of the entry. + /// + public string? Summary { get; set; } - /// - /// Gets or sets the type of content (text, html) of the summary. - /// - public string SummaryType { get; set; } = "html"; + /// + /// Gets or sets the type of content (text, html) of the summary. + /// + public string SummaryType { get; set; } = "html"; - /// - /// Gets or sets the title of the Feed. - /// - public string? Title { get; set; } + /// + /// Gets or sets the title of the Feed. + /// + public string? Title { get; set; } - /// - /// Gets or sets the timestamp that the feed was updated. - /// - public Instant? Updated { get; set; } + /// + /// Gets or sets the timestamp that the feed was updated. + /// + public Instant? Updated { get; set; } - /// - /// Gets or sets the URL associated with this feed. - /// - public Uri? Url { get; set; } + /// + /// Gets or sets the URL associated with this feed. + /// + public Uri? Url { get; set; } - /// - /// Creates an XML element out of the feed along with all items inside - /// the feed. - /// - /// - public XElement? ToXElement() - { - var elem = new XElement(AtomNamespace + "entry"); + /// + /// Creates an XML element out of the feed along with all items inside + /// the feed. + /// + /// + public XElement? ToXElement() + { + var elem = new XElement(AtomNamespace + "entry"); - AtomHelper.AddIfSet(elem, "title", this.Title); + AtomHelper.AddIfSet(elem, "title", this.Title); - if (this.Url != null) - { - elem.Add( - new XElement( - AtomNamespace + "link", - new XAttribute("rel", "alternate"), - new XAttribute("href", this.Url.ToString()))); - } + if (this.Url != null) + { + elem.Add( + new XElement( + AtomNamespace + "link", + new XAttribute("rel", "alternate"), + new XAttribute("href", this.Url.ToString()) + ) + ); + } - AtomHelper.AddIfSet( - elem, - "published", - this.Published?.ToString("g", null)); - AtomHelper.AddIfSet(elem, "updated", this.Updated?.ToString("g", null)); - AtomHelper.AddIfSet(elem, "id", this.Id); - AtomHelper.AddIfSet(elem, this.Author?.ToXElement()); + AtomHelper.AddIfSet(elem, "published", this.Published?.ToString("g", null)); + AtomHelper.AddIfSet(elem, "updated", this.Updated?.ToString("g", null)); + AtomHelper.AddIfSet(elem, "id", this.Id); + AtomHelper.AddIfSet(elem, this.Author?.ToXElement()); - if (this.Categories != null) - { - foreach (AtomCategory? category in this.Categories) - { - elem.Add(category.ToXElement()); - } - } + if (this.Categories != null) + { + foreach (AtomCategory? category in this.Categories) + { + elem.Add(category.ToXElement()); + } + } - if (!string.IsNullOrWhiteSpace(this.Summary)) - { - elem.Add( - new XElement( - AtomNamespace + "summary", - new XAttribute("type", this.SummaryType), - new XText(this.Summary))); - } + if (!string.IsNullOrWhiteSpace(this.Summary)) + { + elem.Add( + new XElement( + AtomNamespace + "summary", + new XAttribute("type", this.SummaryType), + new XText(this.Summary) + ) + ); + } - if (!string.IsNullOrWhiteSpace(this.Content)) - { - elem.Add( - new XElement( - AtomNamespace + "content", - new XAttribute("type", this.ContentType), - new XText(this.Content))); - } + if (!string.IsNullOrWhiteSpace(this.Content)) + { + elem.Add( + new XElement( + AtomNamespace + "content", + new XAttribute("type", this.ContentType), + new XText(this.Content) + ) + ); + } - return elem; - } + return elem; + } } diff --git a/src/MfGames.Nitride.Feeds/Structure/AtomFeed.cs b/src/MfGames.Nitride.Feeds/Structure/AtomFeed.cs index e6a3cbb..fe5253d 100644 --- a/src/MfGames.Nitride.Feeds/Structure/AtomFeed.cs +++ b/src/MfGames.Nitride.Feeds/Structure/AtomFeed.cs @@ -1,7 +1,5 @@ using System.Xml.Linq; - using NodaTime; - using static MfGames.Nitride.Feeds.Structure.XmlConstants; namespace MfGames.Nitride.Feeds.Structure; @@ -11,90 +9,96 @@ namespace MfGames.Nitride.Feeds.Structure; /// public record AtomFeed { - /// - /// Gets or sets the MIME type for the alternate URL. - /// - public string AlternateMimeType { get; set; } = "text/html"; + /// + /// Gets or sets the MIME type for the alternate URL. + /// + public string AlternateMimeType { get; set; } = "text/html"; - /// - /// Gets or sets the alternate URL for this feed. - /// - public Uri? AlternateUrl { get; set; } + /// + /// Gets or sets the alternate URL for this feed. + /// + public Uri? AlternateUrl { get; set; } - /// - /// Gets or sets the author for the feed. - /// - public AtomAuthor? Author { get; set; } + /// + /// Gets or sets the author for the feed. + /// + public AtomAuthor? Author { get; set; } - /// - /// Gets or sets the ID of the feed. - /// - public string? Id { get; set; } + /// + /// Gets or sets the ID of the feed. + /// + public string? Id { get; set; } - /// - /// Gets or sets the rights (license) of the feed. - /// - public string? Rights { get; set; } + /// + /// Gets or sets the rights (license) of the feed. + /// + public string? Rights { get; set; } - /// - /// Gets or sets the title of the Feed. - /// - public string? Title { get; set; } + /// + /// Gets or sets the title of the Feed. + /// + public string? Title { get; set; } - /// - /// Gets or sets the timestamp that the feed was updated. - /// - public Instant? Updated { get; set; } + /// + /// Gets or sets the timestamp that the feed was updated. + /// + public Instant? Updated { get; set; } - /// - /// Gets or sets the URL associated with this feed. - /// - public Uri? Url { get; set; } + /// + /// Gets or sets the URL associated with this feed. + /// + public Uri? Url { get; set; } - /// - /// Creates an XML element out of the feed along with all items inside - /// the feed. - /// - /// - public XElement ToXElement() - { - var elem = new XElement(AtomNamespace + "feed"); + /// + /// Creates an XML element out of the feed along with all items inside + /// the feed. + /// + /// + public XElement ToXElement() + { + var elem = new XElement(AtomNamespace + "feed"); - if (!string.IsNullOrWhiteSpace(this.Title)) - { - elem.Add( - new XElement( - AtomNamespace + "title", - new XAttribute("type", "text"), - new XAttribute(XNamespace.Xml + "lang", "en"), - new XText(this.Title))); - } + if (!string.IsNullOrWhiteSpace(this.Title)) + { + elem.Add( + new XElement( + AtomNamespace + "title", + new XAttribute("type", "text"), + new XAttribute(XNamespace.Xml + "lang", "en"), + new XText(this.Title) + ) + ); + } - if (this.Url != null) - { - elem.Add( - new XElement( - AtomNamespace + "link", - new XAttribute("type", "application/atom+xml"), - new XAttribute("href", this.Url.ToString()), - new XAttribute("rel", "self"))); - } + if (this.Url != null) + { + elem.Add( + new XElement( + AtomNamespace + "link", + new XAttribute("type", "application/atom+xml"), + new XAttribute("href", this.Url.ToString()), + new XAttribute("rel", "self") + ) + ); + } - if (this.AlternateUrl != null) - { - elem.Add( - new XElement( - AtomNamespace + "link", - new XAttribute("type", this.AlternateMimeType), - new XAttribute("href", this.AlternateUrl.ToString()), - new XAttribute("rel", "alternate"))); - } + if (this.AlternateUrl != null) + { + elem.Add( + new XElement( + AtomNamespace + "link", + new XAttribute("type", this.AlternateMimeType), + new XAttribute("href", this.AlternateUrl.ToString()), + new XAttribute("rel", "alternate") + ) + ); + } - AtomHelper.AddIfSet(elem, "updated", this.Updated?.ToString("g", null)); - AtomHelper.AddIfSet(elem, "id", this.Id); - AtomHelper.AddIfSet(elem, this.Author?.ToXElement()); - AtomHelper.AddIfSet(elem, "rights", this.Rights); + AtomHelper.AddIfSet(elem, "updated", this.Updated?.ToString("g", null)); + AtomHelper.AddIfSet(elem, "id", this.Id); + AtomHelper.AddIfSet(elem, this.Author?.ToXElement()); + AtomHelper.AddIfSet(elem, "rights", this.Rights); - return elem; - } + return elem; + } } diff --git a/src/MfGames.Nitride.Feeds/Structure/AtomHelper.cs b/src/MfGames.Nitride.Feeds/Structure/AtomHelper.cs index 5123cd1..fc5f2e6 100644 --- a/src/MfGames.Nitride.Feeds/Structure/AtomHelper.cs +++ b/src/MfGames.Nitride.Feeds/Structure/AtomHelper.cs @@ -7,27 +7,19 @@ namespace MfGames.Nitride.Feeds.Structure; /// public static class AtomHelper { - public static void AddIfSet( - XElement root, - XElement? elem) - { - if (elem != null) - { - root.Add(elem); - } - } + public static void AddIfSet(XElement root, XElement? elem) + { + if (elem != null) + { + root.Add(elem); + } + } - public static void AddIfSet( - XElement elem, - string name, - string? text) - { - if (!string.IsNullOrWhiteSpace(text)) - { - elem.Add( - new XElement( - XmlConstants.AtomNamespace + name, - new XText(text))); - } - } + public static void AddIfSet(XElement elem, string name, string? text) + { + if (!string.IsNullOrWhiteSpace(text)) + { + elem.Add(new XElement(XmlConstants.AtomNamespace + name, new XText(text))); + } + } } diff --git a/src/MfGames.Nitride.Feeds/Structure/XmlConstants.cs b/src/MfGames.Nitride.Feeds/Structure/XmlConstants.cs index ff6e520..2e966ad 100644 --- a/src/MfGames.Nitride.Feeds/Structure/XmlConstants.cs +++ b/src/MfGames.Nitride.Feeds/Structure/XmlConstants.cs @@ -7,15 +7,13 @@ namespace MfGames.Nitride.Feeds.Structure; /// public static class XmlConstants { - /// - /// The XML namespace for Atom feeds. - /// - public static readonly XNamespace AtomNamespace = - "http://www.w3.org/2005/Atom"; + /// + /// The XML namespace for Atom feeds. + /// + public static readonly XNamespace AtomNamespace = "http://www.w3.org/2005/Atom"; - /// - /// The XML namespace for media. - /// - public static readonly XNamespace MediaNamespace = - "http://search.yahoo.com/mrss/"; + /// + /// The XML namespace for media. + /// + public static readonly XNamespace MediaNamespace = "http://search.yahoo.com/mrss/"; } diff --git a/src/MfGames.Nitride.Gemtext/IsGemtext.cs b/src/MfGames.Nitride.Gemtext/IsGemtext.cs index 972a291..3b1eb0a 100644 --- a/src/MfGames.Nitride.Gemtext/IsGemtext.cs +++ b/src/MfGames.Nitride.Gemtext/IsGemtext.cs @@ -7,6 +7,4 @@ namespace MfGames.Nitride.Gemtext; /// for text files using the Gemini protocol. /// [SingletonComponent] -public partial class IsGemtext -{ -} +public partial class IsGemtext { } diff --git a/src/MfGames.Nitride.Gemtext/NitrideGemtextBuilderExtensions.cs b/src/MfGames.Nitride.Gemtext/NitrideGemtextBuilderExtensions.cs index 74e3b3f..202dcb7 100644 --- a/src/MfGames.Nitride.Gemtext/NitrideGemtextBuilderExtensions.cs +++ b/src/MfGames.Nitride.Gemtext/NitrideGemtextBuilderExtensions.cs @@ -4,21 +4,19 @@ namespace MfGames.Nitride.Gemtext; public static class NitrideGemtextBuilderExtensions { - private static bool loaded; + private static bool loaded; - public static NitrideBuilder UseGemtext(this NitrideBuilder builder) - { - // If we've already loaded, then we have a problem. - if (loaded) - { - throw new InvalidOperationException( - "Cannot use UseGemtext() more than once."); - } + public static NitrideBuilder UseGemtext(this NitrideBuilder builder) + { + // If we've already loaded, then we have a problem. + if (loaded) + { + throw new InvalidOperationException("Cannot use UseGemtext() more than once."); + } - loaded = true; + loaded = true; - // Get the configuration so we can set the various options. - return builder.ConfigureContainer( - x => x.RegisterModule()); - } + // Get the configuration so we can set the various options. + return builder.ConfigureContainer(x => x.RegisterModule()); + } } diff --git a/src/MfGames.Nitride.Gemtext/NitrideGemtextModule.cs b/src/MfGames.Nitride.Gemtext/NitrideGemtextModule.cs index a26f25c..555c91f 100644 --- a/src/MfGames.Nitride.Gemtext/NitrideGemtextModule.cs +++ b/src/MfGames.Nitride.Gemtext/NitrideGemtextModule.cs @@ -4,8 +4,6 @@ namespace MfGames.Nitride.Gemtext; public class NitrideGemtextModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - } + /// + protected override void Load(ContainerBuilder builder) { } } diff --git a/src/MfGames.Nitride.Generators/ClassAttributeReference.cs b/src/MfGames.Nitride.Generators/ClassAttributeReference.cs index 7328ac7..2ca1fe0 100644 --- a/src/MfGames.Nitride.Generators/ClassAttributeReference.cs +++ b/src/MfGames.Nitride.Generators/ClassAttributeReference.cs @@ -8,18 +8,18 @@ namespace MfGames.Nitride.Generators; /// public class ClassAttributeReference { - /// - /// Gets the syntax for the class declaration. - /// - public ClassDeclarationSyntax ClassDeclaration { get; set; } = null!; + /// + /// Gets the syntax for the class declaration. + /// + public ClassDeclarationSyntax ClassDeclaration { get; set; } = null!; - /// - /// Gets or sets the namespace associated with the class. - /// - public string Namespace { get; set; } = null!; + /// + /// Gets or sets the namespace associated with the class. + /// + public string Namespace { get; set; } = null!; - /// - /// Gets the using statements that are in the class. - /// - public List UsingDirectiveList { get; set; } = new(); + /// + /// Gets the using statements that are in the class. + /// + public List UsingDirectiveList { get; set; } = new(); } diff --git a/src/MfGames.Nitride.Generators/ClassAttributeSourceGeneratorBase.cs b/src/MfGames.Nitride.Generators/ClassAttributeSourceGeneratorBase.cs index c1b80f9..830cbcd 100644 --- a/src/MfGames.Nitride.Generators/ClassAttributeSourceGeneratorBase.cs +++ b/src/MfGames.Nitride.Generators/ClassAttributeSourceGeneratorBase.cs @@ -6,61 +6,58 @@ namespace MfGames.Nitride.Generators; /// /// Base class for classes marked with an attribute. /// -public abstract class ClassAttributeSourceGeneratorBase - : ISourceGenerator - where TSyntaxReceiver : ClassAttributeSyntaxReceiverBase +public abstract class ClassAttributeSourceGeneratorBase : ISourceGenerator + where TSyntaxReceiver : ClassAttributeSyntaxReceiverBase { - public void Execute(GeneratorExecutionContext context) - { - // Get the generator infrastructure will create a receiver and - // populate it we can retrieve the populated instance via the - // context. - if (context.SyntaxReceiver is not TSyntaxReceiver syntaxReceiver) - { - return; - } + public void Execute(GeneratorExecutionContext context) + { + // Get the generator infrastructure will create a receiver and + // populate it we can retrieve the populated instance via the + // context. + if (context.SyntaxReceiver is not TSyntaxReceiver syntaxReceiver) + { + return; + } - // Report any messages. - foreach (string? message in syntaxReceiver.Messages) - { - context.Warning( - MessageCode.Debug, - Location.Create( - "Temporary.g.cs", - TextSpan.FromBounds(0, 0), - new LinePositionSpan( - new LinePosition(0, 0), - new LinePosition(0, 0))), - "{0}: Syntax Message: {1}", - this.GetType().Name, - message); - } + // Report any messages. + foreach (string? message in syntaxReceiver.Messages) + { + context.Warning( + MessageCode.Debug, + Location.Create( + "Temporary.g.cs", + TextSpan.FromBounds(0, 0), + new LinePositionSpan(new LinePosition(0, 0), new LinePosition(0, 0)) + ), + "{0}: Syntax Message: {1}", + this.GetType().Name, + message + ); + } - // If we didn't find anything, then there is nothing to do. - if (syntaxReceiver.ReferenceList.Count == 0) - { - return; - } + // If we didn't find anything, then there is nothing to do. + if (syntaxReceiver.ReferenceList.Count == 0) + { + return; + } - // Go through each one. - foreach (ClassAttributeReference reference in syntaxReceiver - .ReferenceList) - { - this.GenerateClassFile(context, reference); - } - } + // Go through each one. + foreach (ClassAttributeReference reference in syntaxReceiver.ReferenceList) + { + this.GenerateClassFile(context, reference); + } + } - public void Initialize(GeneratorInitializationContext context) - { - // Register a factory that can create our custom syntax receiver - context.RegisterForSyntaxNotifications( - () => this.CreateSyntaxReceiver(context)); - } + public void Initialize(GeneratorInitializationContext context) + { + // Register a factory that can create our custom syntax receiver + context.RegisterForSyntaxNotifications(() => this.CreateSyntaxReceiver(context)); + } - protected abstract TSyntaxReceiver CreateSyntaxReceiver( - GeneratorInitializationContext context); + protected abstract TSyntaxReceiver CreateSyntaxReceiver(GeneratorInitializationContext context); - protected abstract void GenerateClassFile( - GeneratorExecutionContext context, - ClassAttributeReference reference); + protected abstract void GenerateClassFile( + GeneratorExecutionContext context, + ClassAttributeReference reference + ); } diff --git a/src/MfGames.Nitride.Generators/ClassAttributeSyntaxReceiverBase.cs b/src/MfGames.Nitride.Generators/ClassAttributeSyntaxReceiverBase.cs index 8b05156..2e9a7e2 100644 --- a/src/MfGames.Nitride.Generators/ClassAttributeSyntaxReceiverBase.cs +++ b/src/MfGames.Nitride.Generators/ClassAttributeSyntaxReceiverBase.cs @@ -5,101 +5,103 @@ namespace MfGames.Nitride.Generators; public abstract class ClassAttributeSyntaxReceiverBase : ISyntaxReceiver { - private readonly string attributeName; + private readonly string attributeName; - private readonly GeneratorInitializationContext context; + private readonly GeneratorInitializationContext context; - public ClassAttributeSyntaxReceiverBase( - GeneratorInitializationContext context, - string attributeName) - { - this.context = context; - this.attributeName = attributeName; - this.ReferenceList = new List(); - this.Messages = new List(); - } + public ClassAttributeSyntaxReceiverBase( + GeneratorInitializationContext context, + string attributeName + ) + { + this.context = context; + this.attributeName = attributeName; + this.ReferenceList = new List(); + this.Messages = new List(); + } - /// - /// Gets or sets a value indicating whether we should debug parsing attributes. - /// - public bool DebugAttributes { get; set; } + /// + /// Gets or sets a value indicating whether we should debug parsing attributes. + /// + public bool DebugAttributes { get; set; } - public List Messages { get; } + public List Messages { get; } - /// - /// Gets or sets the name of the analyzed namespace. - /// - public string? Namespace { get; private set; } + /// + /// Gets or sets the name of the analyzed namespace. + /// + public string? Namespace { get; private set; } - public List ReferenceList { get; } + public List ReferenceList { get; } - public List UsingDirectiveList { get; set; } = new(); + public List UsingDirectiveList { get; set; } = new(); - public void OnVisitSyntaxNode(SyntaxNode syntaxNode) - { - // Check for namespaces. - switch (syntaxNode) - { - case CompilationUnitSyntax: - // Reset everything. - this.Namespace = null!; - this.UsingDirectiveList = new List(); + public void OnVisitSyntaxNode(SyntaxNode syntaxNode) + { + // Check for namespaces. + switch (syntaxNode) + { + case CompilationUnitSyntax: + // Reset everything. + this.Namespace = null!; + this.UsingDirectiveList = new List(); - break; - case NamespaceDeclarationSyntax syntax: - this.Namespace = syntax.Name.ToString(); + break; + case NamespaceDeclarationSyntax syntax: + this.Namespace = syntax.Name.ToString(); - return; - case FileScopedNamespaceDeclarationSyntax syntax: - this.Namespace = syntax.Name.ToString(); + return; + case FileScopedNamespaceDeclarationSyntax syntax: + this.Namespace = syntax.Name.ToString(); - return; - case UsingDirectiveSyntax syntax: - this.UsingDirectiveList.Add(syntax); + return; + case UsingDirectiveSyntax syntax: + this.UsingDirectiveList.Add(syntax); - return; - case ClassDeclarationSyntax: - break; - default: - return; - } + return; + case ClassDeclarationSyntax: + break; + default: + return; + } - // We only care about class declarations. - if (syntaxNode is not ClassDeclarationSyntax cds) - { - return; - } + // We only care about class declarations. + if (syntaxNode is not ClassDeclarationSyntax cds) + { + return; + } - // See if the class has our set properties attribute. - var attributes = cds.AttributeLists - .AsEnumerable() - .SelectMany(x => x.Attributes) - .Select(x => x.Name.ToString()) - .ToList(); - bool found = attributes - .Any( - x => x == this.attributeName - || x == $"{this.attributeName}Attribute"); + // See if the class has our set properties attribute. + var attributes = cds.AttributeLists.AsEnumerable() + .SelectMany(x => x.Attributes) + .Select(x => x.Name.ToString()) + .ToList(); + bool found = attributes.Any(x => + x == this.attributeName || x == $"{this.attributeName}Attribute" + ); - if (this.DebugAttributes) - { - this.Messages.Add( - string.Format( - "Parsing {0} found? {1} from attributes [{2}]", - cds.Identifier, - found, - string.Join(", ", attributes))); - } + if (this.DebugAttributes) + { + this.Messages.Add( + string.Format( + "Parsing {0} found? {1} from attributes [{2}]", + cds.Identifier, + found, + string.Join(", ", attributes) + ) + ); + } - if (found) - { - this.ReferenceList.Add( - new ClassAttributeReference - { - Namespace = this.Namespace!, - UsingDirectiveList = this.UsingDirectiveList, - ClassDeclaration = cds, - }); - } - } + if (found) + { + this.ReferenceList.Add( + new ClassAttributeReference + { + Namespace = this.Namespace!, + UsingDirectiveList = this.UsingDirectiveList, + ClassDeclaration = cds, + } + ); + } + } } diff --git a/src/MfGames.Nitride.Generators/CodeAnalysisExtensions.cs b/src/MfGames.Nitride.Generators/CodeAnalysisExtensions.cs index a9bc58e..956734c 100644 --- a/src/MfGames.Nitride.Generators/CodeAnalysisExtensions.cs +++ b/src/MfGames.Nitride.Generators/CodeAnalysisExtensions.cs @@ -7,152 +7,143 @@ namespace MfGames.Nitride.Generators; /// public static class CodeAnalysisExtensions { - /// - /// Creates an error message to break the build while generating code. - /// - /// The context that contains the diagnostic. - /// The normalized message code. - /// The string format for the message. - /// The optional parameters. - public static void Error( - this GeneratorExecutionContext context, - MessageCode messageCode, - string format, - params object?[] parameters) - { - Error(context, messageCode, null, format, parameters); - } + /// + /// Creates an error message to break the build while generating code. + /// + /// The context that contains the diagnostic. + /// The normalized message code. + /// The string format for the message. + /// The optional parameters. + public static void Error( + this GeneratorExecutionContext context, + MessageCode messageCode, + string format, + params object?[] parameters + ) + { + Error(context, messageCode, null, format, parameters); + } - /// - /// Creates an error message to break the build while generating code. - /// - /// The context that contains the diagnostic. - /// The normalized message code. - /// The optional location for the message. - /// The string format for the message. - /// The optional parameters. - public static void Error( - this GeneratorExecutionContext context, - MessageCode messageCode, - Location? location, - string format, - params object?[] parameters) - { - context.Message( - messageCode, - location, - DiagnosticSeverity.Error, - format, - parameters); - } + /// + /// Creates an error message to break the build while generating code. + /// + /// The context that contains the diagnostic. + /// The normalized message code. + /// The optional location for the message. + /// The string format for the message. + /// The optional parameters. + public static void Error( + this GeneratorExecutionContext context, + MessageCode messageCode, + Location? location, + string format, + params object?[] parameters + ) + { + context.Message(messageCode, location, DiagnosticSeverity.Error, format, parameters); + } - /// - /// Creates an informational message to break the build while generating code. - /// - /// The context that contains the diagnostic. - /// The normalized message code. - /// The string format for the message. - /// The optional parameters. - public static void Information( - this GeneratorExecutionContext context, - MessageCode messageCode, - string format, - params object?[] parameters) - { - Information(context, messageCode, null, format, parameters); - } + /// + /// Creates an informational message to break the build while generating code. + /// + /// The context that contains the diagnostic. + /// The normalized message code. + /// The string format for the message. + /// The optional parameters. + public static void Information( + this GeneratorExecutionContext context, + MessageCode messageCode, + string format, + params object?[] parameters + ) + { + Information(context, messageCode, null, format, parameters); + } - /// - /// Creates an informational message to break the build while generating code. - /// - /// The context that contains the diagnostic. - /// The normalized message code. - /// The optional location for the message. - /// The string format for the message. - /// The optional parameters. - public static void Information( - this GeneratorExecutionContext context, - MessageCode messageCode, - Location? location, - string format, - params object?[] parameters) - { - context.Message( - messageCode, - location, - DiagnosticSeverity.Info, - format, - parameters); - } + /// + /// Creates an informational message to break the build while generating code. + /// + /// The context that contains the diagnostic. + /// The normalized message code. + /// The optional location for the message. + /// The string format for the message. + /// The optional parameters. + public static void Information( + this GeneratorExecutionContext context, + MessageCode messageCode, + Location? location, + string format, + params object?[] parameters + ) + { + context.Message(messageCode, location, DiagnosticSeverity.Info, format, parameters); + } - /// - /// Creates a warning message to break the build while generating code. - /// - /// The context that contains the diagnostic. - /// The normalized message code. - /// The string format for the message. - /// The optional parameters. - public static void Warning( - this GeneratorExecutionContext context, - MessageCode messageCode, - string format, - params object?[] parameters) - { - Warning(context, messageCode, null, format, parameters); - } + /// + /// Creates a warning message to break the build while generating code. + /// + /// The context that contains the diagnostic. + /// The normalized message code. + /// The string format for the message. + /// The optional parameters. + public static void Warning( + this GeneratorExecutionContext context, + MessageCode messageCode, + string format, + params object?[] parameters + ) + { + Warning(context, messageCode, null, format, parameters); + } - /// - /// Creates a warning message to break the build while generating code. - /// - /// The context that contains the diagnostic. - /// The normalized message code. - /// The optional location for the message. - /// The string format for the message. - /// The optional parameters. - public static void Warning( - this GeneratorExecutionContext context, - MessageCode messageCode, - Location? location, - string format, - params object?[] parameters) - { - context.Message( - messageCode, - location, - DiagnosticSeverity.Warning, - format, - parameters); - } + /// + /// Creates a warning message to break the build while generating code. + /// + /// The context that contains the diagnostic. + /// The normalized message code. + /// The optional location for the message. + /// The string format for the message. + /// The optional parameters. + public static void Warning( + this GeneratorExecutionContext context, + MessageCode messageCode, + Location? location, + string format, + params object?[] parameters + ) + { + context.Message(messageCode, location, DiagnosticSeverity.Warning, format, parameters); + } - /// - /// Creates a message to break the build while generating code. - /// - /// The context that contains the diagnostic. - /// The normalized message code. - /// The optional location for the message. - /// The string format for the message. - /// The optional parameters. - /// The severity of the message. - private static void Message( - this GeneratorExecutionContext context, - MessageCode messageCode, - Location? location, - DiagnosticSeverity severity, - string format, - params object?[] parameters) - { - context.ReportDiagnostic( - Diagnostic.Create( - "GN" + ((int)messageCode).ToString("D4"), - "Nitride", - string.Format(format, parameters), - severity, - severity, - true, - severity is DiagnosticSeverity.Warning - or DiagnosticSeverity.Info - ? 4 - : 0, - location: location)); - } + /// + /// Creates a message to break the build while generating code. + /// + /// The context that contains the diagnostic. + /// The normalized message code. + /// The optional location for the message. + /// The string format for the message. + /// The optional parameters. + /// The severity of the message. + private static void Message( + this GeneratorExecutionContext context, + MessageCode messageCode, + Location? location, + DiagnosticSeverity severity, + string format, + params object?[] parameters + ) + { + context.ReportDiagnostic( + Diagnostic.Create( + "GN" + ((int)messageCode).ToString("D4"), + "Nitride", + string.Format(format, parameters), + severity, + severity, + true, + severity is DiagnosticSeverity.Warning or DiagnosticSeverity.Info ? 4 : 0, + location: location + ) + ); + } } diff --git a/src/MfGames.Nitride.Generators/MessageCode.cs b/src/MfGames.Nitride.Generators/MessageCode.cs index f67a592..4554d88 100644 --- a/src/MfGames.Nitride.Generators/MessageCode.cs +++ b/src/MfGames.Nitride.Generators/MessageCode.cs @@ -5,5 +5,5 @@ namespace MfGames.Nitride.Generators; /// public enum MessageCode { - Debug = 1, + Debug = 1, } diff --git a/src/MfGames.Nitride.Generators/SingletonComponentSourceGenerator.cs b/src/MfGames.Nitride.Generators/SingletonComponentSourceGenerator.cs index 65ae946..f6595b6 100644 --- a/src/MfGames.Nitride.Generators/SingletonComponentSourceGenerator.cs +++ b/src/MfGames.Nitride.Generators/SingletonComponentSourceGenerator.cs @@ -1,5 +1,4 @@ using System.Text; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Text; @@ -13,79 +12,83 @@ namespace MfGames.Nitride.Generators; /// [Generator] public class SingletonComponentSourceGenerator - : ClassAttributeSourceGeneratorBase + : ClassAttributeSourceGeneratorBase { - protected override SingletonComponentSyntaxReceiver CreateSyntaxReceiver( - GeneratorInitializationContext context) - { - return new SingletonComponentSyntaxReceiver(context); - } + protected override SingletonComponentSyntaxReceiver CreateSyntaxReceiver( + GeneratorInitializationContext context + ) + { + return new SingletonComponentSyntaxReceiver(context); + } - protected override void GenerateClassFile( - GeneratorExecutionContext context, - ClassAttributeReference unit) - { - // Pull out some fields. - ClassDeclarationSyntax cds = unit.ClassDeclaration; + protected override void GenerateClassFile( + GeneratorExecutionContext context, + ClassAttributeReference unit + ) + { + // Pull out some fields. + ClassDeclarationSyntax cds = unit.ClassDeclaration; - // Create the partial class. - StringBuilder buffer = new(); - buffer.AppendLine("#nullable enable"); + // Create the partial class. + StringBuilder buffer = new(); + buffer.AppendLine("#nullable enable"); - // Copy the using statements from the file. - foreach (UsingDirectiveSyntax? uds in unit.UsingDirectiveList) - { - buffer.AppendLine(uds.ToString()); - } + // Copy the using statements from the file. + foreach (UsingDirectiveSyntax? uds in unit.UsingDirectiveList) + { + buffer.AppendLine(uds.ToString()); + } - buffer.AppendLine(); + buffer.AppendLine(); - // Create the namespace. - SyntaxToken cls = cds.Identifier; + // Create the namespace. + SyntaxToken cls = cds.Identifier; - buffer.AppendLine( - string.Join( - "\n", - $"using MfGames.Gallium;", - $"", - $"namespace {unit.Namespace}", - $"{{", - $" public partial class {cls}", - $" {{", - $" static {cls}()", - $" {{", - $" Instance = new {cls}();", - $" }}", - $"", - $" private {cls}()", - $" {{", - $" }}", - $"", - $" public static {cls} Instance {{ get; }}", - $" }}", - $"", - $" public static class {cls}Extensions", - $" {{", - $" public static bool Has{cls}(this Entity entity)", - $" {{", - $" return entity.Has<{cls}>();", - $" }}", - $"", - $" public static Entity Remove{cls}(this Entity entity)", - $" {{", - $" return entity.Remove<{cls}>();", - $" }}", - $"", - $" public static Entity Set{cls}(this Entity entity)", - $" {{", - $" return entity.Set({cls}.Instance);", - $" }}", - $" }}", - $"}}", - "")); + buffer.AppendLine( + string.Join( + "\n", + $"using MfGames.Gallium;", + $"", + $"namespace {unit.Namespace}", + $"{{", + $" public partial class {cls}", + $" {{", + $" static {cls}()", + $" {{", + $" Instance = new {cls}();", + $" }}", + $"", + $" private {cls}()", + $" {{", + $" }}", + $"", + $" public static {cls} Instance {{ get; }}", + $" }}", + $"", + $" public static class {cls}Extensions", + $" {{", + $" public static bool Has{cls}(this Entity entity)", + $" {{", + $" return entity.Has<{cls}>();", + $" }}", + $"", + $" public static Entity Remove{cls}(this Entity entity)", + $" {{", + $" return entity.Remove<{cls}>();", + $" }}", + $"", + $" public static Entity Set{cls}(this Entity entity)", + $" {{", + $" return entity.Set({cls}.Instance);", + $" }}", + $" }}", + $"}}", + "" + ) + ); - // Create the source text and write out the file. - var sourceText = SourceText.From(buffer.ToString(), Encoding.UTF8); - context.AddSource(cls + ".Generated.cs", sourceText); - } + // Create the source text and write out the file. + var sourceText = SourceText.From(buffer.ToString(), Encoding.UTF8); + context.AddSource(cls + ".Generated.cs", sourceText); + } } diff --git a/src/MfGames.Nitride.Generators/SingletonComponentSyntaxReceiver.cs b/src/MfGames.Nitride.Generators/SingletonComponentSyntaxReceiver.cs index f1fe953..6e94e44 100644 --- a/src/MfGames.Nitride.Generators/SingletonComponentSyntaxReceiver.cs +++ b/src/MfGames.Nitride.Generators/SingletonComponentSyntaxReceiver.cs @@ -4,10 +4,7 @@ namespace MfGames.Nitride.Generators; public class SingletonComponentSyntaxReceiver : ClassAttributeSyntaxReceiverBase { - /// - public SingletonComponentSyntaxReceiver( - GeneratorInitializationContext context) - : base(context, "SingletonComponent") - { - } + /// + public SingletonComponentSyntaxReceiver(GeneratorInitializationContext context) + : base(context, "SingletonComponent") { } } diff --git a/src/MfGames.Nitride.Generators/WithPropertiesSourceGenerator.cs b/src/MfGames.Nitride.Generators/WithPropertiesSourceGenerator.cs index 6992f91..d57ce2a 100644 --- a/src/MfGames.Nitride.Generators/WithPropertiesSourceGenerator.cs +++ b/src/MfGames.Nitride.Generators/WithPropertiesSourceGenerator.cs @@ -1,5 +1,4 @@ using System.Text; - using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -14,100 +13,105 @@ namespace MfGames.Nitride.Generators; /// [Generator] public class WithPropertiesSourceGenerator - : ClassAttributeSourceGeneratorBase + : ClassAttributeSourceGeneratorBase { - /// - protected override WithPropertiesSyntaxReceiver CreateSyntaxReceiver( - GeneratorInitializationContext context) - { - return new WithPropertiesSyntaxReceiver(context); - } + /// + protected override WithPropertiesSyntaxReceiver CreateSyntaxReceiver( + GeneratorInitializationContext context + ) + { + return new WithPropertiesSyntaxReceiver(context); + } - protected override void GenerateClassFile( - GeneratorExecutionContext context, - ClassAttributeReference unit) - { - // Pull out some fields. - ClassDeclarationSyntax cds = unit.ClassDeclaration; + protected override void GenerateClassFile( + GeneratorExecutionContext context, + ClassAttributeReference unit + ) + { + // Pull out some fields. + ClassDeclarationSyntax cds = unit.ClassDeclaration; - // Create the partial class. - StringBuilder buffer = new(); - buffer.AppendLine("#nullable enable"); + // Create the partial class. + StringBuilder buffer = new(); + buffer.AppendLine("#nullable enable"); - // Copy the using statements from the file. - foreach (UsingDirectiveSyntax? uds in unit.UsingDirectiveList) - { - buffer.AppendLine(uds.ToString()); - } + // Copy the using statements from the file. + foreach (UsingDirectiveSyntax? uds in unit.UsingDirectiveList) + { + buffer.AppendLine(uds.ToString()); + } - buffer.AppendLine(); + buffer.AppendLine(); - // Create the namespace. - buffer.AppendLine($"namespace {unit.Namespace}"); - buffer.AppendLine("{"); - buffer.AppendLine($" public partial class {cds.Identifier}"); - buffer.AppendLine(" {"); + // Create the namespace. + buffer.AppendLine($"namespace {unit.Namespace}"); + buffer.AppendLine("{"); + buffer.AppendLine($" public partial class {cds.Identifier}"); + buffer.AppendLine(" {"); - // Go through the properties of the namespace. - IEnumerable properties = cds.Members - .Where(m => m.Kind() == SyntaxKind.PropertyDeclaration) - .Cast(); + // Go through the properties of the namespace. + IEnumerable properties = cds.Members.Where(m => + m.Kind() == SyntaxKind.PropertyDeclaration + ) + .Cast(); - bool first = true; + bool first = true; - foreach (PropertyDeclarationSyntax pds in properties) - { - // See if we have a setter. - bool found = pds.AccessorList?.Accessors - .Any(x => x.Keyword.ToString() == "set") - ?? false; + foreach (PropertyDeclarationSyntax pds in properties) + { + // See if we have a setter. + bool found = + pds.AccessorList?.Accessors.Any(x => x.Keyword.ToString() == "set") ?? false; - if (!found) - { - continue; - } + if (!found) + { + continue; + } - // If we aren't first, then add a newline before it. - if (first) - { - first = false; - } - else - { - buffer.AppendLine(); - } + // If we aren't first, then add a newline before it. + if (first) + { + first = false; + } + else + { + buffer.AppendLine(); + } - // Write some documentation. - buffer.AppendLine(" /// "); + // Write some documentation. + buffer.AppendLine(" /// "); - buffer.AppendLine( - string.Format( - " /// Sets the {0} value and returns the operation for chaining.", - pds.Identifier.ToString())); + buffer.AppendLine( + string.Format( + " /// Sets the {0} value and returns the operation for chaining.", + pds.Identifier.ToString() + ) + ); - buffer.AppendLine(" /// "); + buffer.AppendLine(" /// "); - // We have the components for writing out a setter. - buffer.AppendLine( - string.Format( - " public virtual {0} With{1}({2} value)", - cds.Identifier, - pds.Identifier, - pds.Type)); + // We have the components for writing out a setter. + buffer.AppendLine( + string.Format( + " public virtual {0} With{1}({2} value)", + cds.Identifier, + pds.Identifier, + pds.Type + ) + ); - buffer.AppendLine(" {"); - buffer.AppendLine( - string.Format(" this.{0} = value;", pds.Identifier)); - buffer.AppendLine(" return this;"); - buffer.AppendLine(" }"); - } + buffer.AppendLine(" {"); + buffer.AppendLine(string.Format(" this.{0} = value;", pds.Identifier)); + buffer.AppendLine(" return this;"); + buffer.AppendLine(" }"); + } - // Finish up the class. - buffer.AppendLine(" }"); - buffer.AppendLine("}"); + // Finish up the class. + buffer.AppendLine(" }"); + buffer.AppendLine("}"); - // Create the source text and write out the file. - var sourceText = SourceText.From(buffer.ToString(), Encoding.UTF8); - context.AddSource(cds.Identifier + ".Generated.cs", sourceText); - } + // Create the source text and write out the file. + var sourceText = SourceText.From(buffer.ToString(), Encoding.UTF8); + context.AddSource(cds.Identifier + ".Generated.cs", sourceText); + } } diff --git a/src/MfGames.Nitride.Generators/WithPropertiesSyntaxReceiver.cs b/src/MfGames.Nitride.Generators/WithPropertiesSyntaxReceiver.cs index dd43ad5..4012617 100644 --- a/src/MfGames.Nitride.Generators/WithPropertiesSyntaxReceiver.cs +++ b/src/MfGames.Nitride.Generators/WithPropertiesSyntaxReceiver.cs @@ -4,9 +4,7 @@ namespace MfGames.Nitride.Generators; public class WithPropertiesSyntaxReceiver : ClassAttributeSyntaxReceiverBase { - /// - public WithPropertiesSyntaxReceiver(GeneratorInitializationContext context) - : base(context, "WithProperties") - { - } + /// + public WithPropertiesSyntaxReceiver(GeneratorInitializationContext context) + : base(context, "WithProperties") { } } diff --git a/src/MfGames.Nitride.Handlebars/ApplyStyleTemplate.cs b/src/MfGames.Nitride.Handlebars/ApplyStyleTemplate.cs index def4404..a64edf1 100644 --- a/src/MfGames.Nitride.Handlebars/ApplyStyleTemplate.cs +++ b/src/MfGames.Nitride.Handlebars/ApplyStyleTemplate.cs @@ -1,7 +1,5 @@ using FluentValidation; - using HandlebarsDotNet; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Generators; @@ -15,55 +13,54 @@ namespace MfGames.Nitride.Handlebars; [WithProperties] public partial class ApplyStyleTemplate : OperationBase { - private readonly HandlebarsTemplateCache cache; + private readonly HandlebarsTemplateCache cache; - private readonly IValidator validator; + private readonly IValidator validator; - public ApplyStyleTemplate( - IValidator validator, - HandlebarsTemplateCache cache) - { - this.validator = validator; - this.cache = cache; - } + public ApplyStyleTemplate( + IValidator validator, + HandlebarsTemplateCache cache + ) + { + this.validator = validator; + this.cache = cache; + } - /// - /// Gets or sets the callback used to create a model from a given - /// entity. This allows for the website to customize what information is - /// being passed to the template. - /// - public Func? CreateModelCallback { get; set; } + /// + /// Gets or sets the callback used to create a model from a given + /// entity. This allows for the website to customize what information is + /// being passed to the template. + /// + public Func? CreateModelCallback { get; set; } - /// - /// Gets or sets the callback used to determine which template to use - /// for a given entity. This lets one have a per-page template change. - /// - public Func? GetTemplateName { get; set; } + /// + /// Gets or sets the callback used to determine which template to use + /// for a given entity. This lets one have a per-page template change. + /// + public Func? GetTemplateName { get; set; } - public IHandlebars? Handlebars { get; set; } + public IHandlebars? Handlebars { get; set; } - /// - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - // Make sure we have sane data. - this.validator.ValidateAndThrow(this); + /// + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + // Make sure we have sane data. + this.validator.ValidateAndThrow(this); - // Create and set up the Handlebars. - return input.SelectEntity(this.Apply); - } + // Create and set up the Handlebars. + return input.SelectEntity(this.Apply); + } - private Entity Apply( - Entity entity, - ITextContent content) - { - object model = this.CreateModelCallback!(entity); - string name = this.GetTemplateName!(entity); - HandlebarsTemplate template = - this.cache.GetNamedTemplate(name); - string result = template(model!); + private Entity Apply(Entity entity, ITextContent content) + { + object model = this.CreateModelCallback!(entity); + string name = this.GetTemplateName!(entity); + HandlebarsTemplate template = this.cache.GetNamedTemplate(name); + string result = template(model!); - return entity.SetTextContent(result); - } + return entity.SetTextContent(result); + } } diff --git a/src/MfGames.Nitride.Handlebars/ApplyStyleTemplateValidator.cs b/src/MfGames.Nitride.Handlebars/ApplyStyleTemplateValidator.cs index e9f20d5..2778c80 100644 --- a/src/MfGames.Nitride.Handlebars/ApplyStyleTemplateValidator.cs +++ b/src/MfGames.Nitride.Handlebars/ApplyStyleTemplateValidator.cs @@ -4,15 +4,12 @@ namespace MfGames.Nitride.Handlebars; public class ApplyStyleTemplateValidator : AbstractValidator { - public ApplyStyleTemplateValidator() - { - this.RuleFor(x => x.Handlebars) - .NotNull(); + public ApplyStyleTemplateValidator() + { + this.RuleFor(x => x.Handlebars).NotNull(); - this.RuleFor(x => x.GetTemplateName) - .NotNull(); + this.RuleFor(x => x.GetTemplateName).NotNull(); - this.RuleFor(x => x.CreateModelCallback) - .NotNull(); - } + this.RuleFor(x => x.CreateModelCallback).NotNull(); + } } diff --git a/src/MfGames.Nitride.Handlebars/Configuration/FileSystemHandlebarsTemplateLoader.cs b/src/MfGames.Nitride.Handlebars/Configuration/FileSystemHandlebarsTemplateLoader.cs index 4031bf0..d74e732 100644 --- a/src/MfGames.Nitride.Handlebars/Configuration/FileSystemHandlebarsTemplateLoader.cs +++ b/src/MfGames.Nitride.Handlebars/Configuration/FileSystemHandlebarsTemplateLoader.cs @@ -7,27 +7,25 @@ namespace MfGames.Nitride.Handlebars.Configuration; /// public class FileSystemHandlebarsTemplateLoader : IHandlebarsLoader { - private readonly DirectoryInfo directory; + private readonly DirectoryInfo directory; - private readonly string pattern; + private readonly string pattern; - public FileSystemHandlebarsTemplateLoader( - DirectoryInfo directory, - string pattern = "*.hbs") - { - this.directory = directory; - this.pattern = pattern; - } + public FileSystemHandlebarsTemplateLoader(DirectoryInfo directory, string pattern = "*.hbs") + { + this.directory = directory; + this.pattern = pattern; + } - /// - public void Register(IHandlebars handlebars) - { - foreach (FileInfo file in this.directory.GetFiles(this.pattern)) - { - string name = Path.GetFileNameWithoutExtension(file.Name); - string content = File.ReadAllText(file.FullName); + /// + public void Register(IHandlebars handlebars) + { + foreach (FileInfo file in this.directory.GetFiles(this.pattern)) + { + string name = Path.GetFileNameWithoutExtension(file.Name); + string content = File.ReadAllText(file.FullName); - handlebars.RegisterTemplate(name, content); - } - } + handlebars.RegisterTemplate(name, content); + } + } } diff --git a/src/MfGames.Nitride.Handlebars/Configuration/ForEachHandlebarsBlock.cs b/src/MfGames.Nitride.Handlebars/Configuration/ForEachHandlebarsBlock.cs index 0865b81..0b6ae75 100644 --- a/src/MfGames.Nitride.Handlebars/Configuration/ForEachHandlebarsBlock.cs +++ b/src/MfGames.Nitride.Handlebars/Configuration/ForEachHandlebarsBlock.cs @@ -7,93 +7,91 @@ namespace MfGames.Nitride.Handlebars.Configuration; /// A typesafe model of the template. public class ForEachHandlebarsBlock : HandlebarsBlockBase { - public ForEachHandlebarsBlock(string helperName) - { - this.HelperName = helperName; - } + public ForEachHandlebarsBlock(string helperName) + { + this.HelperName = helperName; + } - /// - /// Gets or sets the list that needs to be rendered. - /// - public Func>? GetList { get; set; } + /// + /// Gets or sets the list that needs to be rendered. + /// + public Func>? GetList { get; set; } - /// - /// Gets or sets the callback that is called when nothing is found. - /// - public Action? - NothingFound - { - get; - set; - } + /// + /// Gets or sets the callback that is called when nothing is found. + /// + public Action< + EncodedTextWriter, + BlockHelperOptions, + Context, + Arguments + >? NothingFound { get; set; } - /// - protected override string HelperName { get; } + /// + protected override string HelperName { get; } - public ForEachHandlebarsBlock WithGetList( - Func>? callback) - { - this.GetList = callback; + public ForEachHandlebarsBlock WithGetList(Func>? callback) + { + this.GetList = callback; - return this; - } + return this; + } - public ForEachHandlebarsBlock WithNothingFoundText( - Action? - callback) - { - this.NothingFound = callback; + public ForEachHandlebarsBlock WithNothingFoundText( + Action? callback + ) + { + this.NothingFound = callback; - return this; - } + return this; + } - /// - /// Sets the output to write out text when no items are found. - /// - /// The text to write out. - /// The same object for chained methods. - public ForEachHandlebarsBlock WithNothingFoundText(string text) - { - this.NothingFound = ( - output, - _1, - _2, - _3) => output.Write(text); + /// + /// Sets the output to write out text when no items are found. + /// + /// The text to write out. + /// The same object for chained methods. + public ForEachHandlebarsBlock WithNothingFoundText(string text) + { + this.NothingFound = (output, _1, _2, _3) => output.Write(text); - return this; - } + return this; + } - /// - protected override void Render( - EncodedTextWriter output, - BlockHelperOptions options, - Context context, - Arguments input) - { - if (context.Value is not TModel model) - { - throw new InvalidOperationException( - string.Format( - "Cannot apply the {0} on context value because it is {1}.", - nameof(ForEachHandlebarsBlock), - context.Value.GetType())); - } + /// + protected override void Render( + EncodedTextWriter output, + BlockHelperOptions options, + Context context, + Arguments input + ) + { + if (context.Value is not TModel model) + { + throw new InvalidOperationException( + string.Format( + "Cannot apply the {0} on context value because it is {1}.", + nameof(ForEachHandlebarsBlock), + context.Value.GetType() + ) + ); + } - IEnumerable? list = this.GetList?.Invoke(model); - bool hasItems = false; + IEnumerable? list = this.GetList?.Invoke(model); + bool hasItems = false; - if (list != null) - { - foreach (object item in list) - { - hasItems = true; - options.Template(output, item); - } - } + if (list != null) + { + foreach (object item in list) + { + hasItems = true; + options.Template(output, item); + } + } - if (!hasItems) - { - this.NothingFound?.Invoke(output, options, context, input); - } - } + if (!hasItems) + { + this.NothingFound?.Invoke(output, options, context, input); + } + } } diff --git a/src/MfGames.Nitride.Handlebars/Configuration/HandlebarsBlockBase.cs b/src/MfGames.Nitride.Handlebars/Configuration/HandlebarsBlockBase.cs index 65abd0b..b7cdaca 100644 --- a/src/MfGames.Nitride.Handlebars/Configuration/HandlebarsBlockBase.cs +++ b/src/MfGames.Nitride.Handlebars/Configuration/HandlebarsBlockBase.cs @@ -7,24 +7,25 @@ namespace MfGames.Nitride.Handlebars.Configuration; /// public abstract class HandlebarsBlockBase : IHandlebarsLoader { - /// - /// Gets the name of the helper, which is how it is called in the template. - /// - protected abstract string HelperName { get; } + /// + /// Gets the name of the helper, which is how it is called in the template. + /// + protected abstract string HelperName { get; } - public void Register(IHandlebars handlebars) - { - HandlebarsBlockHelper blockHelper = this.Render; + public void Register(IHandlebars handlebars) + { + HandlebarsBlockHelper blockHelper = this.Render; - handlebars.RegisterHelper(this.HelperName, blockHelper); - } + handlebars.RegisterHelper(this.HelperName, blockHelper); + } - /// - /// Renders the helper to the template. - /// - protected abstract void Render( - EncodedTextWriter output, - BlockHelperOptions options, - Context context, - Arguments input); + /// + /// Renders the helper to the template. + /// + protected abstract void Render( + EncodedTextWriter output, + BlockHelperOptions options, + Context context, + Arguments input + ); } diff --git a/src/MfGames.Nitride.Handlebars/Configuration/IHandlebarsLoader.cs b/src/MfGames.Nitride.Handlebars/Configuration/IHandlebarsLoader.cs index 220fc89..6492944 100644 --- a/src/MfGames.Nitride.Handlebars/Configuration/IHandlebarsLoader.cs +++ b/src/MfGames.Nitride.Handlebars/Configuration/IHandlebarsLoader.cs @@ -7,9 +7,9 @@ namespace MfGames.Nitride.Handlebars.Configuration; /// public interface IHandlebarsLoader { - /// - /// Registers the given helper into the handlebars engine. - /// - /// The handlebars to register the helper into. - void Register(IHandlebars handlebars); + /// + /// Registers the given helper into the handlebars engine. + /// + /// The handlebars to register the helper into. + void Register(IHandlebars handlebars); } diff --git a/src/MfGames.Nitride.Handlebars/HandlebarsTemplateCache.cs b/src/MfGames.Nitride.Handlebars/HandlebarsTemplateCache.cs index 50686f6..ab0a8ca 100644 --- a/src/MfGames.Nitride.Handlebars/HandlebarsTemplateCache.cs +++ b/src/MfGames.Nitride.Handlebars/HandlebarsTemplateCache.cs @@ -1,5 +1,4 @@ using HandlebarsDotNet; - using Open.Threading; namespace MfGames.Nitride.Handlebars; @@ -10,58 +9,55 @@ namespace MfGames.Nitride.Handlebars; /// public class HandlebarsTemplateCache { - private readonly IHandlebars handlebars; + private readonly IHandlebars handlebars; - private readonly ModificationSynchronizer locker; + private readonly ModificationSynchronizer locker; - private readonly Dictionary> - templates; + private readonly Dictionary> templates; - public HandlebarsTemplateCache(IHandlebars handlebars) - { - this.handlebars = handlebars; - this.locker = new ModificationSynchronizer(); - this.templates = - new Dictionary>(); - } + public HandlebarsTemplateCache(IHandlebars handlebars) + { + this.handlebars = handlebars; + this.locker = new ModificationSynchronizer(); + this.templates = new Dictionary>(); + } - /// - /// Caches the template by name based on the contents of the disk. It - /// does it once in a multi-threaded manner to ensure it is only cached - /// once in memory. - /// - /// The string that contains the template. - /// - public HandlebarsTemplate GetLiteralTemplate(string literal) - { - // Start with a read lock to see if we've already compiled it. - this.locker.Modifying( - () => !this.templates.ContainsKey(literal), - () => - { - HandlebarsTemplate template = - this.handlebars!.Compile(literal); + /// + /// Caches the template by name based on the contents of the disk. It + /// does it once in a multi-threaded manner to ensure it is only cached + /// once in memory. + /// + /// The string that contains the template. + /// + public HandlebarsTemplate GetLiteralTemplate(string literal) + { + // Start with a read lock to see if we've already compiled it. + this.locker.Modifying( + () => !this.templates.ContainsKey(literal), + () => + { + HandlebarsTemplate template = this.handlebars!.Compile(literal); - this.templates[literal] = template; + this.templates[literal] = template; - return true; - }); + return true; + } + ); - return this.locker.Reading(() => this.templates[literal]); - } + return this.locker.Reading(() => this.templates[literal]); + } - /// - /// Caches the template by name based on the contents of the disk. It - /// does it once in a multi-threaded manner to ensure it is only cached - /// once in memory. - /// - /// - /// - public HandlebarsTemplate GetNamedTemplate( - string templateName) - { - string template = $"{{{{> {templateName}}}}}"; + /// + /// Caches the template by name based on the contents of the disk. It + /// does it once in a multi-threaded manner to ensure it is only cached + /// once in memory. + /// + /// + /// + public HandlebarsTemplate GetNamedTemplate(string templateName) + { + string template = $"{{{{> {templateName}}}}}"; - return this.GetLiteralTemplate(template); - } + return this.GetLiteralTemplate(template); + } } diff --git a/src/MfGames.Nitride.Handlebars/HasHandlebarsTemplate.cs b/src/MfGames.Nitride.Handlebars/HasHandlebarsTemplate.cs index dda19f8..e4d1c38 100644 --- a/src/MfGames.Nitride.Handlebars/HasHandlebarsTemplate.cs +++ b/src/MfGames.Nitride.Handlebars/HasHandlebarsTemplate.cs @@ -6,5 +6,5 @@ namespace MfGames.Nitride.Handlebars; /// public record HasHandlebarsTemplate { - public static HasHandlebarsTemplate Instance { get; } = new(); + public static HasHandlebarsTemplate Instance { get; } = new(); } diff --git a/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromComponent.cs b/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromComponent.cs index 776617c..2346639 100644 --- a/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromComponent.cs +++ b/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromComponent.cs @@ -1,5 +1,4 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Generators; @@ -12,26 +11,28 @@ namespace MfGames.Nitride.Handlebars; [WithProperties] public partial class IdentifyHandlebarsFromComponent : IOperation { - private readonly IValidator validator; + private readonly IValidator validator; - public IdentifyHandlebarsFromComponent( - IValidator validator) - { - this.validator = validator; - } + public IdentifyHandlebarsFromComponent(IValidator validator) + { + this.validator = validator; + } - public Func HasHandlebarsTest { get; set; } = null!; + public Func HasHandlebarsTest { get; set; } = null!; - /// - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + /// + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return input.Select( - (entity) => this.HasHandlebarsTest.Invoke(entity) - ? entity.Set(HasHandlebarsTemplate.Instance) - : entity); - } + return input.Select( + (entity) => + this.HasHandlebarsTest.Invoke(entity) + ? entity.Set(HasHandlebarsTemplate.Instance) + : entity + ); + } } diff --git a/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromComponentValidator.cs b/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromComponentValidator.cs index a1d72d8..95e3d1c 100644 --- a/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromComponentValidator.cs +++ b/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromComponentValidator.cs @@ -3,11 +3,10 @@ using FluentValidation; namespace MfGames.Nitride.Handlebars; public class IdentifyHandlebarsFromComponentValidator - : AbstractValidator + : AbstractValidator { - public IdentifyHandlebarsFromComponentValidator() - { - this.RuleFor(x => x.HasHandlebarsTest) - .NotNull(); - } + public IdentifyHandlebarsFromComponentValidator() + { + this.RuleFor(x => x.HasHandlebarsTest).NotNull(); + } } diff --git a/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromContent.cs b/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromContent.cs index c569e4a..0dd0fbf 100644 --- a/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromContent.cs +++ b/src/MfGames.Nitride.Handlebars/IdentifyHandlebarsFromContent.cs @@ -9,25 +9,24 @@ namespace MfGames.Nitride.Handlebars; /// public class IdentifyHandlebarsFromContent : IOperation { - /// - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - return input.SelectEntity(this.ScanContent); - } + /// + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + return input.SelectEntity(this.ScanContent); + } - private Entity ScanContent( - Entity entity, - ITextContent content) - { - string text = content.GetTextContentString(); + private Entity ScanContent(Entity entity, ITextContent content) + { + string text = content.GetTextContentString(); - if (text.Contains("{{") && text.Contains("}}")) - { - return entity.Set(HasHandlebarsTemplate.Instance); - } + if (text.Contains("{{") && text.Contains("}}")) + { + return entity.Set(HasHandlebarsTemplate.Instance); + } - return entity; - } + return entity; + } } diff --git a/src/MfGames.Nitride.Handlebars/NitrideHandlebarsBuilderExtensions.cs b/src/MfGames.Nitride.Handlebars/NitrideHandlebarsBuilderExtensions.cs index d518e9c..65da190 100644 --- a/src/MfGames.Nitride.Handlebars/NitrideHandlebarsBuilderExtensions.cs +++ b/src/MfGames.Nitride.Handlebars/NitrideHandlebarsBuilderExtensions.cs @@ -1,49 +1,43 @@ using Autofac; - using MfGames.Nitride.Handlebars.Configuration; namespace MfGames.Nitride.Handlebars; public static class NitrideHandlebarsBuilderExtensions { - private static bool loaded; + private static bool loaded; - public static NitrideBuilder UseHandlebars(this NitrideBuilder builder) - { - // If we've already loaded, then we have a problem. - if (loaded) - { - throw new InvalidOperationException( - "Cannot use UseHandlebars() more than once."); - } + public static NitrideBuilder UseHandlebars(this NitrideBuilder builder) + { + // If we've already loaded, then we have a problem. + if (loaded) + { + throw new InvalidOperationException("Cannot use UseHandlebars() more than once."); + } - loaded = true; + loaded = true; - // Get the configuration so we can set the various options. - return builder - .ConfigureContainer( - x => x.RegisterModule()); - } + // Get the configuration so we can set the various options. + return builder.ConfigureContainer(x => x.RegisterModule()); + } - public static NitrideBuilder UseHandlebars( - this NitrideBuilder builder, - Func> configure) - { - builder.UseHandlebars(); + public static NitrideBuilder UseHandlebars( + this NitrideBuilder builder, + Func> configure + ) + { + builder.UseHandlebars(); - builder.ConfigureContainer( - c => - { - IEnumerable loaders = configure(c); + builder.ConfigureContainer(c => + { + IEnumerable loaders = configure(c); - foreach (IHandlebarsLoader loader in loaders) - { - c.RegisterInstance(loader) - .As() - .SingleInstance(); - } - }); + foreach (IHandlebarsLoader loader in loaders) + { + c.RegisterInstance(loader).As().SingleInstance(); + } + }); - return builder; - } + return builder; + } } diff --git a/src/MfGames.Nitride.Handlebars/NitrideHandlebarsModule.cs b/src/MfGames.Nitride.Handlebars/NitrideHandlebarsModule.cs index 539314a..969a446 100644 --- a/src/MfGames.Nitride.Handlebars/NitrideHandlebarsModule.cs +++ b/src/MfGames.Nitride.Handlebars/NitrideHandlebarsModule.cs @@ -1,39 +1,37 @@ using Autofac; - using HandlebarsDotNet; - using MfGames.Nitride.Handlebars.Configuration; namespace MfGames.Nitride.Handlebars; public class NitrideHandlebarsModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - builder.RegisterOperators(this); - builder.RegisterValidators(this); + /// + protected override void Load(ContainerBuilder builder) + { + builder.RegisterOperators(this); + builder.RegisterValidators(this); - builder.RegisterType() - .AsSelf() - .SingleInstance(); + builder.RegisterType().AsSelf().SingleInstance(); - builder.Register( - (context) => - { - IHandlebars handlebars = - HandlebarsDotNet.Handlebars.Create(); - IEnumerable helpers = - context.Resolve>(); + builder + .Register( + (context) => + { + IHandlebars handlebars = HandlebarsDotNet.Handlebars.Create(); + IEnumerable helpers = context.Resolve< + IEnumerable + >(); - foreach (IHandlebarsLoader helper in helpers) - { - helper.Register(handlebars); - } + foreach (IHandlebarsLoader helper in helpers) + { + helper.Register(handlebars); + } - return handlebars; - }) - .As() - .SingleInstance(); - } + return handlebars; + } + ) + .As() + .SingleInstance(); + } } diff --git a/src/MfGames.Nitride.Handlebars/RenderContentTemplate.cs b/src/MfGames.Nitride.Handlebars/RenderContentTemplate.cs index 3810e24..0a43efc 100644 --- a/src/MfGames.Nitride.Handlebars/RenderContentTemplate.cs +++ b/src/MfGames.Nitride.Handlebars/RenderContentTemplate.cs @@ -1,7 +1,5 @@ using FluentValidation; - using HandlebarsDotNet; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Generators; @@ -16,49 +14,44 @@ namespace MfGames.Nitride.Handlebars; [WithProperties] public partial class RenderContentTemplate : OperationBase { - private readonly HandlebarsTemplateCache cache; + private readonly HandlebarsTemplateCache cache; - private readonly IValidator validator; + private readonly IValidator validator; - public RenderContentTemplate( - IValidator validator, - HandlebarsTemplateCache cache) - { - this.validator = validator; - this.cache = cache; - } + public RenderContentTemplate( + IValidator validator, + HandlebarsTemplateCache cache + ) + { + this.validator = validator; + this.cache = cache; + } - /// - /// Gets or sets the callback used to create a model from a given - /// entity. This allows for the website to customize what information is - /// being passed to the template. - /// - public Func? CreateModelCallback { get; set; } + /// + /// Gets or sets the callback used to create a model from a given + /// entity. This allows for the website to customize what information is + /// being passed to the template. + /// + public Func? CreateModelCallback { get; set; } - /// - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + /// + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return input.SelectEntity( - this.Apply); - } + return input.SelectEntity(this.Apply); + } - private Entity Apply( - Entity entity, - HasHandlebarsTemplate _, - ITextContent content) - { - string text = content.GetTextContentString(); - HandlebarsTemplate template = - this.cache.GetLiteralTemplate(text); - object model = this.CreateModelCallback!(entity); - string result = template(model!); + private Entity Apply(Entity entity, HasHandlebarsTemplate _, ITextContent content) + { + string text = content.GetTextContentString(); + HandlebarsTemplate template = this.cache.GetLiteralTemplate(text); + object model = this.CreateModelCallback!(entity); + string result = template(model!); - return entity - .Remove() - .SetTextContent(result); - } + return entity.Remove().SetTextContent(result); + } } diff --git a/src/MfGames.Nitride.Handlebars/RenderContentTemplateValidator.cs b/src/MfGames.Nitride.Handlebars/RenderContentTemplateValidator.cs index 832bf37..70b0b16 100644 --- a/src/MfGames.Nitride.Handlebars/RenderContentTemplateValidator.cs +++ b/src/MfGames.Nitride.Handlebars/RenderContentTemplateValidator.cs @@ -2,12 +2,10 @@ using FluentValidation; namespace MfGames.Nitride.Handlebars; -public class RenderContentTemplateValidator - : AbstractValidator +public class RenderContentTemplateValidator : AbstractValidator { - public RenderContentTemplateValidator() - { - this.RuleFor(x => x.CreateModelCallback) - .NotNull(); - } + public RenderContentTemplateValidator() + { + this.RuleFor(x => x.CreateModelCallback).NotNull(); + } } diff --git a/src/MfGames.Nitride.Html/ConvertHtmlEntitiesToUnicode.cs b/src/MfGames.Nitride.Html/ConvertHtmlEntitiesToUnicode.cs index 56c51b1..dca5c73 100644 --- a/src/MfGames.Nitride.Html/ConvertHtmlEntitiesToUnicode.cs +++ b/src/MfGames.Nitride.Html/ConvertHtmlEntitiesToUnicode.cs @@ -1,5 +1,4 @@ using System.Net; - using MfGames.Gallium; using MfGames.Nitride.Contents; @@ -11,21 +10,20 @@ namespace MfGames.Nitride.Html; /// public class ConvertHtmlEntitiesToUnicode : OperationBase { - /// - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - return input.SelectEntity(this.ResolveHtmlEntities); - } + /// + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + return input.SelectEntity(this.ResolveHtmlEntities); + } - private Entity ResolveHtmlEntities( - Entity entity, - ITextContent content) - { - string text = content.GetTextContentString(); - string resolved = WebUtility.HtmlDecode(text); + private Entity ResolveHtmlEntities(Entity entity, ITextContent content) + { + string text = content.GetTextContentString(); + string resolved = WebUtility.HtmlDecode(text); - return entity.SetTextContent(resolved); - } + return entity.SetTextContent(resolved); + } } diff --git a/src/MfGames.Nitride.Html/IdentifyHtml.cs b/src/MfGames.Nitride.Html/IdentifyHtml.cs index 46dd207..ca7cf24 100644 --- a/src/MfGames.Nitride.Html/IdentifyHtml.cs +++ b/src/MfGames.Nitride.Html/IdentifyHtml.cs @@ -1,9 +1,7 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.Html; @@ -16,61 +14,53 @@ namespace MfGames.Nitride.Html; [WithProperties] public partial class IdentifyHtml : IOperation { - private readonly IValidator validator; + private readonly IValidator validator; - public IdentifyHtml(IValidator validator) - { - this.validator = validator; - } + public IdentifyHtml(IValidator validator) + { + this.validator = validator; + } - public Func IsHtmlTest { get; set; } = null!; + public Func IsHtmlTest { get; set; } = null!; - /// - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + /// + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return input - .SelectEntity(this.MarkTextEntities) - .SelectEntity(this.MarkBinaryEntities); - } + return input + .SelectEntity(this.MarkTextEntities) + .SelectEntity(this.MarkBinaryEntities); + } - private Entity MarkBinaryEntities( - Entity entity, - UPath path, - IBinaryContent binary) - { - // If we aren't a Markdown file, then there is nothing we can do about that. - if (!this.IsHtmlTest(entity, path)) - { - return entity; - } + private Entity MarkBinaryEntities(Entity entity, UPath path, IBinaryContent binary) + { + // If we aren't a Markdown file, then there is nothing we can do about that. + if (!this.IsHtmlTest(entity, path)) + { + return entity; + } - // Convert the file as a binary. - if (binary is ITextContentConvertable textConvertable) - { - entity = entity - .SetTextContent(textConvertable.ToTextContent()) - .SetIsHtml(); - } - else - { - throw new InvalidOperationException( - "Cannot convert a binary content to a text without ITextContentConvertable."); - } + // Convert the file as a binary. + if (binary is ITextContentConvertable textConvertable) + { + entity = entity.SetTextContent(textConvertable.ToTextContent()).SetIsHtml(); + } + else + { + throw new InvalidOperationException( + "Cannot convert a binary content to a text without ITextContentConvertable." + ); + } - return entity; - } + return entity; + } - private Entity MarkTextEntities( - Entity entity, - UPath path, - ITextContent _) - { - return this.IsHtmlTest(entity, path) - ? entity.SetIsHtml() - : entity; - } + private Entity MarkTextEntities(Entity entity, UPath path, ITextContent _) + { + return this.IsHtmlTest(entity, path) ? entity.SetIsHtml() : entity; + } } diff --git a/src/MfGames.Nitride.Html/IdentifyHtmlFromPath.cs b/src/MfGames.Nitride.Html/IdentifyHtmlFromPath.cs index dcb8602..d5d7489 100644 --- a/src/MfGames.Nitride.Html/IdentifyHtmlFromPath.cs +++ b/src/MfGames.Nitride.Html/IdentifyHtmlFromPath.cs @@ -1,29 +1,24 @@ using FluentValidation; - using MfGames.Gallium; - using Zio; namespace MfGames.Nitride.Html; public class IdentifyHtmlFromPath : IdentifyHtml { - public IdentifyHtmlFromPath(IValidator validator) - : base(validator) - { - this.IsHtmlTest = DefaultIsHtml; - } + public IdentifyHtmlFromPath(IValidator validator) + : base(validator) + { + this.IsHtmlTest = DefaultIsHtml; + } - private static bool DefaultIsHtml( - Entity entity, - UPath path) - { - return (path.GetExtensionWithDot() ?? string.Empty).ToLowerInvariant() - switch - { - ".htm" => true, - ".html" => true, - _ => false, - }; - } + private static bool DefaultIsHtml(Entity entity, UPath path) + { + return (path.GetExtensionWithDot() ?? string.Empty).ToLowerInvariant() switch + { + ".htm" => true, + ".html" => true, + _ => false, + }; + } } diff --git a/src/MfGames.Nitride.Html/IsHtml.cs b/src/MfGames.Nitride.Html/IsHtml.cs index 8a2fbd3..882908a 100644 --- a/src/MfGames.Nitride.Html/IsHtml.cs +++ b/src/MfGames.Nitride.Html/IsHtml.cs @@ -6,6 +6,4 @@ namespace MfGames.Nitride.Html; /// A marker component that indicates that the entity is an HTML file. /// [SingletonComponent] -public partial class IsHtml -{ -} +public partial class IsHtml { } diff --git a/src/MfGames.Nitride.Html/NitrideHtmlBuilderExtensions.cs b/src/MfGames.Nitride.Html/NitrideHtmlBuilderExtensions.cs index 0a631db..f2a4fe1 100644 --- a/src/MfGames.Nitride.Html/NitrideHtmlBuilderExtensions.cs +++ b/src/MfGames.Nitride.Html/NitrideHtmlBuilderExtensions.cs @@ -4,21 +4,19 @@ namespace MfGames.Nitride.Html; public static class NitrideHtmlBuilderExtensions { - private static bool loaded; + private static bool loaded; - public static NitrideBuilder UseHtml(this NitrideBuilder builder) - { - // If we've already loaded, then we have a problem. - if (loaded) - { - throw new InvalidOperationException( - "Cannot use UseHtml() more than once."); - } + public static NitrideBuilder UseHtml(this NitrideBuilder builder) + { + // If we've already loaded, then we have a problem. + if (loaded) + { + throw new InvalidOperationException("Cannot use UseHtml() more than once."); + } - loaded = true; + loaded = true; - // Get the configuration so we can set the various options. - return builder.ConfigureContainer( - x => x.RegisterModule()); - } + // Get the configuration so we can set the various options. + return builder.ConfigureContainer(x => x.RegisterModule()); + } } diff --git a/src/MfGames.Nitride.Html/NitrideHtmlModule.cs b/src/MfGames.Nitride.Html/NitrideHtmlModule.cs index cfa5b8d..45a6233 100644 --- a/src/MfGames.Nitride.Html/NitrideHtmlModule.cs +++ b/src/MfGames.Nitride.Html/NitrideHtmlModule.cs @@ -4,10 +4,10 @@ namespace MfGames.Nitride.Html; public class NitrideHtmlModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - builder.RegisterOperators(this); - builder.RegisterValidators(this); - } + /// + protected override void Load(ContainerBuilder builder) + { + builder.RegisterOperators(this); + builder.RegisterValidators(this); + } } diff --git a/src/MfGames.Nitride.Html/Validators/IdentifyHtmlValidator.cs b/src/MfGames.Nitride.Html/Validators/IdentifyHtmlValidator.cs index a38b7ef..f69460f 100644 --- a/src/MfGames.Nitride.Html/Validators/IdentifyHtmlValidator.cs +++ b/src/MfGames.Nitride.Html/Validators/IdentifyHtmlValidator.cs @@ -4,9 +4,8 @@ namespace MfGames.Nitride.Html.Validators; public class IdentifyHtmlValidator : AbstractValidator { - public IdentifyHtmlValidator() - { - this.RuleFor(x => x.IsHtmlTest) - .NotNull(); - } + public IdentifyHtmlValidator() + { + this.RuleFor(x => x.IsHtmlTest).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Contents/FileEntryBinaryContent.cs b/src/MfGames.Nitride.IO/Contents/FileEntryBinaryContent.cs index 5fca34e..49cfc70 100644 --- a/src/MfGames.Nitride.IO/Contents/FileEntryBinaryContent.cs +++ b/src/MfGames.Nitride.IO/Contents/FileEntryBinaryContent.cs @@ -1,5 +1,4 @@ using MfGames.Nitride.Contents; - using Zio; namespace MfGames.Nitride.IO.Contents; @@ -9,22 +8,22 @@ namespace MfGames.Nitride.IO.Contents; /// public class FileEntryBinaryContent : IBinaryContent, ITextContentConvertable { - private readonly FileEntry entry; + private readonly FileEntry entry; - public FileEntryBinaryContent(FileEntry entry) - { - this.entry = entry; - } + public FileEntryBinaryContent(FileEntry entry) + { + this.entry = entry; + } - /// - public Stream GetStream() - { - return this.entry.Open(FileMode.Open, FileAccess.Read, FileShare.Read); - } + /// + public Stream GetStream() + { + return this.entry.Open(FileMode.Open, FileAccess.Read, FileShare.Read); + } - /// - public ITextContent ToTextContent() - { - return new FileEntryTextContent(this.entry); - } + /// + public ITextContent ToTextContent() + { + return new FileEntryTextContent(this.entry); + } } diff --git a/src/MfGames.Nitride.IO/Contents/FileEntryTextContent.cs b/src/MfGames.Nitride.IO/Contents/FileEntryTextContent.cs index d775978..9c73bd2 100644 --- a/src/MfGames.Nitride.IO/Contents/FileEntryTextContent.cs +++ b/src/MfGames.Nitride.IO/Contents/FileEntryTextContent.cs @@ -1,7 +1,5 @@ using System.Text; - using MfGames.Nitride.Contents; - using Zio; namespace MfGames.Nitride.IO.Contents; @@ -11,24 +9,25 @@ namespace MfGames.Nitride.IO.Contents; /// public class FileEntryTextContent : ITextContent, IBinaryContentConvertable { - private readonly FileEntry entry; + private readonly FileEntry entry; - public FileEntryTextContent(FileEntry entry) - { - this.entry = entry; - } + public FileEntryTextContent(FileEntry entry) + { + this.entry = entry; + } - /// - public TextReader GetReader() - { - return new StreamReader( - this.entry.Open(FileMode.Open, FileAccess.Read, FileShare.Read), - Encoding.UTF8); - } + /// + public TextReader GetReader() + { + return new StreamReader( + this.entry.Open(FileMode.Open, FileAccess.Read, FileShare.Read), + Encoding.UTF8 + ); + } - /// - public IBinaryContent ToBinaryContent() - { - return new FileEntryBinaryContent(this.entry); - } + /// + public IBinaryContent ToBinaryContent() + { + return new FileEntryBinaryContent(this.entry); + } } diff --git a/src/MfGames.Nitride.IO/Contents/ReadFiles.cs b/src/MfGames.Nitride.IO/Contents/ReadFiles.cs index 11a2e87..1b3afcd 100644 --- a/src/MfGames.Nitride.IO/Contents/ReadFiles.cs +++ b/src/MfGames.Nitride.IO/Contents/ReadFiles.cs @@ -1,12 +1,9 @@ using DotNet.Globbing; - using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Generators; using MfGames.Nitride.IO.Paths; - using Zio; namespace MfGames.Nitride.IO.Contents; @@ -18,95 +15,100 @@ namespace MfGames.Nitride.IO.Contents; [WithProperties] public partial class ReadFiles : FileSystemOperationBase { - private readonly Func removePathPrefixFactory; + private readonly Func removePathPrefixFactory; - private readonly IValidator validator; + private readonly IValidator validator; - public ReadFiles( - IValidator validator, - IFileSystem fileSystem, - Func removePathPrefixFactory) - : base(fileSystem) - { - this.validator = validator; - this.removePathPrefixFactory = removePathPrefixFactory; - } + public ReadFiles( + IValidator validator, + IFileSystem fileSystem, + Func removePathPrefixFactory + ) + : base(fileSystem) + { + this.validator = validator; + this.removePathPrefixFactory = removePathPrefixFactory; + } - /// - /// Gets or sets the file pattern to retrieve fields. This supports - /// globbing both "*" and "**" patterns such as "**/*". - /// - public string Pattern { get; set; } = null!; + /// + /// Gets or sets the file pattern to retrieve fields. This supports + /// globbing both "*" and "**" patterns such as "**/*". + /// + public string Pattern { get; set; } = null!; - /// - /// Gets or sets the prefix to remove from the paths. This is convenience - /// method that is the same as calling ReadFiles, then RemovePathPrefix - /// with the parameter. - /// - public string? RemovePathPrefix { get; set; } + /// + /// Gets or sets the prefix to remove from the paths. This is convenience + /// method that is the same as calling ReadFiles, then RemovePathPrefix + /// with the parameter. + /// + public string? RemovePathPrefix { get; set; } - /// - /// Reads all files from the file system, filtering them out by the - /// minimatch pattern (as defined by DotNet.Blob). - /// - /// A populated collection of entities. - public IEnumerable Run( - CancellationToken cancellationToken = default) - { - return this.Run(Array.Empty(), cancellationToken); - } + /// + /// Reads all files from the file system, filtering them out by the + /// minimatch pattern (as defined by DotNet.Blob). + /// + /// A populated collection of entities. + public IEnumerable Run(CancellationToken cancellationToken = default) + { + return this.Run(Array.Empty(), cancellationToken); + } - /// - /// Reads all files from the file system, filtering them out by the - /// minimatch pattern (as defined by DotNet.Blob). - /// - /// A populated collection of entities. - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - // Read the files from the file system. - this.validator.ValidateAndThrow(this); + /// + /// Reads all files from the file system, filtering them out by the + /// minimatch pattern (as defined by DotNet.Blob). + /// + /// A populated collection of entities. + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + // Read the files from the file system. + this.validator.ValidateAndThrow(this); - var glob = Glob.Parse(this.Pattern); + var glob = Glob.Parse(this.Pattern); - IEnumerable files = this.FileSystem - .EnumerateFileEntries("/", "*", SearchOption.AllDirectories) - .Where(x => glob.IsMatch(x.Path.ToString())); + IEnumerable files = this.FileSystem.EnumerateFileEntries( + "/", + "*", + SearchOption.AllDirectories + ) + .Where(x => glob.IsMatch(x.Path.ToString())); - IEnumerable entities = files.Select(this.ToEntity); + IEnumerable entities = files.Select(this.ToEntity); - // If we have a remove prefix, then call that. - if (this.RemovePathPrefix != null) - { - RemovePathPrefix removePath = this.removePathPrefixFactory() - .WithPathPrefix(this.RemovePathPrefix); + // If we have a remove prefix, then call that. + if (this.RemovePathPrefix != null) + { + RemovePathPrefix removePath = this.removePathPrefixFactory() + .WithPathPrefix(this.RemovePathPrefix); - entities = removePath.Run(entities, cancellationToken); - } + entities = removePath.Run(entities, cancellationToken); + } - return entities; - } + return entities; + } - public ReadFiles WithFileSystem(IFileSystem value) - { - this.FileSystem = value; + public ReadFiles WithFileSystem(IFileSystem value) + { + this.FileSystem = value; - return this; - } + return this; + } - /// - /// Creates an entity with the standard components for all Zio-based - /// files. This attaches the file's path relative to the file system - /// and a way of accessing the content from the file system. - /// - /// The Zio file entry. - /// An Entity with appropriate content. - private Entity ToEntity(FileEntry file) - { - Entity entity = new Entity().Set(file.Path) - .SetBinaryContent(new FileEntryBinaryContent(file)); + /// + /// Creates an entity with the standard components for all Zio-based + /// files. This attaches the file's path relative to the file system + /// and a way of accessing the content from the file system. + /// + /// The Zio file entry. + /// An Entity with appropriate content. + private Entity ToEntity(FileEntry file) + { + Entity entity = new Entity() + .Set(file.Path) + .SetBinaryContent(new FileEntryBinaryContent(file)); - return entity; - } + return entity; + } } diff --git a/src/MfGames.Nitride.IO/Contents/ReadFilesValidator.cs b/src/MfGames.Nitride.IO/Contents/ReadFilesValidator.cs index 54096e2..a20891d 100644 --- a/src/MfGames.Nitride.IO/Contents/ReadFilesValidator.cs +++ b/src/MfGames.Nitride.IO/Contents/ReadFilesValidator.cs @@ -4,12 +4,10 @@ namespace MfGames.Nitride.IO.Contents; public class ReadFilesValidator : AbstractValidator { - public ReadFilesValidator() - { - this.RuleFor(x => x.Pattern) - .NotNull(); + public ReadFilesValidator() + { + this.RuleFor(x => x.Pattern).NotNull(); - this.RuleFor(x => x.FileSystem) - .NotNull(); - } + this.RuleFor(x => x.FileSystem).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Contents/WriteFiles.cs b/src/MfGames.Nitride.IO/Contents/WriteFiles.cs index dfe7fdf..5372520 100644 --- a/src/MfGames.Nitride.IO/Contents/WriteFiles.cs +++ b/src/MfGames.Nitride.IO/Contents/WriteFiles.cs @@ -1,14 +1,10 @@ using System.Text; - using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Generators; using MfGames.Nitride.IO.Paths; - using Serilog; - using Zio; namespace MfGames.Nitride.IO.Contents; @@ -19,248 +15,240 @@ namespace MfGames.Nitride.IO.Contents; [WithProperties] public partial class WriteFiles : FileSystemOperationBase, IOperation { - private readonly Func addPathPrefixFactory; + private readonly Func addPathPrefixFactory; - private readonly IValidator validator; + private readonly IValidator validator; - private Dictionary> factories; + private Dictionary> factories; - public WriteFiles( - IValidator validator, - ILogger logger, - IFileSystem fileSystem, - Func addPathPrefixFactory) - : base(fileSystem) - { - this.Logger = logger.ForContext(); - this.validator = validator; - this.addPathPrefixFactory = addPathPrefixFactory; - this.TextEncoding = Encoding.UTF8; + public WriteFiles( + IValidator validator, + ILogger logger, + IFileSystem fileSystem, + Func addPathPrefixFactory + ) + : base(fileSystem) + { + this.Logger = logger.ForContext(); + this.validator = validator; + this.addPathPrefixFactory = addPathPrefixFactory; + this.TextEncoding = Encoding.UTF8; - this.factories = new Dictionary> - { - [typeof(IBinaryContent)] = GetBinaryStream, - [typeof(ITextContent)] = this.GetTextStream, - }; - } + this.factories = new Dictionary> + { + [typeof(IBinaryContent)] = GetBinaryStream, + [typeof(ITextContent)] = this.GetTextStream, + }; + } - /// - /// Gets or sets the optional prefix to add to the files before writing - /// out the files. This is the same as calling AddPathPrefix followed by - /// WriteFiles. - /// - public string? AddPathPrefix { get; set; } + /// + /// Gets or sets the optional prefix to add to the files before writing + /// out the files. This is the same as calling AddPathPrefix followed by + /// WriteFiles. + /// + public string? AddPathPrefix { get; set; } - public ILogger Logger { get; set; } = null!; + public ILogger Logger { get; set; } = null!; - public Dictionary> StreamFactories - { - get => this.factories; - set => this.factories = - value ?? throw new ArgumentNullException(nameof(value)); - } + public Dictionary> StreamFactories + { + get => this.factories; + set => this.factories = value ?? throw new ArgumentNullException(nameof(value)); + } - /// - /// Gets or sets the encoding to force any text output. - /// - public Encoding TextEncoding { get; set; } + /// + /// Gets or sets the encoding to force any text output. + /// + public Encoding TextEncoding { get; set; } - /// - /// Writes out all the files to the given file system using the paths - /// currently stored in the `UPath` component. Only files that have - /// a path and a registered writer will be written. - /// - /// The entities to parse. - /// - /// The same list of entities without changes. - public override IEnumerable Run( - IEnumerable entities, - CancellationToken cancellationToken = default) - { - // Make sure everything is good. - this.validator.ValidateAndThrow(this); + /// + /// Writes out all the files to the given file system using the paths + /// currently stored in the `UPath` component. Only files that have + /// a path and a registered writer will be written. + /// + /// The entities to parse. + /// + /// The same list of entities without changes. + public override IEnumerable Run( + IEnumerable entities, + CancellationToken cancellationToken = default + ) + { + // Make sure everything is good. + this.validator.ValidateAndThrow(this); - // If we have the add prefix, then add it here. If we don't, then just - // pass it on without changes. - if (this.AddPathPrefix != null) - { - AddPathPrefix addPath = this.addPathPrefixFactory() - .WithPathPrefix(this.AddPathPrefix); + // If we have the add prefix, then add it here. If we don't, then just + // pass it on without changes. + if (this.AddPathPrefix != null) + { + AddPathPrefix addPath = this.addPathPrefixFactory().WithPathPrefix(this.AddPathPrefix); - entities = addPath.Run(entities); - } + entities = addPath.Run(entities); + } - // Write out the files to the file system. - IEnumerable results = entities - .SelectEntity(this.Process) - .ToList(); + // Write out the files to the file system. + IEnumerable results = entities.SelectEntity(this.Process).ToList(); - return results; - } + return results; + } - public WriteFiles WithFileSystem(IFileSystem fileSystem) - { - this.FileSystem = fileSystem; + public WriteFiles WithFileSystem(IFileSystem fileSystem) + { + this.FileSystem = fileSystem; - return this; - } + return this; + } - private static Stream GetBinaryStream(IContent content) - { - return ((IBinaryContent)content).GetStream(); - } + private static Stream GetBinaryStream(IContent content) + { + return ((IBinaryContent)content).GetStream(); + } - private Stream GetTextStream(IContent content) - { - // See if we can convert the stream first. If that is the case, then - // we don't have to load it entirely in memory. - if (content is IBinaryContentConvertable convertable) - { - return convertable.ToBinaryContent() - .GetStream(); - } + private Stream GetTextStream(IContent content) + { + // See if we can convert the stream first. If that is the case, then + // we don't have to load it entirely in memory. + if (content is IBinaryContentConvertable convertable) + { + return convertable.ToBinaryContent().GetStream(); + } - // We have the load the text into memory and convert it. - var textContent = (ITextContent)content; + // We have the load the text into memory and convert it. + var textContent = (ITextContent)content; - string text = textContent.GetReader() - .ReadToEnd(); + string text = textContent.GetReader().ReadToEnd(); - var stream = new MemoryStream(); - var writer = new StreamWriter( - stream, - this.TextEncoding ?? Encoding.UTF8); + var stream = new MemoryStream(); + var writer = new StreamWriter(stream, this.TextEncoding ?? Encoding.UTF8); - writer.Write(text); - writer.Flush(); - stream.Position = 0; + writer.Write(text); + writer.Flush(); + stream.Position = 0; - return stream; - } + return stream; + } - /// - /// Internal method for writing out the entity. This handles the - /// registered writers to allow for multiple `IContent` types being - /// written out automatically. - /// - /// The entity to write out. - /// The path of the entity. - /// The entity passed in. - private Entity Process( - Entity entity, - UPath path) - { - // See if we have any content. If we don't, then there is nothing - // to do. - if (!entity.HasContent()) - { - return entity; - } + /// + /// Internal method for writing out the entity. This handles the + /// registered writers to allow for multiple `IContent` types being + /// written out automatically. + /// + /// The entity to write out. + /// The path of the entity. + /// The entity passed in. + private Entity Process(Entity entity, UPath path) + { + // See if we have any content. If we don't, then there is nothing + // to do. + if (!entity.HasContent()) + { + return entity; + } - // First see if we have a factory for the exact type of content. - IContent content = entity.GetContent(); + // First see if we have a factory for the exact type of content. + IContent content = entity.GetContent(); - if (this.factories.TryGetValue( - content.GetType(), - out Func? getStream)) - { - Stream stream = getStream(content); + if (this.factories.TryGetValue(content.GetType(), out Func? getStream)) + { + Stream stream = getStream(content); - return this.Process(entity, path, stream); - } + return this.Process(entity, path, stream); + } - // If we have an easy conversion, then use that so we don't have to - // walk up the tree looking for one we do have. - if (content is IBinaryContentConvertable binaryConvertable - && this.factories.TryGetValue( - typeof(IBinaryContent), - out Func? binaryContent)) - { - Stream stream = binaryContent(binaryConvertable.ToBinaryContent()); + // If we have an easy conversion, then use that so we don't have to + // walk up the tree looking for one we do have. + if ( + content is IBinaryContentConvertable binaryConvertable + && this.factories.TryGetValue( + typeof(IBinaryContent), + out Func? binaryContent + ) + ) + { + Stream stream = binaryContent(binaryConvertable.ToBinaryContent()); - return this.Process(entity, path, stream); - } + return this.Process(entity, path, stream); + } - if (content is ITextContentConvertable textConvertable - && this.factories.TryGetValue( - typeof(ITextContent), - out Func? textContent)) - { - Stream stream = textContent(textConvertable.ToTextContent()); + if ( + content is ITextContentConvertable textConvertable + && this.factories.TryGetValue( + typeof(ITextContent), + out Func? textContent + ) + ) + { + Stream stream = textContent(textConvertable.ToTextContent()); - return this.Process(entity, path, stream); - } + return this.Process(entity, path, stream); + } - // For everything else, we have to find a content that we have a - // registered type for by walking up the inheritance tree and - // finding the right type. - List types = new() { content.GetType() }; + // For everything else, we have to find a content that we have a + // registered type for by walking up the inheritance tree and + // finding the right type. + List types = new() { content.GetType() }; - while (types.Count > 0) - { - // Check to see if we have any of these types. - Func? found = types - .Select( - x => this.factories.TryGetValue( - x, - out Func? factory) - ? factory - : null) - .FirstOrDefault(x => x != null); + while (types.Count > 0) + { + // Check to see if we have any of these types. + Func? found = types + .Select(x => + this.factories.TryGetValue(x, out Func? factory) + ? factory + : null + ) + .FirstOrDefault(x => x != null); - if (found != null) - { - Stream stream = found(content); + if (found != null) + { + Stream stream = found(content); - return this.Process(entity, path, stream); - } + return this.Process(entity, path, stream); + } - // We didn't find one, so add all the parent types and try - // again with the new list. - types = types - .SelectMany(x => new[] { x.BaseType }.Union(x.GetInterfaces())) - .Where(x => x != null) - .Select(x => x!) - .ToList(); - } + // We didn't find one, so add all the parent types and try + // again with the new list. + types = types + .SelectMany(x => new[] { x.BaseType }.Union(x.GetInterfaces())) + .Where(x => x != null) + .Select(x => x!) + .ToList(); + } - // If we got this far, we never found a content to handle. - throw new InvalidOperationException( - "Cannot write out entity " - + path - + " because cannot determine how to get a stream out content type " - + content.GetType() - .FullName - + ". To resolve, register a function to this.StreamFactories."); - } + // If we got this far, we never found a content to handle. + throw new InvalidOperationException( + "Cannot write out entity " + + path + + " because cannot determine how to get a stream out content type " + + content.GetType().FullName + + ". To resolve, register a function to this.StreamFactories." + ); + } - /// - /// Writes out a stream to the given path in the file system. - /// - /// The entity being written out. - /// The path to write out, directories will be created. - /// The stream to write out. - /// The entity passed in. - private Entity Process( - Entity entity, - UPath path, - Stream stream) - { - // Make sure we have the directory structure. - UPath directory = path.GetDirectory(); + /// + /// Writes out a stream to the given path in the file system. + /// + /// The entity being written out. + /// The path to write out, directories will be created. + /// The stream to write out. + /// The entity passed in. + private Entity Process(Entity entity, UPath path, Stream stream) + { + // Make sure we have the directory structure. + UPath directory = path.GetDirectory(); - if (directory != "/") - { - this.FileSystem.CreateDirectory(directory); - } + if (directory != "/") + { + this.FileSystem.CreateDirectory(directory); + } - // Write out the file. - using Stream fileStream = this.FileSystem.CreateFile(path); + // Write out the file. + using Stream fileStream = this.FileSystem.CreateFile(path); - stream.CopyTo(fileStream); - stream.Close(); + stream.CopyTo(fileStream); + stream.Close(); - // Return the entity because we've written out the files. - return entity; - } + // Return the entity because we've written out the files. + return entity; + } } diff --git a/src/MfGames.Nitride.IO/Contents/WriteFilesValidator.cs b/src/MfGames.Nitride.IO/Contents/WriteFilesValidator.cs index ab2f16a..9b84f3d 100644 --- a/src/MfGames.Nitride.IO/Contents/WriteFilesValidator.cs +++ b/src/MfGames.Nitride.IO/Contents/WriteFilesValidator.cs @@ -4,18 +4,14 @@ namespace MfGames.Nitride.IO.Contents; public class WriteFilesValidator : AbstractValidator { - public WriteFilesValidator() - { - this.RuleFor(x => x.StreamFactories) - .NotNull(); + public WriteFilesValidator() + { + this.RuleFor(x => x.StreamFactories).NotNull(); - this.RuleFor(x => x.TextEncoding) - .NotNull(); + this.RuleFor(x => x.TextEncoding).NotNull(); - this.RuleFor(x => x.FileSystem) - .NotNull(); + this.RuleFor(x => x.FileSystem).NotNull(); - this.RuleFor(x => x.Logger) - .NotNull(); - } + this.RuleFor(x => x.Logger).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Directories/ClearDirectory.cs b/src/MfGames.Nitride.IO/Directories/ClearDirectory.cs index 167caa4..8cb9785 100644 --- a/src/MfGames.Nitride.IO/Directories/ClearDirectory.cs +++ b/src/MfGames.Nitride.IO/Directories/ClearDirectory.cs @@ -1,10 +1,7 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Generators; - using Serilog; - using Zio; namespace MfGames.Nitride.IO.Directories; @@ -18,81 +15,82 @@ namespace MfGames.Nitride.IO.Directories; [WithProperties] public partial class ClearDirectory : FileSystemOperationBase, IOperation { - private readonly IValidator validator; + private readonly IValidator validator; - public ClearDirectory( - IValidator validator, - IFileSystem fileSystem, - ILogger logger) - : base(fileSystem) - { - this.Logger = logger.ForContext(); - this.validator = validator; - } + public ClearDirectory( + IValidator validator, + IFileSystem fileSystem, + ILogger logger + ) + : base(fileSystem) + { + this.Logger = logger.ForContext(); + this.validator = validator; + } - public ILogger Logger { get; set; } + public ILogger Logger { get; set; } - /// - /// Gets or sets the path of the directory to clear. - /// - public UPath? Path { get; set; } + /// + /// Gets or sets the path of the directory to clear. + /// + public UPath? Path { get; set; } - public IEnumerable Run( - CancellationToken cancellationToken = default) - { - return this.Run(new List(), cancellationToken); - } + public IEnumerable Run(CancellationToken cancellationToken = default) + { + return this.Run(new List(), cancellationToken); + } - /// - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + /// + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - // This really isn't an input-type of operation, but it can fit - // inside one to keep a pattern. - if (!this.Path.HasValue) - { - throw new InvalidOperationException( - nameof(ClearDirectory) - + "cannot be used without setting the path either by the" - + "factory method, the constructor, the property, or " - + "SetPath method."); - } + // This really isn't an input-type of operation, but it can fit + // inside one to keep a pattern. + if (!this.Path.HasValue) + { + throw new InvalidOperationException( + nameof(ClearDirectory) + + "cannot be used without setting the path either by the" + + "factory method, the constructor, the property, or " + + "SetPath method." + ); + } - // See if the directory exists. If it doesn't, then we make it. - UPath path = this.Path.Value; + // See if the directory exists. If it doesn't, then we make it. + UPath path = this.Path.Value; - if (!this.FileSystem.DirectoryExists(path)) - { - this.Logger.Information("Creating the directory {Path}", path); - this.FileSystem.CreateDirectory(path); - } + if (!this.FileSystem.DirectoryExists(path)) + { + this.Logger.Information("Creating the directory {Path}", path); + this.FileSystem.CreateDirectory(path); + } - // Clear out the contents. - IEnumerable files = this.FileSystem.EnumerateFiles(path); - IEnumerable directories = - this.FileSystem.EnumerateDirectories(path); + // Clear out the contents. + IEnumerable files = this.FileSystem.EnumerateFiles(path); + IEnumerable directories = this.FileSystem.EnumerateDirectories(path); - foreach (UPath file in files) - { - this.FileSystem.DeleteFile(file); - } + foreach (UPath file in files) + { + this.FileSystem.DeleteFile(file); + } - foreach (UPath directory in directories) - { - this.FileSystem.DeleteDirectory(directory, true); - } + foreach (UPath directory in directories) + { + this.FileSystem.DeleteDirectory(directory, true); + } - // Just pass the input on. - return input; - } + // Just pass the input on. + return input; + } - public ClearDirectory WithFileSystem(IFileSystem value) - { - this.FileSystem = value; + public ClearDirectory WithFileSystem(IFileSystem value) + { + this.FileSystem = value; - return this; - } + return this; + } } diff --git a/src/MfGames.Nitride.IO/Directories/ClearDirectoryValidator.cs b/src/MfGames.Nitride.IO/Directories/ClearDirectoryValidator.cs index 18201c9..6ff1995 100644 --- a/src/MfGames.Nitride.IO/Directories/ClearDirectoryValidator.cs +++ b/src/MfGames.Nitride.IO/Directories/ClearDirectoryValidator.cs @@ -4,15 +4,12 @@ namespace MfGames.Nitride.IO.Directories; public class ClearDirectoryValidator : AbstractValidator { - public ClearDirectoryValidator() - { - this.RuleFor(x => x.Path) - .NotNull(); + public ClearDirectoryValidator() + { + this.RuleFor(x => x.Path).NotNull(); - this.RuleFor(x => x.FileSystem) - .NotNull(); + this.RuleFor(x => x.FileSystem).NotNull(); - this.RuleFor(x => x.Logger) - .NotNull(); - } + this.RuleFor(x => x.Logger).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Extensions/NitrideIOEnumerableEntityExtensions.cs b/src/MfGames.Nitride.IO/Extensions/NitrideIOEnumerableEntityExtensions.cs index 0c5790f..a15472a 100644 --- a/src/MfGames.Nitride.IO/Extensions/NitrideIOEnumerableEntityExtensions.cs +++ b/src/MfGames.Nitride.IO/Extensions/NitrideIOEnumerableEntityExtensions.cs @@ -1,7 +1,5 @@ using MAB.DotIgnore; - using MfGames.Gallium; - using Zio; namespace MfGames.Nitride.IO.Extensions; @@ -11,78 +9,80 @@ namespace MfGames.Nitride.IO.Extensions; /// public static class NitrideIOEnumerableEntityExtensions { - /// - /// Retrieves an entity from the sequence of entities. - /// - /// The sequence of iterations to parse. - /// The path to search for. - /// The entity pulled out, if found. Otherwise null. - /// If true, then remove the entity from the list. - /// The sequence of entities, optionally without one. - public static IEnumerable GetEntityByPath( - this IEnumerable input, - UPath path, - out Entity? foundEntity, - IfFoundOutput removeFromResults = IfFoundOutput.RemoveFromOutput) - { - List output = new(); - foundEntity = null; + /// + /// Retrieves an entity from the sequence of entities. + /// + /// The sequence of iterations to parse. + /// The path to search for. + /// The entity pulled out, if found. Otherwise null. + /// If true, then remove the entity from the list. + /// The sequence of entities, optionally without one. + public static IEnumerable GetEntityByPath( + this IEnumerable input, + UPath path, + out Entity? foundEntity, + IfFoundOutput removeFromResults = IfFoundOutput.RemoveFromOutput + ) + { + List output = new(); + foundEntity = null; - foreach (Entity entity in input) - { - // If we don't have a path, it isn't it. - if (!entity.TryGet(out UPath entityPath)) - { - output.Add(entity); + foreach (Entity entity in input) + { + // If we don't have a path, it isn't it. + if (!entity.TryGet(out UPath entityPath)) + { + output.Add(entity); - continue; - } + continue; + } - // See if the path matches. If it doesn't, then return it. - if (entityPath != path) - { - output.Add(entity); + // See if the path matches. If it doesn't, then return it. + if (entityPath != path) + { + output.Add(entity); - continue; - } + continue; + } - // We found the entity, so optionally return it. - foundEntity = entity; + // We found the entity, so optionally return it. + foundEntity = entity; - if (removeFromResults == IfFoundOutput.ReturnInOutput) - { - output.Add(entity); - } - } + if (removeFromResults == IfFoundOutput.ReturnInOutput) + { + output.Add(entity); + } + } - // Return the resulting output. - return output; - } + // Return the resulting output. + return output; + } - /// - /// Filters out entities that match a .gitignore style list and returns - /// the remaining entities. - /// - public static IEnumerable WhereNotIgnored( - this IEnumerable input, - IgnoreList ignoreList) - { - foreach (Entity entity in input) - { - // If we don't have a path, nothing to do. - if (!entity.TryGet(out UPath path)) - { - yield return entity; - } + /// + /// Filters out entities that match a .gitignore style list and returns + /// the remaining entities. + /// + public static IEnumerable WhereNotIgnored( + this IEnumerable input, + IgnoreList ignoreList + ) + { + foreach (Entity entity in input) + { + // If we don't have a path, nothing to do. + if (!entity.TryGet(out UPath path)) + { + yield return entity; + } - // See if the path matches. We use the "path is directory" set to false - // because Entity represents files, not directories. - string text = path.ToString(); + // See if the path matches. We use the "path is directory" set to false + // because Entity represents files, not directories. + string text = path.ToString(); - if (!ignoreList.IsIgnored(text, false)) - { - yield return entity; - } - } - } + if (!ignoreList.IsIgnored(text, false)) + { + yield return entity; + } + } + } } diff --git a/src/MfGames.Nitride.IO/FileSystemOperationBase.cs b/src/MfGames.Nitride.IO/FileSystemOperationBase.cs index 60ef2cb..bf00ecd 100644 --- a/src/MfGames.Nitride.IO/FileSystemOperationBase.cs +++ b/src/MfGames.Nitride.IO/FileSystemOperationBase.cs @@ -1,20 +1,20 @@ using MfGames.Gallium; - using Zio; namespace MfGames.Nitride.IO; public abstract class FileSystemOperationBase : IOperation { - protected FileSystemOperationBase(IFileSystem fileSystem) - { - this.FileSystem = fileSystem; - } + protected FileSystemOperationBase(IFileSystem fileSystem) + { + this.FileSystem = fileSystem; + } - public IFileSystem FileSystem { get; set; } + public IFileSystem FileSystem { get; set; } - /// - public abstract IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default); + /// + public abstract IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ); } diff --git a/src/MfGames.Nitride.IO/FileSystemWatchablePipelineBase.cs b/src/MfGames.Nitride.IO/FileSystemWatchablePipelineBase.cs index 6aebd67..78bfb0c 100644 --- a/src/MfGames.Nitride.IO/FileSystemWatchablePipelineBase.cs +++ b/src/MfGames.Nitride.IO/FileSystemWatchablePipelineBase.cs @@ -1,7 +1,5 @@ using MfGames.Nitride.Pipelines; - using Serilog; - using Zio; namespace MfGames.Nitride.IO; @@ -10,77 +8,74 @@ namespace MfGames.Nitride.IO; /// A watchable pipeline base that has all the plumbing to handle watching /// the virtual file system. /// -public abstract class FileSystemWatchablePipelineBase - : WatchablePipelineBase, IDisposable +public abstract class FileSystemWatchablePipelineBase : WatchablePipelineBase, IDisposable { - private Action? watchAction; + private Action? watchAction; - private IFileSystemWatcher? watcher; + private IFileSystemWatcher? watcher; - protected FileSystemWatchablePipelineBase( - ILogger logger, - IFileSystem fileSystem) - { - this.Logger = logger.ForContext(this.GetType()); - this.FileSystem = fileSystem; - } + protected FileSystemWatchablePipelineBase(ILogger logger, IFileSystem fileSystem) + { + this.Logger = logger.ForContext(this.GetType()); + this.FileSystem = fileSystem; + } - /// - /// Gets the file system associated with the pipeline. - /// - protected IFileSystem FileSystem { get; } + /// + /// Gets the file system associated with the pipeline. + /// + protected IFileSystem FileSystem { get; } - /// - /// Gets the logger associated with the pipeline. - /// - protected ILogger Logger { get; } + /// + /// Gets the logger associated with the pipeline. + /// + protected ILogger Logger { get; } - /// - /// Gets the path to watch for changes. - /// - protected abstract UPath WatchPath { get; } + /// + /// Gets the path to watch for changes. + /// + protected abstract UPath WatchPath { get; } - /// - public void Dispose() - { - this.Dispose(true); - GC.SuppressFinalize(this); - } + /// + public void Dispose() + { + this.Dispose(true); + GC.SuppressFinalize(this); + } - /// - public override void Watch(Action onChange) - { - // If we already have a watcher, then unwind that one. - if (this.watcher != null && this.watchAction != null) - { - this.watcher.Created -= this.OnFileSystemChange; - this.watcher.Changed -= this.OnFileSystemChange; - this.watcher.Deleted -= this.OnFileSystemChange; - this.watcher.Renamed -= this.OnFileSystemChange; - this.watcher.Dispose(); - } + /// + public override void Watch(Action onChange) + { + // If we already have a watcher, then unwind that one. + if (this.watcher != null && this.watchAction != null) + { + this.watcher.Created -= this.OnFileSystemChange; + this.watcher.Changed -= this.OnFileSystemChange; + this.watcher.Deleted -= this.OnFileSystemChange; + this.watcher.Renamed -= this.OnFileSystemChange; + this.watcher.Dispose(); + } - // Create a new watcher and wire up various events. - this.watchAction = onChange; - this.watcher = this.FileSystem.Watch(this.WatchPath); - this.watcher.IncludeSubdirectories = true; - this.watcher.EnableRaisingEvents = true; - this.watcher.Created += this.OnFileSystemChange; - this.watcher.Changed += this.OnFileSystemChange; - this.watcher.Deleted += this.OnFileSystemChange; - this.watcher.Renamed += this.OnFileSystemChange; - } + // Create a new watcher and wire up various events. + this.watchAction = onChange; + this.watcher = this.FileSystem.Watch(this.WatchPath); + this.watcher.IncludeSubdirectories = true; + this.watcher.EnableRaisingEvents = true; + this.watcher.Created += this.OnFileSystemChange; + this.watcher.Changed += this.OnFileSystemChange; + this.watcher.Deleted += this.OnFileSystemChange; + this.watcher.Renamed += this.OnFileSystemChange; + } - protected virtual void Dispose(bool disposing) - { - if (disposing) - { - this.watcher?.Dispose(); - } - } + protected virtual void Dispose(bool disposing) + { + if (disposing) + { + this.watcher?.Dispose(); + } + } - private void OnFileSystemChange(object? sender, FileChangedEventArgs e) - { - this.watchAction?.Invoke(); - } + private void OnFileSystemChange(object? sender, FileChangedEventArgs e) + { + this.watchAction?.Invoke(); + } } diff --git a/src/MfGames.Nitride.IO/IfFoundOutput.cs b/src/MfGames.Nitride.IO/IfFoundOutput.cs index d76da08..66912fe 100644 --- a/src/MfGames.Nitride.IO/IfFoundOutput.cs +++ b/src/MfGames.Nitride.IO/IfFoundOutput.cs @@ -2,13 +2,13 @@ namespace MfGames.Nitride.IO; public enum IfFoundOutput { - /// - /// If the entity is found, then remove it from output. - /// - RemoveFromOutput, + /// + /// If the entity is found, then remove it from output. + /// + RemoveFromOutput, - /// - /// If the entity is found, then keep it in the output sequence. - /// - ReturnInOutput, + /// + /// If the entity is found, then keep it in the output sequence. + /// + ReturnInOutput, } diff --git a/src/MfGames.Nitride.IO/Paths/AddPathPrefix.cs b/src/MfGames.Nitride.IO/Paths/AddPathPrefix.cs index 1660a3d..292b5f6 100644 --- a/src/MfGames.Nitride.IO/Paths/AddPathPrefix.cs +++ b/src/MfGames.Nitride.IO/Paths/AddPathPrefix.cs @@ -1,8 +1,6 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.IO.Paths; @@ -10,41 +8,35 @@ namespace MfGames.Nitride.IO.Paths; [WithProperties] public partial class AddPathPrefix : OperationBase { - private readonly ReplacePath replacePath; + private readonly ReplacePath replacePath; - private readonly IValidator validator; + private readonly IValidator validator; - public AddPathPrefix( - IValidator validator, - ReplacePath replacePath) - { - this.validator = validator; - this.replacePath = replacePath; - } + public AddPathPrefix(IValidator validator, ReplacePath replacePath) + { + this.validator = validator; + this.replacePath = replacePath; + } - /// - /// Gets or sets the prefix for the path operations. - /// - public UPath? PathPrefix { get; set; } + /// + /// Gets or sets the prefix for the path operations. + /// + public UPath? PathPrefix { get; set; } - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return this.replacePath - .WithReplacement(this.RunReplacement) - .Run(input); - } + return this.replacePath.WithReplacement(this.RunReplacement).Run(input); + } - private UPath RunReplacement( - Entity _, - UPath path) - { - string innerRelativePath = path.ToString() - .TrimStart('/'); + private UPath RunReplacement(Entity _, UPath path) + { + string innerRelativePath = path.ToString().TrimStart('/'); - return this.PathPrefix!.Value / innerRelativePath; - } + return this.PathPrefix!.Value / innerRelativePath; + } } diff --git a/src/MfGames.Nitride.IO/Paths/AddPathPrefixValidator.cs b/src/MfGames.Nitride.IO/Paths/AddPathPrefixValidator.cs index de90e23..2f2f1cd 100644 --- a/src/MfGames.Nitride.IO/Paths/AddPathPrefixValidator.cs +++ b/src/MfGames.Nitride.IO/Paths/AddPathPrefixValidator.cs @@ -4,9 +4,8 @@ namespace MfGames.Nitride.IO.Paths; public class AddPathPrefixValidator : AbstractValidator { - public AddPathPrefixValidator() - { - this.RuleFor(x => x.PathPrefix) - .NotNull(); - } + public AddPathPrefixValidator() + { + this.RuleFor(x => x.PathPrefix).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Paths/ChangePathExtension.cs b/src/MfGames.Nitride.IO/Paths/ChangePathExtension.cs index 21ac59d..5827ec9 100644 --- a/src/MfGames.Nitride.IO/Paths/ChangePathExtension.cs +++ b/src/MfGames.Nitride.IO/Paths/ChangePathExtension.cs @@ -1,8 +1,6 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.IO.Paths; @@ -13,37 +11,33 @@ namespace MfGames.Nitride.IO.Paths; [WithProperties] public partial class ChangePathExtension : IOperation { - private readonly ReplacePath replacePath; + private readonly ReplacePath replacePath; - private readonly IValidator validator; + private readonly IValidator validator; - public ChangePathExtension( - IValidator validator, - ReplacePath replacePath) - { - this.validator = validator; - this.replacePath = replacePath; - } + public ChangePathExtension(IValidator validator, ReplacePath replacePath) + { + this.validator = validator; + this.replacePath = replacePath; + } - /// - /// Gets or sets the prefix for the path operations. - /// - public string? Extension { get; set; } + /// + /// Gets or sets the prefix for the path operations. + /// + public string? Extension { get; set; } - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return this.replacePath.WithReplacement(this.RunReplacement) - .Run(input); - } + return this.replacePath.WithReplacement(this.RunReplacement).Run(input); + } - private UPath RunReplacement( - Entity _, - UPath path) - { - return path.ChangeExtension(this.Extension!); - } + private UPath RunReplacement(Entity _, UPath path) + { + return path.ChangeExtension(this.Extension!); + } } diff --git a/src/MfGames.Nitride.IO/Paths/ChangePathExtensionValidator.cs b/src/MfGames.Nitride.IO/Paths/ChangePathExtensionValidator.cs index 75dd408..1d47877 100644 --- a/src/MfGames.Nitride.IO/Paths/ChangePathExtensionValidator.cs +++ b/src/MfGames.Nitride.IO/Paths/ChangePathExtensionValidator.cs @@ -2,12 +2,10 @@ using FluentValidation; namespace MfGames.Nitride.IO.Paths; -public class ChangePathExtensionValidator - : AbstractValidator +public class ChangePathExtensionValidator : AbstractValidator { - public ChangePathExtensionValidator() - { - this.RuleFor(x => x.Extension) - .NotNull(); - } + public ChangePathExtensionValidator() + { + this.RuleFor(x => x.Extension).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Paths/DirectChildEntityList.cs b/src/MfGames.Nitride.IO/Paths/DirectChildEntityList.cs index 3a6cd14..09ac822 100644 --- a/src/MfGames.Nitride.IO/Paths/DirectChildEntityList.cs +++ b/src/MfGames.Nitride.IO/Paths/DirectChildEntityList.cs @@ -7,14 +7,10 @@ namespace MfGames.Nitride.IO.Paths; /// public class DirectChildEntityList : List { - /// - public DirectChildEntityList() - { - } + /// + public DirectChildEntityList() { } - /// - public DirectChildEntityList(IEnumerable collection) - : base(collection) - { - } + /// + public DirectChildEntityList(IEnumerable collection) + : base(collection) { } } diff --git a/src/MfGames.Nitride.IO/Paths/DirectChildPathScanner.cs b/src/MfGames.Nitride.IO/Paths/DirectChildPathScanner.cs index 01d78d7..38d55f2 100644 --- a/src/MfGames.Nitride.IO/Paths/DirectChildPathScanner.cs +++ b/src/MfGames.Nitride.IO/Paths/DirectChildPathScanner.cs @@ -1,9 +1,7 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Entities; using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.IO.Paths; @@ -15,32 +13,32 @@ namespace MfGames.Nitride.IO.Paths; [WithProperties] public partial class DirectChildPathScanner : EntityScanner { - /// - public DirectChildPathScanner(IValidator validator) - : base(validator) - { - this.GetKeysFromEntity = this.InternalGetKeysFromEntity; - } + /// + public DirectChildPathScanner(IValidator validator) + : base(validator) + { + this.GetKeysFromEntity = this.InternalGetKeysFromEntity; + } - private IEnumerable? InternalGetKeysFromEntity(Entity entity) - { - // Get the path for the entity. If we don't have a path, then there - // is nothing to do. - if (!entity.TryGet(out UPath path)) - { - return null; - } + private IEnumerable? InternalGetKeysFromEntity(Entity entity) + { + // Get the path for the entity. If we don't have a path, then there + // is nothing to do. + if (!entity.TryGet(out UPath path)) + { + return null; + } - // If we are a root path, then we don't have a parent. - if (path.IsEmpty || path.IsNull || path == "/") - { - return null; - } + // If we are a root path, then we don't have a parent. + if (path.IsEmpty || path.IsNull || path == "/") + { + return null; + } - // If we are using directory indexes, skip when we have an index root. - // Otherwise, get the parent and use that as the key. - return path.GetDirectoryIndexPath() == "/" - ? null - : new[] { path.GetParentDirectoryIndexPath() }; - } + // If we are using directory indexes, skip when we have an index root. + // Otherwise, get the parent and use that as the key. + return path.GetDirectoryIndexPath() == "/" + ? null + : new[] { path.GetParentDirectoryIndexPath() }; + } } diff --git a/src/MfGames.Nitride.IO/Paths/LinkDirectChildren.cs b/src/MfGames.Nitride.IO/Paths/LinkDirectChildren.cs index 74d117b..3bcf5e6 100644 --- a/src/MfGames.Nitride.IO/Paths/LinkDirectChildren.cs +++ b/src/MfGames.Nitride.IO/Paths/LinkDirectChildren.cs @@ -1,11 +1,8 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Entities; using MfGames.Nitride.Generators; - using Serilog; - using Zio; namespace MfGames.Nitride.IO.Paths; @@ -13,41 +10,35 @@ namespace MfGames.Nitride.IO.Paths; [WithProperties] public partial class LinkDirectChildren : CreateOrUpdateIndex { - /// - public LinkDirectChildren( - ILogger logger, - IValidator validator) - : base(logger, validator) - { - this.UpdateIndex = this.InternalUpdateIndex; + /// + public LinkDirectChildren(ILogger logger, IValidator validator) + : base(logger, validator) + { + this.UpdateIndex = this.InternalUpdateIndex; - this.GetIndexKey = e => e.Get() - .GetDirectoryIndexPath(); - } + this.GetIndexKey = e => e.Get().GetDirectoryIndexPath(); + } - /// - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - if (this.Scanner != null!) - { - return base.Run(input); - } + /// + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + if (this.Scanner != null!) + { + return base.Run(input); + } - this.Scanner = new DirectChildPathScanner(new EntityScannerValidator()); + this.Scanner = new DirectChildPathScanner(new EntityScannerValidator()); - input = this.Scanner.Run(input) - .ToList(); + input = this.Scanner.Run(input).ToList(); - return base.Run(input); - } + return base.Run(input); + } - private Entity InternalUpdateIndex( - Entity entity, - string _, - IEnumerable list) - { - return entity.Add(new DirectChildEntityList(list)); - } + private Entity InternalUpdateIndex(Entity entity, string _, IEnumerable list) + { + return entity.Add(new DirectChildEntityList(list)); + } } diff --git a/src/MfGames.Nitride.IO/Paths/MoveToIndexPath.cs b/src/MfGames.Nitride.IO/Paths/MoveToIndexPath.cs index 186e409..58c6072 100644 --- a/src/MfGames.Nitride.IO/Paths/MoveToIndexPath.cs +++ b/src/MfGames.Nitride.IO/Paths/MoveToIndexPath.cs @@ -1,8 +1,6 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.IO.Paths; @@ -13,78 +11,74 @@ namespace MfGames.Nitride.IO.Paths; [WithProperties] public partial class MoveToIndexPath : OperationBase { - private readonly ReplacePath replacePath; + private readonly ReplacePath replacePath; - private readonly IValidator validator; + private readonly IValidator validator; - public MoveToIndexPath( - IValidator validator, - ReplacePath replacePath) - { - this.validator = validator; - this.replacePath = replacePath; - this.CanMoveCallback = DefaultCanMoveCallback; - } + public MoveToIndexPath(IValidator validator, ReplacePath replacePath) + { + this.validator = validator; + this.replacePath = replacePath; + this.CanMoveCallback = DefaultCanMoveCallback; + } - /// - /// Gets or sets the callback to determine if the file should be moved. - /// This will not be called if the file is already an index. - /// - public Func? CanMoveCallback { get; set; } + /// + /// Gets or sets the callback to determine if the file should be moved. + /// This will not be called if the file is already an index. + /// + public Func? CanMoveCallback { get; set; } - /// - /// Default implement of the operation moves .html, .htm, .md, and - /// .markdown files into their indexes. - /// - /// - /// True if the file should move, otherwise false. - public static bool DefaultCanMoveCallback(UPath path) - { - return path.GetExtensionWithDot() switch - { - ".htm" => true, - ".html" => true, - ".md" => true, - ".markdown" => true, - _ => false, - }; - } + /// + /// Default implement of the operation moves .html, .htm, .md, and + /// .markdown files into their indexes. + /// + /// + /// True if the file should move, otherwise false. + public static bool DefaultCanMoveCallback(UPath path) + { + return path.GetExtensionWithDot() switch + { + ".htm" => true, + ".html" => true, + ".md" => true, + ".markdown" => true, + _ => false, + }; + } - public override IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + public override IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return this.replacePath.WithReplacement(this.RunReplacement) - .Run(input); - } + return this.replacePath.WithReplacement(this.RunReplacement).Run(input); + } - private UPath RunReplacement( - Entity _, - UPath path) - { - // See if we are already an index. If that is true, then we don't - // have to move any further. - string? nameWithoutExtension = path.GetNameWithoutExtension(); + private UPath RunReplacement(Entity _, UPath path) + { + // See if we are already an index. If that is true, then we don't + // have to move any further. + string? nameWithoutExtension = path.GetNameWithoutExtension(); - if (nameWithoutExtension is null or "index") - { - return path; - } + if (nameWithoutExtension is null or "index") + { + return path; + } - // See if the path should be moved. If it can't, then just stop - // processing. - if (!this.CanMoveCallback!.Invoke(path)) - { - return path; - } + // See if the path should be moved. If it can't, then just stop + // processing. + if (!this.CanMoveCallback!.Invoke(path)) + { + return path; + } - // Move the file to an index. - UPath parent = path.GetDirectory(); - string? extension = path.GetExtensionWithDot(); - string index = "index" + extension; + // Move the file to an index. + UPath parent = path.GetDirectory(); + string? extension = path.GetExtensionWithDot(); + string index = "index" + extension; - return parent / nameWithoutExtension / index; - } + return parent / nameWithoutExtension / index; + } } diff --git a/src/MfGames.Nitride.IO/Paths/MoveToIndexPathValidator.cs b/src/MfGames.Nitride.IO/Paths/MoveToIndexPathValidator.cs index e5f4be4..4598537 100644 --- a/src/MfGames.Nitride.IO/Paths/MoveToIndexPathValidator.cs +++ b/src/MfGames.Nitride.IO/Paths/MoveToIndexPathValidator.cs @@ -4,9 +4,8 @@ namespace MfGames.Nitride.IO.Paths; public class MoveToIndexPathValidator : AbstractValidator { - public MoveToIndexPathValidator() - { - this.RuleFor(x => x.CanMoveCallback) - .NotNull(); - } + public MoveToIndexPathValidator() + { + this.RuleFor(x => x.CanMoveCallback).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Paths/RemovePathPrefix.cs b/src/MfGames.Nitride.IO/Paths/RemovePathPrefix.cs index 9be6b18..f1df66a 100644 --- a/src/MfGames.Nitride.IO/Paths/RemovePathPrefix.cs +++ b/src/MfGames.Nitride.IO/Paths/RemovePathPrefix.cs @@ -1,8 +1,6 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.IO.Paths; @@ -13,47 +11,41 @@ namespace MfGames.Nitride.IO.Paths; [WithProperties] public partial class RemovePathPrefix : IOperation { - private readonly ReplacePath replacePath; + private readonly ReplacePath replacePath; - private readonly IValidator validator; + private readonly IValidator validator; - public RemovePathPrefix( - IValidator validator, - ReplacePath replacePath) - { - this.validator = validator; - this.replacePath = replacePath; - } + public RemovePathPrefix(IValidator validator, ReplacePath replacePath) + { + this.validator = validator; + this.replacePath = replacePath; + } - /// - /// Gets or sets the prefix for the path operations. - /// - public UPath PathPrefix { get; set; } + /// + /// Gets or sets the prefix for the path operations. + /// + public UPath PathPrefix { get; set; } - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return this.replacePath - .WithReplacement(this.RunReplacement) - .Run(input); - } + return this.replacePath.WithReplacement(this.RunReplacement).Run(input); + } - private UPath RunReplacement( - Entity _, - UPath path) - { - string normalized = path.ToString(); - string prefix = this.PathPrefix.ToString()!; + private UPath RunReplacement(Entity _, UPath path) + { + string normalized = path.ToString(); + string prefix = this.PathPrefix.ToString()!; - if (normalized.StartsWith(prefix)) - { - return (UPath)path.ToString() - .Substring(prefix.Length); - } + if (normalized.StartsWith(prefix)) + { + return (UPath)path.ToString().Substring(prefix.Length); + } - return path; - } + return path; + } } diff --git a/src/MfGames.Nitride.IO/Paths/RemovePathPrefixValidator.cs b/src/MfGames.Nitride.IO/Paths/RemovePathPrefixValidator.cs index d0fd796..198de03 100644 --- a/src/MfGames.Nitride.IO/Paths/RemovePathPrefixValidator.cs +++ b/src/MfGames.Nitride.IO/Paths/RemovePathPrefixValidator.cs @@ -4,9 +4,8 @@ namespace MfGames.Nitride.IO.Paths; public class RemovePathPrefixValidator : AbstractValidator { - public RemovePathPrefixValidator() - { - this.RuleFor(x => x.PathPrefix) - .NotNull(); - } + public RemovePathPrefixValidator() + { + this.RuleFor(x => x.PathPrefix).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Paths/ReplacePath.cs b/src/MfGames.Nitride.IO/Paths/ReplacePath.cs index d70e65f..84ba3ec 100644 --- a/src/MfGames.Nitride.IO/Paths/ReplacePath.cs +++ b/src/MfGames.Nitride.IO/Paths/ReplacePath.cs @@ -1,8 +1,6 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.IO.Paths; @@ -15,40 +13,40 @@ namespace MfGames.Nitride.IO.Paths; [WithProperties] public partial class ReplacePath : IOperation { - private readonly IValidator validator; + private readonly IValidator validator; - public ReplacePath(IValidator validator) - { - this.validator = validator; - } + public ReplacePath(IValidator validator) + { + this.validator = validator; + } - /// - /// Gets or sets the replacement callback to alter the paths. - /// - public Func Replacement { get; set; } = null!; + /// + /// Gets or sets the replacement callback to alter the paths. + /// + public Func Replacement { get; set; } = null!; - /// - /// Performs the replacement on the input streams and outputs the - /// resulting entities. Only entities that have had their paths changed - /// will be updated, the others will be passed on as-is. - /// - /// The list of input entities. - /// - /// The output entities. - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + /// + /// Performs the replacement on the input streams and outputs the + /// resulting entities. Only entities that have had their paths changed + /// will be updated, the others will be passed on as-is. + /// + /// The list of input entities. + /// + /// The output entities. + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return input.SelectEntity( - ( - entity, - oldPath) => - { - UPath newPath = this.Replacement(entity, oldPath); + return input.SelectEntity( + (entity, oldPath) => + { + UPath newPath = this.Replacement(entity, oldPath); - return newPath != oldPath ? entity.Set(newPath) : entity; - }); - } + return newPath != oldPath ? entity.Set(newPath) : entity; + } + ); + } } diff --git a/src/MfGames.Nitride.IO/Paths/ReplacePathValidator.cs b/src/MfGames.Nitride.IO/Paths/ReplacePathValidator.cs index 1f72986..2e64b7b 100644 --- a/src/MfGames.Nitride.IO/Paths/ReplacePathValidator.cs +++ b/src/MfGames.Nitride.IO/Paths/ReplacePathValidator.cs @@ -4,9 +4,8 @@ namespace MfGames.Nitride.IO.Paths; public class ReplacePathValidator : AbstractValidator { - public ReplacePathValidator() - { - this.RuleFor(x => x.Replacement) - .NotNull(); - } + public ReplacePathValidator() + { + this.RuleFor(x => x.Replacement).NotNull(); + } } diff --git a/src/MfGames.Nitride.IO/Paths/UPathExtensions.cs b/src/MfGames.Nitride.IO/Paths/UPathExtensions.cs index b64b369..47316a3 100644 --- a/src/MfGames.Nitride.IO/Paths/UPathExtensions.cs +++ b/src/MfGames.Nitride.IO/Paths/UPathExtensions.cs @@ -7,39 +7,34 @@ namespace MfGames.Nitride.IO.Paths; /// public static class UPathExtensions { - /// - /// Gets the directory path, which excludes the directory at the end - /// of the path. - /// - /// The path to manipulate. - /// A normalized path. - public static string GetDirectoryIndexPath(this UPath path) - { - if (path.GetNameWithoutExtension() == "index") - { - return path.GetDirectory() - .ToString() - .TrimEnd('/') - + "/"; - } + /// + /// Gets the directory path, which excludes the directory at the end + /// of the path. + /// + /// The path to manipulate. + /// A normalized path. + public static string GetDirectoryIndexPath(this UPath path) + { + if (path.GetNameWithoutExtension() == "index") + { + return path.GetDirectory().ToString().TrimEnd('/') + "/"; + } - return path.ToString(); - } + return path.ToString(); + } - public static string GetParentDirectoryIndexPath(this UPath path) - { - UPath indexPath = path.GetDirectoryIndexPath(); - UPath parent = indexPath.GetDirectory(); + public static string GetParentDirectoryIndexPath(this UPath path) + { + UPath indexPath = path.GetDirectoryIndexPath(); + UPath parent = indexPath.GetDirectory(); - if (parent == null!) - { - parent = "/"; - } + if (parent == null!) + { + parent = "/"; + } - string parentPath = parent.ToString() - .TrimEnd('/') - + "/"; + string parentPath = parent.ToString().TrimEnd('/') + "/"; - return parentPath; - } + return parentPath; + } } diff --git a/src/MfGames.Nitride.IO/README.md b/src/MfGames.Nitride.IO/README.md index 2b62695..6ef044f 100644 --- a/src/MfGames.Nitride.IO/README.md +++ b/src/MfGames.Nitride.IO/README.md @@ -4,9 +4,9 @@ This assembly contains the primary system for reading and writing from the disk, along with various processes to manipulate paths. It contains three primary components: -- File System I/O -- Path Normalization -- Disk-Based Content +- File System I/O +- Path Normalization +- Disk-Based Content ## File System I/O diff --git a/src/MfGames.Nitride.IO/Setup/DefaultRootDirectoryHandling.cs b/src/MfGames.Nitride.IO/Setup/DefaultRootDirectoryHandling.cs index aa2a7f0..c067d29 100644 --- a/src/MfGames.Nitride.IO/Setup/DefaultRootDirectoryHandling.cs +++ b/src/MfGames.Nitride.IO/Setup/DefaultRootDirectoryHandling.cs @@ -2,20 +2,20 @@ namespace MfGames.Nitride.IO.Setup; public enum DefaultRootDirectoryHandling { - /// - /// Indicates that the Git root, if one is found, should be used as the - /// default Git root. - /// - GitRoot, + /// + /// Indicates that the Git root, if one is found, should be used as the + /// default Git root. + /// + GitRoot, - /// - /// Indicates than an exception should be shown if a directory is not set. - /// - ThrowError, + /// + /// Indicates than an exception should be shown if a directory is not set. + /// + ThrowError, - /// - /// Indicates that the current working directory should be used for the - /// default working directory. - /// - WorkingDirectory, + /// + /// Indicates that the current working directory should be used for the + /// default working directory. + /// + WorkingDirectory, } diff --git a/src/MfGames.Nitride.IO/Setup/DirectoryService.cs b/src/MfGames.Nitride.IO/Setup/DirectoryService.cs index b663f07..53b67a6 100644 --- a/src/MfGames.Nitride.IO/Setup/DirectoryService.cs +++ b/src/MfGames.Nitride.IO/Setup/DirectoryService.cs @@ -1,8 +1,6 @@ using MfGames.IO.Extensions; using MfGames.Nitride.Generators; - using Serilog; - using Zio; using Zio.FileSystems; @@ -15,119 +13,113 @@ namespace MfGames.Nitride.IO.Setup; [WithProperties] public partial class DirectoryService { - private readonly ILogger logger; + private readonly ILogger logger; - private IFileSystem? fileSystem; + private IFileSystem? fileSystem; - private DirectoryInfo? rootDirectory; + private DirectoryInfo? rootDirectory; - public DirectoryService( - ILogger logger, - NitrideIOConfiguration config) - { - this.logger = logger.ForContext(); - this.rootDirectory ??= config.RootDirectory; - this.fileSystem ??= config.FileSystem; - } + public DirectoryService(ILogger logger, NitrideIOConfiguration config) + { + this.logger = logger.ForContext(); + this.rootDirectory ??= config.RootDirectory; + this.fileSystem ??= config.FileSystem; + } - /// - /// Gets or sets the handling when a root directory is not provided. - /// This defaults to using the Git root as that is the most likely use for - /// most Nitride installations. - /// - public DefaultRootDirectoryHandling DefaultRootDirectoryHandling - { - get; - set; - } + /// + /// Gets or sets the handling when a root directory is not provided. + /// This defaults to using the Git root as that is the most likely use for + /// most Nitride installations. + /// + public DefaultRootDirectoryHandling DefaultRootDirectoryHandling { get; set; } - /// - /// Gets or sets the root directory - /// - public DirectoryInfo? RootDirectory - { - get => this.rootDirectory; - set - { - this.rootDirectory = value; - this.fileSystem = null; - } - } + /// + /// Gets or sets the root directory + /// + public DirectoryInfo? RootDirectory + { + get => this.rootDirectory; + set + { + this.rootDirectory = value; + this.fileSystem = null; + } + } - /// - /// Constructs the file system from the given root directory. If this is - /// not configured, then a root directory is given based on the working - /// directory or the Git root. - /// - public IFileSystem GetOrCreateFileSystem() - { - // If we already have a file system, then just return it. - if (this.fileSystem != null) - { - return this.fileSystem; - } + /// + /// Constructs the file system from the given root directory. If this is + /// not configured, then a root directory is given based on the working + /// directory or the Git root. + /// + public IFileSystem GetOrCreateFileSystem() + { + // If we already have a file system, then just return it. + if (this.fileSystem != null) + { + return this.fileSystem; + } - // If we have a root directory, then use that. Otherwise, we need to - // calculate it (and report to the user). - DirectoryInfo? directory = this.RootDirectory; + // If we have a root directory, then use that. Otherwise, we need to + // calculate it (and report to the user). + DirectoryInfo? directory = this.RootDirectory; - if (directory == null) - { - switch (this.DefaultRootDirectoryHandling) - { - case DefaultRootDirectoryHandling.GitRoot: - directory = - new DirectoryInfo(Environment.CurrentDirectory) - .FindGitRoot(); + if (directory == null) + { + switch (this.DefaultRootDirectoryHandling) + { + case DefaultRootDirectoryHandling.GitRoot: + directory = new DirectoryInfo(Environment.CurrentDirectory).FindGitRoot(); - if (directory == null) - { - throw new InvalidOperationException( - "Cannot create an IFileSystem without the RootDirectory" - + " being set on DirectoryService and a Git root directory" - + " unable to be found start at " - + Environment.CurrentDirectory - + "."); - } + if (directory == null) + { + throw new InvalidOperationException( + "Cannot create an IFileSystem without the RootDirectory" + + " being set on DirectoryService and a Git root directory" + + " unable to be found start at " + + Environment.CurrentDirectory + + "." + ); + } - this.logger.Verbose( - "Setting root directory to Git root directory: {Path}", - directory.FullName); + this.logger.Verbose( + "Setting root directory to Git root directory: {Path}", + directory.FullName + ); - break; + break; - case DefaultRootDirectoryHandling.ThrowError: - throw new InvalidOperationException( - "Cannot create an IFileSystem without the RootDirectory" - + " being set on DirectoryService or the DefaultRootDirectoryHandling" - + " property set to a value other than ThrowsError."); + case DefaultRootDirectoryHandling.ThrowError: + throw new InvalidOperationException( + "Cannot create an IFileSystem without the RootDirectory" + + " being set on DirectoryService or the DefaultRootDirectoryHandling" + + " property set to a value other than ThrowsError." + ); - case DefaultRootDirectoryHandling.WorkingDirectory: - directory = - new DirectoryInfo(Environment.CurrentDirectory); + case DefaultRootDirectoryHandling.WorkingDirectory: + directory = new DirectoryInfo(Environment.CurrentDirectory); - this.logger.Verbose( - "Setting root directory to current working directory: {Path}", - directory.FullName); + this.logger.Verbose( + "Setting root directory to current working directory: {Path}", + directory.FullName + ); - break; + break; - default: - throw new ArgumentOutOfRangeException(); - } - } + default: + throw new ArgumentOutOfRangeException(); + } + } - // At this point, the root directory is set to something, so use it. - this.logger.Debug( - "Setting root directory and filesystem to {Path}", - this.RootDirectory!.FullName); + // At this point, the root directory is set to something, so use it. + this.logger.Debug( + "Setting root directory and filesystem to {Path}", + this.RootDirectory!.FullName + ); - var rootFileSystem = new PhysicalFileSystem(); + var rootFileSystem = new PhysicalFileSystem(); - this.fileSystem = new SubFileSystem( - rootFileSystem, - this.RootDirectory.FullName); + this.fileSystem = new SubFileSystem(rootFileSystem, this.RootDirectory.FullName); - return this.fileSystem; - } + return this.fileSystem; + } } diff --git a/src/MfGames.Nitride.IO/Setup/NitrideIOBuilderExtensions.cs b/src/MfGames.Nitride.IO/Setup/NitrideIOBuilderExtensions.cs index 502df10..482f6a0 100644 --- a/src/MfGames.Nitride.IO/Setup/NitrideIOBuilderExtensions.cs +++ b/src/MfGames.Nitride.IO/Setup/NitrideIOBuilderExtensions.cs @@ -1,5 +1,4 @@ using Autofac; - using MfGames.Nitride.Commands; namespace MfGames.Nitride.IO.Setup; @@ -9,52 +8,46 @@ namespace MfGames.Nitride.IO.Setup; /// public static class NitrideIOBuilderExtensions { - private static bool loaded; + private static bool loaded; - public static NitrideBuilder UseIO( - this NitrideBuilder builder, - DirectoryInfo rootDirectory) - { - return UseIO( - builder, - x => x.RootDirectory = rootDirectory); - } + public static NitrideBuilder UseIO(this NitrideBuilder builder, DirectoryInfo rootDirectory) + { + return UseIO(builder, x => x.RootDirectory = rootDirectory); + } - public static NitrideBuilder UseIO( - this NitrideBuilder builder, - Action? configure = null) - { - // If we've already loaded, then we have a problem. - if (loaded) - { - throw new InvalidOperationException( - "Cannot use UseIO() more than once."); - } + public static NitrideBuilder UseIO( + this NitrideBuilder builder, + Action? configure = null + ) + { + // If we've already loaded, then we have a problem. + if (loaded) + { + throw new InvalidOperationException("Cannot use UseIO() more than once."); + } - loaded = true; + loaded = true; - // Get the configuration so we can set the various options. - var config = new NitrideIOConfiguration(); + // Get the configuration so we can set the various options. + var config = new NitrideIOConfiguration(); - configure?.Invoke(config); + configure?.Invoke(config); - builder.ConfigureContainer( - x => - { - // Register our module and configuration. - x.RegisterModule(); - x.RegisterInstance(config).AsSelf().SingleInstance(); + builder.ConfigureContainer(x => + { + // Register our module and configuration. + x.RegisterModule(); + x.RegisterInstance(config).AsSelf().SingleInstance(); - // Add in the CLI options. - if (config.AddDirectoryCommandLineOption) - { - x - .RegisterType() - .As() - .SingleInstance(); - } - }); + // Add in the CLI options. + if (config.AddDirectoryCommandLineOption) + { + x.RegisterType() + .As() + .SingleInstance(); + } + }); - return builder; - } + return builder; + } } diff --git a/src/MfGames.Nitride.IO/Setup/NitrideIOConfiguration.cs b/src/MfGames.Nitride.IO/Setup/NitrideIOConfiguration.cs index b62cb4c..2664c33 100644 --- a/src/MfGames.Nitride.IO/Setup/NitrideIOConfiguration.cs +++ b/src/MfGames.Nitride.IO/Setup/NitrideIOConfiguration.cs @@ -1,5 +1,4 @@ using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.IO.Setup; @@ -10,20 +9,20 @@ namespace MfGames.Nitride.IO.Setup; [WithProperties] public partial class NitrideIOConfiguration { - /// - /// Gets or sets a value indicating whether the `--directory` command line - /// option should be added to the build and watch commands. - /// - public bool AddDirectoryCommandLineOption { get; set; } + /// + /// Gets or sets a value indicating whether the `--directory` command line + /// option should be added to the build and watch commands. + /// + public bool AddDirectoryCommandLineOption { get; set; } - /// - /// Gets or sets the file system to use with the process. This is used to - /// override the filesystem entirely. - /// - public IFileSystem? FileSystem { get; set; } + /// + /// Gets or sets the file system to use with the process. This is used to + /// override the filesystem entirely. + /// + public IFileSystem? FileSystem { get; set; } - /// - /// Gets or sets the root directory to use. - /// - public DirectoryInfo? RootDirectory { get; set; } + /// + /// Gets or sets the root directory to use. + /// + public DirectoryInfo? RootDirectory { get; set; } } diff --git a/src/MfGames.Nitride.IO/Setup/NitrideIOModule.cs b/src/MfGames.Nitride.IO/Setup/NitrideIOModule.cs index 7182b28..6bc42e2 100644 --- a/src/MfGames.Nitride.IO/Setup/NitrideIOModule.cs +++ b/src/MfGames.Nitride.IO/Setup/NitrideIOModule.cs @@ -1,29 +1,25 @@ using Autofac; - using Zio; namespace MfGames.Nitride.IO.Setup; public class NitrideIOModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - // Register the directory service which is used as the source of truth - // for the file system. - builder.RegisterType().AsSelf().SingleInstance(); + /// + protected override void Load(ContainerBuilder builder) + { + // Register the directory service which is used as the source of truth + // for the file system. + builder.RegisterType().AsSelf().SingleInstance(); - // Register the IFileSystem as the one inside the directory service, - // which lets us change it from the command line as needed. - builder - .Register( - (context) => context - .Resolve() - .GetOrCreateFileSystem()) - .As(); + // Register the IFileSystem as the one inside the directory service, + // which lets us change it from the command line as needed. + builder + .Register((context) => context.Resolve().GetOrCreateFileSystem()) + .As(); - // Add in the operators and validators. - builder.RegisterOperators(this); - builder.RegisterValidators(this); - } + // Add in the operators and validators. + builder.RegisterOperators(this); + builder.RegisterValidators(this); + } } diff --git a/src/MfGames.Nitride.IO/Setup/RootDirectoryCommandLineOption.cs b/src/MfGames.Nitride.IO/Setup/RootDirectoryCommandLineOption.cs index 6340c8d..286dc64 100644 --- a/src/MfGames.Nitride.IO/Setup/RootDirectoryCommandLineOption.cs +++ b/src/MfGames.Nitride.IO/Setup/RootDirectoryCommandLineOption.cs @@ -1,8 +1,6 @@ using System.CommandLine; using System.CommandLine.Invocation; - using MfGames.Nitride.Commands; - using Serilog; namespace MfGames.Nitride.IO.Setup; @@ -13,35 +11,34 @@ namespace MfGames.Nitride.IO.Setup; /// public class RootDirectoryCommandLineOption : IPipelineCommandOption { - private readonly ILogger logger; + private readonly ILogger logger; - private readonly DirectoryService service; + private readonly DirectoryService service; - public RootDirectoryCommandLineOption( - ILogger logger, - DirectoryService service) - { - this.service = service; - this.logger = logger.ForContext(); + public RootDirectoryCommandLineOption(ILogger logger, DirectoryService service) + { + this.service = service; + this.logger = logger.ForContext(); - this.Option = new Option("--directory") - { - Description = "Sets the root directory", - ArgumentHelpName = "DIR", - }; - } + this.Option = new Option("--directory") + { + Description = "Sets the root directory", + ArgumentHelpName = "DIR", + }; + } - /// - public Option Option { get; } + /// + public Option Option { get; } - /// - public void Handle(InvocationContext context) - { - this.service.RootDirectory = (DirectoryInfo?)context.ParseResult - .GetValueForOption(this.Option); + /// + public void Handle(InvocationContext context) + { + this.service.RootDirectory = (DirectoryInfo?) + context.ParseResult.GetValueForOption(this.Option); - this.logger.Information( - "Setting root directory from arguments: {Path}", - this.service.RootDirectory); - } + this.logger.Information( + "Setting root directory from arguments: {Path}", + this.service.RootDirectory + ); + } } diff --git a/src/MfGames.Nitride.Json/IsJson.cs b/src/MfGames.Nitride.Json/IsJson.cs index 7cb432e..2ca390c 100644 --- a/src/MfGames.Nitride.Json/IsJson.cs +++ b/src/MfGames.Nitride.Json/IsJson.cs @@ -6,6 +6,4 @@ namespace MfGames.Nitride.Json; /// A marker class that indicates that the entity is JSON. /// [SingletonComponent] -public partial class IsJson -{ -} +public partial class IsJson { } diff --git a/src/MfGames.Nitride.Json/NitrideJsonBuilderExtensions.cs b/src/MfGames.Nitride.Json/NitrideJsonBuilderExtensions.cs index 79bfebe..1d3d301 100644 --- a/src/MfGames.Nitride.Json/NitrideJsonBuilderExtensions.cs +++ b/src/MfGames.Nitride.Json/NitrideJsonBuilderExtensions.cs @@ -4,21 +4,19 @@ namespace MfGames.Nitride.Json; public static class NitrideJsonBuilderExtensions { - private static bool loaded; + private static bool loaded; - public static NitrideBuilder UseJson(this NitrideBuilder builder) - { - // If we've already loaded, then we have a problem. - if (loaded) - { - throw new InvalidOperationException( - "Cannot use UseJson() more than once."); - } + public static NitrideBuilder UseJson(this NitrideBuilder builder) + { + // If we've already loaded, then we have a problem. + if (loaded) + { + throw new InvalidOperationException("Cannot use UseJson() more than once."); + } - loaded = true; + loaded = true; - // Get the configuration so we can set the various options. - return builder.ConfigureContainer( - x => x.RegisterModule()); - } + // Get the configuration so we can set the various options. + return builder.ConfigureContainer(x => x.RegisterModule()); + } } diff --git a/src/MfGames.Nitride.Json/NitrideJsonEntityExtensions.cs b/src/MfGames.Nitride.Json/NitrideJsonEntityExtensions.cs index 2032103..fc8637e 100644 --- a/src/MfGames.Nitride.Json/NitrideJsonEntityExtensions.cs +++ b/src/MfGames.Nitride.Json/NitrideJsonEntityExtensions.cs @@ -1,75 +1,76 @@ using MfGames.Gallium; using MfGames.Nitride.Contents; - using Newtonsoft.Json; namespace MfGames.Nitride.Json; public static class NitrideJsonEntityExtensions { - /// - /// Parses the entity text as a JSON file and returns the results. - /// - public static TType? GetTextContentJson( - this Entity entity, - Action configure) - { - JsonSerializerSettings settings = new(); + /// + /// Parses the entity text as a JSON file and returns the results. + /// + public static TType? GetTextContentJson( + this Entity entity, + Action configure + ) + { + JsonSerializerSettings settings = new(); - configure.Invoke(settings); + configure.Invoke(settings); - return entity.GetTextContentJson(settings); - } + return entity.GetTextContentJson(settings); + } - /// - /// Parses the entity text as a JSON file and returns the results. - /// - public static TType? GetTextContentJson( - this Entity entity, - JsonSerializerSettings? settings = null) - { - string? text = entity.GetTextContentString(); + /// + /// Parses the entity text as a JSON file and returns the results. + /// + public static TType? GetTextContentJson( + this Entity entity, + JsonSerializerSettings? settings = null + ) + { + string? text = entity.GetTextContentString(); - return text != null - ? JsonConvert.DeserializeObject(text, settings) - : default; - } + return text != null ? JsonConvert.DeserializeObject(text, settings) : default; + } - /// - /// Sets the text content to the serialized value. If this is null, then - /// the text content is removed. This uses the default serializer which - /// may be configured. - /// - /// The same entity for chaining methods. - public static Entity SetTextContentJson( - this Entity entity, - TType? value, - Action configure) - { - JsonSerializerSettings settings = new(); + /// + /// Sets the text content to the serialized value. If this is null, then + /// the text content is removed. This uses the default serializer which + /// may be configured. + /// + /// The same entity for chaining methods. + public static Entity SetTextContentJson( + this Entity entity, + TType? value, + Action configure + ) + { + JsonSerializerSettings settings = new(); - configure.Invoke(settings); + configure.Invoke(settings); - return SetTextContentJson(entity, value, settings); - } + return SetTextContentJson(entity, value, settings); + } - /// - /// Sets the text content to the serialized value using the serializer - /// provided. If the value is null, then the text content is removed. - /// - /// The same entity for chaining methods. - public static Entity SetTextContentJson( - this Entity entity, - TType? value, - JsonSerializerSettings? settings = null) - { - if (value == null) - { - return entity.Remove(); - } + /// + /// Sets the text content to the serialized value using the serializer + /// provided. If the value is null, then the text content is removed. + /// + /// The same entity for chaining methods. + public static Entity SetTextContentJson( + this Entity entity, + TType? value, + JsonSerializerSettings? settings = null + ) + { + if (value == null) + { + return entity.Remove(); + } - string json = JsonConvert.SerializeObject(value, settings); + string json = JsonConvert.SerializeObject(value, settings); - return entity.SetTextContent(json); - } + return entity.SetTextContent(json); + } } diff --git a/src/MfGames.Nitride.Json/NitrideJsonModule.cs b/src/MfGames.Nitride.Json/NitrideJsonModule.cs index f889e6b..8d4b4b2 100644 --- a/src/MfGames.Nitride.Json/NitrideJsonModule.cs +++ b/src/MfGames.Nitride.Json/NitrideJsonModule.cs @@ -4,10 +4,10 @@ namespace MfGames.Nitride.Json; public class NitrideJsonModule : Module { - /// - protected override void Load(ContainerBuilder builder) - { - builder.RegisterOperators(this); - builder.RegisterValidators(this); - } + /// + protected override void Load(ContainerBuilder builder) + { + builder.RegisterOperators(this); + builder.RegisterValidators(this); + } } diff --git a/src/MfGames.Nitride.Markdown/ConvertMarkdownToBase.cs b/src/MfGames.Nitride.Markdown/ConvertMarkdownToBase.cs index 77a8abc..cb3ea00 100644 --- a/src/MfGames.Nitride.Markdown/ConvertMarkdownToBase.cs +++ b/src/MfGames.Nitride.Markdown/ConvertMarkdownToBase.cs @@ -1,7 +1,5 @@ using FluentValidation; - using Markdig; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Generators; @@ -11,51 +9,51 @@ namespace MfGames.Nitride.Markdown; [WithProperties] public abstract partial class ConvertMarkdownToBase : IOperation { - private readonly IValidator validator; + private readonly IValidator validator; - protected ConvertMarkdownToBase(IValidator validator) - { - this.validator = validator; - } + protected ConvertMarkdownToBase(IValidator validator) + { + this.validator = validator; + } - /// - /// Gets or sets an additional callback to configure additional features - /// from the baseline Markdown. - /// - public Action? ConfigureMarkdown { get; set; } + /// + /// Gets or sets an additional callback to configure additional features + /// from the baseline Markdown. + /// + public Action? ConfigureMarkdown { get; set; } - /// - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - // Validate the inputs. - this.validator.ValidateAndThrow(this); + /// + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + // Validate the inputs. + this.validator.ValidateAndThrow(this); - // Create the Markdown pipeline used for formatting. - var builder = new MarkdownPipelineBuilder(); + // Create the Markdown pipeline used for formatting. + var builder = new MarkdownPipelineBuilder(); - this.ConfigureMarkdown?.Invoke(builder); + this.ConfigureMarkdown?.Invoke(builder); - MarkdownPipeline options = builder.Build(); + MarkdownPipeline options = builder.Build(); - // Process the Markdown files (while passing everything on). - return input.SelectEntity( - ( - entity, - _, - content) => this.Convert(entity, content, options)); - } + // Process the Markdown files (while passing everything on). + return input.SelectEntity( + (entity, _, content) => this.Convert(entity, content, options) + ); + } - /// - /// Converts the Markdown file into HTML. - /// - /// The entity to convert. - /// The content for this entity. - /// The markdown pipeline. - /// A converted entity. - protected abstract Entity Convert( - Entity entity, - ITextContent markdownContent, - MarkdownPipeline options); + /// + /// Converts the Markdown file into HTML. + /// + /// The entity to convert. + /// The content for this entity. + /// The markdown pipeline. + /// A converted entity. + protected abstract Entity Convert( + Entity entity, + ITextContent markdownContent, + MarkdownPipeline options + ); } diff --git a/src/MfGames.Nitride.Markdown/ConvertMarkdownToGemtext.cs b/src/MfGames.Nitride.Markdown/ConvertMarkdownToGemtext.cs index 1314799..b12b23e 100644 --- a/src/MfGames.Nitride.Markdown/ConvertMarkdownToGemtext.cs +++ b/src/MfGames.Nitride.Markdown/ConvertMarkdownToGemtext.cs @@ -1,7 +1,5 @@ using FluentValidation; - using Markdig; - using MfGames.Gallium; using MfGames.Markdown.Gemtext; using MfGames.Nitride.Contents; @@ -16,40 +14,38 @@ namespace MfGames.Nitride.Markdown; /// public class ConvertMarkdownToGemtext : ConvertMarkdownToBase { - public ConvertMarkdownToGemtext(IValidator validator) - : base(validator) - { - } + public ConvertMarkdownToGemtext(IValidator validator) + : base(validator) { } - /// - public override ConvertMarkdownToGemtext WithConfigureMarkdown( - Action? value) - { - base.WithConfigureMarkdown(value); + /// + public override ConvertMarkdownToGemtext WithConfigureMarkdown( + Action? value + ) + { + base.WithConfigureMarkdown(value); - return this; - } + return this; + } - /// - /// Converts the Markdown file into HTML. - /// - /// The entity to convert. - /// The content for this entity. - /// The markdown pipeline. - /// A converted entity. - protected override Entity Convert( - Entity entity, - ITextContent markdownContent, - MarkdownPipeline options) - { - string markdown = markdownContent.GetTextContentString(); - string gemtext = MarkdownGemtext.ToGemtext(markdown, options); - var content = new StringTextContent(gemtext); + /// + /// Converts the Markdown file into HTML. + /// + /// The entity to convert. + /// The content for this entity. + /// The markdown pipeline. + /// A converted entity. + protected override Entity Convert( + Entity entity, + ITextContent markdownContent, + MarkdownPipeline options + ) + { + string markdown = markdownContent.GetTextContentString(); + string gemtext = MarkdownGemtext.ToGemtext(markdown, options); + var content = new StringTextContent(gemtext); - entity = entity.SetTextContent(content) - .RemoveIsMarkdown() - .SetIsGemtext(); + entity = entity.SetTextContent(content).RemoveIsMarkdown().SetIsGemtext(); - return entity; - } + return entity; + } } diff --git a/src/MfGames.Nitride.Markdown/ConvertMarkdownToHtml.cs b/src/MfGames.Nitride.Markdown/ConvertMarkdownToHtml.cs index cb81837..5c5dd7e 100644 --- a/src/MfGames.Nitride.Markdown/ConvertMarkdownToHtml.cs +++ b/src/MfGames.Nitride.Markdown/ConvertMarkdownToHtml.cs @@ -1,7 +1,5 @@ using FluentValidation; - using Markdig; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Html; @@ -14,42 +12,40 @@ namespace MfGames.Nitride.Markdown; /// public class ConvertMarkdownToHtml : ConvertMarkdownToBase { - public ConvertMarkdownToHtml(IValidator validator) - : base(validator) - { - } + public ConvertMarkdownToHtml(IValidator validator) + : base(validator) { } - /// - public override ConvertMarkdownToHtml WithConfigureMarkdown( - Action? value) - { - base.WithConfigureMarkdown(value); + /// + public override ConvertMarkdownToHtml WithConfigureMarkdown( + Action? value + ) + { + base.WithConfigureMarkdown(value); - return this; - } + return this; + } - /// - /// Converts the Markdown file into HTML. - /// - /// The entity to convert. - /// The content for this entity. - /// The markdown pipeline. - /// A converted entity. - protected override Entity Convert( - Entity entity, - ITextContent markdownContent, - MarkdownPipeline options) - { - // Convert the entity to Html. - string markdown = markdownContent.GetTextContentString(); - string html = Markdig.Markdown.ToHtml(markdown, options); - var htmlContent = new StringTextContent(html); + /// + /// Converts the Markdown file into HTML. + /// + /// The entity to convert. + /// The content for this entity. + /// The markdown pipeline. + /// A converted entity. + protected override Entity Convert( + Entity entity, + ITextContent markdownContent, + MarkdownPipeline options + ) + { + // Convert the entity to Html. + string markdown = markdownContent.GetTextContentString(); + string html = Markdig.Markdown.ToHtml(markdown, options); + var htmlContent = new StringTextContent(html); - entity = entity.SetTextContent(htmlContent) - .Remove() - .Set(IsHtml.Instance); + entity = entity.SetTextContent(htmlContent).Remove().Set(IsHtml.Instance); - // Return the resulting entity. - return entity; - } + // Return the resulting entity. + return entity; + } } diff --git a/src/MfGames.Nitride.Markdown/IdentifyMarkdown.cs b/src/MfGames.Nitride.Markdown/IdentifyMarkdown.cs index 392bbbc..1120537 100644 --- a/src/MfGames.Nitride.Markdown/IdentifyMarkdown.cs +++ b/src/MfGames.Nitride.Markdown/IdentifyMarkdown.cs @@ -1,9 +1,7 @@ using FluentValidation; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Generators; - using Zio; namespace MfGames.Nitride.Markdown; @@ -16,61 +14,53 @@ namespace MfGames.Nitride.Markdown; [WithProperties] public partial class IdentifyMarkdown : IOperation { - private readonly IValidator validator; + private readonly IValidator validator; - public IdentifyMarkdown(IValidator validator) - { - this.validator = validator; - } + public IdentifyMarkdown(IValidator validator) + { + this.validator = validator; + } - public Func IsMarkdownTest { get; set; } = null!; + public Func IsMarkdownTest { get; set; } = null!; - /// - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - this.validator.ValidateAndThrow(this); + /// + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + this.validator.ValidateAndThrow(this); - return input - .SelectEntity(this.MarkTextEntities) - .SelectEntity(this.MarkBinaryEntities); - } + return input + .SelectEntity(this.MarkTextEntities) + .SelectEntity(this.MarkBinaryEntities); + } - private Entity MarkBinaryEntities( - Entity entity, - UPath path, - IBinaryContent binary) - { - // If we aren't a Markdown file, then there is nothing we can do about that. - if (!this.IsMarkdownTest(entity, path)) - { - return entity; - } + private Entity MarkBinaryEntities(Entity entity, UPath path, IBinaryContent binary) + { + // If we aren't a Markdown file, then there is nothing we can do about that. + if (!this.IsMarkdownTest(entity, path)) + { + return entity; + } - // Convert the file as a binary. - if (binary is ITextContentConvertable textConvertable) - { - entity = entity - .SetTextContent(textConvertable.ToTextContent()) - .SetIsMarkdown(); - } - else - { - throw new InvalidOperationException( - "Cannot convert a binary content to a text without ITextContentConvertable."); - } + // Convert the file as a binary. + if (binary is ITextContentConvertable textConvertable) + { + entity = entity.SetTextContent(textConvertable.ToTextContent()).SetIsMarkdown(); + } + else + { + throw new InvalidOperationException( + "Cannot convert a binary content to a text without ITextContentConvertable." + ); + } - return entity; - } + return entity; + } - private Entity MarkTextEntities( - Entity entity, - UPath path, - ITextContent _) - { - return this.IsMarkdownTest(entity, path) - ? entity.SetIsMarkdown() - : entity; - } + private Entity MarkTextEntities(Entity entity, UPath path, ITextContent _) + { + return this.IsMarkdownTest(entity, path) ? entity.SetIsMarkdown() : entity; + } } diff --git a/src/MfGames.Nitride.Markdown/IdentifyMarkdownFromPath.cs b/src/MfGames.Nitride.Markdown/IdentifyMarkdownFromPath.cs index d54bf62..c561650 100644 --- a/src/MfGames.Nitride.Markdown/IdentifyMarkdownFromPath.cs +++ b/src/MfGames.Nitride.Markdown/IdentifyMarkdownFromPath.cs @@ -1,29 +1,24 @@ using FluentValidation; - using MfGames.Gallium; - using Zio; namespace MfGames.Nitride.Markdown; public class IdentifyMarkdownFromPath : IdentifyMarkdown { - public IdentifyMarkdownFromPath(IValidator validator) - : base(validator) - { - this.IsMarkdownTest = DefaultIsMarkdown; - } + public IdentifyMarkdownFromPath(IValidator validator) + : base(validator) + { + this.IsMarkdownTest = DefaultIsMarkdown; + } - private static bool DefaultIsMarkdown( - Entity entity, - UPath path) - { - return (path.GetExtensionWithDot() ?? string.Empty).ToLowerInvariant() - switch - { - ".md" => true, - ".markdown" => true, - _ => false, - }; - } + private static bool DefaultIsMarkdown(Entity entity, UPath path) + { + return (path.GetExtensionWithDot() ?? string.Empty).ToLowerInvariant() switch + { + ".md" => true, + ".markdown" => true, + _ => false, + }; + } } diff --git a/src/MfGames.Nitride.Markdown/IsMarkdown.cs b/src/MfGames.Nitride.Markdown/IsMarkdown.cs index e190bba..26867c7 100644 --- a/src/MfGames.Nitride.Markdown/IsMarkdown.cs +++ b/src/MfGames.Nitride.Markdown/IsMarkdown.cs @@ -6,6 +6,4 @@ namespace MfGames.Nitride.Markdown; /// A marker class that indicates that the file is a Markdown file. /// [SingletonComponent] -public partial class IsMarkdown -{ -} +public partial class IsMarkdown { } diff --git a/src/MfGames.Nitride.Markdown/MakeSingleLinkListItems.cs b/src/MfGames.Nitride.Markdown/MakeSingleLinkListItems.cs index 726a127..6a16850 100644 --- a/src/MfGames.Nitride.Markdown/MakeSingleLinkListItems.cs +++ b/src/MfGames.Nitride.Markdown/MakeSingleLinkListItems.cs @@ -1,5 +1,4 @@ using System.Text.RegularExpressions; - using MfGames.Gallium; using MfGames.Nitride.Contents; using MfGames.Nitride.Slugs; @@ -13,88 +12,88 @@ namespace MfGames.Nitride.Markdown; /// public class MakeSingleLinkListItems : IOperation { - private readonly ISlugConverter slugs; + private readonly ISlugConverter slugs; - public MakeSingleLinkListItems(ISlugConverter slugs) - { - this.slugs = slugs; - } + public MakeSingleLinkListItems(ISlugConverter slugs) + { + this.slugs = slugs; + } - /// - public IEnumerable Run( - IEnumerable input, - CancellationToken cancellationToken = default) - { - return input - .SelectManyEntity( - x => x - .Select(this.MakeSingleLinkLists)); - } + /// + public IEnumerable Run( + IEnumerable input, + CancellationToken cancellationToken = default + ) + { + return input.SelectManyEntity(x => x.Select(this.MakeSingleLinkLists)); + } - /// - /// This turns all links that start with a link into a single link while - /// removing all trailing links within the line. This is to simplify the - /// rendering of the link on page. - /// - private Entity MakeSingleLinkLists(Entity entity) - { - string content = entity.GetTextContentString()!; + /// + /// This turns all links that start with a link into a single link while + /// removing all trailing links within the line. This is to simplify the + /// rendering of the link on page. + /// + private Entity MakeSingleLinkLists(Entity entity) + { + string content = entity.GetTextContentString()!; - string output = Regex.Replace( - content, - @"- \[\[(?