-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutilities.rs
More file actions
467 lines (410 loc) · 15.1 KB
/
utilities.rs
File metadata and controls
467 lines (410 loc) · 15.1 KB
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
// SPDX-FileCopyrightText: 2025 Adam Poulemanos <89049923+bashandbone@users.noreply.github.com>
//
// SPDX-License-Identifier: LicenseRef-PlainMIT OR MIT
//! Utility functions for working with `Gitoxide` APIs commonly used across the codebase.
#![allow(dead_code)]
use anyhow::Result;
use git2::Repository as Git2Repository;
use gix::open::Options;
use std::path::PathBuf;
/// Get the current repository using git2, with an optional provided repository. If no repository is provided, it will attempt to discover one in the current directory.
pub fn get_current_git2_repository(
repo: Option<Git2Repository>,
) -> Result<Git2Repository, anyhow::Error> {
if let Some(r) = repo { Ok(r) } else {
let rep = Git2Repository::discover(".")
.map_err(|e| anyhow::anyhow!("Failed to discover repository: {e}"))?;
if rep.is_bare() {
return Err(anyhow::anyhow!("Bare repositories are not supported"));
}
Ok(rep)
}
}
/*=========================================================================
* Gix Utilities
*========================================================================*/
/// Get a repository from a given path. The returned repository is isolated (has very limited access to the working tree and environment).
pub fn repo_from_path(path: &PathBuf) -> Result<gix::Repository, anyhow::Error> {
let options = Options::isolated();
gix::ThreadSafeRepository::open_opts(path, options)
.map(|repo| repo.to_thread_local())
.map_err(|e| anyhow::anyhow!("Failed to open repository at {path:?}: {e}"))
}
/// Get the current repository. The returned repository is isolated (has very limited access to the working tree and environment).
pub fn get_current_repository() -> Result<gix::Repository, anyhow::Error> {
let options = Options::isolated();
Ok(gix::ThreadSafeRepository::open_opts(".", options)?.to_thread_local())
}
/// Gets the current working directory
pub fn get_cwd() -> Result<PathBuf, anyhow::Error> {
std::env::current_dir()
.map_err(|e| anyhow::anyhow!("Failed to get current working directory: {e}"))
}
/// Get a thread-local repository from the given repository.
pub fn get_thread_local_repo(
repo: &gix::Repository,
) -> Result<gix::Repository, anyhow::Error> {
// Get a full access repository from the given repository
let safe_repo = repo.to_owned().into_sync().to_thread_local();
Ok(safe_repo)
}
/// Get the main, or superproject, repository.
pub fn get_main_repo(
repo: Option<&gix::Repository>,
) -> Result<gix::Repository, anyhow::Error> {
let repo = match repo {
Some(r) => r.to_owned(),
None => get_current_repository()?,
};
let super_repo = repo
.main_repo()
.map_err(|e| anyhow::anyhow!("Failed to get main repository: {e}"))?;
Ok(super_repo)
}
/// Get the main repository's root directory.
pub fn get_main_root(repo: Option<&gix::Repository>) -> Result<PathBuf, anyhow::Error> {
let repo = get_main_repo(repo)?;
let path = repo.path().to_path_buf();
if path.is_dir() {
Ok(path)
} else {
Err(anyhow::anyhow!(
"Failed to get main repository root: {}",
path.display()
))
}
}
/// Get the current branch name from the repository.
pub fn get_current_branch(repo: Option<&gix::Repository>) -> Result<String, anyhow::Error> {
fn branch_from_repo(repo: &gix::Repository) -> Result<String, anyhow::Error> {
let head = repo.head()?;
if let Some(reference) = head.referent_name() {
return Ok(reference.as_bstr().to_string());
}
Err(anyhow::anyhow!("Failed to get current branch name"))
}
if let Some(r) = repo { branch_from_repo(r) } else {
let owned = get_current_repository()?;
branch_from_repo(&owned)
}
}
/*=========================================================================
* General Utilities
*========================================================================*/
/// Get the current working directory.
pub fn get_current_working_directory() -> Result<PathBuf, anyhow::Error> {
std::env::current_dir()
.map_err(|e| anyhow::anyhow!("Failed to get current working directory: {e}"))
}
/// Convert a `Path` to a `String`, returning an error if the path is not valid UTF-8
pub fn path_to_string(path: &std::path::Path) -> Result<String, anyhow::Error> {
path.to_str()
.map(std::string::ToString::to_string)
.ok_or_else(|| anyhow::anyhow!("Path is not valid UTF-8"))
}
/// Convert a `Path` to a `String`, using lossy conversion for non-UTF-8 characters
pub fn path_to_string_lossy(path: &std::path::Path) -> String {
if let Some(s) = path.to_str() {
return s.to_string();
}
let lossy = path.to_string_lossy();
eprintln!(
"Warning: Path contains non-UTF-8 characters, using lossy conversion: {lossy}"
);
lossy.to_string()
}
/// Convert a `Path` to an `OsString`
pub fn path_to_os_string(path: &std::path::Path) -> std::ffi::OsString {
path.as_os_str().to_owned()
}
/// Set the path from an OS string, converting to UTF-8 if possible
/// Used for CLI arguments and other scenarios where the path may not be valid UTF-8
pub fn set_path(path: std::ffi::OsString) -> Result<String, anyhow::Error> {
match path.to_str() {
Some(path) => Ok(path.to_string()),
None => {
Ok(path_to_string_lossy(&PathBuf::from(path))) // Use lossy conversion if the path is not valid UTF-8
}
}
}
/// Extract the name from a URL, trimming trailing slashes and `.git` suffix
pub fn name_from_url(url: &str) -> Result<String, anyhow::Error> {
if url.is_empty() {
return Err(anyhow::anyhow!("URL cannot be empty"));
}
let cleaned_url = url.trim_end_matches('/').trim_end_matches(".git");
cleaned_url
.split('/')
.next_back()
.map(std::string::ToString::to_string)
.ok_or_else(|| anyhow::anyhow!("Failed to extract name from URL"))
}
/// Convert an `OsString` to a `String`, extracting the name from the path
pub fn name_from_osstring(os_string: std::ffi::OsString) -> Result<String, anyhow::Error> {
osstring_to_string(os_string).and_then(|s| {
if s.contains('\0') {
return Err(anyhow::anyhow!("Name cannot contain null bytes"));
}
if s.trim().is_empty() {
return Err(anyhow::anyhow!("Name cannot be empty or whitespace-only"));
}
let sep = std::path::MAIN_SEPARATOR.to_string();
s.trim()
.split(&sep)
.last()
.map(std::string::ToString::to_string)
.ok_or_else(|| anyhow::anyhow!("Failed to extract name from OsString"))
})
}
/// Convert an `OsString` to a `String`, returning an error if the conversion fails
pub fn osstring_to_string(os_string: std::ffi::OsString) -> Result<String, anyhow::Error> {
os_string
.into_string()
.map_err(|_| anyhow::anyhow!("Failed to convert OsString to String"))
}
/// Validate and return the sparse paths, ensuring they do not contain null bytes
pub fn get_sparse_paths(
sparse_paths: Option<Vec<String>>,
) -> Result<Option<Vec<String>>, anyhow::Error> {
let sparse_paths_vec = match sparse_paths {
Some(paths) => {
for path in &paths {
if path.contains('\0') {
return Err(anyhow::anyhow!(
"Invalid sparse path pattern: contains null byte"
));
}
}
Some(paths)
}
None => None,
};
Ok(sparse_paths_vec)
}
/// Get the name from either a provided name, URL, or path.
pub fn get_name(
name: Option<String>,
url: Option<String>,
path: Option<std::ffi::OsString>,
) -> Result<String, anyhow::Error> {
if let Some(name) = name {
let trimmed_name = name.trim().to_string();
if trimmed_name.is_empty() { get_name(None, url, path) } else { Ok(trimmed_name) }
} else if let Some(path) = path {
name_from_osstring(path)
} else if let Some(url) = url {
name_from_url(&url)
} else {
Err(anyhow::anyhow!("No valid name source provided"))
}
}
#[cfg(test)]
#[cfg_attr(coverage_nightly, coverage(off))]
mod tests {
use super::*;
#[test]
fn test_get_name_valid_name() {
assert_eq!(
get_name(Some("my-repo".to_string()), None, None).unwrap(),
"my-repo"
);
assert_eq!(
get_name(Some(" spaced-repo ".to_string()), None, None).unwrap(),
"spaced-repo"
);
}
#[test]
fn test_get_name_empty_name_fallback_url() {
assert_eq!(
get_name(
Some(" ".to_string()),
Some("https://github.com/user/repo.git".to_string()),
None
)
.unwrap(),
"repo"
);
}
#[test]
fn test_get_name_empty_name_fallback_path() {
assert_eq!(
get_name(
Some("".to_string()),
None,
Some(PathBuf::from_iter(["path", "to", "my-module"]).into_os_string())
)
.unwrap(),
"my-module"
);
}
#[test]
fn test_get_name_empty_name_no_fallback() {
assert!(get_name(Some(" ".to_string()), None, None).is_err());
}
#[test]
fn test_get_name_no_name_valid_path() {
assert_eq!(
get_name(None, None, Some(std::ffi::OsString::from("another-path"))).unwrap(),
"another-path"
);
}
#[test]
fn test_get_name_no_name_no_path_valid_url() {
assert_eq!(
get_name(
None,
Some("git@github.com:user/another-repo.git".to_string()),
None
)
.unwrap(),
"another-repo"
);
}
#[test]
fn test_get_name_all_none() {
assert!(get_name(None, None, None).is_err());
}
// ================================================================
// name_from_url edge cases
// ================================================================
#[test]
fn test_name_from_url_standard() {
assert_eq!(
name_from_url("https://github.com/user/repo.git").unwrap(),
"repo"
);
assert_eq!(
name_from_url("https://github.com/user/repo").unwrap(),
"repo"
);
}
#[test]
fn test_name_from_url_trailing_slashes() {
assert_eq!(
name_from_url("https://github.com/user/repo/").unwrap(),
"repo"
);
assert_eq!(
name_from_url("https://github.com/user/repo///").unwrap(),
"repo"
);
}
#[test]
fn test_name_from_url_ssh_format() {
assert_eq!(
name_from_url("git@github.com:user/mylib.git").unwrap(),
"mylib"
);
}
#[test]
fn test_name_from_url_file_url() {
assert_eq!(name_from_url("file:///path/to/repo.git").unwrap(), "repo");
}
#[test]
fn test_name_from_url_simple_name() {
assert_eq!(name_from_url("repo").unwrap(), "repo");
assert_eq!(name_from_url("my-lib.git").unwrap(), "my-lib");
}
#[test]
fn test_name_from_url_empty() {
assert!(name_from_url("").is_err());
}
// ================================================================
// name_from_osstring
// ================================================================
#[test]
fn test_name_from_osstring_simple() {
assert_eq!(
name_from_osstring(std::ffi::OsString::from("my-repo")).unwrap(),
"my-repo"
);
}
#[test]
fn test_name_from_osstring_path() {
let path = PathBuf::from_iter(["path", "to", "module"]);
assert_eq!(name_from_osstring(path.into_os_string()).unwrap(), "module");
}
#[test]
fn test_name_from_osstring_empty() {
assert!(name_from_osstring(std::ffi::OsString::from("")).is_err());
assert!(name_from_osstring(std::ffi::OsString::from(" ")).is_err());
}
#[test]
fn test_name_from_osstring_null_byte() {
assert!(name_from_osstring(std::ffi::OsString::from("foo\0bar")).is_err());
}
// ================================================================
// osstring_to_string
// ================================================================
#[test]
fn test_osstring_to_string_valid() {
assert_eq!(
osstring_to_string(std::ffi::OsString::from("hello")).unwrap(),
"hello"
);
}
// ================================================================
// path_to_string
// ================================================================
#[test]
fn test_path_to_string_valid() {
let path = std::path::Path::new("/home/user/repo");
assert_eq!(path_to_string(path).unwrap(), "/home/user/repo");
}
// ================================================================
// path_to_os_string
// ================================================================
#[test]
fn test_path_to_os_string_roundtrip() {
let path = std::path::Path::new("/some/path");
let os = path_to_os_string(path);
assert_eq!(os, std::ffi::OsString::from("/some/path"));
}
// ================================================================
// set_path
// ================================================================
#[test]
fn test_set_path_valid_utf8() {
let os = std::ffi::OsString::from("/valid/path");
assert_eq!(set_path(os).unwrap(), "/valid/path");
}
// ================================================================
// get_sparse_paths
// ================================================================
#[test]
fn test_get_sparse_paths_valid() {
let paths = Some(vec!["src/".to_string(), "docs/".to_string()]);
let result = get_sparse_paths(paths).unwrap();
assert_eq!(result, Some(vec!["src/".to_string(), "docs/".to_string()]));
}
#[test]
fn test_get_sparse_paths_none() {
let result = get_sparse_paths(None).unwrap();
assert!(result.is_none());
}
#[test]
fn test_get_sparse_paths_null_byte() {
let paths = Some(vec!["src/\0bad".to_string()]);
assert!(get_sparse_paths(paths).is_err());
}
#[test]
fn test_get_sparse_paths_empty_vec() {
let result = get_sparse_paths(Some(vec![])).unwrap();
assert_eq!(result, Some(vec![]));
}
#[test]
fn test_path_to_string_lossy_valid() {
let path = std::path::Path::new("valid_utf8");
assert_eq!(path_to_string_lossy(path), "valid_utf8");
}
#[test]
#[cfg(unix)]
fn test_path_to_string_lossy_invalid() {
use std::os::unix::ffi::OsStringExt;
let bytes = vec![0x61, 0xFF, 0x62]; // 'a', invalid, 'b'
let os_string = std::ffi::OsString::from_vec(bytes);
let path = std::path::Path::new(&os_string);
let result = path_to_string_lossy(path);
assert_eq!(result, format!("a{}b", std::char::REPLACEMENT_CHARACTER));
}
}