chrony-confile 0.1.0

A full-featured Rust library for parsing, editing, validating, and serializing chrony configuration files
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
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
//! Chrony configuration AST types.
//!
//! This module defines the core data structures representing chrony configuration files:
//! [`ChronyConfig`], [`ConfigNode`], [`Directive`], [`DirectiveKind`] (all 96 variants),
//! and [`DirectiveCategory`].
//!
//! The sub-modules group configuration types by functional area:
//! - [`source`] -- NTP source configuration (`server`, `pool`, `peer`, `refclock`, etc.)
//! - [`selection`] -- Source selection tuning (`minsources`, `maxdistance`, etc.)
//! - [`clock`] -- System clock configuration (`driftfile`, `makestep`, etc.)
//! - [`log`] -- Logging configuration (`log`, `logdir`, etc.)
//! - [`rtc`] -- RTC configuration (`rtcfile`, `rtcdevice`, etc.)
//! - [`ntp`] -- NTP server configuration (`port`, `bindaddress`, etc.)
//! - [`cmd`] -- Command access configuration (`cmdport`, `cmdallow`, etc.)
//! - [`hw`] -- Hardware timestamping configuration (`hwtimestamp`, etc.)
//! - [`nts`] -- NTS configuration (`ntsaeads`)
//! - [`misc`] -- Miscellaneous directives (`include`, `confdir`, `user`, etc.)
//! - [`source_file`] -- `.sources` file parsing types

pub mod source;
pub mod selection;
pub mod clock;
pub mod log;
pub mod rtc;
pub mod ntp;
pub mod cmd;
pub mod hw;
pub mod nts;
pub mod misc;
pub mod source_file;

pub use source::*;
pub use selection::*;
pub use clock::*;
pub use log::*;
pub use rtc::*;
pub use ntp::*;
pub use cmd::*;
pub use hw::*;
pub use nts::*;
pub use misc::*;
pub use source_file::*;

use crate::span::Span;

/// Every chrony directive as a single enum variant.
#[derive(Debug, Clone, PartialEq)]
pub enum DirectiveKind {
    // Source
    Server(ServerConfig),
    Pool(PoolConfig),
    Peer(PeerConfig),
    InitStepSlew(InitStepSlewConfig),
    RefClock(RefClockConfig),
    Manual,
    AcquisitionPort(AcquisitionPortConfig),
    BindAcqAddress(BindAddressConfig),
    BindAcqDevice(BindDeviceConfig),
    Dscp(DscpConfig),
    DumpDir(DumpDirConfig),
    MaxSamples(MaxSamplesConfig),
    MinSamples(MinSamplesConfig),
    NtsDumpDir(NtsDumpDirConfig),
    NtsRefresh(NtsRefreshConfig),
    NtsTrustedCerts(NtsTrustedCertsConfig),
    NoSystemCert,
    NoCertTimeCheck(NoCertTimeCheckConfig),
    Refresh(RefreshConfig),

    // Selection
    AuthSelectMode(AuthSelectMode),
    CombineLimit(CombineLimitConfig),
    MaxDistance(MaxDistanceConfig),
    MaxJitter(MaxJitterConfig),
    MinSources(MinSourcesConfig),
    ReselectDist(ReselectDistConfig),
    StratumWeight(StratumWeightConfig),

    // System clock
    ClockPrecision(ClockPrecisionConfig),
    CorrTimeRatio(CorrTimeRatioConfig),
    DriftFile(DriftFileConfig),
    FallbackDrift(FallbackDriftConfig),
    LeapSecMode(LeapSecMode),
    LeapSecTz(LeapSecTzConfig),
    LeapSecList(LeapSecListConfig),
    MakeStep(MakeStepConfig),
    MaxChange(MaxChangeConfig),
    MaxClockError(MaxClockErrorConfig),
    MaxDrift(MaxDriftConfig),
    MaxUpdateSkew(MaxUpdateSkewConfig),
    MaxSlewRate(MaxSlewRateConfig),
    TempComp(TempCompConfig),

    // NTP server
    Allow(AllowDenyConfig),
    Deny(AllowDenyConfig),
    BindAddress(BindAddressConfig),
    BindDevice(BindDeviceConfig),
    Broadcast(BroadcastConfig),
    ClientLogLimit(ClientLogLimitConfig),
    NoClientLog,
    Local(LocalConfig),
    NtpSignDSocket(NtpSignDSocketConfig),
    NtsPort(NtsPortConfig),
    NtsServerCert(NtsServerCertConfig),
    NtsServerKey(NtsServerKeyConfig),
    NtsProcesses(NtsProcessesConfig),
    MaxNtsConnections(MaxNtsConnectionsConfig),
    NtsNtpServer(NtsNtpServerConfig),
    NtsRotate(NtsRotateConfig),
    Port(PortConfig),
    RateLimit(RateLimitConfig),
    NtsRateLimit(NtsRateLimitConfig),
    SmoothTime(SmoothTimeConfig),

    // Command access
    BindCmdAddress(BindCmdAddressConfig),
    BindCmdDevice(BindCmdDeviceConfig),
    CmdAllow(AllowDenyConfig),
    CmdDeny(AllowDenyConfig),
    CmdPort(CmdPortConfig),
    CmdRateLimit(CmdRateLimitConfig),
    OpenCommands(OpenCommandsConfig),

    // RTC
    HwClockFile(HwClockFileConfig),
    RtcAutoTrim(RtcAutoTrimConfig),
    RtcDevice(RtcDeviceConfig),
    RtcFile(RtcFileConfig),
    RtcOnUtc,
    RtcSync,

    // Log
    Log(LogConfig),
    LogBanner(LogBannerConfig),
    LogChange(LogChangeConfig),
    LogDir(LogDirConfig),

    // Hardware timestamping
    HwTimestamp(HwTimestampConfig),
    HwTsTimeout(HwTsTimeoutConfig),
    MaxTxBuffers(MaxTxBuffersConfig),
    PtpPort(PtpPortConfig),
    PtpDomain(PtpDomainConfig),

    // NTS
    NtsAeads(NtsAeadsConfig),

    // Miscellaneous
    ConfDir(ConfDirConfig),
    Include(IncludeConfig),
    SourceDir(SourceDirConfig),
    LockAll,
    MailOnChange(MailOnChangeConfig),
    PidFile(PidFileConfig),
    SchedPriority(SchedPriorityConfig),
    User(UserConfig),
    KeyFile(KeyFileConfig),
    DumpOnExit,
}

/// A single chrony directive with its source location and comments.
///
/// Each directive carries its original source location ([`Span`]), any leading comments
/// (comment lines immediately preceding the directive), an optional trailing comment
/// (inline comment after the directive), and the parsed directive body ([`DirectiveKind`]).
///
/// Comments are preserved for lossless round-trip serialization.
///
/// # Examples
///
/// ```rust
/// use chrony_confile::ChronyConfig;
///
/// let config: ChronyConfig = "# My NTP server\nserver ntp.example.com iburst  # preferred\n".parse()?;
///
/// let directive = config.directives().next().unwrap();
/// assert_eq!(directive.leading_comments[0], "My NTP server");
/// assert_eq!(directive.trailing_comment.as_deref(), Some("preferred"));
/// # Ok::<_, chrony_confile::ParseError>(())
/// ```
#[derive(Debug, Clone, PartialEq)]
pub struct Directive {
    /// Source location of the directive.
    pub span: Span,
    /// Comments on lines immediately preceding the directive.
    pub leading_comments: Vec<String>,
    /// An inline comment after the directive, if present.
    pub trailing_comment: Option<String>,
    /// The parsed directive body.
    pub kind: DirectiveKind,
}

impl Directive {
    /// Creates a new directive with the given kind and source span.
    pub fn new(kind: DirectiveKind, span: Span) -> Self {
        Self { span, leading_comments: Vec::new(), trailing_comment: None, kind }
    }

    /// Builder-style method to add a leading comment.
    #[must_use]
    pub fn with_leading_comment(mut self, comment: impl Into<String>) -> Self {
        self.leading_comments.push(comment.into());
        self
    }

    /// Builder-style method to add a trailing comment.
    #[must_use]
    pub fn with_trailing_comment(mut self, comment: impl Into<String>) -> Self {
        self.trailing_comment = Some(comment.into());
        self
    }
}

impl From<DirectiveKind> for Directive {
    fn from(kind: DirectiveKind) -> Self {
        Self::new(kind, Span::new(None, 0, 0, 0))
    }
}

/// A single element in a chrony configuration file.
///
/// Each line in a config file is either a directive, a comment, or a blank line.
///
/// # Examples
///
/// Comments preceding a directive are attached as leading comments to that directive
/// and do not produce a separate [`ConfigNode::Comment`]. Standalone comments (separated
/// by blank lines) produce [`ConfigNode::Comment`] nodes.
///
/// ```rust
/// use chrony_confile::{ChronyConfig, ConfigNode};
///
/// let config: ChronyConfig = "server ntp.example.com\n\n".parse()?;
///
/// assert!(matches!(config.nodes[0], ConfigNode::Directive(_)));
/// assert!(matches!(config.nodes[1], ConfigNode::BlankLine));
/// # Ok::<_, chrony_confile::ParseError>(())
/// ```
#[derive(Debug, Clone, PartialEq)]
pub enum ConfigNode {
    /// A parsed directive with its metadata.
    Directive(Box<Directive>),
    /// A comment line (excluding the leading `#` or `;`).
    Comment(String),
    /// An empty or whitespace-only line.
    BlankLine,
}

impl From<Directive> for ConfigNode {
    fn from(d: Directive) -> Self {
        Self::Directive(Box::new(d))
    }
}

impl From<DirectiveKind> for ConfigNode {
    fn from(kind: DirectiveKind) -> Self {
        Self::Directive(Box::new(Directive::from(kind)))
    }
}

/// A complete chrony configuration file.
///
/// Represents the parsed content of a `chrony.conf` file (or equivalent configuration).
/// The configuration is stored as an ordered list of [`ConfigNode`] values, preserving
/// comments, blank lines, and directives in their original order.
///
/// # Parsing
///
/// ```rust
/// use chrony_confile::ChronyConfig;
///
/// let config = ChronyConfig::parse("\
/// server ntp.example.com iburst
/// pool pool.ntp.org
/// ")?;
/// assert_eq!(config.directives().count(), 2);
/// # Ok::<_, chrony_confile::ParseError>(())
/// ```
///
/// # FromStr
///
/// ```rust
/// use chrony_confile::ChronyConfig;
///
/// let config: ChronyConfig = "server ntp.example.com\n".parse()?;
/// assert!(config.find("server").next().is_some());
/// # Ok::<_, chrony_confile::ParseError>(())
/// ```
///
/// # Serialization
///
/// ```rust
/// use chrony_confile::ChronyConfig;
///
/// let input = "server ntp.example.com iburst\n";
/// let config = ChronyConfig::parse(input)?;
/// let output = config.to_string();
/// assert_eq!(input, output);
/// # Ok::<_, chrony_confile::ParseError>(())
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
pub struct ChronyConfig {
    /// The ordered list of configuration nodes (directives, comments, blank lines).
    pub nodes: Vec<ConfigNode>,
}

impl ChronyConfig {
    /// Creates a new, empty configuration.
    pub fn new() -> Self {
        Self { nodes: Vec::new() }
    }

    /// Adds a directive to the configuration.
    ///
    /// The directive kind is converted into a full [`Directive`] with default metadata
    /// (no source span, no comments).
    ///
    /// # Examples
    ///
    /// ```rust
    /// use chrony_confile::{ChronyConfig, DirectiveKind};
    ///
    /// let mut config = ChronyConfig::new();
    /// config.push(DirectiveKind::RtcOnUtc);
    /// config.push(DirectiveKind::LockAll);
    /// assert_eq!(config.directives().count(), 2);
    /// ```
    pub fn push(&mut self, kind: DirectiveKind) {
        self.nodes.push(ConfigNode::Directive(Box::new(Directive::from(kind))));
    }

    /// Adds a fully-formed directive node to the configuration.
    pub fn push_directive(&mut self, directive: Directive) {
        self.nodes.push(ConfigNode::Directive(Box::new(directive)));
    }

    /// Adds a comment line to the configuration.
    pub fn add_comment(&mut self, comment: impl Into<String>) {
        self.nodes.push(ConfigNode::Comment(comment.into()));
    }

    /// Adds a blank line to the configuration.
    pub fn add_blank(&mut self) {
        self.nodes.push(ConfigNode::BlankLine);
    }

