Created
September 27, 2023 12:21
-
-
Save swissonid/0c1ee0ac85c0f4d875da008961040dd0 to your computer and use it in GitHub Desktop.
pre-commit Hook which formats your kotlin file with ktling
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 'open3' | |
class KtlintPreCommitHook | |
def self.run | |
puts "Running pre commit hook" | |
check_ktlint_availability | |
files_needs_formatting = check_changed_files | |
auto_format_changed_files(files_needs_formatting) | |
end | |
private | |
def self.check_ktlint_availability | |
puts "\nCheck if ktlint is installed...." | |
if !`which ktlint`.strip | |
raise 'Ktlint is not available in the PATH. Please install ktlint or add it to your PATH.' | |
end | |
puts "Ktlint is installed\n" | |
end | |
def self.get_all_changed_kotlin_files | |
puts "\nChecking if there are any changed kotlin files - ignoring deleted files" | |
# this parameter --diff-filter=d filters all the deleted files a way from the change list | |
changed_files = `git diff --name-only --diff-filter=d HEAD`.split("\n") | |
ktlint_files = changed_files.select { |file| file.end_with?('.kt') } | |
if ktlint_files.empty? | |
puts "It seams no Kotlin files has been change skipping format checking" | |
end | |
puts "Found #{ktlint_files.length} Kotlin file(s) that has changed" | |
return ktlint_files | |
end | |
def self.auto_format_changed_files(files_needs_formatting) | |
if files_needs_formatting.empty? | |
return | |
end | |
files_needs_formatting.each do | file | | |
cmd = "ktlint -F #{file}" | |
Open3.popen3(cmd) do |stdin, stdout, stderr| | |
if stderr.read.strip != '' or stdout.read.strip != '' | |
raise "Ktlint found errors in file #{file} run 'ktlint -F #{file}' to see whats the excate issue" | |
end | |
end | |
`git add #{file}` | |
end | |
end | |
def self.check_changed_files | |
ktfiles_need_formatting = [] | |
ktlint_files = get_all_changed_kotlin_files | |
if ktlint_files.empty? | |
return ktfiles_need_formatting | |
end | |
puts "\nChecking if any of the changed files needs reformatting" | |
ktlint_files.each do |file| | |
cmd = "ktlint #{file}" | |
Open3.popen3(cmd) do |stdin, stdout, stderr| | |
if stderr.read.strip != '' or stdout.read.strip != '' | |
ktfiles_need_formatting.push(file) | |
puts "Added file '#{file}' to formatting list" | |
end | |
end | |
end | |
return ktlint_files | |
end | |
end | |
KtlintPreCommitHook.run |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment