cargo-plot 0.3.0-beta.2

Szwajcarski scyzoryk do wizualizacji struktury projektu i generowania dokumentacji bezpośrednio z poziomu Cargo.
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
// 3
use std::{
	collections::{HashMap, HashSet},
	fs,
	io::{self, Read},
	marker::PhantomData,
};

use memchr::memchr;
use walkdir::WalkDir;

// Upewnij się, że PatternsQueries i PattEnvIndex są zaimportowane poprawnie
use crate::lib::logic::{AnchoredPathsDatum, PathNode, PattEnvIndex, PatternsQueries};

const CHUNK_SIZE: usize = 4096;
const MAX_SCAN: usize = 16 * 1024; // 16 KB wystarcza w 99.9%

#[inline(always)]
pub fn is_binary_file(path: &str) -> io::Result<bool> {
	let mut file = fs::File::open(path)?;
	let mut buf = [0u8; CHUNK_SIZE];

	let mut total_read = 0usize;
	let mut bad = 0usize;

	loop {
		let n = file.read(&mut buf)?;
		if n == 0 {
			break;
		}

		let data = &buf[..n];
		total_read += n;

		if memchr(0, data).is_some() {
			return Ok(true);
		}

		for &b in data {
			if is_control_byte(b) {
				bad += 1;
			}
		}

		if bad * 100 > total_read {
			return Ok(true);
		}
		if total_read >= MAX_SCAN {
			break;
		}
	}

	Ok(false)
}

#[inline(always)]
fn is_control_byte(b: u8) -> bool { matches!(b, 0x00..=0x08 | 0x0B | 0x0C | 0x0E..=0x1F) }

// ============================================================================
// PARTITIONS & MARKERS
// ============================================================================

pub trait MatchLabel {
	type Node;
	fn label() -> &'static str;
}

#[derive(Debug, Clone)]
pub struct MatchedFile;
#[derive(Debug, Clone)]
pub struct MismatchedFile;
#[derive(Debug, Clone)]
pub struct MatchedDir;
#[derive(Debug, Clone)]
pub struct MismatchedDir;

impl MatchLabel for MatchedFile {
	type Node = ScannedFileNode; // Związane z węzłem pliku!
	fn label() -> &'static str { "✔F" } // ✔️📄
}

impl MatchLabel for MismatchedFile {
	type Node = ScannedFileNode; // Związane z węzłem pliku!
	fn label() -> &'static str { "✖F" } // ✖️📄
}

impl MatchLabel for MatchedDir {
	type Node = ScannedDirNode; // Związane z węzłem katalogu!
	fn label() -> &'static str { "✔D" } // ✔️📂
}

impl MatchLabel for MismatchedDir {
	type Node = ScannedDirNode; // Związane z węzłem katalogu!
	fn label() -> &'static str { "✖D" } // ✖️📂
}

#[derive(Debug, Clone)]
pub struct Partition<L: MatchLabel> {
	pub nodes: Vec<L::Node>, // Kompilator sam podstawi tu ScannedFileNode lub ScannedDirNode
	pub label: &'static str,
	pub tier_max: usize,
	pub name_len_max: usize,
	pub count: usize,
	_marker: PhantomData<L>,
}

impl<L: MatchLabel> Partition<L> {
	// Pomocniczy trait-like look dla L::Node, aby dobrać się do pól tier i name
	pub fn calculate_metadata(nodes: &[L::Node]) -> (usize, usize)
	where L::Node: AsMetadataNode // Musimy zdefiniować ten pomocniczy trait poniżej
	{
		let t_max = nodes.iter().map(|n| n.get_tier()).max().unwrap_or(0);
		let n_max = nodes.iter().map(|n| n.get_name().chars().count()).max().unwrap_or(0);
		(t_max, n_max)
	}
}
// Dodaj ten pomocniczy trait w fs_scanner.rs, aby Partition mogło operować na typach generycznych
pub trait AsMetadataNode {
	fn get_tier(&self) -> usize;
	fn get_name(&self) -> &str;
}

impl AsMetadataNode for ScannedFileNode {
	fn get_tier(&self) -> usize { self.tier }
	fn get_name(&self) -> &str { &self.name }
}

impl AsMetadataNode for ScannedDirNode {
	fn get_tier(&self) -> usize { self.tier }
	fn get_name(&self) -> &str { &self.name }
}
// ============================================================================
// STRUKTURY DANYCH I STATYSTYK
// ============================================================================

#[derive(Debug, Clone)]
pub struct StatsScannedTreeFs {
	pub count_dirs: usize,
	pub count_dirs_empty: usize,
	pub count_files: usize,
	pub count_files_empty: usize,
	pub count_files_text: usize,
	pub count_files_binary: usize,
	pub count_symlinks_skipped: usize,
}

#[derive(Debug, Clone)]
pub struct StatsPartitioning {
	pub count_m: usize,
	pub count_x: usize,
	pub count_m_f: usize,
	pub count_x_f: usize,
	pub count_m_d: usize,
	pub count_x_d: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub enum NodeIs {
	File,
	Dir,
}

#[derive(Debug, Clone)]
pub struct ScannedNode {
	pub name: String,
	pub path: PathNode,
	pub node: NodeIs,
	pub tier: usize,
	pub dir_has_subdirs: Option<usize>,
	pub dir_has_files_binary: Option<usize>,
	pub dir_has_files_text: Option<usize>,
	pub dir_has_symlinks: Option<usize>,
	pub file_is_binary: Option<bool>,
	pub file_is_empty: Option<bool>,
}

#[derive(Debug, Clone)]
pub struct ScannedDirNode {
	pub name: String,
	pub path: PathNode,
	pub tier: usize,
	pub has_subdirs: usize,
	pub has_files_binary: usize,
	pub has_files_text: usize,
	pub has_symlinks: usize,
}

#[derive(Debug, Clone)]
pub struct ScannedFileNode {
	pub name: String,
	pub path: PathNode,
	pub tier: usize,
	pub is_binary: bool,
	pub is_empty: bool,
}

// ============================================================================
// ENV INDEX (Baza dla filtrowania)
// ============================================================================

struct EnvIndex<'a> {
	pub dirs: HashSet<&'a str>,
	pub files: Vec<&'a str>,
}

impl<'a> PattEnvIndex for EnvIndex<'a> {
	fn has_dir(&self, dir: &str) -> bool { self.dirs.contains(dir) }

	fn has_file_with_prefix(&self, prefix: &str) -> bool {
		let start = self.files.partition_point(|&f| f < prefix);
		start < self.files.len() && self.files[start].starts_with(prefix)
	}

	fn any_file_in_dir(&self, dir: &str, check: &mut dyn FnMut(&str) -> bool) -> bool {
		let start = self.files.partition_point(|&f| f < dir);
		for &f in &self.files[start..] {
			if !f.starts_with(dir) {
				break;
			}
			if check(f) {
				return true;
			}
		}
		false
	}
}

// ============================================================================
// GŁÓWNY OBIEKT WYNIKOWY
// ============================================================================

/// Skaner i filter systemu plików (Zunifikowane)
#[derive(Debug, Clone)]
pub struct PartitionScanned {
	// Rozbite na konkretne typy partycje (pozbywamy się sztucznego markera Partition)
	pub m_f: Partition<MatchedFile>,
	pub x_f: Partition<MismatchedFile>,
	pub m_d: Partition<MatchedDir>,
	pub x_d: Partition<MismatchedDir>,

	pub stat_scan: StatsScannedTreeFs,
	pub stat_part: StatsPartitioning,
	pub stat_patt: Vec<String>,
	pub stat_work: String,
}

