Alfredo Aguila Alfredo Aguila
Python Git

Automating Changelog Generation with Git and Python

Maintaining a detailed changelog is crucial for any project. It informs users and developers about new features, bug fixes, and other important updates. Manually updating the changelog can be tedious and error-prone. This post outlines how to automate changelog generation from Git commits using Python.

The Need for Automation

Manually creating changelogs is time-consuming. Extracting relevant information from commit messages, formatting it consistently, and ensuring accuracy requires significant effort. An automated script can streamline this process, reducing the risk of errors and freeing up developer time.

Implementing the Changelog Generator

A Python script can leverage Git commands to extract commit messages within a specified range (e.g., between releases). The script can then parse these messages, filter out irrelevant commits (e.g., chore commits), and format the remaining commits into a readable changelog.

Here's a basic example of how such a script might look:

import subprocess

def generate_changelog(from_commit, to_commit):
    command = [
        'git', 'log',
        '--pretty=format:%s',  # Subject of the commit
        f'{from_commit}..{to_commit}'
    ]
    result = subprocess.run(command, capture_output=True, text=True)
    commits = result.stdout.splitlines()
    
    # Filter and format commit messages
    changelog_entries = []
    for commit in commits:
        if not commit.startswith('Chore:'):
            changelog_entries.append(f'- {commit}')
    
    return '\n'.join(changelog_entries)

if __name__ == '__main__':
    previous_tag = 'v1.0.0'
    current_tag = 'v1.1.0'
    changelog = generate_changelog(previous_tag, current_tag)
    print(changelog)

This script uses the git log command to retrieve commit messages between two tags. It then filters out commits starting with 'Chore:' and formats the remaining commits as a list of changelog entries.

Dependencies and Usage

This script requires Python and Git to be installed. It can be integrated into a CI/CD pipeline or run manually to generate the changelog before a release. Further improvements can include:

  • Configurable filtering rules.
  • Support for different output formats (e.g., Markdown, reStructuredText).
  • Integration with issue trackers to automatically link issues to commits.

Conclusion

Automating changelog generation with Python and Git significantly simplifies the release process. By leveraging scripting, developers can save time, reduce errors, and ensure consistent and informative changelogs. Consider implementing a similar solution in your project to streamline your release workflow.

Alfredo Águila Calderón

Alfredo Águila Calderón

Author

Share: