# Sloc Cloc and Code (scc)

![SCC illustration](./scc.jpg)

> scc powers [searchcode.com](https://searchcode.com) — structured code intelligence over any repo, built for AI agents.

A tool similar to cloc, sloccount and tokei. For counting the lines of code, blank lines, comment lines, and physical lines of source code in many programming languages.

Goal is to be the fastest code counter possible, but also perform COCOMO calculation like sloccount, LOCOMO estimation for LLM-based development costs, estimate code complexity similar to cyclomatic complexity calculators and produce unique lines of code or DRYness metrics. In short one tool to rule them all.

Also it has a very short name which is easy to type `scc`.

If you don't like sloc cloc and code feel free to use the name `Succinct Code Counter`.

[![Go](https://github.com/boyter/scc/actions/workflows/go.yml/badge.svg)](https://github.com/boyter/scc/actions/workflows/go.yml)
[![Coverage Status](https://coveralls.io/repos/github/boyter/scc/badge.svg?branch=master)](https://coveralls.io/github/boyter/scc?branch=master)
[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/)](https://github.com/boyter/scc/)
![Scc count downloads](https://img.shields.io/github/downloads/boyter/scc/total?label=downloads%20%28GH%29)
[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go)

Licensed under MIT licence.

## Table of Contents

- [Install](#install)
- [Background](#background)
- [Pitch](#pitch)
- [Usage](#usage)
- [Configuration Files](#configuration-files)
- [Complexity Estimates](#complexity-estimates)
- [Unique Lines of Code (ULOC)](#unique-lines-of-code-uloc)
- [COCOMO](#cocomo)
- [LOCOMO](#locomo)
- [Git Insight Reports](#git-insight-reports)
- [HTML Report](#html-report)
- [Output Formats](#output-formats)
- [Performance](#performance)
- [Development](#development)
- [MCP Server Mode](#mcp-server-mode)
- [Adding/Modifying Languages](#addingmodifying-languages)
- [Issues](#issues)
- [Badges](#badges)
- [Language Support](LANGUAGES.md)
- [Citation](#citation)

### scc for Teams & Enterprise

While scc will always be a free and open tool for individual developers, companies and businesses, we are exploring an enhanced version designed for teams and businesses. scc Enterprise will build on the core scc engine to provide historical analysis, team-level dashboards, and policy enforcement to help engineering leaders track code health, manage technical debt, and forecast project costs.

We are currently gathering interest for a private beta. If you want to visualize your codebase's evolution, integrate quality gates into your CI/CD pipeline, and get a big-picture view across all your projects,
sign up for the early access list [here](https://docs.google.com/forms/d/e/1FAIpQLScIBKy3y2m0rKu89L67qwe26Xyn9Scu0gW-HQX9lC0qEAx9nQ/viewform)

### Install

#### Go Install

You can install `scc` by using the standard go toolchain.

To install the latest stable version of scc:

`go install github.com/boyter/scc/v4@latest`

To install a development version:

`go install github.com/boyter/scc/v4@master`

Note that `scc` needs go version >= 1.25.

#### Snap

A [snap install](https://snapcraft.io/scc) exists thanks to [Ricardo](https://feliciano.tech/).

`$ sudo snap install scc`

*NB* Snap installed applications cannot run outside of `/home` <https://askubuntu.com/questions/930437/permission-denied-error-when-running-apps-installed-as-snap-packages-ubuntu-17> so you may encounter issues if you use snap and attempt to run outside this directory.

#### Homebrew

Or if you have [Homebrew](https://brew.sh/) installed

`$ brew install scc`

#### Fedora

Fedora Linux users can use a [COPR repository](https://copr.fedorainfracloud.org/coprs/lihaohong/scc/):

`$ sudo dnf copr enable lihaohong/scc && sudo dnf install scc`

#### MacPorts

On macOS, you can also install via [MacPorts](https://www.macports.org)

`$ sudo port install scc`

#### Scoop

Or if you are using [Scoop](https://scoop.sh/) on Windows

`$ scoop install scc`

#### Chocolatey

Or if you are using [Chocolatey](https://chocolatey.org/) on Windows

`$ choco install scc`

#### WinGet

Or if you are using [WinGet](https://github.com/microsoft/winget-cli) on Windows

`winget install --id benboyter.scc --source winget`

#### FreeBSD

On FreeBSD, scc is available as a package

`$ pkg install scc`

Or, if you prefer to build from source, you can use the ports tree

`$ cd /usr/ports/devel/scc && make install clean`

### Run in Docker

Go to the directory you want to run scc from.

Run the command below to run the latest release of scc on your current working directory:

```bash
docker run --rm -it -v "$PWD:/pwd:ro" --network none ghcr.io/boyter/scc:master scc /pwd
```

#### Manual

Binaries for Windows, GNU/Linux and macOS for both i386 and x86_64 machines are available from the [releases](https://github.com/boyter/scc/releases) page.

#### GitLab

<https://about.gitlab.com/blog/2023/02/15/code-counting-in-gitlab/>

#### Other

If you would like to assist with getting `scc` added into apt/chocolatey/etc... please submit a PR or at least raise an issue with instructions.

### Background

Read all about how it came to be along with performance benchmarks,

- <https://boyter.org/posts/sloc-cloc-code/>
- <https://boyter.org/posts/why-count-lines-of-code/>
- <https://boyter.org/posts/sloc-cloc-code-revisited/>
- <https://boyter.org/posts/sloc-cloc-code-performance/>
- <https://boyter.org/posts/sloc-cloc-code-performance-update/>

Some reviews of `scc`

- <https://nickmchardy.com/2018/10/counting-lines-of-code-in-koi-cms.html>
- <https://www.feliciano.tech/blog/determine-source-code-size-and-complexity-with-scc/>
- <https://metaredux.com/posts/2019/12/13/counting-lines.html>

Setting up `scc` in GitLab

- <https://about.gitlab.com/blog/2023/02/15/code-counting-in-gitlab/>

A talk given at the first GopherCon AU about `scc` (press S to see speaker notes)

- <https://boyter.org/static/gophercon-syd-presentation/>
- <https://www.youtube.com/watch?v=jd-sjoy3GZo>

For performance see the [Performance](https://github.com/boyter/scc#performance) section

Other similar projects,

- [SLOCCount](https://www.dwheeler.com/sloccount/) the original sloc counter
- [cloc](https://github.com/AlDanial/cloc), inspired by SLOCCount; implemented in Perl for portability
- [gocloc](https://github.com/hhatto/gocloc) a sloc counter in Go inspired by tokei
- [loc](https://github.com/cgag/loc) rust implementation similar to tokei but often faster
- [loccount](https://gitlab.com/esr/loccount) Go implementation written and maintained by ESR
- [polyglot](https://github.com/vmchale/polyglot) ATS sloc counter
- [tokei](https://github.com/XAMPPRocky/tokei) fast, accurate and written in rust
- [sloc](https://github.com/flosse/sloc) coffeescript code counter
- [stto](https://github.com/mainak55512/stto) new Go code counter with a focus on performance

Interesting reading about other code counting projects tokei, loc, polyglot and loccount

- <https://www.reddit.com/r/rust/comments/59bm3t/a_fast_cloc_replacement_in_rust/>
- <https://www.reddit.com/r/rust/comments/82k9iy/loc_count_lines_of_code_quickly/>
- <http://blog.vmchale.com/article/polyglot-comparisons>
- <http://esr.ibiblio.org/?p=8270>

Further reading about processing files on the disk performance

- <https://blog.burntsushi.net/ripgrep/>

Using `scc` to process 40 TB of files from GitHub/Bitbucket/GitLab

- <https://boyter.org/posts/an-informal-survey-of-10-million-github-bitbucket-gitlab-projects/>

### Pitch

Why use `scc`?

- It is very fast and gets faster the more CPU you throw at it
- Accurate
- Works very well across multiple platforms without slowdown (Windows, Linux, macOS)
- Large language support
- Can ignore duplicate files
- Has complexity estimations
- You need to tell the difference between Coq and Verilog in the same directory
- cloc yaml output support so potentially a drop in replacement for some users
- Can identify or ignore minified files
- Able to identify many #! files ADVANCED! <https://github.com/boyter/scc/issues/115>
- Can ignore large files by lines or bytes
- Can calculate the ULOC or unique lines of code by file, language or project
- Supports multiple output formats for integration, CSV, SQL, JSON, HTML and more

Why not use `scc`?

- You don't like Go for some reason
- It cannot count D source with different nested multi-line comments correctly <https://github.com/boyter/scc/issues/27>

### Differences

There are some important differences between `scc` and other tools that are out there. Here are a few important ones for you to consider.

Blank lines inside comments are counted as comments. While the line is technically blank the decision was made that once in a comment everything there should be considered a comment until that comment is ended. As such the following,

```c
/* blank lines follow


*/
```

Would be counted as 4 lines of comments. This is noticeable when comparing scc's output to other tools on large
repositories.

`scc` is able to count verbatim strings correctly. For example in C# the following,

```C#
private const string BasePath = @"a:\";
// The below is returned to the user as a version
private const string Version = "1.0.0";
```

Because of the prefixed @ this string ends at the trailing " by ignoring the escape character \ and as such should be
counted as 2 code lines and 1 comment. Some tools are unable to
deal with this and instead count up to the "1.0.0" as a string which can cause the middle comment to be counted as
code rather than a comment.

`scc` will also tell you the number of bytes it has processed (for most output formats) allowing you to estimate the
cost of running some static analysis tools.

### Usage

Command line usage of `scc` is designed to be as simple as possible.
Full details can be found in `scc --help` or `scc -h`. Note that the below reflects the state of master not a release, as such
features listed below may be missing from your installation.

```text
$ scc -h
Sloc, Cloc and Code. Count lines of code in a directory with complexity estimation.
Version 4.0.0
Ben Boyter <ben@boyter.org> + Contributors
https://github.com/boyter/scc

Usage:
  scc [flags] [files or directories]

Examples:
  Count the current directory:
    scc

  Count a specific folder or file:
    scc myproject/
    scc main.go

  Count several paths at once:
    scc src/ docs/ README.md

  Show a per-file breakdown instead of the per-language summary:
    scc --by-file

  Output as CSV or JSON (e.g. for further processing):
    scc --format csv
    scc --format json -o counts.json

  Count an unrecognised extension as a known language:
    scc --count-as jsp:html

  Count files matching a path pattern as a new category (glob by default):
    scc --count-as-pattern '*_spec.rb:Ruby Spec:Ruby'

  Generate a self-contained HTML infographic report:
    scc --report
    scc --report=out.html --report-title "myrepo" --report-skip cocomo

  Use a project config file (./.sccconfig) or a global one (precedence: global < project < CLI):
    export SCC_CONFIG_PATH=~/.sccconfig
    scc --config team.sccconfig

  Tune the COCOMO cost estimate, or turn it off (see https://en.wikipedia.org/wiki/COCOMO):
    scc --avg-wage 75000 --cocomo-project-type semi-detached
    scc --no-cocomo

Flags:
      --avg-wage int                        average wage value used for basic COCOMO calculation (default 56286)
      --binary                              disable binary file detection
      --buckets int                         time-bucket resolution for the git timeline reports (default 60)
      --by-author                           render the author rollup report (bus factor and last-toucher attribution over recent git history)
      --by-file                             display output for every file
  -m, --character                           calculate max and mean characters per line
      --ci                                  enable CI output settings where stdout is ASCII
      --cocomo-project-type string          change COCOMO model type [organic, semi-detached, embedded, "custom,1,1,1,1"] (default "organic")
      --cognitive                           calculate cognitive (nesting-weighted) complexity
      --config string                       load this file as the global config source; overrides SCC_CONFIG_PATH, honored even with --no-config
      --cost-comparison                     show both COCOMO and LOCOMO estimates side by side
      --count-as string                     count extension as language [e.g. jsp:htm,chead:"C Header" maps extension jsp to html and chead to C Header]
      --count-as-pattern stringArray        count files matching a path pattern as a new named category backed by a base language [repeatable; pattern is glob by default, prefix with re: for regex; e.g. *_spec.rb:"Ruby Spec":Ruby or re:\.test\.js$:"JavaScript Tests":JavaScript]
      --count-ignore                        set to allow .gitignore and .ignore files to be counted
      --count-unsupported                   count files with an unrecognised language under an "Unknown" category as plain text
      --coupling                            render the change-coupling report (file pairs that change together over recent git history)
      --coupling-for string                 blast-radius view: given a file path, show what tends to change with it over recent git history
      --coupling-weighted                   weight coupling by file complexity so pairs of complex files rank above generated/data-file churn (implies --coupling)
      --currency-symbol string              set currency symbol (default "$")
      --debug                               enable debug output
      --depth int                           commit window size for git history reports; 0 means entire history (large repos may be slow) (default 1000)
      --directory-walker-job-workers int    controls the maximum number of workers which will walk the directory tree (default 8)
  -a, --dryness                             calculate the DRYness of the project (implies --uloc)
      --eaf float                           the effort adjustment factor derived from the cost drivers (1.0 if rated nominal) (default 1)
      --exclude-dir strings                 directories to exclude (default [.git,.hg,.svn])
  -x, --exclude-ext strings                 ignore file extensions (overrides include-ext) [comma separated list: e.g. go,java,js]
  -n, --exclude-file strings                ignore files with matching names (default [package-lock.json,Cargo.lock,yarn.lock,pubspec.lock,Podfile.lock,pnpm-lock.yaml])
      --file-gc-count int                   number of files to parse before turning the GC on (default 10000)
      --file-list-queue-size int            the size of the queue of files found and ready to be read into memory (default 8)
      --file-process-job-workers int        number of goroutine workers that process files collecting stats (default 8)
      --file-summary-job-queue-size int     the size of the queue used to hold processed file statistics before formatting (default 8)
      --find-root-config                    discover the project .sccconfig by walking up to the repository root instead of using ./.sccconfig
  -f, --format string                       set output format [tabular, wide, json, json2, csv, csv-stream, cloc-yaml, html, html-table, sql, sql-insert, openmetrics] (default "tabular")
      --format-multi string                 have multiple format output overriding --format [e.g. tabular:stdout,csv:file.csv,json:file.json]
      --gen                                 identify generated files
      --generated-markers strings           string markers in head of generated files (default [do not edit,<auto-generated />])
  -h, --help                                help for scc
      --hotspots                            render the hotspots report (files ranked by complexity × change frequency over recent git history)
      --ignore-file stringArray             path to an additional gitignore-format ignore file, applied from the scan root; repeat to add more, later files and any in-tree ignore files take precedence
  -i, --include-ext strings                 limit to file extensions [comma separated list: e.g. go,java,js]
      --include-symlinks                    if set will count symlink files
  -l, --languages                           print supported languages and extensions
      --large-byte-count int                number of bytes a file can contain before being removed from output (default 1000000)
      --large-line-count int                number of lines a file can contain before being removed from output (default 40000)
      --locomo                              enable LOCOMO (LLM Output COst MOdel) cost estimation
      --locomo-config string                LOCOMO power-user config "tokensPerLine,inputPerLine,complexityWeight,iterations,iterationWeight"
      --locomo-cycles float                 override estimated LLM iteration cycles (default: calculated from complexity)
      --locomo-input-price float            LOCOMO cost per 1M input tokens in dollars (overrides preset)
      --locomo-output-price float           LOCOMO cost per 1M output tokens in dollars (overrides preset)
      --locomo-preset string                LOCOMO model preset [large, medium, small, local] (default "medium")
      --locomo-review float                 human review minutes per line of code for LOCOMO estimate (default 0.01)
      --locomo-tps float                    LOCOMO output tokens per second (overrides preset)
      --mcp                                 start as an MCP (Model Context Protocol) server over stdio
      --min                                 identify minified files
  -z, --min-gen                             identify minified or generated files
      --min-gen-line-length int             number of bytes per average line for file to be considered minified or generated (default 255)
      --no-cocomo                           remove COCOMO calculation output
  -c, --no-complexity                       skip calculation of code complexity
      --no-config                           disable auto-discovery of the SCC_CONFIG_PATH global and the project ./.sccconfig config
  -d, --no-duplicates                       remove duplicate files from stats and output
      --no-fold-authors                     disable the name+email-domain identity folding fallback for git author reports (mailmap still applied)
      --no-gen                              ignore generated files in output (implies --gen)
      --no-gitignore                        disables .gitignore file logic
      --no-gitmodule                        disables .gitmodules file logic
      --no-hborder                          remove horizontal borders between sections
      --no-ignore                           disables .ignore file logic
      --no-large                            ignore files over certain byte and line size set by large-line-count and large-byte-count
      --no-min                              ignore minified files in output (implies --min)
      --no-min-gen                          ignore minified or generated files in output (implies --min-gen)
      --no-scc-ignore                       disables .sccignore file logic
      --no-size                             remove size calculation output
  -M, --not-match stringArray               ignore files and directories matching regular expression
  -o, --output string                       output filename (default stdout)
      --overhead float                      set the overhead multiplier for corporate overhead (facilities, equipment, accounting, etc.) (default 2.4)
  -p, --percent                             include percentage values in output
      --remap-all string                    inspect every file and remap by checking for a string and remapping the language [e.g. "-*- C++ -*-":"C Header"]
      --remap-unknown string                inspect files of unknown type and remap by checking for a string and remapping the language [e.g. "-*- C++ -*-":"C Header"]
      --report string[="scc-report.html"]   write a self-contained HTML report; bare flag writes scc-report.html and prompts before overwriting, --report=path/out.html overwrites silently
      --report-skip string                  comma-separated sections to omit (cocomo,locomo,hotspots,coupling,authors,timeline,files,uloc,linelength,card)
      --report-title string                 override the repo name shown in the report banner
      --size-unit string                    set size unit [si, binary, mixed, xkcd-kb, xkcd-kelly, xkcd-imaginary, xkcd-intel, xkcd-drive, xkcd-bakers] (default "si")
      --sloccount-format                    print a more SLOCCount like COCOMO calculation
  -s, --sort string                         column to sort by [files, name, lines, blanks, code, comments, complexity] (default "files")
      --sql-project string                  use supplied name as the project identifier for the current run. Only valid with the --format sql or sql-insert option
      --timeline                            render an over-time view of recent git history; with --by-author runs the author timeline, alone runs the languages timeline
  -t, --trace                               enable trace output (not recommended when processing multiple files)
  -u, --uloc                                calculate the number of unique lines of code (ULOC) for the project
  -v, --verbose                             verbose output
      --version                             version for scc
  -w, --wide                                wider output with additional statistics (implies --complexity)
```

Output should look something like the below for the redis project

```text
$ scc redis 
───────────────────────────────────────────────────────────────────────────────
Language                 Files     Lines   Blanks  Comments     Code Complexity
───────────────────────────────────────────────────────────────────────────────
C                          437   267,353   31,103    45,998  190,252     48,269
JSON                       406    25,392        4         0   25,388          0
C Header                   288    48,831    5,648    11,302   31,881      3,097
TCL                        215    66,943    7,330     4,651   54,962      3,816
Shell                       75     1,626      239       343    1,044        185
Python                      34     4,802      694       498    3,610        621
Markdown                    26     4,647    1,226         0    3,421          0
Autoconf                    22    11,732    1,124     1,420    9,188      1,016
Lua                         20       525       69        71      385         89
Makefile                    20     1,956      368       170    1,418         85
YAML                        20     2,696      147        53    2,496          0
MSBuild                     11     1,995        2         0    1,993        160
Plain Text                  10     1,773      313         0    1,460          0
Ruby                         9       817       73       105      639        123
C++                          8       546       85        43      418         43
HTML                         5     9,658    2,928        12    6,718          0
License                      3        90       17         0       73          0
CMake                        2       298       49         5      244         12
CSS                          2       107       16         0       91          0
Systemd                      2        80        6         0       74          0
BASH                         1       143       16         5      122         38
Batch                        1        28        2         0       26          3
C++ Header                   1         9        1         3        5          0
Extensible Styleshe…         1        10        0         0       10          0
JavaScript                   1        31        1         0       30          5
Module-Definition            1    11,375    2,116         0    9,259        167
SVG                          1         1        0         0        1          0
Smarty Template              1        44        1         0       43          5
m4                           1       951      218        64      669          0
───────────────────────────────────────────────────────────────────────────────
Total                    1,624   464,459   53,796    64,743  345,920     57,734
───────────────────────────────────────────────────────────────────────────────
Estimated Cost to Develop (organic) $12,517,562
Estimated Schedule Effort (organic) 35.93 months
Estimated People Required (organic) 30.95
───────────────────────────────────────────────────────────────────────────────
Processed 16601962 bytes, 16.602 megabytes (SI)
───────────────────────────────────────────────────────────────────────────────
```

Note that you don't have to specify the directory you want to run against. Running `scc` will assume you want to run against the current directory.

You can also run against multiple files or directories `scc directory1 directory2 file1 file2` with the results aggregated in the output.

Since `scc` writes to standard output, there are many ways to easily share the results. For example, using [netcat](https://manpages.org/nc)
and [one of many pastebins](https://paste.c-net.org/) gives a public URL:

```bash
$ scc | nc paste.c-net.org 9999
https://paste.c-net.org/Example
```

### Ignore Files

`scc` supports .ignore files inside directories that it scans. This is similar to how ripgrep, ag and tokei work. 
.ignore files are 100% the same as .gitignore files with the same syntax, and as such `scc` will ignore files and 
directories listed in them. You can add .ignore files to ignore things like vendored dependency checked in files and 
such. The idea is allowing you to add a file or folder to git and have ignored in the count.

It also supports its own ignore file `.sccignore` if you want `scc` to ignore things while having ripgrep, ag, tokei 
and others support them.

You can also supply additional ignore files from outside the scanned tree with `--ignore-file`. The file uses the 
same gitignore syntax and its patterns are anchored at the scan root (so `/build` matches only the top-level `build`). 
This is handy for applying a shared ruleset such as a `.dockerignore` or a personal global ignore:

```
scc --ignore-file ~/.gitignore --ignore-file ./.dockerignore
```

The flag can be repeated and order matters: a later file can re-include something an earlier one ignored (via a `!` 
negation), and any `.gitignore`, `.ignore` or `.sccignore` discovered inside the scanned tree takes precedence over 
everything supplied with `--ignore-file`.

If you want to apply your global git excludes file, point `--ignore-file` at it directly (for example 
`--ignore-file ~/.config/git/ignore`). `scc` deliberately does not shell out to `git` to discover it for you, but you 
can make it automatic by putting the flag in a `.sccconfig` configuration file and pointing the `SCC_CONFIG_PATH` environment 
variable at it, so every run picks it up without typing:

```
# ~/.config/scc/global.sccconfig
--ignore-file /home/me/.config/git/ignore
```

```
export SCC_CONFIG_PATH=~/.config/scc/global.sccconfig
scc   # now applies your global ignore on every run
```

### Configuration Files

`scc` can read default flags from a configuration file to avoid creating shell aliases. 
The format is an *opts-list* in the style of ripgrep and bat: the file is simply a list of the same command-line flags 
you would otherwise type, and anything valid on the command line is valid in the file, with the exception
of output flags.

Format rules:

- One flag per line is the recommended style, but multiple whitespace-separated tokens per line are allowed (`--exclude-dir vendor`).
- Lines use the normal `--` prefix, e.g. `--no-cocomo`.
- `#` begins a comment. Whole-line and inline trailing comments are stripped.
- Blank lines are ignored.
- Tokenization is quote-aware, so both `--exclude-dir vendor` and `--count-as 'jsp:html'` work. Quotes (single or double) are the only grouping mechanism; to include a literal quote, switch quote style (`--count-as "a'b"`).
- Backslash is an ordinary literal, not an escape character, so a Windows path such as `--exclude-dir C:\build\out` survives verbatim.
- A line whose first token does not start with `-` (a bare positional such as `src/`) is skipped with a warning, so a config file cannot inject extra count targets.

Example `.sccconfig`:

```
# count the way I like it
--no-cocomo
--exclude-dir vendor,node_modules
--format wide          # default to the wider table
```

#### Sources and discovery

There are two configuration tiers:

- **Global** — there is no fixed default location and no per-run home-directory stat. The global source is consulted only when set explicitly via the `SCC_CONFIG_PATH` environment variable or the `--config <path>` flag. `--config` which overrides `SCC_CONFIG_PATH`.
- **Project** — a file named `.sccconfig` in the current working directory (`./.sccconfig`), found with a single stat and **no walk-up**. `cd project && scc` picks up `project/.sccconfig`; running `scc` from a subdirectory does **not** pick up an ancestor's `.sccconfig`. Path arguments do not move the anchor — `scc ./project` still reads `./.sccconfig`, not `./project/.sccconfig`.

To read the repository root's `.sccconfig` from a subdirectory, pass `--find-root-config`, which walks back from the current directory to the git/hg root. It is off by default and affects config discovery only - it changes which `.sccconfig` is read, not which directory is counted. Outside a repository it degrades to `./.sccconfig`.

#### Precedence

Lowest to highest, later wins: **global config < project config < command line**. Scalar and boolean flags follow last-wins, so the command line always overrides config.

Slice flags (`--exclude-dir`, `--exclude-file`, `--exclude-ext`, `--include-ext`, `--not-match`) **union** instead of overriding:

```
config: --exclude-dir vendor
CLI:    --exclude-dir dist
result: vendor, dist
```

The three slice flags that ship with built-in defaults — `--exclude-dir` (`.git`, `.hg`, `.svn`), `--exclude-file` (the lockfile set) and `--generated-markers` — keep those defaults as a non-removable safety net: a config or CLI value is *added* to the defaults rather than replacing them, so putting `vendor` in `.sccconfig` never stops `scc` skipping `.git`.

#### Config can never write a file

A configuration file can change how `scc` counts and formats, including selecting a stdout format such as `--format json`, but it can **never** cause `scc` to write a file. The file-output flags — `--output` / `-o`, `--report` and `--format-multi` — are honoured only from the command line; the same flags supplied by config are ignored (output goes to stdout, the default). This is because a project `.sccconfig` is auto-discovered, so a cloned repository could otherwise silently overwrite one of your files. Only the command line can make `scc` write to disk.

#### Control flags

| Flag | Effect |
|------|--------|
| `--no-config` | Disable auto-discovery: skip the `SCC_CONFIG_PATH` global and the project `.sccconfig`. |
| `--config <path>` | Load this file as the global source. Always honoured, even with `--no-config`; overrides `SCC_CONFIG_PATH`. |
| `--find-root-config` | Discover the project `.sccconfig` by walking up to the repository root instead of using `./.sccconfig`. No-op under `--no-config`. |

`--config test.sccconfig --no-config` loads exactly `test.sccconfig` and nothing else — a clean isolated-config mode. A `--config` or `--no-config` written *inside* a config file is inert (a config file cannot chain-load another config file).

#### The `@file` argument bundle

`scc @flags.txt` expands the contents of `flags.txt` as if its lines had been typed on the command line. It uses the same opts-list tokenizer as config files (comments, quotes, backslash-literal), but unlike config files it **keeps positional paths** and **may write files** — an `@file` is an explicit, user-supplied argument bundle equivalent to typing the flags, so it is trusted like the command line (including a `--config` inside it being honoured). `@file` expansion fires only when `@file` is the sole argument.

Note that because config discovery now runs on the post-`@file` arguments, `scc @flags.txt` in a directory containing `./.sccconfig` loads **both** — the `@file` tokens sit above the config in precedence. To get the old "exactly these args, nothing else" behaviour, add `--no-config`.

### Interesting Use Cases

Used inside Intel Nemu Hypervisor to track code changes between revisions <https://github.com/intel/nemu/blob/topic/virt-x86/tools/cloc-change.sh#L9>
Appears to also be used inside both <http://codescoop.com/> <https://pinpoint.com/> <https://github.com/chaoss/grimoirelab-graal>

It also is used to count code and guess language types in <https://searchcode.com/> which makes it one of the most frequently run code counters in the world.

You can also hook scc into your gitlab pipeline <https://gitlab.com/guided-explorations/ci-cd-plugin-extensions/ci-cd-plugin-extension-scc>

Used by the following products and services,

- [GitHub CodeQL](https://github.com/boyter/scc/pull/317) - The CodeQL engine uses `scc` for line counting
- [JetBrains Qodana](https://github.com/JetBrains/qodana-cli) - The Qodana CLI leverages `scc` as a command-line helper for code analysis
- [Scaleway](https://twitter.com/Scaleway/status/1488087029476995074?s=20&t=N2-z6O-ISDdDzULg4o4uVQ) - Cloud provider using `scc`
- [Linux Foundation LFX Insights](https://docs.linuxfoundation.org/lfx/insights/v3-beta-version-current/getting-started/landing-page/cocomo-cost-estimation-simplified) - COCOMO cost estimation
- [OpenEMS](https://openems.io/)

### Features

`scc` uses a small state machine in order to determine what state the code is when it reaches a newline `\n`. As such it is aware of and able to count

- Single Line Comments
- Multi Line Comments
- Strings
- Multi Line Strings
- Blank lines

Because of this it is able to accurately determine if a comment is in a string or is actually a comment.

It also attempts to count the complexity of code. This is done by checking for branching operations in the code. For example, each of the following `for if switch while else || && != ==` if encountered in Java would increment that files complexity by one.

### Complexity Estimates

Let's take a minute to discuss the complexity estimate itself.

The complexity estimate is really just a number that is only comparable to files in the same language. It should not be used to compare languages directly without weighting them. The reason for this is that its calculated by looking for branch and loop statements in the code and incrementing a counter for that file.

Because some languages don't have loops and instead use recursion they can have a lower complexity count. Does this mean they are less complex? Probably not, but the tool cannot see this because it does not build an AST of the code as it only scans through it.

Generally though the complexity there is to help estimate between projects written in the same language, or for finding the most complex file in a project `scc --by-file -s complexity` which can be useful when you are estimating on how hard something is to maintain, or when looking for those files that should probably be refactored.

As for how it works.

It's my own definition, but tries to be an approximation of cyclomatic complexity <https://en.wikipedia.org/wiki/Cyclomatic_complexity> although done only on a file level.

The reason it's an approximation is that it's calculated almost for free from a CPU point of view (since its a cheap lookup when counting), whereas a real cyclomatic complexity count would need to parse the code. It gives a reasonable guess in practice though even if it fails to identify recursive methods. The goal was never for it to be exact.

In short when scc is looking through what it has identified as code if it notices what are usually branch conditions it will increment a counter.

The conditions it looks for are compiled into the code and you can get an idea for them by looking at the JSON inside the repository. See <https://github.com/boyter/scc/blob/master/languages.json#L3869> for an example of what it's looking at for a file that's Java.

The increment happens for each of the matching conditions and produces the number you see.

### Unique Lines of Code (ULOC)

ULOC stands for Unique Lines of Code and represents the unique lines across languages, files and the project itself. This idea was taken from
<https://cmcenroe.me/2018/12/14/uloc.html> where the calculation is presented using standard Unix tools `sort -u *.h *.c | wc -l`. This metric is
there to assist with the estimation of complexity within the project. Quoting the source

> In my opinion, the number this produces should be a better estimate of the complexity of a project. Compared to SLOC, not only are blank lines discounted, but so are close-brace lines and other repetitive code such as common includes. On the other hand, ULOC counts comments, which require just as much maintenance as the code around them does, while avoiding inflating the result with license headers which appear in every file, for example.

You can obtain the ULOC by supplying the `-u` or `--uloc` argument to `scc`.

It has a corresponding metric `DRYness %` which is the percentage of ULOC to CLOC or `DRYness = ULOC / SLOC`. The
higher the number the more DRY (don't repeat yourself) the project can be considered. In general a higher value
here is a better as it indicates less duplicated code. The DRYness metric was taken from a comment by minimax <https://lobste.rs/s/has9r7/uloc_unique_lines_code>

To obtain the DRYness metric you can use the `-a` or `--dryness` argument to `scc`, which will implicitly set `--uloc`.

Note that there is a performance penalty when calculating the ULOC metrics which can double the runtime.

Running the uloc and DRYness calculations against C code a clone of redis produces an output as follows.

```bash
$ scc -a -i c redis 
───────────────────────────────────────────────────────────────────────────────
Language                 Files     Lines   Blanks  Comments     Code Complexity
───────────────────────────────────────────────────────────────────────────────
C                          437   267,353   31,103    45,998  190,252     48,269
(ULOC)                            149892
───────────────────────────────────────────────────────────────────────────────
Total                      437   267,353   31,103    45,998  190,252     48,269
───────────────────────────────────────────────────────────────────────────────
Unique Lines of Code (ULOC)       149892
DRYness %                           0.56
───────────────────────────────────────────────────────────────────────────────
Estimated Cost to Develop (organic) $6,681,762
Estimated Schedule Effort (organic) 28.31 months
Estimated People Required (organic) 20.97
───────────────────────────────────────────────────────────────────────────────
Processed 9390815 bytes, 9.391 megabytes (SI)
───────────────────────────────────────────────────────────────────────────────
```

Further reading about the ULOC calculation can be found at <https://boyter.org/posts/sloc-cloc-code-new-metic-uloc/>

Interpreting Dryness,

- 75% (High Density): Very terse, expressive code. Every line counts. (Example: Clojure, Haskell)
- 60% - 70% (Standard): A healthy balance of logic and structural ceremony. (Example: Java, Python)
- < 55% (High Boilerplate): High repetition. Likely due to mandatory error handling, auto-generated code, or verbose configuration. (Example: C#, CSS)

See <https://boyter.org/posts/boilerplate-tax-ranking-popular-languages-by-density/> for more details.

### COCOMO

The COCOMO statistics displayed at the bottom of any command line run can be configured as needed.

```text
Estimated Cost to Develop (organic) $664,081
Estimated Schedule Effort (organic) 11.772217 months
Estimated People Required (organic) 5.011633
```

To change the COCOMO parameters, you can either use one of the default COCOMO models.

```text
scc --cocomo-project-type organic
scc --cocomo-project-type semi-detached
scc --cocomo-project-type embedded
```

You can also supply your own parameters if you are familiar with COCOMO as follows,

```text
scc --cocomo-project-type "custom,1,1,1,1"
```

See below for details about how the model choices, and the parameters they use.

Organic – A software project is said to be an organic type if the team size required is adequately small, the
problem is well understood and has been solved in the past and also the team members have a nominal experience
regarding the problem.

`scc --cocomo-project-type "organic,2.4,1.05,2.5,0.38"`

Semi-detached – A software project is said to be a Semi-detached type if the vital characteristics such as team-size,
experience, knowledge of the various programming environment lie in between that of organic and Embedded.
The projects classified as Semi-Detached are comparatively less familiar and difficult to develop compared to
the organic ones and require more experience and better guidance and creativity. Eg: Compilers or
different Embedded Systems can be considered of Semi-Detached type.

`scc --cocomo-project-type "semi-detached,3.0,1.12,2.5,0.35"`

Embedded – A software project with requiring the highest level of complexity, creativity, and experience
requirement fall under this category. Such software requires a larger team size than the other two models
and also the developers need to be sufficiently experienced and creative to develop such complex models.

`scc --cocomo-project-type "embedded,3.6,1.20,2.5,0.32"`

### LOCOMO

LOCOMO (LLM Output COst MOdel) estimates the cost to regenerate a codebase using a large language model. It is the LLM-era counterpart to COCOMO - a rough ballpark estimator, not a project planning tool.

Note: LOCOMO was developed as part of `scc` and is not an industry-standard model. Unlike COCOMO, which is based on decades of empirical research by Barry Boehm, LOCOMO is an experimental heuristic designed to give a useful order-of-magnitude estimate for LLM-assisted development costs. Treat its output as a conversation starter, not a definitive answer.

**Important distinction:** LOCOMO estimates the cost to **regenerate** known code - essentially "given this exact codebase, how much would it cost to have an LLM produce it?" This is fundamentally different from the cost to **create** something from scratch, which involves exploration, architectural decisions, dead ends, debugging, and iteration that can cost orders of magnitude more. COCOMO estimates the human *creation* cost; LOCOMO estimates the LLM *regeneration* cost. They answer different questions.

LOCOMO is opt-in. Enable it with `--locomo` or use `--cost-comparison` to display both COCOMO and LOCOMO side by side.

```
$ scc --locomo .
...
LOCOMO LLM Cost Estimate (medium)
  Tokens Required (in/out) 3.0M / 0.7M
  Cost to Generate $20
  Estimated Cycles 2.1
  Generation Time (serial) 3.9 hours
  Human Review Time 5.9 hours
  Disclaimer: rough ballpark for regenerating code using a LLM.
  Does not account for context reuse, test generation, or heavy debugging.
```

#### How it works

LOCOMO uses SLOC and complexity data that `scc` already computes. The model works per-file and aggregates:

1. **Output tokens** - each line of code maps to ~10 LLM output tokens (configurable).
2. **Input tokens** - estimated prompting cost, scaled by code complexity. More complex code (higher branch density) requires more detailed prompts. Scales to prevent runaway estimates.
3. **Iteration factor** - LLMs rarely produce correct code on the first try. A retry multiplier scales with complexity, also scales.
4. **Dollar cost** - input and output tokens multiplied by per-token pricing.
5. **Generation time** - total serial output tokens divided by tokens-per-second throughput.
6. **Human review time** - estimated per-line overhead for planning, review, testing, and integration.

#### Model presets

Presets are tier-based rather than tied to specific models, so they don't go stale as models are retired or renamed. Use `--locomo-preset` to select a tier:

| Preset | Represents | Input $/1M | Output $/1M | TPS |
|--------|-----------|-----------|-------------|-----|
| `large` | Frontier models (Opus, GPT-5.3, Gemini 3.1 Pro, etc.) | 10.00 | 30.00 | 30 |
| `medium` (default) | Balanced models (Sonnet, Gemini Flash, etc.) | 3.00 | 15.00 | 50 |
| `small` | Fast/cheap models (Haiku, GPT-4o-mini, etc.) | 0.50 | 2.00 | 100 |
| `local` | Self-hosted models (Llama, Mistral, Qwen etc.) | 0.00 | 0.00 | 15 |

For `local`, cost is $0 but generation time is still reported to capture the compute/time investment. Preset pricing reflects approximate tier rates as of early 2026 and can be overridden with explicit flags.

```
scc --locomo --locomo-preset large .
scc --locomo --locomo-preset local .
```

#### Overriding preset values

You can override individual preset values for pricing or throughput:

```
scc --locomo --locomo-input-price 1.0 --locomo-output-price 5.0 .
scc --locomo --locomo-tps 100 .
```

#### Human review time

The `--locomo-review` flag controls estimated human review minutes per line of code (default: 0.01, i.e. 0.6 seconds per line). This is intentionally optimistic and assumes light oversight.

For mission-critical, security-sensitive, or complex algorithmic code you should increase this:

```
scc --locomo --locomo-review 0.05 .
scc --locomo --locomo-review 0.1 .
```

#### Power-user configuration

The five internal model parameters can be overridden with a single comma-separated config string:

```
scc --locomo --locomo-config "tokensPerLine,inputPerLine,complexityWeight,iterations,iterationWeight"
```

The defaults are `"10,20,5,1.5,2"`. Here is what each parameter controls:

| Position | Name | Default | Description |
|----------|------|---------|-------------|
| 1 | tokensPerLine | 10 | Average LLM output tokens per line of code |
| 2 | inputPerLine | 20 | Base LLM input (prompt) tokens per output line |
| 3 | complexityWeight | 5 | How much complexity density scales input tokens: `inputFactor = 1 + sqrt(density) * weight` |
| 4 | iterations | 1.5 | Base iteration/retry cycles before complexity adjustment |
| 5 | iterationWeight | 2 | How much complexity density adds extra cycles: `cycles = iterations + sqrt(density) * weight` |

The iteration factor (cycles) scales both input and output tokens - it represents how many generation attempts the LLM needs. Simple code (~0.05 complexity density) produces ~1.9 cycles; complex code (~0.3 density) produces ~2.6 cycles. Use `--locomo-cycles` to override this with a fixed value.

For example, to model a cheaper/faster LLM that needs fewer tokens but more retries:

```
scc --locomo --locomo-config "8,15,3,2.0,1.5"
```

#### Comparing COCOMO and LOCOMO

Use `--cost-comparison` to show both estimates side by side. This enables COCOMO (if it was disabled) and LOCOMO together:

```
scc --cost-comparison .
```

#### What LOCOMO does not account for

LOCOMO is a rough estimator with known limitations:

- **No context reuse.** Real LLM-assisted development shares context across files. The per-file model overestimates input tokens for large projects with shared patterns.
- **Boilerplate vs algorithmic code.** A 500-line CRUD controller and a 500-line compression algorithm have very different real costs, but the model only differentiates them via complexity density.
- **Code that LLMs can't write well.** Complex concurrency, platform-specific edge cases, and security-critical crypto need human authoring, not just review.
- **No test generation cost.** The model estimates source code generation only, not test suites.
- **Pricing changes.** LLM pricing drops rapidly. Preset defaults will become stale - use explicit price flags for current estimates.

#### All LOCOMO flags

| Flag | Default | Description |
|------|---------|-------------|
| `--locomo` | false | Enable LOCOMO output |
| `--cost-comparison` | false | Show COCOMO + LOCOMO side by side |
| `--locomo-preset` | medium | Model tier preset for pricing and throughput |
| `--locomo-input-price` | (preset) | Override: cost per 1M input tokens ($) |
| `--locomo-output-price` | (preset) | Override: cost per 1M output tokens ($) |
| `--locomo-tps` | (preset) | Override: output tokens per second |
| `--locomo-review` | 0.01 | Human review minutes per line of code |
| `--locomo-cycles` | (calculated) | Override estimated LLM iteration cycles |
| `--locomo-config` | 10,20,5,1.5,2 | Power-user config: tokensPerLine, inputPerLine, complexityWeight, iterations, iterationWeight |

### Git Insight Reports

In addition to counting the working tree, `scc` can run five git-aware reports over recent commit history. Each is selected by a flag and rendered as `tabular` (default), `csv`, or `json` via `--format`. All are derived from one in-process walk of the repository - there is no `exec("git")`, so the `git` binary does not need to be on `PATH`.

> **Note:** these reports are **slower** than a normal `scc` run. They walk the repository history (one diff per commit using pure-Go Myers diff via [go-git](https://github.com/go-git/go-git)) instead of just counting the current working tree. Runtime scales with `--depth` (the commit window size, default `1000`; `0` means entire history). On large repositories with deep history, expect runtimes measured in seconds to minutes rather than the millisecond-scale you get from a plain `scc` run. Use `--depth` to bound the window.

When no report flag is set, `scc` behaves exactly as today, these flags are strictly opt-in.

| Flag | Report | Answers |
|---|---|---|
| `--hotspots` | Hotspots | Which files are defect-prone - high complexity × high churn. |
| `--coupling` / `--coupling-for FILE` | Change coupling | Which files change together - hidden dependencies and blast radius. |
| `--by-author` | Author rollup | Bus factor - who last-touched the surviving code. |
| `--by-author --timeline` | Author timeline | How each author's activity rises and falls over time. |
| `--timeline` | Languages over time | How the language mix shifts - rewrites, migrations. |

Shared flags for these reports:

| Flag | Default | Purpose |
|---|---|---|
| `--depth N` | 1000 | Commit window size (newest N commits). `0` walks the entire history (slow on big repos). Negative values are rejected. |
| `--buckets N` | 60 | Time-bucket resolution for timeline reports. Must be `>= 1` when `--timeline` is set. CSV/JSON always emit full-resolution; tabular sparklines downsample to fit. |
| `-w, --wide` | - | 109-column variant of any report (extra columns where applicable). |
| `--no-fold-authors` | off | Disable the name + email-domain identity folding fallback applied after `.mailmap`. |

Each report is standalone: `--hotspots`, `--coupling` (or `--coupling-for`), and `--by-author` / `--timeline` are mutually exclusive, and combining them is an error. `--coupling-for FILE` implies `--coupling`. With `--by-author` set, `--timeline` switches from the author rollup to the author timeline. Alone, `--timeline` renders the languages timeline.

#### Hotspots - `--hotspots`

Ranks files by defect-proneness: complexity × change frequency over the window. Surfaces *where to review*, not a defect probability.

```text
$ scc --hotspots
───────────────────────────────────────────────────────────────────────────────
Hotspots · last 500 commits · 2024-01-09 → 2026-05-20
───────────────────────────────────────────────────────────────────────────────
File                            Lang   Cmplx  Commits   Lines±  Authrs  Hotspot
───────────────────────────────────────────────────────────────────────────────
processor/workers.go              Go     488       62    7,240       9    100.0
processor/processor.go            Go     402       41    3,910       7     71.4
processor/formatters.go           Go     233       38    2,980       6     51.8
main.go                           Go     180       44    2,510       8     48.2
───────────────────────────────────────────────────────────────────────────────
   complexity × change-frequency, normalised · 20 of 142 files shown
───────────────────────────────────────────────────────────────────────────────
```

Tabular output shows the top files (≈20). `--wide` adds a hotspot bar and an added-lines code-vs-comment split (`+Code%`). `--format csv|json` emits every file with a positive score along with the full per-file detail and window metadata.

#### Change coupling - `--coupling` / `--coupling-for`

Which files tend to change together in the same commit I.E. *temporal* coupling.
Surfaces the "if you edit A you probably need to edit B" relationships. `Shared Commits` is how
many commits touched both files; `Coupling` is the share of commits touching *either* file that
touched *both*, so 100% means they never move apart. Pairs are ranked strongest first,
and only pairs sharing at least 2 commits are reported.

```text
$ scc --coupling
───────────────────────────────────────────────────────────────────────────────
Change Coupling · last 1000 commits · 2019-07-24 → 2026-07-20
───────────────────────────────────────────────────────────────────────────────
File A                      File B                      Shared Commits Coupling
───────────────────────────────────────────────────────────────────────────────
languages.json              processor/constants.go                 196    67.6%
LANGUAGES.md                languages.json                         166    61.3%
LANGUAGES.md                processor/constants.go                 152    58.2%
main.go                     processor/processor.go                  65    33.9%
───────────────────────────────────────────────────────────────────────────────
top 15 of 492 pairs · sharing ≥2 commits
───────────────────────────────────────────────────────────────────────────────
```

`--coupling-for FILE` narrows to a single file's and what history says tends to move with it.

```text
$ scc --coupling-for processor/workers.go
───────────────────────────────────────────────────────────────────────────────
Change Coupling · last 1000 commits · 2019-07-24 → 2026-07-20
───────────────────────────────────────────────────────────────────────────────
Related File                                          Shared Commits   Coupling
───────────────────────────────────────────────────────────────────────────────
processor/structs.go                                              27      25.2%
processor/workers_test.go                                         17      17.7%
processor/processor.go                                            34      15.7%
main.go                                                           23      13.7%
───────────────────────────────────────────────────────────────────────────────
```

#### Author rollup - `--by-author`

Bus factor and last-toucher attribution. Lines untouched in the window collect under the sentinel `(before window)` so percentages reconcile to 100%.

```text
$ scc --by-author
───────────────────────────────────────────────────────────────────────────────
Authors · last 500 commits · 2024-01-09 → 2026-05-20
───────────────────────────────────────────────────────────────────────────────
Author                               Code     Cmplx   Files     Owns  Last seen
───────────────────────────────────────────────────────────────────────────────
Alice Smith                         24,110     4,180     118    38.6%  2026-05-22
Bob Jones                           15,447     1,902      74    24.7%  2026-03-14
Carol Lee                            9,205     3,640      51    14.7%  2026-05-19
(before window)                      6,540       810      29    10.4%          -
others (12)                          1,300       190       -     2.1%          -
───────────────────────────────────────────────────────────────────────────────
Bus factor 2 · Alice + Bob last-touched 63% of in-window code
───────────────────────────────────────────────────────────────────────────────
```

Bus factor is the fewest authors whose combined share of *in-window* code exceeds 50%. The `(before window)` sentinel is excluded from that denominator so the footer reflects who could realistically pick up recent work, not who's stamped on long-frozen lines. The `Owns` column on each row still uses the share-of-all denominator (sentinel included; rows reconcile to 100%).

Identity folding is layered: `.mailmap` is honoured first; then, by default, two commits sharing a lowercased name *and* an email domain collapse to one author (a fallback for repos without a mailmap). Generic names (`root`, `admin`, `unknown`, …) are excluded from the heuristic to avoid false merges. Disable the fallback with `--no-fold-authors` if you'd rather see every email as its own row. `--wide` adds a Comment column.

#### Author timeline - `--by-author --timeline`

How each author's activity rises and falls across the window. The Activity column is a Unicode sparkline normalised per row; the trailing tag is `quiet Nmo` (recently silent) or `↑` (currently near peak).

```text
$ scc --by-author --timeline
───────────────────────────────────────────────────────────────────────────────
Authors · last 500 commits · 2024-01-09 → 2026-05-20
───────────────────────────────────────────────────────────────────────────────
Author                   Activity                  Commits     Code±
───────────────────────────────────────────────────────────────────────────────
Alice Smith              ▂▃▅▇█▇▆▅▄▄▃▃                   210      +38k
Bob Jones                ▇█▆▄▂▁▁▁▁▁▁▁                   142      +21k  quiet 2mo
Carol Lee                ▁▁▁▁▂▃▄▅▆▇██                    96      +14k  ↑
───────────────────────────────────────────────────────────────────────────────
```

CSV is long format (one row per `(author, bucket)`); JSON includes per-author full-resolution series. Under `--ci` or non-TTY output the sparkline falls back to ASCII.

#### Languages over time - `--timeline`

How the language mix shifts: rewrites, migrations (e.g. JS → TS), gradual additions. The Trend sparkline plots each language's **absolute** trajectory, not deltas - so "rising" means "more code in this language now than at window-start".

```text
$ scc --timeline
───────────────────────────────────────────────────────────────────────────────
Languages · last 500 commits · 2024-01-09 → 2026-05-20
───────────────────────────────────────────────────────────────────────────────
Language             Trend                             Code    Share     Change
───────────────────────────────────────────────────────────────────────────────
TypeScript           ▁▁▂▃▄▅▆▇████                     36,840    58.0%    +36,840
Go                   ▃▃▄▄▅▅▅▆▆▆▆▆                     24,110    38.0%     +9,205
JavaScript           ██▇▆▅▄▃▂▁▁▁▁                      2,540     4.0%    -18,300
Markdown             ▂▃▃▄▄▅▅▆▆▆▇▇                      1,204     1.9%       +994
───────────────────────────────────────────────────────────────────────────────
```

Totals reconcile with a plain `scc` against the current HEAD tree. CSV/JSON include every non-empty language with the full per-bucket series.

#### Output format and caveats

- Tabular is for humans (sparklines, bars, ASCII fallback under `--ci`). CSV/JSON carry raw numbers only - no presentation glyphs - and include a `window` object (depth, commit count, date range) so downstream tools can reproduce the slice.
- `.gitignore` is already applied by git when each commit was recorded; `.ignore` / `.sccignore` are honoured by the engine (disable with `--no-ignore` / `--no-scc-ignore`).
- Merge commits are diffed against their first parent (`git log --first-parent` semantics).
- Rename detection uses go-git's similarity heuristic; large renames may inflate hotspot churn and reset blame attribution. Shallow clones produce a clear error rather than a panic.
- `Lines±` is the sum of added and removed lines, so files rewritten in place count twice the displaced size.
- Symlinks are skipped (v1). Binary detection is unchanged.

### HTML Report

`scc --report` writes a self-contained, infographic-style HTML page summarising the codebase: overview metrics, language breakdown, line-length histogram, hotspots, change coupling, author rollup, language and author timelines, COCOMO / LOCOMO cost estimates, and a per-file table. The page bundles its own CSS and inline SVG — no external network requests, no JavaScript runtime dependencies — so it can be opened locally, committed to a repo, attached to a release, or hosted as a static artifact.

```text
$ scc --report                       # writes scc-report.html (prompts before overwriting)
$ scc --report=docs/code.html        # explicit path; overwrites silently
```

A bare `--report` is non-destructive: if `scc-report.html` already exists in the current directory, `scc` prompts before clobbering it. Naming the file explicitly (`--report=path/out.html`) is treated as consent and overwrites without asking.

| Flag | Purpose |
|---|---|
| `--report[=path]` | Write the HTML report. Bare flag writes `scc-report.html`; explicit path overwrites silently. |
| `--report-title NAME` | Override the repo name shown in the report banner. Defaults to the `origin` remote name or the directory basename. |
| `--report-skip LIST` | Comma-separated sections to omit: `cocomo`, `locomo`, `hotspots`, `authors`, `timeline`, `files`, `uloc`, `linelength`, `card`. |

The git-history sections (hotspots, coupling, authors, timelines) only render when the directory is a git repository; outside a repo they're omitted gracefully. The report embeds an OpenGraph share card as a `data:` URL so links unfurl on most social platforms — pass `--report-skip card` to drop it.

### Large File Detection

You can have `scc` exclude large files from the output.

The option to do so is `--no-large` which by default will exclude files over 1,000,000 bytes or 40,000 lines.

You can control the size of either value using `--large-byte-count` or `--large-line-count`.

For example to exclude files over 1,000 lines and 50kb you could use the following,

`scc --no-large --large-byte-count 50000 --large-line-count 1000`

### Minified/Generated File Detection

You can have `scc` identify and optionally remove files identified as being minified or generated from the output.

You can do so by enabling the `-z` flag like so `scc -z` which will identify any file with an average line byte size >= 255 (by default) as being minified.

Minified files appear like so in the output.

```text
$ scc --no-cocomo -z ./examples/minified/jquery-3.1.1.min.js
───────────────────────────────────────────────────────────────────────────────
Language                 Files     Lines   Blanks  Comments     Code Complexity
───────────────────────────────────────────────────────────────────────────────
JavaScript (min)             1         4        0         1        3         17
───────────────────────────────────────────────────────────────────────────────
Total                        1         4        0         1        3         17
───────────────────────────────────────────────────────────────────────────────
Processed 86709 bytes, 0.087 megabytes (SI)
───────────────────────────────────────────────────────────────────────────────
```

Minified files are indicated with the text `(min)` after the language name.

Generated files are indicated with the text `(gen)` after the language name.

You can control the average line byte size using `--min-gen-line-length` such as `scc -z --min-gen-line-length 1`. Please note you need `-z` as modifying this value does not imply minified detection.

You can exclude minified files from the count totally using the flag `--no-min-gen`. Files which match the minified check will be excluded from the output.

### Remapping

Some files may not have an extension. They will be checked to see if they are a #! file. If they are then the language will be remapped to the
correct language. Otherwise, it will not process.

However, you may have the situation where you want to remap such files based on a string inside it. To do so you can use `--remap-unknown`

```bash
 scc --remap-unknown "-*- C++ -*-":"C Header"
```

The above will inspect any file with no extension looking for the string `-*- C++ -*-` and if found remap the file to be counted using the C Header rules.
You can have multiple remap rules if required,

```bash
 scc --remap-unknown "-*- C++ -*-":"C Header","other":"Java"
```

There is also the `--remap-all` parameter which will remap all files.

Note that in all cases if the remap rule does not apply normal #! rules will apply.

### Counting files as a custom category

Sometimes you want to break out a subset of files into their own reporting category without changing how they are counted.
A common example is test files such as Ruby specs (`*_spec.rb`) or JavaScript tests (`*.test.js`), which are still Ruby or
JavaScript but which you would like to see called out separately.

The `--count-as-pattern` flag matches files by their path and counts them as a new named category, while borrowing the
counting rules (comments, strings, complexity) of an existing base language. The format is `[engine:]pattern:name:baselang`.

**Patterns are globs by default**, so you usually do not need a prefix:

```bash
 scc --count-as-pattern '*_spec.rb:Ruby Spec:Ruby'
```

The above counts every file whose path matches the glob `*_spec.rb` as a new `Ruby Spec` category, counted using the Ruby
rules. The original Ruby files are unaffected and remain in the `Ruby` row. Globs support `*` (any characters) and `?`
(single character) and are matched as a full match against the path.

For more control you can opt into a regular expression with the `re:` prefix, which is matched anywhere in the path (use `^`
and `$` to anchor it yourself). You can also write `glob:` explicitly if you prefer:

```bash
 scc --count-as-pattern 're:\.test\.js$:JavaScript Tests:JavaScript'
```

Glob and regex are kept as separate modes rather than being inferred, because the same pattern can be valid in both with
different meaning (for example `foo.rb` matches only `foo.rb` as a glob, but also `fooXrb` as a regex), so guessing the engine
could silently match the wrong files.

The flag is repeatable, with the first matching rule winning:

```bash
 scc --count-as-pattern 'glob:*_spec.rb:Ruby Spec:Ruby' --count-as-pattern 'glob:*.test.js:JavaScript Tests:JavaScript'
```

The pattern is matched against the path exactly as supplied to `scc`, with no normalisation, so on Windows you must account
for the path separators yourself. A rule with an unknown base language, an invalid pattern, or missing fields is reported on
stderr and skipped.

If you want to break a monorepo down by sub-project directory, run `scc` once per directory and combine the results yourself
using the `csv`, `json`, or `sql` output formats.

### Output Formats

By default `scc` will output to the console. However, you can produce output in other formats if you require.

The different options are `tabular, wide, json, csv, csv-stream, cloc-yaml, html, html-table, sql, sql-insert, openmetrics`.

Note that you can write `scc` output to disk using the `-o, --output` option. This allows you to specify a file to
write your output to. For example `scc -f html -o output.html` will run `scc` against the current directory, and output
the results in html to the file `output.html`.

You can also write to multiple output files, or multiple types to stdout if you want using the `--format-multi` option. This is
most useful when working in CI/CD systems where you want HTML reports as an artifact while also displaying the counts in stdout.

```bash
scc --format-multi "tabular:stdout,html:output.html,csv:output.csv"
```

The above will run against the current directory, outputting to standard output the default output, as well as writing
to output.html and output.csv with the appropriate formats.

#### Tabular

This is the default output format when scc is run.

#### Wide

Wide produces some additional information which is the complexity/lines metric. This can be useful when trying to
identify the most complex file inside a project based on the complexity estimate.

#### JSON

JSON produces JSON output. Mostly designed to allow `scc` to feed into other programs.

Note that this format will give you the byte size of every file `scc` reads allowing you to get a breakdown of the
number of bytes processed.

#### CSV

CSV as an option is good for importing into a spreadsheet for analysis.

Note that this format will give you the byte size of every file `scc` reads allowing you to get a breakdown of the
number of bytes processed. Also note that CSV respects `--by-file` and as such will return a summary by default.

#### CSV-Stream

csv-stream is an option useful for processing very large repositories where you are likely to run into memory issues. It's output format is 100% the same as CSV.

Note that you should not use this with the `format-multi` option as it will always print to standard output, and because of how it works will negate the memory saving it normally gains.
savings that this option provides. Note that there is no sort applied with this option.

#### cloc-yaml

Is a drop in replacement for cloc using its yaml output option. This is quite often used for passing into other
build systems and can help with replacing cloc if required.

```text
$ scc -f cloc-yml processor
# https://github.com/boyter/scc/
header:
  url: https://github.com/boyter/scc/
  version: 2.11.0
  elapsed_seconds: 0.008
  n_files: 21
  n_lines: 6562
  files_per_second: 2625
  lines_per_second: 820250
Go:
  name: Go
  code: 5186
  comment: 273
  blank: 1103
  nFiles: 21
SUM:
  code: 5186
  comment: 273
  blank: 1103
  nFiles: 21

$ cloc --yaml processor
      21 text files.
      21 unique files.
       0 files ignored.

---
# http://cloc.sourceforge.net
header :
  cloc_url           : http://cloc.sourceforge.net
  cloc_version       : 1.60
  elapsed_seconds    : 0.196972846984863
  n_files            : 21
  n_lines            : 6562
  files_per_second   : 106.613679608407
  lines_per_second   : 33314.2364566841
Go:
  nFiles: 21
  blank: 1137
  comment: 606
  code: 4819
SUM:
  blank: 1137
  code: 4819
  comment: 606
  nFiles: 21
```

#### HTML and HTML-TABLE

The HTML output options produce a minimal html report using a table that is either standalone `html` or as just a table `html-table`
which can be injected into your own HTML pages. The only difference between the two is that the `html` option includes
html head and body tags with minimal styling.

The markup is designed to allow your own custom styles to be applied. An example report
[is here to view](SCC-OUTPUT-REPORT.html).

Note that the HTML options follow the command line options, so you can use `scc --by-file -f html` to produce a report with every
file and not just the summary.

Note that this format if it has the `--by-file` option will give you the byte size of every file `scc` reads allowing you to get a breakdown of the
number of bytes processed.

#### SQL and SQL-Insert

The SQL output format "mostly" compatible with cloc's SQL output format <https://github.com/AlDanial/cloc#sql->

While all queries on the cloc documentation should work as expected, you will not be able to append output from `scc` and `cloc` into the same database. This is because the table format is slightly different
to account for scc including complexity counts and bytes.

The difference between `sql` and `sql-insert` is that `sql` will include table creation while the latter will only have the insert commands.

Usage is 100% the same as any other `scc` command but sql output will always contain per file details. You can compute totals yourself using SQL, however COCOMO calculations will appear against the metadata table as the columns `estimated_cost` `estimated_schedule_months` and `estimated_people`.

The below will run scc against the current directory, name the output as the project scc and then pipe the output to sqlite to put into the database code.db

```bash
scc --format sql --sql-project scc . | sqlite3 code.db
```

Assuming you then wanted to append another project

```bash
scc --format sql-insert --sql-project redis . | sqlite3 code.db
```

You could then run SQL against the database,

```bash
sqlite3 code.db 'select project,file,max(nCode) as nL from t
                         group by project order by nL desc;'
```

See the cloc documentation for more examples.

#### OpenMetrics

[OpenMetrics](https://openmetrics.io/) is a metric reporting format specification extending the Prometheus exposition text format.

The produced output is natively supported by [Prometheus](https://prometheus.io/) and [GitLab CI](https://docs.gitlab.com/ee/ci/testing/metrics_reports.html)

Note that OpenMetrics respects `--by-file` and as such will return a summary by default.

The output includes a metadata header containing definitions of the returned metrics:

```text
# TYPE scc_files count
# HELP scc_files Number of sourcecode files.
# TYPE scc_lines count
# UNIT scc_lines lines
# HELP scc_lines Number of lines.
# TYPE scc_code count
# HELP scc_code Number of lines of actual code.
# TYPE scc_comments count
# HELP scc_comments Number of comments.
# TYPE scc_blanks count
# HELP scc_blanks Number of blank lines.
# TYPE scc_complexity count
# HELP scc_complexity Code complexity.
# TYPE scc_bytes count
# UNIT scc_bytes bytes
# HELP scc_bytes Size in bytes.
```

The header is followed by the metric data in either language summary form:

```text
scc_files{language="Go"} 1
scc_lines{language="Go"} 1000
scc_code{language="Go"} 1000
scc_comments{language="Go"} 1000
scc_blanks{language="Go"} 1000
scc_complexity{language="Go"} 1000
scc_bytes{language="Go"} 1000
```

or, if `--by-file` is present, in per file form:

```text
scc_lines{language="Go",file="./bbbb.go"} 1000
scc_code{language="Go",file="./bbbb.go"} 1000
scc_comments{language="Go",file="./bbbb.go"} 1000
scc_blanks{language="Go",file="./bbbb.go"} 1000
scc_complexity{language="Go",file="./bbbb.go"} 1000
scc_bytes{language="Go",file="./bbbb.go"} 1000
```

### Performance

Generally `scc` will the fastest code counter compared to any I am aware of and have compared against. The below comparisons are taken from the fastest alternative counters. See `Other similar projects` above to see all of the other code counters compared against. It is designed to scale to as many CPU's cores as you can provide.

However, if you want greater performance and you have RAM to spare you can disable the garbage collector like the following on Linux `GOGC=-1 scc .` which should speed things up considerably. For some repositories turning off the code complexity calculation via `-c` can reduce runtime as well.

Benchmarks are run on fresh 32 Core CPU Optimised Vultr Ocean Virtual Machine 2026/03/05 all done using [hyperfine](https://github.com/sharkdp/hyperfine).

See <https://github.com/boyter/scc/blob/master/benchmark.sh> to see how the benchmarks are run.

#### Valkey <https://github.com/valkey-io/valkey>

```shell
Benchmark 1: scc valkey
  Time (mean ± σ):      27.7 ms ±   2.1 ms    [User: 175.7 ms, System: 87.0 ms]
  Range (min … max):    23.1 ms …  32.1 ms    96 runs
 
Benchmark 2: scc -c valkey
  Time (mean ± σ):      23.0 ms ±   1.5 ms    [User: 131.7 ms, System: 84.0 ms]
  Range (min … max):    19.5 ms …  31.4 ms    130 runs
 
Benchmark 3: tokei valkey
  Time (mean ± σ):      74.0 ms ±  13.0 ms    [User: 394.2 ms, System: 245.1 ms]
  Range (min … max):    49.1 ms …  92.5 ms    37 runs
 
Benchmark 4: polyglot valkey
  Time (mean ± σ):      41.1 ms ±   1.2 ms    [User: 54.2 ms, System: 103.3 ms]
  Range (min … max):    37.5 ms …  47.0 ms    69 runs
 
Summary
  scc -c valkey ran
    1.20 ± 0.12 times faster than scc valkey
    1.78 ± 0.13 times faster than polyglot valkey
    3.21 ± 0.61 times faster than tokei valkey
```

#### CPython <https://github.com/python/cpython>

```shell
Benchmark 1: scc cpython
  Time (mean ± σ):      80.8 ms ±   2.6 ms    [User: 751.1 ms, System: 265.6 ms]
  Range (min … max):    75.7 ms …  87.4 ms    36 runs
 
Benchmark 2: scc -c cpython
  Time (mean ± σ):      70.5 ms ±   2.4 ms    [User: 592.6 ms, System: 254.7 ms]
  Range (min … max):    66.2 ms …  77.6 ms    40 runs
 
Benchmark 3: tokei cpython
  Time (mean ± σ):     450.2 ms ±  36.1 ms    [User: 1822.0 ms, System: 1246.9 ms]
  Range (min … max):   378.6 ms … 491.2 ms    10 runs
 
Benchmark 4: polyglot cpython
  Time (mean ± σ):     149.9 ms ±   5.8 ms    [User: 199.2 ms, System: 326.2 ms]
  Range (min … max):   138.3 ms … 164.1 ms    19 runs
 
Summary
  scc -c cpython ran
    1.15 ± 0.05 times faster than scc cpython
    2.13 ± 0.11 times faster than polyglot cpython
    6.39 ± 0.56 times faster than tokei cpython
```

#### Linux Kernel <https://github.com/torvalds/linux>

```shell
Benchmark 1: scc linux
  Time (mean ± σ):     907.2 ms ±  17.1 ms    [User: 13764.7 ms, System: 2957.0 ms]
  Range (min … max):   878.2 ms … 925.0 ms    10 runs
 
Benchmark 2: scc -c linux
  Time (mean ± σ):     842.5 ms ±  17.2 ms    [User: 9363.3 ms, System: 2977.0 ms]
  Range (min … max):   819.4 ms … 874.0 ms    10 runs
 
Benchmark 3: tokei linux
  Time (mean ± σ):      1.422 s ±  0.089 s    [User: 13.292 s, System: 9.582 s]
  Range (min … max):    1.176 s …  1.471 s    10 runs
 
Benchmark 4: polyglot linux
  Time (mean ± σ):      1.862 s ±  0.046 s    [User: 3.802 s, System: 3.543 s]
  Range (min … max):    1.800 s …  1.935 s    10 runs
 
Summary
  scc -c linux ran
    1.08 ± 0.03 times faster than scc linux
    1.69 ± 0.11 times faster than tokei linux
    2.21 ± 0.07 times faster than polyglot linux
```

#### Sourcegraph <https://github.com/SINTEF/sourcegraph.git>

Sourcegraph has gone dark since I last ran these benchmarks hence using a clone taken before this occurred.
The reason for this is to track what appears to be a performance regression in tokei.

```shell
Benchmark 1: scc sourcegraph
  Time (mean ± σ):     108.2 ms ±   3.5 ms    [User: 559.4 ms, System: 323.6 ms]
  Range (min … max):   100.5 ms … 115.9 ms    26 runs
 
Benchmark 2: scc -c sourcegraph
  Time (mean ± σ):      99.7 ms ±   4.2 ms    [User: 503.1 ms, System: 316.8 ms]
  Range (min … max):    91.4 ms … 109.4 ms    29 runs
 
Benchmark 3: tokei sourcegraph
  Time (mean ± σ):     21.359 s ±  1.025 s    [User: 57.252 s, System: 411.480 s]
  Range (min … max):   19.371 s … 22.741 s    10 runs
 
Benchmark 4: polyglot sourcegraph
  Time (mean ± σ):     135.1 ms ±   5.0 ms    [User: 198.6 ms, System: 543.7 ms]
  Range (min … max):   126.0 ms … 144.8 ms    21 runs
 
Summary
  scc -c sourcegraph ran
    1.08 ± 0.06 times faster than scc sourcegraph
    1.36 ± 0.08 times faster than polyglot sourcegraph
  214.26 ± 13.64 times faster than tokei sourcegraph
```

If you enable duplicate detection expect performance to fall by about 20% in `scc`.

Performance is tracked for some releases and presented below.

[![scc performance on Linux kernel](./performance-over-time.png)]
The decrease in performance from the 3.3.0 release was due to accurate .gitignore, .ignore and .gitmodule support.
Current work is focussed on resolving this.

### CI/CD Support

Some CI/CD systems which will remain nameless do not work very well with the box-lines used by `scc`. To support those systems better there is an option `--ci` which will change the default output to ASCII only.

```text
$ scc --ci main.go
-------------------------------------------------------------------------------
Language                 Files     Lines   Blanks  Comments     Code Complexity
-------------------------------------------------------------------------------
Go                           1       272        7         6      259          4
-------------------------------------------------------------------------------
Total                        1       272        7         6      259          4
-------------------------------------------------------------------------------
Estimated Cost to Develop $6,539
Estimated Schedule Effort 2.268839 months
Estimated People Required 0.341437
-------------------------------------------------------------------------------
Processed 5674 bytes, 0.006 megabytes (SI)
-------------------------------------------------------------------------------
```

The `--format-multi` option is especially useful in CI/CD where you want to get multiple output formats useful for storage or reporting.

### Development

If you want to hack away feel free! PR's are accepted. Some things to keep in mind. If you want to change a language definition you need to update `languages.json` and then run `go generate` which will convert it into the `processor/constants.go` file.

For all other changes ensure you run all tests before submitting. You can do so using `go test ./...`. However, for maximum coverage please run `test-all.sh` which will run `gofmt`, unit tests, race detector and then all of the integration tests. All of those must pass to ensure a stable release.

### API Support

The core part of `scc` which is the counting engine is exposed publicly to be integrated into other Go applications. See <https://github.com/pinpt/ripsrc> for an example of how to do this.

It also powers all of the code calculations displayed in <https://searchcode.com/> such as <https://searchcode.com/file/169350674/main.go/> making it one of the more used code counters in the world.

However as a quick start consider the following,

Note that you must pass in the number of bytes in the content in order to ensure it is counted!

```go
package main

import (
  "fmt"
  "io/ioutil"

  "github.com/boyter/scc/v4/processor"
)

type statsProcessor struct{}

func (p *statsProcessor) ProcessLine(job *processor.FileJob, currentLine int64, lineType processor.LineType) bool {
  switch lineType {
  case processor.LINE_BLANK:
    fmt.Println(currentLine, "lineType", "BLANK")
  case processor.LINE_CODE:
    fmt.Println(currentLine, "lineType", "CODE")
  case processor.LINE_COMMENT:
    fmt.Println(currentLine, "lineType", "COMMENT")
  }
  return true
}

func main() {
  bts, _ := ioutil.ReadFile("somefile.go")  
  t := &statsProcessor{}
  filejob := &processor.FileJob{
    Filename: "test.go",
    Language: "Go",
    Content:  bts,
    Callback: t,
    Bytes:    int64(len(bts)),
  }  
  processor.ProcessConstants() // Required to load the language information and need only be done once
  processor.CountStats(filejob)
}
```

#### Per-Byte Content Classification

For library consumers who need finer granularity than per-line classification, `scc` supports opt-in per-byte content classification. When enabled, `CountStats` populates a byte slice classifying every byte in the file as code, comment, string, or blank. This is useful for stripping comments from source files, extracting only comments, or building syntax-aware tools without reimplementing language parsing.

To enable it, set `ClassifyContent: true` on the `FileJob` before calling `CountStats`. When disabled (the default), there is zero performance impact.

```go
package main

import (
  "fmt"
  "os"

  "github.com/boyter/scc/v4/processor"
)

func main() {
  processor.ProcessConstants()

  bts, _ := os.ReadFile("main.go")
  filejob := &processor.FileJob{
    Filename:        "main.go",
    Language:        "Go",
    Content:         bts,
    Bytes:           int64(len(bts)),
    ClassifyContent: true, // Enable per-byte classification
  }
  processor.CountStats(filejob)

  // ContentByteType has one entry per byte with values:
  //   processor.ByteTypeBlank   (0) - blank lines / leading whitespace
  //   processor.ByteTypeCode    (1) - code
  //   processor.ByteTypeComment (2) - comments (including docstrings)
  //   processor.ByteTypeString  (3) - string literals

  // Example: extract only code, replacing everything else with spaces
  codeOnly := filejob.FilterContentByType(processor.ByteTypeCode)
  fmt.Println(string(codeOnly))

  // Example: extract only comments
  commentsOnly := filejob.FilterContentByType(processor.ByteTypeComment)
  fmt.Println(string(commentsOnly))

  // Example: keep both code and strings, strip comments
  noComments := filejob.FilterContentByType(processor.ByteTypeCode, processor.ByteTypeString)
  fmt.Println(string(noComments))
}
```

`FilterContentByType` returns a copy of the content with non-matching bytes replaced by spaces. Newlines are always preserved regardless of type, so the output maintains the same line structure as the original file. It returns `nil` if classification was not enabled.

Note that at syntax marker boundaries (e.g., `//`, `/*`, `"`), the first byte of the marker may be classified as the preceding state. This is a 1-byte approximation that is acceptable for content filtering use cases.

### MCP Server Mode

`scc` can run as an [MCP (Model Context Protocol)](https://modelcontextprotocol.io/) server over stdio, allowing LLM tools like Claude Desktop, Claude Code, Cursor, and others to use it as a code analysis tool.

```shell
scc --mcp
```

#### Claude Code Configuration

Run in your terminal for the current project:

```shell
claude mcp add scc -- scc --mcp
```

Or globally for all projects:

```shell
claude mcp add scc --scope user -- scc --mcp
```

Alternatively, add to your `.mcp.json`:

```json
{
  "mcpServers": {
    "scc": {
      "command": "scc",
      "args": ["--mcp"]
    }
  }
}
```

#### Claude Desktop Configuration

Add to your `claude_desktop_config.json`:

```json
{
  "mcpServers": {
    "scc": {
      "command": "/path/to/scc",
      "args": ["--mcp"]
    }
  }
}
```

#### Exposed Tools

The MCP server exposes three tools:

**`analyze`** - Count lines of code, comments, blanks and estimate complexity for a project directory or file.

| Parameter | Type | Required | Description |
|---|---|---|---|
| `path` | string | no | Directory or file path to analyze. Defaults to current directory. |
| `sort` | string | no | Column to sort by: `files`, `name`, `lines`, `blanks`, `code`, `comments`, `complexity`, `bytes`. Default: `files`. |
| `by_file` | boolean | no | If true, return per-file results instead of per-language summary. |
| `include_ext` | string | no | Comma-separated file extensions to include (e.g. `go,java,js`). |
| `exclude_ext` | string | no | Comma-separated file extensions to exclude (e.g. `json,xml`). |
| `no_duplicates` | boolean | no | Remove duplicate files from stats. |
| `no_min_gen` | boolean | no | Ignore minified or generated files. |
| `locomo` | boolean | no | Include LOCOMO (LLM cost) estimation in results. |
| `locomo_preset` | string | no | LOCOMO model preset: `large`, `medium`, `small`, `local`. Default: `medium`. |

Results are returned as JSON with per-language breakdown (files, lines, code, comments, blanks, complexity, bytes), totals, and COCOMO cost/schedule estimates. When `locomo` is enabled, LOCOMO estimates (token counts, cost, generation time, review hours) are also included.

**`hotspots`** - Rank the files in a git repository by hotspot score (complexity × change-frequency over recent history), surfacing the files most likely to need refactoring or close review.

| Parameter | Type | Required | Description |
|---|---|---|---|
| `path` | string | no | Directory inside the git repository to analyze. Defaults to current directory. |
| `depth` | number | no | Maximum number of recent commits to walk. Default: `1000`. Set to `0` for unlimited. |
| `limit` | number | no | Maximum number of files to return, highest-scoring first. Default: `50`. Set to `-1` for unlimited. |

Results are returned as JSON with the history window walked (depth, commit count, date range) and a per-file list (file, language, complexity, commits, lines changed, authors, code/comment churn, and a normalised 0–100 score). Requires `path` to be inside a git repository.

**`coupling`** - Report change coupling from a git repository's history: files that historically change together. Has two modes, selected by whether `file` is set. With `file`, returns that file's blast radius - the other files that change together with it. Without `file`, returns the repo-wide all-pairs overview.

| Parameter | Type | Required | Description |
|---|---|---|---|
| `path` | string | no | Directory inside the git repository to analyze. Defaults to current directory. |
| `file` | string | no | Target file (as it appears at HEAD). Set it for the per-file blast-radius view; omit it for the repo-wide all-pairs report. |
| `depth` | number | no | Maximum number of recent commits to walk. Default: `1000`. Set to `0` for unlimited. |
| `limit` | number | no | Maximum rows to return, strongest first - coupled files in per-file mode, file pairs in all-pairs mode. Default: `50`. Set to `-1` for unlimited. |

Results are returned as JSON with the history window walked. With `file`, each partner carries its shared-commit count and the directional probabilities `couple` (given you changed the target, how often the partner follows) and `reverse` (the other direction). Without `file`, each pair carries its shared-commit count and symmetric coupling degree. Requires `path` to be inside a git repository.

### Adding/Modifying Languages

To add or modify a language you will need to edit the `languages.json` file in the root of the project, and then run `go generate` to build it into the application. You can then `go install` or `go build` as normal to produce the binary with your modifications.

### Issues

Its possible that you may see the counts vary between runs. This usually means one of two things. Either something is changing or locking the files under scc, or that you are hitting ulimit restrictions. To change the ulimit see the following links.

- <https://superuser.com/questions/261023/how-to-change-default-ulimit-values-in-mac-os-x-10-6#306555>
- <https://unix.stackexchange.com/questions/108174/how-to-persistently-control-maximum-system-resource-consumption-on-mac/221988#221988>
- <https://access.redhat.com/solutions/61334>
- <https://serverfault.com/questions/356962/where-are-the-default-ulimit-values-set-linux-centos>
- <https://www.tecmint.com/increase-set-open-file-limits-in-linux/>

To help identify this issue run scc like so `scc -v .` and look for the message `too many open files` in the output. If it is there you can rectify it by setting your ulimit to a higher value.

### Low Memory

If you are running `scc` in a low memory environment < 512 MB of RAM you may need to set `--file-gc-count` to a lower value such as `0` to force the garbage collector to be on at all times.

A sign that this is required will be `scc` crashing with panic errors.

### Tests

scc is pretty well tested with many unit, integration and benchmarks to ensure that it is fast and complete.

### Package

Packaging as of version v3.1.0 is done through <https://goreleaser.com/>

### Containers

Note if you plan to run `scc` in Alpine containers you will need to build with CGO_ENABLED=0.

See the below Dockerfile as an example on how to achieve this based on this issue <https://github.com/boyter/scc/issues/208>

```Dockerfile
FROM golang as scc-get

ENV GOOS=linux \
GOARCH=amd64 \
CGO_ENABLED=0

ARG VERSION
RUN git clone --branch $VERSION --depth 1 https://github.com/boyter/scc
WORKDIR /go/scc
RUN go build -ldflags="-s -w"

FROM alpine
COPY --from=scc-get /go/scc/scc /bin/
ENTRYPOINT ["scc"]
```

### Badges

You can use `scc` to provide badges on your github/bitbucket/gitlab/sr.ht/codeberg open repositories. For example, [![Scc Count Badge](https://sloc.xyz/github/boyter/scc/)](https://github.com/boyter/scc/)
 The format to do so is,

<https://sloc.xyz/PROVIDER/USER/REPO>

An example of the badge for `scc` is included below, and is used on this page.

```Markdown
[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/)](https://github.com/boyter/scc/)
```

By default the badge will show the repo's lines count. You can also specify for it to show a different category, by using the `?category=` query string.

Valid values include `code, blanks, lines, comments, cocomo, effort` and examples of the appearance are included below.

[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=code)](https://github.com/boyter/scc/)
[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=blanks)](https://github.com/boyter/scc/)
[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=lines)](https://github.com/boyter/scc/)
[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=comments)](https://github.com/boyter/scc/)
[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=cocomo)](https://github.com/boyter/scc/)
[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=effort)](https://github.com/boyter/scc/)

For `cocomo` you can also set the `avg-wage` value similar to `scc` itself. For example,

<https://sloc.xyz/github/boyter/scc/?category=cocomo&avg-wage=1>
<https://sloc.xyz/github/boyter/scc/?category=cocomo&avg-wage=100000>

Note that the avg-wage value must be a positive integer otherwise it will revert back to the default value of 56286.

You can also configure the look and feel of the badge using the following parameters,

- ?lower=true will lower the title text, so "Total lines" would be "total lines"

The below can control the colours of shadows, fonts and badges. Colors can be specified as either hex codes or named colors (similar to shields.io):

- ?font-color=fff
- ?font-shadow-color=010101
- ?top-shadow-accent-color=bbb
- ?title-bg-color=555
- ?badge-bg-color=4c1

##### Named Colors

For convenience, you can use named colors instead of hex codes. The following named colors are supported:

**Shields.io colors:** `brightgreen`, `green`, `yellowgreen`, `yellow`, `orange`, `red`, `blue`, `lightgrey`, `blueviolet`

**Semantic aliases:** `success`, `important`, `critical`, `informational`, `inactive`

**CSS colors:** `white`, `black`, `silver`, `gray`, `maroon`, `purple`, `fuchsia`, `lime`, `olive`, `navy`, `teal`, `aqua`, `cyan`, `magenta`, `pink`, `coral`, `salmon`, `gold`, `khaki`, `violet`, `indigo`, `crimson`, `turquoise`, `tan`, `brown`, and many more standard CSS color names.

For example, instead of `?badge-bg-color=007ec6` you can use `?badge-bg-color=blue`.

An example of using some of these parameters to produce an admittedly ugly result

[![Scc Count Badge](https://sloc.xyz/github/boyter/scc?font-color=ff0000&badge-bg-color=0000ff&lower=true)](https://github.com/boyter/scc/)

An example using named colors for as a slightly nicer result

[![Scc Count Badge](https://sloc.xyz/github/boyter/scc?title-bg-color=navy&badge-bg-color=blue&font-color=white)](https://github.com/boyter/scc/)

*NB* it may not work for VERY large repositories (has been tested on Apache hadoop/spark without issue).

You can find the source code for badges in the repository at <https://github.com/boyter/scc/blob/master/cmd/badges/main.go>

#### A example for each supported provider

- Github - <https://sloc.xyz/github/boyter/scc/>
- sr.ht - <https://sloc.xyz/sr.ht/~nektro/magnolia-desktop/>
- Bitbucket - <https://sloc.xyz/bitbucket/boyter/decodingcaptchas>
- Gitlab - <https://sloc.xyz/gitlab/esr/loccount>
- Codeberg - <https://sloc.xyz/codeberg/NextBroomTeam/NextBroom>

### Languages

List of supported languages. The master version of `scc` supports 322 languages at last count. Note that this is always assumed that you built from master, and it might trail behind what is actually supported. To see what your version of `scc` supports run `scc --languages`

[Click here to view all languages supported by master](LANGUAGES.md)

### Citation

Please use the following Bib**La**TeX entry to cite scc in a publication:

```bib
@Software{scc,
 author     = {Ben Boyter and {Contributors}},
 title      = {scc},
 version    = {vx.y.z},
 year       = {...},
 month      = {...},
 repository = {https://github.com/boyter/scc},
}
```

You may need to check the release page <https://github.com/boyter/scc/releases> to find the correct year and month for the release you are using.

### Release Checklist

- Update version
- Push code with release number
- Tag off
- Release via goreleaser
- Update dockerfile
