1 # Copyright (C) The Arvados Authors. All rights reserved.
3 # SPDX-License-Identifier: Apache-2.0
7 # A Locator is used to parse and manipulate Keep locator strings.
9 # Locators obey the following syntax:
11 # locator ::= address hint*
12 # address ::= digest size-hint
13 # digest ::= <32 hexadecimal digits>
14 # size-hint ::= "+" [0-9]+
15 # hint ::= "+" hint-type hint-content
17 # hint-content ::= [A-Za-z0-9@_-]+
19 # Individual hints may have their own required format:
21 # sign-hint ::= "+A" <40 lowercase hex digits> "@" sign-timestamp
22 # sign-timestamp ::= <8 lowercase hex digits>
23 attr_reader :hash, :hints, :size
25 LOCATOR_REGEXP = /^([[:xdigit:]]{32})(\+([[:digit:]]+))?((\+([[:upper:]][[:alnum:]@_-]*))+)?\z/
27 def initialize(hasharg, sizearg, hintarg)
34 !!(LOCATOR_REGEXP.match tok)
37 # Locator.parse returns a Locator object parsed from the string tok.
38 # Returns nil if tok could not be parsed as a valid locator.
47 # Locator.parse! returns a Locator object parsed from the string tok,
48 # raising an ArgumentError if tok cannot be parsed.
50 if tok.nil? or tok.empty?
51 raise ArgumentError.new "locator is nil or empty"
54 m = LOCATOR_REGEXP.match(tok)
56 raise ArgumentError.new "not a valid locator #{tok}"
59 tokhash, _, toksize, _, _, trailer = m[1..6]
62 trailer.split('+').each do |hint|
63 if hint =~ /^[[:upper:]][[:alnum:]@_-]*$/
66 raise ArgumentError.new "invalid hint #{hint}"
71 Locator.new(tokhash, toksize, tokhints)
74 # Returns the signature hint supplied with this locator,
75 # or nil if the locator was not signed.
77 @hints.grep(/^A/).first
80 # Returns an unsigned Locator.
82 Locator.new(@hash, @size, @hints.reject { |o| o.start_with?("A") })
86 Locator.new(@hash, @size, [])
96 [ @hash, @size, *@hints ].join('+')
98 [ @hash, *@hints ].join('+')
104 STRICT_STREAM_TOKEN_REGEXP = /^(\.)(\/[^\/\t\v\n\r]+)*$/
105 STRICT_FILE_TOKEN_REGEXP = /^[[:digit:]]+:[[:digit:]]+:([^\t\v\n\r\/]+(\/[^\t\v\n\r\/]+)*)$/
106 EMPTY_DOT_FILE_TOKEN_REGEXP = /^0:0:\.$/
108 # Class to parse a manifest text and provide common views of that data.
109 def initialize(manifest_text)
110 @text = manifest_text
115 return to_enum(__method__) unless block_given?
116 @text.each_line do |line|
120 line.scan(/\S+/) do |token|
122 stream_name = unescape token
123 elsif file_tokens.empty? and Locator.valid? token
124 block_tokens << token
126 file_tokens << unescape(token)
130 next if stream_name.nil?
131 yield [stream_name, block_tokens, file_tokens]
138 # Parse backslash escapes in a Keep manifest stream or file name.
139 s.gsub(/\\(\\|[0-7]{3})/) do |_|
150 self.class.unescape(s)
153 def split_file_token token
154 start_pos, filesize, filename = token.split(':', 3)
156 raise ArgumentError.new "Invalid file token '#{token}'"
158 [start_pos.to_i, filesize.to_i, unescape(filename)]
162 return to_enum(__method__) unless block_given?
163 @text.each_line do |line|
165 in_file_tokens = false
166 line.scan(/\S+/) do |token|
168 stream_name = unescape token
169 elsif in_file_tokens or not Locator.valid? token
170 in_file_tokens = true
172 start_pos, file_size, file_name = split_file_token(token)
173 stream_name_adjuster = ''
174 if file_name.include?('/') # '/' in filename
175 dirname, sep, basename = file_name.rpartition('/')
176 stream_name_adjuster = sep + dirname # /dir_parts
180 yield [stream_name + stream_name_adjuster, start_pos, file_size, file_name]
189 file_sizes = Hash.new(0)
190 each_file_spec do |streamname, _, filesize, filename|
191 file_sizes[[streamname, filename]] += filesize
193 @files = file_sizes.each_pair.map do |(streamname, filename), size|
194 [streamname, filename, size]
200 def files_count(stop_after=nil)
201 # Return the number of files represented in this manifest.
202 # If stop_after is provided, files_count will read the manifest
203 # incrementally, and return immediately when it counts that number of
204 # files. This can help you avoid parsing the entire manifest if you
205 # just want to check if a small number of files are specified.
206 if stop_after.nil? or not @files.nil?
207 # Avoid counting empty dir placeholders
208 return files.reject{|_, name, size| name == '.' and size == 0}.size
211 each_file_spec do |streamname, _, filesize, filename|
212 # Avoid counting empty dir placeholders
213 next if filename == "." and filesize == 0
214 seen_files[[streamname, filename]] = true
215 return stop_after if (seen_files.size >= stop_after)
221 # Return the total size of all files in this manifest.
222 files.reduce(0) { |total, (_, _, size)| total + size }
225 def exact_file_count?(want_count)
226 files_count(want_count + 1) == want_count
229 def minimum_file_count?(want_count)
230 files_count(want_count) >= want_count
233 def has_file?(want_stream, want_file=nil)
235 want_stream, want_file = File.split(want_stream)
237 each_file_spec do |streamname, _, _, name|
238 if streamname == want_stream and name == want_file
245 # Verify that a given manifest is valid according to
246 # https://arvados.org/projects/arvados/wiki/Keep_manifest_format
247 def self.validate! manifest
248 raise ArgumentError.new "No manifest found" if !manifest
250 return true if manifest.empty?
252 raise ArgumentError.new "Invalid manifest: does not end with newline" if !manifest.end_with?("\n")
254 manifest.each_line do |line|
257 words = line[0..-2].split(/ /)
258 raise ArgumentError.new "Manifest invalid for stream #{line_count}: missing stream name" if words.empty?
263 unescaped_word = unescape(word)
264 count += 1 if unescaped_word =~ STRICT_STREAM_TOKEN_REGEXP and unescaped_word !~ /\/\.\.?(\/|$)/
265 raise ArgumentError.new "Manifest invalid for stream #{line_count}: missing or invalid stream name #{word.inspect if word}" if count != 1
269 while word =~ Locator::LOCATOR_REGEXP
273 raise ArgumentError.new "Manifest invalid for stream #{line_count}: missing or invalid locator #{word.inspect if word}" if count == 0
276 while unescape(word) =~ EMPTY_DOT_FILE_TOKEN_REGEXP or
277 (unescape(word) =~ STRICT_FILE_TOKEN_REGEXP and ($~[1].split('/') & ['..', '.']).empty?)
283 raise ArgumentError.new "Manifest invalid for stream #{line_count}: invalid file token #{word.inspect}"
285 raise ArgumentError.new "Manifest invalid for stream #{line_count}: no file tokens"
288 # Ruby's split() method silently drops trailing empty tokens
289 # (which are not allowed by the manifest format) so we have to
290 # check trailing spaces manually.
291 raise ArgumentError.new "Manifest invalid for stream #{line_count}: trailing space" if line.end_with? " \n"
296 def self.valid? manifest