Skip to content

Commit

Permalink
refactor: simplified inline find-up
Browse files Browse the repository at this point in the history
no need for the extra dep
  • Loading branch information
AviVahl committed Dec 14, 2021
1 parent f38caf2 commit ebef619
Show file tree
Hide file tree
Showing 5 changed files with 52 additions and 18 deletions.
41 changes: 26 additions & 15 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
"typecheck": "tsc --noEmit"
},
"dependencies": {
"find-up": "^5.0.0",
"glob": "^7.2.0",
"tslib": "^2.3.1",
"type-fest": "^2.8.0"
Expand Down
4 changes: 2 additions & 2 deletions src/directory-context.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import fs from 'fs';
import path from 'path';
import findUp from 'find-up';
import type { PackageJson } from 'type-fest';
import { resolveWorkspacePackages, extractPackageLocations } from './yarn-workspaces';
import { isPlainObject, isString } from './language-helpers';
import { INpmPackage, PACKAGE_JSON, resolveLinkedPackages, sortPackagesByDepth } from './npm-package';
import { findFileUpSync } from './find-up';

export interface SinglePackageContext {
type: 'single';
Expand All @@ -18,7 +18,7 @@ export interface MultiPackageContext {
}

export function resolveDirectoryContext(basePath: string): SinglePackageContext | MultiPackageContext {
const packageJsonPath = findUp.sync(PACKAGE_JSON, { cwd: basePath });
const packageJsonPath = findFileUpSync(basePath, PACKAGE_JSON);

if (!isString(packageJsonPath)) {
throw new Error(`Cannot find ${PACKAGE_JSON} for ${basePath}`);
Expand Down
23 changes: 23 additions & 0 deletions src/find-up.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { statSync } from 'fs';
import { dirname, join } from 'path';

export function findFileUpSync(directoryPath: string, fileName: string) {
for (const directoryInChain of pathChainToRoot(directoryPath)) {
const filePath = join(directoryInChain, fileName);
try {
if (statSync(filePath).isFile()) {
return filePath;
}
} catch {}
}
return;
}

function* pathChainToRoot(currentPath: string) {
let lastPath: string | undefined;
while (lastPath !== currentPath) {
yield currentPath;
lastPath = currentPath;
currentPath = dirname(currentPath);
}
}
1 change: 1 addition & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
export * from './directory-context';
export * from './find-up';
export * from './language-helpers';
export * from './npm-package';
export * from './yarn-workspaces';

0 comments on commit ebef619

Please sign in to comment.