-
Notifications
You must be signed in to change notification settings - Fork 336
feat(cli): add migrate-images for KBs ingested before note-relative links #182
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Aldominguez12
wants to merge
2
commits into
VectifyAI:main
Choose a base branch
from
Aldominguez12:feat/migrate-image-links
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+253
−0
Open
Changes from 1 commit
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,57 @@ | ||
| """One-time migrations for knowledge bases created by older OpenKB versions.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import re | ||
| from pathlib import Path | ||
|
|
||
| from openkb.locks import atomic_write_text | ||
|
|
||
| # Inline-link opener followed by the old wiki-root-relative image prefix. | ||
| # Only the prefix is swapped (`](sources/images/` → `](images/`), so the | ||
| # path tail up to the closing paren never needs parsing, and image embeds | ||
| # (``) and plain links are handled alike. | ||
| _OLD_IMAGE_PREFIX_RE = re.compile(r"\]\(sources/images/") | ||
|
|
||
|
|
||
| def migrate_source_image_links(wiki: Path, *, dry_run: bool = False) -> list[tuple[Path, int]]: | ||
| """Rewrite wiki-root-relative image links in sources pages to note-relative. | ||
|
|
||
| KBs ingested before the ``md_image_ref()`` change embedded images in | ||
| ``wiki/sources/<doc>.md`` as ````. | ||
| Renderers resolve links relative to the containing file, so from a | ||
| sources page those pointed at the non-existent | ||
| ``sources/sources/images/...`` and rendered broken. This rewrites them | ||
| to the ``images/<doc>/<file>`` form now emitted at ingest. | ||
|
|
||
| Only ``.md`` files directly under ``wiki/sources/`` are touched — the | ||
| per-page JSON of long documents intentionally keeps wiki-root-relative | ||
| paths (internal metadata, resolved against the wiki root), and pages | ||
| outside ``sources/`` never carried the old prefix. Idempotent: already | ||
| note-relative links don't match the old prefix. | ||
|
|
||
| Args: | ||
| wiki: Path to the wiki root directory. | ||
| dry_run: When True, report what would change without writing. | ||
|
|
||
| Returns: | ||
| List of ``(path, links_rewritten)`` for each file that changed | ||
| (or would change, under ``dry_run``). | ||
| """ | ||
| sources = wiki / "sources" | ||
| changed: list[tuple[Path, int]] = [] | ||
| if not sources.is_dir(): | ||
| return changed | ||
|
|
||
| for md in sorted(sources.glob("*.md")): | ||
| try: | ||
| text = md.read_text(encoding="utf-8") | ||
| except OSError: | ||
| continue | ||
| migrated, count = _OLD_IMAGE_PREFIX_RE.subn("](images/", text) | ||
| if count == 0: | ||
| continue | ||
| if not dry_run: | ||
| atomic_write_text(md, migrated) | ||
| changed.append((md, count)) | ||
| return changed |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| """Tests for openkb.migrate and the migrate-images CLI command.""" | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import json | ||
| from pathlib import Path | ||
| from unittest.mock import patch | ||
|
|
||
| from click.testing import CliRunner | ||
|
|
||
| from openkb.cli import cli | ||
| from openkb.migrate import migrate_source_image_links | ||
|
|
||
| OLD_PAGE = ( | ||
| "# Doc\n\n" | ||
| "Intro text.\n\n" | ||
| "\n\n" | ||
| "More text with an inline  here.\n" | ||
| ) | ||
|
|
||
| MIGRATED_PAGE = ( | ||
| "# Doc\n\n" | ||
| "Intro text.\n\n" | ||
| "\n\n" | ||
| "More text with an inline  here.\n" | ||
| ) | ||
|
|
||
|
|
||
| def _make_wiki(tmp_path: Path) -> Path: | ||
| wiki = tmp_path / "wiki" | ||
| (wiki / "sources" / "images").mkdir(parents=True) | ||
| (wiki / "summaries").mkdir(parents=True) | ||
| return wiki | ||
|
|
||
|
|
||
| class TestMigrateSourceImageLinks: | ||
| def test_rewrites_old_links_preserving_alt_and_text(self, tmp_path): | ||
| wiki = _make_wiki(tmp_path) | ||
| page = wiki / "sources" / "doc.md" | ||
| page.write_text(OLD_PAGE, encoding="utf-8") | ||
|
|
||
| changed = migrate_source_image_links(wiki) | ||
|
|
||
| assert changed == [(page, 2)] | ||
| assert page.read_text(encoding="utf-8") == MIGRATED_PAGE | ||
|
|
||
| def test_idempotent_on_migrated_page(self, tmp_path): | ||
| wiki = _make_wiki(tmp_path) | ||
| page = wiki / "sources" / "doc.md" | ||
| page.write_text(MIGRATED_PAGE, encoding="utf-8") | ||
|
|
||
| assert migrate_source_image_links(wiki) == [] | ||
| assert page.read_text(encoding="utf-8") == MIGRATED_PAGE | ||
|
|
||
| def test_dry_run_reports_without_writing(self, tmp_path): | ||
| wiki = _make_wiki(tmp_path) | ||
| page = wiki / "sources" / "doc.md" | ||
| page.write_text(OLD_PAGE, encoding="utf-8") | ||
|
|
||
| changed = migrate_source_image_links(wiki, dry_run=True) | ||
|
|
||
| assert changed == [(page, 2)] | ||
| assert page.read_text(encoding="utf-8") == OLD_PAGE | ||
|
|
||
| def test_long_doc_json_left_untouched(self, tmp_path): | ||
| # Per-page JSON keeps wiki-root-relative paths by design. | ||
| wiki = _make_wiki(tmp_path) | ||
| payload = json.dumps([{"page": 1, "content": ""}]) | ||
| doc_json = wiki / "sources" / "doc.json" | ||
| doc_json.write_text(payload, encoding="utf-8") | ||
|
|
||
| assert migrate_source_image_links(wiki) == [] | ||
| assert doc_json.read_text(encoding="utf-8") == payload | ||
|
|
||
| def test_pages_outside_sources_left_untouched(self, tmp_path): | ||
| # Note-relative resolution differs outside sources/ — out of scope. | ||
| wiki = _make_wiki(tmp_path) | ||
| summary = wiki / "summaries" / "doc.md" | ||
| summary.write_text(OLD_PAGE, encoding="utf-8") | ||
|
|
||
| assert migrate_source_image_links(wiki) == [] | ||
| assert summary.read_text(encoding="utf-8") == OLD_PAGE | ||
|
|
||
| def test_missing_sources_dir_is_noop(self, tmp_path): | ||
| wiki = tmp_path / "wiki" | ||
| wiki.mkdir() | ||
|
|
||
| assert migrate_source_image_links(wiki) == [] | ||
|
|
||
| def test_multiple_files_sorted(self, tmp_path): | ||
| wiki = _make_wiki(tmp_path) | ||
| page_b = wiki / "sources" / "b.md" | ||
| page_a = wiki / "sources" / "a.md" | ||
| page_b.write_text("", encoding="utf-8") | ||
| page_a.write_text(OLD_PAGE, encoding="utf-8") | ||
|
|
||
| changed = migrate_source_image_links(wiki) | ||
|
|
||
| assert changed == [(page_a, 2), (page_b, 1)] | ||
|
|
||
|
|
||
| class TestMigrateImagesCommand: | ||
| def _setup_kb(self, tmp_path: Path) -> Path: | ||
| kb_dir = tmp_path | ||
| (kb_dir / "wiki" / "sources" / "images").mkdir(parents=True) | ||
| (kb_dir / ".openkb").mkdir() | ||
| return kb_dir | ||
|
|
||
| def test_no_kb(self, tmp_path): | ||
| runner = CliRunner() | ||
| with ( | ||
| runner.isolated_filesystem(temp_dir=tmp_path), | ||
| patch("openkb.cli._find_kb_dir", return_value=None), | ||
| ): | ||
| result = runner.invoke(cli, ["migrate-images"]) | ||
| assert result.exit_code == 0 | ||
| assert "No knowledge base found" in result.output | ||
|
|
||
| def test_nothing_to_migrate(self, tmp_path): | ||
| kb_dir = self._setup_kb(tmp_path) | ||
| (kb_dir / "wiki" / "sources" / "doc.md").write_text(MIGRATED_PAGE, encoding="utf-8") | ||
| runner = CliRunner() | ||
| with patch("openkb.cli._find_kb_dir", return_value=kb_dir): | ||
| result = runner.invoke(cli, ["migrate-images"]) | ||
| assert result.exit_code == 0 | ||
| assert "Nothing to migrate" in result.output | ||
|
|
||
| def test_migrates_and_logs(self, tmp_path): | ||
| kb_dir = self._setup_kb(tmp_path) | ||
| page = kb_dir / "wiki" / "sources" / "doc.md" | ||
| page.write_text(OLD_PAGE, encoding="utf-8") | ||
| runner = CliRunner() | ||
| with patch("openkb.cli._find_kb_dir", return_value=kb_dir): | ||
| result = runner.invoke(cli, ["migrate-images"]) | ||
| assert result.exit_code == 0 | ||
| assert "Rewrote 2 image link(s) across 1 file(s)." in result.output | ||
| assert "doc.md: 2 link(s)" in result.output | ||
| assert page.read_text(encoding="utf-8") == MIGRATED_PAGE | ||
| log = kb_dir / "wiki" / "log.md" | ||
| assert log.exists() | ||
| assert "migrate-images" in log.read_text(encoding="utf-8") | ||
|
|
||
| def test_dry_run_does_not_write(self, tmp_path): | ||
| kb_dir = self._setup_kb(tmp_path) | ||
| page = kb_dir / "wiki" / "sources" / "doc.md" | ||
| page.write_text(OLD_PAGE, encoding="utf-8") | ||
| runner = CliRunner() | ||
| with patch("openkb.cli._find_kb_dir", return_value=kb_dir): | ||
| result = runner.invoke(cli, ["migrate-images", "--dry-run"]) | ||
| assert result.exit_code == 0 | ||
| assert "Would rewrite 2 image link(s) across 1 file(s)." in result.output | ||
| assert page.read_text(encoding="utf-8") == OLD_PAGE | ||
| assert not (kb_dir / "wiki" / "log.md").exists() |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When
openkb migrate-imagesruns concurrently with another mutating command, thisappend_logexecutes after the exclusivekb_ingest_lockblock has already been released. Sinceappend_logwriteswiki/log.md, this leaves a wiki write outside the repo's locking invariant fromAGENTS.mdand can interleave with another process's locked log update; keep the log append inside the same exclusive lock as the file rewrites.Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch — fixed in 29da160. The
append_logcall now runs inside the samekb_ingest_lockblock as the file rewrites, matching the pattern used by the lint command.tests/test_migrate.pystill passes (11/11).