Skip to main content

cargo_wrap/
lib.rs

1use std::{env, fs, io};
2use std::fs::OpenOptions;
3use std::io::{Error, ErrorKind, Write};
4use std::path::PathBuf;
5use std::process::Command;
6use toml::Value;
7
8
9/// Holds configuration settings for a Rust project build.
10///
11/// This struct encapsulates settings like build target, output paths, enabled features, and
12/// release/debug modes.
13///
14/// # Fields
15///
16/// * `compilation_target` - Optional string specifying a custom compilation target.
17/// * `features` - Optional list of features to enable during the build.
18/// * `output_path` - Optional path to store compiled artifacts.
19/// * `release` - Whether to compile in release mode (`true`) or debug mode (`false`).
20/// * `is_lib` - If `true`, builds the project as a library (`--lib`), otherwise builds as a binary (`--bin`).
21/// * `no_default_features` - If `true`, disables default features (`--no-default-features`).
22/// * `project_path` - The root directory of the Rust project.
23/// * `cargo_toml_path` - Path to the project's `Cargo.toml`.
24/// * `target` - Optional specific binary/library to build.
25#[derive(Default, Debug, Clone)]
26pub struct ProjectSettings {
27    compilation_target: Option<String>,
28    features: Option<Vec<String>>,
29    output_path: Option<PathBuf>,
30    release: bool,
31    is_lib: bool,
32    no_default_features: bool,
33    project_path: PathBuf,
34    cargo_toml_path: PathBuf,
35    target: Option<String>
36}
37
38impl ProjectSettings {
39
40    /// Creates a new `ProjectSettings` instance for managing build configurations.
41    ///
42    /// # Arguments
43    ///
44    /// * `project_path` - The root directory of the Rust project.
45    /// * `output_path` - Optional path where the build output should be stored.
46    /// * `target` - Optional target triple (e.g., "x86_64-unknown-linux-gnu").
47    /// * `is_lib` - If `true`, builds the project as a library (`--lib`). If `false`, builds as a binary (`--bin`).
48    ///
49    /// # Returns
50    ///
51    /// A `ProjectSettings` instance with default values.
52    ///
53    /// # Example
54    /// ```rust
55    /// use cargo_wrap::ProjectSettings;
56    /// let settings = ProjectSettings::new("/path/to/project", None, None, false);
57    /// ```
58    pub fn new(project_path: impl Into<PathBuf>, output_path: Option<impl Into<PathBuf>>, target: Option<String>,
59               is_lib: bool) -> Self {
60        let project_path = project_path.into();
61        let cargo_toml = project_path.clone().join("Cargo.toml");
62        Self {
63            project_path,
64            release: false,
65            output_path: output_path.map(Into::into),
66            cargo_toml_path: cargo_toml,
67            is_lib,
68            target,
69            ..Default::default()
70        }
71    }
72
73    /// Retrieves a list of available features from `Cargo.toml`.
74    ///
75    /// # Returns
76    ///
77    /// * `Ok(Vec<String>)` - A list of feature names if parsing succeeds.
78    /// * `Err(io::Error)` - If `Cargo.toml` is missing or cannot be parsed.
79    ///
80    /// # Errors
81    ///
82    /// This function will return an error if:
83    /// - `Cargo.toml` does not exist.
84    /// - The file cannot be read due to I/O issues.
85    /// - The `features` section in `Cargo.toml` is invalid.
86    ///
87    /// # Example
88    /// ```rust
89    /// use cargo_wrap::ProjectSettings;
90    /// let settings = ProjectSettings::new("/path/to/project", None, None, false);
91    /// match settings.get_features() {
92    ///     Ok(features) => println!("Available features: {:?}", features),
93    ///     Err(e) => eprintln!("Error retrieving features: {}", e),
94    /// }
95    /// ```
96    pub fn get_features(&self) -> io::Result<Vec<String>> {
97        let cargo_content = fs::read_to_string(&self.cargo_toml_path)?;
98        let parsed_toml: Value = cargo_content.parse().map_err(|e| Error::new(ErrorKind::InvalidData, e))?;
99        if let Some(features) = parsed_toml.get("features").and_then(|f| f.as_table()) {
100            Ok(features.keys().cloned().collect())
101        } else {
102            Ok(vec![])
103        }
104    }
105
106    /// Marks the project to be built as `release`
107    pub fn set_release(&mut self) {
108        self.release = true;
109    }
110
111    /// Manually enable a feature that's available in the project
112    pub fn add_feature(&mut self, feature: String) {
113        self.features.get_or_insert_with(Vec::new).push(feature)
114    }
115
116    /// Manually sets the build target
117    pub fn set_target(&mut self, target: String) {
118        self.target = Some(target)
119    }
120
121    /// Manually set the build output path
122    pub fn set_output_path(&mut self, path: PathBuf) {
123        self.output_path = Some(path)
124    }
125
126    /// Manually set the project path
127    pub fn set_project_path(&mut self, path: PathBuf) {
128        self.project_path = path
129    }
130}
131
132/// The main struct responsible for building a Rust project.
133///
134/// `Builder` acts as a wrapper around the `cargo build` command, allowing
135/// users to configure build settings such as verbosity, threading, and output paths.
136///
137/// # Fields
138///
139/// * `cargo_path` - Path to the `cargo` binary.
140/// * `project_settings` - The `ProjectSettings` instance containing build configurations.
141/// * `thread_count` - Optional number of jobs (`--jobs N`) to use during the build. Default value is 0.
142/// * `output_path` - Optional log file to store output.
143/// * `verbose_build` - If `true`, enables verbose output (`--verbose`).
144/// * `additional_flags` - Optional flags to pass to the `rustc` binary (via the `RUSTFLAGS` environment variable)
145#[derive(Default, Debug)]
146pub struct Builder {
147    cargo_path: PathBuf,
148    project_settings: ProjectSettings,
149    thread_count: usize,
150    log_path: Option<PathBuf>,
151    verbose_build: bool,
152    additional_flags: Vec<String>
153}
154
155impl Builder {
156
157    /// Private function to get the `cargo` binary path from the environment
158    fn get_cargo_path() -> io::Result<PathBuf> {
159        env::var_os("CARGO")
160            .map(PathBuf::from)
161            .ok_or_else(|| Error::new(ErrorKind::NotFound, "CARGO environment variable not found"))
162    }
163
164    /// Creates a new `Builder` instance for managing and executing cargo builds.
165    ///
166    /// This function initializes the builder with the given project settings,
167    /// allowing for configuration of build parameters such as job count and log output.
168    ///
169    /// # Arguments
170    ///
171    /// * `project_settings` - A `ProjectSettings` instance containing the configuration
172    ///   for the Rust project to be built.
173    /// * `thread_count` - Optional number of parallel jobs (`--jobs N`) to use for building.
174    ///   If `0`, the default job count will be used.
175    /// * `log_path` - Optional path to a log file where build output will be stored.
176    ///
177    /// # Returns
178    ///
179    /// * `Ok(Builder)` - A new `Builder` instance ready to execute a build.
180    /// * `Err(io::Error)` - If the `cargo` binary is not found in the environment.
181    ///
182    /// # Errors
183    ///
184    /// This function will return an error if:
185    /// - The `CARGO` environment variable is not set, meaning `cargo` cannot be found.
186    /// - The provided `log_path` is invalid or cannot be written to.
187    ///
188    /// # Example
189    /// ```rust
190    /// use cargo_wrap::{Builder, ProjectSettings};
191    /// use std::io;
192    ///
193    /// fn main() -> io::Result<()> {
194    ///     let settings = ProjectSettings::new("/path/to/project", None, None, false);
195    ///     let builder = Builder::new(settings, 4, Some("build.log"))?;
196    ///     Ok(())
197    /// }
198    pub fn new(project_settings: ProjectSettings, thread_count: usize, log_path:
199    Option<impl Into<PathBuf>>) ->
200               io::Result<Builder> {
201        let cargo_path = Builder::get_cargo_path()?;
202        Ok(Self {
203            cargo_path,
204            project_settings,
205            thread_count,
206            log_path: log_path.map(Into::into),
207            ..Default::default()
208        })
209    }
210
211    /// Tells the builder to use the `--verbose` flag when building
212    pub fn set_verbose(&mut self) {
213        self.verbose_build = true;
214    }
215
216    /// Adds a flag to the list of additional flags that will be passed to `rustc`
217    pub fn add_rustc_flag(&mut self, flag: String) {
218        self.additional_flags.push(flag);
219    }
220
221    /// Executes the build process using `cargo build`.
222    ///
223    /// This function spawns a `cargo build` process with the specified settings,
224    /// such as release/debug mode, enabled features, and output directories.
225    ///
226    /// # Returns
227    ///
228    /// * `Ok(())` - If the build succeeds.
229    /// * `Err(io::Error)` - If the build process fails.
230    ///
231    /// # Errors
232    ///
233    /// This function will return an error if:
234    /// - The `cargo` binary is missing from the system.
235    /// - The build process fails (e.g., compilation errors).
236    /// - The log file cannot be written to (if logging is enabled).
237    ///
238    /// # Example
239    /// ```rust
240    /// use cargo_wrap::{Builder, ProjectSettings};
241    /// use std::io;
242    ///
243    /// fn main() -> io::Result<()> {
244    ///     let settings = ProjectSettings::new("/path/to/project", None, None, false);
245    ///     let builder = Builder::new(settings, 4, Some("build.log"))?;
246    ///     builder.build()?;
247    ///     Ok(())
248    /// }
249    /// ```
250    pub fn build(&self) -> io::Result<()> {
251        let mut command = Command::new(self.cargo_path.clone());
252        command.arg("build");
253        if self.verbose_build {
254            command.arg("--verbose");
255        }
256        if self.project_settings.release {
257            command.arg("--release");
258        }
259        if self.thread_count > 0 {
260            command.arg("--jobs").arg(self.thread_count.to_string());
261
262        }
263        if let Some(output_path) = &self.project_settings.output_path {
264            command.env("CARGO_TARGET_DIR", output_path);
265        }
266        if !self.additional_flags.is_empty() {
267            command.env("RUSTFLAGS", self.additional_flags.join(" "));
268        }
269        if let Some(ref target) = self.project_settings.compilation_target {
270            command.arg("--target").arg(target);
271        }
272        if let Some(features) = &self.project_settings.features {
273            features.iter().for_each(|f| {
274                command.arg("--features");
275                command.arg(f);
276            });
277        }
278        if self.project_settings.no_default_features {
279            command.arg("--no-default-features");
280        }
281        if let Some(target) = &self.project_settings.target {
282            command.arg(if self.project_settings.is_lib { "--lib" } else { "--bin" }).arg(target);
283        }
284
285        let output = command.current_dir(&self.project_settings.project_path).output()?;
286        if let Some(output_log) = &self.log_path {
287            let mut output_file = OpenOptions::new().create(true).append(true).open(output_log)?;
288            output_file.write_all(&output.stdout)?;
289            output_file.write_all(&output.stderr)?;
290        }
291        if output.status.success() {
292            Ok(())
293        } else {
294            Err(Error::new(ErrorKind::Other, format!("Failed to compile project: {}", output.status)))
295        }
296    }
297}
298