-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathdebug_cmd.rs
More file actions
2656 lines (2367 loc) · 84.1 KB
/
debug_cmd.rs
File metadata and controls
2656 lines (2367 loc) · 84.1 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
//! Debug commands for Cortex CLI.
//!
//! Provides diagnostic and debugging functionality:
//! - Configuration inspection
//! - File metadata and MIME detection
//! - LSP server status
//! - Ripgrep availability
//! - Skill validation
//! - Snapshot inspection
//! - Path inspection
//! - System information (OS, arch, shell, etc.)
//! - Wait for conditions
use anyhow::{Context, Result, bail};
use clap::Parser;
use cortex_engine::create_default_client;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::path::PathBuf;
use std::time::Duration;
use cortex_engine::list_sessions;
use cortex_engine::rollout::get_rollout_path;
use cortex_protocol::ConversationId;
/// Debug CLI for Cortex.
#[derive(Debug, Parser)]
pub struct DebugCli {
#[command(subcommand)]
pub subcommand: Option<DebugSubcommand>,
}
/// Debug subcommands.
#[derive(Debug, clap::Subcommand)]
pub enum DebugSubcommand {
/// Show resolved configuration and config file locations.
Config(ConfigArgs),
/// Show file metadata, MIME type, and encoding.
File(FileArgs),
/// List and test LSP servers.
Lsp(LspArgs),
/// Check ripgrep availability and test search.
Ripgrep(RipgrepArgs),
/// Parse and validate a skill file.
Skill(SkillArgs),
/// Show snapshot status and diffs.
Snapshot(SnapshotArgs),
/// Show all Cortex paths.
Paths(PathsArgs),
/// Show system information (OS, architecture, shell, etc.) for bug reports.
System(SystemArgs),
/// Wait for a condition (useful for scripts).
Wait(WaitArgs),
}
// =============================================================================
// Config subcommand
// =============================================================================
/// Arguments for config subcommand.
#[derive(Debug, Parser)]
pub struct ConfigArgs {
/// Output as JSON.
#[arg(long)]
pub json: bool,
/// Show environment variables related to Cortex.
#[arg(long)]
pub env: bool,
/// Show diff between local project config and global config.
#[arg(long)]
pub diff: bool,
}
/// Config debug output.
#[derive(Debug, Serialize)]
struct ConfigDebugOutput {
resolved: ResolvedConfig,
locations: ConfigLocations,
#[serde(skip_serializing_if = "Option::is_none")]
environment: Option<HashMap<String, String>>,
}
/// Resolved configuration values.
#[derive(Debug, Serialize)]
struct ResolvedConfig {
model: String,
provider: String,
cwd: PathBuf,
cortex_home: PathBuf,
}
/// Config file locations.
#[derive(Debug, Serialize)]
struct ConfigLocations {
global_config: PathBuf,
global_config_exists: bool,
local_config: Option<PathBuf>,
local_config_exists: bool,
}
async fn run_config(args: ConfigArgs) -> Result<()> {
let config = cortex_engine::Config::default();
let global_config = config.cortex_home.join("config.toml");
let local_config = std::env::current_dir()
.ok()
.map(|d| d.join(".cortex/config.toml"));
let resolved = ResolvedConfig {
model: config.model.clone(),
provider: config.model_provider_id.clone(),
cwd: config.cwd.clone(),
cortex_home: config.cortex_home.clone(),
};
let locations = ConfigLocations {
global_config_exists: global_config.exists(),
global_config,
local_config_exists: local_config.as_ref().is_some_and(|p| p.exists()),
local_config,
};
let environment = if args.env {
let mut env_vars = HashMap::new();
// Cortex environment variables
let cortex_vars = [
"CORTEX_HOME",
"CORTEX_MODEL",
"CORTEX_PROVIDER",
"CORTEX_API_KEY",
"CORTEX_DEBUG",
"CORTEX_LOG_LEVEL",
"CORTEX_AUTH_TOKEN",
"CORTEX_API_URL",
// Standard environment variables
"EDITOR",
"VISUAL",
"SHELL",
];
for var in cortex_vars {
if let Ok(val) = std::env::var(var) {
// Mask sensitive values (API keys, secrets, tokens, passwords, credentials)
let display_val = if is_sensitive_var_name(var) {
redact_sensitive_value(&val)
} else {
val
};
env_vars.insert(var.to_string(), display_val);
}
}
Some(env_vars)
} else {
None
};
let output = ConfigDebugOutput {
resolved,
locations,
environment,
};
if args.json {
println!("{}", serde_json::to_string_pretty(&output)?);
} else {
println!("Resolved Configuration");
println!("{}", "=".repeat(50));
println!(" Model: {}", output.resolved.model);
// Clarify that 'cortex' provider means requests go through Cortex backend
let provider_desc = if output.resolved.provider == "cortex" {
"cortex (routes to model's underlying provider)"
} else {
&output.resolved.provider
};
println!(" Provider: {}", provider_desc);
println!(" CWD: {}", output.resolved.cwd.display());
println!(" Cortex Home: {}", output.resolved.cortex_home.display());
println!();
println!("Config File Locations");
println!("{}", "-".repeat(40));
println!(
" Global: {} {}",
output.locations.global_config.display(),
if output.locations.global_config_exists {
"(exists)"
} else {
"(not found)"
}
);
if let Some(ref local) = output.locations.local_config {
println!(
" Local: {} {}",
local.display(),
if output.locations.local_config_exists {
"(exists)"
} else {
"(not found)"
}
);
}
if let Some(ref env) = output.environment {
println!();
println!("Environment Variables");
println!("{}", "-".repeat(40));
if env.is_empty() {
println!(" (no Cortex-related environment variables set)");
} else {
for (key, val) in env {
println!(" {key}={val}");
}
}
}
// Show hints about available options
println!();
println!("Tip: Use --json for machine-readable output, --env for environment variables.");
}
// Handle --diff flag: compare local and global configs
if args.diff {
println!();
println!("Config Diff (Global vs Local)");
println!("{}", "=".repeat(50));
let global_path = config.cortex_home.join("config.toml");
let local_path = std::env::current_dir()
.ok()
.map(|d| d.join(".cortex/config.toml"));
let global_content = if global_path.exists() {
std::fs::read_to_string(&global_path).ok()
} else {
None
};
let local_content = local_path.as_ref().and_then(|p| {
if p.exists() {
std::fs::read_to_string(p).ok()
} else {
None
}
});
match (global_content.as_ref(), local_content.as_ref()) {
(None, None) => {
println!(" No config files found.");
}
(Some(global), None) => {
println!(" Only global config exists.");
if args.json {
let diff_output = serde_json::json!({
"global_only": true,
"local_only": false,
"differences": [],
});
println!("{}", serde_json::to_string_pretty(&diff_output)?);
}
}
(None, Some(local)) => {
println!(" Only local config exists.");
if args.json {
let diff_output = serde_json::json!({
"global_only": false,
"local_only": true,
"differences": [],
});
println!("{}", serde_json::to_string_pretty(&diff_output)?);
}
}
(Some(global), Some(local)) => {
if global == local {
println!(" Configs are identical.");
} else {
let diff = compute_config_diff(global, local);
if args.json {
println!("{}", serde_json::to_string_pretty(&diff)?);
} else {
println!();
if !diff.only_in_global.is_empty() {
println!("Lines only in global config:");
for line in &diff.only_in_global {
println!(" - {}", line);
}
println!();
}
if !diff.only_in_local.is_empty() {
println!("Lines only in local config:");
for line in &diff.only_in_local {
println!(" + {}", line);
}
println!();
}
if !diff.unified_diff.is_empty() {
println!("Unified diff:");
println!("{}", diff.unified_diff);
}
}
}
}
}
}
Ok(())
}
/// Result of comparing two config files.
#[derive(Debug, Serialize)]
struct ConfigDiff {
only_in_global: Vec<String>,
only_in_local: Vec<String>,
unified_diff: String,
}
/// Compute diff between two config file contents.
fn compute_config_diff(global: &str, local: &str) -> ConfigDiff {
use std::collections::HashSet;
let global_lines: HashSet<&str> = global.lines().filter(|l| !l.trim().is_empty()).collect();
let local_lines: HashSet<&str> = local.lines().filter(|l| !l.trim().is_empty()).collect();
let only_in_global: Vec<String> = global_lines
.difference(&local_lines)
.map(|s| s.to_string())
.collect();
let only_in_local: Vec<String> = local_lines
.difference(&global_lines)
.map(|s| s.to_string())
.collect();
// Generate a simple unified diff
let unified_diff = generate_unified_diff(global, local);
ConfigDiff {
only_in_global,
only_in_local,
unified_diff,
}
}
/// Generate a simple unified diff output.
fn generate_unified_diff(old_content: &str, new_content: &str) -> String {
let old_lines: Vec<&str> = old_content.lines().collect();
let new_lines: Vec<&str> = new_content.lines().collect();
let mut diff_output = String::new();
diff_output.push_str("--- global/config.toml\n");
diff_output.push_str("+++ local/config.toml\n");
// Simple line-by-line comparison (not a proper LCS diff, but useful for config files)
let max_lines = old_lines.len().max(new_lines.len());
let mut has_changes = false;
for i in 0..max_lines {
let old_line = old_lines.get(i).copied();
let new_line = new_lines.get(i).copied();
match (old_line, new_line) {
(Some(o), Some(n)) if o == n => {
// Lines are the same, show context
diff_output.push_str(&format!(" {}\n", o));
}
(Some(o), Some(n)) => {
// Lines differ
has_changes = true;
diff_output.push_str(&format!("-{}\n", o));
diff_output.push_str(&format!("+{}\n", n));
}
(Some(o), None) => {
// Line only in old
has_changes = true;
diff_output.push_str(&format!("-{}\n", o));
}
(None, Some(n)) => {
// Line only in new
has_changes = true;
diff_output.push_str(&format!("+{}\n", n));
}
(None, None) => break,
}
}
if !has_changes {
String::new()
} else {
diff_output
}
}
// =============================================================================
// File subcommand
// =============================================================================
/// Arguments for file subcommand.
#[derive(Debug, Parser)]
pub struct FileArgs {
/// Path to the file to inspect.
pub path: PathBuf,
/// Output as JSON.
#[arg(long)]
pub json: bool,
}
/// File debug output.
#[derive(Debug, Serialize)]
struct FileDebugOutput {
path: PathBuf,
exists: bool,
#[serde(skip_serializing_if = "Option::is_none")]
metadata: Option<FileMetadata>,
#[serde(skip_serializing_if = "Option::is_none")]
mime_type: Option<String>,
encoding: Option<String>,
is_binary: Option<bool>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
/// Warning when the file appears to be actively modified
#[serde(skip_serializing_if = "Option::is_none")]
active_modification_warning: Option<String>,
}
/// File metadata.
#[derive(Debug, Serialize)]
struct FileMetadata {
size: u64,
/// For virtual filesystems (procfs, sysfs), stat() returns 0 but reading
/// the file may return actual content. This field stores the actual
/// content size when available.
#[serde(skip_serializing_if = "Option::is_none")]
actual_size: Option<u64>,
/// Whether the file is on a virtual filesystem (procfs, sysfs, etc.)
#[serde(skip_serializing_if = "Option::is_none")]
is_virtual_fs: Option<bool>,
is_file: bool,
is_dir: bool,
is_symlink: bool,
#[serde(skip_serializing_if = "Option::is_none")]
file_type: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
symlink_target: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
modified: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
created: Option<String>,
readonly: bool,
}
async fn run_file(args: FileArgs) -> Result<()> {
let path = if args.path.is_absolute() {
args.path.clone()
} else {
std::env::current_dir()?.join(&args.path)
};
let exists = path.exists();
// Detect special file types using stat() BEFORE attempting any reads
// This prevents blocking on FIFOs, sockets, and other special files
let special_file_type = if exists {
detect_special_file_type(&path)
} else {
None
};
let (metadata, error) = if exists {
match std::fs::metadata(&path) {
Ok(meta) => {
let modified = meta
.modified()
.ok()
.map(|t| chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339());
let created = meta
.created()
.ok()
.map(|t| chrono::DateTime::<chrono::Utc>::from(t).to_rfc3339());
// Get symlink target if applicable
let symlink_target = if meta.file_type().is_symlink() {
std::fs::read_link(&path)
.ok()
.map(|p| p.to_string_lossy().to_string())
} else {
None
};
// Check if the current user can actually write to the file
// This is more accurate than just checking permission bits
// Skip this check for special files (FIFOs, etc.) to avoid blocking
let readonly = if special_file_type.is_some() {
false // Don't check writability for special files
} else {
!is_writable_by_current_user(&path)
};
// Check if this is a virtual filesystem (procfs, sysfs, etc.)
// These report size=0 in stat() but may have actual content
let is_virtual_fs = is_virtual_filesystem(&path);
let stat_size = meta.len();
// For virtual filesystem files that report 0 size, try to read actual content size
let actual_size = if is_virtual_fs && stat_size == 0 && meta.is_file() {
// Try to read the file to get actual content size
// Limit read to 1MB to avoid hanging on infinite streams
match std::fs::read(&path) {
Ok(content) if !content.is_empty() => Some(content.len() as u64),
_ => None,
}
} else {
None
};
(
Some(FileMetadata {
size: stat_size,
actual_size,
is_virtual_fs: if is_virtual_fs { Some(true) } else { None },
is_file: meta.is_file(),
is_dir: meta.is_dir(),
is_symlink: meta.file_type().is_symlink(),
file_type: special_file_type.clone(),
symlink_target,
modified,
created,
readonly,
}),
None,
)
}
Err(e) => (None, Some(e.to_string())),
}
} else {
(None, Some("File does not exist".to_string()))
};
// Detect MIME type from extension - skip for special files
let mime_type = if exists && path.is_file() && special_file_type.is_none() {
path.extension()
.and_then(|ext| ext.to_str())
.map(|ext| guess_mime_type(ext))
} else {
None
};
// Detect encoding and binary status - SKIP for special files to avoid blocking
let (encoding, is_binary) = if exists && path.is_file() && special_file_type.is_none() {
detect_encoding_and_binary(&path)
} else {
(None, None)
};
// Check if the file appears to be actively modified by comparing
// metadata from two reads with a small delay
let active_modification_warning = if exists && path.is_file() {
// Get initial size
let initial_size = std::fs::metadata(&path).ok().map(|m| m.len());
// Brief delay to detect active writes
std::thread::sleep(std::time::Duration::from_millis(50));
// Get size again
let final_size = std::fs::metadata(&path).ok().map(|m| m.len());
match (initial_size, final_size) {
(Some(s1), Some(s2)) if s1 != s2 => Some(format!(
"File appears to be actively modified (size changed from {} to {} bytes during read). \
Content may be inconsistent.",
s1, s2
)),
_ => None,
}
} else {
None
};
let output = FileDebugOutput {
path,
exists,
metadata,
mime_type,
encoding,
is_binary,
error,
active_modification_warning,
};
if args.json {
println!("{}", serde_json::to_string_pretty(&output)?);
} else {
println!("File Debug Info");
println!("{}", "=".repeat(50));
println!(" Path: {}", output.path.display());
println!(" Exists: {}", output.exists);
if let Some(ref meta) = output.metadata {
println!();
println!("Metadata");
println!("{}", "-".repeat(40));
// Handle virtual filesystem files that report 0 size (#2829)
if meta.is_virtual_fs.unwrap_or(false) {
if let Some(actual) = meta.actual_size {
println!(
" Size: {} (stat reports 0, virtual filesystem)",
format_size(actual)
);
} else {
println!(" Size: unknown (virtual filesystem)");
}
} else {
println!(" Size: {}", format_size(meta.size));
}
// Display file type, including special types like FIFO, socket, etc.
let type_str = if let Some(ref special_type) = meta.file_type {
special_type.as_str()
} else if meta.is_file {
"file"
} else if meta.is_dir {
"directory"
} else if meta.is_symlink {
"symlink"
} else {
"unknown"
};
println!(" Type: {}", type_str);
if meta.is_virtual_fs.unwrap_or(false) {
println!(" Virtual: yes (procfs/sysfs/etc)");
}
println!(" Readonly: {}", meta.readonly);
if let Some(ref modified) = meta.modified {
println!(" Modified: {}", modified);
}
if let Some(ref created) = meta.created {
println!(" Created: {}", created);
}
}
if let Some(ref mime) = output.mime_type {
println!();
println!("Content Detection");
println!("{}", "-".repeat(40));
println!(" MIME Type: {}", mime);
}
if let Some(ref enc) = output.encoding {
println!(" Encoding: {}", enc);
}
if let Some(binary) = output.is_binary {
println!(" Binary: {}", binary);
}
if let Some(ref err) = output.error {
println!();
println!("Error: {}", err);
}
if let Some(ref warning) = output.active_modification_warning {
println!();
println!("Warning: {}", warning);
}
}
Ok(())
}
/// Guess MIME type from file extension.
fn guess_mime_type(ext: &str) -> String {
match ext.to_lowercase().as_str() {
// Text
"txt" => "text/plain",
"md" | "markdown" => "text/markdown",
"html" | "htm" => "text/html",
"css" => "text/css",
"csv" => "text/csv",
"xml" => "text/xml",
// Code
"rs" => "text/x-rust",
"js" => "text/javascript",
"ts" => "text/typescript",
"jsx" => "text/jsx",
"tsx" => "text/tsx",
"py" => "text/x-python",
"rb" => "text/x-ruby",
"go" => "text/x-go",
"java" => "text/x-java",
"c" | "h" => "text/x-c",
"cpp" | "hpp" | "cc" => "text/x-c++",
"cs" => "text/x-csharp",
"swift" => "text/x-swift",
"kt" => "text/x-kotlin",
"sh" | "bash" => "text/x-shellscript",
"ps1" => "text/x-powershell",
"sql" => "text/x-sql",
// Config
"json" => "application/json",
"yaml" | "yml" => "text/yaml",
"toml" => "text/toml",
"ini" | "cfg" => "text/plain",
// Images
"png" => "image/png",
"jpg" | "jpeg" => "image/jpeg",
"gif" => "image/gif",
"svg" => "image/svg+xml",
"webp" => "image/webp",
"ico" => "image/x-icon",
// Documents
"pdf" => "application/pdf",
"doc" => "application/msword",
"docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
// Archives
"zip" => "application/zip",
"tar" => "application/x-tar",
"gz" => "application/gzip",
// Executables
"exe" => "application/x-msdownload",
"dll" => "application/x-msdownload",
"so" => "application/x-sharedlib",
"dylib" => "application/x-mach-binary",
// Default
_ => "application/octet-stream",
}
.to_string()
}
/// Check if the current user can write to the file.
///
/// This function attempts to open the file for writing to determine
/// if the current user has write access. This is more accurate than
/// checking permission bits, as it accounts for ownership, group
/// membership, and ACLs.
fn is_writable_by_current_user(path: &std::path::Path) -> bool {
std::fs::OpenOptions::new().write(true).open(path).is_ok()
}
/// Detect special file types (FIFO, socket, block device, char device).
/// Uses stat() to determine the file type WITHOUT opening/reading the file,
/// which would block indefinitely for FIFOs and sockets.
fn detect_special_file_type(path: &std::path::Path) -> Option<String> {
#[cfg(unix)]
{
use std::os::unix::fs::FileTypeExt;
if let Ok(meta) = std::fs::metadata(path) {
let file_type = meta.file_type();
if file_type.is_fifo() {
return Some("fifo".to_string());
}
if file_type.is_socket() {
return Some("socket".to_string());
}
if file_type.is_block_device() {
return Some("block_device".to_string());
}
if file_type.is_char_device() {
return Some("char_device".to_string());
}
}
None
}
#[cfg(not(unix))]
{
// On non-Unix systems, special file types are not common
let _ = path;
None
}
}
/// Check if the path is on a virtual filesystem like procfs or sysfs.
/// These filesystems report size=0 in stat() for files that have actual content. (#2829)
#[cfg(target_os = "linux")]
fn is_virtual_filesystem(path: &std::path::Path) -> bool {
let path_str = path.to_string_lossy();
path_str.starts_with("/proc/")
|| path_str.starts_with("/sys/")
|| path_str.starts_with("/dev/")
|| path_str == "/proc"
|| path_str == "/sys"
|| path_str == "/dev"
}
/// Check if the path is on a virtual filesystem like procfs or sysfs.
/// On non-Linux systems, return false as these filesystems are Linux-specific.
#[cfg(not(target_os = "linux"))]
fn is_virtual_filesystem(_path: &std::path::Path) -> bool {
false
}
/// Detect encoding and binary status.
fn detect_encoding_and_binary(path: &PathBuf) -> (Option<String>, Option<bool>) {
// Read first 8KB to check for binary content
let Ok(file) = std::fs::File::open(path) else {
return (None, None);
};
use std::io::Read;
let mut reader = std::io::BufReader::new(file);
let mut buffer = [0u8; 8192];
let Ok(bytes_read) = reader.read(&mut buffer) else {
return (None, None);
};
let sample = &buffer[..bytes_read];
// Check for null bytes (common in binary files)
let has_null = sample.contains(&0);
// Check for UTF-8 BOM
let has_utf8_bom = sample.starts_with(&[0xEF, 0xBB, 0xBF]);
// Check for UTF-16 BOM
let has_utf16_le_bom = sample.starts_with(&[0xFF, 0xFE]);
let has_utf16_be_bom = sample.starts_with(&[0xFE, 0xFF]);
let encoding = if has_utf8_bom {
Some("UTF-8 (with BOM)".to_string())
} else if has_utf16_le_bom {
Some("UTF-16 LE".to_string())
} else if has_utf16_be_bom {
Some("UTF-16 BE".to_string())
} else if !has_null && std::str::from_utf8(sample).is_ok() {
Some("UTF-8".to_string())
} else if has_null {
Some("Binary".to_string())
} else {
Some("Unknown".to_string())
};
let is_binary = Some(has_null);
(encoding, is_binary)
}
/// Format file size in human-readable format.
fn format_size(bytes: u64) -> String {
const KB: u64 = 1024;
const MB: u64 = KB * 1024;
const GB: u64 = MB * 1024;
if bytes >= GB {
format!("{:.2} GB", bytes as f64 / GB as f64)
} else if bytes >= MB {
format!("{:.2} MB", bytes as f64 / MB as f64)
} else if bytes >= KB {
format!("{:.2} KB", bytes as f64 / KB as f64)
} else {
format!("{} B", bytes)
}
}
// =============================================================================
// LSP subcommand
// =============================================================================
/// Arguments for lsp subcommand.
#[derive(Debug, Parser)]
pub struct LspArgs {
/// Test a specific LSP server.
#[arg(long)]
pub server: Option<String>,
/// Filter by programming language (e.g., python, rust, go).
#[arg(long, short = 'l')]
pub language: Option<String>,
/// Test LSP connection for a specific file.
#[arg(long)]
pub file: Option<PathBuf>,
/// Output as JSON.
#[arg(long)]
pub json: bool,
}
/// LSP server info.
#[derive(Debug, Serialize)]
struct LspServerInfo {
name: String,
language: String,
command: String,
installed: bool,
version: Option<String>,
path: Option<PathBuf>,
}
/// LSP debug output.
#[derive(Debug, Serialize)]
struct LspDebugOutput {
servers: Vec<LspServerInfo>,
#[serde(skip_serializing_if = "Option::is_none")]
connection_test: Option<LspConnectionTest>,
}
/// LSP connection test result.
#[derive(Debug, Serialize)]
struct LspConnectionTest {
server: String,
success: bool,
#[serde(skip_serializing_if = "Option::is_none")]
latency_ms: Option<u64>,
#[serde(skip_serializing_if = "Option::is_none")]
error: Option<String>,
}
async fn run_lsp(args: LspArgs) -> Result<()> {
// Known LSP servers
let known_servers = vec![
("rust-analyzer", "Rust", "rust-analyzer"),
(
"typescript-language-server",
"TypeScript/JavaScript",
"typescript-language-server",
),
("pyright", "Python", "pyright-langserver"),
("pylsp", "Python", "pylsp"),
("gopls", "Go", "gopls"),
("clangd", "C/C++", "clangd"),
("lua-language-server", "Lua", "lua-language-server"),
("marksman", "Markdown", "marksman"),
("yaml-language-server", "YAML", "yaml-language-server"),
(
"vscode-json-language-server",
"JSON",
"vscode-json-language-server",
),
("bash-language-server", "Bash", "bash-language-server"),
("taplo", "TOML", "taplo"),
("zls", "Zig", "zls"),
];
let mut servers = Vec::new();
for (name, language, command) in known_servers {
let (installed, path, version) = check_command_installed(command).await;
servers.push(LspServerInfo {
name: name.to_string(),
language: language.to_string(),
command: command.to_string(),
installed,
version,
path,
});
}
// Filter if specific server requested
if let Some(ref server_name) = args.server {
servers.retain(|s| s.name.to_lowercase().contains(&server_name.to_lowercase()));
}
// Filter by language if specified
if let Some(ref lang) = args.language {
servers.retain(|s| s.language.to_lowercase().contains(&lang.to_lowercase()));
}
// Connection test placeholder (actual implementation would require LSP client)
let connection_test = if args.server.is_some() || args.file.is_some() {
let server = args.server.as_deref().unwrap_or("auto-detect");
Some(LspConnectionTest {
server: server.to_string(),
success: false,
latency_ms: None,
error: Some("LSP connection testing not yet implemented".to_string()),
})
} else {
None
};
let output = LspDebugOutput {
servers,
connection_test,
};
if args.json {
println!("{}", serde_json::to_string_pretty(&output)?);
} else {
println!("LSP Servers");
println!("{}", "=".repeat(60));
println!("{:<30} {:<15} {:<10}", "Server", "Language", "Status");
println!("{}", "-".repeat(60));
for server in &output.servers {
let status = if server.installed {
"installed"
} else {
"not found"
};
println!("{:<30} {:<15} {:<10}", server.name, server.language, status);
if let Some(ref path) = server.path {
println!(" Path: {}", path.display());
}
if let Some(ref version) = server.version {