I have too many files in .m2 folder where maven stores downloaded dependencies. Is there a way to clean all old dependencies? For example, if there is a dependency with 3 di
It's been more than 6 years since the question was asked, but I didn't find any tool to clean up my repository. So I wrote one myself in python to get rid of old jars. Maybe it will be useful for someone:
from os.path import isdir
from os import listdir
import re
import shutil
dry_run = False # change to True to get a log of what will be removed
m2_path = '/home/jb/.m2/repository/' # here comes your repo path
version_regex = '^\d[.\d]*$'
def check_and_clean(path):
files = listdir(path)
for file in files:
if not isdir('/'.join([path, file])):
return
last = check_if_versions(files)
if last is None:
for file in files:
check_and_clean('/'.join([path, file]))
elif len(files) == 1:
return
else:
print('update ' + path.split(m2_path)[1])
for file in files:
if file == last:
continue
print(file + ' (newer version: ' + last + ')')
if not dry_run:
shutil.rmtree('/'.join([path, file]))
def check_if_versions(files):
if len(files) == 0:
return None
last = ''
for file in files:
if re.match(version_regex, file):
if last == '':
last = file
if len(last.split('.')) == len(file.split('.')):
for (current, new) in zip(last.split('.'), file.split('.')):
if int(new) > int(current):
last = file
break
elif int(new) < int(current):
break
else:
return None
else:
return None
return last
check_and_clean(m2_path)
It recursively searches within the .m2 repository and if it finds a catalog where different versions reside it removes all of them but the newest.
Say you have the following tree somewhere in your .m2 repo:
.
└── antlr
├── 2.7.2
│ ├── antlr-2.7.2.jar
│ ├── antlr-2.7.2.jar.sha1
│ ├── antlr-2.7.2.pom
│ ├── antlr-2.7.2.pom.sha1
│ └── _remote.repositories
└── 2.7.7
├── antlr-2.7.7.jar
├── antlr-2.7.7.jar.sha1
├── antlr-2.7.7.pom
├── antlr-2.7.7.pom.sha1
└── _remote.repositories
Then the script removes version 2.7.2 of antlr and what is left is:
.
└── antlr
└── 2.7.7
├── antlr-2.7.7.jar
├── antlr-2.7.7.jar.sha1
├── antlr-2.7.7.pom
├── antlr-2.7.7.pom.sha1
└── _remote.repositories
If any old version, that you actively use, will be removed. It can easily be restored with maven (or other tools that manage dependencies).
You can get a log of what is going to be removed without actually removing it by setting dry_run = False. The output will go like this:
update /org/projectlombok/lombok
1.18.2 (newer version: 1.18.6)
1.16.20 (newer version: 1.18.6)
This means, that versions 1.16.20 and 1.18.2 of lombok will be removed and 1.18.6 will be left untouched.
The file can be found on my github (the latest version).