relaton 3.1.7 → 3.1.8

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: f9a1dcc62dca48c6e2c80ad43a9e404d13ac3692be82282545271322681ca3d7
4
- data.tar.gz: 3997131f34e955e52439d88b8c943a63984ca3df5f77a5a379eff5a8b7cf7afb
3
+ metadata.gz: 484ac816f24c076b74df5381aa7ead832120a1bbb37f2373424da2324d119d26
4
+ data.tar.gz: d51bacaae6cdc3d9a0dcffeb8c89ecd723f025f56d6a8c9b79a35d4f89a22939
5
5
  SHA512:
6
- metadata.gz: 99c5dbe4bfa6197a209df83a9fc07bf9516f9915aa98158adf64da1168b65d2f8811f7e9e87db9cccf17880aa0e8910c94e49cb1d53d532143d8324b1620936a
7
- data.tar.gz: 6fc0ef51ff656c6776efa46f33306789569bfa72743caebf594b3ff2ec441fc0b3838521d6edd6bb37c40b83c7ff28158a49fa4a6cad18e6add449a4bec4b831
6
+ metadata.gz: d9c865518f46c07fbfcf997f2377dae9f026d90716f446a9956a76504eaa20891ddff8e4e934bc78d4adff873b0ecbebb34d3a0b0995c20f7d1533769de2e569
7
+ data.tar.gz: 77a173df28a3541713387b2e0a58365ad9f95d4063475c398a7a8484beca8152ff59e7d19f78836fc6a9b536bd2309dc0d9440875ab433b52c62ec29aa77acc3
@@ -13,7 +13,7 @@ module Relaton
13
13
  relaton/oasis relaton/doi relaton/jis relaton/xsf
14
14
  relaton/ccsds relaton/etsi relaton/isbn relaton/plateau
15
15
  relaton/oiml relaton/jcgm relaton/easc relaton/gost relaton/adobe
16
- relaton/iala relaton/evs relaton/sae relaton/arxiv
16
+ relaton/iala relaton/evs relaton/sae relaton/eu relaton/arxiv
17
17
  ].freeze
18
18
 
19
19
  include Singleton
