Analysing branch lifetime in GitLab CI with Python

Introduction

Managing branches efficiently is crucial for a healthy CI/CD workflow. In this post, I’ll show how you can analyze the life of branches in a GitLab repository using Python to fetch data from the GitLab API and Matplotlib to visualize the results. This approach helps teams identify stale branches, understand merge patterns, and optimize their development process.

Fetching Branch Data from GitLab

First, we need to collect branch data from the GitLab API. For this, you’ll need a GitLab personal access token and the requests library.

import os
import requests

GITLAB_TOKEN = os.getenv("GITLAB_TOKEN")
PROJECT_ID = "your_project_id"
GITLAB_URL = f"https://gitlab.com/api/v4/projects/{PROJECT_ID}/repository/branches"

headers = {"PRIVATE-TOKEN": GITLAB_TOKEN}
response = requests.get(GITLAB_URL, headers=headers)
branches = response.json()

# Example: Collect branch names and last commit dates
branch_data = [
    {"name": b["name"], "last_commit": b["commit"]["committed_date"]}
    for b in branches
]

Processing the Data

Let’s convert the data into a pandas DataFrame for easier manipulation.

import pandas as pd

df = pd.DataFrame(branch_data)
df["last_commit"] = pd.to_datetime(df["last_commit"])
df = df.sort_values("last_commit")

Visualizing Branch Activity with Matplotlib

Now, let’s plot the branch activity to see which branches are active and which are stale.

import matplotlib.pyplot as plt

plt.figure(figsize=(10, 6))
plt.barh(df["name"], df["last_commit"].map(lambda d: d.timestamp()))
plt.xlabel("Last Commit Timestamp")
plt.ylabel("Branch Name")
plt.title("GitLab Branch Activity")
plt.tight_layout()
plt.show()

This bar chart gives a quick overview of branch activity. You can easily spot branches that haven’t seen recent commits and may need attention.

Insights and Next Steps

  • Identify Stale Branches: Branches with old last commit dates may be candidates for cleanup.
  • Merge Patterns: By analyzing commit dates, you can infer merge frequency and team activity.
  • Automate Reports: Schedule this script to run regularly and notify your team about stale branches.

Conclusion

By combining Python, the GitLab API, and Matplotlib, you can gain valuable insights into your repository’s branch lifecycle. This helps maintain a clean, efficient CI/CD pipeline and fosters better collaboration within your team.


Happy coding and branch managing!

You also might like

About this post

This post was written by a human with AI assistance, which was used for research, outlining, editing and code suggestions. Claims, code samples and references were reviewed before publication, and the sources are cited so you can judge them yourself.