Fail the Profile Checks When a Changed Bundle Keeps Its Version (#16923)

The app installs a bundled profile set only when its version is newer than
the installed one, and the OTA profile update is named after the version, so
a vendor bundle merged without a bump in its <Vendor>.json never reaches a
user. Nothing checked that: two recent OrcaFilamentLibrary additions and a
Qidi printer model merged with their version unchanged.

Add a version-check command to orca_profile_tool.py that diffs two revisions
(or the working tree against the commit it left main at), groups the changed
files by vendor bundle, and fails unless every changed bundle's version is
newer than before and written as four numbers. The fourth component folds
into the third as the app reads it, so 02.04.00.100 is not newer than
02.04.01.00. A bundle the base does not have, blacklist.json and the user
preset directory are not judged.

Run it as the version_bump check in the Check profiles workflow against the
branch a PR merges into, and in check_profile.sh and check_profile.ps1,
which take --base / -Base to compare with another ref and skip the check for
a --profiles tree outside a git checkout.
This commit is contained in:
HanifKoh authored and GitHub committed 2026-10-27 21:10:54 +08:00
1 parent a50b0a167b
commit be4eff43f4
9 files changed
+521 -49

No files matched your search

+46 -8
View File
@@ -5,11 +5,13 @@
.DESCRIPTION
The Windows counterpart of scripts/check_profile.sh, and kept deliberately close to it.
Runs the same six checks, in the same order, with the same validator flags, and with the
Runs the same seven checks, in the same order, with the same validator flags, and with the
same semantics: every check runs even after an earlier one fails (the workflow's
continue-on-error), then the script exits non-zero once at the end.
profile_tool scripts/orca_profile_tool.py check
version_bump scripts/orca_profile_tool.py version-check: every changed
bundle's <Vendor>.json has a newer version than at -Base
legacy_compat scripts/orca_profile_tool.py legacy-compat --check against
the v2.4.2 profiles
validate_system validator -p <profiles> -l <level>
@@ -17,10 +19,15 @@
validate_filament_subtypes validator -p <profiles> -l <level> -f
validate_custom validator against every released custom-preset fixture
profile_tool is the only check that is not the validator binary; it makes the static checks
the validator cannot, because the validator loads the tree the way the slicer does and so
never sees a profile no <vendor>.json indexes, a preset name two files claim, or a file
normalize and update-index would still rewrite.
profile_tool, version_bump and legacy_compat are the checks that are not the validator
binary; they make the static checks the validator cannot, because the validator loads the
tree the way the slicer does and so never sees a profile no <vendor>.json indexes, a preset
name two files claim, a file normalize and update-index would still rewrite, or a bundle
that changed without its version being bumped. version_bump compares the tree with the
commit it left main at, where CI compares a PR with the branch it merges into; -Base points
it elsewhere. It is skipped, unless named, for a -ProfilesDir tree that is not inside a git
checkout, or one with neither upstream/main nor origin/main to compare with when no -Base
is given.
Everything that has to be downloaded - the profile validator, the custom-preset fixture
archives and the v2.4.2 profile tree - lands under a per-user cache directory
@@ -54,6 +61,10 @@
fail on another vendor's files, and legacy_compat is tree-wide too: the map it checks covers
every vendor.
.PARAMETER Base
The git ref version_bump compares the tree with (default: where the branch left
upstream/main, else origin/main).
.PARAMETER Validator
OrcaSlicer_profile_validator.exe to use; also $env:ORCA_PROFILE_VALIDATOR. Default: the local
build*\ Release build (then RelWithDebInfo, MinSizeRel, Debug) for this architecture, else
@@ -91,6 +102,7 @@
param(
[Alias('p')] [string] $ProfilesDir,
[Alias('v')] [string] $Vendor,
[string] $Base,
[string] $Validator,
[string] $WorkDir,
[Alias('l')] [int] $LogLevel = 2,
@@ -120,7 +132,7 @@ $HostArch = switch ($HostArch) {
default { 'x86' }
}
$AllChecks = @('profile_tool', 'legacy_compat', 'validate_system', 'validate_slice', 'validate_filament_subtypes', 'validate_custom')
$AllChecks = @('profile_tool', 'version_bump', 'legacy_compat', 'validate_system', 'validate_slice', 'validate_filament_subtypes', 'validate_custom')
$script:LogWriter = $null
$script:Python = ''
@@ -217,6 +229,7 @@ if ($Vendor) {
# run passes neither, so the checks below splat these in either way.
$VendorArgs = if ($Vendor) { @('-v', $Vendor) } else { @() }
$VendorPyArgs = if ($Vendor) { @('--vendor', $Vendor) } else { @() }
$BaseArgs = if ($Base) { @('--base', $Base) } else { @() }
if (-not $WorkDir) {
# Per-user cache dir, so every worktree on the machine shares one set of downloads.
@@ -451,6 +464,19 @@ function Expand-VendorPresets([string] $Zip, [string] $Tree, [string] $Prefix) {
$LegacyBaseTag = 'v2.4.2'
$LegacyBaseUrl = 'https://github.com/OrcaSlicer/OrcaSlicer.git'
# Why the default run leaves version_bump out, or $null when it can run.
function Get-VersionBumpSkipReason {
$ErrorActionPreference = 'Continue'
& git -C $ProfilesDir rev-parse --is-inside-work-tree 2>$null | Out-Null
if ($LASTEXITCODE -ne 0) { return "$ProfilesDir is not in a git checkout" }
if ($Base) { return $null }
foreach ($main in 'upstream/main', 'origin/main') {
& git -C $ProfilesDir rev-parse -q --verify "$main^{commit}" 2>$null | Out-Null
if ($LASTEXITCODE -eq 0) { return $null }
}
return 'neither upstream/main nor origin/main exists to compare with; pass -Base'
}
function Get-LegacyBaseProfiles {
$ErrorActionPreference = 'Continue'
$base = Join-Path (Join-Path $WorkDir 'legacy-base') $LegacyBaseTag
@@ -488,6 +514,13 @@ $CheckBodies = @{
Invoke-Tool -Exe (Resolve-Python) -Arguments (@((Join-Path $RepoRoot 'scripts\orca_profile_tool.py'), 'check', '--profiles', $ProfilesDir) + $VendorPyArgs)
}
# The app installs a bundle only when its version is newer than the installed one, and the
# OTA profile update is named after it, so a changed bundle whose <Vendor>.json keeps its
# version never reaches users.
version_bump = {
Invoke-Tool -Exe (Resolve-Python) -Arguments (@((Join-Path $RepoRoot 'scripts\orca_profile_tool.py'), 'version-check', '--profiles', $ProfilesDir) + $VendorPyArgs + $BaseArgs)
}
# The map says which printers a user filament preset made against 2.4.2 can be migrated
# back to, so a profile change that renames a filament preset or narrows its
# compatible_printers has to regenerate it (the CI comment gives the command).
@@ -630,6 +663,7 @@ $CheckBodies = @{
# Heading CI puts above this check's log in the PR comment.
$CommentHeadings = @{
profile_tool = '### Profile Check Failed (orca_profile_tool.py)'
version_bump = '### Profile Version Not Bumped'
legacy_compat = '### Legacy Compatible Printers Map Out of Date'
validate_system = '### System Profile Validation Failed'
validate_slice = '### Slice Validation Failed (custom g-code expansion)'
@@ -677,11 +711,12 @@ try {
[Console]::OutputEncoding = New-Object Text.UTF8Encoding($false)
Push-UserPresets
if ($Checks | Where-Object { $_ -ne 'profile_tool' -and $_ -ne 'legacy_compat' }) { $Validator = Resolve-Validator }
if ($Checks | Where-Object { $_ -notin 'profile_tool', 'version_bump', 'legacy_compat' }) { $Validator = Resolve-Validator }
# An empty printer set is a failure to the sweep, so validate_slice is recorded as skipped
# rather than run for a vendor that ships no printers (the filament-only OrcaFilamentLibrary);
# naming the check explicitly still runs it.
# naming the check explicitly still runs it. So is version_bump for a -ProfilesDir tree git
# cannot diff, such as a copy made to try a change on, or one with no main to diff against.
$results = [ordered] @{}
$skipReasons = @{}
foreach ($name in $AllChecks) {
@@ -690,6 +725,9 @@ try {
-not (Test-Path -LiteralPath (Join-Path (Join-Path $ProfilesDir $Vendor) 'machine') -PathType Container)) {
$results[$name] = 'skip'
$skipReasons[$name] = "$Vendor ships no printers"
} elseif ($name -eq 'version_bump' -and -not $NamedChecks -and ($why = Get-VersionBumpSkipReason)) {
$results[$name] = 'skip'
$skipReasons[$name] = $why
} else {
$results[$name] = if (Invoke-Check $name) { 'pass' } else { 'fail' }
}
+47 -8
View File
@@ -2,7 +2,7 @@
#
# Local twin of the "Check profiles" CI job (.github/workflows/check_profiles.yml).
#
# Runs the same six checks, in the same order, with the same validator flags, and with the
# Runs the same seven checks, in the same order, with the same validator flags, and with the
# same semantics: every check runs even after an earlier one fails (the workflow's
# continue-on-error), then the script exits non-zero once at the end.
#
@@ -18,7 +18,9 @@
#
# -v/--vendor narrows a run to one vendor while working on that vendor's profiles - the one
# deliberate divergence from CI, which always checks the whole tree. A check that cannot be
# narrowed is left out of the run and reported as skipped; see usage().
# narrowed is left out of the run and reported as skipped; see usage(). version_bump compares
# the tree with the commit it left main at, where CI compares a PR with the branch it merges
# into; --base points it elsewhere.
#
# Usage: scripts/check_profile.sh [OPTION]... [CHECK]...
@@ -55,11 +57,12 @@ VALIDATOR="${ORCA_PROFILE_VALIDATOR:-}"
# So the flag is passed unconditionally below rather than kept in an array bash 3.2 cannot expand
# empty under `set -u`.
VENDOR=""
BASE_REF=""
LOG_LEVEL=2
PREFER_DOWNLOAD=0
REFRESH=0
ALL_CHECKS=(profile_tool legacy_compat validate_system validate_slice validate_filament_subtypes validate_custom)
ALL_CHECKS=(profile_tool version_bump legacy_compat validate_system validate_slice validate_filament_subtypes validate_custom)
CHECKS=()
# "<check><TAB>pass|fail" per check that ran, plus "<check><TAB>skip<TAB>why" for one a vendor
# scope left out; a string rather than an array because bash 3.2 (still the /bin/bash on macOS)
@@ -74,6 +77,8 @@ Usage: scripts/check_profile.sh [OPTION]... [CHECK]...
Checks (default: all, in this order):
profile_tool scripts/orca_profile_tool.py check
version_bump scripts/orca_profile_tool.py version-check: every changed
bundle's <Vendor>.json has a newer version than at --base
legacy_compat scripts/orca_profile_tool.py legacy-compat --check against the
v2.4.2 profiles
validate_system validator -p <profiles> -l <level>
@@ -84,6 +89,8 @@ Checks (default: all, in this order):
Options:
-p, --profiles DIR profile tree to validate (default: resources/profiles)
-v, --vendor NAME check only this vendor, named after its <Vendor>.json (e.g. "Co Print")
--base REF the git ref version_bump compares the tree with (default: where the
branch left upstream/main, else origin/main)
--validator BIN OrcaSlicer_profile_validator to use; also \$ORCA_PROFILE_VALIDATOR.
Default: the local build*/ Release build (then RelWithDebInfo, then
Debug) for this architecture, else the nightly release build is
@@ -94,10 +101,13 @@ Options:
-l, --log-level N validator log level (default: ${LOG_LEVEL}, as in CI)
-h, --help show this help
Note: profile_tool is the only check that is not the validator binary; it makes the static
checks the validator cannot, because the validator loads the tree the way the slicer does
and so never sees a profile no <vendor>.json indexes, a preset name two files claim, or a
file normalize and update-index would still rewrite.
Note: profile_tool, version_bump and legacy_compat are the checks that are not the validator
binary; they make the static checks the validator cannot, because the validator loads the tree
the way the slicer does and so never sees a profile no <vendor>.json indexes, a preset name
two files claim, a file normalize and update-index would still rewrite, or a bundle that
changed without its version being bumped. version_bump is skipped, unless named, for a
--profiles tree that is not inside a git checkout, or one with neither upstream/main nor
origin/main to compare with when no --base is given.
Note: --vendor narrows validate_custom too, by keeping only that vendor's presets in each
fixture tree. The one check it cannot narrow is validate_slice for a vendor that ships no
@@ -124,6 +134,7 @@ while [ $# -gt 0 ]; do
-h|--help) usage; exit 0 ;;
-p|--profiles) [ $# -ge 2 ] || die "$1 needs a directory"; PROFILES_DIR="$2"; shift 2 ;;
-v|--vendor) [ $# -ge 2 ] || die "$1 needs a vendor name"; VENDOR="$2"; shift 2 ;;
--base) [ $# -ge 2 ] || die "$1 needs a git ref"; BASE_REF="$2"; shift 2 ;;
--validator) [ $# -ge 2 ] || die "$1 needs a path"; VALIDATOR="$2"; shift 2 ;;
--work-dir) [ $# -ge 2 ] || die "$1 needs a directory"; WORK_DIR="$2"; shift 2 ;;
-l|--log-level) [ $# -ge 2 ] || die "$1 needs a number"; LOG_LEVEL="$2"; shift 2 ;;
@@ -383,6 +394,29 @@ check_profile_tool() {
python3 "${REPO_ROOT}/scripts/orca_profile_tool.py" check --profiles "${PROFILES_DIR}" --vendor "${VENDOR}"
}
# The app installs a bundle only when its version is newer than the installed one, and the OTA
# profile update is named after it, so a changed bundle whose <Vendor>.json keeps its version
# never reaches users.
check_version_bump() {
python3 "${REPO_ROOT}/scripts/orca_profile_tool.py" version-check --profiles "${PROFILES_DIR}" \
--vendor "${VENDOR}" ${BASE_REF:+--base "${BASE_REF}"}
}
# Why the default run leaves version_bump out, on stdout; nothing, and status 1, when it can run.
version_bump_skip_reason() {
local main
if ! git -C "${PROFILES_DIR}" rev-parse --is-inside-work-tree >/dev/null 2>&1; then
echo "${PROFILES_DIR} is not in a git checkout"
return 0
fi
[ -z "${BASE_REF}" ] || return 1
for main in upstream/main origin/main; do
git -C "${PROFILES_DIR}" rev-parse -q --verify "${main}^{commit}" >/dev/null 2>&1 && return 1
done
echo "neither upstream/main nor origin/main exists to compare with; pass --base"
return 0
}
# The profile tree of the release resources/info/legacy_compatible_printers.json is generated
# against. The tag is immutable, so the extracted tree is cached in the work dir and --refresh
# re-extracts it. A checkout without the tag (a shallow clone, a fork that never fetched tags)
@@ -605,6 +639,7 @@ EOF
comment_heading() {
case "$1" in
profile_tool) echo "### Profile Check Failed (orca_profile_tool.py)" ;;
version_bump) echo "### Profile Version Not Bumped" ;;
legacy_compat) echo "### Legacy Compatible Printers Map Out of Date" ;;
validate_system) echo "### System Profile Validation Failed" ;;
validate_slice) echo "### Slice Validation Failed (custom g-code expansion)" ;;
@@ -637,12 +672,16 @@ fi
# An empty printer set is a failure to the sweep, so validate_slice is recorded as skipped rather
# than run for a vendor that ships no printers (the filament-only OrcaFilamentLibrary); naming the
# check explicitly still runs it.
# check explicitly still runs it. So is version_bump for a --profiles tree git cannot diff, such
# as a copy made to try a change on, or one with no main to diff against.
for check in "${ALL_CHECKS[@]}"; do
wants "${check}" || continue
if [ "${check}" = validate_slice ] && [ "${NAMED_CHECKS}" -eq 0 ] && [ -n "${VENDOR}" ] &&
[ ! -d "${PROFILES_DIR}/${VENDOR}/machine" ]; then
RESULTS="${RESULTS}${check}"$'\t'"skip"$'\t'"${VENDOR} ships no printers"$'\n'
elif [ "${check}" = version_bump ] && [ "${NAMED_CHECKS}" -eq 0 ] &&
why="$(version_bump_skip_reason)"; then
RESULTS="${RESULTS}${check}"$'\t'"skip"$'\t'"${why}"$'\n'
else
run_check "${check}"
fi
+187 -7
View File
@@ -13,6 +13,7 @@ commands:
update-index regenerate the *_list sections of <vendor>.json
legacy-compat write the printers user presets can be migrated back to
gcode-diff print a readable markdown diff of changed custom G-code
version-check fail unless every changed bundle's version was bumped
options shared by several commands:
--vendor VENDOR act on one vendor bundle only; repeatable, empty means all
@@ -3409,7 +3410,7 @@ def gcode_diff(profiles_dir, base, head=None, vendors=None):
return GCODE_DIFF_HEADER + "".join(sections[:shown]) + note
def _default_gcode_diff_base(profiles_dir, head):
def _default_diff_base(profiles_dir, head):
for main in ("upstream/main", "origin/main"):
try:
return _git(profiles_dir, "merge-base", head or "HEAD", main).decode().strip()
@@ -3420,7 +3421,7 @@ def _default_gcode_diff_base(profiles_dir, head):
def run_gcode_diff(profiles_dir, vendors, base, head):
try:
markdown = gcode_diff(profiles_dir, base or _default_gcode_diff_base(profiles_dir, head),
markdown = gcode_diff(profiles_dir, base or _default_diff_base(profiles_dir, head),
head, vendors)
# UnicodeDecodeError means git listed a file name that is not UTF-8.
except (OSError, RuntimeError, UnicodeDecodeError, subprocess.CalledProcessError) as e:
@@ -3431,6 +3432,167 @@ def run_gcode_diff(profiles_dir, vendors, base, head):
return 0
# ---------------------------------------------------------------------------
# version-check
# ---------------------------------------------------------------------------
# What the app's Semver::parse reads: three or four dot-separated numbers. Bundles write
# four, MM.mm.pp.bb, and the OTA profile update's asset name requires all four.
VERSION_RE = re.compile(r"^\d+\.\d+\.\d+(?:\.\d+)?$")
# The files a version-check error names before "and N more".
VERSION_CHECK_SUMMARY_FILES = 3
def _version_key(version):
"""The version as the app orders it, or None when it does not parse. The fourth
component is folded into the third (patch * 100 + build), so 02.04.00.100 is not
newer than 02.04.01.00."""
if not isinstance(version, str) or not VERSION_RE.match(version):
return None
parts = [int(part) for part in version.split(".")]
build = parts[3] if len(parts) == 4 else 0
return (parts[0], parts[1], parts[2] * 100 + build)
def next_version(version):
"""The version after this one, in its own notation: the last component plus one,
carrying .99 into the third (02.03.02.99 -> 02.03.03.00). A three-part version
gains the fourth component (1.0.0 -> 1.0.0.01)."""
parts = version.split(".")
if len(parts) == 3:
return version + ".01"
patch, build = int(parts[2]), int(parts[3]) + 1
if build > 99:
patch, build = patch + 1, 0
return ".".join((parts[0], parts[1], str(patch).zfill(len(parts[2])),
str(build).zfill(len(parts[3]))))
def _changed_paths(profiles_dir, base, head):
"""Every path under profiles_dir, relative to it, that differs between base and
head (the working tree, untracked files included, when None). Renames are not
paired, so a file moved between bundles changes both."""
out = _git(profiles_dir, "diff", "--name-only", "-z", "--no-renames", "--relative", base,
*([head] if head else []), "--", ".")
paths = [rel for rel in out.decode("utf-8").split("\0") if rel]
if head is None:
out = _git(profiles_dir, "ls-files", "-z", "--others", "--exclude-standard", "--", ".")
paths += [rel for rel in out.decode("utf-8").split("\0") if rel]
return paths
def _is_dir_at(profiles_dir, ref, rel):
"""Whether rel (relative to profiles_dir) is a directory at ref, or in the working
tree when ref is None."""
if ref is None:
return os.path.isdir(os.path.join(profiles_dir, rel))
prefix = _git(profiles_dir, "rev-parse", "--show-prefix").decode("utf-8").strip()
try:
return _git(profiles_dir, "cat-file", "-t", f"{ref}:{prefix}{rel}").strip() == b"tree"
except subprocess.CalledProcessError:
return False
def _file_summary(files):
shown = ", ".join(files[:VERSION_CHECK_SUMMARY_FILES])
if len(files) > VERSION_CHECK_SUMMARY_FILES + 1: # never "and 1 more"
return f"{shown} and {len(files) - VERSION_CHECK_SUMMARY_FILES} more"
return ", ".join(files)
def version_check(profiles_dir, base, head=None, vendors=None):
"""(bumped, errors) over the vendor bundles with a file that differs between base
and head: bumped lists (vendor, old version or None, new version, changed file
count) for each whose <Vendor>.json version at head is newer than at base (or that
base does not have); errors describes each whose version is unchanged, older,
missing, or not four numbers, and one whose index is gone while <Vendor>/ remains.
A top-level .json without a version and without a <Vendor>/ directory, such as
blacklist.json, is not a bundle; nor is one head deletes whole."""
files_by_vendor = defaultdict(list)
for rel in _changed_paths(profiles_dir, base, head):
top, sep, _ = rel.partition("/")
vendor = top if sep else (top[:-5] if top.endswith(".json") else "")
if vendor and vendor != USER_DIR and (not vendors or vendor in vendors):
files_by_vendor[vendor].append(rel)
if not files_by_vendor:
return [], []
specs = [(base, f"{vendor}.json") for vendor in files_by_vendor]
if head:
specs += [(head, f"{vendor}.json") for vendor in files_by_vendor]
blobs = _blobs_at(profiles_dir, specs)
def index_version(ref, vendor):
"""(found, version) of <vendor>.json at ref, or in the working tree."""
if ref:
raw = blobs[(ref, f"{vendor}.json")]
else:
try:
raw = Path(profiles_dir, f"{vendor}.json").read_bytes()
except FileNotFoundError:
raw = None
if raw is None:
return False, None
try:
index = json.loads(raw.decode("utf-8-sig"))
except ValueError:
return True, None
return True, index.get("version") if isinstance(index, dict) else None
bumped, errors = [], []
where = head or "the working tree"
for vendor, files in sorted(files_by_vendor.items()):
found, new = index_version(head, vendor)
if not found:
if _is_dir_at(profiles_dir, head, vendor):
errors.append(f"{vendor}.json is missing in {where} while {vendor}/ still has "
f"files; restore the index or delete the directory")
continue
if new is None:
if _is_dir_at(profiles_dir, head, vendor):
errors.append(f"{vendor}.json has no version in {where}, so the app never "
f"installs the bundle; write one (MM.mm.pp.bb)")
continue
new_key = _version_key(new)
if new_key is None or new.count(".") != 3:
errors.append(f'{vendor}.json: version "{new}" in {where} is not four numbers '
f"(MM.mm.pp.bb), which the profile update needs")
continue
found, old = index_version(base, vendor)
old_key = _version_key(old)
if old_key is None or new_key > old_key:
# No comparable base: a bundle base lacks, or whose index there has no
# usable version.
label = None if not found else ("no version" if old is None else str(old))
bumped.append((vendor, label, new, len(files)))
else:
what = (f"version {new} was not bumped" if new == old
else f"version {new} is not newer than {old} at {base}")
count = f"{len(files)} file" + ("" if len(files) == 1 else "s")
errors.append(f"{vendor}.json: {what}, but {count} of the bundle changed "
f"({_file_summary(files)}); bump it to {next_version(old)}")
return bumped, errors
def run_version_check(profiles_dir, vendors, base, head):
try:
base = base or _default_diff_base(profiles_dir, head)
bumped, errors = version_check(profiles_dir, base, head, vendors)
# UnicodeDecodeError means git listed a file name that is not UTF-8.
except (OSError, RuntimeError, UnicodeDecodeError, subprocess.CalledProcessError) as e:
stderr = getattr(e, "stderr", None)
print_error(stderr.decode(errors="replace").strip() if stderr else str(e))
return 1
for vendor, old, new, count in bumped:
print(f"{vendor}: {old or 'new bundle'} -> {new}, {count} file"
f"{'' if count == 1 else 's'} changed")
for error in errors:
print_error(error)
if not bumped and not errors:
print(f"no profile bundle changed since {base}")
return 1 if errors else 0
# ---------------------------------------------------------------------------
# CLI
# ---------------------------------------------------------------------------
@@ -3458,6 +3620,9 @@ examples:
orca_profile_tool.py gcode-diff > gcode.md
the changed custom G-code of the working tree since it left upstream/main,
as markdown with one collapsed diff per setting
orca_profile_tool.py version-check
fail unless every bundle the working tree changed since it left
upstream/main has a newer version in its <Vendor>.json
after adding, renaming or deleting profile files, run in this order:
normalize -> update-index -> generate-id -> check
@@ -3625,11 +3790,23 @@ def build_parser():
"The settings are the *_gcode and multiline string options PrintConfig.cpp\n"
"defines, the options Tab.cpp edits as code (such as filename_format), and any\n"
"string value that spans several lines.")
gcode_cmd.add_argument("--base", metavar="REF",
help="compare against this git ref (default: the merge base "
"with upstream/main, else origin/main)")
gcode_cmd.add_argument("--head", metavar="REF",
help="compare this git ref (default: the working tree)")
version_cmd = add(
"version-check", [vendor_opt, profiles_opt],
"fail unless every changed bundle's version was bumped",
"Fail unless every vendor bundle with a file that differs between --base and\n"
"--head (<Vendor>.json, or anything under <Vendor>/) has, at --head, a version\n"
"in <Vendor>.json that is newer than at --base and written as four numbers\n"
"(MM.mm.pp.bb). A bundle --base does not have passes. The app installs a\n"
"bundled profile only when its version is newer than the installed one, and\n"
"the OTA profile update is named after it, so a change without a bump never\n"
"reaches users. CI runs it on profile PRs against the branch they merge into.")
for cmd in (gcode_cmd, version_cmd):
cmd.add_argument("--base", metavar="REF",
help="compare against this git ref (default: the merge base "
"with upstream/main, else origin/main)")
cmd.add_argument("--head", metavar="REF",
help="compare this git ref (default: the working tree)")
return parser
@@ -3670,6 +3847,9 @@ def main(argv=None):
if args.command == "gcode-diff":
return run_gcode_diff(profiles_dir, vendors, args.base, args.head)
if args.command == "version-check":
return run_version_check(profiles_dir, vendors, args.base, args.head)
if args.command == "fix-variant":
_changed, errors = fix_variant_arrays(profiles_dir, vendors, dry_run=args.dry_run,
strict=args.strict)
+187 -6
View File
@@ -1,6 +1,6 @@
#!/usr/bin/env python3
"""Tests for the tree-maintenance half of scripts/orca_profile_tool.py: the
normalize, trim, update-index, fix-variant, check and gcode-diff commands, and the
normalize, trim, update-index, fix-variant, check, gcode-diff and version-check commands, and the
subcommand dispatch that reaches them (stdlib unittest, no external deps).
The id halves are covered by test_filament_id.py and test_setting_id.py.
@@ -1434,16 +1434,13 @@ class TestDispatch(TreeCase):
# ---------------------------------------------------------------------------
@unittest.skipUnless(shutil.which("git"), "git not installed")
class TestGcodeDiff(TreeCase):
START = "G28\nM104 S200\nG1 Z5"
class GitTreeCase(TreeCase):
"""A tree that is a git repository, for the commands that diff two revisions."""
def git(self, *args):
subprocess.run(["git", "-C", self.t.dir, "-c", "user.name=t", "-c", "user.email=t@t",
"-c", "commit.gpgsign=false", *args], check=True, capture_output=True)
def printer(self, name, **extra):
self.t.write("V", f"machine/{name}.json", {"type": "machine", "name": name, **extra})
def commit(self):
self.git("add", "-A")
self.git("commit", "-q", "--allow-empty", "-m", "x")
@@ -1466,6 +1463,16 @@ class TestGcodeDiff(TreeCase):
patcher.start()
self.addCleanup(patcher.stop)
self.git("init", "-q")
class TestGcodeDiff(GitTreeCase):
START = "G28\nM104 S200\nG1 Z5"
def printer(self, name, **extra):
self.t.write("V", f"machine/{name}.json", {"type": "machine", "name": name, **extra})
def setUp(self):
super().setUp()
for name in ("A", "B", "C"):
self.printer(name, machine_start_gcode=self.START, nozzle_diameter=["0.4"])
self.printer("Gone", machine_end_gcode="M84")
@@ -1715,6 +1722,180 @@ class TestGcodeDiff(TreeCase):
self.assertIn("\n<p><code>V/a *b*.json</code>, ", section)
# ---------------------------------------------------------------------------
# version-check
# ---------------------------------------------------------------------------
class TestVersionCheck(GitTreeCase):
def index(self, vendor, version, **extra):
self.t.write_index(vendor, {"name": vendor, "version": version, **extra})
def setUp(self):
super().setUp()
for vendor in ("V", "W"):
self.t.add_vendor(vendor)
self.t.write(vendor, "machine/A.json", {"type": "machine", "name": "A"})
self.commit()
def check(self, *args):
return self.run_command("version-check", "--base", "HEAD", *args)
def test_a_changed_file_needs_a_bump(self):
self.t.write("V", "machine/A.json", {"type": "machine", "name": "A", "x": "1"})
rc, out = self.check()
self.assertEqual(rc, 1)
self.assertIn("V.json: version 01.00.00.00 was not bumped, but 1 file of the bundle "
"changed (V/machine/A.json); bump it to 01.00.00.01", out)
def test_a_bumped_bundle_passes(self):
self.t.write("V", "machine/A.json", {"type": "machine", "name": "A", "x": "1"})
self.index("V", "01.00.00.01")
rc, out = self.check()
self.assertEqual((rc, out), (0, "V: 01.00.00.00 -> 01.00.00.01, 2 files changed\n"))
def test_an_index_only_change_needs_a_bump(self):
self.index("V", "01.00.00.00", machine_list=[])
rc, out = self.check()
self.assertEqual(rc, 1)
self.assertIn("V.json: version 01.00.00.00 was not bumped, but 1 file", out)
def test_an_added_and_a_deleted_file_count(self):
self.t.write("V", "machine/B.json", {"type": "machine", "name": "B"}) # untracked
os.remove(self.t.path("W", "machine/A.json"))
rc, out = self.check()
self.assertEqual(rc, 1)
self.assertIn("V.json: version 01.00.00.00 was not bumped", out)
self.assertIn("W.json: version 01.00.00.00 was not bumped, but 1 file of the bundle "
"changed (W/machine/A.json)", out)
def test_a_file_moved_between_bundles_changes_both(self):
os.rename(self.t.path("V", "machine/A.json"), self.t.path("W", "machine/B.json"))
self.index("W", "01.00.00.01")
self.commit()
rc, out = self.run_command("version-check", "--base", "HEAD~1", "--head", "HEAD")
self.assertEqual(rc, 1)
self.assertIn("W: 01.00.00.00 -> 01.00.00.01, 2 files changed", out)
self.assertIn("V.json: version 01.00.00.00 was not bumped, but 1 file of the bundle "
"changed (V/machine/A.json)", out)
def test_a_deleted_index_with_files_left_is_an_error(self):
os.remove(self.t.index_path("V"))
rc, out = self.check()
self.assertEqual(rc, 1)
self.assertIn("V.json is missing in the working tree while V/ still has files", out)
shutil.rmtree(self.t.path("V", ""))
rc, out = self.check()
self.assertEqual((rc, out), (0, "no profile bundle changed since HEAD\n"))
def test_a_base_without_a_usable_version_is_named(self):
self.t.write_index("V", {"name": "V"})
self.commit()
self.index("V", "01.00.00.00")
rc, out = self.check()
self.assertEqual((rc, out), (0, "V: no version -> 01.00.00.00, 1 file changed\n"))
self.index("V", "garbage")
self.commit()
self.index("V", "01.00.00.00")
rc, out = self.check()
self.assertEqual((rc, out), (0, "V: garbage -> 01.00.00.00, 1 file changed\n"))
def test_a_new_bundle_passes(self):
self.t.add_vendor("N")
self.t.write("N", "machine/A.json", {"type": "machine", "name": "A"})
rc, out = self.check()
self.assertEqual((rc, out), (0, "N: new bundle -> 01.00.00.00, 2 files changed\n"))
def test_nothing_changed(self):
self.t.write("user", "default/machine/U.json", {"inherits": "A"})
with open(os.path.join(self.t.profiles, "blacklist.json"), "w", encoding="utf-8") as f:
f.write("{}\n")
rc, out = self.check()
self.assertEqual((rc, out), (0, "no profile bundle changed since HEAD\n"))
def test_a_lower_version_is_not_newer(self):
self.index("V", "00.09.00.00")
rc, out = self.check()
self.assertEqual(rc, 1)
self.assertIn("V.json: version 00.09.00.00 is not newer than 01.00.00.00 at HEAD, but "
"1 file of the bundle changed (V.json); bump it to 01.00.00.01", out)
def test_the_fourth_component_folds_into_the_third(self):
# The app reads both as 1.0.100, so this is not a bump.
self.index("V", "01.00.01.00")
self.commit()
self.index("V", "01.00.00.100")
rc, out = self.check()
self.assertEqual(rc, 1)
self.assertIn("version 01.00.00.100 is not newer than 01.00.01.00", out)
def test_a_version_needs_four_numbers(self):
for version in ("1.0.1", "01.00.00.01-beta", "x"):
self.index("V", version)
rc, out = self.check()
self.assertEqual(rc, 1, version)
self.assertIn(f'V.json: version "{version}" in the working tree is not four '
"numbers (MM.mm.pp.bb)", out)
def test_a_three_part_base_version_is_still_compared(self):
self.index("V", "1.0.0")
self.commit()
self.index("V", "1.0.0.01")
rc, out = self.check()
self.assertEqual((rc, out), (0, "V: 1.0.0 -> 1.0.0.01, 1 file changed\n"))
self.index("V", "1.0.0.00")
rc, out = self.check()
self.assertEqual(rc, 1)
self.assertIn("bump it to 1.0.0.01", out)
def test_a_missing_version_is_an_error_only_with_a_bundle(self):
self.t.write_index("V", {"name": "V"})
rc, out = self.check()
self.assertEqual(rc, 1)
self.assertIn("V.json has no version in the working tree", out)
self.index("V", "01.00.00.00")
with open(os.path.join(self.t.profiles, "notes.json"), "w", encoding="utf-8") as f:
f.write("{}\n") # a top-level file that is not a bundle
rc, out = self.check()
self.assertEqual((rc, out), (0, "no profile bundle changed since HEAD\n"))
def test_vendor_narrows(self):
for vendor in ("V", "W"):
self.t.write(vendor, "machine/A.json", {"type": "machine", "name": "A", "x": "1"})
rc, out = self.check("--vendor", "W")
self.assertEqual(rc, 1)
self.assertNotIn("V.json", out)
self.assertIn("W.json: version 01.00.00.00 was not bumped", out)
def test_head_compares_two_commits(self):
self.t.write("V", "machine/A.json", {"type": "machine", "name": "A", "x": "1"})
self.commit()
rc, out = self.run_command("version-check", "--base", "HEAD~1", "--head", "HEAD")
self.assertEqual(rc, 1)
self.assertIn("V.json: version 01.00.00.00 was not bumped", out)
self.index("V", "01.00.00.01")
self.commit()
rc, out = self.run_command("version-check", "--base", "HEAD~2", "--head", "HEAD")
self.assertEqual((rc, out), (0, "V: 01.00.00.00 -> 01.00.00.01, 2 files changed\n"))
def test_a_bad_ref_is_an_error(self):
rc, out = self.run_command("version-check", "--base", "no-such-ref")
self.assertEqual(rc, 1)
self.assertIn("no-such-ref", out)
def test_next_version(self):
for version, after in (("02.04.00.16", "02.04.00.17"), ("02.03.02.99", "02.03.03.00"),
("01.00.00.9", "01.00.00.10"), ("2.4.0.05", "2.4.0.06"),
("1.0.0", "1.0.0.01")):
self.assertEqual(apt.next_version(version), after)
def test_version_key(self):
self.assertEqual(apt._version_key("02.04.00.100"), apt._version_key("02.04.01.00"))
self.assertLess(apt._version_key("02.04.00.99"), apt._version_key("02.04.01.00"))
self.assertEqual(apt._version_key("1.0.0"), (1, 0, 0))
for bad in ("1.0.0.0.0", "a.b.c", "1.0", "", None):
self.assertIsNone(apt._version_key(bad), bad)
# ---------------------------------------------------------------------------
# the real tree
# ---------------------------------------------------------------------------