diff --git a/.github/workflows/docs.yml b/.github/workflows/docs.yml
index 00f10c4..55300e0 100644
--- a/.github/workflows/docs.yml
+++ b/.github/workflows/docs.yml
@@ -1,11 +1,22 @@
name: Docs
-# Builds the documentation site with DocFX and publishes it to GitHub Pages. One workflow, two sites:
-# - in StellarEngine-Core: the site of the core (docfx.json): Docs/, the API reference, the schemas, the installer;
-# - in the mirror (StellarEngine-Mono), recognized by the .orchestra file scripts/mirror.ps1 puts at its root:
-# the site of the orchestra (scripts/orchestra-site.ps1), the core and every module in one site.
-# Pull requests and manual runs on other branches only build; the site is deployed from master only.
-# Repository setting required once: Settings -> Pages -> Source = "GitHub Actions".
+# Publishes the documentation of this repository to GitHub Pages for the Prometheus site (the team site).
+# GitHub Pages is only the storage of the site: static files (the installer, the schemas), the documentation as data
+# (bundle/) and a small embed that redirects to the site when the site is up.
+#
+# This file is a thin wrapper and does not need updates: the steps (ci.py, the bundle builder, the embed) are
+# downloaded from the site on every run (/docs-kit.zip), so they are always the same version as the site.
+# What to build is described by the repository itself in prometheus.json (format prometheus-repo/1, see the DOCS
+# page of the site); without it: Docs/ and the API of the projects in docfx.json.
+# If the site is down, the static files and a page that leads to the site are published; the next run fixes the rest.
+#
+# Repository settings:
+# Settings -> Pages -> Source = "GitHub Actions" (once)
+# Variables (optional): PROMETHEUS_SITE (https://notagood.org by default),
+# PROMETHEUS_PROJECT, PROMETHEUS_TITLE (override prometheus.json)
+# Secrets (optional): PROMETHEUS_SYNC_KEY an API key of the site with the "sync" scope: the site learns about
+# the new build at once instead of on its next check
+# Pull requests and manual runs on other branches only build; Pages is deployed from master only.
on:
push:
@@ -24,49 +35,88 @@ env:
DOCFX_VERSION: '2.81.0'
DOTNET_NOLOGO: 'true'
DOTNET_CLI_TELEMETRY_OPTOUT: 'true'
+ PROMETHEUS_SITE: ${{ vars.PROMETHEUS_SITE || 'https://notagood.org' }}
+ PROMETHEUS_PROJECT: ${{ vars.PROMETHEUS_PROJECT }}
+ PROMETHEUS_TITLE: ${{ vars.PROMETHEUS_TITLE }}
+ OUT: artifacts/pages
jobs:
build:
- name: Build site
- runs-on: ubuntu-latest
+ name: Build
+ runs-on: ubuntu-latest # pwsh, python3 and bash are there: "prepare" scripts may use any of them
steps:
- name: Checkout
uses: actions/checkout@v5
- name: Setup .NET
+ if: hashFiles('global.json') != ''
uses: actions/setup-dotnet@v5
with:
global-json-file: global.json
- # Installed outside the checkout so the repository NuGet.config (local "packages" feed) is not involved.
+ - name: Setup .NET (no global.json)
+ if: hashFiles('global.json') == ''
+ uses: actions/setup-dotnet@v5
+ with:
+ dotnet-version: '9.0.x'
+
+ # Installed outside the checkout so a repository NuGet.config (a local feed) is not involved.
- name: Install DocFX
working-directory: ${{ runner.temp }}
run: dotnet tool install docfx --version "$DOCFX_VERSION" --tool-path "$RUNNER_TEMP/docfx"
- - name: Choose the site
- id: site
- shell: pwsh
+ - name: Prometheus
+ id: prometheus
+ continue-on-error: true
run: |
- # The local feed of an installation: empty here, but NuGet wants the folder it names to exist
- New-Item -ItemType Directory -Force packages | Out-Null
- if (Test-Path .orchestra) {
- ./scripts/orchestra-site.ps1
- "config=docfx.orchestra.json" >> $env:GITHUB_OUTPUT
- "output=artifacts/docs/orchestra-site" >> $env:GITHUB_OUTPUT
- } else {
- "config=docfx.json" >> $env:GITHUB_OUTPUT
- "output=artifacts/docs/site" >> $env:GITHUB_OUTPUT
- }
+ set -euo pipefail
+ # NuGet wants the local feed folder of an installation to exist, even empty
+ mkdir -p packages
+ curl -fsSL --retry 2 "$PROMETHEUS_SITE/docs-kit.zip" -o "$RUNNER_TEMP/kit.zip"
+ unzip -q -o "$RUNNER_TEMP/kit.zip" -d "$RUNNER_TEMP/kit"
+ python3 -m pip install --quiet pyyaml
+ python3 "$RUNNER_TEMP/kit/ci.py" --out "$OUT" --docfx "$RUNNER_TEMP/docfx/docfx"
- # metadata (the API reference from the managed projects), then build
- - name: Build documentation
- run: '"$RUNNER_TEMP/docfx/docfx" "${{ steps.site.outputs.config }}" --warningsAsErrors'
+ # The site is down or the build failed: publish the static files and a page that leads to the site.
+ # Self-contained on purpose (no kit): the installer and the schemas keep their addresses whatever happens.
+ - name: Fallback
+ if: steps.prometheus.outcome == 'failure'
+ run: |
+ echo "::warning title=Prometheus::The documentation was not built (is $PROMETHEUS_SITE up?); publishing the static files only"
+ mkdir -p "$OUT" && touch "$OUT/.nojekyll"
+ python3 - <<'PY'
+ import glob, html, json, os, re, shutil
+ out = os.environ["OUT"]
+ cfg = json.load(open("prometheus.json", encoding="utf-8-sig")) if os.path.isfile("prometheus.json") else {}
+ static = cfg.get("static") or next((a.get("docfx") if isinstance(a, dict) else a for a in cfg.get("api") or []), None) \
+ or ("docfx.json" if os.path.isfile("docfx.json") else None)
+ for config in ([static] if isinstance(static, str) else static or []):
+ if not os.path.isfile(config):
+ continue
+ base = os.path.dirname(os.path.abspath(config))
+ for r in json.load(open(config, encoding="utf-8-sig")).get("build", {}).get("resource", []):
+ src, dest = os.path.join(base, r.get("src", "")), os.path.join(out, r.get("dest", ""))
+ for pattern in r.get("files", []):
+ for f in glob.glob(os.path.join(src, pattern), recursive=True):
+ if os.path.isfile(f):
+ t = os.path.join(dest, os.path.relpath(f, src))
+ os.makedirs(os.path.dirname(t), exist_ok=True)
+ shutil.copy2(f, t)
+ repo = os.environ.get("GITHUB_REPOSITORY", "").rsplit("/", 1)[-1]
+ project = os.environ.get("PROMETHEUS_PROJECT") or cfg.get("project") or re.sub(r"[^a-z0-9]+", "-", repo.lower()).strip("-")
+ url = html.escape(f"{os.environ['PROMETHEUS_SITE'].rstrip('/')}/docs/{project}")
+ title = html.escape(os.environ.get("PROMETHEUS_TITLE") or cfg.get("title") or repo)
+ with open(os.path.join(out, "index.html"), "w", encoding="utf-8") as f:
+ f.write(f'
{title}'
+ f''
+ f'{title} documentation
')
+ PY
- name: Upload Pages artifact
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master'
uses: actions/upload-pages-artifact@v5
with:
- path: ${{ steps.site.outputs.output }}
+ path: ${{ env.OUT }}
deploy:
name: Deploy to GitHub Pages
@@ -87,3 +137,13 @@ jobs:
- name: Deploy
id: deployment
uses: actions/deploy-pages@v5
+
+ # The site would notice the new bundle on its next check anyway; this makes it immediate.
+ - name: Nudge the site
+ continue-on-error: true
+ env:
+ KEY: ${{ secrets.PROMETHEUS_SYNC_KEY }}
+ run: |
+ if [ -z "$KEY" ]; then echo "::notice::PROMETHEUS_SYNC_KEY is not set: the site picks the docs up on its next check"; exit 0; fi
+ sleep 30 # Pages needs a moment to serve the new files
+ curl -fsS -X POST -H "Authorization: Bearer $KEY" "$PROMETHEUS_SITE/api/v1/sync"
diff --git a/.github/workflows/marks.yml b/.github/workflows/marks.yml
new file mode 100644
index 0000000..aa54a8d
--- /dev/null
+++ b/.github/workflows/marks.yml
@@ -0,0 +1,55 @@
+name: Marks
+
+# Marks in the comments of the code (Docs/Engine/Marks.md): one that stops a commit, or that nobody knows, does not
+# get in. The hooks of git check the same on a machine; they can be skipped, this cannot.
+#
+# One workflow for every repository: the core runs it as it is, a module calls it. The kinds of marks and the command
+# are those of the core, so a module is checked out into modules/ of a checkout of the core.
+
+on:
+ push:
+ branches: [develop, master]
+ pull_request:
+ workflow_call:
+
+permissions:
+ contents: read
+
+jobs:
+ marks:
+ name: Marks
+ if: vars.STELLAR_MIRROR != 'true'
+ runs-on: ubuntu-latest
+ env:
+ IS_CORE: ${{ github.event.repository.name == 'StellarEngine-Core' }}
+ steps:
+ - name: Checkout
+ if: env.IS_CORE == 'true'
+ uses: actions/checkout@v5
+
+ - name: Checkout the core
+ if: env.IS_CORE != 'true'
+ uses: actions/checkout@v5
+ with:
+ repository: QuantumDevTeam/StellarEngine-Core
+ ref: develop
+
+ - name: Checkout the module
+ if: env.IS_CORE != 'true'
+ uses: actions/checkout@v5
+ with:
+ path: modules/${{ github.event.repository.name }}
+
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v5
+ with:
+ global-json-file: global.json
+
+ # A pull request into master is a release: what may lie in develop may not go there
+ - name: Check the marks
+ env:
+ STAGE: ${{ (github.base_ref == 'master' || github.ref == 'refs/heads/master') && 'release' || 'commit' }}
+ TARGET: ${{ github.event.repository.name == 'StellarEngine-Core' && '.' || format('modules/{0}', github.event.repository.name) }}
+ run: |
+ mkdir -p packages
+ dotnet run --project SDK/src/Stellar.Cli/Stellar.Cli.csproj -- marks check "$TARGET" --stage "$STAGE"
diff --git a/.github/workflows/mirror.yml b/.github/workflows/mirror.yml
index 71a86a5..c9ffa9f 100644
--- a/.github/workflows/mirror.yml
+++ b/.github/workflows/mirror.yml
@@ -23,10 +23,18 @@ name: Mirror
# The first snapshot comes from a machine: scripts/mirror.ps1 -Push. After that this workflow is the only writer:
# on a machine, mirror.ps1 without -Push shows the next snapshot, Run workflow here publishes it.
+# It never starts by itself on a timer: a release of the core sends 'orchestra-release' (release.yml), or a person
+# presses Run workflow. Run workflow also takes a component the mirror does not hold yet.
+
on:
+ repository_dispatch:
+ types: [orchestra-release]
workflow_dispatch:
- schedule:
- - cron: '17 3 * * *'
+ inputs:
+ add:
+ description: 'New components, e.g. modules/Stellar.LoggingSystem (comma separated). Empty: the ones of the mirror'
+ required: false
+ default: ''
permissions:
contents: write
@@ -62,6 +70,8 @@ jobs:
shell: pwsh
env:
COMPONENTS_TOKEN: ${{ secrets.STELLAR_MIRROR_TOKEN || github.token }}
+ # Through the environment, never pasted into the script
+ ADD: ${{ inputs.add }}
run: |
if (-not (Test-Path .orchestra)) {
throw 'No .orchestra here: make the first snapshot on a machine with scripts/mirror.ps1 -Push'
@@ -85,6 +95,13 @@ jobs:
$workspace = Join-Path $env:RUNNER_TEMP 'orchestra'
$components = @((Get-Content .orchestra -Raw | ConvertFrom-Json).Components)
+ # New components: a repository of the organization of the mirror, at its default branch
+ foreach ($entry in @("$env:ADD" -split ',' | ForEach-Object { $_.Trim() } | Where-Object { $_ })) {
+ if ($entry -cnotmatch '^(modules|tools)/([A-Za-z][A-Za-z0-9.-]*)$') { throw "Not modules/ or tools/: $entry" }
+ $area, $name = $Matches[1], $Matches[2]
+ if ($components | Where-Object { $_.Name -eq $name }) { throw "$name is in the mirror already" }
+ $components += [pscustomobject]@{ Name = $name; Area = $area; Repository = "https://github.com/${{ github.repository_owner }}/$name.git" }
+ }
foreach ($component in $components) {
if ("$($component.Repository)" -like 'https://github.com/*' -and ($component.Repository -replace '\.git$', '') -ne $mirrorRepository) {
Set-Credentials $component.Repository $env:COMPONENTS_TOKEN
@@ -108,6 +125,18 @@ jobs:
"path=$workspace" >> $env:GITHUB_OUTPUT
"keep=$($keep -join ',')" >> $env:GITHUB_OUTPUT
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v5
+ with:
+ global-json-file: global.json
+
+ # The core and every component of the snapshot, as it will be pushed
+ - name: Check the marks
+ working-directory: ${{ steps.workspace.outputs.path }}
+ run: |
+ mkdir -p packages
+ dotnet run --project SDK/src/Stellar.Cli/Stellar.Cli.csproj -- marks check --all --stage release
+
- name: Snapshot and push
id: snapshot
shell: pwsh
diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml
index af08d79..b9a9f5e 100644
--- a/.github/workflows/release.yml
+++ b/.github/workflows/release.yml
@@ -5,9 +5,9 @@ name: Release
# into the tag v and a GitHub release of the core.
#
# The orchestra is released by the mirror: its workflow tags the snapshot with the same version and publishes the
-# release the installer installs. With the secret STELLAR_DISPATCH_TOKEN (a fine-grained token allowed to run the
-# Actions of the mirror) this workflow starts it at once; without it the release of the orchestra waits for the
-# nightly run of the mirror, or for Run workflow there.
+# release the installer installs. With the variable STELLAR_MIRROR_APP_ID and the secret STELLAR_MIRROR_APP_KEY (the app
+# that writes the mirror, see mirror.yml) this workflow starts it at once; without them the release of the orchestra
+# waits for Run workflow in the mirror. Merge the modules into their master before the core: a snapshot takes it.
#
# The mirror holds this file too, as everything of the core: it never runs there (STELLAR_MIRROR is 'true').
@@ -34,6 +34,17 @@ jobs:
with:
fetch-depth: 0
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v5
+ with:
+ global-json-file: global.json
+
+ # Nothing that a mark stops is released: a tag cannot be taken back
+ - name: Check the marks
+ run: |
+ mkdir -p packages
+ dotnet run --project SDK/src/Stellar.Cli/Stellar.Cli.csproj -- marks check --stage release
+
- name: Tag and publish
id: release
shell: pwsh
@@ -77,14 +88,20 @@ jobs:
if ($LASTEXITCODE -ne 0) { throw "gh release create $tag failed" }
"released=true" >> $env:GITHUB_OUTPUT
+ # Only a release starts the mirror. Without the app here, Run workflow in the mirror does it
+ - name: Token of the mirror app
+ id: app
+ if: steps.release.outputs.released == 'true' && vars.STELLAR_MIRROR_APP_ID != ''
+ uses: actions/create-github-app-token@v3
+ with:
+ client-id: ${{ vars.STELLAR_MIRROR_APP_ID }}
+ private-key: ${{ secrets.STELLAR_MIRROR_APP_KEY }}
+ owner: ${{ github.repository_owner }}
+ repositories: StellarEngine-Mono
+ permission-contents: write
+
- name: Start the mirror
- if: steps.release.outputs.released == 'true'
+ if: steps.app.outputs.token != ''
env:
- GH_TOKEN: ${{ secrets.STELLAR_DISPATCH_TOKEN }}
- MIRROR: ${{ vars.STELLAR_MIRROR_REPOSITORY || 'QuantumDevTeam/StellarEngine-Mono' }}
- run: |
- if [ -z "$GH_TOKEN" ]; then
- echo "::notice::No STELLAR_DISPATCH_TOKEN: the orchestra is released by the next run of the mirror ($MIRROR)"
- exit 0
- fi
- gh workflow run mirror.yml --repo "$MIRROR" --ref master
+ GH_TOKEN: ${{ steps.app.outputs.token }}
+ run: gh api "repos/${{ github.repository_owner }}/StellarEngine-Mono/dispatches" -f event_type=orchestra-release
diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml
new file mode 100644
index 0000000..c3f2d00
--- /dev/null
+++ b/.github/workflows/tests.yml
@@ -0,0 +1,80 @@
+name: Tests
+
+# Builds everything, native and managed, and runs the tests. One workflow for every repository, as marks.yml: the core
+# runs it as it is; a module calls it and is checked out into modules/ of a checkout of the core.
+#
+# Windows with the Visual Studio the native toolset asks for (Shared/Build/Stellar.Native.props), C++/CLI included.
+#
+# By itself only on the way into master; on any other branch by hand (Run workflow).
+
+on:
+ workflow_dispatch:
+ push:
+ branches: [master]
+ pull_request:
+ branches: [master]
+ workflow_call:
+
+permissions:
+ contents: read
+
+concurrency:
+ group: tests-${{ github.ref }}
+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}
+
+jobs:
+ tests:
+ name: Tests
+ if: vars.STELLAR_MIRROR != 'true'
+ runs-on: windows-2025-vs2026
+ timeout-minutes: 45
+ env:
+ IS_CORE: ${{ github.event.repository.name == 'StellarEngine-Core' }}
+ DOTNET_NOLOGO: 'true'
+ DOTNET_CLI_TELEMETRY_OPTOUT: 'true'
+ steps:
+ - name: Checkout
+ if: env.IS_CORE == 'true'
+ uses: actions/checkout@v5
+
+ - name: Checkout the core
+ if: env.IS_CORE != 'true'
+ uses: actions/checkout@v5
+ with:
+ repository: QuantumDevTeam/StellarEngine-Core
+ ref: develop
+
+ - name: Checkout the module
+ if: env.IS_CORE != 'true'
+ uses: actions/checkout@v5
+ with:
+ path: modules/${{ github.event.repository.name }}
+
+ - name: Setup .NET
+ uses: actions/setup-dotnet@v5
+ with:
+ global-json-file: global.json
+
+ - name: Build and test the core
+ if: env.IS_CORE == 'true'
+ shell: pwsh
+ run: |
+ New-Item -ItemType Directory -Force packages | Out-Null
+ ./scripts/build.ps1 -Configuration Debug
+
+ # Its own tests ran in the repository of the core
+ - name: Install the core
+ if: env.IS_CORE != 'true'
+ shell: pwsh
+ run: |
+ New-Item -ItemType Directory -Force packages | Out-Null
+ ./scripts/build.ps1 -Configuration Debug -SkipTests -Install -NoUserRegistration -SkipModules
+
+ - name: Build and test the module
+ if: env.IS_CORE != 'true'
+ shell: pwsh
+ env:
+ MODULE: ${{ github.event.repository.name }}
+ run: |
+ dotnet run --project SDK/src/Stellar.Cli/Stellar.Cli.csproj -c Debug --no-build -- modules build $env:MODULE --tests --pack
+ exit $LASTEXITCODE
diff --git a/.gitignore b/.gitignore
index 65937a5..33ae65d 100644
--- a/.gitignore
+++ b/.gitignore
@@ -16,8 +16,6 @@
/StellarEngine.*.slnf
# The bare repository scripts/mirror.ps1 builds the snapshots of the orchestra in
/.mirror/
-# The DocFX project of the orchestra site, generated by scripts/orchestra-site.ps1
-/docfx.orchestra.json
# ---- Build output ----
[Bb]in/
diff --git a/Core/tests/Managed/Stellar.Core.Tests/EngineInstanceTests.cs b/Core/tests/Managed/Stellar.Core.Tests/EngineInstanceTests.cs
index 0f4b62d..29ccf85 100644
--- a/Core/tests/Managed/Stellar.Core.Tests/EngineInstanceTests.cs
+++ b/Core/tests/Managed/Stellar.Core.Tests/EngineInstanceTests.cs
@@ -3,9 +3,7 @@
using Stellar.Core.Global;
using Stellar.Core.Native;
using Stellar.Core.Quantization;
-using Stellar.Kernel;
using Stellar.Kernel.Configuration;
-using Stellar.Kernel.EntryPoint;
using Stellar.Kernel.Lifecycle;
using Stellar.Kernel.Services;
using Stellar.Kernel.Threading;
@@ -18,7 +16,7 @@ namespace Stellar.Core.Tests;
///
public class EngineInstanceTests
{
- [Fact]
+ [NativeFact]
public void TwoEngines_HaveTheirOwnServicesAndRegistries()
{
var editor = new FakeEngine("Editor");
@@ -57,7 +55,7 @@ public void Outside_AnyEngine_TheDefaultIsUsed()
}
}
- [Fact]
+ [NativeFact]
public async Task TheScope_FollowsTheWork_IntoAwaitAndOtherThreads()
{
var engine = new FakeEngine("Flowing");
@@ -67,7 +65,7 @@ public async Task TheScope_FollowsTheWork_IntoAwaitAndOtherThreads()
await Task.Yield();
CoreEngine.Current.Instance.Should().BeSameAs(engine);
- var seen = await Task.Run(() => CoreEngine.Current.Instance);
+ IEngineInstance? seen = await Task.Run(() => CoreEngine.Current.Instance);
seen.Should().BeSameAs(engine);
IEngineInstance? onThread = null;
@@ -80,7 +78,7 @@ public async Task TheScope_FollowsTheWork_IntoAwaitAndOtherThreads()
CoreEngine.Release(engine);
}
- [Fact]
+ [NativeFact]
public void AQuant_LeavesTheRegistryOfTheEngineItWasMadeIn()
{
var first = new FakeEngine("First");
@@ -106,11 +104,11 @@ public void AQuant_LeavesTheRegistryOfTheEngineItWasMadeIn()
CoreEngine.Release(second);
}
- [Fact]
+ [NativeFact]
public void Releasing_AnEngine_DisposesItsNativeRegistries()
{
var engine = new FakeEngine("Short");
- var native = CoreEngine.For(engine).Native;
+ CoreContext native = CoreEngine.For(engine).Native;
CoreEngine.Release(engine).Should().BeTrue();
@@ -119,7 +117,7 @@ public void Releasing_AnEngine_DisposesItsNativeRegistries()
CoreEngine.Release(engine).Should().BeFalse();
}
- [Fact]
+ [NativeFact]
public void TheCoreModule_RunsForTheEngineOfItsContext()
{
var engine = new FakeEngine("Hosted");
@@ -155,6 +153,6 @@ private sealed class FakeEngine(string name)
public IMainThreadDispatcher Dispatcher => throw new NotSupportedException();
- public IServiceCatalog? Services => CoreEngine.For(this).Services;
+ public IServiceCatalog Services => CoreEngine.For(this).Services;
}
}
diff --git a/Core/tests/Managed/Stellar.Core.Tests/FailureTests.cs b/Core/tests/Managed/Stellar.Core.Tests/FailureTests.cs
index 9e5c475..84bc331 100644
--- a/Core/tests/Managed/Stellar.Core.Tests/FailureTests.cs
+++ b/Core/tests/Managed/Stellar.Core.Tests/FailureTests.cs
@@ -26,11 +26,21 @@ private sealed class RecordingLogger : ILogger
public Kernel.Data.Registry.IRegistrations Registrations => throw new NotSupportedException();
- public TMeta? FindMeta() where TMeta : class, IMetaQuant => null;
+ public TMeta? FindMeta()
+ where TMeta : class, IMetaQuant
+ {
+ return null;
+ }
- public void Log(LogLevel level, string message) => Lines.Add((level, message));
+ public void Log(LogLevel level, string message)
+ {
+ Lines.Add((level, message));
+ }
- public void LogWithoutFormat(string message) => Lines.Add((LogLevel.Info, message));
+ public void LogWithoutFormat(string message)
+ {
+ Lines.Add((LogLevel.Info, message));
+ }
public void Start()
{
@@ -47,21 +57,28 @@ private sealed class RecordingControl : IEngineControl
public Failure? Stopped { get; private set; }
- public void RequestStop(StopReason reason, Failure? failure = null) => Stopped = failure;
+ public void RequestStop(StopReason reason, Failure? failure = null)
+ {
+ Stopped = failure;
+ }
}
private sealed class Recorder : IFailureHandler
{
public List Heard { get; } = [];
- public void Handle(Failure failure) => Heard.Add(failure);
+ public void Handle(Failure failure)
+ {
+ Heard.Add(failure);
+ }
}
[Theory]
[InlineData(FailureLevel.NonCritical, FailureReaction.None)]
[InlineData(FailureLevel.Warning, FailureReaction.Log)]
[InlineData(FailureLevel.Error, FailureReaction.Log | FailureReaction.StopExecution)]
- [InlineData(FailureLevel.CriticalError, FailureReaction.Log | FailureReaction.StopExecution | FailureReaction.StopEngine)]
+ [InlineData(FailureLevel.CriticalError,
+ FailureReaction.Log | FailureReaction.StopExecution | FailureReaction.StopEngine)]
public void Levels_HaveTheirReactionsByDefault(FailureLevel level, FailureReaction reaction)
{
new FailureSystem().ReactionTo(new Failure(FailureKind.Engine, level, "x")).Should().Be(reaction);
@@ -130,8 +147,8 @@ public void AFailureThatLetsTheWorkGoOn_GivesTheFallback()
{
using var catcher = new Catcher(FailureKind.FileSystem, FailureLevel.Warning);
- var save = catcher.Try(() => throw new IOException("no save"), fallback: "empty");
- var next = catcher.Run(() => { });
+ string save = catcher.Try(() => throw new IOException("no save"), "empty");
+ bool next = catcher.Run(() => { });
save.Should().Be("empty");
next.Should().BeTrue();
@@ -142,9 +159,9 @@ public void AFailureThatLetsTheWorkGoOn_GivesTheFallback()
[Fact]
public void AFailureThatStopsTheWork_IsThrownOn_AndTheWholeTryStops()
{
- var reached = false;
+ bool reached = false;
- var block = () =>
+ Action block = () =>
{
using var catcher = new Catcher(FailureKind.FileSystem);
catcher.Run(() => throw new IOException("disk gone"));
@@ -158,8 +175,8 @@ public void AFailureThatStopsTheWork_IsThrownOn_AndTheWholeTryStops()
[Fact]
public void CatchBlocks_HandleTheirExceptions_AndAreNotReported()
{
- var firstRun = false;
- using var catcher = new Catcher(FailureKind.FileSystem)
+ bool firstRun = false;
+ using Catcher catcher = new Catcher(FailureKind.FileSystem)
.Catch(_ => firstRun = true)
.Catch(FailureLevel.Warning);
@@ -175,9 +192,9 @@ public void ErrorsOfTheEngine_KeepTheirFailure()
{
using var catcher = new Catcher(FailureKind.Application, FailureLevel.Warning);
- var block = () => catcher.Run(() => throw new DomainNotFoundException("assets"));
+ Func block = () => catcher.Run(() => throw new DomainNotFoundException("assets"));
- var thrown = block.Should().Throw().Which;
+ DomainNotFoundException thrown = block.Should().Throw().Which;
thrown.Failure.Kind.Should().Be(FailureKind.FileSystem);
catcher.Failures.Should().ContainSingle().Which.Should().BeSameAs(thrown.Failure);
}
@@ -192,7 +209,7 @@ public void AFailureCaughtAgain_KeepsItsFirstReaction()
using var outer = new Catcher(system, FailureKind.Engine, FailureLevel.Warning);
// A stop goes up through every catcher, as if none were there, until a plain try; it is reported once
- var block = () => outer.Run(() =>
+ Func block = () => outer.Run(() =>
{
using var inner = new Catcher(system, FailureKind.Engine);
inner.Run(() => throw new InvalidOperationException("deep"));
@@ -209,7 +226,7 @@ public void ACatcherThatKeepsAFew_KeepsTheLastOnes_AndCountsThemAll()
using var catcher = new Catcher(FailureKind.Engine, FailureLevel.Warning) { Keeps = 2 };
using var forgetful = new Catcher(FailureKind.Engine, FailureLevel.Warning) { Keeps = 0 };
- for (var i = 0; i < 5; i++)
+ for (int i = 0; i < 5; i++)
{
catcher.Report($"failure {i}");
forgetful.Report($"failure {i}");
@@ -219,7 +236,7 @@ public void ACatcherThatKeepsAFew_KeepsTheLastOnes_AndCountsThemAll()
catcher.Failures.Select(failure => failure.Message).Should().Equal("failure 3", "failure 4");
forgetful.HasFailed.Should().BeTrue();
forgetful.Failures.Should().BeEmpty();
- var negative = () => new Catcher { Keeps = -1 };
+ Func negative = () => new Catcher { Keeps = -1 };
negative.Should().Throw();
}
@@ -228,7 +245,8 @@ public void Guard_NeverThrows_AndGivesTheFailure()
{
using var catcher = new Catcher(FailureKind.Engine, FailureLevel.CriticalError);
- var failure = catcher.Guard(() => throw new InvalidOperationException("boom"), "the frame", phase: FramePhase.Update);
+ Failure? failure = catcher.Guard(() => throw new InvalidOperationException("boom"), "the frame",
+ phase: FramePhase.Update);
failure.Should().NotBeNull();
failure!.Message.Should().Be("the frame: boom");
@@ -257,7 +275,8 @@ public void Cancellation_IsNotAFailure()
{
using var catcher = new Catcher();
- catcher.Invoking(c => c.Run(() => throw new OperationCanceledException())).Should().Throw();
+ catcher.Invoking(c => c.Run(() => throw new OperationCanceledException())).Should()
+ .Throw();
catcher.HasFailed.Should().BeFalse();
}
@@ -269,10 +288,11 @@ public void ThrowIfFailed_ThrowsTheWorst()
catcher.Report(new InvalidOperationException("worse"), level: FailureLevel.NonCritical);
catcher.Report("the worst", FailureLevel.Warning);
- catcher.Invoking(c => c.ThrowIfFailed()).Should().Throw().WithMessage("a placeholder was used");
+ catcher.Invoking(c => c.ThrowIfFailed()).Should().Throw()
+ .WithMessage("a placeholder was used");
}
- [Fact]
+ [NativeFact]
public void InAnEngine_TheCatcherReportsToItsSystem()
{
var engine = new ScopeEngine("Failing");
@@ -283,7 +303,9 @@ public void InAnEngine_TheCatcherReportsToItsSystem()
using (EngineScope.Enter(engine))
using (var catcher = new Catcher(FailureKind.Engine, FailureLevel.Warning))
+ {
catcher.Run(() => throw new InvalidOperationException("in the engine"));
+ }
recorder.Count.Should().Be(1);
CoreEngine.Release(engine);
@@ -293,7 +315,10 @@ private sealed class FailureSystemRecorder : IFailureHandler
{
public int Count { get; private set; }
- public void Handle(Failure failure) => Count++;
+ public void Handle(Failure failure)
+ {
+ Count++;
+ }
}
}
@@ -310,12 +335,12 @@ public void EntryPoint_IsQuantAndDisposable()
[Fact]
public void Constructor_WithNullConfiguration_Throws()
{
- var action = () => new EntryPoint(null!);
+ Func action = () => new EntryPoint(null!);
action.Should().Throw();
}
- [Fact]
+ [NativeFact]
public void Run_PublishesTheFailureSystem_AndDisposeWithdrawsIt()
{
var engine = new ScopeEngine("Entry");
diff --git a/Core/tests/Managed/Stellar.Core.Tests/RegistryTests.cs b/Core/tests/Managed/Stellar.Core.Tests/RegistryTests.cs
index 9f3cde8..76c69a7 100644
--- a/Core/tests/Managed/Stellar.Core.Tests/RegistryTests.cs
+++ b/Core/tests/Managed/Stellar.Core.Tests/RegistryTests.cs
@@ -1,7 +1,6 @@
using Stellar.Core.Data.Registry;
using Stellar.Core.Global;
using Stellar.Core.Quantization;
-using Stellar.Kernel;
using Stellar.Kernel.Data.Registry;
using Stellar.Kernel.Lifecycle;
using Stellar.Kernel.Quantization;
@@ -31,7 +30,7 @@ private sealed class Prop()
public void ADerivedQuant_IsInTheRegistryOfItsBase_AndFoundAsWhatItIs()
{
using var player = new Player();
- var actors = CoreEngine.Current.Registry.Of();
+ IRegistry actors = CoreEngine.Current.Registry.Of();
actors.Get(player.UID).Should().BeSameAs(player);
actors.Get(player.UID).Should().BeSameAs(player);
@@ -49,7 +48,7 @@ public void AGetOfTheWrongType_IsNull_NotAGuess()
public void MarkedTypes_HaveRegistriesOfTheirOwn()
{
using var player = new Player();
- var registries = CoreEngine.Current.Registry;
+ CoreEngine.CoreRegistries registries = CoreEngine.Current.Registry;
registries.Of().Get(player.UID).Should().BeSameAs(player);
registries.Of().Get(player.UID).Should().BeSameAs(player);
@@ -60,9 +59,9 @@ public void MarkedTypes_HaveRegistriesOfTheirOwn()
[Fact]
public void KeysAndValues_FollowTheRegistry()
{
- var registry = CoreEngine.Current.Registry.Of();
+ IRegistry registry = CoreEngine.Current.Registry.Of();
var first = new Crate();
- var values = registry.Values;
+ ICollection values = registry.Values;
registry.Values.Should().BeSameAs(values);
using var second = new Crate();
@@ -79,7 +78,7 @@ private sealed class Crate()
public void Dispose_LeavesEveryRegistry()
{
var player = new Player();
- var registries = CoreEngine.Current.Registry;
+ CoreEngine.CoreRegistries registries = CoreEngine.Current.Registry;
player.Dispose();
@@ -93,7 +92,7 @@ public void Dispose_LeavesEveryRegistry()
public void AnyRegistry_CanTakeAnObject_AndTheObjectKnows()
{
using var prop = new Prop();
- var mine = new Registry();
+ Registry mine = new();
prop.Registrations.Should().BeEmpty();
CoreEngine.Current.Registry.Of().Exists(prop.UID).Should().BeFalse();
@@ -110,7 +109,7 @@ public void AnyRegistry_CanTakeAnObject_AndTheObjectKnows()
public void Dispose_LeavesARegistryMadeByHand()
{
var prop = new Prop();
- var mine = new Registry();
+ Registry mine = new();
mine.Register(prop);
prop.Dispose();
@@ -121,23 +120,31 @@ public void Dispose_LeavesARegistryMadeByHand()
[Fact]
public void ATypeWithoutRegistrableObjects_HasNoRegistry()
{
- FluentActions.Invoking(() => CoreEngine.Current.Registry.Of(typeof(string))).Should().Throw();
+ FluentActions.Invoking(() => CoreEngine.Current.Registry.Of(typeof(string))).Should()
+ .Throw();
}
- [Fact]
+ [NativeFact]
public void RegistriesOfTwoEngines_AreApart()
{
var first = new ScopeEngine("First");
var second = new ScopeEngine("Second");
Actor actor;
- using (EngineScope.Enter(first)) actor = new Actor();
+ using (EngineScope.Enter(first))
+ {
+ actor = new Actor();
+ }
CoreEngine.For(first).Registry.Of().Exists(actor.UID).Should().BeTrue();
CoreEngine.For(second).Registry.Of().Exists(actor.UID).Should().BeFalse();
// Disposed anywhere, it leaves the registries it is really in
- using (EngineScope.Enter(second)) actor.Dispose();
+ using (EngineScope.Enter(second))
+ {
+ actor.Dispose();
+ }
+
CoreEngine.For(first).Registry.Of().Exists(actor.UID).Should().BeFalse();
CoreEngine.Release(first);
@@ -148,7 +155,7 @@ public void RegistriesOfTwoEngines_AreApart()
[Collection(DetachedPolicyCollection.Name)]
public class DetachedPolicyTests
{
- [Fact]
+ [NativeFact]
public void Outside_AnyEngine_TheDefaultIsUsed_UnlessThePolicySaysOtherwise()
{
using (EngineScope.Enter(null))
@@ -156,14 +163,18 @@ public void Outside_AnyEngine_TheDefaultIsUsed_UnlessThePolicySaysOtherwise()
EngineScope.Resolve().Should().BeNull();
CoreEngine.Current.Should().BeSameAs(CoreEngine.Default);
- var previous = EngineScope.Detached;
+ DetachedPolicy previous = EngineScope.Detached;
EngineScope.Detached = DetachedPolicy.Throw;
try
{
FluentActions.Invoking(() => CoreEngine.Current).Should().Throw();
var engine = new ScopeEngine("Strict");
- using (EngineScope.Enter(engine)) CoreEngine.Current.Instance.Should().BeSameAs(engine);
+ using (EngineScope.Enter(engine))
+ {
+ CoreEngine.Current.Instance.Should().BeSameAs(engine);
+ }
+
CoreEngine.Release(engine);
}
finally
diff --git a/Core/tests/Managed/Stellar.Core.Tests/WrapperTests.cs b/Core/tests/Managed/Stellar.Core.Tests/WrapperTests.cs
index c30694e..3d25f0b 100644
--- a/Core/tests/Managed/Stellar.Core.Tests/WrapperTests.cs
+++ b/Core/tests/Managed/Stellar.Core.Tests/WrapperTests.cs
@@ -1,12 +1,11 @@
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
-using Stellar.Core.Data.Registry;
-using Stellar.Core.Modules;
-using Stellar.Core.Native;
+
using Stellar.Kernel;
using Stellar.Kernel.Interop;
using Stellar.Kernel.Versioning;
+using Stellar.Core.Native;
namespace Stellar.Core.Tests;
@@ -17,7 +16,8 @@ internal static class Build
{
private static string Metadata(string key)
{
- return typeof(Build).Assembly.GetCustomAttributes()
+ return typeof(Build).Assembly
+ .GetCustomAttributes()
.Single(attribute => attribute.Key == key).Value
?? string.Empty;
}
@@ -61,11 +61,14 @@ public class ContractTests
[InlineData(1u, 1u, 1u, 2u, false)]
[InlineData(2u, 0u, 1u, 0u, false)]
[InlineData(1u, 0u, 2u, 0u, false)]
- public void Satisfies_FollowsTheVersionRule(uint major, uint minor, uint requiredMajor, uint requiredMinor,
- bool expected)
+ public void Satisfies_FollowsTheVersionRule(
+ uint major, uint minor, uint requiredMajor, uint requiredMinor,
+ bool expected
+ )
{
- new ContractVersion(major, minor).Satisfies(new ContractVersion(requiredMajor, requiredMinor)).Should()
- .Be(expected);
+ new ContractVersion(major, minor)
+ .Satisfies(new ContractVersion(requiredMajor, requiredMinor))
+ .Should().Be(expected);
}
[Fact]
@@ -85,7 +88,7 @@ public void Handle_WithZeroGeneration_IsInvalid()
}
///
-/// The behaviour every wrapper must have. The suite runs once per wrapper: -p:StellarNativeWrapper=....
+/// The behavior every wrapper must have. The suite runs once per wrapper: -p:StellarNativeWrapper=....
///
public class WrapperTests
{
@@ -99,14 +102,19 @@ public void Wrapper_IsTheOneTheSdkChose()
public void Identifier_HasTheBytesOfTheNativeCore()
{
// The vector of the native tests: the same text gives the same 16 bytes on both sides
- Identifier.Parse("00112233-4455-6677-8899-aabbccddeeff").ToBytes().Should().Equal(
- 0x33, 0x22, 0x11, 0x00, 0x55, 0x44, 0x77, 0x66, 0x88, 0x99, 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF);
+ Identifier.Parse("00112233-4455-6677-8899-aabbccddeeff").ToBytes()
+ .Should().Equal(
+ 0x33, 0x22, 0x11, 0x00,
+ 0x55, 0x44,
+ 0x77, 0x66,
+ 0x88, 0x99,
+ 0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF);
}
[NativeFact]
public void Failures_ComeBackAsExceptions()
{
- var load = () => CoreContext.Current.Modules.Load("no-such-module.dll");
+ Func load = () => CoreContext.Current.Modules.Load("no-such-module.dll");
load.Should().Throw()
.Where(exception => exception.Result == NativeResult.NotFound)
@@ -117,9 +125,9 @@ public void Failures_ComeBackAsExceptions()
public void StaleModuleHandle_IsRejected()
{
var stale = new NativeHandle(1000, 1);
- var getName = () => CoreContext.Current.Modules.GetName(stale);
-
CoreContext.Current.Modules.Unload(stale).Should().BeFalse();
+
+ Func getName = () => CoreContext.Current.Modules.GetName(stale);
getName.Should().Throw()
.Where(exception => exception.Result == NativeResult.InvalidHandle);
}
@@ -137,39 +145,29 @@ public class WrapperParityTests
internal static string ManagedPath => Path.Combine(Build.EngineCoreDir, "artifacts", "bin",
"Stellar.Native.Core.Wrapper.Managed", Build.Configuration, "Stellar.Native.Core.Wrapper.Managed.dll");
- [BothWrappersFact]
- public void Wrappers_DefineTheSameApi()
- {
- var cli = Surface(CliPath);
- var managed = Surface(ManagedPath);
-
- cli.Except(managed).Should().BeEmpty("the C++/CLI wrapper must not have what the Managed one lacks");
- managed.Except(cli).Should().BeEmpty("the Managed wrapper must not have what the C++/CLI one lacks");
- }
-
private static SortedSet Surface(string path)
{
- var runtime = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll");
- var kernel = typeof(NativeHandle).Assembly.Location;
+ string[] runtime = Directory.GetFiles(RuntimeEnvironment.GetRuntimeDirectory(), "*.dll");
+ string kernel = typeof(NativeHandle).Assembly.Location;
var resolver = new PathAssemblyResolver(runtime.Append(kernel).Append(path));
using var context = new MetadataLoadContext(resolver);
- var assembly = context.LoadFromAssemblyPath(path);
- var surface = new SortedSet(StringComparer.Ordinal);
+ Assembly assembly = context.LoadFromAssemblyPath(path);
+ SortedSet surface = new(StringComparer.Ordinal);
const BindingFlags members = BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static |
BindingFlags.DeclaredOnly;
- foreach (var type in assembly.GetExportedTypes())
+ foreach (Type type in assembly.GetExportedTypes())
{
surface.Add($"type {type.FullName}");
- foreach (var member in type.GetMembers(members))
+ foreach (MemberInfo member in type.GetMembers(members))
{
- var signature = member switch
+ string? signature = member switch
{
- MethodBase { IsSpecialName: true } method when !method.IsConstructor &&
- !method.Name.StartsWith("op_") => null,
+ MethodBase { IsSpecialName: true, IsConstructor: false } method
+ when !method.Name.StartsWith("op_") => null,
MethodBase method =>
$"{Name(method)}({string.Join(", ", method.GetParameters().Select(Parameter))})"
+ (method is MethodInfo info ? $" : {TypeName(info.ReturnType)}" : string.Empty),
@@ -211,4 +209,14 @@ static string Parameter(ParameterInfo parameter)
$"{TypeName(parameter.ParameterType)} {parameter.Name}{(parameter.IsOptional ? " = optional" : string.Empty)}";
}
}
+
+ [BothWrappersFact]
+ public void Wrappers_DefineTheSameApi()
+ {
+ SortedSet cli = Surface(CliPath);
+ SortedSet managed = Surface(ManagedPath);
+
+ cli.Except(managed).Should().BeEmpty("the C++/CLI wrapper must not have what the Managed one lacks");
+ managed.Except(cli).Should().BeEmpty("the Managed wrapper must not have what the C++/CLI one lacks");
+ }
}
diff --git a/Docs/Architecture/NativeAbi.md b/Docs/Architecture/NativeAbi.md
index 3cae2f5..3cd5611 100644
--- a/Docs/Architecture/NativeAbi.md
+++ b/Docs/Architecture/NativeAbi.md
@@ -230,7 +230,7 @@ The native core follows the handle and umbrella rules of the Kernel:
```
A native project of a module gets the include directories, `STELLAR_KERNEL_STATIC` and the import libraries from
-`Shared/Build/Stellar.Native.Module.props` (see [Modules](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Modules.html)); the toolchain itself comes from
+`Shared/Build/Stellar.Native.Module.props` (see [Modules](../Engine/Modules.md)); the toolchain itself comes from
`Shared/Build/Stellar.Native.props`, shared with the core. Inside a module, paths start at the root of the module.
Headers of the C++/CLI wrapper end with `.cli.h`: MSVC also searches the folders of the open includes, and a wrapper
diff --git a/Docs/Architecture/Runtime.md b/Docs/Architecture/Runtime.md
index 2f03918..4bc17b4 100644
--- a/Docs/Architecture/Runtime.md
+++ b/Docs/Architecture/Runtime.md
@@ -271,7 +271,7 @@ wins:
| `ModuleInitializationParallelism` | `1` | How many modules of one level start at once |
| `Verbose` | `false` | The runtime tells every step on the error output |
-Settings the runtime does not know stay in `RuntimeConfiguration.Settings` for the modules.
+Modules find all of them in `RuntimeConfiguration.Settings`, the command line included, by names in any case.
## Exit codes
diff --git a/Docs/Architecture/Sdk.md b/Docs/Architecture/Sdk.md
index 537af99..eb60aac 100644
--- a/Docs/Architecture/Sdk.md
+++ b/Docs/Architecture/Sdk.md
@@ -26,14 +26,14 @@ them, but Rider shows an item written in a project file as a file of the project
The SDK version is pinned once, in `global.json`, not in every project:
```json
-{ "msbuild-sdks": { "Stellar.Sdk": "0.4.1" } }
+{ "msbuild-sdks": { "Stellar.Sdk": "0.4.2" } }
```
The SDK itself comes from the local feed through `NuGet.config`. `stellar project new` and `stellar modules new`
generate both files; a project under the root of the installation also finds the `NuGet.config` of the root.
A module project needs even less: it is nearly empty, and the SDK takes its kind, version and dependencies from its
-descriptor. See [Modules](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Modules.html). Every property: [Sdk.Properties](../Reference/Sdk.Properties.md).
+descriptor. See [Modules](../Engine/Modules.md). Every property: [Sdk.Properties](../Reference/Sdk.Properties.md).
## Kinds of projects
@@ -136,7 +136,7 @@ NuGet cache: the next restore of a game takes the new ones.
| Target | Task | Result | Switch (`=false`) |
|---|---|---|---|
| `StellarResolveProject` | `ResolveStellarProject` | Parses `.stellar.project`, selects assets | `StellarEnableAssets` for the assets |
-| `StellarCompileResources` | `CompileStellarResources` | `resources/**/*.sres` in the output | `StellarEnableResourceCompilation` |
+| `StellarCompileResources` | `CompileStellarResources` | `Resources/**/*.sres` in the output | `StellarEnableResourceCompilation` |
| `StellarGenerateRuntimeConfiguration` | `GenerateRuntimeConfiguration` | `{Project}.stellar.runtime.config.json` | `StellarEnableRuntimeConfiguration` |
| `StellarGenerateLauncher` | `GenerateStellarLauncher` | The `Main` of an executable module | `StellarEnableLauncher` |
diff --git a/Docs/Architecture/Tools.md b/Docs/Architecture/Tools.md
index 9dd801d..6643782 100644
--- a/Docs/Architecture/Tools.md
+++ b/Docs/Architecture/Tools.md
@@ -83,7 +83,7 @@ Later additions win, and anything no compiler claims is packed as is by `RawReso
| `stellar uninstall [path]` | Remove an installation: unregister it, drop its packages from the NuGet cache, remove what the installer made; `--all`, `--artifacts`, `--dry-run` |
| `stellar modules list` | Show the manifest in load order |
| `stellar modules sync` | Find the modules, apply the manifest, check the rules, regenerate the catalog |
-| `stellar modules new`, `templates`, `add`, `enable`, `disable`, `reset`, `build` | See [Modules](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Modules.html) |
+| `stellar modules new`, `templates`, `add`, `enable`, `disable`, `reset`, `build` | See [Modules](../Engine/Modules.md) |
| `stellar solution sync [directory]` | Write the `.sln` again: the projects of the solution, the engine when `"Engine"` is `Sources` |
| `stellar run [target]` | Build and run a game or a tool of the solution, or several at once; see [`.stellar.solution`](../Formats/SolutionFile.md) |
| `stellar project new ` | Create a solution and its project in a folder of its own; `--flat` for the project alone |
diff --git a/Docs/Engine/Architecture.md b/Docs/Engine/Architecture.md
index ebdad9a..6643a4b 100644
--- a/Docs/Engine/Architecture.md
+++ b/Docs/Engine/Architecture.md
@@ -4,7 +4,7 @@
> It is intended to explain *how the system is structured* and *why it is structured this way*,
> without going into low-level implementation details.
-- [README.md](../../README.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
---
diff --git a/Docs/Engine/DesignPhilosophy.md b/Docs/Engine/DesignPhilosophy.md
index de4652b..1e13e39 100644
--- a/Docs/Engine/DesignPhilosophy.md
+++ b/Docs/Engine/DesignPhilosophy.md
@@ -4,7 +4,7 @@
> It explains *why* the project exists, *how decisions are made*,
> and *what kind of system StellarEngine intentionally aims to be*.
-- [README.md](../../README.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
---
diff --git a/Docs/Engine/Documentation.md b/Docs/Engine/Documentation.md
new file mode 100644
index 0000000..a46389f
--- /dev/null
+++ b/Docs/Engine/Documentation.md
@@ -0,0 +1,103 @@
+# Writing the documentation
+
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
+
+The documentation of the engine is Markdown in the repositories, next to the code it describes. The docs site reads
+it; nothing about it is edited on the site.
+
+## Where it is read
+
+Every repository publishes a bundle of its documentation to its GitHub Pages: its `Docs/` and the API reference made
+from the XML comments of its code. The docs site shows the bundles, one project each:
+
+| Project | Repository | What |
+|---|---|---|
+| `stellar-engine` | StellarEngine-Mono, the mirror | the whole engine: the guide (`Docs/Engine` of the core), the core with its API, every module and tool |
+| `stellar-core` | StellarEngine-Core | the core alone: `Docs/` without `Docs/Engine`, its API |
+| a module or a tool | its own repository | its `Docs/` |
+
+The address of the docs site is set once, in `StellarDocsUri` of `Shared/Build/Stellar.Versions.props`, with the
+projects of the core and of the engine next to it. The tools take them from there; Markdown never names the site.
+GitHub Pages also keeps the installer and the JSON schemas at the addresses of `StellarSiteUri`.
+
+## What a repository publishes
+
+`prometheus.json` at the root of a repository says what goes into its bundle: the project, its title, where its
+version is, the folders of articles, the API, the static files, and where links out of the bundle go.
+
+```json
+{
+ "format": "prometheus-repo/1",
+ "project": "stellar-filesystem",
+ "title": "Stellar.FileSystem",
+ "version": { "file": "Stellar.FileSystem.stellar.module", "regex": "\"Version\"\\s*:\\s*\"([^\"]+)\"" },
+ "docs": [ { "path": "Docs" } ],
+ "static": "docfx.json"
+}
+```
+
+A module gets one from `stellar modules new`. Its `project` is a guess made from the id of the module: it must be the
+name of the card of the module on the docs site.
+
+The core does not write its description by hand. Its `prometheus.json` names `scripts/prometheus.ps1`, which the docs
+workflow runs first: it writes the description of the core, or, in the mirror, that of the whole engine, with every
+module and tool that has a `Docs/toc.yml`. Only this script knows the layout of the engine. To look at what it
+writes:
+
+```powershell
+powershell -File scripts/prometheus.ps1 -Print
+```
+
+The format of `prometheus.json` belongs to the docs site, which documents every field.
+
+## Links
+
+| To | Write | Example |
+|---|---|---|
+| a page of the same bundle | a relative path to the `.md` file | `[Modules](Modules.md)` |
+| a page of the same repository, published by another project | a relative path too; `links` of `prometheus.json` says which project | from `Docs/Architecture/Sdk.md`: `[Modules](../Engine/Modules.md)` |
+| a page of another repository | `prometheus:/`, the page being its path in `Docs/` without `.md` | `[the guide](prometheus:stellar-engine/guide/Install)` |
+| a file that is not documentation (README, LICENSE) | its address on GitHub | `https://github.com/QuantumDevTeam/StellarEngine-Core#readme` |
+
+Relative links work on GitHub as well as on the site. A `prometheus:` link works on the site only: use it between
+repositories, where nothing else can.
+
+Never write the address of the docs site or of GitHub Pages into a page: when the site moves, the pages stay right.
+
+## Checking it on a machine
+
+The builder of the bundle comes from the docs site, in `docs-kit.zip`. A bundle built on a machine shows the broken
+links of the pages before a push. In the core, the description is written to a file of its own first, so that
+`prometheus.json` of the repository stays as it is:
+
+```powershell
+powershell -File scripts/prometheus.ps1 -Output artifacts/prometheus.json
+python build_bundle.py --config artifacts/prometheus.json --out artifacts/bundle
+```
+
+A module has its description committed: `python build_bundle.py --out artifacts/bundle` in its folder.
+
+The whole run of the workflow, the static files and the embed included, is `ci.py` of the same kit, in the folder of
+the repository. It runs the `prepare` script of `prometheus.json` (PowerShell 7, or Windows PowerShell where there is
+no other), which writes the description into `artifacts/prometheus/`: `prometheus.json` of the repository stays as it
+is.
+
+```powershell
+$env:PROMETHEUS_SITE = 'https://notagood.org'
+python ci.py --out artifacts/pages --skip-metadata
+```
+
+`--skip-metadata` takes the API made before (`docfx metadata docfx.json`); without it, `--docfx` names the `docfx`
+to run.
+
+A `warning` line names a link that does not lead anywhere. The docs workflow prints the same lines, and publishes
+anyway.
+
+## Publishing
+
+A push to the default branch runs the docs workflow of the repository: it builds the bundle and puts it on GitHub
+Pages, and the docs site picks it up within minutes (at once, when the repository has the key of the site). A
+release of the mirror makes the new version of the engine appear on the site.
+
+Settings of a repository, once: Settings → Pages → Source = GitHub Actions; the card of the project on the docs site
+points at `https://quantumdevteam.github.io//bundle/`.
diff --git a/Docs/Engine/FAQ.md b/Docs/Engine/FAQ.md
new file mode 100644
index 0000000..1602627
--- /dev/null
+++ b/Docs/Engine/FAQ.md
@@ -0,0 +1,81 @@
+# Questions
+
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
+
+Short answers to what comes up first. The pages they point at say it in full.
+
+## Installing and building
+
+**Does `build.ps1 -Install` remove the old installation first?**
+No. `-Uninstall` is a mode of its own: it does its work and stops, and it is refused together with `-Install` or
+`-Pack`. An install only replaces the `stellar` command with the one it has just packed. Everything the installation
+holds stays: `stellar install` never overwrites a file. See [the layout](Repository.md).
+
+**Why does `-Install` pack when `-Pack` is not given?**
+An installation needs its local feed, `packages/`, so `-Install` implies `-Pack`. Packing in turn needs the native
+core: the package of Stellar.Core carries it with its wrapper, so `-Pack` cannot be combined with `-SkipNative`.
+
+**Does `build.ps1` check the toolchain?**
+The installer does ([Installing](Install.md)): it checks Git, the .NET SDK and Visual Studio first and prints what is
+missing. `build.ps1` assumes them and stops at the first tool that is not there.
+
+**Can the engine be built on Linux?**
+Not yet. `build.ps1` already picks the right wrapper there (the P/Invoke one) and `-SkipNative` builds and tests the
+managed part. The native projects are Visual Studio projects, though, and games and modules target Windows, so
+packing and installing need Windows.
+
+**What are the `Cli` and `Managed` wrappers?**
+Two wrappers of the native core with the same classes. `Cli` is C++/CLI: Windows only, and only where Visual Studio
+has its C++/CLI component. `Managed` is C# over the P/Invoke exports of the native core: it works everywhere and with
+Native AOT. `StellarNativeWrapper` chooses; by default the SDK takes `Cli` where it was built. See
+[Native core](../Architecture/NativeAbi.md).
+
+## Finding the installation
+
+**How does a game find the engine?**
+Through `$(StellarRoot)`, which Stellar.Sdk sets: the `StellarRoot` property, the `STELLAR_ROOT` variable, a folder
+above the project with `manifests/engine.manifest.json`, or the registry of the user, `~/.stellar`, for the orchestra
+version of its Stellar.Sdk. Its packages come from `packages/` of that installation, through its `NuGet.config`. See
+[the layout](Repository.md).
+
+**What is in `~/.stellar`?**
+Where each orchestra version is installed: `installations.json`, and `installations.props` made from it for MSBuild.
+One installation per version, and one version per root. What an orchestra holds is in its own `manifests/`.
+
+## Modules
+
+**Why is `Modules` empty in `manifests/engine.manifest.json`?**
+Modules are found by themselves: a folder of `modules/` with a `.stellar.module` file is a module. The manifest
+only holds what this installation does differently: a module that lives elsewhere (`Path`), one turned off
+(`Enabled`), another version or way of linking it (`Link`). `stellar modules add`, `enable`, `disable` and `reset`
+write it. The full list of modules is the generated catalog in `manifests/.generated/`. See
+[Engine manifest](../Formats/EngineManifest.md).
+
+**What does `Link` of a module mean?**
+How projects reference it. `Default`: as the project decides (`StellarPrecompiled`), sources in Debug and packages
+otherwise. `Sources`: always the sources, through a project reference. `Package`: always the package of the local
+feed. A module the manifest declares with a `Version` and no folder is always a package.
+
+**What writes the catalog of modules, and when?**
+`stellar modules sync`, and `stellar install` through it: it finds the modules, applies the manifest, checks the rule
+of the levels and writes `stellar.modules.props` for MSBuild and `stellar.modules.json` for tools, only when they
+change. A module project learns its level, version and dependencies from it. See [Modules](Modules.md).
+
+**Why do I not list `Stellar.Kernel` and `Stellar.Core` as dependencies?**
+Every project gets them implicitly, and a game gets `Stellar.Runtime` too, which its launcher calls. A dependency on
+them in a descriptor is dropped with a warning. A project turns one off with `StellarImplicitKernelReference`,
+`StellarImplicitCoreReference` or `StellarImplicitRuntimeReference` set to `false`; empty means on. See
+[SDK properties](../Reference/Sdk.Properties.md).
+
+## The build of a game
+
+**What is in `bin/` of a game?**
+`.exe` (the apphost of .NET) and `.Launcher.dll`, which calls `StellarRuntime.Run`; the game itself,
+`.dll`, a library; `.stellar.runtime.config.json`, its modules in load order and its settings; the engine
+(`Stellar.Kernel`, `Stellar.Core`, `Stellar.Runtime`) with the native core and its wrapper; compiled resources in
+`Resources/`. See [Runtime](../Architecture/Runtime.md).
+
+**Sources or packages?**
+A game takes the engine as packages. With `"Engine": "Sources"` in its `.stellar.solution` it takes the sources in
+Debug, and packages in every other configuration. On a machine without the sources of the core it takes packages
+anyway, with a warning.
diff --git a/Docs/Engine/GitPolicy.md b/Docs/Engine/GitPolicy.md
index 6d029e2..7faa385 100644
--- a/Docs/Engine/GitPolicy.md
+++ b/Docs/Engine/GitPolicy.md
@@ -1,6 +1,6 @@
# StellarEngine — Git & Collaboration Policy
-- [README.md](../../README.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
## 1. Purpose of This Document
@@ -60,35 +60,97 @@ Version numbers **must not** appear in commit messages.
## 3. Branches
-The project allows the following branch types:
+| Branch | What it is | How code gets in |
+|---|---|---|
+| `master` | what is released | a pull request from `develop` |
+| `develop` | active development and integration | a pull request from a work branch |
+| `feature/*` | one task | commits |
+| `experiment/*` | temporary or high-risk research work | commits |
-* `main` — stable integration branch
-* `develop` — active development and integration
-* `feature/*` — development of specific systems or technologies
-* `experiment/*` — temporary or high-risk research work
+`master` and `develop` take pull requests only: nobody pushes there, the owner included. A work branch may be rewritten
+or abandoned; once merged it is deleted.
-Branches may be:
+---
-* deleted without preservation
-* rewritten
-* abandoned
+## 4. The way of a change
-This is expected and acceptable.
+The same in the core, in a module and in a tool. Each is a repository of its own: run the commands in its folder.
----
+### 4.1 Every day
-## 4. Merging
+```powershell
+# 1. A branch, from a fresh develop
+git switch develop
+git pull --ff-only
+git switch -c feature/
-Before merging into `main`:
+# 2. Commits, small ones. The hooks check the marks
+git add .
+git commit -m "[TAG] "
-* the code must build
-* changes must be logically complete
-* commit history must remain readable
+# 3. A pull request into develop
+git push -u origin HEAD
+gh pr create -B develop --fill
-Versions (Git tags) are **created only on `main`**.
+# 4. Merged once everything is green
+gh pr checks --watch
+gh pr merge --merge --delete-branch
----
+# 5. Back to develop
+git switch develop
+git pull --ff-only
+```
+
+A pull request into `develop` waits for the marks and the CLA, not for the tests: they run by themselves only for
+`master`. Test on your machine (`scripts/build.ps1`, `stellar modules build --tests`), and to test a branch on
+the server start it by hand, for example after several merges into `develop`: *Actions → Tests → Run workflow*, or
+
+```powershell
+gh workflow run tests.yml --ref develop
+```
+
+The button appears once the workflow is in `master`.
+
+More commits on the same task before the merge: `git commit` and `git push`, the pull request takes them by itself.
+
+Always a **merge commit**, never a squash or a rebase: those make other commits out of the same changes, and `develop`
+and `master` drift apart.
+
+### 4.2 A change of several repositories
+The one the others use goes first: the core, then the modules. At a release it is the other way round (4.3).
+
+### 4.3 A release
+
+A snapshot of the mirror takes `master` of every component, so the core goes last:
+
+1. each module that changed: a pull request from `develop` into `master`, merged;
+2. the core: the new versions in `Shared/Build/Stellar.Versions.props` through a usual pull request into `develop`;
+3. the core: a pull request from `develop` into `master`. **Its merge releases the version**;
+4. the mirror: Run workflow of *Mirror* in StellarEngine-Mono, unless the release started it.
+
+```powershell
+gh pr create -B master -H develop -t " " -b ""
+gh pr checks develop --watch
+gh pr merge develop --merge
+```
+
+`develop` is not deleted, and `master` is never merged back by hand.
+
+### 4.4 When something is in the way
+
+| What you see | What to do |
+|---|---|
+| the commit is stopped by a mark | `stellar marks list`, look at the place, take the mark out or leave the file out of the commit |
+| `push` says *protected branch* | you are on `develop` or `master`: `git switch -c feature/` and push that; the commits come with you |
+| the pull request says *out of date* or *conflicts* | `git fetch origin`, `git merge origin/develop` in the work branch, solve, commit, push |
+| a check is red | open it, fix in the same branch, push |
+| `pull --ff-only` refuses | there are commits on `develop` that are not on the server: `git switch -c feature/`, then `git branch -f develop origin/develop` |
+
+Before merging into `master` the code must build, changes must be logically complete, and the history must remain
+readable. Versions (Git tags) are **created only on `master`**.
+
+---
## 5. Git Tags
### 5.1 Version Tags
@@ -147,5 +209,5 @@ Each contributor:
Also see:
- [Versioning.md](Versioning.md)
-- [CONTRIBUTING.md](../../CONTRIBUTING.md)
-- [README.md](../../README.md)
\ No newline at end of file
+- [CONTRIBUTING.md](https://github.com/QuantumDevTeam/StellarEngine-Core/blob/master/CONTRIBUTING.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
diff --git a/Docs/Engine/Install.md b/Docs/Engine/Install.md
index 3751e1d..0ec5df2 100644
--- a/Docs/Engine/Install.md
+++ b/Docs/Engine/Install.md
@@ -78,3 +78,6 @@ the installation in the NuGet cache and the build output go. Modules, tools and
git clone https://github.com/QuantumDevTeam/StellarEngine-Core.git StellarEngine
powershell -File StellarEngine\scripts\build.ps1 -Configuration Release -Install
```
+
+It builds the core, installs it, then builds and packs every module of `modules/`, so that games which take the
+engine as packages find them; `-SkipModules` leaves the modules for later (`stellar modules build --pack`).
diff --git a/Docs/Engine/Marks.md b/Docs/Engine/Marks.md
new file mode 100644
index 0000000..2b4b236
--- /dev/null
+++ b/Docs/Engine/Marks.md
@@ -0,0 +1,47 @@
+# Marks
+
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
+
+A mark is metadata in a comment of the code: `#` and a name in angle brackets, capital letters, digits, `-` and `_`.
+`MVP` as a mark in C# is a comment `// #` followed by ``. It is found in comments only, in C#, C++, shaders,
+PowerShell, shell, YAML, TOML, XML, MSBuild and Markdown files.
+
+## Kinds
+
+| File | Whose | Committed |
+|---|---|---|
+| `Shared/Marks/marks.json` | of the engine, the same for everyone | yes |
+| `config/marks.json` | of one machine; adds kinds and replaces those of the engine | never, git ignores `config/` |
+
+```json
+{ "Marks": { "WIP": { "Level": "Release", "Description": "Not finished: it cannot be released" } } }
+```
+
+| Level | How far code with the mark goes |
+|---|---|
+| `Info` | anywhere |
+| `Release` | into commits and `develop`, not into `master`, a release or the mirror |
+| `Commit` | nowhere: not even into a commit |
+
+A mark of a kind that is in neither file is stopped everywhere: a typing error, or a kind of another machine.
+
+## Checking
+
+```powershell
+stellar marks install --all # git checks every commit, merge and push of the core, the modules and the tools
+stellar marks list --all # where the marks are
+stellar marks check # the files of this repository
+stellar marks check --staged # what the next commit changes
+stellar marks check --all --stage release
+stellar marks uninstall --all
+```
+
+| Where | What it checks |
+|---|---|
+| the hooks of git | what is committed, merged and pushed |
+| `.github/workflows/marks.yml` | every push to `develop` and `master` and every pull request; `master` as a release. A module calls the workflow of the core, `stellar modules new` writes it. Required by the rulesets |
+| `.github/workflows/release.yml` | before a release is tagged |
+| `.github/workflows/mirror.yml` | the core and every component, before a snapshot |
+
+The hooks stop the commit when the `stellar` command is missing or older than the marks. They can be skipped with
+`--no-verify`; the workflows cannot. A hook somebody else wrote is never replaced.
diff --git a/Docs/Engine/Modules.md b/Docs/Engine/Modules.md
index 957f2a3..764aa3e 100644
--- a/Docs/Engine/Modules.md
+++ b/Docs/Engine/Modules.md
@@ -1,6 +1,6 @@
# Modules
-- [README.md](../../README.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
A module is a folder with a [`.stellar.module`](../Formats/ModuleDescriptor.md) file. Everything else follows from
it: the installation finds it, the SDK builds it, the analyzers keep its architecture, the packages carry it. The rule
@@ -18,13 +18,15 @@ stellar modules build --tests --pack
| Step | What happens |
|---|---|
-| `modules new` | Renders `Shared/Templates/Modules/` into `modules//`, with its documentation site (`Docs/`, `docfx.json`, a Pages workflow, a placeholder icon in `Branding/`), and syncs |
+| `modules new` | Renders `Shared/Templates/Modules/` into `modules//`, with its documentation (`Docs/`, `prometheus.json`, `docfx.json`, the docs workflow, a placeholder icon in `Branding/`), and syncs |
| `modules sync` | Finds the modules, applies the manifest, checks the rules, writes the catalog |
-| `modules build` | For each module in load order, with the dependencies of the selected ones: native projects (MSBuild of Visual Studio), the managed project, the tests, the package |
+| `modules build` | For each module in load order, with the dependencies of the selected ones: native projects (MSBuild of Visual Studio), the managed project, the package (`--pack`), the tests (`--tests`) |
| `modules list` | The modules in load order, where each came from, how it is linked |
`modules build --plan` shows the commands without running them; `--no-native`, `--wrapper Managed`,
-`-c Release` change what is built.
+`-c Release` change what is built. The order of `--tests` and `--pack` means nothing: the package always goes first.
+In Debug the tests take the module from its sources; in Release they take the package, so `-c Release --tests` needs
+`--pack` with it, or it fails without a package and tests the one packed last time when there is one.
A module developed in its own repository stays there:
diff --git a/Docs/Engine/PostInstallSetup.md b/Docs/Engine/PostInstallSetup.md
index b02eb18..2b6490d 100644
--- a/Docs/Engine/PostInstallSetup.md
+++ b/Docs/Engine/PostInstallSetup.md
@@ -1,6 +1,6 @@
# Setting up the machine after the install
-- [README.md](../../README.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
What to know once the installation stands: how git behaves in a tree of nested repositories.
diff --git a/Docs/Engine/Repository.md b/Docs/Engine/Repository.md
index 071abb5..a225ab9 100644
--- a/Docs/Engine/Repository.md
+++ b/Docs/Engine/Repository.md
@@ -1,6 +1,6 @@
# Repository and installation layout
-- [README.md](../../README.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
## One tree: the core is the root
@@ -33,7 +33,8 @@ cd StellarEngine
powershell -File scripts/build.ps1 -Configuration Release -Install
```
-`build.ps1 -Install` builds the core, fills `packages/` and runs `stellar install` in place. Running it again after
+`build.ps1 -Install` builds the core, fills `packages/` and runs `stellar install` in place, then builds and packs the
+modules of `modules/` (`-SkipModules` leaves them). Running it again after
`git pull` updates the core and keeps everything the installation holds: `stellar install` never overwrites a file.
`Stellar.Tools.Environment.StellarInstallation` is the single description of this tree in code. MSBuild has its own
@@ -59,7 +60,8 @@ So a module or a game inside the installation needs nothing, and one elsewhere u
```
What an orchestra holds stays in its own `manifests/`. `stellar install` registers the installation, registering a
-version again moves it; `stellar install --no-user-registration` leaves the registry alone.
+version again moves it, and a root installed again with another orchestra keeps only that one;
+`stellar install --no-user-registration` leaves the registry alone.
### Uninstalling
@@ -157,23 +159,23 @@ snapshot stays local and the script prints the push command; `-Tag` marks a rele
### Sites
-Every repository publishes its documentation with DocFX to GitHub Pages, by the same `.github/workflows/docs.yml`.
-Each site says where it is: the site of the engine is about the engine as a whole, the site of a component about that
-component alone.
+The documentation is read on the docs site (`StellarDocsUri`). Every repository publishes its part to its GitHub
+Pages with the same `.github/workflows/docs.yml`, a copy of the workflow of the docs site that never needs updating:
+it takes the steps from the site on every run. What a repository publishes is in `prometheus.json` at its root.
-| Site | Address | Content |
+| Project of the docs site | Built from | Content |
|---|---|---|
-| the engine | `StellarEngineSiteUri`, built from the mirror | the home of StellarEngine: getting started, the guide (`Docs/Engine/` of the core: installing, architecture, modules, this page, the project), the core under `/core/`, each component under `/modules//` or `/tools//`, the installer and the schemas |
-| the core | `StellarSiteUri` | the core alone: `Docs/` without `Docs/Engine/`, the API reference of `Stellar.Kernel`, `Stellar.Core`, `Stellar.Runtime` and `Stellar.Tools`, the JSON schemas (`/schemas/`), the installer (`/install.ps1`) |
-| a module | the same host, `//` | its `Docs/` and README; `stellar modules new` creates them with `docfx.json` and the workflow |
+| the engine, `StellarEngineDocsProject` | the mirror | the guide (`Docs/Engine/` of the core: installing, architecture, modules, this page, the project), the core under `core/` with its API, each module and tool with a `Docs/toc.yml` under `modules//` or `tools//` |
+| the core, `StellarDocsProject` | the core | `Docs/` without `Docs/Engine/`, the API reference of `Stellar.Kernel`, `Stellar.Core`, `Stellar.Runtime` and `Stellar.Tools` |
+| a module | its repository | its `Docs/`; `stellar modules new` creates them with `prometheus.json` and the workflow |
-Both addresses are set once, in `Shared/Build/Stellar.Versions.props`. The pages about the engine as a whole live in
-the core, in `Docs/Engine/`, since the mirror is generated and holds nothing of its own; the site of the core leaves
-them out and links to the site of the engine instead.
+GitHub Pages of the core keeps the installer (`/install.ps1`) and the JSON schemas (`/schemas/`) at `StellarSiteUri`.
+All the addresses and projects are set once, in `Shared/Build/Stellar.Versions.props`. The pages about the engine as
+a whole live in the core, in `Docs/Engine/`, since the mirror is generated and holds nothing of its own.
-The workflow tells the mirror by the `.orchestra` file `scripts/mirror.ps1` puts at the root of each snapshot (the
-commits and the repositories it was made of): there it runs `scripts/orchestra-site.ps1`, which writes
-`docfx.orchestra.json`, and builds that instead of `docfx.json`.
+`prometheus.json` of the core names `scripts/prometheus.ps1`, which the workflow runs first: it describes the core, or,
+where the `.orchestra` file of `scripts/mirror.ps1` is (the mirror), the whole engine. See
+[Writing the documentation](Documentation.md).
### Releases
@@ -182,25 +184,27 @@ A release starts as a decision: a new `StellarOrchesterVersion` in `Shared/Build
1. a push of that version to `master` of the core: `.github/workflows/release.yml` sees a version without a tag, tags
the commit `v` and publishes a GitHub release of the core with the versions of its components;
-2. the next run of the mirror (`.github/workflows/mirror.yml`, nightly or Run workflow; at once with the secret
- `STELLAR_DISPATCH_TOKEN` in the core) makes a snapshot with the new core, sees the same version without a tag in
- the mirror, tags the snapshot `v` and publishes the release of the orchestra: every component, its
- version and its commit;
+2. that release starts the mirror (`.github/workflows/mirror.yml`) when the core has `STELLAR_MIRROR_APP_ID` and
+ `STELLAR_MIRROR_APP_KEY`; without them Run workflow there does. It makes a snapshot with the new core, sees the same
+ version without a tag in the mirror, tags the snapshot `v` and publishes the release of the orchestra:
+ every component, its version and its commit. It takes the default branch of each module, so the modules of a release
+ are merged there before the core;
3. the installer installs the latest release by default: it reads `.orchestra` at that tag.
A version with a suffix (`0.9.0-rc.1`) is a pre-release, which the installer takes only when asked for by name.
### The mirror regenerates itself
-`.github/workflows/mirror.yml` runs in the mirror (where the repository variable `STELLAR_MIRROR` is `true`) every
-night and on demand: it clones every component the last `.orchestra` names, at its default branch, makes a snapshot
+`.github/workflows/mirror.yml` runs in the mirror (where the repository variable `STELLAR_MIRROR` is `true`) on a
+release of the core and on demand, never on a timer: it clones every component the last `.orchestra` names, at its default branch, makes a snapshot
when anything changed and pushes it, which starts the docs workflow. A component it cannot clone (a private repository) is
kept as the mirror has it (`scripts/mirror.ps1 -Keep`); the secret `STELLAR_MIRROR_TOKEN` lets it read private ones
too. The first snapshot comes from a machine: `scripts/mirror.ps1 -Push`.
The rulesets of the mirror let nobody write its branch, so the workflow pushes with the token of a GitHub App, installed
on the mirror only and in the bypass list of the ruleset (`STELLAR_MIRROR_APP_ID`, `STELLAR_MIRROR_APP_KEY`). The token
-of a workflow does not do: it passes no ruleset, and cannot change the files of `.github/workflows/`.
+of a workflow does not do: it passes no ruleset, and cannot change the files of `.github/workflows/`. Run workflow takes
+a new component in its `add` field, `modules/` or `tools/`: a public repository of the organization.
After that the workflow is the only writer of the mirror: on a machine, `scripts/mirror.ps1` without `-Push` shows
what the next snapshot would be, and Run workflow publishes it. A snapshot is always made on top of the last one of
diff --git a/Docs/Engine/Versioning.md b/Docs/Engine/Versioning.md
index 2c98f59..4480db3 100644
--- a/Docs/Engine/Versioning.md
+++ b/Docs/Engine/Versioning.md
@@ -1,6 +1,6 @@
# StellarEngine — Versioning Policy
-- [README.md](../../README.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
## 1. General Concept
@@ -112,7 +112,32 @@ After `v1.0.0`:
---
+## 8. Versions of Components
+
+Every component (`Shared/Build/Stellar.Versions.props`, `*.stellar.module`) has a version of its own. What counts is the
+version of the last release, the one on `master`:
+
+| Since the last release | Version |
+|---|---|
+| nothing that matters to others: formatting, tests, documentation | stays |
+| the first compatible change | `Y` is raised, once: `0.10.0` → `0.10.1` |
+| more compatible changes | stays: they go into the version that is raised already |
+| a breaking change | `X` is raised, once, instead of `Y`: `0.10.1` → `0.11.0` |
+| more changes of any kind after it | stays |
+
+A change is breaking for a component when what uses it does not work with the new one as it is. A component that did not
+change is raised only if it does not work with the old version of what it depends on. The orchestra takes `X` when any of
+its components does, or when a module enters it.
+
+Before raising, compare:
+
+```powershell
+git show origin/master:Shared/Build/Stellar.Versions.props
+```
+
+---
+
Also see:
- [GitPolicy.md](GitPolicy.md)
-- [CONTRIBUTING.md](../../CONTRIBUTING.md)
-- [README.md](../../README.md)
\ No newline at end of file
+- [CONTRIBUTING.md](https://github.com/QuantumDevTeam/StellarEngine-Core/blob/master/CONTRIBUTING.md)
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
diff --git a/Docs/Engine/toc.yml b/Docs/Engine/toc.yml
index 50e6efc..fa4ff28 100644
--- a/Docs/Engine/toc.yml
+++ b/Docs/Engine/toc.yml
@@ -1,4 +1,4 @@
-# Navigation of the guide of the whole engine, on the site of the engine (scripts/orchestra-site.ps1).
+# Navigation of the guide of the whole engine, in the documentation of the engine (scripts/prometheus.ps1).
# The pages live in the core, the only place they can, and are published with the orchestra, not with the core.
- name: Installing
href: Install.md
@@ -12,15 +12,21 @@
href: Repository.md
- name: Setting up the machine
href: PostInstallSetup.md
+- name: Marks
+ href: Marks.md
+- name: Writing the documentation
+ href: Documentation.md
+- name: Questions
+ href: FAQ.md
- name: Project
items:
- name: README
- href: ../../README.md
+ href: https://github.com/QuantumDevTeam/StellarEngine-Core#readme
- name: Contributing
- href: ../../CONTRIBUTING.md
+ href: https://github.com/QuantumDevTeam/StellarEngine-Core/blob/master/CONTRIBUTING.md
- name: Git policy
href: GitPolicy.md
- name: Versioning
href: Versioning.md
- name: License
- href: ../../LICENSE.md
+ href: https://github.com/QuantumDevTeam/StellarEngine-Core/blob/master/LICENSE.md
diff --git a/Docs/Formats/EngineManifest.md b/Docs/Formats/EngineManifest.md
index 7b1eac4..d6125f8 100644
--- a/Docs/Formats/EngineManifest.md
+++ b/Docs/Formats/EngineManifest.md
@@ -68,7 +68,7 @@ stellar modules reset Stellar.Physics # removes the entry
| File | For |
|---|---|
-| `stellar.modules.props` | The catalog MSBuild imports, see [Modules](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Modules.html) |
+| `stellar.modules.props` | The catalog MSBuild imports, see [Modules](../Engine/Modules.md) |
| `stellar.modules.json` | The same modules in load order, for tools that read JSON |
## Validation
diff --git a/Docs/Formats/ProjectFile.md b/Docs/Formats/ProjectFile.md
index 55afdb9..257e79b 100644
--- a/Docs/Formats/ProjectFile.md
+++ b/Docs/Formats/ProjectFile.md
@@ -40,7 +40,7 @@ and `.idea` are never searched.
| `Assets.Include` | Files copied to the output as they are |
| `Assets.Embedded` | Files embedded into the assembly. They win over `Include` |
| `Assets.Exclude` | Files removed from both lists |
-| `Resources.Include` | Files compiled into `.sres` containers, in `resources/` of the output |
+| `Resources.Include` | Files compiled into `.sres` containers, in `Resources/` of the output |
| `Resources.Compilers` | Assemblies with additional resource compilers |
| `Localizations.IndexFiles` | Index files. The culture is the file name before `.stellar.loc.index` |
| `Runtime` | The settings of the runtime ([Runtime](../Architecture/Runtime.md#settings)), and free-form values for modules. They reach `RuntimeConfiguration.Settings`: strings as they are, other values as JSON text |
diff --git a/Docs/Migration-0.11.md b/Docs/Migration-0.11.md
new file mode 100644
index 0000000..fe483a8
--- /dev/null
+++ b/Docs/Migration-0.11.md
@@ -0,0 +1,72 @@
+# Migrating to 0.11
+
+- [README.md](https://github.com/QuantumDevTeam/StellarEngine-Core#readme)
+
+What changed for the code that uses the core, from 0.10. Nothing of the core breaks: the orchestra takes the second
+number because the logging module enters it.
+
+| Component | 0.10 | 0.11 | Why |
+|---|---|---|---|
+| Orchester | 0.10.0 | 0.11.0 | The logging module, and the file system published by its module |
+| Kernel | 0.10.0 | 0.10.1 | Compatible: `Folders`; a color of `LoggerFormat.Default` |
+| FileSystem | 0.9.0 | 0.11.0 | It publishes itself and mounts the folders of the engine |
+| Runtime | 0.10.0 | 0.10.1 | Compatible: settings of the command line reach modules |
+| Stellar.Tools | 0.3.2 | 0.3.3 | Compatible: marks; a module is packed before its tests |
+| `stellar` (CLI) | 0.2.3 | 0.2.4 | Compatible: `stellar marks` |
+| Stellar.Sdk | 0.4.1 | 0.4.2 | Compatible: compiled resources go into `Resources` |
+| Core, P/Invoke exports | 0.10.0, 3.1 | the same | Nothing changed |
+
+Build the engine again and install it (`scripts/build.ps1 -Configuration Release -Install`). `global.json` pins an exact version of
+Stellar.Sdk, so change `0.4.1` to `0.4.2` in that of every solution:
+
+```json
+{ "msbuild-sdks": { "Stellar.Sdk": "0.4.2" } }
+```
+
+## Installing
+
+`scripts/build.ps1 -Install` also builds and packs the modules of `modules/` after the core, with their tests unless
+`-SkipTests`: a game built against packages finds them in `packages/` without `stellar modules build --pack` by hand.
+`-SkipModules` turns it off.
+
+`stellar install` keeps one registration per root in `~/.stellar`: an installation updated to 0.11 replaces the
+entry of its old orchestra version instead of keeping both.
+
+## Resources
+
+Compiled resources lie in `Resources` next to the application, not `resources`: only a system that tells case apart sees
+the difference.
+
+## Settings
+
+`RuntimeConfiguration.Settings` holds the settings of the project and those of the command line
+(`--stellar:Name=Value`), which win; names are in any case. Before, a module saw those of the project only.
+
+## File system
+
+`Stellar.FileSystem` publishes `IFileSystem` by itself and mounts the folders of the engine. Code names them through
+`Folders`, so it needs neither `Environment.GetFolderPath` nor the names of the domains:
+
+| `Folders` | Domain | Where |
+|---|---|---|
+| `App` | `app://` | the folder of the application, read-only |
+| `Assets` | `assets://` | `Assets` of it, read-only; the setting `AssetsFolder` moves it |
+| `Resources` | `resources://` | `Resources` of it, read-only; the setting `ResourcesFolder` moves it |
+| `AppData.Roaming` | `user://` | `//` |
+| `AppData.Local` | `local://` | the same in the local data of the user |
+| `AppData.LocalLow` | `locallow://` | the same in the low local data |
+| `Temp` | `temp://` | the same in the temporary files |
+
+The company is `Starlet` when the project names none; a project without a name has none of the last four. They are
+created by the first write. Full paths of the machine, to mount domains of your own: `Stellar.FileSystem.SystemFolders`.
+
+A cancelled or failed atomic write leaves the file as it was.
+
+## Logging
+
+When the module that published the logger stops, the runtime goes back to the error output: what fails after it is
+told there instead of being lost.
+
+## Marks
+
+Marks in the comments of the code, checked by git and by the workflows: [Marks](Engine/Marks.md).
diff --git a/Docs/Migration-0.8.md b/Docs/Migration-0.8.md
index b45b0d8..08b4ee2 100644
--- a/Docs/Migration-0.8.md
+++ b/Docs/Migration-0.8.md
@@ -42,7 +42,7 @@ built against the 0.7.0 packages of earlier states of this repository.
```
- A module is a folder with a [`.stellar.module`](Formats/ModuleDescriptor.md): its kind, version, description and
- dependencies come from there, and the project file is nearly empty. See [Modules](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Modules.html).
+ dependencies come from there, and the project file is nearly empty. See [Modules](Engine/Modules.md).
`stellar modules new` creates the folder, the descriptor, the projects and the tests.
- The SDK version moved to `global.json`.
- Dependencies are plain `StellarDependency` items: the descriptor makes them, a project may add or remove some.
diff --git a/Docs/Reference/Sdk.Properties.md b/Docs/Reference/Sdk.Properties.md
index b4dcccf..ff8f55b 100644
--- a/Docs/Reference/Sdk.Properties.md
+++ b/Docs/Reference/Sdk.Properties.md
@@ -27,7 +27,7 @@ The project wins over `config/`, `config/` over the defaults.
| `StellarRoot` | `STELLAR_ROOT`, a `manifests/` above, the user registry | The root of the installation |
| `StellarHome` | `STELLAR_HOME`, or `~/.stellar` | The registry of the user, read only when nothing else gave `StellarRoot` |
| `StellarPackagesDir` | `$(StellarRoot)packages/` | The local feed |
-| `StellarArtifactsDir` | `$(StellarRoot)artifacts/` | Everything built: `bin/` and `obj/`, see [the layout](https://quantumdevteam.github.io/StellarEngine-Mono/guide/Repository.html) |
+| `StellarArtifactsDir` | `$(StellarRoot)artifacts/` | Everything built: `bin/` and `obj/`, see [the layout](../Engine/Repository.md) |
| `StellarIsEngineProject` | `true` under `$(StellarRoot)`, but in `projects/` | The engine side (modules, tools): sources in Debug, `artifacts/`. A game or a library is not |
| `StellarUseArtifactsOutput` | `true` on the engine side, `false` for games | `false`: the plain `bin/` and `obj/` next to the project |
| `StellarArtifactsName` | `$(MSBuildProjectName)` | The folder of the project in `artifacts/bin` and `artifacts/obj` |
diff --git a/Docs/index.md b/Docs/index.md
index e962b5b..399b5fa 100644
--- a/Docs/index.md
+++ b/Docs/index.md
@@ -2,10 +2,10 @@
# StellarEngine-Core
-The core of [StellarEngine](https://quantumdevteam.github.io/StellarEngine-Mono/): the one component installed into the
+The core of [StellarEngine](prometheus:stellar-engine): the one component installed into the
root of every installation. This site is about the core alone: how it is built, the formats it reads, the SDK it gives
modules and games, and its API. Everything about the engine as a whole (installing it, getting started, the
-architecture, the modules, the orchestra) is on the [site of the engine](https://quantumdevteam.github.io/StellarEngine-Mono/).
+architecture, the modules, the orchestra) is on the [site of the engine](prometheus:stellar-engine).
## What the core is
@@ -41,6 +41,7 @@ The JSON schemas of these files are published here, under [`/schemas/`](https://
- [API reference](xref:Stellar.Kernel), generated from the code of `Stellar.Kernel`, `Stellar.Core`, `Stellar.Runtime` and `Stellar.Tools`
- [SDK properties and items](Reference/Sdk.Properties.md)
- [Diagnostics](Reference/Diagnostics.md)
+- [Migrating to 0.11](Migration-0.11.md)
- [Migrating to 0.10](Migration-0.10.md)
- [Migrating to 0.9](Migration-0.9.md)
- [Migrating to 0.8](Migration-0.8.md)
diff --git a/Docs/toc.yml b/Docs/toc.yml
index 97adea3..f8ae818 100644
--- a/Docs/toc.yml
+++ b/Docs/toc.yml
@@ -1,5 +1,5 @@
-# Navigation of the site of the core (DocFX). Paths are relative to this file.
-# Docs/Engine/ is not here: it is the guide of the whole engine, on the site of the engine (scripts/orchestra-site.ps1).
+# Navigation of the documentation of the core (the bundle of the site). Paths are relative to this file.
+# Docs/Engine/ is not here: it is the guide of the whole engine, in the documentation of the engine (scripts/prometheus.ps1).
- name: Home
href: index.md
- name: Architecture
@@ -36,6 +36,8 @@
href: Reference/Sdk.Properties.md
- name: Diagnostics
href: Reference/Diagnostics.md
+ - name: Migrating to 0.11
+ href: Migration-0.11.md
- name: Migrating to 0.10
href: Migration-0.10.md
- name: Migrating to 0.9
@@ -45,4 +47,4 @@
- name: API
href: ../artifacts/docs/api/
- name: StellarEngine
- href: https://quantumdevteam.github.io/StellarEngine-Mono/
+ href: prometheus:stellar-engine
diff --git a/Kernel/src/Managed/Stellar.Kernel/FileSystem/Folders.cs b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Folders.cs
new file mode 100644
index 0000000..5f43361
--- /dev/null
+++ b/Kernel/src/Managed/Stellar.Kernel/FileSystem/Folders.cs
@@ -0,0 +1,41 @@
+namespace Stellar.Kernel.FileSystem;
+
+///
+/// The folders of the engine, as paths of its domains: what a game names instead of locations of the machine.
+///
+///
+/// Folders.AppData.Roaming.Combine("saves/slot1.json") is user://saves/slot1.json. These are names
+/// only, the same in every engine instance: where each lies is up to the file system of that instance.
+/// The module Stellar.FileSystem mounts them when the engine starts. and
+/// are there if the application has such folders, and
+/// if it has a name.
+///
+public static class Folders
+{
+ /// Gets the folder of the application, read-only.
+ public static FilePath App { get; } = FilePath.Root("app");
+
+ /// Gets the assets of the application, read-only.
+ public static FilePath Assets { get; } = FilePath.Root("assets");
+
+ /// Gets the compiled resources of the application, read-only.
+ public static FilePath Resources { get; } = FilePath.Root("resources");
+
+ /// Gets the folder for files that may disappear once the application stops.
+ public static FilePath Temp { get; } = FilePath.Root("temp");
+
+ ///
+ /// The folders of the application among the data of the user.
+ ///
+ public static class AppData
+ {
+ /// Gets the data that follows the user from machine to machine: settings, saves.
+ public static FilePath Roaming { get; } = FilePath.Root("user");
+
+ /// Gets the data of this machine: caches, logs.
+ public static FilePath Local { get; } = FilePath.Root("local");
+
+ /// Gets the data of this machine a process with few rights may write.
+ public static FilePath LocalLow { get; } = FilePath.Root("locallow");
+ }
+}
diff --git a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/ILogger.cs b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/ILogger.cs
index 8018b26..2559f55 100644
--- a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/ILogger.cs
+++ b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/ILogger.cs
@@ -3,31 +3,34 @@
namespace Stellar.Kernel.LoggingSystem;
///
-/// Engine logger
+/// Takes messages: the logger of an engine, or one of those it gives them to ().
///
+///
+/// Every member is safe to call from any thread. LoggerExtensions has a method for every level.
+///
public interface ILogger
: IQuant
{
///
- /// Create log with formatting
+ /// Logs a message in the format of its level ().
///
- /// Log level
- /// Log message
+ /// How serious the message is.
+ /// The message.
void Log(LogLevel level, string message);
///
- /// Create log without formatting
+ /// Logs a message as it is: no format and no level, so no level turns it away.
///
- /// just message to write
+ /// The message.
void LogWithoutFormat(string message);
///
- /// TODO: summary
+ /// Starts taking messages. A logger may be started again after .
///
void Start();
///
- /// TODO: summary
+ /// Stops taking messages, and writes out the ones taken before.
///
void Stop();
}
diff --git a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/ILoggerCatalog.cs b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/ILoggerCatalog.cs
index 690b751..8cb32fe 100644
--- a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/ILoggerCatalog.cs
+++ b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/ILoggerCatalog.cs
@@ -3,7 +3,11 @@
namespace Stellar.Kernel.LoggingSystem;
///
-/// TODO: summary
+/// The loggers of one engine, by name: where its messages end up (a console, a file, a logger of a game).
///
+///
+/// The logging module publishes it in the services of the engine. A module adds a logger when it starts and takes it
+/// out when it stops; the one that added a logger owns it.
+///
public interface ILoggerCatalog
: ICatalog;
diff --git a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LogFormat.cs b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LogFormat.cs
index b611c6a..5f1e1fd 100644
--- a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LogFormat.cs
+++ b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LogFormat.cs
@@ -1,18 +1,24 @@
namespace Stellar.Kernel.LoggingSystem;
///
-/// {0} - date yyyy-MMM-dd
-/// {1} - time HH:mm:ss.fff
-/// {2} - engine clock name
-/// {3} - engine clock time HH:mm:ss.fff
-/// {4} - LogLevel
-/// {5} - Engine instance name
-/// {6} - Logger instance name
-/// {7} - Thread ID
-/// {8} - C# Type name
-/// {9} - C# Method name
-/// {10} - message
+/// The format of the lines of one level: a composite format string ().
///
-/// Format string
-/// Colorized Format string (ASCII)
+///
+///
+/// PlaceholderWhat it is
+/// - {0}the date, yyyy-MM-dd
+/// - {1}the time, HH:mm:ss.fff
+/// - {2}the name of the engine clock
+/// - {3}the time of the engine clock, HH:mm:ss.fff
+/// - {4}the
+/// - {5}the name of the engine
+/// - {6}the name of the logger
+/// - {7}the identifier of the managed thread
+/// - {8}the type that logs; costs a walk of the stack, as {9} does
+/// - {9}the method that logs
+/// - {10}the message
+///
+///
+/// The format string.
+/// The same with ANSI colors, for consoles; null for none.
public record struct LogFormat(string Format, string? ColorizedFormat = null);
diff --git a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LogLevel.cs b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LogLevel.cs
index 9957153..50e2c77 100644
--- a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LogLevel.cs
+++ b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LogLevel.cs
@@ -1,37 +1,37 @@
namespace Stellar.Kernel.LoggingSystem;
///
-/// Level of log
+/// How serious a message is, the least serious first: a logger that takes a level takes every one after it.
///
public enum LogLevel
{
///
- /// Debug message or information
+ /// For those who work on the code: steps, values.
///
Debug = 0,
///
- /// Any Information
+ /// What happens in the course of things.
///
Info = 1,
///
- /// Operation succeed
+ /// Something worth telling succeeded.
///
Success = 2,
///
- /// A Warning
+ /// Something is wrong, and the engine goes on as if it were not.
///
Warning = 3,
///
- /// An Error
+ /// Something failed, and what depends on it does not work.
///
Error = 4,
///
- /// An Exception
+ /// Something failed with an exception, told with it.
///
Exception = 5
}
diff --git a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LoggerExtensions.cs b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LoggerExtensions.cs
index 9b75f0e..b455c7a 100644
--- a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LoggerExtensions.cs
+++ b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LoggerExtensions.cs
@@ -4,53 +4,66 @@
namespace Stellar.Kernel.LoggingSystem;
///
-/// TODO: summary
+/// A method of for every level.
///
public static class LoggerExtensions
{
///
- /// TODO: summary
+ /// Logs a message of : what happens in the course of things.
///
+ /// The logger.
+ /// The message.
public static void Info(this ILogger logger, string message)
{
logger.Log(LogLevel.Info, message);
}
///
- /// TODO: summary
+ /// Logs a message of : for those who work on the code.
///
+ /// The logger.
+ /// The message.
public static void Debug(this ILogger logger, string message)
{
logger.Log(LogLevel.Debug, message);
}
///
- /// TODO: summary
+ /// Logs a message of : a success worth telling.
///
+ /// The logger.
+ /// The message.
public static void Success(this ILogger logger, string message)
{
logger.Log(LogLevel.Success, message);
}
///
- /// TODO: summary
+ /// Logs a message of : something wrong the engine goes on with.
///
+ /// The logger.
+ /// The message.
public static void Warning(this ILogger logger, string message)
{
logger.Log(LogLevel.Warning, message);
}
///
- /// TODO: summary
+ /// Logs a message of : a failure.
///
+ /// The logger.
+ /// The message.
public static void Error(this ILogger logger, string message)
{
logger.Log(LogLevel.Error, message);
}
///
- /// TODO: summary
+ /// Logs a message of with the exception behind it.
///
+ /// The logger.
+ /// What was being done.
+ /// The exception.
public static void Exception(this ILogger logger, string message, Exception exception)
{
logger.Log(LogLevel.Exception,
@@ -60,8 +73,9 @@ public static void Exception(this ILogger logger, string message, Exception exce
}
///
- /// TODO: summary
+ /// Logs an empty line.
///
+ /// The logger.
public static void Separator(this ILogger logger)
{
logger.LogWithoutFormat("");
diff --git a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LoggerFormat.cs b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LoggerFormat.cs
index f83eb4b..3e0cab4 100644
--- a/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LoggerFormat.cs
+++ b/Kernel/src/Managed/Stellar.Kernel/LoggingSystem/LoggerFormat.cs
@@ -3,27 +3,28 @@
namespace Stellar.Kernel.LoggingSystem;
///
-/// Full logger formats alias
+/// The formats of a logger, one per level.
///
-/// Info log format
-/// Debug log format
-/// Success log format
-/// Warning log format
-/// Error log format
-/// Exception log format
+/// The format of .
+/// The format of .
+/// The format of .
+/// The format of .
+/// The format of .
+/// The format of .
public readonly record struct LoggerFormat(
LogFormat Info,
LogFormat Debug,
LogFormat Success,
LogFormat Warning,
LogFormat Error,
- LogFormat Exception)
+ LogFormat Exception
+)
{
///
- /// Default Logger format
+ /// The formats a logger has when none are given: every placeholder of , colored by level.
///
public static readonly LoggerFormat Default = new(
- new()
+ new LogFormat
{
Format = "{0}:{1} | {2}:{3} | {4} | {5}:{6}:{7} : {8}.{9} - {10}",
ColorizedFormat = "\e[32m{0}\e[0m" +
@@ -34,21 +35,21 @@ public readonly record struct LoggerFormat(
"\e[31m:\e[0m" +
"\e[2;32m{3}\e[0m " +
"\e[31m|\e[0m " +
- "\e[1;38m{4}\e[0m " +
+ "\e[1;37m{4}\e[0m " +
"\e[31m|\e[0m " +
"\e[36m{5}\e[0m" +
"\e[31m:\e[0m" +
- "\e[36m{6}\e[0m " +
+ "\e[36m{6}\e[0m" +
"\e[31m:\e[0m" +
"\e[36m{7}\e[0m " +
"\e[31m:\e[0m " +
- "\e[36m{8}\e[0m " +
+ "\e[36m{8}\e[0m" +
"\e[31m.\e[0m" +
"\e[36m{9}\e[0m " +
"\e[31m-\e[0m " +
- "\e[1;38m{10}\e[0m"
+ "\e[1;37m{10}\e[0m"
},
- new()
+ new LogFormat
{
Format = "{0}:{1} | {2}:{3} | {4} | {5}:{6}:{7} : {8}.{9} - {10}",
ColorizedFormat = "\e[32m{0}\e[0m" +
@@ -63,17 +64,17 @@ public readonly record struct LoggerFormat(
"\e[31m|\e[0m " +
"\e[36m{5}\e[0m" +
"\e[31m:\e[0m" +
- "\e[36m{6}\e[0m " +
+ "\e[36m{6}\e[0m" +
"\e[31m:\e[0m" +
"\e[36m{7}\e[0m " +
"\e[31m:\e[0m " +
- "\e[36m{8}\e[0m " +
+ "\e[36m{8}\e[0m" +
"\e[31m.\e[0m" +
"\e[36m{9}\e[0m " +
"\e[31m-\e[0m " +
"\e[1;33m{10}\e[0m"
},
- new()
+ new LogFormat
{
Format = "{0}:{1} | {2}:{3} | {4} | {5}:{6}:{7} : {8}.{9} - {10}",
ColorizedFormat = "\e[32m{0}\e[0m" +
@@ -88,17 +89,17 @@ public readonly record struct LoggerFormat(
"\e[31m|\e[0m " +
"\e[36m{5}\e[0m" +
"\e[31m:\e[0m" +
- "\e[36m{6}\e[0m " +
+ "\e[36m{6}\e[0m" +
"\e[31m:\e[0m" +
"\e[36m{7}\e[0m " +
"\e[31m:\e[0m " +
- "\e[36m{8}\e[0m " +
+ "\e[36m{8}\e[0m" +
"\e[31m.\e[0m" +
"\e[36m{9}\e[0m " +
"\e[31m-\e[0m " +
"\e[1;32m{10}\e[0m"
},
- new()
+ new LogFormat
{
Format = "{0}:{1} | {2}:{3} | {4} | {5}:{6}:{7} : {8}.{9} - {10}",
ColorizedFormat = "\e[32m{0}\e[0m" +
@@ -113,17 +114,17 @@ public readonly record struct LoggerFormat(
"\e[31m|\e[0m " +
"\e[36m{5}\e[0m" +
"\e[31m:\e[0m" +
- "\e[36m{6}\e[0m " +
+ "\e[36m{6}\e[0m" +
"\e[31m:\e[0m" +
"\e[36m{7}\e[0m " +
"\e[31m:\e[0m " +
- "\e[36m{8}\e[0m " +
+ "\e[36m{8}\e[0m" +
"\e[31m.\e[0m" +
"\e[36m{9}\e[0m " +
"\e[31m-\e[0m " +
"\e[1;34m{10}\e[0m"
},
- new()
+ new LogFormat
{
Format = "{0}:{1} | {2}:{3} | {4} | {5}:{6}:{7} : {8}.{9} - {10}",
ColorizedFormat = "\e[32m{0}\e[0m" +
@@ -142,13 +143,13 @@ public readonly record struct LoggerFormat(
"\e[31m:\e[0m" +
"\e[36m{7}\e[0m " +
"\e[31m:\e[0m " +
- "\e[36m{8}\e[0m " +
+ "\e[36m{8}\e[0m" +
"\e[31m.\e[0m" +
"\e[36m{9}\e[0m " +
"\e[31m-\e[0m " +
- "\e[1;38m{10}\e[0m"
+ "\e[1;37m{10}\e[0m"
},
- new()
+ new LogFormat
{
Format = "{0}:{1} | {2}:{3} | {4} | {5}:{6}:{7} : {8}.{9} - {10}",
ColorizedFormat = "\e[32m{0}\e[0m" +
@@ -163,11 +164,11 @@ public readonly record struct LoggerFormat(
"\e[31m|\e[0m " +
"\e[36m{5}\e[0m" +
"\e[31m:\e[0m" +
- "\e[36m{6}\e[0m " +
+ "\e[36m{6}\e[0m" +
"\e[31m:\e[0m" +
"\e[36m{7}\e[0m " +
"\e[31m:\e[0m " +
- "\e[36m{8}\e[0m " +
+ "\e[36m{8}\e[0m" +
"\e[31m.\e[0m" +
"\e[36m{9}\e[0m " +
"\e[31m-\e[0m " +
@@ -176,20 +177,23 @@ public readonly record struct LoggerFormat(
);
///
- /// Gets LogFormat for a LogLevel
+ /// Gets the format of a level.
///
- /// Log level
- /// a LogFormat for given LogLevel
- /// if LogLevel is out of LogLevel enum
- public LogFormat ForLevel(LogLevel level) => level switch
+ /// The level.
+ /// The format of .
+ /// Thrown if is not one of .
+ public LogFormat ForLevel(LogLevel level)
{
- LogLevel.Info => Info,
- LogLevel.Debug => Debug,
- LogLevel.Success => Success,
- LogLevel.Warning => Warning,
- LogLevel.Error => Error,
- LogLevel.Exception => Exception,
- _ => throw new ArgumentException("LoggerFormat.ForLevel operate only levels writen in LogLevel enum",
- nameof(level), null)
- };
+ return level switch
+ {
+ LogLevel.Info => Info,
+ LogLevel.Debug => Debug,
+ LogLevel.Success => Success,
+ LogLevel.Warning => Warning,
+ LogLevel.Error => Error,
+ LogLevel.Exception => Exception,
+ _ => throw new ArgumentException("LoggerFormat.ForLevel operate only levels writen in LogLevel enum",
+ nameof(level), null)
+ };
+ }
}
diff --git a/README.md b/README.md
index b486cca..8b88d8d 100644
--- a/README.md
+++ b/README.md
@@ -77,6 +77,7 @@ powershell -File scripts/build.ps1
| `-Pack` | Also fills the local feed, `packages/` |
| `-Install` | Also runs `stellar install` here; implies `-Pack` |
| `-NoUserRegistration` | With `-Install`: do not register the installation for the current user (`~/.stellar`) |
+| `-SkipModules` | With `-Install`: do not build and pack the modules of `modules/`, which it does by default |
| `-Uninstall` | Instead of building: `stellar uninstall` here, then `artifacts/`. Modules, tools and games stay |
| `-All` | With `-Uninstall`: also the files you may have edited (`config/`, isolation files, the manifest) |
| `-KeepArtifacts` | With `-Uninstall`: keep the build output |
@@ -109,7 +110,7 @@ Every module and tool is a repository of its own, cloned into its folder of the
|---|---|
| `scripts/solution.ps1` | Writes `StellarEngine.sln`: the core and every project of `modules/` and `tools/`, for the IDE. Ignored by git; run it again when a module or a project appears |
| `scripts/mirror.ps1` | Makes a snapshot of the committed state of every component as one commit of the mirror (StellarEngine-Mono), the core at the root and each component in its folder. `-Tag v0.8.0`, `-Push` |
-| `scripts/orchestra-site.ps1` | Generates the DocFX project of the orchestra site (`docfx.orchestra.json`): the core and every module in one site. The docs workflow runs it in the mirror |
+| `scripts/prometheus.ps1` | Writes `prometheus.json`, what the docs workflow publishes: the core, or in the mirror the whole engine. `-Print` shows it. See [Writing the documentation](Docs/Engine/Documentation.md) |
See [Components and the mirror](Docs/Engine/Repository.md#components-and-the-mirror).
@@ -141,6 +142,7 @@ Reference:
Workflow:
- [Contributing](CONTRIBUTING.md), [Git policy](Docs/Engine/GitPolicy.md), [versioning](Docs/Engine/Versioning.md)
+- [Migrating to 0.11](Docs/Migration-0.11.md)
- [Migrating to 0.10](Docs/Migration-0.10.md)
- [Migrating to 0.9](Docs/Migration-0.9.md)
- [Migrating modules to 0.8](Docs/Migration-0.8.md)
diff --git a/Runtime/src/Managed/Stellar.Runtime/Configuration/RuntimeSettings.cs b/Runtime/src/Managed/Stellar.Runtime/Configuration/RuntimeSettings.cs
index b22b9a4..d38e691 100644
--- a/Runtime/src/Managed/Stellar.Runtime/Configuration/RuntimeSettings.cs
+++ b/Runtime/src/Managed/Stellar.Runtime/Configuration/RuntimeSettings.cs
@@ -1,4 +1,5 @@
using System.Globalization;
+
using Stellar.Kernel.Configuration;
namespace Stellar.Runtime.Configuration;
@@ -77,18 +78,18 @@ private RuntimeSettings(Dictionary values)
/// The settings.
public static RuntimeSettings Create(RuntimeConfiguration? configuration, IEnumerable? arguments = null)
{
- var values = new Dictionary(StringComparer.OrdinalIgnoreCase);
+ Dictionary values = new(StringComparer.OrdinalIgnoreCase);
if (configuration is not null)
- foreach (var pair in configuration.Settings)
+ foreach (KeyValuePair pair in configuration.Settings)
values[pair.Key] = pair.Value;
- foreach (var argument in arguments ?? [])
+ foreach (string argument in arguments ?? [])
{
if (!argument.StartsWith(CommandLinePrefix, StringComparison.OrdinalIgnoreCase)) continue;
- var setting = argument[CommandLinePrefix.Length..];
- var separator = setting.IndexOf('=');
+ string setting = argument[CommandLinePrefix.Length..];
+ int separator = setting.IndexOf('=');
if (separator > 0)
values[setting[..separator]] = setting[(separator + 1)..];
@@ -109,15 +110,27 @@ public static RuntimeSettings Create(RuntimeConfiguration? configuration, IEnume
return _values.GetValueOrDefault(name);
}
+ ///
+ /// Gets every setting as modules see them: the project, then the command line. Names in any case.
+ ///
+ /// A copy.
+ public Dictionary ToDictionary()
+ {
+ return new Dictionary(_values, StringComparer.OrdinalIgnoreCase);
+ }
+
private bool GetBoolean(string name, bool fallback)
{
- return _values.TryGetValue(name, out var value) && bool.TryParse(value, out var result) ? result : fallback;
+ return _values.TryGetValue(name, out string? value)
+ && bool.TryParse(value, out bool result)
+ ? result
+ : fallback;
}
private double GetDouble(string name, double fallback)
{
- return _values.TryGetValue(name, out var value) &&
- double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)
+ return _values.TryGetValue(name, out string? value)
+ && double.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out double result)
? result
: fallback;
}
diff --git a/Runtime/src/Managed/Stellar.Runtime/Lifecycle/ModuleStarter.cs b/Runtime/src/Managed/Stellar.Runtime/Lifecycle/ModuleStarter.cs
index 92cc1fc..be06984 100644
--- a/Runtime/src/Managed/Stellar.Runtime/Lifecycle/ModuleStarter.cs
+++ b/Runtime/src/Managed/Stellar.Runtime/Lifecycle/ModuleStarter.cs
@@ -1,5 +1,6 @@
using System.Reflection;
using System.Runtime.ExceptionServices;
+
using Stellar.Kernel.Configuration;
using Stellar.Kernel.EntryPoint;
using Stellar.Kernel.FailureSystem;
@@ -36,7 +37,8 @@ public static void Start(RuntimeContext context, LoadedModule module)
if (module.EntryPointType is null) return;
- var entryPoint = Create(module.EntryPointType, context.Configuration ?? new RuntimeConfiguration());
+ StellarEntryPoint entryPoint =
+ Create(module.EntryPointType, context.Configuration ?? new RuntimeConfiguration());
module.EntryPoint = entryPoint;
if (entryPoint is IServiceHost host && context.Services is null)
@@ -45,11 +47,11 @@ public static void Start(RuntimeContext context, LoadedModule module)
RuntimeServices.Publish(context, host.Services);
}
- var services = context.Services;
+ IServiceCatalog? services = context.Services;
var runContext = new RuntimeRunContext(context, services?.Find(),
services?.Find(), services, context.Engine);
- var code = entryPoint.Run(in runContext);
+ int code = entryPoint.Run(in runContext);
// The module that owns the services may have brought a logger
context.Log.Logger ??= context.Services?.Find();
@@ -77,7 +79,7 @@ public static void Stop(RuntimeContext context, LoadedModule module)
{
context.MainLoop?.Remove(entryPoint);
- var reason = context.Control.IsStopRequested ? context.Control.StopReason : StopReason.Regular;
+ StopReason reason = context.Control.IsStopRequested ? context.Control.StopReason : StopReason.Regular;
context.Catchers.Engine.Guard(() =>
{
@@ -85,16 +87,18 @@ public static void Stop(RuntimeContext context, LoadedModule module)
entryPoint.RequestStop(in stopContext);
}, $"the stop of {module.Id}", FailureKind.Module, context);
- context.Catchers.Engine.Guard(entryPoint.Dispose, $"the disposal of {module.Id}", FailureKind.Module, context);
+ context.Catchers.Engine.Guard(entryPoint.Dispose, $"the disposal of {module.Id}", FailureKind.Module,
+ context);
if (entryPoint is IServiceHost host && ReferenceEquals(host.Services, context.Services))
{
RuntimeServices.Withdraw(host.Services);
context.Services = null;
- context.Log.Logger = null;
}
module.EntryPoint = null;
+
+ context.Log.Logger = context.Services?.Find();
}
context.MarkStopped(module);
@@ -112,6 +116,7 @@ public static void Stop(RuntimeContext context, LoadedModule module)
private static bool TakesPartInFrames(StellarEntryPoint entryPoint)
{
+ // ReSharper disable once SuspiciousTypeConversion.Global
return entryPoint is IUpdatable or IFixedUpdatable or IRenderable;
}
diff --git a/Runtime/src/Managed/Stellar.Runtime/Lifecycle/Stages/ConfigurationStage.cs b/Runtime/src/Managed/Stellar.Runtime/Lifecycle/Stages/ConfigurationStage.cs
index 0f4ddb6..87ed342 100644
--- a/Runtime/src/Managed/Stellar.Runtime/Lifecycle/Stages/ConfigurationStage.cs
+++ b/Runtime/src/Managed/Stellar.Runtime/Lifecycle/Stages/ConfigurationStage.cs
@@ -1,3 +1,4 @@
+using Stellar.Kernel.Configuration;
using Stellar.Runtime.Configuration;
using Stellar.Runtime.Failures;
using Stellar.Runtime.Modules;
@@ -20,10 +21,10 @@ public sealed class ConfigurationStage
///
public ValueTask StartAsync(RuntimeContext context)
{
- var configuration = context.ConfigurationLocator.Read(context.Launch.ApplicationPath);
-
- context.Configuration = configuration;
+ RuntimeConfiguration configuration =
+ context.Configuration = context.ConfigurationLocator.Read(context.Launch.ApplicationPath);
context.Settings = RuntimeSettings.Create(configuration, context.Launch.Arguments);
+ configuration.Settings = context.Settings.ToDictionary(); // applying Launch.Arguments to runtime config
context.Log.Verbose |= context.Settings.Verbose;
context.Plan = ModulePlan.From(configuration);
diff --git a/Runtime/tests/Stellar.Runtime.Tests/ConfigurationTests.cs b/Runtime/tests/Stellar.Runtime.Tests/ConfigurationTests.cs
index 063cebe..6f56ea4 100644
--- a/Runtime/tests/Stellar.Runtime.Tests/ConfigurationTests.cs
+++ b/Runtime/tests/Stellar.Runtime.Tests/ConfigurationTests.cs
@@ -17,7 +17,8 @@ private static string Fixture(string name)
[Fact]
public void AssemblyFile_ReadsTheAttribute_WithoutLoadingTheAssembly()
{
- var attribute = AssemblyFile.ReadConfigurationAttribute(Fixture("Stellar.Runtime.Tests.Application"));
+ StellarRuntimeConfigurationAttribute? attribute =
+ AssemblyFile.ReadConfigurationAttribute(Fixture("Stellar.Runtime.Tests.Application"));
attribute.Should().NotBeNull();
attribute!.Source.Should().Be(RuntimeConfigurationSource.External);
@@ -36,7 +37,8 @@ public void AssemblyFile_NoAttribute_IsNull()
[Fact]
public void Locator_ReadsAFileNextToTheAssembly()
{
- var configuration = new RuntimeConfigurationLocator().Read(Fixture("Stellar.Runtime.Tests.Application"));
+ RuntimeConfiguration configuration =
+ new RuntimeConfigurationLocator().Read(Fixture("Stellar.Runtime.Tests.Application"));
configuration.EntryPoint.Should().Be("Stellar.Runtime.Tests.Application.Game");
configuration.Components.OfType().Single().Modules
@@ -46,7 +48,8 @@ public void Locator_ReadsAFileNextToTheAssembly()
[Fact]
public void Locator_ReadsAnEmbeddedResource()
{
- var configuration = new RuntimeConfigurationLocator().Read(Fixture("Stellar.Runtime.Tests.Host"));
+ RuntimeConfiguration configuration =
+ new RuntimeConfigurationLocator().Read(Fixture("Stellar.Runtime.Tests.Host"));
configuration.ProjectName.Should().Be("Host");
configuration.Settings["MaxFrames"].Should().Be("7");
@@ -56,14 +59,28 @@ public void Locator_ReadsAnEmbeddedResource()
public void Locator_MissingFile_SaysWhere()
{
using var directory = new TempFolder();
- var copy = Path.Combine(directory.Path, "Stellar.Runtime.Tests.Application.dll");
+ string copy = Path.Combine(directory.Path, "Stellar.Runtime.Tests.Application.dll");
File.Copy(Fixture("Stellar.Runtime.Tests.Application"), copy);
- var action = () => new RuntimeConfigurationLocator().Read(copy);
+ Func action = () => new RuntimeConfigurationLocator().Read(copy);
action.Should().Throw().WithMessage("*missing*stellar.runtime.config.json*");
}
+ [Fact]
+ public void Settings_ReachTheModules_WithTheCommandLine()
+ {
+ var configuration = new RuntimeConfiguration { Settings = { ["LogPath"] = "a.log", ["Custom"] = "x" } };
+
+ Dictionary settings = RuntimeSettings
+ .Create(configuration, ["--stellar:logpath=b.log", "--stellar:New=1"]).ToDictionary();
+
+ settings.Should().HaveCount(3);
+ settings["LogPath"].Should().Be("b.log");
+ settings["CUSTOM"].Should().Be("x");
+ settings["New"].Should().Be("1");
+ }
+
[Fact]
public void Settings_ProjectThenCommandLine()
{
@@ -104,7 +121,7 @@ public void Plan_RejectsDuplicates_AndWrongOrder()
[Fact]
public void Plan_WithoutModules_AsksForARebuild()
{
- var action = () => ModulePlan.From(new RuntimeConfiguration { ProjectName = "Old" });
+ Func action = () => ModulePlan.From(new RuntimeConfiguration { ProjectName = "Old" });
action.Should().Throw().WithMessage("*rebuild*");
}
diff --git a/Runtime/tests/Stellar.Runtime.Tests/ModuleStarterTests.cs b/Runtime/tests/Stellar.Runtime.Tests/ModuleStarterTests.cs
new file mode 100644
index 0000000..61be659
--- /dev/null
+++ b/Runtime/tests/Stellar.Runtime.Tests/ModuleStarterTests.cs
@@ -0,0 +1,98 @@
+using System.Reflection;
+
+using Stellar.Kernel.Configuration;
+using Stellar.Kernel.Configuration.Modules;
+using Stellar.Kernel.EntryPoint;
+using Stellar.Kernel.LoggingSystem;
+using Stellar.Kernel.Services;
+using Stellar.Runtime.Diagnostics;
+using Stellar.Runtime.Hosting;
+using Stellar.Runtime.Lifecycle;
+using Stellar.Runtime.Modules;
+using Stellar.Runtime.Threading;
+
+namespace Stellar.Runtime.Tests;
+
+public class ModuleStarterTests
+{
+ [Fact]
+ public void ALoggerWithdrawnByItsModule_IsNotWrittenToAnyMore()
+ {
+ var output = new StringWriter();
+ using var dispatcher = new MainThreadDispatcher();
+ using var control = new EngineControl();
+ var context =
+ new RuntimeContext(new RuntimeLaunch("Tests"), new RuntimeLog(fallback: output), dispatcher, control)
+ {
+ Services = DispatchProxy.Create()
+ };
+ var module = new LoadedModule(new RuntimeModuleData { Id = "Logging" }, typeof(Logging).Assembly,
+ typeof(Logging));
+
+ ModuleStarter.Start(context, module);
+ context.Log.Logger.Should().NotBeNull();
+
+ ModuleStarter.Stop(context, module);
+ context.Log.Error("after the logger");
+
+ output.ToString().Should().Contain("after the logger");
+ }
+
+ /// Publishes a logger, and takes it back when it stops.
+ public sealed class Logging(RuntimeConfiguration configuration)
+ : StellarEntryPoint("Tests/Logging", configuration)
+ {
+ private IServiceCatalog? _services;
+
+ public override int Run(ref readonly TContext context)
+ {
+ _services = context.Services;
+ _services!.Set(DispatchProxy.Create());
+ return 0;
+ }
+
+ public override void RequestStop(ref readonly TContext context)
+ {
+ _services!.Remove();
+ }
+
+ public override void Dispose()
+ {
+ }
+ }
+
+ public class Silent
+ : DispatchProxy
+ {
+ protected override object? Invoke(MethodInfo? method, object?[]? args)
+ {
+ return null;
+ }
+ }
+
+ public class Services
+ : DispatchProxy
+ {
+ private readonly Dictionary _items = [];
+
+ protected override object? Invoke(MethodInfo? method, object?[]? args)
+ {
+ var key = (Type)args![0]!;
+
+ switch (method!.Name)
+ {
+ case "Set":
+ _items[key] = args[1]!;
+ return null;
+ case "Remove":
+ return _items.Remove(key);
+ case "TryGet":
+ bool found = _items.TryGetValue(key, out object? value);
+ args[1] = value;
+ return found;
+ default:
+ throw new NotSupportedException(method.Name);
+ }
+ }
+ }
+}
diff --git a/SDK/src/MSBuild/Stellar.Sdk.Tasks/CompileStellarResources.cs b/SDK/src/MSBuild/Stellar.Sdk.Tasks/CompileStellarResources.cs
index a53759b..cc637f6 100644
--- a/SDK/src/MSBuild/Stellar.Sdk.Tasks/CompileStellarResources.cs
+++ b/SDK/src/MSBuild/Stellar.Sdk.Tasks/CompileStellarResources.cs
@@ -2,10 +2,13 @@
// ReSharper disable AutoPropertyCanBeMadeGetOnly.Global
// ReSharper disable UnusedAutoPropertyAccessor.Global
+using System.Collections.Generic;
using System.IO;
using System.Linq;
+
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
+
using Stellar.Tools.Environment;
using Stellar.Tools.Projects;
using Stellar.Tools.Resources;
@@ -36,21 +39,21 @@ public sealed class CompileStellarResources
///
protected override void Run()
{
- var project = StellarProject.Load(ConfigurationFile);
- var sources = ProjectFileResolver.Resolve(project).Resources;
+ StellarProject project = StellarProject.Load(ConfigurationFile);
+ IReadOnlyList sources = ProjectFileResolver.Resolve(project).Resources;
var compilers = ResourceCompilerRegistry.CreateDefault();
if (!string.IsNullOrEmpty(StellarRoot))
compilers.AddFromDirectory(new StellarInstallation(StellarRoot).ResourceCompilers, this);
- foreach (var assembly in project.Configuration.Resources?.Compilers ?? [])
+ foreach (string assembly in project.Configuration.Resources?.Compilers ?? [])
compilers.AddFrom(Path.Combine(project.Directory, assembly), this);
- var outputRoot = Path.GetFullPath(Path.Combine(project.Directory, OutputDirectory))
+ string outputRoot = Path.GetFullPath(Path.Combine(project.Directory, OutputDirectory))
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar);
- var result = new ResourcePipeline(compilers, this).Compile(sources, outputRoot);
+ ResourcePipelineResult result = new ResourcePipeline(compilers, this).Compile(sources, outputRoot);
Log.LogMessage(MessageImportance.High, $"Resource compilation result: " +
$"UpToDate - {result.UpToDate}, " +
@@ -61,7 +64,7 @@ protected override void Run()
.Select(output =>
{
var item = new TaskItem(output);
- item.SetMetadata("Link", Path.Combine("resources", output.Substring(outputRoot.Length + 1)));
+ item.SetMetadata("Link", Path.Combine("Resources", output.Substring(outputRoot.Length + 1)));
item.SetMetadata("CopyToOutputDirectory", "PreserveNewest");
return (ITaskItem)item;
})
diff --git a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/Configuration/ConfigurationFileAnalyzer.cs b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/Configuration/ConfigurationFileAnalyzer.cs
index cf36310..f8031d4 100644
--- a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/Configuration/ConfigurationFileAnalyzer.cs
+++ b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/Configuration/ConfigurationFileAnalyzer.cs
@@ -1,8 +1,10 @@
using System;
using System.Collections.Immutable;
+
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
+
using Stellar.Sdk.Analyzers.Diagnostics;
using Stellar.Sdk.Analyzers.Internal;
@@ -16,7 +18,9 @@ namespace Stellar.Sdk.Analyzers.Analyzers.Configuration;
public sealed class ConfigurationFileAnalyzer
: DiagnosticAnalyzer
{
- private static readonly string[] Extensions = { ".stellar.project", ".stellar.module" };
+ private static readonly string[] Extensions = [".stellar.project", ".stellar.module"];
+
+ // ── DiagnosticAnalyzer ────────────────────────────────────────────────
///
public override ImmutableArray SupportedDiagnostics =>
@@ -30,19 +34,22 @@ public override void Initialize(AnalysisContext context)
context.RegisterAdditionalFileAction(Analyze);
}
+ // ── Additional file action ────────────────────────────────────────────
+
private static void Analyze(AdditionalFileAnalysisContext context)
{
- var path = context.AdditionalFile.Path;
+ string path = context.AdditionalFile.Path;
if (Array.TrueForAll(Extensions, extension => !path.EndsWith(extension, StringComparison.OrdinalIgnoreCase)))
return;
- var text = context.AdditionalFile.GetText(context.CancellationToken);
- if (text is null || JsonSyntaxChecker.TryCheck(text.ToString(), out var position, out var message))
+ SourceText? text = context.AdditionalFile.GetText(context.CancellationToken);
+ if (text is null || JsonSyntaxChecker.TryCheck(text.ToString(), out int position, out string message))
return;
var span = new TextSpan(Math.Min(position, Math.Max(0, text.Length - 1)), text.Length == 0 ? 0 : 1);
var location = Location.Create(path, span, text.Lines.GetLinePositionSpan(span));
+ // ── STLR0301: malformed configuration file ────────────────────────
context.ReportDiagnostic(Diagnostic.Create(
StellarDiagnosticDescriptors.MalformedConfigurationFile,
location,
diff --git a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/EntryPoint/StellarEntryPointAnalyzer.cs b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/EntryPoint/StellarEntryPointAnalyzer.cs
index 2cfadda..bbc0ef2 100644
--- a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/EntryPoint/StellarEntryPointAnalyzer.cs
+++ b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/EntryPoint/StellarEntryPointAnalyzer.cs
@@ -2,8 +2,11 @@
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Linq;
+
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Text;
+
using Stellar.Sdk.Analyzers.Configuration;
using Stellar.Sdk.Analyzers.Diagnostics;
using Stellar.Sdk.Analyzers.Internal;
@@ -22,6 +25,23 @@ public sealed class StellarEntryPointAnalyzer : DiagnosticAnalyzer
private const string EntryPointBaseFqn = "Stellar.Kernel.EntryPoint.StellarEntryPoint";
private const string EntryPointAttributeFqn = "Stellar.Kernel.EntryPoint.StellarEntryPointAttribute";
+ // ── Helpers ───────────────────────────────────────────────────────────
+
+ private static string ResolveEntryPointTypeName(
+ string rawValue,
+ string? assemblyName
+ )
+ {
+ if (string.IsNullOrEmpty(rawValue)
+ || string.Equals(rawValue, DefaultEntryPointKeyword, StringComparison.OrdinalIgnoreCase))
+ // Convention: {AssemblyName}.EntryPoint in the root namespace
+ return string.IsNullOrEmpty(assemblyName)
+ ? DefaultEntryPointTypeSuffix
+ : $"{assemblyName}.{DefaultEntryPointTypeSuffix}";
+
+ return rawValue; // fully-qualified name written by the developer
+ }
+
// ── DiagnosticAnalyzer ────────────────────────────────────────────────
public override ImmutableArray SupportedDiagnostics =>
@@ -45,36 +65,36 @@ public override void Initialize(AnalysisContext context)
private static void OnCompilationStart(CompilationStartAnalysisContext ctx)
{
// 1. Locate .stellar.project in AdditionalFiles
- var configFile = ctx.Options.AdditionalFiles
+ AdditionalText? configFile = ctx.Options.AdditionalFiles
.FirstOrDefault(f => f.Path.EndsWith(
StellarProjectFileExtension,
StringComparison.OrdinalIgnoreCase));
if (configFile is null) return;
- var sourceText = configFile.GetText(ctx.CancellationToken);
+ SourceText? sourceText = configFile.GetText(ctx.CancellationToken);
if (sourceText is null) return;
// 2. Parse config — bail silently on malformed JSON
// (the build task will produce a proper build error for that)
- var readResult = StellarProjectConfigReader.TryRead(sourceText.ToString());
+ ConfigReadResult readResult = StellarProjectConfigReader.TryRead(sourceText.ToString());
if (!readResult.IsSuccess) return;
- var rawEntryPointValue =
+ string rawEntryPointValue =
readResult.Config!.Project?.StellarEntryPoint?.Trim()
?? DefaultEntryPointKeyword;
// 3. Resolve well-known Stellar symbols — they may be null if the
// kernel assembly isn't referenced, which is fine for pure
// library projects; checks will be skipped gracefully.
- var baseTypeSymbol =
+ INamedTypeSymbol? baseTypeSymbol =
ctx.Compilation.GetTypeByMetadataName(EntryPointBaseFqn);
- var attributeTypeSymbol =
+ INamedTypeSymbol? attributeTypeSymbol =
ctx.Compilation.GetTypeByMetadataName(EntryPointAttributeFqn);
// 4. Collect all types in this compilation that carry [StellarEntryPoint].
// ConcurrentBag because RegisterSymbolAction may run in parallel.
- var decoratedTypes = new ConcurrentBag();
+ ConcurrentBag decoratedTypes = new();
if (attributeTypeSymbol is not null)
ctx.RegisterSymbolAction(symbolCtx =>
@@ -105,15 +125,13 @@ private static void AnalyzeCompilationEnd(
string rawEntryPointValue,
INamedTypeSymbol? baseTypeSymbol,
INamedTypeSymbol? attributeTypeSymbol,
- ConcurrentBag decoratedTypes)
+ ConcurrentBag decoratedTypes
+ )
{
- var compilation = ctx.Compilation;
-
- // Resolve the configured type name
- var resolvedTypeName = ResolveEntryPointTypeName(rawEntryPointValue, compilation.AssemblyName);
+ Compilation compilation = ctx.Compilation;
// Location of the value token inside the .stellar.project file
- var configValueLocation = JsonTextLocator.FindValueLocation(
+ Location configValueLocation = JsonTextLocator.FindValueLocation(
sourceText, configFilePath, "StellarEntryPoint");
// ── STLR0104: no entry-point types at all in the module ───────────
@@ -126,7 +144,8 @@ private static void AnalyzeCompilationEnd(
compilation.AssemblyName ?? ""));
// ── Resolve the configured type ───────────────────────────────────
- var configuredType = compilation.GetTypeByMetadataName(resolvedTypeName);
+ string resolvedTypeName = ResolveEntryPointTypeName(rawEntryPointValue, compilation.AssemblyName);
+ INamedTypeSymbol? configuredType = compilation.GetTypeByMetadataName(resolvedTypeName);
// ── STLR0101: type not found ──────────────────────────────────────
if (configuredType is null)
@@ -140,7 +159,7 @@ private static void AnalyzeCompilationEnd(
// Use the first declaration location on the type itself for STLR0102/0103
// so the squiggle lands on the class keyword.
- var typeLocation = configuredType.Locations.FirstOrDefault() ?? Location.None;
+ Location typeLocation = configuredType.Locations.FirstOrDefault() ?? Location.None;
// ── STLR0102: missing inheritance ─────────────────────────────────
if (baseTypeSymbol is not null
@@ -158,20 +177,4 @@ private static void AnalyzeCompilationEnd(
typeLocation,
resolvedTypeName));
}
-
- // ── Helpers ───────────────────────────────────────────────────────────
-
- private static string ResolveEntryPointTypeName(
- string rawValue,
- string? assemblyName)
- {
- if (string.IsNullOrEmpty(rawValue)
- || string.Equals(rawValue, DefaultEntryPointKeyword, StringComparison.OrdinalIgnoreCase))
- // Convention: {AssemblyName}.EntryPoint in the root namespace
- return string.IsNullOrEmpty(assemblyName)
- ? DefaultEntryPointTypeSuffix
- : $"{assemblyName}.{DefaultEntryPointTypeSuffix}";
-
- return rawValue; // fully-qualified name written by the developer
- }
}
diff --git a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/Modules/ModuleArchitectureAnalyzer.cs b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/Modules/ModuleArchitectureAnalyzer.cs
index f55e309..ceb665b 100644
--- a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/Modules/ModuleArchitectureAnalyzer.cs
+++ b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Analyzers/Modules/ModuleArchitectureAnalyzer.cs
@@ -2,8 +2,11 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
+
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Diagnostics;
+using Microsoft.CodeAnalysis.Text;
+
using Stellar.Sdk.Analyzers.Configuration;
using Stellar.Sdk.Analyzers.Diagnostics;
using Stellar.Sdk.Analyzers.Internal;
@@ -23,9 +26,68 @@ namespace Stellar.Sdk.Analyzers.Analyzers.Modules;
public sealed class ModuleArchitectureAnalyzer
: DiagnosticAnalyzer
{
+ // ── Well-known Stellar type names ─────────────────────────────────────
+
private const string MetadataAttribute = "System.Reflection.AssemblyMetadataAttribute";
private const string DescriptorExtension = ".stellar.module";
+ // ── Helpers ───────────────────────────────────────────────────────────
+
+ private static Dictionary ReadMetadata(IAssemblySymbol assembly)
+ {
+ Dictionary values = new(StringComparer.Ordinal);
+
+ foreach (AttributeData attribute in assembly.GetAttributes())
+ {
+ if (attribute.AttributeClass?.ToDisplayString() != MetadataAttribute ||
+ attribute.ConstructorArguments.Length != 2)
+ continue;
+
+ if (attribute.ConstructorArguments[0].Value is string key &&
+ attribute.ConstructorArguments[1].Value is string value)
+ values[key] = value;
+ }
+
+ return values;
+ }
+
+ private static void CheckDescriptor(CompilationAnalysisContext context, string id)
+ {
+ AdditionalText? descriptor = context.Options.AdditionalFiles.FirstOrDefault(file =>
+ file.Path.EndsWith(DescriptorExtension, StringComparison.OrdinalIgnoreCase));
+ SourceText? text = descriptor?.GetText(context.CancellationToken);
+ if (descriptor is null || text is null)
+ return;
+
+ string? describedId = MinimalJson.GetString(text.ToString(), "Id");
+ if (describedId is null || string.Equals(describedId, id, StringComparison.Ordinal))
+ return;
+
+ // ── STLR0203: module descriptor mismatch ──────────────────────────
+ context.ReportDiagnostic(Diagnostic.Create(
+ StellarDiagnosticDescriptors.ModuleDescriptorMismatch,
+ JsonTextLocator.FindValueLocation(text, descriptor.Path, "Id"),
+ describedId, id));
+ }
+
+ private static void AddDependencies(
+ Dictionary metadata,
+ Dictionary> modules,
+ HashSet found
+ )
+ {
+ if (!metadata.TryGetValue("StellarModuleDependencies", out string? list))
+ return;
+
+ foreach (string dependency in list
+ .Split([';'], StringSplitOptions.RemoveEmptyEntries)
+ .Select(name => name.Trim()))
+ if (found.Add(dependency) && modules.TryGetValue(dependency, out Dictionary? next))
+ AddDependencies(next, modules, found);
+ }
+
+ // ── DiagnosticAnalyzer ────────────────────────────────────────────────
+
///
public override ImmutableArray SupportedDiagnostics =>
ImmutableArray.Create(
@@ -41,62 +103,68 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationAction(Analyze);
}
+ // ── Compilation action ────────────────────────────────────────────────
+
private static void Analyze(CompilationAnalysisContext context)
{
- var options = context.Options.AnalyzerConfigOptionsProvider.GlobalOptions;
+ AnalyzerConfigOptions options = context.Options.AnalyzerConfigOptionsProvider.GlobalOptions;
string? Property(string name)
{
- return options.TryGetValue("build_property." + name, out var value) && !string.IsNullOrWhiteSpace(value)
+ return options.TryGetValue("build_property." + name, out string? value)
+ && !string.IsNullOrWhiteSpace(value)
? value.Trim()
: null;
}
- var id = Property("StellarModuleId") ?? context.Compilation.AssemblyName ?? string.Empty;
- var isModule = string.Equals(Property("StellarIsModule"), "true", StringComparison.OrdinalIgnoreCase);
- var level = ModuleLevels.Parse(Property("StellarModuleLevel")) ??
- ModuleLevels.FromUsage(Property("StellarSdkUsage"));
+ string id = Property("StellarModuleId") ?? context.Compilation.AssemblyName ?? string.Empty;
+ bool isModule = string.Equals(Property("StellarIsModule"), "true", StringComparison.OrdinalIgnoreCase);
+ int? level = ModuleLevels.Parse(Property("StellarModuleLevel"))
+ ?? ModuleLevels.FromUsage(Property("StellarSdkUsage"));
if (level is null)
return;
- var declared = new HashSet(
+ HashSet declared = new(
(Property("StellarModuleDependencies") ?? string.Empty)
- .Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).Select(name => name.Trim()),
+ .Split([';'], StringSplitOptions.RemoveEmptyEntries).Select(name => name.Trim()),
StringComparer.Ordinal);
// Every referenced module, with what it says about itself
- var modules = new Dictionary>(StringComparer.Ordinal);
- foreach (var reference in context.Compilation.References)
+ Dictionary> modules = new(StringComparer.Ordinal);
+ foreach (MetadataReference reference in context.Compilation.References)
{
if (context.Compilation.GetAssemblyOrModuleSymbol(reference) is not IAssemblySymbol assembly)
continue;
- var metadata = ReadMetadata(assembly);
- if (metadata.TryGetValue("StellarModuleId", out var dependencyId) &&
- !string.Equals(dependencyId, id, StringComparison.Ordinal))
+ Dictionary metadata = ReadMetadata(assembly);
+ if (metadata.TryGetValue("StellarModuleId", out string? dependencyId)
+ && !string.Equals(dependencyId, id, StringComparison.Ordinal))
modules[dependencyId] = metadata;
}
// The compiler sees transitive references too. A module another referenced module depends on is not a
// dependency of this project: only the direct ones are checked
- var transitive = new HashSet(StringComparer.Ordinal);
- foreach (var metadata in modules.Values)
+ HashSet transitive = new(StringComparer.Ordinal);
+ foreach (Dictionary metadata in modules.Values)
AddDependencies(metadata, modules, transitive);
- foreach (var pair in modules.Where(pair => !transitive.Contains(pair.Key))
+ foreach (KeyValuePair> pair in modules
+ .Where(pair => !transitive.Contains(pair.Key))
.OrderBy(pair => pair.Key, StringComparer.Ordinal))
{
- var dependencyId = pair.Key;
- pair.Value.TryGetValue("StellarModuleLevel", out var dependencyLevelName);
- var dependencyLevel = ModuleLevels.Parse(dependencyLevelName);
+ string dependencyId = pair.Key;
+ pair.Value.TryGetValue("StellarModuleLevel", out string? dependencyLevelName);
+ int? dependencyLevel = ModuleLevels.Parse(dependencyLevelName);
+ // ── STLR0201: module level violation ──────────────────────────
if (dependencyLevel is { } known && !ModuleLevels.MayDependOn(level.Value, known))
context.ReportDiagnostic(Diagnostic.Create(
StellarDiagnosticDescriptors.ModuleLevelViolation,
Location.None,
id, ModuleLevels.Name(level.Value), dependencyId, ModuleLevels.Name(known)));
+ // ── STLR0202: undeclared module dependency ────────────────────
if (isModule && !ModuleLevels.IsCore(dependencyId) && !declared.Contains(dependencyId))
context.ReportDiagnostic(Diagnostic.Create(
StellarDiagnosticDescriptors.UndeclaredModuleDependency,
@@ -107,54 +175,4 @@ private static void Analyze(CompilationAnalysisContext context)
if (isModule)
CheckDescriptor(context, id);
}
-
- private static void CheckDescriptor(CompilationAnalysisContext context, string id)
- {
- var descriptor = context.Options.AdditionalFiles.FirstOrDefault(file =>
- file.Path.EndsWith(DescriptorExtension, StringComparison.OrdinalIgnoreCase));
- var text = descriptor?.GetText(context.CancellationToken);
- if (descriptor is null || text is null)
- return;
-
- var describedId = MinimalJson.GetString(text.ToString(), "Id");
- if (describedId is null || string.Equals(describedId, id, StringComparison.Ordinal))
- return;
-
- context.ReportDiagnostic(Diagnostic.Create(
- StellarDiagnosticDescriptors.ModuleDescriptorMismatch,
- JsonTextLocator.FindValueLocation(text, descriptor.Path, "Id"),
- describedId, id));
- }
-
- private static void AddDependencies(
- Dictionary metadata,
- Dictionary> modules,
- HashSet found)
- {
- if (!metadata.TryGetValue("StellarModuleDependencies", out var list))
- return;
-
- foreach (var dependency in list.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)
- .Select(name => name.Trim()))
- if (found.Add(dependency) && modules.TryGetValue(dependency, out var next))
- AddDependencies(next, modules, found);
- }
-
- private static Dictionary ReadMetadata(IAssemblySymbol assembly)
- {
- var values = new Dictionary(StringComparer.Ordinal);
-
- foreach (var attribute in assembly.GetAttributes())
- {
- if (attribute.AttributeClass?.ToDisplayString() != MetadataAttribute ||
- attribute.ConstructorArguments.Length != 2)
- continue;
-
- if (attribute.ConstructorArguments[0].Value is string key &&
- attribute.ConstructorArguments[1].Value is string value)
- values[key] = value;
- }
-
- return values;
- }
}
diff --git a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Configuration/StellarAnalyzerProjectDtos.cs b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Configuration/StellarAnalyzerProjectDtos.cs
index dce467e..efedc9f 100644
--- a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Configuration/StellarAnalyzerProjectDtos.cs
+++ b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Configuration/StellarAnalyzerProjectDtos.cs
@@ -7,13 +7,6 @@ namespace Stellar.Sdk.Analyzers.Configuration;
// These are thin, analyzer-private mirrors of the public DTOs.
// ─────────────────────────────────────────────────────────────────────────
-internal sealed class StellarAnalyzerConfigFile
-{
- public StellarAnalyzerProjectConfig? Project { get; set; }
-
- // Runtime section intentionally omitted — analyzers don't need it.
-}
-
internal sealed class StellarAnalyzerProjectConfig
{
public string? StellarEntryPoint { get; set; }
@@ -21,3 +14,10 @@ internal sealed class StellarAnalyzerProjectConfig
// Other fields (Assets, Localizations …) will be added here
// as future analyzers need them — zero cost when unused.
}
+
+internal sealed class StellarAnalyzerConfigFile
+{
+ public StellarAnalyzerProjectConfig? Project { get; set; }
+
+ // Runtime section intentionally omitted — analyzers don't need it.
+}
diff --git a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Configuration/StellarProjectConfigReader.cs b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Configuration/StellarProjectConfigReader.cs
index cb0e621..451faa0 100644
--- a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Configuration/StellarProjectConfigReader.cs
+++ b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Configuration/StellarProjectConfigReader.cs
@@ -37,50 +37,30 @@ public static ConfigReadResult Failure(string errorMessage)
internal static class MinimalJson
{
- public static string? GetNestedString(string json, string parentKey, string childKey)
- {
- var parentIndex = json.IndexOf($"\"{parentKey}\"", StringComparison.Ordinal);
- if (parentIndex < 0) return null;
-
- var colonIndex = json.IndexOf(':', parentIndex);
- if (colonIndex < 0) return null;
-
- var objStart = json.IndexOf('{', colonIndex);
- if (objStart < 0) return null;
-
- var objEnd = FindMatchingBrace(json, objStart);
- if (objEnd < 0) return null;
-
- // from here on only the inside of Project { ... } is looked at
- var span = json.Substring(objStart, objEnd - objStart + 1);
-
- return GetString(span, childKey);
- }
-
- public static string? GetString(string json, string key)
+ private static int FindStringEnd(string json, int start)
{
- var keyIndex = json.IndexOf($"\"{key}\"", StringComparison.Ordinal);
- if (keyIndex < 0) return null;
-
- var colonIndex = json.IndexOf(':', keyIndex);
- if (colonIndex < 0) return null;
-
- var startQuote = json.IndexOf('"', colonIndex + 1);
- if (startQuote < 0) return null;
+ for (int i = start; i < json.Length; i++)
+ {
+ if (json[i] == '\\') // skip escaped char
+ {
+ i++;
+ continue;
+ }
- var endQuote = FindStringEnd(json, startQuote + 1);
- if (endQuote < 0) return null;
+ if (json[i] == '"')
+ return i;
+ }
- return json.Substring(startQuote + 1, endQuote - startQuote - 1);
+ return -1;
}
private static int FindMatchingBrace(string json, int start)
{
- var depth = 0;
+ int depth = 0;
- for (var i = start; i < json.Length; i++)
+ for (int i = start; i < json.Length; i++)
{
- var c = json[i];
+ char c = json[i];
if (c == '{')
{
@@ -102,21 +82,41 @@ private static int FindMatchingBrace(string json, int start)
return -1;
}
- private static int FindStringEnd(string json, int start)
+ public static string? GetString(string json, string key)
{
- for (var i = start; i < json.Length; i++)
- {
- if (json[i] == '\\') // skip escaped char
- {
- i++;
- continue;
- }
+ int keyIndex = json.IndexOf($"\"{key}\"", StringComparison.Ordinal);
+ if (keyIndex < 0) return null;
- if (json[i] == '"')
- return i;
- }
+ int colonIndex = json.IndexOf(':', keyIndex);
+ if (colonIndex < 0) return null;
- return -1;
+ int startQuote = json.IndexOf('"', colonIndex + 1);
+ if (startQuote < 0) return null;
+
+ int endQuote = FindStringEnd(json, startQuote + 1);
+ if (endQuote < 0) return null;
+
+ return json.Substring(startQuote + 1, endQuote - startQuote - 1);
+ }
+
+ public static string? GetNestedString(string json, string parentKey, string childKey)
+ {
+ int parentIndex = json.IndexOf($"\"{parentKey}\"", StringComparison.Ordinal);
+ if (parentIndex < 0) return null;
+
+ int colonIndex = json.IndexOf(':', parentIndex);
+ if (colonIndex < 0) return null;
+
+ int objStart = json.IndexOf('{', colonIndex);
+ if (objStart < 0) return null;
+
+ int objEnd = FindMatchingBrace(json, objStart);
+ if (objEnd < 0) return null;
+
+ // from here on only the inside of Project { ... } is looked at
+ string span = json.Substring(objStart, objEnd - objStart + 1);
+
+ return GetString(span, childKey);
}
}
@@ -129,8 +129,7 @@ public static ConfigReadResult TryRead(string json)
try
{
- var entryPoint = MinimalJson.GetNestedString(
- json,
+ string? entryPoint = MinimalJson.GetNestedString(json,
"Project",
"StellarEntryPoint");
diff --git a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Internal/ModuleLevels.cs b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Internal/ModuleLevels.cs
index d328f9d..2e5c857 100644
--- a/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Internal/ModuleLevels.cs
+++ b/SDK/src/Roslyn/Stellar.Sdk.Analyzers/Internal/ModuleLevels.cs
@@ -69,7 +69,7 @@ public static string Name(int level)
public static bool IsCore(string id)
{
- return string.Equals(id, "Stellar.Kernel", StringComparison.Ordinal) ||
- string.Equals(id, "Stellar.Core", StringComparison.Ordinal);
+ return string.Equals(id, "Stellar.Kernel", StringComparison.Ordinal)
+ || string.Equals(id, "Stellar.Core", StringComparison.Ordinal);
}
}
diff --git a/SDK/src/Stellar.Cli/Commands/InstallCommand.cs b/SDK/src/Stellar.Cli/Commands/InstallCommand.cs
index 4081785..9fd417d 100644
--- a/SDK/src/Stellar.Cli/Commands/InstallCommand.cs
+++ b/SDK/src/Stellar.Cli/Commands/InstallCommand.cs
@@ -1,16 +1,42 @@
using System.ComponentModel;
+
using Spectre.Console.Cli;
+
using Stellar.Tools.Environment;
using Stellar.Tools.Installation;
namespace Stellar.Cli.Commands;
+///
+/// What install and uninstall take from the machine.
+///
+internal static class InstallationPaths
+{
+ ///
+ /// The root a command acts on: the argument, $STELLAR_ROOT or the current directory.
+ ///
+ public static string Root(string? path)
+ {
+ return path
+ ?? Environment.GetEnvironmentVariable(StellarInstallation.EnvironmentVariable)
+ ?? Environment.CurrentDirectory;
+ }
+
+ ///
+ /// The NuGet package cache of the user: $NUGET_PACKAGES, or ~/.nuget/packages.
+ ///
+ public static string PackageCache()
+ {
+ return Tools.Installation.PackageCache.Location();
+ }
+}
+
public sealed class InstallSettings
: CommandSettings
{
[CommandArgument(0, "[PATH]")]
- [Description(
- "The checkout of StellarEngine-Core to turn into an installation. $STELLAR_ROOT or the current directory when omitted")]
+ [Description("The checkout of StellarEngine-Core to turn into an installation. " +
+ "$STELLAR_ROOT or the current directory when omitted")]
public string? Path { get; set; }
[CommandOption("--no-user-registration")]
@@ -32,27 +58,3 @@ public override int Execute(CommandContext context, InstallSettings settings)
return 0;
}
}
-
-///
-/// What install and uninstall take from the machine.
-///
-internal static class InstallationPaths
-{
- ///
- /// The root a command acts on: the argument, $STELLAR_ROOT or the current directory.
- ///
- public static string Root(string? path)
- {
- return path
- ?? Environment.GetEnvironmentVariable(StellarInstallation.EnvironmentVariable)
- ?? Environment.CurrentDirectory;
- }
-
- ///
- /// The NuGet package cache of the user: $NUGET_PACKAGES, or ~/.nuget/packages.
- ///
- public static string PackageCache()
- {
- return Stellar.Tools.Installation.PackageCache.Location();
- }
-}
diff --git a/SDK/src/Stellar.Cli/Commands/MarksCommands.cs b/SDK/src/Stellar.Cli/Commands/MarksCommands.cs
new file mode 100644
index 0000000..4af4ebe
--- /dev/null
+++ b/SDK/src/Stellar.Cli/Commands/MarksCommands.cs
@@ -0,0 +1,165 @@
+using System.ComponentModel;
+
+using Spectre.Console;
+using Spectre.Console.Cli;
+
+using Stellar.Tools.Diagnostics;
+using Stellar.Tools.Environment;
+using Stellar.Tools.Marks;
+
+namespace Stellar.Cli.Commands;
+
+///
+/// What every stellar marks command takes.
+///
+public class MarksSettings
+ : CommandSettings
+{
+ [CommandArgument(0, "[PATH]")]
+ [Description("A folder of the repository. The current one when omitted")]
+ public string? Path { get; set; }
+
+ [CommandOption("-a|--all")]
+ [Description("The core and every module and tool of the installation, not one repository")]
+ public bool All { get; set; }
+
+ internal string Directory => System.IO.Path.GetFullPath(Path ?? Environment.CurrentDirectory);
+
+ // The kinds lie in the core, above the repository or in the registered installation
+ internal string Root => MarkCatalog.FindRoot(Directory)
+ ?? StellarInstallation.TryLocate(Directory, InstallationRegistry.ForCurrentUser())?.Root
+ ?? throw new ToolException(
+ $"No installation for {Directory}: the kinds of marks are not known");
+
+ internal IReadOnlyList Repositories =>
+ All ? MarkRepository.OpenAll(Root) : [MarkRepository.Open(Directory)];
+}
+
+///
+/// The settings of stellar marks check.
+///
+public sealed class CheckMarksSettings
+ : MarksSettings
+{
+ [CommandOption("--staged")]
+ [Description("What the next commit changes, as it will be committed")]
+ public bool Staged { get; set; }
+
+ [CommandOption("--revision ")]
+ [Description("A commit, not the files of the folder")]
+ public string? Revision { get; set; }
+
+ [CommandOption("--stage ")]
+ [Description("What is about to happen: commit (the default) or release")]
+ [DefaultValue(MarkStage.Commit)]
+ public MarkStage Stage { get; set; }
+
+ public override ValidationResult Validate()
+ {
+ return Staged && Revision is not null
+ ? ValidationResult.Error("--staged and --revision exclude one another")
+ : ValidationResult.Success();
+ }
+}
+
+///
+/// stellar marks check: fails if a mark stops the code at the stage.
+///
+public sealed class CheckMarksCommand
+ : Command
+{
+ public override int Execute(CommandContext context, CheckMarksSettings settings)
+ {
+ MarkCatalog catalog = MarkCatalog.Load(settings.Root);
+ int stopped = 0;
+ int total = 0;
+
+ foreach (MarkRepository repository in settings.Repositories)
+ {
+ IReadOnlyList marks = settings.Staged ? repository.ScanStaged()
+ : settings.Revision is { } revision ? repository.ScanRevision(revision)
+ : repository.ScanFiles();
+ total += marks.Count;
+
+ foreach (Mark mark in marks.Where(mark => catalog.Stops(mark.Name, settings.Stage)))
+ {
+ stopped++;
+ string why = catalog.Kinds.TryGetValue(mark.Name, out MarkKind? kind)
+ ? kind.Description
+ : "unknown mark";
+ Console.Error.WriteLine($"{Path.Combine(repository.Root, mark.File)}:{mark.Line}: {mark.Name}: {why}");
+ }
+ }
+
+ if (stopped > 0)
+ {
+ Console.Error.WriteLine($"{stopped} mark(s) stop the {settings.Stage.ToString().ToLowerInvariant()}");
+ return 1;
+ }
+
+ Console.WriteLine($"Marks: {total}, none stops the {settings.Stage.ToString().ToLowerInvariant()}");
+ return 0;
+ }
+}
+
+///
+/// stellar marks list: the marks and what they mean.
+///
+public sealed class ListMarksCommand
+ : Command
+{
+ public override int Execute(CommandContext context, MarksSettings settings)
+ {
+ MarkCatalog catalog = MarkCatalog.Load(settings.Root);
+ ILookup marks = settings.Repositories
+ .SelectMany(repository => repository.ScanFiles()
+ .Select(mark => (mark.Name, Place: $"{Path.Combine(repository.Root, mark.File)}:{mark.Line}")))
+ .ToLookup(mark => mark.Name, mark => mark.Place);
+
+ foreach (string name in catalog.Kinds.Keys.Union(marks.Select(group => group.Key))
+ .OrderBy(name => name, StringComparer.Ordinal))
+ {
+ string about = catalog.Kinds.TryGetValue(name, out MarkKind? kind)
+ ? $"{kind.Level}: {kind.Description}"
+ : "unknown";
+ Console.WriteLine($"{name} ({marks[name].Count()}) {about}");
+ foreach (string place in marks[name]) Console.WriteLine($" {place}");
+ }
+
+ return 0;
+ }
+}
+
+///
+/// stellar marks install: git checks the marks of every commit, merge and push.
+///
+public sealed class InstallMarksCommand
+ : Command
+{
+ public override int Execute(CommandContext context, MarksSettings settings)
+ {
+ MarkCatalog.Load(settings.Root);
+ foreach (MarkRepository repository in settings.Repositories)
+ {
+ repository.InstallHooks();
+ Console.WriteLine($"Checks the marks: {repository.Root}");
+ }
+
+ return 0;
+ }
+}
+
+///
+/// stellar marks uninstall: takes the checks out of git.
+///
+public sealed class UninstallMarksCommand
+ : Command
+{
+ public override int Execute(CommandContext context, MarksSettings settings)
+ {
+ foreach (MarkRepository repository in settings.Repositories)
+ Console.WriteLine($"Removed {repository.RemoveHooks().Count} hook(s): {repository.Root}");
+
+ return 0;
+ }
+}
diff --git a/SDK/src/Stellar.Cli/Commands/Modules/ModuleCommands.cs b/SDK/src/Stellar.Cli/Commands/Modules/ModuleCommands.cs
index a74346d..0eb6c33 100644
--- a/SDK/src/Stellar.Cli/Commands/Modules/ModuleCommands.cs
+++ b/SDK/src/Stellar.Cli/Commands/Modules/ModuleCommands.cs
@@ -1,6 +1,9 @@
using System.ComponentModel;
+
using Spectre.Console;
using Spectre.Console.Cli;
+
+using Stellar.Kernel.Configuration.Manifest;
using Stellar.Kernel.Modules;
using Stellar.Tools.Building;
using Stellar.Tools.Diagnostics;
@@ -15,15 +18,15 @@ public sealed class ListModulesCommand
{
public override int Execute(CommandContext context)
{
- var set = ModuleSynchronizer.Load(StellarInstallation.Locate());
+ ModuleSet set = ModuleSynchronizer.Load(StellarInstallation.Locate());
- var table = new Table()
+ Table table = new Table()
.AddColumn("#").AddColumn("Module").AddColumn("Version").AddColumn("Level")
.AddColumn("Source").AddColumn("Link").AddColumn("Dependencies");
- for (var index = 0; index < set.LoadOrder.Count; index++)
+ for (int index = 0; index < set.LoadOrder.Count; index++)
{
- var module = set.LoadOrder[index];
+ ResolvedModule module = set.LoadOrder[index];
table.AddRow(
(index + 1).ToString(),
module.Id.EscapeMarkup(),
@@ -36,10 +39,10 @@ public override int Execute(CommandContext context)
AnsiConsole.Write(table);
- foreach (var id in set.Resolution.Disabled)
+ foreach (string id in set.Resolution.Disabled)
AnsiConsole.MarkupLineInterpolated($"[grey]disabled: {id}[/]");
- foreach (var warning in set.Resolution.Warnings)
+ foreach (string warning in set.Resolution.Warnings)
AnsiConsole.MarkupLineInterpolated($"[yellow]{warning}[/]");
return 0;
@@ -91,8 +94,8 @@ public override int Execute(CommandContext context, NewModuleSettings settings)
throw new ToolException(
$"{settings.Level} is the core itself: a module is CoreModule, Runtime, HighLevel or EndPoint");
- var installation = StellarInstallation.Locate();
- var directory = new ModuleScaffolder(installation, ConsoleToolLogger.Instance)
+ StellarInstallation installation = StellarInstallation.Locate();
+ string directory = new ModuleScaffolder(installation, ConsoleToolLogger.Instance)
.Create(new ModuleRequest(settings.Id, settings.Level, settings.Description, settings.Template,
settings.Output));
@@ -114,7 +117,7 @@ public override int Execute(CommandContext context)
{
var scaffolder = new ModuleScaffolder(StellarInstallation.Locate(), ConsoleToolLogger.Instance);
- foreach (var template in scaffolder.ListTemplates())
+ foreach (string template in scaffolder.ListTemplates())
AnsiConsole.MarkupLineInterpolated(
$"- {template} [grey]{scaffolder.DescribeTemplate(template) ?? string.Empty}[/]");
@@ -139,16 +142,16 @@ public sealed class AddModuleCommand
{
public override int Execute(CommandContext context, AddModuleSettings settings)
{
- var directory = Path.GetFullPath(settings.Directory);
- var file = ModuleDescriptorFile.Find(directory)
- ?? throw new ToolException($"{directory} is not a module: it has no .stellar.module file");
- var descriptor = ModuleDescriptorFile.Read(file);
- var installation = StellarInstallation.Locate();
+ string directory = Path.GetFullPath(settings.Directory);
+ string file = ModuleDescriptorFile.Find(directory)
+ ?? throw new ToolException($"{directory} is not a module: it has no .stellar.module file");
+ ModuleDescriptor descriptor = ModuleDescriptorFile.Read(file);
+ StellarInstallation installation = StellarInstallation.Locate();
ModuleFeed.EnsureReachable(installation, directory, ConsoleToolLogger.Instance);
ManifestChanges.Apply(installation, manifest =>
{
- var entry = EngineManifestEditor.Entry(manifest, descriptor.Id);
+ ModuleOverride entry = EngineManifestEditor.Entry(manifest, descriptor.Id);
entry.Path = directory;
entry.Link = settings.Link ?? entry.Link;
});
@@ -239,28 +242,26 @@ public sealed class BuildModulesCommand
{
public override int Execute(CommandContext context, BuildModulesSettings settings)
{
- var installation = StellarInstallation.Locate();
- var set = ModuleSynchronizer.Synchronize(installation, ConsoleToolLogger.Instance);
+ StellarInstallation installation = StellarInstallation.Locate();
+ ModuleSet set = ModuleSynchronizer.Synchronize(installation, ConsoleToolLogger.Instance);
var options = new ModuleBuildOptions(settings.Configuration, !settings.NoNative, true, settings.Tests,
settings.Pack, settings.Wrapper);
- var steps = ModuleBuildPlanner.Plan(installation, set, settings.Ids, options,
+ IReadOnlyList steps = ModuleBuildPlanner.Plan(installation, set, settings.Ids, options,
settings.NoNative ? null : MSBuildLocator.Find());
if (settings.Plan)
{
- foreach (var step in steps)
+ foreach (BuildStep step in steps)
AnsiConsole.MarkupLineInterpolated(
$"{step.Module}: [grey]{step.FileName} {string.Join(" ", step.Arguments)}[/]");
return 0;
}
- new ModuleBuilder(new ProcessRunner(ConsoleToolLogger.Instance), ConsoleToolLogger.Instance).Run(steps,
- installation.Root);
-
- // Packed again under the same versions: the games must not keep the copies NuGet unpacked before
- if (settings.Pack)
- Stellar.Tools.Installation.PackageCache.RefreshStale(installation.Packages, null, ConsoleToolLogger.Instance);
+ new ModuleBuilder(new ProcessRunner(ConsoleToolLogger.Instance), ConsoleToolLogger.Instance,
+ () => Tools.Installation.PackageCache.RefreshStale(installation.Packages, null,
+ ConsoleToolLogger.Instance))
+ .Run(steps, installation.Root);
return 0;
}
}
@@ -270,11 +271,13 @@ public override int Execute(CommandContext context, BuildModulesSettings setting
///
internal static class ManifestChanges
{
- public static void Apply(StellarInstallation installation,
- Action change)
+ public static void Apply(
+ StellarInstallation installation,
+ Action change
+ )
{
- var original = File.ReadAllText(installation.EngineManifest);
- var manifest = EngineManifestStore.Load(installation.EngineManifest);
+ string original = File.ReadAllText(installation.EngineManifest);
+ EngineManifest manifest = EngineManifestStore.Load(installation.EngineManifest);
change(manifest);
EngineManifestEditor.Compact(manifest);
diff --git a/SDK/src/Stellar.Cli/Program.cs b/SDK/src/Stellar.Cli/Program.cs
index e86a295..79337a8 100644
--- a/SDK/src/Stellar.Cli/Program.cs
+++ b/SDK/src/Stellar.Cli/Program.cs
@@ -1,10 +1,11 @@
using Spectre.Console;
using Spectre.Console.Cli;
+
+using Stellar.Tools.Diagnostics;
using Stellar.Cli.Commands;
using Stellar.Cli.Commands.Modules;
using Stellar.Cli.Commands.Project;
using Stellar.Cli.Commands.Resources;
-using Stellar.Tools.Diagnostics;
var app = new CommandApp();
@@ -71,6 +72,23 @@
.WithDescription("Build modules with their dependencies: native, managed, tests, packages");
}).WithAlias("module");
+ config.AddBranch("marks", marks =>
+ {
+ marks.SetDescription("The marks in the comments of the code");
+
+ marks.AddCommand("check")
+ .WithDescription("Fail if a mark stops a commit or a release");
+
+ marks.AddCommand("list")
+ .WithDescription("Show the marks and what they mean");
+
+ marks.AddCommand("install")
+ .WithDescription("Make git check the marks of every commit, merge and push");
+
+ marks.AddCommand("uninstall")
+ .WithDescription("Take the checks out of git");
+ }).WithAlias("mark");
+
config.AddBranch("project", project =>
{
project.SetDescription("Project related commands");
diff --git a/SDK/src/Stellar.Tools/Building/ModuleBuildPlanner.cs b/SDK/src/Stellar.Tools/Building/ModuleBuildPlanner.cs
index 4224251..ca028bb 100644
--- a/SDK/src/Stellar.Tools/Building/ModuleBuildPlanner.cs
+++ b/SDK/src/Stellar.Tools/Building/ModuleBuildPlanner.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Linq;
+
using Stellar.Tools.Diagnostics;
using Stellar.Tools.Environment;
using Stellar.Tools.Modules;
@@ -23,7 +24,8 @@ public sealed record ModuleBuildOptions(
bool Managed = true,
bool Tests = false,
bool Pack = false,
- string? NativeWrapper = null);
+ string? NativeWrapper = null
+);
///
/// One program to run.
@@ -32,11 +34,18 @@ public sealed record ModuleBuildOptions(
/// What the step does, for the output.
/// The program.
/// Its arguments.
-public sealed record BuildStep(string Module, string Description, string FileName, IReadOnlyList Arguments);
+/// Whether the step puts a package into the local feed.
+public sealed record BuildStep(
+ string Module,
+ string Description,
+ string FileName,
+ IReadOnlyList Arguments,
+ bool IsPack = false
+);
///
/// Turns modules into the steps that build them: for each module in load order, its native projects (MSBuild of
-/// Visual Studio), its managed project, its tests and its package. The dependencies of the selected modules come
+/// Visual Studio), its managed project, its package and its tests. The dependencies of the selected modules come
/// first, since a module is built against what they produced.
///
public static class ModuleBuildPlanner
@@ -56,12 +65,14 @@ public static IReadOnlyList Plan(
ModuleSet set,
IReadOnlyCollection selected,
ModuleBuildOptions options,
- string? msbuild)
+ string? msbuild
+ )
{
- var byId = set.LoadOrder.ToDictionary(module => module.Id, StringComparer.Ordinal);
- var wanted = new HashSet(StringComparer.Ordinal);
+ Dictionary byId =
+ set.LoadOrder.ToDictionary(module => module.Id, StringComparer.Ordinal);
+ HashSet wanted = new(StringComparer.Ordinal);
- foreach (var id in selected.Count == 0 ? byId.Keys : selected)
+ foreach (string id in selected.Count == 0 ? byId.Keys : selected)
{
if (!byId.ContainsKey(id))
throw new ToolException($"Unknown module {id}. Known: {string.Join(", ", byId.Keys)}");
@@ -69,19 +80,19 @@ public static IReadOnlyList Plan(
AddWithDependencies(id);
}
- var steps = new List();
+ List steps = new();
// Modules outside the root find it this way. Forward slashes: a trailing backslash would escape the quote
- var root = $"-p:StellarRoot={installation.Root.Replace('\\', '/').TrimEnd('/')}/";
- var properties = new List { $"-p:Configuration={options.Configuration}", root };
+ string root = $"-p:StellarRoot={installation.Root.Replace('\\', '/').TrimEnd('/')}/";
+ List properties = [$"-p:Configuration={options.Configuration}", root];
if (options.NativeWrapper is { Length: > 0 } wrapper)
properties.Add($"-p:StellarNativeWrapper={wrapper}");
- foreach (var module in
+ foreach (ResolvedModule module in
set.LoadOrder.Where(module => wanted.Contains(module.Id) && module.Directory is not null))
{
if (options.Native)
- foreach (var project in module.NativeProjectPaths)
+ foreach (string project in module.NativeProjectPaths)
{
if (msbuild is null)
throw new ToolException(
@@ -89,27 +100,25 @@ public static IReadOnlyList Plan(
$"Install Visual Studio with the C++ workload, set {MSBuildLocator.EnvironmentVariable}, or build with --no-native.");
steps.Add(new BuildStep(module.Id, $"native {Path.GetFileNameWithoutExtension(project)}", msbuild,
- new[]
- {
- project, "-restore", $"-p:Configuration={options.Configuration}", "-p:Platform=x64", root,
- "-m", "-nologo", "-v:minimal"
- }));
+ [
+ project, "-restore", $"-p:Configuration={options.Configuration}", "-p:Platform=x64", root,
+ "-m", "-nologo", "-v:minimal"
+ ]));
}
if (options.Managed && module.ProjectPath is { } managed)
steps.Add(new BuildStep(module.Id, $"build {Path.GetFileNameWithoutExtension(managed)}", "dotnet",
- new[] { "build", managed, "-v", "minimal", "--nologo" }.Concat(properties).ToArray()));
+ ["build", managed, "-v", "minimal", "--nologo", .. properties]));
+
+ if (options.Pack && module.ProjectPath is { } packed)
+ steps.Add(new BuildStep(module.Id, $"pack {Path.GetFileNameWithoutExtension(packed)}", "dotnet",
+ ["pack", packed, "-o", installation.Packages, "-v", "quiet", "--nologo", .. properties], true));
if (options.Tests)
- foreach (var tests in module.TestProjectPaths.Where(path =>
+ foreach (string tests in module.TestProjectPaths.Where(path =>
path.EndsWith(".csproj", StringComparison.OrdinalIgnoreCase)))
steps.Add(new BuildStep(module.Id, $"test {Path.GetFileNameWithoutExtension(tests)}", "dotnet",
- new[] { "test", tests, "--nologo" }.Concat(properties).ToArray()));
-
- if (options.Pack && module.ProjectPath is { } packed)
- steps.Add(new BuildStep(module.Id, $"pack {Path.GetFileNameWithoutExtension(packed)}", "dotnet",
- new[] { "pack", packed, "-o", installation.Packages, "-v", "quiet", "--nologo" }.Concat(properties)
- .ToArray()));
+ ["test", tests, "--nologo", .. properties]));
}
return steps;
@@ -119,7 +128,7 @@ void AddWithDependencies(string id)
if (!wanted.Add(id))
return;
- foreach (var dependency in byId[id].Descriptor.Dependencies.Where(byId.ContainsKey))
+ foreach (string dependency in byId[id].Descriptor.Dependencies.Where(byId.ContainsKey))
AddWithDependencies(dependency);
}
}
@@ -132,14 +141,19 @@ public sealed class ModuleBuilder
{
private readonly IProcessRunner _runner;
private readonly IToolLogger _logger;
+ private readonly Action? _packed;
///
/// Creates a builder.
///
- public ModuleBuilder(IProcessRunner runner, IToolLogger logger)
+ /// Runs the programs.
+ /// The output.
+ /// Called after every step that packed, before the next one, which may take the package.
+ public ModuleBuilder(IProcessRunner runner, IToolLogger logger, Action? packed = null)
{
_runner = runner;
_logger = logger;
+ _packed = packed;
}
///
@@ -150,14 +164,17 @@ public ModuleBuilder(IProcessRunner runner, IToolLogger logger)
/// Thrown at the first step that fails.
public void Run(IReadOnlyList steps, string workingDirectory)
{
- for (var index = 0; index < steps.Count; index++)
+ for (int index = 0; index < steps.Count; index++)
{
- var step = steps[index];
+ BuildStep step = steps[index];
_logger.Info($"[{index + 1}/{steps.Count}] {step.Module}: {step.Description}");
- var exitCode = _runner.Run(step.FileName, step.Arguments, workingDirectory);
+ int exitCode = _runner.Run(step.FileName, step.Arguments, workingDirectory);
if (exitCode != 0)
throw new ToolException($"{step.Module}: {step.Description} failed with exit code {exitCode}");
+
+ if (step.IsPack)
+ _packed?.Invoke();
}
_logger.Info(steps.Count == 0
diff --git a/SDK/src/Stellar.Tools/Environment/InstallationRegistry.cs b/SDK/src/Stellar.Tools/Environment/InstallationRegistry.cs
index f20fcbe..335f175 100644
--- a/SDK/src/Stellar.Tools/Environment/InstallationRegistry.cs
+++ b/SDK/src/Stellar.Tools/Environment/InstallationRegistry.cs
@@ -1,3 +1,5 @@
+// ReSharper disable PropertyCanBeMadeInitOnly.Global
+
using System;
using System.Collections.Generic;
using System.IO;
@@ -45,8 +47,9 @@ public sealed class InstallationRegistryFile
/// while it evaluates a project. Tools change the JSON through this class only, so both stay in step.
///
///
-/// One installation per orchestra version: registering a version again moves it to the new root. What an orchestra
-/// holds (modules, versions) is not here: it is in the manifests of the installation itself.
+/// One installation per orchestra version, and one version per root: registering a version again moves it to the
+/// new root, and a root installed again with a newer orchestra keeps only that one. What an orchestra holds (modules,
+/// versions) is not here: it is in the manifests of the installation itself.
///
///
/// An instance is a folder, not a global: tests and sandboxes create their own.
@@ -94,9 +97,9 @@ public static string UserDirectory
{
get
{
- var fromVariable = System.Environment.GetEnvironmentVariable(EnvironmentVariable);
+ string? fromVariable = System.Environment.GetEnvironmentVariable(EnvironmentVariable);
return !string.IsNullOrWhiteSpace(fromVariable)
- ? Path.GetFullPath(fromVariable!)
+ ? Path.GetFullPath(fromVariable)
: Path.Combine(
System.Environment.GetFolderPath(System.Environment.SpecialFolder.UserProfile), ".stellar");
}
@@ -124,22 +127,24 @@ public IReadOnlyList List()
/// The installation, or null if the version is not registered.
public StellarInstallation? Find(string orchesterVersion)
{
- var entry = Read().Installations.FirstOrDefault(installation =>
+ RegisteredInstallation? entry = Read().Installations.FirstOrDefault(installation =>
string.Equals(installation.OrchesterVersion, orchesterVersion, StringComparison.Ordinal));
return entry is null ? null : new StellarInstallation(entry.Root);
}
///
- /// Registers an installation for an orchestra version, replacing the one registered for it before.
+ /// Registers an installation for an orchestra version, replacing the one registered for it before and what was
+ /// registered for the same root.
///
public void Register(string orchesterVersion, StellarInstallation installation)
{
if (string.IsNullOrWhiteSpace(orchesterVersion))
throw new ArgumentException("The orchestra version must not be empty", nameof(orchesterVersion));
- var file = Read();
+ InstallationRegistryFile file = Read();
file.Installations.RemoveAll(entry =>
- string.Equals(entry.OrchesterVersion, orchesterVersion, StringComparison.Ordinal));
+ string.Equals(entry.OrchesterVersion, orchesterVersion, StringComparison.Ordinal)
+ || RootComparer.Equals(Normalize(entry.Root), Normalize(installation.Root)));
file.Installations.Add(new RegisteredInstallation
{ OrchesterVersion = orchesterVersion, Root = installation.Root });
Write(file);
@@ -151,8 +156,8 @@ public void Register(string orchesterVersion, StellarInstallation installation)
/// The orchestra versions that were registered for it.
public IReadOnlyList Unregister(StellarInstallation installation)
{
- var file = Read();
- var removed = file.Installations
+ InstallationRegistryFile file = Read();
+ List removed = file.Installations
.Where(entry => RootComparer.Equals(Normalize(entry.Root), Normalize(installation.Root)))
.ToList();
@@ -182,7 +187,8 @@ private void Write(InstallationRegistryFile file)
// Nothing registered: the registry leaves nothing behind, and an empty folder goes with it
Delete(File);
Delete(MSBuildFile);
- if (System.IO.Directory.Exists(Directory) && !System.IO.Directory.EnumerateFileSystemEntries(Directory).Any())
+ if (System.IO.Directory.Exists(Directory) &&
+ !System.IO.Directory.EnumerateFileSystemEntries(Directory).Any())
System.IO.Directory.Delete(Directory);
return;
}
@@ -198,13 +204,14 @@ internal static string RenderMSBuild(InstallationRegistryFile file)
{
var builder = new StringBuilder();
builder.AppendLine("");
- builder.AppendLine($" ");
+ builder.AppendLine(
+ $" ");
builder.AppendLine(" ");
- foreach (var entry in file.Installations)
+ foreach (RegisteredInstallation entry in file.Installations)
{
- var version = SecurityElement.Escape(entry.OrchesterVersion);
- var root = SecurityElement.Escape(entry.Root.TrimEnd('/', '\\') + Path.DirectorySeparatorChar);
+ string version = SecurityElement.Escape(entry.OrchesterVersion);
+ string root = SecurityElement.Escape(entry.Root.TrimEnd('/', '\\') + Path.DirectorySeparatorChar);
builder.AppendLine(
$" {root}");
}
diff --git a/SDK/src/Stellar.Tools/Environment/StellarVersions.cs b/SDK/src/Stellar.Tools/Environment/StellarVersions.cs
index a2a4d01..61edc4d 100644
--- a/SDK/src/Stellar.Tools/Environment/StellarVersions.cs
+++ b/SDK/src/Stellar.Tools/Environment/StellarVersions.cs
@@ -1,6 +1,7 @@
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
+
using Stellar.Tools.Diagnostics;
namespace Stellar.Tools.Environment;
@@ -57,9 +58,31 @@ public static class StellarVersions
///
public static string SchemasUri => Get("StellarSchemasUri");
+ ///
+ /// Gets the address of the docs site, ending with a slash: a page of a project is
+ /// {DocsUri}{project}/{page}.
+ ///
+ public static string DocsUri => Get("StellarDocsUri");
+
+ /// Gets the project of the core on the docs site.
+ public static string DocsProject => Get("StellarDocsProject");
+
+ /// Gets the project of the whole engine on the docs site: the guide, the core and every module.
+ public static string EngineDocsProject => Get("StellarEngineDocsProject");
+
+ ///
+ /// Gets the address of a page of a project on the docs site.
+ ///
+ /// The project, for example .
+ /// The page: its path in Docs/ without .md; empty for the home of the project.
+ public static string DocsPage(string project, string page = "")
+ {
+ return DocsUri + project + (string.IsNullOrEmpty(page) ? string.Empty : "/" + page.TrimStart('/'));
+ }
+
private static string Get(string key)
{
- return Metadata.TryGetValue(key, out var value)
+ return Metadata.TryGetValue(key, out string? value)
? value
: throw new ToolException($"{key} is missing from the assembly metadata of Stellar.Tools");
}
diff --git a/SDK/src/Stellar.Tools/Installation/EngineInstaller.cs b/SDK/src/Stellar.Tools/Installation/EngineInstaller.cs
index 960e093..51d5cc2 100644
--- a/SDK/src/Stellar.Tools/Installation/EngineInstaller.cs
+++ b/SDK/src/Stellar.Tools/Installation/EngineInstaller.cs
@@ -1,5 +1,6 @@
using System.Collections.Generic;
using System.IO;
+
using Stellar.Kernel.Configuration.Manifest;
using Stellar.Tools.Diagnostics;
using Stellar.Tools.Environment;
@@ -41,7 +42,7 @@ public static void Install(StellarInstallation installation, IToolLogger logger,
throw new ToolException(
$"{installation.Root} is not a checkout of StellarEngine-Core: the root of an installation is the core itself");
- foreach (var directory in new[]
+ foreach (string directory in new[]
{
installation.Modules, installation.Packages, installation.Manifests, installation.Config,
installation.Tools, installation.ResourceCompilers, installation.Projects
diff --git a/SDK/src/Stellar.Tools/Marks/MarkCatalog.cs b/SDK/src/Stellar.Tools/Marks/MarkCatalog.cs
new file mode 100644
index 0000000..4b46063
--- /dev/null
+++ b/SDK/src/Stellar.Tools/Marks/MarkCatalog.cs
@@ -0,0 +1,132 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Text.RegularExpressions;
+
+using Stellar.Tools.Diagnostics;
+using Stellar.Tools.Environment;
+
+namespace Stellar.Tools.Marks;
+
+///
+/// How far code with a mark may go.
+///
+public enum MarkLevel
+{
+ /// Anywhere: the mark only tells something.
+ Info,
+
+ /// Into commits, but not into a release.
+ Release,
+
+ /// Nowhere: not even into a commit.
+ Commit
+}
+
+///
+/// What is about to happen to the code.
+///
+public enum MarkStage
+{
+ /// A commit or a push.
+ Commit,
+
+ /// A release, or a snapshot of the mirror.
+ Release
+}
+
+///
+/// A kind of marks.
+///
+public sealed class MarkKind
+{
+ ///
+ /// Gets or sets how far code with such a mark may go.
+ ///
+ public MarkLevel Level { get; set; }
+
+ ///
+ /// Gets or sets what the mark means.
+ ///
+ public string Description { get; set; } = string.Empty;
+}
+
+///
+/// The kinds of marks: those of the engine (Shared/Marks/marks.json) and those of the machine
+/// (config/marks.json, never committed), which win.
+///
+/// A mark of a kind nobody knows is stopped at every stage: a typing error, or a kind of another machine.
+public sealed class MarkCatalog
+{
+ ///
+ /// The file of the kinds, in Shared/Marks and in config.
+ ///
+ public const string FileName = "marks.json";
+
+ private static readonly Regex Name = new("^[A-Z][A-Z0-9_-]*$", RegexOptions.CultureInvariant);
+
+ private readonly Dictionary _kinds = new(StringComparer.Ordinal);
+
+ ///
+ /// Gets the kinds, by name.
+ ///
+ public IReadOnlyDictionary Kinds => _kinds;
+
+ ///
+ /// Reads the kinds of an installation.
+ ///
+ /// The root of the installation.
+ /// The kinds.
+ /// Thrown if there is no file of the engine, or a file is malformed.
+ public static MarkCatalog Load(string root)
+ {
+ var catalog = new MarkCatalog();
+ catalog.Add(Path.Combine(root, "Shared", "Marks", FileName));
+
+ string own = Path.Combine(root, "config", FileName);
+ if (File.Exists(own)) catalog.Add(own);
+ return catalog;
+ }
+
+ ///
+ /// Finds the root of the installation a directory lies in.
+ ///
+ /// The directory.
+ /// The root, or null.
+ public static string? FindRoot(string directory)
+ {
+ for (var current = new DirectoryInfo(directory); current is not null; current = current.Parent)
+ if (File.Exists(Path.Combine(current.FullName, "Shared", "Marks", FileName)))
+ return current.FullName;
+
+ return null;
+ }
+
+ ///
+ /// Whether a mark stops the code.
+ ///
+ /// The name of the mark.
+ /// What is about to happen.
+ /// true if the code must not go on.
+ public bool Stops(string name, MarkStage stage)
+ {
+ if (!_kinds.TryGetValue(name, out MarkKind? kind)) return true;
+ return kind.Level == MarkLevel.Commit || (kind.Level == MarkLevel.Release && stage == MarkStage.Release);
+ }
+
+ private void Add(string path)
+ {
+ foreach (KeyValuePair pair in StellarJson.Read(path).Marks)
+ {
+ if (!Name.IsMatch(pair.Key))
+ throw new ToolException(
+ $"'{pair.Key}' in {path} is not the name of a mark: capital letters, digits, '-' and '_'");
+ _kinds[pair.Key] = pair.Value;
+ }
+ }
+
+ private sealed class MarkFile
+ {
+ public Dictionary Marks { get; set; } = new();
+ }
+}
diff --git a/SDK/src/Stellar.Tools/Marks/MarkRepository.cs b/SDK/src/Stellar.Tools/Marks/MarkRepository.cs
new file mode 100644
index 0000000..d815590
--- /dev/null
+++ b/SDK/src/Stellar.Tools/Marks/MarkRepository.cs
@@ -0,0 +1,217 @@
+using System;
+using System.Collections.Generic;
+using System.Diagnostics;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+using Stellar.Tools.Diagnostics;
+
+namespace Stellar.Tools.Marks;
+
+///
+/// The marks of a git repository, and the hooks that check them.
+///
+public sealed class MarkRepository
+{
+ private const string HookMark = "# stellar marks";
+ private static readonly string[] HookNames = ["pre-commit", "pre-merge-commit", "pre-push"];
+
+ private MarkRepository(string root)
+ {
+ Root = root;
+ }
+
+ ///
+ /// Gets the folder of the repository.
+ ///
+ public string Root { get; }
+
+ ///
+ /// Opens the repository a directory lies in.
+ ///
+ /// The directory.
+ /// The repository.
+ /// Thrown if there is none.
+ public static MarkRepository Open(string directory)
+ {
+ return new MarkRepository(Path.GetFullPath(Git(directory, "rev-parse", "--show-toplevel").Trim()));
+ }
+
+ ///
+ /// Opens the core of an installation and every module and tool that is a repository.
+ ///
+ /// The root of the installation.
+ /// The repositories, the core first.
+ public static IReadOnlyList OpenAll(string root)
+ {
+ List repositories = [Open(root)];
+
+ foreach (string area in new[] { "modules", "tools" }.Select(area => Path.Combine(root, area))
+ .Where(Directory.Exists))
+ foreach (string directory in Directory.GetDirectories(area).OrderBy(path => path, StringComparer.Ordinal))
+ // A file, not a folder, in a worktree
+ if (Directory.Exists(Path.Combine(directory, ".git")) || File.Exists(Path.Combine(directory, ".git")))
+ repositories.Add(Open(directory));
+
+ return repositories;
+ }
+
+ ///
+ /// Finds the marks of the files in the folder, the ignored ones left out.
+ ///
+ /// The marks.
+ public IReadOnlyList ScanFiles()
+ {
+ return Split(Git(Root, "ls-files", "-z", "--cached", "--others", "--exclude-standard"))
+ .Where(MarkScanner.Knows)
+ .Distinct()
+ .Where(file => File.Exists(Path.Combine(Root, file)))
+ .SelectMany(file => MarkScanner.Scan(file, File.ReadAllText(Path.Combine(Root, file))))
+ .ToList();
+ }
+
+ ///
+ /// Finds the marks of what the next commit changes, as it will be committed.
+ ///
+ /// The marks, the old ones of the changed files too.
+ public IReadOnlyList ScanStaged()
+ {
+ return Split(Git(Root, "diff", "--cached", "--name-only", "-z", "--diff-filter=ACMRT", "--no-ext-diff"))
+ .Where(MarkScanner.Knows)
+ .SelectMany(file => MarkScanner.Scan(file, Git(Root, "show", ":" + file)))
+ .ToList();
+ }
+
+ ///
+ /// Finds the marks of a commit.
+ ///
+ /// The commit.
+ /// The marks.
+ public IReadOnlyList ScanRevision(string revision)
+ {
+ string commit = Git(Root, "rev-parse", "--verify", "--end-of-options", revision + "^{commit}").Trim();
+ return Split(Git(Root, "ls-tree", "-r", "-z", "--name-only", "--full-tree", commit))
+ .Where(MarkScanner.Knows)
+ .Where(new HashSet(FilesWithMarks(commit), StringComparer.Ordinal).Contains)
+ .SelectMany(file => MarkScanner.Scan(file, Git(Root, "show", commit + ":" + file)))
+ .ToList();
+ }
+
+ ///
+ /// Puts in the hooks that check the marks of every commit, merge and push.
+ ///
+ /// The hooks written.
+ /// Thrown if the repository has a hook of somebody else: it is left alone.
+ public IReadOnlyList InstallHooks()
+ {
+ string hooks = HooksDirectory();
+ Dictionary paths = HookNames.ToDictionary(name => name, name => Path.Combine(hooks, name));
+
+ string? foreign = paths.Values.FirstOrDefault(path => File.Exists(path) && !IsOurs(path));
+ if (foreign is not null)
+ throw new ToolException(
+ $"{foreign} is not a hook of 'stellar marks': add 'stellar marks check' to it by hand");
+
+ Directory.CreateDirectory(hooks);
+ foreach (KeyValuePair pair in paths)
+ {
+ string what = pair.Key == "pre-push" ? "--revision HEAD" : "--staged";
+ // A command that is missing or fails stops the commit too: nothing goes unchecked by accident
+ File.WriteAllText(pair.Value,
+ $"#!/bin/sh\n{HookMark}\nstellar marks check {what} || {{\n echo \"Stopped by the marks of the code (stellar marks check {what})\" >&2\n exit 1\n}}\n");
+#if NET
+ if (!OperatingSystem.IsWindows())
+ File.SetUnixFileMode(pair.Value,
+ File.GetUnixFileMode(pair.Value) | UnixFileMode.UserExecute | UnixFileMode.GroupExecute |
+ UnixFileMode.OtherExecute);
+#endif
+ }
+
+ return paths.Values.ToList();
+ }
+
+ ///
+ /// Takes the hooks out, only those made.
+ ///
+ /// The hooks removed.
+ public IReadOnlyList RemoveHooks()
+ {
+ string hooks = HooksDirectory();
+ List removed = HookNames.Select(name => Path.Combine(hooks, name))
+ .Where(path => File.Exists(path) && IsOurs(path)).ToList();
+ removed.ForEach(File.Delete);
+ return removed;
+ }
+
+ private static bool IsOurs(string path)
+ {
+ return File.ReadAllText(path).Contains(HookMark);
+ }
+
+ private string HooksDirectory()
+ {
+ return Path.GetFullPath(Path.Combine(Root, Git(Root, "rev-parse", "--git-path", "hooks").Trim()));
+ }
+
+ // git grep ends with 1 when it finds nothing
+ private IEnumerable FilesWithMarks(string commit)
+ {
+ string prefix = commit + ":";
+ return Split(Git(Root, [0, 1], "grep", "-l", "-z", "-I", "-F", "--full-name", "-e", "#<", commit))
+ .Select(entry =>
+ entry.StartsWith(prefix, StringComparison.Ordinal) ? entry.Substring(prefix.Length) : entry);
+ }
+
+ private static IEnumerable Split(string output)
+ {
+ return output.Split(['\0'], StringSplitOptions.RemoveEmptyEntries);
+ }
+
+ private static string Git(string directory, params string[] arguments)
+ {
+ return Git(directory, [0], arguments);
+ }
+
+ private static string Git(string directory, int[] successes, params string[] arguments)
+ {
+ var start = new ProcessStartInfo("git", string.Join(" ", arguments.Select(Quote)))
+ {
+ WorkingDirectory = directory,
+ UseShellExecute = false,
+ CreateNoWindow = true,
+ RedirectStandardOutput = true,
+ RedirectStandardError = true,
+ StandardOutputEncoding = new UTF8Encoding(false),
+ StandardErrorEncoding = new UTF8Encoding(false)
+ };
+
+ Process process;
+ try
+ {
+ process = Process.Start(start)!;
+ }
+ catch (System.ComponentModel.Win32Exception exception)
+ {
+ throw new ToolException("git was not found", exception);
+ }
+
+ using (process)
+ {
+ Task error = Task.Run(() => process.StandardError.ReadToEnd());
+ string output = process.StandardOutput.ReadToEnd();
+ process.WaitForExit();
+
+ return successes.Contains(process.ExitCode)
+ ? output
+ : throw new ToolException(
+ $"git {string.Join(" ", arguments)} in {directory} failed: {error.Result.Trim()}");
+ }
+ }
+
+ private static string Quote(string argument)
+ {
+ return "\"" + argument.Replace("\"", "\\\"") + "\"";
+ }
+}
diff --git a/SDK/src/Stellar.Tools/Marks/MarkScanner.cs b/SDK/src/Stellar.Tools/Marks/MarkScanner.cs
new file mode 100644
index 0000000..d0fec36
--- /dev/null
+++ b/SDK/src/Stellar.Tools/Marks/MarkScanner.cs
@@ -0,0 +1,128 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text.RegularExpressions;
+
+namespace Stellar.Tools.Marks;
+
+///
+/// A mark found in a file.
+///
+/// The file.
+/// The line, from 1.
+/// The name of the mark.
+/// The line it stands in.
+public sealed record Mark(string File, int Line, string Name, string Text);
+
+///
+/// Finds marks in the comments of sources: #<NAME>, capital letters, digits, '-' and '_'.
+///
+///
+/// It knows comments, not languages: what looks like the start of a comment inside a string counts as one, so a mark
+/// may be found where there is none, but is never missed. Files of other kinds have no comments and no marks.
+///
+public static class MarkScanner
+{
+ private sealed class Style
+ {
+ public Style(string? line, string? open, string? close, params string[] extensions)
+ {
+ Line = line;
+ Open = open;
+ Close = close;
+ Extensions = extensions;
+ }
+
+ public string? Line { get; }
+ public string? Open { get; }
+ public string? Close { get; }
+ public string[] Extensions { get; }
+ }
+
+ private static readonly Regex Pattern = new("#<([A-Z][A-Z0-9_-]*)>", RegexOptions.CultureInvariant);
+
+ private static readonly Style[] Styles =
+ {
+ new("//", "/*", "*/", ".cs", ".c", ".cc", ".cpp", ".cxx", ".h", ".hh", ".hpp", ".hxx", ".inl", ".ixx", ".hlsl",
+ ".hlsli", ".glsl", ".vert", ".frag", ".comp", ".js", ".ts", ".css", ".rc"),
+ new("#", "<#", "#>", ".ps1", ".psm1", ".psd1"),
+ new("#", null, null, ".yml", ".yaml", ".sh", ".py", ".toml", ".editorconfig", ".gitignore", ".gitattributes"),
+ new(null, "", ".xml", ".csproj", ".vcxproj", ".props", ".targets", ".filters", ".config", ".md",
+ ".html", ".xaml", ".axaml", ".svg", ".resx")
+ };
+
+ private static readonly Dictionary ByExtension =
+ Styles.SelectMany(style => style.Extensions.Select(extension => (extension, style)))
+ .ToDictionary(pair => pair.extension, pair => pair.style, StringComparer.OrdinalIgnoreCase);
+
+ ///
+ /// Whether a file may hold marks.
+ ///
+ /// The file.
+ /// true if its comments are known.
+ public static bool Knows(string file)
+ {
+ return ByExtension.ContainsKey(Path.GetExtension(file));
+ }
+
+ ///
+ /// Finds the marks of a text.
+ ///
+ /// The file the text is of: its extension tells the comments.
+ /// The text.
+ /// The marks, in order.
+ public static IReadOnlyList Scan(string file, string text)
+ {
+ List marks = new();
+ if (!ByExtension.TryGetValue(Path.GetExtension(file), out Style? style)) return marks;
+
+ bool inBlock = false;
+ int number = 0;
+ foreach (string line in text.Split('\n'))
+ {
+ number++;
+ // The comments of the line, as ranges: a mark counts if it starts in one
+ List<(int Start, int End)> ranges = Comments(line, style, ref inBlock);
+ foreach (Match match in Pattern.Matches(line))
+ if (ranges.Any(range => match.Index >= range.Start && match.Index < range.End))
+ marks.Add(new Mark(file, number, match.Groups[1].Value, line.Trim()));
+ }
+
+ return marks;
+ }
+
+ private static List<(int Start, int End)> Comments(string line, Style style, ref bool inBlock)
+ {
+ List<(int Start, int End)> ranges = new();
+ int position = 0;
+
+ while (position < line.Length)
+ {
+ if (inBlock)
+ {
+ int close = line.IndexOf(style.Close!, position, StringComparison.Ordinal);
+ ranges.Add((position, close < 0 ? line.Length : close));
+ if (close < 0) return ranges;
+ inBlock = false;
+ position = close + style.Close!.Length;
+ continue;
+ }
+
+ int open = style.Open is null ? -1 : line.IndexOf(style.Open, position, StringComparison.Ordinal);
+ int single = style.Line is null ? -1 : line.IndexOf(style.Line, position, StringComparison.Ordinal);
+
+ if (single >= 0 && (open < 0 || single < open))
+ {
+ ranges.Add((single, line.Length));
+ return ranges;
+ }
+
+ if (open < 0) return ranges;
+ inBlock = true;
+ position = open + style.Open!.Length;
+ }
+
+ return ranges;
+ }
+}
diff --git a/SDK/src/Stellar.Tools/Modules/ModuleScaffolder.cs b/SDK/src/Stellar.Tools/Modules/ModuleScaffolder.cs
index 6379e57..166a883 100644
--- a/SDK/src/Stellar.Tools/Modules/ModuleScaffolder.cs
+++ b/SDK/src/Stellar.Tools/Modules/ModuleScaffolder.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
+
using Stellar.Kernel.Modules;
using Stellar.Tools.Diagnostics;
using Stellar.Tools.Environment;
@@ -22,7 +23,8 @@ public sealed record ModuleRequest(
ModuleLevel Level,
string? Description,
string Template,
- string? Directory = null);
+ string? Directory = null
+);
///
/// Creates modules from Shared/Templates/Modules, and registers them with the installation.
@@ -80,12 +82,12 @@ public string Create(ModuleRequest request)
if (Array.IndexOf(ModuleResolver.CoreModules, request.Id) >= 0)
throw new ToolException($"{request.Id} is part of the core");
- var template = Path.Combine(TemplatesDirectory, request.Template);
+ string template = Path.Combine(TemplatesDirectory, request.Template);
if (!Directory.Exists(template))
throw new ToolException(
$"Unknown module template '{request.Template}'. Available: {string.Join(", ", ListTemplates())}");
- var directory = Path.GetFullPath(request.Directory ?? Path.Combine(_installation.Modules, request.Id));
+ string directory = Path.GetFullPath(request.Directory ?? Path.Combine(_installation.Modules, request.Id));
_renderer.Render(template, directory, Values(request));
ModuleFeed.EnsureReachable(_installation, directory, _logger);
@@ -99,10 +101,10 @@ public string Create(ModuleRequest request)
///
public Dictionary Values(ModuleRequest request)
{
- var shortName = request.Id.StartsWith("Stellar.", StringComparison.Ordinal)
+ string shortName = request.Id.StartsWith("Stellar.", StringComparison.Ordinal)
? request.Id.Substring("Stellar.".Length)
: request.Id;
- var description = request.Description ?? $"The {shortName} module of StellarEngine";
+ string description = request.Description ?? $"The {shortName} module of StellarEngine";
return new Dictionary
{
@@ -121,6 +123,10 @@ public Dictionary Values(ModuleRequest request)
["CoreSiteUri"] = StellarVersions.SiteUri,
["EngineSiteUri"] = StellarVersions.EngineSiteUri,
["ModuleSiteUri"] = new Uri(new Uri(StellarVersions.SiteUri), "/" + request.Id + "/").AbsoluteUri,
+ // The project of the module on the docs site (prometheus.json): a guess the author changes when the card
+ // of the module on the site is named otherwise
+ ["ModuleDocsProject"] = "stellar-" + shortName.ToLowerInvariant().Replace(".", "-"),
+ ["EngineDocsProject"] = StellarVersions.EngineDocsProject,
["OrchesterVersion"] = StellarVersions.Orchester,
["StellarRoot"] = _installation.Root,
["StellarSchemasUri"] = StellarVersions.SchemasUri
diff --git a/SDK/src/Stellar.Tools/Modules/ModuleSynchronizer.cs b/SDK/src/Stellar.Tools/Modules/ModuleSynchronizer.cs
index f64a5e9..2604dcc 100644
--- a/SDK/src/Stellar.Tools/Modules/ModuleSynchronizer.cs
+++ b/SDK/src/Stellar.Tools/Modules/ModuleSynchronizer.cs
@@ -1,5 +1,7 @@
using System.Collections.Generic;
using System.Linq;
+
+using Stellar.Kernel.Configuration.Manifest;
using Stellar.Tools.Diagnostics;
using Stellar.Tools.Environment;
using Stellar.Tools.Manifests;
@@ -27,17 +29,17 @@ public static class ModuleSynchronizer
/// Thrown if the modules break the rules.
public static ModuleSet Load(StellarInstallation installation)
{
- var manifest = EngineManifestStore.Load(installation.EngineManifest);
- var resolution = ModuleResolver.Resolve(installation, manifest);
+ EngineManifest manifest = EngineManifestStore.Load(installation.EngineManifest);
+ ModuleResolution resolution = ModuleResolver.Resolve(installation, manifest);
if (!resolution.IsValid)
throw Failure(resolution.Errors);
- var graph = ModuleGraph.Analyze(resolution.Modules.Select(module => module.Descriptor));
+ ModuleGraphResult graph = ModuleGraph.Analyze(resolution.Modules.Select(module => module.Descriptor));
if (!graph.IsValid)
throw Failure(graph.Errors);
- var byId = resolution.Modules.ToDictionary(module => module.Id);
+ Dictionary byId = resolution.Modules.ToDictionary(module => module.Id);
return new ModuleSet(resolution, graph.LoadOrder.Select(descriptor => byId[descriptor.Id]).ToList());
}
@@ -50,15 +52,15 @@ public static ModuleSet Load(StellarInstallation installation)
/// Thrown if the modules break the rules. Nothing is written then.
public static ModuleSet Synchronize(StellarInstallation installation, IToolLogger logger)
{
- var set = Load(installation);
+ ModuleSet set = Load(installation);
- foreach (var warning in set.Resolution.Warnings)
+ foreach (string warning in set.Resolution.Warnings)
logger.Warning(warning);
- var catalogChanged =
+ bool catalogChanged =
FileWriter.WriteAllText(installation.ModuleCatalog, ModuleCatalogGenerator.Render(set.LoadOrder));
- var lockChanged = FileWriter.WriteAllText(installation.ModuleLock,
- StellarJson.Serialize(new ModuleLockFile(set.LoadOrder)));
+ bool lockChanged =
+ FileWriter.WriteAllText(installation.ModuleLock, StellarJson.Serialize(new ModuleLockFile(set.LoadOrder)));
if (catalogChanged || lockChanged)
logger.Info($"Module catalog updated: {set.LoadOrder.Count} module(s), {installation.ModuleCatalog}");
diff --git a/SDK/tests/Stellar.Tools.Tests/InstallationTests.cs b/SDK/tests/Stellar.Tools.Tests/InstallationTests.cs
index bc4ca5d..353a529 100644
--- a/SDK/tests/Stellar.Tools.Tests/InstallationTests.cs
+++ b/SDK/tests/Stellar.Tools.Tests/InstallationTests.cs
@@ -1,4 +1,5 @@
using System.Diagnostics;
+
using Stellar.Tools.Diagnostics;
using Stellar.Tools.Environment;
using Stellar.Tools.Installation;
@@ -35,8 +36,9 @@ public void Register_KeepsOneInstallationPerOrchestra_AndWritesTheMSBuildView()
registry.Find("0.8.0")!.Root.Should().Be(second.Root);
registry.Find("0.9.0")!.Root.Should().Be(other.Root);
- var props = File.ReadAllText(registry.MSBuildFile);
- props.Should().Contain("'$(StellarOrchesterVersion)' == '0.8.0'\">" + second.Root + Path.DirectorySeparatorChar);
+ string props = File.ReadAllText(registry.MSBuildFile);
+ props.Should()
+ .Contain("'$(StellarOrchesterVersion)' == '0.8.0'\">" + second.Root + Path.DirectorySeparatorChar);
props.Should().Contain("'$(StellarOrchesterVersion)' == '0.9.0'\">" + other.Root + Path.DirectorySeparatorChar);
props.Should().NotContain(first.Root + Path.DirectorySeparatorChar + "<");
}
@@ -49,9 +51,10 @@ public void Unregister_RemovesEveryVersionOfTheRoot_AndTheLastOneLeavesNothing()
var installation = new StellarInstallation(Path.Combine(directory.Path, "engine"));
var other = new StellarInstallation(Path.Combine(directory.Path, "other"));
- registry.Register("0.8.0", installation);
- registry.Register("0.9.0", installation);
registry.Register("1.0.0", other);
+ File.WriteAllText(registry.File, File.ReadAllText(registry.File).Replace("\"Installations\": [",
+ $"\"Installations\": [ {{ \"OrchesterVersion\": \"0.8.0\", \"Root\": {Json(installation.Root)} }}, " +
+ $"{{ \"OrchesterVersion\": \"0.9.0\", \"Root\": {Json(installation.Root)} }},"));
registry.Unregister(installation).Should().BeEquivalentTo("0.8.0", "0.9.0");
registry.List().Should().ContainSingle().Which.OrchesterVersion.Should().Be("1.0.0");
@@ -60,6 +63,27 @@ public void Unregister_RemovesEveryVersionOfTheRoot_AndTheLastOneLeavesNothing()
Directory.Exists(registry.Directory).Should().BeFalse();
}
+ private static string Json(string text)
+ {
+ return System.Text.Json.JsonSerializer.Serialize(text);
+ }
+
+ [Fact]
+ public void Register_ANewOrchestraInTheSameRoot_ReplacesTheOldOne()
+ {
+ using var directory = new TempDirectory();
+ var registry = new InstallationRegistry(Path.Combine(directory.Path, "home"));
+ var installation = new StellarInstallation(Path.Combine(directory.Path, "engine"));
+ var other = new StellarInstallation(Path.Combine(directory.Path, "other"));
+
+ registry.Register("0.9.0", other);
+ registry.Register("0.10.0", installation);
+ registry.Register("0.11.0", installation);
+
+ registry.List().Select(entry => $"{entry.OrchesterVersion} {entry.Root}")
+ .Should().Equal($"0.11.0 {installation.Root}", $"0.9.0 {other.Root}");
+ }
+
[Fact]
public void TryLocate_FindsTheInstallationOfThisOrchestraInTheRegistry()
{
@@ -78,18 +102,19 @@ public void TryLocate_FindsTheInstallationOfThisOrchestraInTheRegistry()
public class UninstallerTests
{
private static (StellarInstallation Installation, InstallationRegistry Registry, string Cache) Installed(
- TempDirectory directory)
+ TempDirectory directory
+ )
{
directory.Write("Shared/Templates/Installation/config/Stellar.Sdk.props", "settings {{OrchesterVersion}}");
directory.Write("Shared/Templates/Installation/projects/Directory.Build.props", "isolation");
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
var registry = new InstallationRegistry(Path.Combine(directory.Path, "home"));
EngineInstaller.Install(installation, NullToolLogger.Instance, registry);
directory.Write("packages/Stellar.Kernel.0.8.0.nupkg");
directory.Write("packages/Stellar.Sdk.0.4.0-preview.1.nupkg");
- var cache = Path.Combine(directory.Path, "nuget");
+ string cache = Path.Combine(directory.Path, "nuget");
directory.Write("nuget/stellar.kernel/0.8.0/stellar.kernel.nuspec");
directory.Write("nuget/stellar.kernel/0.7.0/stellar.kernel.nuspec");
directory.Write("nuget/stellar.sdk/0.4.0-preview.1/stellar.sdk.nuspec");
@@ -103,7 +128,7 @@ public void Uninstall_RefusesADirectoryThatIsNotTheCore()
{
using var directory = new TempDirectory();
- var action = () => EngineUninstaller.Uninstall(new StellarInstallation(directory.Path),
+ Func action = () => EngineUninstaller.Uninstall(new StellarInstallation(directory.Path),
NullToolLogger.Instance, new UninstallOptions());
action.Should().Throw().WithMessage("*not a checkout of StellarEngine-Core*");
@@ -113,12 +138,12 @@ public void Uninstall_RefusesADirectoryThatIsNotTheCore()
public void Uninstall_LeavesAPlainCheckout_AndNeverTouchesTheContentOfTheUser()
{
using var directory = new TempDirectory();
- var (installation, registry, cache) = Installed(directory);
+ (StellarInstallation installation, InstallationRegistry registry, string cache) = Installed(directory);
directory.Write("modules/Stellar.FileSystem/Stellar.FileSystem.stellar.module", "{}");
directory.Write("projects/MyGame/MyGame.csproj", "");
directory.Write("tools/StellarEditor/README.md");
- var report = EngineUninstaller.Uninstall(installation, NullToolLogger.Instance,
+ UninstallReport report = EngineUninstaller.Uninstall(installation, NullToolLogger.Instance,
new UninstallOptions { Registry = registry, PackageCache = cache });
// The machine forgot it
@@ -132,7 +157,7 @@ public void Uninstall_LeavesAPlainCheckout_AndNeverTouchesTheContentOfTheUser()
Directory.Exists(Path.Combine(cache, "newtonsoft.json", "13.0.3")).Should().BeTrue();
// What the installer made is gone
- foreach (var path in new[]
+ foreach (string path in new[]
{
installation.Packages, installation.Manifests, installation.Config,
Path.Combine(installation.Modules, "Directory.Build.props"),
@@ -153,12 +178,12 @@ public void Uninstall_LeavesAPlainCheckout_AndNeverTouchesTheContentOfTheUser()
public void Uninstall_RemovesEmptyFoldersOfTheInstaller()
{
using var directory = new TempDirectory();
- var (installation, registry, cache) = Installed(directory);
+ (StellarInstallation installation, InstallationRegistry registry, string cache) = Installed(directory);
EngineUninstaller.Uninstall(installation, NullToolLogger.Instance,
new UninstallOptions { Registry = registry, PackageCache = cache });
- foreach (var path in new[] { installation.Modules, installation.Projects, installation.Tools })
+ foreach (string path in new[] { installation.Modules, installation.Projects, installation.Tools })
Directory.Exists(path).Should().BeFalse(path);
}
@@ -166,11 +191,11 @@ public void Uninstall_RemovesEmptyFoldersOfTheInstaller()
public void Uninstall_KeepsEditedFiles_UnlessAll()
{
using var directory = new TempDirectory();
- var (installation, registry, _) = Installed(directory);
- var settings = Path.Combine(installation.Config, "Stellar.Sdk.props");
+ (StellarInstallation installation, InstallationRegistry registry, _) = Installed(directory);
+ string settings = Path.Combine(installation.Config, "Stellar.Sdk.props");
File.WriteAllText(settings, "my settings");
- var report = EngineUninstaller.Uninstall(installation, NullToolLogger.Instance,
+ UninstallReport report = EngineUninstaller.Uninstall(installation, NullToolLogger.Instance,
new UninstallOptions { Registry = registry });
File.ReadAllText(settings).Should().Be("my settings");
@@ -186,9 +211,9 @@ public void Uninstall_KeepsEditedFiles_UnlessAll()
public void Uninstall_DryRun_ChangesNothing()
{
using var directory = new TempDirectory();
- var (installation, registry, cache) = Installed(directory);
+ (StellarInstallation installation, InstallationRegistry registry, string cache) = Installed(directory);
- var report = EngineUninstaller.Uninstall(installation, NullToolLogger.Instance,
+ UninstallReport report = EngineUninstaller.Uninstall(installation, NullToolLogger.Instance,
new UninstallOptions { Registry = registry, PackageCache = cache, DryRun = true });
report.Unregistered.Should().Equal(StellarVersions.Orchester);
@@ -207,16 +232,21 @@ public void Uninstall_RemovesALinkAsALink_NeverWhatItPointsAt()
using var directory = new TempDirectory();
using var outside = new TempDirectory();
- var precious = outside.Write("precious.txt", "keep me");
- var (installation, registry, _) = Installed(directory);
-
- var junction = Path.Combine(installation.Packages, "linked");
- using (var mklink = Process.Start(new ProcessStartInfo("cmd.exe", $"/c mklink /J \"{junction}\" \"{outside.Path}\"")
- { CreateNoWindow = true, UseShellExecute = false }))
+ string precious = outside.Write("precious.txt", "keep me");
+ (StellarInstallation installation, InstallationRegistry registry, _) = Installed(directory);
+
+ string junction = Path.Combine(installation.Packages, "linked");
+ using (Process? mklink = Process.Start(
+ new ProcessStartInfo("cmd.exe", $"/c mklink /J \"{junction}\" \"{outside.Path}\"")
+ { CreateNoWindow = true, UseShellExecute = false }))
+ {
mklink!.WaitForExit();
+ }
+
Directory.Exists(junction).Should().BeTrue("the junction must exist for this test to mean anything");
- EngineUninstaller.Uninstall(installation, NullToolLogger.Instance, new UninstallOptions { Registry = registry });
+ EngineUninstaller.Uninstall(installation, NullToolLogger.Instance,
+ new UninstallOptions { Registry = registry });
Directory.Exists(installation.Packages).Should().BeFalse();
File.ReadAllText(precious).Should().Be("keep me");
diff --git a/SDK/tests/Stellar.Tools.Tests/MarkTests.cs b/SDK/tests/Stellar.Tools.Tests/MarkTests.cs
new file mode 100644
index 0000000..3d2c200
--- /dev/null
+++ b/SDK/tests/Stellar.Tools.Tests/MarkTests.cs
@@ -0,0 +1,198 @@
+using System.Diagnostics;
+
+using Stellar.Tools.Diagnostics;
+using Stellar.Tools.Marks;
+
+namespace Stellar.Tools.Tests;
+
+public class MarkTests
+{
+ // Put together here, or this file would carry the marks itself
+ private static string M(string name)
+ {
+ return "#" + "<" + name + ">";
+ }
+
+ private static string[] Names(string file, string text)
+ {
+ return MarkScanner.Scan(file, text).Select(mark => $"{mark.Line}:{mark.Name}").ToArray();
+ }
+
+ [Fact]
+ public void Scan_FindsMarksInEveryKindOfComment()
+ {
+ Names("a.cs", $"int a; // {M("MVP")}\n/* {M("A1")}\n * {M("B-2")} */ int b;\n/// {M("C_3")}")
+ .Should().Equal("1:MVP", "2:A1", "3:B-2", "4:C_3");
+ Names("a.h", $"/* x */ /* {M("MVP")} */").Should().Equal("1:MVP");
+ Names("a.ps1", $"{M("MVP")}\n<#\n {M("WIP")}\n#>").Should().Equal("1:MVP", "3:WIP");
+ Names("a.yml", $"a: 1 # {M("MVP")}").Should().Equal("1:MVP");
+ Names("a.props", $"\n").Should().Equal("2:MVP", "3:WIP");
+ Names("A.CS", $"// {M("MVP")}\r\n// {M("WIP")}\r\n").Should().Equal("1:MVP", "2:WIP");
+ Names(".gitignore", M("MVP")).Should().Equal("1:MVP");
+ Names("a.cs", $"// {M("MVP")} {M("WIP")}").Should().Equal("1:MVP", "1:WIP");
+ }
+
+ [Fact]
+ public void Scan_LeavesCodeAndOtherFilesAlone()
+ {
+ Names("a.cs", $"var a = \"{M("MVP")}\";").Should().BeEmpty();
+ Names("a.cs", $"/* x */ {M("MVP")}").Should().BeEmpty();
+ Names("a.props", $"
{M("MVP")}
").Should().BeEmpty();
+ Names("a.md", $"text {M("MVP")}").Should().BeEmpty();
+ Names("a.json", $"// {M("MVP")}").Should().BeEmpty();
+ Names("a.cs", $"// {M("mvp")} {M("1A")} {M("")} #< MVP> List").Should().BeEmpty();
+ }
+
+ private static MarkCatalog Catalog(TempDirectory directory, string? own = null)
+ {
+ directory.Write("Shared/Marks/marks.json",
+ """{ "Marks": { "MVP": { "Level": "Info" }, "WIP": { "Level": "Release" }, "STOP": { "Level": "Commit" } } }""");
+ if (own is not null) directory.Write("config/marks.json", own);
+ return MarkCatalog.Load(directory.Path);
+ }
+
+ [Theory]
+ [InlineData("MVP", false, false)]
+ [InlineData("WIP", false, true)]
+ [InlineData("STOP", true, true)]
+ [InlineData("UNKNOWN", true, true)]
+ public void Levels_StopAtTheirStages(string name, bool commit, bool release)
+ {
+ using var directory = new TempDirectory();
+ MarkCatalog catalog = Catalog(directory);
+
+ catalog.Stops(name, MarkStage.Commit).Should().Be(commit);
+ catalog.Stops(name, MarkStage.Release).Should().Be(release);
+ }
+
+ [Fact]
+ public void KindsOfTheMachine_AddAndReplace()
+ {
+ using var directory = new TempDirectory();
+ MarkCatalog catalog = Catalog(directory,
+ """{ "Marks": { "OWN": { "Level": "Commit" }, "WIP": { "Level": "Info" } } }""");
+
+ catalog.Kinds.Keys.Should().BeEquivalentTo("MVP", "WIP", "STOP", "OWN");
+ catalog.Stops("WIP", MarkStage.Release).Should().BeFalse();
+ catalog.Stops("OWN", MarkStage.Commit).Should().BeTrue();
+ }
+
+ [Fact]
+ public void ABadCatalog_IsAnError_NeverAnEmptyOne()
+ {
+ using var directory = new TempDirectory();
+
+ FluentActions.Invoking(() => MarkCatalog.Load(directory.Path)).Should().Throw();
+ FluentActions.Invoking(() => Catalog(directory, """{ "Marks": { "own": {} } }""")).Should()
+ .Throw();
+ FluentActions.Invoking(() => Catalog(directory, """{ "Marks": { "OWN": { "Level": "Nowhere" } } }"""))
+ .Should().Throw();
+ }
+
+ [Fact]
+ public void FindRoot_GoesUp()
+ {
+ using var directory = new TempDirectory();
+ Catalog(directory);
+ directory.Write("modules/Stellar.A/src/a.cs", "");
+
+ MarkCatalog.FindRoot(Path.Combine(directory.Path, "modules", "Stellar.A", "src")).Should().Be(directory.Path);
+ MarkCatalog.FindRoot(Path.GetTempPath()).Should().BeNull();
+ }
+
+ private static string Git(string directory, params string[] arguments)
+ {
+ var start = new ProcessStartInfo("git")
+ { WorkingDirectory = directory, RedirectStandardOutput = true, RedirectStandardError = true };
+ foreach (string argument in (string[])
+ [
+ "-c", "user.name=Tests", "-c", "user.email=tests@localhost", "-c", "commit.gpgsign=false", "-c",
+ "core.hooksPath=.none", .. arguments
+ ])
+ start.ArgumentList.Add(argument);
+ using Process process = Process.Start(start)!;
+ Task error = process.StandardError.ReadToEndAsync();
+ string output = process.StandardOutput.ReadToEnd();
+ process.WaitForExit();
+ return process.ExitCode == 0 ? output : throw new InvalidOperationException(error.Result);
+ }
+
+ [Fact]
+ public void Repository_TellsStagedFromTheFolderAndFromACommit()
+ {
+ using var directory = new TempDirectory();
+ Git(directory.Path, "init", "-q");
+ directory.Write(".gitignore", "/hidden/\n");
+ directory.Write("папка с пробелом/a.cs", $"// {M("MVP")}\n");
+ directory.Write("hidden/b.cs", $"// {M("OWN")}\n");
+ Git(directory.Path, "add", ".");
+ Git(directory.Path, "commit", "-q", "-m", "one");
+
+ directory.Write("папка с пробелом/a.cs", $"// {M("WIP")}\n");
+ Git(directory.Path, "add", ".");
+ directory.Write("папка с пробелом/a.cs", $"// {M("STOP")}\n");
+ directory.Write("new.cs", $"// {M("NEW")}\n");
+
+ MarkRepository repository = MarkRepository.Open(Path.Combine(directory.Path, "папка с пробелом"));
+ repository.ScanRevision("HEAD").Select(mark => mark.Name).Should().Equal("MVP");
+ repository.ScanStaged().Select(mark => mark.Name).Should().Equal("WIP");
+ repository.ScanFiles().Select(mark => mark.Name).Should().BeEquivalentTo("STOP", "NEW");
+ repository.ScanRevision("HEAD").Single().File.Should().Be("папка с пробелом/a.cs");
+ repository.Invoking(it => it.ScanRevision("nowhere")).Should().Throw();
+ }
+
+ [Fact]
+ public void Repository_WithoutMarks_HasNone_AndACommitThatDeletes_IsFine()
+ {
+ using var directory = new TempDirectory();
+ Git(directory.Path, "init", "-q");
+ directory.Write("a.cs", "int a;\n");
+ Git(directory.Path, "add", ".");
+ Git(directory.Path, "commit", "-q", "-m", "one");
+ Git(directory.Path, "rm", "-q", "a.cs");
+
+ MarkRepository repository = MarkRepository.Open(directory.Path);
+ repository.ScanRevision("HEAD").Should().BeEmpty();
+ repository.ScanStaged().Should().BeEmpty();
+ repository.ScanFiles().Should().BeEmpty();
+ }
+
+ [Fact]
+ public void Hooks_AreOurs_OrLeftAlone()
+ {
+ using var directory = new TempDirectory();
+ Git(directory.Path, "init", "-q");
+ MarkRepository repository = MarkRepository.Open(directory.Path);
+
+ repository.InstallHooks().Should().HaveCount(3);
+ repository.InstallHooks().Should().HaveCount(3);
+ repository.RemoveHooks().Should().HaveCount(3);
+ repository.RemoveHooks().Should().BeEmpty();
+
+ directory.Write(".git/hooks/pre-commit", "#!/bin/sh\nexit 0\n");
+ repository.Invoking(it => it.InstallHooks()).Should().Throw();
+ repository.RemoveHooks().Should().BeEmpty();
+ File.Exists(Path.Combine(directory.Path, ".git", "hooks", "pre-commit")).Should().BeTrue();
+ File.Exists(Path.Combine(directory.Path, ".git", "hooks", "pre-push")).Should().BeFalse();
+ }
+
+ [Fact]
+ public void OpenAll_TakesTheCoreAndItsComponents()
+ {
+ using var directory = new TempDirectory();
+ Git(directory.Path, "init", "-q");
+ directory.Write("modules/Stellar.A/a.cs", "");
+ directory.Write("modules/NotARepository/a.cs", "");
+ Git(Path.Combine(directory.Path, "modules", "Stellar.A"), "init", "-q");
+
+ MarkRepository.OpenAll(directory.Path).Select(repository => Path.GetFileName(repository.Root))
+ .Should().Equal(Path.GetFileName(directory.Path), "Stellar.A");
+ }
+
+ [Fact]
+ public void NoRepository_IsAnError()
+ {
+ using var directory = new TempDirectory();
+ FluentActions.Invoking(() => MarkRepository.Open(directory.Path)).Should().Throw();
+ }
+}
diff --git a/SDK/tests/Stellar.Tools.Tests/ModuleTests.cs b/SDK/tests/Stellar.Tools.Tests/ModuleTests.cs
index 0233be9..7f063b2 100644
--- a/SDK/tests/Stellar.Tools.Tests/ModuleTests.cs
+++ b/SDK/tests/Stellar.Tools.Tests/ModuleTests.cs
@@ -22,16 +22,18 @@ public static StellarInstallation Create(TempDirectory directory)
public static StellarInstallation Installed(TempDirectory directory, EngineManifest? manifest = null)
{
- var installation = Create(directory);
+ StellarInstallation installation = Create(directory);
EngineManifestStore.Save(installation.EngineManifest,
manifest ?? new EngineManifest { OrchesterVersion = "0.7.0" });
return installation;
}
- public static string Module(TempDirectory directory, string folder, string id, string json = "",
- bool withProject = true)
+ public static string Module(
+ TempDirectory directory, string folder, string id, string json = "",
+ bool withProject = true
+ )
{
- var body = json.Length == 0 ? string.Empty : ", " + json;
+ string body = json.Length == 0 ? string.Empty : ", " + json;
directory.Write($"{folder}/{id}.stellar.module", $$"""{ "Id": "{{id}}"{{body}} }""");
if (withProject)
@@ -47,7 +49,7 @@ public class ModuleDiscoveryTests
public void Discover_FindsModulesUpToTheDepth_AndNotInsideModules()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A");
FakeCore.Module(directory, "modules/Group/Stellar.B", "Stellar.B");
@@ -55,7 +57,8 @@ public void Discover_FindsModulesUpToTheDepth_AndNotInsideModules()
FakeCore.Module(directory, "modules/One/Two/Stellar.D", "Stellar.D");
FakeCore.Module(directory, "modules/.hidden/Stellar.E", "Stellar.E");
- var found = ModuleDiscovery.Discover(installation, new ModuleDiscoverySettings()).Select(Path.GetFileName);
+ IEnumerable found = ModuleDiscovery.Discover(installation, new ModuleDiscoverySettings())
+ .Select(Path.GetFileName);
found.Should().BeEquivalentTo(["Stellar.A.stellar.module", "Stellar.B.stellar.module"]);
}
@@ -64,7 +67,7 @@ public void Discover_FindsModulesUpToTheDepth_AndNotInsideModules()
public void Discover_CanBeSwitchedOff()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A");
ModuleDiscovery.Discover(installation, new ModuleDiscoverySettings { Enabled = false }).Should().BeEmpty();
@@ -74,9 +77,9 @@ public void Discover_CanBeSwitchedOff()
public void Descriptor_MustBeNamedAfterItsModule()
{
using var directory = new TempDirectory();
- var path = directory.Write("Stellar.A.stellar.module", """{ "Id": "Stellar.B" }""");
+ string path = directory.Write("Stellar.A.stellar.module", """{ "Id": "Stellar.B" }""");
- var action = () => ModuleDescriptorFile.Read(path);
+ Func action = () => ModuleDescriptorFile.Read(path);
action.Should().Throw().WithMessage("*Stellar.B.stellar.module*");
}
@@ -105,10 +108,11 @@ public class ModuleResolverTests
public void Resolve_FillsTheDefaults()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A");
- var module = ModuleResolver.Resolve(installation, new EngineManifest()).Modules.Should().ContainSingle()
+ ResolvedModule module = ModuleResolver.Resolve(installation, new EngineManifest()).Modules.Should()
+ .ContainSingle()
.Subject;
module.Source.Should().Be(ModuleSource.Discovered);
@@ -121,7 +125,7 @@ public void Resolve_FillsTheDefaults()
public void Resolve_TheManifestWinsOverTheDescriptor()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A", """ "Version": "1.0.0", "Level": "CoreModule" """);
var manifest = new EngineManifest
@@ -129,7 +133,7 @@ public void Resolve_TheManifestWinsOverTheDescriptor()
Modules = [new ModuleOverride { Id = "Stellar.A", Version = "2.0.0", Link = ModuleLink.Package }]
};
- var module = ModuleResolver.Resolve(installation, manifest).Modules.Single();
+ ResolvedModule module = ModuleResolver.Resolve(installation, manifest).Modules.Single();
module.Descriptor.Version.Should().Be("2.0.0");
module.Descriptor.Level.Should().Be(ModuleLevel.CoreModule);
@@ -140,13 +144,13 @@ public void Resolve_TheManifestWinsOverTheDescriptor()
public void Resolve_AFolderOfTheManifestWinsOverADiscoveredOne()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A");
- var external = FakeCore.Module(directory, "work/Stellar.A", "Stellar.A");
+ string external = FakeCore.Module(directory, "work/Stellar.A", "Stellar.A");
var manifest = new EngineManifest { Modules = [new ModuleOverride { Id = "Stellar.A", Path = external }] };
- var module = ModuleResolver.Resolve(installation, manifest).Modules.Single();
+ ResolvedModule module = ModuleResolver.Resolve(installation, manifest).Modules.Single();
module.Source.Should().Be(ModuleSource.External);
module.Directory.Should().Be(Path.GetFullPath(external));
@@ -156,13 +160,13 @@ public void Resolve_AFolderOfTheManifestWinsOverADiscoveredOne()
public void Resolve_DisabledModules_AndWhoDependsOnThem()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A", """ "Level": "CoreModule" """);
FakeCore.Module(directory, "modules/Stellar.B", "Stellar.B", """ "Dependencies": ["Stellar.A"] """);
var manifest = new EngineManifest { Modules = [new ModuleOverride { Id = "Stellar.A", Enabled = false }] };
- var resolution = ModuleResolver.Resolve(installation, manifest);
+ ModuleResolution resolution = ModuleResolver.Resolve(installation, manifest);
resolution.Disabled.Should().Equal("Stellar.A");
resolution.Errors.Should().ContainSingle().Which.Should().Contain("turned off");
@@ -172,11 +176,11 @@ public void Resolve_DisabledModules_AndWhoDependsOnThem()
public void Resolve_APackageOnlyModuleNeedsAVersion()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
- var withoutVersion = ModuleResolver.Resolve(installation,
+ ModuleResolution withoutVersion = ModuleResolver.Resolve(installation,
new EngineManifest { Modules = [new ModuleOverride { Id = "Stellar.P" }] });
- var withVersion = ModuleResolver.Resolve(installation,
+ ModuleResolution withVersion = ModuleResolver.Resolve(installation,
new EngineManifest { Modules = [new ModuleOverride { Id = "Stellar.P", Version = "1.0.0" }] });
withoutVersion.Errors.Should().ContainSingle().Which.Should().Contain("Version");
@@ -188,12 +192,12 @@ public void Resolve_APackageOnlyModuleNeedsAVersion()
public void Resolve_RejectsDuplicatesAndTheCore()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
FakeCore.Module(directory, "modules/One/Stellar.A", "Stellar.A");
FakeCore.Module(directory, "modules/Two/Stellar.A", "Stellar.A");
FakeCore.Module(directory, "modules/Stellar.Core", "Stellar.Core");
- var errors = ModuleResolver.Resolve(installation, new EngineManifest()).Errors;
+ IReadOnlyList errors = ModuleResolver.Resolve(installation, new EngineManifest()).Errors;
errors.Should().Contain(error => error.Contains("found twice")).And
.Contain(error => error.Contains("part of the core"));
@@ -203,10 +207,10 @@ public void Resolve_RejectsDuplicatesAndTheCore()
public void Resolve_ImplicitDependenciesAreDropped()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Create(directory);
+ StellarInstallation installation = FakeCore.Create(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A", """ "Dependencies": ["Stellar.Core"] """);
- var resolution = ModuleResolver.Resolve(installation, new EngineManifest());
+ ModuleResolution resolution = ModuleResolver.Resolve(installation, new EngineManifest());
resolution.Modules.Single().Descriptor.Dependencies.Should().BeEmpty();
resolution.Warnings.Should().ContainSingle().Which.Should().Contain("implicit");
@@ -219,13 +223,13 @@ public class ModuleSynchronizerTests
public void Synchronize_WritesTheCatalog_ThatTellsAModuleWhoItIs()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Installed(directory);
+ StellarInstallation installation = FakeCore.Installed(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A", """ "Level": "CoreModule", "Version": "1.2.3" """);
FakeCore.Module(directory, "modules/Stellar.B", "Stellar.B",
""" "Dependencies": ["Stellar.A"], "Description": "B & co" """);
- var set = ModuleSynchronizer.Synchronize(installation, NullToolLogger.Instance);
- var catalog = File.ReadAllText(installation.ModuleCatalog);
+ ModuleSet set = ModuleSynchronizer.Synchronize(installation, NullToolLogger.Instance);
+ string catalog = File.ReadAllText(installation.ModuleCatalog);
set.LoadOrder.Select(module => module.Id).Should().Equal("Stellar.A", "Stellar.B");
catalog.Should()
@@ -244,12 +248,12 @@ public void Synchronize_WritesTheCatalog_ThatTellsAModuleWhoItIs()
public void Synchronize_RefusesALevelViolation_AndWritesNothing()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Installed(directory);
+ StellarInstallation installation = FakeCore.Installed(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A",
""" "Level": "CoreModule", "Dependencies": ["Stellar.B"] """);
FakeCore.Module(directory, "modules/Stellar.B", "Stellar.B");
- var action = () => ModuleSynchronizer.Synchronize(installation, NullToolLogger.Instance);
+ Func action = () => ModuleSynchronizer.Synchronize(installation, NullToolLogger.Instance);
action.Should().Throw().WithMessage("*must not depend on*");
File.Exists(installation.ModuleCatalog).Should().BeFalse();
@@ -262,13 +266,13 @@ public class ModuleScaffolderTests
public void Create_RendersTheTemplateIntoModules()
{
using var directory = new TempDirectory();
- var installation = FakeCore.Installed(directory);
+ StellarInstallation installation = FakeCore.Installed(directory);
directory.Write("Shared/Templates/Modules/Managed/__ModuleId__.stellar.module",
"""{ "Id": "{{ModuleId}}", "Level": "{{ModuleLevel}}" }""");
directory.Write("Shared/Templates/Modules/Managed/src/Native/__ModuleNativeId__/__ModuleNativeId__.vcxproj",
"{{ModuleNativeGuid}}");
- var created = new ModuleScaffolder(installation, NullToolLogger.Instance)
+ string created = new ModuleScaffolder(installation, NullToolLogger.Instance)
.Create(new ModuleRequest("Stellar.Sample", ModuleLevel.CoreModule, null, "Managed"));
created.Should().Be(Path.Combine(installation.Modules, "Stellar.Sample"));
@@ -286,10 +290,10 @@ public void Create_RendersTheTemplateIntoModules()
public void Create_RejectsBadIdentifiers(string id)
{
using var directory = new TempDirectory();
- var installation = FakeCore.Installed(directory);
+ StellarInstallation installation = FakeCore.Installed(directory);
directory.Write("Shared/Templates/Modules/Managed/x.txt", "x");
- var action = () => new ModuleScaffolder(installation, NullToolLogger.Instance)
+ Func action = () => new ModuleScaffolder(installation, NullToolLogger.Instance)
.Create(new ModuleRequest(id, ModuleLevel.HighLevel, null, "Managed"));
action.Should().Throw();
@@ -300,7 +304,7 @@ public class ModuleBuildPlannerTests
{
private static (StellarInstallation Installation, ModuleSet Set) Installation(TempDirectory directory)
{
- var installation = FakeCore.Installed(directory);
+ StellarInstallation installation = FakeCore.Installed(directory);
FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A", """ "Level": "CoreModule" """);
directory.Write("modules/Stellar.A/src/Native/Stellar.Native.A/Stellar.Native.A.vcxproj", "");
FakeCore.Module(directory, "modules/Stellar.B", "Stellar.B", """ "Dependencies": ["Stellar.A"] """);
@@ -313,9 +317,10 @@ private static (StellarInstallation Installation, ModuleSet Set) Installation(Te
public void Plan_BuildsTheDependenciesFirst_NativeBeforeManaged()
{
using var directory = new TempDirectory();
- var (installation, set) = Installation(directory);
+ (StellarInstallation installation, ModuleSet set) = Installation(directory);
- var steps = ModuleBuildPlanner.Plan(installation, set, ["Stellar.B"], new ModuleBuildOptions(Pack: true),
+ IReadOnlyList steps = ModuleBuildPlanner.Plan(installation, set, ["Stellar.B"],
+ new ModuleBuildOptions(Pack: true),
"msbuild.exe");
steps.Select(step => $"{step.Module}: {step.Description}").Should().Equal(
@@ -328,14 +333,50 @@ public void Plan_BuildsTheDependenciesFirst_NativeBeforeManaged()
step.Arguments.Any(argument => argument.StartsWith("-p:StellarRoot=") && argument.EndsWith("/")));
}
+ [Fact]
+ public void Plan_PacksBeforeTheTests_WhichTakeThePackageOutsideDebug()
+ {
+ using var directory = new TempDirectory();
+ StellarInstallation installation = FakeCore.Installed(directory);
+ FakeCore.Module(directory, "modules/Stellar.A", "Stellar.A");
+ directory.Write("modules/Stellar.A/tests/Stellar.A.Tests/Stellar.A.Tests.csproj", "");
+ ModuleSet set = ModuleSynchronizer.Synchronize(installation, NullToolLogger.Instance);
+
+ IReadOnlyList steps = ModuleBuildPlanner.Plan(installation, set, [],
+ new ModuleBuildOptions(Tests: true, Pack: true), null);
+
+ steps.Select(step => step.Description).Should()
+ .Equal("build Stellar.A", "pack Stellar.A", "test Stellar.A.Tests");
+ steps.Select(step => step.IsPack).Should().Equal(false, true, false);
+ }
+
+ [Fact]
+ public void Builder_TellsAboutAPackageBeforeTheNextStep()
+ {
+ var runner = new RecordingRunner(-1);
+ int callsWhenPacked = 0;
+ BuildStep[] steps = new[]
+ {
+ new BuildStep("A", "pack", "dotnet", ["pack"], true),
+ new BuildStep("A", "test", "dotnet", ["test"])
+ };
+
+ new ModuleBuilder(runner, NullToolLogger.Instance, () => callsWhenPacked = runner.Calls).Run(steps, ".");
+
+ callsWhenPacked.Should().Be(1);
+ runner.Calls.Should().Be(2);
+ }
+
[Fact]
public void Plan_NeedsMSBuildForNativeProjects_UnlessTheyAreSkipped()
{
using var directory = new TempDirectory();
- var (installation, set) = Installation(directory);
+ (StellarInstallation installation, ModuleSet set) = Installation(directory);
- var withNative = () => ModuleBuildPlanner.Plan(installation, set, [], new ModuleBuildOptions(), null);
- var withoutNative = ModuleBuildPlanner.Plan(installation, set, [], new ModuleBuildOptions(Native: false), null);
+ Func> withNative = () =>
+ ModuleBuildPlanner.Plan(installation, set, [], new ModuleBuildOptions(), null);
+ IReadOnlyList withoutNative =
+ ModuleBuildPlanner.Plan(installation, set, [], new ModuleBuildOptions(Native: false), null);
withNative.Should().Throw().WithMessage("*--no-native*");
withoutNative.Should().HaveCount(3);
@@ -345,14 +386,14 @@ public void Plan_NeedsMSBuildForNativeProjects_UnlessTheyAreSkipped()
public void Builder_StopsAtTheFirstFailure()
{
var runner = new RecordingRunner(1);
- var steps = new[]
+ BuildStep[] steps = new[]
{
new BuildStep("A", "one", "dotnet", ["build"]),
new BuildStep("A", "two", "dotnet", ["build"]),
new BuildStep("B", "three", "dotnet", ["build"])
};
- var action = () => new ModuleBuilder(runner, NullToolLogger.Instance).Run(steps, ".");
+ Action action = () => new ModuleBuilder(runner, NullToolLogger.Instance).Run(steps, ".");
action.Should().Throw().WithMessage("*two*");
runner.Calls.Should().Be(2);
diff --git a/SDK/tests/Stellar.Tools.Tests/TempDirectory.cs b/SDK/tests/Stellar.Tools.Tests/TempDirectory.cs
index 0dab5af..b14eb3c 100644
--- a/SDK/tests/Stellar.Tools.Tests/TempDirectory.cs
+++ b/SDK/tests/Stellar.Tools.Tests/TempDirectory.cs
@@ -11,7 +11,7 @@ public sealed class TempDirectory : IDisposable
public string Write(string relativePath, string content = "content")
{
- var path = System.IO.Path.Combine(Path, relativePath);
+ string path = System.IO.Path.Combine(Path, relativePath);
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(path)!);
File.WriteAllText(path, content);
@@ -21,6 +21,11 @@ public string Write(string relativePath, string content = "content")
public void Dispose()
{
+ // git makes its objects read-only, and Windows does not delete those
+ foreach (FileInfo file in new DirectoryInfo(Path).EnumerateFiles("*", SearchOption.AllDirectories))
+ if (file.IsReadOnly)
+ file.IsReadOnly = false;
+
Directory.Delete(Path, true);
}
}
diff --git a/Shared/Build/Stellar.Core.Build.targets b/Shared/Build/Stellar.Core.Build.targets
index e344915..1cc3b3d 100644
--- a/Shared/Build/Stellar.Core.Build.targets
+++ b/Shared/Build/Stellar.Core.Build.targets
@@ -12,5 +12,8 @@
+
+
+
diff --git a/Shared/Build/Stellar.Versions.props b/Shared/Build/Stellar.Versions.props
index 9ed9d35..ec43021 100644
--- a/Shared/Build/Stellar.Versions.props
+++ b/Shared/Build/Stellar.Versions.props
@@ -7,31 +7,43 @@
-->
- 0.10.0
+ 0.11.0
- 0.10.0
+ 0.10.1
0.10.0
- 0.10.0
- 0.3.2
- 0.4.1
- 0.2.3
+ 0.10.1
+ 0.3.3
+ 0.4.2
+ 0.2.4
- 0.9.0
+ 0.11.0
3
https://quantumdevteam.github.io/StellarEngine-Core/
$(StellarSiteUri)schemas/
-
+
https://quantumdevteam.github.io/StellarEngine-Mono/
+
+
+
+ https://notagood.org/docs/
+ stellar-core
+ stellar-engine
+
diff --git a/Shared/Docs/Template/public/main.css b/Shared/Docs/Template/public/main.css
deleted file mode 100644
index 3e66746..0000000
--- a/Shared/Docs/Template/public/main.css
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- The theme of the StellarEngine sites, over the "modern" template of DocFX: the sites of the core and of the
- orchestra list this folder last in "template", the template of a module carries a copy.
-*/
-
-:root {
- --stellar-accent: #8a63ff;
- --stellar-accent-strong: #6d3df5;
-}
-
-[data-bs-theme="dark"] {
- --stellar-accent: #a98bff;
- --stellar-accent-strong: #c4b0ff;
-}
-
-/* The brand: the icon and the name side by side, a fixed size, room before the menu */
-.navbar-brand {
- display: inline-flex;
- align-items: center;
- gap: 0.55rem;
- margin-right: 1.75rem;
- font-weight: 600;
- letter-spacing: 0.01em;
- white-space: nowrap;
-}
-
-/* The icon is wide (Shared/Branding/stellar_icon.svg: the emblem without the name): fixed height, its own width */
-.navbar-brand #logo {
- height: 34px;
- width: auto;
- max-width: 84px;
- flex: none;
- object-fit: contain;
-}
-
-/* Entries of the menu stay on one line */
-.navbar-nav .nav-link {
- white-space: nowrap;
-}
-
-/* A thin line under the header instead of a block */
-header .navbar {
- border-bottom: 1px solid var(--bs-border-color-translucent);
-}
-
-/* Links and the active entry in the accent of the logo */
-article a,
-.toc a.active,
-.navbar-nav .nav-link.active {
- color: var(--stellar-accent);
-}
-
-article a:hover {
- color: var(--stellar-accent-strong);
-}
-
-/* Code blocks of one command (the installer) read better a little larger */
-article pre > code {
- font-size: 0.92em;
-}
-
-/* Wide tables of the docs scroll inside the page instead of pushing it */
-article table {
- display: block;
- max-width: 100%;
- overflow-x: auto;
-}
diff --git a/Shared/Marks/marks.json b/Shared/Marks/marks.json
new file mode 100644
index 0000000..032eecf
--- /dev/null
+++ b/Shared/Marks/marks.json
@@ -0,0 +1,7 @@
+{
+ "Marks": {
+ "MVP": { "Level": "Info", "Description": "The minimum that works is reached here" },
+ "WIP": { "Level": "Release", "Description": "Not finished: it cannot be released" },
+ "DRAFT": { "Level": "Commit", "Description": "A trial of one machine: it cannot be committed" }
+ }
+}
diff --git a/Shared/Templates/Modules/Managed/.github/workflows/docs.yml b/Shared/Templates/Modules/Managed/.github/workflows/docs.yml
index ae87db5..55300e0 100644
--- a/Shared/Templates/Modules/Managed/.github/workflows/docs.yml
+++ b/Shared/Templates/Modules/Managed/.github/workflows/docs.yml
@@ -1,23 +1,27 @@
name: Docs
-# Builds the documentation site of the module from Docs/ with DocFX (docfx.json) and publishes it to GitHub Pages.
-# Pull requests and manual runs on other branches only build; the site is deployed from master only.
-# Repository setting required once: Settings -> Pages -> Source = "GitHub Actions".
+# Publishes the documentation of this repository to GitHub Pages for the Prometheus site (the team site).
+# GitHub Pages is only the storage of the site: static files (the installer, the schemas), the documentation as data
+# (bundle/) and a small embed that redirects to the site when the site is up.
+#
+# This file is a thin wrapper and does not need updates: the steps (ci.py, the bundle builder, the embed) are
+# downloaded from the site on every run (/docs-kit.zip), so they are always the same version as the site.
+# What to build is described by the repository itself in prometheus.json (format prometheus-repo/1, see the DOCS
+# page of the site); without it: Docs/ and the API of the projects in docfx.json.
+# If the site is down, the static files and a page that leads to the site are published; the next run fixes the rest.
+#
+# Repository settings:
+# Settings -> Pages -> Source = "GitHub Actions" (once)
+# Variables (optional): PROMETHEUS_SITE (https://notagood.org by default),
+# PROMETHEUS_PROJECT, PROMETHEUS_TITLE (override prometheus.json)
+# Secrets (optional): PROMETHEUS_SYNC_KEY an API key of the site with the "sync" scope: the site learns about
+# the new build at once instead of on its next check
+# Pull requests and manual runs on other branches only build; Pages is deployed from master only.
on:
push:
branches: [master]
- paths:
- - 'Docs/**'
- - 'README.md'
- - 'docfx.json'
- - '.github/workflows/docs.yml'
pull_request:
- paths:
- - 'Docs/**'
- - 'README.md'
- - 'docfx.json'
- - '.github/workflows/docs.yml'
workflow_dispatch:
permissions:
@@ -31,39 +35,95 @@ env:
DOCFX_VERSION: '2.81.0'
DOTNET_NOLOGO: 'true'
DOTNET_CLI_TELEMETRY_OPTOUT: 'true'
+ PROMETHEUS_SITE: ${{ vars.PROMETHEUS_SITE || 'https://notagood.org' }}
+ PROMETHEUS_PROJECT: ${{ vars.PROMETHEUS_PROJECT }}
+ PROMETHEUS_TITLE: ${{ vars.PROMETHEUS_TITLE }}
+ OUT: artifacts/pages
jobs:
build:
- name: Build site
- runs-on: ubuntu-latest
+ name: Build
+ runs-on: ubuntu-latest # pwsh, python3 and bash are there: "prepare" scripts may use any of them
steps:
- name: Checkout
uses: actions/checkout@v5
- # The global.json of a module pins Stellar.Sdk, not the .NET SDK
- name: Setup .NET
+ if: hashFiles('global.json') != ''
+ uses: actions/setup-dotnet@v5
+ with:
+ global-json-file: global.json
+
+ - name: Setup .NET (no global.json)
+ if: hashFiles('global.json') == ''
uses: actions/setup-dotnet@v5
with:
dotnet-version: '9.0.x'
+ # Installed outside the checkout so a repository NuGet.config (a local feed) is not involved.
- name: Install DocFX
working-directory: ${{ runner.temp }}
run: dotnet tool install docfx --version "$DOCFX_VERSION" --tool-path "$RUNNER_TEMP/docfx"
- - name: Build documentation
- run: '"$RUNNER_TEMP/docfx/docfx" build docfx.json --warningsAsErrors'
+ - name: Prometheus
+ id: prometheus
+ continue-on-error: true
+ run: |
+ set -euo pipefail
+ # NuGet wants the local feed folder of an installation to exist, even empty
+ mkdir -p packages
+ curl -fsSL --retry 2 "$PROMETHEUS_SITE/docs-kit.zip" -o "$RUNNER_TEMP/kit.zip"
+ unzip -q -o "$RUNNER_TEMP/kit.zip" -d "$RUNNER_TEMP/kit"
+ python3 -m pip install --quiet pyyaml
+ python3 "$RUNNER_TEMP/kit/ci.py" --out "$OUT" --docfx "$RUNNER_TEMP/docfx/docfx"
+
+ # The site is down or the build failed: publish the static files and a page that leads to the site.
+ # Self-contained on purpose (no kit): the installer and the schemas keep their addresses whatever happens.
+ - name: Fallback
+ if: steps.prometheus.outcome == 'failure'
+ run: |
+ echo "::warning title=Prometheus::The documentation was not built (is $PROMETHEUS_SITE up?); publishing the static files only"
+ mkdir -p "$OUT" && touch "$OUT/.nojekyll"
+ python3 - <<'PY'
+ import glob, html, json, os, re, shutil
+ out = os.environ["OUT"]
+ cfg = json.load(open("prometheus.json", encoding="utf-8-sig")) if os.path.isfile("prometheus.json") else {}
+ static = cfg.get("static") or next((a.get("docfx") if isinstance(a, dict) else a for a in cfg.get("api") or []), None) \
+ or ("docfx.json" if os.path.isfile("docfx.json") else None)
+ for config in ([static] if isinstance(static, str) else static or []):
+ if not os.path.isfile(config):
+ continue
+ base = os.path.dirname(os.path.abspath(config))
+ for r in json.load(open(config, encoding="utf-8-sig")).get("build", {}).get("resource", []):
+ src, dest = os.path.join(base, r.get("src", "")), os.path.join(out, r.get("dest", ""))
+ for pattern in r.get("files", []):
+ for f in glob.glob(os.path.join(src, pattern), recursive=True):
+ if os.path.isfile(f):
+ t = os.path.join(dest, os.path.relpath(f, src))
+ os.makedirs(os.path.dirname(t), exist_ok=True)
+ shutil.copy2(f, t)
+ repo = os.environ.get("GITHUB_REPOSITORY", "").rsplit("/", 1)[-1]
+ project = os.environ.get("PROMETHEUS_PROJECT") or cfg.get("project") or re.sub(r"[^a-z0-9]+", "-", repo.lower()).strip("-")
+ url = html.escape(f"{os.environ['PROMETHEUS_SITE'].rstrip('/')}/docs/{project}")
+ title = html.escape(os.environ.get("PROMETHEUS_TITLE") or cfg.get("title") or repo)
+ with open(os.path.join(out, "index.html"), "w", encoding="utf-8") as f:
+ f.write(f'{title}'
+ f''
+ f'{title} documentation
')
+ PY
- name: Upload Pages artifact
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master'
uses: actions/upload-pages-artifact@v5
with:
- path: artifacts/docs/site
+ path: ${{ env.OUT }}
deploy:
name: Deploy to GitHub Pages
if: github.event_name != 'pull_request' && github.ref == 'refs/heads/master'
needs: build
runs-on: ubuntu-latest
+ # Never cancel a deployment that is already running.
concurrency:
group: pages
cancel-in-progress: false
@@ -77,3 +137,13 @@ jobs:
- name: Deploy
id: deployment
uses: actions/deploy-pages@v5
+
+ # The site would notice the new bundle on its next check anyway; this makes it immediate.
+ - name: Nudge the site
+ continue-on-error: true
+ env:
+ KEY: ${{ secrets.PROMETHEUS_SYNC_KEY }}
+ run: |
+ if [ -z "$KEY" ]; then echo "::notice::PROMETHEUS_SYNC_KEY is not set: the site picks the docs up on its next check"; exit 0; fi
+ sleep 30 # Pages needs a moment to serve the new files
+ curl -fsS -X POST -H "Authorization: Bearer $KEY" "$PROMETHEUS_SITE/api/v1/sync"
diff --git a/Shared/Templates/Modules/Managed/.github/workflows/marks.yml b/Shared/Templates/Modules/Managed/.github/workflows/marks.yml
new file mode 100644
index 0000000..ce1e719
--- /dev/null
+++ b/Shared/Templates/Modules/Managed/.github/workflows/marks.yml
@@ -0,0 +1,15 @@
+name: Marks
+
+# The marks in the comments of the code, checked by the workflow of the core (Docs/Engine/Marks.md there).
+
+on:
+ push:
+ branches: [develop, master]
+ pull_request:
+
+permissions:
+ contents: read
+
+jobs:
+ marks:
+ uses: QuantumDevTeam/StellarEngine-Core/.github/workflows/marks.yml@develop
diff --git a/Shared/Templates/Modules/Managed/.github/workflows/tests.yml b/Shared/Templates/Modules/Managed/.github/workflows/tests.yml
new file mode 100644
index 0000000..73cfede
--- /dev/null
+++ b/Shared/Templates/Modules/Managed/.github/workflows/tests.yml
@@ -0,0 +1,18 @@
+name: Tests
+
+# The module built and tested on the core, by the workflow of the core.
+# By itself only on the way into master; on any other branch by hand (Run workflow).
+
+on:
+ workflow_dispatch:
+ push:
+ branches: [master]
+ pull_request:
+ branches: [master]
+
+permissions:
+ contents: read
+
+jobs:
+ tests:
+ uses: QuantumDevTeam/StellarEngine-Core/.github/workflows/tests.yml@develop
diff --git a/Shared/Templates/Modules/Managed/Docs/index.md b/Shared/Templates/Modules/Managed/Docs/index.md
index 7295789..2dcfffd 100644
--- a/Shared/Templates/Modules/Managed/Docs/index.md
+++ b/Shared/Templates/Modules/Managed/Docs/index.md
@@ -2,8 +2,7 @@
{{ModuleDescription}}
-A `{{ModuleLevel}}` module of [StellarEngine]({{EngineSiteUri}}). Its site is {{ModuleSiteUri}}, built from the Markdown
-files of `Docs/` with DocFX; the whole engine, with every module, is on the [site of the engine]({{EngineSiteUri}}).
+A `{{ModuleLevel}}` module of [StellarEngine](prometheus:{{EngineDocsProject}}). Its documentation is on the [docs site](prometheus:{{ModuleDocsProject}}), built from the Markdown files of `Docs/`; the whole engine, with every module, is on the [site of the engine](prometheus:{{EngineDocsProject}}).
## Using it
diff --git a/Shared/Templates/Modules/Managed/Docs/toc.yml b/Shared/Templates/Modules/Managed/Docs/toc.yml
index f68fcde..6cbb743 100644
--- a/Shared/Templates/Modules/Managed/Docs/toc.yml
+++ b/Shared/Templates/Modules/Managed/Docs/toc.yml
@@ -1,7 +1,7 @@
-# Navigation of the documentation site of the module (DocFX). Paths are relative to this file.
+# Navigation of the documentation site of the module (the bundle of the site). Paths are relative to this file.
- name: Home
href: index.md
- name: README
href: ../README.md
- name: StellarEngine
- href: {{EngineSiteUri}}
+ href: prometheus:{{EngineDocsProject}}
diff --git a/Shared/Templates/Modules/Managed/Template/public/main.css b/Shared/Templates/Modules/Managed/Template/public/main.css
deleted file mode 100644
index 3e66746..0000000
--- a/Shared/Templates/Modules/Managed/Template/public/main.css
+++ /dev/null
@@ -1,67 +0,0 @@
-/*
- The theme of the StellarEngine sites, over the "modern" template of DocFX: the sites of the core and of the
- orchestra list this folder last in "template", the template of a module carries a copy.
-*/
-
-:root {
- --stellar-accent: #8a63ff;
- --stellar-accent-strong: #6d3df5;
-}
-
-[data-bs-theme="dark"] {
- --stellar-accent: #a98bff;
- --stellar-accent-strong: #c4b0ff;
-}
-
-/* The brand: the icon and the name side by side, a fixed size, room before the menu */
-.navbar-brand {
- display: inline-flex;
- align-items: center;
- gap: 0.55rem;
- margin-right: 1.75rem;
- font-weight: 600;
- letter-spacing: 0.01em;
- white-space: nowrap;
-}
-
-/* The icon is wide (Shared/Branding/stellar_icon.svg: the emblem without the name): fixed height, its own width */
-.navbar-brand #logo {
- height: 34px;
- width: auto;
- max-width: 84px;
- flex: none;
- object-fit: contain;
-}
-
-/* Entries of the menu stay on one line */
-.navbar-nav .nav-link {
- white-space: nowrap;
-}
-
-/* A thin line under the header instead of a block */
-header .navbar {
- border-bottom: 1px solid var(--bs-border-color-translucent);
-}
-
-/* Links and the active entry in the accent of the logo */
-article a,
-.toc a.active,
-.navbar-nav .nav-link.active {
- color: var(--stellar-accent);
-}
-
-article a:hover {
- color: var(--stellar-accent-strong);
-}
-
-/* Code blocks of one command (the installer) read better a little larger */
-article pre > code {
- font-size: 0.92em;
-}
-
-/* Wide tables of the docs scroll inside the page instead of pushing it */
-article table {
- display: block;
- max-width: 100%;
- overflow-x: auto;
-}
diff --git a/Shared/Templates/Modules/Managed/docfx.json b/Shared/Templates/Modules/Managed/docfx.json
index a007073..d651cee 100644
--- a/Shared/Templates/Modules/Managed/docfx.json
+++ b/Shared/Templates/Modules/Managed/docfx.json
@@ -1,40 +1,12 @@
{
"$schema": "https://raw.githubusercontent.com/dotnet/docfx/main/schemas/docfx.schema.json",
"build": {
- "content": [
- {
- "src": "Docs",
- "files": [
- "**/*.md",
- "toc.yml"
- ]
- },
- {
- "files": [
- "README.md"
- ]
- }
- ],
"resource": [
{
"files": [
"Branding/Logo.svg"
]
}
- ],
- "output": "artifacts/docs/site",
- "template": [
- "default",
- "modern",
- "Template"
- ],
- "globalMetadata": {
- "_appName": "{{ModuleId}}",
- "_appTitle": "{{ModuleId}}",
- "_appFooter": "{{ModuleId}}, a module of StellarEngine",
- "_appLogoPath": "Branding/Logo.svg",
- "_appFaviconPath": "Branding/Logo.svg",
- "_enableSearch": true
- }
+ ]
}
}
diff --git a/Shared/Templates/Modules/Managed/prometheus.json b/Shared/Templates/Modules/Managed/prometheus.json
new file mode 100644
index 0000000..e2f66c2
--- /dev/null
+++ b/Shared/Templates/Modules/Managed/prometheus.json
@@ -0,0 +1,15 @@
+{
+ "format": "prometheus-repo/1",
+ "project": "{{ModuleDocsProject}}",
+ "title": "{{ModuleId}}",
+ "version": {
+ "file": "{{ModuleId}}.stellar.module",
+ "regex": "\"Version\"\\s*:\\s*\"([^\"]+)\""
+ },
+ "docs": [
+ {
+ "path": "Docs"
+ }
+ ],
+ "static": "docfx.json"
+}
diff --git a/docfx.json b/docfx.json
index 27dc317..6caa42a 100644
--- a/docfx.json
+++ b/docfx.json
@@ -24,25 +24,6 @@
}
],
"build": {
- "content": [
- {
- "src": "Docs",
- "files": [
- "**/*.md",
- "toc.yml"
- ],
- "exclude": [
- "Engine/**"
- ]
- },
- {
- "src": "artifacts/docs/api",
- "dest": "api",
- "files": [
- "**/*.yml"
- ]
- }
- ],
"resource": [
{
"files": [
@@ -64,24 +45,6 @@
"install.ps1"
]
}
- ],
- "output": "artifacts/docs/site",
- "template": [
- "default",
- "modern",
- "Shared/Docs/Template"
- ],
- "globalMetadata": {
- "_appName": "StellarEngine-Core",
- "_appTitle": "StellarEngine-Core",
- "_appFooter": "StellarEngine-Core, the core of StellarEngine, by QuantumDevTeam",
- "_appLogoPath": "Shared/Branding/stellar_icon.svg",
- "_appFaviconPath": "Shared/Branding/stellar_icon.svg",
- "_enableSearch": true,
- "_gitContribute": {
- "repo": "https://github.com/QuantumDevTeam/StellarEngine-Core",
- "branch": "master"
- }
- }
+ ]
}
}
diff --git a/global.json b/global.json
index e7a2998..8303ef6 100644
--- a/global.json
+++ b/global.json
@@ -5,6 +5,6 @@
"allowPrerelease": false
},
"msbuild-sdks": {
- "Stellar.Sdk": "0.4.1"
+ "Stellar.Sdk": "0.4.2"
}
}
diff --git a/prometheus.json b/prometheus.json
new file mode 100644
index 0000000..801b9d7
--- /dev/null
+++ b/prometheus.json
@@ -0,0 +1,4 @@
+{
+ "format": "prometheus-repo/1",
+ "prepare": "scripts/prometheus.ps1"
+}
diff --git a/scripts/build.ps1 b/scripts/build.ps1
index 7d015b7..c56fabf 100644
--- a/scripts/build.ps1
+++ b/scripts/build.ps1
@@ -36,6 +36,10 @@
With -Install: do not register this installation for the current user ($STELLAR_HOME or ~/.stellar), and do
not install the 'stellar' command. For sandboxes.
+.PARAMETER SkipModules
+ With -Install: do not build and pack the modules of modules/. Without it they are built after the core, with
+ their tests unless -SkipTests, so games that take the engine as packages find them.
+
.PARAMETER Uninstall
Undoes -Install and the build instead of building: 'stellar uninstall' here (the registration of the user, the
packages of this installation in the NuGet cache, what the installer created), the 'stellar' command, then
@@ -57,6 +61,7 @@ param(
[switch]$Pack,
[switch]$Install,
[switch]$NoUserRegistration,
+ [switch]$SkipModules,
[switch]$Uninstall,
[switch]$All,
[switch]$KeepArtifacts
@@ -181,6 +186,12 @@ if (-not $SkipNative) {
"-p:Configuration=$Configuration" -p:Platform=x64 -m -nologo -v:minimal
}
+ if (-not $SkipTests) {
+ Invoke-Step 'Native tests' {
+ & (Join-Path $root "artifacts/bin/Stellar.Native.Core.Tests/$Configuration/Stellar.Native.Core.Tests.exe")
+ }
+ }
+
# Built by the MSBuild of Visual Studio: the .NET SDK cannot build C++/CLI
if ($canBuildCli) {
Invoke-Step 'C++/CLI wrapper' {
@@ -188,12 +199,6 @@ if (-not $SkipNative) {
-restore "-p:Configuration=$Configuration" -p:Platform=x64 -m -nologo -v:minimal
}
}
-
- if (-not $SkipTests) {
- Invoke-Step 'Native tests' {
- & (Join-Path $root "artifacts/bin/Stellar.Native.Core.Tests/$Configuration/Stellar.Native.Core.Tests.exe")
- }
- }
}
$managed = Join-Path $root 'StellarEngine-Core.Managed.slnf'
@@ -212,7 +217,12 @@ foreach ($variant in $wrappers) {
}
if ($Pack) {
- $projects = 'Kernel/src/Managed/Stellar.Kernel', 'Core/src/Managed/Stellar.Core', 'Runtime/src/Managed/Stellar.Runtime', 'SDK/src/Stellar.Tools', 'SDK/src/Stellar.Cli', 'SDK/src/MSBuild/Stellar.Sdk'
+ $projects = 'Kernel/src/Managed/Stellar.Kernel',
+ 'Core/src/Managed/Stellar.Core',
+ 'Runtime/src/Managed/Stellar.Runtime',
+ 'SDK/src/Stellar.Tools',
+ 'SDK/src/Stellar.Cli',
+ 'SDK/src/MSBuild/Stellar.Sdk'
foreach ($project in $projects) {
$csproj = Join-Path $root "$project/$(Split-Path $project -Leaf).csproj"
@@ -251,6 +261,21 @@ if ($Install) {
# Registration and the command go together: both belong to the user, not to the checkout
if (-not $NoUserRegistration) { Install-StellarTool }
+
+ $modules = @(Get-ChildItem (Join-Path $root 'modules') -Filter '*.stellar.module' -Recurse -Depth 1 -ErrorAction SilentlyContinue)
+ if (-not $SkipModules -and $modules.Count -gt 0) {
+ $arguments = @('modules', 'build', '--pack', '-c', $Configuration, '--wrapper', $Wrapper)
+ if (-not $SkipTests) { $arguments += '--tests' }
+
+ Invoke-Step "Modules ($($modules.Count))" {
+ Push-Location $root
+ try {
+ dotnet run --project (Join-Path $root 'SDK/src/Stellar.Cli/Stellar.Cli.csproj') -c $Configuration --no-build -- @arguments
+ } finally {
+ Pop-Location
+ }
+ }
+ }
}
-Write-Host "StellarEngine-Core built ($Configuration, wrappers: $($wrappers -join ', '), packed with: $Wrapper) in $root" -ForegroundColor Green
+Write-Host "StellarEngine built ($Configuration, wrappers: $($wrappers -join ', '), packed with: $Wrapper) in $root" -ForegroundColor Green
diff --git a/scripts/orchestra-site.ps1 b/scripts/orchestra-site.ps1
deleted file mode 100644
index 388b524..0000000
--- a/scripts/orchestra-site.ps1
+++ /dev/null
@@ -1,230 +0,0 @@
-<#
-.SYNOPSIS
- Generates the DocFX project of the orchestra site: the core and every module of the tree in one site.
-
-.DESCRIPTION
- The mirror (StellarEngine-Mono) holds the core at its root and every component in modules// and
- tools//. Its site gathers them:
-
- / the home of StellarEngine: getting started, what the orchestra is made of
- /guide/ the guide of the whole engine: Docs/Engine of the core (installing, architecture,
- modules, the orchestra, the project), with README, CONTRIBUTING, LICENSE at /
- /core/ the core as a component: the rest of its Docs/, /core/api/ its API reference
- /modules// the Docs/ of each module (each also has a site of its own)
- /tools// the same for tools
- /install.ps1 the installer, /schemas/ the JSON schemas
-
- The project is written to docfx.orchestra.json at the root, its pages to artifacts/orchestra/ (both generated,
- never edited, ignored by git); build it with 'docfx docfx.orchestra.json'. The docs workflow does that when the tree is a mirror: scripts/mirror.ps1
- puts a .orchestra file at the root of every snapshot, with the commits it was made of.
-
-.PARAMETER Output
- The folder of the generated pages (the hub and its navigation). artifacts/orchestra by default.
-#>
-param(
- [string]$Output = ''
-)
-
-$ErrorActionPreference = 'Stop'
-$root = Split-Path $PSScriptRoot -Parent
-if (-not $Output) { $Output = Join-Path $root 'artifacts/orchestra' }
-$Output = [System.IO.Path]::GetFullPath($Output)
-New-Item -ItemType Directory -Force $Output | Out-Null
-
-# DocFX takes the paths of a project relative to it
-function Get-FromProject([string]$Path) {
- $from = [System.Uri]::new($Output.TrimEnd('\', '/') + '/')
- $to = [System.Uri]::new([System.IO.Path]::GetFullPath($Path).TrimEnd('\', '/') + '/')
- return [System.Uri]::UnescapeDataString($from.MakeRelativeUri($to).ToString()).TrimEnd('/')
-}
-
-# The project itself lies at the root, above every source: DocFX resolves nested tables of contents wrongly for
-# sources above the folder of its project
-$project_ = Join-Path $root 'docfx.orchestra.json'
-function Get-FromRoot([string]$Path) {
- return [System.IO.Path]::GetFullPath($Path).Substring($root.TrimEnd('\', '/').Length).TrimStart('\', '/').Replace('\', '/')
-}
-
-$versions = [System.IO.File]::ReadAllText((Join-Path $root 'Shared/Build/Stellar.Versions.props'))
-$orchestra = [regex]::Match($versions, '([^<]+)<').Groups[1].Value
-$site = [regex]::Match($versions, '([^<]+)<').Groups[1].Value
-$host_ = ([System.Uri]$site).GetLeftPart([System.UriPartial]::Authority)
-
-# What the snapshot was made of, if this is one
-$snapshot = @{}
-$marker = Join-Path $root '.orchestra'
-if (Test-Path $marker) {
- foreach ($component in (Get-Content $marker -Raw | ConvertFrom-Json).Components) { $snapshot[$component.Name] = $component }
-}
-
-$rootPath = Get-FromProject $root
-# Links of the hub name source files, as DocFX resolves them; the site paths follow from the content mapping below
-$engineDocs = Get-FromProject (Join-Path $root 'Docs/Engine')
-$coreDocs = Get-FromProject (Join-Path $root 'Docs')
-$coreApi = Get-FromProject (Join-Path $root 'artifacts/docs/api')
-$content = [System.Collections.Generic.List[object]]::new()
-$navigation = [System.Collections.Generic.List[string]]::new()
-$rows = [System.Collections.Generic.List[string]]::new()
-
-# ---- The guide of the engine ----
-# Docs/Engine of the core: the pages about the engine as a whole live there, published here only
-$content.Add([ordered]@{ src = 'Docs/Engine'; dest = 'guide'; files = @('**/*.md', 'toc.yml') })
-$content.Add([ordered]@{ files = @('README.md', 'CONTRIBUTING.md', 'LICENSE.md') })
-
-# ---- The core, a component ----
-$content.Add([ordered]@{ src = 'Docs'; dest = 'core'; files = @('**/*.md', 'toc.yml'); exclude = @('Engine/**') })
-$content.Add([ordered]@{ src = 'artifacts/docs/api'; dest = 'core/api'; files = @('**/*.yml') })
-$coreCommit = if ($snapshot['StellarEngine-Core']) { "``$($snapshot['StellarEngine-Core'].Commit.Substring(0, 10))``" } else { '' }
-$coreRepository = if ($snapshot['StellarEngine-Core'] -and $snapshot['StellarEngine-Core'].Repository) { ", [repository]($($snapshot['StellarEngine-Core'].Repository -replace '\.git$', ''))" } else { '' }
-$rows.Add("| [StellarEngine-Core]($coreDocs/index.md) | the kernel, the core, the runtime, the SDK and the tools | $coreCommit | [site]($site)$coreRepository |")
-
-# ---- The components ----
-$componentNavigation = [System.Collections.Generic.List[string]]::new()
-foreach ($area in 'modules', 'tools') {
- $directory = Join-Path $root $area
- if (-not (Test-Path $directory)) { continue }
-
- foreach ($component in (Get-ChildItem $directory -Directory | Sort-Object Name)) {
- if ($component.Name.StartsWith('_')) { continue }
- # tools/compilers belongs to the installer, not to a component
- if ($area -eq 'tools' -and $component.Name -eq 'compilers') { continue }
- $docs = Join-Path $component.FullName 'Docs'
-
- $description = ''
- $descriptor = Join-Path $component.FullName "$($component.Name).stellar.module"
- if (Test-Path $descriptor) { $description = (Get-Content $descriptor -Raw | ConvertFrom-Json).Description }
-
- $commit = if ($snapshot[$component.Name]) { "``$($snapshot[$component.Name].Commit.Substring(0, 10))``" } else { '' }
- $componentDocs = Get-FromProject $docs
- $own = "$host_/$($component.Name)/"
- $repository = if ($snapshot[$component.Name] -and $snapshot[$component.Name].Repository) { ", [repository]($($snapshot[$component.Name].Repository -replace '\.git$', ''))" } else { '' }
-
- if (Test-Path (Join-Path $docs 'index.md')) {
- $content.Add([ordered]@{ src = Get-FromRoot $docs; dest = "$area/$($component.Name)"; files = @('**/*.md', 'toc.yml') })
- # The README of the component, which its pages link to as ../README.md: same place in the site
- if (Test-Path (Join-Path $component.FullName 'README.md')) {
- $content.Add([ordered]@{ src = Get-FromRoot $component.FullName; dest = "$area/$($component.Name)"; files = @('README.md') })
- }
- $rows.Add("| [$($component.Name)]($componentDocs/index.md) | $description | $commit | [site]($own)$repository |")
- $componentNavigation.Add(" - name: $($component.Name)`n href: $componentDocs/index.md")
- }
- else {
- $rows.Add("| $($component.Name) | $description | $commit | [site]($own)$repository |")
- }
- }
-}
-
-# ---- The hub ----
-$installUri = "${site}install.ps1"
-$engineLogo = "$rootPath/Shared/Branding/stellar_1x1.svg"
-$brandLogo = "$rootPath/Shared/Branding/logo_clean.svg"
-$index = @"
-
-
-# StellarEngine $orchestra
-
-A hypermodular game engine built from the bottom up: a C++ native core, a managed core over it, and everything else as
-modules, each in a repository of its own. This is the site of the whole engine: the documentation, the API reference,
-and every module and tool of the orchestra, built from StellarEngine-Mono, the mirror of all of them.
-
-## Getting started
-
-1. **Install the engine.** One command checks the toolchain, clones the core, builds and registers it
- ([what it needs and does]($engineDocs/Install.md)):
-
- ``````powershell
- irm $installUri | iex
- ``````
-
-2. **Check it.** Open a new terminal, so the ``stellar`` command is on the ``PATH``:
-
- ``````powershell
- stellar info
- ``````
-
-3. **Make a module** in the installation, and the solution of the whole installation for the IDE:
-
- ``````powershell
- stellar modules new Managed Stellar.MyModule
- powershell -File \scripts\solution.ps1
- ``````
-
-4. **Build and test it:**
-
- ``````powershell
- stellar modules build Stellar.MyModule --tests
- ``````
-
-5. **Read on:** the [architecture]($engineDocs/Architecture.md), the [design philosophy]($engineDocs/DesignPhilosophy.md),
- [modules]($engineDocs/Modules.md), the [installation and the repositories]($engineDocs/Repository.md),
- and [the core]($coreDocs/index.md) with its [API reference](xref:Stellar.Kernel).
-
-## The orchestra
-
-Every component of this snapshot, with the commit it was taken at, its own site and its repository:
-
-| Component | What | Commit | Links |
-|---|---|---|---|
-$($rows -join "`n")
-
----
-
-
StellarEngine is made by QuantumDevTeam.
-"@
-[System.IO.File]::WriteAllText((Join-Path $Output 'index.md'), $index + "`n", [System.Text.UTF8Encoding]::new($false))
-
-$toc = @"
-- name: Home
- href: index.md
-- name: Install
- href: $engineDocs/Install.md
-- name: Guide
- href: $engineDocs/
-- name: Core
- href: $coreDocs/
-- name: API
- href: $coreApi/
-"@
-if ($componentNavigation.Count -gt 0) { $toc += "`n- name: Modules`n items:`n$($componentNavigation -join "`n")" }
-[System.IO.File]::WriteAllText((Join-Path $Output 'toc.yml'), $toc + "`n", [System.Text.UTF8Encoding]::new($false))
-
-$content.Insert(0, [ordered]@{ src = Get-FromRoot $Output; files = @('index.md', 'toc.yml') })
-
-$project = [ordered]@{
- metadata = @(
- [ordered]@{
- src = @([ordered]@{
- src = '.'
- files = @(
- 'Kernel/src/Managed/Stellar.Kernel/Stellar.Kernel.csproj',
- 'Core/src/Managed/Stellar.Core/Stellar.Core.csproj',
- 'Runtime/src/Managed/Stellar.Runtime/Stellar.Runtime.csproj',
- 'SDK/src/Stellar.Tools/Stellar.Tools.csproj')
- })
- dest = 'artifacts/docs/api'
- properties = [ordered]@{ TargetFramework = 'net9.0'; StellarNativeWrapper = 'Managed' }
- memberLayout = 'separatePages'
- namespaceLayout = 'nested'
- enumSortOrder = 'declaringOrder'
- })
- build = [ordered]@{
- content = $content
- resource = @(
- [ordered]@{ files = @('Shared/Branding/stellar_1x1.svg', 'Shared/Branding/stellar_icon.svg', 'Shared/Branding/logo_clean.svg') },
- [ordered]@{ src = 'Shared/Schemas'; dest = 'schemas'; files = @('*.json') },
- [ordered]@{ src = 'scripts/bootstrap'; files = @('install.ps1') })
- output = 'artifacts/docs/orchestra-site'
- template = @('default', 'modern', 'Shared/Docs/Template')
- globalMetadata = [ordered]@{
- _appName = 'StellarEngine'
- _appTitle = "StellarEngine $orchestra"
- _appFooter = 'StellarEngine by QuantumDevTeam'
- _appLogoPath = 'Shared/Branding/stellar_icon.svg'
- _appFaviconPath = 'Shared/Branding/stellar_icon.svg'
- _enableSearch = $true
- }
- }
-}
-[System.IO.File]::WriteAllText($project_, ($project | ConvertTo-Json -Depth 10), [System.Text.UTF8Encoding]::new($false))
-
-Write-Host "Orchestra site project: $project_ (core + $($componentNavigation.Count) component site(s))" -ForegroundColor Green
diff --git a/scripts/prometheus.ps1 b/scripts/prometheus.ps1
new file mode 100644
index 0000000..9dbdc79
--- /dev/null
+++ b/scripts/prometheus.ps1
@@ -0,0 +1,98 @@
+<#
+.SYNOPSIS
+ Writes prometheus.json: what the docs site publishes from this tree.
+
+.DESCRIPTION
+ The docs workflow of every repository builds a bundle of its documentation for the docs site, as prometheus.json
+ at the root says (Docs/Engine/Documentation.md). The core commits a small prometheus.json that names this script
+ as "prepare": the workflow runs it first, and it writes the full description in place.
+
+ It knows the layout of the engine, so that the workflow does not:
+ the core Docs/ without Docs/Engine, the API of docfx.json; links into Docs/Engine go to the guide of the
+ engine
+ the mirror (a .orchestra file at the root) the whole engine: the guide (Docs/Engine), the core (Docs/ and
+ its API), and the Docs/ of every module and tool that has a toc.yml
+
+ The projects and the version come from Shared/Build/Stellar.Versions.props, the only place that names them.
+
+.PARAMETER Print
+ Writes the description to the output instead of prometheus.json, to look at it on a machine.
+
+.PARAMETER Output
+ Writes the description to this file instead of prometheus.json, to build a bundle on a machine without changing
+ the file of the repository. The docs workflow names the file in PROMETHEUS_CONFIG_OUT, which -Output overrides.
+#>
+param(
+ [switch]$Print,
+ [string]$Output = ''
+)
+
+$ErrorActionPreference = 'Stop'
+$root = Split-Path $PSScriptRoot -Parent
+
+$versions = [System.IO.File]::ReadAllText((Join-Path $root 'Shared/Build/Stellar.Versions.props'))
+function Get-Property([string]$Name) {
+ $value = [regex]::Match($versions, "<$Name>([^<]+)$Name>").Groups[1].Value
+ if (-not $value) { throw "$Name is missing from Shared/Build/Stellar.Versions.props" }
+ return $value
+}
+
+$coreProject = Get-Property 'StellarDocsProject'
+$engineProject = Get-Property 'StellarEngineDocsProject'
+$version = [ordered]@{ file = 'Shared/Build/Stellar.Versions.props'; xml = 'StellarOrchesterVersion' }
+$api = @([ordered]@{ docfx = 'docfx.json'; prefix = 'api' })
+
+if (Test-Path (Join-Path $root '.orchestra')) {
+ # The mirror: the whole engine in one bundle
+ $docs = [System.Collections.Generic.List[object]]::new()
+ $docs.Add([ordered]@{ path = 'Docs/Engine'; prefix = 'guide'; title = 'Guide' })
+ $docs.Add([ordered]@{ path = 'Docs'; prefix = 'core'; title = 'Core'; exclude = @('Engine/**') })
+
+ foreach ($area in 'modules', 'tools') {
+ $directory = Join-Path $root $area
+ if (-not (Test-Path $directory)) { continue }
+
+ foreach ($component in (Get-ChildItem $directory -Directory | Sort-Object Name)) {
+ # Hidden components (modules/_legacy) and the compilers of the installer are not components to publish
+ if ($component.Name.StartsWith('_') -or $component.Name.StartsWith('.')) { continue }
+ if (-not (Test-Path (Join-Path $component.FullName 'Docs/toc.yml'))) { continue }
+
+ $docs.Add([ordered]@{ path = "$area/$($component.Name)/Docs"; prefix = "$area/$($component.Name)"; title = $component.Name })
+ }
+ }
+
+ $description = [ordered]@{
+ format = 'prometheus-repo/1'
+ project = $engineProject
+ title = 'StellarEngine'
+ version = $version
+ docs = $docs
+ api = @([ordered]@{ docfx = 'docfx.json'; prefix = 'core/api' })
+ static = 'docfx.json'
+ }
+}
+else {
+ # The core: its own pages; the guide of the whole engine lives here too, but is published with the engine
+ $description = [ordered]@{
+ format = 'prometheus-repo/1'
+ project = $coreProject
+ title = 'StellarEngine-Core'
+ version = $version
+ docs = @([ordered]@{ path = 'Docs'; prefix = ''; exclude = @('Engine/**') })
+ api = $api
+ static = 'docfx.json'
+ links = [ordered]@{ 'Docs/Engine/' = "$engineProject/guide/" }
+ }
+}
+
+$json = $description | ConvertTo-Json -Depth 8
+if ($Print) {
+ $json
+ return
+}
+
+# The docs workflow says where the description goes, so that prometheus.json of the repository stays as it is
+if (-not $Output) { $Output = $env:PROMETHEUS_CONFIG_OUT }
+if (-not $Output) { $Output = Join-Path $root 'prometheus.json' }
+[System.IO.File]::WriteAllText([System.IO.Path]::GetFullPath($Output), $json + "`n", [System.Text.UTF8Encoding]::new($false))
+Write-Host "Wrote $Output for $($description.project)"