Repository navigation
Conversation
- Add `trail.cli` package: argument parsing and entry point in `__init__`, the prompt_toolkit `Console` application, a `Command` base with the concrete `commands`, `Column` layout, `Node` listing rows, `Feed` event streaming, `render` helpers, and `theme` - Add `trail.__main__` so `python -m trail` runs the console - Add tests for input handling and listing
- Split source lines into separate strings in the notebook cell to improve readability
- Introduce `Select` class inheriting from `Node` to pick records from a collection - Implement methods for slicing, comparison, and timestamp comparison - Add functionality to handle paths, IDs, and text lookups - Implement union and subset operations for record selection - Add helper methods for comparison, equality checks, and value coercion
- Replace `EntryLookup` with `Entries` class to provide a unified interface for assets and directories - Implement `_synced` property to ensure changes in `assets` and `dirs` are reflected in `entries` - Simplify entry tracking and untracking logic - Update `entry` method to streamline entry lookup by ID or path - Remove redundant id shortening and prefix handling in CLI commands - Add tests for entry movement and path handling - Refactor repr and str methods for cleaner output
…`Select` class inheriting from `Node` to pick records from a collection - Implement methods for slicing, comparison, and timestamp comparison - Add functionality to handle paths, IDs, and text lookups - Implement union and subset operations for record selection - Add helper methods for comparison, equality checks, and value coercion - Refactor `Entries` class to use `Select` for event selection - Update tests to use `Select` for event selection and slicing
- Refactor `select.py` to streamline string splitting and improve readability - Update `commands.py` to simplify command definitions and improve usability - Enhance `test_listing.py` to cover new behaviors and edge cases - Refactor `command.py` to improve command handling and query processing - Update `console.py` to simplify command execution and improve error handling - Update `CLI` to enhance query handling and improve user experience
…eration Replace .values() calls with direct iteration now that collections are iterable. Rename Collection protocol to Selectable to avoid naming conflict with new Collection base class. Add extend() method to Events for batch recording, replacing update().
… storage Introduce generic Collection[K, V] base class that stores records by id while maintaining insertion order. Provides dict-like access patterns (get, __getitem__, __setitem__, __delitem__) and iterable interface over records rather than keys. Includes Select property for filtering operations.
- Introduce `TestSelect` class with various test methods to validate event selection - Test slicing, field selection, logical operations, and error handling - Validate timestamp comparison and coercion - Ensure selections do not alter the original log or collection - Test entry selection by ID, path, and name - Validate the behavior of the `Select` class with different scenarios
- Introduce `Markers` class inheriting from `Node` and `MutableSet` to manage asset extensions - Implement methods for adding, removing, and clearing markers - Add `Text` class to handle the `.markers` file operations - Integrate `Markers` with `Trail` class for automatic extension tracking - Update `Trail` class to include a `markers` property for accessing the `Markers` instance
- Change marker normalization to keep the leading dot, as per `Path.suffix` - Update docstring to reflect the new marker format - Modify `normalize` method to return the normalized marker with a leading dot - Adjust `matches` method to handle the new marker format without removing the prefix dot - Update comments to clarify the behavior of the `matches` method
- Introduce `mark` method to track files indicated by markers but not yet tracked - Implement `_scoped` method to determine if a path is within the project directory or tracked directories - Add `_markable` method to check if a path should be marked based on markers and other conditions - Implement `_walk` method to iterate over files in specified directories - Add `_descends` method to determine if a path should be included based on ignoring and symlink conditions - Update `watchdog.py` to call `mark` method for files created or moved in watched directories - Modify `event.py` to handle marked files in tracked directories - Update `dir.py` to only include marked files in the trail assets - Add `mark` method to `Markers` class to update tracked entries when markers change - Update `trail.py` to call `mark` method after replaying events and tracking new directories - Add tests for marking files with markers and tracking them in the trail
- Add `test_a_new_trail_tracks_its_project_directory` to verify project directory tracking - Update event selection indices to account for the project directory event - Adjust assertions in `test_track_untrack_and_retrack_history_can_be_restored` for new event order - Update slicing and filtering tests in `test_listing.py` to reflect new event positions - Modify `Trail` initialization to track the project directory if it's a new trail - Update `Trail` replay logic to handle existing project directory tracking
- Add `create` method to `Markers` class for creating a project's .markers file - Implement logic to copy premade markers files or use user-provided paths - Update `Trail` initialization to create markers if they don't exist - Add package data configuration for premade markers files in `pyproject
- Add `test_a_subdirectory_opens_the_enclosing_trail` to verify subdirectory behavior - Add `test_the_nearest_trail_wins` to ensure the nearest trail is opened - Add `test_the_search_stops_at_a_ceiling_directory` to test ceiling directory behavior - Update `Trail` initialization to search for nearest `.trail` directory - Modify `Trail` class to handle ceiling directories using environment variables - Improve representation logic in `Trail` class for cleaner output
…ality - Replace `ask` function with `display`, `bare`, `Paths`, `expand`, `respecify`, `directory`, `Picker`, `offer`, `Asked`, and `ask` functions for improved user interaction - Add `toggle` function to manage markers - Update `resolve` function to handle errors in path resolution - Replace `gather` function with new implementation for better path tracking - Update `init` function to handle directory selection and initialization - Remove `YES` and `NO` constants - Add new imports from `prompt_toolkit` and `trail` modules
- Add a cursor to `gather` so the arrows move through the listed paths and <ENTER> removes the one under it - Let the Trail directory be removed from the listing, and add a `tracked` option to `Trail` for a new Trail that skips its own directory - Offtrail the Trail directory on re-initialization if it was removed - Scope markers to tracked directories only, rather than always including the project directory - Add `tabbing` bindings so <TAB> takes a completion and descends into directories - Accept a live `request` and `extra` bindings in `ask`, and style its session with `STYLE` - Report an already listed path instead of toggling it off - Update the walkthrough hints for adding, removing, and continuing
- Add geospatial.markers covering vector, raster, and tabular GIS extensions - Add ml.markers covering model checkpoints, arrays, and serialized data
- Keep `Trail.locate` from climbing into any directory listed in TRAIL_CEILING_DIRECTORIES (split on os.pathsep), the same way GIT_CEILING_DIRECTORIES works - Mention the ceiling in the `Trail` docstring - Use `pytest.MonkeyPatch.context()` in the ceiling test so it runs without the fixture, and add it to the `__main__` test list
- Move markers files from `premade` to `markers` directory - Update `pyproject.toml` to reflect the new markers file path - Update docstrings and comments in `trail.py` and `markers.py` to reflect the new directory structure - Rename `premade` function to `available` in `markers.py` - Update function calls and references in `cli/init.py` to use the new function and directory names - Remove the use of `PREMADE_NAME` and replace with `DEFAULT_MARKERS` - Update the `offer` function to list available markers files from the new directory
- Change markers file extension from `.markers` to `.txt` in `pyproject.toml` - Rename all markers files from `.markers` to `.txt` - Update `markers.py` to recognize `.txt` extension instead of `.markers` - Modify `cli/init.py` to correctly reference the new `.txt` markers files - Add `json` to the list of supported file types in `default.txt` - Update function docstrings and error messages to reflect the new file extension
- Add `test_init.py` with comprehensive test cases for the `init` function: - Test accepting every default starts a trail with the default markers - Test the arrow climbs to the parent directory - Test a typed directory replaces the suggestion - Test a directory nested in a trail starts its own - Test escape turns down the default markers - Test a typed path chooses a markers file of its own - Test a typed directory offers the markers inside it - Test an arrow after typing returns to the markers files - Test extensions toggle - Test a bad extension is refused without ending the step - Test entered paths are tracked and entered again are kept - Test the path under the cursor is removed - Test a pasted list is entered whole - Test right and left choose what the arrows scroll - Test reinitializing starts from the default markers - Test reinitializing keeps the project markers when they are named - Test escape with nothing toggled leaves a blank markers file - Test a completed directory is typed on into - Test an interrupt writes nothing - Test an interrupt in the picker writes nothing - Add `test_markers.py` with comprehensive test cases for the `Markers` class: - Test instantiation tracks marked files - Test marking is idempotent and survives reload - Test offtrailed files stay offtrailed - Test adding a marker tracks existing files - Test tracking a hidden directory tracks its marked files - Test tracked directory outside the project is marked - Test created file beside a tracked asset is marked - Test tracked directory takes in only marked files - Test a new trail copies the default markers - Test a new trail copies markers from a path - Test existing markers are not overwritten - Test a reopened trail does not copy markers - Test an unknown markers name is refused
- Update `Console` class to move run logic to a new `Run` class - Refactor command submission and error handling in `Console` class - Update method names and logic for streaming events and monitoring watchdog - Add new `Run` class to manage live session and event streaming - Update `Node` class to include parent node property - Refactor command collection property to use `@property` decorator - Update marker description in `init.py` to clarify file types - Refactor `command.py` to simplify command handling and query processing
- Add comprehensive docstrings to `TrackCommand`, `UntrackCommand`, `AssetsCommand`, and other command classes - Update `Feed` and `Console` class docstrings to provide detailed descriptions of their roles and properties - Expand `Render` and `Renderer` class docstrings to clarify their responsibilities and usage - Add detailed explanations for the CLI initialization and main function - Improve documentation for key bindings, command line parsing, and error handling
- Add `blank` method to `Feed` class for separating banner from events - Remove `backlog` and update `Run` class to print only new events - Update `banner` method to display welcome message and asset counts - Add `welcome` method to `Render` class for personalized welcome messages - Add `returning` parameter to `Console` class to track session continuity - Update `theme.py` to include new styles for welcome messages - Remove redundant code and improve overall readability
A Dir is a directory named by .markers. It now has an ID and a history in the log, so events are associated with watched directories as they are with assets. .markers still decides which Dirs are live, and the log records their identity and what happened to them. - Add entry.py with Entry (id, path, track, offtrail, repr) and Entries (lookup by id and path). Asset and Dir derive from Entry, and Assets and Dirs derive from Entries. - Dir keeps its ID while its root and scopes follow .markers. Dirs.refresh logs an AddDirEvent or RemoveDirEvent for each Dir that comes or goes. It runs after the log is replayed, after each change to .markers, and when a directory asset is tracked or offtrailed. - A .markers edited by hand is read on the next start as removals and additions. No rename is inferred. - A Dir's directory renamed or deleted on disk is logged against the Dir. A rename warns, and the Dir keeps its path, since its line still names it. Replaying a moved event never moves a Dir. - Rename Event.asset to Event.entry, including the record key. The replay makes a Dir or an Asset from the first record about each ID. - Events.clear logs the live Dirs again with their IDs, so later events about them still replay. - Apply a repeated directory event once per batch. A deleted directory was reported by its own watch and by its parent's. - Make the console's dirs command a selectable listing again, refuse dirs clear, and word the new events as watched and unwatched. - Add tests/test_dirs.py and update the other tests for the renames and the Dir events that now open a new log.
…havior - Remove RIGHT and LEFT key constants from test_init.py - Update test_escape_turns_down_the_default_markers to reflect new behavior - Modify test_the_arrows_choose_another_marker_set to use general.txt markers - Update test_a_file_longer_than_the_preview_is_cut_off to handle single file case - Refactor test_markers.py to reflect changes in default markers behavior - Update test_trail.py to use general markers in Trail initialization - Remove redundant tests and update docstrings to reflect new behavior
- Drop `Editor`, `ask`, `Asked` and `tally`; init now writes the chosen markers file as is - Pass the imported flag to `trail.markers` so warnings name anchored lines from elsewhere - Point the user at `.markers` to change the markers after init - Update the `Picker` docstring and margin now that no editor follows - Remove `TestEditor` and the editor-driven init tests; cover import warnings and blank escape
…mples that use them - Call methods on `self` in method examples instead of reaching through `trail` - Use `Renderer.home` in the `Renderer.home` example - Build the `Markers` repr example from `lines_repr` directly in `util` - Define `dirs` and `scopes` in the `match` example
- Describe the chosen file as the starting point for a new `.markers` rather than its copy source - Note that the preview truncates long files since the following editor shows every line - Reduce `Picker.margin` from 15 to 14 terminal rows
- Split compound boolean returns in `Assets._markable` and `Assets._descends` into early returns - Build `Assets` walk depths as a dict comprehension merged with `|` - Name intermediate values for `iglob` results, `create_task` calls, prompt_toolkit windows, completion documents and `list_repr` output instead of nesting them inline - Replace nested `next(...)` generators in `markers.parse` and `markers.canonical_path` with named `wildcards` generators - Extract `EVENT_TYPES` in `event` and `EVENT_FILTER` in `watchdog` as module-level `Final` constants - Break single-line comprehensions and `Path` method chains across multiple lines - Unpack `(style, text, *_)` directly in `Feed.append` instead of indexing fragments - Apply the `within` filter in `Watchdog.desired` as a separate pass before the ignore and `is_dir` checks - Reindent continuation lines in `watchdog` conditions and the `_reaches` signature
- Add notes/10-8-1-dirasset-access-plan.md with a summary at the top
- Add notes/10-8-directory-asset-sessions-plan.md, which 10-8-1 replaces and cites for the inotify measurements
- Rename the plan's PRs to commits on one local branch off dhodczak - Review the series together at the tip
- Rename `trail.cli.scopes` to `trail.cli.marker_completion` - Rename `Scope` to `MarkerCompleter` and `ScopePaths` to `MarkerPaths` - Move `CHILDREN` and `EVERYTHING` from `trail.util` to `trail.asset` - Move `OPS` from `trail.util` to `trail.event` - Rename `Assets._is_markable` to `_is_trackable` and `Assets._descends` to `_is_descending` - List the per-command completions in `Console`'s completer docstring as bullets, adding `unmark` - Build `Scopes.relative` with a comprehension - Wrap the condition in `Trail._is_ignored` across lines - Update imports in tests for the moved names
- Add `Entries` in `trail/entries.py`, reached as `trail.entries`, to look up an asset or a Dir by id or path with `[]`, `get`, `in`, iteration and `len` - Rename the per-kind base class `Entries` in `trail/entry.py` to `EntryCollection` - Move `Trail._offtrailed_paths` to `trail.entries.untracked` - Move `Trail._is_ignored` to `trail.entries.is_metadata` - Move `Assets._is_trackable` and `Assets._is_descending` to `trail.entries.is_trackable` and `trail.entries.is_walkable` - Replace `Trail._entry` with `trail.entries` lookups in `Event.from_record` and `JSONL` loading - Move the module constant `CHILDREN` to the class attribute `DirAsset.suffix2children` and make `DirAsset.is_match` a classmethod - Add tests for `trail.entries` lookups, membership, iteration, untracked paths across reloads and metadata checks
…tory dataset access logging - Update the PR draft to include `.offtrail` rules and shared rules base - Add `trail.entries` to look up assets and Dirs together - Add `Rule`, `Rules`, and `TXT` classes for rule management; inherited by `OnTrail` and `OffTrail` - Add `OffTrail` for exclusion rules and its integration with `OnTrail` - Update `Dir`, `Dirs`, `Asset`, and `DirAsset` classes with new methods and properties - Update `Entries` class to include `untracked`, `is_metadata`, `is_trackable`, and `is_walkable` methods - Add `DirectoryAccessEvent` and `Access` for directory dataset access logging - Update `Watchdog` and `WatchdogSession` classes for observation and event handling - Update command-line interface for interactive console and initialization
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
This PR extends Trail with automatic asset discovery, directory dataset tracking, and an interactive terminal.
.ontrailand exclusions in.offtrail.trail.selectexpression language through Python collections and terminal listings.Quick usage
From the repository checkout, using Python 3.12 or newer:
Choose the
generalpreset when prompted. At Trail's prompt:ontrailandofftrailchange active tracking. Edit.ontrailand.offtrailto change automatic discovery, then restart Trail. The log persists between runs.The class examples below use a temporary project containing
new.csv,data/map.png,cube.zarr, and an initially untrackednotes.md. The directory-access example uses a constructed event with representative notification counts. The directory dataset tests and access tests cover discovery and observation behavior.Core classes
Trail
Trailis the project entry point. It exposes inclusion and exclusion rules, configured directories, tracked assets, and the event log.For the Python examples, open a project containing the sample files:
Later blocks such as
trail.ontrail: OnTrailshow an attribute's type. They are access hints, not setup statements.Trail(path)opens the nearest project found from the supplied directory. A new project can start from an inclusion preset, such asTrail(path, ontrail='geospatial').Trail.locate()searches the directory and its ancestors for.trail, stopping before directories listed inTRAIL_CEILING_DIRECTORIES.Trail.clear()untracks assets and discards the log. The project ID and rule files remain; configured directories are logged again with their existing IDs.Rules and scopes
The rule files define automatic discovery:
Ruleparses rule syntax.TXTreads the rule files.Scopesmatches inclusion patterns.Rulessupplies the common collection behavior inherited byOnTrailandOffTrail.Rule(str)
Ruleis an immutable string with the syntax operations used by both rule files.Rule.parse()separates a rule into its directory anchor and matching pattern.Rule.kind()describes it for rule listings, for exampleroot scopeordir scope.Rule.validate()rejects invalid syntax.Rule.ambiguous_directory()identifies a directory written without its trailing/so diagnostics can explain how the rule will be read.TXT
TXTwraps the text file stored in a rule collection's.txtattribute.TXT.read()loads rules in file order, skipping comments and blank lines. It does not rewrite the file or itself rebuild project state.TXT.numbered()retains source line numbers for diagnostics.TXT.create()initializes a missing file from its owner's preset directory or a supplied file. This setup operation remains necessary with direct text editing.Scopes(Sequence[str])
Scopesholds inclusion rules beside their compiled patterns. Root scopes apply beneath configured roots; local scopes apply relative to one configured directory.This PR exposes root inclusion scopes as
trail.scopes. A future commit moves them totrail.ontrail.scopesand exposes exclusion scopes astrail.offtrail.scopes.Scopes.decide()returns the last matching rule. Matching ignores case; a leading!excludes the match.**. A root rule alone watches a directory without selecting all its files.Rules(Sequence[Rule])
Rulesholds the ordered rules of one file. Its inclusion and exclusion subclasses share iteration, indexing, diagnostics, and preset lookup.Rules.available()lists the presets belonging to the subclass. Inclusion and exclusion presets stay separate.OnTrail(Rules)
OnTrailholds.ontrail, the text file beside.trailthat names directories to watch and files or datasets to discover.trail.ontrail(*paths)tracks paths immediately. A directory becomes one directory dataset. A single path returns its asset; multiple paths return a list. Neither rule file changes../name directories to watch recursively. Root patterns such as*.csvapply at any depth beneath those roots;data/*.pngapplies relative todata.OnTrail.warningsreports invalid rules, ambiguous directory syntax, and attempts to use directory datasets as scan roots.default,general,geospatial, andml. The default contains only./; the others also select extensions.OffTrail(Rules)
OffTrailholds.offtrail, whose rules exclude paths from automatic discovery before inclusion rules are considered.trail.offtrail(*paths)untracks assets and remembers their paths so later discovery, including after reopening, does not take them again. Neither rule file changes.OffTrail.default()initializes a missing.offtrailwith.*, excluding dotfiles and hidden folders. An empty file ignores nothing; a missing file receives the default again.OffTrail.decide()uses case-insensitive matching and the last matching rule. A negation such as!.envmakes the path eligible for inclusion rules again.trail.ontrail(path)can track a path excluded by.offtrail. Trail metadata remains protected.Entries and collections
Collectionsupplies ordered storage.EntryCollectionadds path lookup for the directory and asset collections.Entriesprovides one lookup across those collections.Entryis the shared record base for configured directories and tracked assets.Dirrepresents a configured directory;Dirsholds those records.Assetrepresents a tracked file;DirAssetrepresents a directory dataset.Assetsholds both.Collection
Collectionsupplies ordered storage shared by event, asset, and directory collections.Collection.selectexposes positional and expression-based selection, described underSelectbelow.Collection.get()supports a default for missing keys.EntryCollection(Collection[EntryKey, E])
EntryCollectionsupplies ID and path lookup forAssets(tracked files and datasets) andDirs(configured directories). Passing several keys returns a tuple of entries.EntryKeyaccepts an ID or path;Eis the entry record type.Entries
Entriesis a combined view over assets and configured directories, without maintaining a second collection of records.entries[key]looks up an ID or path, trying assets first. Several keys return a tuple; missing keys raiseKeyError.Entries.get()returns a default for missing keys.Entries.untrackedremembers explicitly untracked paths across log replay. Tracking a path again removes it from this set.Entries.is_metadata()protects.trailand its contents,.ontrail, and.offtrailfrom tracking and filesystem-event handling.Entries.is_trackable()applies discovery eligibility, exclusions, remembered untracking, and dataset ownership.Entries.is_walkable()prevents descending into symlinks, metadata, remembered untracked paths, and directory datasets. An excluded directory is traversed only when a configured directory at or below it requires access.Dir(Entry)
Dirnow represents a directory named by inclusion rules, with its root status and local scopes. Ordinary subfolders encountered by recursive observation do not acquire separate directory records.Dir.decide()evaluates its local scope patterns.Dirs(EntryCollection[Dir])
Dirsholds the configured directory records and the root scopes used during matching.Dirs.refresh()reconciles records with inclusion rules and records directory additions or removals. Surviving records retain their IDs across refreshes and reopening.Dirs.match()consults the deepest matching directory before its ancestors and the root scopes.Dirs.clear()refuses direct clearing: a configured directory goes when its rules leave.ontrail.Asset(Entry)
Assetrepresents a tracked file. Its repr now includes its current size and modification time; a missing resource displays<missing>.Asset.from_path()chooses a file asset or a directory dataset from the supplied path.DirAsset(Asset)
DirAssetrepresents a directory tracked as one dataset. It shares the asset collection with files and retains one resource ID across dataset rewrites and moves.DirAsset.is_match()recognizes.zarr,.n5,.gdb, and.safedirectories during automatic discovery. Explicit tracking also accepts other directories as datasets.DirAsset.childrenchooses the format-specific filename patterns that distinguish dataset activity from locks, temporary files, and unrelated files. Other explicitly tracked directories include every child.DirAsset.accessexposes the currentAccess, the object accumulating filesystem notifications for that dataset.Assets(EntryCollection[Asset])
Assetsholds tracked files and directory datasets, using the shared entry-collection lookup and selection behavior.Assets.add()accepts resolved paths mapped to their selecting rule, orNonefor explicit additions. It returns assets in request order, reuses existing assets without duplicate addition events, and reconciles directory records and watches.Assets.scan()discovers eligible paths. It can select a directory dataset itself and skips descending into its dataset contents.Assets.holder()identifies the dataset owning a path and prevents separate tracking of dataset children. Unrelated files within recognized dataset directories can still be tracked independently. Tracking a directory whole untracks already tracked children it absorbs and warns about them.Filesystem observation and dataset accesses
Watchdogchooses what to watch.WatchdogSessionruns the observer.Handlerreceives filesystem notifications.Accessaccumulates a directory dataset's notifications and produces oneDirectoryAccessEvent.Watchdog
Watchdogmanages watch placement separately from the observer run; synchronous inspection shows the watches a later run would place.Watchdog.desired()requests recursive watches for configured directories and directory datasets, plus parent watches for moves and deletion. Watches already covered by recursive ancestors are omitted.WatchdogSession
WatchdogSessionowns the observer and consumes its notifications.Handlerreceives notifications on the observer thread, using rule snapshots published by the session. For directory datasets,Accessaccumulates notifications into oneDirectoryAccessEvent. Concurrent readers and writers share the same access.WatchdogSession.start()starts observation on a running asyncio loop. Synchronous use remains dormant until a loop starts a session.async with trail.watchdog.sessionmanages a run explicitly.WatchdogSession.reconcile()updates watch placement and publishes rule snapshots for the observer thread.WatchdogSession.stop()stops observation, drains delivered events, and closes remaining accesses. A later run creates a fresh observer and per-run state.DirectoryAccessEvent(WatchdogEvent)
DirectoryAccessEventrecords a completed dataset access as one synthetic event. The representative fixture below contains one open and 72 modification notifications over 242 ms.openedwhen only opens occurred, ormodifiedwhen other counted activity occurred. Empty accesses are discarded.opened,created,modified,moved, anddeletednotifications, not distinct files or application operations. Temporary-file renames into dataset children count as writes; ignored lock files do not turn a read into a write.startedis the first notification's arrival time;timestampis the last.Command-line interface
The terminal combines setup, a live event feed, and commands for inspecting or changing active tracking. Rule configuration stays in the two text files.
Project setup
Initialization prepares a project before opening the console.
Pickerlets the user choose the inclusion rules during that setup.Initialization
main()opens the console, running setup first when the directory has no project. Setup can also run alone:--nodirskips setup and holds events in memory..ontrailand initializes a missing.offtrail, then discovers eligible assets..ontrailwhile retaining.offtrail, the project ID, tracked assets, and event history.pathspec, and terminal input usesprompt_toolkit>=3.0.52.From the shell, initialize a project and open its interactive console:
Running
trail /path/to/projectalone also starts setup if needed. The commands below are entered at Trail's prompt, without thetrailprefix.Picker
Pickerpreviews bundled presets and supplied rule files during initialization..ontrailinside a directory.Console and output
Consoleowns the command bar.Runprints events during observation.Feedkeeps terminal output.Rendererformats records and counts.Console
Consoleholds the editable command bar, command dispatch, and rendering objects.To inspect its Python components, construct it from the project opened above:
The shell command
trailconstructs and runs the console during normal use.The header keeps project, asset, directory, event, and open-access counts current while a session runs. These synchronous examples show the console idle.
Use
helpto list commands,assetsto inspect tracked files and datasets, anddirsto inspect watched directories:Tab completes commands and paths. Up and Down recall earlier commands. Ctrl+L clears terminal output. Enter
quitor press Ctrl+C to stop; the saved log loads when the project is reopened.Run
Runprints the banner and events recorded during the run. Earlier history remains available throughevents, and shutdown drains access events closed by the session.Feed
Feedprints ordinary terminal output, retaining native scrollback and text selection, with an in-memory history bounded to 2,000 rows.Feed.write()prints events with their collection positions and a date row when the day changes.Feed.clear()discards retained rows and the current date. Clearing the terminal does not clear tracked resources or event history.Renderer
Rendererturns resources and events into feed rows with project-relative paths, collection positions, resource IDs, and counts.Renderer.header()reports counts, open dataset accesses, and whether observation is active.Renderer.verb()chooses the event verb used to color each heading: tracking, untracking, directory watching, or a filesystem operation.Commands and tracking
Commandsholds the registered commands.Commandsupplies their dispatch hooks and shared path handling.RulesCommandand its two subclasses list rules and change active tracking.Commands
Commandsholds the registered commands. Named command subclasses register themselves so dispatch, help, and completion use the same table.Commands.find()accepts exact names and unambiguous prefixes.helplists commands, key bindings, path-versus-rule behavior, selections, and clearing.clear -funtracks assets and empties the project log. Ctrl-L clears terminal output.restartreopens the console in a new process, picking up source and rule-file edits. With--nodir, it requires-fbecause the in-memory log would be lost.To apply rule-file edits, reopen the project in a new process:
To leave the console:
Command
Commandis the base of terminal commands. Named subclasses register themselves for dispatch, help, and completion.RulesCommandadds rule listings and path operations;Listingadds filtered collection listings.RulesCommand(Command)
RulesCommandsupplies rule listings and path operations for the inclusion and exclusion commands. With no arguments, each lists its rule file; paths change active tracking.RulesCommand.show()prints each rule's kind and owning directory, then diagnostics.OnTrailCommand(RulesCommand)
OnTrailCommandimplementsontrail: list inclusion rules or track supplied paths immediately..ontrailand.offtrailunchanged.trail ontrail [PATH...], performs the same kind of operation without opening the console.Track a file, inspect it, or track the sample Zarr directory as one dataset:
The file and directory must already exist. To discover future CSV files automatically, edit
.ontrailin Vim and add*.csv, then restart the console.OffTrailCommand(RulesCommand)
OffTrailCommandimplementsofftrail: list exclusion rules or untrack supplied paths.trail offtrail [PATH...].Stop tracking the file and then track it again:
After
offtrail, the asset listing is empty for that path. Explicitontrailtracks it again.Resource and history listings
Listingsupplies filtered listings for the three concrete commands below.Queryparses their selections and resolves terminal paths against the project root.Listing(Command)
Listingsupplies resource and event listings. It appliesQueryto the named collection.field=terms.clearpreviews clearing the whole named collection;-fconfirms it. It does not reuse a previous listing's filter.AssetsCommand(Listing)
AssetsCommandlists tracked resources. Here the 5-byte dataset is excluded by a numeric size comparison:assets clear -funtracks all assets and records their removals.List all tracked resources or select the sample CSV by its path:
Use
pathfor asset and directory records; usesrc_pathfor event records.DirsCommand(Listing)
DirsCommandlists configured directories, including their root status and local scopes. It refusesdirs clear: remove their rules from.ontrailand reopen the project instead.EventsCommand(Listing)
EventsCommandlists recorded history:events clear -fdiscards the log and records the configured directories again. Tracked assets remain active during the session; reopening reconstructs assets from the remaining log and current discovery rules.Read the last 20 events, the last five events, or the sample CSV's last five events:
Filters support adjacent terms (
and), alternatives (or), and exclusions (not):A slice acts on the records left by the terms before it.
events src_path=new.csv -5:shows that file's last five events;events -5: src_path=new.csvsearches only the log's last five events.Shared selections
The collections and CLI listings above share one expression language:
Selectimplements Python selections.Queryadds project-relative paths for terminal commands.Select
Selectimplements the selections reached through each collection's.select. The terminal uses the same parser and comparison rules.select[index]supports positive and negative positions. A slice returns a selection of the same collection type.select(expression)supports field comparisons, quoted values, parentheses,not,and, andor. Adjacent terms implyand.event_type=modified -5:takes the last five matching events;-5: event_type=modifiedfilters only the last five events.Select.compare()converts comparison values to the field's type. Class comparisons include subclasses, record references compare by ID, and timestamps accept ISO datetimes or a UTC clock time for today.Select.subset()copies membership while sharing records and their project parent. Clearing an event selection leaves the persisted log unchanged; clearing an asset selection untracks the selected assets from the project.Query(Select[T, V])
Queryparses selection expressions for terminal commands.Tis the selected collection type;Vis its record type. Relative path comparisons resolve against the project root, sosrc_path=new.csvmatches an absolute stored path. Numeric fields compare numerically.Validation
Coverage relevant to this PR includes:
The test workflow runs pytest with Python 3.12 on Ubuntu, macOS, and Windows. Open-event coverage accounts for backend support.
Known macOS CI failures: 11 filesystem-notification tests remain failing. All 37 rule and scope tests pass after the path-normalization fix. Notification handling remains follow-up work.
Validated commit:
55bc37116f3454f53153c1e137ab3e48e27edf9a, in an isolated Linux copy using Python 3.12.16, pytest 9.2.0, and Ruff 0.17.5.🔍 Preview: https://geojupyter-trail--3.org.readthedocs.build/
Note: This Pull Request preview is provided by ReadTheDocs. Our production website, however, is currently deployed with GitHub Pages.