git-vet 0.4.0

Git-based review gate for tracked file contents
Documentation
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
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::process::ExitCode;

use clap::builder::styling::{AnsiColor, Effects, Styles};
use clap::{ColorChoice, CommandFactory, FromArgMatches, Parser, Subcommand, ValueEnum};

use crate::channel::{
    ChannelError, ChannelTransfer, ChannelTransferKind, DEFAULT_REVIEW_CHANNEL, ReviewChannel,
};
use crate::commands::{
    DiffTarget, DirtyPathHandling, Gate, MarkOptions, StatusMode, StatusTarget, diff_path,
    list_channels, mark_paths, remove_channel, status, sync_notes, transfer_channel_notes,
    unmark_paths,
};
use crate::error::AppError;
use crate::git::Git;
use crate::manpage;
use crate::notes::{GitNotesChannelStore, GitNotesStore, NotesStore};
use crate::sync_progress::SyncProgressReporter;
use crate::ui::{ColorMode, ColorPolicy};

const CLI_STYLES: Styles = Styles::styled()
    .header(AnsiColor::BrightCyan.on_default().effects(Effects::BOLD))
    .usage(AnsiColor::BrightCyan.on_default().effects(Effects::BOLD))
    .literal(AnsiColor::BrightGreen.on_default().effects(Effects::BOLD))
    .placeholder(AnsiColor::Cyan.on_default())
    .error(AnsiColor::BrightRed.on_default().effects(Effects::BOLD))
    .valid(AnsiColor::BrightGreen.on_default())
    .invalid(AnsiColor::BrightYellow.on_default());

#[derive(Parser, Debug)]
#[command(
    name = "git-vet",
    version,
    about = "Track human review state for Git-tracked file contents",
    styles = CLI_STYLES,
    after_help = "Typical workflow:\n  git vet status\n  git vet diff <path>\n  git vet mark <path>\n  git vet status --check"
)]
pub struct Cli {
    /// Review channel for commands that operate on one selected channel.
    #[arg(long, global = true)]
    channel: Option<String>,
    /// Control ANSI color output.
    #[arg(long, value_enum, global = true)]
    color: Option<CliColorMode>,
    #[command(subcommand)]
    command: CommandKind,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq, ValueEnum)]
enum CliColorMode {
    Auto,
    Always,
    Never,
}

impl From<CliColorMode> for ColorMode {
    fn from(mode: CliColorMode) -> Self {
        match mode {
            CliColorMode::Auto => Self::Auto,
            CliColorMode::Always => Self::Always,
            CliColorMode::Never => Self::Never,
        }
    }
}

#[derive(Subcommand, Debug)]
enum CommandKind {
    /// Install the git-vet(1) manual page for the current user.
    InstallMan {
        // Override the inherited global argument so it stays out of this command's help.
        #[arg(long, hide = true)]
        channel: Option<String>,
        /// Install into this man1 directory instead of the user default.
        #[arg(long, value_name = "DIRECTORY")]
        man_dir: Option<PathBuf>,
    },
    /// Manage local review notes across channels.
    Channel {
        #[command(subcommand)]
        command: ChannelCommand,
    },
    /// Sign off the current HEAD content of tracked files.
    Mark {
        /// Proceed even if target paths have uncommitted working-tree changes.
        #[arg(long)]
        allow_dirty: bool,
        #[arg(required = true)]
        paths: Vec<PathBuf>,
    },
    /// Remove sign-off for the current HEAD content of tracked files.
    Unmark {
        #[arg(required = true)]
        paths: Vec<PathBuf>,
    },
    /// Show review state for tracked files.
    Status {
        /// Emit stable machine-readable JSON.
        #[arg(long)]
        json: bool,
        /// Include files that are already vetted in human-readable output.
        #[arg(long)]
        all: bool,
        /// Exit 1 when any in-scope tracked file is unreviewed.
        #[arg(long)]
        check: bool,
        /// Classify local working-tree contents instead of committed HEAD contents.
        #[arg(long)]
        workspace: bool,
        /// Limit status to tracked files matching these file or directory pathspecs.
        #[arg(value_name = "PATHSPEC")]
        paths: Vec<PathBuf>,
    },
    /// Show the diff that still needs review for a tracked file.
    Diff {
        /// Compare the latest vetted content with the workspace instead of HEAD.
        #[arg(long)]
        workspace: bool,
        path: PathBuf,
    },
    /// Fetch, merge, and push review notes for the selected channel.
    Sync {
        /// Remote to sync with. Overrides vet.syncRemote and origin fallback.
        #[arg(long)]
        remote: Option<String>,
    },
    /// Prune notes for objects that are no longer present.
    Prune,
}

