cargo.rs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //! Utilities for working with cargo and rust files
  2. use crate::error::{Error, Result};
  3. use std::{env, fs, path::PathBuf, process::Command, str};
  4. /// How many parent folders are searched for a `Cargo.toml`
  5. const MAX_ANCESTORS: u32 = 10;
  6. /// Returns the root of the crate that the command is run from
  7. ///
  8. /// If the command is run from the workspace root, this will return the top-level Cargo.toml
  9. pub fn crate_root() -> Result<PathBuf> {
  10. // From the current directory we work our way up, looking for `Cargo.toml`
  11. env::current_dir()
  12. .ok()
  13. .and_then(|mut wd| {
  14. for _ in 0..MAX_ANCESTORS {
  15. if contains_manifest(&wd) {
  16. return Some(wd);
  17. }
  18. if !wd.pop() {
  19. break;
  20. }
  21. }
  22. None
  23. })
  24. .ok_or_else(|| Error::CargoError("Failed to find the cargo directory".to_string()))
  25. }
  26. /// Returns the root of a workspace
  27. /// TODO @Jon, find a different way that doesn't rely on the cargo metadata command (it's slow)
  28. pub fn workspace_root() -> Result<PathBuf> {
  29. let output = Command::new("cargo")
  30. .args(&["metadata"])
  31. .output()
  32. .map_err(|_| Error::CargoError("Manifset".to_string()))?;
  33. if !output.status.success() {
  34. let mut msg = str::from_utf8(&output.stderr).unwrap().trim();
  35. if msg.starts_with("error: ") {
  36. msg = &msg[7..];
  37. }
  38. return Err(Error::CargoError(msg.to_string()));
  39. }
  40. let stdout = str::from_utf8(&output.stdout).unwrap();
  41. for line in stdout.lines() {
  42. let meta: serde_json::Value = serde_json::from_str(line)
  43. .map_err(|_| Error::CargoError("InvalidOutput".to_string()))?;
  44. let root = meta["workspace_root"]
  45. .as_str()
  46. .ok_or_else(|| Error::CargoError("InvalidOutput".to_string()))?;
  47. return Ok(root.into());
  48. }
  49. Err(Error::CargoError("InvalidOutput".to_string()))
  50. }
  51. /// Checks if the directory contains `Cargo.toml`
  52. fn contains_manifest(path: &PathBuf) -> bool {
  53. fs::read_dir(path)
  54. .map(|entries| {
  55. entries
  56. .filter_map(Result::ok)
  57. .any(|ent| &ent.file_name() == "Cargo.toml")
  58. })
  59. .unwrap_or(false)
  60. }