Skip to content
rafageist edited this page Dec 4, 2026 · 6 revisions

Files

turboframe.files opens, saves and lists a project's files, and turboframe.watch says when they change. Neither needs a user interface, so a command-line tool or a service can use them too.

Use it for opening and saving a user's files safely, listing a project's files, following changes made by other programs
Import from turboframe.files import read_source, write_source, newline_of, lf_text, project_files, read_text; from turboframe.watch import FolderWatcher
Needs turboframe.files: nothing more. turboframe.watch: the watch extra (watchdog)
Extend project_files(hidden=, hidden_suffixes=); a watcher's callbacks; observer_factory in tests

EditorMixin saves and opens through turboframe.files (see The Editor), and the explorer watches its folders through turboframe.watch (see The Explorer). Use them directly for anything else.

Open and save without losing a byte

from pathlib import Path
from turboframe.files import ChangedOnDisk, FileProblem, read_source, write_source

try:
    source = read_source(Path("models/book.py"))   # .text, .stamp
except FileProblem as problem:
    print(problem)            # why it was not opened, in TurboFrame's language

text = source.text + "# reviewed\n"
try:
    saved = write_source(source.path, text, expected=source.stamp)
except ChangedOnDisk:
    # another program changed the file since it was read: ask the user, then
    saved = write_source(source.path, text, expected=source.stamp, overwrite=True)
  • read_source(path) returns a SourceFile(path, text, stamp). It opens only UTF-8 text. A binary file, a file that is not UTF-8, or one over MAX_BYTES (5 MB) is refused with a reason, never decoded with replacements: saving it would rewrite bytes the user never changed. The text keeps its \r\n if the file has it.
  • write_source(path, text, *, expected, overwrite=False) returns the new SourceFile. It writes a temporary file next to the target and then replaces it, so an interrupted save leaves the old file whole. The permissions are kept.
  • read_source(path, lf=True) and write_source(..., newline=) (since v0.2.1) are for code that counts offsets in \n text (a lexer, an outline): see "Newlines" below.
  • FileProblem (a binary file, a permission, a full disk) carries a message for the user, in TurboFrame's language; ChangedOnDisk is a FileProblem too, so catch it first.
  • The Stamp (modification time and size) is what the file was when it was read or saved. If the disk no longer matches, the save raises ChangedOnDisk, unless overwrite=True says the user chose to replace it. A new file has no stamp (expected=None); saving it is refused if a file of that name appeared meanwhile. changed_on_disk(path, stamp) asks the same question without saving.

Newlines

By default a file's text is exactly what is on disk, \r\n included, and a save writes it back byte for byte. When your code counts in \n text, ask for it, and give the file its newlines back when you save:

source = read_source(path, lf=True)        # source.text has \n newlines; source.newline is the file's: "\r\n"
...
write_source(path, text, expected=source.stamp, newline=source.newline)   # every \n written as "\r\n"
  • source.newline is the file's most frequent newline ("\r\n", "\n" or "\r"), "\n" for a file without any; a file with mixed newlines is saved with the most frequent one. Without lf it is None.
  • With newline=, the text you give is taken as \n text (a \r\n in it counts as one newline, never doubled). Anything but the three newlines is a ValueError.
  • newline_of(text) and lf_text(text) are the two helpers underneath.
  • For an editor, set LF = True on your EditorWindow instead: see The Editor.

List and search

from turboframe.files import project_files, read_text

for rel in project_files(Path("."), limit=20000):   # "src/app.py", with /; MAX_FILES by default
    text = read_text(Path(rel))                      # None for what is not text

project_files is git's list when the folder is a repository (what it tracks and what it does not ignore). Otherwise it walks the folder and skips HIDDEN_NAMES (version control, caches, virtual environments, node_modules), folders starting with a dot or ending with .egg-info, and compiled Python. Pass hidden= and hidden_suffixes= to change what a walk skips.

read_text(path, max_bytes=MAX_TEXT_BYTES) is for searching, not editing: it returns None for a file over 2 MB, a binary or an unreadable one, replaces bytes that are not UTF-8, and makes every newline \n. Find in files and the command palette's Go to file are built on these two (see Search, Command Palette).

API: turboframe.files.

Watch folders

turboframe.watch tells an application when entries appear, disappear or move in the folders it shows, through the system's own notifications (inotify on Linux, ReadDirectoryChangesW on Windows; FSEvents on macOS, untested). Nothing is polled. It needs the watch extra:

pip install "turboframe[watch] @ git+https://github.com/divengine/turboframe@v0.3.0"

The module imports without watchdog; watchdog is needed once a folder is watched. To make watching optional, test for it: importlib.util.find_spec("watchdog"), as the explorer does.

from turboframe.watch import Batch, FolderWatcher

class ProjectTree(Tree):
    def on_mount(self) -> None:
        self.watcher = FolderWatcher(self.changed, self.refused)
        self.watcher.set_folders(self.open_folders())   # the folders the tree shows unfolded

    def changed(self, batch: Batch) -> None:             # on watchdog's thread: move to the app's
        self.app.call_from_thread(self.reload, batch)

    def reload(self, batch: Batch) -> None:
        if self.watcher.is_current(batch):                # not for a set of folders changed since
            for folder in batch.folders:                  # batch.everything: too many, all of them
                ...                                       # compare with the disk, reload if it differs

    def refused(self, folder, why: str) -> None:         # a limit, permissions, a network drive: said once
        self.app.call_from_thread(self.app.notify, why, severity="warning")

    def on_unmount(self) -> None:
        self.watcher.stop()                               # every watch and thread ends
  • FolderWatcher(on_change, on_error=None, *, delay=DELAY, max_watched=MAX_WATCHED, max_pending=MAX_PENDING, observer_factory=None). on_change(batch) and on_error(folder, why) run on watchdog's threads: move them to your application's with call_from_thread, and never touch a widget from them.
  • Each folder is watched alone, not recursively; give the watcher the folders you show (MAX_WATCHED, 64, at most). watcher.folders is the set being watched.
  • A file's contents changing is not a change of its folder; a move affects both folders.
  • Events are gathered for a moment (DELAY, 0.3 seconds) and handed over once, without repeats. A storm, such as a checkout, becomes one batch with everything=True instead of a list of more than MAX_PENDING (128) folders.
  • A folder the system refuses to watch (a limit, permissions, a network drive) is reported once through on_error and left out; nothing polls instead.
  • In tests, pass observer_factory: a callable that returns an object with watchdog's observer methods, so no thread or real notification is needed.
  • set_folders with the same set changes nothing; a different set makes batches already gathered stale (is_current).

API: turboframe.watch.

Clone this wiki locally