daytona 0.234.3 → 0.238.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 9f9a1714703bcc6d5dbeeee37504f03144df98164356904b9b0a4ddee5c809e2
4
- data.tar.gz: 8ea8179af48d3bd2ce38033fc358237269324f233181e1ea99c50fbc1195bc6b
3
+ metadata.gz: 44b1feb4814d3ecb8e01550027a10979c8dbff95830c06c0f153334be64ff979
4
+ data.tar.gz: 1ed6f941e5cd72b8c3fea5d8e3b14186226fda9186324a6ef97e70e988d0badc
5
5
  SHA512:
6
- metadata.gz: 4e54c86576cb854d8ab21b430f19c2a9a1355202822afb9189276c0243430dc7ac132e3c750d137b03b7e278b44632a21a36d7522cf893c31accce4576c95f70
7
- data.tar.gz: e690bb7f15a60dbe1e51347c9d3d54ce216153a312d07868de365e767883661cbf70809f5be785081b0ae4103001baa7a90b7021c0c7ce83ed6d7b28970effb6
6
+ metadata.gz: cb12008517acc876f597ca2c987558ff2549e940d0dd0e239da19bf09474773a7001a3e9bc1c66738130ea6badf33d3bc1eb0060126300edf0e1b99ecbf4e480
7
+ data.tar.gz: 92590de2247240fcceed4a8d12484b5066f0c6de792fd00155ce7e2009e240f7539e4fe75dfc87c865fea0106ef1578a239d27fe0038b7b8f7c4dc727bad5efc
@@ -13,12 +13,18 @@ module Daytona
13
13
  class Context
14
14
  attr_reader :source_path
15
15
  attr_reader :archive_path
16
+ # @return [String, nil] The `.dockerignore` of the build context the source belongs to. Entries
17
+ # it excludes are not uploaded.
18
+ attr_reader :dockerignore_path
16
19
 
17
20
  # @param source_path [String] The path to the source file or directory
18
21
  # @param archive_path [String, nil] The path inside the archive file in object storage
19
- def initialize(source_path:, archive_path: nil)
22
+ # @param dockerignore_path [String, nil] The `.dockerignore` of the build context the source
23
+ # belongs to
24
+ def initialize(source_path:, archive_path: nil, dockerignore_path: nil)
20
25
  @source_path = source_path
21
26
  @archive_path = archive_path
27
+ @dockerignore_path = dockerignore_path
22
28
  end
23
29
  end
24
30
 
@@ -255,7 +261,8 @@ module Daytona
255
261
  # Adds arbitrary Dockerfile-like commands to the image
256
262
  #
257
263
  # @param dockerfile_commands [Array<String>] The commands to add to the Dockerfile
258
- # @param context_dir [String, nil] The path to the context directory
264
+ # @param context_dir [String, nil] The path to the context directory. Files excluded by its
265
+ # `.dockerignore` are not uploaded
259
266
  # @param strict_context [Boolean] When true, a COPY source that resolves outside context_dir is
260
267
  # rejected instead of read. Requires context_dir, so that the boundary is explicit rather than
261
268
  # taken from the working directory. Sources that legitimately live elsewhere belong in
@@ -264,17 +271,18 @@ module Daytona
264
271
  #
265
272
  # @example
266
273
  # image = Image.debian_slim("3.12").dockerfile_commands(["RUN echo 'Hello, world!'"])
267
- def dockerfile_commands(dockerfile_commands, context_dir: nil, strict_context: false) # rubocop:disable Metrics/MethodLength
274
+ def dockerfile_commands(dockerfile_commands, context_dir: nil, strict_context: false) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
268
275
  context_dir = self.class.send(:validate_context_dir, context_dir, strict_context)
269
276
  root, real_root = self.class.send(:context_boundary, context_dir, strict_context)
270
277
  commands = dockerfile_commands.join("\n")
271
278
 
272
279
  # Extract copy sources from dockerfile commands (class-level helper)
273
280
  copy_sources = self.class.send(:extract_copy_sources, commands, context_dir || '', real_root)
281
+ dockerignore_path = context_dir && File.join(context_dir, '.dockerignore')
274
282
  copy_sources.each do |context_path, original_path|
275
283
  archive_base_path = context_path
276
284
  archive_base_path = context_path.delete_prefix(root) unless original_path.start_with?(root)
277
- @context_list << Context.new(source_path: context_path, archive_path: archive_base_path)
285
+ @context_list << Context.new(source_path: context_path, archive_path: archive_base_path, dockerignore_path:)
278
286
  end
279
287
 
280
288
  @dockerfile += "#{commands}\n"
@@ -284,6 +292,10 @@ module Daytona
284
292
  class << self
285
293
  # Creates an Image from an existing Dockerfile
286
294
  #
295
+ # The Dockerfile's directory is the build context. Like Docker, files excluded by
296
+ # `<Dockerfile name>.dockerignore` next to the Dockerfile, or else by `.dockerignore` in the
297
+ # context, are not uploaded.
298
+ #
287
299
  # @param path [String] The path to the Dockerfile
288
300
  # @param strict_context [Boolean] When true, a COPY source that resolves outside the
289
301
  # Dockerfile's directory is rejected instead of read. Sources that legitimately live
@@ -300,11 +312,13 @@ module Daytona
300
312
  # Remove dockerfile filename from path
301
313
  path_prefix = path.to_s.delete_suffix(path.basename.to_s)
302
314
  real_root = strict_root(path_prefix, strict_context)
315
+ dockerignore_path = dockerignore_for(path)
303
316
 
304
317
  extract_copy_sources(dockerfile, path_prefix, real_root).each do |context_path, original_path|
305
318
  archive_base_path = context_path
306
319
  archive_base_path = context_path.delete_prefix(path_prefix) unless original_path.start_with?(path_prefix)
307
- img.context_list << Context.new(source_path: context_path, archive_path: archive_base_path)
320
+ img.context_list << Context.new(source_path: context_path, archive_path: archive_base_path,
321
+ dockerignore_path:)
308
322
  end
309
323
 
310
324
  img
@@ -347,6 +361,15 @@ module Daytona
347
361
 
348
362
  private
349
363
 
364
+ # Like Docker, a Dockerfile-specific ignore file takes precedence over the context's one
365
+ #
366
+ # @param dockerfile_path [Pathname] The expanded Dockerfile path
367
+ # @return [String] The `.dockerignore` that applies to the Dockerfile's build context
368
+ def dockerignore_for(dockerfile_path)
369
+ specific = "#{dockerfile_path}.dockerignore"
370
+ File.file?(specific) ? specific : File.join(dockerfile_path.dirname.to_s, '.dockerignore')
371
+ end
372
+
350
373
  # Processes the Python version
351
374
  #
352
375
  # @param python_version [String, nil] The Python version to process
@@ -9,9 +9,10 @@ require 'pathname'
9
9
  require 'tempfile'
10
10
  require 'zlib'
11
11
  require 'aws-sdk-s3'
12
+ require_relative 'utils/docker_ignore'
12
13
 
13
14
  module Daytona
14
- class ObjectStorage
15
+ class ObjectStorage # rubocop:disable Metrics/ClassLength
15
16
  # @return [String] The name of the S3 bucket used for object storage
16
17
  attr_reader :bucket_name
17
18
 
@@ -44,11 +45,17 @@ module Daytona
44
45
  # @param path [String] The path to the file to upload
45
46
  # @param organization_id [String] The organization ID to use
46
47
  # @param archive_base_path [String, nil] The base path to use for the archive
48
+ # @param dockerignore_path [String, nil] The `.dockerignore` of the build context the path belongs
49
+ # to. Entries it excludes are left out of the archive and its hash.
47
50
  # @return [String] The hash of the uploaded file
48
51
  # @raise [Errno::ENOENT] If the path does not exist
49
- def upload(path, organization_id, archive_base_path = nil)
52
+ # @raise [Sdk::Error] If the `.dockerignore` holds a pattern Docker rejects
53
+ def upload(path, organization_id, archive_base_path = nil, dockerignore_path: nil)
50
54
  raise Errno::ENOENT, "Path does not exist: #{path}" unless File.exist?(path)
51
55
 
56
+ dockerignore = Utils::DockerIgnore.load(dockerignore_path)
57
+ return upload_filtered(path, organization_id, archive_base_path, dockerignore) if dockerignore
58
+
52
59
  path_hash = compute_hash_for_path_md5(path, archive_base_path)
53
60
  s3_key = "#{organization_id}/#{path_hash}/context.tar"
54
61
 
@@ -166,6 +173,93 @@ module Daytona
166
173
  end
167
174
  end
168
175
 
176
+ # Uploads the entries of a path that the `.dockerignore` rules keep
177
+ #
178
+ # @param path [String] The path to upload
179
+ # @param organization_id [String] The organization ID to use
180
+ # @param archive_base_path [String, nil] The base path to use for the archive
181
+ # @param dockerignore [Utils::DockerIgnore] The rules whose exclusions to leave out
182
+ # @return [String] The hash of the uploaded entries
183
+ def upload_filtered(path, organization_id, archive_base_path, dockerignore)
184
+ archive_base_path = self.class.compute_archive_base_path(path) if archive_base_path.nil?
185
+ root, name = archive_root(path, archive_base_path)
186
+ entries = dockerignore.context_entries(path, name)
187
+ path_hash = compute_hash_for_entries_md5(entries, archive_base_path)
188
+ s3_key = "#{organization_id}/#{path_hash}/context.tar"
189
+
190
+ upload_entries_as_tar(s3_key, root, entries) unless file_exists_in_s3(s3_key)
191
+
192
+ path_hash
193
+ end
194
+
195
+ # The directory to archive from and the name to archive a source under, so that the source is
196
+ # stored where the Dockerfile refers to it: at `archive_base_path`, as in the other SDKs. When
197
+ # the source path does not end with that name, or it climbs out with `..`, the source keeps
198
+ # its own name.
199
+ #
200
+ # @param path [String] The path to upload
201
+ # @param archive_base_path [String] The base path to use for the archive
202
+ # @return [Array(String, String)] The directory and the name of the source within it
203
+ def archive_root(path, archive_base_path)
204
+ name = archive_base_path.sub(%r{\A/+}, '')
205
+ name = '.' if name.empty?
206
+ unless name.split('/').include?('..')
207
+ return ['.', name] if path == name
208
+ return [path.delete_suffix(name), name] if path.end_with?("/#{name}")
209
+ end
210
+
211
+ expanded = File.expand_path(path)
212
+ [File.dirname(expanded), File.basename(expanded)]
213
+ end
214
+
215
+ # Computes the MD5 hash of exactly the entries `upload_entries_as_tar` archives
216
+ #
217
+ # @param entries [Array<Array(String, String)>] The local path and archive name of each entry
218
+ # @param archive_base_path [String] The base path to use for the archive
219
+ # @return [String] The MD5 hash
220
+ def compute_hash_for_entries_md5(entries, archive_base_path) # rubocop:disable Metrics/MethodLength
221
+ md5_hasher = Digest::MD5.new
222
+ md5_hasher.update(archive_base_path)
223
+ entries.each do |local_path, name|
224
+ if File.symlink?(local_path)
225
+ md5_hasher.update("l\0#{name}\0#{File.readlink(local_path)}\0")
226
+ elsif File.directory?(local_path)
227
+ md5_hasher.update("d\0#{name}\0")
228
+ else
229
+ md5_hasher.update("f\0#{name}\0#{File.size(local_path)}\0")
230
+ md5_hasher.file(local_path)
231
+ end
232
+ end
233
+ md5_hasher.hexdigest
234
+ end
235
+
236
+ # Uploads the given entries as a tar, without recursing into directories
237
+ #
238
+ # @param s3_key [String] The key to upload the archive to
239
+ # @param root [String] The directory the entry names are relative to
240
+ # @param entries [Array<Array(String, String)>] The local path and archive name of each entry
241
+ def upload_entries_as_tar(s3_key, root, entries) # rubocop:disable Metrics/AbcSize, Metrics/MethodLength
242
+ temp_file = Tempfile.new(['context', '.tar'])
243
+ list_file = Tempfile.new(['context', '.list'])
244
+
245
+ begin
246
+ # NUL-separated names are read verbatim, so a name beginning with `-` is never an option.
247
+ list_file.binmode
248
+ list_file.write(entries.map { |_local_path, name| "#{name}\0" }.join)
249
+ list_file.close
250
+ unless system('tar', '-cf', temp_file.path, '-C', root, '--no-recursion', '--null', '-T', list_file.path)
251
+ raise Sdk::Error, "Failed to create tar archive for #{root}"
252
+ end
253
+
254
+ Aws::S3::TransferManager.new(client: s3_client)
255
+ .upload_file(temp_file.path, bucket: bucket_name, key: s3_key, **UPLOAD_OPTIONS)
256
+ ensure
257
+ list_file.close!
258
+ temp_file.close
259
+ temp_file.unlink
260
+ end
261
+ end
262
+
169
263
  DEFAULT_BUCKET_NAME = 'daytona-volume-builds'
170
264
 
171
265
  # multipart_threshold is also the part size floor: S3 rejects any part but the
@@ -527,11 +527,11 @@ module Daytona
527
527
  # For the current usage of a running Sandbox, use #get_metrics_latest, which reads
528
528
  # the live sample from the Sandbox daemon and does not go through the Analytics API.
529
529
  #
