8000 Reject conflicting batch export paths by iyuzhang · Pull Request #168 · gimp-mcp/gimp-mcp · GitHub
[go: up one dir, main page]

Skip to content
Merged
8000
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,12 @@ right command when the versions differ.

## [Unreleased]

### Fixed
- `batch_export` rejects duplicate output names in the same resolved directory
before writing files. Include `{index}` in `name_pattern` to give same-named
images distinct paths. If a destination refers to a file already written
by the batch, the later export is skipped and reported as an error (#161).

## [0.6.0] - 2026-11-21

### Fixed
Expand Down
63 changes: 60 additions & 3 deletions gimp-mcp-plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -2952,8 +2952,8 @@ def _batch_export(self, params):
image_index = self._index(image_index, "image_index")
targets = [(image_index, self._get_image(image_index))]

os.makedirs(output_dir, exist_ok=True)
exported = []
planned = []
destinations: dict[str, tuple[int, str]] = {}
errors = []

for idx, image in targets:
Expand All @@ -2962,7 +2962,36 @@ def _batch_export(self, params):
raw_name = gio_file.get_basename().rsplit(".", 1)[0] if gio_file else f"image_{idx}"
filename = name_pattern.format(name=raw_name, index=idx) + f".{fmt}"
out_path = os.path.join(output_dir, filename)
self._export_to_path(image, out_path, fmt, quality, True)
# Collapse dot components as Gio.File.new_for_path does.
absolute_path = os.path.abspath(out_path)
directory, basename = os.path.split(absolute_path)
# Leave filename aliases for the check immediately before writing.
destination = os.path.join(os.path.realpath(directory), basename)
except Exception as ex:
errors.append({"index": idx, "error": str(ex)})
continue

source = (idx, raw_name)
if destination in destinations:
return self._batch_export_collision(out_path, destinations[destination], source)
destinations[destination] = source
planned.append((idx, image, raw_name, out_path, absolute_path))

os.makedirs(output_dir, exist_ok=True)
exported = []
written_paths: dict[str, str] = {}
for idx, image, raw_name, out_path, absolute_path in planned:
try:
previous_path = self._previous_export_path(absolute_path, written_paths)
if previous_path is not None:
errors.append({
"index": idx,
"error": f"Output path {out_path!r} refers to the same file as "
f"{previous_path!r}, already written by this batch.",
8000 })
continue
self._export_to_path(image, absolute_path, fmt, quality, True)
written_paths[absolute_path] = out_path
exported.append({
"file_path": out_path,
"name": raw_name,
Expand All @@ -2972,6 +3001,7 @@ def _batch_export(self, params):
except Exception as ex:
errors.append({"index": idx, "error": str(ex)})

errors.sort(key=lambda error: error["index"])
# Some images exported is a success that lists the others in
# errors; none at all is an error (it used to be a success too).
if not exported:
Expand All @@ -2984,6 +3014,33 @@ def _batch_export(self, params):
except Exception as e:
return {"status": "error", "error": str(e), "traceback": traceback.format_exc()}

@staticmethod
def _batch_export_collision(
path: str, first: tuple[int, str], second: tuple[int, str],
) -> dict[str, str]:
"""Reports the images that share an export destination."""
first_idx, first_name = first
second_idx, second_name = second
return {
"status": "error",
"error": f"Output path {path!r} is shared by image {first_idx} ({first_name!r}) "
f"and image {second_idx} ({second_name!r}). "
"Choose distinct destinations, for example with {index} in name_pattern.",
}

@staticmethod
def _previous_export_path(path: str, written_paths: dict[str, str]) -> str | None:
"""Finds the reported path of an earlier export that shares this file."""
if not os.path.exists(path):
return None
for written_path, reported_path in written_paths.items():
try:
if os.path.samefile(path, written_path):
return reported_path
except (FileNotFoundError, NotADirectoryError):
continue
return None

# =========================================================================
# CATEGORY 2 — Image Adjustments
# =========================================================================
Expand Down
7 changes: 5 additions & 2 deletions gimp_mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -945,8 +945,11 @@ def batch_export(
- count: number of files written
- errors: list of {index, error} for images that failed to export
When no image could be exported, the call fails with each image's error instead.
A name_pattern with fields other than {name} and {index} is an error, and
nothing is exported.
An invalid name_pattern or duplicate output names in the same resolved
directory stop the batch before any files are written. Include {index} to
give same-named images distinct paths.
If a destination refers to a file already written by this batch, the later
export is skipped and reported in errors. Other existing files can be replaced.
"""
try:
params: dict = {
Expand Down
100 changes: 96 additions & 4 deletions tests/test_batch_export_live.py
8000
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
"""Live test for batch_export when nothing can be exported (#63).
"""Live checks for batch_export failures and output files (#63, #161).

batch_export reported success with exported: [] when every image failed, and
a bad name_pattern failed for each image with a bare "'bogus'" (also a
Expand All @@ -10,20 +10,26 @@
indexed or attribute one, such as {name[3]}, or one in a format spec) or
bad syntax is an error naming it, and writes nothing;
- one image failing among others still succeeds, listing it in errors.
- two source files with the same base name are rejected before any writes.
- {index} produces distinct paths and allows overwriting an existing export.
- for symlinked and hard-linked filenames, the first export survives and
the later one is skipped with an error naming both paths.

The last check exports every open image, so it runs only when the test's own
The last checks export every open image, so they run only when the test's own
two images are the only ones open (it prints SKIP otherwise); the files go to
a temporary directory that is deleted again.

Requires the GIMP MCP plugin running on localhost:9877 (GIMP_MCP_PORT
overrides the port). Exits 0 on pass, 1 on fail.
overrides the port). Set TMPDIR to test on a specific filesystem. Exits 0 on
pass, 1 on fail.
"""
import json
import os
import shutil
import socket
import sys
import tempfile
from pathlib import Path

HOST, PORT = '127.0.0.1', int(os.environ.get('GIMP_MCP_PORT', 9877))

Expand Down Expand Up @@ -76,6 +82,91 @@ def files(path):
return sorted(os.listdir(path)) if os.path.isdir(path) else []


def check_duplicate_names(out_dir, made):
"""Checks collision rejection and the indexed naming workaround."""
source = Path(out_dir) / 'source'
fixtures = (
('_BE_PNG', source / 'a' / 'photo.png', 'png'),
('_BE_JPEG', source / 'b' / 'photo.jpg', 'jpeg'),
)
for _, path, fmt in fixtures:
path.parent.mkdir(parents=True)
r = cmd('export_image', {'file_path': str(path), 'format': fmt,
'image_index': index('_BE_OK')})
check(r.get('status') == 'success', 'could not create a source file', r)
py('_BE_EMPTY.delete()', '_BE_OK.delete()', 'from gi.repository import Gio')
for var, path, _ in fixtures:
py(f'{var} = Gimp.file_load(Gimp.RunMode.NONINTERACTIVE, '
f'Gio.File.new_for_path({str(path)!r}))')
check(py(f'print({var} is not None)') == 'True', 'could not load the source image', path)
made.append(var)
py('_BE_JPEG.scale(12, 10)')
indices = sorted(index(var) for var, _, _ in fixtures)
widths = [int(py(f'print(Gimp.get_images()[{idx}].get_width())')) for idx in indices]
check(widths[0] != widths[1], 'the source images should have distinct widths', widths)

target = Path(out_dir) / 'duplicate'
r = cmd('batch_export', {'output_dir': str(target)})
error = r.get('error', '')
check(r.get('status') == 'error' and 'photo.png' in error
and '{index}' in error
and all(f"image {idx} ('photo')" in error for idx in indices),
'duplicate output paths were not rejected with both image indices and a workaround', r)
check(not target.exists(), 'the rejected batch created its output directory')
print('PASS: conflicting destinations are rejected before writing')

target.mkdir()
expected = {target / f'photo_{idx}.png' for idx in indices}
for path in expected:
path.write_bytes(b'old export')
r = cmd('batch_export', {'output_dir': str(target), 'name_pattern': '{name}_{index}'})
check(r.get('status') == 'success', 'unique destinations were refused', r)
result = r['results']
check(result['count'] == 2 and result['errors'] == []
and {Path(item['file_path']) for item in result['exported']} == expected,
'the indexed batch did not report both destinations', result)
check(set(target.iterdir()) == expected
and all(path.read_bytes().startswith(b'\x89PNG\r\n\x1a\n') for path in expected),
'both destinations should contain new PNG exports', files(target))
print('PASS: unique destinations export both images and replace existing files')

check_linked_destinations(Path(out_dir), indices, widths[0])


def check_linked_destinations(out_dir: Path, indices: list[int], first_width: int) -> None:
"""Checks that the first PNG survives when two destinations share a file."""
for kind in ('symlink', 'hardlink'):
output = out_dir / kind
output.mkdir()
first, second = (output / f'photo_{idx}.png' for idx in indices)
first.write_bytes(b'old export')
try:
if kind == 'hardlink':
second.hardlink_to(first)
else:
second.symlink_to(first.name)
except (NotImplementedError, OSError) as exc:
print(f'SKIP: cannot create {kind}: {exc}')
continue

r = cmd('batch_export', {'output_dir': str(output), 'name_pattern': '{name}_{index}'})
check(r.get('status') == 'success', f'{kind} prevented the first export', r)
result = r['results']
check(result['count'] == 1
and [item['file_path'] for item in result['exported']] == [str(first)],
f'{kind} did not leave exactly the first export in the result', result)
errors = result['errors']
check(len(errors) == 1 and errors[0]['index'] == indices[1]
and all(repr(str(path)) in errors[0]['error'] for path in (first, second)),
f'{kind} did not report the second export and both paths', errors)
png_header = first.read_bytes()[:24]
check(png_header.startswith(b'\x89PNG\r\n\x1a\n')
and int.from_bytes(png_header[16:20], 'big') == first_width
and first.samefile(second),
f'{kind} did not preserve the first PNG')
print(f'PASS: {kind} skips the second export and preserves the first PNG')


def main():
out_dir = tempfile.mkdtemp(prefix='gimp-mcp-batch-export-')
made = []
Expand Down Expand Up @@ -112,7 +203,7 @@ def main():
print("PASS: a bad name_pattern is an error and writes nothing")

if py("print(len(Gimp.get_images()))") != "2":
print("SKIP: some-exported case: batch_export without image_index exports every "
print("SKIP: multi-image cases: batch_export without image_index exports every "
"open image; needs GIMP with no other images open")
return 0
target = os.path.join(out_dir, 'all')
Expand All @@ -123,6 +214,7 @@ def main():
check(f"be_{index('_BE_OK')}.png" in files(target), "the good image wasn't exported",
files(target))
print("PASS: some images exported is a success that lists the failed ones")
check_duplicate_names(out_dir, made)
return 0
finally:
for var in made:
Expand Down
39 changes: 39 additions & 0 deletions tests/test_pdb_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,8 @@
import sys
import tempfile
import types
from pathlib import Path
from unittest.mock import patch

HERE = os.path.dirname(os.path.abspath(__file__))
PLUGIN = os.path.join(HERE, os.pardir, "gimp-mcp-plugin.py")
Expand Down Expand Up @@ -231,6 +233,11 @@ def get_item_position(self, item):
return 0


class UnnamedImage(FakeImage):
def get_file(self) -> None:
return None


class LayerlessImage(FakeImage):
"""An image without layers. As in GIMP 3.2, flatten() on it returns None."""

Expand Down Expand Up @@ -1038,6 +1045,38 @@ def export(fmt, quality=80, flatten=False, image=None):
check("export_image reports an error for an unsupported format",
None if r["status"] == "error" and "Unsupported export format" in r["error"] else f"got {r}")

for kind, link in (("symlink", os.symlink), ("hardlink", os.link)):
with tempfile.TemporaryDirectory() as batch_dir:
first = Path(batch_dir) / "image_0.png"
second = Path(batch_dir) / "image_1.png"
first.write_bytes(b"old export")
try:
link(first, second)
except (NotImplementedError, OSError) as exc:
print(f"SKIP: cannot create {kind}: {exc}")
continue
images = [UnnamedImage(), UnnamedImage()]

def write_export(image: UnnamedImage, path: str, _fmt: str, _quality: int,
_flatten: bool) -> int:
return Path(path).write_bytes(b"first" if image is images[0] else b"second")

with (
patch.object(mod.Gimp, "get_images", return_value=images),
patch.object(plugin, "_export_to_path", side_effect=write_export) as writer,
):
r = plugin._batch_export({"output_dir": batch_dir})

result = r.get("results", {})
errors = result.get("errors", [])
check(f"batch_export skips a {kind} to the first export and preserves its contents",
None if r["status"] == "success" and result.get("count") == 1
and [item["file_path"] for item in result["exported"]] == [str(first)]
and len(errors) == 1 and errors[0]["index"] == 1
and all(repr(str(path)) in errors[0]["error"] for path in (first, second))
and writer.call_count == 1 and first.read_bytes() == second.read_bytes() == b"first"
else f"got {r}, export calls {writer.call_args_list}")

print(f"\n{'FAILED' if failures else 'PASSED'}: {len(failures)} failure(s)")
return 1 if failures else 0

Expand Down
Loading
0