Skip to content

Scrapy, a fast high-level web crawling & scraping framework for Python.

Add scrapy.utils.project.find_projects() (#8024)

Adrian31a279d28ce0
diff --git a/docs/topics/commands.rst b/docs/topics/commands.rst
index d88bdb38b..fa2bb6d99 100644
--- a/docs/topics/commands.rst
+++ b/docs/topics/commands.rst
@@ -80,6 +80,16 @@ but is just an identifier, and the capitalized project-name prefix of class
names in :file:`middlewares.py` and :file:`pipelines.py` is only a naming
convention; neither needs to match the module name.
+.. _find-projects:
+
+Finding projects
+----------------
+
+To find the Scrapy projects in a directory tree, e.g. from an editor extension,
+use :func:`~scrapy.utils.project.find_projects`:
+
+.. autofunction:: scrapy.utils.project.find_projects
+
.. _topics-project-envvar:
Sharing the root directory between projects
diff --git a/scrapy/utils/project.py b/scrapy/utils/project.py
index 831ac7770..406d6d960 100644
--- a/scrapy/utils/project.py
+++ b/scrapy/utils/project.py
@@ -4,15 +4,61 @@ import os
import warnings
from importlib import import_module
from pathlib import Path
+from typing import TYPE_CHECKING
from scrapy.exceptions import NotConfigured
from scrapy.settings import Settings
from scrapy.utils.conf import closest_scrapy_cfg, get_config, init_env
+if TYPE_CHECKING:
+ from collections.abc import Iterable, Iterator
+
ENVVAR = "SCRAPY_SETTINGS_MODULE"
DATADIR_CFG_SECTION = "datadir"
+def find_projects(
+ path: str | os.PathLike[str] = ".",
+ *,
+ max_depth: int | None = None,
+ ignored_dirs: Iterable[str] = (),
+) -> Iterator[Path]:
+ """Yield the root directory of every Scrapy project found in *path* or,
+ recursively, in any of its subdirectories.
+
+ .. versionadded:: VERSION
+
+ Once a project is found, its subdirectories are not searched.
+
+ Hidden directories and any directory named in *ignored_dirs* are not
+ searched either, and neither are virtual environments, identified by a
+ :file:`pyvenv.cfg` file, regardless of their directory name.
+
+ *max_depth* limits how deep to search: 0 only checks *path* itself, 1 also
+ checks its direct subdirectories, and so on. By default, the whole
+ directory tree is searched.
+ """
+ root = Path(path)
+ ignored = frozenset(ignored_dirs)
+ for dirpath, dirnames, filenames in os.walk(root):
+ current = Path(dirpath)
+ if "scrapy.cfg" in filenames:
+ dirnames.clear()
+ yield current
+ continue
+ if "pyvenv.cfg" in filenames:
+ dirnames.clear()
+ continue
+ if max_depth is not None and len(current.relative_to(root).parts) >= max_depth:
+ dirnames.clear()
+ continue
+ dirnames[:] = sorted(
+ dirname
+ for dirname in dirnames
+ if not dirname.startswith(".") and dirname not in ignored
+ )
+
+
def inside_project() -> bool:
scrapy_module = os.environ.get(ENVVAR)
if scrapy_module:
diff --git a/tests/test_utils_project.py b/tests/test_utils_project.py
index 8a7f2ee03..297ae4414 100644
--- a/tests/test_utils_project.py
+++ b/tests/test_utils_project.py
@@ -10,6 +10,7 @@ from scrapy.exceptions import NotConfigured
from scrapy.utils.misc import set_environ
from scrapy.utils.project import (
data_path,
+ find_projects,
get_project_settings,
inside_project,
project_data_dir,
@@ -133,3 +134,59 @@ class TestGetProjectSettings:
settings = get_project_settings()
assert settings.get("SETTINGS_MODULE") == value
assert settings.get("SCRAPY_FOO") is None
+
+
+def test_find_projects(tmp_path: Path) -> None:
+ for relative_path in (
+ "a/scrapy.cfg",
+ "a/nested/scrapy.cfg",
+ "b/c/d/scrapy.cfg",
+ ".hidden/scrapy.cfg",
+ "no-project/setup.py",
+ ):
+ path = tmp_path / relative_path
+ path.parent.mkdir(parents=True, exist_ok=True)
+ path.touch()
+
+ assert list(find_projects(tmp_path)) == [
+ tmp_path / "a",
+ tmp_path / "b" / "c" / "d",
+ ]
+
+
+def test_find_projects_skips_virtual_environments(tmp_path: Path) -> None:
+ # An arbitrarily-named directory, to show detection does not rely on it
+ # being called venv or .venv.
+ venv = tmp_path / "my-env"
+ (venv / "lib" / "project").mkdir(parents=True)
+ (venv / "pyvenv.cfg").touch()
+ (venv / "lib" / "project" / "scrapy.cfg").touch()
+
+ assert list(find_projects(tmp_path)) == []
+
+
+def test_find_projects_ignored_dirs(tmp_path: Path) -> None:
+ for relative_path in ("a/scrapy.cfg", "b/scrapy.cfg"):
+ path = tmp_path / relative_path
+ path.parent.mkdir(parents=True)
+ path.touch()
+
+ assert list(find_projects(tmp_path, ignored_dirs=["a"])) == [tmp_path / "b"]
+
+
+def test_find_projects_root(tmp_path: Path) -> None:
+ (tmp_path / "scrapy.cfg").touch()
+ (tmp_path / "a").mkdir()
+ (tmp_path / "a" / "scrapy.cfg").touch()
+
+ assert list(find_projects(tmp_path)) == [tmp_path]
+
+
+def test_find_projects_max_depth(tmp_path: Path) -> None:
+ for relative_path in ("a/scrapy.cfg", "b/c/scrapy.cfg"):
+ path = tmp_path / relative_path
+ path.parent.mkdir(parents=True)
+ path.touch()
+
+ assert list(find_projects(tmp_path, max_depth=0)) == []
+ assert list(find_projects(tmp_path, max_depth=1)) == [tmp_path / "a"]