530
- # An HTTP 401 from the Analytics API does not always mean that the API key is
531
- # invalid: it also answers 401 when the Sandbox has been deleted (retrying does not
532
- # help) and when its access check was rate limited, for example on a burst of first
533
- # calls across many Sandboxes (a short retry with backoff succeeds). A 401 after an
534
- # earlier successful call for the same Sandbox can mean that the Sandbox is gone.
530
+ # Raises Sdk::NotFoundError when the Sandbox was not found, for example because it
531
+ # has been deleted (retrying does not help); Sdk::RateLimitError when the request was
532
+ # rate limited, for example its access check on a burst of first calls across many
533
+ # Sandboxes (retry after the delay in the Retry-After header, error.headers); and
534
+ # Sdk::AuthenticationError when the API key or token was not accepted.
535
535
  #
536
536
  # @param start_time [Time, nil] Start of the range. Defaults to the Sandbox creation time.
537
537
  # @param end_time [Time, nil] End of the range. Defaults to the current time.
@@ -539,7 +539,7 @@ module Daytona
539
539
  #
540
540
  # @example
541
541
  # sandbox.get_metrics.each { |m| puts "#{m.timestamp}: #{m.cpu_used_pct}%" }
542
- def get_metrics(start_time = nil, end_time = nil)
542
+ def get_metrics(start_time = nil, end_time = nil) # rubocop:disable Metrics/MethodLength
543
543
  from, to = metrics_range(start_time, end_time)
544
544
  analytics_api_url = fetch_analytics_api_url
545
545
  if analytics_api_url && !analytics_api_url.empty?
@@ -547,6 +547,8 @@ module Daytona
547
547
  else
548
548
  pivot_sandbox_metrics(fetch_proxy_metrics(from, to))
549
549
  end
550
+ rescue *Sdk::API_ERROR_CLASSES => e
551
+ raise Sdk.wrap_error(e, 'Failed to get sandbox metrics')
550
552
  rescue StandardError => e
551
553
  raise Sdk::Error, "Failed to get sandbox metrics: #{e.message}"
552
554
  end
@@ -9,7 +9,9 @@ module Daytona
9
9
  module Sdk # rubocop:disable Metrics/ModuleLength
10
10
  # ApiError classes raised by the generated OpenAPI clients. Kept here so
11
11
  # the error module can resolve them without depending on `sdk.rb`.
12
- API_ERROR_CLASSES = [DaytonaApiClient::ApiError, DaytonaToolboxApiClient::ApiError].freeze
12
+ API_ERROR_CLASSES = [
13
+ DaytonaApiClient::ApiError, DaytonaToolboxApiClient::ApiError, DaytonaAnalyticsApiClient::ApiError
14
+ ].freeze
13
15
 
14
16
  # Wire-format `source` values set by the translation layer when a
15
17
  # Daytona service stamps them on the wire envelope. `nil` source means
@@ -68,10 +70,7 @@ module Daytona
68
70
  class BadRequestError < Error; end
69
71
 
70
72
  # HTTP 401 — a Daytona service did not accept the request's credentials.
71
- # Usually the API key or token is missing, invalid or expired. A 401 can also
72
- # have other causes: when the deployment runs a dedicated Analytics API, the one
73
- # behind Sandbox#get_metrics also answers 401 for a deleted Sandbox or a
74
- # rate-limited access check (see that method).
73
+ # Usually the API key or token is missing, invalid or expired.
75
74
  class AuthenticationError < Error; end
76
75
 
77
76
  # HTTP 403 — caller is authenticated but not allowed.
@@ -5,6 +5,6 @@
5
5
 
6
6
  module Daytona
7
7
  module Sdk
8
- VERSION = '0.234.3'
8
+ VERSION = '0.238.0'
9
9
  end
10
10
  end
@@ -167,7 +167,8 @@ module Daytona
167
167
  object_storage.upload(
168
168
  context.source_path,
169
169
  push_access_creds.organization_id,
170
- context.archive_path
170
+ context.archive_path,
171
+ dockerignore_path: context.dockerignore_path
171
172
  )
172
173
  end
173
174
  end
@@ -0,0 +1,352 @@
1
+ # Copyright Daytona Platforms Inc.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # frozen_string_literal: true
5
+
6
+ require 'pathname'
7
+ require_relative 'go_glob'
8
+ require_relative 'go_regexp'
9
+
10
+ module Daytona
11
+ module Utils
12
+ # The `.dockerignore` rules of one build context.
13
+ #
14
+ # Matching follows Docker's own rules (moby/patternmatcher and the BuildKit context walker),
15
+ # not `.gitignore` rules: every pattern is anchored at the context root, `*` and `?` never
16
+ # cross a `/`, `**` spans any number of directories, a later `!` rule re-includes what an
17
+ # earlier rule excluded, and a rule that matches a directory excludes everything below it. A
18
+ # pattern Docker rejects fails the upload instead of being skipped.
19
+ class DockerIgnore # rubocop:disable Metrics/ClassLength
20
+ # One compiled pattern
21
+ class Pattern
22
+ attr_reader :cleaned
23
+ attr_reader :exclusion
24
+
25
+ def initialize(cleaned, exclusion, match_type, regex)
26
+ @cleaned = cleaned
27
+ @exclusion = exclusion
28
+ @match_type = match_type
29
+ @regex = regex
30
+ end
31
+
32
+ def match?(path)
33
+ case @match_type
34
+ when :exact then path == @cleaned
35
+ when :prefix then path.start_with?(@cleaned[0..-3])
36
+ when :suffix
37
+ suffix = @cleaned[2..]
38
+ path.end_with?(suffix) || (suffix.start_with?('/') && path == suffix[1..])
39
+ else
40
+ # Like Go's MatchString, the regexp may match anywhere; its own anchors decide.
41
+ @regex.match?(path.valid_encoding? ? path : path.scrub)
42
+ end
43
+ end
44
+
45
+ def without_trailing_glob
46
+ @cleaned.delete_suffix('/**').delete_suffix('/*')
47
+ end
48
+ end
49
+
50
+ # Regexp metacharacters Docker escapes so that they match literally. Its escape table is meant
51
+ # to cover "{", "|" and "}" too but overflows for them, so those reach the regexp unescaped.
52
+ LITERAL_REGEX_CHARS = '.+()$'
53
+ # Characters that make a pattern more than a plain path prefix
54
+ WILDCARD_CHARS = /[*\[\]?^\\]/
55
+ # Go's unicode.IsSpace, which strings.TrimSpace strips
56
+ SPACE = "\t\n\v\f\r \u0085\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000"
57
+ TRIM_SPACE = /\A[#{SPACE}]+|[#{SPACE}]+\z/
58
+ private_constant :LITERAL_REGEX_CHARS, :WILDCARD_CHARS, :SPACE, :TRIM_SPACE
59
+
60
+ # @return [String] The absolute build context root
61
+ attr_reader :context_root
62
+
63
+ # Reads the rules at `dockerignore_path`
64
+ #
65
+ # @param dockerignore_path [String, nil] The `.dockerignore` to read
66
+ # @return [DockerIgnore, nil] The rules, or nil when there is no such file or it has no rules,
67
+ # so that callers keep the unfiltered behaviour for contexts without a `.dockerignore`
68
+ # @raise [Sdk::Error] If the file holds a pattern Docker rejects
69
+ def self.load(dockerignore_path)
70
+ return nil if dockerignore_path.nil? || !File.file?(dockerignore_path)
71
+
72
+ patterns = parse(File.binread(dockerignore_path).force_encoding(Encoding::UTF_8), dockerignore_path)
73
+ return nil if patterns.empty?
74
+
75
+ new(File.dirname(File.expand_path(dockerignore_path)), patterns)
76
+ end
77
+
78
+ # Parses `.dockerignore` content into patterns, in file order
79
+ #
80
+ # @param content [String] The file content
81
+ # @param source [String] The file name, for error messages
82
+ # @return [Array<Pattern>]
83
+ # @raise [Sdk::Error] If a line holds a pattern Docker rejects
84
+ def self.parse(content, source) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
85
+ patterns = []
86
+ content.split("\n", -1).each_with_index do |raw_line, line_number|
87
+ line = raw_line.delete_suffix("\r")
88
+ line = line.byteslice(3..) if line_number.zero? && line.b.start_with?("\xEF\xBB\xBF".b)
89
+ next if line.start_with?('#')
90
+
91
+ line = trim_space(line)
92
+ next if line.empty?
93
+
94
+ # On Windows a backslash is a path separator, never an escape.
95
+ line = line.tr('\\', '/') if File::ALT_SEPARATOR == '\\'
96
+ exclusion = line.start_with?('!')
97
+ line = trim_space(line[1..]) if exclusion
98
+ line = clean(line) unless line.empty?
99
+ begin
100
+ pattern = read_pattern(exclusion ? "!#{line}" : line)
101
+ patterns << pattern if pattern
102
+ rescue GoRegexp::Error => e
103
+ raise Sdk::Error,
104
+ "#{source}:#{line_number + 1}: invalid pattern #{trim_space(raw_line).inspect}: #{e.message}"
105
+ end
106
+ end
107
+ patterns
108
+ end
109
+
110
+ # Reads one pattern the way Docker's matcher does. It cleans the pattern again, `!` included,
111
+ # and reads the `!` anew, so `!/` becomes the illegal `!` and `/!a` re-includes `a`.
112
+ #
113
+ # @return [Pattern, nil] The pattern, or nil when it is left empty
114
+ def self.read_pattern(line)
115
+ line = trim_space(line)
116
+ return nil if line.empty?
117
+
118
+ line = clean(line, strip_root: false)
119
+ exclusion = line.start_with?('!')
120
+ if exclusion
121
+ raise GoRegexp::Error, 'illegal exclusion pattern: "!"' if line.length == 1
122
+
123
+ line = line[1..]
124
+ end
125
+ compile(line, exclusion)
126
+ end
127
+
128
+ # Lexically cleans a pattern the way Go's `filepath.Clean` does. With `strip_root`, a leading
129
+ # slash is dropped as the ignore file reader does: every pattern is relative to the context root.
130
+ def self.clean(path, strip_root: true) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
131
+ rooted = path.start_with?('/')
132
+ parts = []
133
+ path.split('/').each do |part|
134
+ next if part.empty? || part == '.'
135
+
136
+ if part == '..'
137
+ if !parts.empty? && parts.last != '..' then parts.pop
138
+ elsif !rooted then parts << part
139
+ end
140
+ next
141
+ end
142
+ parts << part
143
+ end
144
+ cleaned = parts.join('/')
145
+ return rooted ? '/' : '.' if cleaned.empty?
146
+
147
+ rooted && !strip_root ? "/#{cleaned}" : cleaned
148
+ end
149
+
150
+ # Translates one pattern into a matcher, raising if Docker would reject it
151
+ def self.compile(cleaned, exclusion) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
152
+ # Docker checks the syntax with Go's filepath.Match against ".".
153
+ raise GoRegexp::Error, 'syntax error in pattern' if GoGlob.bad_pattern?(cleaned)
154
+
155
+ regex = +'^'
156
+ match_type = :exact
157
+ chars = cleaned.chars
158
+ position = 0
159
+ index = 0
160
+ while position < chars.length
161
+ char = chars[position]
162
+ position += 1
163
+ if char == '*' && chars[position] == '*'
164
+ position += 1
165
+ # "**/" behaves like "**".
166
+ position += 1 if chars[position] == '/'
167
+ if position == chars.length && match_type == :exact
168
+ match_type = :prefix
169
+ elsif position == chars.length
170
+ regex << '.*'
171
+ match_type = :regex
172
+ else
173
+ regex << '(.*/)?'
174
+ match_type = :regex
175
+ end
176
+ match_type = :suffix if index.zero?
177
+ elsif char == '*'
178
+ regex << '[^/]*'
179
+ match_type = :regex
180
+ elsif char == '?'
181
+ regex << '[^/]'
182
+ match_type = :regex
183
+ elsif LITERAL_REGEX_CHARS.include?(char)
184
+ regex << "\\#{char}"
185
+ elsif char == '\\'
186
+ if position < chars.length
187
+ regex << "\\#{chars[position]}"
188
+ position += 1
189
+ match_type = :regex
190
+ else
191
+ regex << '\\'
192
+ end
193
+ elsif ['[', ']'].include?(char)
194
+ regex << char
195
+ match_type = :regex
196
+ else
197
+ regex << char
198
+ end
199
+ index += 1
200
+ end
201
+
202
+ return Pattern.new(cleaned, exclusion, match_type, nil) unless match_type == :regex
203
+
204
+ # Docker's regexp is a Go one. Translate it so that it matches the same paths in Ruby.
205
+ Pattern.new(cleaned, exclusion, match_type, GoRegexp.compile("#{regex}$"))
206
+ end
207
+
208
+ def self.trim_space(text)
209
+ return text.gsub(TRIM_SPACE, '') if text.valid_encoding?
210
+
211
+ text.b.gsub(/\A[\t\n\v\f\r ]+|[\t\n\v\f\r ]+\z/n, '').force_encoding(Encoding::UTF_8)
212
+ end
213
+
214
+ private_class_method :parse, :read_pattern, :clean, :compile, :trim_space
215
+
216
+ # @param context_root [String] The absolute build context root
217
+ # @param patterns [Array<Pattern>] The rules, in file order
218
+ def initialize(context_root, patterns)
219
+ @context_root = context_root
220
+ @patterns = patterns
221
+ exclusions = patterns.select(&:exclusion)
222
+ @has_exclusions = !exclusions.empty?
223
+ @only_prefix_exclusions = exclusions.none? { |pattern| pattern.without_trailing_glob.match?(WILDCARD_CHARS) }
224
+ end
225
+
226
+ # Returns `path` relative to the context root with `/` separators, or nil when it lies outside
227
+ #
228
+ # @param path [String]
229
+ # @return [String, nil]
230
+ def relative(path)
231
+ relative = Pathname.new(File.expand_path(path)).relative_path_from(Pathname.new(@context_root)).to_s
232
+ relative = relative.tr(File::ALT_SEPARATOR, '/') if File::ALT_SEPARATOR
233
+ relative == '..' || relative.start_with?('../') ? nil : relative
234
+ rescue ArgumentError
235
+ # A different drive on Windows
236
+ nil
237
+ end
238
+
239
+ # Matches a context-relative path the way BuildKit does while it walks the context.
240
+ #
241
+ # @param relative [String] The context-relative path
242
+ # @param parent [Array<Boolean>, nil] Per pattern, whether it matched the parent directory (nil
243
+ # for an entry at the context root). A pattern that matched a parent applies to every entry
244
+ # below it, and one skipped at the parent is checked against the entry itself only.
245
+ # @return [Array(Boolean, Array<Boolean>)] Whether the path is excluded, and the per-pattern
246
+ # results to pass on to its children
247
+ def match(relative, parent)
248
+ excluded = false
249
+ results = @patterns.each_with_index.map do |pattern, index|
250
+ matched = !parent.nil? && parent[index]
251
+ # An exclusion can only change an excluded path, an inclusion an included one.
252
+ next false if !matched && pattern.exclusion != excluded
253
+
254
+ matched ||= pattern.match?(relative)
255
+ excluded = !pattern.exclusion if matched
256
+ matched
257
+ end
258
+ [excluded, results]
259
+ end
260
+
261
+ # Whether a context-relative path is excluded, given the directories above it
262
+ #
263
+ # @param relative [String]
264
+ # @return [Boolean]
265
+ def excludes?(relative)
266
+ # Docker never excludes the context root itself.
267
+ return false if relative == '.'
268
+
269
+ parts = relative.split('/')
270
+ parent = nil
271
+ (1...parts.length).each { |depth| parent = match(parts[0, depth].join('/'), parent)[1] }
272
+ match(relative, parent)[0]
273
+ end
274
+
275
+ # Whether a later `!` rule could re-include something inside an excluded directory
276
+ #
277
+ # @param relative_dir [String]
278
+ # @return [Boolean]
279
+ def may_include_below?(relative_dir)
280
+ return false unless @has_exclusions
281
+ return true unless @only_prefix_exclusions
282
+
283
+ dir_slash = "#{relative_dir}/"
284
+ @patterns.any? { |pattern| pattern.exclusion && "#{pattern.without_trailing_glob}/".start_with?(dir_slash) }
285
+ end
286
+
287
+ # Lists `[local path, name]` for every entry of a source that the rules keep, parents before
288
+ # children and siblings in name order. The source is named `name` and the entries below it
289
+ # `name/...`. Symlinks are kept as links and never followed, entries that are neither a
290
+ # regular file, a directory nor a symlink (sockets, FIFOs, devices) are left out, and a source
291
+ # outside the context root is not filtered at all.
292
+ #
293
+ # @param source_path [String] The file or directory to archive
294
+ # @param name [String] The name of the source in the archive
295
+ # @return [Array<Array(String, String)>]
296
+ def context_entries(source_path, name = File.basename(File.expand_path(source_path))) # rubocop:disable Metrics/MethodLength
297
+ source_path = File.expand_path(source_path)
298
+ relative = relative(source_path)
299
+ parent = nil
300
+ if relative && relative != '.'
301
+ # Match the directories above the source as BuildKit's walk from the context root would.
302
+ parts = relative.split('/')
303
+ (1...parts.length).each do |depth|
304
+ ancestor = parts[0, depth].join('/')
305
+ excluded, parent = match(ancestor, parent)
306
+ return [] if excluded && !may_include_below?(ancestor)
307
+ end
308
+ end
309
+ entries = []
310
+ walk(source_path, name, relative, parent, [], entries)
311
+ entries
312
+ end
313
+
314
+ private
315
+
316
+ # An excluded directory that is archived only if something below it is re-included
317
+ PendingDir = Struct.new(:local_path, :name, :emitted)
318
+ private_constant :PendingDir
319
+
320
+ def walk(local_path, name, relative, parent, pending, entries) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/ParameterLists, Metrics/PerceivedComplexity
321
+ type = File.lstat(local_path).ftype
322
+ # A socket cannot be archived, and reading a FIFO or a device would block or never end.
323
+ return unless %w[file directory link].include?(type)
324
+
325
+ is_dir = type == 'directory'
326
+ excluded = false
327
+ results = nil
328
+ excluded, results = match(relative, parent) if relative && relative != '.'
329
+ if excluded
330
+ return if !is_dir || !may_include_below?(relative)
331
+
332
+ pending = [*pending, PendingDir.new(local_path, name, false)]
333
+ else
334
+ pending.each do |directory|
335
+ next if directory.emitted
336
+
337
+ directory.emitted = true
338
+ entries << [directory.local_path, directory.name]
339
+ end
340
+ pending = []
341
+ entries << [local_path, name]
342
+ end
343
+ return unless is_dir
344
+
345
+ Dir.children(local_path).sort.each do |child|
346
+ child_relative = relative && (relative == '.' ? child : "#{relative}/#{child}")
347
+ walk(File.join(local_path, child), "#{name}/#{child}", child_relative, results, pending, entries)
348
+ end
349
+ end
350
+ end
351
+ end
352
+ end
@@ -0,0 +1,165 @@
1
+ # Copyright Daytona Platforms Inc.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # frozen_string_literal: true
5
+
6
+ module Daytona
7
+ module Utils
8
+ # Go's `filepath.Match(pattern, ".")`, which Docker calls to check the syntax of a
9
+ # `.dockerignore` pattern. It reports a malformed part only when matching reaches it, so it is
10
+ # followed step by step here rather than by checking the whole pattern.
11
+ module GoGlob # rubocop:disable Metrics/ModuleLength
12
+ SEPARATOR = 0x2f
13
+ NAME = [0x2e].freeze
14
+ RUNE_ERROR = 0xFFFD
15
+ private_constant :SEPARATOR, :NAME, :RUNE_ERROR
16
+
17
+ # Whether Go's `filepath.Match` rejects `pattern`
18
+ #
19
+ # @param pattern [String]
20
+ # @return [Boolean]
21
+ def self.bad_pattern?(pattern) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
22
+ pattern = pattern.b.bytes
23
+ name = NAME
24
+ until pattern.empty?
25
+ star, chunk, pattern = scan_chunk(pattern)
26
+ return false if star && chunk.empty?
27
+
28
+ rest, ok, bad = match_chunk(chunk, name)
29
+ if ok && (rest.empty? || !pattern.empty?)
30
+ name = rest
31
+ next
32
+ end
33
+ return true if bad
34
+ return false unless star
35
+
36
+ matched = false
37
+ (0...name.length).each do |i|
38
+ break if name[i] == SEPARATOR
39
+
40
+ rest, ok, bad = match_chunk(chunk, name[(i + 1)..])
41
+ next if ok && pattern.empty? && !rest.empty?
42
+
43
+ if ok
44
+ name = rest
45
+ matched = true
46
+ break
47
+ end
48
+ return true if bad
49
+ end
50
+ return false unless matched
51
+ end
52
+ false
53
+ end
54
+
55
+ def self.scan_chunk(pattern) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/MethodLength
56
+ star = false
57
+ while pattern.first == 0x2a
58
+ pattern = pattern.drop(1)
59
+ star = true
60
+ end
61
+ in_range = false
62
+ i = 0
63
+ while i < pattern.length
64
+ case pattern[i]
65
+ when 0x5c then i += 1 if i + 1 < pattern.length
66
+ when 0x5b then in_range = true
67
+ when 0x5d then in_range = false
68
+ when 0x2a then return [star, pattern[0...i], pattern[i..]] unless in_range
69
+ end
70
+ i += 1
71
+ end
72
+ [star, pattern, []]
73
+ end
74
+
75
+ # Returns [rest, ok, bad pattern]
76
+ def self.match_chunk(chunk, str) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
77
+ failed = false
78
+ until chunk.empty?
79
+ failed ||= str.empty?
80
+ case chunk.first
81
+ when 0x5b
82
+ rune = nil
83
+ unless failed
84
+ rune, size = decode_rune(str)
85
+ str = str.drop(size)
86
+ end
87
+ chunk, matched, bad = match_class(chunk.drop(1), rune)
88
+ return [[], false, true] if bad
89
+
90
+ failed ||= !matched
91
+ when 0x3f
92
+ unless failed
93
+ failed = str.first == SEPARATOR
94
+ str = str.drop(decode_rune(str)[1])
95
+ end
96
+ chunk = chunk.drop(1)
97
+ else
98
+ if chunk.first == 0x5c
99
+ chunk = chunk.drop(1)
100
+ return [[], false, true] if chunk.empty?
101
+ end
102
+ unless failed
103
+ failed = chunk.first != str.first
104
+ str = str.drop(1)
105
+ end
106
+ chunk = chunk.drop(1)
107
+ end
108
+ end
109
+ failed ? [[], false, false] : [str, true, false]
110
+ end
111
+
112
+ # Reads a bracket expression after its `[`. Returns [rest, matched, bad pattern]
113
+ def self.match_class(chunk, rune) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
114
+ negated = chunk.first == 0x5e
115
+ chunk = chunk.drop(1) if negated
116
+ matched = false
117
+ ranges = 0
118
+ loop do
119
+ return [chunk.drop(1), matched != negated, false] if chunk.first == 0x5d && ranges.positive?
120
+
121
+ low, chunk = class_char(chunk)
122
+ return [[], false, true] if low.nil?
123
+
124
+ high = low
125
+ if chunk.first == 0x2d
126
+ high, chunk = class_char(chunk.drop(1))
127
+ return [[], false, true] if high.nil?
128
+ end
129
+ matched ||= !rune.nil? && low <= rune && rune <= high
130
+ ranges += 1
131
+ end
132
+ end
133
+
134
+ # Go's getEsc: one character of a bracket expression, or nil for a bad pattern
135
+ def self.class_char(chunk) # rubocop:disable Metrics/CyclomaticComplexity
136
+ return nil if chunk.empty? || [0x2d, 0x5d].include?(chunk.first)
137
+
138
+ if chunk.first == 0x5c
139
+ chunk = chunk.drop(1)
140
+ return nil if chunk.empty?
141
+ end
142
+ rune, size = decode_rune(chunk)
143
+ rest = chunk.drop(size)
144
+ return nil if (rune == RUNE_ERROR && size == 1) || rest.empty?
145
+
146
+ [rune, rest]
147
+ end
148
+
149
+ # Go's utf8.DecodeRune
150
+ def self.decode_rune(bytes)
151
+ return [RUNE_ERROR, 0] if bytes.empty?
152
+ return [bytes.first, 1] if bytes.first < 0x80
153
+
154
+ size = if bytes.first >= 0xF0 then 4
155
+ elsif bytes.first >= 0xE0 then 3
156
+ else 2
157
+ end
158
+ text = bytes.first(size).pack('C*').force_encoding(Encoding::UTF_8)
159
+ bytes.length >= size && text.valid_encoding? ? [text.ord, size] : [RUNE_ERROR, 1]
160
+ end
161
+
162
+ private_class_method :scan_chunk, :match_chunk, :match_class, :class_char, :decode_rune
163
+ end
164
+ end
165
+ end
@@ -0,0 +1,291 @@
1
+ # Copyright Daytona Platforms Inc.
2
+ # SPDX-License-Identifier: Apache-2.0
3
+
4
+ # frozen_string_literal: true
5
+
6
+ require 'strscan'
7
+
8
+ module Daytona
9
+ module Utils
10
+ # Translates the Go regexp Docker builds for a `.dockerignore` pattern into a Ruby Regexp that
11
+ # matches the same paths.
12
+ #
13
+ # Only the syntax that can reach Docker's regexp is handled: Docker escapes `.`, `+`, `(`, `)`
14
+ # and `$`, but brackets, escapes, `|`, `{n,m}` and `^` reach it as they are. Ruby spells
15
+ # several of these differently (`^` and `$` are line anchors, `{,n}` is a repetition, POSIX
16
+ # classes are Unicode-aware), so everything is translated explicitly. Unicode classes (`\p`)
17
+ # are not supported, so a pattern using one is rejected.
18
+ class GoRegexp # rubocop:disable Metrics/ClassLength
19
+ # Raised for a regexp Go rejects or that has no Ruby equivalent
20
+ class Error < StandardError; end
21
+
22
+ # POSIX classes Go's regexp accepts in brackets, as ASCII ranges
23
+ POSIX_CLASSES = {
24
+ 'alnum' => [[0x30, 0x39], [0x41, 0x5a], [0x61, 0x7a]],
25
+ 'alpha' => [[0x41, 0x5a], [0x61, 0x7a]],
26
+ 'ascii' => [[0x00, 0x7f]],
27
+ 'blank' => [[0x09, 0x09], [0x20, 0x20]],
28
+ 'cntrl' => [[0x00, 0x1f], [0x7f, 0x7f]],
29
+ 'digit' => [[0x30, 0x39]],
30
+ 'graph' => [[0x21, 0x7e]],
31
+ 'lower' => [[0x61, 0x7a]],
32
+ 'print' => [[0x20, 0x7e]],
33
+ 'punct' => [[0x21, 0x2f], [0x3a, 0x40], [0x5b, 0x60], [0x7b, 0x7e]],
34
+ 'space' => [[0x09, 0x0d], [0x20, 0x20]],
35
+ 'upper' => [[0x41, 0x5a]],
36
+ 'word' => [[0x30, 0x39], [0x41, 0x5a], [0x61, 0x7a], [0x5f, 0x5f]],
37
+ 'xdigit' => [[0x30, 0x39], [0x41, 0x46], [0x61, 0x66]]
38
+ }.freeze
39
+ # Go's Perl classes; \s is narrower than POSIX space
40
+ PERL_CLASSES = {
41
+ 'd' => POSIX_CLASSES['digit'],
42
+ 's' => [[0x09, 0x0a], [0x0c, 0x0d], [0x20, 0x20]],
43
+ 'w' => POSIX_CLASSES['word']
44
+ }.freeze
45
+ CONTROL_ESCAPES = { 'a' => 0x07, 'f' => 0x0c, 'n' => 0x0a, 'r' => 0x0d, 't' => 0x09, 'v' => 0x0b }.freeze
46
+ WORD = '[0-9A-Za-z_]'
47
+ # Go's ASCII word boundaries, independent of the string's encoding
48
+ ASSERTIONS = {
49
+ 'A' => '\A',
50
+ 'z' => '\z',
51
+ 'b' => "(?:(?<=#{WORD})(?!#{WORD})|(?<!#{WORD})(?=#{WORD}))",
52
+ 'B' => "(?:(?<=#{WORD})(?=#{WORD})|(?<!#{WORD})(?!#{WORD}))"
53
+ }.freeze
54
+ # Go's limit on repetition counts
55
+ MAX_REPEAT = 1000
56
+ MAX_RUNE = 0x10FFFF
57
+ SURROGATES = (0xD800..0xDFFF)
58
+ # Matches nothing
59
+ NEVER = '(?:(?!))'
60
+ private_constant :POSIX_CLASSES, :PERL_CLASSES, :CONTROL_ESCAPES, :WORD, :ASSERTIONS, :MAX_REPEAT, :MAX_RUNE,
61
+ :SURROGATES, :NEVER
62
+
63
+ # @param regex [String] A Go regexp as Docker builds it
64
+ # @return [Regexp] The Ruby equivalent
65
+ # @raise [GoRegexp::Error] If Go rejects the regexp, or it has no Ruby equivalent
66
+ def self.compile(regex) # rubocop:disable Metrics/MethodLength
67
+ raise Error, 'invalid UTF-8' unless regex.valid_encoding?
68
+
69
+ translated = new(regex).translate
70
+ verbose = $VERBOSE
71
+ begin
72
+ # Go accepts overlapping class ranges, which Ruby warns about
73
+ $VERBOSE = nil
74
+ Regexp.new(translated)
75
+ rescue RegexpError => e
76
+ raise Error, e.message
77
+ ensure
78
+ $VERBOSE = verbose
79
+ end
80
+ end
81
+
82
+ def initialize(regex)
83
+ @scanner = StringScanner.new(regex)
84
+ @out = +''
85
+ # :none where a repetition has nothing to repeat, :repeat right after one
86
+ @last = :none
87
+ end
88
+
89
+ def translate # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
90
+ until @scanner.eos?
91
+ char = @scanner.getch
92
+ case char
93
+ when '[' then atom(translate_class)
94
+ when '\\' then translate_escape
95
+ when '{' then translate_brace
96
+ when '*', '?' then repeat(char)
97
+ when '|' then emit('|', :none)
98
+ when '(' then emit('(?:', :none)
99
+ when ')' then atom(')')
100
+ when '^' then atom('\A')
101
+ when '$' then atom('\z')
102
+ when '.' then atom('.')
103
+ else atom(literal(char.ord))
104
+ end
105
+ end
106
+ @out
107
+ end
108
+
109
+ private
110
+
111
+ # The next character, without consuming it (`StringScanner#peek` counts bytes)
112
+ def next_char
113
+ @scanner.check(/./m) || ''
114
+ end
115
+
116
+ def emit(fragment, kind)
117
+ @out << fragment
118
+ @last = kind
119
+ end
120
+
121
+ def atom(fragment)
122
+ emit(fragment, :atom)
123
+ end
124
+
125
+ def repeat(operator)
126
+ raise Error, 'missing argument to repetition operator' if @last == :none
127
+ raise Error, 'invalid nested repetition operator' if @last == :repeat
128
+
129
+ emit(operator, :repeat)
130
+ end
131
+
132
+ # A Go repetition `{n}`, `{n,}` or `{n,m}`; any other `{`, including one whose count has a
133
+ # leading zero, is a literal
134
+ def translate_brace # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
135
+ match = @scanner.scan(/(0|[1-9]\d*)(,(0|[1-9]\d*)?)?\}/)
136
+ return atom('\{') unless match
137
+
138
+ low = @scanner[1].to_i
139
+ high = @scanner[2] && @scanner[3] ? @scanner[3].to_i : nil
140
+ high = low if @scanner[2].nil?
141
+ raise Error, "invalid repeat count {#{match}" if low > MAX_REPEAT || (high && (high > MAX_REPEAT || high < low))
142
+
143
+ repeat("{#{match}")
144
+ end
145
+
146
+ def translate_escape # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength, Metrics/PerceivedComplexity
147
+ char = next_char
148
+ raise Error, 'trailing backslash at end of expression' if char.empty?
149
+
150
+ if (code = escaped_char)
151
+ atom(literal(code))
152
+ elsif PERL_CLASSES.key?(char.downcase)
153
+ @scanner.getch
154
+ set = PERL_CLASSES[char.downcase]
155
+ atom(char == char.downcase ? class_of(set, []) : class_of([], [set]))
156
+ elsif ASSERTIONS.key?(char)
157
+ @scanner.getch
158
+ atom(ASSERTIONS[char])
159
+ elsif char == 'Q'
160
+ @scanner.getch
161
+ text = @scanner.scan_until(/\\E/)
162
+ text = text ? text[0..-3] : @scanner.rest.tap { @scanner.terminate }
163
+ atom(text.each_char.map { |c| literal(c.ord) }.join)
164
+ else
165
+ raise Error, "unsupported escape \\#{char}"
166
+ end
167
+ end
168
+
169
+ # Reads the escape after a backslash when it stands for a single character, or returns nil
170
+ def escaped_char # rubocop:disable Metrics/MethodLength
171
+ char = next_char
172
+ if CONTROL_ESCAPES.key?(char)
173
+ @scanner.getch
174
+ CONTROL_ESCAPES[char]
175
+ elsif char == 'x'
176
+ @scanner.getch
177
+ hex_escape
178
+ elsif char.match?(/[0-7]/)
179
+ octal_escape
180
+ elsif char.match?(/[0-9A-Za-z]/)
181
+ nil
182
+ elsif !char.ascii_only?
183
+ raise Error, "invalid escape \\#{char}"
184
+ else
185
+ @scanner.getch.ord
186
+ end
187
+ end
188
+
189
+ def hex_escape
190
+ digits = @scanner.scan(/\{([0-9A-Fa-f]+)\}/) ? @scanner[1] : @scanner.scan(/[0-9A-Fa-f]{2}/)
191
+ raise Error, 'invalid escape \\x' if digits.nil? || digits.to_i(16) > MAX_RUNE
192
+
193
+ digits.to_i(16)
194
+ end
195
+
196
+ def octal_escape
197
+ digits = @scanner.scan(/[0-7]{1,3}/)
198
+ # A single non-zero digit would be a backreference, which Go does not support
199
+ raise Error, "invalid escape \\#{digits}" if digits.length == 1 && digits != '0'
200
+
201
+ digits.to_i(8)
202
+ end
203
+
204
+ # Translates a Go bracket expression, starting after its `[`
205
+ def translate_class # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/MethodLength
206
+ negated = !@scanner.scan('^').nil?
207
+ ranges = []
208
+ complements = []
209
+ first = true
210
+ loop do
211
+ raise Error, 'missing closing ]' if @scanner.eos?
212
+ break @scanner.getch if !first && next_char == ']'
213
+
214
+ first = false
215
+ next if named_class?(ranges, complements) || perl_class?(ranges, complements)
216
+
217
+ low = class_char
218
+ high = low
219
+ if @scanner.check(/-[^\]]/)
220
+ @scanner.getch
221
+ high = class_char
222
+ raise Error, 'invalid character class range' if high < low
223
+ end
224
+ ranges << [low, high]
225
+ end
226
+ class_of(ranges, complements, negated:)
227
+ end
228
+
229
+ def named_class?(ranges, complements)
230
+ return false unless @scanner.check(/\[:(.*?):\]/m)
231
+
232
+ name = @scanner[1]
233
+ class_name = name.delete_prefix('^')
234
+ raise Error, "unsupported character class [:#{name}:]" unless POSIX_CLASSES.key?(class_name)
235
+
236
+ @scanner.pos += name.bytesize + 4
237
+ name.start_with?('^') ? complements << POSIX_CLASSES[class_name] : ranges.concat(POSIX_CLASSES[class_name])
238
+ true
239
+ end
240
+
241
+ def perl_class?(ranges, complements)
242
+ escape = @scanner.check(/\\[dDsSwW]/)
243
+ return false unless escape
244
+
245
+ @scanner.pos += 2
246
+ set = PERL_CLASSES[escape[1].downcase]
247
+ escape[1] == escape[1].upcase ? complements << set : ranges.concat(set)
248
+ true
249
+ end
250
+
251
+ def class_char
252
+ char = @scanner.getch
253
+ raise Error, 'missing closing ]' if char.nil?
254
+ return char.ord unless char == '\\'
255
+
256
+ code = escaped_char
257
+ raise Error, "unsupported escape \\#{next_char} in a character class" if code.nil?
258
+
259
+ code
260
+ end
261
+
262
+ # A Ruby class holding `ranges` plus the complement of each set in `complements`
263
+ def class_of(ranges, complements, negated: false)
264
+ body = class_body(ranges) + complements.map { |set| "[^#{class_body(set)}]" }.join
265
+ # Every range was a surrogate, which no text holds.
266
+ return negated ? '(?m:.)' : NEVER if body.empty?
267
+
268
+ negated ? "[^#{body}]" : "[#{body}]"
269
+ end
270
+
271
+ def class_body(ranges)
272
+ without_surrogates(ranges).map do |low, high|
273
+ low == high ? literal(low) : "#{literal(low)}-#{literal(high)}"
274
+ end.join
275
+ end
276
+
277
+ # Go accepts surrogates, which never match UTF-8 text, and Ruby cannot spell them
278
+ def without_surrogates(ranges)
279
+ ranges.flat_map do |low, high|
280
+ next [[low, high]] if high < SURROGATES.first || low > SURROGATES.last
281
+
282
+ [[low, SURROGATES.first - 1], [SURROGATES.last + 1, high]].reject { |l, h| l > h }
283
+ end
284
+ end
285
+
286
+ def literal(code)
287
+ SURROGATES.cover?(code) ? NEVER : format('\\u{%x}', code)
288
+ end
289
+ end
290
+ end
291
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: daytona
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.234.3
4
+ version: 0.238.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Daytona Platforms Inc.
@@ -91,42 +91,42 @@ dependencies:
91
91
  requirements:
