commit d89e7cd5626adf21f740b82f12f137ff5614a907 Author: Jon Michael Aanes Date: Wed Oct 30 13:24:41 2024 +0100 Basic script with test scope checking diff --git a/README.md b/README.md new file mode 100644 index 0000000..6a334ea --- /dev/null +++ b/README.md @@ -0,0 +1,3 @@ + +Script for checking whether some Maven project has minimal dependencies. + diff --git a/maven_check_minimal_deps/__init__.py b/maven_check_minimal_deps/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/maven_check_minimal_deps/__main__.py b/maven_check_minimal_deps/__main__.py new file mode 100644 index 0000000..94ffd4f --- /dev/null +++ b/maven_check_minimal_deps/__main__.py @@ -0,0 +1,66 @@ +import subprocess +import bs4 +import argparse +import logging +from pathlib import Path + +logger = logging.getLogger(__name__) + +def parse_arguments(): + parser = argparse.ArgumentParser() + parser.add_argument('project', type=Path) + return parser.parse_args() + +def can_compile(path: Path) -> bool: + process = subprocess.run(['mvn', 'clean', 'compile'], cwd=path, check=False,capture_output=True) + return process.returncode == 0 + +def write_pom(project_path: Path, pom: bs4.BeautifulSoup | str) -> None: + with open(project_path / 'pom.xml', 'w') as f: + f.write(str(pom)) + +def main(): + logging.basicConfig() + logger.setLevel('INFO') + args = parse_arguments() + + assert can_compile(args.project), 'Project did not compile before modification!' + + with open(args.project / 'pom.xml') as f: + original_pom = f.read() + pom = bs4.BeautifulSoup(original_pom, 'lxml-xml') + + main_dependencies = [] + for dep in pom.select('dependencies > dependency'): + if dep.scope is None: + main_dependencies.append(dep) + + errors = [] + + for dep in main_dependencies: + name = '{}:{}'.format(dep.groupId.get_text(), dep.artifactId.get_text()) + logger.info('Checking %s', name) + dep.insert(-1, bs4.BeautifulSoup('test', 'lxml-xml')) + + write_pom(args.project, pom) + + if can_compile(args.project): + errors.append(f'Could move {name} to test scope') + logger.error('%s', errors[-1]) + else: + dep.scope.extract() + del dep, name + + logger.info('Resetting POM') + write_pom(args.project, original_pom) + logger.info('Finished checks') + + if errors: + logger.error('Encountered %d errors', len(errors)) + for error in errors: + logger.error('%s', error) + exit(1) + +if __name__ == '__main__': + main() +