app-path 1.1.2

Create file paths relative to your executable for truly portable applications
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
use crate::{AppPath, AppPathError};
use std::error::Error;
use std::fmt::Write;

#[test]
fn test_error_type_display() {
    // Test that error types have meaningful Display implementations with realistic scenarios
    let exec_error =
        AppPathError::ExecutableNotFound("Failed to determine executable location".to_string());
    let invalid_error = AppPathError::InvalidExecutablePath(
        "Library file is not a valid executable path".to_string(),
    );

    let mut exec_str = String::new();
    write!(&mut exec_str, "{exec_error}").unwrap();
    assert!(exec_str.contains("Failed to determine executable location"));

    let mut invalid_str = String::new();
    write!(&mut invalid_str, "{invalid_error}").unwrap();
    assert!(invalid_str.contains("Invalid executable path"));
}

#[test]
fn test_error_type_debug() {
    // Test that error types have Debug implementations with realistic errors
    let exec_error =
        AppPathError::ExecutableNotFound("Cannot access current executable".to_string());
    let invalid_error =
        AppPathError::InvalidExecutablePath("Dynamic library is not an executable".to_string());

    let exec_debug = format!("{exec_error:?}");
    let invalid_debug = format!("{invalid_error:?}");

    assert!(exec_debug.contains("ExecutableNotFound"));
    assert!(invalid_debug.contains("InvalidExecutablePath"));
}

#[test]
fn test_error_type_functionality() {
    // Test that error types work correctly with realistic scenarios
    let exec_error =
        AppPathError::ExecutableNotFound("Current executable access failed".to_string());
    let invalid_error =
        AppPathError::InvalidExecutablePath("Library file is not a valid executable".to_string());

    // Test that we can match on error types
    match exec_error {
        AppPathError::ExecutableNotFound(msg) => {
            assert!(msg.contains("executable access failed"));
        }
        _ => panic!("Wrong error type"),
    }

    match invalid_error {
        AppPathError::InvalidExecutablePath(msg) => {
            assert!(msg.contains("not a valid executable"));
        }
        _ => panic!("Wrong error type"),
    }
}

#[test]
fn test_error_is_std_error() {
    // Test that our error type implements std::error::Error with realistic scenario
    let error =
        AppPathError::ExecutableNotFound("Failed to determine executable location".to_string());
    let _std_error: &dyn std::error::Error = &error;

    // Should compile without issues
}

#[test]
fn test_fallible_api_documentation_examples() {
    // Test the examples from the documentation work correctly

    // Example 1: Basic error handling pattern
    match AppPath::try_with("config.toml") {
        Ok(config) => {
            assert!(config.ends_with("config.toml"));
        }
        Err(_e) => {
            // In our test environment, this shouldn't happen
            panic!("try_new should succeed in test environment");
        }
    }

    // Example 2: Using ? operator (simulated)
    fn load_config() -> Result<AppPath, AppPathError> {
        let config = AppPath::try_with("config.toml")?;
        Ok(config)
    }

    let config = load_config().unwrap();
    assert!(config.ends_with("config.toml"));

    // Example 3: Fallback strategy
    fn get_config_with_fallback() -> AppPath {
        AppPath::try_with("config.toml").unwrap_or_else(|_| {
            let temp_config = std::env::temp_dir().join("myapp").join("config.toml");
            AppPath::with(temp_config)
        })
    }

    let config = get_config_with_fallback();
    // Should succeed in either case
    assert!(config.is_absolute());
}

#[test]
fn test_io_error_variant_from_real_operation() {
    // Test conversion from a real I/O error by trying to read a non-existent file
    let result = std::fs::File::open("definitely_does_not_exist_12345.txt");

    match result {
        Err(io_error) => {
            let app_error = AppPathError::from(io_error);
            match app_error {
                AppPathError::IoError(io_err) => {
                    // The error message will naturally be OS-appropriate
                    assert!(!io_err.to_string().is_empty());
                }
                _ => panic!("Expected IoError variant"),
            }
        }
        Ok(_) => panic!("Expected file not found error"),
    }
}

#[test]
fn test_io_error_display_from_real_operation() {
    // Test with a real "directory not found" error by trying to create a directory in a non-existent parent
    let nonexistent_parent = std::env::temp_dir()
        .join("definitely_nonexistent_parent_12345")
        .join("child");
    let result = std::fs::create_dir(&nonexistent_parent);

    match result {
        Err(io_error) => {
            let app_error = AppPathError::from(io_error);
            let error_str = format!("{app_error}");
            assert!(error_str.contains("I/O operation failed"));
            // Don't check for specific text - let the OS provide its natural error message
        }
        Ok(_) => panic!("Expected directory creation to fail"),
    }
}

#[test]
fn test_io_error_debug_from_real_operation() {
    // Test with a real error by trying to open a directory as a file
    let temp_dir = std::env::temp_dir().join("app_path_debug_test");
    std::fs::create_dir_all(&temp_dir).unwrap();

    let result = std::fs::File::open(&temp_dir);

    // Clean up
    std::fs::remove_dir_all(&temp_dir).ok();

    match result {
        Err(io_error) => {
            let app_error = AppPathError::from(io_error);
            let debug_str = format!("{app_error:?}");
            assert!(debug_str.contains("IoError"));
            // The actual error message will be OS-appropriate naturally
        }
        Ok(_) => {
            // Some systems might allow opening a directory as a file, that's OK
            // Just verify the conversion would work
            let fake_error = std::io::Error::new(std::io::ErrorKind::InvalidInput, "test");
            let app_error = AppPathError::from(fake_error);
            let debug_str = format!("{app_error:?}");
            assert!(debug_str.contains("IoError"));
        }
    }
}

#[cfg(unix)]
#[test]
fn test_create_parents_permission_error() {
    use std::os::unix::fs::PermissionsExt;

    // Create a test directory that we'll make read-only
    let temp_dir = std::env::temp_dir().join("app_path_permission_test");
    std::fs::create_dir_all(&temp_dir).unwrap();

    // Make it read-only (no write permissions)
    let mut perms = std::fs::metadata(&temp_dir).unwrap().permissions();
    perms.set_mode(0o444); // Read-only
    std::fs::set_permissions(&temp_dir, perms).unwrap();

    // Try to create a subdirectory (should fail with permission error)
    let protected_file = AppPath::with(temp_dir.join("protected/file.txt"));
    let result = protected_file.create_parents();

    // Restore write permissions for cleanup
    let mut perms = std::fs::metadata(&temp_dir).unwrap().permissions();
    perms.set_mode(0o755); // Restore write permissions
    std::fs::set_permissions(&temp_dir, perms).unwrap();

    // Clean up
    std::fs::remove_dir_all(&temp_dir).ok();

    // Check that we got an IoError
    match result {
        Err(AppPathError::IoError(io_err)) => {
            let msg = io_err.to_string();
            assert!(msg.contains("Permission denied") || msg.contains("Access is denied"));
        }
        _ => panic!("Expected IoError for permission denied, got: {result:?}"),
    }
}

#[cfg(unix)]
#[test]
fn test_create_dir_permission_error() {
    use std::os::unix::fs::PermissionsExt;

    // Create a test directory that we'll make read-only
    let temp_dir = std::env::temp_dir().join("app_path_dir_permission_test");
    std::fs::create_dir_all(&temp_dir).unwrap();

    // Make it read-only (no write permissions)
    let mut perms = std::fs::metadata(&temp_dir).unwrap().permissions();
    perms.set_mode(0o444); // Read-only
    std::fs::set_permissions(&temp_dir, perms).unwrap();

    // Try to create a subdirectory (should fail with permission error)
    let protected_dir = AppPath::with(temp_dir.join("protected"));
    let result = protected_dir.create_dir();

    // Restore write permissions for cleanup
    let mut perms = std::fs::metadata(&temp_dir).unwrap().permissions();
    perms.set_mode(0o755); // Restore write permissions
    std::fs::set_permissions(&temp_dir, perms).unwrap();

    // Clean up
    std::fs::remove_dir_all(&temp_dir).ok();

    // Check that we got an IoError
    match result {
        Err(AppPathError::IoError(io_err)) => {
            let msg = io_err.to_string();
            assert!(msg.contains("Permission denied") || msg.contains("Access is denied"));
        }
        _ => panic!("Expected IoError for permission denied, got: {result:?}"),
    }
}

#[test]
fn test_error_variant_completeness() {
    // Test all error variants for completeness
    let exec_error = AppPathError::ExecutableNotFound("exec error".to_string());
    let invalid_error = AppPathError::InvalidExecutablePath("invalid path".to_string());
    let io_error = AppPathError::IoError(std::io::Error::other("io error"));

    // Test Display
    assert!(format!("{exec_error}").contains("Failed to determine executable location"));
    assert!(format!("{invalid_error}").contains("Invalid executable path"));
    assert!(format!("{io_error}").contains("I/O operation failed"));

    // Test Debug
    assert!(format!("{exec_error:?}").contains("ExecutableNotFound"));
    assert!(format!("{invalid_error:?}").contains("InvalidExecutablePath"));
    assert!(format!("{io_error:?}").contains("IoError"));
}

#[test]
fn test_error_source_chain() {
    // Test error source chain for IoError
    let io_err = std::io::Error::new(std::io::ErrorKind::PermissionDenied, "access denied");
    let app_error = AppPathError::from(io_err);

    // Test that we can access the source error
    assert!(app_error.source().is_some());
    match app_error {
        AppPathError::IoError(inner) => {
            assert_eq!(inner.kind(), std::io::ErrorKind::PermissionDenied);
            assert!(inner.to_string().contains("access denied"));
        }
        _ => panic!("Expected IoError variant"),
    }
}

#[test]
fn test_io_error_comprehensive_access() {
    // Test all the key benefits of preserving std::io::Error
    use std::io::ErrorKind;

    // Test different error kinds
    let test_cases = [
        (ErrorKind::NotFound, "file not found"),
        (ErrorKind::PermissionDenied, "access denied"),
        (ErrorKind::AlreadyExists, "already exists"),
        (ErrorKind::InvalidInput, "invalid input"),
        (ErrorKind::TimedOut, "timed out"),
    ];

    for (kind, message) in test_cases {
        let io_err = std::io::Error::new(kind, message);
        let app_error = AppPathError::from(io_err);

        // Test error source chain first
        assert!(app_error.source().is_some());

        // Test that we can downcast the source back to io::Error
        let source = app_error.source().unwrap();
        assert!(source.downcast_ref::<std::io::Error>().is_some());

        match app_error {
            AppPathError::IoError(inner) => {
                // Test kind() access
                assert_eq!(inner.kind(), kind);

                // Test message preservation
                assert!(inner.to_string().contains(message));
            }
            _ => panic!("Expected IoError variant for kind: {kind:?}"),
        }
    }
}

#[test]
fn test_io_error_raw_os_error_access() {
    // Test access to raw OS error codes when available

    // Create an error that might have an OS error code
    // We'll test the API even if the specific code isn't guaranteed
    let io_err = std::io::Error::from(std::io::ErrorKind::PermissionDenied);
    let app_error = AppPathError::from(io_err);

    match app_error {
        AppPathError::IoError(inner) => {
            // Test that raw_os_error() method is accessible
            // Note: The actual value depends on the platform and context
            let _os_error = inner.raw_os_error(); // Option<i32>

            // Test that we can use it in error handling logic
            match inner.raw_os_error() {
                Some(code) => {
                    // OS-specific error code is available
                    assert!(code != 0); // Usually non-zero for actual errors
                }
                None => {
                    // No OS-specific code, but that's also valid
                    // Just ensure the method is callable
                }
            }
        }
        _ => panic!("Expected IoError variant"),
    }
}

#[test]
fn test_io_error_path_context_preservation() {
    // Test that path context is preserved when using the (io::Error, &PathBuf) conversion
    use std::path::PathBuf;

    let path = PathBuf::from("/some/test/path");
    let io_err = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
    let app_error = AppPathError::from((io_err, &path));

    match app_error {
        AppPathError::IoError(inner) => {
            // Verify the error kind is preserved
            assert_eq!(inner.kind(), std::io::ErrorKind::NotFound);

            // Verify path context is included in the message
            let message = inner.to_string();
            assert!(message.contains("file not found"));
            assert!(message.contains("/some/test/path"));
        }
        _ => panic!("Expected IoError variant"),
    }
}

#[test]
fn test_directory_creation_error_propagation() {
    // Test that directory creation methods properly propagate IoError

    // Create a file where we'll try to create a directory
    let temp_dir = std::env::temp_dir().join("app_path_error_propagation_test");
    std::fs::create_dir_all(&temp_dir).unwrap();
    let blocking_file = temp_dir.join("blocking_file");
    std::fs::write(&blocking_file, "content").unwrap();

    // Try to create a directory with the same name as the file (should fail)
    let blocked_path = AppPath::from(&blocking_file);
    let result = blocked_path.create_dir();

    // Clean up
    std::fs::remove_dir_all(&temp_dir).ok();

    // Should get an IoError
    match result {
        Err(AppPathError::IoError(_)) => {
            // Expected - trying to create a directory where a file exists
        }
        _ => panic!(
            "Expected IoError when trying to create directory over existing file, got: {result:?}"
        ),
    }
}

#[test]
fn test_create_parents_with_file_blocking_parent() {
    // Test create_parents when a file blocks parent creation

    let temp_dir = std::env::temp_dir().join("app_path_parent_block_test");
    std::fs::create_dir_all(&temp_dir).unwrap();

    // Create a file that will block parent directory creation
    let blocking_file = temp_dir.join("logs");
    std::fs::write(&blocking_file, "content").unwrap();

    // Try to create parents for a path that needs "logs" as a directory
    let log_file = AppPath::with(temp_dir.join("logs/app.log"));
    let result = log_file.create_parents();

    // Clean up
    std::fs::remove_dir_all(&temp_dir).ok();

    // Should get an IoError because "logs" exists as a file, not a directory
    match result {
        Err(AppPathError::IoError(_)) => {
            // Expected - can't create directory where file exists
        }
        _ => panic!("Expected IoError when file blocks parent creation, got: {result:?}"),
    }
}