#[derive(Subcommand, Debug)]
enum ChannelCommand {
    /// List local review-note channels.
    List {
        /// Emit stable machine-readable JSON.
        #[arg(long)]
        json: bool,
    },
    /// Copy all local review notes into a new channel.
    Copy {
        /// Channel whose local review notes are copied.
        #[arg(value_name = "SOURCE")]
        source: String,
        /// New channel that receives the copied review notes.
        #[arg(value_name = "DESTINATION")]
        destination: String,
    },
    /// Move all local review notes into a new channel.
    Move {
        /// Channel whose local review notes are moved.
        #[arg(value_name = "SOURCE")]
        source: String,
        /// New channel that receives the moved review notes.
        #[arg(value_name = "DESTINATION")]
        destination: String,
    },
    /// Remove a local review-note channel.
    Remove {
        /// Channel whose local review notes are removed.
        #[arg(value_name = "CHANNEL")]
        target: String,
        /// Skip confirmation.
        #[arg(long)]
        force: bool,
    },
}

pub struct CliError {
    error: AppError,
    color_error: bool,
}

impl CliError {
    #[must_use]
    pub const fn error(&self) -> &AppError {
        &self.error
    }

    #[must_use]
    pub const fn color_error(&self) -> bool {
        self.color_error
    }
}

pub fn run_cli() -> Result<ExitCode, CliError> {
    let environment_color = ColorPolicy::resolve(None);
    let Cli {
        channel,
        color,
        command,
    } = parse_cli(environment_color);
    let color = ColorPolicy::resolve(color.map(Into::into));

    if let CommandKind::InstallMan {
        channel: command_channel,
        man_dir,
    } = &command
    {
        return install_man_page(
            channel.as_deref().or(command_channel.as_deref()),
            man_dir.as_deref(),
        )
        .map_err(|error| CliError {
            error,
            color_error: color.stderr(),
        });
    }

    let git = Git::discover().map_err(|error| CliError {
        error,
        color_error: color.stderr(),
    })?;
    run_cli_inner(&git, channel.as_deref(), command, color).map_err(|error| CliError {
        error,
        color_error: color.stderr(),
    })
}

fn parse_cli(color: ColorPolicy) -> Cli {
    let command = Cli::command().color(if color.stderr() {
        ColorChoice::Always
    } else {
        ColorChoice::Never
    });
    let matches = command.get_matches();
    Cli::from_arg_matches(&matches).unwrap_or_else(|error| error.exit())
}

fn run_cli_inner(
    git: &Git,
    channel: Option<&str>,
    command: CommandKind,
    color: ColorPolicy,
) -> Result<ExitCode, AppError> {
    match command {
        CommandKind::InstallMan {
            channel: command_channel,
            man_dir,
        } => install_man_page(channel.or(command_channel.as_deref()), man_dir.as_deref()),
        CommandKind::Channel { command } => run_channel_command(git, channel, command),
        CommandKind::Mark { paths, allow_dirty } => {
            with_selected_channel(git, channel, |_, notes| {
                let dirty_paths = if allow_dirty {
                    DirtyPathHandling::Allow
                } else {
                    DirtyPathHandling::Prompt
                };
                mark_paths(git, notes, &paths, MarkOptions { dirty_paths })?;
                Ok(ExitCode::SUCCESS)
            })
        }
        CommandKind::Unmark { paths } => with_selected_channel(git, channel, |_, notes| {
            unmark_paths(git, notes, &paths)?;
            Ok(ExitCode::SUCCESS)
        }),
        CommandKind::Status {
            json,
            all,
            check,
            workspace,
            paths,
        } => with_selected_channel(git, channel, |channel, notes| {
            let target = if workspace {
                StatusTarget::Workspace
            } else {
                StatusTarget::Head
            };
            match status(
                git,
                notes,
                channel,
                StatusMode {
                    json,
                    all: all || !paths.is_empty(),
                    check,
                    target,
                    color,
                },
                &paths,
            )? {
                Gate::Open => Ok(ExitCode::SUCCESS),
                Gate::Closed => Ok(ExitCode::from(1)),
            }
        }),
        CommandKind::Diff { path, workspace } => with_selected_channel(git, channel, |_, notes| {
            let target = if workspace {
                DiffTarget::Workspace
            } else {
                DiffTarget::Head
            };
            diff_path(git, notes, &path, target, color)?;
            Ok(ExitCode::SUCCESS)
        }),
        CommandKind::Sync { remote } => with_selected_channel(git, channel, |channel, notes| {
            let remote = git.select_sync_remote(remote.as_deref())?;
            let mut progress = SyncProgressReporter::from_environment(color.stderr());
            sync_notes(notes, channel, &remote, &mut progress)?;
            Ok(ExitCode::SUCCESS)
        }),
        CommandKind::Prune => with_selected_channel(git, channel, |_, notes| {
            notes.prune()?;
            Ok(ExitCode::SUCCESS)
        }),
    }
}

