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