---
# System prepended metadata

title: Query 130

---

To perform a shallow clone of a Git repository while including all branches using GitPython, you can use the following Python script [1][2]:
```
# Import necessary modules from GitPython
from git import Repo

# Define the URL of the Git repository you want to clone
repository_url = 'https://github.com/username/repo.git'

# Specify the local directory where you want to clone the repository
local_directory = '/path/to/local/directory'

# Depth for the initial clone (1 for a single commit)
shallow_clone_depth = 1

try:
    # Clone the repository with a shallow clone (depth 1)
    repo = Repo.clone_from(repository_url, local_directory, depth=shallow_clone_depth)

    # If the clone was successful, print a success message
    print(f'Successfully shallow cloned {repository_url} to {local_directory}')

    # Fetch all branches from the remote
    for remote_ref in repo.remotes.origin.refs:
        remote_ref_name = str(remote_ref).split('/', 2)[-1]  # Extract the branch name
        repo.create_head(remote_ref_name, remote_ref)

    # Update the remote branches
    repo.remotes.origin.update()

    # If the fetch was successful, print a success message
    print('Fetched all remote branches')

except Exception as e:
    # If an error occurs during cloning, print an error message
    print(f'Error: {e}')
```
Explanation of the code:

* Import the necessary modules from GitPython, including the Repo class.
* Define the URL of the Git repository you want to clone and the local directory where you want to clone it. Replace `https://github.com/username/repo.git` and ``/path/to/local/directory`` with the actual repository URL and local directory path.
* Set the shallow_clone_depth variable to 1 to perform the initial shallow clone, which retrieves only the latest commit.
* Inside a try block, clone the repository with a shallow clone using Repo.clone_from. This retrieves only the latest commit.
* After the clone, you can use a loop to fetch and create local branches for all remote branches. This step ensures that you have access to all branches in the local repository.
* Update the remote branches using repo.remotes.origin.update() to ensure your local branches are synchronized with the remote repository.
* If the clone and fetch were successful, print success messages.
* If an error occurs during any step, an error message is printed.

This script performs a shallow clone while including all branches in the local repository using GitPython. Make sure to replace the placeholders with your specific repository URL and local directory path.