-
Notifications
You must be signed in to change notification settings - Fork 609
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[rush] Refactor rush-sdk to expose a loader API. #3212
Open
iclanton
wants to merge
2
commits into
microsoft:main
Choose a base branch
from
iclanton:rush-sdk-refactor
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,30 @@ | ||
## API Report File for "@rushstack/rush-sdk" | ||
|
||
> Do not edit this file. It is a report generated by [API Extractor](https://api-extractor.com/). | ||
|
||
```ts | ||
|
||
import { ITerminal } from '@rushstack/node-core-library'; | ||
|
||
// @beta (undocumented) | ||
export interface IRushSdkLoaderOptions { | ||
// (undocumented) | ||
terminal?: ITerminal; | ||
} | ||
|
||
// @internal (undocumented) | ||
export type _RushLibModuleType = Record<string, unknown>; | ||
|
||
// @beta (undocumented) | ||
export class RushSdkLoader { | ||
// (undocumented) | ||
static install(options?: IRushSdkLoaderOptions): void; | ||
// @internal (undocumented) | ||
static _rushLibModule: _RushLibModuleType | undefined; | ||
// @internal (undocumented) | ||
static _rushLibModuleHasBeenInstalled: boolean; | ||
} | ||
|
||
// (No @packageDocumentation comment for this package) | ||
|
||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
{ | ||
"$schema": "https://developer.microsoft.com/json-schemas/api-extractor/v7/api-extractor.schema.json", | ||
|
||
"mainEntryPointFilePath": "<projectFolder>/lib/RushSdkLoader.d.ts", | ||
|
||
"apiReport": { | ||
"enabled": true, | ||
"reportFolder": "../../../common/reviews/api", | ||
"reportFileName": "<unscopedPackageName>-loader.api.md" | ||
}, | ||
|
||
"docModel": { | ||
"enabled": true, | ||
"apiJsonFilePath": "../../../common/temp/api/<unscopedPackageName>-loader.api.json" | ||
}, | ||
|
||
"dtsRollup": { | ||
"enabled": true, | ||
"omitTrimmingComments": true, | ||
"untrimmedFilePath": "<projectFolder>/temp/<unscopedPackageName>-loader.d.ts", | ||
"betaTrimmedFilePath": "<projectFolder>/dist/<unscopedPackageName>-loader.d.ts" | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './dist/rush-sdk-loader'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
const RushSdkLoader = require('./lib/RushSdkLoader'); | ||
module.exports = RushSdkLoader; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
export * from './lib/RushSdkLoader'; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,251 @@ | ||
// Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. | ||
// See LICENSE in the project root for license information. | ||
|
||
import * as path from 'path'; | ||
import { | ||
ConsoleTerminalProvider, | ||
Executable, | ||
FileSystem, | ||
Import, | ||
IPackageJson, | ||
ITerminal, | ||
JsonFile, | ||
JsonObject, | ||
PackageJsonLookup, | ||
Terminal | ||
} from '@rushstack/node-core-library'; | ||
import { SpawnSyncReturns } from 'child_process'; | ||
|
||
const RUSH_LIB_NAME: string = '@microsoft/rush-lib'; | ||
|
||
/** | ||
* @internal | ||
*/ | ||
export type _RushLibModuleType = Record<string, unknown>; | ||
|
||
/** | ||
* @beta | ||
*/ | ||
export interface IRushSdkLoaderOptions { | ||
terminal?: ITerminal; | ||
} | ||
|
||
declare const global: NodeJS.Global & | ||
typeof globalThis & { | ||
___rush___rushLibModule?: _RushLibModuleType; | ||
___rush___rushLibModuleFromInstallAndRunRush?: _RushLibModuleType; | ||
}; | ||
|
||
/** | ||
* @beta | ||
*/ | ||
export class RushSdkLoader { | ||
/** | ||
* @internal | ||
*/ | ||
public static _rushLibModule: _RushLibModuleType | undefined = RushSdkLoader._tryLoadRushLib(); | ||
|
||
/** | ||
* @internal | ||
*/ | ||
public static _rushLibModuleHasBeenInstalled: boolean = !!RushSdkLoader._rushLibModule; | ||
|
||
public static install(options?: IRushSdkLoaderOptions): void { | ||
if (RushSdkLoader._rushLibModuleHasBeenInstalled) { | ||
return; | ||
} | ||
|
||
const { terminal = new Terminal(new ConsoleTerminalProvider()) } = options || {}; | ||
|
||
// SCENARIO 3: A tool or script depends on "rush-sdk", and is meant to be used inside a monorepo folder. | ||
// In this case, we can use install-run-rush.js to obtain the appropriate rush-lib version for the monorepo. | ||
if (RushSdkLoader._rushLibModule === undefined) { | ||
try { | ||
const rushJsonPath: string | undefined = RushSdkLoader._tryFindRushJsonLocation(process.cwd()); | ||
if (!rushJsonPath) { | ||
throw new Error( | ||
'Unable to find rush.json in the current folder or its parent folders.\n' + | ||
'This tool is meant to be invoked from a working directory inside a Rush repository.' | ||
); | ||
} | ||
const monorepoRoot: string = path.dirname(rushJsonPath); | ||
|
||
const rushJson: JsonObject = JsonFile.load(rushJsonPath); | ||
const { rushVersion } = rushJson; | ||
|
||
const installRunNodeModuleFolder: string = `${monorepoRoot}common/temp/install-run/@microsoft+rush@${rushVersion}`; | ||
try { | ||
// First, try to load the version of "rush-lib" that was installed by install-run-rush.js | ||
terminal.writeVerboseLine(`Trying to load ${RUSH_LIB_NAME} installed by install-run-rush`); | ||
RushSdkLoader._rushLibModule = | ||
RushSdkLoader._requireRushLibUnderFolderPath(installRunNodeModuleFolder); | ||
} catch (e) { | ||
let installAndRunRushStderrContent: string = ''; | ||
try { | ||
const installAndRunRushJSPath: string = path.join( | ||
monorepoRoot, | ||
'common/scripts/install-run-rush.js' | ||
); | ||
|
||
terminal.writeLine('The Rush engine has not been installed yet. Invoking install-run-rush.js...'); | ||
|
||
const installAndRuhRushProcess: SpawnSyncReturns<string> = Executable.spawnSync('node', [ | ||
installAndRunRushJSPath, | ||
'--help' | ||
]); | ||
terminal.write(installAndRuhRushProcess.stdout); | ||
|
||
installAndRunRushStderrContent = installAndRuhRushProcess.stderr; | ||
if (installAndRuhRushProcess.status !== 0) { | ||
throw new Error(`The ${RUSH_LIB_NAME} package failed to install`); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This error gets immediately discarded by the catch below. |
||
} | ||
|
||
// Retry to load "rush-lib" after install-run-rush run | ||
terminal.writeVerboseLine( | ||
`Trying to load ${RUSH_LIB_NAME} installed by install-run-rush a second time` | ||
); | ||
RushSdkLoader._rushLibModule = | ||
RushSdkLoader._requireRushLibUnderFolderPath(installRunNodeModuleFolder); | ||
} catch (e) { | ||
terminal.writeErrorLine(`${installAndRunRushStderrContent}`); | ||
throw new Error(`The ${RUSH_LIB_NAME} package failed to load`); | ||
} | ||
} | ||
|
||
if (RushSdkLoader._rushLibModule !== undefined) { | ||
// to track which scenario is active and how it got initialized. | ||
global.___rush___rushLibModuleFromInstallAndRunRush = RushSdkLoader._rushLibModule; | ||
terminal.writeVerboseLine(`Loaded ${RUSH_LIB_NAME} installed by install-run-rush`); | ||
} | ||
} catch (e) { | ||
// This error indicates that a project is trying to import "@rushstack/rush-sdk", but the Rush engine | ||
// instance cannot be found. If you are writing Jest tests for a Rush plugin, add "@microsoft/rush-lib" | ||
// to the devDependencies for your project. | ||
throw new Error( | ||
'The @rushstack/rush-sdk package was not able to load the Rush engine:' + (e as Error).message | ||
); | ||
} finally { | ||
RushSdkLoader._rushLibModuleHasBeenInstalled = true; | ||
} | ||
|
||
if (!RushSdkLoader._rushLibModule) { | ||
throw new Error('The @rushstack/rush-sdk package was not able to load the Rush engine.'); | ||
} | ||
} | ||
} | ||
|
||
private static _tryLoadRushLib(): _RushLibModuleType | undefined { | ||
// SCENARIO 1: Rush's PluginManager has initialized "rush-sdk" with Rush's own instance of rush-lib. | ||
// The Rush host process will assign "global.___rush___rushLibModule" before loading the plugin. | ||
let rushLibModule: _RushLibModuleType | undefined = | ||
global.___rush___rushLibModule || global.___rush___rushLibModuleFromInstallAndRunRush; | ||
|
||
// SCENARIO 2: The project importing "rush-sdk" has installed its own instance of "rush-lib" | ||
// as a package.json dependency. For example, this is used by the Jest tests for Rush plugins. | ||
if (rushLibModule === undefined) { | ||
const thisProjectRoot: string | undefined = | ||
PackageJsonLookup.instance.tryGetPackageFolderFor(__dirname); | ||
if (!thisProjectRoot) { | ||
throw new Error('Unable to find package.json for @rushstack/rush-sdk.'); | ||
} | ||
|
||
let callingModule: NodeModule | null | undefined = module?.parent; | ||
while (callingModule?.filename?.startsWith(thisProjectRoot)) { | ||
// Walk up calling modules until we're out of this package. | ||
callingModule = callingModule.parent; | ||
} | ||
|
||
const importingPath: string | undefined = callingModule?.filename; | ||
if (importingPath !== undefined) { | ||
const callerPackageFolder: string | undefined = | ||
PackageJsonLookup.instance.tryGetPackageFolderFor(importingPath); | ||
|
||
if (callerPackageFolder !== undefined) { | ||
const callerPackageJson: IPackageJson = RushSdkLoader._require( | ||
`${callerPackageFolder}/package.json` | ||
); | ||
|
||
// Does the caller properly declare a dependency on rush-lib? | ||
if ( | ||
(callerPackageJson.devDependencies?.[RUSH_LIB_NAME] ?? | ||
callerPackageJson.dependencies?.[RUSH_LIB_NAME] ?? | ||
callerPackageJson.peerDependencies?.[RUSH_LIB_NAME] ?? | ||
callerPackageJson.optionalDependencies?.[RUSH_LIB_NAME]) !== undefined | ||
(callerPackageJson.devDependencies && | ||
callerPackageJson.devDependencies[RUSH_LIB_NAME] !== undefined) || | ||
(callerPackageJson.peerDependencies && | ||
callerPackageJson.peerDependencies[RUSH_LIB_NAME] !== undefined) | ||
) { | ||
// Try to resolve rush-lib from the caller's folder | ||
try { | ||
rushLibModule = RushSdkLoader._requireRushLibUnderFolderPath(callerPackageFolder); | ||
} catch (error) { | ||
// If we fail to resolve it, ignore the error | ||
} | ||
|
||
// If two different libraries invoke `rush-sdk`, and one of them provides "rush-lib" | ||
// then the first version to be loaded wins. We do not support side-by-side instances of "rush-lib". | ||
if (rushLibModule !== undefined) { | ||
// to track which scenario is active and how it got initialized. | ||
global.___rush___rushLibModule = rushLibModule; | ||
} | ||
} | ||
} | ||
} | ||
} | ||
|
||
return rushLibModule; | ||
} | ||
|
||
/** | ||
* Require `@microsoft/rush-lib` under the specified folder path. | ||
*/ | ||
private static _requireRushLibUnderFolderPath(folderPath: string): _RushLibModuleType { | ||
const rushLibModulePath: string = Import.resolveModule({ | ||
modulePath: RUSH_LIB_NAME, | ||
baseFolderPath: folderPath | ||
}); | ||
|
||
return RushSdkLoader._require(rushLibModulePath); | ||
} | ||
|
||
/** | ||
* Find the rush.json location and return the path, or undefined if a rush.json can't be found. | ||
* | ||
* @privateRemarks | ||
* Keep this in sync with `RushConfiguration.tryFindRushJsonLocation`. | ||
*/ | ||
private static _tryFindRushJsonLocation(startingFolder: string): string | undefined { | ||
let currentFolder: string = startingFolder; | ||
|
||
// Look upwards at parent folders until we find a folder containing rush.json | ||
for (let i: number = 0; i < 10; ++i) { | ||
const rushJsonFilename: string = path.join(currentFolder, 'rush.json'); | ||
|
||
if (FileSystem.exists(rushJsonFilename)) { | ||
return rushJsonFilename; | ||
} | ||
|
||
const parentFolder: string = path.dirname(currentFolder); | ||
if (parentFolder === currentFolder) { | ||
break; | ||
} | ||
|
||
currentFolder = parentFolder; | ||
} | ||
|
||
return undefined; | ||
} | ||
|
||
private static _require<TResult>(moduleName: string): TResult { | ||
if (typeof __non_webpack_require__ === 'function') { | ||
// If this library has been bundled with Webpack, we need to call the real `require` function | ||
// that doesn't get turned into a `__webpack_require__` statement. | ||
// `__non_webpack_require__` is a Webpack macro that gets turned into a `require` statement | ||
// during bundling. | ||
return __non_webpack_require__(moduleName); | ||
} else { | ||
return require(moduleName); | ||
} | ||
} | ||
} |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Note:
rush --help
lists all rush commands information, but the idea is just trigger theinstall-run
logic behind. I can see this stdout would be pretty annoying, so it's intentionaly removed in original implementation.