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
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ff04579a25e218e0c76b1ae31308d09db8c5322425eb72a51a2dce2c1dfb39f2
4
+ data.tar.gz: 72c16139ab201d6c8b045b74430204274a7bbd5c1bcf44ae9c75053f39a35728
5
+ SHA512:
6
+ metadata.gz: 5face33180141f5a37c0704ffec660f9daf9ce910bcec2e3b5710749f751a7d46abb1583f92b7f5c25719ed3563a8015561443134850b54500c1f4e1cd377e55
7
+ data.tar.gz: 3836c59ce810d4a5fa92e985aa3b444f3c0e913eab92642bbcd08a94965d2a399e6dd0e81329b13d2c2728bc7ab49a85e89a52444633df528afa8676f62fd338
data/CHANGELOG.md ADDED
@@ -0,0 +1,3 @@
1
+ ## [Unreleased]
2
+
3
+ - `Fs::Directory.root_path` is now configurable and defaults to `/` instead of `Rails.root`; relative base paths are resolved on every read, so it may be set after Directory classes are defined
data/LICENSE ADDED
@@ -0,0 +1,289 @@
1
+ Copyright Jan-Christian Foeh
2
+
3
+ EUROPEAN UNION PUBLIC LICENCE v. 1.2
4
+ EUPL © the European Union 2007, 2016
5
+
6
+ This European Union Public Licence (the ‘EUPL’) applies to the Work (as defined
7
+ below) which is provided under the terms of this Licence. Any use of the Work,
8
+ other than as authorised under this Licence is prohibited (to the extent such
9
+ use is covered by a right of the copyright holder of the Work).
10
+
11
+ The Work is provided under the terms of this Licence when the Licensor (as
12
+ defined below) has placed the following notice immediately following the
13
+ copyright notice for the Work:
14
+
15
+ Licensed under the EUPL
16
+
17
+ or has expressed by any other means his willingness to license under the EUPL.
18
+
19
+ 1. Definitions
20
+
21
+ In this Licence, the following terms have the following meaning:
22
+
23
+ - ‘The Licence’: this Licence.
24
+
25
+ - ‘The Original Work’: the work or software distributed or communicated by the
26
+ Licensor under this Licence, available as Source Code and also as Executable
27
+ Code as the case may be.
28
+
29
+ - ‘Derivative Works’: the works or software that could be created by the
30
+ Licensee, based upon the Original Work or modifications thereof. This Licence
31
+ does not define the extent of modification or dependence on the Original Work
32
+ required in order to classify a work as a Derivative Work; this extent is
33
+ determined by copyright law applicable in the country mentioned in Article 15.
34
+
35
+ - ‘The Work’: the Original Work or its Derivative Works.
36
+
37
+ - ‘The Source Code’: the human-readable form of the Work which is the most
38
+ convenient for people to study and modify.
39
+
40
+ - ‘The Executable Code’: any code which has generally been compiled and which is
41
+ meant to be interpreted by a computer as a program.
42
+
43
+ - ‘The Licensor’: the natural or legal person that distributes or communicates
44
+ the Work under the Licence.
45
+
46
+ - ‘Contributor(s)’: any natural or legal person who modifies the Work under the
47
+ Licence, or otherwise contributes to the creation of a Derivative Work.
48
+
49
+ - ‘The Licensee’ or ‘You’: any natural or legal person who makes any usage of
50
+ the Work under the terms of the Licence.
51
+
52
+ - ‘Distribution’ or ‘Communication’: any act of selling, giving, lending,
53
+ renting, distributing, communicating, transmitting, or otherwise making
54
+ available, online or offline, copies of the Work or providing access to its
55
+ essential functionalities at the disposal of any other natural or legal
56
+ person.
57
+
58
+ 2. Scope of the rights granted by the Licence
59
+
60
+ The Licensor hereby grants You a worldwide, royalty-free, non-exclusive,
61
+ sublicensable licence to do the following, for the duration of copyright vested
62
+ in the Original Work:
63
+
64
+ - use the Work in any circumstance and for all usage,
65
+ - reproduce the Work,
66
+ - modify the Work, and make Derivative Works based upon the Work,
67
+ - communicate to the public, including the right to make available or display
68
+ the Work or copies thereof to the public and perform publicly, as the case may
69
+ be, the Work,
70
+ - distribute the Work or copies thereof,
71
+ - lend and rent the Work or copies thereof,
72
+ - sublicense rights in the Work or copies thereof.
73
+
74
+ Those rights can be exercised on any media, supports and formats, whether now
75
+ known or later invented, as far as the applicable law permits so.
76
+
77
+ In the countries where moral rights apply, the Licensor waives his right to
78
+ exercise his moral right to the extent allowed by law in order to make effective
79
+ the licence of the economic rights here above listed.
80
+
81
+ The Licensor grants to the Licensee royalty-free, non-exclusive usage rights to
82
+ any patents held by the Licensor, to the extent necessary to make use of the
83
+ rights granted on the Work under this Licence.
84
+
85
+ 3. Communication of the Source Code
86
+
87
+ The Licensor may provide the Work either in its Source Code form, or as
88
+ Executable Code. If the Work is provided as Executable Code, the Licensor
89
+ provides in addition a machine-readable copy of the Source Code of the Work
90
+ along with each copy of the Work that the Licensor distributes or indicates, in
91
+ a notice following the copyright notice attached to the Work, a repository where
92
+ the Source Code is easily and freely accessible for as long as the Licensor
93
+ continues to distribute or communicate the Work.
94
+
95
+ 4. Limitations on copyright
96
+
97
+ Nothing in this Licence is intended to deprive the Licensee of the benefits from
98
+ any exception or limitation to the exclusive rights of the rights owners in the
99
+ Work, of the exhaustion of those rights or of other applicable limitations
100
+ thereto.
101
+
102
+ 5. Obligations of the Licensee
103
+
104
+ The grant of the rights mentioned above is subject to some restrictions and
105
+ obligations imposed on the Licensee. Those obligations are the following:
106
+
107
+ Attribution right: The Licensee shall keep intact all copyright, patent or
108
+ trademarks notices and all notices that refer to the Licence and to the
109
+ disclaimer of warranties. The Licensee must include a copy of such notices and a
110
+ copy of the Licence with every copy of the Work he/she distributes or
111
+ communicates. The Licensee must cause any Derivative Work to carry prominent
112
+ notices stating that the Work has been modified and the date of modification.
113
+
114
+ Copyleft clause: If the Licensee distributes or communicates copies of the
115
+ Original Works or Derivative Works, this Distribution or Communication will be
116
+ done under the terms of this Licence or of a later version of this Licence
117
+ unless the Original Work is expressly distributed only under this version of the
118
+ Licence — for example by communicating ‘EUPL v. 1.2 only’. The Licensee
119
+ (becoming Licensor) cannot offer or impose any additional terms or conditions on
120
+ the Work or Derivative Work that alter or restrict the terms of the Licence.
121
+
122
+ Compatibility clause: If the Licensee Distributes or Communicates Derivative
123
+ Works or copies thereof based upon both the Work and another work licensed under
124
+ a Compatible Licence, this Distribution or Communication can be done under the
125
+ terms of this Compatible Licence. For the sake of this clause, ‘Compatible
126
+ Licence’ refers to the licences listed in the appendix attached to this Licence.
127
+ Should the Licensee's obligations under the Compatible Licence conflict with
128
+ his/her obligations under this Licence, the obligations of the Compatible
129
+ Licence shall prevail.
130
+
131
+ Provision of Source Code: When distributing or communicating copies of the Work,
132
+ the Licensee will provide a machine-readable copy of the Source Code or indicate
133
+ a repository where this Source will be easily and freely available for as long
134
+ as the Licensee continues to distribute or communicate the Work.
135
+
136
+ Legal Protection: This Licence does not grant permission to use the trade names,
137
+ trademarks, service marks, or names of the Licensor, except as required for
138
+ reasonable and customary use in describing the origin of the Work and
139
+ reproducing the content of the copyright notice.
140
+
141
+ 6. Chain of Authorship
142
+
143
+ The original Licensor warrants that the copyright in the Original Work granted
144
+ hereunder is owned by him/her or licensed to him/her and that he/she has the
145
+ power and authority to grant the Licence.
146
+
147
+ Each Contributor warrants that the copyright in the modifications he/she brings
148
+ to the Work are owned by him/her or licensed to him/her and that he/she has the
149
+ power and authority to grant the Licence.
150
+
151
+ Each time You accept the Licence, the original Licensor and subsequent
152
+ Contributors grant You a licence to their contributions to the Work, under the
153
+ terms of this Licence.
154
+
155
+ 7. Disclaimer of Warranty
156
+
157
+ The Work is a work in progress, which is continuously improved by numerous
158
+ Contributors. It is not a finished work and may therefore contain defects or
159
+ ‘bugs’ inherent to this type of development.
160
+
161
+ For the above reason, the Work is provided under the Licence on an ‘as is’ basis
162
+ and without warranties of any kind concerning the Work, including without
163
+ limitation merchantability, fitness for a particular purpose, absence of defects
164
+ or errors, accuracy, non-infringement of intellectual property rights other than
165
+ copyright as stated in Article 6 of this Licence.
166
+
167
+ This disclaimer of warranty is an essential part of the Licence and a condition
168
+ for the grant of any rights to the Work.
169
+
170
+ 8. Disclaimer of Liability
171
+
172
+ Except in the cases of wilful misconduct or damages directly caused to natural
173
+ persons, the Licensor will in no event be liable for any direct or indirect,
174
+ material or moral, damages of any kind, arising out of the Licence or of the use
175
+ of the Work, including without limitation, damages for loss of goodwill, work
176
+ stoppage, computer failure or malfunction, loss of data or any commercial
177
+ damage, even if the Licensor has been advised of the possibility of such damage.
178
+ However, the Licensor will be liable under statutory product liability laws as
179
+ far such laws apply to the Work.
180
+
181
+ 9. Additional agreements
182
+
183
+ While distributing the Work, You may choose to conclude an additional agreement,
184
+ defining obligations or services consistent with this Licence. However, if
185
+ accepting obligations, You may act only on your own behalf and on your sole
186
+ responsibility, not on behalf of the original Licensor or any other Contributor,
187
+ and only if You agree to indemnify, defend, and hold each Contributor harmless
188
+ for any liability incurred by, or claims asserted against such Contributor by
189
+ the fact You have accepted any warranty or additional liability.
190
+
191
+ 10. Acceptance of the Licence
192
+
193
+ The provisions of this Licence can be accepted by clicking on an icon ‘I agree’
194
+ placed under the bottom of a window displaying the text of this Licence or by
195
+ affirming consent in any other similar way, in accordance with the rules of
196
+ applicable law. Clicking on that icon indicates your clear and irrevocable
197
+ acceptance of this Licence and all of its terms and conditions.
198
+
199
+ Similarly, you irrevocably accept this Licence and all of its terms and
200
+ conditions by exercising any rights granted to You by Article 2 of this Licence,
201
+ such as the use of the Work, the creation by You of a Derivative Work or the
202
+ Distribution or Communication by You of the Work or copies thereof.
203
+
204
+ 11. Information to the public
205
+
206
+ In case of any Distribution or Communication of the Work by means of electronic
207
+ communication by You (for example, by offering to download the Work from a
208
+ remote location) the distribution channel or media (for example, a website) must
209
+ at least provide to the public the information requested by the applicable law
210
+ regarding the Licensor, the Licence and the way it may be accessible, concluded,
211
+ stored and reproduced by the Licensee.
212
+
213
+ 12. Termination of the Licence
214
+
215
+ The Licence and the rights granted hereunder will terminate automatically upon
216
+ any breach by the Licensee of the terms of the Licence.
217
+
218
+ Such a termination will not terminate the licences of any person who has
219
+ received the Work from the Licensee under the Licence, provided such persons
220
+ remain in full compliance with the Licence.
221
+
222
+ 13. Miscellaneous
223
+
224
+ Without prejudice of Article 9 above, the Licence represents the complete
225
+ agreement between the Parties as to the Work.
226
+
227
+ If any provision of the Licence is invalid or unenforceable under applicable
228
+ law, this will not affect the validity or enforceability of the Licence as a
229
+ whole. Such provision will be construed or reformed so as necessary to make it
230
+ valid and enforceable.
231
+
232
+ The European Commission may publish other linguistic versions or new versions of
233
+ this Licence or updated versions of the Appendix, so far this is required and
234
+ reasonable, without reducing the scope of the rights granted by the Licence. New
235
+ versions of the Licence will be published with a unique version number.
236
+
237
+ All linguistic versions of this Licence, approved by the European Commission,
238
+ have identical value. Parties can take advantage of the linguistic version of
239
+ their choice.
240
+
241
+ 14. Jurisdiction
242
+
243
+ Without prejudice to specific agreement between parties,
244
+
245
+ - any litigation resulting from the interpretation of this License, arising
246
+ between the European Union institutions, bodies, offices or agencies, as a
247
+ Licensor, and any Licensee, will be subject to the jurisdiction of the Court
248
+ of Justice of the European Union, as laid down in article 272 of the Treaty on
249
+ the Functioning of the European Union,
250
+
251
+ - any litigation arising between other parties and resulting from the
252
+ interpretation of this License, will be subject to the exclusive jurisdiction
253
+ of the competent court where the Licensor resides or conducts its primary
254
+ business.
255
+
256
+ 15. Applicable Law
257
+
258
+ Without prejudice to specific agreement between parties,
259
+
260
+ - this Licence shall be governed by the law of the European Union Member State
261
+ where the Licensor has his seat, resides or has his registered office,
262
+
263
+ - this licence shall be governed by Belgian law if the Licensor has no seat,
264
+ residence or registered office inside a European Union Member State.
265
+
266
+ Appendix
267
+
268
+ ‘Compatible Licences’ according to Article 5 EUPL are:
269
+
270
+ - GNU General Public License (GPL) v. 2, v. 3
271
+ - GNU Affero General Public License (AGPL) v. 3
272
+ - Open Software License (OSL) v. 2.1, v. 3.0
273
+ - Eclipse Public License (EPL) v. 1.0
274
+ - CeCILL v. 2.0, v. 2.1
275
+ - Mozilla Public Licence (MPL) v. 2
276
+ - GNU Lesser General Public Licence (LGPL) v. 2.1, v. 3
277
+ - Creative Commons Attribution-ShareAlike v. 3.0 Unported (CC BY-SA 3.0) for
278
+ works other than software
279
+ - European Union Public Licence (EUPL) v. 1.1, v. 1.2
280
+ - Québec Free and Open-Source Licence — Reciprocity (LiLiQ-R) or Strong
281
+ Reciprocity (LiLiQ-R+).
282
+
283
+ The European Commission may update this Appendix to later versions of the above
284
+ licences without producing a new version of the EUPL, as long as they provide
285
+ the rights granted in Article 2 of this Licence and protect the covered Source
286
+ Code from exclusive appropriation.
287
+
288
+ All other changes or additions to this Appendix require the production of a new
289
+ EUPL version.
data/README.md ADDED
@@ -0,0 +1,128 @@
1
+ # gubbins-fs
2
+
3
+ Classes for the files and directories of an application. Describe a kind of file once, with the directory it
4
+ lives in, its extension, MIME type and encoding, and get validation, atomic and locked creation, copying and
5
+ moving, and conversions into other formats for it. Ready-made classes cover text, CSV, JSON, images, PDFs and
6
+ ZIP archives.
7
+
8
+ ## Requirements
9
+
10
+ Ruby 3.2 or newer, ActiveSupport 7.0 or newer (up to 8.x), and [gubbins-shell](https://codeberg.org/janfoeh/gubbins-shell),
11
+ which is installed with it. The work on images, PDFs and archives is done by command line programs, which have to
12
+ be installed; see "Programs" below.
13
+
14
+ ## Installation
15
+
16
+ Add to your Gemfile:
17
+
18
+ ```ruby
19
+ gem "gubbins-fs"
20
+ ```
21
+
22
+ or install it directly:
23
+
24
+ ```bash
25
+ $ gem install gubbins-fs
26
+ ```
27
+
28
+ The classes live in the `Fs` namespace; Bundler requires `gubbins/fs`, and `require "fs"` does the same by hand.
29
+
30
+ ## Usage
31
+
32
+ A directory class knows where something is stored. Relative paths are anchored at `Fs::Directory.root_path`,
33
+ which defaults to `/`; set it once for your application:
34
+
35
+ ```ruby
36
+ Fs::Directory.root_path = "/var/app/storage"
37
+
38
+ module Fs
39
+ module Dirs
40
+ class ProjectReports < Fs::Directory
41
+ base_path "project_reports"
42
+ requires_arguments project: "Project"
43
+
44
+ def path
45
+ super / project.id.to_s
46
+ end
47
+ end
48
+ end
49
+ end
50
+
51
+ Fs::Dirs::ProjectReports.base_path # => #<Pathname:/var/app/storage/project_reports>
52
+ Fs::Dirs::ProjectReports.new(project: project).path # => #<Pathname:/var/app/storage/project_reports/15>
53
+ ```
54
+
55
+ A file class knows what a kind of file looks like, and which directory it belongs to:
56
+
57
+ ```ruby
58
+ module Fs
59
+ module Files
60
+ class ProjectReportCsv < Fs::Files::CSV
61
+ directory Fs::Dirs::ProjectReports
62
+ requires_arguments project: "Project"
63
+ end
64
+ end
65
+ end
66
+
67
+ file = Fs::Files::ProjectReportCsv.load(project: project, basename: "report_#{project.id}")
68
+ file.path # => #<Pathname:/var/app/storage/project_reports/15/report_15.csv>
69
+ ```
70
+
71
+ `.load` insists on a valid file that exists: the extension, MIME type and encoding the class declares are checked,
72
+ and a file that does not fit raises an `Errors::Fs::Validation::…` error. `.create`, `.load_or_create`, `.copy_from`
73
+ and `.move_from` bring files into place. There is much more, such as variants (a PNG as a JPG, a PDF as images)
74
+ and the `get_path_from` hook for naming files; the documentation of `Fs::File` has a tutorial.
75
+
76
+ ### File types
77
+
78
+ | Class | For |
79
+ |---|---|
80
+ | `Fs::Files::Text`, `Fs::Files::CSV`, `Fs::Files::JSON` | plain text, CSV and JSON files |
81
+ | `Fs::Files::Image`, with `JPG`, `PNG`, `GIF`, `TIFF` | images: dimensions, OCR, rotating, cropping, deskewing, padding, comparing |
82
+ | `Fs::Files::PDF` | PDFs: page count, text extraction, e-invoice detection, re-encoding |
83
+ | `Fs::Files::PDFCollection` | PDF portfolios, which carry other files inside them |
84
+ | `Fs::Files::Zip` | ZIP archives, which can be unpacked into a temporary directory |
85
+
86
+ Any `Fs::File` can tell its MIME type and encoding, its Base64 content and its SHA-512 digest, and whether it
87
+ passes a ClamAV scan.
88
+
89
+ ### Atomic writes and locks
90
+
91
+ Files are written to a temporary path next to their target and moved into place in one step, so nobody sees a
92
+ half-written file (`Fs::AtomicWrite`). Expensive creation can be serialized with a lock per path
93
+ (`Fs::File.with_creation_lock`). A process which is killed halfway leaves temporary files and lockfiles behind;
94
+ `Fs::TempfileSweeper` and `Fs::LockfileSweeper` clear them away.
95
+
96
+ ### Errors
97
+
98
+ The gem raises `Errors::Fs::…` errors. Their messages are looked up in I18n, under keys such as
99
+ `errors.fs.validation.file_empty`; without a translation, the message is the name of the class. The gem defines
100
+ the `Errors` base class, and the tag modules these errors carry, for itself, and shares them with
101
+ [gubbins-rails](https://codeberg.org/janfoeh/gubbins-rails) where both are loaded.
102
+
103
+ ## Programs
104
+
105
+ The file types call these programs, via gubbins-shell, when you use the corresponding features:
106
+
107
+ | For | Programs |
108
+ |---|---|
109
+ | any file: MIME type and encoding, SHA-512, Base64, virus scan | `file`, `openssl`, `base64`, `clamdscan` |
110
+ | images | ImageMagick (`convert`, `magick`, `identify`), `img2pdf`, `tesseract` |
111
+ | TIFF to PDF | `tiff2pdf` |
112
+ | PDFs | Ghostscript (`gs`), Poppler (`pdfinfo`, `pdftotext`, `pdfimages`, `pdfdetach`) |
113
+ | ZIP archives | `7z`, `zip` |
114
+
115
+ ## Testing
116
+
117
+ `fs/testing` has RSpec mocks for the file and directory classes, such as `Mock::Fs::Files::PDF` or
118
+ `Mock::Fs::Dirs::Directory`. They need `rspec-mocks`, which this gem does not install. Mocks of your own file
119
+ classes inherit from the ones it ships; see the documentation of `Mock::Fs::FileKlassMock`.
120
+
121
+ ## Development
122
+
123
+ After checking out the repo, run `bin/setup` to install dependencies. Then run `bundle exec rake` to run the specs. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
124
+
125
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
126
+
127
+ ## License
128
+ The gem is available as open source under the terms of the [European Union Public Licence v1.2](https://interoperable-europe.ec.europa.eu/sites/default/files/custom-page/attachment/2020-03/EUPL-1.2%20EN.txt).
@@ -0,0 +1,121 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require "tmpdir"
5
+
6
+ module Fs
7
+ # Writes a file so that nobody ever sees it half-written: the content is produced at a
8
+ # temporary path and moved into place in one step.
9
+ #
10
+ # Concurrent writers of the same path each work on a temporary path of their own, and the
11
+ # last one to finish wins. Work that is too expensive to do twice additionally needs
12
+ # serializing, see {Fs::File.with_creation_lock}.
13
+ #
14
+ # The temporary file is named after its target and keeps the target's extension, because
15
+ # tools such as ImageMagick pick the output format from it. It carries {TEMP_MARKER}, which
16
+ # is how leftovers of a killed process are recognized.
17
+ #
18
+ # Where the temporary file lives is up to the caller (see {Fs::File.atomic_write_directory}):
19
+ #
20
+ # * `:alongside` next to the target, hidden by a leading dot
21
+ # * `:system` in the system's temporary directory
22
+ # * an {Fs::Directory} subclass, or its name
23
+ #
24
+ # A rename cannot cross file systems, and copying straight onto the target would not be atomic.
25
+ # If the temporary directory is on another device than the target, the file is therefore copied
26
+ # to a temporary name next to the target first, and that copy is renamed. That is still atomic,
27
+ # just not as cheap as a single rename.
28
+ #
29
+ # @example
30
+ # Fs::AtomicWrite.perform("/some/path/file.txt") do |temp_path|
31
+ # temp_path.write("file content")
32
+ # end
33
+ class AtomicWrite
34
+ # Part of the name of every temporary file
35
+ TEMP_MARKER = "tmp"
36
+
37
+ # What {#temp_filename} produces, eg. `.page.1f3a9c0b7d2e.tmp.jpg`
38
+ TEMP_FILENAME_PATTERN = /\A\..+\.\h{12}\.#{TEMP_MARKER}(\.[^.]+)?\z/
39
+
40
+ # Is this one of our temporary files, as opposed to something which merely looks like one?
41
+ #
42
+ # @param path [Pathname, String]
43
+ # @return [Boolean]
44
+ def self.temp_file?(path)
45
+ TEMP_FILENAME_PATTERN.match?(Pathname.new(path).basename.to_s)
46
+ end
47
+
48
+ # @param path [Pathname, Fs::File, String] where the file is to appear
49
+ # @param directory [Symbol, Class, String] where the temporary file is put, see
50
+ # {Fs::File.atomic_write_directory}
51
+ # @yieldparam temp_path [Pathname]
52
+ # @raise [Errors::Fs::ReadWrite]
53
+ # @return [void]
54
+ def self.perform(path, directory: :alongside, &block)
55
+ new(path, directory: directory).perform(&block)
56
+ end
57
+
58
+ # @param path [Pathname, Fs::File, String]
59
+ # @param directory [Symbol, Class, String]
60
+ def initialize(path, directory: :alongside)
61
+ @path = Fs::File.normalize_path_input(path)
62
+ @directory = directory
63
+ end
64
+
65
+ # Yields the temporary path, then moves what was written there to the target. Nothing is
66
+ # left behind if the block, or the move, fails.
67
+ #
68
+ # @yieldparam temp_path [Pathname]
69
+ # @raise [Errors::Fs::ReadWrite]
70
+ # @return [void]
71
+ def perform
72
+ yield temp_path
73
+
74
+ if same_device?
75
+ ::File.rename(temp_path, path)
76
+
77
+ else
78
+ FileUtils.cp(temp_path, staging_path)
79
+ ::File.rename(staging_path, path)
80
+ end
81
+
82
+ rescue IOError, EOFError, SystemCallError
83
+ Errors::Fs::ReadWrite.raise(label: path.to_s)
84
+
85
+ ensure
86
+ [@temp_path, @staging_path].compact
87
+ .each do |leftover|
88
+ FileUtils.rm_f(leftover)
89
+ end
90
+ end
91
+
92
+ private
93
+
94
+ # @return [Pathname]
95
+ attr_reader :path
96
+ # @return [Symbol, Class, String]
97
+ attr_reader :directory
98
+
99
+ # @return [Pathname]
100
+ def temp_path
101
+ @temp_path ||= Fs::File.resolve_temp_directory(directory, alongside: path.dirname) / temp_filename
102
+ end
103
+
104
+ # Only exists if the temporary directory is on another device
105
+ #
106
+ # @return [Pathname]
107
+ def staging_path
108
+ @staging_path ||= path.dirname / temp_filename
109
+ end
110
+
111
+ # @return [String]
112
+ def temp_filename
113
+ ".#{path.basename(path.extname)}.#{SecureRandom.hex(6)}.#{TEMP_MARKER}#{path.extname}"
114
+ end
115
+
116
+ # @return [Boolean]
117
+ def same_device?
118
+ temp_path.dirname == path.dirname || temp_path.dirname.stat.dev == path.dirname.stat.dev
119
+ end
120
+ end
121
+ end
@@ -0,0 +1,140 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/concern"
5
+ require "active_support/core_ext/array/conversions"
6
+ require "active_support/core_ext/object/inclusion"
7
+
8
+ module Fs
9
+ module Concerns
10
+ # Helper methods for performing type checks on arguments
11
+ #
12
+ # All helpers are available as both private class and instance methods.
13
+ module ArgumentValidation
14
+ extend ActiveSupport::Concern
15
+
16
+ included do
17
+ # Ensure parameters are of type or types
18
+ #
19
+ # @example
20
+ # def self.foo(x, y)
21
+ # ensure_type x => String,
22
+ # y => [Boolean, NilClass]
23
+ # end
24
+ #
25
+ # def foo(z)
26
+ # ensure_type z => Integer
27
+ # end
28
+ #
29
+ # @param **kargs [Hash{Object=>Class,Array[Class]}]
30
+ # @raise [ArgumentError] on mismatch
31
+ private_class_method def self.ensure_type(**kargs)
32
+ kargs.each do |argument, klasses|
33
+ klasses = [*klasses]
34
+
35
+ unless klasses.any? { |klass| argument.is_a?(klass) }
36
+ raise ArgumentError, "expected #{argument.inspect} to be "\
37
+ "#{klasses.map(&:name).join(', ')}, "\
38
+ "got #{argument.class.name}"
39
+ end
40
+ end
41
+ end
42
+ # Yes, there is some amount of fuckery going on with here,
43
+ # but I found that to be necessary to have
44
+ #
45
+ # 1. private class and instance methods,
46
+ # 2. which are not simply duplicated,
47
+ # 3. which can also be used within other Concerns
48
+ private define_method :ensure_type, &method(:ensure_type)
49
+
50
+ # Ensure parameters are an Array of type or types
51
+ #
52
+ # @example
53
+ # def self.foo(x, y)
54
+ # ensure_array_of_type x => String,
55
+ # y => [Boolean, NilClass]
56
+ # end
57
+ #
58
+ # def foo(z)
59
+ # ensure_array_of_type z => Integer
60
+ # end
61
+ #
62
+ # @param **kargs [Hash{Object=>Class,Array[Class]}]
63
+ # @raise [ArgumentError] on mismatch
64
+ private_class_method def self.ensure_array_of_type(**kargs)
65
+ kargs.each do |argument, klasses|
66
+ klasses = [*klasses]
67
+
68
+ unless argument.is_a?(Array)
69
+ raise ArgumentError, "expected #{argument.inspect} to be "\
70
+ "an Array, got #{argument.class.name}"
71
+ end
72
+
73
+ unless argument.all? { |item| klasses.any? { |klass| item.is_a?(klass) } }
74
+ raise ArgumentError, "expected #{argument.inspect} to all be "\
75
+ "#{klasses.map(&:name).join(', ')}, "\
76
+ "got #{argument.map { |item| item.class.name }.uniq}"
77
+ end
78
+ end
79
+ end
80
+ private define_method :ensure_array_of_type, &method(:ensure_array_of_type)
81
+
82
+ # Ensure parameters are a `Range` of type or types
83
+ #
84
+ # @example
85
+ # def self.foo(x, y)
86
+ # ensure_range_of_type x => String,
87
+ # y => [Boolean, NilClass]
88
+ # end
89
+ #
90
+ # def foo(z)
91
+ # ensure_range_of_type z => Integer
92
+ # end
93
+ #
94
+ # @param **kargs [Hash{Object=>Class,Array[Class]}]
95
+ # @raise [ArgumentError] on mismatch
96
+ private_class_method def self.ensure_range_of_type(**kargs)
97
+ kargs.each do |argument, klasses|
98
+ klasses = [*klasses]
99
+
100
+ unless argument.is_a?(Range)
101
+ raise ArgumentError, "expected #{argument.inspect} to be "\
102
+ "a Range, got #{argument.class.name}"
103
+ end
104
+
105
+ unless klasses.any? { |klass| argument.begin.is_a?(klass) }
106
+ raise ArgumentError, "expected #{argument.inspect} to be a Range of "\
107
+ "#{klasses.map(&:name).join(', ')}, "\
108
+ "got #{argument.begin.class.name}"
109
+ end
110
+ end
111
+ end
112
+ private define_method :ensure_range_of_type, &method(:ensure_range_of_type)
113
+
114
+ # Ensure parameters are one of the given values
115
+ #
116
+ # @example
117
+ # def self.foo(x, y)
118
+ # ensure_value_is_one_of x => %i(foo bar baz),
119
+ # y => 1
120
+ # end
121
+ #
122
+ # def foo(z)
123
+ # ensure_value_is_one_of z => 1..100
124
+ # end
125
+ #
126
+ # @param **kargs [Hash{Object=>Class,Array[Class]}]
127
+ # @raise [ArgumentError] on mismatch
128
+ private_class_method def self.ensure_value_is_one_of(**kargs)
129
+ kargs.each do |value, allowed_values|
130
+ unless value.in?(allowed_values)
131
+ raise ArgumentError, "value '#{value}' is not supported, "\
132
+ "allowed are #{allowed_values.to_sentence}"
133
+ end
134
+ end
135
+ end
136
+ private define_method :ensure_value_is_one_of, &method(:ensure_value_is_one_of)
137
+ end
138
+ end
139
+ end
140
+ end