pijul 1.0.0-beta.12

A distributed version control system.
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
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::bail;
use canonical_path::{CanonicalPath, CanonicalPathBuf};
use clap::Parser;
use jiff::Timestamp;
use log::debug;
use pijul_core::change::*;
use pijul_core::changestore::*;
use pijul_core::{
    ArcTxn, Base32, ChannelMutTxnT, ChannelRef, ChannelTxnT, MutTxnTExt, TxnT, TxnTExt,
};
use pijul_core::{HashMap, HashSet};

use crate::commands::common_opts::RepoAndChannel;
use crate::commands::load_channel;
use pijul_repository::*;

#[derive(Parser, Debug)]
pub struct Record {
    #[clap(flatten)]
    base: RepoAndChannel,
    /// Record all paths that have changed
    #[clap(short = 'a', long = "all")]
    pub all: bool,
    /// Set the change message
    #[clap(short = 'm', long = "message")]
    pub message: Option<String>,
    /// Set the description field.
    #[clap(long = "description")]
    pub description: Option<String>,
    /// Set the author field
    #[clap(long = "author")]
    pub author: Option<String>,
    /// Set the timestamp field
    #[clap(long = "timestamp")]
    pub timestamp: Option<Timestamp>,
    /// Ignore missing (deleted) files
    #[clap(long = "ignore-missing")]
    pub ignore_missing: bool,
    #[clap(long = "working-copy")]
    pub working_copy: Option<String>,
    /// Amend this change instead of creating a new change
    #[clap(long = "amend")]
    #[allow(clippy::option_option)]
    pub amend: Option<Option<String>>,
    /// Paths in which to record the changes
    pub prefixes: Vec<PathBuf>,
    /// Identity to sign changes with
    #[clap(long = "identity")]
    pub identity: Option<String>,
    /// Use Patience diff instead of the default Myers diff
    #[clap(long = "patience")]
    pub patience: bool,
    /// Use Histogram diff algorithm instead of the default
    #[clap(long = "histogram")]
    pub histogram: bool,
    /// Use Histogram diff algorithm instead of the default
    #[clap(long = "no-keyring")]
    pub no_keyring: bool,
}

impl Record {
    pub fn repository_path(&self) -> Option<&Path> {
        self.base.repo_path()
    }

    pub async fn run(self, config: &pijul_config::Config) -> Result<(), anyhow::Error> {
        let repo = Repository::find_root(self.base.repo_path())?;
        let mut stdout = std::io::stdout();
        let mut stderr = std::io::stderr();

        for h in config.hooks.record.iter() {
            h.run(repo.path.clone())?
        }
        let txn = repo.pristine.arc_txn_begin()?;

        let (mut channel, extra) = {
            let txn = txn.read();

            let (channel, _) = load_channel(self.base.channel(), &*txn)?;

            let mut extra = Vec::new();
            for h in config.extra_dependencies.iter() {
                let (h, c) = txn.hash_from_prefix(h)?;
                if txn
                    .get_changeset(txn.changes(&*channel.read()), &c)?
                    .is_none()
                {
                    bail!(
                        "Change {:?} (from .pijul/config) is not on channel {:?}",
                        h,
                        channel.read().name
                    )
                }
                extra.push(h)
            }

            (channel, extra)
        };

        let header = if let Some(ref amend) = self.amend {
            let h = {
                let txn = txn.read();

                if let Some(hash) = amend {
                    txn.hash_from_prefix(hash)?.0
                } else if let Some(h) = txn.reverse_log(&*channel.read(), None)?.next() {
                    h?.1.0.into()
                } else {
                    return Ok(());
                }
            };
            let header = if let Some(message) = self.message.clone() {
                ChangeHeader {
                    message,
                    ..repo.changes.get_header(&h)?
                }
            } else {
                repo.changes.get_header(&h)?
            };

            txn.write().unrecord(
                &repo.changes,
                &mut channel,
                &h,
                self.timestamp.map(Timestamp::as_second).unwrap_or(0) as u64,
                &repo.working_copy,
            )?;
            header
        } else {
            self.header(config).await?
        };
        let no_prefixes =
            self.prefixes.is_empty() && !self.ignore_missing && self.working_copy.is_none();
        let (repo_path, working_copy) = if let Some(ref w) = self.working_copy {
            (
                CanonicalPathBuf::canonicalize(w)?,
                Some(pijul_core::working_copy::filesystem::FileSystem::from_root(
                    w,
                )),
            )
        } else {
            (CanonicalPathBuf::canonicalize(&repo.path)?, None)
        };

        let complete = pijul_identity::Complete::load(
            &pijul_identity::choose_identity_name(config, !self.no_keyring).await?,
        )?;

        let (secret, _) = complete.decrypt(config, !self.no_keyring)?;

        txn.write()
            .apply_root_change_if_needed(&repo.changes, &channel, rand::rng())?;

        let result = self.record(
            txn,
            channel.clone(),
            working_copy.as_ref().unwrap_or(&repo.working_copy),
            &repo.changes,
            repo_path,
            header,
            &extra,
        )?;
        match result {
            Either::A((txn, mut change, updates, oldest)) => {
                let hash = repo.changes.save_change(&mut change, |change, hash| {
                    change.unhashed = Some(serde_json::json!({
                        "signature": secret.sign_raw(&hash.to_bytes()).unwrap(),
                    }));
                    Ok::<_, anyhow::Error>(())
                })?;

                let mut txn_ = txn.write();
                txn_.apply_local_change(&mut channel, &change, &hash, &updates)?;
                let mut path = repo.path.join(pijul_core::DOT_DIR);
                path.push("identities");
                std::fs::create_dir_all(&path)?;

                writeln!(stdout, "Hash: {}", hash.to_base32())?;
                debug!("oldest = {:?}", oldest);
                if no_prefixes {
                    let mut oldest = oldest
                        .duration_since(std::time::SystemTime::UNIX_EPOCH)
                        .unwrap()
                        .as_millis() as u64;
                    if oldest == 0 {
                        // If no diff was done at all, it means that no
                        // existing file changed since last time (some
                        // files may have been added, deleted or moved,
                        // but `touch` isn't about those).
                        oldest = std::time::SystemTime::now()
                            .duration_since(std::time::SystemTime::UNIX_EPOCH)
                            .unwrap()
                            .as_millis() as u64;
                    }
                    txn_.touch_channel(&mut *channel.write(), Some((oldest / 1000) * 1000));
                }
                std::mem::drop(txn_);
                txn.commit()?;
            }
            Either::B(txn) => {
                if no_prefixes {
                    txn.write().touch_channel(&mut *channel.write(), None);
                    txn.commit()?;
                }
                writeln!(stderr, "Nothing to record")?;
            }
        }
        Ok(())
    }

