Skip to content

Instantly share code, notes, and snippets.

@loopiezlol
Created April 10, 2018 14:12
Show Gist options
  • Save loopiezlol/e00c35b0166b4eae891ec6b8d610f83c to your computer and use it in GitHub Desktop.
Save loopiezlol/e00c35b0166b4eae891ec6b8d610f83c to your computer and use it in GitHub Desktop.
flow showing off how to clone, update and push to a git repo from an AWS lambda function
const fs = require('fs')
const path = require('path')
const process = require('process')
const { spawnSync } = require('child_process')
const { GITHUB_TOKEN, GITHUB_USERNAME, GITHUB_EMAIL } = process.env
// leaving this without https:// in order to reuse it when adding the remote
const gitRepositoryURL = 'github.com/owner/repo-name.git'
const repositoryName = 'repo-name'
function runCommand (commandString, options) {
const [command, ...args] = commandString.match(/(".*?")|(\S+)/g)
const cmd = spawnSync(command, args, options)
// you should probably obfuscate the credentials before logging
const errorString = cmd.stderr.toString()
if (errorString) {
throw new Error(
`Git command failed
${commandString}
${errorString}`
)
}
}
exports.handle = async function (event, context, callback) {
// install git binary
await require('lambda-git')()
// change the cwd to /tmp
process.chdir('/tmp')
// clone the repository and set it as the cwd
// sadly, clone doesn't support --porcelain
runCommand(`git clone --quiet https://${gitRepositoryURL}`)
process.chdir(path.join(process.cwd(), repositoryName))
// make your modifications to the local repository
fs.appendFileSync(
path.join(process.cwd(), 'README.md'),
'\nAutomagically inserted line'
)
// update local git config with email and username (required)
runCommand(`git config --local user.email ${GITHUB_EMAIL}`)
runCommand(`git config --local user.name ${GITHUB_USERNAME}`)
// stage local files
runCommand('git add .')
// commit changes
runCommand('git commit -m "commit by :robot:"')
// replace the remote with an authenticated one
runCommand('git remote rm origin')
runCommand(
`git remote add origin https://${GITHUB_USERNAME}:${GITHUB_TOKEN}@${gitRepositoryURL}`
)
// push changes to remote
runCommand('git push --porcelain --set-upstream origin master')
// terminate the lambda
callback(null, 'bye')
}
@yefriddavid
Copy link

yefriddavid commented Mar 16, 2020

People this line saved my life (aws lambda + nodjs)

const bug = spawnSync("ln", ["-s", "/usr/lib64/libpcre.so.1.2.0", "/tmp/git/usr/lib64/libpcre.so.0"])

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment