Skip to main content

sr_git/
lib.rs

1use std::path::{Path, PathBuf};
2use std::process::Command;
3
4use semver::Version;
5use sr_core::commit::Commit;
6use sr_core::error::ReleaseError;
7use sr_core::git::{GitRepository, TagInfo};
8
9/// Git repository implementation backed by native `git` CLI commands.
10pub struct NativeGitRepository {
11    path: PathBuf,
12}
13
14impl NativeGitRepository {
15    pub fn open(path: &Path) -> Result<Self, ReleaseError> {
16        let repo = Self {
17            path: path.to_path_buf(),
18        };
19        // Validate this is a git repo
20        repo.git(&["rev-parse", "--git-dir"])?;
21        Ok(repo)
22    }
23
24    fn git(&self, args: &[&str]) -> Result<String, ReleaseError> {
25        let output = Command::new("git")
26            .arg("-C")
27            .arg(&self.path)
28            .args(args)
29            .output()
30            .map_err(|e| ReleaseError::Git(format!("failed to run git: {e}")))?;
31
32        if !output.status.success() {
33            let stderr = String::from_utf8_lossy(&output.stderr);
34            return Err(ReleaseError::Git(format!(
35                "git {} failed: {}",
36                args.join(" "),
37                stderr.trim()
38            )));
39        }
40
41        Ok(String::from_utf8_lossy(&output.stdout).trim().to_string())
42    }
43
44    /// Parse owner/repo from a git remote URL.
45    pub fn parse_remote(&self) -> Result<(String, String), ReleaseError> {
46        let url = self.git(&["remote", "get-url", "origin"])?;
47        parse_owner_repo(&url)
48    }
49}
50
51/// Extract owner/repo from a GitHub remote URL.
52/// Supports SSH (git@github.com:owner/repo.git) and HTTPS (https://github.com/owner/repo.git).
53pub fn parse_owner_repo(url: &str) -> Result<(String, String), ReleaseError> {
54    let trimmed = url.trim_end_matches(".git");
55
56    // Try HTTPS/HTTP first: https://github.com/owner/repo
57    let path = trimmed
58        .strip_prefix("https://")
59        .or_else(|| trimmed.strip_prefix("http://"))
60        .and_then(|s| {
61            // Skip the hostname: "github.com/owner/repo" -> "owner/repo"
62            s.split_once('/').map(|(_, rest)| rest)
63        })
64        // Fall back to SSH style: git@github.com:owner/repo
65        .or_else(|| trimmed.rsplit_once(':').map(|(_, p)| p))
66        .ok_or_else(|| ReleaseError::Git(format!("cannot parse remote URL: {url}")))?;
67
68    let (owner, repo) = path
69        .split_once('/')
70        .ok_or_else(|| ReleaseError::Git(format!("cannot parse owner/repo from: {url}")))?;
71
72    Ok((owner.to_string(), repo.to_string()))
73}
74
75/// Parse the output of `git log --format=%H%n%an%n%B%n--END--` into commits.
76fn parse_commit_log(output: &str) -> Vec<Commit> {
77    if output.is_empty() {
78        return Vec::new();
79    }
80
81    let mut commits = Vec::new();
82    let mut current_sha: Option<String> = None;
83    let mut current_author: Option<String> = None;
84    let mut current_message = String::new();
85
86    for line in output.lines() {
87        if line == "--END--" {
88            if let Some(sha) = current_sha.take() {
89                commits.push(Commit {
90                    sha,
91                    message: current_message.trim().to_string(),
92                    author: current_author.take(),
93                });
94                current_message.clear();
95            }
96        } else if current_sha.is_none()
97            && line.len() == 40
98            && line.chars().all(|c| c.is_ascii_hexdigit())
99        {
100            current_sha = Some(line.to_string());
101        } else if current_sha.is_some() && current_author.is_none() {
102            current_author = Some(line.to_string());
103        } else {
104            if !current_message.is_empty() {
105                current_message.push('\n');
106            }
107            current_message.push_str(line);
108        }
109    }
110
111    // Handle last commit if no trailing --END--
112    if let Some(sha) = current_sha {
113        commits.push(Commit {
114            sha,
115            message: current_message.trim().to_string(),
116            author: current_author.take(),
117        });
118    }
119
120    commits
121}
122
123impl GitRepository for NativeGitRepository {
124    fn latest_tag(&self, prefix: &str) -> Result<Option<TagInfo>, ReleaseError> {
125        let pattern = format!("{prefix}*");
126        let result = self.git(&["tag", "--list", &pattern, "--sort=-v:refname"]);
127
128        let tags_output = match result {
129            Ok(output) if output.is_empty() => return Ok(None),
130            Ok(output) => output,
131            Err(_) => return Ok(None),
132        };
133
134        let tag_name = match tags_output.lines().next() {
135            Some(name) => name.trim(),
136            None => return Ok(None),
137        };
138
139        let version_str = tag_name.strip_prefix(prefix).unwrap_or(tag_name);
140        let version = match Version::parse(version_str) {
141            Ok(v) => v,
142            Err(_) => return Ok(None),
143        };
144
145        let sha = self.git(&["rev-list", "-1", tag_name])?;
146
147        Ok(Some(TagInfo {
148            name: tag_name.to_string(),
149            version,
150            sha,
151        }))
152    }
153
154    fn commits_since(&self, from: Option<&str>) -> Result<Vec<Commit>, ReleaseError> {
155        let range = match from {
156            Some(sha) => format!("{sha}..HEAD"),
157            None => "HEAD".to_string(),
158        };
159
160        let output = self.git(&["log", "--format=%H%n%an%n%B%n--END--", &range])?;
161        Ok(parse_commit_log(&output))
162    }
163
164    fn create_tag(&self, name: &str, message: &str) -> Result<(), ReleaseError> {
165        self.git(&["tag", "-a", name, "-m", message])?;
166        Ok(())
167    }
168
169    fn push_tag(&self, name: &str) -> Result<(), ReleaseError> {
170        self.git(&["push", "origin", name])?;
171        Ok(())
172    }
173
174    fn stage_and_commit(&self, paths: &[&str], message: &str) -> Result<bool, ReleaseError> {
175        let mut args = vec!["add", "--"];
176        args.extend(paths);
177        self.git(&args)?;
178
179        let status = self.git(&["status", "--porcelain"]);
180        match status {
181            Ok(s) if s.is_empty() => Ok(false),
182            _ => {
183                self.git(&["commit", "-m", message])?;
184                Ok(true)
185            }
186        }
187    }
188
189    fn push(&self) -> Result<(), ReleaseError> {
190        self.git(&["push", "origin", "HEAD"])?;
191        Ok(())
192    }
193
194    fn tag_exists(&self, name: &str) -> Result<bool, ReleaseError> {
195        match self.git(&["rev-parse", "--verify", &format!("refs/tags/{name}")]) {
196            Ok(_) => Ok(true),
197            Err(_) => Ok(false),
198        }
199    }
200
201    fn remote_tag_exists(&self, name: &str) -> Result<bool, ReleaseError> {
202        let output = self.git(&["ls-remote", "--tags", "origin", name])?;
203        Ok(!output.is_empty())
204    }
205
206    fn all_tags(&self, prefix: &str) -> Result<Vec<TagInfo>, ReleaseError> {
207        let pattern = format!("{prefix}*");
208        let result = self.git(&["tag", "--list", &pattern, "--sort=v:refname"]);
209
210        let tags_output = match result {
211            Ok(output) if output.is_empty() => return Ok(Vec::new()),
212            Ok(output) => output,
213            Err(_) => return Ok(Vec::new()),
214        };
215
216        let mut tags = Vec::new();
217        for line in tags_output.lines() {
218            let tag_name = line.trim();
219            if tag_name.is_empty() {
220                continue;
221            }
222            let version_str = tag_name.strip_prefix(prefix).unwrap_or(tag_name);
223            let version = match Version::parse(version_str) {
224                Ok(v) => v,
225                Err(_) => continue,
226            };
227            let sha = self.git(&["rev-list", "-1", tag_name])?;
228            tags.push(TagInfo {
229                name: tag_name.to_string(),
230                version,
231                sha,
232            });
233        }
234
235        Ok(tags)
236    }
237
238    fn commits_between(&self, from: Option<&str>, to: &str) -> Result<Vec<Commit>, ReleaseError> {
239        let range = match from {
240            Some(sha) => format!("{sha}..{to}"),
241            None => to.to_string(),
242        };
243
244        let output = self.git(&["log", "--format=%H%n%an%n%B%n--END--", &range])?;
245        Ok(parse_commit_log(&output))
246    }
247
248    fn tag_date(&self, tag_name: &str) -> Result<String, ReleaseError> {
249        let date = self.git(&["log", "-1", "--format=%cd", "--date=short", tag_name])?;
250        Ok(date)
251    }
252}
253
254#[cfg(test)]
255mod tests {
256    use super::*;
257
258    #[test]
259    fn parse_ssh_remote() {
260        let (owner, repo) = parse_owner_repo("git@github.com:urmzd/semantic-release.git").unwrap();
261        assert_eq!(owner, "urmzd");
262        assert_eq!(repo, "semantic-release");
263    }
264
265    #[test]
266    fn parse_https_remote() {
267        let (owner, repo) =
268            parse_owner_repo("https://github.com/urmzd/semantic-release.git").unwrap();
269        assert_eq!(owner, "urmzd");
270        assert_eq!(repo, "semantic-release");
271    }
272
273    #[test]
274    fn parse_https_no_git_suffix() {
275        let (owner, repo) = parse_owner_repo("https://github.com/urmzd/semantic-release").unwrap();
276        assert_eq!(owner, "urmzd");
277        assert_eq!(repo, "semantic-release");
278    }
279}