Skip to content

Instantly share code, notes, and snippets.

@ignatev
Forked from bknopper/purge-nexus.groovy
Created December 10, 2018 16:25
Show Gist options
  • Save ignatev/e48652517935e65fde2fa020d071b8e7 to your computer and use it in GitHub Desktop.
Save ignatev/e48652517935e65fde2fa020d071b8e7 to your computer and use it in GitHub Desktop.
Groovy script for Nexus 3 to purge old releases
import org.sonatype.nexus.repository.storage.StorageFacet;
import org.sonatype.nexus.repository.storage.Query;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
def fmt = DateTimeFormat.forPattern('yyyy-MM-dd HH:mm:ss');
[
'releases'
].each { reponame ->
// Get a repository
def repo = repository.repositoryManager.get(reponame);
// Get a database transaction
def tx = repo.facet(StorageFacet).txSupplier().get();
// Search assets that haven't been downloaded for more than two months
try {
// Begin the transaction
tx.begin();
tx.findAssets(Query.builder()
.where('last_downloaded <')
.param(DateTime.now().minusMonths(2).toString(fmt))
.build(), [repo]).take(10000).each { asset ->
if (asset.componentId() != null) {
def component = tx.findComponent(asset.componentId());
if (component != null) {
def count = tx.countComponents(Query.builder().where('name').eq(component.name()).and('version >').param(component.version()).build(), [repo]);
// Check if there is newer components of the same name
if (count > 0) {
log.info("Delete asset ${asset.name()} and its component as it has not been downloaded since 2 months and has a newer version")
tx.deleteAsset(asset);
tx.deleteComponent(component);
}
} else {
log.info("Delete Asset ${asset.name()} wasn't downloaded for more than 2 months, I hope we dont' need it anymore even if this is the only version.")
tx.deleteAsset(asset);
}
}
}
// End the transaction
log.info("Committing deletes...")
tx.commit();
log.info("Committing deletes done.")
} catch (all) {
log.info("Exception: ${all}")
all.printStackTrace()
log.info("Rolling back changes...")
tx.rollback()
log.info("Rollback done.")
} finally {
tx.close();
log.info("Transaction closed.")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment