Pioneered by Linux creator Linus Torvalds, Git ranks with caffeine as a software development essential. Git is a version control system that preserves a comprehensive record of the code in an application at all time points. With Git, each team member has a local repository and a full history with it. The Git system fosters accountability, productivity, and — best of all — creativity. It works as well for a hobbyist as it does for an international team. Branches empower Git, and knowing how to use branches is essential to the rapid deployment of web applications.
What Is a Git Branch?
While other version control systems include branches, Git empowered coders with near-instant branch creation and equally quick switching between branches. As programmers add or edit code in a branch, they save snapshots of their work with Git’s commit command. Each branch is thus a collection of snapshots, with each snapshot a collection of files needed to build an application.
Git does not store incremental changes. When changes occur, it stores an entire file and saves a pointer for unchanged files. Maintaining this structure on a local computer lessens overhead and solves the latency issues of other version systems.
How Do Git Branches Work?
When a programmer creates a new branch and begins adding new code, the files in the parent branch remain unchanged until the coder explicitly merges the changes back into the parent branch. With a well-organized tree, programmers never need to spin their wheels waiting for another team member to perfect their branch.
What Are Git’s Branch Commands?
Git’s branch management commands are the building blocks for modern software. With mastery of the syntax, coders can navigate their local tree and push their work to a remote repository.
Create a Git Branch
Here’s the syntax for creating a new local branch named “cool-new-feature”, with the “#” denoting a comment:
# create git branch
git branch cool-new-feature
Git’s branch names may not contain a space or these characters:
- Two or more consecutive dots
Git permits very long branch names, but some online programming environments discourage names exceeding 32 characters.
Create a Remote Branch
With a URL to a configured repository account, users can create a remote branch with these commands:
git remote add my-remote-repo http://bigrepobucket.com/user/repo.git
git push <my-remote-repo> cool-new-feature~
A list comes in handy to stay on top of their branches. Git’s list command
# List local branches
# List remote branches
git branch -r
# list all branches
git branch -a
# display the working branch
Move Among Branches
Creating a branch does not make that new branch the current branch. Programmers must explicitly move to a branch to add or edit code. Git’s checkout command handles this vital task:
git checkout cool-new-feature
Git’s track flag enables checking out to a remote branch:
git checkout --track origin/cool-new-feature
Merge a Branch
If the code in a branch passes all tests, a programming team can merge the changes back into its parent branch. These commands return to the parent branch and merge the code:
git checkout main
git merge cool-new-feature
Along with merging all the commits from “cool-new-feature” into “main,” the merge command creates a new commit to record the merge.
Remove a Branch
After a programmer has merged a branch into the main code, the coder can delete the branch without losing any history. This syntax deletes a merged branch:
# remove git branch example
git branch -d cool-new-feature
When a coder executes this command on an unmerged branch, Git flashes an error warning to forestall a loss of history. However, there are times when deleting an unmerged branch is precisely what a programmer wants. Git fosters experimentation. As every coder learns, some experiments go awry. Deleting a branch needs this syntax:
git branch -D world-changing-branch
This command will delete the branch without an “Are you sure?” warning, so coders should exercise care with the capital “D” flag.
Remove a Remote Branch
The “-d” or “-D” flags enable the deletion of locally stored branches. Deleting a branch from a remote repository requires Git’s push command. Here are three equivalent syntaxes to execute a remote branch deletion:
# delete remote branch examples
git push origin --world-changing-branch
git push origin -d world-changing-branch
git push origin :world-changing-branch
Rename a Branch
In the coding pressure cooker, a programmer may decide that a branch name needs improvement. Git’s counterintuitively named branch
--move command pulls off this change for a local branch:
# rename git branch locally
git branch --move mediocre-name new-and-improved-name
This command only changes the local branch name and leaves all files and history intact. Pulling off a branch rename for a remote repository takes two steps. First, the Git’s
push --set-upstream command creates a copy of the local “new-and-improved-name” branch on the remote repository:
git push --set-upstream origin new-and-improved-branch-name
This action still leaves branch “mediocre-name” on the remote. Deleting the duplicate with any of the remote deletion syntaxes will tidy the remote repository:
git push origin --delete mediocre-name
What Are Git Branch Best Practices for Workflow?
While there is no one-size-fits-all Git strategy that will work for every environment, there are practices that aid efficiency, accountability, and security.
Keep the Main Branch Working
For most of Git’s history, creating a new repository with the Init command also created a default branch named “master.” Connotations with slavery have led most professional organizations to rename their “master” branches to “main.” Git’s proprietors plan to make the system default to “main” in a future release, but current releases now include a message urging users to rename the default branch after invoking the init command.
Whether a programming team is large or small, it pays to keep the main branch functional at all times. Ideally, the main branch’s most recent commit contains the latest fully tested version of the application. Keeping the main branch in this condition means that no programmer needs to stop and wait for another team member to complete a task.
Develop a Branch Use Strategy
With the main branch always functional, a team needs a strategy that utilizes Git’s flexibility without allowing a project to grow into a rat’s nest of branches. Microsoft’s Azure team recommends branches for these programming tasks.
Release branches are how application developers ring the cash register. The Azure team recommends creating release branches from the latest commit of the main branch. Once created, a release branch receives no further edits, commits, or merges. This routine maintains an easy-to-search archive of releases, a boon for performing the inevitable bug fixes.
A release branch’s name should include the version and sub-version that customers will see. This approach guarantees that user bug reports refer to the correct release. Including a Unix-style release date in YYYY-MM-DD format also aids release branch readability.
Feature branches should have tightly defined goals for adding a capability to an application and may include a calendar deadline for shops that employ sprints. Before merging into the main branch, a feature branch should receive a scan with a capable software composition analysis tool. With scanned trouble spots eliminated, the code should receive a review from a programmer skilled in spotting architecture defects. After the gauntlet of scans and human eyeballs, a feature branch is ready for merging into its parent branch.
When a customer encounters a critical shortcoming in a recent release — the software equivalent of a five-alarm fire — a hotfix branch is a necessary move. The branch’s purpose is to solve or patch a critical issue.
Once a solution passes verification tests, the next move depends on the developer’s business model. A developer offering custom applications to clients should issue a one-shot release for the client’s evaluation. Developers serving a broader market can issue an interim release. Since bug reports generate customer response tickets, the name for a hotfix branch should include the ticket number.
As with hotfix branches, a bug fix branch is a single-issue branch created to solve a flaw found by a customer. Bug fixes address less severe issues, and the corrected code from these branches can merge into a scheduled software update release. Bugfix branch names should also include the customer response ticket number.
The Name Game
With the purpose of branches established, nailing down a consistent naming scheme aids readability among team members. Git allows hyphens, underscores, and forward slashes for separators in branch names. Microsoft’s Azure team names their feature branches with the coder’s account name, a slash, and a short description of the feature’s purpose:
Massive projects may substitute a team name for an individual. Any naming scheme should be consistent and intuitive enough for newcomers to learn quickly.
Git Security Best Practices
With massive numbers of files and coders contributing to remote repositories, it’s no surprise that Git opens the door to security issues. Disciplined attention to sound coding practices can lower the risk.
Implement Authentication Standards
Nearly all web applications use remote repositories to enable collaboration, which makes secure access essential. Securing that connection in this era requires — at a minimum — two-factor authorization. While SMS text message verification offers some protection, any professional coding operation should aim higher. Timed one-time passwords are less vulnerable to interception by hackers. Smartphone TOTP authenticator apps such as Authy, Google Authenticator, and Microsoft Authenticator work for both Android and Apple’s iOS.
A better solution is a hardware token. Available from Yubico, Thetis, Kensington, and Google’s Titan line, hardware tokens plug into a computer’s USB port. Hardware tokens move beyond TOTP with the Fast Identity Online Protocol. FIDO does away with passwords entirely. Tapping a button after a login prompt completes the verification. Most tokens are the size of a thumb drive, but Yubico and Kensington offer tiny models suitable for laptop computers.
GitHub and BitBucket currently support Yubikeys, with GitLab planning to roll out support. Each token requires an individual 20-minute setup routine, and equipping team members with a primary and backup token makes sense.
Stay Up to Date
Keeping the Git environment up to date is a no-brainer from a security standpoint. The git version command spits out the version of the local installation, and Git’s homepage displays the system’s current version.
Linux users can update their shells with these commands:
# install the system support packages
sudo apt-get update
# download and install Git’s latest version
sudo apt-get install git
One line in the shell updates Git for Windows coders:
macOS users can download an installer or invoke Homebrew to perform the update with this syntax:
brew upgrade git
Beyond the Git environment, it pays for developers to subscribe to and read the security feeds from their chosen repositories.
Keep Sensitive Files Away From Hackers
Git won over programmers by handling the tedious file management chores, allowing coders to focus on code. Part of this drudge work is handling hidden files. Hidden files perform utility services for applications but remain invisible unless a user invokes a particular operating system flag. These files may contain sensitive information such as access tokens or IP addresses. Allowing this data into a remote repository can prove catastrophic, making a multi-tiered strategy essential.
Adding at least one
.gitignore file to a repository is a basic security measure. A
.gitignore file lives up to its name. Git will not track or commit the specified files. In addition to the
.gitignore file in the repo’s highest directory level, a project may have additional versions of this file in subdirectories.
With more than one
.gitignorefile, Git resolves conflicts by assigning precedence to the file in the lowest subdirectory. Listing files individually would quickly become a nightmare, so Git includes a powerful pattern-matching capability to sweep up the files that need privacy.
Text Editor Configuration
The venerable vim text editor remains a favorite for many coders in all three popular operating systems, but the app’s default settings may leave sensitive info available to prying eyes. As programmers write their code, vim maintains these files:
- A swap file to preserve unsaved changes
- A backup file to handle power shutdowns from power outages
- An undo file to preserve several generations of saved code for rollbacks
By default, these files reside in the working directory where a programmer saves the code. In theory, a well-configured
.gitignore file will save the day. In practice, reconfiguring vim eliminates the issue.
Xilin Sun recommends appending these lines to vim’s .vimrc file:
This elegant solution walls off any chance of Git committing — and exposing — these potentially sensitive files. Better still, these settings create a portable temporary directory, a handy solution for coders who must swap work files between their laptop and desktop computers.
Git’s tagging feature allows coders to create annotated tags for selected points in an application’s history. Developers usually apply these tags to release branches but may also apply them to highlight other milestones. Among the possible annotations with Git tags is the option to include GNU Privacy Guard encryption. GPG uses public-key cryptography, a system that employs a public and private encryption key.
With GPG, two parties who wish to exchange data securely share their public keys. The sender can then sign a message with their private key. With GPG, the receiver can verify that the message came from an authorized sender and then decrypt the message. In Git, the message is code with an annotated GPG tag. The receiver is a remote repository, the destination for shipping an application. GPG tags assure a software team that incoming code comes from an authorized team member.
If an organization has already implemented FIDO hardware tokens to secure repository access, the same devices can also streamline the GPG signing process. Beyond signing tags, Git permits the direct signing of commits. With small teams, this step may add a small margin of security. With larger corporate teams, signing commits quickly leads to traffic jams, the very problem Git’s branching system aimed to prevent.
What Makes SOOS the Best SCA Scanning and Security Option?
Creating a Git release branch is a satisfying moment for any programming team. A mission-critical task on route to those milestones is a software composition analysis scan of the build files. Like your Git branching strategy, your scanning tool should enable the team to maintain momentum. That tool is SOOS, the SCA solution that delivers the features you need without the time-killing bloatware.
SOOS compares every file of your build against nearly 190,000 known vulnerabilities. With a scan completed, the SOOS dashboard displays found vulnerabilities in three tiers of severity. Malware isn’t the only industry hazard; licensing violations can paralyze an organization of any size. The SOOS governance wizard makes it a snap to create custom policies for licenses, packages, GitHub attributes, and more.
SOOS integrates with the CI/CD tools you’re already using. All of this capability comes with the simplest pricing plan in the industry. While naming your Git branches is a challenge, naming your SCA solution is easy: SOOS.