From 9697f60bc27e319bdc024629d72159fd858467aa Mon Sep 17 00:00:00 2001 From: Thomas Walker Lynch Date: Thu, 12 Nov 2026 07:37:12 +0000 Subject: [PATCH] cascading make --- .../tool/Account-Tree_directory_rename | 149 +++++ administrator/tool/makefile_to_project_mk | 178 +++++ administrator/tool/project_rename | 633 ++++++++++++++++++ developer/tool/build_component/make | 2 +- .../build_component/{makefile => project.mk} | 2 +- shared/tool/makefile/Harmony.mk | 4 +- 6 files changed, 964 insertions(+), 4 deletions(-) create mode 100755 administrator/tool/Account-Tree_directory_rename create mode 100755 administrator/tool/makefile_to_project_mk create mode 100755 administrator/tool/project_rename rename developer/tool/build_component/{makefile => project.mk} (95%) diff --git a/administrator/tool/Account-Tree_directory_rename b/administrator/tool/Account-Tree_directory_rename new file mode 100755 index 0000000..92e2026 --- /dev/null +++ b/administrator/tool/Account-Tree_directory_rename @@ -0,0 +1,149 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +""" +Account-Tree_directory_rename + +Give the directories Account-Tree makes on systems and on storage the +hyphenated name, in the project's code and documents. Run it after +project_rename, in the directory that holds the projects, such as ~/project; +it acts on ./Account-Tree. + + /home/AccountTree becomes /home/Account-Tree + /var/lib/AccountTree becomes /var/lib/Account-Tree + /run/AccountTree becomes /run/Account-Tree + /usr/local/lib/AccountTree becomes /usr/local/lib/Account-Tree + +The name reserved for accounts follows the tree dir, since /home/ would +collide with it. The messages, window titles and unit descriptions that name +Account-Tree, prose a person reads and that nothing keeps, take the +hyphenated name too; a unit file whose description changes is written again +by the next system configure, which still recognizes it by its mark. "consumer/AccountTree" becomes consumer/Account_Tree, the +promoted namespace. The other names Account-Tree gives things on systems, +the unit names, the udev rule file, the storage device names, the mark on +the files it writes, the application id, the temporary file suffix and the +string the database hash begins from, are names other things depend on, and +are left; the lines still naming AccountTree are listed +at the end. + +Only exact strings are changed. Each code constant names its directory once +and everything else derives from it, so the program follows the constants. +Existing systems and storage are moved by hand, under root, with every +storage unplugged: the directories are renamed with mv, and the program is +installed again. This tool changes no system. + +Usage: Account-Tree_directory_rename + Account-Tree_directory_rename preview + + help | -h | --help print this message (also printed when given no arguments) + project act on ./Account-Tree + preview print the log of what would do, change nothing +""" + +import sys ,os ,subprocess +from pathlib import Path + +PROJECT = "Account-Tree" + +PAIR_LIST = [ + ("/usr/local/lib/AccountTree" ,"/usr/local/lib/Account-Tree"), + ("/var/lib/AccountTree" ,"/var/lib/Account-Tree"), + ("/run/AccountTree" ,"/run/Account-Tree"), + ("consumer/AccountTree" ,"consumer/Account_Tree"), + ("home/AccountTree" ,"home/Account-Tree"), + ('TREE_DIR_NAME = "AccountTree"' ,'TREE_DIR_NAME = "Account-Tree"'), + ("holds AccountTree's own files" ,"holds Account-Tree's own files"), + ("The name AccountTree is reserved" ,"The name Account-Tree is reserved"), + # messages, window titles and unit descriptions: prose a person reads, kept nowhere + ("AccountTree mounts a home only at" ,"Account-Tree mounts a home only at"), + ("it existed before AccountTree adopted it" ,"it existed before Account-Tree adopted it"), + ("is not AccountTree's" ,"is not Account-Tree's"), + ("unlocked outside AccountTree," ,"unlocked outside Account-Tree,"), + ("nothing AccountTree plugged in" ,"nothing Account-Tree plugged in"), + ("was not made by AccountTree;" ,"was not made by Account-Tree;"), + ("until AccountTree is\"" ,"until Account-Tree is\""), + ("AccountTree window: GTK 4" ,"Account-Tree window: GTK 4"), + ('set_title(f"AccountTree: ' ,'set_title(f"Account-Tree: '), + ("Description=AccountTree " ,"Description=Account-Tree "), + ('''
  • Whether the names Account-Tree gives things on systems and on storage take the hyphenated form: the tree dir home/Account-Tree, /var/lib/Account-Tree, /run/Account-Tree, /usr/local/lib/Account-Tree, the server's account AccountTree, the systemd units and udev rule, the names of unlocked storage devices, and the line that marks a file Account-Tree wrote. Each is on storage or installed systems already made, so a change to it needs a migration of what exists. Until it is decided they keep the form given here.
  • ''' + ,'''
  • Whether the names Account-Tree gives things on systems and on storage that are not directories take the hyphenated form: the server's account AccountTree, the systemd units and udev rule, the names of unlocked storage devices, the line that marks a file Account-Tree wrote, and the application id. Each is on installed systems already made, so a change to it needs a migration of what exists. Until it is decided they keep the form given here. The directories were renamed to the hyphenated form; the string the database hash begins from keeps AccountTree, since changing it would change the hash of every database already made.
  • '''), +] + + +def file_list(dirpa_root): + """The files git sees, tracked or not yet added. git runs without a shell.""" + run = subprocess.run(["git" ,"-C" ,str(dirpa_root) ,"ls-files" ,"-z" ,"--cached" ,"--others" ,"--exclude-standard"] + ,capture_output=True ,check=True) + rel_set = {Path(p) for p in run.stdout.decode("utf-8").split("\0") if p} + return sorted(rel for rel in rel_set if (dirpa_root / rel).is_file() and not (dirpa_root / rel).is_symlink()) + +def read_text(fpath): + try: + data = fpath.read_bytes() + if b"\0" in data: + return None + return data.decode("utf-8") + except (UnicodeDecodeError ,OSError): + return None + +def convert(dirpa_root ,preview): + """Make the replacements. Returns (files edited, replacements, lines still naming AccountTree).""" + edited ,count ,remaining = 0 ,0 ,[] + # the pairs are applied in order, the open question's text after the paths it lists + for rel in file_list(dirpa_root): + fpath = dirpa_root / rel + text = read_text(fpath) + if text is None: + continue + new = text + n = 0 + for old ,replacement in PAIR_LIST: + n += new.count(old) + new = new.replace(old ,replacement) + if n: + edited += 1 + count += n + print(f" {'would edit' if preview else 'edited':<16}{rel} ({n} mention" + ("" if n == 1 else "s") + ")") + if not preview: + fpath.write_bytes(new.encode("utf-8")) + for number ,line in enumerate(new.split("\n") ,1): + if "AccountTree" in line: + remaining.append((rel ,number ,line.strip())) + return edited ,count ,remaining + +def print_help(): + print(__doc__.strip()) + return 0 + +def CLI(argv=None): + if argv is None: + argv = sys.argv[1:] + if not argv or argv[0] in ("help" ,"-h" ,"--help"): + return print_help() + preview = argv[0] == "preview" + if preview: + argv = argv[1:] + if argv != ["project"]: + print(f"Error: expected the command 'project', given: {' '.join(argv) or 'nothing'}\n" ,file=sys.stderr) + print_help() + return 1 + dirpa_root = Path.cwd() / PROJECT + if not (dirpa_root / ".git").exists(): + print(f"Error: no project {dirpa_root}. Run project_rename first, then this, in the directory that holds the projects." ,file=sys.stderr) + return 1 + + print(f"Account-Tree_directory_rename {'preview ' if preview else ''}project in {dirpa_root}") + edited ,count ,remaining = convert(dirpa_root ,preview) + print() + for rel ,number ,line in remaining: + print(f" {'still names':<16}{rel}:{number}: {line[:120]}") + print() + print("summary:") + print(f" {edited:4d} files edited, {count} mentions changed") + print(f" {len(remaining):4d} lines still name AccountTree") + if preview: + print("preview only: nothing was changed.") + return 0 + +if __name__ == "__main__": + sys.exit(CLI()) diff --git a/administrator/tool/makefile_to_project_mk b/administrator/tool/makefile_to_project_mk new file mode 100755 index 0000000..b606377 --- /dev/null +++ b/administrator/tool/makefile_to_project_mk @@ -0,0 +1,178 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +""" +makefile_to_project_mk + +Rename the project's make settings file, developer/tool/build_component/makefile, +to project.mk, and change the mentions of its path in the files that name it: +Harmony.mk, which includes it, the build component's make script, and the +file's own header. The file is only ever included by Harmony.mk, never run, so +it takes the .mk extension of the other included makefiles. Its content is +kept: a project that customized its settings keeps them. + +Run it in each project, Harmony included, before skeleton_update. A +skeleton_update alone would add Harmony's starting project.mk beside the old +file, and Harmony.mk would then read the starting settings, not the project's. + +The project must already have Harmony.mk version 9.0, the one that includes +the settings file. Nothing is changed unless every file is as expected. + +Usage: makefile_to_project_mk + makefile_to_project_mk preview + + help | -h | --help print this message (also printed when given no arguments) + project act on the project rooted at $REPO_HOME + preview print the log of what would do, change nothing +""" + +import sys ,os +from pathlib import Path + +PATH_OLD = "tool/build_component/makefile" +PATH_NEW = "tool/build_component/project.mk" + +# relative to $REPO_HOME +SETTINGS_OLD = Path("developer") / PATH_OLD +SETTINGS_NEW = Path("developer") / PATH_NEW +HARMONY_MK = Path("shared/tool/makefile/Harmony.mk") +MAKE_SCRIPT = Path("developer/tool/build_component/make") + +INCLUDE_OLD = b"include " + PATH_OLD.encode() + b"\n" +INCLUDE_NEW = b"include " + PATH_NEW.encode() + b"\n" + + +class Log: + def __init__(self ,preview): + self.preview = preview + self.count = {"renamed": 0 ,"edited": 0 ,"current": 0 ,"error": 0} + + def line(self ,tag ,path ,note=""): + if self.preview: + tag = {"renamed": "would rename" ,"edited": "would edit"}.get(tag ,tag) + print(f" {tag:<16}{path}" + (f" ({note})" if note else "")) + + def summary(self): + print() + print("summary:") + print(f" {self.count['renamed']:4d} settings file renamed to project.mk") + print(f" {self.count['edited']:4d} files edited") + print(f" {self.count['current']:4d} files already current") + if self.count["error"]: + print(f" {self.count['error']:4d} errors") + if self.preview: + print("preview only: nothing was changed.") + + +def mention_count(data): + return data.count(PATH_OLD.encode()) + +def problem_list(dirpa_root): + """ + The reasons the project cannot be converted, an empty list when it can. + Checked before anything is changed, so a run changes all or nothing. + """ + problem = [] + old = (dirpa_root / SETTINGS_OLD).is_file() + new = (dirpa_root / SETTINGS_NEW).exists() + if old and new: + problem.append(f"{SETTINGS_OLD} and {SETTINGS_NEW} both exist; merge them by hand") + if not old and not new: + problem.append(f"no {SETTINGS_OLD} or {SETTINGS_NEW}") + + harmony = dirpa_root / HARMONY_MK + if not harmony.is_file(): + problem.append(f"no {HARMONY_MK}") + else: + data = harmony.read_bytes() + if INCLUDE_OLD not in data and INCLUDE_NEW not in data: + problem.append(f"{HARMONY_MK} does not include the settings file; it is older than version 9.0, update it from Harmony first") + + if not (dirpa_root / MAKE_SCRIPT).is_file(): + problem.append(f"no {MAKE_SCRIPT}") + return problem + +def edit(fpath ,rel ,log ,preview ,fpath_read=None): + """ + Replace each mention of the old path in fpath with the new one, byte for + byte otherwise. fpath_read is where the content is read from when the file + has not been renamed yet, as in a preview. + """ + data = (fpath_read or fpath).read_bytes() + n = mention_count(data) + if n == 0: + log.count["current"] += 1 + return + log.line("edited" ,rel ,f"{n} mention" + ("" if n == 1 else "s")) + log.count["edited"] += 1 + if not preview: + # writing to the existing file keeps its mode and owner + fpath.write_bytes(data.replace(PATH_OLD.encode() ,PATH_NEW.encode())) + +def convert(dirpa_root ,log ,preview): + """ + Rename the settings file and edit the mentions. Returns 0 on success, + 1 when the project is not as expected; then nothing is changed. + """ + problem = problem_list(dirpa_root) + for p in problem: + log.line("error" ,p) + log.count["error"] += 1 + if problem: + return 1 + + fpath_old = dirpa_root / SETTINGS_OLD + fpath_new = dirpa_root / SETTINGS_NEW + if fpath_old.is_file(): + log.line("renamed" ,SETTINGS_OLD ,f"now {fpath_new.name}") + log.count["renamed"] += 1 + if not preview: + os.rename(fpath_old ,fpath_new) + + edit(dirpa_root / HARMONY_MK ,HARMONY_MK ,log ,preview) + edit(dirpa_root / MAKE_SCRIPT ,MAKE_SCRIPT ,log ,preview) + edit(fpath_new ,SETTINGS_NEW ,log ,preview + ,fpath_read=fpath_old if (preview and fpath_old.is_file()) else None) + return 0 + + +def print_help(): + print(__doc__.strip()) + return 0 + +def CLI(argv=None): + if argv is None: + argv = sys.argv[1:] + if not argv or argv[0] in ("help" ,"-h" ,"--help"): + return print_help() + + preview = argv[0] == "preview" + if preview: + argv = argv[1:] + if not argv: + print("Error: 'preview' needs a command after it.\n" ,file=sys.stderr) + print_help() + return 1 + + command ,rest = argv[0] ,argv[1:] + if command != "project": + print(f"Error: unknown command '{command}'.\n" ,file=sys.stderr) + print_help() + return 1 + if rest: + print(f"Error: 'project' takes no arguments, given: {' '.join(rest)}" ,file=sys.stderr) + return 1 + repo_home = os.environ.get("REPO_HOME") + if not repo_home: + print("Error: REPO_HOME is not set; run this from a role setup." ,file=sys.stderr) + return 1 + + dirpa_root = Path(repo_home).resolve() + print(f"makefile_to_project_mk {'preview ' if preview else ''}project in {dirpa_root}") + log = Log(preview) + status = convert(dirpa_root ,log ,preview) + log.summary() + return status + +if __name__ == "__main__": + sys.exit(CLI()) diff --git a/administrator/tool/project_rename b/administrator/tool/project_rename new file mode 100755 index 0000000..eed0526 --- /dev/null +++ b/administrator/tool/project_rename @@ -0,0 +1,633 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +""" +project_rename + +Rename a project to its hyphenated name. Run it in the directory that holds +the projects, such as ~/project. It renames the project in the directory +named , then follows the rename in every other project there that +depends on it, through a link shared/project-dependency/, and last +renames the directory to . + +A project name is written with hyphens between its words wherever a hyphen +is allowed. Where the name must be an identifier, in a namespace, a module, a +C symbol or a command in a namespace, it is written with each hyphen made an +underscore. For Man-In-Grey the identifier form is Man_In_Grey, for +Account-Tree it is Account_Tree. + +What is changed: + + - the Opus file, 0pus_, becomes 0pus_ + - in shared/project-dependency, a link named and .init take the + hyphenated name, and the link is pointed at project// + - document file names take the hyphenated name, and references to them + are changed to match + - in the .html documents, outside , the name standing as a word + becomes the hyphenated name; inside it is code, as below + - in code, the old name becomes the identifier form in names, and in + comments and Python docstrings unless it is in a path, a unit or rule + file name or a reverse-domain name; so do the names of namespace + directories and the files in them + - in a code example in a document, the old name becomes the identifier + form unless it is in a path, a unit or rule file name or a reverse-domain + name + - "project-dependency/" and ".init" become the hyphenated name in + every file + +What is logged for editing by hand, with the line: + + - in code, the name in a string, unless the string names a code file this + run renames, such as "$dir/_admin", which is changed. A string is data: it can name a directory + on storage, a device, a file the program wrote and recognizes, or feed a + hash. Changing such a name changes what installed systems and existing + storage hold, and needs a migration this tool cannot judge. In code + other than Python, every line that is not a comment line counts as + possibly in a string. + - in a code example in a document, the name in a path, a unit or rule file + name, or a reverse-domain name + - in .html prose, the name joined to other characters, as in a file name + - in .org, .md and .txt files, which are notes and logs: a log records + what was, and is not to be rewritten + +The files acted on are the files git sees: those it tracks and those not yet +added that .gitignore does not exclude. Products of the build, which are +made again, are left alone. A project in the directory that mentions the +name without depending on it is listed, not changed. The GitHub repository +and the git remote are renamed by hand afterwards, and each role's setup is +run again, since REPO_HOME and PROJECT come from the directory name. + +Checkpoint each project with git first, run preview, then review with git +diff. Nothing is changed unless every rename, in every project, can be made. + +Usage: project_rename + project_rename preview + + help | -h | --help print this message (also printed when given no arguments) + project rename the project in the directory under the current + directory, for example, in ~/project: + project_rename project Man_In_Grey Man-In-Grey + preview ... print the log of what would do, change nothing +""" + +import sys ,os ,re ,io ,subprocess ,tokenize +from pathlib import Path + +DOCUMENT_EXTENSION = {".html" ,".org" ,".md" ,".txt" ,".png" ,".jpg" ,".svg" ,".pdf"} +NOTE_EXTENSION = {".org" ,".md" ,".txt"} +DEPENDENCY_DIR = Path("shared/project-dependency") + +# elements of an .html document whose content is not prose +HTML_CODE_ELEMENT = re.compile(r"(<(RT·code|script|style)\b[^>]*>)(.*?)()" ,re.S) + +# a character that joins a name to a larger token +TOKEN_CHAR = r"[\w·/.\-]" + + +class Log: + def __init__(self ,preview): + self.preview = preview + self.count = {"renamed": 0 ,"retargeted": 0 ,"edited": 0 ,"mention": 0 ,"by_hand": 0} + + def line(self ,tag ,text ,note=""): + if self.preview: + tag = {"renamed": "would rename" ,"retargeted": "would retarget" ,"edited": "would edit"}.get(tag ,tag) + print(f" {tag:<16}{text}" + (f" ({note})" if note else "")) + + def by_hand(self ,rel ,line_number ,line): + self.count["by_hand"] += 1 + print(f" {'edit by hand':<16}{rel}:{line_number}: {line.strip()}") + + def summary(self): + print() + print("summary:") + print(f" {self.count['renamed']:4d} files and directories renamed") + print(f" {self.count['retargeted']:4d} links retargeted") + print(f" {self.count['edited']:4d} files edited, {self.count['mention']} mentions changed") + print(f" {self.count['by_hand']:4d} lines to edit by hand") + if self.preview: + print("preview only: nothing was changed.") + + +class Name: + """ + The forms of one project name. old is the name as written now, new the + hyphenated name, identifier the form used where a hyphen is not allowed. + prose_old is every old form that can stand in prose: the old name, and for + a name with underscores, its words separated by spaces. + """ + def __init__(self ,old ,new): + self.old = old + self.new = new + self.identifier = new.replace("-" ,"_") + self.prose_old = [old] + ([old.replace("_" ," ")] if "_" in old else []) + # old base names of the code files this run renames, other than the bare + # old name, which is ambiguous: it is also the project's name in data + self.renamed_file = set() + +def is_renamed_file_reference(token ,name): + """ + True when token, a word in a string, names a code file this run renames, + alone or as the last part of a path: "$dir/AccountTree_admin". Trailing + punctuation of a sentence is not part of the name. + """ + last = token.rstrip(".,:;!?").rsplit("/" ,1)[-1] + return last in name.renamed_file + + +#-------------------------------------------------------------------------------- +# finding the files + +def tracked_file_list(dirpa_root): + """ + The files git sees, relative to the root, sorted: those it tracks and those + not yet added that .gitignore does not exclude, so a second run before + git add sees the files the first one renamed. git runs without a shell. + """ + run = subprocess.run(["git" ,"-C" ,str(dirpa_root) ,"ls-files" ,"-z" ,"--cached" ,"--others" ,"--exclude-standard"] + ,capture_output=True ,check=True) + rel_set = {Path(p) for p in run.stdout.decode("utf-8").split("\0") if p} + return sorted(rel for rel in rel_set if (dirpa_root / rel).exists() or (dirpa_root / rel).is_symlink()) + +def is_document(rel): + return "document" in rel.parts[:-1] or rel.suffix in DOCUMENT_EXTENSION + +def is_note(rel): + return rel.suffix in NOTE_EXTENSION + +def is_text(fpath): + try: + data = fpath.read_bytes() + data.decode("utf-8") + return b"\0" not in data + except (UnicodeDecodeError ,OSError): + return False + + +#-------------------------------------------------------------------------------- +# what each path becomes + +def renamed_component(component ,rel_parent ,is_file ,is_doc ,name): + """The new form of one path component, or the component unchanged.""" + if name.old not in component: + return component + if rel_parent == Path(".") and component == f"0pus_{name.old}": + return f"0pus_{name.new}" + if rel_parent == DEPENDENCY_DIR: + return component.replace(name.old ,name.new) + if (is_file and is_doc) or "document" in rel_parent.parts: + return component.replace(name.old ,name.new) + return component.replace(name.old ,name.identifier) + +def rename_map(rel_list ,name): + """ + Each path to rename, files and directories, mapped to its new path. A + directory is renamed when one of its components holds the old name. + """ + mapping = {} + for rel in rel_list: + part_new = [] + for i ,component in enumerate(rel.parts): + is_file = i == len(rel.parts) - 1 + rel_parent = Path(*rel.parts[:i]) if i else Path(".") + part_new.append(renamed_component(component ,rel_parent ,is_file ,is_document(rel) ,name)) + for i in range(1 ,len(rel.parts) + 1): + old_prefix = Path(*rel.parts[:i]) + new_prefix = Path(*rel.parts[:i - 1] ,part_new[i - 1]) if i > 1 else Path(part_new[0]) + if old_prefix.name != new_prefix.name: + mapping[old_prefix] = new_prefix + return mapping + + +#-------------------------------------------------------------------------------- +# what each file's content becomes + +def is_system_token(token): + """A token naming a thing on an installed system or on storage.""" + return ("/" in token or "@" in token + or re.search(r"\.(service|rules|socket|timer|target|conf|db|sqlite)\b" ,token) is not None + or re.match(r"(com|org|net)\." ,token) is not None) + +def token_around(text ,start ,end): + """The run of characters around text[start:end] up to whitespace, a quote or a bracket.""" + stop = set(" \t\n\"'`()[]{},;<>=") + a = start + while a > 0 and text[a - 1] not in stop: + a -= 1 + b = end + while b < len(text) and text[b] not in stop: + b += 1 + return text[a:b] + +def line_number(text ,offset ,line_base): + """ + The line of text[offset], counted in the whole file. No edit adds or + removes a newline, so the newlines before a segment, line_base, are the + same in the edited file as in the original. + """ + return line_base + text.count("\n" ,0 ,offset) + 1 + +def edit_exact(text ,pair_list): + """Replace each exact old string with its new one. Returns the text and the count.""" + count = 0 + for old ,new in pair_list: + count += text.count(old) + text = text.replace(old ,new) + return text ,count + +def edit_code_example(text ,name ,line_base ,hand ,frozen=frozenset()): + """ + The old name in a code example in a document becomes the identifier form, + line by line. A line with the name in a system token is left whole and put + on hand, since the example's other mentions on it can name the same data. + line_base is the number of lines before text in the file. + """ + if name.old == name.identifier: + return text ,0 + out ,count ,number = [] ,0 ,line_base + for line in text.splitlines(keepends=True): + number += 1 + if name.old in line: + match_list = list(re.finditer(re.escape(name.old) ,line)) + if number in frozen or any(is_system_token(token_around(line ,m.start() ,m.end())) for m in match_list): + hand.append(number) + else: + count += len(match_list) + line = line.replace(name.old ,name.identifier) + out.append(line) + return "".join(out) ,count + +def replace_span(text ,span_list ,new): + """text with each (start ,end) span replaced by new, spans in order and apart.""" + out ,last = [] ,0 + for start ,end in span_list: + out.append(text[last:start]); out.append(new); last = end + out.append(text[last:]) + return "".join(out) + +def is_python(rel ,text): + return rel.suffix == ".py" or (rel.suffix == "" and text.startswith("#!") and "python" in text.split("\n" ,1)[0]) + +def edit_python(text ,name ,hand): + """ + In Python the old name becomes the identifier form in names, comments and + docstrings. In any other string it is data, which can name a thing on a + system or on storage, so its line is put on hand. A file Python cannot + tokenize is all put on hand. + """ + line_start = [0] + for line in text.splitlines(keepends=True): + line_start.append(line_start[-1] + len(line)) + def offset(row ,col): + return line_start[row - 1] + col + + string_type = {tokenize.STRING} + for kind in ("FSTRING_START" ,"FSTRING_MIDDLE" ,"FSTRING_END"): + if hasattr(tokenize ,kind): + string_type.add(getattr(tokenize ,kind)) + ignore = {tokenize.NL ,tokenize.COMMENT ,tokenize.ENCODING} + + span_list = [] + try: + previous = None + for token in tokenize.generate_tokens(io.StringIO(text).readline): + if name.old in token.string: + start = offset(*token.start) + is_docstring = token.type == tokenize.STRING and previous in (None ,tokenize.NEWLINE ,tokenize.INDENT ,tokenize.DEDENT) + if token.type in string_type and not is_docstring: + # a string is changed whole or not at all: part of a string that is + # data changed would make a value no installed system has + match_list = list(re.finditer(re.escape(name.old) ,token.string)) + if all(is_renamed_file_reference(token_around(token.string ,m.start() ,m.end()) ,name) for m in match_list): + span_list.extend((start + m.start() ,start + m.end()) for m in match_list) + else: + hand.append(line_number(text ,start + match_list[0].start() ,0)) + continue + for m in re.finditer(re.escape(name.old) ,token.string): + at = start + m.start() + if token.type == tokenize.NAME: + span_list.append((at ,at + len(name.old))) + elif token.type == tokenize.COMMENT or is_docstring: + # prose about the code: a system name in it stays as the code has it + if is_system_token(token_around(token.string ,m.start() ,m.end())): + hand.append(line_number(text ,at ,0)) + else: + span_list.append((at ,at + len(name.old))) + + if token.type not in ignore: + previous = token.type + except (tokenize.TokenError ,SyntaxError ,IndentationError): + hand.extend(line_number(text ,m.start() ,0) for m in re.finditer(re.escape(name.old) ,text)) + return text ,0 + span_list.sort() + return replace_span(text ,span_list ,name.identifier) ,len(span_list) + +COMMENT_LEAD = ("#" ,"--" ,"//" ,"/*" ,"*") + +def edit_other_code(text ,name ,hand): + """ + In code other than Python, the old name becomes the identifier form on a + comment line. Anywhere else it can be in a quoted string, which is data, so + its line is put on hand. + """ + out ,count ,number = [] ,0 ,0 + for line in text.splitlines(keepends=True): + number += 1 + if name.old in line: + if line.lstrip().startswith(COMMENT_LEAD) and not line.startswith("#!"): + # a system name in a comment stays as the code has it + edited ,n = edit_code_example(line ,name ,number - 1 ,hand) + count += n + line = edited + else: + # changed only when every mention on the line refers to a renamed + # file; otherwise the line can hold data, and is left whole + match_list = list(re.finditer(re.escape(name.old) ,line)) + if all(is_renamed_file_reference(token_around(line ,m.start() ,m.end()) ,name) for m in match_list): + count += len(match_list) + line = line.replace(name.old ,name.identifier) + else: + hand.append(number) + out.append(line) + return "".join(out) ,count + +def edit_code(rel ,text ,name ,hand): + """The old name in a code file, by the rules of its language.""" + if name.old == name.identifier: + return text ,0 + if is_python(rel ,text): + return edit_python(text ,name ,hand) + return edit_other_code(text ,name ,hand) + +def edit_prose(text ,name ,line_base ,hand ,frozen=frozenset()): + """ + The old name standing as a word in prose becomes the hyphenated name. Joined + to other characters it is part of some token, a file name or code, and is + logged. A possessive or the end of a sentence does not join it. + """ + count = 0 + for old in name.prose_old: + pattern = re.compile(r"(?,