Skip to content

Commit

Permalink
feat: add option to stop git.find at a directory
Browse files Browse the repository at this point in the history
  • Loading branch information
lukekarrys committed Jun 5, 2023
1 parent 17527e5 commit 8d48579
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 13 deletions.
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, normalize } = 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 = normalize('/') } = {}) => {
while (true) {
if (await is({ cwd })) {
return cwd
}
const next = dirname(cwd)
if (cwd === root || cwd === next) {
return null
}
cwd = next
}
return null
}
7 changes: 3 additions & 4 deletions lib/is.js
@@ -1,6 +1,5 @@
// not an airtight indicator, but a good gut-check to even bother trying
const { promisify } = require('util')
const fs = require('fs')
const stat = promisify(fs.stat)
const fs = require('fs/promises')
const { join } = require('path')
module.exports = ({ cwd = process.cwd() } = {}) =>
stat(cwd + '/.git').then(() => true, () => false)
fs.stat(join(cwd, '.git')).then(() => true, () => false)
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

0 comments on commit 8d48579

Please sign in to comment.