Skip to content

Instantly share code, notes, and snippets.

@bscofield
Created August 11, 2022 16:12
Show Gist options
  • Save bscofield/6a4a54deeab338517bf3a26edd9ee6b3 to your computer and use it in GitHub Desktop.
Save bscofield/6a4a54deeab338517bf3a26edd9ee6b3 to your computer and use it in GitHub Desktop.
#! /usr/bin/env ruby
require "json"
require "set"
require "yaml"
USAGE = <<-EOS
USAGE: From within an application folder that includes Packwerk packages, run this
script. The script will loop through each package.yml and check each of the declared
dependencies to find any that are no longer needed.
This takes a bit ⏳
EOS
options = ARGV.shift
if options == "-h" || options == "--help"
puts USAGE
exit
end
file_pattern = "**/package.yml"
services = Dir.glob("./**/package.yml").filter do |f|
f =~ /\.\/services/
end
def check(output)
system('bundle exec packwerk check', out: output)
end
def clean_name(name)
name.sub("./", "").sub("/package.yml", "")
end
if !check(File::NULL)
puts "💥 Packweck check fails on this branch"
exit
end
data = Set.new
start = Time.now
services.sort.each do |file|
name = clean_name(file)
contents = {}
begin
contents = YAML.load_file(file)
rescue
next
end
next unless contents['enforce_dependencies'] && contents['dependencies']
contents['dependencies'].each do |dependency|
data.add([name, dependency].join("|"))
end
# clear deps
contents['dependencies'] = []
File.open(file, 'w') do |f|
f.write contents.to_yaml
end
end
violation_file = "/tmp/violations"
File.open(violation_file, "w") do |f|
check(f)
end
violations = File.readlines(violation_file).select { |line| line =~ /\ADependency violation/ }
violations.each do |violation|
pieces = /but '(.+?)' does not specify a dependency on '(.+?)'/.match(violation)
data.delete([pieces[1], pieces[2]].join("|"))
end
system("git checkout .", out: File::NULL)
puts
puts
puts "Done in #{Time.now - start}s"
puts
puts "Summary: "
if data.count == 0
puts "No unnecessary dependencies"
else
data.to_a.each do |violation|
pieces = violation.split('|')
puts pieces.join(" →\t")
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment