rung-core 0.8.0

Core library for Rung - stack model, state management, sync engine
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
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//! Branch name validation and newtype.
//!
//! Provides a [`BranchName`] type that enforces git branch name rules
//! and prevents security issues like path traversal and shell injection.
//!
//! Also provides [`slugify`] to convert arbitrary text into a valid branch name.

use std::fmt;

use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::Error;

/// A validated git branch name.
///
/// This newtype ensures branch names are valid according to git's rules
/// and don't contain dangerous characters that could enable:
/// - Path traversal attacks (`../`)
/// - Shell injection (`$`, `;`, `|`, etc.)
///
/// # Examples
///
/// ```
/// use rung_core::BranchName;
///
/// // Valid branch names
/// let name = BranchName::new("feature/auth").unwrap();
/// let name = BranchName::new("fix-bug-123").unwrap();
///
/// // Invalid branch names
/// assert!(BranchName::new("../etc/passwd").is_err());
/// assert!(BranchName::new("name;rm -rf").is_err());
/// assert!(BranchName::new("branch..name").is_err());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct BranchName(String);

impl BranchName {
    /// Create a new validated branch name.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidBranchName`] if the name violates git's
    /// branch naming rules or contains dangerous characters.
    pub fn new(name: impl Into<String>) -> Result<Self, Error> {
        let name = name.into();
        validate_branch_name(&name)?;
        Ok(Self(name))
    }

    /// Create a branch name by slugifying a commit message.
    ///
    /// Takes the first line of the message, converts to lowercase,
    /// and replaces non-alphanumeric characters with hyphens.
    ///
    /// # Errors
    ///
    /// Returns [`Error::InvalidBranchName`] if the slugified result is invalid
    /// (e.g., empty message).
    ///
    /// # Examples
    ///
    /// ```
    /// use rung_core::BranchName;
    ///
    /// let name = BranchName::from_message("feat: add authentication").unwrap();
    /// assert_eq!(name.as_str(), "feat-add-authentication");
    /// ```
    pub fn from_message(message: &str) -> Result<Self, Error> {
        let slugified = slugify(message);

        if slugified.is_empty() {
            return Err(Error::InvalidBranchName {
                name: message.to_string(),
                reason: "message contains no alphanumeric characters".to_string(),
            });
        }

        Self::new(slugified)
    }

    /// Get the branch name as a string slice.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consume the `BranchName` and return the inner `String`.
    #[must_use]
    pub fn into_inner(self) -> String {
        self.0
    }
}

impl AsRef<str> for BranchName {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl std::ops::Deref for BranchName {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl fmt::Display for BranchName {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

impl PartialEq<str> for BranchName {
    fn eq(&self, other: &str) -> bool {
        self.0 == other
    }
}

impl PartialEq<&str> for BranchName {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

impl PartialEq<String> for BranchName {
    fn eq(&self, other: &String) -> bool {
        self.0 == *other
    }
}

impl Serialize for BranchName {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.0)
    }
}

impl<'de> Deserialize<'de> for BranchName {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let s = String::deserialize(deserializer)?;
        Self::new(s).map_err(serde::de::Error::custom)
    }
}

/// Validate a branch name against git rules and security constraints.
fn validate_branch_name(name: &str) -> Result<(), Error> {
    // Empty name
    if name.is_empty() {
        return Err(Error::InvalidBranchName {
            name: name.to_string(),
            reason: "branch name cannot be empty".to_string(),
        });
    }

    // Single @ is not allowed
    if name == "@" {
        return Err(Error::InvalidBranchName {
            name: name.to_string(),
            reason: "branch name cannot be '@'".to_string(),
        });
    }

    // Cannot start with a dot
    if name.starts_with('.') {
        return Err(Error::InvalidBranchName {
            name: name.to_string(),
            reason: "branch name cannot start with '.'".to_string(),
        });
    }

    // Cannot end with a dot
    if name.ends_with('.') {
        return Err(Error::InvalidBranchName {
            name: name.to_string(),
            reason: "branch name cannot end with '.'".to_string(),
        });
    }

    // Cannot end with .lock (git's rule is case-sensitive)
    #[allow(clippy::case_sensitive_file_extension_comparisons)]
    if name.ends_with(".lock") {
        return Err(Error::InvalidBranchName {
            name: name.to_string(),
            reason: "branch name cannot end with '.lock'".to_string(),
        });
    }

    // Cannot start or end with a slash
    if name.starts_with('/') || name.ends_with('/') {
        return Err(Error::InvalidBranchName {
            name: name.to_string(),
            reason: "branch name cannot start or end with '/'".to_string(),
        });
    }

    // Check for invalid patterns and characters
    for (i, c) in name.chars().enumerate() {
        // Control characters (0x00-0x1f, 0x7f)
        if c.is_ascii_control() {
            return Err(Error::InvalidBranchName {
                name: name.to_string(),
                reason: "branch name cannot contain control characters".to_string(),
            });
        }

        // Git-forbidden characters: space ~ ^ : ? * [
        if matches!(c, ' ' | '~' | '^' | ':' | '?' | '*' | '[') {
            return Err(Error::InvalidBranchName {
                name: name.to_string(),
                reason: format!("branch name cannot contain '{c}'"),
            });
        }

        // Shell metacharacters for security: $ ; | & > < ` \ " ' ( ) { } !
        if matches!(
            c,
            '$' | ';'
                | '|'
                | '&'
                | '>'
                | '<'
                | '`'
                | '\\'
                | '"'
                | '\''
                | '('
                | ')'
                | '{'
                | '}'
                | '!'
        ) {
            return Err(Error::InvalidBranchName {
                name: name.to_string(),
                reason: format!("branch name cannot contain shell metacharacter '{c}'"),
            });
        }

        // Check for consecutive dots (..)
        if c == '.' && name.chars().nth(i + 1) == Some('.') {
            return Err(Error::InvalidBranchName {
                name: name.to_string(),
                reason: "branch name cannot contain '..'".to_string(),
            });
        }

        // Check for consecutive slashes (//)
        if c == '/' && name.chars().nth(i + 1) == Some('/') {
            return Err(Error::InvalidBranchName {
                name: name.to_string(),
                reason: "branch name cannot contain '//'".to_string(),
            });
        }

        // Check for @{ sequence
        if c == '@' && name.chars().nth(i + 1) == Some('{') {
            return Err(Error::InvalidBranchName {
                name: name.to_string(),
                reason: "branch name cannot contain '@{'".to_string(),
            });
        }

        // Check for slash followed by dot (/.component)
        if c == '/' && name.chars().nth(i + 1) == Some('.') {
            return Err(Error::InvalidBranchName {
                name: name.to_string(),
                reason: "branch name component cannot start with '.'".to_string(),
            });
        }
    }

    Ok(())
}

/// Maximum length for generated branch names.
const MAX_BRANCH_NAME_LENGTH: usize = 50;

/// Convert arbitrary text into a git-safe branch name.
///
/// Takes the first line and slugifies it:
/// - Converts to lowercase
/// - Replaces non-alphanumeric characters with hyphens
/// - Removes consecutive/leading/trailing hyphens
/// - Truncates to 50 characters at word boundaries
///
/// # Examples
///
/// ```
/// use rung_core::slugify;
///
/// assert_eq!(slugify("feat: add authentication"), "feat-add-authentication");
/// assert_eq!(slugify("Fix login bug"), "fix-login-bug");
/// assert_eq!(slugify("feat(auth): add OAuth support"), "feat-auth-add-oauth-support");
///
/// // Long messages are truncated at word boundaries
/// let long_msg = "feat: implement very long feature name that exceeds the maximum length";
/// let result = slugify(long_msg);
/// assert!(result.len() <= 50);
/// assert!(!result.ends_with('-'));
/// ```
#[must_use]
pub fn slugify(text: &str) -> String {
    let first_line = text.lines().next().unwrap_or(text);

    let slug: String = first_line
        .to_lowercase()
        .chars()
        .map(|c| if c.is_alphanumeric() { c } else { '-' })
        .collect::<String>()
        .split('-')
        .filter(|s| !s.is_empty())
        .collect::<Vec<_>>()
        .join("-");

    // Truncate at word boundary if too long (character-safe for UTF-8)
    if slug.chars().count() <= MAX_BRANCH_NAME_LENGTH {
        return slug;
    }

    // Find last hyphen within the character limit
    // Track both character count and byte index for proper UTF-8 slicing
    let mut last_hyphen_byte_pos = None;
    for (char_count, (byte_pos, c)) in slug.char_indices().enumerate() {
        if char_count >= MAX_BRANCH_NAME_LENGTH {
            break;
        }
        if c == '-' {
            last_hyphen_byte_pos = Some(byte_pos);
        }
    }

    last_hyphen_byte_pos.map_or_else(
        || slug.chars().take(MAX_BRANCH_NAME_LENGTH).collect(),
        |pos| slug[..pos].to_string(),
    )
}

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

    #[test]
    fn test_valid_branch_names() {
        // Simple names
        assert!(BranchName::new("main").is_ok());
        assert!(BranchName::new("master").is_ok());
        assert!(BranchName::new("develop").is_ok());

        // With slashes (hierarchical)
        assert!(BranchName::new("feature/auth").is_ok());
        assert!(BranchName::new("feature/user/login").is_ok());
        assert!(BranchName::new("fix/bug-123").is_ok());

        // With dashes and underscores
        assert!(BranchName::new("my-feature").is_ok());
        assert!(BranchName::new("my_feature").is_ok());
        assert!(BranchName::new("feature-123-fix").is_ok());

        // With numbers
        assert!(BranchName::new("v1.0.0").is_ok());
        assert!(BranchName::new("release-2024-01").is_ok());

        // With @ (not followed by {)
        assert!(BranchName::new("user@feature").is_ok());
    }

    #[test]
    fn test_empty_name() {
        let err = BranchName::new("").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_single_at() {
        let err = BranchName::new("@").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_starts_with_dot() {
        let err = BranchName::new(".hidden").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_ends_with_dot() {
        let err = BranchName::new("branch.").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_ends_with_lock() {
        let err = BranchName::new("branch.lock").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_consecutive_dots() {
        let err = BranchName::new("branch..name").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));

        // Path traversal attempt
        let err = BranchName::new("../etc/passwd").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_slash_rules() {
        // Starts with slash
        let err = BranchName::new("/branch").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));

        // Ends with slash
        let err = BranchName::new("branch/").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));

        // Consecutive slashes
        let err = BranchName::new("feature//auth").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));

        // Slash followed by dot
        let err = BranchName::new("feature/.hidden").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_git_forbidden_characters() {
        for c in [' ', '~', '^', ':', '?', '*', '['] {
            let name = format!("branch{c}name");
            let err = BranchName::new(&name).unwrap_err();
            assert!(matches!(err, Error::InvalidBranchName { .. }), "char: {c}");
        }
    }

    #[test]
    fn test_shell_metacharacters() {
        for c in [
            '$', ';', '|', '&', '>', '<', '`', '\\', '"', '\'', '(', ')', '{', '}', '!',
        ] {
            let name = format!("branch{c}name");
            let err = BranchName::new(&name).unwrap_err();
            assert!(matches!(err, Error::InvalidBranchName { .. }), "char: {c}");
        }
    }

    #[test]
    fn test_shell_injection_attempts() {
        // Command substitution
        let err = BranchName::new("branch$(whoami)").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));

        // Command chaining
        let err = BranchName::new("branch;rm -rf /").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));

        // Pipe
        let err = BranchName::new("branch|cat /etc/passwd").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_at_brace_sequence() {
        let err = BranchName::new("branch@{1}").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_control_characters() {
        let err = BranchName::new("branch\x00name").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));

        let err = BranchName::new("branch\tname").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));

        let err = BranchName::new("branch\nname").unwrap_err();
        assert!(matches!(err, Error::InvalidBranchName { .. }));
    }

    #[test]
    fn test_display_and_deref() {
        let name = BranchName::new("feature/auth").unwrap();
        assert_eq!(format!("{name}"), "feature/auth");
        assert_eq!(name.as_str(), "feature/auth");
        assert_eq!(&*name, "feature/auth");
    }

    #[test]
    fn test_serialize_deserialize() {
        let name = BranchName::new("feature/auth").unwrap();

        // Serialize
        let json = serde_json::to_string(&name).unwrap();
        assert_eq!(json, "\"feature/auth\"");

        // Deserialize valid
        let parsed: BranchName = serde_json::from_str("\"feature/test\"").unwrap();
        assert_eq!(parsed.as_str(), "feature/test");

        // Deserialize invalid should fail
        let result: Result<BranchName, _> = serde_json::from_str("\"..invalid\"");
        assert!(result.is_err());
    }

    // === slugify tests ===

    #[test]
    fn test_slugify_basic() {
        assert_eq!(
            slugify("feat: add authentication"),
            "feat-add-authentication"
        );
        assert_eq!(slugify("Fix login bug"), "fix-login-bug");
        assert_eq!(
            slugify("feat(auth): add OAuth support"),
            "feat-auth-add-oauth-support"
        );
    }

    #[test]
    fn test_slugify_whitespace_only() {
        assert_eq!(slugify("   "), "");
        assert_eq!(slugify("\t\n"), "");
    }

    #[test]
    fn test_slugify_empty() {
        assert_eq!(slugify(""), "");
    }

    #[test]
    fn test_slugify_emoji_only() {
        assert_eq!(slugify("🔥🚀"), "");
        assert_eq!(slugify("✨ ⭐ 💫"), "");
    }

    #[test]
    fn test_slugify_multiline() {
        // Only first line should be used
        assert_eq!(
            slugify("feat: add auth\n\nThis is a longer description"),
            "feat-add-auth"
        );
        assert_eq!(slugify("fix: bug\nSecond line\nThird line"), "fix-bug");
    }

    #[test]
    fn test_slugify_truncation() {
        // 50 char limit at word boundary
        let long_msg =
            "feat: implement very long feature name that exceeds the maximum length allowed";
        let result = slugify(long_msg);
        assert!(result.chars().count() <= 50);
        assert!(!result.ends_with('-'));
        // Should truncate at word boundary
        assert_eq!(result, "feat-implement-very-long-feature-name-that");
    }

    #[test]
    fn test_slugify_truncation_no_hyphen() {
        // Very long single word should just truncate at char limit
        let long_word = "a".repeat(60);
        let result = slugify(&long_word);
        assert_eq!(result.chars().count(), 50);
    }

    #[test]
    fn test_slugify_unicode() {
        // Accented characters (alphanumeric in Unicode)
        assert_eq!(slugify("café feature"), "café-feature");
        assert_eq!(slugify("naïve implementation"), "naïve-implementation");

        // CJK characters
        assert_eq!(slugify("新功能 feature"), "新功能-feature");

        // Mixed unicode and ASCII
        assert_eq!(slugify("über cool änderung"), "über-cool-änderung");
    }

    #[test]
    fn test_slugify_special_chars() {
        assert_eq!(slugify("fix: bug #123"), "fix-bug-123");
        assert_eq!(
            slugify("feat(scope): add [feature]"),
            "feat-scope-add-feature"
        );
        assert_eq!(slugify("fix: path/to/file"), "fix-path-to-file");
    }

    // === from_message tests ===

    #[test]
    fn test_from_message_basic() {
        let name = BranchName::from_message("feat: add authentication").unwrap();
        assert_eq!(name.as_str(), "feat-add-authentication");
    }

    #[test]
    fn test_from_message_empty_error() {
        let result = BranchName::from_message("");
        assert!(result.is_err());
        if let Err(Error::InvalidBranchName { reason, .. }) = result {
            assert!(reason.contains("no alphanumeric"));
        }
    }

    #[test]
    fn test_from_message_whitespace_only_error() {
        let result = BranchName::from_message("   \t\n  ");
        assert!(result.is_err());
    }

    #[test]
    fn test_from_message_emoji_only_error() {
        let result = BranchName::from_message("🔥🚀✨");
        assert!(result.is_err());
        if let Err(Error::InvalidBranchName { reason, .. }) = result {
            assert!(reason.contains("no alphanumeric"));
        }
    }

    #[test]
    fn test_from_message_multiline() {
        let name = BranchName::from_message("feat: add auth\n\nDetailed description here").unwrap();
        assert_eq!(name.as_str(), "feat-add-auth");
    }

    #[test]
    fn test_into_inner() {
        let name = BranchName::new("feature/auth").unwrap();
        let inner: String = name.into_inner();
        assert_eq!(inner, "feature/auth");
    }

    #[test]
    fn test_as_ref() {
        let name = BranchName::new("feature/auth").unwrap();
        let s: &str = name.as_ref();
        assert_eq!(s, "feature/auth");
    }
}