| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
use crate::attest::{Attest, AttestBody}; |
| 11 |
use crate::diff::{ranges, split_lines, text_edits}; |
| 12 |
use crate::protocol::{open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef, SignedAttest, SignedPolicy}; |
| 13 |
use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType}; |
| 14 |
use crate::identity::{verify as verify_signature, Domain, Identity, SecretKey, Signature}; |
| 15 |
use crate::ids::{ChangeId, NodeId, WorkspaceId}; |
| 16 |
use crate::objects::{Blob, Change, ChangeKind, Edit, Hlc, Mode, NodeKind, OpRef, StateObject, TreeOp}; |
| 17 |
use crate::oplog::{Format1Op, Op, View, SNAPSHOT_SUFFIX}; |
| 18 |
use crate::state::{FileContent, Snapshot, State}; |
| 19 |
use crate::store::{Store, StoreError}; |
| 20 |
use crate::tree::OpKey; |
| 21 |
use rand::RngCore; |
| 22 |
use std::collections::{BTreeMap, BTreeSet, HashMap}; |
| 23 |
use std::fs; |
| 24 |
use std::io::Write; |
| 25 |
use std::path::{Path, PathBuf}; |
| 26 |
|
| 27 |
pub const OXY_DIR: &str = ".oxy"; |
| 28 |
pub const FORMAT_LINE: &str = "oxy repository format 2\n"; |
| 29 |
const FORMAT1_LINE: &str = "oxy repository format 1\n"; |
| 30 |
const BINARY_SNIFF: usize = 8 * 1024; |
| 31 |
|
| 32 |
pub const AUTOPACK_THRESHOLD: usize = 4096; |
| 33 |
|
| 34 |
#[derive(Debug, thiserror::Error)] |
| 35 |
pub enum RepoError { |
| 36 |
#[error("io: {0}")] |
| 37 |
Io(#[from] std::io::Error), |
| 38 |
#[error(transparent)] |
| 39 |
Store(#[from] StoreError), |
| 40 |
#[error(transparent)] |
| 41 |
Object(#[from] crate::objects::ObjectError), |
| 42 |
#[error(transparent)] |
| 43 |
State(#[from] crate::state::StateError), |
| 44 |
#[error("{0}")] |
| 45 |
Msg(String), |
| 46 |
} |
| 47 |
|
| 48 |
pub type Result<T> = std::result::Result<T, RepoError>; |
| 49 |
|
| 50 |
fn fail<T>(s: impl Into<String>) -> Result<T> { |
| 51 |
Err(RepoError::Msg(s.into())) |
| 52 |
} |
| 53 |
|
| 54 |
mod checkout; |
| 55 |
mod config; |
| 56 |
mod gc; |
| 57 |
mod git; |
| 58 |
mod history; |
| 59 |
mod identity; |
| 60 |
mod policy; |
| 61 |
mod snapshot; |
| 62 |
mod sync; |
| 63 |
#[cfg(test)] |
| 64 |
mod tests; |
| 65 |
|
| 66 |
pub use checkout::CheckoutReport; |
| 67 |
pub use config::{read_config_file, Config}; |
| 68 |
pub use gc::GcReport; |
| 69 |
pub use git::{GitExportReport, GitImportReport}; |
| 70 |
pub use identity::SignatureStatus; |
| 71 |
pub use snapshot::{added_node_paths, has_conflict_markers, is_binary, referenced_changes, render_change, ChangeStatus, PathStatus, SnapshotResult}; |
| 72 |
pub use sync::{FetchReport, PullReport}; |
| 73 |
|
| 74 |
fn write_atomic(path: &Path, data: &[u8]) -> Result<()> { |
| 75 |
let tmp = path.with_extension("tmp"); |
| 76 |
{ |
| 77 |
let mut f = fs::File::create(&tmp)?; |
| 78 |
f.write_all(data)?; |
| 79 |
f.sync_all()?; |
| 80 |
} |
| 81 |
fs::rename(&tmp, path)?; |
| 82 |
Ok(()) |
| 83 |
} |
| 84 |
|
| 85 |
pub struct LogEntry { |
| 86 |
pub hash: ChangeHash, |
| 87 |
pub change: Change, |
| 88 |
pub is_working_copy: bool, |
| 89 |
pub is_head: bool, |
| 90 |
} |
| 91 |
|
| 92 |
|
| 93 |
pub(crate) struct FsEntry { |
| 94 |
pub kind: NodeKind, |
| 95 |
pub exec: bool, |
| 96 |
|
| 97 |
pub content: Vec<u8>, |
| 98 |
} |
| 99 |
|
| 100 |
pub struct Repo { |
| 101 |
root: PathBuf, |
| 102 |
oxy: PathBuf, |
| 103 |
store: Store, |
| 104 |
workspace: WorkspaceId, |
| 105 |
keys_dir: PathBuf, |
| 106 |
user_config: PathBuf, |
| 107 |
pub config: Config, |
| 108 |
} |
| 109 |
|
| 110 |
|
| 111 |
|
| 112 |
pub fn default_home() -> PathBuf { |
| 113 |
if let Ok(h) = std::env::var("OXY_HOME") { |
| 114 |
return PathBuf::from(h); |
| 115 |
} |
| 116 |
if let Ok(x) = std::env::var("XDG_CONFIG_HOME") { |
| 117 |
return PathBuf::from(x).join("oxy"); |
| 118 |
} |
| 119 |
let home = std::env::var("HOME").unwrap_or_else(|_| ".".into()); |
| 120 |
PathBuf::from(home).join(".config").join("oxy") |
| 121 |
} |
| 122 |
|
| 123 |
pub fn default_keys_dir() -> PathBuf { |
| 124 |
default_home().join("keys") |
| 125 |
} |
| 126 |
|
| 127 |
pub fn default_user_config() -> PathBuf { |
| 128 |
default_home().join("config.toml") |
| 129 |
} |
| 130 |
|
| 131 |
|
| 132 |
#[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 133 |
pub enum IdentityScope { |
| 134 |
|
| 135 |
User, |
| 136 |
|
| 137 |
Repo, |
| 138 |
} |
| 139 |
|
| 140 |
impl Repo { |
| 141 |
|
| 142 |
|
| 143 |
pub fn init(root: &Path) -> Result<Repo> { |
| 144 |
let mut id = [0u8; 16]; |
| 145 |
rand::rngs::OsRng.fill_bytes(&mut id); |
| 146 |
Self::init_with_id(root, id) |
| 147 |
} |
| 148 |
|
| 149 |
|
| 150 |
|
| 151 |
pub fn init_with_id(root: &Path, id: [u8; 16]) -> Result<Repo> { |
| 152 |
fs::create_dir_all(root)?; |
| 153 |
let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf()); |
| 154 |
let oxy = root.join(OXY_DIR); |
| 155 |
if oxy.exists() { |
| 156 |
return fail(format!("{} is already an oxy repository", root.display())); |
| 157 |
} |
| 158 |
fs::create_dir_all(oxy.join("ops"))?; |
| 159 |
write_atomic(&oxy.join("format"), FORMAT_LINE.as_bytes())?; |
| 160 |
write_atomic(&oxy.join("id"), hex::encode(id).as_bytes())?; |
| 161 |
let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?; |
| 162 |
config.save(&oxy.join("config"))?; |
| 163 |
let workspace = WorkspaceId::random(); |
| 164 |
write_atomic(&oxy.join("workspace"), workspace.to_hex().as_bytes())?; |
| 165 |
let store = Store::open(oxy.join("objects"))?; |
| 166 |
let repo = Repo { root, oxy, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config }; |
| 167 |
|
| 168 |
let wc = repo.new_working_copy(vec![], ""); |
| 169 |
let wc_hash = repo.store.put_change(&wc)?; |
| 170 |
let mut view = View::default(); |
| 171 |
view.bookmarks.insert(repo.config.bookmark.clone(), repo.store.put_state(&StateObject::new(vec![]))?); |
| 172 |
view.workspaces.insert(workspace, wc_hash); |
| 173 |
repo.record_op(&[], "oxy init", view)?; |
| 174 |
Ok(repo) |
| 175 |
} |
| 176 |
|
| 177 |
|
| 178 |
pub fn open(start: &Path) -> Result<Repo> { |
| 179 |
let start = start.canonicalize()?; |
| 180 |
let mut dir: Option<&Path> = Some(&start); |
| 181 |
while let Some(d) = dir { |
| 182 |
let oxy = d.join(OXY_DIR); |
| 183 |
if oxy.is_dir() { |
| 184 |
let format = fs::read_to_string(oxy.join("format"))?; |
| 185 |
let config = Config::load(Some(&default_user_config()), &oxy.join("config"))?; |
| 186 |
let workspace = WorkspaceId::from_hex(fs::read_to_string(oxy.join("workspace"))?.trim()) |
| 187 |
.ok_or_else(|| RepoError::Msg("corrupt .oxy/workspace".into()))?; |
| 188 |
let store = Store::open(oxy.join("objects"))?; |
| 189 |
let repo = Repo { root: d.to_path_buf(), oxy, store, workspace, keys_dir: default_keys_dir(), user_config: default_user_config(), config }; |
| 190 |
if format == FORMAT1_LINE { |
| 191 |
repo.migrate_format1()?; |
| 192 |
} else if format != FORMAT_LINE { |
| 193 |
return fail(format!("unsupported repository format: {}", format.trim())); |
| 194 |
} |
| 195 |
return Ok(repo); |
| 196 |
} |
| 197 |
dir = d.parent(); |
| 198 |
} |
| 199 |
fail(format!("no oxy repository found at or above {}", start.display())) |
| 200 |
} |
| 201 |
|
| 202 |
|
| 203 |
|
| 204 |
fn migrate_format1(&self) -> Result<()> { |
| 205 |
let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?; |
| 206 |
let head = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?; |
| 207 |
|
| 208 |
let mut chain: Vec<Format1Op> = Vec::new(); |
| 209 |
let mut cur = Some(head); |
| 210 |
while let Some(r) = cur { |
| 211 |
let op = Op::decode_format1(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 212 |
cur = op.parents.first().copied(); |
| 213 |
chain.push(op); |
| 214 |
} |
| 215 |
chain.reverse(); |
| 216 |
let mut new_parent: Option<ObjectRef> = None; |
| 217 |
for old in chain { |
| 218 |
let mut view = View::default(); |
| 219 |
for (name, heads) in &old.view.bookmarks { |
| 220 |
view.bookmarks.insert(name.clone(), self.store.put_state(&StateObject::new(heads.clone()))?); |
| 221 |
} |
| 222 |
view.workspaces = old.view.workspaces.clone(); |
| 223 |
let op = Op { parents: new_parent.into_iter().collect(), hlc: old.hlc, command: old.command, view }; |
| 224 |
new_parent = Some(self.store.put(ObjectType::Op, &op.encode())?); |
| 225 |
} |
| 226 |
write_atomic(&self.oxy.join("ops").join("head"), new_parent.unwrap().to_hex().as_bytes())?; |
| 227 |
write_atomic(&self.oxy.join("format"), FORMAT_LINE.as_bytes())?; |
| 228 |
Ok(()) |
| 229 |
} |
| 230 |
|
| 231 |
|
| 232 |
pub(crate) fn maybe_autopack(&self) -> Result<()> { |
| 233 |
if self.store.loose_count()? > AUTOPACK_THRESHOLD { |
| 234 |
self.store.pack_loose()?; |
| 235 |
} |
| 236 |
Ok(()) |
| 237 |
} |
| 238 |
|
| 239 |
|
| 240 |
pub fn id(&self) -> Result<[u8; 16]> { |
| 241 |
let path = self.oxy.join("id"); |
| 242 |
match fs::read_to_string(&path) { |
| 243 |
Ok(h) => hex::decode(h.trim()).ok().and_then(|v| v.try_into().ok()).ok_or_else(|| RepoError::Msg("corrupt .oxy/id".into())), |
| 244 |
Err(e) if e.kind() == std::io::ErrorKind::NotFound => { |
| 245 |
let mut id = [0u8; 16]; |
| 246 |
rand::rngs::OsRng.fill_bytes(&mut id); |
| 247 |
write_atomic(&path, hex::encode(id).as_bytes())?; |
| 248 |
Ok(id) |
| 249 |
} |
| 250 |
Err(e) => Err(e.into()), |
| 251 |
} |
| 252 |
} |
| 253 |
|
| 254 |
pub fn root(&self) -> &Path { |
| 255 |
&self.root |
| 256 |
} |
| 257 |
pub fn store(&self) -> &Store { |
| 258 |
&self.store |
| 259 |
} |
| 260 |
pub fn workspace(&self) -> WorkspaceId { |
| 261 |
self.workspace |
| 262 |
} |
| 263 |
|
| 264 |
|
| 265 |
|
| 266 |
pub fn with_home(mut self, dir: impl Into<PathBuf>) -> Repo { |
| 267 |
let dir = dir.into(); |
| 268 |
self.keys_dir = dir.join("keys"); |
| 269 |
self.user_config = dir.join("config.toml"); |
| 270 |
if let Ok(c) = Config::load(Some(&self.user_config), &self.oxy.join("config")) { |
| 271 |
self.config = c; |
| 272 |
} |
| 273 |
self |
| 274 |
} |
| 275 |
|
| 276 |
pub fn user_config_path(&self) -> &Path { |
| 277 |
&self.user_config |
| 278 |
} |
| 279 |
|
| 280 |
|
| 281 |
pub fn set_user_config(&mut self, key: &str, value: &str) -> Result<()> { |
| 282 |
Config::set_user(&self.user_config, key, value)?; |
| 283 |
self.config = Config::load(Some(&self.user_config), &self.oxy.join("config"))?; |
| 284 |
Ok(()) |
| 285 |
} |
| 286 |
|
| 287 |
pub fn save_config(&self) -> Result<()> { |
| 288 |
self.config.save(&self.oxy.join("config")) |
| 289 |
} |
| 290 |
|
| 291 |
fn author(&self) -> KeyId { |
| 292 |
self.config.author_key.unwrap_or(ObjectRef::ZERO) |
| 293 |
} |
| 294 |
} |
| 295 |
|
| 296 |
impl Repo { |
| 297 |
fn new_working_copy(&self, deps: Vec<ChangeHash>, message: &str) -> Change { |
| 298 |
let mut c = Change { |
| 299 |
change_id: ChangeId::random(), |
| 300 |
deps, |
| 301 |
author: self.author(), |
| 302 |
hlc: Hlc::now(), |
| 303 |
message: message.into(), |
| 304 |
tree_ops: vec![], |
| 305 |
edits: vec![], |
| 306 |
kind: ChangeKind::WorkingCopy, |
| 307 |
}; |
| 308 |
c.normalize(); |
| 309 |
c |
| 310 |
} |
| 311 |
|
| 312 |
|
| 313 |
|
| 314 |
pub fn head_op(&self) -> Result<(ObjectRef, Op)> { |
| 315 |
let hex = fs::read_to_string(self.oxy.join("ops").join("head"))?; |
| 316 |
let r = ObjectRef::from_hex(hex.trim()).ok_or_else(|| RepoError::Msg("corrupt .oxy/ops/head".into()))?; |
| 317 |
let op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 318 |
Ok((r, op)) |
| 319 |
} |
| 320 |
|
| 321 |
pub fn view(&self) -> Result<View> { |
| 322 |
Ok(self.head_op()?.1.view) |
| 323 |
} |
| 324 |
|
| 325 |
fn record_op(&self, parents: &[ObjectRef], command: &str, view: View) -> Result<ObjectRef> { |
| 326 |
let op = Op { parents: parents.to_vec(), hlc: Hlc::now(), command: command.into(), view }; |
| 327 |
let r = self.store.put(ObjectType::Op, &op.encode())?; |
| 328 |
write_atomic(&self.oxy.join("ops").join("head"), r.to_hex().as_bytes())?; |
| 329 |
Ok(r) |
| 330 |
} |
| 331 |
|
| 332 |
pub fn op_log(&self) -> Result<Vec<(ObjectRef, Op)>> { |
| 333 |
let mut out = Vec::new(); |
| 334 |
let (mut r, mut op) = self.head_op()?; |
| 335 |
loop { |
| 336 |
let next = op.parents.first().copied(); |
| 337 |
out.push((r, op)); |
| 338 |
match next { |
| 339 |
Some(p) => { |
| 340 |
r = p; |
| 341 |
op = Op::decode(&self.store.get_typed(&r, ObjectType::Op)?)?; |
| 342 |
} |
| 343 |
None => break, |
| 344 |
} |
| 345 |
} |
| 346 |
Ok(out) |
| 347 |
} |
| 348 |
|
| 349 |
|
| 350 |
|
| 351 |
|
| 352 |
pub fn undo(&self) -> Result<Op> { |
| 353 |
let (_, mut op) = self.head_op()?; |
| 354 |
while op.is_snapshot() { |
| 355 |
let Some(parent) = op.parents.first() else { break }; |
| 356 |
op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?; |
| 357 |
} |
| 358 |
let Some(parent) = op.parents.first() else { |
| 359 |
return fail("nothing to undo"); |
| 360 |
}; |
| 361 |
let parent_op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?; |
| 362 |
write_atomic(&self.oxy.join("ops").join("head"), parent.to_hex().as_bytes())?; |
| 363 |
Ok(parent_op) |
| 364 |
} |
| 365 |
|
| 366 |
|
| 367 |
pub fn last_command(&self) -> Result<Op> { |
| 368 |
let (_, mut op) = self.head_op()?; |
| 369 |
while op.is_snapshot() { |
| 370 |
let Some(parent) = op.parents.first() else { break }; |
| 371 |
op = Op::decode(&self.store.get_typed(parent, ObjectType::Op)?)?; |
| 372 |
} |
| 373 |
Ok(op) |
| 374 |
} |
| 375 |
|
| 376 |
|
| 377 |
|
| 378 |
|
| 379 |
pub fn load_state(&self, heads: &[ChangeHash]) -> Result<State> { |
| 380 |
let mut state = State::new(); |
| 381 |
let mut stack: Vec<ChangeHash> = heads.to_vec(); |
| 382 |
let mut seen: BTreeSet<ChangeHash> = BTreeSet::new(); |
| 383 |
while let Some(h) = stack.pop() { |
| 384 |
if !seen.insert(h) { |
| 385 |
continue; |
| 386 |
} |
| 387 |
let c = self.store.get_change(&h)?; |
| 388 |
stack.extend(c.deps.iter().copied()); |
| 389 |
state.add_unchecked(c); |
| 390 |
} |
| 391 |
state.validate()?; |
| 392 |
Ok(state) |
| 393 |
} |
| 394 |
|
| 395 |
pub fn working_copy(&self) -> Result<(ChangeHash, Change)> { |
| 396 |
let view = self.view()?; |
| 397 |
let h = *view |
| 398 |
.workspaces |
| 399 |
.get(&self.workspace) |
| 400 |
.ok_or_else(|| RepoError::Msg("this workspace is not in the current view".into()))?; |
| 401 |
Ok((h, self.store.get_change(&h)?)) |
| 402 |
} |
| 403 |
|
| 404 |
|
| 405 |
pub fn heads_of(&self, view: &View, bookmark: &str) -> Result<Vec<ChangeHash>> { |
| 406 |
match view.bookmarks.get(bookmark) { |
| 407 |
Some(st) => Ok(self.store.get_state(st)?.heads), |
| 408 |
None => Ok(vec![]), |
| 409 |
} |
| 410 |
} |
| 411 |
|
| 412 |
pub fn bookmark_heads(&self) -> Result<Vec<ChangeHash>> { |
| 413 |
self.heads_of(&self.view()?, &self.config.bookmark) |
| 414 |
} |
| 415 |
|
| 416 |
|
| 417 |
|
| 418 |
fn blob_for(content: &[u8]) -> Blob { |
| 419 |
Blob { |
| 420 |
length: content.len() as u64, |
| 421 |
chunks: crate::chunk::chunks(content).into_iter().map(|c| hash_object(ObjectType::Chunk, c)).collect(), |
| 422 |
} |
| 423 |
} |
| 424 |
|
| 425 |
pub fn blob_ref(content: &[u8]) -> ObjectRef { |
| 426 |
Self::blob_for(content).hash() |
| 427 |
} |
| 428 |
|
| 429 |
pub fn store_blob(&self, content: &[u8]) -> Result<ObjectRef> { |
| 430 |
for c in crate::chunk::chunks(content) { |
| 431 |
self.store.put_chunk(c)?; |
| 432 |
} |
| 433 |
Ok(self.store.put(ObjectType::Blob, &Self::blob_for(content).encode())?) |
| 434 |
} |
| 435 |
|
| 436 |
pub fn read_blob(&self, r: &ObjectRef) -> Result<Vec<u8>> { |
| 437 |
let blob = Blob::decode(&self.store.get_typed(r, ObjectType::Blob)?)?; |
| 438 |
let mut out = Vec::with_capacity(blob.length as usize); |
| 439 |
for c in &blob.chunks { |
| 440 |
out.extend(self.store.get_typed(c, ObjectType::Chunk)?); |
| 441 |
} |
| 442 |
Ok(out) |
| 443 |
} |
| 444 |
|
| 445 |
|
| 446 |
|
| 447 |
fn walk_working_copy(&self) -> Result<BTreeMap<String, FsEntry>> { |
| 448 |
let mut wb = ignore::WalkBuilder::new(&self.root); |
| 449 |
wb.hidden(false) |
| 450 |
.git_ignore(false) |
| 451 |
.git_global(false) |
| 452 |
.git_exclude(false) |
| 453 |
.require_git(false) |
| 454 |
.follow_links(false) |
| 455 |
.add_custom_ignore_filename(".oxyignore"); |
| 456 |
wb.filter_entry(|e| e.file_name() != OXY_DIR); |
| 457 |
let mut out = BTreeMap::new(); |
| 458 |
for entry in wb.build() { |
| 459 |
let entry = entry.map_err(|e| RepoError::Msg(e.to_string()))?; |
| 460 |
let path = entry.path(); |
| 461 |
if path == self.root { |
| 462 |
continue; |
| 463 |
} |
| 464 |
let rel = path.strip_prefix(&self.root).unwrap(); |
| 465 |
let rel: String = rel.components().map(|c| c.as_os_str().to_string_lossy().to_string()).collect::<Vec<_>>().join("/"); |
| 466 |
let Some(ft) = entry.file_type() else { continue }; |
| 467 |
if ft.is_dir() { |
| 468 |
continue; |
| 469 |
} |
| 470 |
if ft.is_symlink() { |
| 471 |
let target = fs::read_link(path)?; |
| 472 |
out.insert(rel, FsEntry { kind: NodeKind::Symlink, exec: false, content: target.to_string_lossy().as_bytes().to_vec() }); |
| 473 |
} else if ft.is_file() { |
| 474 |
let exec = is_executable(&entry.metadata().map_err(|e| RepoError::Msg(e.to_string()))?); |
| 475 |
out.insert(rel, FsEntry { kind: NodeKind::File, exec, content: fs::read(path)? }); |
| 476 |
} |
| 477 |
} |
| 478 |
Ok(out) |
| 479 |
} |
| 480 |
} |
| 481 |
|
| 482 |
impl Repo { |
| 483 |
|
| 484 |
pub fn log(&self) -> Result<Vec<LogEntry>> { |
| 485 |
let (wc_hash, _) = self.working_copy()?; |
| 486 |
let mut heads = self.bookmark_heads()?; |
| 487 |
heads.push(wc_hash); |
| 488 |
let state = self.load_state(&heads)?; |
| 489 |
let head_set: BTreeSet<ChangeHash> = self.bookmark_heads()?.into_iter().collect(); |
| 490 |
let mut entries: Vec<LogEntry> = state |
| 491 |
.changes() |
| 492 |
.map(|(h, c)| LogEntry { hash: *h, change: c.clone(), is_working_copy: *h == wc_hash, is_head: head_set.contains(h) }) |
| 493 |
.collect(); |
| 494 |
entries.sort_by(|a, b| b.is_working_copy.cmp(&a.is_working_copy).then(b.change.hlc.cmp(&a.change.hlc)).then(b.hash.cmp(&a.hash))); |
| 495 |
Ok(entries) |
| 496 |
} |
| 497 |
|
| 498 |
|
| 499 |
pub fn resolve_change(&self, spec: &str) -> Result<ChangeHash> { |
| 500 |
if spec == "@" { |
| 501 |
return Ok(self.working_copy()?.0); |
| 502 |
} |
| 503 |
if spec.is_empty() || spec == "#" { |
| 504 |
return fail("empty change specifier"); |
| 505 |
} |
| 506 |
let entries = self.log()?; |
| 507 |
let matches: Vec<&LogEntry> = if let Some(hp) = spec.strip_prefix('#') { |
| 508 |
entries.iter().filter(|e| e.hash.starts_with_hex(hp)).collect() |
| 509 |
} else { |
| 510 |
entries.iter().filter(|e| e.change.change_id.starts_with_hex(spec)).collect() |
| 511 |
}; |
| 512 |
match matches.len() { |
| 513 |
1 => Ok(matches[0].hash), |
| 514 |
0 => fail(format!("no change matches {spec:?}")), |
| 515 |
_ => { |
| 516 |
let ids: BTreeSet<ChangeId> = matches.iter().map(|e| e.change.change_id).collect(); |
| 517 |
if ids.len() == 1 { |
| 518 |
fail(format!("change {spec} is divergent: {} variants", matches.len())) |
| 519 |
} else { |
| 520 |
fail(format!("{spec:?} is ambiguous")) |
| 521 |
} |
| 522 |
} |
| 523 |
} |
| 524 |
} |
| 525 |
|
| 526 |
|
| 527 |
pub fn describe_change(&self, hash: &ChangeHash) -> Result<String> { |
| 528 |
let change = self.store.get_change(hash)?; |
| 529 |
let base = self.load_state(&change.deps)?; |
| 530 |
let base_snapshot = base.materialize(); |
| 531 |
Ok(render_change(&change, &base, &base_snapshot)) |
| 532 |
} |
| 533 |
} |
| 534 |
|
| 535 |
fn remove_any(path: &Path) -> std::io::Result<()> { |
| 536 |
let m = fs::symlink_metadata(path)?; |
| 537 |
if m.is_dir() { fs::remove_dir_all(path) } else { fs::remove_file(path) } |
| 538 |
} |
| 539 |
|
| 540 |
#[cfg(unix)] |
| 541 |
fn set_executable(path: &Path, exec: bool) -> std::io::Result<()> { |
| 542 |
use std::os::unix::fs::PermissionsExt; |
| 543 |
let mut perms = fs::metadata(path)?.permissions(); |
| 544 |
let mode = perms.mode(); |
| 545 |
let want = if exec { mode | 0o111 } else { mode & !0o111 }; |
| 546 |
if want != mode { |
| 547 |
perms.set_mode(want); |
| 548 |
fs::set_permissions(path, perms)?; |
| 549 |
} |
| 550 |
Ok(()) |
| 551 |
} |
| 552 |
#[cfg(not(unix))] |
| 553 |
fn set_executable(_path: &Path, _exec: bool) -> std::io::Result<()> { |
| 554 |
Ok(()) |
| 555 |
} |
| 556 |
|
| 557 |
#[cfg(unix)] |
| 558 |
fn is_executable(m: &fs::Metadata) -> bool { |
| 559 |
use std::os::unix::fs::PermissionsExt; |
| 560 |
m.permissions().mode() & 0o111 != 0 |
| 561 |
} |
| 562 |
#[cfg(not(unix))] |
| 563 |
fn is_executable(_m: &fs::Metadata) -> bool { |
| 564 |
false |
| 565 |
} |
| 566 |
|
| 567 |
fn op_ref(k: OpKey) -> OpRef { |
| 568 |
OpRef { change: k.0, index: k.1 } |
| 569 |
} |
| 570 |
|
| 571 |
fn split_path(path: &str) -> (&str, &str) { |
| 572 |
match path.rfind('/') { |
| 573 |
Some(i) => (&path[..i], &path[i + 1..]), |
| 574 |
None => ("", path), |
| 575 |
} |
| 576 |
} |