impl PartitionScanned {
	pub fn scan(p: &AnchoredPathsDatum, q: &PatternsQueries) -> Self {
		let mut files = Vec::new();
		let mut dirs_raw = Vec::new();
		let mut symlink_counts = HashMap::new();

		let mut count_dirs = 0;
		let mut count_dirs_empty = 0;
		let mut count_files = 0;
		let mut count_files_empty = 0;
		let mut count_files_text = 0;
		let mut count_files_binary = 0;
		let mut count_symlinks_skipped = 0;

		for e in WalkDir::new(&p.workspace_dir.buf).into_iter().filter_map(|e| e.ok()) {
			if e.depth() == 0 {
				continue;
			}

			let tier = e.depth();

			if e.path_is_symlink() {
				count_symlinks_skipped += 1;
				if let Some(parent) = e.path().strip_prefix(&p.workspace_dir.buf).ok().and_then(|p| p.parent()) {
					let parent_str = parent.to_string_lossy().replace('\\', "/");
					let formatted = if parent_str.is_empty() { "./".to_string() } else { format!("./{}/", parent_str) };
					*symlink_counts.entry(formatted).or_insert(0usize) += 1;
				}
				continue;
			}

			let Ok(rel_path) = e.path().strip_prefix(&p.workspace_dir.buf) else {
				continue;
			};
			let mut path = rel_path.to_string_lossy().replace('\\', "/");

			if e.file_type().is_dir() {
				path.push('/');
				count_dirs += 1;

				let is_empty = e.metadata().map(|m| m.is_dir()).unwrap_or(false)
					&& e.path().read_dir().map(|mut r| r.next().is_none()).unwrap_or(false);

				if is_empty {
					count_dirs_empty += 1;
				}
				dirs_raw.push((PathNode::new(format!("./{}", path).into()), tier));
			} else {
				count_files += 1;
				let abs_path = e.path();
				let is_empty = abs_path.metadata().map(|m| m.len() == 0).unwrap_or(false);
				let mut is_binary = false;

				if is_empty {
					count_files_empty += 1;
				} else {
					is_binary = is_binary_file(abs_path.to_str().unwrap_or("")).unwrap_or(false);
					if is_binary {
						count_files_binary += 1;
					} else {
						count_files_text += 1;
					}
				}

				files.push(ScannedFileNode {
					name: abs_path.file_name().unwrap_or_default().to_string_lossy().to_string(),
					path: PathNode::new(format!("./{}", path).into()),
					tier,
					is_binary,
					is_empty,
				});
			}
		}

		files.sort_unstable_by(|a, b| a.path.str.cmp(&b.path.str));
		dirs_raw.sort_unstable_by(|a, b| a.0.str.cmp(&b.0.str));

		let mut dirs = Vec::with_capacity(dirs_raw.len());
		for i in 0..dirs_raw.len() {
			let (path, tier) = dirs_raw[i].clone();
			let mut count_subdirs = 0;
			let mut count_files_binary = 0;
			let mut count_files_text = 0;
			let count_symlinks = *symlink_counts.get(&path.str).unwrap_or(&0);

			// Zliczanie plików bezpośrednich
			for f in &files {
				if f.path.str.starts_with(&path.str) {
					let remainder = &f.path.str[path.str.len()..];
					if !remainder.contains('/') {
						// Tylko bezpośrednie dzieci
						if f.is_binary {
							count_files_binary += 1;
						} else if !f.is_empty {
							count_files_text += 1;
						}
					}
				}
			}

			// Zliczanie subkatalogów bezpośrednich
			for j in (i + 1)..dirs_raw.len() {
				if dirs_raw[j].0.str.starts_with(&path.str) {
					let remainder = &dirs_raw[j].0.str[path.str.len()..];
					if !remainder.is_empty() && !remainder.trim_end_matches('/').contains('/') {
						count_subdirs += 1;
					}
				} else {
					break;
				}
			}

			dirs.push(ScannedDirNode {
				name: path.str.trim_end_matches('/').split('/').next_back().unwrap_or("").to_string(),
				path,
				tier,
				has_subdirs: count_subdirs,
				has_files_binary: count_files_binary,
				has_files_text: count_files_text,
				has_symlinks: count_symlinks,
			});
		}

		let stat_scan = StatsScannedTreeFs {
			count_dirs,
			count_dirs_empty,
			count_files,
			count_files_empty,
			count_files_text,
			count_files_binary,
			count_symlinks_skipped,
		};

		// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░
		// FAZA FILTROWANIA (Rozwiązanie problemu 'Borrow Checkera')
		// ░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░░

		// 1. Zbudowanie EnvIndex na referencjach (pożyczamy ścieżki)
		let env_index = EnvIndex {
			dirs: dirs.iter().map(|d| d.path.str.as_str()).collect(),
			files: files.iter().map(|f| f.path.str.as_str()).collect(),
		};

		// 2. Pierwszy przebieg: zbieramy TYLKO wyniki true/false do masek
		let files_matches: Vec<bool> = files.iter().map(|f| q.is_match(&f.path.str, &env_index)).collect();
		let dirs_matches: Vec<bool> = dirs.iter().map(|d| q.is_match(&d.path.str, &env_index)).collect();

		/* 3. Uwalniamy referencje - od tego momentu env_index przestaje istnieć,
		 * więc wektory files i dirs znów są 'wolne' i można je przenosić.
		 * */
		drop(env_index);

		let mut vec_m_f = Vec::new();
		let mut vec_x_f = Vec::new();
		let mut vec_m_d = Vec::new();
		let mut vec_x_d = Vec::new();

		// 4. Drugi przebieg: złączenie (zip) plików z zapisanymi wynikami (bez żadnego klonowania!)
		for (f, is_matched) in files.into_iter().zip(files_matches) {
			if is_matched {
				vec_m_f.push(f);
			} else {
				vec_x_f.push(f);
			}
		}

		for (d, is_matched) in dirs.into_iter().zip(dirs_matches) {
			if is_matched {
				vec_m_d.push(d);
			} else {
				vec_x_d.push(d);
			}
		}

		let stat_part = StatsPartitioning {
			count_m: vec_m_f.len() + vec_m_d.len(),
			count_x: vec_x_f.len() + vec_x_d.len(),
			count_m_f: vec_m_f.len(),
			count_x_f: vec_x_f.len(),
			count_m_d: vec_m_d.len(),
			count_x_d: vec_x_d.len(),
		};
		let (mf_t, mf_n) = Partition::<MatchedFile>::calculate_metadata(&vec_m_f);
		let (xf_t, xf_n) = Partition::<MismatchedFile>::calculate_metadata(&vec_x_f);
		let (md_t, md_n) = Partition::<MatchedDir>::calculate_metadata(&vec_m_d);
		let (xd_t, xd_n) = Partition::<MismatchedDir>::calculate_metadata(&vec_x_d);

		Self {
			m_f: Partition {
				nodes: vec_m_f,
				label: MatchedFile::label(),
				tier_max: mf_t,
				name_len_max: mf_n,
				count: stat_part.count_m_f, // ⚡ Używamy policzonej wartości
				_marker: PhantomData,
			},
			x_f: Partition {
				nodes: vec_x_f,
				label: MismatchedFile::label(),
				tier_max: xf_t,
				name_len_max: xf_n,
				count: stat_part.count_x_f, // ⚡ Używamy policzonej wartości
				_marker: PhantomData,
			},
			m_d: Partition {
				nodes: vec_m_d,
				label: MatchedDir::label(),
				tier_max: md_t,
				name_len_max: md_n,
				count: stat_part.count_m_d, // ⚡ Używamy policzonej wartości
				_marker: PhantomData,
			},
			x_d: Partition {
				nodes: vec_x_d,
				label: MismatchedDir::label(),
				tier_max: xd_t,
				name_len_max: xd_n,
				count: stat_part.count_x_d, // ⚡ Używamy policzonej wartości
				_marker: PhantomData,
			},
			stat_scan,
			stat_part,
			stat_patt: q.patterns.0.clone(),
			stat_work: p.workspace_dir.str.clone(),
		}
	}