    /// Returns an iterator over all directives in the configuration.
    ///
    /// This excludes comments and blank lines; only [`ConfigNode::Directive`] nodes are yielded.
    pub fn directives(&self) -> impl Iterator<Item = &Directive> {
        self.nodes.iter().filter_map(|n| match n {
            ConfigNode::Directive(d) => Some(d.as_ref()),
            _ => None,
        })
    }

    /// Returns a mutable iterator over all directives in the configuration.
    ///
    /// This allows modifying directives in place while preserving their order relative
    /// to comments and blank lines.
    pub fn directives_mut(&mut self) -> impl Iterator<Item = &mut Directive> {
        self.nodes.iter_mut().filter_map(|n| match n {
            ConfigNode::Directive(d) => Some(d.as_mut()),
            _ => None,
        })
    }

    /// Find all directives with the given directive name.
    ///
    /// The name is compared case-sensitively against the directive's canonical name
    /// (lowercase). Common values include `"server"`, `"pool"`, `"driftfile"`,
    /// `"allow"`, and `"deny"`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use chrony_confile::ChronyConfig;
    ///
    /// let config: ChronyConfig = "\
    /// server ntp1.example.com
    /// server ntp2.example.com
    /// pool pool.ntp.org
    /// ".parse()?;
    ///
    /// assert_eq!(config.find("server").count(), 2);
    /// assert_eq!(config.find("pool").count(), 1);
    /// # Ok::<_, chrony_confile::ParseError>(())
    /// ```
    pub fn find(&self, name: &str) -> impl Iterator<Item = &Directive> {
        self.directives().filter(move |d| d.kind.name() == name)
    }
}

/// Categorizes directives by their functional area in chrony.
///
/// Each [`DirectiveKind`] variant maps to one category via [`DirectiveKind::category`].
/// This is useful for grouping directives when displaying or filtering configuration.
///
/// # Examples
///
/// ```rust
/// use chrony_confile::{DirectiveKind, DirectiveCategory, ServerConfig};
/// use chrony_confile::values::UdpPort;
///
/// let kind = DirectiveKind::Server(ServerConfig::default());
/// assert_eq!(kind.category(), DirectiveCategory::Source);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DirectiveCategory {
    /// NTP source configuration (`server`, `pool`, `peer`, `refclock`, etc.)
    Source,
    /// Source selection tuning (`minsources`, `maxdistance`, etc.)
    Selection,
    /// System clock configuration (`driftfile`, `makestep`, etc.)
    SystemClock,
    /// NTP server configuration (`allow`, `port`, `bindaddress`, etc.)
    NtpServer,
    /// Command access configuration (`cmdallow`, `cmdport`, etc.)
    CommandAccess,
    /// RTC configuration (`rtcfile`, `rtcdevice`, etc.)
    Rtc,
    /// Logging configuration (`log`, `logdir`, etc.)
    Log,
    /// Hardware timestamping configuration (`hwtimestamp`, etc.)
    HardwareTimestamping,
    /// NTS (Network Time Security) configuration
    Nts,
    /// Miscellaneous directives (`include`, `confdir`, `user`, etc.)
    Miscellaneous,
    /// Deprecated directives silently accepted for compatibility
    Deprecated,
}

