https://www.theserverside.com/blog/Coffee-Talk-Java-News-Stories-and-Opinions/How-to-git-clone-a-specific-branch-only
To git clone only a single, specific Git branch, issue this command:
git clone --single-branch --branch development https://github.com/username/project.git
The steps to clone a specific Git branch differ from a typical clone command in two ways:
Here is an example of clone of a single branch from a GitHub repo.
git-clone@branch:~$ git clone --single-branch --branch development https://github.com/username/project.git * development remotes/origin/development
Notice how a request to list all branches after a single Git branch has been cloned only shows two things:
git-clone@branch:~$ git branch --all * development remotes/origin/development
This proves that indeed the command only cloned a single, specific Git branch on the remote server.
Contrast the output above to the result of a normal clone operation, as follows:
git-clone@branch:~$git clone https://github.com/username/project.git * master remotes/origin/HEAD -> origin/master remotes/origin/develop remotes/origin/hotfix remotes/origin/master remotes/origin/release
As you can see, without parameterization, a normal git clone command makes the default main or master branch local, and maintains remote references to other branches that the developer can checkout or switch to at will.
For CI/CD pipelines built with tools such as Jenkins, GitHub Actions or TeamCity, it makes sense to only clone a single, specific Git branch.
However, for day-to-day development operations the consequences of cloning only a single branch make it more difficult to merge code and switch between branches.
After you git clone a specific branch, your local copy of the remote repo has two attributes:
For example, in this single branch clone example, we have not copied the main or master branch.
Any attempts to check out the main or master branch will trigger a pathspec error telling us the branch does not exist locally, despite the fact that it does indeed exist on the remote repo we cloned.
git-clone@branch:~$ git checkout master error: pathspec 'master' did not match any file(s) known to git
git-clone@branch:~$ git checkout main
error: pathspec ‘main’ did not match any file(s) known to git
To fix the pathspec error, the developer must do one of two things:
Continuous integration builds commonly require cloning only a single, specific Git branch.
After all, if you’re just compiling the latest commit in the development branch, why clone every other branch in the process?
If this is the case, you might also want to limit the git clone depth.
If you set the clone depth to 1, you’ll only get the latest commit, not the entire history of the project.
It’s a nice feature that might save your Jenkins server or GitHub Actions routine some clock-cycles.
It’ll save your CI/CD pipeline servers some hard drive space.
02 Sep 2023