Repository navigation
Expand file tree
/
Copy pathlib.rs
More file actions
4127 lines (3787 loc) · 139 KB
/
Copy pathlib.rs
File metadata and controls
4127 lines (3787 loc) · 139 KB
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
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Parse a `--help` string into a [`Command`] structure.
//!
//! The entry point is [`parse_help`]. It tries to identify which help format
//! the text comes from (clap, Python argparse, or an unknown generic format)
//! and dispatches to the appropriate sub-parser.
use anyhow::Context;
use chrono::{SecondsFormat, Utc};
use regex_lite as regex;
use strum::IntoStaticStr;
use std::sync::atomic::{AtomicUsize, Ordering};
static MAN_PAGES_READ: AtomicUsize = AtomicUsize::new(0);
static HELP_RUNS: AtomicUsize = AtomicUsize::new(0);
pub fn increment_man_pages_read() {
MAN_PAGES_READ.fetch_add(1, Ordering::Relaxed);
}
pub fn increment_help_runs() {
HELP_RUNS.fetch_add(1, Ordering::Relaxed);
}
pub fn get_man_pages_read() -> usize {
MAN_PAGES_READ.load(Ordering::Relaxed)
}
pub fn get_help_runs() -> usize {
HELP_RUNS.load(Ordering::Relaxed)
}
pub fn reset_stats() {
MAN_PAGES_READ.store(0, Ordering::Relaxed);
HELP_RUNS.store(0, Ordering::Relaxed);
}
pub fn is_sandboxing_available() -> Option<String> {
// Test if bwrap exists in PATH by trying to spawn it with --version
match std::process::Command::new("bwrap")
.arg("--version")
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.spawn()
{
Ok(mut child) => {
let _ = child.wait();
Some(
"bwrap --ro-bind / / --dev /dev --proc /proc --tmpfs /tmp --unshare-all --"
.to_string(),
)
}
_ => None,
}
}
mod bash_with_descriptions;
mod parse_help;
pub mod parse_man;
use bash_with_descriptions::try_apply_bash_descriptions;
pub use parse_help::{parse_help, parse_help_argparse, parse_help_clap, parse_help_generic};
#[derive(
Clone,
Copy,
Debug,
PartialEq,
Eq,
Default,
clap::ValueEnum,
IntoStaticStr,
serde::Serialize,
serde::Deserialize,
)]
#[value(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
pub enum SynthesisStrategy {
ManPageThenRunHelp,
ManPage,
RunHelp,
#[default]
ManPageOrRunHelp,
}
/// Settings and configuration options for flycomp synthesis.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, clap::Args)]
pub struct FlycompSettings {
/// Enable or disable flycomp for synthesizing shell completions.
#[arg(long = "enabled", default_missing_value = "true", num_args = 0..=1)]
pub enabled: Option<bool>,
/// Parsing strategy (man-page-then-run-help, man-page, run-help, man-page-or-run-help).
#[arg(long = "strategy", value_enum)]
pub strategy: Option<SynthesisStrategy>,
/// Enable or disable sandboxing (bubblewrap/bwrap).
#[arg(long = "sandbox", default_missing_value = "true", num_args = 0..=1)]
pub sandbox: Option<bool>,
/// Run execution unsandboxed (bypass bubblewrap/bwrap sandboxing).
#[arg(long = "no-sandbox", overrides_with = "sandbox")]
pub no_sandbox: bool,
/// Timeout in milliseconds for running commands during synthesis.
#[arg(long = "timeout-ms")]
pub timeout_ms: Option<u64>,
/// Maximum depth for recursive subcommand synthesis/exploration.
#[arg(long = "recurse-limit")]
pub recurse_limit: Option<usize>,
/// Directory where flycomp output should be saved.
#[arg(long = "output-dir", value_name = "DIR")]
pub output_dir: Option<String>,
/// Blacklist of command words for which flycomp prompt should be bypassed.
#[arg(long = "blacklist", value_name = "COMMANDS", num_args = 1..)]
pub blacklist: Option<Vec<String>>,
}
impl Default for FlycompSettings {
fn default() -> Self {
Self {
enabled: Some(true),
strategy: Some(SynthesisStrategy::ManPageOrRunHelp),
sandbox: Some(true),
no_sandbox: false,
timeout_ms: Some(5000),
recurse_limit: Some(2),
output_dir: None,
blacklist: Some(Vec::new()),
}
}
}
/// The status and reasoning for whether bubblewrap sandboxing will be used.
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub enum SandboxStatus {
/// Sandboxing is enabled and bubblewrap command is available.
Sandboxed(String),
/// Sandboxing was explicitly disabled via settings (`--no-sandbox` / `--sandbox false`).
DisabledInSettings,
/// Sandboxing is enabled in settings, but `bwrap` executable was not found in PATH.
BwrapNotFound,
}
impl SandboxStatus {
/// Returns true if sandboxing is active.
pub fn is_sandboxed(&self) -> bool {
matches!(self, SandboxStatus::Sandboxed(_))
}
/// Short label ("sandboxed" or "unsandboxed").
pub fn label(&self) -> &'static str {
if self.is_sandboxed() {
"sandboxed"
} else {
"unsandboxed"
}
}
/// Detailed description explaining why sandboxing is or isn't active.
pub fn description(&self) -> &str {
match self {
SandboxStatus::Sandboxed(cmd) => cmd.as_str(),
SandboxStatus::DisabledInSettings => {
"Sandboxing disabled in flycomp settings (`--no-sandbox`)."
}
SandboxStatus::BwrapNotFound => {
"bubblewrap (bwrap) not found in PATH; running completion check unsandboxed."
}
}
}
}
impl FlycompSettings {
pub fn empty() -> Self {
Self {
enabled: None,
strategy: None,
sandbox: None,
no_sandbox: false,
timeout_ms: None,
recurse_limit: None,
output_dir: None,
blacklist: None,
}
}
pub fn update(&mut self, other: FlycompSettings) {
if let Some(enabled) = other.enabled {
self.enabled = Some(enabled);
}
if let Some(strategy) = other.strategy {
self.strategy = Some(strategy);
}
if other.no_sandbox {
self.sandbox = Some(false);
self.no_sandbox = true;
} else if let Some(sandbox) = other.sandbox {
self.sandbox = Some(sandbox);
self.no_sandbox = !sandbox;
}
if let Some(timeout_ms) = other.timeout_ms {
self.timeout_ms = Some(timeout_ms);
}
if let Some(recurse_limit) = other.recurse_limit {
self.recurse_limit = Some(recurse_limit);
}
if let Some(output_dir) = other.output_dir {
self.output_dir = Some(output_dir);
}
if let Some(blacklist) = other.blacklist {
self.blacklist = Some(blacklist);
}
}
pub fn enabled(&self) -> bool {
self.enabled.unwrap_or(true)
}
pub fn strategy(&self) -> SynthesisStrategy {
self.strategy.unwrap_or(SynthesisStrategy::ManPageOrRunHelp)
}
pub fn sandbox(&self) -> bool {
if self.no_sandbox || self.sandbox == Some(false) {
false
} else {
self.sandbox.unwrap_or(true)
}
}
/// Resolves the current sandbox status considering settings and host system capabilities.
pub fn sandbox_status(&self) -> SandboxStatus {
if !self.sandbox() {
SandboxStatus::DisabledInSettings
} else if let Some(cmd) = is_sandboxing_available() {
SandboxStatus::Sandboxed(cmd)
} else {
SandboxStatus::BwrapNotFound
}
}
/// Returns the bwrap sandbox command string if sandboxing is enabled in settings
/// AND bwrap is available on the system. Returns `None` otherwise.
pub fn resolved_sandbox(&self) -> Option<String> {
match self.sandbox_status() {
SandboxStatus::Sandboxed(cmd) => Some(cmd),
_ => None,
}
}
pub fn timeout_ms(&self) -> u64 {
self.timeout_ms.unwrap_or(5000)
}
pub fn recurse_limit(&self) -> usize {
self.recurse_limit.unwrap_or(2)
}
pub fn output_dir(&self) -> Option<&str> {
self.output_dir.as_deref()
}
pub fn is_blacklisted(&self, command: &str) -> bool {
self.blacklist
.as_ref()
.map_or(false, |bl| bl.iter().any(|cmd| cmd == command))
}
pub fn add_to_blacklist(&mut self, command: String) {
let mut list = self.blacklist.take().unwrap_or_default();
if !list.contains(&command) {
list.push(command);
}
self.blacklist = Some(list);
}
}
#[derive(
Clone, Copy, Debug, clap::ValueEnum, PartialEq, Eq, serde::Serialize, serde::Deserialize,
)]
#[value(rename_all = "lower")]
pub enum OutputFormat {
Bash,
#[value(
name = "bash-with-descriptions",
alias = "bashwithdescriptions",
alias = "bash_with_descriptions"
)]
BashWithDescriptions,
Elvish,
Fish,
Powershell,
Zsh,
Json,
}
impl OutputFormat {
fn shell(&self) -> Option<clap_complete::Shell> {
match self {
OutputFormat::Bash | OutputFormat::BashWithDescriptions => {
Some(clap_complete::Shell::Bash)
}
OutputFormat::Elvish => Some(clap_complete::Shell::Elvish),
OutputFormat::Fish => Some(clap_complete::Shell::Fish),
OutputFormat::Powershell => Some(clap_complete::Shell::PowerShell),
OutputFormat::Zsh => Some(clap_complete::Shell::Zsh),
OutputFormat::Json => None,
}
}
}
// ──────────────────────────────────────────────────────────────────────────────
// Public data structures
// ──────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, Default)]
#[serde(rename_all = "kebab-case")]
pub enum ValueHint {
#[default]
Unknown,
Other,
AnyPath,
FilePath,
DirPath,
ExecutablePath,
CommandName,
CommandString,
CommandWithArguments,
Username,
Hostname,
Url,
EmailAddress,
EnvVar,
NetworkInterface,
GitBranch,
GitRevision,
SystemdUnit,
Integral,
}
/// A single command-line argument / flag.
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
pub struct Arg {
/// Long flag name, e.g. `--verbose`.
pub long: Option<String>,
/// Short flag name, e.g. `-v`.
pub short: Option<String>,
/// Human-readable description.
pub description: Option<String>,
/// Meta-variable / value name hint (e.g. `<PATH>`, `<N>`).
pub value_name: Option<String>,
/// Number of values accepted (e.g. `*`, `+`, `?`, or a count like `"1"`).
pub num_args: Option<String>,
/// Possible values for the option.
pub value_enum: Option<Vec<String>>,
/// Completion hint for the option value.
pub value_hint: ValueHint,
}
impl Arg {
pub fn takes_value(&self) -> bool {
self.value_name.is_some()
|| self.num_args.is_some()
|| self.short.as_ref().map_or(false, |s| s.ends_with('#'))
|| self.long.as_ref().map_or(false, |l| l.ends_with('#'))
}
}
/// A parsed command (or sub-command).
#[derive(Debug, Clone, Default, PartialEq, serde::Serialize)]
pub struct Command {
/// Name of the command, if known.
pub name: Option<String>,
/// Subcommand aliases.
pub aliases: Vec<String>,
/// Author / maintainer information, if present.
pub author: Option<String>,
/// Short description / about line.
pub description: Option<String>,
/// Recognised arguments / flags.
pub args: Vec<Arg>,
/// Recognised sub-commands.
pub subcommands: Vec<Command>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, serde::Serialize, IntoStaticStr)]
#[serde(rename_all = "kebab-case")]
#[strum(serialize_all = "kebab-case")]
enum SynthesisMethod {
ManPage,
RunHelp,
}
#[derive(Debug, Clone, PartialEq)]
struct SynthesisOutcome {
command: Command,
strategy_used: SynthesisMethod,
}
#[derive(Debug, Clone, serde::Serialize)]
struct JsonMetadata {
flycomp_version: &'static str,
git_hash: &'static str,
build_time: &'static str,
generated_at: String,
output_format: &'static str,
requested_strategy: &'static str,
strategy_used: &'static str,
sandboxed: bool,
timeout_ms: u64,
command_path: String,
man_pages_read: usize,
help_runs: usize,
}
#[derive(Debug, Clone, serde::Serialize)]
struct JsonCompletionOutput {
metadata: JsonMetadata,
command: Command,
}
impl Command {
pub fn expand_no_options(&mut self) {
let mut expanded_args = Vec::new();
for arg in std::mem::take(&mut self.args) {
if let Some(long) = &arg.long {
if long.contains("[no-]") {
let base = long.replace("[no-]", "");
let no_variant = long.replace("[no-]", "no-");
let mut arg1 = arg.clone();
arg1.long = Some(base);
expanded_args.push(arg1);
let mut arg2 = arg.clone();
arg2.long = Some(no_variant);
arg2.short = None;
expanded_args.push(arg2);
} else if long.contains("[no]") {
let base = long.replace("[no]", "");
let no_variant = long.replace("[no]", "no");
let mut arg1 = arg.clone();
arg1.long = Some(base);
expanded_args.push(arg1);
let mut arg2 = arg.clone();
arg2.long = Some(no_variant);
arg2.short = None;
expanded_args.push(arg2);
} else {
expanded_args.push(arg);
}
} else {
expanded_args.push(arg);
}
}
self.args = expanded_args;
for sub in &mut self.subcommands {
sub.expand_no_options();
}
}
pub fn resolve_alias_args(&mut self) {
let mut aliases_to_merge = Vec::new();
let mut i = 0;
while i < self.args.len() {
let arg = &self.args[i];
if arg.short.is_some() && arg.long.is_none() {
if let Some(desc) = &arg.description {
let desc_lower = desc.to_lowercase();
if let Some(pos) = desc_lower.find("alias for --") {
let target_long = &desc_lower[pos + "alias for --".len()..];
let target_long =
target_long.split_whitespace().next().unwrap_or("").trim();
let target_long = target_long.trim_end_matches(|c: char| {
c.is_ascii_punctuation() && c != '_' && c != '-'
});
if !target_long.is_empty() {
aliases_to_merge.push((i, format!("--{}", target_long)));
}
}
}
}
i += 1;
}
let mut to_remove = std::collections::HashSet::new();
for (alias_idx, target_long) in aliases_to_merge {
if let Some(target_idx) = self
.args
.iter()
.position(|a| a.long.as_ref() == Some(&target_long))
{
let short_val = self.args[alias_idx].short.clone();
self.args[target_idx].short = short_val;
to_remove.insert(alias_idx);
}
}
if !to_remove.is_empty() {
let mut new_args = Vec::new();
for (idx, arg) in self.args.drain(..).enumerate() {
if !to_remove.contains(&idx) {
new_args.push(arg);
}
}
self.args = new_args;
}
for sub in &mut self.subcommands {
sub.resolve_alias_args();
}
}
pub fn deduplicate_args(&mut self) {
self.resolve_alias_args();
let mut unique_args: Vec<Arg> = Vec::new();
for arg in std::mem::take(&mut self.args) {
let mut found_idx = None;
if let Some(ref long) = arg.long {
found_idx = unique_args
.iter()
.position(|a| a.long.as_ref() == Some(long));
}
if found_idx.is_none() {
if let Some(ref short) = arg.short {
found_idx = unique_args
.iter()
.position(|a| a.short.as_ref() == Some(short));
}
}
if let Some(idx) = found_idx {
let existing = &mut unique_args[idx];
if existing.short.is_none() {
existing.short = arg.short;
}
if existing.long.is_none() {
existing.long = arg.long;
}
if existing.value_name.is_none() {
existing.value_name = arg.value_name;
}
if existing.num_args.is_none() {
existing.num_args = arg.num_args;
}
if existing.value_hint == ValueHint::Unknown {
existing.value_hint = arg.value_hint;
}
if let (Some(d1), Some(d2)) = (&existing.description, &arg.description) {
if d1 != d2 && !d1.contains(d2) {
existing.description = Some(format!("{} {}", d1, d2));
}
} else if existing.description.is_none() {
existing.description = arg.description;
}
match (&mut existing.value_enum, arg.value_enum) {
(Some(v1), Some(v2)) => {
for val in v2 {
if !v1.contains(&val) {
v1.push(val);
}
}
}
(None, Some(v2)) => {
existing.value_enum = Some(v2);
}
_ => {}
}
} else {
unique_args.push(arg);
}
}
self.args = unique_args;
for sub in &mut self.subcommands {
sub.deduplicate_args();
}
}
pub fn populate_possible_values(&mut self) {
for arg in &mut self.args {
if arg.value_enum.is_none() {
let should_parse = if arg.takes_value() {
true
} else {
arg.description
.as_ref()
.map_or(false, |desc| desc.contains("/="))
};
if should_parse {
arg.value_enum = parse_possible_values(
arg.value_name.as_deref(),
arg.description.as_deref(),
);
}
}
if arg.value_hint == ValueHint::Unknown {
if arg.takes_value() {
arg.value_hint =
extract_value_hint(arg.value_name.as_deref(), arg.description.as_deref());
}
}
}
for sub in &mut self.subcommands {
sub.populate_possible_values();
}
}
}
pub fn extract_value_hint(value_name: Option<&str>, description: Option<&str>) -> ValueHint {
let name_lower = value_name.map(|s| s.to_lowercase());
let desc_lower = description.map(|s| s.to_lowercase());
// Helper to check if name contains a substring
let name_contains = |substring: &str| {
if let Some(ref name) = name_lower {
name.contains(substring)
} else {
false
}
};
// Helper to check if desc contains a substring
let desc_contains = |substring: &str| {
if let Some(ref desc) = desc_lower {
desc.contains(substring)
} else {
false
}
};
// Helper to check if name contains a specific word (boundary-aware)
let name_has_word = |word: &str| -> bool {
if let Some(ref name) = name_lower {
let mut start = 0;
while let Some(pos) = name[start..].find(word) {
let actual_pos = start + pos;
let char_before_ok = if actual_pos > 0 {
if let Some(prev_char) = name[..actual_pos].chars().next_back() {
!prev_char.is_alphanumeric()
} else {
true
}
} else {
true
};
let char_after_ok = if actual_pos + word.len() < name.len() {
if let Some(next_char) = name[actual_pos + word.len()..].chars().next() {
!next_char.is_alphanumeric()
} else {
true
}
} else {
true
};
if char_before_ok && char_after_ok {
return true;
}
if let Some((offset, _)) = name[actual_pos..].char_indices().nth(1) {
start = actual_pos + offset;
} else {
break;
}
}
}
false
};
// Helper to check if desc contains a specific word (boundary-aware)
let desc_has_word = |word: &str| -> bool {
if let Some(ref desc) = desc_lower {
let mut start = 0;
while let Some(pos) = desc[start..].find(word) {
let actual_pos = start + pos;
let char_before_ok = if actual_pos > 0 {
if let Some(prev_char) = desc[..actual_pos].chars().next_back() {
!prev_char.is_alphanumeric()
} else {
true
}
} else {
true
};
let char_after_ok = if actual_pos + word.len() < desc.len() {
if let Some(next_char) = desc[actual_pos + word.len()..].chars().next() {
!next_char.is_alphanumeric()
} else {
true
}
} else {
true
};
if char_before_ok && char_after_ok {
return true;
}
if let Some((offset, _)) = desc[actual_pos..].char_indices().nth(1) {
start = actual_pos + offset;
} else {
break;
}
}
}
false
};
// 1. Check value_name first (high precision)
if name_has_word("int")
|| name_contains("integer")
|| name_has_word("num")
|| name_contains("number")
|| name_contains("count")
|| name_contains("index")
|| name_contains("port")
|| name_has_word("pid")
|| name_has_word("uid")
|| name_has_word("gid")
|| name_has_word("offset")
|| name_has_word("limit")
|| name_has_word("n")
{
return ValueHint::Integral;
}
if name_has_word("url") || name_has_word("uri") {
return ValueHint::Url;
}
if name_has_word("email") {
return ValueHint::EmailAddress;
}
if name_contains("hostname")
|| name_has_word("host")
|| name_has_word("domain")
|| name_lower.as_ref().map_or(false, |n| n.ends_with("domain"))
|| name_has_word("address")
|| name_lower
.as_ref()
.map_or(false, |n| n.ends_with("address"))
{
return ValueHint::Hostname;
}
if name_contains("username") || name_contains("user_name") || name_contains("user-name") {
return ValueHint::Username;
}
if name_contains("command")
|| name_has_word("cmd")
|| name_lower.as_ref().map_or(false, |n| n.ends_with("cmd"))
{
if name_contains("line") || name_contains("string") {
return ValueHint::CommandString;
}
return ValueHint::CommandName;
}
if name_has_word("executable") || name_has_word("binary") {
return ValueHint::ExecutablePath;
}
if name_has_word("dir")
|| name_contains("directory")
|| name_contains("folder")
|| name_lower.as_ref().map_or(false, |n| n.ends_with("dir"))
{
return ValueHint::DirPath;
}
if name_contains("env-var") || name_contains("envvar") || name_contains("env_var") {
return ValueHint::EnvVar;
}
if name_has_word("interface") || name_has_word("iface") {
return ValueHint::NetworkInterface;
}
if name_has_word("branch") {
return ValueHint::GitBranch;
}
if name_has_word("revision") || name_has_word("commit") {
return ValueHint::GitRevision;
}
if name_has_word("service")
|| (name_has_word("unit")
&& !desc_contains("time")
&& !desc_contains("size")
&& !desc_contains("bytes")
&& !desc_contains("speed")
&& !desc_contains("duration")
&& !desc_contains("interval")
&& !desc_contains("format")
&& !desc_contains("measure"))
{
return ValueHint::SystemdUnit;
}
// Dict, Log, Archive, and File are FilePaths
if name_has_word("file")
|| name_lower
.as_ref()
.map_or(false, |n| n.ends_with("file") && n != "profile")
|| name_contains("filename")
|| name_contains("filepath")
|| name_has_word("dict")
|| name_contains("dictionary")
|| name_has_word("log")
|| name_contains("logfile")
|| name_has_word("archive")
{
// Exclude "level" to avoid "log-level" or "log_level" matching file
if !name_contains("level") {
return ValueHint::FilePath;
}
}
if name_has_word("path") || name_lower.as_ref().map_or(false, |n| n.ends_with("path")) {
if desc_contains("directory") || desc_contains("folder") {
return ValueHint::DirPath;
}
if desc_contains("file") && !desc_contains("files") {
return ValueHint::FilePath;
}
return ValueHint::AnyPath;
}
if name_contains("unix:") || name_contains("socket") {
return ValueHint::AnyPath;
}
// 2. Check description (lower precision, needs more specific phrases)
if desc_contains("http://")
|| desc_contains("https://")
|| desc_has_word("url")
|| desc_has_word("uri")
|| desc_contains("endpoint")
{
return ValueHint::Url;
}
if desc_has_word("email") || desc_has_word("e-mail") {
return ValueHint::EmailAddress;
}
if desc_contains("hostname")
|| desc_contains("host name")
|| desc_contains("domain name")
|| desc_contains("ip address")
|| desc_contains("ipv4")
|| desc_contains("ipv6")
|| desc_contains("dns name")
|| desc_contains("target host")
|| desc_contains("remote host")
|| desc_contains("server address")
{
return ValueHint::Hostname;
}
if desc_contains("username") || desc_contains("user name") || desc_contains("login name") {
return ValueHint::Username;
}
if (desc_contains("command line") || desc_contains("command-line"))
&& !desc_contains("command line file")
&& !desc_contains("command-line file")
&& !desc_contains("command line directory")
&& !desc_contains("command-line directory")
&& !desc_contains("command line dir")
&& !desc_contains("command-line dir")
&& !desc_contains("command line arg")
&& !desc_contains("command-line arg")
&& !desc_contains("command line option")
&& !desc_contains("command-line option")
&& !desc_contains("command line flag")
&& !desc_contains("command-line flag")
&& !desc_contains("command line parameter")
&& !desc_contains("command-line parameter")
&& !desc_contains("command line param")
&& !desc_contains("command-line param")
{
return ValueHint::CommandString;
}
if desc_contains("command name") || desc_contains("cmd name") {
return ValueHint::CommandName;
}
if desc_contains("path to executable")
|| desc_contains("path to binary")
|| desc_contains("path to command")
|| desc_contains("executable file")
|| desc_contains("binary file")
{
return ValueHint::ExecutablePath;
}
if desc_contains("environment variable")
|| desc_contains("env variable")
|| desc_contains("env-var")
|| (desc_contains("variable") && desc_contains("environment"))
{
let is_non_env_var_name = if let Some(ref name) = name_lower {
name == "string"
|| name == "suffix"
|| name == "prefix"
|| name == "pattern"
|| name == "glob"
|| name == "command"
|| name == "cmd"
|| name == "file"
|| name == "dir"
|| name == "directory"
|| name == "path"
|| name == "format"
|| name == "date"
|| name == "time"
} else {
false
};
if !is_non_env_var_name {
return ValueHint::EnvVar;
}
}
if desc_contains("network interface") {
return ValueHint::NetworkInterface;
}
if desc_contains("git branch") {
return ValueHint::GitBranch;
}
if desc_contains("git revision") || desc_contains("git commit") {
return ValueHint::GitRevision;
}
if desc_contains("systemd service") || desc_contains("systemd unit") {
return ValueHint::SystemdUnit;
}
if desc_contains("port number")
|| desc_contains("process id")
|| desc_contains("user id")
|| desc_contains("group id")
|| desc_contains("number of")
|| desc_has_word("port")
|| desc_has_word("int")
|| desc_has_word("integer")
|| desc_has_word("count")
{
return ValueHint::Integral;
}
let is_known_non_path_value = if let Some(ref name) = name_lower {
name == "when"
|| name == "mode"
|| name == "type"
|| name == "format"
|| name == "how"
|| name == "value"
|| name == "val"
|| name == "values"
|| name == "key"
|| name == "lang"
|| name == "language"
|| name == "locale"
|| name == "encoding"
|| name == "charset"
|| name == "bool"
|| name == "boolean"
|| name == "level"
|| name == "width"
|| name == "height"
|| name == "size"
|| name == "count"
|| name == "num"
|| name == "number"
|| name == "color"
|| name == "colour"
|| name == "speed"
|| name == "rate"
|| name == "delay"
|| name == "timeout"
|| name == "pattern"
|| name == "patterns"
|| name == "glob"
|| name == "action"
|| name == "actions"
|| name == "sep"
|| name == "separator"
|| name == "date"
|| name == "time"
|| name == "datetime"
|| name == "timestamp"
|| name == "expression"
|| name == "expr"
|| name == "string"
|| name == "suffix"
|| name == "prefix"
|| name == "ext"
|| name == "extension"
|| name == "style"
|| name == "keyword"
|| name == "name"
|| name == "regex"
|| name == "regexp"
|| name == "symbol"
|| name == "token"
} else {
false
};
// Paths/Directories/Files in description
if !is_known_non_path_value {
if desc_contains("directory path")
|| desc_contains("folder path")
|| desc_contains("path to directory")
|| desc_contains("path to folder")
{