chore: switching to mfgames-project-setup-flake + reformat

This commit is contained in:
D. Moonfire 2024-03-05 23:15:03 -06:00
parent 32be8aad6e
commit 5702d4f9b8
385 changed files with 15399 additions and 17472 deletions

View file

@ -1,84 +1,88 @@
root = true
[*]
charset=utf-8
["*"]
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_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
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
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
indent_style = "space"
insert_final_newline = true
max_line_length = 80
resharper_alignment_tab_fill_style=optimal_fill
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_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_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_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_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_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=tab
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_js_wrap_chained_method_calls = "chop_if_long"
resharper_keep_blank_lines_between_declarations = 1
resharper_localizable_element_highlighting=none
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_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_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_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
@ -86,36 +90,34 @@ 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_indent_child_elements = "ZeroIndent"
resharper_xmldoc_indent_text = "ZeroIndent"
resharper_xmldoc_insert_final_newline = false
tab_width = 4
trim_trailing_whitespace = true
[*.md]
max_line_length=off
trim_trailing_whitespace=false
["*.cs"]
indent_size = 4
indent_style = "space"
tab_width = 4
[*.{appxmanifest,build,config,csproj,dbml,discomap,dtd,jsproj,lsproj,njsproj,nuspec,proj,props,resw,resx,StyleCop,targets,tasks,vbproj,xml,xsd}]
["*.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
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]
["package.json"]
indent_size = 2
indent_style=space
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"

1
.gitignore vendored
View file

@ -23,6 +23,7 @@ TestResults/
tests/artifacts/
# nixago: ignore-linked-files
/.prettierrc.json
/lefthook.yml
/.conform.yaml
/treefmt.toml

133
CODE_OF_CONDUCT.md Normal file
View file

@ -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

33
DCO.md Normal file
View file

@ -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.

View file

@ -539,7 +539,7 @@ II.2.12 <HandlesEvent />
<s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForOtherTypes/@EntryValue">UseVarWhenEvident</s:String>
<s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForSimpleTypes/@EntryValue">UseVarWhenEvident</s:String>
<s:Boolean x:Key="/Default/CodeStyle/EditorConfig/EnableStyleCopSupport/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/FileHeader/FileHeaderText/@EntryValue"></s:String>
<s:Boolean x:Key="/Default/CodeStyle/LiveTemplatesUseVar/UseVar/@EntryValue">False</s:Boolean>
@ -663,6 +663,7 @@ II.2.12 &lt;HandlesEvent /&gt;&#xD;
<s:String x:Key="/Default/Environment/PerformanceGuide/SwitchBehaviour/=VCS/@EntryIndexedValue">LIVE_MONITOR</s:String>
<s:String x:Key="/Default/Environment/PerformanceGuide/SwitchBehaviour/=VsBulb/@EntryIndexedValue">DO_NOTHING</s:String>
<s:String x:Key="/Default/Environment/PerformanceGuide/SwitchBehaviour/=XAML_0020Designer/@EntryIndexedValue">LIVE_MONITOR</s:String>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EFeature_002EServices_002ECodeCleanup_002EFileHeader_002EFileHeaderSettingsMigrate/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpAttributeForSingleLineMethodUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpFileLayoutPatternsUpgrade/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>

View file

@ -10,9 +10,8 @@ public class CopyFilesModule : Module
// 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)
builder
.RegisterAssemblyTypes(this.GetType().Assembly)
.AsSelf()
.AsImplementedInterfaces()
.SingleInstance();

View file

@ -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;
@ -31,7 +30,8 @@ public class CopyFilesPipeline : PipelineBase
ClearDirectory clearDirectory,
WriteFiles writeFiles,
RemovePathPrefix removePathPrefix,
AddPathPrefix addPathPrefix)
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
@ -46,7 +46,8 @@ public class CopyFilesPipeline : PipelineBase
/// <inheritdoc />
public override IAsyncEnumerable<Entity> RunAsync(
IEnumerable<Entity> _,
CancellationToken cancellationToken = default)
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

View file

@ -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;

View file

@ -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;
@ -24,8 +22,7 @@ public static class NitridePipelinesProgram
return await new NitrideBuilder(args, ConfigureNitride)
.UseIO(rootDir)
.ConfigureContainer(
x => x.RegisterModule<NitridePipelinesModule>())
.ConfigureContainer(x => x.RegisterModule<NitridePipelinesModule>())
.RunAsync();
}

View file

@ -2,12 +2,9 @@ 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;
@ -16,9 +13,7 @@ public class DelayPipeline1 : PipelineBase
{
private readonly ILogger logger;
public DelayPipeline1(
ILogger logger,
InputPipeline1 input1)
public DelayPipeline1(ILogger logger, InputPipeline1 input1)
{
this.logger = logger.ForContext<DelayPipeline1>();
this.AddDependency(input1);
@ -27,17 +22,14 @@ public class DelayPipeline1 : PipelineBase
/// <inheritdoc />
public override IAsyncEnumerable<Entity> RunAsync(
IEnumerable<Entity> entities,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default
)
{
entities = entities
.Select(
entity =>
entities = entities.Select(entity =>
{
Task.Delay(1000, cancellationToken).Wait(cancellationToken);
this.logger.Information(
"Delayed {Value}",
entity.Get<UPath>());
this.logger.Information("Delayed {Value}", entity.Get<UPath>());
return entity;
});

View file

@ -2,13 +2,10 @@ 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;
@ -17,14 +14,10 @@ public class InputPipeline1 : FileSystemWatchablePipelineBase
{
private readonly ReadFiles readFiles;
public InputPipeline1(
ILogger logger,
IFileSystem fileSystem,
ReadFiles readFiles)
public InputPipeline1(ILogger logger, IFileSystem fileSystem, ReadFiles readFiles)
: base(logger, fileSystem)
{
this.readFiles = readFiles
.WithPattern("/input/input1/*.txt");
this.readFiles = readFiles.WithPattern("/input/input1/*.txt");
}
/// <inheritdoc />
@ -33,18 +26,15 @@ public class InputPipeline1 : FileSystemWatchablePipelineBase
/// <inheritdoc />
public override IAsyncEnumerable<Entity> RunAsync(
IEnumerable<Entity> _,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default
)
{
IEnumerable<Entity> entities = this.readFiles
.Run()
.Select(
entity =>
IEnumerable<Entity> entities = this.readFiles.Run()
.Select(entity =>
{
Task.Delay(1000, cancellationToken).Wait(cancellationToken);
this.Logger.Information(
"Read {Value}",
entity.Get<UPath>());
this.Logger.Information("Read {Value}", entity.Get<UPath>());
return entity;
});

View file

@ -2,13 +2,10 @@ 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;
@ -19,15 +16,11 @@ public class InputPipeline2 : FileSystemWatchablePipelineBase
private readonly ReadFiles readFiles;
public InputPipeline2(
ILogger logger,
IFileSystem fileSystem,
ReadFiles readFiles)
public InputPipeline2(ILogger logger, IFileSystem fileSystem, ReadFiles readFiles)
: base(logger, fileSystem)
{
this.logger = logger.ForContext<InputPipeline2>();
this.readFiles = readFiles
.WithPattern("/input/input2/*.txt");
this.readFiles = readFiles.WithPattern("/input/input2/*.txt");
}
/// <inheritdoc />
@ -36,18 +29,15 @@ public class InputPipeline2 : FileSystemWatchablePipelineBase
/// <inheritdoc />
public override IAsyncEnumerable<Entity> RunAsync(
IEnumerable<Entity> _,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default
)
{
IEnumerable<Entity> entities = this.readFiles
.Run()
.Select(
entity =>
IEnumerable<Entity> entities = this.readFiles.Run()
.Select(entity =>
{
Task.Delay(1000, cancellationToken).Wait(cancellationToken);
this.logger.Information(
"Read {Value}",
entity.Get<UPath>());
this.logger.Information("Read {Value}", entity.Get<UPath>());
return entity;
});

View file

@ -2,12 +2,9 @@ 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;
@ -16,10 +13,7 @@ public class OutputPipeline1 : PipelineBase
{
private readonly ILogger logger;
public OutputPipeline1(
ILogger logger,
DelayPipeline1 delay1,
InputPipeline2 input2)
public OutputPipeline1(ILogger logger, DelayPipeline1 delay1, InputPipeline2 input2)
{
this.logger = logger.ForContext<OutputPipeline1>();
this.AddDependency(delay1, input2);
@ -28,17 +22,14 @@ public class OutputPipeline1 : PipelineBase
/// <inheritdoc />
public override IAsyncEnumerable<Entity> RunAsync(
IEnumerable<Entity> entities,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default
)
{
entities = entities
.Select(
entity =>
entities = entities.Select(entity =>
{
Task.Delay(1000, cancellationToken).Wait(cancellationToken);
this.logger.Information(
"Pretended to write {Value}",
entity.Get<UPath>());
this.logger.Information("Pretended to write {Value}", entity.Get<UPath>());
return entity;
});

View file

@ -2,12 +2,9 @@ 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;
@ -16,9 +13,7 @@ public class OutputPipeline2 : PipelineBase
{
private readonly ILogger logger;
public OutputPipeline2(
ILogger logger,
InputPipeline2 input2)
public OutputPipeline2(ILogger logger, InputPipeline2 input2)
{
this.logger = logger.ForContext<OutputPipeline2>();
this.AddDependency(input2);
@ -27,17 +22,14 @@ public class OutputPipeline2 : PipelineBase
/// <inheritdoc />
public override IAsyncEnumerable<Entity> RunAsync(
IEnumerable<Entity> entities,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default
)
{
entities = entities
.Select(
entity =>
entities = entities.Select(entity =>
{
Task.Delay(1000, cancellationToken).Wait(cancellationToken);
this.logger.Information(
"Pretended to write {Value}",
entity.Get<UPath>());
this.logger.Information("Pretended to write {Value}", entity.Get<UPath>());
return entity;
});

View file

@ -2,12 +2,9 @@ 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;
@ -21,20 +18,14 @@ public class ConfigCommand : Command, ICommandHandler, ITopCommand
private readonly Option<string> setOption;
/// <inheritdoc />
public ConfigCommand(
ILoggerFactory loggerFactory,
ConfigToolService service)
: base(
"config",
"Sets and displays the configuration settings")
public ConfigCommand(ILoggerFactory loggerFactory, ConfigToolService service)
: base("config", "Sets and displays the configuration settings")
{
this.logger = loggerFactory.CreateLogger<ConfigCommand>();
this.service = service;
this.Handler = this;
this.setOption = new Option<string>(
"--set",
"Sets the text value in the setting");
this.setOption = new Option<string>("--set", "Sets the text value in the setting");
this.AddOption(this.setOption);
}
@ -59,8 +50,7 @@ public class ConfigCommand : Command, ICommandHandler, ITopCommand
}
// If we have a set command, then provide it.
string value = context.ParseResult
.GetValueForOption(this.setOption);
string value = context.ParseResult.GetValueForOption(this.setOption);
if (value != null)
{
@ -71,8 +61,7 @@ public class ConfigCommand : Command, ICommandHandler, ITopCommand
settings.TimesRead++;
// Report the values.
Console.WriteLine(
JsonConvert.SerializeObject(settings, Formatting.Indented));
Console.WriteLine(JsonConvert.SerializeObject(settings, Formatting.Indented));
// Write out the settings.
this.service.WriteDefaultConfigFile(settings);

View file

@ -2,7 +2,6 @@ using System;
using System.CommandLine;
using System.CommandLine.Invocation;
using System.Threading.Tasks;
using MfGames.ToolBuilder;
namespace SampleTool.Commands;
@ -34,8 +33,7 @@ public class CrashCommand : Command, ICommandHandler, ITopCommand
if (messy)
{
throw new Exception(
"This command crashed messily as requested.");
throw new Exception("This command crashed messily as requested.");
}
throw new ToolException("This command crashed as requested.");

View file

@ -1,11 +1,8 @@
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;
@ -19,12 +16,8 @@ public class LogCommand : Command, ICommandHandler, ITopCommand
private readonly ILogger serilogLogger;
/// <inheritdoc />
public LogCommand(
ILoggerFactory loggerFactory,
ILogger serilogLogger)
: base(
"log",
"Shows various logging messages using Serilog and Microsoft")
public LogCommand(ILoggerFactory loggerFactory, ILogger serilogLogger)
: base("log", "Shows various logging messages using Serilog and Microsoft")
{
this.serilogLogger = serilogLogger;
this.serilogContextLogger = serilogLogger.ForContext<LogCommand>();
@ -50,22 +43,15 @@ public class LogCommand : Command, ICommandHandler, ITopCommand
this.serilogLogger.Fatal("Serilog Fatal()");
// Show serilog with context.
this.serilogContextLogger.Information(
"Serilog Information() 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");
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
@ -78,18 +64,19 @@ public class LogCommand : Command, ICommandHandler, ITopCommand
this.serilogLogger.Information(
"Serilog Contextual parameters {Name} and {Quotes:l}",
"extension logger",
"without quotes");
this.serilogLogger.Information(
"Serilog Contextual nested object {@Nested}",
hash);
"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");
"without quotes"
);
this.extensionLogger.LogInformation(
"System.Extension.Logging nested object {@Nested}",
hash);
hash
);
// We're good.
return Task.FromResult(0);

View file

@ -11,11 +11,8 @@ 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;
@ -48,10 +45,10 @@ public class SpectreCommand : Command, ICommandHandler, ITopCommand
CancellationToken cancellationToken = context.GetCancellationToken();
DateTime last = DateTime.UtcNow;
await AnsiConsole.Progress()
await AnsiConsole
.Progress()
.AutoClear(true)
.StartAsync(
async ctx =>
.StartAsync(async ctx =>
{
ProgressTask task1 = ctx.AddTask("[green]Fast Task[/]");
ProgressTask task2 = ctx.AddTask("[green]Slow Task[/]");
@ -67,8 +64,7 @@ public class SpectreCommand : Command, ICommandHandler, ITopCommand
// Simulate some work
await Task.Delay(25, cancellationToken);
if (DateTime.UtcNow - last
> TimeSpan.FromMilliseconds(500))
if (DateTime.UtcNow - last > TimeSpan.FromMilliseconds(500))
{
this.logger.LogWarning("Working...");
last = DateTime.UtcNow;

View file

@ -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;
@ -28,11 +27,8 @@ public class TableCommand : Command, ICommandHandler, ITopCommand
// Create the table service for formatting and displaying results.
this.tableService = tableService(
this.table,
new List<string>
{
"DefaultString",
"DefaultInt32",
})
new List<string> { "DefaultString", "DefaultInt32", }
)
.Attach(this);
// This class handles the command.

View file

@ -1,7 +1,5 @@
using System.Threading.Tasks;
using Autofac;
using MfGames.ToolBuilder;
using MfGames.ToolBuilder.Config;
using MfGames.ToolBuilder.Tables;

View file

@ -2,9 +2,7 @@ using System;
using System.Collections.Generic;
using System.CommandLine;
using System.Linq;
using Autofac;
using MfGames.ToolBuilder;
namespace SampleTool;
@ -17,32 +15,26 @@ public class SampleToolModule : Module
/// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{
builder
.RegisterAssemblyTypes(this.GetType().Assembly)
.AsSelf()
.AsImplementedInterfaces();
builder.RegisterAssemblyTypes(this.GetType().Assembly).AsSelf().AsImplementedInterfaces();
builder
.Register(
c =>
.Register(c =>
{
// Create the top-level command.
var root = new RootCommand
{
Name = "sample-tool",
Description =
"A sample tool that demonstrates functionality",
Description = "A sample tool that demonstrates functionality",
};
// Add in the top-level commands.
var commandList = c.Resolve<IList<ITopCommand>>()
.Cast<Command>()
.ToList();
var commandList = c.Resolve<IList<ITopCommand>>().Cast<Command>().ToList();
if (commandList.Count == 0)
{
throw new InvalidOperationException(
"Cannot create a tool without at least one command extending System.CommandLine.Command");
"Cannot create a tool without at least one command extending System.CommandLine.Command"
);
}
foreach (Command command in commandList)

View file

@ -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"
}
}
},

View file

@ -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);
};
}

View file

@ -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
#'';
};
}

View file

@ -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;
}

View file

@ -15,7 +15,8 @@ public static class CryptoByteArrayExtensions
/// <returns></returns>
public static string? ToByteString(
this byte[]? input,
ByteStringFormat format = ByteStringFormat.LowercaseHex)
ByteStringFormat format = ByteStringFormat.LowercaseHex
)
{
if (input == null)
{
@ -34,10 +35,7 @@ public static class CryptoByteArrayExtensions
return Convert.ToBase64String(input);
default:
throw new ArgumentOutOfRangeException(
nameof(format),
format,
null);
throw new ArgumentOutOfRangeException(nameof(format), format, null);
}
}
@ -47,13 +45,9 @@ public static class CryptoByteArrayExtensions
/// <param name="input">A byte array or null.</param>
/// <param name="hash">The type of hash requested.</param>
/// <returns>Null if input is null, otherwise the hash value.</returns>
public static byte[]? ToHashBytes(
this byte[]? input,
HashType hash = HashType.Sha512)
public static byte[]? ToHashBytes(this byte[]? input, HashType hash = HashType.Sha512)
{
return input == null
? null
: hash.CreateHash().ComputeHash(input);
return input == null ? null : hash.CreateHash().ComputeHash(input);
}
/// <summary>
@ -66,7 +60,8 @@ public static class CryptoByteArrayExtensions
public static string? ToHashString(
this byte[]? input,
HashType hash = HashType.Sha512,
ByteStringFormat format = ByteStringFormat.LowercaseHex)
ByteStringFormat format = ByteStringFormat.LowercaseHex
)
{
return input?.ToHashBytes(hash)?.ToByteString(format);
}

View file

@ -1,5 +1,4 @@
using System.Text;
using MfGames.Crypto.Hashes;
namespace MfGames.Crypto.Extensions;
@ -15,15 +14,11 @@ public static class CryptoStringExtensions
/// <param name="input">The input string or null.</param>
/// <param name="encoding">The encoding to use, defaults to UTF-8.</param>
/// <returns>Null if the input was null, otherwise the byte array.</returns>
public static byte[]? ToBytes(
this string? input,
Encoding? encoding = null)
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);
}
/// <summary>
@ -36,11 +31,10 @@ public static class CryptoStringExtensions
public static byte[]? ToHashBytes(
this string? input,
HashType hash = HashType.Sha512,
Encoding? encoding = null)
Encoding? encoding = null
)
{
return input == null
? null
: hash.CreateHash().ComputeHash(input.ToBytes(encoding)!);
return input == null ? null : hash.CreateHash().ComputeHash(input.ToBytes(encoding)!);
}
/// <summary>
@ -55,7 +49,8 @@ public static class CryptoStringExtensions
this string? input,
HashType hash = HashType.Sha512,
ByteStringFormat format = ByteStringFormat.LowercaseHex,
Encoding? encoding = null)
Encoding? encoding = null
)
{
return input?.ToHashBytes(hash, encoding)?.ToByteString(format);
}

View file

@ -8,9 +8,7 @@ namespace MfGames.Gallium;
public record Entity
{
public Entity()
: this(Interlocked.Increment(ref nextId))
{
}
: this(Interlocked.Increment(ref nextId)) { }
private Entity(int id)
{
@ -137,9 +135,7 @@ public record Entity
/// <param name="t1">The component type.</param>
/// <param name="t2">The component type.</param>
/// <returns>True if the type exists, otherwise false.</returns>
public bool HasAll(
Type t1,
Type t2)
public bool HasAll(Type t1, Type t2)
{
return this.Has(t1) && this.Components.ContainsKey(t2);
}
@ -152,10 +148,7 @@ public record Entity
/// <param name="t2">The component type.</param>
/// <param name="t3">The component type.</param>
/// <returns>True if the type exists, otherwise false.</returns>
public bool HasAll(
Type t1,
Type t2,
Type t3)
public bool HasAll(Type t1, Type t2, Type t3)
{
return this.HasAll(t1, t2) && this.Components.ContainsKey(t3);
}
@ -169,11 +162,7 @@ public record Entity
/// <param name="t3">The component type.</param>
/// <param name="t4">The component type.</param>
/// <returns>True if the type exists, otherwise false.</returns>
public bool HasAll(
Type t1,
Type t2,
Type t3,
Type t4)
public bool HasAll(Type t1, Type t2, Type t3, Type t4)
{
return this.HasAll(t1, t2, t3) && this.Components.ContainsKey(t4);
}
@ -248,9 +237,7 @@ public record Entity
/// <typeparam name="T1">The first component type.</typeparam>
/// <typeparam name="T2">The second component type.</typeparam>
/// <returns>True if found, otherwise false.</returns>
public bool TryGet<T1, T2>(
out T1 value1,
out T2 value2)
public bool TryGet<T1, T2>(out T1 value1, out T2 value2)
{
if (this.HasAll<T1, T2>())
{
@ -278,10 +265,7 @@ public record Entity
/// <typeparam name="T2">The second component type.</typeparam>
/// <typeparam name="T3">The third component type.</typeparam>
/// <returns>True if found, otherwise false.</returns>
public bool TryGet<T1, T2, T3>(
out T1 value1,
out T2 value2,
out T3 value3)
public bool TryGet<T1, T2, T3>(out T1 value1, out T2 value2, out T3 value3)
{
if (this.HasAll<T1, T2, T3>())
{
@ -313,11 +297,7 @@ public record Entity
/// <typeparam name="T3">The third component type.</typeparam>
/// <typeparam name="T4">The fourth component type.</typeparam>
/// <returns>True if found, otherwise false.</returns>
public bool TryGet<T1, T2, T3, T4>(
out T1 value1,
out T2 value2,
out T3 value3,
out T4 value4)
public bool TryGet<T1, T2, T3, T4>(out T1 value1, out T2 value2, out T3 value3, out T4 value4)
{
if (this.HasAll<T1, T2, T3, T4>())
{
@ -352,9 +332,11 @@ public record Entity
throw new ArgumentNullException(nameof(component));
}
if (this.Components.TryGetValue(typeof(T1), out object? value)
if (
this.Components.TryGetValue(typeof(T1), out object? value)
&& value is T1
&& value.Equals(component))
&& value.Equals(component)
)
{
return this;
}
@ -421,15 +403,16 @@ public record Entity
if (this.Has<T1>())
{
throw new ArgumentException(
"An element with the same type ("
+ typeof(T1).FullName
+ ") already exists.",
nameof(component));
"An element with the same type (" + typeof(T1).FullName + ") already exists.",
nameof(component)
);
}
if (this.Components.TryGetValue(typeof(T1), out object? value)
if (
this.Components.TryGetValue(typeof(T1), out object? value)
&& value is T1
&& value.Equals(component))
&& value.Equals(component)
)
{
return this;
}
@ -497,10 +480,7 @@ public record Entity
/// <returns></returns>
public Entity Copy()
{
return this with
{
Id = Interlocked.Increment(ref nextId)
};
return this with { Id = Interlocked.Increment(ref nextId) };
}
/// <summary>

View file

@ -17,7 +17,8 @@ public static class JoinEntityExtensions
public static IEnumerable<Entity> JoinEntity(
this IEnumerable<Entity> input,
ICollection<Entity> other,
Func<Entity, Entity, Entity> merge)
Func<Entity, Entity, Entity> merge
)
{
return input.Join(other, a => a.Id, a => a.Id, merge);
}

View file

@ -13,8 +13,7 @@ public static class SelectComponentExtensions
/// <param name="entities">The entities to process.</param>
/// <typeparam name="T1">The component type being searched.</typeparam>
/// <returns>A sequence of T1.</returns>
public static IEnumerable<T1> SelectComponent<T1>(
this IEnumerable<Entity> entities)
public static IEnumerable<T1> SelectComponent<T1>(this IEnumerable<Entity> entities)
{
foreach (Entity entity in entities)
{
@ -32,9 +31,7 @@ public static class SelectComponentExtensions
/// <param name="entities">The entities to process.</param>
/// <param name="t1">The component type being searched.</param>
/// <returns>A sequence of T1.</returns>
public static IEnumerable<object> SelectComponent(
IEnumerable<Entity> entities,
Type t1)
public static IEnumerable<object> SelectComponent(IEnumerable<Entity> entities, Type t1)
{
foreach (Entity entity in entities)
{

View file

@ -12,9 +12,7 @@ public static class SelectComponentOrDefaultExtensions
/// <param name="entities">The entities to process.</param>
/// <param name="t1">The component type being searched.</param>
/// <returns>A sequence of T1 or nulls.</returns>
public static IEnumerable<object?> SelectComponent(
IEnumerable<Entity> entities,
Type t1)
public static IEnumerable<object?> SelectComponent(IEnumerable<Entity> entities, Type t1)
{
foreach (Entity entity in entities)
{
@ -34,8 +32,7 @@ public static class SelectComponentOrDefaultExtensions
/// <param name="entities">The entities to process.</param>
/// <typeparam name="T1">The component type being searched.</typeparam>
/// <returns>A sequence of T1.</returns>
public static IEnumerable<T1?> SelectComponentOrDefault<T1>(
this IEnumerable<Entity> entities)
public static IEnumerable<T1?> SelectComponentOrDefault<T1>(this IEnumerable<Entity> entities)
{
foreach (Entity entity in entities)
{

View file

@ -21,11 +21,13 @@ public static class SelectEntityExtensions
public static IEnumerable<Entity> SelectEntity<T1>(
this IEnumerable<Entity> entities,
Func<Entity, T1, Entity?> selectWithComponents,
bool includeEntitiesWithoutComponents = true)
bool includeEntitiesWithoutComponents = true
)
{
return entities.SelectEntity(
selectWithComponents,
includeEntitiesWithoutComponents ? a => a : a => null);
includeEntitiesWithoutComponents ? a => a : a => null
);
}
/// <summary>
@ -48,11 +50,13 @@ public static class SelectEntityExtensions
public static IEnumerable<Entity> SelectEntity<T1, T2>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, Entity?> selectWithComponents,
bool includeEntitiesWithoutComponents = true)
bool includeEntitiesWithoutComponents = true
)
{
return entities.SelectEntity(
selectWithComponents,
includeEntitiesWithoutComponents ? a => a : a => null);
includeEntitiesWithoutComponents ? a => a : a => null
);
}
/// <summary>
@ -76,11 +80,13 @@ public static class SelectEntityExtensions
public static IEnumerable<Entity> SelectEntity<T1, T2, T3>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, T3, Entity?> selectWithComponents,
bool includeEntitiesWithoutComponents = true)
bool includeEntitiesWithoutComponents = true
)
{
return entities.SelectEntity(
selectWithComponents,
includeEntitiesWithoutComponents ? a => a : a => null);
includeEntitiesWithoutComponents ? a => a : a => null
);
}
/// <summary>
@ -105,11 +111,13 @@ public static class SelectEntityExtensions
public static IEnumerable<Entity> SelectEntity<T1, T2, T3, T4>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, T3, T4, Entity?> selectWithComponents,
bool includeEntitiesWithoutComponents = true)
bool includeEntitiesWithoutComponents = true
)
{
return entities.SelectEntity(
selectWithComponents,
includeEntitiesWithoutComponents ? a => a : a => null);
includeEntitiesWithoutComponents ? a => a : a => null
);
}
/// <summary>
@ -132,7 +140,8 @@ public static class SelectEntityExtensions
public static IEnumerable<Entity> SelectEntity<T1>(
this IEnumerable<Entity> entities,
Func<Entity, T1, Entity?> selectWithComponents,
Func<Entity, Entity?> selectWithoutComponents)
Func<Entity, Entity?> selectWithoutComponents
)
{
foreach (Entity entity in entities)
{
@ -168,12 +177,13 @@ public static class SelectEntityExtensions
public static IEnumerable<Entity> SelectEntity<T1, T2>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, Entity?> selectWithComponents,
Func<Entity, Entity?> selectWithoutComponents)
Func<Entity, Entity?> selectWithoutComponents
)
{
foreach (Entity entity in entities)
{
Entity? result = entity.TryGet(out T1 value1)
&& entity.TryGet(out T2 value2)
Entity? result =
entity.TryGet(out T1 value1) && entity.TryGet(out T2 value2)
? selectWithComponents?.Invoke(entity, value1, value2)
: selectWithoutComponents?.Invoke(entity);
@ -206,7 +216,8 @@ public static class SelectEntityExtensions
public static IEnumerable<Entity> SelectEntity<T1, T2, T3>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, T3, Entity?> selectWithComponents,
Func<Entity, Entity?> selectWithoutComponents)
Func<Entity, Entity?> selectWithoutComponents
)
{
foreach (Entity entity in entities)
{
@ -214,11 +225,7 @@ public static class SelectEntityExtensions
entity.TryGet(out T1 value1)
&& entity.TryGet(out T2 value2)
&& entity.TryGet(out T3 value3)
? selectWithComponents?.Invoke(
entity,
value1,
value2,
value3)
? selectWithComponents?.Invoke(entity, value1, value2, value3)
: selectWithoutComponents?.Invoke(entity);
if (result != null)
@ -251,7 +258,8 @@ public static class SelectEntityExtensions
public static IEnumerable<Entity> SelectEntity<T1, T2, T3, T4>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, T3, T4, Entity?> selectWithComponents,
Func<Entity, Entity?> selectWithoutComponents)
Func<Entity, Entity?> selectWithoutComponents
)
{
foreach (Entity entity in entities)
{
@ -260,12 +268,7 @@ public static class SelectEntityExtensions
&& entity.TryGet(out T2 value2)
&& entity.TryGet(out T3 value3)
&& entity.TryGet(out T4 value4)
? selectWithComponents?.Invoke(
entity,
value1,
value2,
value3,
value4)
? selectWithComponents?.Invoke(entity, value1, value2, value3, value4)
: selectWithoutComponents?.Invoke(entity);
if (result != null)

View file

@ -29,7 +29,8 @@ public static class SelectManyEntityExtensions
public static IEnumerable<Entity> SelectManyEntity<T1>(
this IEnumerable<Entity> entities,
Func<IEnumerable<Entity>, IEnumerable<Entity>> selectMany,
bool includeEntitiesWithoutComponents = true)
bool includeEntitiesWithoutComponents = true
)
{
SplitEntityEnumerations split = entities.SplitEntity<T1>();
IEnumerable<Entity> results = selectMany(split.HasAll);
@ -63,7 +64,8 @@ public static class SelectManyEntityExtensions
public static IEnumerable<Entity> SelectManyEntity<T1, T2>(
this IEnumerable<Entity> entities,
Func<IEnumerable<Entity>, IEnumerable<Entity>> selectMany,
bool includeEntitiesWithoutComponents = true)
bool includeEntitiesWithoutComponents = true
)
{
SplitEntityEnumerations split = entities.SplitEntity<T1, T2>();
IEnumerable<Entity> results = selectMany(split.HasAll);
@ -98,7 +100,8 @@ public static class SelectManyEntityExtensions
public static IEnumerable<Entity> SelectManyEntity<T1, T2, T3>(
this IEnumerable<Entity> entities,
Func<IEnumerable<Entity>, IEnumerable<Entity>> selectMany,
bool includeEntitiesWithoutComponents = true)
bool includeEntitiesWithoutComponents = true
)
{
SplitEntityEnumerations split = entities.SplitEntity<T1, T2, T3>();
IEnumerable<Entity> results = selectMany(split.HasAll);
@ -134,7 +137,8 @@ public static class SelectManyEntityExtensions
public static IEnumerable<Entity> SelectManyEntity<T1, T2, T3, T4>(
this IEnumerable<Entity> entities,
Func<IEnumerable<Entity>, IEnumerable<Entity>> selectMany,
bool includeEntitiesWithoutComponents = true)
bool includeEntitiesWithoutComponents = true
)
{
SplitEntityEnumerations split = entities.SplitEntity<T1, T2, T3, T4>();
IEnumerable<Entity> results = selectMany(split.HasAll);

View file

@ -1,8 +1,6 @@
namespace MfGames.Gallium;
public record SplitEntityEnumerations(
IEnumerable<Entity> HasAll,
IEnumerable<Entity> NotHasAll)
public record SplitEntityEnumerations(IEnumerable<Entity> HasAll, IEnumerable<Entity> NotHasAll)
{
/// <summary>
/// Gets a sequence of all entities that have all the given components.

View file

@ -23,20 +23,14 @@ public static class SplitEntityExtensions
/// list.
/// </typeparam>
/// <returns>A pair of enumerations, ones with the components and ones without.</returns>
public static SplitEntityEnumerations SplitEntity
<T1>(
public static SplitEntityEnumerations SplitEntity<T1>(
this IEnumerable<Entity> entities,
Func<Entity, T1, bool>? test = null)
Func<Entity, T1, bool>? test = null
)
{
test ??= (
e,
v1) => true;
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));
}
/// <summary>
@ -57,23 +51,14 @@ public static class SplitEntityExtensions
/// A component to require to be in included in the first list.
/// </typeparam>
/// <returns>A pair of enumerations, ones with the components and ones without.</returns>
public static SplitEntityEnumerations SplitEntity
<T1, T2>(
public static SplitEntityEnumerations SplitEntity<T1, T2>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, bool>? test = null)
Func<Entity, T1, T2, bool>? test = null
)
{
test ??= (
e,
v1,
v2) => true;
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));
}
/// <summary>
@ -97,26 +82,19 @@ public static class SplitEntityExtensions
/// A component to require to be in included in the first list.
/// </typeparam>
/// <returns>A pair of enumerations, ones with the components and ones without.</returns>
public static SplitEntityEnumerations SplitEntity
<T1, T2, T3>(
public static SplitEntityEnumerations SplitEntity<T1, T2, T3>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, T3, bool>? test = null)
Func<Entity, T1, T2, T3, bool>? test = null
)
{
test ??= (
e,
v1,
v2,
v3) => true;
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));
(e, v1, v2, v3) => test(e, (T1)v1, (T2)v2, (T3)v3)
);
}
/// <summary>
@ -143,29 +121,20 @@ public static class SplitEntityExtensions
/// A component to require to be in included in the first list.
/// </typeparam>
/// <returns>A pair of enumerations, ones with the components and ones without.</returns>
public static SplitEntityEnumerations SplitEntity
<T1, T2, T3, T4>(
public static SplitEntityEnumerations SplitEntity<T1, T2, T3, T4>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, T3, T4, bool>? test = null)
Func<Entity, T1, T2, T3, T4, bool>? test = null
)
{
test ??= (
e,
v1,
v2,
v3,
v4) => true;
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));
(e, v1, v2, v3, v4) => test(e, (T1)v1, (T2)v2, (T3)v3, (T4)v4)
);
}
/// <summary>
@ -183,11 +152,10 @@ public static class SplitEntityExtensions
public static SplitEntityEnumerations SplitEntity(
this IEnumerable<Entity> entities,
Type t1,
Func<Entity, object, bool> test)
Func<Entity, object, bool> test
)
{
return SplitEntity(
entities,
a => a.Has(t1) && test(a, a.Get<object>(t1)));
return SplitEntity(entities, a => a.Has(t1) && test(a, a.Get<object>(t1)));
}
/// <summary>
@ -207,7 +175,8 @@ public static class SplitEntityExtensions
this IEnumerable<Entity> entities,
Type t1,
Type t2,
Func<Entity, object, object, bool> test)
Func<Entity, object, object, bool> test
)
{
return SplitEntity(entities, a => a.HasAll(t1, t2));
}
@ -231,7 +200,8 @@ public static class SplitEntityExtensions
Type t1,
Type t2,
Type t3,
Func<Entity, object, object, object, bool> test)
Func<Entity, object, object, object, bool> test
)
{
return SplitEntity(entities, a => a.HasAll(t1, t2, t3));
}
@ -257,39 +227,38 @@ public static class SplitEntityExtensions
Type t2,
Type t3,
Type t4,
Func<Entity, object, object, object, object, bool> test)
Func<Entity, object, object, object, object, bool> test
)
{
return SplitEntity(
entities,
a => a.HasAll(t1, t2, t3, t4)
a =>
a.HasAll(t1, t2, t3, t4)
&& test(
a,
a.Get<object>(t1),
a.Get<object>(t2),
a.Get<object>(t3),
a.Get<object>(t4)));
a.Get<object>(t4)
)
);
}
private static SplitEntityEnumerations SplitEntity(
IEnumerable<Entity> entities,
Func<Entity, bool> keySelector)
Func<Entity, bool> keySelector
)
{
if (entities == null)
{
throw new ArgumentNullException(nameof(entities));
}
IEnumerable<IGrouping<bool, Entity>> group = entities
.GroupBy(keySelector, a => a)
.ToList();
IEnumerable<IGrouping<bool, Entity>> group = entities.GroupBy(keySelector, a => a).ToList();
IEnumerable<Entity>? has = group
.Where(a => a.Key)
.SelectMany(a => a);
IEnumerable<Entity>? has = group.Where(a => a.Key).SelectMany(a => a);
IEnumerable<Entity>? hasNot = group
.Where(a => !a.Key)
.SelectMany(a => a);
IEnumerable<Entity>? hasNot = group.Where(a => !a.Key).SelectMany(a => a);
return new SplitEntityEnumerations(has, hasNot);
}

View file

@ -4,40 +4,38 @@ public static class WhereEntityExtensions
{
public static IEnumerable<Entity> WhereEntity<T1>(
this IEnumerable<Entity> entities,
Func<Entity, T1, bool> include)
Func<Entity, T1, bool> include
)
{
return entities.Where(x => x.Has<T1>() && include(x, x.Get<T1>()));
}
public static IEnumerable<Entity> WhereEntity<T1, T2>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, bool> include)
Func<Entity, T1, T2, bool> include
)
{
return entities.Where(
x => x.HasAll<T1, T2>()
&& include(x, x.Get<T1>(), x.Get<T2>()));
return entities.Where(x => x.HasAll<T1, T2>() && include(x, x.Get<T1>(), x.Get<T2>()));
}
public static IEnumerable<Entity> WhereEntity<T1, T2, T3>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, T3, bool> include)
Func<Entity, T1, T2, T3, bool> include
)
{
return entities.Where(
x => x.HasAll<T1, T2, T3>()
&& include(x, x.Get<T1>(), x.Get<T2>(), x.Get<T3>()));
return entities.Where(x =>
x.HasAll<T1, T2, T3>() && include(x, x.Get<T1>(), x.Get<T2>(), x.Get<T3>())
);
}
public static IEnumerable<Entity> WhereEntity<T1, T2, T3, T4>(
this IEnumerable<Entity> entities,
Func<Entity, T1, T2, T3, T4, bool> include)
Func<Entity, T1, T2, T3, T4, bool> include
)
{
return entities.Where(
x => x.HasAll<T1, T2, T3, T4>()
&& include(
x,
x.Get<T1>(),
x.Get<T2>(),
x.Get<T3>(),
x.Get<T4>()));
return entities.Where(x =>
x.HasAll<T1, T2, T3, T4>()
&& include(x, x.Get<T1>(), x.Get<T2>(), x.Get<T3>(), x.Get<T4>())
);
}
}

View file

@ -2,26 +2,26 @@ namespace MfGames.Gallium;
public static class WhereEntityHasExtensions
{
public static IEnumerable<Entity> WhereEntityHas<T1>(
this IEnumerable<Entity> entities)
public static IEnumerable<Entity> WhereEntityHas<T1>(this IEnumerable<Entity> entities)
{
return entities.Where(x => x.Has<T1>());
}
public static IEnumerable<Entity> WhereEntityHasAll
<T1, T2>(this IEnumerable<Entity> entities)
public static IEnumerable<Entity> WhereEntityHasAll<T1, T2>(this IEnumerable<Entity> entities)
{
return entities.Where(x => x.HasAll<T1, T2>());
}
public static IEnumerable<Entity> WhereEntityHasAll
<T1, T2, T3>(this IEnumerable<Entity> entities)
public static IEnumerable<Entity> WhereEntityHasAll<T1, T2, T3>(
this IEnumerable<Entity> entities
)
{
return entities.Where(x => x.HasAll<T1, T2, T3>());
}
public static IEnumerable<Entity> WhereEntityHasAll
<T1, T2, T3, T4>(this IEnumerable<Entity> entities)
public static IEnumerable<Entity> WhereEntityHasAll<T1, T2, T3, T4>(
this IEnumerable<Entity> entities
)
{
return entities.Where(x => x.HasAll<T1, T2, T3, T4>());
}

View file

@ -2,26 +2,28 @@ namespace MfGames.Gallium;
public static class WhereEntityNotHasExtensions
{
public static IEnumerable<Entity> WhereEntityNotHas<T1>(
this IEnumerable<Entity> entities)
public static IEnumerable<Entity> WhereEntityNotHas<T1>(this IEnumerable<Entity> entities)
{
return entities.Where(x => !x.Has<T1>());
}
public static IEnumerable<Entity> WhereEntityNotHasAll
<T1, T2>(this IEnumerable<Entity> entities)
public static IEnumerable<Entity> WhereEntityNotHasAll<T1, T2>(
this IEnumerable<Entity> entities
)
{
return entities.Where(x => !x.HasAll<T1, T2>());
}
public static IEnumerable<Entity> WhereEntityNotHasAll
<T1, T2, T3>(this IEnumerable<Entity> entities)
public static IEnumerable<Entity> WhereEntityNotHasAll<T1, T2, T3>(
this IEnumerable<Entity> entities
)
{
return entities.Where(x => !x.HasAll<T1, T2, T3>());
}
public static IEnumerable<Entity> WhereEntityNotHasAll
<T1, T2, T3, T4>(this IEnumerable<Entity> entities)
public static IEnumerable<Entity> WhereEntityNotHasAll<T1, T2, T3, T4>(
this IEnumerable<Entity> entities
)
{
return entities.Where(x => !x.HasAll<T1, T2, T3, T4>());
}

View file

@ -24,8 +24,6 @@ public static class AssemblyExtensions
/// <returns>The directory or null if the assembly or location is null.</returns>
public static FileInfo? GetFile(this Assembly? assembly)
{
return assembly?.Location == null
? null
: new FileInfo(assembly.Location);
return assembly?.Location == null ? null : new FileInfo(assembly.Location);
}
}

View file

@ -15,19 +15,14 @@ public static class CryptoFileInfoExtensions
/// <param name="file">The FileInfo object or null.</param>
/// <param name="hash">The type of hash requested.</param>
/// <returns>Null if input is null, otherwise the hash value.</returns>
public static byte[]? ToHashBytes(
this FileInfo? file,
HashType hash = HashType.Sha512)
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);
}
@ -42,7 +37,8 @@ public static class CryptoFileInfoExtensions
public static string? ToHashString(
this FileInfo? file,
HashType hash = HashType.Sha512,
ByteStringFormat format = ByteStringFormat.LowercaseHex)
ByteStringFormat format = ByteStringFormat.LowercaseHex
)
{
return file?.ToHashBytes(hash).ToByteString(format);
}

View file

@ -51,11 +51,10 @@ public static class DirectoryInfoExtensions
/// <returns>A parent directory that matches, otherwise null.</returns>
public static DirectoryInfo? FindParent(
this DirectoryInfo? directory,
Func<DirectoryInfo, bool> match)
Func<DirectoryInfo, bool> match
)
{
return directory == null
? null
: FindSelfOrParent(directory.Parent, match);
return directory == null ? null : FindSelfOrParent(directory.Parent, match);
}
/// <summary>
@ -68,7 +67,8 @@ public static class DirectoryInfoExtensions
/// <returns>A parent directory that matches, otherwise null.</returns>
public static DirectoryInfo? FindSelfOrParent(
this DirectoryInfo? directory,
Func<DirectoryInfo, bool> match)
Func<DirectoryInfo, bool> match
)
{
while (true)
{
@ -103,9 +103,7 @@ public static class DirectoryInfoExtensions
/// <param name="directory">The directory to get the root path.</param>
/// <param name="paths">Additional child paths.</param>
/// <returns>A DirectoryInfo of the given path.</returns>
public static DirectoryInfo GetDirectory(
this DirectoryInfo directory,
params string[] paths)
public static DirectoryInfo GetDirectory(this DirectoryInfo directory, params string[] paths)
{
if (directory == null)
{
@ -117,9 +115,7 @@ public static class DirectoryInfoExtensions
throw new ArgumentNullException(nameof(paths));
}
string[] parts = new[] { directory.FullName }
.Union(paths)
.ToArray();
string[] parts = new[] { directory.FullName }.Union(paths).ToArray();
string path = Path.Combine(parts);
var info = new DirectoryInfo(path);
@ -133,9 +129,7 @@ public static class DirectoryInfoExtensions
/// <param name="directory">The directory to get the root path.</param>
/// <param name="paths">Additional child paths.</param>
/// <returns>A FileInfo of the given path.</returns>
public static FileInfo GetFile(
this DirectoryInfo directory,
params string[] paths)
public static FileInfo GetFile(this DirectoryInfo directory, params string[] paths)
{
if (directory == null)
{
@ -147,9 +141,7 @@ public static class DirectoryInfoExtensions
throw new ArgumentNullException(nameof(paths));
}
string[] parts = new[] { directory.FullName }
.Union(paths)
.ToArray();
string[] parts = new[] { directory.FullName }.Union(paths).ToArray();
string path = Path.Combine(parts);
var info = new FileInfo(path);
@ -164,7 +156,6 @@ public static class DirectoryInfoExtensions
/// <returns>True if the directory contains ".git", otherwise false.</returns>
public static bool IsGitRoot(this DirectoryInfo? directory)
{
return directory != null
&& directory.GetDirectories(".git").Length > 0;
return directory != null && directory.GetDirectories(".git").Length > 0;
}
}

View file

@ -44,10 +44,7 @@ public static class FileInfoExtensions
/// <param name="file">The file to write to.</param>
/// <param name="text">The text to write out.</param>
/// <param name="encoding">The encoding to use.</param>
public static void WriteAllText(
this FileInfo file,
string text,
Encoding encoding)
public static void WriteAllText(this FileInfo file, string text, Encoding encoding)
{
File.WriteAllText(file.FullName, text, encoding);
}

View file

@ -19,9 +19,11 @@ public class NestableReadLock : IDisposable
this.readerWriterLockSlim = readerWriterLockSlim;
// If we already have a read or write lock, we don't do anything.
if (readerWriterLockSlim.IsReadLockHeld
if (
readerWriterLockSlim.IsReadLockHeld
|| readerWriterLockSlim.IsUpgradeableReadLockHeld
|| readerWriterLockSlim.IsWriteLockHeld)
|| readerWriterLockSlim.IsWriteLockHeld
)
{
this.lockAcquired = false;
}

View file

@ -20,8 +20,7 @@ public class NestableUpgradableReadLock : IDisposable
this.readerWriterLockSlim = readerWriterLockSlim;
// If we already have a read or write lock, we don't do anything.
if (readerWriterLockSlim.IsUpgradeableReadLockHeld
|| readerWriterLockSlim.IsWriteLockHeld)
if (readerWriterLockSlim.IsUpgradeableReadLockHeld || readerWriterLockSlim.IsWriteLockHeld)
{
this.lockAcquired = false;
}

View file

@ -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;
@ -45,7 +44,8 @@ public class GemtextPipeTableExtension : IMarkdownExtension
if (!pipeline.InlineParsers.Contains<PipeTableParser>())
{
pipeline.InlineParsers.InsertBefore<EmphasisInlineParser>(
new PipeTableParser(lineBreakParser!, this.Options));
new PipeTableParser(lineBreakParser!, this.Options)
);
}
}
@ -58,8 +58,7 @@ public class GemtextPipeTableExtension : IMarkdownExtension
}
gemtext.ObjectRenderers.Add(
new TableRenderer(
this.Options.OmitPreformatLines,
this.Options.ConfigureTableBuilder));
new TableRenderer(this.Options.OmitPreformatLines, this.Options.ConfigureTableBuilder)
);
}
}

