import * as simpleGit from "simple-git" ; import { URL } from "url" ; import { CommitInfo } from "./git-metadata/interfaces" ; export const newSimpleGit = async ( ) : Promise < simpleGit . SimpleGit > => { const options = { baseDir : process . cwd ( ) , binary : "git" , maxConcurrentProcesses : 1 , } ; try { const git = simpleGit . gitP ( options ) ; const root = await git . revparse ( "--show-toplevel" ) ; options . baseDir = root ; } catch { } return simpleGit . gitP ( options ) ; } ; export const gitRemote = async ( git ) : Promise < string > => { const remotes = await git . getRemotes ( true ) ; if ( remotes . length === 0 ) { throw new Error ( "No git remotes available" ) ; } for ( const remote of remotes ) { if ( remote . name === "origin" ) { return stripCredentials ( remote . refs . push ) ; } } return stripCredentials ( remotes [ 0 ] . refs . push ) ; } ; export const stripCredentials = ( remote ) => { try { const url = new URL ( remote ) ; url . username = "" ; url . password = "" ; return url . toString ( ) ; } catch { return remote ; } } ; const gitHash = async ( git ) : Promise < string > => git . revparse ( "HEAD" ) ; export const gitTrackedFiles = async ( git ) : Promise < string [ ] > => { const files = await git . raw ( "ls-files" ) ; return files . split ( /\r\n|\r|\n/ ) . filter ( ( s ) => s !== "" ) ; } ; export const getCommitInfo = async ( git , repositoryURL ? ) : Promise < CommitInfo | undefined > => { let remote ; let hash ; let trackedFiles ; try { if ( repositoryURL ) { [ hash , trackedFiles ] = await Promise . all ( [ gitHash ( git ) , gitTrackedFiles ( git ) ] ) ; remote = repositoryURL ; } else { [ remote , hash , trackedFiles ] = await Promise . all ( [ gitRemote ( git ) , gitHash ( git ) , gitTrackedFiles ( git ) ] ) ; } } catch ( e ) { throw e ; } return new CommitInfo ( hash , remote , trackedFiles ) ; } ;