is_wsl/lib.rs
1extern crate is_docker;
2extern crate once_cell;
3
4use once_cell::sync::OnceCell;
5use std::{fs::File, io::Read};
6
7pub fn is_wsl() -> bool {
8 static CACHED_RESULT: OnceCell<bool> = OnceCell::new();
9
10 *CACHED_RESULT.get_or_init(|| {
11 if std::env::consts::OS != "linux" {
12 return false;
13 }
14
15 if let Ok(os_release) = get_os_release() {
16 if os_release.to_lowercase().contains("microsoft") {
17 return !is_docker::is_docker();
18 }
19 }
20
21 if proc_version_includes_microsoft() {
22 !is_docker::is_docker()
23 } else {
24 false
25 }
26 })
27}
28
29fn proc_version_includes_microsoft() -> bool {
30 match std::fs::read_to_string("/proc/version") {
31 Ok(file_contents) => file_contents.to_lowercase().contains("microsoft"),
32 Err(_) => false,
33 }
34}
35
36// This function is copied from the sys-info crate to avoid taking a dependency on all of sys-info
37// https://docs.rs/sys-info/0.9.1/src/sys_info/lib.rs.html#426-433
38//
39// The MIT License (MIT)
40//
41// Copyright (c) 2015 Siyu Wang
42//
43// Permission is hereby granted, free of charge, to any person obtaining a copy
44// of this software and associated documentation files (the "Software"), to deal
45// in the Software without restriction, including without limitation the rights
46// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
47// copies of the Software, and to permit persons to whom the Software is
48// furnished to do so, subject to the following conditions:
49//
50// The above copyright notice and this permission notice shall be included in all
51// copies or substantial portions of the Software.
52//
53// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
54// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
55// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
56// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
57// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
58// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
59// SOFTWARE.
60fn get_os_release() -> Result<String, std::io::Error> {
61 let mut s = String::new();
62 File::open("/proc/sys/kernel/osrelease")?.read_to_string(&mut s)?;
63 s.pop(); // pop '\n'
64 Ok(s)
65}