mod.rs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. use std::{cell::OnceCell, path::PathBuf};
  2. use anyhow::Result;
  3. use clap::Parser;
  4. use dadk_config::{
  5. common::target_arch::TargetArch, manifest::DadkManifestFile, rootfs::RootFSConfigFile,
  6. };
  7. use derive_builder::Builder;
  8. use manifest::parse_manifest;
  9. use crate::{
  10. console::CommandLineArgs,
  11. utils::{abs_path, check_dir_exists},
  12. };
  13. mod manifest;
  14. /// DADK的执行上下文
  15. #[derive(Debug, Clone, Builder)]
  16. pub struct DADKExecContext {
  17. pub command: CommandLineArgs,
  18. /// DADK manifest file
  19. pub manifest: DadkManifestFile,
  20. /// RootFS config file
  21. rootfs: OnceCell<RootFSConfigFile>,
  22. }
  23. pub fn build_exec_context() -> Result<DADKExecContext> {
  24. let mut builder = DADKExecContextBuilder::create_empty();
  25. builder.command(CommandLineArgs::parse());
  26. builder.rootfs(OnceCell::new());
  27. parse_manifest(&mut builder).expect("Failed to parse manifest");
  28. let ctx = builder.build()?;
  29. ctx.setup_workdir().expect("Failed to setup workdir");
  30. Ok(ctx)
  31. }
  32. impl DADKExecContext {
  33. /// 获取工作目录的绝对路径
  34. pub fn workdir(&self) -> PathBuf {
  35. abs_path(&PathBuf::from(&self.command.workdir))
  36. }
  37. /// 设置进程的工作目录
  38. fn setup_workdir(&self) -> Result<()> {
  39. std::env::set_current_dir(&self.workdir()).expect("Failed to set current directory");
  40. Ok(())
  41. }
  42. /// Get rootfs configuration
  43. pub fn rootfs(&self) -> &RootFSConfigFile {
  44. self.rootfs.get_or_init(|| {
  45. RootFSConfigFile::load(&self.manifest.metadata.rootfs_config)
  46. .expect("Failed to load rootfs config")
  47. })
  48. }
  49. /// Get sysroot directory
  50. ///
  51. /// If the directory does not exist, or the path is not a folder, an error is returned
  52. pub fn sysroot_dir(&self) -> Result<PathBuf> {
  53. check_dir_exists(&self.manifest.metadata.sysroot_dir)
  54. .map(|p| p.clone())
  55. .map_err(|e| anyhow::anyhow!("Failed to get sysroot dir: {}", e))
  56. }
  57. /// Get cache root directory
  58. ///
  59. /// If the directory does not exist, or the path is not a folder, an error is returned
  60. pub fn cache_root_dir(&self) -> Result<PathBuf> {
  61. check_dir_exists(&self.manifest.metadata.cache_root_dir)
  62. .map(|p| p.clone())
  63. .map_err(|e| anyhow::anyhow!("Failed to get cache root dir: {}", e))
  64. }
  65. #[deprecated]
  66. pub fn user_config_dir(&self) -> Result<PathBuf> {
  67. check_dir_exists(&self.manifest.metadata.user_config_dir)
  68. .map(|p| p.clone())
  69. .map_err(|e| anyhow::anyhow!("Failed to get user config dir: {}", e))
  70. }
  71. pub fn target_arch(&self) -> TargetArch {
  72. self.manifest.metadata.arch
  73. }
  74. }