@nx/gradle 23.2.0-beta.1 → 23.2.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -7,9 +7,9 @@
7
7
 
8
8
  <div style="text-align: center;">
9
9
 
10
- [![License](https://img.shields.io/npm/l/@nx/workspace.svg?style=flat-square)]()
10
+ [![License](https://img.shields.io/npm/l/@nx/workspace.svg?style=flat-square)](<>)
11
11
  [![NPM Version](https://badge.fury.io/js/nx.svg)](https://www.npmjs.com/package/nx)
12
- [![Semantic Release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)]()
12
+ [![Semantic Release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](<>)
13
13
  [![Commitizen friendly](https://img.shields.io/badge/commitizen-friendly-brightgreen.svg)](http://commitizen.github.io/cz-cli/)
14
14
  [![Join us on the Official Nx Discord Server](https://img.shields.io/discord/1143497901675401286?label=discord)](https://go.nx.dev/community)
15
15
  [![Nx Sandboxing](https://staging.nx.app/workspaces/62d013ea0852fe0a2df74438/sandbox-badge.svg)](https://nx.dev/docs/features/ci-features/sandboxing)
@@ -1,7 +1,6 @@
1
1
  import { ExecutorContext, ProjectGraphProjectNode, TaskGraph } from '@nx/devkit';
2
- import { RunCommandsOptions } from 'nx/src/executors/run-commands/run-commands.impl';
3
- import { TaskResult } from 'nx/src/config/misc-interfaces';
4
2
  import { GradleExecutorSchema } from './schema';
3
+ import { RunCommandsOptions, TaskResult } from '@nx/devkit/internal';
5
4
  export declare const batchRunnerPath: string;
6
5
  export default function gradleBatch(taskGraph: TaskGraph, inputs: Record<string, GradleExecutorSchema>, overrides: RunCommandsOptions, context: ExecutorContext): AsyncGenerator<{
7
6
  task: string;
@@ -1,11 +1,10 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.default = gradleExecutor;
4
- const tslib_1 = require("tslib");
5
4
  const devkit_1 = require("@nx/devkit");
6
5
  const exec_gradle_1 = require("../../utils/exec-gradle");
7
6
  const node_path_1 = require("node:path");
8
- const run_commands_impl_1 = tslib_1.__importDefault(require("nx/src/executors/run-commands/run-commands.impl"));
7
+ const internal_1 = require("@nx/devkit/internal");
9
8
  const get_exclude_task_1 = require("./get-exclude-task");
10
9
  async function gradleExecutor(options, context) {
11
10
  let projectRoot = context.projectGraph.nodes[context.projectName]?.data?.root ?? context.root;
@@ -56,7 +55,7 @@ async function gradleExecutor(options, context) {
56
55
  });
57
56
  }
58
57
  try {
59
- const { success } = await (0, run_commands_impl_1.default)({
58
+ const { success } = await (0, internal_1.runCommandsExecutor)({
60
59
  command: `${gradlewPath} ${options.taskName}`,
61
60
  cwd: (0, node_path_1.dirname)(gradlewPath),
62
61
  args: args,
@@ -3,8 +3,7 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.ciWorkflowGenerator = ciWorkflowGenerator;
4
4
  const devkit_1 = require("@nx/devkit");
5
5
  const path_1 = require("path");
6
- const nx_cloud_utils_1 = require("nx/src/utils/nx-cloud-utils");
7
- const default_base_1 = require("nx/src/utils/default-base");
6
+ const internal_1 = require("@nx/devkit/internal");
8
7
  function getCiCommands(ci) {
9
8
  switch (ci) {
10
9
  case 'circleci': {
@@ -54,13 +53,13 @@ function getTemplateData(tree, options) {
54
53
  const { name: workflowName, fileName: workflowFileName } = (0, devkit_1.names)(options.name);
55
54
  let nxCloudHost = 'nx.app';
56
55
  try {
57
- const nxCloudUrl = (0, nx_cloud_utils_1.getNxCloudUrl)((0, devkit_1.readNxJson)(tree));
56
+ const nxCloudUrl = (0, internal_1.getNxCloudUrl)((0, devkit_1.readNxJson)(tree));
58
57
  nxCloudHost = new URL(nxCloudUrl).host;
59
58
  }
60
59
  catch { }
61
- const mainBranch = (0, default_base_1.deduceDefaultBase)();
60
+ const mainBranch = (0, internal_1.deduceDefaultBase)();
62
61
  const commands = options.commands ?? getCiCommands(options.ci);
63
- const connectedToCloud = (0, nx_cloud_utils_1.isNxCloudUsed)((0, devkit_1.readNxJson)(tree));
62
+ const connectedToCloud = (0, internal_1.isNxCloudUsed)((0, devkit_1.readNxJson)(tree));
64
63
  return {
65
64
  workflowName,
66
65
  workflowFileName,
@@ -205,14 +205,15 @@ async function addNxProjectGraphPluginToBuildGradle(gradleFilePath, buildGradleC
205
205
  if (!hasPluginViaAlias) {
206
206
  const applyPluginPattern = versionCatalogPluginAccessor
207
207
  ? new RegExp(`\\s*plugin\\(${versionCatalogPluginAccessor.replace(/\./g, '\\.')}\\)`)
208
- : new RegExp(`\\s*plugin\\(["']${versions_1.gradleProjectGraphPluginName}["']\\)`);
208
+ : // Both DSL forms, so a re-run doesn't append a duplicate apply.
209
+ new RegExp(`\\s*plugin\\s*[:(]\\s*["']${versions_1.gradleProjectGraphPluginName.replace(/\./g, '\\.')}["']`);
209
210
  if (buildGradleContent.includes('allprojects {')) {
210
211
  if (!applyPluginPattern.test(buildGradleContent)) {
211
212
  const applyPlugin = versionCatalogPluginAccessor
212
213
  ? `plugin(${versionCatalogPluginAccessor})`
213
214
  : isKotlinDsl
214
215
  ? `plugin("${versions_1.gradleProjectGraphPluginName}")`
215
- : `plugin "${versions_1.gradleProjectGraphPluginName}"`;
216
+ : `plugin: "${versions_1.gradleProjectGraphPluginName}"`;
216
217
  buildGradleContent = buildGradleContent.replace(/allprojects\s*\{/, `allprojects {\n apply ${applyPlugin}`);
217
218
  }
218
219
  }
@@ -0,0 +1,2 @@
1
+ import { Tree } from '@nx/devkit';
2
+ export default function update(tree: Tree): Promise<void>;
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.default = update;
4
+ const devkit_1 = require("@nx/devkit");
5
+ const has_gradle_plugin_1 = require("../../utils/has-gradle-plugin");
6
+ const gradle_project_graph_plugin_utils_1 = require("../../generators/init/gradle-project-graph-plugin-utils");
7
+ const version_catalog_ast_utils_1 = require("../../utils/version-catalog-ast-utils");
8
+ /* Change the plugin version to 0.1.25
9
+ */
10
+ async function update(tree) {
11
+ const nxJson = (0, devkit_1.readNxJson)(tree);
12
+ if (!nxJson) {
13
+ return;
14
+ }
15
+ if (!(0, has_gradle_plugin_1.hasGradlePlugin)(tree)) {
16
+ return;
17
+ }
18
+ const gradlePluginVersionToUpdate = '0.1.25';
19
+ // Update version in version catalogs using AST-based approach to preserve formatting
20
+ await (0, version_catalog_ast_utils_1.updateNxPluginVersionInCatalogsAst)(tree, gradlePluginVersionToUpdate);
21
+ // Then update in build.gradle(.kts) files
22
+ await (0, gradle_project_graph_plugin_utils_1.addNxProjectGraphPlugin)(tree, gradlePluginVersionToUpdate);
23
+ }
@@ -0,0 +1,21 @@
1
+ #### Change dev.nx.gradle.project-graph to version 0.1.25
2
+
3
+ Change dev.nx.gradle.project-graph to version 0.1.25 in build file
4
+
5
+ #### Sample Code Changes
6
+
7
+ ##### Before
8
+
9
+ ```text title="build.gradle"
10
+ plugins {
11
+ id "dev.nx.gradle.project-graph" version "0.1.24"
12
+ }
13
+ ```
14
+
15
+ ##### After
16
+
17
+ ```text title="build.gradle"
18
+ plugins {
19
+ id "dev.nx.gradle.project-graph" version "0.1.25"
20
+ }
21
+ ```
@@ -5,10 +5,10 @@ const devkit_1 = require("@nx/devkit");
5
5
  const node_path_1 = require("node:path");
6
6
  const get_project_graph_from_gradle_plugin_1 = require("./utils/get-project-graph-from-gradle-plugin");
7
7
  const split_config_files_1 = require("../utils/split-config-files");
8
- const workspace_context_1 = require("nx/src/utils/workspace-context");
9
8
  const node_fs_1 = require("node:fs");
9
+ const internal_1 = require("@nx/devkit/internal");
10
10
  const createDependencies = async (options, context) => {
11
- const files = await (0, workspace_context_1.globWithWorkspaceContext)(devkit_1.workspaceRoot, Array.from(split_config_files_1.GRADLEW_FILES));
11
+ const files = await (0, internal_1.globWithWorkspaceContext)(devkit_1.workspaceRoot, Array.from(split_config_files_1.GRADLEW_FILES));
12
12
  const { gradlewFiles } = (0, split_config_files_1.splitConfigFiles)(files);
13
13
  await (0, get_project_graph_from_gradle_plugin_1.populateProjectGraph)(context.workspaceRoot, gradlewFiles.map((file) => (0, node_path_1.join)(devkit_1.workspaceRoot, file)), options);
14
14
  const { dependencies: dependenciesFromReport } = (0, get_project_graph_from_gradle_plugin_1.getCurrentProjectGraphReport)();
@@ -16,7 +16,8 @@ const createDependencies = async (options, context) => {
16
16
  dependenciesFromReport.forEach((dependencyFromPlugin) => {
17
17
  try {
18
18
  // Report paths are workspace-relative with `/` separators
19
- const sourceProjectName = Object.values(context.projects).find((project) => dependencyFromPlugin.source === project.root)?.name ?? dependencyFromPlugin.source;
19
+ const sourceProject = Object.values(context.projects).find((project) => dependencyFromPlugin.source === project.root);
20
+ const sourceProjectName = sourceProject?.name ?? dependencyFromPlugin.source;
20
21
  const targetProjectName = Object.values(context.projects).find((project) => dependencyFromPlugin.target === project.root)?.name ?? dependencyFromPlugin.target;
21
22
  const sourceFile = dependencyFromPlugin.sourceFile;
22
23
  if (!sourceProjectName ||
@@ -24,12 +25,21 @@ const createDependencies = async (options, context) => {
24
25
  !(0, node_fs_1.existsSync)((0, node_path_1.join)(devkit_1.workspaceRoot, sourceFile))) {
25
26
  return;
26
27
  }
27
- const dependency = {
28
- source: sourceProjectName,
29
- target: targetProjectName,
30
- type: devkit_1.DependencyType.static,
31
- sourceFile,
32
- };
28
+ // An ancestor-configured project's build file lies outside it, and Nx rejects a foreign
29
+ // sourceFile — record implicit rather than drop.
30
+ const ownsSourceFile = !!sourceProject && (0, node_path_1.dirname)(sourceFile) === sourceProject.root;
31
+ const dependency = ownsSourceFile
32
+ ? {
33
+ source: sourceProjectName,
34
+ target: targetProjectName,
35
+ type: devkit_1.DependencyType.static,
36
+ sourceFile,
37
+ }
38
+ : {
39
+ source: sourceProjectName,
40
+ target: targetProjectName,
41
+ type: devkit_1.DependencyType.implicit,
42
+ };
33
43
  (0, devkit_1.validateDependency)(dependency, context);
34
44
  dependencies.push(dependency);
35
45
  }
@@ -4,9 +4,6 @@ exports.makeCreateNodesForGradleConfigFile = exports.createNodesV2 = exports.cre
4
4
  const internal_1 = require("@nx/devkit/internal");
5
5
  const devkit_1 = require("@nx/devkit");
6
6
  const node_path_1 = require("node:path");
7
- const cache_directory_1 = require("nx/src/utils/cache-directory");
8
- const plugin_cache_utils_1 = require("nx/src/utils/plugin-cache-utils");
9
- const file_hasher_1 = require("nx/src/hasher/file-hasher");
10
7
  const split_config_files_1 = require("../utils/split-config-files");
11
8
  const get_project_graph_from_gradle_plugin_1 = require("./utils/get-project-graph-from-gradle-plugin");
12
9
  const gradle_plugin_options_1 = require("./utils/gradle-plugin-options");
@@ -70,68 +67,54 @@ function extractNxConfigOnly(project) {
70
67
  exports.createNodes = [
71
68
  split_config_files_1.gradleConfigAndTestGlob,
72
69
  async (files, options, context) => {
73
- const { buildFiles: buildFilesFromSplitConfigFiles, gradlewFiles } = (0, split_config_files_1.splitConfigFiles)(files);
74
- const optionsHash = (0, file_hasher_1.hashObject)(options);
75
- const cachePath = (0, node_path_1.join)(cache_directory_1.workspaceDataDirectory, `gradle-${optionsHash}.hash`);
76
- const pluginCache = new plugin_cache_utils_1.PluginCache(cachePath);
70
+ const { gradlewFiles } = (0, split_config_files_1.splitConfigFiles)(files);
77
71
  await (0, get_project_graph_from_gradle_plugin_1.populateProjectGraph)(context.workspaceRoot, gradlewFiles.map((f) => (0, node_path_1.join)(context.workspaceRoot, f)), options);
78
72
  const report = (0, get_project_graph_from_gradle_plugin_1.getCurrentProjectGraphReport)();
79
- const { nodes, externalNodes = {}, buildFiles = [] } = report;
80
- // Combine buildFilesFromSplitConfigFiles and buildFiles, making each value distinct
81
- const allBuildFiles = Array.from(new Set([...buildFilesFromSplitConfigFiles, ...buildFiles]));
82
- try {
83
- const results = [];
84
- const normalizedOptions = (0, gradle_plugin_options_1.normalizeOptions)(options);
85
- const buildFileProjectRoots = allBuildFiles.map((f) => (0, node_path_1.dirname)(f));
86
- const buildFileHashes = await (0, internal_1.calculateHashesForCreateNodes)(buildFileProjectRoots, normalizedOptions ?? {}, context);
87
- for (let i = 0; i < allBuildFiles.length; i++) {
88
- const gradleFilePath = allBuildFiles[i];
89
- const projectRoot = buildFileProjectRoots[i];
90
- const hash = buildFileHashes[i];
91
- // Get project from cache or nodes (report keys are workspace-relative
92
- // with `/` separators)
93
- if (!pluginCache.has(hash)) {
94
- const nodeProject = nodes[(0, devkit_1.normalizePath)(projectRoot)];
95
- if (nodeProject) {
96
- pluginCache.set(hash, nodeProject);
97
- }
98
- }
99
- const project = pluginCache.get(hash);
100
- if (!project) {
101
- continue;
102
- }
103
- const normalizedProjectRoot = (0, devkit_1.normalizePath)(projectRoot);
104
- // Result 1: Gradle-detected configuration (without nxConfig)
105
- const gradleConfig = stripNxConfig(project);
106
- gradleConfig.root = normalizedProjectRoot;
73
+ const { nodes, externalNodes = {}, buildFileByProjectRoot = {} } = report;
74
+ const results = [];
75
+ // Roots outside the workspace stay absolute in the report and cannot become Nx projects.
76
+ const projectRoots = Object.keys(nodes)
77
+ .map((root) => (0, devkit_1.normalizePath)(root))
78
+ .filter((root) => !(0, node_path_1.isAbsolute)(root) && !root.startsWith('../'));
79
+ for (const normalizedProjectRoot of projectRoots) {
80
+ const gradleFilePath = buildFileByProjectRoot[normalizedProjectRoot];
81
+ if (!gradleFilePath) {
82
+ // No build file anywhere up the ancestry, or an ancestor configures it and the plugin
83
+ // predates effectiveBuildFile.
84
+ devkit_1.logger.verbose(`[@nx/gradle] no build file reported for "${normalizedProjectRoot}"; skipping it. Add a build file (or run @nx/gradle:init), or upgrade dev.nx.gradle.project-graph if projects are missing.`);
85
+ continue;
86
+ }
87
+ const project = nodes[normalizedProjectRoot];
88
+ if (!project) {
89
+ continue;
90
+ }
91
+ // Result 1: Gradle-detected configuration (without nxConfig)
92
+ const gradleConfig = stripNxConfig(project);
93
+ gradleConfig.root = normalizedProjectRoot;
94
+ results.push([
95
+ gradleFilePath,
96
+ {
97
+ projects: {
98
+ [normalizedProjectRoot]: gradleConfig,
99
+ },
100
+ externalNodes: externalNodes,
101
+ },
102
+ ]);
103
+ // Result 2: nxConfig-only configuration (if exists)
104
+ const nxConfigOnly = extractNxConfigOnly(project);
105
+ if (nxConfigOnly) {
106
+ nxConfigOnly.root = normalizedProjectRoot;
107
107
  results.push([
108
108
  gradleFilePath,
109
109
  {
110
110
  projects: {
111
- [normalizedProjectRoot]: gradleConfig,
111
+ [normalizedProjectRoot]: nxConfigOnly,
112
112
  },
113
- externalNodes: externalNodes,
114
113
  },
115
114
  ]);
116
- // Result 2: nxConfig-only configuration (if exists)
117
- const nxConfigOnly = extractNxConfigOnly(project);
118
- if (nxConfigOnly) {
119
- nxConfigOnly.root = normalizedProjectRoot;
120
- results.push([
121
- gradleFilePath,
122
- {
123
- projects: {
124
- [normalizedProjectRoot]: nxConfigOnly,
125
- },
126
- },
127
- ]);
128
- }
129
115
  }
130
- return results;
131
- }
132
- finally {
133
- pluginCache.writeToDisk();
134
116
  }
117
+ return results;
135
118
  },
136
119
  ];
137
120
  /**
@@ -7,6 +7,11 @@ export interface ProjectGraphReport {
7
7
  dependencies: Array<StaticDependency>;
8
8
  externalNodes?: Record<string, ProjectGraphExternalNode>;
9
9
  buildFiles?: string[];
10
+ /**
11
+ * Project root -> the build file that configures it, derived here (not plugin-reported). Flat
12
+ * `buildFiles` loses the pairing; no entry means the report named no build file.
13
+ */
14
+ buildFileByProjectRoot?: Record<string, string>;
10
15
  }
11
16
  export interface ProjectGraphReportCache extends ProjectGraphReport {
12
17
  hash: string;
@@ -8,13 +8,11 @@ exports.processNxProjectGraph = processNxProjectGraph;
8
8
  const node_fs_1 = require("node:fs");
9
9
  const node_path_1 = require("node:path");
10
10
  const devkit_1 = require("@nx/devkit");
11
- const workspace_context_1 = require("nx/src/utils/workspace-context");
12
11
  const split_config_files_1 = require("../../utils/split-config-files");
13
12
  const versions_1 = require("../../utils/versions");
14
- const cache_directory_1 = require("nx/src/utils/cache-directory");
15
13
  const get_project_graph_lines_1 = require("./get-project-graph-lines");
16
14
  const gradle_plugin_options_1 = require("./gradle-plugin-options");
17
- const devkit_internals_1 = require("nx/src/devkit-internals");
15
+ const internal_1 = require("@nx/devkit/internal");
18
16
  function readProjectGraphReportCache(cachePath, hash) {
19
17
  const projectGraphReportCache = (0, node_fs_1.existsSync)(cachePath)
20
18
  ? (0, devkit_1.readJsonFile)(cachePath)
@@ -43,7 +41,7 @@ function writeProjectGraphReportToCache(cachePath, results, hash) {
43
41
  }
44
42
  }
45
43
  let projectGraphReportCache;
46
- let projectGraphReportCachePath = (0, node_path_1.join)(cache_directory_1.workspaceDataDirectory, 'gradle-nodes.hash');
44
+ let projectGraphReportCachePath = (0, node_path_1.join)(internal_1.workspaceDataDirectory, 'gradle-nodes.hash');
47
45
  function getCurrentProjectGraphReport() {
48
46
  if (!projectGraphReportCache) {
49
47
  throw new devkit_1.AggregateCreateNodesError([
@@ -72,8 +70,8 @@ function getCurrentBuildFiles() {
72
70
  async function populateProjectGraph(workspaceRoot, gradlewFiles, options) {
73
71
  const normalizedOptions = (0, gradle_plugin_options_1.normalizeOptions)(options);
74
72
  const gradleConfigHash = (0, devkit_1.hashArray)([
75
- await (0, workspace_context_1.hashWithWorkspaceContext)(workspaceRoot, [split_config_files_1.gradleConfigAndTestGlob]),
76
- (0, devkit_internals_1.hashObject)(normalizedOptions),
73
+ await (0, internal_1.hashWithWorkspaceContext)(workspaceRoot, [split_config_files_1.gradleConfigAndTestGlob]),
74
+ (0, internal_1.hashObject)(normalizedOptions),
77
75
  process.env.CI,
78
76
  ]);
79
77
  const cached = readProjectGraphReportCache(projectGraphReportCachePath, gradleConfigHash);
@@ -120,6 +118,7 @@ function processNxProjectGraph(projectGraphLines) {
120
118
  externalNodes: {},
121
119
  };
122
120
  const allBuildFiles = new Set();
121
+ const buildFileByProjectRoot = {};
123
122
  while (index < projectGraphLines.length) {
124
123
  const line = projectGraphLines[index].trim();
125
124
  if (line.startsWith('> Task ') && line.endsWith(':nxProjectGraph')) {
@@ -151,11 +150,20 @@ function processNxProjectGraph(projectGraphLines) {
151
150
  }
152
151
  if (projectGraphReportJson.buildFiles) {
153
152
  projectGraphReportJson.buildFiles.forEach((buildFile) => allBuildFiles.add(buildFile));
153
+ // One report describes one project, so its single build file is that project's.
154
+ const [buildFile] = projectGraphReportJson.buildFiles;
155
+ if (buildFile) {
156
+ for (const projectRoot of Object.keys(projectGraphReportJson.nodes ?? {})) {
157
+ buildFileByProjectRoot[projectRoot] = buildFile;
158
+ }
159
+ }
154
160
  }
155
161
  }
156
162
  index++;
157
163
  }
158
164
  // Convert Set to array for the final result
159
165
  projectGraphReportForAllProjects.buildFiles = Array.from(allBuildFiles);
166
+ projectGraphReportForAllProjects.buildFileByProjectRoot =
167
+ buildFileByProjectRoot;
160
168
  return projectGraphReportForAllProjects;
161
169
  }
@@ -4,9 +4,20 @@ exports.cancelPendingProjectGraphRequest = cancelPendingProjectGraphRequest;
4
4
  exports.getGraphTimeoutMs = getGraphTimeoutMs;
5
5
  exports.getNxProjectGraphLines = getNxProjectGraphLines;
6
6
  const devkit_1 = require("@nx/devkit");
7
- const devkit_internals_1 = require("nx/src/devkit-internals");
8
7
  const exec_gradle_1 = require("../../utils/exec-gradle");
9
- const DEFAULT_GRAPH_TIMEOUT_SECONDS = (0, devkit_internals_1.isCI)() ? 600 : 120;
8
+ const internal_1 = require("@nx/devkit/internal");
9
+ const DEFAULT_GRAPH_TIMEOUT_SECONDS = (0, internal_1.isCI)() ? 600 : 120;
10
+ // setTimeout silently clamps a delay past the 32-bit signed max to 1ms, which
11
+ // would abort immediately — the opposite of what a large value asks for.
12
+ const MAX_TIMEOUT_MS = 2 ** 31 - 1;
13
+ const GRADLE_LOCK_TIMEOUT_MESSAGE = 'Timeout waiting to lock';
14
+ // Gradle gives up on a contended lock (e.g. buildLogic.lock held by another
15
+ // build in the same project) after ~60s, so at the 120s local default one wait
16
+ // consumes the budget and the deadline guard below refuses a retry; retries
17
+ // engage on CI (600s) or a raised NX_GRADLE_PROJECT_GRAPH_TIMEOUT. Do not relax
18
+ // that `>=` to `>` — it refuses the borderline attempt rather than letting the
19
+ // abort fire mid-retry and replace the lock message with a generic timeout.
20
+ const MAX_LOCK_TIMEOUT_RETRIES = 2;
10
21
  let currentAbortController;
11
22
  /**
12
23
  * Cancel any in-flight Gradle project graph process.
@@ -23,35 +34,65 @@ function getGraphTimeoutMs() {
23
34
  if (envTimeout) {
24
35
  const parsed = Number(envTimeout);
25
36
  if (!Number.isNaN(parsed) && parsed > 0) {
26
- return parsed * 1000;
37
+ return Math.min(parsed * 1000, MAX_TIMEOUT_MS);
27
38
  }
28
39
  }
29
40
  return DEFAULT_GRAPH_TIMEOUT_SECONDS * 1000;
30
41
  }
42
+ function isGradleLockTimeout(e) {
43
+ return String(e).includes(GRADLE_LOCK_TIMEOUT_MESSAGE);
44
+ }
45
+ async function execGradleWithLockRetry(gradlewFile, args, signal, deadline) {
46
+ for (let attempt = 0;; attempt++) {
47
+ const attemptStart = Date.now();
48
+ try {
49
+ return await (0, exec_gradle_1.execGradleAsync)(gradlewFile, args, { signal });
50
+ }
51
+ catch (e) {
52
+ if (signal.aborted ||
53
+ attempt >= MAX_LOCK_TIMEOUT_RETRIES ||
54
+ !isGradleLockTimeout(e)) {
55
+ throw e;
56
+ }
57
+ // Retry only if another full lock wait still fits in the graph timeout.
58
+ // Otherwise the timeout aborts mid-attempt and its generic message
59
+ // replaces the lock guidance the user actually needs.
60
+ const lockWaitMs = Date.now() - attemptStart;
61
+ if (Date.now() + lockWaitMs >= deadline) {
62
+ throw e;
63
+ }
64
+ devkit_1.output.warn({
65
+ title: `Gradle lock is held by another build; retrying 'nxProjectGraph' (${attempt + 1}/${MAX_LOCK_TIMEOUT_RETRIES})`,
66
+ });
67
+ }
68
+ }
69
+ }
31
70
  async function getNxProjectGraphLines(gradlewFile, gradleConfigHash, gradlePluginOptions) {
32
71
  let nxProjectGraphBuffer;
33
72
  const gradlePluginOptionsArgs = Object.entries(gradlePluginOptions ?? {})?.map(([key, value]) => `-P${key}=${value}`) ?? [];
34
73
  const timeoutMs = getGraphTimeoutMs();
35
74
  const timeoutSeconds = timeoutMs / 1000;
75
+ const deadline = Date.now() + timeoutMs;
36
76
  // Cancel any in-flight Gradle process from a previous call, then create a fresh controller.
37
77
  cancelPendingProjectGraphRequest();
38
78
  const controller = new AbortController();
39
79
  currentAbortController = controller;
40
80
  const signal = controller.signal;
41
81
  const timer = setTimeout(() => controller.abort(), timeoutMs);
82
+ const args = [
83
+ 'nxProjectGraph',
84
+ `-Phash=${gradleConfigHash}`,
85
+ '--no-configuration-cache', // disable configuration cache
86
+ '--parallel', // add parallel to improve performance
87
+ '--build-cache', // enable build cache
88
+ '--warning-mode',
89
+ 'none',
90
+ ...gradlePluginOptionsArgs,
91
+ `-PworkspaceRoot=${devkit_1.workspaceRoot}`,
92
+ process.env.NX_GRADLE_VERBOSE_LOGGING ? '--info' : '',
93
+ ];
42
94
  try {
43
- nxProjectGraphBuffer = await (0, exec_gradle_1.execGradleAsync)(gradlewFile, [
44
- 'nxProjectGraph',
45
- `-Phash=${gradleConfigHash}`,
46
- '--no-configuration-cache', // disable configuration cache
47
- '--parallel', // add parallel to improve performance
48
- '--build-cache', // enable build cache
49
- '--warning-mode',
50
- 'none',
51
- ...gradlePluginOptionsArgs,
52
- `-PworkspaceRoot=${devkit_1.workspaceRoot}`,
53
- process.env.NX_GRADLE_VERBOSE_LOGGING ? '--info' : '',
54
- ], { signal });
95
+ nxProjectGraphBuffer = await execGradleWithLockRetry(gradlewFile, args, signal, deadline);
55
96
  }
56
97
  catch (e) {
57
98
  // Cancelled by a newer populateProjectGraph call — let the caller handle it
@@ -77,6 +118,15 @@ async function getNxProjectGraphLines(gradlewFile, gradleConfigHash, gradlePlugi
77
118
  ],
78
119
  ], []);
79
120
  }
121
+ else if (isGradleLockTimeout(e)) {
122
+ throw new devkit_1.AggregateCreateNodesError([
123
+ [
124
+ gradlewFile,
125
+ new Error(`Could not run 'nxProjectGraph' Gradle task because another Gradle build is holding a lock on the project.\n` +
126
+ ` Wait for the other build to finish, or run "gradlew --stop" to stop stale Gradle daemons, then try again.\n\r${e.toString()}`),
127
+ ],
128
+ ], []);
129
+ }
80
130
  else if (e.toString()?.includes(`Task 'nxProjectGraph' not found`)) {
81
131
  throw new devkit_1.AggregateCreateNodesError([
82
132
  [
@@ -1,5 +1,5 @@
1
+ import { PluginCache } from '@nx/devkit/internal';
1
2
  import { CreateNodes, CreateNodesContext, ProjectConfiguration } from '@nx/devkit';
2
- import { PluginCache } from 'nx/src/utils/plugin-cache-utils';
3
3
  import { GradleReport } from './utils/get-gradle-report';
4
4
  export interface GradlePluginOptions {
5
5
  includeSubprojectsTasks?: boolean;
@@ -4,11 +4,7 @@ exports.createNodes = exports.makeCreateNodesForGradleConfigFile = exports.creat
4
4
  const internal_1 = require("@nx/devkit/internal");
5
5
  const devkit_1 = require("@nx/devkit");
6
6
  const node_path_1 = require("node:path");
7
- const cache_directory_1 = require("nx/src/utils/cache-directory");
8
- const plugin_cache_utils_1 = require("nx/src/utils/plugin-cache-utils");
9
- const devkit_internals_1 = require("nx/src/devkit-internals");
10
7
  const get_gradle_report_1 = require("./utils/get-gradle-report");
11
- const file_hasher_1 = require("nx/src/hasher/file-hasher");
12
8
  const split_config_files_1 = require("../utils/split-config-files");
13
9
  const exec_gradle_1 = require("../utils/exec-gradle");
14
10
  const cacheableTaskType = new Set(['Build', 'Verification']);
@@ -33,9 +29,9 @@ exports.createNodesV2 = [
33
29
  split_config_files_1.gradleConfigAndTestGlob,
34
30
  async (files, options, context) => {
35
31
  const { buildFiles, projectRoots, gradlewFiles, testFiles } = (0, split_config_files_1.splitConfigFiles)(files);
36
- const optionsHash = (0, file_hasher_1.hashObject)(options);
37
- const cachePath = (0, node_path_1.join)(cache_directory_1.workspaceDataDirectory, `gradle-${optionsHash}.hash`);
38
- const pluginCache = new plugin_cache_utils_1.PluginCache(cachePath);
32
+ const optionsHash = (0, internal_1.hashObject)(options);
33
+ const cachePath = (0, node_path_1.join)(internal_1.workspaceDataDirectory, `gradle-${optionsHash}.hash`);
34
+ const pluginCache = new internal_1.PluginCache(cachePath);
39
35
  await (0, get_gradle_report_1.populateGradleReport)(context.workspaceRoot, gradlewFiles.map((f) => (0, node_path_1.join)(context.workspaceRoot, f)));
40
36
  const gradleReport = (0, get_gradle_report_1.getCurrentGradleReport)();
41
37
  const gradleProjectRootToTestFilesMap = getGradleProjectRootToTestFilesMap(testFiles, projectRoots);
@@ -257,7 +253,7 @@ function getGradleProjectRootToTestFilesMap(testFiles, projectRoots) {
257
253
  const roots = new Map(projectRoots.map((root) => [root, root]));
258
254
  const testFilesToGradleProjectMap = {};
259
255
  testFiles.forEach((testFile) => {
260
- const projectRoot = (0, devkit_internals_1.findProjectForPath)(testFile, roots);
256
+ const projectRoot = (0, internal_1.findProjectForPath)(testFile, roots);
261
257
  if (projectRoot) {
262
258
  if (!testFilesToGradleProjectMap[projectRoot]) {
263
259
  testFilesToGradleProjectMap[projectRoot] = [];
@@ -8,12 +8,11 @@ exports.processGradleDependencies = processGradleDependencies;
8
8
  const node_fs_1 = require("node:fs");
9
9
  const node_path_1 = require("node:path");
10
10
  const devkit_1 = require("@nx/devkit");
11
- const workspace_context_1 = require("nx/src/utils/workspace-context");
12
11
  const path_1 = require("path");
13
12
  const split_config_files_1 = require("../../utils/split-config-files");
14
13
  const get_project_report_lines_1 = require("./get-project-report-lines");
15
- const cache_directory_1 = require("nx/src/utils/cache-directory");
16
14
  const exec_gradle_1 = require("../../utils/exec-gradle");
15
+ const internal_1 = require("@nx/devkit/internal");
17
16
  function readGradleReportCache(cachePath, hash) {
18
17
  const gradleReportJson = (0, node_fs_1.existsSync)(cachePath)
19
18
  ? (0, devkit_1.readJsonFile)(cachePath)
@@ -65,7 +64,7 @@ function writeGradleReportToCache(cachePath, results, hash) {
65
64
  }
66
65
  }
67
66
  let gradleReportCache;
68
- let gradleReportCachePath = (0, node_path_1.join)(cache_directory_1.workspaceDataDirectory, 'gradle-report-v1.hash');
67
+ let gradleReportCachePath = (0, node_path_1.join)(internal_1.workspaceDataDirectory, 'gradle-report-v1.hash');
69
68
  function getCurrentGradleReport() {
70
69
  if (!gradleReportCache) {
71
70
  throw new devkit_1.AggregateCreateNodesError([
@@ -88,7 +87,7 @@ function getCurrentGradleReport() {
88
87
  * @returns Promise<void>
89
88
  */
90
89
  async function populateGradleReport(workspaceRoot, gradlewFiles) {
91
- const gradleConfigHash = await (0, workspace_context_1.hashWithWorkspaceContext)(workspaceRoot, [
90
+ const gradleConfigHash = await (0, internal_1.hashWithWorkspaceContext)(workspaceRoot, [
92
91
  split_config_files_1.gradleConfigAndTestGlob,
93
92
  ]);
94
93
  const cached = readGradleReportCache(gradleReportCachePath, gradleConfigHash);
@@ -1,5 +1,5 @@
1
1
  import { NxJsonConfiguration } from '@nx/devkit';
2
- import { ExecFileOptions } from 'node:child_process';
2
+ import { SpawnOptions } from 'node:child_process';
3
3
  export declare const fileSeparator: string;
4
4
  export declare const newLineSeparator: string;
5
5
  /**
@@ -14,7 +14,7 @@ export declare function getGradleExecFile(): string;
14
14
  * @param execOptions exec options
15
15
  * @returns promise with the stdout buffer
16
16
  */
17
- export declare function execGradleAsync(gradleBinaryPath: string, args: ReadonlyArray<string>, execOptions?: ExecFileOptions): Promise<Buffer>;
17
+ export declare function execGradleAsync(gradleBinaryPath: string, args: ReadonlyArray<string>, execOptions?: Omit<SpawnOptions, 'shell'>): Promise<Buffer>;
18
18
  export declare function getCustomGradleExecutableDirectoryFromPlugin(nxJson: NxJsonConfiguration): string | undefined;
19
19
  /**
20
20
  * This function recursively finds the nearest gradlew file in the workspace
@@ -7,14 +7,10 @@ exports.getCustomGradleExecutableDirectoryFromPlugin = getCustomGradleExecutable
7
7
  exports.findGradlewFile = findGradlewFile;
8
8
  exports.findGradlewUsingFilePathTraversal = findGradlewUsingFilePathTraversal;
9
9
  exports.findGradlewUsingCustomExecutableDirectory = findGradlewUsingCustomExecutableDirectory;
10
- const tslib_1 = require("tslib");
11
10
  const devkit_1 = require("@nx/devkit");
12
- const node_child_process_1 = require("node:child_process");
13
11
  const node_fs_1 = require("node:fs");
14
12
  const node_path_1 = require("node:path");
15
- const run_commands_impl_1 = require("nx/src/executors/run-commands/run-commands.impl");
16
- const exit_codes_1 = require("nx/src/utils/exit-codes");
17
- const tree_kill_1 = tslib_1.__importDefault(require("tree-kill"));
13
+ const internal_1 = require("@nx/devkit/internal");
18
14
  exports.fileSeparator = process.platform.startsWith('win')
19
15
  ? 'file:///'
20
16
  : 'file://';
@@ -36,37 +32,45 @@ function getGradleExecFile() {
36
32
  * @returns promise with the stdout buffer
37
33
  */
38
34
  function execGradleAsync(gradleBinaryPath, args, execOptions = {}) {
39
- // Extract signal so we can handle cancellation with tree-kill
35
+ // Extract signal so we can handle cancellation with a process-tree kill
40
36
  // instead of Node's default which only kills the immediate child.
41
37
  const { signal, ...restOptions } = execOptions;
42
38
  return new Promise((res, rej) => {
43
- const cp = (0, node_child_process_1.execFile)(gradleBinaryPath, args, {
39
+ // Without the filter, empty args reach gradle as literal empty arguments.
40
+ const cp = (0, internal_1.safeSpawn)(gradleBinaryPath, args.filter(Boolean), {
44
41
  cwd: (0, node_path_1.dirname)(gradleBinaryPath),
45
- shell: true,
46
- windowsHide: true,
47
42
  env: process.env,
48
- maxBuffer: run_commands_impl_1.LARGE_BUFFER,
49
43
  ...restOptions,
50
- }, undefined);
51
- // Use tree-kill on abort to kill the entire process tree
52
- // (cmd.exe → gradlew.bat → java.exe), not just the shell.
44
+ });
45
+ // A plugin worker torn down by `nx reset` would otherwise orphan the build.
46
+ (0, internal_1.killChildOnHostExit)(cp);
47
+ let stdout = Buffer.from('');
48
+ // On abort, kill the entire process tree (gradlew spawns java) and settle
49
+ // immediately — a wedged JVM that outlives the kill signal would otherwise
50
+ // keep this promise pending and the abort error would never surface.
53
51
  const onAbort = () => {
54
52
  if (cp.pid) {
55
- (0, tree_kill_1.default)(cp.pid);
53
+ (0, internal_1.killProcessTreeGraceful)(cp.pid).catch(() => { });
56
54
  }
55
+ rej(stdout);
57
56
  };
58
57
  signal?.addEventListener('abort', onAbort, { once: true });
59
- let stdout = Buffer.from('');
60
58
  cp.stdout?.on('data', (data) => {
61
59
  stdout += data;
62
60
  });
63
61
  cp.stderr?.on('data', (data) => {
64
62
  stdout += data;
65
63
  });
64
+ // Without a shell the child is gradlew itself, so spawn can fail outright —
65
+ // Node then emits `error` and never `exit`.
66
+ cp.on('error', (err) => {
67
+ signal?.removeEventListener('abort', onAbort);
68
+ rej(err);
69
+ });
66
70
  cp.on('exit', (code, s) => {
67
71
  signal?.removeEventListener('abort', onAbort);
68
72
  if (code === null)
69
- code = (0, exit_codes_1.signalToCode)(s);
73
+ code = (0, internal_1.signalToCode)(s);
70
74
  if (code === 0) {
71
75
  res(stdout);
72
76
  }
@@ -2,8 +2,8 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.gradleConfigAndTestGlob = exports.gradleConfigGlob = exports.GRADLE_TEST_FILES = exports.GRADLE_VERSION_CATALOG_GLOB = exports.GRADLEW_FILES = exports.GRADLE_BUILD_FILES = void 0;
4
4
  exports.splitConfigFiles = splitConfigFiles;
5
- const globs_1 = require("nx/src/utils/globs");
6
5
  const node_path_1 = require("node:path");
6
+ const internal_1 = require("@nx/devkit/internal");
7
7
  exports.GRADLE_BUILD_FILES = new Set(['build.gradle', 'build.gradle.kts']);
8
8
  exports.GRADLEW_FILES = new Set(['gradlew', 'gradlew.bat']);
9
9
  exports.GRADLE_VERSION_CATALOG_GLOB = '**/gradle/*.versions.toml';
@@ -15,7 +15,7 @@ exports.GRADLE_TEST_FILES = [
15
15
  '**/src/test/groovy/**/*Test.groovy',
16
16
  '**/src/test/groovy/**/*Tests.groovy',
17
17
  ];
18
- exports.gradleConfigGlob = (0, globs_1.combineGlobPatterns)(...Array.from(exports.GRADLE_BUILD_FILES).map((file) => `**/${file}`));
18
+ exports.gradleConfigGlob = (0, internal_1.combineGlobPatterns)(...Array.from(exports.GRADLE_BUILD_FILES).map((file) => `**/${file}`));
19
19
  // Files that influence Gradle's configuration phase and therefore the project
20
20
  // graph report: any *.gradle(.kts) script (build, settings, script plugins),
21
21
  // gradle.properties, the wrapper pin, and buildSrc build logic.
@@ -28,7 +28,7 @@ const GRADLE_CONFIG_FILE_PATTERNS = [
28
28
  'buildSrc/**/*.java',
29
29
  'buildSrc/**/*.groovy',
30
30
  ];
31
- exports.gradleConfigAndTestGlob = (0, globs_1.combineGlobPatterns)(...GRADLE_CONFIG_FILE_PATTERNS, ...GRADLE_CONFIG_FILE_PATTERNS.map((pattern) => `**/${pattern}`), ...Array.from(exports.GRADLEW_FILES), ...Array.from(exports.GRADLEW_FILES).map((file) => `**/${file}`), ...exports.GRADLE_TEST_FILES, exports.GRADLE_VERSION_CATALOG_GLOB);
31
+ exports.gradleConfigAndTestGlob = (0, internal_1.combineGlobPatterns)(...GRADLE_CONFIG_FILE_PATTERNS, ...GRADLE_CONFIG_FILE_PATTERNS.map((pattern) => `**/${pattern}`), ...Array.from(exports.GRADLEW_FILES), ...Array.from(exports.GRADLEW_FILES).map((file) => `**/${file}`), ...exports.GRADLE_TEST_FILES, exports.GRADLE_VERSION_CATALOG_GLOB);
32
32
  /**
33
33
  * This function split config files into build files, settings files, test files and project roots
34
34
  * @param files list of files to split
@@ -1,3 +1,3 @@
1
1
  export declare const nxVersion: any;
2
2
  export declare const gradleProjectGraphPluginName = "dev.nx.gradle.project-graph";
3
- export declare const gradleProjectGraphVersion = "0.1.24";
3
+ export declare const gradleProjectGraphVersion = "0.1.25";
@@ -4,4 +4,4 @@ exports.gradleProjectGraphVersion = exports.gradleProjectGraphPluginName = expor
4
4
  const path_1 = require("path");
5
5
  exports.nxVersion = require((0, path_1.join)('@nx/gradle', 'package.json')).version;
6
6
  exports.gradleProjectGraphPluginName = 'dev.nx.gradle.project-graph';
7
- exports.gradleProjectGraphVersion = '0.1.24';
7
+ exports.gradleProjectGraphVersion = '0.1.25';
package/migrations.json CHANGED
@@ -180,6 +180,12 @@
180
180
  "description": "Change dev.nx.gradle.project-graph to version 0.1.24 in build file",
181
181
  "factory": "./dist/src/migrations/23-1-0/change-plugin-version-0-1-24",
182
182
  "documentation": "./dist/src/migrations/23-1-0/change-plugin-version-0-1-24.md"
183
+ },
184
+ "change-plugin-version-0-1-25": {
185
+ "version": "23.2.0-beta.11",
186
+ "description": "Change dev.nx.gradle.project-graph to version 0.1.25 in build file",
187
+ "implementation": "./dist/src/migrations/23-2-0/change-plugin-version-0-1-25",
188
+ "documentation": "./dist/src/migrations/23-2-0/change-plugin-version-0-1-25.md"
183
189
  }
184
190
  },
185
191
  "packageJsonUpdates": {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/gradle",
3
- "version": "23.2.0-beta.1",
3
+ "version": "23.2.0-beta.11",
4
4
  "private": false,
5
5
  "type": "commonjs",
6
6
  "files": [
@@ -76,12 +76,11 @@
76
76
  },
77
77
  "dependencies": {
78
78
  "toml-eslint-parser": "^0.10.0",
79
- "tree-kill": "^1.2.2",
80
79
  "tslib": "^2.3.0",
81
- "@nx/devkit": "23.2.0-beta.1"
80
+ "@nx/devkit": "23.2.0-beta.11"
82
81
  },
83
82
  "devDependencies": {
84
- "nx": "23.2.0-beta.1"
83
+ "nx": "23.2.0-beta.11"
85
84
  },
86
85
  "publishConfig": {
87
86
  "access": "public"