View file

@ -1,5 +1,4 @@
using ConsoleTableExt;
using Markdig.Extensions.Tables;
namespace MfGames.Markdown.Gemtext.Extensions;

View file

@ -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;
@ -32,8 +31,7 @@ public class GemtextSmartyPantsExtension : IMarkdownExtension
if (!pipeline.InlineParsers.Contains<SmartyPantsInlineParser>())
{
// Insert the parser after the code span parser
pipeline.InlineParsers.InsertAfter<CodeInlineParser>(
new SmartyPantsInlineParser());
pipeline.InlineParsers.InsertAfter<CodeInlineParser>(new SmartyPantsInlineParser());
}
}
@ -44,11 +42,9 @@ public class GemtextSmartyPantsExtension : IMarkdownExtension
return;
}
if (!gemtextRenderer.ObjectRenderers
.Contains<GemtextSmartyPantRenderer>())
if (!gemtextRenderer.ObjectRenderers.Contains<GemtextSmartyPantRenderer>())
{
gemtextRenderer.ObjectRenderers.Add(
new GemtextSmartyPantRenderer(this.Options));
gemtextRenderer.ObjectRenderers.Add(new GemtextSmartyPantRenderer(this.Options));
}
}
}

View file

@ -1,6 +1,5 @@
using Markdig;
using Markdig.Renderers;
using MfGames.Markdown.Gemtext.Renderers;
namespace MfGames.Markdown.Gemtext.Extensions;
@ -13,9 +12,7 @@ namespace MfGames.Markdown.Gemtext.Extensions;
public class HtmlAsCodeBlocks : IMarkdownExtension
{
/// <inheritdoc />
public void Setup(MarkdownPipelineBuilder pipeline)
{
}
public void Setup(MarkdownPipelineBuilder pipeline) { }
/// <inheritdoc />
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)

View file

@ -1,6 +1,5 @@
using Markdig;
using Markdig.Renderers;
using MfGames.Markdown.Gemtext.Renderers;
using MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks;
@ -15,9 +14,7 @@ namespace MfGames.Markdown.Gemtext.Extensions;
public class IncreaseHeaderDepthsAfterFirst : IMarkdownExtension
{
/// <inheritdoc />
public void Setup(MarkdownPipelineBuilder pipeline)
{
}
public void Setup(MarkdownPipelineBuilder pipeline) { }
/// <inheritdoc />
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
@ -27,8 +24,7 @@ public class IncreaseHeaderDepthsAfterFirst : IMarkdownExtension
return;
}
HeadingRenderer? heading =
gemtext.ObjectRenderers.Find<HeadingRenderer>();
HeadingRenderer? heading = gemtext.ObjectRenderers.Find<HeadingRenderer>();
if (heading != null)
{

View file

@ -1,6 +1,5 @@
using Markdig;
using Markdig.Renderers;
using MfGames.Markdown.Gemtext.Renderers;
namespace MfGames.Markdown.Gemtext.Extensions;
@ -14,7 +13,8 @@ public class SetBlockLinkHandling : IMarkdownExtension
public SetBlockLinkHandling(
BlockLinkHandling? blockLinkHandling = null,
EndLinkInlineFormatting? endLinkInlineFormatting = null,
int? nextFootnoteNumber = null)
int? nextFootnoteNumber = null
)
{
this.BlockLinkHandling = blockLinkHandling;
this.EndLinkInlineFormatting = endLinkInlineFormatting;
@ -41,9 +41,7 @@ public class SetBlockLinkHandling : IMarkdownExtension
public int? NextFootnoteNumber { get; set; }
/// <inheritdoc />
public void Setup(MarkdownPipelineBuilder pipeline)
{
}
public void Setup(MarkdownPipelineBuilder pipeline) { }
/// <inheritdoc />
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
@ -53,11 +51,9 @@ public class SetBlockLinkHandling : IMarkdownExtension
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;
}
}

View file

@ -1,6 +1,5 @@
using Markdig;
using Markdig.Renderers;
using MfGames.Markdown.Gemtext.Renderers;
namespace MfGames.Markdown.Gemtext.Extensions;
@ -30,9 +29,7 @@ public class SetInlineFormatting : IMarkdownExtension
public InlineFormatting? Emphasis { get; set; }
/// <inheritdoc />
public void Setup(MarkdownPipelineBuilder pipeline)
{
}
public void Setup(MarkdownPipelineBuilder pipeline) { }
/// <inheritdoc />
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)

View file

@ -1,7 +1,6 @@
using Markdig;
using Markdig.Parsers;
using Markdig.Syntax;
using MfGames.Markdown.Gemtext.Renderers;
namespace MfGames.Markdown.Gemtext;
@ -17,8 +16,7 @@ public static class MarkdownGemtext
static MarkdownGemtext()
{
DefaultPipeline = new MarkdownPipelineBuilder()
.Build();
DefaultPipeline = new MarkdownPipelineBuilder().Build();
}
/// <summary>
@ -31,7 +29,8 @@ public static class MarkdownGemtext
public static string ToGemtext(
string markdown,
MarkdownPipeline? pipeline = null,
MarkdownParserContext? context = null)
MarkdownParserContext? context = null
)
{
if (markdown == null)
{
@ -40,8 +39,7 @@ public static class MarkdownGemtext
pipeline ??= DefaultPipeline;
MarkdownDocument document = MarkdownParser
.Parse(markdown, pipeline, context);
MarkdownDocument document = MarkdownParser.Parse(markdown, pipeline, context);
return ToGemtext(document, pipeline);
}
@ -55,7 +53,8 @@ public static class MarkdownGemtext
/// <exception cref="ArgumentNullException">if markdown document variable is null</exception>
public static string ToGemtext(
this MarkdownDocument document,
MarkdownPipeline? pipeline = null)
MarkdownPipeline? pipeline = null
)
{
// Make sure we have sane parameters.
if (document == null)

View file

@ -16,9 +16,7 @@ public class HeadingRenderer : GemtextObjectRenderer<HeadingBlock>
/// </summary>
public bool IncreaseHeaderDepthAfterFirst { get; set; }
protected override void Write(
GemtextRenderer renderer,
HeadingBlock obj)
protected override void Write(GemtextRenderer renderer, HeadingBlock obj)
{
// Figure out the level we should be processing.
int level = obj.Level;

View file

@ -8,9 +8,7 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks;
/// <seealso cref="GemtextObjectRenderer{ListBlock}" />
public class ListRenderer : GemtextObjectRenderer<ListBlock>
{
protected override void Write(
GemtextRenderer renderer,
ListBlock listBlock)
protected override void Write(GemtextRenderer renderer, ListBlock listBlock)
{
// Lists need to be separated from the rest.
renderer.EnsureTwoLines();

View file

@ -1,5 +1,4 @@
using Markdig.Syntax;
using MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks;
@ -8,12 +7,9 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks;
/// A Gemtext renderer for a <see cref="MarkdownDocument" />.
/// </summary>
/// <seealso cref="GemtextObjectRenderer{ParagraphBlock}" />
public class MarkdownDocumentRenderer
: GemtextObjectRenderer<MarkdownDocument>
public class MarkdownDocumentRenderer : GemtextObjectRenderer<MarkdownDocument>
{
protected override void Write(
GemtextRenderer renderer,
MarkdownDocument obj)
protected override void Write(GemtextRenderer renderer, MarkdownDocument obj)
{
// Simply write out the contents.
renderer.WriteChildren(obj);

View file

@ -1,5 +1,4 @@
using Markdig.Syntax;
using MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks;
@ -10,9 +9,7 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks;
/// <seealso cref="GemtextObjectRenderer{ParagraphBlock}" />
public class ParagraphRenderer : GemtextObjectRenderer<ParagraphBlock>
{
protected override void Write(
GemtextRenderer renderer,
ParagraphBlock obj)
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.
@ -29,8 +26,7 @@ public class ParagraphRenderer : GemtextObjectRenderer<ParagraphBlock>
}
else
{
renderer.WhileLinkInsideBlock(
() => renderer.WriteLeafInline(obj));
renderer.WhileLinkInsideBlock(() => renderer.WriteLeafInline(obj));
}
// If we get to the end of the paragraph and we have gathered links,

View file

@ -1,5 +1,4 @@
using ConsoleTableExt;
using Markdig.Extensions.Tables;
namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks;
@ -10,9 +9,7 @@ public class TableRenderer : GemtextObjectRenderer<Table>
private readonly bool omitPreformat;
public TableRenderer(
bool omitPreformat,
Action<ConsoleTableBuilder>? configureTableBuilder)
public TableRenderer(bool omitPreformat, Action<ConsoleTableBuilder>? configureTableBuilder)
{
this.omitPreformat = omitPreformat;
this.configureTableBuilder = configureTableBuilder;
@ -97,24 +94,22 @@ public class TableRenderer : GemtextObjectRenderer<Table>
private static void SetAlignments(
Table table,
Dictionary<int, TextAligntment> align,
TableRow row)
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
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;
TableColumnAlign? alignment = table.ColumnDefinitions[columnIndex].Alignment;
if (alignment.HasValue)
{

View file

@ -6,12 +6,9 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Blocks;
/// A Gemtext renderer for a <see cref="ThematicBreakBlock" />.
/// </summary>
/// <seealso cref="GemtextObjectRenderer{ThematicBreakBlock}" />
public class ThematicBreakRenderer
: GemtextObjectRenderer<ThematicBreakBlock>
public class ThematicBreakRenderer : GemtextObjectRenderer<ThematicBreakBlock>
{
protected override void Write(
GemtextRenderer renderer,
ThematicBreakBlock obj)
protected override void Write(GemtextRenderer renderer, ThematicBreakBlock obj)
{
renderer.EnsureTwoLines();
renderer.WriteLine("---");

View file

@ -12,6 +12,4 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext;
/// <seealso cref="IMarkdownObjectRenderer" />
public abstract class GemtextObjectRenderer<TObject>
: MarkdownObjectRenderer<GemtextRenderer, TObject>
where TObject : MarkdownObject
{
}
where TObject : MarkdownObject { }

View file

@ -6,12 +6,9 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
/// A Gemtext renderer for a <see cref="DelimiterInline" />.
/// </summary>
/// <seealso cref="GemtextObjectRenderer{DelimiterInline}" />
public class DelimiterInlineRenderer
: GemtextObjectRenderer<DelimiterInline>
public class DelimiterInlineRenderer : GemtextObjectRenderer<DelimiterInline>
{
protected override void Write(
GemtextRenderer renderer,
DelimiterInline obj)
protected override void Write(GemtextRenderer renderer, DelimiterInline obj)
{
renderer.Write(obj.ToLiteral());
renderer.WriteChildren(obj);

View file

@ -8,9 +8,7 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
/// <seealso cref="GemtextObjectRenderer{EmphasisInline}" />
public class EmphasisInlineRenderer : GemtextObjectRenderer<EmphasisInline>
{
protected override void Write(
GemtextRenderer renderer,
EmphasisInline obj)
protected override void Write(GemtextRenderer renderer, EmphasisInline obj)
{
InlineFormatting formatting = renderer.EmphasisFormattingResolved;
bool normalize = formatting == InlineFormatting.Normalize;

View file

@ -1,5 +1,4 @@
using System.Net;
using Markdig.Extensions.SmartyPants;
namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
@ -8,8 +7,7 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
/// A Gemtext renderer for a <see cref="SmartyPant" />.
/// </summary>
/// <seealso cref="GemtextObjectRenderer{GemtextEntityInline}" />
public class GemtextSmartyPantRenderer
: GemtextObjectRenderer<SmartyPant>
public class GemtextSmartyPantRenderer : GemtextObjectRenderer<SmartyPant>
{
private static readonly SmartyPantOptions DefaultOptions = new();
@ -22,8 +20,7 @@ public class GemtextSmartyPantRenderer
/// <exception cref="ArgumentNullException"></exception>
public GemtextSmartyPantRenderer(SmartyPantOptions? options)
{
this.options = options
?? throw new ArgumentNullException(nameof(options));
this.options = options ?? throw new ArgumentNullException(nameof(options));
}
protected override void Write(GemtextRenderer renderer, SmartyPant obj)

View file

@ -6,12 +6,9 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
/// A Gemtext renderer for a <see cref="GemtextEntityInline" />.
/// </summary>
/// <seealso cref="GemtextObjectRenderer{GemtextEntityInline}" />
public class HtmlEntityInlineRenderer
: GemtextObjectRenderer<HtmlEntityInline>
public class HtmlEntityInlineRenderer : GemtextObjectRenderer<HtmlEntityInline>
{
protected override void Write(
GemtextRenderer renderer,
HtmlEntityInline obj)
protected override void Write(GemtextRenderer renderer, HtmlEntityInline obj)
{
renderer.Write(obj.Transcoded);
}

View file

@ -6,8 +6,7 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
/// A Gemtext renderer for a <see cref="LineBreakInline" />.
/// </summary>
/// <seealso cref="GemtextObjectRenderer{LineBreakInline}" />
public class LineBreakInlineRenderer
: GemtextObjectRenderer<LineBreakInline>
public class LineBreakInlineRenderer : GemtextObjectRenderer<LineBreakInline>
{
/// <summary>
/// Gets or sets a value indicating whether to render this softline break as a
@ -15,9 +14,7 @@ public class LineBreakInlineRenderer
/// </summary>
public bool RenderAsHardlineBreak { get; set; }
protected override void Write(
GemtextRenderer renderer,
LineBreakInline obj)
protected override void Write(GemtextRenderer renderer, LineBreakInline obj)
{
if (obj.IsHard || this.RenderAsHardlineBreak)
{

View file

@ -38,10 +38,9 @@ public class LinkInlineRenderer : GemtextObjectRenderer<LinkInline>
{
// Figure out the various states we have.
bool outside = !renderer.LinkInsideBlock;
bool insert = !outside
&& renderer.BlockLinkHandling ==
BlockLinkHandling.InsertLine;
bool gather = !outside
bool insert = !outside && renderer.BlockLinkHandling == BlockLinkHandling.InsertLine;
bool gather =
!outside
&& renderer.BlockLinkHandling switch
{
BlockLinkHandling.DocumentEnd => true,
@ -49,14 +48,11 @@ public class LinkInlineRenderer : GemtextObjectRenderer<LinkInline>
_ => false,
};
bool hasText = link.FirstChild != null;
bool footnotes = renderer.EndLinkInlineFormatting
== EndLinkInlineFormatting.Footnote;
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;
string? url = link.GetDynamicUrl != null ? link.GetDynamicUrl() ?? link.Url : link.Url;
if (outside || insert)
{
@ -84,9 +80,7 @@ public class LinkInlineRenderer : GemtextObjectRenderer<LinkInline>
if (gather)
{
int footnoteNumber = renderer.NextFootnoteNumber++;
string linkText = footnotes
? footnoteNumber + ": " + url
: GetLinkText(link);
string linkText = footnotes ? footnoteNumber + ": " + url : GetLinkText(link);
if (footnotes)
{

View file

@ -8,9 +8,7 @@ namespace MfGames.Markdown.Gemtext.Renderers.Gemtext.Inlines;
/// <seealso cref="GemtextObjectRenderer{LiteralInline}" />
public class LiteralInlineRenderer : GemtextObjectRenderer<LiteralInline>
{
protected override void Write(
GemtextRenderer renderer,
LiteralInline obj)
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.

View file

@ -15,9 +15,7 @@ public static class MarkdigExtensions
/// <returns>True if there is only a link in the paragraph.</returns>
public static bool OnlyHasSingleLink(this ParagraphBlock obj)
{
return obj.Inline != null
&& obj.Inline.Count() == 1
&& obj.Inline.FirstChild is LinkInline;
return obj.Inline != null && obj.Inline.Count() == 1 && obj.Inline.FirstChild is LinkInline;
}
/// <summary>

View file

@ -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;
@ -54,8 +53,7 @@ public class GemtextRenderer : TextRendererBase<GemtextRenderer>
/// is either `CodeInlineFormatting` or `InlineFormatting` if that
/// is not set.
/// </summary>
public InlineFormatting CodeFormattingResolved =>
this.CodeFormatting ?? this.InlineFormatting;
public InlineFormatting CodeFormattingResolved => this.CodeFormatting ?? this.InlineFormatting;
/// <summary>
/// Gets or sets the optional formatting for emphasis (which includes
@ -140,9 +138,7 @@ public class GemtextRenderer : TextRendererBase<GemtextRenderer>
/// <param name="leafBlock">The leaf block.</param>
/// <param name="writeEndOfLines">if set to <c>true</c> write end of lines.</param>
/// <returns>This instance</returns>
public GemtextRenderer WriteLeafRawLines(
LeafBlock leafBlock,
bool writeEndOfLines)
public GemtextRenderer WriteLeafRawLines(LeafBlock leafBlock, bool writeEndOfLines)
{
// Make sure we have sane input.
if (leafBlock == null)

View file

@ -10,9 +10,7 @@ namespace MfGames.Markdown.Extensions;
public class WikiLinkExtension : IMarkdownExtension
{
public WikiLinkExtension()
: this(null)
{
}
: this(null) { }
public WikiLinkExtension(WikiLinkOptions? options)
{
@ -24,8 +22,7 @@ public class WikiLinkExtension : IMarkdownExtension
/// <inheritdoc />
public void Setup(MarkdownPipelineBuilder pipeline)
{
WikiLinkInlineParser? parser = pipeline.InlineParsers
.FindExact<WikiLinkInlineParser>();
WikiLinkInlineParser? parser = pipeline.InlineParsers.FindExact<WikiLinkInlineParser>();
if (parser != null)
{
@ -37,9 +34,7 @@ public class WikiLinkExtension : IMarkdownExtension
}
/// <inheritdoc />
public void Setup(
MarkdownPipeline pipeline,
IMarkdownRenderer renderer)
public void Setup(MarkdownPipeline pipeline, IMarkdownRenderer renderer)
{
// No setup needed here because we're using LinkInline which does the
// bulk of the work.

View file

@ -15,9 +15,7 @@ public class WikiLinkInlineParser : InlineParser
}
/// <inheritdoc />
public override bool Match(
InlineProcessor processor,
ref StringSlice slice)
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.
@ -52,9 +50,7 @@ public class WikiLinkInlineParser : InlineParser
slice.NextChar();
// Format the label and the URL.
string content = slice.Text.Substring(
contentStart,
contentEnd - contentStart);
string content = slice.Text.Substring(contentStart, contentEnd - contentStart);
string[] contentParts = content.Split('|', 2);
string label = contentParts.Last();
string url = this.options.GetUrl(contentParts.First());
@ -69,14 +65,12 @@ public class WikiLinkInlineParser : InlineParser
}
// Create the link that we're replacing.
WikiLink link = new()
WikiLink link =
new()
{
Span =
{
Start = processor.GetSourcePosition(
linkStart,
out int line,
out int column),
Start = processor.GetSourcePosition(linkStart, out int line, out int column),
},
Line = line,
Column = column,
@ -91,7 +85,8 @@ public class WikiLinkInlineParser : InlineParser
Column = column,
Content = new StringSlice(label),
IsClosed = true,
});
}
);
// Replace the inline and then indicate we have a match.
processor.Inline = link;
@ -99,9 +94,7 @@ public class WikiLinkInlineParser : InlineParser
return true;
}
private static bool IsNotDelimiter(
StringSlice slice,
char delimiter)
private static bool IsNotDelimiter(StringSlice slice, char delimiter)
{
return slice.CurrentChar != delimiter
|| slice.PeekChar() != delimiter

View file

@ -6,13 +6,10 @@ public class CreateCalendarValidator : AbstractValidator<CreateCalender>
{
public CreateCalendarValidator()
{
this.RuleFor(x => x.Path)
.NotNull();
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();
}
}

View file

@ -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;
@ -27,9 +23,7 @@ public partial class CreateCalender : OperationBase
private readonly IValidator<CreateCalender> validator;
public CreateCalender(
IValidator<CreateCalender> validator,
TimeService clock)
public CreateCalender(IValidator<CreateCalender> validator, TimeService clock)
{
this.validator = validator;
this.clock = clock;
@ -55,19 +49,18 @@ public partial class CreateCalender : OperationBase
/// <inheritdoc />
public override IEnumerable<Entity> Run(
IEnumerable<Entity> input,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default
)
{
this.validator.ValidateAndThrow(this);
SplitEntityEnumerations split = input.SplitEntity<Instant>();
IEnumerable<Entity> datedAndCalendars =
this.CreateCalendarEntity(split.HasAll);
IEnumerable<Entity> datedAndCalendars = this.CreateCalendarEntity(split.HasAll);
return datedAndCalendars.Union(split.NotHasAll);
}
private IEnumerable<Entity> CreateCalendarEntity(
IEnumerable<Entity> entities)
private IEnumerable<Entity> CreateCalendarEntity(IEnumerable<Entity> entities)
{
// Create the calendar in the same time zone as the rest of the system.
var calendar = new Ical.Net.Calendar();
@ -76,8 +69,7 @@ public partial class CreateCalender : OperationBase
// Go through the events and add all of them.
var input = entities.ToList();
IEnumerable<CalendarEvent> events =
input.Select(this.CreateCalendarEvent);
IEnumerable<CalendarEvent> events = input.Select(this.CreateCalendarEvent);
calendar.Events.AddRange(events);
@ -86,7 +78,8 @@ public partial class CreateCalender : OperationBase
string serializedCalendar = serializer.SerializeToString(calendar);
// Create the calendar entity and populate everything.
Entity calendarEntity = new Entity().Set(IsCalendar.Instance)
Entity calendarEntity = new Entity()
.Set(IsCalendar.Instance)
.Set(this.Path!.Value)
.SetTextContent(serializedCalendar);

View file

@ -6,6 +6,4 @@ namespace MfGames.Nitride.Calendar;
/// A marker component for identifying an entity that represents a calendar.
/// </summary>
[SingletonComponent]
public partial class IsCalendar
{
}
public partial class IsCalendar { }

View file

@ -1,5 +1,4 @@
using Autofac;
using MfGames.Nitride.Temporal.Setup;
namespace MfGames.Nitride.Calendar;
@ -13,14 +12,12 @@ public static class NitrideCalendarBuilderExtensions
// If we've already loaded, then we have a problem.
if (loaded)
{
throw new InvalidOperationException(
"Cannot use UseCalendar() more than once.");
throw new InvalidOperationException("Cannot use UseCalendar() more than once.");
}
loaded = true;
// Get the configuration so we can set the various options.
return builder
.ConfigureContainer(x => x.RegisterModule<NitrideCalendarModule>());
return builder.ConfigureContainer(x => x.RegisterModule<NitrideCalendarModule>());
}
}

View file

@ -1,5 +1,4 @@
using Autofac;
using MfGames.Nitride.Temporal.Setup;
namespace MfGames.Nitride.Calendar;

View file

@ -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
@ -24,9 +20,7 @@ public partial class ExecOperation : AsyncOperationBase
private readonly IValidator<ExecOperation> validator;
public ExecOperation(
ILogger logger,
IValidator<ExecOperation> validator)
public ExecOperation(ILogger logger, IValidator<ExecOperation> validator)
{
this.logger = logger.ForContext<ExecOperation>();
this.validator = validator;
@ -43,11 +37,7 @@ public partial class ExecOperation : AsyncOperationBase
/// <remarks>
/// This is mutually exclusive with OnResult.
/// </remarks>
public Func<BufferedCommandResult, IEnumerable<Entity>>? OnBufferedResult
{
get;
set;
}
public Func<BufferedCommandResult, IEnumerable<Entity>>? OnBufferedResult { get; set; }
/// <summary>
/// Gets or sets a callback to process the output.
@ -60,7 +50,8 @@ public partial class ExecOperation : AsyncOperationBase
/// <inheritdoc />
public override async IAsyncEnumerable<Entity> RunAsync(
IAsyncEnumerable<Entity> input,
[EnumeratorCancellation] CancellationToken cancellationToken = default)
[EnumeratorCancellation] CancellationToken cancellationToken = default
)
{
// Make sure everything is validated.
await this.validator.ValidateAndThrowAsync(this, cancellationToken);
@ -78,14 +69,14 @@ public partial class ExecOperation : AsyncOperationBase
if (this.OnBufferedResult != null)
{
BufferedCommandResult result = await command
.ExecuteBufferedAsync(cancellationToken);
BufferedCommandResult result = await command.ExecuteBufferedAsync(cancellationToken);
this.logger.Debug(
"Execute buffered: {Command} {Arguments} = {ExitCode}",
command.TargetFilePath,
command.Arguments,
result.ExitCode);
result.ExitCode
);
IEnumerable<Entity> list = this.OnBufferedResult(result);
@ -96,14 +87,14 @@ public partial class ExecOperation : AsyncOperationBase
}
else
{
CommandResult result = await command
.ExecuteAsync(cancellationToken);
CommandResult result = await command.ExecuteAsync(cancellationToken);
this.logger.Debug(
"Execute: {Command} {Arguments} = {ExitCode}",
command.TargetFilePath,
command.Arguments,
result.ExitCode);
result.ExitCode
);
IEnumerable<Entity>? list = this.OnResult?.Invoke(result);

View file

@ -9,14 +9,12 @@ public static class NitrideExecBuilderExtensions
// If we've already loaded, then we have a problem.
if (loaded)
{
throw new InvalidOperationException(
"Cannot use UseExec() more than once.");
throw new InvalidOperationException("Cannot use UseExec() more than once.");
}
loaded = true;
// Get the configuration so we can set the various options.
return builder
.UseModule<NitrideExecModule>();
return builder.UseModule<NitrideExecModule>();
}
}

View file

@ -6,15 +6,10 @@ public class ExecOperationValidator : AbstractValidator<ExecOperation>
{
public ExecOperationValidator()
{
this.RuleFor(x => x.CreateCommand)
.NotNull();
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);
}
}

View file

@ -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;
@ -23,9 +19,7 @@ public partial class CreateAtomFeed : OperationBase
private readonly IValidator<CreateAtomFeed> validator;
public CreateAtomFeed(
ILogger logger,
IValidator<CreateAtomFeed> validator)
public CreateAtomFeed(ILogger logger, IValidator<CreateAtomFeed> validator)
{
this.logger = logger;
this.validator = validator;
@ -91,7 +85,8 @@ public partial class CreateAtomFeed : OperationBase
/// <inheritdoc />
public override IEnumerable<Entity> Run(
IEnumerable<Entity> input,
CancellationToken cancellationToken = default)
CancellationToken cancellationToken = default
)
{
this.validator.ValidateAndThrow(this);
@ -121,7 +116,8 @@ public partial class CreateAtomFeed : OperationBase
}
// Create the feed entity and return both objects.
Entity feedEntity = new Entity().Set(IsFeed.Instance)
Entity feedEntity = new Entity()
.Set(IsFeed.Instance)
.Set(this.GetPath!(entity))
.SetTextContent(feed + "\n");

View file

@ -6,13 +6,10 @@ public class CreateAtomFeedValidator : AbstractValidator<CreateAtomFeed>
{
public CreateAtomFeedValidator()
{
this.RuleFor(x => x.GetEntries)
.NotNull();
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();
}
}

View file

@ -6,9 +6,7 @@ namespace MfGames.Nitride.Feeds;
/// </summary>
public class HasFeed
{
public HasFeed()
{
}
public HasFeed() { }
public static HasFeed Instance { get; } = new();
}

View file

@ -6,6 +6,4 @@ namespace MfGames.Nitride.Feeds;
/// A marker component that indicates this page is a feed.
/// </summary>
[SingletonComponent]
public partial class IsFeed
{
}
public partial class IsFeed { }

View file

@ -11,14 +11,12 @@ public static class NitrideFeedsBuilderExtensions
// If we've already loaded, then we have a problem.
if (loaded)
{
throw new InvalidOperationException(
"Cannot use UseFeeds() more than once.");
throw new InvalidOperationException("Cannot use UseFeeds() more than once.");
}
loaded = true;
// Get the configuration so we can set the various options.
return builder
.ConfigureContainer(x => x.RegisterModule<NitrideFeedsModule>());
return builder.ConfigureContainer(x => x.RegisterModule<NitrideFeedsModule>());
}
}

View file

@ -1,5 +1,4 @@
using Autofac;
using MfGames.Nitride.Temporal.Setup;
namespace MfGames.Nitride.Feeds.Setup;

View file

@ -1,5 +1,4 @@
using System.Xml.Linq;
using MfGames.Nitride.Generators;
namespace MfGames.Nitride.Feeds.Structure;
@ -31,10 +30,7 @@ public partial class AtomAuthor
if (!string.IsNullOrEmpty(this.Name))
{
author.Add(
new XElement(
XmlConstants.AtomNamespace + "name",
new XText(this.Name)));
author.Add(new XElement(XmlConstants.AtomNamespace + "name", new XText(this.Name)));
}
return author;

View file

@ -1,5 +1,4 @@
using System.Xml.Linq;
using MfGames.Nitride.Generators;
namespace MfGames.Nitride.Feeds.Structure;
@ -39,7 +38,8 @@ public partial class AtomCategory
var elem = new XElement(
XmlConstants.AtomNamespace + "category",
new XAttribute("term", this.Term));
new XAttribute("term", this.Term)
);
if (this.Scheme != null)
{

View file

@ -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;
@ -86,13 +83,12 @@ public partial class AtomEntry
new XElement(
AtomNamespace + "link",
new XAttribute("rel", "alternate"),
new XAttribute("href", this.Url.ToString())));
new XAttribute("href", this.Url.ToString())
)
);
}
AtomHelper.AddIfSet(
elem,
"published",
this.Published?.ToString("g", null));
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());
@ -111,7 +107,9 @@ public partial class AtomEntry
new XElement(
AtomNamespace + "summary",
new XAttribute("type", this.SummaryType),
new XText(this.Summary)));
new XText(this.Summary)
)
);
}
if (!string.IsNullOrWhiteSpace(this.Content))
@ -120,7 +118,9 @@ public partial class AtomEntry
new XElement(
AtomNamespace + "content",
new XAttribute("type", this.ContentType),
new XText(this.Content)));
new XText(this.Content)
)
);
}
return elem;

View file

@ -1,7 +1,5 @@
using System.Xml.Linq;
using NodaTime;
using static MfGames.Nitride.Feeds.Structure.XmlConstants;
namespace MfGames.Nitride.Feeds.Structure;
@ -67,7 +65,9 @@ public record AtomFeed
AtomNamespace + "title",
new XAttribute("type", "text"),
new XAttribute(XNamespace.Xml + "lang", "en"),
new XText(this.Title)));
new XText(this.Title)
)
);
}
if (this.Url != null)
@ -77,7 +77,9 @@ public record AtomFeed
AtomNamespace + "link",
new XAttribute("type", "application/atom+xml"),
new XAttribute("href", this.Url.ToString()),
new XAttribute("rel", "self")));
new XAttribute("rel", "self")
)
);
}
if (this.AlternateUrl != null)
@ -87,7 +89,9 @@ public record AtomFeed
AtomNamespace + "link",
new XAttribute("type", this.AlternateMimeType),
new XAttribute("href", this.AlternateUrl.ToString()),
new XAttribute("rel", "alternate")));
new XAttribute("rel", "alternate")
)
);
}
AtomHelper.AddIfSet(elem, "updated", this.Updated?.ToString("g", null));

View file

@ -7,9 +7,7 @@ namespace MfGames.Nitride.Feeds.Structure;
/// </summary>
public static class AtomHelper
{
public static void AddIfSet(
XElement root,
XElement? elem)
public static void AddIfSet(XElement root, XElement? elem)
{
if (elem != null)
{
@ -17,17 +15,11 @@ public static class AtomHelper
}
}
public static void AddIfSet(
XElement elem,
string name,
string? 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)));
elem.Add(new XElement(XmlConstants.AtomNamespace + name, new XText(text)));
}
}
}

View file

@ -10,12 +10,10 @@ public static class XmlConstants
/// <summary>
/// The XML namespace for Atom feeds.
/// </summary>
public static readonly XNamespace AtomNamespace =
"http://www.w3.org/2005/Atom";
public static readonly XNamespace AtomNamespace = "http://www.w3.org/2005/Atom";
/// <summary>
/// The XML namespace for media.
/// </summary>
public static readonly XNamespace MediaNamespace =
"http://search.yahoo.com/mrss/";
public static readonly XNamespace MediaNamespace = "http://search.yahoo.com/mrss/";
}

View file

@ -7,6 +7,4 @@ namespace MfGames.Nitride.Gemtext;
/// for text files using the Gemini protocol.
/// </summary>
[SingletonComponent]
public partial class IsGemtext
{
}
public partial class IsGemtext { }

