Skip to content

Instantly share code, notes, and snippets.

@aleung
Last active April 24, 2017 18:07
Show Gist options
  • Save aleung/5203736 to your computer and use it in GitHub Desktop.
Save aleung/5203736 to your computer and use it in GitHub Desktop.
Clean up unused (long time no download) artifacts from Artifactory repository. See: http://aleung.github.com/blog/2013/03/22/clean-aged-artifacts-from-artifactory/
#!/bin/env ruby
# --- Configuration ---------------------------------
# Remove artifacts which were created before $age_days ago and haven't been downloaded in recent $age_days.
$age_days = 730
# The repository to be cleaned.
$repo = 'repository-key'
$user = 'user'
$password = 'password'
$host = 'mavenrepo.mycompany.com'
$artifactory_root_path = '/repo'
# --- Configuration end ------------------------------
require 'rubygems'
require 'net/http'
require 'json'
def handle_usused_result(result)
JSON.parse(result)["results"].each { |artifact|
delete_artifact(artifact["uri"])
}
end
def delete_artifact(artifact_uri)
puts "Delete artifact #{artifact_uri}"
%r|.*/#{$repo}/(.*)/.*| =~ artifact_uri
url = "#{$artifactory_root_path}/#{$repo}/#{$1}"
http = Net::HTTP.new($host)
request = Net::HTTP::Delete.new(url)
request.basic_auth($user, $password)
response = http.request(request)
puts "#{response.code} #{response.body}\n"
end
def retrieve_unused_artifacts()
since = (Time.now - $age_days * 3600*24).to_i * 1000
url = "#{$artifactory_root_path}/api/search/usage?notUsedSince=#{since}&createdBefore=#{since}&repos=#{$repo}"
puts url
http = Net::HTTP.new($host)
http.read_timeout = 500
request = Net::HTTP::Get.new(url)
request.basic_auth($user, $password)
response = http.request(request)
if response.code != "200"
puts "#{response.code} #{response.body}"
exit!
end
save_file(response.body)
return response.body
end
def save_file(result)
File.open('unused_artifactorys.txt', 'w') { |f| f.puts(result) }
end
def load_file()
File.open('unused_artifactorys.txt') { |f| f.gets }
end
handle_usused_result(retrieve_unused_artifacts())
# handle_usused_result(load_file())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment