Skip to main content

gdck_config/
lib.rs

1//! Configuration for `gdck`.
2//!
3//! Defaults come from the [GDScript style guide][guide], so a project with no
4//! configuration file at all gets style-guide behaviour.
5//!
6//! [guide]: https://docs.godotengine.org/en/stable/tutorials/scripting/gdscript/gdscript_styleguide.html
7//!
8//! # Reading a project's settings
9//!
10//! [`resolve`] walks up from a directory and returns the settings in force
11//! there, along with the files they came from:
12//!
13//! ```no_run
14//! let loaded = gdck_config::resolve(std::path::Path::new("."))?;
15//! println!("{} columns", loaded.config.format.line_length);
16//! # Ok::<(), gdck_config::Error>(())
17//! ```
18//!
19//! The nearest `gdck.toml` wins outright. Failing that, `gdtoolkit`'s own
20//! `gdformatrc` and `gdlintrc` are read, so a project already using `gdformat`
21//! and `gdlint` keeps its line length and its disabled rules without writing
22//! anything new. See `docs/CONFIG.md` for the schema and the precedence.
23//!
24//! # Two file formats, two approaches
25//!
26//! `gdck.toml` is read by the [`toml`] crate, and validated here for the
27//! things a deserialiser cannot know — ranges, and settings that only mean
28//! something alongside another.
29//!
30//! The `gdtoolkit` files are read by [`yaml_serde`] into an untyped mapping
31//! rather than into a struct, because a `gdlintrc` holds dozens of settings
32//! `gdck` has no equivalent for and each should be skipped with a note rather
33//! than failing the file. A file that cannot be parsed at all *is* an error:
34//! none of its settings would apply, and a project formatted by rules it had
35//! written down and rejected is the outcome worse than not running.
36
37mod compat;
38mod schema;
39
40use std::fmt;
41use std::path::{Path, PathBuf};
42
43/// Config file names searched for, in priority order, walking up from the
44/// working directory.
45pub const CONFIG_FILE_NAMES: &[&str] = &["gdck.toml", ".gdck.toml"];
46
47/// `gdformat`'s configuration file, read for compatibility.
48pub const GDFORMAT_FILE_NAMES: &[&str] = &["gdformatrc", ".gdformatrc"];
49
50/// `gdlint`'s configuration file, read for compatibility.
51pub const GDLINT_FILE_NAMES: &[&str] = &["gdlintrc", ".gdlintrc"];
52
53/// Directories skipped when collecting `.gd` files.
54///
55/// `.godot` holds the editor's generated import cache and `addons` is usually
56/// third-party code a project does not want reformatted.
57pub const DEFAULT_EXCLUDED_DIRS: &[&str] = &[".git", ".godot", ".import", "addons"];
58
59/// Indentation style. The style guide mandates tabs; spaces are available
60/// because some existing projects have already committed to them.
61#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
62pub enum IndentStyle {
63    #[default]
64    Tabs,
65    Spaces(u8),
66}
67
68/// How a file-level `class_name` and its `extends` are laid out.
69///
70/// The style guide asks for two lines, and says so three ways: the prose
71/// introduces them in sequence ("Follow with the optional `@icon` then the
72/// `class_name`... Then, add the `extends` keyword"), every example writes
73/// them apart, and inner classes are singled out for the opposite treatment —
74/// "For inner classes, use single-line declarations". That contrast only means
75/// something if file-level declarations are not single-line, so
76/// [`MultiLine`](Self::MultiLine) is the default.
77///
78/// `gdformat` enforces neither: its grammar has a separate rule for the joined
79/// form and it preserves whichever the author wrote. So a project arriving from
80/// `gdformat` can be consistently on the one-line form without ever having
81/// chosen it, and the first `gdck format` would rewrite most of its files.
82/// [`SingleLine`](Self::SingleLine) exists for a project that has looked at
83/// that diff and decided it prefers what it already had.
84#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
85pub enum ClassDeclaration {
86    /// `class_name Player` and `extends Node` on their own lines.
87    #[default]
88    MultiLine,
89    /// `class_name Player extends Node`, as `gdformat` leaves it.
90    SingleLine,
91}
92
93/// Formatting options.
94#[derive(Debug, Clone, PartialEq, Eq)]
95#[non_exhaustive]
96pub struct FormatConfig {
97    /// Hard wrap width. The style guide says keep lines under 100 characters.
98    pub line_length: u16,
99    pub indent: IndentStyle,
100    /// Whether a file-level `class_name` keeps its `extends` on the same line.
101    pub class_declaration: ClassDeclaration,
102    /// Re-run the formatter on its own output and reject the result if it is
103    /// not stable, and check that no comments were dropped. Cheap insurance
104    /// against a formatter bug silently eating code.
105    pub safety_checks: bool,
106}
107
108impl Default for FormatConfig {
109    fn default() -> Self {
110        Self {
111            line_length: 100,
112            indent: IndentStyle::Tabs,
113            class_declaration: ClassDeclaration::MultiLine,
114            safety_checks: true,
115        }
116    }
117}
118
119/// How aggressively `gdck fix` may reorder class members.
120///
121/// Reordering is not purely cosmetic: class-level initialisers run in
122/// declaration order, so moving a public variable above a private one it reads
123/// changes behaviour. See `docs/DESIGN.md` for the full analysis.
124#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
125pub enum CodeOrderFix {
126    /// Report violations; only reorder when `--fix-order` is passed.
127    #[default]
128    ReportOnly,
129    /// Reorder a file when every required move is provably safe, and leave the
130    /// file completely untouched otherwise.
131    WholeFileWhenSafe,
132    /// Never reorder, and do not report ordering problems either.
133    Off,
134}
135
136/// The groups a project may put in an order of its own.
137///
138/// This is `gdtoolkit`'s vocabulary rather than `gdck`'s, deliberately: it
139/// exists so a project that pinned `class-definitions-order` in a `gdlintrc`
140/// keeps the order it chose. `gdck` sorts more finely than these fourteen
141/// names can express — it knows `_ready()` from `_process()` from a static
142/// function, where `gdtoolkit` has only `others` — and that finer order is
143/// kept *within* whichever position `Others` is given.
144#[derive(Debug, Clone, Copy, PartialEq, Eq)]
145pub enum DeclarationGroup {
146    Tools,
147    ClassNames,
148    Extends,
149    Docstrings,
150    Signals,
151    Enums,
152    Consts,
153    Exports,
154    PubVars,
155    PrvVars,
156    OnreadyPubVars,
157    OnreadyPrvVars,
158    StaticVars,
159    Others,
160}
161
162impl DeclarationGroup {
163    /// The `gdtoolkit` spelling, which is also `gdck`'s.
164    #[must_use]
165    pub fn name(self) -> &'static str {
166        match self {
167            Self::Tools => "tools",
168            Self::ClassNames => "classnames",
169            Self::Extends => "extends",
170            Self::Docstrings => "docstrings",
171            Self::Enums => "enums",
172            Self::Signals => "signals",
173            Self::Consts => "consts",
174            Self::Exports => "exports",
175            Self::PubVars => "pubvars",
176            Self::PrvVars => "prvvars",
177            Self::OnreadyPubVars => "onreadypubvars",
178            Self::OnreadyPrvVars => "onreadyprvvars",
179            Self::StaticVars => "staticvars",
180            Self::Others => "others",
181        }
182    }
183
184    /// Read one from the name `gdtoolkit` uses for it.
185    #[must_use]
186    pub fn from_name(name: &str) -> Option<Self> {
187        [
188            Self::Tools,
189            Self::ClassNames,
190            Self::Extends,
191            Self::Docstrings,
192            Self::Signals,
193            Self::Enums,
194            Self::Consts,
195            Self::Exports,
196            Self::PubVars,
197            Self::PrvVars,
198            Self::OnreadyPubVars,
199            Self::OnreadyPrvVars,
200            Self::StaticVars,
201            Self::Others,
202        ]
203        .into_iter()
204        .find(|group| group.name() == name)
205    }
206}
207
208/// Which convention the `file-name` rule holds a file to.
209///
210/// The style guide says snake_case and that is the default. It is also the one
211/// naming rule where a project's own answer is worth honouring rather than
212/// suppressing: a file name is not an identifier the language sees, so a
213/// project that names files after the classes in them is following a
214/// convention rather than breaking one. Saying which is being followed keeps
215/// the rule working, where disabling it stops it noticing anything at all.
216///
217/// Both settings are a convention by name, not a pattern to match. The
218/// alternative — a regular expression, as `gdtoolkit` takes — makes every
219/// project's spelling of "snake_case" subtly its own. See `docs/DESIGN.md`.
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
221pub enum FileNameCase {
222    /// `player_controller.gd`, what the guide asks for.
223    #[default]
224    SnakeCase,
225    /// `PlayerController.gd`, matching the class the file holds.
226    PascalCase,
227}
228
229/// Lint options.
230#[derive(Debug, Clone, PartialEq, Eq)]
231#[non_exhaustive]
232pub struct LintConfig {
233    pub max_line_length: u16,
234    pub max_file_lines: u32,
235    pub max_public_methods: u32,
236    pub max_returns: u32,
237    pub max_function_arguments: u32,
238    pub code_order: CodeOrderFix,
239    pub file_name: FileNameCase,
240    /// A declaration order of the project's own, if it stated one.
241    ///
242    /// `None` means the style guide's, which is what `gdck` sorts by and what
243    /// its own buckets are named after. A project that pinned
244    /// `class-definitions-order` in a `gdlintrc` gets that order instead.
245    pub declaration_order: Option<Vec<DeclarationGroup>>,
246    /// Rule names switched off for this project.
247    pub disabled: Vec<String>,
248}
249
250impl Default for LintConfig {
251    fn default() -> Self {
252        Self {
253            max_line_length: 100,
254            max_file_lines: 1000,
255            max_public_methods: 20,
256            max_returns: 6,
257            max_function_arguments: 10,
258            code_order: CodeOrderFix::default(),
259            file_name: FileNameCase::default(),
260            declaration_order: None,
261            disabled: Vec::new(),
262        }
263    }
264}
265
266/// Naming patterns from the style guide's conventions table.
267///
268/// Written out as source strings because that is the least ambiguous way to
269/// state a convention, and because it is the form a project would use to
270/// override one. The linter does not compile them: `is_snake_case` and its
271/// two siblings are a dozen lines each and read better than the equivalent
272/// pattern, so these stand as documentation of what those functions accept.
273/// See [`crate::naming`] and `gdck_lint::names`.
274pub mod naming {
275    pub const PASCAL_CASE: &str = r"([A-Z][a-z0-9]*)+";
276    pub const SNAKE_CASE: &str = r"[a-z][a-z0-9]*(_[a-z0-9]+)*";
277    pub const PRIVATE_SNAKE_CASE: &str = r"_?[a-z][a-z0-9]*(_[a-z0-9]+)*";
278    pub const CONSTANT_CASE: &str = r"[A-Z][A-Z0-9]*(_[A-Z0-9]+)*";
279    pub const PRIVATE_CONSTANT_CASE: &str = r"_?[A-Z][A-Z0-9]*(_[A-Z0-9]+)*";
280}
281
282/// The full configuration for a run.
283#[derive(Debug, Clone, PartialEq, Eq, Default)]
284#[non_exhaustive]
285pub struct Config {
286    pub format: FormatConfig,
287    pub lint: LintConfig,
288    pub excluded_dirs: Vec<String>,
289}
290
291impl Config {
292    /// Whether a directory name should be skipped when collecting files.
293    #[must_use]
294    pub fn is_excluded_dir(&self, name: &str) -> bool {
295        if self.excluded_dirs.is_empty() {
296            return DEFAULT_EXCLUDED_DIRS.contains(&name);
297        }
298        self.excluded_dirs.iter().any(|dir| dir == name)
299    }
300
301    /// Write these settings out as a `gdck.toml`.
302    ///
303    /// Every setting is written, including the ones left at their default,
304    /// because the question this answers is what a run is actually using.
305    #[must_use]
306    pub fn to_toml(&self) -> String {
307        schema::to_toml(self)
308    }
309
310    /// Write these settings out as a `gdck.toml` for a project to keep.
311    ///
312    /// Every setting appears, but the ones still at their default are
313    /// commented out. The live lines are then what this project decided, and
314    /// the commented ones are a catalogue to uncomment from — and a project
315    /// inherits later changes to a default rather than pinning today's value
316    /// without meaning to.
317    ///
318    /// This is what `gdck init` writes. [`to_toml`](Self::to_toml) is the
319    /// other question — what a run is using — and answers it in full.
320    #[must_use]
321    pub fn to_starter_toml(&self) -> String {
322        schema::to_starter_toml(self)
323    }
324}
325
326// -- errors and notes -------------------------------------------------------
327
328/// Something wrong at a line of a file, before the file is known.
329#[derive(Debug, Clone, PartialEq, Eq)]
330pub(crate) struct Problem {
331    pub(crate) line: u32,
332    pub(crate) message: String,
333}
334
335/// A configuration file that could not be used.
336///
337/// A broken configuration file is always fatal rather than a fall back to the
338/// defaults. Settings that quietly do not apply are worse than a run that
339/// stops and says why.
340#[derive(Debug, Clone, PartialEq, Eq)]
341pub struct Error {
342    pub path: PathBuf,
343    /// The line at fault, when the file was read but not understood.
344    pub line: Option<u32>,
345    pub message: String,
346}
347
348impl fmt::Display for Error {
349    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
350        match self.line {
351            Some(line) => write!(f, "{}:{line}: {}", self.path.display(), self.message),
352            None => write!(f, "{}: {}", self.path.display(), self.message),
353        }
354    }
355}
356
357impl std::error::Error for Error {}
358
359/// Something a configuration file asked for that `gdck` cannot honour.
360///
361/// Only the `gdtoolkit` files produce these. `gdck.toml` refuses what it
362/// cannot do, but a foreign file is allowed to hold settings that mean nothing
363/// here — and saying so is the difference between a setting that does not
364/// apply and one that silently does not apply.
365#[derive(Debug, Clone, PartialEq, Eq)]
366pub struct Note {
367    pub path: PathBuf,
368    pub line: u32,
369    pub message: String,
370}
371
372impl fmt::Display for Note {
373    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
374        write!(f, "{}:{}: {}", self.path.display(), self.line, self.message)
375    }
376}
377
378/// Settings, and where they came from.
379#[derive(Debug, Clone, PartialEq, Eq, Default)]
380pub struct Loaded {
381    pub config: Config,
382    /// The files read, in the order they were applied. Empty when nothing was
383    /// found and the defaults are in force.
384    pub files: Vec<PathBuf>,
385    pub notes: Vec<Note>,
386}
387
388// -- discovery and loading --------------------------------------------------
389
390/// One of the `gdtoolkit` readers: settings in, notes out.
391type Reader = fn(&str, &mut Config) -> Result<Vec<Problem>, Problem>;
392
393/// Find the nearest `gdck.toml`, searching `start` and then each ancestor.
394///
395/// Returns `None` when the search reaches the filesystem root without a match,
396/// which is the normal case for a project that has not configured anything.
397#[must_use]
398pub fn discover(start: &Path) -> Option<PathBuf> {
399    discover_named(start, CONFIG_FILE_NAMES)
400}
401
402/// Find the nearest file with one of `names`, searching `start` and then each
403/// ancestor.
404#[must_use]
405pub fn discover_named(start: &Path, names: &[&str]) -> Option<PathBuf> {
406    for dir in start.ancestors() {
407        for name in names {
408            let candidate = dir.join(name);
409            if candidate.is_file() {
410                return Some(candidate);
411            }
412        }
413    }
414    None
415}
416
417/// The settings in force in a directory.
418///
419/// The nearest `gdck.toml` wins outright: a project that has written one has
420/// said what it wants, and quietly mixing in a `gdlintrc` from three
421/// directories further up would make the result impossible to predict. Only
422/// when there is no `gdck.toml` are `gdformatrc` and `gdlintrc` read, so a
423/// project already set up for `gdtoolkit` keeps its settings.
424pub fn resolve(start: &Path) -> Result<Loaded, Error> {
425    if let Some(path) = discover(start) {
426        let mut loaded = load(&path)?;
427        loaded.notes.extend(shadowed_notes(start, &loaded.config));
428        return Ok(loaded);
429    }
430
431    let mut loaded = Loaded::default();
432    // Formatting first, so a `gdlintrc` naming its own line length has the
433    // last word on what the linter reports.
434    let readers: [(&[&str], Reader); 2] = [
435        (GDFORMAT_FILE_NAMES, compat::apply_gdformatrc),
436        (GDLINT_FILE_NAMES, compat::apply_gdlintrc),
437    ];
438    for (names, apply) in readers {
439        let Some(path) = discover_named(start, names) else {
440            continue;
441        };
442        let text = read_to_string(&path)?;
443        let problems = apply(&text, &mut loaded.config).map_err(|problem| at(&path, problem))?;
444        loaded.notes.extend(notes_at(&path, problems));
445        loaded.files.push(path);
446    }
447    Ok(loaded)
448}
449
450/// Note any `gdtoolkit` file whose settings a `gdck.toml` is keeping out.
451///
452/// The precedence itself is deliberate and stays: a project that has written a
453/// `gdck.toml` has said what it wants. What is not defensible is doing it
454/// silently, which is how a project ends up governed by rules it thought it had
455/// set — `gdck` says so for a single unknown key in a `gdlintrc`, so passing
456/// over the whole file without a word was the odd one out.
457///
458/// Only a file that would actually *change* something is reported. After
459/// `gdck init` has carried the settings across, both files say the same thing
460/// and there is nothing to warn about, so the warning does not become a
461/// permanent fixture that teaches people to ignore it.
462///
463/// A shadowed file that cannot be read or parsed is passed over in silence. It
464/// is not governing this run, so it cannot mislead anyone about it, and failing
465/// a run over a file it is not using would be worse.
466fn shadowed_notes(start: &Path, active: &Config) -> Vec<Note> {
467    let mut notes = Vec::new();
468    let readers: [(&[&str], Reader); 2] = [
469        (GDFORMAT_FILE_NAMES, compat::apply_gdformatrc),
470        (GDLINT_FILE_NAMES, compat::apply_gdlintrc),
471    ];
472
473    let mut would_be = Config::default();
474    let mut found = Vec::new();
475    for (names, apply) in readers {
476        let Some(path) = discover_named(start, names) else {
477            continue;
478        };
479        let Ok(text) = std::fs::read_to_string(&path) else {
480            continue;
481        };
482        if apply(&text, &mut would_be).is_err() {
483            continue;
484        }
485        found.push(path);
486    }
487    if found.is_empty() {
488        return notes;
489    }
490
491    let changed = differences(active, &would_be);
492    if changed.is_empty() {
493        return notes;
494    }
495
496    for path in found {
497        notes.push(Note {
498            path,
499            line: 1,
500            message: format!(
501                "not applied, because the gdck.toml takes precedence. It disagrees \
502                 about {}. Copy those into the gdck.toml, or delete this file",
503                changed.join(", ")
504            ),
505        });
506    }
507    notes
508}
509
510/// The settings two configurations disagree about, by the name a `gdck.toml`
511/// spells them, so the message names something searchable.
512fn differences(active: &Config, other: &Config) -> Vec<&'static str> {
513    let mut changed = Vec::new();
514    if active.format.line_length != other.format.line_length {
515        changed.push("format.line-length");
516    }
517    if active.format.indent != other.format.indent {
518        changed.push("format.indent");
519    }
520    if active.format.safety_checks != other.format.safety_checks {
521        changed.push("format.safety-checks");
522    }
523    if active.lint.max_line_length != other.lint.max_line_length {
524        changed.push("lint.max-line-length");
525    }
526    if active.lint.max_file_lines != other.lint.max_file_lines {
527        changed.push("lint.max-file-lines");
528    }
529    if active.lint.max_public_methods != other.lint.max_public_methods {
530        changed.push("lint.max-public-methods");
531    }
532    if active.lint.max_returns != other.lint.max_returns {
533        changed.push("lint.max-returns");
534    }
535    if active.lint.max_function_arguments != other.lint.max_function_arguments {
536        changed.push("lint.max-arguments");
537    }
538    if active.lint.declaration_order != other.lint.declaration_order {
539        changed.push("lint.declaration-order");
540    }
541    if active.lint.disabled != other.lint.disabled {
542        changed.push("lint.disable");
543    }
544    if active.excluded_dirs != other.excluded_dirs {
545        changed.push("files.exclude");
546    }
547    changed
548}
549
550/// Read one configuration file, whatever kind it is.
551///
552/// The kind is decided by the file's name, so `--config` can be pointed at a
553/// `gdlintrc` as readily as at a `gdck.toml`. A name matching none of them is
554/// read as a `gdck.toml`.
555pub fn load(path: &Path) -> Result<Loaded, Error> {
556    let text = read_to_string(path)?;
557    let name = path
558        .file_name()
559        .map_or_else(String::new, |name| name.to_string_lossy().into_owned());
560
561    let mut loaded = Loaded {
562        files: vec![path.to_path_buf()],
563        ..Loaded::default()
564    };
565    let problems = if GDLINT_FILE_NAMES.contains(&name.as_str()) {
566        compat::apply_gdlintrc(&text, &mut loaded.config).map_err(|problem| at(path, problem))?
567    } else if GDFORMAT_FILE_NAMES.contains(&name.as_str()) {
568        compat::apply_gdformatrc(&text, &mut loaded.config).map_err(|problem| at(path, problem))?
569    } else {
570        loaded.config = schema::read(&text).map_err(|problem| at(path, problem))?;
571        Vec::new()
572    };
573    loaded.notes = notes_at(path, problems);
574    Ok(loaded)
575}
576
577/// Pin a problem to the file it was found in.
578fn at(path: &Path, problem: Problem) -> Error {
579    Error {
580        path: path.to_path_buf(),
581        line: Some(problem.line),
582        message: problem.message,
583    }
584}
585
586fn notes_at(path: &Path, problems: Vec<Problem>) -> Vec<Note> {
587    problems
588        .into_iter()
589        .map(|problem| Note {
590            path: path.to_path_buf(),
591            line: problem.line,
592            message: problem.message,
593        })
594        .collect()
595}
596
597fn read_to_string(path: &Path) -> Result<String, Error> {
598    std::fs::read_to_string(path).map_err(|error| Error {
599        path: path.to_path_buf(),
600        line: None,
601        message: error.to_string(),
602    })
603}
604
605#[cfg(test)]
606mod tests {
607    use super::*;
608
609    #[test]
610    fn defaults_match_the_style_guide() {
611        let config = Config::default();
612        assert_eq!(config.format.line_length, 100);
613        assert_eq!(config.format.indent, IndentStyle::Tabs);
614        assert!(config.format.safety_checks);
615        // Reordering must be opt-in until the dependency analysis is proven.
616        assert_eq!(config.lint.code_order, CodeOrderFix::ReportOnly);
617    }
618
619    #[test]
620    fn excluded_dirs_fall_back_to_defaults() {
621        let config = Config::default();
622        assert!(config.is_excluded_dir(".git"));
623        assert!(config.is_excluded_dir(".godot"));
624        assert!(!config.is_excluded_dir("src"));
625    }
626
627    #[test]
628    fn explicit_excluded_dirs_replace_the_defaults() {
629        let config = Config {
630            excluded_dirs: vec!["vendor".to_string()],
631            ..Config::default()
632        };
633        assert!(config.is_excluded_dir("vendor"));
634        assert!(!config.is_excluded_dir(".git"));
635    }
636
637    #[test]
638    fn discover_returns_none_when_nothing_is_configured() {
639        // A directory that certainly holds no gdck.toml above it is hard to
640        // guarantee, so just check the call is total and does not panic.
641        let _ = discover(Path::new("/"));
642    }
643
644    #[test]
645    fn an_error_reads_as_a_place_and_a_reason() {
646        let error = Error {
647            path: PathBuf::from("gdck.toml"),
648            line: Some(4),
649            message: "unknown setting `foo`".to_string(),
650        };
651        assert_eq!(error.to_string(), "gdck.toml:4: unknown setting `foo`");
652        let error = Error {
653            line: None,
654            ..error
655        };
656        assert_eq!(error.to_string(), "gdck.toml: unknown setting `foo`");
657    }
658}