lib.rs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. use anyhow::{anyhow, Error, Result};
  2. use cargo_toml::Manifest;
  3. use chrono::{TimeZone, Utc};
  4. use once_cell::sync::Lazy;
  5. use reqwest::header::USER_AGENT;
  6. use reqwest::StatusCode;
  7. use semver::{Prerelease, Version};
  8. use serde::{de, Deserialize};
  9. use std::fs;
  10. use std::io::{BufRead, Write};
  11. use std::path::PathBuf;
  12. use std::process::{Command, Stdio};
  13. /// Storage directory for AVM, customizable by setting the $AVM_HOME, defaults to ~/.avm
  14. pub static AVM_HOME: Lazy<PathBuf> = Lazy::new(|| {
  15. cfg_if::cfg_if! {
  16. if #[cfg(test)] {
  17. let dir = tempfile::tempdir().expect("Could not create temporary directory");
  18. dir.path().join(".avm")
  19. } else {
  20. if let Ok(avm_home) = std::env::var("AVM_HOME") {
  21. PathBuf::from(avm_home)
  22. } else {
  23. let mut user_home = dirs::home_dir().expect("Could not find home directory");
  24. user_home.push(".avm");
  25. user_home
  26. }
  27. }
  28. }
  29. });
  30. /// Path to the current version file $AVM_HOME/.version
  31. fn current_version_file_path() -> PathBuf {
  32. AVM_HOME.join(".version")
  33. }
  34. /// Path to the current version file $AVM_HOME/bin
  35. fn get_bin_dir_path() -> PathBuf {
  36. AVM_HOME.join("bin")
  37. }
  38. /// Path to the binary for the given version
  39. pub fn version_binary_path(version: &Version) -> PathBuf {
  40. get_bin_dir_path().join(format!("anchor-{version}"))
  41. }
  42. /// Ensure the users home directory is setup with the paths required by AVM.
  43. pub fn ensure_paths() {
  44. let home_dir = AVM_HOME.to_path_buf();
  45. if !home_dir.exists() {
  46. fs::create_dir_all(&home_dir).expect("Could not create .avm directory");
  47. }
  48. let bin_dir = get_bin_dir_path();
  49. if !bin_dir.exists() {
  50. fs::create_dir_all(bin_dir).expect("Could not create .avm/bin directory");
  51. }
  52. if !current_version_file_path().exists() {
  53. fs::File::create(current_version_file_path()).expect("Could not create .version file");
  54. }
  55. }
  56. /// Read the current version from the version file
  57. pub fn current_version() -> Result<Version> {
  58. fs::read_to_string(current_version_file_path())
  59. .map_err(|e| anyhow!("Could not read version file: {}", e))?
  60. .trim_end_matches('\n')
  61. .parse::<Version>()
  62. .map_err(|e| anyhow!("Could not parse version file: {}", e))
  63. }
  64. /// Update the current version to a new version
  65. pub fn use_version(opt_version: Option<Version>) -> Result<()> {
  66. let version = match opt_version {
  67. Some(version) => version,
  68. None => read_anchorversion_file()?,
  69. };
  70. // Make sure the requested version is installed
  71. let installed_versions = read_installed_versions()?;
  72. if !installed_versions.contains(&version) {
  73. println!("Version {version} is not installed. Would you like to install? [y/n]");
  74. let input = std::io::stdin()
  75. .lock()
  76. .lines()
  77. .next()
  78. .expect("Expected input")?;
  79. match input.as_str() {
  80. "y" | "yes" => return install_version(InstallTarget::Version(version), false),
  81. _ => return Err(anyhow!("Installation rejected.")),
  82. };
  83. }
  84. let mut current_version_file = fs::File::create(current_version_file_path())?;
  85. current_version_file.write_all(version.to_string().as_bytes())?;
  86. println!("Now using anchor version {}.", current_version()?);
  87. Ok(())
  88. }
  89. #[derive(Clone)]
  90. pub enum InstallTarget {
  91. Version(Version),
  92. Commit(String),
  93. }
  94. /// Update to the latest version
  95. pub fn update() -> Result<()> {
  96. let latest_version = get_latest_version()?;
  97. install_version(InstallTarget::Version(latest_version), false)
  98. }
  99. /// The commit sha provided can be shortened,
  100. ///
  101. /// returns the full commit sha3 for unique versioning downstream
  102. pub fn check_and_get_full_commit(commit: &str) -> Result<String> {
  103. let client = reqwest::blocking::Client::new();
  104. let response = client
  105. .get(format!(
  106. "https://api.github.com/repos/coral-xyz/anchor/commits/{commit}"
  107. ))
  108. .header(USER_AGENT, "avm https://github.com/coral-xyz/anchor")
  109. .send()?;
  110. if response.status() != StatusCode::OK {
  111. return Err(anyhow!(
  112. "Error checking commit {commit}: {}",
  113. response.text()?
  114. ));
  115. };
  116. #[derive(Deserialize)]
  117. struct GetCommitResponse {
  118. sha: String,
  119. }
  120. response
  121. .json::<GetCommitResponse>()
  122. .map(|resp| resp.sha)
  123. .map_err(|err| anyhow!("Failed to parse the response to JSON: {err:?}"))
  124. }
  125. fn get_anchor_version_from_commit(commit: &str) -> Result<Version> {
  126. // We read the version from cli/Cargo.toml since there is no simpler way to do so
  127. let client = reqwest::blocking::Client::new();
  128. let response = client
  129. .get(format!(
  130. "https://raw.githubusercontent.com/coral-xyz/anchor/{commit}/cli/Cargo.toml"
  131. ))
  132. .header(USER_AGENT, "avm https://github.com/coral-xyz/anchor")
  133. .send()?;
  134. if response.status() != StatusCode::OK {
  135. return Err(anyhow!(
  136. "Could not find anchor-cli version for commit: {response:?}"
  137. ));
  138. };
  139. let anchor_cli_cargo_toml = response.text()?;
  140. let anchor_cli_manifest = Manifest::from_str(&anchor_cli_cargo_toml)?;
  141. let mut version = anchor_cli_manifest.package().version().parse::<Version>()?;
  142. version.pre = Prerelease::new(commit)?;
  143. Ok(version)
  144. }
  145. /// Install a version of anchor-cli
  146. pub fn install_version(install_target: InstallTarget, force: bool) -> Result<()> {
  147. let mut args: Vec<String> = vec![
  148. "install".into(),
  149. "--git".into(),
  150. "https://github.com/coral-xyz/anchor".into(),
  151. "anchor-cli".into(),
  152. "--locked".into(),
  153. "--root".into(),
  154. AVM_HOME.to_str().unwrap().into(),
  155. ];
  156. let version = match install_target {
  157. InstallTarget::Version(version) => {
  158. args.extend(["--tag".into(), format!("v{}", version), "anchor-cli".into()]);
  159. version
  160. }
  161. InstallTarget::Commit(commit) => {
  162. args.extend(["--rev".into(), commit.clone()]);
  163. get_anchor_version_from_commit(&commit)?
  164. }
  165. };
  166. // If version is already installed we ignore the request.
  167. let installed_versions = read_installed_versions()?;
  168. if installed_versions.contains(&version) && !force {
  169. println!("Version {version} is already installed");
  170. return Ok(());
  171. }
  172. // If the version is older than v0.31, install using `rustc 1.79.0` to get around the problem
  173. // explained in https://github.com/coral-xyz/anchor/pull/3143
  174. if version < Version::parse("0.31.0")? {
  175. const REQUIRED_VERSION: &str = "1.79.0";
  176. let is_installed = Command::new("rustup")
  177. .args(["toolchain", "list"])
  178. .output()
  179. .map(|output| String::from_utf8(output.stdout))??
  180. .lines()
  181. .any(|line| line.starts_with(REQUIRED_VERSION));
  182. if !is_installed {
  183. let exit_status = Command::new("rustup")
  184. .args(["toolchain", "install", REQUIRED_VERSION])
  185. .spawn()?
  186. .wait()?;
  187. if !exit_status.success() {
  188. return Err(anyhow!(
  189. "Installation of `rustc {REQUIRED_VERSION}` failed. \
  190. `rustc <1.80` is required to install Anchor v{version} from source. \
  191. See https://github.com/coral-xyz/anchor/pull/3143 for more information."
  192. ));
  193. }
  194. }
  195. // Prepend the toolchain to use with the `cargo install` command
  196. args.insert(0, format!("+{REQUIRED_VERSION}"));
  197. }
  198. let output = Command::new("cargo")
  199. .args(args)
  200. .stdout(Stdio::inherit())
  201. .stderr(Stdio::inherit())
  202. .output()
  203. .map_err(|e| anyhow!("Cargo install for {version} failed: {e}"))?;
  204. if !output.status.success() {
  205. return Err(anyhow!(
  206. "Failed to install {version}, is it a valid version?"
  207. ));
  208. }
  209. let bin_dir = get_bin_dir_path();
  210. let bin_name = if cfg!(target_os = "windows") {
  211. "anchor.exe"
  212. } else {
  213. "anchor"
  214. };
  215. fs::rename(
  216. bin_dir.join(bin_name),
  217. bin_dir.join(format!("anchor-{version}")),
  218. )?;
  219. // If .version file is empty or not parseable, write the newly installed version to it
  220. if current_version().is_err() {
  221. let mut current_version_file = fs::File::create(current_version_file_path())?;
  222. current_version_file.write_all(version.to_string().as_bytes())?;
  223. }
  224. use_version(Some(version))
  225. }
  226. /// Remove an installed version of anchor-cli
  227. pub fn uninstall_version(version: &Version) -> Result<()> {
  228. let version_path = get_bin_dir_path().join(format!("anchor-{version}"));
  229. if !version_path.exists() {
  230. return Err(anyhow!("anchor-cli {} is not installed", version));
  231. }
  232. if version == &current_version()? {
  233. return Err(anyhow!("anchor-cli {} is currently in use", version));
  234. }
  235. fs::remove_file(version_path)?;
  236. Ok(())
  237. }
  238. /// Read version from .anchorversion
  239. pub fn read_anchorversion_file() -> Result<Version> {
  240. fs::read_to_string(".anchorversion")
  241. .map_err(|e| anyhow!(".anchorversion file not found: {e}"))
  242. .map(|content| Version::parse(content.trim()))?
  243. .map_err(|e| anyhow!("Unable to parse version: {e}"))
  244. }
  245. /// Retrieve a list of installable versions of anchor-cli using the GitHub API and tags on the Anchor
  246. /// repository.
  247. pub fn fetch_versions() -> Result<Vec<Version>, Error> {
  248. #[derive(Deserialize)]
  249. struct Release {
  250. #[serde(rename = "name", deserialize_with = "version_deserializer")]
  251. version: Version,
  252. }
  253. fn version_deserializer<'de, D>(deserializer: D) -> Result<Version, D::Error>
  254. where
  255. D: de::Deserializer<'de>,
  256. {
  257. let s: &str = de::Deserialize::deserialize(deserializer)?;
  258. Version::parse(s.trim_start_matches('v')).map_err(de::Error::custom)
  259. }
  260. let response = reqwest::blocking::Client::new()
  261. .get("https://api.github.com/repos/coral-xyz/anchor/tags")
  262. .header(USER_AGENT, "avm https://github.com/coral-xyz/anchor")
  263. .send()?;
  264. if response.status().is_success() {
  265. let releases: Vec<Release> = response.json()?;
  266. let versions = releases.into_iter().map(|r| r.version).collect();
  267. Ok(versions)
  268. } else {
  269. let reset_time_header = response
  270. .headers()
  271. .get("X-RateLimit-Reset")
  272. .map_or("unknown", |v| v.to_str().unwrap());
  273. let t = Utc.timestamp_opt(reset_time_header.parse::<i64>().unwrap(), 0);
  274. let reset_time = t
  275. .single()
  276. .map(|t| t.format("%Y-%m-%d %H:%M:%S").to_string())
  277. .unwrap_or_else(|| "unknown".to_string());
  278. Err(anyhow!(
  279. "GitHub API rate limit exceeded. Try again after {} UTC.",
  280. reset_time
  281. ))
  282. }
  283. }
  284. /// Print available versions and flags indicating installed, current and latest
  285. pub fn list_versions() -> Result<()> {
  286. let mut installed_versions = read_installed_versions()?;
  287. let mut available_versions = fetch_versions()?;
  288. // Reverse version list so latest versions are printed last
  289. available_versions.reverse();
  290. let print_versions =
  291. |versions: Vec<Version>, installed_versions: &mut Vec<Version>, show_latest: bool| {
  292. versions.iter().enumerate().for_each(|(i, v)| {
  293. print!("{v}");
  294. let mut flags = vec![];
  295. if i == versions.len() - 1 && show_latest {
  296. flags.push("latest");
  297. }
  298. if let Some(position) = installed_versions.iter().position(|iv| iv == v) {
  299. flags.push("installed");
  300. installed_versions.remove(position);
  301. }
  302. if current_version().map(|cv| &cv == v).unwrap_or_default() {
  303. flags.push("current");
  304. }
  305. if flags.is_empty() {
  306. println!();
  307. } else {
  308. println!("\t({})", flags.join(", "));
  309. }
  310. })
  311. };
  312. print_versions(available_versions, &mut installed_versions, true);
  313. print_versions(installed_versions.clone(), &mut installed_versions, false);
  314. Ok(())
  315. }
  316. pub fn get_latest_version() -> Result<Version> {
  317. fetch_versions()?
  318. .into_iter()
  319. .next()
  320. .ok_or_else(|| anyhow!("First version not found"))
  321. }
  322. /// Read the installed anchor-cli versions by reading the binaries in the AVM_HOME/bin directory.
  323. pub fn read_installed_versions() -> Result<Vec<Version>> {
  324. const PREFIX: &str = "anchor-";
  325. let versions = fs::read_dir(get_bin_dir_path())?
  326. .filter_map(|entry_result| entry_result.ok())
  327. .filter_map(|entry| entry.file_name().to_str().map(|f| f.to_owned()))
  328. .filter(|file_name| file_name.starts_with(PREFIX))
  329. .filter_map(|file_name| file_name.trim_start_matches(PREFIX).parse::<Version>().ok())
  330. .collect();
  331. Ok(versions)
  332. }
  333. #[cfg(test)]
  334. mod tests {
  335. use crate::*;
  336. use semver::Version;
  337. use std::fs;
  338. use std::io::Write;
  339. use std::path::Path;
  340. #[test]
  341. fn test_ensure_paths() {
  342. ensure_paths();
  343. assert!(AVM_HOME.exists());
  344. let bin_dir = get_bin_dir_path();
  345. assert!(bin_dir.exists());
  346. let current_version_file = current_version_file_path();
  347. assert!(current_version_file.exists());
  348. }
  349. #[test]
  350. fn test_version_binary_path() {
  351. assert_eq!(
  352. version_binary_path(&Version::parse("0.18.2").unwrap()),
  353. get_bin_dir_path().join("anchor-0.18.2")
  354. );
  355. }
  356. #[test]
  357. fn test_read_anchorversion() -> Result<()> {
  358. ensure_paths();
  359. let anchorversion_path = Path::new(".anchorversion");
  360. let test_version = "0.26.0";
  361. fs::write(anchorversion_path, test_version)?;
  362. let version = read_anchorversion_file()?;
  363. assert_eq!(version.to_string(), test_version);
  364. fs::remove_file(anchorversion_path)?;
  365. Ok(())
  366. }
  367. #[test]
  368. fn test_current_version() {
  369. ensure_paths();
  370. let mut current_version_file = fs::File::create(current_version_file_path()).unwrap();
  371. current_version_file.write_all("0.18.2".as_bytes()).unwrap();
  372. // Sync the file to disk before the read in current_version() to
  373. // mitigate the read not seeing the written version bytes.
  374. current_version_file.sync_all().unwrap();
  375. assert_eq!(
  376. current_version().unwrap(),
  377. Version::parse("0.18.2").unwrap()
  378. );
  379. }
  380. #[test]
  381. #[should_panic(expected = "anchor-cli 0.18.1 is not installed")]
  382. fn test_uninstall_non_installed_version() {
  383. uninstall_version(&Version::parse("0.18.1").unwrap()).unwrap();
  384. }
  385. #[test]
  386. #[should_panic(expected = "anchor-cli 0.18.2 is currently in use")]
  387. fn test_uninstalled_in_use_version() {
  388. ensure_paths();
  389. let version = Version::parse("0.18.2").unwrap();
  390. let mut current_version_file = fs::File::create(current_version_file_path()).unwrap();
  391. current_version_file.write_all("0.18.2".as_bytes()).unwrap();
  392. // Sync the file to disk before the read in current_version() to
  393. // mitigate the read not seeing the written version bytes.
  394. current_version_file.sync_all().unwrap();
  395. // Create a fake binary for anchor-0.18.2 in the bin directory
  396. fs::File::create(version_binary_path(&version)).unwrap();
  397. uninstall_version(&version).unwrap();
  398. }
  399. #[test]
  400. fn test_read_installed_versions() {
  401. ensure_paths();
  402. let version = Version::parse("0.18.2").unwrap();
  403. // Create a fake binary for anchor-0.18.2 in the bin directory
  404. fs::File::create(version_binary_path(&version)).unwrap();
  405. let expected = vec![version];
  406. assert_eq!(read_installed_versions().unwrap(), expected);
  407. // Should ignore this file because its not anchor- prefixed
  408. fs::File::create(AVM_HOME.join("bin").join("garbage").as_path()).unwrap();
  409. assert_eq!(read_installed_versions().unwrap(), expected);
  410. }
  411. #[test]
  412. fn test_get_anchor_version_from_commit() {
  413. let version =
  414. get_anchor_version_from_commit("e1afcbf71e0f2e10fae14525934a6a68479167b9").unwrap();
  415. assert_eq!(
  416. version.to_string(),
  417. "0.28.0-e1afcbf71e0f2e10fae14525934a6a68479167b9"
  418. )
  419. }
  420. #[test]
  421. fn test_check_and_get_full_commit_when_full_commit() {
  422. assert_eq!(
  423. check_and_get_full_commit("e1afcbf71e0f2e10fae14525934a6a68479167b9").unwrap(),
  424. "e1afcbf71e0f2e10fae14525934a6a68479167b9"
  425. )
  426. }
  427. #[test]
  428. fn test_check_and_get_full_commit_when_partial_commit() {
  429. assert_eq!(
  430. check_and_get_full_commit("e1afcbf").unwrap(),
  431. "e1afcbf71e0f2e10fae14525934a6a68479167b9"
  432. )
  433. }
  434. }