schemic 0.1.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 +7 -0
- data/.gitignore +13 -0
- data/.rspec +2 -0
- data/.rubocop.yml +183 -0
- data/.rvmrc +53 -0
- data/.travis.yml +5 -0
- data/CODE_OF_CONDUCT.md +49 -0
- data/Gemfile +10 -0
- data/LICENSE.txt +21 -0
- data/README.md +194 -0
- data/Rakefile +14 -0
- data/TODO +3 -0
- data/bin/console +15 -0
- data/bin/setup +8 -0
- data/exe/schemic +15 -0
- data/lib/schemic/adapter/rails.rb +160 -0
- data/lib/schemic/adapter.rb +12 -0
- data/lib/schemic/crawler/cache.rb +77 -0
- data/lib/schemic/crawler/http.rb +163 -0
- data/lib/schemic/crawler/navigation.rb +125 -0
- data/lib/schemic/crawler/pipeline.rb +123 -0
- data/lib/schemic/crawler.rb +161 -0
- data/lib/schemic/generator/ruby.rb +41 -0
- data/lib/schemic/generator/yaml.rb +23 -0
- data/lib/schemic/generator.rb +21 -0
- data/lib/schemic/inflector.rb +66 -0
- data/lib/schemic/parser/callbacks.rb +71 -0
- data/lib/schemic/parser/cli/input.rb +62 -0
- data/lib/schemic/parser/cli/switches.rb +52 -0
- data/lib/schemic/parser/cli.rb +148 -0
- data/lib/schemic/parser/methods/selectors.rb +98 -0
- data/lib/schemic/parser/methods.rb +177 -0
- data/lib/schemic/parser/selection.rb +78 -0
- data/lib/schemic/parser/values.rb +122 -0
- data/lib/schemic/parser.rb +121 -0
- data/lib/schemic/version.rb +6 -0
- data/lib/schemic.rb +12 -0
- data/schemic.gemspec +44 -0
- data/tools/rubocop/compact_block_braces.rb +39 -0
- data/tools/rubocop/spacing.rb +96 -0
- metadata +279 -0
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Selector construction for the Ruby schema DSL.
|
|
4
|
+
module Schemic::Parser::Methods::Selectors
|
|
5
|
+
# +paths_context+ объединяет переданные строки контекста в единую строку в
|
|
6
|
+
# формате xpath.
|
|
7
|
+
#
|
|
8
|
+
# +forms_in+ array of some parent nodes to search the +name+ node in.
|
|
9
|
+
#
|
|
10
|
+
# special chars for from and context options' fields are:
|
|
11
|
+
# @ - root context
|
|
12
|
+
# ^ - parent context
|
|
13
|
+
# . or <blank> - current context
|
|
14
|
+
#
|
|
15
|
+
# Example 1:
|
|
16
|
+
# args:
|
|
17
|
+
# from: ["deliveryEndDateTime"]
|
|
18
|
+
# context: "ns2:documentationDelivery"
|
|
19
|
+
# out:
|
|
20
|
+
# paths: ["ns2|documentationDelivery > deliveryEndDateTime"]
|
|
21
|
+
# dom_context: # current
|
|
22
|
+
#
|
|
23
|
+
# Example 2:
|
|
24
|
+
# args:
|
|
25
|
+
# from: ["ns2:documentationDelivery>lots", ""]
|
|
26
|
+
# context: "@lot"
|
|
27
|
+
# out:
|
|
28
|
+
# paths: ["lot>ns2|documentationDelivery>lots", "lot>ns2|documentationDelivery"]
|
|
29
|
+
# dom_context: # root
|
|
30
|
+
#
|
|
31
|
+
# Example 3:
|
|
32
|
+
# args:
|
|
33
|
+
# from: ["ns2:documentationDelivery", "^"]
|
|
34
|
+
# context: "^^"
|
|
35
|
+
# out:
|
|
36
|
+
# paths: ["documentationDelivery", ""]
|
|
37
|
+
# dom_context: # parent * 3
|
|
38
|
+
#
|
|
39
|
+
def make_selector name, options_in
|
|
40
|
+
options = options_in.dup
|
|
41
|
+
paths = selector_paths(name, options)
|
|
42
|
+
|
|
43
|
+
paths.to_h {|path| selector_pair(name, path, options) }.to_os
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
def filter_hashes hashes, by
|
|
47
|
+
values = [hashes].flatten
|
|
48
|
+
|
|
49
|
+
values.filter_map do |hash|
|
|
50
|
+
selected = (hash.keys & by).to_h {|key| [key, hash[key]] }
|
|
51
|
+
|
|
52
|
+
selected unless selected.empty?
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# Combines DSL and local contexts, omitting blank parts before joining child selectors.
|
|
57
|
+
# @param context [String, Array] Local context declaration.
|
|
58
|
+
# @return [String] Combined context path.
|
|
59
|
+
def selector_context context
|
|
60
|
+
parts = [current_context, context].flatten
|
|
61
|
+
|
|
62
|
+
parts.reject!(&:blank?)
|
|
63
|
+
|
|
64
|
+
parts.join('/')
|
|
65
|
+
end
|
|
66
|
+
|
|
67
|
+
# Builds selector alternatives from source paths and optional contexts without mutating caller data.
|
|
68
|
+
# @param name [String] Default field selector.
|
|
69
|
+
# @param options [Hash] Local options copy, consumed for from/context keys.
|
|
70
|
+
# @return [Array<String>] Source selector paths.
|
|
71
|
+
def selector_paths name, options
|
|
72
|
+
froms = [options.delete(:from) || [name].compact].flatten
|
|
73
|
+
paths =
|
|
74
|
+
if options[:context]
|
|
75
|
+
[options.delete(:context)].flatten.integrate(froms).map {|from| from.reject(&:blank?).join('>') }
|
|
76
|
+
else
|
|
77
|
+
froms
|
|
78
|
+
end
|
|
79
|
+
|
|
80
|
+
paths.map!(&:to_s)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Normalizes root/parent markers and namespace syntax while retaining CSS class dots.
|
|
84
|
+
# @param name [String] Field name used for standalone dot placeholders.
|
|
85
|
+
# @param path [String] Raw selector.
|
|
86
|
+
# @param options [Hash] Remaining selector options.
|
|
87
|
+
# @return [Array] Normalized selector and its level/options pair.
|
|
88
|
+
def selector_pair name, path, options
|
|
89
|
+
no_parent = path.delete('^')
|
|
90
|
+
level = path.size - no_parent.size
|
|
91
|
+
no_root = no_parent.delete('@')
|
|
92
|
+
level_root = no_root.size < no_parent.size ? -1 : level
|
|
93
|
+
normalized = no_root.sub(':', '|').tr('/', '>')
|
|
94
|
+
new_path = normalized.gsub(/(^|[>\s])\.(?=$|[>\s])/) {|token| token.sub('.', name.to_s) }
|
|
95
|
+
|
|
96
|
+
[new_path, transform_selector_keys({ level: level_root }.merge(options))]
|
|
97
|
+
end
|
|
98
|
+
end
|
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Cartesian-product helper retained for existing schema builders.
|
|
4
|
+
class Array
|
|
5
|
+
# [1,2].map { |x| [3,4].map { |y| [x, y] } }.flatten(1)
|
|
6
|
+
#=> [[1, 3], [1, 4], [2, 3], [2, 4]]
|
|
7
|
+
def integrate ary2
|
|
8
|
+
flat_map {|x| ary2.map {|y| [x, y] }}
|
|
9
|
+
end
|
|
10
|
+
end
|
|
11
|
+
|
|
12
|
+
# Ruby DSL for fields, nested schemas and selector configuration.
|
|
13
|
+
module Schemic::Parser::Methods
|
|
14
|
+
autoload :Selectors, 'schemic/parser/methods/selectors'
|
|
15
|
+
|
|
16
|
+
include Selectors
|
|
17
|
+
|
|
18
|
+
CONTEXT_KEYS = %i[by re from context field on_proceed scheme on_found].freeze
|
|
19
|
+
FIELD_KEYS = %i[required as if update update_field on_complete map postfix].freeze
|
|
20
|
+
PURE_CONTEXT_KEYS = %i[from context].freeze
|
|
21
|
+
|
|
22
|
+
# Defines a named nested schema and restores its parent after an exception.
|
|
23
|
+
# @param name [String, Symbol] Schema name.
|
|
24
|
+
# @param options [Hash] Reserved schema options.
|
|
25
|
+
# @yield Defines fields in this schema.
|
|
26
|
+
# @return [String] Defined scope name.
|
|
27
|
+
def scheme name, _options = {}
|
|
28
|
+
current_scheme_path << name.to_s
|
|
29
|
+
yield
|
|
30
|
+
|
|
31
|
+
name.to_s
|
|
32
|
+
ensure
|
|
33
|
+
current_scheme_path.pop
|
|
34
|
+
end
|
|
35
|
+
|
|
36
|
+
# Scopes field selectors and restores the enclosing context after an exception.
|
|
37
|
+
# @param name [String] CSS selector prefix.
|
|
38
|
+
# @yield Defines fields in this selector context.
|
|
39
|
+
# @return [String] Defined scope name.
|
|
40
|
+
def context name
|
|
41
|
+
current_context << name.to_s
|
|
42
|
+
yield
|
|
43
|
+
|
|
44
|
+
name.to_s
|
|
45
|
+
ensure
|
|
46
|
+
current_context.pop
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Converts a nested schema name to its singular form.
|
|
50
|
+
# @param name [String, Symbol] Name from a DSL declaration.
|
|
51
|
+
# @return [String] Schema name used for lookup.
|
|
52
|
+
def scheme_name name
|
|
53
|
+
Schemic::Inflector.singularize(name.to_s)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def use_default_key name
|
|
57
|
+
current_scheme[:key] = name
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
# Public schema declarations describe fields rather than asking a boolean question.
|
|
61
|
+
# rubocop:disable Naming/PredicatePrefix
|
|
62
|
+
def has_field name_in, *args
|
|
63
|
+
has_param(name_in.to_s, :field, true, args)
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
def has_scheme name, *args
|
|
67
|
+
has_param(scheme_name(name), :scheme, true, args)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def has_schemes name, *args
|
|
71
|
+
has_param(scheme_name(name), :scheme, false, args)
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
def has_reference name, *args
|
|
75
|
+
has_param(name.to_s, :reference, true, args)
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def has_param name, param_name, single, *args
|
|
79
|
+
current_scheme[:has][name] = make_options(param_name, args, name, single)
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# rubocop:enable Naming/PredicatePrefix
|
|
83
|
+
|
|
84
|
+
# has_reference :lot, [
|
|
85
|
+
# { by: 'guid', from: 'ns2:lot', reset_context: 'ns2:protocolLotApplications' },
|
|
86
|
+
# { by: 'ns2:guid', from: 'ns2:protocolLotApplications', reset_context: 'ns2:lotApplicationsList' },
|
|
87
|
+
# ], required: true
|
|
88
|
+
#
|
|
89
|
+
# TODO move to protected
|
|
90
|
+
#
|
|
91
|
+
# The positional flag is retained for existing schema extensions.
|
|
92
|
+
# rubocop:disable Style/OptionalBooleanParameter
|
|
93
|
+
def make_options kind, args, name, single = true
|
|
94
|
+
selectors = make_selectors(filter_hashes(args, CONTEXT_KEYS), name, args)
|
|
95
|
+
local = transform_field_keys(args)
|
|
96
|
+
|
|
97
|
+
{ kind: kind, single: single, selectors: selectors }.to_os.merge(local)
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# rubocop:enable Style/OptionalBooleanParameter
|
|
101
|
+
|
|
102
|
+
# +transform_field_keys+ filters out and then transforms the passed in arguments to then merge them in to the scheme
|
|
103
|
+
#
|
|
104
|
+
def transform_field_keys hash_in
|
|
105
|
+
transformed_keys(hash_in, FIELD_KEYS, /if|on_complete/)
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Filters selector keys and resolves callbacks before merging them into the schema.
|
|
109
|
+
#
|
|
110
|
+
def transform_selector_keys hash_in
|
|
111
|
+
transformed_keys(hash_in, CONTEXT_KEYS | [:level], /on_proceed|on_found/)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# Combines the DSL context with each explicit selector context.
|
|
115
|
+
# Empty context parts are omitted to keep a single child separator.
|
|
116
|
+
# @param contexts [Array<Hash>] Selector option alternatives.
|
|
117
|
+
# @param name [String] Field or nested schema name.
|
|
118
|
+
# @param args [Array] Original field arguments.
|
|
119
|
+
# @return [OpenStruct] Ordered selector definitions.
|
|
120
|
+
def make_selectors contexts, name, _args
|
|
121
|
+
contexts = [{}] if contexts.empty?
|
|
122
|
+
|
|
123
|
+
contexts.reduce({}.to_os) do |selectors, options|
|
|
124
|
+
local_contexts = [options[:context] || ''].flatten
|
|
125
|
+
context = local_contexts.map! {|ctx| selector_context(ctx) }
|
|
126
|
+
|
|
127
|
+
current_scheme
|
|
128
|
+
|
|
129
|
+
selectors.merge(make_selector(name, options.merge(context: context)))
|
|
130
|
+
end
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
def current_context
|
|
134
|
+
@current_context ||= []
|
|
135
|
+
end
|
|
136
|
+
|
|
137
|
+
def current_scheme_path
|
|
138
|
+
@current_scheme_path ||= [to_s.downcase]
|
|
139
|
+
end
|
|
140
|
+
|
|
141
|
+
def schemes
|
|
142
|
+
@schemes ||= {}.to_os
|
|
143
|
+
end
|
|
144
|
+
|
|
145
|
+
def current_scheme
|
|
146
|
+
schemes[current_scheme_path.last] ||= { has: {}, root: schemes.to_h.keys.empty? }.to_os
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def generate
|
|
150
|
+
{ schemes: @schemes }.to_os
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
# Filters option declarations and resolves only named callbacks for matching keys.
|
|
154
|
+
# @param input [Array<Hash>, Hash] Raw declarations.
|
|
155
|
+
# @param keys [Array<Symbol>] Accepted keys.
|
|
156
|
+
# @param callbacks [Regexp] Keys whose values can name a builder method.
|
|
157
|
+
# @return [OpenStruct] Combined normalized options.
|
|
158
|
+
def transformed_keys input, keys, callbacks
|
|
159
|
+
filter_hashes(input, keys).reduce({}.to_os) do |result, attributes|
|
|
160
|
+
values =
|
|
161
|
+
attributes.to_h do |key, value|
|
|
162
|
+
[key, callbacks.match?(key) ? resolved_handler(value) : value]
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
result.merge(values.to_os)
|
|
166
|
+
end
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# Resolves a symbol on the builder; unavailable methods retain their name for runtime lookup.
|
|
170
|
+
# @param value [Object] Callback name or already callable object.
|
|
171
|
+
# @return [Object] Bound Method when available, otherwise original value.
|
|
172
|
+
def resolved_handler value
|
|
173
|
+
value.is_a?(Symbol) ? method(value) : value
|
|
174
|
+
rescue StandardError
|
|
175
|
+
value
|
|
176
|
+
end
|
|
177
|
+
end
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Ordered CSS selection and subtree navigation.
|
|
4
|
+
module Schemic::Parser::Selection
|
|
5
|
+
protected
|
|
6
|
+
|
|
7
|
+
def find_new_selector name, xml_context, options
|
|
8
|
+
inx, selector = select_value(name, xml_context, options.selectors, options)
|
|
9
|
+
|
|
10
|
+
inc = selector if inx&.text
|
|
11
|
+
|
|
12
|
+
[inx, inc]
|
|
13
|
+
end
|
|
14
|
+
|
|
15
|
+
# +select_value+ выборка общего обработчика контекста для заданного атрибута.
|
|
16
|
+
# Осуществляет выбор между обработчиками встроенным и заданным пользователем в
|
|
17
|
+
# подробностях (options).
|
|
18
|
+
#
|
|
19
|
+
def select_value name, dom_context_in, selectors, options
|
|
20
|
+
selectors.reduce([nil, nil]) do |(value, previous), path, selector|
|
|
21
|
+
next [value, previous] unless is_selector_needed?(value, selector, dom_context_in)
|
|
22
|
+
|
|
23
|
+
context = level_to_dom_context(selector.level, dom_context_in)
|
|
24
|
+
selected = search_in(path, context, name, options)
|
|
25
|
+
|
|
26
|
+
transformed = handled_value(selector.on_proceed, selected, name, context, options) if selector.on_proceed
|
|
27
|
+
|
|
28
|
+
[is_empty?(transformed) ? selected : transformed, selector]
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# Returns a DOM context at the requested level relative to the supplied subtree.
|
|
33
|
+
# Positive levels move to parents, zero keeps the subtree, and -1 selects the document root.
|
|
34
|
+
# when +level+ is a zero, it returns self context, when +level+ is a -1, it returns a root context.
|
|
35
|
+
# Examples:
|
|
36
|
+
# level_to_dom_context(-1, dom_context_in) # root DOM context
|
|
37
|
+
# level_to_dom_context(0, dom_context_in) # self DOM context
|
|
38
|
+
# level_to_dom_context(1, dom_context_in) # parent DOM context
|
|
39
|
+
#
|
|
40
|
+
def level_to_dom_context level, dom_context_in
|
|
41
|
+
case level
|
|
42
|
+
when -1
|
|
43
|
+
# dom_context_in.xpath('/*').first
|
|
44
|
+
dom_context_in.document
|
|
45
|
+
when 0
|
|
46
|
+
dom_context_in
|
|
47
|
+
else
|
|
48
|
+
(0...level.to_i).reduce(dom_context_in) do |res, _|
|
|
49
|
+
res.parent
|
|
50
|
+
rescue StandardError
|
|
51
|
+
res
|
|
52
|
+
end
|
|
53
|
+
end
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
def search_in path, xml_context, name, options
|
|
57
|
+
res =
|
|
58
|
+
if path.blank?
|
|
59
|
+
xml_context
|
|
60
|
+
else
|
|
61
|
+
xml_context.css(path.to_s)
|
|
62
|
+
end
|
|
63
|
+
|
|
64
|
+
options.single && res.first || res
|
|
65
|
+
rescue Nokogiri::CSS::SyntaxError => error
|
|
66
|
+
error(name, "Failed to navigate path with messages '#{error.message}'")
|
|
67
|
+
nil
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
# Allows another selector only for an empty value and an accepted optional condition.
|
|
71
|
+
# @param value [Object] Previous extraction result.
|
|
72
|
+
# @param selector [OpenStruct] Next selector options.
|
|
73
|
+
# @param context [Nokogiri::XML::Node] Original subtree.
|
|
74
|
+
# @return [Boolean] Whether this alternative must run.
|
|
75
|
+
def is_selector_needed? value, selector, context
|
|
76
|
+
is_empty?(extract_value(value)) && (selector.if.nil? || handler_for(selector.if)[value, context])
|
|
77
|
+
end
|
|
78
|
+
end
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Field values, nested records and required-field semantics.
|
|
4
|
+
module Schemic::Parser::Values
|
|
5
|
+
protected
|
|
6
|
+
|
|
7
|
+
def each_field_for schema, xml_context
|
|
8
|
+
schema.has.reduce({}) do |result, name, options|
|
|
9
|
+
key, value = type_value(name, options, xml_context)
|
|
10
|
+
value = conditional_value(value, options, xml_context)
|
|
11
|
+
|
|
12
|
+
value.nil? ? result : result.merge(key => value)
|
|
13
|
+
end
|
|
14
|
+
end
|
|
15
|
+
|
|
16
|
+
# Reads node text and trims strings while retaining zero, false and structured values.
|
|
17
|
+
# @param value [Object] Selected node or transformed value.
|
|
18
|
+
# @return [Object] Node text, trimmed string, or the original non-text value.
|
|
19
|
+
def extract_value value
|
|
20
|
+
text = value.respond_to?(:text) ? value.text : value
|
|
21
|
+
|
|
22
|
+
text.respond_to?(:strip) ? text.strip : text
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
def type_value name, options, xml_context
|
|
26
|
+
new_name, value = extracted_pair(name, options, xml_context)
|
|
27
|
+
|
|
28
|
+
if options.on_complete
|
|
29
|
+
value = extract_value(handled_value(options.on_complete, value, name, xml_context,
|
|
30
|
+
options))
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
error(name, 'field is required') if options.required && is_empty?(value)
|
|
34
|
+
|
|
35
|
+
[new_name, value]
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Extracts a nested schema when its selected nodes contain text.
|
|
39
|
+
# @param name [String, Symbol] Nested field name.
|
|
40
|
+
# @param options [OpenStruct] Schema selectors, multiplicity and key suffix.
|
|
41
|
+
# @param xml_context [Nokogiri::XML::Node] Current subtree.
|
|
42
|
+
# @return [Array] Output key and optional nested value.
|
|
43
|
+
def scheme_value name, options, xml_context
|
|
44
|
+
value, selector = select_value(name, xml_context, options.selectors, options)
|
|
45
|
+
|
|
46
|
+
new_name, new_value = nested_pair(name, options, value, selector) unless is_empty?(value&.text)
|
|
47
|
+
|
|
48
|
+
new_name = [new_name, options.postfix].compact.join('_')
|
|
49
|
+
|
|
50
|
+
[new_name, new_value]
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Checks emptiness recursively and treats whitespace-only strings as empty.
|
|
54
|
+
# @param value [Object] Extracted value or selected node text.
|
|
55
|
+
# @return [Boolean] Whether the value is empty. Boolean input is always retained.
|
|
56
|
+
# Examples:
|
|
57
|
+
# is_empty?("new_names"=>[{"field3"=>""}]) #=> true
|
|
58
|
+
# is_empty?(false) #=> false
|
|
59
|
+
# is_empty?(nil) #=> true
|
|
60
|
+
# is_empty?("") #=> true
|
|
61
|
+
#
|
|
62
|
+
def is_empty? value
|
|
63
|
+
case value
|
|
64
|
+
when Hash then value.values.all? {|item| is_empty?(item) }
|
|
65
|
+
when Array then value.all? {|item| is_empty?(item) }
|
|
66
|
+
when String then value.match?(/\A[[:space:]]*\z/)
|
|
67
|
+
when FalseClass, TrueClass then false
|
|
68
|
+
else value.blank?
|
|
69
|
+
end
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
def reference_value name, _options, _xml_context
|
|
73
|
+
error(name, 'no reference type is supported')
|
|
74
|
+
|
|
75
|
+
[]
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
# Applies the optional field condition; an absent callback retains the original value.
|
|
79
|
+
# @param value [Object] Extracted field value.
|
|
80
|
+
# @param options [OpenStruct] Field declaration.
|
|
81
|
+
# @param xml_context [Nokogiri::XML::Node] Current subtree.
|
|
82
|
+
# @return [Object, nil] Value when accepted, or nil when rejected.
|
|
83
|
+
def conditional_value value, options, xml_context
|
|
84
|
+
return value unless options.if
|
|
85
|
+
|
|
86
|
+
handler = handler_for(options.if)
|
|
87
|
+
args = [value, xml_context][0...handler.arity]
|
|
88
|
+
|
|
89
|
+
value if handler[*args]
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Dispatches extraction by declaration kind; unknown kinds yield an empty pair.
|
|
93
|
+
# @param name [String, Symbol] Output field name.
|
|
94
|
+
# @param options [OpenStruct] Field, scheme or reference options.
|
|
95
|
+
# @param xml_context [Nokogiri::XML::Node] Current subtree.
|
|
96
|
+
# @return [Array, nil] Output name/value pair, or nil for an unsupported kind.
|
|
97
|
+
def extracted_pair name, options, xml_context
|
|
98
|
+
case options.kind.to_s
|
|
99
|
+
when 'field'
|
|
100
|
+
value, = select_value(name, xml_context, options.selectors, options)
|
|
101
|
+
|
|
102
|
+
[name.to_s, extract_value(value)]
|
|
103
|
+
when 'scheme' then scheme_value(name, options, xml_context)
|
|
104
|
+
when 'reference' then reference_value(name, options, xml_context)
|
|
105
|
+
end
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# Extracts one nested record or all selected nodes according to the declaration.
|
|
109
|
+
# Empty nested values become nil so optional structures can be omitted.
|
|
110
|
+
# @param name [String] Nested declaration name.
|
|
111
|
+
# @param options [OpenStruct] Scheme options.
|
|
112
|
+
# @param value [Nokogiri::XML::Node, Nokogiri::XML::NodeSet] Selected subtree.
|
|
113
|
+
# @param selector [OpenStruct] Winning selector options.
|
|
114
|
+
# @return [Array] Output name and nested structure.
|
|
115
|
+
def nested_pair name, options, value, selector
|
|
116
|
+
schema = @scheme.schemes[Schemic::Inflector.singularize((selector.as || options.as || name).to_s)]
|
|
117
|
+
key = options.single ? name : Schemic::Inflector.pluralize(name.to_s)
|
|
118
|
+
result = options.single ? each_field_for(schema, value) : value.map {|node| each_field_for(schema, node) }
|
|
119
|
+
|
|
120
|
+
[key, is_empty?(result) ? nil : result]
|
|
121
|
+
end
|
|
122
|
+
end
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'nokogiri'
|
|
4
|
+
require 'rdoba/os'
|
|
5
|
+
|
|
6
|
+
require 'schemic/version'
|
|
7
|
+
require 'schemic/inflector'
|
|
8
|
+
|
|
9
|
+
# Extracts structured values from a document using a DSL or YAML schema.
|
|
10
|
+
class Schemic::Parser
|
|
11
|
+
autoload :Methods, 'schemic/parser/methods'
|
|
12
|
+
autoload :Values, 'schemic/parser/values'
|
|
13
|
+
autoload :Selection, 'schemic/parser/selection'
|
|
14
|
+
autoload :Callbacks, 'schemic/parser/callbacks'
|
|
15
|
+
|
|
16
|
+
include Values
|
|
17
|
+
include Selection
|
|
18
|
+
include Callbacks
|
|
19
|
+
|
|
20
|
+
DOCUMENT_TYPES = {
|
|
21
|
+
xml: Nokogiri::XML::Document,
|
|
22
|
+
html: Nokogiri::HTML::Document
|
|
23
|
+
}.freeze
|
|
24
|
+
|
|
25
|
+
attr_reader :errors
|
|
26
|
+
|
|
27
|
+
class ParameterError < StandardError; end
|
|
28
|
+
class InvalidSchemeError < StandardError; end
|
|
29
|
+
|
|
30
|
+
def initialize scheme
|
|
31
|
+
unless scheme.respond_to?(:schemes) && scheme.schemes.respond_to?(:select)
|
|
32
|
+
raise(InvalidSchemeError, 'Expected an extraction schema with schemes')
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
@scheme = scheme
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Extracts a tree with the configured schema; malformed XML produces document errors.
|
|
39
|
+
# HTML explicitly enables recovery for ordinary web pages.
|
|
40
|
+
# @param source [String, IO, Nokogiri::XML::Node] Input document.
|
|
41
|
+
# @param format [Symbol] :xml by default, or :html; other values raise ParameterError.
|
|
42
|
+
# @return [Hash] Extracted tree, or an empty tree for malformed XML.
|
|
43
|
+
def parse source, format: :xml
|
|
44
|
+
clean_errors
|
|
45
|
+
|
|
46
|
+
document = parsed_document(readflow(source), format)
|
|
47
|
+
|
|
48
|
+
return {} if errors.key?(:document)
|
|
49
|
+
|
|
50
|
+
each_field_for(root_scheme, document)
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
def root_scheme
|
|
54
|
+
@scheme.schemes.select {|_, value| value.root }.to_h.values.first
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# Normalizes in-memory text and reads open files from the beginning.
|
|
58
|
+
# Preserves binary strings so Nokogiri can detect the document encoding.
|
|
59
|
+
# @param xml [String, IO, Nokogiri::XML::Node] Source document.
|
|
60
|
+
# @return [String, Nokogiri::XML::Node] Document contents or an existing node.
|
|
61
|
+
def readflow xml
|
|
62
|
+
case xml
|
|
63
|
+
when String
|
|
64
|
+
xml.encoding == Encoding::BINARY ? xml : xml.gsub(/[\r\u{feff}]/, '')
|
|
65
|
+
when File, IO
|
|
66
|
+
xml.rewind
|
|
67
|
+
xml.readlines.join
|
|
68
|
+
else
|
|
69
|
+
xml
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
protected
|
|
74
|
+
|
|
75
|
+
# Parses only the requested document format without fetching external network entities.
|
|
76
|
+
# Existing Nokogiri nodes are retained. XML syntax errors are added to errors;
|
|
77
|
+
# HTML recovery diagnostics do not reject a page.
|
|
78
|
+
# @param source [String, IO, Nokogiri::XML::Node] Normalized document input.
|
|
79
|
+
# @param format [Symbol] Supported format key from DOCUMENT_TYPES.
|
|
80
|
+
# @return [Nokogiri::XML::Node] Parsed or supplied document node.
|
|
81
|
+
# @raise [ParameterError] The format is neither :xml nor :html.
|
|
82
|
+
def parsed_document source, format
|
|
83
|
+
document_type = DOCUMENT_TYPES.fetch(format) { raise(ParameterError, "Unsupported document format: #{format}") }
|
|
84
|
+
document = source.is_a?(Nokogiri::XML::Node) ? source : document_type.parse(source, &:nonet)
|
|
85
|
+
|
|
86
|
+
record_document_errors(document) if format == :xml
|
|
87
|
+
|
|
88
|
+
document
|
|
89
|
+
end
|
|
90
|
+
|
|
91
|
+
def clean_errors
|
|
92
|
+
@errors = {}
|
|
93
|
+
end
|
|
94
|
+
|
|
95
|
+
def show_errors errors
|
|
96
|
+
errors.messages.flat_map {|field, msgs| msgs.map {|msg| "#{field} #{msg}" }}.join(', ')
|
|
97
|
+
end
|
|
98
|
+
|
|
99
|
+
def error name, error
|
|
100
|
+
@errors ||= {}
|
|
101
|
+
@errors[name] ||= []
|
|
102
|
+
|
|
103
|
+
@errors[name] << error
|
|
104
|
+
|
|
105
|
+
nil
|
|
106
|
+
end
|
|
107
|
+
|
|
108
|
+
# log method TODO
|
|
109
|
+
def debug text
|
|
110
|
+
warn(text) if ENV['DEBUG']
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# Records fatal and ordinary XML syntax errors; warnings alone do not reject a document.
|
|
114
|
+
# @param document [Nokogiri::XML::Node] Parsed document or subtree.
|
|
115
|
+
# @return [Array] Original diagnostic list.
|
|
116
|
+
def record_document_errors document
|
|
117
|
+
document.document.errors.each do |entry|
|
|
118
|
+
error(:document, entry.message.strip) if entry.error? || entry.fatal?
|
|
119
|
+
end
|
|
120
|
+
end
|
|
121
|
+
end
|
data/lib/schemic.rb
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'schemic/version'
|
|
4
|
+
|
|
5
|
+
# Collects source documents and extracts structured data using application schemas.
|
|
6
|
+
module Schemic
|
|
7
|
+
autoload :Parser, 'schemic/parser'
|
|
8
|
+
autoload :Inflector, 'schemic/inflector'
|
|
9
|
+
autoload :Generator, 'schemic/generator'
|
|
10
|
+
autoload :Crawler, 'schemic/crawler'
|
|
11
|
+
autoload :Adapter, 'schemic/adapter'
|
|
12
|
+
end
|
data/schemic.gemspec
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
lib = File.expand_path('lib', __dir__)
|
|
4
|
+
$LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
|
|
5
|
+
require 'schemic/version'
|
|
6
|
+
|
|
7
|
+
Gem::Specification.new do |spec|
|
|
8
|
+
spec.required_ruby_version = '>= 3.1'
|
|
9
|
+
spec.name = 'schemic'
|
|
10
|
+
spec.version = Schemic::VERSION
|
|
11
|
+
spec.authors = ['Pavel «Malo» Skrylev']
|
|
12
|
+
spec.email = ['majioa@yandex.ru']
|
|
13
|
+
|
|
14
|
+
spec.summary = 'Schemic collects XML/HTML sources and extracts structured data with schemas'
|
|
15
|
+
spec.description = 'Schemic collects XML/HTML sources and extracts structured data with schemas,
|
|
16
|
+
prepared to import to a DB, or just serialize it and save it as is'
|
|
17
|
+
spec.homepage = 'https://github.com/majioa/schemic_parser'
|
|
18
|
+
spec.license = 'MIT'
|
|
19
|
+
|
|
20
|
+
# Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
|
|
21
|
+
# to allow pushing to a single host or delete this section to allow pushing to any host.
|
|
22
|
+
raise 'RubyGems 2.0 or newer is required to protect against public gem pushes.' unless spec.respond_to?(:metadata)
|
|
23
|
+
|
|
24
|
+
spec.metadata['allowed_push_host'] = 'https://rubygems.org'
|
|
25
|
+
spec.metadata['rubygems_mfa_required'] = 'false'
|
|
26
|
+
|
|
27
|
+
spec.files = `git ls-files -z`.split("\x0").reject {|f| f.match(%r{^(test|spec|features)/}) }
|
|
28
|
+
spec.bindir = 'exe'
|
|
29
|
+
spec.executables = spec.files.grep(%r{^exe/}) {|f| File.basename(f) }
|
|
30
|
+
spec.require_paths = ['lib']
|
|
31
|
+
|
|
32
|
+
spec.add_dependency('nokogiri', '~> 1.13', '>= 1.13.2')
|
|
33
|
+
spec.add_dependency('rdoba', '~> 0.9', '>= 0.9.4')
|
|
34
|
+
spec.add_development_dependency('bundler', '~> 2.4')
|
|
35
|
+
spec.add_development_dependency('cucumber', '~> 5.2')
|
|
36
|
+
spec.add_development_dependency('pry', '~> 0.13', '>= 0.13.1')
|
|
37
|
+
spec.add_development_dependency('rake', '>= 12.3.3')
|
|
38
|
+
spec.add_development_dependency('rspec-json_expectations', '~> 2.2')
|
|
39
|
+
spec.add_development_dependency('rubocop', '~> 1.81.7')
|
|
40
|
+
spec.add_development_dependency('rubocop-md', '~> 3.0.0')
|
|
41
|
+
spec.add_development_dependency('rubocop-performance', '~> 1.26.1')
|
|
42
|
+
spec.add_development_dependency('rubocop-rspec', '~> 3.9.0')
|
|
43
|
+
spec.add_development_dependency('shoulda-matchers-cucumber', '~> 1.0', '>= 1.0.1')
|
|
44
|
+
end
|