DEV Community

Pacharapol Withayasakpunt
Pacharapol Withayasakpunt

Posted on

How to add gitignored files to Heroku (and how not to)

Sometimes, you want to add extra files to Heroku or Git, such as built files, or secrets; but it is already in .gitignore, so you have to build on the server.

You have options, as this command is available.

git push heroku new-branch:master
Enter fullscreen mode Exit fullscreen mode

But how do I create such new-branch.

A naive solution would be to use git switch, but this endangers gitignored files as well. (It might disappear when you switch branch.)

That's where git worktree comes in.

I can use a real shell script, but I feel like using Node.js is much easier (and safer due to pour-console).

So, it is basically like this.

async function deploy (
  callback,
  deployFolder = 'dist',
  deployBranch = 'heroku',
  deployMessage = 'Deploy to Heroku'
) {
  // Ensure that dist folder isn't exist in the first place
  await pour('rm -rf dist')

  try {
    await pour(`git branch ${deployBranch} master`)
  } catch (e) {
    console.error(e)
  }

  await pour(`git worktree add -f ${deployFolder} ${deployBranch}`)

  await callback(deployFolder, deployBranch)

  await pour('git add .', {
    cwd: deployFolder
  })

  await pour([
    'git',
    'commit',
    '-m',
    deployMessage
  ], {
    cwd: deployFolder
  })

  await pour(`git push -f heroku ${deployBranch}:master`, {
    cwd: deployFolder
  })

  await pour(`git worktree remove ${deployFolder}`)

  await pour(`git branch -D ${deployBranch}`)
}

deploy(async (deployFolder) => {
  fs.writeFileSync(
    `${deployFolder}/.gitignore`,
    fs.readFileSync('.gitignore', 'utf8').replace(ADDED_FILE, '')
  )
  fs.copyFileSync(
    ADDED_FILE,
    `${deployFolder}/${ADDED_FILE}`
  )
}).catch(console.error)

Enter fullscreen mode Exit fullscreen mode

How not to commit

Apparently, this problem is easily solved on Heroku with

pour(`heroku config:set SECRET_FILE=${fs.readFileSync(secretFile, 'utf8')}`)
Enter fullscreen mode Exit fullscreen mode

Just make sure the file is deserializable.

You might even write a custom serializing function, with

JSON.stringify(obj[, replacer])

JSON.parse(str[, reviver])
Enter fullscreen mode Exit fullscreen mode

Don't forget that JSON object is customizable.

Top comments (0)