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
use std::collections::{BTreeMap, BTreeSet};
use std::io::{IsTerminal, Write};
use std::path::{Path, PathBuf};

use canonical_path::CanonicalPathBuf;
use clap::Parser;
use pijul_core::change::*;
use pijul_core::{MutTxnT, TxnTExt};
use serde_derive::Serialize;

use crate::commands::common_opts::RepoAndChannel;

use pijul_repository::*;

#[derive(Parser, Debug)]
pub struct Diff {
    #[clap(flatten)]
    pub base: RepoAndChannel,
    /// Output the diff in JSON format instead of the default change text format.
    #[clap(long = "json")]
    pub json: bool,
    /// Add all the changes of this channel as dependencies (except changes implied transitively), instead of the minimal dependencies.
    #[clap(long = "tag")]
    pub tag: bool,
    /// Show a short version of the diff.
    #[clap(short = 's', long = "short")]
    pub short: bool,
    /// Include the untracked files
    #[clap(short = 'u', long = "untracked")]
    pub untracked: bool,
    /// Only diff those paths (files or directories). If missing, diff the entire repository.
    pub prefixes: Vec<PathBuf>,
    /// 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,
}

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

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

        if self.untracked && self.json {
            serde_json::to_writer_pretty(
                &mut std::io::stdout(),
                &untracked(&repo, txn.clone())?.collect::<Result<Vec<_>, _>>()?,
            )?;
            writeln!(stdout)?;
            return Ok(());
        }

        let channel = get_channel(self.base.channel(), &*txn.read()).0.to_string();
        let channel = txn.write().open_or_create_channel(&channel)?;

        let mut state = pijul_core::RecordBuilder::new();
        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() {
            state.record(
                txn.clone(),
                algorithm,
                self.short,
                &pijul_core::DEFAULT_SEPARATOR,
                channel.clone(),
                &repo.working_copy,
                &repo.changes,
                "",
                std::thread::available_parallelism()?.get(),
            )?
        } else {
            self.fill_relative_prefixes()?;
            repo.working_copy.record_prefixes(
                txn.clone(),
                algorithm,
                channel.clone(),
                &repo.changes,
                &mut state,
                CanonicalPathBuf::canonicalize(&repo.path)?,
                &self.prefixes,
                false,
                std::thread::available_parallelism()?.get(),
                0,
            )?;
        }
        let rec = state.finish();
        if rec.actions.is_empty() {
            if self.short && self.untracked {
                print_untracked_files(&repo, txn.clone())?;
            } else if self.untracked {
                for path in untracked(&repo, txn.clone())? {
                    writeln!(stdout, "{}", path?.to_str().unwrap())?;
                }
            }
            return Ok(());
        }
        let actions: Vec<_> = {
            let txn_ = txn.read();
            rec.actions
                .into_iter()
                .map(|rec| rec.globalize(&*txn_).unwrap())
                .collect()
        };
        let actions_is_empty = actions.is_empty();
        let contents = if let Ok(cont) = std::sync::Arc::try_unwrap(rec.contents) {
            cont.into_inner()
        } else {
            unreachable!()
        };
        let mut change = LocalChange::make_change(
            &*txn.read(),
            &channel,
            actions,
            contents,
            ChangeHeader::default(),
            Vec::new(),
        )?;

        let (dependencies, extra_known) = {
            let txn_ = txn.read();
            if self.tag {
                full_dependencies(&*txn_, &channel)?
            } else {
                dependencies(&*txn_, &*channel.read(), change.changes.iter())?
            }
        };
        change.dependencies = dependencies;
        change.extra_known = extra_known;

        let colors = is_colored(config);
        if self.json {
            let mut changes = BTreeMap::new();
            for ch in change.changes.iter() {
                changes
                    .entry(ch.path())
                    .or_insert_with(Vec::new)
                    .push(Status {
                        operation: match ch {
                            Hunk::FileMove { .. } => "file move",
                            Hunk::FileDel { .. } => "file del",
                            Hunk::FileUndel { .. } => "file undel",
                            Hunk::SolveNameConflict { .. } => "solve name conflict",
                            Hunk::UnsolveNameConflict { .. } => "unsolve name conflict",
                            Hunk::FileAdd { .. } => "file add",
                            Hunk::Edit { .. } => "edit",
                            Hunk::Replacement { .. } => "replacement",
                            Hunk::SolveOrderConflict { .. } => "solve order conflict",
                            Hunk::UnsolveOrderConflict { .. } => "unsolve order conflict",
                            Hunk::ResurrectZombies { .. } => "resurrect zombies",
                            Hunk::AddRoot { .. } => "root",
                            Hunk::DelRoot { .. } => "unroot",
                        },
                        line: ch.line(),
                    });
            }
            serde_json::to_writer_pretty(&mut std::io::stdout(), &changes)?;
            writeln!(stdout)?;
        } else if self.short {
            let mut changes = BTreeMap::new();
            for ch in change.changes.iter() {
                match ch {
                    Hunk::FileMove { path, .. } => {
                        changes.entry(path).or_insert(BTreeSet::new()).insert("MV")
                    }
                    Hunk::FileDel { path, .. } => {
                        changes.entry(path).or_insert(BTreeSet::new()).insert("D")
                    }
                    Hunk::FileUndel { path, .. } => {
                        changes.entry(path).or_insert(BTreeSet::new()).insert("UD")
                    }
                    Hunk::FileAdd { path, .. } => {
                        changes.entry(path).or_insert(BTreeSet::new()).insert("A")
                    }
                    Hunk::SolveNameConflict { path, .. } => {
                        changes.entry(path).or_insert(BTreeSet::new()).insert("SC")
                    }
                    Hunk::UnsolveNameConflict { path, .. } => {
                        changes.entry(path).or_insert(BTreeSet::new()).insert("UC")
                    }
                    Hunk::Edit {
                        local: Local { path, .. },
                        ..
                    } => changes.entry(path).or_insert(BTreeSet::new()).insert("M"),
                    Hunk::Replacement {
                        local: Local { path, .. },
                        ..
                    } => changes.entry(path).or_insert(BTreeSet::new()).insert("R"),
                    Hunk::SolveOrderConflict {
                        local: Local { path, .. },
                        ..
                    } => changes.entry(path).or_insert(BTreeSet::new()).insert("SC"),
                    Hunk::UnsolveOrderConflict {
                        local: Local { path, .. },
                        ..
                    } => changes.entry(path).or_insert(BTreeSet::new()).insert("UC"),
                    Hunk::ResurrectZombies {
                        local: Local { path, .. },
                        ..
                    } => changes.entry(path).or_insert(BTreeSet::new()).insert("RZ"),
                    Hunk::AddRoot { .. } | Hunk::DelRoot { .. } => true,
                };
            }
            let al = changes
                .iter()
                .map(|(_, v)| v.iter().map(|x| x.len()).sum::<usize>() + v.len() - 1)
                .max()
                .unwrap_or(0);
            let spaces: String = std::iter::repeat(' ').take(al).collect();
            for (k, v) in changes.iter() {
                let mut is_first = true;
                for v in v.iter() {
                    if is_first {
                        write!(stdout, "{}", v)?;
                    } else {
                        write!(stdout, ",{}", v)?;
                    }
                    is_first = false;
                }
                let (sp, _) = spaces.split_at(al - v.len());
                writeln!(stdout, "{} {}", sp, k)?;
            }
            if self.untracked {
                print_untracked_files(&repo, txn.clone())?;
            }
        } else if self.untracked {
            for path in untracked(&repo, txn.clone())? {
                writeln!(stdout, "{}", path?.to_str().unwrap())?;
            }
        } else {
            match change.write(
                &repo.changes,
                None,
                true,
                Colored {
                    w: termcolor::StandardStream::stdout(termcolor::ColorChoice::Auto),
                    colors,
                },
            ) {
                Ok(()) => {}
                Err(pijul_core::change::TextSerError::Io(e))
                    if e.kind() == std::io::ErrorKind::BrokenPipe => {}
                Err(e) => return Err(e.into()),
            }
        }
        if actions_is_empty && self.prefixes.is_empty() {
            use pijul_core::ChannelMutTxnT;
            {
                let mut txn_ = txn.write();
                txn_.touch_channel(&mut *channel.write(), None);
            }
            txn.commit()?;
        }
        Ok(())
    }

    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(())
    }
}

