Skip to content

Commit fba156e

Browse files
path utils
1 parent cbd44a8 commit fba156e

File tree

2 files changed

+81
-2
lines changed

2 files changed

+81
-2
lines changed

cli/_utils/path/index.ts

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import fs from "fs";
2+
import path from "path";
3+
4+
/**
5+
* finds file with name in cwd
6+
*
7+
* e.g. package.json -> <cwd>/package.json
8+
*
9+
* @param name
10+
* @param cwd
11+
* @returns
12+
*/
13+
export function find_in_cwd(name, cwd = process.cwd()) {
14+
const file = path.join(cwd, name);
15+
if (fs.existsSync(file)) {
16+
return file;
17+
}
18+
return null;
19+
}
20+
21+
/**
22+
* find file in parent directory (recursively)
23+
* cwd
24+
* ../package.json
25+
* ../../package.json
26+
* ../../../package.json
27+
* ...
28+
*/
29+
export function find_in_parent(name, cwd = process.cwd(), recursively = true) {
30+
const parent_dir = path.dirname(cwd);
31+
if (parent_dir === cwd) {
32+
return null;
33+
}
34+
const file = path.join(parent_dir, name);
35+
if (fs.existsSync(file)) {
36+
return file;
37+
}
38+
if (recursively) {
39+
return find_in_parent(name, parent_dir, recursively);
40+
}
41+
return null;
42+
}

cli/npm/index.ts

Lines changed: 39 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,41 @@
1+
import type { IPackageManifest } from "@web-builder/nodejs";
2+
import path from "path";
3+
import { find_in_cwd, find_in_parent } from "../_utils/path";
4+
5+
const _PACKAGE_JSON = "package.json";
6+
17
/**
2-
* finds a package root with package.json search
8+
* finds a npm pacakge root with package.json search
39
*/
4-
export function findPackageRoot() {}
10+
export function locatePackage(cwd = process.cwd()): {
11+
base_dir: string;
12+
package_json: string;
13+
manifest: IPackageManifest;
14+
} | null {
15+
const packagejson = find_in_cwd(_PACKAGE_JSON, cwd);
16+
if (packagejson) {
17+
return {
18+
base_dir: path.dirname(packagejson),
19+
package_json: packagejson,
20+
manifest: read(packagejson),
21+
};
22+
}
23+
const packagejson_in_parent_dir = find_in_parent(_PACKAGE_JSON, cwd, true);
24+
if (packagejson_in_parent_dir) {
25+
return {
26+
base_dir: path.dirname(packagejson_in_parent_dir),
27+
package_json: packagejson_in_parent_dir,
28+
manifest: read(packagejson_in_parent_dir),
29+
};
30+
}
31+
return null;
32+
}
33+
34+
/**
35+
* returns the config object by reading package.json file
36+
* @param path
37+
* @returns
38+
*/
39+
export function read(path): IPackageManifest {
40+
return require(path);
41+
}

0 commit comments

Comments
 (0)