makiri 0.3.0-aarch64-linux → 0.5.0-aarch64-linux

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.
@@ -48,17 +48,13 @@ module Makiri
48
48
  # Run a CSS selector against every node and return the unioned matches.
49
49
  # @return [Makiri::NodeSet]
50
50
  def css(selector)
51
- return self if empty?
52
-
53
- map { |node| node.css(selector) }.reduce(:|)
51
+ union_query(:css, selector)
54
52
  end
55
53
 
56
54
  # Run an XPath expression against every node and union the node-set results.
57
55
  # @return [Makiri::NodeSet]
58
56
  def xpath(expr)
59
- return self if empty?
60
-
61
- map { |node| node.xpath(expr) }.reduce(:|)
57
+ union_query(:xpath, expr)
62
58
  end
63
59
 
64
60
  # First node matching the CSS selector across the set, or nil.
@@ -77,9 +73,7 @@ module Makiri
77
73
  # CSS- or XPath-detecting query against every node (see {Node#search}).
78
74
  # @return [Makiri::NodeSet]
79
75
  def search(path)
80
- return self if empty?
81
-
82
- map { |node| node.search(path) }.reduce(:|)
76
+ union_query(:search, path)
83
77
  end
84
78
 
85
79
  # Remove the named attribute from every node in the set.
@@ -109,5 +103,16 @@ module Makiri
109
103
  def inspect
110
104
  "#<#{self.class.name} length=#{length}>"
111
105
  end
106
+
107
+ private
108
+
109
+ # Run +method+(+arg+) on every node in the set and union the per-node
110
+ # results. An empty set returns self unchanged, so it stays a NodeSet (the
111
+ # shared shape behind #css / #xpath / #search).
112
+ def union_query(method, arg)
113
+ return self if empty?
114
+
115
+ map { |node| node.public_send(method, arg) }.reduce(:|)
116
+ end
112
117
  end
113
118
  end
@@ -12,9 +12,15 @@ module Makiri
12
12
  # @param content [String]
13
13
  # @return [Makiri::ProcessingInstruction]
14
14
  def self.new(document, target, content)
15
- raise TypeError, "expected a Makiri::Document" unless document.is_a?(Makiri::Document)
15
+ Makiri::Document.coerce!(document).create_processing_instruction(target, content)
16
+ end
16
17
 
17
- document.create_processing_instruction(target, content)
18
+ # DOM `ProcessingInstruction#target` — the PI's target name. Defined once on
19
+ # the shared base so both backends expose it: the XML node reaches it here
20
+ # (its target IS its node name), while the HTML node overrides it with a
21
+ # native implementation earlier in the ancestor chain.
22
+ def target
23
+ name
18
24
  end
19
25
  end
20
26
  end
data/lib/makiri/text.rb CHANGED
@@ -10,9 +10,7 @@ module Makiri
10
10
  # @param document [Makiri::Document]
11
11
  # @return [Makiri::Text]
12
12
  def self.new(content, document)
13
- raise TypeError, "expected a Makiri::Document" unless document.is_a?(Makiri::Document)
14
-
15
- document.create_text_node(content)
13
+ Makiri::Document.coerce!(document).create_text_node(content)
16
14
  end
17
15
  end
18
16
  end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Makiri
4
- VERSION = "0.3.0"
4
+ VERSION = "0.5.0"
5
5
  end
