From bd67f573d4c6c800940c39a4492f8f8fb15af297 Mon Sep 17 00:00:00 2001 From: Thomas Walker Lynch Date: Thu, 26 Nov 2026 07:12:59 +0000 Subject: [PATCH] Initial commit of Jizo from Harmony skeleton --- .gitignore | 30 + 0pus_Jizo | 0 LICENSE | 21 + README.md | 26 + administrator/authored/.gitkeep | 0 .../how-to_add-project-dependency.html | 119 ++++ administrator/document/how-to_release.html | 114 ++++ .../tool/Account-Tree_directory_rename | 149 +++++ administrator/tool/RT-Style_header_v5_to_v6 | 306 +++++++++ administrator/tool/archive | 284 ++++++++ administrator/tool/html_to_v31 | 63 ++ administrator/tool/makefile_to_project_mk | 178 +++++ administrator/tool/new-project | 177 +++++ administrator/tool/project_rename | 633 ++++++++++++++++++ administrator/tool/setup | 3 + administrator/tool/skeleton_diff | 250 +++++++ administrator/tool/skeleton_update | 621 +++++++++++++++++ consumer/.gitignore | 5 + developer/authored/.gitkeep | 0 .../authored/ExampleGreet.make/Greeter.lib.c | 20 + .../authored/ExampleGreet.make/Math.lib.c | 12 + .../authored/ExampleGreet.make/hello.CLI.c | 20 + .../document/naming_file-and-directory.html | 101 +++ .../single-file_C-module-and-namespace.html | 184 +++++ developer/experiment/.gitkeep | 0 developer/scratchpad/.gitignore | 2 + developer/tool/build | 123 ++++ developer/tool/build_component/copy | 59 ++ developer/tool/build_component/make | 17 + developer/tool/build_component/project.mk | 20 + developer/tool/build_component/sync_engine.py | 80 +++ developer/tool/promote | 261 ++++++++ developer/tool/setup | 3 + document/introduction_Harmony.html | 249 +++++++ ...role-and-workflow_product-development.html | 134 ++++ ...role-and-workflow_product-maintenance.html | 111 +++ document/writing_tool-script.html | 287 ++++++++ scratchpad/.gitignore | 2 + setup | 116 ++++ shared/authored/.gitkeep | 0 shared/project-dependency/.gitignore | 11 + shared/project-dependency/Python.init | 25 + shared/project-dependency/Python.org | 71 ++ shared/project-dependency/project | 1 + shared/tool/PATH.sh | 0 shared/tool/env_to_emacs | 78 +++ shared/tool/makefile/Harmony.mk | 192 ++++++ shared/tool/makefile/RT_global.h | 11 + shared/tool/makefile/target_kernel-module.mk | 130 ++++ shared/tool/replace_from_tar | 182 +++++ shared/tool/scratchpad | 225 +++++++ shared/tool/setup | 100 +++ shared/tool/version | 4 + tester/.gitkeep | 0 tester/authored/.gitkeep | 0 tester/tool/setup | 3 + 56 files changed, 5813 insertions(+) create mode 100644 .gitignore create mode 100644 0pus_Jizo create mode 100644 LICENSE create mode 100644 README.md create mode 100644 administrator/authored/.gitkeep create mode 100644 administrator/document/how-to_add-project-dependency.html create mode 100644 administrator/document/how-to_release.html create mode 100755 administrator/tool/Account-Tree_directory_rename create mode 100755 administrator/tool/RT-Style_header_v5_to_v6 create mode 100755 administrator/tool/archive create mode 100755 administrator/tool/html_to_v31 create mode 100755 administrator/tool/makefile_to_project_mk create mode 100755 administrator/tool/new-project create mode 100755 administrator/tool/project_rename create mode 100644 administrator/tool/setup create mode 100755 administrator/tool/skeleton_diff create mode 100755 administrator/tool/skeleton_update create mode 100644 consumer/.gitignore create mode 100644 developer/authored/.gitkeep create mode 100644 developer/authored/ExampleGreet.make/Greeter.lib.c create mode 100644 developer/authored/ExampleGreet.make/Math.lib.c create mode 100644 developer/authored/ExampleGreet.make/hello.CLI.c create mode 100644 developer/document/naming_file-and-directory.html create mode 100644 developer/document/single-file_C-module-and-namespace.html create mode 100644 developer/experiment/.gitkeep create mode 100644 developer/scratchpad/.gitignore create mode 100755 developer/tool/build create mode 100755 developer/tool/build_component/copy create mode 100755 developer/tool/build_component/make create mode 100644 developer/tool/build_component/project.mk create mode 100644 developer/tool/build_component/sync_engine.py create mode 100755 developer/tool/promote create mode 100644 developer/tool/setup create mode 100644 document/introduction_Harmony.html create mode 100644 document/role-and-workflow_product-development.html create mode 100644 document/role-and-workflow_product-maintenance.html create mode 100644 document/writing_tool-script.html create mode 100644 scratchpad/.gitignore create mode 100755 setup create mode 100644 shared/authored/.gitkeep create mode 100644 shared/project-dependency/.gitignore create mode 100644 shared/project-dependency/Python.init create mode 100644 shared/project-dependency/Python.org create mode 120000 shared/project-dependency/project create mode 100644 shared/tool/PATH.sh create mode 100755 shared/tool/env_to_emacs create mode 100644 shared/tool/makefile/Harmony.mk create mode 100644 shared/tool/makefile/RT_global.h create mode 100644 shared/tool/makefile/target_kernel-module.mk create mode 100755 shared/tool/replace_from_tar create mode 100755 shared/tool/scratchpad create mode 100644 shared/tool/setup create mode 100755 shared/tool/version create mode 100644 tester/.gitkeep create mode 100644 tester/authored/.gitkeep create mode 100644 tester/tool/setup diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..be24c0f --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ + +# no archive or temporary files +*.tar +*.tgz +*.zip +*. +temp.* +**/scratchpad/* +!**/scratchpad/.gitignore +*.patch + +# Python +__pycache__/ +*.py[cod] +*.pyo +*.pyd +.ipynb_checkpoints/ +.pytest_cache/ + +# C / compiled artifacts +*.o +*.a +*.out +*.so + +# OS and editor backup files +*~ +*.bak +*.swp +.DS_Store diff --git a/0pus_Jizo b/0pus_Jizo new file mode 100644 index 0000000..e69de29 diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..3864ac4 --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2026 Reasoning Technology + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..d0fa797 --- /dev/null +++ b/README.md @@ -0,0 +1,26 @@ +# Harmony + +Harmony provides a language-agnostic project directory structure and maintenance tools for long-lived software development. It enforces clarity about where things live, utilizing role-based work areas and the strict separation of skeleton, team member authored, machine-made, and third-party software. + +While designed to manage the complexity of multi-person teams, Harmony serves equally well for an individual developer. A single person can easily assume the roles of administrator, developer, and tester simultaneously by opening separate emacs buffers or terminal windows for each role. + +## Bootstrapping a New Project + +**Important:** Do not begin writing code directly in a fresh clone of this skeleton. You must decouple your new project from the Harmony version control history to prevent accidentally committing your project files back to the upstream skeleton. + +To create a Harmony-based project, the project administrator performs these steps: + +1. Clone the Harmony project to a local directory. +2. Remove the `.git` tree. +3. Rename the Harmony directory to the name of the new project. +4. Rename the `0pus_Harmony` file to reflect the name of the new project. +5. Add a line to the `shared/tool/version` file for the new project. +6. Run `git init -b core_developer_branch` to start your own repository. + +## Viewing the Documentation + +The documents are HTML written against the RT-Style library. With nothing set up, a document loads RT-Style from https://style.ReasoningTechnology.com, so it formats whenever the machine is online. + +To read offline, or against a local copy of RT-Style, put a built RT-Style project on the machine and open its consumer/Manuscript/setup.html once in Chrome, from disk. Chrome then loads RT-Style from that copy for every local document. Opening another copy of setup.html, then reloading the document, will switch to using that other copy. + +Find an introductory document at `document/introduction_Harmony.html`. diff --git a/administrator/authored/.gitkeep b/administrator/authored/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/administrator/document/how-to_add-project-dependency.html b/administrator/document/how-to_add-project-dependency.html new file mode 100644 index 0000000..327a28c --- /dev/null +++ b/administrator/document/how-to_add-project-dependency.html @@ -0,0 +1,119 @@ + + + + + How to add a project dependency + + + + + + + + + + + +

Project dependencies

+ +

+ A project dependency is software the project uses but did not author: a language toolchain, a library, a tool, or another project. A dependency is installed outside the project, as a sibling directory of it, and is linked into the project under shared/project-dependency. +

+ +

+ Getting an arbitrary piece of software working is different every time, so the administrator is free to do whatever a dependency needs inside shared/project-dependency. The skeleton relies on only the few conventions given in the next section. +

+ +

What the skeleton relies on

+ + + +

+ Files for one dependency share a base name, so that Python.init, Python.org, and the link they describe sit together in a listing. +

+ +

Steps

+ +

Install the dependency beside the project

+

+ Download, clone, or extract the dependency into the directory that holds the project, so that it sits as a sibling of the project directory. Build it there if it needs building. +

+ +

Link it

+

+ Make the link through the project link. The word project in the link target is literal. +

+ + > cd $REPO_HOME/shared/project-dependency + > ln -s project/<dependency directory> <name> + + +

Write the init file

+

+ Write <name>.init in the same directory. Because it runs on every setup for every role, keep it to setting the environment: +

+ +

+ Python.init, which comes with the skeleton, is an example: +

+ + if [[ -d "$REPO_HOME/shared/project-dependency/Python-3.12.3/bin" ]]; then + PATH="$REPO_HOME/shared/project-dependency/Python-3.12.3/bin:$PATH" + else + if [[ "$ROLE" == "administrator" ]]; then + echo "Notice: Local Python-3.12.3 bin not found. Using system Python." + fi + fi + + +

Write the installation notes

+

+ Record what was installed, where it came from, and the commands used, in <name>.org, <name>.html, or comments in the init file. A team member who has cloned the project follows these notes to install the dependency, and then recreates the link if it is not tracked. +

+ +

Decide what is tracked

+

+ The skeleton's .gitignore tracks itself, the project link, and files ending in .init, .install, .org, and .html. Everything else in the directory is ignored. To track a dependency's link, so that it arrives with every clone, add a line naming it: +

+ + !<name> + +

+ A tracked link points at nothing until the dependency is installed beside the project, which is why init files test for the dependency before using it. +

+ +

Commit

+

+ Add the init file, the notes, the .gitignore change, and any tracked link, then commit. +

+ +
+ + diff --git a/administrator/document/how-to_release.html b/administrator/document/how-to_release.html new file mode 100644 index 0000000..0f33c4a --- /dev/null +++ b/administrator/document/how-to_release.html @@ -0,0 +1,114 @@ + + + + + + + Release howto + + + + + + + + + + + +

Prerequisites

+

+ A developer works in the developer branch of the project, and makes use of the build and promote tools to stage release candidates into the $REPO_HOME/consumer directory. The tester then validates the release candidate. This constitutes a cycle of work, developing, promoting candidates, testing, and then further developing. Once the project manager agrees this cycle is complete, the release flow moves to the next step. +

+ +

Make the release branch

+

+ The administrator executes the release. Open a terminal. Enter the project workspace. +

+ + > . setup administrator + + +

+ Switch to the core development branch. Ensure the local repository is current. +

+ + > git checkout core-developer_branch + > git pull + + +

+ Make a new branch for the release. Use the major version number. +

+ + > git checkout -b release_v<major> + + +

Issue management and patching

+

+ Only critical issues receive patches on a release branch. The product manager defines what is critical. If approved, the release team applies the fix directly to the existing release_v<major> branch. +

+

+ The branch name release_v<major> remains static. The code on the branch is updated. The administrator advances the minor release number in the shared/tool/version file. +

+

+ The administrator tags the new commit with the full version number, such as v<major>.<minor>. Minor versions are edits on the major release branch. They are visible to a person by running the version command. +

+

+ The developer must ensure the fix is also ported to the core-developer_branch. This prevents the defect from reappearing in future major releases. +

+ +

Tag and push

+

+ Tag the release with the exact version number. +

+ + > git tag -a v<major>.<minor> -m "Release v<major>.<minor>" + + +

+ Push the branch to the remote repository. Push the tags. +

+ + > git push origin release_v<major> + > git push origin --tags + + +

Repository default branch

+

+ Set the repository default branch to the new release_v<major> branch on the hosting platform. This ensures a person cloning or pulling the repository receives the most recent major release code by default. +

+ +

Verification

+

+ Check the remote repository. Confirm the branch exists. Confirm the tag is visible. Confirm the default branch is updated. +

+ +

Role responsibilities

+ + +
+ + 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/RT-Style_header_v5_to_v6 b/administrator/tool/RT-Style_header_v5_to_v6 new file mode 100755 index 0000000..3ca4169 --- /dev/null +++ b/administrator/tool/RT-Style_header_v5_to_v6 @@ -0,0 +1,306 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +""" +RT-Style_header_v5_to_v6 + +Converts RT-Style version 5 document headers to version 6. + +A version 5 document loads the engine through a locator file beside it: + + + +A version 6 document carries an inline header block instead. The block takes +the library from the record made by opening a Manuscript directory's +setup.html, and falls back to the Reasoning Technology server. + +For each version 5 .html file found, the tool replaces the locator line in + with the version 6 block, keeping its indentation. It then deletes +RT-Manuscript_locator.js from that file's directory, unless another version 5 +document there, not converted in this run, still uses it. Any other mention of +RT-Manuscript_locator in the file (an escaped example, prose) is logged for a +person to edit. + +Usage: RT-Style_header_v5_to_v6 [file ...] + RT-Style_header_v5_to_v6 preview [file ...] + + help | -h | --help print this message (also printed when given no arguments) + project walk the directory tree rooted at $REPO_HOME + tree walk the directory tree rooted at the current directory + local only the current directory, no subdirectories + file ... only the named .html files + preview print the log of what would do, change nothing + +Every directory is walked, whatever its name. Symbolic links to directories +are not followed, so a link back up the tree cannot cause a loop or reach +outside it. +""" + +import sys ,os ,re +from pathlib import Path + +LOCATOR_FILE = "RT-Manuscript_locator.js" +V6_MARK = 'localStorage.getItem("RT.dirpr_library")' + +V6_BLOCK = [ + '' +] + +LOCATOR_LINE = re.compile( + r'^(?P[ \t]*)\s*\s*$' + ,re.IGNORECASE +) +HEAD_END = re.compile(r'' ,re.IGNORECASE) + + +# ---------------------------------------------------------------- log + +class Log: + def __init__(self ,preview: bool ,base: Path): + self.preview = preview + self.base = base + self.count = {"converted": 0 ,"deleted": 0 ,"already": 0 ,"hand": 0 + ,"untouched": 0 ,"stray": 0 ,"error": 0} + + def rel(self ,p: Path) -> str: + try: return str(p.resolve().relative_to(self.base)) + except ValueError: return str(p) + + def line(self ,tag: str ,text: str): + print(f" {tag:<15} {text}") + + def act(self ,done: str ,would: str ,p: Path ,key: str): + self.line(would if self.preview else done ,self.rel(p)) + self.count[key] += 1 + + def summary(self): + c = self.count + v = "would be " if self.preview else "" + print() + print("summary:") + print(f" {c['converted']:>4} .html files {v}converted to version 6") + print(f" {c['deleted']:>4} {LOCATOR_FILE} files {v}deleted") + print(f" {c['already']:>4} .html files already version 6") + print(f" {c['hand']:>4} .html files with mentions to edit by hand") + print(f" {c['untouched']:>4} other .html files left alone") + if c['stray']: + print(f" {c['stray']:>4} {LOCATOR_FILE} files kept (see 'kept' lines)") + if c['error']: + print(f" {c['error']:>4} errors") + if self.preview: + print("preview only: nothing was changed") + + +# ---------------------------------------------------------------- finding files + +def walk(root: Path ,recursive: bool): + """Yields (directory ,[.html files] ,has_locator) for each directory.""" + if not recursive: + entries = sorted(root.iterdir()) + yield root ,[e for e in entries if e.is_file() and e.suffix == ".html"] ,(root / LOCATOR_FILE).is_file() + return + for d ,dirs ,files in os.walk(root): + dirs.sort() + files = sorted(files) + yield Path(d) ,[Path(d) / f for f in files if f.endswith(".html")] ,LOCATOR_FILE in files + + +# ---------------------------------------------------------------- conversion + +def convert(text: str): + """Returns (new_text ,replaced_count ,leftover). leftover lists + (line_number ,line) for locator mentions that were not replaced.""" + lines = text.split("\n") + out = [] + replaced = 0 + leftover = [] + in_head = True + for n ,line in enumerate(lines ,1): + m = LOCATOR_LINE.match(line) if in_head else None + if m: + eol = "\r" if line.endswith("\r") else "" + out.extend(m.group("indent") + b + eol for b in V6_BLOCK) + replaced += 1 + else: + out.append(line) + if LOCATOR_FILE.removesuffix(".js") in line: + leftover.append((n ,line.strip())) + if in_head and HEAD_END.search(line): + in_head = False + return "\n".join(out) ,replaced ,leftover + +def do_file(f: Path ,log: Log) -> bool: + """Converts one .html file. Returns True when it was version 5.""" + try: + text = f.read_text(encoding="utf-8") + except Exception as e: + log.line("error" ,f"{log.rel(f)}: cannot read: {e}") + log.count["error"] += 1 + return False + + if V6_MARK in text and LOCATOR_FILE.removesuffix(".js") not in text: + log.line("already v6" ,log.rel(f)) + log.count["already"] += 1 + return False + + new_text ,replaced ,leftover = convert(text) + + if replaced: + if not log.preview: + try: + mode = f.stat().st_mode + f.write_text(new_text ,encoding="utf-8") + os.chmod(f ,mode) + except Exception as e: + log.line("error" ,f"{log.rel(f)}: cannot write: {e}") + log.count["error"] += 1 + return False + log.act("converted" ,"would convert" ,f ,"converted") + if replaced > 1: + log.line("note" ,f"{log.rel(f)}: {replaced} locator lines in , all replaced") + elif not leftover: + log.count["untouched"] += 1 + + if leftover: + log.count["hand"] += 1 + for n ,line in leftover: + log.line("edit by hand" ,f"{log.rel(f)}:{n}: {line[:100]}") + + return replaced > 0 + +def uses_locator(f: Path) -> bool: + """True when f still loads the engine through a locator line in .""" + try: + text = f.read_text(encoding="utf-8") + except Exception: + return False + for line in text.split("\n"): + if LOCATOR_LINE.match(line): return True + if HEAD_END.search(line): return False + return False + +def do_locator(d: Path ,converted: set ,log: Log): + """Deletes d's locator unless a version 5 document not converted in this + run still uses it.""" + loc = d / LOCATOR_FILE + users = sorted(f.name for f in d.iterdir() + if f.is_file() and f.suffix == ".html" + and f.resolve() not in converted and uses_locator(f)) + if users: + shown = ", ".join(users[:3]) + (" ..." if len(users) > 3 else "") + log.line("kept" ,f"{log.rel(loc)} (still used by {shown})") + log.count["stray"] += 1 + return + if not log.preview: + try: + loc.unlink() + except Exception as e: + log.line("error" ,f"{log.rel(loc)}: cannot delete: {e}") + log.count["error"] += 1 + return + log.act("deleted" ,"would delete" ,loc ,"deleted") + +def run_dirs(root: Path ,recursive: bool ,log: Log): + for d ,html ,has_locator in walk(root ,recursive): + converted = set() + for f in html: + if do_file(f ,log): converted.add(f.resolve()) + if has_locator: + if converted: + do_locator(d ,converted ,log) + else: + log.line("kept" ,f"{log.rel(d / LOCATOR_FILE)} (no version 5 document beside it)") + log.count["stray"] += 1 + +def run_files(files: list[Path] ,log: Log): + converted = set() + dirs = [] + for f in files: + if do_file(f ,log): + converted.add(f.resolve()) + d = f.parent.resolve() + if d not in dirs: dirs.append(d) + for d in dirs: + if (d / LOCATOR_FILE).is_file(): + do_locator(d ,converted ,log) + + +# ---------------------------------------------------------------- command line + +def print_help() -> int: + print(__doc__.strip()) + return 0 + +def CLI(argv=None) -> int: + if argv is None: + argv = sys.argv[1:] + if not argv or argv[0] in ("help" ,"-h" ,"--help"): + return print_help() + + preview = False + if argv[0] == "preview": + preview = True + 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 == "file": + if not rest: + print("Error: 'file' needs at least one file name." ,file=sys.stderr) + return 1 + files = [Path(a) for a in rest] + for f in files: + if not f.is_file(): + print(f"Error: {f} is not a file." ,file=sys.stderr) + return 1 + base = Path.cwd().resolve() + log = Log(preview ,base) + print(f"RT-Style_header_v5_to_v6 {'preview ' if preview else ''}file in {base}") + run_files(files ,log) + log.summary() + return 1 if log.count["error"] else 0 + + if rest: + print(f"Error: '{command}' takes no arguments." ,file=sys.stderr) + return 1 + + if command == "project": + repo_home = os.environ.get("REPO_HOME") + if not repo_home: + print("Error: 'project' needs REPO_HOME to be set." ,file=sys.stderr) + return 1 + root ,recursive = Path(repo_home) ,True + elif command == "tree": + root ,recursive = Path.cwd() ,True + elif command == "local": + root ,recursive = Path.cwd() ,False + else: + print(f"Error: unknown command '{command}'.\n" ,file=sys.stderr) + print_help() + return 1 + + if not root.is_dir(): + print(f"Error: {root} is not a directory." ,file=sys.stderr) + return 1 + + base = root.resolve() + log = Log(preview ,base) + print(f"RT-Style_header_v5_to_v6 {'preview ' if preview else ''}{command} in {base}") + run_dirs(base ,recursive ,log) + log.summary() + return 1 if log.count["error"] else 0 + +if __name__ == "__main__": + sys.exit(CLI()) diff --git a/administrator/tool/archive b/administrator/tool/archive new file mode 100755 index 0000000..a60a0a0 --- /dev/null +++ b/administrator/tool/archive @@ -0,0 +1,284 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +""" +archive - Create an archive of the current Git repo's ref into ./scratchpad + +Commands (order-insensitive): + archive # default: zip (HEAD, ./scratchpad, Z-stamp if importable) + archive help # show help + archive version # show version + archive ref- # choose ref (tag/branch/commit), default HEAD + archive out- # choose output directory (default: /scratchpad) + archive no-stamp # force omit timestamp even if Z is importable + archive z-format- # override timestamp format used with Z (optional) + archive zip # write .zip + archive tgz # write .tgz (compressed tar) + archive tar # write .tar (uncompressed tar) + +Output names: + __[__].zip + __[__].tgz + __[__].tar +""" + +from __future__ import annotations +import gzip ,os ,pathlib ,subprocess ,sys +from typing import Optional +import importlib ,importlib.util +from importlib.machinery import SourceFileLoader + +VERSION = "2.0" + +# ---------------------------------------------------------------------- +# Editable timestamp format (used when calling Z) +# ---------------------------------------------------------------------- +Z_FORMAT = "%year-%month-%day_%hour%minute%secondZ" + +USAGE = f"""archive {VERSION} + +Usage: + archive [commands...] + +Commands (order-insensitive): + help + version + ref- + out- + no-stamp + z-format- + zip + tgz + tar + +Examples: + archive + archive tgz + archive ref-main out-/tmp + archive z-format-%year-%month-%dayT%hour:%minute:%second.%scintillaZ +""".rstrip() + +# ---------------------------------------------------------------------- +# git helpers +# ---------------------------------------------------------------------- +def _run(*args: str ,check: bool = True ,cwd: Optional[pathlib.Path] = None) -> subprocess.CompletedProcess[str]: + return subprocess.run( + args + ,check=check + ,cwd=(str(cwd) if cwd else None) + ,text=True + ,stdout=subprocess.PIPE + ,stderr=subprocess.PIPE + ) + +def _in_git_repo() -> bool: + try: + return _run("git" ,"rev-parse" ,"--is-inside-work-tree").stdout.strip().lower() == "true" + except subprocess.CalledProcessError: + return False + +def _git_top() -> pathlib.Path: + return pathlib.Path(_run("git" ,"rev-parse" ,"--show-toplevel").stdout.strip()) + +def _git_ref_label(repo_top: pathlib.Path ,ref: str) -> str: + try: + return _run("git" ,"-C" ,str(repo_top) ,"describe" ,"--tags" ,"--always" ,"--dirty" ,ref).stdout.strip() + except subprocess.CalledProcessError: + return _run("git" ,"-C" ,str(repo_top) ,"rev-parse" ,"--short" ,ref).stdout.strip() + +# ---------------------------------------------------------------------- +# Z module discovery (supports extension-less file named "Z") +# ---------------------------------------------------------------------- +def _import_Z_module(repo_top: pathlib.Path) -> Optional[object]: + try: + return importlib.import_module("Z") + except Exception: + pass + + candidates: list[pathlib.Path] = [] + here = pathlib.Path(__file__).resolve().parent + candidates += [here / "Z" ,here / "Z.py"] + candidates += [ + repo_top / "shared" / "third_party" / "RT-project-share" / "release" / "python" / "Z" + ,repo_top / "shared" / "third_party" / "RT-project-share" / "release" / "python" / "Z.py" + ,repo_top / "shared" / "third_party" / "RT-project-share" / "release" / "bash" / "Z" + ] + for d in (pathlib.Path(p) for p in (os.getenv("PATH") or "").split(os.pathsep) if p): + p = d / "Z" + if p.exists() and p.is_file(): + candidates.append(p) + + for path in candidates: + try: + if not path.exists() or not path.is_file(): continue + spec = importlib.util.spec_from_loader("Z" ,SourceFileLoader("Z" ,str(path))) + if not spec or not spec.loader: continue + mod = importlib.util.module_from_spec(spec) + spec.loader.exec_module(mod) + if hasattr(mod ,"make_timestamp") or (hasattr(mod ,"get_utc_dict") and hasattr(mod ,"format_timestamp")): + return mod + except Exception: + continue + return None + +# ---------------------------------------------------------------------- +# Z stamp helper +# ---------------------------------------------------------------------- +def make_z_stamp(zmod: object ,z_format: str) -> Optional[str]: + try: + if hasattr(zmod ,"make_timestamp"): + s = zmod.make_timestamp(fmt=z_format) + return (str(s).strip().replace("\n" ,"") or None) + if hasattr(zmod ,"get_utc_dict") and hasattr(zmod ,"format_timestamp"): + td = zmod.get_utc_dict() + s = zmod.format_timestamp(td ,z_format) + return (str(s).strip().replace("\n" ,"") or None) + except Exception: + return None + return None + +# ---------------------------------------------------------------------- +# archiving +# ---------------------------------------------------------------------- +def _stream_git_archive_tar(repo_top: pathlib.Path ,prefix: str ,ref: str ,out_path: pathlib.Path ,compress: bool) -> None: + proc = subprocess.Popen( + ["git" ,"-C" ,str(repo_top) ,"archive" ,"--format=tar" ,f"--prefix={prefix}/" ,ref] + ,stdout=subprocess.PIPE + ) + try: + if compress: + with gzip.open(out_path ,"wb") as f: + while True: + chunk = proc.stdout.read(1024 * 1024) + if not chunk: break + f.write(chunk) + else: + with open(out_path ,"wb") as f: + while True: + chunk = proc.stdout.read(1024 * 1024) + if not chunk: break + f.write(chunk) + finally: + if proc.stdout: proc.stdout.close() + rc = proc.wait() + if rc != 0: + try: + out_path.unlink(missing_ok=True) + finally: + raise subprocess.CalledProcessError(rc ,proc.args) + +def _stream_git_archive_zip(repo_top: pathlib.Path ,prefix: str ,ref: str ,out_zip_path: pathlib.Path) -> None: + proc = subprocess.Popen( + ["git" ,"-C" ,str(repo_top) ,"archive" ,"--format=zip" ,f"--prefix={prefix}/" ,ref] + ,stdout=subprocess.PIPE + ) + try: + with open(out_zip_path ,"wb") as f: + while True: + chunk = proc.stdout.read(1024 * 1024) + if not chunk: break + f.write(chunk) + finally: + if proc.stdout: proc.stdout.close() + rc = proc.wait() + if rc != 0: + try: + out_zip_path.unlink(missing_ok=True) + finally: + raise subprocess.CalledProcessError(rc ,proc.args) + +# ---------------------------------------------------------------------- +# work function +# ---------------------------------------------------------------------- +def work( + ref: str = "HEAD" + ,outdir: Optional[pathlib.Path] = None + ,force_no_stamp: bool = False + ,z_format: Optional[str] = None + ,archive_kind: str = "zip" +) -> pathlib.Path: + + if archive_kind not in ("zip" ,"tgz" ,"tar"): + raise RuntimeError("archive_kind must be 'zip', 'tgz', or 'tar'") + + if not _in_git_repo(): + raise RuntimeError("not inside a git repository") + + repo_top = _git_top() + repo_name = repo_top.name + ref_label = _git_ref_label(repo_top ,ref) + + stamp: Optional[str] = None + if not force_no_stamp: + zmod = _import_Z_module(repo_top) + if zmod is not None: + stamp = make_z_stamp(zmod ,z_format or Z_FORMAT) + + target_dir = (outdir or (repo_top / "scratchpad")) + target_dir.mkdir(parents=True ,exist_ok=True) + + if archive_kind == "zip": + suffix = ".zip" + elif archive_kind == "tgz": + suffix = ".tgz" + else: + suffix = ".tar" + + out_name = f"{repo_name}__{ref_label}{('__' + stamp) if stamp else ''}{suffix}" + out_path = target_dir / out_name + + if archive_kind == "zip": + _stream_git_archive_zip(repo_top ,repo_name ,ref ,out_path) + else: + compress = (archive_kind == "tgz") + _stream_git_archive_tar(repo_top ,repo_name ,ref ,out_path ,compress) + + return out_path + +# ---------------------------------------------------------------------- +# CLI with command tokens +# ---------------------------------------------------------------------- +def CLI(argv: Optional[list[str]] = None) -> int: + if argv is None: argv = sys.argv[1:] + + ref = "HEAD" + outdir: Optional[pathlib.Path] = None + force_no_stamp = False + z_format: Optional[str] = None + archive_kind = "zip" + + if not argv: + try: + print(f"Wrote {work(ref=ref ,outdir=outdir ,force_no_stamp=force_no_stamp ,z_format=z_format ,archive_kind=archive_kind)}") + return 0 + except Exception as e: + print(f"archive: {e}" ,file=sys.stderr); return 1 + + for arg in argv: + if arg in ("help" ,"-h" ,"--help"): print(USAGE); return 0 + if arg == "version": print(f"archive {VERSION}"); return 0 + if arg == "no-stamp": force_no_stamp = True; continue + if arg == "zip": archive_kind = "zip"; continue + if arg == "tgz": archive_kind = "tgz"; continue + if arg == "tar": archive_kind = "tar"; continue + if arg.startswith("ref-"): ref = arg[4:] or ref; continue + if arg.startswith("out-"): + od = arg[4:] + outdir = pathlib.Path(od).resolve() if od else None + continue + if arg.startswith("z-format-"): + z_format = arg[len("z-format-"):] or None + continue + print(f"archive: unknown command '{arg}'" ,file=sys.stderr); return 1 + + try: + out_path = work(ref=ref ,outdir=outdir ,force_no_stamp=force_no_stamp ,z_format=z_format ,archive_kind=archive_kind) + except Exception as e: + print(f"archive: {e}" ,file=sys.stderr); return 1 + + print(f"Wrote {out_path}") + return 0 + +# ---------------------------------------------------------------------- +if __name__ == "__main__": + raise SystemExit(CLI()) diff --git a/administrator/tool/html_to_v31 b/administrator/tool/html_to_v31 new file mode 100755 index 0000000..b1aba38 --- /dev/null +++ b/administrator/tool/html_to_v31 @@ -0,0 +1,63 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- +""" +html_update_to_3-1 + +Replaces specific StyleRT script blocks with RT 3.1 loader blocks using +literal string replacement. +""" + +import sys ,os + +OLD_BLOCK = \ +""" + """ + +NEW_BLOCK = \ +""" + """ + +def process_file(file_path: str) -> None: + try: + with open(file_path ,"r" ,encoding="utf-8") as f: + content = f.read() + except Exception as e: + print(f"Error reading {file_path}: {e}" ,file=sys.stderr) + return + + # Normalize line endings to ensure a match across environments + normalized_content = content.replace("\r\n" ,"\n") + normalized_old = OLD_BLOCK.replace("\r\n" ,"\n") + + if( normalized_old in normalized_content ): + new_content = normalized_content.replace(normalized_old ,NEW_BLOCK) + with open(file_path ,"w" ,encoding="utf-8") as f: + f.write(new_content) + print(f"Updated: {file_path}") + else: + print(f"Target lines not found in: {file_path}") + +def CLI() -> None: + args = sys.argv[1:] + + if( not args or "-h" in args or "--help" in args ): + print("Usage: html_update_to_3-1 ") + sys.exit(0) + + for TM_f in args: + process_file(TM_f) + +if __name__ == "__main__": + 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/new-project b/administrator/tool/new-project new file mode 100755 index 0000000..c949ddb --- /dev/null +++ b/administrator/tool/new-project @@ -0,0 +1,177 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +""" +new-project + +This administrative tool instantiates a fresh project workspace modeled after +the Harmony skeleton architecture. + +The script executes the following sequential lifecycle: + 1. Validates the execution environment (requires an active role session). + 2. Checks the git status of the skeleton. The new project is made from the + last commit, so uncommitted changes and untracked files would be left + out. When there are any, lists them and asks whether to continue. + 3. Safely extracts a clean copy of all Git-tracked files using an archive stream. + 4. Renames the boilerplate 0pus_Harmony anchor file to reflect the new project. + 5. Injects an initial version tracking entry into the shared configuration space. + 6. Initializes a fresh Git repository bound to the core-developer_branch. + 7. Stages and commits the pristine skeleton infrastructure as a baseline. + 8. Maps any upstream remote network targets passed via CLI parameters. +""" + +import sys ,os ,subprocess +from pathlib import Path + +def get_Z_date() -> str: + """Retrieves the current date utilizing the system Z timestamp tool.""" + try: + res = subprocess.run(["Z" ,"format-%year-%month-%day"] ,capture_output=True ,text=True ,check=True) + return res.stdout.strip() + except Exception: + return "1970-01-01" + +def uncommitted(repo_path: Path) -> list[str] | None: + """Returns the lines of 'git status --porcelain' for the skeleton: one per + file with uncommitted changes or untracked. None when git cannot report.""" + try: + res = subprocess.run( + ["git" ,"status" ,"--porcelain" ,"--untracked-files=normal"] + ,cwd=str(repo_path) ,capture_output=True ,text=True ,check=True + ) + except Exception: + return None + return [line for line in res.stdout.splitlines() if line.strip()] + +def confirm(question: str) -> bool: + """Asks a yes or no question at the terminal. Without a terminal to ask + at, the answer is no.""" + if not sys.stdin.isatty(): + return False + try: + answer = input(question + " [y/N] ") + except EOFError: + return False + return answer.strip().lower() in ("y" ,"yes") + +def work(repo_path: Path ,project_name: str ,remotes: list[str]) -> int: + """Orchestrates the assembly of the new skeleton instance.""" + + # Resolve destination relative to the parent space of the current repository + dest_path = Path(project_name) + if not dest_path.is_absolute(): + dest_path = (repo_path.parent / project_name).resolve() + + if dest_path.exists(): + print(f"Error: Destination {dest_path} already exists." ,file=sys.stderr) + return 1 + + print(f"Making new project at: {dest_path}") + dest_path.mkdir(parents=True) + + # Export tracked files without duplicating untracked scratchpads or git histories + archive_cmd = "git archive HEAD | tar -x -C " + str(dest_path) + res = subprocess.run(archive_cmd ,shell=True ,cwd=str(repo_path)) + if res.returncode != 0: + print("Error extracting archive." ,file=sys.stderr) + return 1 + + # Personalize the project baseline anchor file + opus_src = dest_path / "0pus_Harmony" + opus_dst = dest_path / f"0pus_{dest_path.name}" + if opus_src.exists(): + opus_src.rename(opus_dst) + + # Record the lineage in the shared version history + version_file = dest_path / "shared" / "tool" / "version" + date_str = get_Z_date() + version_line = f"echo \"{dest_path.name} v0.1 {date_str}\"\n" + + if version_file.exists(): + with open(version_file ,"a" ,encoding="utf-8") as vf: + vf.write(version_line) + else: + with open(version_file ,"w" ,encoding="utf-8") as vf: + vf.write(version_line) + + # Initialize the pristine Git environment tracking system + print("Initializing git repository...") + subprocess.run(["git" ,"init" ,"-b" ,"core-developer_branch"] ,cwd=str(dest_path) ,check=True) + subprocess.run(["git" ,"add" ,"."] ,cwd=str(dest_path) ,check=True) + subprocess.run(["git" ,"commit" ,"-m" ,f"Initial commit of {dest_path.name} from Harmony skeleton"] ,cwd=str(dest_path) ,check=True) + + # Configure tracking addresses for upstreams + for idx ,remote_url in enumerate(remotes): + remote_name = f"remote_{idx}" + if "github.com" in remote_url: + remote_name = "github" + elif "RT" in remote_url: + remote_name = "RT" + elif idx == 0: + remote_name = "origin" + + print(f"Adding remote '{remote_name}': {remote_url}") + subprocess.run(["git" ,"remote" ,"add" ,remote_name ,remote_url] ,cwd=str(dest_path) ,check=True) + + print(f"Project '{dest_path.name}' successfully made.") + return 0 + +def CLI(argv=None) -> int: + """Parses user input tokens from the shell execution frame.""" + if argv is None: + argv = sys.argv[1:] + + if not argv or "-h" in argv or "--help" in argv: + print("Usage: new-project [-remote ]...") + return 0 + + project_name = None + remotes = [] + + idx = 0 + while idx < len(argv): + arg = argv[idx] + if arg == "-remote": + if idx + 1 < len(argv): + remotes.append(argv[idx+1]) + idx += 1 + else: + print("Error: -remote requires a URL." ,file=sys.stderr) + return 1 + elif project_name is None: + project_name = arg + else: + print(f"Error: unexpected argument '{arg}'" ,file=sys.stderr) + return 1 + idx += 1 + + if not project_name: + print("Error: project name is required." ,file=sys.stderr) + return 1 + + repo_home = os.environ.get("REPO_HOME") + if not repo_home: + print("Error: REPO_HOME is not set. A person must run this from within a sourced role environment." ,file=sys.stderr) + return 1 + repo_path = Path(repo_home).resolve() + + status = uncommitted(repo_path) + if status is None: + print(f"Error: could not read the git status of {repo_path}." ,file=sys.stderr) + return 1 + if status: + shown = status[:20] + print(f"Warning: {repo_path} has {len(status)} uncommitted or untracked file(s):") + for line in shown: + print(" " + line) + if len(status) > len(shown): + print(f" ... and {len(status) - len(shown)} more (see 'git status')") + print("The new project is made from the last commit, so these will not be in it.") + if not confirm("Continue anyway?"): + print("Stopped. Nothing was made. Commit or stash the changes, then run new-project again.") + return 1 + + return work(repo_path ,project_name ,remotes) + +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"(?, + + + + + + + + + + +

    Program file system objects

    + +

    + Harmony files and directories are considered to be program file systems objects. +

    + +

    Files

    +

    + Files that hold a single class, have he same base name as that class. If a file holds multiple classes, but there is a class of primary importance and auxiliary classes, the file carries the name of the primary class. +

    + +

    + If a file represents a module or name space, follow the same naming conventions specified for classes and name spaces in the format_RT·code.html document. +

    + +

    + Other program files follow the same naming conventions specified in the format_RT·code.html document for an identifier of the + contained or related language. +

    + +

    Hyphens and spaces

    + +

    In a C language culture, file names use underscores between words. In a Lisp language culture use snake-kebab_case. Spaces are generally not used in program file names. Though the Harmony skeleton is language agnostic, it was first used with C, hence file names use primarily underscores. +

    + + +

    Program Directories

    +

    + A directory that is a package, follows the convention for name spaces. +

    + +

    + A directory that is used to give the contained files a property is an identifier. +

    + +

    + What is a reasonable primary property for a set of files? Perhaps: +

    +
      +
    • Who uses each file with this property. Home directories are named like this.
    • +
    • The role of the people using the file. The developer and tester directories were named in this manner.
    • +
    • What program are the files for.
    • +
    • The generic category of program said files are for. We prefer the names authored and made. authored files are those written by humans or AI, while made files are products of tools.
    • +
    + +

    Property indicators on files

    +

    + We add a second property to a file using dot extensions to the file's name. We can extend the dot suffix model by using multiple dot suffixes. File name extensions are used to signal to the build tools how the file is to be processed: +

    +
      +
    • .cli.c : Compiler fodder made into a stand-alone executable.
    • +
    • .lib.c : Library code source, compiled as an object file and added to the project archive.
    • +
    • .mod.c : Kernel module sources.
    • +
    + +

    Exercises

    +

    Exercise 1: Program file names

    +

    + Rename the following poorly named files to strictly adhere to the RT naming conventions. Pay close attention to the language culture, the capitalization of acronyms, and the rule for spelling out abbreviations in outer scope identifiers. +

    +
      +
    • A C-culture makefile that builds a target library and command line interface: target-lib-cli.mk
    • +
    • A Lisp-culture source file for an HTML parsing module: html_parser_mod.el
    • +
    • A C language source file that initializes an HTTP server: init-http-srv.c
    • +
    + +
    + + diff --git a/developer/document/single-file_C-module-and-namespace.html b/developer/document/single-file_C-module-and-namespace.html new file mode 100644 index 0000000..0e6cd17 --- /dev/null +++ b/developer/document/single-file_C-module-and-namespace.html @@ -0,0 +1,184 @@ + + + + + + + C modules, namespaces, and the build lifecycle + + + + + + + + + + + +

    Single-file C source

    +

    + The RT C language culture abandons the traditional separation of declarations into .h header files and definitions into .c source files. A developer integrates the interface and the implementation into a single file. +

    +

    + When a person includes the file using an #include directive, the file exposes only its interface. When the build system compiles the file into an object, a preprocessor macro acts as an implementation gate to compile the definitions. This keeps the source tree clean and ensures the interface and implementation never fall out of synchronization. +

    + +

    Ad hoc namespaces

    +

    + The C language lacks native namespaces. To prevent symbol collisions in large projects, RT code format uses a center dot (·) to denote ad hoc namespaces within identifiers. +

    +

    + A programmer maps the directory structure directly to these namespaces. For example, a file located at authored/ExampleGreet/Math.lib.c belongs to the ExampleGreet namespace and defines the Math module. +

    +
      +
    • Types and modules use PascalCase.
    • +
    • Functions and variables use snake_case.
    • +
    +

    + An exported function from this module carries the full namespace and module prefix, such as ExampleGreet·Math·add. +

    + +

    The implementation gate

    +

    + To achieve the single-file source pattern, the code relies on two preprocessor constructs: +

    +
      +
    • Include Guard: The entire file is wrapped in an include guard using the ·ONCE suffix. This prevents redeclaration errors if the file is included multiple times.
    • +
    • Implementation Block: The definitions are wrapped in a single #ifdef block using the exact namespace and module name. The build system dynamically injects this macro via a -D compiler flag when building the module's specific object file.
    • +
    + +

    Build system mechanics

    +

    + When a consumer file, such as hello.CLI.c, contains #include "Math.lib.c", the compiler processes the file without the ExampleGreet·Math macro defined. It skips the implementation and reads only the function prototype. +

    +

    + When the orchestrator compiles the library object, it evaluates the target name and explicitly passes -DExampleGreet·Math to the compiler. This unlocks the gate, compiling the machine code for the definitions into Math.lib.o. +

    + +

    Example: Math.lib.c

    +

    + The following example demonstrates the complete structure. +

    + + + #ifndef ExampleGreet·Math·ONCE + #define ExampleGreet·Math·ONCE + + int ExampleGreet·Math·add(int a ,int b); + + #ifdef ExampleGreet·Math + + int ExampleGreet·Math·add(int a ,int b){ + return a + b; + } + + #endif // ExampleGreet·Math + #endif // ExampleGreet·Math·ONCE + + +

    Cross-module dependencies

    +

    + When one module depends on another, the developer directly includes the library source file. For example, if the Greeter module requires the Math module, the file Greeter.lib.c will contain: +

    + + #include "Math.lib.c" + +

    + Because every file is protected by a ·ONCE include guard, it is safe for multiple modules to include the same dependency. The preprocessor will expand the interface once per translation unit. +

    + +

    Information hiding

    +

    + To define internal helper functions or private data that should not be exposed in the module's public interface, a programmer places them strictly inside the #ifdef implementation block. +

    +

    + To prevent these internal symbols from leaking into the global namespace during linking, they must be given internal linkage. The RT skeleton provides the Local macro (defined as static in RT_global.h) for this exact purpose. +

    + + #ifdef ExampleGreet·Math + + Local int internal_helper(int val){ + return val * 2; + } + + int ExampleGreet·Math·add(int a ,int b){ + return internal_helper(a) + b; + } + + #endif // ExampleGreet·Math + + +

    Executable entry points

    +

    + Programs intended to be compiled into standalone executables use the .CLI.c suffix. These files consume the library modules but do not define their own namespaces or include guards, as they are never included by other files. +

    +

    + A .CLI.c file includes the necessary .lib.c files, parses command-line arguments in the main function, and passes native data types to a dedicated CLI() function to orchestrate the core logic. +

    + +

    Directory structure and namespaces

    +

    + The physical layout of the authored directory dictates how the build orchestrator finds the source code. +

    +
      +
    • Flat Structure: If a project does not utilize namespaces, the .lib.c and .CLI.c files reside directly inside the developer/authored/ directory.
    • +
    • Namespaced Structure: If a project utilizes namespaces, the files are grouped into subdirectories matching the namespace name, such as developer/authored/ExampleGreet/.
    • +
    + +

    Making the code

    +

    + The developer compiles the code using the make wrapper script located in developer/tool/make. This script accepts two primary arguments: the build command and the target namespace. +

    + + + > make <command> [namespace] + + +

    + To build the ExampleGreet code, a person issues the following command from the developer workspace: +

    + + + > make all ExampleGreet + + +

    + Behind the scenes, the make wrapper assigns the namespace to an environment variable and calls the master orchestrator makefile. The orchestrator detects the namespace, updates the source directory search path to authored/ExampleGreet, and injects the appropriate namespace macros during compilation. +

    +

    + The orchestrator compiles the .lib.c files into object files under scratchpad/build/object/, archives them into a library file, and links the .CLI.c objects into standalone executables. The final artifacts are placed in the scratchpad/made/ directory. +

    + +

    Promoting the artifacts

    +

    + Artifacts resting in the scratchpad are volatile and private to the developer. To share the executables and libraries with the rest of the project (such as the tester or consumer roles), the developer must promote them. +

    + + + > promote write + + +

    + The promote tool compares the contents of developer/scratchpad/made/ against consumer/made/. It atomically copies any new or updated files to the consumer workspace, stripping write permissions to enforce the immutability of the deployment target. Once promoted, the hello executable is ready for testing. +

    + +
    + + diff --git a/developer/experiment/.gitkeep b/developer/experiment/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/developer/scratchpad/.gitignore b/developer/scratchpad/.gitignore new file mode 100644 index 0000000..120f485 --- /dev/null +++ b/developer/scratchpad/.gitignore @@ -0,0 +1,2 @@ +* +!/.gitignore diff --git a/developer/tool/build b/developer/tool/build new file mode 100755 index 0000000..547fc4c --- /dev/null +++ b/developer/tool/build @@ -0,0 +1,123 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- +""" +developer/tool/build - Build Orchestrator Wrapper + +This script acts as the primary entry point for staging the project. +It parses colon-separated arguments mapping specific namespaces to their +intended build arguments. + +It enforces the structural convention where authored directories must +be named .. The script delegates execution to +developer/tool/build_component/. +""" + +import sys, os, subprocess, fnmatch +from typing import Dict, Tuple + +def check_environment() -> None: + setup_must_be = "developer/tool/setup" + current_setup = os.environ.get("SETUP", "") + if current_setup != setup_must_be: + print(f"developer/tool/build:: error: must be run in the {setup_must_be} environment", file=sys.stderr) + sys.exit(1) + +def get_namespaces() -> Dict[str, Tuple[str, str]]: + authored_dir = os.path.join(os.environ.get("REPO_HOME", "."), "developer", "authored") + if not os.path.isdir(authored_dir): + return {} + + namespaces = {} + for TM_item in os.listdir(authored_dir): + path = os.path.join(authored_dir, TM_item) + if os.path.isdir(path) and not TM_item.startswith("."): + parts = TM_item.rsplit(".", 1) + if len(parts) == 2: + ns = parts[0] + tool = parts[1] + namespaces[ns] = (tool, TM_item) + else: + print(f"(warning) Ignoring '{TM_item}': directory lacks the required . suffix.", file=sys.stderr) + + return dict(sorted(namespaces.items())) + +def print_usage(namespaces: Dict[str, Tuple[str, str]]) -> None: + print("Usage: build [[:]*]*\n") + print("Arguments are passed directly to the component specified by the directory suffix.\n") + + print("Available namespaces:") + if namespaces: + for TM_ns, (TM_tool, TM_raw_dir) in namespaces.items(): + print(f" {TM_ns:<20} (Component: {TM_tool}, Dir: {TM_raw_dir})") + else: + print(" (No conforming namespaces currently found in authored/)") + + print("\nExamples:") + print(" build (Displays this usage message)") + print(" build ExampleGreet (Executes 'all' via its assigned component)") + print(" build Ex*:library RT:all:information (Batch execution with pattern matching)") + print(" build \"*:clean\" (Cleans all namespaces. Quotes prevent Bash expansion)") + +def run_build(argument: str, namespace: str, tool: str, raw_dir: str) -> None: + tool_path = os.path.join("tool", "build_component", tool) + + if not os.path.isfile(tool_path) or not os.access(tool_path, os.X_OK): + print(f"error: Build component '{tool}' for namespace '{namespace}' is missing or not executable at {tool_path}", file=sys.stderr) + sys.exit(1) + + env = os.environ.copy() + env["NAMESPACE"] = namespace + env["NAMESPACE_DIR"] = raw_dir + + tool_cmd = [tool_path, argument] + + try: + subprocess.run(tool_cmd, env=env, check=True) + except subprocess.CalledProcessError as e: + print(f"Build component '{tool}' failed for namespace '{namespace}' with exit code {e.returncode}", file=sys.stderr) + sys.exit(e.returncode) + +def CLI() -> None: + check_environment() + + repo_home = os.environ.get("REPO_HOME", ".") + dev_dir = os.path.join(repo_home, "developer") + os.chdir(dev_dir) + + args = sys.argv[1:] + namespaces = get_namespaces() + + if not args or args[0] in ["usage", "help", "-h", "--help"]: + print_usage(namespaces) + sys.exit(0) + + matched_any = False + ns_keys = list(namespaces.keys()) + + for TM_arg in args: + parts = TM_arg.split(":") + pattern = parts[0] + arguments = parts[1:] + + if not arguments: + arguments = ["all"] + + matches = fnmatch.filter(ns_keys, pattern) + + if not matches: + print(f"(warning) Pattern '{pattern}' matched no namespaces.", file=sys.stderr) + continue + + matched_any = True + for TM_ns in matches: + tool, raw_dir = namespaces[TM_ns] + for TM_argument in arguments: + run_build(TM_argument, TM_ns, tool, raw_dir) + + if not matched_any: + sys.exit(1) + + print("build done.") + +if __name__ == "__main__": + CLI() diff --git a/developer/tool/build_component/copy b/developer/tool/build_component/copy new file mode 100755 index 0000000..0a1998c --- /dev/null +++ b/developer/tool/build_component/copy @@ -0,0 +1,59 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- +# developer/tool/build_component/copy + +import sys +import os +import shutil + +sys.path.insert(0, os.path.join(os.path.abspath("tool"), "build_component")) +import sync_engine + +HELP = """usage: copy {all|clean|help} + all Stages files from authored to scratchpad/made/. + clean Removes scratchpad/made/. + help Shows this message. +""" + +def cmd_all(): + namespace = os.environ.get("NAMESPACE") + namespace_dir = os.environ.get("NAMESPACE_DIR") + + if not namespace or not namespace_dir: + print("copy: error: NAMESPACE and NAMESPACE_DIR environment variables must be set.", file=sys.stderr) + sys.exit(1) + + src_root = os.path.join("authored", namespace_dir) + dst_root = os.path.join("scratchpad", "made", namespace) + + sync_engine.execute_sync(src_root, dst_root, prefix="copy", apply_modes=False) + +def cmd_clean(): + namespace = os.environ.get("NAMESPACE") + if not namespace: + print("copy: error: NAMESPACE environment variable must be set.", file=sys.stderr) + sys.exit(1) + + dst_root = os.path.join("scratchpad", "made", namespace) + if os.path.exists(dst_root): + shutil.rmtree(dst_root) + print(f"copy: Cleaned {dst_root}") + +def CLI(): + if len(sys.argv) < 2: + cmd = "all" + else: + cmd = sys.argv[1] + + if cmd == "all": + cmd_all() + elif cmd == "clean": + cmd_clean() + elif cmd in ["help", "-h", "--help"]: + print(HELP) + else: + print(f"copy: Unrecognized command '{cmd}'", file=sys.stderr) + sys.exit(1) + +if __name__ == "__main__": + CLI() diff --git a/developer/tool/build_component/make b/developer/tool/build_component/make new file mode 100755 index 0000000..833c27c --- /dev/null +++ b/developer/tool/build_component/make @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# developer/tool/build_component/make + +set -euo pipefail +CMD="${1:-all}" + +# The GNU Make orchestrator expects C_SOURCE_DIR to point to the raw directory +export C_SOURCE_DIR="authored/$NAMESPACE_DIR" +export KMOD_SOURCE_DIR="authored/$NAMESPACE_DIR" + +# Isolate build products into their specific namespace directory +export LIBRARY_DIR="scratchpad/made/$NAMESPACE" +export MACHINE_DIR="scratchpad/made/$NAMESPACE" + +# Harmony.mk is the makefile run; it includes tool/build_component/project.mk, +# the project's settings, and the namespace's *.mk files. +/bin/make -f "$REPO_HOME/shared/tool/makefile/Harmony.mk" "$CMD" diff --git a/developer/tool/build_component/project.mk b/developer/tool/build_component/project.mk new file mode 100644 index 0000000..a362ead --- /dev/null +++ b/developer/tool/build_component/project.mk @@ -0,0 +1,20 @@ +# developer/tool/build_component/project.mk +# +# The project's make settings, for every namespace the project builds with +# make. Harmony.mk includes this file after its own defaults and before the +# namespace's *.mk files, which have the last say. This file holds settings, +# not rules for building: Harmony.mk has those. +# +# Add to a default with +=, replace one with :=, for example: +# +# CFLAGS += -O2 +# LN_FLAGS += -lm +# +# Settings for one namespace go in a .mk file beside its source instead, such +# as authored/.make/.mk. That file is also staged and +# promoted with the namespace's library, so a project built against the +# library reads the same settings. +# +# Harmony.mk's information and clean are double-colon rules, so a recipe +# added here as 'information::' or 'clean::' runs as well as Harmony.mk's. +# Make runs them in the order it read them, so this file's runs first. diff --git a/developer/tool/build_component/sync_engine.py b/developer/tool/build_component/sync_engine.py new file mode 100644 index 0000000..cf6412b --- /dev/null +++ b/developer/tool/build_component/sync_engine.py @@ -0,0 +1,80 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- +# developer/tool/sync_engine.py + +import os +import sys +import shutil +import filecmp +import stat +import tempfile + +def copy_file_atomic(src_abs, dst_abs, mode, dry=False, prefix="sync"): + if dry: + print(f"(dry) {prefix}: install -m {oct(mode)[2:]} '{src_abs}' -> '{dst_abs}'") + return + + parent = os.path.dirname(dst_abs) + os.makedirs(parent, exist_ok=True) + + fd, tmp_path = tempfile.mkstemp(prefix=".tmp.", dir=parent) + try: + with os.fdopen(fd, "wb") as tmpf, open(src_abs, "rb") as sf: + shutil.copyfileobj(sf, tmpf) + tmpf.flush() + os.chmod(tmp_path, mode) + os.replace(tmp_path, dst_abs) + except Exception as e: + if os.path.exists(tmp_path): + os.unlink(tmp_path) + raise e + +def execute_sync(src_root, dst_root, prefix="sync", dry=False, apply_modes=False, ignore_list=None): + wrote = False + if ignore_list is None: + ignore_list = [] + + if not os.path.isdir(src_root): + print(f"{prefix}: error: Source directory '{src_root}' does not exist.", file=sys.stderr) + return False + + for root, dirs, files in os.walk(src_root): + dirs.sort() + files.sort() + for fn in files: + if fn in ignore_list: + continue + + src_abs = os.path.join(root, fn) + rel = os.path.relpath(src_abs, src_root) + dst_abs = os.path.join(dst_root, rel) + + st = os.stat(src_abs) + if apply_modes: + is_exec = st.st_mode & stat.S_IXUSR + mode = 0o500 if is_exec else 0o400 + else: + mode = stat.S_IMODE(st.st_mode) + + if not os.path.exists(dst_abs): + copy_file_atomic(src_abs, dst_abs, mode, dry, prefix) + if not dry: print(f"{prefix}: Added {rel}") + wrote = True + continue + + if filecmp.cmp(src_abs, dst_abs, shallow=False): + continue + + dst_st = os.stat(dst_abs) + if dst_st.st_mtime > st.st_mtime: + print(f"{prefix}: error: {rel} skipped. Destination version is newer.") + continue + + copy_file_atomic(src_abs, dst_abs, mode, dry, prefix) + if not dry: print(f"{prefix}: Updated {rel}") + wrote = True + + if not wrote and not dry: + print(f"{prefix}: (info) nothing new to synchronize from {src_root}") + + return wrote diff --git a/developer/tool/promote b/developer/tool/promote new file mode 100755 index 0000000..7292374 --- /dev/null +++ b/developer/tool/promote @@ -0,0 +1,261 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- +# developer/tool/promote + +import os +import sys +import shutil +import stat +import pwd +import grp +import filecmp + +# Calculate the path relative to this script's location +SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__)) +# Assumes this script is in developer/tool/ +# sync_engine is in developer/tool/build_component +sys.path.insert(0, os.path.join(SCRIPT_DIR, "build_component")) +import sync_engine + +HELP = """usage: promote {write|clean|ls|diff|help|dry write} + write Copies what is staged in scratchpad/made into consumer. Only updates newer files. + clean Remove all contents of the consumer directory (preserves .gitignore). + ls List consumer as an indented tree: PERMS OWNER NAME. + diff List missing, orphaned, or out of sync files between scratchpad/made and consumer. + help Show this message. + dry write Preview what write would do without modifying the filesystem. + +Promoted files are read-only: 400, or 500 when executable. Directories below +consumer/ are 500, so not even the owner can add, replace or remove a file in +them; write and clean open them (700) for the duration and lock them again. +consumer/ itself stays 700, as it holds the .gitignore git manages. +""" + +SETUP_MUST_BE = "developer/tool/setup" +DEFAULT_DIR_MODE = 0o700 +LOCKED_DIR_MODE = 0o500 + +def exit_with_status(msg, code=1): + print(f"promote: {msg}", file=sys.stderr) + sys.exit(code) + +def assert_setup(): + setup_val = os.environ.get("SETUP", "") + if setup_val != SETUP_MUST_BE: + hint = ( + "SETUP is not 'developer/tool/setup'.\n" + "Enter the developer role with: ./setup developer\n" + "That script exports: ROLE=developer; SETUP=$ROLE/tool/setup" + ) + exit_with_status(f"bad environment: SETUP='{setup_val}'. {hint}") + +def repo_home(): + rh = os.environ.get("REPO_HOME") + if not rh: + exit_with_status("REPO_HOME not set") + return rh + +def dpath(*parts): + return os.path.join(repo_home(), "developer", *parts) + +def cpath(*parts): + return os.path.join(repo_home(), "consumer", *parts) + +def ensure_mode(path_str, mode): + try: os.chmod(path_str, mode) + except Exception: pass + +def ensure_dir(path_str, mode=DEFAULT_DIR_MODE, dry=False): + if dry: + return + os.makedirs(path_str, exist_ok=True) + ensure_mode(path_str, mode) + +def consumer_subdirs(root_dp): + """Every directory below root_dp; root_dp itself is not included.""" + found = [] + for TM_root, TM_dirs, TM_files in os.walk(root_dp): + for TM_d in TM_dirs: + found.append(os.path.join(TM_root, TM_d)) + return found + +def set_subdir_modes(root_dp, mode): + for TM_d in consumer_subdirs(root_dp): + ensure_mode(TM_d, mode) + +def filemode(m): + try: return stat.filemode(m) + except Exception: return oct(m & 0o777) + +def owner_group(st): + try: return f"{pwd.getpwuid(st.st_uid).pw_name}:{grp.getgrgid(st.st_gid).gr_name}" + except Exception: return f"{st.st_uid}:{st.st_gid}" + +def list_tree(root_dp): + if not os.path.isdir(root_dp): + return + + entries = [] + def gather(path_str, depth, is_root): + try: + it = list(os.scandir(path_str)) + except FileNotFoundError: + return + dirs = [TM_e for TM_e in it if TM_e.is_dir(follow_symlinks=False)] + files = [TM_e for TM_e in it if not TM_e.is_dir(follow_symlinks=False)] + dirs.sort(key=lambda TM_e: TM_e.name) + files.sort(key=lambda TM_e: TM_e.name) + + if is_root: + for TM_f in (TM_e for TM_e in files if TM_e.name.startswith(".")): + st = os.lstat(TM_f.path) + entries.append((False, depth, filemode(st.st_mode), owner_group(st), TM_f.name)) + for TM_d in dirs: + st = os.lstat(TM_d.path) + entries.append((True, depth, filemode(st.st_mode), owner_group(st), TM_d.name + "/")) + gather(TM_d.path, depth + 1, False) + for TM_f in (TM_e for TM_e in files if not TM_e.name.startswith(".")): + st = os.lstat(TM_f.path) + entries.append((False, depth, filemode(st.st_mode), owner_group(st), TM_f.name)) + else: + for TM_d in dirs: + st = os.lstat(TM_d.path) + entries.append((True, depth, filemode(st.st_mode), owner_group(st), TM_d.name + "/")) + gather(TM_d.path, depth + 1, False) + for TM_f in files: + st = os.lstat(TM_f.path) + entries.append((False, depth, filemode(st.st_mode), owner_group(st), TM_f.name)) + + gather(root_dp, 1, True) + + ogw = 0 + for TM_isdir, TM_depth, TM_perms, TM_ownergrp, TM_name in entries: + if len(TM_ownergrp) > ogw: + ogw = len(TM_ownergrp) + + print("consumer/") + for TM_isdir, TM_depth, TM_perms, TM_ownergrp, TM_name in entries: + indent = " " * TM_depth + print(f"{TM_perms} {TM_ownergrp:<{ogw}} {indent}{TM_name}") + +def cmd_write(dry=False): + dst_root = cpath() + ensure_dir(dst_root, DEFAULT_DIR_MODE, dry=dry) + src_root = dpath("scratchpad", "made") + + # Files are replaced by writing a temporary file beside them and renaming + # it into place, which needs write permission on the directory. + if not dry: set_subdir_modes(dst_root, DEFAULT_DIR_MODE) + try: + sync_engine.execute_sync( + src_root, + dst_root, + prefix="promote", + dry=dry, + apply_modes=True, + ignore_list=[".gitignore"] + ) + finally: + if not dry: set_subdir_modes(dst_root, LOCKED_DIR_MODE) + +def cmd_diff(): + dst_root = cpath() + src_root = dpath("scratchpad", "made") + + src_files = set() + if os.path.isdir(src_root): + for TM_root, TM_dirs, TM_files in os.walk(src_root): + for TM_fn in TM_files: + if TM_fn == ".gitignore": + continue + src_files.add(os.path.relpath(os.path.join(TM_root, TM_fn), src_root)) + + dst_files = set() + if os.path.isdir(dst_root): + for TM_root, TM_dirs, TM_files in os.walk(dst_root): + for TM_fn in TM_files: + if TM_fn == ".gitignore": + continue + dst_files.add(os.path.relpath(os.path.join(TM_root, TM_fn), dst_root)) + + if not src_files and not dst_files: + print("No differences found. Both directories are empty or missing.") + return + + all_files = sorted(list(src_files | dst_files)) + found_diff = False + + for TM_rel in all_files: + if TM_rel not in dst_files: + print(f"Pending promotion (missing in consumer): {TM_rel}") + found_diff = True + elif TM_rel not in src_files: + print(f"Orphaned in consumer (missing in scratchpad/made): {TM_rel}") + found_diff = True + else: + src_abs = os.path.join(src_root, TM_rel) + dst_abs = os.path.join(dst_root, TM_rel) + + if not filecmp.cmp(src_abs, dst_abs, shallow=False): + src_mtime = os.stat(src_abs).st_mtime + dst_mtime = os.stat(dst_abs).st_mtime + + if src_mtime > dst_mtime: + print(f"Pending update (contents differ, newer in scratchpad/made): {TM_rel}") + else: + print(f"Contents differ (locally modified in consumer): {TM_rel}") + found_diff = True + + if not found_diff: + print("No differences found. Consumer matches developer scratchpad/made.") + +def cmd_clean(): + consumer_root_dir = cpath() + if not os.path.isdir(consumer_root_dir): + return + # Removing an entry needs write permission on the directory holding it. + set_subdir_modes(consumer_root_dir, DEFAULT_DIR_MODE) + for TM_name in os.listdir(consumer_root_dir): + if TM_name == ".gitignore": + continue + p = os.path.join(consumer_root_dir, TM_name) + if os.path.isdir(p) and not os.path.islink(p): + shutil.rmtree(p, ignore_errors=True) + else: + try: os.unlink(p) + except FileNotFoundError: pass + +def CLI(): + assert_setup() + + repo_home = os.environ.get("REPO_HOME", ".") + dev_dir = os.path.join(repo_home, "developer") + os.chdir(dev_dir) + + if len(sys.argv) < 2: + print(HELP) + return + + cmd = sys.argv[1] + args = sys.argv[2:] + + if cmd == "write": + cmd_write(dry=False) + elif cmd == "clean": + cmd_clean() + elif cmd == "ls": + list_tree(cpath()) + elif cmd == "diff": + cmd_diff() + elif cmd == "help": + print(HELP) + elif cmd == "dry": + if args and args[0] == "write": + cmd_write(dry=True) + else: + print(HELP) + else: + print(HELP) + +if __name__ == "__main__": + CLI() diff --git a/developer/tool/setup b/developer/tool/setup new file mode 100644 index 0000000..0b993ad --- /dev/null +++ b/developer/tool/setup @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") + diff --git a/document/introduction_Harmony.html b/document/introduction_Harmony.html new file mode 100644 index 0000000..432c63b --- /dev/null +++ b/document/introduction_Harmony.html @@ -0,0 +1,249 @@ + + + + + Introduction to Harmony + + + + + + + + + + + +

    Purpose

    +

    + Harmony is a project skeleton: a language-agnostic directory structure and a set of maintenance tools, kept in a git repository, from which new projects are made. It is designed for long-lived software developed by a team, and serves equally well for one person, who takes on each role in turn. The structure exists to give: +

    +
      +
    1. Clarity about where things live. +
        +
      • Role-based work areas.
      • +
      • Separation of skeleton, team member authored, machine-made, and depended-upon software.
      • +
      +
    2. +
    3. A safe, predictable build and promotion workflow.
    4. +
    + +

    Making a project

    +

    + A project administrator makes a new project from a clone of Harmony, by taking on the administrator role and running new-project with the name of the new project: +

    + + > cd Harmony + > ./setup administrator + > new-project <name> + +

    + new-project makes the new project as a sibling directory of Harmony, then: +

    +
      +
    1. Copies the files of Harmony's last commit, leaving out Harmony's git history, untracked files, and uncommitted changes.
    2. +
    3. Renames 0pus_Harmony to 0pus_<name>.
    4. +
    5. Adds a line for the new project to shared/tool/version.
    6. +
    7. Initializes a git repository on the core-developer_branch branch, and commits the copied skeleton.
    8. +
    9. Adds any remote repositories given as -remote <url>.
    10. +
    +

    + Because the new project starts with its own git history, work done in it cannot be checked in to the Harmony skeleton by accident. +

    +

    + Leave the Harmony line in the version file. It records which skeleton the project was made from, so that an administrator can later see what has changed in the skeleton since, and bring the project up to date. The administrator tool skeleton_diff compares a project with a Harmony checkout for this purpose. +

    + +

    Taking on a role

    +

    + A person works in a project by taking on a role. The roles are administrator, developer, tester, and consumer. From the top directory of the project, run setup with the role: +

    + + > ./setup developer + +

    + setup starts a new bash shell configured for the role, and leaves the person in the role's directory. The prompt shows the project and the role. exit leaves the role and returns to the shell setup was run from. It is common to have several terminal windows or Emacs shells open, each in a different role. +

    +

    + Python programmers will recognize this as similar to a virtual environment. Harmony calls it the project setup, and the command is setup rather than activate. Unlike a Python virtual environment, there is one setup for each role. +

    +

    + In the new shell, the setup: +

    +
      +
    • Sets ROLE, ROLE_HOME and SETUP, and puts <role>/tool on the PATH.
    • +
    • Sources the project-wide shared/tool/setup, which sets REPO_HOME and PROJECT, puts shared/tool and shared/authored on the PATH, and sources each project dependency's .init file.
    • +
    • Sources shared/authored/setup, when the project has one, for project-specific additions to every role.
    • +
    • Changes into the role's directory and sources <role>/tool/setup, the setup customized for that role in this project.
    • +
    • When running inside Emacs, copies the environment to Emacs with env_to_emacs.
    • +
    +

    + Tools rely on this environment. Absolute paths are formed from REPO_HOME, and some tools, such as build and promote, refuse to run outside the role they belong to. +

    + +

    Roles and their directories

    +

    + Each role has a directory at the top of the project. The shared directory holds what all roles use. +

    + +

    Administrator

    +

    + The administrator keeps the project in step with the Harmony skeleton, maintains the role environments, installs project dependencies, and makes releases. administrator/tool holds the tools for this, among them new-project, skeleton_diff, and archive, which writes an archive of the repository to the scratchpad. +

    + +

    Developer

    +

    + The developer writes the project's source and builds it. +

    +
      +
    • authored/ : Source written by the team. Tracked.
    • +
    • document/ : Documents for developers, such as coding and naming conventions.
    • +
    • experiment/ : Informal, short-lived trials.
    • +
    • scratchpad/ : Untracked. Intermediate build files and the staged products of a build.
    • +
    • tool/ : The developer's tools, including build and promote.
    • +
    + +

    Tester

    +

    + The tester holds the formal tests, including regression suites, and runs them against the work product in consumer/. A developer may keep informal tests in developer/experiment. A test that is to be kept is moved to tester/, which keeps writing code and validating it apart. +

    + +

    Consumer

    +

    + consumer/ receives the work product when a developer promotes it. It is untracked, apart from its .gitignore, and is treated as a deployment target: files arrive there only through promote, and nothing is built in it. The consumer role uses the work product as its end users would. +

    + +

    Shared

    +
      +
    • shared/tool/ : Tools for all roles, and the project-wide setup. The version command prints the version lines.
    • +
    • shared/authored/ : Project-specific additions for all roles. It is on every role's PATH, and may hold a setup that every role sources.
    • +
    • shared/project-dependency/ : Software the project uses but did not author. See "Project dependencies" below.
    • +
    + +

    Building and promoting

    +

    + Building and promotion are separate steps. In the developer role, build makes the work product from developer/authored and stages it on the developer's scratchpad. promote write then copies what changed to consumer/. The result is a promotion candidate, which stays as it is until the next promotion. +

    +

    + Source in developer/authored is grouped into directories named <Namespace>.<Tool>. The suffix names the build component in developer/tool/build_component that builds that directory, such as make for C, or copy for files used as they are. Given no arguments, build prints its usage and the namespaces it found. promote given no arguments prints its commands, among them dry write, which shows what write would copy. +

    +

    + The tester runs tests against the promotion candidate. Tests read from consumer/ and never write to it, though a tester may copy files elsewhere to experiment with them. A developer often has a second window open in the tester role, and cycles through edit, build, promote and test. +

    + +

    After cloning a project

    +

    + Built products are not tracked, so a fresh clone has an empty consumer/. A team member who needs the work product builds it, taking on the developer role to do so: +

    + + > ./setup developer + > build <namespace> + > promote write + > exit + > ./setup <role> + +

    + The developer documents any project-specific build steps in developer/document/build.html. A fresh clone also lacks the project's dependencies, which each team member installs as described beside each dependency in shared/project-dependency. +

    + +

    Project dependencies

    +

    + Harmony is language agnostic. When a project uses C, Python, NodeJS, Java, or other software it did not author, the administrator installs that software as a sibling directory of the project and links it in under shared/project-dependency, with an .init file that every role's setup sources to put the dependency into the environment. Installation notes for each dependency sit beside its .init file, so that each team member can repeat the installation after cloning. +

    +

    + The directory comes with a project link to the directory holding the project and its siblings, through which dependencies are linked, and with Python as an example dependency. The steps are given in administrator/document/how-to_add-project-dependency.html. +

    + +

    Directory names

    +

    + A directory name is a property of each file in the directory, so a full path reads as a description of the file. Because a name states a property of each file, it is rarely plural: when every file in a directory is a test, the directory is named test. +

    +

    + A conventional file system can only approximate a property-based one. Each file sits in one directory, so it receives one property per level of the path. Files sharing several properties can be given a compound name with the properties separated by an underscore, but overlapping groupings cannot be expressed. +

    +

    + When choosing a directory name, prefer properties in this order: +

    +
      +
    • Role (administrator, developer, tester, consumer): the role, human or AI, that works with the files.
    • +
    • Provenance (authored, made): whether a person wrote the file or a tool produced it.
    • +
    • Capability (tool, document, experiment): what the file is for.
    • +
    • Lifecycle (scratchpad, stage): how long the file is expected to last, or where it is in promotion.
    • +
    • Tracking (tracked, untracked): what version control does with it.
    • +
    + +

    Authored, made, scratchpad, inherited

    +

    + Files in a directory named authored were written by the project's team. They did not come with the skeleton, nor with the installation of other software, and they typically constitute the project's intellectual property. Build tools treat authored directories as read-only. All source that is built into a promotion or a release is placed in developer/authored. +

    +

    + Files that came with the skeleton are inherited. When the team edits one, such as developer/tool/build, it becomes a customization. New documents go in document directories and new tools in tool directories. Because the Harmony line stays in the version file, an administrator can tell which skeleton files a project has customized and which it has added. +

    +

    + Files in a directory named scratchpad are untracked, so a clone always has empty scratchpads. Tools place intermediate and staged files there, each in its own subdirectory, so a person who knows those names can also use a scratchpad as a temporary directory. The scratchpad tool maintains the scratchpad of the current directory. Note that its clear command deletes everything on that scratchpad. +

    + +

    Documents

    +

    + Each directory named document holds documents for the role, or the scope, of its parent: +

    +
      +
    • document/ : The project as a whole, such as this introduction.
    • +
    • administrator/document/ : Maintaining the project skeleton, adding dependencies, and making releases.
    • +
    • developer/document/ : Coding standards, conventions, and the build.
    • +
    • tester/document/ : Test plans and testing tools.
    • +
    • consumer/<namespace>/document/ : Documents released with the work product, such as manuals and API references.
    • +
    +

    + Documents are written in HTML with the RT semantic tags, and formatted by RT-Style, a separate project at https://github.com/Thomas-Walker-Lynch/RT-Style. A document loads RT-Style through a short script block at the top of its head. To write a new document, copy an existing one, keep that block as it is, and type over the contents. +

    +

    + Documents are read in Chrome. With nothing set up, a document loads RT-Style from style.ReasoningTechnology.com. To read without a network connection, or against a local copy of RT-Style, open that copy's Manuscript/setup.html once in Chrome. Chrome then loads RT-Style from it for every local document. +

    +

    + document/writing_tool-script.html gives the conventions for writing tools. +

    + +

    What git tracks

    +

    + Everything is tracked except: +

    +
      +
    • consumer/, apart from its .gitignore.
    • +
    • Every scratchpad/, apart from its .gitignore.
    • +
    • In shared/project-dependency/, whatever its .gitignore does not list as tracked.
    • +
    • Archives, editor backups, and compiled files, as listed in the top-level .gitignore.
    • +
    + +

    Workflow and releases

    +

    + The project moves forward through a cycle: the developer promotes a candidate, the tester tests it and files issues, and the developer fixes them and promotes again. The core-developer_branch is the branch the core development team works on. When the product manager judges the work product reliable and complete enough, the administrator makes a project release on a branch named release_v<major>, and tags it. +

    +

    + These documents give the details: +

    +
      +
    • document/role-and-workflow_product-development.html : The roles, and how their work interacts.
    • +
    • document/role-and-workflow_product-maintenance.html : Issues, triage, and patching releases.
    • +
    • administrator/document/how-to_release.html : Making a release.
    • +
    + +
    + + diff --git a/document/role-and-workflow_product-development.html b/document/role-and-workflow_product-development.html new file mode 100644 index 0000000..411b732 --- /dev/null +++ b/document/role-and-workflow_product-development.html @@ -0,0 +1,134 @@ + + + + + Product development roles and workflow + + + + + + + + + + + +

    Roles as hats

    +

    + In Harmony, a role is a hat a person wears. There can be multiple people sharing a single role, and a single person can wear many hats. Some roles interact directly with the project directory structure, while others guide the process from outside the codebase. +

    + +

    Workspace roles

    +

    + These roles interact directly with the repository. To enter a workspace, change directory to the top-level of the project and source the setup file for the desired role: +

    + + > ./setup administrator + > ./setup developer + > ./setup tester + > ./setup consumer + + +

    This will run a new shell with the proper environment setting. It is common for a person to have multiple shells, terminal sessions, or IDEs open, each running under a different role environment. Development and tests is a common pair, though tests are intended to be production tests. The developer has an experiment directory for experiments. +

    + +

    Administrator role

    +

    Responsibilities:

    +
      +
    1. Set up the project directory and keep it in sync with the Harmony skeleton.
    2. +
    3. Maintain role environments (apart from role-specific tool/setup files).
    4. +
    5. Install and maintain shared and third_party tools, addressing issues with the project workflow. Note that the term "third_party" encompasses any software not authored within this specific project.
    6. +
    + +

    Developer role

    +

    Responsibilities and Boundaries:

    +
      +
    1. Write and modify authored/ source.
    2. +
    3. Run builds and place artifacts in scratchpad/made, then execute the promote write script to copy artifacts to consumer/made for testing.
    4. +
    5. Run experiments in experiment/. These experiments can sometimes be promoted to formal tests, but there is no requirement to do so. The developer role should not blur into the tester role; experiments are informal, whereas tests are formal and retained.
    6. +
    7. Strict Boundary: A developer never writes into the tester/ directory. Instead, a developer adds tests to developer/experiment/ and offers to share them.
    8. +
    + +

    Tester role

    +

    Responsibilities and Boundaries:

    +
      +
    1. Evaluate candidates under consumer/made/ and run regression suites to confirm: +
        +
      • That the code does not crash.
      • +
      • That consumers do not have a bad experience.
      • +
      • That the goals specified by the product manager are met.
      • +
      +
    2. +
    3. File issues and communicate feedback to the developers.
    4. +
    5. Strict Boundary: A tester never patches code in the developer/ directory. Instead, the tester files issues or proposes code fixes on a separate branch.
    6. +
    + +

    Consumer role

    +

    Responsibilities:

    +
      +
    1. Act as the end-user simulation environment.
    2. +
    3. Consume and deploy artifacts exclusively from the consumer/made/ target.
    4. +
    5. Never author or modify code; strictly run local builds or deployments for architecture-specific testing.
    6. +
    7. Report issues. (Anyone can report an issue, and consumers regularly do).
    8. +
    + +

    External roles

    +

    + These roles drive the project forward but do not have a dedicated setup <role> workspace, as they do not directly build or test the code in that capacity. If these individuals need to interface with the code, they simply put on a workspace role hat, such as administer, developer, tester, or consumer. +

    + +

    Product manager

    +

    + The product manager receives specifications from the architect and sets the specific goals for a release. When the project manager provides updates indicating readiness, the product manager makes the final decision to cut a project release. +

    + +

    Project manager

    +

    + The project manager owns the schedule (such as the Gantt chart) and monitors progress. They coordinate code reviews, read issues and announcements, reformulate the schedule, and instruct the product manager. When parts of the codebase are outsourced, the project manager serves as the primary point of contact with the external teams. +

    + +

    Architect

    +

    + The architect writes the original specification, sets the technical direction, and performs code reviews. The architect might be a contractor or an in-house team member. +

    + +

    The four interacting loops

    +

    + The project moves forward through the continuous interaction of four distinct operational cycles. +

    + +
      +
    1. Developer Loop: Write code, compile to the scratchpad made directory, promote to the consumer made directory, announce the promotion to the tester, read issues, and repeat.
    2. +
    3. Tester Loop: Read developer announcements, read the consumer made directory, run tests, and file issues.
    4. +
    5. Product Manager Loop: Provide specifications to the developer, receive progress updates from the project manager, and instruct the project administrator to make new git branch project releases and deploy.
    6. +
    7. Project Manager Loop: Own the Gantt chart, coordinate code reviews, read issues and announcements, reformulate the Gantt chart, and instruct the product manager.
    8. +
    + +

    Promotion mechanics

    +

    + Building and promotion are separate activities. The developer compiles and places files in developer/scratchpad/made. The developer then runs promote write to transfer those files to consumer/made. +

    +

    + The consumer/made directory is strictly an untracked deployment target. No tools are permitted to rebuild during promotion, and no builds are run directly inside the consumer made directory. +

    + +
    + + diff --git a/document/role-and-workflow_product-maintenance.html b/document/role-and-workflow_product-maintenance.html new file mode 100644 index 0000000..e93f12d --- /dev/null +++ b/document/role-and-workflow_product-maintenance.html @@ -0,0 +1,111 @@ + + + + + Product maintenance roles and workflow + + + + + + + + + + + +

    Maintenance philosophy

    +

    + Deployed software must be a usable quality product for the customer, beyond that we favor addressing issues in new releases, and encourage customers who are having issues to upgrade. This approach is purely one of keeping the maintenance problem tractable. +

    + +

    Maintenance structure

    +

    + Teams mentioned in this document: +

    +
      +
    1. tester team
    2. +
    3. core developer team
    4. +
    5. branch maintenance team
    6. +
    7. triage team
    8. +
    + +

    + Team membership is a role a person takes on. Multiple people can share a single role, and one person might take on multiple roles. +

    + +

    + The tester team develops and maintains the regression suite, the reliability suite, and additional tests. +

    + +

    + The core developer team writes the source code and compiles promotion candidates. +

    + +

    + The branch maintenance team is typically a subset of the core developer team. This group is dedicated to applying approved fixes to specific release branches. +

    + +

    + The triage team evaluates defects reported against active releases. The team usually includes a developer contact, the project manager, and the product manager. +

    + +

    Issue queues

    +

    + The project maintains two primary issue queues: +

    +
      +
    1. released product
    2. +
    3. core developer
    4. +
    + +

    + There can be additional queues for multiple branches of development, and for experiments. +

    + +

    Core developer queue

    +

    + This queue serves the core_developer_branch. A tester writes a test for every issue reported in this queue. Doing so isolates the defect, proves the fix, and guards against future regressions. +

    + +

    Released product queue

    +

    + All issues found in release branches go onto this queue initially. It tracks defects reported against deployed software across any major version. +

    + +

    Triage and patching

    +

    + Guided by the project philosophy, the triage team reviews each release queue issue to determine its impact. The team assesses whether the defect affects the core_developer_branch, assuming by default that it probably does. The team also determines if the defect is critical enough to warrant a patch on one or more active release branches. +

    +

    + Based on this assessment, the triage team files actionable tickets in the core developer queue. A ticket explicitly specifies its target branches. A ticket will be filed against either the core developer branch, specific release branches, or a combination of both. +

    +

    + Members of the tester team also file tickets directly into the core developer queue when they discover defects in the core branch. +

    +

    + Responsibility for resolving a ticket depends on its target. The core developer team addresses fixes required on the core_developer_branch. The branch maintenance team addresses fixes required on the release_v<major> branches. +

    +

    + When a release is patched, the branch name remains static. The administrator advances the minor release number in the shared/tool/version file and tags the commit. +

    + +
    + + diff --git a/document/writing_tool-script.html b/document/writing_tool-script.html new file mode 100644 index 0000000..5942d3f --- /dev/null +++ b/document/writing_tool-script.html @@ -0,0 +1,287 @@ + + + + + Writing a tool script + + + + + + + + + + + +

    Purpose

    + +

    + A tool is a script a person runs from a role setup to do work on files. This document gives the conventions for how an RT tool presents itself on the command line, reports what it does, and changes files safely. It complements RT-code-format.html, which covers identifier names, layout, and the separation of the CLI() function from the work functions. Those rules apply here and are not repeated. +

    + +

    + The conventions serve three needs of the person at the keyboard. They must be able to see what a tool will do before it does it, read afterward what it did, and run it again without harm. +

    + +

    + Examples are taken from RT-Style_header_v5_to_v6, the administrator tool that converts RT-Style version 5 document headers to version 6. +

    + +

    The command line

    + +

    No arguments prints the help

    + +

    + A tool given no arguments prints its help message and exits with status 0. A person who types the bare name of a tool is asking what it does. Nothing on the file system changes. +

    + +

    The first argument is a command

    + +

    + The first argument names a command, written as a word, not a flag. The words help, -h and --help all print the help message. Further arguments, when a command accepts any, follow the command. A command that accepts no further arguments rejects them with an error. +

    + +

    + An unknown command prints an error naming it, then the help message, and exits with a nonzero status. +

    + +

    The help message is the module docstring

    + +

    + In Python the help message is the module docstring, printed by print(__doc__.strip()). The documentation at the top of the file and the message the person sees are then the same text, and cannot drift apart. The docstring opens with the tool name, a paragraph on what the tool does, then the usage and one line per command: +

    + + + Usage: RT-Style_header_v5_to_v6 <command> [file ...] + RT-Style_header_v5_to_v6 preview <command> [file ...] + + help | -h | --help print this message (also printed when given no arguments) + project walk the directory tree rooted at $REPO_HOME + tree walk the directory tree rooted at the current directory + local only the current directory, no subdirectories + file <name> ... only the named .html files + preview <command> print the log of what <command> would do, change nothing + + +

    Scope commands

    + +

    + A tool that acts on files found in a directory tree offers the same four commands for choosing which files: +

    +
      +
    • project walks the tree rooted at $REPO_HOME. When REPO_HOME is not set, the command is an error. Otherwise it behaves as tree run from $REPO_HOME, from whatever directory the person is in.
    • +
    • tree walks the tree rooted at the current directory.
    • +
    • local acts on the current directory only, without descending.
    • +
    • file acts on the files named after it.
    • +
    + +

    + Only project depends on a Harmony project. The others work anywhere, because the files a tool serves are not always in a project. RT-Style documents, for example, appear in projects and outside them. +

    + +

    Preview

    + +

    + A tool that changes files offers preview, placed before any other command. preview tree prints the log that tree would print and changes nothing. The person reads it, decides, then runs the command without preview. +

    + +

    + Preview is not a separate code path. The work functions are given a preview flag and test it only at the point of each action, immediately before writing or deleting. Everything else, finding files, deciding what to do, and logging, runs the same in both modes. A preview log that came from different code could not be trusted to describe the real run. +

    + +

    The log

    + +

    + A tool that acts on files prints a log of each thing it did. The log is for a person reading a terminal, and for that same person reading it again in a scrollback or a saved file later. This is the log of converting the Harmony skeleton documents, with the path on the first line shortened to fit the page: +

    + + + RT-Style_header_v5_to_v6 project in /home/Thomas/.../project/Harmony + converted administrator/document/how-to_release.html + converted developer/document/naming_file-and-directory.html + converted developer/document/single-file_C-module-and-namespace.html + converted document/introduction_Harmony.html + converted document/role-and-workflow_product-development.html + converted document/role-and-workflow_product-maintenance.html + + summary: + 6 .html files converted to version 6 + 0 RT-Manuscript_locator.js files deleted + 0 .html files already version 6 + 0 .html files with mentions to edit by hand + 0 other .html files left alone + + +
      +
    • The first line names the tool, the command, and the absolute directory the work is rooted in, so a saved log says where it came from.
    • +
    • Each action is one line. A fixed-width tag in the past tense says what happened, followed by the path relative to the root. Relative paths keep lines short and make logs from different machines comparable.
    • +
    • In a preview the tags read would convert, would delete, and the summary ends with preview only: nothing was changed.
    • +
    • A decision not to act is logged too, with the reason in parentheses, as in kept shared/document/RT-Manuscript_locator.js (no version 5 document beside it). A file the tool left alone on purpose must be distinguishable from one it missed.
    • +
    • Work the tool cannot do safely is logged with the tag edit by hand, the file, the line number and the line, as in edit by hand .../Document/user.html:83: &lt;script src=..., so a person can go straight to it.
    • +
    • A summary of counts ends the log. A count line that would always be zero for a run, such as errors, may be left out when it is zero.
    • +
    • Walk directories and files in sorted order, so two runs over the same tree produce the same log.
    • +
    + +

    + Errors are logged on their own lines with the tag error, the tool carries on with the remaining files, and the exit status is nonzero when any error occurred. Errors in the command line itself are printed to standard error before any work starts. +

    + +

    Walking directories

    + +

    + A tool walks every directory in its scope, whatever the directory is named. It does not skip directories by name, since a name that means nothing to the tool's author may hold files that matter to its user. +

    + +

    + A tool does not follow symbolic links to directories. A Harmony project has shared/project-dependency/project pointing to ../../../, the directory holding all the projects. Following it would send the walk into every neighboring project and around the loop back into this one. In Python, os.walk does not follow such links unless given followlinks=True, so leave that argument out. +

    + +

    Paths

    + +

    + A tool forms an absolute path only by starting from an environment variable that the role setup provides, such as $REPO_HOME. Paths the tool writes into files, and symbolic links it creates, are relative. +

    + +

    + An absolute path written into a file is correct for only one view of the file system. Under the subu arrangement, the master user reaches a sub-user's files through a mapped mount at a different absolute path from the one the sub-user sees. A path recorded by one of them is then unreadable, or points somewhere else, for the other. A relative path is resolved from wherever the file is reached, so it is correct in every view. +

    + +

    Changing files safely

    + +

    Checkpoint first

    + +

    + A tool edits files in place and does not make backup copies. The person checkpoints the project with git before running it, and reviews the result with git diff. Run preview first. +

    + +

    Change only what is recognized exactly

    + +

    + Match the precise form the tool was written to change, in the precise place it occurs. RT-Style_header_v5_to_v6 replaces a locator script line only when it stands alone on a line inside <head>. A mention of the locator anywhere else, such as an escaped example in a manual, is not touched. It is logged for a person to edit. +

    + +

    Keep everything not being changed

    + +

    + Carry over what the edit is not about: the indentation of a replaced line, line endings, file permissions, and every other line of the file byte for byte. After a run, git diff should show the intended change and nothing else. +

    + +

    Running twice does no harm

    + +

    + A second run of the same command finds nothing left to do, changes nothing, and says so in its summary. A tool achieves this by recognizing work already done. The header converter counts a file holding the version 6 block as already version 6 and leaves it alone. A person can therefore rerun a tool to confirm a job is complete, or to finish one that stopped part way. +

    + +

    Before deleting, check nothing still uses it

    + +

    + A tool deletes a file only when nothing remaining depends on it. In testing, the header converter run with file on two of six test documents in a directory deleted the shared locator file while the other four still needed it. The rule now is that a locator is deleted only when no unconverted version 5 document beside it still loads it. Otherwise it is kept, and the log names the documents still using it. +

    + +

    Leave alone what the tool cannot identify as its own

    + +

    + A file with the right name in an unexpected place is not evidence that the tool should remove it. The converter keeps a locator file that has no version 5 document beside it, and logs it as kept, leaving the decision to a person. +

    + +

    Testing a tool

    + +

    + Test a new tool on a copy of real material before it runs on the original. An archive of the project, extracted into a scratch directory, gives realistic files that can be discarded. +

    +
      +
    1. Run with no arguments, an unknown command, and each command's error cases, such as project with REPO_HOME unset or file naming a file that does not exist.
    2. +
    3. Run preview and confirm that nothing changed, for example with diff -r against an untouched copy.
    4. +
    5. Run each scope command from more than one directory, including from outside any project.
    6. +
    7. Run each command twice. The second run must report nothing left to do.
    8. +
    9. Run on part of a job, such as file on some of the documents in a directory, and confirm the rest still work.
    10. +
    11. Read the diff of a changed file in full.
    12. +
    + +

    A skeleton

    + +

    + A Python tool laid out to these conventions begins with #!/usr/bin/env python3, then the Emacs mode line the Harmony tools carry, which sets two-space indentation and no tabs. The rest of the skeleton follows: +

    + + + """ + tool_name + + What the tool does, in a paragraph. + + Usage: tool_name <command> [file ...] + tool_name preview <command> [file ...] + + help | -h | --help print this message, also printed given no arguments + project walk the tree rooted at $REPO_HOME + tree walk the tree rooted at the current directory + local only the current directory + file <name> ... only the named files + preview <command> print the log of <command>, change nothing + """ + + import sys ,os + from pathlib import Path + + def work(dirpa_root ,recursive ,preview): + ... + + 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." ,file=sys.stderr) + return 1 + + command ,rest = argv[0] ,argv[1:] + ... + + if __name__ == "__main__": + sys.exit(CLI()) + + +

    Exercises

    + +

    Exercise 1: The bare tool

    +

    + A tool named tidy deletes editor backup files ending in ~. When run with no arguments it deletes them from the current directory. List what is wrong with that behavior under these conventions, and give the command line it should have instead. +

    + +

    Exercise 2: A log line

    +

    + A tool prints Processing /home/Thomas/subu/developer/project/Two/document/a.html ... done for every file it looks at, whether or not it changed it. Rewrite the log for a run in which one of three files was changed, one was already correct, and one could not be read. +

    + +

    Exercise 3: A safe delete

    +

    + A tool replaces each include.css link in an HTML document with an inline style block, then deletes include.css from the directory. Describe the run in which this breaks a document, and the check that prevents it. +

    + +
    + + diff --git a/scratchpad/.gitignore b/scratchpad/.gitignore new file mode 100644 index 0000000..120f485 --- /dev/null +++ b/scratchpad/.gitignore @@ -0,0 +1,2 @@ +* +!/.gitignore diff --git a/setup b/setup new file mode 100755 index 0000000..d2a452a --- /dev/null +++ b/setup @@ -0,0 +1,116 @@ +#!/usr/bin/env python3 +# setup - enter a project role environment + +import os +import sys +import json +import argparse +import tempfile + +PROJECT_ROLES = ["administrator", "consumer", "developer", "tester"] + +# Role shells stack: setup run inside a role shell starts a shell in the new +# role, and exiting it returns to the shell it was started from. A loop +# through setup, such as one started from ~/.bashrc, is stopped at this depth. +DEPTH_MAX = 8 + +# The environment setup was first run from, before any role, recorded so that +# every role shell starts from it rather than from the role shell around it. +BASE_KEY = "RT_SETUP_BASE" + +# The outer role's values, for handing an Emacs shell buffer back on exit. +OUTER_KEY = ("REPO_HOME", "PROJECT", "ROLE", "PATH") + +def main(): + parser = argparse.ArgumentParser( + description="Enter a project role environment by spawning an isolated subshell." + ) + parser.add_argument("role", choices=PROJECT_ROLES, help="The project role to assume.") + args = parser.parse_args() + + outer = os.environ.copy() + + # A role shell started inside another would otherwise inherit the outer + # role's environment: its tool directory on PATH, its variables, and the + # shell functions the shared setup exports. So every role shell starts + # from the base environment, the one setup was first run from, however + # deeply role shells are stacked. RT_SETUP_DEPTH counts the role shells + # this process is inside. + depth = outer.get("RT_SETUP_DEPTH", "0") + depth = int(depth) if depth.isdigit() else 0 + if depth >= DEPTH_MAX: + print(f"setup: already {depth} role shells deep; refusing, to stop a loop through setup.") + sys.exit(1) + + base = None + if depth > 0 and BASE_KEY in outer: + try: + base = json.loads(outer[BASE_KEY]) + except ValueError: + base = None + if not isinstance(base, dict): + base = {k: v for k, v in outer.items() if not k.startswith("RT_SETUP_")} + + env = dict(base) + env[BASE_KEY] = json.dumps(base) + env["RT_SETUP_DEPTH"] = str(depth + 1) + if depth > 0: + for key in OUTER_KEY: + env[f"RT_SETUP_OUTER_{key}"] = outer.get(key, "") + + # Python-domain logic: Variables and Paths + # The project is the directory holding this file, whatever REPO_HOME the + # calling shell carries; an inherited REPO_HOME may name another project. + repo_home = os.path.dirname(os.path.realpath(__file__)) + role = args.role + role_home = os.path.join(repo_home, role) + tool_dir = os.path.join(role_home, "tool") + setup_file = os.path.join(role, "tool", "setup") + + env["ROLE"] = role + env["ROLE_HOME"] = role_home + env["SETUP"] = setup_file + + print(f"ROLE_HOME {role_home}") + + # Python-domain logic: Directory validation + if not os.path.isdir(role_home): + print(f"setup: failed to locate directory for role '{role}'") + sys.exit(1) + + # Bash-domain logic: The rcfile only handles operations Python cannot inherit + # (sourcing bash functions) and performs the directory change internally to + # guarantee the shared scripts are sourced from the project root. + bash_logic = [ + 'if [[ -f ~/.bashrc ]]; then source ~/.bashrc; fi', + 'if [[ -f "shared/tool/setup" ]]; then source "shared/tool/setup"; fi', + 'if [[ -f "shared/authored/setup" ]]; then source "shared/authored/setup"; fi', + '# the role tool directory is searched before everything the shared setup added', + f'PATH="{tool_dir}:$PATH"; export PATH', + f'cd "{role}"', + 'if [[ -f "tool/setup" ]]; then', + ' source "tool/setup"', + f' echo "in environment: {setup_file}"', + 'else', + f' echo "not found: {setup_file}"', + 'fi', + 'if [[ -n "${INSIDE_EMACS}" ]] && command -v env_to_emacs >/dev/null 2>&1; then', + ' env_to_emacs', + ' # inside another role shell: on exit, hand the Emacs buffer back to the outer role', + ' if [[ -n "${RT_SETUP_OUTER_ROLE:-}" ]]; then', + ' rt_setup_env_to_emacs="$(command -v env_to_emacs)"', + ' trap \'REPO_HOME="$RT_SETUP_OUTER_REPO_HOME" PROJECT="$RT_SETUP_OUTER_PROJECT" ROLE="$RT_SETUP_OUTER_ROLE" PATH="$RT_SETUP_OUTER_PATH" "$rt_setup_env_to_emacs"\' EXIT', + ' fi', + 'fi', + 'rm -f "${BASH_SOURCE[0]}"' + ] + + fd, rcfile_path = tempfile.mkstemp(suffix="-rt-setup.sh") + with os.fdopen(fd, "w") as f: + f.write("\n".join(bash_logic) + "\n") + + os.chdir(repo_home) + os.execvpe("bash", ["bash", "--rcfile", rcfile_path], env) + +if __name__ == "__main__": + main() diff --git a/shared/authored/.gitkeep b/shared/authored/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/shared/project-dependency/.gitignore b/shared/project-dependency/.gitignore new file mode 100644 index 0000000..a033c31 --- /dev/null +++ b/shared/project-dependency/.gitignore @@ -0,0 +1,11 @@ +# shared/project-dependency/.gitignore +# Tracks the skeleton's parts. Add a ! line for anything else to track, +# such as a dependency's link. +* +!.gitignore +!project +!*.init +!*.install +!*.org +!*.html +!Python-3.12.3 diff --git a/shared/project-dependency/Python.init b/shared/project-dependency/Python.init new file mode 100644 index 0000000..f0b108d --- /dev/null +++ b/shared/project-dependency/Python.init @@ -0,0 +1,25 @@ +# -*- mode: sh; sh-shell: bash; -*- +# init files are bash script + +# Python.init +# -------------------------------------------------------------------------------- +# Put the project's Python build at the front of PATH, but only when it runs. +# +# Every '#!/usr/bin/env python3' script the person runs, their own tools +# included, takes the first python3 on PATH. A build that cannot start, for +# example one that lost its libpython after its directory moved, must not be +# put there, or all of those scripts fail with it. The test runs the +# interpreter once with an empty program. + +python_dp="$REPO_HOME/shared/project-dependency/Python-3.12.3" +if [[ ! -e "$python_dp" ]]; then + if [[ "$ROLE" == "administrator" ]]; then + echo "Python.init: no $python_dp; using the system python3" + fi +elif "$python_dp/bin/python3" -c '' 2>/dev/null; then + PATH="$python_dp/bin:$PATH" +else + echo "Python.init: $python_dp/bin/python3 does not run; using the system python3" >&2 + echo "Python.init: run it directly to see why, and see Python.org beside this file" >&2 +fi +unset python_dp diff --git a/shared/project-dependency/Python.org b/shared/project-dependency/Python.org new file mode 100644 index 0000000..8e67c79 --- /dev/null +++ b/shared/project-dependency/Python.org @@ -0,0 +1,71 @@ +#+TITLE: Python Installation Guide +#+AUTHOR: Project Administrator + +This project requires a dedicated Python environment. The configuration plugin (`shared/project-dependency/Python.init`) was written targeting Python 3.12.3, though the architecture does not rely on any known version-dependent features. + +The build below can be moved. Nothing in it records the absolute directory it was built in where the interpreter depends on it, so the directory can move with a home directory, or to another machine, and keep working. + +* 1. Install the development libraries + +Python's configure step looks for the development files of each optional library, and silently leaves out any module whose library it does not find. A build without sqlite3-devel, for example, has no sqlite3 module, and the gap shows only when a program imports it. Install these first. The names are for openSUSE; zypper search finds the name of one that differs. + +#+begin_src bash +sudo zypper install gcc make sqlite3-devel libopenssl-devel libffi-devel zlib-devel \ + readline-devel ncurses-devel xz-devel libbz2-devel gdbm-devel tk-devel libuuid-devel +#+end_src + +zlib-ng-compat-devel serves in place of zlib-devel, and the two conflict; if zypper reports that conflict, keep the one already installed. + +tk-devel gives the tkinter module, which the window programs use. + +* 2. Download and Extract +Download the Python source code and extract it as a sibling to the main project directory. Assuming you are at the top level of your project workspace: + +#+begin_src bash +cd ../ +wget https://www.python.org/ftp/python/3.12.3/Python-3.12.3.tgz +tar -xzf Python-3.12.3.tgz +cd Python-3.12.3 +#+end_src + +* 3. Build the Environment +Compile the Python binaries in place. Setting the installation prefix to the current directory isolates the build. + +#+begin_src bash +CONFIG_SITE= ./configure --prefix="$(pwd)" --libdir="$(pwd)/lib" --enable-optimizations +make -j8 2>&1 | tee build.log +make install +#+end_src + +Everything installs inside this directory; nothing is written to the system. + +CONFIG_SITE= and --libdir keep the machine's own defaults out of the build, so the recipe gives the same layout on every Linux. Some distributions, openSUSE and Fedora among them, name a site file in CONFIG_SITE that sets the library directory to lib64 for every configure script. Python then installs its compiled modules under lib64 while the interpreter looks for them under lib, and every import of a compiled module, such as ssl, fails. + +The build is static: the interpreter is one program, with no separate libpython3.12.so to find when it starts. A build with --enable-shared records the absolute path of its library directory in the program, and stops working when the directory moves. C extension modules, such as those pip installs, work with the static build. + +Near the end of build.log, make lists any optional modules it could not build, under "The necessary bits to build these optional modules were not found". nis, an obsolete network directory service, and _curses_panel may appear there; the project uses neither. For any other module listed, install the missing development library and build again. + +* 4. Check the build + +#+begin_src bash +bin/python3 -c 'import sys ,ssl ,sqlite3 ,ctypes ,lzma ,bz2 ,readline ,tkinter; print(sys.prefix)' +ldd bin/python3 | grep libpython # prints nothing: no shared libpython +#+end_src + +* 5. Use pip through the interpreter + +The scripts make install writes into bin/, such as pip3, start with a #! line naming the absolute path of the interpreter, so they break when the directory moves. Run pip as a module instead, which uses whichever interpreter runs it: + +#+begin_src bash +python3 -m pip install +#+end_src + +* 6. Link the Project + +Python-3.12.3 is linked to a Harmony derived project by default. + +See administrator/document/how-to_add-project-dependency.html for details about linking a project, if you want to check the setup. + +If you are installing a different version, then at least the Python-3.12.3 version project linking is there as a good example. + +Project linking is not difficult, make a sym link to `project/`, and then add an init file, as described in administrator/document/how-to_add-project-dependency.html. The 'project' in the link is literal. diff --git a/shared/project-dependency/project b/shared/project-dependency/project new file mode 120000 index 0000000..1b20c9f --- /dev/null +++ b/shared/project-dependency/project @@ -0,0 +1 @@ +../../../ \ No newline at end of file diff --git a/shared/tool/PATH.sh b/shared/tool/PATH.sh new file mode 100644 index 0000000..e69de29 diff --git a/shared/tool/env_to_emacs b/shared/tool/env_to_emacs new file mode 100755 index 0000000..8a65dba --- /dev/null +++ b/shared/tool/env_to_emacs @@ -0,0 +1,78 @@ +#!/usr/bin/env bash +# env_to_emacs - give the Emacs shell buffer this setup runs in the role's environment +# +# Emacs starts programs (compile, grep, and the like) with its own copy of the +# environment, which a shell running inside it cannot change. This tool sets +# REPO_HOME, PROJECT, ROLE and PATH in Emacs, and exec-path to match, for the +# one shell buffer whose shell this setup runs under, and for no other. +# +# The values are buffer-local. Killing the buffer discards them, and other +# buffers, including shells started later, keep Emacs's own environment. (An +# earlier version set them globally, so every shell started afterward began +# in the last role set up, even after that role's buffer was gone.) +# +# The buffer is found by process: Emacs knows the process id of the shell in +# each shell buffer, and that shell is an ancestor of this script, perhaps +# several generations up, since setup starts a new bash under the buffer's own. + +script_afp=$(realpath "${BASH_SOURCE[0]}") + +set -euo pipefail + +if [ -z "${REPO_HOME:-}" ]; then + echo "env_to_emacs: error: REPO_HOME is not set. Source a setup environment first." + exit 1 +fi + +if ! command -v emacsclient >/dev/null 2>&1; then + echo "env_to_emacs: error: emacsclient is not installed or not in PATH." + exit 1 +fi + +# quote a value as an Emacs Lisp string +elisp_string(){ + local s="$1" + s=${s//\\/\\\\} + s=${s//\"/\\\"} + printf '"%s"' "$s" +} + +form=$(cat < pid 1) (not buffer)) + (setq buffer + (seq-find (lambda (b) + (let ((p (get-buffer-process b))) + (and p (eql (process-id p) pid)))) + (buffer-list))) + (unless buffer + (setq pid (alist-get 'ppid (process-attributes pid))))) + (if (not buffer) + "no shell buffer found" + (with-current-buffer buffer + (setq-local process-environment (copy-sequence process-environment)) + (setenv "REPO_HOME" $(elisp_string "$REPO_HOME")) + (setenv "PROJECT" $(elisp_string "${PROJECT:-}")) + (setenv "ROLE" $(elisp_string "${ROLE:-}")) + (setenv "PATH" $(elisp_string "$PATH")) + (setq-local exec-path (append (parse-colon-path $(elisp_string "$PATH")) (list exec-directory))) + (buffer-name)))) +EOF +) + +if ! result=$(emacsclient --eval "$form" 2>&1); then + echo "env_to_emacs: cannot reach the Emacs server; Emacs environment left unchanged" + echo " $result" + exit 0 +fi +result=${result#\"} +result=${result%\"} + +if [[ "$result" == "no shell buffer found" ]]; then + echo "env_to_emacs: no Emacs shell buffer runs this shell; Emacs environment left unchanged" + exit 0 +fi + +echo "Emacs buffer $result has the environment of $PROJECT ${ROLE:-}" diff --git a/shared/tool/makefile/Harmony.mk b/shared/tool/makefile/Harmony.mk new file mode 100644 index 0000000..58aab0d --- /dev/null +++ b/shared/tool/makefile/Harmony.mk @@ -0,0 +1,192 @@ +# make/Harmony.mk - build *.lib.c and *.CLI.c +# written for the Harmony skeleton, always invoked from cwd $REPO_HOME/ +# files have two suffixes by convention, e.g.: X.lib.c or Y.CLI.c +# +# One make reads three layers, each after the one before, so each can change +# what the layers before it set: +# +# 1. Harmony's defaults, in this file +# 2. the project's settings, tool/build_component/project.mk +# 3. the namespace's settings, any *.mk beside its source +# +# A layer adds to a default with += and replaces one with :=. The flags the +# build itself depends on (dependency files, the global header, the source +# directory) are added after the layers, so replacing a default cannot remove +# them. +# +# The layers are read before the derived variables and the rules, because +# make expands those as it reads them. A rule a layer defines is read at that +# point too, so its targets and prerequisites cannot use the derived lists. + +.SUFFIXES: +.DELETE_ON_ERROR: +.DEFAULT_GOAL := usage + +#-------------------------------------------------------------------------------- +# 1. Harmony's defaults + +SHELL := /bin/bash + +ECHO := printf "%b\n" + +RT_MAKEFILE_DP := $(REPO_HOME)/shared/tool/makefile + +# The build component supplies these on the environment, for the namespace +# being built; ?= keeps its values, and a layer can still replace them. +C_SOURCE_DIR ?= authored +LIBRARY_DIR ?= scratchpad/made +MACHINE_DIR ?= scratchpad/made + +C := gcc +CFLAGS := -std=gnu11 -Wall -Wextra -Wpedantic -finput-charset=UTF-8 +LN_FLAGS := -L/lib64 -L/lib + +LIBRARY_NAME := $(PROJECT) + +BUILD_DIR := scratchpad/build +OBJECT_DIR = $(BUILD_DIR)/object + +KMOD_SOURCE_DIR ?= authored +KMOD_CCFLAGS ?= -I $(KMOD_SOURCE_DIR) +# Pass the global header to Kbuild exactly as done for user-space +KMOD_CCFLAGS += -include $(REPO_HOME)/shared/tool/makefile/RT_global.h +KMOD_OUTPUT_DIR ?= scratchpad/kmod + +#-------------------------------------------------------------------------------- +# 2. the project's settings + +include tool/build_component/project.mk + +#-------------------------------------------------------------------------------- +# 3. the namespace's settings + +-include $(wildcard $(C_SOURCE_DIR)/*.mk) + +#-------------------------------------------------------------------------------- +# derived variables + +LIBRARY_NAME := $(subst -,_,$(LIBRARY_NAME)) +LIBRARY_FILE := $(LIBRARY_DIR)/lib$(LIBRARY_NAME).a + +# source discovery (single dir) +c_source_lib := $(wildcard $(C_SOURCE_DIR)/*.lib.c) +c_source_exec := $(wildcard $(C_SOURCE_DIR)/*.CLI.c) + +# remove suffix to get base name +c_base_lib := $(sort $(patsubst %.lib.c,%, $(notdir $(c_source_lib)))) +c_base_exec := $(sort $(patsubst %.CLI.c,%, $(notdir $(c_source_exec)))) + +# two sets of object files, one for the lib, and one for the CLI programs +object_lib := $(patsubst %, $(OBJECT_DIR)/%.lib.o, $(c_base_lib)) +object_exec := $(patsubst %, $(OBJECT_DIR)/%.CLI.o, $(c_base_exec)) + +# executables are made from exec_ sources +exec_ := $(patsubst %, $(MACHINE_DIR)/%, $(c_base_exec)) + +# A library's product is its archive, its interface and its settings: in the +# single-file C module the .lib.c is its own header, and a .mk holds what a +# program built against the library needs. Both are staged beside the +# archive, so promotion hands a consumer all three. A namespace that makes no +# library stages neither. +interface_ := $(if $(c_source_lib),$(patsubst $(C_SOURCE_DIR)/%,$(LIBRARY_DIR)/%,$(c_source_lib) $(wildcard $(C_SOURCE_DIR)/*.mk))) + +# the flags the build depends on, after the layers +CFLAGS += -MMD -MP +CFLAGS += -include "$(REPO_HOME)/shared/tool/makefile/RT_global.h" +CFLAGS += -I $(C_SOURCE_DIR) +# the project library is linked only when the namespace makes one +LN_FLAGS += -L$(LIBRARY_DIR) $(if $(object_lib),-l$(LIBRARY_NAME)) + +#-------------------------------------------------------------------------------- +# pull in dependencies + +-include $(object_lib:.o=.d) $(object_exec:.o=.d) + + +#-------------------------------------------------------------------------------- +# targets + +.PHONY: usage +usage: + @printf "Usage: make [usage|version|information|all|library|lib|CLI|kmod|clean]\n" + +.PHONY: version +version: + @echo Harmony.mk version 9.0 + if [ ! -z "$(C)" ]; then $(C) -v; fi + /bin/make -v + @$(MAKE) --no-print-directory -f $(RT_MAKEFILE_DP)/target_kernel-module.mk version + +# information and clean are double-colon rules, so the project's settings or a +# namespace's .mk can add a recipe of its own; each recipe runs. +.PHONY: information +information:: + @printf "· → Unicode middle dot - visible: [%b]\n" "·" + @echo "REPO_HOME: " $(REPO_HOME) + @echo "NAMESPACE: " $(NAMESPACE) + @echo "C_SOURCE_DIR: " $(C_SOURCE_DIR) + @echo "BUILD_DIR: " $(BUILD_DIR) + @echo "LIBRARY_DIR: " $(LIBRARY_DIR) + @echo "MACHINE_DIR: " $(MACHINE_DIR) + @echo "makefiles read: " $(MAKEFILE_LIST) + @echo "CFLAGS: " $(CFLAGS) + @echo "LN_FLAGS: " $(LN_FLAGS) + @echo "c_source_lib: " $(c_source_lib) + @echo "c_source_exec: " $(c_source_exec) + @echo "c_base_lib: " $(c_base_lib) + @echo "c_base_exec: " $(c_base_exec) + @echo "object_lib: " $(object_lib) + @echo "object_exec: " $(object_exec) + @echo "exec_: " $(exec_) + @echo "interface_: " $(interface_) + @$(MAKE) --no-print-directory -f $(RT_MAKEFILE_DP)/target_kernel-module.mk information + +.PHONY: all +all: library CLI kmod + +.PHONY: library lib +library lib: $(LIBRARY_FILE) $(interface_) + +$(LIBRARY_FILE): $(object_lib) + @mkdir -p $(LIBRARY_DIR) + @if [ -s "$@" ] || [ -n "$(object_lib)" ]; then \ + echo "ar rcs $@ $^"; \ + ar rcs $@ $^; \ + else \ + rm -f "$@"; \ + fi + +# each staged interface file depends on its source file of the same name +$(interface_): $(LIBRARY_DIR)/%: $(C_SOURCE_DIR)/% + @mkdir -p $(LIBRARY_DIR) + cp $< $@ + +.PHONY: CLI +CLI: library $(exec_) + +# The kernel modules are built by a make of their own, which drives Kbuild. +# It defines targets of the same names as this file, so it is run, not +# included. +.PHONY: kmod +kmod: + @$(MAKE) --no-print-directory -f $(RT_MAKEFILE_DP)/target_kernel-module.mk kmod + +# generally better to use the project local clean scripts, but this will make it so that the make targets can be run again +.PHONY: clean +clean:: + rm -f $(LIBRARY_FILE) $(interface_) + for obj in $(object_lib) $(object_exec); do rm -f $$obj $${obj%.o}.d || true; done + for i in $(exec_); do [ -e $$i ] && rm $$i || true; done + rm -rf $(BUILD_DIR) + @$(MAKE) --no-print-directory -f $(RT_MAKEFILE_DP)/target_kernel-module.mk clean + + +# recipes + +$(OBJECT_DIR)/%.o: $(C_SOURCE_DIR)/%.c + @mkdir -p $(OBJECT_DIR) + $(C) $(CFLAGS) $(if $(findstring .lib,$@),-D$(if $(NAMESPACE),$(NAMESPACE)·,)$(basename $*)) -o $@ -c $< + +$(MACHINE_DIR)/%: $(OBJECT_DIR)/%.CLI.o + @mkdir -p $(MACHINE_DIR) + $(C) -o $@ $< $(LN_FLAGS) diff --git a/shared/tool/makefile/RT_global.h b/shared/tool/makefile/RT_global.h new file mode 100644 index 0000000..29f2e63 --- /dev/null +++ b/shared/tool/makefile/RT_global.h @@ -0,0 +1,11 @@ +#ifndef RT_global_H +#define RT_global_H + #include + #include + + typedef unsigned int uint; + + #define Local static + #define Free(pt) free(pt); (pt) = NULL; + +#endif diff --git a/shared/tool/makefile/target_kernel-module.mk b/shared/tool/makefile/target_kernel-module.mk new file mode 100644 index 0000000..b3684c4 --- /dev/null +++ b/shared/tool/makefile/target_kernel-module.mk @@ -0,0 +1,130 @@ +# make/target_kernel-module.mk — build *.kmod.c as kernel modules (single-pass, kmod-only) +# invoked from $REPO_HOME/ +# version 1.4 + +.SUFFIXES: +.DELETE_ON_ERROR: + +#-------------------------------------------------------------------------------- +# defaults for environment variables (override from outer make/env as needed) + +# Kernel build tree, which is part of the Linux system, use running kernel if unset +KMOD_BUILD_DIR ?= /lib/modules/$(shell uname -r)/build + +# Authored source directory (single dir) +KMOD_SOURCE_DIR ?= cc + +# Extra compiler flags passed to Kbuild (e.g., -I $(KMOD_SOURCE_DIR)) +KMOD_CCFLAGS ?= + +# Include *.lib.c into modules (1=yes, 0=no) +KMOD_INCLUDE_LIB ?= 1 + +# KMOD_OUTPUT_DIR is constrained, relative path, on the scratchpad, and ends in kmod +# Require: non-empty, relative, no '..', ends with 'kmod' dir +define assert_kmod_output_dir_ok + $(if $(strip $(1)),,$(error KMOD_OUTPUT_DIR is empty)) + $(if $(filter /%,$(1)),$(error KMOD_OUTPUT_DIR must be relative: '$(1)'),) + $(if $(filter %/../% ../% %/.. ..,$(1)),$(error KMOD_OUTPUT_DIR must not contain '..': '$(1)'),) + $(if $(filter %/kmod %/kmod/ kmod,$(1)),,$(error KMOD_OUTPUT_DIR must end with 'kmod': '$(1)')) +endef +KMOD_OUTPUT_DIR ?= scratchpad/kmod +$(eval $(call assert_kmod_output_dir_ok,$(KMOD_OUTPUT_DIR))) + +# The kernel make needs and absolute path to find the output directory +ABS_KMOD_OUTPUT_DIR := $(CURDIR)/$(KMOD_OUTPUT_DIR) + +#-------------------------------------------------------------------------------- +# derived variables (computed from the above) + +# Authored basenames (without suffix) +base_list := $(patsubst %.kmod.c,%,$(notdir $(wildcard $(KMOD_SOURCE_DIR)/*.kmod.c))) + +# Optional library sources (without suffix) to include inside modules +ifeq ($(KMOD_INCLUDE_LIB),1) +lib_base := $(patsubst %.lib.c,%,$(notdir $(wildcard $(KMOD_SOURCE_DIR)/*.lib.c))) +else +lib_base := +endif + +# Staged sources (kept namespaced to prevent .o collisions) +all_kmod_c := $(addsuffix .kmod.c,$(addprefix $(KMOD_OUTPUT_DIR)/,$(base_list))) +all_lib_c := $(addsuffix .lib.c,$(addprefix $(KMOD_OUTPUT_DIR)/,$(lib_base))) + + + +#-------------------------------------------------------------------------------- +# targets + +.PHONY: usage +usage: + @printf "Usage: make [kmod|clean|information|version]\n" + +.PHONY: version +version: + @echo target_kmod version 1.4 + +.PHONY: information +information: + @echo "KMOD_SOURCE_DIR: " $(KMOD_SOURCE_DIR) + @echo "KMOD_BUILD_DIR: " $(KMOD_BUILD_DIR) + @echo "KMOD_OUTPUT_DIR: " $(KMOD_OUTPUT_DIR) + @echo "base_list: " $(base_list) + @echo "lib_base: " $(lib_base) + @echo "all_kmod_c: " $(all_kmod_c) + @echo "all_lib_c: " $(all_lib_c) + @echo "KMOD_INCLUDE_LIB=" $(KMOD_INCLUDE_LIB) + + +ifeq ($(strip $(base_list)),) + $(warning No *.kmod.c found under $(KMOD_SOURCE_DIR); nothing to build) +endif + +# --- Parallel-safe preparation as real targets --- + +# ensure the staging dir exists (order-only prereq) +$(KMOD_OUTPUT_DIR): + @mkdir -p "$(KMOD_OUTPUT_DIR)" + +# generate the Kbuild control Makefile +$(KMOD_OUTPUT_DIR)/Makefile: | $(KMOD_OUTPUT_DIR) + @{ \ + printf "ccflags-y += %s\n" "$(KMOD_CCFLAGS)"; \ + printf "obj-m := %s\n" "$(foreach m,$(base_list),$(m).o)"; \ + for m in $(base_list); do \ + printf "%s-objs := %s.kmod.o" "$$m" "$$m"; \ + for lb in $(lib_base); do printf " %s.lib.o" "$$lb"; done; \ + printf "\n"; \ + done; \ + } > "$@" + +# stage kmod sources (one rule per file; parallelizable) +$(KMOD_OUTPUT_DIR)/%.kmod.c: $(KMOD_SOURCE_DIR)/%.kmod.c | $(KMOD_OUTPUT_DIR) + @echo "--- Stage: $@ ---" + @cp -f "$(abspath $<)" "$@" + +# stage library sources (optional; also parallelizable) +$(KMOD_OUTPUT_DIR)/%.lib.c: $(KMOD_SOURCE_DIR)/%.lib.c | $(KMOD_OUTPUT_DIR) + @echo "--- Stage: $@ ---" + @cp -f "$(abspath $<)" "$@" + + +.PHONY: kmod +kmod: $(KMOD_OUTPUT_DIR)/Makefile $(all_kmod_c) $(all_lib_c) +ifeq ($(strip $(base_list)),) + @echo "--- No kmod sources; nothing to do ---" +else + @echo "--- Invoking Kbuild for kmod: $(base_list) ---" + $(MAKE) -C "$(KMOD_BUILD_DIR)" M="$(ABS_KMOD_OUTPUT_DIR)" modules +endif + +# quality-of-life: allow 'make scratchpad/kmod/foo.ko' after batch build +$(KMOD_OUTPUT_DIR)/%.ko: kmod + @true + +.PHONY: clean +clean: + @echo "Cleaning: $(KMOD_BUILD_DIR)" + @$(MAKE) -C "$(KMOD_BUILD_DIR)" M="$(ABS_KMOD_OUTPUT_DIR)" clean >/dev/null 2>&1 || true + @echo "Cleaning: $(KMOD_OUTPUT_DIR)" + @rm -rf -- "$(KMOD_OUTPUT_DIR)" diff --git a/shared/tool/replace_from_tar b/shared/tool/replace_from_tar new file mode 100755 index 0000000..6da5c0f --- /dev/null +++ b/shared/tool/replace_from_tar @@ -0,0 +1,182 @@ +#!/usr/bin/env python3 +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- +""" +replace_from_tar + +Makes directories hold exactly what a tar file holds. For each directory at +the top of the tar file, such as SubU.copy/, the directory of the same name in +the extract dir is brought to match: files the tar file has are written when +they are new or differ, and files and directories it does not have are +deleted. The extract dir is the directory 'tar -x' would be run in: the one +that holds SubU.copy, not SubU.copy itself. It is the current directory unless +given. Extracting a tar file over a directory only adds and overwrites, so +a file that was removed from the tar file would otherwise stay behind. + +The tool deletes files. Checkpoint the project with git first, and run +preview to read what it would do. + +Usage: replace_from_tar [argument ...] + replace_from_tar preview [argument ...] + help | -h | --help print this message (also printed when given no arguments) + replace [] + bring each directory at the top of the tar file, + in the extract dir, to match the tar file + preview print the log of what would do, change nothing + +Example, run in developer/authored, which holds SubU.copy: + replace_from_tar preview replace SubU.copy.tar + replace_from_tar replace SubU.copy.tar +""" + +import sys ,os ,tarfile +from pathlib import Path, PurePosixPath + +TAG_WIDTH = 12 + + +class Log: + PREVIEW_TAG = {"made": "would make" ,"replaced": "would replace" ,"deleted": "would delete"} + + def __init__(self ,preview): + self.preview = preview + self.count = {} + self.error_count = 0 + + def line(self ,tag ,subject ,reason=None): + self.count[tag] = self.count.get(tag ,0) + 1 + if tag == "unchanged": return + shown = self.PREVIEW_TAG.get(tag ,tag) if self.preview else tag + print(f" {shown:<{TAG_WIDTH + 2}}{subject}" + (f" ({reason})" if reason else "")) + + def error(self ,subject ,reason): + self.error_count += 1 + print(f" {'error':<{TAG_WIDTH + 2}}{subject} ({reason})") + + def summary(self): + print("summary:") + for tag ,what in (("made" ,"files") ,("replaced" ,"files") ,("deleted" ,"files and directories") ,("unchanged" ,"files")): + n = self.count.get(tag ,0) + verb = f"that would be {tag}" if self.preview and tag != "unchanged" else tag + print(f" {n:>4} {what} {verb}") + if self.error_count: + print(f" {self.error_count:>4} errors") + if self.preview: + print("preview only: nothing was changed.") + return 1 if self.error_count else 0 + + +def member_problem(member): + path = PurePosixPath(member.name) + if path.is_absolute() or ".." in path.parts: + return "an absolute path or '..'" + if len(path.parts) < 1: + return "an empty name" + if not (member.isfile() or member.isdir() or member.issym()): + return "neither a file, a directory nor a symbolic link" + if member.issym() and (PurePosixPath(member.linkname).is_absolute() or ".." in PurePosixPath(member.linkname).parts): + return "a symbolic link leaving its directory" + return None + +def replace(tar_path ,extract_dir ,log ,preview): + extract_dir = Path(extract_dir) + if not extract_dir.is_dir(): + log.error(str(extract_dir) ,"not a directory"); return + with tarfile.open(tar_path) as tar: + member_list = tar.getmembers() + for m in member_list: + problem = member_problem(m) + if problem: + log.error(m.name ,f"refused: {problem}; nothing was changed"); return + top_set = sorted({PurePosixPath(m.name).parts[0] for m in member_list}) + for top in top_set: + if any(PurePosixPath(m.name) == PurePosixPath(top) and not m.isdir() for m in member_list): + log.error(top ,"refused: the top of the tar file must hold directories; nothing was changed"); return + target = extract_dir / top + if target.is_symlink(): + log.error(str(target) ,"refused: it is a symbolic link; nothing was changed"); return + + wanted = {str(PurePosixPath(m.name)): m for m in member_list} + + # ---- delete what the tar file does not have, deepest first + for top in top_set: + target = extract_dir / top + if not target.exists(): continue + for dirpath ,dirname_list ,filename_list in os.walk(target ,topdown=False ,followlinks=False): + for name in sorted(filename_list) + sorted(d for d in dirname_list if (Path(dirpath) / d).is_symlink()): + path = Path(dirpath) / name + key = str(PurePosixPath(path.relative_to(extract_dir))) + if key not in wanted or wanted[key].isdir(): + if not preview: path.unlink() + log.line("deleted" ,key) + for name in sorted(d for d in dirname_list if not (Path(dirpath) / d).is_symlink()): + path = Path(dirpath) / name + key = str(PurePosixPath(path.relative_to(extract_dir))) + if key not in wanted: + if not preview: + if any(path.iterdir()): + log.error(key ,"not empty after its files were deleted"); continue + path.rmdir() + log.line("deleted" ,key + "/") + + # ---- write what is new or differs + for m in sorted(member_list ,key=lambda m: m.name): + key = str(PurePosixPath(m.name)) + path = extract_dir / key + if m.isdir(): + if not path.is_dir(): + if not preview: path.mkdir(parents=True ,exist_ok=True) + log.line("made" ,key + "/") + continue + if m.issym(): + if path.is_symlink() and os.readlink(path) == m.linkname: + log.line("unchanged" ,key); continue + if not preview: + if path.is_symlink() or path.exists(): path.unlink() + path.parent.mkdir(parents=True ,exist_ok=True) + os.symlink(m.linkname ,path) + log.line("replaced" if path.is_symlink() else "made" ,key); continue + data = tar.extractfile(m).read() + mode = m.mode & 0o777 + if path.is_file() and not path.is_symlink(): + if path.read_bytes() == data and (path.stat().st_mode & 0o777) == mode: + log.line("unchanged" ,key); continue + tag = "replaced" + else: + tag = "made" + if not preview: + path.parent.mkdir(parents=True ,exist_ok=True) + if path.is_symlink(): path.unlink() + path.write_bytes(data) + os.chmod(path ,mode) + log.line(tag ,key) + + +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." ,file=sys.stderr) + return 1 + command ,rest = argv[0] ,argv[1:] + if command == "replace" and len(rest) in (1 ,2): + if len(rest) == 1: rest = [rest[0] ,"."] + if not Path(rest[0]).is_file(): + print(f"Error: no tar file at {rest[0]}." ,file=sys.stderr) + return 1 + log = Log(preview) + print(f"replace_from_tar {'preview ' if preview else ''}replace {rest[0]} in {os.path.abspath(rest[1])}") + replace(rest[0] ,rest[1] ,log ,preview) + return log.summary() + print(f"Error: unknown command or wrong arguments: '{command}'." ,file=sys.stderr) + print_help() + return 1 + + +if __name__ == "__main__": + sys.exit(CLI()) diff --git a/shared/tool/scratchpad b/shared/tool/scratchpad new file mode 100755 index 0000000..f14f140 --- /dev/null +++ b/shared/tool/scratchpad @@ -0,0 +1,225 @@ +#!/usr/bin/env -S python3 -B +# -*- mode: python; coding: utf-8; python-indent-offset: 2; indent-tabs-mode: nil -*- + +import os, sys, shutil, stat, pwd, grp, subprocess + +HELP = """usage: scratchpad {ls|clear|help|make|write|size|find|lock|unlock} [ARGS] + ls List scratchpad in an indented tree with perms and owner (quiet if missing). + clear Remove all contents of scratchpad/ except top-level .gitignore. + clear NAME Remove scratchpad/NAME only. + make [NAME] Ensure scratchpad/ exists with .gitignore; with NAME, mkdir scratchpad/NAME. + write SRC [DST] Copy file/dir SRC into scratchpad (to DST if given; parents created). + size Print 'empty' if only .gitignore; else total bytes and item count. + find [OPTS...] Run system 'find' rooted at scratchpad/ with OPTS (omit literal 'scratchpad'). + lock PATH... Attempt 'chattr +i' on given paths under scratchpad/ (no state kept). + unlock PATH... Attempt 'chattr -i' on given paths under scratchpad/. + +Examples: + scratchpad make + scratchpad write ~/Downloads/test.tar.gz + scratchpad find -type f -mtime +30 -print # files older than 30 days + scratchpad lock some/dir important.txt + scratchpad unlock some/dir important.txt +""" + +CWD = os.getcwd() +SP = os.path.join(CWD, "scratchpad") +GITIGNORE = os.path.join(SP, ".gitignore") + +def have_sp() -> bool: + return os.path.isdir(SP) + +def ensure_sp(): + os.makedirs(SP, exist_ok=True) + ensure_gitignore() + +def ensure_gitignore(): + os.makedirs(SP, exist_ok=True) + if not os.path.isfile(GITIGNORE): + with open(GITIGNORE, "w", encoding="utf-8") as f: + f.write("*\n!.gitignore\n") + +def filemode(mode: int) -> str: + try: + return stat.filemode(mode) + except Exception: + return oct(mode & 0o777) + +def owner_group(st) -> str: + try: + return f"{pwd.getpwuid(st.st_uid).pw_name}:{grp.getgrgid(st.st_gid).gr_name}" + except Exception: + return f"{st.st_uid}:{st.st_gid}" + +def rel_depth(base: str, root: str) -> int: + rel = os.path.relpath(base, root) + return 0 if rel == "." else rel.count(os.sep) + 1 + +def ls_tree(root: str) -> None: + if not have_sp(): + return + print("scratchpad/") + + def walk(path: str, indent: str, is_root: bool) -> None: + try: + it = list(os.scandir(path)) + except FileNotFoundError: + return + + dirs = [e for e in it if e.is_dir(follow_symlinks=False)] + files = [e for e in it if not e.is_dir(follow_symlinks=False)] + dirs.sort(key=lambda e: e.name) + files.sort(key=lambda e: e.name) + + if is_root: + # 1) root-level hidden files first + for f in (e for e in files if e.name.startswith(".")): + st = os.lstat(f.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{f.name}") + # 2) then directories (and recurse so children sit under the parent) + for d in dirs: + st = os.lstat(d.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{d.name}/") + walk(d.path, indent + ' ', False) + # 3) then non-hidden files + for f in (e for e in files if not e.name.startswith(".")): + st = os.lstat(f.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{f.name}") + else: + # subdirs: keep previous order (dirs first, then files; dotfiles naturally sort first) + for d in dirs: + st = os.lstat(d.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{d.name}/") + walk(d.path, indent + ' ', False) + for f in files: + st = os.lstat(f.path) + print(f"{filemode(st.st_mode)} {owner_group(st)} {indent}{f.name}") + + walk(root, " ", True) + + +def clear_all() -> None: + if not have_sp(): + return + for name in os.listdir(SP): + p = os.path.join(SP, name) + if name == ".gitignore" and os.path.isfile(p): + continue # preserve only top-level .gitignore + if os.path.isdir(p) and not os.path.islink(p): + shutil.rmtree(p, ignore_errors=True) + else: + try: os.unlink(p) + except FileNotFoundError: pass + +def clear_subdir(sub: str) -> None: + if not have_sp(): + return + target = os.path.normpath(os.path.join(SP, sub)) + try: + if os.path.commonpath([SP]) != os.path.commonpath([SP, target]): + return + except Exception: + return + if os.path.isdir(target) and not os.path.islink(target): + shutil.rmtree(target, ignore_errors=True) + +def cmd_make(args): + ensure_sp() + if args: + os.makedirs(os.path.join(SP, args[0]), exist_ok=True) + +def cmd_write(args): + if len(args) < 1: + print(HELP); return + if not have_sp(): + ensure_sp() + src = args[0] + dst = args[1] if len(args) >= 2 else (os.path.basename(src.rstrip(os.sep)) or "untitled") + dst_path = os.path.normpath(os.path.join(SP, dst)) + try: + if os.path.commonpath([SP]) != os.path.commonpath([SP, dst_path]): + print("refusing to write outside scratchpad", file=sys.stderr); return + except Exception: + print("invalid destination", file=sys.stderr); return + os.makedirs(os.path.dirname(dst_path), exist_ok=True) + if os.path.isdir(src): + if os.path.exists(dst_path): + shutil.rmtree(dst_path, ignore_errors=True) + shutil.copytree(src, dst_path, dirs_exist_ok=False) + else: + shutil.copy2(src, dst_path) + +def cmd_size(): + if not have_sp(): + return + names = os.listdir(SP) + if [n for n in names if n != ".gitignore"] == []: + print("empty"); return + total = 0; count = 0 + for base, dirs, files in os.walk(SP): + for fn in files: + if fn == ".gitignore": + continue + p = os.path.join(base, fn) + try: + total += os.path.getsize(p); count += 1 + except OSError: + pass + print(f"bytes={total} items={count}") + +def cmd_find(args): + if not have_sp(): + return + try: + subprocess.run(["find", SP] + args, check=False) + except FileNotFoundError: + print("find not available", file=sys.stderr) + +def cmd_chattr(flag: str, paths): + if not have_sp() or not paths: + return + try: + subprocess.run(["chattr", "-V"], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, check=False) + except FileNotFoundError: + print("chattr not available; lock/unlock skipped", file=sys.stderr); return + for rel in paths: + target = os.path.normpath(os.path.join(SP, rel)) + try: + if os.path.commonpath([SP]) != os.path.commonpath([SP, target]): + continue + except Exception: + continue + try: + subprocess.run(["chattr", flag, target], check=False) + except Exception: + pass + +def CLI(): + if len(sys.argv) < 2: + print(HELP); return + cmd, *args = sys.argv[1:] + if cmd == "ls": + if have_sp(): ls_tree(SP) + else: return + elif cmd == "clear": + if len(args) >= 1: clear_subdir(args[0]) + else: clear_all() + elif cmd == "help": + print(HELP) + elif cmd == "make": + cmd_make(args) + elif cmd == "write": + cmd_write(args) + elif cmd == "size": + cmd_size() + elif cmd == "find": + cmd_find(args) + elif cmd == "lock": + cmd_chattr("+i", args) + elif cmd == "unlock": + cmd_chattr("-i", args) + else: + print(HELP) + +if __name__ == "__main__": + CLI() diff --git a/shared/tool/setup b/shared/tool/setup new file mode 100644 index 0000000..7dc24d3 --- /dev/null +++ b/shared/tool/setup @@ -0,0 +1,100 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") +if [[ "${BASH_SOURCE[0]}" == "$0" ]]; then + echo "$script_afp:: This script must be sourced, not executed." + exit 1 +fi + +# without this bash takes non-matching globs literally +shopt -s nullglob + +# does not presume sharing or world permissions +umask 0077 + +# -------------------------------------------------------------------------------- +# project definition + +# actual absolute directory path for this script file + script_adp(){ + dirname "$script_afp" + } + +# This script is located at $REPO_HOME/shared/tool/setup. +# Ascend two directories to discover the absolute $REPO_HOME path. + REPO_HOME=$(dirname "$(dirname "$(script_adp)")") + echo REPO_HOME "$REPO_HOME" + + PROJECT=$(basename "$REPO_HOME") + echo PROJECT "$PROJECT" + + # set the prompt decoration to the name of the project + PROMPT_DECOR=$PROJECT + + export REPO_HOME PROJECT PROMPT_DECOR + +# -------------------------------------------------------------------------------- +# the following functions are provided for other scripts to use. +# at the top of files that make use of these functions put the following line: +# script_afp=$(realpath "${BASH_SOURCE[0]}") +# + + ## script's filename + script_fn(){ + basename "$script_afp" + } + + ## script's file path relative to $REPO_HOME + script_fp(){ + realpath --relative-to="${REPO_HOME}" "$script_afp" + } + + ## script's dirpath relative to $REPO_HOME + script_dp(){ + dirname "$(script_fp)" + } + + export -f script_adp script_fn script_dp script_fp + +# -------------------------------------------------------------------------------- +# PATH & Plugin Sourcing +# Each addition goes to the front, so the last added is searched first. +# Resulting search order, most specific first: +# shared/authored, shared/made, shared/tool, project dependencies, the rest. +# The top-level setup then puts the role's tool directory in front of these. + + # Project dependencies: source each .init file. Each prepends its own entries. + for init_file in "$REPO_HOME/shared/project-dependency/"*.init; do + if [[ -f "$init_file" ]]; then + source "$init_file" + fi + done + + PATH="$REPO_HOME/shared/tool:$PATH" + PATH="$REPO_HOME/shared/made:$PATH" + PATH="$REPO_HOME/shared/authored:$PATH" + + # Remove duplicates, keeping the first occurrence + # Done with bash built-ins only. A pipeline through awk and sed left PATH + # empty whenever either program failed to run. + clean_path(){ + local entry result="" + local -A seen=() + local -a part + IFS=: read -r -a part <<< "$PATH" + for entry in "${part[@]}"; do + [[ -z "$entry" || -n "${seen[$entry]:-}" ]] && continue + seen[$entry]=1 + result="${result:+$result:}$entry" + done + PATH="$result" + } + clean_path + + export PATH + +# -------------------------------------------------------------------------------- +# closing +# + if [[ -z "$ENV" ]]; then + export ENV=$(script_fp) + fi diff --git a/shared/tool/version b/shared/tool/version new file mode 100755 index 0000000..051366f --- /dev/null +++ b/shared/tool/version @@ -0,0 +1,4 @@ +echo "Harmony v3.5 2026-10-14 04:51:11 Z" + + +echo "Jizo v0.1 2026-11-26" diff --git a/tester/.gitkeep b/tester/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tester/authored/.gitkeep b/tester/authored/.gitkeep new file mode 100644 index 0000000..e69de29 diff --git a/tester/tool/setup b/tester/tool/setup new file mode 100644 index 0000000..0b993ad --- /dev/null +++ b/tester/tool/setup @@ -0,0 +1,3 @@ +#!/usr/bin/env bash +script_afp=$(realpath "${BASH_SOURCE[0]}") + -- 2.20.1