1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::fs;
use std::fs::OpenOptions;
use std::io::{Read, Write};
use std::path::Path;
use std::sync::Arc;

use itertools::Itertools;
use tempfile::TempDir;

use crate::backend::{FileId, TreeId, TreeValue};
use crate::commit::Commit;
use crate::commit_builder::CommitBuilder;
use crate::repo::{MutableRepo, ReadonlyRepo};
use crate::repo_path::RepoPath;
use crate::rewrite::RebasedDescendant;
use crate::settings::UserSettings;
use crate::store::Store;
use crate::tree::Tree;
use crate::tree_builder::TreeBuilder;
use crate::workspace::Workspace;

pub fn new_user_home() -> TempDir {
    // Set $HOME to some arbitrary place so libgit2 doesn't use ~/.gitignore
    // of the person running the tests.
    let home_dir = tempfile::tempdir().unwrap();
    std::env::set_var("HOME", home_dir.path());
    home_dir
}

pub fn user_settings() -> UserSettings {
    let mut config = config::Config::new();
    config.set("user.name", "Test User").unwrap();
    config.set("user.email", "test.user@example.com").unwrap();
    UserSettings::from_config(config)
}

pub struct TestRepo {
    pub temp_dir: TempDir,
    pub repo: Arc<ReadonlyRepo>,
}

pub fn init_repo(settings: &UserSettings, use_git: bool) -> TestRepo {
    let temp_dir = tempfile::tempdir().unwrap();

    let repo_dir = temp_dir.path().join("repo");
    fs::create_dir(&repo_dir).unwrap();

    let repo = if use_git {
        let git_path = temp_dir.path().join("git-repo");
        git2::Repository::init(&git_path).unwrap();
        ReadonlyRepo::init_external_git(settings, repo_dir, git_path)
    } else {
        ReadonlyRepo::init_local(settings, repo_dir)
    };

    TestRepo { temp_dir, repo }
}

pub struct TestWorkspace {
    pub temp_dir: TempDir,
    pub workspace: Workspace,
    pub repo: Arc<ReadonlyRepo>,
}

pub fn init_workspace(settings: &UserSettings, use_git: bool) -> TestWorkspace {
    let temp_dir = tempfile::tempdir().unwrap();

    let workspace_root = temp_dir.path().join("repo");
    fs::create_dir(&workspace_root).unwrap();

    let (workspace, repo) = if use_git {
        let git_path = temp_dir.path().join("git-repo");
        git2::Repository::init(&git_path).unwrap();
        Workspace::init_external_git(settings, workspace_root, git_path).unwrap()
    } else {
        Workspace::init_local(settings, workspace_root).unwrap()
    };

    TestWorkspace {
        temp_dir,
        workspace,
        repo,
    }
}

pub fn read_file(store: &Store, path: &RepoPath, id: &FileId) -> Vec<u8> {
    let mut reader = store.read_file(path, id).unwrap();
    let mut content = vec![];
    reader.read_to_end(&mut content).unwrap();
    content
}

pub fn write_file(store: &Store, path: &RepoPath, contents: &str) -> FileId {
    store.write_file(path, &mut contents.as_bytes()).unwrap()
}

pub fn write_normal_file(tree_builder: &mut TreeBuilder, path: &RepoPath, contents: &str) {
    let id = write_file(tree_builder.store(), path, contents);
    tree_builder.set(
        path.clone(),
        TreeValue::Normal {
            id,
            executable: false,
        },
    );
}

pub fn write_executable_file(tree_builder: &mut TreeBuilder, path: &RepoPath, contents: &str) {
    let id = write_file(tree_builder.store(), path, contents);
    tree_builder.set(
        path.clone(),
        TreeValue::Normal {
            id,
            executable: true,
        },
    );
}

pub fn write_symlink(tree_builder: &mut TreeBuilder, path: &RepoPath, target: &str) {
    let id = tree_builder.store().write_symlink(path, target).unwrap();
    tree_builder.set(path.clone(), TreeValue::Symlink(id));
}

pub fn create_tree(repo: &ReadonlyRepo, path_contents: &[(&RepoPath, &str)]) -> Tree {
    let store = repo.store();
    let mut tree_builder = store.tree_builder(store.empty_tree_id().clone());
    for (path, contents) in path_contents {
        write_normal_file(&mut tree_builder, path, contents);
    }
    let id = tree_builder.write_tree();
    store.get_tree(&RepoPath::root(), &id).unwrap()
}

#[must_use]
pub fn create_random_tree(repo: &ReadonlyRepo) -> TreeId {
    let mut tree_builder = repo
        .store()
        .tree_builder(repo.store().empty_tree_id().clone());
    let number = rand::random::<u32>();
    let path = RepoPath::from_internal_string(format!("file{}", number).as_str());
    write_normal_file(&mut tree_builder, &path, "contents");
    tree_builder.write_tree()
}

#[must_use]
pub fn create_random_commit(settings: &UserSettings, repo: &ReadonlyRepo) -> CommitBuilder {
    let tree_id = create_random_tree(repo);
    let number = rand::random::<u32>();
    CommitBuilder::for_new_commit(settings, repo.store(), tree_id)
        .set_description(format!("random commit {}", number))
}

pub fn write_working_copy_file(workspace_root: &Path, path: &RepoPath, contents: &str) {
    let mut file = OpenOptions::new()
        .write(true)
        .create(true)
        .truncate(true)
        .open(path.to_fs_path(workspace_root))
        .unwrap();
    file.write_all(contents.as_bytes()).unwrap();
}

pub struct CommitGraphBuilder<'settings, 'repo> {
    settings: &'settings UserSettings,
    mut_repo: &'repo mut MutableRepo,
}

impl<'settings, 'repo> CommitGraphBuilder<'settings, 'repo> {
    pub fn new(
        settings: &'settings UserSettings,
        mut_repo: &'repo mut MutableRepo,
    ) -> CommitGraphBuilder<'settings, 'repo> {
        CommitGraphBuilder { settings, mut_repo }
    }

    pub fn initial_commit(&mut self) -> Commit {
        create_random_commit(self.settings, self.mut_repo.base_repo().as_ref())
            .write_to_repo(self.mut_repo)
    }

    pub fn commit_with_parents(&mut self, parents: &[&Commit]) -> Commit {
        let parent_ids = parents
            .iter()
            .map(|commit| commit.id().clone())
            .collect_vec();
        create_random_commit(self.settings, self.mut_repo.base_repo().as_ref())
            .set_parents(parent_ids)
            .write_to_repo(self.mut_repo)
    }
}

pub fn assert_rebased(
    rebased: Option<RebasedDescendant>,
    expected_old_commit: &Commit,
    expected_new_parents: &[&Commit],
) -> Commit {
    if let Some(RebasedDescendant {
        old_commit,
        new_commit,
    }) = rebased
    {
        assert_eq!(old_commit, *expected_old_commit);
        assert_eq!(new_commit.change_id(), expected_old_commit.change_id());
        assert_eq!(
            new_commit.parent_ids(),
            expected_new_parents
                .iter()
                .map(|commit| commit.id().clone())
                .collect_vec()
        );
        new_commit
    } else {
        panic!("expected rebased commit: {:?}", rebased);
    }
}