normalizefs 0.0.11

Normalization of file system paths
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
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
/*
Normalization of file system paths.

Written by Radim Kolar <hsn@sendmail.cz> 2025
https://gitlab.com/hsn10/normalizefs

This is free and unencumbered software released into the public domain.
For more information, please refer to <https://unlicense.org/>

CC0: This work has been marked as dedicated to the public domain.
For more information, please refer to <https://creativecommons.org/public-domain/cc0/>

SPDX-License-Identifier: Unlicense OR CC0-1.0
*/

#![forbid(unsafe_code)]
#![forbid(missing_docs)]
#![forbid(clippy::missing_errors_doc)]


//!   Normalization of file system paths.
//!
//!   Independant Rust implementation of file path normalizer.
//!   This crate can normalize POSIX, Windows UNC, Windows with drive and
//!   Windows with drive relative.

use std::{ops::Index, path::{Path, PathBuf}};


#[path = "pathconv.rs"]
mod pathconv;

/**

  Convert path to absolute form.

  If input is relative and we can't query current directory
  error is returned.

  ### Parameters

  `path` - what we want to convert

  ### Returns

  Result holding PathBuf containing absolute version of `path`

  ### Errors

  Error is returned if current dir is inaccessible
```rust
use normalizefs::canonicalize;
let res = canonicalize ( "./demo" );
if let Ok(path) = res {
   println!("Absolute path is {}", path.display());
}
```
*/
pub fn canonicalize(path: impl AsRef<Path>) -> std::io::Result<PathBuf> {
   // Convert trait AsRef to a Path reference
   let path = path.as_ref();

   match path.is_relative() {
      // convert path to absolute form by
      // appending it to current_dir
      true => match std::env::current_dir() {
         Ok(current_dir) => Ok(current_dir.join(path)),
         Err(e) => Err(e),
      },
      // path is already absolute
      false => Ok(path.to_path_buf()),
   }
}

macro_rules! make_pub_posix2 {
    ($(#[$meta:meta])* $vis:vis fn $name:ident $args:tt -> $ret:ty $body:block) => {
        #[cfg(feature = "posix")]
        $(#[$meta])*
        pub fn $name $args -> $ret $body

        #[cfg(any(test,all(target_family = "unix", not(feature = "posix"))))]
        fn $name $args -> $ret $body
    };
}

macro_rules! make_pub_win2 {
    ($(#[$meta:meta])* $vis:vis fn $name:ident $args:tt -> $ret:ty $body:block) => {
        #[cfg(feature = "windows")]
        $(#[$meta])*
        pub fn $name $args -> $ret $body

        #[cfg(any(test,all(target_os = "windows", not(feature = "windows"))))]
        fn $name $args -> $ret $body
    };
}

/**

   Normalize path according to current os
*/
pub fn normalize(path: impl AsRef<Path>) -> PathBuf {
   #[cfg(target_family = "windows")]
   { normalize_windows(path) }

   #[cfg(target_family = "unix")]
   { normalize_posix(path) }
}

make_pub_posix2!{
/**

   Normalizes POSIX path

   Normalize function doesn't prevent from going to parent
   directory. This is similar behaviour to JavaScript and Python.
*/
pub fn normalize_posix(path: impl AsRef<Path>) -> PathBuf {
   let mut p = pathconv::path_to_vector(path);
   remove_double_separators(&mut p, '/');
   remove_start_dot_slash(&mut p, '/');
   remove_slash_dot_slash(&mut p, '/');
   remove_end_dot(&mut p, '/');
   resolve_end_updir(&mut p, '/');
   resolve_updirs(&mut p, '/');
   pathconv::vector_to_pathbuf(p)
}
}

make_pub_win2!{
/**

   Normalizes Windows path

   Normalize function doesn't prevent from going to parent
   directory. This is similar behaviour to JavaScript and Python.
*/
fn normalize_windows(path: impl AsRef<Path>) -> PathBuf {
   let mut p: Vec<char> = pathconv::path_to_vector(path);
   replace_slashes(&mut p, '/', '\\');
   unc_remove_extra_backslashes(&mut p);
   normalize_unc(&mut p);
   normalize_drive(&mut p);
   let prefix_len = windows_prefix_len(&p);
   let prefix: Vec<char> =
   if prefix_len > 0 {
      p.drain(..prefix_len).collect()
   } else {
      Vec::<char>::new()
   };
   remove_start_dot_slash(&mut p, '\\');
   remove_slash_dot_slash(&mut p, '\\');
   remove_end_dot(&mut p, '\\');
   resolve_end_updir(&mut p, '\\');
   resolve_updirs(&mut p, '\\');
   p.splice(..0, prefix);
   pathconv::vector_to_pathbuf(p)
}
}

/**

   Checks if path is absolute according to current os
*/
pub fn is_absolute(path: impl AsRef<Path>) -> bool {
   #[cfg(target_family = "windows")]
   { is_absolute_windows(path) }

   #[cfg(target_family = "unix")]
   { is_absolute_posix(path) }
}

make_pub_posix2!{
/**

   Check if POSIX path is absolute

   POSIX path is considered absolute if it starts with '/'.
   This function won't panic on invalid UTF-8 input.
*/
fn is_absolute_posix(path: impl AsRef<Path>) -> bool {
   // Convert the `Path` to a string slice
   if let Some(first_char) = path.as_ref().to_string_lossy().chars().next() {
      if first_char == '/' {
         true
      } else {
         // first char is not '/'
         false
      }
   } else {
      // empty path, no first char exists
      false
   }
}
}

make_pub_win2!{
/**

   Check if Windows path is absolute

   Windows path is considered absolute if it starts with UNC identifier '\\\\'
   or with drive 'C:\\'
   This function won't panic on invalid UTF-8 input.
*/
fn is_absolute_windows(path: impl AsRef<Path>) -> bool {
   /* check if character is any slash */
   fn any_slash(c: char) -> bool {
      c == '/' || c == '\\'
   }
   #[allow(non_snake_case)]
   /* get character at position */
   fn charAt(s: impl AsRef<str>, pos: usize) -> char {
      s.as_ref().chars().nth(pos).unwrap()
   }
   // convert path to string
   let str = path.as_ref().to_string_lossy();
   // string must be at least 3 characters long
   if str.len() >=3 {
      // case 1 unc path \\server\res
      // case 2 unc path with extra slashes \\\\server\res
      if any_slash(charAt(&str, 0)) && any_slash(charAt(&str, 1)) &&
         ( charAt(&str,2).is_ascii_alphabetic() || any_slash(charAt(&str, 2)) ) {
         true
      // case 3 drive with root c:\
      } else if charAt(&str,0).is_ascii_alphabetic() && charAt(&str,1) == ':' && any_slash(charAt(&str, 2)) {
         true
      } else {
         false
      }
   } else {
      // too short path
      false
   }
}
}

/**

   Joins two paths according to current os
*/
pub fn join(base: impl AsRef<Path>, append: impl AsRef<Path>) -> PathBuf {
   #[cfg(target_family = "windows")]
   { join_windows(base, append) }

   #[cfg(target_family = "unix")]
   { join_posix(base, append) }
}

make_pub_posix2!{
/**

   Join posix paths

   Returned path is normalized
*/
fn join_posix(base: impl AsRef<Path>, append: impl AsRef<Path>) -> PathBuf {
   if is_absolute_posix(&append) {
      normalize_posix(append)
   } else if append.as_ref().as_os_str().is_empty() {
      normalize_posix(base)
   } else
   {
      let mut joined = pathconv::path_to_vector(base);
      joined.push('/');
      joined.append(&mut pathconv::path_to_vector(append));
      normalize_posix(pathconv::vector_to_pathbuf(joined))
   }
}
}

make_pub_win2!{
/**

   Join Windows paths

   Returned path is normalized
*/
fn join_windows(base: impl AsRef<Path>, append: impl AsRef<Path>) -> PathBuf {
   if is_absolute_windows(&append) {
      // append is absolute, overwrite base
      normalize_windows(append)
   } else if append.as_ref().as_os_str().is_empty() {
      // append is empty, return base
      normalize_windows(base)
   } else
   {
      // append is relative
      let mut base1 = pathconv::path_to_vector(&base);
      let mut append2 = pathconv::path_to_vector(&append);
      let havedrive2 = have_drive(&append2);
      if havedrive2 == false {
         // append doesn't have drive, do simple join
         base1.push('\\');
         base1.append(&mut append2);
         normalize_windows(pathconv::vector_to_pathbuf(base1))
      } else {
         // we have drive on append path
         let havedrive1 = have_drive(&base1);
         if havedrive1 == true {
            // we have both drives
            normalize_drive(&mut base1);
            normalize_drive(&mut append2);
            if base1[0] == append2[0] {
               // same drives, remove drive at append
               append2.drain(0..2);
               // and join
               base1.push('\\');
               base1.append(&mut append2);
            } else {
               // different drives, overwrite base
               base1.clear();
               base1.append(&mut append2);
            }
            normalize_windows(pathconv::vector_to_pathbuf(base1))
         } else {
            // we have drive-relative on append but no drive on base
            // remove drive from append
            append2.drain(0..2);
            // and join
            base1.push('\\');
            base1.append(&mut append2);
            normalize_windows(pathconv::vector_to_pathbuf(base1))
         }
      }
   }
}
}

/**

   Removes extra separators but keeping two first '\\\\'
   used for marking UNC path on windows.

   Code assumes that separators are already converted
   to backslashes.
*/
fn unc_remove_extra_backslashes(path: &mut Vec<char>) {
   if path.len() >= 1 {
      if let Some(&first) = path.first() {
         if first == '\\' {
            path.remove(0);
            remove_double_separators(path, '\\');
            path.insert(0, '\\');
         } else {
            // no need to be UNC aware
            remove_double_separators(path, '\\');
         }
      }
   }
}

/**

   Windows UNC normalizer.
   Converts both server and share name to lowercase
   while rest of path is left untouched.

   Code assumes that separators are already converted
   to backslashes and extra backslashes are removed.
*/
fn normalize_unc(path: &mut Vec<char>) {
   if path.len() >= 3 {
      if path[0] == '\\' && path[1] == '\\' {
         // it is an UNC path
         // We need to normalize \\SERVER\SHARE\Directory
         let mut slash_count = 0;
         for ch in path.iter_mut().skip(2) {
            if *ch == '\\' {
               slash_count += 1;
            } else if ch.is_ascii_uppercase() {
               *ch = ch.to_ascii_lowercase();
            };
            if slash_count == 2 {
                return;
            };
         }
      }
   }
}

/**

   Windows drive letter normalizer.

   Normalizes drive letter to uppercase.
*/
fn normalize_drive(path: &mut Vec<char>) {
   if path.len() >= 2 {
      if path[1] == ':' {
         // path with drive specification
         if path[0].is_ascii_lowercase() {
            path[0] = path[0].to_ascii_uppercase();
         }
      }
   }
}

/**

   Checks if path starts with Windows drive letter
*/
fn have_drive(path: & Vec<char>) -> bool {
   if path.len()>= 2 {
      if path[0].is_ascii_alphabetic() && path[1] == ':' {
         true
      } else {
         false
      }
   } else {
     false
   }
}

/**

   Replaces double or more separators by just one
*/
fn remove_double_separators(path: &mut Vec<char>, separator: char) {
   let mut i = 0;
   let mut previous = false;
   while i < path.len() {
      if *path.index(i) == separator {
         if previous {
            path.remove(i);
            i -= 1;
         } else {
            previous = true;
         }
      } else {
         previous = false;
      }
      i += 1;
   }
}

/**

   Replaces characters

   Used for converting '/' into '\\' but any character replacement
   is possible.
*/
fn replace_slashes(path: &mut Vec<char>, from: char, to: char) {
   for c in path.iter_mut() {
      if *c == from {
         *c = to;
      }
   }
}

/**

  Removes initial dot slash - current dir reference

  Cases:
   * ./dir - dir
   * ././dir - dir
*/
fn remove_start_dot_slash(path: &mut Vec<char>, separator: char) {
   // is path long enough to include "./" ?
   while path.len() >= 2 {
      // Check if the path starts with the pattern ['.', separator]
      if path[0] == '.' && path[1] == separator {
         // Remove the first two characters
         path.drain(0..2);
         // and repeat loop, check for possible next match
      } else {
         // nothing found, we done
         return
      }
   }
}

/**

  Removes all slash dot slashes representing current dir

  Cases:
   * dir/./file
   * file/./
*/
fn remove_slash_dot_slash(path: &mut Vec<char>, separator: char) {
   // find "/./" and replace them with "/"
   while let Some(pos) = path.windows(3).position(|f| f[0] == separator && f[1] == '.' && f[2] == separator ) {
      path.drain(pos..pos+2);
   }
}

/**

  Removes slash dot at end of path

  Case:
   * file/. - file/
*/
fn remove_end_dot(path: &mut Vec<char>, separator: char) {
   // Check if the path ends with the pattern [separator, '.']
   if path.len() >= 2 {
      if path[path.len() - 2] == separator && path[path.len() - 1] == '.' {
        // Remove the last '.' character
        path.pop();
      }
   }
}

/**

  Resolve updirs

  Case:
   * dir1/dir2/../file - dir1/file
   * /../file - /file
   * /../ - /
*/
fn resolve_updirs(path: &mut Vec<char>, separator: char) {
   while let Some(pos) = path.windows(4).position(
      |f| f[0] == separator && f[1] == '.' && f[2] == '.' && f[3] == separator ) {
         let frontal = &path[0..pos];
         if let Some(index) = frontal.iter().rposition(|&x| x == separator) {
            path.drain(index + 1..pos+4);
         } else {
            if pos == 0 {
               // special case "/../file"
               path.drain(1..pos+4);
            } else {
               // special case no second updir "dir2/../"
               path.drain(0..pos+4);
            }
         }
   }
}

/**

  Resolve updir at the end

  Case:
   * dir1/dir2/.. - dir1/
   * dir2/.. - ""
   * /.. - /
*/
fn resolve_end_updir(path: &mut Vec<char>, separator: char) {
   if path.len() >= 3 {
      if path[path.len() -3] == separator && path[path.len() -2] == '.' && path[path.len() -1] == '.' {
         if path.len() == 3 {
            // special short case "/.."
            path.drain(1..3);
         } else {
            // remove last 3 items from vector
            let truncated_path = &path[..path.len() - 3];
            // find separator
            if let Some(index) = truncated_path.iter().rposition(|&x| x == separator) {
               path.drain(index + 1..);
            } else {
               // special case no second updir "dir2/.."
               path.clear();
            }
         }
      }
   }
}

/**

  Get length of prefix in Windows path

  Prefix gets temporarily removed then POSIX style
  normalization is applied and prefix is added back.

  Case:
   * C:\ - 2
   * \\server\share - 1
   * other cases - 0

  Code assumes that forward slashes are already converted
  to back slashes.
*/
fn windows_prefix_len(path: &Vec<char>) -> usize {
   if path.len() >=2 {
      if path[1] == ':' {
         // Drive path
         2
      } else if path[0] == '\\' && path[1] == '\\' {
         // UNC path
         1
      } else {
         // no prefix found
         0
      }
   } else {
      // too short
      0
   }
}

#[cfg(test)]
#[path = "tests.rs"]
mod test_normalizefs;

//   high level test suites

#[cfg(test)]
#[path = "normalize_posix_tests.rs"]
mod normalize_posix_tests;

#[cfg(test)]
#[path = "normalize_windows_tests.rs"]
mod normalize_windows_tests;

#[cfg(test)]
#[path = "absolute_posix_tests.rs"]
mod absolute_posix_tests;

#[cfg(test)]
#[path = "absolute_windows_tests.rs"]
mod absolute_windows_tests;

#[cfg(test)]
#[path = "join_posix_tests.rs"]
mod join_posix_tests;

#[cfg(test)]
#[path = "join_windows_tests.rs"]
mod join_windows_tests;

//   low level test suites

#[cfg(test)]
#[path = "double_separator_tests.rs"]
mod double_separator_tests;

#[cfg(test)]
#[path = "start_dot_slash_tests.rs"]
mod start_dot_slash_tests;

#[cfg(test)]
#[path = "end_dot_tests.rs"]
mod end_dot_tests;

#[cfg(test)]
#[path = "slash_dot_slash_tests.rs"]
mod slash_dot_slash_tests;

#[cfg(test)]
#[path = "end_updir_tests.rs"]
mod end_updir_tests;

#[cfg(test)]
#[path = "updirs_tests.rs"]
mod resolve_updirs_tests;

#[cfg(test)]
#[path = "replace_slashes_tests.rs"]
mod replace_slashes_tests;

#[cfg(test)]
#[path = "unc_extra_backslashes_tests.rs"]
mod unc_extra_backslashes_tests;

#[cfg(test)]
#[path = "normalize_unc_tests.rs"]
mod normalize_unc_tests;

#[cfg(test)]
#[path = "normalize_drive_tests.rs"]
mod normalize_drive_tests;

#[cfg(test)]
#[path = "windows_prefix_tests.rs"]
mod windows_prefix_tests;

#[cfg(test)]
#[path = "have_drive_tests.rs"]
mod have_drive_tests;