feat: refactored code base to normalize patterns

This commit is contained in:
Dylan R. E. Moonfire 2022-06-05 13:44:51 -05:00
parent dfdecdcbae
commit 1df8a6f56b
246 changed files with 7132 additions and 19246 deletions

18
.config/dotnet-tools.json Normal file
View file

@ -0,0 +1,18 @@
{
"version": 1,
"isRoot": true,
"tools": {
"gitversion.tool": {
"version": "5.9.0",
"commands": [
"dotnet-gitversion"
]
},
"dotnet-reportgenerator-globaltool": {
"version": "5.1.3",
"commands": [
"reportgenerator"
]
}
}
}

View file

@ -1,122 +1,207 @@
root = true
# EditorConfig is awesome: https://EditorConfig.org # EditorConfig is awesome: https://EditorConfig.org
root = true
[*] [*]
charset=utf-8 charset = utf-8
end_of_line = lf end_of_line = lf
insert_final_newline=true insert_final_newline = true
indent_style=space indent_style = space
indent_size=4 indent_size = 4
# Microsoft .NET properties # Microsoft .NET properties
csharp_new_line_before_members_in_object_initializers=false 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, 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:suggestion
csharp_style_var_elsewhere=false:hint csharp_style_var_for_built_in_types = false:suggestion
csharp_style_var_for_built_in_types=false:hint csharp_style_var_when_type_is_apparent = true:suggestion
csharp_style_var_when_type_is_apparent=true:hint csharp_preserve_single_line_statements = false
csharp_preserve_single_line_statements=false dotnet_naming_rule.event_rule.import_to_resharper = as_predefined
csharp_preserve_single_line_blocks=true dotnet_naming_rule.event_rule.severity = warning
dotnet_style_predefined_type_for_locals_parameters_members=true:hint dotnet_naming_rule.event_rule.style = upper_camel_case_underscore_tolerant_style
dotnet_style_predefined_type_for_member_access=true:hint dotnet_naming_rule.event_rule.symbols = event_symbols
dotnet_style_qualification_for_event=true:hint dotnet_naming_rule.local_constants_rule.import_to_resharper = as_predefined
dotnet_style_qualification_for_field=true:hint dotnet_naming_rule.local_constants_rule.severity = warning
dotnet_style_qualification_for_method=true:hint dotnet_naming_rule.local_constants_rule.style = upper_camel_case_style
dotnet_style_qualification_for_property=true:hint dotnet_naming_rule.local_constants_rule.symbols = local_constants_symbols
dotnet_style_require_accessibility_modifiers=for_non_interface_members:hint dotnet_naming_rule.private_constants_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_constants_rule.severity = warning
dotnet_naming_rule.private_constants_rule.style = upper_camel_case_style
dotnet_naming_rule.private_constants_rule.symbols = private_constants_symbols
dotnet_naming_rule.private_instance_fields_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_instance_fields_rule.severity = warning
dotnet_naming_rule.private_instance_fields_rule.style = lower_camel_case_style
dotnet_naming_rule.private_instance_fields_rule.symbols = private_instance_fields_symbols
dotnet_naming_rule.private_static_fields_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_static_fields_rule.resharper_style = AaBb, aaBb
dotnet_naming_rule.private_static_fields_rule.severity = warning
dotnet_naming_rule.private_static_fields_rule.style = upper_camel_case_style
dotnet_naming_rule.private_static_fields_rule.symbols = private_static_fields_symbols
dotnet_naming_rule.private_static_readonly_rule.import_to_resharper = as_predefined
dotnet_naming_rule.private_static_readonly_rule.severity = warning
dotnet_naming_rule.private_static_readonly_rule.style = upper_camel_case_style
dotnet_naming_rule.private_static_readonly_rule.symbols = private_static_readonly_symbols
dotnet_naming_style.lower_camel_case_style.capitalization = camel_case
dotnet_naming_style.upper_camel_case_style.capitalization = pascal_case
dotnet_naming_style.upper_camel_case_underscore_tolerant_style.capitalization = pascal_case
dotnet_naming_style.upper_camel_case_underscore_tolerant_style.word_separator = _
dotnet_naming_symbols.event_symbols.applicable_accessibilities = *
dotnet_naming_symbols.event_symbols.applicable_kinds = event
dotnet_naming_symbols.local_constants_symbols.applicable_accessibilities = *
dotnet_naming_symbols.local_constants_symbols.applicable_kinds = local
dotnet_naming_symbols.local_constants_symbols.required_modifiers = const
dotnet_naming_symbols.private_constants_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_constants_symbols.applicable_kinds = field
dotnet_naming_symbols.private_constants_symbols.required_modifiers = const
dotnet_naming_symbols.private_instance_fields_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_instance_fields_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_fields_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_static_fields_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_fields_symbols.required_modifiers = static
dotnet_naming_symbols.private_static_readonly_symbols.applicable_accessibilities = private
dotnet_naming_symbols.private_static_readonly_symbols.applicable_kinds = field
dotnet_naming_symbols.private_static_readonly_symbols.required_modifiers = static, readonly
dotnet_separate_import_directive_groups = true
dotnet_style_parentheses_in_arithmetic_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_other_binary_operators = never_if_unnecessary:none
dotnet_style_parentheses_in_relational_binary_operators = never_if_unnecessary:none
dotnet_style_predefined_type_for_locals_parameters_members = true:suggestion
dotnet_style_predefined_type_for_member_access = true:suggestion
dotnet_style_qualification_for_event = true:suggestion
dotnet_style_qualification_for_field = true:suggestion
dotnet_style_qualification_for_method = true:suggestion
dotnet_style_qualification_for_property = true:suggestion
dotnet_style_require_accessibility_modifiers = for_non_interface_members:suggestion
# ReSharper properties # ReSharper properties
resharper_alignment_tab_fill_style=optimal_fill resharper_alignment_tab_fill_style = optimal_fill
resharper_apply_on_completion=true resharper_align_multiline_binary_expressions_chain = false
resharper_blank_lines_after_control_transfer_statements=1 resharper_apply_on_completion = true
resharper_blank_lines_around_single_line_auto_property=1 resharper_autodetect_indent_settings = true
resharper_blank_lines_around_single_line_property=1 resharper_blank_lines_after_control_transfer_statements = 1
resharper_blank_lines_before_single_line_comment=1 resharper_blank_lines_around_single_line_auto_property = 1
resharper_blank_lines_between_using_groups=1 resharper_blank_lines_around_single_line_property = 1
resharper_braces_for_for=required resharper_blank_lines_before_single_line_comment = 1
resharper_braces_for_foreach=required resharper_braces_for_for = required
resharper_braces_for_ifelse=required resharper_braces_for_foreach = required
resharper_braces_for_while=required resharper_braces_for_ifelse = required
resharper_can_use_global_alias=false resharper_braces_for_while = required
resharper_csharp_blank_lines_around_single_line_field=1 resharper_can_use_global_alias = false
resharper_csharp_blank_lines_around_single_line_invocable=1 resharper_continuous_indent_multiplier = 1
resharper_csharp_indent_style=tab resharper_cpp_alignment_tab_fill_style = optimal_fill
resharper_csharp_insert_final_newline=true resharper_cpp_insert_final_newline = true
resharper_csharp_keep_blank_lines_in_code=1 resharper_csharp_alignment_tab_fill_style = use_spaces
resharper_csharp_keep_blank_lines_in_declarations=1 resharper_csharp_blank_lines_around_single_line_field = 1
resharper_csharp_new_line_before_while=true resharper_csharp_blank_lines_around_single_line_invocable = 1
resharper_csharp_use_indent_from_vs=false resharper_csharp_indent_style = space
resharper_csharp_wrap_arguments_style=chop_if_long resharper_csharp_insert_final_newline = true
resharper_csharp_wrap_extends_list_style=chop_if_long resharper_csharp_keep_blank_lines_in_code = 1
resharper_csharp_wrap_parameters_style=chop_if_long resharper_csharp_keep_blank_lines_in_declarations = 1
resharper_css_insert_final_newline=false resharper_csharp_max_line_length = 120
resharper_enforce_line_ending_style=true resharper_csharp_naming_rule.method_property_event = AaBb_AaBb
resharper_html_insert_final_newline=false resharper_csharp_naming_rule.private_constants = AaBb
resharper_indent_nested_fixed_stmt=true resharper_csharp_naming_rule.private_static_fields = AaBb, aaBb
resharper_js_indent_style=tab resharper_csharp_naming_rule.private_static_readonly = AaBb
resharper_js_insert_final_newline=true resharper_csharp_stick_comment = false
resharper_js_keep_blank_lines_in_code=1 resharper_csharp_wrap_arguments_style = chop_if_long
resharper_js_stick_comment=false resharper_csharp_wrap_before_binary_opsign = true
resharper_js_use_indent_from_vs=false resharper_csharp_wrap_extends_list_style = chop_if_long
resharper_js_wrap_before_binary_opsign=true resharper_csharp_wrap_parameters_style = chop_if_long
resharper_js_wrap_chained_method_calls=chop_if_long resharper_css_insert_final_newline = true
resharper_keep_blank_lines_between_declarations=1 resharper_default_exception_variable_name = exception
resharper_min_blank_lines_after_imports=1 resharper_enforce_line_ending_style = true
resharper_place_attribute_on_same_line=False resharper_event_handler_pattern_long = On$event$
resharper_place_constructor_initializer_on_same_line=false resharper_html_alignment_tab_fill_style = optimal_fill
resharper_place_type_constraints_on_same_line=false resharper_indent_nested_fixed_stmt = true
resharper_protobuf_insert_final_newline=false resharper_js_indent_style = tab
resharper_qualified_using_at_nested_scope=true resharper_js_insert_final_newline = true
resharper_resx_insert_final_newline=false resharper_js_keep_blank_lines_in_code = 1
resharper_space_within_single_line_array_initializer_braces=true resharper_js_stick_comment = false
resharper_use_indents_from_main_language_in_file=false resharper_js_use_indent_from_vs = false
resharper_vb_insert_final_newline=false resharper_js_wrap_before_binary_opsign = true
resharper_wrap_after_declaration_lpar=true resharper_js_wrap_chained_method_calls = chop_if_long
resharper_wrap_after_invocation_lpar=true resharper_keep_blank_lines_between_declarations = 1
resharper_wrap_before_extends_colon=true resharper_keep_existing_declaration_block_arrangement = true
resharper_wrap_before_first_type_parameter_constraint=true resharper_keep_existing_declaration_parens_arrangement = false
resharper_wrap_before_type_parameter_langle=true resharper_keep_existing_embedded_block_arrangement = true
resharper_xmldoc_indent_child_elements=ZeroIndent resharper_keep_existing_enum_arrangement = true
resharper_xmldoc_indent_text=ZeroIndent resharper_min_blank_lines_after_imports = 1
resharper_xmldoc_insert_final_newline=false resharper_nested_ternary_style = expanded
resharper_xml_insert_final_newline=false resharper_new_line_before_while = true
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 = true
resharper_qualified_using_at_nested_scope = true
resharper_resx_alignment_tab_fill_style = optimal_fill
resharper_T4_alignment_tab_fill_style = optimal_fill
resharper_t4_insert_final_newline = true
resharper_use_continuous_indent_inside_initializer_braces = false
resharper_use_indents_from_main_language_in_file = false
resharper_use_indent_from_vs = false
resharper_vb_alignment_tab_fill_style = optimal_fill
resharper_wrap_after_declaration_lpar = true
resharper_wrap_after_invocation_lpar = true
resharper_wrap_array_initializer_style = chop_if_long
resharper_wrap_before_extends_colon = true
resharper_wrap_before_first_type_parameter_constraint = true
resharper_wrap_before_type_parameter_langle = true
resharper_wrap_chained_binary_expressions = chop_if_long
resharper_wrap_chained_method_calls = chop_if_long
resharper_wrap_object_and_collection_initializer_style = chop_always
resharper_xmldoc_alignment_tab_fill_style = optimal_fill
resharper_xmldoc_indent_child_elements = ZeroIndent
resharper_xmldoc_indent_text = ZeroIndent
resharper_xmldoc_max_line_length = 80
resharper_xml_alignment_tab_fill_style = optimal_fill
# ReSharper inspection severities # ReSharper inspection severities
resharper_check_namespace_highlighting=none resharper_arrange_redundant_parentheses_highlighting = hint
resharper_convert_to_auto_property_highlighting=none resharper_arrange_this_qualifier_highlighting = hint
resharper_localizable_element_highlighting=none resharper_arrange_type_member_modifiers_highlighting = hint
resharper_redundant_comma_in_attribute_list_highlighting=none resharper_arrange_type_modifiers_highlighting = hint
resharper_redundant_comma_in_enum_declaration_highlighting=none resharper_built_in_type_reference_style_for_member_access_highlighting = hint
resharper_redundant_comma_in_initializer_highlighting=none resharper_built_in_type_reference_style_highlighting = hint
resharper_string_compare_to_is_culture_specific_highlighting=none resharper_check_namespace_highlighting = none
resharper_string_index_of_is_culture_specific_1_highlighting=none resharper_convert_to_auto_property_highlighting = none
resharper_use_null_propagation_highlighting=none resharper_localizable_element_highlighting = none
resharper_use_object_or_collection_initializer_highlighting=hint resharper_redundant_comma_in_attribute_list_highlighting = none
resharper_use_string_interpolation_highlighting=hint 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_suggest_var_or_type_built_in_types_highlighting = hint
resharper_suggest_var_or_type_elsewhere_highlighting = hint
resharper_suggest_var_or_type_simple_types_highlighting = hint
resharper_use_null_propagation_highlighting = none
resharper_use_object_or_collection_initializer_highlighting = hint
resharper_use_string_interpolation_highlighting = hint
resharper_web_config_module_not_resolved_highlighting = warning
resharper_web_config_type_not_resolved_highlighting = warning
resharper_web_config_wrong_module_highlighting = warning
trim_trailing_whitespace = false
# Matches the exact files either package.json or .travis.yml # Matches the exact files either package.json or .travis.yml
[{package.json,.travis.yml}] [{package.json,.travis.yml}]
indent_style=space indent_style = space
indent_size=2 indent_size = 2
tab_width=2 tab_width = 2
[*.{cs,js,json,jsx,proto,resjson,ts,tsx}]
indent_style=space
indent_size=space
tab_width=4
[*.{asax,ascx,aspx,cshtml,css,htm,html,master,razor,skin,vb,xaml,xamlx,xoml}]
indent_style=space
indent_size=4
tab_width=4
[*.{appxmanifest,build,config,csproj,dbml,discomap,dtd,jsproj,lsproj,njsproj,nuspec,proj,props,resw,resx,StyleCop,targets,tasks,vbproj,xml,xsd}] [*.{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_style = space
indent_size=2 indent_size = 2
tab_width=2 tab_width = 2
[*.proto] [*.proto]
indent_style=space indent_style = space
indent_size=2 indent_size = 2
tab_width=2 tab_width = 2
[*.cs]
indent_style = space
indent_size = 4
tab_width = 4
[*.{appxmanifest,asax,ascx,aspx,axaml,build,cg,cginc,compute,cs,cshtml,dtd,hlsl,hlsli,hlslinc,master,nuspec,paml,razor,resw,resx,skin,usf,ush,vb,xaml,xamlx,xoml,xsd}]
indent_style = space
indent_size = 4
tab_width = 4

6
.envrc
View file

@ -1 +1,5 @@
use nix # Insert our scripts into the path.
export PATH=$PWD/scripts:$PATH
# Nix flakes are awesome.
use flake

4
.gitignore vendored
View file

@ -12,3 +12,7 @@ obj/
_ReSharper.Caches/ _ReSharper.Caches/
node_modules/ node_modules/
.direnv/ .direnv/
coverage
TestResults/
tests/artifacts/
.lefthook*

View file

@ -1,67 +1,45 @@
include: include:
- template: Security/SAST.gitlab-ci.yml - template: Security/SAST.gitlab-ci.yml
# Nix handling based on https://gitlab.com/Vonfry/gitlab-ci-nix/-/blob/master/.gitlab-ci.yml
stages: stages:
- build - build
- test - test
- release - release
variables:
GIT_SUBMODULE_STRATEGY: recursive
LOCAL_NIX_STORE: $CI_PROJECT_DIR/.nix/store
default: default:
image: nixos/nix:latest image: registry.gitlab.com/dmoonfire/nix-flake-docker:latest
before_script:
- "[ -f $LOCAL_NIX_STORE ] && nix-store --import < $LOCAL_NIX_STORE"
after_script:
- "[ ! -d $(dirname \"$LOCAL_NIX_STORE\") ] && mkdir -p $LOCAL_NIX_STORE"
- "[ -h ./result ] && nix-store --export $(nix-store --query --requisites --include-outputs ./result) > $LOCAL_NIX_STORE"
cache:
paths:
- .nix/
build: build:
stage: build stage: build
script: script:
- nix-shell --run "npm install --ci" - nix develop --command scripts/build.sh
- nix-shell --run "npx commitlint-gitlab-ci -x @commitlint/config-conventional"
- nix-shell --run "npm run build"
rules: rules:
- if: $CI_COMMIT_BRANCH - if: $CI_COMMIT_BRANCH
#test: test:
# stage: test stage: test
# script: script:
# - nix-shell --run "npm run test" - nix develop --command scripts/test.sh
# # Testing is currently not working. artifacts:
# #- 'dotnet test --test-adapter-path:. --logger:"junit;LogFilePath=../artifacts/{assembly}-test-result.xml;MethodFormat=Default;FailureBodyFormat=Verbose" --collect:"XPlat Code Coverage"' when: always
# paths:
# # Summarize the output for Gitlab CI reporting. - ./**/*test-result.xml
# #- dotnet new tool-manifest - ./coverage/Cobertura.xml
# #- dotnet tool install dotnet-reportgenerator-globaltool - ./coverage/Summary.*
# #- dotnet tool run reportgenerator -reports:src/*/TestResults/*/coverage.cobertura.xml -targetdir:./coverage "-reporttypes:Cobertura;TextSummary" - ./**/*.nupkg
# #- grep "Line coverage" coverage/Summary.txt reports:
# artifacts: junit:
# when: always - ./**/*test-result.xml
# paths: cobertura:
# - ./**/*test-result.xml - ./coverage/Cobertura.xml
# - ./coverage/Cobertura.xml
# - ./coverage/Summary.*
# - ./**/*.nupkg
# reports:
# junit:
# - ./**/*test-result.xml
# cobertura:
# - ./coverage/Cobertura.xml
publish: publish:
stage: release stage: release
before_script:
# Set it up so we can push the tag
- project_url=$(echo $CI_PROJECT_URL | sed 's/https:\/\///')
- git remote set-url origin https://oauth2:$GITLAB_TOKEN@$project_url
script: script:
- nix-shell --run "npm install --ci" - nix develop --command scripts/release.sh
- nix-shell --run "npm run build"
- nix-shell --run "npx semantic-release"
rules: rules:
- if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH - if: $CI_COMMIT_BRANCH == $CI_DEFAULT_BRANCH

View file

@ -1,4 +0,0 @@
#!/bin/sh
. "$(dirname "$0")/_/husky.sh"
npx --no-install commitlint --edit $1

8
.prettierignore Normal file
View file

@ -0,0 +1,8 @@
*~
flake.*
node_modules/
.direnv/
.config/
obj/
bin/

View file

@ -1,48 +0,0 @@
# Building
## Environment
To simplify environmental setup, this project uses the following:
- [Nix](https://nixos.org/)
- [direnv](https://direnv.net/)
Nix does not require the full NixOS (the operating system component), just a single- or multi-user setup. `direnv` is used to automatically configure the environment when entering the directory including setting up the needed PATH and other environment variables for the build.
### Working Without Nix
If not using Nix to set up the environment, look at `buildInputs` in [./shell.nix](./shell.nix) which includes the tools require for building (such as a specific version of Yarn, .NET Core, and the like).
`shell.nix` along with the data inside the `nix/` folder is considered the source of truth of dependencies and requirements for this project.
### Node and Yarn
Node is used as both the package metadata format (package version) and also build processes. We use [Husky]() to automatically set up Git hooks, [commitlint]() to ensure consistent check-ins that work with [semantic-release]() which automates the build process.
Setting up the environment consists of:
```
npm install
```
## Building
The preferred method for building is:
```
npm run build
```
This ensures everything is properly run. A short-cut can be to call the `dotnet build` directly.
```
dotnet build
```
## Testing
Again, the preferred method of testing is:
```
npm test
```

View file

@ -1,6 +0,0 @@
# 1.0.0 (2021-09-07)
### Features
* initial release ([78054ee](https://gitlab.com/mfgames-cil/nitride-cil/commit/78054ee2a72ca453cc2364427f864aca68dfae78))

View file

@ -1,4 +1,3 @@
# Contributor Covenant Code of Conduct # Contributor Covenant Code of Conduct
## Our Pledge ## Our Pledge
@ -18,24 +17,24 @@ diverse, inclusive, and healthy community.
Examples of behavior that contributes to a positive environment for our Examples of behavior that contributes to a positive environment for our
community include: community include:
* Demonstrating empathy and kindness toward other people - Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences - Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback - Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes, - Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience and learning from the experience
* Focusing on what is best not just for us as individuals, but for the overall - Focusing on what is best not just for us as individuals, but for the overall
community community
Examples of unacceptable behavior include: Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or advances of - The use of sexualized language or imagery, and sexual attention or advances of
any kind any kind
* Trolling, insulting or derogatory comments, and personal or political attacks - Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment - Public or private harassment
* Publishing others' private information, such as a physical or email address, - Publishing others' private information, such as a physical or email address,
without their explicit permission without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a - Other conduct which could reasonably be considered inappropriate in a
professional setting professional setting
## Enforcement Responsibilities ## Enforcement Responsibilities
@ -120,15 +119,14 @@ version 2.1, available at
[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. [https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1].
Community Impact Guidelines were inspired by Community Impact Guidelines were inspired by
[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. [Mozilla's code of conduct enforcement ladder][mozilla coc].
For answers to common questions about this code of conduct, see the FAQ at 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/faq][faq]. Translations are available at
[https://www.contributor-covenant.org/translations][translations]. [https://www.contributor-covenant.org/translations][translations].
[homepage]: https://www.contributor-covenant.org [homepage]: https://www.contributor-covenant.org
[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html [v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html
[Mozilla CoC]: https://github.com/mozilla/diversity [mozilla coc]: https://github.com/mozilla/diversity
[FAQ]: https://www.contributor-covenant.org/faq [faq]: https://www.contributor-covenant.org/faq
[translations]: https://www.contributor-covenant.org/translations [translations]: https://www.contributor-covenant.org/translations

660
LICENSE.md Normal file
View file

@ -0,0 +1,660 @@
### GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
<https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies of this
license document, but changing it is not allowed.
### Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains
free software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing
under this license.
The precise terms and conditions for copying, distribution and
modification follow.
### TERMS AND CONDITIONS
#### 0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public
License.
"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of
an exact copy. The resulting work is called a "modified version" of
the earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user
through a computer network, with no transfer of a copy, is not
conveying.
An interactive user interface displays "Appropriate Legal Notices" to
the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
#### 1. Source Code.
The "source code" for a work means the preferred form of the work for
making modifications to it. "Object code" means any non-source form of
a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users can
regenerate automatically from other parts of the Corresponding Source.
The Corresponding Source for a work in source code form is that same
work.
#### 2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not convey,
without conditions so long as your license otherwise remains in force.
You may convey covered works to others for the sole purpose of having
them make modifications exclusively for you, or provide you with
facilities for running those works, provided that you comply with the
terms of this License in conveying all material for which you do not
control copyright. Those thus making or running the covered works for
you must do so exclusively on your behalf, under your direction and
control, on terms that prohibit them from making any copies of your
copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under the
conditions stated below. Sublicensing is not allowed; section 10 makes
it unnecessary.
#### 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such
circumvention is effected by exercising rights under this License with
respect to the covered work, and you disclaim any intention to limit
operation or modification of the work as a means of enforcing, against
the work's users, your or third parties' legal rights to forbid
circumvention of technological measures.
#### 4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
#### 5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these
conditions:
- a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
- b) The work must carry prominent notices stating that it is
released under this License and any conditions added under
section 7. This requirement modifies the requirement in section 4
to "keep intact all notices".
- c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
- d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
#### 6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms of
sections 4 and 5, provided that you also convey the machine-readable
Corresponding Source under the terms of this License, in one of these
ways:
- a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
- b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the Corresponding
Source from a network server at no charge.
- c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
- d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
- e) Convey the object code using peer-to-peer transmission,
provided you inform other peers where the object code and
Corresponding Source of the work are being offered to the general
public at no charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal,
family, or household purposes, or (2) anything designed or sold for
incorporation into a dwelling. In determining whether a product is a
consumer product, doubtful cases shall be resolved in favor of
coverage. For a particular product received by a particular user,
"normally used" refers to a typical or common use of that class of
product, regardless of the status of the particular user or of the way
in which the particular user actually uses, or expects or is expected
to use, the product. A product is a consumer product regardless of
whether the product has substantial commercial, industrial or
non-consumer uses, unless such uses represent the only significant
mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to
install and execute modified versions of a covered work in that User
Product from a modified version of its Corresponding Source. The
information must suffice to ensure that the continued functioning of
the modified object code is in no case prevented or interfered with
solely because modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or
updates for a work that has been modified or installed by the
recipient, or for the User Product in which it has been modified or
installed. Access to a network may be denied when the modification
itself materially and adversely affects the operation of the network
or violates the rules and protocols for communication across the
network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
#### 7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders
of that material) supplement the terms of this License with terms:
- a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
- b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
- c) Prohibiting misrepresentation of the origin of that material,
or requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
- d) Limiting the use for publicity purposes of names of licensors
or authors of the material; or
- e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
- f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions
of it) with contractual assumptions of liability to the recipient,
for any liability that these contractual assumptions directly
impose on those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions; the
above requirements apply either way.
#### 8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your license
from a particular copyright holder is reinstated (a) provisionally,
unless and until the copyright holder explicitly and finally
terminates your license, and (b) permanently, if the copyright holder
fails to notify you of the violation by some reasonable means prior to
60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
#### 9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or run
a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
#### 10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
#### 11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims owned
or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within the
scope of its coverage, prohibits the exercise of, or is conditioned on
the non-exercise of one or more of the rights that are specifically
granted under this License. You may not convey a covered work if you
are a party to an arrangement with a third party that is in the
business of distributing software, under which you make payment to the
third party based on the extent of your activity of conveying the
work, and under which the third party grants, to any of the parties
who would receive the covered work from you, a discriminatory patent
license (a) in connection with copies of the covered work conveyed by
you (or copies made from those copies), or (b) primarily for and in
connection with specific products or compilations that contain the
covered work, unless you entered into that arrangement, or that patent
license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
#### 12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under
this License and any other pertinent obligations, then as a
consequence you may not convey it at all. For example, if you agree to
terms that obligate you to collect a royalty for further conveying
from those to whom you convey the Program, the only way you could
satisfy both those terms and this License would be to refrain entirely
from conveying the Program.
#### 13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your
version supports such interaction) an opportunity to receive the
Corresponding Source of your version by providing access to the
Corresponding Source from a network server at no charge, through some
standard or customary means of facilitating copying of software. This
Corresponding Source shall include the Corresponding Source for any
work covered by version 3 of the GNU General Public License that is
incorporated pursuant to the following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
#### 14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever
published by the Free Software Foundation.
If the Program specifies that a proxy can decide which future versions
of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
#### 15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT
WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND
PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE
DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR
CORRECTION.
#### 16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR
CONVEYS THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES
ARISING OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT
NOT LIMITED TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR
LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM
TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER
PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
#### 17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
### How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these
terms.
To do so, attach the following notices to the program. It is safest to
attach them to the start of each source file to most effectively state
the exclusion of warranty; and each file should have at least the
"copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper
mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for
the specific requirements.
You should also get your employer (if you work as a programmer) or
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. For more information on this, and how to apply and follow
the GNU AGPL, see <https://www.gnu.org/licenses/>.

View file

@ -1,21 +0,0 @@
MIT License
Copyright (c) Moonfire Games
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -19,8 +19,6 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nitride.Html", "src\Nitride
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nitride.IO", "src\Nitride.IO\Nitride.IO.csproj", "{534BF940-25B2-4948-A101-7890CC9C4EA5}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nitride.IO", "src\Nitride.IO\Nitride.IO.csproj", "{534BF940-25B2-4948-A101-7890CC9C4EA5}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nitride.Javascript", "src\Nitride.Javascript\Nitride.Javascript.csproj", "{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nitride.Markdown", "src\Nitride.Markdown\Nitride.Markdown.csproj", "{41FF3823-7008-43B1-AD6A-92437E0600B7}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nitride.Markdown", "src\Nitride.Markdown\Nitride.Markdown.csproj", "{41FF3823-7008-43B1-AD6A-92437E0600B7}"
EndProject EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nitride", "src\Nitride\Nitride.csproj", "{757BA115-3465-46C5-ADDB-7B96D6900F33}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Nitride", "src\Nitride\Nitride.csproj", "{757BA115-3465-46C5-ADDB-7B96D6900F33}"
@ -140,18 +138,6 @@ Global
{534BF940-25B2-4948-A101-7890CC9C4EA5}.Release|x64.Build.0 = Release|Any CPU {534BF940-25B2-4948-A101-7890CC9C4EA5}.Release|x64.Build.0 = Release|Any CPU
{534BF940-25B2-4948-A101-7890CC9C4EA5}.Release|x86.ActiveCfg = Release|Any CPU {534BF940-25B2-4948-A101-7890CC9C4EA5}.Release|x86.ActiveCfg = Release|Any CPU
{534BF940-25B2-4948-A101-7890CC9C4EA5}.Release|x86.Build.0 = Release|Any CPU {534BF940-25B2-4948-A101-7890CC9C4EA5}.Release|x86.Build.0 = Release|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Debug|Any CPU.Build.0 = Debug|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Debug|x64.ActiveCfg = Debug|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Debug|x64.Build.0 = Debug|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Debug|x86.ActiveCfg = Debug|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Debug|x86.Build.0 = Debug|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Release|Any CPU.ActiveCfg = Release|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Release|Any CPU.Build.0 = Release|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Release|x64.ActiveCfg = Release|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Release|x64.Build.0 = Release|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Release|x86.ActiveCfg = Release|Any CPU
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C}.Release|x86.Build.0 = Release|Any CPU
{41FF3823-7008-43B1-AD6A-92437E0600B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {41FF3823-7008-43B1-AD6A-92437E0600B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{41FF3823-7008-43B1-AD6A-92437E0600B7}.Debug|Any CPU.Build.0 = Debug|Any CPU {41FF3823-7008-43B1-AD6A-92437E0600B7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{41FF3823-7008-43B1-AD6A-92437E0600B7}.Debug|x64.ActiveCfg = Debug|Any CPU {41FF3823-7008-43B1-AD6A-92437E0600B7}.Debug|x64.ActiveCfg = Debug|Any CPU
@ -269,7 +255,6 @@ Global
{56E595A6-7880-416E-B328-93B9617F92A6} = {570184FD-ECE4-4EC8-86E1-C1265E17D647} {56E595A6-7880-416E-B328-93B9617F92A6} = {570184FD-ECE4-4EC8-86E1-C1265E17D647}
{3F9292D3-DA50-4DBA-AE90-E33E462470A1} = {570184FD-ECE4-4EC8-86E1-C1265E17D647} {3F9292D3-DA50-4DBA-AE90-E33E462470A1} = {570184FD-ECE4-4EC8-86E1-C1265E17D647}
{534BF940-25B2-4948-A101-7890CC9C4EA5} = {570184FD-ECE4-4EC8-86E1-C1265E17D647} {534BF940-25B2-4948-A101-7890CC9C4EA5} = {570184FD-ECE4-4EC8-86E1-C1265E17D647}
{285A855E-B2FC-4770-AFD9-4CC67AD3C83C} = {570184FD-ECE4-4EC8-86E1-C1265E17D647}
{41FF3823-7008-43B1-AD6A-92437E0600B7} = {570184FD-ECE4-4EC8-86E1-C1265E17D647} {41FF3823-7008-43B1-AD6A-92437E0600B7} = {570184FD-ECE4-4EC8-86E1-C1265E17D647}
{757BA115-3465-46C5-ADDB-7B96D6900F33} = {570184FD-ECE4-4EC8-86E1-C1265E17D647} {757BA115-3465-46C5-ADDB-7B96D6900F33} = {570184FD-ECE4-4EC8-86E1-C1265E17D647}
{17BF2A03-2C1D-4F75-9C18-B4341FAAF1A5} = {570184FD-ECE4-4EC8-86E1-C1265E17D647} {17BF2A03-2C1D-4F75-9C18-B4341FAAF1A5} = {570184FD-ECE4-4EC8-86E1-C1265E17D647}

View file

@ -1,4 +1,19 @@
Nitride CIL # Nitride CIL
===========
A static site generator based on the [Gallium ECS](https://gitlab.com/mfgames-cil/gallium-cil/). A static site generator written in C#.
## Entity Component System
It is build on [Gallium ECS](https://gitlab.com/mfgames-cil/gallium-cil/), an [entity-component-system](https://en.wikipedia.org/wiki/Entity_component_system) that allows for a flexibility of adding and removing aspects of individual files including creating new ones from JSON/YAML, web servers, or the file system. Additional markers and details can be added without significant changes, allowing for new concepts that weren't envisioned by the original developers.
## Configuration as Code
Because it can be difficult to explain the complexities of a website with just a collection of templates and scripts, this library uses C# for the configuration. In effect, you create a program that generates a website from source files.
## Unix Philosophy
This library is designed with the [Unix Philosophy](https://en.wikipedia.org/wiki/Unix_philosophy):
> Do one thing well.
It generates website HTML from a variety of sources (mostly Markdown). The core library doesn't try to wrangle Javascript or minify CSS. It doesn't have plugins for pushing up to S3 or copy files. Those are things [Webpack](https://webpack.js.org/), [Parcel](https://parceljs.org/), `scp`, or other tools specialize in.

View file

@ -1,6 +1,27 @@
# Tasks # Tasks
- [ ] Does not return a proper code when failing - [ ] Create Nitride.Core that doesn't depend on Serilog and Autofac?
- [ ] CopyFiles sample does not generate data
- [ ] ReadFiles should have With methods ## CLI
- [ ] WriteFiles should have With methods
- [ ] `watch` command to generate pages
- [ ] Fancy Specter-based display
## Testing
Write tests for the following namespaces:
- [ ] Calendar
- [ ] Feeds
- [ ] Gemtext
- [ ] Handlebars
- [ ] Html
- [x] IO
- [ ] Markdown
- [ ] Slugs
- [ ] Temporal
- [ ] Yaml
## Examples
- [ ] Write more examples

View file

@ -1,3 +0,0 @@
module.exports = {
extends: ["@commitlint/config-conventional"],
};

View file

@ -2,26 +2,26 @@
<PropertyGroup> <PropertyGroup>
<OutputType>Exe</OutputType> <OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\..\src\Nitride.IO\Nitride.IO.csproj" /> <ProjectReference Include="..\..\src\Nitride.IO\Nitride.IO.csproj"/>
<ProjectReference Include="..\..\src\Nitride\Nitride.csproj" /> <ProjectReference Include="..\..\src\Nitride\Nitride.csproj"/>
<ProjectReference Include="..\..\tests\Nitride.Tests\Nitride.Tests.csproj" /> <ProjectReference Include="..\..\tests\Nitride.Tests\Nitride.Tests.csproj"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="CliWrap" Version="3.3.3" /> <PackageReference Include="CliWrap" Version="3.4.4"/>
<PackageReference Include="JunitXml.TestLogger" Version="3.0.110" /> <PackageReference Include="JunitXml.TestLogger" Version="3.0.114"/>
<PackageReference Include="xunit" Version="2.4.1" /> <PackageReference Include="xunit" Version="2.4.1"/>
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.3"> <PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference> </PackageReference>
<PackageReference Include="MfGames.IO" Version="1.2.3" /> <PackageReference Include="MfGames.IO" Version="1.2.3"/>
<PackageReference Include="coverlet.collector" Version="3.0.3"> <PackageReference Include="coverlet.collector" Version="3.1.2">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets> <PrivateAssets>all</PrivateAssets>
</PackageReference> </PackageReference>

View file

@ -1,20 +1,15 @@
using Autofac; using Autofac;
namespace CopyFiles namespace CopyFiles;
public class CopyFilesModule : Module
{ {
public class CopyFilesModule : Module /// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{ {
/// <inheritdoc /> // This just registers all the non-static classes as singletons
protected override void Load(ContainerBuilder builder) // within the system. We use lifetimes in other components depending
{ // on how they are used, but in this case, we don't need it.
// This just registers all the non-static classes as singletons builder.RegisterAssemblyTypes(this.GetType().Assembly).AsSelf().AsImplementedInterfaces().SingleInstance();
// within the system. We use lifetimes in other components depending
// on how they are used, but in this case, we don't need it.
builder
.RegisterAssemblyTypes(this.GetType().Assembly)
.AsSelf()
.AsImplementedInterfaces()
.SingleInstance();
}
} }
} }

View file

@ -1,39 +1,106 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Threading.Tasks; using System.Threading.Tasks;
using Gallium; using Gallium;
using Nitride;
using Nitride.IO.Contents; using Nitride.IO.Contents;
using Nitride.IO.Directories;
using Nitride.IO.Paths;
using Nitride.Pipelines; using Nitride.Pipelines;
namespace CopyFiles namespace CopyFiles;
/// <summary>
/// The single pipeline used by the CopyFiles project.
/// </summary>
public class CopyFilesPipeline : PipelineBase
{ {
/// <summary> private readonly AddPathPrefix addPathPrefix;
/// The single pipeline used by the CopyFiles project.
/// </summary> private readonly ClearDirectory clearDirectory;
public class CopyFilesPipeline : PipelineBase
private readonly ReadFiles readFiles;
private readonly RemovePathPrefix removePathPrefix;
private readonly WriteFiles writeFiles;
public CopyFilesPipeline(
ReadFiles readFiles,
ClearDirectory clearDirectory,
WriteFiles writeFiles,
RemovePathPrefix removePathPrefix,
AddPathPrefix addPathPrefix)
{ {
private readonly ReadFiles readFiles; // While we can configure these during runtime, it seems cleaner to
// build them up during the constructor to call out the ones that
// require runtime data.
this.readFiles = readFiles.WithPattern("/input/**/*.txt");
this.clearDirectory = clearDirectory.WithPath("/output");
this.writeFiles = writeFiles;
this.removePathPrefix = removePathPrefix.WithPathPrefix("/input");
this.addPathPrefix = addPathPrefix.WithPathPrefix("/output");
}
private readonly WriteFiles writeFiles; /// <inheritdoc />
public override Task<IEnumerable<Entity>> RunAsync(IEnumerable<Entity> _)
{
// We don't care about the incoming entities which means we can
// ignore them and use the entities from the ReadFiles operation
// or we can union the entities pass in with the ReadFiles in case
// we want to merge them.
//
// This will read all the files of the given pattern and return them
// as an IEnumerable<Entity> with the Zio components (UPath and
// binary contents) set. As a note, this doesn't actually read the
// file, just create a pointer to where the file could be read from.
//
// The path component will always be the relative path to the root,
// so `/input/a.txt` in this case since we only have one file.
IEnumerable<Entity> entities = this.readFiles.Run();
public CopyFilesPipeline( // Change the path. The path (Zio.UPath component) stays with the
ReadFiles readFiles, // entity which is why there is no root directory in the writeFiles
WriteFiles writeFiles) // operation. Instead, we need to remove the `/input` and replace it
{ // with the `/output`.
// While we can configure these during runtime, it seems cleaner to //
// build them up during the constructor to call out the ones that // We can do that with a RemovePathPrefix followed by an
// require runtime data. // AddPathPrefix, or use the more complex version of ChangePaths.
this.readFiles = readFiles; // In this case, we are going for easy to learn, so we'll do the
this.writeFiles = writeFiles; // pair.
} //
// We are going to use the chain extension to make it easier to
// read. Coming out of this, we will have one entity that fulfills:
//
// entity.Get<UPath> == "/output/a.txt"
entities = entities.Run(this.removePathPrefix).Run(this.addPathPrefix);
/// <inheritdoc /> // Then we write out the files to the output. First we make sure we
public override Task<IEnumerable<Entity>> RunAsync( // clear out the output. This operation performs an action when it
IEnumerable<Entity> entities) // it is first entered, but otherwise passes all the inputs through.
{ //
throw new NotImplementedException(); // We can call the clear directory in three ways. The first is to call
} // the operation with:
//
// this.clearDirectory.Run()
//
// The other is to pass in the entities and get a new list of
// modified ones out. In this case, clear doesn't make any changes,
// but Entity objects are immutable, so we always work on the list
// returned.
//
// entities = this.clearDirectory.Run(entity)
//
// The third way is to use an extension on entities which lets us
// chain calls, ala Gulp's pipelines. The below code does this along
// with writing the files to the output.
entities = entities.Run(this.clearDirectory).Run(this.writeFiles);
// If we are chaining this pipeline into another, we return the
// entities. Otherwise, we can just return an empty list. The
// pipeline is async, so it is wrapped in a task, but most
// operations are not (or are both).
return Task.FromResult(entities);
} }
} }

View file

@ -1,6 +1,4 @@
using System;
using System.IO; using System.IO;
using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using Autofac; using Autofac;
@ -10,46 +8,42 @@ using MfGames.IO.Extensions;
using Nitride; using Nitride;
using Nitride.IO; using Nitride.IO;
namespace CopyFiles namespace CopyFiles;
/// <summary>
/// Main entry point into the CopyFiles sample generator.
/// </summary>
public static class CopyFilesProgram
{ {
/// <summary> public static async Task<int> Main(string[] args)
/// Main entry point into the CopyFiles sample generator.
/// </summary>
public static class CopyFilesProgram
{ {
public static async Task<int> Main(string[] args) // All of the builder methods are fluent in that they return the
{ // builder to allow them to be chained. However, for documentation
// All of the builder methods are fluent in that they return the // purposes, we are going to split them apart to explain the details.
// builder to allow them to be chained. However, for documentation var builder = new NitrideBuilder(args);
// purposes, we are going to split them apart to explain the details.
var builder = new NitrideBuilder(args);
// Filesystem access is provided by Zio, which allows for mutliple // Filesystem access is provided by Zio, which allows for mutliple
// folders to be combined together into a single unified file // folders to be combined together into a single unified file
// system. At the moment, we set the "root" directory which will // system. At the moment, we set the "root" directory which will
// contains all the paths, both input and output. // contains all the paths, both input and output.
DirectoryInfo rootDir = typeof(CopyFilesProgram) DirectoryInfo rootDir =
.GetDirectory() typeof(CopyFilesProgram).GetDirectory()!.FindGitRoot()!.GetDirectory("examples/CopyFiles");
!.FindGitRoot()
!.GetDirectory("examples/CopyFiles");
builder.WithRootDirectory(rootDir); builder.WithRootDirectory(rootDir);
// Like Serilog, we use a number of extension methods on the builder // Like Serilog, we use a number of extension methods on the builder
// to inject functionality such as plugins and extensions. In this // to inject functionality such as plugins and extensions. In this
// case, we only need the Nitride.IO module so we use the `UseIO` // case, we only need the Nitride.IO module so we use the `UseIO`
// to inject the requisite modules and configure it. // to inject the requisite modules and configure it.
builder.UseIO(); builder.UseIO();
// We use Autofac for the bulk of our registration handling. This // We use Autofac for the bulk of our registration handling. This
// was mainly because we are more comfortable with Autofac, but it // was mainly because we are more comfortable with Autofac, but it
// also has a clean interface for handling some of the more esoteric // also has a clean interface for handling some of the more esoteric
// problems we've encountered. // problems we've encountered.
builder.ConfigureContainer( builder.ConfigureContainer(x => x.RegisterModule<CopyFilesModule>());
x => x.RegisterModule<CopyFilesModule>());
// Finally, we build the site generator object and run it. // Finally, we build the site generator object and run it.
return await builder.BuildAsync(); return await builder.RunAsync();
}
} }
} }

View file

@ -1,6 +1,4 @@
using System;
using System.IO; using System.IO;
using System.Reflection;
using System.Threading.Tasks; using System.Threading.Tasks;
using CliWrap; using CliWrap;
@ -12,57 +10,47 @@ using Nitride.Tests;
using Xunit; using Xunit;
using Xunit.Abstractions; using Xunit.Abstractions;
namespace CopyFiles namespace CopyFiles;
/// <summary>
/// Tests the execution of the tool and ensures it is working correctly.
/// </summary>
public class CopyFilesTest : NitrideTestBase
{ {
/// <summary> public CopyFilesTest(ITestOutputHelper output)
/// Tests the execution of the tool and ensures it is working correctly. : base(output)
/// </summary>
public class CopyFilesTest : NitrideTestsBase
{ {
public CopyFilesTest(ITestOutputHelper output) }
: base(output)
[Fact]
public async Task Run()
{
// Figure out the paths for this test.
DirectoryInfo rootDir =
typeof(CopyFilesProgram).GetDirectory()!.FindGitRoot()!.GetDirectory("examples/CopyFiles");
DirectoryInfo outputDir = rootDir.GetDirectory("output");
FileInfo projectFile = rootDir.GetFile("CopyFiles.csproj");
this.Logger.Error("A {0}", rootDir);
// Clear out the output directory if we have an old one.
if (outputDir.Exists)
{ {
outputDir.Delete(true);
} }
[Fact] // Execute the generator. This will throw if there is an exception.
public async Task Run() await Cli.Wrap("dotnet")
{ .WithArguments(x => x.Add("run").Add("--project").Add(projectFile.FullName).Add("--").Add("build"))
// Figure out the paths for this test. .ExecuteAsync();
DirectoryInfo rootDir = typeof(CopyFilesProgram)
.GetDirectory()
!.FindGitRoot()
!.GetDirectory("examples/CopyFiles");
DirectoryInfo outputDir = rootDir.GetDirectory("output");
FileInfo projectFile = rootDir.GetFile("CopyFiles.csproj");
this.Logger.Error("A {0}", rootDir); // Make sure we have our output.
FileInfo aFile = outputDir.GetFile("a.txt");
// Clear out the output directory if we have an old one. Assert.True(aFile.Exists);
if (outputDir.Exists)
{
outputDir.Delete(true);
}
// Execute the generator. This will throw if there is an exception. string aText = aFile.ReadAllText().Trim();
await Cli
.Wrap("dotnet")
.WithArguments(
x => x
.Add("run")
.Add("--project")
.Add(projectFile.FullName)
.Add("--")
.Add("build"))
.ExecuteAsync();
// Make sure we have our output. Assert.Equal("This is the 'A' file.", aText);
FileInfo aFile = outputDir.GetFile("a.txt");
Assert.True(aFile.Exists);
string aText = aFile.ReadAllText().Trim();
Assert.Equal("This is the 'A' file.", aText);
}
} }
} }

View file

@ -1,6 +1,6 @@
# Copy Files # Copy Files
This is probably the most basic generator possible. It simply copies files from This is probably the most basic generator possible. It simply copies files from
the input and places them into the output. However, it also demonstrates a the input and places them into the output. However, it also demonstrates a basic
basic setup including creating a pipeline, wiring everything up with modules, setup including creating a pipeline, wiring everything up with modules, and
and configuring everything. configuring everything.

View file

@ -0,0 +1 @@
This is the 'A' file.

42
flake.lock Normal file
View file

@ -0,0 +1,42 @@
{
"nodes": {
"flake-utils": {
"locked": {
"lastModified": 1649676176,
"narHash": "sha256-OWKJratjt2RW151VUlJPRALb7OU2S5s+f0vLj4o1bHM=",
"owner": "numtide",
"repo": "flake-utils",
"rev": "a4b154ebbdc88c8498a5c7b01589addc9e9cb678",
"type": "github"
},
"original": {
"owner": "numtide",
"repo": "flake-utils",
"type": "github"
}
},
"nixpkgs": {
"locked": {
"lastModified": 1651558728,
"narHash": "sha256-8HzyRnWlgZluUrVFNOfZAOlA1fghpOSezXvxhalGMUo=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "cbe587c735b734405f56803e267820ee1559e6c1",
"type": "github"
},
"original": {
"id": "nixpkgs",
"ref": "nixos-unstable",
"type": "indirect"
}
},
"root": {
"inputs": {
"flake-utils": "flake-utils",
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

24
flake.nix Normal file
View file

@ -0,0 +1,24 @@
{
description = "A .NET core library for easily building CLI tools";
inputs = {
nixpkgs.url = "nixpkgs/nixos-unstable";
flake-utils.url = "github:numtide/flake-utils";
};
outputs = { self, nixpkgs, flake-utils }:
flake-utils.lib.eachDefaultSystem (system:
let pkgs = nixpkgs.legacyPackages.${system};
in {
devShell = pkgs.mkShell {
buildInputs = [
pkgs.dotnet-sdk
pkgs.lefthook
pkgs.convco
pkgs.nodePackages.prettier
pkgs.nixfmt
pkgs.jq
];
};
});
}

19
lefthook.yml Normal file
View file

@ -0,0 +1,19 @@
pre-push:
parallel: true
commands:
commit-check:
run: convco check
pre-commit:
parallel: false
commands:
dotnet-format-style:
glob: "*.cs"
run: dotnet format style
dotnet-format-whitespace:
glob: "*.cs"
run: dotnet format whitespace
prettier:
run: prettier . --write --loglevel warn
nixfmt:
run: nixfmt flake.nix

View file

@ -1,26 +0,0 @@
{
"niv": {
"branch": "master",
"description": "Easy dependency management for Nix projects",
"homepage": "https://github.com/nmattia/niv",
"owner": "nmattia",
"repo": "niv",
"rev": "65a61b147f307d24bfd0a5cd56ce7d7b7cc61d2e",
"sha256": "17mirpsx5wyw262fpsd6n6m47jcgw8k2bwcp1iwdnrlzy4dhcgqh",
"type": "tarball",
"url": "https://github.com/nmattia/niv/archive/65a61b147f307d24bfd0a5cd56ce7d7b7cc61d2e.tar.gz",
"url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
},
"nixpkgs": {
"branch": "nixos-21.05",
"description": "Nix Packages collection",
"homepage": "",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "6c0c30146347188ce908838fd2b50c1b7db47c0c",
"sha256": "05bh6kw7jzfxpvhndsg6swgbk1x7fsgnwahzm3jgd61rsvknhn93",
"type": "tarball",
"url": "https://github.com/NixOS/nixpkgs/archive/6c0c30146347188ce908838fd2b50c1b7db47c0c.tar.gz",
"url_template": "https://github.com/<owner>/<repo>/archive/<rev>.tar.gz"
}
}

View file

@ -1,174 +0,0 @@
# This file has been generated by Niv.
let
#
# The fetchers. fetch_<type> fetches specs of type <type>.
#
fetch_file = pkgs: name: spec:
let
name' = sanitizeName name + "-src";
in
if spec.builtin or true then
builtins_fetchurl { inherit (spec) url sha256; name = name'; }
else
pkgs.fetchurl { inherit (spec) url sha256; name = name'; };
fetch_tarball = pkgs: name: spec:
let
name' = sanitizeName name + "-src";
in
if spec.builtin or true then
builtins_fetchTarball { name = name'; inherit (spec) url sha256; }
else
pkgs.fetchzip { name = name'; inherit (spec) url sha256; };
fetch_git = name: spec:
let
ref =
if spec ? ref then spec.ref else
if spec ? branch then "refs/heads/${spec.branch}" else
if spec ? tag then "refs/tags/${spec.tag}" else
abort "In git source '${name}': Please specify `ref`, `tag` or `branch`!";
in
builtins.fetchGit { url = spec.repo; inherit (spec) rev; inherit ref; };
fetch_local = spec: spec.path;
fetch_builtin-tarball = name: throw
''[${name}] The niv type "builtin-tarball" is deprecated. You should instead use `builtin = true`.
$ niv modify ${name} -a type=tarball -a builtin=true'';
fetch_builtin-url = name: throw
''[${name}] The niv type "builtin-url" will soon be deprecated. You should instead use `builtin = true`.
$ niv modify ${name} -a type=file -a builtin=true'';
#
# Various helpers
#
# https://github.com/NixOS/nixpkgs/pull/83241/files#diff-c6f540a4f3bfa4b0e8b6bafd4cd54e8bR695
sanitizeName = name:
(
concatMapStrings (s: if builtins.isList s then "-" else s)
(
builtins.split "[^[:alnum:]+._?=-]+"
((x: builtins.elemAt (builtins.match "\\.*(.*)" x) 0) name)
)
);
# The set of packages used when specs are fetched using non-builtins.
mkPkgs = sources: system:
let
sourcesNixpkgs =
import (builtins_fetchTarball { inherit (sources.nixpkgs) url sha256; }) { inherit system; };
hasNixpkgsPath = builtins.any (x: x.prefix == "nixpkgs") builtins.nixPath;
hasThisAsNixpkgsPath = <nixpkgs> == ./.;
in
if builtins.hasAttr "nixpkgs" sources
then sourcesNixpkgs
else if hasNixpkgsPath && ! hasThisAsNixpkgsPath then
import <nixpkgs> {}
else
abort
''
Please specify either <nixpkgs> (through -I or NIX_PATH=nixpkgs=...) or
add a package called "nixpkgs" to your sources.json.
'';
# The actual fetching function.
fetch = pkgs: name: spec:
if ! builtins.hasAttr "type" spec then
abort "ERROR: niv spec ${name} does not have a 'type' attribute"
else if spec.type == "file" then fetch_file pkgs name spec
else if spec.type == "tarball" then fetch_tarball pkgs name spec
else if spec.type == "git" then fetch_git name spec
else if spec.type == "local" then fetch_local spec
else if spec.type == "builtin-tarball" then fetch_builtin-tarball name
else if spec.type == "builtin-url" then fetch_builtin-url name
else
abort "ERROR: niv spec ${name} has unknown type ${builtins.toJSON spec.type}";
# If the environment variable NIV_OVERRIDE_${name} is set, then use
# the path directly as opposed to the fetched source.
replace = name: drv:
let
saneName = stringAsChars (c: if isNull (builtins.match "[a-zA-Z0-9]" c) then "_" else c) name;
ersatz = builtins.getEnv "NIV_OVERRIDE_${saneName}";
in
if ersatz == "" then drv else
# this turns the string into an actual Nix path (for both absolute and
# relative paths)
if builtins.substring 0 1 ersatz == "/" then /. + ersatz else /. + builtins.getEnv "PWD" + "/${ersatz}";
# Ports of functions for older nix versions
# a Nix version of mapAttrs if the built-in doesn't exist
mapAttrs = builtins.mapAttrs or (
f: set: with builtins;
listToAttrs (map (attr: { name = attr; value = f attr set.${attr}; }) (attrNames set))
);
# https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/lists.nix#L295
range = first: last: if first > last then [] else builtins.genList (n: first + n) (last - first + 1);
# https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L257
stringToCharacters = s: map (p: builtins.substring p 1 s) (range 0 (builtins.stringLength s - 1));
# https://github.com/NixOS/nixpkgs/blob/0258808f5744ca980b9a1f24fe0b1e6f0fecee9c/lib/strings.nix#L269
stringAsChars = f: s: concatStrings (map f (stringToCharacters s));
concatMapStrings = f: list: concatStrings (map f list);
concatStrings = builtins.concatStringsSep "";
# https://github.com/NixOS/nixpkgs/blob/8a9f58a375c401b96da862d969f66429def1d118/lib/attrsets.nix#L331
optionalAttrs = cond: as: if cond then as else {};
# fetchTarball version that is compatible between all the versions of Nix
builtins_fetchTarball = { url, name ? null, sha256 }@attrs:
let
inherit (builtins) lessThan nixVersion fetchTarball;
in
if lessThan nixVersion "1.12" then
fetchTarball ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; }))
else
fetchTarball attrs;
# fetchurl version that is compatible between all the versions of Nix
builtins_fetchurl = { url, name ? null, sha256 }@attrs:
let
inherit (builtins) lessThan nixVersion fetchurl;
in
if lessThan nixVersion "1.12" then
fetchurl ({ inherit url; } // (optionalAttrs (!isNull name) { inherit name; }))
else
fetchurl attrs;
# Create the final "sources" from the config
mkSources = config:
mapAttrs (
name: spec:
if builtins.hasAttr "outPath" spec
then abort
"The values in sources.json should not have an 'outPath' attribute"
else
spec // { outPath = replace name (fetch config.pkgs name spec); }
) config.sources;
# The "config" used by the fetchers
mkConfig =
{ sourcesFile ? if builtins.pathExists ./sources.json then ./sources.json else null
, sources ? if isNull sourcesFile then {} else builtins.fromJSON (builtins.readFile sourcesFile)
, system ? builtins.currentSystem
, pkgs ? mkPkgs sources system
}: rec {
# The sources, i.e. the attribute set of spec name to spec
inherit sources;
# The "pkgs" (evaluated nixpkgs) to use for e.g. non-builtin fetchers
inherit pkgs;
};
in
mkSources (mkConfig {}) // { __functor = _: settings: mkSources (mkConfig settings); }

12310
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -1,23 +0,0 @@
{
"name": "nitride-cil",
"version": "1.0.0",
"private": true,
"scripts": {
"prepare": "husky install",
"build": "dotnet build",
"test": "dotnet test"
},
"devDependencies": {
"@commitlint/cli": "^13.1.0",
"@commitlint/config-conventional": "^13.1.0",
"@semantic-release/changelog": "^5.0.1",
"@semantic-release/git": "^9.0.0",
"@semantic-release/gitlab": "^6.2.2",
"@semantic-release/npm": "^7.1.3",
"commitlint-gitlab-ci": "^0.0.4",
"husky": "^7.0.2",
"semantic-release": "^17.4.7",
"semantic-release-dotnet": "^1.0.0",
"semantic-release-nuget": "^1.1.0"
}
}

View file

@ -1,20 +0,0 @@
module.exports = {
branches: ["main"],
message: "chore(release): v${nextRelease.version} [skip ci]\n\n${nextRelease.notes}",
plugins: [
"@semantic-release/commit-analyzer",
"@semantic-release/release-notes-generator",
"@semantic-release/npm",
"semantic-release-dotnet",
[
"semantic-release-nuget",
{
packArguments: ["--include-symbols", "--include-source"],
pushFiles: ["src/*/bin/Debug/*.nupkg"],
},
],
"@semantic-release/changelog",
"@semantic-release/git",
"@semantic-release/gitlab",
],
};

23
scripts/README.md Normal file
View file

@ -0,0 +1,23 @@
# Scripts Directory
This directory contains the basic scripts for working with the library.
## `setup.sh`
This verifies the environment is correct and makes sure everything is configured.
## `build.sh`
This builds the project and creates the binaries in debug mode.
## `test.sh`
This runs any required tests.
## `format.sh`
This is used to format the code base using our standards. It matches the commands in the `lefthook` pre-commit hook.
## `release.sh`
Intended to run in a CI environment, this creates a NuGet package and publishes it.

6
scripts/build.sh Executable file
View file

@ -0,0 +1,6 @@
#!/usr/bin/env sh
cd $(dirname $0)/..
./scripts/setup.sh || exit 1
dotnet build

14
scripts/format.sh Executable file
View file

@ -0,0 +1,14 @@
#!/usr/bin/env sh
# Normalize our environment.
cd $(dirname $0)/..
./scripts/setup.sh || exit 1
# Format the .NET code
dotnet format || exit 1
# Format using Prettier.
prettier . --write --loglevel warn
# Format the Flake.
nixfmt flake.nix

47
scripts/release.sh Executable file
View file

@ -0,0 +1,47 @@
#!/usr/bin/env sh
cd $(dirname $0)/..
./scripts/setup.sh || exit 1
# Verify the input.
if [ "x$NUGET_TOKEN" = "x" ]
then
echo "the environment variable NUGET_TOKEN is not defined"
exit 1
fi
if [ "x$NUGET_PUSH_URL" = "x" ]
then
echo "the environment variable NUGET_PUSH_URL is not defined"
exit 1
fi
# Clean up everything from the previous runs.
dotnet clean
# Version the file based on the Git repository.
(cd src && dotnet dotnet-gitversion /updateprojectfiles)
SEMVER="v$(dotnet gitversion /output json | jq -r .SemVer)"
if [ "x$SEMVER" = "x" ]
then
echo "cannot figure out the semantic version"
exit 1
fi
# Build to pick up the new version.
dotnet build
# Create and publish the NuGet packages.
dotnet pack --include-symbols --include-source
dotnet nuget push src/*/bin/Debug/*.nupkg --api-key $NUGET_TOKEN --source $NUGET_PUSH_URL
# Tag and push, but only if we don't have a tag.
if ! git tag | grep $SEMVER >& /dev/null
then
echo "tagging and pushing"
git tag $SEMVER
git push origin $SEMVER
else
echo "not tagging, already exists"
fi

23
scripts/setup.sh Executable file
View file

@ -0,0 +1,23 @@
#!/usr/bin/env sh
# Normalize our environment.
cd $(dirname $0)/..
# Make sure we have the needed executables installed.
for e in dotnet lefthook prettier nixfmt
do
if ! which $e >& /dev/null
then
echo "Cannot find '$e' in the path"
exit 1
fi
done
# Make sure we have lefthook is installed.
lefthook install
# Make sure our tools are installed.
dotnet tool restore
# Everything is good.
exit 0

8
scripts/test.sh Executable file
View file

@ -0,0 +1,8 @@
#!/usr/bin/env sh
cd $(dirname $0)/..
./scripts/setup.sh || exit 1
dotnet test --test-adapter-path:. --logger:"junit;LogFilePath=../artifacts/{assembly}-test-result.xml;MethodFormat=Default;FailureBodyFormat=Verbose" --collect:"XPlat Code Coverage"
dotnet tool run reportgenerator -reports:tests/*/TestResults/*/coverage.cobertura.xml -targetdir:./coverage "-reporttypes:Cobertura;TextSummary"
grep "Line coverage" coverage/Summary.txt

View file

@ -1,17 +0,0 @@
let
sources = import ./nix/sources.nix;
pkgs = import sources.nixpkgs {};
in
pkgs.mkShell {
buildInputs = [
pkgs.git
pkgs.nodejs-16_x
pkgs.yarn
pkgs.dotnet-sdk_5
pkgs.niv
];
shellHooks = ''
export DOTNET_CLI_TELEMETRY_OPTOUT=true
'';
}

View file

@ -1,14 +1,14 @@
<Project> <Project>
<PropertyGroup> <PropertyGroup>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild> <GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<Authors>Dylan Moonfire</Authors> <Authors>Dylan Moonfire</Authors>
<Company>Moonfire Games</Company> <Company>Moonfire Games</Company>
<RepositoryUrl>https://gitlab.com/mfgames-cil/nitride-cil</RepositoryUrl> <RepositoryUrl>https://gitlab.com/mfgames-cil/nitride-cil</RepositoryUrl>
<RepositoryType>Git</RepositoryType> <RepositoryType>Git</RepositoryType>
<PackageTags>nitride</PackageTags> <PackageTags>nitride</PackageTags>
<PackageProjectUrl>https://gitlab.com/mfgames-cil/nitride-cil</PackageProjectUrl> <PackageProjectUrl>https://gitlab.com/mfgames-cil/nitride-cil</PackageProjectUrl>
<PackageLicense>MIT</PackageLicense> <PackageLicense>AGPL-3.0</PackageLicense>
</PropertyGroup> </PropertyGroup>
</Project> </Project>

13
src/GitVersion.yml Normal file
View file

@ -0,0 +1,13 @@
mode: ContinuousDelivery
increment: Inherit
continuous-delivery-fallback-tag: ci
major-version-bump-message: "^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\\([\\w\\s-]*\\))?(!:|:.*\\n\\n((.+\\n)+\\n)?BREAKING CHANGE:\\s.+)"
minor-version-bump-message: "^(feat)(\\([\\w\\s-]*\\))?:"
patch-version-bump-message: "^(build|chore|ci|docs|fix|perf|refactor|revert|style|test)(\\([\\w\\s-]*\\))?:"
assembly-versioning-scheme: MajorMinorPatch
assembly-file-versioning-scheme: MajorMinorPatch
assembly-informational-format: "{InformationalVersion}"
tag-prefix: "[vV]"

View file

@ -0,0 +1,13 @@
using FluentValidation;
namespace Nitride.Calendar;
public class CreateCalendarValidator : AbstractValidator<CreateCalender>
{
public CreateCalendarValidator()
{
this.RuleFor(x => x.Path).NotNull();
this.RuleFor(x => x.GetEventSummary).NotNull();
this.RuleFor(x => x.GetEventUrl).NotNull();
}
}

View file

@ -1,104 +1,108 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using FluentValidation;
using Gallium; using Gallium;
using Ical.Net.CalendarComponents; using Ical.Net.CalendarComponents;
using Ical.Net.DataTypes; using Ical.Net.DataTypes;
using Ical.Net.Serialization; using Ical.Net.Serialization;
using Nitride.Contents; using Nitride.Contents;
using Nitride.Temporal; using Nitride.Temporal;
using NodaTime; using NodaTime;
using Zio; using Zio;
namespace Nitride.Calendar namespace Nitride.Calendar;
/// <summary>
/// Creates an iCalendar file from all the entities passed into the method
/// that have a NodaTime.Instant component. This will write both past and
/// future events.
/// </summary>
[WithProperties]
public partial class CreateCalender : OperationBase
{ {
/// <summary> private readonly Timekeeper clock;
/// Creates an iCalendar file from all the entities passed into the method
/// that have a NodaTime.Instant component. This will write both past and private readonly IValidator<CreateCalender> validator;
/// future events.
/// </summary> public CreateCalender(IValidator<CreateCalender> validator, Timekeeper clock)
[WithProperties]
public partial class CreateCalender : NitrideOperationBase
{ {
private readonly NitrideClock clock; this.validator = validator;
this.clock = clock;
}
public CreateCalender(NitrideClock clock) /// <summary>
/// Gets or sets a callback to get the summary of the event representing
/// the entity.
/// </summary>
public Func<Entity, string>? GetEventSummary { get; set; }
/// <summary>
/// Gets or sets a callback to get the optional URL of an event for
/// the entity.
/// </summary>
public Func<Entity, Uri?>? GetEventUrl { get; set; }
/// <summary>
/// Gets or sets the file system path for the resulting calendar.
/// </summary>
public UPath? Path { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
IEnumerable<Entity> output = input.ForEntities<Instant>(this.CreateCalendarEntity);
return output;
}
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();
calendar.TimeZones.Add(new VTimeZone(this.clock.DateTimeZone.Id));
// Go through the events and add all of them.
var input = entities.ToList();
IEnumerable<CalendarEvent> events = input.Select(this.CreateCalendarEvent);
calendar.Events.AddRange(events);
// Create the iCalendar file.
var serializer = new CalendarSerializer();
string serializedCalendar = serializer.SerializeToString(calendar);
// Create the calendar entity and populate everything.
Entity calendarEntity = new Entity().Set(IsCalendar.Instance)
.Set(this.Path!.Value)
.SetTextContent(serializedCalendar);
// Return the results along with the new calendar.
return input.Union(new[] { calendarEntity });
}
private CalendarEvent CreateCalendarEvent(Entity entity)
{
Instant instant = entity.Get<Instant>();
var when = this.clock.ToDateTime(instant);
string summary = this.GetEventSummary!(entity);
Uri? url = this.GetEventUrl?.Invoke(entity);
var calendarEvent = new CalendarEvent
{ {
this.clock = clock; Summary = summary,
} Start = new CalDateTime(when),
Url = url,
};
/// <summary> return calendarEvent;
/// Gets or sets a callback to get the summary of the event representing
/// the entity.
/// </summary>
public Func<Entity, string>? GetEventSummary { get; set; }
/// <summary>
/// Gets or sets a callback to get the optional URL of an event for
/// the entity.
/// </summary>
public Func<Entity, Uri?>? GetEventUrl { get; set; }
/// <summary>
/// Gets or sets the file system path for the resulting calendar.
/// </summary>
public UPath? Path { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.CheckNotNull(x => x.Path);
this.CheckNotNull(x => x.GetEventSummary);
IEnumerable<Entity> output = input
.ForEntities<Instant>(this.CreateCalendarEntity);
return output;
}
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();
calendar.TimeZones.Add(new VTimeZone(this.clock.DateTimeZone.Id));
// Go through the events and add all of them.
List<Entity> input = entities.ToList();
IEnumerable<CalendarEvent> events =
input.Select(this.CreateCalendarEvent);
calendar.Events.AddRange(events);
// Create the iCalendar file.
var serializer = new CalendarSerializer();
string serializedCalendar = serializer.SerializeToString(calendar);
// Create the calendar entity and populate everything.
Entity calendarEntity = new Entity()
.Set(IsCalendar.Instance)
.Set(this.Path!.Value)
.SetTextContent(serializedCalendar);
// Return the results along with the new calendar.
return input.Union(new[] { calendarEntity });
}
private CalendarEvent CreateCalendarEvent(Entity entity)
{
var instant = entity.Get<Instant>();
var when = this.clock.ToDateTime(instant);
string summary = this.GetEventSummary!(entity);
Uri? url = this.GetEventUrl?.Invoke(entity);
var calendarEvent = new CalendarEvent
{
Summary = summary,
Start = new CalDateTime(when),
Url = url,
};
return calendarEvent;
}
} }
} }

View file

@ -1,10 +1,9 @@
namespace Nitride.Calendar namespace Nitride.Calendar;
/// <summary>
/// A marker component for identifying an entity that represents a calendar.
/// </summary>
public record IsCalendar
{ {
/// <summary> public static IsCalendar Instance { get; } = new();
/// A marker component for identifying an entity that represents a calendar.
/// </summary>
public class IsCalendar
{
public static IsCalendar Instance { get; } = new();
}
} }

View file

@ -1,37 +1,37 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<Description>An extension to Nitride static site generator to generate iCalendar files.</Description> <Description>An extension to Nitride static site generator to generate iCalendar files.</Description>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride.IO\Nitride.IO.csproj" /> <ProjectReference Include="..\Nitride.IO\Nitride.IO.csproj"/>
<ProjectReference Include="..\Nitride.Temporal\Nitride.Temporal.csproj" /> <ProjectReference Include="..\Nitride.Temporal\Nitride.Temporal.csproj"/>
<ProjectReference Include="..\Nitride\Nitride.csproj" /> <ProjectReference Include="..\Nitride\Nitride.csproj"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Gallium" Version="1.0.2" /> <PackageReference Include="Gallium" Version="1.0.2"/>
<PackageReference Include="Ical.Net" Version="4.2.0" /> <PackageReference Include="Ical.Net" Version="4.2.0"/>
<PackageReference Include="NodaTime" Version="3.0.5" /> <PackageReference Include="NodaTime" Version="3.1.0"/>
<PackageReference Include="Zio" Version="0.12.0" /> <PackageReference Include="Zio" Version="0.15.0"/>
</ItemGroup> </ItemGroup>
<!-- Include the source generator --> <!-- Include the source generator -->
<PropertyGroup> <PropertyGroup>
<EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles> <EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj"> <ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj">
<OutputItemType>Analyzer</OutputItemType> <OutputItemType>Analyzer</OutputItemType>
<ReferenceOutputAssembly>False</ReferenceOutputAssembly> <ReferenceOutputAssembly>False</ReferenceOutputAssembly>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -1,16 +1,13 @@
using Autofac; using Autofac;
using Nitride.Temporal; using Nitride.Temporal;
namespace Nitride.Calendar namespace Nitride.Calendar;
public static class NitrideCalendarBuilderExtensions
{ {
public static class NitrideCalendarBuilderExtensions public static NitrideBuilder UseCalendar(this NitrideBuilder builder)
{ {
public static NitrideBuilder UseCalendar(this NitrideBuilder builder) return builder.UseTemporal().ConfigureContainer(x => x.RegisterModule<NitrideCalendarModule>());
{
return builder
.UseTemporal()
.ConfigureContainer(
x => x.RegisterModule<NitrideCalendarModule>());
}
} }
} }

View file

@ -1,6 +1,13 @@
namespace Nitride.Calendar using Autofac;
namespace Nitride.Calendar;
public class NitrideCalendarModule : Module
{ {
public class NitrideCalendarModule : NitrideModuleBase /// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{ {
builder.RegisterOperators(this);
builder.RegisterValidators(this);
} }
} }

View file

@ -0,0 +1,128 @@
using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using Gallium;
using Nitride.Contents;
using Nitride.Feeds.Structure;
using NodaTime;
using Serilog;
using Zio;
namespace Nitride.Feeds;
/// <summary>
/// Creates various feeds from the given input.
/// </summary>
[WithProperties]
public partial class CreateAtomFeed : OperationBase
{
private readonly ILogger logger;
private readonly IValidator<CreateAtomFeed> validator;
public CreateAtomFeed(ILogger logger, IValidator<CreateAtomFeed> validator)
{
this.logger = logger;
this.validator = validator;
this.GetAlternateMimeType = _ => "text/html";
}
/// <summary>
/// Gets or sets the base URL for all the links.
/// </summary>
public string? BaseUrl { get; set; }
/// <summary>
/// Gets or sets the alternate MIME type.
/// </summary>
public Func<Entity, string> GetAlternateMimeType { get; set; }
/// <summary>
/// Gets or sets the alternate URL associated with the feed.
/// </summary>
public Func<Entity, Uri>? GetAlternateUrl { get; set; }
/// <summary>
/// Gets or sets the callback to get the author for the feed.
/// </summary>
public Func<Entity, AtomAuthor>? GetAuthor { get; set; }
/// <summary>
/// Gets or sets the callback to get the entries associated with the
/// feed.
/// </summary>
public Func<Entity, IEnumerable<AtomEntry>>? GetEntries { get; set; }
/// <summary>
/// Gets or sets the identifier (typically a URL) of the feed.
/// </summary>
public Func<Entity, string>? GetId { get; set; }
/// <summary>
/// Gets or sets the callback to get the path of the generated feed.
/// </summary>
public Func<Entity, UPath>? GetPath { get; set; }
/// <summary>
/// Gets or sets the rights (license) of the feed.
/// </summary>
public Func<Entity, string>? GetRights { get; set; }
/// <summary>
/// A callback that gets the title of the feed from the given entity.
/// </summary>
public Func<Entity, string>? GetTitle { get; set; }
/// <summary>
/// Gets or sets the updated timestamp for the feed.
/// </summary>
public Func<Entity, Instant>? GetUpdated { get; set; }
/// <summary>
/// Gets or sets the URL associated with the feed.
/// </summary>
public Func<Entity, Uri>? GetUrl { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
return input.SelectMany(this.CreateEntityFeed);
}
private IEnumerable<Entity> CreateEntityFeed(Entity entity)
{
// Create the top-level feed. All the nullable callbacks were
// verified in the function that calls this.
var feed = new AtomFeed
{
Title = this.GetTitle?.Invoke(entity),
Id = this.GetId?.Invoke(entity),
Rights = this.GetRights?.Invoke(entity),
Updated = this.GetUpdated?.Invoke(entity),
Url = this.GetUrl?.Invoke(entity),
AlternateUrl = this.GetAlternateUrl?.Invoke(entity),
AlternateMimeType = this.GetAlternateMimeType.Invoke(entity),
Author = this.GetAuthor?.Invoke(entity),
}.ToXElement();
// Go through all the items inside the feed and add them.
foreach (AtomEntry? entry in this.GetEntries!(entity))
{
feed.Add(entry.ToXElement());
}
// Create the feed entity and return both objects.
Entity feedEntity = new Entity().Set(IsFeed.Instance).Set(this.GetPath!(entity)).SetTextContent(feed + "\n");
return new[] { entity, feedEntity };
}
}

View file

@ -0,0 +1,13 @@
using FluentValidation;
namespace Nitride.Feeds;
public class CreateAtomFeedValidator : AbstractValidator<CreateAtomFeed>
{
public CreateAtomFeedValidator()
{
this.RuleFor(x => x.GetEntries).NotNull();
this.RuleFor(x => x.GetPath).NotNull();
this.RuleFor(x => x.GetTitle).NotNull();
}
}

View file

@ -1,123 +0,0 @@
using System;
using System.Collections.Generic;
using System.Linq;
using Gallium;
using Nitride.Contents;
using Nitride.Feeds.Structure;
using NodaTime;
using Serilog;
using Zio;
namespace Nitride.Feeds
{
/// <summary>
/// Creates various feeds from the given input.
/// </summary>
[WithProperties]
public partial class CreateAtomFeeds : NitrideOperationBase
{
private readonly ILogger logger;
public CreateAtomFeeds(ILogger logger)
{
this.logger = logger;
this.GetAlternateMimeType = _ => "text/html";
}
/// <summary>
/// Gets or sets the base URL for all the links.
/// </summary>
public string? BaseUrl { get; set; }
/// <summary>
/// Gets or sets the alternate MIME type.
/// </summary>
public Func<Entity, string> GetAlternateMimeType { get; set; }
/// <summary>
/// Gets or sets the alternate URL associated with the feed.
/// </summary>
public Func<Entity, Uri>? GetAlternateUrl { get; set; }
/// <summary>
/// Gets or sets the callback to get the author for the feed.
/// </summary>
public Func<Entity, AtomAuthor>? GetAuthor { get; set; }
/// <summary>
/// Gets or sets the callback to get the entries associated with the
/// feed.
/// </summary>
public Func<Entity, IEnumerable<AtomEntry>>? GetEntries { get; set; }
/// <summary>
/// Gets or sets the identifier (typically a URL) of the feed.
/// </summary>
public Func<Entity, string>? GetId { get; set; }
/// <summary>
/// Gets or sets the callback to get the path of the generated feed.
/// </summary>
public Func<Entity, UPath>? GetPath { get; set; }
/// <summary>
/// Gets or sets the rights (license) of the feed.
/// </summary>
public Func<Entity, string>? GetRights { get; set; }
/// <summary>
/// A callback that gets the title of the feed from the given entity.
/// </summary>
public Func<Entity, string>? GetTitle { get; set; }
/// <summary>
/// Gets or sets the updated timestamp for the feed.
/// </summary>
public Func<Entity, Instant>? GetUpdated { get; set; }
/// <summary>
/// Gets or sets the URL associated with the feed.
/// </summary>
public Func<Entity, Uri>? GetUrl { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.CheckNotNull(x => this.GetTitle);
this.CheckNotNull(x => this.GetPath);
this.CheckNotNull(x => this.GetEntries);
return input.SelectMany(this.CreateEntityFeed);
}
private IEnumerable<Entity> CreateEntityFeed(Entity entity)
{
// Create the top-level feed. All the nullable callbacks were
// verified in the function that calls this.
var feed = new AtomFeed()
.WithTitle(this.GetTitle?.Invoke(entity))
.WithId(this.GetId?.Invoke(entity))
.WithRights(this.GetRights?.Invoke(entity))
.WithUpdated(this.GetUpdated?.Invoke(entity))
.WithUrl(this.GetUrl?.Invoke(entity))
.WithAlternateUrl(this.GetAlternateUrl?.Invoke(entity))
.WithAlternateMimeType(this.GetAlternateMimeType.Invoke(entity))
.WithAuthor(this.GetAuthor?.Invoke(entity))
.ToXElement();
// Go through all the items inside the feed and add them.
foreach (var entry in this.GetEntries!(entity))
{
feed.Add(entry.ToXElement());
}
// Create the feed entity and return both objects.
Entity feedEntity = new Entity()
.Set(IsFeed.Instance)
.Set(this.GetPath!(entity))
.SetTextContent(feed + "\n");
return new[] { entity, feedEntity };
}
}
}

View file

@ -1,15 +1,14 @@
namespace Nitride.Feeds namespace Nitride.Feeds;
{
/// <summary>
/// A marker component that indicates this entity has a feed associated with
/// it.
/// </summary>
public class HasFeed
{
public HasFeed()
{
}
public static HasFeed Instance { get; } = new(); /// <summary>
/// A marker component that indicates this entity has a feed associated with
/// it.
/// </summary>
public class HasFeed
{
public HasFeed()
{
} }
public static HasFeed Instance { get; } = new();
} }

View file

@ -1,14 +1,13 @@
namespace Nitride.Feeds namespace Nitride.Feeds;
{
/// <summary>
/// A marker component that indicates this page is a feed.
/// </summary>
public class IsFeed
{
public IsFeed()
{
}
public static IsFeed Instance { get; } = new(); /// <summary>
/// A marker component that indicates this page is a feed.
/// </summary>
public class IsFeed
{
public IsFeed()
{
} }
public static IsFeed Instance { get; } = new();
} }

View file

@ -1,36 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<Description>An extension to Nitride static site generator to generate Atom feeds.</Description> <Description>An extension to Nitride static site generator to generate Atom feeds.</Description>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride.IO\Nitride.IO.csproj" /> <ProjectReference Include="..\Nitride.IO\Nitride.IO.csproj"/>
<ProjectReference Include="..\Nitride.Temporal\Nitride.Temporal.csproj" /> <ProjectReference Include="..\Nitride.Temporal\Nitride.Temporal.csproj"/>
<ProjectReference Include="..\Nitride\Nitride.csproj" /> <ProjectReference Include="..\Nitride\Nitride.csproj"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Gallium" Version="1.0.2" /> <PackageReference Include="Gallium" Version="1.0.2"/>
<PackageReference Include="NodaTime" Version="3.0.5" /> <PackageReference Include="NodaTime" Version="3.1.0"/>
<PackageReference Include="Zio" Version="0.12.0" /> <PackageReference Include="Zio" Version="0.15.0"/>
</ItemGroup> </ItemGroup>
<!-- Include the source generator --> <!-- Include the source generator -->
<PropertyGroup> <PropertyGroup>
<EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles> <EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj"> <ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj">
<OutputItemType>Analyzer</OutputItemType> <OutputItemType>Analyzer</OutputItemType>
<ReferenceOutputAssembly>False</ReferenceOutputAssembly> <ReferenceOutputAssembly>False</ReferenceOutputAssembly>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -1,16 +1,13 @@
using Autofac; using Autofac;
using Nitride.Temporal; using Nitride.Temporal;
namespace Nitride.Feeds namespace Nitride.Feeds;
public static class NitrideFeedsBuilderExtensions
{ {
public static class NitrideFeedsBuilderExtensions public static NitrideBuilder UseFeeds(this NitrideBuilder builder)
{ {
public static NitrideBuilder UseFeeds(this NitrideBuilder builder) return builder.UseTemporal().ConfigureContainer(x => x.RegisterModule<NitrideFeedsModule>());
{
return builder
.UseTemporal()
.ConfigureContainer(
x => x.RegisterModule<NitrideFeedsModule>());
}
} }
} }

View file

@ -1,6 +1,13 @@
namespace Nitride.Feeds using Autofac;
namespace Nitride.Feeds;
public class NitrideFeedsModule : Module
{ {
public class NitrideFeedsModule : NitrideModuleBase /// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{ {
builder.RegisterOperators(this);
builder.RegisterValidators(this);
} }
} }

View file

@ -1,41 +1,37 @@
using System.Xml.Linq; using System.Xml.Linq;
namespace Nitride.Feeds.Structure namespace Nitride.Feeds.Structure;
/// <summary>
/// The type-safe structure for an author element.
/// </summary>
[WithProperties]
public partial class AtomAuthor
{ {
/// <summary> /// <summary>
/// The type-safe structure for an author element. /// Gets or sets the name of the author.
/// </summary> /// </summary>
[WithProperties] public string? Name { get; set; }
public partial class AtomAuthor
/// <summary>
/// Creates an XML element out of the feed along with all items inside
/// the feed.
/// </summary>
/// <returns></returns>
public XElement? ToXElement()
{ {
/// <summary> if (this.Name == null)
/// Gets or sets the name of the author.
/// </summary>
public string? Name { get; set; }
/// <summary>
/// Creates an XML element out of the feed along with all items inside
/// the feed.
/// </summary>
/// <returns></returns>
public XElement? ToXElement()
{ {
if (this.Name == null) return null;
{
return null;
}
var author = new XElement(XmlConstants.AtomNamespace + "author");
if (!string.IsNullOrEmpty(this.Name))
{
author.Add(
new XElement(
XmlConstants.AtomNamespace + "name",
new XText(this.Name)));
}
return author;
} }
var author = new XElement(XmlConstants.AtomNamespace + "author");
if (!string.IsNullOrEmpty(this.Name))
{
author.Add(new XElement(XmlConstants.AtomNamespace + "name", new XText(this.Name)));
}
return author;
} }
} }

View file

@ -1,57 +1,53 @@
using System; using System;
using System.Xml.Linq; using System.Xml.Linq;
namespace Nitride.Feeds.Structure namespace Nitride.Feeds.Structure;
/// <summary>
/// The type-safe structure for a entry's category element.
/// </summary>
[WithProperties]
public partial class AtomCategory
{ {
/// <summary> /// <summary>
/// The type-safe structure for a entry's category element. /// Gets or sets the label associated with the category.
/// </summary> /// </summary>
[WithProperties] public string? Label { get; set; }
public partial class AtomCategory
/// <summary>
/// Gets or sets the scheme associated with the category.
/// </summary>
public Uri? Scheme { get; set; }
/// <summary>
/// Gets or sets the term of the category.
/// </summary>
public string? Term { get; set; }
/// <summary>
/// Creates an XML element out of the feed along with all items inside
/// the feed.
/// </summary>
/// <returns></returns>
public XElement ToXElement()
{ {
/// <summary> if (this.Term == null)
/// Gets or sets the label associated with the category.
/// </summary>
public string? Label { get; set; }
/// <summary>
/// Gets or sets the scheme associated with the category.
/// </summary>
public Uri? Scheme { get; set; }
/// <summary>
/// Gets or sets the term of the category.
/// </summary>
public string? Term { get; set; }
/// <summary>
/// Creates an XML element out of the feed along with all items inside
/// the feed.
/// </summary>
/// <returns></returns>
public XElement ToXElement()
{ {
if (this.Term == null) throw new NullReferenceException("Category term cannot be null.");
{
throw new NullReferenceException(
"Category term cannot be null.");
}
var elem = new XElement(
XmlConstants.AtomNamespace + "category",
new XAttribute("term", this.Term));
if (this.Scheme != null)
{
elem.Add(new XAttribute("scheme", this.Scheme.ToString()));
}
if (!string.IsNullOrEmpty(this.Label))
{
elem.Add(new XAttribute("label", this.Label));
}
return elem;
} }
var elem = new XElement(XmlConstants.AtomNamespace + "category", new XAttribute("term", this.Term));
if (this.Scheme != null)
{
elem.Add(new XAttribute("scheme", this.Scheme.ToString()));
}
if (!string.IsNullOrEmpty(this.Label))
{
elem.Add(new XAttribute("label", this.Label));
}
return elem;
} }
} }

View file

@ -1,121 +1,119 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.Xml.Linq; using System.Xml.Linq;
using NodaTime; using NodaTime;
using static Nitride.Feeds.Structure.XmlConstants; using static Nitride.Feeds.Structure.XmlConstants;
namespace Nitride.Feeds.Structure namespace Nitride.Feeds.Structure;
/// <summary>
/// The type-safe structure for an entry in the Atom feed.
/// </summary>
[WithProperties]
public partial class AtomEntry
{ {
/// <summary> /// <summary>
/// The type-safe structure for an entry in the Atom feed. /// Gets or sets the author for the feed.
/// </summary> /// </summary>
[WithProperties] public AtomAuthor? Author { get; set; }
public partial class AtomEntry
/// <summary>
/// Gets or sets the categories associated with this entry.
/// </summary>
public IEnumerable<AtomCategory>? Categories { get; set; }
/// <summary>
/// Gets or sets the content of the entry.
/// </summary>
public string? Content { get; set; }
/// <summary>
/// Gets or sets the type of content (text, html) of the content.
/// </summary>
public string ContentType { get; set; } = "html";
/// <summary>
/// Gets or sets the ID of the feed.
/// </summary>
public string? Id { get; set; }
/// <summary>
/// Gets or sets the summary of the entry.
/// </summary>
public string? Summary { get; set; }
/// <summary>
/// Gets or sets the type of content (text, html) of the summary.
/// </summary>
public string SummaryType { get; set; } = "html";
/// <summary>
/// Gets or sets the title of the Feed.
/// </summary>
public string? Title { get; set; }
/// <summary>
/// Gets or sets the timestamp that the feed was updated.
/// </summary>
public Instant? Updated { get; set; }
/// <summary>
/// Gets or sets the URL associated with this feed.
/// </summary>
public Uri? Url { get; set; }
/// <summary>
/// Creates an XML element out of the feed along with all items inside
/// the feed.
/// </summary>
/// <returns></returns>
public XElement? ToXElement()
{ {
/// <summary> var elem = new XElement(AtomNamespace + "entry");
/// Gets or sets the author for the feed.
/// </summary>
public AtomAuthor? Author { get; set; }
/// <summary> AtomHelper.AddIfSet(elem, "title", this.Title);
/// Gets or sets the categories associated with this entry.
/// </summary>
public IEnumerable<AtomCategory>? Categories { get; set; }
/// <summary> if (this.Url != null)
/// Gets or sets the content of the entry.
/// </summary>
public string? Content { get; set; }
/// <summary>
/// Gets or sets the type of content (text, html) of the content.
/// </summary>
public string ContentType { get; set; } = "html";
/// <summary>
/// Gets or sets the ID of the feed.
/// </summary>
public string? Id { get; set; }
/// <summary>
/// Gets or sets the summary of the entry.
/// </summary>
public string? Summary { get; set; }
/// <summary>
/// Gets or sets the type of content (text, html) of the summary.
/// </summary>
public string SummaryType { get; set; } = "html";
/// <summary>
/// Gets or sets the title of the Feed.
/// </summary>
public string? Title { get; set; }
/// <summary>
/// Gets or sets the timestamp that the feed was updated.
/// </summary>
public Instant? Updated { get; set; }
/// <summary>
/// Gets or sets the URL associated with this feed.
/// </summary>
public Uri? Url { get; set; }
/// <summary>
/// Creates an XML element out of the feed along with all items inside
/// the feed.
/// </summary>
/// <returns></returns>
public XElement? ToXElement()
{ {
var elem = new XElement(AtomNamespace + "entry"); elem.Add(
new XElement(
AtomHelper.AddIfSet(elem, "title", this.Title); AtomNamespace + "link",
new XAttribute("rel", "alternate"),
if (this.Url != null) new XAttribute("href", this.Url.ToString())));
{
elem.Add(
new XElement(
AtomNamespace + "link",
new XAttribute("rel", "alternate"),
new XAttribute("href", this.Url.ToString())));
}
AtomHelper.AddIfSet(
elem,
"updated",
this.Updated?.ToString("g", null));
AtomHelper.AddIfSet(elem, "id", this.Id);
AtomHelper.AddIfSet(elem, this.Author?.ToXElement());
if (this.Categories != null)
{
foreach (var category in this.Categories)
{
elem.Add(category.ToXElement());
}
}
if (!string.IsNullOrWhiteSpace(this.Summary))
{
elem.Add(
new XElement(
AtomNamespace + "summary",
new XAttribute("type", this.SummaryType),
new XText(this.Summary)));
}
if (!string.IsNullOrWhiteSpace(this.Content))
{
elem.Add(
new XElement(
AtomNamespace + "content",
new XAttribute("type", this.ContentType),
new XText(this.Content)));
}
return elem;
} }
AtomHelper.AddIfSet(elem, "updated", this.Updated?.ToString("g", null));
AtomHelper.AddIfSet(elem, "id", this.Id);
AtomHelper.AddIfSet(elem, this.Author?.ToXElement());
if (this.Categories != null)
{
foreach (AtomCategory? category in this.Categories)
{
elem.Add(category.ToXElement());
}
}
if (!string.IsNullOrWhiteSpace(this.Summary))
{
elem.Add(
new XElement(
AtomNamespace + "summary",
new XAttribute("type", this.SummaryType),
new XText(this.Summary)));
}
if (!string.IsNullOrWhiteSpace(this.Content))
{
elem.Add(
new XElement(
AtomNamespace + "content",
new XAttribute("type", this.ContentType),
new XText(this.Content)));
}
return elem;
} }
} }

View file

@ -1,104 +1,101 @@
using System; using System;
using System.Xml.Linq; using System.Xml.Linq;
using NodaTime; using NodaTime;
using static Nitride.Feeds.Structure.XmlConstants; using static Nitride.Feeds.Structure.XmlConstants;
namespace Nitride.Feeds.Structure namespace Nitride.Feeds.Structure;
/// <summary>
/// The type-safe structure of the top-level feed.
/// </summary>
public record AtomFeed
{ {
/// <summary> /// <summary>
/// The type-safe structure of the top-level feed. /// Gets or sets the MIME type for the alternate URL.
/// </summary> /// </summary>
[WithProperties] public string AlternateMimeType { get; set; } = "text/html";
public partial class AtomFeed
/// <summary>
/// Gets or sets the alternate URL for this feed.
/// </summary>
public Uri? AlternateUrl { get; set; }
/// <summary>
/// Gets or sets the author for the feed.
/// </summary>
public AtomAuthor? Author { get; set; }
/// <summary>
/// Gets or sets the ID of the feed.
/// </summary>
public string? Id { get; set; }
/// <summary>
/// Gets or sets the rights (license) of the feed.
/// </summary>
public string? Rights { get; set; }
/// <summary>
/// Gets or sets the title of the Feed.
/// </summary>
public string? Title { get; set; }
/// <summary>
/// Gets or sets the timestamp that the feed was updated.
/// </summary>
public Instant? Updated { get; set; }
/// <summary>
/// Gets or sets the URL associated with this feed.
/// </summary>
public Uri? Url { get; set; }
/// <summary>
/// Creates an XML element out of the feed along with all items inside
/// the feed.
/// </summary>
/// <returns></returns>
public XElement ToXElement()
{ {
/// <summary> var elem = new XElement(AtomNamespace + "feed");
/// Gets or sets the MIME type for the alternate URL.
/// </summary>
public string AlternateMimeType { get; set; } = "text/html";
/// <summary> if (!string.IsNullOrWhiteSpace(this.Title))
/// Gets or sets the alternate URL for this feed.
/// </summary>
public Uri? AlternateUrl { get; set; }
/// <summary>
/// Gets or sets the author for the feed.
/// </summary>
public AtomAuthor? Author { get; set; }
/// <summary>
/// Gets or sets the ID of the feed.
/// </summary>
public string? Id { get; set; }
/// <summary>
/// Gets or sets the rights (license) of the feed.
/// </summary>
public string? Rights { get; set; }
/// <summary>
/// Gets or sets the title of the Feed.
/// </summary>
public string? Title { get; set; }
/// <summary>
/// Gets or sets the timestamp that the feed was updated.
/// </summary>
public Instant? Updated { get; set; }
/// <summary>
/// Gets or sets the URL associated with this feed.
/// </summary>
public Uri? Url { get; set; }
/// <summary>
/// Creates an XML element out of the feed along with all items inside
/// the feed.
/// </summary>
/// <returns></returns>
public XElement ToXElement()
{ {
var elem = new XElement(AtomNamespace + "feed"); elem.Add(
new XElement(
if (!string.IsNullOrWhiteSpace(this.Title)) AtomNamespace + "title",
{ new XAttribute("type", "text"),
elem.Add( new XAttribute(XNamespace.Xml + "lang", "en"),
new XElement( new XText(this.Title)));
AtomNamespace + "title",
new XAttribute("type", "text"),
new XAttribute(XNamespace.Xml + "lang", "en"),
new XText(this.Title)));
}
if (this.Url != null)
{
elem.Add(
new XElement(
AtomNamespace + "link",
new XAttribute("type", "application/atom+xml"),
new XAttribute("href", this.Url.ToString()),
new XAttribute("rel", "self")));
}
if (this.AlternateUrl != null)
{
elem.Add(
new XElement(
AtomNamespace + "link",
new XAttribute("type", this.AlternateMimeType),
new XAttribute("href", this.AlternateUrl.ToString()),
new XAttribute("rel", "alternate")));
}
AtomHelper.AddIfSet(
elem,
"updated",
this.Updated?.ToString("g", null));
AtomHelper.AddIfSet(elem, "id", this.Id);
AtomHelper.AddIfSet(elem, this.Author?.ToXElement());
AtomHelper.AddIfSet(elem, "rights", this.Rights);
return elem;
} }
if (this.Url != null)
{
elem.Add(
new XElement(
AtomNamespace + "link",
new XAttribute("type", "application/atom+xml"),
new XAttribute("href", this.Url.ToString()),
new XAttribute("rel", "self")));
}
if (this.AlternateUrl != null)
{
elem.Add(
new XElement(
AtomNamespace + "link",
new XAttribute("type", this.AlternateMimeType),
new XAttribute("href", this.AlternateUrl.ToString()),
new XAttribute("rel", "alternate")));
}
AtomHelper.AddIfSet(elem, "updated", this.Updated?.ToString("g", null));
AtomHelper.AddIfSet(elem, "id", this.Id);
AtomHelper.AddIfSet(elem, this.Author?.ToXElement());
AtomHelper.AddIfSet(elem, "rights", this.Rights);
return elem;
} }
} }

View file

@ -1,29 +1,25 @@
using System.Xml.Linq; using System.Xml.Linq;
namespace Nitride.Feeds.Structure namespace Nitride.Feeds.Structure;
{
/// <summary>
/// Helper methods for working with XML elements.
/// </summary>
public static class AtomHelper
{
public static void AddIfSet(XElement root, XElement? elem)
{
if (elem != null)
{
root.Add(elem);
}
}
public static void AddIfSet(XElement elem, string name, string? text) /// <summary>
/// Helper methods for working with XML elements.
/// </summary>
public static class AtomHelper
{
public static void AddIfSet(XElement root, XElement? elem)
{
if (elem != null)
{ {
if (!string.IsNullOrWhiteSpace(text)) root.Add(elem);
{ }
elem.Add( }
new XElement(
XmlConstants.AtomNamespace + name, public static void AddIfSet(XElement elem, string name, string? text)
new XText(text))); {
} if (!string.IsNullOrWhiteSpace(text))
{
elem.Add(new XElement(XmlConstants.AtomNamespace + name, new XText(text)));
} }
} }
} }

View file

@ -1,22 +1,19 @@
using System.Xml.Linq; using System.Xml.Linq;
namespace Nitride.Feeds.Structure namespace Nitride.Feeds.Structure;
/// <summary>
/// Common constants used while generating feeds.
/// </summary>
public static class XmlConstants
{ {
/// <summary> /// <summary>
/// Common constants used while generating feeds. /// The XML namespace for Atom feeds.
/// </summary> /// </summary>
public static class XmlConstants public static readonly XNamespace AtomNamespace = "http://www.w3.org/2005/Atom";
{
/// <summary>
/// The XML namespace for Atom feeds.
/// </summary>
public static readonly XNamespace AtomNamespace =
"http://www.w3.org/2005/Atom";
/// <summary> /// <summary>
/// The XML namespace for media. /// The XML namespace for media.
/// </summary> /// </summary>
public static readonly XNamespace MediaNamespace = public static readonly XNamespace MediaNamespace = "http://search.yahoo.com/mrss/";
"http://search.yahoo.com/mrss/";
}
} }

View file

@ -1,11 +1,10 @@
namespace Nitride.Gemtext namespace Nitride.Gemtext;
/// <summary>
/// A marker component for indicating that an entity is Gemtext, the format
/// for text files using the Gemini protocol.
/// </summary>
public record IsGemtext
{ {
/// <summary> public static IsGemtext Instance { get; } = new();
/// A marker component for indicating that an entity is Gemtext, the format
/// for text files using the Gemini protocol.
/// </summary>
public class IsGemtext
{
public static IsGemtext Instance { get; } = new IsGemtext();
}
} }

View file

@ -1,27 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<Description>An extension to Nitride static site generator to generate Gemtext output.</Description> <Description>An extension to Nitride static site generator to generate Gemtext output.</Description>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride\Nitride.csproj"/> <ProjectReference Include="..\Nitride\Nitride.csproj"/>
</ItemGroup> </ItemGroup>
<!-- Include the source generator --> <!-- Include the source generator -->
<PropertyGroup> <PropertyGroup>
<EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles> <EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj"> <ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj">
<OutputItemType>Analyzer</OutputItemType> <OutputItemType>Analyzer</OutputItemType>
<ReferenceOutputAssembly>False</ReferenceOutputAssembly> <ReferenceOutputAssembly>False</ReferenceOutputAssembly>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -1,14 +1,11 @@
using Autofac; using Autofac;
namespace Nitride.Gemtext namespace Nitride.Gemtext;
public static class NitrideGemtextBuilderExtensions
{ {
public static class NitrideGemtextBuilderExtensions public static NitrideBuilder UseGemtext(this NitrideBuilder builder)
{ {
public static NitrideBuilder UseGemtext(this NitrideBuilder builder) return builder.ConfigureContainer(x => x.RegisterModule<NitrideGemtextModule>());
{
return builder
.ConfigureContainer(
x => x.RegisterModule<NitrideGemtextModule>());
}
} }
} }

View file

@ -1,6 +1,11 @@
namespace Nitride.Gemtext using Autofac;
namespace Nitride.Gemtext;
public class NitrideGemtextModule : Module
{ {
public class NitrideGemtextModule : NitrideModuleBase /// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{ {
} }
} }

View file

@ -1,159 +1,140 @@
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis;
namespace Nitride.Generators namespace Nitride.Generators;
/// <summary>
/// Various wrappers around the diagnostics to simplify generation.
/// </summary>
public static class CodeAnalysisExtensions
{ {
/// <summary> /// <summary>
/// Various wrappers around the diagnostics to simplify generation. /// Creates an error message to break the build while generating code.
/// </summary> /// </summary>
public static class CodeAnalysisExtensions /// <param name="context">The context that contains the diagnostic.</param>
/// <param name="messageCode">The normalized message code.</param>
/// <param name="format">The string format for the message.</param>
/// <param name="parameters">The optional parameters.</param>
public static void Error(
this GeneratorExecutionContext context,
MessageCode messageCode,
string format,
params object[] parameters)
{ {
/// <summary> Error(context, messageCode, null, format, parameters);
/// Creates an error message to break the build while generating code. }
/// </summary>
/// <param name="context">The context that contains the diagnostic.</param>
/// <param name="messageCode">The normalized message code.</param>
/// <param name="format">The string format for the message.</param>
/// <param name="parameters">The optional parameters.</param>
public static void Error(
this GeneratorExecutionContext context,
MessageCode messageCode,
string format,
params object[] parameters)
{
Error(context, messageCode, null, format, parameters);
}
/// <summary> /// <summary>
/// Creates an error message to break the build while generating code. /// Creates an error message to break the build while generating code.
/// </summary> /// </summary>
/// <param name="context">The context that contains the diagnostic.</param> /// <param name="context">The context that contains the diagnostic.</param>
/// <param name="messageCode">The normalized message code.</param> /// <param name="messageCode">The normalized message code.</param>
/// <param name="location">The optional location for the message.</param> /// <param name="location">The optional location for the message.</param>
/// <param name="format">The string format for the message.</param> /// <param name="format">The string format for the message.</param>
/// <param name="parameters">The optional parameters.</param> /// <param name="parameters">The optional parameters.</param>
public static void Error( public static void Error(
this GeneratorExecutionContext context, this GeneratorExecutionContext context,
MessageCode messageCode, MessageCode messageCode,
Location? location, Location? location,
string format, string format,
params object[] parameters) params object[] parameters)
{ {
context.Message( context.Message(messageCode, location, DiagnosticSeverity.Error, format, parameters);
messageCode, }
location,
DiagnosticSeverity.Error,
format,
parameters);
}
/// <summary> /// <summary>
/// Creates an informational message to break the build while generating code. /// Creates an informational message to break the build while generating code.
/// </summary> /// </summary>
/// <param name="context">The context that contains the diagnostic.</param> /// <param name="context">The context that contains the diagnostic.</param>
/// <param name="messageCode">The normalized message code.</param> /// <param name="messageCode">The normalized message code.</param>
/// <param name="format">The string format for the message.</param> /// <param name="format">The string format for the message.</param>
/// <param name="parameters">The optional parameters.</param> /// <param name="parameters">The optional parameters.</param>
public static void Information( public static void Information(
this GeneratorExecutionContext context, this GeneratorExecutionContext context,
MessageCode messageCode, MessageCode messageCode,
string format, string format,
params object[] parameters) params object[] parameters)
{ {
Information(context, messageCode, null, format, parameters); Information(context, messageCode, null, format, parameters);
} }
/// <summary> /// <summary>
/// Creates an informational message to break the build while generating code. /// Creates an informational message to break the build while generating code.
/// </summary> /// </summary>
/// <param name="context">The context that contains the diagnostic.</param> /// <param name="context">The context that contains the diagnostic.</param>
/// <param name="messageCode">The normalized message code.</param> /// <param name="messageCode">The normalized message code.</param>
/// <param name="location">The optional location for the message.</param> /// <param name="location">The optional location for the message.</param>
/// <param name="format">The string format for the message.</param> /// <param name="format">The string format for the message.</param>
/// <param name="parameters">The optional parameters.</param> /// <param name="parameters">The optional parameters.</param>
public static void Information( public static void Information(
this GeneratorExecutionContext context, this GeneratorExecutionContext context,
MessageCode messageCode, MessageCode messageCode,
Location? location, Location? location,
string format, string format,
params object[] parameters) params object[] parameters)
{ {
context.Message( context.Message(messageCode, location, DiagnosticSeverity.Info, format, parameters);
messageCode, }
location,
DiagnosticSeverity.Info,
format,
parameters);
}
/// <summary> /// <summary>
/// Creates a warning message to break the build while generating code. /// Creates a warning message to break the build while generating code.
/// </summary> /// </summary>
/// <param name="context">The context that contains the diagnostic.</param> /// <param name="context">The context that contains the diagnostic.</param>
/// <param name="messageCode">The normalized message code.</param> /// <param name="messageCode">The normalized message code.</param>
/// <param name="format">The string format for the message.</param> /// <param name="format">The string format for the message.</param>
/// <param name="parameters">The optional parameters.</param> /// <param name="parameters">The optional parameters.</param>
public static void Warning( public static void Warning(
this GeneratorExecutionContext context, this GeneratorExecutionContext context,
MessageCode messageCode, MessageCode messageCode,
string format, string format,
params object[] parameters) params object[] parameters)
{ {
Warning(context, messageCode, null, format, parameters); Warning(context, messageCode, null, format, parameters);
} }
/// <summary> /// <summary>
/// Creates a warning message to break the build while generating code. /// Creates a warning message to break the build while generating code.
/// </summary> /// </summary>
/// <param name="context">The context that contains the diagnostic.</param> /// <param name="context">The context that contains the diagnostic.</param>
/// <param name="messageCode">The normalized message code.</param> /// <param name="messageCode">The normalized message code.</param>
/// <param name="location">The optional location for the message.</param> /// <param name="location">The optional location for the message.</param>
/// <param name="format">The string format for the message.</param> /// <param name="format">The string format for the message.</param>
/// <param name="parameters">The optional parameters.</param> /// <param name="parameters">The optional parameters.</param>
public static void Warning( public static void Warning(
this GeneratorExecutionContext context, this GeneratorExecutionContext context,
MessageCode messageCode, MessageCode messageCode,
Location? location, Location? location,
string format, string format,
params object[] parameters) params object[] parameters)
{ {
context.Message( context.Message(messageCode, location, DiagnosticSeverity.Warning, format, parameters);
messageCode, }
location,
DiagnosticSeverity.Warning,
format,
parameters);
}
/// <summary> /// <summary>
/// Creates a message to break the build while generating code. /// Creates a message to break the build while generating code.
/// </summary> /// </summary>
/// <param name="context">The context that contains the diagnostic.</param> /// <param name="context">The context that contains the diagnostic.</param>
/// <param name="messageCode">The normalized message code.</param> /// <param name="messageCode">The normalized message code.</param>
/// <param name="location">The optional location for the message.</param> /// <param name="location">The optional location for the message.</param>
/// <param name="format">The string format for the message.</param> /// <param name="format">The string format for the message.</param>
/// <param name="parameters">The optional parameters.</param> /// <param name="parameters">The optional parameters.</param>
/// <param name="severity">The severity of the message.</param> /// <param name="severity">The severity of the message.</param>
private static void Message( private static void Message(
this GeneratorExecutionContext context, this GeneratorExecutionContext context,
MessageCode messageCode, MessageCode messageCode,
Location? location, Location? location,
DiagnosticSeverity severity, DiagnosticSeverity severity,
string format, string format,
params object[] parameters) params object[] parameters)
{ {
context.ReportDiagnostic( context.ReportDiagnostic(
Diagnostic.Create( Diagnostic.Create(
"GN" + ((int)messageCode).ToString("D4"), "GN" + ((int)messageCode).ToString("D4"),
"Nitride", "Nitride",
string.Format(format, parameters), string.Format(format, parameters),
severity, severity,
severity, severity,
true, true,
severity is DiagnosticSeverity.Warning severity is DiagnosticSeverity.Warning or DiagnosticSeverity.Info ? 4 : 0,
or DiagnosticSeverity.Info location: location));
? 4
: 0,
location: location));
}
} }
} }

View file

@ -1,10 +1,9 @@
namespace Nitride.Generators namespace Nitride.Generators;
/// <summary>
/// All the error messages produced by the generators.
/// </summary>
public enum MessageCode
{ {
/// <summary> Debug = 1,
/// All the error messages produced by the generators.
/// </summary>
public enum MessageCode
{
Debug = 1,
}
} }

View file

@ -1,19 +1,19 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<Description>Common source generators for Nitride.</Description> <Description>Common source generators for Nitride.</Description>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Gallium" Version="1.0.2" /> <PackageReference Include="Gallium" Version="1.0.2"/>
<PackageReference Include="Microsoft.CodeAnalysis.Common" Version="3.8.0" /> <PackageReference Include="Microsoft.CodeAnalysis.Common" Version="4.1.0"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.1.0"/>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="3.8.0" /> <PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.1.0"/>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -0,0 +1,27 @@
using System.Collections.Generic;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Nitride.Generators;
/// <summary>
/// Internal class that consolidates all of the information needed to generate a
/// file.
/// </summary>
internal class WithPropertyClass
{
/// <summary>
/// Gets the syntax for the class declaration.
/// </summary>
public ClassDeclarationSyntax ClassDeclaration { get; set; } = null!;
/// <summary>
/// Gets or sets the namespace associated with the class.
/// </summary>
public string Namespace { get; set; } = null!;
/// <summary>
/// Gets the using statements that are in the class.
/// </summary>
public List<UsingDirectiveSyntax> UsingDirectiveList { get; set; } = new();
}

View file

@ -1,209 +1,138 @@
using System.Collections.Generic; using System.Collections.Generic;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Text; using Microsoft.CodeAnalysis.Text;
namespace Nitride.Generators namespace Nitride.Generators;
/// <summary>
/// Implements a source generator that creates Set* methods for the various
/// properties that also returns the same object for purposes of chaining
/// together calls.
/// </summary>
[Generator]
public class WithPropertySourceGenerator : ISourceGenerator
{ {
/// <summary> public void Execute(GeneratorExecutionContext context)
/// Implements a source generator that creates Set* methods for the various
/// properties that also returns the same object for purposes of chaining
/// together calls.
/// </summary>
[Generator]
public class WithPropertySourceGenerator : ISourceGenerator
{ {
public void Execute(GeneratorExecutionContext context) // Get the generator infrastructure will create a receiver and
// populate it we can retrieve the populated instance via the
// context.
var syntaxReceiver = (WithPropertySyntaxReceiver?)context.SyntaxReceiver;
if (syntaxReceiver == null)
{ {
// Get the generator infrastructure will create a receiver and return;
// populate it we can retrieve the populated instance via the
// context.
var syntaxReceiver = (SyntaxReceiver?)context.SyntaxReceiver;
if (syntaxReceiver == null)
{
return;
}
// Report any messages.
foreach (var message in syntaxReceiver.Messages)
{
context.Information(
MessageCode.Debug,
Location.Create(
"Temporary.g.cs",
TextSpan.FromBounds(0, 0),
new LinePositionSpan(
new LinePosition(0, 0),
new LinePosition(0, 0))),
"Generating additional identifier code: {0}",
message);
}
// If we didn't find anything, then there is nothing to do.
if (syntaxReceiver.ClassesToAugment.Count == 0)
{
return;
}
// Go through each one.
foreach (var cds in syntaxReceiver.ClassesToAugment)
{
this.GenerateClassFile(context, cds);
}
} }
public void Initialize(GeneratorInitializationContext context) // Report any messages.
foreach (string? message in syntaxReceiver.Messages)
{ {
// Register a factory that can create our custom syntax receiver context.Information(
context.RegisterForSyntaxNotifications( MessageCode.Debug,
() => new SyntaxReceiver(context)); Location.Create(
"Temporary.g.cs",
TextSpan.FromBounds(0, 0),
new LinePositionSpan(new LinePosition(0, 0), new LinePosition(0, 0))),
"Generating additional identifier code: {0}",
message);
} }
private void GenerateClassFile( // If we didn't find anything, then there is nothing to do.
GeneratorExecutionContext context, if (syntaxReceiver.ClassList.Count == 0)
ClassDeclarationSyntax cds)
{ {
// Get the namespace. return;
var nds = (NamespaceDeclarationSyntax?)cds.Parent; }
if (nds == null) // Go through each one.
foreach (WithPropertyClass classInfo in syntaxReceiver.ClassList)
{
this.GenerateClassFile(context, classInfo);
}
}
public void Initialize(GeneratorInitializationContext context)
{
// Register a factory that can create our custom syntax receiver
context.RegisterForSyntaxNotifications(() => new WithPropertySyntaxReceiver(context));
}
private void GenerateClassFile(GeneratorExecutionContext context, WithPropertyClass unit)
{
// Pull out some fields.
ClassDeclarationSyntax? cds = unit.ClassDeclaration;
// Create the partial class.
StringBuilder buffer = new();
buffer.AppendLine("#nullable enable");
// Copy the using statements from the file.
foreach (UsingDirectiveSyntax? uds in unit.UsingDirectiveList)
{
buffer.AppendLine(uds.ToString());
}
buffer.AppendLine();
// Create the namespace.
buffer.AppendLine($"namespace {unit.Namespace}");
buffer.AppendLine("{");
buffer.AppendLine($" public partial class {cds.Identifier}");
buffer.AppendLine(" {");
// Go through the properties of the namespace.
IEnumerable<PropertyDeclarationSyntax> properties = cds.Members
.Where(m => m.Kind() == SyntaxKind.PropertyDeclaration)
.Cast<PropertyDeclarationSyntax>();
bool first = true;
foreach (PropertyDeclarationSyntax pds in properties)
{
// See if we have a setter.
bool found = pds.AccessorList?.Accessors.Any(x => x.Keyword.ToString() == "set") ?? false;
if (!found)
{ {
return; continue;
} }
string? ns = nds.Name.ToString(); // If we aren't first, then add a newline before it.
if (first)
// Create the partial class. {
StringBuilder buffer = new(); first = false;
buffer.AppendLine("#nullable enable"); }
else
// Copy the using statements from the file.
if (nds.Parent is CompilationUnitSyntax cus)
{ {
foreach (var uds in cus.Usings)
{
buffer.AppendLine(uds.ToString());
}
buffer.AppendLine(); buffer.AppendLine();
} }
// Create the namespace. // Write some documentation.
buffer.AppendLine($"namespace {ns}"); buffer.AppendLine(" /// <summary>");
buffer.AppendLine("{"); buffer.AppendLine(
buffer.AppendLine($" public partial class {cds.Identifier}"); string.Format(
buffer.AppendLine(" {"); " /// Sets the {0} value and returns the operation for chaining.",
pds.Identifier.ToString()));
buffer.AppendLine(" /// </summary>");
// Go through the properties of the namespace. // We have the components for writing out a setter.
IEnumerable<PropertyDeclarationSyntax> properties = cds.Members buffer.AppendLine(
.Where(m => m.Kind() == SyntaxKind.PropertyDeclaration) string.Format(" public {0} With{1}({2} value)", cds.Identifier, pds.Identifier, pds.Type));
.Cast<PropertyDeclarationSyntax>(); buffer.AppendLine(" {");
bool first = true; buffer.AppendLine(string.Format(" this.{0} = value;", pds.Identifier));
buffer.AppendLine(" return this;");
foreach (PropertyDeclarationSyntax pds in properties) buffer.AppendLine(" }");
{
// See if we have a setter.
bool found =
pds.AccessorList?.Accessors
.Any(x => x.Keyword.ToString() == "set")
?? false;
if (!found)
{
continue;
}
// If we aren't first, then add a newline before it.
if (first)
{
first = false;
}
else
{
buffer.AppendLine();
}
// Write some documentation.
buffer.AppendLine(" /// <summary>");
buffer.AppendLine(
string.Format(
" /// Sets the {0} value and returns the operation for chaining.",
pds.Identifier));
buffer.AppendLine(" /// </summary>");
// We have the components for writing out a setter.
buffer.AppendLine(
string.Format(
" public {0} With{1}({2} value)",
cds.Identifier,
pds.Identifier,
pds.Type));
buffer.AppendLine(" {");
buffer.AppendLine(
string.Format(
" this.{0} = value;",
pds.Identifier));
buffer.AppendLine(" return this;");
buffer.AppendLine(" }");
}
// Finish up the class.
buffer.AppendLine(" }");
buffer.AppendLine("}");
// Create the source text and write out the file.
SourceText sourceText = SourceText.From(
buffer.ToString(),
Encoding.UTF8);
context.AddSource(cds.Identifier + ".Generated.cs", sourceText);
} }
private class SyntaxReceiver : ISyntaxReceiver // Finish up the class.
{ buffer.AppendLine(" }");
private readonly GeneratorInitializationContext context; buffer.AppendLine("}");
public SyntaxReceiver(GeneratorInitializationContext context) // Create the source text and write out the file.
{ var sourceText = SourceText.From(buffer.ToString(), Encoding.UTF8);
this.context = context; context.AddSource(cds.Identifier + ".Generated.cs", sourceText);
this.ClassesToAugment = new List<ClassDeclarationSyntax>();
this.Messages = new List<string>();
}
public List<ClassDeclarationSyntax> ClassesToAugment { get; }
public List<string> Messages { get; }
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// We only care about class declarations.
if (syntaxNode is not ClassDeclarationSyntax cds)
{
return;
}
// See if the class has our set properties attribute.
bool found = cds
.AttributeLists
.AsEnumerable()
.SelectMany(x => x.Attributes)
.Select(x => x.Name.ToString())
.Any(
x => x switch
{
"WithProperties" => true,
"WithPropertiesAttribute" => true,
_ => false,
});
if (found)
{
this.ClassesToAugment.Add(cds);
}
}
}
} }
} }

View file

@ -0,0 +1,85 @@
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace Nitride.Generators;
internal class WithPropertySyntaxReceiver : ISyntaxReceiver
{
private readonly GeneratorInitializationContext context;
public WithPropertySyntaxReceiver(GeneratorInitializationContext context)
{
this.context = context;
this.ClassList = new List<WithPropertyClass>();
this.Messages = new List<string>();
}
public List<WithPropertyClass> ClassList { get; }
public List<string> Messages { get; }
/// <summary>
/// Gets or sets the name of the analyzed namespace.
/// </summary>
public string? Namespace { get; private set; }
public List<UsingDirectiveSyntax> UsingDirectiveList { get; set; } = new();
public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
// Check for namespaces.
switch (syntaxNode)
{
case CompilationUnitSyntax:
// Reset everything.
this.Namespace = null!;
this.UsingDirectiveList = new List<UsingDirectiveSyntax>();
break;
case NamespaceDeclarationSyntax syntax:
this.Namespace = syntax.Name.ToString();
return;
case FileScopedNamespaceDeclarationSyntax syntax:
this.Namespace = syntax.Name.ToString();
return;
case UsingDirectiveSyntax syntax:
this.UsingDirectiveList.Add(syntax);
return;
case ClassDeclarationSyntax:
break;
default:
return;
}
// We only care about class declarations.
if (syntaxNode is not ClassDeclarationSyntax cds)
{
return;
}
// See if the class has our set properties attribute.
bool found = cds.AttributeLists.AsEnumerable()
.SelectMany(x => x.Attributes)
.Select(x => x.Name.ToString())
.Any(
x => x switch
{
"WithProperties" => true,
"WithPropertiesAttribute" => true,
_ => false,
});
if (found)
{
this.ClassList.Add(
new WithPropertyClass
{
Namespace = this.Namespace!,
UsingDirectiveList = this.UsingDirectiveList,
ClassDeclaration = cds,
});
}
}
}

View file

@ -1,74 +0,0 @@
using System;
using System.Collections.Generic;
using Gallium;
using HandlebarsDotNet;
using Nitride.Contents;
namespace Nitride.Handlebars
{
/// <summary>
/// An operation that uses the content to create a template that is then
/// applied against the content and metadata and then replaces the content
/// of that entity.
/// </summary>
public class ApplyContentHandlebarsTemplate<TModel> : NitrideOperationBase
{
private readonly HandlebarsTemplateCache cache;
public ApplyContentHandlebarsTemplate(HandlebarsTemplateCache cache)
{
this.cache = cache;
}
/// <summary>
/// Gets or sets the callback used to create a model from a given
/// entity. This allows for the website to customize what information is
/// being passed to the template.
/// </summary>
public Func<Entity, TModel>? CreateModelCallback { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.CheckNotNull(x => x.CreateModelCallback);
return input
.ForEachEntity<HasHandlebarsTemplate, ITextContent>(this.Apply);
}
/// <summary>
/// Sets the callback for the template and returns the operation to
/// chain operations.
/// </summary>
/// <param name="callback">The callback to set.</param>
/// <returns>The ApplyContentHandlebarsTemplate to chain requests.</returns>
public ApplyContentHandlebarsTemplate<TModel> WithCreateModelCallback(
Func<Entity, TModel>? callback)
{
this.CreateModelCallback = callback;
return this;
}
private Entity Apply(
Entity entity,
HasHandlebarsTemplate _,
ITextContent content)
{
// Create the model using the callback.
TModel model = this.CreateModelCallback!(entity);
// Create a template from the contents.
string text = content.GetText();
HandlebarsTemplate<object, object> template =
this.cache.GetLiteralTemplate(text);
// Render the template and create a new entity with the updated
// text.
string result = template(model!);
return entity
.Remove<HasHandlebarsTemplate>()
.SetTextContent(new StringTextContent(result));
}
}
}

View file

@ -1,88 +0,0 @@
using System;
using System.Collections.Generic;
using Gallium;
using HandlebarsDotNet;
using Nitride.Contents;
namespace Nitride.Handlebars
{
/// <summary>
/// An operation that applies a common or shared template on the content of
/// a document that includes theme or styling information.
/// </summary>
public class ApplyStyleHandlebarsTemplate<TModel> : NitrideOperationBase
{
private readonly HandlebarsTemplateCache cache;
public ApplyStyleHandlebarsTemplate(HandlebarsTemplateCache cache)
{
this.cache = cache;
}
/// <summary>
/// Gets or sets the callback used to create a model from a given
/// entity. This allows for the website to customize what information is
/// being passed to the template.
/// </summary>
public Func<Entity, TModel>? CreateModelCallback { get; set; }
/// <summary>
/// Gets or sets the callback used to determine which template to use
/// for a given entity. This lets one have a per-page template change.
/// </summary>
public Func<Entity, string>? GetTemplateName { get; set; }
public IHandlebars? Handlebars { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
// Make sure we have sane data.
this.CheckNotNull(x => x.CreateModelCallback);
this.CheckNotNull(x => x.Handlebars);
this.CheckNotNull(x => x.GetTemplateName);
// Create and set up the Handlebars.
return input
.ForEachEntity<ITextContent>(this.Apply);
}
/// <summary>
/// Sets the callback for the template and returns the operation to
/// chain operations.
/// </summary>
/// <param name="callback">The callback to set.</param>
/// <returns>The ApplyContentHandlebarsTemplate to chain requests.</returns>
public ApplyStyleHandlebarsTemplate<TModel> WithCreateModelCallback(
Func<Entity, TModel>? callback)
{
this.CreateModelCallback = callback;
return this;
}
public ApplyStyleHandlebarsTemplate<TModel> WithGetTemplateName(
Func<Entity, string>? callback)
{
this.GetTemplateName = callback;
return this;
}
public ApplyStyleHandlebarsTemplate<TModel> WithHandlebars(
IHandlebars? handlebars)
{
this.Handlebars = handlebars;
return this;
}
private Entity Apply(Entity entity, ITextContent content)
{
TModel model = this.CreateModelCallback!(entity);
string name = this.GetTemplateName!(entity);
HandlebarsTemplate<object, object> template =
this.cache.GetNamedTemplate(name);
string result = template(model!);
return entity.SetTextContent(result);
}
}
}

View file

@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using FluentValidation;
using Gallium;
using HandlebarsDotNet;
using Nitride.Contents;
namespace Nitride.Handlebars;
/// <summary>
/// An operation that applies a common or shared template on the content of
/// a document that includes theme or styling information.
/// </summary>
public class ApplyStyleTemplate<TModel> : OperationBase
{
// TODO: This does not use [WithProperties] because the source generator hasn't been taught how to do generics.
private readonly HandlebarsTemplateCache cache;
private readonly IValidator<ApplyStyleTemplate<TModel>> validator;
public ApplyStyleTemplate(IValidator<ApplyStyleTemplate<TModel>> validator, HandlebarsTemplateCache cache)
{
this.validator = validator;
this.cache = cache;
}
/// <summary>
/// Gets or sets the callback used to create a model from a given
/// entity. This allows for the website to customize what information is
/// being passed to the template.
/// </summary>
public Func<Entity, TModel>? CreateModelCallback { get; set; }
/// <summary>
/// Gets or sets the callback used to determine which template to use
/// for a given entity. This lets one have a per-page template change.
/// </summary>
public Func<Entity, string>? GetTemplateName { get; set; }
public IHandlebars? Handlebars { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
// Make sure we have sane data.
this.validator.ValidateAndThrow(this);
// Create and set up the Handlebars.
return input.ForEachEntity<ITextContent>(this.Apply);
}
/// <summary>
/// Sets the callback for the template and returns the operation to
/// chain operations.
/// </summary>
/// <param name="callback">The callback to set.</param>
/// <returns>The ApplyContentHandlebarsTemplate to chain requests.</returns>
public ApplyStyleTemplate<TModel> WithCreateModelCallback(Func<Entity, TModel>? callback)
{
this.CreateModelCallback = callback;
return this;
}
public ApplyStyleTemplate<TModel> WithGetTemplateName(Func<Entity, string>? callback)
{
this.GetTemplateName = callback;
return this;
}
public ApplyStyleTemplate<TModel> WithHandlebars(IHandlebars? handlebars)
{
this.Handlebars = handlebars;
return this;
}
private Entity Apply(Entity entity, ITextContent content)
{
TModel model = this.CreateModelCallback!(entity);
string name = this.GetTemplateName!(entity);
HandlebarsTemplate<object, object> template = this.cache.GetNamedTemplate(name);
string result = template(model!);
return entity.SetTextContent(result);
}
}

View file

@ -0,0 +1,13 @@
using FluentValidation;
namespace Nitride.Handlebars;
public class ApplyStyleTemplateValidator<TModel> : AbstractValidator<ApplyStyleTemplate<TModel>>
{
public ApplyStyleTemplateValidator()
{
this.RuleFor(x => x.Handlebars).NotNull();
this.RuleFor(x => x.GetTemplateName).NotNull();
this.RuleFor(x => x.CreateModelCallback).NotNull();
}
}

View file

@ -1,70 +1,65 @@
using System.Collections.Generic; using System.Collections.Generic;
using HandlebarsDotNet; using HandlebarsDotNet;
using Open.Threading; using Open.Threading;
namespace Nitride.Handlebars namespace Nitride.Handlebars;
/// <summary>
/// Implements a cache for templates to prevent compiling the same template
/// more than once.
/// </summary>
public class HandlebarsTemplateCache
{ {
/// <summary> private readonly IHandlebars handlebars;
/// Implements a cache for templates to prevent compiling the same template
/// more than once. private readonly ModificationSynchronizer locker;
/// </summary>
public class HandlebarsTemplateCache private readonly Dictionary<string, HandlebarsTemplate<object, object>> templates;
public HandlebarsTemplateCache(IHandlebars handlebars)
{ {
private readonly IHandlebars handlebars; this.handlebars = handlebars;
this.locker = new ModificationSynchronizer();
this.templates = new Dictionary<string, HandlebarsTemplate<object, object>>();
}
private readonly ModificationSynchronizer locker; /// <summary>
/// Caches the template by name based on the contents of the disk. It
/// does it once in a multi-threaded manner to ensure it is only cached
/// once in memory.
/// </summary>
/// <param name="literal">The string that contains the template.</param>
/// <returns></returns>
public HandlebarsTemplate<object, object> GetLiteralTemplate(string literal)
{
// Start with a read lock to see if we've already compiled it.
this.locker.Modifying(
() => !this.templates.ContainsKey(literal),
() =>
{
HandlebarsTemplate<object, object> template = this.handlebars!.Compile(literal);
private readonly Dictionary<string, HandlebarsTemplate<object, object>> this.templates[literal] = template;
templates;
public HandlebarsTemplateCache(IHandlebars handlebars) return true;
{ });
this.handlebars = handlebars;
this.locker = new ModificationSynchronizer();
this.templates =
new Dictionary<string, HandlebarsTemplate<object, object>>();
}
/// <summary> return this.locker.Reading(() => this.templates[literal]);
/// Caches the template by name based on the contents of the disk. It }
/// does it once in a multi-threaded manner to ensure it is only cached
/// once in memory.
/// </summary>
/// <param name="literal">The string that contains the template.</param>
/// <returns></returns>
public HandlebarsTemplate<object, object> GetLiteralTemplate(
string literal)
{
// Start with a read lock to see if we've already compiled it.
this.locker.Modifying(
() => !this.templates.ContainsKey(literal),
() =>
{
HandlebarsTemplate<object, object> template =
this.handlebars
!.Compile(literal);
this.templates[literal] = template; /// <summary>
/// Caches the template by name based on the contents of the disk. It
/// does it once in a multi-threaded manner to ensure it is only cached
/// once in memory.
/// </summary>
/// <param name="templateName"></param>
/// <returns></returns>
public HandlebarsTemplate<object, object> GetNamedTemplate(string templateName)
{
string template = $"{{{{> {templateName}}}}}";
return true; return this.GetLiteralTemplate(template);
});
return this.locker.Reading(() => this.templates[literal]);
}
/// <summary>
/// Caches the template by name based on the contents of the disk. It
/// does it once in a multi-threaded manner to ensure it is only cached
/// once in memory.
/// </summary>
/// <param name="templateName"></param>
/// <returns></returns>
public HandlebarsTemplate<object, object> GetNamedTemplate(
string templateName)
{
string template = $"{{{{> {templateName}}}}}";
return this.GetLiteralTemplate(template);
}
} }
} }

View file

@ -1,11 +1,10 @@
namespace Nitride.Handlebars namespace Nitride.Handlebars;
/// <summary>
/// A marker component that indicates that a given file with text component
/// has a Handlebars template in it.
/// </summary>
public record HasHandlebarsTemplate
{ {
/// <summary> public static HasHandlebarsTemplate Instance { get; } = new();
/// A marker component that indicates that a given file with text component
/// has a Handlebars template in it.
/// </summary>
public class HasHandlebarsTemplate
{
public static HasHandlebarsTemplate Instance { get; } = new();
}
} }

View file

@ -1,32 +0,0 @@
using System.Collections.Generic;
using Gallium;
using Nitride.Contents;
namespace Nitride.Handlebars
{
/// <summary>
/// An operation that discovers which text files have a Handlebars template
/// inside them.
/// </summary>
public class IdentifyHandlebars : INitrideOperation
{
/// <inheritdoc />
public IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
return input
.ForEachEntity<ITextContent>(this.ScanContent);
}
private Entity ScanContent(Entity entity, ITextContent content)
{
string text = content.GetText();
if (text.Contains("{{") && text.Contains("}}"))
{
return entity.Set(HasHandlebarsTemplate.Instance);
}
return entity;
}
}
}

View file

@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
using FluentValidation;
using Gallium;
namespace Nitride.Handlebars;
/// <summary>
/// An operation that discovers which text files have a Handlebars template
/// based on a component.
/// </summary>
[WithProperties]
public partial class IdentifyHandlebarsFromComponent : IOperation
{
private readonly IValidator<IdentifyHandlebarsFromComponent> validator;
public IdentifyHandlebarsFromComponent(IValidator<IdentifyHandlebarsFromComponent> validator)
{
this.validator = validator;
}
public Func<Entity, bool> HasHandlebarsTest { get; set; } = null!;
/// <inheritdoc />
public IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
return input.Select(
(entity) => this.HasHandlebarsTest.Invoke(entity) ? entity.Set(HasHandlebarsTemplate.Instance) : entity);
}
}

View file

@ -0,0 +1,11 @@
using FluentValidation;
namespace Nitride.Handlebars;
public class IdentifyHandlebarsFromComponentValidator : AbstractValidator<IdentifyHandlebarsFromComponent>
{
public IdentifyHandlebarsFromComponentValidator()
{
this.RuleFor(x => x.HasHandlebarsTest).NotNull();
}
}

View file

@ -0,0 +1,32 @@
using System.Collections.Generic;
using Gallium;
using Nitride.Contents;
namespace Nitride.Handlebars;
/// <summary>
/// An operation that discovers which text files have a Handlebars template
/// inside them.
/// </summary>
public class IdentifyHandlebarsFromContent : IOperation
{
/// <inheritdoc />
public IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
return input.ForEachEntity<ITextContent>(this.ScanContent);
}
private Entity ScanContent(Entity entity, ITextContent content)
{
string text = content.GetText();
if (text.Contains("{{") && text.Contains("}}"))
{
return entity.Set(HasHandlebarsTemplate.Instance);
}
return entity;
}
}

View file

@ -1,36 +1,36 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable> <Nullable>enable</Nullable>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<Description>An extension to Nitride static site generator to style output with Handlebars.</Description> <Description>An extension to Nitride static site generator to style output with Handlebars.</Description>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Autofac" Version="6.2.0" /> <PackageReference Include="Autofac" Version="6.4.0"/>
<PackageReference Include="Gallium" Version="1.0.2" /> <PackageReference Include="Gallium" Version="1.0.2"/>
<PackageReference Include="Handlebars.Net" Version="2.0.8" /> <PackageReference Include="Handlebars.Net" Version="2.1.2"/>
<PackageReference Include="NodaTime.Testing" Version="3.0.5" /> <PackageReference Include="NodaTime.Testing" Version="3.1.0"/>
<PackageReference Include="Open.Threading" Version="1.6.3" /> <PackageReference Include="Open.Threading" Version="2.2.0"/>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride\Nitride.csproj" /> <ProjectReference Include="..\Nitride\Nitride.csproj"/>
</ItemGroup> </ItemGroup>
<!-- Include the source generator --> <!-- Include the source generator -->
<PropertyGroup> <PropertyGroup>
<EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles> <EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj"> <ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj">
<OutputItemType>Analyzer</OutputItemType> <OutputItemType>Analyzer</OutputItemType>
<ReferenceOutputAssembly>False</ReferenceOutputAssembly> <ReferenceOutputAssembly>False</ReferenceOutputAssembly>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -1,14 +1,11 @@
using Autofac; using Autofac;
namespace Nitride.Handlebars namespace Nitride.Handlebars;
public static class NitrideHandlebarsBuilderExtensions
{ {
public static class NitrideHandlebarsBuilderExtensions public static NitrideBuilder UseHandlebars(this NitrideBuilder builder)
{ {
public static NitrideBuilder UseHandlebars(this NitrideBuilder builder) return builder.ConfigureContainer(x => x.RegisterModule<NitrideHandlebarsModule>());
{
return builder
.ConfigureContainer(
x => x.RegisterModule<NitrideHandlebarsModule>());
}
} }
} }

View file

@ -1,22 +1,17 @@
using Autofac; using Autofac;
namespace Nitride.Handlebars namespace Nitride.Handlebars;
public class NitrideHandlebarsModule : Module
{ {
public class NitrideHandlebarsModule : NitrideModuleBase /// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{ {
/// <inheritdoc /> builder.RegisterOperators(this);
protected override void Register(ContainerBuilder builder) builder.RegisterValidators(this);
{
builder builder.RegisterType<HandlebarsTemplateCache>().AsSelf().SingleInstance();
.RegisterType<HandlebarsTemplateCache>() builder.RegisterGeneric(typeof(RenderContentTemplate<>)).As(typeof(RenderContentTemplate<>));
.AsSelf() builder.RegisterGeneric(typeof(ApplyStyleTemplate<>)).As(typeof(ApplyStyleTemplate<>));
.SingleInstance();
builder
.RegisterGeneric(typeof(ApplyContentHandlebarsTemplate<>))
.As(typeof(ApplyContentHandlebarsTemplate<>));
builder
.RegisterGeneric(typeof(ApplyStyleHandlebarsTemplate<>))
.As(typeof(ApplyStyleHandlebarsTemplate<>));
}
} }
} }

View file

@ -1,5 +1,4 @@
Nitride.Handlebars # Nitride.Handlebars
==================
This is a collection This is a collection
of [Handlebars](https://github.com/Handlebars-Net/Handlebars.Net) of [Handlebars](https://github.com/Handlebars-Net/Handlebars.Net)
@ -8,7 +7,7 @@ this package.
## IHandlebars ## IHandlebars
This library does *not* configure or register `IHandlebars` but requires it to This library does _not_ configure or register `IHandlebars` but requires it to
be injected into the DI container (Autofac) along with any templates or inlines be injected into the DI container (Autofac) along with any templates or inlines
loaded. loaded.

View file

@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using FluentValidation;
using Gallium;
using HandlebarsDotNet;
using Nitride.Contents;
namespace Nitride.Handlebars;
/// <summary>
/// An operation that uses the content to create a template that is then
/// applied against the content and metadata and then replaces the content
/// of that entity.
/// </summary>
public class RenderContentTemplate<TModel> : OperationBase
{
private readonly HandlebarsTemplateCache cache;
// TODO: This does not use [WithProperties] because the source generator hasn't been taught how to do generics.
private readonly IValidator<RenderContentTemplate<TModel>> validator;
public RenderContentTemplate(IValidator<RenderContentTemplate<TModel>> validator, HandlebarsTemplateCache cache)
{
this.validator = validator;
this.cache = cache;
}
/// <summary>
/// Gets or sets the callback used to create a model from a given
/// entity. This allows for the website to customize what information is
/// being passed to the template.
/// </summary>
public Func<Entity, TModel>? CreateModelCallback { get; set; }
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
return input.ForEachEntity<HasHandlebarsTemplate, ITextContent>(this.Apply);
}
/// <summary>
/// Sets the callback for the template and returns the operation to
/// chain operations.
/// </summary>
/// <param name="callback">The callback to set.</param>
/// <returns>The ApplyContentHandlebarsTemplate to chain requests.</returns>
public RenderContentTemplate<TModel> WithCreateModelCallback(Func<Entity, TModel>? callback)
{
this.CreateModelCallback = callback;
return this;
}
private Entity Apply(Entity entity, HasHandlebarsTemplate _, ITextContent content)
{
// Create the model using the callback.
TModel model = this.CreateModelCallback!(entity);
// Create a template from the contents.
string text = content.GetText();
HandlebarsTemplate<object, object> template = this.cache.GetLiteralTemplate(text);
// Render the template and create a new entity with the updated
// text.
string result = template(model!);
return entity.Remove<HasHandlebarsTemplate>().SetTextContent(new StringTextContent(result));
}
}

View file

@ -0,0 +1,11 @@
using FluentValidation;
namespace Nitride.Handlebars;
public class RenderContentTemplateValidator<TModel> : AbstractValidator<RenderContentTemplate<TModel>>
{
public RenderContentTemplateValidator()
{
this.RuleFor(x => x.CreateModelCallback).NotNull();
}
}

View file

@ -0,0 +1,29 @@
using System.Collections.Generic;
using System.Net;
using Gallium;
using Nitride.Contents;
namespace Nitride.Html;
/// <summary>
/// Converts the text input that uses HTML entities and turns them into
/// Unicode variations.
/// </summary>
public class ConvertHtmlEntitiesToUnicode : OperationBase
{
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
return input.ForEachEntity<ITextContent>(this.ResolveHtmlEntities);
}
private Entity ResolveHtmlEntities(Entity entity, ITextContent content)
{
string text = content.GetText();
string resolved = WebUtility.HtmlDecode(text);
return entity.SetTextContent(resolved);
}
}

View file

@ -1,31 +0,0 @@
using System.Collections.Generic;
using System.Net;
using Gallium;
using Nitride.Contents;
namespace Nitride.Html
{
/// <summary>
/// Converts the text input that uses HTML entities and turns them into
/// Unicode variations.
/// </summary>
public class HtmlEntitiesToUnicode : NitrideOperationBase
{
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
return input
.ForEachEntity<ITextContent>(this.ResolveHtmlEntities);
}
private Entity ResolveHtmlEntities(
Entity entity,
ITextContent content)
{
string text = content.GetText();
string resolved = WebUtility.HtmlDecode(text);
return entity.SetTextContent(resolved);
}
}
}

View file

@ -1,10 +1,9 @@
namespace Nitride.Html namespace Nitride.Html;
/// <summary>
/// A marker component that indicates that the entity is an HTML file.
/// </summary>
public record IsHtml
{ {
/// <summary> public static IsHtml Instance { get; } = new();
/// A marker component that indicates that the entity is an HTML file.
/// </summary>
public class IsHtml
{
public static IsHtml Instance { get; } = new();
}
} }

View file

@ -1,31 +1,31 @@
<Project Sdk="Microsoft.NET.Sdk"> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup> <PropertyGroup>
<TargetFramework>net5.0</TargetFramework> <TargetFramework>net6.0</TargetFramework>
</PropertyGroup> </PropertyGroup>
<PropertyGroup> <PropertyGroup>
<Description>An extension to Nitride static site generator to generate HTML output.</Description> <Description>An extension to Nitride static site generator to generate HTML output.</Description>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride\Nitride.csproj" /> <ProjectReference Include="..\Nitride\Nitride.csproj"/>
</ItemGroup> </ItemGroup>
<!-- Include the source generator --> <!-- Include the source generator -->
<PropertyGroup> <PropertyGroup>
<EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles> <EmitCompilerGeneratedFiles>True</EmitCompilerGeneratedFiles>
</PropertyGroup> </PropertyGroup>
<ItemGroup> <ItemGroup>
<ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj"> <ProjectReference Include="..\Nitride.Generators\Nitride.Generators.csproj">
<OutputItemType>Analyzer</OutputItemType> <OutputItemType>Analyzer</OutputItemType>
<ReferenceOutputAssembly>False</ReferenceOutputAssembly> <ReferenceOutputAssembly>False</ReferenceOutputAssembly>
</ProjectReference> </ProjectReference>
</ItemGroup> </ItemGroup>
<ItemGroup> <ItemGroup>
<PackageReference Include="Gallium" Version="1.0.2" /> <PackageReference Include="Gallium" Version="1.0.2"/>
</ItemGroup> </ItemGroup>
</Project> </Project>

View file

@ -1,14 +1,11 @@
using Autofac; using Autofac;
namespace Nitride.Html namespace Nitride.Html;
public static class NitrideHtmlBuilderExtensions
{ {
public static class NitrideHtmlBuilderExtensions public static NitrideBuilder UseHtml(this NitrideBuilder builder)
{ {
public static NitrideBuilder UseHtml(this NitrideBuilder builder) return builder.ConfigureContainer(x => x.RegisterModule<NitrideHtmlModule>());
{
return builder
.ConfigureContainer(
x => x.RegisterModule<NitrideHtmlModule>());
}
} }
} }

View file

@ -1,6 +1,12 @@
namespace Nitride.Html using Autofac;
namespace Nitride.Html;
public class NitrideHtmlModule : Module
{ {
public class NitrideHtmlModule : NitrideModuleBase /// <inheritdoc />
protected override void Load(ContainerBuilder builder)
{ {
builder.RegisterOperators(this);
} }
} }

View file

@ -1,35 +1,32 @@
using System.IO; using System.IO;
using Nitride.Contents; using Nitride.Contents;
using Zio; using Zio;
namespace Nitride.IO.Contents namespace Nitride.IO.Contents;
/// <summary>
/// Contains a wrapper around a file entry to retrieve the binary data.
/// </summary>
public class FileEntryBinaryContent : IBinaryContent, ITextContentConvertable
{ {
/// <summary> private readonly FileEntry entry;
/// Contains a wrapper around a file entry to retrieve the binary data.
/// </summary> public FileEntryBinaryContent(FileEntry entry)
public class FileEntryBinaryContent
: IBinaryContent, ITextContentConvertable
{ {
private readonly FileEntry entry; this.entry = entry;
}
public FileEntryBinaryContent(FileEntry entry) /// <inheritdoc />
{ public Stream GetStream()
this.entry = entry; {
} return this.entry.Open(FileMode.Open, FileAccess.Read, FileShare.Read);
}
/// <inheritdoc /> /// <inheritdoc />
public Stream GetStream() public ITextContent ToTextContent()
{ {
return this.entry.Open( return new FileEntryTextContent(this.entry);
FileMode.Open,
FileAccess.Read,
FileShare.Read);
}
/// <inheritdoc />
public ITextContent ToTextContent()
{
return new FileEntryTextContent(this.entry);
}
} }
} }

View file

@ -1,38 +1,33 @@
using System.IO; using System.IO;
using System.Text; using System.Text;
using Nitride.Contents; using Nitride.Contents;
using Zio; using Zio;
namespace Nitride.IO.Contents namespace Nitride.IO.Contents;
/// <summary>
/// Contains a wrapper around a file entry to retrieve text data.
/// </summary>
public class FileEntryTextContent : ITextContent, IBinaryContentConvertable
{ {
/// <summary> private readonly FileEntry entry;
/// Contains a wrapper around a file entry to retrieve text data.
/// </summary> public FileEntryTextContent(FileEntry entry)
public class FileEntryTextContent
: ITextContent, IBinaryContentConvertable
{ {
private readonly FileEntry entry; this.entry = entry;
}
public FileEntryTextContent(FileEntry entry) /// <inheritdoc />
{ public TextReader GetReader()
this.entry = entry; {
} return new StreamReader(this.entry.Open(FileMode.Open, FileAccess.Read, FileShare.Read), Encoding.UTF8);
}
/// <inheritdoc /> /// <inheritdoc />
public TextReader GetReader() public IBinaryContent ToBinaryContent()
{ {
return new StreamReader( return new FileEntryBinaryContent(this.entry);
this.entry.Open(
FileMode.Open,
FileAccess.Read,
FileShare.Read),
Encoding.UTF8);
}
/// <inheritdoc />
public IBinaryContent ToBinaryContent()
{
return new FileEntryBinaryContent(this.entry);
}
} }
} }

View file

@ -1,89 +1,85 @@
using System;
using System.Collections.Generic; using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using DotNet.Globbing; using DotNet.Globbing;
using FluentValidation;
using Gallium; using Gallium;
using Nitride.Contents; using Nitride.Contents;
using Zio; using Zio;
namespace Nitride.IO.Contents namespace Nitride.IO.Contents;
/// <summary>
/// A module that reads files from the file system and wraps them in an
/// entity with the following components: UPath, IContent.
/// </summary>
[WithProperties]
public partial class ReadFiles : FileSystemOperationBase
{ {
/// <summary> private readonly IValidator<ReadFiles> validator;
/// A module that reads files from the file system and wraps them in an
/// entity with the following components: UPath, IContent. public ReadFiles(IValidator<ReadFiles> validator, IFileSystem fileSystem)
/// </summary> : base(fileSystem)
public class ReadFiles : FileSystemOperation
{ {
public ReadFiles(IFileSystem fileSystem) this.validator = validator;
: base(fileSystem) }
{
}
/// <summary> /// <summary>
/// Primary method for creating a read file. /// Gets or sets the file pattern to retrieve fields. This supports
/// </summary> /// globbing both "*" and "**" patterns such as "**/*".
public delegate ReadFiles Factory(IFileSystem fileSystem); /// </summary>
public string Pattern { get; set; } = null!;
/// <summary> /// <summary>
/// Reads all files from the file system and returns them. /// Reads all files from the file system, filtering them out by the
/// </summary> /// minimatch pattern (as defined by DotNet.Blob).
/// <returns>A populated collection of entities.</returns> /// </summary>
public IEnumerable<Entity> Read( /// <returns>A populated collection of entities.</returns>
UPath path = new(), public IEnumerable<Entity> Run()
string searchPattern = "*", {
SearchOption search = SearchOption.AllDirectories) return this.Run(Array.Empty<Entity>());
{ }
// Normalize the path.
path = path == new UPath() ? "/" : path;
// Search for the file and wrap the results. /// <summary>
IEnumerable<FileEntry> files = this.FileSystem /// Reads all files from the file system, filtering them out by the
.EnumerateFileEntries(path, searchPattern, search); /// minimatch pattern (as defined by DotNet.Blob).
IEnumerable<Entity> entities = files.Select(this.ToEntity); /// </summary>
/// <returns>A populated collection of entities.</returns>
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
return entities; var glob = Glob.Parse(this.Pattern);
} IEnumerable<FileEntry> files = this.FileSystem.EnumerateFileEntries("/", "*", SearchOption.AllDirectories)
.Where(x => glob.IsMatch(x.Path.ToString()));
IEnumerable<Entity> entities = files.Select(this.ToEntity);
/// <summary> return entities;
/// Reads all files from the file system and returns them. }
/// </summary>
/// <returns>A populated collection of entities.</returns>
public IEnumerable<Entity> Read(string glob)
{
Glob parsed = Glob.Parse(glob);
return this.Read(parsed); public ReadFiles WithFileSystem(IFileSystem value)
} {
this.FileSystem = value;
return this;
}
/// <summary> /// <summary>
/// Reads all files from the file system, filtering them out by the /// Creates an entity with the standard components for all Zio-based
/// minimatch pattern (as defined by DotNet.Blob). /// files. This attaches the file's path relative to the file system
/// </summary> /// and a way of accessing the content from the file system.
/// <returns>A populated collection of entities.</returns> /// </summary>
public IEnumerable<Entity> Read(Glob glob) /// <param name="file">The Zio file entry.</param>
{ /// <returns>An Entity with appropriate content.</returns>
IEnumerable<FileEntry> files = this.FileSystem private Entity ToEntity(FileEntry file)
.EnumerateFileEntries("/", "*.*", SearchOption.AllDirectories) {
.Where(x => glob.IsMatch(x.Path.ToString())); Entity entity = new Entity().Set(file.Path).SetBinaryContent(new FileEntryBinaryContent(file));
IEnumerable<Entity> entities = files.Select(this.ToEntity);
return entities; return entity;
}
/// <summary>
/// Creates an entity with the standard components for all Zio-based
/// files. This attaches the file's path relative to the file system
/// and a way of accessing the content from the file system.
/// </summary>
/// <param name="file">The Zio file entry.</param>
/// <returns>An Entity with appropriate content.</returns>
private Entity ToEntity(FileEntry file)
{
Entity entity = new Entity()
.Set(file.Path)
.SetBinaryContent(new FileEntryBinaryContent(file));
return entity;
}
} }
} }

View file

@ -0,0 +1,12 @@
using FluentValidation;
namespace Nitride.IO.Contents;
public class ReadFilesValidator : AbstractValidator<ReadFiles>
{
public ReadFilesValidator()
{
this.RuleFor(x => x.Pattern).NotNull();
this.RuleFor(x => x.FileSystem).NotNull();
}
}

View file

@ -3,218 +3,209 @@ using System.Collections.Generic;
using System.IO; using System.IO;
using System.Linq; using System.Linq;
using System.Text; using System.Text;
using FluentValidation;
using Gallium; using Gallium;
using Nitride.Contents; using Nitride.Contents;
using Serilog; using Serilog;
using Zio; using Zio;
namespace Nitride.IO.Contents namespace Nitride.IO.Contents;
/// <summary>
/// An operation that writes out entities to a file system.
/// </summary>
[WithProperties]
public partial class WriteFiles : FileSystemOperationBase, IOperation
{ {
/// <summary> private readonly IValidator<WriteFiles> validator;
/// An operation that writes out entities to a file system.
/// </summary> private Dictionary<Type, Func<IContent, Stream>> factories;
[WithProperties]
public partial class WriteFiles : FileSystemOperation, INitrideOperation public WriteFiles(IValidator<WriteFiles> validator, ILogger logger, IFileSystem fileSystem)
: base(fileSystem)
{ {
private readonly ILogger logger; this.Logger = logger;
this.validator = validator;
private Dictionary<Type, Func<IContent, Stream>> factories; this.TextEncoding = Encoding.UTF8;
this.factories = new Dictionary<Type, Func<IContent, Stream>>
public WriteFiles(
IFileSystem fileSystem,
ILogger logger)
: base(fileSystem)
{ {
this.logger = logger.ForContext<WriteFiles>(); [typeof(IBinaryContent)] = GetBinaryStream,
this.factories = new Dictionary<Type, Func<IContent, Stream>> [typeof(ITextContent)] = this.GetTextStream,
{ };
[typeof(IBinaryContent)] = GetBinaryStream, }
[typeof(ITextContent)] = this.GetTextStream,
}; public ILogger Logger { get; set; } = null!;
public Dictionary<Type, Func<IContent, Stream>> StreamFactories
{
get => this.factories;
set => this.factories = value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Gets or sets the encoding to force any text output.
/// </summary>
public Encoding TextEncoding { get; set; }
/// <summary>
/// Writes out all the files to the given file system using the paths
/// currently stored in the `UPath` component. Only files that have
/// a path and a registered writer will be written.
/// </summary>
/// <param name="entities">The entities to parse.</param>
/// <returns>The same list of entities without changes.</returns>
public override IEnumerable<Entity> Run(IEnumerable<Entity> entities)
{
this.validator.ValidateAndThrow(this);
IEnumerable<Entity> results = entities.ForEachEntity<UPath>(this.Process).ToList();
return results;
}
public WriteFiles WithFileSystem(IFileSystem fileSystem)
{
this.FileSystem = fileSystem;
return this;
}
private static Stream GetBinaryStream(IContent content)
{
return ((IBinaryContent)content).GetStream();
}
private Stream GetTextStream(IContent content)
{
// See if we can convert the stream first. If that is the case, then
// we don't have to load it entirely in memory.
if (content is IBinaryContentConvertable convertable)
{
return convertable.ToBinaryContent().GetStream();
} }
/// <summary> // We have the load the text into memory and convert it.
/// Primary method for creating a write files operation. var textContent = (ITextContent)content;
/// </summary> string text = textContent.GetReader().ReadToEnd();
public delegate WriteFiles Factory(IFileSystem fileSystem); var stream = new MemoryStream();
var writer = new StreamWriter(stream, this.TextEncoding ?? Encoding.UTF8);
public Dictionary<Type, Func<IContent, Stream>> StreamFactories writer.Write(text);
writer.Flush();
stream.Position = 0;
return stream;
}
/// <summary>
/// Internal method for writing out the entity. This handles the
/// registered writers to allow for multiple `IContent` types being
/// written out automatically.
/// </summary>
/// <param name="entity">The entity to write out.</param>
/// <param name="path">The path of the entity.</param>
/// <returns>The entity passed in.</returns>
private Entity Process(Entity entity, UPath path)
{
// See if we have any content. If we don't, then there is nothing
// to do.
if (!entity.HasContent())
{ {
get => this.factories;
set => this.factories =
value ?? throw new ArgumentNullException(nameof(value));
}
/// <summary>
/// Gets or sets the encoding to force any text output.
/// </summary>
public Encoding? TextEncoding { get; set; }
/// <summary>
/// Writes out all the files to the given file system using the paths
/// currently stored in the `UPath` component. Only files that have
/// a path and a registered writer will be written.
/// </summary>
/// <param name="entities">The entities to parse.</param>
/// <returns>The same list of entities without changes.</returns>
public IEnumerable<Entity> Run(IEnumerable<Entity> entities)
{
// We need the `ToList()` here, otherwise it doesn't work.
IEnumerable<Entity> results = entities
.ForEachEntity<UPath>(this.Process)
.ToList();
return results;
}
private static Stream GetBinaryStream(IContent content)
{
return ((IBinaryContent)content).GetStream();
}
private Stream GetTextStream(IContent content)
{
// See if we can convert the stream first. If that is the case, then
// we don't have to load it entirely in memory.
if (content is IBinaryContentConvertable convertable)
{
return convertable.ToBinaryContent().GetStream();
}
// We have the load the text into memory and convert it.
var textContent = (ITextContent)content;
string text = textContent.GetReader().ReadToEnd();
var stream = new MemoryStream();
var writer = new StreamWriter(
stream,
this.TextEncoding ?? Encoding.UTF8);
writer.Write(text);
writer.Flush();
stream.Position = 0;
return stream;
}
/// <summary>
/// Internal method for writing out the entity. This handles the
/// registered writers to allow for multiple `IContent` types being
/// written out automatically.
/// </summary>
/// <param name="entity">The entity to write out.</param>
/// <param name="path">The path of the entity.</param>
/// <returns>The entity passed in.</returns>
private Entity Process(Entity entity, UPath path)
{
// See if we have any content. If we don't, then there is nothing
// to do.
if (!entity.HasContent())
{
return entity;
}
// First see if we have a factory for the exact type of content.
IContent content = entity.GetContent();
if (this.factories.TryGetValue(
content.GetType(),
out var getStream))
{
Stream stream = getStream(content);
return this.Process(entity, path, stream);
}
// If we have an easy conversion, then use that so we don't have to
// walk up the tree looking for one we do have.
if (content is IBinaryContentConvertable binaryConvertable
&& this.factories.TryGetValue(
typeof(IBinaryContent),
out var binaryContent))
{
Stream stream =
binaryContent(binaryConvertable.ToBinaryContent());
return this.Process(entity, path, stream);
}
if (content is ITextContentConvertable textConvertable
&& this.factories.TryGetValue(
typeof(ITextContent),
out var textContent))
{
Stream stream = textContent(textConvertable.ToTextContent());
return this.Process(entity, path, stream);
}
// For everything else, we have to find a content that we have a
// registered type for by walking up the inheritance tree and
// finding the right type.
List<Type> types = new() { content.GetType() };
while (types.Count > 0)
{
// Check to see if we have any of these types.
Func<IContent, Stream>? found = types
.Select(
x => this.factories.TryGetValue(x, out var factory)
? factory
: null)
.FirstOrDefault(x => x != null);
if (found != null)
{
Stream stream = found(content);
return this.Process(entity, path, stream);
}
// We didn't find one, so add all the parent types and try
// again with the new list.
types = types
.SelectMany(
x => new[] { x.BaseType }
.Union(x.GetInterfaces()))
.Where(x => x != null)
.Select(x => x!)
.ToList();
}
// If we got this far, we never found a content to handle.
throw new InvalidOperationException(
"Cannot write out entity "
+ path
+ " because cannot determine how to get a stream out content type "
+ content.GetType().FullName
+ ". To resolve, register a function to this.StreamFactories.");
}
/// <summary>
/// Writes out a stream to the given path in the file system.
/// </summary>
/// <param name="entity">The entity being written out.</param>
/// <param name="path">The path to write out, directories will be created.</param>
/// <param name="stream">The stream to write out.</param>
/// <returns>The entity passed in.</returns>
private Entity Process(Entity entity, UPath path, Stream stream)
{
// Make sure we have the directory structure.
UPath directory = path.GetDirectory();
if (directory != "/")
{
this.FileSystem.CreateDirectory(directory);
}
// Write out the file.
using Stream fileStream = this.FileSystem.CreateFile(path);
stream.CopyTo(fileStream);
stream.Close();
// Return the entity because we've written out the files.
return entity; return entity;
} }
// First see if we have a factory for the exact type of content.
IContent content = entity.GetContent();
if (this.factories.TryGetValue(content.GetType(), out Func<IContent, Stream>? getStream))
{
Stream stream = getStream(content);
return this.Process(entity, path, stream);
}
// If we have an easy conversion, then use that so we don't have to
// walk up the tree looking for one we do have.
if (content is IBinaryContentConvertable binaryConvertable
&& this.factories.TryGetValue(typeof(IBinaryContent), out Func<IContent, Stream>? binaryContent))
{
Stream stream = binaryContent(binaryConvertable.ToBinaryContent());
return this.Process(entity, path, stream);
}
if (content is ITextContentConvertable textConvertable
&& this.factories.TryGetValue(typeof(ITextContent), out Func<IContent, Stream>? textContent))
{
Stream stream = textContent(textConvertable.ToTextContent());
return this.Process(entity, path, stream);
}
// For everything else, we have to find a content that we have a
// registered type for by walking up the inheritance tree and
// finding the right type.
List<Type> types = new() { content.GetType() };
while (types.Count > 0)
{
// Check to see if we have any of these types.
Func<IContent, Stream>? found = types
.Select(x => this.factories.TryGetValue(x, out Func<IContent, Stream>? factory) ? factory : null)
.FirstOrDefault(x => x != null);
if (found != null)
{
Stream stream = found(content);
return this.Process(entity, path, stream);
}
// We didn't find one, so add all the parent types and try
// again with the new list.
types = types.SelectMany(x => new[] { x.BaseType }.Union(x.GetInterfaces()))
.Where(x => x != null)
.Select(x => x!)
.ToList();
}
// If we got this far, we never found a content to handle.
throw new InvalidOperationException(
"Cannot write out entity "
+ path
+ " because cannot determine how to get a stream out content type "
+ content.GetType().FullName
+ ". To resolve, register a function to this.StreamFactories.");
}
/// <summary>
/// Writes out a stream to the given path in the file system.
/// </summary>
/// <param name="entity">The entity being written out.</param>
/// <param name="path">The path to write out, directories will be created.</param>
/// <param name="stream">The stream to write out.</param>
/// <returns>The entity passed in.</returns>
private Entity Process(Entity entity, UPath path, Stream stream)
{
// Make sure we have the directory structure.
UPath directory = path.GetDirectory();
if (directory != "/")
{
this.FileSystem.CreateDirectory(directory);
}
// Write out the file.
using Stream fileStream = this.FileSystem.CreateFile(path);
stream.CopyTo(fileStream);
stream.Close();
// Return the entity because we've written out the files.
return entity;
} }
} }

View file

@ -0,0 +1,14 @@
using FluentValidation;
namespace Nitride.IO.Contents;
public class WriteFilesValidator : AbstractValidator<WriteFiles>
{
public WriteFilesValidator()
{
this.RuleFor(x => x.StreamFactories).NotNull();
this.RuleFor(x => x.TextEncoding).NotNull();
this.RuleFor(x => x.FileSystem).NotNull();
this.RuleFor(x => x.Logger).NotNull();
}
}

View file

@ -1,82 +1,92 @@
using System; using System;
using System.Collections.Generic; using System.Collections.Generic;
using FluentValidation;
using Gallium; using Gallium;
using Serilog; using Serilog;
using Zio; using Zio;
namespace Nitride.IO.Directories namespace Nitride.IO.Directories;
/// <summary>
/// A Nitride operation that removes the contents of a directory but not
/// the directory itself. This is used because some tools don't handle
/// when the root directory is removed.
/// This will create the top-level directory if it doesn't exist.
/// </summary>
[WithProperties]
public partial class ClearDirectory : FileSystemOperationBase, IOperation
{ {
/// <summary> private readonly IValidator<ClearDirectory> validator;
/// A Nitride operation that removes the contents of a directory but not
/// the directory itself. This is used because some tools don't handle public ClearDirectory(IValidator<ClearDirectory> validator, IFileSystem fileSystem, ILogger logger)
/// when the root directory is removed. : base(fileSystem)
/// This will create the top-level directory if it doesn't exist.
/// </summary>
[WithProperties]
public partial class ClearDirectory : FileSystemOperation, INitrideOperation
{ {
private readonly ILogger logger; this.Logger = logger;
this.validator = validator;
}
public ClearDirectory( public ILogger Logger { get; set; }
ILogger logger,
IFileSystem fileSystem) /// <summary>
: base(fileSystem) /// Gets or sets the path of the directory to clear.
/// </summary>
public UPath? Path { get; set; }
public IEnumerable<Entity> Run()
{
return this.Run(new List<Entity>());
}
/// <inheritdoc />
public override IEnumerable<Entity> Run(IEnumerable<Entity> input)
{
this.validator.ValidateAndThrow(this);
// This really isn't an input-type of operation, but it can fit
// inside one to keep a pattern.
if (!this.Path.HasValue)
{ {
this.logger = logger.ForContext<ClearDirectory>(); throw new InvalidOperationException(
nameof(ClearDirectory)
+ "cannot be used without setting the path either by the"
+ "factory method, the constructor, the property, or "
+ "SetPath method.");
} }
/// <summary> // See if the directory exists. If it doesn't, then we make it.
/// Gets or sets the path of the directory to clear. UPath path = this.Path.Value;
/// </summary>
public UPath? Path { get; set; }
public IEnumerable<Entity> Run() if (!this.FileSystem.DirectoryExists(path))
{ {
return this.Run(new List<Entity>()); this.Logger.Information("Creating the directory {Path}", path);
this.FileSystem.CreateDirectory(path);
} }
/// <inheritdoc /> // Clear out the contents.
public IEnumerable<Entity> Run(IEnumerable<Entity> input) IEnumerable<UPath> files = this.FileSystem.EnumerateFiles(path);
IEnumerable<UPath> directories = this.FileSystem.EnumerateDirectories(path);
foreach (UPath file in files)
{ {
// This really isn't an input-type of operation, but it can fit this.FileSystem.DeleteFile(file);
// inside one to keep a pattern.
if (!this.Path.HasValue)
{
throw new InvalidOperationException(
nameof(ClearDirectory)
+ "cannot be used without setting the path either by the"
+ "factory method, the constructor, the property, or "
+ "SetPath method.");
}
// See if the directory exists. If it doesn't, then we make it.
UPath path = this.Path.Value;
if (!this.FileSystem.DirectoryExists(path))
{
this.logger.Information(
"Creating the directory {Path}",
path);
this.FileSystem.CreateDirectory(path);
}
// Clear out the contents.
IEnumerable<UPath> files = this.FileSystem.EnumerateFiles(path);
IEnumerable<UPath> directories =
this.FileSystem.EnumerateDirectories(path);
foreach (UPath file in files)
{
this.FileSystem.DeleteFile(file);
}
foreach (UPath directory in directories)
{
this.FileSystem.DeleteDirectory(directory, true);
}
// Just pass the input on.
return input;
} }
foreach (UPath directory in directories)
{
this.FileSystem.DeleteDirectory(directory, true);
}
// Just pass the input on.
return input;
}
public ClearDirectory WithFileSystem(IFileSystem value)
{
this.FileSystem = value;
return this;
} }
} }

View file

@ -0,0 +1,13 @@
using FluentValidation;
namespace Nitride.IO.Directories;
public class ClearDirectoryValidator : AbstractValidator<ClearDirectory>
{
public ClearDirectoryValidator()
{
this.RuleFor(x => x.Path).NotNull();
this.RuleFor(x => x.FileSystem).NotNull();
this.RuleFor(x => x.Logger).NotNull();
}
}

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