Gersemi

0.27.2 · active · verified Fri Apr 17

Gersemi is a Python-based command-line formatter for CMake code, designed to make your CMakeLists.txt files and `.cmake` modules consistent and readable. It leverages a custom handwritten parser in Rust for robust and efficient formatting. The current version is 0.27.2, with frequent releases addressing bug fixes and introducing new features.

Common errors

Warnings

Install

Quickstart

This quickstart demonstrates how to use `gersemi` to format a CMake file. It creates a temporary `CMakeLists.txt`, formats it using the `gersemi format` command-line tool, and prints the original and formatted content.

import os
import subprocess
import tempfile
from pathlib import Path

# Create a temporary directory and CMake file for demonstration
with tempfile.TemporaryDirectory() as tmpdir_name:
    tmp_path = Path(tmpdir_name)
    cmake_file = tmp_path / "CMakeLists.txt"
    original_content = """
cmake_minimum_required(VERSION 3.8)

project(MyProject CXX)

set(MY_VAR  "Hello"
  CACHE INTERNAL "A variable")

  add_executable(my_app main.cpp
    src/utils.cpp)

macro(MyMacro arg1 arg2)
  message("Args: ${arg1} ${arg2}")
endmacro()

MyMacro(VALUE_ONE VALUE_TWO)

"""
    cmake_file.write_text(original_content.strip())

    print(f"--- Original {cmake_file.name} ---")
    print(cmake_file.read_text())

    # Run gersemi format command
    try:
        # Change current working directory for subprocess to find the file easily
        process = subprocess.run(
            ["gersemi", "format", "CMakeLists.txt"],
            cwd=tmp_path,
            capture_output=True,
            text=True,
            check=True # Raise an exception for non-zero exit codes
        )
        print(f"\n--- gersemi command output ---")
        print(process.stdout)
        if process.stderr:
            print(f"Stderr: {process.stderr}")

        print(f"\n--- Formatted {cmake_file.name} ---")
        print(cmake_file.read_text())

    except FileNotFoundError:
        print("\nERROR: 'gersemi' command not found.")
        print("Please install it: pip install gersemi")
    except subprocess.CalledProcessError as e:
        print(f"\nERROR: gersemi exited with code {e.returncode}")
        print(f"Stdout: {e.stdout}")
        print(f"Stderr: {e.stderr}")

view raw JSON →