From 102c66e798d71c0f0dfe7d1837e56335e63c547a Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 00:11:14 +0100 Subject: [PATCH 1/8] feat: configurable assets_dir and lockfile_dir for apps sharing a project root --- docs/getting_started/project-structure.md | 10 +++++++ news/+app-assets-and-lockfile-dirs.feature.md | 1 + .../+app-assets-and-lockfile-dirs.feature.md | 1 + .../reflex-base/src/reflex_base/config.py | 11 ++++++++ reflex/assets.py | 9 +++---- reflex/compiler/compiler.py | 2 +- reflex/compiler/utils.py | 3 ++- reflex/utils/exec.py | 2 +- reflex/utils/frontend_skeleton.py | 15 ++++++++--- reflex/utils/js_runtimes.py | 6 ++--- reflex/utils/rename.py | 2 +- reflex/utils/telemetry.py | 2 +- tests/units/assets/test_assets.py | 21 +++++++++++++++ tests/units/compiler/test_compiler.py | 26 +++++++++++++++++++ tests/units/compiler/test_compiler_utils.py | 22 ++++++++++++++++ tests/units/test_config.py | 20 ++++++++++++++ tests/units/test_prerequisites.py | 21 +++++++++++++++ tests/units/test_telemetry.py | 7 ++++- 18 files changed, 164 insertions(+), 17 deletions(-) create mode 100644 news/+app-assets-and-lockfile-dirs.feature.md create mode 100644 packages/reflex-base/news/+app-assets-and-lockfile-dirs.feature.md diff --git a/docs/getting_started/project-structure.md b/docs/getting_started/project-structure.md index 64319be8fc2..eed744a2c63 100644 --- a/docs/getting_started/project-structure.md +++ b/docs/getting_started/project-structure.md @@ -52,6 +52,16 @@ The `assets` directory is where you can store any static assets you want to be p Reflex copies these files into `.web/public` during compilation. Deleting or renaming an asset removes its previous copy on the next compile, including production exports, while preserving public files generated by plugins. If another process has changed a copied file, Reflex preserves that replacement. Files already deleted before upgrading to a version with asset tracking require a one-time removal of the stale copies or a clean `.web` directory. +`rx.Config(assets_dir=...)` and `rx.Config(lockfile_dir=...)` move the `assets` and `reflex.lock` directories, relative to the project root. This lets two apps that share a root keep their own assets and frontend lockfiles (and their own `.web` with `REFLEX_WEB_WORKDIR`): + +```python +config = rx.Config( + app_name="website", + assets_dir=Path("website/assets"), + lockfile_dir=Path("website/reflex.lock"), +) +``` + For example, if you save an image to `assets/image.png` you can display it from your app like this: ```python diff --git a/news/+app-assets-and-lockfile-dirs.feature.md b/news/+app-assets-and-lockfile-dirs.feature.md new file mode 100644 index 00000000000..78ff9de5843 --- /dev/null +++ b/news/+app-assets-and-lockfile-dirs.feature.md @@ -0,0 +1 @@ +`rx.Config(assets_dir=...)` and `rx.Config(lockfile_dir=...)` move an app's `assets` and `reflex.lock` directories, so apps that share a project root each ship only their own assets and keep their own frontend lockfiles: `rx.Config(app_name="website", assets_dir=Path("website/assets"), lockfile_dir=Path("website/reflex.lock"))`. diff --git a/packages/reflex-base/news/+app-assets-and-lockfile-dirs.feature.md b/packages/reflex-base/news/+app-assets-and-lockfile-dirs.feature.md new file mode 100644 index 00000000000..d4d57131580 --- /dev/null +++ b/packages/reflex-base/news/+app-assets-and-lockfile-dirs.feature.md @@ -0,0 +1 @@ +`Config` has `assets_dir` and `lockfile_dir`, defaulting to `assets` and `reflex.lock` under the app root. diff --git a/packages/reflex-base/src/reflex_base/config.py b/packages/reflex-base/src/reflex_base/config.py index bdd66072f6d..ce6f5e31add 100644 --- a/packages/reflex-base/src/reflex_base/config.py +++ b/packages/reflex-base/src/reflex_base/config.py @@ -178,6 +178,8 @@ class BaseConfig: telemetry_enabled: Telemetry opt-in. bun_path: The bun path. frozen_lockfile: Run frontend package manager in lockfile-enforcing mode (only honored by bun). + lockfile_dir: The directory that keeps the frontend's package.json and lockfiles between builds, to commit with the app. Relative to the app root. Lets apps that share a root keep their own lockfiles. + assets_dir: The directory of the static files copied into the frontend and served from its root, which `rx.asset` and local stylesheets resolve against. Relative to the app root. Lets apps that share a root ship only their own assets. static_page_generation_timeout: Timeout to do a production build of a frontend page. cors_allowed_origins: Comma separated list of origins that are allowed to connect to the backend API. The default allows any origin in dev mode; in prod mode it allows the backend's own origin and, when deploy_url is set, the origin of deploy_url. vite_allowed_hosts: Allowed hosts for the Vite dev server. Set to True to allow all hosts, or provide a list of hostnames (e.g. ["myservice.local"]) to allow specific ones. Prevents 403 errors in Docker, Codespaces, reverse proxies, etc. @@ -239,6 +241,10 @@ class BaseConfig: frozen_lockfile: bool = True + lockfile_dir: Path = Path(constants.Bun.ROOT_LOCKFILE_DIR) + + assets_dir: Path = Path(constants.Dirs.APP_ASSETS) + static_page_generation_timeout: int = 60 cors_allowed_origins: Annotated[ @@ -663,6 +669,8 @@ def _normalize_frontend_compression_formats(self): def _normalize_paths(self): """Ensure frontend and backend paths start with a slash if provided. + Directories given as strings become ``Path`` objects. + Raises: ConfigError: If a frontend_path segment is not a plain directory name. """ @@ -687,6 +695,9 @@ def _normalize_paths(self): if self.backend_path and not self.backend_path.startswith("/"): self.backend_path = f"/{self.backend_path}" + self.lockfile_dir = Path(self.lockfile_dir) + self.assets_dir = Path(self.assets_dir) + def _add_builtin_plugins(self): """Add the builtin plugins to the config.""" for plugin in _PLUGINS_ENABLED_BY_DEFAULT: diff --git a/reflex/assets.py b/reflex/assets.py index 83b3d033477..1eb464f1a41 100644 --- a/reflex/assets.py +++ b/reflex/assets.py @@ -184,7 +184,7 @@ def remove_stale_external_asset_symlinks(): re-creation during import. """ external_dir = ( - Path.cwd() / constants.Dirs.APP_ASSETS / constants.Dirs.EXTERNAL_APP_ASSETS + Path.cwd() / get_config().assets_dir / constants.Dirs.EXTERNAL_APP_ASSETS ) if not external_dir.exists(): return @@ -324,13 +324,12 @@ def asset( FileNotFoundError: If the file does not exist. ValueError: If subfolder is provided for local assets. """ - assets = constants.Dirs.APP_ASSETS + assets = Path.cwd() / get_config().assets_dir backend_only = EnvironmentVariables.REFLEX_BACKEND_ONLY.get() # Local asset handling if not shared: - cwd = Path.cwd() - src_file_local = cwd / assets / path + src_file_local = assets / path if subfolder is not None: msg = "Subfolder is not supported for local assets." raise ValueError(msg) @@ -361,7 +360,7 @@ def asset( # Symlink the asset to the app's external assets directory if running frontend. if not backend_only: # Create the asset folder in the currently compiling app. - asset_folder = Path.cwd() / assets / external / subfolder + asset_folder = assets / external / subfolder asset_folder.mkdir(parents=True, exist_ok=True) _link_shared_asset(asset_folder / path, src_file_shared) diff --git a/reflex/compiler/compiler.py b/reflex/compiler/compiler.py index 83d72e5dd12..028e1b4d454 100644 --- a/reflex/compiler/compiler.py +++ b/reflex/compiler/compiler.py @@ -401,7 +401,7 @@ def _compile_root_stylesheet( ]) failed_to_import_sass = False - assets_app_path = Path.cwd() / constants.Dirs.APP_ASSETS + assets_app_path = Path.cwd() / get_config().assets_dir stylesheets_files: list[Path] = [] stylesheets_urls = [] diff --git a/reflex/compiler/utils.py b/reflex/compiler/utils.py index e0b490938b3..d7052518d28 100644 --- a/reflex/compiler/utils.py +++ b/reflex/compiler/utils.py @@ -31,6 +31,7 @@ MemoFunctionDefinition, MemoParamKind, ) +from reflex_base.config import get_config from reflex_base.constants.state import FIELD_MARKER from reflex_base.registry import RegistrationContext from reflex_base.style import Style @@ -1276,7 +1277,7 @@ def _sync_app_assets() -> None: Raises: OSError: If the source cannot be scanned or the output cannot be updated. """ - assets = Path(constants.Dirs.APP_ASSETS) + assets = get_config().assets_dir web_dir = get_web_dir() public = web_dir / constants.Dirs.PUBLIC manifest_path = web_dir / _ASSET_MANIFEST_FILENAME diff --git a/reflex/utils/exec.py b/reflex/utils/exec.py index 6a5603b234d..642fd361bf9 100644 --- a/reflex/utils/exec.py +++ b/reflex/utils/exec.py @@ -720,7 +720,7 @@ def is_excluded_by_default(path: Path) -> bool: return path.name in ( ".gitignore", "uploaded_files", - constants.Bun.ROOT_LOCKFILE_DIR, + get_config().lockfile_dir.name, ) reload_paths = ( diff --git a/reflex/utils/frontend_skeleton.py b/reflex/utils/frontend_skeleton.py index 0c18ffbb3e6..bcdc1bec173 100644 --- a/reflex/utils/frontend_skeleton.py +++ b/reflex/utils/frontend_skeleton.py @@ -277,16 +277,25 @@ def initialize_requirements_txt( NO_PRUNE_LOCKFILE_NAMES: tuple[str, ...] = (constants.PackageJson.PATH,) +def get_root_lockfile_dir() -> Path: + """Get the directory the frontend lockfiles persist in, ``reflex.lock`` by default. + + Returns: + The configured ``lockfile_dir`` under the app root. + """ + return Path.cwd() / get_config().lockfile_dir + + def get_root_lockfile_path(filename: str) -> Path: - """Get a persisted lockfile path under the app root's reflex.lock dir. + """Get a persisted lockfile path under the app's lockfile directory. Args: filename: The lockfile basename (e.g. ``bun.lock``, ``package-lock.json``). Returns: - The lockfile path inside ``/reflex.lock/``. + The lockfile path inside the configured ``lockfile_dir``. """ - return Path.cwd() / constants.Bun.ROOT_LOCKFILE_DIR / filename + return get_root_lockfile_dir() / filename def get_web_lockfile_path(filename: str) -> Path: diff --git a/reflex/utils/js_runtimes.py b/reflex/utils/js_runtimes.py index 535d6ff57ad..6602a04ef11 100644 --- a/reflex/utils/js_runtimes.py +++ b/reflex/utils/js_runtimes.py @@ -106,7 +106,7 @@ def _persisted_lockfile_implies_npm() -> bool: Returns: Whether the persisted state implies npm. """ - root_dir = Path.cwd() / constants.Bun.ROOT_LOCKFILE_DIR + root_dir = frontend_skeleton.get_root_lockfile_dir() return (root_dir / constants.Node.LOCKFILE_PATH).exists() and not ( root_dir / constants.Bun.LOCKFILE_PATH ).exists() @@ -144,7 +144,7 @@ def prefer_npm_over_bun() -> bool: if explicit is not None: return explicit if _persisted_lockfile_implies_npm(): - _log_implicit_npm_notice(Path.cwd() / constants.Bun.ROOT_LOCKFILE_DIR) + _log_implicit_npm_notice(frontend_skeleton.get_root_lockfile_dir()) return True return False @@ -553,7 +553,7 @@ def _run_initial_install( return if any("lockfile had changes, but lockfile is frozen" in line for line in logs): - root_dir = Path.cwd() / constants.Bun.ROOT_LOCKFILE_DIR + root_dir = frontend_skeleton.get_root_lockfile_dir() logger.error( "The persisted lockfile is out of sync with the recovered " f"package.json. Delete the [bold]{escape(str(root_dir))}[/bold] directory " diff --git a/reflex/utils/rename.py b/reflex/utils/rename.py index f88b7d28ad2..e463fd22450 100644 --- a/reflex/utils/rename.py +++ b/reflex/utils/rename.py @@ -85,7 +85,7 @@ def rename_app(new_app_name: str, loglevel: constants.LogLevel): Path.cwd(), config.app_name, new_app_name, - exclude_dirs=[constants.Dirs.WEB, constants.Dirs.APP_ASSETS], + exclude_dirs=[constants.Dirs.WEB, config.assets_dir], ) rename_path_up_tree(module_path, config.app_name, new_app_name) diff --git a/reflex/utils/telemetry.py b/reflex/utils/telemetry.py index e669935681c..8669029cc70 100644 --- a/reflex/utils/telemetry.py +++ b/reflex/utils/telemetry.py @@ -210,7 +210,7 @@ def get_init_environment() -> dict[str, bool]: "has_pyproject_toml": Path(constants.PyprojectToml.FILE).exists(), "has_requirements_txt": Path(constants.RequirementsTxt.FILE).exists(), "has_uv_lock": Path(constants.UvLock.FILE).exists(), - "has_reflex_lock": Path(constants.Bun.ROOT_LOCKFILE_DIR).is_dir(), + "has_reflex_lock": get_config().lockfile_dir.is_dir(), } diff --git a/tests/units/assets/test_assets.py b/tests/units/assets/test_assets.py index 27fc1e5003f..a0d9f41e16f 100644 --- a/tests/units/assets/test_assets.py +++ b/tests/units/assets/test_assets.py @@ -496,6 +496,27 @@ def test_local_asset(custom_script_in_asset_dir: Path) -> None: assert asset == f"/custom_script.js?v={_asset_hash(custom_script_in_asset_dir)}" +def test_local_asset_from_the_configured_directory( + mock_asset_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """A local asset resolves against the configured assets directory. + + Args: + mock_asset_path: The app root the test runs in. + monkeypatch: A pytest fixture for patching. + """ + site_assets = mock_asset_path / "site" / "assets" + site_assets.mkdir(parents=True) + script = site_assets / "site_script.js" + script.write_text("site") + config = rx.Config(app_name="site", assets_dir=Path("site/assets")) + monkeypatch.setattr(assets_module, "get_config", lambda: config) + + asset = rx.asset("site_script.js", shared=False) + + assert asset == f"/site_script.js?v={_asset_hash(script)}" + + def test_local_asset_hash_changes_with_content( custom_script_in_asset_dir: Path, ) -> None: diff --git a/tests/units/compiler/test_compiler.py b/tests/units/compiler/test_compiler.py index 0f42e0ea870..282e79cfd8c 100644 --- a/tests/units/compiler/test_compiler.py +++ b/tests/units/compiler/test_compiler.py @@ -328,6 +328,30 @@ def test_compile_stylesheets(tmp_path: Path, mocker: MockerFixture): ).read_text() +def test_compile_stylesheets_from_the_configured_assets_dir( + tmp_path: Path, mocker: MockerFixture +): + """Local stylesheets resolve against the configured assets directory. + + Args: + tmp_path: The test directory. + mocker: Pytest mocker object. + """ + site_assets = tmp_path / "site" / "assets" + site_assets.mkdir(parents=True) + (site_assets / "site.css").write_text(".site { color: red; }") + web_dir = tmp_path / constants.Dirs.WEB + mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=tmp_path) + mocker.patch("reflex.compiler.compiler.get_web_dir", return_value=web_dir) + config = rx.Config(app_name="site", assets_dir=Path("site/assets")) + mocker.patch("reflex.compiler.compiler.get_config", return_value=config) + + _, code = compiler.compile_root_stylesheet(["/site.css"], reset_style=False) + + assert code == "@layer __reflex_base;\n@import url('./site.css');" + assert (web_dir / "styles" / "site.css").read_text() == ".site { color: red; }" + + def test_compile_stylesheets_scss_sass(tmp_path: Path, mocker: MockerFixture): if importlib.util.find_spec("sass") is None: pytest.skip( @@ -484,6 +508,7 @@ def test_compile_stylesheets_exclude_tailwind(tmp_path, mocker: MockerFixture): mocker.patch.object(mock, "tailwind", None) mocker.patch.object(mock, "plugins", []) + mocker.patch.object(mock, "assets_dir", Path("assets")) mocker.patch("reflex.compiler.compiler.get_config", return_value=mock) (assets_dir / "style.css").touch() @@ -551,6 +576,7 @@ def test_compile_stylesheets_includes_radix_plugin( config = mocker.Mock() config.plugins = [rx.plugins.RadixThemesPlugin()] + config.assets_dir = Path("assets") mocker.patch("reflex.compiler.compiler.get_config", return_value=config) mocker.patch("reflex.compiler.compiler.Path.cwd", return_value=project) mocker.patch( diff --git a/tests/units/compiler/test_compiler_utils.py b/tests/units/compiler/test_compiler_utils.py index 5e2b83b4d17..8ec1ec29cb9 100644 --- a/tests/units/compiler/test_compiler_utils.py +++ b/tests/units/compiler/test_compiler_utils.py @@ -78,6 +78,28 @@ def test_sync_app_assets_renames_and_prunes_empty_directories(asset_project): assert not (public / utils._ASSET_MANIFEST_FILENAME).exists() +def test_sync_app_assets_copies_the_configured_directory( + asset_project, monkeypatch: pytest.MonkeyPatch +): + """An app whose config names another assets directory ships only that one. + + Args: + asset_project: The source and destination directories. + monkeypatch: Fixture for configuring the app. + """ + assets, public = asset_project + (assets / "default.txt").write_text("default") + site_assets = assets.parent / "site" / "assets" + site_assets.mkdir(parents=True) + (site_assets / "site.txt").write_text("site") + config = rx.Config(app_name="site", assets_dir=Path("site/assets")) + monkeypatch.setattr(utils, "get_config", lambda: config) + + utils._sync_app_assets() + + assert sorted(path.name for path in public.iterdir()) == ["site.txt"] + + def test_sync_app_assets_preserves_incremental_copies(asset_project): """Unchanged assets and their manifest keep timestamps across compiles. diff --git a/tests/units/test_config.py b/tests/units/test_config.py index 8eabd94dd1b..2f5197f4139 100644 --- a/tests/units/test_config.py +++ b/tests/units/test_config.py @@ -67,6 +67,26 @@ def test_frozen_lockfile_default(base_config_values): assert config.frozen_lockfile is True +def test_app_directories(base_config_values, monkeypatch: pytest.MonkeyPatch): + """The assets and lockfile directories default to the app root's and take strings. + + Args: + base_config_values: Config values. + monkeypatch: Fixture for setting environment variables. + """ + config = rx.Config(**base_config_values) + assert (config.assets_dir, config.lockfile_dir) == ( + Path("assets"), + Path("reflex.lock"), + ) + + config = rx.Config(**base_config_values, assets_dir="site/assets") # pyright: ignore[reportArgumentType] + assert config.assets_dir == Path("site/assets") + + monkeypatch.setenv("REFLEX_LOCKFILE_DIR", "site/reflex.lock") + assert rx.Config(**base_config_values).lockfile_dir == Path("site/reflex.lock") + + def test_trusted_proxy_hops_defaults_to_zero(base_config_values): """Do not trust client-controlled forwarded headers by default.""" assert rx.Config(**base_config_values).trusted_proxy_hops == 0 diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index 607b03e5805..ae105428fae 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -665,6 +665,27 @@ def test_sync_root_lockfiles_to_web_keeps_web_package_json(tmp_path, monkeypatch assert not web_lock.exists() +def test_lockfiles_persist_in_the_configured_directory(tmp_path, monkeypatch): + """An app whose config names another lockfile directory keeps its lockfiles there.""" + web_dir = tmp_path / constants.Dirs.WEB + web_dir.mkdir() + _patch_web_dir(monkeypatch, web_dir) + config = Config(app_name="site", lockfile_dir=Path("site/reflex.lock")) + monkeypatch.setattr(frontend_skeleton, "get_config", lambda: config) + (web_dir / constants.Bun.LOCKFILE_PATH).write_text("site-lock") + + with chdir(tmp_path): + assert frontend_skeleton.get_root_lockfile_path( + constants.Bun.LOCKFILE_PATH + ) == (tmp_path / "site" / "reflex.lock" / constants.Bun.LOCKFILE_PATH) + frontend_skeleton.sync_web_lockfiles_to_root() + + assert ( + tmp_path / "site" / "reflex.lock" / constants.Bun.LOCKFILE_PATH + ).read_text() == ("site-lock") + assert not (tmp_path / constants.Bun.ROOT_LOCKFILE_DIR).exists() + + def test_sync_root_lockfiles_to_web_processes_package_json(tmp_path, monkeypatch): """Persisted package.json is rendered into .web instead of byte-copied.""" web_dir = tmp_path / constants.Dirs.WEB diff --git a/tests/units/test_telemetry.py b/tests/units/test_telemetry.py index db2cc600e3a..aa089d0eb34 100644 --- a/tests/units/test_telemetry.py +++ b/tests/units/test_telemetry.py @@ -7,11 +7,13 @@ import time import uuid import warnings +from pathlib import Path from types import SimpleNamespace import pytest from packaging.version import parse as parse_python_version from pytest_mock import MockerFixture +from reflex_base import constants from reflex_base.config import get_config from reflex_base.registry import RegistrationContext @@ -356,7 +358,10 @@ def patch_telemetry_config(mocker: MockerFixture): def patch(*, enabled: bool) -> None: mocker.patch( "reflex.utils.telemetry.get_config", - return_value=SimpleNamespace(telemetry_enabled=enabled), + return_value=SimpleNamespace( + telemetry_enabled=enabled, + lockfile_dir=Path(constants.Bun.ROOT_LOCKFILE_DIR), + ), ) return patch From 536867a7a9fa60850536621b8baebbefa59eca14 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:52:04 +0100 Subject: [PATCH 2/8] fix: keep lockfile writes in nested or foreign lockfile dirs from restarting the dev backend --- reflex/utils/exec.py | 10 +++-- tests/units/utils/test_exec.py | 82 ++++++++++++++++++++++++++++++++++ 2 files changed, 88 insertions(+), 4 deletions(-) diff --git a/reflex/utils/exec.py b/reflex/utils/exec.py index 642fd361bf9..b6f14db2bb0 100644 --- a/reflex/utils/exec.py +++ b/reflex/utils/exec.py @@ -709,6 +709,8 @@ def get_reload_paths() -> Sequence[Path]: if path.exists() ) + lockfile_dir = Path.cwd() / config.lockfile_dir + def is_excluded_by_default(path: Path) -> bool: if path.is_dir(): if path.name.startswith("."): @@ -717,10 +719,8 @@ def is_excluded_by_default(path: Path) -> bool: if path.name.startswith("__"): # ignore things like __pycache__ return True - return path.name in ( - ".gitignore", - "uploaded_files", - get_config().lockfile_dir.name, + return path.name in (".gitignore", "uploaded_files") or ( + path.absolute() == lockfile_dir ) reload_paths = ( @@ -771,6 +771,8 @@ def run_uvicorn_backend(host: str, port: int, loglevel: LogLevel): HOTRELOAD_IGNORE_EXTENSIONS = ( + # Watched lockfile dirs: nested ones and those of other apps sharing the root. + "lock", "txt", "toml", "sqlite", diff --git a/tests/units/utils/test_exec.py b/tests/units/utils/test_exec.py index 4eeff83f785..7521ef77439 100644 --- a/tests/units/utils/test_exec.py +++ b/tests/units/utils/test_exec.py @@ -1507,6 +1507,88 @@ def test_get_reload_paths_ignores_missing_exclude_path( assert sorted(exec_utils.get_reload_paths()) == [cwd / "pkg", cwd / "rxconfig.py"] +@pytest.mark.parametrize( + ("lockfile_dir", "expected"), + [ + ("reflex.lock", ["other.lock", "site", "site.lock"]), + ("site.lock", ["other.lock", "reflex.lock", "site"]), + ("site/reflex.lock", ["other.lock", "reflex.lock", "site", "site.lock"]), + ], +) +def test_get_reload_paths_skips_the_configured_lockfile_dir( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + mocker: MockerFixture, + lockfile_dir: str, + expected: list[str], +): + """Only the app's own lockfile directory is skipped, matched by its path. + + Args: + tmp_path: Temporary app root. + monkeypatch: Pytest monkeypatch fixture. + mocker: Pytest mocker fixture. + lockfile_dir: The configured lockfile directory. + expected: The top-level entries expected to be watched. + """ + from reflex_base.config import Config + + for name in ("reflex.lock", "site.lock", "other.lock", "site/reflex.lock"): + (tmp_path / name).mkdir(parents=True) + monkeypatch.chdir(tmp_path) + mocker.patch.object(exec_utils, "get_module_path", return_value=None) + mocker.patch.object( + exec_utils, + "get_config", + return_value=Config(app_name="site", lockfile_dir=Path(lockfile_dir)), + ) + for var in ( + environment.REFLEX_HOT_RELOAD_OVERRIDE_PATHS, + environment.REFLEX_HOT_RELOAD_INCLUDE_PATHS, + environment.REFLEX_HOT_RELOAD_EXCLUDE_PATHS, + ): + monkeypatch.delenv(var.name, raising=False) + + assert sorted(exec_utils.get_reload_paths()) == [ + Path.cwd() / name for name in expected + ] + + +@pytest.mark.parametrize( + ("relative_path", "reloads"), + [ + ("site/reflex.lock/bun.lock", False), + ("site/reflex.lock/package.json", False), + ("site/reflex.lock/package-lock.json", False), + ("other/reflex.lock", False), + ("site/site.py", True), + ], +) +def test_lockfile_writes_do_not_trigger_hot_reload( + tmp_path: Path, relative_path: str, reloads: bool +): + """Lockfile writes anywhere in the watched tree never restart the backend. + + A lockfile directory deeper than the reload root's direct children, or + another app's sharing the root, is still watched. + + Args: + tmp_path: Temporary app root. + relative_path: The changed path. + reloads: Whether the change should trigger a reload. + """ + from watchfiles import Change, DefaultFilter + + watch_filter = DefaultFilter( + ignore_entity_patterns=( + *DefaultFilter.ignore_entity_patterns, + *exec_utils.HOTRELOAD_IGNORE_PATTERNS, + ) + ) + + assert watch_filter(Change.modified, str(tmp_path / relative_path)) is reloads + + @pytest.mark.usefixtures("windows_text_io") def test_get_package_json_and_hash_reads_utf8(tmp_path: Path): """package.json is read as UTF-8 whatever the locale encoding. From 8dcb5fe62455138ec3f872176b9979be48a3da26 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:52:08 +0100 Subject: [PATCH 3/8] fix: update configured dirs that reflex rename moves with the app --- reflex/utils/rename.py | 97 ++++++++++++++++++++++++++++--- tests/units/test_prerequisites.py | 92 +++++++++++++++++++++++++++++ 2 files changed, 181 insertions(+), 8 deletions(-) diff --git a/reflex/utils/rename.py b/reflex/utils/rename.py index e463fd22450..3fbb8ec0a3a 100644 --- a/reflex/utils/rename.py +++ b/reflex/utils/rename.py @@ -7,7 +7,7 @@ from pathlib import Path from reflex_base import constants -from reflex_base.config import get_config +from reflex_base.config import Config, get_config from reflex_base.utils import console, log from rich.markup import escape @@ -15,6 +15,8 @@ logger = logging.getLogger(__name__) +_CONFIG_DIR_FIELDS = ("assets_dir", "lockfile_dir") + def rename_path_up_tree(full_path: str | Path, old_name: str, new_name: str) -> Path: """Rename all instances of `old_name` in the path (file and directories) to `new_name`. @@ -81,6 +83,7 @@ def rename_app(new_app_name: str, loglevel: constants.LogLevel): raise SystemExit(1) logger.info(f"Renaming app directory to {new_app_name}.") + moved_dirs = _config_dirs_moved_by_rename(config, module_path, new_app_name) process_directory( Path.cwd(), config.app_name, @@ -89,6 +92,7 @@ def rename_app(new_app_name: str, loglevel: constants.LogLevel): ) rename_path_up_tree(module_path, config.app_name, new_app_name) + _update_moved_config_dirs(moved_dirs) logger.log( log.SUCCESS, @@ -106,13 +110,7 @@ def rename_imports_and_app_name(file_path: str | Path, old_name: str, new_name: new_name: The new name to use. """ file_path = Path(file_path) - if file_path.suffix == constants.Ext.PY: - with file_path.open("rb") as source: - encoding = tokenize.detect_encoding(source.readline)[0] - else: - encoding = "utf-8" - with file_path.open("r", encoding=encoding, newline="") as source: - content = source.read() + content, encoding = _read_source(file_path) # Replace `from old_name.` or `from old_name` with `from new_name` content = re.sub( @@ -145,6 +143,89 @@ def rename_imports_and_app_name(file_path: str | Path, old_name: str, new_name: file_path.write_text(content, encoding=encoding, newline="") +def _config_dirs_moved_by_rename( + config: Config, module_path: Path, new_app_name: str +) -> dict[str, tuple[Path, Path]]: + """Find the configured directories inside the app directories a rename moves. + + Args: + config: The app config. + module_path: The path of the app module. + new_app_name: The new name for the app. + + Returns: + The old and new path, relative to the app root, of each moved directory by config field. + """ + root = Path.cwd() + if not module_path.is_relative_to(root): + return {} + module_dir_parts = module_path.parent.relative_to(root).parts + moved = {} + for field in _CONFIG_DIR_FIELDS: + configured = root / getattr(config, field) + if not configured.is_relative_to(root): + continue + old = configured.relative_to(root) + new_parts = list(old.parts) + for i, (part, module_dir_part) in enumerate( + zip(old.parts, module_dir_parts, strict=False) + ): + if part != module_dir_part: + break + if part == config.app_name: + new_parts[i] = new_app_name + new = Path(*new_parts) + if new != old: + moved[field] = (old, new) + return moved + + +def _update_moved_config_dirs(moved_dirs: dict[str, tuple[Path, Path]]): + """Point configured directories that moved with the app at their new location. + + Only string literals in rxconfig.py are rewritten, any other source is left to the user. + + Args: + moved_dirs: The old and new path of each moved directory by config field. + """ + if not moved_dirs: + return + config_file = constants.Config.FILE + content, encoding = _read_source(config_file) + for field, (old, new) in moved_dirs.items(): + literals = [ + (f"{quote}{old.as_posix()}{quote}", f"{quote}{new.as_posix()}{quote}") + for quote in "\"'" + ] + if not any(old_literal in content for old_literal, _ in literals): + logger.warning( + f"{field} {old.as_posix()} moved to {new.as_posix()} with the app " + "directory. Update it in your config." + ) + continue + for old_literal, new_literal in literals: + content = content.replace(old_literal, new_literal) + config_file.write_text(content, encoding=encoding, newline="") + + +def _read_source(file_path: Path) -> tuple[str, str]: + """Read a file in its declared encoding, keeping its line endings. + + Args: + file_path: The file to read. + + Returns: + The content and the encoding of the file. + """ + if file_path.suffix == constants.Ext.PY: + with file_path.open("rb") as source: + encoding = tokenize.detect_encoding(source.readline)[0] + else: + encoding = "utf-8" + with file_path.open("r", encoding=encoding, newline="") as source: + return source.read(), encoding + + def process_directory( directory: str | Path, old_name: str, diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index 4cc148aca51..56bb883c69b 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -2679,6 +2679,98 @@ def index(): ) +def _run_rename(app_root: Path, config_args: str) -> tuple[str, str]: + """Rename the app ``foo`` in ``app_root`` to ``bar``. + + Args: + app_root: The app root, containing the ``foo`` app package. + config_args: Extra arguments of the ``rx.Config`` call. + + Returns: + The renamed app's rxconfig.py and the command output. + """ + (app_root / "foo").mkdir() + (app_root / "foo" / "__init__.py").touch() + (app_root / "foo" / "foo.py").write_text("import reflex as rx\n") + config_file = app_root / "rxconfig.py" + config_file.write_text( + "from pathlib import Path\n\nimport reflex as rx\n\n" + f'config = rx.Config(app_name="foo", {config_args})\n' + ) + try: + with chdir(app_root): + result = runner.invoke(cli, ["rename", "bar"]) + finally: + log._reset() + assert result.exit_code == 0, result.output + return config_file.read_text(), result.output + + +@pytest.mark.usefixtures("clean_registration_context") +def test_cli_rename_moves_configured_dirs_inside_the_app( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """Directories configured inside the app package follow it to its new name. + + Args: + tmp_path: The app root. + monkeypatch: The pytest monkeypatch fixture. + """ + monkeypatch.delenv(log._MANAGED_ENV_VAR, raising=False) + + config, _ = _run_rename( + tmp_path, + "assets_dir=Path('foo/assets'), lockfile_dir=\"foo/reflex.lock\"", + ) + + assert config.endswith( + "config = rx.Config(app_name=\"bar\", assets_dir=Path('bar/assets'), " + 'lockfile_dir="bar/reflex.lock")\n' + ) + + +@pytest.mark.usefixtures("clean_registration_context") +def test_cli_rename_keeps_configured_dirs_outside_the_app( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """Directories configured next to the app package stay where they are. + + Args: + tmp_path: The app root. + monkeypatch: The pytest monkeypatch fixture. + """ + monkeypatch.delenv(log._MANAGED_ENV_VAR, raising=False) + + config, _ = _run_rename( + tmp_path, 'assets_dir=Path("foo_assets"), lockfile_dir="foo.lock"' + ) + + assert config.endswith( + 'config = rx.Config(app_name="bar", assets_dir=Path("foo_assets"), ' + 'lockfile_dir="foo.lock")\n' + ) + + +@pytest.mark.usefixtures("clean_registration_context") +def test_cli_rename_warns_about_a_moved_dir_it_cannot_update( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +): + """A moved directory that is not a literal in rxconfig.py is left to the user. + + Args: + tmp_path: The app root. + monkeypatch: The pytest monkeypatch fixture. + """ + monkeypatch.delenv(log._MANAGED_ENV_VAR, raising=False) + + config, output = _run_rename(tmp_path, 'assets_dir=Path("foo") / "assets"') + + assert config.endswith( + 'config = rx.Config(app_name="bar", assets_dir=Path("foo") / "assets")\n' + ) + assert "assets_dir foo/assets moved to bar/assets" in " ".join(output.split()) + + def test_has_uuid_distinct_id_semantics_absent( tmp_path, monkeypatch: pytest.MonkeyPatch ): From 83df04ec3a1403579fdfb20a3b0528737995024f Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 09:52:13 +0100 Subject: [PATCH 4/8] fix: gitignore shared asset links in the configured assets dir on init --- reflex/utils/frontend_skeleton.py | 28 +++++++++++++++++++++++-- tests/units/utils/test_utils.py | 34 +++++++++++++++++++++++++++++++ 2 files changed, 60 insertions(+), 2 deletions(-) diff --git a/reflex/utils/frontend_skeleton.py b/reflex/utils/frontend_skeleton.py index ea8e453a56e..5cf4334410b 100644 --- a/reflex/utils/frontend_skeleton.py +++ b/reflex/utils/frontend_skeleton.py @@ -2,6 +2,7 @@ import json import logging +import os import uuid from pathlib import Path from typing import Literal @@ -20,16 +21,39 @@ logger = logging.getLogger(__name__) +def _external_assets_gitignore_entry() -> str | None: + """Get the gitignore entry for the shared asset links in the configured assets dir. + + Returns: + The entry relative to the app root, or None if the assets dir lies outside it. + """ + root = Path.cwd() + external_dir = Path( + os.path.normpath( + root / get_config().assets_dir / constants.Dirs.EXTERNAL_APP_ASSETS + ) + ) + if not external_dir.is_relative_to(root): + return None + return f"{external_dir.relative_to(root).as_posix()}/" + + def initialize_gitignore( gitignore_file: Path = constants.GitIgnore.FILE, - files_to_ignore: set[str] | list[str] = constants.GitIgnore.DEFAULTS, + files_to_ignore: set[str] | list[str] | None = None, ): """Initialize the template .gitignore file. Args: gitignore_file: The .gitignore file to create. - files_to_ignore: The files to add to the .gitignore file. + files_to_ignore: The files to add to the .gitignore file, by default Reflex's own and the shared asset links of the configured assets dir. """ + if files_to_ignore is None: + external_assets = _external_assets_gitignore_entry() + files_to_ignore = constants.GitIgnore.DEFAULTS | ( + {external_assets} if external_assets else set() + ) + # Combine with the current ignored files. current_ignore: list[str] = [] if gitignore_file.exists(): diff --git a/tests/units/utils/test_utils.py b/tests/units/utils/test_utils.py index 0d0698f6908..05335a01cd3 100644 --- a/tests/units/utils/test_utils.py +++ b/tests/units/utils/test_utils.py @@ -380,6 +380,40 @@ def test_initialize_non_existent_gitignore( assert set(file_content) - expected == set() +@pytest.mark.parametrize( + ("assets_dir", "entry"), + [ + ("assets", None), + ("site/assets", "site/assets/external/"), + ("../shared/assets", None), + ], +) +def test_initialize_gitignore_ignores_external_links_of_the_configured_assets_dir( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + assets_dir: str, + entry: str | None, +): + """The links of shared assets are ignored in the configured assets directory too. + + Args: + tmp_path: The app root. + monkeypatch: The pytest monkeypatch fixture. + assets_dir: The configured assets directory. + entry: The entry expected besides the defaults. + """ + from reflex_base.config import Config + + monkeypatch.chdir(tmp_path) + config = Config(app_name="site", assets_dir=Path(assets_dir)) + monkeypatch.setattr(frontend_skeleton, "get_config", lambda: config) + + frontend_skeleton.initialize_gitignore() + + lines = set((tmp_path / ".gitignore").read_text().splitlines()) + assert lines == constants.GitIgnore.DEFAULTS | ({entry} if entry else set()) + + def test_initialize_agents_md_fetches_canonical(tmp_path, mocker): """Test that AGENTS.md is fetched and a CLAUDE.md bridge is created when absent.""" agents_file = tmp_path / "AGENTS.md" From 30c230d8f7ded4aaddf6c94ca0d49da4b76e1bee Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:14:45 +0100 Subject: [PATCH 5/8] fix: rewrite only the moved directory settings and resolve excluded dirs on reflex rename --- reflex/utils/rename.py | 41 ++++++--- tests/units/test_prerequisites.py | 141 ++++++++++++++++-------------- 2 files changed, 105 insertions(+), 77 deletions(-) diff --git a/reflex/utils/rename.py b/reflex/utils/rename.py index 3fbb8ec0a3a..e11ad5578e0 100644 --- a/reflex/utils/rename.py +++ b/reflex/utils/rename.py @@ -183,7 +183,7 @@ def _config_dirs_moved_by_rename( def _update_moved_config_dirs(moved_dirs: dict[str, tuple[Path, Path]]): """Point configured directories that moved with the app at their new location. - Only string literals in rxconfig.py are rewritten, any other source is left to the user. + Only a string literal passed as the setting in rxconfig.py is rewritten, any other source is left to the user. Args: moved_dirs: The old and new path of each moved directory by config field. @@ -193,21 +193,40 @@ def _update_moved_config_dirs(moved_dirs: dict[str, tuple[Path, Path]]): config_file = constants.Config.FILE content, encoding = _read_source(config_file) for field, (old, new) in moved_dirs.items(): - literals = [ - (f"{quote}{old.as_posix()}{quote}", f"{quote}{new.as_posix()}{quote}") - for quote in "\"'" - ] - if not any(old_literal in content for old_literal, _ in literals): + content, count = _replace_config_dir_literal(content, field, old, new) + if not count: logger.warning( f"{field} {old.as_posix()} moved to {new.as_posix()} with the app " "directory. Update it in your config." ) - continue - for old_literal, new_literal in literals: - content = content.replace(old_literal, new_literal) config_file.write_text(content, encoding=encoding, newline="") +def _replace_config_dir_literal( + content: str, field: str, old: Path, new: Path +) -> tuple[str, int]: + """Replace the string literal passed as a directory setting, bare or in ``Path()``. + + Args: + content: The config source. + field: The name of the setting. + old: The path to replace. + new: The replacement path. + + Returns: + The updated source and the number of replacements. + """ + pattern = re.compile( + rf"(\b{field}\s*=\s*(?:(?:pathlib\.)?Path\(\s*)?)([\"']){re.escape(old.as_posix())}\2" + ) + return pattern.subn( + lambda match: ( + f"{match.group(1)}{match.group(2)}{new.as_posix()}{match.group(2)}" + ), + content, + ) + + def _read_source(file_path: Path) -> tuple[str, str]: """Read a file in its declared encoding, keeping its line endings. @@ -250,7 +269,9 @@ def process_directory( extensions_set = {ext.lstrip(".") for ext in extensions} directory = Path(directory) - root_exclude_dirs = {directory / exclude_dir for exclude_dir in exclude_dirs} + root_exclude_dirs = { + (directory / exclude_dir).resolve() for exclude_dir in exclude_dirs + } files = ( p.resolve() diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index 56bb883c69b..3815661cd0e 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -33,7 +33,7 @@ _compile_vite_config, _update_react_router_config, ) -from reflex.utils.rename import rename_imports_and_app_name +from reflex.utils.rename import process_directory, rename_imports_and_app_name from reflex.utils.telemetry import CpuInfo, get_cpu_info runner = CliRunner() @@ -2679,96 +2679,103 @@ def index(): ) -def _run_rename(app_root: Path, config_args: str) -> tuple[str, str]: - """Rename the app ``foo`` in ``app_root`` to ``bar``. +_RENAME_CONFIG = """from pathlib import Path - Args: - app_root: The app root, containing the ``foo`` app package. - config_args: Extra arguments of the ``rx.Config`` call. +import reflex as rx - Returns: - The renamed app's rxconfig.py and the command output. - """ - (app_root / "foo").mkdir() - (app_root / "foo" / "__init__.py").touch() - (app_root / "foo" / "foo.py").write_text("import reflex as rx\n") - config_file = app_root / "rxconfig.py" - config_file.write_text( - "from pathlib import Path\n\nimport reflex as rx\n\n" - f'config = rx.Config(app_name="foo", {config_args})\n' - ) - try: - with chdir(app_root): - result = runner.invoke(cli, ["rename", "bar"]) - finally: - log._reset() - assert result.exit_code == 0, result.output - return config_file.read_text(), result.output +config = rx.Config( + app_name="{app_name}", + disable_plugins=[rx.plugins.SitemapPlugin], + {args} +) +""" @pytest.mark.usefixtures("clean_registration_context") -def test_cli_rename_moves_configured_dirs_inside_the_app( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch +@pytest.mark.parametrize( + ("config_args", "renamed_config_args", "warning"), + [ + pytest.param( + "assets_dir=Path('foo/assets'), lockfile_dir=\"foo/reflex.lock\"", + "assets_dir=Path('bar/assets'), lockfile_dir=\"bar/reflex.lock\"", + "", + id="literals-inside-the-app", + ), + pytest.param( + 'assets_dir="foo/assets", frontend_path="foo/assets"', + 'assets_dir="bar/assets", frontend_path="foo/assets"', + "", + id="other-settings-untouched", + ), + pytest.param( + 'assets_dir=Path("foo_assets"), lockfile_dir="foo.lock"', + 'assets_dir=Path("foo_assets"), lockfile_dir="foo.lock"', + "", + id="outside-the-app", + ), + pytest.param( + 'assets_dir=Path("foo") / "assets"', + 'assets_dir=Path("foo") / "assets"', + "Warning: assets_dir foo/assets moved to bar/assets with the app " + "directory. Update it in your config. ", + id="not-a-literal", + ), + ], +) +def test_cli_rename_updates_configured_dirs_it_moves( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + config_args: str, + renamed_config_args: str, + warning: str, ): """Directories configured inside the app package follow it to its new name. Args: tmp_path: The app root. monkeypatch: The pytest monkeypatch fixture. + config_args: The directory settings before the rename. + renamed_config_args: The directory settings expected after the rename. + warning: The warning expected for a setting the rename cannot update. """ monkeypatch.delenv(log._MANAGED_ENV_VAR, raising=False) + (tmp_path / "foo").mkdir() + (tmp_path / "foo" / "__init__.py").touch() + (tmp_path / "foo" / "foo.py").write_text("import reflex as rx\n") + config_file = tmp_path / "rxconfig.py" + config_file.write_text(_RENAME_CONFIG.format(app_name="foo", args=config_args)) - config, _ = _run_rename( - tmp_path, - "assets_dir=Path('foo/assets'), lockfile_dir=\"foo/reflex.lock\"", - ) - - assert config.endswith( - "config = rx.Config(app_name=\"bar\", assets_dir=Path('bar/assets'), " - 'lockfile_dir="bar/reflex.lock")\n' - ) - - -@pytest.mark.usefixtures("clean_registration_context") -def test_cli_rename_keeps_configured_dirs_outside_the_app( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -): - """Directories configured next to the app package stay where they are. - - Args: - tmp_path: The app root. - monkeypatch: The pytest monkeypatch fixture. - """ - monkeypatch.delenv(log._MANAGED_ENV_VAR, raising=False) + try: + with chdir(tmp_path): + result = runner.invoke(cli, ["rename", "bar"]) + finally: + log._reset() - config, _ = _run_rename( - tmp_path, 'assets_dir=Path("foo_assets"), lockfile_dir="foo.lock"' + assert result.exit_code == 0, result.output + assert config_file.read_text() == _RENAME_CONFIG.format( + app_name="bar", args=renamed_config_args ) - - assert config.endswith( - 'config = rx.Config(app_name="bar", assets_dir=Path("foo_assets"), ' - 'lockfile_dir="foo.lock")\n' + assert " ".join(result.output.split()) == ( + f"Info: Renaming app directory to bar. {warning}" + "Success: App directory renamed to bar." ) -@pytest.mark.usefixtures("clean_registration_context") -def test_cli_rename_warns_about_a_moved_dir_it_cannot_update( - tmp_path: Path, monkeypatch: pytest.MonkeyPatch -): - """A moved directory that is not a literal in rxconfig.py is left to the user. +def test_process_directory_skips_an_exclude_dir_given_with_dot_dot(tmp_path: Path): + """An excluded directory is matched however its path is spelled. Args: - tmp_path: The app root. - monkeypatch: The pytest monkeypatch fixture. + tmp_path: The directory to process. """ - monkeypatch.delenv(log._MANAGED_ENV_VAR, raising=False) + (tmp_path / "foo").mkdir() + (tmp_path / "assets").mkdir() + (tmp_path / "foo" / "page.py").write_text("import foo\n") + (tmp_path / "assets" / "page.py").write_text("import foo\n") - config, output = _run_rename(tmp_path, 'assets_dir=Path("foo") / "assets"') + process_directory(tmp_path, "foo", "bar", exclude_dirs=[Path("foo/../assets")]) - assert config.endswith( - 'config = rx.Config(app_name="bar", assets_dir=Path("foo") / "assets")\n' - ) - assert "assets_dir foo/assets moved to bar/assets" in " ".join(output.split()) + assert (tmp_path / "foo" / "page.py").read_text() == "import bar\n" + assert (tmp_path / "assets" / "page.py").read_text() == "import foo\n" def test_has_uuid_distinct_id_semantics_absent( From 6d9168db16563f71c053dda89d4ca65802ffed9b Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:14:49 +0100 Subject: [PATCH 6/8] docs: note absolute paths and imports in the assets_dir and lockfile_dir example --- docs/getting_started/project-structure.md | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/docs/getting_started/project-structure.md b/docs/getting_started/project-structure.md index eed744a2c63..ba3d8a87b3a 100644 --- a/docs/getting_started/project-structure.md +++ b/docs/getting_started/project-structure.md @@ -52,9 +52,13 @@ The `assets` directory is where you can store any static assets you want to be p Reflex copies these files into `.web/public` during compilation. Deleting or renaming an asset removes its previous copy on the next compile, including production exports, while preserving public files generated by plugins. If another process has changed a copied file, Reflex preserves that replacement. Files already deleted before upgrading to a version with asset tracking require a one-time removal of the stale copies or a clean `.web` directory. -`rx.Config(assets_dir=...)` and `rx.Config(lockfile_dir=...)` move the `assets` and `reflex.lock` directories, relative to the project root. This lets two apps that share a root keep their own assets and frontend lockfiles (and their own `.web` with `REFLEX_WEB_WORKDIR`): +`rx.Config(assets_dir=...)` and `rx.Config(lockfile_dir=...)` move the `assets` and `reflex.lock` directories, to a path relative to the project root or an absolute one. This lets two apps that share a root keep their own assets and frontend lockfiles (and their own `.web` with `REFLEX_WEB_WORKDIR`): ```python +from pathlib import Path + +import reflex as rx + config = rx.Config( app_name="website", assets_dir=Path("website/assets"), From e1a4a622e77f98caebf2a5849d439b62dfdf7496 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 10:36:36 +0100 Subject: [PATCH 7/8] fix: match the moved directory settings of reflex rename by syntax tree --- reflex/utils/rename.py | 98 ++++++++++++++++++++++++------- tests/units/test_prerequisites.py | 12 +++- 2 files changed, 87 insertions(+), 23 deletions(-) diff --git a/reflex/utils/rename.py b/reflex/utils/rename.py index e11ad5578e0..6c1fd46fa38 100644 --- a/reflex/utils/rename.py +++ b/reflex/utils/rename.py @@ -1,9 +1,11 @@ """This module provides utilities for renaming directories and files in a Reflex app.""" +import ast import logging import re import sys import tokenize +from collections.abc import Collection from pathlib import Path from reflex_base import constants @@ -183,7 +185,8 @@ def _config_dirs_moved_by_rename( def _update_moved_config_dirs(moved_dirs: dict[str, tuple[Path, Path]]): """Point configured directories that moved with the app at their new location. - Only a string literal passed as the setting in rxconfig.py is rewritten, any other source is left to the user. + Only a string literal passed as the setting to ``Config()`` in rxconfig.py, bare or + in ``Path()``, is rewritten; any other source is left to the user. Args: moved_dirs: The old and new path of each moved directory by config field. @@ -192,39 +195,90 @@ def _update_moved_config_dirs(moved_dirs: dict[str, tuple[Path, Path]]): return config_file = constants.Config.FILE content, encoding = _read_source(config_file) + # ast positions count lines like this and columns in UTF-8 bytes. + lines = re.findall(r".*?(?:\r\n|\r|\n)|.+\Z", content, flags=re.DOTALL) + updated = set() + for field, value, literal in sorted( + _config_dir_literals(content, moved_dirs), + key=lambda item: (item[2].lineno, item[2].col_offset), + reverse=True, + ): + old, new = moved_dirs[field] + if Path(value) != old or literal.end_lineno != literal.lineno: + continue + line = lines[literal.lineno - 1].encode() + segment = line[literal.col_offset : literal.end_col_offset].decode() + if value not in segment: + continue + segment = segment.replace(value, new.as_posix(), 1) + lines[literal.lineno - 1] = ( + line[: literal.col_offset] + + segment.encode() + + line[literal.end_col_offset :] + ).decode() + updated.add(field) for field, (old, new) in moved_dirs.items(): - content, count = _replace_config_dir_literal(content, field, old, new) - if not count: + if field not in updated: logger.warning( f"{field} {old.as_posix()} moved to {new.as_posix()} with the app " "directory. Update it in your config." ) - config_file.write_text(content, encoding=encoding, newline="") + config_file.write_text("".join(lines), encoding=encoding, newline="") -def _replace_config_dir_literal( - content: str, field: str, old: Path, new: Path -) -> tuple[str, int]: - """Replace the string literal passed as a directory setting, bare or in ``Path()``. +def _config_dir_literals( + source: str, fields: Collection[str] +) -> list[tuple[str, str, ast.Constant]]: + """Find the string literals passed to ``Config()`` as the given settings, bare or in ``Path()``. Args: - content: The config source. - field: The name of the setting. - old: The path to replace. - new: The replacement path. + source: The config source. + fields: The names of the settings. Returns: - The updated source and the number of replacements. + The setting, its value and its literal, for each one found. """ - pattern = re.compile( - rf"(\b{field}\s*=\s*(?:(?:pathlib\.)?Path\(\s*)?)([\"']){re.escape(old.as_posix())}\2" - ) - return pattern.subn( - lambda match: ( - f"{match.group(1)}{match.group(2)}{new.as_posix()}{match.group(2)}" - ), - content, - ) + try: + tree = ast.parse(source) + except SyntaxError: + return [] + literals: list[tuple[str, str, ast.Constant]] = [] + for node in ast.walk(tree): + if not (isinstance(node, ast.Call) and _called_name(node) == "Config"): + continue + for keyword in node.keywords: + value = keyword.value + if ( + isinstance(value, ast.Call) + and _called_name(value) == "Path" + and len(value.args) == 1 + and not value.keywords + ): + value = value.args[0] + if ( + keyword.arg is not None + and keyword.arg in fields + and isinstance(value, ast.Constant) + and isinstance(value.value, str) + ): + literals.append((keyword.arg, value.value, value)) + return literals + + +def _called_name(call: ast.Call) -> str | None: + """Get the name a call is made through, ``Config`` for both ``Config()`` and ``rx.Config()``. + + Args: + call: The call. + + Returns: + The name, or None if the callee is not a plain name or attribute. + """ + if isinstance(call.func, ast.Name): + return call.func.id + if isinstance(call.func, ast.Attribute): + return call.func.attr + return None def _read_source(file_path: Path) -> tuple[str, str]: diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index 3815661cd0e..c84a5830381 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -2679,10 +2679,14 @@ def index(): ) -_RENAME_CONFIG = """from pathlib import Path +_RENAME_CONFIG = """import pathlib +from pathlib import Path import reflex as rx +# Keep assets_dir="foo/assets" out of the other app. +OTHER_APP = dict(assets_dir="foo/assets") + config = rx.Config( app_name="{app_name}", disable_plugins=[rx.plugins.SitemapPlugin], @@ -2701,6 +2705,12 @@ def index(): "", id="literals-inside-the-app", ), + pytest.param( + 'assets_dir=Path (r"foo/assets"), lockfile_dir=pathlib.Path("foo/reflex.lock")', + 'assets_dir=Path (r"bar/assets"), lockfile_dir=pathlib.Path("bar/reflex.lock")', + "", + id="raw-string-and-spacing", + ), pytest.param( 'assets_dir="foo/assets", frontend_path="foo/assets"', 'assets_dir="bar/assets", frontend_path="foo/assets"', From 57051a99e1f2506f34b86fba54aa176eac52e493 Mon Sep 17 00:00:00 2001 From: Benedikt Bartscher Date: Thu, 26 Nov 2026 11:33:11 +0100 Subject: [PATCH 8/8] fix: update absolute directory settings inside the app on reflex rename --- reflex/utils/rename.py | 5 +++-- tests/units/test_prerequisites.py | 10 +++++++++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/reflex/utils/rename.py b/reflex/utils/rename.py index 6c1fd46fa38..190f81db0e1 100644 --- a/reflex/utils/rename.py +++ b/reflex/utils/rename.py @@ -204,13 +204,14 @@ def _update_moved_config_dirs(moved_dirs: dict[str, tuple[Path, Path]]): reverse=True, ): old, new = moved_dirs[field] - if Path(value) != old or literal.end_lineno != literal.lineno: + root = Path.cwd() if Path(value).is_absolute() else Path() + if Path(value) != root / old or literal.end_lineno != literal.lineno: continue line = lines[literal.lineno - 1].encode() segment = line[literal.col_offset : literal.end_col_offset].decode() if value not in segment: continue - segment = segment.replace(value, new.as_posix(), 1) + segment = segment.replace(value, (root / new).as_posix(), 1) lines[literal.lineno - 1] = ( line[: literal.col_offset] + segment.encode() diff --git a/tests/units/test_prerequisites.py b/tests/units/test_prerequisites.py index c84a5830381..46d23882899 100644 --- a/tests/units/test_prerequisites.py +++ b/tests/units/test_prerequisites.py @@ -2723,6 +2723,12 @@ def index(): "", id="outside-the-app", ), + pytest.param( + 'assets_dir="{root}/foo/assets", lockfile_dir=Path("{root}/foo.lock")', + 'assets_dir="{root}/bar/assets", lockfile_dir=Path("{root}/foo.lock")', + "", + id="absolute-paths", + ), pytest.param( 'assets_dir=Path("foo") / "assets"', 'assets_dir=Path("foo") / "assets"', @@ -2744,11 +2750,13 @@ def test_cli_rename_updates_configured_dirs_it_moves( Args: tmp_path: The app root. monkeypatch: The pytest monkeypatch fixture. - config_args: The directory settings before the rename. + config_args: The directory settings before the rename, ``{root}`` standing for the app root. renamed_config_args: The directory settings expected after the rename. warning: The warning expected for a setting the rename cannot update. """ monkeypatch.delenv(log._MANAGED_ENV_VAR, raising=False) + config_args = config_args.format(root=tmp_path.as_posix()) + renamed_config_args = renamed_config_args.format(root=tmp_path.as_posix()) (tmp_path / "foo").mkdir() (tmp_path / "foo" / "__init__.py").touch() (tmp_path / "foo" / "foo.py").write_text("import reflex as rx\n")