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
230
231
232
233
234
235
236
237
238
239
240
241
242
243
//! Layout of a repository (files in `.pijul`) on the disk. This
//! module exports both high-level functions that require no knowledge
//! of the repository, and lower-level constants documented on
//! [pijul.org/documentation/repository](https://pijul.org/documentation/repository),
//! used for instance for downloading files from remote repositories.

use Result;
use backend::DEFAULT_BRANCH;
use backend::{Hash, HashRef, MutTxn, ROOT_INODE};
use bs58;
use flate2;
use ignore::WalkBuilder;
use ignore::overrides::OverrideBuilder;
use patch::{Patch, PatchHeader};
use rand;
use rand::Rng;
use rand::distributions::Alphanumeric;
use std;
use std::collections::HashSet;
use std::fs::canonicalize;
use std::fs::{create_dir_all, metadata, File};
use std::io::{BufReader, Read, Write};
use std::path::{Path, PathBuf};

/// Name of the root directory, i.e. `.pijul`.
pub const PIJUL_DIR_NAME: &'static str = ".pijul";

/// Concatenate the parameter with `PIJUL_DIR_NAME`.
pub fn repo_dir<P: AsRef<Path>>(p: P) -> PathBuf {
    p.as_ref().join(PIJUL_DIR_NAME)
}

/// Directory where the pristine is, from the root of the repository.
/// For instance, if the repository in in `/a/b`,
/// `pristine_dir("/a/b") returns `/a/b/.pijul/pristine`.
pub fn pristine_dir<P: AsRef<Path>>(p: P) -> PathBuf {
    return p.as_ref().join(PIJUL_DIR_NAME).join("pristine");
}

/// Directory where the patches are. `patches_dir("/a/b") = "/a/b/.pijul/patches"`.
pub fn patches_dir<P: AsRef<Path>>(p: P) -> PathBuf {
    return p.as_ref().join(PIJUL_DIR_NAME).join("patches");
}

/// Basename of the changes file for branch `br`. This file is only
/// used when pulling/pushing over HTTP (where calling remote programs
/// to list patches is impossible).
///
/// The changes file contains the same information as the one returned by `pijul log --hash-only`.
pub fn branch_changes_base_path(b: &str) -> String {
    "changes.".to_string() + &bs58::encode(b.as_bytes()).into_string()
}

/// Changes file from the repository root and branch name.
pub fn branch_changes_file(p: &Path, b: &str) -> PathBuf {
    p.join(PIJUL_DIR_NAME).join(branch_changes_base_path(b))
}

/// The meta file, where user preferences are stored.
pub fn meta_file(p: &Path) -> PathBuf {
    p.join(PIJUL_DIR_NAME).join("meta.toml")
}

/// The id file is used for remote operations, to identify a
/// repository and save bandwidth when the remote state is partially
/// known.
pub fn id_file(p: &Path) -> PathBuf {
    p.join(PIJUL_DIR_NAME).join("id")
}

/// Find the repository root from one of its descendant
/// directories. Return `None` iff `dir` is not in a repository.
pub fn find_repo_root<'a>(dir: &'a Path) -> Option<PathBuf> {
    let mut p = dir.to_path_buf();
    loop {
        p.push(PIJUL_DIR_NAME);
        match metadata(&p) {
            Ok(ref attr) if attr.is_dir() => {
                p.pop();
                return Some(p);
            }
            _ => {}
        }
        p.pop();

        if !p.pop() {
            return None;
        }
    }
}

#[doc(hidden)]
pub const ID_LENGTH: usize = 100;

/// Create a repository. `dir` must be the repository root (a
/// `".pijul"` directory will be created in `dir`).
pub fn create<R: Rng>(dir: &Path, mut rng: R) -> std::io::Result<()> {
    debug!("create: {:?}", dir);
    let mut repo_dir = repo_dir(dir);
    create_dir_all(&repo_dir)?;

    repo_dir.push("pristine");
    create_dir_all(&repo_dir)?;
    repo_dir.pop();

    repo_dir.push("patches");
    create_dir_all(&repo_dir)?;
    repo_dir.pop();

    repo_dir.push("id");
    let mut f = std::fs::File::create(&repo_dir)?;
    let mut x = String::new();
    x.extend(rng.sample_iter(&Alphanumeric).take(ID_LENGTH));
    f.write_all(x.as_bytes())?;
    repo_dir.pop();

    repo_dir.push("version");
    let mut f = std::fs::File::create(&repo_dir)?;
    writeln!(f, "{}", env!("CARGO_PKG_VERSION"))?;
    repo_dir.pop();

    repo_dir.push("local");
    create_dir_all(&repo_dir)?;
    repo_dir.pop();

    repo_dir.push("hooks");
    create_dir_all(&repo_dir)?;
    repo_dir.pop();

    repo_dir.push("local");
    repo_dir.push("ignore");
    std::fs::File::create(&repo_dir)?;
    repo_dir.pop();
    repo_dir.pop();

    Ok(())
}

/// Basename of the patch corresponding to the given patch hash.
pub fn patch_file_name(hash: HashRef) -> String {
    hash.to_base58() + ".gz"
}

/// Read a complete patch.
pub fn read_patch(repo: &Path, hash: HashRef) -> Result<Patch> {
    let patch_dir = patches_dir(repo);
    let path = patch_dir.join(&patch_file_name(hash));
    debug!("read_patch, reading from {:?}", path);
    let f = File::open(path)?;
    let mut f = BufReader::new(f);
    let (_, _, patch) = Patch::from_reader_compressed(&mut f)?;
    Ok(patch)
}

/// Read a patch, but without the "changes" part, i.e. the actual
/// contents of the patch.
pub fn read_patch_nochanges(repo: &Path, hash: HashRef) -> Result<PatchHeader> {
    let patch_dir = patches_dir(repo);
    let path = patch_dir.join(&patch_file_name(hash));
    debug!("read_patch_nochanges, reading from {:?}", path);
    let f = File::open(path)?;
    let mut f = flate2::bufread::GzDecoder::new(BufReader::new(f));
    Ok(PatchHeader::from_reader_nochanges(&mut f)?)
}

/// Read a patch, but without the "changes" part, i.e. the actual
/// contents of the patch.
pub fn read_dependencies(repo: &Path, hash: HashRef) -> Result<Vec<Hash>> {
    let patch_dir = patches_dir(repo);
    let path = patch_dir.join(&patch_file_name(hash));
    debug!("read_patch_nochanges, reading from {:?}", path);
    let f = File::open(path)?;
    let mut f = flate2::bufread::GzDecoder::new(BufReader::new(f));
    Ok(Patch::read_dependencies(&mut f)?)
}

pub fn ignore_file(repo_root: &Path) -> PathBuf {
    repo_root.join(PIJUL_DIR_NAME).join("local").join("ignore")
}

pub fn untracked_files<T: rand::Rng>(txn: &MutTxn<T>, repo_root: &Path) -> HashSet<PathBuf> {
    let known_files = txn.list_files(ROOT_INODE).unwrap_or_else(|_| vec![]);

    let o = OverrideBuilder::new(repo_root)
        .add("!.pijul")
        .unwrap()
        .build()
        .unwrap(); // we can be pretty confident these two calls will
                   // not fail as the glob is hard-coded

    let mut w = WalkBuilder::new(repo_root);
    w.git_ignore(false)
        .git_exclude(false)
        .git_global(false)
        .hidden(false)
        .add_custom_ignore_filename(".pijulignore");

    // add .pijul/local/ignore
    w.add_ignore(ignore_file(repo_root));
    w.overrides(o);

    let mut ret = HashSet::<PathBuf>::new();
    for f in w.build() {
        if let Ok(f) = f {
            let p = f.path();
            if p == repo_root {
                continue;
            }
            let pb = p.to_path_buf();

            if let Ok(stripped) = p.strip_prefix(repo_root) {
                if known_files.iter().any(|t| *t == stripped) {
                    continue;
                }
            }
            ret.insert(pb);
        }
    }
    ret
}

pub fn get_current_branch(root: &Path) -> Result<String> {
    debug!("path: {:?}", root);
    let mut path = repo_dir(&canonicalize(root)?);
    path.push("current_branch");
    if let Ok(mut f) = File::open(&path) {
        let mut s = String::new();
        f.read_to_string(&mut s)?;
        Ok(s.trim().to_string())
    } else {
        Ok(DEFAULT_BRANCH.to_string())
    }
}

pub fn set_current_branch(root: &Path, branch: &str) -> Result<()> {
    debug!("set current branch: root={:?}, branch={:?}", root, branch);
    let mut path = repo_dir(&canonicalize(root)?);
    path.push("current_branch");
    let mut f = File::create(&path)?;
    f.write_all(branch.trim().as_ref())?;
    f.write_all(b"\n")?;
    Ok(())
}