1use crate::config;
2use crate::git;
3
4pub fn wip_ref(name: &str, user: &str) -> String {
6 format!("refs/wip/{user}/{name}")
7}
8
9pub fn resolve_name(name: Option<String>) -> Result<String, String> {
11 match name {
12 Some(n) => Ok(slugify(&n)),
13 None => auto_name(),
14 }
15}
16
17fn auto_name() -> Result<String, String> {
19 let branch = git::git_stdout(&["rev-parse", "--abbrev-ref", "HEAD"])?;
20 Ok(slugify(&branch))
21}
22
23pub fn user() -> Result<String, String> {
25 config::user()
26}
27
28pub fn list_pattern(user: Option<&str>) -> String {
30 match user {
31 Some(u) => format!("refs/wip/{u}/"),
32 None => "refs/wip/".to_string(),
33 }
34}
35
36fn slugify(s: &str) -> String {
37 s.to_lowercase()
38 .chars()
39 .map(|c| {
40 if c.is_alphanumeric() || c == '-' {
41 c
42 } else {
43 '-'
44 }
45 })
46 .collect::<String>()
47 .trim_matches('-')
48 .to_string()
49}
50
51#[cfg(test)]
52mod tests {
53 use super::*;
54
55 #[test]
56 fn test_wip_ref() {
57 assert_eq!(wip_ref("auth-fix", "alice"), "refs/wip/alice/auth-fix");
58 assert_eq!(wip_ref("my-wip", "bob"), "refs/wip/bob/my-wip");
59 }
60
61 #[test]
62 fn test_slugify() {
63 assert_eq!(slugify("Hello World"), "hello-world");
64 assert_eq!(slugify("Feature/Auth"), "feature-auth");
65 assert_eq!(slugify("--leading-trailing--"), "leading-trailing");
66 assert_eq!(slugify("UPPER"), "upper");
67 assert_eq!(slugify("special!@#chars"), "special---chars");
68 assert_eq!(slugify("already-valid"), "already-valid");
69 }
70
71 #[test]
72 fn test_list_pattern() {
73 assert_eq!(list_pattern(Some("alice")), "refs/wip/alice/");
74 assert_eq!(list_pattern(None), "refs/wip/");
75 }
76}