Skip to content

Commit ebede48

Browse files
committed
feat: add option to stop git.find at a directory
1 parent 17527e5 commit ebede48

File tree

3 files changed

+29
-9
lines changed

3 files changed

+29
-9
lines changed

README.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,8 @@ or a file named `.git`.
124124
Given a path, walk up the file system tree until a git repo working
125125
directory is found. Since this calls `stat` a bunch of times, it's
126126
probably best to only call it if you're reasonably sure you're likely to be
127-
in a git project somewhere.
127+
in a git project somewhere. Pass in `opts.root` to stop checking at that
128+
directory.
128129

129130
Resolves to `null` if not in a git project.
130131

lib/find.js

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
const is = require('./is.js')
2-
const { dirname } = require('path')
2+
const { dirname, sep } = require('path')
33

4-
module.exports = async ({ cwd = process.cwd() } = {}) => {
5-
if (await is({ cwd })) {
6-
return cwd
7-
}
8-
while (cwd !== dirname(cwd)) {
9-
cwd = dirname(cwd)
4+
module.exports = async ({ cwd = process.cwd(), root = sep } = {}) => {
5+
while (true) {
106
if (await is({ cwd })) {
117
return cwd
128
}
9+
const next = dirname(cwd)
10+
if (cwd === root || cwd === next) {
11+
return null
12+
}
13+
cwd = next
1314
}
14-
return null
1515
}

test/find.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
const t = require('tap')
2+
const { join } = require('path')
23
const find = require('../lib/find.js')
34

45
t.test('find the git dir many folders up', t => {
@@ -10,6 +11,24 @@ t.test('find the git dir many folders up', t => {
1011
return t.resolveMatch(find({ cwd: path }), root)
1112
})
1213

14+
t.test('stop before root dir', t => {
15+
const root = t.testdir({
16+
'.git': { index: 'hello' },
17+
a: { b: { c: { d: { e: {} } } } },
18+
})
19+
const path = `${root}/a/b/c/d/e`
20+
return t.resolveMatch(find({ cwd: path, root: join(root, 'a') }), null)
21+
})
22+
23+
t.test('stop at root dir', t => {
24+
const root = t.testdir({
25+
'.git': { index: 'hello' },
26+
a: { b: { c: { d: { e: {} } } } },
27+
})
28+
const path = `${root}/a/b/c/d/e`
29+
return t.resolveMatch(find({ cwd: path, root }), root)
30+
})
31+
1332
t.test('find the git dir at current level', t => {
1433
const cwd = t.testdir({
1534
'.git': { index: 'hello' },

0 commit comments

Comments
 (0)