From 6b48da8485ff79f481f42e0d91d793206b0f97e2 Mon Sep 17 00:00:00 2001 From: goenning Date: Sat, 30 Nov 2024 17:08:38 +0000 Subject: [PATCH] support for utf16 files Signed-off-by: goenning --- kube-client/src/config/file_config.rs | 33 ++++++++++++++++++++++++--- 1 file changed, 30 insertions(+), 3 deletions(-) diff --git a/kube-client/src/config/file_config.rs b/kube-client/src/config/file_config.rs index dd41cc5db..698ae2ca7 100644 --- a/kube-client/src/config/file_config.rs +++ b/kube-client/src/config/file_config.rs @@ -1,6 +1,6 @@ use std::{ collections::HashMap, - fs, + fs, io, path::{Path, PathBuf}, }; @@ -351,8 +351,8 @@ const KUBECONFIG: &str = "KUBECONFIG"; impl Kubeconfig { /// Read a Config from an arbitrary location pub fn read_from>(path: P) -> Result { - let data = fs::read_to_string(&path) - .map_err(|source| KubeconfigError::ReadConfig(source, path.as_ref().into()))?; + let data = + read_path(&path).map_err(|source| KubeconfigError::ReadConfig(source, path.as_ref().into()))?; // Remap all files we read to absolute paths. let mut merged_docs = None; @@ -497,6 +497,33 @@ where }); } +fn read_path>(path: P) -> io::Result { + let bytes = fs::read(&path)?; + match bytes.as_slice() { + [0xFF, 0xFE, ..] => { + let utf16_data: Vec = bytes[2..] + .chunks(2) + .map(|chunk| u16::from_le_bytes([chunk[0], chunk[1]])) + .collect(); + String::from_utf16(&utf16_data) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-16 LE")) + } + [0xFE, 0xFF, ..] => { + let utf16_data: Vec = bytes[2..] + .chunks(2) + .map(|chunk| u16::from_be_bytes([chunk[0], chunk[1]])) + .collect(); + String::from_utf16(&utf16_data) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-16 BE")) + } + [0xEF, 0xBB, 0xBF, ..] => String::from_utf8(bytes[3..].to_vec()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8 BOM")), + _ => { + String::from_utf8(bytes).map_err(|_| io::Error::new(io::ErrorKind::InvalidData, "Invalid UTF-8")) + } + } +} + fn to_absolute(dir: &Path, file: &str) -> Option { let path = Path::new(&file); if path.is_relative() {