Run cmc include before validating

Change-Id: I42cbdf530385d8ddd4c9ad79fd05a11bf2c484ea
Reviewed-on: https://fuchsia-review.googlesource.com/c/fargo/+/453701
Reviewed-by: Marc Khouri <mnck@google.com>
Reviewed-by: Rob Tsuk <robtsuk@google.com>
diff --git a/src/package.rs b/src/package.rs
index 405c23e..8ef2b19 100644
--- a/src/package.rs
+++ b/src/package.rs
@@ -73,6 +73,40 @@
     Ok(())
 }
 
+fn include_cmx_file(
+    fuchsia_config: &FuchsiaConfig,
+    cmx_path: &Path,
+    temp_dir: &TempDir,
+) -> Result<PathBuf, Error> {
+    let temp_dir_str = temp_dir.path().to_string_lossy();
+    let destination_path = format!(
+        "{}/included_{}",
+        temp_dir_str,
+        cmx_path
+            .file_name()
+            .ok_or(format_err!("file_name failed on {:#?}", cmx_path))?
+            .to_string_lossy()
+    );
+
+    let cmc = cmc_path(fuchsia_config)?;
+
+    let output = Command::new(cmc)
+        .arg("include")
+        .arg(cmx_path)
+        .arg("--output")
+        .arg(&destination_path)
+        .arg("--includepath")
+        .arg(&fuchsia_dir()?)
+        .output()
+        .context("Running `cmc` to resolve includes cmx file")?;
+
+    if !output.status.success() {
+        bail!("cmc returned error: {}", String::from_utf8_lossy(&output.stderr));
+    }
+
+    Ok(PathBuf::from(destination_path))
+}
+
 fn format_cmx_file(
     fuchsia_config: &FuchsiaConfig,
     cmx_path: &Path,
@@ -376,8 +410,9 @@
     }
     create_dir_all(&output_path).context("create_dir_all failed")?;
     let stripped_binary_path = strip_binary(binary_path)?;
-    validate_cmx_file(verbose, &target_options.config, &cmx_path)?;
-    let formatted_path = format_cmx_file(&target_options.config, &cmx_path, &temp_dir)?;
+    let included_cmx_file = include_cmx_file(&target_options.config, &cmx_path, &temp_dir)?;
+    validate_cmx_file(verbose, &target_options.config, &included_cmx_file)?;
+    let formatted_path = format_cmx_file(&target_options.config, &included_cmx_file, &temp_dir)?;
     let package_path = temp_dir.path().join("package");
     write_package_file(verbose, &package_path, &package_name)?;
     let manifest_path = temp_dir.path().join("manifest");