gobject-linter 0.1.2

A fast tree-sitter-based linter for GObject/C 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
use std::{
    collections::{HashMap, HashSet},
    io::{IsTerminal, Read},
    path::PathBuf,
};

use anyhow::{Context, Result};
use clap::Parser;
use colored::Colorize;
use gobject_linter::{
    ast_context,
    config::{self, OutputFormat},
    fixer,
    meson::MesonIntrospection,
    output, reporter,
    rules::Category,
    scanner,
};
use indicatif::{ProgressBar, ProgressStyle};
use unidiff::PatchSet;

#[derive(Parser, Debug)]
#[command(name = "gobject-linter")]
#[command(about = "A fast tree-sitter-based linter for GObject/C code", long_about = None)]
struct Args {
    /// Directory to scan for C files
    #[arg(value_name = "DIRECTORY", default_value = ".")]
    directory: PathBuf,

    /// Path to configuration file
    #[arg(short, long, value_name = "FILE", default_value = concat!(env!("CARGO_PKG_NAME"), ".toml"))]
    config: PathBuf,

    /// Ignore files matching glob patterns (e.g., "tests/**", "vendor/**")
    #[arg(short, long, value_name = "PATTERN")]
    ignore: Vec<String>,

    /// Show verbose output
    #[arg(short, long)]
    verbose: bool,

    /// List all available lint rules
    #[arg(long)]
    list_rules: bool,

    /// Enable only specific rules (can be repeated, overrides config)
    #[arg(long, value_name = "RULE")]
    only: Vec<String>,

    /// Disable specific rules (can be repeated, overrides config)
    #[arg(long, value_name = "RULE")]
    exclude: Vec<String>,

    /// Enable only rules from this category (e.g., correctness, style, perf)
    #[arg(long, value_name = "CATEGORY")]
    category: Option<Category>,

    /// Output format
    #[arg(long, value_enum)]
    format: Option<OutputFormat>,

    /// Automatically apply fixes for violations
    #[arg(long)]
    fix: bool,

    /// Print a summary table of violation counts grouped by rule
    #[arg(long)]
    summary: bool,

    /// Set minimum GLib version (e.g., "2.76") - disables rules requiring newer
    /// versions
    #[arg(long, value_name = "VERSION", value_parser = parse_glib_version_arg)]
    min_glib_version: Option<(u32, u32)>,

    /// Target MSVC-compatible code (disables g_auto* rules, enables
    /// no_g_auto_macros)
    #[arg(long)]
    msvc_compatible: bool,

    /// Only report violations on lines changed in this unified diff (use `-`
    /// to read from stdin). Useful for CI to report only on PR changes.
    #[arg(long, value_name = "FILE")]
    diff: Option<PathBuf>,
}

/// Parse GLib version string for clap
fn parse_glib_version_arg(s: &str) -> Result<(u32, u32), String> {
    config::parse_glib_version(s).ok_or_else(|| {
        format!(
            "Invalid GLib version format: '{}'. Expected format: 'major.minor' (e.g., '2.76')",
            s
        )
    })
}

