diff --git a/README.md b/README.md index 4ead821..b4a0747 100644 --- a/README.md +++ b/README.md @@ -21,6 +21,7 @@ The following tools are available under the [tools](tools) folder: | Tool | Folder | Description | |------|--------|-------------| +| `nano-migrate` (NanoMigrate) | [tools/migrate](tools/migrate) | Converts legacy `.nfproj` projects to SDK-style, single-repo or across an entire fleet. Driven by the companion [migration skill](skills/nanoframework-sdk-migration). | | `nanodu` (Dependency Updater) | [tools/DependencyUpdater](tools/DependencyUpdater) | Updates NuGet dependencies and related metadata for .NET nanoFramework solutions. | | `nanovc` (VersionCop) | [tools/VersionCop](tools/VersionCop) | Validates package version consistency and reports version mismatches in nanoFramework builds. | | `NanoProfiler` | [tools/Profiler](tools/Profiler) | Windows profiler application to inspect runtime and memory behavior of nanoFramework targets. | diff --git a/README.zh-cn.md b/README.zh-cn.md index 611f362..95a66c2 100644 --- a/README.zh-cn.md +++ b/README.zh-cn.md @@ -21,6 +21,7 @@ | 工具 | 文件夹 | 描述 | |------|--------|------| +| `nano-migrate` (NanoMigrate) | [tools/migrate](tools/migrate) | 将旧式 `.nfproj` 项目转换为 SDK 风格,支持单仓库或整个仓库集群。由配套的[迁移技能](skills/nanoframework-sdk-migration)驱动。 | | `nanodu` (Dependency Updater) | [tools/DependencyUpdater](tools/DependencyUpdater) | 更新 .NET nanoFramework 解决方案中的 NuGet 依赖项及相关元数据。 | | `nanovc` (VersionCop) | [tools/VersionCop](tools/VersionCop) | 校验包版本一致性,并报告 nanoFramework 构建中的版本不匹配。 | | `NanoProfiler` | [tools/Profiler](tools/Profiler) | 用于分析 nanoFramework 目标设备运行时和内存行为的 Windows 分析工具。 | diff --git a/azure-pipelines.yml b/azure-pipelines.yml index af4c9ef..04c7d51 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -64,6 +64,7 @@ jobs: echo "##vso[task.setvariable variable=BUILD_NANOVC;isOutput=true]false" echo "##vso[task.setvariable variable=BUILD_NANODU;isOutput=true]false" echo "##vso[task.setvariable variable=BUILD_PROFILER;isOutput=true]false" + echo "##vso[task.setvariable variable=BUILD_MIGRATE;isOutput=true]false" if( ($files.where{$_.Contains('tools/VersionCop')}).Count -gt 0) { @@ -88,7 +89,15 @@ jobs: Write-host "Building Profiler" } - + + if( ($files.where{$_.Contains('tools/migrate')}).Count -gt 0) + { + # files at NanoMigrate tool folder + echo "##vso[task.setvariable variable=BUILD_MIGRATE;isOutput=true]true" + + Write-host "Building migrate" + } + name: TargetsToBuild displayName: Get targets to build @@ -399,6 +408,139 @@ jobs: configuration: 'Release' maximumCpuCount: true +############## +- job: Build_Migrate + condition: >- + or( + eq(dependencies.Check_Build_Options.outputs['TargetsToBuild.BUILD_MIGRATE'], true), + eq(variables['BUILD_MIGRATE'], 'true') + ) + dependsOn: + Check_Build_Options + + pool: + vmImage: 'windows-2022' + + variables: + - group: sign-client-credentials + - name: DOTNET_NOLOGO + value: true + + steps: + + - checkout: self + persistCredentials: true + + - template: azure-pipelines-templates/install-nuget.yml + + - task: NuGetCommand@2 + displayName: Restore NuGet packages + condition: succeeded() + retryCountOnTaskFailure: 5 + inputs: + restoreSolution: $(System.DefaultWorkingDirectory)/tools/migrate/NanoMigrate.sln + feedsToUse: select + includeNuGetOrg: true + + - script: dotnet build NanoMigrate.sln -c Release -p:Platform="Any CPU" -p:PublicRelease=true --no-restore /t:build,pack + displayName: Build NuGet packages + condition: succeeded() + workingDirectory: '$(System.DefaultWorkingDirectory)/tools/migrate' + + - task: DotNetCoreCLI@2 + condition: succeeded() + displayName: 'Running Unit Tests' + inputs: + command: 'test' + projects: | + tools/migrate/**/*Tests.csproj + !**/obj/** + !**/bin/**/ref/** + arguments: '--configuration Release --no-build' + testRunTitle: 'NanoMigrate Unit Tests' + + - task: CopyFiles@1 + condition: succeeded() + displayName: Collecting deployable artifacts + inputs: + sourceFolder: $(Agent.BuildDirectory) + Contents: | + **\nanoFramework.Migrate.*.nupkg + TargetFolder: '$(Build.ArtifactStagingDirectory)' + flattenFolders: true + + - task: PowerShell@2 + condition: >- + and( + succeeded(), + eq(variables['StartReleaseCandidate'], false), + not(startsWith(variables['Build.SourceBranch'], 'refs/tags/v')) + ) + displayName: Check deployable artifacts + inputs: + targetType: 'inline' + script: | + + $artifacts = (Get-ChildItem -Path "$env:Build_ArtifactStagingDirectory" -Recurse) + + if ($artifacts.Count -eq 0) + { + Write-Error "No deployable artifacts found!" + Exit 1 + } + + - task: DotNetCoreCLI@2 + displayName: Install Sign Client CLI + condition: succeeded() + inputs: + command: custom + custom: tool + arguments: install --tool-path . sign --version 0.9.1-beta.23530.1 + + - pwsh: | + .\sign code azure-key-vault ` + "**/*.nupkg" ` + --base-directory "$(Build.ArtifactStagingDirectory)" ` + --description ".NET nanoFramework Migrate" ` + --description-url "https://github.com/$env:Build_Repository_Name" ` + --azure-key-vault-tenant-id "$(SignTenantId)" ` + --azure-key-vault-client-id "$(SignClientId)" ` + --azure-key-vault-client-secret "$(SignClientSecret)" ` + --azure-key-vault-url "$(SignKeyVaultUrl)" ` + --azure-key-vault-certificate "$(SignKeyVaultCertificate)" ` + --timestamp-url http://timestamp.digicert.com + displayName: Sign packages + continueOnError: true + condition: succeeded() + + # publish artifacts (only possible if this is not a PR originated on a fork) + - task: PublishPipelineArtifact@1 + condition: succeeded() + displayName: Publish deployables artifacts + inputs: + targetPath: '$(Build.ArtifactStagingDirectory)' + artifactName: deployables + artifactType: pipeline + + # push NuGet packages to NuGet + # NOTE: publishing is gated off until these tools are ready for release. Set the + # pipeline variable PublishNanoTools=true to enable pushing the packages to NuGet. + - task: NuGetCommand@2 + displayName: Push NuGet packages to NuGet + condition: >- + and( + succeeded(), + eq(variables['System.PullRequest.PullRequestId'], ''), + eq(variables['PublishNanoTools'], 'true') + ) + continueOnError: true + inputs: + command: push + nuGetFeedType: external + packagesToPush: '$(Build.ArtifactStagingDirectory)/*.nupkg' + includeSymbols: true + publishFeedCredentials: 'NuGet-$(System.TeamProject)' + ################################## # report build failure to Discord - job: Report_Build_Failure @@ -407,12 +549,14 @@ jobs: - Build_VersionCop - Build_DependencyUpdater - Build_NanoProfiler + - Build_Migrate condition: >- or( failed('Check_Build_Options'), failed('Build_VersionCop'), failed('Build_DependencyUpdater'), - failed('Build_NanoProfiler') + failed('Build_NanoProfiler'), + failed('Build_Migrate') ) pool: diff --git a/skills/nanoframework-sdk-migration/SKILL.md b/skills/nanoframework-sdk-migration/SKILL.md new file mode 100644 index 0000000..2fc2a66 --- /dev/null +++ b/skills/nanoframework-sdk-migration/SKILL.md @@ -0,0 +1,148 @@ +--- +name: nanoframework-sdk-migration +description: >- + Migrate .NET nanoFramework projects from the legacy custom .nfproj project system to the + SDK-style MSBuild project system (, netnano1.0, + PackageReference). Use whenever converting a nanoFramework library or app to SDK-style, + folding packages.config into PackageReference or .nuspec into MSBuild Pack properties, or + bulk-migrating many repos at once (the nanoframework/lib-* fleet). Trigger for any mention of + ".nfproj", "SDK-style nanoFramework", "convert nfproj to csproj", "migrate the nano + libraries", or a fleet/bulk migration — even if the word "skill" is never used. + SCOPE: project-system migration only; this does NOT cover OTA updates or modular firmware + packaging. +--- + +# nanoFramework SDK-style project migration + +Convert a nanoFramework repo from the legacy-flavored `.nfproj` project system onto SDK-style +projects that compose over `nanoFramework.NET.Sdk`. The mechanical conversion is done by the +**NanoMigrate** tool (in this repo at `tools/migrate`, surfaced as `dotnet nano migrate`). The +tool is **idempotent + reentrant**: it skips already-SDK-style projects and re-running over a tree +is a safe no-op, so a partial or repeated migration is never destructive. + +The full, as-built command/option reference is [`tools/migrate/README.md`](../../tools/migrate/README.md) +(and [`tools/nano/README.md`](../../tools/nano/README.md) for the umbrella). It is the source of +truth; this skill is the workflow guide. **Always confirm the live surface with `--help`** — it +matches the installed version exactly: + +```bash +dotnet nano --help # every command +dotnet nano migrate --help # options for one command +``` + +## Scope — read this first + +Project-system migration **only**. Do not add, and do not ask the tool to touch: OTA update +artifacts, modular/firmware packaging, `runtimes/{rid}/native` layouts, or ABI manifests. The +exact per-project transformation rules are in +[references/migration-rules.md](references/migration-rules.md); contribution + PR conventions are +in [references/contributing-compliance.md](references/contributing-compliance.md). + +## Commands at a glance + +Run any of these as `dotnet nano ` (umbrella) or `nano-migrate ` (standalone) — +or from source with `dotnet run --project tools/migrate/src/NanoMigrate.Cli -- `. + +| Command | What it does | +|---|---| +| `migrate ` | Convert a `.nfproj`, a solution (`.sln`/`.slnx`), or every `.nfproj` under a directory. | +| `clean [path]` | Remove migration leftovers: `*.nfproj.bak` files and `.nanomigrate/` rollback folders. | +| `rollback [path]` | Revert the last recorded migration (restore originals, delete created projects). | +| `clone [out-dir]` | Clone all matching repos from a GitHub org (fleet prep). *Standalone CLI only.* | +| `fleet ` | Migrate every `.nfproj` across cloned repos; write a report; optionally branch + commit. *Standalone CLI only.* | + +Key `migrate` options (see `migrate --help` / the README for the rest): `--dry-run`, `--glob

`, +`--solution

`, `--ext .csproj|.nfproj`, `--no-backup`, `--report `, +`--verify`/`--no-verify`, `-y|--yes`. + +## Always test a directory first, then migrate for real + +1. **Dry-run** to preview every change (writes nothing): + ``` + dotnet nano migrate --dry-run + # or, from this repo: dotnet run --project tools/migrate/src/NanoMigrate.Cli -- migrate --dry-run + ``` + Review the preview table: the target `.csproj`, the resolved `PackageReference`s, the files + that would be deleted, the `.sln` edits, and anything in the yellow **manual review** panel. +2. **Scope** with a glob if you only want part of the tree (`*`, `**`, `?`; relative to ``): + ``` + dotnet nano migrate --glob "Beginner/**" --dry-run + ``` +3. **Run for real** once the preview is right: + ``` + dotnet nano migrate # interactive: confirms once. Add --yes for CI/unattended. + ``` +4. **Re-run is safe** — reentrant. A partially-converted tree converts only the remaining + `.nfproj` and leaves existing `.csproj` untouched. + +A real run **verifies by default**: after converting, it builds the affected solution(s)/project(s) +and, on a failed build, offers to roll the whole run back (interactive) or tells you to run +`rollback` later (non-interactive). Use `--no-verify` to skip it. Add `--report ` to emit a +record of what changed — `.md`/`.markdown` → Markdown, `.html`/`.htm` → HTML — which also works +under `--dry-run` (it reports what *would* change). + +## Solutions (.sln / .slnx) + +Migration is solution-aware and keeps solutions in sync: + +- **Pass a solution** (`migrate .sln` or `.slnx`) to convert only the projects it references + and retarget the solution itself (classic `.sln`: project-type GUID + `.nfproj`→`.csproj`; + `.slnx`: the `Path`). +- **Pass a directory**: if it contains solutions you are asked to pick which one(s) to migrate + (all / none / several); if it contains none, every `.nfproj` under it is converted (loose mode). +- **With `--glob`**: the tool finds the matching projects, discovers the solutions that reference + them, and (after you confirm / select) updates only those solutions. +- `--solution ` forces a single target; `--yes` (or non-interactive) selects all affected. + +## What the tool does per project + +(Full detail in [references/migration-rules.md](references/migration-rules.md).) + +- Emits `` with `netnano1.0`. +- Maps `packages.config` / HintPath versions to `PackageReference` — the package id comes from the + `packages\.\` folder, so nano package ids resolve correctly (not the bare assembly + name). +- Folds `.nuspec` metadata into MSBuild `Pack` properties. +- Deletes `packages.config` and a hand-written `Properties/AssemblyInfo.cs` (the SDK generates it). +- Rewrites the `.sln` entry: project-type GUID → the SDK C#/CPS GUID, path `.nfproj` → `.csproj`. +- Writes a `.nfproj.bak` backup (unless `--no-backup`). + +## Manual review + +Entries in the yellow "manual review" panel did not resolve automatically — typically a +`` with no HintPath and no matching `packages.config` entry. Add the right +`PackageReference` by hand, then re-run (a no-op for everything already converted). + +## Back up, roll back, clean up + +- Each real conversion writes a `.nfproj.bak` next to the project (suppress with `--no-backup`). +- Independently, a real run records a **self-contained rollback journal** under `.nanomigrate/`. + `rollback [path]` reverts the last recorded migration (restore originals, delete created files); + it's idempotent — no journal means "nothing to roll back", exit 0. +- When you're satisfied with a migration, `clean [path]` removes the leftovers — every + `*.nfproj.bak` and every `.nanomigrate/` folder — so you don't commit a pile of backups. Both + preview before deleting; add `-y|--yes` to skip the prompt. + +## Fleet migration (many repos) + +Two steps — `clone` to fetch the repos, `fleet` to migrate them (`clone`/`fleet` are in the +standalone `nano-migrate` CLI). From source: + +``` +# 1) clone a GitHub org's matching repos (default org nanoframework, filter lib-) +dotnet run --project tools/migrate/src/NanoMigrate.Cli -- clone ./nano-repos --token $GITHUB_TOKEN + +# 2) dry-run the whole fleet and read the report before changing anything +dotnet run --project tools/migrate/src/NanoMigrate.Cli -- fleet ./nano-repos --dry-run --report fleet-report.md + +# 3) apply on a branch and commit, so each repo ends up ready to PR +dotnet run --project tools/migrate/src/NanoMigrate.Cli -- fleet ./nano-repos \ + --branch sdk-migration --commit --issue --report fleet-report.md +``` + +`fleet` walks each repo, converts every matching `.nfproj`, writes the report, and (with +`--branch`/`--commit`) commits a contribution-compliant, signed-off message; `--commit` implies +`--no-backup`. It stops at the commit — it never pushes or opens PRs. Open PRs from the +nanoFramework org template — see +[references/contributing-compliance.md](references/contributing-compliance.md). Convert leaf-first +(dependencies before dependents); branch names must not start with `develop`; never target `main`. diff --git a/skills/nanoframework-sdk-migration/references/contributing-compliance.md b/skills/nanoframework-sdk-migration/references/contributing-compliance.md new file mode 100644 index 0000000..493a185 --- /dev/null +++ b/skills/nanoframework-sdk-migration/references/contributing-compliance.md @@ -0,0 +1,167 @@ +# Contributing-compliance rules for migration PRs + +These rules make a migration land as a contribution the nanoFramework project +will accept. They are distilled from the official contributing docs: + +- Contribution workflow — +- C# Coding Style — +- Labels — +- Contributor License Agreement — + +Treat this as the checklist the migration must satisfy before a PR goes up. The +`nano-migrate` tool enforces the parts it can (commit format, sign-off, branch +naming); the rest is on the contributor. + +## Contents + +- [Before you start](#before-you-start) +- [Branching](#branching) +- [Scope of the change](#scope-of-the-change) +- [Commits](#commits) +- [Build and test clean](#build-and-test-clean) +- [Opening the PR](#opening-the-pr) +- [C# coding style (only if you touch .cs)](#c-coding-style-only-if-you-touch-cs) +- [What the tool does vs. what you do](#what-the-tool-does-vs-what-you-do) + +## Before you start + +- **Sign the CLA.** Every contribution (code, config, docs — including a project + migration) requires a signed Contributor License Agreement. Without it the PR + cannot be merged. +- **Use your real name.** Commits must use a real name; anonymous or pseudonymous + contributions are not accepted. Set it once: + `git config --global user.name "Your Real Name"` and a real + `git config --global user.email`. +- **File or find an issue for non-trivial work.** A fleet-wide project-system + migration is not trivial — open a tracking issue (or reuse one) and get team + agreement before opening PRs. Trivial one-off fixes can skip this. +- **Work from a fork.** The project uses a fork-based workflow: fork the repo, + clone your fork, add `upstream` pointing at `nanoframework/`, and sync + `main` from upstream before branching. + +## Branching + +- Branch off **`main`**: `git checkout -b main`. +- Name the branch for its intent, e.g. `sdk-migration` or `issue-123`. +- **Never** start a branch name with `develop` — it collides with upstream + `develop-*` branches. (`nano-migrate fleet` refuses such names.) + +## Scope of the change + +- This migration is a **structural** change to the project system, not a style + change. That is allowed. **Do not** bundle in code reformatting or style-only + edits — the project explicitly does **not** accept style-only PRs and asks + contributors to preserve the existing style of any file they touch. +- **Do not modify `.cs` source** as part of the migration. `nano-migrate` only + rewrites `.nfproj`, `packages.config`, and `.nuspec`; keep it that way. If a + repo genuinely needs a code change, that is a separate PR with its own issue. +- **Keep `.editorconfig`.** Each repo carries an `.editorconfig` (and + `spelling_exclusion.dic`) from the project template that encodes the style + rules. Don't delete or reformat around it. If a repo is missing it, copy the + current one from the `.github` template repo rather than inventing one. +- **Generated project XML**: the rule for non-code files is consistency. The + SDK-style project the tool emits uses standard two-space MSBuild indentation, + which is the broadly-accepted convention for a brand-new SDK-style file. +- **Versioning**: the tool does not fold `` from `.nuspec`. Leave the + repo's existing versioning (typically Nerdbank.GitVersioning via `version.json`) + in place; don't hard-code a version into the project. + +## Commits + +Format every commit like this (the tool does this automatically for fleet +commits): + +```text +Summarize the change in 50 characters or less + +Body explaining what changed and why, wrapped at 72 columns. For a +migration: what was converted and that there are no functional code +changes. + +Fix # + +Signed-off-by: Your Real Name +``` + +- Summary line **≤ 50 characters**, body wrapped at **72**. +- Reference the tracking issue with a `Fix #` trailer when there is one + (`nano-migrate ... --issue `). +- Include a **`Signed-off-by`** line (`git commit -s`). The tool signs off by + default; this requires a configured real name/email. +- **Factor commits sensibly** — not one giant commit of unrelated things, not a + swarm of tiny ones. Rebase away accidental whitespace/reformatting before the + PR. A clean migration is usually a single commit per repo. + +## Build and test clean + +A migration is not done until the repo **builds clean and all tests pass**: + +- `dotnet build` (or the repo's build) must restore and build with no errors. +- Run the repo's unit tests; they must pass, including any that exercise the + migrated project. +- Rebase on `upstream/main` if upstream moved while you worked, then re-build and + re-test before pushing. + +Do not open (or mark ready) a PR whose build is red. + +## Opening the PR + +- Push the branch to **your fork**, then open a PR against the upstream repo's + **`main`** branch. The tool stops at the local commit — it does not push or + open PRs; do that with the maintainers' normal flow. +- **Follow the PR template** that GitHub shows; it doubles as a submission + checklist. Fill in every section. +- A migration PR is typically **`area-Config-and-Build`** (project system / + build). For org-wide tooling/coordination, `area-Infrastructure-and-Organization` + may also apply. Maintainers manage the lifecycle labels (`code review`, + `do not merge`, `merge OK`); you generally don't set those yourself. +- It's fine to open a **`[WIP]`** PR early to start feedback, and it's fine to be + asked to **squash** commits before merge. +- Expect review comments — they are normal and not a rejection. Resolve feedback + and keep the branch building green. + +## C# coding style (only if you touch .cs) + +The migration should not change `.cs` files. But if you must (e.g. you drop a +hand-written `Properties/AssemblyInfo.cs` and need to re-express a custom +assembly attribute, or add a small fix), the change must follow the project's C# +style. Key rules: + +- **Visual Studio defaults**, Allman braces (each brace on its own line), braces + even on single-line blocks, **4 spaces** indentation, no tabs. +- `_camelCase` for private/internal fields; `s_` for static, `t_` for thread + static; `static readonly` (in that order) where possible. +- Always state visibility, visibility first (`private string _foo`, `public + abstract`). Avoid `this.` unless required. +- `using` directives at the top, outside the namespace, sorted alphabetically. +- Use language keywords, not BCL type names (`int`, `string`, not `Int32`, + `String`). Use `var` only when the type is obvious. Use `nameof(...)` over + string literals. `PascalCase` for constants. +- One empty line maximum between members; a blank line after a closing `}` unless + another `}` or an `else`/continuation follows; no spurious whitespace. +- **XML doc comments (`///`) on all public members**, including params and + returns. Prefer documenting exceptions in the comment and keep thrown-exception + message strings empty to save PE space (except for tooling like `nanoff`). +- **Include the file license header** (the two-line simplified form is fine). +- Prefer full words over abbreviations; for accepted acronyms follow Pascal + casing (`HttpSomething`, not `HTTPSomething`). +- If an existing file already uses a different convention (e.g. `m_member`), keep + that file's existing style. + +Re-run the project's `.editorconfig` formatting (in VS, `Ctrl+K, Ctrl+D`) before +committing any code change. + +## What the tool does vs. what you do + +| Requirement | `nano-migrate` | You | +|--------------------------------------|-----------------------|-----| +| Convert project files | ✅ automatic | | +| Commit message format (50/72, Fix #) | ✅ `--issue` | | +| `Signed-off-by` sign-off | ✅ default (needs real name in git config) | | +| Reject `develop*` branch names | ✅ guard | | +| Leave `.cs` and `.editorconfig` alone| ✅ by design | | +| Sign the CLA | | ✅ | +| Open/track the issue | | ✅ | +| Build clean + tests pass | | ✅ | +| Push to fork, open PR, fill template | | ✅ | +| Apply/respond to review | | ✅ | diff --git a/skills/nanoframework-sdk-migration/references/migration-rules.md b/skills/nanoframework-sdk-migration/references/migration-rules.md new file mode 100644 index 0000000..9ff7b4f --- /dev/null +++ b/skills/nanoframework-sdk-migration/references/migration-rules.md @@ -0,0 +1,156 @@ +# Migration rules reference + +The precise rules the converter (`tools/migrate`) applies, the reasoning +behind each, and the edge cases you may meet. Read this when a `MANUAL REVIEW +NEEDED` item appears, when output looks surprising, or when changing the rules. + +## Contents + +- [Property handling](#property-handling) +- [Reference and package handling](#reference-and-package-handling) +- [Compile items and AssemblyInfo](#compile-items-and-assemblyinfo) +- [Other item types](#other-item-types) +- [.nuspec folding](#nuspec-folding) +- [File operations and safety](#file-operations-and-safety) +- [Fail-loud philosophy](#fail-loud-philosophy) +- [Dependency ordering for the fleet](#dependency-ordering-for-the-fleet) +- [Things intentionally out of scope](#things-intentionally-out-of-scope) + +## Property handling + +The legacy project carries properties that the SDK now supplies, plus boilerplate +the flavored project system needed. These are **dropped**: + +`ProjectTypeGuids`, `ProjectGuid`, `FileAlignment`, `AppDesignerFolder`, +`NanoFrameworkProjectSystemPath`, `TargetFrameworkVersion`, `OldToolsVersion`, +`Configuration`, `Platform`. + +`TargetFrameworkVersion` (`v1.0`) is replaced by a single `` +(default `netnano1.0`, override with `--tfm`). `Configuration`/`Platform` defaults +come from the SDK. The `NFProjectSystem` import disappears entirely — the +`Sdk="nanoFramework.Sdk/"` attribute replaces it. + +These are **carried through verbatim** when present: + +`RootNamespace`, `AssemblyName`, `DocumentationFile`, `DefineConstants`, +`LangVersion`, plus packaging metadata `Description`, `Authors`, `PackageTags`, +`Copyright`. + +Any other property is **not** copied. If a repo relies on an unusual property, +add it back by hand after reviewing whether the SDK already provides it. (This is +a conservative default: copying unknown properties blindly risks dragging legacy +assumptions into the SDK build.) + +## Reference and package handling + +The legacy system used `` items resolved through `packages.config`. +The SDK system uses ``. Conversion: + +1. For each ``, strip any assembly-name suffix after a + comma, giving the bare name `X`. +2. Apply legacy aliases: `mscorlib` and `System` both map to the package + `nanoFramework.CoreLibrary`, because the legacy reference name does not match + the NuGet package id. +3. Resolve the version from `packages.config` (by package id, then by the raw + reference name). +4. If that fails, **fall back** to inferring the version from the `HintPath` + folder segment (e.g. `packages\nanoFramework.CoreLibrary.1.15.0\lib\...` → + `1.15.0`). This inference is always flagged for review so a human confirms it. +5. If neither works, emit a review line and leave the reference for manual mapping. + +`` items already present are carried through (version taken from +the item, else from `packages.config`). `PackageReference`s are emitted sorted by +package id for stable diffs. + +## Compile items and AssemblyInfo + +SDK-style projects glob `**/*.cs` by default, so explicit `` items for +files the glob already covers are redundant and are **dropped**. The rule: + +- A `Compile Include="Foo.cs"` (top-level, no folder separator) → dropped. +- A `Compile Include="Internal\Helper.cs"` (in a subfolder) → **kept**, because + legacy projects sometimes list files that the default glob would still pick up + but whose presence is load-bearing in unusual layouts; preserving them is the + safe choice. +- A `Compile` with a `Link` attribute → kept (it is a linked file, not a default). +- `Properties\AssemblyInfo.cs` → **dropped even though it is hand-written**, + because the SDK's `GenerateAssemblyInfo` produces assembly attributes and a + checked-in `AssemblyInfo.cs` causes duplicate-attribute build errors. If the + repo needs custom assembly attributes, set them as MSBuild properties + (``, ``, etc.) or disable `GenerateAssemblyInfo` deliberately. + +## Other item types + +- `None Include="packages.config"` and `None Include="*.nuspec"` → dropped (both + are obsolete after migration). +- Other `None`, plus `EmbeddedResource` and `Content` → kept verbatim (attributes + preserved, emitted self-closing). +- `ProjectReference` → kept verbatim. +- Any other item element → emitted as a review line ("Unhandled item…") so a + human decides. The tool does not silently drop or transform unknown items. + +## .nuspec folding + +If a `.nuspec` sits next to the project, its `` is mapped into MSBuild +Pack properties so `dotnet pack` reproduces the package: + +| .nuspec | MSBuild property | +|----------------|-----------------------| +| `id` | `PackageId` | +| `description` | `Description` | +| `authors` | `Authors` | +| `tags` | `PackageTags` | +| `projectUrl` | `PackageProjectUrl` | + +Existing project properties win (the fold uses set-if-absent), so a value already +on the project is not overwritten. `version` is intentionally **not** folded: +versioning is usually handled by Nerdbank.GitVersioning or a CI property, and +hard-coding it from an old `.nuspec` would regress that. Confirm the repo's +versioning strategy carries over. + +## File operations and safety + +- By default a `.nfproj.bak` is written next to each converted project. + `--no-backup` skips it; `fleet --commit` skips it automatically (git history is + the backup). +- With the default `--ext .nfproj`, the project is rewritten in place. With + `--ext .csproj`, a new `.csproj` is written and the original `.nfproj` is + removed. +- `packages.config` is deleted after its contents are folded into + `PackageReference`s. +- `--dry-run` performs the full analysis and prints the review list but writes + nothing and touches no git state — safe to run anywhere, any number of times. + +## Fail-loud philosophy + +The tool never guesses when it is unsure. Every uncertain case becomes a review +line rather than a silent transformation. This matters at fleet scale: a silent +wrong guess multiplied across 100+ repos is far more expensive than a review line +a human clears in seconds. When triaging a fleet report, treat the review list as +the real work and the clean set as already done. + +## Dependency ordering for the fleet + +Migrate leaf-first so a dependency is already available as an SDK-style package +when its dependents build: + +1. `nanoFramework.CoreLibrary` (the root; may need a special SDK variant). +2. Base/runtime libraries (`nanoFramework.Runtime.*`, `System.*` bindings). +3. Device and protocol libraries that depend on the base. +4. Higher-level IoT bindings and aggregates last. + +Within a single dry-run the order does not matter (nothing is published), but it +does matter for the publish/PR sequence: do not merge a dependent before the +dependency it relies on has shipped an SDK-style package. + +## Things intentionally out of scope + +The tool stops at the project system. It does not, and should not be extended to: + +- generate OTA update artifacts or manifests, +- produce `runtimes/{rid}/native/` layouts or relocatable native modules, +- emit ABI/module compatibility manifests, +- build firmware or invoke the metadata processor. + +Those belong to separate, later phases. Keeping this tool narrow is what makes it +safe to run unattended across the whole fleet. diff --git a/tools/migrate/NanoMigrate.sln b/tools/migrate/NanoMigrate.sln new file mode 100644 index 0000000..518f9b5 --- /dev/null +++ b/tools/migrate/NanoMigrate.sln @@ -0,0 +1,86 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 17 +VisualStudioVersion = 17.0.31903.59 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{827E0CD3-B72D-47B6-A68D-7590B98EB39B}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NanoMigrate.Core", "src\NanoMigrate.Core\NanoMigrate.Core.csproj", "{AEBCAB7C-FF89-4263-A46D-5802D29DD602}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NanoMigrate.Cli", "src\NanoMigrate.Cli\NanoMigrate.Cli.csproj", "{6560B18A-C816-4E38-B604-C4E771FD6534}" +EndProject +Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "tests", "tests", "{0AB3BF05-4346-4AA6-1389-037BE0695223}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NanoMigrate.Tests", "tests\NanoMigrate.Tests\NanoMigrate.Tests.csproj", "{2EB1343E-3AF7-4584-AE5D-606ADF7C891E}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "NanoMigrate.Cli.Commands", "src\NanoMigrate.Cli.Commands\NanoMigrate.Cli.Commands.csproj", "{838A3335-D3A2-4B3A-A69E-038CCB8CAB49}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|Any CPU = Release|Any CPU + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Debug|Any CPU.Build.0 = Debug|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Debug|x64.ActiveCfg = Debug|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Debug|x64.Build.0 = Debug|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Debug|x86.ActiveCfg = Debug|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Debug|x86.Build.0 = Debug|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Release|Any CPU.ActiveCfg = Release|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Release|Any CPU.Build.0 = Release|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Release|x64.ActiveCfg = Release|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Release|x64.Build.0 = Release|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Release|x86.ActiveCfg = Release|Any CPU + {AEBCAB7C-FF89-4263-A46D-5802D29DD602}.Release|x86.Build.0 = Release|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Debug|Any CPU.Build.0 = Debug|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Debug|x64.ActiveCfg = Debug|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Debug|x64.Build.0 = Debug|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Debug|x86.ActiveCfg = Debug|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Debug|x86.Build.0 = Debug|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Release|Any CPU.ActiveCfg = Release|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Release|Any CPU.Build.0 = Release|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Release|x64.ActiveCfg = Release|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Release|x64.Build.0 = Release|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Release|x86.ActiveCfg = Release|Any CPU + {6560B18A-C816-4E38-B604-C4E771FD6534}.Release|x86.Build.0 = Release|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Debug|x64.ActiveCfg = Debug|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Debug|x64.Build.0 = Debug|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Debug|x86.ActiveCfg = Debug|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Debug|x86.Build.0 = Debug|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Release|Any CPU.Build.0 = Release|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Release|x64.ActiveCfg = Release|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Release|x64.Build.0 = Release|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Release|x86.ActiveCfg = Release|Any CPU + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E}.Release|x86.Build.0 = Release|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Debug|Any CPU.Build.0 = Debug|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Debug|x64.ActiveCfg = Debug|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Debug|x64.Build.0 = Debug|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Debug|x86.ActiveCfg = Debug|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Debug|x86.Build.0 = Debug|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Release|Any CPU.ActiveCfg = Release|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Release|Any CPU.Build.0 = Release|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Release|x64.ActiveCfg = Release|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Release|x64.Build.0 = Release|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Release|x86.ActiveCfg = Release|Any CPU + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49}.Release|x86.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(NestedProjects) = preSolution + {AEBCAB7C-FF89-4263-A46D-5802D29DD602} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {6560B18A-C816-4E38-B604-C4E771FD6534} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + {2EB1343E-3AF7-4584-AE5D-606ADF7C891E} = {0AB3BF05-4346-4AA6-1389-037BE0695223} + {838A3335-D3A2-4B3A-A69E-038CCB8CAB49} = {827E0CD3-B72D-47B6-A68D-7590B98EB39B} + EndGlobalSection +EndGlobal diff --git a/tools/migrate/README.md b/tools/migrate/README.md new file mode 100644 index 0000000..57451f5 --- /dev/null +++ b/tools/migrate/README.md @@ -0,0 +1,206 @@ +# NanoMigrate — `nano-migrate` + +Convert legacy nanoFramework `.nfproj` projects to the SDK-style MSBuild project system — +one project, a whole directory/solution, or an entire cloned fleet of repositories. + +> **Scope: project-system migration only.** This tool moves a repo from the legacy flavored +> `.nfproj` format onto an SDK-style project that composes over `nanoFramework.NET.Sdk`, folds +> `packages.config` into `PackageReference`, and folds `.nuspec` metadata into MSBuild `Pack` +> properties. It does **not** touch OTA updates, modular firmware packaging, +> `runtimes/{rid}/native` layouts, or ABI manifests. + +The conversion is **idempotent and reentrant**: already-SDK-style projects are skipped and +re-running over a tree is a safe no-op, so a partial or repeated migration is never destructive. + +## Layout + +```text +tools/migrate/ + src/ + NanoMigrate.Core/ # conversion engine — console-free, unit-testable, NuGet-ready library + NanoMigrate.Cli.Commands/ # shared Spectre commands (migrate, clean, rollback) used by both front ends + NanoMigrate.Cli/ # the standalone `nano-migrate` CLI (adds clone + fleet) + tests/ + NanoMigrate.Tests/ # unit tests over NanoMigrate.Core +``` + +The engine (`NanoMigrate.Core`) has no `Console`/`AnsiConsole` dependency, so it is testable and +packable on its own. The same `migrate`/`clean`/`rollback` commands are shared with the +[`dotnet nano`](../nano/README.md) umbrella tool, so `nano-migrate migrate …` and +`dotnet nano migrate …` behave identically. + +### Packages + +| Package id | Command | What it is | +|---|---|---| +| `nanoFramework.Migrate.Core` | — | the console-free conversion engine (library) | +| `nanoFramework.Migrate` | `nano-migrate` | the standalone CLI (this tool) | +| `nanoFramework.Tool` | `dotnet nano` | the umbrella that also hosts `migrate` (see [../nano](../nano/README.md)) | + +## Install / run + +As a .NET global (or local) tool: + +```bash +dotnet tool install -g nanoFramework.Migrate # then: nano-migrate … +# or via the umbrella: +dotnet tool install -g nanoFramework.Tool # then: dotnet nano migrate … +``` + +From source in this repo (no separate build step needed): + +```bash +dotnet run --project tools/migrate/src/NanoMigrate.Cli -- [options] +``` + +For repeated fleet runs, build once and call the dll directly (faster): + +```bash +dotnet build -c Release tools/migrate/src/NanoMigrate.Cli +dotnet tools/migrate/src/NanoMigrate.Cli/bin/Release/net8.0/nano-migrate.dll [options] +``` + +Requires the **.NET 8 SDK**. The tool is BCL-only apart from Spectre.Console and the official +`Microsoft.VisualStudio.SolutionPersistence` solution reader/writer. + +## Discovering commands and options + +Everything below is also discoverable from the tool itself — prefer `--help` as the source of +truth, since it always matches the installed version: + +```bash +nano-migrate --help # list every command +nano-migrate migrate --help # options for one command +dotnet nano migrate --help # same surface via the umbrella +``` + +## Commands + +| Command | Summary | +|---|---| +| `migrate ` | Convert a `.nfproj`, a solution, or every `.nfproj` under a directory. | +| `clean [path]` | Remove migration leftovers: `*.nfproj.bak` files and `.nanomigrate/` rollback folders. | +| `rollback [path]` | Revert the last recorded migration under a path (restore originals, delete created projects). | +| `clone [out-dir]` | Clone all matching repos from a GitHub org (fleet prep). | +| `fleet ` | Migrate every `.nfproj` across cloned repos; write a report; optionally branch + commit. | + +`clone` and `fleet` are only in the standalone `nano-migrate` CLI; `migrate`, `clean`, and +`rollback` are shared with `dotnet nano`. + +### `migrate ` + +`` is a `.nfproj` file, a solution (`.sln`/`.slnx`), or a directory. + +- **Solution** → only its referenced `.nfproj` are converted and that solution is retargeted. +- **Directory with solutions** → you choose which solution(s) to migrate (interactive multi-select; + non-interactive / `--yes` selects all affected). +- **Directory with no solution** → every `.nfproj` under it is converted (loose mode); any solutions + found higher in the tree are retargeted automatically. + +| Option | Default | Meaning | +|---|---|---| +| `--solution ` | — | Migrate only this solution; overrides directory discovery. | +| `--glob ` | — | Only convert `.nfproj` whose path (relative to ``) matches; `*`, `**`, `?` supported (e.g. `"Beginner/**"`). Solutions referencing a matched project are updated. | +| `--tfm ` | `netnano1.0` | Target framework moniker. | +| `--ext ` | `.csproj` | Output extension: `.csproj` (retire `.nfproj`) or `.nfproj` (rewrite in place — lower-risk during a phased rollout). | +| `--no-backup` | off | Don't write a `.nfproj.bak`. Fully suppresses loose backups; the rollback journal stays self-contained in `.nanomigrate/`. | +| `--dry-run` (`--no-write`) | off | Analyse and preview only; write nothing. | +| `--verify` / `--no-verify` | on for real runs, off for `--dry-run` | After a real migration, build the affected solution(s)/project(s); a failed build offers a rollback. | +| `--report ` | — | Write a migration report. Format by extension: `.md`/`.markdown` → Markdown, `.html`/`.htm` → HTML (else Markdown). Works for `--dry-run` too. | +| `--sdk ` | (ignored) | Accepted for back-compat only; the SDK reference is versionless (pinned via `global.json` `msbuild-sdks`). | +| `-y\|--yes` | off | Skip interactive prompts and proceed with the default action. (Non-interactive runs never prompt regardless.) | + +**Exit codes:** `0` clean · `2` completed but some projects need manual review · `1` an error +occurred or a verification build failed (and changes were kept or rolled back per the prompt). + +### `clean [path]` + +Removes migration leftovers under a path: every `*.nfproj.bak` and every `.nanomigrate/` rollback +folder. Previews what will go and confirms before deleting (`-y|--yes` to skip the prompt; +non-interactive proceeds). `[path]` defaults to the current directory. This is the tidy-up step +after a migration you're happy with, so you don't commit a pile of `.bak` files. + +### `rollback [path]` + +Reverts the last recorded migration under a path by reading its `.nanomigrate/` rollback journal: +restores backed-up originals and deletes files the migration created. Idempotent and safe — with no +journal it reports "nothing to roll back" and exits `0`. `[path]` defaults to the current directory. + +### `clone [out-dir]` + +Clones all matching repositories from a GitHub org (the first half of a fleet migration). +`[out-dir]` defaults to `./nano-repos`. + +| Option | Default | Meaning | +|---|---|---| +| `--org ` | `nanoframework` | GitHub org to enumerate. | +| `--filter ` | `lib-` | Repo-name prefix to match. | +| `--token ` | `$GITHUB_TOKEN` | GitHub token to lift the unauthenticated API rate limit. | +| `--include-archived` | off | Include archived repositories (skipped by default). | + +### `fleet ` + +Migrates every `.nfproj` across a directory of cloned repos and writes a report. With `--branch` +(and optionally `--commit`) each repo ends up on a ready-to-PR branch. + +| Option | Default | Meaning | +|---|---|---| +| `--glob ` | — | Only convert matching `.nfproj` within each repo (`*`, `**`, `?`). | +| `--tfm ` | `netnano1.0` | Target framework moniker. | +| `--ext ` | `.csproj` | Output extension (`.csproj` or `.nfproj`). | +| `--no-backup` | off | Don't write `.nfproj.bak` (implied by `--commit` — git history already preserves the original). | +| `--dry-run` (`--no-write`) | off | Analyse and preview only. | +| `--report ` | `migration-report.md` | Report path (Markdown). | +| `--branch ` | — | Create/reset this git branch in each repo. Must not start with `develop`. | +| `--commit` | off | Commit the changes (requires `--branch`); writes a contribution-compliant message and signs off. | +| `--message ` | — | Commit summary line (kept ≤ 50 chars). | +| `--issue ` | — | Add a `Fix #` trailer to the commit. | +| `--no-sign-off` | off | Don't add a `Signed-off-by` line. | + +`fleet` stops at the commit — it never pushes or opens PRs. Migrate **leaf-first** (dependencies +before dependents) and open PRs from the org template (see the contribution guide). **Exit codes:** +`0` all clean · `2` one or more repos errored or need review. + +## What the conversion does (per project) + +- Emits `` with `netnano1.0`. +- Maps `packages.config` / `` HintPath versions to `` — the package id + comes from the `packages\.\` folder, so nano package ids resolve correctly rather + than the bare assembly name. Aliases legacy `mscorlib`/`System` to `nanoFramework.CoreLibrary`. +- Folds `.nuspec` metadata (`id`, `description`, `authors`, `tags`, `projectUrl`) into MSBuild + `Pack` properties. +- Deletes `packages.config` and a hand-written `Properties/AssemblyInfo.cs` (the SDK regenerates + it), while preserving non-default items (linked files, files in subfolders, `EmbeddedResource`, + `Content`). +- Rewrites the `.sln`/`.slnx` entry: project-type GUID → the SDK C#/CPS GUID, path `.nfproj` → + `.csproj`. Solutions are read/written through the official + `Microsoft.VisualStudio.SolutionPersistence` library. +- **Fails loud:** anything it cannot confidently resolve is written to a manual-review list instead + of being silently guessed. + +The exact rule set, including edge cases, lives in the skill at +[`skills/nanoframework-sdk-migration/references/migration-rules.md`](../../skills/nanoframework-sdk-migration/references/migration-rules.md). + +## Backups, the rollback journal, and verification + +- Each real conversion writes a `.nfproj.bak` next to the project (unless `--no-backup`). +- Independently, a real run records a **self-contained rollback journal** under `.nanomigrate/` + (`rollback-/` + `manifest.json`) that backs up every file the run modifies or deletes and + records every file it creates — this is what `rollback` and the post-verify rollback prompt use. +- With `--verify` (default for real runs) the affected solution(s)/project(s) are built after the + conversion; on failure you're offered an immediate rollback (interactive) or advised to run + `rollback` later (non-interactive). +- When you're done, `clean` removes both the loose `*.nfproj.bak` files and the `.nanomigrate/` + folders. + +## Tests + +```bash +dotnet test tools/migrate/tests/NanoMigrate.Tests +``` + +## See also + +- [`../nano/README.md`](../nano/README.md) — the `dotnet nano` umbrella tool that also hosts these commands. +- [`skills/nanoframework-sdk-migration`](../../skills/nanoframework-sdk-migration) — the installable + skill that drives this tool, with the full rule set and contribution/PR conventions. diff --git a/tools/migrate/nuget.config b/tools/migrate/nuget.config new file mode 100644 index 0000000..8edd5d5 --- /dev/null +++ b/tools/migrate/nuget.config @@ -0,0 +1,10 @@ + + + + + + + + diff --git a/tools/migrate/src/NanoMigrate.Cli.Commands/CleanCommand.cs b/tools/migrate/src/NanoMigrate.Cli.Commands/CleanCommand.cs new file mode 100644 index 0000000..0250077 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli.Commands/CleanCommand.cs @@ -0,0 +1,80 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.ComponentModel; +using nanoFramework.Migrate.Cli.Rendering; +using Spectre.Console; +using Spectre.Console.Cli; +using static nanoFramework.Migrate.Cli.Rendering.ConsoleSupport; + +namespace nanoFramework.Migrate.Cli.Commands; + +public sealed class CleanSettings : AssumeYesSettings +{ + [CommandArgument(0, "[path]")] + [Description("A directory (or file) under which migration leftovers are removed: " + + "all *.nfproj.bak files and any .nanomigrate/ rollback folders. Defaults to the current directory.")] + public string Path { get; init; } = "."; +} + +///

+/// Removes migration leftovers under a path: every *.nfproj.bak and every +/// .nanomigrate rollback folder/journal. Previews what will go and confirms +/// before deleting (skip with --yes; non-interactive proceeds). Pure file +/// logic lives in ; this is the thin presentation/prompt. +/// +public sealed class CleanCommand : Command +{ + protected override int Execute(CommandContext context, CleanSettings settings, CancellationToken cancellationToken) + { + Header("NanoMigrate · clean"); + + var root = System.IO.Path.GetFullPath(settings.Path); + var plan = BackupCleaner.Plan(root); + + if (plan.IsEmpty) + { + AnsiConsole.MarkupLine($"[grey]nothing to clean under '{Esc(root)}'.[/]"); + return 0; + } + + // Show exactly what will be deleted before any prompt. + var tree = new Tree($"[bold]Leftovers under[/] [blue]{Esc(root)}[/]"); + if (plan.BackupFiles.Count > 0) + { + var node = tree.AddNode($"[yellow]{plan.BackupFiles.Count}[/] backup file(s)"); + foreach (var f in plan.BackupFiles) + node.AddNode($"[grey]{Esc(System.IO.Path.GetRelativePath(root, f))}[/]"); + } + if (plan.RollbackFolders.Count > 0) + { + var node = tree.AddNode($"[yellow]{plan.RollbackFolders.Count}[/] rollback folder(s)"); + foreach (var d in plan.RollbackFolders) + node.AddNode($"[grey]{Esc(System.IO.Path.GetRelativePath(root, d))}[/]"); + } + AnsiConsole.Write(tree); + AnsiConsole.WriteLine(); + + if (!Confirm($"Delete {plan.Total} leftover item(s)?", settings.AssumeYes)) + { + AnsiConsole.MarkupLine("[grey]aborted; nothing deleted.[/]"); + return 0; + } + + var result = BackupCleaner.Remove(plan, cancellationToken); + foreach (var p in result.Problems) + AnsiConsole.MarkupLine($"[red]clean issue:[/] {Esc(p)}"); + + AnsiConsole.MarkupLine( + $"[green]removed {result.Total} item(s)[/] " + + $"([yellow]{result.RemovedBackups.Count}[/] backup file(s), " + + $"[yellow]{result.RemovedFolders.Count}[/] rollback folder(s))."); + return result.Problems.Count > 0 ? 1 : 0; + } + + private static bool Confirm(string question, bool assumeYes) + { + if (assumeYes || !IsInteractive()) return true; + return AnsiConsole.Confirm(question, defaultValue: false); + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli.Commands/MigrateCommand.cs b/tools/migrate/src/NanoMigrate.Cli.Commands/MigrateCommand.cs new file mode 100644 index 0000000..43c4d0c --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli.Commands/MigrateCommand.cs @@ -0,0 +1,522 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.ComponentModel; +using nanoFramework.Migrate.Cli.Rendering; +using Spectre.Console; +using Spectre.Console.Cli; +using static nanoFramework.Migrate.Cli.Rendering.ConsoleSupport; + +namespace nanoFramework.Migrate.Cli.Commands; + +/// +/// A small shared base so the migrate, clean and rollback +/// commands declare the common -y|--yes flag once. (The commands are sibling +/// top-level commands rather than subcommands of migrate because Spectre.Cli +/// cannot host a command that is both a branch/default AND takes a positional +/// argument, and migrate <path> must keep working.) +/// +public abstract class AssumeYesSettings : CommandSettings +{ + [CommandOption("-y|--yes")] + [Description("Skip interactive prompts: proceed with the default action. (Non-interactive runs never prompt regardless.)")] + public bool AssumeYes { get; init; } +} + +public sealed class MigrateSettings : AssumeYesSettings +{ + [CommandArgument(0, "")] + [Description("A .nfproj file, a solution (.sln/.slnx), or a directory. " + + "For a solution, only its referenced .nfproj are converted and the solution is retargeted. " + + "For a directory, discovered solutions drive the selection; with no solution found, every .nfproj under the directory is converted.")] + public string Path { get; init; } = ""; + + [CommandOption("--solution ")] + [Description("Migrate only this solution (.sln or .slnx): convert just its referenced .nfproj and retarget that one solution. Overrides directory discovery.")] + public string? Solution { get; init; } + + [CommandOption("--sdk ")] + [Description("Accepted for back-compat but ignored: the SDK reference is versionless (pinned via global.json msbuild-sdks).")] + public string Sdk { get; init; } = "2.0.0"; + + [CommandOption("--tfm ")] + [Description("Target framework moniker (default netnano1.0).")] + public string Tfm { get; init; } = "netnano1.0"; + + [CommandOption("--ext ")] + [Description("Output extension: .nfproj or .csproj (default .csproj).")] + public string Ext { get; init; } = ".csproj"; + + [CommandOption("--no-backup")] + [Description("Don't write a .nfproj.bak.")] + public bool NoBackup { get; init; } + + [CommandOption("--dry-run|--no-write")] + [Description("Analyse and preview only; write nothing.")] + public bool DryRun { get; init; } + + [CommandOption("--glob ")] + [Description("Only convert .nfproj whose path (relative to ) matches the glob; the solutions referencing any matched project are updated. Supports *, ** and ?. Example: \"Beginner/**\".")] + public string? Glob { get; init; } + + [CommandOption("--verify")] + [Description("After a real migration, build the affected solution(s)/project(s) to verify the result; a failed build offers a rollback. Default: on for real runs, off for --dry-run.")] + public bool Verify { get; init; } + + [CommandOption("--no-verify")] + [Description("Skip the post-migration build verification.")] + public bool NoVerify { get; init; } + + [CommandOption("--report ")] + [Description("Write a migration report to this path. The format is chosen by the extension: " + + ".md/.markdown -> Markdown, .html/.htm -> HTML (anything else -> Markdown). " + + "Works for --dry-run too (reports what WOULD change).")] + public string? Report { get; init; } + + public override ValidationResult Validate() + { + if (Ext is not (".nfproj" or ".csproj")) + return ValidationResult.Error("--ext must be .nfproj or .csproj"); + if (Verify && NoVerify) + return ValidationResult.Error("--verify and --no-verify are mutually exclusive"); + return ValidationResult.Success(); + } + + public ConversionOptions ToConversionOptions() => new() + { + Sdk = Sdk, + Tfm = Tfm, + Ext = Ext, + NoBackup = NoBackup, + DryRun = DryRun, + Glob = Glob, + // --verify forces on, --no-verify forces off, neither leaves the default + // (on for real runs, off for dry-run). + Verify = Verify ? true : NoVerify ? false : (bool?)null, + }; +} + +public sealed class MigrateCommand : Command +{ + private readonly IProjectConverter _converter = new ProjectConverter(); + + // Spectre hands a fresh command instance per invocation and cancels this token on + // Ctrl+C / console close; the conversion and verify helpers read it so a long run + // (convert + dotnet build) stops promptly. + private CancellationToken _cancellationToken; + + protected override int Execute(CommandContext context, MigrateSettings settings, CancellationToken cancellationToken) + { + _cancellationToken = cancellationToken; + Header("NanoMigrate"); + + var o = settings.ToConversionOptions(); + var plan = MigrationPlanner.Plan(settings.Path, settings.Solution, settings.Glob); + + // Solution-aware plans (explicit solution, directory-with-solutions, glob) + // are handled by their own path; loose/single plans keep the historical flow. + return plan.Kind switch + { + PlanKind.SingleProject or PlanKind.LooseDirectory => RunLoose(settings, o, plan), + _ => RunSolutionScoped(settings, o, plan), + }; + } + + // The historical flow: a single .nfproj or a directory with no solutions. The + // converter retargets any solutions it finds by walking up the tree. + private int RunLoose(MigrateSettings settings, ConversionOptions o, MigrationPlan plan) + { + var targets = plan.LooseProjects.ToList(); + + // Reentrant: a fully-converted tree has no .nfproj left. Exit cleanly (0). + if (targets.Count == 0) + { + var why = o.Glob is null + ? $"no .nfproj found under '{Esc(settings.Path)}' (already SDK-style?)." + : $"no .nfproj matched glob '{Esc(o.Glob)}' under '{Esc(settings.Path)}'."; + AnsiConsole.MarkupLine($"[grey]nothing to convert: {why}[/]"); + return 0; + } + + var baseDir = BaseDirFor(settings.Path); + + AnsiConsole.MarkupLine(o.DryRun + ? $"[yellow]Dry run[/] — analysing [bold]{targets.Count}[/] project(s) under [blue]{Esc(baseDir)}[/]. Nothing will be written." + : $"Found [bold]{targets.Count}[/] project(s) to convert under [blue]{Esc(baseDir)}[/]."); + AnsiConsole.WriteLine(); + + if (!Confirm($"Proceed with {targets.Count} conversion(s)?", settings, o)) return AbortedExit(); + + // Record a rollback journal (real runs only): back up every file the + // conversions will modify or delete BEFORE the converter touches disk. + var journal = OpenJournal(baseDir, o); + if (journal is not null) + RecordJournal(journal, targets, o, extraSolutions: null); + + var results = ProcessProjects(targets, baseDir, o); + journal?.Save(); + + var rewritten = Array.Empty(); + var report = Report(results, baseDir, o, rewritten); + + // Verification targets in loose mode are the converted projects themselves + // (no host-owned solution set). A failed verify can roll the run back. + var verifyTargets = results + .Where(r => r.Result.Status is ConvertStatus.Converted or ConvertStatus.Review) + .Select(r => r.Result.OutputPath) + .ToList(); + var reportCtx = new ReportContext(results, baseDir, o.DryRun, rewritten, settings.Report); + return VerifyAndMaybeRollback(report, verifyTargets, journal, baseDir, settings, o, reportCtx); + } + + // The solution-aware flow: pick the candidate solutions (multi-select / confirm), + // convert their .nfproj, then retarget exactly those solutions ourselves. + private int RunSolutionScoped(MigrateSettings settings, ConversionOptions o, MigrationPlan plan) + { + var baseDir = BaseDirFor(settings.Path); + + if (plan.Candidates.Count == 0) + { + AnsiConsole.MarkupLine("[grey]nothing to convert: the selected solution(s) reference no .nfproj (already SDK-style?).[/]"); + return 0; + } + + // Show what is in scope before any prompt. + MigrateRenderer.RenderCandidateSolutions(plan.Candidates, baseDir); + + var chosen = SelectSolutions(plan, settings, o); + if (chosen.Count == 0) + { + AnsiConsole.MarkupLine("[grey]aborted; no solution selected, nothing written.[/]"); + return 0; + } + + var targets = MigrationPlan.ProjectsOf(chosen); + if (targets.Count == 0) + { + AnsiConsole.MarkupLine("[grey]nothing to convert: the chosen solution(s) reference no .nfproj.[/]"); + return 0; + } + + AnsiConsole.MarkupLine(o.DryRun + ? $"[yellow]Dry run[/] — analysing [bold]{targets.Count}[/] project(s) across [bold]{chosen.Count}[/] solution(s). Nothing will be written." + : $"Converting [bold]{targets.Count}[/] project(s) across [bold]{chosen.Count}[/] solution(s)."); + AnsiConsole.WriteLine(); + + if (!Confirm($"Proceed with {targets.Count} conversion(s) and update {chosen.Count} solution(s)?", settings, o)) + return AbortedExit(); + + // The host owns solution retargeting here, so the converter must not also + // walk up and rewrite solutions the user did not select. + var convOpts = o with { SkipSolutionRewrite = true }; + + // Record a rollback journal (real runs only): back up the files the + // conversions touch PLUS the chosen solutions the host will rewrite itself. + var journal = OpenJournal(baseDir, o); + if (journal is not null) + RecordJournal(journal, targets, convOpts, extraSolutions: chosen.Select(c => c.Solution.Path)); + + var results = ProcessProjects(targets, baseDir, convOpts); + + // Retarget exactly the chosen solutions to the converted projects. Only + // projects that actually converted (a .csproj now exists / would exist) are + // handed to the rewriter; idempotent on re-run. + var converted = results + .Where(r => r.Result.Status is ConvertStatus.Converted or ConvertStatus.Review) + .Select(r => r.Nfproj) + .ToList(); + + var rewritten = new List(); + if (!o.DryRun && converted.Count > 0) + { + foreach (var c in chosen) + if (SolutionRewriter.RewriteFile(c.Solution, converted)) + rewritten.Add(c.Solution.Path); + } + + journal?.Save(); + var report = Report(results, baseDir, o, rewritten); + + // Verify by building exactly the chosen solutions. + var verifyTargets = chosen.Select(c => c.Solution.Path).ToList(); + var reportCtx = new ReportContext(results, baseDir, o.DryRun, rewritten, settings.Report); + return VerifyAndMaybeRollback(report, verifyTargets, journal, baseDir, settings, o, reportCtx); + } + + // Opens a rollback journal rooted at baseDir for real runs only; dry-runs return + // null (nothing is written, nothing to reverse). + private static RollbackJournal? OpenJournal(string baseDir, ConversionOptions o) => + o.DryRun ? null : RollbackJournal.Start(baseDir); + + // Backs up — into the journal — every file the conversions will modify or delete, + // and records the files they will create, by analysing each target with a dry-run + // preview pass FIRST (before any real write). extraSolutions are host-rewritten + // solutions to back up as well. + private void RecordJournal(RollbackJournal journal, List targets, ConversionOptions o, + IEnumerable? extraSolutions) + { + var dryOpts = o with { DryRun = true }; + var extras = extraSolutions?.ToList(); + foreach (var nf in targets) + { + ConvertResult preview; + try { preview = _converter.Convert(nf, dryOpts, _cancellationToken); } + catch { continue; } // a project that fails to analyse is converted (and reported) normally; just not journaled + if (preview.AlreadySdk) continue; + MigrationJournaling.Record(journal, preview, extras); + extras = null; // back up the host solutions once, not per project + } + } + + // Runs the verification build (when enabled) and, on failure, applies the rollback + // policy: prompt-and-revert interactively, or keep-and-advise non-interactively. + // Maps to the final exit code. When verification is off/clean, returns the + // already-computed migrate exit code unchanged. + private int VerifyAndMaybeRollback(int migrateExit, List verifyTargets, + RollbackJournal? journal, string baseDir, MigrateSettings settings, ConversionOptions o, + ReportContext reportCtx) + { + if (!o.VerifyEffective || verifyTargets.Count == 0) + { + WriteReportIfRequested(reportCtx, verify: null); + return migrateExit; + } + + var builder = new SolutionBuilder(); + List outcomes; + bool toolMissing = false; + if (IsInteractive()) + { + List? captured = null; + AnsiConsole.Status().Spinner(Spinner.Known.Dots).Start("Verifying build…", ctx => + captured = builder.VerifyAll(verifyTargets, + t => ctx.Status($"Building [blue]{Esc(Path.GetFileName(t))}[/]…"), + () => toolMissing = true, _cancellationToken)); + outcomes = captured!; + } + else + { + outcomes = builder.VerifyAll(verifyTargets, null, () => toolMissing = true, _cancellationToken); + } + + if (toolMissing) + AnsiConsole.MarkupLine("[yellow]warning:[/] dotnet not found on PATH — build verification skipped."); + + MigrateRenderer.RenderVerifyTable(outcomes, baseDir); + + // Write the report (when requested) now that the verify outcomes are known, so + // a single write covers the passed-and-failed paths alike. A subsequent + // rollback reverts files on disk but the report still records what was attempted. + WriteReportIfRequested(reportCtx, outcomes); + + var verifyOutcome = Verification.Evaluate(outcomes); + if (verifyOutcome != VerifyOutcome.Failed) + return migrateExit; + + var failed = Verification.FailedCount(outcomes); + AnsiConsole.WriteLine(); + AnsiConsole.MarkupLine($"[red]Build verification failed for {failed} target(s).[/]"); + + var interactive = IsInteractive() && !settings.AssumeYes; + bool? answer = null; + if (interactive) + answer = AnsiConsole.Confirm( + $"Migration verification failed for {failed} target(s). Roll back all changes?", defaultValue: false); + else if (settings.AssumeYes) + // --yes is about skipping prompts to PROCEED, never to silently destroy a + // migration; a failed verify under --yes keeps the changes (advise rollback). + answer = false; + + var decision = Verification.Decide(verifyOutcome, interactive, answer); + switch (decision) + { + case RollbackDecision.RollBack: + ApplyRollback(journal, baseDir); + AnsiConsole.MarkupLine("[green]All changes rolled back.[/]"); + return 1; + case RollbackDecision.KeepInteractive: + AnsiConsole.MarkupLine( + $"[yellow]Changes kept.[/] Run [bold]rollback \"{Esc(baseDir)}\"[/] later to revert."); + return 1; + case RollbackDecision.KeepNonInteractive: + default: + AnsiConsole.MarkupLine( + $"[yellow]Changes kept (non-interactive).[/] Run [bold]rollback \"{Esc(baseDir)}\"[/] to revert."); + return 1; + } + } + + // Reverts the just-recorded run from the live journal (preferred), falling back to + // the latest saved manifest under baseDir. Removes the backup set on success. + private static void ApplyRollback(RollbackJournal? journal, string baseDir) + { + RollbackResult? result = null; + if (journal is not null && !journal.IsEmpty && File.Exists(journal.ManifestPath)) + result = RollbackJournal.ApplyAndCleanup(journal.ManifestPath); + if (result is null) + { + var latest = RollbackJournal.ManifestPaths(baseDir).FirstOrDefault(); + if (latest is not null) result = RollbackJournal.ApplyAndCleanup(latest); + } + if (result is not null) MigrateRenderer.RenderRollbackResult(result, baseDir); + } + + // Decides which candidate solutions to operate on. Explicit single solution: no + // choice. Otherwise multi-select when interactive; non-interactive / --yes + // selects all affected (announcing it). + private static List SelectSolutions(MigrationPlan plan, MigrateSettings settings, ConversionOptions o) + { + // An explicit single solution (positional .sln/.slnx or --solution) is the + // only candidate; there is nothing to choose. + if (!plan.RequiresSelection) + return plan.Candidates.ToList(); + + var all = plan.Candidates.ToList(); + + // Only one affected solution: a simple confirm, not a multi-select. + if (all.Count == 1) + { + if (settings.AssumeYes || o.DryRun || !IsInteractive()) + { + if (!settings.AssumeYes && !o.DryRun) + AnsiConsole.MarkupLine("[grey]non-interactive: selecting the only affected solution.[/]"); + return all; + } + var fmt = all[0].Solution.Format == SolutionFormat.Xml ? "slnx" : "sln"; + return AnsiConsole.Confirm($"Migrate solution '{Esc(Path.GetFileName(all[0].Solution.Path))}' ({fmt})?") + ? all : new List(); + } + + // Several solutions: CI / non-interactive selects all and proceeds. + if (settings.AssumeYes || o.DryRun || !IsInteractive()) + { + if (!settings.AssumeYes && !o.DryRun) + AnsiConsole.MarkupLine($"[grey]non-interactive: selecting all {all.Count} affected solution(s).[/]"); + return all; + } + + // Interactive: present the multi-select. Picking none aborts cleanly. + var prompt = new MultiSelectionPrompt() + .Title("Select the solution(s) to migrate") + .NotRequired() // picking none is allowed (aborts) + .PageSize(15) + .InstructionsText("[grey](space to toggle, enter to confirm; pick none to abort)[/]") + .UseConverter(c => + { + var fmt = c.Solution.Format == SolutionFormat.Xml ? "slnx" : "sln"; + return $"{Path.GetFileName(c.Solution.Path)} ({fmt}, {c.NanoProjects.Count} project(s))"; + }); + prompt.AddChoices(all); + return AnsiConsole.Prompt(prompt); + } + + // The shared confirm gate. Returns true when we should proceed. In dry-run, when + // --yes is set, or in a non-interactive context we never block. + private static bool Confirm(string question, MigrateSettings settings, ConversionOptions o) + { + if (o.DryRun || settings.AssumeYes || !IsInteractive()) return true; + return AnsiConsole.Confirm(question); + } + + private static int AbortedExit() + { + AnsiConsole.MarkupLine("[grey]aborted; nothing written.[/]"); + return 0; + } + + // The base directory glob/relative paths are reported against. + private static string BaseDirFor(string path) => + Directory.Exists(path) ? Path.GetFullPath(path) + : File.Exists(path) ? Path.GetDirectoryName(Path.GetFullPath(path))! + : Path.GetFullPath(path); + + // Renders the summary/review/tally and (for solution-scoped runs) the rewritten + // solutions, then maps the outcome to the exit code (0 clean / 2 review / 1 error). + private static int Report(List results, string baseDir, ConversionOptions o, IReadOnlyList rewritten) + { + MigrateRenderer.RenderSummaryTable(results, baseDir, o.DryRun); + MigrateRenderer.RenderReviewNotes(results, baseDir); + MigrateRenderer.RenderRewrittenSolutions(rewritten, baseDir); + MigrateRenderer.RenderTally(results, o.DryRun); + + var errors = results.Count(r => r.Result.Status == ConvertStatus.Error); + var flagged = results.Count(r => r.Result.Status == ConvertStatus.Review); + if (errors > 0) return 1; + return flagged > 0 ? 2 : 0; + } + + // The data needed to render the optional migration report, carried from the + // outcome computation through the verify pass so a single write site can include + // the verify results when a verify pass ran. ReportPath is null when --report + // was not supplied. + private readonly record struct ReportContext( + IReadOnlyList Results, + string BaseDir, + bool DryRun, + IReadOnlyList Rewritten, + string? ReportPath); + + // Builds the MigrationReport from the same outcome/verify data the summary table + // used and writes it to the requested path (format chosen by extension), printing + // a Spectre line. A no-op when --report was not supplied. The caller (Core) owns + // the clock: the timestamp is captured here, not inside the engine. + private static void WriteReportIfRequested(ReportContext ctx, IReadOnlyList? verify) + { + if (string.IsNullOrWhiteSpace(ctx.ReportPath)) return; + + var report = MigrationReportBuilder.Build( + ctx.Results, ctx.BaseDir, ctx.DryRun, ctx.Rewritten, verify, DateTime.UtcNow); + + try + { + var format = MigrationReportBuilder.Write(report, ctx.ReportPath); + var kind = format == ReportFormat.Html ? "HTML" : "Markdown"; + AnsiConsole.MarkupLine($"[grey]{kind} report written to[/] [blue]{Esc(ctx.ReportPath)}[/]"); + } + catch (Exception ex) + { + AnsiConsole.MarkupLine($"[yellow]warning:[/] could not write report to [blue]{Esc(ctx.ReportPath)}[/]: {Esc(ex.Message)}"); + } + } + + // Runs every conversion, surfacing progress with a spinner. Any per-project + // exception is captured as an Error row rather than aborting the batch. + private List ProcessProjects(List targets, string baseDir, ConversionOptions o) + { + var results = new List(targets.Count); + + void RunAll(Action? report) + { + foreach (var nf in targets) + { + var rel = Path.GetRelativePath(baseDir, nf); + report?.Invoke(rel); + ConvertResult result; + try + { + result = _converter.Convert(nf, o, _cancellationToken); + } + catch (Exception ex) + { + result = new ConvertResult { OutputPath = nf, Error = ex.Message }; + } + results.Add(new ProjectOutcome(nf, result)); + } + } + + // Status() needs an interactive, non-redirected console; otherwise just + // run straight through (Spectre would no-op the spinner anyway). + if (IsInteractive()) + { + AnsiConsole.Status() + .Spinner(Spinner.Known.Dots) + .Start(o.DryRun ? "Analysing…" : "Converting…", ctx => + RunAll(rel => ctx.Status($"{(o.DryRun ? "Analysing" : "Converting")} [blue]{Esc(rel)}[/]…"))); + } + else + { + RunAll(null); + } + return results; + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli.Commands/MigrateRegistration.cs b/tools/migrate/src/NanoMigrate.Cli.Commands/MigrateRegistration.cs new file mode 100644 index 0000000..da3f681 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli.Commands/MigrateRegistration.cs @@ -0,0 +1,40 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Spectre.Console.Cli; + +namespace nanoFramework.Migrate.Cli.Commands; + +/// +/// Registers the migrate command surface once, so BOTH front ends — the standalone +/// nano-migrate exe and the umbrella nano tool — expose the same verbs: +/// migrate (the conversion, with a positional <path>), plus the +/// sibling clean and rollback commands. +/// +/// These are top-level commands rather than subcommands of migrate on purpose: +/// Spectre.Console.Cli (0.55) cannot host a default/branch command that ALSO takes a +/// positional argument (the first token is parsed as a subcommand selector, breaking +/// migrate <path>), and preserving migrate <path> is required. +/// +public static class MigrateRegistration +{ + /// + /// Adds migrate, clean and rollback to . + /// is the lead description for the migrate + /// verb, phrased by the host (nano or nano-migrate). + /// + public static void Add(IConfigurator config, string migrateDescription) + { + config.AddCommand("migrate") + .WithDescription(migrateDescription + " Related: 'clean' and 'rollback'.") + .WithExample("migrate", "./samples", "--glob", "Beginner/**", "--dry-run"); + + config.AddCommand("clean") + .WithDescription("Remove migration leftovers (*.nfproj.bak files and .nanomigrate/ rollback folders) under a path.") + .WithExample("clean", "./samples", "--yes"); + + config.AddCommand("rollback") + .WithDescription("Revert the last recorded migration under a path (restore originals, delete created projects).") + .WithExample("rollback", "./samples"); + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli.Commands/NanoMigrate.Cli.Commands.csproj b/tools/migrate/src/NanoMigrate.Cli.Commands/NanoMigrate.Cli.Commands.csproj new file mode 100644 index 0000000..5db680e --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli.Commands/NanoMigrate.Cli.Commands.csproj @@ -0,0 +1,62 @@ + + + + net10.0 + enable + enable + nanoFramework.Migrate.Cli + NanoMigrate.Cli.Commands + true + + + + + nanoFramework.Migrate.Cli.Commands + nanoFramework Migrate (shared Spectre command) + The shared `migrate` Spectre.Console.Cli command and its rendering, sitting over the nanoFramework.Migrate.Core engine. Referenced by both the standalone `nano-migrate` CLI and the `dotnet nano` umbrella tool so there is one MigrateCommand implementation. + nanoFramework + nanoFramework + https://github.com/nanoframework/nf-tools + https://github.com/nanoframework/nf-tools + git + MIT + nanoFramework;MSBuild;SDK;migration;nfproj;Spectre;IoT;embedded;C# + Copyright (c) .NET Foundation and Contributors + false + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/ConsoleSupport.cs b/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/ConsoleSupport.cs new file mode 100644 index 0000000..f2851a3 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/ConsoleSupport.cs @@ -0,0 +1,29 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Spectre.Console; + +namespace nanoFramework.Migrate.Cli.Rendering; + +/// Shared, low-level console helpers. The only consumers of AnsiConsole. +public static class ConsoleSupport +{ + // A "title rule" header. Spectre renders this as a centred rule when the + // terminal is wide enough, and degrades to plain text when redirected. + public static void Header(string title) + { + var rule = new Rule($"[bold]{Esc(title)}[/]") { Justification = Justify.Left }; + AnsiConsole.Write(rule); + AnsiConsole.WriteLine(); + } + + // Escapes interpolated text (notably file paths) so Spectre markup like + // "[" in a path can't be interpreted as styling — guards against injection. + public static string Esc(string s) => Markup.Escape(s); + + // Interactive == an attached terminal whose stdin is not redirected. We use + // this to decide whether to show a spinner and whether to prompt. In + // non-interactive contexts (CI, piped input) we never prompt or block. + public static bool IsInteractive() => + !Console.IsInputRedirected && AnsiConsole.Profile.Capabilities.Interactive; +} diff --git a/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/MigrateRenderer.cs b/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/MigrateRenderer.cs new file mode 100644 index 0000000..14e21cf --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/MigrateRenderer.cs @@ -0,0 +1,204 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using Spectre.Console; +using static nanoFramework.Migrate.Cli.Rendering.ConsoleSupport; + +namespace nanoFramework.Migrate.Cli.Rendering; + +/// Pairs a source .nfproj path with its conversion outcome. +public readonly record struct ProjectOutcome(string Nfproj, ConvertResult Result); + +/// Spectre presentation for the migrate command. Consumes Core's data. +public static class MigrateRenderer +{ + public static void RenderSummaryTable(List results, string baseDir, bool dryRun) + { + var table = new Table().Border(TableBorder.Rounded).Expand(); + table.Title = new TableTitle(dryRun ? "Migration preview (dry run)" : "Migration summary"); + table.AddColumn("Project"); + table.AddColumn("Result"); + table.AddColumn("Packages"); + table.AddColumn("Notes"); + + foreach (var (nf, result) in results) + { + var rel = Path.GetRelativePath(baseDir, nf); + var (label, color) = StatusLabel(result.Status); + + var pkgs = result.Packages.Count == 0 + ? "[grey]—[/]" + : string.Join("\n", result.Packages.Select(p => $"{Esc(p.Key)} [grey]{Esc(p.Value)}[/]")); + + var notes = BuildNotesCell(result, dryRun); + + table.AddRow( + new Markup($"[blue]{Esc(rel)}[/]"), + new Markup($"[{color}]{label}[/]"), + new Markup(pkgs), + new Markup(notes)); + } + + AnsiConsole.Write(table); + } + + // The Notes cell: in dry-run it previews what WOULD change (target path, + // deletions, .sln edits); otherwise it shows the count of review flags. + private static string BuildNotesCell(ConvertResult result, bool dryRun) + { + if (result.Status == ConvertStatus.Error) + return $"[red]{Esc(result.Error ?? "error")}[/]"; + if (result.Status == ConvertStatus.Skipped) + return "[grey]already SDK-style[/]"; + + var lines = new List(); + if (dryRun) + { + lines.Add($"[grey]→[/] {Esc(Path.GetFileName(result.OutputPath))}"); + foreach (var d in result.DeletedFiles) + lines.Add($"[red]delete[/] {Esc(Path.GetFileName(d))}"); + foreach (var s in result.UpdatedSolutions) + lines.Add($"[yellow]edit[/] {Esc(Path.GetFileName(s))}"); + } + if (result.Review.Count > 0) + lines.Add($"[yellow]{result.Review.Count} item(s) need review[/]"); + return lines.Count == 0 ? "[green]clean[/]" : string.Join("\n", lines); + } + + // Review notes get a clearly-visible yellow panel, grouped per project, so + // they are never buried in the table. + public static void RenderReviewNotes(List results, string baseDir) + { + var flagged = results.Where(r => r.Result.Review.Count > 0 + && r.Result.Status == ConvertStatus.Review).ToList(); + if (flagged.Count == 0) return; + + var sb = new StringBuilder(); + foreach (var (nf, result) in flagged) + { + var rel = Path.GetRelativePath(baseDir, nf); + sb.Append($"[bold]{Esc(rel)}[/]\n"); + foreach (var item in result.Review) + sb.Append($" [yellow]•[/] {Esc(item)}\n"); + } + + var panel = new Panel(sb.ToString().TrimEnd('\n')) + { + Header = new PanelHeader("[yellow]MANUAL REVIEW NEEDED[/]"), + Border = BoxBorder.Rounded, + BorderStyle = new Style(Color.Yellow), + Expand = true, + }; + AnsiConsole.WriteLine(); + AnsiConsole.Write(panel); + } + + public static void RenderTally(List results, bool dryRun) + { + int converted = results.Count(r => r.Result.Status == ConvertStatus.Converted); + int skipped = results.Count(r => r.Result.Status == ConvertStatus.Skipped); + int flagged = results.Count(r => r.Result.Status == ConvertStatus.Review); + int errors = results.Count(r => r.Result.Status == ConvertStatus.Error); + var verb = dryRun ? "would convert" : "converted"; + + AnsiConsole.WriteLine(); + AnsiConsole.MarkupLine( + $"[green]{verb} {converted}[/] • [grey]skipped {skipped}[/] • " + + $"[yellow]flagged {flagged}[/] • [red]errors {errors}[/] • total {results.Count}"); + } + + // A tree of the candidate solutions and the .nfproj each would convert, so the + // user sees what is in scope before any prompt. Used for solution-input, + // directory-with-solutions, and glob-scoped plans. + public static void RenderCandidateSolutions(IReadOnlyList candidates, string baseDir) + { + if (candidates.Count == 0) return; + + var tree = new Tree("[bold]Affected solution(s)[/]"); + foreach (var c in candidates) + { + var fmt = c.Solution.Format == SolutionFormat.Xml ? "slnx" : "sln"; + var slnRel = RelOrName(baseDir, c.Solution.Path); + var node = tree.AddNode($"[yellow]{Esc(slnRel)}[/] [grey]({fmt}, {c.NanoProjects.Count} project(s))[/]"); + foreach (var nf in c.NanoProjects) + node.AddNode($"[blue]{Esc(RelOrName(baseDir, nf))}[/]"); + } + AnsiConsole.Write(tree); + AnsiConsole.WriteLine(); + } + + // The solutions actually retargeted by a real run (grouped notice). Pure + // presentation over the rewrite results. + public static void RenderRewrittenSolutions(IReadOnlyList rewritten, string baseDir) + { + if (rewritten.Count == 0) return; + AnsiConsole.WriteLine(); + foreach (var sln in rewritten) + AnsiConsole.MarkupLine($"[yellow]updated[/] {Esc(RelOrName(baseDir, sln))}"); + } + + // A path relative to baseDir when it sits underneath it; otherwise the bare + // file name. Keeps output readable whether or not the file is inside the tree. + private static string RelOrName(string baseDir, string path) + { + var rel = Path.GetRelativePath(baseDir, path); + return rel.StartsWith("..", StringComparison.Ordinal) ? Path.GetFileName(path) : rel; + } + + // The verification build results: one row per target with a Pass/Fail/Skipped + // badge and (on failure) a short error tail. Pure presentation over Core data. + public static void RenderVerifyTable(IReadOnlyList outcomes, string baseDir) + { + if (outcomes.Count == 0) return; + + var table = new Table().Border(TableBorder.Rounded).Expand(); + table.Title = new TableTitle("Build verification"); + table.AddColumn("Target"); + table.AddColumn("Result"); + table.AddColumn("Details"); + + foreach (var o in outcomes) + { + var (label, color) = o.Skipped ? ("Skipped", "grey") + : o.Succeeded ? ("Pass", "green") + : ("Fail", "red"); + var details = o.Skipped ? Esc(o.Message ?? "skipped") + : o.Succeeded ? "[grey]—[/]" + : $"[red]exit {o.ExitCode}[/]\n{Esc(Truncate(o.ErrorTail, 600))}"; + table.AddRow( + new Markup($"[blue]{Esc(RelOrName(baseDir, o.Target))}[/]"), + new Markup($"[{color}]{label}[/]"), + new Markup(details)); + } + AnsiConsole.WriteLine(); + AnsiConsole.Write(table); + } + + // The result of a rollback: what was restored/deleted (grouped notice). + public static void RenderRollbackResult(RollbackResult result, string baseDir) + { + AnsiConsole.WriteLine(); + foreach (var r in result.Restored) + AnsiConsole.MarkupLine($"[green]restored[/] {Esc(RelOrName(baseDir, r))}"); + foreach (var d in result.Deleted) + AnsiConsole.MarkupLine($"[yellow]removed[/] {Esc(RelOrName(baseDir, d))}"); + foreach (var p in result.Problems) + AnsiConsole.MarkupLine($"[red]rollback issue:[/] {Esc(p)}"); + AnsiConsole.WriteLine(); + AnsiConsole.MarkupLine($"[bold]rolled back {result.Total} file(s)[/] " + + $"([green]{result.Restored.Count} restored[/], [yellow]{result.Deleted.Count} removed[/])."); + } + + private static string Truncate(string s, int max) => + s.Length <= max ? s : s[..max] + "…"; + + private static (string label, string color) StatusLabel(ConvertStatus s) => s switch + { + ConvertStatus.Converted => ("Converted", "green"), + ConvertStatus.Skipped => ("Skipped", "grey"), + ConvertStatus.Review => ("Review", "yellow"), + ConvertStatus.Error => ("Error", "red"), + _ => ("?", "white"), + }; +} diff --git a/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/MigrationReportBuilder.cs b/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/MigrationReportBuilder.cs new file mode 100644 index 0000000..0920ed5 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli.Commands/Rendering/MigrationReportBuilder.cs @@ -0,0 +1,121 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Ardalis.SmartEnum; + +namespace nanoFramework.Migrate.Cli.Rendering; + +/// +/// The output format for a written migration report. A SmartEnum so each value owns its +/// file extensions and its writer; adding a format (e.g. JSON) is a new value rather than +/// another switch arm. keys the format off the path's extension. +/// +public sealed class ReportFormat : SmartEnum +{ + public static readonly ReportFormat Markdown = + new("Markdown", 0, new[] { ".md", ".markdown" }, MarkdownReportWriter.Write); + + public static readonly ReportFormat Html = + new("Html", 1, new[] { ".html", ".htm" }, HtmlReportWriter.Write); + + private readonly string[] _extensions; + private readonly Action _write; + + private ReportFormat(string name, int value, string[] extensions, Action write) + : base(name, value) + { + _extensions = extensions; + _write = write; + } + + /// The format keyed by a path's extension; unknown or none falls back to Markdown. + public static ReportFormat FromPath(string path) + { + var ext = Path.GetExtension(path).ToLowerInvariant(); + return List.FirstOrDefault(f => f._extensions.Contains(ext)) ?? Markdown; + } + + /// Renders to in this format. + public void Write(MigrationReport report, string path) => _write(report, path); +} + +/// +/// Maps the command-layer migration data (, rewritten +/// solutions and verification s) onto the console-free +/// Core the report writers consume. Lives in the +/// presentation layer because is a command-layer type; +/// the resulting report and the writers stay pure Core. +/// +public static class MigrationReportBuilder +{ + /// + /// Builds a from the same outcome data the summary + /// table renders. is supplied by the caller so + /// Core never reads the clock. + /// + public static MigrationReport Build( + IReadOnlyList results, + string baseDir, + bool dryRun, + IReadOnlyList affectedSolutions, + IReadOnlyList? verify, + DateTime generatedUtc) + { + var projects = results + .Select(o => new ReportEntry + { + RelativePath = Rel(baseDir, o.Nfproj), + Status = o.Result.Status, + Packages = o.Result.Packages.ToList(), + Review = o.Result.Review.ToList(), + Error = o.Result.Error, + }) + .ToList(); + + var solutions = affectedSolutions.Select(s => Rel(baseDir, s)).ToList(); + + var verifyEntries = (verify ?? Array.Empty()) + .Select(v => new ReportVerifyEntry + { + Target = Rel(baseDir, v.Target), + Succeeded = v.Succeeded, + Skipped = v.Skipped, + ExitCode = v.ExitCode, + Details = v.Skipped ? v.Message + : v.Succeeded ? null + : v.ErrorTail, + }) + .ToList(); + + return new MigrationReport + { + RootPath = baseDir, + GeneratedUtc = generatedUtc, + DryRun = dryRun, + Projects = projects, + AffectedSolutions = solutions, + Verify = verifyEntries, + }; + } + + /// Picks the report format from the file extension (unknown or none → Markdown). + public static ReportFormat FormatFor(string path) => ReportFormat.FromPath(path); + + /// Renders to in the format keyed by the extension. + public static ReportFormat Write(MigrationReport report, string path) + { + var format = ReportFormat.FromPath(path); + format.Write(report, path); + return format; + } + + // A forward-slash path relative to baseDir when the file sits beneath it; + // otherwise the bare file name. Keeps the report stable across machines. + private static string Rel(string baseDir, string path) + { + var rel = Path.GetRelativePath(baseDir, path); + if (rel.StartsWith("..", StringComparison.Ordinal)) + rel = Path.GetFileName(path); + return rel.Replace('\\', '/'); + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli.Commands/RollbackCommand.cs b/tools/migrate/src/NanoMigrate.Cli.Commands/RollbackCommand.cs new file mode 100644 index 0000000..40d147d --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli.Commands/RollbackCommand.cs @@ -0,0 +1,67 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.ComponentModel; +using nanoFramework.Migrate.Cli.Rendering; +using Spectre.Console; +using Spectre.Console.Cli; +using static nanoFramework.Migrate.Cli.Rendering.ConsoleSupport; + +namespace nanoFramework.Migrate.Cli.Commands; + +public sealed class RollbackSettings : AssumeYesSettings +{ + [CommandArgument(0, "[path]")] + [Description("The directory whose last recorded migration is reverted (looks for a " + + ".nanomigrate/ journal under it). Defaults to the current directory.")] + public string Path { get; init; } = "."; +} + +/// +/// Reverts the last recorded migration under a path by reading its rollback journal +/// (restore backed-up originals, delete created files). Idempotent and safe: with no +/// journal it reports "nothing to roll back" and exits 0. The reversal logic lives in +/// ; this is the thin presentation/prompt. +/// +public sealed class RollbackCommand : Command +{ + protected override int Execute(CommandContext context, RollbackSettings settings, CancellationToken cancellationToken) + { + Header("NanoMigrate · rollback"); + + var root = System.IO.Path.GetFullPath(settings.Path); + var manifestPath = RollbackJournal.ManifestPaths(root).FirstOrDefault(); + if (manifestPath is null) + { + AnsiConsole.MarkupLine($"[grey]nothing to roll back under '{Esc(root)}' (no migration journal found).[/]"); + return 0; + } + + var manifest = RollbackJournal.FindLatest(root); + var count = manifest?.Entries.Count ?? 0; + AnsiConsole.MarkupLine( + $"Found a recorded migration ([blue]{Esc(manifest?.Id ?? "?")}[/]) with [bold]{count}[/] action(s)."); + + if (!Confirm("Roll back the last recorded migration?", settings.AssumeYes)) + { + AnsiConsole.MarkupLine("[grey]aborted; nothing reverted.[/]"); + return 0; + } + + var result = RollbackJournal.ApplyAndCleanup(manifestPath, cancellationToken); + if (result is null) + { + AnsiConsole.MarkupLine("[red]error:[/] the rollback journal could not be read."); + return 1; + } + + MigrateRenderer.RenderRollbackResult(result, root); + return result.Problems.Count > 0 ? 1 : 0; + } + + private static bool Confirm(string question, bool assumeYes) + { + if (assumeYes || !IsInteractive()) return true; + return AnsiConsole.Confirm(question, defaultValue: false); + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli/Cli/CloneCommand.cs b/tools/migrate/src/NanoMigrate.Cli/Cli/CloneCommand.cs new file mode 100644 index 0000000..a9a4364 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli/Cli/CloneCommand.cs @@ -0,0 +1,100 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.ComponentModel; +using Spectre.Console; +using Spectre.Console.Cli; +using static nanoFramework.Migrate.Cli.Rendering.ConsoleSupport; + +namespace nanoFramework.Migrate.Cli.Commands; + +internal sealed class CloneSettings : CommandSettings +{ + [CommandArgument(0, "[out-dir]")] + [Description("Directory to clone into (default ./nano-repos).")] + public string? OutDir { get; init; } + + [CommandOption("--org ")] + [Description("GitHub org (default nanoframework).")] + public string Org { get; init; } = "nanoframework"; + + [CommandOption("--filter ")] + [Description("Repo name prefix to match (default lib-).")] + public string Filter { get; init; } = "lib-"; + + [CommandOption("--token ")] + [Description("GitHub token (or env GITHUB_TOKEN) to raise the API rate limit.")] + public string? Token { get; init; } = Environment.GetEnvironmentVariable("GITHUB_TOKEN"); + + [CommandOption("--include-archived")] + [Description("Include archived repositories (skipped by default).")] + public bool IncludeArchived { get; init; } +} + +internal sealed class CloneCommand : AsyncCommand +{ + protected override async Task ExecuteAsync(CommandContext context, CloneSettings settings, CancellationToken cancellationToken) + { + Header("NanoMigrate · clone"); + // Resolve to an absolute path so the destination is stable regardless of the + // working directory git inherits for each clone. + var outDir = Path.GetFullPath(settings.OutDir ?? "./nano-repos"); + Directory.CreateDirectory(outDir); + + AnsiConsole.MarkupLine($"Enumerating [bold]{Esc(settings.Org)}[/] repositories matching '[blue]{Esc(settings.Filter)}*[/]'…"); + var repos = (await GitHub.ListOrgReposAsync(settings.Org, settings.Token, settings.IncludeArchived, cancellationToken)) + .Where(r => r.Name.StartsWith(settings.Filter, StringComparison.OrdinalIgnoreCase)) + .OrderBy(r => r.Name).ToList(); + + if (repos.Count == 0) throw new UserError( + $"no repos matched '{settings.Filter}*' in org '{settings.Org}'. " + + "Check the org name and filter, or pass --token to lift the API rate limit."); + + AnsiConsole.MarkupLine($"Found [bold]{repos.Count}[/] repositories. Cloning into [blue]{Esc(outDir)}[/]…"); + AnsiConsole.WriteLine(); + + var table = new Table().Border(TableBorder.Rounded).Expand(); + table.Title = new TableTitle("Clone results"); + table.AddColumn("Repository"); + table.AddColumn("Result"); + + int ok = 0, skipped = 0, failed = 0; + void CloneAll(Action? report) + { + foreach (var r in repos) + { + cancellationToken.ThrowIfCancellationRequested(); + report?.Invoke(r.Name); + var dest = Path.Combine(outDir, r.Name); + if (Directory.Exists(dest)) + { + table.AddRow(new Markup($"[blue]{Esc(r.Name)}[/]"), new Markup("[grey]skipped (already present)[/]")); + skipped++; continue; + } + var (code, _, err) = ProcessRunner.Run("git", $"clone --depth 1 {r.CloneUrl} \"{dest}\"", outDir, cancellationToken); + if (code == 0) + { + table.AddRow(new Markup($"[blue]{Esc(r.Name)}[/]"), new Markup("[green]cloned[/]")); + ok++; + } + else + { + var msg = err.Trim().Split('\n').LastOrDefault() ?? "git clone failed"; + table.AddRow(new Markup($"[blue]{Esc(r.Name)}[/]"), new Markup($"[red]FAIL[/] {Esc(msg)}")); + failed++; + } + } + } + + if (IsInteractive()) + AnsiConsole.Status().Spinner(Spinner.Known.Dots) + .Start("Cloning…", ctx => CloneAll(name => ctx.Status($"Cloning [blue]{Esc(name)}[/]…"))); + else + CloneAll(null); + + AnsiConsole.Write(table); + AnsiConsole.WriteLine(); + AnsiConsole.MarkupLine($"[green]cloned {ok}[/] • [grey]skipped {skipped}[/] • [red]failed {failed}[/]"); + return failed > 0 ? 2 : 0; + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli/Cli/FleetCommand.cs b/tools/migrate/src/NanoMigrate.Cli/Cli/FleetCommand.cs new file mode 100644 index 0000000..98b72d6 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli/Cli/FleetCommand.cs @@ -0,0 +1,150 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.ComponentModel; +using nanoFramework.Migrate.Cli.Rendering; +using Spectre.Console; +using Spectre.Console.Cli; +using static nanoFramework.Migrate.Cli.Rendering.ConsoleSupport; + +namespace nanoFramework.Migrate.Cli.Commands; + +internal sealed class FleetSettings : CommandSettings +{ + [CommandArgument(0, "")] + [Description("A directory of cloned repos; every .nfproj across them is migrated.")] + public string ReposDir { get; init; } = ""; + + [CommandOption("--sdk ")] + [Description("Accepted for back-compat but ignored: the SDK reference is versionless (pinned via global.json msbuild-sdks).")] + public string Sdk { get; init; } = "2.0.0"; + + [CommandOption("--tfm ")] + [Description("Target framework moniker (default netnano1.0).")] + public string Tfm { get; init; } = "netnano1.0"; + + [CommandOption("--ext ")] + [Description("Output extension: .nfproj or .csproj (default .csproj).")] + public string Ext { get; init; } = ".csproj"; + + [CommandOption("--no-backup")] + [Description("Don't write a .nfproj.bak (implied by --commit).")] + public bool NoBackup { get; init; } + + [CommandOption("--dry-run|--no-write")] + [Description("Analyse and preview only; write nothing.")] + public bool DryRun { get; init; } + + [CommandOption("--glob ")] + [Description("Only convert matching .nfproj within each repo. Supports *, ** and ?.")] + public string? Glob { get; init; } + + [CommandOption("--report ")] + [Description("Markdown report path (default migration-report.md).")] + public string Report { get; init; } = "migration-report.md"; + + [CommandOption("--branch ")] + [Description("Create/reset this git branch in each repo (must not start with 'develop').")] + public string? Branch { get; init; } + + [CommandOption("--commit")] + [Description("Commit the changes (requires --branch). Uses a contribution-compliant message and signs off (Signed-off-by) by default.")] + public bool Commit { get; init; } + + [CommandOption("--message ")] + [Description("Commit summary line (kept <= 50 chars).")] + public string? Message { get; init; } + + [CommandOption("--issue ")] + [Description("Reference an issue: adds a \"Fix #\" trailer to the commit.")] + public string? Issue { get; init; } + + [CommandOption("--no-sign-off")] + [Description("Don't add a Signed-off-by line.")] + public bool NoSignOff { get; init; } + + public override ValidationResult Validate() + { + if (Ext is not (".nfproj" or ".csproj")) + return ValidationResult.Error("--ext must be .nfproj or .csproj"); + return ValidationResult.Success(); + } + + public FleetOptions ToFleetOptions() => new() + { + Conversion = new ConversionOptions + { + Sdk = Sdk, + Tfm = Tfm, + Ext = Ext, + NoBackup = NoBackup, + DryRun = DryRun, + Glob = Glob, + }, + Report = Report, + Branch = Branch, + Commit = Commit, + CommitMessage = Message, + Issue = Issue?.TrimStart('#'), + SignOff = !NoSignOff, + }; +} + +internal sealed class FleetCommand : Command +{ + protected override int Execute(CommandContext context, FleetSettings settings, CancellationToken cancellationToken) + { + Header("NanoMigrate · fleet"); + + var o = settings.ToFleetOptions(); + var reposDir = settings.ReposDir; + var service = new FleetService(new ProjectConverter(), new ProcessRunner()); + + // Core validates and discovers; surface its messages as clean usage errors. + List repoDirs; + try + { + repoDirs = service.ResolveRepos(reposDir, o); + } + catch (ArgumentException ex) + { + throw new UserError(ex.Message); + } + + if (o.Conversion.DryRun) + AnsiConsole.MarkupLine($"[yellow]Dry run[/] — {repoDirs.Count} repo(s); nothing will be written."); + else + AnsiConsole.MarkupLine($"Processing [bold]{repoDirs.Count}[/] repo(s) under [blue]{Esc(reposDir)}[/]" + + (o.Branch is not null ? $" on branch [blue]{Esc(o.Branch)}[/]" : "") + + (o.Commit ? ", committing" : "") + "."); + AnsiConsole.WriteLine(); + + List report; + if (IsInteractive()) + { + List? captured = null; + AnsiConsole.Status().Spinner(Spinner.Known.Dots) + .Start("Migrating…", ctx => captured = service.Process(repoDirs, o, + name => ctx.Status($"Migrating [blue]{Esc(name)}[/]…"), cancellationToken)); + report = captured!; + } + else + { + report = service.Process(repoDirs, o, cancellationToken: cancellationToken); + } + + FleetRenderer.RenderFleetTable(report); + FleetRenderer.RenderFleetTree(report); + FleetRenderer.RenderFleetReview(report); + + service.WriteReport(report, o, reposDir); + var errored = report.Count(r => r.Error is not null); + var needsReview = report.Count(r => r.Error is null && r.Review.Count > 0); + AnsiConsole.WriteLine(); + AnsiConsole.MarkupLine( + $"[bold]{report.Count}[/] repo(s) processed • " + + $"[yellow]{needsReview} need review[/] • [red]{errored} with errors[/] • " + + $"report: [blue]{Esc(o.Report)}[/]"); + return errored > 0 ? 2 : 0; + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli/GitHub.cs b/tools/migrate/src/NanoMigrate.Cli/GitHub.cs new file mode 100644 index 0000000..bf8a376 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli/GitHub.cs @@ -0,0 +1,52 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Net.Http.Headers; +using System.Text.Json; + +namespace nanoFramework.Migrate.Cli; + +/// Minimal GitHub REST client (BCL only) for listing org repositories. +internal static class GitHub +{ + internal sealed record Repo(string Name, string CloneUrl, bool Archived); + + public static async Task> ListOrgReposAsync(string org, string? token, bool includeArchived, CancellationToken ct = default) + { + using var http = new HttpClient(); + http.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("nano-migrate", "1.0")); + http.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/vnd.github+json")); + if (!string.IsNullOrEmpty(token)) + http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token); + + var repos = new List(); + for (int page = 1; ; page++) + { + var url = $"https://api.github.com/orgs/{org}/repos?per_page=100&page={page}&type=public"; + using var resp = await http.GetAsync(url, ct); + if (!resp.IsSuccessStatusCode) + { + var hint = resp.StatusCode == System.Net.HttpStatusCode.Forbidden + ? " (rate limited — pass --token or set GITHUB_TOKEN)" : ""; + throw new UserError($"GitHub API returned {(int)resp.StatusCode} {resp.StatusCode}{hint}"); + } + + var json = await resp.Content.ReadAsStringAsync(ct); + using var doc = JsonDocument.Parse(json); + var arr = doc.RootElement; + if (arr.GetArrayLength() == 0) break; + + foreach (var e in arr.EnumerateArray()) + { + var archived = e.TryGetProperty("archived", out var ar) && ar.GetBoolean(); + if (archived && !includeArchived) continue; + repos.Add(new Repo( + e.GetProperty("name").GetString()!, + e.GetProperty("clone_url").GetString()!, + archived)); + } + if (arr.GetArrayLength() < 100) break; + } + return repos; + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli/NanoMigrate.Cli.csproj b/tools/migrate/src/NanoMigrate.Cli/NanoMigrate.Cli.csproj new file mode 100644 index 0000000..a4d82cc --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli/NanoMigrate.Cli.csproj @@ -0,0 +1,69 @@ + + + + Exe + net10.0 + enable + enable + nano-migrate + nanoFramework.Migrate.Cli + true + + false + + + + + true + nano-migrate + nanoFramework.Migrate + nanoFramework Migrate (CLI) + Command-line tool that migrates legacy nanoFramework .nfproj projects to the SDK-style MSBuild project system — one project, a directory, or an entire cloned fleet. Built on the nanoFramework.Migrate.Core engine. + nanoFramework + nanoFramework + https://github.com/nanoframework/nf-tools + https://github.com/nanoframework/nf-tools + git + MIT + nanoFramework;MSBuild;SDK;migration;nfproj;dotnet-tool;IoT;embedded;C# + Copyright (c) .NET Foundation and Contributors + false + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/migrate/src/NanoMigrate.Cli/ProcessRunner.cs b/tools/migrate/src/NanoMigrate.Cli/ProcessRunner.cs new file mode 100644 index 0000000..f60f786 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli/ProcessRunner.cs @@ -0,0 +1,21 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Cli; + +/// +/// Runs external processes. Also implements so Core's +/// fleet orchestration can issue git commands without depending on a process API. +/// The spawn/drain/cancel/timeout details live once in . +/// +internal sealed class ProcessRunner : IGitRunner +{ + public GitResult Run(string args, string workingDirectory, CancellationToken cancellationToken = default) + { + var (code, so, se) = Run("git", args, workingDirectory, cancellationToken); + return new GitResult(code, so, se); + } + + public static (int code, string stdout, string stderr) Run(string file, string args, string cwd, CancellationToken cancellationToken = default) => + ProcessExec.Run(file, args, cwd, cancellationToken: cancellationToken); +} diff --git a/tools/migrate/src/NanoMigrate.Cli/Program.cs b/tools/migrate/src/NanoMigrate.Cli/Program.cs new file mode 100644 index 0000000..8626dcf --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli/Program.cs @@ -0,0 +1,76 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +// nano-migrate — convert legacy nanoFramework .nfproj projects to the SDK-style +// MSBuild project system, one project at a time or across an entire cloned fleet. +// +// SCOPE: project-system migration ONLY. This tool does NOT touch OTA, modular +// firmware packaging, runtimes/{rid}/native layouts, or ABI manifests. It moves +// a repo from the legacy flavored .nfproj format onto an SDK-style project that +// composes over the nanoFramework SDK, folds packages.config into PackageReference, +// and folds .nuspec metadata into MSBuild Pack properties. Nothing more. +// +// The conversion engine lives in NanoMigrate.Core (a console-free library). This +// project is a thin Spectre.Console.Cli front end over it. + +using nanoFramework.Migrate.Cli; +using nanoFramework.Migrate.Cli.Commands; +using Spectre.Console; +using Spectre.Console.Cli; + +// No arguments: show help and signal misuse (exit 1), matching the original. +if (args.Length == 0) +{ + BuildApp(out _).Run(new[] { "--help" }); + return 1; +} + +var app = BuildApp(out _); +try +{ + return app.Run(args); +} +catch (UserError ue) +{ + AnsiConsole.MarkupLine($"[red]error:[/] {Markup.Escape(ue.Message)}"); + return 1; +} +catch (OperationCanceledException) +{ + // Ctrl+C / console close — Spectre cancels the command token, which the long-running + // operations observe and surface here. 130 = 128 + SIGINT, the conventional code. + AnsiConsole.MarkupLine("[yellow]cancelled.[/]"); + return 130; +} +catch (Exception ex) +{ + // Spectre's own parse/validation errors surface here (PropagateExceptions). + AnsiConsole.MarkupLine($"[red]error:[/] {Markup.Escape(ex.Message)}"); + return 1; +} + +static CommandApp BuildApp(out CommandApp app) +{ + var a = new CommandApp(); + a.Configure(config => + { + config.SetApplicationName("nano-migrate"); + // Surface exceptions to Program so UserError maps to exit 1 and parse + // errors render cleanly without a stack trace. + config.PropagateExceptions(); + + // migrate + clean + rollback, registered once and shared with the umbrella tool. + MigrateRegistration.Add(config, + "Convert a .nfproj, or every .nfproj under a directory."); + + config.AddCommand("clone") + .WithDescription("Clone all matching repos from a GitHub org.") + .WithExample("clone", "./nano-repos", "--token", "$GITHUB_TOKEN"); + + config.AddCommand("fleet") + .WithDescription("Migrate every .nfproj across cloned repos; write a report.") + .WithExample("fleet", "./nano-repos", "--branch", "sdk-migration", "--commit", "--dry-run"); + }); + app = a; + return a; +} diff --git a/tools/migrate/src/NanoMigrate.Cli/Rendering/FleetRenderer.cs b/tools/migrate/src/NanoMigrate.Cli/Rendering/FleetRenderer.cs new file mode 100644 index 0000000..e6e192f --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli/Rendering/FleetRenderer.cs @@ -0,0 +1,84 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using Spectre.Console; +using static nanoFramework.Migrate.Cli.Rendering.ConsoleSupport; + +namespace nanoFramework.Migrate.Cli.Rendering; + +/// Spectre presentation for the fleet command. Consumes Core's RepoReport data. +internal static class FleetRenderer +{ + public static void RenderFleetTable(List report) + { + var table = new Table().Border(TableBorder.Rounded).Expand(); + table.Title = new TableTitle("Fleet results"); + table.AddColumn("Repository"); + table.AddColumn("Result"); + table.AddColumn("Projects"); + table.AddColumn("Review"); + + foreach (var rr in report) + { + string label, color; + if (rr.Error is not null) { label = "Error"; color = "red"; } + else if (rr.Review.Count > 0) { label = "Review"; color = "yellow"; } + else { label = rr.Committed ? "OK (committed)" : "OK"; color = "green"; } + + var note = rr.Error is not null ? $" [red]{Esc(rr.Error.Split('\n')[0])}[/]" : ""; + table.AddRow( + new Markup($"[blue]{Esc(rr.Name)}[/]"), + new Markup($"[{color}]{label}[/]{note}"), + new Markup(rr.Projects.ToString()), + new Markup(rr.Review.Count == 0 ? "[grey]—[/]" : $"[yellow]{rr.Review.Count}[/]")); + } + AnsiConsole.Write(table); + } + + // A tree view of the fleet: one branch per repo, with each repo's review + // items as leaves. Complements the summary table for at-a-glance structure. + public static void RenderFleetTree(List report) + { + if (report.Count == 0) return; + + var tree = new Tree("[bold]Fleet[/]"); + foreach (var rr in report) + { + string label, color; + if (rr.Error is not null) { label = "error"; color = "red"; } + else if (rr.Review.Count > 0) { label = "review"; color = "yellow"; } + else { label = rr.Committed ? "ok (committed)" : "ok"; color = "green"; } + + var node = tree.AddNode($"[blue]{Esc(rr.Name)}[/] [{color}]{label}[/] [grey]({rr.Projects} project(s))[/]"); + if (rr.Error is not null) + node.AddNode($"[red]{Esc(rr.Error.Split('\n')[0])}[/]"); + foreach (var item in rr.Review) + node.AddNode($"[yellow]•[/] {Esc(item)}"); + } + AnsiConsole.WriteLine(); + AnsiConsole.Write(tree); + } + + public static void RenderFleetReview(List report) + { + var flagged = report.Where(r => r.Error is null && r.Review.Count > 0).ToList(); + if (flagged.Count == 0) return; + + var sb = new StringBuilder(); + foreach (var rr in flagged) + { + sb.Append($"[bold]{Esc(rr.Name)}[/]\n"); + foreach (var item in rr.Review) sb.Append($" [yellow]•[/] {Esc(item)}\n"); + } + var panel = new Panel(sb.ToString().TrimEnd('\n')) + { + Header = new PanelHeader("[yellow]MANUAL REVIEW NEEDED[/]"), + Border = BoxBorder.Rounded, + BorderStyle = new Style(Color.Yellow), + Expand = true, + }; + AnsiConsole.WriteLine(); + AnsiConsole.Write(panel); + } +} diff --git a/tools/migrate/src/NanoMigrate.Cli/UserError.cs b/tools/migrate/src/NanoMigrate.Cli/UserError.cs new file mode 100644 index 0000000..285bfdf --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Cli/UserError.cs @@ -0,0 +1,7 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Cli; + +/// A user-facing error that prints cleanly without a stack trace. +internal sealed class UserError(string message) : Exception(message); diff --git a/tools/migrate/src/NanoMigrate.Core/Backup/BackupCleaner.cs b/tools/migrate/src/NanoMigrate.Core/Backup/BackupCleaner.cs new file mode 100644 index 0000000..6a2c1ef --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Backup/BackupCleaner.cs @@ -0,0 +1,144 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Backup; + +/// The leftovers a clean would remove, gathered for preview before deletion. +public sealed class CleanPlan +{ + /// The root the scan was rooted at (absolute). + public required string Root { get; init; } + + /// *.nfproj.bak files found under the root. + public List BackupFiles { get; } = new(); + + /// .nanomigrate rollback folders found under the root. + public List RollbackFolders { get; } = new(); + + /// Total leftovers (backup files + rollback folders). + public int Total => BackupFiles.Count + RollbackFolders.Count; + + /// True when there is nothing to remove. + public bool IsEmpty => Total == 0; +} + +/// The tally of an executed clean. +public sealed class CleanResult +{ + /// *.nfproj.bak files actually deleted. + public List RemovedBackups { get; } = new(); + + /// .nanomigrate folders actually removed. + public List RemovedFolders { get; } = new(); + + /// Non-fatal problems (a file that could not be deleted, etc.). + public List Problems { get; } = new(); + + /// Total leftovers removed. + public int Total => RemovedBackups.Count + RemovedFolders.Count; +} + +/// +/// Finds and removes migration leftovers under a path: every *.nfproj.bak +/// file and every .nanomigrate rollback folder/journal. Pure file logic — +/// the planning () and the removal () are +/// separate so a command can preview, confirm, then act. Idempotent and safe: a +/// tree with no leftovers yields an empty plan and a no-op clean. +/// +public static class BackupCleaner +{ + /// + /// Scans (recursively) for migration leftovers. A + /// non-existent root yields an empty plan. .nanomigrate folders are + /// reported as folders (their contents are not enumerated as individual files). + /// + public static CleanPlan Plan(string root) + { + var full = Path.GetFullPath(root); + var plan = new CleanPlan { Root = full }; + if (!Directory.Exists(full) && !File.Exists(full)) return plan; + + // A single file argument: only its sibling .bak makes sense; treat its dir as root. + var scanRoot = Directory.Exists(full) ? full : Path.GetDirectoryName(full)!; + + // Loose, next-to-project backups only — the opt-in `--backup` artifact. The + // rollback journal keeps its OWN copy of the original .nfproj inside + // .nanomigrate/rollback-/ under a "-.nfproj.bak" name; those are + // part of the self-contained journal (removed as a whole folder below) and must + // NOT be counted as loose backups, else clean double-reports them. + foreach (var bak in SafeEnumerateFiles(scanRoot, "*.nfproj.bak")) + if (!IsInsideRollbackFolder(bak)) + plan.BackupFiles.Add(Path.GetFullPath(bak)); + + foreach (var dir in SafeEnumerateDirectories(scanRoot, RollbackJournal.FolderName)) + plan.RollbackFolders.Add(Path.GetFullPath(dir)); + + plan.BackupFiles.Sort(StringComparer.OrdinalIgnoreCase); + plan.RollbackFolders.Sort(StringComparer.OrdinalIgnoreCase); + return plan; + } + + /// + /// Removes everything in . Returns a tally; per-item + /// failures are collected as problems rather than aborting the sweep. + /// + public static CleanResult Remove(CleanPlan plan, CancellationToken cancellationToken = default) + { + var result = new CleanResult(); + + foreach (var bak in plan.BackupFiles) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + // Only tally what actually existed and was deleted, so the report doesn't + // over-count phantom removals for files that were already gone. + if (File.Exists(bak)) { File.Delete(bak); result.RemovedBackups.Add(bak); } + } + catch (Exception ex) { result.Problems.Add($"could not delete {bak}: {ex.Message}"); } + } + + foreach (var dir in plan.RollbackFolders) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + if (Directory.Exists(dir)) { Directory.Delete(dir, recursive: true); result.RemovedFolders.Add(dir); } + } + catch (Exception ex) { result.Problems.Add($"could not remove {dir}: {ex.Message}"); } + } + + return result; + } + + // True when a path lies anywhere beneath a ".nanomigrate" rollback folder. Such + // files are the journal's self-contained backups, not loose next-to-project ones. + private static bool IsInsideRollbackFolder(string path) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(path)); + while (!string.IsNullOrEmpty(dir)) + { + if (string.Equals(Path.GetFileName(dir), RollbackJournal.FolderName, StringComparison.OrdinalIgnoreCase)) + return true; + dir = Path.GetDirectoryName(dir); + } + return false; + } + + private static IEnumerable SafeEnumerateFiles(string root, string pattern) + { + try { return Directory.EnumerateFiles(root, pattern, SearchOption.AllDirectories).ToList(); } + catch { return Array.Empty(); } + } + + private static IEnumerable SafeEnumerateDirectories(string root, string name) + { + try + { + return Directory.EnumerateDirectories(root, name, SearchOption.AllDirectories) + .Where(d => string.Equals(Path.GetFileName(d), name, StringComparison.OrdinalIgnoreCase)) + .ToList(); + } + catch { return Array.Empty(); } + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Backup/MigrationJournaling.cs b/tools/migrate/src/NanoMigrate.Core/Backup/MigrationJournaling.cs new file mode 100644 index 0000000..e011e53 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Backup/MigrationJournaling.cs @@ -0,0 +1,72 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using nanoFramework.Migrate.Core.Projects; + +namespace nanoFramework.Migrate.Core.Backup; + +/// +/// Bridges a (dry-run) preview into a +/// : backs up every file the conversion will modify or +/// delete and records the files it will create. This must run BEFORE the real +/// conversion touches disk, so the backups hold the true originals. +/// +/// The converter already computes, in dry-run, exactly what a real run acts on: +/// (the .nfproj, packages.config and any +/// hand-written AssemblyInfo.cs it removes), +/// (the .csproj it creates) and / +/// (the files it rewrites). We +/// journal all of those. +/// +/// The journal is SELF-CONTAINED: every original it must restore (the .nfproj, +/// packages.config, Properties/AssemblyInfo.cs, and any touched .sln/.slnx/ +/// Directory.Packages.props) is copied INTO .nanomigrate/rollback-<id>/, +/// and rollback restores from there only. It does NOT depend on the converter's loose +/// next-to-project *.nfproj.bak, so a --no-backup migration (which writes +/// no loose .bak at all) is still fully reversible. +/// +public static class MigrationJournaling +{ + /// + /// Records, into , the rollback entries implied by a + /// dry-run of converting one project. Optionally also + /// backs up the host-driven solutions in + /// (the solutions a solution-scoped run rewrites itself). + /// + public static void Record(RollbackJournal journal, ConvertResult preview, + IEnumerable? extraSolutionsToBackup = null) + { + // Files removed by the conversion (original .nfproj, packages.config, + // AssemblyInfo.cs): back up so they can be restored. + foreach (var deleted in preview.DeletedFiles) + journal.BackupBeforeChange(deleted); + + // Solutions the conversion rewrites: back up so the original references and + // GUIDs can be restored. + foreach (var sln in preview.UpdatedSolutions) + journal.BackupBeforeChange(sln); + + // A central Directory.Packages.props the conversion appends to: back up. + if (preview.UpdatedPackagesProps is not null) + journal.BackupBeforeChange(preview.UpdatedPackagesProps); + + // The .csproj the conversion creates (only when it differs from the source, + // i.e. it is a genuinely new file): record for deletion on rollback. + var output = Path.GetFullPath(preview.OutputPath); + var createsNewFile = !preview.DeletedFiles.Any(d => + string.Equals(Path.GetFullPath(d), output, StringComparison.OrdinalIgnoreCase)) + ? true + // When OutputPath equals a deleted source (same extension run) nothing new is created. + : false; + // The .csproj is "new" whenever it is not already the original being deleted. + if (createsNewFile && !File.Exists(output)) + journal.RecordCreated(output); + else if (createsNewFile) + // Output already exists on disk (e.g. a prior partial run): treat as modified. + journal.BackupBeforeChange(output); + + if (extraSolutionsToBackup is not null) + foreach (var sln in extraSolutionsToBackup) + journal.BackupBeforeChange(sln); + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Backup/RollbackJournal.cs b/tools/migrate/src/NanoMigrate.Core/Backup/RollbackJournal.cs new file mode 100644 index 0000000..a7b8855 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Backup/RollbackJournal.cs @@ -0,0 +1,314 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace nanoFramework.Migrate.Core.Backup; + +/// +/// One recorded action in a rollback journal: either a file the migration CREATED +/// (which a rollback deletes) or a file it MODIFIED/DELETED whose original content +/// was backed up (which a rollback restores). +/// +public sealed class RollbackEntry +{ + /// The kind of action that was recorded. + public RollbackAction Action { get; set; } + + /// + /// The live (original) path the action concerns: the file that was created (for + /// ) or the file that was modified/deleted and + /// must be restored (for ). + /// + public string OriginalPath { get; set; } = ""; + + /// + /// For : the path of the backup copy that + /// holds the original bytes. Null for . + /// + public string? BackupPath { get; set; } +} + +/// What a recorded entry does on rollback. +[JsonConverter(typeof(JsonStringEnumConverter))] +public enum RollbackAction +{ + /// The migration created this file; rolling back deletes it. + Created, + + /// The migration modified or deleted this file; rolling back restores it from the backup. + Restore, +} + +/// +/// The on-disk manifest of a single migration run: an id, a timestamp, and the +/// ordered list of recorded actions. Serialized as JSON inside the run's backup +/// folder so a later rollback can reverse the run without git. +/// +public sealed class RollbackManifest +{ + /// The run id (also the backup folder name suffix). + public string Id { get; set; } = ""; + + /// When the run was started (UTC, round-trip format). + public string CreatedUtc { get; set; } = ""; + + /// The recorded actions, in the order they were registered. + public List Entries { get; set; } = new(); +} + +/// +/// Records — and reverses — the file-level effects of a migration run so a real +/// run is reversible without git. Before anything is changed the command asks the +/// journal to back up every file that will be modified or deleted and to remember +/// every file that will be created; the backups + a JSON manifest live under +/// .nanomigrate/rollback-<id>/ beneath a chosen root. A later rollback +/// reads the manifest, restores the backups, and deletes the created files. +/// +/// Pure file logic — no console. Idempotent and safe: restoring an already-restored +/// tree, or rolling back when there is no journal, is a clean no-op. +/// +public sealed class RollbackJournal +{ + /// The folder that holds all migration rollback sets (.nanomigrate). + public const string FolderName = ".nanomigrate"; + + private static readonly JsonSerializerOptions JsonOpts = new() + { + WriteIndented = true, + DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull, + }; + + private readonly RollbackManifest _manifest; + private int _backupSeq; + + /// The root the .nanomigrate folder is created under. + public string Root { get; } + + /// This run's id. + public string Id => _manifest.Id; + + /// The per-run set folder: <root>/.nanomigrate/rollback-<id>. + public string SetDirectory => Path.Combine(Root, FolderName, "rollback-" + _manifest.Id); + + /// The manifest file path inside . + public string ManifestPath => Path.Combine(SetDirectory, "manifest.json"); + + /// The recorded entries so far. + public IReadOnlyList Entries => _manifest.Entries; + + private RollbackJournal(string root, RollbackManifest manifest) + { + Root = root; + _manifest = manifest; + } + + /// + /// Starts a fresh journal rooted at . The backup folder is + /// created lazily on the first ; an empty run that + /// records nothing leaves no folder behind. + /// + public static RollbackJournal Start(string root) + { + var id = DateTime.UtcNow.ToString("yyyyMMdd-HHmmss") + "-" + Guid.NewGuid().ToString("N")[..8]; + return new RollbackJournal(Path.GetFullPath(root), new RollbackManifest + { + Id = id, + CreatedUtc = DateTime.UtcNow.ToString("O"), + }); + } + + /// + /// Backs up the original bytes of a file that the migration is about to MODIFY or + /// DELETE, recording a restore entry. A missing source is ignored (nothing to + /// restore). Re-recording the same original path is a no-op so the FIRST backup — + /// the true original — always wins. + /// + public void BackupBeforeChange(string path) + { + var full = Path.GetFullPath(path); + if (!File.Exists(full)) return; + if (_manifest.Entries.Any(e => e.Action == RollbackAction.Restore + && PathEquals(e.OriginalPath, full))) + return; + + Directory.CreateDirectory(SetDirectory); + var backupName = $"{_backupSeq++:D4}-{Path.GetFileName(full)}.bak"; + var backupPath = Path.Combine(SetDirectory, backupName); + File.Copy(full, backupPath, overwrite: true); + + _manifest.Entries.Add(new RollbackEntry + { + Action = RollbackAction.Restore, + OriginalPath = full, + BackupPath = backupPath, + }); + } + + /// + /// Records that the migration CREATED (so a rollback + /// deletes it). Recording the same path twice is a no-op. + /// + public void RecordCreated(string path) + { + var full = Path.GetFullPath(path); + if (_manifest.Entries.Any(e => e.Action == RollbackAction.Created + && PathEquals(e.OriginalPath, full))) + return; + _manifest.Entries.Add(new RollbackEntry + { + Action = RollbackAction.Created, + OriginalPath = full, + }); + } + + /// True when nothing has been recorded yet. + public bool IsEmpty => _manifest.Entries.Count == 0; + + /// + /// Writes the manifest to disk so the run can later be rolled back. A journal that + /// recorded nothing writes nothing (no empty folder is left behind). + /// + public void Save() + { + if (IsEmpty) return; + Directory.CreateDirectory(SetDirectory); + File.WriteAllText(ManifestPath, JsonSerializer.Serialize(_manifest, JsonOpts), new UTF8Encoding(false)); + } + + /// + /// The newest saved manifest under 's .nanomigrate + /// folder, or null when none exists. "Newest" is by the manifest's recorded UTC + /// timestamp (folder names sort the same way, so this is stable). + /// + public static RollbackManifest? FindLatest(string root) + { + var sets = ManifestPaths(root); + RollbackManifest? newest = null; + foreach (var path in sets) + { + var m = TryLoadManifest(path); + if (m is null) continue; + if (newest is null + || string.Compare(m.CreatedUtc, newest.CreatedUtc, StringComparison.Ordinal) > 0) + newest = m; + } + return newest; + } + + /// Every saved manifest under , newest first. + public static IReadOnlyList ManifestPaths(string root) + { + var dir = Path.Combine(Path.GetFullPath(root), FolderName); + if (!Directory.Exists(dir)) return Array.Empty(); + return Directory.EnumerateFiles(dir, "manifest.json", SearchOption.AllDirectories) + .OrderByDescending(p => p, StringComparer.OrdinalIgnoreCase) + .ToList(); + } + + private static RollbackManifest? TryLoadManifest(string manifestPath) + { + try { return JsonSerializer.Deserialize(File.ReadAllText(manifestPath), JsonOpts); } + catch { return null; } + } + + /// + /// Reverses the run described by : created files are + /// deleted and modified/deleted files are restored from their backups. Restores + /// run before deletes so a restore can never be clobbered. Idempotent: a created + /// file already gone, or a restore target already matching its backup, is a no-op. + /// Returns a tally of what was reverted (and any per-entry problems). + /// + public static RollbackResult Apply(RollbackManifest manifest, CancellationToken cancellationToken = default) + { + var result = new RollbackResult(); + + // Restore originals first (modified/deleted files), then remove created files. + foreach (var e in manifest.Entries.Where(e => e.Action == RollbackAction.Restore)) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + if (e.BackupPath is null || !File.Exists(e.BackupPath)) + { + result.Problems.Add($"missing backup for {e.OriginalPath}"); + continue; + } + var dir = Path.GetDirectoryName(e.OriginalPath); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.Copy(e.BackupPath, e.OriginalPath, overwrite: true); + result.Restored.Add(e.OriginalPath); + } + catch (Exception ex) + { + result.Problems.Add($"restore failed for {e.OriginalPath}: {ex.Message}"); + } + } + + foreach (var e in manifest.Entries.Where(e => e.Action == RollbackAction.Created)) + { + cancellationToken.ThrowIfCancellationRequested(); + try + { + if (File.Exists(e.OriginalPath)) + { + File.Delete(e.OriginalPath); + result.Deleted.Add(e.OriginalPath); + } + } + catch (Exception ex) + { + result.Problems.Add($"delete failed for {e.OriginalPath}: {ex.Message}"); + } + } + + return result; + } + + /// + /// Loads the manifest at , reverses it, and on + /// success removes its backup set folder. Returns the result, or null when the + /// manifest could not be read. + /// + public static RollbackResult? ApplyAndCleanup(string manifestPath, CancellationToken cancellationToken = default) + { + var manifest = TryLoadManifest(manifestPath); + if (manifest is null) return null; + var result = Apply(manifest, cancellationToken); + + // Only remove the backup set when the revert fully succeeded; on partial failure + // keep it so the originals remain available for a retry or manual recovery. + if (result.Problems.Count == 0) + { + try + { + var setDir = Path.GetDirectoryName(manifestPath); + if (setDir is not null && Directory.Exists(setDir)) Directory.Delete(setDir, recursive: true); + } + catch { /* leave the set if it cannot be removed; clean can mop up later */ } + } + + return result; + } + + private static bool PathEquals(string a, string b) => + string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase); +} + +/// The tally of a rollback: files restored, files deleted, and any problems. +public sealed class RollbackResult +{ + /// Original files restored from backups. + public List Restored { get; } = new(); + + /// Created files removed. + public List Deleted { get; } = new(); + + /// Non-fatal problems encountered per entry (a missing backup, etc.). + public List Problems { get; } = new(); + + /// Total files touched (restored + deleted). + public int Total => Restored.Count + Deleted.Count; +} diff --git a/tools/migrate/src/NanoMigrate.Core/Common/Glob.cs b/tools/migrate/src/NanoMigrate.Core/Common/Glob.cs new file mode 100644 index 0000000..ef3e19b --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Common/Glob.cs @@ -0,0 +1,81 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using System.Text.RegularExpressions; + +namespace nanoFramework.Migrate.Core.Common; + +/// +/// Small hand-rolled glob matcher (no external dependency). Matches a path that +/// is relative to the input directory against a pattern supporting: +/// * any run of characters except a path separator +/// ** any run of characters including path separators (spanning directories) +/// ? exactly one character except a path separator +/// Matching is case-insensitive and separator-insensitive ('/' and '\' are +/// treated as equivalent), and is anchored to the whole relative path. +/// +public static class Glob +{ + public static bool IsMatch(string relativePath, string pattern) + { + var input = Normalize(relativePath); + var regex = ToRegex(Normalize(pattern)); + return regex.IsMatch(input); + } + + private static string Normalize(string s) => s.Replace('\\', '/').Trim('/'); + + // Translates a normalized ('/'-separated) glob into an anchored, case-insensitive + // regex. Literal characters are escaped; only *, ** and ? carry meaning. + private static Regex ToRegex(string pattern) + { + var sb = new StringBuilder("^"); + for (int i = 0; i < pattern.Length; i++) + { + var c = pattern[i]; + switch (c) + { + // "/**" spans directories AND the leading separator is optional, so + // "Beginner/**" also matches "Beginner" itself. Emit "(/.*)?" and + // consume the slash, both stars, and any trailing slash. + case '/' when i + 2 < pattern.Length && pattern[i + 1] == '*' && pattern[i + 2] == '*': + i += 2; // consume '/' is current; skip both '*' + if (i + 1 < pattern.Length && pattern[i + 1] == '/') i++; + sb.Append("(/.*)?"); + break; + case '*': + if (i + 1 < pattern.Length && pattern[i + 1] == '*') + { + i++; // consume the second '*' + // "**/" spans zero or more WHOLE directory segments, so it must end + // on a separator: "**/Foo.nfproj" matches "Foo.nfproj" and "a/Foo.nfproj" + // but not "MyFoo.nfproj". A trailing "**" (no following slash) matches the + // rest of the path, separators included. + if (i + 1 < pattern.Length && pattern[i + 1] == '/') + { + i++; + sb.Append("(?:.*/)?"); + } + else + { + sb.Append(".*"); + } + } + else + { + sb.Append("[^/]*"); // single star: stay within a segment + } + break; + case '?': + sb.Append("[^/]"); + break; + default: + sb.Append(Regex.Escape(c.ToString())); + break; + } + } + sb.Append('$'); + return new Regex(sb.ToString(), RegexOptions.IgnoreCase | RegexOptions.CultureInvariant); + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Common/ProcessExec.cs b/tools/migrate/src/NanoMigrate.Core/Common/ProcessExec.cs new file mode 100644 index 0000000..dace4ac --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Common/ProcessExec.cs @@ -0,0 +1,76 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Diagnostics; +using System.Text; + +namespace nanoFramework.Migrate.Core.Common; + +/// +/// Runs an external process and returns its exit code plus captured output. One place +/// for the spawn details every caller needs to get right: stdout/stderr are drained +/// concurrently (sequential ReadToEnd() can deadlock when a child fills one +/// buffer while we block on the other), cancellation kills the child so a long +/// git/dotnet invocation stops promptly, and a timeout bounds a wedged process. +/// +public static class ProcessExec +{ + /// Generous default cap so a hung child can't block the run indefinitely. + public const int DefaultTimeoutMs = 600_000; + + /// + /// Starts with in + /// , returning (exitCode, stdout, stderr). + /// On timeout the child is killed and a synthetic -1 result with a timeout + /// message is returned; on cancellation the child is killed and + /// is thrown. + /// + public static (int exitCode, string stdout, string stderr) Run( + string fileName, string arguments, string workingDirectory, + int timeoutMs = DefaultTimeoutMs, CancellationToken cancellationToken = default) + { + var psi = new ProcessStartInfo(fileName, arguments) + { + WorkingDirectory = workingDirectory, + RedirectStandardOutput = true, + RedirectStandardError = true, + UseShellExecute = false, + CreateNoWindow = true, + }; + using var p = Process.Start(psi) ?? throw new InvalidOperationException($"failed to start process: {fileName}"); + // Cancellation (Ctrl+C / console close) kills the child so it stops promptly. + using var reg = cancellationToken.Register(static state => + { + var proc = (Process)state!; + try { if (!proc.HasExited) proc.Kill(entireProcessTree: true); } catch { /* already gone */ } + }, p); + + // Named local functions (not lambdas) so the handlers can be detached afterwards, + // leaving no reference from the Process to the captured builders. + var so = new StringBuilder(); + var se = new StringBuilder(); + void OnOutput(object? _, DataReceivedEventArgs e) { if (e.Data is not null) so.AppendLine(e.Data); } + void OnError(object? _, DataReceivedEventArgs e) { if (e.Data is not null) se.AppendLine(e.Data); } + p.OutputDataReceived += OnOutput; + p.ErrorDataReceived += OnError; + try + { + p.BeginOutputReadLine(); + p.BeginErrorReadLine(); + + if (!p.WaitForExit(timeoutMs)) + { + try { p.Kill(entireProcessTree: true); } catch { /* already exited */ } + return (-1, so.ToString(), $"process timed out after {timeoutMs / 1000}s: {fileName} {arguments}"); + } + p.WaitForExit(); // ensure the async output handlers have flushed + cancellationToken.ThrowIfCancellationRequested(); // a cancel-kill surfaces as cancellation, not a bad exit code + return (p.ExitCode, so.ToString(), se.ToString()); + } + finally + { + p.OutputDataReceived -= OnOutput; + p.ErrorDataReceived -= OnError; + } + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Common/ProjectScanner.cs b/tools/migrate/src/NanoMigrate.Core/Common/ProjectScanner.cs new file mode 100644 index 0000000..a35b509 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Common/ProjectScanner.cs @@ -0,0 +1,48 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Common; + +/// +/// Enumerates .nfproj files under a path, with an optional glob filter. +/// Pure file-system discovery — no console, no side effects. +/// +public static class ProjectScanner +{ + /// + /// Resolves the set of .nfproj targets for a path. If + /// is a single .nfproj file it is returned alone; if it is a directory, + /// every .nfproj beneath it (optionally filtered by , + /// matched against the path relative to the directory) is returned, sorted. + /// A non-existent path yields an empty list. + /// + public static List ResolveProjects(string path, string? glob) + { + if (File.Exists(path) && path.EndsWith(".nfproj", StringComparison.OrdinalIgnoreCase)) + return new List { Path.GetFullPath(path) }; + if (!Directory.Exists(path)) return new List(); + + var baseDir = Path.GetFullPath(path); + return Directory.EnumerateFiles(path, "*.nfproj", SearchOption.AllDirectories) + .Select(Path.GetFullPath) + .Where(p => glob is null || Glob.IsMatch(Path.GetRelativePath(baseDir, p), glob)) + .OrderBy(p => p) + .ToList(); + } + + /// + /// Enumerates the .nfproj under a repo directory that survive the glob + /// filter (matched against the path relative to the repo directory). Returns + /// absolute, full paths. + /// + public static IEnumerable NfprojUnder(string repoDir, string? glob) + { + var baseDir = Path.GetFullPath(repoDir); + foreach (var nf in Directory.EnumerateFiles(repoDir, "*.nfproj", SearchOption.AllDirectories)) + { + var full = Path.GetFullPath(nf); + if (glob is null || Glob.IsMatch(Path.GetRelativePath(baseDir, full), glob)) + yield return full; + } + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Fleet/FleetService.cs b/tools/migrate/src/NanoMigrate.Core/Fleet/FleetService.cs new file mode 100644 index 0000000..dcdafde --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Fleet/FleetService.cs @@ -0,0 +1,265 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using nanoFramework.Migrate.Core.Common; +using nanoFramework.Migrate.Core.Projects; + +namespace nanoFramework.Migrate.Core.Fleet; + +/// Result of a single git invocation. Mirrors a process exit. +public readonly record struct GitResult(int Code, string Stdout, string Stderr); + +/// +/// Runs git in a working directory. The engine stays process-free by delegating +/// the actual side effect to an implementation supplied by the host (the CLI). +/// +public interface IGitRunner +{ + GitResult Run(string args, string workingDirectory, CancellationToken cancellationToken = default); +} + +/// The knobs that drive a fleet run, layered over the per-project options. +public sealed record FleetOptions +{ + /// Per-project conversion options applied to every project in the fleet. + public ConversionOptions Conversion { get; init; } = new(); + + /// Markdown report path. + public string Report { get; init; } = "migration-report.md"; + + /// Create/reset this git branch in each repo. Must not start with 'develop'. + public string? Branch { get; init; } + + /// Commit the changes (requires ). + public bool Commit { get; init; } + + /// Commit summary line (kept <= 50 chars). + public string? CommitMessage { get; init; } + + /// Referenced as "Fix #<n>" in the commit. + public string? Issue { get; init; } + + /// nanoFramework recommends a Signed-off-by line; on by default. + public bool SignOff { get; init; } = true; +} + +/// +/// Pure fleet orchestration: validate options, discover repos, convert every +/// project in each, optionally branch and commit (via an injected +/// ), and produce a markdown report. Never writes to the +/// console; progress is surfaced through an optional callback so a host can drive +/// a spinner. +/// +public sealed class FleetService +{ + private readonly IProjectConverter _converter; + private readonly IGitRunner _git; + + public FleetService(IProjectConverter converter, IGitRunner git) + { + _converter = converter; + _git = git; + } + + /// + /// Validates the fleet options against the repos directory, throwing + /// with a user-facing message on any problem. + /// Mirrors the original command's up-front checks. + /// + public List ResolveRepos(string reposDir, FleetOptions o) + { + if (!Directory.Exists(reposDir)) throw new ArgumentException($"directory not found: {reposDir}"); + if (o.Commit && o.Branch is null) throw new ArgumentException("--commit requires --branch"); + // nanoFramework workflow: branch names must not start with "develop" (they + // collide with upstream develop-* branches). + if (o.Branch is not null && o.Branch.StartsWith("develop", StringComparison.OrdinalIgnoreCase)) + throw new ArgumentException("branch name must not start with 'develop' (nanoFramework workflow); " + + "use something like 'sdk-migration' or 'issue-123'"); + // The branch is interpolated into `git checkout -B `; reject anything that + // could smuggle a git option or otherwise alter argument parsing. + if (o.Branch is not null && !IsSafeBranchName(o.Branch)) + throw new ArgumentException("invalid branch name; use only letters, digits, '.', '_', '-', '/' " + + "and do not start with '-'"); + + // A repo qualifies if it contains at least one .nfproj that survives the + // glob filter (default: any .nfproj). + bool RepoMatches(string d) => ProjectScanner.NfprojUnder(d, o.Conversion.Glob).Any(); + + var repoDirs = Directory.EnumerateDirectories(reposDir) + .Where(RepoMatches) + .OrderBy(d => d).ToList(); + if (repoDirs.Count == 0) + throw new ArgumentException(o.Conversion.Glob is null + ? $"no repos containing .nfproj found under '{reposDir}'" + : $"no repos with .nfproj matching glob '{o.Conversion.Glob}' found under '{reposDir}'"); + return repoDirs; + } + + /// + /// Processes every repo: optionally branch, convert each project, optionally + /// commit. (if supplied) is invoked with each repo + /// name before it is processed. Returns one per repo. + /// + public List Process(List repoDirs, FleetOptions o, Action? progress = null, + CancellationToken cancellationToken = default) + { + // In a git repo the commit history already preserves the pre-migration file, + // so a .bak alongside it is just noise in the diff. Skip backups when committing. + var conv = o.Commit ? o.Conversion with { NoBackup = true } : o.Conversion; + + var report = new List(); + foreach (var repo in repoDirs) + { + cancellationToken.ThrowIfCancellationRequested(); + progress?.Invoke(Path.GetFileName(repo)); + var rr = new RepoReport { Name = Path.GetFileName(repo) }; + try + { + if (o.Branch is not null && !conv.DryRun) + { + var checkout = _git.Run($"checkout -B {o.Branch}", repo, cancellationToken); + if (checkout.Code != 0) { rr.Error = $"git checkout failed: {checkout.Stderr.Trim()}"; report.Add(rr); continue; } + } + + foreach (var nf in ProjectScanner.NfprojUnder(repo, conv.Glob).OrderBy(p => p)) + { + cancellationToken.ThrowIfCancellationRequested(); + rr.Projects++; + var result = _converter.Convert(nf, conv, cancellationToken); + var rel = Path.GetRelativePath(repo, nf); + foreach (var item in result.Review) rr.Review.Add($"{rel}: {item}"); + } + + if (o.Commit && !conv.DryRun) + { + _git.Run("add -A", repo, cancellationToken); + var msgFile = WriteCommitMessage(o); + var signOff = o.SignOff ? "-s " : ""; + var commit = _git.Run($"commit {signOff}-F \"{msgFile}\"", repo, cancellationToken); + File.Delete(msgFile); + rr.Committed = commit.Code == 0; + if (commit.Code != 0 && !commit.Stderr.Contains("nothing to commit")) + { + rr.Error = commit.Stderr.Contains("Please tell me who you are") || commit.Stderr.Contains("user.name") + ? "git commit failed: set git user.name/user.email (real name) so the " + + "Signed-off-by line is valid, or pass --no-sign-off" + : $"git commit: {commit.Stderr.Trim()}"; + } + } + } + catch (Exception ex) + { + rr.Error = ex.Message; + } + report.Add(rr); + } + return report; + } + + /// Builds the markdown fleet report and writes it to o.Report. + public void WriteReport(List report, FleetOptions o, string reposDir) + { + // Create the report's parent directory so a nested --report path (e.g. + // reports/fleet/migration.md) does not fail the write. + var dir = Path.GetDirectoryName(Path.GetFullPath(o.Report)); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(o.Report, BuildReport(report, o, reposDir)); + } + + // Reject branch names that could smuggle a git option or otherwise alter argument + // parsing when interpolated into `git checkout -B `. + private static bool IsSafeBranchName(string branch) => + branch.Length > 0 + && !branch.StartsWith('-') + && branch.All(c => char.IsLetterOrDigit(c) || c is '.' or '_' or '-' or '/'); + + /// Builds the markdown fleet report as a string (pure; no I/O). + public static string BuildReport(List report, FleetOptions o, string reposDir) + { + var sb = new StringBuilder(); + sb.AppendLine("# nanoFramework SDK-style migration — fleet report\n"); + sb.AppendLine($"- Source: `{Path.GetFullPath(reposDir)}`"); + sb.AppendLine($"- Mode: {(o.Conversion.DryRun ? "dry-run (no files written)" : "applied")}" + + (o.Branch is not null ? $", branch `{o.Branch}`" : "") + + (o.Commit ? ", committed" : "")); + sb.AppendLine($"- SDK `nanoFramework.NET.Sdk` (versionless), TFM `{o.Conversion.Tfm}`, output extension `{o.Conversion.Ext}`\n"); + + int total = report.Count, clean = report.Count(r => r.Error is null && r.Review.Count == 0); + int needsReview = report.Count(r => r.Error is null && r.Review.Count > 0); + int errors = report.Count(r => r.Error is not null); + sb.AppendLine("## Summary\n"); + sb.AppendLine($"| Repos | Clean | Needs review | Errored |"); + sb.AppendLine($"|------:|------:|-------------:|--------:|"); + sb.AppendLine($"| {total} | {clean} | {needsReview} | {errors} |\n"); + + if (errors > 0) + { + sb.AppendLine("## Errored repos\n"); + foreach (var r in report.Where(r => r.Error is not null)) + sb.AppendLine($"- **{r.Name}** — {r.Error}"); + sb.AppendLine(); + } + + if (needsReview > 0) + { + sb.AppendLine("## Repos needing manual review\n"); + sb.AppendLine("These migrated, but the tool could not confidently resolve everything. " + + "Each line is something a human should confirm before merging.\n"); + foreach (var r in report.Where(r => r.Error is null && r.Review.Count > 0)) + { + sb.AppendLine($"### {r.Name}\n"); + foreach (var item in r.Review) sb.AppendLine($"- {item}"); + sb.AppendLine(); + } + } + + if (clean > 0) + { + sb.AppendLine("## Clean migrations\n"); + sb.AppendLine("Converted with no items flagged for review:\n"); + foreach (var r in report.Where(r => r.Error is null && r.Review.Count == 0)) + sb.AppendLine($"- {r.Name} ({r.Projects} project(s))" + + (r.Committed ? " — committed" : "")); + sb.AppendLine(); + } + + return sb.ToString(); + } + + // Builds a commit message that follows the nanoFramework guidance: a short + // summary (<= 50 chars), a blank line, a body wrapped at 72 columns, and an + // optional "Fix #" trailer. Returns the path to a temp message file. + private static string WriteCommitMessage(FleetOptions o) + { + var summary = o.CommitMessage ?? "Migrate project system to SDK-style"; + if (summary.Length > 50) summary = summary[..50].TrimEnd(); + + var body = Wrap( + "Convert the legacy .nfproj project system to an SDK-style MSBuild project: " + + "drop project-system boilerplate, fold packages.config into PackageReference, " + + "and fold .nuspec metadata into MSBuild Pack properties. " + + "No functional code changes.", 72); + + var sb = new StringBuilder(); + sb.Append(summary).Append("\n\n").Append(body).Append('\n'); + if (o.Issue is not null) sb.Append("\nFix #").Append(o.Issue).Append('\n'); + + var path = Path.GetTempFileName(); + File.WriteAllText(path, sb.ToString()); + return path; + } + + private static string Wrap(string text, int width) + { + var sb = new StringBuilder(); + int lineLen = 0; + foreach (var word in text.Split(' ', StringSplitOptions.RemoveEmptyEntries)) + { + if (lineLen > 0 && lineLen + 1 + word.Length > width) { sb.Append('\n'); lineLen = 0; } + else if (lineLen > 0) { sb.Append(' '); lineLen++; } + sb.Append(word); lineLen += word.Length; + } + return sb.ToString(); + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Fleet/RepoReport.cs b/tools/migrate/src/NanoMigrate.Core/Fleet/RepoReport.cs new file mode 100644 index 0000000..8ce6d06 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Fleet/RepoReport.cs @@ -0,0 +1,14 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Fleet; + +/// Per-repo outcome accumulated by the fleet command. Pure data. +public sealed class RepoReport +{ + public required string Name { get; init; } + public int Projects { get; set; } + public List Review { get; } = new(); + public bool Committed { get; set; } + public string? Error { get; set; } +} diff --git a/tools/migrate/src/NanoMigrate.Core/NanoMigrate.Core.csproj b/tools/migrate/src/NanoMigrate.Core/NanoMigrate.Core.csproj new file mode 100644 index 0000000..935ad76 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/NanoMigrate.Core.csproj @@ -0,0 +1,44 @@ + + + + net10.0 + enable + enable + nanoFramework.Migrate.Core + NanoMigrate.Core + true + + + + + nanoFramework.Migrate.Core + nanoFramework Migrate (Core) + Conversion engine that migrates legacy nanoFramework .nfproj projects to the SDK-style MSBuild project system: folds packages.config into PackageReference and .nuspec metadata into Pack properties. Console-free library; see the nano-migrate CLI for an interactive front end. + nanoFramework + nanoFramework + https://github.com/nanoframework/nf-tools + https://github.com/nanoframework/nf-tools + git + MIT + nanoFramework;MSBuild;SDK;migration;nfproj;IoT;embedded;C# + Copyright (c) .NET Foundation and Contributors + false + + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + + + + + + + + + diff --git a/tools/migrate/src/NanoMigrate.Core/Projects/ConversionOptions.cs b/tools/migrate/src/NanoMigrate.Core/Projects/ConversionOptions.cs new file mode 100644 index 0000000..0b7027d --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Projects/ConversionOptions.cs @@ -0,0 +1,78 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Projects; + +/// +/// The knobs that drive a conversion. This is the engine-facing options type — it +/// is intentionally NOT the CLI settings type, so the engine carries no console or +/// command-line dependency. The CLI maps its parsed settings onto this record. +/// +public sealed record ConversionOptions +{ + /// + /// Output extension for the emitted project. Either .csproj or + /// .nfproj. Default .csproj: a normal run produces Foo.csproj and + /// retires Foo.nfproj. + /// + public string Ext { get; init; } = ".csproj"; + + /// Target framework moniker written into the emitted project. + public string Tfm { get; init; } = "netnano1.0"; + + /// + /// Accepted for back-compat but no longer emitted: the SDK reference is + /// versionless (the version is pinned via global.json msbuild-sdks). + /// + public string Sdk { get; init; } = "2.0.0"; + + /// Analyse and preview only; write nothing to disk. + public bool DryRun { get; init; } + + /// Don't write a .nfproj.bak alongside the converted project. + public bool NoBackup { get; init; } + + /// + /// Glob filter (relative to the input directory) selecting which .nfproj + /// to convert. Null means "all .nfproj recursively" (the default). + /// Supports *, ** and ?. + /// + public string? Glob { get; init; } + + /// + /// Suppress the converter's built-in solution retargeting (its walk-up + /// discovery + rewrite). Set when the host drives a solution-scoped + /// migration and rewrites the chosen solutions itself via + /// , so the converter never touches a solution the + /// user did not select. The preview + /// list is still populated. Default false preserves the historical behavior. + /// + public bool SkipSolutionRewrite { get; init; } + + /// + /// After a real (non-dry-run) migration, verify the result by building the + /// affected solution(s)/project(s) with the dotnet CLI. null (the + /// default) means "verify on for real runs, off for dry-run"; set + /// true/false to force it on/off. A failed verification is what + /// triggers the rollback prompt. + /// + public bool? Verify { get; init; } + + /// + /// Resolves against : dry-run never + /// verifies; otherwise the default is on. + /// + public bool VerifyEffective => !DryRun && (Verify ?? true); + + /// + /// Central Package Management (CPM) override. null (the default) means + /// auto-detect: the converter walks up from the project directory for a + /// Directory.Packages.props with + /// <ManagePackageVersionsCentrally>true</ManagePackageVersionsCentrally>. + /// Set true/false to force CPM on/off regardless of what is on disk. + /// When CPM is active the emitted PackageReference elements are versionless + /// and each referenced id is ensured to have a PackageVersion entry in the + /// nearest Directory.Packages.props. + /// + public bool? CentralPackageManagement { get; init; } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Projects/ConvertResult.cs b/tools/migrate/src/NanoMigrate.Core/Projects/ConvertResult.cs new file mode 100644 index 0000000..5a69b27 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Projects/ConvertResult.cs @@ -0,0 +1,68 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Projects; + +/// How a single project ended up after a (dry-run or real) conversion. +public enum ConvertStatus +{ + /// Converted cleanly. + Converted, + + /// Already SDK-style; nothing to do. + Skipped, + + /// Converted, but flagged items need a human. + Review, + + /// Threw while converting. + Error, +} + +/// +/// Outcome of converting a single project, expressed as DATA. The engine never +/// writes to the console — the CLI consumes this to render its presentation. +/// +public sealed class ConvertResult +{ + /// The path the conversion emits (or, in dry-run, would emit). + public required string OutputPath { get; init; } + + /// Items the tool could not confidently resolve; each needs a human. + public List Review { get; } = new(); + + /// True when the project was already SDK-style and was left untouched. + public bool AlreadySdk { get; set; } + + /// Resolved PackageReferences (id -> version) the emitted project will carry. + public List> Packages { get; } = new(); + + /// Files this conversion deletes (or, in dry-run, would delete). + public List DeletedFiles { get; } = new(); + + /// .sln files this conversion retargets (or, in dry-run, would retarget). + public List UpdatedSolutions { get; } = new(); + + /// + /// Under Central Package Management, the Directory.Packages.props this + /// conversion adds PackageVersion entries to (or, in dry-run, would add). + /// Null when CPM is inactive or no entries are missing. + /// + public string? UpdatedPackagesProps { get; set; } + + /// + /// The PackageVersion entries (id -> version) added to the central + /// Directory.Packages.props under CPM (or, in dry-run, that would be added). + /// + public List> AddedPackageVersions { get; } = new(); + + /// Set when the conversion threw; used to render a red Error row. + public string? Error { get; set; } + + /// Derived status, computed from the data above. + public ConvertStatus Status => + Error is not null ? ConvertStatus.Error + : AlreadySdk ? ConvertStatus.Skipped + : Review.Count > 0 ? ConvertStatus.Review + : ConvertStatus.Converted; +} diff --git a/tools/migrate/src/NanoMigrate.Core/Projects/IProjectConverter.cs b/tools/migrate/src/NanoMigrate.Core/Projects/IProjectConverter.cs new file mode 100644 index 0000000..dc75067 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Projects/IProjectConverter.cs @@ -0,0 +1,18 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Projects; + +/// +/// Converts a single legacy .nfproj into an SDK-style project. The result +/// is returned as data; implementations never write to the console. +/// +public interface IProjectConverter +{ + /// + /// Converts the project at per . + /// In dry-run mode nothing is written; the returned + /// still describes exactly what a real run would change. + /// + ConvertResult Convert(string nfprojPath, ConversionOptions options, CancellationToken cancellationToken = default); +} diff --git a/tools/migrate/src/NanoMigrate.Core/Projects/ProjectConverter.cs b/tools/migrate/src/NanoMigrate.Core/Projects/ProjectConverter.cs new file mode 100644 index 0000000..86345df --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Projects/ProjectConverter.cs @@ -0,0 +1,808 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using System.Text.RegularExpressions; +using System.Xml.Linq; +using nanoFramework.Migrate.Core.Solutions; + +namespace nanoFramework.Migrate.Core.Projects; + +/// +/// Converts one legacy .nfproj into an SDK-style project. Faithful to the +/// reference rules: drop project-system boilerplate and SDK-supplied defaults, +/// fold packages.config into PackageReference, fold .nuspec metadata into Pack +/// properties, drop default Compile globs and a hand-written AssemblyInfo.cs, +/// and "fail loud" — anything it cannot confidently convert is surfaced for a +/// human rather than guessed. +/// +public sealed class ProjectConverter : IProjectConverter +{ + private static readonly XNamespace Ns = "http://schemas.microsoft.com/developer/msbuild/2003"; + + // Project-system boilerplate and properties the SDK now supplies itself. + private static readonly HashSet DropProps = new(StringComparer.Ordinal) + { + "ProjectTypeGuids", "ProjectGuid", "FileAlignment", "AppDesignerFolder", + "NanoFrameworkProjectSystemPath", "TargetFrameworkVersion", "OldToolsVersion", + "Configuration", "Platform", + }; + + // The converter emits the TFM itself (see Emit), so a source TargetFramework is not + // carried through. Every other non-boilerplate property is passed through verbatim + // (OutputType, LangVersion, Nullable, SignAssembly, IsTestProject, custom props, …) — + // silently dropping unknown properties was a bug (e.g. OutputType=Exe was lost, turning + // app projects into libraries → CS8805). + private static readonly HashSet EmittedProps = new(StringComparer.Ordinal) + { + "TargetFramework", + }; + + // Legacy names whose NuGet package id differs from X. + private static readonly Dictionary LegacyPkgAliases = new(StringComparer.Ordinal) + { + ["mscorlib"] = "nanoFramework.CoreLibrary", + ["System"] = "nanoFramework.CoreLibrary", + }; + + // Matches a NuGet "packages\.\" folder segment inside a HintPath. + // is greedy-then-split: the version is the tail starting at the first + // dotted segment that begins with a digit, so prerelease/build suffixes + // (e.g. "2.0.0-preview.52") stay attached to the version, not the id. + private static readonly Regex HintPathPackage = new( + @"[\\/]packages[\\/](?[^\\/]+)[\\/]", + RegexOptions.Compiled | RegexOptions.IgnoreCase); + + // The SDK reference is versionless; the concrete version is pinned via a + // global.json `msbuild-sdks` entry, not the Sdk attribute. + private const string SdkReference = "nanoFramework.NET.Sdk"; + + public ConvertResult Convert(string nfprojPath, ConversionOptions options, CancellationToken cancellationToken = default) + { + cancellationToken.ThrowIfCancellationRequested(); + var nfproj = nfprojPath; + var o = options; + var projDir = Path.GetDirectoryName(Path.GetFullPath(nfproj))!; + var root = XElement.Load(nfproj); + + // Idempotency guard: an SDK-style project already has an Sdk attribute on + // the root. Treat it as already-converted and skip without touching disk, + // so a second run over a repo is a true no-op rather than destructive. + if (root.Attribute("Sdk") is not null) + { + var skipped = new ConvertResult { OutputPath = Path.GetFullPath(nfproj), AlreadySdk = true }; + skipped.Review.Add("already SDK-style; skipped"); + return skipped; + } + + var pkgs = LoadPackagesConfig(projDir); + // packages.config — when present and non-empty — IS the authoritative + // dependency list. In that mode legacy assembly names are NOT + // mapped to packages (their names routinely differ from the NuGet package + // id, e.g. assembly "System.Net.Http" ships in package + // "nanoFramework.System.Net.Http.Server"); the packages.config ids+versions + // are taken verbatim instead, eliminating the name/id mismatch. + var packagesConfigAuthoritative = pkgs.Count > 0; + + // Detect Central Package Management: an explicit option override wins; + // otherwise walk up for a Directory.Packages.props with + // ManagePackageVersionsCentrally=true. + var cpmPropsPath = FindDirectoryPackagesProps(projDir); + var cpmActive = o.CentralPackageManagement + ?? (cpmPropsPath is not null && IsCpmEnabled(cpmPropsPath)); + + var props = new List>(); // discovery order, deduped + var pkgRefs = new Dictionary(StringComparer.OrdinalIgnoreCase); + var projRefs = new List(); + var keepItems = new List(); + var review = new List(); + // Normalized relative paths of .cs files the legacy project explicitly + // compiled and that the SDK would also glob by default. Used to detect a + // legacy project that compiled only a SUBSET of the .cs files on disk: the + // unlisted ones must be excluded via , else the SDK's + // **/*.cs glob compiles files the project never built (duplicate types). + var explicitCompile = new HashSet(StringComparer.OrdinalIgnoreCase); + // Top-level projects to carry through verbatim — notably a Shared + // Project (.projitems) import, whose source files the SDK would otherwise + // never see (dropping it leaves the consuming project missing those types). + var imports = new List(); + + // Seed package references straight from packages.config when it is the + // authoritative source. Drop the legacy elements entirely in + // this mode (handled in the item loop below). + if (packagesConfigAuthoritative) + foreach (var kv in pkgs) + pkgRefs[kv.Key] = kv.Value; + + void SetProp(string k, string? v) + { + if (string.IsNullOrEmpty(v)) return; + if (props.Any(p => p.Key == k)) return; + props.Add(new(k, v)); + } + + // Read by local name so the converter works whether the input uses the + // legacy MSBuild namespace or none at all. + foreach (var pg in root.Elements().Where(e => e.Name.LocalName == "PropertyGroup")) + foreach (var el in pg.Elements()) + { + var tag = el.Name.LocalName; + if (DropProps.Contains(tag)) continue; // project-system boilerplate the SDK supplies + if (EmittedProps.Contains(tag)) continue; // the converter emits these itself (e.g. TargetFramework) + SetProp(tag, el.Value); // pass through everything else (OutputType, LangVersion, …) + } + + // Top-level elements. The NFProjectSystem.* props/targets imports are + // SDK-supplied boilerplate and are dropped. A Shared Project (.projitems) import + // carries real source into the project and MUST be preserved, else its types go + // missing (CS0246). Anything else unrecognized is surfaced for review. + foreach (var imp in root.Elements().Where(e => e.Name.LocalName == "Import")) + { + var project = (string?)imp.Attribute("Project") ?? ""; + if (project.Contains("NFProjectSystem", StringComparison.OrdinalIgnoreCase)) continue; + if (project.EndsWith(".projitems", StringComparison.OrdinalIgnoreCase)) + { + imports.Add(project); + continue; + } + if (!string.IsNullOrWhiteSpace(project)) + review.Add($"Unhandled (carry it over manually if needed)"); + } + + foreach (var ig in root.Elements().Where(e => e.Name.LocalName == "ItemGroup")) + foreach (var el in ig.Elements()) + { + var tag = el.Name.LocalName; + var inc = (string?)el.Attribute("Include") ?? ""; + switch (tag) + { + case "Reference": + { + // packages.config is authoritative: it already carries the + // full dependency set, so legacy assembly names + // are dropped rather than (mis)mapped to a package id. + if (packagesConfigAuthoritative) break; + + var rawName = inc.Split(',')[0].Trim(); + // Prefer id+version parsed straight from the HintPath folder. + var fromHint = InferFromHintPath(el); + if (fromHint is not null) + { + pkgRefs[fromHint.Value.id] = fromHint.Value.ver; + break; + } + // Fallback: resolve the package id via the alias table, then + // look up its version in packages.config. + var name = LegacyPkgAliases.GetValueOrDefault(rawName, rawName); + var ver = pkgs.GetValueOrDefault(name) ?? pkgs.GetValueOrDefault(rawName); + if (ver is not null) pkgRefs[name] = ver; + else + review.Add($"Reference without resolvable version: {inc} " + + "(no HintPath or packages.config entry; map to a PackageReference manually)"); + break; + } + case "PackageReference": + { + // A versionless is valid under CPM; carry + // it through (its version, if any, comes from the central + // props). Otherwise resolve a version from the attribute or + // packages.config; only flag when truly unresolvable. + var ver = (string?)el.Attribute("Version") ?? pkgs.GetValueOrDefault(inc); + if (ver is not null) pkgRefs[inc] = ver; + else if (cpmActive) pkgRefs.TryAdd(inc, ""); // version lives in central props + else + review.Add($"PackageReference without resolvable version: {inc} " + + "(add a Version manually)"); + break; + } + case "ProjectReference": + projRefs.Add(inc); + break; + case "Compile": + // Explicit Compile of a hand-written AssemblyInfo / default-globbed + // .cs is dropped (the SDK globs **/*.cs). Keep only non-default + // paths or links the SDK would NOT glob. (Files on disk that the + // legacy project deliberately did NOT compile are excluded via a + // Compile Remove computed after the loop — see explicitCompile.) + if (el.Attribute("Link") is not null || !IsDefaultCompile(inc)) + keepItems.Add(el); + else + explicitCompile.Add(NormalizeRel(inc)); + break; + case "None": + // packages.config and the .nuspec are folded away, never carried. + if (inc == "packages.config" || inc.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase)) + break; + KeepOrUpdateDefaultGlobItem(el, keepItems); + break; + case "EmbeddedResource": + case "Content": + KeepOrUpdateDefaultGlobItem(el, keepItems); + break; + case "ProjectCapability": + // nanoFramework test projects mark themselves with + // ; this is a + // meaningful item the SDK does not supply, so carry it through. + keepItems.Add(el); + break; + default: + review.Add($"Unhandled item <{tag} Include='{inc}'>"); + break; + } + } + + FoldNuspec(projDir, SetProp); + + // A hand-written AssemblyInfo.cs that carries nanoFramework-specific + // attributes the SDK's GenerateAssemblyInfo does NOT emit (notably + // AssemblyNativeVersion, required by the MetadataProcessor when generating + // interop/skeleton stubs) must be KEPT rather than deleted. In that case we + // turn GenerateAssemblyInfo off so the hand-written file is authoritative + // and the standard attributes it also declares don't collide with generated + // ones. Otherwise the file is deleted as before (it would duplicate the + // SDK-generated assembly attributes). + var keepAssemblyInfo = HasNanoAssemblyInfo(projDir); + if (keepAssemblyInfo) SetProp("GenerateAssemblyInfo", "false"); + + // Compile-subset exclusion: when the legacy project explicitly compiled a + // strict subset of the .cs files present on disk, the unlisted files must be + // removed from the SDK's default **/*.cs glob. Without this the SDK compiles + // source the project never built (e.g. an alternate/draft copy of a class), + // producing duplicate-definition errors. Only meaningful when the project + // had explicit Compile items in the first place. + var compileRemoves = new List(); + if (explicitCompile.Count > 0) + foreach (var rel in OnDiskDefaultCompile(projDir)) + if (!explicitCompile.Contains(rel)) + compileRemoves.Add(rel); + + var xml = Emit(props, pkgRefs, projRefs, keepItems, compileRemoves, imports, o, cpmActive); + + var outPath = Path.ChangeExtension(Path.GetFullPath(nfproj), o.Ext); + var nfFull = Path.GetFullPath(nfproj); + var replacingNfproj = !string.Equals(outPath, nfFull, StringComparison.OrdinalIgnoreCase); + + var result = new ConvertResult { OutputPath = outPath }; + result.Review.AddRange(review); + result.Packages.AddRange(pkgRefs.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase)); + + // Under CPM, each referenced id must have a in the nearest + // Directory.Packages.props. Compute the ids whose version we know (from + // packages.config / HintPath) that are missing from the central props, and + // record them; the real run adds them idempotently below. Versionless ids + // (no resolvable version) cannot seed a PackageVersion and are left as-is. + var cpmAdditions = new List>(); + if (cpmActive && cpmPropsPath is not null) + { + var existing = LoadPackageVersionIds(cpmPropsPath); + foreach (var kv in pkgRefs.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase)) + if (!string.IsNullOrEmpty(kv.Value) && !existing.Contains(kv.Key)) + cpmAdditions.Add(kv); + foreach (var add in cpmAdditions) + result.AddedPackageVersions.Add(add); + if (cpmAdditions.Count > 0) result.UpdatedPackagesProps = cpmPropsPath; + } + + // Compute the set of files that will be (or, in dry-run, would be) removed + // and the solutions that will be retargeted. This drives the dry-run + // preview and is identical to what the real run acts on. + if (replacingNfproj) result.DeletedFiles.Add(nfFull); + var pc = Path.Combine(projDir, "packages.config"); + if (File.Exists(pc)) result.DeletedFiles.Add(Path.GetFullPath(pc)); + if (!keepAssemblyInfo) + foreach (var ai in ExistingAssemblyInfo(projDir)) result.DeletedFiles.Add(ai); + // The .sln/.slnx that still reference the .nfproj are what a rewrite would + // touch. We always populate this preview list (even when SkipSolutionRewrite + // is set, so the host can render it); the actual rewrite below is gated. + if (replacingNfproj) + foreach (var sln in SolutionsReferencing(projDir, nfFull)) result.UpdatedSolutions.Add(sln); + + if (!o.DryRun) + { + // The loose, next-to-project *.nfproj.bak is purely the opt-in backup + // convenience: it is written ONLY when backups are enabled (default) and + // suppressed entirely under --no-backup. The rollback journal does NOT rely + // on it — the journal keeps its own copy of the original .nfproj inside + // .nanomigrate/rollback-/ — so a --no-backup run leaves zero loose .bak + // yet is still fully reversible. Never clobber an existing backup: the + // original first-run .bak must survive reruns. + if (!o.NoBackup && !File.Exists(nfproj + ".bak")) File.Copy(nfproj, nfproj + ".bak", overwrite: false); + File.WriteAllText(outPath, xml, new UTF8Encoding(false)); + // Add any missing entries to the central props, + // idempotently (existing entries are neither duplicated nor reordered). + if (cpmActive && cpmPropsPath is not null && cpmAdditions.Count > 0) + AddPackageVersions(cpmPropsPath, cpmAdditions); + // If we emitted a .csproj alongside, retire the original .nfproj. + if (replacingNfproj) + { + File.Delete(nfproj); + // Point any .sln/.slnx entries at the new .csproj (idempotent), + // unless the host is driving solution rewriting itself. + if (!o.SkipSolutionRewrite) UpdateSolutions(projDir, nfFull); + } + if (File.Exists(pc)) File.Delete(pc); + // The SDK default **/*.cs glob plus generated assembly info would + // otherwise produce duplicate-attribute build errors, so delete a + // hand-written AssemblyInfo.cs from disk (dropping the Compile item + // is not enough). EXCEPTION: an AssemblyInfo.cs that carries + // nanoFramework-specific attributes the SDK never generates is kept + // (with GenerateAssemblyInfo=false set above) so those attributes + // survive — deleting it would break MetadataProcessor stub generation. + if (!keepAssemblyInfo) DeleteAssemblyInfo(projDir); + } + + return result; + } + + // Paths of any hand-written AssemblyInfo.cs that exist on disk (the files + // DeleteAssemblyInfo would remove). Used to preview deletions in dry-run. + private static IEnumerable ExistingAssemblyInfo(string projDir) + { + foreach (var rel in new[] { Path.Combine("Properties", "AssemblyInfo.cs"), "AssemblyInfo.cs" }) + { + var path = Path.Combine(projDir, rel); + if (File.Exists(path)) yield return Path.GetFullPath(path); + } + } + + // The .sln/.slnx files that currently still reference the .nfproj (i.e. those + // UpdateSolutions would rewrite). Used to preview solution edits in dry-run. + // Resolves entries through the SolutionFile parser so both classic and XML + // solutions are considered and only genuine references count. + private static IEnumerable SolutionsReferencing(string projDir, string nfproj) + { + var target = Path.GetFullPath(nfproj); + foreach (var sln in FindSolutionFiles(projDir)) + { + SolutionFile parsed; + try { parsed = SolutionFile.Load(sln); } + catch { continue; } + if (parsed.ProjectPaths.Any(p => string.Equals(Path.GetFullPath(p), target, StringComparison.OrdinalIgnoreCase))) + yield return sln; + } + } + + // Parses the "packages\.\" folder segment of a HintPath into a + // (id, version) pair. The version is the suffix that begins at the first + // dotted segment starting with a digit; everything before it is the id. + private static (string id, string ver)? InferFromHintPath(XElement reference) + { + var hint = reference.Elements().FirstOrDefault(e => e.Name.LocalName == "HintPath")?.Value; + if (string.IsNullOrEmpty(hint)) return null; + var m = HintPathPackage.Match(hint); + if (!m.Success) return null; + return SplitPackageFolder(m.Groups["folder"].Value); + } + + // "nanoFramework.System.Device.Gpio.1.1.57" -> ("nanoFramework.System.Device.Gpio", "1.1.57") + // "nanoFramework.CoreLibrary.2.0.0-preview.52" -> ("nanoFramework.CoreLibrary", "2.0.0-preview.52") + private static (string id, string ver)? SplitPackageFolder(string folder) + { + var parts = folder.Split('.'); + for (int i = 0; i < parts.Length; i++) + { + if (parts[i].Length > 0 && char.IsDigit(parts[i][0])) + { + if (i == 0) return null; // no id before the version + var id = string.Join('.', parts[..i]); + var ver = string.Join('.', parts[i..]); + return (id, ver); + } + } + return null; // no version segment found + } + + private static Dictionary LoadPackagesConfig(string projDir) + { + var result = new Dictionary(StringComparer.OrdinalIgnoreCase); + var pc = Path.Combine(projDir, "packages.config"); + if (!File.Exists(pc)) return result; + foreach (var p in XElement.Load(pc).Elements().Where(e => e.Name.LocalName == "package")) + { + var id = (string?)p.Attribute("id"); + var ver = (string?)p.Attribute("version"); + if (id is not null && ver is not null) result[id] = ver; + } + return result; + } + + // Walks UP from the project directory looking for the nearest + // Directory.Packages.props (the file MSBuild itself would pick for CPM). Returns + // its full path, or null if none exists in the ancestor chain. Pure: read-only. + private static string? FindDirectoryPackagesProps(string projDir) + { + var dir = new DirectoryInfo(Path.GetFullPath(projDir)); + while (dir is not null) + { + var candidate = Path.Combine(dir.FullName, "Directory.Packages.props"); + if (File.Exists(candidate)) return candidate; + dir = dir.Parent; + } + return null; + } + + // True when a Directory.Packages.props opts into CPM via + // true. + // A malformed/unreadable file is treated as "not enabled" (never throws). + private static bool IsCpmEnabled(string propsPath) + { + try + { + var root = XElement.Load(propsPath); + var flag = root.Descendants() + .FirstOrDefault(e => e.Name.LocalName == "ManagePackageVersionsCentrally"); + return flag is not null + && bool.TryParse(flag.Value.Trim(), out var on) && on; + } + catch { return false; } + } + + // The set of package ids already declared as in a + // Directory.Packages.props. Used to avoid duplicating entries on add/re-run. + private static HashSet LoadPackageVersionIds(string propsPath) + { + var ids = new HashSet(StringComparer.OrdinalIgnoreCase); + try + { + foreach (var pv in XElement.Load(propsPath).Descendants() + .Where(e => e.Name.LocalName == "PackageVersion")) + { + var id = (string?)pv.Attribute("Include"); + if (!string.IsNullOrEmpty(id)) ids.Add(id); + } + } + catch { /* unreadable props → treat as having no entries */ } + return ids; + } + + // Idempotently inserts entries for + // the given (id, version) pairs into the nearest ItemGroup of a + // Directory.Packages.props. Existing entries are neither duplicated nor + // reordered; only genuinely-missing ids are appended. Preserves the file's + // namespace and overall shape. Caller has already filtered to missing ids. + private static void AddPackageVersions(string propsPath, IEnumerable> additions) + { + var toAdd = additions.ToList(); + if (toAdd.Count == 0) return; + + var doc = System.Xml.Linq.XDocument.Load(propsPath, System.Xml.Linq.LoadOptions.PreserveWhitespace); + var root = doc.Root!; + var ns = root.Name.Namespace; + var existing = root.Descendants().Where(e => e.Name.LocalName == "PackageVersion") + .Select(e => (string?)e.Attribute("Include")) + .Where(s => !string.IsNullOrEmpty(s)) + .ToHashSet(StringComparer.OrdinalIgnoreCase); + + // Reuse the ItemGroup that already holds PackageVersion items; otherwise the + // first ItemGroup; otherwise create a fresh one. + var group = root.Elements().FirstOrDefault(e => e.Name.LocalName == "ItemGroup" + && e.Elements().Any(c => c.Name.LocalName == "PackageVersion")) + ?? root.Elements().FirstOrDefault(e => e.Name.LocalName == "ItemGroup"); + if (group is null) + { + group = new XElement(ns + "ItemGroup"); + root.Add(group); + } + + // Match the indentation of an existing PackageVersion so appended entries + // line up; fall back to a sensible default for a freshly-created group. + var indent = ElementIndent(group.Elements() + .FirstOrDefault(c => c.Name.LocalName == "PackageVersion")) ?? " "; + + // The last PackageVersion to append after (so new entries sit with the rest, + // before the ItemGroup's closing tag rather than after its trailing newline). + var anchor = group.Elements().LastOrDefault(c => c.Name.LocalName == "PackageVersion"); + + foreach (var kv in toAdd) + { + if (existing.Contains(kv.Key)) continue; // idempotent guard + var pv = new XElement(ns + "PackageVersion", + new XAttribute("Include", kv.Key), + new XAttribute("Version", kv.Value)); + if (anchor is not null) + { + anchor.AddAfterSelf(pv); + anchor.AddAfterSelf(new System.Xml.Linq.XText("\n" + indent)); + } + else + { + group.AddFirst(pv); + group.AddFirst(new System.Xml.Linq.XText("\n" + indent)); + } + anchor = pv; + existing.Add(kv.Key); + } + + doc.Save(propsPath); + } + + // The leading-whitespace indentation of an element, read from the immediately + // preceding whitespace text node. Null if there is no such node (or no element). + private static string? ElementIndent(XElement? el) + { + if (el?.PreviousNode is System.Xml.Linq.XText t) + { + var s = t.Value; + var nl = s.LastIndexOf('\n'); + return nl >= 0 ? s[(nl + 1)..] : s; + } + return null; + } + + // Removes a hand-written AssemblyInfo.cs from disk. With the SDK's default + // **/*.cs glob and GenerateAssemblyInfo, leaving it would cause duplicate + // assembly-attribute build errors. Idempotent: a missing file is a no-op. + private static void DeleteAssemblyInfo(string projDir) + { + foreach (var rel in new[] { Path.Combine("Properties", "AssemblyInfo.cs"), "AssemblyInfo.cs" }) + { + var path = Path.Combine(projDir, rel); + if (File.Exists(path)) File.Delete(path); + } + } + + // Rewrites .sln/.slnx entries that reference the converted .nfproj so they point + // at the new .csproj (classic .sln also swaps the project-type GUID). Searches + // walking up from the project directory to the repo root (the dir containing + // .git), plus any solution in the project's own directory tree. The actual + // retarget is delegated to SolutionRewriter, which is line/path-scoped and + // idempotent, so re-running is a no-op. + private static void UpdateSolutions(string projDir, string nfproj) + { + var converted = new[] { Path.GetFullPath(nfproj) }; + foreach (var sln in FindSolutionFiles(projDir)) + { + SolutionFile parsed; + try { parsed = SolutionFile.Load(sln); } + catch { continue; } + SolutionRewriter.RewriteFile(parsed, converted); + } + } + + private static List FindSolutionFiles(string projDir) + { + var found = new HashSet(StringComparer.OrdinalIgnoreCase); + + void AddSolutionsIn(string d, SearchOption option) + { + foreach (var pattern in new[] { "*.sln", "*.slnx" }) + foreach (var sln in Directory.EnumerateFiles(d, pattern, option)) + found.Add(Path.GetFullPath(sln)); + } + + // Walk up to the repo root (the directory containing .git), collecting + // solution files at each level. + var dir = new DirectoryInfo(Path.GetFullPath(projDir)); + while (dir is not null) + { + AddSolutionsIn(dir.FullName, SearchOption.TopDirectoryOnly); + if (Directory.Exists(Path.Combine(dir.FullName, ".git")) + || File.Exists(Path.Combine(dir.FullName, ".git"))) + break; // reached the repo root + dir = dir.Parent; + } + + // Also any solution anywhere in the project's own directory tree. + AddSolutionsIn(projDir, SearchOption.AllDirectories); + + return found.ToList(); + } + + private static bool IsDefaultCompile(string inc) + { + if (!inc.EndsWith(".cs", StringComparison.OrdinalIgnoreCase)) return false; + var baseName = inc.TrimStart('.', '\\', '/'); + // A hand-written AssemblyInfo.cs collides with GenerateAssemblyInfo → drop it. + if (baseName.Replace('\\', '/').EndsWith("Properties/AssemblyInfo.cs", StringComparison.OrdinalIgnoreCase)) + return true; + // The SDK globs **/*.cs recursively, so any relative under-project path is a + // default-globbed compile item (not just files in the project root). + return IsDefaultGlobPath(inc); + } + + // A path is "default-globbed" — i.e. the SDK's implicit **/* globs would already + // pick it up — when it is relative, rooted under the project directory, and does + // not escape it via "..". Such items must NOT be re-Included explicitly (that + // duplicates the globbed item); rooted/external paths and links are NOT globbed + // and so are kept verbatim. + private static bool IsDefaultGlobPath(string inc) + { + if (string.IsNullOrWhiteSpace(inc)) return false; + var norm = inc.Replace('\\', '/').Trim(); + if (norm.StartsWith("../") || norm == "..") return false; // escapes project dir + if (norm.StartsWith('/')) return false; // rooted (unix) + if (norm.Length >= 2 && norm[1] == ':') return false; // rooted (drive letter) + if (norm.Contains("/../")) return false; // climbs out partway + if (norm.Contains('*') || norm.Contains('?')) return false; // already a glob + return true; + } + + // Decides how a default-globbable item (None / EmbeddedResource / Content) should + // be carried into the SDK project, per the rules: + // - external/rooted path or a Link present → keep as Include (SDK won't glob it); + // - default-globbed path WITH metadata → rewrite Include→Update so the + // metadata attaches to the SDK's already-globbed item (no duplicate); + // - default-globbed path WITHOUT metadata → drop entirely (SDK globs it plain). + private static void KeepOrUpdateDefaultGlobItem(XElement el, List keepItems) + { + var inc = (string?)el.Attribute("Include") ?? ""; + var hasLink = el.Attribute("Link") is not null + || el.Elements().Any(e => e.Name.LocalName == "Link"); + + if (hasLink || !IsDefaultGlobPath(inc)) + { + keepItems.Add(el); // SDK won't glob this — keep the explicit Include + return; + } + + var hasMetadata = el.Elements().Any() || el.Attributes().Any(a => a.Name.LocalName != "Include"); + if (!hasMetadata) + return; // SDK globs it plainly — drop the redundant item + + // Rewrite Include → Update so the metadata lands on the globbed item without + // re-including (which would trip NETSDK1022 for EmbeddedResource/Content). + el.Attribute("Include")!.Remove(); + el.SetAttributeValue("Update", inc); + keepItems.Add(el); + } + + // Normalizes a project-relative path for comparison against on-disk enumeration: + // forward slashes, leading "./" stripped, no surrounding whitespace. + private static string NormalizeRel(string inc) + { + var s = inc.Replace('\\', '/').Trim(); + while (s.StartsWith("./")) s = s[2..]; + return s; + } + + // True when a hand-written AssemblyInfo.cs on disk declares an attribute the SDK's + // GenerateAssemblyInfo does not emit (AssemblyNativeVersion). Such a file must be + // kept (with GenerateAssemblyInfo disabled) rather than deleted. + private static bool HasNanoAssemblyInfo(string projDir) + { + foreach (var rel in new[] { Path.Combine("Properties", "AssemblyInfo.cs"), "AssemblyInfo.cs" }) + { + var path = Path.Combine(projDir, rel); + if (!File.Exists(path)) continue; + try + { + if (File.ReadAllText(path).Contains("AssemblyNativeVersion", StringComparison.Ordinal)) + return true; + } + catch { /* unreadable → treat as ordinary, deletable AssemblyInfo */ } + } + return false; + } + + // Project-relative paths (forward-slashed) of every .cs file on disk that the SDK + // would compile by default: all **/*.cs under the project directory, excluding + // bin/obj and a hand-written AssemblyInfo.cs. (A deletable AssemblyInfo is removed + // from disk by the converter, and a kept nano-specific one is authoritative — in + // both cases it must not appear in the Compile Remove list.) Used to detect files + // the legacy project deliberately did not compile. + private static IEnumerable OnDiskDefaultCompile(string projDir) + { + var root = Path.GetFullPath(projDir); + IEnumerable files; + try { files = Directory.EnumerateFiles(root, "*.cs", SearchOption.AllDirectories); } + catch { yield break; } + + foreach (var f in files) + { + var rel = Path.GetRelativePath(root, f).Replace('\\', '/'); + var lower = rel.ToLowerInvariant(); + if (lower.StartsWith("bin/") || lower.Contains("/bin/")) continue; + if (lower.StartsWith("obj/") || lower.Contains("/obj/")) continue; + // A deletable AssemblyInfo.cs is removed from disk by the converter, so it + // is neither globbed nor needs a Remove. A KEPT one is authoritative and + // must not be Removed either. + if (rel.EndsWith("Properties/AssemblyInfo.cs", StringComparison.OrdinalIgnoreCase) + || rel.Equals("AssemblyInfo.cs", StringComparison.OrdinalIgnoreCase)) + continue; + yield return rel; + } + } + + private static void FoldNuspec(string projDir, Action setProp) + { + var nuspec = Directory.EnumerateFiles(projDir, "*.nuspec").FirstOrDefault(); + if (nuspec is null) return; + var meta = XElement.Load(nuspec).Descendants().FirstOrDefault(e => e.Name.LocalName == "metadata"); + if (meta is null) return; + foreach (var (xml, msb) in new[] + { + ("id", "PackageId"), ("description", "Description"), ("authors", "Authors"), + ("tags", "PackageTags"), ("projectUrl", "PackageProjectUrl"), + }) + { + var e = meta.Elements().FirstOrDefault(x => x.Name.LocalName == xml); + if (e is not null && !string.IsNullOrEmpty(e.Value)) setProp(msb, e.Value); + } + } + + private static string Emit( + List> props, + Dictionary pkgRefs, + List projRefs, + List keepItems, + List compileRemoves, + List imports, + ConversionOptions o, + bool cpmActive) + { + var sb = new StringBuilder(); + // Versionless SDK reference; the version is pinned via global.json msbuild-sdks. + sb.Append($"\n\n"); + sb.Append(" \n"); + sb.Append($" {o.Tfm}\n"); + foreach (var kv in props) + sb.Append($" <{kv.Key}>{Escape(kv.Value)}\n"); + sb.Append(" \n\n"); + + if (pkgRefs.Count > 0) + { + sb.Append(" \n"); + foreach (var kv in pkgRefs.OrderBy(k => k.Key, StringComparer.OrdinalIgnoreCase)) + // Under CPM the version belongs in the central props, not here — a + // Version attribute would trip NU1008. Otherwise pin it inline. + sb.Append(cpmActive + ? $" \n" + : $" \n"); + sb.Append(" \n\n"); + } + if (projRefs.Count > 0) + { + sb.Append(" \n"); + foreach (var r in projRefs) + sb.Append($" \n"); + sb.Append(" \n\n"); + } + if (keepItems.Count > 0) + { + sb.Append(" \n"); + foreach (var el in keepItems) + AppendItem(sb, el); + sb.Append(" \n\n"); + } + // Files the legacy project deliberately did not compile but that the SDK's + // **/*.cs glob would otherwise pick up: exclude them so the converted project + // builds the same source set as the original. + if (compileRemoves.Count > 0) + { + sb.Append(" \n"); + foreach (var rel in compileRemoves) + sb.Append($" \n"); + sb.Append(" \n\n"); + } + // Shared Project imports carry source into the project; emit them with the + // Shared label MSBuild/VS expects for a .projitems import. + foreach (var import in imports) + sb.Append($" \n"); + if (imports.Count > 0) sb.Append('\n'); + sb.Append("\n"); + return sb.ToString(); + } + + // Renders one kept item element, preserving its attributes AND its child-element + // metadata (Generator, LastGenOutput, CopyToOutputDirectory, Link, …). Earlier the + // emitter wrote attributes only, silently dropping the child metadata that, for an + // Update item, is the whole point of carrying it through. + private static void AppendItem(StringBuilder sb, XElement el) + { + var attrs = string.Join(" ", el.Attributes().Select(a => $"{a.Name.LocalName}=\"{Escape(a.Value)}\"")); + var children = el.Elements().ToList(); + var name = el.Name.LocalName; + if (children.Count == 0) + { + sb.Append($" <{name} {attrs} />\n"); + return; + } + sb.Append($" <{name} {attrs}>\n"); + foreach (var c in children) + sb.Append($" <{c.Name.LocalName}>{Escape(c.Value)}\n"); + sb.Append($" \n"); + } + + private static string Escape(string s) => s + .Replace("&", "&").Replace("<", "<").Replace(">", ">").Replace("\"", """); +} diff --git a/tools/migrate/src/NanoMigrate.Core/Reporting/HtmlReportWriter.cs b/tools/migrate/src/NanoMigrate.Core/Reporting/HtmlReportWriter.cs new file mode 100644 index 0000000..6d405d4 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Reporting/HtmlReportWriter.cs @@ -0,0 +1,181 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Net; +using System.Text; +using nanoFramework.Migrate.Core.Projects; + +namespace nanoFramework.Migrate.Core.Reporting; + +/// +/// Renders a as a self-contained HTML page: inline +/// <style>, no external assets. The results table is colour-coded by +/// status (green converted / grey skipped / amber review / red error). Pure and +/// console-free; ALL interpolated text (project names, notes, package ids) is +/// HTML-escaped to guard against injection. +/// +public static class HtmlReportWriter +{ + /// Renders the report to a self-contained HTML string. + public static string Render(MigrationReport report) + { + var sb = new StringBuilder(); + var title = report.DryRun + ? "nanoFramework migration report (dry run)" + : "nanoFramework migration report"; + + sb.Append("\n"); + sb.Append("\n\n"); + sb.Append("\n"); + sb.Append("\n"); + sb.Append("").Append(Esc(title)).Append("\n"); + sb.Append("\n"); + sb.Append("\n\n"); + + sb.Append("

").Append(Esc(title)).Append("

\n"); + sb.Append("

Root: ").Append(Esc(report.RootPath)).Append("
\n"); + sb.Append("Generated (UTC): ") + .Append(Esc(report.GeneratedUtc.ToString("yyyy-MM-dd HH:mm:ss'Z'"))) + .Append("

\n"); + + var verb = report.DryRun ? "would convert" : "converted"; + sb.Append("
    \n"); + sb.Append("
  • ").Append(Esc(verb)).Append(' ').Append(report.Converted).Append("
  • \n"); + sb.Append("
  • skipped ").Append(report.Skipped).Append("
  • \n"); + sb.Append("
  • flagged ").Append(report.Flagged).Append("
  • \n"); + sb.Append("
  • errors ").Append(report.Errors).Append("
  • \n"); + sb.Append("
  • total ").Append(report.Total).Append("
  • \n"); + sb.Append("
\n"); + + // Results table. + sb.Append("\n\n"); + sb.Append(""); + sb.Append("\n\n\n"); + foreach (var p in report.Projects) + { + var (label, cls) = StatusLabel(p.Status); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("\n"); + } + sb.Append("\n
ProjectResultPackagesNotes
").Append(Esc(p.RelativePath)).Append("").Append(Esc(label)).Append("").Append(Packages(p)).Append("").Append(Esc(Notes(p))).Append("
\n"); + + if (report.AffectedSolutions.Count > 0) + { + sb.Append("

Solutions

\n
    \n"); + foreach (var s in report.AffectedSolutions) + sb.Append("
  • ").Append(Esc(s)).Append("
  • \n"); + sb.Append("
\n"); + } + + var flagged = report.Projects.Where(p => p.Review.Count > 0).ToList(); + if (flagged.Count > 0) + { + sb.Append("

Manual review

\n"); + foreach (var p in flagged) + { + sb.Append("

").Append(Esc(p.RelativePath)).Append("

\n
    \n"); + foreach (var item in p.Review) + sb.Append("
  • ").Append(Esc(item)).Append("
  • \n"); + sb.Append("
\n"); + } + } + + if (report.Verify.Count > 0) + { + sb.Append("

Verification

\n"); + sb.Append("\n\n"); + sb.Append(""); + sb.Append("\n\n\n"); + foreach (var v in report.Verify) + { + var (label, cls) = v.Skipped ? ("Skipped", "skipped") + : v.Succeeded ? ("Pass", "converted") + : ("Fail", "error"); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append(""); + sb.Append("\n"); + } + sb.Append("\n
TargetResultDetails
").Append(Esc(v.Target)).Append("").Append(Esc(label)).Append(""); + sb.Append(string.IsNullOrEmpty(v.Details) ? "—" : $"
{Esc(v.Details!)}
"); + sb.Append("
\n"); + } + + sb.Append("\n\n"); + return sb.ToString(); + } + + /// Renders the report and writes it to as UTF-8 (no BOM). + public static void Write(MigrationReport report, string path) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(path)); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(path, Render(report), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + } + + private static string Packages(ReportEntry p) + { + if (p.Packages.Count == 0) return "—"; + return string.Join("
", p.Packages.Select(kv => + $"{Esc(kv.Key)} {Esc(kv.Value)}")); + } + + private static (string label, string cls) StatusLabel(ConvertStatus s) => s switch + { + ConvertStatus.Converted => ("Converted", "converted"), + ConvertStatus.Skipped => ("Skipped", "skipped"), + ConvertStatus.Review => ("Review", "review"), + ConvertStatus.Error => ("Error", "error"), + _ => ("?", "skipped"), + }; + + private static string Notes(ReportEntry p) => p.Status switch + { + ConvertStatus.Error => p.Error ?? "error", + ConvertStatus.Skipped => "already SDK-style", + ConvertStatus.Review => $"{p.Review.Count} item(s) need review", + _ => "clean", + }; + + // HTML-escapes interpolated text. WebUtility.HtmlEncode handles &, <, >, ". + private static string Esc(string s) => WebUtility.HtmlEncode(s); + + // A small, self-contained stylesheet. Status colours: green (converted), + // grey (skipped), amber (review), red (error). + private const string Css = """ + :root { color-scheme: light dark; } + body { font-family: -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; + margin: 2rem; line-height: 1.45; color: #1b1b1b; background: #fff; } + h1 { font-size: 1.6rem; margin-bottom: .25rem; } + h2 { margin-top: 2rem; border-bottom: 1px solid #ddd; padding-bottom: .25rem; } + .meta { color: #555; } + code { font-family: Consolas, Menlo, monospace; font-size: .9em; } + .muted { color: #888; } + ul.totals { list-style: none; padding: 0; display: flex; flex-wrap: wrap; gap: .5rem; } + ul.totals li { padding: .35rem .7rem; border-radius: .4rem; font-weight: 600; } + .t-converted { background: #e6f4ea; color: #137333; } + .t-skipped { background: #f1f3f4; color: #5f6368; } + .t-review { background: #fef7e0; color: #b06000; } + .t-error { background: #fce8e6; color: #c5221f; } + .t-total { background: #e8f0fe; color: #1a73e8; } + table.results { border-collapse: collapse; width: 100%; margin-top: 1rem; } + table.results th, table.results td { border: 1px solid #ddd; padding: .5rem .65rem; text-align: left; vertical-align: top; } + table.results th { background: #f5f5f5; } + .badge { display: inline-block; padding: .15rem .55rem; border-radius: .35rem; font-size: .85em; font-weight: 600; } + tr.converted .badge, .badge.converted { background: #e6f4ea; color: #137333; } + tr.skipped .badge, .badge.skipped { background: #f1f3f4; color: #5f6368; } + tr.review .badge, .badge.review { background: #fef7e0; color: #b06000; } + tr.error .badge, .badge.error { background: #fce8e6; color: #c5221f; } + tr.converted td:first-child { border-left: 4px solid #34a853; } + tr.skipped td:first-child { border-left: 4px solid #9aa0a6; } + tr.review td:first-child { border-left: 4px solid #f9ab00; } + tr.error td:first-child { border-left: 4px solid #ea4335; } + pre { margin: 0; white-space: pre-wrap; font-size: .85em; } + + """; +} diff --git a/tools/migrate/src/NanoMigrate.Core/Reporting/MarkdownReportWriter.cs b/tools/migrate/src/NanoMigrate.Core/Reporting/MarkdownReportWriter.cs new file mode 100644 index 0000000..55a4373 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Reporting/MarkdownReportWriter.cs @@ -0,0 +1,132 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using nanoFramework.Migrate.Core.Projects; + +namespace nanoFramework.Migrate.Core.Reporting; + +/// +/// Renders a as Markdown. Pure: it returns a string +/// (or writes that string to a path) and never touches the console. The document is +/// a title, a summary line, a results table, and — when present — a "Manual review" +/// section and a "Verification" section. +/// +public static class MarkdownReportWriter +{ + /// Renders the report to a Markdown string. + public static string Render(MigrationReport report) + { + var sb = new StringBuilder(); + + sb.Append("# nanoFramework migration report"); + if (report.DryRun) sb.Append(" (dry run)"); + sb.Append('\n').Append('\n'); + + sb.Append("- **Root:** `").Append(report.RootPath).Append("`\n"); + sb.Append("- **Generated (UTC):** ") + .Append(report.GeneratedUtc.ToString("yyyy-MM-dd HH:mm:ss'Z'")) + .Append('\n').Append('\n'); + + var verb = report.DryRun ? "would convert" : "converted"; + sb.Append("**Summary:** ") + .Append(verb).Append(' ').Append(report.Converted) + .Append(" · skipped ").Append(report.Skipped) + .Append(" · flagged ").Append(report.Flagged) + .Append(" · errors ").Append(report.Errors) + .Append(" · total ").Append(report.Total) + .Append('\n').Append('\n'); + + // Results table. + sb.Append("| Project | Result | Packages | Notes |\n"); + sb.Append("| --- | --- | --- | --- |\n"); + foreach (var p in report.Projects) + { + var packages = p.Packages.Count == 0 + ? "—" + : string.Join("
", p.Packages.Select(kv => $"{Cell(kv.Key)} {Cell(kv.Value)}")); + sb.Append("| ") + .Append(Cell(p.RelativePath)).Append(" | ") + .Append(StatusLabel(p.Status)).Append(" | ") + .Append(packages).Append(" | ") + .Append(Notes(p)).Append(" |\n"); + } + sb.Append('\n'); + + if (report.AffectedSolutions.Count > 0) + { + sb.Append("## Solutions\n\n"); + foreach (var s in report.AffectedSolutions) + sb.Append("- `").Append(s).Append("`\n"); + sb.Append('\n'); + } + + var flagged = report.Projects.Where(p => p.Review.Count > 0).ToList(); + if (flagged.Count > 0) + { + sb.Append("## Manual review\n\n"); + foreach (var p in flagged) + { + sb.Append("### ").Append(p.RelativePath).Append('\n').Append('\n'); + foreach (var item in p.Review) + sb.Append("- ").Append(item).Append('\n'); + sb.Append('\n'); + } + } + + if (report.Verify.Count > 0) + { + sb.Append("## Verification\n\n"); + sb.Append("| Target | Result | Details |\n"); + sb.Append("| --- | --- | --- |\n"); + foreach (var v in report.Verify) + { + var label = v.Skipped ? "Skipped" : v.Succeeded ? "Pass" : "Fail"; + var details = string.IsNullOrEmpty(v.Details) + ? "—" + : Cell(v.Details); + sb.Append("| ") + .Append(Cell(v.Target)).Append(" | ") + .Append(label).Append(" | ") + .Append(details).Append(" |\n"); + } + sb.Append('\n'); + } + + return sb.ToString(); + } + + /// Renders the report and writes it to as UTF-8 (no BOM). + public static void Write(MigrationReport report, string path) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(path)); + if (!string.IsNullOrEmpty(dir)) Directory.CreateDirectory(dir); + File.WriteAllText(path, Render(report), new UTF8Encoding(encoderShouldEmitUTF8Identifier: false)); + } + + private static string StatusLabel(ConvertStatus s) => s switch + { + ConvertStatus.Converted => "Converted", + ConvertStatus.Skipped => "Skipped", + ConvertStatus.Review => "Review", + ConvertStatus.Error => "Error", + _ => "?", + }; + + private static string Notes(ReportEntry p) => p.Status switch + { + ConvertStatus.Error => Cell(p.Error ?? "error"), + ConvertStatus.Skipped => "already SDK-style", + ConvertStatus.Review => $"{p.Review.Count} item(s) need review", + _ => "clean", + }; + + // Escapes the few characters that would break a Markdown table cell: pipes + // (column separators) and newlines (row separators ->
). + private static string Cell(string s) => + s.Replace("\\", "\\\\") + .Replace("|", "\\|") + .Replace("\r\n", "
") + .Replace("\n", "
") + .Replace("\r", "
"); +} diff --git a/tools/migrate/src/NanoMigrate.Core/Reporting/MigrationReport.cs b/tools/migrate/src/NanoMigrate.Core/Reporting/MigrationReport.cs new file mode 100644 index 0000000..f0375ca --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Reporting/MigrationReport.cs @@ -0,0 +1,96 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using nanoFramework.Migrate.Core.Projects; +using nanoFramework.Migrate.Core.Verification; + +namespace nanoFramework.Migrate.Core.Reporting; + +/// +/// The result of a single project within a , expressed +/// as plain DATA so the report writers stay pure and console-free. Mirrors the data +/// the on-screen summary table renders, but decoupled from any presentation layer. +/// +public sealed class ReportEntry +{ + /// The project path, relative to the report's root, with forward slashes. + public required string RelativePath { get; init; } + + /// The conversion status of the project. + public required ConvertStatus Status { get; init; } + + /// The resolved PackageReference ids and versions the project carries. + public IReadOnlyList> Packages { get; init; } = + Array.Empty>(); + + /// The items flagged for manual review (empty when none). + public IReadOnlyList Review { get; init; } = Array.Empty(); + + /// An optional error message (set only when is Error). + public string? Error { get; init; } +} + +/// +/// One verification build result inside a . A flat, +/// presentation-free projection of keyed by a relative +/// target path so the writers don't depend on the verification slice's shape. +/// +public sealed class ReportVerifyEntry +{ + /// The built target, relative to the report's root where possible. + public required string Target { get; init; } + + /// True when the build succeeded. + public required bool Succeeded { get; init; } + + /// True when the build was skipped (e.g. no dotnet on PATH). + public required bool Skipped { get; init; } + + /// The build process exit code. + public int ExitCode { get; init; } + + /// A short note: the skip reason or the error tail on failure. + public string? Details { get; init; } +} + +/// +/// A migration run captured as DATA, ready to be rendered by the +/// or . The engine +/// never calls DateTime.Now: the timestamp is supplied by the caller so the +/// writers stay pure and deterministically testable. +/// +public sealed class MigrationReport +{ + /// The root directory the migration ran against (paths are relative to it). + public required string RootPath { get; init; } + + /// A UTC timestamp for the run, supplied by the caller. + public required DateTime GeneratedUtc { get; init; } + + /// True when this report describes a dry-run (what WOULD change). + public bool DryRun { get; init; } + + /// The per-project results, in run order. + public IReadOnlyList Projects { get; init; } = Array.Empty(); + + /// The solutions retargeted (or, in dry-run, that would be retargeted). + public IReadOnlyList AffectedSolutions { get; init; } = Array.Empty(); + + /// The verification build results, when a verify pass ran (otherwise empty). + public IReadOnlyList Verify { get; init; } = Array.Empty(); + + /// Projects that converted cleanly. + public int Converted => Projects.Count(p => p.Status == ConvertStatus.Converted); + + /// Projects already SDK-style (skipped). + public int Skipped => Projects.Count(p => p.Status == ConvertStatus.Skipped); + + /// Projects converted but flagged for manual review. + public int Flagged => Projects.Count(p => p.Status == ConvertStatus.Review); + + /// Projects that errored. + public int Errors => Projects.Count(p => p.Status == ConvertStatus.Error); + + /// The total number of projects in the report. + public int Total => Projects.Count; +} diff --git a/tools/migrate/src/NanoMigrate.Core/Solutions/MigrationPlan.cs b/tools/migrate/src/NanoMigrate.Core/Solutions/MigrationPlan.cs new file mode 100644 index 0000000..623a8f4 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Solutions/MigrationPlan.cs @@ -0,0 +1,203 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using nanoFramework.Migrate.Core.Common; + +namespace nanoFramework.Migrate.Core.Solutions; + +/// +/// How the migration target was specified, which decides whether the CLI must +/// prompt the user to choose among candidate solutions. +/// +public enum PlanKind +{ + /// Input was a single .nfproj file (no solution awareness). + SingleProject, + + /// + /// A directory with no solutions found: fall back to converting every + /// .nfproj loosely (the historical directory behavior). + /// + LooseDirectory, + + /// + /// Input was an explicit solution (positional .sln/.slnx or + /// --solution): convert only that solution's projects, update only it. + /// No prompt. + /// + ExplicitSolution, + + /// + /// A directory where solutions were discovered: the user must choose which + /// solution(s) to migrate (multi-select), unless non-interactive/--yes. + /// + DirectoryWithSolutions, + + /// + /// A glob narrowed the projects; the affected solutions (those referencing a + /// matched project) are presented for confirmation / multi-select. + /// + GlobScoped, +} + +/// +/// A candidate solution surfaced by the planner, paired with the matched +/// .nfproj projects it references (the projects that would be converted and +/// for which this solution would be retargeted). +/// +public sealed class SolutionCandidate +{ + public required SolutionFile Solution { get; init; } + + /// The matched .nfproj (absolute paths) this solution references. + public required IReadOnlyList NanoProjects { get; init; } +} + +/// +/// The pure result of planning a migration. Carries enough data for the CLI to +/// render a preview and (when ) prompt the user — +/// the planner itself does no console I/O and no prompting. +/// +public sealed class MigrationPlan +{ + /// How the target was specified. + public required PlanKind Kind { get; init; } + + /// + /// Candidate solutions the user may choose among (empty for + /// / ). + /// + public IReadOnlyList Candidates { get; init; } = Array.Empty(); + + /// + /// For project/loose-directory plans: the .nfproj to convert when no + /// solution is involved. Empty for solution-scoped plans (those projects come + /// from the chosen candidates). + /// + public IReadOnlyList LooseProjects { get; init; } = Array.Empty(); + + /// + /// True when the CLI must let the user pick among + /// (more than one candidate, or a glob scoping that warrants confirmation). For + /// an explicit single solution this is false (no choice to make). + /// + public bool RequiresSelection => Kind is PlanKind.DirectoryWithSolutions or PlanKind.GlobScoped; + + /// + /// Flattens a chosen set of candidates into the distinct .nfproj projects + /// to convert (sorted, absolute). For non-solution plans the caller uses + /// instead. + /// + public static List ProjectsOf(IEnumerable chosen) => + chosen.SelectMany(c => c.NanoProjects) + .Distinct(StringComparer.OrdinalIgnoreCase) + .OrderBy(p => p, StringComparer.OrdinalIgnoreCase) + .ToList(); +} + +/// +/// Builds a from the command inputs and the file system. +/// All branching about solutions vs loose conversion lives here, so the CLI only +/// renders the plan and (when required) prompts. No console, no prompting. +/// +public static class MigrationPlanner +{ + /// + /// Plans a migration. + /// + /// — the positional argument: a .nfproj, a + /// solution (.sln/.slnx), or a directory. + /// — the --solution override; + /// when set, only that solution is touched. + /// — narrows the .nfproj within a directory + /// and triggers solution discovery over the matched projects. + /// + /// + public static MigrationPlan Plan(string path, string? explicitSolution, string? glob) + { + // 1. An explicit --solution always wins: convert only its .nfproj, touch + // only it. (Honoured even if the positional path is a directory.) + if (!string.IsNullOrEmpty(explicitSolution)) + return ExplicitSolutionPlan(explicitSolution); + + // 2. Positional path is itself a solution file. + if (File.Exists(path) && SolutionFile.IsSolutionPath(path)) + return ExplicitSolutionPlan(path); + + // 3. Positional path is a single .nfproj file: no solution awareness. + if (File.Exists(path) && path.EndsWith(".nfproj", StringComparison.OrdinalIgnoreCase)) + return new MigrationPlan + { + Kind = PlanKind.SingleProject, + LooseProjects = new[] { Path.GetFullPath(path) }, + }; + + // 4. Directory. + if (Directory.Exists(path)) + return DirectoryPlan(path, glob); + + // Non-existent path: nothing to do (empty loose plan). + return new MigrationPlan { Kind = PlanKind.LooseDirectory }; + } + + private static MigrationPlan ExplicitSolutionPlan(string solutionPath) + { + var sln = SolutionFile.Load(solutionPath); + var nano = sln.NanoProjects(); + return new MigrationPlan + { + Kind = PlanKind.ExplicitSolution, + Candidates = new[] + { + new SolutionCandidate { Solution = sln, NanoProjects = nano }, + }, + }; + } + + private static MigrationPlan DirectoryPlan(string dir, string? glob) + { + var solutions = SolutionScanner.Load(dir); + + // GLOB MODE: scope to the matched projects, then discover which solutions + // reference any of them. Even with no solutions found we honour the glob via + // a loose conversion of the matched projects. + if (glob is not null) + { + var matched = ProjectScanner.NfprojUnder(dir, glob) + .OrderBy(p => p, StringComparer.OrdinalIgnoreCase) + .ToList(); + var affected = SolutionDiscovery.Referencing(solutions, matched); + if (affected.Count == 0) + return new MigrationPlan { Kind = PlanKind.LooseDirectory, LooseProjects = matched }; + + var matchedSet = new HashSet(matched, StringComparer.OrdinalIgnoreCase); + return new MigrationPlan + { + Kind = PlanKind.GlobScoped, + Candidates = affected.Select(s => new SolutionCandidate + { + Solution = s, + NanoProjects = s.NanoProjects() + .Where(p => matchedSet.Contains(Path.GetFullPath(p))) + .ToList(), + }).ToList(), + }; + } + + // NO GLOB: 0 solutions => loose directory; >=1 => the user chooses. + if (solutions.Count == 0) + { + var all = ProjectScanner.ResolveProjects(dir, glob: null); + return new MigrationPlan { Kind = PlanKind.LooseDirectory, LooseProjects = all }; + } + + return new MigrationPlan + { + Kind = PlanKind.DirectoryWithSolutions, + Candidates = solutions + .Where(s => s.NanoProjects().Count > 0) // only solutions with .nfproj to convert + .Select(s => new SolutionCandidate { Solution = s, NanoProjects = s.NanoProjects() }) + .ToList(), + }; + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionDiscovery.cs b/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionDiscovery.cs new file mode 100644 index 0000000..74af3a7 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionDiscovery.cs @@ -0,0 +1,37 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Solutions; + +/// +/// Given a set of target .nfproj paths, finds which discovered solutions +/// reference any of them — by parsing each solution's project list and intersecting +/// it with the targets. Pure analysis over already-loaded solution models. +/// +public static class SolutionDiscovery +{ + /// + /// Returns the solutions (from ) that reference at + /// least one of . Comparison is by absolute + /// path, case-insensitive. Unrelated solutions are excluded. + /// + public static List Referencing( + IEnumerable solutions, + IEnumerable targetNfprojPaths) + { + var targets = new HashSet( + targetNfprojPaths.Select(Path.GetFullPath), StringComparer.OrdinalIgnoreCase); + if (targets.Count == 0) return new List(); + + return solutions + .Where(s => s.ProjectPaths.Any(p => targets.Contains(Path.GetFullPath(p)))) + .ToList(); + } + + /// + /// Loads every solution under and returns those that + /// reference at least one of . + /// + public static List FindReferencing(string dir, IEnumerable targetNfprojPaths) => + Referencing(SolutionScanner.Load(dir), targetNfprojPaths); +} diff --git a/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionFile.cs b/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionFile.cs new file mode 100644 index 0000000..d93cb0b --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionFile.cs @@ -0,0 +1,146 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using System.Xml.Linq; +using Microsoft.VisualStudio.SolutionPersistence.Model; +using Microsoft.VisualStudio.SolutionPersistence.Serializer; + +namespace nanoFramework.Migrate.Core.Solutions; + +/// The on-disk format of a Visual Studio solution. +public enum SolutionFormat +{ + /// Classic line-based .sln (each project has a type GUID). + Classic, + + /// XML .slnx (path-based). + Xml, +} + +/// +/// Parsed model of a Visual Studio solution — both the classic .sln line +/// format and the newer XML .slnx format. Backed by the .NET Foundation +/// Microsoft.VisualStudio.SolutionPersistence serializers: the library does +/// all of the parsing and (on retarget) re-serialization; this type only exposes the +/// referenced project paths (absolute) and the format, and drives the nfproj→csproj +/// retarget through the model. +/// +public sealed class SolutionFile +{ + // The legacy nanoFramework project-type GUID. A flavored .nfproj carries this in a + // classic .sln, and VS writes it as the Type attribute in a .slnx. The serializer + // does not know the .nfproj extension, so a .slnx that references a bare .nfproj + // (no Type attribute) cannot be parsed as-is; we inject this Type for those + // entries before handing the text to the library (see LoadSlnxModel). + internal const string NfprojTypeGuid = "{11A8DD76-328B-46DF-9F39-F559912D0360}"; + + /// Absolute path to the solution file. + public string Path { get; } + + /// Whether this is a classic .sln or an XML .slnx. + public SolutionFormat Format { get; } + + /// + /// Every project the solution references, as an absolute path. Solution folders + /// are excluded (the library models them separately from projects). + /// + public IReadOnlyList ProjectPaths { get; } + + private SolutionFile(string path, SolutionFormat format, IReadOnlyList projectPaths) + { + Path = path; + Format = format; + ProjectPaths = projectPaths; + } + + /// True if the file extension denotes a solution (.sln or .slnx). + public static bool IsSolutionPath(string path) => + path.EndsWith(".sln", StringComparison.OrdinalIgnoreCase) + || path.EndsWith(".slnx", StringComparison.OrdinalIgnoreCase); + + /// Loads and parses the solution at . + public static SolutionFile Load(string solutionPath) + { + var full = System.IO.Path.GetFullPath(solutionPath); + var dir = System.IO.Path.GetDirectoryName(full)!; + var isXml = full.EndsWith(".slnx", StringComparison.OrdinalIgnoreCase); + + var model = LoadModel(full, isXml); + var paths = model.SolutionProjects + .Select(p => System.IO.Path.GetFullPath(System.IO.Path.Combine(dir, p.FilePath))) + .ToList(); + + return new SolutionFile(full, isXml ? SolutionFormat.Xml : SolutionFormat.Classic, paths); + } + + /// + /// The .nfproj projects referenced by the solution (absolute paths). + /// + public IReadOnlyList NanoProjects() => + ProjectPaths.Where(p => p.EndsWith(".nfproj", StringComparison.OrdinalIgnoreCase)).ToList(); + + // ---- Library bridge ------------------------------------------------------ + + /// + /// Reads a solution into the library's , picking the + /// serializer by extension. For .slnx the bare-.nfproj compatibility + /// shim is applied so a solution that references a flavored project without an + /// explicit Type attribute still parses (the serializer does not know the + /// .nfproj extension on its own). + /// + internal static SolutionModel LoadModel(string fullPath, bool isXml) => + isXml ? LoadSlnxModel(File.ReadAllText(fullPath)) : OpenFromText(isXml: false, File.ReadAllText(fullPath)); + + // Classic .sln: the serializer carries the project-type GUID per entry, so no shim + // is needed. .slnx: try a straight parse; if the serializer rejects an unknown + // .nfproj project type, inject the nanoFramework Type attribute on bare .nfproj + // elements and retry. This is the only place we touch the raw text, and + // only to make an otherwise-unparseable solution ingestible by the library. + internal static SolutionModel LoadSlnxModel(string text) + { + try + { + return OpenFromText(isXml: true, text); + } + catch (SolutionException) + { + var patched = InjectNfprojTypeAttribute(text); + if (patched is null) throw; + return OpenFromText(isXml: true, patched); + } + } + + // Opens solution text into the model via the matching typed serializer (chosen by + // format). The library's stream-based open avoids any temp file. + internal static SolutionModel OpenFromText(bool isXml, string text) + { + using var ms = new MemoryStream(new UTF8Encoding(false).GetBytes(text)); + return isXml + ? SolutionSerializers.SlnXml.OpenAsync(ms, CancellationToken.None).GetAwaiter().GetResult() + : SolutionSerializers.SlnFileV12.OpenAsync(ms, CancellationToken.None).GetAwaiter().GetResult(); + } + + // Adds Type="{nfproj GUID}" to every element that lacks + // a Type attribute, so the SolutionPersistence .slnx serializer can resolve the + // otherwise-unknown extension. Returns null when nothing needed patching (so the + // original error is preserved). Preserves all other formatting via XDocument. + internal static string? InjectNfprojTypeAttribute(string slnxText) + { + XDocument doc; + try { doc = XDocument.Parse(slnxText, LoadOptions.PreserveWhitespace); } + catch { return null; } + + var changed = false; + foreach (var proj in doc.Descendants().Where(e => e.Name.LocalName == "Project")) + { + var path = (string?)proj.Attribute("Path"); + if (path is null || !path.EndsWith(".nfproj", StringComparison.OrdinalIgnoreCase)) continue; + var hasType = proj.Attributes().Any(a => a.Name.LocalName == "Type"); + if (hasType) continue; + proj.SetAttributeValue("Type", NfprojTypeGuid); + changed = true; + } + return changed ? doc.ToString(SaveOptions.DisableFormatting) : null; + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionRewriter.cs b/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionRewriter.cs new file mode 100644 index 0000000..c85db84 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionRewriter.cs @@ -0,0 +1,123 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; +using Microsoft.VisualStudio.SolutionPersistence.Model; +using Microsoft.VisualStudio.SolutionPersistence.Serializer; + +namespace nanoFramework.Migrate.Core.Solutions; + +/// +/// Retargets a solution's converted projects from .nfproj to .csproj. +/// Handles both the classic line-based .sln and the XML .slnx by +/// mutating the .NET Foundation and re-serialising with +/// the matching serializer — the library writes the canonical format for each (a +/// .sln stays a .sln, a .slnx stays a .slnx). For a +/// classic .sln the retargeted entry's project type is set to the SDK-style C# +/// GUID; for a path-based .slnx the now-redundant nanoFramework type is cleared. +/// +/// Idempotent / reentrant: the retarget is decided at the model level — only projects +/// still pointing at a .nfproj that is in the converted set are touched. When +/// nothing matched, the original file text is returned/left untouched (no write, no +/// reformat). +/// +public static class SolutionRewriter +{ + // Project-type GUIDs: legacy nanoFramework flavor -> SDK-style C#. Retained for + // back-compat (tests/consumers reference these); the actual GUID swap on a classic + // .sln is performed by the serializer when the project type is cleared and the + // path becomes a .csproj. + public const string NfprojTypeGuid = "{11A8DD76-328B-46DF-9F39-F559912D0360}"; + public const string CsprojTypeGuid = "{9A19103F-16F7-4668-BE54-9A1E7A4F7556}"; + + /// + /// Returns the rewritten text of , retargeting any + /// entry whose referenced .nfproj (resolved against ) + /// is in (absolute paths). The returned + /// string equals the input when nothing matched (no-op). + /// + public static string Rewrite( + string solutionText, + string solutionDir, + SolutionFormat format, + IEnumerable convertedNfprojPaths) + { + var converted = new HashSet( + convertedNfprojPaths.Select(Path.GetFullPath), StringComparer.OrdinalIgnoreCase); + if (converted.Count == 0) return solutionText; + + var isXml = format == SolutionFormat.Xml; + + SolutionModel model; + try + { + // .slnx parsing applies the bare-.nfproj Type compatibility shim; .sln + // carries its type GUIDs per entry and needs none. + model = isXml ? SolutionFile.LoadSlnxModel(solutionText) : SolutionFile.OpenFromText(isXml: false, solutionText); + } + catch + { + // If the library cannot parse it even after the shim, leave it untouched. + return solutionText; + } + + var changed = RetargetModel(model, solutionDir, converted, isXml); + if (!changed) return solutionText; + + return SaveToText(isXml, model); + } + + /// + /// Rewrites the solution file in place when at least one entry was retargeted. + /// Returns true if the file changed. A no-op leaves the file untouched (no write). + /// + public static bool RewriteFile(SolutionFile solution, IEnumerable convertedNfprojPaths) + { + string text; + try { text = File.ReadAllText(solution.Path); } + catch { return false; } + + var dir = Path.GetDirectoryName(solution.Path)!; + var updated = Rewrite(text, dir, solution.Format, convertedNfprojPaths); + if (string.Equals(updated, text, StringComparison.Ordinal)) return false; + + File.WriteAllText(solution.Path, updated, new UTF8Encoding(false)); + return true; + } + + // Mutates the model: every project whose resolved .nfproj path is in the converted + // set is pointed at the sibling .csproj. For a classic .sln the project type is + // set to the SDK-style C# type GUID (so the serializer writes it on that entry, + // line-scoped — other still-unconverted nanoFramework projects keep their legacy + // GUID). For a .slnx (path-based) the now-redundant nanoFramework Type attribute is + // cleared so the converted entry carries no Type, exactly as before. Returns true + // if any project changed. + private static bool RetargetModel(SolutionModel model, string solutionDir, HashSet converted, bool isXml) + { + var changed = false; + foreach (var project in model.SolutionProjects) + { + var rel = project.FilePath; + if (!rel.EndsWith(".nfproj", StringComparison.OrdinalIgnoreCase)) continue; + + var abs = Path.GetFullPath(Path.Combine(solutionDir, rel)); + if (!converted.Contains(abs)) continue; + + project.FilePath = Path.ChangeExtension(rel, ".csproj"); + try { project.Type = isXml ? string.Empty : CsprojTypeGuid; } + catch (SolutionException) { /* leave the type as-is */ } + changed = true; + } + return changed; + } + + private static string SaveToText(bool isXml, SolutionModel model) + { + using var ms = new MemoryStream(); + if (isXml) + SolutionSerializers.SlnXml.SaveAsync(ms, model, CancellationToken.None).GetAwaiter().GetResult(); + else + SolutionSerializers.SlnFileV12.SaveAsync(ms, model, CancellationToken.None).GetAwaiter().GetResult(); + return new UTF8Encoding(false).GetString(ms.ToArray()); + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionScanner.cs b/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionScanner.cs new file mode 100644 index 0000000..0d8e3bf --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Solutions/SolutionScanner.cs @@ -0,0 +1,46 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Solutions; + +/// +/// Discovers Visual Studio solution files (.sln and .slnx) beneath a +/// directory. Pure file-system discovery — no console, no side effects. +/// +public static class SolutionScanner +{ + /// + /// Finds every .sln and .slnx under + /// (recursively), returning absolute paths, sorted. A non-existent directory + /// yields an empty list. + /// + public static List Find(string dir) + { + if (!Directory.Exists(dir)) return new List(); + + // IgnoreInaccessible so a single permission-denied subtree doesn't abort the + // whole scan (the SearchOption overload throws instead of skipping). + var opts = new EnumerationOptions { RecurseSubdirectories = true, IgnoreInaccessible = true }; + var found = new HashSet(StringComparer.OrdinalIgnoreCase); + foreach (var pattern in new[] { "*.sln", "*.slnx" }) + foreach (var sln in Directory.EnumerateFiles(dir, pattern, opts)) + found.Add(Path.GetFullPath(sln)); + + return found.OrderBy(p => p, StringComparer.OrdinalIgnoreCase).ToList(); + } + + /// + /// Loads every solution under . Files that fail to parse + /// (malformed XML, unreadable) are skipped rather than aborting discovery. + /// + public static List Load(string dir) + { + var result = new List(); + foreach (var path in Find(dir)) + { + try { result.Add(SolutionFile.Load(path)); } + catch { /* skip a solution we cannot parse */ } + } + return result; + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Verification/SolutionBuilder.cs b/tools/migrate/src/NanoMigrate.Core/Verification/SolutionBuilder.cs new file mode 100644 index 0000000..8a0da14 --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Verification/SolutionBuilder.cs @@ -0,0 +1,176 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using nanoFramework.Migrate.Core.Common; + +namespace nanoFramework.Migrate.Core.Verification; + +/// +/// The outcome of verifying one target (a solution or a project) by building it. +/// +public sealed class BuildOutcome +{ + /// The solution/project that was built (absolute path). + public required string Target { get; init; } + + /// True when the build succeeded (exit code 0). + public bool Succeeded { get; init; } + + /// + /// True when the build could not be attempted at all — e.g. the dotnet + /// CLI is not on PATH. Such a target is reported as skipped, not failed, + /// and never triggers rollback. + /// + public bool Skipped { get; init; } + + /// The process exit code (or a synthetic non-zero when skipped/errored). + public int ExitCode { get; init; } + + /// A short tail of the build output, surfaced on failure for diagnosis. + public string ErrorTail { get; init; } = ""; + + /// A skipped/setup message (e.g. "dotnet not found on PATH"). + public string? Message { get; init; } +} + +/// +/// Verifies a migration by building the affected solution(s)/project(s) with the +/// dotnet CLI on PATH. Captures the exit code and a short error tail so the +/// command can render pass/fail and decide whether to offer a rollback. +/// +/// The build invocation is isolated behind so the +/// result interpretation () is unit-testable without a real +/// build. The absence of dotnet is tolerated: the target is marked skipped +/// (a warning), never failed. +/// +public sealed class SolutionBuilder +{ + /// How many trailing non-empty output lines to keep as the error tail. + public const int ErrorTailLines = 12; + + private readonly IBuildRunner _runner; + + /// Builds via the real dotnet CLI on PATH. + public SolutionBuilder() : this(new DotnetBuildRunner()) { } + + /// Builds via the supplied runner (used by tests to fake the process). + public SolutionBuilder(IBuildRunner runner) => _runner = runner; + + /// + /// Builds every target and returns one each. When + /// dotnet is unavailable, every target is reported skipped and + /// (if given) is invoked once. + /// + public List VerifyAll(IEnumerable targets, Action? onProgress = null, + Action? onSkippedToolMissing = null, CancellationToken cancellationToken = default) + { + var results = new List(); + if (!_runner.IsAvailable) + { + onSkippedToolMissing?.Invoke(); + foreach (var t in targets) + results.Add(new BuildOutcome + { + Target = Path.GetFullPath(t), + Skipped = true, + ExitCode = -1, + Message = "dotnet not found on PATH; verification skipped", + }); + return results; + } + + foreach (var t in targets) + { + cancellationToken.ThrowIfCancellationRequested(); + var full = Path.GetFullPath(t); + onProgress?.Invoke(full); + var (code, stdout, stderr) = _runner.Build(full, cancellationToken); + results.Add(Interpret(full, code, stdout, stderr)); + } + return results; + } + + /// + /// Turns a raw build result (exit code + output streams) into a + /// . Pure and side-effect-free, so the pass/fail and + /// error-tail logic can be unit-tested without spawning a process. + /// + public static BuildOutcome Interpret(string target, int exitCode, string stdout, string stderr) + { + var succeeded = exitCode == 0; + return new BuildOutcome + { + Target = Path.GetFullPath(target), + Succeeded = succeeded, + ExitCode = exitCode, + ErrorTail = succeeded ? "" : Tail(stdout, stderr, ErrorTailLines), + }; + } + + /// + /// The last non-empty lines of the build output, + /// preferring lines that look like errors/warnings when there are many. Joined + /// with newlines; empty when both streams are blank. + /// + public static string Tail(string stdout, string stderr, int lines) + { + var all = (stdout ?? "") + .Replace("\r\n", "\n").Split('\n') + .Concat((stderr ?? "").Replace("\r\n", "\n").Split('\n')) + .Select(l => l.TrimEnd()) + .Where(l => l.Length > 0) + .ToList(); + if (all.Count == 0) return ""; + + // Prefer error/warning lines if present; otherwise just the tail. + var errs = all.Where(l => l.Contains("error", StringComparison.OrdinalIgnoreCase) + || l.Contains(": error", StringComparison.OrdinalIgnoreCase)).ToList(); + var pick = errs.Count > 0 ? errs : all; + return string.Join("\n", pick.Skip(Math.Max(0, pick.Count - lines))); + } +} + +/// +/// Abstracts the actual dotnet build invocation so the result interpretation +/// is testable without a real build. +/// +public interface IBuildRunner +{ + /// True when a build can be attempted (the dotnet CLI is on PATH). + bool IsAvailable { get; } + + /// Builds , returning the exit code and output streams. + (int exitCode, string stdout, string stderr) Build(string target, CancellationToken cancellationToken = default); +} + +/// The production runner: shells the dotnet already on PATH. +public sealed class DotnetBuildRunner : IBuildRunner +{ + private readonly Lazy _available = new(ProbeDotnet); + + public bool IsAvailable => _available.Value; + + public (int exitCode, string stdout, string stderr) Build(string target, CancellationToken cancellationToken = default) + { + var dir = Path.GetDirectoryName(Path.GetFullPath(target)) ?? "."; + try + { + return ProcessExec.Run("dotnet", $"build \"{target}\" --nologo", dir, cancellationToken: cancellationToken); + } + catch (OperationCanceledException) + { + throw; // propagate cancellation rather than reporting it as a build failure + } + catch (Exception ex) + { + return (-1, "", ex.Message); + } + } + + // True when `dotnet --version` runs and exits 0. Cached for the runner's lifetime. + private static bool ProbeDotnet() + { + try { return ProcessExec.Run("dotnet", "--version", Directory.GetCurrentDirectory(), timeoutMs: 30_000).exitCode == 0; } + catch { return false; } + } +} diff --git a/tools/migrate/src/NanoMigrate.Core/Verification/Verification.cs b/tools/migrate/src/NanoMigrate.Core/Verification/Verification.cs new file mode 100644 index 0000000..03b6a7b --- /dev/null +++ b/tools/migrate/src/NanoMigrate.Core/Verification/Verification.cs @@ -0,0 +1,79 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +namespace nanoFramework.Migrate.Core.Verification; + +/// What the command should do after the verification build(s) ran. +public enum VerifyOutcome +{ + /// Verification was not run (dry-run, --no-verify, or no targets). + NotRun, + + /// Every attempted target built (some may have been skipped). + Passed, + + /// At least one target failed to build — a rollback should be considered. + Failed, +} + +/// +/// The pure decision logic that turns a set of into a +/// verify outcome and, when it failed, into the rollback action the command should +/// take. Kept free of console/prompts so the failed-verify → rollback decision path +/// is unit-testable: the command renders/prompts around these answers. +/// +public static class Verification +{ + /// + /// The outcome of a verification pass. A failed target (built and returned + /// non-zero) means ; targets that were only + /// skipped (no dotnet) never count as failures. + /// + public static VerifyOutcome Evaluate(IReadOnlyList outcomes) + { + if (outcomes.Count == 0) return VerifyOutcome.NotRun; + if (outcomes.All(o => o.Skipped)) return VerifyOutcome.NotRun; + return outcomes.Any(o => !o.Succeeded && !o.Skipped) + ? VerifyOutcome.Failed + : VerifyOutcome.Passed; + } + + /// The number of targets that actually failed to build. + public static int FailedCount(IReadOnlyList outcomes) => + outcomes.Count(o => !o.Succeeded && !o.Skipped); + + /// + /// The rollback decision after a verification pass, given whether the session is + /// interactive and (for the interactive case) the user's yes/no answer supplied + /// as . This is the pure policy: + /// + /// verify did not fail → ; + /// failed + interactive + user said yes → ; + /// failed + interactive + user said no → ; + /// failed + non-interactive → + /// (never auto-roll-back silently; tell the user to run rollback). + /// + /// + public static RollbackDecision Decide(VerifyOutcome outcome, bool interactive, bool? userSaidYes) + { + if (outcome != VerifyOutcome.Failed) return RollbackDecision.None; + if (!interactive) return RollbackDecision.KeepNonInteractive; + return userSaidYes == true ? RollbackDecision.RollBack : RollbackDecision.KeepInteractive; + } +} + +/// What the command does about rollback after a verification. +public enum RollbackDecision +{ + /// No rollback needed (verification passed or did not run). + None, + + /// Roll back: restore originals and delete created files. + RollBack, + + /// Verification failed but the user (interactively) chose to keep the changes. + KeepInteractive, + + /// Verification failed in a non-interactive run: keep changes, exit non-zero, advise rollback. + KeepNonInteractive, +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/CleanTests.cs b/tools/migrate/tests/NanoMigrate.Tests/CleanTests.cs new file mode 100644 index 0000000..d74ede2 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/CleanTests.cs @@ -0,0 +1,113 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +public class CleanTests +{ + private static readonly IProjectConverter Converter = new ProjectConverter(); + + private const string Nfproj = """ + + Sample + + """; + + [Fact] + public void Clean_removes_all_nfproj_bak_and_nanomigrate_folders_and_reports_count() + { + using var dir = new TempDir(); + + // A real conversion leaves a Sample.nfproj.bak behind. + var nfproj = dir.File("a/Sample.nfproj", Nfproj); + Converter.Convert(nfproj, new ConversionOptions()); + Assert.True(File.Exists(nfproj + ".bak")); + + // A second, nested project's backup, plus a rollback journal folder. + var nfproj2 = dir.File("b/Other.nfproj", Nfproj); + Converter.Convert(nfproj2, new ConversionOptions()); + var journal = RollbackJournal.Start(dir.Path); + journal.BackupBeforeChange(dir.File("c/some.txt", "x")); + journal.Save(); + Assert.True(Directory.Exists(Path.Combine(dir.Path, RollbackJournal.FolderName))); + + var plan = BackupCleaner.Plan(dir.Path); + Assert.Equal(2, plan.BackupFiles.Count); + Assert.Single(plan.RollbackFolders); + Assert.Equal(3, plan.Total); + + var result = BackupCleaner.Remove(plan); + Assert.Empty(result.Problems); + Assert.Equal(3, result.Total); + + // Everything is gone; a re-plan finds nothing (idempotent). + Assert.False(File.Exists(nfproj + ".bak")); + Assert.False(File.Exists(nfproj2 + ".bak")); + Assert.False(Directory.Exists(Path.Combine(dir.Path, RollbackJournal.FolderName))); + Assert.True(BackupCleaner.Plan(dir.Path).IsEmpty); + } + + [Fact] + public void Clean_does_not_count_journal_internal_nfproj_backups_as_loose_backups() + { + using var dir = new TempDir(); + + // A --no-backup real migration: zero loose .bak, but the journal keeps its own + // "-Sample.nfproj.bak" copy of the original .nfproj inside .nanomigrate/. + var nfproj = dir.File("Sample.nfproj", Nfproj); + var journal = RollbackJournal.Start(dir.Path); + journal.BackupBeforeChange(nfproj); // -> .nanomigrate/rollback-/0000-Sample.nfproj.bak + journal.Save(); + + var plan = BackupCleaner.Plan(dir.Path); + + // The journal-internal .nfproj.bak must NOT be listed as a loose backup; the + // whole .nanomigrate folder is the single rollback-folder leftover instead. + Assert.Empty(plan.BackupFiles); + Assert.Single(plan.RollbackFolders); + + // Clean still removes the .nanomigrate folder wholesale. + BackupCleaner.Remove(plan); + Assert.False(Directory.Exists(Path.Combine(dir.Path, RollbackJournal.FolderName))); + } + + [Fact] + public void Clean_on_a_tree_with_no_leftovers_is_an_empty_noop() + { + using var dir = new TempDir(); + dir.File("Sample.csproj", ""); + + var plan = BackupCleaner.Plan(dir.Path); + Assert.True(plan.IsEmpty); + + var result = BackupCleaner.Remove(plan); + Assert.Equal(0, result.Total); + Assert.Empty(result.Problems); + } + + [Fact] + public void Clean_on_nonexistent_path_yields_empty_plan() + { + var plan = BackupCleaner.Plan(Path.Combine(Path.GetTempPath(), "nanomig-does-not-exist-" + Guid.NewGuid())); + Assert.True(plan.IsEmpty); + } + + [Fact] + public void Clean_does_not_touch_unrelated_files() + { + using var dir = new TempDir(); + var keep = dir.File("Keep.nfproj", Nfproj); // a live project, NOT a .bak + var keepCs = dir.File("Sample.csproj", ""); + dir.File("Sample.nfproj.bak", "backup"); // a leftover to remove + + var plan = BackupCleaner.Plan(dir.Path); + Assert.Single(plan.BackupFiles); + BackupCleaner.Remove(plan); + + Assert.True(File.Exists(keep)); + Assert.True(File.Exists(keepCs)); + Assert.False(File.Exists(dir.Combine("Sample.nfproj.bak"))); + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/ConverterTests.cs b/tools/migrate/tests/NanoMigrate.Tests/ConverterTests.cs new file mode 100644 index 0000000..af43e47 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/ConverterTests.cs @@ -0,0 +1,185 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +public class ConverterTests +{ + private static readonly IProjectConverter Converter = new ProjectConverter(); + + [Fact] + public void Already_sdk_style_project_is_skipped_and_not_written() + { + using var dir = new TempDir(); + const string sdkStyle = """ + + + netnano1.0 + + + """; + var nfproj = dir.File("Already.nfproj", sdkStyle); + var before = File.ReadAllText(nfproj); + + // A non-dry-run so we can prove nothing on disk changed. + var result = Converter.Convert(nfproj, new ConversionOptions()); + + Assert.Equal(ConvertStatus.Skipped, result.Status); + Assert.True(result.AlreadySdk); + Assert.True(File.Exists(nfproj)); // not deleted/renamed + Assert.Equal(before, File.ReadAllText(nfproj)); // not rewritten + Assert.False(File.Exists(nfproj + ".bak")); // no backup written + Assert.False(File.Exists(dir.Combine("Already.csproj"))); // nothing emitted + } + + [Fact] + public void PackageReference_version_comes_from_packages_config_when_absent() + { + using var dir = new TempDir(); + dir.File("packages.config", """ + + + + + """); + var nfproj = dir.File("Sample.nfproj", """ + + Sample + + + + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions { DryRun = true }); + + Assert.Contains(result.Packages, + p => p.Key == "nanoFramework.System.Text" && p.Value == "1.2.54"); + } + + [Fact] + public void Legacy_alias_mscorlib_maps_to_corelibrary_when_no_hintpath() + { + using var dir = new TempDir(); + dir.File("packages.config", """ + + + + + """); + var nfproj = dir.File("Sample.nfproj", """ + + Sample + + + + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions { DryRun = true }); + + Assert.Contains(result.Packages, + p => p.Key == "nanoFramework.CoreLibrary" && p.Value == "1.15.5"); + Assert.Empty(result.Review); + } + + [Fact] + public void Unresolved_reference_is_flagged_for_review_and_no_blank_version_emitted() + { + using var dir = new TempDir(); + // No HintPath, no packages.config — the version cannot be resolved. + var nfproj = dir.File("Sample.nfproj", """ + + Sample + + + + + """); + + var outPath = dir.Combine("Sample.csproj"); + var result = Converter.Convert(nfproj, new ConversionOptions()); // real run so we can read the emitted file + + Assert.Equal(ConvertStatus.Review, result.Status); + Assert.Contains(result.Review, r => r.Contains("SomeRandomLib")); + + var emitted = File.ReadAllText(outPath); + Assert.DoesNotContain("Version=\"\"", emitted); // never emit a blank version + Assert.DoesNotContain("SomeRandomLib", emitted); // the unresolved ref is not carried over + } + + [Fact] + public void Full_convert_emits_sdk_project_deletes_inputs_and_writes_backup() + { + using var dir = new TempDir(); + dir.File("packages.config", """ + + + + + """); + dir.File(Path.Combine("Properties", "AssemblyInfo.cs"), + "using System.Reflection;\n[assembly: AssemblyTitle(\"Sample\")]\n"); + var nfproj = dir.File("Sample.nfproj", """ + + + {00000000-0000-0000-0000-000000000000} + Sample + Sample + + + + + + + + + + + + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions()); + + var csproj = dir.Combine("Sample.csproj"); + Assert.Equal(ConvertStatus.Converted, result.Status); + + // Emitted SDK-style project. + Assert.True(File.Exists(csproj)); + var emitted = File.ReadAllText(csproj); + Assert.Contains("", emitted); + Assert.Contains("netnano1.0", emitted); + Assert.Contains("Sample", emitted); + Assert.Contains("nanoFramework.CoreLibrary", emitted); + Assert.DoesNotContain("ProjectGuid", emitted); // boilerplate dropped + + // Inputs removed. + Assert.False(File.Exists(nfproj)); // .nfproj retired + Assert.False(File.Exists(dir.Combine("packages.config"))); + Assert.False(File.Exists(dir.Combine(Path.Combine("Properties", "AssemblyInfo.cs")))); + + // Backup of the original .nfproj written. + Assert.True(File.Exists(nfproj + ".bak")); + } + + [Fact] + public void Dry_run_writes_nothing() + { + using var dir = new TempDir(); + var nfproj = dir.File("Sample.nfproj", """ + + Sample + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions { DryRun = true }); + + Assert.Equal(ConvertStatus.Converted, result.Status); + Assert.True(File.Exists(nfproj)); // original untouched + Assert.False(File.Exists(dir.Combine("Sample.csproj"))); // nothing emitted + Assert.False(File.Exists(nfproj + ".bak")); // no backup + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/CpmTests.cs b/tools/migrate/tests/NanoMigrate.Tests/CpmTests.cs new file mode 100644 index 0000000..91d7656 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/CpmTests.cs @@ -0,0 +1,201 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +/// +/// Central Package Management (CPM) behavior: versionless PackageReferences in the +/// project, central PackageVersion entries in Directory.Packages.props, idempotency, +/// and no-crash on already-central inputs. +/// +public class CpmTests +{ + private static readonly IProjectConverter Converter = new ProjectConverter(); + + private const string CpmPropsEnabled = """ + + + true + + + + + """; + + private const string LegacyNfproj = """ + + Sample + + + + + + """; + + private const string LegacyPackagesConfig = """ + + + + + + """; + + [Fact] + public void Cpm_emits_versionless_PackageReferences_and_seeds_central_props() + { + using var dir = new TempDir(); + var props = dir.File("Directory.Packages.props", CpmPropsEnabled); + dir.File(Path.Combine("Sample", "packages.config"), LegacyPackagesConfig); + var nfproj = dir.File(Path.Combine("Sample", "Sample.nfproj"), LegacyNfproj); + + var result = Converter.Convert(nfproj, new ConversionOptions()); + + Assert.Equal(ConvertStatus.Converted, result.Status); + Assert.Empty(result.Review); + + // Project: versionless references, never with a Version attribute. + var emitted = File.ReadAllText(dir.Combine(Path.Combine("Sample", "Sample.csproj"))); + Assert.Contains("", emitted); + Assert.Contains("", emitted); + Assert.DoesNotContain("Version=", emitted); // no version on any PackageReference + + // Central props: gained a PackageVersion for each referenced id. + var propsXml = File.ReadAllText(props); + Assert.Contains("", propsXml); + Assert.Contains("", propsXml); + + // Result preview reflects the central-props edit. + Assert.Equal(Path.GetFullPath(props), result.UpdatedPackagesProps); + Assert.Equal(2, result.AddedPackageVersions.Count); + } + + [Fact] + public void Cpm_second_project_with_same_ids_adds_no_duplicate_PackageVersion() + { + using var dir = new TempDir(); + var props = dir.File("Directory.Packages.props", CpmPropsEnabled); + + // Project A seeds the central props. + dir.File(Path.Combine("A", "packages.config"), LegacyPackagesConfig); + var a = dir.File(Path.Combine("A", "A.nfproj"), LegacyNfproj); + var resultA = Converter.Convert(a, new ConversionOptions()); + Assert.Equal(2, resultA.AddedPackageVersions.Count); + var propsAfterA = File.ReadAllText(props); + + // Project B references the same ids; the props already has them, so nothing + // is added and the file is byte-for-byte unchanged (idempotent). + dir.File(Path.Combine("B", "packages.config"), LegacyPackagesConfig); + var b = dir.File(Path.Combine("B", "B.nfproj"), LegacyNfproj); + var resultB = Converter.Convert(b, new ConversionOptions()); + + Assert.Empty(resultB.AddedPackageVersions); + Assert.Null(resultB.UpdatedPackagesProps); + var propsAfterB = File.ReadAllText(props); + Assert.Equal(propsAfterA, propsAfterB); // central props untouched the second time + + // Exactly one PackageVersion per id (no duplicates). + Assert.Equal(1, CountOccurrences(propsAfterB, "Include=\"nanoFramework.CoreLibrary\"")); + Assert.Equal(1, CountOccurrences(propsAfterB, "Include=\"nanoFramework.System.Device.Gpio\"")); + } + + [Fact] + public void Cpm_does_not_duplicate_a_preexisting_PackageVersion() + { + using var dir = new TempDir(); + // Central props already pins one of the two ids. + var props = dir.File("Directory.Packages.props", """ + + + true + + + + + + """); + dir.File(Path.Combine("Sample", "packages.config"), LegacyPackagesConfig); + var nfproj = dir.File(Path.Combine("Sample", "Sample.nfproj"), LegacyNfproj); + + var result = Converter.Convert(nfproj, new ConversionOptions()); + + var propsXml = File.ReadAllText(props); + // The pre-existing entry appears exactly once (not duplicated). + Assert.Equal(1, CountOccurrences(propsXml, "Include=\"nanoFramework.CoreLibrary\"")); + // The genuinely-missing id was added. + Assert.Contains("", propsXml); + // Only the missing id is recorded as an addition. + Assert.Single(result.AddedPackageVersions); + Assert.Equal("nanoFramework.System.Device.Gpio", result.AddedPackageVersions[0].Key); + } + + [Fact] + public void Cpm_disabled_props_does_not_trigger_versionless_emission() + { + using var dir = new TempDir(); + // A Directory.Packages.props that does NOT enable CPM. + dir.File("Directory.Packages.props", """ + + + false + + + """); + dir.File(Path.Combine("Sample", "packages.config"), LegacyPackagesConfig); + var nfproj = dir.File(Path.Combine("Sample", "Sample.nfproj"), LegacyNfproj); + + Converter.Convert(nfproj, new ConversionOptions()); + + var emitted = File.ReadAllText(dir.Combine(Path.Combine("Sample", "Sample.csproj"))); + // Versions are pinned inline because CPM is not active. + Assert.Contains("", emitted); + } + + [Fact] + public void Cpm_does_not_crash_when_input_already_under_central_props() + { + using var dir = new TempDir(); + dir.File("Directory.Packages.props", CpmPropsEnabled); + // An already-SDK-style project sitting under the central props: it is skipped + // by the Sdk-attribute guard and must not throw. + var csproj = dir.File(Path.Combine("Sample", "Sample.csproj"), """ + + netnano1.0 + + + + + """); + + var ex = Record.Exception(() => Converter.Convert(csproj, new ConversionOptions())); + Assert.Null(ex); + var result = Converter.Convert(csproj, new ConversionOptions()); + Assert.Equal(ConvertStatus.Skipped, result.Status); + } + + [Fact] + public void Cpm_option_override_forces_versionless_without_props_on_disk() + { + using var dir = new TempDir(); + // No Directory.Packages.props at all, but the option forces CPM on. + dir.File("packages.config", LegacyPackagesConfig); + var nfproj = dir.File("Sample.nfproj", LegacyNfproj); + + var result = Converter.Convert(nfproj, + new ConversionOptions { DryRun = true, CentralPackageManagement = true }); + + // Dry run writes nothing; assert via the result data. + Assert.Empty(result.Review); + Assert.Contains(result.Packages, p => p.Key == "nanoFramework.CoreLibrary"); + // No central props on disk → nothing to update, but it must not crash. + Assert.Null(result.UpdatedPackagesProps); + } + + private static int CountOccurrences(string haystack, string needle) + { + int count = 0, i = 0; + while ((i = haystack.IndexOf(needle, i, StringComparison.Ordinal)) >= 0) { count++; i += needle.Length; } + return count; + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/GlobTests.cs b/tools/migrate/tests/NanoMigrate.Tests/GlobTests.cs new file mode 100644 index 0000000..633b3a8 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/GlobTests.cs @@ -0,0 +1,39 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +public class GlobTests +{ + [Theory] + // single star: stays within a path segment + [InlineData("Foo.nfproj", "*.nfproj", true)] + [InlineData("Foo.csproj", "*.nfproj", false)] + [InlineData("sub/Foo.nfproj", "*.nfproj", false)] // '*' does not cross a separator + [InlineData("sub/Foo.nfproj", "*/*.nfproj", true)] + // double star: spans directories + [InlineData("a/b/c/Foo.nfproj", "**/*.nfproj", true)] + [InlineData("Foo.nfproj", "**/*.nfproj", true)] // ** can match zero directories + [InlineData("Beginner/x/y.nfproj", "Beginner/**", true)] + [InlineData("Other/x/y.nfproj", "Beginner/**", false)] + // "**/" ends on a directory boundary: it matches zero or whole segments, not a partial one + [InlineData("Foo.nfproj", "**/Foo.nfproj", true)] + [InlineData("a/b/Foo.nfproj", "**/Foo.nfproj", true)] + [InlineData("MyFoo.nfproj", "**/Foo.nfproj", false)] + // the "Beginner/** matches Beginner itself" rule + [InlineData("Beginner", "Beginner/**", true)] + // single char wildcard + [InlineData("Foo1.nfproj", "Foo?.nfproj", true)] + [InlineData("Foo12.nfproj", "Foo?.nfproj", false)] // '?' is exactly one char + [InlineData("Foo/.nfproj", "Foo?.nfproj", false)] // '?' does not match a separator + // separator-insensitive + [InlineData("a\\b\\Foo.nfproj", "a/b/*.nfproj", true)] + // case-insensitive + [InlineData("FOO.NFPROJ", "*.nfproj", true)] + public void IsMatch(string path, string pattern, bool expected) + { + Assert.Equal(expected, Glob.IsMatch(path, pattern)); + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/HintPathTests.cs b/tools/migrate/tests/NanoMigrate.Tests/HintPathTests.cs new file mode 100644 index 0000000..c975b00 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/HintPathTests.cs @@ -0,0 +1,52 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +public class HintPathTests +{ + private static readonly IProjectConverter Converter = new ProjectConverter(); + + private static string NfprojWithHintPath(string hintPath, string referenceInclude) => $""" + + + Sample + + + + {hintPath} + + + + """; + + [Fact] + public void HintPath_splits_id_and_version_at_first_numeric_segment() + { + using var dir = new TempDir(); + var nfproj = dir.File("Sample.nfproj", NfprojWithHintPath( + @"..\packages\nanoFramework.System.Device.Gpio.1.1.57\lib\System.Device.Gpio.dll", + "System.Device.Gpio")); + + var result = Converter.Convert(nfproj, new ConversionOptions { DryRun = true }); + + Assert.Contains(result.Packages, + p => p.Key == "nanoFramework.System.Device.Gpio" && p.Value == "1.1.57"); + } + + [Fact] + public void HintPath_keeps_prerelease_suffix_attached_to_version() + { + using var dir = new TempDir(); + var nfproj = dir.File("Sample.nfproj", NfprojWithHintPath( + @"..\packages\nanoFramework.CoreLibrary.2.0.0-preview.52\lib\mscorlib.dll", + "mscorlib")); + + var result = Converter.Convert(nfproj, new ConversionOptions { DryRun = true }); + + Assert.Contains(result.Packages, + p => p.Key == "nanoFramework.CoreLibrary" && p.Value == "2.0.0-preview.52"); + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/ItemGlobTests.cs b/tools/migrate/tests/NanoMigrate.Tests/ItemGlobTests.cs new file mode 100644 index 0000000..38d013c --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/ItemGlobTests.cs @@ -0,0 +1,308 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +/// +/// Tests for the converter hardening that keeps migrated samples building: the SDK +/// globs Compile/EmbeddedResource/Content/None by default, so an explicit +/// Include= of a default-located file duplicates the globbed item (NETSDK1022) +/// or loses an intended exclusion. These cover the Include→Update / drop / keep +/// decisions, the Compile-subset Remove, a kept nano AssemblyInfo, and the +/// Shared Project import. +/// +public class ItemGlobTests +{ + private static readonly IProjectConverter Converter = new ProjectConverter(); + + // Convert a project (real run so we can read the emitted .csproj) and return the + // emitted text. Seeds a packages.config so packages.config-authoritative mode is + // exercised, matching real samples. + private static string ConvertAndRead(TempDir dir, string nfprojBody, string? csName = null) + { + dir.File("packages.config", """ + + + + + """); + var nfproj = dir.File((csName ?? "Sample") + ".nfproj", nfprojBody); + var result = Converter.Convert(nfproj, new ConversionOptions()); + Assert.Null(result.Error); + return File.ReadAllText(dir.Combine((csName ?? "Sample") + ".csproj")); + } + + [Fact] + public void EmbeddedResource_with_metadata_becomes_Update_not_Include() + { + using var dir = new TempDir(); + var emitted = ConvertAndRead(dir, """ + + Sample + + + nFResXFileCodeGenerator + Resources.Designer.cs + + + + """); + + // Update (not Include) so the metadata attaches to the SDK-globbed resx + // without re-including it — re-including would trip NETSDK1022. + Assert.Contains("", emitted); + Assert.DoesNotContain("nFResXFileCodeGenerator", emitted); + Assert.Contains("Resources.Designer.cs", emitted); + } + + [Fact] + public void EmbeddedResource_without_metadata_is_dropped() + { + using var dir = new TempDir(); + var emitted = ConvertAndRead(dir, """ + + Sample + + + + + """); + + // No metadata → the SDK globs it plainly, so the explicit item is dropped + // entirely (keeping it would duplicate the globbed item). + Assert.DoesNotContain("Plain.resx", emitted); + } + + [Fact] + public void None_with_metadata_becomes_Update() + { + using var dir = new TempDir(); + var emitted = ConvertAndRead(dir, """ + + Sample + + + PreserveNewest + + + + """); + + Assert.Contains("", emitted); + Assert.Contains("PreserveNewest", emitted); + } + + [Fact] + public void None_without_metadata_is_dropped() + { + using var dir = new TempDir(); + var emitted = ConvertAndRead(dir, """ + + Sample + + + + + """); + + Assert.DoesNotContain("favicon.png", emitted); + } + + [Fact] + public void Item_with_Link_is_kept_as_Include() + { + using var dir = new TempDir(); + var emitted = ConvertAndRead(dir, """ + + Sample + + + shared.txt + + + + """); + + // A linked file is NOT default-globbed, so it must stay an Include with its Link. + Assert.Contains("Include=\"..\\Shared\\shared.txt\"", emitted); + Assert.Contains("shared.txt", emitted); + Assert.DoesNotContain("Update=", emitted); + } + + [Fact] + public void External_rooted_path_is_kept_as_Include() + { + using var dir = new TempDir(); + var emitted = ConvertAndRead(dir, """ + + Sample + + + + + """); + + // Outside the project dir → SDK won't glob it → keep verbatim (no dup, no drop). + Assert.Contains("Include=\"..\\Outside\\external.resx\"", emitted); + } + + [Fact] + public void Content_with_metadata_becomes_Update() + { + using var dir = new TempDir(); + var emitted = ConvertAndRead(dir, """ + + Sample + + + Always + + + + """); + + Assert.Contains("", emitted); + Assert.Contains("Always", emitted); + } + + [Fact] + public void Compile_subset_emits_Remove_for_unlisted_on_disk_cs() + { + using var dir = new TempDir(); + // On disk there are TWO .cs files, but the legacy project compiles only one. + // The SDK globs **/*.cs, so the unlisted file must be Removed or it gets + // compiled (duplicate definitions in real samples). + dir.File("Test.cs", "// compiled\n"); + dir.File("Alternate.cs", "// NOT compiled by the legacy project\n"); + var emitted = ConvertAndRead(dir, """ + + Sample + + + + + """); + + Assert.Contains("", emitted); + Assert.DoesNotContain("Remove=\"Test.cs\"", emitted); // the listed file is not removed + } + + [Fact] + public void Compile_listing_all_on_disk_cs_emits_no_Remove() + { + using var dir = new TempDir(); + dir.File("Program.cs", "// compiled\n"); + var emitted = ConvertAndRead(dir, """ + + Sample + + + + + """); + + // The explicit set equals the on-disk set → nothing to exclude. + Assert.DoesNotContain("Compile Remove", emitted); + } + + [Fact] + public void AssemblyInfo_with_native_version_is_kept_and_generation_disabled() + { + using var dir = new TempDir(); + var aiPath = dir.File(Path.Combine("Properties", "AssemblyInfo.cs"), + "using System.Reflection;\n[assembly: AssemblyNativeVersion(\"1.0.0.0\")]\n"); + var nfproj = dir.File("Lib.nfproj", """ + + + Library + Lib + + + + + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions()); + var emitted = File.ReadAllText(dir.Combine("Lib.csproj")); + + // The MetadataProcessor needs AssemblyNativeVersion when generating stubs, and + // the SDK never generates it — so the file is KEPT (not deleted) and generation + // is turned off so the standard attributes don't collide with generated ones. + Assert.True(File.Exists(aiPath)); // not deleted + Assert.Contains("false", emitted); + Assert.DoesNotContain(aiPath, result.DeletedFiles); // not previewed as a deletion + } + + [Fact] + public void Ordinary_AssemblyInfo_is_still_deleted_and_generation_left_on() + { + using var dir = new TempDir(); + var aiPath = dir.File(Path.Combine("Properties", "AssemblyInfo.cs"), + "using System.Reflection;\n[assembly: AssemblyTitle(\"Sample\")]\n"); + var nfproj = dir.File("Sample.nfproj", """ + + Sample + + + + + """); + + Converter.Convert(nfproj, new ConversionOptions()); + var emitted = File.ReadAllText(dir.Combine("Sample.csproj")); + + // No nano-specific attribute → original behavior: delete the file, let the SDK + // generate the assembly info. + Assert.False(File.Exists(aiPath)); + Assert.DoesNotContain("GenerateAssemblyInfo", emitted); + } + + [Fact] + public void Shared_project_import_is_carried_through() + { + using var dir = new TempDir(); + var emitted = ConvertAndRead(dir, """ + + + $(MSBuildExtensionsPath)\nanoFramework\v1.0\ + + + Sample + + + + """); + + // The Shared Project import carries source the SDK would otherwise never see — + // it must survive. The NFProjectSystem.* imports are SDK boilerplate, dropped. + Assert.Contains("", emitted); + Assert.DoesNotContain("NFProjectSystem", emitted); + } + + [Fact] + public void Unknown_top_level_import_is_flagged_for_review() + { + using var dir = new TempDir(); + dir.File("packages.config", """ + + + + + """); + var nfproj = dir.File("Sample.nfproj", """ + + Sample + + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions { DryRun = true }); + + Assert.Contains(result.Review, r => r.Contains("Custom.targets")); + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/NanoMigrate.Tests.csproj b/tools/migrate/tests/NanoMigrate.Tests/NanoMigrate.Tests.csproj new file mode 100644 index 0000000..78d20b1 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/NanoMigrate.Tests.csproj @@ -0,0 +1,36 @@ + + + + net10.0 + enable + enable + nanoFramework.Migrate.Tests + false + true + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/tools/migrate/tests/NanoMigrate.Tests/OutputTypeTests.cs b/tools/migrate/tests/NanoMigrate.Tests/OutputTypeTests.cs new file mode 100644 index 0000000..61fcb95 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/OutputTypeTests.cs @@ -0,0 +1,39 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +public class OutputTypeTests +{ + private static readonly IProjectConverter Converter = new ProjectConverter(); + + [Fact] + public void OutputType_Exe_is_preserved_so_apps_stay_executables() + { + using var dir = new TempDir(); + dir.File("packages.config", """ + + + + + """); + var nfproj = dir.File("App.nfproj", """ + + + Exe + App + + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions()); + + Assert.Equal(ConvertStatus.Converted, result.Status); + var csproj = File.ReadAllText(dir.Combine("App.csproj")); + // Regression: OutputType used to be silently dropped, turning apps into libraries + // (CS8805 for top-level-statement apps). It must survive conversion. + Assert.Contains("Exe", csproj); + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/PackageResolutionTests.cs b/tools/migrate/tests/NanoMigrate.Tests/PackageResolutionTests.cs new file mode 100644 index 0000000..fc6e63b --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/PackageResolutionTests.cs @@ -0,0 +1,166 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +/// +/// Tests for the packages.config-first resolution strategy and Central Package +/// Management (CPM) support added to . +/// +public class PackageResolutionTests +{ + private static readonly IProjectConverter Converter = new ProjectConverter(); + + // A WiFiAP-like project whose elements are bare assembly names that + // routinely differ from the NuGet package id, while packages.config carries the + // real nano package ids+versions. + private const string WiFiApLikeNfproj = """ + + + WifiAP + WifiAP + + + + + + + + + """; + + private const string WiFiApLikePackagesConfig = """ + + + + + + + + """; + + [Fact] + public void PackagesConfig_is_authoritative_emits_exactly_its_ids_and_versions() + { + using var dir = new TempDir(); + dir.File("packages.config", WiFiApLikePackagesConfig); + var nfproj = dir.File("WifiAP.nfproj", WiFiApLikeNfproj); + + var result = Converter.Convert(nfproj, new ConversionOptions { DryRun = true }); + + Assert.Equal(ConvertStatus.Converted, result.Status); + Assert.Empty(result.Review); // no assembly/id mismatch flags + + // The emitted package set is exactly the packages.config entries, verbatim. + var expected = new Dictionary + { + ["nanoFramework.System.Device.Gpio"] = "1.1.57", + ["nanoFramework.System.Net.Http.Server"] = "1.5.207", + ["nanoFramework.System.Threading"] = "1.1.52", + ["nanoFramework.CoreLibrary"] = "1.17.11", + }; + Assert.Equal(expected.Count, result.Packages.Count); + foreach (var kv in expected) + Assert.Contains(result.Packages, p => p.Key == kv.Key && p.Value == kv.Value); + + // The bare assembly names from never become packages. + Assert.DoesNotContain(result.Packages, p => p.Key == "System.Device.Gpio"); + Assert.DoesNotContain(result.Packages, p => p.Key == "System.Net.Http"); + Assert.DoesNotContain(result.Packages, p => p.Key == "System.Threading"); + Assert.DoesNotContain(result.Packages, p => p.Key == "mscorlib"); + } + + [Fact] + public void PackagesConfig_first_emits_no_Reference_elements() + { + using var dir = new TempDir(); + dir.File("packages.config", WiFiApLikePackagesConfig); + var nfproj = dir.File("WifiAP.nfproj", WiFiApLikeNfproj); + + Converter.Convert(nfproj, new ConversionOptions()); // real run + + var emitted = File.ReadAllText(dir.Combine("WifiAP.csproj")); + Assert.DoesNotContain(" + Sample + + + ..\packages\nanoFramework.System.Device.Gpio.1.1.57\lib\System.Device.Gpio.dll + + + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions { DryRun = true }); + + Assert.Empty(result.Review); + Assert.Contains(result.Packages, + p => p.Key == "nanoFramework.System.Device.Gpio" && p.Value == "1.1.57"); + } + + [Fact] + public void No_packages_config_unresolved_reference_is_flagged() + { + using var dir = new TempDir(); + // No packages.config and no HintPath: unresolvable → review, never blank version. + var nfproj = dir.File("Sample.nfproj", """ + + Sample + + + + + """); + + var result = Converter.Convert(nfproj, new ConversionOptions()); + + Assert.Equal(ConvertStatus.Review, result.Status); + Assert.Contains(result.Review, r => r.Contains("MysteryLib")); + var emitted = File.ReadAllText(dir.Combine("Sample.csproj")); + Assert.DoesNotContain("Version=\"\"", emitted); + } + + [Fact] + public void ProjectCapability_TestContainer_is_preserved_not_flagged() + { + using var dir = new TempDir(); + dir.File("packages.config", """ + + + + + + """); + var nfproj = dir.File("NFUnitTest.nfproj", """ + + + + + + NFUnitTest + true + UnitTest + + + """); + + Converter.Convert(nfproj, new ConversionOptions()); + + var emitted = File.ReadAllText(dir.Combine("NFUnitTest.csproj")); + Assert.Contains("", emitted); + Assert.Contains("true", emitted); + Assert.Contains("UnitTest", emitted); + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/ProjectScannerTests.cs b/tools/migrate/tests/NanoMigrate.Tests/ProjectScannerTests.cs new file mode 100644 index 0000000..779d386 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/ProjectScannerTests.cs @@ -0,0 +1,58 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +public class ProjectScannerTests +{ + private const string Stub = ""; + + [Fact] + public void ResolveProjects_returns_single_file_when_path_is_an_nfproj() + { + using var dir = new TempDir(); + var nfproj = dir.File("Solo.nfproj", Stub); + + var targets = ProjectScanner.ResolveProjects(nfproj, glob: null); + + Assert.Single(targets); + Assert.Equal(Path.GetFullPath(nfproj), targets[0]); + } + + [Fact] + public void ResolveProjects_enumerates_directory_recursively_sorted() + { + using var dir = new TempDir(); + dir.File(Path.Combine("b", "Two.nfproj"), Stub); + dir.File(Path.Combine("a", "One.nfproj"), Stub); + dir.File("ReadMe.txt", "not a project"); + + var targets = ProjectScanner.ResolveProjects(dir.Path, glob: null); + + Assert.Equal(2, targets.Count); + Assert.EndsWith("One.nfproj", targets[0]); // sorted: a/ before b/ + Assert.EndsWith("Two.nfproj", targets[1]); + } + + [Fact] + public void ResolveProjects_applies_glob_filter() + { + using var dir = new TempDir(); + dir.File(Path.Combine("Beginner", "Blink.nfproj"), Stub); + dir.File(Path.Combine("Advanced", "Threads.nfproj"), Stub); + + var targets = ProjectScanner.ResolveProjects(dir.Path, glob: "Beginner/**"); + + Assert.Single(targets); + Assert.EndsWith("Blink.nfproj", targets[0]); + } + + [Fact] + public void ResolveProjects_returns_empty_for_missing_path() + { + var targets = ProjectScanner.ResolveProjects(Path.Combine(Path.GetTempPath(), "does-not-exist-" + Guid.NewGuid()), glob: null); + Assert.Empty(targets); + } +} diff --git a/tools/migrate/tests/NanoMigrate.Tests/ReportingTests.cs b/tools/migrate/tests/NanoMigrate.Tests/ReportingTests.cs new file mode 100644 index 0000000..70279b2 --- /dev/null +++ b/tools/migrate/tests/NanoMigrate.Tests/ReportingTests.cs @@ -0,0 +1,209 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using nanoFramework.Migrate.Cli.Commands; +using nanoFramework.Migrate.Cli.Rendering; +using Spectre.Console.Cli; +using Xunit; + +namespace nanoFramework.Migrate.Tests; + +public class ReportingTests +{ + // A representative set of project outcomes: one clean conversion (with packages), + // one skipped (already SDK-style), one flagged for review (with a name that needs + // HTML escaping), and one error. + private static MigrationReport BuildRepresentativeReport(DateTime utc) + { + var converted = new ReportEntry + { + RelativePath = "src/Clean.nfproj", + Status = ConvertStatus.Converted, + Packages = new[] + { + new KeyValuePair("nanoFramework.System.Text", "1.2.54"), + }, + }; + var skipped = new ReportEntry + { + RelativePath = "src/Already.nfproj", + Status = ConvertStatus.Skipped, + }; + var review = new ReportEntry + { + // A name with characters that MUST be escaped in HTML. + RelativePath = "src/A&B.nfproj", + Status = ConvertStatus.Review, + Review = new[] { "HintPath '..\\bin\\' could not be resolved & needs review" }, + }; + var error = new ReportEntry + { + RelativePath = "src/Boom.nfproj", + Status = ConvertStatus.Error, + Error = "the project file could not be parsed", + }; + + return new MigrationReport + { + RootPath = @"C:\repo", + GeneratedUtc = utc, + DryRun = false, + Projects = new[] { converted, skipped, review, error }, + AffectedSolutions = new[] { "Sample.sln" }, + Verify = new[] + { + new ReportVerifyEntry { Target = "Sample.sln", Succeeded = true, Skipped = false }, + }, + }; + } + + [Fact] + public void Markdown_contains_totals_a_row_per_project_and_review_section() + { + var report = BuildRepresentativeReport(new DateTime(2026, 6, 16, 12, 0, 0, DateTimeKind.Utc)); + var md = MarkdownReportWriter.Render(report); + + // Totals line. + Assert.Contains("converted 1", md); + Assert.Contains("skipped 1", md); + Assert.Contains("flagged 1", md); + Assert.Contains("errors 1", md); + Assert.Contains("total 4", md); + + // A row per project (the table uses the relative path in the first cell). + Assert.Contains("src/Clean.nfproj", md); + Assert.Contains("src/Already.nfproj", md); + Assert.Contains("src/Boom.nfproj", md); + + // The package id/version appear in the converted row. + Assert.Contains("nanoFramework.System.Text", md); + Assert.Contains("1.2.54", md); + + // The manual review section lists the flagged item. + Assert.Contains("## Manual review", md); + Assert.Contains("HintPath", md); + + // The verification section is present. + Assert.Contains("## Verification", md); + } + + [Fact] + public void Html_contains_rows_status_css_classes_and_escapes_special_characters() + { + var report = BuildRepresentativeReport(new DateTime(2026, 6, 16, 12, 0, 0, DateTimeKind.Utc)); + var html = HtmlReportWriter.Render(report); + + // Self-contained: inline style, no external assets. + Assert.Contains("