impl DirectiveKind {
    /// Returns the canonical directive name (e.g. `"server"`, `"driftfile"`, `"allow"`).
    ///
    /// This is the lower-case name used in chrony configuration files.
    pub fn name(&self) -> &'static str {
        match self {
            Self::Server(_) => "server",
            Self::Pool(_) => "pool",
            Self::Peer(_) => "peer",
            Self::InitStepSlew(_) => "initstepslew",
            Self::RefClock(_) => "refclock",
            Self::Manual => "manual",
            Self::AcquisitionPort(_) => "acquisitionport",
            Self::BindAcqAddress(_) => "bindacqaddress",
            Self::BindAcqDevice(_) => "bindacqdevice",
            Self::Dscp(_) => "dscp",
            Self::DumpDir(_) => "dumpdir",
            Self::MaxSamples(_) => "maxsamples",
            Self::MinSamples(_) => "minsamples",
            Self::NtsDumpDir(_) => "ntsdumpdir",
            Self::NtsRefresh(_) => "ntsrefresh",
            Self::NtsTrustedCerts(_) => "ntstrustedcerts",
            Self::NoSystemCert => "nosystemcert",
            Self::NoCertTimeCheck(_) => "nocerttimecheck",
            Self::Refresh(_) => "refresh",
            Self::AuthSelectMode(_) => "authselectmode",
            Self::CombineLimit(_) => "combinelimit",
            Self::MaxDistance(_) => "maxdistance",
            Self::MaxJitter(_) => "maxjitter",
            Self::MinSources(_) => "minsources",
            Self::ReselectDist(_) => "reselectdist",
            Self::StratumWeight(_) => "stratumweight",
            Self::ClockPrecision(_) => "clockprecision",
            Self::CorrTimeRatio(_) => "corrtimeratio",
            Self::DriftFile(_) => "driftfile",
            Self::FallbackDrift(_) => "fallbackdrift",
            Self::LeapSecMode(_) => "leapsecmode",
            Self::LeapSecTz(_) => "leapsectz",
            Self::LeapSecList(_) => "leapseclist",
            Self::MakeStep(_) => "makestep",
            Self::MaxChange(_) => "maxchange",
            Self::MaxClockError(_) => "maxclockerror",
            Self::MaxDrift(_) => "maxdrift",
            Self::MaxUpdateSkew(_) => "maxupdateskew",
            Self::MaxSlewRate(_) => "maxslewrate",
            Self::TempComp(_) => "tempcomp",
            Self::Allow(_) => "allow",
            Self::Deny(_) => "deny",
            Self::BindAddress(_) => "bindaddress",
            Self::BindDevice(_) => "binddevice",
            Self::Broadcast(_) => "broadcast",
            Self::ClientLogLimit(_) => "clientloglimit",
            Self::NoClientLog => "noclientlog",
            Self::Local(_) => "local",
            Self::NtpSignDSocket(_) => "ntpsigndsocket",
            Self::NtsPort(_) => "ntsport",
            Self::NtsServerCert(_) => "ntsservercert",
            Self::NtsServerKey(_) => "ntsserverkey",
            Self::NtsProcesses(_) => "ntsprocesses",
            Self::MaxNtsConnections(_) => "maxntsconnections",
            Self::NtsNtpServer(_) => "ntsntpserver",
            Self::NtsRotate(_) => "ntsrotate",
            Self::Port(_) => "port",
            Self::RateLimit(_) => "ratelimit",
            Self::NtsRateLimit(_) => "ntsratelimit",
            Self::SmoothTime(_) => "smoothtime",
            Self::BindCmdAddress(_) => "bindcmdaddress",
            Self::BindCmdDevice(_) => "bindcmddevice",
            Self::CmdAllow(_) => "cmdallow",
            Self::CmdDeny(_) => "cmddeny",
            Self::CmdPort(_) => "cmdport",
            Self::CmdRateLimit(_) => "cmdratelimit",
            Self::OpenCommands(_) => "opencommands",
            Self::HwClockFile(_) => "hwclockfile",
            Self::RtcAutoTrim(_) => "rtcautotrim",
            Self::RtcDevice(_) => "rtcdevice",
            Self::RtcFile(_) => "rtcfile",
            Self::RtcOnUtc => "rtconutc",
            Self::RtcSync => "rtcsync",
            Self::Log(_) => "log",
            Self::LogBanner(_) => "logbanner",
            Self::LogChange(_) => "logchange",
            Self::LogDir(_) => "logdir",
            Self::HwTimestamp(_) => "hwtimestamp",
            Self::HwTsTimeout(_) => "hwtstimeout",
            Self::MaxTxBuffers(_) => "maxtxbuffers",
            Self::PtpPort(_) => "ptpport",
            Self::PtpDomain(_) => "ptpdomain",
            Self::NtsAeads(_) => "ntsaeads",
            Self::ConfDir(_) => "confdir",
            Self::Include(_) => "include",
            Self::SourceDir(_) => "sourcedir",
            Self::LockAll => "lock_all",
            Self::MailOnChange(_) => "mailonchange",
            Self::PidFile(_) => "pidfile",
            Self::SchedPriority(_) => "sched_priority",
            Self::User(_) => "user",
            Self::KeyFile(_) => "keyfile",
            Self::DumpOnExit => "dumponexit",
        }
    }

    /// Returns the category this directive belongs to.
    ///
    /// Categories group directives by their functional area: source configuration,
    /// selection tuning, system clock, NTP server, command access, RTC, logging,
    /// hardware timestamping, NTS, and miscellaneous.
    pub fn category(&self) -> DirectiveCategory {
        match self {
            Self::Server(_) | Self::Pool(_) | Self::Peer(_)
                | Self::InitStepSlew(_) | Self::RefClock(_) | Self::Manual
                | Self::AcquisitionPort(_) | Self::BindAcqAddress(_)
                | Self::BindAcqDevice(_) | Self::Dscp(_) | Self::DumpDir(_)
                | Self::MaxSamples(_) | Self::MinSamples(_) | Self::NtsDumpDir(_)
                | Self::NtsRefresh(_) | Self::NtsTrustedCerts(_)
                | Self::NoSystemCert | Self::NoCertTimeCheck(_)
                | Self::Refresh(_) => DirectiveCategory::Source,
            Self::AuthSelectMode(_) | Self::CombineLimit(_)
                | Self::MaxDistance(_) | Self::MaxJitter(_)
                | Self::MinSources(_) | Self::ReselectDist(_)
                | Self::StratumWeight(_) => DirectiveCategory::Selection,
            Self::ClockPrecision(_) | Self::CorrTimeRatio(_)
                | Self::DriftFile(_) | Self::FallbackDrift(_)
                | Self::LeapSecMode(_) | Self::LeapSecTz(_)
                | Self::LeapSecList(_) | Self::MakeStep(_)
                | Self::MaxChange(_) | Self::MaxClockError(_)
                | Self::MaxDrift(_) | Self::MaxUpdateSkew(_)
                | Self::MaxSlewRate(_) | Self::TempComp(_) => DirectiveCategory::SystemClock,
            Self::Allow(_) | Self::Deny(_) | Self::BindAddress(_)
                | Self::BindDevice(_) | Self::Broadcast(_)
                | Self::ClientLogLimit(_) | Self::NoClientLog
                | Self::Local(_) | Self::NtpSignDSocket(_)
                | Self::NtsPort(_) | Self::NtsServerCert(_)
                | Self::NtsServerKey(_) | Self::NtsProcesses(_)
                | Self::MaxNtsConnections(_) | Self::NtsNtpServer(_)
                | Self::NtsRotate(_) | Self::Port(_) | Self::RateLimit(_)
                | Self::NtsRateLimit(_) | Self::SmoothTime(_) => DirectiveCategory::NtpServer,
            Self::BindCmdAddress(_) | Self::BindCmdDevice(_)
                | Self::CmdAllow(_) | Self::CmdDeny(_)
                | Self::CmdPort(_) | Self::CmdRateLimit(_)
                | Self::OpenCommands(_) => DirectiveCategory::CommandAccess,
            Self::HwClockFile(_) | Self::RtcAutoTrim(_)
                | Self::RtcDevice(_) | Self::RtcFile(_)
                | Self::RtcOnUtc | Self::RtcSync => DirectiveCategory::Rtc,
            Self::Log(_) | Self::LogBanner(_) | Self::LogChange(_)
                | Self::LogDir(_) => DirectiveCategory::Log,
            Self::HwTimestamp(_) | Self::HwTsTimeout(_)
                | Self::MaxTxBuffers(_) | Self::PtpPort(_)
                | Self::PtpDomain(_) => DirectiveCategory::HardwareTimestamping,
            Self::NtsAeads(_) => DirectiveCategory::Nts,
            Self::ConfDir(_) | Self::Include(_) | Self::SourceDir(_)
                | Self::LockAll | Self::MailOnChange(_) | Self::PidFile(_)
                | Self::SchedPriority(_) | Self::User(_) | Self::KeyFile(_)
                | Self::DumpOnExit => DirectiveCategory::Miscellaneous,
        }
    }

    /// Returns `true` if this directive is deprecated and silently accepted for backward
    /// compatibility.
    pub fn is_deprecated(&self) -> bool {
        matches!(self, Self::DumpOnExit)
    }
}