soar-utils 0.4.3

Utilities for soar package manager
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
//! Error types for soar-utils.

use std::path::PathBuf;

use miette::Diagnostic;
use thiserror::Error;

/// Error type for byte parsing operations.
#[derive(Error, Diagnostic, Debug)]
pub enum BytesError {
    #[error("Failed to parse '{input}' as bytes: {reason}")]
    #[diagnostic(
        code(soar_utils::bytes::parse),
        help("Use a valid byte format like '1KB', '2MB', or '3GB'")
    )]
    ParseFailed { input: String, reason: String },
}

/// Error type for hash operations.
#[derive(Error, Diagnostic, Debug)]
pub enum HashError {
    #[error("Failed to read file '{path}'")]
    #[diagnostic(
        code(soar_utils::hash::read),
        help("Check if the file exists and you have read permissions")
    )]
    ReadFailed {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },
}

/// Errors that can occur when working with locks.
#[derive(Debug, Diagnostic, Error)]
pub enum LockError {
    #[error(transparent)]
    #[diagnostic(
        code(soar_utils::lock::io),
        help("Check if you have write permissions to the lock directory")
    )]
    Io(#[from] std::io::Error),

    #[error("Failed to acquire lock for '{0}'")]
    #[diagnostic(
        code(soar_utils::lock::acquire_failed),
        help("Check if the lock directory exists and you have write permissions")
    )]
    AcquireFailed(String),
}

/// Error type for path operations.
#[derive(Error, Diagnostic, Debug)]
pub enum PathError {
    #[error("Failed to get current directory")]
    #[diagnostic(
        code(soar_utils::path::cwd),
        help("Check if the current directory still exists")
    )]
    FailedToGetCurrentDir {
        #[source]
        source: std::io::Error,
    },

    #[error("Path is empty")]
    #[diagnostic(code(soar_utils::path::empty), help("Provide a non-empty path"))]
    Empty,

    #[error("Environment variable '{var}' not set in '{input}'")]
    #[diagnostic(
        code(soar_utils::path::env_var),
        help("Set the environment variable or use a different path")
    )]
    MissingEnvVar { var: String, input: String },

    #[error("Unclosed variable expression starting at '{input}'")]
    #[diagnostic(
        code(soar_utils::path::unclosed_var),
        help("Close the variable expression with '}}'")
    )]
    UnclosedVariable { input: String },
}

/// Error type for filesystem operations.
#[derive(Error, Diagnostic, Debug)]
pub enum FileSystemError {
    #[error("Failed to read file '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::read_file),
        help("Check if the file exists and you have read permissions")
    )]
    ReadFile {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to write file '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::write_file),
        help("Check if you have write permissions to the directory")
    )]
    WriteFile {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to create file '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::create_file),
        help("Check if the directory exists and you have write permissions")
    )]
    CreateFile {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to remove file '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::remove_file),
        help("Check if you have write permissions to the file")
    )]
    RemoveFile {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to read directory '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::read_dir),
        help("Check if the directory exists and you have read permissions")
    )]
    ReadDirectory {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to create directory '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::create_dir),
        help("Check if the parent directory exists and you have write permissions")
    )]
    CreateDirectory {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to remove directory '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::remove_dir),
        help("Check if the directory is empty and you have write permissions")
    )]
    RemoveDirectory {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to create symlink from '{from}' to '{target}'")]
    #[diagnostic(
        code(soar_utils::fs::create_symlink),
        help("Check if you have write permissions and the target doesn't already exist")
    )]
    CreateSymlink {
        from: PathBuf,
        target: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to remove symlink '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::remove_symlink),
        help("Check if you have write permissions")
    )]
    RemoveSymlink {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Failed to read symlink '{path}'")]
    #[diagnostic(
        code(soar_utils::fs::read_symlink),
        help("Check if the symlink exists")
    )]
    ReadSymlink {
        path: PathBuf,
        #[source]
        source: std::io::Error,
    },

    #[error("Path '{path}' not found")]
    #[diagnostic(code(soar_utils::fs::not_found), help("Check if the path exists"))]
    NotFound { path: PathBuf },

    #[error("'{path}' is not a directory")]
    #[diagnostic(code(soar_utils::fs::not_a_dir), help("Provide a path to a directory"))]
    NotADirectory { path: PathBuf },

    #[diagnostic(code(soar_utils::fs::not_a_file), help("Provide a path to a file"))]
    #[error("'{path}' is not a file")]
    NotAFile { path: PathBuf },
}

/// Context for filesystem operations.
pub struct IoContext {
    path: PathBuf,
    operation: IoOperation,
}

/// Type of filesystem operation.
#[derive(Debug, Clone)]
pub enum IoOperation {
    ReadFile,
    WriteFile,
    CreateFile,
    RemoveFile,
    CreateDirectory,
    RemoveDirectory,
    ReadDirectory,
    CreateSymlink { target: PathBuf },
    RemoveSymlink,
    ReadSymlink,
}

impl IoContext {
    pub fn new(path: PathBuf, operation: IoOperation) -> Self {
        Self {
            path,
            operation,
        }
    }

    pub fn read_file<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::ReadFile)
    }

    pub fn write_file<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::WriteFile)
    }

    pub fn create_file<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::CreateFile)
    }

    pub fn remove_file<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::RemoveFile)
    }

    pub fn read_directory<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::ReadDirectory)
    }

    pub fn create_directory<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::CreateDirectory)
    }

    pub fn remove_directory<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::RemoveDirectory)
    }

    pub fn read_symlink<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::ReadSymlink)
    }

    pub fn create_symlink<P: Into<PathBuf>, T: Into<PathBuf>>(from: P, target: T) -> Self {
        Self::new(
            from.into(),
            IoOperation::CreateSymlink {
                target: target.into(),
            },
        )
    }

    pub fn remove_symlink<P: Into<PathBuf>>(path: P) -> Self {
        Self::new(path.into(), IoOperation::RemoveSymlink)
    }

    pub fn operation(&self) -> &IoOperation {
        &self.operation
    }
}

impl From<(IoContext, std::io::Error)> for FileSystemError {
    fn from((ctx, source): (IoContext, std::io::Error)) -> Self {
        match ctx.operation {
            IoOperation::ReadFile => {
                FileSystemError::ReadFile {
                    path: ctx.path,
                    source,
                }
            }
            IoOperation::WriteFile => {
                FileSystemError::WriteFile {
                    path: ctx.path,
                    source,
                }
            }
            IoOperation::CreateFile => {
                FileSystemError::CreateFile {
                    path: ctx.path,
                    source,
                }
            }
            IoOperation::RemoveFile => {
                FileSystemError::RemoveFile {
                    path: ctx.path,
                    source,
                }
            }
            IoOperation::CreateDirectory => {
                FileSystemError::CreateDirectory {
                    path: ctx.path,
                    source,
                }
            }
            IoOperation::RemoveDirectory => {
                FileSystemError::RemoveDirectory {
                    path: ctx.path,
                    source,
                }
            }
            IoOperation::ReadDirectory => {
                FileSystemError::ReadDirectory {
                    path: ctx.path,
                    source,
                }
            }
            IoOperation::CreateSymlink {
                target,
            } => {
                FileSystemError::CreateSymlink {
                    from: ctx.path,
                    target,
                    source,
                }
            }
            IoOperation::RemoveSymlink => {
                FileSystemError::RemoveSymlink {
                    path: ctx.path,
                    source,
                }
            }
            IoOperation::ReadSymlink => {
                FileSystemError::ReadSymlink {
                    path: ctx.path,
                    source,
                }
            }
        }
    }
}

/// Extension trait for adding path context to IO results.
pub trait IoResultExt<T> {
    fn with_path<P: Into<PathBuf>>(self, path: P, operation: IoOperation) -> FileSystemResult<T>;
}

impl<T> IoResultExt<T> for std::io::Result<T> {
    fn with_path<P: Into<PathBuf>>(self, path: P, operation: IoOperation) -> FileSystemResult<T> {
        self.map_err(|e| {
            let ctx = IoContext::new(path.into(), operation);
            (ctx, e).into()
        })
    }
}

/// Combined error type for all utils errors.
#[derive(Error, Diagnostic, Debug)]
pub enum UtilsError {
    #[error(transparent)]
    #[diagnostic(transparent)]
    Bytes(#[from] BytesError),

    #[error(transparent)]
    #[diagnostic(transparent)]
    Lock(#[from] LockError),

    #[error(transparent)]
    #[diagnostic(transparent)]
    Path(#[from] PathError),

    #[error(transparent)]
    #[diagnostic(transparent)]
    FileSystem(#[from] FileSystemError),

    #[error(transparent)]
    #[diagnostic(transparent)]
    Hash(#[from] HashError),
}

pub type BytesResult<T> = std::result::Result<T, BytesError>;
pub type FileSystemResult<T> = std::result::Result<T, FileSystemError>;
pub type HashResult<T> = std::result::Result<T, HashError>;
pub type LockResult<T> = std::result::Result<T, LockError>;
pub type PathResult<T> = std::result::Result<T, PathError>;
pub type UtilsResult<T> = std::result::Result<T, UtilsError>;

#[cfg(test)]
mod tests {
    use std::io;

    use super::*;

    #[test]
    fn test_bytes_error_display() {
        let error = BytesError::ParseFailed {
            input: "test".to_string(),
            reason: "invalid".to_string(),
        };
        assert_eq!(
            error.to_string(),
            "Failed to parse 'test' as bytes: invalid"
        );
    }

    #[test]
    fn test_hash_error_display_and_source() {
        let io_error = io::Error::new(io::ErrorKind::NotFound, "file not found");
        let error = HashError::ReadFailed {
            path: PathBuf::from("/test"),
            source: io_error,
        };
        assert_eq!(error.to_string(), "Failed to read file '/test'");
    }

    #[test]
    fn test_path_error_display() {
        let empty_error = PathError::Empty;
        assert_eq!(empty_error.to_string(), "Path is empty");

        let missing_env_var_error = PathError::MissingEnvVar {
            var: "VAR".to_string(),
            input: "$VAR".to_string(),
        };
        assert_eq!(
            missing_env_var_error.to_string(),
            "Environment variable 'VAR' not set in '$VAR'"
        );

        let unclosed_variable_error = PathError::UnclosedVariable {
            input: "${VAR".to_string(),
        };
        assert_eq!(
            unclosed_variable_error.to_string(),
            "Unclosed variable expression starting at '${VAR'"
        );
    }

    #[test]
    fn test_file_system_error_display() {
        let io_error = io::Error::new(io::ErrorKind::PermissionDenied, "permission denied");
        let file_error = FileSystemError::ReadFile {
            path: PathBuf::from("/file"),
            source: io_error,
        };
        assert_eq!(file_error.to_string(), "Failed to read file '/file'");

        let not_a_dir_error = FileSystemError::NotADirectory {
            path: PathBuf::from("/path"),
        };
        assert_eq!(not_a_dir_error.to_string(), "'/path' is not a directory");
    }
}