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
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.

use crate::*;

/// build_abs_path will build an absolute path with root.
///
/// # Rules
///
/// - Input root MUST be the format like `/abc/def/`
/// - Output will be the format like `path/to/root/path`.
pub fn build_abs_path(root: &str, path: &str) -> String {
    debug_assert!(root.starts_with('/'), "root must start with /");
    debug_assert!(root.ends_with('/'), "root must end with /");

    let p = root[1..].to_string();

    if path == "/" {
        p
    } else {
        debug_assert!(!path.starts_with('/'), "path must not start with /");
        p + path
    }
}

/// build_rooted_abs_path will build an absolute path with root.
///
/// # Rules
///
/// - Input root MUST be the format like `/abc/def/`
/// - Output will be the format like `/path/to/root/path`.
pub fn build_rooted_abs_path(root: &str, path: &str) -> String {
    debug_assert!(root.starts_with('/'), "root must start with /");
    debug_assert!(root.ends_with('/'), "root must end with /");

    let p = root.to_string();

    if path == "/" {
        p
    } else {
        debug_assert!(!path.starts_with('/'), "path must not start with /");
        p + path
    }
}

/// build_rel_path will build a relative path towards root.
///
/// # Rules
///
/// - Input root MUST be the format like `/abc/def/`
/// - Input path MUST start with root like `/abc/def/path/to/file`
/// - Output will be the format like `path/to/file`.
pub fn build_rel_path(root: &str, path: &str) -> String {
    debug_assert!(root != path, "get rel path with root is invalid");

    if path.starts_with('/') {
        debug_assert!(
            path.starts_with(root),
            "path {path} doesn't start with root {root}"
        );
        path[root.len()..].to_string()
    } else {
        debug_assert!(
            path.starts_with(&root[1..]),
            "path {path} doesn't start with root {root}"
        );
        path[root.len() - 1..].to_string()
    }
}

/// Make sure all operation are constructed by normalized path:
///
/// - Path endswith `/` means it's a dir path.
/// - Otherwise, it's a file path.
///
/// # Normalize Rules
///
/// - All whitespace will be trimmed: ` abc/def ` => `abc/def`
/// - All leading / will be trimmed: `///abc` => `abc`
/// - Internal // will be replaced by /: `abc///def` => `abc/def`
/// - Empty path will be `/`: `` => `/`
pub fn normalize_path(path: &str) -> String {
    // - all whitespace has been trimmed.
    // - all leading `/` has been trimmed.
    let path = path.trim().trim_start_matches('/');

    // Fast line for empty path.
    if path.is_empty() {
        return "/".to_string();
    }

    let has_trailing = path.ends_with('/');

    let mut p = path
        .split('/')
        .filter(|v| !v.is_empty())
        .collect::<Vec<&str>>()
        .join("/");

    // Append trailing back if input path is endswith `/`.
    if has_trailing {
        p.push('/');
    }

    p
}

/// Make sure root is normalized to style like `/abc/def/`.
///
/// # Normalize Rules
///
/// - All whitespace will be trimmed: ` abc/def ` => `abc/def`
/// - All leading / will be trimmed: `///abc` => `abc`
/// - Internal // will be replaced by /: `abc///def` => `abc/def`
/// - Empty path will be `/`: `` => `/`
/// - Add leading `/` if not starts with: `abc/` => `/abc/`
/// - Add trailing `/` if not ends with: `/abc` => `/abc/`
///
/// Finally, we will got path like `/path/to/root/`.
pub fn normalize_root(v: &str) -> String {
    let mut v = v
        .split('/')
        .filter(|v| !v.is_empty())
        .collect::<Vec<&str>>()
        .join("/");
    if !v.starts_with('/') {
        v.insert(0, '/');
    }
    if !v.ends_with('/') {
        v.push('/')
    }
    v
}

/// Get basename from path.
pub fn get_basename(path: &str) -> &str {
    // Handle root case
    if path == "/" {
        return "/";
    }

    // Handle file case
    if !path.ends_with('/') {
        return path
            .split('/')
            .last()
            .expect("file path without name is invalid");
    }

    // The idx of second `/` if path in reserve order.
    // - `abc/` => `None`
    // - `abc/def/` => `Some(3)`
    let idx = path[..path.len() - 1].rfind('/').map(|v| v + 1);

    match idx {
        Some(v) => {
            let (_, name) = path.split_at(v);
            name
        }
        None => path,
    }
}

/// Get parent from path.
pub fn get_parent(path: &str) -> &str {
    if path == "/" {
        return "/";
    }

    if !path.ends_with('/') {
        // The idx of first `/` if path in reserve order.
        // - `abc` => `None`
        // - `abc/def` => `Some(3)`
        let idx = path.rfind('/');

        return match idx {
            Some(v) => {
                let (parent, _) = path.split_at(v + 1);
                parent
            }
            None => "/",
        };
    }

    // The idx of second `/` if path in reserve order.
    // - `abc/` => `None`
    // - `abc/def/` => `Some(3)`
    let idx = path[..path.len() - 1].rfind('/').map(|v| v + 1);

    match idx {
        Some(v) => {
            let (parent, _) = path.split_at(v);
            parent
        }
        None => "/",
    }
}

/// Validate given path is match with given EntryMode.
pub fn validate_path(path: &str, mode: EntryMode) -> bool {
    debug_assert!(!path.is_empty(), "input path should not be empty");

    match mode {
        EntryMode::FILE => !path.ends_with('/'),
        EntryMode::DIR => path.ends_with('/'),
        EntryMode::Unknown => false,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_normalize_path() {
        let cases = vec![
            ("file path", "abc", "abc"),
            ("dir path", "abc/", "abc/"),
            ("empty path", "", "/"),
            ("root path", "/", "/"),
            ("root path with extra /", "///", "/"),
            ("abs file path", "/abc/def", "abc/def"),
            ("abs dir path", "/abc/def/", "abc/def/"),
            ("abs file path with extra /", "///abc/def", "abc/def"),
            ("abs dir path with extra /", "///abc/def/", "abc/def/"),
            ("file path contains ///", "abc///def", "abc/def"),
            ("dir path contains ///", "abc///def///", "abc/def/"),
            ("file with whitespace", "abc/def   ", "abc/def"),
        ];

        for (name, input, expect) in cases {
            assert_eq!(normalize_path(input), expect, "{name}")
        }
    }

    #[test]
    fn test_normalize_root() {
        let cases = vec![
            ("dir path", "abc/", "/abc/"),
            ("empty path", "", "/"),
            ("root path", "/", "/"),
            ("root path with extra /", "///", "/"),
            ("abs dir path", "/abc/def/", "/abc/def/"),
            ("abs file path with extra /", "///abc/def", "/abc/def/"),
            ("abs dir path with extra /", "///abc/def/", "/abc/def/"),
            ("dir path contains ///", "abc///def///", "/abc/def/"),
        ];

        for (name, input, expect) in cases {
            assert_eq!(normalize_root(input), expect, "{name}")
        }
    }

    #[test]
    fn test_get_basename() {
        let cases = vec![
            ("file abs path", "foo/bar/baz.txt", "baz.txt"),
            ("file rel path", "bar/baz.txt", "baz.txt"),
            ("file walk", "foo/bar/baz", "baz"),
            ("dir rel path", "bar/baz/", "baz/"),
            ("dir root", "/", "/"),
            ("dir walk", "foo/bar/baz/", "baz/"),
        ];

        for (name, input, expect) in cases {
            let actual = get_basename(input);
            assert_eq!(actual, expect, "{name}")
        }
    }

    #[test]
    fn test_get_parent() {
        let cases = vec![
            ("file abs path", "foo/bar/baz.txt", "foo/bar/"),
            ("file rel path", "bar/baz.txt", "bar/"),
            ("file walk", "foo/bar/baz", "foo/bar/"),
            ("dir rel path", "bar/baz/", "bar/"),
            ("dir root", "/", "/"),
            ("dir walk", "foo/bar/baz/", "foo/bar/"),
        ];

        for (name, input, expect) in cases {
            let actual = get_parent(input);
            assert_eq!(actual, expect, "{name}")
        }
    }

    #[test]
    fn test_build_abs_path() {
        let cases = vec![
            ("input abs file", "/abc/", "/", "abc/"),
            ("input dir", "/abc/", "def/", "abc/def/"),
            ("input file", "/abc/", "def", "abc/def"),
            ("input abs file with root /", "/", "/", ""),
            ("input empty with root /", "/", "", ""),
            ("input dir with root /", "/", "def/", "def/"),
            ("input file with root /", "/", "def", "def"),
        ];

        for (name, root, input, expect) in cases {
            let actual = build_abs_path(root, input);
            assert_eq!(actual, expect, "{name}")
        }
    }

    #[test]
    fn test_build_rooted_abs_path() {
        let cases = vec![
            ("input abs file", "/abc/", "/", "/abc/"),
            ("input dir", "/abc/", "def/", "/abc/def/"),
            ("input file", "/abc/", "def", "/abc/def"),
            ("input abs file with root /", "/", "/", "/"),
            ("input dir with root /", "/", "def/", "/def/"),
            ("input file with root /", "/", "def", "/def"),
        ];

        for (name, root, input, expect) in cases {
            let actual = build_rooted_abs_path(root, input);
            assert_eq!(actual, expect, "{name}")
        }
    }

    #[test]
    fn test_build_rel_path() {
        let cases = vec![
            ("input abs file", "/abc/", "/abc/def", "def"),
            ("input dir", "/abc/", "/abc/def/", "def/"),
            ("input file", "/abc/", "abc/def", "def"),
            ("input dir with root /", "/", "def/", "def/"),
            ("input file with root /", "/", "def", "def"),
        ];

        for (name, root, input, expect) in cases {
            let actual = build_rel_path(root, input);
            assert_eq!(actual, expect, "{name}")
        }
    }

    #[test]
    fn test_validate_path() {
        let cases = vec![
            ("input file with mode file", "abc", EntryMode::FILE, true),
            ("input file with mode dir", "abc", EntryMode::DIR, false),
            ("input dir with mode file", "abc/", EntryMode::FILE, false),
            ("input dir with mode dir", "abc/", EntryMode::DIR, true),
            ("root with mode dir", "/", EntryMode::DIR, true),
            (
                "input file with mode unknown",
                "abc",
                EntryMode::Unknown,
                false,
            ),
            (
                "input dir with mode unknown",
                "abc/",
                EntryMode::Unknown,
                false,
            ),
        ];

        for (name, path, mode, expect) in cases {
            let actual = validate_path(path, mode);
            assert_eq!(actual, expect, "{name}")
        }
    }
}