workspace.rs 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. use anchor_cli::config::{Config, ConfigOverride, WithPath};
  2. // with_workspace ensures the current working directory is always the top level
  3. // workspace directory, i.e., where the `Anchor.toml` file is located, before
  4. // and after the closure invocation.
  5. //
  6. // The closure passed into this function must never change the working directory
  7. // to be outside the workspace. Doing so will have undefined behavior.
  8. pub fn with_workspace<R>(
  9. cfg_override: &ConfigOverride,
  10. f: impl FnOnce(&mut WithPath<Config>) -> R,
  11. ) -> R {
  12. set_workspace_dir_or_exit();
  13. let mut cfg = Config::discover(cfg_override)
  14. .expect("Previously set the workspace dir")
  15. .expect("Anchor.toml must always exist");
  16. let r = f(&mut cfg);
  17. set_workspace_dir_or_exit();
  18. r
  19. }
  20. pub fn set_workspace_dir_or_exit() {
  21. let d = match Config::discover(&ConfigOverride::default()) {
  22. Err(err) => {
  23. println!("Workspace configuration error: {err}");
  24. std::process::exit(1);
  25. }
  26. Ok(d) => d,
  27. };
  28. match d {
  29. None => {
  30. println!("Not in anchor workspace.");
  31. std::process::exit(1);
  32. }
  33. Some(cfg) => {
  34. match cfg.path().parent() {
  35. None => {
  36. println!("Unable to make new program");
  37. }
  38. Some(parent) => {
  39. if std::env::set_current_dir(parent).is_err() {
  40. println!("Not in anchor workspace.");
  41. std::process::exit(1);
  42. }
  43. }
  44. };
  45. }
  46. }
  47. }