gubbins-fs 0.1.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.
Files changed (42) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +3 -0
  3. data/LICENSE +289 -0
  4. data/README.md +128 -0
  5. data/lib/fs/atomic_write.rb +121 -0
  6. data/lib/fs/concerns/argument_validation.rb +140 -0
  7. data/lib/fs/concerns/file_dsl_methods.rb +471 -0
  8. data/lib/fs/concerns/required_arguments.rb +141 -0
  9. data/lib/fs/directory/accessibility_check.rb +89 -0
  10. data/lib/fs/directory.rb +497 -0
  11. data/lib/fs/errors.rb +491 -0
  12. data/lib/fs/file.rb +1524 -0
  13. data/lib/fs/file_variant_builder.rb +269 -0
  14. data/lib/fs/file_variant_proxy.rb +253 -0
  15. data/lib/fs/files/csv.rb +26 -0
  16. data/lib/fs/files/gif.rb +10 -0
  17. data/lib/fs/files/image.rb +390 -0
  18. data/lib/fs/files/jpg.rb +36 -0
  19. data/lib/fs/files/json.rb +24 -0
  20. data/lib/fs/files/pdf.rb +231 -0
  21. data/lib/fs/files/pdf_collection.rb +64 -0
  22. data/lib/fs/files/png.rb +10 -0
  23. data/lib/fs/files/text.rb +13 -0
  24. data/lib/fs/files/tiff.rb +24 -0
  25. data/lib/fs/files/zip.rb +123 -0
  26. data/lib/fs/lockfile_sweeper.rb +70 -0
  27. data/lib/fs/tempfile_sweeper.rb +79 -0
  28. data/lib/fs/testing/mock/fs/configurator.rb +223 -0
  29. data/lib/fs/testing/mock/fs/dirs/directory.rb +41 -0
  30. data/lib/fs/testing/mock/fs/dsl.rb +81 -0
  31. data/lib/fs/testing/mock/fs/file.rb +60 -0
  32. data/lib/fs/testing/mock/fs/file_klass_mock.rb +350 -0
  33. data/lib/fs/testing/mock/fs/files/jpg.rb +14 -0
  34. data/lib/fs/testing/mock/fs/files/pdf.rb +19 -0
  35. data/lib/fs/testing/mock/fs/files/png.rb +12 -0
  36. data/lib/fs/testing/mock/fs/files/tiff.rb +12 -0
  37. data/lib/fs/testing/mock/fs/files/zip.rb +23 -0
  38. data/lib/fs/testing.rb +17 -0
  39. data/lib/fs/version.rb +3 -0
  40. data/lib/fs.rb +26 -0
  41. data/lib/gubbins/fs.rb +4 -0
  42. metadata +124 -0
data/lib/fs/errors.rb ADDED
@@ -0,0 +1,491 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/core_ext/array/access"
5
+ require "active_support/core_ext/class/attribute"
6
+ require "active_support/core_ext/object/blank"
7
+ require "active_support/core_ext/string/inflections"
8
+ require "i18n"
9
+
10
+ # The error classes this gem raises, and the base class and tag modules they need
11
+ #
12
+ # A copy of what gubbins-rails defines under the same names. Where both are loaded, they reopen
13
+ # the same classes with the same definitions, in whichever order. Keep them in step until
14
+ # the shared parts live in a gem of their own.
15
+ module Errors
16
+ # Base error class all our errors should descend from
17
+ #
18
+ # Since a lot of exceptions revolve around one specific subject
19
+ # which caused the error or is affected by it, you can pass one
20
+ # with `:subject`:
21
+ #
22
+ # `raise Errors::Error, subject: Order.last`
23
+ #
24
+ # WARNING: `Kernel#raise` does not play well with custom
25
+ # exception arguments. If your exception takes arguments such as `:subject`,
26
+ # use `MyError.raise` instead of `raise MyError`, or you will
27
+ # produce `TypeError: backtrace must be Array of String`.
28
+ #
29
+ # Your subclasses have a convenience helper available for
30
+ # producing an exception message automatically with `default_message`:
31
+ #
32
+ # ```ruby
33
+ # module Errors
34
+ # class MyError < Error
35
+ # default_message "This is the default message"
36
+ # end
37
+ # end
38
+ #
39
+ # raise Errors::MyError
40
+ # # => MyError: This is the default message
41
+ # ```
42
+ #
43
+ # If you provide an I81n key at errors/module name/class name,
44
+ # it will be used automatically without declaring `default_message`:
45
+ #
46
+ # ```ruby
47
+ # # config/locales/de.yml
48
+ # errors:
49
+ # my_error: Dies ist die Standardnachricht
50
+ #
51
+ # module Errors
52
+ # class MyError < Error
53
+ # end
54
+ # end
55
+ #
56
+ # raise Errors::MyError
57
+ # # => MyError: Dies ist die Standardnachricht
58
+ # ```
59
+ #
60
+ # Default messages can be blocks. These blocks receive
61
+ # two parameters, `:label` and `:subject`. Any object
62
+ # can be a subject; the label is the subjects textual
63
+ # representation.
64
+ #
65
+ # You can provide the label when raising the exception;
66
+ # if you don't, it is set automatically to `<class name> #<ID>`
67
+ #
68
+ # ```ruby
69
+ # class MyError < Error
70
+ # default_message do |label, subject|
71
+ # "#{label} is in state #{subject.state}"
72
+ # end
73
+ # end
74
+ #
75
+ # raise MyError, subject: Order.last
76
+ # # => MyError: Order #25 is in state :foo
77
+ #
78
+ # raise MyError, subject: Order.last, label: "Our lovely order"
79
+ # # => MyError: Our lovely client is in state :foo
80
+ #
81
+ # # Raising the exception with a message overrides the default:
82
+ # raise MyError, "custom message"
83
+ # # => MyError: custom message
84
+ #
85
+ # # Labels are still prefixed when providing a message:
86
+ # raise MyError, "produced an error", subject: Order.last
87
+ # # => MyError: Order #25 produced an error
88
+ # ```
89
+ #
90
+ # Raising it while handling another exception wraps that one, as it does
91
+ # for any Ruby exception: it becomes the `#cause`. To wrap one which is not
92
+ # the exception being handled, say so when raising:
93
+ # `raise MyError.new(subject: exchange), cause: exchange.exception`.
94
+ #
95
+ # ```ruby
96
+ # begin
97
+ # begin
98
+ # File.read("file.txt")
99
+ # rescue IOError
100
+ # raise Errors::Error, "failed to read file.txt"
101
+ # end
102
+ #
103
+ # rescue Errors::Error => ex
104
+ # puts ex.message
105
+ # # => "failed to read file.txt"
106
+ # puts ex.cause.class
107
+ # # => IOError
108
+ # end
109
+ # ```
110
+ #
111
+ class Error < StandardError
112
+ # Is this kind of error worth reporting to the error tracker?
113
+ #
114
+ # Reportable by default; subclasses which are expected, routine
115
+ # and handled (user input errors and the like) can opt out with
116
+ # {.not_reportable}. This only informs error trackers, it does not
117
+ # affect how the exception is raised, rescued or logged locally.
118
+ #
119
+ # @!method reportable?
120
+ # @return [Boolean]
121
+ class_attribute :reportable, instance_writer: false, default: true
122
+
123
+ # @return [Object] an optional subject this exception is
124
+ # about
125
+ attr_reader :subject
126
+
127
+ # @return [String, nil] what identifies the subject, eg. the path
128
+ # of the file this exception is about. Not part of the message of
129
+ # errors which have a translation, so error trackers need to ask for it.
130
+ attr_reader :label
131
+
132
+ class << self
133
+ # Mark this error class, and its subclasses, as not worth reporting
134
+ # to the error tracker
135
+ #
136
+ # @example
137
+ # ```ruby
138
+ # class MyError < Error
139
+ # not_reportable
140
+ # end
141
+ #
142
+ # MyError.new.reportable? # => false
143
+ # ```
144
+ #
145
+ # @return [void]
146
+ def not_reportable
147
+ self.reportable = false
148
+ end
149
+
150
+ # Set or get the default exception message
151
+ # for your subclass, or a formatter Proc that
152
+ # returns one
153
+ #
154
+ # @example
155
+ # ```ruby
156
+ # class MyError < Error
157
+ # default_message "This is a default message"
158
+ # end
159
+ #
160
+ # class MyOtherError < Error
161
+ # default_message do |label, subject|
162
+ # "#{label} was not found"
163
+ # end
164
+ # end
165
+ # ```
166
+ #
167
+ # @param message [String]
168
+ # @yieldreturn [String]
169
+ # @return [String]
170
+ def default_message(value = nil, &block)
171
+ if value || block
172
+ @default_message = value || block
173
+ else
174
+ @default_message
175
+ end
176
+ end
177
+ end
178
+
179
+ # Raise an exception
180
+ #
181
+ # This is a workaround for `Kernel.raise` not playing well
182
+ # with custom arguments, such as `:subject` or `:label`.
183
+ #
184
+ # If you use standard `raise MyError` and find yourself getting a
185
+ # `TypeError: backtrace must be Array of String`, use
186
+ # `MyError.raise` instead.
187
+ #
188
+ # @see #initialize
189
+ def self.raise(*args, **kargs)
190
+ backtrace = caller
191
+
192
+ new(*args, **kargs).tap do |exception|
193
+ Kernel.raise exception, exception.message, backtrace
194
+ end
195
+ end
196
+
197
+ # @param message [#to_s]
198
+ # @param subject [Object] an optional subject used to format the
199
+ # exception message
200
+ # @param label [String] an optional label to identify the subject
201
+ # of this exception
202
+ def initialize(message = nil, subject: nil, label: nil)
203
+ # Argument handling of `raise` with "optional args missing, but
204
+ # keyword args present" has changed in Ruby 3. Kwargs now end up as
205
+ # a `Hash` in the first `message` argument.
206
+ if message.is_a?(Hash)
207
+ subject ||= message[:subject]
208
+ label ||= message[:label]
209
+ message = nil
210
+ end
211
+
212
+ default_message = self.class.default_message
213
+
214
+ # `#cause` is only assigned by `raise`; until then, this is what it is going to be
215
+ handled = $!
216
+
217
+ if default_message.nil? && I18n.exists?(i18n_key, scope: i18n_scope)
218
+ default_message = t
219
+ end
220
+
221
+ if subject.present? && label.blank?
222
+ label =
223
+ "#{subject.class.name} ##{subject.id rescue subject.object_id}"
224
+ end
225
+
226
+ message =
227
+ if label.present? && message.present?
228
+ "#{label}: #{message}"
229
+
230
+ elsif message.present?
231
+ message
232
+
233
+ elsif default_message.is_a?(String)
234
+ default_message
235
+
236
+ elsif label.present? && default_message.is_a?(Proc)
237
+ instance_exec(label, subject, handled, &default_message)
238
+
239
+ elsif default_message.is_a?(Proc)
240
+ instance_exec(handled, &default_message)
241
+
242
+ elsif handled
243
+ handled.message
244
+ end
245
+
246
+ super(message)
247
+
248
+ @subject = subject
249
+ @label = label.presence
250
+ end
251
+
252
+ # A cleaned backtrace filtering out third-party and framework code
253
+ #
254
+ # @return [Array<String>]
255
+ def application_backtrace
256
+ application_backtrace_of(backtrace)
257
+ end
258
+
259
+ # A cleaned backtrace filtering out third-party and framework code
260
+ # for the exception which caused this one, if any
261
+ #
262
+ # @return [Array<String>]
263
+ def cause_application_backtrace
264
+ cause ? application_backtrace_of(cause.backtrace) : []
265
+ end
266
+
267
+ # @see I18n.t
268
+ # @param key [Symbol]
269
+ # @param scope [Symbol, Array<Symbol,String>]
270
+ # @return [String]
271
+ def t(key = i18n_key, scope: i18n_scope, **kargs)
272
+ I18n.t(key, scope: scope, **kargs)
273
+ end
274
+
275
+ # The class name as an I18n key
276
+ #
277
+ # @example
278
+ # Errors::Input::Invalid.new.i18n_key
279
+ # # => :invalid
280
+ #
281
+ # @return [Symbol]
282
+ def i18n_key
283
+ self.class
284
+ .name
285
+ .demodulize
286
+ .underscore
287
+ .to_sym
288
+ end
289
+
290
+ # The I18n lookup scope for this class
291
+ #
292
+ # @example
293
+ # Errors::Input::Invalid.new.i18n_scope
294
+ # # => [:errors, :input]
295
+ #
296
+ # @return [Array<Symbol>]
297
+ def i18n_scope
298
+ self.class
299
+ .name
300
+ .split("::")
301
+ .to(-2)
302
+ .map { |string| string.underscore.to_sym }
303
+ end
304
+
305
+ private
306
+
307
+ # Cleaned of framework and third-party code when running inside Rails, complete otherwise
308
+ #
309
+ # @param backtrace [Array<String>, nil]
310
+ # @return [Array<String>]
311
+ def application_backtrace_of(backtrace)
312
+ if defined?(Rails) && Rails.respond_to?(:backtrace_cleaner)
313
+ Rails.backtrace_cleaner.clean(backtrace)
314
+ else
315
+ Array(backtrace)
316
+ end
317
+ end
318
+ end
319
+
320
+ # This is a "tag module". Include it in your Error subclass to mark
321
+ # it as possibly transient and worth retrying.
322
+ #
323
+ # ```ruby
324
+ # module Errors
325
+ # class ApiFailure < Error
326
+ # include TransientError
327
+ # end
328
+ # end
329
+ #
330
+ # begin
331
+ # raise ApiFailure, "API is taking a nap"
332
+ # rescue TransientError =>
333
+ # # .. retry
334
+ # end
335
+ # ```
336
+ module TransientError; end
337
+
338
+ # Marks an error as probably being correctable by User intervention
339
+ module UserCorrectableError; end
340
+
341
+ # Marks an error as suitable for display to end users
342
+ #
343
+ # A host application can intercept these and pass their
344
+ # messages on to the client
345
+ module UserVisibleError
346
+ def self.included(klass)
347
+ klass.extend ClassMethods
348
+ end
349
+
350
+ module ClassMethods
351
+ # The HTTP status code to respond with
352
+ #
353
+ # Declare it with `@http_status_code = :not_found` in the class body.
354
+ # Subclasses inherit their parents' setting unless they declare their own.
355
+ #
356
+ # @return [Symbol]
357
+ def http_status_code
358
+ @http_status_code ||
359
+ (superclass.http_status_code if superclass.respond_to?(:http_status_code)) ||
360
+ :unprocessable_entity
361
+ end
362
+ end
363
+
364
+ def http_status_code
365
+ self.class.http_status_code
366
+ end
367
+ end
368
+
369
+ # Marks an error as unrecoverable one that produces an error page
370
+ #
371
+ # UserVisibleErrors can be recoverable and may thus be displayed
372
+ # inline inside the original page - for example as a dialog.
373
+ #
374
+ # UserVisibleFatalErrors move the User out of the original context
375
+ # and render an entire error page, like a HTTP 500 does.
376
+ #
377
+ # A host application can intercept these and pass their
378
+ # messages on to the client
379
+ module UserVisibleFatalError
380
+ def self.included(klass)
381
+ klass.extend ClassMethods
382
+ end
383
+
384
+ module ClassMethods
385
+ # The HTTP status code to respond with
386
+ #
387
+ # Declare it with `@http_status_code = :not_found` in the class body.
388
+ # Subclasses inherit their parents' setting unless they declare their own.
389
+ #
390
+ # @return [Symbol]
391
+ def http_status_code
392
+ @http_status_code ||
393
+ (superclass.http_status_code if superclass.respond_to?(:http_status_code)) ||
394
+ :forbidden
395
+ end
396
+ end
397
+
398
+ def http_status_code
399
+ self.class.http_status_code
400
+ end
401
+ end
402
+
403
+ module Fs
404
+ class ReadWrite < Error; end
405
+
406
+ # Raised when a {Fs::File.create}/{Fs::File.load_or_create} caller could
407
+ # not acquire the per-path creation lock within the given timeout - eg.
408
+ # because whoever is holding it crashed without releasing it and the
409
+ # underlying NFS lease hasn't expired yet.
410
+ class LockTimeout < ReadWrite; end
411
+
412
+ # Raised when a configured base directory of an {Fs::Directory} is not in a
413
+ # usable state. Base directories are hardcoded and supposed to be there, so
414
+ # trouble with one is infrastructure's.
415
+ #
416
+ # Never raised for anything below them, nor for a directory merely wrapped
417
+ # via `base_path:`: those are part of a file's path, and fail as
418
+ # {ReadWrite}, like the file would.
419
+ class BaseDirectory < Error
420
+ # The directory does not exist, and we were told not to create it
421
+ class Missing < BaseDirectory; end
422
+
423
+ # Something that is not a directory (a file, a dangling symlink) is in
424
+ # the way
425
+ class IsFile < BaseDirectory; end
426
+
427
+ # The directory was missing and we failed to create it
428
+ class CreateFailed < BaseDirectory; end
429
+
430
+ # The directory, or a parent of it, cannot even be inspected; `cause`
431
+ # holds the system error, eg. `EACCES` or `ESTALE` on a flaky NFS mount
432
+ class Inaccessible < BaseDirectory; end
433
+
434
+ # We lack read permission on the directory
435
+ class Unreadable < BaseDirectory; end
436
+
437
+ class Unwriteable < BaseDirectory; end
438
+ end
439
+
440
+ module Validation
441
+ class FileDoesNotExist < ReadWrite
442
+ include UserVisibleFatalError
443
+
444
+ @http_status_code = :not_found
445
+ end
446
+
447
+ class FileEmpty < ReadWrite
448
+ include UserVisibleError
449
+ end
450
+
451
+ class FileNotReadable < ReadWrite
452
+ include UserVisibleError
453
+ end
454
+
455
+ class FileNotWriteable < ReadWrite
456
+ include UserVisibleError
457
+ end
458
+
459
+ class FileUnreadable < ReadWrite
460
+ include UserVisibleError
461
+ end
462
+
463
+ # The `subject` of the three `Unsupported*` errors is the offending
464
+ # value (the extension, MIME type or encoding), the `label` is the
465
+ # path, as everywhere else in this namespace.
466
+ class UnsupportedExtension < ReadWrite
467
+ include UserVisibleError
468
+
469
+ default_message do |_label, subject|
470
+ t(extension: subject)
471
+ end
472
+ end
473
+
474
+ class UnsupportedMimeType < ReadWrite
475
+ include UserVisibleError
476
+
477
+ default_message do |_label, subject|
478
+ t(mime_type: subject)
479
+ end
480
+ end
481
+
482
+ class UnsupportedEncoding < ReadWrite
483
+ include UserVisibleError
484
+
485
+ default_message do |_label, subject|
486
+ t(encoding: subject)
487
+ end
488
+ end
489
+ end
490
+ end
491
+ end