gubbins-shell 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 (49) hide show
  1. checksums.yaml +7 -0
  2. data/CHANGELOG.md +19 -0
  3. data/LICENSE +289 -0
  4. data/README.md +186 -0
  5. data/lib/gubbins/shell.rb +4 -0
  6. data/lib/shell/all.rb +34 -0
  7. data/lib/shell/base_64.rb +40 -0
  8. data/lib/shell/clam_av.rb +68 -0
  9. data/lib/shell/command.rb +1400 -0
  10. data/lib/shell/convert.rb +312 -0
  11. data/lib/shell/errors.rb +89 -0
  12. data/lib/shell/exiftool.rb +15 -0
  13. data/lib/shell/file.rb +84 -0
  14. data/lib/shell/ghostscript.rb +239 -0
  15. data/lib/shell/identify.rb +111 -0
  16. data/lib/shell/img2_pdf.rb +47 -0
  17. data/lib/shell/magick.rb +111 -0
  18. data/lib/shell/open_ssl.rb +26 -0
  19. data/lib/shell/optional_dependencies.rb +36 -0
  20. data/lib/shell/path.rb +40 -0
  21. data/lib/shell/pdf_detach.rb +86 -0
  22. data/lib/shell/pdffonts.rb +73 -0
  23. data/lib/shell/pdfimages.rb +48 -0
  24. data/lib/shell/pdfinfo.rb +79 -0
  25. data/lib/shell/pdftocairo.rb +24 -0
  26. data/lib/shell/pdftotext.rb +32 -0
  27. data/lib/shell/ping.rb +50 -0
  28. data/lib/shell/power_array.rb +42 -0
  29. data/lib/shell/seven_zip.rb +142 -0
  30. data/lib/shell/tesseract.rb +120 -0
  31. data/lib/shell/testing/mock/shell/clam_av.rb +12 -0
  32. data/lib/shell/testing/mock/shell/command.rb +241 -0
  33. data/lib/shell/testing/mock/shell/configurator.rb +223 -0
  34. data/lib/shell/testing/mock/shell/convert.rb +12 -0
  35. data/lib/shell/testing/mock/shell/file.rb +12 -0
  36. data/lib/shell/testing/mock/shell/ghostscript.rb +13 -0
  37. data/lib/shell/testing/mock/shell/identify.rb +11 -0
  38. data/lib/shell/testing/mock/shell/open_ssl.rb +11 -0
  39. data/lib/shell/testing/mock/shell/tesseract.rb +12 -0
  40. data/lib/shell/testing/mock/shell/unzip.rb +20 -0
  41. data/lib/shell/testing/mock/shell/zip.rb +11 -0
  42. data/lib/shell/testing.rb +15 -0
  43. data/lib/shell/tiff_2_pdf.rb +19 -0
  44. data/lib/shell/unzip.rb +137 -0
  45. data/lib/shell/version.rb +5 -0
  46. data/lib/shell/zbar.rb +123 -0
  47. data/lib/shell/zip.rb +52 -0
  48. data/lib/shell.rb +16 -0
  49. metadata +116 -0