@@ -0,0 +1,271 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Makiri
4
+ module XML
5
+ # A Nokogiri-compatible DSL for building an XML document (or subtree) from
6
+ # scratch. It is a thin, pure-Ruby layer over the public construction surface
7
+ # (+XML::Document.new+, +Document#create_element+ / +#create_text_node+ /
8
+ # +#create_cdata+ / +#create_comment+, and +Node#add_child+); no C code is
9
+ # involved.
10
+ #
11
+ # @example Block-with-argument form (recommended)
12
+ # builder = Makiri::XML::Builder.new do |xml|
13
+ # xml.feed("xmlns" => "urn:a") do
14
+ # xml.entry do
15
+ # xml.title("Hello")
16
+ # end
17
+ # end
18
+ # end
19
+ # builder.to_xml
20
+ #
21
+ # @example instance_eval form (no block argument)
22
+ # builder = Makiri::XML::Builder.new do
23
+ # root { child("text") }
24
+ # end
25
+ #
26
+ # An element is created by calling a method named after the tag. Trailing
27
+ # arguments follow the Nokogiri convention: a Hash sets attributes (including
28
+ # +xmlns+ / +xmlns:prefix+ namespace declarations), any other argument becomes
29
+ # the element's text content, and a block builds nested children.
30
+ #
31
+ # Tag names that collide with a Ruby/Kernel method (or with one of this
32
+ # builder's own helpers below - +text+, +cdata+, +comment+, +doc+, +parent+,
33
+ # +to_xml+, +to_s+, +descend+) must be written with a trailing underscore, which is
34
+ # stripped: +xml.id_("9")+ produces +<id>9</id>+. This matches Nokogiri.
35
+ #
36
+ # A namespace prefix is selected for the next element with +[]+:
37
+ # +xml["dc"].title+ produces +<dc:title>+ (the prefix must be in scope, i.e.
38
+ # declared via an +"xmlns:dc"+ attribute on an ancestor or on the element
39
+ # itself, exactly as Makiri resolves prefixes at insertion time).
40
+ class Builder
41
+ # The document being built (a {Makiri::XML::Document}).
42
+ attr_reader :doc
43
+
44
+ # The node new children are currently appended to. While a nested block is
45
+ # running this is that block's element; otherwise it is {#doc}.
46
+ attr_reader :parent
47
+
48
+ # @param options [Hash] accepted for Nokogiri compatibility and ignored - a
49
+ # Makiri document has no configurable options (it is always UTF-8).
50
+ # @param root [Makiri::XML::Node, nil] when given, build into this node:
51
+ # top-level calls append to it and its document is used. (This is what
52
+ # {.with} passes; mirrors +Nokogiri::XML::Builder.new(options, root)+.)
53
+ # @yield [self] when the block takes an argument; otherwise the block is
54
+ # +instance_eval+'d against the builder.
55
+ def initialize(options = {}, root = nil, &block)
56
+ if root
57
+ @doc = root.document
58
+ @parent = root
59
+ else
60
+ @parent = @doc = Makiri::XML::Document.new
61
+ end
62
+ @ns_prefix = nil
63
+ @arity = nil
64
+ return unless block
65
+
66
+ run(&block)
67
+ @parent = @doc # like Nokogiri: after a build block, settle back at the document
68
+ end
69
+
70
+ # Build into an existing node: top-level calls append to +node+, using
71
+ # +node+'s document. Mirrors +Nokogiri::XML::Builder.with+.
72
+ #
73
+ # @param node [Makiri::XML::Node]
74
+ # @return [Builder]
75
+ def self.with(node, &block)
76
+ new({}, node, &block)
77
+ end
78
+
79
+ # Append a text node to the current parent.
80
+ # @return [NodeBuilder]
81
+ def text(string)
82
+ insert(@doc.create_text_node(string.to_s))
83
+ end
84
+
85
+ # Append a CDATA section to the current parent.
86
+ # @return [NodeBuilder]
87
+ def cdata(string)
88
+ insert(@doc.create_cdata(string.to_s))
89
+ end
90
+
91
+ # Append a comment node to the current parent.
92
+ # @return [NodeBuilder]
93
+ def comment(string)
94
+ insert(@doc.create_comment(string.to_s))
95
+ end
96
+
97
+ # Parse +string+ as an XML fragment (against the document's in-scope
98
+ # namespaces) and append its children to the current parent. The Builder
99
+ # analogue of +Nokogiri::XML::Builder#<<+.
100
+ # @return [self]
101
+ def <<(string)
102
+ @doc.fragment(string).children.to_a.each { |child| insert(child) }
103
+ self
104
+ end
105
+
106
+ # Select the namespace prefix for the next element (consumed by the next
107
+ # tag method). Returns self so it reads as +xml["dc"].title+.
108
+ # @return [self]
109
+ def [](ns_prefix)
110
+ @ns_prefix = ns_prefix.to_s
111
+ self
112
+ end
113
+
114
+ # Serialize the built document. Forwards to {Document#to_xml} (so +pretty:+
115
+ # works).
116
+ def to_xml(...)
117
+ @doc.to_xml(...)
118
+ end
119
+ alias_method :to_s, :to_xml
120
+
121
+ # Any other method name is a tag: create the element and insert it.
122
+ def method_missing(name, *args, &block)
123
+ tag = name.to_s.sub(/[_!]\z/, "")
124
+ prefix = @ns_prefix
125
+ if prefix
126
+ tag = "#{prefix}:#{tag}"
127
+ @ns_prefix = nil
128
+ end
129
+ node = create_element(tag, args)
130
+ check_prefix_defined!(node, prefix) if prefix
131
+ insert(node, &block)
132
+ end
133
+
134
+ # Tag methods are open-ended, so report respond_to? truthfully for them
135
+ # (anything that is not already a real method is a candidate tag).
136
+ def respond_to_missing?(_name, _include_private = false)
137
+ true
138
+ end
139
+
140
+ # Run +block+ with +node+ as the current parent, restoring the previous
141
+ # parent afterward (even if the block raises) and returning the block's
142
+ # value. The single place +@parent+ is pushed/popped - shared by #insert and
143
+ # by {NodeBuilder}'s nested-block chain, so neither manipulates the parent
144
+ # state directly. Public so NodeBuilder (a separate class) can reuse it
145
+ # without reaching into a private method.
146
+ def descend(node, &block)
147
+ previous = @parent
148
+ @parent = node
149
+ begin
150
+ run(&block)
151
+ ensure
152
+ @parent = previous
153
+ end
154
+ end
155
+
156
+ private
157
+
158
+ # Translate the Nokogiri-style trailing arguments (a Hash is attributes,
159
+ # anything else is text content) into a {Document#create_element} call.
160
+ def create_element(tag, args)
161
+ text = nil
162
+ attributes = nil
163
+ args.each do |arg|
164
+ if arg.is_a?(Hash)
165
+ attributes = attributes ? attributes.merge(arg) : arg
166
+ else
167
+ text = arg
168
+ end
169
+ end
170
+ cargs = []
171
+ cargs << text.to_s unless text.nil?
172
+ cargs << attributes unless attributes.nil?
173
+ @doc.create_element(tag, *cargs)
174
+ end
175
+
176
+ # Raise like Nokogiri when a prefix selected via +[]+ resolves nowhere: not
177
+ # in scope at the insertion point (+@parent+ and its ancestors) and not
178
+ # self-declared on +node+ itself (e.g. +xml["foo"].root("xmlns:foo" => ...)+).
179
+ def check_prefix_defined!(node, prefix)
180
+ return if @parent.respond_to?(:namespaces) && @parent.namespaces.key?("xmlns:#{prefix}")
181
+ return if node.namespace_definitions.any? { |ns| ns.prefix == prefix }
182
+
183
+ raise ArgumentError, "Namespace #{prefix} has not been defined"
184
+ end
185
+
186
+ # Append +node+ to the current parent, then, if a block is given, descend
187
+ # into the inserted node for the duration of that block. Returns a
188
+ # {NodeBuilder} over the inserted node (which may be an imported copy, e.g.
189
+ # from a fragment), so the Nokogiri attribute-shortcut chain works.
190
+ def insert(node, &block)
191
+ node = @parent.add_child(node)
192
+ descend(node, &block) if block
193
+ NodeBuilder.new(node, self)
194
+ end
195
+
196
+ # Run a DSL block, choosing instance_eval vs yield once (from the first
197
+ # block seen), the same way Nokogiri does, so the form is consistent
198
+ # throughout a build.
199
+ def run(&block)
200
+ @arity = block.arity if @arity.nil?
201
+ if @arity <= 0
202
+ instance_eval(&block)
203
+ else
204
+ block.call(self)
205
+ end
206
+ end
207
+
208
+ # The value returned by each element call, wrapping the just-inserted node
209
+ # so attributes can be added with the Nokogiri terse-chain syntax:
210
+ #
211
+ # xml.object.classy.thing! # => <object class="classy" id="thing"/>
212
+ #
213
+ # A plain method name appends to the +class+ attribute, +name!+ sets +id+
214
+ # (and content if given), +name=+ sets that attribute, a trailing Hash adds
215
+ # each key as an attribute, and a block descends into the node. +[]+ / +[]=+
216
+ # read and write attributes directly. Semantics mirror
217
+ # +Nokogiri::XML::Builder::NodeBuilder+.
218
+ class NodeBuilder
219
+ def initialize(node, doc_builder)
220
+ @node = node
221
+ @doc_builder = doc_builder
222
+ end
223
+
224
+ # Read an attribute of the wrapped node.
225
+ def [](key)
226
+ @node[key]
227
+ end
228
+
229
+ # Write an attribute of the wrapped node.
230
+ def []=(key, value)
231
+ @node[key] = value
232
+ end
233
+
234
+ def method_missing(method, *args, &block)
235
+ opts = args.last.is_a?(Hash) ? args.pop : {}
236
+ case method.to_s
237
+ when /\A(.*)!\z/
238
+ @node["id"] = Regexp.last_match(1)
239
+ @node.content = args.first if args.first
240
+ when /\A(.*)=\z/
241
+ @node[Regexp.last_match(1)] = args.first
242
+ else
243
+ append_attr("class", method.to_s)
244
+ @node.content = args.first if args.first
245
+ end
246
+
247
+ opts.each { |key, value| append_attr(key.to_s, value) }
248
+
249
+ # Descend into this node for a nested block via the builder's own parent
250
+ # stack (with its ensure-based restore), rather than re-rooting it by hand.
251
+ return @doc_builder.descend(@node, &block) if block
252
+
253
+ self
254
+ end
255
+
256
+ def respond_to_missing?(_name, _include_private = false)
257
+ true
258
+ end
259
+
260
+ private
261
+
262
+ # Append +value+ as a space-separated token to the +key+ attribute,
263
+ # preserving any existing tokens. The shared idiom behind the terse
264
+ # class-append and the trailing-Hash attribute shortcut.
265
+ def append_attr(key, value)
266
+ @node[key] = ((@node[key] || "").split(/\s/) + [value]).join(" ")
267
+ end
268
+ end
269
+ end
270
+ end
271
+ end
@@ -32,6 +32,53 @@ module Makiri
32
32
  end
