Skip to content

Commit 2f876e0

Browse files
JamesHenryjaysoo
authored andcommitted
fix(core): tweaks to nx init (#30002)
<!-- Please make sure you have read the submission guidelines before posting an PR --> <!-- https://github.com/nrwl/nx/blob/master/CONTRIBUTING.md#-submitting-a-pr --> <!-- Please make sure that your commit message follows our format --> <!-- Example: `fix(nx): must begin with lowercase` --> <!-- If this is a particularly complex change or feature addition, you can request a dedicated Nx release for this pull request branch. Mention someone from the Nx team or the `@nrwl/nx-pipelines-reviewers` and they will confirm if the PR warrants its own release for testing purposes, and generate it for you if appropriate. --> ## Current Behavior <!-- This is the behavior we have today --> ## Expected Behavior <!-- This is the behavior we should expect with the changes in this PR --> ## Related Issue(s) <!-- Please link the issue being fixed so it gets closed when this is merged. --> Fixes #
1 parent c79febe commit 2f876e0

File tree

10 files changed

+570
-65
lines changed

10 files changed

+570
-65
lines changed

docs/generated/devkit/NxJsonConfiguration.md

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ Nx.json configuration
1818

1919
### Properties
2020

21+
- [$schema](../../devkit/documents/NxJsonConfiguration#$schema): string
2122
- [affected](../../devkit/documents/NxJsonConfiguration#affected): NxAffectedConfig
2223
- [cacheDirectory](../../devkit/documents/NxJsonConfiguration#cachedirectory): string
2324
- [cli](../../devkit/documents/NxJsonConfiguration#cli): Object
@@ -47,6 +48,12 @@ Nx.json configuration
4748

4849
## Properties
4950

51+
### $schema
52+
53+
`Optional` **$schema**: `string`
54+
55+
---
56+
5057
### affected
5158

5259
`Optional` **affected**: [`NxAffectedConfig`](../../devkit/documents/NxAffectedConfig)

docs/generated/devkit/Workspace.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@ use ProjectsConfigurations or NxJsonConfiguration
1616

1717
### Properties
1818

19+
- [$schema](../../devkit/documents/Workspace#$schema): string
1920
- [affected](../../devkit/documents/Workspace#affected): NxAffectedConfig
2021
- [cacheDirectory](../../devkit/documents/Workspace#cachedirectory): string
2122
- [cli](../../devkit/documents/Workspace#cli): Object
@@ -47,6 +48,16 @@ use ProjectsConfigurations or NxJsonConfiguration
4748

4849
## Properties
4950

51+
### $schema
52+
53+
`Optional` **$schema**: `string`
54+
55+
#### Inherited from
56+
57+
[NxJsonConfiguration](../../devkit/documents/NxJsonConfiguration).[$schema](../../devkit/documents/NxJsonConfiguration#$schema)
58+
59+
---
60+
5061
### affected
5162

5263
`Optional` **affected**: [`NxAffectedConfig`](../../devkit/documents/NxAffectedConfig)

packages/nx/src/adapter/compat.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,7 @@ export const allowedProjectExtensions = [
5454
// There are some props in here (root) that angular already knows about,
5555
// but it doesn't hurt to have them in here as well to help static analysis.
5656
export const allowedWorkspaceExtensions = [
57+
'$schema',
5758
'implicitDependencies',
5859
'affected',
5960
'defaultBase',

packages/nx/src/command-line/init/command-object.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,19 @@ export const yargsInitCommand: CommandModule = {
77
'Adds Nx to any type of workspace. It installs nx, creates an nx.json configuration file and optionally sets up remote caching. For more info, check https://nx.dev/recipes/adopting-nx.',
88
builder: (yargs) => withInitOptions(yargs),
99
handler: async (args: any) => {
10-
const useV2 = await isInitV2();
11-
if (useV2) {
12-
await require('./init-v2').initHandler(args);
13-
} else {
14-
await require('./init-v1').initHandler(args);
10+
try {
11+
const useV2 = await isInitV2();
12+
if (useV2) {
13+
await require('./init-v2').initHandler(args);
14+
} else {
15+
await require('./init-v1').initHandler(args);
16+
}
17+
process.exit(0);
18+
} catch {
19+
// Ensure the cursor is always restored just in case the user has bailed during interactive prompts
20+
process.stdout.write('\x1b[?25h');
21+
process.exit(1);
1522
}
16-
process.exit(0);
1723
},
1824
};
1925

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { writeFileSync } from 'node:fs';
2+
import { join } from 'node:path';
3+
import { readJsonFile, writeJsonFile } from '../../../utils/fileutils';
4+
import { output } from '../../../utils/output';
5+
import { getPackageManagerCommand } from '../../../utils/package-manager';
6+
import { InitArgs } from '../init-v1';
7+
import {
8+
addDepsToPackageJson,
9+
createNxJsonFromTurboJson,
10+
runInstall,
11+
updateGitIgnore,
12+
} from './utils';
13+
14+
type Options = Pick<InitArgs, 'nxCloud' | 'interactive'>;
15+
16+
export async function addNxToTurborepo(_options: Options) {
17+
const repoRoot = process.cwd();
18+
19+
output.log({
20+
title: 'Initializing Nx based on your old Turborepo configuration',
21+
});
22+
23+
output.log({
24+
title: '💡 Did you know?',
25+
bodyLines: [
26+
'- Turborepo requires you to maintain all your common scripts like "build", "lint", "test" in all your packages, as well as their applicable cache inputs and outputs.',
27+
`- Nx is extensible and has plugins for the tools you use to infer all of this for you purely based on that tool's configuration file within your packages.`,
28+
'',
29+
' - E.g. the `@nx/vite` plugin will infer the "build" script based on the existence of a vite.config.js file.',
30+
' - Therefore with zero package level config, `nx build my-app` knows to run the `vite build` CLI directly, with all Nx cache inputs and outputs automatically inferred.',
31+
'',
32+
`NOTE: None of your existing package.json scripts will be modified as part of this initialization process, you can already use them as-is with Nx, but you can learn more about the benefits of Nx's inferred tasks at https://nx.dev/concepts/inferred-tasks`,
33+
],
34+
});
35+
36+
let nxJson = createNxJsonFromTurboJson(readJsonFile('turbo.json'));
37+
const nxJsonPath = join(repoRoot, 'nx.json');
38+
39+
// Turborepo workspaces usually have prettier installed, so try and match the formatting before writing the file
40+
try {
41+
const prettier = await import('prettier');
42+
const config = await prettier.resolveConfig(repoRoot);
43+
writeFileSync(
44+
nxJsonPath,
45+
// @ts-ignore - Always await prettier.format, in modern versions it's async
46+
await prettier.format(JSON.stringify(nxJson, null, 2), {
47+
...(config ?? {}),
48+
parser: 'json',
49+
})
50+
);
51+
} catch (err) {
52+
// Apply fallback JSON write
53+
writeJsonFile(nxJsonPath, nxJson);
54+
}
55+
56+
const pmc = getPackageManagerCommand();
57+
58+
updateGitIgnore(repoRoot);
59+
addDepsToPackageJson(repoRoot);
60+
61+
output.log({ title: '📦 Installing dependencies' });
62+
63+
runInstall(repoRoot, pmc);
64+
}
Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,46 @@
1+
import { execSync } from 'node:child_process';
2+
import { deduceDefaultBase as gitInitDefaultBase } from '../../../utils/default-base';
3+
4+
export function deduceDefaultBase() {
5+
try {
6+
execSync(`git rev-parse --verify main`, {
7+
stdio: ['ignore', 'ignore', 'ignore'],
8+
windowsHide: false,
9+
});
10+
return 'main';
11+
} catch {
12+
try {
13+
execSync(`git rev-parse --verify dev`, {
14+
stdio: ['ignore', 'ignore', 'ignore'],
15+
windowsHide: false,
16+
});
17+
return 'dev';
18+
} catch {
19+
try {
20+
execSync(`git rev-parse --verify develop`, {
21+
stdio: ['ignore', 'ignore', 'ignore'],
22+
windowsHide: false,
23+
});
24+
return 'develop';
25+
} catch {
26+
try {
27+
execSync(`git rev-parse --verify next`, {
28+
stdio: ['ignore', 'ignore', 'ignore'],
29+
windowsHide: false,
30+
});
31+
return 'next';
32+
} catch {
33+
try {
34+
execSync(`git rev-parse --verify master`, {
35+
stdio: ['ignore', 'ignore', 'ignore'],
36+
windowsHide: false,
37+
});
38+
return 'master';
39+
} catch {
40+
return gitInitDefaultBase();
41+
}
42+
}
43+
}
44+
}
45+
}
46+
}

0 commit comments

Comments
 (0)