Using Git Effectively
Using git effectively can be a challenge for a lot of people. I'm going to run through a quick tutorial on how I like to use Git to segment my changes, manage my branches, and merge my code.
Basic command tips
Here are the basic Git commands that I use over and over throughout the day
# Adds all new files to the repository
git add -A
# commit -am means "commit all files with the following message"
# Messages are required in Git commits
git commit -am 'my new changes!'
# Push your changes
git push remote_name branch_name
# Pull the latest code
git pull remote_name branch_name
# Switches branches
git checkout my_branch
# Creates a new branch called "branch", and switches into that branch
git checkout -b branch
# Merges the specified branch into the current branch
git merge other_branch
### Segment Changes
Seriously, if you work on an application that already has a user base, segmenting changes is so, so important. Let's say your on the master branch and you would like to implement two new features, a new login form, and a new dashboard. Put these changes into separate branches. Here's how.
# On master
# creates a new branch called login and moves into that branch
git checkout -b login
# Now make the new login page, and commit your changes
git commit -am 'new login page'
# Great job, now let's make the new dashboard
# Switch back to master
git checkout master
# Now make another copy of the master branch, and switch into it
git checkout -b dashboard
# Make the new dashboard, and commit your changes
git commit -am 'new dashboard!'
# Now you have three branches: master, dashboard, and login
# When your code has been tested and/or looked over, you can merge
git checkout master
git merge dashboard
git merge login
See how clean and easy it was to make changes in separate branches, and then merge them when we're ready.
Managing branches & merging
If you are working on applications that can't break, you probably have a staging environment set up for them. If you have a staging environment, you probably have three different remote git repositories, origin (on github.com), staging, and production, or something to that effect. When I have to make changes here is what I like to do.
# From branch master
git checkout -b my_change
# Do work & commit
git commit -am 'did work'
# Make a staging branch from the my_change branch
git checkout -b staging
# Push to the staging branch to the master branch on the staging server
git push staging staging:master
# Now that we're sure everything works
git checkout master
# Merge either the whole staging branch,
# or if you have multiple changes, merge
# them one by one.
git merge staging
# OR
git merge my_change