build: 템플릿 밖에서 혼자 빌드·배포되는 Gradle 루트를 만든다
옮겨 온 메시징 19개 모듈은 템플릿의 src/settings.gradle·build-logic· 카탈로그·registry에 기대고 있어 이 repo만으로는 빌드되지 않는다. repo 루트를 Gradle 루트로 하는 단독 빌드를 만든다. - build-logic/: grpc-library main 2e880c7의 줄인 사본(템플릿 22df3525에서 복사, 템플릿 2959eff0까지의 변경도 같은 내용)에서 gRPC BOM 규칙(ca.grpc-platform-module)만 뺐다. 배포 플러그인 ca.library-publishing과 서명 키 해석(SigningKeys)은 그대로다. 출처·뺀 것·고친 것은 build-logic/UPSTREAM.md. - settings.gradle·build.gradle·gradle.properties: group dev.cakit.messaging, 단계 태스크 ci·mainCheck·releaseCheck와 배포(release·releaseRehearsal·verifySigningKey)는 grpc-library와 같은 모양이다. 메시징만 다른 점: Buf가 없고, 성능 lane이 없고, mainCheck와 releaseCheck가 브로커 인증 증거 게이트 (verifyMessagingCertificationEvidence)를 부른다. 템플릿은 이 게이트를 따로 messaging-certification.yml로 돌렸다. 그 workflow는 지운다. - config/: registry 19행(source_path만 messaging/<leaf>로), 메시징 클래스만 남긴 SpotBugs 제외 목록, 이미지 셋(postgres-16, kafka, toxiproxy, 모두 digest 고정), checkstyle 사본. - gradle/libs.versions.toml: 메시징이 쓰는 항목만(avro, cloudevents, protobuf 4.33.2, toxiproxy, jmh)과 kafka-clients가 끌고 오는 취약 버전을 덮는 pinned-lz4-java·pinned-snappy-java. - 저장소 계약 테스트: MessagingPublicSurfaceContractTest(템플릿 app-bootstrap에서 이력째 옮김)와 새 MessagingSettingsOwnerContractTest (app.messaging 주인은 starter 하나)를 messaging-testkit의 repositoryContractTest lane에 둔다. check에 들어가 PR 단계에서 돈다. - messaging-kafka: 인증 manifest 경로를 새 배치로 고친다. 버린 대안: 계약 테스트를 build-logic 테스트로 두는 안. 빌드 플러그인 시험과 모듈 계약이 섞이고, 소스·build.gradle을 입력으로 선언하는 기존 lane 장치를 쓸 수 없다. 위험: 이 커밋 단독으로는 lockfile을 다시 쓰지 않았다(뒤 커밋에서 desktop에서 쓴다). 패키지는 아직 dev.caskeleton.messaging이다. 검증: desktop ./gradlew projects rc=0(19개 모듈 포함). Refs: design-docs repo-structure/05-library-repos.md 4·10.3·13.1절
This commit is contained in:
+201
@@ -0,0 +1,201 @@
|
||||
package dev.caskeleton.buildlogic.architecture;
|
||||
|
||||
import dev.caskeleton.buildlogic.ModuleRegistry;
|
||||
import java.io.File;
|
||||
import java.nio.file.Path;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.gradle.api.Plugin;
|
||||
import org.gradle.api.Project;
|
||||
import org.gradle.api.artifacts.Configuration;
|
||||
import org.gradle.api.artifacts.ProjectDependency;
|
||||
import org.gradle.api.artifacts.result.ResolvedComponentResult;
|
||||
import org.gradle.api.provider.Provider;
|
||||
import org.gradle.api.tasks.SourceSet;
|
||||
import org.gradle.api.tasks.SourceSetContainer;
|
||||
|
||||
public final class ArchitecturePlugin implements Plugin<Project> {
|
||||
private static final List<String> PRODUCTION_DECLARATIONS =
|
||||
List.of("api", "implementation", "compileOnly", "runtimeOnly");
|
||||
/** The registry, relative to the repository root. */
|
||||
public static final String REGISTRY = "config/architecture/modules.json";
|
||||
|
||||
@Override
|
||||
public void apply(Project project) {
|
||||
// One build, rooted at the repository root: the registry is the root's, and every source_path
|
||||
// is relative to it (the template's main build sits in src/, which is why its copy reads the
|
||||
// registry relative to the parent).
|
||||
Project root = project.getRootProject();
|
||||
File repositoryRoot = root.getProjectDir();
|
||||
File registryFile = new File(repositoryRoot, REGISTRY);
|
||||
ModuleRegistry registry = ModuleRegistry.read(registryFile, repositoryRoot);
|
||||
List<ModuleRegistry.Module> modules = registry.modulesForBuild("main");
|
||||
List<String> registryViolations = registryViolations(registry, modules);
|
||||
|
||||
var clean =
|
||||
project
|
||||
.getTasks()
|
||||
.register(
|
||||
"verifyCleanArchitectureDependencies",
|
||||
VerifyCleanArchitectureDependenciesTask.class,
|
||||
task -> {
|
||||
task.setGroup("verification");
|
||||
task.setDescription("Verifies Clean Architecture project dependency direction.");
|
||||
task.getRegistryFile().fileValue(registryFile);
|
||||
task.getRegistryViolations().set(registryViolations);
|
||||
task.getUnregisteredBuildScripts()
|
||||
.set(registry.unregisteredBuildScripts(root.getProjectDir()));
|
||||
});
|
||||
var ignoredSources =
|
||||
project
|
||||
.getTasks()
|
||||
.register(
|
||||
"verifyNoIgnoredSourcePackages",
|
||||
VerifyNoIgnoredSourcePackagesTask.class,
|
||||
task -> {
|
||||
task.setGroup("verification");
|
||||
task.setDescription(
|
||||
"Fails when a Java source file lives in a package that Git ignores or would"
|
||||
+ " ignore.");
|
||||
task.getBuildRoot().set(root.getLayout().getProjectDirectory());
|
||||
});
|
||||
|
||||
project
|
||||
.getGradle()
|
||||
.projectsEvaluated(
|
||||
ignored -> {
|
||||
Set<String> declaredModules = new HashSet<>();
|
||||
root.getSubprojects().stream()
|
||||
.filter(sub -> sub.getChildProjects().isEmpty())
|
||||
.forEach(sub -> declaredModules.add(sub.getPath().replaceFirst("^:", "")));
|
||||
// One task per module, registered in the project that owns the configurations. The
|
||||
// root task used to walk every other project and resolve its `compileClasspath`,
|
||||
// which asks Gradle for state another project holds the lock on — with
|
||||
// `org.gradle.parallel=true` that is a hard failure, and it is why the flag was
|
||||
// turned off instead of the verification moved.
|
||||
List<String> moduleTaskPaths = new ArrayList<>();
|
||||
for (ModuleRegistry.Module module : modules) {
|
||||
Project owner = root.project(module.gradlePath());
|
||||
Set<String> allowed = new HashSet<>();
|
||||
for (String dependencyId : module.allowedDependencies()) {
|
||||
ModuleRegistry.Module dependency = registry.byId(dependencyId);
|
||||
if (dependency != null) {
|
||||
allowed.add(dependency.gradlePath().replaceFirst("^:", ""));
|
||||
}
|
||||
}
|
||||
Set<String> declaredEdges = declaredProjectEdges(owner);
|
||||
Provider<ResolvedComponentResult> compileClasspathRoot =
|
||||
owner
|
||||
.getConfigurations()
|
||||
.getByName("compileClasspath")
|
||||
.getIncoming()
|
||||
.getResolutionResult()
|
||||
.getRootComponent();
|
||||
String moduleName = module.gradlePath().replaceFirst("^:", "");
|
||||
owner
|
||||
.getTasks()
|
||||
.register(
|
||||
"verifyModuleDependencyDirection",
|
||||
VerifyModuleDependencyDirectionTask.class,
|
||||
task -> {
|
||||
task.setGroup("verification");
|
||||
task.setDescription(
|
||||
"Verifies this module's declared and compile-visible project edges"
|
||||
+ " against the architecture registry.");
|
||||
task.getModuleName().set(moduleName);
|
||||
task.getAllowedDependencies().set(allowed);
|
||||
task.getDeclaredProjectEdges().set(declaredEdges);
|
||||
task.getCompileClasspathRoot().set(compileClasspathRoot);
|
||||
});
|
||||
moduleTaskPaths.add(module.gradlePath() + ":verifyModuleDependencyDirection");
|
||||
}
|
||||
clean.configure(
|
||||
task -> {
|
||||
task.getDeclaredModules().set(declaredModules);
|
||||
task.getGovernedModules()
|
||||
.set(
|
||||
modules.stream()
|
||||
.map(module -> module.gradlePath().replaceFirst("^:", ""))
|
||||
.toList());
|
||||
task.dependsOn(moduleTaskPaths);
|
||||
});
|
||||
|
||||
// Every source set of every project — testFixtures, integrationTest, systemTest and
|
||||
// the sample included — because a file Git drops is lost whichever lane owns it.
|
||||
// Directories under a build directory are generated and never committed.
|
||||
List<File> sourceRoots = new ArrayList<>();
|
||||
for (Project sub : root.getSubprojects()) {
|
||||
SourceSetContainer sourceSets =
|
||||
sub.getExtensions().findByType(SourceSetContainer.class);
|
||||
if (sourceSets == null) {
|
||||
continue;
|
||||
}
|
||||
Path buildDirectory = sub.getLayout().getBuildDirectory().get().getAsFile().toPath();
|
||||
for (SourceSet sourceSet : sourceSets) {
|
||||
for (File sourceRoot : sourceSet.getJava().getSrcDirs()) {
|
||||
if (!sourceRoot.toPath().startsWith(buildDirectory)) {
|
||||
sourceRoots.add(sourceRoot);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ignoredSources.configure(task -> task.getSourceRoots().from(sourceRoots));
|
||||
});
|
||||
|
||||
project
|
||||
.getTasks()
|
||||
.register(
|
||||
"architectureCheck",
|
||||
task -> {
|
||||
task.setGroup("verification");
|
||||
task.setDescription("Runs the build's architecture invariants.");
|
||||
task.dependsOn(clean, ignoredSources);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* This module's declared {@code project(...)} edges, read while the owning project is configured.
|
||||
*
|
||||
* <p>Read here rather than in the task action: a {@link Configuration} cannot be stored in the
|
||||
* configuration cache, and every declaration this reads is final by {@code projectsEvaluated}.
|
||||
*/
|
||||
private static Set<String> declaredProjectEdges(Project owner) {
|
||||
Set<String> edges = new TreeSet<>();
|
||||
for (String name : PRODUCTION_DECLARATIONS) {
|
||||
Configuration configuration = owner.getConfigurations().findByName(name);
|
||||
if (configuration == null) {
|
||||
continue;
|
||||
}
|
||||
configuration
|
||||
.getDependencies()
|
||||
.withType(ProjectDependency.class)
|
||||
.forEach(dependency -> edges.add(dependency.getPath().replaceFirst("^:", "")));
|
||||
}
|
||||
return edges;
|
||||
}
|
||||
|
||||
private static List<String> registryViolations(
|
||||
ModuleRegistry registry, List<ModuleRegistry.Module> modules) {
|
||||
List<String> violations = new ArrayList<>();
|
||||
for (ModuleRegistry.Module module : modules) {
|
||||
for (String dependencyId : module.allowedDependencies()) {
|
||||
if (dependencyId.equals(module.id())) {
|
||||
violations.add("'" + module.id() + "' declares itself as an allowed dependency");
|
||||
continue;
|
||||
}
|
||||
ModuleRegistry.Module dependency = registry.byId(dependencyId);
|
||||
if (dependency == null) {
|
||||
violations.add(
|
||||
"'" + module.id() + "' allows unknown dependency id '" + dependencyId + "'");
|
||||
} else if (!dependency.buildName().equals(module.buildName())) {
|
||||
violations.add(
|
||||
"'" + module.id() + "' allows cross-build dependency id '" + dependencyId + "'");
|
||||
}
|
||||
}
|
||||
}
|
||||
return List.copyOf(violations);
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package dev.caskeleton.buildlogic.architecture;
|
||||
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.RegularFileProperty;
|
||||
import org.gradle.api.provider.ListProperty;
|
||||
import org.gradle.api.provider.SetProperty;
|
||||
import org.gradle.api.tasks.Input;
|
||||
import org.gradle.api.tasks.InputFile;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.gradle.work.DisableCachingByDefault;
|
||||
|
||||
/**
|
||||
* The repository-wide half of the dependency contract.
|
||||
*
|
||||
* <p>Two questions only, and both are answered from the registry rather than from any project's
|
||||
* configurations: is the registry internally consistent, and does the set of modules it governs
|
||||
* match the set of leaves the build actually declares. A leaf that exists and is ungoverned is the
|
||||
* failure this catches — a new module cannot be added and quietly escape the direction rules.
|
||||
*
|
||||
* <p>Whether a given module's edges are allowed is {@link VerifyModuleDependencyDirectionTask}'s
|
||||
* job, one task per module, in the project that owns the configurations. That split is the whole
|
||||
* point: this task used to resolve every other project's {@code compileClasspath} itself, which
|
||||
* needs a lock it does not hold, and made {@code org.gradle.parallel=true} fail rather than merely
|
||||
* be unused.
|
||||
*/
|
||||
@DisableCachingByDefault(because = "Verification of live build structure emits no reusable output")
|
||||
public abstract class VerifyCleanArchitectureDependenciesTask extends DefaultTask {
|
||||
|
||||
@InputFile
|
||||
public abstract RegularFileProperty getRegistryFile();
|
||||
|
||||
@Input
|
||||
public abstract ListProperty<String> getRegistryViolations();
|
||||
|
||||
/** Every leaf the build declares. */
|
||||
@Input
|
||||
public abstract SetProperty<String> getDeclaredModules();
|
||||
|
||||
/** Every module the registry governs. */
|
||||
@Input
|
||||
public abstract ListProperty<String> getGovernedModules();
|
||||
|
||||
/**
|
||||
* Build scripts under the Gradle root that no registry entry owns. The settings plugin includes
|
||||
* registered modules only, so such a leaf never reaches {@link #getDeclaredModules()} and the
|
||||
* comparison below cannot see it (review 2026-11-01 08-05).
|
||||
*/
|
||||
@Input
|
||||
public abstract ListProperty<String> getUnregisteredBuildScripts();
|
||||
|
||||
@TaskAction
|
||||
public void verifyDependencies() {
|
||||
List<String> registryViolations = getRegistryViolations().get();
|
||||
if (!registryViolations.isEmpty()) {
|
||||
throw new GradleException(
|
||||
"config/architecture/modules.json declares impossible edges:\n "
|
||||
+ String.join("\n ", registryViolations));
|
||||
}
|
||||
|
||||
List<String> unregistered = getUnregisteredBuildScripts().get();
|
||||
if (!unregistered.isEmpty()) {
|
||||
throw new GradleException(
|
||||
"These build scripts have no registry entry, so the build does not include them and no"
|
||||
+ " gate compiles or tests them. Register each in config/architecture/modules.json"
|
||||
+ " or delete it:\n "
|
||||
+ String.join("\n ", unregistered));
|
||||
}
|
||||
|
||||
Set<String> declared = getDeclaredModules().get();
|
||||
Set<String> governed = new HashSet<>(getGovernedModules().get());
|
||||
Set<String> missingFromBuild = new TreeSet<>(governed);
|
||||
missingFromBuild.removeAll(declared);
|
||||
Set<String> missingFromPolicy = new TreeSet<>(declared);
|
||||
missingFromPolicy.removeAll(governed);
|
||||
if (!missingFromBuild.isEmpty()) {
|
||||
throw new GradleException(
|
||||
"Clean Architecture dependency policy references missing Gradle modules "
|
||||
+ missingFromBuild
|
||||
+ ". Declared modules are "
|
||||
+ new TreeSet<>(declared)
|
||||
+ ".");
|
||||
}
|
||||
if (!missingFromPolicy.isEmpty()) {
|
||||
throw new GradleException(
|
||||
"Gradle modules "
|
||||
+ missingFromPolicy
|
||||
+ " are not covered by verifyCleanArchitectureDependencies. Add an explicit dependency"
|
||||
+ " policy before using them.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package dev.caskeleton.buildlogic.architecture;
|
||||
|
||||
import dev.caskeleton.buildlogic.ResolvedComponents;
|
||||
import java.util.HashSet;
|
||||
import java.util.Set;
|
||||
import java.util.TreeSet;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.artifacts.component.ProjectComponentIdentifier;
|
||||
import org.gradle.api.artifacts.result.ResolvedComponentResult;
|
||||
import org.gradle.api.provider.Property;
|
||||
import org.gradle.api.provider.SetProperty;
|
||||
import org.gradle.api.tasks.Input;
|
||||
import org.gradle.api.tasks.Internal;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.gradle.work.DisableCachingByDefault;
|
||||
|
||||
/**
|
||||
* One module's own dependency-direction check, run by the project that owns the configurations.
|
||||
*
|
||||
* <p>This used to be a loop inside the root task, which reached into every other project and
|
||||
* resolved its {@code compileClasspath}. That is the one thing a task must not do: a configuration
|
||||
* belongs to its project, and resolving it from somewhere else asks Gradle for state it holds under
|
||||
* another project's lock. With {@code org.gradle.parallel=true} that is not a style objection — the
|
||||
* root task failed outright, which is why the flag was turned back off rather than the verification
|
||||
* moved. Here the task and the configurations are in the same project, so the check costs the build
|
||||
* nothing to parallelise.
|
||||
*
|
||||
* <p>The task keeps no {@code Configuration}. It keeps the declared project edges as strings and the
|
||||
* compile classpath's resolved root component, both established while the owning project is
|
||||
* configuring. Holding the configurations themselves is what made this task unstorable in the
|
||||
* configuration cache.
|
||||
*
|
||||
* <p>The root task keeps what is genuinely repository-wide — the registry's own consistency, and
|
||||
* whether the set of governed modules matches the set of declared ones — and depends on every one of
|
||||
* these.
|
||||
*/
|
||||
@DisableCachingByDefault(because = "Verification inspects live declarations and a resolved classpath")
|
||||
public abstract class VerifyModuleDependencyDirectionTask extends DefaultTask {
|
||||
|
||||
/** The registry name of the module this task governs. */
|
||||
@Input
|
||||
public abstract Property<String> getModuleName();
|
||||
|
||||
/** The module ids this module's registry entry permits. */
|
||||
@Input
|
||||
public abstract SetProperty<String> getAllowedDependencies();
|
||||
|
||||
/** Project paths this module declares in {@code api/implementation/compileOnly/runtimeOnly}. */
|
||||
@Input
|
||||
public abstract SetProperty<String> getDeclaredProjectEdges();
|
||||
|
||||
/** Root of this module's resolved {@code compileClasspath}. */
|
||||
@Internal
|
||||
public abstract Property<ResolvedComponentResult> getCompileClasspathRoot();
|
||||
|
||||
@TaskAction
|
||||
public void verify() {
|
||||
String moduleName = getModuleName().get();
|
||||
Set<String> allowed = getAllowedDependencies().get();
|
||||
|
||||
Set<String> actual = new HashSet<>(getDeclaredProjectEdges().get());
|
||||
// Declared edges are not the whole story: an `api(project(...))` two leaves away is visible to
|
||||
// this module's compiler and is therefore a real edge, whatever this build file says.
|
||||
for (ResolvedComponentResult component :
|
||||
ResolvedComponents.reachableFrom(getCompileClasspathRoot().get())) {
|
||||
if (component.getId() instanceof ProjectComponentIdentifier project) {
|
||||
String projectPath = project.getProjectPath().replaceFirst("^:", "");
|
||||
if (!projectPath.equals(moduleName)) {
|
||||
actual.add(projectPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Set<String> forbidden = new TreeSet<>(actual);
|
||||
forbidden.removeAll(allowed);
|
||||
if (!forbidden.isEmpty()) {
|
||||
throw new GradleException(
|
||||
"Module ':"
|
||||
+ moduleName
|
||||
+ "' has forbidden project dependencies "
|
||||
+ forbidden
|
||||
+ ". Allowed dependencies are "
|
||||
+ new TreeSet<>(allowed)
|
||||
+ ".\nDirect and compile-visible production project edges must be explicitly"
|
||||
+ " registered.");
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
package dev.caskeleton.buildlogic.architecture;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Set;
|
||||
import org.gradle.api.DefaultTask;
|
||||
import org.gradle.api.GradleException;
|
||||
import org.gradle.api.file.ConfigurableFileCollection;
|
||||
import org.gradle.api.file.DirectoryProperty;
|
||||
import org.gradle.api.tasks.InputFiles;
|
||||
import org.gradle.api.tasks.Internal;
|
||||
import org.gradle.api.tasks.PathSensitive;
|
||||
import org.gradle.api.tasks.PathSensitivity;
|
||||
import org.gradle.api.tasks.TaskAction;
|
||||
import org.gradle.work.DisableCachingByDefault;
|
||||
|
||||
@DisableCachingByDefault(because = "Verification consults Git ignore rules")
|
||||
public abstract class VerifyNoIgnoredSourcePackagesTask extends DefaultTask {
|
||||
private static final Set<String> OUTPUT_DIRECTORY_NAMES =
|
||||
Set.of("build", "out", "target", "bin", "classes");
|
||||
|
||||
@InputFiles
|
||||
@PathSensitive(PathSensitivity.RELATIVE)
|
||||
public abstract ConfigurableFileCollection getSourceRoots();
|
||||
|
||||
@Internal
|
||||
public abstract DirectoryProperty getBuildRoot();
|
||||
|
||||
@TaskAction
|
||||
public void verifySourcePackages() {
|
||||
List<String> violations = new ArrayList<>();
|
||||
List<File> sourceFiles = new ArrayList<>();
|
||||
for (File sourceRoot : getSourceRoots().getFiles()) {
|
||||
if (!sourceRoot.isDirectory()) {
|
||||
continue;
|
||||
}
|
||||
try (var paths = Files.walk(sourceRoot.toPath())) {
|
||||
paths
|
||||
.filter(Files::isRegularFile)
|
||||
.filter(path -> path.getFileName().toString().endsWith(".java"))
|
||||
.forEach(
|
||||
path -> {
|
||||
File candidate = path.toFile();
|
||||
sourceFiles.add(candidate);
|
||||
var relative = sourceRoot.toPath().relativize(path);
|
||||
for (int index = 0; index < relative.getNameCount() - 1; index++) {
|
||||
String segment = relative.getName(index).toString();
|
||||
if (OUTPUT_DIRECTORY_NAMES.contains(segment)) {
|
||||
violations.add(
|
||||
candidate
|
||||
+ ": package segment '"
|
||||
+ segment
|
||||
+ "' collides with a build output directory name");
|
||||
}
|
||||
}
|
||||
});
|
||||
} catch (IOException exception) {
|
||||
throw new GradleException("verifyNoIgnoredSourcePackages: cannot scan " + sourceRoot, exception);
|
||||
}
|
||||
}
|
||||
if (sourceFiles.isEmpty()) {
|
||||
throw new GradleException(
|
||||
"verifyNoIgnoredSourcePackages: found no Java sources at all; the gate would pass vacuously.");
|
||||
}
|
||||
|
||||
File repositoryRoot = checkoutRoot(getBuildRoot().get().getAsFile());
|
||||
if (repositoryRoot == null) {
|
||||
getLogger().lifecycle("verifyNoIgnoredSourcePackages: not a Git checkout; naming rule only.");
|
||||
} else {
|
||||
String stdin = sourceFiles.stream().map(File::getPath).collect(java.util.stream.Collectors.joining("\n"));
|
||||
String output = checkIgnore(repositoryRoot, stdin);
|
||||
for (String line : output.lines().filter(value -> !value.isBlank()).toList()) {
|
||||
String[] parts = line.split("\\t", -1);
|
||||
String rule = parts.length > 1 ? parts[0] : "(unknown rule)";
|
||||
String path = parts.length > 1 ? String.join("\t", java.util.Arrays.copyOfRange(parts, 1, parts.length)) : line;
|
||||
violations.add(path + ": ignored by " + rule + "; it will not survive a fresh checkout");
|
||||
}
|
||||
}
|
||||
|
||||
if (!violations.isEmpty()) {
|
||||
throw new GradleException(
|
||||
"verifyNoIgnoredSourcePackages: "
|
||||
+ violations.size()
|
||||
+ " source file(s) Git cannot carry:\n "
|
||||
+ String.join("\n ", violations));
|
||||
}
|
||||
getLogger()
|
||||
.lifecycle(
|
||||
"verifyNoIgnoredSourcePackages: OK — {} Java sources are all committable.",
|
||||
sourceFiles.size());
|
||||
}
|
||||
|
||||
/**
|
||||
* The nearest directory at or above {@code start} holding {@code .git} (a directory, or the file
|
||||
* a worktree has), or {@code null} for an exported source tree. Decided on the file system rather
|
||||
* than by asking Git, so that Git failing inside a checkout cannot read as "not a checkout".
|
||||
*/
|
||||
private static File checkoutRoot(File start) {
|
||||
for (File directory = start.getAbsoluteFile(); directory != null; directory = directory.getParentFile()) {
|
||||
if (new File(directory, ".git").exists()) {
|
||||
return directory;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Git's ignore verdicts for the paths on {@code stdin}. Fails closed: inside a checkout, a git that
|
||||
* cannot run or exits with anything but 0 (some path ignored) or 1 (none ignored) is an error, not
|
||||
* an empty answer — an empty answer is how the gate used to pass without asking.
|
||||
*/
|
||||
private String checkIgnore(File repositoryRoot, String stdin) {
|
||||
List<String> command =
|
||||
List.of("git", "-C", repositoryRoot.getPath(), "check-ignore", "--no-index", "-v", "--stdin");
|
||||
Process process;
|
||||
try {
|
||||
process = new ProcessBuilder(command).start();
|
||||
} catch (IOException unavailable) {
|
||||
throw new GradleException(
|
||||
"verifyNoIgnoredSourcePackages: "
|
||||
+ repositoryRoot
|
||||
+ " is a Git checkout but git could not run: "
|
||||
+ unavailable.getMessage(),
|
||||
unavailable);
|
||||
}
|
||||
try {
|
||||
try (var input = process.getOutputStream()) {
|
||||
input.write(stdin.getBytes(StandardCharsets.UTF_8));
|
||||
} catch (IOException exitedEarly) {
|
||||
// git stopped reading, which it does when it fails; its exit code below says why.
|
||||
}
|
||||
String output = new String(process.getInputStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
String error = new String(process.getErrorStream().readAllBytes(), StandardCharsets.UTF_8);
|
||||
int exitCode = process.waitFor();
|
||||
if (exitCode != 0 && exitCode != 1) {
|
||||
throw new GradleException(
|
||||
"verifyNoIgnoredSourcePackages: `git check-ignore` exited "
|
||||
+ exitCode
|
||||
+ " inside the Git checkout at "
|
||||
+ repositoryRoot
|
||||
+ ": "
|
||||
+ error.strip());
|
||||
}
|
||||
return output;
|
||||
} catch (IOException unreadable) {
|
||||
throw new GradleException(
|
||||
"verifyNoIgnoredSourcePackages: could not read `git check-ignore` output", unreadable);
|
||||
} catch (InterruptedException interrupted) {
|
||||
Thread.currentThread().interrupt();
|
||||
throw new GradleException("verifyNoIgnoredSourcePackages: git command interrupted", interrupted);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user