62 lines
1.8 KiB
Python
62 lines
1.8 KiB
Python
import argparse
|
|
import json
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
from datalad_core.repo import Worktree
|
|
from datalad_core.runners import call_git, call_git_success
|
|
|
|
|
|
def main() -> None:
|
|
parser = argparse.ArgumentParser(
|
|
description='Write a JSON record as a deterministically formatted file.'
|
|
)
|
|
parser.add_argument('--mirror', type=Path, default='mirror')
|
|
parser.add_argument('--message', type=str, default=None)
|
|
args = parser.parse_args()
|
|
|
|
wt = Worktree.from_path(Path.cwd())
|
|
mirror_spec_path = wt.path / args.mirror
|
|
|
|
record_str = sys.stdin.read()
|
|
if not record_str.strip():
|
|
return
|
|
record = json.loads(record_str)
|
|
|
|
record_id = record['id']
|
|
mirror_spec_path.mkdir(parents=True, exist_ok=True)
|
|
|
|
output_path = mirror_spec_path / f'{record_id}.json'
|
|
|
|
with output_path.open('w', encoding='utf-8') as file:
|
|
json.dump(
|
|
record,
|
|
file,
|
|
ensure_ascii=False,
|
|
indent=2,
|
|
sort_keys=True,
|
|
)
|
|
file.write('\n')
|
|
|
|
msg = args.message or f'chore: update {record_id}'
|
|
# capture Git output so standard output carries only the stored record
|
|
call_git(['add', '--', str(output_path)], cwd=wt.path, capture_output=True)
|
|
# `git commit -- <path>` fails when the path has no staged changes;
|
|
# only commit when the record was actually changed
|
|
if not call_git_success(
|
|
['diff', '--cached', '--quiet', '--', str(output_path)],
|
|
cwd=wt.path,
|
|
):
|
|
call_git(
|
|
[
|
|
'commit',
|
|
'-m',
|
|
msg,
|
|
'--',
|
|
str(output_path),
|
|
],
|
|
cwd=wt.path,
|
|
capture_output=True,
|
|
)
|
|
# the file already ends with a newline; do not add another one
|
|
print(output_path.read_text(), end='') # noqa: T201
|