⚡️ merkle tree index caching
This commit is contained in:
parent
685e105126
commit
4262ea016e
12 changed files with 2176 additions and 4 deletions
3
.vscode/settings.json
vendored
3
.vscode/settings.json
vendored
|
|
@ -1,4 +1,5 @@
|
|||
{
|
||||
"python.defaultInterpreterPath": "${workspaceFolder}/server/.venv/bin/python3",
|
||||
"continue.showInlineTip": false
|
||||
"continue.showInlineTip": false,
|
||||
"rust-analyzer.linkedProjects": ["./server/Cargo.toml"]
|
||||
}
|
||||
|
|
|
|||
1015
server/Cargo.lock
generated
Normal file
1015
server/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load diff
29
server/Cargo.toml
Normal file
29
server/Cargo.toml
Normal file
|
|
@ -0,0 +1,29 @@
|
|||
# If you already have [package] information in `Cargo.toml`, you can ignore
|
||||
# this section!
|
||||
[package]
|
||||
# `name` here is name of the package.
|
||||
name = "continuedev"
|
||||
# these are good defaults:
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[lib]
|
||||
# The name of the native library. This is the name which will be used in Python to import the
|
||||
# library (i.e. `import string_sum`). If you change this, you must also change the name of the
|
||||
# `#[pymodule]` in `src/lib.rs`.
|
||||
name = "continuedev"
|
||||
|
||||
# "cdylib" is necessary to produce a shared library for Python to import from.
|
||||
crate-type = ["cdylib"]
|
||||
|
||||
[dependencies]
|
||||
hex-literal = "0.4.1"
|
||||
homedir = "0.2.1"
|
||||
ignore = "0.4.20"
|
||||
pyo3 = { version = "0.20.0", features = ["extension-module"] }
|
||||
serde = { version = "1.0.192", features = ["derive"] }
|
||||
serde_json = "1.0.108"
|
||||
sha1 = "0.10.6"
|
||||
|
||||
[dev-dependencies]
|
||||
tempfile = "3.8.1"
|
||||
20
server/continuedev/continuedev.py
Normal file
20
server/continuedev/continuedev.py
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
import asyncio
|
||||
from typing import Union
|
||||
|
||||
from .core.config import ContinueConfig
|
||||
from .core.main import Step
|
||||
|
||||
# from .headless import start_headless_session
|
||||
|
||||
|
||||
def run(step_or_config: Union[Step, ContinueConfig]):
|
||||
if isinstance(step_or_config, ContinueConfig):
|
||||
config = step_or_config
|
||||
else:
|
||||
config = ContinueConfig()
|
||||
config.steps_on_startup = [step_or_config]
|
||||
|
||||
loop = asyncio.get_event_loop()
|
||||
# loop.run_until_complete(start_headless_session(config=config))
|
||||
tasks = asyncio.all_tasks(loop)
|
||||
loop.run_until_complete(asyncio.gather(*tasks))
|
||||
5
server/continuedev/continuedev.pyi
Normal file
5
server/continuedev/continuedev.pyi
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
from typing import List, Tuple
|
||||
|
||||
def sync_results(
|
||||
dir: str, branch: str
|
||||
) -> Tuple[List[Tuple[str, str]], List[Tuple[str, str]]]: ...
|
||||
0
server/continuedev/py.typed
Normal file
0
server/continuedev/py.typed
Normal file
31
server/poetry.lock
generated
31
server/poetry.lock
generated
|
|
@ -1615,6 +1615,35 @@ files = [
|
|||
[package.dependencies]
|
||||
traitlets = "*"
|
||||
|
||||
[[package]]
|
||||
name = "maturin"
|
||||
version = "1.3.1"
|
||||
description = "Build and publish crates with pyo3, rust-cpython and cffi bindings as well as rust binaries as python packages"
|
||||
optional = false
|
||||
python-versions = ">=3.7"
|
||||
files = [
|
||||
{file = "maturin-1.3.1-py3-none-linux_armv6l.whl", hash = "sha256:925f8324d9bbe8fad90b73ebc6c7f6f594645e7f13af50bded72606b6c233208"},
|
||||
{file = "maturin-1.3.1-py3-none-macosx_10_7_x86_64.whl", hash = "sha256:f3c2c694b76e63e78c353e4a2a74f8baff5ac6becf807f23435d28e47a567d63"},
|
||||
{file = "maturin-1.3.1-py3-none-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:13188296f389d05043b8bd2265df66692490b61ba219ae7d5abc09e81e5659ce"},
|
||||
{file = "maturin-1.3.1-py3-none-manylinux_2_12_i686.manylinux2010_i686.musllinux_1_1_i686.whl", hash = "sha256:11bbf9978695ac066729af08bc24123317ca3fad51757b0fbdfe811212896714"},
|
||||
{file = "maturin-1.3.1-py3-none-manylinux_2_12_x86_64.manylinux2010_x86_64.musllinux_1_1_x86_64.whl", hash = "sha256:d566d2f424fa3f5cd6bd3033fd300b80654884abd061bd53c68f4717753e7d58"},
|
||||
{file = "maturin-1.3.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.musllinux_1_1_aarch64.whl", hash = "sha256:c0e2b8171f1a70270b86ed72397ba548e3bf4d914f24cd50a228ed85a9d5e914"},
|
||||
{file = "maturin-1.3.1-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.musllinux_1_1_armv7l.whl", hash = "sha256:804c6706588a9ca78f18f1a10adf9d24099b9cd3c2917628063ba8d4418b8a50"},
|
||||
{file = "maturin-1.3.1-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.musllinux_1_1_ppc64le.whl", hash = "sha256:c533d02563bb185125488cdcf161cc6ba2cdd4812ebff1b6504d1b29880ba1f8"},
|
||||
{file = "maturin-1.3.1-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:066b0c515505d4a4c526a9afc26fad4f010972d60937530dc4949dda0f49aa61"},
|
||||
{file = "maturin-1.3.1-py3-none-win32.whl", hash = "sha256:4835c332e3b632547db12e6a70abc18cb90ba9df06200dd9a7cc73424919901d"},
|
||||
{file = "maturin-1.3.1-py3-none-win_amd64.whl", hash = "sha256:871268417d6b3e2b46018c54a0522efc018bc4918b885d005df90b338e0674c7"},
|
||||
{file = "maturin-1.3.1-py3-none-win_arm64.whl", hash = "sha256:659a601c27984a50350f792447ff65ec60309423747f5304c98cb7b7fbb63d39"},
|
||||
{file = "maturin-1.3.1.tar.gz", hash = "sha256:efa194e99ae5fff185263d8244acacb12ae256ea73aba62c9446f6075ffc7ac1"},
|
||||
]
|
||||
|
||||
[package.dependencies]
|
||||
tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""}
|
||||
|
||||
[package.extras]
|
||||
patchelf = ["patchelf"]
|
||||
zig = ["ziglang (>=0.10.0,<0.11.0)"]
|
||||
|
||||
[[package]]
|
||||
name = "mdurl"
|
||||
version = "0.1.2"
|
||||
|
|
@ -4260,4 +4289,4 @@ testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "p
|
|||
[metadata]
|
||||
lock-version = "2.0"
|
||||
python-versions = "^3.8.1"
|
||||
content-hash = "05cdea7254c872a290327729b8cea62ad62a865b9a528823e109fd51d2ded9cf"
|
||||
content-hash = "62e8f3ea636a605897e697ad7ce0d49dad49a44e8cbe0103dc731efba9669664"
|
||||
|
|
|
|||
|
|
@ -43,6 +43,7 @@ pathspec = "^0.11.2"
|
|||
tqdm = "^4.66.1"
|
||||
html2text = "^2020.1.16"
|
||||
pygit2 = "^1.13.2"
|
||||
maturin = "^1.3.1"
|
||||
|
||||
[tool.poetry.scripts]
|
||||
typegen = "continuedev.models.generate_json_schema:main"
|
||||
|
|
@ -53,5 +54,19 @@ pytest-asyncio = "^0.21.1"
|
|||
ipykernel = "^6.26.0"
|
||||
|
||||
[build-system]
|
||||
requires = ["poetry-core"]
|
||||
build-backend = "poetry.core.masonry.api"
|
||||
requires = ["poetry-core", "maturin>=1,<2"]
|
||||
# build-backend = "poetry.core.masonry.api"
|
||||
build-backend = "maturin"
|
||||
|
||||
[project]
|
||||
name = "continuedev"
|
||||
version = "0.1.90"
|
||||
description = ""
|
||||
authors = [{ name= "Nate Sesti", email = "<sestinj@gmail.com>" }]
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8.1"
|
||||
classifiers = [
|
||||
"Programming Language :: Rust",
|
||||
"Programming Language :: Python :: Implementation :: CPython",
|
||||
"Programming Language :: Python :: Implementation :: PyPy",
|
||||
]
|
||||
102
server/src/gitignore.rs
Normal file
102
server/src/gitignore.rs
Normal file
|
|
@ -0,0 +1,102 @@
|
|||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io::{self, Read};
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub fn local_find_gitignores(workspace_dir: &Path) -> io::Result<HashMap<PathBuf, String>> {
|
||||
let mut gitignores = HashMap::new();
|
||||
for entry in fs::read_dir(workspace_dir)? {
|
||||
let entry = entry?;
|
||||
let path = entry.path();
|
||||
if path.is_dir() {
|
||||
gitignores.extend(local_find_gitignores(&path)?);
|
||||
} else {
|
||||
match path.file_name().and_then(|name| name.to_str()) {
|
||||
Some(file_name) if file_name.ends_with(".gitignore") || file_name.ends_with(".continueignore") => {
|
||||
let mut contents = String::new();
|
||||
fs::File::open(&path)?.read_to_string(&mut contents)?;
|
||||
gitignores.insert(path, contents);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(gitignores)
|
||||
}
|
||||
|
||||
fn main() -> io::Result<()> {
|
||||
let workspace_dir = Path::new("path/to/workspace");
|
||||
let gitignore_map = local_find_gitignores(workspace_dir)?;
|
||||
|
||||
// Print out the result (optional)
|
||||
for (path, contents) in gitignore_map {
|
||||
println!("{}:\n{}", path.display(), contents);
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use tempfile::tempdir;
|
||||
|
||||
#[test]
|
||||
fn test_local_find_gitignores() -> io::Result<()> {
|
||||
// Create a temporary directory for the test
|
||||
let temp_dir = tempdir()?;
|
||||
let temp_path = temp_dir.path();
|
||||
|
||||
// Create some directories and .gitignore/.continueignore files
|
||||
let dir_structure = [
|
||||
("dir1", Some(".gitignore"), "node_modules/"),
|
||||
("dir2", Some(".continueignore"), "target/"),
|
||||
("dir3", None, ""),
|
||||
];
|
||||
|
||||
for (dir, file, contents) in dir_structure.iter() {
|
||||
let dir_path = temp_path.join(dir);
|
||||
fs::create_dir(&dir_path)?;
|
||||
|
||||
if let Some(file_name) = file {
|
||||
let file_path = dir_path.join(file_name);
|
||||
let mut file = File::create(file_path)?;
|
||||
writeln!(file, "{}", contents)?;
|
||||
}
|
||||
}
|
||||
|
||||
// Call the function under test
|
||||
let gitignores = local_find_gitignores(temp_path)?;
|
||||
|
||||
// Verify that the returned HashMap contains the correct paths and contents
|
||||
for (dir, file, contents) in dir_structure.iter() {
|
||||
if let Some(file_name) = file {
|
||||
let file_path = temp_path.join(dir).join(file_name);
|
||||
assert!(gitignores.contains_key(&file_path));
|
||||
assert_eq!(gitignores.get(&file_path).unwrap().trim(), *contents);
|
||||
}
|
||||
}
|
||||
|
||||
// Cleanup the temporary directory automatically
|
||||
temp_dir.close()?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_in_continue_repo() -> io::Result<()> {
|
||||
// Get the current directory
|
||||
let current_dir = std::env::current_dir()?;
|
||||
let parent_dir = current_dir.parent().unwrap();
|
||||
let gitignores = local_find_gitignores(&parent_dir)?;
|
||||
|
||||
// Verify that the returned HashMap contains the correct paths and contents
|
||||
let top_level_gitignore = parent_dir.join(".gitignore");
|
||||
assert!(gitignores.contains_key(&top_level_gitignore));
|
||||
assert!(gitignores[&top_level_gitignore].contains(".tiktoken_cache"));
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
19
server/src/lib.rs
Normal file
19
server/src/lib.rs
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
use pyo3::{exceptions, prelude::*};
|
||||
use std::path::Path;
|
||||
mod gitignore;
|
||||
mod sync;
|
||||
|
||||
#[pyfunction]
|
||||
fn sync_results(
|
||||
dir: String,
|
||||
branch: String,
|
||||
) -> PyResult<(Vec<(String, String)>, Vec<(String, String)>)> {
|
||||
return sync::sync(Path::new(&dir), Some(&branch))
|
||||
.map_err(|err| PyErr::new::<exceptions::PyException, _>(format!("{}", err)));
|
||||
}
|
||||
|
||||
#[pymodule]
|
||||
fn continuedev(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
|
||||
m.add_function(wrap_pyfunction!(sync_results, m)?)?;
|
||||
Ok(())
|
||||
}
|
||||
620
server/src/sync/merkle.rs
Normal file
620
server/src/sync/merkle.rs
Normal file
|
|
@ -0,0 +1,620 @@
|
|||
use ignore::{Walk, WalkBuilder};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sha1::{Digest, Sha1};
|
||||
use std::{
|
||||
io::{self, Read, Result, Write},
|
||||
path::Path,
|
||||
};
|
||||
|
||||
pub type ObjectHash = [u8; 20];
|
||||
|
||||
pub fn hash_string(hash: ObjectHash) -> String {
|
||||
let mut result = String::new();
|
||||
for byte in hash {
|
||||
result.push_str(&format!("{:02x}", byte));
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Tree {
|
||||
parent: Option<ObjectHash>,
|
||||
children: Vec<Object>,
|
||||
hash: ObjectHash,
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Deserialize)]
|
||||
struct SerializeableNode {
|
||||
parent: Option<ObjectHash>,
|
||||
|
||||
/// Blobs would have no children
|
||||
children: Option<Vec<ObjectHash>>,
|
||||
hash: ObjectHash,
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Blob {
|
||||
parent: Option<ObjectHash>,
|
||||
hash: ObjectHash,
|
||||
path: String,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
enum Object {
|
||||
Tree(Tree),
|
||||
Blob(Blob),
|
||||
}
|
||||
|
||||
pub struct ObjDescription {
|
||||
pub hash: ObjectHash,
|
||||
pub path: String,
|
||||
pub is_blob: bool,
|
||||
}
|
||||
|
||||
impl Object {
|
||||
fn hash(&self) -> ObjectHash {
|
||||
match self {
|
||||
Object::Tree(tree) => tree.hash,
|
||||
Object::Blob(blob) => blob.hash,
|
||||
}
|
||||
}
|
||||
|
||||
fn path(&self) -> &String {
|
||||
match self {
|
||||
Object::Tree(tree) => &tree.path,
|
||||
Object::Blob(blob) => &blob.path,
|
||||
}
|
||||
}
|
||||
|
||||
fn json_for_obj(&self) -> String {
|
||||
match self {
|
||||
Object::Tree(tree) => tree.json_for_obj(),
|
||||
Object::Blob(blob) => blob.json_for_obj(),
|
||||
}
|
||||
}
|
||||
|
||||
fn descr(&self) -> ObjDescription {
|
||||
return ObjDescription {
|
||||
hash: self.hash(),
|
||||
path: self.path().clone(),
|
||||
is_blob: match self {
|
||||
Object::Tree(_) => false,
|
||||
Object::Blob(_) => true,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/// Return a tuple of (paths to add, paths to remove)
|
||||
fn diff(&self, other: &Object) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
|
||||
let mut add: Vec<ObjDescription> = Vec::new();
|
||||
let mut remove: Vec<ObjDescription> = Vec::new();
|
||||
|
||||
if self.hash() == other.hash() {
|
||||
return (add, remove);
|
||||
}
|
||||
|
||||
match (self, other) {
|
||||
(Object::Tree(self_tree), Object::Tree(other_tree)) => {
|
||||
// This is where you recurse like below
|
||||
let (child_add, child_remove) = self_tree.diff_children(other_tree);
|
||||
add.push(other_tree.descr());
|
||||
remove.push(self_tree.descr());
|
||||
add.extend(child_add);
|
||||
remove.extend(child_remove);
|
||||
}
|
||||
(Object::Blob(self_blob), Object::Blob(other_blob)) => {
|
||||
add.push(self_blob.descr());
|
||||
remove.push(other_blob.descr());
|
||||
}
|
||||
(Object::Blob(self_blob), Object::Tree(other_tree)) => {
|
||||
// Remove blob, add entire new tree
|
||||
remove.push(self_blob.descr());
|
||||
add.extend(other_tree.all_obj_descriptions());
|
||||
}
|
||||
(Object::Tree(self_tree), Object::Blob(other_blob)) => {
|
||||
// Remove entire old tree, add blob
|
||||
remove.extend(self_tree.all_obj_descriptions());
|
||||
add.push(other_blob.descr());
|
||||
}
|
||||
}
|
||||
|
||||
return (add, remove);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn diff(old_tree: &Tree, new_tree: &Tree) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
|
||||
let mut add: Vec<ObjDescription> = Vec::new();
|
||||
let mut remove: Vec<ObjDescription> = Vec::new();
|
||||
|
||||
if old_tree.hash == new_tree.hash {
|
||||
return (add, remove);
|
||||
}
|
||||
|
||||
let (child_add, child_remove) = old_tree.diff_children(new_tree);
|
||||
|
||||
add.push(new_tree.descr());
|
||||
remove.push(old_tree.descr());
|
||||
add.extend(child_add);
|
||||
remove.extend(child_remove);
|
||||
|
||||
return (add, remove);
|
||||
}
|
||||
|
||||
impl Blob {
|
||||
fn json_for_obj(&self) -> String {
|
||||
let node = SerializeableNode {
|
||||
parent: self.parent,
|
||||
children: None,
|
||||
hash: self.hash,
|
||||
path: self.path.clone(),
|
||||
};
|
||||
|
||||
let mut json = serde_json::to_string(&node).unwrap();
|
||||
json.push_str("\n");
|
||||
return json;
|
||||
}
|
||||
|
||||
fn descr(&self) -> ObjDescription {
|
||||
return ObjDescription {
|
||||
hash: self.hash,
|
||||
path: self.path.clone(),
|
||||
is_blob: true,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
enum DiffType {
|
||||
Add,
|
||||
Update,
|
||||
Remove,
|
||||
}
|
||||
impl Tree {
|
||||
fn descr(&self) -> ObjDescription {
|
||||
return ObjDescription {
|
||||
hash: self.hash,
|
||||
path: self.path.clone(),
|
||||
is_blob: false,
|
||||
};
|
||||
}
|
||||
|
||||
fn json_for_node(&self) -> String {
|
||||
let node = SerializeableNode {
|
||||
parent: self.parent,
|
||||
children: Some(self.children.iter().map(|child| child.hash()).collect()),
|
||||
hash: self.hash,
|
||||
path: self.path.clone(),
|
||||
};
|
||||
|
||||
let mut json = serde_json::to_string(&node).unwrap();
|
||||
json.push_str("\n");
|
||||
return json;
|
||||
}
|
||||
|
||||
fn json_for_obj(&self) -> String {
|
||||
let mut result = String::new();
|
||||
result.push_str(&self.json_for_node());
|
||||
|
||||
for child in &self.children {
|
||||
result.push_str(&child.json_for_obj());
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
fn obj_from_jsonl(lines: &mut std::str::Lines, first_line: Option<SerializeableNode>) -> Tree {
|
||||
let root_node = match first_line {
|
||||
Some(line) => line,
|
||||
None => serde_json::from_str(lines.next().unwrap()).unwrap(),
|
||||
};
|
||||
|
||||
let mut children: Vec<Object> = Vec::new();
|
||||
for child_hash in root_node.children.unwrap() {
|
||||
let child_jsonl = lines.next().unwrap();
|
||||
let child_node: SerializeableNode = serde_json::from_str(child_jsonl).unwrap();
|
||||
match child_node.children {
|
||||
Some(_) => {
|
||||
let child = Tree::obj_from_jsonl(lines, Some(child_node));
|
||||
children.push(Object::Tree(child));
|
||||
}
|
||||
None => {
|
||||
let child = Blob {
|
||||
parent: child_node.parent,
|
||||
hash: child_node.hash,
|
||||
path: child_node.path,
|
||||
};
|
||||
children.push(Object::Blob(child));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return Tree {
|
||||
parent: root_node.parent,
|
||||
children,
|
||||
hash: root_node.hash,
|
||||
path: root_node.path,
|
||||
};
|
||||
}
|
||||
|
||||
/// Persist the tree to disk as JSONL
|
||||
pub fn persist(&self, filepath: &Path) {
|
||||
if let Some(dir) = filepath.parent() {
|
||||
std::fs::create_dir_all(dir)
|
||||
.expect(format!("Failed to create dir {}", dir.display()).as_str());
|
||||
}
|
||||
let mut file = std::fs::File::create(filepath).unwrap();
|
||||
file.write_all(self.json_for_obj().as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
/// Load the tree from JSONL file
|
||||
pub fn load(filepath: &Path) -> Result<Tree> {
|
||||
let mut file = std::fs::File::open(filepath)?;
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents)?;
|
||||
let mut lines = contents.lines();
|
||||
return Ok(Tree::obj_from_jsonl(&mut lines, None));
|
||||
}
|
||||
|
||||
pub fn empty() -> Tree {
|
||||
return Tree {
|
||||
parent: None,
|
||||
children: Vec::new(),
|
||||
hash: tree_hash(Vec::new()),
|
||||
path: String::new(),
|
||||
};
|
||||
}
|
||||
|
||||
fn set_childrens_parent(&mut self) {
|
||||
for child in &mut self.children {
|
||||
match child {
|
||||
Object::Tree(tree) => {
|
||||
tree.parent = Some(self.hash);
|
||||
tree.set_childrens_parent();
|
||||
}
|
||||
Object::Blob(blob) => {
|
||||
blob.parent = Some(self.hash);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn walk(&self, callback: &mut dyn FnMut(&Object)) {
|
||||
callback(&Object::Tree(self.clone()));
|
||||
for child in &self.children {
|
||||
match child {
|
||||
Object::Tree(tree) => tree.walk(callback),
|
||||
Object::Blob(blob) => callback(&Object::Blob(blob.clone())),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn all_obj_descriptions(&self) -> Vec<ObjDescription> {
|
||||
let mut result = Vec::new();
|
||||
self.walk(&mut |obj| result.push(obj.descr()));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Return a list of paths that have changed and the type of change (0 = add, 1 = update, 2 = remove)
|
||||
/// other is considered the "new" tree
|
||||
fn diff_children(&self, other: &Tree) -> (Vec<ObjDescription>, Vec<ObjDescription>) {
|
||||
let mut add = Vec::new();
|
||||
let mut remove = Vec::new();
|
||||
|
||||
// There are situations where the names of two folders could be swapped and then each slightly changed
|
||||
// where you would need some heuristics to avoid throwing them out...but...don't worry for now. Just match by path
|
||||
|
||||
let mut old_path_to_object: std::collections::HashMap<String, &Object> = self
|
||||
.children
|
||||
.iter()
|
||||
.map(|child| (child.path().clone(), child))
|
||||
.collect();
|
||||
|
||||
for child in &other.children {
|
||||
if let Some(old_child) = old_path_to_object.remove(child.path()) {
|
||||
// If the same path name exists in old children
|
||||
let (child_add, child_remove) = old_child.diff(child);
|
||||
add.extend(child_add);
|
||||
remove.extend(child_remove);
|
||||
} else {
|
||||
// Name didn't exist before. Add all
|
||||
match child {
|
||||
Object::Tree(tree) => {
|
||||
add.extend(tree.all_obj_descriptions());
|
||||
}
|
||||
Object::Blob(blob) => {
|
||||
add.push(blob.descr());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove - along with all children
|
||||
for (path, obj) in old_path_to_object {
|
||||
match obj {
|
||||
Object::Tree(tree) => tree.walk(&mut |obj| {
|
||||
remove.extend(tree.all_obj_descriptions());
|
||||
}),
|
||||
Object::Blob(_) => remove.push(obj.descr()),
|
||||
}
|
||||
}
|
||||
|
||||
return (add, remove);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn build_walk(dir: &Path) -> Walk {
|
||||
// Make sure it sorts alphabetically by default
|
||||
return WalkBuilder::new(dir)
|
||||
.add_custom_ignore_filename(".continueignore")
|
||||
.build();
|
||||
}
|
||||
|
||||
fn sha1_hash(content: &str) -> ObjectHash {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update(content);
|
||||
let result = hasher.finalize();
|
||||
let hash_bytes: [u8; 20] = result.into();
|
||||
return hash_bytes;
|
||||
}
|
||||
|
||||
fn blob_hash(content: &str, file_ext: &str) -> ObjectHash {
|
||||
return sha1_hash(&format!("blob {} {}", file_ext, content));
|
||||
}
|
||||
|
||||
fn create_blob(filepath: &Path, parent: Option<ObjectHash>) -> Result<Blob> {
|
||||
let content = std::fs::read_to_string(filepath)?;
|
||||
let hash = blob_hash(
|
||||
&content,
|
||||
match filepath.extension() {
|
||||
Some(ext) => ext.to_str().unwrap(),
|
||||
None => "",
|
||||
},
|
||||
);
|
||||
return Ok(Blob {
|
||||
parent: parent,
|
||||
hash: hash,
|
||||
path: filepath.to_str().unwrap().to_string(),
|
||||
});
|
||||
}
|
||||
|
||||
fn tree_hash(children: Vec<ObjectHash>) -> ObjectHash {
|
||||
let mut hasher = Sha1::new();
|
||||
hasher.update("tree".as_bytes());
|
||||
|
||||
// Note you're not just concatenating
|
||||
for child in &children {
|
||||
hasher.update(child);
|
||||
}
|
||||
let result = hasher.finalize();
|
||||
let hash_bytes: [u8; 20] = result.into();
|
||||
return hash_bytes;
|
||||
}
|
||||
|
||||
struct PreTree {
|
||||
children: Vec<Object>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl PreTree {
|
||||
fn finalize(&self) -> Tree {
|
||||
return Tree {
|
||||
parent: None,
|
||||
children: self.children.clone(),
|
||||
hash: tree_hash(self.children.iter().map(|child| child.hash()).collect()),
|
||||
path: self.path.clone(),
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
/// Compute merkle tree and all sub-objects
|
||||
/// The last element in the vector is the root of the tree
|
||||
pub fn compute_tree_for_dir(dir: &Path, parent: Option<ObjectHash>) -> Result<Tree> {
|
||||
let mut walk = build_walk(dir);
|
||||
let root_entry = walk
|
||||
.next() // This is just "."
|
||||
.expect("Directory does not exist")
|
||||
.expect("Error parsing directory");
|
||||
|
||||
// The last in the vector is the latest
|
||||
// The first in the stack will end up being the root
|
||||
let mut tree_stack: Vec<PreTree> = Vec::new();
|
||||
tree_stack.push(PreTree {
|
||||
children: Vec::new(),
|
||||
path: root_entry.path().to_str().unwrap().to_string(),
|
||||
});
|
||||
let mut current_dir = dir.to_path_buf();
|
||||
|
||||
for entry in walk {
|
||||
let entry = entry.unwrap();
|
||||
let path = entry.path();
|
||||
let metadata = entry.metadata().unwrap();
|
||||
|
||||
// Check whether current_dir is complete
|
||||
while !path.starts_with(current_dir.as_path()) {
|
||||
// We've moved up by (at least) one directory
|
||||
// We need to pop the current directory off the stack
|
||||
// and create a tree object for it
|
||||
let partial_tree = tree_stack.pop().unwrap();
|
||||
tree_stack
|
||||
.last_mut()
|
||||
.unwrap()
|
||||
.children
|
||||
.push(Object::Tree(partial_tree.finalize()));
|
||||
|
||||
// Update current_dir
|
||||
current_dir = current_dir.parent().unwrap().to_path_buf();
|
||||
}
|
||||
|
||||
if metadata.is_dir() {
|
||||
let partial_tree = PreTree {
|
||||
children: Vec::new(),
|
||||
path: path.to_str().unwrap().to_string(),
|
||||
};
|
||||
tree_stack.push(partial_tree);
|
||||
current_dir = path.to_owned();
|
||||
} else {
|
||||
match create_blob(path, None) {
|
||||
Ok(blob) => {
|
||||
tree_stack
|
||||
.last_mut()
|
||||
.unwrap()
|
||||
.children
|
||||
.push(Object::Blob(blob));
|
||||
}
|
||||
Err(err) => {
|
||||
// Not UTF-8 formatted. Binary file. Ignore.
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Collapse the stack upward
|
||||
while tree_stack.len() > 1 {
|
||||
let partial_tree = tree_stack.pop().unwrap();
|
||||
tree_stack
|
||||
.last_mut()
|
||||
.unwrap()
|
||||
.children
|
||||
.push(Object::Tree(partial_tree.finalize()));
|
||||
}
|
||||
|
||||
assert!(
|
||||
tree_stack.len() == 1,
|
||||
"Tree stack should only have exactly one element"
|
||||
);
|
||||
|
||||
// Convert to Tree
|
||||
let mut root_tree = tree_stack.pop().unwrap().finalize();
|
||||
|
||||
// Go through and update the parent of each child
|
||||
root_tree.set_childrens_parent();
|
||||
|
||||
return Ok(root_tree);
|
||||
}
|
||||
|
||||
// Tests
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs::{self, File};
|
||||
use std::io::Write;
|
||||
use tempfile::{tempdir, Builder};
|
||||
|
||||
struct TempDirBuilder {
|
||||
files: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
impl TempDirBuilder {
|
||||
fn new() -> TempDirBuilder {
|
||||
return TempDirBuilder { files: Vec::new() };
|
||||
}
|
||||
|
||||
fn add(&mut self, path: &str, content: &str) -> &mut TempDirBuilder {
|
||||
self.files.push((path.to_string(), content.to_string()));
|
||||
return self;
|
||||
}
|
||||
|
||||
fn create(&self) -> tempfile::TempDir {
|
||||
let temp_dir = tempdir().expect("Failed to create temp dir");
|
||||
|
||||
for (path, content) in &self.files {
|
||||
let file_path = temp_dir.path().join(path);
|
||||
if let Some(dir) = file_path.parent() {
|
||||
fs::create_dir_all(dir).expect("Failed to create directory");
|
||||
}
|
||||
let mut file = File::create(&file_path).expect("Failed to create test file");
|
||||
writeln!(file, "{}", content).expect("Failed to write to test file");
|
||||
}
|
||||
|
||||
return temp_dir;
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_compute_tree_for_temp_dir() {
|
||||
let temp_dir = TempDirBuilder::new()
|
||||
.add("dir1/file1.txt", "Hello, world!")
|
||||
.add("dir1/file2.txt", "Hello, world!")
|
||||
.add("dir2/file3.txt", "Hello, world!")
|
||||
.add("dir2/subdir/continue.py", "[continue for i in range(10)]")
|
||||
.add("__init__.py", "a = 5")
|
||||
.create();
|
||||
|
||||
let tree = compute_tree_for_dir(temp_dir.path(), None).expect("Failed to compute tree");
|
||||
|
||||
// Check that every node but the root has a parent, matching that parent's hash
|
||||
tree.walk(&mut |obj| match obj {
|
||||
Object::Tree(tree) => {
|
||||
for child in &tree.children {
|
||||
match child {
|
||||
Object::Tree(child_tree) => {
|
||||
assert_eq!(child_tree.parent, Some(tree.hash));
|
||||
}
|
||||
Object::Blob(child_blob) => {
|
||||
assert_eq!(child_blob.parent, Some(tree.hash));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Object::Blob(_) => {}
|
||||
});
|
||||
|
||||
// TODO: If a folder was removed, and another added, but they have the same hash, you should then assume it was renamed
|
||||
|
||||
// Make sure hash was calculated in same way as always
|
||||
assert_eq!(
|
||||
hash_string(tree.hash),
|
||||
"cb6bf3834fdc9c356a23fca2cb6f6d7a571474c4"
|
||||
);
|
||||
|
||||
let temp_dir2 = TempDirBuilder::new()
|
||||
.add("dir1/file1.txt", "Hello, world!")
|
||||
.add("dir1/file2.txt", "Hello, world!")
|
||||
.add("dir2/file3.txt", "Hello, world!")
|
||||
.add("dir2/subdir/continue.py", "[continue for i in range(11)]") // Difference here
|
||||
.add("__init__.py", "a = 5")
|
||||
.create();
|
||||
|
||||
let tree2 = compute_tree_for_dir(temp_dir2.path(), None).expect("Failed to compute tree");
|
||||
|
||||
// Make sure hash was calculated in same way as always
|
||||
|
||||
// Check that certain nodes have different hashes
|
||||
assert_ne!(tree.hash, tree2.hash);
|
||||
assert_ne!(tree.children[0].hash(), tree2.children[0].hash());
|
||||
assert_eq!(tree.children[1].hash(), tree2.children[1].hash());
|
||||
assert_eq!(tree.children[2].hash(), tree2.children[2].hash());
|
||||
|
||||
// Make a small change and recompute the tree
|
||||
let path = temp_dir.path().join("dir2/subdir/continue.py");
|
||||
fs::write(path, "[continue for i in range(11)]").expect("Failed to write to file");
|
||||
let tree_prime =
|
||||
compute_tree_for_dir(temp_dir.path(), None).expect("Failed to compute tree");
|
||||
|
||||
// All nodes up the tree from dir2/subdir/continue.py should be marked as changed
|
||||
let (add, remove) = diff(&tree, &tree_prime);
|
||||
assert_eq!(add.len(), 4);
|
||||
assert_eq!(remove.len(), 4);
|
||||
|
||||
// Try adding a file at the root level
|
||||
let path = temp_dir.path().join("new_file.txt");
|
||||
fs::write(path, "42").expect("Failed to write to file");
|
||||
let tree_prime_prime = compute_tree_for_dir(temp_dir.path(), None)
|
||||
.expect("Failed to compute tree")
|
||||
.clone();
|
||||
|
||||
// Compare original and ''
|
||||
let (add, remove) = diff(&tree, &tree_prime_prime);
|
||||
assert_eq!(add.len(), 5);
|
||||
assert_eq!(remove.len(), 4);
|
||||
|
||||
// Compare ' and ''
|
||||
let (add, remove) = diff(&tree_prime, &tree_prime_prime);
|
||||
assert_eq!(add.len(), 2);
|
||||
assert_eq!(remove.len(), 1);
|
||||
|
||||
temp_dir.close().expect("Failed to clean up temp dir");
|
||||
temp_dir2.close().expect("Failed to clean up temp dir");
|
||||
}
|
||||
}
|
||||
317
server/src/sync/mod.rs
Normal file
317
server/src/sync/mod.rs
Normal file
|
|
@ -0,0 +1,317 @@
|
|||
mod merkle;
|
||||
use homedir::get_my_home;
|
||||
use ignore;
|
||||
use merkle::{build_walk, compute_tree_for_dir, diff, hash_string, ObjectHash};
|
||||
use std::{
|
||||
fs::{File, OpenOptions},
|
||||
io::{BufRead, BufReader, Read, Seek, SeekFrom, Write},
|
||||
path::{Path, PathBuf},
|
||||
time::{SystemTime, UNIX_EPOCH},
|
||||
};
|
||||
|
||||
use self::merkle::{ObjDescription, Tree};
|
||||
|
||||
/// Stored in ~/.continue/index/.last_sync
|
||||
fn get_last_sync_time() -> u64 {
|
||||
// TODO: Error handle here
|
||||
let home = get_my_home().unwrap().unwrap();
|
||||
let path = home.join(".continue/index/.last_sync");
|
||||
|
||||
let mut file = File::open(path).unwrap();
|
||||
let mut contents = String::new();
|
||||
file.read_to_string(&mut contents).unwrap();
|
||||
|
||||
let last_sync_time = contents.parse::<u64>().unwrap();
|
||||
return last_sync_time;
|
||||
}
|
||||
|
||||
fn write_sync_time() {
|
||||
let home = get_my_home().unwrap().unwrap();
|
||||
let path = home.join(".continue/index/.last_sync");
|
||||
|
||||
let mut file = File::create(path).unwrap();
|
||||
let now = SystemTime::now()
|
||||
.duration_since(UNIX_EPOCH)
|
||||
.unwrap()
|
||||
.as_secs();
|
||||
file.write_all(now.to_string().as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
/// Use stat to find files since last sync time
|
||||
pub fn get_modified_files(dir: &Path) -> Vec<PathBuf> {
|
||||
let last_sync_time = get_last_sync_time();
|
||||
let mut modified_files = Vec::new();
|
||||
for entry in build_walk(dir) {
|
||||
let entry = entry.unwrap();
|
||||
let path = entry.path();
|
||||
let metadata = path.metadata().unwrap();
|
||||
let modified = metadata.modified().unwrap();
|
||||
|
||||
if modified.duration_since(UNIX_EPOCH).unwrap().as_secs() > last_sync_time {
|
||||
modified_files.push(path.to_path_buf().clone());
|
||||
}
|
||||
}
|
||||
|
||||
return modified_files;
|
||||
}
|
||||
|
||||
// Merkle trees are unique to directories, even if nested, but .index_cache is shared between all
|
||||
|
||||
fn remove_seps_from_path(dir: &Path) -> String {
|
||||
let mut path = String::new();
|
||||
for component in dir.components() {
|
||||
path.push_str(component.as_os_str().to_str().unwrap());
|
||||
}
|
||||
|
||||
// Remove leading slash
|
||||
if path.starts_with("/") || path.starts_with("\\") {
|
||||
path.remove(0);
|
||||
}
|
||||
return path;
|
||||
}
|
||||
|
||||
fn tree_path_for_dir_branch(dir: &Path, branch: Option<&str>) -> PathBuf {
|
||||
let mut path = get_my_home().unwrap().unwrap();
|
||||
path.push(".continue/index");
|
||||
path.push(remove_seps_from_path(dir));
|
||||
if let Some(branch) = branch {
|
||||
path.push(branch);
|
||||
} else {
|
||||
path.push("main");
|
||||
}
|
||||
path.push("merkle_tree");
|
||||
return path;
|
||||
}
|
||||
|
||||
struct DiskSet {
|
||||
file: File,
|
||||
}
|
||||
|
||||
const ITEM_SIZE: usize = 20;
|
||||
|
||||
impl DiskSet {
|
||||
pub fn new(path: &str) -> DiskSet {
|
||||
let path = Path::new(path);
|
||||
if !path.exists() {
|
||||
File::create(path).unwrap();
|
||||
}
|
||||
|
||||
DiskSet {
|
||||
file: OpenOptions::new()
|
||||
.read(true)
|
||||
.write(true)
|
||||
.open(path)
|
||||
.unwrap(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn contains(&mut self, item: &[u8; ITEM_SIZE]) -> bool {
|
||||
self.file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut buffer = [0; ITEM_SIZE];
|
||||
while self.file.read_exact(&mut buffer).is_ok() {
|
||||
if &buffer == item {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
pub fn add(&mut self, item: &[u8; ITEM_SIZE]) {
|
||||
if self.contains(item) {
|
||||
return;
|
||||
}
|
||||
|
||||
self.file.write_all(item).unwrap();
|
||||
self.file.flush().unwrap();
|
||||
}
|
||||
|
||||
pub fn remove(&mut self, item: &[u8; ITEM_SIZE]) {
|
||||
self.file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut buffer = [0; ITEM_SIZE];
|
||||
let mut pos = 0;
|
||||
let mut found = false;
|
||||
while self.file.read_exact(&mut buffer).is_ok() {
|
||||
if &buffer == item {
|
||||
found = true;
|
||||
break;
|
||||
}
|
||||
pos = self.file.stream_position().unwrap() as usize;
|
||||
}
|
||||
|
||||
if found {
|
||||
// Calculate the position of the last item
|
||||
let len = self.file.metadata().unwrap().len() as usize;
|
||||
let last_item_pos = len - ITEM_SIZE;
|
||||
|
||||
// Move the last item in the file to the position of the item we want to remove
|
||||
self.file
|
||||
.seek(SeekFrom::Start(last_item_pos as u64))
|
||||
.unwrap();
|
||||
self.file.read_exact(&mut buffer).unwrap();
|
||||
self.file.seek(SeekFrom::Start(pos as u64)).unwrap();
|
||||
self.file.write_all(&buffer).unwrap();
|
||||
|
||||
// Truncate the file at the position of the last item
|
||||
self.file.set_len(last_item_pos as u64).unwrap();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn sync(
|
||||
dir: &Path,
|
||||
branch: Option<&str>,
|
||||
) -> Result<
|
||||
(
|
||||
Vec<(String, String)>,
|
||||
Vec<(String, String)>,
|
||||
Vec<(String, String)>,
|
||||
Vec<(String, String)>,
|
||||
),
|
||||
Box<dyn std::error::Error>,
|
||||
> {
|
||||
let tree_path = tree_path_for_dir_branch(dir, branch);
|
||||
let old_tree: Tree = match Tree::load(&tree_path) {
|
||||
Ok(tree) => tree,
|
||||
Err(_) => Tree::empty(),
|
||||
};
|
||||
|
||||
// Calculate and save new tree
|
||||
// TODO: Use modified files to speed up calculation
|
||||
// let modified_files = get_modified_files(dir);
|
||||
let new_tree = compute_tree_for_dir(dir, None)?;
|
||||
|
||||
// Update last sync time
|
||||
write_sync_time();
|
||||
|
||||
// Save new tree
|
||||
new_tree.persist(&tree_path);
|
||||
|
||||
// Compute diff
|
||||
let (add, remove) = diff(&old_tree, &new_tree);
|
||||
|
||||
// Compute the four action types: compute, remove, add tag, remove tag,
|
||||
// transform into desired format: [(path, hash), ...],
|
||||
// and update .index_cache
|
||||
let index_cache_path = get_my_home()
|
||||
.unwrap()
|
||||
.unwrap()
|
||||
.join(".continue/index/.index_cache");
|
||||
let mut disk_set = DiskSet::new(index_cache_path.to_str().unwrap());
|
||||
|
||||
let mut compute: Vec<(String, String)> = Vec::new();
|
||||
let mut delete: Vec<(String, String)> = Vec::new();
|
||||
let mut add_label: Vec<(String, String)> = Vec::new();
|
||||
let mut remove_label: Vec<(String, String)> = Vec::new();
|
||||
|
||||
for item in add {
|
||||
if !item.is_blob {
|
||||
continue;
|
||||
}
|
||||
let path = item.path.as_str().to_string();
|
||||
let hash = hash_string(item.hash);
|
||||
if disk_set.contains(&item.hash) {
|
||||
add_label.push((path, hash));
|
||||
} else {
|
||||
compute.push((path, hash));
|
||||
}
|
||||
}
|
||||
|
||||
for item in remove {
|
||||
if !item.is_blob {
|
||||
continue;
|
||||
}
|
||||
if disk_set.contains(&item.hash) {
|
||||
let path = item.path.as_str().to_string();
|
||||
let hash = hash_string(item.hash);
|
||||
} else {
|
||||
// Should never happen
|
||||
}
|
||||
}
|
||||
|
||||
return Ok((compute, delete, add_label, remove_label));
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::fs::remove_file;
|
||||
|
||||
#[test]
|
||||
fn test_disk_set() {
|
||||
let path = "testfile";
|
||||
let mut disk_set = DiskSet::new(path);
|
||||
|
||||
let item1: ObjectHash = [1; ITEM_SIZE];
|
||||
let item2: ObjectHash = [20; ITEM_SIZE];
|
||||
let item3: ObjectHash = [30; ITEM_SIZE];
|
||||
|
||||
// Test add and contains
|
||||
disk_set.add(&item1);
|
||||
disk_set.add(&item2);
|
||||
assert!(disk_set.contains(&item1));
|
||||
assert!(disk_set.contains(&item2));
|
||||
|
||||
// Test the exact contents of the file
|
||||
disk_set.file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut buffer = [0; ITEM_SIZE];
|
||||
disk_set.file.read_exact(&mut buffer).unwrap();
|
||||
assert_eq!(buffer, item1);
|
||||
disk_set.file.read_exact(&mut buffer).unwrap();
|
||||
assert_eq!(buffer, item2);
|
||||
|
||||
// Test remove
|
||||
disk_set.remove(&item1);
|
||||
assert!(!disk_set.contains(&item1));
|
||||
assert!(disk_set.contains(&item2));
|
||||
|
||||
// Test one more add
|
||||
disk_set.add(&item3);
|
||||
assert!(disk_set.contains(&item3));
|
||||
|
||||
// Test the length of the file
|
||||
disk_set.file.seek(SeekFrom::Start(0)).unwrap();
|
||||
let mut buffer = [0; ITEM_SIZE];
|
||||
let mut count = 0;
|
||||
while disk_set.file.read_exact(&mut buffer).is_ok() {
|
||||
count += 1;
|
||||
}
|
||||
assert_eq!(count, 2);
|
||||
|
||||
// Clean up
|
||||
remove_file(path).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sync() {
|
||||
let ti = std::time::Instant::now();
|
||||
let results = sync(
|
||||
Path::new("/Users/natesesti/Desktop/continue"),
|
||||
Some("nate/pyO3"),
|
||||
);
|
||||
println!("Sync took {:?}", ti.elapsed());
|
||||
// Vast majority (90+%) of this time is spent in compute_tree_for_dir
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_double_sync() {
|
||||
let ti = std::time::Instant::now();
|
||||
let results = sync(
|
||||
Path::new("/Users/natesesti/Desktop/continue"),
|
||||
Some("nate/pyO3"),
|
||||
)
|
||||
.expect("Sync failed.");
|
||||
println!("First sync took {:?}", ti.elapsed());
|
||||
assert!(results.0.len() > 0);
|
||||
assert!(results.1.len() > 0);
|
||||
|
||||
let ti = std::time::Instant::now();
|
||||
let results = sync(
|
||||
Path::new("/Users/natesesti/Desktop/continue"),
|
||||
Some("nate/pyO3"),
|
||||
)
|
||||
.expect("Sync failed");
|
||||
println!("Second sync took {:?}", ti.elapsed());
|
||||
assert_eq!(results.0.len(), 0);
|
||||
assert_eq!(results.1.len(), 0);
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Reference in a new issue