    async fn header(&self, config: &pijul_config::Config) -> Result<ChangeHeader, anyhow::Error> {
        let mut authors = Vec::new();
        let mut b = std::collections::BTreeMap::new();
        if let Some(ref a) = self.author {
            b.insert("name".to_string(), a.clone());
        } else {
            let identity_name = self
                .identity
                .clone()
                .unwrap_or(pijul_identity::choose_identity_name(config, !self.no_keyring).await?);

            let public_key = pijul_identity::public_key(&identity_name);
            b.insert("key".to_string(), public_key?.key);
        }

        authors.push(Author(b));
        let templates = config.template.as_ref();
        let message = if let Some(message) = &self.message {
            message.clone()
        } else if let Some(message_file) = templates.and_then(|t| t.message.as_ref()) {
            match std::fs::read_to_string(message_file) {
                Ok(m) => m,
                Err(e) => bail!("Could not read message template: {:?}: {}", message_file, e),
            }
        } else {
            String::new()
        };
        let description = if let Some(description) = &self.description {
            Some(description.clone())
        } else if let Some(descr_file) = templates.and_then(|t| t.description.as_ref()) {
            match std::fs::read_to_string(descr_file) {
                Ok(d) => Some(d),
                Err(e) => bail!(
                    "Could not read description template: {:?}: {}",
                    descr_file,
                    e
                ),
            }
        } else {
            None
        };
        let header = ChangeHeader {
            message,
            authors,
            description,
            timestamp: self.timestamp.unwrap_or_else(Timestamp::now),
        };
        Ok(header)
    }

    fn fill_relative_prefixes(&mut self) -> Result<(), anyhow::Error> {
        let cwd = std::env::current_dir()?;
        for p in self.prefixes.iter_mut() {
            if p.is_relative() {
                *p = cwd.join(&p);
            }
        }
        Ok(())
    }

