pop_common/
git.rs

1// SPDX-License-Identifier: GPL-3.0
2
3use crate::{api::ApiClient, errors::Error, polkadot_sdk::parse_latest_tag};
4use anyhow::Result;
5use git2::{
6	build::RepoBuilder, FetchOptions, IndexAddOption, RemoteCallbacks, Repository as GitRepository,
7	ResetType,
8};
9use git2_credentials::CredentialHandler;
10use std::{fs, path::Path, sync::LazyLock};
11use url::Url;
12
13/// A helper for handling Git operations.
14pub struct Git;
15impl Git {
16	/// Clone a Git repository.
17	///
18	/// # Arguments
19	/// * `url` - the URL of the repository to clone.
20	/// * `working_dir` - the target working directory.
21	/// * `reference` - an optional reference (revision/tag).
22	pub fn clone(url: &Url, working_dir: &Path, reference: Option<&str>) -> Result<()> {
23		let mut fo = FetchOptions::new();
24		if reference.is_none() {
25			fo.depth(1);
26		}
27		let mut repo = RepoBuilder::new();
28		repo.fetch_options(fo);
29		let repo = match repo.clone(url.as_str(), working_dir) {
30			Ok(repository) => repository,
31			Err(e) => match Self::ssh_clone(url, working_dir) {
32				Ok(repository) => repository,
33				Err(_) => return Err(e.into()),
34			},
35		};
36
37		if let Some(reference) = reference {
38			let object = repo
39				.revparse_single(reference)
40				.or_else(|_| repo.revparse_single(&format!("refs/tags/{}", reference)))
41				.or_else(|_| repo.revparse_single(&format!("refs/remotes/origin/{}", reference)))?;
42			repo.checkout_tree(&object, None)?;
43			repo.set_head_detached(object.id())?;
44		}
45		Ok(())
46	}
47
48	fn ssh_clone(url: &Url, working_dir: &Path) -> Result<GitRepository> {
49		let ssh_url = GitHub::convert_to_ssh_url(url);
50		// Prepare callback and fetch options.
51		let mut fo = FetchOptions::new();
52		Self::set_up_ssh_fetch_options(&mut fo)?;
53		// Prepare builder and clone.
54		let mut repo = RepoBuilder::new();
55		repo.fetch_options(fo);
56		Ok(repo.clone(&ssh_url, working_dir)?)
57	}
58
59	/// Clone a Git repository and degit it.
60	///
61	/// # Arguments
62	///
63	/// * `url` - the URL of the repository to clone.
64	/// * `target` - location where the repository will be cloned.
65	/// * `tag_version` - the specific tag or version of the repository to use
66	pub fn clone_and_degit(
67		url: &str,
68		target: &Path,
69		tag_version: Option<String>,
70	) -> Result<Option<String>> {
71		let repo = match GitRepository::clone(url, target) {
72			Ok(repo) => repo,
73			Err(_e) => Self::ssh_clone_and_degit(Url::parse(url).map_err(Error::from)?, target)?,
74		};
75
76		if let Some(tag_version) = tag_version {
77			let (object, reference) = repo.revparse_ext(&tag_version).expect("Object not found");
78			repo.checkout_tree(&object, None).expect("Failed to checkout");
79			match reference {
80				// gref is an actual reference like branches or tags
81				Some(gref) => repo.set_head(gref.name().unwrap()),
82				// this is a commit, not a reference
83				None => repo.set_head_detached(object.id()),
84			}
85			.expect("Failed to set HEAD");
86
87			let git_dir = repo.path();
88			fs::remove_dir_all(git_dir)?;
89			return Ok(Some(tag_version));
90		}
91
92		// fetch tags from remote
93		let release = Self::fetch_latest_tag(&repo);
94
95		let git_dir = repo.path();
96		fs::remove_dir_all(git_dir)?;
97		// Or by default the last one
98		Ok(release)
99	}
100
101	/// For users that have ssh configuration for cloning repositories.
102	fn ssh_clone_and_degit(url: Url, target: &Path) -> Result<GitRepository> {
103		let ssh_url = GitHub::convert_to_ssh_url(&url);
104		// Prepare callback and fetch options.
105		let mut fo = FetchOptions::new();
106		Self::set_up_ssh_fetch_options(&mut fo)?;
107		// Prepare builder and clone.
108		let mut builder = RepoBuilder::new();
109		builder.fetch_options(fo);
110		let repo = builder.clone(&ssh_url, target)?;
111		Ok(repo)
112	}
113
114	fn set_up_ssh_fetch_options(fo: &mut FetchOptions) -> Result<()> {
115		let mut callbacks = RemoteCallbacks::new();
116		let git_config = git2::Config::open_default()
117			.map_err(|e| Error::Config(format!("Cannot open git configuration: {}", e)))?;
118		let mut ch = CredentialHandler::new(git_config);
119		callbacks.credentials(move |url, username, allowed| {
120			ch.try_next_credential(url, username, allowed)
121		});
122
123		fo.remote_callbacks(callbacks);
124		Ok(())
125	}
126
127	/// Fetch the latest release from a repository
128	fn fetch_latest_tag(repo: &GitRepository) -> Option<String> {
129		let tags = repo.tag_names(None).ok()?;
130		parse_latest_tag(&tags.iter().flatten().collect::<Vec<_>>()).map(|t| t.to_string())
131	}
132
133	/// Init a new git repository.
134	///
135	/// # Arguments
136	///
137	/// * `target` - location where the parachain will be created.
138	/// * `message` - message for first commit.
139	pub fn git_init(target: &Path, message: &str) -> Result<(), git2::Error> {
140		let repo = GitRepository::init(target)?;
141		let signature = repo.signature()?;
142
143		let mut index = repo.index()?;
144		index.add_all(["*"].iter(), IndexAddOption::DEFAULT, None)?;
145		let tree_id = index.write_tree()?;
146
147		let tree = repo.find_tree(tree_id)?;
148		let commit_id = repo.commit(Some("HEAD"), &signature, &signature, message, &tree, &[])?;
149
150		let commit_object = repo.find_object(commit_id, Some(git2::ObjectType::Commit))?;
151		repo.reset(&commit_object, ResetType::Hard, None)?;
152
153		Ok(())
154	}
155}
156
157/// A client for the GitHub REST API.
158pub(crate) static GITHUB_API_CLIENT: LazyLock<ApiClient> = LazyLock::new(|| {
159	// GitHub API: unauthenticated = 60 requests per hour, authenticated = 5,000 requests per hour,
160	// GitHub Actions = 1,000 requests per hour per repository
161	ApiClient::new(1, std::env::var("GITHUB_TOKEN").ok())
162});
163
164/// A helper for handling GitHub operations.
165pub struct GitHub {
166	/// The organization name.
167	pub org: String,
168	/// The repository name
169	pub name: String,
170	api: String,
171}
172
173impl GitHub {
174	const GITHUB: &'static str = "github.com";
175
176	/// Parse URL of a GitHub repository.
177	///
178	/// # Arguments
179	///
180	/// * `url` - the URL of the repository to clone.
181	pub fn parse(url: &str) -> Result<Self> {
182		let url = Url::parse(url)?;
183		Ok(Self::new(Self::org(&url)?, Self::name(&url)?))
184	}
185
186	/// Create a new [GitHub] instance.
187	///
188	/// # Arguments
189	/// * `org` - The organization name.
190	/// * `name` - The repository name.
191	pub(crate) fn new(org: impl Into<String>, name: impl Into<String>) -> Self {
192		Self { org: org.into(), name: name.into(), api: "https://api.github.com".into() }
193	}
194
195	// Overrides the api base url for testing
196	#[cfg(test)]
197	fn with_api(mut self, api: impl Into<String>) -> Self {
198		self.api = api.into();
199		self
200	}
201
202	/// Fetch the latest releases of the GitHub repository.
203	///
204	/// # Arguments
205	/// * `prerelease` - Whether to include prereleases.
206	pub async fn releases(&self, prerelease: bool) -> Result<Vec<Release>> {
207		let url = self.api_releases_url();
208		let response = GITHUB_API_CLIENT.get(url).await?;
209		let mut releases = response.json::<Vec<Release>>().await?;
210		releases.retain(|r| prerelease || !r.prerelease);
211		// Sort releases by `published_at` in descending order
212		releases.sort_by(|a, b| b.published_at.cmp(&a.published_at));
213		Ok(releases)
214	}
215
216	/// Retrieves the commit hash associated with a specified tag in a GitHub repository.
217	pub async fn get_commit_sha_from_release(&self, tag_name: &str) -> Result<String> {
218		let response = GITHUB_API_CLIENT.get(self.api_tag_information(tag_name)).await?;
219		let value = response.json::<serde_json::Value>().await?;
220		let commit = value
221			.get("object")
222			.and_then(|v| v.get("sha"))
223			.and_then(|v| v.as_str())
224			.map(|v| v.to_owned())
225			.ok_or(Error::Git("the github release tag sha was not found".to_string()))?;
226		Ok(commit)
227	}
228
229	/// Retrieves the license from the repository.
230	pub async fn get_repo_license(&self) -> Result<String> {
231		let url = self.api_license_url();
232		let response = GITHUB_API_CLIENT.get(url).await?;
233		let value = response.json::<serde_json::Value>().await?;
234		let license = value
235			.get("license")
236			.and_then(|v| v.get("spdx_id"))
237			.and_then(|v| v.as_str())
238			.map(|v| v.to_owned())
239			.ok_or(Error::Git("Unable to find license for GitHub repo".to_string()))?;
240		Ok(license)
241	}
242
243	fn api_releases_url(&self) -> String {
244		format!("{}/repos/{}/{}/releases", self.api, self.org, self.name)
245	}
246
247	fn api_tag_information(&self, tag_name: &str) -> String {
248		format!("{}/repos/{}/{}/git/ref/tags/{}", self.api, self.org, self.name, tag_name)
249	}
250
251	fn api_license_url(&self) -> String {
252		format!("{}/repos/{}/{}/license", self.api, self.org, self.name)
253	}
254
255	fn org(repo: &Url) -> Result<&str> {
256		let path_segments = repo
257			.path_segments()
258			.map(|c| c.collect::<Vec<_>>())
259			.expect("repository must have path segments");
260		Ok(path_segments.first().ok_or(Error::Git(
261			"the organization (or user) is missing from the github url".to_string(),
262		))?)
263	}
264
265	/// Determines the name of a repository from a URL.
266	///
267	/// # Arguments
268	/// * `repo` - the URL of the repository.
269	pub fn name(repo: &Url) -> Result<&str> {
270		let path_segments = repo
271			.path_segments()
272			.map(|c| c.collect::<Vec<_>>())
273			.expect("repository must have path segments");
274		Ok(path_segments
275			.get(1)
276			.ok_or(Error::Git("the repository name is missing from the github url".to_string()))?)
277	}
278
279	#[cfg(test)]
280	pub(crate) fn release(repo: &Url, tag: &str, artifact: &str) -> String {
281		format!("{}/releases/download/{tag}/{artifact}", repo.as_str())
282	}
283
284	pub(crate) fn convert_to_ssh_url(url: &Url) -> String {
285		format!("git@{}:{}.git", url.host_str().unwrap_or(Self::GITHUB), &url.path()[1..])
286	}
287}
288
289/// Represents the data of a GitHub release.
290#[derive(Debug, PartialEq, serde::Deserialize)]
291pub struct Release {
292	/// The name of the tag.
293	pub tag_name: String,
294	/// The name of the release.
295	pub name: String,
296	/// Whether to identify the release as a prerelease or a full release.
297	pub prerelease: bool,
298	/// The commit hash for the release.
299	pub commit: Option<String>,
300	/// When the release was published.
301	pub published_at: String,
302}
303
304/// A descriptor of a remote repository.
305#[derive(Debug, PartialEq)]
306pub struct Repository {
307	/// The url of the repository.
308	pub url: Url,
309	/// If applicable, the branch or tag to be used.
310	pub reference: Option<String>,
311	/// The name of a package within the repository. Defaults to the repository name.
312	pub package: String,
313}
314
315impl Repository {
316	/// Parses a url in the form of <https://github.com/org/repository?package#tag> into its component parts.
317	///
318	/// # Arguments
319	/// * `url` - The url to be parsed.
320	pub fn parse(url: &str) -> Result<Self, Error> {
321		let url = Url::parse(url)?;
322		let package = url.query();
323		let reference = url.fragment().map(|f| f.to_string());
324
325		let mut url = url.clone();
326		url.set_query(None);
327		url.set_fragment(None);
328
329		let package = match package {
330			Some(b) => b,
331			None => GitHub::name(&url)?,
332		}
333		.to_string();
334
335		Ok(Self { url, reference, package })
336	}
337}
338
339#[cfg(test)]
340mod tests {
341	use super::*;
342	use mockito::{Mock, Server};
343
344	const BASE_PARACHAIN: &str = "https://github.com/r0gue-io/base-parachain";
345	const POLKADOT_SDK: &str = "https://github.com/paritytech/polkadot-sdk";
346
347	async fn releases_mock(mock_server: &mut Server, repo: &GitHub, payload: &str) -> Mock {
348		mock_server
349			.mock("GET", format!("/repos/{}/{}/releases", repo.org, repo.name).as_str())
350			.with_status(200)
351			.with_header("content-type", "application/json")
352			.with_body(payload)
353			.create_async()
354			.await
355	}
356
357	async fn tag_mock(mock_server: &mut Server, repo: &GitHub, tag: &str, payload: &str) -> Mock {
358		mock_server
359			.mock("GET", format!("/repos/{}/{}/git/ref/tags/{tag}", repo.org, repo.name).as_str())
360			.with_status(200)
361			.with_header("content-type", "application/json")
362			.with_body(payload)
363			.create_async()
364			.await
365	}
366
367	async fn license_mock(mock_server: &mut Server, repo: &GitHub, payload: &str) -> Mock {
368		mock_server
369			.mock("GET", format!("/repos/{}/{}/license", repo.org, repo.name).as_str())
370			.with_status(200)
371			.with_header("content-type", "application/json")
372			.with_body(payload)
373			.create_async()
374			.await
375	}
376
377	#[tokio::test]
378	async fn test_get_latest_releases() -> Result<(), Box<dyn std::error::Error>> {
379		let mut mock_server = Server::new_async().await;
380
381		let expected_payload = r#"[{
382			"tag_name": "polkadot-v1.10.0",
383			"name": "Polkadot v1.10.0",
384			"prerelease": false,
385			"published_at": "2024-01-01T00:00:00Z"
386		  },
387		  {
388			"tag_name": "polkadot-v1.11.0",
389			"name": "Polkadot v1.11.0",
390			"prerelease": false,
391			"published_at": "2023-01-01T00:00:00Z"
392		  },
393		  {
394			"tag_name": "polkadot-v1.12.0",
395			"name": "Polkadot v1.12.0",
396			"prerelease": false,
397			"published_at": "2025-01-01T00:00:00Z"
398		  }
399		]"#;
400		let repo = GitHub::parse(BASE_PARACHAIN)?.with_api(&mock_server.url());
401		let mock = releases_mock(&mut mock_server, &repo, expected_payload).await;
402		let latest_release = repo.releases(false).await?;
403		assert_eq!(
404			latest_release,
405			vec![
406				Release {
407					tag_name: "polkadot-v1.12.0".to_string(),
408					name: "Polkadot v1.12.0".into(),
409					prerelease: false,
410					commit: None,
411					published_at: "2025-01-01T00:00:00Z".to_string()
412				},
413				Release {
414					tag_name: "polkadot-v1.10.0".to_string(),
415					name: "Polkadot v1.10.0".into(),
416					prerelease: false,
417					commit: None,
418					published_at: "2024-01-01T00:00:00Z".to_string()
419				},
420				Release {
421					tag_name: "polkadot-v1.11.0".to_string(),
422					name: "Polkadot v1.11.0".into(),
423					prerelease: false,
424					commit: None,
425					published_at: "2023-01-01T00:00:00Z".to_string()
426				}
427			]
428		);
429		mock.assert_async().await;
430		Ok(())
431	}
432
433	#[tokio::test]
434	async fn get_releases_with_commit_sha() -> Result<(), Box<dyn std::error::Error>> {
435		let mut mock_server = Server::new_async().await;
436
437		let expected_payload = r#"{
438			"ref": "refs/tags/polkadot-v1.11.0",
439			"node_id": "REF_kwDOKDT1SrpyZWZzL3RhZ3MvcG9sa2Fkb3QtdjEuMTEuMA",
440			"url": "https://api.github.com/repos/paritytech/polkadot-sdk/git/refs/tags/polkadot-v1.11.0",
441			"object": {
442				"sha": "0bb6249268c0b77d2834640b84cb52fdd3d7e860",
443				"type": "commit",
444				"url": "https://api.github.com/repos/paritytech/polkadot-sdk/git/commits/0bb6249268c0b77d2834640b84cb52fdd3d7e860"
445			}
446		  }"#;
447		let repo = GitHub::parse(BASE_PARACHAIN)?.with_api(&mock_server.url());
448		let mock = tag_mock(&mut mock_server, &repo, "polkadot-v1.11.0", expected_payload).await;
449		let hash = repo.get_commit_sha_from_release("polkadot-v1.11.0").await?;
450		assert_eq!(hash, "0bb6249268c0b77d2834640b84cb52fdd3d7e860");
451		mock.assert_async().await;
452		Ok(())
453	}
454
455	#[tokio::test]
456	async fn get_repo_license() -> Result<(), Box<dyn std::error::Error>> {
457		let mut mock_server = Server::new_async().await;
458
459		let expected_payload = r#"{
460			"license": {
461			"key":"unlicense",
462			"name":"The Unlicense",
463			"spdx_id":"Unlicense",
464			"url":"https://api.github.com/licenses/unlicense",
465			"node_id":"MDc6TGljZW5zZTE1"
466			}
467		}"#;
468		let repo = GitHub::parse(BASE_PARACHAIN)?.with_api(&mock_server.url());
469		let mock = license_mock(&mut mock_server, &repo, expected_payload).await;
470		let license = repo.get_repo_license().await?;
471		assert_eq!(license, "Unlicense".to_string());
472		mock.assert_async().await;
473		Ok(())
474	}
475
476	#[test]
477	fn test_get_releases_api_url() -> Result<(), Box<dyn std::error::Error>> {
478		assert_eq!(
479			GitHub::parse(POLKADOT_SDK)?.api_releases_url(),
480			"https://api.github.com/repos/paritytech/polkadot-sdk/releases"
481		);
482		Ok(())
483	}
484
485	#[test]
486	fn test_url_api_tag_information() -> Result<(), Box<dyn std::error::Error>> {
487		assert_eq!(
488			GitHub::parse(POLKADOT_SDK)?.api_tag_information("polkadot-v1.11.0"),
489			"https://api.github.com/repos/paritytech/polkadot-sdk/git/ref/tags/polkadot-v1.11.0"
490		);
491		Ok(())
492	}
493
494	#[test]
495	fn test_api_license_url() -> Result<(), Box<dyn std::error::Error>> {
496		assert_eq!(
497			GitHub::parse(POLKADOT_SDK)?.api_license_url(),
498			"https://api.github.com/repos/paritytech/polkadot-sdk/license"
499		);
500		Ok(())
501	}
502
503	#[test]
504	fn test_parse_org() -> Result<(), Box<dyn std::error::Error>> {
505		assert_eq!(GitHub::parse(BASE_PARACHAIN)?.org, "r0gue-io");
506		Ok(())
507	}
508
509	#[test]
510	fn test_parse_name() -> Result<(), Box<dyn std::error::Error>> {
511		let url = Url::parse(BASE_PARACHAIN)?;
512		let name = GitHub::name(&url)?;
513		assert_eq!(name, "base-parachain");
514		Ok(())
515	}
516
517	#[test]
518	fn test_release_url() -> Result<(), Box<dyn std::error::Error>> {
519		let repo = Url::parse(POLKADOT_SDK)?;
520		let url = GitHub::release(&repo, "polkadot-v1.9.0", "polkadot");
521		assert_eq!(url, format!("{}/releases/download/polkadot-v1.9.0/polkadot", POLKADOT_SDK));
522		Ok(())
523	}
524
525	#[test]
526	fn test_convert_to_ssh_url() {
527		assert_eq!(
528			GitHub::convert_to_ssh_url(&Url::parse(BASE_PARACHAIN).expect("valid repository url")),
529			"git@github.com:r0gue-io/base-parachain.git"
530		);
531		assert_eq!(
532			GitHub::convert_to_ssh_url(
533				&Url::parse("https://github.com/paritytech/substrate-contracts-node")
534					.expect("valid repository url")
535			),
536			"git@github.com:paritytech/substrate-contracts-node.git"
537		);
538		assert_eq!(
539			GitHub::convert_to_ssh_url(
540				&Url::parse("https://github.com/paritytech/frontier-parachain-template")
541					.expect("valid repository url")
542			),
543			"git@github.com:paritytech/frontier-parachain-template.git"
544		);
545	}
546
547	mod repository {
548		use super::Error;
549		use crate::git::Repository;
550		use url::Url;
551
552		#[test]
553		fn parsing_full_url_works() {
554			assert_eq!(
555				Repository::parse("https://github.com/org/repository?package#tag").unwrap(),
556				Repository {
557					url: Url::parse("https://github.com/org/repository").unwrap(),
558					reference: Some("tag".into()),
559					package: "package".into(),
560				}
561			);
562		}
563
564		#[test]
565		fn parsing_simple_url_works() {
566			let url = "https://github.com/org/repository";
567			assert_eq!(
568				Repository::parse(url).unwrap(),
569				Repository {
570					url: Url::parse(url).unwrap(),
571					reference: None,
572					package: "repository".into(),
573				}
574			);
575		}
576
577		#[test]
578		fn parsing_invalid_url_returns_error() {
579			assert!(matches!(
580				Repository::parse("github.com/org/repository"),
581				Err(Error::ParseError(..))
582			));
583		}
584	}
585}