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