Skip to content

Commit

Permalink
refactor: locate mechanism to be more maintainable
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremylvln committed Jan 4, 2021
1 parent f6d7972 commit 897024d
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 36 deletions.
2 changes: 1 addition & 1 deletion dist/index.js

Large diffs are not rendered by default.

79 changes: 44 additions & 35 deletions src/locate-nx.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,43 +30,52 @@ async function assertHasNxPackageScript(): Promise<void> {
core.info("Found 'nx' script inside package.json file");
}

export async function locateNx(): Promise<CommandWrapper> {
await assertHasNxPackageScript();
async function tryLocate(
entries: [pmName: string, filePath: string, factory: () => CommandWrapper][],
): Promise<CommandWrapper> {
if (entries.length === 0) {
throw new Error(
'Failed to detect your package manager, are you using npm or yarn?',
);
}

const [entry, ...rest] = entries;

return fsPromises
.stat('package-lock.json')
.stat(entry[1])
.then(() => {
core.info('Using npm as package manager');
return new CommandBuilder()
.withCommand('npm')
.withArgs('run', 'nx', '--')
.build();
core.info(`Using ${entry[0]} as package manager`);
return entry[2]();
})
.catch(() => {
return fsPromises
.stat('yarn.lock')
.then(() => {
core.info('Using yarn as package manager');
return new CommandBuilder()
.withCommand('yarn')
.withArgs('nx')
.build();
})
.catch(() => {
return fsPromises
.stat('pnpm-lock.yaml')
.then(() => {
core.info('Using pnpm as package manager');
return new CommandBuilder()
.withCommand('pnpm')
.withArgs('run', 'nx', '--')
.build();
})
.catch(() => {
throw new Error(
'Failed to detect your package manager, are you using npm or yarn?',
);
});
});
});
.catch(() => tryLocate(rest));
}

export async function locateNx(): Promise<CommandWrapper> {
await assertHasNxPackageScript();

return tryLocate([
[
'npm',
'package-lock.json',
() =>
new CommandBuilder()
.withCommand('npm')
.withArgs('run', 'nx', '--')
.build(),
],
[
'yarn',
'yarn.lock',
() => new CommandBuilder().withCommand('yarn').withArgs('nx').build(),
],
[
'pnpm',
'pnpm-lock.yaml',
() =>
new CommandBuilder()
.withCommand('pnpm')
.withArgs('run', 'nx', '--')
.build(),
],
]);
}

0 comments on commit 897024d

Please sign in to comment.