README.md MARKDOWN 1,863 lines View on github.com → Search inside
1# Sloc Cloc and Code (scc)23![SCC illustration](./scc.jpg)45> scc powers [searchcode.com](https://searchcode.com) — structured code intelligence over any repo, built for AI agents.67A 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.89Goal 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.1011Also it has a very short name which is easy to type `scc`.1213If you don't like sloc cloc and code feel free to use the name `Succinct Code Counter`.1415[![Go](https://github.com/boyter/scc/actions/workflows/go.yml/badge.svg)](https://github.com/boyter/scc/actions/workflows/go.yml)16[![Coverage Status](https://coveralls.io/repos/github/boyter/scc/badge.svg?branch=master)](https://coveralls.io/github/boyter/scc?branch=master)17[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/)](https://github.com/boyter/scc/)18![Scc count downloads](https://img.shields.io/github/downloads/boyter/scc/total?label=downloads%20%28GH%29)19[![Mentioned in Awesome Go](https://awesome.re/mentioned-badge.svg)](https://github.com/avelino/awesome-go)2021Licensed under MIT licence.2223## Table of Contents2425- [Install](#install)26- [Background](#background)27- [Pitch](#pitch)28- [Usage](#usage)29- [Configuration Files](#configuration-files)30- [Complexity Estimates](#complexity-estimates)31- [Unique Lines of Code (ULOC)](#unique-lines-of-code-uloc)32- [COCOMO](#cocomo)33- [LOCOMO](#locomo)34- [Git Insight Reports](#git-insight-reports)35- [HTML Report](#html-report)36- [Output Formats](#output-formats)37- [Performance](#performance)38- [Development](#development)39- [MCP Server Mode](#mcp-server-mode)40- [Adding/Modifying Languages](#addingmodifying-languages)41- [Issues](#issues)42- [Badges](#badges)43- [Language Support](LANGUAGES.md)44- [Citation](#citation)4546### scc for Teams & Enterprise4748While 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.4950We 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,51sign up for the early access list [here](https://docs.google.com/forms/d/e/1FAIpQLScIBKy3y2m0rKu89L67qwe26Xyn9Scu0gW-HQX9lC0qEAx9nQ/viewform)5253### Install5455#### Go Install5657You can install `scc` by using the standard go toolchain.5859To install the latest stable version of scc:6061`go install github.com/boyter/scc/v4@latest`6263To install a development version:6465`go install github.com/boyter/scc/v4@master`6667Note that `scc` needs go version >= 1.25.6869#### Snap7071A [snap install](https://snapcraft.io/scc) exists thanks to [Ricardo](https://feliciano.tech/).7273`$ sudo snap install scc`7475*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.7677#### Homebrew7879Or if you have [Homebrew](https://brew.sh/) installed8081`$ brew install scc`8283#### Fedora8485Fedora Linux users can use a [COPR repository](https://copr.fedorainfracloud.org/coprs/lihaohong/scc/):8687`$ sudo dnf copr enable lihaohong/scc && sudo dnf install scc`8889#### MacPorts9091On macOS, you can also install via [MacPorts](https://www.macports.org)9293`$ sudo port install scc`9495#### Scoop9697Or if you are using [Scoop](https://scoop.sh/) on Windows9899`$ scoop install scc`100101#### Chocolatey102103Or if you are using [Chocolatey](https://chocolatey.org/) on Windows104105`$ choco install scc`106107#### WinGet108109Or if you are using [WinGet](https://github.com/microsoft/winget-cli) on Windows110111`winget install --id benboyter.scc --source winget`112113#### FreeBSD114115On FreeBSD, scc is available as a package116117`$ pkg install scc`118119Or, if you prefer to build from source, you can use the ports tree120121`$ cd /usr/ports/devel/scc && make install clean`122123### Run in Docker124125Go to the directory you want to run scc from.126127Run the command below to run the latest release of scc on your current working directory:128129```bash130docker run --rm -it -v "$PWD:/pwd:ro" --network none ghcr.io/boyter/scc:master scc /pwd131```132133#### Manual134135Binaries 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.136137#### GitLab138139<https://about.gitlab.com/blog/2023/02/15/code-counting-in-gitlab/>140141#### Other142143If 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.144145### Background146147Read all about how it came to be along with performance benchmarks,148149- <https://boyter.org/posts/sloc-cloc-code/>150- <https://boyter.org/posts/why-count-lines-of-code/>151- <https://boyter.org/posts/sloc-cloc-code-revisited/>152- <https://boyter.org/posts/sloc-cloc-code-performance/>153- <https://boyter.org/posts/sloc-cloc-code-performance-update/>154155Some reviews of `scc`156157- <https://nickmchardy.com/2018/10/counting-lines-of-code-in-koi-cms.html>158- <https://www.feliciano.tech/blog/determine-source-code-size-and-complexity-with-scc/>159- <https://metaredux.com/posts/2019/12/13/counting-lines.html>160161Setting up `scc` in GitLab162163- <https://about.gitlab.com/blog/2023/02/15/code-counting-in-gitlab/>164165A talk given at the first GopherCon AU about `scc` (press S to see speaker notes)166167- <https://boyter.org/static/gophercon-syd-presentation/>168- <https://www.youtube.com/watch?v=jd-sjoy3GZo>169170For performance see the [Performance](https://github.com/boyter/scc#performance) section171172Other similar projects,173174- [SLOCCount](https://www.dwheeler.com/sloccount/) the original sloc counter175- [cloc](https://github.com/AlDanial/cloc), inspired by SLOCCount; implemented in Perl for portability176- [gocloc](https://github.com/hhatto/gocloc) a sloc counter in Go inspired by tokei177- [loc](https://github.com/cgag/loc) rust implementation similar to tokei but often faster178- [loccount](https://gitlab.com/esr/loccount) Go implementation written and maintained by ESR179- [mezura](https://github.com/subamanis/mezura) fast code counter in C++180- [polyglot](https://github.com/vmchale/polyglot) ATS sloc counter181- [tokei](https://github.com/XAMPPRocky/tokei) fast, accurate and written in rust182- [sloc](https://github.com/flosse/sloc) coffeescript code counter183- [stto](https://github.com/mainak55512/stto) new Go code counter with a focus on performance184- [linejudge](https://github.com/loc-conformance/linejudge) conformance and differential testing suite for line counters185- [linebench](https://github.com/loc-conformance/linebench) multi-counter performance and resource benchmark suite186187Interesting reading about other code counting projects tokei, loc, polyglot and loccount188189- <https://www.reddit.com/r/rust/comments/59bm3t/a_fast_cloc_replacement_in_rust/>190- <https://www.reddit.com/r/rust/comments/82k9iy/loc_count_lines_of_code_quickly/>191- <http://blog.vmchale.com/article/polyglot-comparisons>192- <http://esr.ibiblio.org/?p=8270>193194Further reading about processing files on the disk performance195196- <https://blog.burntsushi.net/ripgrep/>197198Using `scc` to process 40 TB of files from GitHub/Bitbucket/GitLab199200- <https://boyter.org/posts/an-informal-survey-of-10-million-github-bitbucket-gitlab-projects/>201202### Pitch203204Why use `scc`?205206- It is very fast and gets faster the more CPU you throw at it207- Accurate208- Works very well across multiple platforms without slowdown (Windows, Linux, macOS)209- Large language support210- Can ignore duplicate files211- Has complexity estimations212- You need to tell the difference between Coq and Verilog in the same directory213- cloc yaml output support so potentially a drop in replacement for some users214- Can identify or ignore minified files215- Able to identify many #! files ADVANCED! <https://github.com/boyter/scc/issues/115>216- Can ignore large files by lines or bytes217- Can calculate the ULOC or unique lines of code by file, language or project218- Supports multiple output formats for integration, CSV, SQL, JSON, HTML and more219220Why not use `scc`?221222- You don't like Go for some reason223- It cannot count D source with different nested multi-line comments correctly <https://github.com/boyter/scc/issues/27>224225### Differences226227There are some important differences between `scc` and other tools that are out there. Here are a few important ones for you to consider.228229Blank 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,230231```c232/* blank lines follow233234235*/236```237238Would be counted as 4 lines of comments. This is noticeable when comparing scc's output to other tools on large239repositories.240241`scc` is able to count verbatim strings correctly. For example in C# the following,242243```C#244private const string BasePath = @"a:\";245// The below is returned to the user as a version246private const string Version = "1.0.0";247```248249Because of the prefixed @ this string ends at the trailing " by ignoring the escape character \ and as such should be250counted as 2 code lines and 1 comment. Some tools are unable to251deal with this and instead count up to the "1.0.0" as a string which can cause the middle comment to be counted as252code rather than a comment.253254`scc` will also tell you the number of bytes it has processed (for most output formats) allowing you to estimate the255cost of running some static analysis tools.256257### Usage258259Command line usage of `scc` is designed to be as simple as possible.260Full details can be found in `scc --help` or `scc -h`. Note that the below reflects the state of master not a release, as such261features listed below may be missing from your installation.262263```text264$ scc -h265Sloc, Cloc and Code. Count lines of code in a directory with complexity estimation.266Version 4.1.0267Ben Boyter <ben@boyter.org> + Contributors268https://github.com/boyter/scc269270Usage:271  scc [flags] [files or directories]272273Examples:274  Count the current directory:275    scc276277  Count a specific folder or file:278    scc myproject/279    scc main.go280281  Count several paths at once:282    scc src/ docs/ README.md283284  Show a per-file breakdown instead of the per-language summary:285    scc --by-file286287  Output as CSV or JSON (e.g. for further processing):288    scc --format csv289    scc --format json -o counts.json290291  Count an unrecognised extension as a known language:292    scc --count-as jsp:html293294  Count files matching a path pattern as a new category (glob by default):295    scc --count-as-pattern '*_spec.rb:Ruby Spec:Ruby'296297  Generate a self-contained HTML infographic report:298    scc --report299    scc --report=out.html --report-title "myrepo" --report-skip cocomo300301  Use a project config file (./.sccconfig) or a global one (precedence: global < project < CLI):302    export SCC_CONFIG_PATH=~/.sccconfig303    scc --config team.sccconfig304305  Tune the COCOMO cost estimate, or turn it off (see https://en.wikipedia.org/wiki/COCOMO):306    scc --avg-wage 75000 --cocomo-project-type semi-detached307    scc --no-cocomo308309Flags:310      --avg-wage int                        average wage value used for basic COCOMO calculation (default 56286)311      --binary                              disable binary file detection312      --buckets int                         time-bucket resolution for the git timeline reports (default 60)313      --by-author                           render the author rollup report (bus factor and last-toucher attribution over recent git history)314      --by-file                             display output for every file315  -m, --character                           calculate max and mean characters per line316      --ci                                  enable CI output settings where stdout is ASCII317      --cocomo-project-type string          change COCOMO model type [organic, semi-detached, embedded, "custom,1,1,1,1"] (default "organic")318      --cognitive                           calculate cognitive (nesting-weighted) complexity319      --config string                       load this file as the global config source; overrides SCC_CONFIG_PATH, honored even with --no-config320      --cost-comparison                     show both COCOMO and LOCOMO estimates side by side321      --count-as string                     count extension as language [e.g. jsp:htm,chead:"C Header" maps extension jsp to html and chead to C Header]322      --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]323      --count-ignore                        set to allow .gitignore and .ignore files to be counted324      --count-unsupported                   count files with an unrecognised language under an "Unknown" category as plain text325      --coupling                            render the change-coupling report (file pairs that change together over recent git history)326      --coupling-for string                 blast-radius view: given a file path, show what tends to change with it over recent git history327      --coupling-weighted                   weight coupling by file complexity so pairs of complex files rank above generated/data-file churn (implies --coupling)328      --currency-symbol string              set currency symbol (default "$")329      --debug                               enable debug output330      --depth int                           commit window size for git history reports; 0 means entire history (large repos may be slow) (default 1000)331      --directory-walker-job-workers int    controls the maximum number of workers which will walk the directory tree (default 8)332  -a, --dryness                             calculate the DRYness of the project (implies --uloc)333      --eaf float                           the effort adjustment factor derived from the cost drivers (1.0 if rated nominal) (default 1)334      --exclude-dir strings                 directories to exclude (default [.git,.hg,.svn])335  -x, --exclude-ext strings                 ignore file extensions (overrides include-ext) [comma separated list: e.g. go,java,js]336  -n, --exclude-file strings                ignore files with matching names (default [package-lock.json,Cargo.lock,yarn.lock,pubspec.lock,Podfile.lock,pnpm-lock.yaml])337      --exp-per-language-counters           experimental, may change or be removed: count with the scanner written for the file's language where there is one, see --list-counters338      --file-gc-count int                   number of files to parse before turning the GC on (default 10000)339      --file-list-job-workers int           number of goroutine workers that turn a walked path into a job to be counted (default 8)340      --file-list-queue-size int            the size of the queue of files found and ready to be read into memory (default 8)341      --file-process-job-workers int        number of goroutine workers that process files collecting stats (default 8)342      --file-summary-job-queue-size int     the size of the queue used to hold processed file statistics before formatting (default 8)343      --find-root-config                    discover the project .sccconfig by walking up to the repository root instead of using ./.sccconfig344  -f, --format string                       set output format [tabular, wide, json, json2, csv, csv-stream, cloc-yaml, html, html-table, sql, sql-insert, openmetrics] (default "tabular")345      --format-multi string                 have multiple format output overriding --format [e.g. tabular:stdout,csv:file.csv,json:file.json]346      --gen                                 identify generated files347      --generated-markers strings           string markers in head of generated files (default [do not edit,<auto-generated />])348  -h, --help                                help for scc349      --hotspots                            render the hotspots report (files ranked by complexity × change frequency over recent git history)350      --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 precedence351  -i, --include-ext strings                 limit to file extensions [comma separated list: e.g. go,java,js]352      --include-symlinks                    if set will count symlink files353  -l, --languages                           print supported languages and extensions354      --large-byte-count int                number of bytes a file can contain before being removed from output (default 1000000)355      --large-line-count int                number of lines a file can contain before being removed from output (default 40000)356      --list-counters                       print the languages that have a scanner of their own and exit357      --locomo                              enable LOCOMO (LLM Output COst MOdel) cost estimation358      --locomo-config string                LOCOMO power-user config "tokensPerLine,inputPerLine,complexityWeight,iterations,iterationWeight"359      --locomo-cycles float                 override estimated LLM iteration cycles (default: calculated from complexity)360      --locomo-input-price float            LOCOMO cost per 1M input tokens in dollars (overrides preset)361      --locomo-output-price float           LOCOMO cost per 1M output tokens in dollars (overrides preset)362      --locomo-preset string                LOCOMO model preset [large, medium, small, local] (default "medium")363      --locomo-review float                 human review minutes per line of code for LOCOMO estimate (default 0.01)364      --locomo-tps float                    LOCOMO output tokens per second (overrides preset)365      --mcp                                 start as an MCP (Model Context Protocol) server over stdio366      --min                                 identify minified files367  -z, --min-gen                             identify minified or generated files368      --min-gen-line-length int             number of bytes per average line for file to be considered minified or generated (default 255)369      --no-cocomo                           remove COCOMO calculation output370  -c, --no-complexity                       skip calculation of code complexity371      --no-config                           disable auto-discovery of the SCC_CONFIG_PATH global and the project ./.sccconfig config372  -d, --no-duplicates                       remove duplicate files from stats and output373      --no-fold-authors                     disable the name+email-domain identity folding fallback for git author reports (mailmap still applied)374      --no-gen                              ignore generated files in output (implies --gen)375      --no-gitignore                        disables .gitignore file logic376      --no-gitmodule                        disables .gitmodules file logic377      --no-hborder                          remove horizontal borders between sections378      --no-ignore                           disables .ignore file logic379      --no-large                            ignore files over certain byte and line size set by large-line-count and large-byte-count380      --no-min                              ignore minified files in output (implies --min)381      --no-min-gen                          ignore minified or generated files in output (implies --min-gen)382      --no-scc-ignore                       disables .sccignore file logic383      --no-size                             remove size calculation output384  -M, --not-match stringArray               ignore files and directories matching regular expression385  -o, --output string                       output filename (default stdout)386      --overhead float                      set the overhead multiplier for corporate overhead (facilities, equipment, accounting, etc.) (default 2.4)387  -p, --percent                             include percentage values in output388      --remap-all string                    inspect every file and remap by checking for a string and remapping the language [e.g. "-*- C++ -*-":"C Header"]389      --remap-unknown string                inspect files of unknown type and remap by checking for a string and remapping the language [e.g. "-*- C++ -*-":"C Header"]390      --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 silently391      --report-skip string                  comma-separated sections to omit (cocomo,locomo,hotspots,coupling,authors,timeline,files,uloc,linelength,card)392      --report-title string                 override the repo name shown in the report banner393      --size-unit string                    set size unit [si, binary, mixed, xkcd-kb, xkcd-kelly, xkcd-imaginary, xkcd-intel, xkcd-drive, xkcd-bakers] (default "si")394      --sloccount-format                    print a more SLOCCount like COCOMO calculation395  -s, --sort string                         column to sort by [files, name, lines, blanks, code, comments, complexity] (default "files")396      --sql-project string                  use supplied name as the project identifier for the current run. Only valid with the --format sql or sql-insert option397      --timeline                            render an over-time view of recent git history; with --by-author runs the author timeline, alone runs the languages timeline398  -t, --trace                               enable trace output (not recommended when processing multiple files)399  -u, --uloc                                calculate the number of unique lines of code (ULOC) for the project400  -v, --verbose                             verbose output401      --version                             version for scc402  -w, --wide                                wider output with additional statistics (implies --complexity)403```404405Output should look something like the below for the redis project406407```text408$ scc redis 409───────────────────────────────────────────────────────────────────────────────410Language                 Files     Lines   Blanks  Comments     Code Complexity411───────────────────────────────────────────────────────────────────────────────412C                          437   267,353   31,103    45,998  190,252     48,269413JSON                       406    25,392        4         0   25,388          0414C Header                   288    48,831    5,648    11,302   31,881      3,097415TCL                        215    66,943    7,330     4,651   54,962      3,816416Shell                       75     1,626      239       343    1,044        185417Python                      34     4,802      694       498    3,610        621418Markdown                    26     4,647    1,226         0    3,421          0419Autoconf                    22    11,732    1,124     1,420    9,188      1,016420Lua                         20       525       69        71      385         89421Makefile                    20     1,956      368       170    1,418         85422YAML                        20     2,696      147        53    2,496          0423MSBuild                     11     1,995        2         0    1,993        160424Plain Text                  10     1,773      313         0    1,460          0425Ruby                         9       817       73       105      639        123426C++                          8       546       85        43      418         43427HTML                         5     9,658    2,928        12    6,718          0428License                      3        90       17         0       73          0429CMake                        2       298       49         5      244         12430CSS                          2       107       16         0       91          0431Systemd                      2        80        6         0       74          0432BASH                         1       143       16         5      122         38433Batch                        1        28        2         0       26          3434C++ Header                   1         9        1         3        5          0435Extensible Styleshe…         1        10        0         0       10          0436JavaScript                   1        31        1         0       30          5437Module-Definition            1    11,375    2,116         0    9,259        167438SVG                          1         1        0         0        1          0439Smarty Template              1        44        1         0       43          5440m4                           1       951      218        64      669          0441───────────────────────────────────────────────────────────────────────────────442Total                    1,624   464,459   53,796    64,743  345,920     57,734443───────────────────────────────────────────────────────────────────────────────444Estimated Cost to Develop (organic) $12,517,562445Estimated Schedule Effort (organic) 35.93 months446Estimated People Required (organic) 30.95447───────────────────────────────────────────────────────────────────────────────448Processed 16601962 bytes, 16.602 megabytes (SI)449───────────────────────────────────────────────────────────────────────────────450```451452Note 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.453454You can also run against multiple files or directories `scc directory1 directory2 file1 file2` with the results aggregated in the output.455456Since `scc` writes to standard output, there are many ways to easily share the results. For example, using [netcat](https://manpages.org/nc)457and [one of many pastebins](https://paste.c-net.org/) gives a public URL:458459```bash460$ scc | nc paste.c-net.org 9999461https://paste.c-net.org/Example462```463464### Ignore Files465466`scc` supports .ignore files inside directories that it scans. This is similar to how ripgrep, ag and tokei work. 467.ignore files are 100% the same as .gitignore files with the same syntax, and as such `scc` will ignore files and 468directories listed in them. You can add .ignore files to ignore things like vendored dependency checked in files and 469such. The idea is allowing you to add a file or folder to git and have ignored in the count.470471It also supports its own ignore file `.sccignore` if you want `scc` to ignore things while having ripgrep, ag, tokei 472and others support them.473474You can also supply additional ignore files from outside the scanned tree with `--ignore-file`. The file uses the 475same gitignore syntax and its patterns are anchored at the scan root (so `/build` matches only the top-level `build`). 476This is handy for applying a shared ruleset such as a `.dockerignore` or a personal global ignore:477478```479scc --ignore-file ~/.gitignore --ignore-file ./.dockerignore480```481482The flag can be repeated and order matters: a later file can re-include something an earlier one ignored (via a `!` 483negation), and any `.gitignore`, `.ignore` or `.sccignore` discovered inside the scanned tree takes precedence over 484everything supplied with `--ignore-file`.485486If you want to apply your global git excludes file, point `--ignore-file` at it directly (for example 487`--ignore-file ~/.config/git/ignore`). `scc` deliberately does not shell out to `git` to discover it for you, but you 488can make it automatic by putting the flag in a `.sccconfig` configuration file and pointing the `SCC_CONFIG_PATH` environment 489variable at it, so every run picks it up without typing:490491```492# ~/.config/scc/global.sccconfig493--ignore-file /home/me/.config/git/ignore494```495496```497export SCC_CONFIG_PATH=~/.config/scc/global.sccconfig498scc   # now applies your global ignore on every run499```500501### Configuration Files502503`scc` can read default flags from a configuration file to avoid creating shell aliases. 504The format is an *opts-list* in the style of ripgrep and bat: the file is simply a list of the same command-line flags 505you would otherwise type, and anything valid on the command line is valid in the file, with the exception506of output flags.507508Format rules:509510- One flag per line is the recommended style, but multiple whitespace-separated tokens per line are allowed (`--exclude-dir vendor`).511- Lines use the normal `--` prefix, e.g. `--no-cocomo`.512- `#` begins a comment. Whole-line and inline trailing comments are stripped.513- Blank lines are ignored.514- 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"`).515- Backslash is an ordinary literal, not an escape character, so a Windows path such as `--exclude-dir C:\build\out` survives verbatim.516- 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.517518Example `.sccconfig`:519520```521# count the way I like it522--no-cocomo523--exclude-dir vendor,node_modules524--format wide          # default to the wider table525```526527#### Sources and discovery528529There are two configuration tiers:530531- **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`.532- **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`.533534To 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`.535536#### Precedence537538Lowest to highest, later wins: **global config < project config < command line**. Scalar and boolean flags follow last-wins, so the command line always overrides config.539540Slice flags (`--exclude-dir`, `--exclude-file`, `--exclude-ext`, `--include-ext`, `--not-match`) **union** instead of overriding:541542```543config: --exclude-dir vendor544CLI:    --exclude-dir dist545result: vendor, dist546```547548The 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`.549550#### Config can never write a file551552A 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.553554#### Control flags555556| Flag | Effect |557|------|--------|558| `--no-config` | Disable auto-discovery: skip the `SCC_CONFIG_PATH` global and the project `.sccconfig`. |559| `--config <path>` | Load this file as the global source. Always honoured, even with `--no-config`; overrides `SCC_CONFIG_PATH`. |560| `--find-root-config` | Discover the project `.sccconfig` by walking up to the repository root instead of using `./.sccconfig`. No-op under `--no-config`. |561562`--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).563564#### The `@file` argument bundle565566`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.567568Note 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`.569570### Interesting Use Cases571572Used inside Intel Nemu Hypervisor to track code changes between revisions <https://github.com/intel/nemu/blob/topic/virt-x86/tools/cloc-change.sh#L9>573Appears to also be used inside both <http://codescoop.com/> <https://pinpoint.com/> <https://github.com/chaoss/grimoirelab-graal>574575It 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.576577You can also hook scc into your gitlab pipeline <https://gitlab.com/guided-explorations/ci-cd-plugin-extensions/ci-cd-plugin-extension-scc>578579Used by the following products and services,580581- [GitHub CodeQL](https://github.com/boyter/scc/pull/317) - The CodeQL engine uses `scc` for line counting582- [JetBrains Qodana](https://github.com/JetBrains/qodana-cli) - The Qodana CLI leverages `scc` as a command-line helper for code analysis583- [Scaleway](https://twitter.com/Scaleway/status/1488087029476995074?s=20&t=N2-z6O-ISDdDzULg4o4uVQ) - Cloud provider using `scc`584- [Linux Foundation LFX Insights](https://docs.linuxfoundation.org/lfx/insights/v3-beta-version-current/getting-started/landing-page/cocomo-cost-estimation-simplified) - COCOMO cost estimation585- [OpenEMS](https://openems.io/)586587### Features588589`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 count590591- Single Line Comments592- Multi Line Comments593- Strings594- Multi Line Strings595- Blank lines596597Because of this it is able to accurately determine if a comment is in a string or is actually a comment.598599It 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.600601### Complexity Estimates602603Let's take a minute to discuss the complexity estimate itself.604605The 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.606607Because 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.608609Generally 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.610611As for how it works.612613It'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.614615The 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.616617In 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.618619The 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.620621The increment happens for each of the matching conditions and produces the number you see.622623### Unique Lines of Code (ULOC)624625ULOC stands for Unique Lines of Code and represents the unique lines across languages, files and the project itself. This idea was taken from626<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 is627there to assist with the estimation of complexity within the project. Quoting the source628629> 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.630631You can obtain the ULOC by supplying the `-u` or `--uloc` argument to `scc`.632633It has a corresponding metric `DRYness %` which is the percentage of ULOC to CLOC or `DRYness = ULOC / SLOC`. The634higher the number the more DRY (don't repeat yourself) the project can be considered. In general a higher value635here 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>636637To obtain the DRYness metric you can use the `-a` or `--dryness` argument to `scc`, which will implicitly set `--uloc`.638639Note that there is a performance penalty when calculating the ULOC metrics which can double the runtime.640641Running the uloc and DRYness calculations against C code a clone of redis produces an output as follows.642643```bash644$ scc -a -i c redis 645───────────────────────────────────────────────────────────────────────────────646Language                 Files     Lines   Blanks  Comments     Code Complexity647───────────────────────────────────────────────────────────────────────────────648C                          437   267,353   31,103    45,998  190,252     48,269649(ULOC)                            149892650───────────────────────────────────────────────────────────────────────────────651Total                      437   267,353   31,103    45,998  190,252     48,269652───────────────────────────────────────────────────────────────────────────────653Unique Lines of Code (ULOC)       149892654DRYness %                           0.56655───────────────────────────────────────────────────────────────────────────────656Estimated Cost to Develop (organic) $6,681,762657Estimated Schedule Effort (organic) 28.31 months658Estimated People Required (organic) 20.97659───────────────────────────────────────────────────────────────────────────────660Processed 9390815 bytes, 9.391 megabytes (SI)661───────────────────────────────────────────────────────────────────────────────662```663664Further reading about the ULOC calculation can be found at <https://boyter.org/posts/sloc-cloc-code-new-metic-uloc/>665666Interpreting Dryness,667668- 75% (High Density): Very terse, expressive code. Every line counts. (Example: Clojure, Haskell)669- 60% - 70% (Standard): A healthy balance of logic and structural ceremony. (Example: Java, Python)670- < 55% (High Boilerplate): High repetition. Likely due to mandatory error handling, auto-generated code, or verbose configuration. (Example: C#, CSS)671672See <https://boyter.org/posts/boilerplate-tax-ranking-popular-languages-by-density/> for more details.673674### COCOMO675676The COCOMO statistics displayed at the bottom of any command line run can be configured as needed.677678```text679Estimated Cost to Develop (organic) $664,081680Estimated Schedule Effort (organic) 11.772217 months681Estimated People Required (organic) 5.011633682```683684To change the COCOMO parameters, you can either use one of the default COCOMO models.685686```text687scc --cocomo-project-type organic688scc --cocomo-project-type semi-detached689scc --cocomo-project-type embedded690```691692You can also supply your own parameters if you are familiar with COCOMO as follows,693694```text695scc --cocomo-project-type "custom,1,1,1,1"696```697698See below for details about how the model choices, and the parameters they use.699700Organic – A software project is said to be an organic type if the team size required is adequately small, the701problem is well understood and has been solved in the past and also the team members have a nominal experience702regarding the problem.703704`scc --cocomo-project-type "organic,2.4,1.05,2.5,0.38"`705706Semi-detached – A software project is said to be a Semi-detached type if the vital characteristics such as team-size,707experience, knowledge of the various programming environment lie in between that of organic and Embedded.708The projects classified as Semi-Detached are comparatively less familiar and difficult to develop compared to709the organic ones and require more experience and better guidance and creativity. Eg: Compilers or710different Embedded Systems can be considered of Semi-Detached type.711712`scc --cocomo-project-type "semi-detached,3.0,1.12,2.5,0.35"`713714Embedded – A software project with requiring the highest level of complexity, creativity, and experience715requirement fall under this category. Such software requires a larger team size than the other two models716and also the developers need to be sufficiently experienced and creative to develop such complex models.717718`scc --cocomo-project-type "embedded,3.6,1.20,2.5,0.32"`719720### LOCOMO721722LOCOMO (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.723724Note: 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.725726**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.727728LOCOMO is opt-in. Enable it with `--locomo` or use `--cost-comparison` to display both COCOMO and LOCOMO side by side.729730```731$ scc --locomo .732...733LOCOMO LLM Cost Estimate (medium)734  Tokens Required (in/out) 3.0M / 0.7M735  Cost to Generate $20736  Estimated Cycles 2.1737  Generation Time (serial) 3.9 hours738  Human Review Time 5.9 hours739  Disclaimer: rough ballpark for regenerating code using a LLM.740  Does not account for context reuse, test generation, or heavy debugging.741```742743#### How it works744745LOCOMO uses SLOC and complexity data that `scc` already computes. The model works per-file and aggregates:7467471. **Output tokens** - each line of code maps to ~10 LLM output tokens (configurable).7482. **Input tokens** - estimated prompting cost, scaled by code complexity. More complex code (higher branch density) requires more detailed prompts. Scales to prevent runaway estimates.7493. **Iteration factor** - LLMs rarely produce correct code on the first try. A retry multiplier scales with complexity, also scales.7504. **Dollar cost** - input and output tokens multiplied by per-token pricing.7515. **Generation time** - total serial output tokens divided by tokens-per-second throughput.7526. **Human review time** - estimated per-line overhead for planning, review, testing, and integration.753754#### Model presets755756Presets 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:757758| Preset | Represents | Input $/1M | Output $/1M | TPS |759|--------|-----------|-----------|-------------|-----|760| `large` | Frontier models (Opus, GPT-5.3, Gemini 3.1 Pro, etc.) | 10.00 | 30.00 | 30 |761| `medium` (default) | Balanced models (Sonnet, Gemini Flash, etc.) | 3.00 | 15.00 | 50 |762| `small` | Fast/cheap models (Haiku, GPT-4o-mini, etc.) | 0.50 | 2.00 | 100 |763| `local` | Self-hosted models (Llama, Mistral, Qwen etc.) | 0.00 | 0.00 | 15 |764765For `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.766767```768scc --locomo --locomo-preset large .769scc --locomo --locomo-preset local .770```771772#### Overriding preset values773774You can override individual preset values for pricing or throughput:775776```777scc --locomo --locomo-input-price 1.0 --locomo-output-price 5.0 .778scc --locomo --locomo-tps 100 .779```780781#### Human review time782783The `--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.784785For mission-critical, security-sensitive, or complex algorithmic code you should increase this:786787```788scc --locomo --locomo-review 0.05 .789scc --locomo --locomo-review 0.1 .790```791792#### Power-user configuration793794The five internal model parameters can be overridden with a single comma-separated config string:795796```797scc --locomo --locomo-config "tokensPerLine,inputPerLine,complexityWeight,iterations,iterationWeight"798```799800The defaults are `"10,20,5,1.5,2"`. Here is what each parameter controls:801802| Position | Name | Default | Description |803|----------|------|---------|-------------|804| 1 | tokensPerLine | 10 | Average LLM output tokens per line of code |805| 2 | inputPerLine | 20 | Base LLM input (prompt) tokens per output line |806| 3 | complexityWeight | 5 | How much complexity density scales input tokens: `inputFactor = 1 + sqrt(density) * weight` |807| 4 | iterations | 1.5 | Base iteration/retry cycles before complexity adjustment |808| 5 | iterationWeight | 2 | How much complexity density adds extra cycles: `cycles = iterations + sqrt(density) * weight` |809810The 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.811812For example, to model a cheaper/faster LLM that needs fewer tokens but more retries:813814```815scc --locomo --locomo-config "8,15,3,2.0,1.5"816```817818#### Comparing COCOMO and LOCOMO819820Use `--cost-comparison` to show both estimates side by side. This enables COCOMO (if it was disabled) and LOCOMO together:821822```823scc --cost-comparison .824```825826#### What LOCOMO does not account for827828LOCOMO is a rough estimator with known limitations:829830- **No context reuse.** Real LLM-assisted development shares context across files. The per-file model overestimates input tokens for large projects with shared patterns.831- **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.832- **Code that LLMs can't write well.** Complex concurrency, platform-specific edge cases, and security-critical crypto need human authoring, not just review.833- **No test generation cost.** The model estimates source code generation only, not test suites.834- **Pricing changes.** LLM pricing drops rapidly. Preset defaults will become stale - use explicit price flags for current estimates.835836#### All LOCOMO flags837838| Flag | Default | Description |839|------|---------|-------------|840| `--locomo` | false | Enable LOCOMO output |841| `--cost-comparison` | false | Show COCOMO + LOCOMO side by side |842| `--locomo-preset` | medium | Model tier preset for pricing and throughput |843| `--locomo-input-price` | (preset) | Override: cost per 1M input tokens ($) |844| `--locomo-output-price` | (preset) | Override: cost per 1M output tokens ($) |845| `--locomo-tps` | (preset) | Override: output tokens per second |846| `--locomo-review` | 0.01 | Human review minutes per line of code |847| `--locomo-cycles` | (calculated) | Override estimated LLM iteration cycles |848| `--locomo-config` | 10,20,5,1.5,2 | Power-user config: tokensPerLine, inputPerLine, complexityWeight, iterations, iterationWeight |849850### Git Insight Reports851852In 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`.853854> **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.855856When no report flag is set, `scc` behaves exactly as today, these flags are strictly opt-in.857858| Flag | Report | Answers |859|---|---|---|860| `--hotspots` | Hotspots | Which files are defect-prone - high complexity × high churn. |861| `--coupling` / `--coupling-for FILE` | Change coupling | Which files change together - hidden dependencies and blast radius. |862| `--by-author` | Author rollup | Bus factor - who last-touched the surviving code. |863| `--by-author --timeline` | Author timeline | How each author's activity rises and falls over time. |864| `--timeline` | Languages over time | How the language mix shifts - rewrites, migrations. |865866Shared flags for these reports:867868| Flag | Default | Purpose |869|---|---|---|870| `--depth N` | 1000 | Commit window size (newest N commits). `0` walks the entire history (slow on big repos). Negative values are rejected. |871| `--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. |872| `-w, --wide` | - | 109-column variant of any report (extra columns where applicable). |873| `--no-fold-authors` | off | Disable the name + email-domain identity folding fallback applied after `.mailmap`. |874875Each 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.876877#### Hotspots - `--hotspots`878879Ranks files by defect-proneness: complexity × change frequency over the window. Surfaces *where to review*, not a defect probability.880881```text882$ scc --hotspots883───────────────────────────────────────────────────────────────────────────────884Hotspots · last 500 commits · 2024-01-09 → 2026-05-20885───────────────────────────────────────────────────────────────────────────────886File                            Lang   Cmplx  Commits   Lines±  Authrs  Hotspot887───────────────────────────────────────────────────────────────────────────────888processor/workers.go              Go     488       62    7,240       9    100.0889processor/processor.go            Go     402       41    3,910       7     71.4890processor/formatters.go           Go     233       38    2,980       6     51.8891main.go                           Go     180       44    2,510       8     48.2892───────────────────────────────────────────────────────────────────────────────893   complexity × change-frequency, normalised · 20 of 142 files shown894───────────────────────────────────────────────────────────────────────────────895```896897Tabular 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.898899#### Change coupling - `--coupling` / `--coupling-for`900901Which files tend to change together in the same commit I.E. *temporal* coupling.902Surfaces the "if you edit A you probably need to edit B" relationships. `Shared Commits` is how903many commits touched both files; `Coupling` is the share of commits touching *either* file that904touched *both*, so 100% means they never move apart. Pairs are ranked strongest first,905and only pairs sharing at least 2 commits are reported.906907```text908$ scc --coupling909───────────────────────────────────────────────────────────────────────────────910Change Coupling · last 1000 commits · 2019-07-24 → 2026-07-20911───────────────────────────────────────────────────────────────────────────────912File A                      File B                      Shared Commits Coupling913───────────────────────────────────────────────────────────────────────────────914languages.json              processor/constants.go                 196    67.6%915LANGUAGES.md                languages.json                         166    61.3%916LANGUAGES.md                processor/constants.go                 152    58.2%917main.go                     processor/processor.go                  65    33.9%918───────────────────────────────────────────────────────────────────────────────919top 15 of 492 pairs · sharing ≥2 commits920───────────────────────────────────────────────────────────────────────────────921```922923`--coupling-for FILE` narrows to a single file's and what history says tends to move with it.924925```text926$ scc --coupling-for processor/workers.go927───────────────────────────────────────────────────────────────────────────────928Change Coupling · last 1000 commits · 2019-07-24 → 2026-07-20929───────────────────────────────────────────────────────────────────────────────930Related File                                          Shared Commits   Coupling931───────────────────────────────────────────────────────────────────────────────932processor/structs.go                                              27      25.2%933processor/workers_test.go                                         17      17.7%934processor/processor.go                                            34      15.7%935main.go                                                           23      13.7%936───────────────────────────────────────────────────────────────────────────────937```938939#### Author rollup - `--by-author`940941Bus factor and last-toucher attribution. Lines untouched in the window collect under the sentinel `(before window)` so percentages reconcile to 100%.942943```text944$ scc --by-author945───────────────────────────────────────────────────────────────────────────────946Authors · last 500 commits · 2024-01-09 → 2026-05-20947───────────────────────────────────────────────────────────────────────────────948Author                               Code     Cmplx   Files     Owns  Last seen949───────────────────────────────────────────────────────────────────────────────950Alice Smith                         24,110     4,180     118    38.6%  2026-05-22951Bob Jones                           15,447     1,902      74    24.7%  2026-03-14952Carol Lee                            9,205     3,640      51    14.7%  2026-05-19953(before window)                      6,540       810      29    10.4%          -954others (12)                          1,300       190       -     2.1%          -955───────────────────────────────────────────────────────────────────────────────956Bus factor 2 · Alice + Bob last-touched 63% of in-window code957───────────────────────────────────────────────────────────────────────────────958```959960Bus 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%).961962Identity 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.963964#### Author timeline - `--by-author --timeline`965966How 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).967968```text969$ scc --by-author --timeline970───────────────────────────────────────────────────────────────────────────────971Authors · last 500 commits · 2024-01-09 → 2026-05-20972───────────────────────────────────────────────────────────────────────────────973Author                   Activity                  Commits     Code±974───────────────────────────────────────────────────────────────────────────────975Alice Smith              ▂▃▅▇█▇▆▅▄▄▃▃                   210      +38k976Bob Jones                ▇█▆▄▂▁▁▁▁▁▁▁                   142      +21k  quiet 2mo977Carol Lee                ▁▁▁▁▂▃▄▅▆▇██                    96      +14k  ↑978───────────────────────────────────────────────────────────────────────────────979```980981CSV 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.982983#### Languages over time - `--timeline`984985How 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".986987```text988$ scc --timeline989───────────────────────────────────────────────────────────────────────────────990Languages · last 500 commits · 2024-01-09 → 2026-05-20991───────────────────────────────────────────────────────────────────────────────992Language             Trend                             Code    Share     Change993───────────────────────────────────────────────────────────────────────────────994TypeScript           ▁▁▂▃▄▅▆▇████                     36,840    58.0%    +36,840995Go                   ▃▃▄▄▅▅▅▆▆▆▆▆                     24,110    38.0%     +9,205996JavaScript           ██▇▆▅▄▃▂▁▁▁▁                      2,540     4.0%    -18,300997Markdown             ▂▃▃▄▄▅▅▆▆▆▇▇                      1,204     1.9%       +994998───────────────────────────────────────────────────────────────────────────────999```10001001Totals reconcile with a plain `scc` against the current HEAD tree. CSV/JSON include every non-empty language with the full per-bucket series.10021003#### Output format and caveats10041005- 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.1006- `.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`).1007- Merge commits are diffed against their first parent (`git log --first-parent` semantics).1008- 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.1009- `Lines±` is the sum of added and removed lines, so files rewritten in place count twice the displaced size.1010- Symlinks are skipped (v1). Binary detection is unchanged.10111012### HTML Report10131014`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.10151016```text1017$ scc --report                       # writes scc-report.html (prompts before overwriting)1018$ scc --report=docs/code.html        # explicit path; overwrites silently1019```10201021A 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.10221023| Flag | Purpose |1024|---|---|1025| `--report[=path]` | Write the HTML report. Bare flag writes `scc-report.html`; explicit path overwrites silently. |1026| `--report-title NAME` | Override the repo name shown in the report banner. Defaults to the `origin` remote name or the directory basename. |1027| `--report-skip LIST` | Comma-separated sections to omit: `cocomo`, `locomo`, `hotspots`, `coupling`, `authors`, `timeline`, `files`, `uloc`, `linelength`, `card`. |10281029The 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.10301031### Large File Detection10321033You can have `scc` exclude large files from the output.10341035The option to do so is `--no-large` which by default will exclude files over 1,000,000 bytes or 40,000 lines.10361037You can control the size of either value using `--large-byte-count` or `--large-line-count`.10381039For example to exclude files over 1,000 lines and 50kb you could use the following,10401041`scc --no-large --large-byte-count 50000 --large-line-count 1000`10421043### Minified/Generated File Detection10441045You can have `scc` identify and optionally remove files identified as being minified or generated from the output.10461047You 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.10481049Minified files appear like so in the output.10501051```text1052$ scc --no-cocomo -z ./examples/minified/jquery-3.1.1.min.js1053───────────────────────────────────────────────────────────────────────────────1054Language                 Files     Lines   Blanks  Comments     Code Complexity1055───────────────────────────────────────────────────────────────────────────────1056JavaScript (min)             1         4        0         1        3         171057───────────────────────────────────────────────────────────────────────────────1058Total                        1         4        0         1        3         171059───────────────────────────────────────────────────────────────────────────────1060Processed 86709 bytes, 0.087 megabytes (SI)1061───────────────────────────────────────────────────────────────────────────────1062```10631064Minified files are indicated with the text `(min)` after the language name.10651066Generated files are indicated with the text `(gen)` after the language name.10671068You 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.10691070You 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.10711072### Remapping10731074Some 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 the1075correct language. Otherwise, it will not process.10761077However, 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`10781079```bash1080 scc --remap-unknown "-*- C++ -*-":"C Header"1081```10821083The 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.1084You can have multiple remap rules if required,10851086```bash1087 scc --remap-unknown "-*- C++ -*-":"C Header","other":"Java"1088```10891090There is also the `--remap-all` parameter which will remap all files.10911092Note that in all cases if the remap rule does not apply normal #! rules will apply.10931094### Counting files as a custom category10951096Sometimes you want to break out a subset of files into their own reporting category without changing how they are counted.1097A common example is test files such as Ruby specs (`*_spec.rb`) or JavaScript tests (`*.test.js`), which are still Ruby or1098JavaScript but which you would like to see called out separately.10991100The `--count-as-pattern` flag matches files by their path and counts them as a new named category, while borrowing the1101counting rules (comments, strings, complexity) of an existing base language. The format is `[engine:]pattern:name:baselang`.11021103**Patterns are globs by default**, so you usually do not need a prefix:11041105```bash1106 scc --count-as-pattern '*_spec.rb:Ruby Spec:Ruby'1107```11081109The above counts every file whose path matches the glob `*_spec.rb` as a new `Ruby Spec` category, counted using the Ruby1110rules. The original Ruby files are unaffected and remain in the `Ruby` row. Globs support `*` (any characters) and `?`1111(single character) and are matched as a full match against the path.11121113For more control you can opt into a regular expression with the `re:` prefix, which is matched anywhere in the path (use `^`1114and `$` to anchor it yourself). You can also write `glob:` explicitly if you prefer:11151116```bash1117 scc --count-as-pattern 're:\.test\.js$:JavaScript Tests:JavaScript'1118```11191120Glob and regex are kept as separate modes rather than being inferred, because the same pattern can be valid in both with1121different meaning (for example `foo.rb` matches only `foo.rb` as a glob, but also `fooXrb` as a regex), so guessing the engine1122could silently match the wrong files.11231124The flag is repeatable, with the first matching rule winning:11251126```bash1127 scc --count-as-pattern 'glob:*_spec.rb:Ruby Spec:Ruby' --count-as-pattern 'glob:*.test.js:JavaScript Tests:JavaScript'1128```11291130The pattern is matched against the path exactly as supplied to `scc`, with no normalisation, so on Windows you must account1131for the path separators yourself. A rule with an unknown base language, an invalid pattern, or missing fields is reported on1132stderr and skipped.11331134If you want to break a monorepo down by sub-project directory, run `scc` once per directory and combine the results yourself1135using the `csv`, `json`, or `sql` output formats.11361137### Output Formats11381139By default `scc` will output to the console. However, you can produce output in other formats if you require.11401141The different options are `tabular, wide, json, csv, csv-stream, cloc-yaml, html, html-table, sql, sql-insert, openmetrics`.11421143Note that you can write `scc` output to disk using the `-o, --output` option. This allows you to specify a file to1144write your output to. For example `scc -f html -o output.html` will run `scc` against the current directory, and output1145the results in html to the file `output.html`.11461147You can also write to multiple output files, or multiple types to stdout if you want using the `--format-multi` option. This is1148most useful when working in CI/CD systems where you want HTML reports as an artifact while also displaying the counts in stdout.11491150```bash1151scc --format-multi "tabular:stdout,html:output.html,csv:output.csv"1152```11531154The above will run against the current directory, outputting to standard output the default output, as well as writing1155to output.html and output.csv with the appropriate formats.11561157#### Tabular11581159This is the default output format when scc is run.11601161#### Wide11621163Wide produces some additional information which is the complexity/lines metric. This can be useful when trying to1164identify the most complex file inside a project based on the complexity estimate.11651166#### JSON11671168JSON produces JSON output. Mostly designed to allow `scc` to feed into other programs.11691170Note that this format will give you the byte size of every file `scc` reads allowing you to get a breakdown of the1171number of bytes processed.11721173#### CSV11741175CSV as an option is good for importing into a spreadsheet for analysis.11761177Note that this format will give you the byte size of every file `scc` reads allowing you to get a breakdown of the1178number of bytes processed. Also note that CSV respects `--by-file` and as such will return a summary by default.11791180#### CSV-Stream11811182csv-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.11831184Note 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.1185savings that this option provides. Note that there is no sort applied with this option.11861187#### cloc-yaml11881189Is a drop in replacement for cloc using its yaml output option. This is quite often used for passing into other1190build systems and can help with replacing cloc if required.11911192```text1193$ scc -f cloc-yml processor1194# https://github.com/boyter/scc/1195header:1196  url: https://github.com/boyter/scc/1197  version: 2.11.01198  elapsed_seconds: 0.0081199  n_files: 211200  n_lines: 65621201  files_per_second: 26251202  lines_per_second: 8202501203Go:1204  name: Go1205  code: 51861206  comment: 2731207  blank: 11031208  nFiles: 211209SUM:1210  code: 51861211  comment: 2731212  blank: 11031213  nFiles: 2112141215$ cloc --yaml processor1216      21 text files.1217      21 unique files.1218       0 files ignored.12191220---1221# http://cloc.sourceforge.net1222header :1223  cloc_url           : http://cloc.sourceforge.net1224  cloc_version       : 1.601225  elapsed_seconds    : 0.1969728469848631226  n_files            : 211227  n_lines            : 65621228  files_per_second   : 106.6136796084071229  lines_per_second   : 33314.23645668411230Go:1231  nFiles: 211232  blank: 11371233  comment: 6061234  code: 48191235SUM:1236  blank: 11371237  code: 48191238  comment: 6061239  nFiles: 211240```12411242#### HTML and HTML-TABLE12431244The HTML output options produce a minimal html report using a table that is either standalone `html` or as just a table `html-table`1245which can be injected into your own HTML pages. The only difference between the two is that the `html` option includes1246html head and body tags with minimal styling.12471248The markup is designed to allow your own custom styles to be applied. An example report1249[is here to view](SCC-OUTPUT-REPORT.html).12501251Note that the HTML options follow the command line options, so you can use `scc --by-file -f html` to produce a report with every1252file and not just the summary.12531254Note 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 the1255number of bytes processed.12561257#### SQL and SQL-Insert12581259The SQL output format "mostly" compatible with cloc's SQL output format <https://github.com/AlDanial/cloc#sql->12601261While 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 different1262to account for scc including complexity counts and bytes.12631264The difference between `sql` and `sql-insert` is that `sql` will include table creation while the latter will only have the insert commands.12651266Usage 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`.12671268The 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.db12691270```bash1271scc --format sql --sql-project scc . | sqlite3 code.db1272```12731274Assuming you then wanted to append another project12751276```bash1277scc --format sql-insert --sql-project redis . | sqlite3 code.db1278```12791280You could then run SQL against the database,12811282```bash1283sqlite3 code.db 'select project,file,max(nCode) as nL from t1284                         group by project order by nL desc;'1285```12861287See the cloc documentation for more examples.12881289#### OpenMetrics12901291[OpenMetrics](https://openmetrics.io/) is a metric reporting format specification extending the Prometheus exposition text format.12921293The produced output is natively supported by [Prometheus](https://prometheus.io/) and [GitLab CI](https://docs.gitlab.com/ee/ci/testing/metrics_reports.html)12941295Note that OpenMetrics respects `--by-file` and as such will return a summary by default.12961297The output includes a metadata header containing definitions of the returned metrics:12981299```text1300# TYPE scc_files count1301# HELP scc_files Number of sourcecode files.1302# TYPE scc_lines count1303# UNIT scc_lines lines1304# HELP scc_lines Number of lines.1305# TYPE scc_code count1306# HELP scc_code Number of lines of actual code.1307# TYPE scc_comments count1308# HELP scc_comments Number of comments.1309# TYPE scc_blanks count1310# HELP scc_blanks Number of blank lines.1311# TYPE scc_complexity count1312# HELP scc_complexity Code complexity.1313# TYPE scc_bytes count1314# UNIT scc_bytes bytes1315# HELP scc_bytes Size in bytes.1316```13171318The header is followed by the metric data in either language summary form:13191320```text1321scc_files{language="Go"} 11322scc_lines{language="Go"} 10001323scc_code{language="Go"} 10001324scc_comments{language="Go"} 10001325scc_blanks{language="Go"} 10001326scc_complexity{language="Go"} 10001327scc_bytes{language="Go"} 10001328```13291330or, if `--by-file` is present, in per file form:13311332```text1333scc_lines{language="Go",file="./bbbb.go"} 10001334scc_code{language="Go",file="./bbbb.go"} 10001335scc_comments{language="Go",file="./bbbb.go"} 10001336scc_blanks{language="Go",file="./bbbb.go"} 10001337scc_complexity{language="Go",file="./bbbb.go"} 10001338scc_bytes{language="Go",file="./bbbb.go"} 10001339```13401341### Performance13421343Generally `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.13441345However, 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.13461347#### Benchmark Standardization and Work Equivalence13481349When comparing line counters, accounting for work equivalence is necessary for objective performance evaluation (as discussed in [LineBench](https://github.com/loc-conformance/linebench) and issue #769). By default, `scc` performs extensive analysis beyond line counting:1350- Computes cyclomatic and cognitive code complexity across all supported languages.1351- Identifies minified and generated code files.1352- Evaluates multi-language heuristics and shebang classification.1353- Computes COCOMO and LOCOMO cost and effort estimates.13541355In contrast, minimal counters typically measure raw physical lines without complexity calculation or secondary classifications. For apples-to-apples throughput benchmarks ("equal work" runs):1356- Disable complexity analysis with `-c` or `--no-complexity`.1357- Normalize ignore-file handling (standardizing `.gitignore` and hidden file filtering across counters).1358- Align language corpora to evaluate identical file sets and byte volumes.13591360For correctness and differential validation across counter heuristics, see [LineJudge](https://github.com/loc-conformance/linejudge), which verifies counter output against formal dialect rule specifications.13611362Benchmarks are run on fresh 32 Core CPU Optimised Vultr Ocean Virtual Machine 2026/03/05 all done using [hyperfine](https://github.com/sharkdp/hyperfine).13631364See <https://github.com/boyter/scc/blob/master/benchmark.sh> to see how the benchmarks are run.13651366#### Valkey <https://github.com/valkey-io/valkey>13671368```shell1369Benchmark 1: scc valkey1370  Time (mean ± σ):      27.7 ms ±   2.1 ms    [User: 175.7 ms, System: 87.0 ms]1371  Range (min … max):    23.1 ms …  32.1 ms    96 runs1372 1373Benchmark 2: scc -c valkey1374  Time (mean ± σ):      23.0 ms ±   1.5 ms    [User: 131.7 ms, System: 84.0 ms]1375  Range (min … max):    19.5 ms …  31.4 ms    130 runs1376 1377Benchmark 3: tokei valkey1378  Time (mean ± σ):      74.0 ms ±  13.0 ms    [User: 394.2 ms, System: 245.1 ms]1379  Range (min … max):    49.1 ms …  92.5 ms    37 runs1380 1381Benchmark 4: polyglot valkey1382  Time (mean ± σ):      41.1 ms ±   1.2 ms    [User: 54.2 ms, System: 103.3 ms]1383  Range (min … max):    37.5 ms …  47.0 ms    69 runs1384 1385Summary1386  scc -c valkey ran1387    1.20 ± 0.12 times faster than scc valkey1388    1.78 ± 0.13 times faster than polyglot valkey1389    3.21 ± 0.61 times faster than tokei valkey1390```13911392#### CPython <https://github.com/python/cpython>13931394```shell1395Benchmark 1: scc cpython1396  Time (mean ± σ):      80.8 ms ±   2.6 ms    [User: 751.1 ms, System: 265.6 ms]1397  Range (min … max):    75.7 ms …  87.4 ms    36 runs1398 1399Benchmark 2: scc -c cpython1400  Time (mean ± σ):      70.5 ms ±   2.4 ms    [User: 592.6 ms, System: 254.7 ms]1401  Range (min … max):    66.2 ms …  77.6 ms    40 runs1402 1403Benchmark 3: tokei cpython1404  Time (mean ± σ):     450.2 ms ±  36.1 ms    [User: 1822.0 ms, System: 1246.9 ms]1405  Range (min … max):   378.6 ms … 491.2 ms    10 runs1406 1407Benchmark 4: polyglot cpython1408  Time (mean ± σ):     149.9 ms ±   5.8 ms    [User: 199.2 ms, System: 326.2 ms]1409  Range (min … max):   138.3 ms … 164.1 ms    19 runs1410 1411Summary1412  scc -c cpython ran1413    1.15 ± 0.05 times faster than scc cpython1414    2.13 ± 0.11 times faster than polyglot cpython1415    6.39 ± 0.56 times faster than tokei cpython1416```14171418#### Linux Kernel <https://github.com/torvalds/linux>14191420```shell1421Benchmark 1: scc linux1422  Time (mean ± σ):     907.2 ms ±  17.1 ms    [User: 13764.7 ms, System: 2957.0 ms]1423  Range (min … max):   878.2 ms … 925.0 ms    10 runs1424 1425Benchmark 2: scc -c linux1426  Time (mean ± σ):     842.5 ms ±  17.2 ms    [User: 9363.3 ms, System: 2977.0 ms]1427  Range (min … max):   819.4 ms … 874.0 ms    10 runs1428 1429Benchmark 3: tokei linux1430  Time (mean ± σ):      1.422 s ±  0.089 s    [User: 13.292 s, System: 9.582 s]1431  Range (min … max):    1.176 s …  1.471 s    10 runs1432 1433Benchmark 4: polyglot linux1434  Time (mean ± σ):      1.862 s ±  0.046 s    [User: 3.802 s, System: 3.543 s]1435  Range (min … max):    1.800 s …  1.935 s    10 runs1436 1437Summary1438  scc -c linux ran1439    1.08 ± 0.03 times faster than scc linux1440    1.69 ± 0.11 times faster than tokei linux1441    2.21 ± 0.07 times faster than polyglot linux1442```14431444#### Sourcegraph <https://github.com/SINTEF/sourcegraph.git>14451446Sourcegraph has gone dark since I last ran these benchmarks hence using a clone taken before this occurred.1447The reason for this is to track what appears to be a performance regression in tokei.14481449```shell1450Benchmark 1: scc sourcegraph1451  Time (mean ± σ):     108.2 ms ±   3.5 ms    [User: 559.4 ms, System: 323.6 ms]1452  Range (min … max):   100.5 ms … 115.9 ms    26 runs1453 1454Benchmark 2: scc -c sourcegraph1455  Time (mean ± σ):      99.7 ms ±   4.2 ms    [User: 503.1 ms, System: 316.8 ms]1456  Range (min … max):    91.4 ms … 109.4 ms    29 runs1457 1458Benchmark 3: tokei sourcegraph1459  Time (mean ± σ):     21.359 s ±  1.025 s    [User: 57.252 s, System: 411.480 s]1460  Range (min … max):   19.371 s … 22.741 s    10 runs1461 1462Benchmark 4: polyglot sourcegraph1463  Time (mean ± σ):     135.1 ms ±   5.0 ms    [User: 198.6 ms, System: 543.7 ms]1464  Range (min … max):   126.0 ms … 144.8 ms    21 runs1465 1466Summary1467  scc -c sourcegraph ran1468    1.08 ± 0.06 times faster than scc sourcegraph1469    1.36 ± 0.08 times faster than polyglot sourcegraph1470  214.26 ± 13.64 times faster than tokei sourcegraph1471```14721473If you enable duplicate detection expect performance to fall by about 20% in `scc`.14741475Performance is tracked for some releases and presented below.14761477[![scc performance on Linux kernel](./performance-over-time.png)]1478The decrease in performance from the 3.3.0 release was due to accurate .gitignore, .ignore and .gitmodule support.1479Current work is focussed on resolving this.14801481### CI/CD Support14821483Some 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.14841485```text1486$ scc --ci main.go1487-------------------------------------------------------------------------------1488Language                 Files     Lines   Blanks  Comments     Code Complexity1489-------------------------------------------------------------------------------1490Go                           1       272        7         6      259          41491-------------------------------------------------------------------------------1492Total                        1       272        7         6      259          41493-------------------------------------------------------------------------------1494Estimated Cost to Develop $6,5391495Estimated Schedule Effort 2.268839 months1496Estimated People Required 0.3414371497-------------------------------------------------------------------------------1498Processed 5674 bytes, 0.006 megabytes (SI)1499-------------------------------------------------------------------------------1500```15011502The `--format-multi` option is especially useful in CI/CD where you want to get multiple output formats useful for storage or reporting.15031504### Development15051506If 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.15071508For 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.15091510### API Support15111512The 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.15131514It 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.15151516However as a quick start consider the following,15171518Note that you must pass in the number of bytes in the content in order to ensure it is counted!15191520```go1521package main15221523import (1524  "fmt"1525  "io/ioutil"15261527  "github.com/boyter/scc/v4/processor"1528)15291530type statsProcessor struct{}15311532func (p *statsProcessor) ProcessLine(job *processor.FileJob, currentLine int64, lineType processor.LineType) bool {1533  switch lineType {1534  case processor.LINE_BLANK:1535    fmt.Println(currentLine, "lineType", "BLANK")1536  case processor.LINE_CODE:1537    fmt.Println(currentLine, "lineType", "CODE")1538  case processor.LINE_COMMENT:1539    fmt.Println(currentLine, "lineType", "COMMENT")1540  }1541  return true1542}15431544func main() {1545  bts, _ := ioutil.ReadFile("somefile.go")  1546  t := &statsProcessor{}1547  filejob := &processor.FileJob{1548    Filename: "test.go",1549    Language: "Go",1550    Content:  bts,1551    Callback: t,1552    Bytes:    int64(len(bts)),1553  }  1554  processor.ProcessConstants() // Required to load the language information and need only be done once1555  processor.CountStats(filejob)1556}1557```15581559#### Per-Byte Content Classification15601561For 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.15621563To enable it, set `ClassifyContent: true` on the `FileJob` before calling `CountStats`. When disabled (the default), there is zero performance impact.15641565```go1566package main15671568import (1569  "fmt"1570  "os"15711572  "github.com/boyter/scc/v4/processor"1573)15741575func main() {1576  processor.ProcessConstants()15771578  bts, _ := os.ReadFile("main.go")1579  filejob := &processor.FileJob{1580    Filename:        "main.go",1581    Language:        "Go",1582    Content:         bts,1583    Bytes:           int64(len(bts)),1584    ClassifyContent: true, // Enable per-byte classification1585  }1586  processor.CountStats(filejob)15871588  // ContentByteType has one entry per byte with values:1589  //   processor.ByteTypeBlank   (0) - blank lines / leading whitespace1590  //   processor.ByteTypeCode    (1) - code1591  //   processor.ByteTypeComment (2) - comments (including docstrings)1592  //   processor.ByteTypeString  (3) - string literals15931594  // Example: extract only code, replacing everything else with spaces1595  codeOnly := filejob.FilterContentByType(processor.ByteTypeCode)1596  fmt.Println(string(codeOnly))15971598  // Example: extract only comments1599  commentsOnly := filejob.FilterContentByType(processor.ByteTypeComment)1600  fmt.Println(string(commentsOnly))16011602  // Example: keep both code and strings, strip comments1603  noComments := filejob.FilterContentByType(processor.ByteTypeCode, processor.ByteTypeString)1604  fmt.Println(string(noComments))1605}1606```16071608`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.16091610Note 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.16111612### MCP Server Mode16131614`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.16151616```shell1617scc --mcp1618```16191620#### Claude Code Configuration16211622Run in your terminal for the current project:16231624```shell1625claude mcp add scc -- scc --mcp1626```16271628Or globally for all projects:16291630```shell1631claude mcp add scc --scope user -- scc --mcp1632```16331634Alternatively, add to your `.mcp.json`:16351636```json1637{1638  "mcpServers": {1639    "scc": {1640      "command": "scc",1641      "args": ["--mcp"]1642    }1643  }1644}1645```16461647#### Claude Desktop Configuration16481649Add to your `claude_desktop_config.json`:16501651```json1652{1653  "mcpServers": {1654    "scc": {1655      "command": "/path/to/scc",1656      "args": ["--mcp"]1657    }1658  }1659}1660```16611662#### Exposed Tools16631664The MCP server exposes three tools:16651666**`analyze`** - Count lines of code, comments, blanks and estimate complexity for a project directory or file.16671668| Parameter | Type | Required | Description |1669|---|---|---|---|1670| `path` | string | no | Directory or file path to analyze. Defaults to current directory. |1671| `sort` | string | no | Column to sort by: `files`, `name`, `lines`, `blanks`, `code`, `comments`, `complexity`, `bytes`. Default: `files`. |1672| `by_file` | boolean | no | If true, return per-file results instead of per-language summary. |1673| `limit` | number | no | Maximum number of files to return per language when `by_file` is true. Default: `10`. Set to `-1` for unlimited. |1674| `include_ext` | string | no | Comma-separated file extensions to include (e.g. `go,java,js`). |1675| `exclude_ext` | string | no | Comma-separated file extensions to exclude (e.g. `json,xml`). |1676| `no_duplicates` | boolean | no | Remove duplicate files from stats. |1677| `no_min_gen` | boolean | no | Ignore minified or generated files. |1678| `cognitive` | boolean | no | Also compute nesting-weighted cognitive complexity. Off by default, in which case the `cognitive` field is `0`. |1679| `locomo` | boolean | no | Include LOCOMO (LLM cost) estimation in results. |1680| `locomo_preset` | string | no | LOCOMO model preset: `large`, `medium`, `small`, `local`. Default: `medium`. |16811682Results are returned as JSON with per-language breakdown (files, lines, code, comments, blanks, complexity, cognitive, bytes), totals, and COCOMO cost/schedule estimates. When `locomo` is enabled, LOCOMO estimates (token counts, cost, generation time, review hours) are also included.16831684**`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.16851686| Parameter | Type | Required | Description |1687|---|---|---|---|1688| `path` | string | no | Directory inside the git repository to analyze. Defaults to current directory. |1689| `depth` | number | no | Maximum number of recent commits to walk. Default: `1000`. Set to `0` for unlimited. |1690| `limit` | number | no | Maximum number of files to return, highest-scoring first. Default: `50`. Set to `-1` for unlimited. |16911692Results 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.16931694**`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.16951696| Parameter | Type | Required | Description |1697|---|---|---|---|1698| `path` | string | no | Directory inside the git repository to analyze. Defaults to current directory. |1699| `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. |1700| `depth` | number | no | Maximum number of recent commits to walk. Default: `1000`. Set to `0` for unlimited. |1701| `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. |17021703Results 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.17041705### Adding/Modifying Languages17061707To 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.17081709### Issues17101711Its 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.17121713- <https://superuser.com/questions/261023/how-to-change-default-ulimit-values-in-mac-os-x-10-6#306555>1714- <https://unix.stackexchange.com/questions/108174/how-to-persistently-control-maximum-system-resource-consumption-on-mac/221988#221988>1715- <https://access.redhat.com/solutions/61334>1716- <https://serverfault.com/questions/356962/where-are-the-default-ulimit-values-set-linux-centos>1717- <https://www.tecmint.com/increase-set-open-file-limits-in-linux/>17181719To 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.17201721### Low Memory17221723If 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.17241725A sign that this is required will be `scc` crashing with panic errors.17261727### Tests17281729scc is pretty well tested with many unit, integration and benchmarks to ensure that it is fast and complete.17301731### Package17321733Packaging as of version v3.1.0 is done through <https://goreleaser.com/>17341735### Containers17361737Note if you plan to run `scc` in Alpine containers you will need to build with CGO_ENABLED=0.17381739See the below Dockerfile as an example on how to achieve this based on this issue <https://github.com/boyter/scc/issues/208>17401741```Dockerfile1742FROM golang as scc-get17431744ENV GOOS=linux \1745GOARCH=amd64 \1746CGO_ENABLED=017471748ARG VERSION1749RUN git clone --branch $VERSION --depth 1 https://github.com/boyter/scc1750WORKDIR /go/scc1751RUN go build -ldflags="-s -w"17521753FROM alpine1754COPY --from=scc-get /go/scc/scc /bin/1755ENTRYPOINT ["scc"]1756```17571758### Badges17591760You 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/)1761 The format to do so is,17621763<https://sloc.xyz/PROVIDER/USER/REPO>17641765An example of the badge for `scc` is included below, and is used on this page.17661767```Markdown1768[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/)](https://github.com/boyter/scc/)1769```17701771By 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.17721773Valid values include `code, blanks, lines, comments, cocomo, effort` and examples of the appearance are included below.17741775[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=code)](https://github.com/boyter/scc/)1776[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=blanks)](https://github.com/boyter/scc/)1777[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=lines)](https://github.com/boyter/scc/)1778[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=comments)](https://github.com/boyter/scc/)1779[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=cocomo)](https://github.com/boyter/scc/)1780[![Scc Count Badge](https://sloc.xyz/github/boyter/scc/?category=effort)](https://github.com/boyter/scc/)17811782For `cocomo` you can also set the `avg-wage` value similar to `scc` itself. For example,17831784<https://sloc.xyz/github/boyter/scc/?category=cocomo&avg-wage=1>1785<https://sloc.xyz/github/boyter/scc/?category=cocomo&avg-wage=100000>17861787Note that the avg-wage value must be a positive integer otherwise it will revert back to the default value of 56286.17881789You can also configure the look and feel of the badge using the following parameters,17901791- ?lower=true will lower the title text, so "Total lines" would be "total lines"17921793The 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):17941795- ?font-color=fff1796- ?font-shadow-color=0101011797- ?top-shadow-accent-color=bbb1798- ?title-bg-color=5551799- ?badge-bg-color=4c118001801##### Named Colors18021803For convenience, you can use named colors instead of hex codes. The following named colors are supported:18041805**Shields.io colors:** `brightgreen`, `green`, `yellowgreen`, `yellow`, `orange`, `red`, `blue`, `lightgrey`, `blueviolet`18061807**Semantic aliases:** `success`, `important`, `critical`, `informational`, `inactive`18081809**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.18101811For example, instead of `?badge-bg-color=007ec6` you can use `?badge-bg-color=blue`.18121813An example of using some of these parameters to produce an admittedly ugly result18141815[![Scc Count Badge](https://sloc.xyz/github/boyter/scc?font-color=ff0000&badge-bg-color=0000ff&lower=true)](https://github.com/boyter/scc/)18161817An example using named colors for as a slightly nicer result18181819[![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/)18201821*NB* it may not work for VERY large repositories (has been tested on Apache hadoop/spark without issue).18221823You can find the source code for badges in the repository at <https://github.com/boyter/scc/blob/master/cmd/badges/main.go>18241825#### A example for each supported provider18261827- Github - <https://sloc.xyz/github/boyter/scc/>1828- sr.ht - <https://sloc.xyz/sr.ht/~nektro/magnolia-desktop/>1829- Bitbucket - <https://sloc.xyz/bitbucket/boyter/decodingcaptchas>1830- Gitlab - <https://sloc.xyz/gitlab/esr/loccount>1831- Codeberg - <https://sloc.xyz/codeberg/NextBroomTeam/NextBroom>18321833### Languages18341835List 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`18361837[Click here to view all languages supported by master](LANGUAGES.md)18381839### Citation18401841Please use the following Bib**La**TeX entry to cite scc in a publication:18421843```bib1844@Software{scc,1845 author     = {Ben Boyter and {Contributors}},1846 title      = {scc},1847 version    = {vx.y.z},1848 year       = {...},1849 month      = {...},1850 repository = {https://github.com/boyter/scc},1851}1852```18531854You 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.18551856### Release Checklist18571858- Update version1859- Push code with release number1860- Tag off1861- Release via goreleaser1862- Update dockerfile

Findings

✓ No findings reported for this file.

Get this view in your editor

Same data, no extra tab — call code_get_file + code_get_findings over MCP from Claude/Cursor/Copilot.

Generated by searchcode.com · powered by code_get_file + code_get_findings