Visual Studio Code, rebuilt in Rust
Rust
//! filePolicyService.ts on Linux: the policies are the JSON object in `LINUX_SYSTEM_POLICY_FILE_PATH`.
use std::path::Path;
use serde_json::{Map, Value};
/// base/common/policy.ts `LINUX_SYSTEM_POLICY_FILE_PATH`.
pub const WATCHED_PATH: &str = "/etc/vscode/policy.json";
/// FilePolicyService `read()`: the file's object, empty when the file is missing; any other failure is logged.
pub(super) fn read_policy_file(path: &Path) -> Map<String, Value> {
let text = match std::fs::read_to_string(path) {
Ok(text) => text,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Map::new(),
Err(error) => {
eprintln!("[FilePolicyService] Failed to read policies {error}");
return Map::new();
}
};
match serde_json::from_str(&text) {
Ok(Value::Object(policies)) => policies,
Ok(_) => {
eprintln!("[FilePolicyService] Failed to read policies Policy file isn't a JSON object");
Map::new()
}
Err(error) => {
eprintln!("[FilePolicyService] Failed to read policies {error}");
Map::new()
}
}
}
/// FilePolicyService's `fileService.watch(file)`: an inotify watch on the file's folder, which has to exist when the
/// app starts; `on_change` runs for each batch of changes to the file. The watch lives as long as the process.
pub fn watch_policy_changes(path: &str, on_change: impl Fn() + Send + 'static) {
let path = Path::new(path).to_path_buf();
let folder = path.parent().expect("an absolute policy file path").to_path_buf();
let watched = path.clone();
let watcher = files::watcher::Watcher::new(move |changes| {
if changes.iter().any(|change| change.path == watched) {
on_change();
}
});
let mut watcher = match watcher {
Ok(watcher) => watcher,
Err(error) => return eprintln!("[FilePolicyService] Failed to watch {}: {error}", path.display()),
};
if watcher.watch(0, &folder, false, &[]).is_ok() {
std::mem::forget(watcher);
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::read_policy_file;
#[test]
fn the_policy_file_is_read_as_an_object_and_missing_or_malformed_reads_empty() {
let file = std::env::temp_dir().join(format!("vsrustium-policy-{}.json", std::process::id()));
assert!(read_policy_file(&file).is_empty());
std::fs::write(&file, "[1]").unwrap();
assert!(read_policy_file(&file).is_empty());
std::fs::write(&file, r#"{ "UpdateMode": "none", "Other": [1] }"#).unwrap();
assert_eq!(serde_json::Value::Object(read_policy_file(&file)), json!({ "UpdateMode": "none", "Other": [1] }));
}
}