Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add option to stop git.find at a directory #135

Merged
merged 1 commit into from Jun 5, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Expand Up @@ -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.

Expand Down
16 changes: 8 additions & 8 deletions 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
}
19 changes: 19 additions & 0 deletions 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 => {
Expand All @@ -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' },
Expand Down