diff --git a/README.md b/README.md index ca8afcb..03a8786 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,8 @@ or a file named `.git`. Given a path, walk up the file system tree until a git repo working directory is found. Since this calls `stat` a bunch of times, it's probably best to only call it if you're reasonably sure you're likely to be -in a git project somewhere. +in a git project somewhere. Pass in `opts.root` to stop checking at that +directory. Resolves to `null` if not in a git project. diff --git a/lib/find.js b/lib/find.js index d58f01d..e520ce8 100644 --- a/lib/find.js +++ b/lib/find.js @@ -1,15 +1,15 @@ const is = require('./is.js') -const { dirname } = require('path') +const { dirname, sep } = require('path') -module.exports = async ({ cwd = process.cwd() } = {}) => { - if (await is({ cwd })) { - return cwd - } - while (cwd !== dirname(cwd)) { - cwd = dirname(cwd) +module.exports = async ({ cwd = process.cwd(), root = sep } = {}) => { + while (true) { if (await is({ cwd })) { return cwd } + const next = dirname(cwd) + if (cwd === root || cwd === next) { + return null + } + cwd = next } - return null } diff --git a/test/find.js b/test/find.js index 57d7287..3101912 100644 --- a/test/find.js +++ b/test/find.js @@ -1,4 +1,5 @@ const t = require('tap') +const { join } = require('path') const find = require('../lib/find.js') t.test('find the git dir many folders up', t => { @@ -10,6 +11,24 @@ t.test('find the git dir many folders up', t => { return t.resolveMatch(find({ cwd: path }), root) }) +t.test('stop before root dir', t => { + const root = t.testdir({ + '.git': { index: 'hello' }, + a: { b: { c: { d: { e: {} } } } }, + }) + const path = `${root}/a/b/c/d/e` + return t.resolveMatch(find({ cwd: path, root: join(root, 'a') }), null) +}) + +t.test('stop at root dir', t => { + const root = t.testdir({ + '.git': { index: 'hello' }, + a: { b: { c: { d: { e: {} } } } }, + }) + const path = `${root}/a/b/c/d/e` + return t.resolveMatch(find({ cwd: path, root }), root) +}) + t.test('find the git dir at current level', t => { const cwd = t.testdir({ '.git': { index: 'hello' },