    fn record<
        T: TxnTExt + MutTxnTExt + Sync + Send + 'static,
        C: ChangeStore + Send + Clone + 'static,
    >(
        mut self,
        txn: ArcTxn<T>,
        channel: ChannelRef<T>,
        working_copy: &pijul_core::working_copy::FileSystem,
        changes: &C,
        repo_path: CanonicalPathBuf,
        header: ChangeHeader,
        extra_deps: &[pijul_core::Hash],
    ) -> Result<
        Either<
            (
                ArcTxn<T>,
                Change,
                HashMap<usize, pijul_core::InodeUpdate>,
                std::time::SystemTime,
            ),
            ArcTxn<T>,
        >,
        anyhow::Error,
    > {
        let mut state = pijul_core::RecordBuilder::new();
        if self.ignore_missing {
            state.ignore_missing = true;
        }
        if self.patience && self.histogram {
            log::warn!("Only specify one algorithm option.")
        }
        let algorithm = if self.patience {
            pijul_core::Algorithm::Patience
        } else if self.histogram {
            pijul_core::Algorithm::ImaraHistogram
        } else {
            pijul_core::Algorithm::default()
        };
        if self.prefixes.is_empty() {
            if self.ignore_missing {
                for f in ignore::Walk::new(&repo_path) {
                    let f = f?;
                    if f.metadata()?.is_file() {
                        let p = CanonicalPath::new(f.path())?;
                        let p = p.as_path().strip_prefix(&repo_path).unwrap();
                        state.record(
                            txn.clone(),
                            algorithm,
                            false,
                            &pijul_core::DEFAULT_SEPARATOR,
                            channel.clone(),
                            working_copy,
                            changes,
                            p.to_str().unwrap(),
                            1, // std::thread::available_parallelism()?.get(),
                        )?
                    }
                }
            } else {
                state.record(
                    txn.clone(),
                    algorithm,
                    false,
                    &pijul_core::DEFAULT_SEPARATOR,
                    channel.clone(),
                    working_copy,
                    changes,
                    "",
                    1, // std::thread::available_parallelism()?.get(),
                )?
            }
        } else {
            self.fill_relative_prefixes()?;
            working_copy.record_prefixes(
                txn.clone(),
                algorithm,
                channel.clone(),
                changes,
                &mut state,
                repo_path,
                &self.prefixes,
                false,
                1, // std::thread::available_parallelism()?.get(),
                self.timestamp.map(Timestamp::as_second).unwrap_or(0) as u64,
            )?;
        }

        let mut rec = state.finish();
        if rec.actions.is_empty() {
            return Ok(Either::B(txn));
        }

        if rec.has_binary_files && !self.all {
            bail!("Cannot record a binary change interactively. Please use -a.")
        }

        debug!("TAKING LOCK {}", line!());
        let txn_ = txn.write();
        let actions = rec
            .actions
            .into_iter()
            .map(|rec| rec.globalize(&*txn_).unwrap())
            .collect();
        debug!("globalize done");
        let contents = if let Ok(c) = Arc::try_unwrap(rec.contents) {
            c.into_inner()
        } else {
            unreachable!()
        };
        let mut change =
            LocalChange::make_change(&*txn_, &channel, actions, contents, header, Vec::new())?;
        debug!("make change done");
        let current: HashSet<_> = change.dependencies.iter().cloned().collect();
        for dep in extra_deps.iter() {
            if !current.contains(dep) {
                change.dependencies.push(*dep)
            }
        }

        debug!("has_binary = {:?}", rec.has_binary_files);
        let mut change = if self.all {
            change
        } else {
            let mut o = Vec::new();
            debug!("write change");
            change.write(changes, None, true, &mut o)?;
            debug!("write change done");

            let mut with_errors: Option<Vec<u8>> = None;
            let change = loop {
                let mut bytes = if let Some(ref o) = with_errors {
                    edit::edit_bytes_with_builder(
                        &o[..],
                        tempfile::Builder::new().suffix(".pijul-commit"),
                    )?
                } else {
                    edit::edit_bytes_with_builder(
                        &o[..],
                        tempfile::Builder::new().suffix(".pijul-commit"),
                    )?
                };
                if bytes.iter().all(|c| (*c as char).is_whitespace()) {
                    bail!("Empty change")
                }
                let mut change = std::io::BufReader::new(std::io::Cursor::new(&bytes));
                if let Ok(change) =
                    Change::read_and_deps(&mut change, &mut rec.updatables, &*txn_, &channel)
                {
                    break change;
                }

                let mut err = SYNTAX_ERROR.as_bytes().to_vec();
                err.append(&mut bytes);
                with_errors = Some(err)
            };
            if change.changes.is_empty() {
                bail!("Cannot parse change")
            }
            change
        };

        let current: HashSet<_> = change.dependencies.iter().cloned().collect();
        for dep in extra_deps.iter() {
            if !current.contains(dep) {
                change.dependencies.push(*dep)
            }
        }

        if change.header.message.trim().is_empty() {
            bail!("No change message")
        }
        debug!("saving change");
        std::mem::drop(txn_);
        Ok(Either::A((txn, change, rec.updatables, rec.oldest_change)))
    }
}

enum Either<A, B> {
    A(A),
    B(B),
}

const SYNTAX_ERROR: &str = "# Syntax errors, please try again.
# Alternatively, you may delete the entire file (including this
# comment) to abort.
";