lib.rs 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. use anyhow::{anyhow, Result};
  2. use dialoguer::Input;
  3. use once_cell::sync::Lazy;
  4. use reqwest::header::USER_AGENT;
  5. use semver::Version;
  6. use serde::{de, Deserialize};
  7. use std::fs;
  8. use std::io::Write;
  9. use std::path::PathBuf;
  10. use std::process::Stdio;
  11. /// Storage directory for AVM, ~/.avm
  12. pub static AVM_HOME: Lazy<PathBuf> = Lazy::new(|| {
  13. cfg_if::cfg_if! {
  14. if #[cfg(test)] {
  15. let dir = tempfile::tempdir().expect("Could not create temporary directory");
  16. dir.path().join(".avm")
  17. } else {
  18. let mut user_home = dirs::home_dir().expect("Could not find home directory");
  19. user_home.push(".avm");
  20. user_home
  21. }
  22. }
  23. });
  24. /// Path to the current version file ~/.avm/.version
  25. pub fn current_version_file_path() -> PathBuf {
  26. let mut current_version_file_path = AVM_HOME.to_path_buf();
  27. current_version_file_path.push(".version");
  28. current_version_file_path
  29. }
  30. /// Read the current version from the version file
  31. pub fn current_version() -> Result<Version> {
  32. let v = fs::read_to_string(current_version_file_path().as_path())
  33. .map_err(|e| anyhow!("Could not read version file: {}", e))?;
  34. Version::parse(v.trim_end_matches('\n').to_string().as_str())
  35. .map_err(|e| anyhow!("Could not parse version file: {}", e))
  36. }
  37. /// Path to the binary for the given version
  38. pub fn version_binary_path(version: &Version) -> PathBuf {
  39. let mut version_path = AVM_HOME.join("bin");
  40. version_path.push(format!("anchor-{}", version));
  41. version_path
  42. }
  43. /// Update the current version to a new version
  44. pub fn use_version(version: &Version) -> Result<()> {
  45. let installed_versions = read_installed_versions();
  46. // Make sure the requested version is installed
  47. if !installed_versions.contains(version) {
  48. let input: String = Input::new()
  49. .with_prompt(format!(
  50. "anchor-cli {} is not installed, would you like to install it? (y/n)",
  51. version
  52. ))
  53. .with_initial_text("y")
  54. .default("n".into())
  55. .interact_text()?;
  56. if matches!(input.as_str(), "y" | "yy" | "Y" | "yes" | "Yes") {
  57. install_version(version)?;
  58. }
  59. }
  60. let mut current_version_file = fs::File::create(current_version_file_path().as_path())?;
  61. current_version_file.write_all(version.to_string().as_bytes())?;
  62. Ok(())
  63. }
  64. /// Install a version of anchor-cli
  65. pub fn install_version(version: &Version) -> Result<()> {
  66. let exit = std::process::Command::new("cargo")
  67. .args(&[
  68. "install",
  69. "--git",
  70. "https://github.com/project-serum/anchor",
  71. "--tag",
  72. &format!("v{}", &version),
  73. "anchor-cli",
  74. "--locked",
  75. "--root",
  76. AVM_HOME.to_str().unwrap(),
  77. ])
  78. .stdout(Stdio::inherit())
  79. .stderr(Stdio::inherit())
  80. .output()
  81. .map_err(|e| {
  82. anyhow::format_err!("Cargo install for {} failed: {}", version, e.to_string())
  83. })?;
  84. if !exit.status.success() {
  85. return Err(anyhow!(
  86. "Failed to install {}, is it a valid version?",
  87. version
  88. ));
  89. }
  90. fs::rename(
  91. &AVM_HOME.join("bin").join("anchor"),
  92. &AVM_HOME.join("bin").join(format!("anchor-{}", version)),
  93. )?;
  94. // If .version file is empty or not parseable, write the newly installed version to it
  95. if current_version().is_err() {
  96. let mut current_version_file = fs::File::create(current_version_file_path().as_path())?;
  97. current_version_file.write_all(version.to_string().as_bytes())?;
  98. }
  99. Ok(())
  100. }
  101. /// Remove an installed version of anchor-cli
  102. pub fn uninstall_version(version: &Version) -> Result<()> {
  103. let version_path = AVM_HOME.join("bin").join(format!("anchor-{}", version));
  104. if !version_path.exists() {
  105. return Err(anyhow!("anchor-cli {} is not installed", version));
  106. }
  107. if version == &current_version().unwrap() {
  108. return Err(anyhow!("anchor-cli {} is currently in use", version));
  109. }
  110. fs::remove_file(version_path.as_path())?;
  111. Ok(())
  112. }
  113. /// Ensure the users home directory is setup with the paths required by AVM.
  114. pub fn ensure_paths() {
  115. let home_dir = AVM_HOME.to_path_buf();
  116. if !home_dir.as_path().exists() {
  117. fs::create_dir_all(home_dir.clone()).expect("Could not create .avm directory");
  118. }
  119. let bin_dir = home_dir.join("bin");
  120. if !bin_dir.as_path().exists() {
  121. fs::create_dir_all(bin_dir).expect("Could not create .avm/bin directory");
  122. }
  123. if !current_version_file_path().exists() {
  124. fs::File::create(current_version_file_path()).expect("Could not create .version file");
  125. }
  126. }
  127. /// Retrieve a list of installable versions of anchor-cli using the GitHub API and tags on the Anchor
  128. /// repository.
  129. pub fn fetch_versions() -> Vec<semver::Version> {
  130. #[derive(Deserialize)]
  131. struct Release {
  132. #[serde(rename = "name", deserialize_with = "version_deserializer")]
  133. version: semver::Version,
  134. }
  135. fn version_deserializer<'de, D>(deserializer: D) -> Result<semver::Version, D::Error>
  136. where
  137. D: de::Deserializer<'de>,
  138. {
  139. let s: &str = de::Deserialize::deserialize(deserializer)?;
  140. Version::parse(s.trim_start_matches('v')).map_err(de::Error::custom)
  141. }
  142. let client = reqwest::blocking::Client::new();
  143. let versions: Vec<Release> = client
  144. .get("https://api.github.com/repos/project-serum/anchor/tags")
  145. .header(USER_AGENT, "avm https://github.com/project-serum/anchor")
  146. .send()
  147. .unwrap()
  148. .json()
  149. .unwrap();
  150. versions.into_iter().map(|r| r.version).collect()
  151. }
  152. /// Print available versions and flags indicating installed, current and latest
  153. pub fn list_versions() -> Result<()> {
  154. let installed_versions = read_installed_versions();
  155. let mut available_versions = fetch_versions();
  156. // Reverse version list so latest versions are printed last
  157. available_versions.reverse();
  158. available_versions.iter().enumerate().for_each(|(i, v)| {
  159. print!("{}", v);
  160. let mut flags = vec![];
  161. if i == available_versions.len() - 1 {
  162. flags.push("latest");
  163. }
  164. if installed_versions.contains(v) {
  165. flags.push("installed");
  166. }
  167. if current_version().is_ok() && current_version().unwrap() == v.clone() {
  168. flags.push("current");
  169. }
  170. if flags.is_empty() {
  171. println!();
  172. } else {
  173. println!("\t({})", flags.join(", "));
  174. }
  175. });
  176. Ok(())
  177. }
  178. pub fn get_latest_version() -> semver::Version {
  179. let available_versions = fetch_versions();
  180. available_versions.first().unwrap().clone()
  181. }
  182. /// Read the installed anchor-cli versions by reading the binaries in the AVM_HOME/bin directory.
  183. pub fn read_installed_versions() -> Vec<semver::Version> {
  184. let home_dir = AVM_HOME.to_path_buf();
  185. let mut versions = vec![];
  186. for file in fs::read_dir(&home_dir.join("bin")).unwrap() {
  187. let file_name = file.unwrap().file_name();
  188. // Match only things that look like anchor-*
  189. if file_name.to_str().unwrap().starts_with("anchor-") {
  190. let version = file_name
  191. .to_str()
  192. .unwrap()
  193. .trim_start_matches("anchor-")
  194. .parse::<semver::Version>()
  195. .unwrap();
  196. versions.push(version);
  197. }
  198. }
  199. versions
  200. }
  201. #[cfg(test)]
  202. mod tests {
  203. use crate::*;
  204. use semver::Version;
  205. use std::fs;
  206. use std::io::Write;
  207. #[test]
  208. fn test_ensure_paths() {
  209. ensure_paths();
  210. assert!(AVM_HOME.exists());
  211. let bin_dir = AVM_HOME.join("bin");
  212. assert!(bin_dir.exists());
  213. let current_version_file = AVM_HOME.join(".version");
  214. assert!(current_version_file.exists());
  215. }
  216. #[test]
  217. fn test_current_version_file_path() {
  218. ensure_paths();
  219. assert!(current_version_file_path().exists());
  220. }
  221. #[test]
  222. fn test_version_binary_path() {
  223. assert!(
  224. version_binary_path(&Version::parse("0.18.2").unwrap())
  225. == AVM_HOME.join("bin/anchor-0.18.2")
  226. );
  227. }
  228. #[test]
  229. fn test_current_version() {
  230. ensure_paths();
  231. let mut current_version_file =
  232. fs::File::create(current_version_file_path().as_path()).unwrap();
  233. current_version_file.write_all("0.18.2".as_bytes()).unwrap();
  234. assert!(current_version().unwrap() == Version::parse("0.18.2").unwrap());
  235. }
  236. #[test]
  237. #[should_panic(expected = "anchor-cli 0.18.1 is not installed")]
  238. fn test_uninstall_non_installed_version() {
  239. uninstall_version(&Version::parse("0.18.1").unwrap()).unwrap();
  240. }
  241. #[test]
  242. #[should_panic(expected = "anchor-cli 0.18.2 is currently in use")]
  243. fn test_uninstalled_in_use_version() {
  244. ensure_paths();
  245. let version = Version::parse("0.18.2").unwrap();
  246. let mut current_version_file =
  247. fs::File::create(current_version_file_path().as_path()).unwrap();
  248. current_version_file.write_all("0.18.2".as_bytes()).unwrap();
  249. // Create a fake binary for anchor-0.18.2 in the bin directory
  250. fs::File::create(version_binary_path(&version)).unwrap();
  251. uninstall_version(&version).unwrap();
  252. }
  253. #[test]
  254. fn test_read_installed_versions() {
  255. ensure_paths();
  256. let version = Version::parse("0.18.2").unwrap();
  257. // Create a fake binary for anchor-0.18.2 in the bin directory
  258. fs::File::create(version_binary_path(&version)).unwrap();
  259. let expected = vec![version];
  260. assert!(read_installed_versions() == expected);
  261. // Should ignore this file because its not anchor- prefixed
  262. fs::File::create(AVM_HOME.join("bin").join("garbage").as_path()).unwrap();
  263. assert!(read_installed_versions() == expected);
  264. }
  265. }