#[derive(Debug, Serialize)]
struct Status {
    operation: &'static str,
    line: Option<usize>,
}

pub struct Colored<W> {
    pub w: W,
    pub colors: bool,
}

impl<W: std::io::Write> std::io::Write for Colored<W> {
    fn write(&mut self, s: &[u8]) -> Result<usize, std::io::Error> {
        self.w.write(s)
    }
    fn flush(&mut self) -> Result<(), std::io::Error> {
        self.w.flush()
    }
}

use crate::commands::get_channel;
use termcolor::*;

impl<W: termcolor::WriteColor> pijul_core::change::WriteChangeLine for Colored<W> {
    fn write_change_line(&mut self, pref: &str, contents: &str) -> Result<(), std::io::Error> {
        if self.colors {
            let col = if pref == "+" {
                Color::Green
            } else {
                Color::Red
            };
            self.w.set_color(ColorSpec::new().set_fg(Some(col)))?;
            writeln!(self.w, "{} {}", pref, contents)?;
            self.w.reset()
        } else {
            writeln!(self.w, "{} {}", pref, contents)
        }
    }
    fn write_change_line_binary(
        &mut self,
        pref: &str,
        contents: &[u8],
    ) -> Result<(), std::io::Error> {
        if self.colors {
            let col = if pref == "+" {
                Color::Green
            } else {
                Color::Red
            };
            self.w.set_color(ColorSpec::new().set_fg(Some(col)))?;
            write!(
                self.w,
                "{}b{}",
                pref,
                data_encoding::BASE64.encode(contents)
            )?;
            self.w.reset()
        } else {
            write!(
                self.w,
                "{}b{}",
                pref,
                data_encoding::BASE64.encode(contents)
            )
        }
    }
}

