Skip to content

Instantly share code, notes, and snippets.

@mtancoigne
Last active September 22, 2022 07:48
Show Gist options
  • Save mtancoigne/67737db51af8707700b16de065ba9d86 to your computer and use it in GitHub Desktop.
Save mtancoigne/67737db51af8707700b16de065ba9d86 to your computer and use it in GitHub Desktop.
#!/usr/bin/env ruby
# frozen_string_literal: true
# Find non-existing entries in gitignore
#
# For reference: https://git-scm.com/docs/gitignore
#
# @author Manuel Tancoigne <[email protected]>
# @license MIT
# @version 0.2.0
#
#
# Usage
# gitignore-cleaner # Use current directory
# gitignore-cleaner path/to/repo # Use .gitignore in "repo"
# gitignore-cleaner path/to/.gitignore # Use specific gitignore
#
#
# Changelog:
# 0.2.0 - Support "!" lines, comments
# 0.1.0 - Initial creation
FILE = '.gitignore'
def message_and_exit(message, code = 1)
puts message
exit code
end
def determine_file(path = nil)
return File.join(Dir.pwd, FILE) unless path
message_and_exit 'Invalid path provided' unless File.exist? path
return File.expand_path path if File.file? path
full_path = File.join(path, FILE)
message_and_exit "No #{FILE} found in \"#{path}\"" unless File.exist? full_path
full_path
end
path = determine_file ARGV[0]
base = File.expand_path File.dirname path
content = File.read(path)
.split("\n")
.map(&:strip)
# Remove empty lines
.reject(&:empty?)
# Ignore comments
.grep_v(/^\s*#/)
.map do |entry|
# Handle "!" lines
glob = entry.sub(/^!/, '')
# Handle "/" lines
glob = glob.match?(%r{^\s*/}) ? ".#{glob}" : "**/#{glob}"
# Keep original entry for summary
[entry, glob]
end
missing = []
Dir.chdir base do
missing = content.select { |entry| Dir.glob(entry[1]).count.zero? }
.map { |entry| entry[0] }
end
line_prefix = ' - '
puts <<~TXT
#{missing.count}/#{content.count} unused entries#{missing.count.zero? ? ', great!' : ':'}
#{line_prefix}#{missing.join("\n#{line_prefix}")}
TXT
@mtancoigne
Copy link
Author

mtancoigne commented Sep 22, 2022

No support for !file now. Done

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment