Wednesday, 6 February 2019

Using Git Worktree, Branch and Merge on Multiple Heroku Environments

Git worktree is a handy feature when a developer is working on major upgrade, such as between Swift upgrade or any major version upgrade that are breaking existing API.

Create a Staging Environment on Heroku
If you are hosting your app on Heroku, you can create a staging app using heroku CLI (command line interface).  The following two command create elostaging remote and rename the auto-created app name, salty-garden-12345 to elostaging.
$ heroku create --remote elostaging
$ heroku apps:rename elostaging --app salty-garden-12345

Create a Branch and Worktree
Organise your directory structure
Git stores it depository in local .git folder and therefore it allows you to restructure your working folder easily.  My original working folder is ~/code/elo.  To allow easier organization of main and branches.  I re-structure my app, elo, working folders to the followings structure.

This can be done via 3 commands.
$ mv ~/code/elo main 
$ mkdir ~/code/elo
$ mv main ~/code/elo/

Create a Branch
$ cd ~/code/elo/main
$ git branch branch-4.0

Create a Worktree for the Branch
$ cd ~/code/elo/main
$ git worktree add ../branch-4.0 branch-4.0

Commit Changes to Branch
$ cd ~/code/elo/main
$ git add file1 file2
$ git commit -a "Updated"

Deploy from a Branch to Heroku Staging
You can deploy from a branch to staging with the following syntax.
$ cd ~/code/elo/branch-4.0
$ git push elostaging branch-4.0:master

Merge a Branch into Master
Suppose you are done with all works in the branch, you can merge the changes back to master using the following commands.  You will need to issue the merge command in the master worktree.

$ cd ~/code/elo/main
$ git merge branch-4.0
Updating xxxxxxa..yyyyyy2
 file1 |  9 +++++++++
 file2 | 16 ++++++++++++++++
 2 files changed, 29 insertions(+)

Delete Worktree
You can delete a worktree by deleting the folder and run
$ cd ~/code/elo
$ rm -rf branch-4.0
$ cd ~/code/elo/main
$ git worktree prune

Merge Production Fixes in Master to Branch
While you are working on a branch, you also make a hot fix in the master.  You can bring the changes in master back into the branch so that you have less work to merge in the future.

$ cd ~/code/elo/branch-4.0
$ git merge master
Auto-merging readme.txt
CONFLICT (content): Merge conflict in readme.txt
Auto-merging xxx/yyy.js
Auto-merging xxx/zzz.js
Automatic merge failed; fix conflicts and then commit the result.

In this case, merge the conflict in readme.txt manually.  Test and then commit the changes into branch4.0.

git add readme.txt
$ git commit -m "merged production hotfix"

These are useful references on worktree, heroku, git branching and merging.
  1. SaltyCrane git-worktree-notes
  2. Useful commands from Matts
  3. Git Branching and Merging Basic
  4. Managing Multiple Environments for Heroku App

No comments:

Post a comment