Skip to content

Commit

Permalink
Convert all paths to Camino (#511)
Browse files Browse the repository at this point in the history
Fixes #427.
Fixes #510.
  • Loading branch information
sayrer authored Jun 24, 2022
1 parent 4a523e1 commit e655d34
Show file tree
Hide file tree
Showing 17 changed files with 247 additions and 221 deletions.
5 changes: 3 additions & 2 deletions impl/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions impl/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ path = "src/bin/cargo-raze.rs"

[dependencies]
anyhow = "1.0.38"
camino = "1.0.9"
cargo_metadata = "0.14"
cargo_toml = "0.8.1"
cargo-clone-crate = { version = "0.1.6", default-features = false }
Expand Down
41 changes: 19 additions & 22 deletions impl/src/bin/cargo-raze.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ use std::{
env,
fs::{self, File},
io::Write,
path::{Path, PathBuf},
};

use anyhow::{anyhow, Context, Result};
use camino::{Utf8Path, Utf8PathBuf};

use cargo_metadata::Metadata;
use docopt::Docopt;
Expand Down Expand Up @@ -104,6 +104,11 @@ fn main() -> Result<()> {
Ok(())
}

fn current_dir_utf8() -> Result<Utf8PathBuf> {
Utf8PathBuf::from_path_buf(std::env::current_dir()?)
.map_err(|_e| anyhow!("std::env::current_dir is invalid UTF-8."))
}

fn parse_options() -> Options {
// When used as a cargo subcommand, the string "raze" will always be
// passed as the second `argv` entry. We need to remove that to keep
Expand Down Expand Up @@ -147,34 +152,26 @@ fn fetch_local_metadata(options: &Options) -> Result<Metadata> {
// Gather basic, offline metadata to parse settings from
let fetcher = if let Some(cargo_bin_path) = &options.flag_cargo_bin_path {
SettingsMetadataFetcher {
cargo_bin_path: PathBuf::from(cargo_bin_path),
cargo_bin_path: Utf8PathBuf::from(cargo_bin_path),
}
} else {
SettingsMetadataFetcher::default()
};

let working_directory = if let Some(manifest_path) = &options.flag_manifest_path {
let manifest_path = PathBuf::from(manifest_path).canonicalize()?;
let manifest_path = Utf8PathBuf::from(manifest_path).canonicalize_utf8()?;
if !manifest_path.is_file() {
return Err(anyhow!(
"manifest path `{}` is not a file.",
manifest_path.display()
));
return Err(anyhow!("manifest path `{}` is not a file.", manifest_path));
}
// UNWRAP: Unwrap safe due to check above.
PathBuf::from(manifest_path.parent().unwrap())
Utf8PathBuf::from(manifest_path.parent().unwrap())
} else {
env::current_dir()?
current_dir_utf8()?
};

fetcher
.fetch_metadata(&working_directory, false)
.with_context(|| {
format!(
"Failed to fetch metadata for {}",
working_directory.display()
)
})
.with_context(|| format!("Failed to fetch metadata for {}", working_directory))
}

fn fetch_raze_metadata(
Expand All @@ -193,7 +190,7 @@ fn fetch_raze_metadata(
};

let cargo_raze_working_dir = find_bazel_workspace_root(local_metadata.workspace_root.as_ref())
.unwrap_or(env::current_dir()?);
.unwrap_or(current_dir_utf8()?);

let binary_dep_info = if settings.genmode == GenMode::Remote {
Some(&settings.binary_deps)
Expand Down Expand Up @@ -238,12 +235,12 @@ fn render_files(
local_metadata: &Metadata,
) -> Result<(RenderDetails, Vec<FileOutputs>)> {
let cargo_raze_working_dir = find_bazel_workspace_root(local_metadata.workspace_root.as_ref())
.unwrap_or(env::current_dir()?);
.unwrap_or(current_dir_utf8()?);

let mut bazel_renderer = BazelRenderer::new();
let render_details = RenderDetails {
cargo_root: metadata.cargo_workspace_root.clone(),
path_prefix: PathBuf::from(&settings.workspace_path.trim_start_matches('/')),
path_prefix: Utf8PathBuf::from(&settings.workspace_path.trim_start_matches('/')),
package_aliases_dir: settings.package_aliases_dir.clone(),
vendored_buildfile_name: settings.output_buildfile_suffix.clone(),
bazel_root: cargo_raze_working_dir,
Expand Down Expand Up @@ -276,7 +273,7 @@ fn write_files(
.join("remote");
// Clean out the "remote" directory so users can easily see what build files are relevant
if remote_dir.exists() {
let build_glob = format!("{}/BUILD*.bazel", remote_dir.display());
let build_glob = format!("{}/BUILD*.bazel", remote_dir);
for entry in glob::glob(&build_glob)? {
fs::remove_file(entry?)?;
}
Expand All @@ -285,7 +282,7 @@ fn write_files(

for output in bazel_file_outputs.iter() {
if options.flag_dryrun.unwrap_or(false) {
println!("{}:\n{}", output.path.display(), output.contents);
println!("{}:\n{}", output.path, output.contents);
continue;
}
// Ensure all parent directories exist
Expand All @@ -303,10 +300,10 @@ fn write_files(
}

/// Writes rendered files to filesystem.
fn write_to_file(path: &Path, contents: &str, verbose: bool) -> Result<()> {
fn write_to_file(path: &Utf8Path, contents: &str, verbose: bool) -> Result<()> {
File::create(&path).and_then(|mut f| f.write_all(contents.as_bytes()))?;
if verbose {
println!("Generated {} successfully", path.display());
println!("Generated {} successfully", path);
}
Ok(())
}
21 changes: 11 additions & 10 deletions impl/src/checks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,10 @@
use std::{
collections::{HashMap, HashSet},
fs,
path::Path,
path::PathBuf,
};

use anyhow::{anyhow, Result};
use camino::{Utf8Path, Utf8PathBuf};

use crate::{
error::RazeError,
Expand All @@ -39,7 +38,7 @@ const MAX_DISPLAYED_MISSING_RESOLVE_PACKAGES: usize = 5;
pub fn check_metadata(
raze_metadata: &RazeMetadata,
settings: &RazeSettings,
bazel_workspace_root: &Path,
bazel_workspace_root: &Utf8Path,
) -> Result<()> {
// Check for errors
check_resolve_matches_packages(&raze_metadata.metadata)?;
Expand Down Expand Up @@ -106,7 +105,7 @@ fn check_lockfile_for_missing_checksums(
fn check_all_vendored(
metadata: &Metadata,
settings: &RazeSettings,
bazel_workspace_root: &Path,
bazel_workspace_root: &Utf8Path,
) -> Result<()> {
let non_workspace_packages: Vec<&Package> = metadata
.packages
Expand Down Expand Up @@ -149,15 +148,18 @@ fn check_all_vendored(
message: format!(
"Failed to find expected vendored crates in {:?}: {:?}. Did you forget to run cargo \
vendor?",
expected_full_path.display(),
limited_missing_crates
expected_full_path, limited_missing_crates
),
}
.into(),
)
}

fn vendor_path(bazel_workspace_root: &Path, workspace_path: &str, vendor_dir: &str) -> PathBuf {
fn vendor_path(
bazel_workspace_root: &Utf8Path,
workspace_path: &str,
vendor_dir: &str,
) -> Utf8PathBuf {
bazel_workspace_root
// Trim the absolute label identifier from the start of the workspace path
.join(workspace_path.trim_start_matches('/'))
Expand All @@ -167,13 +169,12 @@ fn vendor_path(bazel_workspace_root: &Path, workspace_path: &str, vendor_dir: &s
/// Returns the packages expected path during current execution.
fn expected_vendored_path(
package: &Package,
bazel_workspace_root: &Path,
bazel_workspace_root: &Utf8Path,
workspace_path: &str,
vendor_dir: &str,
) -> String {
vendor_path(bazel_workspace_root, workspace_path, vendor_dir)
.join(package_ident(&package.name, &package.version.to_string()))
.display()
.to_string()
}

Expand Down Expand Up @@ -289,7 +290,7 @@ mod tests {
let result = check_all_vendored(
&template_metadata(templates::DUMMY_MODIFIED_METADATA),
&settings,
&PathBuf::from("/tmp/some/path"),
&Utf8PathBuf::from("/tmp/some/path"),
);

// Vendored crates will not have been rendered at that path
Expand Down
16 changes: 7 additions & 9 deletions impl/src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,10 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use std::{
collections::{BTreeMap, BTreeSet},
path::PathBuf,
};
use std::collections::{BTreeMap, BTreeSet};

use crate::{features::Features, settings::CrateSettings};
use camino::Utf8PathBuf;
use semver::Version;
use serde::{Deserialize, Serialize};
use url::Url;
Expand Down Expand Up @@ -154,15 +152,15 @@ pub struct CrateContext {
pub pkg_version: Version,
pub edition: String,
pub raze_settings: CrateSettings,
pub canonical_additional_build_file: Option<PathBuf>,
pub canonical_additional_build_file: Option<Utf8PathBuf>,
pub default_deps: CrateDependencyContext,
pub targeted_deps: Vec<CrateTargetedDepContext>,
pub license: LicenseData,
pub features: Features,
pub workspace_path_to_crate: String,
pub workspace_member_dependents: Vec<PathBuf>,
pub workspace_member_dev_dependents: Vec<PathBuf>,
pub workspace_member_build_dependents: Vec<PathBuf>,
pub workspace_member_dependents: Vec<Utf8PathBuf>,
pub workspace_member_dev_dependents: Vec<Utf8PathBuf>,
pub workspace_member_build_dependents: Vec<Utf8PathBuf>,
pub is_workspace_member_dependency: bool,
pub is_binary_dependency: bool,
pub targets: Vec<BuildableTarget>,
Expand Down Expand Up @@ -203,5 +201,5 @@ pub struct WorkspaceContext {
pub output_buildfile_suffix: String,

// A list of relative paths from a Cargo workspace root to a Cargo package.
pub workspace_members: Vec<PathBuf>,
pub workspace_members: Vec<Utf8PathBuf>,
}
7 changes: 4 additions & 3 deletions impl/src/features.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,14 @@
// limitations under the License.

use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::path::{Path, PathBuf};
use std::path::Path;
use std::process::Command;

use crate::error::RazeError;
use crate::settings::RazeSettings;
use crate::util::cargo_bin_path;
use anyhow::{Error, Result};
use camino::Utf8PathBuf;
use cargo_metadata::{Package, PackageId, Version};
use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -133,7 +134,7 @@ fn clean_cargo_tree_output(cargo_tree_output: &str) -> Vec<String> {
// Runs `cargo-tree` with a very specific format argument that makes it easier
// to extract per-platform targets.
fn run_cargo_tree(cargo_dir: &Path, triple: &str) -> Result<String> {
let cargo_bin: PathBuf = cargo_bin_path();
let cargo_bin: Utf8PathBuf = cargo_bin_path();
let mut cargo_tree = Command::new(cargo_bin);
cargo_tree.current_dir(cargo_dir);
cargo_tree
Expand Down Expand Up @@ -386,7 +387,7 @@ proc-macro2 v1.0.26|default,proc-macro| (*)
}

fn mock_cargo_tree_command(_cargo_dir: &Path, triple: &str) -> Result<String> {
let cargo_tree_template_dir = PathBuf::from(std::file!())
let cargo_tree_template_dir = Utf8PathBuf::from(std::file!())
.parent()
.unwrap()
.join("testing/cargo_tree")
Expand Down
Loading

0 comments on commit e655d34

Please sign in to comment.