tcxkit 0.1.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.
@@ -0,0 +1,270 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TcxKit
4
+ # Decodes the text of a field by its XSD type. Never raises: text that does
5
+ # not fit the type gives a nil value and a reason.
6
+ module Types
7
+ # A field's type: name (as Field#type reports it), the decoder, and the
8
+ # range or enumeration it is restricted to.
9
+ # preserve: keep whitespace (an enumeration based on xsd:string) instead
10
+ # of collapsing it. min_length, max_length and pattern restrict a token
11
+ # (XSD minLength, maxLength or length, and pattern), in characters.
12
+ Spec = Struct.new(:name, :decoder, :min, :max, :max_exclusive, :values, :signed, :preserve,
13
+ :min_length, :max_length, :pattern, keyword_init: true) do
14
+ def known?
15
+ name != :unknown
16
+ end
17
+ end
18
+
19
+ DOUBLE = /\A[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?\z/
20
+ DECIMAL = /\A[+-]?(?:\d+(?:\.\d*)?|\.\d+)\z/
21
+ SIGNED_INTEGER = /\A[+-]?\d+\z/
22
+ NON_FINITE_DOUBLES = %w[INF +INF -INF NaN].freeze
23
+ # The XSD 1.1 lexical rule for unsigned types: an optional "+", and "-"
24
+ # only before zero. XSD 1.0 allows digits only; the value is the same
25
+ # either way, so the more lenient rule is kept (SPECIFICATION.md 6.3).
26
+ UNSIGNED_INTEGER = /\A(?:\+?\d+|-0+)\z/
27
+ G_YEAR = /\A(-?\d{4,})(Z|[+-]\d{2}:\d{2})?\z/
28
+ DATE_TIME = /\A(-?\d{4,})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}(?:\.\d+)?)(Z|[+-]\d{2}:\d{2})?\z/
29
+ BOOLEANS = { "true" => true, "1" => true, "false" => false, "0" => false }.freeze
30
+ DAYS_IN_MONTH = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze
31
+
32
+ module_function
33
+
34
+ def string(name = :string) = Spec.new(name: name, decoder: :string)
35
+ def token(name = :token, min_length: nil, max_length: nil, length: nil, pattern: nil)
36
+ Spec.new(name: name, decoder: :token, min_length: length || min_length, max_length: length || max_length,
37
+ pattern: pattern && Regexp.new("\\A(?:#{pattern})\\z"))
38
+ end
39
+ def g_year = Spec.new(name: :g_year, decoder: :g_year)
40
+ def double(name = :double, min: nil, max: nil, max_exclusive: nil)
41
+ Spec.new(name: name, decoder: :double, min: min, max: max, max_exclusive: max_exclusive)
42
+ end
43
+ def decimal(name = :decimal, min: nil, max: nil, max_exclusive: nil)
44
+ Spec.new(name: name, decoder: :decimal, min: min, max: max, max_exclusive: max_exclusive)
45
+ end
46
+ def integer(name, min:, max:, signed: false) = Spec.new(name: name, decoder: :integer, min: min, max: max, signed: signed)
47
+ def date_time = Spec.new(name: :date_time, decoder: :date_time)
48
+ def boolean = Spec.new(name: :boolean, decoder: :boolean)
49
+
50
+ # values: the schema's enumeration, mapped to symbols in snake_case.
51
+ def enumeration(name, values, preserve: false)
52
+ Spec.new(name: name, decoder: :enumeration, preserve: preserve,
53
+ values: values.to_h { |value| [value, Naming.snake_case(value).to_sym] })
54
+ end
55
+
56
+ UNKNOWN = Spec.new(name: :unknown, decoder: :string).freeze
57
+
58
+ # [raw_value, value, invalid_reason] for text as written. raw_value is the
59
+ # text after the type's whitespace rule: kept for strings, collapsed for
60
+ # everything else (XSD whiteSpace "collapse").
61
+ def decode(spec, text)
62
+ return [text, text, nil] if spec.decoder == :string
63
+
64
+ raw = spec.preserve ? text : collapse(text)
65
+ return decode_token(spec, raw) if spec.decoder == :token
66
+ return [raw, nil, :empty] if raw.empty?
67
+
68
+ value, reason =
69
+ case spec.decoder
70
+ when :double then decode_double(spec, raw)
71
+ when :decimal then decode_decimal(spec, raw)
72
+ when :integer then decode_integer(spec, raw)
73
+ when :date_time then decode_date_time(spec, raw)
74
+ when :enumeration then decode_enumeration(spec, raw)
75
+ when :boolean then decode_boolean(spec, raw)
76
+ when :g_year then decode_g_year(spec, raw)
77
+ end
78
+ [raw, reason ? nil : value, reason]
79
+ end
80
+
81
+ WHITESPACE = /[ \t\r\n]/
82
+
83
+ def collapse(text)
84
+ return text unless text.match?(WHITESPACE)
85
+
86
+ text.gsub(/[ \t\r\n]+/, " ").strip
87
+ end
88
+
89
+ def decode_double(spec, raw)
90
+ return [nil, :not_finite] if NON_FINITE_DOUBLES.include?(raw)
91
+ return [nil, :not_a_number] unless DOUBLE.match?(raw)
92
+
93
+ value = to_float(raw)
94
+ return [nil, :not_finite] unless value.finite?
95
+
96
+ [value, range_reason(spec, value)]
97
+ end
98
+
99
+ # A token, checked against its length and pattern facets.
100
+ def decode_token(spec, raw)
101
+ reason =
102
+ if spec.min_length && raw.length < spec.min_length then :too_short
103
+ elsif spec.max_length && raw.length > spec.max_length then :too_long
104
+ elsif spec.pattern && !spec.pattern.match?(raw) then :no_pattern_match
105
+ end
106
+ [raw, reason ? nil : raw, reason]
107
+ end
108
+
109
+ # xsd:gYear: the year as an Integer; a time zone, if written, stays in
110
+ # the raw value.
111
+ def decode_g_year(_spec, raw)
112
+ match = G_YEAR.match(raw)
113
+ return [nil, :not_a_year] unless match
114
+ return [nil, :not_a_year] if match[2] && !valid_zone?(match[2])
115
+
116
+ [Integer(match[1], 10), nil]
117
+ end
118
+
119
+ # xsd:decimal: no exponent, no INF or NaN.
120
+ def decode_decimal(spec, raw)
121
+ return [nil, :not_a_number] unless DECIMAL.match?(raw)
122
+
123
+ value = to_float(raw)
124
+ return [nil, :not_finite] unless value.finite?
125
+
126
+ [value, range_reason(spec, value)]
127
+ end
128
+
129
+ # Kernel#Float prints "out of range" warnings (with $VERBOSE on) for
130
+ # numbers beyond a Float, which a file could use to flood logs. Numbers
131
+ # are therefore sorted by their decimal order of magnitude first: well
132
+ # inside the Float range they go to Float; far beyond it they are
133
+ # infinite or zero without computing anything large (1e999999999 must
134
+ # not build a billion-digit number); the band in between is computed
135
+ # exactly with Rational, which does not warn.
136
+ SAFE_MAGNITUDE = 300
137
+ MAX_MAGNITUDE = 400
138
+ MAX_FLOAT = Rational(Float::MAX)
139
+
140
+ # XSD allows nothing after the decimal point ("5.", "1.e3"); Ruby before
141
+ # 3.4 does not, so the missing zero is added before converting.
142
+ TRAILING_POINT = /\.(?=[eE]|\z)/
143
+
144
+ def to_float(raw)
145
+ raw = raw.sub(TRAILING_POINT, ".0") if raw.include?(".")
146
+ magnitude = decimal_magnitude(raw)
147
+ return 0.0 if magnitude.nil?
148
+ return Float(raw) if magnitude.abs < SAFE_MAGNITUDE
149
+
150
+ negative = raw.start_with?("-")
151
+ if magnitude >= MAX_MAGNITUDE
152
+ negative ? -Float::INFINITY : Float::INFINITY
153
+ elsif magnitude <= -MAX_MAGNITUDE
154
+ negative ? -0.0 : 0.0
155
+ else
156
+ exact = Rational(raw)
157
+ return negative ? -Float::INFINITY : Float::INFINITY if exact.abs > MAX_FLOAT
158
+
159
+ exact.to_f
160
+ end
161
+ end
162
+
163
+ # The power of ten of the first significant digit ("1500" is 3,
164
+ # "0.025" is -2, "1e400" is 400), or nil for zero. raw has already
165
+ # matched DOUBLE or DECIMAL.
166
+ def decimal_magnitude(raw)
167
+ mantissa, exponent = raw.delete_prefix("+").delete_prefix("-").split(/[eE]/, 2)
168
+ whole, fraction = mantissa.split(".", 2)
169
+ whole = whole.to_s.sub(/\A0+/, "")
170
+ fraction = fraction.to_s
171
+ exponent = exponent ? Integer(exponent, 10) : 0
172
+
173
+ if whole.empty?
174
+ leading = fraction[/\A0*/].length
175
+ return nil if leading == fraction.length
176
+
177
+ exponent - leading - 1
178
+ else
179
+ exponent + whole.length - 1
180
+ end
181
+ end
182
+
183
+ def decode_integer(spec, raw)
184
+ return [nil, :not_an_integer] unless (spec.signed ? SIGNED_INTEGER : UNSIGNED_INTEGER).match?(raw)
185
+
186
+ value = Integer(raw.delete_prefix("+"), 10)
187
+ [value, range_reason(spec, value)]
188
+ end
189
+
190
+ def decode_enumeration(spec, raw)
191
+ value = spec.values[raw]
192
+ [value, value.nil? ? :not_in_enumeration : nil]
193
+ end
194
+
195
+ def decode_boolean(_spec, raw)
196
+ [BOOLEANS[raw], BOOLEANS.key?(raw) ? nil : :not_a_boolean]
197
+ end
198
+
199
+ # A Time in UTC. Text without a UTC offset has no value (decision 1):
200
+ # its time zone is unknown and is never guessed.
201
+ def decode_date_time(_spec, raw)
202
+ match = DATE_TIME.match(raw)
203
+ return [nil, :not_a_date_time] unless match
204
+
205
+ year, month, day, hour, minute = match[1..5].map { |part| Integer(part, 10) }
206
+ second = match[6].include?(".") ? Rational(match[6]) : Integer(match[6], 10)
207
+ zone = match[7]
208
+ return [nil, :not_a_date_time] unless valid_date_time?(year, month, day, hour, minute, second, zone)
209
+ return [nil, :no_utc_offset] unless zone
210
+
211
+ offset = zone == "Z" ? "+00:00" : zone
212
+ [Time.new(year, month, day, hour, minute, second, offset).utc, nil]
213
+ end
214
+
215
+ def valid_date_time?(year, month, day, hour, minute, second, zone)
216
+ return false unless (1..12).cover?(month) && day.between?(1, days_in_month(year, month))
217
+ return false unless hour.between?(0, 23) && minute.between?(0, 59) && second < 60
218
+ zone.nil? || valid_zone?(zone)
219
+ end
220
+
221
+ def valid_zone?(zone)
222
+ return true if zone == "Z"
223
+
224
+ zone_hours, zone_minutes = zone[1..].split(":").map { |part| Integer(part, 10) }
225
+ zone_minutes <= 59 && (zone_hours * 60 + zone_minutes) <= 14 * 60
226
+ end
227
+
228
+ def days_in_month(year, month)
229
+ return 29 if month == 2 && (year % 4).zero? && (!(year % 100).zero? || (year % 400).zero?)
230
+
231
+ DAYS_IN_MONTH[month]
232
+ end
233
+
234
+ def range_reason(spec, value)
235
+ return :out_of_range if spec.min && value < spec.min
236
+ return :out_of_range if spec.max && value > spec.max
237
+ return :out_of_range if spec.max_exclusive && value >= spec.max_exclusive
238
+
239
+ nil
240
+ end
241
+ end
242
+
243
+ module Naming
244
+ module_function
245
+
246
+ CACHE_SIZE = 4096
247
+ @cache = {}
248
+
249
+ # "HeartRateBpm" => "heart_rate_bpm", "ProductID" => "product_id".
250
+ # Cached, since the same few names repeat on every trackpoint; the cache
251
+ # is bounded because unknown names come from the file.
252
+ def snake_case(name)
253
+ cache = Naming.instance_variable_get(:@cache)
254
+ cached = cache[name]
255
+ return cached if cached
256
+
257
+ converted = convert(name).freeze
258
+ cache[name.dup.freeze] = converted if cache.size < CACHE_SIZE
259
+ converted
260
+ end
261
+
262
+ def convert(name)
263
+ name.to_s
264
+ .gsub(/([A-Z]+)([A-Z][a-z])/, '\1_\2')
265
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
266
+ .tr("- ", "__")
267
+ .downcase
268
+ end
269
+ end
270
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TcxKit
4
+ VERSION = "0.1.0"
5
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TcxKit
4
+ module XML
5
+ # Measures reading time for Limits#max_seconds, leaving out the time
6
+ # spent in the caller's block.
7
+ class Clock
8
+ MONOTONIC = -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) }
9
+
10
+ def initialize(max_seconds, now: MONOTONIC)
11
+ @max_seconds = max_seconds
12
+ @now = now
13
+ @started = now.call
14
+ @paused = 0.0
15
+ end
16
+
17
+ # Starts measuring from now.
18
+ def restart
19
+ @started = @now.call
20
+ @paused = 0.0
21
+ end
22
+
23
+ def exceeded?
24
+ @max_seconds && (@now.call - @started - @paused) > @max_seconds
25
+ end
26
+
27
+ # Runs the caller's block without counting its time. Without a time
28
+ # limit there is nothing to measure.
29
+ def outside
30
+ return yield unless @max_seconds
31
+
32
+ started = @now.call
33
+ begin
34
+ yield
35
+ ensure
36
+ @paused += @now.call - started
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,60 @@
1
+ # frozen_string_literal: true
2
+
3
+ module TcxKit
4
+ module XML
5
+ # An attribute as written: namespace URI (nil for none), local name and value.
6
+ Attribute = Struct.new(:namespace, :name, :value, keyword_init: true)
7
+
8
+ # One XML element. Its text is known when it closes: the text as written
9
+ # for an element without child elements, nil for one with children.
10
+ class Element
11
+ attr_reader :namespace, :name, :attributes, :line, :column, :depth, :text
12
+
13
+ def initialize(namespace:, name:, attributes:, line:, column:, depth:)
14
+ @namespace = namespace
15
+ @name = name
16
+ @attributes = attributes
17
+ @line = line
18
+ @column = column
19
+ @depth = depth
20
+ @children = false
21
+ @buffer = nil
22
+ @text = nil
23
+ end
24
+
25
+ def children?
26
+ @children
27
+ end
28
+
29
+ def attribute(name, namespace: nil)
30
+ attributes.find { |attribute| attribute.name == name && attribute.namespace == namespace }
31
+ end
32
+
33
+ # Called by the Parser while reading.
34
+
35
+ def child_started!
36
+ @children = true
37
+ @buffer = nil
38
+ end
39
+
40
+ # Appends text and returns the text's size in bytes so far.
41
+ def append_text(string)
42
+ return 0 if @children
43
+
44
+ if @buffer.nil?
45
+ @buffer = string
46
+ else
47
+ @buffer = +@buffer if @buffer.frozen?
48
+ @buffer << string
49
+ end
50
+ @buffer.bytesize
51
+ end
52
+
53
+ def finish!
54
+ @text = @children ? nil : (@buffer || "").freeze
55
+ @buffer = nil
56
+ freeze
57
+ end
58
+ end
59
+ end
60
+ end
@@ -0,0 +1,193 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "nokogiri"
4
+
5
+ module TcxKit
6
+ module XML
7
+ # Streams the elements of an XML document with Nokogiri's SAX parser,
8
+ # enforcing Limits and refusing unsafe input. Knows nothing about TCX.
9
+ #
10
+ # Parser.new(io, limits: Limits::DEFAULT, source_label: "run.tcx").each_event do |type, element|
11
+ # # type is :start or :end; element.text is set at :end
12
+ # end
13
+ #
14
+ # One pass only. Internal API: use Reader.
15
+ class Parser < Nokogiri::XML::SAX::Document
16
+ def initialize(io, limits:, source_label:)
17
+ super()
18
+ @io = io
19
+ @limits = limits
20
+ @source_label = source_label
21
+ @clock = Clock.new(limits.max_seconds)
22
+ @max_elements = limits.max_elements
23
+ @max_depth = limits.max_depth
24
+ @max_text_bytes = limits.max_text_bytes
25
+ end
26
+
27
+ # Runs a block without counting its time towards Limits#max_seconds.
28
+ def outside(&block)
29
+ @clock.outside(&block)
30
+ end
31
+
32
+ def each_event(&block)
33
+ raise ArgumentError, "each_event needs a block" unless block
34
+ raise Error.new("A Parser reads once", source: @source_label) if @block
35
+
36
+ @block = block
37
+ @clock.restart
38
+ @source = Source.new(@io, limits: @limits, source_label: @source_label, clock: @clock)
39
+ @stack = []
40
+ @elements = 0
41
+ @root_seen = false
42
+
43
+ Nokogiri::XML::SAX::Parser.new(self).parse_io(@source) do |context|
44
+ context.replace_entities = false
45
+ context.recovery = false
46
+ @context = context
47
+ end
48
+
49
+ raise @source.error if @source.error
50
+ raise invalid("The document has no root element") unless @root_seen
51
+ raise truncated("The document ended before its root element closed") unless @stack.empty?
52
+
53
+ nil
54
+ end
55
+
56
+ # SAX callbacks
57
+
58
+ NO_ATTRIBUTES = [].freeze
59
+
60
+ # How many elements pass between clock checks.
61
+ CLOCK_INTERVAL = 64
62
+
63
+ def start_element_namespace(name, attrs = [], _prefix = nil, uri = nil, _namespaces = [])
64
+ raise_source_error
65
+ @elements += 1
66
+ check_clock if (@elements % CLOCK_INTERVAL).zero?
67
+ exceeded(:max_elements, "More than #{@max_elements} elements") if @max_elements && @elements > @max_elements
68
+ depth = @stack.size + 1
69
+ exceeded(:max_depth, "Elements nested deeper than #{@max_depth}") if @max_depth && depth > @max_depth
70
+
71
+ attributes = attrs.empty? ? NO_ATTRIBUTES : attrs.map do |attribute|
72
+ if @max_text_bytes && attribute.value.bytesize > @max_text_bytes
73
+ exceeded(:max_text_bytes, "Attribute #{short(attribute.localname)} is over the #{@max_text_bytes}-byte text limit")
74
+ end
75
+ Attribute.new(namespace: attribute.uri, name: attribute.localname, value: attribute.value).freeze
76
+ end.freeze
77
+
78
+ # libxml2 reports a start tag cut off by the end of the input (as in
79
+ # "<Trai") before failing on it. A complete start tag ends at or after
80
+ # the reported position, so there is text after it.
81
+ if @source.eof? && @source.tail_after(@context.line, @context.column) == ""
82
+ raise truncated("The document ended inside the start tag of #{short(name)}")
83
+ end
84
+
85
+ @stack.last&.child_started!
86
+ element = Element.new(namespace: uri, name: name, attributes: attributes,
87
+ line: @context.line, column: @context.column, depth: depth)
88
+ @root_seen = true
89
+ @stack << element
90
+ emit(:start, element)
91
+ end
92
+
93
+ def end_element_namespace(_name, _prefix = nil, _uri = nil)
94
+ raise_source_error
95
+ element = @stack.pop
96
+ element.finish!
97
+ emit(:end, element)
98
+ end
99
+
100
+ def characters(string)
101
+ element = @stack.last
102
+ return unless element
103
+
104
+ size = element.append_text(string)
105
+ return unless @max_text_bytes && size > @max_text_bytes
106
+
107
+ exceeded(:max_text_bytes, "Text of #{short(element.name)} is over the #{@max_text_bytes}-byte limit")
108
+ end
109
+
110
+ def cdata_block(string)
111
+ characters(string)
112
+ end
113
+
114
+ # Nokogiri calls this for a reference to an entity declared in a DTD,
115
+ # never for the five predefined entities or character references.
116
+ def reference(name, _content)
117
+ raise UnsafeContentError.new("Reference to the DTD entity #{short(name)}", **position)
118
+ end
119
+
120
+ # Namespace errors that libxml2 reports and reads past: the element is
121
+ # read without a namespace (SPECIFICATION.md, section 7).
122
+ NAMESPACE_ERRORS = [
123
+ /\ANamespace prefix \S+ (?:for \S+ )?on \S+ is not defined\z/,
124
+ /\Axmlns(?::\S+)?: Empty XML namespace is not allowed\z/
125
+ ].freeze
126
+
127
+ def error(message)
128
+ raise_source_error
129
+ message = message.to_s.strip
130
+ return if NAMESPACE_ERRORS.any? { |pattern| pattern.match?(message) }
131
+ raise truncated(message) if cut_off?(message)
132
+
133
+ raise invalid(message)
134
+ end
135
+
136
+ def warning(_message); end
137
+
138
+ private
139
+
140
+ # Events go straight to the block: its time counts as reading time.
141
+ # The Reader leaves out only the time spent in its caller's block,
142
+ # through #outside, once per message instead of once per element.
143
+ def emit(type, element)
144
+ @block.call(type, element)
145
+ end
146
+
147
+ # A file that was cut off makes libxml2 fail at the end of the input,
148
+ # before the root element has closed, with at most part of one token
149
+ # (a name, a value, some text) after the reported position. A malformed
150
+ # file has markup after it. A mismatched end tag at the very end is
151
+ # malformed too.
152
+ def cut_off?(message)
153
+ return false unless @source.eof? && @source.markup?
154
+ return false if @root_seen && @stack.empty?
155
+ return false if message.include?("mismatch")
156
+
157
+ tail = @source.tail_after(@context.line, @context.column)
158
+ !tail.nil? && !tail.match?(/[<>]/)
159
+ end
160
+
161
+ def check_clock
162
+ return unless @clock.exceeded?
163
+
164
+ raise LimitExceededError.new("Reading took more than #{@limits.max_seconds} s",
165
+ limit: :max_seconds, **position)
166
+ end
167
+
168
+ def exceeded(limit, message)
169
+ raise LimitExceededError.new(message, limit: limit, **position)
170
+ end
171
+
172
+ def raise_source_error
173
+ raise @source.error if @source.error
174
+ end
175
+
176
+ def invalid(message)
177
+ InvalidFileError.new(message, **position)
178
+ end
179
+
180
+ def truncated(message)
181
+ TruncatedFileError.new(message, **position)
182
+ end
183
+
184
+ def position
185
+ { source: @source_label, line: @context&.line, column: @context&.column }
186
+ end
187
+
188
+ def short(name)
189
+ name.to_s.length > 64 ? "#{name.to_s[0, 64]}..." : name.to_s
190
+ end
191
+ end
192
+ end
193
+ end