92
92
  - - '='
93
93
  - !ruby/object:Gem::Version
94
- version: 0.234.3
94
+ version: 0.238.0
95
95
  type: :runtime
96
96
  prerelease: false
97
97
  version_requirements: !ruby/object:Gem::Requirement
98
98
  requirements:
99
99
  - - '='
100
100
  - !ruby/object:Gem::Version
101
- version: 0.234.3
101
+ version: 0.238.0
102
102
  - !ruby/object:Gem::Dependency
103
103
  name: daytona_api_client
104
104
  requirement: !ruby/object:Gem::Requirement
105
105
  requirements:
106
106
  - - '='
107
107
  - !ruby/object:Gem::Version
108
- version: 0.234.3
108
+ version: 0.238.0
109
109
  type: :runtime
110
110
  prerelease: false
111
111
  version_requirements: !ruby/object:Gem::Requirement
112
112
  requirements:
113
113
  - - '='
114
114
  - !ruby/object:Gem::Version
115
- version: 0.234.3
115
+ version: 0.238.0
116
116
  - !ruby/object:Gem::Dependency
117
117
  name: daytona_toolbox_api_client
118
118
  requirement: !ruby/object:Gem::Requirement
119
119
  requirements:
120
120
  - - '='
121
121
  - !ruby/object:Gem::Version
122
- version: 0.234.3
122
+ version: 0.238.0
123
123
  type: :runtime
124
124
  prerelease: false
125
125
  version_requirements: !ruby/object:Gem::Requirement
126
126
  requirements:
127
127
  - - '='
128
128
  - !ruby/object:Gem::Version
129
- version: 0.234.3
129
+ version: 0.238.0
130
130
  - !ruby/object:Gem::Dependency
131
131
  name: dotenv
132
132
  requirement: !ruby/object:Gem::Requirement
@@ -243,7 +243,10 @@ files:
243
243
  - lib/daytona/secret_service.rb
244
244
  - lib/daytona/snapshot_service.rb
245
245
  - lib/daytona/util.rb
246
+ - lib/daytona/utils/docker_ignore.rb
246
247
  - lib/daytona/utils/file_url_signing.rb
248
+ - lib/daytona/utils/go_glob.rb
249
+ - lib/daytona/utils/go_regexp.rb
247
250
  - lib/daytona/volume.rb
248
251
  - lib/daytona/volume_service.rb
249
252
  - lib/daytona/warm_pool.rb