conventional-changelog-action/src/helpers/git.js

141 lines
2.9 KiB
JavaScript

const core = require('@actions/core')
const exec = require('@actions/exec')
const { GITHUB_REPOSITORY, GITHUB_REF, ENV } = process.env
const branch = GITHUB_REF.replace('refs/heads/', '')
module.exports = new (class Git {
constructor() {
const githubToken = core.getInput('github-token', { required: true })
// Make the Github token secret
core.setSecret(githubToken)
const gitUserName = core.getInput('git-user-name')
const gitUserEmail = core.getInput('git-user-email')
// if the env is dont-use-git then we mock exec as we are testing a workflow locally
if (ENV === 'dont-use-git') {
this.exec = (command) => {
console.log(`Skipping "git ${command}" because of test env`)
}
}
// Set config
this.config('user.name', gitUserName)
this.config('user.email', gitUserEmail)
// Update the origin
this.updateOrigin(`https://x-access-token:${githubToken}@github.com/${GITHUB_REPOSITORY}.git`)
}
/**
* Executes the git command
*
* @param command
* @return {Promise<>}
*/
exec = (command) => new Promise(async(resolve, reject) => {
const exitCode = await exec.exec(`git ${command}`)
if (exitCode === 0) {
resolve()
} else {
reject(`Command "git ${command}" exited with code ${exitCode}.`)
}
})
/**
* Set a git config prop
*
* @param prop
* @param value
* @return {Promise<>}
*/
config = (prop, value) => this.exec(`config ${prop} "${value}"`)
/**
* Add a file to commit
*
* @param file
* @returns {*}
*/
add = (file) => this.exec(`add ${file}`)
/**
* Commit all changes
*
* @param message
* @param args
*
* @return {Promise<>}
*/
commit = (message, args = []) => (
this.exec(`commit -m "${message}" ${args.join(' ')}`)
)
/**
* Pull the full history
*
* @return {Promise<>}
*/
pull = async() => {
const args = ['pull']
// Check if the repo is unshallow
if (await this.isShallow()) {
args.push('--unshallow')
}
args.push('--tags')
args.push(core.getInput('git-pull-method'))
return this.exec(args.join(' '))
}
/**
* Push all changes
*
* @return {Promise<>}
*/
push = () => (
this.exec(`push origin ${branch} --follow-tags`)
)
/**
* Check if the repo is shallow
*
* @return {Promise<>}
*/
isShallow = async() => {
const isShallow = await this.exec('rev-parse --is-shallow-repository')
// isShallow does not return anything on local machine
if (isShallow) {
return isShallow.trim().replace('\n', '') === 'true'
} else {
return false
}
}
/**
* Updates the origin remote
*
* @param repo
* @return {Promise<>}
*/
updateOrigin = (repo) => this.exec(`remote set-url origin ${repo}`)
/**
* Creates git tag
*
* @param tag
* @return {Promise<>}
*/
createTag = (tag) => this.exec(`tag -a ${tag} -m "${tag}"`)
})()