Skip to content

Instantly share code, notes, and snippets.

@mholtzhausen
Last active May 12, 2020 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mholtzhausen/5e39fa123aaf054b55ad36d8a4ccb4cf to your computer and use it in GitHub Desktop.
Save mholtzhausen/5e39fa123aaf054b55ad36d8a4ccb4cf to your computer and use it in GitHub Desktop.
Find the first occurance of a string in the git-history of a file

git.find.first

I needed a tool to tell me the first time a certain string appeared in the git-history of a file. It was a node package, and I wanted to find out why it first got included.

Usage

node git.find.first.js <path-to-file> <search-term> [--open]

--open will open a github-url for that commit if you have a github repository

#!/usr/bin/env node
const [targetFile, searchTerm] = process.argv.slice(2)
const { execSync } = require('child_process')
const path = require('path')
const log = str => process.stdout.write(str)
let cwd = process.cwd()
const shell = (command) => execSync(command, { cwd, stdio: ['pipe', 'pipe', 'pipe'], encoding: 'utf8' }).toString()
//cls
process.stdout.write('\x1b[2J');
if (!searchTerm || !targetFile) {
console.log('Usage: git.search.first <targetFile> <searchTerm>')
console.log({ searchParam: searchTerm, targetFile, cwd })
process.exit(-1)
}
const fixPath= p=>p.replace(/^(\\|\/)/g, '')
const gitRoot = shell('git rev-parse --show-toplevel').replace('\n', '')
const targetFileFromRoot = fixPath([fixPath(cwd.replace(gitRoot, '')), targetFile].join(path.sep))
//find all commits that the file was
let logs = shell(`git log --oneline --follow ${targetFile}`)
//parse into array of commits
let commits = logs.split('\n').map(l => l.split(' ')[0]).reverse().filter(c => !!c)
//start looking for the text
let fcommit = commits.find(c => {
let content = ''
try {
content = shell(`git show ${c}:${targetFileFromRoot}`).toString()
} catch (e) {
return false
}
let pos = content.indexOf(searchTerm)
if (pos >= 0) return true
return false
})
// if no commit was found -- kill the process
if (!fcommit) {
console.log(`could not find '${searchTerm}' in the git history of '${targetFile}'`)
process.exit(0)
}
// get the remote url
let remote = shell(`git config --get remote.origin.url`).trim('\n')
// if github
if (remote.indexOf('git@github.com:') >= 0) {
remote = remote.replace('git@github.com:', 'https://github.com/').replace(/\.git$/, '') + `/commit/${fcommit}#:~:text=${searchTerm}`
console.log(`\n\nFound '${searchTerm}' \nin ${targetFile} \nfirst introduced in commit ${fcommit} \n\n${remote}\n\n`)
if (process.argv.slice(2).indexOf('--open') >= 0) shell(`open "${remote}"`)
process.exit()
}
console.log(`\n\nFound '${searchTerm}' in \n${targetFile} \nfirst introduced in commit ${fcommit}\n\n`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment