Skip to content

Instantly share code, notes, and snippets.

@hlavki
Last active May 28, 2018 05:21
Show Gist options
  • Save hlavki/15134ba6626726e1b0a0f3d68a74d6fd to your computer and use it in GitHub Desktop.
Save hlavki/15134ba6626726e1b0a0f3d68a74d6fd to your computer and use it in GitHub Desktop.
Delete relased snapshots images from nexus 3 docker registry
import org.sonatype.nexus.repository.storage.Asset
import org.sonatype.nexus.repository.storage.Component
import org.sonatype.nexus.repository.storage.Query
import org.sonatype.nexus.repository.storage.StorageFacet
// https://gist.github.com/kellyrob99/2d1483828c5de0e41732327ded3ab224
// https://gist.github.com/emexelem/bcf6b504d81ea9019ad4ab2369006e66
final SNAPSHOT_SUFFIX = "-SNAPSHOT"
final REPOSITORY = "docker"
def repo = repository.repositoryManager.get(REPOSITORY)
assert repo: "Repository ${REPOSITORY} does not exist"
StorageFacet storageFacet = repo.facet(StorageFacet)
def tx = storageFacet.txSupplier().get()
try {
tx.begin()
Iterable<Component> components = tx.findComponents(Query.builder().build(), [repo])
def snapshots = components.findAll{ it.version().contains(SNAPSHOT_SUFFIX)}.collectEntries {[(it.name() + ":" + it.version()), it]}
def releases = components.findAll{ !it.version().contains(SNAPSHOT_SUFFIX)}.collect {it.name() + ":" + it.version()}.toSet()
def toRemove = snapshots.findAll{ k,v -> releases.contains(k - SNAPSHOT_SUFFIX) }.collect{ k, v -> v }
toRemove.each { cmp ->
log.info("Deleting component ${cmp.name()}:${cmp.version()}")
tx.deleteComponent(cmp)
}
log.info("Removed ${toRemove.size()} released snapshots")
tx.commit()
}catch (Exception e) {
log.warn("Error occurs while deleting snapshot images from docker repository: {}", e.toString())
tx.rollback()
}
finally {
// @todo Fix me! Danger Will Robinson!
tx.close()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment