checks.rs 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184
  1. use std::{fs, path::Path};
  2. use anyhow::{anyhow, Result};
  3. use semver::{Version, VersionReq};
  4. use crate::{
  5. config::{Config, Manifest, PackageManager, WithPath},
  6. VERSION,
  7. };
  8. /// Check whether `overflow-checks` codegen option is enabled.
  9. ///
  10. /// https://doc.rust-lang.org/rustc/codegen-options/index.html#overflow-checks
  11. pub fn check_overflow(cargo_toml_path: impl AsRef<Path>) -> Result<bool> {
  12. Manifest::from_path(cargo_toml_path)?
  13. .profile
  14. .release
  15. .as_ref()
  16. .and_then(|profile| profile.overflow_checks)
  17. .ok_or(anyhow!(
  18. "`overflow-checks` is not enabled. To enable, add:\n\n\
  19. [profile.release]\n\
  20. overflow-checks = true\n\n\
  21. in workspace root Cargo.toml",
  22. ))
  23. }
  24. /// Check whether there is a mismatch between the current CLI version and:
  25. ///
  26. /// - `anchor-lang` crate version
  27. /// - `@coral-xyz/anchor` package version
  28. ///
  29. /// This function logs warnings in the case of a mismatch.
  30. pub fn check_anchor_version(cfg: &WithPath<Config>) -> Result<()> {
  31. let cli_version = Version::parse(VERSION)?;
  32. // Check lang crate
  33. let mismatched_lang_version = cfg
  34. .get_rust_program_list()?
  35. .into_iter()
  36. .map(|path| path.join("Cargo.toml"))
  37. .map(cargo_toml::Manifest::from_path)
  38. .filter_map(|man| man.ok())
  39. .filter_map(|man| man.dependencies.get("anchor-lang").map(|d| d.to_owned()))
  40. .filter_map(|dep| Version::parse(dep.req()).ok())
  41. .find(|ver| ver != &cli_version); // Only log the warning once
  42. if let Some(ver) = mismatched_lang_version {
  43. eprintln!(
  44. "WARNING: `anchor-lang` version({ver}) and the current CLI version({cli_version}) \
  45. don't match.\n\n\t\
  46. This can lead to unwanted behavior. To use the same CLI version, add:\n\n\t\
  47. [toolchain]\n\t\
  48. anchor_version = \"{ver}\"\n\n\t\
  49. to Anchor.toml\n"
  50. );
  51. }
  52. // Check TS package
  53. let package_json = {
  54. let package_json_path = cfg.path().parent().unwrap().join("package.json");
  55. let package_json_content = fs::read_to_string(package_json_path)?;
  56. serde_json::from_str::<serde_json::Value>(&package_json_content)?
  57. };
  58. let mismatched_ts_version = package_json
  59. .get("dependencies")
  60. .and_then(|deps| deps.get("@coral-xyz/anchor"))
  61. .and_then(|ver| ver.as_str())
  62. .and_then(|ver| VersionReq::parse(ver).ok())
  63. .filter(|ver| !ver.matches(&cli_version));
  64. if let Some(ver) = mismatched_ts_version {
  65. let update_cmd = match cfg.toolchain.package_manager.clone().unwrap_or_default() {
  66. PackageManager::NPM => "npm update",
  67. PackageManager::Yarn => "yarn upgrade",
  68. PackageManager::PNPM => "pnpm update",
  69. };
  70. eprintln!(
  71. "WARNING: `@coral-xyz/anchor` version({ver}) and the current CLI version\
  72. ({cli_version}) don't match.\n\n\t\
  73. This can lead to unwanted behavior. To fix, upgrade the package by running:\n\n\t\
  74. {update_cmd} @coral-xyz/anchor@{cli_version}\n"
  75. );
  76. }
  77. Ok(())
  78. }
  79. /// Check for potential dependency improvements.
  80. ///
  81. /// The main problem people will run into with Solana v2 is that the `solana-program` version
  82. /// specified in users' `Cargo.toml` might be incompatible with `anchor-lang`'s dependency.
  83. /// To fix this and similar problems, users should use the crates exported from `anchor-lang` or
  84. /// `anchor-spl` when possible.
  85. pub fn check_deps(cfg: &WithPath<Config>) -> Result<()> {
  86. // Check `solana-program`
  87. cfg.get_rust_program_list()?
  88. .into_iter()
  89. .map(|path| path.join("Cargo.toml"))
  90. .map(cargo_toml::Manifest::from_path)
  91. .map(|man| man.map_err(|e| anyhow!("Failed to read manifest: {e}")))
  92. .collect::<Result<Vec<_>>>()?
  93. .into_iter()
  94. .filter(|man| man.dependencies.contains_key("solana-program"))
  95. .for_each(|man| {
  96. eprintln!(
  97. "WARNING: Adding `solana-program` as a separate dependency might cause conflicts.\n\
  98. To solve, remove the `solana-program` dependency and use the exported crate from \
  99. `anchor-lang`.\n\
  100. `use solana_program` becomes `use anchor_lang::solana_program`.\n\
  101. Program name: `{}`\n",
  102. man.package().name()
  103. )
  104. });
  105. Ok(())
  106. }
  107. /// Check whether the `idl-build` feature is being used correctly.
  108. ///
  109. /// **Note:** The check expects the current directory to be a program directory.
  110. pub fn check_idl_build_feature() -> Result<()> {
  111. let manifest_path = Path::new("Cargo.toml").canonicalize()?;
  112. let manifest = Manifest::from_path(&manifest_path)?;
  113. // Check whether the manifest has `idl-build` feature
  114. let has_idl_build_feature = manifest
  115. .features
  116. .iter()
  117. .any(|(feature, _)| feature == "idl-build");
  118. if !has_idl_build_feature {
  119. let anchor_spl_idl_build = manifest
  120. .dependencies
  121. .iter()
  122. .any(|dep| dep.0 == "anchor-spl")
  123. .then_some(r#", "anchor-spl/idl-build""#)
  124. .unwrap_or_default();
  125. return Err(anyhow!(
  126. r#"`idl-build` feature is missing. To solve, add
  127. [features]
  128. idl-build = ["anchor-lang/idl-build"{anchor_spl_idl_build}]
  129. in `{manifest_path:?}`."#
  130. ));
  131. }
  132. // Check if `idl-build` is enabled by default
  133. manifest
  134. .dependencies
  135. .iter()
  136. .filter(|(_, dep)| dep.req_features().contains(&"idl-build".into()))
  137. .for_each(|(name, _)| {
  138. eprintln!(
  139. "WARNING: `idl-build` feature of crate `{name}` is enabled by default. \
  140. This is not the intended usage.\n\n\t\
  141. To solve, do not enable the `idl-build` feature and include crates that have \
  142. `idl-build` feature in the `idl-build` feature list:\n\n\t\
  143. [features]\n\t\
  144. idl-build = [\"{name}/idl-build\", ...]\n"
  145. )
  146. });
  147. // Check `anchor-spl`'s `idl-build` feature
  148. manifest
  149. .dependencies
  150. .get("anchor-spl")
  151. .and_then(|_| manifest.features.get("idl-build"))
  152. .map(|feature_list| !feature_list.contains(&"anchor-spl/idl-build".into()))
  153. .unwrap_or_default()
  154. .then(|| {
  155. eprintln!(
  156. "WARNING: `idl-build` feature of `anchor-spl` is not enabled. \
  157. This is likely to result in cryptic compile errors.\n\n\t\
  158. To solve, add `anchor-spl/idl-build` to the `idl-build` feature list:\n\n\t\
  159. [features]\n\t\
  160. idl-build = [\"anchor-spl/idl-build\", ...]\n"
  161. )
  162. });
  163. Ok(())
  164. }