minioj 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
minioj/__init__.py ADDED
@@ -0,0 +1 @@
1
+ """MiniOJ: run configured exercise stages and report results on GitHub."""
minioj/__main__.py ADDED
@@ -0,0 +1,5 @@
1
+ from .cli import main
2
+
3
+
4
+ if __name__ == "__main__":
5
+ raise SystemExit(main())
minioj/cli.py ADDED
@@ -0,0 +1,68 @@
1
+ """Command-line parsing and orchestration for a single judge run."""
2
+
3
+ import subprocess
4
+ import sys
5
+ from argparse import ArgumentParser
6
+ from collections.abc import Sequence
7
+ from pathlib import Path
8
+
9
+ import requests
10
+
11
+ from .config import ConfigurationError, load_exercise
12
+ from .feedback import construct_feedback, construct_stage_feedback
13
+ from .github import GitHubClient, GitHubError, get_repo
14
+ from .models import ExerciseId
15
+ from .runner import run_exercise
16
+
17
+
18
+ def build_parser() -> ArgumentParser:
19
+ parser = ArgumentParser(description="Judge a program based on the configuration.")
20
+ parser.add_argument("-c", "--config", help="The config path.", default=".minioj/")
21
+ parser.add_argument("-r", "--repo", help="The repo where the triggering PR lives.")
22
+ parser.add_argument(
23
+ "-x",
24
+ "--comment",
25
+ help="The PR comment body that triggers MiniOJ.",
26
+ required=True,
27
+ )
28
+ parser.add_argument(
29
+ "-i",
30
+ "--pull-request",
31
+ type=int,
32
+ help="The ID of the PR that triggers MiniOJ.",
33
+ required=True,
34
+ )
35
+ parser.add_argument(
36
+ "-t", "--token", help="The token for the PR feedback comment.", required=True
37
+ )
38
+ return parser
39
+
40
+
41
+ def main(argv: Sequence[str] | None = None) -> int:
42
+ args = build_parser().parse_args(argv)
43
+ try:
44
+ client = GitHubClient(get_repo(args.repo), args.token)
45
+ exercise_id = ExerciseId.from_comment(args.comment)
46
+ try:
47
+ exercise = load_exercise(Path(args.config), exercise_id)
48
+ except ConfigurationError as error:
49
+ body = construct_feedback(
50
+ (error.title, str(error)),
51
+ append_title=str(error.exercise) if error.exercise is not None else "",
52
+ )
53
+ else:
54
+ results = run_exercise(exercise)
55
+ body = construct_feedback(
56
+ *construct_stage_feedback(*results), append_title=exercise.name
57
+ )
58
+ client.send_comment(args.pull_request, body)
59
+ except (
60
+ OSError,
61
+ ValueError,
62
+ subprocess.SubprocessError,
63
+ requests.RequestException,
64
+ GitHubError,
65
+ ) as error:
66
+ print(f"MiniOJ: {error}", file=sys.stderr)
67
+ return 1
68
+ return 0
minioj/config.py ADDED
@@ -0,0 +1,72 @@
1
+ """Read the existing .minioj/wN/exN/conf.json configuration format."""
2
+
3
+ import json
4
+ from pathlib import Path
5
+
6
+ from .models import Exercise, ExerciseId, Stage
7
+
8
+
9
+ class ConfigurationError(ValueError):
10
+ """A configuration problem that can be reported in PR feedback."""
11
+
12
+ def __init__(
13
+ self,
14
+ title: str,
15
+ message: str = "Contact admins to setup OJ config.",
16
+ exercise: ExerciseId | None = None,
17
+ ) -> None:
18
+ super().__init__(message)
19
+ self.title = title
20
+ self.exercise = exercise
21
+
22
+
23
+ def load_exercise(config_root: Path, exercise_id: ExerciseId) -> Exercise:
24
+ if not config_root.is_dir():
25
+ raise ConfigurationError("OJ config not found")
26
+
27
+ directory = config_root / str(exercise_id)
28
+ if not directory.is_dir():
29
+ raise ConfigurationError(
30
+ "Exercise not found",
31
+ "Check if you typed the right exercise.",
32
+ exercise_id,
33
+ )
34
+
35
+ config_file = directory / "conf.json"
36
+ if not config_file.is_file():
37
+ raise ConfigurationError("Exercise config not found", exercise=exercise_id)
38
+
39
+ try:
40
+ with config_file.open(encoding="utf-8") as config_stream:
41
+ config = json.load(config_stream)
42
+ except (OSError, UnicodeError, ValueError) as error:
43
+ raise ConfigurationError(
44
+ "Exercise config error", exercise=exercise_id
45
+ ) from error
46
+
47
+ if not isinstance(config, dict) or not isinstance(config.get("stages"), list):
48
+ raise ConfigurationError("Exercise config error", exercise=exercise_id)
49
+
50
+ name = config.get("name")
51
+ if not isinstance(name, str):
52
+ name = str(exercise_id)
53
+
54
+ stages = []
55
+ for index, raw_stage in enumerate(config["stages"]):
56
+ if not isinstance(raw_stage, dict):
57
+ continue
58
+ command = raw_stage.get("command")
59
+ if not isinstance(command, str):
60
+ continue
61
+ stage_name = raw_stage.get("name")
62
+ if not isinstance(stage_name, str):
63
+ stage_name = f"Stage {index}"
64
+ stages.append(
65
+ Stage(
66
+ name=stage_name,
67
+ command=command,
68
+ cased=raw_stage.get("cased") is True,
69
+ )
70
+ )
71
+
72
+ return Exercise(exercise_id, name, directory, tuple(stages))
minioj/feedback.py ADDED
@@ -0,0 +1,72 @@
1
+ """Render model objects as Markdown without performing I/O."""
2
+
3
+ from difflib import unified_diff
4
+ from pathlib import Path
5
+
6
+ from .models import CommandResult, StageResult
7
+
8
+
9
+ def construct_feedback(*sections: tuple[str, str], append_title: str = "") -> str:
10
+ body = "## MiniOJ feedback"
11
+ if append_title:
12
+ body += f" - {append_title}"
13
+ body += "\n\nMade with :heart: by FTC Team FFFabulous 19726.\n\n"
14
+ for title, section_body in sections:
15
+ body += f"### {title}\n\n{section_body}\n\n"
16
+ return body
17
+
18
+
19
+ def construct_output_diff(expected: str, actual: str, expected_name: str) -> str:
20
+ lines = unified_diff(
21
+ expected.splitlines(keepends=True),
22
+ actual.splitlines(keepends=True),
23
+ fromfile=expected_name,
24
+ tofile="stdout",
25
+ )
26
+ # difflib leaves unterminated lines as-is; separate them and mark the missing
27
+ # newline just as diff -u does, so a trailing-newline mismatch is visible.
28
+ return "".join(
29
+ line if line.endswith("\n") else f"{line}\n\\n"
30
+ for line in lines
31
+ )
32
+
33
+
34
+ def construct_result_feedback(result: CommandResult) -> str:
35
+ stdout = result.stdout
36
+ language = ""
37
+ note = ""
38
+ if result.case_name is not None:
39
+ expected_name = Path(result.case_name).with_suffix(".out").name
40
+ if result.expected_stdout is None:
41
+ note = (
42
+ f"Expected output missing: `{expected_name}`. "
43
+ "Comparison unavailable.\n\n"
44
+ )
45
+ else:
46
+ language = "diff"
47
+ stdout = construct_output_diff(
48
+ result.expected_stdout, result.stdout, expected_name
49
+ ) or "No differences."
50
+ return (
51
+ f"Status: {result.returncode}\n\n"
52
+ f"<details><summary>Details:</summary>\n\n"
53
+ f"`stdout`:\n\n{note}```{language}\n{stdout}\n```\n\n"
54
+ f"`stderr`: \n\n```\n{result.stderr}\n```\n\n"
55
+ f"</details>\n\n"
56
+ )
57
+
58
+
59
+ def construct_stage_feedback(*stages: StageResult) -> list[tuple[str, str]]:
60
+ sections = []
61
+ for result in stages:
62
+ body = ""
63
+ for index, command in enumerate(result.commands):
64
+ if result.stage.cased:
65
+ body += f"**Case {index}:**\n\n"
66
+ body += construct_result_feedback(command)
67
+ if result.stage.cased:
68
+ passed = command.returncode == 0 and command.output_matches is True
69
+ verdict = "Passed!" if passed else "Failed..."
70
+ body += f"{verdict}\n\n"
71
+ sections.append((result.stage.name, body))
72
+ return sections
minioj/github.py ADDED
@@ -0,0 +1,72 @@
1
+ """Resolve the target repository and publish feedback through GitHub."""
2
+
3
+ import re
4
+ import subprocess
5
+
6
+ import requests
7
+
8
+
9
+ class NoRemoteFoundError(ValueError):
10
+ """No repository could be inferred from Git remotes."""
11
+
12
+
13
+ class GitHubError(RuntimeError):
14
+ def __init__(self, status_code: int) -> None:
15
+ super().__init__(f"GitHub rejected the feedback comment (HTTP {status_code}).")
16
+ self.status_code = status_code
17
+
18
+
19
+ class NotAllowedError(GitHubError):
20
+ pass
21
+
22
+
23
+ class ResourceNotFoundError(GitHubError):
24
+ pass
25
+
26
+
27
+ def get_repo(repo_hint: str | None) -> str:
28
+ if repo_hint is not None:
29
+ return repo_hint
30
+ remotes = subprocess.run(
31
+ ["git", "remote"], capture_output=True, text=True, check=True
32
+ ).stdout.splitlines()
33
+ if not remotes:
34
+ raise NoRemoteFoundError("No Git remote found; supply --repo owner/repository.")
35
+ remote_url = subprocess.run(
36
+ ["git", "remote", "get-url", remotes[0]],
37
+ capture_output=True,
38
+ text=True,
39
+ check=True,
40
+ ).stdout.strip()
41
+ match = re.search(r"[:/]([^/:]+/[^/]+?)(?:\.git)?/?$", remote_url)
42
+ if match is None:
43
+ raise NoRemoteFoundError(
44
+ "Cannot determine the repository from Git; supply --repo owner/repository."
45
+ )
46
+ return match[1]
47
+
48
+
49
+ class GitHubClient:
50
+ def __init__(self, repo: str, token: str) -> None:
51
+ self.repo = repo
52
+ self._token = token
53
+
54
+ def send_comment(self, pull_request: int, body: str) -> None:
55
+ url = f"https://api.github.com/repos/{self.repo}/issues/{pull_request}/comments"
56
+ response = requests.post(
57
+ url,
58
+ headers={
59
+ "Accept": "application/vnd.github+json",
60
+ "Authorization": f"Bearer {self._token}",
61
+ },
62
+ json={"body": body},
63
+ timeout=30,
64
+ )
65
+ if response.status_code in (403, 422):
66
+ raise NotAllowedError(response.status_code)
67
+ if response.status_code in (404, 410):
68
+ raise ResourceNotFoundError(response.status_code)
69
+ response.raise_for_status()
70
+ if response.status_code != 201:
71
+ raise GitHubError(response.status_code)
72
+ print(f"Sent comment to {url}")
minioj/models.py ADDED
@@ -0,0 +1,66 @@
1
+ """Data shared by configuration, execution, and feedback."""
2
+
3
+ import re
4
+ from dataclasses import dataclass
5
+ from pathlib import Path
6
+
7
+
8
+ class ExerciseNotFoundError(ValueError):
9
+ """The triggering comment does not identify an exercise."""
10
+
11
+
12
+ @dataclass(frozen=True)
13
+ class ExerciseId:
14
+ week: int
15
+ exercise: int
16
+
17
+ def __str__(self) -> str:
18
+ return f"w{self.week}/ex{self.exercise}"
19
+
20
+ @classmethod
21
+ def from_comment(cls, comment: str) -> "ExerciseId":
22
+ for line in comment.lower().splitlines():
23
+ if "@minioj-bot" not in line:
24
+ continue
25
+ match = re.search(r"run w([0-9]+)/ex([0-9]+)", line)
26
+ if match is not None:
27
+ return cls(week=int(match[1]), exercise=int(match[2]))
28
+ raise ExerciseNotFoundError(
29
+ "No exercise found; mention @minioj-bot and use 'run w1/ex1'."
30
+ )
31
+
32
+
33
+ @dataclass(frozen=True)
34
+ class Stage:
35
+ name: str
36
+ command: str
37
+ cased: bool = False
38
+
39
+
40
+ @dataclass(frozen=True)
41
+ class Exercise:
42
+ id: ExerciseId
43
+ name: str
44
+ directory: Path
45
+ stages: tuple[Stage, ...]
46
+
47
+
48
+ @dataclass(frozen=True)
49
+ class CommandResult:
50
+ returncode: int
51
+ stdout: str
52
+ stderr: str
53
+ case_name: str | None = None
54
+ expected_stdout: str | None = None
55
+
56
+ @property
57
+ def output_matches(self) -> bool | None:
58
+ if self.expected_stdout is None:
59
+ return None
60
+ return self.stdout == self.expected_stdout
61
+
62
+
63
+ @dataclass(frozen=True)
64
+ class StageResult:
65
+ stage: Stage
66
+ commands: tuple[CommandResult, ...]
minioj/runner.py ADDED
@@ -0,0 +1,68 @@
1
+ """Execute stages in order, optionally once per exercise input file."""
2
+
3
+ import re
4
+ import shlex
5
+ import subprocess
6
+ from pathlib import Path
7
+
8
+ from .models import CommandResult, Exercise, Stage, StageResult
9
+
10
+
11
+ def find_case_files(directory: Path) -> tuple[Path, ...]:
12
+ cases = [
13
+ candidate
14
+ for candidate in directory.iterdir()
15
+ if candidate.is_file() and re.fullmatch(r"case[0-9]+\.in", candidate.name)
16
+ ]
17
+ return tuple(sorted(cases, key=lambda case: (int(case.stem[4:]), case.name)))
18
+
19
+
20
+ def run_stage(stage: Stage, directory: Path) -> StageResult:
21
+ # Commands use shell-style quoting for arguments, but do not start a shell.
22
+ command = shlex.split(stage.command)
23
+ if not command:
24
+ raise ValueError(f"Stage {stage.name!r} has an empty command.")
25
+
26
+ results = []
27
+ if stage.cased:
28
+ for case_file in find_case_files(directory):
29
+ expected_file = case_file.with_suffix(".out")
30
+ expected_stdout = (
31
+ expected_file.read_text(encoding="utf-8")
32
+ if expected_file.is_file()
33
+ else None
34
+ )
35
+ with case_file.open(encoding="utf-8") as case_input:
36
+ process = subprocess.run(
37
+ command,
38
+ stdin=case_input,
39
+ capture_output=True,
40
+ text=True,
41
+ check=False,
42
+ )
43
+ results.append(
44
+ CommandResult(
45
+ process.returncode,
46
+ process.stdout,
47
+ process.stderr,
48
+ case_file.name,
49
+ expected_stdout,
50
+ )
51
+ )
52
+ else:
53
+ process = subprocess.run(
54
+ command,
55
+ stdin=subprocess.DEVNULL,
56
+ capture_output=True,
57
+ text=True,
58
+ check=False,
59
+ )
60
+ results.append(
61
+ CommandResult(process.returncode, process.stdout, process.stderr)
62
+ )
63
+
64
+ return StageResult(stage, tuple(results))
65
+
66
+
67
+ def run_exercise(exercise: Exercise) -> tuple[StageResult, ...]:
68
+ return tuple(run_stage(stage, exercise.directory) for stage in exercise.stages)
@@ -0,0 +1,99 @@
1
+ Metadata-Version: 2.4
2
+ Name: minioj
3
+ Version: 0.1.0
4
+ Summary: Run configured exercise stages and report feedback on GitHub pull requests.
5
+ License-Expression: MIT
6
+ Requires-Python: >=3.10
7
+ Description-Content-Type: text/markdown
8
+ License-File: LICENSE
9
+ Requires-Dist: requests>=2.28
10
+ Dynamic: license-file
11
+
12
+ # MiniOJ
13
+
14
+ MiniOJ reads an exercise configuration, runs its stages, and posts the captured
15
+ exit statuses, stdout, and stderr to a GitHub pull request.
16
+
17
+ ## Install and run
18
+
19
+ Python 3.10 or newer is required. From this checkout:
20
+
21
+ ```sh
22
+ python -m pip install -e .
23
+ minioj --repo owner/repository --pull-request 123 \
24
+ --comment '@minioj-bot run w1/ex1' --token "$GITHUB_TOKEN"
25
+ ```
26
+
27
+ `python -m minioj` and `python main.py` accept the same arguments. `--config`
28
+ defaults to `.minioj/`. When `--repo` is omitted, MiniOJ uses the first Git remote
29
+ in the current working directory.
30
+
31
+ ## Exercise configuration
32
+
33
+ Store each exercise at `.minioj/w<week>/ex<exercise>/conf.json`:
34
+
35
+ ```json
36
+ {
37
+ "name": "Week 1: Hello world",
38
+ "stages": [
39
+ {"name": "Compile", "command": "cc main.c -o solution"},
40
+ {"name": "Run", "command": "./solution", "cased": true}
41
+ ]
42
+ }
43
+ ```
44
+
45
+ An exercise name defaults to `w<week>/ex<exercise>`, and stage names default to
46
+ `Stage <index>` starting at zero. As in the original format, stage entries without
47
+ a string `command` are skipped. Only the JSON boolean `true` enables `cased`.
48
+
49
+ Commands support quoted arguments and run directly without a shell. Pipes,
50
+ redirection, and shell variable expansion require explicitly invoking a shell
51
+ (for example, `sh -c 'echo hello > output.txt'`). Run MiniOJ from the submission
52
+ directory: all stages inherit that working directory and run in config order,
53
+ including stages after a nonzero exit status.
54
+
55
+ A stage normally runs once with closed standard input. A `cased` stage runs once
56
+ for each `case<number>.in` file in the exercise directory, in numeric order. Each
57
+ file supplies stdin, and its matching `case<number>.out` supplies expected stdout
58
+ (for example, `case2.in` pairs with `case2.out`). Feedback numbers the cases from
59
+ zero and shows a unified diff in each case's `stdout` block: `-` lines are expected
60
+ output and `+` lines are actual output. Matching output displays `No differences.`
61
+ Whitespace and trailing newlines matter. If the expected file is missing,
62
+ feedback marks comparison as unavailable and shows the raw stdout instead.
63
+ Process exit status and stderr are reported independently of the comparison.
64
+ Each case ends with `Passed!` or `Failed...` outside its details block. Passing
65
+ requires a zero exit status and matching expected output; missing expected output
66
+ counts as a failure.
67
+
68
+ Configuration commands execute with the permissions of the MiniOJ process. Use
69
+ a separate sandbox when running submissions that you do not trust; this project
70
+ does not implement execution isolation or resource limits.
71
+
72
+ ## Project layout
73
+
74
+ | Module | Responsibility |
75
+ | --- | --- |
76
+ | `minioj/models.py` | Exercise IDs, exercise and stage definitions, command and stage results |
77
+ | `minioj/config.py` | JSON loading, defaults, and configuration errors |
78
+ | `minioj/runner.py` | Case discovery and subprocess execution |
79
+ | `minioj/feedback.py` | Markdown feedback and unified output diffs |
80
+ | `minioj/github.py` | Repository discovery and GitHub comments |
81
+ | `minioj/cli.py` | Arguments and orchestration |
82
+
83
+ The data models are immutable dataclasses. Config parsing produces `Exercise`
84
+ and `Stage` objects; execution produces `StageResult` objects containing
85
+ `CommandResult` objects. Feedback formatting consumes those results without
86
+ performing network or process I/O.
87
+
88
+ ## Tests
89
+
90
+ ```sh
91
+ python -m unittest discover -s tests -v
92
+ ```
93
+
94
+ Tests use temporary exercise directories and local subprocesses. GitHub requests
95
+ are mocked; running the test suite does not publish comments.
96
+
97
+ ## License
98
+
99
+ MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,14 @@
1
+ minioj/__init__.py,sha256=Ay6T2FE_mU4OviN4Y_KF-T7HTVl50TdBqcVFrcC9yn0,75
2
+ minioj/__main__.py,sha256=PSQ4rpL0dG6f-qH4N7H-gD9igQkdHzH4yVZDcW8lfZo,80
3
+ minioj/cli.py,sha256=ithEVFfdqHWGKZqTXqEIHy49zcoC4a20L_tetHiVRk8,2230
4
+ minioj/config.py,sha256=Fp6THf62tTdVYzmk_1UZ1lkKXzg5VsIyGOwSqRYFb4w,2277
5
+ minioj/feedback.py,sha256=wD19Z_3ovrk5G7UHNOBivwm84ZQuwAo6zbG7hp8ubA4,2581
6
+ minioj/github.py,sha256=U-dapE2FH9_wASFO6zh4nZ9nNOhQzQEELH-gC5b0E0w,2220
7
+ minioj/models.py,sha256=9JgMSHfk8VQl6BklcNXGgzszg-kD0iyStowXqb-rS2s,1546
8
+ minioj/runner.py,sha256=u7K3oP0_nbgpDEbECLtrW5uuOhngpq-3m2S_CGSZ7xM,2187
9
+ minioj-0.1.0.dist-info/licenses/LICENSE,sha256=DkKBT7fn-IGtmGOB3DJYnSYStMSB1Cts_jHLdwrv_gc,1076
10
+ minioj-0.1.0.dist-info/METADATA,sha256=9j4ayn0AwqcTFBQl2Lz-FdOplfcsDprgLNDXeGDSrEE,3870
11
+ minioj-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ minioj-0.1.0.dist-info/entry_points.txt,sha256=jVp8GOe9wtCZObniftg2WjUaCAecVcMaFGoitGSJw78,43
13
+ minioj-0.1.0.dist-info/top_level.txt,sha256=yalMxEX6qPcadzoTFp2GDiuEHchB-ABGdFVZZGiLLc4,7
14
+ minioj-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ minioj = minioj.cli:main
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 MiniOJ contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ minioj