fix: canonicalize paths

This commit is contained in:
2026-01-31 17:02:11 +08:00
parent db64763d77
commit 0360bbe4aa
2 changed files with 34 additions and 5 deletions

View File

@@ -1,7 +1,38 @@
import { IS_PATH, type NixPath } from "./types"; import { IS_PATH, type NixPath } from "./types";
const canonicalizePath = (path: string): string => {
const parts: string[] = [];
let i = 0;
const len = path.length;
while (i < len) {
while (i < len && path[i] === "/") i++;
if (i >= len) break;
let j = i;
while (j < len && path[j] !== "/") j++;
const component = path.slice(i, j);
i = j;
if (component === ".") {
continue;
} else if (component === "..") {
if (parts.length > 0) {
parts.pop();
}
} else {
parts.push(component);
}
}
if (parts.length === 0) {
return "/";
}
return "/" + parts.join("/");
};
export const mkPath = (value: string): NixPath => { export const mkPath = (value: string): NixPath => {
return { [IS_PATH]: true, value }; return { [IS_PATH]: true, value: canonicalizePath(value) };
}; };
export const getPathValue = (p: NixPath): string => { export const getPathValue = (p: NixPath): string => {

View File

@@ -62,12 +62,10 @@ pub fn nix_base32_decode(input: &str) -> Option<Vec<u8>> {
} }
pub fn decode_hash_to_hex(hash_str: &str) -> Option<String> { pub fn decode_hash_to_hex(hash_str: &str) -> Option<String> {
if hash_str.starts_with("sha256:") { if let Some(rest) = hash_str.strip_prefix("sha256:") {
let rest = &hash_str[7..];
return decode_hash_to_hex(rest); return decode_hash_to_hex(rest);
} }
if hash_str.starts_with("sha256-") { if let Some(base64_str) = hash_str.strip_prefix("sha256-") {
let base64_str = &hash_str[7..];
use base64::{Engine, engine::general_purpose::STANDARD}; use base64::{Engine, engine::general_purpose::STANDARD};
let bytes = STANDARD.decode(base64_str).ok()?; let bytes = STANDARD.decode(base64_str).ok()?;
return Some(hex::encode(bytes)); return Some(hex::encode(bytes));