Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

クイックスタート

This page shows the least code needed to compute metrics for one source file: install the package, call analyze, read a value. It assumes Python 3.12 or newer and pip.

1. パッケージをインストールする

pip install big-code-analysis

wheel マトリクスとソースからのビルド手順についてはインストールを参照してください。

2. ファイルを分析する

bca.analyze(path) returns a dict matching the JSON bca metrics --format json emits for the same file: same field order, same numeric formatting, same shape.

"""Quick-start: analyse one file and print the headline cyclomatic count.

Mirrors the worked example shown on the book's
``python/quick-start.md`` page. The book embeds this file verbatim,
so the snippet is the test fixture — if the API drifts, the
``test_book_examples.py`` test fails and the docs are forced back
into sync.
"""

from __future__ import annotations

from pathlib import Path

import big_code_analysis as bca
from big_code_analysis import FuncSpaceDict


def run(path: Path) -> FuncSpaceDict:
    """Analyse ``path`` and return its metric dict."""
    result = bca.analyze(path)
    if result is None:
        msg = f"{path} was skipped (empty, binary, or generated)"
        raise SystemExit(msg)

    cyclomatic = result["metrics"]["cyclomatic"]
    print(f"{result['name']}: cyclomatic sum = {cyclomatic['sum']:.0f}")
    return result


if __name__ == "__main__":
    import sys

    if len(sys.argv) != 2:
        sys.exit("usage: python quick_start.py <path>")
    run(Path(sys.argv[1]))

Three details matter here:

  • analyze returns None for any file the CLI walker would skip: one that is three bytes or fewer (treated as empty), one whose leading window is not valid UTF-8 (treated as binary), or, with the default skip_generated=True, one matching the walker’s is_generated predicate (a leading @generated, DO NOT EDIT, or GENERATED CODE marker). Handle the None before reaching into result["metrics"].
  • The returned object is a plain dict at runtime, so you can serialise it with json.dumps, ship it to a downstream service, or feed it to flatten_spaces for tabular consumers. Type checkers see it as the FuncSpaceDict TypedDict (generated from the Rust wire shapes), so nested metric access checks statically under mypy and pyright without casts.
  • Language detection mirrors the CLI: path extension first, then an Emacs or Vim mode line, then the shebang. Pass bca.analyze_source(code, language) when the source is already in memory.

3. メモリ上のスニペットを分析する

import big_code_analysis as bca

metrics = bca.analyze_source("fn main() {}\n", "rust")
print(metrics["metrics"]["loc"]["sloc"])

analyze_source は str、bytes、bytearray を受け付けます。返される dict は analyze の出力と同じ構造で、name は None になります(メモリ上のバッファにはパスが関連付けられないためです)。

次のステップ