|
| 1 | +/* |
| 2 | + * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one |
| 3 | + * or more contributor license agreements. Licensed under the "Elastic License |
| 4 | + * 2.0", the "GNU Affero General Public License v3.0 only", and the "Server Side |
| 5 | + * Public License v 1"; you may not use this file except in compliance with, at |
| 6 | + * your election, the "Elastic License 2.0", the "GNU Affero General Public |
| 7 | + * License v3.0 only", or the "Server Side Public License, v 1". |
| 8 | + */ |
| 9 | + |
| 10 | +package org.elasticsearch.gradle.internal.dependencies.rules; |
| 11 | + |
| 12 | +import org.gradle.api.artifacts.CacheableRule; |
| 13 | +import org.gradle.api.artifacts.ComponentMetadataContext; |
| 14 | +import org.gradle.api.artifacts.ComponentMetadataRule; |
| 15 | + |
| 16 | +/** |
| 17 | + * A Gradle component metadata rule that excludes transitive dependencies with different group IDs |
| 18 | + * than the parent component. |
| 19 | + * |
| 20 | + * <p>This rule helps prevent dependency conflicts and reduces the dependency tree size by ensuring |
| 21 | + * that only dependencies from the same Maven group ID are included transitively. This is particularly |
| 22 | + * useful for large projects where different modules should not pull in external dependencies from |
| 23 | + * other organizations or groups.</p> |
| 24 | + * |
| 25 | + * <p>The rule operates on all variants of a component and removes any transitive dependency whose |
| 26 | + * group ID differs from the component's own group ID.</p> |
| 27 | + * |
| 28 | + * <h3>Example Usage:</h3> |
| 29 | + * <pre>{@code |
| 30 | + * dependencies { |
| 31 | + * components { |
| 32 | + * withModule("com.azure:azure-core", ExcludeOtherGroupsTransitiveRule) |
| 33 | + * } |
| 34 | + * } |
| 35 | + * }</pre> |
| 36 | + * |
| 37 | + * <h3>Example Behavior:</h3> |
| 38 | + * <p>If component {@code com.example:my-lib:1.0} has transitive dependencies:</p> |
| 39 | + * <ul> |
| 40 | + * <li>{@code com.example:another-lib:1.0} - KEPT (same group)</li> |
| 41 | + * <li>{@code org.apache.commons:commons-lang3:3.12.0} - REMOVED (different group)</li> |
| 42 | + * <li>{@code com.example:utils:1.5} - KEPT (same group)</li> |
| 43 | + * </ul> |
| 44 | + * |
| 45 | + */ |
| 46 | +@CacheableRule |
| 47 | +public abstract class ExcludeOtherGroupsTransitiveRule implements ComponentMetadataRule { |
| 48 | + |
| 49 | + @Override |
| 50 | + public void execute(ComponentMetadataContext context) { |
| 51 | + context.getDetails().allVariants(variant -> { |
| 52 | + variant.withDependencies(dependencies -> { |
| 53 | + // Exclude transitive dependencies with a different groupId than the parent |
| 54 | + dependencies.removeIf(dep -> dep.getGroup().equals(context.getDetails().getId().getGroup()) == false); |
| 55 | + }); |
| 56 | + }); |
| 57 | + } |
| 58 | +} |
0 commit comments