Elffuss BraidHub

kikocis/continue public

4131ae02de3e · 19.3 KiBRawPermalink
1use homedir::get_my_home;
2use ignore::{Walk, WalkBuilder};
3use serde::{Deserialize, Serialize};
4use sha1::{Digest, Sha1};
5use std::{
6 io::{Read, Result, Write},
7 path::{Path, PathBuf},
8};
9
10pub type ObjectHash = [u8; 20];
11
12pub fn hash_string(hash: ObjectHash) -> String {
13 hash.iter().fold(String::new(), |mut output, byte| {
14 output.push_str(&format!("{byte:02x}"));
15 output
16 })
17}
18
19#[derive(Clone, Default)]
20pub struct Tree {
21 parent: Option<ObjectHash>,
22 children: Vec<Object>,
23 hash: ObjectHash,
24 path: String,
25}
26
27#[derive(Serialize, Deserialize)]
28struct SerializeableNode {
29 parent: Option<ObjectHash>,
30
31 /// Blobs would have no children
32 children: Option<Vec<ObjectHash>>,
33 hash: ObjectHash,
34 path: String,
35}
36
37#[derive(Clone)]
38struct Blob {
39 parent: Option<ObjectHash>,
40 hash: ObjectHash,
41 path: String,
42}
43
44#[derive(Clone)]
45enum Object {
46 Tree(Tree),
47 Blob(Blob),
48}
49
50impl From<Tree> for Object {
51 fn from(tree: Tree) -> Self {
52 Self::Tree(tree)
53 }
54}
55
56impl From<Blob> for Object {
57 fn from(blob: Blob) -> Self {
58 Self::Blob(blob)
59 }
60}
61
62pub struct ObjDescription {
63 pub hash: ObjectHash,
64 pub path: String,
65 pub is_blob: bool,
66}
67
68impl Object {
69 fn hash(&self) -> ObjectHash {
70 match self {
71 Self::Tree(tree) => tree.hash,
72 Self::Blob(blob) => blob.hash,
73 }
74 }
75
76 fn path(&self) -> &String {
77 match self {
78 Self::Tree(tree) => &tree.path,
79 Self::Blob(blob) => &blob.path,
80 }
81 }
82
83 fn json_for_obj(&self) -> String {
84 match self {
85 Self::Tree(tree) => tree.json_for_obj(),
86 Self::Blob(blob) => blob.json_for_obj(),
87 }
88 }
89
90 fn descr(&self) -> ObjDescription {
91 return ObjDescription {
92 hash: self.hash(),
93 path: self.path().clone(),
94 is_blob: matches!(self, Self::Blob(_)),
95 };
96 }
97
98 /// Return a tuple of (paths to add, paths to remove)
99 fn diff(&self, new_obj: &Self) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
100 let mut add: Vec<ObjDescription> = Vec::new();
101 let mut remove: Vec<ObjDescription> = Vec::new();
102
103 if self.hash() == new_obj.hash() {
104 return (add, remove);
105 }
106
107 match (self, new_obj) {
108 (Self::Tree(old_tree), Self::Tree(new_tree)) => {
109 // This is where you recurse like below
110 let (child_add, child_remove) = old_tree.diff_children(new_tree);
111 add.push(new_tree.descr());
112 remove.push(old_tree.descr());
113 add.extend(child_add);
114 remove.extend(child_remove);
115 }
116 (Self::Blob(old_blob), Self::Blob(new_blob)) => {
117 add.push(new_blob.descr());
118 remove.push(old_blob.descr());
119 }
120 (Self::Blob(old_blob), Self::Tree(new_tree)) => {
121 // Remove blob, add entire new tree
122 remove.push(old_blob.descr());
123 add.extend(new_tree.all_obj_descriptions());
124 }
125 (Self::Tree(old_tree), Self::Blob(new_blob)) => {
126 // Remove entire old tree, add blob
127 remove.extend(old_tree.all_obj_descriptions());
128 add.push(new_blob.descr());
129 }
130 }
131
132 (add, remove)
133 }
134}
135
136pub fn diff(old_tree: &Tree, new_tree: &Tree) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
137 let mut add: Vec<ObjDescription> = Vec::new();
138 let mut remove: Vec<ObjDescription> = Vec::new();
139
140 if old_tree.hash == new_tree.hash {
141 return (add, remove);
142 }
143
144 let (child_add, child_remove) = old_tree.diff_children(new_tree);
145
146 add.push(new_tree.descr());
147 remove.push(old_tree.descr());
148 add.extend(child_add);
149 remove.extend(child_remove);
150
151 (add, remove)
152}
153
154impl Blob {
155 fn json_for_obj(&self) -> String {
156 let node = SerializeableNode {
157 parent: self.parent,
158 children: None,
159 hash: self.hash,
160 path: self.path.clone(),
161 };
162
163 let mut json = serde_json::to_string(&node).unwrap();
164 json.push('\n');
165 json
166 }
167
168 fn descr(&self) -> ObjDescription {
169 ObjDescription {
170 hash: self.hash,
171 path: self.path.clone(),
172 is_blob: true,
173 }
174 }
175}
176
177// enum DiffType {
178// Add,
179// Update,
180// Remove,
181// }
182
183impl Tree {
184 fn descr(&self) -> ObjDescription {
185 ObjDescription {
186 hash: self.hash,
187 path: self.path.clone(),
188 is_blob: false,
189 }
190 }
191
192 fn json_for_node(&self) -> String {
193 let node = SerializeableNode {
194 parent: self.parent,
195 children: Some(self.children.iter().map(Object::hash).collect()),
196 hash: self.hash,
197 path: self.path.clone(),
198 };
199
200 let mut json = serde_json::to_string(&node).unwrap();
201 json.push('\n');
202 json
203 }
204
205 fn json_for_obj(&self) -> String {
206 let mut result = String::new();
207 result.push_str(&self.json_for_node());
208
209 for child in &self.children {
210 result.push_str(&child.json_for_obj());
211 }
212
213 result
214 }
215
216 fn obj_from_jsonl(lines: &mut std::str::Lines, first_line: Option<SerializeableNode>) -> Self {
217 let root_node =
218 first_line.unwrap_or_else(|| serde_json::from_str(lines.next().unwrap()).unwrap());
219
220 let children = root_node
221 .children
222 .unwrap()
223 .into_iter()
224 .map(|_child_hash| {
225 let child_jsonl = lines.next().unwrap();
226 let child_node: SerializeableNode = serde_json::from_str(child_jsonl).unwrap();
227 if child_node.children.is_some() {
228 Self::obj_from_jsonl(lines, Some(child_node)).into()
229 } else {
230 Blob {
231 parent: child_node.parent,
232 hash: child_node.hash,
233 path: child_node.path,
234 }
235 .into()
236 }
237 })
238 .collect();
239
240 Self {
241 parent: root_node.parent,
242 children,
243 hash: root_node.hash,
244 path: root_node.path,
245 }
246 }
247
248 /// Persist the tree to disk as JSONL
249 pub fn persist(&self, filepath: &Path) {
250 if let Some(dir) = filepath.parent() {
251 std::fs::create_dir_all(dir)
252 .unwrap_or_else(|_| panic!("Failed to create dir {}", dir.display()));
253 }
254 let mut file = std::fs::File::create(filepath).unwrap();
255 file.write_all(self.json_for_obj().as_bytes()).unwrap();
256 }
257
258 /// Load the tree from JSONL file
259 pub fn load(filepath: &Path) -> Result<Self> {
260 let mut file = std::fs::File::open(filepath)?;
261 let mut contents = String::new();
262 file.read_to_string(&mut contents)?;
263 let mut lines = contents.lines();
264 Ok(Self::obj_from_jsonl(&mut lines, None))
265 }
266
267 // pub fn empty() -> Self {
268 // Self::default()
269 // }
270
271 fn set_childrens_parent(&mut self) {
272 for child in &mut self.children {
273 match child {
274 Object::Tree(tree) => {
275 tree.parent = Some(self.hash);
276 tree.set_childrens_parent();
277 }
278 Object::Blob(blob) => {
279 blob.parent = Some(self.hash);
280 }
281 }
282 }
283 }
284
285 fn walk(&self, callback: &mut dyn FnMut(&Object)) {
286 callback(&Object::Tree(self.clone()));
287 for child in &self.children {
288 match child {
289 Object::Tree(tree) => tree.walk(callback),
290 Object::Blob(blob) => callback(&Object::Blob(blob.clone())),
291 }
292 }
293 }
294
295 fn all_obj_descriptions(&self) -> Vec<ObjDescription> {
296 let mut result = Vec::new();
297 self.walk(&mut |obj| result.push(obj.descr()));
298 result
299 }
300
301 /// Return a list of paths that have changed and the type of change (0 = add, 1 = update, 2 = remove)
302 /// other is considered the "new" tree
303 fn diff_children(&self, new_tree: &Self) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
304 let mut add = Vec::new();
305 let mut remove = Vec::new();
306
307 // There are situations where the names of two folders could be swapped and then each slightly changed
308 // where you would need some heuristics to avoid throwing them out...but...don't worry for now. Just match by path
309
310 let mut old_path_to_object: std::collections::HashMap<String, &Object> = self
311 .children
312 .iter()
313 .map(|child| (child.path().clone(), child))
314 .collect();
315
316 for child in &new_tree.children {
317 if let Some(old_child) = old_path_to_object.remove(child.path()) {
318 // If the same path name exists in old children
319 let (child_add, child_remove) = old_child.diff(child);
320 add.extend(child_add);
321 remove.extend(child_remove);
322 } else {
323 // Name didn't exist before. Add all
324 match child {
325 Object::Tree(tree) => {
326 add.extend(tree.all_obj_descriptions());
327 }
328 Object::Blob(blob) => {
329 add.push(blob.descr());
330 }
331 }
332 }
333 }
334
335 // Remove - along with all children
336 for obj in old_path_to_object.values() {
337 match obj {
338 Object::Tree(tree) => tree.walk(&mut |_obj| {
339 remove.extend(tree.all_obj_descriptions());
340 }),
341 Object::Blob(_) => remove.push(obj.descr()),
342 }
343 }
344
345 (add, remove)
346 }
347}
348
349const GLOBAL_IGNORE_PATTERNS: &[&str] = &[
350 "**/.DS_Store",
351 "**/package-lock.json",
352 "*.lock",
353 "*.log",
354 "*.ttf",
355 "*.png",
356 "*.jpg",
357 "*.jpeg",
358 "*.gif",
359 "*.mp4",
360 "*.svg",
361 "*.ico",
362 "*.pdf",
363 "*.zip",
364 "*.gz",
365 "*.tar",
366 "*.tgz",
367 "*.rar",
368 "*.7z",
369 "*.exe",
370 "*.dll",
371 "*.obj",
372 "*.o",
373 "*.a",
374 "*.lib",
375 "*.so",
376 "*.dylib",
377 "*.ncb",
378 "*.sdf",
379 "*.woff",
380 "*.woff2",
381 "*.eot",
382 "*.cur",
383 "*.avi",
384 "*.mpg",
385 "*.mpeg",
386 "*.mov",
387 "*.mp3",
388 "*.mkv",
389 "*.webm",
390 "*.jar",
391 "*.onnx",
392 "*.tmp",
393 "*.swp",
394 "*.bak",
395 "*.dmp",
396 "**/node_modules/",
397 "**/.git",
398 "*.class",
399 "*.pyc",
400 "*.pyo",
401 "*.whl",
402 "*.egg-info",
403 "*.db",
404 "*.sql",
405 "*.sqlite",
406 "*.sqlite3",
407 "**/__pycache__/",
408 "**/.pytest_cache/",
409 "**/.env",
410 "*.pem",
411 "*.cert",
412 "*.key",
413 "*.csr",
414 "**/.idea/",
415 "**/.vscode/",
416 "**/.history/",
417 "*.sass-cache",
418 "*.scssc",
419 "*.parquet",
420];
421
422fn global_ignore_path() -> PathBuf {
423 let mut path = get_my_home().unwrap().unwrap();
424 path.push(".continue");
425 path.push(".continueignore");
426 path
427}
428
429fn create_global_ignore_file() -> PathBuf {
430 // Because you have to pass a real filepath to the ignore crate, you can't just pass a string
431 let path = global_ignore_path();
432
433 if !path.exists() {
434 let mut file = std::fs::File::create(path).unwrap();
435 for pattern in GLOBAL_IGNORE_PATTERNS {
436 file.write_all(pattern.as_bytes()).unwrap();
437 file.write_all(b"\n").unwrap();
438 }
439 }
440
441 global_ignore_path()
442}
443
444pub fn build_walk(dir: &Path) -> Walk {
445 let path = create_global_ignore_file();
446 // Make sure it sorts alphabetically by default
447 let mut binding = WalkBuilder::new(dir);
448 let builder = binding.add_custom_ignore_filename(".continueignore");
449
450 builder.add_ignore(path);
451 builder.build()
452}
453
454fn sha1_hash(content: &str) -> ObjectHash {
455 let mut hasher = Sha1::new();
456 hasher.update(content);
457 hasher.finalize().into()
458}
459
460fn blob_hash(content: &str, file_ext: &str) -> ObjectHash {
461 sha1_hash(&format!("blob {file_ext} {content}"))
462}
463
464fn create_blob(filepath: &Path, parent: Option<ObjectHash>) -> Result<Blob> {
465 let content = std::fs::read_to_string(filepath)?;
466 let hash = blob_hash(
467 &content,
468 filepath.extension().map_or("", |ext| ext.to_str().unwrap()),
469 );
470 Ok(Blob {
471 parent,
472 hash,
473 path: filepath.to_str().unwrap().to_string(),
474 })
475}
476
477fn tree_hash(children: impl IntoIterator<Item = ObjectHash>) -> ObjectHash {
478 let mut hasher = Sha1::new();
479 hasher.update(b"tree");
480
481 // Note you're not just concatenating
482 for child in children {
483 hasher.update(child);
484 }
485 let result = hasher.finalize();
486 let hash_bytes: [u8; 20] = result.into();
487 hash_bytes
488}
489
490struct PreTree {
491 children: Vec<Object>,
492 path: String,
493}
494
495impl PreTree {
496 fn finalize(&self) -> Tree {
497 return Tree {
498 parent: None,
499 children: self.children.clone(),
500 hash: tree_hash(self.children.iter().map(Object::hash)),
501 path: self.path.clone(),
502 };
503 }
504}
505
506/// Compute merkle tree and all sub-objects
507/// The last element in the vector is the root of the tree
508pub fn compute_tree_for_dir(dir: &Path, _parent: Option<ObjectHash>) -> Result<Tree> {
509 let mut walk = build_walk(dir);
510 let root_entry = walk
511 .next() // This is just "."
512 .expect("Directory does not exist")
513 .expect("Error parsing directory");
514
515 // The last in the vector is the latest
516 // The first in the stack will end up being the root
517 let mut tree_stack: Vec<PreTree> = Vec::new();
518 tree_stack.push(PreTree {
519 children: Vec::new(),
520 path: root_entry.path().to_str().unwrap().to_string(),
521 });
522 let mut current_dir = dir.to_path_buf();
523
524 for entry in walk {
525 let entry = entry.unwrap();
526 let path = entry.path();
527 let metadata = entry.metadata().unwrap();
528
529 // Check whether current_dir is complete
530 while !path.starts_with(current_dir.as_path()) {
531 // We've moved up by (at least) one directory
532 // We need to pop the current directory off the stack
533 // and create a tree object for it
534 let partial_tree = tree_stack.pop().unwrap();
535 tree_stack
536 .last_mut()
537 .unwrap()
538 .children
539 .push(Object::Tree(partial_tree.finalize()));
540
541 // Update current_dir
542 current_dir = current_dir.parent().unwrap().to_path_buf();
543 }
544
545 if metadata.is_dir() {
546 let partial_tree = PreTree {
547 children: Vec::new(),
548 path: path.to_str().unwrap().to_string(),
549 };
550 tree_stack.push(partial_tree);
551 current_dir = path.to_owned();
552 } else {
553 match create_blob(path, None) {
554 Ok(blob) => {
555 tree_stack
556 .last_mut()
557 .unwrap()
558 .children
559 .push(Object::Blob(blob));
560 }
561 Err(_err) => {
562 // Not UTF-8 formatted. Binary file. Ignore.
563 }
564 }
565 }
566 }
567
568 // Collapse the stack upward
569 while tree_stack.len() > 1 {
570 let partial_tree = tree_stack.pop().unwrap();
571 tree_stack
572 .last_mut()
573 .unwrap()
574 .children
575 .push(Object::Tree(partial_tree.finalize()));
576 }
577
578 assert!(
579 tree_stack.len() == 1,
580 "Tree stack should only have exactly one element"
581 );
582
583 // Convert to Tree
584 let mut root_tree = tree_stack.pop().unwrap().finalize();
585
586 // Go through and update the parent of each child
587 root_tree.set_childrens_parent();
588
589 Ok(root_tree)
590}
591
592// Tests
593#[cfg(test)]
594mod tests {
595 use super::*;
596 use crate::utils::TempDirBuilder;
597 use std::fs::{self};
598
599 #[test]
600 fn test_compute_tree_for_temp_dir() {
601 let temp_dir = TempDirBuilder::new()
602 .add("dir1/file1.txt", "Hello, world!")
603 .add("dir1/file2.txt", "Hello, world!")
604 .add("dir2/file3.txt", "Hello, world!")
605 .add("dir2/subdir/continue.py", "[continue for i in range(10)]")
606 .add("__init__.py", "a = 5")
607 .create();
608
609 let tree = compute_tree_for_dir(temp_dir.path(), None).expect("Failed to compute tree");
610
611 // Check that every node but the root has a parent, matching that parent's hash
612 tree.walk(&mut |obj| match obj {
613 Object::Tree(tree) => {
614 for child in &tree.children {
615 match child {
616 Object::Tree(child_tree) => {
617 assert_eq!(child_tree.parent, Some(tree.hash));
618 }
619 Object::Blob(child_blob) => {
620 assert_eq!(child_blob.parent, Some(tree.hash));
621 }
622 }
623 }
624 }
625 Object::Blob(_) => {}
626 });
627
628 // TODO: If a folder was removed, and another added, but they have the same hash, you should then assume it was renamed
629
630 // Make sure hash was calculated in same way as always
631 assert_eq!(
632 hash_string(tree.hash),
633 "cb6bf3834fdc9c356a23fca2cb6f6d7a571474c4"
634 );
635
636 let temp_dir2 = TempDirBuilder::new()
637 .add("dir1/file1.txt", "Hello, world!")
638 .add("dir1/file2.txt", "Hello, world!")
639 .add("dir2/file3.txt", "Hello, world!")
640 .add("dir2/subdir/continue.py", "[continue for i in range(11)]") // Difference here
641 .add("__init__.py", "a = 5")
642 .create();
643
644 let tree2 = compute_tree_for_dir(temp_dir2.path(), None).expect("Failed to compute tree");
645
646 // Make sure hash was calculated in same way as always
647
648 // Check that certain nodes have different hashes
649 assert_ne!(tree.hash, tree2.hash);
650 assert_ne!(tree.children[0].hash(), tree2.children[0].hash());
651 assert_eq!(tree.children[1].hash(), tree2.children[1].hash());
652 assert_eq!(tree.children[2].hash(), tree2.children[2].hash());
653
654 // Make a small change and recompute the tree
655 let path = temp_dir.path().join("dir2/subdir/continue.py");
656 fs::write(path, "[continue for i in range(11)]").expect("Failed to write to file");
657 let tree_prime =
658 compute_tree_for_dir(temp_dir.path(), None).expect("Failed to compute tree");
659
660 // All nodes up the tree from dir2/subdir/continue.py should be marked as changed
661 let (add, remove) = diff(&tree, &tree_prime);
662 assert_eq!(add.len(), 4);
663 assert_eq!(remove.len(), 4);
664
665 // Try adding a file at the root level
666 let path = temp_dir.path().join("new_file.txt");
667 fs::write(path, "42").expect("Failed to write to file");
668 let tree_prime_prime =
669 compute_tree_for_dir(temp_dir.path(), None).expect("Failed to compute tree");
670
671 // Compare original and ''
672 let (add, remove) = diff(&tree, &tree_prime_prime);
673 assert_eq!(add.len(), 5);
674 assert_eq!(remove.len(), 4);
675
676 // Compare ' and ''
677 let (add, remove) = diff(&tree_prime, &tree_prime_prime);
678 assert_eq!(add.len(), 2);
679 assert_eq!(remove.len(), 1);
680
681 temp_dir.close().expect("Failed to clean up temp dir");
682 temp_dir2.close().expect("Failed to clean up temp dir");
683 }
684}