lib.rs 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287
  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. Ok(())
  95. }
  96. /// Remove an installed version of anchor-cli
  97. pub fn uninstall_version(version: &Version) -> Result<()> {
  98. let version_path = AVM_HOME.join("bin").join(format!("anchor-{}", version));
  99. if !version_path.exists() {
  100. return Err(anyhow!("anchor-cli {} is not installed", version));
  101. }
  102. if version == &current_version().unwrap() {
  103. return Err(anyhow!("anchor-cli {} is currently in use", version));
  104. }
  105. fs::remove_file(version_path.as_path())?;
  106. Ok(())
  107. }
  108. /// Ensure the users home directory is setup with the paths required by AVM.
  109. pub fn ensure_paths() {
  110. let home_dir = AVM_HOME.to_path_buf();
  111. if !home_dir.as_path().exists() {
  112. fs::create_dir_all(home_dir.clone()).expect("Could not create .avm directory");
  113. }
  114. let bin_dir = home_dir.join("bin");
  115. if !bin_dir.as_path().exists() {
  116. fs::create_dir_all(bin_dir).expect("Could not create .avm/bin directory");
  117. }
  118. if !current_version_file_path().exists() {
  119. fs::File::create(current_version_file_path()).expect("Could not create .version file");
  120. }
  121. }
  122. /// Retrieve a list of installable versions of anchor-cli using the GitHub API and tags on the Anchor
  123. /// repository.
  124. pub fn fetch_versions() -> Vec<semver::Version> {
  125. #[derive(Deserialize)]
  126. struct Release {
  127. #[serde(rename = "name", deserialize_with = "version_deserializer")]
  128. version: semver::Version,
  129. }
  130. fn version_deserializer<'de, D>(deserializer: D) -> Result<semver::Version, D::Error>
  131. where
  132. D: de::Deserializer<'de>,
  133. {
  134. let s: &str = de::Deserialize::deserialize(deserializer)?;
  135. Version::parse(s.trim_start_matches('v')).map_err(de::Error::custom)
  136. }
  137. let client = reqwest::blocking::Client::new();
  138. let versions: Vec<Release> = client
  139. .get("https://api.github.com/repos/project-serum/anchor/tags")
  140. .header(USER_AGENT, "avm https://github.com/project-serum/anchor")
  141. .send()
  142. .unwrap()
  143. .json()
  144. .unwrap();
  145. versions.into_iter().map(|r| r.version).collect()
  146. }
  147. /// Print available versions and flags indicating installed, current and latest
  148. pub fn list_versions() -> Result<()> {
  149. let installed_versions = read_installed_versions();
  150. let mut available_versions = fetch_versions();
  151. // Reverse version list so latest versions are printed last
  152. available_versions.reverse();
  153. available_versions.iter().enumerate().for_each(|(i, v)| {
  154. print!("{}", v);
  155. let mut flags = vec![];
  156. if i == available_versions.len() - 1 {
  157. flags.push("latest");
  158. }
  159. if installed_versions.contains(v) {
  160. flags.push("installed");
  161. }
  162. if current_version().unwrap() == v.clone() {
  163. flags.push("current");
  164. }
  165. if flags.is_empty() {
  166. println!();
  167. } else {
  168. println!("\t({})", flags.join(", "));
  169. }
  170. });
  171. Ok(())
  172. }
  173. pub fn get_latest_version() -> semver::Version {
  174. let available_versions = fetch_versions();
  175. available_versions.first().unwrap().clone()
  176. }
  177. /// Read the installed anchor-cli versions by reading the binaries in the AVM_HOME/bin directory.
  178. pub fn read_installed_versions() -> Vec<semver::Version> {
  179. let home_dir = AVM_HOME.to_path_buf();
  180. let mut versions = vec![];
  181. for file in fs::read_dir(&home_dir.join("bin")).unwrap() {
  182. let file_name = file.unwrap().file_name();
  183. // Match only things that look like anchor-*
  184. if file_name.to_str().unwrap().starts_with("anchor-") {
  185. let version = file_name
  186. .to_str()
  187. .unwrap()
  188. .trim_start_matches("anchor-")
  189. .parse::<semver::Version>()
  190. .unwrap();
  191. versions.push(version);
  192. }
  193. }
  194. versions
  195. }
  196. #[cfg(test)]
  197. mod tests {
  198. use crate::*;
  199. use semver::Version;
  200. use std::fs;
  201. use std::io::Write;
  202. #[test]
  203. fn test_ensure_paths() {
  204. ensure_paths();
  205. assert!(AVM_HOME.exists());
  206. let bin_dir = AVM_HOME.join("bin");
  207. assert!(bin_dir.exists());
  208. let current_version_file = AVM_HOME.join(".version");
  209. assert!(current_version_file.exists());
  210. }
  211. #[test]
  212. fn test_current_version_file_path() {
  213. ensure_paths();
  214. assert!(current_version_file_path().exists());
  215. }
  216. #[test]
  217. fn test_version_binary_path() {
  218. assert!(
  219. version_binary_path(&Version::parse("0.18.2").unwrap())
  220. == AVM_HOME.join("bin/anchor-0.18.2")
  221. );
  222. }
  223. #[test]
  224. fn test_current_version() {
  225. ensure_paths();
  226. let mut current_version_file =
  227. fs::File::create(current_version_file_path().as_path()).unwrap();
  228. current_version_file.write_all("0.18.2".as_bytes()).unwrap();
  229. assert!(current_version().unwrap() == Version::parse("0.18.2").unwrap());
  230. }
  231. #[test]
  232. #[should_panic(expected = "anchor-cli 0.18.1 is not installed")]
  233. fn test_uninstall_non_installed_version() {
  234. uninstall_version(&Version::parse("0.18.1").unwrap()).unwrap();
  235. }
  236. #[test]
  237. #[should_panic(expected = "anchor-cli 0.18.2 is currently in use")]
  238. fn test_uninstalled_in_use_version() {
  239. ensure_paths();
  240. let version = Version::parse("0.18.2").unwrap();
  241. let mut current_version_file =
  242. fs::File::create(current_version_file_path().as_path()).unwrap();
  243. current_version_file.write_all("0.18.2".as_bytes()).unwrap();
  244. // Create a fake binary for anchor-0.18.2 in the bin directory
  245. fs::File::create(version_binary_path(&version)).unwrap();
  246. uninstall_version(&version).unwrap();
  247. }
  248. #[test]
  249. fn test_read_installed_versions() {
  250. ensure_paths();
  251. let version = Version::parse("0.18.2").unwrap();
  252. // Create a fake binary for anchor-0.18.2 in the bin directory
  253. fs::File::create(version_binary_path(&version)).unwrap();
  254. let expected = vec![version];
  255. assert!(read_installed_versions() == expected);
  256. // Should ignore this file because its not anchor- prefixed
  257. fs::File::create(AVM_HOME.join("bin").join("garbage").as_path()).unwrap();
  258. assert!(read_installed_versions() == expected);
  259. }
  260. }