Can we get the branch name from Notebook
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Thursday
Hi Folks,
Is there a way to display the current git branch name from Databricks notebook
Thanks
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
Thursday
Yes, you can display the current git branch name from a Databricks notebook in several ways:
Using the Databricks UI
The simplest method is to use the Databricks UI, which already shows the current branch name:
- In a notebook, look for the button next to the notebook name that identifies the current Git branch
- Click this button to open the Git dialog where you can see your current working branch and perform other Git operations[
Using Code in a Notebook
If you need to programmatically get the branch name within your notebook code:
1. Use the Databricks API approach:
```python
import json
import requests
def get_current_branch():
nb_context = json.loads(dbutils.notebook.entry_point.getDbutils().notebook().getContext().toJson())
api_url = nb_context['extraContext']['api_url']
api_token = nb_context['extraContext']['api_token']
db_repo_data = requests.get(f"{api_url}/api/2.0/repos",
headers = {"Authorization": f"Bearer {api_token}"}).json()
# Process the response to extract branch information
return db_repo_data
```
2. If your repository is accessible from the filesystem, you can try:
```python
# This might work in some Databricks configurations
!cat /Workspace/Repos/user@domain/repository/.git/HEAD | sed 's~ref: refs/heads/~~'
```
Note that standard Git Python libraries like `pygit2` or `GitPython` don't work well with Databricks Repos as they're configured differently than standard Git repositories. A community user reported that these packages cannot recognize Databricks Repos properly.
The Databricks UI approach is the most reliable method since it's built into the platform and doesn't require additional code or permissions.

