Skip to content

Commit 4b127eb

Browse files
committed
feature: @putout/operator-filesystem: getRootDirectory: add
1 parent 04dd5ed commit 4b127eb

File tree

3 files changed

+31
-4
lines changed

3 files changed

+31
-4
lines changed

packages/operator-filesystem/README.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,20 @@ dirPath === getParentDirectory(newDirectoryPath);
140140
true;
141141
```
142142

143+
### `getRootDirectory(path: FilePath | DirectoryPath): DrectoryPath`
144+
145+
```js
146+
const {operator} = require('putout');
147+
const {
148+
findFile,
149+
getRootDirectory,
150+
} = operator;
151+
152+
const [filePath] = findFile(ast, 'hello');
153+
154+
getRootDirectory(dirPath);
155+
```
156+
143157
### `getFilename(path: FilePath | DirectoryPath): string`
144158

145159
```js

packages/operator-filesystem/lib/filesystem.js

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -399,22 +399,21 @@ module.exports.createNestedDirectory = (path, name) => {
399399
return lastDirectoryPath;
400400
};
401401

402+
module.exports.getRootDirectory = getRootDirectory;
402403
function getRootDirectory(path) {
403404
let currentDirPath = getParentDirectory(path);
404405

405406
if (!currentDirPath)
406407
return path;
407408

408-
let prevPath = path;
409+
let prevPath = currentDirPath;
409410

410411
while (currentDirPath = getParentDirectory(currentDirPath)) {
411412
prevPath = currentDirPath;
412413
}
413414

414415
return prevPath;
415-
}
416-
417-
module.exports.init = maybeFS.init;
416+
}module.exports.init = maybeFS.init;
418417
module.exports.deinit = maybeFS.deinit;
419418

420419
module.exports.pause = maybeFS.pause;

packages/operator-filesystem/lib/filesystem.spec.js

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,7 @@ const {
2727
createNestedDirectory,
2828
readDirectory,
2929
getParentDirectory,
30+
getRootDirectory,
3031
readFileContent,
3132
writeFileContent,
3233
init,
@@ -1282,3 +1283,16 @@ test('putout: operator: filesystem: pause', (t) => {
12821283
t.equal(pause, maybeFS.pause);
12831284
t.end();
12841285
});
1286+
1287+
test('putout: operator: filesystem: getRootDirectory', (t) => {
1288+
const ast = parseFilesystem(['/hello/world/', '/hello/world/package.json']);
1289+
1290+
const [filePath] = findFile(ast, 'package.json');
1291+
const rootDirectoryPath = getRootDirectory(filePath);
1292+
const filename = getFilename(rootDirectoryPath);
1293+
1294+
const expected = '/hello/world';
1295+
1296+
t.equal(filename, expected);
1297+
t.end();
1298+
});

0 commit comments

Comments
 (0)