fn main() -> Result<()> {
    let args = Args::parse();

    // Initialize tracing
    tracing_subscriber::fmt()
        .with_env_filter(tracing_subscriber::EnvFilter::from_default_env())
        .with_target(true)
        .with_line_number(true)
        .init();

    // Load configuration
    let default_config = std::path::Path::new("gobject-linter.toml");
    let is_explicit = args.config != default_config;
    let config_path = if !args.config.exists() && !is_explicit {
        let legacy = std::path::Path::new("goblint.toml");
        if legacy.exists() {
            legacy.to_path_buf()
        } else {
            args.config.clone()
        }
    } else {
        args.config.clone()
    };
    if is_explicit && !config_path.exists() {
        eprintln!(
            "{} config file not found: {}",
            "error:".red().bold(),
            config_path.display()
        );
        std::process::exit(1);
    }
    let mut config = config::Config::load(&config_path)?;

    let format = args.format.or(config.format).unwrap_or_default();

    // Auto-disable colors for machine-readable formats or when not a terminal
    if matches!(
        format,
        OutputFormat::Json | OutputFormat::Sarif | OutputFormat::Gcc
    ) {
        // Machine-readable formats never use colors
        colored::control::set_override(false);
    } else if !std::io::stdout().is_terminal() {
        colored::control::set_override(false);
    }

    // Merge CLI ignore patterns with config
    config.ignore.extend(args.ignore.clone());

    // Apply --min-glib-version if specified (overrides config)
    if let Some(version) = args.min_glib_version {
        config.min_glib_version = Some(version);
    }

    // Apply --msvc-compatible if specified (overrides config)
    if args.msvc_compatible {
        config.msvc_compatible = true;
    }

    // Apply --only filter if specified
    if !args.only.is_empty()
        && let Err(e) = config.enable_only_rules(&args.only)
    {
        eprintln!("{} {}", "error:".red().bold(), e);
        std::process::exit(1);
    }

    // Apply --exclude filter if specified
    if !args.exclude.is_empty()
        && let Err(e) = config.disable_rules(&args.exclude)
    {
        eprintln!("{} {}", "error:".red().bold(), e);
        std::process::exit(1);
    }

    // Apply --category filter if specified
    if let Some(category) = args.category {
        config.filter_by_category(category)?;
    }

    // Validate that explicitly enabled rules don't conflict with config
    scanner::validate_config(&config)?;

    // Handle --list-rules
    if args.list_rules {
        match format {
            OutputFormat::Json => {
                println!("{}", scanner::list_all_rules_json(&config));
            }
            _ => {
                scanner::list_all_rules(&config);
            }
        }
        return Ok(());
    }

    // Canonicalize directory path for consistent path handling
    if !args.directory.exists() {
        eprintln!(
            "{} path '{}' does not exist",
            "error:".red().bold(),
            args.directory.display()
        );
        std::process::exit(1);
    }
    let project_root = args
        .directory
        .canonicalize()
        .unwrap_or(args.directory.clone());

    // Build ignore matcher
    let ignore_matcher = config.build_ignore_matcher()?;

    // Create spinner for progress
    let spinner = if args.verbose {
        let sp = ProgressBar::new_spinner();
        sp.set_style(
            ProgressStyle::default_spinner()
                .template("{spinner:.green} {msg}")
                .unwrap(),
        );
        sp.enable_steady_tick(std::time::Duration::from_millis(100));
        Some(sp)
    } else {
        None
    };

    // Get meson introspection (for header visibility and compiler info)
    if let Some(ref sp) = spinner {
        sp.set_message("Running meson introspection...");
    }

    let meson_introspection = MesonIntrospection::new(&project_root, config.build_dir.as_deref())
        .ok()
        .flatten();

    let compiler_map = meson_introspection
        .as_ref()
        .and_then(|i| i.load_compiler_map().ok());

    if args.verbose {
        if let Some(ref m) = meson_introspection {
            let gir_count = m.get_introspected_headers().len();
            let installed_count = m.get_installed_headers().len();
            let compile_commands_count = compiler_map
                .as_ref()
                .map_or(0, std::collections::HashMap::len);
            println!(
                "Meson introspection: {} GIR headers, {} installed headers, {} compile commands",
                gir_count, installed_count, compile_commands_count
            );
        } else {
            println!(
                "Meson introspection not available - proceeding without public/private distinction"
            );
        }
    }

    let analysis_start = std::time::Instant::now();

    // Build AST-based context
    if let Some(ref sp) = spinner {
        sp.set_message("Parsing files...");
    }
    let ast_context = ast_context::AstContext::build_with_ignore(
        &project_root,
        &ignore_matcher,
        spinner.as_ref(),
        meson_introspection,
    )?;
    let parse_duration = analysis_start.elapsed();

    // Run AST-based rules
    let scan_start = std::time::Instant::now();
    let (mut violations, rule_timings) = scanner::scan_with_ast(
        &ast_context,
        &config,
        &project_root,
        spinner.as_ref(),
        !args.summary && !args.fix,
    )?;
    let scan_duration = scan_start.elapsed();
    let analysis_duration = parse_duration + scan_duration;

    if let Some(sp) = spinner {
        sp.finish_and_clear();
    }

    // Filter violations to changed lines when a diff is provided
    if let Some(diff_path) = &args.diff {
        let diff_content = if diff_path == std::path::Path::new("-") {
            let mut buf = String::new();
            std::io::stdin().read_to_string(&mut buf)?;
            buf
        } else {
            std::fs::read_to_string(diff_path)?
        };

        let mut patch = PatchSet::new();
        patch.parse(&diff_content).context("Failed to parse diff")?;

        // Diff paths are relative to the git root, which may differ from project_root
        let git_root = {
            let mut dir = project_root.as_path();
            loop {
                if dir.join(".git").exists() {
                    break dir.to_path_buf();
                }
                match dir.parent() {
                    Some(p) => dir = p,
                    None => break project_root.clone(),
                }
            }
        };

        let mut changed_lines: HashMap<std::path::PathBuf, HashSet<usize>> = HashMap::new();
        for file in patch {
            let path = git_root.join(file.path().trim_start_matches("b/"));
            let lines = changed_lines.entry(path).or_default();
            for hunk in file {
                for line in hunk {
                    if line.is_added()
                        && let Some(line_no) = line.target_line_no
                    {
                        lines.insert(line_no);
                    }
                }
            }
        }

        violations.retain(|v| {
            changed_lines
                .get(&v.file)
                .is_some_and(|lines| lines.contains(&v.line))
        });
    }

    if args.verbose {
        let total_functions: usize = ast_context
            .project
            .files
            .values()
            .map(|f| f.iter_function_declarations().count() + f.iter_function_definitions().count())
            .sum();
        let total_gobject_types: usize = ast_context
            .project
            .files
            .values()
            .map(|f| f.iter_all_gobject_types().count())
            .sum();
        println!(
            "Parsed {} files, {} functions, {} GObject types in {}",
            ast_context.project.files.len(),
            total_functions,
            total_gobject_types,
            reporter::format_duration(parse_duration),
        );
    }

    // Apply fixes if --fix was passed
    if args.fix {
        // Check if any enabled rules are fixable
        let rules = scanner::create_all_rules(&config);
        let has_fixable_rules = rules
            .iter()
            .any(|entry| entry.level.is_enabled() && entry.rule.fixable());

        if !has_fixable_rules {
            eprintln!(
                "Warning: --fix was specified but no enabled rules are auto-fixable.\n\
                 Run `gobject-linter --list-rules` to see which rules support auto-fix."
            );
        } else {
            let fixed_count = fixer::apply_fixes(&violations)?;
            println!("Fixed {} violation(s)", fixed_count);
        }

        // Don't exit with error code when we fixed things
        return Ok(());
    }

    // Summary table mode
    if args.summary {
        let rules = scanner::create_all_rules(&config);
        let fixable: std::collections::HashMap<&str, bool> = rules
            .iter()
            .map(|e| (e.rule.name(), e.rule.fixable()))
            .collect();
        reporter::report_summary(&violations, &fixable, &rule_timings, analysis_duration);
        let has_errors = violations.iter().any(|v| v.level.is_error());
        if has_errors {
            std::process::exit(1);
        }
        return Ok(());
    }

    // Output violations in the requested format
    match format {
        OutputFormat::Text => {
            reporter::report_violations(&violations, args.verbose, &config, analysis_duration);
        }
        OutputFormat::Json => {
            let json_output = serde_json::to_string_pretty(&violations)
                .expect("Failed to serialize violations to JSON");
            println!("{}", json_output);
        }
        OutputFormat::Sarif => {
            let sarif_output = output::sarif::generate_sarif(&violations, &config, &project_root);
            println!("{}", sarif_output);
        }
        OutputFormat::Gcc => {
            output::gcc::generate_gcc(&violations);
        }
        OutputFormat::GitlabCodequality => {
            let json =
                output::gitlab_codequality::generate_gitlab_codequality(&violations, &project_root);
            println!("{}", json);
        }
    }

    // Exit with error code only if there are error-level violations (not warnings)
    let has_errors = violations.iter().any(|v| v.level.is_error());
    if has_errors {
        std::process::exit(1);
    }

    Ok(())
}