@@ -0,0 +1,239 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/core_ext/enumerable"
5
+ require_relative "../shell"
6
+
7
+ module Shell
8
+ class Ghostscript < Command
9
+ command_path `which gs`
10
+ option_prefix "-"
11
+
12
+ transform_options input: :f,
13
+ output: :o,
14
+ device: "-sDEVICE=#VALUE#",
15
+ batch: :dBATCH,
16
+ first_page: "-dFirstPage=#VALUE#",
17
+ last_page: "-dLastPage=#VALUE#",
18
+ resolution: "-r#VALUE#"
19
+
20
+ FORMAT_DEVICES = {
21
+ jpg: { color: :jpeg, gray: :jpeggray }.freeze,
22
+ pdf: { color: :pdfwrite }.freeze,
23
+ png: { color: :png16m, gray: :pnggray }.freeze,
24
+ tiff: { color: :tiff24nc, gray: :tiffgray }.freeze
25
+ }.freeze
26
+
27
+ # The default user space unit is 1/72 inch, as per the PDF/PostScript specs.
28
+ # It is also what `pdfinfo` reports page sizes in ("pts").
29
+ POINTS_PER_INCH = 72
30
+
31
+ # What Ghostscript 9.x reports when it gives up on a page partway through
32
+ # and renders only the part it got to. It still exits with status 0 then.
33
+ INCOMPLETE_PAGE_PATTERN = /Error reading a content stream|File did not complete the page properly/
34
+
35
+ # Convert a single page of an input PDF to JPEG, PNG or TIFF
36
+ #
37
+ # @param input [String, #to_s, #path] path to the input PDF
38
+ # @param output [String, #to_s, #path] path template for the output files
39
+ # @param page [Integer] the index of the page to convert
40
+ # @param format [:jpg, :png, :tiff]
41
+ # @param colorspace [:color, :gray]
42
+ # @param resolution [Integer, String] resolution in DPI, or "<xres>x<yres>"
43
+ # @param max_pixels [Integer, nil] lowers an Integer `resolution` as far as needed for
44
+ # the page to stay within this pixel area; see {.resolutions_within}
45
+ # @param device [String] a Ghostscript output device:
46
+ # https://ghostscript.com/docs/9.54.0/Devices.htm
47
+ # @raise [Shell::Errors::CommandUnsuccessful] via `Result#raise_failures`,
48
+ # if Ghostscript could only render part of the page
49
+ # @return [Shell::Command::Result]
50
+ def self.pdf_to_image(input:, output:, page: 1, format: :jpg, colorspace: :color, resolution: 150,
51
+ max_pixels: nil, device: nil)
52
+ device ||= device_code_for(format, colorspace)
53
+
54
+ if max_pixels
55
+ resolution = resolutions_within(input: input, resolution: resolution, max_pixels: max_pixels, page: page)
56
+ .sole
57
+ end
58
+
59
+ exec(input, resolution: resolution, output: output,
60
+ device: device, first_page: page, last_page: page)
61
+ .post_process { |result| ensure_complete_pages(result) }
62
+ end
63
+
64
+ # Extract one or more pages from a PDF into a new PDF
65
+ #
66
+ # @param input [String, #to_s, #path] path to the input PDF
67
+ # @param output [String, #to_s, #path] path for the output file
68
+ # @param page [Integer] the index of the page to extract
69
+ # @param first_page [Integer] the index of the first page to extract
70
+ # when extracting a range of pages
71
+ # @param last_page [Integer] the index of the last page to extract
72
+ # when extracting a range of pages
73
+ # @param format [:jpg, :png, :tiff]
74
+ # @param colorspace [:color, :gray]
75
+ # @param resolution [Integer, String] resolution in DPI, or "<xres>x<yres>"
76
+ # @param device [String] a Ghostscript output device:
77
+ # https://ghostscript.com/docs/9.54.0/Devices.htm
78
+ # @return [Shell::Command::Result]
79
+ def self.extract_pdf(input:, output: nil, page: nil, first_page: nil, last_page: nil, resolution: 150, device: nil)
80
+ first_page = last_page = page if page
81
+ device ||= device_code_for(:pdf, :color)
82
+
83
+ raise ArgumentError, "neither page nor first_page and last_page given" unless first_page && last_page
84
+
85
+ exec(input, resolution: resolution, output: output,
86
+ device: device, first_page: first_page, last_page: last_page)
87
+ end
88
+
89
+ # Extract one or more pages from a PDF into a new PDF
90
+ #
91
+ # @param input [String, #to_s, #path] path to the input PDF
92
+ # @param output [String, #to_s, #path] path for the output file
93
+ # @param colorspace [:color, :gray]
94
+ # @param resolution [Integer, String] resolution in DPI, or "<xres>x<yres>"
95
+ # @param device [String] a Ghostscript output device:
96
+ # https://ghostscript.com/docs/9.54.0/Devices.htm
97
+ # @return [Shell::Command::Result]
98
+ def self.regenerate(input:, output: nil, resolution: 300, colorspace: :color, device: nil)
99
+ device ||= device_code_for(:pdf, colorspace)
100
+
101
+ exec(input, resolution: resolution, output: output, device: device)
102
+ end
103
+
104
+ # Convert a multiple or all pages of an input PDF to JPEG, PNG or TIFF
105
+ #
106
+ # If your given output path does not already contain the "%d" counter placeholder, one will be
107
+ # inserted between filename and file extension.
108
+ #
109
+ # @param input [String, #to_s, #path] path to the input PDF
110
+ # @param output [String, #to_s, #path] path template for the output files. Note that "-%d"
111
+ # will be inserted between the basename and the file extension if "%d" is not already present
112
+ # @param first_page [Integer] the begin of the page range to convert; first page if nil
113
+ # @param last_page [Integer] the end of the page range to convert; last page if nil
114
+ # @param format [:jpg, :png, :tiff]
115
+ # @param colorspace [:color, :gray]
116
+ # @param resolution [Integer, String] resolution in DPI, or "<xres>x<yres>"
117
+ # @param device [String] a Ghostscript output device:
118
+ # https://ghostscript.com/docs/9.54.0/Devices.htm
119
+ # @raise [Shell::Errors::CommandUnsuccessful] via `Result#raise_failures`,
120
+ # if Ghostscript could only render part of a page
121
+ # @return [Shell::Command::Result]
122
+ def self.pdf_to_images(input:, output:, format: :jpg, colorspace: :color, resolution: 150, first_page: nil,
123
+ last_page: nil, device: nil)
124
+ device ||= device_code_for(format, colorspace)
125
+
126
+ output =
127
+ output.respond_to?(:path) ? output.path : Pathname.new(output.to_s)
128
+
129
+ unless output.to_s.include?("%d")
130
+ output =
131
+ output.dirname + "#{output.basename('.*')}-%d#{output.extname}"
132
+ end
133
+
134
+ kargs = {
135
+ resolution: resolution,
136
+ output: output,
137
+ device: device,
138
+ first_page: first_page,
139
+ last_page: last_page
140
+ }
141
+
142
+ kargs.delete(:first_page) if first_page.nil?
143
+ kargs.delete(:last_page) if last_page.nil?
144
+
145
+ exec(input, **kargs)
146
+ .post_process { |result| ensure_complete_pages(result) }
147
+ end
148
+
149
+ # Checks whether Ghostscript's PDF interpreter considers `input` to be well-formed
150
+ #
151
+ # Runs a lightweight dry run using the `nullpage` output device, which exercises
152
+ # the full PDF interpreter without producing any raster output.
153
+ #
154
+ # @param input [String, #to_s, #path] path to the input PDF
155
+ # @return [Shell::Command::Result]
156
+ # `Result#value` [Boolean]
157
+ def self.well_formed?(input)
158
+ exec(input, :dNOPAUSE, :dBATCH, device: "nullpage").tap do |result|
159
+ result.value = result.stderr.empty?
160
+ end
161
+ end
162
+
163
+ # The resolution at which each page of `input` renders to at most `max_pixels`
164
+ #
165
+ # Pages which fit at `resolution` keep it; larger ones (posters, scans embedded at
166
+ # 72 dpi with a huge page size) are rendered at a lower resolution, as Ghostscript
167
+ # would otherwise happily produce images that no image tool can open.
168
+ #
169
+ # @param input [Pathname, String, Fs::File]
170
+ # @param resolution [Integer] the desired resolution in DPI
171
+ # @param max_pixels [Integer] the maximum pixel area of a rendered page
172
+ # @param page [Integer, nil] only consider this page (1-based); all pages if nil
173
+ # @return [Array<Integer>] one resolution in DPI per page, in page order
174
+ def self.resolutions_within(input:, resolution:, max_pixels:, page: nil)
175
+ Shell::Pdfinfo.page_sizes(input, page: page).raise_failures.value.map do |width, height|
176
+ [resolution, highest_resolution_within(max_pixels, width: width, height: height)].min
177
+ end
178
+ end
179
+
180
+ # The highest resolution at which a page of the given size renders to at most `max_pixels`
181
+ #
182
+ # A page of `width` x `height` points rendered at `dpi` is
183
+ #
184
+ # (width / 72 * dpi) x (height / 72 * dpi) pixels
185
+ #
186
+ # in size, so its pixel area is `width * height * dpi**2 / 72**2`.
187
+ # Solving "area <= max_pixels" for `dpi` yields what we calculate here.
188
+ #
189
+ # @param max_pixels [Integer]
190
+ # @param width [Float] page width in points
191
+ # @param height [Float] page height in points
192
+ # @return [Integer, Float] DPI; infinite for a page without area (degenerate
193
+ # MediaBoxes of size 0 exist in the wild), as there is nothing to limit then
194
+ def self.highest_resolution_within(max_pixels, width:, height:)
195
+ area_in_points = width * height
196
+
197
+ return Float::INFINITY if area_in_points <= 0
198
+
199
+ area_in_square_inches = area_in_points / POINTS_PER_INCH**2.0
200
+ dpi = Math.sqrt(max_pixels / area_in_square_inches)
201
+
202
+ dpi.floor
203
+ end
204
+ private_class_method :highest_resolution_within
205
+
206
+ # Fails `result` if Ghostscript reports having rendered a page only partially
207
+ #
208
+ # Ghostscript 9.x exits with status 0 in that case, leaving a truncated image behind.
209
+ # 9.53.3 reports it on STDOUT, not STDERR, so we look at both. Either may contain
210
+ # invalid UTF-8, as Ghostscript's reports name the PDF's producer, which we don't control.
211
+ #
212
+ # @param result [Shell::Command::Result]
213
+ # @raise [RuntimeError]
214
+ # @return [void]
215
+ def self.ensure_complete_pages(result)
216
+ complaint = "#{result.stdout}#{result.stderr}".scrub[INCOMPLETE_PAGE_PATTERN]
217
+
218
+ return unless complaint
219
+
220
+ raise "Ghostscript rendered a page incompletely: #{complaint}"
221
+ end
222
+ private_class_method :ensure_complete_pages
223
+
224
+ # Returns the Ghostscript device code for a given combination of format and colorspace
225
+ #
226
+ # @param format [Symbol]
227
+ # @param colorspace [Symbol]
228
+ # @raise [ArgumentError] if the combination is unsupported
229
+ # @return [Symbol]
230
+ def self.device_code_for(format, colorspace)
231
+ device = FORMAT_DEVICES[format][colorspace]
232
+
233
+ raise ArgumentError, "unsupported format #{format} in colorspace #{colorspace}" unless device
234
+
235
+ device
236
+ end
237
+ private_class_method :device_code_for
238
+ end
239
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/core_ext/string/inflections"
5
+ require_relative "../shell"
6
+
7
+ module Shell
8
+ class Identify < Command
9
+ command_path `which identify`
10
+ option_prefix "-"
11
+
12
+ # Runs `identify` on `filename` and returns output
13
+ # as a nested Hash
14
+ #
15
+ # @param filename [Pathname, String]
16
+ # @return [Shell::Command::Result]
17
+ def self.info(filename, *args, **kargs)
18
+ exec(filename, :verbose, *args, **kargs).on_success do |result|
19
+ result.value =
20
+ parse(result.stdout.lines.map(&:chomp))
21
+ end
22
+ end
23
+
24
+ # Returns an images dimensions and area
25
+ #
26
+ # @param filename [Pathname, String]
27
+ # @return [Shell::Command::Result]
28
+ # `Result#value` [Struct] a Struct with `:x`, `:y` and `:area` attributes
29
+ def self.dimensions(filename, *args, **kargs)
30
+ exec(filename, :ping, *args, format: "%[width]x%[height]", **kargs).on_success do |result|
31
+ x, y = *result.stdout
32
+ .split("x")
33
+ .map(&:to_i)
34
+ area = x * y
35
+
36
+ result.value =
37
+ Struct.new(:x, :y, :area).new(x, y, area)
38
+ end
39
+ end
40
+
41
+ # Count the number of images contained in `filename`
42
+ #
43
+ # This of course only makes sense for formats like TIFF
44
+ # or GIF.
45
+ #
46
+ # @param filename [Pathname, String]
47
+ # @return [Shell::Command::Result]
48
+ # `Result#value` [Integer]
49
+ def self.image_count(filename)
50
+ exec(filename).on_success do |result|
51
+ result.value =
52
+ result.stdout.lines.count
53
+ end
54
+ end
55
+
56
+ # Is `filename` a valid image according to `identify`?
57
+ #
58
+ # @param filename [String, #to_s, #path]
59
+ # @return [Boolean]
60
+ def self.valid?(filename)
61
+ exec(filename).success?
62
+ end
63
+
64
+ # Recursively parses `identify` output into a Hash
65
+ #
66
+ # @param output [Array<String>]
67
+ # @return [Hash]
68
+ def self.parse(output)
69
+ result = {}
70
+ indent_level = indent_level_for(output.first)
71
+ idx = 0
72
+
73
+ while line = output.at(idx)
74
+ key, value =
75
+ *line.split(":")
76
+
77
+ subtree = []
78
+ next_idx = idx.succ
79
+
80
+ while (next_line = output.at(next_idx)) && indent_level_for(next_line) > indent_level
81
+ subtree << next_line
82
+ next_idx += 1
83
+ end
84
+
85
+ if subtree.any?
86
+ value = parse(subtree)
87
+ idx = next_idx
88
+ else
89
+ value = value&.strip
90
+ idx += 1
91
+ end
92
+
93
+ result[key.parameterize.underscore.to_sym] = value
94
+ end
95
+
96
+ result
97
+ end
98
+ private_class_method :parse
99
+
100
+ # Detects a lines indentation level by counting leading spaces
101
+ #
102
+ # @param line [String, nil]
103
+ # @return [Integer, nil]
104
+ def self.indent_level_for(line)
105
+ return nil unless line.is_a?(String)
106
+
107
+ line.size - line.lstrip.size
108
+ end
109
+ private_class_method :indent_level_for
110
+ end
111
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../shell"
4
+
5
+ module Shell
6
+ class Img2PDF < Command
7
+ command_path `which img2pdf`
8
+ positional_parameters :first
9
+ transform_options output: :o
10
+
11
+ # Convert one or multiple images into one PDF
12
+ #
13
+ # @param input [Pathname, Fs::File, String, Array<Pathname, Fs::File, String>] one or multiple image paths
14
+ # @param output [Pathname, Fs::File, String] where to write the output to
15
+ # @param pagesize [String] available options:
16
+ # A0 841mmx1189mm
17
+ # A1 594mmx841mm
18
+ # A2 420mmx594mm
19
+ # A3 297mmx420mm
20
+ # A4 210mmx297mm
21
+ # A5 148mmx210mm
22
+ # A6 105mmx148mm
23
+ # B0 1000mmx1414mm
24
+ # B1 707mmx1000mm
25
+ # B2 500mmx707mm
26
+ # B3 353mmx500mm
27
+ # B4 250mmx353mm
28
+ # B5 176mmx250mm
29
+ # B6 125mmx176mm
30
+ # JB0 1030mmx1456mm
31
+ # JB1 728mmx1030mm
32
+ # JB2 515mmx728mm
33
+ # JB3 364mmx515mm
34
+ # JB4 257mmx364mm
35
+ # JB5 182mmx257mm
36
+ # JB6 128mmx182mm
37
+ # Legal 8.5inx14in
38
+ # Letter 8.5inx11in
39
+ # Tabloid 11inx17in
40
+ #
41
+ # Append `^T` to your chosen format for landscape, ie. `A4^T`
42
+ def self.convert(input:, output:, pagesize: "A4", **kargs)
43
+ kargs = kargs.merge(pagesize: pagesize) if pagesize
44
+ exec(*[*input], output: output, **kargs)
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support"
4
+ require "active_support/core_ext/object/blank"
5
+ require_relative "../shell"
6
+
7
+ module Shell
8
+ class Magick < Command
9
+ command_path `which magick`
10
+ option_prefix "-"
11
+ transform_options compare: "compare"
12
+
13
+ # Perform a Structural similarity Index comparison between
14
+ # `input_a` and `input_b`
15
+ #
16
+ # @param input_a [Pathname, Fs::File, String]
17
+ # @param input_b [Pathname, Fs::File, String]
18
+ # @param metric [String] default: `SSIM`. One of
19
+ # * `AE` - absolute error count, number of different pixels (-fuzz affected)
20
+ # * `DSSIM` - structural dissimilarity index
21
+ # * `FUZZ` - mean color distance
22
+ # * `MAE` - mean absolute error (normalized), average channel error distance
23
+ # * `MEPP` - mean error per pixel (normalized mean error, normalized peak error)
24
+ # * `MSE` - mean error squared, average of the channel error squared
25
+ # * `NCC` - normalized cross correlation
26
+ # * `PAE` - peak absolute (normalized peak absolute)
27
+ # * `PHASH` - perceptual hash for the sRGB and HCLp colorspaces. Specify an alternative colorspace with -define phash:colorspaces=colorspace,colorspace,...
28
+ # * `PSNR` - peak signal to noise ratio
29
+ # * `RMSE` - root mean squared (normalized root mean squared)
30
+ # * `SSIM` - structural similarity index
31
+ # @return [Shell::Command::Result]
32
+ # `Result#value` [Float]
33
+ def self.compare(input_a, input_b, metric: "SSIM")
34
+ exec(:compare, metric: metric, output: [input_a, input_b, "null:"]).consider_successful(1).on_success do |result|
35
+ result.value =
36
+ (result.stdout.presence || result.stderr).to_f
37
+ .then do |value|
38
+ (value * 100).round(1)
39
+ end
40
+ end
41
+ end
42
+
43
+ # Crop `input` to `percentage` top part
44
+ #
45
+ # @param input [Pathname, Fs::File, String]
46
+ # @param output [Pathname, Fs::File, String]
47
+ # @param percentage [Integer] 0-100
48
+ # @return [Shell::Command::Result]
49
+ def self.top(input:, output:, percentage:)
50
+ exec(input: input, gravity: "North", crop: "x#{percentage}%+0+0", output: output)
51
+ end
52
+
53
+ # Crop `input` to `percentage` bottom part
54
+ #
55
+ # @param input [Pathname, Fs::File, String]
56
+ # @param output [Pathname, Fs::File, String]
57
+ # @param percentage [Integer] 0-100
58
+ # @return [Shell::Command::Result]
59
+ def self.bottom(input:, output:, percentage:)
60
+ exec(input: input, gravity: "South", crop: "x#{percentage}%+0+0", output: output)
61
+ end
62
+
63
+ # Blank out the entire document in white, except for the
64
+ # `top` and `bottom` percentages
65
+ #
66
+ # @param input [Pathname, Fs::File, String]
67
+ # @param output [Pathname, Fs::File, String]
68
+ # @param top [Integer] 0-100
69
+ # @param bottom [Integer] 0-100
70
+ # @return [Shell::Command::Result]
71
+ def blank_center(input:, output:, top: 15, bottom: 10)
72
+ exec(input: input, fill: "white", draw: "\"rectangle 0,%[fx:int(h*0.#{top})] %[w],%[fx:int(h*0.#{100 - bottom})]\"", output: output)
73
+ end
74
+
75
+ private
76
+
77
+ # ImageMagick uses a more peculiar argument format in the form of
78
+ # `convert input_file <options> output_file`, so we overload the
79
+ # command builder to automatically put the `:input` karg in front
80
+ # and append the `:output` karg at the end.
81
+ #
82
+ # TODO enable a more elegant approach to complex custom argument
83
+ # ordering somehow.
84
+ def build_command_arguments(*args, **kargs)
85
+ _positional_args, options =
86
+ preprocess_arguments(args, kargs)
87
+
88
+ input, output = nil
89
+
90
+ options.delete_if do |elem|
91
+ case elem.first
92
+ when :input
93
+ input = elem.last.respond_to?(:path) ? elem.last.path.to_s : elem.last.to_s
94
+ when :output
95
+ output = [*elem.last].map do |value|
96
+ value.respond_to?(:path) ? value.path.to_s : value.to_s
97
+ end
98
+ else
99
+ next false
100
+ end
101
+ end
102
+
103
+ command_arguments = stringify_options(options)
104
+
105
+ command_arguments.prepend(input) if input
106
+ command_arguments.concat(output) if output
107
+
108
+ command_arguments
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,26 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../shell"
4
+
5
+ module Shell
6
+ # Interface for `unzip` and `7z` (7z preferred if available)
7
+ class OpenSsl < Command
8
+ command_path `which openssl`
9
+ option_prefix "-"
10
+ transform_options digest: "dgst"
11
+
12
+ # Returns the SHA512 hash for `input` in hex
13
+ #
14
+ # @param input [Pathname, Fs::File, String]
15
+ # @return [Shell::Command::Result]
16
+ # `Result#value` [String]
17
+ def self.sha512_hexdigest(input)
18
+ exec(input, :digest, :sha512, :hex).on_success do |result|
19
+ result.value =
20
+ result.stdout
21
+ .split
22
+ .last
23
+ end
24
+ end
25
+ end
26
+ end
@@ -0,0 +1,36 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shell
4
+ # Lets a wrapper ask for a gem which gubbins-shell does not depend on itself
5
+ #
6
+ # See "Optional dependencies" in the README.
7
+ module OptionalDependencies
8
+ private
9
+
10
+ # Requires `feature`, or explains which gem is missing
11
+ #
12
+ # Call it from a class method, before anything else the method does, and not inside
13
+ # `Result#post_process`, which would turn the missing gem into a failed Result: it is a
14
+ # problem with the installation, not with the input. The error names that class method.
15
+ #
16
+ # @param feature [String] what to `require`
17
+ # @param gem_name [String] the gem providing it, if it is not named like `feature`
18
+ # @raise [Shell::Errors::DependencyMissing]
19
+ # @return [void]
20
+ def require_optional(feature, gem_name: feature)
21
+ require feature
22
+ rescue LoadError
23
+ raise Shell::Errors::DependencyMissing.new(gem_name: gem_name, needed_by: calling_method_description)
24
+ end
25
+
26
+ # The first frame outside this file, as counting frames would be thrown off by the
27
+ # `rescue` clause being one of its own
28
+ #
29
+ # @return [String] eg. `"Shell::Zbar.scan"`, for the method which called {#require_optional}
30
+ def calling_method_description
31
+ caller = caller_locations.find { |location| location.path != __FILE__ }
32
+
33
+ "#{name}.#{caller.base_label}"
34
+ end
35
+ end
36
+ end
data/lib/shell/path.rb ADDED
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Shell
4
+ module Path
5
+ # Convert `input` into a {Pathname}
6
+ #
7
+ # @param input [String, Pathname, #to_path, nil] anything responding to `#to_path` will do,
8
+ # such as an `Fs::File`
9
+ # @raise [ArgumentError] if input is not supported
10
+ # @return [Pathname]
11
+ def self.convert(input)
12
+ case input
13
+ when Pathname, nil
14
+ input
15
+ when String
16
+ Pathname.new(input)
17
+ else
18
+ raise ArgumentError, "cannot convert #{input} (#{input.class}) to Pathname" unless input.respond_to?(:to_path)
19
+
20
+ Pathname.new(input.to_path)
21
+ end
22
+ end
23
+
24
+ # Returns a new {Pathname} with the file extension changed to `:with`
25
+ #
26
+ # @param input [String, Pathname, Fs::File]
27
+ # @param with [String, Symbol, nil] the new file extension
28
+ # @raise [ArgumentError] if input is not supported or `nil`
29
+ # @return [Pathname]
30
+ def self.replace_extname(input, with:)
31
+ raise ArgumentError, "file path expected as input" if input.nil?
32
+
33
+ input = convert(input)
34
+ filename =
35
+ with.nil? ? input.basename(".*") : "#{input.basename('.*')}.#{with.to_s.delete('.')}"
36
+
37
+ ::File.join(input.dirname, filename)
38
+ end
39
+ end
40
+ end