fontisan 0.4.48 → 0.4.50

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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 1acd9a7fdcd6fc469e7d8ca2614a8e5e036248e31fa297d1056f151b2796ab27
4
- data.tar.gz: 6c9593f9cce03a5aba93dedf68a1c3606e25bf7f2deb5991443f048cb51c753e
3
+ metadata.gz: fbcf721dc93a236fbbeb08e0e09f0f6eda47a01fd16a21abbb1e39e68ff88979
4
+ data.tar.gz: 24e189fbdc46b6ee5503d8b7df483811999a85f6d48e21e50b519f032f970cfc
5
5
  SHA512:
6
- metadata.gz: 5db866166488d311c45a6fc0265ba3da422d28717469bc5303a06028dc2c50038d84d953d850303e967d55c59cbc1f3113a1ce364a9b0b2eab3be3f40e94845d
7
- data.tar.gz: bf0cecbde3bc1ebc7312ada4fafc112e8e6e905fe682a1f33ee46645cf8e54eadcad15c768d1a5b22212cd1ddc9b9928795e7bf94c044b0e528bf517920277ae
6
+ metadata.gz: ab3678716f7bcbd36e6258829325ba263a30230169c71b6920043b74a725c262ee231e6279106eaca2258955e7c63e5ffc9fd291e4ff43725d7a08c9a3f4d61e
7
+ data.tar.gz: b6ab7b24940b1bf463cb1e384d3e26d5f42fb6c18f146659f1581bf48d98f50068a50d868f7616b16af8ddf8cb897b793e232ea552afa702649ea20c09ed6923
data/CHANGELOG.md CHANGED
@@ -9,10 +9,10 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
9
9
 
10
10
  ### Changed
11
11
 
12
- - The default engine is now `FONTISAN_ENGINE=auto`: installs with a native tier
13
- serve the path-based `Fontisan::Reference` operations from it (native, then
14
- ffi), and installs without one fall back to Ruby with no toolchain needed.
15
- Set `FONTISAN_ENGINE=ruby` to opt out. Engine: fontisan-rs at git rev
12
+ - `FONTISAN_ENGINE=auto` (the default) resolves to the Ruby tier until the
13
+ phase-3 gates pass (fontisan#160); `FONTISAN_ENGINE=native` or `ffi` still
14
+ select the Rust tiers explicitly. The native-preferring order is kept as
15
+ `Engine::NATIVE_PREFERRED_ORDER` for the later flip. Engine: fontisan-rs at git rev
16
16
  `daffb3f45b67517e924a3e5d0e113a2ecbde9959` (crate version 0.0.0, not yet on
17
17
  crates.io), bundled as the magnus extension and the C-ABI shared library.
18
18
  Platform gems: `x86_64-linux`, `x86_64-linux-musl`, `arm64-darwin`,
data/Cargo.lock CHANGED
@@ -185,7 +185,7 @@ dependencies = [
185
185
  [[package]]
186
186
  name = "fontisan"
187
187
  version = "0.0.0"
188
- source = "git+https://github.com/fontist/fontisan-rs?rev=daffb3f45b67517e924a3e5d0e113a2ecbde9959#daffb3f45b67517e924a3e5d0e113a2ecbde9959"
188
+ source = "git+https://github.com/fontist/fontisan-rs?rev=f45057a12e15ba9f2c02526cd8ca0603c80edaf9#f45057a12e15ba9f2c02526cd8ca0603c80edaf9"
189
189
  dependencies = [
190
190
  "brotli",
191
191
  "brotli-decompressor",
@@ -252,9 +252,9 @@ dependencies = [
252
252
 
253
253
  [[package]]
254
254
  name = "magnus"
255
- version = "0.8.4"
255
+ version = "0.9.4"
256
256
  source = "registry+https://github.com/rust-lang/crates.io-index"
257
- checksum = "e76237a607e1dea288dd0ef0c6c8f49037df2152d14bb52b3542c46522d9e6fc"
257
+ checksum = "3c5f2dd2017d172e2fde9969a35f10f1374a4dd79b37a17f1847f83201883de7"
258
258
  dependencies = [
259
259
  "magnus-macros",
260
260
  "rb-sys",
@@ -264,9 +264,9 @@ dependencies = [
264
264
 
265
265
  [[package]]
266
266
  name = "magnus-macros"
267
- version = "0.8.0"
267
+ version = "0.9.1"
268
268
  source = "registry+https://github.com/rust-lang/crates.io-index"
269
- checksum = "47607461fd8e1513cb4f2076c197d8092d921a1ea75bd08af97398f593751892"
269
+ checksum = "9dafde2eeb66f090e0f326112323eb8324b12cb32b5d1210e541d3df6b0ce77e"
270
270
  dependencies = [
271
271
  "proc-macro2",
272
272
  "quote",
data/README.adoc CHANGED
@@ -60,11 +60,10 @@ operations from three tiers: `native` (a precompiled Rust extension), `ffi` (the
60
60
  bundled Rust shared library, loaded through the `ffi` gem) and `ruby` (the pure
61
61
  Ruby implementation, always present).
62
62
 
63
- The default is `auto`: the first available tier wins, in the order
64
- `native`, `ffi`, `ruby`. An operation a tier cannot serve goes to the next one.
65
- Installed from the source gem on a machine with no Rust toolchain and no
66
- bundled library, `auto` serves everything from `ruby`, with no warning and
67
- no error.
63
+ The default is `auto`, which currently serves everything from `ruby`: the Rust
64
+ tiers are used only when selected with `FONTISAN_ENGINE=native` or `ffi`, until
65
+ the native tier's release gates pass (see fontist/fontisan#160). After that,
66
+ `auto` will pick the first available tier in the order `native`, `ffi`, `ruby`.
68
67
 
69
68
  [cols="1,3"]
70
69
  |===
@@ -85,6 +84,24 @@ unset, empty, `0`, `false`, `no` and `off` leave it off; any other value raises
85
84
  an operation. See link:docs/guide/engines.md[Engines] for tiers, platforms and
86
85
  troubleshooting.
87
86
 
87
+ === Python face
88
+
89
+ https://github.com/fontist/fontisan-python[fontisan-python] is the Python face
90
+ of fontisan. It is a setuptools package that rides the same Rust cdylib the
91
+ `ffi` tier loads, shipped as per-platform package data and bound with
92
+ `ctypes`. It is not a second engine and adds no new FFI surface.
93
+
94
+ It binds the batch audit and table-read operations. Anything the C ABI does not
95
+ expose returns an explicit `unsupported` result rather than a guess.
96
+
97
+ Its results are held to the same parity contract as the other faces: they are
98
+ compared against the Ruby-tier goldens in `corpus/` (see
99
+ link:https://github.com/fontist/fontisan/issues/166[fontist/fontisan#166]).
100
+
101
+ NOTE: The package name on PyPI and the Python version floor are not settled,
102
+ and nothing is published yet. Treat the package as unreleased until the
103
+ maintainers say otherwise.
104
+
88
105
  == Installation
89
106
 
90
107
  Add this line to your application's Gemfile:
@@ -44,22 +44,22 @@ end
44
44
  ### Parse SVG Content
45
45
 
46
46
  ```ruby
47
- require 'nokogiri'
47
+ require 'moxml'
48
48
 
49
49
  svg = font.tables['SVG']
50
50
  doc = svg.documents[42] # SVG for glyph 42
51
51
 
52
- parsed = Nokogiri::XML(doc)
52
+ parsed = Moxml.parse(doc)
53
53
 
54
54
  # Find elements
55
- paths = parsed.css('path')
55
+ paths = parsed.root.css('path')
56
56
  puts "Paths: #{paths.length}"
57
57
 
58
- rects = parsed.css('rect')
58
+ rects = parsed.root.css('rect')
59
59
  puts "Rectangles: #{rects.length}"
60
60
 
61
61
  # Find gradients
62
- gradients = parsed.css('linearGradient', 'radialGradient')
62
+ gradients = parsed.root.css('linearGradient, radialGradient')
63
63
  puts "Gradients: #{gradients.length}"
64
64
  ```
65
65
 
@@ -31,7 +31,7 @@ Set `FONTISAN_ENGINE` before the process starts. Unset or empty means `auto`:
31
31
  | `ruby` | Use the Ruby tier only. |
32
32
  | `native` | Use the native tier. |
33
33
  | `ffi` | Use the ffi tier. |
34
- | `auto` | The default. Use the first tier that is available and supports the operation, in the order native, ffi, ruby. |
34
+ | `auto` | The default. Currently serves everything from ruby; the Rust tiers are used only when selected explicitly, until the phase-3 gates pass (fontisan#160). After that, the first available tier in the order native, ffi, ruby. |
35
35
 
36
36
  ```sh
37
37
  FONTISAN_ENGINE=native FONTISAN_ENGINE_STRICT=1 fontisan convert MyFont.ttf --to woff2 --output out.woff2
@@ -126,7 +126,7 @@ dependencies = [
126
126
  [[package]]
127
127
  name = "fontisan"
128
128
  version = "0.0.0"
129
- source = "git+https://github.com/fontist/fontisan-rs?rev=daffb3f45b67517e924a3e5d0e113a2ecbde9959#daffb3f45b67517e924a3e5d0e113a2ecbde9959"
129
+ source = "git+https://github.com/fontist/fontisan-rs?rev=f45057a12e15ba9f2c02526cd8ca0603c80edaf9#f45057a12e15ba9f2c02526cd8ca0603c80edaf9"
130
130
  dependencies = [
131
131
  "brotli",
132
132
  "brotli-decompressor",
@@ -15,4 +15,4 @@ crate-type = ["cdylib"]
15
15
  [dependencies]
16
16
  # TEMPORARY (decision D3: the crate is not on crates.io yet). Replace with
17
17
  # `fontisan = { version = "=<release>", features = ["ffi"] }` once published.
18
- fontisan = { git = "https://github.com/fontist/fontisan-rs", rev = "daffb3f45b67517e924a3e5d0e113a2ecbde9959", features = ["ffi"] }
18
+ fontisan = { git = "https://github.com/fontist/fontisan-rs", rev = "f45057a12e15ba9f2c02526cd8ca0603c80edaf9", features = ["ffi"] }
@@ -13,8 +13,8 @@ crate-type = ["cdylib"]
13
13
  # TEMPORARY (decision D3: the crate is not on crates.io yet). Replace with
14
14
  # `fontisan = "=<version>"` once published. The rev must be a commit on
15
15
  # fontist/fontisan-rs; keep it equal to the rev in ext/fontisan_cdylib/Cargo.toml.
16
- fontisan = { git = "https://github.com/fontist/fontisan-rs", rev = "daffb3f45b67517e924a3e5d0e113a2ecbde9959" }
17
- magnus = "=0.8.4"
16
+ fontisan = { git = "https://github.com/fontist/fontisan-rs", rev = "f45057a12e15ba9f2c02526cd8ca0603c80edaf9" }
17
+ magnus = "=0.9.4"
18
18
  rb-sys = { version = "=0.9.130", default-features = false }
19
19
 
20
20
  [lints.rust]
@@ -1,9 +1,12 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- # Builds the :native tier. Degrades cleanly: without a Rust toolchain (or the
4
- # rb_sys gem) it writes a no-op Makefile, the gem installs without the
5
- # extension, and Fontisan::Native.available? is false, so only the :ruby tier
6
- # serves. Set FONTISAN_NATIVE_REQUIRED=1 to turn that degradation into a failure.
3
+ # Builds the :native tier. Degrades cleanly: without a working Rust toolchain
4
+ # (both `cargo --version` and `rustc --version` must succeed) or the rb_sys gem,
5
+ # or when rb_sys raises while configuring (a Cargo/Ruby target mismatch, a
6
+ # cargo shim with no usable rustc), it writes a no-op Makefile, the gem installs
7
+ # without the extension, and Fontisan::Native.available? is false, so only the
8
+ # :ruby tier serves. Set FONTISAN_NATIVE_REQUIRED=1 to turn that degradation
9
+ # into a failure.
7
10
  #
8
11
  # A failure at `make` time (a Cargo/Ruby target mismatch on Windows, a missing
9
12
  # linker, an old rustc) degrades the same way: rb_sys's Makefile is kept as
@@ -11,18 +14,26 @@
11
14
  # warning. Only POSIX-sh-compatible recipe syntax is used (`cmd || echo`), so it
12
15
  # works under GNU make on Linux/macOS and the RubyInstaller devkit (msys sh).
13
16
  require "mkmf"
17
+ require "fileutils"
14
18
 
15
19
  RB_SYS_MAKEFILE = "Makefile.rb_sys"
16
20
 
17
- def cargo_present?
18
- system("cargo", "--version", out: File::NULL, err: File::NULL)
21
+ def tool_present?(tool)
22
+ system(tool, "--version", out: File::NULL, err: File::NULL)
19
23
  rescue SystemCallError
20
24
  false
21
25
  end
22
26
 
27
+ # The first of cargo and rustc whose `--version` does not succeed, or nil.
28
+ def missing_rust_tool
29
+ %w[cargo rustc].find { |tool| !tool_present?(tool) }
30
+ end
31
+
23
32
  def skip_native(reason)
24
33
  abort "fontisan: cannot build the native extension: #{reason}" if ENV["FONTISAN_NATIVE_REQUIRED"] == "1"
25
34
 
35
+ # rb_sys may have written (part of) its Makefile before raising.
36
+ FileUtils.rm_f(["Makefile", RB_SYS_MAKEFILE])
26
37
  warn "fontisan: skipping the native extension (#{reason}); the :ruby engine tier serves."
27
38
  File.write("Makefile", <<~MAKEFILE)
28
39
  all:
@@ -46,14 +57,16 @@ def wrap_rust_makefile
46
57
  File.write("Makefile", "#{targets.join}\n.PHONY: all install clean distclean\n")
47
58
  end
48
59
 
49
- if cargo_present?
60
+ if (missing = missing_rust_tool)
61
+ skip_native("#{missing} not found")
62
+ else
50
63
  begin
51
64
  require "rb_sys/mkmf"
52
65
  create_rust_makefile("fontisan/native/fontisan_native")
53
66
  wrap_rust_makefile
54
67
  rescue LoadError
55
68
  skip_native("the rb_sys gem is not installed")
69
+ rescue StandardError => e
70
+ skip_native("rb_sys could not configure the build: #{e.message}")
56
71
  end
57
- else
58
- skip_native("cargo not found")
59
72
  end
@@ -9,13 +9,14 @@
9
9
  //! section touches Ruby: inputs are copied into owned Rust values first and
10
10
  //! the result is plain Rust data until the GVL is back.
11
11
  //! * A failure is raised as `Fontisan::Native::Failure` carrying the engine's
12
- //! `[class, message, [[cause class, cause message], ...]]`; the Ruby side
12
+ //! `[class, message, [[cause class, cause message], ...], error kind]`; the Ruby side
13
13
  //! rebuilds the Ruby tier's exception class and cause chain from it. A Rust
14
14
  //! panic is caught inside the released section and raised as
15
15
  //! `Fontisan::Native::Panic`.
16
16
  use fontisan::audit;
17
17
  use fontisan::convert::{self, Target};
18
18
  use fontisan::json::Json;
19
+ use fontisan::ErrorKind;
19
20
  use fontisan::read;
20
21
  use fontisan::scan::{self, RowStatus};
21
22
  use fontisan::sfnt::{self, Format, LoadingMode, Options};
@@ -36,6 +37,8 @@ enum Fail {
36
37
  class: String,
37
38
  message: String,
38
39
  causes: Vec<(String, String)>,
40
+ /// `ErrorKind` code (the C ABI's `FONTISAN_KIND_*`); the Ruby side maps by it.
41
+ kind: i32,
39
42
  },
40
43
  Panic(String),
41
44
  }
@@ -46,6 +49,7 @@ impl Fail {
46
49
  class: class.to_string(),
47
50
  message: message.into(),
48
51
  causes: Vec::new(),
52
+ kind: ErrorKind::from_class(class).code(),
49
53
  }
50
54
  }
51
55
 
@@ -75,10 +79,13 @@ impl Fail {
75
79
  .collect(),
76
80
  _ => Vec::new(),
77
81
  };
82
+ let class = text("class");
83
+ let kind = ErrorKind::from_class(&class).code();
78
84
  Self::Engine {
79
- class: text("class"),
85
+ class,
80
86
  message: text("message"),
81
87
  causes,
88
+ kind,
82
89
  }
83
90
  }
84
91
  }
@@ -150,6 +157,7 @@ fn raise(ruby: &Ruby, fail: Fail) -> Error {
150
157
  class,
151
158
  message,
152
159
  causes,
160
+ kind,
153
161
  } => {
154
162
  let klass: magnus::ExceptionClass = native.const_get("Failure")?;
155
163
  let exc: Value = klass.funcall("new", (message.as_str(),))?;
@@ -160,10 +168,11 @@ fn raise(ruby: &Ruby, fail: Fail) -> Error {
160
168
  pair.push(ruby.str_new(m))?;
161
169
  causes_rb.push(pair)?;
162
170
  }
163
- let details = ruby.ary_new_capa(3);
171
+ let details = ruby.ary_new_capa(4);
164
172
  details.push(ruby.str_new(&class))?;
165
173
  details.push(ruby.str_new(&message))?;
166
174
  details.push(causes_rb)?;
175
+ details.push(kind)?;
167
176
  exc.funcall::<_, _, Value>("instance_variable_set", ("@details", details))?;
168
177
  let exception = magnus::Exception::from_value(exc)
169
178
  .ok_or_else(|| Error::new(ruby.exception_runtime_error(), "bad failure"))?;
@@ -310,7 +319,7 @@ fn native_audit_dir_rows(ruby: &Ruby, dir: String, validate: bool) -> Result<RAr
310
319
  }
311
320
 
312
321
  /// Whether the engine reads the file itself: false for a file that is gone, a
313
- /// directory, dfont and Type 1 (the Ruby tier serves those).
322
+ /// directory, dfont, Type 1 and anything that is not a font (the Ruby tier serves those).
314
323
  fn native_supports_file(ruby: &Ruby, path: String) -> Result<bool, Error> {
315
324
  finish(
316
325
  ruby,
@@ -323,10 +332,16 @@ fn native_supports_file(ruby: &Ruby, path: String) -> Result<bool, Error> {
323
332
  if file.take(256).read_to_end(&mut head).is_err() {
324
333
  return Ok(false);
325
334
  }
326
- Ok(!matches!(
327
- sfnt::detect_format(&head),
328
- Some(Format::Dfont | Format::Pfa | Format::Pfb)
329
- ))
335
+ // Not a font at all (random bytes, a zero-filled or empty file): the
336
+ // Ruby tier raises the canonical InvalidFontError, and the engine never
337
+ // slurps a huge non-font into memory. A `ttcf` file whose directory lies
338
+ // past the 256-byte head is a font the engine reads itself.
339
+ let unknown = sfnt::detect_format(&head).is_none() && !head.starts_with(b"ttcf");
340
+ Ok(!unknown
341
+ && !matches!(
342
+ sfnt::detect_format(&head),
343
+ Some(Format::Dfont | Format::Pfa | Format::Pfb)
344
+ ))
330
345
  }),
331
346
  )
332
347
  }
@@ -13,14 +13,45 @@ module Fontisan
13
13
  CONVERT_OPTIONS = %i[to output timestamp quiet].freeze
14
14
  SUBSET_PROFILES = %w[web pdf minimal].freeze
15
15
  MAX_CODEPOINT = 0x10FFFF
16
+ # The engine's extract index is a u32; a larger one would wrap, not raise.
17
+ MAX_FONT_INDEX = 0xFFFF_FFFF
16
18
 
17
19
  BYTE_OPERATIONS = %i[convert extract instance subset].freeze
18
20
 
19
21
  # "<ruby class>: <message>": how the engine reports a Ruby exception it
20
22
  # mirrors (the byte operations carry one class and one message, no chain).
21
23
  FAILURE_MESSAGE = /\A([A-Z]\w*(?:::\w+)*): (.*)\z/m
22
- # The engine's text for a file that is no font; Ruby's is InvalidFontError.
23
- UNRECOGNISED_FORMAT_MESSAGE = "Conversion failed: unrecognised font format"
24
+ # The engine's text for a file that is no font (convert adds a "Conversion
25
+ # failed: " prefix); Ruby's is InvalidFontError.
26
+ UNRECOGNISED_FORMAT_MESSAGE = "unrecognised font format"
27
+ # Prefix of a convert failure that wraps the engine's own message.
28
+ TRANSFORMATION_PREFIX = "Conversion failed: Transformation failed: "
29
+ # Engine messages for bad font data that Ruby raises as InvalidFontError:
30
+ # the WOFF/WOFF2 container decoders ("woff: ...", "woff2: ..."), and the
31
+ # same error as its debug text.
32
+ INVALID_FONT_MESSAGE = /\A(?:woff2?: |Error \{ class: InvalidFont, message: ")/
33
+ # The instancer's own error; convert keeps Fontisan::Error for it, as Ruby does.
34
+ TRUNCATED_TABLE_MESSAGE = "Static instancing: truncated or malformed table"
35
+ # The engine prints the error's Debug form: the message is a Rust string
36
+ # literal and a cause follows it (`, cause: None`).
37
+ DEBUG_ERROR_MESSAGE = /\AError \{ class: InvalidFont, message: "(.*?)"(?:, cause: .*)? \}\z/m
38
+ # The text InvalidAxisError builds from its axis and reason.
39
+ AXIS_MESSAGE = /\AInvalid variation axis '(.*?)': (.*)\z/m
40
+ RUST_ESCAPES = { '\\"' => '"', "\\\\" => "\\", "\\n" => "\n", "\\t" => "\t", "\\r" => "\r" }.freeze
41
+
42
+ # The engine's error kinds (fontisan-rs `ErrorKind`, `FONTISAN_KIND_*` of the
43
+ # C ABI), by number. Only the kinds that name one Ruby class are mapped: the
44
+ # others stand for several (InvalidFont: InvalidFontError and RuntimeError;
45
+ # MissingTable: MissingTableError and MissingVariationTableError; Truncated:
46
+ # EOFError and IOError; Io: every Errno), or for none (Other, Unsupported),
47
+ # and fall back to the reported class and message text.
48
+ KIND_CLASSES = {
49
+ 2 => "Fontisan::InvalidAxisError",
50
+ 3 => "Fontisan::InvalidCoordinatesError",
51
+ 6 => "Fontisan::SubsettingError",
52
+ 7 => "Fontisan::CorruptedTableError",
53
+ 9 => "ArgumentError",
54
+ }.freeze
24
55
 
25
56
  private
26
57
 
@@ -79,7 +110,7 @@ module Fontisan
79
110
 
80
111
  def extract_options?(options)
81
112
  options.keys.sort == %i[index output_dir] && options[:index].is_a?(Integer) &&
82
- !options[:index].negative? && options[:output_dir].respond_to?(:to_str)
113
+ options[:index].between?(0, MAX_FONT_INDEX) && options[:output_dir].respond_to?(:to_str)
83
114
  end
84
115
 
85
116
  def instance_options?(options, path)
@@ -107,14 +138,44 @@ module Fontisan
107
138
  false
108
139
  end
109
140
 
141
+ # The output path of a convert, after the checks the Ruby tier makes before
142
+ # it converts: the name ConvertCommand gives a single font (an output with no
143
+ # extension gets ".<format>", a ".ttf" dot file keeps its name), never the
144
+ # input file, and its directory exists. A collection is written to the path
145
+ # as given.
146
+ def convert_output(path, output, target)
147
+ output = File.path(output)
148
+ output = Commands::MultiFormatOutput.new(output, [target]).paths.first unless collection_file?(path)
149
+ OutputGuard.check!(path, output)
150
+ dir = File.dirname(output)
151
+ raise ArgumentError, "Output directory not found: #{dir}" unless File.directory?(dir)
152
+
153
+ output
154
+ end
155
+
110
156
  def finish_convert(path, target, output, bytes)
111
- File.binwrite(output, bytes)
157
+ write_output(output, bytes)
112
158
  result = { success: true, input_path: path, output_path: output }
113
159
  result.merge!(convert_formats(path, target))
114
160
  result.merge(input_size: File.size(path), output_size: bytes.bytesize,
115
161
  **convert_tail(path))
116
162
  end
117
163
 
164
+ # Writes as the Ruby tier's convert does: an IO failure is a Fontisan::Error.
165
+ def write_output(output, bytes)
166
+ File.binwrite(output, bytes)
167
+ rescue SystemCallError => e
168
+ raise Fontisan::Error, "Conversion failed: Transformation failed: #{e.message}"
169
+ end
170
+
171
+ # An IO failure while extracting (unreadable input, output directory that
172
+ # cannot be made or written) is a Fontisan::Error, as UnpackCommand raises it.
173
+ def unpacking_io
174
+ yield
175
+ rescue SystemCallError => e
176
+ raise Fontisan::Error, "Unexpected error during unpacking: #{e.message}"
177
+ end
178
+
118
179
  def convert_formats(path, target)
119
180
  return { source_format: single_format(path), target_format: target } unless collection_file?(path)
120
181
 
@@ -170,37 +231,71 @@ module Fontisan
170
231
  # Raise the Ruby tier's exception: class, message and the cause chain
171
232
  # (each cause is raised so that its own #cause is set).
172
233
  def raise_failure(details, byte_operation: false)
173
- class_name, message, causes = details
234
+ class_name, message, causes, kind = details
235
+ klass, message = byte_failure(class_name, message, kind) if byte_operation
236
+ klass ||= exception_class(class_name)
237
+ raised, text = public_failure(klass, message)
238
+ # The leaked Ruby error stays as the cause, as the Ruby tier's does.
239
+ causes = [[class_name, message], *causes] unless raised == klass
174
240
  cause = nil
175
- causes.reverse_each { |name, text| cause = build_exception(name, text, cause) }
176
- klass, message = byte_failure(class_name, message) if byte_operation
177
- raise build_instance(klass || exception_class(class_name), message), cause: cause
241
+ causes.reverse_each { |name, detail| cause = build_exception(name, detail, cause) }
242
+ raise build_instance(raised, text), cause: cause
243
+ end
244
+
245
+ # An engine error that mirrors a Ruby parser leak (EOFError, NoMethodError,
246
+ # ...) is raised as the Ruby tier raises it now: InvalidFontError.
247
+ def public_failure(klass, message)
248
+ return [klass, message] unless Reference::PARSER_LEAKS.any? { |leak| klass <= leak }
249
+
250
+ [InvalidFontError, Reference.malformed_message(klass, message)]
178
251
  end
179
252
 
180
253
  # The Ruby class and message of a failed byte operation, so that a tier
181
254
  # never changes what a caller can rescue or match: an engine error that
182
255
  # names the Ruby exception it mirrors ("RuntimeError: ...") is unwrapped,
183
- # and the engine's unrecognised-format error becomes the loader's.
184
- def byte_failure(class_name, message)
256
+ # and the engine's unrecognised-format error becomes the loader's. A +kind+
257
+ # that names one Ruby class decides it; message text is read only for the
258
+ # other kinds (Other and the ambiguous ones), and when no kind was reported.
259
+ def byte_failure(class_name, message, kind = nil)
260
+ kind_class = KIND_CLASSES[kind]
261
+ return [exception_class(kind_class), message] if kind_class
262
+
185
263
  if class_name == "Fontisan::Error" && (match = FAILURE_MESSAGE.match(message))
186
264
  class_name = match[1]
187
265
  message = match[2]
188
266
  end
189
- return [InvalidFontError, FontLoader::UNKNOWN_FORMAT_MESSAGE] if message == UNRECOGNISED_FORMAT_MESSAGE
267
+ bare = message.delete_prefix(TRANSFORMATION_PREFIX)
268
+ return [InvalidFontError, FontLoader::UNKNOWN_FORMAT_MESSAGE] if bare.delete_prefix("Conversion failed: ") == UNRECOGNISED_FORMAT_MESSAGE
269
+ return [InvalidFontError, message] if message == TRUNCATED_TABLE_MESSAGE
270
+ return [InvalidFontError, unwrap_debug_message(bare)] if class_name == "Fontisan::Error" && INVALID_FONT_MESSAGE.match?(bare)
190
271
 
191
272
  [exception_class(class_name), message]
192
273
  end
193
274
 
194
- # `klass.new(message)`, or the `message:` keyword form some Fontisan
195
- # errors use (MissingVariationTableError); never a failed constructor.
275
+ # The message inside the engine's Debug text for an InvalidFont error, with
276
+ # the Rust string escapes undone; any other text is returned as it is.
277
+ def unwrap_debug_message(text)
278
+ match = DEBUG_ERROR_MESSAGE.match(text) or return text
279
+
280
+ match[1].gsub(/\\[\\"ntr]/) { |escape| RUST_ESCAPES.fetch(escape) }
281
+ end
282
+
283
+ # `klass.new(message)`, or the keyword form some Fontisan errors use
284
+ # (`message:` for MissingVariationTableError; `axis:` and `reason:` for
285
+ # InvalidAxisError, split out of its own text); never a failed constructor.
196
286
  def build_instance(klass, message)
197
287
  klass.new(message)
198
288
  rescue ArgumentError
199
- begin
200
- klass.new(message: message)
201
- rescue ArgumentError
202
- Fontisan::Error.new(message)
203
- end
289
+ build_keyword_instance(klass, message)
290
+ end
291
+
292
+ def build_keyword_instance(klass, message)
293
+ axis = AXIS_MESSAGE.match(message) if klass <= InvalidAxisError
294
+ return klass.new(axis: axis[1], reason: axis[2]) if axis
295
+
296
+ klass.new(message: message)
297
+ rescue ArgumentError
298
+ Fontisan::Error.new(message)
204
299
  end
205
300
 
206
301
  def build_exception(name, text, cause)
data/lib/fontisan/cli.rb CHANGED
@@ -12,6 +12,12 @@ module Fontisan
12
12
  # @example Run the info command
13
13
  # Fontisan::Cli.start(['info', 'font.ttf'])
14
14
  class Cli < Thor
15
+ # A Thor::Error (unknown command, missing --output) must fail the process:
16
+ # without this Thor exits 0 and prints a deprecation warning.
17
+ def self.exit_on_failure?
18
+ true
19
+ end
20
+
15
21
  class_option :format, type: :string, default: "text",
16
22
  desc: "Output format (text, yaml, json)",
17
23
  aliases: "-f"
@@ -116,6 +116,7 @@ module Fontisan
116
116
  # @raise [Error] If conversion fails
117
117
  def run
118
118
  validate_options!
119
+ Array(@output_paths || @output_path).each { |out| OutputGuard.check!(font_path, out) }
119
120
 
120
121
  if collection_file?
121
122
  if multi_format?
@@ -130,7 +131,7 @@ module Fontisan
130
131
  else
131
132
  convert_single_font(@target_formats.first, @output_paths.first)
132
133
  end
133
- rescue ArgumentError
134
+ rescue ArgumentError, OutputGuard::Refused
134
135
  # Let ArgumentError propagate for validation errors
135
136
  raise
136
137
  rescue StandardError => e
@@ -51,8 +51,13 @@ module Fontisan
51
51
  @target_formats.map { |fmt| "#{@base_path}.#{fmt}" }
52
52
  end
53
53
 
54
+ # A dot file whose whole name is the extension (".ttf") has one: appending
55
+ # the format would write ".ttf.ttf".
54
56
  def has_extension?
55
- !File.extname(@base_path).strip.downcase.empty?
57
+ name = File.basename(@base_path)
58
+ return true if name.length > 1 && name.start_with?(".") && name.count(".") == 1
59
+
60
+ !File.extname(name).strip.downcase.empty?
56
61
  end
57
62
  end
58
63
  end