pub fn is_colored(config: &pijul_config::Config) -> bool {
    let mut colors = std::io::stdout().is_terminal();
    match config.colors {
        pijul_config::Choice::Auto => (),
        pijul_config::Choice::Always => colors = true,
        pijul_config::Choice::Never => colors = false,
    }
    match config.pager {
        pijul_config::Choice::Never => colors = false,
        _ => {
            super::pager(config);
        }
    }
    colors
}

pub fn print_untracked_files<T: TxnTExt + Send + Sync + 'static>(
    repo: &Repository,
    txn: pijul_core::ArcTxn<T>,
) -> Result<(), anyhow::Error> {
    let mut stdout = std::io::stdout();
    for path in untracked(&repo, txn)? {
        writeln!(stdout, "U {}", path?.to_str().unwrap())?;
    }
    Ok(())
}

fn untracked<T: TxnTExt + Send + Sync + 'static>(
    repo: &Repository,
    txn: pijul_core::ArcTxn<T>,
) -> Result<impl Iterator<Item = Result<PathBuf, std::io::Error>>, anyhow::Error> {
    let repo_path = CanonicalPathBuf::canonicalize(&repo.path)?;
    let threads = std::thread::available_parallelism()?.get();
    let txn_ = txn.clone();
    Ok(repo
        .working_copy
        .iterate_prefix_rec(
            repo_path.clone(),
            repo_path.clone(),
            false,
            threads,
            move |path, _| {
                use path_slash::PathExt;
                let path_str = path.to_slash_lossy();
                log::debug!("untracked {:?}", path_str);
                path_str.is_empty() || txn.read().is_tracked(&path_str).unwrap()
            },
        )?
        .filter_map(move |path| match path {
            Err(e) => Some(Err(e)),
            Ok((path, _)) => {
                use path_slash::PathExt;
                let path_str = path.to_slash_lossy();
                log::debug!("untracked {:?}", path_str);
                if !txn_.read().is_tracked(&path_str).unwrap() {
                    Some(Ok(path))
                } else {
                    None
                }
            }
        }))
}