From 2af22d526438d4b6e29448c3ac36b0df0ba101f7 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 12:46:15 +0100 Subject: [PATCH 1/9] updiff: detect edits from the attach manifest and merge chains do_diffcompose diffed the tree against ${S}.pristine, so every patched file came out as a candidate, edited or not, and do_updiff compared it with the series to sort them out. A file that differs from the series was then taken for an edit, even when the series had moved: after a git pull bringing new patches, with do_patch not replayed, an updiff about an unrelated file rewrote those patches from the old tree and silently reverted them. A file restored to its pristine state produced no diff at all, so its patch survived. Candidates now come from the manifest do_attach_infrabase records: files whose hash changed, files it does not list, and files that are gone. Untouched files are not looked at, and the series replay is checked against the attached hash, so an edit on a file whose patches moved stops with nothing written. Without a manifest the tree is compared to pristine, with a warning, and that old exposure remains. ${S}.pristine stays the base of the replay: a hash cannot rebuild the state the earlier patches leave. Chains left by the older updiff are merged when such a file is edited: the tail of the chain lying in one patchset becomes one patch, the later ones lose their section, and a patch left empty is deleted with its .inc line. A file back at its state before that tail thus drops it, which used to be fatal. Patchsets never merge with one another, so a bbappend stays apart from its base recipe, and a patch with a description or a non-generated .inc is left alone. updiff also refuses a tree attached to another recipe. The doc claimed the diff ran against patched files, which had been wrong for a while. --- build/meta/classes/patch.bbclass | 476 ++++++++++++----------- doc/source/build_system/build_system.rst | 21 +- 2 files changed, 271 insertions(+), 226 deletions(-) diff --git a/build/meta/classes/patch.bbclass b/build/meta/classes/patch.bbclass index d24aa3b21..9278d25b8 100644 --- a/build/meta/classes/patch.bbclass +++ b/build/meta/classes/patch.bbclass @@ -210,31 +210,19 @@ python patch_save_pristine() { # second, unused patchset next to the base recipe. IB_PATCHSET_DIR ??= "${FILE_DIRNAME}/files" -# Infrabase patch generation algorithm +# Stage what was edited in IB_TARGET since do_attach_infrabase, the baseline +# being the attach manifest: one "pristine -> IB_TARGET" diff per file in +# ${IB_PATCHSET_DIR}/${PF}/, listed in .edited for do_updiff. A file the user did +# not touch is not looked at, so a patch set updated behind the tree stays intact. # -# Produces per-file patches in ${IB_PATCHSET_DIR}/${PF}/ comparing the -# pristine upstream sources (${S}.pristine, saved by patch_save_pristine -# right after do_unpack) against the local working tree (IB_TARGET). Each -# staged patch is therefore a self-contained "upstream → final" diff for -# one source file; do_updiff can drop it in place at the slot of the -# existing patch for that file, fully replacing the previous content. -# -# Patch headers use git-style "a/" / "b/" labels so the resulting -# patches apply cleanly with `patch -p1` from the source tree root, -# independent of where the project was checked out. Earlier versions of -# this task wrote absolute paths on both sides (e.g. /home/...//.../), -# which silently broke as soon as the repository was cloned anywhere else. -# -# The staging directory ${IB_PATCHSET_DIR}/${PF}/ is wiped and recreated -# on every run so that stale patches from previous invocations do not leak -# into the new patchset (do_updiff promotes this directory in place into -# the existing numbered patchset). +# Without a manifest, every file differing from pristine counts as edited. + +do_diffcompose[prefuncs] += "do_check_attach" python patch_do_diffcompose() { + import fnmatch import os import re - import fnmatch - import shlex import shutil import subprocess @@ -252,16 +240,9 @@ python patch_do_diffcompose() { shutil.rmtree(output_dir) os.makedirs(output_dir) - diff_files_tmp = os.path.join(d.getVar('TMPDIR'), "diff_files.tmp") + # Build artefacts that leak into IB_TARGET when the user runs `make` + # before `updiff`, matched against every file and directory name. - # Enumerate differing/added/removed files. cwd=target_dir so the target - # side of each line is reported as "./". - # - # Excludes filter out build artefacts that leak into IB_TARGET when the - # user runs `make` before `updiff`. Without this filter the patchset - # gets polluted with hundreds of generated files (kconfig output, dtc - # intermediates, kbuild auto-generated headers, etc.). Patterns are - # matched against basenames by `diff -x`. exclude_patterns = [ # compiler / linker object artefacts. NOTE: *.lds is NOT excluded — # SO3 ships hand-written linker scripts (e.g. arch/*/so3.lds) and @@ -310,112 +291,53 @@ python patch_do_diffcompose() { # include/generated/ — kbuild's auto-generated arch headers (cfi.h, # delay.h, etc. from arch/*/include/asm/Kbuild) # include/config/ — kbuild's symbol-tracking files - excludes = ' '.join(f'-x "{p}"' for p in exclude_patterns) - excludes += ' --exclude=.git --exclude=patches' - excludes += ' --exclude=generated --exclude=config' - # Recipe-supplied extra excludes — space-separated directory/file - # basenames (glob), matched by `diff --exclude` at any depth. Used for - # things that vary per recipe and would otherwise flood the patchset, - # most notably an out-of-tree build directory (e.g. QEMU's meson/ninja - # `build/`, which holds 1000+ generated files). A blanket exclude in - # this shared class would be unsafe (another recipe might ship real - # source under such a name), so each recipe opts in via IB_UPDIFF_EXCLUDE. - # - # An entry holding a '/' is a path from the tree root instead (fnmatch - # pattern), for a generated file whose basename a real source shares: - # U-Boot's include/config.h against arch/*/include/asm/config.h. A - # leading '/' names a file at the root itself. + # patches/ is the quilt staging of do_attach_infrabase, generated/ and + # config/ the kbuild-generated trees. A recipe adds its own through + # IB_UPDIFF_EXCLUDE: an entry with a '/' is a path from the tree root (a + # leading '/' names a file at the root), any other a name at any depth. + + names = exclude_patterns + ['.git', '.pc', 'patches', 'generated', 'config'] path_excludes = [] for x in (d.getVar('IB_UPDIFF_EXCLUDE') or '').split(): if '/' in x: path_excludes.append(x.lstrip('/')) else: - excludes += f' --exclude={shlex.quote(x)}' - statement = ( - f'diff -Nrq {excludes} --no-dereference ' - f'{shlex.quote(source_dir)} . > {shlex.quote(diff_files_tmp)}' - ) - subprocess.call(statement, shell=True, cwd=target_dir) - - new_number = 1 - src_norm = source_dir.rstrip('/') + '/' - - with open(diff_files_tmp, "r") as diff_file: - for raw_line in diff_file: - line = raw_line.rstrip('\n') - if not line: - continue + names.append(x) + hidden = re.compile('|'.join(fnmatch.translate(p) for p in names)) - src_path = None - tgt_path = None - rel = None - - # Form 1: "Files and differ" - m = re.match(r'^Files (.+) and (.+) differ$', line) - if m: - src_path = m.group(1) - tgt_path = m.group(2) - if tgt_path.startswith('./'): - rel = tgt_path[2:] - elif src_path.startswith(src_norm): - rel = src_path[len(src_norm):] - else: - bb.warn(f"do_diffcompose: cannot derive relative path for: {line}") - continue - else: - # Form 2: "Only in : " - m = re.match(r'^Only in (.+): (.+)$', line) - if not m: - bb.warn(f"do_diffcompose: unrecognised diff -Nrq line: {line}") - continue - only_dir = m.group(1) - only_name = m.group(2) - full = os.path.join(only_dir, only_name) - if only_dir == source_dir or only_dir.startswith(src_norm): - # Present only in source -> file deleted in target. - src_path = full - rel = os.path.relpath(full, source_dir) - tgt_path = os.path.join('.', rel) - else: - # only_dir is relative to cwd=target_dir; file added locally. - tgt_path = full - rel = os.path.relpath(full, '.') - src_path = os.path.join(source_dir, rel) - - if any(fnmatch.fnmatch(rel, p) for p in path_excludes): - continue + hashes = ib_attach_hashes(target_dir) + if hashes is None: + bb.warn(f"do_diffcompose: no attach manifest for {target_dir}, " + "comparing the whole tree to pristine") - filename = os.path.basename(rel) - output_patch = os.path.join(output_dir, f"{new_number:04d}-{filename}.patch") - - # Per-file unified diff with git-style a/ b/ labels so - # the patch applies cleanly with `patch -p1` regardless of the - # checkout location. - cmd = [ - 'diff', '--no-dereference', '-uN', - '--label', f'a/{rel}', - '--label', f'b/{rel}', - src_path, tgt_path, - ] - with open(output_patch, 'wb') as out: - subprocess.run(cmd, stdout=out, cwd=target_dir, check=False) - - # `diff -uN` emits "Binary files and differ" instead of - # a usable hunk when either side is binary. Writing that as a - # .patch file makes do_patch fail later with "Only garbage was - # found in the patch input". These are typically build - # artefacts (e.g. compiled scripts/kconfig/conf) that leaked - # into IB_TARGET; just drop the patch and move on. - with open(output_patch, 'rb') as f: - first = f.readline() - if first.startswith(b'Binary files '): - bb.note(f"do_diffcompose: skipping binary file: {rel}") - os.remove(output_patch) - continue + edited = [] + for rel in ib_edited_files(target_dir, source_dir, hashes, hidden): + if any(fnmatch.fnmatch(rel, p) for p in path_excludes): + continue - new_number += 1 + output_patch = os.path.join(output_dir, f"{len(edited) + 1:04d}-" + f"{os.path.basename(rel)}.patch") + cmd = ['diff', '--no-dereference', '-uN', + '--label', f'a/{rel}', '--label', f'b/{rel}', + os.path.join(source_dir, rel), os.path.join('.', rel)] + with open(output_patch, 'wb') as out: + subprocess.run(cmd, stdout=out, cwd=target_dir, check=False) + + # A binary file would make do_patch fail with "Only garbage was found + # in the patch input". + + with open(output_patch, 'rb') as f: + binary = f.readline().startswith(b'Binary files ') + if binary: + bb.note(f"do_diffcompose: skipping binary file: {rel}") + os.remove(output_patch) + continue + + edited.append(rel) - os.remove(diff_files_tmp) + with open(os.path.join(output_dir, '.edited'), 'w', + errors='surrogateescape') as f: + f.writelines(rel + '\n' for rel in edited) } def generate_src_uri(patch_directory, header=None): @@ -477,12 +399,73 @@ def index_patchset(directory): idx.setdefault(pid, []).append(fname) return idx +def ib_sha256(path): + """Hex SHA-256 of the file at `path`.""" + import hashlib + + h = hashlib.sha256() + with open(path, 'rb') as f: + for chunk in iter(lambda: f.read(1 << 20), b''): + h.update(chunk) + + return h.hexdigest() + +def ib_attach_hashes(target): + """{rel: sha256} recorded by the last attach of `target`, None without a + manifest. Lines escaped by sha256sum (a name with a newline or a backslash) + are left out.""" + manifest = target + '.attach.sha256' + if not os.path.isfile(manifest): + return None + + hashes = {} + with open(manifest, 'r', errors='surrogateescape') as f: + for line in f: + if line[:1] != '\\' and line[64:68] == ' ./': + hashes[line[68:].rstrip('\n')] = line[:64] + + return hashes + +def ib_edited_files(target, pristine, hashes, hidden): + """Paths edited in `target`, created and deleted ones included, compared + to the `hashes` of the attach, or to `pristine` when `hashes` is None. A + file or directory whose name matches the regex `hidden` is skipped, and so + are symlinks, which a patch cannot carry.""" + import filecmp + + edited = [] + for root, dirs, files in os.walk(target): + dirs[:] = [x for x in dirs if not hidden.match(x)] + + for name in files: + path = os.path.join(root, name) + if hidden.match(name) or os.path.islink(path): + continue + + rel = os.path.relpath(path, target) + if hashes is not None: + changed = rel not in hashes or ib_sha256(path) != hashes[rel] + else: + src = os.path.join(pristine, rel) + changed = not os.path.isfile(src) \ + or not filecmp.cmp(src, path, shallow=False) + if changed: + edited.append(rel) + + known = hashes + if known is None: + known = [os.path.relpath(os.path.join(root, name), pristine) + for root, _, files in os.walk(pristine) for name in files] + edited += [rel for rel in known + if not os.path.lexists(os.path.join(target, rel)) + and not any(hidden.match(p) for p in rel.split('/'))] + + return edited + def ib_refresh_attach_manifest(d, rels): """Rewrite the ${IB_TARGET}.attach.sha256 entries for the given relative paths with the files' current hashes: added when the file is new, dropped when it is gone. Other entries are kept as they are.""" - import hashlib - target = d.getVar('IB_TARGET') manifest = target + '.attach.sha256' if not os.path.isfile(manifest): @@ -503,11 +486,7 @@ def ib_refresh_attach_manifest(d, rels): key = './' + rel path = os.path.join(target, rel) if os.path.isfile(path) and not os.path.islink(path): - h = hashlib.sha256() - with open(path, 'rb') as f: - for chunk in iter(lambda: f.read(1 << 20), b''): - h.update(chunk) - entries[key] = h.hexdigest() + entries[key] = ib_sha256(path) else: entries.pop(key, None) @@ -519,41 +498,21 @@ def ib_refresh_attach_manifest(d, rels): addtask do_updiff do_updiff[nostamp] = "1" -# Merge the staged patches produced by do_diffcompose -# (${IB_PATCHSET_DIR}/${PF}/, one "pristine → IB_TARGET" diff per file) back -# into the patch series the recipe actually applies. -# -# The series is read from SRC_URI (src_patches(), the very list do_patch -# applies, in order), so EVERY patchset is seen: the recipe's own files/ and -# those a bbappend brings from another directory (the course's vext layers). -# Looking at the recipe's own files/ alone made updiff blind to the bbappend -# patches: it re-appended their content to the base set, and do_patch then -# applied it twice. +# Fold the files staged by do_diffcompose into the patch series do_patch applies +# (src_patches(), so the bbappend patchsets are seen too). Given the patches of +# the series touching an edited file, its chain: # -# Each patch is split into per-file sections and indexed by target path -# (header path with the patch's striplevel removed, exactly as `patch -pN` -# does — so "./arch/x" and "b/arch/x" are the same file). For each staged -# file, given the CHAIN of series patches that touch it: +# * KEEP: the chain already yields the file, nothing to write. +# * REFUSE: the chain no longer yields what was attached, so the series moved +# behind the tree and rewriting it would revert that change. +# * FOLD: the tail of the chain lying in one patchset (see ib_fold_run) becomes +# one fresh section on top of what the earlier patches leave. A patch losing +# its last section is deleted, and the file reverting to that state only +# removes the tail. +# * APPEND: no patch touches the file: a new patch goes to the last patchset of +# the series with a plain .inc, or to ${IB_PATCHSET_DIR}/0001-${PF}/. # -# * KEEP — the chain already turns pristine into IB_TARGET's content -# (checked by applying it on a scratch copy). Nothing is rewritten, so a -# patch generated by another tool does not churn into an equivalent one. -# * REWRITE — otherwise the LAST patch of the chain gets a fresh section -# for this file, diffed against the state the earlier patches leave -# (pristine + chain[:-1]). The earlier patches are untouched and nothing -# is applied twice. A one-patch chain is the old "consolidate"; longer -# chains (two patchsets on one file, or append-only history) used to be -# refused. Other sections of a multi-file patch are kept as they are. -# * APPEND — no patch touches the file yet: the staged diff becomes a new -# patch at the end of the last patchset of the series whose .inc is a -# plain generated one (the course's, for a vext bbappend), or of -# ${IB_PATCHSET_DIR}/0001-${PF}/ when there is none. -# -# Nothing is written unless every file was resolved: if a chain no longer -# applies, updiff stops with the file named and the patchsets untouched. -# Patches whose file is not staged (unchanged since pristine, or excluded) -# are kept as they are. The .inc of a patchset is regenerated only when a -# patch was appended to it. +# Nothing is written unless every file was resolved. def ib_patch_split(path): """Split a patch file into (preamble, [(src, dst, text), ...]), one entry @@ -662,9 +621,59 @@ def ib_inc_is_plain(inc_path): def ib_inc_for(setdir): return setdir.rstrip('/') + '-patches.inc' +def ib_set_is_plain(setdir, pf): + """True for a numbered patchset of `pf` whose .inc is a generated one.""" + import re + + return bool(re.match(r'^\d{4}-' + re.escape(pf) + r'$', + os.path.basename(setdir))) \ + and ib_inc_is_plain(ib_inc_for(setdir)) + +def ib_patch_has_text(preamble): + """True when a patch's preamble holds a description, not just the headers + `diff` or git print.""" + import re + + return any(not re.match(r'^(diff |index |new file|deleted file|Index: |=+$|$)', + line) + for line in preamble.splitlines()) + +def ib_foldable(entry, pf): + """True when updiff may rewrite or delete this patch. Patchsets stay apart + through their .inc, and a description is someone's work to keep.""" + return entry['strip'] == 1 and not ib_patch_has_text(entry['preamble']) \ + and ib_set_is_plain(os.path.dirname(entry['path']), pf) + +def ib_fold_run(chain, pf): + """The tail of `chain` to merge: its last link, plus the links before it + in the same patchset. A base recipe and a bbappend are never merged.""" + last = chain[-1] + if not ib_foldable(last[0], pf): + return [last] + + setdir = os.path.dirname(last[0]['path']) + run = [last] + for link in reversed(chain[:-1]): + if os.path.dirname(link[0]['path']) != setdir \ + or not ib_foldable(link[0], pf): + break + run.insert(0, link) + + return run + +def ib_inc_drop(path): + """Remove the deleted patch `path` from its patchset's .inc.""" + inc_path = ib_inc_for(os.path.dirname(path)) + uri = 'file://' + os.path.basename(path) + + with open(inc_path) as f: + lines = [l for l in f if l.split(';')[0].split()[:1] != [uri]] + with open(inc_path, 'w') as f: + f.writelines(lines) + python do_updiff() { + import hashlib import os - import re import shutil import subprocess import tempfile @@ -678,8 +687,16 @@ python do_updiff() { bb.fatal(f"do_updiff: staging directory {staging} not found " "(run do_diffcompose first?)") + def fail(msg): + shutil.rmtree(staging, ignore_errors=True) + bb.fatal(f"do_updiff: {msg} Nothing was written.") + series, index = ib_patch_series(d) staged = index_patchset(staging) + hashes = ib_attach_hashes(target) + + with open(os.path.join(staging, '.edited'), errors='surrogateescape') as f: + edited = sorted(line.rstrip('\n') for line in f) # A real edit adds a handful of files. Dozens of new ones is a built tree # seen through an incomplete exclude list: refuse before writing anything. @@ -687,20 +704,17 @@ python do_updiff() { limit = int(d.getVar('IB_UPDIFF_MAX_NEW') or 20) new = sorted(rel for rel in staged if rel not in index) if len(new) > limit: - shutil.rmtree(staging) - bb.fatal(f"do_updiff: {len(new)} files in {target} have no patch yet " - f"(limit {limit}), e.g. {', '.join(new[:5])}. That is build " - "output taken for source: name it in IB_UPDIFF_EXCLUDE, or " - "raise IB_UPDIFF_MAX_NEW if the count is right. Nothing was " - "written.") + fail(f"{len(new)} files in {target} have no patch yet (limit {limit}), " + f"e.g. {', '.join(new[:5])}. That is build output taken for " + "source: name it in IB_UPDIFF_EXCLUDE, or raise IB_UPDIFF_MAX_NEW " + "if the count is right.") # Where new patches go: the last patchset of the series with a plain # .inc, else the recipe's own 0001-${PF}/ (created on first use). append_dir = None for entry in reversed(series): setdir = os.path.dirname(entry['path']) - if re.match(r'^\d{4}-' + re.escape(pf) + r'$', os.path.basename(setdir)) \ - and ib_inc_is_plain(ib_inc_for(setdir)): + if ib_set_is_plain(setdir, pf): append_dir = setdir break if append_dir is None: @@ -717,66 +731,84 @@ python do_updiff() { kept, rewritten, rewrites, appends = [], [], {}, [] tmpdir = tempfile.mkdtemp(prefix='updiff-', dir=d.getVar('TMPDIR')) try: - for rel, snames in sorted(staged.items()): + for rel in edited: chain = index.get(rel, []) if not chain: - appends.append((rel, os.path.join(staging, snames[0]))) + if rel in staged: + appends.append((rel, os.path.join(staging, staged[rel][0]))) continue final = final_of(rel) + run = ib_fold_run(chain, pf) try: - if ib_apply_chain(rel, chain, pristine, tmpdir) == final: + replay = ib_apply_chain(rel, chain, pristine, tmpdir) + if replay == final: kept.append(rel) continue - base = ib_apply_chain(rel, chain[:-1], pristine, tmpdir) + + digest = None if replay is None \ + else hashlib.sha256(replay).hexdigest() + if hashes is not None and digest != hashes.get(rel): + fail(f"{rel} was edited and its patches changed since the " + "attach. Save the edit, re-attach with " + "IB_FORCE_ATTACH=1, then redo it.") + + base = ib_apply_chain(rel, chain[:-len(run)], pristine, tmpdir) except RuntimeError as e: - shutil.rmtree(tmpdir, ignore_errors=True) - bb.fatal(f"do_updiff: {rel}: the series no longer applies " - f"({e}). Nothing was written.") + fail(f"{rel}: the series no longer applies ({e}).") + head, section = run[0] if base == final: - shutil.rmtree(tmpdir, ignore_errors=True) - bb.fatal(f"do_updiff: {rel} is back to its state before " - f"{os.path.basename(chain[-1][0]['path'])}: that " - "patch would become empty. Remove its section by " - "hand (and the patch from its .inc if it was the only " - "one). Nothing was written.") - - a = os.path.join(tmpdir, 'a') - b = os.path.join(tmpdir, 'b') - for path, content in ((a, base), (b, final)): - if content is None: - if os.path.exists(path): - os.remove(path) - else: - with open(path, 'wb') as f: - f.write(content) - r = subprocess.run(['diff', '-uN', '--label', f'a/{rel}', - '--label', f'b/{rel}', a, b], - capture_output=True, text=True, - errors='surrogateescape') - if r.stdout.startswith('Binary files '): - bb.warn(f"do_updiff: {rel} is binary, skipped") - continue + if not ib_foldable(chain[-1][0], pf): + fail(f"{rel} is back to its state before " + f"{os.path.basename(chain[-1][0]['path'])}: that patch " + "would become empty. Remove its section by hand (and " + "the patch from its .inc if it was the only one).") + text = '' + else: + if head['strip'] != 1: + bb.warn(f"do_updiff: {rel}: {os.path.basename(head['path'])} " + f"uses striplevel={head['strip']}, skipped") + continue - # Rewritten sections must apply with the patch's own striplevel; - # do_diffcompose labels are a/ b/, i.e. -p1. - entry, n = chain[-1] - if entry['strip'] != 1: - bb.warn(f"do_updiff: {rel}: {os.path.basename(entry['path'])} " - f"uses striplevel={entry['strip']}, skipped") - continue - rewrites.setdefault(entry['path'], (entry, {}))[1][n] = r.stdout + a = os.path.join(tmpdir, 'a') + b = os.path.join(tmpdir, 'b') + for path, content in ((a, base), (b, final)): + if content is None: + if os.path.exists(path): + os.remove(path) + else: + with open(path, 'wb') as f: + f.write(content) + r = subprocess.run(['diff', '-uN', '--label', f'a/{rel}', + '--label', f'b/{rel}', a, b], + capture_output=True, text=True, + errors='surrogateescape') + if r.stdout.startswith('Binary files '): + bb.warn(f"do_updiff: {rel} is binary, skipped") + continue + text = r.stdout + + rewrites.setdefault(head['path'], (head, {}))[1][section] = text + for entry, n in run[1:]: + rewrites.setdefault(entry['path'], (entry, {}))[1][n] = '' rewritten.append(rel) finally: shutil.rmtree(tmpdir, ignore_errors=True) # Second pass: write. + + removed = [] for path, (entry, new) in rewrites.items(): + sections = [new.get(n, s[2]) for n, s in enumerate(entry['sections'])] + if not any(sections) and not ib_patch_has_text(entry['preamble']): + os.remove(path) + ib_inc_drop(path) + removed.append(path) + continue + with open(path, 'w', errors='surrogateescape') as f: - f.write(entry['preamble']) - for n, (_, _, text) in enumerate(entry['sections']): - f.write(new.get(n, text)) + f.write(entry['preamble'] + ''.join(sections)) if appends: os.makedirs(append_dir, exist_ok=True) @@ -802,17 +834,21 @@ python do_updiff() { with open(inc_path, 'w') as f: f.write(generate_src_uri(append_dir, header)) - # The series now yields IB_TARGET's content for every file handled, so - # move those files' attach-manifest entries to it (see base.bbclass: the - # dirty-tree guards would otherwise keep flagging what was just captured). + # The series now yields these files, so the dirty-tree guards of + # base.bbclass must stop flagging them. + ib_refresh_attach_manifest(d, kept + rewritten + [rel for rel, _ in appends]) shutil.rmtree(staging) + if not edited: + bb.plain("do_updiff: nothing edited since the attach") + return + sets = sorted({os.path.relpath(os.path.dirname(path), d.getVar('IB_DIR')) for path in rewrites}) bb.plain(f"do_updiff: {len(kept)} unchanged, {len(rewritten)} rewritten, " - f"{len(appends)} appended" + f"{len(removed)} merged away, {len(appends)} appended" + (f" (into {os.path.relpath(append_dir, d.getVar('IB_DIR'))})" if appends else "") + (f"; patchsets touched: {', '.join(sets)}" if sets else "")) diff --git a/doc/source/build_system/build_system.rst b/doc/source/build_system/build_system.rst index 8eee65c1e..e7a9e4181 100644 --- a/doc/source/build_system/build_system.rst +++ b/doc/source/build_system/build_system.rst @@ -259,9 +259,10 @@ clean, and a ``clean`` of a recipe drops the manifest on purpose. .. warning:: - It has to be noted that the generated patches are issued from the difference between the local - files and the original **patched** files. This leads to an incremental patching process. - The *diff* process is always done against the directory which is stored in ``tmp/work//`` + ``do_updiff`` only looks at what changed in the attached tree since ``do_attach_infrabase``, using + the manifest recorded there. The patches themselves are computed from ``${S}.pristine``, the + untouched upstream sources in ``tmp/work//``: the series is replayed on it, not read from + the patched ``${S}``. Building a patchset @@ -280,9 +281,17 @@ As result, the patchset is generated in ``build/meta-linux/recipes-linux/linux/f the file ``000x-linux-5.10-r0-patches.inc`` and its associated directory called ``000x-linux-5.10-r0`` in which the set of patches is located. -The prefix is made of four digits and is incremented at each patchset generation. +The patchset is folded in place, not extended with a patch of the patch. For each edited file: -Based on these two elements, the patchset can be manually worked out. +* The patches touching it at the end of the series, within one patchset, become a single patch: the + first of them is rewritten, the others lose their section, and a patch left empty is deleted along + with its line in the ``.inc``. A patch carrying a description is left out of this merge. +* A patch of another patchset is never merged, so a bbappend's series stays apart from its base recipe. +* A file no patch touches gets a new patch at the end of the last generated patchset of the series. +* If the patches of an edited file changed since the attach, for example after a ``git pull``, + ``do_updiff`` stops without writing anything, as rewriting them would revert that change. + +Files that were not edited are never looked at. To include a patchset in a recipe, the recipe file has to include the following lines: @@ -298,7 +307,7 @@ the first patchset should be called with prefix ``0001-`` Excluding generated files ========================= -``do_updiff`` diffs the whole attached tree, so anything *generated* in it would end up in the patchset. +``do_updiff`` walks the whole attached tree, so anything *generated* in it would read as a new file. The shared exclusions (``.git``, ``patches``, the kbuild leftovers, …) live in the ``patch`` class, and a recipe adds its own with ``IB_UPDIFF_EXCLUDE`` — a space-separated list of file or directory names matched at any depth. The QEMU recipe is the clearest case: From 992930259f0684ed393c45b3638d1b5e2e456749 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 14:14:10 +0100 Subject: [PATCH 2/9] updiff: ignore the attach traces of a nested tree usr-so3 attaches into so3/usr, and leaves usr.back, usr.attach.sha256 and the like next to it, inside the so3 tree. updiff of so3 took them for new files and hit IB_UPDIFF_MAX_NEW on an untouched tree, as soon as a usr.back existed. These are the build system's own files, in every tree that nests another, so the class excludes them rather than each recipe. --- build/meta/classes/patch.bbclass | 3 +++ 1 file changed, 3 insertions(+) diff --git a/build/meta/classes/patch.bbclass b/build/meta/classes/patch.bbclass index 9278d25b8..868affdb0 100644 --- a/build/meta/classes/patch.bbclass +++ b/build/meta/classes/patch.bbclass @@ -285,6 +285,9 @@ python patch_do_diffcompose() { 'efi_miniapp_*.h', # initramfs build deps '.initramfs_*', + # what do_attach_infrabase leaves next to a tree nested in this one + # (so3/usr in so3) + '*.attach.sha256', '*.attach.pf', '*.attach.series', '*.back', ] # Exclude the quilt working directory + kbuild-generated trees: # patches/ — quilt staging from do_attach_infrabase From 47d23b014c8e28faaa05bec43fdbef63aba5f861 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 14:14:34 +0100 Subject: [PATCH 3/9] updiff: refuse a tree built with patches no longer in the series The series depends on the overrides and the stamps do not, so a tree built with :lvgl keeps the lvgl changes once the override is removed. Untouched files are no longer looked at, but an edited one had no chain left: the whole of what the vanished patch brought was appended with the edit. do_attach_infrabase now records the series in ${IB_TARGET}.attach.series, and do_updiff refuses an edit on a tree holding a patch that left it. Patches added since the attach stay allowed: the replay check already handles them. --- .gitignore | 1 + build/meta/classes/base.bbclass | 30 ++++++++++++++++++++++++++++++ build/meta/classes/patch.bbclass | 19 ++++++++++++++++++- 3 files changed, 49 insertions(+), 1 deletion(-) diff --git a/.gitignore b/.gitignore index d4c1b8da0..5a29dee13 100644 --- a/.gitignore +++ b/.gitignore @@ -54,6 +54,7 @@ build/cache # attached component tree, so the next attach can refuse to clobber local edits. *.attach.sha256 *.attach.pf +*.attach.series **/doxy/** **/generated/** diff --git a/build/meta/classes/base.bbclass b/build/meta/classes/base.bbclass index 7f462e6c5..600b2dd62 100644 --- a/build/meta/classes/base.bbclass +++ b/build/meta/classes/base.bbclass @@ -530,6 +530,36 @@ python ib_clean_guard() { } do_clean[prefuncs] += "ib_clean_guard" +# The patches SRC_URI applies depend on the overrides, and the stamps do not: +# changing an override leaves the tree as it was built. The series that built +# the tree is therefore recorded in ${IB_TARGET}.attach.series for do_updiff. + +def ib_series_names(d): + names = set() + for uri in (d.getVar('SRC_URI') or '').split(): + if uri.startswith('file://'): + name = os.path.basename(uri[len('file://'):].split(';')[0]) + if name.endswith(('.patch', '.diff')): + names.add(name) + return names + +def ib_attached_series(d): + try: + with open(d.getVar('IB_TARGET') + '.attach.series') as f: + return set(f.read().split()) + except OSError: + return None + +def ib_record_attached_series(d, names): + with open(d.getVar('IB_TARGET') + '.attach.series', 'w') as f: + f.writelines(n + '\n' for n in sorted(names)) + +python ib_attach_series() { + if d.getVar('IB_TARGET'): + ib_record_attached_series(d, ib_series_names(d)) +} +do_attach_infrabase[postfuncs] += "ib_attach_series" + do_attach_infrabase () { ib_manifest="${IB_TARGET}.attach.sha256" diff --git a/build/meta/classes/patch.bbclass b/build/meta/classes/patch.bbclass index 868affdb0..64c86198b 100644 --- a/build/meta/classes/patch.bbclass +++ b/build/meta/classes/patch.bbclass @@ -701,6 +701,18 @@ python do_updiff() { with open(os.path.join(staging, '.edited'), errors='surrogateescape') as f: edited = sorted(line.rstrip('\n') for line in f) + # A patch that built the tree but left the series makes an edited file look + # unpatched: all it brought would be appended with the edit. + + attached = ib_attached_series(d) + gone = (attached or set()) - ib_series_names(d) + if gone and edited: + fail(f"{target} was built with patches no longer in the series " + f"({', '.join(sorted(gone)[:5])}): an override probably changed " + "since the build. Restore it to fold your edits, or run " + f"'./scripts/build.sh -c {d.getVar('PN')}' to rebuild the tree " + "from the current series.") + # A real edit adds a handful of files. Dozens of new ones is a built tree # seen through an incomplete exclude list: refuse before writing anything. @@ -801,7 +813,7 @@ python do_updiff() { # Second pass: write. - removed = [] + removed, added = [], set() for path, (entry, new) in rewrites.items(): sections = [new.get(n, s[2]) for n, s in enumerate(entry['sections'])] if not any(sections) and not ib_patch_has_text(entry['preamble']): @@ -821,6 +833,7 @@ python do_updiff() { for rel, spath in appends: name = f"{next_number:04d}-{os.path.basename(rel)}.patch" shutil.copyfile(spath, os.path.join(append_dir, name)) + added.add(name) next_number += 1 inc_path = ib_inc_for(append_dir) @@ -837,6 +850,10 @@ python do_updiff() { with open(inc_path, 'w') as f: f.write(generate_src_uri(append_dir, header)) + if attached is not None: + ib_record_attached_series(d, (attached | added) + - {os.path.basename(p) for p in removed}) + # The series now yields these files, so the dirty-tree guards of # base.bbclass must stop flagging them. From 7152f747759ce31f70d57b58b594692d9664a97e Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 14:14:34 +0100 Subject: [PATCH 4/9] usr-so3 (lvgl): restore the base tree on clean so3/ is gitignored since it is fetched, so the git checkout of the do_clean restored nothing and the next do_unpack took the lvgl CMakeLists blocks for pristine. The clean was also skipped once :lvgl was removed, leaving nothing able to clean such a tree. Restore from the ${S}/usr of the so3 recipe, which also ships some of the files the series replaces, and run when the tree was attached with the series. Any other tree is left alone, as a clean keeps local edits. --- .../recipes-usr/lvgl/usr-so3_1.0.bbappend | 52 ++++++++++++++----- 1 file changed, 39 insertions(+), 13 deletions(-) diff --git a/build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend b/build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend index 1be107b06..cdfebead4 100644 --- a/build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend +++ b/build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend @@ -70,24 +70,29 @@ python do_handle_fetch_git() { # bitbake owns WORKDIR; we only purge the fetched lvgl tree. python do_clean:append() { import os, shutil, subprocess - if 'lvgl' not in (d.getVar('OVERRIDES') or '').split(':'): + + # The tree holds the lvgl series if it was attached with it, whatever the + # overrides say now. Any other tree is left alone: a clean keeps local edits. + + series = {os.path.basename(u) for u in (d.getVar('LVGL_PATCHES') or '').split()} + if 'lvgl' not in (d.getVar('OVERRIDES') or '').split(':') \ + and not series & (ib_attached_series(d) or set()): return target = d.getVar('IB_TARGET') s = d.getVar('S') ib_dir = d.getVar('IB_DIR') - # Everything the :lvgl override creates in the committed-but-build-mutated - # usr/ tree (lib/slv, lib/lvgl, lib/lv_conf.h, the lvgl_*.elf sources and - # fillfb.c). do_attach_infrabase mirrors the patched ${S} back into - # IB_TARGET, so these end up in BOTH; remove from both so the next :lvgl - # build re-applies the creation patches onto a clean base instead of - # failing with "already exists" (idempotent :lvgl rebuilds). + # Everything the :lvgl override creates or replaces. do_attach_infrabase + # mirrors the patched ${S} back into IB_TARGET, so these end up in BOTH. + created = [ 'lib/lvgl', 'lib/slv', 'lib/lv_conf.h', 'src/lib', 'src/fillfb.c', 'src/lvgl_demo.c', 'src/lvgl_perf.c', 'src/lvgl_benchmark.c', 'src/lvgl_widgets.c', ] + cmakelists = ['lib/CMakeLists.txt', 'src/CMakeLists.txt'] + for base in (target, s): if not base: continue @@ -101,11 +106,32 @@ python do_clean:append() { except OSError: pass - # The lvgl CMakeLists blocks are added by the :lvgl patches to the tracked - # lib/CMakeLists.txt and src/CMakeLists.txt; restore them to the committed - # lvgl-free base (git index) so the tree fully matches the base again. - if ib_dir and os.path.isdir(os.path.join(ib_dir, '.git')): - for rel in ('lib/CMakeLists.txt', 'src/CMakeLists.txt'): + # usr/ belongs to the so3 recipe, so its ${S} is the lvgl-free base, some of + # these files included. Without a fetched so3, usr/ is under git. + + usr = None + try: + with open(d.getVar('IB_SO3_PATH') + '.attach.pf') as f: + pf = f.read().strip() + usr = os.path.join(d.getVar('TMPDIR'), 'work', pf, pf.rsplit('-', 1)[0], 'usr') + except OSError: + pass + + if usr and os.path.isdir(usr): + for rel in created + cmakelists: + src = os.path.join(usr, rel) + dst = os.path.join(target, rel) + if os.path.isdir(src): + shutil.copytree(src, dst, symlinks=True) + elif os.path.isfile(src): + shutil.copyfile(src, dst) + elif ib_dir and os.path.isdir(os.path.join(ib_dir, '.git')): + for rel in cmakelists: subprocess.run(['git', '-C', ib_dir, 'checkout', '--', os.path.join(target, rel)], check=False) -} \ No newline at end of file + + try: + os.remove(target + '.attach.series') + except OSError: + pass +} From 7fb5c10b169bc4239faa0ee0537fe12bdea07fdd Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 14:18:45 +0100 Subject: [PATCH 5/9] updiff: leave alone what a neighbouring recipe attached so3 and usr-so3 both write so3/usr. With :lvgl, updiff of so3 took the 2000-odd files usr-so3 had attached for its own edits, and a file folded through one recipe came back as an edit for the other. A file identical to what the recipe sharing the tree attached is now that recipe's. An append into a patch set no recipe requires applies nothing, yet was recorded as part of the series: the next updiff took the tree for one built with another series and refused. It now warns and records nothing. --- build/meta/classes/patch.bbclass | 34 ++++++++++++++++++++++++++++++-- 1 file changed, 32 insertions(+), 2 deletions(-) diff --git a/build/meta/classes/patch.bbclass b/build/meta/classes/patch.bbclass index 64c86198b..fd705010d 100644 --- a/build/meta/classes/patch.bbclass +++ b/build/meta/classes/patch.bbclass @@ -429,13 +429,35 @@ def ib_attach_hashes(target): return hashes +def ib_neighbour_hashes(target): + """{rel: sha256}, relative to `target`, of what the recipes sharing it + attached: so3 and usr-so3 both write so3/usr, from either side.""" + import glob + + suffix = '.attach.sha256' + hashes = {} + for manifest in glob.glob(glob.escape(target) + '/*' + suffix): + name = os.path.basename(manifest)[:-len(suffix)] + nested = ib_attach_hashes(os.path.join(target, name)) or {} + hashes.update({os.path.join(name, rel): h for rel, h in nested.items()}) + + parent, name = os.path.split(os.path.normpath(target)) + prefix = name + '/' + for rel, h in (ib_attach_hashes(parent) or {}).items(): + if rel.startswith(prefix): + hashes[rel[len(prefix):]] = h + + return hashes + def ib_edited_files(target, pristine, hashes, hidden): """Paths edited in `target`, created and deleted ones included, compared to the `hashes` of the attach, or to `pristine` when `hashes` is None. A file or directory whose name matches the regex `hidden` is skipped, and so - are symlinks, which a patch cannot carry.""" + are symlinks, which a patch cannot carry. A file as a neighbouring recipe + attached it is that recipe's, not an edit.""" import filecmp + neighbours = ib_neighbour_hashes(target) edited = [] for root, dirs, files in os.walk(target): dirs[:] = [x for x in dirs if not hidden.match(x)] @@ -452,7 +474,7 @@ def ib_edited_files(target, pristine, hashes, hidden): src = os.path.join(pristine, rel) changed = not os.path.isfile(src) \ or not filecmp.cmp(src, path, shallow=False) - if changed: + if changed and neighbours.get(rel) != ib_sha256(path): edited.append(rel) known = hashes @@ -836,6 +858,14 @@ python do_updiff() { added.add(name) next_number += 1 + # A set the recipe does not require yet applies nothing, so what it + # holds did not join the series. + + if append_dir not in {os.path.dirname(e['path']) for e in series}: + added.clear() + bb.warn(f"do_updiff: {ib_inc_for(append_dir)} is not used yet: " + "require it from the recipe") + inc_path = ib_inc_for(append_dir) header = None if os.path.isfile(inc_path): From ec02c7bd5dccb38e0369d75814ffa9f548b7e801 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 14:18:45 +0100 Subject: [PATCH 6/9] so3: keep the build outputs out of updiff --- build/meta-so3/recipes-so3/so3/so3_6.3.1.bb | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/build/meta-so3/recipes-so3/so3/so3_6.3.1.bb b/build/meta-so3/recipes-so3/so3/so3_6.3.1.bb index f7ae209fd..04251d66f 100644 --- a/build/meta-so3/recipes-so3/so3/so3_6.3.1.bb +++ b/build/meta-so3/recipes-so3/so3/so3_6.3.1.bb @@ -21,6 +21,11 @@ OVERRIDES:append = ":so3" IB_TARGET = "${IB_SO3_PATH}" +# The build leaves its arch marker, the usr-so3 CMake directory and the rendered +# ITS/ITB in this tree. Upstream SO3 has no directory of either name. + +IB_UPDIFF_EXCLUDE = ".ib_last_arch build images" + # Infrabase does not embed the SO3 sources. Same revision as the AVZ recipe: # both are the same kernel tree, and move together. From b6b15aec80824f693569db73b419e695cf7cd84e Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 15:37:21 +0100 Subject: [PATCH 7/9] usr-linux (lvgl): drop the patch repeating the base CMakeLists The base tree already adds lvgl and graphic: 0001-CMakeLists.txt.patch added them a second time, which do_configure then removed with a warning. The tree came out equal to the base, but no longer to its series, so updiff took the untouched file for an edit undoing the patch and stopped. --- .../lvgl/files/0001-usr-linux-1.0-r0-patches.inc | 1 - .../files/0001-usr-linux-1.0-r0/0001-CMakeLists.txt.patch | 8 -------- 2 files changed, 9 deletions(-) delete mode 100644 build/meta-usr/recipes-usr/lvgl/files/0001-usr-linux-1.0-r0/0001-CMakeLists.txt.patch diff --git a/build/meta-usr/recipes-usr/lvgl/files/0001-usr-linux-1.0-r0-patches.inc b/build/meta-usr/recipes-usr/lvgl/files/0001-usr-linux-1.0-r0-patches.inc index 4577cf6ea..99a3013e8 100644 --- a/build/meta-usr/recipes-usr/lvgl/files/0001-usr-linux-1.0-r0-patches.inc +++ b/build/meta-usr/recipes-usr/lvgl/files/0001-usr-linux-1.0-r0-patches.inc @@ -1,5 +1,4 @@ LVGL_URI:append = "\ - file://0001-CMakeLists.txt.patch \ file://0063-CMakeLists.txt.patch \ file://0008-CMakeLists.txt.patch \ file://0005-LICENSE.patch \ diff --git a/build/meta-usr/recipes-usr/lvgl/files/0001-usr-linux-1.0-r0/0001-CMakeLists.txt.patch b/build/meta-usr/recipes-usr/lvgl/files/0001-usr-linux-1.0-r0/0001-CMakeLists.txt.patch deleted file mode 100644 index 0779a1469..000000000 --- a/build/meta-usr/recipes-usr/lvgl/files/0001-usr-linux-1.0-r0/0001-CMakeLists.txt.patch +++ /dev/null @@ -1,8 +0,0 @@ ---- a/src/CMakeLists.txt -+++ b/src/CMakeLists.txt -@@ -1 +1,3 @@ - add_subdirectory(examples) -+add_subdirectory(lvgl) -+add_subdirectory(graphic) - - From 26891c8695c987e3bdfbc63a45f135f1f6800050 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 15:48:45 +0100 Subject: [PATCH 8/9] usr-so3 (lvgl): find the so3 tree from IB_TARGET IB_SO3_PATH comes from the so3 class, which usr-so3 does not inherit: every clean of a tree holding the lvgl series died on a TypeError. --- build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend b/build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend index cdfebead4..c2ca68083 100644 --- a/build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend +++ b/build/meta-usr/recipes-usr/lvgl/usr-so3_1.0.bbappend @@ -111,7 +111,7 @@ python do_clean:append() { usr = None try: - with open(d.getVar('IB_SO3_PATH') + '.attach.pf') as f: + with open(os.path.dirname(target) + '.attach.pf') as f: pf = f.read().strip() usr = os.path.join(d.getVar('TMPDIR'), 'work', pf, pf.rsplit('-', 1)[0], 'usr') except OSError: From b1b3f883a0276a36f5fe848c18f18208307123f1 Mon Sep 17 00:00:00 2001 From: Daniel Rossier Date: Sat, 7 Nov 2026 15:48:45 +0100 Subject: [PATCH 9/9] build: space out the comments and document the updiff helpers A blank line after the comment blocks of these classes, and a short description for the two functions local to do_updiff. --- build/meta-usr/classes/usr.bbclass | 1 + build/meta/classes/base.bbclass | 5 +++++ build/meta/classes/patch.bbclass | 7 +++++++ 3 files changed, 13 insertions(+) diff --git a/build/meta-usr/classes/usr.bbclass b/build/meta-usr/classes/usr.bbclass index b16b79880..9484a01c2 100644 --- a/build/meta-usr/classes/usr.bbclass +++ b/build/meta-usr/classes/usr.bbclass @@ -11,6 +11,7 @@ inherit rootfs # updiff turns every CMake-generated file into a patch. Neither the linux nor # the so3 usr tree ships a directory of that name. .ib_last_arch is the arch # marker do_build writes, .ib_last_toolchain the one usr-so3 writes. + IB_UPDIFF_EXCLUDE:append = " build .ib_last_arch .ib_last_toolchain" # Deployment of user space components diff --git a/build/meta/classes/base.bbclass b/build/meta/classes/base.bbclass index 600b2dd62..a74d94738 100644 --- a/build/meta/classes/base.bbclass +++ b/build/meta/classes/base.bbclass @@ -408,6 +408,7 @@ do_unpack[postfuncs] = "do_handle_fetch_git" # Default to the safe behaviour; set IB_FORCE_ATTACH=1 (env or local.conf) # to override the dirty-tree guards below. + IB_FORCE_ATTACH ??= "0" # Edits in ${IB_TARGET} that the patch set does not hold. @@ -430,6 +431,7 @@ IB_FORCE_ATTACH ??= "0" # artefacts and refuse a perfectly clean tree. Filtered here as well as # pruned at attach time, so manifests recorded before that fix stop # blocking too. + def ib_unfolded_edits(d): import os import re @@ -475,6 +477,7 @@ def ib_guard_unfolded_edits(d, action, consequence): # do_updiff) would never re-run do_patch/do_attach_infrabase. Each file is also # registered as a parse dependency, so editing one invalidates the parse cache # and the digest is recomputed. Call it from anonymous python. + def ib_patchset_digest(d): import hashlib @@ -497,6 +500,7 @@ def ib_patchset_digest(d): # patch, a SRCREV rolled back) finds its old stamp still there, BitBake deems the # task current, and the tree is silently left at the newer content. Add it to # the task's prefuncs; the stamp for the current key is written after the task. + python ib_drop_stale_stamps() { import glob @@ -519,6 +523,7 @@ do_attach_infrabase[prefuncs] += "ib_attach_guard" # Opt out with IB_CLEAN_GUARD = "0" in a recipe whose own build rewrites # attached files (see usr.bbclass), where the manifest cannot tell an edit # from a build step. + IB_CLEAN_GUARD ??= "1" python ib_clean_guard() { diff --git a/build/meta/classes/patch.bbclass b/build/meta/classes/patch.bbclass index fd705010d..25c2829d9 100644 --- a/build/meta/classes/patch.bbclass +++ b/build/meta/classes/patch.bbclass @@ -208,6 +208,7 @@ python patch_save_pristine() { # in its own layer directory must point it there (with :=, so THISDIR is the # bbappend's): otherwise updiff never sees the existing patches and builds a # second, unused patchset next to the base recipe. + IB_PATCHSET_DIR ??= "${FILE_DIRNAME}/files" # Stage what was edited in IB_TARGET since do_attach_infrabase, the baseline @@ -348,6 +349,7 @@ def generate_src_uri(patch_directory, header=None): if p.endswith(".patch")) # Keep the existing .inc's leading comment block (its copyright and any # notes), so repeated updiff runs don't churn it; standard one otherwise. + src_uri = header or "# Copyright (c) 2025-2026 EDGEMTech SA\n\n" src_uri += "SRC_URI += \"\\ \n" for patch in patches: @@ -498,6 +500,7 @@ def ib_refresh_attach_manifest(d, rels): # sha256sum lines are " ./". A line it escaped (leading # backslash, for a name with a newline or backslash) is kept verbatim. + entries = {} with open(manifest, 'r', errors='surrogateescape') as f: for line in f: @@ -713,6 +716,7 @@ python do_updiff() { "(run do_diffcompose first?)") def fail(msg): + """Stop on `msg`, leaving the patch sets as they were.""" shutil.rmtree(staging, ignore_errors=True) bb.fatal(f"do_updiff: {msg} Nothing was written.") @@ -748,6 +752,7 @@ python do_updiff() { # Where new patches go: the last patchset of the series with a plain # .inc, else the recipe's own 0001-${PF}/ (created on first use). + append_dir = None for entry in reversed(series): setdir = os.path.dirname(entry['path']) @@ -758,6 +763,7 @@ python do_updiff() { append_dir = os.path.join(d.getVar('IB_PATCHSET_DIR'), f"0001-{pf}") def final_of(rel): + """Content of `rel` in the tree, None if it is gone.""" path = os.path.join(target, rel) if os.path.isfile(path) and not os.path.islink(path): with open(path, 'rb') as f: @@ -765,6 +771,7 @@ python do_updiff() { return None # First pass: decide everything, write nothing. + kept, rewritten, rewrites, appends = [], [], {}, [] tmpdir = tempfile.mkdtemp(prefix='updiff-', dir=d.getVar('TMPDIR')) try: