|
|
|
|
Quelle README.md Sprache: unbekannt
|
|
Spracherkennung für: .md vermutete Sprache: Abap {ABAP[144] SQL[132] VDM[121]} [Methode: maximale Elemente, drei Dimensionen]
# Miscellaneous scripts for working on mathlib
This directory contains miscellaneous scripts that are useful for working on or with mathlib.
When adding a new script, please make sure to document it here, so other readers have a chance
to learn about it as well!
## Where does a new script belong?
A script belongs in [ **`leanprover-community/mathlib-ci`**](https://github.com/leanprover-community/mathlib-ci)
if it is a CI automation script that interacts with GitHub (e.g. managing labels, posting
comments, triggering bots), runs from a trusted external checkout in CI, or requires access
to secrets. CI automation scripts have been moved there; workflows that use them execute
them from external checkouts (typically under `ci-tools/`).
A script belongs in **this directory** (`scripts/`) if it is a developer or maintainer tool
to be run locally, a code maintenance or analysis utility, a style linting tool, or a data
file used by the library 's own linters.
## Current scripts and their purpose
**Repository analysis and reporting**
- `bench` is mathlib's benchmark suite. View its [README.md](bench/README.md) for more deta ils.
- `user_activity_report.py`
Generates a comprehensive report of all users with repository access and their last commit activity.
Shows username, age of last commit, and access level, sorted by commit recency (most recent first).
**Features:**
- Fetches repository collaborators and organization members via GitHub API
- Intelligent caching: user lists (24h TTL) and commit data (6h TTL) for performance
- Access level filtering: `--admin` (admin users only), `--write` (write+ access)
- Single user analysis: `--user USERNAME` for debugging specific users
- Result limiting: `--limit N` for testing with smaller datasets
- Inactive user cleanup: `--remove N` generates (but doesn't execute) gh commands
to remove write access from non-admin users inactive for more than N days
- Fallback to contributors API if collaborators access is restricted (`--contributors-only`)
**Caching:** Results cached in `scripts/users_cache.json` and `scripts/commits_cache.json`
(automatically added to .gitignore). Cache saved after each commit lookup to prevent data loss.
**Requirements:** `gh` (GitHub CLI) installed and authenticated (`gh auth login`).
- `dup_decls_report.lean`
Runs the `Mathlib.Tactic.DuplicateDecls` linter
(`lintDuplicateDeclarations`) for theorems, instances, and defs, logging any duplicate
declarations found. Run in CI by the `duplicate_decls_report.yml` workflow
(see [docs/workflows.md](../docs/workflows.md)). Run locally with
`lake env lean scripts/dup_decls_report.lean`.
**Tools for manual maintenance**
- `fix_unused.py`
Bulk processing of unused variable warnings, replacing them with `_`.
- `fix_deprecations.py`
Automatically fixes deprecation warnings by replacing deprecated identifiers with their suggested
replacements. Runs `lake build --no-build` to collect deprecation warnings, then applies
minimal changes by verifying the deprecated term appears at the expected column position before
replacement. Handles both fully-qualified names (e.g., `Fin.lt_iff_val_lt_val`) and unqualified
names used within namespaces (e.g., `lt_iff_val_lt_val`). Only processes files that exist in the
current repository. Safe to run multiple times; processes all warnings in a single pass.
Usage: `python3 scripts/fix_deprecations.py`
- `add_deprecations.sh` is a text-based script that automatically adds deprecation statements.
It assumes that the only difference between master and the current status of the PR consists
of renames. More precisely, any change on a line that contains a declaration name
and is not a rename, will likely confuse the script.
- `create_deprecated_modules.lean` defines the `#create_deprecated_modules` command that
automatically generates the `deprecated_module` entries, gathering information from `git`.
The expectation is that this will be expanded to a fully automated process that happens in CI.
- `runSkimmer.sh` applies all interactive text suggestions generated within Mathlib (the
`lean_lib`). `runSkimmer.sh --on tgt1 tgt2 ...` applies only to those lake targets (libraries,
modules) within mathlib. If oleans for the refactored targets are already present, it will use them;
else it will build any necessary oleans. This script may be copy-pasted to other repos with altered
config variables, then set up with `runSkimmer.sh --init`. This sets up a minimal side package
`SideSkimmer` which avoids the need for including `skimmer` as a dependency.
See `runSkimmer.sh -h` and the bash module doc for more details.
NOTE: the functionality exposed by this script is very experimental, and subject to change.
Please report issues to Thomas Murrills on Zulip.
- `migrate_to_fork.py`
Helps contributors migrate from having direct write access to the main repository
to using a fork-based workflow. This comprehensive script automates the entire migration process:
* Validates the current branch (prevents migration of system branches like master, nightly-testing)
* Checks GitHub CLI installation/authentication with OS-specific installation instructions
* Creates or syncs a fork of mathlib4 automatically
* Sets up git remotes correctly (`upstream` for leanprover-community/mathlib4, `origin` for user's fork)
* Detects already-completed migration steps and skips them for efficiency
* Migrates the current branch to the fork with proper upstream tracking
* Intelligently handles existing PRs (migrates main repo PRs to fork-based PRs, detects existing fork PRs)
* Uses fast delete/re-add approach for remote operations to avoid slow branch tracking updates
* Provides comprehensive status reporting and next steps guidance
Run with `python3 scripts/migrate_to_fork.py` (interactive) or `python3 scripts/migrate_to_fork.py -y` (auto-accept).
Requires GitHub CLI (`gh`) installed and authenticated. Safe to run multiple times.
- `githelper.py`
The subcommand `githelper.py fix` helps contributors fix their git repository setup
by step-by-step converting it from its current state to a well-defined target state.
The target state mostly matches the state after of a freshly cloned fork (`gh repo clone <fork>`)
and looks like this:
- The remote `upstream` points to `leanprover-community/mathlib4`
- The remote `origin` points to the contributor's own fork
- The `gh` default repo points to `leanprover-community/mathlib4`
- `master`s remote is `upstream` but its pushRemote is `origin`
Other subcommands to automate git-related actions may be added in the future.
**Analyzing Mathlib's import structure**
- `unused_in_pole.sh` (followed by an optional `<target>`, defaulting to `Mathlib`)
calls `lake exe pole --loc --to <target>` to compute the longest
pole to a given target module, and then feeds this into
`lake exe unused` to analyze transitively unused imports.
Generates `unused.md` containing a markdown table showing the unused imports,
and suggests `lake exe graph` commands to visualize the largest "rectangles" of unused imports.
- `topological_sort.py`
Prints Mathlib modules in topological (import-DAG) order. By default leaves come last
(roots first); use `--reverse` for leaves first. If filenames or module names are
provided on stdin, outputs only those modules in topological order.
Usage: `python3 scripts/topological_sort.py [--reverse]`
**CI debugging tools**
- `find-ci-errors.sh`
Searches through recent failed CI workflow runs to find open PRs whose current CI
contains a specific error string. Useful for diagnosing widespread CI issues affecting
multiple PRs (e.g., infrastructure problems, toolchain bugs).
**Usage:**
```bash
# Find all PRs currently failing with a specific error
./scripts/find-ci-errors.sh "Error parsing args: cannot parse arguments"
# Find PRs and automatically add please-merge-master label to trigger rebuilds
./scripts/find-ci-errors.sh --please-merge-master "cannot parse arguments"
```
**Options:**
- `--please-merge-master`: Adds the `please-merge-master` label to all matching PRs,
except those with the `merge-conflict` label.
**Notes:**
- Downloads CI logs to `/tmp/gh-run-*.log` (cached to avoid re-downloading)
- Checks up to 200 recent failed runs
- Only reports PRs whose current CI status is failing (ignores PRs fixed by retries)
**Requirements:** `gh` (GitHub CLI) installed and authenticated, `jq` for JSON parsing.
**Backward-compatibility `set_option` migration tools**
These scripts help with testing Lean PRs that change backward-compatibility option
behaviour. They share a common DAG traversal library that parallelises work in import-graph order.
***Using these scripts in a downstream project.*** Each script depends on sibling
files in the same directory. Minimally:
1. Copy the script you want plus `dag_traversal.py` and `set_option_utils.py` into
a `scripts/` directory in your project. `fix_nonlocal_set_option.py` additionally
requires `add_module_set_option.py` and `rm_module_set_option.py`.
2. From the project root, run e.g. `python3 scripts/rm_set_option.py --dry-run --option <name>`.
3. If you see "warning: no .lean files found", pass `--directories <your-source-dir>`
(e.g. `--directories FLT`).
4. If you have a `lakefile.toml` and have configured the option in `leanOptions`,
remove the entry manually — these scripts only edit `lakefile.lean`.
Module-name derivation assumes a Mathlib-style layout where `Foo/Bar.lean` corresponds
to module `Foo.Bar` (no `srcDir` indirection).
- `dag_traversal.py`
Reusable parallel DAG traversal for Lean import graphs. Parses the import DAG from `.lean`
source files and parallelises an action over a forward or backward traversal. Each module is
submitted to the thread pool the moment its last in-DAG dependency finishes.
**Library usage:**
```python
from dag_traversal import DAG, traverse_dag
dag = DAG.from_directories(Path("."))
results = traverse_dag(dag, my_action, direction="forward", stop_on_failure=True)
```
**CLI usage:**
```bash
scripts/dag_traversal.py --forward 'lake build {}' # {} = file path
scripts/dag_traversal.py --backward --module 'echo {}' # {} = module name
scripts/dag_traversal.py --forward -j4 'my_script {}'
```
- `set_option_utils.py`
Shared configuration for `add_set_option.py` and `rm_set_option.py`. Contains the list of
managed options and helpers for generating `set_option` lines and regex patterns.
- `add_set_option.py`
Adds `set_option ... false in` before declarations that fail to build. Traverses the DAG
**forward** (roots first) so each module is only built after all its imports are clean. For
each error, finds the enclosing declaration and tries candidate option combinations
(most-recently-successful first, then each single option, then all together).
Usage: `python3 scripts/add_set_option.py [--option NAME] [--max-workers N] [--timeout N] [--files FILE ...]`
- `rm_set_option.py`
Removes unnecessary `set_option ... in` lines. Only targets lines without a trailing
comment; lines like `set_option ... false in -- reason` are left untouched. Traverses the DAG
**backward** (leaves first) so removing an option from an upstream file doesn't invalidate
cached builds of downstream files. Tries removing all occurrences at once; if that fails,
falls back to one-at-a-time removal. Only the edited files are rebuilt, so options that
change what a declaration exports (`EXPORT_AFFECTING_OPTIONS` in `set_option_utils.py`,
e.g. `backward.privateInPublic`) are skipped unless passed via `--option`. It also removes
project-wide `backward.*` entries for these options from `lakefile.lean`, but leaves other
entries (such as linter settings) alone.
Usage: `python3 scripts/rm_set_option.py [--option NAME] [--dry-run] [--max-workers N] [--files FILE ...] [--resume]`
- `add_module_set_option.py`, `rm_module_set_option.py`
File-level variants of `add_set_option.py` / `rm_set_option.py`: they insert or remove a
`set_option ...` at the top of the file rather than scoped to individual declarations.
Both accept `--directories <root>` for downstream projects whose source files aren't
directly under the project root.
- `fix_nonlocal_set_option.py`
Helper that bisects the import DAG to find the upstream file whose missing
`set_option ...` is causing a downstream failure — useful when the direct fix is in a
different module than the one reporting the error. Accepts `--directories <root>` for
downstream projects.
- `fix_unused_simp_args.py`
Parses `lake build` warnings of the form `This simp argument is unused: X` and removes `X`
from the corresponding `simp`/`simp only` call. For `← X` arguments it rewrites to `- X`
instead, because the `←` form has side effects on the simp set even when the rewrite itself
is unused.
Usage: `lake build 2>&1 | scripts/fix_unused_simp_args.py`
- `fix_long_lines.py`
Breaks a too-long line at the last comma before column 100 and indents the continuation.
Takes `path:line` pairs as arguments; intended as a follow-up to scripts that rewrite simp
lists (which occasionally leave lines over the 100-char limit).
Usage: `scripts/fix_long_lines.py path:line ...`
**CI workflow**
- `lake-build-with-retry.sh`
Runs `lake build` on one or more targets until `lake build --no-build` succeeds. Used in the main build workflows.
- `lake-build-wrapper.py`
A wrapper script for `lake build` which collapses normal build into log groups and saves a build summary JSON file. See file for usage.
- `mk_all.lean`
run via `lake exe mk_all`, regenerates the import-only files
`Mathlib.lean`, `Mathlib/Tactic.lean`, `Archive.lean` and `Counterexamples.lean`
- `lint-style.lean`: style linters written in Lean. Run via `lake exe lint-style`.
- `check-title-labels.lean` verifies that a (non-WIP, non-draft) PR has a well-formed title.
In the future, it may also check that a feature PR has a topic label.
`check_title_labels.lean` is a temporary copy of `check-title-labels.lean` and will be deleted soon.
- `lint-bib.sh`
normalize the BibTeX file `docs/references.bib` using `bibtool`.
- `yaml_check.py`, `check-yaml.lean`
Sanity checks for `undergrad.yaml`, `overview.yaml`, `100.yaml` and `1000.yaml`.
- `export_crossrefs.lean`
Exports a JSON dictionary of every declaration with a `CrossRef.Tag` attribute (e.g.: `@[stacks]`)
with declaration name, source file, line number, cross-reference ids and resolved url(s).
It runs as a Lean command over the fully-imported `Mathlib` environment (like `#stacks_tags`),
so it is invoked with `lake env lean scripts/export_crossrefs.lean` rather than `lake exe`.
The output path defaults to `crossrefs.json` (override with `CROSSREFS_OUT`); the embedded
mathlib commit SHA is read from `CROSSREFS_COMMIT`. The
[`export_crossrefs.yml`](../.github/workflows/export_crossrefs.yml) workflow runs this after every
successful master build and publishes the result to the
[`crossref-exports`](https://github.com/leanprover-community/crossref-exports) repository
(committing only when the entries actually change).
- `autolabel.lean` is the Lean script in charge of automatically adding a `t-`label on eligible PRs.
Autolabelling is inferred by which directories the current PR modifies.
- `auto_commit.sh` runs a command and creates a commit with the result. The commit message format
`x scripts/auto_commit.sh <command>` enables a rebase workflow: during interactive rebase,
you can convert `pick abc # x scripts/auto_commit.sh cmd` to `x scripts/auto_commit.sh cmd`
(by deleting the "pick abc # " prefix), and git will re-run the command via exec.
Example: `scripts/auto_commit.sh lake exe mk_all`
- `parse_shake_output.py` parses the captured output of `lake shake` and reports the number of
files changed and imports added/removed. Used by the `shake` workflow to populate the PR body
and Zulip notification. Counts are printed to stdout and, if a second argument is given
(typically `$GITHUB_OUTPUT`), appended there as `changed_files=`, `added=`, `removed=`.
Usage: `scripts/parse_shake_output.py <shake-output.txt> [$GITHUB_OUTPUT]`
**Nightly testing**
- `nightly-testing-checklist.lean` reports and fixes the state of `nightly-testing` branches
at Batteries and Mathlib. Run via `lake exe nightly-testing-checklist`.
**What it checks:**
- Whether each repo's toolchain matches the latest lean4 nightly
- Whether upstream dependencies (e.g. Batteries in Mathlib) are up to date
- CI status, with inline display of failing jobs and Lean error messages
**What it can fix:**
- Bumps stale `lean-toolchain` files
- Runs `lake update` for stale upstream dependencies
- Removes duplicate declarations ("has already been declared" errors) using Lean's parser
to identify command boundaries
**Flags:**
- `--watch`: wait for in-progress CI runs to complete (wakes on first job failure)
- `--fix`: commit and push fixes (default is dry-run: generate `.patch` files)
- `--no-clone`: report only, don't clone repos to `/tmp`
- `--no-build`: clone and update deps, but don't build or fix errors
- `find_command_range.lean` is a helper used by `nightly-testing-checklist.lean`.
Given a file and position, it uses Lean's parser to find the byte range of the enclosing
top-level command (including preceding attributes and doc comments). It is copied to
cloned repos at runtime and executed via `lake env lean --run`.
**Managing downstream repos**
- `downstream_repos.yml` contains basic information about significant downstream repositories.
- `downstream-tags.py` is a script to check whether a given tag exists on the downstream
repositories listed in `downstream_repos.yml`.
- `extract-unique-nonascii.lean` is used for updating the list of non-ascii characters in
`Mathlib/Tactic/Linter/TextBased/UnicodeLinter.lean`
which have an abbreviation provided by the Lean VSCode extension.
- `downstream_dashboard.py` inspects the CI infrastructure of each repository in
`downstream_repos.yml` and makes actionable suggestions for improvement or automation.
**Version tag verification**
- `verify_version_tags.py` verifies that Mathlib version tags are correctly published across git, GitHub, elan toolchains, and build cache.
**Data files with linter exceptions**
- `nolints.json` contains exceptions for all `env_linter`s in mathlib.
For permanent and deliberate exceptions, add a `@[nolint lintername]` in the .lean file instead.
- `nolints_prime_decls.txt` contains temporary exceptions for the `docPrime` linter
Both of these files should tend to zero over time;
please do not add new entries to these files. PRs removing (the need for) entries are welcome.
**Linter configuration files**
- `forbiddenDirs.json` is read by the `directoryDependency` linter
(in `Mathlib/Tactic/Linter/DirectoryDependency.lean`): it records which directories are not
allowed to import from each other, to keep mathlib's import graph manageable.
**Grind tactic analysis**
- `grind_unused_lemmas.sh` `[N] [logfile]`
Builds Mathlib with `set_option grind.unusedLemmaThreshold N` (default 10) and reports
E-matching lemmas that are activated N+ times but do not appear in the final proof term.
Outputs `grind-unused-lemmas.md` with a table of lemmas ranked by how many files they
appear as unused in. If a logfile is given, skips the build and processes that log instead.
Requires a Lean toolchain with `grind.unusedLemmaThreshold` support
(leanprover/lean4#12805 or later).
**API surrounding CI**
- `check_title_labels.lean` is used to check whether a PR title follows our [commit style conventions](https://leanprover-community.github.io/contribute/commit.html).
**Docker images**
- `docker_build.sh` builds the `lean4`, `gitpod4`, and `gitpod4-blueprint` Docker images.
These are used by some CI workflows, as well as places such as Gitpod.
- `docker_push.sh` first runs `docker_build.sh`, and then pushes the images to Docker Hub,
appropriately tagged with the date on which the images were built.
This should be re-run after breaking changes to `elan`, so that CI and Gitpod have access to
updated versions of `elan`.
[Dauer der Verarbeitung: 0.5 Sekunden, vorverarbeitet 2026-11-17]
|
2026-11-24
|
|
|
|
|