navid/veins / 83508482911f348af86cb892949a35bdce0d6b2f949b4a0faab7cba9a499fb82 / veinsrs/src/core.rs
core.rs
← veinsrs/src · 25645 bytes · raw · download
use std::collections::BTreeMap;
use std::env;
use std::fs;
use std::io::{Read, Write};
use std::os::unix::ffi::{OsStrExt, OsStringExt};
use std::os::unix::fs::MetadataExt;
use std::path::{Path, PathBuf};
use crate::error::{Error, Result};
pub fn is_flag(argument: &str) -> bool {
!argument.is_empty() && argument.starts_with('-')
}
pub fn trim_str(text: &str) -> &str {
text.trim_matches(|character| {
character == ' ' || character == '\t' || character == '\r' || character == '\n'
})
}
pub fn trim_bytes(text: &[u8]) -> &[u8] {
let mut start = 0;
let mut end = text.len();
while start < end && matches!(text[start], b' ' | b'\t' | b'\r' | b'\n') {
start += 1;
}
while end > start && matches!(text[end - 1], b' ' | b'\t' | b'\r' | b'\n') {
end -= 1;
}
&text[start..end]
}
pub fn path_from_bytes(bytes: &[u8]) -> PathBuf {
PathBuf::from(std::ffi::OsString::from_vec(bytes.to_vec()))
}
pub fn path_to_bytes(path: &Path) -> Vec<u8> {
path.as_os_str().as_bytes().to_vec()
}
pub fn path_display(path: &Path) -> String {
String::from_utf8_lossy(path.as_os_str().as_bytes()).into_owned()
}
pub fn read_file_opt(path: &Path, maximum: u64) -> Option<Vec<u8>> {
let metadata = fs::symlink_metadata(path).ok()?;
if !metadata.is_file() {
return None;
}
if maximum != 0 && metadata.len() > maximum {
return None;
}
let mut file = fs::File::open(path).ok()?;
let mut data = Vec::with_capacity(usize::try_from(metadata.len()).unwrap_or(0));
file.read_to_end(&mut data).ok()?;
Some(data)
}
pub fn read_file_range(path: &Path, offset: u64, length: usize) -> Option<Vec<u8>> {
use std::io::{Seek, SeekFrom};
let mut file = fs::File::open(path).ok()?;
file.seek(SeekFrom::Start(offset)).ok()?;
let mut data = vec![0u8; length];
let mut done = 0;
while done < length {
match file.read(&mut data[done..]) {
Ok(0) => break,
Ok(count) => done += count,
Err(error) if error.kind() == std::io::ErrorKind::Interrupted => continue,
Err(_) => return None,
}
}
data.truncate(done);
Some(data)
}
pub fn read_file(path: &Path, maximum: u64) -> Result<Vec<u8>> {
read_file_opt(path, maximum).ok_or_else(|| Error::io(format!("cannot read {}", path.display())))
}
pub fn write_file(path: &Path, data: &[u8]) -> bool {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
&& fs::create_dir_all(parent).is_err()
{
return false;
}
let mut options = fs::OpenOptions::new();
options.write(true).create(true).truncate(true);
let Ok(mut file) = options.open(path) else {
return false;
};
file.write_all(data).is_ok() && file.flush().is_ok()
}
pub fn append_file(path: &Path, data: &[u8]) -> bool {
if let Some(parent) = path.parent()
&& !parent.as_os_str().is_empty()
&& fs::create_dir_all(parent).is_err()
{
return false;
}
let Ok(mut file) = fs::OpenOptions::new().create(true).append(true).open(path) else {
return false;
};
file.write_all(data).is_ok() && file.flush().is_ok()
}
fn sync_file(path: &Path) -> bool {
use std::os::unix::io::AsRawFd;
let Ok(file) = fs::File::open(path) else {
return false;
};
unsafe { libc::fsync(file.as_raw_fd()) == 0 }
}
fn sync_directory(path: &Path) {
use std::os::unix::io::AsRawFd;
if let Ok(directory) = fs::File::open(path) {
unsafe {
libc::fsync(directory.as_raw_fd());
}
}
}
pub fn write_atomic(tmp_path: &Path, final_path: &Path, data: &[u8]) -> bool {
if let Some(parent) = tmp_path.parent()
&& !parent.as_os_str().is_empty()
&& fs::create_dir_all(parent).is_err()
{
return false;
}
if let Some(parent) = final_path.parent()
&& !parent.as_os_str().is_empty()
&& fs::create_dir_all(parent).is_err()
{
return false;
}
if !write_file(tmp_path, data) {
return false;
}
if !sync_file(tmp_path) {
let _ = fs::remove_file(tmp_path);
return false;
}
if fs::rename(tmp_path, final_path).is_err() {
let _ = fs::remove_file(tmp_path);
return false;
}
if let Some(parent) = final_path.parent() {
sync_directory(parent);
}
true
}
pub fn write_atomic_name(final_path: &Path, data: &[u8]) -> bool {
let parent = final_path.parent().unwrap_or_else(|| Path::new(""));
let name = final_path
.file_name()
.map(|value| value.to_string_lossy().into_owned())
.unwrap_or_default();
let temporary = parent.join(format!(".{name}.tmp.{}", random_u64()));
write_atomic(&temporary, final_path, data)
}
pub fn ensure_directory(path: &Path) -> bool {
fs::create_dir_all(path).is_ok()
}
pub fn remove_file(path: &Path) -> bool {
fs::remove_file(path).is_ok()
}
pub fn remove_tree(path: &Path) -> bool {
fs::remove_dir_all(path).is_ok()
}
pub fn list_directory(path: &Path) -> Vec<Vec<u8>> {
let mut names = Vec::new();
let Ok(entries) = fs::read_dir(path) else {
return names;
};
for entry in entries.flatten() {
names.push(entry.file_name().into_vec());
}
names
}
pub fn same_or_under(child: &Path, parent: &Path) -> bool {
let Ok(child) = fs::canonicalize(child) else {
return false;
};
let Ok(parent) = fs::canonicalize(parent) else {
return false;
};
child.starts_with(parent)
}
pub fn basename_string(path: &Path) -> String {
path.file_name()
.map(|value| value.to_string_lossy().into_owned())
.unwrap_or_default()
}
pub fn path_read_symlink(path: &Path) -> Option<Vec<u8>> {
fs::read_link(path)
.ok()
.map(|target| target.as_os_str().as_bytes().to_vec())
}
#[derive(Clone, Copy)]
pub struct StatInfo {
pub kind: u8,
pub executable: bool,
pub size: u64,
pub mtime_ns: u64,
pub inode: u64,
}
pub fn stat_path(path: &Path) -> Option<StatInfo> {
let metadata = fs::symlink_metadata(path).ok()?;
let file_type = metadata.file_type();
let kind = if file_type.is_symlink() {
3
} else if file_type.is_dir() {
2
} else if file_type.is_file() {
1
} else {
return None;
};
Some(StatInfo {
kind,
executable: metadata.mode() & 0o111 != 0,
size: metadata.size(),
mtime_ns: (metadata.mtime() as u64)
.wrapping_mul(1_000_000_000)
.wrapping_add(metadata.mtime_nsec() as u64),
inode: metadata.ino(),
})
}
pub fn repo_config_value(root: &Path, key: &str) -> Option<String> {
let data = read_file_opt(&root.join(".veins").join("config"), 0)?;
let text = String::from_utf8_lossy(&data);
for raw in text.lines() {
let line = trim_str(raw);
if line.is_empty() || line.starts_with('#') {
continue;
}
let Some((name, value)) = line.split_once('=') else {
continue;
};
if trim_str(name) == key {
return Some(trim_str(value).to_string());
}
}
None
}
fn config_without_key(data: &[u8], key: &str) -> Vec<u8> {
let text = String::from_utf8_lossy(data);
let mut output = String::new();
let lines: Vec<&str> = text.lines().collect();
for (index, raw) in lines.iter().enumerate() {
let line = trim_str(raw);
let mut skip = false;
if !line.is_empty()
&& !line.starts_with('#')
&& let Some((name, _)) = line.split_once('=')
{
skip = trim_str(name) == key;
}
if !skip {
output.push_str(raw);
if index + 1 < lines.len() || text.ends_with('\n') {
output.push('\n');
}
}
}
output.into_bytes()
}
pub fn repo_config_set(root: &Path, key: &str, value: &str) -> bool {
let path = root.join(".veins").join("config");
let mut output = read_file_opt(&path, 0)
.map(|data| config_without_key(&data, key))
.unwrap_or_default();
output.extend_from_slice(key.as_bytes());
output.extend_from_slice(b" = ");
output.extend_from_slice(value.as_bytes());
output.push(b'\n');
write_file(&path, &output)
}
pub fn repo_config_remove(root: &Path, key: &str) -> bool {
let path = root.join(".veins").join("config");
let output = read_file_opt(&path, 0)
.map(|data| config_without_key(&data, key))
.unwrap_or_default();
write_file(&path, &output)
}
pub fn repo_config_bool(root: &Path, key: &str, fallback: bool) -> bool {
let Some(value) = repo_config_value(root, key) else {
return fallback;
};
let value = value.split('#').next().unwrap_or("").trim();
matches!(value, "true" | "1" | "yes" | "on")
}
fn user_config_path() -> Option<PathBuf> {
let home = env::var_os("HOME")?;
if home.is_empty() {
return None;
}
Some(
PathBuf::from(home)
.join(".local")
.join("config")
.join("veins")
.join("veins.toml"),
)
}
fn unquote_toml(raw: &str) -> Option<String> {
let raw = trim_str(raw);
if raw.len() >= 2 {
let first = raw.as_bytes()[0];
let last = raw.as_bytes()[raw.len() - 1];
if (first == b'\'' && last == b'\'') || (first == b'"' && last == b'"') {
let quote = first;
let mut output = String::new();
let bytes = raw.as_bytes();
let mut index = 1;
while index + 1 < bytes.len() {
let byte = bytes[index];
if quote == b'"' && byte == b'\\' && index + 2 < bytes.len() {
match bytes[index + 1] {
b'"' => output.push('"'),
b'\\' => output.push('\\'),
b'n' => output.push('\n'),
b'r' => output.push('\r'),
b't' => output.push('\t'),
other => {
output.push('\\');
output.push(other as char);
}
}
index += 2;
} else {
output.push(byte as char);
index += 1;
}
}
return Some(output);
}
}
if raw.is_empty() {
return None;
}
Some(raw.to_string())
}
fn user_config_full_key(section: &str, key: &str) -> String {
if section.is_empty() {
key.to_string()
} else {
format!("{section}.{key}")
}
}
fn user_config_entries_inner() -> BTreeMap<String, String> {
let mut output = BTreeMap::new();
let Some(path) = user_config_path() else {
return output;
};
let Some(data) = read_file_opt(&path, 0) else {
return output;
};
let text = String::from_utf8_lossy(&data);
let mut section = String::new();
for raw in text.lines() {
let line = trim_str(raw);
if line.is_empty() || line.starts_with('#') {
continue;
}
if let Some(rest) = line.strip_prefix('[') {
if let Some(close) = rest.find(']') {
section = trim_str(&rest[..close]).to_string();
}
continue;
}
let Some((key, value)) = line.split_once('=') else {
continue;
};
let value = value.split('#').next().unwrap_or("");
if let Some(decoded) = unquote_toml(value) {
output.insert(user_config_full_key(§ion, trim_str(key)), decoded);
}
}
output
}
pub fn user_config_entries() -> BTreeMap<String, String> {
user_config_entries_inner()
}
pub fn user_config_value(key: &str) -> Option<String> {
user_config_entries_inner().remove(key)
}
pub fn user_config_author_name() -> Option<String> {
user_config_value("user.name")
}
pub fn user_config_author_email() -> Option<String> {
user_config_value("user.email")
}
fn toml_quote(value: &str) -> String {
let mut output = String::from("\"");
for character in value.chars() {
match character {
'"' => output.push_str("\\\""),
'\\' => output.push_str("\\\\"),
'\n' => output.push_str("\\n"),
'\r' => output.push_str("\\r"),
'\t' => output.push_str("\\t"),
other => output.push(other),
}
}
output.push('"');
output
}
fn update_user_config(key: &str, value: Option<&str>) -> bool {
if key.is_empty() {
return false;
}
let Some(path) = user_config_path() else {
return false;
};
let lines: Vec<String> = read_file_opt(&path, 0)
.map(|data| {
String::from_utf8_lossy(&data)
.lines()
.map(|line| line.to_string())
.collect()
})
.unwrap_or_default();
let mut output = Vec::new();
let mut section = String::new();
for line in lines {
let trimmed = trim_str(&line);
if let Some(rest) = trimmed.strip_prefix('[') {
if let Some(close) = rest.find(']') {
section = trim_str(&rest[..close]).to_string();
}
output.push(line);
continue;
}
let Some((name, _)) = trimmed.split_once('=') else {
output.push(line);
continue;
};
if trimmed.is_empty() || trimmed.starts_with('#') {
output.push(line);
continue;
}
if user_config_full_key(§ion, trim_str(name)) != key {
output.push(line);
}
}
if let Some(value) = value {
output.insert(0, format!("{key} = {}", toml_quote(value)));
} else {
while output.last().is_some_and(|line| trim_str(line).is_empty()) {
output.pop();
}
}
let mut body = output.join("\n");
if !output.is_empty() {
body.push('\n');
}
write_file(&path, body.as_bytes())
}
pub fn user_config_set(key: &str, value: &str) -> bool {
update_user_config(key, Some(value))
}
pub fn user_config_remove(key: &str) -> bool {
update_user_config(key, None)
}
pub fn shell_quote_arg(value: &str) -> String {
let mut output = String::from("'");
for character in value.chars() {
if character == '\'' {
output.push_str("'\\''");
} else {
output.push(character);
}
}
output.push('\'');
output
}
pub fn editor_command(root: &Path) -> String {
for key in ["editor", "core.editor"] {
if let Some(value) = user_config_value(key)
&& !value.is_empty()
{
return value;
}
}
if let Some(value) = repo_config_value(root, "editor")
&& !value.is_empty()
{
return value;
}
for name in ["VN_EDITOR", "VISUAL", "EDITOR"] {
if let Ok(value) = env::var(name)
&& !value.is_empty()
{
return value;
}
}
"vi".to_string()
}
pub fn run_editor(root: &Path, paths: &[String], message_file: Option<&Path>) -> bool {
let mut command = editor_command(root);
for path in paths {
command.push(' ');
command.push_str(&shell_quote_arg(path));
}
if let Some(file) = message_file {
command.push(' ');
command.push_str(&shell_quote_arg(&path_display(file)));
}
std::process::Command::new("sh")
.arg("-c")
.arg(command)
.status()
.is_ok_and(|status| status.success())
}
pub fn stdin_is_terminal() -> bool {
unsafe { libc::isatty(libc::STDIN_FILENO) == 1 }
}
pub fn stdout_is_terminal() -> bool {
unsafe { libc::isatty(libc::STDOUT_FILENO) == 1 }
}
pub fn stderr_is_terminal() -> bool {
unsafe { libc::isatty(libc::STDERR_FILENO) == 1 }
}
pub fn pager_command(root: &Path) -> String {
for key in ["pager", "core.pager"] {
if let Some(value) = user_config_value(key)
&& !value.is_empty()
{
return value;
}
}
if let Some(value) = repo_config_value(root, "pager")
&& !value.is_empty()
{
return value;
}
for name in ["VN_PAGER", "PAGER"] {
if let Ok(value) = env::var(name)
&& !value.is_empty()
{
return value;
}
}
"less -R".to_string()
}
pub fn run_pager(root: &Path, text: &str) -> bool {
if !stdout_is_terminal() {
print!("{text}");
return true;
}
let file = env::temp_dir().join(format!("vn-pager-{}.txt", random_u64()));
if !write_file(&file, text.as_bytes()) {
print!("{text}");
return false;
}
let command = format!(
"{} {}",
pager_command(root),
shell_quote_arg(&path_display(&file))
);
let ok = std::process::Command::new("sh")
.arg("-c")
.arg(command)
.status()
.is_ok_and(|status| status.success());
let _ = fs::remove_file(&file);
if !ok {
print!("{text}");
}
ok
}
pub fn current_bookmark_name(root: &Path) -> Option<String> {
repo_config_value(root, "bookmark.current")
}
pub fn set_current_bookmark(root: &Path, name: &str) -> bool {
if name.is_empty() {
repo_config_remove(root, "bookmark.current")
} else {
repo_config_set(root, "bookmark.current", name)
}
}
pub fn clear_current_bookmark(root: &Path) -> bool {
repo_config_remove(root, "bookmark.current")
}
pub fn random_u64() -> u64 {
let mut value = [0u8; 8];
if let Ok(mut file) = fs::File::open("/dev/urandom")
&& file.read_exact(&mut value).is_ok()
{
return u64::from_le_bytes(value);
}
let mut hasher = blake3::Hasher::new();
hasher.update(&crate::time::now_millis().to_le_bytes());
hasher.update(&std::process::id().to_le_bytes());
hasher.update(format!("{:?}", std::time::Instant::now()).as_bytes());
let digest = hasher.finalize();
let mut bytes = [0u8; 8];
bytes.copy_from_slice(&digest.as_bytes()[..8]);
u64::from_le_bytes(bytes)
}
impl From<std::ffi::OsString> for Error {
fn from(value: std::ffi::OsString) -> Self {
Error::new(value.to_string_lossy())
}
}
#[derive(Clone, Default)]
pub struct IgnoreRule {
pub pattern: String,
pub negated: bool,
pub dir_only: bool,
pub anchored: bool,
pub has_slash: bool,
pub base: String,
}
#[derive(Clone, Default)]
pub struct IgnoreRules {
pub items: Vec<IgnoreRule>,
}
pub fn ignore_empty() -> IgnoreRules {
IgnoreRules::default()
}
fn ignore_add_line(rules: &mut IgnoreRules, base: &str, input: &str) {
let line = trim_str(input);
if line.is_empty() || line.starts_with('#') {
return;
}
let mut negated = false;
let mut start = 0;
if line.starts_with('!') {
negated = true;
start = 1;
}
if start >= line.len() {
return;
}
let bytes = line.as_bytes();
let mut end = bytes.len();
let mut dir_only = false;
if bytes[end - 1] == b'/' {
dir_only = true;
end -= 1;
}
if start >= end {
return;
}
let mut anchored = false;
if bytes[start] == b'/' {
anchored = true;
start += 1;
}
if start >= end {
return;
}
let pattern = &line[start..end];
rules.items.push(IgnoreRule {
pattern: pattern.to_string(),
negated,
dir_only,
anchored,
has_slash: pattern.contains('/'),
base: base.to_string(),
});
}
pub fn ignore_load_file(rules: &mut IgnoreRules, root: &Path, base: &str, name: &str) {
let directory = if base.is_empty() {
root.to_path_buf()
} else {
root.join(base)
};
let Some(data) = read_file_opt(&directory.join(name), 0) else {
return;
};
let text = String::from_utf8_lossy(&data);
for line in text.lines() {
ignore_add_line(rules, base, line);
}
}
pub fn ignore_load_root(rules: &mut IgnoreRules, root: &Path) {
ignore_load_file(rules, root, "", ".vnexclude");
ignore_load_file(rules, root, "", ".gitignore");
}
#[derive(Clone, Copy)]
struct GlobState {
pi: usize,
ti: usize,
}
pub fn glob_match(pattern: &str, text: &str) -> bool {
let pattern = pattern.as_bytes();
let text = text.as_bytes();
const MAX_WORK: usize = 1_000_000;
fn push(stack: &mut Vec<GlobState>, work: &mut usize, state: GlobState) -> bool {
if *work >= MAX_WORK {
return false;
}
*work += 1;
stack.push(state);
true
}
let mut stack = Vec::new();
let mut work = 0usize;
if !push(&mut stack, &mut work, GlobState { pi: 0, ti: 0 }) {
return false;
}
while let Some(state) = stack.pop() {
let p = state.pi;
let t = state.ti;
if p >= pattern.len() {
if t >= text.len() {
return true;
}
continue;
}
let pc = pattern[p];
if pc == b'*' {
let double = p + 1 < pattern.len() && pattern[p + 1] == b'*';
if double {
let next = p + 2;
if next < pattern.len() && pattern[next] == b'/' {
let after = next + 1;
let mut j = t;
loop {
if !push(&mut stack, &mut work, GlobState { pi: after, ti: j }) {
return false;
}
if j >= text.len() {
break;
}
if text[j] == b'/' {
j += 1;
continue;
}
j += 1;
while j < text.len() && text[j] != b'/' {
j += 1;
}
}
} else {
let mut j = t;
loop {
if !push(&mut stack, &mut work, GlobState { pi: next, ti: j }) {
return false;
}
if j >= text.len() {
break;
}
j += 1;
}
}
} else {
let mut j = t;
loop {
if !push(&mut stack, &mut work, GlobState { pi: p + 1, ti: j }) {
return false;
}
if j >= text.len() || text[j] == b'/' {
break;
}
j += 1;
}
}
continue;
}
if t >= text.len() {
continue;
}
if pc == b'?' {
if text[t] != b'/' {
let _ = push(
&mut stack,
&mut work,
GlobState {
pi: p + 1,
ti: t + 1,
},
);
}
continue;
}
if pc == text[t] {
let _ = push(
&mut stack,
&mut work,
GlobState {
pi: p + 1,
ti: t + 1,
},
);
}
}
false
}
fn relative_to<'a>(base: &str, path: &'a str) -> Option<&'a str> {
if base.is_empty() {
return Some(path);
}
if path.len() <= base.len() || !path.starts_with(base) {
return None;
}
if path.as_bytes()[base.len()] != b'/' {
return None;
}
Some(&path[base.len() + 1..])
}
fn rule_matches(rule: &IgnoreRule, path: &str, is_dir: bool) -> bool {
let Some(relative) = relative_to(&rule.base, path) else {
return false;
};
if relative.is_empty() || (rule.dir_only && !is_dir) {
return false;
}
if !rule.has_slash && !rule.anchored {
let mut start = 0;
loop {
let end = relative[start..]
.find('/')
.map(|offset| start + offset)
.unwrap_or(relative.len());
if glob_match(&rule.pattern, &relative[start..end]) {
return true;
}
if end >= relative.len() {
break;
}
start = end + 1;
}
return false;
}
glob_match(&rule.pattern, relative)
}
pub fn ignore_ignored(rules: &IgnoreRules, path: &str, is_dir: bool) -> bool {
let mut ignored = false;
for rule in &rules.items {
if rule_matches(rule, path, is_dir) {
ignored = !rule.negated;
}
}
ignored
}
pub fn ignore_path_ignored(root: &Path, path: &str) -> bool {
let mut rules = ignore_empty();
ignore_load_root(&mut rules, root);
for (index, byte) in path.bytes().enumerate() {
if byte == b'/' {
let base = &path[..index];
ignore_load_file(&mut rules, root, base, ".vnexclude");
ignore_load_file(&mut rules, root, base, ".gitignore");
}
}
for (index, byte) in path.bytes().enumerate() {
if byte == b'/' && ignore_ignored(&rules, &path[..index], true) {
return true;
}
}
ignore_ignored(&rules, path, false)
}