33
33
 
34
34
  alias_method :has_attribute?, :key? unless method_defined?(:has_attribute?)
35
+
36
+ # CSS selector queries over XML, lowered to the native XPath engine (so
37
+ # matching is case-sensitive and namespace-aware, unlike a Lexbor HTML
38
+ # matcher). Nokogiri-compatible namespaces: the document's in-scope
39
+ # declarations are collected automatically (a bare type selector binds to
40
+ # the default namespace), and an optional +ns+ hash of {prefix => uri}
41
+ # supplements/overrides them.
42
+ #
43
+ # doc.css("entry") # default-namespace bound (Atom/RSS just work)
44
+ # doc.css("a|entry", "a" => uri) # explicit prefix
45
+ #
46
+ # @return [Makiri::NodeSet]
47
+ def css(selector, ns = nil)
48
+ _css(selector.to_s, _css_namespaces(ns))
49
+ end
50
+
51
+ # First descendant matching +selector+, or nil. @return [Makiri::Node, nil]
52
+ def at_css(selector, ns = nil)
53
+ _at_css(selector.to_s, _css_namespaces(ns))
54
+ end
55
+
56
+ # Whether this node matches +selector+ (full selector, combinators included).
57
+ # @return [Boolean]
58
+ def matches?(selector, ns = nil)
59
+ _css_matches(selector.to_s, _css_namespaces(ns))
60
+ end
61
+
62
+ private
63
+
64
+ # Build the {prefix => uri} hash the C primitives register. Matching
65
+ # Nokogiri: with NO explicit namespaces the document's own declarations are
66
+ # collected (the default namespace under the synthetic prefix "xmlns", so a
67
+ # bare type selector binds to it - the RSS/Atom common case); but once the
68
+ # caller passes a namespaces hash, ONLY those prefixes are used and a bare
69
+ # selector resolves to no namespace (Nokogiri disables the default binding
70
+ # the moment an explicit map is given). Reading only the root's
71
+ # declarations is O(root attributes), not the whole-document walk.
72
+ def _css_namespaces(user)
73
+ return user.transform_keys(&:to_s).transform_values(&:to_s) if user && !user.empty?
74
+
75
+ reg = {}
76
+ root = document&.root
77
+ root&.namespace_definitions&.each do |ns|
78
+ reg[ns.prefix.nil? ? "xmlns" : ns.prefix] = ns.href
79
+ end
80
+ reg
81
+ end
35
82
  end
