pikopiko-cli 0.1.0

Command-line tool and MCP server to check, inspect, render and play MML with pikopiko.
Documentation
//! `file:` の URI とファイルのパスの変換。
//!
//! LSP は文書を URI で指す。`#include` をファイルのあるフォルダーから読むのと、定義へ移動で読み込んだ
//! ファイルを指すのに、パスとの行き来が要る。`lsp-types` の `Uri` は URI の形を確かめるだけで
//! パスへの変換を持たないので、ここで行う(Windows のドライブ `file:///C:/…` と、`%` の符号化に対応)。

use std::path::{Path, PathBuf};
use std::str::FromStr;

use lsp_types::Uri;

/// `file:` の URI のパス。ほかの形(`untitled:` など)や読めない URI は `None`。
pub(super) fn uri_to_path(uri: &Uri) -> Option<PathBuf> {
    let s = uri.as_str();
    let rest = s.strip_prefix("file://")?;
    // `file://host/path` のホストは使わない(`file:///path` のホストは空)
    let path = &rest[rest.find('/')?..];
    let decoded = percent_decode(path)?;
    // Windows のドライブ(`/C:/x` → `C:/x`)
    let b = decoded.as_bytes();
    let decoded = if b.len() >= 3 && b[0] == b'/' && b[1].is_ascii_alphabetic() && b[2] == b':' {
        decoded[1..].to_string()
    } else {
        decoded
    };
    Some(PathBuf::from(decoded))
}

/// パスの `file:` の URI。
pub(super) fn path_to_uri(path: &Path) -> Option<Uri> {
    let s = path.to_str()?.replace('\\', "/");
    let s = if s.starts_with('/') {
        s
    } else {
        format!("/{s}")
    };
    let mut out = String::from("file://");
    for b in s.bytes() {
        if b.is_ascii_alphanumeric() || b"/-._~:".contains(&b) {
            out.push(b as char);
        } else {
            out.push_str(&format!("%{b:02X}"));
        }
    }
    Uri::from_str(&out).ok()
}

fn percent_decode(s: &str) -> Option<String> {
    let b = s.as_bytes();
    let mut out = Vec::with_capacity(b.len());
    let mut i = 0;
    while i < b.len() {
        if b[i] == b'%' {
            let h = std::str::from_utf8(b.get(i + 1..i + 3)?).ok()?;
            out.push(u8::from_str_radix(h, 16).ok()?);
            i += 3;
        } else {
            out.push(b[i]);
            i += 1;
        }
    }
    String::from_utf8(out).ok()
}