Skip to content

Commit

Permalink
fix(core): tweaks to nx init (nrwl#30002)
Browse files Browse the repository at this point in the history
<!-- 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 #
  • Loading branch information
JamesHenry authored Feb 12, 2025
1 parent 672318d commit 8b1cd48
Show file tree
Hide file tree
Showing 10 changed files with 570 additions and 65 deletions.
7 changes: 7 additions & 0 deletions docs/generated/devkit/NxJsonConfiguration.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Nx.json configuration

### Properties

- [$schema](../../devkit/documents/NxJsonConfiguration#$schema): string
- [affected](../../devkit/documents/NxJsonConfiguration#affected): NxAffectedConfig
- [cacheDirectory](../../devkit/documents/NxJsonConfiguration#cachedirectory): string
- [cli](../../devkit/documents/NxJsonConfiguration#cli): Object
Expand Down Expand Up @@ -47,6 +48,12 @@ Nx.json configuration

## Properties

### $schema

`Optional` **$schema**: `string`

---

### affected

`Optional` **affected**: [`NxAffectedConfig`](../../devkit/documents/NxAffectedConfig)
Expand Down
11 changes: 11 additions & 0 deletions docs/generated/devkit/Workspace.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use ProjectsConfigurations or NxJsonConfiguration

### Properties

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

## Properties

### $schema

`Optional` **$schema**: `string`

#### Inherited from

[NxJsonConfiguration](../../devkit/documents/NxJsonConfiguration).[$schema](../../devkit/documents/NxJsonConfiguration#$schema)

---

### affected

`Optional` **affected**: [`NxAffectedConfig`](../../devkit/documents/NxAffectedConfig)
Expand Down
1 change: 1 addition & 0 deletions packages/nx/src/adapter/compat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,7 @@ export const allowedProjectExtensions = [
// There are some props in here (root) that angular already knows about,
// but it doesn't hurt to have them in here as well to help static analysis.
export const allowedWorkspaceExtensions = [
'$schema',
'implicitDependencies',
'affected',
'defaultBase',
Expand Down
18 changes: 12 additions & 6 deletions packages/nx/src/command-line/init/command-object.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,19 @@ export const yargsInitCommand: CommandModule = {
'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.',
builder: (yargs) => withInitOptions(yargs),
handler: async (args: any) => {
const useV2 = await isInitV2();
if (useV2) {
await require('./init-v2').initHandler(args);
} else {
await require('./init-v1').initHandler(args);
try {
const useV2 = await isInitV2();
if (useV2) {
await require('./init-v2').initHandler(args);
} else {
await require('./init-v1').initHandler(args);
}
process.exit(0);
} catch {
// Ensure the cursor is always restored just in case the user has bailed during interactive prompts
process.stdout.write('\x1b[?25h');
process.exit(1);
}
process.exit(0);
},
};

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import { writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { readJsonFile, writeJsonFile } from '../../../utils/fileutils';
import { output } from '../../../utils/output';
import { getPackageManagerCommand } from '../../../utils/package-manager';
import { InitArgs } from '../init-v1';
import {
addDepsToPackageJson,
createNxJsonFromTurboJson,
runInstall,
updateGitIgnore,
} from './utils';

type Options = Pick<InitArgs, 'nxCloud' | 'interactive'>;

export async function addNxToTurborepo(_options: Options) {
const repoRoot = process.cwd();

output.log({
title: 'Initializing Nx based on your old Turborepo configuration',
});

output.log({
title: '💡 Did you know?',
bodyLines: [
'- 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.',
`- 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.`,
'',
' - E.g. the `@nx/vite` plugin will infer the "build" script based on the existence of a vite.config.js file.',
' - 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.',
'',
`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`,
],
});

let nxJson = createNxJsonFromTurboJson(readJsonFile('turbo.json'));
const nxJsonPath = join(repoRoot, 'nx.json');

// Turborepo workspaces usually have prettier installed, so try and match the formatting before writing the file
try {
const prettier = await import('prettier');
const config = await prettier.resolveConfig(repoRoot);
writeFileSync(
nxJsonPath,
// @ts-ignore - Always await prettier.format, in modern versions it's async
await prettier.format(JSON.stringify(nxJson, null, 2), {
...(config ?? {}),
parser: 'json',
})
);
} catch (err) {
// Apply fallback JSON write
writeJsonFile(nxJsonPath, nxJson);
}

const pmc = getPackageManagerCommand();

updateGitIgnore(repoRoot);
addDepsToPackageJson(repoRoot);

output.log({ title: '📦 Installing dependencies' });

runInstall(repoRoot, pmc);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { execSync } from 'node:child_process';
import { deduceDefaultBase as gitInitDefaultBase } from '../../../utils/default-base';

export function deduceDefaultBase() {
try {
execSync(`git rev-parse --verify main`, {
stdio: ['ignore', 'ignore', 'ignore'],
windowsHide: false,
});
return 'main';
} catch {
try {
execSync(`git rev-parse --verify dev`, {
stdio: ['ignore', 'ignore', 'ignore'],
windowsHide: false,
});
return 'dev';
} catch {
try {
execSync(`git rev-parse --verify develop`, {
stdio: ['ignore', 'ignore', 'ignore'],
windowsHide: false,
});
return 'develop';
} catch {
try {
execSync(`git rev-parse --verify next`, {
stdio: ['ignore', 'ignore', 'ignore'],
windowsHide: false,
});
return 'next';
} catch {
try {
execSync(`git rev-parse --verify master`, {
stdio: ['ignore', 'ignore', 'ignore'],
windowsHide: false,
});
return 'master';
} catch {
return gitInitDefaultBase();
}
}
}
}
}
}
Loading

0 comments on commit 8b1cd48

Please sign in to comment.