Skip to content

refactor: consolidate the filesystem subsystem under src/fl/fs/ #4008

Closed

Description

@zackees

Summary

Filesystem code is spread across four unrelated parts of the tree with no directory that names the subsystem. Proposal: consolidate under src/fl/fs/**.

This surfaced while adding a second storage backend (#3984 / #4007). Nothing about that work was hard; deciding where each file goes was, repeatedly — which is the symptom worth acting on.

Where filesystem code lives today

Concern Location
Public API + FsImpl interface fl/system/file_system.{h,cpp.hpp}
SD backend fl/system/sd/
Embedded-flash backend fl/system/embedded_fs/ (new)
filebuf — the file handle every backend implements fl/stl/detail/file_handle.h
ifstream / filebuf_ptr fl/stl/fstream.h
Asset resolution (.lnk, FL_ASSET) fl/asset/
Platform backends platforms/stub/fs_stub.hpp, platforms/wasm/fs_wasm.*, platforms/arm/teensy/sdfat/**, platforms/esp/fs/
Unity TUs fl/build/fl.system+.cpp, fl.system.sd+.cpp, fl.system.embedded_fs+.cpp, fl.asset+.cpp

fl/stl/ is the odd one. filebuf is the abstraction every backend subclasses — it is the filesystem's core type, sitting in the standard-library-shims directory because it is spelled like std::filebuf. Anyone tracing how a backend works has to leave the filesystem code entirely to find its base class.

fl/system/ is a grab bag by construction: delay.h, pin.h, heap.h, serial.h, yield.h, timeout.h, engine_events.h and the filesystem all share it. A subsystem with three subdirectories, four translation units, and platform fragments in five places has outgrown a shared folder.

Proposed

src/fl/fs/
    fs.h                  public API (FileSystem, FsImpl, factories)
    fs.cpp.hpp
    file_handle.h         filebuf — moved from fl/stl/detail/
    fstream.h             ifstream — moved from fl/stl/
    sd/                   SD backend
    embedded/             on-chip flash backend
    asset/                .lnk resolution, FL_ASSET   (or left in fl/asset/)

with src/fl/build/fl.fs*.cpp for the translation units and platform fragments staying under src/platforms/**, reached through a dispatch header exactly as they are now.

Why now

Two related issues are already open against the current shape, and both get easier with a home for the subsystem:

Doing this before more backends land is cheaper than after. RP2040 LittleFS and any FatFS work would otherwise each repeat the "where does this go?" decision.

Constraints any restructure must preserve

  1. Per-backend translation units. fl.system.sd+.cpp exists so the linker drops the SD chain (~16 KB on ESP32-S3) when beginSd() is never called — Meta: ESP32-S3 binary-size reduction — Batch 1 (~26 KB) + Batch 2 (~26–50 KB) (supersedes #2771) #2773 item 1.2. fl.system.embedded_fs+.cpp does the same for flash. Renaming is fine; merging them is not.
  2. The entry point must share a TU with its backend. Splitting them puts the backend in platforms+.cpp, which every sketch links, and the tree-shaking silently stops working.
  3. #include "fl/system/file_system.h" must keep working, or this becomes a breaking change for every sketch that opens a file. A forwarding header is the obvious answer; the deprecation timeline is a separate decision.

Open questions

  1. fl/fs/ vs fl/filesystem/ — fs.h is terse and matches fl/stl/, fl/fx/, fl/ui/; filesystem.h is unambiguous. Note the existing comment at the top of file_system.h: "fs.h breaks ESPAsyncWebServer so we use file_system.h instead" — worth checking whether a fl/fs/fs.h path collides the same way before committing to the name.
  2. Does fl/asset/ move in, or stay adjacent? It is a consumer of the filesystem, not part of it.
  3. Should filebuf / ifstream move, given they are deliberately std-shaped and live with the other shims?
  4. Big-bang move plus forwarding headers, or incremental with both paths live?

Related

Activity

  1. zackees commented on Aug 23, 2026

    @zackees
    MemberAuthor

    Open question 1 resolved — fl/fs/fs.h is safe

    The concern was the comment atop file_system.h: "fs.h breaks ESPAsyncWebServer so we use file_system.h instead." That collision cannot recur at fl/fs/fs.h, and the tooling that guarantees it is already in place — nothing needs adding.

    IncludePathsChecker (ci/lint_cpp_rs/src/checkers/basic.rs) enforces src-root-relative includes on two fronts:

    1. Relative paths are rejected outright (lint_core/path_helpers.rs:77):

      Invalid include path: #include "../foo.h" - Relative paths (../ or ./) are
      not allowed. Use paths relative to src/ instead (e.g., "fl/foo.h" or
      "platforms/bar.h"). Add '// ok include path' comment to suppress.
      
    2. Every other include must resolve from src/ (basic.rs:460-465):

      Header not found: #include "fs.h"
        Expected: src/fs.h
      

    The second is what closes this. A bare #include "fs.h" is not a relative path, so rule 1 misses it — but rule 2 catches it, because it would have to resolve to src/fs.h, which will not exist. The only spelling that compiles is #include "fl/fs/fs.h".

    The external-library case is closed by construction: ESPAsyncWebServer's #include <fs.h> looks for a bare fs.h, which FastLED would not have at a shadowing location. The original breakage came from a header reachable as fs.h; one at fl/fs/fs.h is not.

    Verified state of the tree: the only relative includes under src/ are seven lines in the vendored platforms/arm/teensy/sdfat/** tree, each carrying an explicit // ok include path; // ok relative include - imported SdFat layout suppression. There are no unsuppressed violations, so the convention is enforced in practice rather than merely documented.

    No build-system change is required. I checked whether the build files needed to restrict include paths and they do not — the lint layer covers it more precisely than an include-path change could, because it also rejects the bare-filename form that a compiler would otherwise resolve happily from the including file's own directory.

    Naming decision: fl/fs/fs.h.

  2. zackees commented on Aug 23, 2026

    @zackees
    MemberAuthor

    Proposed fl/fs/fs.h — concrete draft

    Resolving open questions 2 and 3 by showing the shape rather than describing it. Not implemented; posting for review before anyone moves files.

    #pragma once
    
    /// @file fl/fs/fs.h
    /// @brief Reading files, wherever they live.
    ///
    /// Three pieces, deliberately separate:
    ///
    ///   - `FileSystem`  — open / read / close. Knows nothing about formats.
    ///   - `getXxxFs()`  — where the bytes live. One free factory per medium.
    ///   - `fl/fs/read.h` — decode helpers. Opt in by including them.
    ///
    /// A sketch picks a medium, hands it to `FileSystem`, and reads:
    ///
    /// @code
    ///     fl::FileSystem fs;
    ///     if (fs.begin(fl::getEmbeddedFs())) {          // on-chip flash
    ///         fl::ifstream f = fs.openRead("data/frame.rgb");
    ///     }
    /// @endcode
    ///
    /// Adding a medium costs one free function and no change to `FileSystem`.
    /// Adding a format costs one free function in `fl/fs/read.h` and no change
    /// to either. That is the whole point of the split — see #4003, #4007.
    
    #include "fl/fs/file_handle.h"   // filebuf            // IWYU pragma: export
    #include "fl/fs/fstream.h"       // ifstream           // IWYU pragma: export
    #include "fl/stl/noexcept.h"
    #include "fl/stl/shared_ptr.h"
    
    namespace fl {
    
    FASTLED_SHARED_PTR(FsImpl);
    
    // ---------------------------------------------------------------------------
    // Media
    // ---------------------------------------------------------------------------
    // Each names *where the bytes live*, never the driver that reads them.
    // `getEmbeddedFs()` is LittleFS on ESP today and may not be tomorrow; no
    // sketch has to care, and no platform has to hold an opinion about a
    // filesystem it does not have (#4007).
    //
    // All return null where the platform lacks that medium, so a call is safe
    // to make unconditionally and the failure surfaces at `begin()` rather
    // than at link time.
    
    /// Removable SD card on the given chip-select pin.
    FsImplPtr getSdFs(int cs_pin) FL_NO_EXCEPT;
    
    /// Storage built into the microcontroller itself (on-chip flash).
    ///
    /// @param format_on_fail  Format and mount when the storage is absent or
    ///                        corrupt. Off by default: reformatting discards
    ///                        whatever was there. Platforms with no such hook
    ///                        ignore it and simply fail to mount.
    FsImplPtr getEmbeddedFs(bool format_on_fail = false) FL_NO_EXCEPT;
    
    // ---------------------------------------------------------------------------
    // FileSystem
    // ---------------------------------------------------------------------------
    
    class FileSystem {
      public:
        FileSystem() FL_NO_EXCEPT;
    
        /// Mount a medium. False if it could not be opened — including when the
        /// factory returned null because the platform has no such storage.
        bool begin(FsImplPtr medium) FL_NO_EXCEPT;
    
        /// Release the medium. Safe on an unmounted FileSystem.
        void end() FL_NO_EXCEPT;
    
        /// Closed stream if the file could not be opened.
        ifstream openRead(const char *path) FL_NO_EXCEPT;
    
      private:
        FsImplPtr mFs;
    };
    
    } // namespace fl
    
    // ---------------------------------------------------------------------------
    // What is deliberately NOT here
    // ---------------------------------------------------------------------------
    //
    // `openVideo`, `openMpeg1Video`, `loadJpeg`, `openMp3`, `readJson`,
    // `readText`, `readScreenMap`, `readScreenMaps`, `loadFled` — every format
    // helper currently on `FileSystem` — move to `fl/fs/read.h` as free
    // functions over a `FileSystem&`:
    //
    //     namespace fl {
    //     FramePtr readJpeg(FileSystem &fs, const char *path,
    //                       const JpegConfig &config = JpegConfig(),
    //                       string *error = nullptr) FL_NO_EXCEPT;
    //     bool     readJson(FileSystem &fs, const char *path, json *out) FL_NO_EXCEPT;
    //     Video    readVideo(FileSystem &fs, const char *path, size pixelsPerFrame,
    //                        float fps = 30.0f, size nFrameHistory = 0) FL_NO_EXCEPT;
    //     }  // and so on
    //
    // Two reasons, both concrete:
    //
    //   1. Today `file_system.h` re-exports `fl/fx/video.h` and `fl/codec/jpeg.h`
    //      (`// IWYU pragma: export`), so every sketch that opens a file also
    //      compiles the video and JPEG headers whether it decodes anything or
    //      not. Splitting them means you pay for the decoder you include.
    //
    //   2. `FileSystem` currently grows a method per format. The tenth format
    //      makes the class bigger; a tenth free function does not.
    //
    // `FsImpl` — the interface a platform subclasses — moves to `fl/fs/backend.h`.
    // Sketch authors and platform implementers read different files for
    // different reasons; today they share one.
    //
    // `loadJpegFromSD()`, an inline body in the current header that constructs a
    // FileSystem, mounts SD, and decodes a JPEG, is dropped. It hard-couples two
    // unrelated concerns and is two lines at the call site:
    //
    //     fl::FileSystem fs;
    //     if (fs.begin(fl::getSdFs(cs_pin))) { fl::readJpeg(fs, path); }

    Directory

    src/fl/fs/
        fs.h              this file — FileSystem + media factories
        fs.cpp.hpp
        read.h            format helpers as free functions over FileSystem&
        read.cpp.hpp
        backend.h         FsImpl — the platform extension point
        file_handle.h     filebuf     (moved from fl/stl/detail/)
        fstream.h         ifstream    (moved from fl/stl/)
        sd/               SD backend
        embedded/         on-chip flash backend
    

    Answers to the open questions

    Q1 naming — settled as fl/fs/fs.h. See the comment above; the include checker makes the bare-fs.h collision impossible.

    Q2 does fl/asset/ move in? No. It is a consumer of the filesystem — it resolves .lnk files and FL_ASSET paths by reading through FileSystem. Same relationship as the codecs, and they are staying out too.

    Q3 do filebuf / ifstream move? Yes. filebuf is the base class every backend subclasses — it is the filesystem's core type, sitting in fl/stl/detail/ only because it is spelled like std::filebuf. Tracing a backend today means leaving the filesystem code to find its own base class.

    Q4 big-bang or incremental? Incremental. fl/system/file_system.h becomes a forwarding header that includes fl/fs/fs.h and fl/fs/read.h, so existing sketches keep compiling unchanged. The format helpers stay as deprecated FileSystem members forwarding to the free functions until a major version drops them.

    Cost

    The include-graph win is the measurable part: file_system.h currently re-exports fl/fx/video.h and fl/codec/jpeg.h, so every sketch that opens a file compiles both. Worth measuring on a small target before and after — that number should decide how hard to push on this.

  3. added a commit that references this issue on Aug 23, 2026
    a5d65bb
  4. moved this from Triage to Done in FastLED Trackeron Aug 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions