98286406 Andy McCall 1 month ago ↶
1
2
3
83e0677b Andy McCall 1 month ago ↶
4
5
6
7
98286406 Andy McCall 1 month ago ↶
8
9
10
use crate :: attest:: { Attest, AttestBody} ;
11
use crate :: diff:: { ranges, split_lines, text_edits} ;
83e0677b Andy McCall 1 month ago ↶
12
use crate :: protocol:: { open_remote, Bundle, RefResult, RefUpdate, RefsResponse, RemoteOptions, RemoteRef, SignedAttest, SignedPolicy} ;
98286406 Andy McCall 1 month ago ↶
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 ;
d02e545d Andy McCall 1 month ago ↶
31
32
pub const AUTOPACK_THRESHOLD : usize = 4096 ;
98286406 Andy McCall 1 month ago ↶
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 ;
252e8cb2 Andy McCall 1 month ago ↶
55
mod checkpoint ;
98286406 Andy McCall 1 month ago ↶
56
mod config ;
ba160f60 Andy McCall 1 month ago ↶
57
mod gc ;
79ab8528 Andy McCall 1 month ago ↶
58
mod git ;
614541c3 Andy McCall 1 month ago ↶
59
mod history ;
6d3eefbc Andy McCall 1 month ago ↶
60
mod hooks ;
98286406 Andy McCall 1 month ago ↶
61
mod identity ;
83e0677b Andy McCall 1 month ago ↶
62
mod policy ;
135212de Andy McCall 1 month ago ↶
63
mod prompt ;
98286406 Andy McCall 1 month ago ↶
64
mod snapshot ;
65
mod sync ;
132b884b Andy McCall 1 month ago ↶
66
mod tags ;
4e88e774 Andy McCall 1 month ago ↶
67
mod workspace ;
98286406 Andy McCall 1 month ago ↶
68
# [ cfg ( test ) ]
69
mod tests ;
70
71
pub use checkout:: CheckoutReport;
b3c5a59a Andy McCall 1 month ago ↶
72
pub use config:: { parse_size, read_config_file, Config} ;
ba160f60 Andy McCall 1 month ago ↶
73
pub use gc:: GcReport;
6d3eefbc Andy McCall 1 month ago ↶
74
pub use hooks:: { json_array, json_str, HookOutcome} ;
135212de Andy McCall 1 month ago ↶
75
pub use prompt:: { PromptInfo, DEFAULT_PROMPT_FORMAT } ;
c3069537 Andy McCall 1 month ago ↶
76
pub use git:: { GitExportReport, GitImportReport} ;
28fc23d7 Andy McCall 1 month ago ↶
77
pub use identity:: { Rotation, SignatureStatus} ;
78
pub use policy:: PolicyUpdate;
6e723b81 Andy McCall 1 month ago ↶
79
pub use snapshot:: { added_node_paths, has_conflict_markers, is_binary, referenced_changes, render_change, similarity, ChangeStatus, PathStatus, SnapshotResult} ;
83e0677b Andy McCall 1 month ago ↶
80
pub use sync:: { FetchReport, PullReport} ;
132b884b Andy McCall 1 month ago ↶
81
pub use tags:: TagInfo;
4e88e774 Andy McCall 1 month ago ↶
82
pub use workspace:: { SnapshotLock, WorkspaceInfo} ;
98286406 Andy McCall 1 month ago ↶
83
84
fn write_atomic ( path : & Path, data : & [u8 ]) -> Result< ( ) > {
85
let tmp = path.with_extension ( " tmp" ) ;
86
{
87
let mut f = fs:: File:: create( & tmp) ? ;
88
f.write_all ( data) ? ;
89
f.sync_all ( ) ? ;
90
}
91
fs:: rename( & tmp, path) ? ;
92
Ok ( ( ) )
93
}
94
95
pub struct LogEntry {
96
pub hash : ChangeHash,
2863456a Andy McCall 1 month ago ↶
97
98
pub change : crate:: state:: ChangeMeta,
98286406 Andy McCall 1 month ago ↶
99
pub is_working_copy : bool ,
100
pub is_head : bool ,
101
}
102
c3069537 Andy McCall 1 month ago ↶
103
104
pub ( crate ) struct FsEntry {
105
pub kind : NodeKind,
106
pub exec : bool ,
b7f102fc Andy McCall 1 month ago ↶
107
c3069537 Andy McCall 1 month ago ↶
108
pub content : Vec< u8 > ,
b7f102fc Andy McCall 1 month ago ↶
109
110
111
112
pub blob : Option< ObjectRef> ,
113
114
115
pub content_hash : Option< String> ,
98286406 Andy McCall 1 month ago ↶
116
}
117
b7f102fc Andy McCall 1 month ago ↶
118
impl FsEntry {
119
pub ( crate ) fn new ( kind : NodeKind, exec : bool , content : Vec< u8 > ) -> FsEntry {
120
FsEntry { kind, exec, content, blob: None , content_hash: None }
121
}
122
}
123
98286406 Andy McCall 1 month ago ↶
124
pub struct Repo {
125
root : PathBuf,
126
oxy : PathBuf,
127
store : Store,
128
workspace : WorkspaceId,
129
keys_dir : PathBuf,
130
user_config : PathBuf,
131
pub config : Config,
132
}
133
134
135
136
pub fn default_home ( ) -> PathBuf {
137
if let Ok ( h) = std:: env:: var( " OXY_HOME" ) {
138
return PathBuf:: from( h) ;
139
}
140
if let Ok ( x) = std:: env:: var( " XDG_CONFIG_HOME" ) {
141
return PathBuf:: from( x) .join ( " oxy" ) ;
142
}
143
let home = std:: env:: var( " HOME" ) .unwrap_or_else ( | _| " ." .into ( ) ) ;
144
PathBuf:: from( home) .join ( " .config" ) .join ( " oxy" )
145
}
146
147
pub fn default_keys_dir ( ) -> PathBuf {
148
default_home ( ) .join ( " keys" )
149
}
150
151
pub fn default_user_config ( ) -> PathBuf {
152
default_home ( ) .join ( " config.toml" )
153
}
154
155
156
# [ derive ( Clone, Copy, Debug, PartialEq, Eq ) ]
157
pub enum IdentityScope {
158
159
User,
160
161
Repo,
162
}
163
164
impl Repo {
165
166
167
pub fn init ( root : & Path) -> Result< Repo> {
168
let mut id = [ 0 u8 ; 16 ] ;
169
rand:: rngs:: OsRng.fill_bytes ( & mut id) ;
170
Self :: init_with_id( root, id)
171
}
172
173
174
175
pub fn init_with_id ( root : & Path, id : [u8 ; 16]) -> Result< Repo> {
176
fs:: create_dir_all( root) ? ;
177
let root = root.canonicalize ( ) .unwrap_or_else ( | _| root.to_path_buf ( ) ) ;
178
let oxy = root.join ( OXY_DIR ) ;
179
if oxy.exists ( ) {
180
return fail ( format! ( " {} is already an oxy repository" , root.display ( ) ) ) ;
181
}
182
fs:: create_dir_all( oxy.join ( " ops" ) ) ? ;
183
write_atomic ( & oxy.join ( " format" ) , FORMAT_LINE .as_bytes ( ) ) ? ;
184
write_atomic ( & oxy.join ( " id" ) , hex:: encode( id) .as_bytes ( ) ) ? ;
185
let config = Config:: load( Some ( & default_user_config ( ) ) , & oxy.join ( " config" ) ) ? ;
186
config.save ( & oxy.join ( " config" ) ) ? ;
187
let workspace = WorkspaceId:: random( ) ;
188
write_atomic ( & oxy.join ( " workspace" ) , workspace.to_hex ( ) .as_bytes ( ) ) ? ;
189
let store = Store:: open( oxy.join ( " objects" ) ) ? ;
190
let repo = Repo { root, oxy, store, workspace, keys_dir: default_keys_dir ( ) , user_config: default_user_config ( ) , config } ;
4e88e774 Andy McCall 1 month ago ↶
191
repo.register_workspace ( & workspace, & repo.root) ? ;
98286406 Andy McCall 1 month ago ↶
192
193
let wc = repo.new_working_copy ( vec! [ ] , " " ) ;
194
let wc_hash = repo.store.put_change ( & wc) ? ;
195
let mut view = View:: default( ) ;
196
view.bookmarks.insert ( repo.config.bookmark.clone ( ) , repo.store.put_state ( & StateObject:: new( vec! [ ] ) ) ? ) ;
197
view.workspaces.insert ( workspace, wc_hash) ;
198
repo.record_op ( & [ ] , " oxy init" , view) ? ;
199
Ok ( repo)
200
}
201
202
203
pub fn open ( start : & Path) -> Result< Repo> {
204
let start = start.canonicalize ( ) ? ;
205
let mut dir: Option< & Path> = Some ( & start) ;
206
while let Some ( d) = dir {
207
let oxy = d.join ( OXY_DIR ) ;
4e88e774 Andy McCall 1 month ago ↶
208
if oxy.is_file ( ) {
209
210
let text = fs:: read_to_string( & oxy) ? ;
211
let Some ( ( shared, workspace) ) = workspace:: parse_workspace_file( & text) else {
212
return fail ( format! ( " {} is not a valid workspace file" , oxy.display ( ) ) ) ;
213
} ;
214
let format = fs:: read_to_string( shared.join ( " format" ) ) ? ;
215
if format ! = FORMAT_LINE {
216
return fail ( format! ( " unsupported repository format: {} " , format.trim ( ) ) ) ;
217
}
218
let config = Config:: load( Some ( & default_user_config ( ) ) , & shared.join ( " config" ) ) ? ;
219
let store = Store:: open( shared.join ( " objects" ) ) ? ;
220
return Ok ( Repo { root: d.to_path_buf ( ) , oxy: shared, store, workspace, keys_dir: default_keys_dir ( ) , user_config: default_user_config ( ) , config } ) ;
221
}
98286406 Andy McCall 1 month ago ↶
222
if oxy.is_dir ( ) {
223
let format = fs:: read_to_string( oxy.join ( " format" ) ) ? ;
224
let config = Config:: load( Some ( & default_user_config ( ) ) , & oxy.join ( " config" ) ) ? ;
225
let workspace = WorkspaceId:: from_hex( fs:: read_to_string( oxy.join ( " workspace" ) ) ? .trim ( ) )
226
.ok_or_else ( | | RepoError:: Msg( " corrupt .oxy/workspace" .into ( ) ) ) ? ;
227
let store = Store:: open( oxy.join ( " objects" ) ) ? ;
228
let repo = Repo { root: d.to_path_buf ( ) , oxy, store, workspace, keys_dir: default_keys_dir ( ) , user_config: default_user_config ( ) , config } ;
229
if format = = FORMAT1_LINE {
230
repo.migrate_format1 ( ) ? ;
231
} else if format ! = FORMAT_LINE {
232
return fail ( format! ( " unsupported repository format: {} " , format.trim ( ) ) ) ;
233
}
234
return Ok ( repo) ;
235
}
236
dir = d.parent ( ) ;
237
}
238
fail ( format! ( " no oxy repository found at or above {} " , start.display ( ) ) )
239
}
240
241
242
243
fn migrate_format1 ( & self ) -> Result< ( ) > {
244
let hex = fs:: read_to_string( self .oxy.join ( " ops" ) .join ( " head" ) ) ? ;
245
let head = ObjectRef:: from_hex( hex.trim ( ) ) .ok_or_else ( | | RepoError:: Msg( " corrupt .oxy/ops/head" .into ( ) ) ) ? ;
246
247
let mut chain: Vec< Format1Op> = Vec :: new( ) ;
248
let mut cur = Some ( head) ;
249
while let Some ( r) = cur {
250
let op = Op:: decode_format1( & self .store.get_typed ( & r, ObjectType:: Op) ? ) ? ;
251
cur = op.parents.first ( ) .copied ( ) ;
252
chain.push ( op) ;
253
}
254
chain.reverse ( ) ;
255
let mut new_parent: Option< ObjectRef> = None ;
256
for old in chain {
257
let mut view = View:: default( ) ;
258
for ( name, heads) in & old.view.bookmarks {
259
view.bookmarks.insert ( name.clone ( ) , self .store.put_state ( & StateObject:: new( heads.clone ( ) ) ) ? ) ;
260
}
261
view.workspaces = old.view.workspaces.clone ( ) ;
262
let op = Op { parents: new_parent.into_iter ( ) .collect ( ) , hlc: old.hlc, command: old.command, view } ;
263
new_parent = Some ( self .store.put ( ObjectType:: Op, & op.encode ( ) ) ? ) ;
264
}
265
write_atomic ( & self .oxy.join ( " ops" ) .join ( " head" ) , new_parent.unwrap ( ) .to_hex ( ) .as_bytes ( ) ) ? ;
266
write_atomic ( & self .oxy.join ( " format" ) , FORMAT_LINE .as_bytes ( ) ) ? ;
267
Ok ( ( ) )
d02e545d Andy McCall 1 month ago ↶
268
}
269
270
271
pub ( crate ) fn maybe_autopack ( & self ) -> Result< ( ) > {
272
if self .store.loose_count ( ) ? > AUTOPACK_THRESHOLD {
273
self .store.pack_loose ( ) ? ;
135212de Andy McCall 1 month ago ↶
274
self .store.merge_packs ( ) ? ;
d02e545d Andy McCall 1 month ago ↶
275
}
276
Ok ( ( ) )
277
}
278
98286406 Andy McCall 1 month ago ↶
279
280
pub fn id ( & self ) -> Result< [ u8 ; 16 ] > {
281
let path = self .oxy.join ( " id" ) ;
282
match fs:: read_to_string( & path) {
283
Ok ( h) => hex:: decode( h.trim ( ) ) .ok ( ) .and_then ( | v | v.try_into ( ) .ok ( ) ) .ok_or_else ( | | RepoError:: Msg( " corrupt .oxy/id" .into ( ) ) ) ,
284
Err ( e) if e.kind ( ) = = std:: io:: ErrorKind:: NotFound => {
285
let mut id = [ 0 u8 ; 16 ] ;
286
rand:: rngs:: OsRng.fill_bytes ( & mut id) ;
287
write_atomic ( & path, hex:: encode( id) .as_bytes ( ) ) ? ;
288
Ok ( id)
289
}
290
Err ( e) => Err ( e.into ( ) ) ,
291
}
292
}
293
294
pub fn root ( & self ) -> & Path {
295
& self .root
296
}
297
pub fn store ( & self ) -> & Store {
298
& self .store
299
}
300
pub fn workspace ( & self ) -> WorkspaceId {
301
self .workspace
302
}
303
304
305
306
pub fn with_home ( mut self , dir : impl Into< PathBuf> ) -> Repo {
307
let dir = dir.into ( ) ;
308
self .keys_dir = dir.join ( " keys" ) ;
309
self .user_config = dir.join ( " config.toml" ) ;
310
if let Ok ( c) = Config:: load( Some ( & self .user_config) , & self .oxy.join ( " config" ) ) {
311
self .config = c;
312
}
313
self
314
}
315
316
pub fn user_config_path ( & self ) -> & Path {
317
& self .user_config
318
}
319
320
321
pub fn set_user_config ( & mut self , key : & str , value : & str ) -> Result< ( ) > {
322
Config:: set_user( & self .user_config, key, value) ? ;
323
self .config = Config:: load( Some ( & self .user_config) , & self .oxy.join ( " config" ) ) ? ;
324
Ok ( ( ) )
325
}
326
327
pub fn save_config ( & self ) -> Result< ( ) > {
328
self .config.save ( & self .oxy.join ( " config" ) )
329
}
330
331
fn author ( & self ) -> KeyId {
332
self .config.author_key.unwrap_or ( ObjectRef:: ZERO )
333
}
334
}
335
336
impl Repo {
337
fn new_working_copy ( & self , deps : Vec< ChangeHash> , message : & str ) -> Change {
338
let mut c = Change {
339
change_id: ChangeId:: random( ) ,
340
deps,
341
author: self .author ( ) ,
342
hlc: Hlc:: now( ) ,
343
message: message.into ( ) ,
344
tree_ops: vec! [ ] ,
345
edits: vec! [ ] ,
346
kind: ChangeKind:: WorkingCopy,
347
} ;
348
c.normalize ( ) ;
349
c
350
}
351
352
353
354
pub fn head_op ( & self ) -> Result< ( ObjectRef, Op) > {
355
let hex = fs:: read_to_string( self .oxy.join ( " ops" ) .join ( " head" ) ) ? ;
356
let r = ObjectRef:: from_hex( hex.trim ( ) ) .ok_or_else ( | | RepoError:: Msg( " corrupt .oxy/ops/head" .into ( ) ) ) ? ;
357
let op = Op:: decode( & self .store.get_typed ( & r, ObjectType:: Op) ? ) ? ;
358
Ok ( ( r, op) )
359
}
360
361
pub fn view ( & self ) -> Result< View> {
362
Ok ( self .head_op ( ) ? .1. view)
363
}
364
365
fn record_op ( & self , parents : & [ObjectRef], command : & str , view : View) -> Result< ObjectRef> {
366
let op = Op { parents: parents.to_vec ( ) , hlc: Hlc:: now( ) , command: command.into ( ) , view } ;
367
let r = self .store.put ( ObjectType:: Op, & op.encode ( ) ) ? ;
368
write_atomic ( & self .oxy.join ( " ops" ) .join ( " head" ) , r.to_hex ( ) .as_bytes ( ) ) ? ;
369
Ok ( r)
370
}
371
372
pub fn op_log ( & self ) -> Result< Vec< ( ObjectRef, Op) > > {
373
let mut out = Vec :: new( ) ;
374
let ( mut r, mut op) = self .head_op ( ) ? ;
375
loop {
376
let next = op.parents.first ( ) .copied ( ) ;
377
out.push ( ( r, op) ) ;
378
match next {
379
Some ( p) => {
380
r = p;
381
op = Op:: decode( & self .store.get_typed ( & r, ObjectType:: Op) ? ) ? ;
382
}
383
None => break ,
384
}
385
}
386
Ok ( out)
387
}
388
389
390
391
392
pub fn undo ( & self ) -> Result< Op> {
393
let ( _ , mut op) = self .head_op ( ) ? ;
394
while op.is_snapshot ( ) {
395
let Some ( parent) = op.parents.first ( ) else { break } ;
396
op = Op:: decode( & self .store.get_typed ( parent, ObjectType:: Op) ? ) ? ;
397
}
398
let Some ( parent) = op.parents.first ( ) else {
399
return fail ( " nothing to undo" ) ;
400
} ;
401
let parent_op = Op:: decode( & self .store.get_typed ( parent, ObjectType:: Op) ? ) ? ;
402
write_atomic ( & self .oxy.join ( " ops" ) .join ( " head" ) , parent.to_hex ( ) .as_bytes ( ) ) ? ;
135212de Andy McCall 1 month ago ↶
403
self .drop_manifest ( ) ;
98286406 Andy McCall 1 month ago ↶
404
Ok ( parent_op)
405
}
406
407
408
pub fn last_command ( & self ) -> Result< Op> {
409
let ( _ , mut op) = self .head_op ( ) ? ;
410
while op.is_snapshot ( ) {
411
let Some ( parent) = op.parents.first ( ) else { break } ;
412
op = Op:: decode( & self .store.get_typed ( parent, ObjectType:: Op) ? ) ? ;
413
}
414
Ok ( op)
415
}
416
417
418
252e8cb2 Andy McCall 1 month ago ↶
419
98286406 Andy McCall 1 month ago ↶
420
pub fn load_state ( & self , heads : & [ChangeHash]) -> Result< State> {
252e8cb2 Andy McCall 1 month ago ↶
421
if let Some ( st) = self .load_state_checkpointed ( heads) ? {
422
return Ok ( st) ;
423
}
424
self .load_state_full ( heads)
425
}
426
427
428
pub fn load_state_full ( & self , heads : & [ChangeHash]) -> Result< State> {
98286406 Andy McCall 1 month ago ↶
429
let mut state = State:: new( ) ;
430
let mut stack: Vec< ChangeHash> = heads.to_vec ( ) ;
431
let mut seen: BTreeSet< ChangeHash> = BTreeSet:: new( ) ;
432
while let Some ( h) = stack.pop ( ) {
433
if ! seen.insert ( h) {
434
continue ;
435
}
436
let c = self .store.get_change ( & h) ? ;
437
stack.extend ( c.deps.iter ( ) .copied ( ) ) ;
438
state.add_unchecked ( c) ;
439
}
440
state.validate ( ) ? ;
441
Ok ( state)
442
}
443
444
pub fn working_copy ( & self ) -> Result< ( ChangeHash, Change) > {
445
let view = self .view ( ) ? ;
446
let h = * view
447
.workspaces
448
.get ( & self .workspace)
449
.ok_or_else ( | | RepoError:: Msg( " this workspace is not in the current view" .into ( ) ) ) ? ;
450
Ok ( ( h, self .store.get_change ( & h) ? ) )
451
}
452
453
454
pub fn heads_of ( & self , view : & View, bookmark : & str ) -> Result< Vec< ChangeHash> > {
455
match view.bookmarks.get ( bookmark) {
456
Some ( st) => Ok ( self .store.get_state ( st) ? .heads) ,
457
None => Ok ( vec! [ ] ) ,
458
}
459
}
460
461
pub fn bookmark_heads ( & self ) -> Result< Vec< ChangeHash> > {
462
self .heads_of ( & self .view ( ) ? , & self .config.bookmark)
463
}
464
465
466
467
fn blob_for ( content : & [u8 ]) -> Blob {
468
Blob {
469
length: content.len ( ) as u64 ,
470
chunks: crate :: chunk:: chunks( content) .into_iter ( ) .map ( | c | hash_object ( ObjectType:: Chunk, c) ) .collect ( ) ,
471
}
472
}
473
474
pub fn blob_ref ( content : & [u8 ]) -> ObjectRef {
475
Self :: blob_for( content) .hash ( )
476
}
477
478
pub fn store_blob ( & self , content : & [u8 ]) -> Result< ObjectRef> {
479
for c in crate :: chunk:: chunks( content) {
480
self .store.put_chunk ( c) ? ;
481
}
482
Ok ( self .store.put ( ObjectType:: Blob, & Self :: blob_for( content) .encode ( ) ) ? )
483
}
484
b3c5a59a Andy McCall 1 month ago ↶
485
486
98286406 Andy McCall 1 month ago ↶
487
pub fn read_blob ( & self , r : & ObjectRef) -> Result< Vec< u8 > > {
b3c5a59a Andy McCall 1 month ago ↶
488
if ! self .store.has ( r) & & self .lazy_remote ( r) .is_some ( ) {
489
self .fetch_lazy_blob ( r) ? ;
490
}
98286406 Andy McCall 1 month ago ↶
491
let blob = Blob:: decode( & self .store.get_typed ( r, ObjectType:: Blob) ? ) ? ;
492
let mut out = Vec :: with_capacity( blob.length as usize ) ;
493
for c in & blob.chunks {
494
out.extend ( self .store.get_typed ( c, ObjectType:: Chunk) ? ) ;
495
}
496
Ok ( out)
497
}
498
499
500
cdb5beba Andy McCall 1 month ago ↶
501
502
pub fn disk_attributes ( & self ) -> crate:: attributes:: Attributes {
503
let mut files: Vec< ( String, Vec< u8 > ) > = Vec :: new( ) ;
504
if let Ok ( b) = fs:: read( self .root.join ( " .oxyattributes" ) ) {
505
files.push ( ( " .oxyattributes" .into ( ) , b) ) ;
506
}
507
let mut wb = ignore:: WalkBuilder:: new( & self .root) ;
508
wb.hidden ( false ) .git_ignore ( false ) .git_global ( false ) .git_exclude ( false ) .require_git ( false ) .follow_links ( false ) .add_custom_ignore_filename ( " .oxyignore" ) ;
509
wb.filter_entry ( | e | e.file_name ( ) ! = OXY_DIR ) ;
510
for entry in wb.build ( ) .flatten ( ) {
511
if entry.file_name ( ) = = " .oxyattributes" & & entry.path ( ) ! = self .root.join ( " .oxyattributes" ) {
512
if let Ok ( b) = fs:: read( entry.path ( ) ) {
513
let rel: String = entry.path ( ) .strip_prefix ( & self .root) .unwrap ( ) .components ( ) .map ( | c | c.as_os_str ( ) .to_string_lossy ( ) .to_string ( ) ) .collect:: < Vec< _ > > ( ) .join ( " /" ) ;
514
files.push ( ( rel, b) ) ;
515
}
516
}
517
}
518
crate :: attributes:: Attributes:: from_files( files.iter ( ) .map ( | ( p , c ) | ( p.as_str ( ) , c.as_slice ( ) ) ) )
519
}
520
521
522
pub fn state_attributes ( snapshot : & Snapshot) -> crate:: attributes:: Attributes {
523
crate :: attributes:: Attributes:: from_files( snapshot.files.iter ( ) .filter_map ( | ( p , f ) | match & f.content {
524
FileContent:: Text { bytes, .. } if p = = " .oxyattributes" | | p.ends_with ( " /.oxyattributes" ) => Some ( ( p.as_str ( ) , bytes.as_slice ( ) ) ) ,
525
_ => None ,
526
} ) )
527
}
528
529
530
pub fn store_blob_for ( & self , content : & [u8 ], nocompress : bool ) -> Result< ObjectRef> {
531
if ! nocompress {
532
return self .store_blob ( content) ;
533
}
534
for c in crate :: chunk:: chunks( content) {
535
self .store.put_chunk_nocompress ( c) ? ;
536
}
537
Ok ( self .store.put ( ObjectType:: Blob, & Self :: blob_for( content) .encode ( ) ) ? )
538
}
539
540
fn locks_dir ( & self ) -> PathBuf {
541
self .oxy.join ( " locks" )
542
}
543
544
545
pub fn is_locked ( & self , path : & str ) -> bool {
546
self .locks_dir ( ) .join ( path.replace ( ' /' , " %2F" ) ) .exists ( )
547
}
548
549
550
pub fn lock_path ( & self , path : & str ) -> Result< ( ) > {
551
let attrs = self .disk_attributes ( ) ;
552
if ! attrs.lookup ( path) .lockable {
553
return fail ( format! ( " {path} is not marked lockable in .oxyattributes" ) ) ;
554
}
555
fs:: create_dir_all( self .locks_dir ( ) ) ? ;
556
write_atomic ( & self .locks_dir ( ) .join ( path.replace ( ' /' , " %2F" ) ) , std:: process:: id( ) .to_string ( ) .as_bytes ( ) ) ? ;
557
set_readonly ( & self .root.join ( path) , false ) ? ;
558
Ok ( ( ) )
559
}
560
561
562
pub fn unlock_path ( & self , path : & str ) -> Result< ( ) > {
563
let _ = fs:: remove_file( self .locks_dir ( ) .join ( path.replace ( ' /' , " %2F" ) ) ) ;
564
if self .root.join ( path) .exists ( ) {
565
set_readonly ( & self .root.join ( path) , true ) ? ;
566
}
567
Ok ( ( ) )
568
}
569
7421309f Andy McCall 1 month ago ↶
570
571
pub fn in_scope ( & self , path : & str ) -> bool {
572
self .config.sparse_paths.is_empty ( ) | | self .config.sparse_paths.iter ( ) .any ( | p | path = = p | | path.starts_with ( & format! ( " {p} /" ) ) )
573
}
574
98286406 Andy McCall 1 month ago ↶
575
fn walk_working_copy ( & self ) -> Result< BTreeMap< String, FsEntry> > {
b7f102fc Andy McCall 1 month ago ↶
576
self .walk_working_copy_with ( None )
577
}
578
579
580
581
582
583
fn walk_working_copy_with ( & self , cache : Option< & prompt:: Manifest> ) -> Result< BTreeMap< String, FsEntry> > {
98286406 Andy McCall 1 month ago ↶
584
let mut wb = ignore:: WalkBuilder:: new( & self .root) ;
585
wb.hidden ( false )
586
.git_ignore ( false )
587
.git_global ( false )
588
.git_exclude ( false )
589
.require_git ( false )
590
.follow_links ( false )
591
.add_custom_ignore_filename ( " .oxyignore" ) ;
592
wb.filter_entry ( | e | e.file_name ( ) ! = OXY_DIR ) ;
593
let mut out = BTreeMap:: new( ) ;
594
for entry in wb.build ( ) {
595
let entry = entry.map_err ( | e | RepoError:: Msg( e.to_string ( ) ) ) ? ;
596
let path = entry.path ( ) ;
597
if path = = self .root {
598
continue ;
599
}
600
let rel = path.strip_prefix ( & self .root) .unwrap ( ) ;
601
let rel: String = rel.components ( ) .map ( | c | c.as_os_str ( ) .to_string_lossy ( ) .to_string ( ) ) .collect:: < Vec< _ > > ( ) .join ( " /" ) ;
602
let Some ( ft) = entry.file_type ( ) else { continue } ;
7421309f Andy McCall 1 month ago ↶
603
if ft.is_dir ( ) | | ! self .in_scope ( & rel) {
98286406 Andy McCall 1 month ago ↶
604
continue ;
605
}
606
if ft.is_symlink ( ) {
607
let target = fs:: read_link( path) ? ;
b7f102fc Andy McCall 1 month ago ↶
608
out.insert ( rel, FsEntry:: new( NodeKind:: Symlink, false , target.to_string_lossy ( ) .as_bytes ( ) .to_vec ( ) ) ) ;
98286406 Andy McCall 1 month ago ↶
609
} else if ft.is_file ( ) {
b7f102fc Andy McCall 1 month ago ↶
610
let meta = entry.metadata ( ) .map_err ( | e | RepoError:: Msg( e.to_string ( ) ) ) ? ;
611
let exec = is_executable ( & meta) ;
612
let cached = cache.and_then ( | m | {
613
let e = m.entries.get ( & rel) ? ;
614
let mtime_ns = prompt:: mtime_ns( & meta) ;
615
let racy = mtime_ns + 2_000_000_000 > = m.written_ns;
616
( e.size = = meta.len ( ) & & e.mtime_ns = = mtime_ns & & ! racy) .then_some ( e)
617
} ) ;
618
match cached {
619
Some ( e) if e.blob.is_some_and ( | b | self .store.has ( & b) ) => {
620
out.insert ( rel, FsEntry { kind: NodeKind:: File, exec, content: vec! [ ] , blob: e.blob, content_hash: Some ( e.hash.clone ( ) ) } ) ;
621
}
622
Some ( e) => {
623
out.insert ( rel, FsEntry { kind: NodeKind:: File, exec, content: fs:: read( path) ? , blob: None , content_hash: Some ( e.hash.clone ( ) ) } ) ;
624
}
625
None => {
626
out.insert ( rel, FsEntry:: new( NodeKind:: File, exec, fs:: read( path) ? ) ) ;
627
}
628
}
98286406 Andy McCall 1 month ago ↶
629
}
630
}
631
Ok ( out)
632
}
633
}
634
635
impl Repo {
636
637
pub fn log ( & self ) -> Result< Vec< LogEntry> > {
638
let ( wc_hash, _ ) = self .working_copy ( ) ? ;
639
let mut heads = self .bookmark_heads ( ) ? ;
640
heads.push ( wc_hash) ;
641
let state = self .load_state ( & heads) ? ;
642
let head_set: BTreeSet< ChangeHash> = self .bookmark_heads ( ) ? .into_iter ( ) .collect ( ) ;
252e8cb2 Andy McCall 1 month ago ↶
643
let mut entries: Vec< LogEntry> = Vec :: new( ) ;
2863456a Andy McCall 1 month ago ↶
644
for ( h, meta) in state.changes ( ) {
645
entries.push ( LogEntry { hash: * h, change: meta.clone ( ) , is_working_copy: * h = = wc_hash, is_head: head_set.contains ( h) } ) ;
252e8cb2 Andy McCall 1 month ago ↶
646
}
98286406 Andy McCall 1 month ago ↶
647
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) ) ) ;
648
Ok ( entries)
649
}
650
132b884b Andy McCall 1 month ago ↶
651
652
653
pub fn resolve_heads ( & self , spec : & str ) -> Result< Vec< ChangeHash> > {
654
if spec = = self .config.bookmark {
655
return self .bookmark_heads ( ) ;
656
}
657
if let Some ( heads) = self .tag_heads ( spec) ? {
658
return Ok ( heads) ;
659
}
660
Ok ( vec! [ self .resolve_change ( spec) ? ] )
661
}
662
98286406 Andy McCall 1 month ago ↶
663
664
pub fn resolve_change ( & self , spec : & str ) -> Result< ChangeHash> {
665
if spec = = " @" {
666
return Ok ( self .working_copy ( ) ? .0 ) ;
667
}
668
if spec.is_empty ( ) | | spec = = " #" {
669
return fail ( " empty change specifier" ) ;
670
}
671
let entries = self .log ( ) ? ;
672
let matches: Vec< & LogEntry> = if let Some ( hp) = spec.strip_prefix ( ' #' ) {
673
entries.iter ( ) .filter ( | e | e.hash.starts_with_hex ( hp) ) .collect ( )
674
} else {
675
entries.iter ( ) .filter ( | e | e.change.change_id.starts_with_hex ( spec) ) .collect ( )
676
} ;
677
match matches.len ( ) {
678
1 => Ok ( matches[ 0 ] .hash) ,
679
0 => fail ( format! ( " no change matches {spec:?} " ) ) ,
680
_ => {
681
let ids: BTreeSet< ChangeId> = matches.iter ( ) .map ( | e | e.change.change_id ) .collect ( ) ;
682
if ids.len ( ) = = 1 {
683
fail ( format! ( " change {spec} is divergent: {} variants" , matches.len ( ) ) )
684
} else {
685
fail ( format! ( " {spec:?} is ambiguous" ) )
686
}
687
}
688
}
689
}
690
691
692
pub fn describe_change ( & self , hash : & ChangeHash) -> Result< String> {
693
let change = self .store.get_change ( hash) ? ;
694
let base = self .load_state ( & change.deps) ? ;
695
let base_snapshot = base.materialize ( ) ;
696
Ok ( render_change ( & change, & base, & base_snapshot) )
697
}
698
}
699
700
fn remove_any ( path : & Path) -> std:: io:: Result< ( ) > {
701
let m = fs:: symlink_metadata( path) ? ;
702
if m.is_dir ( ) { fs:: remove_dir_all( path) } else { fs:: remove_file( path) }
703
}
704
cdb5beba Andy McCall 1 month ago ↶
705
fn set_readonly ( path : & Path, readonly : bool ) -> std:: io:: Result< ( ) > {
706
let mut perms = fs:: metadata( path) ? .permissions ( ) ;
707
perms.set_readonly ( readonly) ;
708
fs:: set_permissions( path, perms)
709
}
710
98286406 Andy McCall 1 month ago ↶
711
# [ cfg ( unix ) ]
712
fn set_executable ( path : & Path, exec : bool ) -> std:: io:: Result< ( ) > {
713
use std:: os:: unix:: fs:: PermissionsExt;
714
let mut perms = fs:: metadata( path) ? .permissions ( ) ;
715
let mode = perms.mode ( ) ;
716
let want = if exec { mode | 0o111 } else { mode & ! 0o111 } ;
717
if want ! = mode {
718
perms.set_mode ( want) ;
719
fs:: set_permissions( path, perms) ? ;
720
}
721
Ok ( ( ) )
722
}
723
# [ cfg ( not ( unix ) ) ]
724
fn set_executable ( _path : & Path, _exec : bool ) -> std:: io:: Result< ( ) > {
725
Ok ( ( ) )
726
}
727
728
# [ cfg ( unix ) ]
729
fn is_executable ( m : & fs:: Metadata) -> bool {
730
use std:: os:: unix:: fs:: PermissionsExt;
731
m.permissions ( ) .mode ( ) & 0o111 ! = 0
732
}
733
# [ cfg ( not ( unix ) ) ]
734
fn is_executable ( _m : & fs:: Metadata) -> bool {
735
false
736
}
737
738
fn op_ref ( k : OpKey) -> OpRef {
739
OpRef { change: k.0 , index: k.1 }
740
}
741
742
fn split_path ( path : & str ) -> ( & str , & str ) {
743
match path.rfind ( ' /' ) {
744
Some ( i) => ( & path[ .. i] , & path[ i + 1 .. ] ) ,
745
None => ( " " , path) ,
746
}
747
}