Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

make env.volumes only change package path when used #665

Merged
merged 1 commit into from
Mar 31, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ This project adheres to [Semantic Versioning](http://semver.org/).

## [Unreleased]

- #665 - when not using [env.volumes](https://github.com/cross-rs/cross#mounting-volumes-into-the-build-environment), mount project in /project
- #624 - Add `build.default-target`
- #670 - Use serde for deserialization of Cross.toml
- Change rust edition to 2021 and bump MSRV for the cross binary to 1.58.1
Expand Down
7 changes: 7 additions & 0 deletions 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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ libc = "0.2"

[target.'cfg(windows)'.dependencies]
winapi = { version = "0.3", features = ["winbase"] }
dunce = "1"

[profile.release]
lto = true
79 changes: 69 additions & 10 deletions src/docker.rs
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,17 @@ pub fn run(
let cargo_dir = mount_finder.find_mount_path(cargo_dir);
let xargo_dir = mount_finder.find_mount_path(xargo_dir);
let target_dir = mount_finder.find_mount_path(target_dir);
let mount_root = mount_finder.find_mount_path(root);
let host_root = mount_finder.find_mount_path(root);
let mount_root: PathBuf;
#[cfg(target_os = "windows")]
{
// On Windows, we can not mount the directory name directly. Instead, we use wslpath to convert the path to a linux compatible path.
mount_root = wslpath(&host_root, verbose)?;
}
#[cfg(not(target_os = "windows"))]
{
mount_root = host_root.clone();
}
let sysroot = mount_finder.find_mount_path(sysroot);

let mut cmd = if uses_xargo {
Expand Down Expand Up @@ -123,18 +133,35 @@ pub fn run(
// flag forwards the value from the parent shell
docker.args(&["-e", var]);
}

let mut env_volumes = false;
for ref var in config.env_volumes(target)? {
validate_env_var(var)?;

if let Ok(val) = env::var(var) {
let host_path = Path::new(&val).canonicalize()?;
let mount_path = &host_path;
let host_path: PathBuf;
let mount_path: PathBuf;

#[cfg(target_os = "windows")]
{
// Docker does not support UNC paths, this will try to not use UNC paths
host_path = dunce::canonicalize(&val)
.wrap_err_with(|| format!("when canonicalizing path `{val}`"))?;
// On Windows, we can not mount the directory name directly. Instead, we use wslpath to convert the path to a linux compatible path.
mount_path = wslpath(&host_path, verbose)?;
}
#[cfg(not(target_os = "windows"))]
{
host_path = Path::new(&val)
.canonicalize()
.wrap_err_with(|| format!("when canonicalizing path `{val}`"))?;
mount_path = host_path.clone();
}
docker.args(&[
"-v",
&format!("{}:{}", host_path.display(), mount_path.display()),
]);
docker.args(&["-e", &format!("{}={}", var, mount_path.display())]);
env_volumes = true;
}
}

Expand Down Expand Up @@ -186,14 +213,24 @@ pub fn run(
.args(&["-v", &format!("{}:/xargo:Z", xargo_dir.display())])
.args(&["-v", &format!("{}:/cargo:Z", cargo_dir.display())])
// Prevent `bin` from being mounted inside the Docker container.
.args(&["-v", "/cargo/bin"])
.args(&[
.args(&["-v", "/cargo/bin"]);
if env_volumes {
docker.args(&[
"-v",
&format!("{}:{}:Z", mount_root.display(), mount_root.display()),
])
&format!("{}:{}:Z", host_root.display(), mount_root.display()),
]);
} else {
docker.args(&["-v", &format!("{}:/project:Z", host_root.display())]);
}
docker
.args(&["-v", &format!("{}:/rust:Z,ro", sysroot.display())])
.args(&["-v", &format!("{}:/target:Z", target_dir.display())])
.args(&["-w", &mount_root.display().to_string()]);
.args(&["-v", &format!("{}:/target:Z", target_dir.display())]);

if env_volumes {
Emilgardis marked this conversation as resolved.
Show resolved Hide resolved
docker.args(&["-w", &mount_root.display().to_string()]);
} else {
docker.args(&["-w", "/project"]);
}

// When running inside NixOS or using Nix packaging we need to add the Nix
// Store to the running container so it can load the needed binaries.
Expand Down Expand Up @@ -233,6 +270,28 @@ pub fn image(config: &Config, target: &Target) -> Result<String> {
Ok(format!("{CROSS_IMAGE}/{target}:{version}"))
}

#[cfg(target_os = "windows")]
fn wslpath(path: &Path, verbose: bool) -> Result<PathBuf> {
let wslpath = which::which("wsl.exe")
.map_err(|_| eyre::eyre!("could not find wsl.exe"))
.warning("usage of `env.volumes` requires WSL on Windows")
.suggestion("is WSL installed on the host?")?;

Command::new(wslpath)
.arg("-e")
.arg("wslpath")
.arg("-a")
.arg(path)
.run_and_get_stdout(verbose)
.wrap_err_with(|| {
format!(
"could not get linux compatible path for `{}`",
path.display()
)
})
.map(|s| s.trim().into())
}
Comment on lines +274 to +293
Copy link
Member Author

@Emilgardis Emilgardis Mar 18, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

it would be possible to fallback to a manual implementation of "normalizing". the logic should be quite simple but I don't feel like it's necessary to do.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I take that back, I tried to do it correctly but handling this is quite annoying :)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

maybe

fn wslpath2(path: impl AsRef<Path>) -> Result<String> {
    fn get_path_prefix_drive(path: &Path) -> Option<&str> {
        match path.components().next().unwrap() {
            std::path::Component::Prefix(prefix_component) => match prefix_component.kind() {
                std::path::Prefix::VerbatimDisk(_) => Some(
                    prefix_component
                        .as_os_str()
                        .to_str()
                        .expect("windows drive letters should be ascii A-Z")
                        .strip_prefix(r"\\?\")?
                        .strip_suffix(":")?,
                ),
                std::path::Prefix::Disk(_) => Some(
                    prefix_component
                        .as_os_str()
                        .to_str()
                        .expect("windows drive letters should be ascii A-Z")
                        .strip_suffix(":")?,
                ),
                _ => None,
            },
            _ => None,
        }
    }
    let path = path.as_ref();
    let components = path.components().skip(2);
    let mut path_c = String::from("/mnt/");

    path_c
        .push_str(&get_path_prefix_drive(path).ok_or_else(|| eyre::eyre!("no drive letter found"))?.to_lowercase());
    let mut sep = true;
    for comp in components {
        if sep {
            path_c.push('/');
        } else {
            sep = true;
        }
        match comp {
            std::path::Component::Normal(p) => path_c.push_str(
                p.to_str()
                    .ok_or_else(|| eyre::eyre!("path needs to be utf8"))?,
            ),
            std::path::Component::ParentDir => path_c.push_str(".."),
            std::path::Component::CurDir => path_c.push('.'),
            _ => sep = false,
        }
    }
    Ok(path_c)
}


fn docker_read_mount_paths() -> Result<Vec<MountDetail>> {
let hostname = env::var("HOSTNAME").wrap_err("HOSTNAME environment variable not found")?;

Expand Down