Last active
September 26, 2024 08:58
-
-
Save ajitid/582a41fb76656cdfb98e4087fbfdda33 to your computer and use it in GitHub Desktop.
Git copy contents
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { $ } from 'dax-sh' | |
export const getCommitHashFromTagName = async ( | |
tagName: string, | |
cwd: string | |
): Promise<string | null> => { | |
try { | |
const v = await $`git rev-list -n 1 ${tagName}`.cwd(cwd).quiet() | |
return v.stdout.trim() | |
} catch { | |
return null | |
} | |
} | |
export const isValidCommitHash = async (hash: string, cwd: string): Promise<boolean> => { | |
try { | |
// taken from https://stackoverflow.com/a/31780867 | |
const type = '^{commit}' // done to escape this, otherwise the cmd fails | |
await $`git cat-file -e ${hash}${type}`.cwd(cwd).quiet() | |
return true | |
} catch (err) { | |
return false | |
} | |
} | |
interface CopyGitRepoContentsArgs { | |
gitRepoRoot: string | |
commitHash: string | |
pathToCopy: string | |
toDir: string | |
} | |
export const copyGitRepoContents = async ({ | |
commitHash, | |
gitRepoRoot, | |
pathToCopy, | |
toDir, | |
}: CopyGitRepoContentsArgs): Promise<void> => { | |
// devised from https://stackoverflow.com/questions/4479960/checkout-to-a-specific-folder and docs | |
await $`git worktree add -d --no-checkout ${toDir}`.cwd(gitRepoRoot).quiet() | |
await $`git checkout ${commitHash} -- ${pathToCopy}`.cwd(toDir).quiet() | |
} | |
export const postCopyGitRepoContents = async ({ | |
gitRepoRoot, | |
toDir, | |
}: Pick<CopyGitRepoContentsArgs, 'toDir' | 'gitRepoRoot'>): Promise<void> => { | |
await $`rm -r .git`.cwd(toDir) // makes the dir prunable | |
await $`git worktree prune`.cwd(gitRepoRoot) // only removes the dangling entries, doesn't deletes their folder | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
async function copyConfigFiles( | |
projectRoot: string, | |
commitHash: string, | |
configDirRelativeToProjectRoot: string, | |
toDir: string | |
) { | |
try { | |
await copyGitRepoContents({ | |
gitRepoRoot: projectRoot, | |
commitHash, | |
pathToCopy: configDirRelativeToProjectRoot, | |
toDir: toDir, | |
}) | |
await postCopyGitRepoContents({ | |
gitRepoRoot: projectRoot, | |
toDir: toDir, | |
}) | |
} catch { | |
await postCopyGitRepoContents({ | |
gitRepoRoot: projectRoot, | |
toDir: toDir, | |
}) | |
return Promise.reject( | |
`Couldn't make a copy of config files. Does ${configDirRelativeToProjectRoot} exists in ${commitHash} commit hash?` | |
) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment