asciidoc-pubkit 1.3.1 → 1.4.1
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 +59 -1
- data/README.md +32 -3
- data/data/writing/en/criteria.md +33 -0
- data/data/writing/ja/criteria.md +163 -2
- data/docs/image-commands.md +317 -0
- data/docs/installation.md +5 -1
- data/docs/prose-evaluation.md +31 -3
- data/docs/writing.md +63 -0
- data/examples/skills/review-asciidoc-manuscript/SKILL.md +5 -0
- data/lib/asciidoc_pubkit/cli.rb +7 -2
- data/lib/asciidoc_pubkit/document_commands.rb +1 -0
- data/lib/asciidoc_pubkit/image_commands.rb +524 -0
- data/lib/asciidoc_pubkit.rb +2 -1
- metadata +9 -7
|
@@ -0,0 +1,524 @@
|
|
|
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 scale find].include?(command)
|
|
54
|
+
options = { attributes: {}, include: [], exclude: [], ratio: 0.8, min: 40.0, max: 100.0, mode: 'automatic', scale_factor: 0.9, height_factor: 1.0, area_factor: 0.8 }
|
|
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('--include GLOB', 'Select matching image basename or document-relative path; repeatable') { |v| options[:include] << v }
|
|
66
|
+
opts.on('--exclude GLOB', 'Exclude image basename or document-relative path; repeatable') { |v| options[:exclude] << v }
|
|
67
|
+
opts.on('--include-artwork', 'Include block images matching default artwork exclusions') { options[:artwork] = true }
|
|
68
|
+
opts.on('--json', 'Print a structured report') { options[:json] = true }
|
|
69
|
+
add_find_options(opts, options) if command == 'find'
|
|
70
|
+
if command == 'scale'
|
|
71
|
+
opts.on('--mode MODE', 'Sizing mode: automatic (default) or book') { |v| options[:mode] = v; options[:automatic_options] = true }
|
|
72
|
+
opts.on('--scale-factor NUMBER', Float, 'Book-mode overall multiplier (default: 0.9)') { |v| options[:scale_factor] = v; options[:book_options] = true }
|
|
73
|
+
opts.on('--height-factor NUMBER', Float, 'Book-mode median height multiplier (default: 1)') { |v| options[:height_factor] = v; options[:book_options] = true }
|
|
74
|
+
opts.on('--area-factor NUMBER', Float, 'Book-mode median area multiplier (default: 0.8)') { |v| options[:area_factor] = v; options[:book_options] = true }
|
|
75
|
+
opts.on('--width PERCENT', Float, 'Fixed scaledwidth percentage instead of automatic calculation') { |v| options[:width] = v }
|
|
76
|
+
opts.on('--height-width-ratio NUMBER', Float, 'Target image height / text width (default: 0.8)') { |v| options[:ratio] = v; options[:automatic_options] = true }
|
|
77
|
+
opts.on('--min-width PERCENT', Float, 'Minimum display width (default: 40)') { |v| options[:min] = v; options[:automatic_options] = true }
|
|
78
|
+
opts.on('--max-width PERCENT', Float, 'Maximum display width (default: 100)') { |v| options[:max] = v; options[:automatic_options] = true }
|
|
79
|
+
opts.on('--dry-run', 'Preview only (default)') { options[:dry_run] = true }
|
|
80
|
+
opts.on('--diff', 'Preview a unified source diff') { options[:diff] = true }
|
|
81
|
+
opts.on('--in-place', 'Explicitly update source image macros') { options[:in_place] = true }
|
|
82
|
+
end
|
|
83
|
+
opts.on('-h', '--help', 'Show command help') { options[:help] = true }
|
|
84
|
+
end
|
|
85
|
+
parser.parse!(args)
|
|
86
|
+
if options[:help]
|
|
87
|
+
out.puts parser
|
|
88
|
+
return 0
|
|
89
|
+
end
|
|
90
|
+
raise Error, 'Exactly one AsciiDoc document is required.' unless args.length == 1
|
|
91
|
+
raise Error, 'Expected an AsciiDoc document (.adoc or .asciidoc), not an image.' unless %w[.adoc .asciidoc].include?(File.extname(args.first).downcase)
|
|
92
|
+
if command == 'scale'
|
|
93
|
+
raise Error, 'Mode must be automatic or book.' unless %w[automatic book].include?(options[:mode])
|
|
94
|
+
if options[:book_options] && (options[:mode] != 'book' || options[:width])
|
|
95
|
+
raise Error, 'Book factor options require --mode book without --width.'
|
|
96
|
+
end
|
|
97
|
+
if options[:mode] == 'book'
|
|
98
|
+
raise Error, '--only cannot be used with book mode; calibrate the entire selected image set.' if options[:only]
|
|
99
|
+
unless %i[scale_factor height_factor area_factor].all? { |key| options[key].finite? && options[key].positive? && options[key] <= 1 }
|
|
100
|
+
raise Error, 'Book factors must be finite and greater than 0 and at most 1.'
|
|
101
|
+
end
|
|
102
|
+
end
|
|
103
|
+
if options[:width]
|
|
104
|
+
raise Error, 'Require finite 0 < width <= 100.' unless options[:width].finite? && options[:width].positive? && options[:width] <= 100
|
|
105
|
+
raise Error, '--width cannot be combined with automatic sizing options.' if options[:automatic_options]
|
|
106
|
+
end
|
|
107
|
+
unless [options[:ratio], options[:min], options[:max]].all?(&:finite?) &&
|
|
108
|
+
options[:ratio].positive? && options[:min].positive? && options[:min] <= options[:max] && options[:max] <= 100
|
|
109
|
+
raise Error, 'Require finite ratio > 0 and 0 < min-width <= max-width <= 100.'
|
|
110
|
+
end
|
|
111
|
+
raise Error, '--in-place cannot be combined with --dry-run or --diff.' if options[:in_place] && (options[:dry_run] || options[:diff])
|
|
112
|
+
raise Error, '--diff cannot be combined with --json.' if options[:diff] && options[:json]
|
|
113
|
+
end
|
|
114
|
+
validate_find_options(options) if command == 'find'
|
|
115
|
+
tool = new(args.first, options, err)
|
|
116
|
+
report = command == 'stats' ? tool.stats : command == 'scale' ? tool.scale : command == 'find' ? tool.find : tool.report
|
|
117
|
+
if options[:diff]
|
|
118
|
+
out.write(tool.diff)
|
|
119
|
+
elsif options[:json]
|
|
120
|
+
out.puts JSON.pretty_generate(report)
|
|
121
|
+
else
|
|
122
|
+
out.write(tool.format(command, report))
|
|
123
|
+
end
|
|
124
|
+
0
|
|
125
|
+
end
|
|
126
|
+
|
|
127
|
+
FIND_METRICS = {
|
|
128
|
+
'bytes' => 'bytes', 'pixels' => 'pixels', 'pixel-width' => 'width',
|
|
129
|
+
'pixel-height' => 'height', 'aspect-ratio' => 'aspect_ratio'
|
|
130
|
+
}.freeze
|
|
131
|
+
|
|
132
|
+
def self.add_find_options(opts, options)
|
|
133
|
+
options[:filters] = {}
|
|
134
|
+
FIND_METRICS.each_key do |metric|
|
|
135
|
+
%w[min max].each do |bound|
|
|
136
|
+
name = "#{bound}-#{metric}"
|
|
137
|
+
opts.on("--#{name} VALUE", "Inclusive #{bound}imum #{metric}") do |value|
|
|
138
|
+
parsed = if metric == 'bytes'
|
|
139
|
+
match = value.match(/\A([0-9]+)(B|KB|MB|KiB|MiB)?\z/)
|
|
140
|
+
raise Error, "Invalid byte size: #{value}" unless match
|
|
141
|
+
match[1].to_i * { nil => 1, 'B' => 1, 'KB' => 1000, 'MB' => 1000**2,
|
|
142
|
+
'KiB' => 1024, 'MiB' => 1024**2 }.fetch(match[2])
|
|
143
|
+
elsif metric == 'aspect-ratio'
|
|
144
|
+
Float(value)
|
|
145
|
+
else
|
|
146
|
+
raise Error, "#{name} must be a positive integer." unless value.match?(/\A[0-9]+\z/)
|
|
147
|
+
value.to_i
|
|
148
|
+
end
|
|
149
|
+
options[:filters][name] = parsed
|
|
150
|
+
end
|
|
151
|
+
end
|
|
152
|
+
end
|
|
153
|
+
opts.on('--portrait', 'Select height > width; exclude squares') { options[:portrait] = true }
|
|
154
|
+
opts.on('--landscape', 'Select width > height; exclude squares') { options[:landscape] = true }
|
|
155
|
+
opts.on('--sort METRIC', "Sort by #{FIND_METRICS.keys.join(', ')} (default: document order)") { |v| options[:sort] = v }
|
|
156
|
+
opts.on('--order ORDER', 'asc or desc (default with --sort: desc)') { |v| options[:order] = v }
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def self.validate_find_options(options)
|
|
160
|
+
raise Error, '--portrait and --landscape cannot be combined.' if options[:portrait] && options[:landscape]
|
|
161
|
+
raise Error, "Unknown sort metric: #{options[:sort]}" if options[:sort] && !FIND_METRICS.key?(options[:sort])
|
|
162
|
+
raise Error, 'Order must be asc or desc.' if options[:order] && !%w[asc desc].include?(options[:order])
|
|
163
|
+
raise Error, '--order requires --sort.' if options[:order] && !options[:sort]
|
|
164
|
+
options[:filters].each do |name, value|
|
|
165
|
+
unless value.finite? && (name.end_with?('-bytes') ? value >= 0 : value > 0)
|
|
166
|
+
raise Error, "#{name} must be finite and #{name.end_with?('-bytes') ? 'nonnegative' : 'positive'}."
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
FIND_METRICS.each_key do |metric|
|
|
170
|
+
lower, upper = options[:filters].values_at("min-#{metric}", "max-#{metric}")
|
|
171
|
+
raise Error, "min-#{metric} cannot exceed max-#{metric}." if lower && upper && lower > upper
|
|
172
|
+
end
|
|
173
|
+
end
|
|
174
|
+
|
|
175
|
+
def initialize(entry, options, err)
|
|
176
|
+
@options, @err = options, err
|
|
177
|
+
@entry = File.realpath(entry)
|
|
178
|
+
@root = File.realpath(options[:base_dir] || File.dirname(@entry))
|
|
179
|
+
@loader = SourceLoader.new(options, err)
|
|
180
|
+
@doc = @loader.load(entry)
|
|
181
|
+
@sources = @loader.sources
|
|
182
|
+
@only = options[:only] && File.realpath(options[:only])
|
|
183
|
+
raise Error, '--only must be a source included in the parsed document.' if @only && !@sources.key?(@only)
|
|
184
|
+
@images, @excluded, @references, @changes, @revised = {}, [], [], [], {}
|
|
185
|
+
covers = %w[front-cover-image back-cover-image title-logo-image].filter_map do |key|
|
|
186
|
+
value = @doc.attr(key)
|
|
187
|
+
next unless value && (match = value.match(/\Aimage:{1,2}([^\[]+)\[/))
|
|
188
|
+
resolve_image(match[1], @doc.attr('imagesdir', '')) unless remote?(match[1]) || remote?(@doc.attr('imagesdir', ''))
|
|
189
|
+
end
|
|
190
|
+
@doc.find_by(context: :image).each do |node|
|
|
191
|
+
target, directory = node.attr('target'), node.attr('imagesdir', '')
|
|
192
|
+
cursor = node.source_location
|
|
193
|
+
provenance = @loader.image_sources[node.attr(@loader.source_key)] || {}
|
|
194
|
+
reference = { 'file' => provenance['file'] || (cursor&.file && File.realpath(cursor.file)),
|
|
195
|
+
'line' => provenance['line'] || cursor&.lineno,
|
|
196
|
+
'target' => target, 'current_scaledwidth' => node.attr('scaledwidth'),
|
|
197
|
+
'mapped' => !provenance.empty? }
|
|
198
|
+
@references << reference
|
|
199
|
+
reason = if remote?(target) || remote?(directory)
|
|
200
|
+
'remote image'
|
|
201
|
+
elsif @only && reference['file'] != @only
|
|
202
|
+
'outside --only source'
|
|
203
|
+
end
|
|
204
|
+
unless reason
|
|
205
|
+
path = resolve_image(target, directory)
|
|
206
|
+
reference['image'] = path
|
|
207
|
+
relative = Pathname.new(path).relative_path_from(Pathname.new(@root)).to_s
|
|
208
|
+
included = options.fetch(:include, []).any? { |glob| matches?(glob, path, relative) }
|
|
209
|
+
if options[:exclude].any? { |glob| matches?(glob, path, relative) }
|
|
210
|
+
reason = 'excluded by pattern'
|
|
211
|
+
elsif !options.fetch(:include, []).empty? && !included
|
|
212
|
+
reason = 'outside --include patterns'
|
|
213
|
+
elsif !included && !options[:artwork] && (covers.include?(path) || ARTWORK.any? { |glob| File.fnmatch?(glob, File.basename(path)) })
|
|
214
|
+
reason = 'artwork'
|
|
215
|
+
end
|
|
216
|
+
end
|
|
217
|
+
if reason
|
|
218
|
+
reference['excluded'] = reason
|
|
219
|
+
@excluded << reference
|
|
220
|
+
next
|
|
221
|
+
end
|
|
222
|
+
path = reference.fetch('image')
|
|
223
|
+
raise Error, "Image does not exist: #{path}" unless File.file?(path)
|
|
224
|
+
real = File.realpath(path)
|
|
225
|
+
raise Error, "Image is outside the base directory: #{path}" unless inside?(real)
|
|
226
|
+
reference['image'] = real
|
|
227
|
+
image = @images[real] ||= inspect_image(real)
|
|
228
|
+
reference['editable'] = !!source_macro(reference)
|
|
229
|
+
image['references'] << reference
|
|
230
|
+
end
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
def matches?(glob, path, relative)
|
|
234
|
+
File.fnmatch?(glob, File.basename(path)) || File.fnmatch?(glob, relative, File::FNM_PATHNAME | File::FNM_EXTGLOB)
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
def remote?(path)
|
|
238
|
+
Asciidoctor::Helpers.uriish?(path.to_s)
|
|
239
|
+
end
|
|
240
|
+
|
|
241
|
+
def inside?(path)
|
|
242
|
+
path.start_with?(@root.end_with?('/') ? @root : @root + '/')
|
|
243
|
+
end
|
|
244
|
+
|
|
245
|
+
def resolve_image(target, directory)
|
|
246
|
+
path = File.expand_path(target, File.expand_path(directory, @root))
|
|
247
|
+
raise Error, "Image is outside the base directory: #{path}" unless inside?(path)
|
|
248
|
+
path
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
def inspect_image(path)
|
|
252
|
+
command = executable?('magick') ? %w[magick identify] : ['identify']
|
|
253
|
+
stdout, stderr, status = Open3.capture3(*command, '-format', '%w %h\n', '--', path)
|
|
254
|
+
raise Error, "Cannot inspect image #{path}: #{stderr.strip}" unless status.success?
|
|
255
|
+
lines = stdout.lines
|
|
256
|
+
match = lines.length == 1 && lines.first.match(/\A([1-9][0-9]*) ([1-9][0-9]*)\s*\z/)
|
|
257
|
+
raise Error, "Unsupported image dimensions or multiple frames: #{path}" unless match
|
|
258
|
+
w, h = match[1].to_i, match[2].to_i
|
|
259
|
+
{ 'path' => path, 'width' => w, 'height' => h, 'aspect_ratio' => w.fdiv(h),
|
|
260
|
+
'bytes' => File.size(path), 'references' => [] }
|
|
261
|
+
end
|
|
262
|
+
|
|
263
|
+
def executable?(name)
|
|
264
|
+
ENV.fetch('PATH', '').split(File::PATH_SEPARATOR).any? { |dir| File.file?(path = File.join(dir, name)) && File.executable?(path) }
|
|
265
|
+
end
|
|
266
|
+
|
|
267
|
+
def report
|
|
268
|
+
{ 'document' => @entry, 'base_dir' => @root, 'images' => @images.values,
|
|
269
|
+
'image_count' => @images.length, 'reference_count' => @images.values.sum { |i| i['references'].length },
|
|
270
|
+
'excluded' => @excluded, 'scope' => 'parsed block image macros; inline images are not included' }
|
|
271
|
+
end
|
|
272
|
+
|
|
273
|
+
def find
|
|
274
|
+
result = report
|
|
275
|
+
images = @images.values.map { |image| image.merge('pixels' => image['width'] * image['height']) }
|
|
276
|
+
images.select! do |image|
|
|
277
|
+
(!@options[:portrait] || image['height'] > image['width']) &&
|
|
278
|
+
(!@options[:landscape] || image['width'] > image['height']) &&
|
|
279
|
+
@options[:filters].all? do |name, threshold|
|
|
280
|
+
bound, metric = name.split('-', 2)
|
|
281
|
+
value = image.fetch(FIND_METRICS.fetch(metric))
|
|
282
|
+
bound == 'min' ? value >= threshold : value <= threshold
|
|
283
|
+
end
|
|
284
|
+
end
|
|
285
|
+
if @options[:sort]
|
|
286
|
+
key = FIND_METRICS.fetch(@options[:sort])
|
|
287
|
+
direction = @options[:order] == 'asc' ? 1 : -1
|
|
288
|
+
images = images.each_with_index.sort_by { |image, index| [direction * image[key], index] }.map(&:first)
|
|
289
|
+
end
|
|
290
|
+
result.merge('images' => images, 'selected_image_count' => result['image_count'],
|
|
291
|
+
'selected_reference_count' => result['reference_count'],
|
|
292
|
+
'image_count' => images.length, 'reference_count' => images.sum { |i| i['references'].length },
|
|
293
|
+
'filters' => @options[:filters].merge('portrait' => !!@options[:portrait], 'landscape' => !!@options[:landscape]),
|
|
294
|
+
'sort' => @options[:sort], 'order' => @options[:sort] && (@options[:order] || 'desc'))
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
def stats
|
|
298
|
+
result = report.reject { |key, _| key == 'images' }
|
|
299
|
+
result['total_bytes'] = @images.values.sum { |i| i['bytes'] }
|
|
300
|
+
%w[width height aspect_ratio bytes].each do |key|
|
|
301
|
+
values = @images.values.map { |i| i[key] }
|
|
302
|
+
result[key] = { 'min' => values.min, 'max' => values.max,
|
|
303
|
+
'mean' => values.empty? ? nil : values.sum.fdiv(values.length) }
|
|
304
|
+
end
|
|
305
|
+
result
|
|
306
|
+
end
|
|
307
|
+
|
|
308
|
+
def source_macro(reference)
|
|
309
|
+
file, line = reference.values_at('file', 'line')
|
|
310
|
+
return unless reference['mapped'] && file && line && @sources.key?(file)
|
|
311
|
+
@sources[file].lines[line - 1]&.match(MACRO)
|
|
312
|
+
end
|
|
313
|
+
|
|
314
|
+
# Split only top-level attribute commas, retaining the original spelling.
|
|
315
|
+
def attributes(text)
|
|
316
|
+
parts, start, quote, index = [], 0, nil, 0
|
|
317
|
+
while index < text.length
|
|
318
|
+
char = text[index]
|
|
319
|
+
if char == '\\'
|
|
320
|
+
index += 2
|
|
321
|
+
next
|
|
322
|
+
elsif quote
|
|
323
|
+
quote = nil if char == quote
|
|
324
|
+
elsif (char == '"' || char == "'") && text[start...index].strip.match?(/\A(?:[^\s=,]+\s*=\s*)?\z/)
|
|
325
|
+
quote = char
|
|
326
|
+
elsif char == ','
|
|
327
|
+
parts << text[start...index]
|
|
328
|
+
start = index + 1
|
|
329
|
+
end
|
|
330
|
+
index += 1
|
|
331
|
+
end
|
|
332
|
+
raise Error, 'Unclosed quote in source image attributes.' if quote
|
|
333
|
+
parts << text[start..]
|
|
334
|
+
end
|
|
335
|
+
|
|
336
|
+
def with_width(match, width)
|
|
337
|
+
parts = attributes(match[2])
|
|
338
|
+
positions = parts.each_index.select { |index| parts[index].match?(/\A\s*scaledwidth\s*=/) }
|
|
339
|
+
raise Error, 'Duplicate scaledwidth attributes are unsupported.' if positions.length > 1
|
|
340
|
+
value = "#{number(width)}%"
|
|
341
|
+
if positions.empty?
|
|
342
|
+
content = match[2].empty? ? "scaledwidth=#{value}" : "#{match[2]},scaledwidth=#{value}"
|
|
343
|
+
else
|
|
344
|
+
index = positions.first
|
|
345
|
+
token = parts[index].match(/\A(\s*scaledwidth\s*=\s*)(.*?)(\s*)\z/)
|
|
346
|
+
old = token[2]
|
|
347
|
+
value = "#{old[0]}#{value}#{old[0]}" if ['"', "'"].include?(old[0]) && old[-1] == old[0]
|
|
348
|
+
parts[index] = token[1] + value + token[3]
|
|
349
|
+
content = parts.join(',')
|
|
350
|
+
end
|
|
351
|
+
match[1] + content + match[3] + match[4].to_s
|
|
352
|
+
end
|
|
353
|
+
|
|
354
|
+
def number(value)
|
|
355
|
+
value.to_s.delete_suffix('.0')
|
|
356
|
+
end
|
|
357
|
+
|
|
358
|
+
def automatic_width(image)
|
|
359
|
+
raw = 100 * @options[:ratio] * image['aspect_ratio']
|
|
360
|
+
[[[[raw, @options[:min]].max, @options[:max]].min.round(1), @options[:min]].max, @options[:max]].min
|
|
361
|
+
end
|
|
362
|
+
|
|
363
|
+
def median(values)
|
|
364
|
+
return nil if values.empty?
|
|
365
|
+
values = values.sort
|
|
366
|
+
middle = values.length / 2
|
|
367
|
+
values.length.odd? ? values[middle] : (values[middle - 1] + values[middle]) / 2.0
|
|
368
|
+
end
|
|
369
|
+
|
|
370
|
+
def book_calibration
|
|
371
|
+
images = @images.values
|
|
372
|
+
heights = images.map { |i| automatic_width(i) / 100.0 / i['aspect_ratio'] }
|
|
373
|
+
areas = images.map { |i| (automatic_width(i) / 100.0)**2 / i['aspect_ratio'] }
|
|
374
|
+
height, area = median(heights), median(areas)
|
|
375
|
+
{ 'image_count' => images.length, 'median_height' => height, 'median_area' => area,
|
|
376
|
+
'height_cap' => height && height * @options[:height_factor],
|
|
377
|
+
'area_cap' => area && area * @options[:area_factor],
|
|
378
|
+
'scale_factor' => @options[:scale_factor], 'height_factor' => @options[:height_factor],
|
|
379
|
+
'area_factor' => @options[:area_factor], 'units' => 'height: text width; area: text width squared' }
|
|
380
|
+
end
|
|
381
|
+
|
|
382
|
+
def scale
|
|
383
|
+
desired = {}
|
|
384
|
+
book = @options[:mode] == 'book'
|
|
385
|
+
calibration = book_calibration if book
|
|
386
|
+
conflicts = []
|
|
387
|
+
@images.each_value do |image|
|
|
388
|
+
raw = 100 * @options[:ratio] * image['aspect_ratio']
|
|
389
|
+
baseline = automatic_width(image)
|
|
390
|
+
value = @options[:width] || baseline
|
|
391
|
+
image['width_percent'], image['minimum_limited'] = value, !@options[:width] && raw < @options[:min]
|
|
392
|
+
if book
|
|
393
|
+
ratio = image['aspect_ratio']
|
|
394
|
+
candidate = [baseline * @options[:scale_factor],
|
|
395
|
+
100 * calibration['height_cap'] * ratio,
|
|
396
|
+
100 * Math.sqrt(calibration['area_cap'] * ratio)].min.floor(1)
|
|
397
|
+
image['baseline_width_percent'] = baseline
|
|
398
|
+
image['proposed_width_percent'] = candidate
|
|
399
|
+
if candidate < @options[:min] || candidate <= 0
|
|
400
|
+
image['requires_review'] = true
|
|
401
|
+
conflicts << { 'image' => image['path'], 'proposed_width_percent' => candidate,
|
|
402
|
+
'min_width' => @options[:min], 'reason' => 'minimum width conflicts with book size budgets' }
|
|
403
|
+
next
|
|
404
|
+
end
|
|
405
|
+
value = candidate
|
|
406
|
+
image['width_percent'], image['minimum_limited'] = value, false
|
|
407
|
+
image['display_height'] = value / 100.0 / ratio
|
|
408
|
+
image['display_area'] = (value / 100.0)**2 / ratio
|
|
409
|
+
end
|
|
410
|
+
image['references'].each do |reference|
|
|
411
|
+
match = source_macro(reference)
|
|
412
|
+
raise Error, "Cannot safely map image macro: #{reference['file']}:#{reference['line']}" unless match
|
|
413
|
+
before = match[0]
|
|
414
|
+
after = with_width(match, value)
|
|
415
|
+
file, line = reference.values_at('file', 'line')
|
|
416
|
+
key = [file, line]
|
|
417
|
+
prior = desired[key]
|
|
418
|
+
raise Error, "Reused source image needs conflicting widths: #{file}:#{line}" if prior && prior != after
|
|
419
|
+
desired[key] = after
|
|
420
|
+
next if prior || before == after
|
|
421
|
+
if @excluded.any? { |r| r['file'] == file && r['line'] == line }
|
|
422
|
+
raise Error, "Reused source also has excluded references: #{file}:#{line}"
|
|
423
|
+
end
|
|
424
|
+
@changes << { 'file' => file, 'line' => line, 'image' => image['path'],
|
|
425
|
+
'width_percent' => value, 'before' => before, 'after' => after }
|
|
426
|
+
end
|
|
427
|
+
end
|
|
428
|
+
@changes.group_by { |c| c['file'] }.each do |file, changes|
|
|
429
|
+
lines = @sources.fetch(file).lines
|
|
430
|
+
changes.each { |c| lines[c['line'] - 1] = c['after'] }
|
|
431
|
+
@revised[file] = lines.join
|
|
432
|
+
end
|
|
433
|
+
if book && !conflicts.empty?
|
|
434
|
+
@err.puts "Book scaling: #{conflicts.length} image(s) require review; minimum width conflicts with size budgets. No source is changed in preview."
|
|
435
|
+
raise Error, 'Book scaling has unresolved size conflicts; no sources were changed. Lower --min-width or revise the selection/budgets, then preview again.' if @options[:in_place]
|
|
436
|
+
end
|
|
437
|
+
apply if @options[:in_place]
|
|
438
|
+
report.merge('settings' => { 'mode' => @options[:width] ? 'fixed' : (book ? 'book' : 'automatic'), 'width' => @options[:width],
|
|
439
|
+
'height_width_ratio' => @options[:width] ? nil : @options[:ratio],
|
|
440
|
+
'min_width' => @options[:width] ? nil : @options[:min],
|
|
441
|
+
'max_width' => @options[:width] ? nil : @options[:max] },
|
|
442
|
+
'calibration' => calibration, 'conflicts' => conflicts,
|
|
443
|
+
'changes' => @changes, 'changed_files' => @revised.keys, 'applied' => !!@options[:in_place])
|
|
444
|
+
end
|
|
445
|
+
|
|
446
|
+
def unchanged?(file, content)
|
|
447
|
+
File.file?(file) && !File.symlink?(file) && File.realpath(file) == file && File.binread(file) == content.b
|
|
448
|
+
end
|
|
449
|
+
|
|
450
|
+
def apply
|
|
451
|
+
staged, backups, installed = {}, {}, []
|
|
452
|
+
begin
|
|
453
|
+
@sources.each do |file, content|
|
|
454
|
+
raise Error, "Source changed during analysis: #{file}" unless unchanged?(file, content)
|
|
455
|
+
end
|
|
456
|
+
@revised.each do |file, content|
|
|
457
|
+
raise Error, "Source changed during analysis: #{file}" unless unchanged?(file, @sources.fetch(file))
|
|
458
|
+
staged[file] = stage(file, content)
|
|
459
|
+
backups[file] = stage(file, @sources.fetch(file))
|
|
460
|
+
end
|
|
461
|
+
@revised.each_key do |file|
|
|
462
|
+
raise Error, "Source changed during analysis: #{file}" unless unchanged?(file, @sources.fetch(file))
|
|
463
|
+
File.rename(staged.fetch(file).path, file)
|
|
464
|
+
installed << file
|
|
465
|
+
end
|
|
466
|
+
rescue StandardError
|
|
467
|
+
installed.reverse_each do |file|
|
|
468
|
+
# Do not replace another writer's changes while rolling back.
|
|
469
|
+
if File.binread(file) == @revised.fetch(file).b
|
|
470
|
+
File.rename(backups.fetch(file).path, file)
|
|
471
|
+
end
|
|
472
|
+
end
|
|
473
|
+
raise
|
|
474
|
+
ensure
|
|
475
|
+
(staged.values + backups.values).each(&:close!)
|
|
476
|
+
end
|
|
477
|
+
end
|
|
478
|
+
|
|
479
|
+
def stage(file, content)
|
|
480
|
+
temp = Tempfile.new(['.pubkit-image-', '.adoc'], File.dirname(file))
|
|
481
|
+
temp.binmode
|
|
482
|
+
temp.write(content)
|
|
483
|
+
temp.flush
|
|
484
|
+
temp.chmod(File.stat(file).mode & 0o777)
|
|
485
|
+
temp
|
|
486
|
+
rescue StandardError
|
|
487
|
+
temp&.close!
|
|
488
|
+
raise
|
|
489
|
+
end
|
|
490
|
+
|
|
491
|
+
def diff
|
|
492
|
+
@revised.map do |file, content|
|
|
493
|
+
relative = Pathname.new(file).relative_path_from(Pathname.new(@root)).to_s
|
|
494
|
+
Tempfile.create('pubkit-before') do |a|
|
|
495
|
+
Tempfile.create('pubkit-after') do |b|
|
|
496
|
+
a.write(@sources.fetch(file)); a.flush
|
|
497
|
+
b.write(content); b.flush
|
|
498
|
+
stdout, stderr, status = Open3.capture3('diff', '-u', '--label', "a/#{relative}", '--label', "b/#{relative}", a.path, b.path)
|
|
499
|
+
raise Error, stderr unless [0, 1].include?(status.exitstatus)
|
|
500
|
+
stdout
|
|
501
|
+
end
|
|
502
|
+
end
|
|
503
|
+
end.join
|
|
504
|
+
end
|
|
505
|
+
|
|
506
|
+
def format(command, result)
|
|
507
|
+
if command == 'find'
|
|
508
|
+
result['images'].map do |image|
|
|
509
|
+
"#{image['path']}\t#{image['width']}x#{image['height']}\taspect=#{image['aspect_ratio'].round(4)}\tpixels=#{image['pixels']}\tbytes=#{image['bytes']}\treferences=#{image['references'].length}\n" +
|
|
510
|
+
image['references'].map { |ref| " #{ref['file'] || '(unmapped)'}:#{ref['line'] || '?'}\n" }.join
|
|
511
|
+
end.join + "Matched images: #{result['image_count']} / #{result['selected_image_count']}; matched references: #{result['reference_count']}; excluded: #{@excluded.length}\n"
|
|
512
|
+
elsif command == 'stats'
|
|
513
|
+
"Images: #{result['image_count']}; references: #{result['reference_count']}; bytes: #{result['total_bytes']}\n" +
|
|
514
|
+
%w[width height aspect_ratio bytes].map { |key| "#{key}: #{result[key].to_json}\n" }.join
|
|
515
|
+
else
|
|
516
|
+
result['images'].map do |image|
|
|
517
|
+
"#{image['path']}\t#{image['width']}x#{image['height']}\taspect=#{image['aspect_ratio'].round(4)}\tbytes=#{image['bytes']}\treferences=#{image['references'].length}" +
|
|
518
|
+
(command == 'scale' ? "\twidth=#{number(image['width_percent'])}%#{image['requires_review'] ? ' (requires review; proposed width=' + number(image['proposed_width_percent']) + '%; source unchanged)' : ''}#{image['minimum_limited'] ? ' (minimum width reached; height may exceed target)' : ''}" : '') + "\n"
|
|
519
|
+
end.join + "Images: #{result['image_count']}; references: #{result['reference_count']}; excluded: #{@excluded.length}" +
|
|
520
|
+
(command == 'scale' ? "; changes: #{@changes.length}; #{result['applied'] ? 'applied' : 'preview'}" : '') + "\n"
|
|
521
|
+
end
|
|
522
|
+
end
|
|
523
|
+
end
|
|
524
|
+
end
|
data/lib/asciidoc_pubkit.rb
CHANGED
|
@@ -9,7 +9,7 @@ require 'pathname'
|
|
|
9
9
|
require 'optparse'
|
|
10
10
|
|
|
11
11
|
module AsciidocPubkit
|
|
12
|
-
VERSION = '1.
|
|
12
|
+
VERSION = '1.4.1'
|
|
13
13
|
class Error < StandardError; end
|
|
14
14
|
|
|
15
15
|
def self.hash_text(text)
|
|
@@ -40,4 +40,5 @@ require_relative 'asciidoc_pubkit/score'
|
|
|
40
40
|
require_relative 'asciidoc_pubkit/replacement'
|
|
41
41
|
require_relative 'asciidoc_pubkit/document_commands'
|
|
42
42
|
require_relative 'asciidoc_pubkit/skill_commands'
|
|
43
|
+
require_relative 'asciidoc_pubkit/image_commands'
|
|
43
44
|
require_relative 'asciidoc_pubkit/cli'
|
metadata
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
--- !ruby/object:Gem::Specification
|
|
2
2
|
name: asciidoc-pubkit
|
|
3
3
|
version: !ruby/object:Gem::Version
|
|
4
|
-
version: 1.
|
|
4
|
+
version: 1.4.1
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- CyberGarage
|
|
@@ -37,11 +37,11 @@ dependencies:
|
|
|
37
37
|
- - "~>"
|
|
38
38
|
- !ruby/object:Gem::Version
|
|
39
39
|
version: '1.0'
|
|
40
|
-
description: Inspect
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
replacements.
|
|
40
|
+
description: Inspect document-referenced images and explicitly set source image display
|
|
41
|
+
widths, inspect AsciiDoc outlines, book metadata, and local cross-references, generate
|
|
42
|
+
English document-title indexes, and generate Japanese and English technical writing
|
|
43
|
+
prompts, review AsciiDoc prose, section headings, and list text separately, verify
|
|
44
|
+
protected manuscript content, and explicitly apply prose-only mechanical replacements.
|
|
45
45
|
executables:
|
|
46
46
|
- asciidoc-pubkit
|
|
47
47
|
extensions: []
|
|
@@ -70,6 +70,7 @@ files:
|
|
|
70
70
|
- docs/english-review-research.md
|
|
71
71
|
- docs/english-review.md
|
|
72
72
|
- docs/explanatory-guidance-research.md
|
|
73
|
+
- docs/image-commands.md
|
|
73
74
|
- docs/installation.md
|
|
74
75
|
- docs/list-review.md
|
|
75
76
|
- docs/outline-review.md
|
|
@@ -93,6 +94,7 @@ files:
|
|
|
93
94
|
- lib/asciidoc_pubkit/document_commands.rb
|
|
94
95
|
- lib/asciidoc_pubkit/english.rb
|
|
95
96
|
- lib/asciidoc_pubkit/heading_rules.rb
|
|
97
|
+
- lib/asciidoc_pubkit/image_commands.rb
|
|
96
98
|
- lib/asciidoc_pubkit/japanese_verification.rb
|
|
97
99
|
- lib/asciidoc_pubkit/language.rb
|
|
98
100
|
- lib/asciidoc_pubkit/local_evaluator.rb
|
|
@@ -125,7 +127,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
|
|
|
125
127
|
- !ruby/object:Gem::Version
|
|
126
128
|
version: '0'
|
|
127
129
|
requirements: []
|
|
128
|
-
rubygems_version: 4.0.
|
|
130
|
+
rubygems_version: 4.0.23
|
|
129
131
|
specification_version: 4
|
|
130
132
|
summary: Document inspection, replacement, and Japanese/English review tools for AsciiDoc
|
|
131
133
|
books
|