Created
November 30, 2017 10:01
-
-
Save bknopper/6bb20f67917603aa3c2c0c82fafc49eb to your computer and use it in GitHub Desktop.
Groovy script for Nexus 3 to purge old releases
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.") | |
} | |
} |
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
Original: https://gist.github.com/tgagor/f904221d888c8daaad679cf99c407aef by @tgagor