Skip to content

Commit cefdc59

Browse files
committed
fix shfmt formatter and add support for custom command
1 parent c870e6c commit cefdc59

File tree

2 files changed

+16
-15
lines changed

2 files changed

+16
-15
lines changed

lib/bashly/libraries/settings/settings.yml

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -52,11 +52,12 @@ strict: false
5252
tab_indent: false
5353

5454
# Choose a post-processor for the generated script:
55-
# formatter: internal # Use Bashly's internal formatter (compacts newlines)
56-
# formatter: none # Disable all post-processing
57-
# formatter: shfmt # Use shfmt if installed
58-
formatter: internal
59-
55+
# formatter: :internal # Use Bashly's internal formatter (compacts newlines)
56+
# formatter: :none # Disable all post-processing
57+
# formatter: :shfmt # Use shfmt if installed
58+
# formatter: shfmt -mn # Use any other string, assuming the command accepts
59+
# # the script as stdin and outputs it to stdout
60+
formatter: :internal
6061

6162
#-------------------------------------------------------------------------------
6263
# INTERFACE OPTIONS

lib/bashly/script/formatter.rb

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
require 'open3'
2+
require 'shellwords'
23

34
module Bashly
45
module Script
@@ -9,29 +10,28 @@ class Formatter
910

1011
def initialize(script, mode: nil)
1112
@script = script
12-
@mode = MODES.include?(mode&.to_sym) ? mode.to_sym : MODES.first
13+
@mode = mode
1314
end
1415

1516
def formatted_script
1617
case mode
1718
when :internal then script.gsub(/\s+\n/m, "\n\n")
1819
when :shfmt then shfmt_result
19-
else script
20+
when :none then script
21+
else custom_formatter_result mode
2022
end
2123
end
2224

2325
private
2426

2527
def shfmt_result
26-
unless system 'command -v shfmt > /dev/null 2>&1'
27-
raise DependencyError,
28-
'Cannot find g`shfmt`.\nEither install it or change to the g`internal` formatter.'
29-
end
30-
31-
output, error, status =
32-
Open3.capture3 %w[shfmt --case-indent --indent 2], stdin_data: script
28+
custom_formatter_result %w[shfmt --case-indent --indent 2]
29+
end
3330

34-
raise DependencyError, "Failed running g`shfmt`:\n\n#{error}" unless status.success?
31+
def custom_formatter_result(command)
32+
command = Shellwords.split command if command.is_a? String
33+
output, error, status = Open3.capture3 *command, stdin_data: script
34+
raise DependencyError, "Failed running g`#{command}`:\n\n#{error}" unless status.success?
3535

3636
output
3737
end

0 commit comments

Comments
 (0)