asciidoc-pubkit 1.3.0 → 1.4.0
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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +55 -1
- data/README.md +34 -4
- data/data/writing/en/criteria.md +33 -0
- data/data/writing/ja/criteria.md +189 -2
- data/docs/image-commands.md +165 -0
- data/docs/installation.md +5 -1
- data/docs/prose-evaluation.md +57 -3
- data/docs/review-workflow.md +46 -1
- data/docs/writing.md +63 -0
- data/examples/skills/review-asciidoc-manuscript/SKILL.md +5 -0
- data/lib/asciidoc_pubkit/cli.rb +9 -3
- data/lib/asciidoc_pubkit/document_commands.rb +1 -0
- data/lib/asciidoc_pubkit/image_commands.rb +364 -0
- data/lib/asciidoc_pubkit/japanese_verification.rb +70 -0
- data/lib/asciidoc_pubkit/session.rb +25 -3
- data/lib/asciidoc_pubkit.rb +3 -1
- metadata +10 -7
data/docs/prose-evaluation.md
CHANGED
|
@@ -1,5 +1,45 @@
|
|
|
1
1
|
# Prose evaluation
|
|
2
2
|
|
|
3
|
+
## Japanese verification workflow evaluation (1.3.1)
|
|
4
|
+
|
|
5
|
+
Japanese change-review regressions check that edits are visible without lexical
|
|
6
|
+
candidates, split paragraphs are not falsely paired, protected text is masked
|
|
7
|
+
for cues, scope boundaries remain intact, and saved verification records detect
|
|
8
|
+
later source/session/implementation changes. Real MeCab tests and literal-mode
|
|
9
|
+
tests have different coverage. They do not measure editorial improvement.
|
|
10
|
+
|
|
11
|
+
For a future explicitly authorized model trial, retain the actual source and
|
|
12
|
+
revision, saved session and final verification report, criteria/implementation
|
|
13
|
+
identities, exact model/host configuration and raw tool execution records.
|
|
14
|
+
Measure separately (1) whether required checks ran on the delivered source,
|
|
15
|
+
(2) candidate detection against independently annotated changed passages, and
|
|
16
|
+
(3) readability and fact retention judged from actual revisions. Include
|
|
17
|
+
actor additions, same-number scope changes, condition reversals and legitimate
|
|
18
|
+
procedure/warning repetitions, including changes without lexical cues. Compare
|
|
19
|
+
compatible configurations over repeated trials; adjudicate reviewer disagreements.
|
|
20
|
+
A fresh report, fewer candidates or a successful freshness comparison cannot
|
|
21
|
+
substitute for those judgments. No such model trial has been run for this change.
|
|
22
|
+
|
|
23
|
+
Design reference: [yomiyasu 2.0.1](https://github.com/nanaism/yomiyasu/tree/v2.0.1),
|
|
24
|
+
especially its final-source record, revision-comparison procedure and documented
|
|
25
|
+
limits. This implementation uses pubkit's own selected AsciiDoc scope and
|
|
26
|
+
preservation contracts; upstream performance and model-evaluation results are
|
|
27
|
+
not measurements of pubkit.
|
|
28
|
+
|
|
29
|
+
<a id="explicit-actor-names-unreleased"></a>
|
|
30
|
+
|
|
31
|
+
## Explicit actor names (v1.4.0)
|
|
32
|
+
|
|
33
|
+
Ten additional calibration pairs compare explicit role names with the supported
|
|
34
|
+
system, internal component, execution environment or communication peer. They
|
|
35
|
+
include valid defined roles, accurate return verbs, unintended self-handoffs,
|
|
36
|
+
unsupported owners and a rule applier incorrectly made its configuration owner.
|
|
37
|
+
The existing retained-transfer example now defines its actor first; its historical
|
|
38
|
+
ID remains unchanged. Judge actor specificity independently from verb accuracy.
|
|
39
|
+
Tests cover fixture integrity, writing and saved prompts in all three review
|
|
40
|
+
scopes, immutable session criteria and unchanged sources. They do not invoke an
|
|
41
|
+
AI evaluator, measure editing quality or establish semantic correctness.
|
|
42
|
+
|
|
3
43
|
## Actor clarity comparisons (v1.2.3)
|
|
4
44
|
|
|
5
45
|
Twelve additional calibration pairs cover conditional actor changes, user refusal
|
|
@@ -16,8 +56,8 @@ criteria changes against a project-defined baseline. Keep detection performance,
|
|
|
16
56
|
readability, and meaning preservation separate so that a clearer rewrite cannot
|
|
17
57
|
hide a lost condition or invented fact.
|
|
18
58
|
|
|
19
|
-
This guide describes
|
|
20
|
-
`technical-prose-v3` corpus and
|
|
59
|
+
This guide describes version 1.4.0, including the
|
|
60
|
+
`technical-prose-v3` corpus and 165 revision calibration pairs. The sentence-ending
|
|
21
61
|
criteria and twelve additional pairs, plus the flow guidance and four further
|
|
22
62
|
pairs, are included in version 1.2.0.
|
|
23
63
|
The evaluation runner is not an
|
|
@@ -85,7 +125,7 @@ of Japanese writing.
|
|
|
85
125
|
| [prose_benchmark.ja.adoc](../test/fixtures/prose_benchmark.ja.adoc) | 26 paragraphs used as the actual AsciiDoc input |
|
|
86
126
|
| [prose_benchmark.ja.json](../test/fixtures/prose_benchmark.ja.json) | Matching paragraph IDs and text, 11 annotated detector targets, and preservation checklists |
|
|
87
127
|
| [prose_benchmark.yml](../test/fixtures/prose_benchmark.yml) | Fixed empty configuration that isolates the benchmark from discovered manuscript settings |
|
|
88
|
-
| [prose_evaluation.ja.json](../test/fixtures/prose_evaluation.ja.json) | Detection examples and
|
|
128
|
+
| [prose_evaluation.ja.json](../test/fixtures/prose_evaluation.ja.json) | Detection examples and 165 manual revision pairs with expected `accept`, `reject`, or `needs-evidence` dispositions |
|
|
89
129
|
|
|
90
130
|
The corpus includes framing such as `重要なのは`, metaphorical operations such
|
|
91
131
|
as `地味に効く`, inflected and negative forms, and repeated endings. Controls
|
|
@@ -442,3 +482,17 @@ of criteria to writing and saved review prompts, including historical-session
|
|
|
442
482
|
preservation; they do not establish AI judgment accuracy. The updated judge rubric
|
|
443
483
|
requires a compatible fresh baseline for future AI comparisons. No AI evaluation
|
|
444
484
|
was run; improvement remains unmeasured and `meaning_verified` remains false.
|
|
485
|
+
|
|
486
|
+
|
|
487
|
+
<a id="retention-and-representation-comparisons-unreleased"></a>
|
|
488
|
+
|
|
489
|
+
## Retention and representation comparisons (v1.4.0)
|
|
490
|
+
|
|
491
|
+
`test/fixtures/retention_representation_wording.ja.json` contains 24 manually
|
|
492
|
+
labeled comparisons covering input inclusion, storage, recording, assignment,
|
|
493
|
+
retained history/locks/snapshots, result/state indication and valid notation.
|
|
494
|
+
Rejection examples cover invented persistence, lost identity or lifetime,
|
|
495
|
+
capability changes, unknown results treated as failure, and stronger evidence
|
|
496
|
+
or causation claims. The fixture is separate from the evaluation runner's corpus.
|
|
497
|
+
Its tests check data integrity and saved-prompt behavior, not the correctness of
|
|
498
|
+
these language judgments. No model judge or AI-quality measurement is run.
|
data/docs/review-workflow.md
CHANGED
|
@@ -335,10 +335,55 @@ not read candidate decision records or certify editorial completion. A passing
|
|
|
335
335
|
mechanical result must be reported separately from the reviewer's quality and
|
|
336
336
|
completion assessment.
|
|
337
337
|
|
|
338
|
+
#### Japanese change review and final-source records (1.3.1)
|
|
339
|
+
|
|
340
|
+
Japanese sessions additionally return `japanese_change_review` before the final
|
|
341
|
+
`verification_record` in the JSON result. `changes` contains each changed file's
|
|
342
|
+
complete selected text before and after editing, with source lines on each side.
|
|
343
|
+
These are file-level inventories, not guessed paragraph or sentence pairs.
|
|
344
|
+
Prose, heading and list sessions retain their separate edit scopes. Unselected
|
|
345
|
+
and protected blocks are not included; inline protected tokens remain visible
|
|
346
|
+
in excerpts but are masked when collecting lexical cues.
|
|
347
|
+
|
|
348
|
+
Each changed file includes advisory `review_candidates` for changed inventories
|
|
349
|
+
of Japanese negation, condition, certainty, capability and actor/topic expressions.
|
|
350
|
+
`actor-topic` is a lexical cue around `は` and `が`, not grammatical subject/object
|
|
351
|
+
analysis. Inflections and paraphrases can be missed, legitimate rewrites can
|
|
352
|
+
produce candidates, and equal counts can hide changes between sentences. These
|
|
353
|
+
candidates do not change exit codes or certify meaning. Review all before/after
|
|
354
|
+
text, including changes without candidates. Numeric notices retain their existing
|
|
355
|
+
meaning. No score formula changes are included.
|
|
356
|
+
|
|
357
|
+
Save the completed check, inspect the change review, and compare the current
|
|
358
|
+
sources with that saved result immediately before delivery:
|
|
359
|
+
|
|
360
|
+
```sh
|
|
361
|
+
asciidoc-pubkit review verify .pubkit/review --output verification-final.json
|
|
362
|
+
# Read the report and complete the editorial comparison before delivery.
|
|
363
|
+
asciidoc-pubkit review verify .pubkit/review --checked-report verification-final.json
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
`--checked-report` accepts a successful Japanese report containing a
|
|
367
|
+
`pubkit-ja-verification-v1` record. It reruns preservation checks and compares
|
|
368
|
+
source hashes, the session manifest hash, tool version and Ruby implementation
|
|
369
|
+
fingerprint with the record. Changed sources, session or implementation produce
|
|
370
|
+
`checked-report-stale` and exit 1. A malformed, missing, unsuccessful or legacy
|
|
371
|
+
report, or use with an English session, is an input error (exit 2). The original
|
|
372
|
+
baseline is never reset. If sources change after checking, save a new report to
|
|
373
|
+
a new filename, inspect it and compare again. Do not edit after the final check.
|
|
374
|
+
The command never overwrites an existing output or checked report.
|
|
375
|
+
|
|
376
|
+
The record identifies the source content inspected by the checker. It is not
|
|
377
|
+
tamper-proof, a human approval record, proof that the report was read, or a
|
|
378
|
+
semantic review result. No timestamp or hook enforces delivery order. A report
|
|
379
|
+
can match an earlier identical source state; a newer scan cannot prove
|
|
380
|
+
preservation against a discarded baseline. English verification output is
|
|
381
|
+
unchanged. All results retain `meaning_verified: false`.
|
|
382
|
+
|
|
338
383
|
| Exit code | Meaning |
|
|
339
384
|
| --- | --- |
|
|
340
385
|
| `0` | Command completed; verification found no mechanical violations |
|
|
341
|
-
| `1` | Verification found protected-content, structure, source, or
|
|
386
|
+
| `1` | Verification found protected-content, structure, source, parsing, or checked-report freshness issues |
|
|
342
387
|
| `2` | Invalid arguments, configuration, session, scan input, or output failure |
|
|
343
388
|
|
|
344
389
|
[Back to README](../README.md)
|
data/docs/writing.md
CHANGED
|
@@ -1,5 +1,13 @@
|
|
|
1
1
|
# Writing commands
|
|
2
2
|
|
|
3
|
+
Version 1.4.0 extends the [actor criteria](../data/writing/ja/criteria.md#compare-explicit-actor-names-with-the-actual-responsibility)
|
|
4
|
+
to explicit but vague role names such as `実行側` and `処理側`. Compare the
|
|
5
|
+
evidenced system, internal component, execution environment or communication
|
|
6
|
+
peer, and judge actor specificity separately from verb accuracy. Recheck the
|
|
7
|
+
whole sentence for self-handoffs and changed modifier or configuration ownership.
|
|
8
|
+
These are contextual instructions, with no new detector or replacement rules;
|
|
9
|
+
saved sessions retain their original criteria.
|
|
10
|
+
|
|
3
11
|
The v1.2.3 [actor-change criteria](../data/writing/ja/criteria.md#clarify-omitted-subjects-when-actors-change)
|
|
4
12
|
compare omitted and explicit subjects across clauses, sentences and table roles.
|
|
5
13
|
They distinguish requesting, approving, executing and investigating, preserve
|
|
@@ -241,3 +249,58 @@ their scope. The bundled review skill routes these assignments to the saved
|
|
|
241
249
|
criteria. Writing commands and new heading, prose and list sessions include the
|
|
242
250
|
guidance; existing sessions keep their original criteria. Regression checks cover
|
|
243
251
|
criteria delivery and source preservation, not measured AI proofreading quality.
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
<a id="retention-and-representation-wording-unreleased"></a>
|
|
255
|
+
|
|
256
|
+
## Retention and representation wording (v1.4.0)
|
|
257
|
+
|
|
258
|
+
The shared Japanese criteria now compare `保持` with input inclusion, container
|
|
259
|
+
storage, recording and attribute assignment, and `表す` with state indication,
|
|
260
|
+
evidence and contents. Preserve valid retention of history, original values,
|
|
261
|
+
locks and snapshots, and valid representation by symbols, JSON, code or graphs.
|
|
262
|
+
See [retention](../data/writing/ja/criteria.md#distinguish-retention-from-inclusion-storage-and-assignment)
|
|
263
|
+
and [representation](../data/writing/ja/criteria.md#distinguish-representation-from-evidence-and-state-indication).
|
|
264
|
+
|
|
265
|
+
These are contextual comparisons, not blanket replacements or new detector rules.
|
|
266
|
+
They reach writing commands and new Japanese heading, prose and list sessions;
|
|
267
|
+
existing sessions keep their saved criteria. English guidance, scoring and
|
|
268
|
+
mechanical verification are unchanged. Manual comparison fixtures and delivery
|
|
269
|
+
regressions do not measure AI editing quality or semantic correctness.
|
|
270
|
+
|
|
271
|
+
|
|
272
|
+
<a id="explanation-presentation-and-state-indication-unreleased"></a>
|
|
273
|
+
|
|
274
|
+
## Explanation, presentation and state indication (v1.4.0)
|
|
275
|
+
|
|
276
|
+
The [shared Japanese criteria](../data/writing/ja/criteria.md#distinguish-explanation-presentation-and-state-indication)
|
|
277
|
+
compare `示す` by its role: announcing an explanation, stating technical behavior,
|
|
278
|
+
displaying or recording information, presenting an actual figure/table/example,
|
|
279
|
+
or indicating a value's meaning. Compare whole paragraphs, including repeated
|
|
280
|
+
`説明し…示します` guidance and method/outcome relationships. Preserve valid
|
|
281
|
+
presentation and state-indication wording; do not replace every use with
|
|
282
|
+
`説明します` or strengthen an inspection into a guarantee.
|
|
283
|
+
|
|
284
|
+
Writing commands and new Japanese heading, prose and list sessions include the
|
|
285
|
+
guidance; existing sessions retain their saved criteria. No detector, automatic
|
|
286
|
+
replacement, score or semantic-verification behavior changes. Delivery tests
|
|
287
|
+
check prompt contents and source preservation, not AI proofreading quality.
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
<a id="json-identifiers-and-explanatory-strings-unreleased"></a>
|
|
291
|
+
|
|
292
|
+
## JSON identifiers and explanatory strings (v1.4.0)
|
|
293
|
+
|
|
294
|
+
The [Japanese](../data/writing/ja/criteria.md#preserve-json-identifiers-and-explanatory-strings)
|
|
295
|
+
and [English](../data/writing/en/criteria.md#preserve-json-identifiers-and-explanatory-strings)
|
|
296
|
+
criteria distinguish JSON keys, schema keywords and technical values from
|
|
297
|
+
natural-language descriptions. Compare examples with their explanations,
|
|
298
|
+
including field/value ownership, nesting, required arguments, string/object
|
|
299
|
+
representation and request/result IDs. Follow the book's notation rather than
|
|
300
|
+
requiring emphasis or monospace. JSON/code blocks remain protected in prose
|
|
301
|
+
review; translation of explanatory strings requires its own assigned scope.
|
|
302
|
+
|
|
303
|
+
Writing commands and new review sessions include these comparisons. Existing
|
|
304
|
+
sessions retain their saved criteria. This is prompt guidance, not an automatic
|
|
305
|
+
JSON inventory or rewriting command; parsing and preservation checks do not
|
|
306
|
+
establish semantic correctness or translation fidelity.
|
|
@@ -80,6 +80,11 @@ without forcing repetition. Inspect related authorized table/figure roles in the
|
|
|
80
80
|
own scopes; report missing actor evidence rather than assigning a plausible role.
|
|
81
81
|
If the selected CLI lacks the actor-change examples, report that criteria limitation
|
|
82
82
|
and retain saved sessions; keep the canonical examples in pubkit.
|
|
83
|
+
Review explicit actor names through those criteria too, recording the supported
|
|
84
|
+
responsibility and recipient rather than treating a written subject as sufficient.
|
|
85
|
+
Assess actor specificity and verb accuracy separately and compare the full revised
|
|
86
|
+
sentence before finalizing the decision; preserve defined roles and unresolved
|
|
87
|
+
owners. Do not copy book-specific actor replacements into this shared skill.
|
|
83
88
|
|
|
84
89
|
For an assigned content guide or learning objective, record the whole-paragraph
|
|
85
90
|
viewpoint and any repeated guidance along with the source, alternative and reason.
|
data/lib/asciidoc_pubkit/cli.rb
CHANGED
|
@@ -14,6 +14,9 @@ module AsciidocPubkit
|
|
|
14
14
|
document info FILE Extract book metadata
|
|
15
15
|
document check-xrefs FILE Report unresolved local cross-references
|
|
16
16
|
document index DIRECTORY Generate an English-title AsciiDoc index
|
|
17
|
+
image list FILE List images referenced by an AsciiDoc document
|
|
18
|
+
image stats FILE Summarize document-referenced image dimensions and sizes
|
|
19
|
+
image width FILE Preview or explicitly apply display widths to source image macros
|
|
17
20
|
writing criteria Print the shared Japanese or English prose criteria
|
|
18
21
|
writing prompt Generate a technical writing prompt
|
|
19
22
|
review scan FILE Collect Japanese or English prose, headings, or list text and review candidates
|
|
@@ -31,7 +34,7 @@ module AsciidocPubkit
|
|
|
31
34
|
Use --lang ja (default) or en with writing commands and review commands. Other
|
|
32
35
|
languages and regional tags are unsupported and return an error.
|
|
33
36
|
skill install and upgrade write only the selected skill directory.
|
|
34
|
-
|
|
37
|
+
replace apply and image width --in-place explicitly edit manuscript sources. review score --agent explicitly invokes a
|
|
35
38
|
local Codex or Claude CLI, which may connect to its configured AI service.
|
|
36
39
|
TEXT
|
|
37
40
|
|
|
@@ -46,11 +49,12 @@ module AsciidocPubkit
|
|
|
46
49
|
out.puts VERSION
|
|
47
50
|
return 0
|
|
48
51
|
end
|
|
49
|
-
if args.empty? || args == ['--help'] || args == ['-h'] || %w[review writing replace document skill].any? { |group| args == [group, '--help'] }
|
|
52
|
+
if args.empty? || args == ['--help'] || args == ['-h'] || %w[review writing replace document skill image].any? { |group| args == [group, '--help'] }
|
|
50
53
|
out.puts HELP
|
|
51
54
|
return 0
|
|
52
55
|
end
|
|
53
56
|
group, command = args.shift(2)
|
|
57
|
+
return ImageCommands.run(command, args, out: out, err: err) if group == 'image'
|
|
54
58
|
return SkillCommands.run(command, args, out: out, err: err) if group == 'skill'
|
|
55
59
|
if group == 'document' && %w[toc info check-xrefs index].include?(command)
|
|
56
60
|
return DocumentCommands.run(command, args, out: out, err: err)
|
|
@@ -97,6 +101,8 @@ module AsciidocPubkit
|
|
|
97
101
|
elsif group == 'review' && command == 'prompt'
|
|
98
102
|
opts.on('--mode MODE', 'revise (default) or diagnose') { |v| options[:mode] = v }
|
|
99
103
|
opts.on('--view VIEW', 'full (default) or outline; outline requires a heading session') { |v| options[:view] = v }
|
|
104
|
+
elsif group == 'review' && command == 'verify'
|
|
105
|
+
opts.on('--checked-report FILE', 'Compare current Japanese sources and session with a saved successful verification report') { |v| options[:checked_report] = v }
|
|
100
106
|
end
|
|
101
107
|
opts.on('-h', '--help', 'Show command help') { options[:help] = true }
|
|
102
108
|
end
|
|
@@ -168,7 +174,7 @@ module AsciidocPubkit
|
|
|
168
174
|
output(session.prompt(options.fetch(:mode, 'revise'), view: options.fetch(:view, 'full')), options[:output], out)
|
|
169
175
|
return 0
|
|
170
176
|
end
|
|
171
|
-
result = session.verify
|
|
177
|
+
result = session.verify(checked_report: options[:checked_report])
|
|
172
178
|
output(JSON.pretty_generate(result) + "\n", options[:output], out)
|
|
173
179
|
result['passed'] ? 0 : 1
|
|
174
180
|
rescue Error, OptionParser::ParseError, SystemCallError, Psych::Exception, ArgumentError => e
|
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'open3'
|
|
4
|
+
require 'tempfile'
|
|
5
|
+
|
|
6
|
+
module AsciidocPubkit
|
|
7
|
+
# Only document-referenced block images are selected; image pixels stay unchanged.
|
|
8
|
+
class ImageCommands
|
|
9
|
+
ARTWORK = %w[cover* chapter-* part-* profile*].freeze
|
|
10
|
+
MACRO = /\A(image::[^\[]+\[)(.*)(\][ \t]*)(\r?\n)?\z/
|
|
11
|
+
|
|
12
|
+
class SourceLoader < DocumentCommands
|
|
13
|
+
attr_reader :sources, :image_sources, :source_key
|
|
14
|
+
|
|
15
|
+
def initialize(options, err)
|
|
16
|
+
super
|
|
17
|
+
@sources, @image_sources = {}, {}
|
|
18
|
+
@source_key = "pubkit-image-source-#{object_id}"
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
def load(file)
|
|
22
|
+
raise Error, "Symlinked source is unsupported: #{file}" if File.symlink?(file)
|
|
23
|
+
owner = self
|
|
24
|
+
super(file) do |doc|
|
|
25
|
+
# Asciidoctor can lose a cursor at an include boundary after lookahead.
|
|
26
|
+
# Attach provenance in memory before parsing, never to the source file.
|
|
27
|
+
doc.reader.define_singleton_method(:process_line) do |line|
|
|
28
|
+
location = cursor
|
|
29
|
+
result = super(line)
|
|
30
|
+
annotated = owner.annotate(result, location)
|
|
31
|
+
replace_next_line(annotated) if annotated && annotated != result
|
|
32
|
+
annotated
|
|
33
|
+
end
|
|
34
|
+
end
|
|
35
|
+
end
|
|
36
|
+
|
|
37
|
+
def annotate(line, cursor)
|
|
38
|
+
return line unless line && !line.include?(@source_key) && (match = line.match(MACRO))
|
|
39
|
+
token = @image_sources.length.to_s
|
|
40
|
+
@image_sources[token] = { 'file' => cursor.file && File.realpath(cursor.file), 'line' => cursor.lineno }
|
|
41
|
+
attrs = match[2].empty? ? "#{@source_key}=#{token}" : "#{match[2]},#{@source_key}=#{token}"
|
|
42
|
+
match[1] + attrs + match[3] + match[4].to_s
|
|
43
|
+
end
|
|
44
|
+
|
|
45
|
+
def check_source(file, root)
|
|
46
|
+
super
|
|
47
|
+
raise Error, "Symlinked source is unsupported: #{file}" if File.symlink?(file)
|
|
48
|
+
@sources[File.realpath(file)] ||= AsciidocPubkit.read_text(file)
|
|
49
|
+
end
|
|
50
|
+
end
|
|
51
|
+
|
|
52
|
+
def self.run(command, args, out:, err:)
|
|
53
|
+
raise Error, 'Unknown image command. Use --help.' unless %w[list stats width].include?(command)
|
|
54
|
+
options = { attributes: {}, exclude: [], ratio: 0.8, min: 40.0, max: 100.0 }
|
|
55
|
+
parser = OptionParser.new do |opts|
|
|
56
|
+
opts.banner = "Usage: asciidoc-pubkit image #{command} DOCUMENT.adoc [options]"
|
|
57
|
+
opts.on('--base-dir DIR', 'Local include and image boundary (default: document directory)') { |v| options[:base_dir] = v }
|
|
58
|
+
opts.on('-a', '--attribute NAME=VALUE', 'Asciidoctor attribute; repeat as needed') do |v|
|
|
59
|
+
key, value = v.split('=', 2)
|
|
60
|
+
raise Error, 'Attribute name cannot be empty.' if key.empty?
|
|
61
|
+
raise Error, 'Remote includes are not supported.' if key == 'allow-uri-read'
|
|
62
|
+
options[:attributes][key] = value || ''
|
|
63
|
+
end
|
|
64
|
+
opts.on('--only FILE', 'Select image references from one included source file') { |v| options[:only] = v }
|
|
65
|
+
opts.on('--exclude GLOB', 'Exclude image basename or document-relative path; repeatable') { |v| options[:exclude] << v }
|
|
66
|
+
opts.on('--include-artwork', 'Include block images matching default artwork exclusions') { options[:artwork] = true }
|
|
67
|
+
opts.on('--json', 'Print a structured report') { options[:json] = true }
|
|
68
|
+
if command == 'width'
|
|
69
|
+
opts.on('--height-width-ratio NUMBER', Float, 'Target image height / text width (default: 0.8)') { |v| options[:ratio] = v }
|
|
70
|
+
opts.on('--min-width PERCENT', Float, 'Minimum display width (default: 40)') { |v| options[:min] = v }
|
|
71
|
+
opts.on('--max-width PERCENT', Float, 'Maximum display width (default: 100)') { |v| options[:max] = v }
|
|
72
|
+
opts.on('--dry-run', 'Preview only (default)') { options[:dry_run] = true }
|
|
73
|
+
opts.on('--diff', 'Preview a unified source diff') { options[:diff] = true }
|
|
74
|
+
opts.on('--in-place', 'Explicitly update source image macros') { options[:in_place] = true }
|
|
75
|
+
end
|
|
76
|
+
opts.on('-h', '--help', 'Show command help') { options[:help] = true }
|
|
77
|
+
end
|
|
78
|
+
parser.parse!(args)
|
|
79
|
+
if options[:help]
|
|
80
|
+
out.puts parser
|
|
81
|
+
return 0
|
|
82
|
+
end
|
|
83
|
+
raise Error, 'Exactly one AsciiDoc document is required.' unless args.length == 1
|
|
84
|
+
raise Error, 'Expected an AsciiDoc document (.adoc or .asciidoc), not an image.' unless %w[.adoc .asciidoc].include?(File.extname(args.first).downcase)
|
|
85
|
+
if command == 'width'
|
|
86
|
+
unless [options[:ratio], options[:min], options[:max]].all?(&:finite?) &&
|
|
87
|
+
options[:ratio].positive? && options[:min].positive? && options[:min] <= options[:max] && options[:max] <= 100
|
|
88
|
+
raise Error, 'Require finite ratio > 0 and 0 < min-width <= max-width <= 100.'
|
|
89
|
+
end
|
|
90
|
+
raise Error, '--in-place cannot be combined with --dry-run or --diff.' if options[:in_place] && (options[:dry_run] || options[:diff])
|
|
91
|
+
raise Error, '--diff cannot be combined with --json.' if options[:diff] && options[:json]
|
|
92
|
+
end
|
|
93
|
+
tool = new(args.first, options, err)
|
|
94
|
+
report = command == 'stats' ? tool.stats : command == 'width' ? tool.width : tool.report
|
|
95
|
+
if options[:diff]
|
|
96
|
+
out.write(tool.diff)
|
|
97
|
+
elsif options[:json]
|
|
98
|
+
out.puts JSON.pretty_generate(report)
|
|
99
|
+
else
|
|
100
|
+
out.write(tool.format(command, report))
|
|
101
|
+
end
|
|
102
|
+
0
|
|
103
|
+
end
|
|
104
|
+
|
|
105
|
+
def initialize(entry, options, err)
|
|
106
|
+
@options, @err = options, err
|
|
107
|
+
@entry = File.realpath(entry)
|
|
108
|
+
@root = File.realpath(options[:base_dir] || File.dirname(@entry))
|
|
109
|
+
@loader = SourceLoader.new(options, err)
|
|
110
|
+
@doc = @loader.load(entry)
|
|
111
|
+
@sources = @loader.sources
|
|
112
|
+
@only = options[:only] && File.realpath(options[:only])
|
|
113
|
+
raise Error, '--only must be a source included in the parsed document.' if @only && !@sources.key?(@only)
|
|
114
|
+
@images, @excluded, @references, @changes, @revised = {}, [], [], [], {}
|
|
115
|
+
covers = %w[front-cover-image back-cover-image title-logo-image].filter_map do |key|
|
|
116
|
+
value = @doc.attr(key)
|
|
117
|
+
next unless value && (match = value.match(/\Aimage:{1,2}([^\[]+)\[/))
|
|
118
|
+
resolve_image(match[1], @doc.attr('imagesdir', '')) unless remote?(match[1]) || remote?(@doc.attr('imagesdir', ''))
|
|
119
|
+
end
|
|
120
|
+
@doc.find_by(context: :image).each do |node|
|
|
121
|
+
target, directory = node.attr('target'), node.attr('imagesdir', '')
|
|
122
|
+
cursor = node.source_location
|
|
123
|
+
provenance = @loader.image_sources[node.attr(@loader.source_key)] || {}
|
|
124
|
+
reference = { 'file' => provenance['file'] || (cursor&.file && File.realpath(cursor.file)),
|
|
125
|
+
'line' => provenance['line'] || cursor&.lineno,
|
|
126
|
+
'target' => target, 'current_scaledwidth' => node.attr('scaledwidth'),
|
|
127
|
+
'mapped' => !provenance.empty? }
|
|
128
|
+
@references << reference
|
|
129
|
+
reason = if remote?(target) || remote?(directory)
|
|
130
|
+
'remote image'
|
|
131
|
+
elsif @only && reference['file'] != @only
|
|
132
|
+
'outside --only source'
|
|
133
|
+
end
|
|
134
|
+
unless reason
|
|
135
|
+
path = resolve_image(target, directory)
|
|
136
|
+
reference['image'] = path
|
|
137
|
+
relative = Pathname.new(path).relative_path_from(Pathname.new(@root)).to_s
|
|
138
|
+
if !options[:artwork] && (covers.include?(path) || ARTWORK.any? { |glob| File.fnmatch?(glob, File.basename(path)) })
|
|
139
|
+
reason = 'artwork'
|
|
140
|
+
elsif options[:exclude].any? { |glob| File.fnmatch?(glob, File.basename(path)) || File.fnmatch?(glob, relative, File::FNM_PATHNAME | File::FNM_EXTGLOB) }
|
|
141
|
+
reason = 'excluded by pattern'
|
|
142
|
+
end
|
|
143
|
+
end
|
|
144
|
+
if reason
|
|
145
|
+
reference['excluded'] = reason
|
|
146
|
+
@excluded << reference
|
|
147
|
+
next
|
|
148
|
+
end
|
|
149
|
+
path = reference.fetch('image')
|
|
150
|
+
raise Error, "Image does not exist: #{path}" unless File.file?(path)
|
|
151
|
+
real = File.realpath(path)
|
|
152
|
+
raise Error, "Image is outside the base directory: #{path}" unless inside?(real)
|
|
153
|
+
reference['image'] = real
|
|
154
|
+
image = @images[real] ||= inspect_image(real)
|
|
155
|
+
reference['editable'] = !!source_macro(reference)
|
|
156
|
+
image['references'] << reference
|
|
157
|
+
end
|
|
158
|
+
end
|
|
159
|
+
|
|
160
|
+
def remote?(path)
|
|
161
|
+
Asciidoctor::Helpers.uriish?(path.to_s)
|
|
162
|
+
end
|
|
163
|
+
|
|
164
|
+
def inside?(path)
|
|
165
|
+
path.start_with?(@root.end_with?('/') ? @root : @root + '/')
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
def resolve_image(target, directory)
|
|
169
|
+
path = File.expand_path(target, File.expand_path(directory, @root))
|
|
170
|
+
raise Error, "Image is outside the base directory: #{path}" unless inside?(path)
|
|
171
|
+
path
|
|
172
|
+
end
|
|
173
|
+
|
|
174
|
+
def inspect_image(path)
|
|
175
|
+
command = executable?('magick') ? %w[magick identify] : ['identify']
|
|
176
|
+
stdout, stderr, status = Open3.capture3(*command, '-format', '%w %h\n', '--', path)
|
|
177
|
+
raise Error, "Cannot inspect image #{path}: #{stderr.strip}" unless status.success?
|
|
178
|
+
lines = stdout.lines
|
|
179
|
+
match = lines.length == 1 && lines.first.match(/\A([1-9][0-9]*) ([1-9][0-9]*)\s*\z/)
|
|
180
|
+
raise Error, "Unsupported image dimensions or multiple frames: #{path}" unless match
|
|
181
|
+
w, h = match[1].to_i, match[2].to_i
|
|
182
|
+
{ 'path' => path, 'width' => w, 'height' => h, 'aspect_ratio' => w.fdiv(h),
|
|
183
|
+
'bytes' => File.size(path), 'references' => [] }
|
|
184
|
+
end
|
|
185
|
+
|
|
186
|
+
def executable?(name)
|
|
187
|
+
ENV.fetch('PATH', '').split(File::PATH_SEPARATOR).any? { |dir| File.file?(path = File.join(dir, name)) && File.executable?(path) }
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def report
|
|
191
|
+
{ 'document' => @entry, 'base_dir' => @root, 'images' => @images.values,
|
|
192
|
+
'image_count' => @images.length, 'reference_count' => @images.values.sum { |i| i['references'].length },
|
|
193
|
+
'excluded' => @excluded, 'scope' => 'parsed block image macros; inline images are not included' }
|
|
194
|
+
end
|
|
195
|
+
|
|
196
|
+
def stats
|
|
197
|
+
result = report.reject { |key, _| key == 'images' }
|
|
198
|
+
result['total_bytes'] = @images.values.sum { |i| i['bytes'] }
|
|
199
|
+
%w[width height aspect_ratio bytes].each do |key|
|
|
200
|
+
values = @images.values.map { |i| i[key] }
|
|
201
|
+
result[key] = { 'min' => values.min, 'max' => values.max,
|
|
202
|
+
'mean' => values.empty? ? nil : values.sum.fdiv(values.length) }
|
|
203
|
+
end
|
|
204
|
+
result
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
def source_macro(reference)
|
|
208
|
+
file, line = reference.values_at('file', 'line')
|
|
209
|
+
return unless reference['mapped'] && file && line && @sources.key?(file)
|
|
210
|
+
@sources[file].lines[line - 1]&.match(MACRO)
|
|
211
|
+
end
|
|
212
|
+
|
|
213
|
+
# Split only top-level attribute commas, retaining the original spelling.
|
|
214
|
+
def attributes(text)
|
|
215
|
+
parts, start, quote, index = [], 0, nil, 0
|
|
216
|
+
while index < text.length
|
|
217
|
+
char = text[index]
|
|
218
|
+
if char == '\\'
|
|
219
|
+
index += 2
|
|
220
|
+
next
|
|
221
|
+
elsif quote
|
|
222
|
+
quote = nil if char == quote
|
|
223
|
+
elsif (char == '"' || char == "'") && text[start...index].strip.match?(/\A(?:[^\s=,]+\s*=\s*)?\z/)
|
|
224
|
+
quote = char
|
|
225
|
+
elsif char == ','
|
|
226
|
+
parts << text[start...index]
|
|
227
|
+
start = index + 1
|
|
228
|
+
end
|
|
229
|
+
index += 1
|
|
230
|
+
end
|
|
231
|
+
raise Error, 'Unclosed quote in source image attributes.' if quote
|
|
232
|
+
parts << text[start..]
|
|
233
|
+
end
|
|
234
|
+
|
|
235
|
+
def with_width(match, width)
|
|
236
|
+
parts = attributes(match[2])
|
|
237
|
+
positions = parts.each_index.select { |index| parts[index].match?(/\A\s*scaledwidth\s*=/) }
|
|
238
|
+
raise Error, 'Duplicate scaledwidth attributes are unsupported.' if positions.length > 1
|
|
239
|
+
value = "#{number(width)}%"
|
|
240
|
+
if positions.empty?
|
|
241
|
+
content = match[2].empty? ? "scaledwidth=#{value}" : "#{match[2]},scaledwidth=#{value}"
|
|
242
|
+
else
|
|
243
|
+
index = positions.first
|
|
244
|
+
token = parts[index].match(/\A(\s*scaledwidth\s*=\s*)(.*?)(\s*)\z/)
|
|
245
|
+
old = token[2]
|
|
246
|
+
value = "#{old[0]}#{value}#{old[0]}" if ['"', "'"].include?(old[0]) && old[-1] == old[0]
|
|
247
|
+
parts[index] = token[1] + value + token[3]
|
|
248
|
+
content = parts.join(',')
|
|
249
|
+
end
|
|
250
|
+
match[1] + content + match[3] + match[4].to_s
|
|
251
|
+
end
|
|
252
|
+
|
|
253
|
+
def number(value)
|
|
254
|
+
value.to_s.delete_suffix('.0')
|
|
255
|
+
end
|
|
256
|
+
|
|
257
|
+
def width
|
|
258
|
+
desired = {}
|
|
259
|
+
@images.each_value do |image|
|
|
260
|
+
raw = 100 * @options[:ratio] * image['aspect_ratio']
|
|
261
|
+
value = [[[[raw, @options[:min]].max, @options[:max]].min.round(1), @options[:min]].max, @options[:max]].min
|
|
262
|
+
image['width_percent'], image['minimum_limited'] = value, raw < @options[:min]
|
|
263
|
+
image['references'].each do |reference|
|
|
264
|
+
match = source_macro(reference)
|
|
265
|
+
raise Error, "Cannot safely map image macro: #{reference['file']}:#{reference['line']}" unless match
|
|
266
|
+
before = match[0]
|
|
267
|
+
after = with_width(match, value)
|
|
268
|
+
file, line = reference.values_at('file', 'line')
|
|
269
|
+
key = [file, line]
|
|
270
|
+
prior = desired[key]
|
|
271
|
+
raise Error, "Reused source image needs conflicting widths: #{file}:#{line}" if prior && prior != after
|
|
272
|
+
desired[key] = after
|
|
273
|
+
next if prior || before == after
|
|
274
|
+
if @excluded.any? { |r| r['file'] == file && r['line'] == line }
|
|
275
|
+
raise Error, "Reused source also has excluded references: #{file}:#{line}"
|
|
276
|
+
end
|
|
277
|
+
@changes << { 'file' => file, 'line' => line, 'image' => image['path'],
|
|
278
|
+
'width_percent' => value, 'before' => before, 'after' => after }
|
|
279
|
+
end
|
|
280
|
+
end
|
|
281
|
+
@changes.group_by { |c| c['file'] }.each do |file, changes|
|
|
282
|
+
lines = @sources.fetch(file).lines
|
|
283
|
+
changes.each { |c| lines[c['line'] - 1] = c['after'] }
|
|
284
|
+
@revised[file] = lines.join
|
|
285
|
+
end
|
|
286
|
+
apply if @options[:in_place]
|
|
287
|
+
report.merge('settings' => { 'height_width_ratio' => @options[:ratio], 'min_width' => @options[:min], 'max_width' => @options[:max] },
|
|
288
|
+
'changes' => @changes, 'changed_files' => @revised.keys, 'applied' => !!@options[:in_place])
|
|
289
|
+
end
|
|
290
|
+
|
|
291
|
+
def unchanged?(file, content)
|
|
292
|
+
File.file?(file) && !File.symlink?(file) && File.realpath(file) == file && File.binread(file) == content.b
|
|
293
|
+
end
|
|
294
|
+
|
|
295
|
+
def apply
|
|
296
|
+
staged, backups, installed = {}, {}, []
|
|
297
|
+
begin
|
|
298
|
+
@sources.each do |file, content|
|
|
299
|
+
raise Error, "Source changed during analysis: #{file}" unless unchanged?(file, content)
|
|
300
|
+
end
|
|
301
|
+
@revised.each do |file, content|
|
|
302
|
+
raise Error, "Source changed during analysis: #{file}" unless unchanged?(file, @sources.fetch(file))
|
|
303
|
+
staged[file] = stage(file, content)
|
|
304
|
+
backups[file] = stage(file, @sources.fetch(file))
|
|
305
|
+
end
|
|
306
|
+
@revised.each_key do |file|
|
|
307
|
+
raise Error, "Source changed during analysis: #{file}" unless unchanged?(file, @sources.fetch(file))
|
|
308
|
+
File.rename(staged.fetch(file).path, file)
|
|
309
|
+
installed << file
|
|
310
|
+
end
|
|
311
|
+
rescue StandardError
|
|
312
|
+
installed.reverse_each do |file|
|
|
313
|
+
# Do not replace another writer's changes while rolling back.
|
|
314
|
+
if File.binread(file) == @revised.fetch(file).b
|
|
315
|
+
File.rename(backups.fetch(file).path, file)
|
|
316
|
+
end
|
|
317
|
+
end
|
|
318
|
+
raise
|
|
319
|
+
ensure
|
|
320
|
+
(staged.values + backups.values).each(&:close!)
|
|
321
|
+
end
|
|
322
|
+
end
|
|
323
|
+
|
|
324
|
+
def stage(file, content)
|
|
325
|
+
temp = Tempfile.new(['.pubkit-image-', '.adoc'], File.dirname(file))
|
|
326
|
+
temp.binmode
|
|
327
|
+
temp.write(content)
|
|
328
|
+
temp.flush
|
|
329
|
+
temp.chmod(File.stat(file).mode & 0o777)
|
|
330
|
+
temp
|
|
331
|
+
rescue StandardError
|
|
332
|
+
temp&.close!
|
|
333
|
+
raise
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
def diff
|
|
337
|
+
@revised.map do |file, content|
|
|
338
|
+
relative = Pathname.new(file).relative_path_from(Pathname.new(@root)).to_s
|
|
339
|
+
Tempfile.create('pubkit-before') do |a|
|
|
340
|
+
Tempfile.create('pubkit-after') do |b|
|
|
341
|
+
a.write(@sources.fetch(file)); a.flush
|
|
342
|
+
b.write(content); b.flush
|
|
343
|
+
stdout, stderr, status = Open3.capture3('diff', '-u', '--label', "a/#{relative}", '--label', "b/#{relative}", a.path, b.path)
|
|
344
|
+
raise Error, stderr unless [0, 1].include?(status.exitstatus)
|
|
345
|
+
stdout
|
|
346
|
+
end
|
|
347
|
+
end
|
|
348
|
+
end.join
|
|
349
|
+
end
|
|
350
|
+
|
|
351
|
+
def format(command, result)
|
|
352
|
+
if command == 'stats'
|
|
353
|
+
"Images: #{result['image_count']}; references: #{result['reference_count']}; bytes: #{result['total_bytes']}\n" +
|
|
354
|
+
%w[width height aspect_ratio bytes].map { |key| "#{key}: #{result[key].to_json}\n" }.join
|
|
355
|
+
else
|
|
356
|
+
result['images'].map do |image|
|
|
357
|
+
"#{image['path']}\t#{image['width']}x#{image['height']}\taspect=#{image['aspect_ratio'].round(4)}\tbytes=#{image['bytes']}\treferences=#{image['references'].length}" +
|
|
358
|
+
(command == 'width' ? "\twidth=#{number(image['width_percent'])}%" : '') + "\n"
|
|
359
|
+
end.join + "Images: #{result['image_count']}; references: #{result['reference_count']}; excluded: #{@excluded.length}" +
|
|
360
|
+
(command == 'width' ? "; changes: #{@changes.length}; #{result['applied'] ? 'applied' : 'preview'}" : '') + "\n"
|
|
361
|
+
end
|
|
362
|
+
end
|
|
363
|
+
end
|
|
364
|
+
end
|