aleung
3/28/2013 - 4:05 AM

I have Maven (Artifactory) repository which was configured to store non-unique snapshots. When the configure was changed to store unique (wi

I have Maven (Artifactory) repository which was configured to store non-unique snapshots. When the configure was changed to store unique (with time-stamp) snapshots, if a new snapshot is deployed, there will be both unique snapshot and non-unique snapshot artifact of same version exists. If it happens, the snapshot artifact will be unable to download because of resolution problem. I made this script to scan all recent deployed artifacts and try to remove the non-unique snapshot of the same version. See: http://aleung.github.com/blog/2013/03/30/maven-unique-non-unique-snapshot-conflict/

#!/bin/env ruby

# --- Configuration ---------------------------------

$age_days = 3

# The repository to be cleaned.
$repo = 'repo-name'

$user = 'repo-admin'
$password = 'password'
$host = 'artifactory.mycompany.com'
$artifactory_root_path = '/repo'

# --- Configuration end ------------------------------



require 'net/http'
require 'json'

def handle_recent_deploy_result(result)
	JSON.parse(result)["results"].each { |artifact|
		handle_recent_deploy_artifact(artifact["uri"])
	}
end

def handle_recent_deploy_artifact(artifact_uri)
	puts artifact_uri
	%r|.*/#{$repo}/(.*)/(.*)/(.*)-SNAPSHOT/(.*)| =~ artifact_uri
	#puts "Path:#{$1}\nArtifactId:#{$2}\nVersionBase:#{$3}\nFileName:#{$4}\n"

	groupPath = $1
	artifactId = $2
	versionBase = $3
	fileName = $4

	if /#{artifactId}-#{versionBase}-\d{8}\.\d{6}-\d(.*)/ =~ fileName
		url = "#{$artifactory_root_path}/#{$repo}/#{groupPath}/#{artifactId}/#{versionBase}-SNAPSHOT/#{artifactId}-#{versionBase}-SNAPSHOT#{$1}"
		puts "Delete #{url}"
		delete_artifact(url)
		puts
	end
end


def delete_artifact(url)
	http = Net::HTTP.new($host)
	http.read_timeout = 500
	request = Net::HTTP::Delete.new(url)
	request.basic_auth($user, $password)
	response = http.request(request)
	puts "#{response.code}"
end

def retrieve_recent_artifacts()
	since = (Time.now - $age_days * 3600*24).to_i * 1000
	url = "#{$artifactory_root_path}/api/search/creation?from=#{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('recent_artifactorys.txt', 'w') { |f| f.puts(result) }
end

def load_file()
	File.open('recent_artifactorys.txt') { |f| f.gets }
end

handle_recent_deploy_result(retrieve_recent_artifacts())

#handle_recent_deploy_result(load_file())