wslpath/
lib.rs

1use std::process::Command;
2
3/// Convert Paths using the WSLPath Executable
4fn wsl_paths(
5    path: &str,
6    distro: Option<String>,
7    to_linux_path: bool,
8) -> Result<String, Box<dyn std::error::Error>> {
9    // Check if distro provided
10    let distro_args: Vec<String> = match distro {
11        Some(distro_name) => vec!["-d".to_string(), distro_name],
12        None => vec![],
13    };
14    // Select path arg
15    // Based on this conversion takes place
16    let path_arg = {
17        if to_linux_path {
18            // Return absolute paths
19            "-a".to_string()
20        } else {
21            // Convert to Windows
22            "-m".to_string()
23        }
24    };
25    let stdout = Command::new("wsl.exe")
26        // Specify the distro to select
27        .args(distro_args)
28        .arg("-e")
29        .arg("wslpath")
30        .arg(path_arg)
31        .arg(path.replace("\\", "\\\\"))
32        .output()?
33        .stdout;
34    let wsl_path = std::str::from_utf8(&stdout)?.trim().to_string();
35    Ok(wsl_path)
36}
37
38/// Convert WSL Path to Windows Path
39/// Pass Path and name of distro
40pub fn wsl_to_windows_with_distro(
41    path: &str,
42    distro: String,
43) -> Result<String, Box<dyn std::error::Error>> {
44    wsl_paths(path, Some(distro), false)
45}
46
47/// Convert WSL Path to Windows Path
48/// Pass path
49/// Uses default distro for execution by default
50pub fn wsl_to_windows(path: &str) -> Result<String, Box<dyn std::error::Error>> {
51    wsl_paths(path, None, false)
52}
53
54/// Convert Windows Path to WSL Path
55/// Pass Path and name of distro
56pub fn windows_to_wsl_with_distro(
57    path: &str,
58    distro: String,
59) -> Result<String, Box<dyn std::error::Error>> {
60    wsl_paths(path, Some(distro), true)
61}
62
63/// Convert Windows Path to WSL Path
64/// Pass path
65/// Uses default distro for execution by default
66pub fn windows_to_wsl(path: &str) -> Result<String, Box<dyn std::error::Error>> {
67    wsl_paths(path, None, true)
68}
69
70#[cfg(test)]
71mod tests {
72    use crate::{windows_to_wsl, wsl_to_windows};
73
74    // These tests may not execute on all machines
75    #[test]
76    fn test_wsl_to_windows() {
77        assert_eq!(wsl_to_windows("/mnt/c").unwrap_or_default(), "C:/");
78    }
79    #[test]
80    fn test_windows_to_wsl() {
81        assert_eq!(windows_to_wsl("C:/").unwrap_or_default(), "/mnt/c/");
82    }
83}