	// =========================================================================
	// HELPER
	// =========================================================================

	/// Zwraca połączone i posortowane struktury ScannedNode (pliki + katalogi).
	pub fn to_scanned_nodes(&self) -> Vec<ScannedNode> {
		let total_len = self.stat_part.count_m + self.stat_part.count_x;
		let mut unified = Vec::with_capacity(total_len);

		let map_dir = |d: &ScannedDirNode| ScannedNode {
			name: d.name.clone(), // NOWE
			path: d.path.clone(),
			node: NodeIs::Dir,
			tier: d.tier,
			dir_has_subdirs: Some(d.has_subdirs),
			dir_has_files_binary: Some(d.has_files_binary),
			dir_has_files_text: Some(d.has_files_text),
			dir_has_symlinks: Some(d.has_symlinks),
			file_is_binary: None,
			file_is_empty: None,
		};

		let map_file = |f: &ScannedFileNode| ScannedNode {
			name: f.name.clone(), // NOWE
			path: f.path.clone(),
			node: NodeIs::File,
			tier: f.tier,
			dir_has_subdirs: None,
			dir_has_files_binary: None,
			dir_has_files_text: None,
			dir_has_symlinks: None,
			file_is_binary: Some(f.is_binary),
			file_is_empty: Some(f.is_empty),
		};

		unified.extend(self.m_d.nodes.iter().chain(self.x_d.nodes.iter()).map(map_dir));
		unified.extend(self.m_f.nodes.iter().chain(self.x_f.nodes.iter()).map(map_file));

		unified.sort_unstable_by(|a, b| a.path.str.cmp(&b.path.str));
		unified
	}

	// =========================================================================
	// HELPERY I ITERATORY
	// =========================================================================

	pub fn iter_nodes(&self) -> impl Iterator<Item = ScannedNode> + '_ { self.to_scanned_nodes().into_iter() }

	pub fn iter_file_paths(&self) -> impl Iterator<Item = &str> + '_ {
		self.m_f.nodes.iter().chain(self.x_f.nodes.iter()).map(|n| n.path.str.as_str())
	}

	pub fn iter_dir_paths(&self) -> impl Iterator<Item = &str> + '_ {
		self.m_d.nodes.iter().chain(self.x_d.nodes.iter()).map(|n| n.path.str.as_str())
	}

	pub fn iter_paths(&self) -> impl Iterator<Item = &str> + '_ { self.iter_file_paths().chain(self.iter_dir_paths()) }
}