Skip to content

Instantly share code, notes, and snippets.

@bknopper
Created November 30, 2017 10:01
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save bknopper/6bb20f67917603aa3c2c0c82fafc49eb to your computer and use it in GitHub Desktop.
Save bknopper/6bb20f67917603aa3c2c0c82fafc49eb 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.")
}
}
@bknopper
Copy link
Author

@fabiocruzcoelho
Copy link

Good evening,

I am not able to pass the repository to perform the cleaning, could you help me?

How does this script clean these components?

Thank you

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