Skip to main content

opensession_git_native/
url.rs

1/// Generate a raw content URL from the git remote and file path.
2pub fn generate_raw_url(remote_url: &str, rev: &str, rel_path: &str) -> String {
3    // Normalize remote URL to extract owner/repo
4    let normalized = remote_url
5        .trim_end_matches(".git")
6        .replace("git@github.com:", "https://github.com/")
7        .replace("git@gitlab.com:", "https://gitlab.com/");
8
9    if normalized.contains("github.com") {
10        // https://raw.githubusercontent.com/{owner}/{repo}/{rev}/{path}
11        let path = normalized.trim_start_matches("https://github.com/");
12        format!(
13            "https://raw.githubusercontent.com/{}/{}/{}",
14            path, rev, rel_path
15        )
16    } else if normalized.contains("gitlab.com") {
17        // https://gitlab.com/{owner}/{repo}/-/raw/{rev}/{path}
18        let path = normalized.trim_start_matches("https://gitlab.com/");
19        format!("https://gitlab.com/{}/-/raw/{}/{}", path, rev, rel_path)
20    } else {
21        // Fallback: just use the remote URL as base
22        format!("{}/raw/{}/{}", normalized, rev, rel_path)
23    }
24}
25
26#[cfg(test)]
27mod tests {
28    use super::*;
29
30    #[test]
31    fn test_github_ssh_url() {
32        let url = generate_raw_url(
33            "git@github.com:user/repo.git",
34            "abcd1234",
35            "v1/ab/abc123.hail.jsonl",
36        );
37        assert_eq!(
38            url,
39            "https://raw.githubusercontent.com/user/repo/abcd1234/v1/ab/abc123.hail.jsonl"
40        );
41    }
42
43    #[test]
44    fn test_github_https_url() {
45        let url = generate_raw_url(
46            "https://github.com/user/repo",
47            "refs/opensession/branches/bWFpbg",
48            "v1/ab/abc123.hail.jsonl",
49        );
50        assert_eq!(
51            url,
52            "https://raw.githubusercontent.com/user/repo/refs/opensession/branches/bWFpbg/v1/ab/abc123.hail.jsonl"
53        );
54    }
55
56    #[test]
57    fn test_gitlab_url() {
58        let url = generate_raw_url(
59            "git@gitlab.com:user/repo.git",
60            "abcd1234",
61            "v1/ab/abc123.hail.jsonl",
62        );
63        assert_eq!(
64            url,
65            "https://gitlab.com/user/repo/-/raw/abcd1234/v1/ab/abc123.hail.jsonl"
66        );
67    }
68}