Last active
February 9, 2019 16:52
-
-
Save AliSoftware/b36b4ff089929f340ffdc458b9cccf4a to your computer and use it in GitHub Desktop.
Runs SwiftLint on all code snippets found in a markdown file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
require 'tmpdir' | |
require 'open3' | |
# The first parameter is supposed to be the path to the markdown file | |
input_file = ARGV.first | |
config_file = ARGV[1] || '.swiftlint.yml' | |
config_param = File.exist?(config_file) ? " --config #{File.realpath(config_file)}" : '' | |
Dir.mktmpdir('snippets') do |tmpdir| | |
buffer = nil | |
offsets = {} | |
snippet_index = 0 | |
# Read the markdown file line by line, and extract each snippet into its own file | |
File.foreach(input_file).each_with_index do |line, line_number| | |
if line.chomp == '```' && !buffer.nil? | |
# end of snippet | |
path = "#{tmpdir}/snippet-#{snippet_index}.swift" | |
File.write(path, buffer) | |
buffer = nil | |
elsif line =~ /^```(.*)$/ | |
# beginning of snippet | |
unless $1.empty? || $1 == 'swift' # skip non-swift snippets | |
puts "Snippet found on line #{line_number} but not swift (#{$1})" | |
next | |
end | |
snippet_index += 1 | |
offsets[snippet_index] = line_number + 1 | |
buffer = '' | |
elsif !buffer.nil? | |
# inside snippet | |
buffer += line | |
end | |
end | |
# Run Swiftlint and dump the output | |
Open3.popen3("swiftlint lint --path #{tmpdir}#{config_param}") do |stdin, stdout, stderr| | |
# Print "Linting …" while processing | |
while line = stderr.gets | |
STDERR.puts line | |
end | |
puts '-----' | |
# Order the lint violation messages, as Swiftlint doesn't | |
# guarantee to lint files in alphabetical order | |
ordered_errors = Array.new(snippet_index) { [] } | |
stdout.each_line do |line| | |
if line =~ %r{^#{tmpdir}/snippet-([0-9]+)\.swift:([0-9]+):(.*)$} | |
new_line_number = $2.to_i + offsets[$1.to_i] | |
line = "#{input_file}:#{new_line_number}:#{$3}" | |
end | |
ordered_errors[$1.to_i - 1] << line | |
end | |
STDOUT.puts ordered_errors.flatten | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example output: