rloc 0.1.0

A fast, modern Rust implementation of cloc (Count Lines of Code)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
use crate::output::{OutputConfig, OutputFormat, SortBy};
use crate::walker::{VcsMode, WalkerConfig};
use clap::{Parser, ValueEnum};
use regex::Regex;
use std::path::PathBuf;

#[derive(Parser, Debug)]
#[command(
    name = "rloc",
    author,
    version,
    about = "A fast, modern Rust implementation of cloc (Count Lines of Code)",
    long_about = "rloc counts lines of code, comments, and blanks in source files.\n\n\
                  It automatically detects programming languages by file extension\n\
                  and uses language-specific comment syntax for accurate counting."
)]
pub struct Cli {
    #[arg(
        value_name = "PATH",
        help = "Files or directories to analyze",
        default_value = "."
    )]
    pub paths: Vec<PathBuf>,

    #[arg(
        long,
        value_name = "PATH",
        help = "Compare against another set of files/directories"
    )]
    pub diff: Option<PathBuf>,

    #[arg(long, help = "Report results for every source file")]
    pub by_file: bool,

    #[arg(long, help = "Report by file and by language")]
    pub by_file_by_lang: bool,

    #[arg(long, value_enum, help = "Output format")]
    pub format: Option<Format>,

    #[arg(long, help = "Write results as JSON")]
    pub json: bool,

    #[arg(long, help = "Write results as CSV")]
    pub csv: bool,

    #[arg(
        long,
        value_name = "C",
        help = "Use character <C> as CSV delimiter (default: ',')"
    )]
    pub csv_delimiter: Option<char>,

    #[arg(long, help = "Write results as YAML")]
    pub yaml: bool,

    #[arg(long, help = "Write results as Markdown")]
    pub md: bool,

    #[arg(long, help = "Write results as SQL CREATE and INSERT statements")]
    pub sql: bool,

    #[arg(long, help = "Write results as XML")]
    pub xml: bool,

    #[arg(
        long,
        value_name = "DIR",
        help = "Exclude directories matching these names"
    )]
    pub exclude_dir: Vec<String>,

    #[arg(long, value_name = "EXT", help = "Exclude files with these extensions")]
    pub exclude_ext: Vec<String>,

    #[arg(long, value_name = "LANG", help = "Exclude these languages")]
    pub exclude_lang: Vec<String>,

    #[arg(
        long,
        value_name = "EXT",
        help = "Only count files with these extensions"
    )]
    pub include_ext: Vec<String>,

    #[arg(long, value_name = "LANG", help = "Only count these languages")]
    pub include_lang: Vec<String>,

    #[arg(
        long,
        value_name = "LANG,EXT",
        help = "Treat files with extension EXT as language LANG (e.g. Rust,txt)"
    )]
    pub force_lang: Vec<String>,

    #[arg(
        long,
        value_name = "REGEX",
        help = "Only count files in directories matching regex"
    )]
    pub match_d: Option<String>,

    #[arg(
        long,
        value_name = "REGEX",
        help = "Exclude directories matching regex"
    )]
    pub not_match_d: Vec<String>,

    #[arg(long, value_name = "REGEX", help = "Only count files matching regex")]
    pub match_f: Option<String>,

    #[arg(long, value_name = "REGEX", help = "Exclude files matching regex")]
    pub not_match_f: Vec<String>,

    #[arg(
        long,
        value_name = "REGEX",
        help = "Only count files containing content matching regex"
    )]
    pub include_content: Option<String>,

    #[arg(
        long,
        value_name = "REGEX",
        help = "Exclude files containing content matching regex"
    )]
    pub exclude_content: Option<String>,

    #[arg(long, help = "Use full path in regex matching")]
    pub fullpath: bool,

    #[arg(long, value_enum, help = "Use version control to find files")]
    pub vcs: Option<Vcs>,

    #[arg(long, help = "Synonym for --vcs")]
    pub files_from: Option<Vcs>,

    #[arg(long, help = "Follow symbolic links")]
    pub follow_symlinks: bool,

    #[arg(long, help = "Process archive files (zip, tar, tar.gz)")]
    pub extract_archives: bool,

    #[arg(long, help = "Include hidden files and directories")]
    pub hidden: bool,

    #[arg(
        long,
        help = "Disable default directory exclusions (node_modules, target, etc.)"
    )]
    pub no_ignore: bool,

    #[arg(long, help = "Don't respect .gitignore files")]
    pub skip_gitignore: bool,

    #[arg(
        long,
        help = "Skip file uniqueness check (count duplicate files multiple times)"
    )]
    pub skip_uniqueness: bool,

    #[arg(long, help = "Include files in git submodules (requires Git 2.11+)")]
    pub include_submodules: bool,

    #[arg(
        long,
        value_name = "FILE",
        help = "Read file paths from FILE (one per line)"
    )]
    pub list_file: Option<PathBuf>,

    #[arg(long, value_name = "N", help = "Maximum directory depth")]
    pub max_depth: Option<usize>,

    #[arg(long, help = "Do not recurse into subdirectories")]
    pub no_recurse: bool,

    #[arg(
        long,
        value_name = "MB",
        help = "Skip files larger than <MB> megabytes"
    )]
    pub max_file_size: Option<u64>,

    #[arg(long, value_enum, default_value = "code", help = "Sort output by")]
    pub sort: SortField,

    #[arg(
        long,
        value_name = "N",
        help = "Aggregate languages with fewer than N files into 'Other'"
    )]
    pub summary_cutoff: Option<usize>,

    #[arg(long, help = "Do not show rate statistics")]
    pub hide_rate: bool,

    #[arg(long, help = "Show counts as percentages of column totals")]
    pub by_percent: bool,

    #[arg(long, help = "Suppress progress output")]
    pub quiet: bool,

    #[arg(short, long, action = clap::ArgAction::Count, help = "Verbose output")]
    pub verbose: u8,

    #[arg(long, value_name = "FILE", help = "Write output to file")]
    pub out: Option<PathBuf>,

    #[arg(
        long,
        alias = "report-file",
        value_name = "FILE",
        help = "Write output to file"
    )]
    pub report_file: Option<PathBuf>,

    #[arg(long, help = "Show an extra column with total lines")]
    pub show_total: bool,

    #[arg(long, help = "Print all known languages and exit")]
    pub show_lang: bool,

    #[arg(long, help = "Print all known file extensions and exit")]
    pub show_ext: bool,

    #[arg(
        long,
        value_name = "FILE",
        help = "Load custom language definitions from YAML file"
    )]
    pub read_lang_def: Option<PathBuf>,

    #[arg(
        long,
        value_name = "EXT",
        help = "Write files with comments removed (output to <file>.<EXT>)"
    )]
    pub strip_comments: Option<String>,

    #[arg(
        long,
        value_name = "EXT",
        help = "Write files with code removed, keeping only comments (output to <file>.<EXT>)"
    )]
    pub strip_code: Option<String>,

    #[arg(
        long,
        value_name = "FILE",
        help = "Read and sum JSON reports from files"
    )]
    pub sum_reports: Vec<PathBuf>,

    #[arg(
        long,
        value_name = "N",
        default_value = "0",
        help = "Number of threads (0 = auto)"
    )]
    pub threads: usize,
}

#[derive(ValueEnum, Clone, Debug, Copy)]
pub enum Format {
    Table,
    Json,
    Csv,
    Yaml,
    Md,
    Sql,
    Xml,
}

#[derive(ValueEnum, Clone, Debug, Copy)]
pub enum Vcs {
    Auto,
    Git,
    None,
}

#[derive(ValueEnum, Clone, Debug, Copy)]
pub enum SortField {
    Language,
    Files,
    Code,
    Comments,
    Blanks,
    Total,
}

impl Cli {
    pub fn to_walker_config(&self) -> Result<WalkerConfig, String> {
        let mut config = WalkerConfig::default();

        if !self.paths.is_empty() {
            config.paths = self.paths.clone();
        }

        config.list_file = self.list_file.clone();

        if self.no_ignore {
            config.exclude_dirs.clear();
        }

        config.exclude_dirs.extend(self.exclude_dir.iter().cloned());
        config.exclude_exts.extend(self.exclude_ext.iter().cloned());
        config
            .exclude_langs
            .extend(self.exclude_lang.iter().cloned());
        config.include_exts.extend(self.include_ext.iter().cloned());
        config
            .include_langs
            .extend(self.include_lang.iter().cloned());

        for spec in &self.force_lang {
            if let Some((lang, ext)) = spec.split_once(',') {
                config
                    .force_lang
                    .insert(ext.to_lowercase(), lang.to_string());
            } else {
                return Err(format!(
                    "Invalid --force-lang format '{}', expected LANG,EXT",
                    spec
                ));
            }
        }

        if let Some(ref pattern) = self.match_d {
            config.match_dir =
                Some(Regex::new(pattern).map_err(|e| format!("Invalid --match-d regex: {}", e))?);
        }

        for pattern in &self.not_match_d {
            config.not_match_dir.push(
                Regex::new(pattern).map_err(|e| format!("Invalid --not-match-d regex: {}", e))?,
            );
        }

        if let Some(ref pattern) = self.match_f {
            config.match_file =
                Some(Regex::new(pattern).map_err(|e| format!("Invalid --match-f regex: {}", e))?);
        }

        for pattern in &self.not_match_f {
            config.not_match_file.push(
                Regex::new(pattern).map_err(|e| format!("Invalid --not-match-f regex: {}", e))?,
            );
        }

        if let Some(ref pattern) = self.include_content {
            config.include_content = Some(
                Regex::new(pattern)
                    .map_err(|e| format!("Invalid --include-content regex: {}", e))?,
            );
        }

        if let Some(ref pattern) = self.exclude_content {
            config.exclude_content = Some(
                Regex::new(pattern)
                    .map_err(|e| format!("Invalid --exclude-content regex: {}", e))?,
            );
        }

        config.vcs = self.vcs.or(self.files_from).map(|v| match v {
            Vcs::Auto => VcsMode::Auto,
            Vcs::Git => VcsMode::Git,
            Vcs::None => VcsMode::None,
        });

        config.follow_symlinks = self.follow_symlinks;
        config.hidden = self.hidden;
        config.fullpath = self.fullpath;
        config.max_depth = if self.no_recurse {
            Some(1)
        } else {
            self.max_depth
        };
        config.skip_gitignore = self.skip_gitignore;
        config.skip_uniqueness = self.skip_uniqueness;
        config.include_submodules = self.include_submodules;
        config.max_file_size = self.max_file_size;

        Ok(config)
    }

    pub fn to_output_config(&self) -> OutputConfig {
        let format = if self.json {
            OutputFormat::Json
        } else if self.csv {
            OutputFormat::Csv
        } else if self.yaml {
            OutputFormat::Yaml
        } else if self.md {
            OutputFormat::Markdown
        } else if self.sql {
            OutputFormat::Sql
        } else if self.xml {
            OutputFormat::Xml
        } else {
            match self.format {
                Some(Format::Json) => OutputFormat::Json,
                Some(Format::Csv) => OutputFormat::Csv,
                Some(Format::Yaml) => OutputFormat::Yaml,
                Some(Format::Md) => OutputFormat::Markdown,
                Some(Format::Sql) => OutputFormat::Sql,
                Some(Format::Xml) => OutputFormat::Xml,
                Some(Format::Table) | None => OutputFormat::Table,
            }
        };

        let sort_by = match self.sort {
            SortField::Language => SortBy::Language,
            SortField::Files => SortBy::Files,
            SortField::Code => SortBy::Code,
            SortField::Comments => SortBy::Comments,
            SortField::Blanks => SortBy::Blanks,
            SortField::Total => SortBy::Total,
        };

        OutputConfig {
            format,
            by_file: self.by_file,
            by_file_by_lang: self.by_file_by_lang,
            hide_rate: self.hide_rate,
            sort_by,
            show_total_column: self.show_total,
            csv_delimiter: self.csv_delimiter.map(|c| c as u8).unwrap_or(b','),
            by_percent: self.by_percent,
            summary_cutoff: self.summary_cutoff,
        }
    }

    pub fn output_path(&self) -> Option<&PathBuf> {
        self.out.as_ref().or(self.report_file.as_ref())
    }
}

pub fn show_languages() {
    use crate::languages::list_languages;
    use comfy_table::{presets::UTF8_FULL_CONDENSED, Table};

    let mut table = Table::new();
    table.load_preset(UTF8_FULL_CONDENSED);
    table.set_header([
        "Language",
        "Line Comments",
        "Block Start",
        "Block End",
        "Nested",
    ]);

    let mut langs: Vec<_> = list_languages().collect();
    langs.sort_by_key(|(name, _)| *name);

    for (name, lang) in langs {
        table.add_row([
            name,
            &lang.line_comments.join(", "),
            lang.block_comment_start.unwrap_or("-"),
            lang.block_comment_end.unwrap_or("-"),
            if lang.nested_comments { "yes" } else { "no" },
        ]);
    }

    println!("{}", table);
}

pub fn show_extensions() {
    use crate::languages::list_extensions;
    use comfy_table::{presets::UTF8_FULL_CONDENSED, Table};

    let mut table = Table::new();
    table.load_preset(UTF8_FULL_CONDENSED);
    table.set_header(["Extension", "Language"]);

    let mut exts: Vec<_> = list_extensions().collect();
    exts.sort_by_key(|(ext, _)| *ext);

    for (ext, lang) in exts {
        table.add_row([ext, lang]);
    }

    println!("{}", table);
}