fn install_man_page(
    explicit_channel: Option<&str>,
    man_dir: Option<&Path>,
) -> Result<ExitCode, AppError> {
    if explicit_channel.is_some() {
        return Err(AppError::ChannelOptionNotAllowedForInstallMan);
    }

    let destination = manpage::install(man_dir).map_err(|error| AppError::ManPageInstall {
        details: error.to_string(),
    })?;
    writeln!(
        io::stdout().lock(),
        "Installed git-vet(1) at {}",
        destination.display()
    )?;
    Ok(ExitCode::SUCCESS)
}

fn run_channel_command(
    git: &Git,
    explicit_channel: Option<&str>,
    command: ChannelCommand,
) -> Result<ExitCode, AppError> {
    let (command_name, kind, source, destination) = match command {
        ChannelCommand::List { json } => {
            if explicit_channel.is_some() {
                return Err(AppError::ChannelOptionNotAllowedForList);
            }

            let channels = GitNotesChannelStore::new(git);
            list_channels(&channels, json)?;
            return Ok(ExitCode::SUCCESS);
        }
        ChannelCommand::Copy {
            source,
            destination,
        } => (
            "channel copy",
            ChannelTransferKind::Copy,
            source,
            destination,
        ),
        ChannelCommand::Move {
            source,
            destination,
        } => (
            "channel move",
            ChannelTransferKind::Move,
            source,
            destination,
        ),
        ChannelCommand::Remove { target, force } => {
            if explicit_channel.is_some() {
                return Err(AppError::ChannelOptionNotAllowedForRemove);
            }

            let channel = review_channel_from_input(&target, ReviewChannelSource::RemoveTarget)?;
            let channels = GitNotesChannelStore::new(git);
            remove_channel(&channels, &channel, force)?;
            return Ok(ExitCode::SUCCESS);
        }
    };

    if explicit_channel.is_some() {
        return Err(AppError::ChannelOptionNotAllowed {
            command: command_name,
        });
    }

    let source = review_channel_from_input(&source, ReviewChannelSource::TransferSource)?;
    let destination =
        review_channel_from_input(&destination, ReviewChannelSource::TransferDestination)?;
    let transfer = ChannelTransfer::new(kind, source, destination)?;
    let channels = GitNotesChannelStore::new(git);
    transfer_channel_notes(git, &channels, &transfer)?;
    Ok(ExitCode::SUCCESS)
}

fn with_selected_channel<T>(
    git: &Git,
    explicit_channel: Option<&str>,
    operation: impl FnOnce(&ReviewChannel, &GitNotesStore<'_>) -> Result<T, AppError>,
) -> Result<T, AppError> {
    let channel = review_channel_from_selection(explicit_channel, git)?;
    let notes = GitNotesStore::new(git, channel.notes_ref().clone());
    operation(&channel, &notes)
}

fn review_channel_from_selection(
    explicit: Option<&str>,
    git: &Git,
) -> Result<ReviewChannel, AppError> {
    match explicit {
        Some(input) => review_channel_from_input(input, ReviewChannelSource::Cli),
        None => git.configured_review_channel()?.map_or_else(
            || {
                review_channel_from_input(
                    DEFAULT_REVIEW_CHANNEL,
                    ReviewChannelSource::BuiltInDefault,
                )
            },
            |input| review_channel_from_input(&input, ReviewChannelSource::Config),
        ),
    }
}

#[derive(Clone, Copy, Debug)]
enum ReviewChannelSource {
    Cli,
    Config,
    BuiltInDefault,
    TransferSource,
    TransferDestination,
    RemoveTarget,
}

fn review_channel_from_input(
    input: &str,
    source: ReviewChannelSource,
) -> Result<ReviewChannel, AppError> {
    ReviewChannel::new(input).map_err(|error| channel_error_from_source(input, &error, source))
}

fn channel_error_from_source(
    input: &str,
    error: &ChannelError,
    source: ReviewChannelSource,
) -> AppError {
    AppError::InvalidChannel {
        channel: input.to_owned(),
        details: details_from_source(error.to_string(), source),
    }
}

fn details_from_source(details: String, source: ReviewChannelSource) -> String {
    match source {
        ReviewChannelSource::Config => format!("from git config vet.channel: {details}"),
        ReviewChannelSource::TransferSource => format!("from SOURCE argument: {details}"),
        ReviewChannelSource::TransferDestination => {
            format!("from DESTINATION argument: {details}")
        }
        ReviewChannelSource::RemoveTarget => format!("from CHANNEL argument: {details}"),
        ReviewChannelSource::Cli | ReviewChannelSource::BuiltInDefault => details,
    }
}