Skip to content

Instantly share code, notes, and snippets.

@legege
Last active May 6, 2024 20:56
Show Gist options
  • Save legege/6a60d859258285f79580 to your computer and use it in GitHub Desktop.
Save legege/6a60d859258285f79580 to your computer and use it in GitHub Desktop.
Intelligently clean a Sonatype Nexus repository... keep the last 2 released versions of each "major.minor" artifact
#!/bin/bash
DRY_RUN=1
if [ "$1" != "" ]; then
DRY_RUN="$1"
fi
MAX_VERSION=2
if [ "$2" != "" ]; then
MAX_VERSION="$2"
fi
if [ $MAX_VERSION -lt 2 ]; then
echo "You must keep at least 2 versions"
exit 1
fi
total_space=0
pushd /devel/nexus/sonatype-work/nexus/storage/releases
TRASH=./.nexus/trash
metadata_files=`find . -not -path '*/\.*' -type f -name maven-metadata.xml`
for metadata_file in $metadata_files; do
artifact_folder=`dirname $metadata_file`
if [[ $artifact_folder != *"-setup" ]] && [[ $artifact_folder != *"-webapp" ]] && [[ $artifact_folder != *"-install" ]] && [[ $artifact_folder != *"-application-bundle" ]]; then
continue
fi
minor_versions=`sed 's#.*<version>\([0-9]*\.[0-9]*\).*</version>#\1#;tx;d;:x' $metadata_file | uniq`
for minor_version in $minor_versions; do
inc_versions_todelete_count=`ls -l -d -v $artifact_folder/$minor_version* | wc -l`
if [ $inc_versions_todelete_count -gt $MAX_VERSION ]; then
echo "There are $inc_versions_todelete_count versions in $artifact_folder/$minor_version*... Need to delete old versions"
if [ $DRY_RUN -eq 0 ]; then
trash_artifact_folder=$TRASH${artifact_folder#"."}
trash_artifact_folder_attr=$TRASH/.nexus/attributes${artifact_folder#"."}
mkdir -p $trash_artifact_folder
mkdir -p $trash_artifact_folder_attr
fi
for inc_version_todelete in `ls -l -d -v $artifact_folder/$minor_version* | head -n -$MAX_VERSION | awk '{print $9}'`; do
version=`basename $inc_version_todelete`
inc_version_todelete_attr=.nexus/attributes${inc_version_todelete#"."}
echo " Moving $version to trash..."
space=`du -b -s $inc_version_todelete | awk '{print $1}'`
total_space=$((total_space + space))
space=`du -b -s $inc_version_todelete_attr | awk '{print $1}'`
total_space=$((total_space + space))
if [ $DRY_RUN -eq 0 ]; then
mv $inc_version_todelete $trash_artifact_folder
mv $inc_version_todelete_attr $trash_artifact_folder_attr
fi
done
fi
done
done
chown -R nexus:nexus $TRASH
popd
convert_bytes_human() {
NUMBER=$1
for DESIG in B K M G T P; do
[ $NUMBER -lt 1024 ] && break
let NUMBER=$NUMBER/1024
done
printf "%d%s\n" $NUMBER $DESIG
}
convert_bytes_human $total_space
@legege
Copy link
Author

legege commented Mar 23, 2018

For those interested, Nexus 3 version here:
https://gist.github.com/legege/1f8e7b82675fc15beae4a6d9a8640d03

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