Installation
copilot plugin marketplace add samueltauil/skills-hub
copilot plugin install logicapps-custom-code-net10-migration@skills-hub
Works with GitHub Copilot CLI and VS Code (enable chat.plugins.enabled).
Plugin logicapps-custom-code-net10-migration v1.0.0 follows the Agent Plugins spec.
gh skills-hub install logicapps-custom-code-net10-migration Don't have the extension? Run gh extension install samueltauil/skills-hub first.
Download and extract to your repository:
.github/skills/logicapps-custom-code-net10-migration/ Extract the ZIP to .github/skills/ in your repo. The folder name must match logicapps-custom-code-net10-migration for Copilot to auto-discover it.
Skill Files (6)
LICENSE 1.0 KB
MIT License
Copyright (c) 2026 wsilveiranz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
README.md 7.7 KB
# Logic Apps custom-code .NET 10 migration skill
## Install
With GitHub CLI 2.90.0 or later (`gh skill` is currently preview), inspect the skill
and install it for Copilot across projects:
```powershell
gh skill preview github/awesome-copilot logicapps-custom-code-net10-migration
gh skill install github/awesome-copilot logicapps-custom-code-net10-migration --agent github-copilot --scope user
```
For a project-scoped installation, use `--scope project` from the target repository.
Installation makes the skill available to the agent; it does not run a migration.
Alternatively, copy this **entire folder** into a supported skills directory. For a personal
installation, use `<user profile>\.copilot\skills\logicapps-custom-code-net10-migration`;
for a project installation, use `.github\skills\logicapps-custom-code-net10-migration`.
Cloning the source repository alone does not install the skill. No plugin or third-party
Python package is required. The package is licensed under MIT.
## Prerequisites
The [November 5 announcement](https://techcommunity.microsoft.com/blog/IntegrationsonAzureBlog/logic-apps-standard-custom-code-now-supports-net-10/4570808)
documents the release prerequisites and migration configuration:
- Azure Logic Apps (Standard) VS Code extension 5.1013.2, or a later version with .NET 10 custom-code support.
- Logic Apps Standard extension bundle 1.194.31.
- VS Code-selected .NET 10 SDK/runtime and the existing .NET 8 host runtime.
- Python 3.11+ for the offline configuration helper and its tests.
## Use
Invoke the installed skill with a request such as:
> Migrate this Logic Apps Standard .NET 8 custom-code workspace to .NET 10 using
> logicapps-custom-code-net10-migration. Preserve the host and function identities.
The helper can also be run directly with Python 3.11+:
```powershell
python ".\scripts\migrate.py" --root "C:\src\MySolution"
python ".\scripts\migrate.py" --root "C:\src\MySolution" --apply
```
Default is dry run. Exit `0` means a valid plan or successful configuration application,
not a passing build/runtime test; exit `1` means a blocker/failure. For multiple projects,
add `--project "C:\src\MySolution\CustomCode\Utilities.csproj"`.
Default migration preserves a missing direct Worker reference, existing logging pins
when no direct Worker is selected, and all debugger configuration. Existing Worker
references are aligned to the reviewed baseline with dependent logging pins adjusted.
Do not interpret the sample dependency set as a universal minimum.
The migration targets `Microsoft.Azure.Workflows.Webjobs.Sdk` **1.4.1** to incorporate
a bug fix for 1.4.0. Confirm that 1.4.1 is available from the approved
NuGet feed before applying the migration or restoring packages. Configuration tests
do not establish package restore, build or runtime compatibility.
Conditional options (include the same options in dry run and apply):
```powershell
python ".\scripts\migrate.py" --root "C:\src\MySolution" --integrated-debug
python ".\scripts\migrate.py" --root "C:\src\MySolution" --integrated-debug --apply
python ".\scripts\migrate.py" --root "C:\src\MySolution" --ensure-output-directory
python ".\scripts\migrate.py" --root "C:\src\MySolution" --ensure-output-directory --apply
```
Use `--integrated-debug` for coordinated workflow/custom-code launching, not merely
because the target framework changes. Use `--ensure-output-directory` only when the SDK
directory scan needs the clean-build workaround. A narrowly recognized existing
broken guard is repaired without the flag. Options can be combined when both apply.
The helper supports direct, unconditional SDK-style project configuration and UTF-8
JSON/JSONC settings (comments and trailing commas are preserved). It resolves the host
from `LogicAppFolderToPublish` and does not assume sample folder or assembly names.
With `--integrated-debug`, it appends an integrated debugger entry while keeping existing
entries, or updates an unambiguous existing integrated launcher. Project XML
whitespace/comments are retained, but XML serializer details such as self-closing tag
spacing can change.
It refuses ambiguous layouts, encrypted local settings, external host roots, conditional
or centrally managed package/property definitions, explicit imports, inherited
`Directory.Build.*`/`Directory.Packages.props`/`global.json`, and unreviewed newer Workflows
SDK targets. Agent-led review is required for these cases; see the bundled procedure.
Missing workspace/task files are reported as manual follow-up, not silently fabricated.
Custom publication hooks and unresolved hook expressions block adding publish-on-build.
Existing build/publication hooks are preserved, not authorized for execution: review
their network/deployment effects before any validation build, even in a disposable copy.
Apply keeps originals in memory for rollback and checks for concurrent changes. There
are no intentional persistent backups, network access, package installs, builds, host
execution or Azure operations. Inspect and back up configuration through your approved
process when required. Do not run concurrently with another editor/host modifying the same files.
**Interrupted-write warning:** temporary files use `.<original filename>.<random>` beside
the original. Forced termination can bypass cleanup and leave credentials in
`.local.settings.json.*`. Before applying, verify that source-control and deployment
exclusions cover these temporary names, not just `local.settings.json`. Inspect for
leftovers before committing or packaging, and remove only confirmed migration-owned
files through your approved secret-handling process without displaying their contents.
Existing access restrictions are copied before temporary files receive configuration
bytes: Windows security descriptors (including inheritance protection and integrity
labels), or Linux ownership, permissions and access-control extended attributes.
Application blocks when metadata cannot be preserved; other POSIX platforms and
encrypted Windows filesystem files require manual migration.
For later deployment, the Azure app settings must include both
`LOGIC_APPS_CUSTOMCODE_DOTNETVERSION=net10.0` and `FUNCTIONS_INPROC_NET8_ENABLED=1`.
The .NET 8 host flag is still required for .NET 10 custom code. The helper requires
that host flag before migration and preserves it.
Deployment through the Logic Apps extension in VS Code copies these settings to Azure.
If deploying through a pipeline, explicitly include both application settings in its
deployment configuration. A local settings file alone does not configure the Azure app.
Verify the deployed runtime separately. The helper reports these prerequisites and
performs no Azure changes.
The skill preserves library output and does not create `Program.cs`: a library `Main()`
does not run automatically. Source/API compatibility remains a build/runtime check.
Run the bundled standard-library tests:
```powershell
python -m unittest discover -s ".\tests" -v
```
The tests exercise synthetic project configurations and failure behavior, not real
workflow execution or production support. The package baseline comes from inspected
Workflows SDK 1.4.0 targets and Worker 2.51.0 package metadata. The updated 1.4.1 target
still requires restore/build/runtime verification. The announcement above
documents .NET 10 custom-code support; verify the selected local/deployed runtime separately.
## Provenance
Adapted from the MIT-licensed
[custom-code-net10 skill at commit 2ee2905](https://github.com/wsilveiranz/custom-code-net10/tree/2ee2905c84b2589972a354f0006a036420770ce0/skills/logicapps-custom-code-net10-migration).
The helper and initial 30 regression tests came from that revision. This contribution
adds review-driven target matching, publication side-effect and access-control safeguards
with additional regression tests.
SKILL.md 5.2 KB
---
name: logicapps-custom-code-net10-migration
description: 'Migrate Azure Logic Apps Standard local-function custom-code projects from .NET 8 to .NET 10. Use for legacy Logic Apps custom-code workspace upgrades, project/package configuration, custom-worker settings, publication, and integrated VS Code debugging. Not for ordinary .NET applications, standalone Azure Functions, Consumption workflows, or cloud deployment.'
license: MIT
---
# Logic Apps custom code .NET 10 migration
Read [the migration procedure](references/migration.md) before editing. Resolve bundled
files relative to this skill, not the target repository. Python 3.11+ is required only
for the helper; do not install dependencies or start services merely by activating this skill.
## Procedure
1. Establish the solution root, custom-code `.csproj`, and Logic Apps `host.json` root.
Infer existing names/layout; ask only about ambiguous project selection or effects.
Read repository instructions and affected configuration, including dirty changes,
inherited build/package/SDK settings, workspace and tool paths. Do not inspect C#
contents unless separately authorized to diagnose a build failure.
2. Run the bundled helper in its default dry-run mode:
```powershell
python "<skill root>\scripts\migrate.py" --root "<solution root>"
```
Use `--project "<csproj path>"` to select among multiple custom-code projects.
The helper resolves `LogicAppFolderToPublish`; it does not require `Functions`
or `LogicApps` folder names. Read all reported blockers/warnings. It prints no
settings values and writes nothing in dry-run mode.
Default edits cover framework/SDK/publication/runtime alignment, not reference
dependency parity. Preserve absent Worker packages and existing debugger configuration.
Use `--integrated-debug` only when coordinated launching is requested/needed.
3. For a requested migration, apply the reviewed plan with the same coordinates and
`--apply`. Do not apply for a comparison/plan-only request. The helper guards changed
files and rolls back its own completed writes on failure; it is not an atomic
multi-file transaction or a persistent backup. Preserve unrelated user edits.
4. If the helper refuses central/conditional/imported configuration, newer unreviewed
SDK targets, or an unfamiliar debugger/layout, do not bypass the guard. Read the
owning configuration, resolve scope with the user when shared projects are affected,
and make targeted agent edits using repository tools. Never claim universal helper
coverage. Repeat the dry run to check idempotency for supported layouts.
5. Validate with the repository's build/analyzers and approved package source. Use the
exact SDK selected by VS Code, not just PATH. Verify assembly/dependency publication
and generated local-function metadata. Review custom build/publication hooks and
obtain separate authorization for any deployment/network effects before building;
a disposable copy does not neutralize those hooks. Obtain permission for trigger/connector
effects before host startup or workflow execution. Follow the installed Logic Apps
runtime skill/procedure when available; otherwise perform ownership-aware VS Code
launch and verify actual execution, not just debugger attachment.
If the SDK's directory scan fails on a clean build, rerun the helper dry run/apply
with `--ensure-output-directory`, then repeat the failed build. Do not introduce
the guard as a universal framework requirement. Resolve genuine missing-dependency
errors individually; do not add Worker/HTTP/telemetry packages just to match a sample.
6. Report changed configuration, dry-run/apply/tests, and separate states:
configuration migrated, build verified, local-function execution verified.
State blockers plainly. Always report the later deployment prerequisite:
Azure app settings must carry `LOGIC_APPS_CUSTOMCODE_DOTNETVERSION=net10.0` and
`FUNCTIONS_INPROC_NET8_ENABLED=1`. Deployment through the Logic Apps extension
in VS Code copies these settings; pipelines must explicitly include them.
A local settings file alone does not configure Azure. Do not deploy, change
Azure app settings, or assert cloud/production support.
## Invariants
- Only upgrade the custom-code library; preserve host .NET 8 configuration.
- Preserve names, workflows, connections, authentication, storage, unrelated dependencies,
workspace/task conventions, comments and secret exclusions.
- Do not add sample-only HTTP, telemetry or framework references.
- Do not introduce `Program.cs` or an executable worker host. Library `Main()` is
not automatically executed; source preservation is intent, not verified API compatibility.
- No C# rewrites, SDK installation, restore, host start, Azure mutation or persistent
secret backups inside the configuration helper.
- Do not silently downgrade packages, rewrite shared package management, suppress
restore/build errors, copy .NET 10 DLLs to `net472`, or manufacture passing checks.
Installation and test commands are in [README.md](README.md).
Bundled resources include the [migration helper](scripts/migrate.py),
[regression tests](tests/test_migrate.py), and [MIT license](LICENSE).
migration.md 11.5 KB
# Required migration procedure
## Recognize and scope the project
The custom code is an SDK-style **library** with a Workflows SDK package and
`LogicAppFolderToPublish`. The destination contains `host.json` with the
`Microsoft.Azure.Functions.ExtensionBundle.Workflows` bundle and local
`APP_KIND=workflowapp` settings. These checks prevent ordinary .NET/Functions upgrades.
Do not assume that a folder named Functions contains a standalone Function app.
Inspect workspace roots, existing tasks and effective tool settings. Check inherited
`global.json`, `Directory.Build.*`, central package management and imported/conditional
properties before edits. Multiple projects or shared SDK/package files need explicit
selection and impact review. The helper intentionally stops rather than guessing.
The [November 5 announcement](https://techcommunity.microsoft.com/blog/IntegrationsonAzureBlog/logic-apps-standard-custom-code-now-supports-net-10/4570808)
documents .NET 10 custom-code support with VS Code extension 5.1013.2 and Logic Apps
Standard extension bundle 1.194.31. Verify these release prerequisites before migration.
Do not display local settings, payloads or credential-bearing diffs. The helper reports
filenames and change categories, never local setting values. Its temporary writes may
contain local settings; normal completion removes them after replacement rather than
keeping persistent backups. Forced termination can bypass cleanup and leave files named
`.<original filename>.<random>`, including credential-bearing `.local.settings.json.*`.
Before applying, verify source-control and deployment exclusions cover those names;
an exclusion matching only `local.settings.json` is insufficient. Inspect for leftovers
before committing or packaging and remove only confirmed migration-owned files through
the approved secret-handling process, without displaying their contents. Preserve
existing ignore rules; the helper does not add exclusions automatically.
Before any validation build, inspect custom targets, publication dependencies and
repository build tasks for network/deployment effects. The helper refuses to introduce
publish-on-build when custom publication hooks or unresolved hook expressions exist.
It preserves an existing publish-on-build hook but reports custom publication hooks;
preservation is not permission to run them. Review or disable external effects through
a separately authorized change before building, including in a disposable copy.
Replacement writes preserve Windows ownership, group, discretionary ACLs, integrity labels
and ACL inheritance protection, or Linux ownership, mode and access-control extended
attributes. Access restrictions are applied before configuration bytes enter the temporary
file. Unreadable/unwritable access metadata, encrypted Windows filesystem files and other
POSIX platforms block application rather than fall back to mode-only replacement.
## Required configuration alignment
| Configuration | Change |
|---|---|
| `TargetFramework` | `net8`/`net8.0` to `net10.0`; library identity/layout unchanged |
| Workflows SDK | Upgrade to `1.4.1`; review newer targets before adopting |
| Worker SDK | At least reviewed `2.0.7`; preserve already newer stable versions |
| `CopyLocalLockFileAssemblies` | `true` |
| Publish on build | Preserve existing hook; block insertion when custom publication hooks need side-effect review |
| Host `Values.LOGIC_APPS_CUSTOMCODE_DOTNETVERSION` | Exactly `net10.0` |
| Host `Values.FUNCTIONS_INPROC_NET8_ENABLED` | Keep `1`; still required for the host, and a helper prerequisite |
| Functions editor deploy path | Replace only a `net8`/`net8.0` path component |
Versions here are a selected migration baseline, not an independently established universal minimum.
Workflows SDK 1.4.1 replaces the buggy 1.4.0 release. Verify availability from the approved
NuGet feed before applying the migration or restoring. Restore/build/runtime validation
of 1.4.1 is still required.
## Conditional dependencies, build safeguards and debugging
If Worker is already directly referenced, the helper aligns it to reviewed `2.51.0`
while preserving newer stable versions. It does not add a missing Worker reference solely
because the framework changes. Add dependencies only when application/build evidence
requires them; source preservation does not establish compatibility.
Worker Core 2.51.0 depends on Microsoft.Extensions.Hosting 10.0.0. When a direct Worker
reference is selected, the helper raises existing direct Logging/Logging.Abstractions
pins below `10.0.0`, preserving newer versions. Without a direct Worker reference, it
preserves logging pins. Preserve dependencies rather than indiscriminately deleting them.
Other direct framework-family pins can also cause restore conflicts: inspect actual
restore diagnostics and align only affected dependencies. Do not blanket-upgrade packages
with independent versioning, such as Microsoft.Extensions.Azure.
Do not add ApplicationInsights.WorkerService, Http.AspNetCore or an ASP.NET Core framework
reference solely for this migration. Existing application requirements remain intact.
Add this guard **only if a clean build fails because the function-JSON scan directory
is missing**, using helper flag `--ensure-output-directory`. The failure was observed
with Workflows SDK 1.4.0; do not assume 1.4.1 requires the workaround.
```xml
<Target Name="EnsureOutputDirectory" BeforeTargets="DeleteFunctionJsonFoldersTarget">
<MakeDir Directories="$(MSBuildProjectDirectory)\bin\$(Configuration)\$(TargetFramework)"
Condition="!Exists('$(MSBuildProjectDirectory)\bin\$(Configuration)\$(TargetFramework)')" />
</Target>
```
`FindFunctionJsonFolders` is a task, not a target. The helper repairs the known ineffective
hook only when its contents match that narrow workaround; it refuses conflicting custom
targets. Repairing an existing guard preserves its intended safeguard; a missing guard
is not inserted by default. It leaves unrelated custom targets, including dead sample copy targets, alone
and reports misleading `net472` targets for review.
## Preserve host and workspace configuration
Do not alter existing `FUNCTIONS_WORKER_RUNTIME=dotnet`,
`FUNCTIONS_INPROC_NET8_ENABLED=1`, `APP_KIND=workflowapp`, or multi-language worker
settings. Do not add an in-process .NET 10 flag or set the Logic Apps host to
`dotnet-isolated`. Preserve host.json, connections, authentication, workflow definitions,
ignore rules, design-time settings and workspace/task names.
Do not add `Program.cs` or convert the library into a standalone worker host. A `Main()`
method is not automatically executed with `OutputType=Library`. Preserve existing
implementations/workflows unless separately authorized source changes are required by
actual diagnostics; do not promise they compile or execute unchanged before testing.
The helper preserves source project paths and machine-specific Node configuration.
If moving the solution, explicitly update `ProjectDirectoryPath` in runtime and
design-time settings and verify the Node executable. Relocation is not an implicit
side effect of a target-framework migration.
The helper leaves all debugger configuration unchanged by default. If coordinated
workflow/custom-code launching is requested/needed, use `--integrated-debug` in dry run
and apply. This adds a `logicapp` launch entry with both runtimes `coreclr` and
`isCodeless=true`, retaining old attach configurations. An existing integrated entry for
the default `coreclr` host is updated without overwriting unrelated properties; ambiguous
multiple candidates require manual selection. Select that entry for coordinated debugging.
The difference between the compared projects is not a universal .NET 10 requirement.
The Functions deployment path is not the Logic Apps publication path. Shared missing
predeploy tasks need separate review if deployment is requested; no deployment is authorized
by this skill. Preserve `-nodeReuse:false` and managed Node/.NET PATH conventions.
## Verification gates
1. Inspect the **resolved VS Code-selected** .NET and Core Tools executables. Verify SDK
10, .NET 10 runtime, existing .NET 8 host runtime, and any already-required ASP.NET
runtime. Review effective user/workspace/folder tool settings; do not inject literal
environment-variable expressions into settings and assume universal expansion.
2. Restore using an explicit approved NuGet configuration/source. Respect organizational
proxy policy; do not substitute nuget.org, install an SDK or accept new licensing
terms without the applicable authorization. The helper never restores.
3. Run the smallest repository build/analyzer command using that executable. For example:
```powershell
& $dotnet restore $project --configfile $approvedNuGetConfig
if ($LASTEXITCODE -ne 0) { throw 'Restore failed.' }
& $dotnet build $project --configuration Debug --no-restore -nodeReuse:false
if ($LASTEXITCODE -ne 0) { throw 'Build failed.' }
```
Resolve genuine package/API failures; do not suppress warnings, exclude functions or
rewrite C# without separately authorized source changes.
4. Test a clean build in a safe disposable copy. SDK cleanup removes `lib\custom`; do
not clean another active host's output. If the SDK scan directory is missing, review
and apply `--ensure-output-directory`, then repeat the failed build. Do not use this
flag to mask unrelated failures. Confirm `<host>\lib\custom\net10.0` contains
the **original** project assembly/dependencies and generated per-function metadata
is present under `<host>\lib\custom`. Inspect language/library references and function
identities. `Functions\bin` and standalone `functions.metadata` alone are insufficient.
5. Confirm safe local trigger/connection effects before starting the host. Open the
existing multi-root workspace, run the custom-code build task, launch the integrated
debugger if chosen (otherwise preserve a working launch/attach route), and verify
host readiness and function discovery. Execute an appropriate
existing workflow through its supported trigger and inspect actual local-function
results; use original identities and non-sensitive fixtures.
6. Stop only task-owned sessions/services after verification unless asked to retain them.
Report configuration, build and execution evidence separately, including skipped checks.
## Later deployment prerequisite (report only)
For Azure execution, the deployed Logic Apps **application settings** must carry both
`LOGIC_APPS_CUSTOMCODE_DOTNETVERSION=net10.0` and `FUNCTIONS_INPROC_NET8_ENABLED=1`.
The .NET 8 host flag remains required even though the custom code targets .NET 10.
Deployment through the Logic Apps extension in VS Code copies these settings to Azure.
Pipeline deployments must explicitly include both application settings. A local settings
file alone does not configure the Azure app. Report these prerequisites even for
local-only migration, distinguishing them from completed local changes.
Verify that the intended deployed runtime supports .NET 10 custom code separately.
Do not change Azure resources or deployment/IaC settings as a side effect of this skill.
Any such mutation needs a separately scoped and authorized task with target/environment
verification. Generated assemblies and metadata establish neither cloud support nor a
successful local/deployed run.
The helper has no universal package/host support guarantee. Newer Workflows SDK behavior,
other layouts and deployed-host support need current authoritative validation. The
announcement above documents .NET 10 support; package versions remain a reviewed
baseline, and the intended runtime configuration and execution still require verification.
migrate.py 33.8 KB
"""Offline, guarded configuration migration for Logic Apps local-function libraries."""
import argparse
import json
import os
from pathlib import Path
import re
import sys
import tempfile
from xml.dom import Node as XmlNode, minidom
from xml.parsers.expat import ExpatError
class MigrationError(Exception):
pass
class Node:
def __init__(self, value, start, end, depth, children=None, trailing=False):
self.value, self.start, self.end, self.depth = value, start, end, depth
self.children, self.trailing = children, trailing
class Jsonc:
"""Parse JSONC while retaining token positions for minimal text edits."""
token = re.compile(
r'\s+|//[^\r\n]*|/\*[\s\S]*?\*/|"(?:[^"\\\x00-\x1f]|\\.)*"'
r'|[{}\[\]:,]|true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?'
)
def __init__(self, text):
self.text, self.tokens, self.index = text, [], 0
position = 0
while position < len(text):
match = self.token.match(text, position)
if not match:
raise MigrationError("Invalid JSON/JSONC syntax; no settings values logged.")
raw = match.group()
if not raw.isspace() and not raw.startswith(("//", "/*")):
self.tokens.append((raw, match.start(), match.end()))
position = match.end()
self.root = self.parse(0)
if self.index != len(self.tokens):
raise MigrationError("Unexpected trailing JSON/JSONC content.")
def take(self, expected=None):
if self.index >= len(self.tokens):
raise MigrationError("Incomplete JSON/JSONC configuration.")
token = self.tokens[self.index]
self.index += 1
if expected is not None and token[0] != expected:
raise MigrationError("Invalid JSON/JSONC structure.")
return token
def peek(self):
return self.tokens[self.index][0] if self.index < len(self.tokens) else None
def parse(self, depth):
raw, start, end = self.take()
if raw not in ("{", "["):
try:
value = json.loads(raw)
except json.JSONDecodeError as error:
raise MigrationError("Invalid JSON value; content withheld.") from error
return Node(value, start, end, depth)
object_mode = raw == "{"
close = "}" if object_mode else "]"
children = {} if object_mode else []
trailing = False
while self.peek() != close:
key = None
if object_mode:
key_token = self.take()[0]
if not key_token.startswith('"'):
raise MigrationError("JSON object key must be a string.")
key = json.loads(key_token)
if key in children:
raise MigrationError("Duplicate JSON keys require manual review.")
self.take(":")
child = self.parse(depth + 1)
if object_mode:
children[key] = child
else:
children.append(child)
if self.peek() == close:
break
self.take(",")
trailing = self.peek() == close
_, _, end = self.take(close)
value = ({key: child.value for key, child in children.items()} if object_mode
else [child.value for child in children])
return Node(value, start, end, depth, children, trailing)
def locate(self, path):
node = self.root
for key in path:
if isinstance(node.children, dict) and key in node.children:
node = node.children[key]
elif (isinstance(node.children, list) and isinstance(key, int)
and 0 <= key < len(node.children)):
node = node.children[key]
else:
return None
return node
def set(self, path, value):
node = self.locate(path)
if node is not None:
if node.value == value:
return self.text
return self.text[:node.start] + json.dumps(value) + self.text[node.end:]
parent = self.locate(path[:-1])
if parent is None or not isinstance(parent.children, dict):
raise MigrationError("Missing/non-object settings container requires manual review.")
return self.append(parent, value, path[-1])
def append(self, node, value, key=None):
if key is None and not isinstance(node.children, list):
raise MigrationError("Debugger configurations must be an array.")
newline = "\r\n" if "\r\n" in self.text else "\n"
unit_match = re.search(r'(?m)^([ \t]+)"', self.text)
unit = unit_match.group(1) if unit_match else " "
indent, closing_indent = unit * (node.depth + 1), unit * node.depth
encoded = json.dumps(value, indent=len(unit), ensure_ascii=False)
encoded = encoded.replace("\n", newline + indent)
member = (json.dumps(key) + ": " if key is not None else "") + encoded
close = node.end - 1
line_start = self.text.rfind("\n", 0, close) + 1
if not self.text[line_start:close].strip():
position, addition = line_start, indent + member + newline
else:
position, addition = close, newline + indent + member + newline + closing_indent
edits = []
children = list(node.children.values()) if isinstance(node.children, dict) else node.children
if children and not node.trailing:
comma_position = children[-1].end
if comma_position == position:
addition = "," + addition
else:
edits.append((comma_position, comma_position, ","))
edits.append((position, position, addition))
result = self.text
for start, end, replacement in sorted(edits, reverse=True):
result = result[:start] + replacement + result[end:]
Jsonc(result)
return result
def elements(parent, name, *, case_insensitive=False):
return [node for node in parent.getElementsByTagName("*")
if node.localName == name
or (case_insensitive and node.localName.lower() == name.lower())]
def xml_value(node):
if any(child.nodeType == XmlNode.ELEMENT_NODE for child in node.childNodes):
raise MigrationError("Nested XML value requires manual review.")
return "".join(child.data for child in node.childNodes if child.nodeType == XmlNode.TEXT_NODE).strip()
def unconditional(node):
current = node
while current.nodeType == XmlNode.ELEMENT_NODE:
if current.hasAttribute("Condition"):
raise MigrationError("Conditional project configuration requires manual review.")
current = current.parentNode
def stable_version(value):
if not re.fullmatch(r"\d+\.\d+\.\d+", value):
raise MigrationError("Package expressions/ranges/prereleases require manual review.")
return tuple(map(int, value.split(".")))
def project_xml(text):
if "<!DOCTYPE" in text.upper():
raise MigrationError("XML DTDs are not supported.")
try:
document = minidom.parseString(text)
except ExpatError as error:
raise MigrationError("Invalid project XML.") from error
return document
def update_project(text, notes, ensure_output_directory=False):
document = project_xml(text)
root = document.documentElement
if root.localName != "Project" or root.getAttribute("Sdk") != "Microsoft.NET.Sdk":
raise MigrationError("Expected an SDK-style Microsoft.NET.Sdk library.")
if (elements(root, "Import") or elements(root, "TargetFrameworks", case_insensitive=True)
or elements(root, "ManagePackageVersionsCentrally", case_insensitive=True)):
raise MigrationError("Imported, multi-targeted or centrally managed projects require manual review.")
newline = "\r\n" if "\r\n" in text else "\n"
def new_element(name):
return document.createElementNS(root.namespaceURI, name)
def add(parent, node, depth):
last = parent.lastChild
if last is not None and last.nodeType == XmlNode.TEXT_NODE and not last.data.strip():
parent.insertBefore(document.createTextNode(newline + " " * depth), last)
parent.insertBefore(node, last)
else:
parent.appendChild(document.createTextNode(newline + " " * depth))
parent.appendChild(node)
parent.appendChild(document.createTextNode(newline + " " * (depth - 1)))
return node
def group(name):
groups = [node for node in elements(root, name)
if node.parentNode == root and not node.hasAttribute("Condition")]
return groups[0] if groups else add(root, new_element(name), 1)
def property_node(name, required=False):
nodes = elements(root, name, case_insensitive=True)
if len(nodes) > 1 or (required and not nodes):
raise MigrationError(f"Expected one direct {name} property.")
if nodes:
node = nodes[0]
unconditional(node)
if node.parentNode.localName != "PropertyGroup" or node.parentNode.parentNode != root:
raise MigrationError(f"{name} is not a direct project property.")
return node
return add(group("PropertyGroup"), new_element(name), 2)
def set_text(node, value):
for child in list(node.childNodes):
node.removeChild(child)
node.appendChild(document.createTextNode(value))
framework = property_node("TargetFramework", True)
if xml_value(framework) not in ("net8", "net8.0", "net10.0"):
raise MigrationError("Only .NET 8 local-function libraries (or reruns on net10.0) are supported.")
if xml_value(property_node("OutputType", True)).lower() != "library":
raise MigrationError("Custom code must remain a library.")
if xml_value(property_node("AzureFunctionsVersion", True)) != "v4":
raise MigrationError("Expected the existing Functions v4 project contract.")
property_node("LogicAppFolderToPublish", True)
set_text(framework, "net10.0")
set_text(property_node("CopyLocalLockFileAssemblies"), "true")
def package(name, version, required=False, exact=False):
refs = [node for node in elements(root, "PackageReference")
if node.getAttribute("Include").lower() == name.lower()
or node.getAttribute("Update").lower() == name.lower()]
if len(refs) > 1 or (required and not refs):
raise MigrationError(f"Expected one direct {name} PackageReference.")
if refs:
node = refs[0]
unconditional(node)
if node.parentNode.localName != "ItemGroup" or node.parentNode.parentNode != root:
raise MigrationError(f"{name} is not a direct package reference.")
version_attributes = [attribute for attribute in node.attributes.keys()
if attribute.lower() in ("version", "versionoverride")]
if (not node.hasAttribute("Include") or version_attributes != ["Version"]
or any(child.nodeType == XmlNode.ELEMENT_NODE
and child.localName.lower() in ("version", "versionoverride")
for child in node.childNodes)):
raise MigrationError(f"Central/child-element version for {name} needs manual review.")
current = stable_version(node.getAttribute("Version"))
baseline = stable_version(version)
if exact and current > baseline:
raise MigrationError("Newer Workflows SDK targets require review; refusing to downgrade.")
if current >= baseline:
return
else:
node = new_element("PackageReference")
node.setAttribute("Include", name)
add(group("ItemGroup"), node, 2)
node.setAttribute("Version", version)
package("Microsoft.Azure.Workflows.Webjobs.Sdk", "1.4.1", True, True)
package("Microsoft.Azure.Functions.Worker.Sdk", "2.0.7", True)
has_worker = any(
node.getAttribute(attribute).lower() == "microsoft.azure.functions.worker"
for node in elements(root, "PackageReference") for attribute in ("Include", "Update")
)
if has_worker:
package("Microsoft.Azure.Functions.Worker", "2.51.0")
for name in ("Microsoft.Extensions.Logging", "Microsoft.Extensions.Logging.Abstractions"):
if any(node.getAttribute(attribute).lower() == name.lower()
for node in elements(root, "PackageReference") for attribute in ("Include", "Update")):
package(name, "10.0.0")
else:
notes.append("No direct Worker dependency: preserve existing packages; add Worker only if required "
"by the application and resolve actual restore conflicts.")
targets = elements(root, "Target")
guards = [node for node in targets
if node.getAttribute("Name").lower() == "ensureoutputdirectory"]
if len(guards) > 1:
raise MigrationError("Duplicate output-directory targets require manual review.")
directory = r"$(MSBuildProjectDirectory)\bin\$(Configuration)\$(TargetFramework)"
if guards:
guard = guards[0]
unconditional(guard)
child_elements = [node for node in guard.childNodes if node.nodeType == XmlNode.ELEMENT_NODE]
allowed = {"$(OutputPath)", directory}
if (guard.getAttribute("BeforeTargets") not in
("FindFunctionJsonFolders", "DeleteFunctionJsonFoldersTarget")
or set(guard.attributes.keys()) != {"Name", "BeforeTargets"}
or len(child_elements) != 1 or child_elements[0].localName != "MakeDir"):
raise MigrationError("Custom EnsureOutputDirectory target requires manual review.")
mkdir = child_elements[0]
if (set(mkdir.attributes.keys()) != {"Directories", "Condition"}
or mkdir.getAttribute("Directories") not in allowed
or mkdir.getAttribute("Condition") !=
f"!Exists('{mkdir.getAttribute('Directories')}')"):
raise MigrationError("Custom MakeDir workaround requires manual review.")
elif ensure_output_directory:
guard = new_element("Target")
guard.setAttribute("Name", "EnsureOutputDirectory")
add(root, guard, 1)
mkdir = add(guard, new_element("MakeDir"), 2)
else:
notes.append("Clean-build directory guard not added: use --ensure-output-directory if the SDK "
"fails because its function-JSON scan directory is missing.")
if guards or ensure_output_directory:
guard.setAttribute("BeforeTargets", "DeleteFunctionJsonFoldersTarget")
mkdir.setAttribute("Directories", directory)
mkdir.setAttribute("Condition", f"!Exists('{directory}')")
publish_hooks = [node for node in targets
if any(token.strip().lower() == "build"
for token in node.getAttribute("AfterTargets").split(";"))
and any(token.strip().lower() == "publish"
for call in elements(node, "CallTarget")
for token in call.getAttribute("Targets").split(";"))]
custom_publication = any(
node.getAttribute("Name").lower() in {"publish", "beforepublish", "afterpublish"}
or any("publish" in token.strip().lower() or "$(" in token
for attribute in ("BeforeTargets", "AfterTargets", "DependsOnTargets")
for token in node.getAttribute(attribute).split(";"))
for node in targets
) or any(node.localName.lower().startswith("publish")
and node.localName.lower().endswith("dependson")
for node in root.getElementsByTagName("*")
if node.parentNode.localName == "PropertyGroup")
if custom_publication:
if not publish_hooks:
raise MigrationError("Custom publication hooks require side-effect review before "
"adding publish-on-build; no build or deployment is authorized.")
notes.append("Review custom publication hooks before any build; existing publish-on-build "
"is preserved, not authorization for deployment or other external effects.")
if not publish_hooks:
if any(node.getAttribute("Name").lower() == "triggerpublishonbuild" for node in targets):
raise MigrationError("Conflicting publish-on-build target requires manual review.")
hook = new_element("Target")
hook.setAttribute("Name", "TriggerPublishOnBuild")
hook.setAttribute("AfterTargets", "Build")
add(root, hook, 1)
call = add(hook, new_element("CallTarget"), 2)
call.setAttribute("Targets", "Publish")
elif len(publish_hooks) != 1:
raise MigrationError("Multiple publish-on-build hooks require manual review.")
else:
unconditional(publish_hooks[0])
for call in elements(publish_hooks[0], "CallTarget"):
unconditional(call)
if any("net472" in node.getAttribute("Name").lower() for node in targets):
notes.append("Review existing net472 copy targets; none are introduced or removed.")
result = document.toxml()
if not text.lstrip().startswith("<?xml"):
result = result[result.index("?>") + 2:]
result = result.replace("\r\n", "\n").replace("\n", newline)
if text.endswith(("\n", "\r")):
result += newline
return result
class Plan:
def __init__(self, root):
self.root, self.originals, self.changes, self.notes = root, {}, {}, []
def checked(self, path):
path = Path(path)
if path.is_symlink() or not path.resolve().is_relative_to(self.root):
raise MigrationError("Configuration path escapes the solution or is a symlink.")
return path.resolve()
def read(self, path, default=None):
path = self.checked(path)
if path not in self.originals:
self.originals[path] = path.read_bytes() if path.exists() else None
data = self.originals[path]
if data is None:
if default is None:
raise MigrationError(f"Required configuration is missing: {path.name}")
return default
try:
return data.decode("utf-8-sig")
except UnicodeDecodeError as error:
raise MigrationError("Only UTF-8 configuration is supported.") from error
def change(self, path, text, category):
path = self.checked(path)
original = self.originals[path]
bom = b"\xef\xbb\xbf" if original and original.startswith(b"\xef\xbb\xbf") else b""
data = bom + text.encode("utf-8")
if data != original:
self.changes[path] = (data, category)
def verify(self, path):
current = path.read_bytes() if path.exists() else None
if current != self.originals[path]:
raise MigrationError("Configuration changed after planning; refusing to overwrite.")
@staticmethod
def copy_access(path, temporary):
original = path.stat()
if sys.platform == "win32":
if original.st_file_attributes & 0x4000:
raise MigrationError("Encrypted filesystem configuration requires manual review.")
import ctypes
from ctypes import wintypes
api = ctypes.WinDLL("advapi32", use_last_error=True)
api.GetFileSecurityW.argtypes = (
wintypes.LPCWSTR, wintypes.DWORD, wintypes.LPVOID, wintypes.DWORD,
ctypes.POINTER(wintypes.DWORD))
api.GetFileSecurityW.restype = wintypes.BOOL
api.SetFileSecurityW.argtypes = (wintypes.LPCWSTR, wintypes.DWORD, wintypes.LPVOID)
api.SetFileSecurityW.restype = wintypes.BOOL
api.GetSecurityDescriptorControl.argtypes = (
wintypes.LPVOID, ctypes.POINTER(wintypes.WORD), ctypes.POINTER(wintypes.DWORD))
api.GetSecurityDescriptorControl.restype = wintypes.BOOL
# Owner, group, DACL and integrity label; never weaken inheritance protection.
information = 0x17
size = wintypes.DWORD()
api.GetFileSecurityW(str(path), information, None, 0, ctypes.byref(size))
if ctypes.get_last_error() != 122 or not size.value:
raise ctypes.WinError(ctypes.get_last_error())
security = ctypes.create_string_buffer(size.value)
if not api.GetFileSecurityW(str(path), information, security, size.value,
ctypes.byref(size)):
raise ctypes.WinError(ctypes.get_last_error())
control, revision = wintypes.WORD(), wintypes.DWORD()
if not api.GetSecurityDescriptorControl(security, ctypes.byref(control),
ctypes.byref(revision)):
raise ctypes.WinError(ctypes.get_last_error())
protection = 0x80000000 if control.value & 0x1000 else 0x20000000
if not api.SetFileSecurityW(str(temporary), information | protection, security):
raise ctypes.WinError(ctypes.get_last_error())
elif sys.platform == "linux":
current = os.stat(temporary)
if (current.st_uid, current.st_gid) != (original.st_uid, original.st_gid):
os.chown(temporary, original.st_uid, original.st_gid)
attributes = os.listxattr(path)
if ("system.posix_acl_access" not in attributes
and "system.posix_acl_access" in os.listxattr(temporary)):
os.removexattr(temporary, "system.posix_acl_access")
for attribute in attributes:
os.setxattr(temporary, attribute, os.getxattr(path, attribute))
else:
raise MigrationError("Access-control preservation is supported only on Windows and Linux; "
"this platform requires manual migration.")
os.chmod(temporary, original.st_mode)
@staticmethod
def write(path, data):
descriptor, temporary = tempfile.mkstemp(prefix="." + path.name + ".", dir=path.parent)
try:
with os.fdopen(descriptor, "wb") as stream:
if path.exists():
Plan.copy_access(path, temporary)
else:
os.chmod(temporary, 0o600)
stream.write(data)
os.replace(temporary, path)
finally:
if os.path.exists(temporary):
os.unlink(temporary)
def apply(self):
for path in self.originals:
self.verify(path)
written, directories = [], []
try:
for path, (data, _) in self.changes.items():
self.verify(path)
if not path.parent.exists():
path.parent.mkdir()
directories.append(path.parent)
self.write(path, data)
written.append(path)
except (OSError, MigrationError) as error:
rollback_errors = []
for path in reversed(written):
try:
if path.read_bytes() != self.changes[path][0]:
raise MigrationError("Concurrent edit prevents rollback.")
original = self.originals[path]
if original is None:
path.unlink()
else:
self.write(path, original)
except (OSError, MigrationError):
rollback_errors.append(path.name)
for directory in reversed(directories):
try:
directory.rmdir()
except OSError:
rollback_errors.append(directory.name)
detail = " Rollback incomplete: " + ", ".join(rollback_errors) if rollback_errors else ""
raise MigrationError(f"Apply failed: {error}; own writes rolled back where safe."
+ detail) from error
def update_launch(launch, host_name):
version = Jsonc(launch).locate(("version",))
if version is not None and version.value != "0.2.0":
raise MigrationError("Unfamiliar debugger schema version requires manual review.")
launch = Jsonc(launch).set(("version",), "0.2.0")
configurations = Jsonc(launch).locate(("configurations",))
if configurations is None or not isinstance(configurations.value, list):
raise MigrationError("Expected a debugger configurations array.")
if not all(isinstance(config, dict) for config in configurations.value):
raise MigrationError("Debugger entries must be objects.")
candidates = [index for index, config in enumerate(configurations.value)
if config.get("type") == "logicapp" and config.get("request") == "launch"
and config.get("funcRuntime", "coreclr") == "coreclr"]
if len(candidates) > 1:
raise MigrationError("Multiple integrated debugger entries require manual selection.")
fields = {"type": "logicapp", "request": "launch", "funcRuntime": "coreclr",
"customCodeRuntime": "coreclr", "isCodeless": True}
if candidates:
index = candidates[0]
config = configurations.value[index]
if config.get("customCodeRuntime", "coreclr") != "coreclr":
raise MigrationError("Mixed custom-code debugger runtimes require manual review.")
for key, value in fields.items():
launch = Jsonc(launch).set(("configurations", index, key), value)
else:
name = f"Run/Debug logic app with local function {host_name}"
if any(config.get("name") == name or config.get("type") == "logicapp"
for config in configurations.value):
raise MigrationError("Conflicting integrated debugger configuration requires manual review.")
launch = Jsonc(launch).append(configurations, {"name": name, **fields})
Jsonc(launch)
return launch
def make_plan(root, selected=None, *, ensure_output_directory=False, integrated_debug=False):
root = Path(root).resolve()
if not root.is_dir():
raise MigrationError("Solution root is not a directory.")
plan = Plan(root)
if selected:
project = plan.checked(Path(selected) if Path(selected).is_absolute() else root / selected)
if project.suffix != ".csproj":
raise MigrationError("--project must select a .csproj file.")
else:
candidates = []
for directory, subdirs, files in os.walk(root):
subdirs[:] = [name for name in subdirs if name not in
(".git", ".azurelogicapps", "bin", "obj", "node_modules", "skills")]
for filename in files:
if filename.endswith(".csproj"):
path = Path(directory) / filename
doc = project_xml(plan.read(path))
if any(node.getAttribute("Include").lower() == "microsoft.azure.workflows.webjobs.sdk"
for node in elements(doc.documentElement, "PackageReference")):
candidates.append(path)
if len(candidates) != 1:
raise MigrationError("Select exactly one Logic Apps custom-code project with --project.")
project = candidates[0]
for directory in (project.parent, *project.parent.parents):
for filename in ("Directory.Build.props", "Directory.Build.targets", "Directory.Packages.props",
"global.json"):
if (directory / filename).exists():
raise MigrationError(f"Inherited {filename} requires manual scope/toolchain review.")
text = plan.read(project)
doc = project_xml(text)
destinations = elements(doc.documentElement, "LogicAppFolderToPublish", case_insensitive=True)
if len(destinations) != 1:
raise MigrationError("Expected one LogicAppFolderToPublish destination.")
destination = xml_value(destinations[0]).replace("$(MSBuildProjectDirectory)", str(project.parent))
if "$(" in destination or "%(" in destination:
raise MigrationError("Computed publication destination requires MSBuild/agent review.")
destination_path = Path(destination.replace("\\", os.sep).replace("/", os.sep))
host = plan.checked(destination_path if destination_path.is_absolute()
else project.parent / destination_path)
host_json = Jsonc(plan.read(host / "host.json")).root.value
if (not isinstance(host_json, dict) or not isinstance(host_json.get("extensionBundle"), dict)
or host_json["extensionBundle"].get("id") !=
"Microsoft.Azure.Functions.ExtensionBundle.Workflows"):
raise MigrationError("Destination is not a recognized Logic Apps Standard host.")
settings_path = host / "local.settings.json"
settings = plan.read(settings_path)
values = Jsonc(settings).root.value
if not isinstance(values, dict) or values.get("IsEncrypted", False) is not False:
raise MigrationError("Encrypted/non-object local settings require manual review.")
settings_values = values.get("Values")
if (not isinstance(settings_values, dict) or settings_values.get("APP_KIND") != "workflowapp"
or settings_values.get("FUNCTIONS_WORKER_RUNTIME") != "dotnet"
or settings_values.get("FUNCTIONS_INPROC_NET8_ENABLED") != "1"):
raise MigrationError("Unfamiliar Logic Apps host settings require manual review.")
configured_path = settings_values.get("ProjectDirectoryPath")
if configured_path is not None and not isinstance(configured_path, str):
raise MigrationError("ProjectDirectoryPath must be a string.")
if configured_path and Path(configured_path).resolve() != host:
raise MigrationError("Stale ProjectDirectoryPath: review relocation before migration.")
settings = Jsonc(settings).set(("Values", "LOGIC_APPS_CUSTOMCODE_DOTNETVERSION"), "net10.0")
plan.change(settings_path, settings, "custom-code runtime selector")
plan.change(project, update_project(text, plan.notes, ensure_output_directory),
"framework, applicable packages and publication")
editor_path = project.parent / ".vscode" / "settings.json"
editor = plan.read(editor_path, "{}\n")
deploy = Jsonc(editor).locate(("azureFunctions.deploySubpath",))
if deploy is not None:
if not isinstance(deploy.value, str):
raise MigrationError("Functions deployment path must be a string.")
updated = re.sub(r"(?i)(^|[/\\])net8(?:\.0)?(?=[/\\]|$)",
lambda match: match.group(1) + "net10.0", deploy.value)
if updated == deploy.value and not re.search(r"(^|[/\\])net10\.0([/\\]|$)", updated):
plan.notes.append("No recognized net8/net8.0 or net10.0 deployment-path component; "
"inspect custom deployment tasks.")
editor = Jsonc(editor).set(("azureFunctions.deploySubpath",), updated)
else:
plan.notes.append("No Functions deployment path specified; local publication is controlled by MSBuild.")
if plan.originals[plan.checked(editor_path)] is not None:
plan.change(editor_path, editor, "Functions deployment path")
launch_path = host / ".vscode" / "launch.json"
launch = plan.read(launch_path, '{"version": "0.2.0", "configurations": []}\n')
Jsonc(launch)
if integrated_debug:
plan.change(launch_path, update_launch(launch, host.name), "integrated Logic Apps debugger")
else:
plan.notes.append("Debugger configuration preserved; use --integrated-debug only when coordinated "
"workflow/custom-code launching is required.")
if not list(root.glob("*.code-workspace")):
plan.notes.append("No root workspace found; review/create a workspace containing both existing projects.")
for task_root in (project.parent, host):
if not (task_root / ".vscode" / "tasks.json").exists():
plan.notes.append(f"Missing tasks.json in {task_root.name}; review VS Code build/host tasks.")
plan.notes.append("Toolchain, restore/build, publication and runtime execution still require verification.")
plan.notes.append("Cloud prerequisite (not applied): deployed app settings must set "
"LOGIC_APPS_CUSTOMCODE_DOTNETVERSION=net10.0 and FUNCTIONS_INPROC_NET8_ENABLED=1. "
"Logic Apps VS Code deployment copies these settings; pipelines must include both. "
"A local.settings.json file alone does not configure Azure. "
"Verify deployed runtime support separately; Azure changes require authorization.")
return plan
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--root", required=True, help="Existing solution root")
parser.add_argument("--project", help="Explicit custom-code .csproj (root-relative or absolute)")
parser.add_argument("--ensure-output-directory", action="store_true",
help="Opt in to the SDK missing-directory clean-build workaround")
parser.add_argument("--integrated-debug", action="store_true",
help="Opt in to coordinated Logic Apps/custom-code launch configuration")
parser.add_argument("--apply", action="store_true", help="Apply configuration changes; default is dry run")
args = parser.parse_args()
try:
plan = make_plan(args.root, args.project, ensure_output_directory=args.ensure_output_directory,
integrated_debug=args.integrated_debug)
print("APPLY" if args.apply else "DRY RUN (no writes)")
for path, (_, category) in plan.changes.items():
print(f" {path.relative_to(plan.root)}: {category}")
for note in plan.notes:
print("REVIEW: " + note)
if args.apply:
plan.apply()
print(f"{len(plan.changes)} configuration file(s) {'updated' if args.apply else 'would change'}.")
return 0
except (MigrationError, OSError, ValueError) as error:
# Do not expose configuration content through parser/OS exception messages.
message = str(error) if isinstance(error, MigrationError) else type(error).__name__
print("BLOCKED: " + message, file=sys.stderr)
return 1
if __name__ == "__main__":
sys.exit(main())
test_migrate.py 36.5 KB
import importlib.util
import json
import os
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
SCRIPT = Path(__file__).resolve().parents[1] / "scripts" / "migrate.py"
SPEC = importlib.util.spec_from_file_location("migration", SCRIPT)
migration = importlib.util.module_from_spec(SPEC)
SPEC.loader.exec_module(migration)
PROJECT = """<Project Sdk="Microsoft.NET.Sdk">
<!-- preserve project intent -->
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<OutputType>Library</OutputType>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
<LogicAppFolderToPublish>$(MSBuildProjectDirectory)\\..\\WorkflowHost</LogicAppFolderToPublish>
<AssemblyName>Original.Identity</AssemblyName>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Workflows.Webjobs.Sdk" Version="1.2.0" />
<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" Version="1.15.1" />
<PackageReference Include="Microsoft.Extensions.Logging" Version="6.0.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="6.0.0" />
<PackageReference Include="Unrelated.Library" Version="3.4.5" />
</ItemGroup>
</Project>
"""
class MigrationTests(unittest.TestCase):
def setUp(self):
self.temporary = tempfile.TemporaryDirectory(prefix="logicapps-net10-test-")
self.addCleanup(self.temporary.cleanup)
self.root = Path(self.temporary.name)
self.project = self.root / "CodeLibrary" / "BusinessRules.csproj"
self.host = self.root / "WorkflowHost"
self.write(self.project, PROJECT)
self.write(self.host / "host.json", json.dumps({
"version": "2.0",
"extensionBundle": {"id": "Microsoft.Azure.Functions.ExtensionBundle.Workflows",
"version": "[1.*, 2.0.0)"},
}))
settings = {
"IsEncrypted": False,
"Values": {"APP_KIND": "workflowapp", "FUNCTIONS_WORKER_RUNTIME": "dotnet",
"FUNCTIONS_INPROC_NET8_ENABLED": "1",
"AzureWebJobsFeatureFlags": "EnableMultiLanguageWorker",
"ProjectDirectoryPath": str(self.host),
"AzureWebJobsStorage": "SENSITIVE-TEST-SENTINEL",
"LOGIC_APPS_CUSTOMCODE_DOTNETVERSION": "net8"},
}
self.write(self.host / "local.settings.json", json.dumps(settings, indent=2))
self.write(self.project.parent / ".vscode" / "settings.json",
'{\n // keep editor comment\n "azureFunctions.deploySubpath": '
'"out/Release/net8.0/publish",\n "unrelated": true,\n}\n')
self.write(self.host / ".vscode" / "launch.json", """{
"version": "0.2.0",
"configurations": [
// keep existing debugger
{"name": "Original attach", "type": "coreclr", "request": "attach"},
],
}
""")
self.write(self.root / "Solution.code-workspace", '{"folders": []}')
self.write(self.project.parent / "Untouched.cs", "// synthetic source: never edit\n")
for parent in (self.project.parent, self.host):
self.write(parent / ".vscode" / "tasks.json", '{"tasks": []}')
@staticmethod
def write(path, text):
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(text.encode("utf-8"))
def snapshot(self):
return {path.relative_to(self.root): path.read_bytes()
for path in self.root.rglob("*") if path.is_file()}
def run_cli(self, *args):
return subprocess.run([sys.executable, str(SCRIPT), "--root", str(self.root), *args],
capture_output=True, text=True, check=False)
def assert_blocked_unchanged(self, *args):
before = self.snapshot()
result = self.run_cli("--apply", *args)
self.assertEqual(result.returncode, 1, result.stdout)
self.assertIn("BLOCKED:", result.stderr)
self.assertEqual(before, self.snapshot())
self.assertNotIn("SENSITIVE-TEST-SENTINEL", result.stdout + result.stderr)
def test_dry_run_is_read_only_and_does_not_log_settings(self):
before = self.snapshot()
result = self.run_cli()
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("DRY RUN", result.stdout)
self.assertNotIn("SENSITIVE-TEST-SENTINEL", result.stdout)
self.assertIn("Cloud prerequisite (not applied)", result.stdout)
self.assertIn("LOGIC_APPS_CUSTOMCODE_DOTNETVERSION=net10.0", result.stdout)
self.assertEqual(before, self.snapshot())
def test_apply_generic_layout_preserves_identity_and_unrelated_files(self):
before = self.snapshot()
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
after = self.snapshot()
changed = {name for name in before if before[name] != after[name]}
self.assertEqual(changed, {
self.project.relative_to(self.root),
(self.host / "local.settings.json").relative_to(self.root),
(self.project.parent / ".vscode" / "settings.json").relative_to(self.root),
})
xml = self.project.read_text()
for expected in ("<TargetFramework>net10.0</TargetFramework>", "Original.Identity",
"Unrelated.Library", "preserve project intent",
'Version="1.4.1"', 'Version="2.0.7"', 'Version="6.0.0"'):
self.assertIn(expected, xml)
for optional in ("ApplicationInsights", "Http.AspNetCore", "FrameworkReference",
'Include="Microsoft.Azure.Functions.Worker"', "EnsureOutputDirectory"):
self.assertNotIn(optional, xml)
values = json.loads((self.host / "local.settings.json").read_text())["Values"]
self.assertEqual(values["LOGIC_APPS_CUSTOMCODE_DOTNETVERSION"], "net10.0")
self.assertEqual(values["FUNCTIONS_INPROC_NET8_ENABLED"], "1")
self.assertEqual(values["AzureWebJobsStorage"], "SENSITIVE-TEST-SENTINEL")
editor = (self.project.parent / ".vscode" / "settings.json").read_text()
self.assertIn("// keep editor comment", editor)
self.assertIn("out/Release/net10.0/publish", editor)
launch = (self.host / ".vscode" / "launch.json").read_text()
self.assertIn("// keep existing debugger", launch)
configs = migration.Jsonc(launch).root.value["configurations"]
self.assertEqual(configs[0]["name"], "Original attach")
self.assertEqual(len(configs), 1)
def test_workflows_sdk_migrates_to_fixed_version_and_is_idempotent(self):
for version in ("1.2.0", "1.3.0", "1.4.0", "1.4.1"):
with self.subTest(version=version):
self.write(self.project, PROJECT.replace('Version="1.2.0"', f'Version="{version}"'))
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
root = migration.project_xml(self.project.read_text()).documentElement
sdk = next(node for node in migration.elements(root, "PackageReference")
if node.getAttribute("Include") == "Microsoft.Azure.Workflows.Webjobs.Sdk")
self.assertEqual(sdk.getAttribute("Version"), "1.4.1")
before = self.snapshot()
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(before, self.snapshot())
def test_rerun_is_idempotent(self):
self.assertEqual(self.run_cli("--apply").returncode, 0)
before = self.snapshot()
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("0 configuration file(s) updated", result.stdout)
self.assertEqual(before, self.snapshot())
def test_existing_integrated_launcher_preserves_internal_comments(self):
launch = self.host / ".vscode" / "launch.json"
self.write(launch, """{
"configurations": [{
// keep integrated comment
"name": "My launcher",
"type": "logicapp",
"request": "launch",
"funcRuntime": "coreclr",
"customCodeRuntime": "coreclr",
"customProperty": true,
}],
}
""")
result = self.run_cli("--integrated-debug", "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
text = launch.read_text()
self.assertIn("// keep integrated comment", text)
self.assertEqual(migration.Jsonc(text).root.value["configurations"][0]["customProperty"], True)
def test_bom_crlf_and_missing_runtime_selector_are_preserved(self):
settings = self.host / "local.settings.json"
value = json.loads(settings.read_text())
del value["Values"]["LOGIC_APPS_CUSTOMCODE_DOTNETVERSION"]
settings.write_bytes(b"\xef\xbb\xbf" + json.dumps(value, indent=2).replace("\n", "\r\n").encode())
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
data = settings.read_bytes()
self.assertTrue(data.startswith(b"\xef\xbb\xbf"))
self.assertNotIn(b"\n", data.replace(b"\r\n", b""))
self.assertEqual(migration.Jsonc(data.decode("utf-8-sig")).root.value["Values"]
["LOGIC_APPS_CUSTOMCODE_DOTNETVERSION"], "net10.0")
def test_compact_settings_insert_missing_runtime_selector(self):
path = self.host / "local.settings.json"
expected = json.loads(path.read_text())
del expected["Values"]["LOGIC_APPS_CUSTOMCODE_DOTNETVERSION"]
self.write(path, json.dumps(expected, separators=(",", ":")))
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
expected["Values"]["LOGIC_APPS_CUSTOMCODE_DOTNETVERSION"] = "net10.0"
self.assertEqual(json.loads(path.read_text()), expected)
before = self.snapshot()
self.assertEqual(self.run_cli("--apply").returncode, 0)
self.assertEqual(before, self.snapshot())
def test_compact_launch_appends_integrated_debugger(self):
path = self.host / ".vscode" / "launch.json"
original = {"name": "Original attach", "type": "coreclr", "request": "attach"}
self.write(path, json.dumps({"version": "0.2.0", "configurations": [original]},
separators=(",", ":")))
result = self.run_cli("--integrated-debug", "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
launch = json.loads(path.read_text())
self.assertEqual(launch["version"], "0.2.0")
self.assertEqual(len(launch["configurations"]), 2)
self.assertEqual(launch["configurations"][0], original)
integrated = launch["configurations"][1]
for key, value in (("type", "logicapp"), ("request", "launch"),
("funcRuntime", "coreclr"), ("customCodeRuntime", "coreclr"),
("isCodeless", True)):
self.assertEqual(integrated[key], value)
before = self.snapshot()
self.assertEqual(self.run_cli("--integrated-debug", "--apply").returncode, 0)
self.assertEqual(before, self.snapshot())
def test_project_crlf_is_preserved(self):
self.project.write_bytes(PROJECT.replace("\n", "\r\n").encode())
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
data = self.project.read_bytes()
self.assertNotIn(b"\n", data.replace(b"\r\n", b""))
def test_missing_editor_files_do_not_create_empty_settings(self):
editor = self.project.parent / ".vscode" / "settings.json"
launch = self.host / ".vscode" / "launch.json"
editor.unlink()
launch.unlink()
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertFalse(editor.exists())
self.assertFalse(launch.exists())
result = self.run_cli("--integrated-debug", "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(json.loads(launch.read_text())["version"], "0.2.0")
def test_integrated_debug_option_is_independent_of_build_guard(self):
result = self.run_cli("--integrated-debug", "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
configs = migration.Jsonc((self.host / ".vscode" / "launch.json").read_text()).root.value[
"configurations"]
self.assertEqual(configs[0]["name"], "Original attach")
self.assertEqual(configs[1]["type"], "logicapp")
self.assertEqual(configs[1]["customCodeRuntime"], "coreclr")
self.assertNotIn("EnsureOutputDirectory", self.project.read_text())
def test_clean_build_guard_option_preserves_debugger_and_dependencies(self):
launch = self.host / ".vscode" / "launch.json"
original_launch = launch.read_bytes()
result = self.run_cli("--ensure-output-directory", "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
xml = self.project.read_text()
self.assertIn('BeforeTargets="DeleteFunctionJsonFoldersTarget"', xml)
self.assertIn('Directories="$(MSBuildProjectDirectory)\\bin\\$(Configuration)\\$(TargetFramework)"',
xml)
self.assertNotIn('Include="Microsoft.Azure.Functions.Worker"', xml)
self.assertEqual(original_launch, launch.read_bytes())
def test_optional_changes_are_dry_run_safe_and_idempotent(self):
flags = ("--ensure-output-directory", "--integrated-debug")
before = self.snapshot()
self.assertEqual(self.run_cli(*flags).returncode, 0)
self.assertEqual(before, self.snapshot())
result = self.run_cli(*flags, "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
before = self.snapshot()
result = self.run_cli(*flags, "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("0 configuration file(s) updated", result.stdout)
self.assertEqual(before, self.snapshot())
def test_repairs_known_ineffective_directory_hook(self):
guard = """<Target Name="EnsureOutputDirectory" BeforeTargets="FindFunctionJsonFolders">
<MakeDir Directories="$(OutputPath)" Condition="!Exists('$(OutputPath)')" />
</Target>"""
self.write(self.project, PROJECT.replace("</Project>", guard + "\n</Project>"))
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn('BeforeTargets="DeleteFunctionJsonFoldersTarget"', self.project.read_text())
self.assertNotIn('Directories="$(OutputPath)"', self.project.read_text())
def test_refuses_custom_output_directory_target(self):
guard = '<Target Name="EnsureOutputDirectory" BeforeTargets="Build"><Exec Command="custom" /></Target>'
self.write(self.project, PROJECT.replace("</Project>", guard + "</Project>"))
self.assert_blocked_unchanged()
def test_case_variant_directory_guards_are_validated_before_insertion(self):
for name in ("ensureoutputdirectory", "eNsUrEoUtPuTdIrEcToRy"):
with self.subTest(name=name):
guard = (f'<Target Name="{name}" BeforeTargets="FindFunctionJsonFolders">'
'<MakeDir Directories="$(OutputPath)" '
'Condition="!Exists(\'$(OutputPath)\')" /></Target>')
self.write(self.project, PROJECT.replace("</Project>", guard + "</Project>"))
result = self.run_cli("--ensure-output-directory", "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
targets = migration.elements(
migration.project_xml(self.project.read_text()), "Target")
guards = [node for node in targets
if node.getAttribute("Name").lower() == "ensureoutputdirectory"]
self.assertEqual(len(guards), 1)
self.assertEqual(guards[0].getAttribute("Name"), name)
self.assertEqual(guards[0].getAttribute("BeforeTargets"),
"DeleteFunctionJsonFoldersTarget")
custom = f'<Target Name="{name}" BeforeTargets="Build"><Exec Command="custom" /></Target>'
self.write(self.project, PROJECT.replace("</Project>", custom + "</Project>"))
self.assert_blocked_unchanged("--ensure-output-directory")
def test_refuses_case_variant_duplicate_directory_guards(self):
guards = '<Target Name="ensureoutputdirectory" /><Target Name="eNsUrEoUtPuTdIrEcToRy" />'
self.write(self.project, PROJECT.replace("</Project>", guards + "</Project>"))
self.assert_blocked_unchanged("--ensure-output-directory")
def test_custom_publication_hooks_block_new_publish_on_build(self):
for hook in (
'<Target Name="Upload" AfterTargets=" Pack ; pUbLiSh "><Exec Command="custom" /></Target>',
'<Target Name="Upload" BeforeTargets="BeforePublish"><Exec Command="custom" /></Target>',
'<Target Name="Publish"><Exec Command="custom" /></Target>',
'<PropertyGroup><PublishDependsOn>Upload</PublishDependsOn></PropertyGroup>',
'<Target Name="Upload" AfterTargets="$(CustomHook)"><Exec Command="custom" /></Target>'):
with self.subTest(hook=hook):
self.write(self.project, PROJECT.replace("</Project>", hook + "</Project>"))
self.assert_blocked_unchanged()
result = self.run_cli()
self.assertEqual(result.returncode, 1)
self.assertIn("publication hooks", result.stderr)
def test_existing_publish_on_build_with_custom_publication_hook_is_reported(self):
hooks = ('<Target Name="ExistingPublishHook" AfterTargets="Build">'
'<CallTarget Targets="Publish" /></Target>'
'<Target Name="Upload" AfterTargets="Publish"><Exec Command="custom" /></Target>')
self.write(self.project, PROJECT.replace("</Project>", hooks + "</Project>"))
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("Review custom publication hooks before any build", result.stdout)
self.assertIn('AfterTargets="Publish"', self.project.read_text())
self.assertNotIn("TriggerPublishOnBuild", self.project.read_text())
def test_preserves_case_variant_publish_hooks(self):
for after_targets, call_targets in (
("build", "publish"),
("bUiLd", "pUbLiSh"),
(" BeforeBuild ; Build ", " BeforePublish ; Publish ")):
with self.subTest(after_targets=after_targets, call_targets=call_targets):
hook = (f'<Target Name="ExistingPublishHook" AfterTargets="{after_targets}">'
f'<CallTarget Targets="{call_targets}" /></Target>')
self.write(self.project, PROJECT.replace("</Project>", hook + "</Project>"))
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
targets = migration.elements(
migration.project_xml(self.project.read_text()), "Target")
self.assertEqual([node.getAttribute("Name") for node in targets],
["ExistingPublishHook"])
self.assertEqual(targets[0].getAttribute("AfterTargets"), after_targets)
call = migration.elements(targets[0], "CallTarget")[0]
self.assertEqual(call.getAttribute("Targets"), call_targets)
def test_refuses_case_variant_publish_target_conflict(self):
hook = ('<Target Name="triggerpublishonbuild" AfterTargets="Build">'
'<CallTarget Targets="Pack" /></Target>')
self.write(self.project, PROJECT.replace("</Project>", hook + "</Project>"))
self.assert_blocked_unchanged()
def test_unrecognized_deployment_paths_are_preserved_and_reported_without_values(self):
path = self.project.parent / ".vscode" / "settings.json"
for suffix in (r"custom\publish", r"out\Release\net48\publish"):
with self.subTest(suffix=suffix):
self.write(path, json.dumps({
"azureFunctions.deploySubpath": "SENSITIVE-TEST-SENTINEL\\" + suffix,
}))
before = path.read_bytes()
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(path.read_bytes(), before)
self.assertIn("No recognized net8/net8.0 or net10.0 deployment-path component",
result.stdout)
self.assertNotIn("SENSITIVE-TEST-SENTINEL", result.stdout + result.stderr)
def test_preserves_newer_worker_and_logging_versions(self):
text = PROJECT.replace('Version="1.15.1"', 'Version="2.0.8"')
text = text.replace('Version="6.0.0"', 'Version="10.0.1"')
text = text.replace("</ItemGroup>",
'<PackageReference Include="Microsoft.Azure.Functions.Worker" '
'Version="2.52.0" /></ItemGroup>')
self.write(self.project, text)
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
xml = self.project.read_text()
for version in ("2.0.8", "10.0.1", "2.52.0"):
self.assertIn(f'Version="{version}"', xml)
def test_existing_worker_aligns_dependent_logging_pins(self):
text = PROJECT.replace(
"</ItemGroup>",
'<PackageReference Include="Microsoft.Azure.Functions.Worker" Version="1.20.0" />'
"</ItemGroup>")
self.write(self.project, text)
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
xml = self.project.read_text()
self.assertIn('Include="Microsoft.Azure.Functions.Worker" Version="2.51.0"', xml)
self.assertIn('Include="Microsoft.Extensions.Logging" Version="10.0.0"', xml)
self.assertIn('Include="Microsoft.Extensions.Logging.Abstractions" Version="10.0.0"', xml)
def test_refuses_newer_unreviewed_workflows_sdk(self):
for version in ("1.4.2", "1.5.0"):
with self.subTest(version=version):
self.write(self.project, PROJECT.replace('Version="1.2.0"', f'Version="{version}"'))
self.assert_blocked_unchanged()
def test_updates_case_variant_properties_in_place(self):
expected = {
"TargetFramework": "net10.0",
"OutputType": "Library",
"AzureFunctionsVersion": "v4",
"LogicAppFolderToPublish": r"$(MSBuildProjectDirectory)\..\WorkflowHost",
"CopyLocalLockFileAssemblies": "true",
}
for variant in (str.lower, str.swapcase):
with self.subTest(variant=variant.__name__):
text = PROJECT
for name in expected:
text = text.replace(f"<{name}>", f"<{variant(name)}>")
text = text.replace(f"</{name}>", f"</{variant(name)}>")
name = variant("CopyLocalLockFileAssemblies")
text = text.replace("</Project>", f"<PropertyGroup><{name}>false</{name}>"
"</PropertyGroup></Project>")
self.write(self.project, text)
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
root = migration.project_xml(self.project.read_text()).documentElement
for name, value in expected.items():
nodes = [node for node in root.getElementsByTagName("*")
if node.localName.lower() == name.lower()]
self.assertEqual(len(nodes), 1)
self.assertEqual(nodes[0].localName, variant(name))
self.assertEqual(migration.xml_value(nodes[0]), value)
before = self.snapshot()
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(before, self.snapshot())
def test_refuses_case_variant_duplicate_properties(self):
for name, value in (
("TargetFramework", "net8.0"), ("OutputType", "Library"),
("AzureFunctionsVersion", "v4"),
("LogicAppFolderToPublish", r"$(MSBuildProjectDirectory)\..\WorkflowHost"),
("CopyLocalLockFileAssemblies", "false")):
with self.subTest(name=name):
text = PROJECT
if name == "CopyLocalLockFileAssemblies":
text = text.replace("</PropertyGroup>", f"<{name}>{value}</{name}></PropertyGroup>")
text = text.replace("</Project>", f"<PropertyGroup><{name.lower()}>{value}"
f"</{name.lower()}></PropertyGroup></Project>")
self.write(self.project, text)
self.assert_blocked_unchanged()
def test_refuses_case_variant_multitargeting_or_central_management(self):
for property_xml in (
"<TARGETFRAMEWORKS>net8.0;net10.0</TARGETFRAMEWORKS>",
"<managepackageversionscentrally>true</managepackageversionscentrally>"):
with self.subTest(property_xml=property_xml):
text = PROJECT.replace("<PropertyGroup>", "<PropertyGroup>" + property_xml)
self.write(self.project, text)
self.assert_blocked_unchanged()
def test_refuses_mixed_package_version_metadata(self):
original = ('<PackageReference Include="Microsoft.Azure.Workflows.Webjobs.Sdk" '
'Version="1.2.0" />')
for version, attributes, child in (
("1.2.0", "", "<Version>1.2.0</Version>"),
("1.4.1", "", "<Version>1.2.0</Version>"),
("1.2.0", "", "<Version>1.5.0</Version>"),
("1.2.0", "", '<Version Condition="\'$(Configuration)\' == \'Debug\'">1.2.0</Version>'),
("1.2.0", "", "<versionoverride>1.5.0</versionoverride>"),
("1.2.0", ' version="1.5.0"', ""),
("1.2.0", ' versionoverride="1.5.0"', "")):
with self.subTest(version=version, attributes=attributes, child=child):
reference = ('<PackageReference Include="Microsoft.Azure.Workflows.Webjobs.Sdk" '
f'Version="{version}"{attributes}>{child}</PackageReference>')
self.write(self.project, PROJECT.replace(original, reference))
self.assert_blocked_unchanged()
def test_nonversion_package_metadata_is_preserved(self):
original = ('<PackageReference Include="Microsoft.Azure.Functions.Worker.Sdk" '
'Version="1.15.1" />')
reference = original.replace(" />", "><PrivateAssets>all</PrivateAssets>"
"<OutputItemType>Analyzer</OutputItemType></PackageReference>")
self.write(self.project, PROJECT.replace(original, reference))
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
root = migration.project_xml(self.project.read_text()).documentElement
node = next(node for node in migration.elements(root, "PackageReference")
if node.getAttribute("Include") == "Microsoft.Azure.Functions.Worker.Sdk")
self.assertEqual(node.getAttribute("Version"), "2.0.7")
for name, value in (("PrivateAssets", "all"), ("OutputItemType", "Analyzer")):
self.assertEqual(migration.xml_value(migration.elements(node, name)[0]), value)
def test_refuses_conditional_or_central_configuration(self):
for text in (PROJECT.replace("<PropertyGroup>", '<PropertyGroup Condition="true">'),
PROJECT.replace('Version="1.2.0"', ""),
PROJECT.replace("<PropertyGroup>",
"<PropertyGroup><ManagePackageVersionsCentrally>true"
"</ManagePackageVersionsCentrally>")):
with self.subTest(text=text[:60]):
self.write(self.project, text)
self.assert_blocked_unchanged()
def test_refuses_inherited_sdk_pin(self):
self.write(self.root / "global.json", '{"sdk":{"version":"8.0.100"}}')
self.assert_blocked_unchanged()
def test_refuses_host_destination_outside_solution(self):
text = PROJECT.replace("$(MSBuildProjectDirectory)\\..\\WorkflowHost",
"$(MSBuildProjectDirectory)\\..\\..\\ExternalHost")
self.write(self.project, text)
self.assert_blocked_unchanged()
def test_refuses_stale_project_directory_after_relocation(self):
path = self.host / "local.settings.json"
settings = json.loads(path.read_text())
settings["Values"]["ProjectDirectoryPath"] = str(self.root / "OldHost")
self.write(path, json.dumps(settings))
self.assert_blocked_unchanged()
def test_refuses_ambiguous_integrated_debuggers(self):
path = self.host / ".vscode" / "launch.json"
config = {"type": "logicapp", "request": "launch", "funcRuntime": "coreclr"}
self.write(path, json.dumps({"version": "0.2.0", "configurations": [config, config]}))
self.assert_blocked_unchanged("--integrated-debug")
original_launch = path.read_bytes()
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(original_launch, path.read_bytes())
def test_refuses_encrypted_settings(self):
path = self.host / "local.settings.json"
self.write(path, path.read_text().replace('"IsEncrypted": false', '"IsEncrypted": true'))
self.assert_blocked_unchanged()
def test_refuses_invalid_and_duplicate_json_keys_without_writes(self):
path = self.host / ".vscode" / "launch.json"
for text in ('{"configurations": [}', '{"configurations": [], "configurations": []}'):
with self.subTest(text=text):
self.write(path, text)
self.assert_blocked_unchanged()
def test_explicit_project_selection_for_multiple_projects(self):
self.write(self.project.parent / "Second.csproj", PROJECT)
self.assert_blocked_unchanged()
result = self.run_cli("--project", str(self.project), "--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual((self.project.parent / "Second.csproj").read_text(), PROJECT)
def test_concurrent_change_blocks_apply(self):
plan = migration.make_plan(self.root)
path = self.host / "host.json"
self.write(path, path.read_text() + "\n")
before = self.snapshot()
with self.assertRaises(migration.MigrationError):
plan.apply()
self.assertEqual(before, self.snapshot())
def test_write_failure_rolls_back_completed_changes(self):
plan = migration.make_plan(self.root)
before = self.snapshot()
original_write = plan.write
calls = 0
def fail_second_write(path, data):
nonlocal calls
calls += 1
if calls == 2:
raise OSError("synthetic write failure")
original_write(path, data)
with patch.object(plan, "write", side_effect=fail_second_write):
with self.assertRaises(migration.MigrationError):
plan.apply()
self.assertEqual(before, self.snapshot())
def test_linux_extended_attributes_are_copied_before_replacement(self):
path = self.host / "local.settings.json"
with patch.object(migration.sys, "platform", "linux"), \
patch.object(migration.os, "listxattr", return_value=["system.posix_acl_access"],
create=True), \
patch.object(migration.os, "getxattr", return_value=b"synthetic ACL", create=True), \
patch.object(migration.os, "setxattr", create=True) as copy:
migration.Plan.write(path, b'{"new": true}')
copy.assert_called_once()
self.assertEqual(copy.call_args.args[1:], ("system.posix_acl_access", b"synthetic ACL"))
self.assertEqual(path.read_bytes(), b'{"new": true}')
def test_unreadable_access_metadata_blocks_without_changes(self):
before = self.snapshot()
plan = migration.make_plan(self.root)
with patch.object(migration.sys, "platform", "linux"), \
patch.object(migration.os, "listxattr", side_effect=OSError("metadata unavailable"),
create=True):
with self.assertRaises(migration.MigrationError):
plan.apply()
self.assertEqual(before, self.snapshot())
def test_inherited_acl_removal_failure_blocks_without_changes(self):
before = self.snapshot()
plan = migration.make_plan(self.root)
def attributes(path):
return ["system.posix_acl_access"] if Path(path).name.startswith(".") else []
with patch.object(migration.sys, "platform", "linux"), \
patch.object(migration.os, "listxattr", side_effect=attributes, create=True), \
patch.object(migration.os, "removexattr", side_effect=PermissionError("ACL removal denied"),
create=True):
with self.assertRaises(migration.MigrationError):
plan.apply()
self.assertEqual(before, self.snapshot())
def test_unsupported_posix_access_metadata_blocks_without_changes(self):
before = self.snapshot()
plan = migration.make_plan(self.root)
with patch.object(migration.sys, "platform", "darwin"):
with self.assertRaises(migration.MigrationError):
plan.apply()
self.assertEqual(before, self.snapshot())
@unittest.skipUnless(sys.platform == "win32", "Windows ACL integration test")
def test_windows_replacement_preserves_restricted_acl(self):
path = self.host / "local.settings.json"
result = subprocess.run(["icacls", str(path), "/inheritance:r", "/grant:r", "*S-1-3-4:F"],
capture_output=True, text=True, check=False)
self.assertEqual(result.returncode, 0, result.stderr)
before = subprocess.check_output(["icacls", str(path)], text=True)
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(subprocess.check_output(["icacls", str(path)], text=True), before)
@unittest.skipUnless(sys.platform == "linux", "Linux POSIX ACL integration test")
def test_linux_replacement_preserves_restricted_acl_and_ownership(self):
path = self.host / "local.settings.json"
entries = ((1, 6, 0xffffffff), (2, 4, os.getuid() + 1),
(4, 0, 0xffffffff), (16, 4, 0xffffffff), (32, 0, 0xffffffff))
acl = struct.pack("<I", 2) + b"".join(struct.pack("<HHI", *entry) for entry in entries)
os.setxattr(path, "system.posix_acl_access", acl)
before = path.stat()
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertEqual(os.getxattr(path, "system.posix_acl_access"), acl)
after = path.stat()
self.assertEqual((after.st_uid, after.st_gid, after.st_mode),
(before.st_uid, before.st_gid, before.st_mode))
@unittest.skipUnless(sys.platform == "linux", "Linux inherited ACL integration test")
def test_linux_replacement_clears_inherited_acl_when_source_has_none(self):
path = self.host / "local.settings.json"
path.chmod(0o640)
self.assertNotIn("system.posix_acl_access", os.listxattr(path))
before = path.stat()
entries = ((1, 7, 0xffffffff), (2, 4, os.getuid() + 1),
(4, 0, 0xffffffff), (16, 4, 0xffffffff), (32, 0, 0xffffffff))
default_acl = struct.pack("<I", 2) + b"".join(
struct.pack("<HHI", *entry) for entry in entries)
os.setxattr(self.host, "system.posix_acl_default", default_acl)
with tempfile.NamedTemporaryFile(dir=self.host) as temporary:
self.assertIn("system.posix_acl_access", os.listxattr(temporary.name))
migration.Plan.copy_access(path, temporary.name)
self.assertNotIn("system.posix_acl_access", os.listxattr(temporary.name))
result = self.run_cli("--apply")
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn("system.posix_acl_access", os.listxattr(path))
after = path.stat()
self.assertEqual((after.st_uid, after.st_gid, after.st_mode),
(before.st_uid, before.st_gid, before.st_mode))
if __name__ == "__main__":
unittest.main()
License (MIT)
View full license text
MIT License Copyright (c) 2026 wsilveiranz Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.