@@ -0,0 +1,103 @@
1
+ require "net/http"
2
+
3
+ module Relaton
4
+ module Eu
5
+ module Bibliography
6
+ # Transport failures of the document fetch. They become
7
+ # `Relaton::RequestError`, the one class `Relaton::Db#net_retry` retries.
8
+ NET_ERRORS = [
9
+ SocketError, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED,
10
+ Errno::ETIMEDOUT, EOFError, Net::HTTPBadResponse,
11
+ Net::HTTPHeaderSyntaxError, Net::ProtocolError, Net::OpenTimeout,
12
+ Net::ReadTimeout, OpenSSL::SSL::SSLError
13
+ ].freeze
14
+
15
+ class << self
16
+ #
17
+ # Fetch an EU legal act.
18
+ #
19
+ # @param ref [String, Pubid::Eu::Identifier] `EU Regulation 1227/2011`
20
+ # @param year [String, nil] the act's year; a reference always states
21
+ # it, so a year that differs finds nothing
22
+ # @param _opts [Hash]
23
+ # @return [Relaton::Bib::ItemData, nil]
24
+ #
25
+ def get(ref, year = nil, _opts = {})
26
+ Util.info "Fetching from Relaton repository ...", key: ref.to_s
27
+ pubid = parse_ref ref
28
+ return not_found(ref) unless pubid && (year.nil? || year.to_s == pubid.year.to_s)
29
+
30
+ row = select_row index.search(pubid), pubid
31
+ item = row && fetch_doc(row[:file])
32
+ return not_found(ref) unless item
33
+
34
+ Util.info "Found: `#{item.docidentifier.first.content}`", key: ref.to_s
35
+ item
36
+ end
37
+
38
+ private
39
+
40
+ #
41
+ # Before 2015 a decision had two number series, so two acts can share
42
+ # a number and a year: Council Decision No 252/2013/EU and Commission
43
+ # Implementing Decision 2013/252/EU. `===` ignores the print order,
44
+ # so both rows match; the row printed in the query's order wins.
45
+ # `number_first?` is the order pubid prints: the stored flag is nil
46
+ # for the default order, and a caller can set the default explicitly.
47
+ # With no such row (a query in the other order), the first file.
48
+ #
49
+ def select_row(rows, pubid)
50
+ rows.find { |r| r[:id].number_first? == pubid.number_first? } ||
51
+ rows.min_by { |r| r[:file] }
52
+ end
53
+
54
+ def not_found(ref)
55
+ Util.info "Not found.", key: ref.to_s
56
+ nil
57
+ end
58
+
59
+ #
60
+ # The query as a `Pubid::Eu::Identifier`. A parsed pubid comes from
61
+ # `Relaton::Db` (relaton#205). A reference pubid cannot read answers
62
+ # nil, so `get` answers not-found with a log line (relaton#235).
63
+ #
64
+ # @return [Pubid::Eu::Identifier, nil]
65
+ #
66
+ def parse_ref(ref)
67
+ return ref if ref.is_a?(::Pubid::Eu::Identifier)
68
+
69
+ ::Pubid::Eu::Identifier.parse ref.to_s.strip
70
+ rescue ::Pubid::Errors::Error, ArgumentError => e
71
+ Util.info "Not an EU act identifier pubid reads: #{e.message}", key: ref.to_s
72
+ nil
73
+ end
74
+
75
+ # @param file [String] the row's path in the data repo
76
+ # @return [Relaton::Bib::ItemData, nil] nil when the file is missing
77
+ def fetch_doc(file)
78
+ uri = URI("#{ENDPOINT}#{file}")
79
+ resp = Net::HTTP.get_response uri
80
+ return if resp.code == "404"
81
+ unless resp.code == "200"
82
+ raise Relaton::RequestError, "Could not access #{uri}: HTTP #{resp.code}"
83
+ end
84
+
85
+ Bib::Item.from_yaml(resp.body).tap { |i| i.fetched = Date.today.to_s }
86
+ rescue *NET_ERRORS => e
87
+ raise Relaton::RequestError, "Could not access #{uri}: #{e.message}"
88
+ end
89
+
90
+ #
91
+ # `Index::Type#search` with a pubid narrows to the `number` bucket and
92
+ # selects with pubid's subset match `query === row`: the type and the
93
+ # year must agree, and the legal family is a wildcard.
94
+ #
95
+ def index
96
+ Relaton::Index.find_or_create(
97
+ :eu, pages_url: PAGES_URL, pubid_class: ::Pubid::Eu::Identifier
98
+ )
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,259 @@
1
+ require "net/http"
2
+ require_relative "../core"
3
+ require_relative "../json"
4
+
5
+ module Relaton
6
+ module Eu
7
+ #
8
+ # The EU Publications Office CELLAR SPARQL endpoint, for the crawler.
9
+ #
10
+ # A page holds sector-3 regulations, directives and decisions (CELEX
11
+ # types R, L and D) of one scope, one row a work, ordered by CELEX: one
12
+ # year (`#each_row`), or the works CELLAR changed since a time
13
+ # (`#each_modified_row`, by `cmr:lastModificationDate`). A field with
14
+ # many values (entry-into-force dates, authors, repealed and amended
15
+ # acts) is one `GROUP_CONCAT` string.
16
+ #
17
+ # A property name with a hyphen is written as a full IRI. The endpoint
18
+ # (Virtuoso) misreads `cdm:resource_legal_date_entry-into-force` as a
19
+ # prefixed name: it answers, but with values from no such property.
20
+ #
21
+ class Cellar
22
+ URL = "https://publications.europa.eu/webapi/rdf/sparql".freeze
23
+ # Rows a request. A year has at most about 5,200 works (1988), and a
24
+ # page of 1,000 answers in 4 s to more than 100 s (docs/eu.md).
25
+ ROWS = 1000
26
+ # One request at a time, one a second: the endpoint is public.
27
+ GAP = 1
28
+ ATTEMPTS = 5
29
+ # The wait before retry n (0-based) doubles from this: 15, 30, 60,
30
+ # 120 s. CELLAR can answer 502/504 for a minute or more.
31
+ FIRST_WAIT = 15
32
+ RETRY_CODES = %w[429 500 502 503 504].freeze
33
+ NET_ERRORS = [
34
+ SocketError, Errno::EINVAL, Errno::ECONNRESET, Errno::ECONNREFUSED,
35
+ Errno::ETIMEDOUT, EOFError, Net::HTTPBadResponse,
36
+ Net::HTTPHeaderSyntaxError, Net::ProtocolError, Net::OpenTimeout,
37
+ Net::ReadTimeout, OpenSSL::SSL::SSLError
38
+ ].freeze
39
+
40
+ # The scope of a query: a triple pattern on `?w` that ends with ` ;`,
41
+ # and a FILTER (or nothing).
42
+ Scope = Struct.new(:pattern, :filter, :what, :works)
43
+
44
+ # Joins the `<language>|<title>` pairs of `?titles` (one per language
45
+ # expression, the language as CELLAR's authority code: `ENG`, `BUL`, …).
46
+ # It must be ASCII: Virtuoso turns a non-ASCII character of the query
47
+ # text into `?` (the titles it returns are UTF-8 as stored).
48
+ TITLE_SEP = "~|~".freeze
49
+
50
+ # `%<scope>s`, `%<filter>s`, `%<limit>d` and `%<offset>d` are filled per
51
+ # page.
52
+ QUERY = <<~SPARQL.freeze
53
+ PREFIX cdm: <http://publications.europa.eu/ontology/cdm#>
54
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
55
+ PREFIX skos: <http://www.w3.org/2004/02/skos/core#>
56
+ SELECT ?celex
57
+ (SAMPLE(?eli_) AS ?eli)
58
+ (SAMPLE(?date_) AS ?date)
59
+ (GROUP_CONCAT(DISTINCT STR(?force_); separator=" ") AS ?force)
60
+ (SAMPLE(?inforce_) AS ?inforce)
61
+ (GROUP_CONCAT(DISTINCT CONCAT(STRAFTER(STR(?tlang_), "language/"), "|", STR(?title_)); separator="#{TITLE_SEP}") AS ?titles)
62
+ (GROUP_CONCAT(DISTINCT CONCAT(STR(?author_), "|", COALESCE(STR(?alabel), "")); separator="\\n") AS ?authors)
63
+ (GROUP_CONCAT(DISTINCT ?repeals_; separator=" ") AS ?repeals)
64
+ (GROUP_CONCAT(DISTINCT ?amends_; separator=" ") AS ?amends)
65
+ WHERE {
66
+ ?w cdm:resource_legal_id_sector "3"^^xsd:string ;
67
+ %<scope>s
68
+ cdm:resource_legal_type ?t ;
69
+ cdm:resource_legal_id_celex ?celex .
70
+ FILTER(?t IN ("R"^^xsd:string, "L"^^xsd:string, "D"^^xsd:string))
71
+ %<filter>s
72
+ OPTIONAL { ?w cdm:resource_legal_eli ?eli_ }
73
+ OPTIONAL { ?w cdm:work_date_document ?date_ }
74
+ OPTIONAL { ?w <http://publications.europa.eu/ontology/cdm#resource_legal_date_entry-into-force> ?force_ }
75
+ OPTIONAL { ?w <http://publications.europa.eu/ontology/cdm#resource_legal_in-force> ?inforce_ }
76
+ OPTIONAL { ?w cdm:work_created_by_agent ?author_ .
77
+ OPTIONAL { ?author_ skos:prefLabel ?alabel FILTER(LANG(?alabel) = "en") } }
78
+ OPTIONAL { ?w cdm:resource_legal_repeals_resource_legal/cdm:resource_legal_id_celex ?repeals_ }
79
+ OPTIONAL { ?w cdm:resource_legal_amends_resource_legal/cdm:resource_legal_id_celex ?amends_ }
80
+ OPTIONAL { ?e cdm:expression_belongs_to_work ?w ;
81
+ cdm:expression_uses_language ?tlang_ ;
82
+ cdm:expression_title ?title_ }
83
+ }
84
+ GROUP BY ?celex
85
+ ORDER BY ?celex
86
+ LIMIT %<limit>d OFFSET %<offset>d
87
+ SPARQL
88
+
89
+ # The works of one scope, for #each_scoped to check that it read them
90
+ # all.
91
+ COUNT_QUERY = <<~SPARQL.freeze
92
+ PREFIX cdm: <http://publications.europa.eu/ontology/cdm#>
93
+ PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
94
+ SELECT (COUNT(DISTINCT ?celex) AS ?n) WHERE {
95
+ ?w cdm:resource_legal_id_sector "3"^^xsd:string ;
96
+ %<scope>s
97
+ cdm:resource_legal_type ?t ;
98
+ cdm:resource_legal_id_celex ?celex .
99
+ FILTER(?t IN ("R"^^xsd:string, "L"^^xsd:string, "D"^^xsd:string))
100
+ %<filter>s
101
+ }
102
+ SPARQL
103
+
104
+ # The CELLAR time a work last changed. The name is written as a full
105
+ # IRI, as every name outside the `cdm:` prefix is here.
106
+ MODIFIED = "<http://publications.europa.eu/ontology/cdm/cmr#lastModificationDate>".freeze
107
+
108
+ #
109
+ # Each row of one year, page by page (see #each_scoped).
110
+ #
111
+ # @param year [Integer]
112
+ # @yieldparam binding [Hash{String=>Hash}] one SPARQL result row
113
+ #
114
+ def each_row(year, &block)
115
+ each_scoped year_scope(year), &block
116
+ end
117
+
118
+ #
119
+ # Each row of a work CELLAR changed at or after a time, page by page
120
+ # (see #each_scoped).
121
+ #
122
+ # @param since [Time]
123
+ # @yieldparam binding [Hash{String=>Hash}] one SPARQL result row
124
+ #
125
+ def each_modified_row(since, &block)
126
+ each_scoped modified_scope(since), &block
127
+ end
128
+
129
+ #
130
+ # Each row of one scope, page by page.
131
+ #
132
+ # A page shorter than ROWS ends the scope. Virtuoso can answer a page
133
+ # short with HTTP 200 (a query timeout, a server row cap), so the scope
134
+ # is checked against a COUNT of its works first: a scope that read
135
+ # fewer rows raises `Relaton::RequestError` instead of publishing an
136
+ # index without them.
137
+ #
138
+ # @param scope [Scope]
139
+ # @yieldparam binding [Hash{String=>Hash}] one SPARQL result row
140
+ #
141
+ def each_scoped(scope, &block)
142
+ expected = count(scope)
143
+ read = 0
144
+ offset = 0
145
+ loop do
146
+ rows = page(scope, offset)
147
+ rows.each(&block)
148
+ read += rows.size
149
+ break if rows.size < ROWS
150
+
151
+ offset += ROWS
152
+ end
153
+ return if read == expected
154
+
155
+ raise Relaton::RequestError,
156
+ "CELLAR gave #{read} of #{expected} works #{scope.works}"
157
+ end
158
+
159
+ # @param scope [Scope]
160
+ # @return [Integer] the works of one scope
161
+ def count(scope)
162
+ rows = request fill(COUNT_QUERY, scope), "#{scope.what} count"
163
+ rows.dig(0, "n", "value").to_i
164
+ end
165
+
166
+ # @param scope [Scope]
167
+ # @return [Array<Hash>] the result bindings of one page
168
+ def page(scope, offset)
169
+ query = fill(QUERY, scope, limit: ROWS, offset: offset)
170
+ request query, "#{scope.what} offset #{offset}"
171
+ end
172
+
173
+ # @return [Scope] the works of one year
174
+ def year_scope(year)
175
+ Scope.new(%(cdm:resource_legal_year "#{Integer(year)}"^^xsd:gYear ;), "",
176
+ "year #{year}", "for year #{year}")
177
+ end
178
+
179
+ # @param since [Time]
180
+ # @return [Scope] the works changed at or after `since`
181
+ def modified_scope(since)
182
+ stamp = since.utc.strftime("%Y-%m-%dT%H:%M:%SZ")
183
+ Scope.new("#{MODIFIED} ?modified ;",
184
+ %(FILTER(?modified >= "#{stamp}"^^xsd:dateTime)),
185
+ "changes since #{stamp}", "changed since #{stamp}")
186
+ end
187
+
188
+ #
189
+ # One request. A throttle, a server error or a transport error is
190
+ # retried with a growing wait; any other answer, an answer Virtuoso
191
+ # marks incomplete, or a request that keeps failing, raises
192
+ # `Relaton::RequestError`: a partial crawl would publish a partial
193
+ # index.
194
+ #
195
+ # @return [Array<Hash>] the result bindings
196
+ #
197
+ def request(query, what) # rubocop:disable Metrics/MethodLength
198
+ uri = query_uri(query)
199
+ ATTEMPTS.times do |n|
200
+ pacer.wait
201
+ resp, failure = attempt uri
202
+ return bindings(resp, what) if resp&.code == "200"
203
+ if resp && !RETRY_CODES.include?(resp.code)
204
+ raise Relaton::RequestError, "CELLAR HTTP #{resp.code} for #{what}"
205
+ end
206
+
207
+ break if n == ATTEMPTS - 1
208
+
209
+ Util.warn "CELLAR #{failure || "HTTP #{resp.code}"}, " \
210
+ "retry #{n + 1} of #{ATTEMPTS - 1}"
211
+ sleep FIRST_WAIT * (2**n)
212
+ end
213
+ raise Relaton::RequestError,
214
+ "CELLAR keeps failing for #{what} after #{ATTEMPTS} attempts"
215
+ end
216
+
217
+ private
218
+
219
+ def fill(query, scope, **page)
220
+ format(query, scope: scope.pattern, filter: scope.filter, **page)
221
+ end
222
+
223
+ # Virtuoso sends `X-SQL-State` with a 200 when it cut the answer
224
+ # short (an anytime query that hit its timeout).
225
+ def bindings(resp, what)
226
+ if resp["x-sql-state"]
227
+ raise Relaton::RequestError,
228
+ "CELLAR answer incomplete for #{what}: " \
229
+ "#{resp['x-sql-state']} #{resp['x-sql-message']}".strip
230
+ end
231
+
232
+ Relaton::Json.parse_external(resp.body).dig("results", "bindings") || []
233
+ end
234
+
235
+ def attempt(uri)
236
+ [http_get(uri), nil]
237
+ rescue *NET_ERRORS => e
238
+ [nil, "#{e.class}: #{e.message}"]
239
+ end
240
+
241
+ def query_uri(query)
242
+ uri = URI URL
243
+ uri.query = URI.encode_www_form(query: query)
244
+ uri
245
+ end
246
+
247
+ def http_get(uri)
248
+ Net::HTTP.start(uri.host, uri.port, use_ssl: true,
249
+ open_timeout: 30, read_timeout: 180) do |http|
250
+ http.get uri.request_uri, "Accept" => "application/sparql-results+json"
251
+ end
252
+ end
253
+
254
+ def pacer
255
+ @pacer ||= Core::Pacer.new(gap: GAP)
256
+ end
257
+ end
258
+ end
259
+ end
@@ -0,0 +1,138 @@
1
+ require "time"
2
+ require_relative "../core"
3
+ require_relative "../eu"
4
+
5
+ module Relaton
6
+ module Eu
7
+ #
8
+ # Crawl every EU regulation, directive and decision from CELLAR into a
9
+ # data repo: one document a act and the pubid `index-v2`.
10
+ #
11
+ # Two sources:
12
+ #
13
+ # - `eu-cellar`, the full crawl: CELLAR is read one year at a time
14
+ # (`Cellar#each_row`), from the first year of the Official Journal to
15
+ # this year, into an empty index. Run it with `prune: true`, so an act
16
+ # CELLAR dropped loses its file.
17
+ # - `eu-cellar-updates`: only the works CELLAR changed since the last
18
+ # run (`Cellar#each_modified_row`), written over the existing data and
19
+ # added to the existing index. It cannot see a work CELLAR deleted, nor
20
+ # a change that does not touch the work (an author's new label), so the
21
+ # full crawl still runs from time to time. It refuses `prune: true`.
22
+ #
23
+ # Both write the start time of the run to SINCE_FILE; the next update
24
+ # run reads from one day before it. A page that keeps failing raises
25
+ # before the index and SINCE_FILE are written, so a failed run
26
+ # publishes nothing and the next one reads the same changes again.
27
+ #
28
+ class DataFetcher < Core::DataFetcher
29
+ FULL = "eu-cellar".freeze
30
+ UPDATES = "eu-cellar-updates".freeze
31
+ SOURCES = [FULL, UPDATES].freeze
32
+ # The first year of the Official Journal (of the ECSC).
33
+ FIRST_YEAR = 1952
34
+ # The start time of the last run that finished, in UTC (ISO 8601).
35
+ SINCE_FILE = "cellar-since.txt".freeze
36
+ # An update run reads from this long before the last run started:
37
+ # CELLAR's clock and the crawler's need not agree, and a work can be
38
+ # changed while a run reads its year.
39
+ OVERLAP = 24 * 60 * 60
40
+
41
+ def fetch(source = nil)
42
+ unless SOURCES.include? source
43
+ raise ArgumentError,
44
+ "Unknown source `#{source}`, expected one of #{SOURCES}"
45
+ end
46
+
47
+ started = Time.now.utc
48
+ @keys = {}
49
+ source == FULL ? fetch_all : fetch_updates
50
+ index.save
51
+ File.write SINCE_FILE, "#{started.strftime('%Y-%m-%dT%H:%M:%SZ')}\n"
52
+ report_errors
53
+ end
54
+
55
+ def index
56
+ # `pubid_class:` on the producer too: FileIO#save calls `to_hash` only
57
+ # for instances of it.
58
+ @index ||= Relaton::Index.find_or_create(
59
+ :eu, file: "#{INDEXFILE}.yaml", pubid_class: ::Pubid::Eu::Identifier
60
+ )
61
+ end
62
+
63
+ def log_error(msg)
64
+ Util.error msg
65
+ end
66
+
67
+ private
68
+
69
+ def cellar
70
+ @cellar ||= Cellar.new
71
+ end
72
+
73
+ def fetch_all
74
+ # Every full run writes the whole corpus, so the index starts empty:
75
+ # a row an earlier run wrote for an act that is now skipped would
76
+ # outlive its pruned file.
77
+ index.remove_all
78
+ (FIRST_YEAR..Date.today.year).each do |year|
79
+ cellar.each_row(year) { |row| parse_row row }
80
+ end
81
+ end
82
+
83
+ def fetch_updates
84
+ if prune
85
+ raise ArgumentError, "#{UPDATES} writes only the changed acts; " \
86
+ "prune would delete every other act. Prune " \
87
+ "with #{FULL}."
88
+ end
89
+
90
+ cellar.each_modified_row(last_run - OVERLAP) { |row| parse_row row }
91
+ end
92
+
93
+ # @return [Time] the start time of the last run, from SINCE_FILE
94
+ def last_run
95
+ unless File.exist? SINCE_FILE
96
+ raise ArgumentError, "#{UPDATES} needs #{SINCE_FILE}, which a " \
97
+ "finished #{FULL} run writes; run #{FULL} first"
98
+ end
99
+
100
+ Time.iso8601 File.read(SINCE_FILE, encoding: "UTF-8").strip
101
+ end
102
+
103
+ #
104
+ # Write one work and index it. A work the flavor does not cover (a
105
+ # corrigendum, a work with no ELI of a regulation, directive or
106
+ # decision) gives no item and is skipped. An ELI of a covered act that
107
+ # pubid cannot read is recorded in `@errors`, which `report_errors`
108
+ # sends to the crawl's GitHub issue.
109
+ #
110
+ # Two works of one act keep the first; the second is logged. The act is
111
+ # its ELI, not its printed id: the print order (`number_first`) is not
112
+ # part of the act's identity.
113
+ #
114
+ def parse_row(row)
115
+ parser = Parser.new(row)
116
+ item = parser.parse
117
+ @errors["ELI #{row.dig('eli', 'value')}"] = parser.error if parser.error
118
+ return unless item
119
+
120
+ name = parser.pubid.to_s
121
+ act = parser.pubid.to_eli
122
+ celex = row.dig("celex", "value")
123
+ if @keys[act]
124
+ return Util.warn "Skipped CELEX #{celex}: CELEX #{@keys[act]} " \
125
+ "is the same act", key: name
126
+ end
127
+
128
+ @keys[act] = celex
129
+ file = write_unique name, serialize(item)
130
+ index.add_or_update parser.pubid, file
131
+ end
132
+
133
+ def to_yaml(bib) = bib.to_yaml
134
+ def to_xml(bib) = bib.to_xml(bibdata: true)
135
+ def to_bibxml(bib) = bib.to_rfcxml
136
+ end
137
+ end
138
+ end
@@ -0,0 +1,292 @@
1
+ module Relaton
2
+ module Eu
3
+ #
4
+ # Map one CELLAR result row (`Cellar::QUERY`) to a generic Bib::ItemData.
5
+ #
6
+ # The act identifier comes from the ELI, never from the CELEX number:
7
+ # CELEX numbers are CELLAR's own sequence, and they differ from the act
8
+ # number for many decisions (ECB decision 2016/245 is CELEX 32016D0002).
9
+ #
10
+ class Parser
11
+ # A work of an act this flavor covers, in its original version. The
12
+ # ELI type segment can carry a subtype (`reg_impl`, `dec_del`, …):
13
+ # implementing and delegated acts are numbered with their act type,
14
+ # and `Pubid::Eu` reads the subtype (pubid >= 2.0.46), so the ELI goes
15
+ # to pubid unchanged; a subtype pubid does not know is a crawl error.
16
+ # A corrigendum (`…/corrigendum/<date>/oj`), and every other ELI type
17
+ # (`C`, `convention`, …), does not match.
18
+ ELI = %r{\Ahttp://data\.europa\.eu/eli/(?:reg|dir|dec)(?:_[a-z]+)?/\d{4}/\d+/oj\z}
19
+
20
+ # The act citation in an Official Journal title, in English or (for an
21
+ # act with no English version) French: `Regulation (EU) No 1227/2011`,
22
+ # `Directive 93/42/EEC`, `Decision (EU) 2016/245`,
23
+ # `Règlement (CEE) n 2015/68`. Only the pair of numbers is read.
24
+ CITATION = %r{\b(Regulation|Directive|Decision|Règlement|Décision)\b[^\d]{0,40}?(\d+)/(\d+)}
25
+
26
+ # The French act words of CITATION, by pubid's class name.
27
+ ACT_WORDS = { "Règlement" => "Regulation", "Décision" => "Decision" }.freeze
28
+
29
+ # CELLAR's language authority code (`…/language/ENG`) → the title's
30
+ # language (ISO 639-1) and script (ISO 15924). A code not here (a
31
+ # language of no EU act) gives no title.
32
+ LANGUAGES = {
33
+ "BUL" => %w[bg Cyrl], "CES" => %w[cs Latn], "DAN" => %w[da Latn],
34
+ "DEU" => %w[de Latn], "ELL" => %w[el Grek], "ENG" => %w[en Latn],
35
+ "EST" => %w[et Latn], "FIN" => %w[fi Latn], "FRA" => %w[fr Latn],
36
+ "GLE" => %w[ga Latn], "HRV" => %w[hr Latn], "HUN" => %w[hu Latn],
37
+ "ITA" => %w[it Latn], "LAV" => %w[lv Latn], "LIT" => %w[lt Latn],
38
+ "MLT" => %w[mt Latn], "NLD" => %w[nl Latn], "POL" => %w[pl Latn],
39
+ "POR" => %w[pt Latn], "RON" => %w[ro Latn], "SLK" => %w[sk Latn],
40
+ "SLV" => %w[sl Latn], "SPA" => %w[es Latn], "SWE" => %w[sv Latn]
41
+ }.freeze
42
+
43
+ # Titles go English, French, German first (EUR-Lex shows the French
44
+ # title of an act with no English version), then by CELLAR code.
45
+ FIRST_LANGUAGES = %w[ENG FRA DEU].freeze
46
+
47
+ # The EEA relevance note in each language (regex source), in the form
48
+ # the Official Journal prints now and in the older forms a sample of
49
+ # ten years (1994-2024) showed five times or more. Rarer typing
50
+ # errors, and the longer note that also names the EU-Switzerland
51
+ # agreement, stay in the title. An apostrophe may be typographic.
52
+ EEA_TEXTS = [
53
+ "Text with EEA relevance", "[ТтT]екст от значение за ЕИП",
54
+ "Text ?s významem pro EHP", "EØS- ?relevant tekst",
55
+ "Tekst af betydning for EØS", "Text (?:von|mit) Bedeutung für den EWR",
56
+ "Κείμενο που παρουσιάζει ενδιαφέρον για τον ΕΟΧ",
57
+ "EMPs kohaldatav tekst", "ETA: ?n kannalta merkityksellinen(?: teksti)?",
58
+ "Texte présentant de l['’] ?intérêt pour l['’] ?EEE",
59
+ "Téacs atá ábhartha maidir le(?:is an)? LEE", "Tekst značajan za EGP",
60
+ "EGT[- ]vonatkozású szöveg", "Testo rilevante ai fini del(?:lo)? SEE",
61
+ "Dokuments attiecas uz EEZ", "Tekstas svarbus EEE",
62
+ "Test b['’] ?r[ei]levanza għ(?:aż|all)-ŻEE", "Voor de EER relevante tekst",
63
+ "Tekst mający znaczenie dla EOG", "Texto relevante para efeitos do EEE",
64
+ "Text cu relevan[țţ][ăa] (?:pentru )?SEE",
65
+ "Text s (?:významom|platnosťou) pre EHP",
66
+ "Besedilo (?:velja za|se nanaša na) EGP",
67
+ "Texto pertinente a (?:efectos|los fines) del EEE",
68
+ "Text av betydelse för EES"
69
+ ].freeze
70
+
71
+ # The note that closes many titles; it is not part of the title.
72
+ # It is matched after `#initialize` collapses each whitespace run in
73
+ # the title to one space, so ` ?` stands for any run (no `\s*`:
74
+ # CodeQL rb/polynomial-redos). The full stop can be inside or after
75
+ # the brackets.
76
+ EEA_NOTE = / ?\(? ?(?:#{EEA_TEXTS.join('|')}) ?\.? ?\)? ?\.?\z/i
77
+
78
+ # A placeholder CELLAR uses for an unknown entry-into-force date.
79
+ PLACEHOLDER_DATE = /\A1001-/
80
+
81
+ PUBLISHER = %w[OP Publications\ Office\ of\ the\ European\ Union].freeze
82
+
83
+ EURLEX = "https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=CELEX:".freeze
84
+
85
+ #
86
+ # @param binding [Hash{String=>Hash}] one SPARQL result row
87
+ # @return [Bib::ItemData, nil] nil for a work the flavor does not cover
88
+ #
89
+ def self.parse(binding)
90
+ new(binding).parse
91
+ end
92
+
93
+ def initialize(binding)
94
+ @row = binding.transform_values { |v| v["value"].to_s.strip }
95
+ .reject { |_, v| v.empty? }
96
+ # The Official Journal writes a no-break space after `No`
97
+ # (`No 1227/2011`); a title keeps plain spaces.
98
+ @titles = read_titles @row["titles"].to_s
99
+ end
100
+
101
+ # @return [Bib::ItemData, nil]
102
+ def parse
103
+ return unless pubid
104
+
105
+ Bib::ItemData.new(
106
+ id: pubid.to_s.gsub(/\W/, ""), type: "standard", title: title,
107
+ docidentifier: docidentifier, date: date, contributor: contributor,
108
+ status: status, relation: relation, source: source,
109
+ language: title.map(&:language), script: title.map(&:script).uniq,
110
+ ext: ext
111
+ )
112
+ end
113
+
114
+ #
115
+ # The act identifier, from the ELI, in the order the act's own title
116
+ # prints it.
117
+ #
118
+ # @return [Pubid::Eu::Identifier, nil] nil when the work has no ELI of
119
+ # an act this flavor covers, or pubid cannot read it
120
+ #
121
+ def pubid
122
+ return @pubid if defined? @pubid
123
+
124
+ @pubid = parse_eli
125
+ end
126
+
127
+ # @return [String, nil] why a work of a covered act was not read: an
128
+ # ELI that matches `ELI` but pubid cannot read. Nil for a work the
129
+ # flavor does not cover, which is skipped and not an error.
130
+ def error
131
+ pubid
132
+ @error
133
+ end
134
+
135
+ private
136
+
137
+ def parse_eli
138
+ return unless ELI.match? @row["eli"]
139
+
140
+ keep_title_order ::Pubid::Eu.parse(@row["eli"])
141
+ rescue ::Pubid::Errors::Error, ArgumentError => e
142
+ @error = "CELEX #{@row['celex']}: pubid cannot read ELI " \
143
+ "`#{@row['eli']}` (#{e.message})"
144
+ nil
145
+ end
146
+
147
+ #
148
+ # Before 2015 a decision or a directive can print `<number>/<year>`
149
+ # (`Decision No 1082/2013/EU`) or `<year>/<number>`
150
+ # (`Decision 2010/87/EU`), and only its title tells. A pair that does
151
+ # not name this act (the title cites another act first), or that reads
152
+ # the same both ways (`2003/2003`), changes nothing.
153
+ #
154
+ def keep_title_order(id)
155
+ number_first = title_order(id)
156
+ unless number_first.nil? || number_first == id.default_number_first?
157
+ id.number_first = number_first
158
+ end
159
+ id
160
+ end
161
+
162
+ def title_order(id)
163
+ type = id.class.name.split("::").last
164
+ year = id.year.to_s
165
+ years = [year, year[2..]]
166
+ citing_title.scan(CITATION) do |act, first, second|
167
+ next unless ACT_WORDS.fetch(act, act) == type
168
+
169
+ number_first = first == id.number && years.include?(second)
170
+ year_first = years.include?(first) && second == id.number
171
+ return number_first if number_first != year_first
172
+ end
173
+ nil
174
+ end
175
+
176
+ def docidentifier
177
+ [
178
+ Bib::Docidentifier.new(type: "EU", content: pubid.to_s, primary: true),
179
+ Bib::Docidentifier.new(type: "CELEX", content: "CELEX #{@row['celex']}"),
180
+ Bib::Docidentifier.new(type: "ELI", content: @row["eli"]),
181
+ ]
182
+ end
183
+
184
+ # The title the act order is read from: English, or French for an act
185
+ # with no English version.
186
+ def citing_title
187
+ @titles["ENG"] || @titles["FRA"] || ""
188
+ end
189
+
190
+ #
191
+ # One title a language, in FIRST_LANGUAGES order then by CELLAR code,
192
+ # without the EEA relevance note.
193
+ #
194
+ # @return [Array<Bib::Title>]
195
+ #
196
+ def title
197
+ @title ||= @titles.sort_by { |code, _| [FIRST_LANGUAGES.index(code) || 3, code] }
198
+ .filter_map do |code, text|
199
+ content = text.sub(EEA_NOTE, "")
200
+ next if content.empty?
201
+
202
+ lang, script = LANGUAGES.fetch(code)
203
+ Bib::Title.new(type: "main", content: content, language: lang, script: script)
204
+ end
205
+ end
206
+
207
+ #
208
+ # `?titles` is `<code>|<title>` pairs joined by Cellar::TITLE_SEP. A
209
+ # language CELLAR has two titles for keeps the first; a code not in
210
+ # LANGUAGES is dropped. The Official Journal writes a no-break space
211
+ # after `No`; a title keeps plain spaces.
212
+ #
213
+ # @return [Hash{String=>String}] CELLAR language code => title
214
+ #
215
+ def read_titles(value)
216
+ value.split(Cellar::TITLE_SEP).each_with_object({}) do |pair, titles|
217
+ code, text = pair.split("|", 2)
218
+ next unless LANGUAGES.key?(code) && !titles.key?(code)
219
+
220
+ text = text.to_s.gsub(/[[:space:]]+/, " ").strip
221
+ titles[code] = text unless text.empty?
222
+ end
223
+ end
224
+
225
+ #
226
+ # `issued`: the date of the document (adoption or signature).
227
+ # `implemented`: the first entry into force; an act can enter into
228
+ # force in stages (`2016/679`: 2016-05-24, then 2018-05-25).
229
+ #
230
+ def date
231
+ dates = []
232
+ dates << Bib::Date.new(type: "issued", at: @row["date"]) if @row["date"]
233
+ force = @row["force"].to_s.split.grep_v(PLACEHOLDER_DATE).min
234
+ dates << Bib::Date.new(type: "implemented", at: force) if force
235
+ dates
236
+ end
237
+
238
+ #
239
+ # Authors from the corporate-body authority (`…/corporate-body/EP`,
240
+ # with its English label), ordered by code; the Publications Office
241
+ # publishes every act.
242
+ #
243
+ def contributor
244
+ authors = @row["authors"].to_s.split("\n").filter_map do |line|
245
+ uri, label = line.split("|", 2)
246
+ code = uri.to_s.split("/").last
247
+ next if code.to_s.empty?
248
+
249
+ [code, label.to_s.empty? ? code : label]
250
+ end
251
+ authors.uniq.sort.map { |code, name| contrib("author", code, name) } <<
252
+ contrib("publisher", *PUBLISHER)
253
+ end
254
+
255
+ def contrib(role, code, name)
256
+ org = Bib::Organization.new(
257
+ name: [Bib::TypedLocalizedString.new(content: name)],
258
+ abbreviation: Bib::LocalizedString.new(content: code),
259
+ )
260
+ Bib::Contributor.new(role: [Bib::Contributor::Role.new(type: role)],
261
+ organization: org)
262
+ end
263
+
264
+ def status
265
+ stage = { "1" => "in-force", "0" => "not-in-force" }[@row["inforce"]]
266
+ Bib::Status.new(stage: Bib::Status::Stage.new(content: stage)) if stage
267
+ end
268
+
269
+ #
270
+ # The acts this act repeals and amends, by CELEX: the target's act
271
+ # identifier is not in the row, and a CELEX number cannot give it.
272
+ #
273
+ def relation
274
+ { "repeals" => "obsoletes", "amends" => "updates" }.flat_map do |key, type|
275
+ @row[key].to_s.split.map do |celex|
276
+ docid = Bib::Docidentifier.new(type: "CELEX", content: "CELEX #{celex}")
277
+ Bib::Relation.new(type: type, bibitem: Bib::ItemData.new(docidentifier: [docid]))
278
+ end
279
+ end
280
+ end
281
+
282
+ def source
283
+ [Bib::Uri.new(type: "src", content: "#{EURLEX}#{@row['celex']}")]
284
+ end
285
+
286
+ def ext
287
+ doctype = pubid.class.name.split("::").last.downcase
288
+ Bib::Ext.new(doctype: Bib::Doctype.new(content: doctype), flavor: "eu")
289
+ end
290
+ end
291
+ end
292
+ end
@@ -0,0 +1,61 @@
1
+ require_relative "../core/processor"
2
+
3
+ module Relaton
4
+ module Eu
5
+ class Processor < Relaton::Core::Processor
6
+ attr_reader :idtype
7
+
8
+ def initialize # rubocop:disable Lint/MissingSuper
9
+ @short = :relaton_eu
10
+ @prefix = "EU"
11
+ @defaultprefix = /^EU\s/
12
+ @idtype = "EU"
13
+ @datasets = %w[eu-cellar eu-cellar-updates]
14
+ # Db cache key and prefixes: `Pubid::Eu` (pubid 2.0.44, pubid#752).
15
+ @pubid_flavor = :Eu
16
+ end
17
+
18
+ # @param code [String, Pubid::Eu::Identifier]
19
+ # @param date [String, nil] year
20
+ # @param opts [Hash]
21
+ # @return [Relaton::Bib::ItemData, nil]
22
+ def get(code, date, opts)
23
+ require_relative "../eu"
24
+ Bibliography.get(code, date, opts)
25
+ end
26
+
27
+ # @param source [String] `eu-cellar` (full crawl) or `eu-cellar-updates`
28
+ # @param opts [Hash] `output:`, `format:`
29
+ def fetch_data(source, opts)
30
+ require_relative "data_fetcher"
31
+ DataFetcher.fetch(source, **opts)
32
+ end
33
+
34
+ # @param xml [String]
35
+ # @return [Relaton::Bib::ItemData]
36
+ def from_xml(xml)
37
+ require_relative "../eu"
38
+ Bib::Item.from_xml xml
39
+ end
40
+
41
+ # @param yaml [String]
42
+ # @return [Relaton::Bib::ItemData]
43
+ def from_yaml(yaml)
44
+ require_relative "../eu"
45
+ Bib::Item.from_yaml yaml
46
+ end
47
+
48
+ # @return [String]
49
+ def grammar_hash
50
+ require_relative "../eu"
51
+ @grammar_hash ||= Eu.grammar_hash
52
+ end
53
+
54
+ def remove_index_file
55
+ require_relative "../eu"
56
+ Relaton::Index.find_or_create(:eu, url: true,
57
+ file: "#{INDEXFILE}.yaml").remove_file
58
+ end
59
+ end
60
+ end
61
+ end
@@ -0,0 +1,9 @@
1
+ module Relaton
2
+ module Eu
3
+ module Util
4
+ extend Relaton::Bib::Util
5
+
6
+ PROGNAME = "relaton-eu".freeze
7
+ end
8
+ end
9
+ end
data/lib/relaton/eu.rb ADDED
@@ -0,0 +1,34 @@
1
+ require "digest/md5"
2
+ require "pubid"
3
+ require_relative "bib"
4
+ require_relative "index"
5
+ require_relative "version"
6
+
7
+ # Relaton::Eu is the EU legal acts flavor (relaton#44): regulations,
8
+ # directives and decisions, cited as `EU Regulation 1227/2011`.
9
+ #
10
+ # `DataFetcher` crawls the Publications Office CELLAR SPARQL endpoint into the
11
+ # `relaton-data-eu` data repo with a pubid `index-v2`, and `Bibliography`
12
+ # reads that index. See docs/eu.md.
13
+ module Relaton
14
+ module Eu
15
+ INDEXFILE = "index-v2".freeze
16
+ # The machine index on the data repo's Pages site (relaton#206).
17
+ PAGES_URL = "https://relaton.github.io/relaton-data-eu/".freeze
18
+ # Where the documents the index names are read from.
19
+ ENDPOINT = "https://raw.githubusercontent.com/relaton/relaton-data-eu/main/".freeze
20
+
21
+ autoload :Util, "relaton/eu/util"
22
+ autoload :Cellar, "relaton/eu/cellar"
23
+ autoload :Parser, "relaton/eu/parser"
24
+ autoload :Bibliography, "relaton/eu/bibliography"
25
+ autoload :DataFetcher, "relaton/eu/data_fetcher"
26
+ autoload :Processor, "relaton/eu/processor"
27
+
28
+ # Returns hash of XML grammar
29
+ # @return [String]
30
+ def self.grammar_hash
31
+ Digest::MD5.hexdigest Relaton::VERSION
32
+ end
33
+ end
34
+ end
@@ -204,16 +204,15 @@ module Relaton
204
204
 
205
205
  # Position of a raw row by its id hash — the raw-side equivalent of
206
206
  # `id_lookup`, built once, so a crawl's add_or_update stays O(1) per row.
207
+ # One pass over the rows; of two rows with one id, the first wins. (A
208
+ # search of the rows for each id made the build O(n²): 2800 s on the
209
+ # 184,528-row relaton-data-eu index.)
207
210
  def raw_position(raw_hash)
208
- @raw_lookup ||= raw_index[1].each_with_object({}) do |row, h|
209
- h[row[:id]] = h.key?(row[:id]) ? h[row[:id]] : rows_index_of(h, row)
211
+ @raw_lookup ||= raw_index[1].each_with_index.with_object({}) do |(row, i), h|
212
+ h[row[:id]] = i unless h.key?(row[:id])
210
213
  end
211
214
  @raw_lookup[raw_hash]
212
215
  end
213
-
214
- def rows_index_of(lookup, row)
215
- raw_index[1].index { |r| r[:id].equal?(row[:id]) || r[:id] == row[:id] }
216
- end
217
216
  # The pre-#242 add path, kept verbatim for seeded/materialized and
218
217
  # pubid-less indexes.
219
218
  def legacy_add(id, file)
@@ -159,7 +159,7 @@ module Relaton
159
159
  year = edition_year(refid)
160
160
  result.each do |r|
161
161
  /\((?:\d{2}\/)?(?<pyear>\d{4})\)/ =~ r.hit[:code]
162
- if !year || year == pyear
162
+ if year_selects?(r.hit, year, pyear)
163
163
  ret = r.item
164
164
  return { ret: ret } if ret
165
165
  end
@@ -171,6 +171,12 @@ module Relaton
171
171
  { years: missed_years }
172
172
  end
173
173
 
174
+ # Does a hit have the year? An ITU-R index hit has no `:code`:
175
+ # HitCollection#request_document has already applied the year.
176
+ def year_selects?(hit, year, pyear)
177
+ !year || year == pyear || !hit[:code]
178
+ end
179
+
174
180
  def itubib_get1(refid)
175
181
  result = search_filter(refid) || return
176
182
  ret = isobib_results_filter(result, refid)
@@ -62,7 +62,7 @@ module Relaton
62
62
  # R-REC the displayed code "BO.1130-5 (02/2026)" -> ITU-R BO.1130-5
63
63
  # R-REP the same, prefixed "BO.1227-2 (1998)" -> Report ITU-R BO.1227-2
64
64
  # R-QUE the same, + a colon "202-2/1" -> ITU-R 202-2/1:
65
- # R-RES the **page id** R-RES-R.1-9-2023 -> ITU-R R.1-9
65
+ # R-RES the **page id** R-RES-R.1-9-2023 -> Resolution ITU-R 1-9
66
66
  # R-HDB the **page id** R-HDB-43-2013 -> ITU-R 43.HDB (2013)
67
67
  #
68
68
  # Three of those need saying out loud. A **Report** is prefixed because
@@ -70,8 +70,13 @@ module Relaton
70
70
  # alone names two different documents (pubid #327 types the prefixed form
71
71
  # `pubid:itu:report`, and `output_file` sends it to `report-itu-r-*.yaml`
72
72
  # instead of colliding). A **Resolution** cannot use its displayed code at
73
- # all: the page renders "Res.1-9 (2023)" while the published record is
74
- # `ITU-R R.1-9`, which only the id carries. A **Handbook** likewise: the
73
+ # all: the page renders "Res.1-9 (2023)", and only the id carries the
74
+ # number. It is prefixed like a Report, in the form ITU cites
75
+ # (`Resolution ITU-R 1-9`), which pubid 2.0.46 types
76
+ # `pubid:itu:resolution` (relaton#402); the `ITU-R R.1-9` the dataset
77
+ # carried before read as a Recommendation of series R, and
78
+ # `output_file` now sends a Resolution to `resolution-itu-r-*.yaml`.
79
+ # A **Handbook** likewise: the
75
80
  # index lists its *title* and the leaf shows only a year — see
76
81
  # #handbook_docid.
77
82
  #
@@ -92,7 +97,7 @@ module Relaton
92
97
  # space. Same result, no ambiguity.
93
98
  code = row[:code].to_s.tr(" ", " ").sub(/\(.*\z/m, "").strip
94
99
  # The two id-derived families, before `code` gets a say.
95
- return "ITU-R #{resolution_number row}" if row[:family] == "R-RES"
100
+ return resolution_docid(row) if row[:family] == "R-RES"
96
101
  return handbook_docid(row) if row[:family] == "R-HDB"
97
102
  return nil if code.empty?
98
103
 
@@ -125,13 +130,18 @@ module Relaton
125
130
  m[:year] ? "ITU-R #{m[:number]}.HDB (#{m[:year]})" : "ITU-R #{m[:number]}.HDB"
126
131
  end
127
132
 
128
- # "R-RES-R.1-9-2023" -> "R.1-9"
133
+ # "R-RES-R.1-9-2023" -> "Resolution ITU-R 1-9".
134
+ #
135
+ # The year is dropped: the revision part names the edition, as a
136
+ # Report's does. The `R.` of the page id is the sector, which the
137
+ # `ITU-R` prefix already states.
129
138
  #
130
139
  # @param row [Hash]
131
140
  # @return [String, nil]
132
- def resolution_number(row)
133
- n = row[:id].to_s.sub(/\AR-RES-/, "").sub(/-(?:19|20)\d{2}\z/, "")
134
- n.empty? ? nil : n
141
+ def resolution_docid(row)
142
+ n = row[:id].to_s.delete_prefix("R-RES-").delete_prefix("R.")
143
+ .sub(/-(?:19|20)\d{2}\z/, "")
144
+ n.empty? ? nil : "Resolution ITU-R #{n}"
135
145
  end
136
146
 
137
147
  # @param row [Hash]
@@ -160,11 +160,10 @@ module Relaton
160
160
  # Pass the reference as a pubid (not a String) so Relaton::Index can
161
161
  # narrow candidates by document number before the block; `index_match?`
162
162
  # then matches every edition when the reference omits the part and the
163
- # exact edition when it names one. Rows are Pubid::Itu objects (not
164
- # Comparable), so rank by the numeric edition in `code.parts` (`["3"]` → 3)
165
- # to return the latest — index order isn't by edition.
163
+ # exact edition when it names one. The hit carries no `:code`, so the
164
+ # stated year is applied here (`#same_year?`), not in Bibliography.
166
165
  row = index.search(ref) { |i| index_match?(ref, i[:id]) }
167
- .max_by { |i| i[:id].code&.parts&.last.to_i }
166
+ .select { |i| same_year? i[:id] }.max_by { |i| edition_rank i[:id] }
168
167
  return unless row
169
168
 
170
169
  url = "#{GH_ITU}#{row[:file]}"
@@ -176,6 +175,40 @@ module Relaton
176
175
  @array = [hit]
177
176
  end
178
177
 
178
+ # Rows are Pubid::Itu objects (not Comparable), so rank by the numeric
179
+ # edition in `code.parts` (`["3"]` → 3), then by year (a handbook edition
180
+ # has no part, only a year) — index order isn't by edition.
181
+ #
182
+ # @param id [::Pubid::Itu::Identifier] an index row's id
183
+ # @return [Array<Integer>]
184
+ def edition_rank(id)
185
+ [id.code&.parts&.last.to_i, id.year.to_i]
186
+ end
187
+
188
+ # Does an ITU-R index row have the year the reference states? A dated row
189
+ # (a handbook edition, `ITU-R 43.HDB (2013)`) must have that year. An
190
+ # undated row (a recommendation, `ITU-R P.838-3`) is named by its edition
191
+ # part, so it stands for any year when the reference names that part
192
+ # (`ITU-R P.838-3 (03/2005)`): its record holds the publication date, and
193
+ # a reference cites the approval date, which can differ in year. A
194
+ # reference with a year and no part (`ITU-R P.838 (1999)`) cannot pick an
195
+ # undated edition, so it answers not-found rather than the newest one.
196
+ #
197
+ # @param id [::Pubid::Itu::Identifier] an index row's id
198
+ # @return [Boolean]
199
+ def same_year?(id)
200
+ year = ref.year
201
+ return true if year.nil?
202
+ return ref_part? if id.year.nil?
203
+
204
+ id.year.to_s == year.to_s
205
+ end
206
+
207
+ # @return [Boolean] true when the reference names an edition part
208
+ def ref_part?
209
+ !ref.code&.parts.to_a.empty?
210
+ end
211
+
179
212
  # Does an index row's id match the reference? When the reference omits the
180
213
  # part/edition (a bare `ITU-R P.838`), every edition of that exact document
181
214
  # matches — "search all parts"; when it names a part (`ITU-R P.838-2`), only
@@ -132,24 +132,37 @@ module Relaton
132
132
  suffixes
133
133
  end
134
134
 
135
- # The bibliography terminator; flavors override to suppress it
135
+ # The bibliography terminator is the i18n `punct.biblio-terminator`
136
+ # declaration, defaulting to "." (the 1.x render1 behaviour,
137
+ # relaton#597): a flavor declaring "" in its isodoc i18n hash --
138
+ # metanorma-iso since metanorma-jis#388 -- suppresses the
139
+ # entry-final period. Flavors still override this method outright
136
140
  # (1.x use_terminator?), receiving the item it terminates. A
137
141
  # reference closing on a footnote closes the sentence before it:
138
142
  # the terminator lands ahead of the trailing fn.
139
143
  FOOTNOTE_CLOSE = "</fn>".freeze
140
144
 
141
- def terminate_reference(ref, _item = nil)
142
- return ref if ref.empty? || ref.rstrip.end_with?(".")
145
+ def terminate_reference(ref, item = nil)
146
+ final = biblio_terminator(item)
147
+ return ref if ref.empty? || ref.rstrip.end_with?(final)
143
148
 
144
149
  if (fn = ref.rindex("<fn"))
145
150
  head = ref[0...fn].rstrip
146
151
  return ref if head.empty?
147
152
 
148
- sep = head.end_with?(".") ? "" : "."
153
+ sep = head.end_with?(final) ? "" : final
149
154
  return "#{head}#{sep}#{ref[fn..]}"
150
155
  end
151
156
 
152
- "#{ref}."
157
+ "#{ref}#{final}"
158
+ end
159
+
160
+ # The terminator as the item's language renders it: each item takes
161
+ # the i18n of the renderer localizing it (the 1.x
162
+ # `@i18n.select(obj)` selection)
163
+ def biblio_terminator(item = nil)
164
+ renderer_for(Array(item&.language).first)
165
+ .i18n.punct_fetch("biblio-terminator", ".")
153
166
  end
154
167
 
155
168
  # The style-keyed capsule ("citation" => { author_date: "..." })
@@ -38,7 +38,12 @@ module Relaton
38
38
  end
39
39
 
40
40
  # Runtime label overrides (a caller's i18n hash): the pack's label
41
- # names win as the key mapping; unknown keys are ignored.
41
+ # names win as the key mapping; unknown keys are ignored. The
42
+ # caller's `punct` subtree carries through (the 1.x behaviour,
43
+ # relaton#597): a flavor declares its bibliography punctuation --
44
+ # e.g. metanorma-iso's `punct: biblio-terminator: ""` suppressing
45
+ # the entry-final period -- in the same isodoc i18n hash that
46
+ # passes the labels.
42
47
  def overlay_hash!(hash)
43
48
  known = %w[
44
49
  edition series_no report_no available_from in and oxford_comma
@@ -48,6 +53,11 @@ module Relaton
48
53
  hash.each do |key, value|
49
54
  labels[key.to_s] = value if known.include?(key.to_s) && !value.nil?
50
55
  end
56
+ # callers symbolize the hash to varying depths (Relaton::Render
57
+ # General#deep_symbolize, metanorma-utils); the punct keys land
58
+ # stringified either way
59
+ sub = hash["punct"] || hash[:punct]
60
+ punct.merge!(sub.to_h { |k, v| [k.to_s, v] }) if sub.is_a?(Hash)
51
61
  self
52
62
  end
53
63
 
@@ -36,6 +36,12 @@ module Relaton
36
36
  @script = script
37
37
  end
38
38
 
39
+ # The engine's localized labels and punctuation, as resolved from
40
+ # the language pack, the caller's i18n hash, and the style's own
41
+ # locale (in rising precedence). General#terminate_reference reads
42
+ # the bibliography terminator here.
43
+ attr_reader :i18n
44
+
39
45
  def render(model, disambiguator: nil)
40
46
  kind = @style.kind_for(model.type)
41
47
  template = @style.template_for(kind, home: home_docid?(model))
@@ -1,3 +1,3 @@
1
1
  module Relaton
2
- VERSION = "3.1.7".freeze
2
+ VERSION = "3.1.8".freeze
3
3
  end
data/lib/relaton.rb CHANGED
@@ -36,6 +36,7 @@ module Relaton
36
36
  autoload :Ecma, "relaton/ecma"
37
37
  autoload :Etsi, "relaton/etsi"
38
38
  autoload :Easc, "relaton/easc"
39
+ autoload :Eu, "relaton/eu"
39
40
  autoload :Evs, "relaton/evs"
40
41
  autoload :Gost, "relaton/gost"
41
42
  autoload :Iana, "relaton/iana"
metadata CHANGED
@@ -1,14 +1,14 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: relaton
3
3
  version: !ruby/object:Gem::Version
4
- version: 3.1.7
4
+ version: 3.1.8
5
5
  platform: ruby
6
6
  authors:
7
7
  - Ribose Inc.
8
8
  autorequire:
9
9
  bindir: bin
10
10
  cert_chain: []
11
- date: 2026-11-19 00:00:00.000000000 Z
11
+ date: 2026-11-22 00:00:00.000000000 Z
12
12
  dependencies:
13
13
  - !ruby/object:Gem::Dependency
14
14
  name: addressable
@@ -520,14 +520,14 @@ dependencies:
520
520
  requirements:
521
521
  - - "~>"
522
522
  - !ruby/object:Gem::Version
523
- version: 2.0.44
523
+ version: 2.0.46
524
524
  type: :runtime
525
525
  prerelease: false
526
526
  version_requirements: !ruby/object:Gem::Requirement
527
527
  requirements:
528
528
  - - "~>"
529
529
  - !ruby/object:Gem::Version
530
- version: 2.0.44
530
+ version: 2.0.46
531
531
  - !ruby/object:Gem::Dependency
532
532
  name: yeptris
533
533
  requirement: !ruby/object:Gem::Requirement
@@ -964,6 +964,13 @@ files:
964
964
  - lib/relaton/etsi/pubid.rb
965
965
  - lib/relaton/etsi/status.rb
966
966
  - lib/relaton/etsi/util.rb
967
+ - lib/relaton/eu.rb
968
+ - lib/relaton/eu/bibliography.rb
969
+ - lib/relaton/eu/cellar.rb
970
+ - lib/relaton/eu/data_fetcher.rb
971
+ - lib/relaton/eu/parser.rb
972
+ - lib/relaton/eu/processor.rb
973
+ - lib/relaton/eu/util.rb
967
974
  - lib/relaton/evs.rb
968
975
  - lib/relaton/evs/README.adoc
969
976
  - lib/relaton/evs/bibliography.rb