Skip to content

Commit

Permalink
add depth() method
Browse files Browse the repository at this point in the history
Returns the depth of the current path in the directory tree.

Fix: #3
Re: isaacs/node-glob#296
  • Loading branch information
isaacs committed Mar 1, 2023
1 parent eb89818 commit 842f33b
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 0 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -318,6 +318,13 @@ single tick if the stream is fully consumed.
Path object representing the current working directory for the
PathScurry.

#### `pw.depth(path?: Path | string): number`

Return the depth of the specified path (or the PathScurry cwd)
within the directory tree.

Root entries have a depth of `0`.

#### `pw.resolve(...paths: string[])`

Caching `path.resolve()`.
Expand Down Expand Up @@ -459,6 +466,11 @@ pathname matches, due to unicode normalization mismatches.
Always use this method instead of testing the `path.name`
property directly.

#### `path.depth()`

Return the depth of the Path entry within the directory tree.
Root paths have a depth of `0`.

#### `path.fullpath()`

The fully resolved path to the entry.
Expand Down
22 changes: 22 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,7 @@ export abstract class PathBase implements Dirent {
abstract sep: string

#matchName: string
#depth?: number
#fullpath?: string
#relative?: string
#type: number
Expand Down Expand Up @@ -238,6 +239,17 @@ export abstract class PathBase implements Dirent {
this.parent = opts.parent
}

/**
* Returns the depth of the Path object from its root.
*
* For example, a path at `/foo/bar` would have a depth of 2.
*/
depth(): number {
if (this.#depth !== undefined) return this.#depth
if (!this.parent) return (this.#depth = 0)
return (this.#depth = this.parent.depth() + 1)
}

/**
* @internal
*/
Expand Down Expand Up @@ -1293,6 +1305,16 @@ export abstract class PathScurryBase {
this.cwd = prev
}

/**
* Get the depth of a provided path, string, or the cwd
*/
depth(path: Path | string = this.cwd): number {
if (typeof path === 'string') {
path = this.cwd.resolve(path)
}
return path.depth()
}

/**
* Parse the root portion of a path string
*
Expand Down
10 changes: 10 additions & 0 deletions test/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1406,3 +1406,13 @@ t.test('can use file url as cwd option', t => {
t.equal(pus.cwd.fullpath(), process.cwd())
t.end()
})

t.test('depth', t => {
const ps = new PathScurry('/a/b/c/d')
t.equal(ps.depth(), 4)
t.equal(ps.depth('e/../g'), 5)
t.equal(ps.root.depth(), 0)
t.equal(ps.cwd.depth(), 4)
t.equal(ps.cwd.parent?.depth(), 3)
t.end()
})

0 comments on commit 842f33b

Please sign in to comment.