View file

@ -11,14 +11,12 @@ public static class NitrideGemtextBuilderExtensions
// If we've already loaded, then we have a problem.
if (loaded)
{
throw new InvalidOperationException(
"Cannot use UseGemtext() more than once.");
throw new InvalidOperationException("Cannot use UseGemtext() more than once.");
}
loaded = true;
// Get the configuration so we can set the various options.
return builder.ConfigureContainer(
x => x.RegisterModule<NitrideGemtextModule>());
return builder.ConfigureContainer(x => x.RegisterModule<NitrideGemtextModule>());
}
}

View file

@ -5,7 +5,5 @@ namespace MfGames.Nitride.Gemtext;
public class NitrideGemtextModule : Module
{
/// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{
}
protected override void Load(ContainerBuilder builder) { }
}

View file

@ -6,8 +6,7 @@ namespace MfGames.Nitride.Generators;
/// <summary>
/// Base class for classes marked with an attribute.
/// </summary>
public abstract class ClassAttributeSourceGeneratorBase<TSyntaxReceiver>
: ISourceGenerator
public abstract class ClassAttributeSourceGeneratorBase<TSyntaxReceiver> : ISourceGenerator
where TSyntaxReceiver : ClassAttributeSyntaxReceiverBase
{
public void Execute(GeneratorExecutionContext context)
@ -28,12 +27,12 @@ public abstract class ClassAttributeSourceGeneratorBase<TSyntaxReceiver>
Location.Create(
"Temporary.g.cs",
TextSpan.FromBounds(0, 0),
new LinePositionSpan(
new LinePosition(0, 0),
new LinePosition(0, 0))),
new LinePositionSpan(new LinePosition(0, 0), new LinePosition(0, 0))
),
"{0}: Syntax Message: {1}",
this.GetType().Name,
message);
message
);
}
// If we didn't find anything, then there is nothing to do.
@ -43,8 +42,7 @@ public abstract class ClassAttributeSourceGeneratorBase<TSyntaxReceiver>
}
// Go through each one.
foreach (ClassAttributeReference reference in syntaxReceiver
.ReferenceList)
foreach (ClassAttributeReference reference in syntaxReceiver.ReferenceList)
{
this.GenerateClassFile(context, reference);
}
@ -53,14 +51,13 @@ public abstract class ClassAttributeSourceGeneratorBase<TSyntaxReceiver>
public void Initialize(GeneratorInitializationContext context)
{
// Register a factory that can create our custom syntax receiver
context.RegisterForSyntaxNotifications(
() => this.CreateSyntaxReceiver(context));
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);
ClassAttributeReference reference
);
}

View file

@ -11,7 +11,8 @@ public abstract class ClassAttributeSyntaxReceiverBase : ISyntaxReceiver
public ClassAttributeSyntaxReceiverBase(
GeneratorInitializationContext context,
string attributeName)
string attributeName
)
{
this.context = context;
this.attributeName = attributeName;
@ -71,15 +72,13 @@ public abstract class ClassAttributeSyntaxReceiverBase : ISyntaxReceiver
}
// See if the class has our set properties attribute.
var attributes = cds.AttributeLists
.AsEnumerable()
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");
bool found = attributes.Any(x =>
x == this.attributeName || x == $"{this.attributeName}Attribute"
);
if (this.DebugAttributes)
{
@ -88,7 +87,9 @@ public abstract class ClassAttributeSyntaxReceiverBase : ISyntaxReceiver
"Parsing {0} found? {1} from attributes [{2}]",
cds.Identifier,
found,
string.Join(", ", attributes)));
string.Join(", ", attributes)
)
);
}
if (found)
@ -99,7 +100,8 @@ public abstract class ClassAttributeSyntaxReceiverBase : ISyntaxReceiver
Namespace = this.Namespace!,
UsingDirectiveList = this.UsingDirectiveList,
ClassDeclaration = cds,
});
}
);
}
}
}

View file

@ -18,7 +18,8 @@ public static class CodeAnalysisExtensions
this GeneratorExecutionContext context,
MessageCode messageCode,
string format,
params object?[] parameters)
params object?[] parameters
)
{
Error(context, messageCode, null, format, parameters);
}
@ -36,14 +37,10 @@ public static class CodeAnalysisExtensions
MessageCode messageCode,
Location? location,
string format,
params object?[] parameters)
params object?[] parameters
)
{
context.Message(
messageCode,
location,
DiagnosticSeverity.Error,
format,
parameters);
context.Message(messageCode, location, DiagnosticSeverity.Error, format, parameters);
}
/// <summary>
@ -57,7 +54,8 @@ public static class CodeAnalysisExtensions
this GeneratorExecutionContext context,
MessageCode messageCode,
string format,
params object?[] parameters)
params object?[] parameters
)
{
Information(context, messageCode, null, format, parameters);
}
@ -75,14 +73,10 @@ public static class CodeAnalysisExtensions
MessageCode messageCode,
Location? location,
string format,
params object?[] parameters)
params object?[] parameters
)
{
context.Message(
messageCode,
location,
DiagnosticSeverity.Info,
format,
parameters);
context.Message(messageCode, location, DiagnosticSeverity.Info, format, parameters);
}
/// <summary>
@ -96,7 +90,8 @@ public static class CodeAnalysisExtensions
this GeneratorExecutionContext context,
MessageCode messageCode,
string format,
params object?[] parameters)
params object?[] parameters
)
{
Warning(context, messageCode, null, format, parameters);
}
@ -114,14 +109,10 @@ public static class CodeAnalysisExtensions
MessageCode messageCode,
Location? location,
string format,
params object?[] parameters)
params object?[] parameters
)
{
context.Message(
messageCode,
location,
DiagnosticSeverity.Warning,
format,
parameters);
context.Message(messageCode, location, DiagnosticSeverity.Warning, format, parameters);
}
/// <summary>
@ -139,7 +130,8 @@ public static class CodeAnalysisExtensions
Location? location,
DiagnosticSeverity severity,
string format,
params object?[] parameters)
params object?[] parameters
)
{
context.ReportDiagnostic(
Diagnostic.Create(
@ -149,10 +141,9 @@ public static class CodeAnalysisExtensions
severity,
severity,
true,
severity is DiagnosticSeverity.Warning
or DiagnosticSeverity.Info
? 4
: 0,
location: location));
severity is DiagnosticSeverity.Warning or DiagnosticSeverity.Info ? 4 : 0,
location: location
)
);
}
}

View file

@ -1,5 +1,4 @@
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text;
@ -16,14 +15,16 @@ public class SingletonComponentSourceGenerator
: ClassAttributeSourceGeneratorBase<SingletonComponentSyntaxReceiver>
{
protected override SingletonComponentSyntaxReceiver CreateSyntaxReceiver(
GeneratorInitializationContext context)
GeneratorInitializationContext context
)
{
return new SingletonComponentSyntaxReceiver(context);
}
protected override void GenerateClassFile(
GeneratorExecutionContext context,
ClassAttributeReference unit)
ClassAttributeReference unit
)
{
// Pull out some fields.
ClassDeclarationSyntax cds = unit.ClassDeclaration;
@ -82,7 +83,9 @@ public class SingletonComponentSourceGenerator
$" }}",
$" }}",
$"}}",
""));
""
)
);
// Create the source text and write out the file.
var sourceText = SourceText.From(buffer.ToString(), Encoding.UTF8);

View file

@ -5,9 +5,6 @@ namespace MfGames.Nitride.Generators;
public class SingletonComponentSyntaxReceiver : ClassAttributeSyntaxReceiverBase
{
/// <inheritdoc />
public SingletonComponentSyntaxReceiver(
GeneratorInitializationContext context)
: base(context, "SingletonComponent")
{
}
public SingletonComponentSyntaxReceiver(GeneratorInitializationContext context)
: base(context, "SingletonComponent") { }
}

View file

@ -1,5 +1,4 @@
using System.Text;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@ -18,14 +17,16 @@ public class WithPropertiesSourceGenerator
{
/// <inheritdoc />
protected override WithPropertiesSyntaxReceiver CreateSyntaxReceiver(
GeneratorInitializationContext context)
GeneratorInitializationContext context
)
{
return new WithPropertiesSyntaxReceiver(context);
}
protected override void GenerateClassFile(
GeneratorExecutionContext context,
ClassAttributeReference unit)
ClassAttributeReference unit
)
{
// Pull out some fields.
ClassDeclarationSyntax cds = unit.ClassDeclaration;
@ -49,8 +50,9 @@ public class WithPropertiesSourceGenerator
buffer.AppendLine(" {");
// Go through the properties of the namespace.
IEnumerable<PropertyDeclarationSyntax> properties = cds.Members
.Where(m => m.Kind() == SyntaxKind.PropertyDeclaration)
IEnumerable<PropertyDeclarationSyntax> properties = cds.Members.Where(m =>
m.Kind() == SyntaxKind.PropertyDeclaration
)
.Cast<PropertyDeclarationSyntax>();
bool first = true;
@ -58,9 +60,8 @@ public class WithPropertiesSourceGenerator
foreach (PropertyDeclarationSyntax pds in properties)
{
// See if we have a setter.
bool found = pds.AccessorList?.Accessors
.Any(x => x.Keyword.ToString() == "set")
?? false;
bool found =
pds.AccessorList?.Accessors.Any(x => x.Keyword.ToString() == "set") ?? false;
if (!found)
{
@ -83,7 +84,9 @@ public class WithPropertiesSourceGenerator
buffer.AppendLine(
string.Format(
" /// Sets the {0} value and returns the operation for chaining.",
pds.Identifier.ToString()));
pds.Identifier.ToString()
)
);
buffer.AppendLine(" /// </summary>");
@ -93,11 +96,12 @@ public class WithPropertiesSourceGenerator
" public virtual {0} With{1}({2} value)",
cds.Identifier,
pds.Identifier,
pds.Type));
pds.Type
)
);
buffer.AppendLine(" {");
buffer.AppendLine(
string.Format(" this.{0} = value;", pds.Identifier));
buffer.AppendLine(string.Format(" this.{0} = value;", pds.Identifier));
buffer.AppendLine(" return this;");
buffer.AppendLine(" }");
}

View file

@ -6,7 +6,5 @@ public class WithPropertiesSyntaxReceiver : ClassAttributeSyntaxReceiverBase
{
/// <inheritdoc />
public WithPropertiesSyntaxReceiver(GeneratorInitializationContext context)
: base(context, "WithProperties")
{
}
: base(context, "WithProperties") { }
}

Some files were not shown because too many files have changed in this diff Show more