36
83
  end
37
84
  end
@@ -14,10 +14,18 @@ module Makiri
14
14
  # The bulk of the implementation lives in C (see
15
15
  # ext/makiri/glue/ruby_xpath.c and ext/makiri/xpath/).
16
16
  class XPathContext
17
- # +#evaluate+ is defined in C. It evaluates under the GVL (XPath never
18
- # releases it), so concurrent +evaluate+ / +register_*+ / +node=+ on the
19
- # same context - and any tree mutation of the document being queried - are
20
- # serialised by the GVL and cannot corrupt memory.
17
+ # +#evaluate+ is defined in C and runs under the GVL (XPath never releases
18
+ # it), so it cannot corrupt memory under concurrency. Two distinct hazards,
19
+ # handled differently:
20
+ #
21
+ # * Cross-thread: the GVL serialises all of +evaluate+ / +register_*+ /
22
+ # +node=+ and any tree mutation of the queried document, so threads can
23
+ # never run two of them at once.
24
+ # * Same-thread re-entrancy: a custom function handler runs mid-evaluate and
25
+ # could call back into this same context. A re-entrant +register_namespace+
26
+ # / +register_variable+ / +node=+ is refused (raises) while an evaluate is
27
+ # in progress, since it would free/swap state the suspended evaluator still
28
+ # borrows; a nested +evaluate+ is allowed.
21
29
 
22
30
  # Nokogiri-compatible name for {#register_namespace}.
23
31
  alias register_ns register_namespace
data/lib/makiri.rb CHANGED
@@ -21,6 +21,7 @@ require_relative "makiri/html/document"
21
21
  require_relative "makiri/xml"
22
22
  require_relative "makiri/xml/node_methods"
23
23
  require_relative "makiri/xml/document"
24
+ require_relative "makiri/xml/builder"
24
25
  require_relative "makiri/element"
25
26
  require_relative "makiri/attr"
26
27
  require_relative "makiri/text"