Skip to main content

lit/commands/
reword.rs

1use crate::core::{
2    find_repo_root, get_current_branch, read_head, write_ref, Commit, Object, ObjectHash,
3};
4use crate::response::CommitResponse;
5use crate::storage::ObjectStore;
6
7/// Reword the commit message of the most recent commit (or a specified commit).
8pub fn execute(
9    new_message: String,
10    _target: Option<String>,
11) -> Result<CommitResponse, crate::errors::LitError> {
12    let repo_root = find_repo_root()?;
13    let store = ObjectStore::new(&repo_root);
14
15    let head_hash = read_head(&repo_root)?;
16    let head_obj = store.read(&ObjectHash::from_hex(head_hash.clone()))?;
17
18    let old_commit = match head_obj {
19        Object::Commit(c) => c,
20        _ => return Err("HEAD is not a commit".into()),
21    };
22
23    let parents = old_commit.parents.clone();
24    let parent_str = parents.first().map(|p| p.to_string());
25    let author_name = old_commit.author.clone();
26    let tree_hash = old_commit.tree.clone();
27
28    // Create new commit with updated message, same tree and parents
29    let commit = Commit::new(
30        tree_hash.clone(),
31        parents,
32        author_name.clone(),
33        new_message.clone(),
34    );
35    let timestamp = commit.timestamp;
36    let commit_object = Object::Commit(commit);
37    let commit_hash = store.write(&commit_object)?;
38
39    // Update branch ref
40    let branch = get_current_branch(&repo_root).unwrap_or_else(|_| "main".to_string());
41    write_ref(
42        &repo_root,
43        &format!("heads/{}", branch),
44        commit_hash.as_str(),
45    )?;
46
47    Ok(CommitResponse {
48        hash: commit_hash.to_string(),
49        short_hash: commit_hash.short().to_string(),
50        tree: tree_hash.to_string(),
51        parent: parent_str,
52        author: author_name,
53        message: new_message,
54        timestamp,
55    })
56}