The moving parts
By the end of this chapter you can name the four jobs tokei does between "here is a folder" and the table it prints, and say which job each later surprise belongs to.
The walker
First, tokei walks. Starting from the folder (or folders) you name, it recurses through the tree collecting candidate files — and not collecting others. Three filters act here, before any counting:
- Hidden files — names starting
with a dot are skipped, unless you
pass
--hidden. - Ignore files —
.gitignore,.ignoreand.tokeignorefiles are respected, with the fine print chapter 8 demonstrates: a.gitignoreonly takes effect inside a real git repository. - Exclusions — patterns you pass
with
-eare left out.
The walker works in parallel, which is most of why tokei is fast. Chapter 8 changes each filter and watches the totals move.
The detector
Each surviving file is assigned a language, or none. The detector does not read your code the way a compiler does; it asks three quick questions, in order of cheapness:
- What is the file called? A few
names are languages in themselves —
MakefileandDockerfileare the specimens in chapter 5. - What extension does it carry?
.pysays Python,.rssays Rust, and so on, through a built-in table covering 334 languages (chapter 10 counts them). - What does its first line say?
A file with no useful name at all
can still be claimed by its
shebang — the
#!/bin/shline that tells the system how to run it.
A file none of the witnesses claim is
skipped, quietly. Chapter 5 shows
one, and shows the -v flag that
makes tokei admit it.
The counter
For each claimed file, a small state
machine for that language reads the
file line by line, keeping track of
whether it is inside a string, inside
a block comment, or in plain code,
and sorts every line into code,
comment or blank by the language's
rules. Chapter 6 is this machine's
rulebook, taught on specimens: why a
/* inside a string starts no
comment, why a line holding code
and a comment counts as code, and
why the empty line inside a long
string is not blank.
Some files contain a second language inside the first — a web page with style rules and a script in it, a Markdown file with a fenced code block. The counter splits those out as embedded languages, reported as children of the host language. Chapter 7 takes three such files apart.
The reporter
Last, the counts are added up and
printed: the table this guide reads
in chapter 4, per-file detail with
--files, machine-readable JSON and
a one-line-per-file stream for other
programs (chapter 9). The reporter
is also where configuration —
chapter 10's tokei.toml — quietly
changes what the counter was asked
to do, which is why two runs over
the same folder can disagree.
Check: name the four jobs in order, and one filter, one witness and one rule from the middle two. If you can, you have this chapter.