Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 5 additions & 29 deletions src/mogs/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,6 @@

# The reference regex from PEP 723, for the `script` block.
HEADER_RE = re.compile(r"(?m)^# /// script$\s(?P<content>(^#(| .*)$\s)+)^# ///$")
TABLE_RE = re.compile(r"^\[\[?\s*([A-Za-z0-9_-]+(?:\s*\.\s*[A-Za-z0-9_-]+)*)\s*\]\]?\s*(#.*)?$")
NAME_RE = re.compile(r"^\s*([A-Za-z0-9][A-Za-z0-9._-]*)")
QID_RE = re.compile(r"^[A-Za-z][A-Za-z0-9]*$")
# Characters Windows forbids in file names.
Expand Down Expand Up @@ -752,11 +751,10 @@ def _memory(where: Where, value: object) -> int:


def replace_header(src: str, body: list[str]) -> str:
"""Put the TOML lines `body` in the PEP 723 header of `src`.
"""Put the TOML lines `body` in the PEP 723 header of `src`, in place of the old header.

The old header's `[tool.*]` tables stay after `body`, except uv's (`[tool.uv]` and its
subtables), which `body` replaces. Everything else in the old header goes. Without a
header, the new one goes at the top, followed by a blank line.
mogs owns the header, so nothing of the old one stays. Without a header, the new one goes
at the top, followed by a blank line.

Raises:
ConfigError: If the old header is not valid TOML.
Expand All @@ -768,24 +766,9 @@ def replace_header(src: str, body: list[str]) -> str:
return _join("# /// script\n", body, "# ///\n\n" + src)

read_header(src)
before, old, after = _split(src)
kept: list[str] = []
keep = False
before, _, after = _split(src)

for line in old:
name = _table_name(line)

if name is not None:
uv = name == "tool.uv" or name.startswith("tool.uv.")
keep = name.startswith("tool.") and not uv

if keep:
kept.append(line)

while kept and not kept[-1].strip():
kept.pop()

return _join(before, body + ([""] + kept if kept else []), after)
return _join(before, body, after)


def normalized_name(requirement: str) -> str | None:
Expand Down Expand Up @@ -816,10 +799,3 @@ def _join(before: str, body: list[str], after: str) -> str:

lines = [f"# {line}" if line else "#" for line in body]
return before + "".join(line + "\n" for line in lines) + after


def _table_name(line: str) -> str | None:
"""Dotted name of a TOML table header line, with spaces around dots removed."""

match = TABLE_RE.match(line.strip())
return re.sub(r"\s+", "", match.group(1)) if match else None
11 changes: 8 additions & 3 deletions src/mogs/requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,9 +77,9 @@ def read_requirements(cfg: AssignmentConfig) -> Requirements:

Raises:
ValueError: If `cfg` was not read from a notebook, so it names no file.
ConfigError: If the file is missing, or has a line other than a requirement, an
`--index-url` or `--extra-index-url` option, a comment or a blank line. The
message names the file and the line.
ConfigError: If the file is missing, has a line other than a requirement, an
`--index-url` or `--extra-index-url` option, a comment or a blank line, or has
more than one `--index-url`. The message names the file and the line.
"""

if cfg.requirements is None:
Expand All @@ -99,6 +99,11 @@ def read_requirements(cfg: AssignmentConfig) -> Requirements:
match _parse_line(line, path):
case None:
pass
case Index(default=True) if any(index.default for index in indexes):
raise ConfigError(
f"{ASSIGNMENT} `requirements`: {path} has more than one `--index-url`. "
"Keep one, and add the others with `--extra-index-url`."
)
case Index() as index:
indexes.append(index)
case str() as package if normalized_name(package) != TOOL:
Expand Down
18 changes: 11 additions & 7 deletions tests/test_requirements.py
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,6 @@ def test_lines_as_written(tmp_path):
"pkg @ https://example.com/pkg-1.0-py3-none-any.whl\n"
"--index-url https://pypi.org/simple\n"
"--extra-index-url=https://download.pytorch.org/whl/cpu\n"
"-i https://example.com/simple\n"
)

requirements = requirements_of(tmp_path, text)
Expand All @@ -132,7 +131,6 @@ def test_lines_as_written(tmp_path):
assert requirements.indexes == (
Index("https://pypi.org/simple", default=True),
Index("https://download.pytorch.org/whl/cpu"),
Index("https://example.com/simple", default=True),
)
assert requirements.text == text

Expand Down Expand Up @@ -251,7 +249,7 @@ def test_header_needs_a_python_version(python):
script_header(Requirements(), python, "mogs")


def test_with_header_keeps_tool_tables_but_uv_ones():
def test_with_header_replaces_the_whole_header():
out = with_header(HEADER + CODE, Requirements(("numpy",)), "3.13", "mogs")

assert out == (
Expand All @@ -261,13 +259,19 @@ def test_with_header_keeps_tool_tables_but_uv_ones():
'# "numpy",\n'
'# "mogs",\n'
"# ]\n"
"#\n"
"# [tool.marimo.runtime]\n"
"# reactive_tests = false\n"
"# ///\n" + CODE
)


def test_second_index_url_is_refused(tmp_path):
text = "--index-url https://a.example/simple\nnumpy\n-i https://b.example/simple\n"

with pytest.raises(ConfigError, match="more than one `--index-url`") as error:
requirements_of(tmp_path, text)

assert "requirements.txt" in str(error.value)


def test_with_header_adds_a_missing_header():
out = with_header(CODE.lstrip(), Requirements(), "3.13", "mogs")

Expand Down Expand Up @@ -300,7 +304,7 @@ def test_write_header_warns_about_packages_only_the_header_lists(tmp_path):
header = read_header(notebook.read_text(encoding="utf-8"))
assert header["requires-python"] == "==3.12.*"
assert header["dependencies"] == ["numpy", "mogs"]
assert header["tool"] == {"marimo": {"runtime": {"reactive_tests": False}}}
assert "marimo" not in header.get("tool", {})
assert warnings == [
f"The header of {notebook} listed 'scipy', which {tmp_path / 'requirements.txt'} does "
f"not. Add them to {tmp_path / 'requirements.txt'}; mogs rewrites the header from it."
Expand Down
3 changes: 0 additions & 3 deletions tests/test_transform.py
Original file line number Diff line number Diff line change
Expand Up @@ -805,9 +805,6 @@ def test_header_comes_from_the_requirements():
'# "numpy==2.0",\n'
'# "mogs==9.9.9",\n'
"# ]\n"
"#\n"
"# [tool.marimo.runtime]\n"
"# reactive_tests = false\n"
"# ///\n"
)

Expand Down
Loading