hawkeye 7.0.0-alpha.1

A license header checker and formatter.
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
// Copyright 2026 FastLabs Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

mod analyze;
mod discovery;
mod git;

use std::collections::BTreeMap;
use std::collections::BTreeSet;
use std::fs;
use std::ops::Range;
use std::path::Path;
use std::path::PathBuf;
use std::time::SystemTime;

use ignore::overrides::Override;
use jiff::Timestamp;
use jiff::tz::TimeZone;
use serde::Serialize;

use crate::Error;
use crate::ErrorKind;
use crate::builtin;
use crate::config::Config;
use crate::config::FeatureMode;
use crate::config::GitConfig;
use crate::config::RuleConfig;
use crate::config::StyleConfig;
use crate::engine::git::FileHistory;
use crate::engine::git::Repository;
use crate::report::FileOutcome;
use crate::report::FileReport;
use crate::report::Report;
use crate::template::HeaderTemplate;

#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct FileAttrs {
    filename: String,
    disk_file_created_year: Option<i16>,
    disk_file_modified_year: Option<i16>,
    git_file_created_year: Option<i16>,
    git_file_modified_year: Option<i16>,
    git_authors: Vec<String>,
}

impl FileAttrs {
    fn new(path: &Path, git: Option<&FileHistory>) -> Result<Self, Error> {
        let metadata = fs::metadata(path).map_err(|err| {
            Error::new(
                ErrorKind::Unexpected,
                format!("cannot read metadata for {}", path.display()),
            )
            .with_source(err)
        })?;
        Ok(Self {
            filename: path
                .file_name()
                .expect("selected files must have a filename")
                .to_string_lossy()
                .into_owned(),
            disk_file_created_year: metadata.created().ok().and_then(file_time_to_year),
            disk_file_modified_year: metadata.modified().ok().and_then(file_time_to_year),
            git_file_created_year: git.and_then(|history| history.created_year),
            git_file_modified_year: git.and_then(|history| history.modified_year),
            git_authors: git
                .map(|history| history.authors.iter().cloned().collect())
                .unwrap_or_default(),
        })
    }
}

fn file_time_to_year(time: SystemTime) -> Option<i16> {
    let ts = Timestamp::try_from(time).ok()?;
    Some(ts.to_zoned(TimeZone::system()).year())
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum HeaderTarget {
    Present,
    Absent,
}

/// The files and directories processed by an [`Engine`] operation.
#[derive(Debug, Clone, Copy)]
pub enum Scope<'a> {
    /// Process every file selected by the configuration.
    All,
    /// Process only the requested paths.
    ///
    /// Relative paths are resolved against `files.root`. Direct files bypass Git ignore rules,
    /// while directories use normal discovery. All paths still obey `files.root`,
    /// `files.includes`, and `files.excludes`. An empty slice processes no files.
    Paths(&'a [PathBuf]),
}

/// A license-header processor built from one [`Config`].
pub struct Engine {
    root: PathBuf,
    header_path: Option<PathBuf>,
    file_filter: Override,
    walk_filter: Override,
    props: BTreeMap<String, toml::Value>,
    git: GitConfig,
    keywords: Vec<String>,
    template: HeaderTemplate,
    styles: BTreeMap<String, StyleConfig>,
    rules: Vec<Rule>,
}

#[derive(Debug, Clone)]
struct Rule {
    extensions: BTreeSet<String>,
    filenames: BTreeSet<String>,
    style_out: String,
    styles_in: Vec<String>,
}

impl Engine {
    /// Validates the configuration and builds an engine.
    ///
    /// # Errors
    ///
    /// Returns an error if the configuration is inconsistent or a required path, template, or
    /// style cannot be resolved.
    pub fn new(config: Config) -> Result<Self, Error> {
        config.validate()?;

        let Config {
            header,
            files,
            props,
            git,
            styles: configured_styles,
            rules: configured_rules,
        } = config;

        let root = files.root.canonicalize().map_err(|err| {
            Error::new(
                ErrorKind::Unexpected,
                format!("cannot resolve file root {}", files.root.display()),
            )
            .with_source(err)
        })?;
        if !root.is_dir() {
            return Err(Error::new(
                ErrorKind::ConfigInvalid,
                format!("files.root is not a directory: {}", root.display()),
            ));
        }
        log::debug!(
            "configured file selection: root={}, includes={:?}, excludes={:?}, git.ignore={:?}, git.file_attrs={:?}",
            root.display(),
            files.includes,
            files.excludes,
            git.ignore,
            git.file_attrs
        );
        let (file_filter, walk_filter) =
            discovery::compile_file_filters(&root, &files.includes, &files.excludes)?;

        let (template, header_path) = if let Some(content) = header.text {
            (HeaderTemplate::new(content)?, None)
        } else if let Some(path) = header.path {
            let path = path.canonicalize().map_err(|err| {
                Error::new(
                    ErrorKind::Unexpected,
                    format!("cannot resolve header template {}", path.display()),
                )
                .with_source(err)
            })?;
            let content = fs::read_to_string(&path).map_err(|err| {
                Error::new(
                    ErrorKind::Unexpected,
                    format!("cannot read header template {}", path.display()),
                )
                .with_source(err)
            })?;
            (HeaderTemplate::new(content)?, Some(path))
        } else if let Some(key) = header.builtin {
            let content = builtin::HEADERS.get(key.as_str()).copied().ok_or_else(|| {
                let available = builtin::HEADERS
                    .keys()
                    .copied()
                    .collect::<Vec<_>>()
                    .join(", ");
                Error::new(
                    ErrorKind::ConfigInvalid,
                    format!("unknown header.builtin {key:?}; available values are {available}"),
                )
            })?;
            (HeaderTemplate::new(content)?, None)
        } else {
            return Err(Error::new(
                ErrorKind::ConfigInvalid,
                "header source is missing",
            ));
        };

        let styles = {
            let mut styles = builtin::STYLES.clone();
            for (name, style) in configured_styles {
                if styles.contains_key(&name) {
                    log::warn!("custom style {name:?} overrides a built-in style of the same name");
                }
                styles.insert(name, style);
            }
            styles
        };

        let configured_rules = configured_rules
            .into_iter()
            .enumerate()
            .map(|(index, rule)| (format!("rules[{index}]"), rule));
        let builtin_rules = builtin::RULES
            .iter()
            .cloned()
            .enumerate()
            .map(|(index, rule)| (format!("builtin.rules[{index}]"), rule));
        let mut selectors = BTreeMap::<(&str, String), String>::new();
        let rules = configured_rules
            .chain(builtin_rules)
            .map(|(source, rule)| {
                let extensions = rule.extensions.iter().map(|value| ("extension", value));
                let filenames = rule.filenames.iter().map(|value| ("filename", value));
                for (kind, selector) in extensions.chain(filenames) {
                    let key = (kind, selector.to_lowercase());
                    if let Some(owner) = selectors.get(&key) {
                        log::debug!("{source} {kind} {selector:?} is shadowed by {owner}");
                    } else {
                        selectors.insert(key, source.clone());
                    }
                }
                Rule::new(&source, rule, &styles)
            })
            .collect::<Result<Vec<_>, Error>>()?;
        log::debug!("resolved {} styles and {} rules", styles.len(), rules.len());

        let keywords = header
            .keywords
            .into_iter()
            .map(|keyword| keyword.to_lowercase())
            .collect();

        Ok(Self {
            root,
            header_path,
            file_filter,
            walk_filter,
            props,
            git,
            keywords,
            template,
            styles,
            rules,
        })
    }

    /// Checks files in the given scope without modifying them.
    ///
    /// # Errors
    ///
    /// Returns an error if selected files cannot be discovered, read, or analyzed.
    pub fn check(&self, scope: Scope<'_>) -> Result<Report, Error> {
        Ok(self.edits(HeaderTarget::Present, scope)?.report)
    }

    /// Prepares additions and replacements that make selected headers canonical.
    ///
    /// # Errors
    ///
    /// Returns an error if selected files cannot be discovered, read, or analyzed.
    pub fn format(&self, scope: Scope<'_>) -> Result<Edits, Error> {
        self.edits(HeaderTarget::Present, scope)
    }

    /// Prepares removals for recognized headers.
    ///
    /// # Errors
    ///
    /// Returns an error if selected files cannot be discovered, read, or analyzed.
    pub fn remove(&self, scope: Scope<'_>) -> Result<Edits, Error> {
        self.edits(HeaderTarget::Absent, scope)
    }

    fn edits(&self, target: HeaderTarget, scope: Scope<'_>) -> Result<Edits, Error> {
        if matches!(scope, Scope::Paths([])) {
            return Ok(Edits {
                report: Report { files: Vec::new() },
                files: Vec::new(),
            });
        }

        let git_mode = self.git.ignore.combine(self.git.file_attrs);
        let repo = if git_mode == FeatureMode::Disable {
            None
        } else {
            match Repository::discover(&self.root) {
                Ok(repo) => Some(repo),
                Err(err)
                    if git_mode == FeatureMode::Auto && err.kind() == ErrorKind::Unsupported =>
                {
                    log::debug!("Git integration is unavailable: {err}");
                    None
                }
                Err(err) => return Err(err),
            }
        };
        let paths = self.discover_files(repo.as_ref(), scope)?;
        let files_with_rules = paths
            .into_iter()
            .map(|path| {
                let rule = self.rules.iter().find(|rule| rule.matches(&path));
                (path, rule)
            })
            .collect::<Vec<_>>();
        let supported = files_with_rules
            .iter()
            .filter_map(|(path, rule)| rule.is_some().then_some(path.as_path()))
            .collect::<Vec<_>>();
        let git_history = if self.git.file_attrs == FeatureMode::Disable || supported.is_empty() {
            None
        } else if let Some(repo) = repo.as_ref() {
            if repo.is_shallow() {
                let message = "Git file attributes require complete history, but the repository is shallow; fetch complete history first";
                if self.git.file_attrs == FeatureMode::Auto {
                    log::warn!("{message}; continuing with Git file attributes disabled");
                    None
                } else {
                    return Err(Error::new(ErrorKind::Unsupported, message));
                }
            } else {
                Some(repo.file_history(&self.root, supported)?)
            }
        } else {
            debug_assert_ne!(self.git.file_attrs, FeatureMode::Enable);
            None
        };

        let mut files = Vec::with_capacity(files_with_rules.len());
        let mut file_edits = Vec::new();

        for (relative_path, rule) in files_with_rules {
            let Some(rule) = rule else {
                log::debug!(
                    "{} has no matching rule; reporting it as unsupported",
                    relative_path.display()
                );
                files.push(FileReport {
                    path: relative_path,
                    outcome: FileOutcome::Unsupported,
                });
                continue;
            };

            let path = self.root.join(&relative_path);
            let original = fs::read(&path).map_err(|err| {
                Error::new(
                    ErrorKind::Unexpected,
                    format!("cannot read {}", path.display()),
                )
                .with_source(err)
            })?;
            let Ok(input) = std::str::from_utf8(&original) else {
                log::debug!(
                    "{} is not UTF-8 text; reporting it as unsupported",
                    relative_path.display()
                );
                files.push(FileReport {
                    path: relative_path,
                    outcome: FileOutcome::Unsupported,
                });
                continue;
            };
            let file_attrs = FileAttrs::new(
                &path,
                git_history
                    .as_ref()
                    .and_then(|history| history.get(&relative_path)),
            )?;
            let header = self.render_header(&file_attrs)?;
            let outcome = match self.analyze(rule, input, &header, target) {
                FileAnalysis::Clean => FileOutcome::Clean,
                FileAnalysis::Add(replacement) => {
                    file_edits.push(FileEdit { path, replacement });
                    FileOutcome::Add
                }
                FileAnalysis::Replace(replacement) => {
                    file_edits.push(FileEdit { path, replacement });
                    FileOutcome::Replace
                }
                FileAnalysis::Remove(replacement) => {
                    file_edits.push(FileEdit { path, replacement });
                    FileOutcome::Remove
                }
                FileAnalysis::Conflict => FileOutcome::Conflict,
            };
            files.push(FileReport {
                path: relative_path,
                outcome,
            });
        }

        Ok(Edits {
            report: Report { files },
            files: file_edits,
        })
    }

    fn render_header(&self, attrs: &FileAttrs) -> Result<String, Error> {
        let header = self.template.render(&self.props, attrs)?;
        let folded = header.to_lowercase();
        if let Some(keyword) = self
            .keywords
            .iter()
            .find(|keyword| !folded.contains(keyword.as_str()))
        {
            return Err(Error::new(
                ErrorKind::ConfigInvalid,
                format!(
                    "header template output for {:?} does not contain recognition keyword {:?}",
                    attrs.filename, keyword,
                ),
            ));
        }
        Ok(header)
    }
}

/// Pending file edits prepared by an [`Engine`].
#[must_use = "edits have no effect until they are applied"]
pub struct Edits {
    report: Report,
    files: Vec<FileEdit>,
}

impl Edits {
    /// Discards the pending edits and returns their report.
    pub fn into_report(self) -> Report {
        self.report
    }

    /// Applies the pending edits and returns their report.
    ///
    /// Callers must ensure that selected files are not modified between preparing and applying the
    /// edits.
    ///
    /// # Errors
    ///
    /// Returns an error if a source file cannot be read or written.
    pub fn apply(self) -> Result<Report, Error> {
        for FileEdit { path, replacement } in self.files {
            let mut input = fs::read_to_string(&path).map_err(|err| {
                Error::new(
                    ErrorKind::Unexpected,
                    format!("cannot read {}", path.display()),
                )
                .with_source(err)
            })?;
            input.replace_range(replacement.range, &replacement.text);
            fs::write(&path, input).map_err(|err| {
                Error::new(
                    ErrorKind::Unexpected,
                    format!("cannot write {}", path.display()),
                )
                .with_source(err)
            })?;
        }
        Ok(self.report)
    }
}

struct FileEdit {
    path: PathBuf,
    replacement: Replacement,
}

impl Rule {
    fn new(
        source: &str,
        config: RuleConfig,
        styles: &BTreeMap<String, StyleConfig>,
    ) -> Result<Self, Error> {
        let RuleConfig {
            extensions,
            filenames,
            style_out,
            styles_in: configured_styles_in,
        } = config;

        let configured_styles_in = if configured_styles_in.is_empty() {
            vec![style_out.clone()]
        } else {
            configured_styles_in
        };
        let mut styles_in = Vec::with_capacity(configured_styles_in.len());
        let mut seen = BTreeSet::new();
        for name in configured_styles_in {
            if !styles.contains_key(&name) {
                return Err(Error::new(
                    ErrorKind::ConfigInvalid,
                    format!("{source} references unknown style {name:?}"),
                ));
            }
            if !seen.insert(name.clone()) {
                log::warn!("{source}.styles_in contains duplicate style {name:?}; ignoring it");
                continue;
            }
            styles_in.push(name);
        }
        Ok(Self {
            extensions: extensions
                .into_iter()
                .map(|extension| format!(".{}", extension.to_lowercase()))
                .collect(),
            filenames: filenames
                .into_iter()
                .map(|filename| filename.to_lowercase())
                .collect(),
            style_out,
            styles_in,
        })
    }

    fn matches(&self, path: &Path) -> bool {
        let Some(filename) = path.file_name() else {
            return false;
        };
        let filename = filename.to_string_lossy().to_lowercase();
        self.filenames.contains(&filename)
            || self
                .extensions
                .iter()
                .any(|extension| filename.ends_with(extension))
    }
}

struct Replacement {
    range: Range<usize>,
    text: String,
}

enum FileAnalysis {
    Clean,
    Add(Replacement),
    Replace(Replacement),
    Remove(Replacement),
    Conflict,
}