|
#!/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`) |