rona 2.24.0

A simple CLI tool to help you with your git workflow.
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
//! Git Status Operations
//!
//! Git status processing functionality using the git CLI for handling different
//! file states and contexts.

use std::{collections::HashSet, process::Command};

use crate::errors::{GitError, Result, RonaError};

/// Unquotes a git path.
///
/// When a path contains special characters (spaces, non-ASCII bytes, etc.),
/// git wraps it in double quotes and uses C-style escape sequences. This
/// function strips the surrounding quotes and unescapes the content.
fn unquote_git_path(path: &str) -> String {
    if path.starts_with('"') && path.ends_with('"') && path.len() >= 2 {
        let inner = &path[1..path.len() - 1];
        // Collect raw bytes so that multi-byte UTF-8 octal sequences (e.g. \303\242 -> â)
        // are decoded correctly at the end rather than being misinterpreted as Latin-1.
        let mut result: Vec<u8> = Vec::with_capacity(inner.len());
        let mut chars = inner.chars().peekable();
        while let Some(ch) = chars.next() {
            if ch != '\\' {
                let mut buf = [0u8; 4];
                result.extend_from_slice(ch.encode_utf8(&mut buf).as_bytes());
                continue;
            }
            match chars.next() {
                Some('\\') | None => result.push(b'\\'),
                Some('"') => result.push(b'"'),
                Some('n') => result.push(b'\n'),
                Some('t') => result.push(b'\t'),
                Some('r') => result.push(b'\r'),
                Some(c @ '0'..='7') => {
                    // Octal escape: up to 3 digits
                    let mut octal = String::from(c);
                    for _ in 0..2 {
                        match chars.peek() {
                            Some(&d) if d.is_ascii_digit() && d <= '7' => {
                                octal.push(d);
                                chars.next();
                            }
                            _ => break,
                        }
                    }
                    if let Ok(byte) = u8::from_str_radix(&octal, 8) {
                        result.push(byte);
                    }
                }
                Some(c) => {
                    result.push(b'\\');
                    let mut buf = [0u8; 4];
                    result.extend_from_slice(c.encode_utf8(&mut buf).as_bytes());
                }
            }
        }
        return String::from_utf8_lossy(&result).into_owned();
    }
    path.to_string()
}

/// Runs `git status --porcelain=v1` and returns the output lines.
///
/// Each line has the format `XY PATH` where X is the index status and Y is the
/// working-tree status. For renamed files, the path may include ` -> ` separating
/// the old and new names.
///
/// # Errors
/// * If the git command fails or we are not in a git repository
fn run_git_status() -> Result<Vec<String>> {
    let output = Command::new("git")
        .args(["status", "--porcelain=v1"])
        .output()
        .map_err(RonaError::Io)?;

    if output.status.success() {
        let stdout = String::from_utf8_lossy(&output.stdout);
        return Ok(stdout.lines().map(String::from).collect());
    }

    let stderr = String::from_utf8_lossy(&output.stderr);
    if stderr.to_lowercase().contains("not a git repository") {
        return Err(RonaError::Git(GitError::RepositoryNotFound));
    }

    Err(RonaError::Git(GitError::CommandFailed {
        command: "git status".to_string(),
        output: stderr.trim().to_string(),
    }))
}

/// Returns the new paths of all staged renamed files.
///
/// Uses `git diff --cached --name-status --diff-filter=R` which outputs lines like:
/// `R100\told_name\tnew_name`
///
/// # Errors
/// * If the git command fails
fn get_renamed_new_paths() -> Result<Vec<String>> {
    let output = Command::new("git")
        .args(["diff", "--cached", "--name-status", "--diff-filter=R"])
        .output()
        .map_err(RonaError::Io)?;

    if !output.status.success() {
        return Ok(Vec::new());
    }

    let stdout = String::from_utf8_lossy(&output.stdout);
    let paths = stdout
        .lines()
        .filter_map(|line| {
            let parts: Vec<&str> = line.splitn(3, '\t').collect();
            if parts.len() >= 3 {
                Some(parts[2].to_string())
            } else {
                None
            }
        })
        .collect();

    Ok(paths)
}

/// Returns a list of all files that appear in git status
/// (modified, untracked, staged - but not deleted)
///
/// # Errors
/// * If reading git status fails
///
/// # Returns
/// * `Vec<String>` - List of files from git status
pub fn get_status_files() -> Result<Vec<String>> {
    let lines = run_git_status()?;
    let mut files: HashSet<String> = HashSet::new();

    for line in &lines {
        if line.len() < 4 {
            continue;
        }

        let mut chars = line.chars();
        let index_char = chars.next().unwrap_or(' ');
        let wt_char = chars.next().unwrap_or(' ');
        let path = unquote_git_path(&line[3..]);

        // Skip index-deleted entries unless the working tree has modifications
        if index_char == 'D' && wt_char != 'M' && wt_char != '?' {
            continue;
        }

        // Skip working-tree-deleted files
        if wt_char == 'D' {
            continue;
        }

        // For renames, collect new paths separately below
        if index_char == 'R' {
            continue;
        }

        files.insert(path);
    }

    // Add new paths for renamed files
    for path in get_renamed_new_paths()? {
        files.insert(path);
    }

    Ok(files.into_iter().collect())
}

/// A single entry from `git status` that has unstaged changes and can be staged.
///
/// Used by the interactive add mode (`rona -a -i`) to present a `MultiSelect` of
/// changed files. The [`Display`] implementation renders a human-readable status
/// label followed by the path, e.g. `modified    src/main.rs`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StatusEntry {
    /// Path to the file, relative to the repository root.
    pub path: String,
    /// Short, human-readable status label (e.g. "modified", "untracked").
    pub status: &'static str,
}

impl std::fmt::Display for StatusEntry {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:<11} {}", self.status, self.path)
    }
}

/// Returns the files that currently have unstaged changes and can be staged.
///
/// This includes untracked files and files with working-tree modifications,
/// deletions or type changes. Fully staged files with no remaining working-tree
/// changes are omitted, since there is nothing left to stage for them.
///
/// The list is sorted by path for stable, predictable ordering in the selector.
///
/// # Errors
/// * If reading git status fails
///
/// # Returns
/// * `Vec<StatusEntry>` - The stageable files with their status labels
pub fn get_stageable_files() -> Result<Vec<StatusEntry>> {
    let lines = run_git_status()?;
    let mut entries = Vec::new();

    for line in &lines {
        if line.len() < 4 {
            continue;
        }

        let mut chars = line.chars();
        let index_char = chars.next().unwrap_or(' ');
        let wt_char = chars.next().unwrap_or(' ');

        let is_untracked = index_char == '?' && wt_char == '?';

        // Skip files whose working tree matches the index (nothing left to stage).
        if wt_char == ' ' && !is_untracked {
            continue;
        }

        // For renamed-and-modified entries the path is "old -> new"; stage the new path.
        let raw_path = &line[3..];
        let path_part = raw_path.rsplit(" -> ").next().unwrap_or(raw_path);
        let path = unquote_git_path(path_part);

        let status = match wt_char {
            'D' => "deleted",
            'T' => "type change",
            '?' => "untracked",
            _ => "modified",
        };

        entries.push(StatusEntry { path, status });
    }

    entries.sort_by(|a, b| a.path.cmp(&b.path));
    Ok(entries)
}

/// Processes deleted files that need to be staged for deletion.
/// Only returns files that are deleted in the working directory but not yet staged.
///
/// # Errors
/// * If reading git status fails
///
/// # Returns
/// * `Result<Vec<String>>` - Files that need to be staged for deletion
pub fn process_deleted_files_for_staging() -> Result<Vec<String>> {
    let lines = run_git_status()?;
    let mut deleted_files = Vec::new();

    for line in &lines {
        if line.len() < 4 {
            continue;
        }

        let mut chars = line.chars();
        let index_char = chars.next().unwrap_or(' ');
        let wt_char = chars.next().unwrap_or(' ');
        let path = unquote_git_path(&line[3..]);

        // Working-tree deleted but NOT staged for deletion (index char != 'D')
        if wt_char == 'D' && index_char != 'D' {
            deleted_files.push(path);
        }
    }

    Ok(deleted_files)
}

/// Processes deleted files for commit message generation.
/// Returns all deleted files that are staged for deletion.
///
/// # Errors
/// * If reading git status fails
///
/// # Returns
/// * `Result<Vec<String>>` - All deleted files for the commit message
pub fn process_deleted_files_for_commit_message() -> Result<Vec<String>> {
    let lines = run_git_status()?;
    let mut deleted_files = Vec::new();

    for line in &lines {
        if line.len() < 4 {
            continue;
        }

        let index_char = line.chars().next().unwrap_or(' ');
        let path = unquote_git_path(&line[3..]);

        // Index-deleted (staged deletion)
        if index_char == 'D' {
            deleted_files.push(path);
        }
    }

    Ok(deleted_files)
}

/// Processes the git status.
/// Returns the modified/added/renamed/type-changed files in the index,
/// to prepare the git commit message.
///
/// # Errors
/// * If reading git status fails
///
/// # Returns
/// * `Result<Vec<String>>` - The modified/added files
pub fn process_git_status() -> Result<Vec<String>> {
    let lines = run_git_status()?;
    let mut files = Vec::new();

    for line in &lines {
        if line.len() < 4 {
            continue;
        }

        let index_char = line.chars().next().unwrap_or(' ');
        let path = unquote_git_path(&line[3..]);

        match index_char {
            'M' | 'A' | 'T' => files.push(path),
            _ => {} // 'R' (renamed) files are collected separately below; skip all others
        }
    }

    // Add new paths for renamed files
    files.extend(get_renamed_new_paths()?);

    Ok(files)
}

/// Returns all file paths currently staged in the index.
///
/// Used after `git add -A` to discover which staged files should be unstaged
/// based on exclude patterns.
///
/// # Errors
/// * If reading git status fails
///
/// # Returns
/// * `Result<Vec<String>>` - All staged file paths
pub fn get_all_staged_file_paths() -> Result<Vec<String>> {
    let lines = run_git_status()?;
    let mut files: HashSet<String> = HashSet::new();

    for line in &lines {
        if line.len() < 4 {
            continue;
        }

        let mut chars = line.chars();
        let index_char = chars.next().unwrap_or(' ');

        // Skip untracked and purely unstaged entries
        if index_char == ' ' || index_char == '?' {
            continue;
        }

        // Renames are handled separately to get the new path
        if index_char == 'R' {
            continue;
        }

        let path = unquote_git_path(&line[3..]);
        files.insert(path);
    }

    // Add new paths for renamed files
    for path in get_renamed_new_paths()? {
        files.insert(path);
    }

    Ok(files.into_iter().collect())
}

/// Counts the number of renamed files in the git status.
///
/// This function helps with accurate file counting since renamed files appear
/// as 2 lines in `git diff --cached --numstat` (one deletion, one addition).
///
/// # Errors
/// * If reading git status fails
///
/// # Returns
/// * `Result<usize>` - The count of renamed files
pub fn count_renamed_files() -> Result<usize> {
    let lines = run_git_status()?;
    let count = lines
        .iter()
        .filter(|line| !line.is_empty() && line.starts_with('R'))
        .count();
    Ok(count)
}

#[cfg(test)]
mod tests {
    use super::unquote_git_path;

    #[test]
    fn test_unquote_plain_path() {
        assert_eq!(unquote_git_path("src/main.rs"), "src/main.rs");
    }

    #[test]
    fn test_unquote_quoted_path_with_spaces() {
        assert_eq!(
            unquote_git_path("\"assets/foo bar/file.txt\""),
            "assets/foo bar/file.txt"
        );
    }

    #[test]
    fn test_unquote_escape_sequences() {
        assert_eq!(unquote_git_path("\"a\\\\b\""), "a\\b");
        assert_eq!(unquote_git_path("\"a\\\"b\""), "a\"b");
        assert_eq!(unquote_git_path("\"a\\nb\""), "a\nb");
    }

    #[test]
    fn test_unquote_octal_escape() {
        // Space is octal 040
        assert_eq!(unquote_git_path("\"a\\040b\""), "a b");
    }

    #[test]
    fn test_unquote_multibyte_utf8_octal() {
        // â is U+00E2, encoded in UTF-8 as 0xC3 0xA2 (octal \303\242)
        // git quotes filenames like "Marags\303\242-Display.otf"
        assert_eq!(
            unquote_git_path("\"Marags\\303\\242-Display.otf\""),
            "Maragsâ-Display.otf"
        );
    }
}