|  | 
|  | 1 | +import { exec, removeFile } from '../node' | 
|  | 2 | + | 
|  | 3 | +interface Input { | 
|  | 4 | +  hash: string | 
|  | 5 | +  branch: string | 
|  | 6 | +} | 
|  | 7 | + | 
|  | 8 | +const ignoreError = () => {} | 
|  | 9 | + | 
|  | 10 | +// note: attempted to do this as a bash script | 
|  | 11 | +// but requires the bash script has git permissions | 
|  | 12 | +const reset = async ({ branch, hash }: Input): Promise<void> => { | 
|  | 13 | +  const remote = 'coderoad' | 
|  | 14 | + | 
|  | 15 | +  try { | 
|  | 16 | +    // if no git init, will initialize | 
|  | 17 | +    // otherwise re-initializes git | 
|  | 18 | +    await exec({ command: 'git init' }).catch(console.log) | 
|  | 19 | + | 
|  | 20 | +    // capture current branch | 
|  | 21 | +    const hasBranch = await exec({ command: 'git branch --show-current' }) | 
|  | 22 | +    const localBranch = hasBranch.stdout | 
|  | 23 | +    // check if coderoad remote exists | 
|  | 24 | +    const hasRemote = await exec({ command: 'git remote -v' }).catch(console.warn) | 
|  | 25 | +    if (!hasRemote || !hasRemote.stdout || !hasRemote.stdout.length) { | 
|  | 26 | +      throw new Error('No remote found') | 
|  | 27 | +    } else if (!hasRemote.stdout.match(new RegExp(remote))) { | 
|  | 28 | +      throw new Error(`No "${remote}" remote found`) | 
|  | 29 | +    } | 
|  | 30 | + | 
|  | 31 | +    // switch to an empty branch | 
|  | 32 | +    await exec({ | 
|  | 33 | +      command: 'git checkout --orphan reset-orphan-branch', | 
|  | 34 | +    }) | 
|  | 35 | +    // stash any current work | 
|  | 36 | +    await exec({ | 
|  | 37 | +      command: 'git stash', | 
|  | 38 | +    }).catch(ignoreError) | 
|  | 39 | + | 
|  | 40 | +    // remove any other files | 
|  | 41 | +    await exec({ | 
|  | 42 | +      command: 'git rm -rf .', | 
|  | 43 | +    }).catch(ignoreError) | 
|  | 44 | +    await removeFile('.gitignore').catch(ignoreError) | 
|  | 45 | + | 
|  | 46 | +    await exec({ | 
|  | 47 | +      command: `git branch -D ${localBranch}`, | 
|  | 48 | +    }) | 
|  | 49 | +    await exec({ | 
|  | 50 | +      command: `git checkout -b ${localBranch}`, | 
|  | 51 | +    }) | 
|  | 52 | + | 
|  | 53 | +    // load git timeline | 
|  | 54 | +    await exec({ | 
|  | 55 | +      command: `git fetch coderoad ${branch}`, | 
|  | 56 | +    }) | 
|  | 57 | +    await exec({ | 
|  | 58 | +      command: `git merge coderoad/${branch}`, | 
|  | 59 | +    }) | 
|  | 60 | +    // reset to target commit hash | 
|  | 61 | +    await exec({ | 
|  | 62 | +      command: `git reset --hard ${hash}`, | 
|  | 63 | +    }) | 
|  | 64 | +  } catch (error) { | 
|  | 65 | +    console.error('Error resetting') | 
|  | 66 | +    console.error(error.message) | 
|  | 67 | +  } | 
|  | 68 | +} | 
|  | 69 | + | 
|  | 70 | +export default reset | 
0 commit comments