How to clean old dependencies from maven repositories?

前端 未结 9 1758
小鲜肉
小鲜肉 2020-12-14 05:19

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

相关标签:
9条回答
  • 2020-12-14 05:46
    1. Download all actual dependencies of your projects

      find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
      
    2. Move your local maven repository to temporary location

      mv ~/.m2 ~/saved-m2
      
    3. Rename all files maven-metadata-central.xml* from saved repository into maven-metadata.xml*

      find . -type f -name "maven-metadata-central.xml*" -exec rename -v -- 's/-central//' '{}' \;
      
    4. To setup the modified copy of the local repository as a mirror, create the directory ~/.m2 and the file ~/.m2/settings.xml with the following content (replacing user with your username):

      <settings>
       <mirrors>
        <mirror>
         <id>mycentral</id>
         <name>My Central</name>
         <url>file:/home/user/saved-m2/</url>
         <mirrorOf>central</mirrorOf>
        </mirror>
       </mirrors>
      </settings>
      
    5. Resolve your projects dependencies again:

      find your-projects-dir -name pom.xml -exec mvn -f '{}' dependency:resolve
      
    6. Now you have local maven repository with minimal of necessary artifacts. Remove local mirror from config file and from file system.

    0 讨论(0)
  • 2020-12-14 05:47

    If you are on Unix, you could use the access time of the files in there. Just enable access time for your filesystem, then run a clean build of all your projects you would like to keep dependencies for and then do something like this (UNTESTED!):

    find ~/.m2 -amin +5 -iname '*.pom' | while read pom; do parent=`dirname "$pom"`; rm -Rf "$parent"; done
    

    This will find all *.pom files which have last been accessed more than 5 minutes ago (assuming you started your builds max 5 minutes ago) and delete their directories.

    Add "echo " before the rm to do a 'dry-run'.

    0 讨论(0)
  • 2020-12-14 05:47

    You need to copy the dependency you need for project. Having these in hand please clear all the <dependency> tag embedded into <dependencies> tag from POM.XML file in your project.

    After saving the file you will not see Maven Dependencies in your Libraries. Then please paste those <dependency> you have copied earlier.

    The required jars will be automatically downloaded by Maven, you can see that too in the generated Maven Dependencies Libraries after saving the file.

    Thanks.

    0 讨论(0)
  • 2020-12-14 05:50

    Given a POM file for a maven project you can remove all its dependencies in the local repository (by default ~/.m2/respository) using the Apache Maven Dependency Plugin.

    It includes the dependency:purge-local-repository functionality that removes the project dependencies from the local repository, and optionally re-resolve them.

    To clean the local dependencies you just have to used the optional parameter reResolve and set it to false since it is set to true by default.

    This command line call should work:

    mvn dependency:purge-local-repository -DreResolve=false
    
    0 讨论(0)
  • 2020-12-14 06:00

    Short answer - Deleted .m2 folder in {user.home}. E.g. in windows 10 user home is C:\Users\user1. Re-build your project using mvn clean package. Only those dependencies would remain, which are required by the projects.

    Long Answer - .m2 folder is just like a normal folder and the content of the folder is built from different projects. I think there is no way to figure out automatically that which library is "old". In fact old is a vague word. There could be so many reasons when a previous version of a library is used in a project, hence determining which one is unused is not possible.

    All you could do, is to delete the .m2 folder and re-build all of your projects and then the folder would automatically build with all the required library.

    If you are concern about only a particular version of a library to be used in all the projects; it is important that the project's pom should also update to latest version. i.e. if different POMs refer different versions of the library, all will get downloaded in .m2.

    0 讨论(0)
  • 2020-12-14 06:05

    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).

    0 讨论(0)
提交回复
热议问题