2022-11-26 23:57:50 +00:00
// Copyright 2022 The Jujutsu Authors
2022-09-22 04:44:46 +00:00
//
// 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.
2024-01-20 22:23:43 +00:00
use core ::fmt ;
2023-12-31 01:39:24 +00:00
use std ::collections ::{ HashMap , HashSet } ;
2023-01-04 08:18:45 +00:00
use std ::env ::{ self , ArgsOs , VarError } ;
2022-11-28 14:32:44 +00:00
use std ::ffi ::{ OsStr , OsString } ;
2022-09-22 04:44:46 +00:00
use std ::fmt ::Debug ;
2024-01-22 22:06:47 +00:00
use std ::io ::{ self , Write as _ } ;
2022-11-28 14:32:44 +00:00
use std ::ops ::Deref ;
2022-12-22 03:58:06 +00:00
use std ::path ::{ Path , PathBuf } ;
2023-01-19 15:10:18 +00:00
use std ::process ::ExitCode ;
2022-11-01 07:14:21 +00:00
use std ::rc ::Rc ;
2023-01-15 04:23:44 +00:00
use std ::str ::FromStr ;
2022-09-22 04:44:46 +00:00
use std ::sync ::Arc ;
2023-07-08 12:45:38 +00:00
use std ::time ::SystemTime ;
2024-01-22 22:06:47 +00:00
use std ::{ fs , iter , str } ;
2022-09-22 04:44:46 +00:00
2022-11-28 14:32:44 +00:00
use clap ::builder ::{ NonEmptyStringValueParser , TypedValueParser , ValueParserFactory } ;
2023-01-26 22:19:20 +00:00
use clap ::{ Arg , ArgAction , ArgMatches , Command , FromArgMatches } ;
2023-11-20 02:10:39 +00:00
use indexmap ::{ IndexMap , IndexSet } ;
2022-09-22 04:44:46 +00:00
use itertools ::Itertools ;
2024-01-04 07:18:04 +00:00
use jj_lib ::backend ::{ BackendError , ChangeId , CommitId , MergedTreeId } ;
2023-06-28 14:12:40 +00:00
use jj_lib ::commit ::Commit ;
2024-01-18 01:57:43 +00:00
use jj_lib ::git ::{ GitConfigParseError , GitExportError , GitImportError , GitRemoteManagementError } ;
2023-06-28 14:12:40 +00:00
use jj_lib ::git_backend ::GitBackend ;
2024-02-16 17:54:09 +00:00
use jj_lib ::gitignore ::{ GitIgnoreError , GitIgnoreFile } ;
2023-06-28 14:12:40 +00:00
use jj_lib ::hex_util ::to_reverse_hex ;
use jj_lib ::id_prefix ::IdPrefixContext ;
2023-11-02 04:54:56 +00:00
use jj_lib ::matchers ::{ EverythingMatcher , Matcher , PrefixMatcher } ;
use jj_lib ::merged_tree ::MergedTree ;
2024-01-04 07:18:04 +00:00
use jj_lib ::object_id ::ObjectId ;
2023-12-31 01:39:24 +00:00
use jj_lib ::op_heads_store ::{ self , OpHeadResolutionError } ;
use jj_lib ::op_store ::{ OpStoreError , OperationId , WorkspaceId } ;
use jj_lib ::op_walk ::OpsetEvaluationError ;
2023-06-28 14:12:40 +00:00
use jj_lib ::operation ::Operation ;
use jj_lib ::repo ::{
2023-02-13 17:52:21 +00:00
CheckOutCommitError , EditCommitError , MutableRepo , ReadonlyRepo , Repo , RepoLoader ,
2023-07-25 14:40:12 +00:00
RepoLoaderError , RewriteRootCommit , StoreFactories , StoreLoadError ,
2023-01-11 21:12:17 +00:00
} ;
2023-11-26 07:12:36 +00:00
use jj_lib ::repo_path ::{ FsPathParseError , RepoPath , RepoPathBuf } ;
2023-06-28 14:12:40 +00:00
use jj_lib ::revset ::{
2023-09-09 22:47:27 +00:00
DefaultSymbolResolver , Revset , RevsetAliasesMap , RevsetCommitRef , RevsetEvaluationError ,
2023-11-20 02:10:39 +00:00
RevsetExpression , RevsetFilterPredicate , RevsetIteratorExt , RevsetParseContext ,
RevsetParseError , RevsetParseErrorKind , RevsetResolutionError , RevsetWorkspaceContext ,
2022-10-23 03:41:50 +00:00
} ;
2023-11-02 04:54:56 +00:00
use jj_lib ::rewrite ::restore_tree ;
2023-06-28 14:12:40 +00:00
use jj_lib ::settings ::{ ConfigResultExt as _ , UserSettings } ;
2023-11-24 21:08:16 +00:00
use jj_lib ::signing ::SignInitError ;
2023-10-23 23:24:27 +00:00
use jj_lib ::str_util ::{ StringPattern , StringPatternParseError } ;
2023-06-28 14:12:40 +00:00
use jj_lib ::transaction ::Transaction ;
2023-08-27 12:57:00 +00:00
use jj_lib ::tree ::TreeMergeError ;
2024-01-15 22:31:33 +00:00
use jj_lib ::view ::View ;
2023-10-12 13:10:31 +00:00
use jj_lib ::working_copy ::{
2023-10-12 16:13:58 +00:00
CheckoutStats , LockedWorkingCopy , ResetError , SnapshotError , SnapshotOptions , WorkingCopy ,
2024-01-25 16:30:11 +00:00
WorkingCopyFactory , WorkingCopyStateError ,
2023-10-12 13:10:31 +00:00
} ;
2023-10-15 18:42:25 +00:00
use jj_lib ::workspace ::{
2024-01-25 16:30:11 +00:00
default_working_copy_factories , LockedWorkspace , Workspace , WorkspaceInitError ,
WorkspaceLoadError , WorkspaceLoader ,
2023-10-15 18:42:25 +00:00
} ;
2023-12-31 01:39:24 +00:00
use jj_lib ::{ dag_walk , file_util , git , op_walk , revset } ;
2023-05-04 00:54:08 +00:00
use once_cell ::unsync ::OnceCell ;
2024-01-31 02:35:56 +00:00
use thiserror ::Error ;
2023-01-15 04:23:44 +00:00
use toml_edit ;
2023-07-25 17:51:44 +00:00
use tracing ::instrument ;
2023-07-08 12:45:38 +00:00
use tracing_chrome ::ChromeLayerBuilder ;
2023-01-03 07:24:44 +00:00
use tracing_subscriber ::prelude ::* ;
2022-09-22 04:44:46 +00:00
2023-01-15 04:23:44 +00:00
use crate ::config ::{
2023-07-12 21:08:58 +00:00
new_config_path , AnnotatedValue , CommandNameAndArgs , ConfigSource , LayeredConfigs ,
2023-01-15 04:23:44 +00:00
} ;
2023-03-05 04:10:02 +00:00
use crate ::formatter ::{ FormatRecorder , Formatter , PlainTextFormatter } ;
2024-02-05 08:27:39 +00:00
use crate ::git_util ::{
is_colocated_git_workspace , print_failed_git_export , print_git_import_stats ,
} ;
2023-08-02 03:12:11 +00:00
use crate ::merge_tools ::{ ConflictResolveError , DiffEditError , DiffGenerateError } ;
2023-02-18 08:22:57 +00:00
use crate ::template_parser ::{ TemplateAliasesMap , TemplateParseError } ;
2023-02-12 09:06:48 +00:00
use crate ::templater ::Template ;
2022-10-21 04:50:03 +00:00
use crate ::ui ::{ ColorChoice , Ui } ;
2023-03-04 07:55:01 +00:00
use crate ::{ commit_templater , text_util } ;
2022-09-22 04:44:46 +00:00
2023-01-10 00:42:48 +00:00
#[ derive(Clone, Debug) ]
2022-09-22 04:44:46 +00:00
pub enum CommandError {
2022-11-12 23:28:32 +00:00
UserError {
2024-01-31 11:45:03 +00:00
err : Arc < dyn std ::error ::Error + Send + Sync > ,
2022-11-12 23:28:32 +00:00
hint : Option < String > ,
} ,
2022-09-24 14:15:23 +00:00
ConfigError ( String ) ,
2022-09-22 04:44:46 +00:00
/// Invalid command line
CliError ( String ) ,
2022-10-31 17:49:53 +00:00
/// Invalid command line detected by clap
2023-01-10 00:42:48 +00:00
ClapCliError ( Arc < clap ::Error > ) ,
2022-09-22 04:44:46 +00:00
BrokenPipe ,
2024-01-31 02:35:56 +00:00
InternalError ( Arc < dyn std ::error ::Error + Send + Sync > ) ,
}
/// Wraps error with user-visible message.
#[ derive(Debug, Error) ]
2024-01-31 03:33:23 +00:00
#[ error( " {message} " ) ]
2024-01-31 02:35:56 +00:00
struct ErrorWithMessage {
message : String ,
source : Box < dyn std ::error ::Error + Send + Sync > ,
}
impl ErrorWithMessage {
fn new (
message : impl Into < String > ,
source : impl Into < Box < dyn std ::error ::Error + Send + Sync > > ,
) -> Self {
ErrorWithMessage {
message : message . into ( ) ,
source : source . into ( ) ,
}
}
2022-09-22 04:44:46 +00:00
}
2024-01-31 11:45:03 +00:00
pub fn user_error ( err : impl Into < Box < dyn std ::error ::Error + Send + Sync > > ) -> CommandError {
user_error_with_hint_opt ( err , None )
}
pub fn user_error_with_hint (
err : impl Into < Box < dyn std ::error ::Error + Send + Sync > > ,
hint : impl Into < String > ,
) -> CommandError {
user_error_with_hint_opt ( err , Some ( hint . into ( ) ) )
}
pub fn user_error_with_message (
message : impl Into < String > ,
source : impl Into < Box < dyn std ::error ::Error + Send + Sync > > ,
) -> CommandError {
user_error_with_hint_opt ( ErrorWithMessage ::new ( message , source ) , None )
2022-11-12 23:28:32 +00:00
}
2024-01-31 11:45:03 +00:00
pub fn user_error_with_message_and_hint (
message : impl Into < String > ,
hint : impl Into < String > ,
source : impl Into < Box < dyn std ::error ::Error + Send + Sync > > ,
) -> CommandError {
user_error_with_hint_opt ( ErrorWithMessage ::new ( message , source ) , Some ( hint . into ( ) ) )
}
pub fn user_error_with_hint_opt (
err : impl Into < Box < dyn std ::error ::Error + Send + Sync > > ,
hint : Option < String > ,
) -> CommandError {
2022-11-12 23:28:32 +00:00
CommandError ::UserError {
2024-01-31 11:45:03 +00:00
err : Arc ::from ( err . into ( ) ) ,
hint ,
2022-11-12 23:28:32 +00:00
}
2022-11-12 22:38:43 +00:00
}
2024-01-31 02:35:56 +00:00
pub fn internal_error ( err : impl Into < Box < dyn std ::error ::Error + Send + Sync > > ) -> CommandError {
CommandError ::InternalError ( Arc ::from ( err . into ( ) ) )
}
pub fn internal_error_with_message (
message : impl Into < String > ,
source : impl Into < Box < dyn std ::error ::Error + Send + Sync > > ,
) -> CommandError {
CommandError ::InternalError ( Arc ::new ( ErrorWithMessage ::new ( message , source ) ) )
}
2023-03-23 09:03:01 +00:00
fn format_similarity_hint < S : AsRef < str > > ( candidates : & [ S ] ) -> Option < String > {
match candidates {
[ ] = > None ,
names = > {
let quoted_names = names
. iter ( )
. map ( | s | format! ( r # ""{}""# , s . as_ref ( ) ) )
. join ( " , " ) ;
Some ( format! ( " Did you mean {quoted_names} ? " ) )
}
}
}
2024-01-31 03:33:23 +00:00
fn print_error_sources ( ui : & Ui , source : Option < & dyn std ::error ::Error > ) -> io ::Result < ( ) > {
let Some ( err ) = source else {
return Ok ( ( ) ) ;
} ;
if err . source ( ) . is_none ( ) {
writeln! ( ui . stderr ( ) , " Caused by: {err} " ) ? ;
} else {
writeln! ( ui . stderr ( ) , " Caused by: " ) ? ;
for ( i , err ) in iter ::successors ( Some ( err ) , | err | err . source ( ) ) . enumerate ( ) {
2024-02-03 08:26:10 +00:00
writeln! ( ui . stderr ( ) , " {n}: {err} " , n = i + 1 ) ? ;
2024-01-31 03:33:23 +00:00
}
}
Ok ( ( ) )
}
2022-09-22 04:44:46 +00:00
impl From < std ::io ::Error > for CommandError {
fn from ( err : std ::io ::Error ) -> Self {
if err . kind ( ) = = std ::io ::ErrorKind ::BrokenPipe {
CommandError ::BrokenPipe
} else {
2024-02-01 08:28:53 +00:00
user_error ( err )
2022-09-22 04:44:46 +00:00
}
}
}
impl From < config ::ConfigError > for CommandError {
fn from ( err : config ::ConfigError ) -> Self {
2022-09-24 14:15:23 +00:00
CommandError ::ConfigError ( err . to_string ( ) )
2022-09-22 04:44:46 +00:00
}
}
2023-01-01 07:29:46 +00:00
impl From < crate ::config ::ConfigError > for CommandError {
fn from ( err : crate ::config ::ConfigError ) -> Self {
CommandError ::ConfigError ( err . to_string ( ) )
}
}
2022-10-20 23:33:14 +00:00
impl From < RewriteRootCommit > for CommandError {
fn from ( err : RewriteRootCommit ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Attempted to rewrite the root commit " , err )
2022-10-20 23:33:14 +00:00
}
}
2023-01-23 05:02:41 +00:00
impl From < EditCommitError > for CommandError {
fn from ( err : EditCommitError ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to edit a commit " , err )
2023-01-23 05:02:41 +00:00
}
}
2023-01-23 05:38:06 +00:00
impl From < CheckOutCommitError > for CommandError {
fn from ( err : CheckOutCommitError ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to check out a commit " , err )
2023-01-23 05:38:06 +00:00
}
}
2022-09-22 04:44:46 +00:00
impl From < BackendError > for CommandError {
fn from ( err : BackendError ) -> Self {
2024-01-31 11:52:27 +00:00
internal_error_with_message ( " Unexpected error from backend " , err )
2022-09-22 04:44:46 +00:00
}
}
impl From < WorkspaceInitError > for CommandError {
2023-02-03 18:20:03 +00:00
fn from ( err : WorkspaceInitError ) -> Self {
match err {
WorkspaceInitError ::DestinationExists ( _ ) = > {
user_error ( " The target repo already exists " )
}
WorkspaceInitError ::NonUnicodePath = > {
user_error ( " The target repo path contains non-unicode characters " )
}
2024-01-31 02:35:56 +00:00
WorkspaceInitError ::CheckOutCommit ( err ) = > {
internal_error_with_message ( " Failed to check out the initial commit " , err )
}
2023-02-03 18:20:03 +00:00
WorkspaceInitError ::Path ( err ) = > {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to access the repository " , err )
2023-02-03 18:20:03 +00:00
}
2024-01-08 10:41:07 +00:00
WorkspaceInitError ::PathNotFound ( path ) = > {
user_error ( format! ( " {} doesn't exist " , path . display ( ) ) )
}
2023-06-10 03:31:37 +00:00
WorkspaceInitError ::Backend ( err ) = > {
2024-01-31 11:45:03 +00:00
user_error_with_message ( " Failed to access the repository " , err )
2023-06-10 03:31:37 +00:00
}
2023-10-11 20:20:25 +00:00
WorkspaceInitError ::WorkingCopyState ( err ) = > {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to access the repository " , err )
2023-07-14 19:45:00 +00:00
}
2024-01-31 11:45:03 +00:00
WorkspaceInitError ::SignInit ( err @ SignInitError ::UnknownBackend ( _ ) ) = > user_error ( err ) ,
2024-01-31 02:35:56 +00:00
WorkspaceInitError ::SignInit ( err ) = > internal_error ( err ) ,
2023-02-03 18:20:03 +00:00
}
2022-09-22 04:44:46 +00:00
}
}
2023-12-30 13:20:25 +00:00
impl From < OpHeadResolutionError > for CommandError {
fn from ( err : OpHeadResolutionError ) -> Self {
2022-09-22 04:44:46 +00:00
match err {
2024-01-31 02:35:56 +00:00
OpHeadResolutionError ::NoHeads = > {
internal_error_with_message ( " Corrupt repository " , err )
}
2022-09-22 04:44:46 +00:00
}
}
}
2023-12-30 13:56:50 +00:00
impl From < OpsetEvaluationError > for CommandError {
fn from ( err : OpsetEvaluationError ) -> Self {
match err {
2024-01-31 11:45:03 +00:00
OpsetEvaluationError ::OpsetResolution ( err ) = > user_error ( err ) ,
2023-12-30 13:56:50 +00:00
OpsetEvaluationError ::OpHeadResolution ( err ) = > err . into ( ) ,
OpsetEvaluationError ::OpStore ( err ) = > err . into ( ) ,
}
}
}
2022-09-22 04:44:46 +00:00
impl From < SnapshotError > for CommandError {
fn from ( err : SnapshotError ) -> Self {
2023-09-01 16:08:43 +00:00
match err {
2024-01-31 11:45:03 +00:00
SnapshotError ::NewFileTooLarge { .. } = > user_error_with_message_and_hint (
" Failed to snapshot the working copy " ,
2023-09-01 16:08:43 +00:00
r #" Increase the value of the `snapshot.max-new-file-size` config option if you
want this file to be snapshotted . Otherwise add it to your ` . gitignore ` file . " #,
2024-01-31 11:45:03 +00:00
err ,
2023-09-01 16:08:43 +00:00
) ,
2024-01-31 02:35:56 +00:00
err = > internal_error_with_message ( " Failed to snapshot the working copy " , err ) ,
2023-09-01 16:08:43 +00:00
}
2022-09-22 04:44:46 +00:00
}
}
impl From < TreeMergeError > for CommandError {
fn from ( err : TreeMergeError ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Merge failed " , err )
2022-09-22 04:44:46 +00:00
}
}
2023-07-25 14:40:12 +00:00
impl From < OpStoreError > for CommandError {
fn from ( err : OpStoreError ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to load an operation " , err )
2023-07-25 14:40:12 +00:00
}
}
impl From < RepoLoaderError > for CommandError {
fn from ( err : RepoLoaderError ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to load the repo " , err )
2023-07-25 14:40:12 +00:00
}
}
2022-09-22 04:44:46 +00:00
impl From < ResetError > for CommandError {
2024-01-31 02:35:56 +00:00
fn from ( err : ResetError ) -> Self {
internal_error_with_message ( " Failed to reset the working copy " , err )
2022-09-22 04:44:46 +00:00
}
}
impl From < DiffEditError > for CommandError {
fn from ( err : DiffEditError ) -> Self {
2024-01-31 11:45:03 +00:00
user_error_with_message ( " Failed to edit diff " , err )
2022-09-22 04:44:46 +00:00
}
}
2023-08-02 03:12:11 +00:00
impl From < DiffGenerateError > for CommandError {
fn from ( err : DiffGenerateError ) -> Self {
2024-01-31 11:45:03 +00:00
user_error_with_message ( " Failed to generate diff " , err )
2023-08-02 03:12:11 +00:00
}
}
2022-10-28 03:30:44 +00:00
impl From < ConflictResolveError > for CommandError {
fn from ( err : ConflictResolveError ) -> Self {
2024-01-31 11:45:03 +00:00
user_error_with_message ( " Failed to resolve conflicts " , err )
2022-10-28 03:30:44 +00:00
}
}
2022-09-22 04:44:46 +00:00
impl From < git2 ::Error > for CommandError {
fn from ( err : git2 ::Error ) -> Self {
2024-01-31 11:45:03 +00:00
user_error_with_message ( " Git operation failed " , err )
2022-09-22 04:44:46 +00:00
}
}
impl From < GitImportError > for CommandError {
fn from ( err : GitImportError ) -> Self {
2023-08-09 21:21:13 +00:00
let message = format! ( " Failed to import refs from underlying Git repo: {err} " ) ;
2023-08-29 04:45:56 +00:00
let hint = match & err {
GitImportError ::MissingHeadTarget { .. }
| GitImportError ::MissingRefAncestor { .. } = > Some (
" \
2023-08-09 21:21:13 +00:00
Is this Git repository a shallow or partial clone ( cloned with the - - depth or - - filter \
2023-08-29 04:45:56 +00:00
argument ) ?
jj currently does not support shallow / partial clones . To use jj with this \
repository , try
2023-08-09 21:21:13 +00:00
unshallowing the repository ( https ://stackoverflow.com/q/6802145) or re-cloning with the full
repository contents . "
2023-08-29 04:45:56 +00:00
. to_string ( ) ,
) ,
GitImportError ::RemoteReservedForLocalGitRepo = > {
Some ( " Run `jj git remote rename` to give different name. " . to_string ( ) )
}
2023-12-21 00:38:16 +00:00
GitImportError ::InternalBackend ( _ ) = > None ,
2023-08-29 04:45:56 +00:00
GitImportError ::InternalGitError ( _ ) = > None ,
2023-11-08 10:20:46 +00:00
GitImportError ::UnexpectedBackend = > None ,
2023-08-29 04:45:56 +00:00
} ;
2024-01-31 11:45:03 +00:00
user_error_with_hint_opt ( message , hint )
2022-09-22 04:44:46 +00:00
}
}
impl From < GitExportError > for CommandError {
fn from ( err : GitExportError ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to export refs to underlying Git repo " , err )
2022-09-22 04:44:46 +00:00
}
}
2023-08-19 03:58:18 +00:00
impl From < GitRemoteManagementError > for CommandError {
fn from ( err : GitRemoteManagementError ) -> Self {
2024-01-31 11:45:03 +00:00
user_error ( err )
2023-08-19 03:58:18 +00:00
}
}
2023-04-02 01:59:22 +00:00
impl From < RevsetEvaluationError > for CommandError {
fn from ( err : RevsetEvaluationError ) -> Self {
2024-01-31 11:45:03 +00:00
user_error ( err )
2023-04-02 01:59:22 +00:00
}
}
2022-09-22 04:44:46 +00:00
impl From < RevsetParseError > for CommandError {
fn from ( err : RevsetParseError ) -> Self {
2022-11-25 09:46:30 +00:00
let message = iter ::successors ( Some ( & err ) , | e | e . origin ( ) ) . join ( " \n " ) ;
2023-03-23 09:03:01 +00:00
// Only for the top-level error as we can't attach hint to inner errors
let hint = match err . kind ( ) {
2024-02-13 05:46:21 +00:00
RevsetParseErrorKind ::NotPrefixOperator {
op : _ ,
similar_op ,
description ,
}
| RevsetParseErrorKind ::NotPostfixOperator {
2023-03-23 10:07:34 +00:00
op : _ ,
similar_op ,
description ,
}
| RevsetParseErrorKind ::NotInfixOperator {
op : _ ,
similar_op ,
description ,
} = > Some ( format! ( " Did you mean ' {similar_op} ' for {description} ? " ) ) ,
2023-06-05 04:55:59 +00:00
RevsetParseErrorKind ::NoSuchFunction {
name : _ ,
candidates ,
} = > format_similarity_hint ( candidates ) ,
2023-03-23 09:03:01 +00:00
_ = > None ,
} ;
2024-01-31 11:45:03 +00:00
user_error_with_hint_opt ( format! ( " Failed to parse revset: {message} " ) , hint )
2022-09-22 04:44:46 +00:00
}
}
2023-04-02 01:59:22 +00:00
impl From < RevsetResolutionError > for CommandError {
fn from ( err : RevsetResolutionError ) -> Self {
2023-06-05 04:35:34 +00:00
let hint = match & err {
RevsetResolutionError ::NoSuchRevision {
name : _ ,
candidates ,
} = > format_similarity_hint ( candidates ) ,
RevsetResolutionError ::EmptyString
2023-04-09 23:18:32 +00:00
| RevsetResolutionError ::WorkspaceMissingWorkingCopy { .. }
2023-06-05 04:35:34 +00:00
| RevsetResolutionError ::AmbiguousCommitIdPrefix ( _ )
| RevsetResolutionError ::AmbiguousChangeIdPrefix ( _ )
| RevsetResolutionError ::StoreError ( _ ) = > None ,
} ;
2024-01-31 11:45:03 +00:00
user_error_with_hint_opt ( err , hint )
2022-09-22 04:44:46 +00:00
}
}
2023-02-02 08:57:55 +00:00
impl From < TemplateParseError > for CommandError {
fn from ( err : TemplateParseError ) -> Self {
2023-02-12 09:48:12 +00:00
let message = iter ::successors ( Some ( & err ) , | e | e . origin ( ) ) . join ( " \n " ) ;
user_error ( format! ( " Failed to parse template: {message} " ) )
2023-02-02 08:57:55 +00:00
}
}
2022-10-21 04:50:03 +00:00
impl From < FsPathParseError > for CommandError {
fn from ( err : FsPathParseError ) -> Self {
2024-01-31 11:45:03 +00:00
user_error ( err )
2022-09-22 04:44:46 +00:00
}
}
2022-10-31 17:49:53 +00:00
impl From < clap ::Error > for CommandError {
fn from ( err : clap ::Error ) -> Self {
2023-01-10 00:42:48 +00:00
CommandError ::ClapCliError ( Arc ::new ( err ) )
2022-10-31 17:49:53 +00:00
}
}
2023-04-03 23:28:19 +00:00
impl From < GitConfigParseError > for CommandError {
fn from ( err : GitConfigParseError ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to parse Git config " , err )
2023-04-03 23:28:19 +00:00
}
}
2023-10-11 20:20:25 +00:00
impl From < WorkingCopyStateError > for CommandError {
fn from ( err : WorkingCopyStateError ) -> Self {
2024-01-31 02:35:56 +00:00
internal_error_with_message ( " Failed to access working copy state " , err )
2023-07-14 19:45:00 +00:00
}
}
2024-02-16 17:54:09 +00:00
impl From < GitIgnoreError > for CommandError {
fn from ( err : GitIgnoreError ) -> Self {
user_error_with_message ( " Failed to process .gitignore. " , err )
}
}
2023-07-08 12:45:38 +00:00
#[ derive(Clone) ]
struct ChromeTracingFlushGuard {
_inner : Option < Rc < tracing_chrome ::FlushGuard > > ,
}
impl Debug for ChromeTracingFlushGuard {
fn fmt ( & self , f : & mut std ::fmt ::Formatter < '_ > ) -> std ::fmt ::Result {
let Self { _inner } = self ;
f . debug_struct ( " ChromeTracingFlushGuard " )
2023-07-25 17:51:44 +00:00
. finish_non_exhaustive ( )
2023-07-08 12:45:38 +00:00
}
}
2023-01-03 07:24:44 +00:00
/// Handle to initialize or change tracing subscription.
#[ derive(Clone, Debug) ]
pub struct TracingSubscription {
reload_log_filter : tracing_subscriber ::reload ::Handle <
tracing_subscriber ::EnvFilter ,
tracing_subscriber ::Registry ,
> ,
2023-07-08 12:45:38 +00:00
_chrome_tracing_flush_guard : ChromeTracingFlushGuard ,
2023-01-03 07:24:44 +00:00
}
impl TracingSubscription {
/// Initializes tracing with the default configuration. This should be
/// called as early as possible.
pub fn init ( ) -> Self {
let filter = tracing_subscriber ::EnvFilter ::builder ( )
2023-05-03 03:58:08 +00:00
. with_default_directive ( tracing ::metadata ::LevelFilter ::ERROR . into ( ) )
2023-01-03 07:24:44 +00:00
. from_env_lossy ( ) ;
let ( filter , reload_log_filter ) = tracing_subscriber ::reload ::Layer ::new ( filter ) ;
2023-07-08 12:45:38 +00:00
let ( chrome_tracing_layer , chrome_tracing_flush_guard ) = match std ::env ::var ( " JJ_TRACE " ) {
2023-07-03 15:34:46 +00:00
Ok ( filename ) = > {
let filename = if filename . is_empty ( ) {
format! (
" jj-trace-{}.json " ,
SystemTime ::now ( )
. duration_since ( SystemTime ::UNIX_EPOCH )
. unwrap ( )
. as_secs ( ) ,
)
} else {
filename
} ;
2023-07-08 12:45:38 +00:00
let include_args = std ::env ::var ( " JJ_TRACE_INCLUDE_ARGS " ) . is_ok ( ) ;
let ( layer , guard ) = ChromeLayerBuilder ::new ( )
. file ( filename )
. include_args ( include_args )
. build ( ) ;
(
Some ( layer ) ,
ChromeTracingFlushGuard {
_inner : Some ( Rc ::new ( guard ) ) ,
} ,
)
}
Err ( _ ) = > ( None , ChromeTracingFlushGuard { _inner : None } ) ,
} ;
2023-01-03 07:24:44 +00:00
tracing_subscriber ::registry ( )
2023-07-08 12:45:38 +00:00
. with (
tracing_subscriber ::fmt ::Layer ::default ( )
. with_writer ( std ::io ::stderr )
. with_filter ( filter ) ,
)
. with ( chrome_tracing_layer )
2023-01-03 07:24:44 +00:00
. init ( ) ;
2023-07-08 12:45:38 +00:00
TracingSubscription {
reload_log_filter ,
_chrome_tracing_flush_guard : chrome_tracing_flush_guard ,
}
2023-01-03 07:24:44 +00:00
}
2024-02-18 16:47:12 +00:00
pub fn enable_debug_logging ( & self ) -> Result < ( ) , CommandError > {
2023-01-03 07:24:44 +00:00
self . reload_log_filter
. modify ( | filter | {
* filter = tracing_subscriber ::EnvFilter ::builder ( )
. with_default_directive ( tracing ::metadata ::LevelFilter ::DEBUG . into ( ) )
. from_env_lossy ( )
} )
2024-02-18 16:47:12 +00:00
. map_err ( | err | internal_error_with_message ( " failed to enable debug logging " , err ) ) ? ;
tracing ::info! ( " debug logging enabled " ) ;
2023-01-03 07:24:44 +00:00
Ok ( ( ) )
}
}
2022-09-29 16:12:16 +00:00
pub struct CommandHelper {
2023-01-26 22:23:19 +00:00
app : Command ,
2023-01-04 08:18:45 +00:00
cwd : PathBuf ,
2022-09-22 04:44:46 +00:00
string_args : Vec < String > ,
2023-04-29 13:31:03 +00:00
matches : ArgMatches ,
2022-09-22 04:44:46 +00:00
global_args : GlobalArgs ,
2023-01-04 08:57:36 +00:00
settings : UserSettings ,
2023-01-12 06:24:39 +00:00
layered_configs : LayeredConfigs ,
2023-01-10 00:53:22 +00:00
maybe_workspace_loader : Result < WorkspaceLoader , CommandError > ,
2022-12-14 18:08:31 +00:00
store_factories : StoreFactories ,
2024-01-25 16:30:11 +00:00
working_copy_factories : HashMap < String , Box < dyn WorkingCopyFactory > > ,
2022-09-22 04:44:46 +00:00
}
2022-09-29 16:12:16 +00:00
impl CommandHelper {
2023-01-12 06:24:39 +00:00
#[ allow(clippy::too_many_arguments) ]
2023-01-04 08:16:53 +00:00
pub fn new (
2023-01-26 22:23:19 +00:00
app : Command ,
2023-01-04 08:18:45 +00:00
cwd : PathBuf ,
2023-01-04 08:16:53 +00:00
string_args : Vec < String > ,
2023-04-29 13:31:03 +00:00
matches : ArgMatches ,
2023-01-04 08:16:53 +00:00
global_args : GlobalArgs ,
2023-01-04 08:57:36 +00:00
settings : UserSettings ,
2023-01-12 06:24:39 +00:00
layered_configs : LayeredConfigs ,
2023-01-10 00:53:22 +00:00
maybe_workspace_loader : Result < WorkspaceLoader , CommandError > ,
2023-01-04 08:16:53 +00:00
store_factories : StoreFactories ,
2024-01-25 16:30:11 +00:00
working_copy_factories : HashMap < String , Box < dyn WorkingCopyFactory > > ,
2023-01-04 08:16:53 +00:00
) -> Self {
2023-05-01 03:14:10 +00:00
// `cwd` is canonicalized for consistency with `Workspace::workspace_root()` and
// to easily compute relative paths between them.
let cwd = cwd . canonicalize ( ) . unwrap_or ( cwd ) ;
2022-09-22 04:44:46 +00:00
Self {
app ,
2023-01-04 08:18:45 +00:00
cwd ,
2022-09-22 04:44:46 +00:00
string_args ,
2023-04-29 13:31:03 +00:00
matches ,
2022-09-22 04:44:46 +00:00
global_args ,
2023-01-04 08:57:36 +00:00
settings ,
2023-01-12 06:24:39 +00:00
layered_configs ,
2023-01-10 00:53:22 +00:00
maybe_workspace_loader ,
2023-01-04 08:16:53 +00:00
store_factories ,
2023-10-14 12:52:50 +00:00
working_copy_factories ,
2022-09-22 04:44:46 +00:00
}
}
2023-01-26 22:23:19 +00:00
pub fn app ( & self ) -> & Command {
2022-09-22 04:44:46 +00:00
& self . app
}
2023-01-04 08:18:45 +00:00
pub fn cwd ( & self ) -> & Path {
& self . cwd
}
2022-09-22 04:44:46 +00:00
pub fn string_args ( & self ) -> & Vec < String > {
& self . string_args
}
2023-04-29 13:31:03 +00:00
pub fn matches ( & self ) -> & ArgMatches {
& self . matches
}
2022-09-22 04:44:46 +00:00
pub fn global_args ( & self ) -> & GlobalArgs {
& self . global_args
}
2023-01-04 08:57:36 +00:00
pub fn settings ( & self ) -> & UserSettings {
& self . settings
}
2023-01-12 06:24:39 +00:00
pub fn resolved_config_values (
& self ,
prefix : & [ & str ] ,
) -> Result < Vec < AnnotatedValue > , crate ::config ::ConfigError > {
self . layered_configs . resolved_config_values ( prefix )
}
2024-01-11 03:31:54 +00:00
/// Loads template aliases from the configs.
///
/// For most commands that depend on a loaded repo, you should use
/// `WorkspaceCommandHelper::template_aliases_map()` instead.
pub fn load_template_aliases ( & self , ui : & Ui ) -> Result < TemplateAliasesMap , CommandError > {
load_template_aliases ( ui , & self . layered_configs )
}
2023-02-27 00:02:53 +00:00
pub fn workspace_loader ( & self ) -> Result < & WorkspaceLoader , CommandError > {
self . maybe_workspace_loader . as_ref ( ) . map_err ( Clone ::clone )
}
2024-01-11 10:46:57 +00:00
/// Loads workspace and repo, then snapshots the working copy if allowed.
2023-07-25 17:51:44 +00:00
#[ instrument(skip(self, ui)) ]
2023-01-11 21:12:17 +00:00
pub fn workspace_helper ( & self , ui : & mut Ui ) -> Result < WorkspaceCommandHelper , CommandError > {
2024-01-11 10:46:57 +00:00
let mut workspace_command = self . workspace_helper_no_snapshot ( ui ) ? ;
2024-01-11 10:57:13 +00:00
workspace_command . maybe_snapshot ( ui ) ? ;
2024-01-11 10:46:57 +00:00
Ok ( workspace_command )
2023-01-11 21:12:17 +00:00
}
2024-01-11 10:46:57 +00:00
/// Loads workspace and repo, but never snapshots the working copy. Most
/// commands should use `workspace_helper()` instead.
#[ instrument(skip(self, ui)) ]
2023-01-11 21:12:17 +00:00
pub fn workspace_helper_no_snapshot (
& self ,
ui : & mut Ui ,
) -> Result < WorkspaceCommandHelper , CommandError > {
2024-01-11 10:46:57 +00:00
let workspace = self . load_workspace ( ) ? ;
let op_head = self . resolve_operation ( ui , workspace . repo_loader ( ) ) ? ;
let repo = workspace . repo_loader ( ) . load_at ( & op_head ) ? ;
self . for_loaded_repo ( ui , workspace , repo )
2023-01-11 21:12:17 +00:00
}
2024-01-25 17:25:02 +00:00
pub fn get_working_copy_factory ( & self ) -> Result < & dyn WorkingCopyFactory , CommandError > {
let loader = self . workspace_loader ( ) ? ;
// We convert StoreLoadError -> WorkspaceLoadError -> CommandError
let factory : Result < _ , WorkspaceLoadError > = loader
. get_working_copy_factory ( & self . working_copy_factories )
. map_err ( | e | e . into ( ) ) ;
let factory = factory
. map_err ( | err | map_workspace_load_error ( err , self . global_args . repository . as_deref ( ) ) ) ? ;
Ok ( factory )
}
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2023-01-04 08:57:36 +00:00
pub fn load_workspace ( & self ) -> Result < Workspace , CommandError > {
2023-02-27 00:02:53 +00:00
let loader = self . workspace_loader ( ) ? ;
2023-01-10 00:53:22 +00:00
loader
2023-10-14 12:52:50 +00:00
. load (
& self . settings ,
& self . store_factories ,
& self . working_copy_factories ,
)
2023-12-23 10:36:32 +00:00
. map_err ( | err | map_workspace_load_error ( err , self . global_args . repository . as_deref ( ) ) )
2022-10-09 17:01:05 +00:00
}
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2022-10-02 17:09:46 +00:00
pub fn resolve_operation (
2022-10-09 17:01:05 +00:00
& self ,
ui : & mut Ui ,
2023-01-11 21:12:17 +00:00
repo_loader : & RepoLoader ,
2023-12-30 13:20:25 +00:00
) -> Result < Operation , CommandError > {
2023-01-11 21:12:17 +00:00
if self . global_args . at_operation = = " @ " {
op_heads_store ::resolve_op_heads (
repo_loader . op_heads_store ( ) . as_ref ( ) ,
repo_loader . op_store ( ) ,
| op_heads | {
writeln! (
2023-10-10 11:07:06 +00:00
ui . stderr ( ) ,
2023-01-11 21:12:17 +00:00
" Concurrent modification detected, resolving automatically. " ,
) ? ;
2023-07-25 14:40:12 +00:00
let base_repo = repo_loader . load_at ( & op_heads [ 0 ] ) ? ;
2023-01-11 21:12:17 +00:00
// TODO: It may be helpful to print each operation we're merging here
2023-12-12 05:42:05 +00:00
let mut tx =
start_repo_transaction ( & base_repo , & self . settings , & self . string_args ) ;
2023-01-11 21:12:17 +00:00
for other_op_head in op_heads . into_iter ( ) . skip ( 1 ) {
2023-07-25 14:40:12 +00:00
tx . merge_operation ( other_op_head ) ? ;
2023-01-11 21:12:17 +00:00
let num_rebased = tx . mut_repo ( ) . rebase_descendants ( & self . settings ) ? ;
if num_rebased > 0 {
writeln! (
2023-10-10 11:07:06 +00:00
ui . stderr ( ) ,
2023-01-11 21:12:17 +00:00
" Rebased {num_rebased} descendant commits onto commits rewritten \
by other operation "
) ? ;
}
2022-09-22 04:44:46 +00:00
}
2023-12-12 05:42:05 +00:00
Ok ( tx
. write ( " resolve concurrent operations " )
. leave_unpublished ( )
. operation ( )
. clone ( ) )
2023-01-11 21:12:17 +00:00
} ,
)
} else {
2023-12-31 01:54:22 +00:00
let operation =
op_walk ::resolve_op_for_load ( repo_loader , & self . global_args . at_operation ) ? ;
2023-12-30 13:56:50 +00:00
Ok ( operation )
2023-01-11 21:12:17 +00:00
}
2022-09-22 04:44:46 +00:00
}
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2022-09-22 04:44:46 +00:00
pub fn for_loaded_repo (
& self ,
2022-11-25 10:27:13 +00:00
ui : & mut Ui ,
2022-09-22 04:44:46 +00:00
workspace : Workspace ,
repo : Arc < ReadonlyRepo > ,
) -> Result < WorkspaceCommandHelper , CommandError > {
2023-05-23 03:15:58 +00:00
WorkspaceCommandHelper ::new ( ui , self , workspace , repo )
2022-09-22 04:44:46 +00:00
}
}
2023-05-06 23:44:43 +00:00
/// A ReadonlyRepo along with user-config-dependent derived data. The derived
/// data is lazily loaded.
struct ReadonlyUserRepo {
repo : Arc < ReadonlyRepo > ,
2023-05-12 05:09:48 +00:00
id_prefix_context : OnceCell < IdPrefixContext > ,
2023-05-06 23:44:43 +00:00
}
impl ReadonlyUserRepo {
fn new ( repo : Arc < ReadonlyRepo > ) -> Self {
2023-05-04 00:54:08 +00:00
Self {
repo ,
id_prefix_context : OnceCell ::new ( ) ,
}
2023-05-06 23:44:43 +00:00
}
2023-05-12 13:05:32 +00:00
pub fn git_backend ( & self ) -> Option < & GitBackend > {
self . repo . store ( ) . backend_impl ( ) . downcast_ref ( )
}
2023-05-06 23:44:43 +00:00
}
2022-09-22 04:44:46 +00:00
// Provides utilities for writing a command that works on a workspace (like most
// commands do).
pub struct WorkspaceCommandHelper {
cwd : PathBuf ,
string_args : Vec < String > ,
global_args : GlobalArgs ,
settings : UserSettings ,
workspace : Workspace ,
2023-05-06 23:44:43 +00:00
user_repo : ReadonlyUserRepo ,
2022-11-25 10:27:13 +00:00
revset_aliases_map : RevsetAliasesMap ,
2023-02-12 08:53:09 +00:00
template_aliases_map : TemplateAliasesMap ,
2022-09-22 04:44:46 +00:00
may_update_working_copy : bool ,
working_copy_shared_with_git : bool ,
}
impl WorkspaceCommandHelper {
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2022-10-08 05:24:50 +00:00
pub fn new (
2022-11-25 10:27:13 +00:00
ui : & mut Ui ,
2023-05-23 03:15:58 +00:00
command : & CommandHelper ,
2022-09-22 04:44:46 +00:00
workspace : Workspace ,
repo : Arc < ReadonlyRepo > ,
) -> Result < Self , CommandError > {
2023-05-23 03:45:11 +00:00
let revset_aliases_map = load_revset_aliases ( ui , & command . layered_configs ) ? ;
2024-01-11 03:31:54 +00:00
let template_aliases_map = command . load_template_aliases ( ui ) ? ;
2023-02-14 05:01:37 +00:00
// Parse commit_summary template early to report error before starting mutable
// operation.
// TODO: Parsed template can be cached if it doesn't capture repo
2023-05-12 05:09:48 +00:00
let id_prefix_context = IdPrefixContext ::default ( ) ;
2023-02-14 05:01:37 +00:00
parse_commit_summary_template (
2023-03-21 06:02:29 +00:00
repo . as_ref ( ) ,
2023-02-14 05:01:37 +00:00
workspace . workspace_id ( ) ,
2023-05-04 00:54:08 +00:00
& id_prefix_context ,
2023-02-14 05:01:37 +00:00
& template_aliases_map ,
2023-05-23 03:15:58 +00:00
& command . settings ,
2023-02-14 05:01:37 +00:00
) ? ;
2023-05-23 03:15:58 +00:00
let loaded_at_head = command . global_args . at_operation = = " @ " ;
let may_update_working_copy = loaded_at_head & & ! command . global_args . ignore_working_copy ;
2023-08-10 00:11:17 +00:00
let working_copy_shared_with_git = is_colocated_git_workspace ( & workspace , & repo ) ;
2023-09-30 20:16:14 +00:00
let helper = Self {
2023-05-23 03:15:58 +00:00
cwd : command . cwd . clone ( ) ,
string_args : command . string_args . clone ( ) ,
global_args : command . global_args . clone ( ) ,
settings : command . settings . clone ( ) ,
2022-09-22 04:44:46 +00:00
workspace ,
2023-05-06 23:44:43 +00:00
user_repo : ReadonlyUserRepo ::new ( repo ) ,
2023-01-04 09:20:11 +00:00
revset_aliases_map ,
2023-02-12 08:53:09 +00:00
template_aliases_map ,
2022-09-22 04:44:46 +00:00
may_update_working_copy ,
working_copy_shared_with_git ,
2023-09-30 20:16:14 +00:00
} ;
// Parse short-prefixes revset early to report error before starting mutable
// operation.
helper . id_prefix_context ( ) ? ;
Ok ( helper )
2022-10-08 05:24:50 +00:00
}
2023-05-12 13:05:32 +00:00
pub fn git_backend ( & self ) -> Option < & GitBackend > {
self . user_repo . git_backend ( )
}
2022-10-02 17:09:46 +00:00
pub fn check_working_copy_writable ( & self ) -> Result < ( ) , CommandError > {
2022-09-22 04:44:46 +00:00
if self . may_update_working_copy {
Ok ( ( ) )
} else {
2023-02-02 23:11:18 +00:00
let hint = if self . global_args . ignore_working_copy {
" Don't use --ignore-working-copy. "
2022-11-12 23:28:32 +00:00
} else {
" Don't use --at-op. "
} ;
Err ( user_error_with_hint (
" This command must be able to update the working copy. " ,
hint ,
2022-09-22 04:44:46 +00:00
) )
}
}
2022-10-08 05:56:26 +00:00
/// Snapshot the working copy if allowed, and import Git refs if the working
/// copy is collocated with Git.
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2024-01-11 10:57:13 +00:00
pub fn maybe_snapshot ( & mut self , ui : & mut Ui ) -> Result < ( ) , CommandError > {
2022-10-08 05:56:26 +00:00
if self . may_update_working_copy {
if self . working_copy_shared_with_git {
2024-01-25 10:09:52 +00:00
self . import_git_head ( ui ) ? ;
2022-10-08 05:56:26 +00:00
}
2024-01-25 10:41:42 +00:00
// Because the Git refs (except HEAD) aren't imported yet, the ref
// pointing to the new working-copy commit might not be exported.
// In that situation, the ref would be conflicted anyway, so export
// failure is okay.
2023-02-02 23:28:49 +00:00
self . snapshot_working_copy ( ui ) ? ;
2024-01-25 10:41:42 +00:00
// import_git_refs() can rebase the working-copy commit.
if self . working_copy_shared_with_git {
self . import_git_refs ( ui ) ? ;
}
2022-10-08 05:56:26 +00:00
}
Ok ( ( ) )
}
2024-01-25 10:09:52 +00:00
/// Imports new HEAD from the colocated Git repo.
///
/// If the Git HEAD has changed, this function abandons our old checkout and
/// checks out the new Git HEAD. The working-copy state will be reset to
/// point to the new Git HEAD. The working-copy contents won't be updated.
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2024-01-25 10:09:52 +00:00
fn import_git_head ( & mut self , ui : & mut Ui ) -> Result < ( ) , CommandError > {
assert! ( self . may_update_working_copy ) ;
2023-12-12 05:42:05 +00:00
let mut tx = self . start_transaction ( ) ;
2024-01-25 02:05:45 +00:00
git ::import_head ( tx . mut_repo ( ) ) ? ;
2023-10-01 08:30:35 +00:00
if ! tx . mut_repo ( ) . has_changes ( ) {
return Ok ( ( ) ) ;
}
2024-01-26 08:13:34 +00:00
// TODO: There are various ways to get duplicated working-copy
// commits. Some of them could be mitigated by checking the working-copy
// operation id after acquiring the lock, but that isn't enough.
//
// - moved HEAD was observed by multiple jj processes, and new working-copy
// commits are created concurrently.
// - new HEAD was exported by jj, but the operation isn't committed yet.
// - new HEAD was exported by jj, but the new working-copy commit isn't checked
// out yet.
2023-09-30 05:04:44 +00:00
let mut tx = tx . into_inner ( ) ;
2023-10-01 08:30:35 +00:00
let old_git_head = self . repo ( ) . view ( ) . git_head ( ) . clone ( ) ;
let new_git_head = tx . mut_repo ( ) . view ( ) . git_head ( ) . clone ( ) ;
2024-01-25 10:09:52 +00:00
if let Some ( new_git_head_id ) = new_git_head . as_normal ( ) {
let workspace_id = self . workspace_id ( ) . to_owned ( ) ;
if let Some ( old_wc_commit_id ) = self . repo ( ) . view ( ) . get_wc_commit_id ( & workspace_id ) {
2023-10-01 08:30:35 +00:00
tx . mut_repo ( )
2024-01-25 10:09:52 +00:00
. record_abandoned_commit ( old_wc_commit_id . clone ( ) ) ;
2023-10-01 08:30:35 +00:00
}
2024-01-25 10:09:52 +00:00
let new_git_head_commit = tx . mut_repo ( ) . store ( ) . get_commit ( new_git_head_id ) ? ;
tx . mut_repo ( )
. check_out ( workspace_id , & self . settings , & new_git_head_commit ) ? ;
let mut locked_ws = self . workspace . start_working_copy_mutation ( ) ? ;
// The working copy was presumably updated by the git command that updated
// HEAD, so we just need to reset our working copy
// state to it without updating working copy files.
2024-01-23 18:13:37 +00:00
locked_ws . locked_wc ( ) . reset ( & new_git_head_commit ) ? ;
2024-01-25 10:09:52 +00:00
tx . mut_repo ( ) . rebase_descendants ( & self . settings ) ? ;
self . user_repo = ReadonlyUserRepo ::new ( tx . commit ( " import git head " ) ) ;
locked_ws . finish ( self . user_repo . repo . op_id ( ) . clone ( ) ) ? ;
if old_git_head . is_present ( ) {
writeln! (
ui . stderr ( ) ,
" Reset the working copy parent to the new Git HEAD. "
) ? ;
} else {
// Don't print verbose message on initial checkout.
2022-09-22 04:44:46 +00:00
}
2024-01-25 10:09:52 +00:00
} else {
// Unlikely, but the HEAD ref got deleted by git?
self . finish_transaction ( ui , tx , " import git head " ) ? ;
}
Ok ( ( ) )
}
/// Imports branches and tags from the underlying Git repo, abandons old
/// branches.
///
/// If the working-copy branch is rebased, and if update is allowed, the new
/// working-copy commit will be checked out.
///
2024-02-05 02:49:20 +00:00
/// This function does not import the Git HEAD, but the HEAD may be reset to
/// the working copy parent if the repository is colocated.
2024-01-25 10:09:52 +00:00
#[ instrument(skip_all) ]
2024-02-05 02:49:20 +00:00
fn import_git_refs ( & mut self , ui : & mut Ui ) -> Result < ( ) , CommandError > {
2024-01-25 10:09:52 +00:00
let git_settings = self . settings . git_settings ( ) ;
let mut tx = self . start_transaction ( ) ;
// Automated import shouldn't fail because of reserved remote name.
let stats = git ::import_some_refs ( tx . mut_repo ( ) , & git_settings , | ref_name | {
! git ::is_reserved_git_remote_ref ( ref_name )
} ) ? ;
if ! tx . mut_repo ( ) . has_changes ( ) {
return Ok ( ( ) ) ;
}
2024-02-13 22:17:05 +00:00
print_git_import_stats ( ui , tx . repo ( ) , & stats , false ) ? ;
2024-01-25 10:09:52 +00:00
let mut tx = tx . into_inner ( ) ;
// Rebase here to show slightly different status message.
let num_rebased = tx . mut_repo ( ) . rebase_descendants ( & self . settings ) ? ;
if num_rebased > 0 {
writeln! (
ui . stderr ( ) ,
" Rebased {num_rebased} descendant commits off of commits rewritten from git "
) ? ;
2022-09-22 04:44:46 +00:00
}
2024-01-25 10:09:52 +00:00
self . finish_transaction ( ui , tx , " import git refs " ) ? ;
2023-10-10 11:07:06 +00:00
writeln! (
ui . stderr ( ) ,
" Done importing changes from the underlying Git repo. "
) ? ;
2022-09-22 04:44:46 +00:00
Ok ( ( ) )
}
pub fn repo ( & self ) -> & Arc < ReadonlyRepo > {
2023-05-06 23:44:43 +00:00
& self . user_repo . repo
2022-09-22 04:44:46 +00:00
}
2023-10-14 05:46:28 +00:00
pub fn working_copy ( & self ) -> & dyn WorkingCopy {
2022-09-22 04:44:46 +00:00
self . workspace . working_copy ( )
}
2023-08-08 19:03:23 +00:00
pub fn unchecked_start_working_copy_mutation (
2022-09-22 04:44:46 +00:00
& mut self ,
2023-10-15 18:42:25 +00:00
) -> Result < ( LockedWorkspace , Commit ) , CommandError > {
2022-09-22 04:44:46 +00:00
self . check_working_copy_writable ( ) ? ;
2023-02-22 10:02:52 +00:00
let wc_commit = if let Some ( wc_commit_id ) = self . get_wc_commit_id ( ) {
2023-05-06 23:44:43 +00:00
self . repo ( ) . store ( ) . get_commit ( wc_commit_id ) ?
2022-09-22 04:44:46 +00:00
} else {
2022-11-12 22:38:43 +00:00
return Err ( user_error ( " Nothing checked out in this workspace " ) ) ;
2022-09-22 04:44:46 +00:00
} ;
2023-10-15 18:42:25 +00:00
let locked_ws = self . workspace . start_working_copy_mutation ( ) ? ;
2022-10-02 17:09:46 +00:00
2023-10-15 18:42:25 +00:00
Ok ( ( locked_ws , wc_commit ) )
2022-10-02 17:09:46 +00:00
}
pub fn start_working_copy_mutation (
& mut self ,
2023-10-15 18:42:25 +00:00
) -> Result < ( LockedWorkspace , Commit ) , CommandError > {
let ( mut locked_ws , wc_commit ) = self . unchecked_start_working_copy_mutation ( ) ? ;
if wc_commit . tree_id ( ) ! = locked_ws . locked_wc ( ) . old_tree_id ( ) {
2022-11-12 22:38:43 +00:00
return Err ( user_error ( " Concurrent working copy operation. Try again. " ) ) ;
2022-09-22 04:44:46 +00:00
}
2023-10-15 18:42:25 +00:00
Ok ( ( locked_ws , wc_commit ) )
2022-09-22 04:44:46 +00:00
}
pub fn workspace_root ( & self ) -> & PathBuf {
self . workspace . workspace_root ( )
}
2023-01-24 03:55:15 +00:00
pub fn workspace_id ( & self ) -> & WorkspaceId {
self . workspace . workspace_id ( )
2022-09-22 04:44:46 +00:00
}
2023-02-22 10:02:52 +00:00
pub fn get_wc_commit_id ( & self ) -> Option < & CommitId > {
2023-05-06 23:44:43 +00:00
self . repo ( ) . view ( ) . get_wc_commit_id ( self . workspace_id ( ) )
2023-02-22 10:02:52 +00:00
}
2022-09-22 04:44:46 +00:00
pub fn working_copy_shared_with_git ( & self ) -> bool {
self . working_copy_shared_with_git
}
pub fn format_file_path ( & self , file : & RepoPath ) -> String {
2022-10-21 04:08:23 +00:00
file_util ::relative_path ( & self . cwd , & file . to_fs_path ( self . workspace_root ( ) ) )
2022-09-22 04:44:46 +00:00
. to_str ( )
. unwrap ( )
. to_owned ( )
}
2022-10-21 04:44:37 +00:00
/// Parses a path relative to cwd into a RepoPath, which is relative to the
/// workspace root.
2023-11-26 07:12:36 +00:00
pub fn parse_file_path ( & self , input : & str ) -> Result < RepoPathBuf , FsPathParseError > {
RepoPathBuf ::parse_fs_path ( & self . cwd , self . workspace_root ( ) , input )
2022-10-21 04:44:37 +00:00
}
2022-10-21 05:32:39 +00:00
pub fn matcher_from_values ( & self , values : & [ String ] ) -> Result < Box < dyn Matcher > , CommandError > {
2022-10-21 05:46:27 +00:00
if values . is_empty ( ) {
2022-10-21 05:32:39 +00:00
Ok ( Box ::new ( EverythingMatcher ) )
} else {
2022-10-21 05:46:27 +00:00
// TODO: Add support for globs and other formats
2022-12-16 03:51:25 +00:00
let paths : Vec < _ > = values
2022-10-21 05:46:27 +00:00
. iter ( )
. map ( | v | self . parse_file_path ( v ) )
2022-12-16 03:51:25 +00:00
. try_collect ( ) ? ;
2023-11-26 08:42:12 +00:00
Ok ( Box ::new ( PrefixMatcher ::new ( paths ) ) )
2022-10-21 05:32:39 +00:00
}
}
2023-07-25 18:31:05 +00:00
#[ instrument(skip_all) ]
2024-02-16 17:54:09 +00:00
pub fn base_ignores ( & self ) -> Result < Arc < GitIgnoreFile > , GitIgnoreError > {
2023-10-31 00:50:10 +00:00
fn get_excludes_file_path ( config : & gix ::config ::File ) -> Option < PathBuf > {
// TODO: maybe use path_by_key() and interpolate(), which can process non-utf-8
// path on Unix.
if let Some ( value ) = config . string_by_key ( " core.excludesFile " ) {
2024-01-18 01:57:43 +00:00
str ::from_utf8 ( & value )
. ok ( )
. map ( crate ::git_util ::expand_git_path )
2023-10-31 00:50:10 +00:00
} else {
xdg_config_home ( ) . ok ( ) . map ( | x | x . join ( " git " ) . join ( " ignore " ) )
}
}
2022-12-22 03:58:06 +00:00
fn xdg_config_home ( ) -> Result < PathBuf , VarError > {
if let Ok ( x ) = std ::env ::var ( " XDG_CONFIG_HOME " ) {
if ! x . is_empty ( ) {
return Ok ( PathBuf ::from ( x ) ) ;
}
}
std ::env ::var ( " HOME " ) . map ( | x | Path ::new ( & x ) . join ( " .config " ) )
}
2022-09-22 04:44:46 +00:00
let mut git_ignores = GitIgnoreFile ::empty ( ) ;
2023-05-12 13:05:32 +00:00
if let Some ( git_backend ) = self . git_backend ( ) {
2023-10-31 00:50:10 +00:00
let git_repo = git_backend . git_repo ( ) ;
if let Some ( excludes_file_path ) = get_excludes_file_path ( & git_repo . config_snapshot ( ) ) {
2024-02-16 17:54:09 +00:00
git_ignores = git_ignores . chain_with_file ( " " , excludes_file_path ) ? ;
2023-10-31 00:50:10 +00:00
}
2023-10-03 09:05:43 +00:00
git_ignores = git_ignores
2024-02-16 17:54:09 +00:00
. chain_with_file ( " " , git_backend . git_repo_path ( ) . join ( " info " ) . join ( " exclude " ) ) ? ;
2023-10-31 00:50:10 +00:00
} else if let Ok ( git_config ) = gix ::config ::File ::from_globals ( ) {
if let Some ( excludes_file_path ) = get_excludes_file_path ( & git_config ) {
2024-02-16 17:54:09 +00:00
git_ignores = git_ignores . chain_with_file ( " " , excludes_file_path ) ? ;
2023-10-31 00:50:10 +00:00
}
2022-09-22 04:44:46 +00:00
}
2024-02-16 17:54:09 +00:00
Ok ( git_ignores )
2022-09-22 04:44:46 +00:00
}
2023-12-30 13:56:50 +00:00
pub fn resolve_single_op ( & self , op_str : & str ) -> Result < Operation , OpsetEvaluationError > {
2023-12-31 01:54:22 +00:00
op_walk ::resolve_op_with_repo ( self . repo ( ) , op_str )
2022-09-22 04:44:46 +00:00
}
2023-07-25 16:07:03 +00:00
/// Resolve a revset to a single revision. Return an error if the revset is
/// empty or has multiple revisions.
2024-02-13 06:44:35 +00:00
pub fn resolve_single_rev ( & self , revision_str : & str ) -> Result < Commit , CommandError > {
let revset_expression = self . parse_revset ( revision_str ) ? ;
2023-09-09 22:47:27 +00:00
let revset = self . evaluate_revset ( revset_expression . clone ( ) ) ? ;
2023-05-06 23:44:43 +00:00
let mut iter = revset . iter ( ) . commits ( self . repo ( ) . store ( ) ) . fuse ( ) ;
2022-12-15 11:28:02 +00:00
match ( iter . next ( ) , iter . next ( ) ) {
( Some ( commit ) , None ) = > Ok ( commit ? ) ,
( None , _ ) = > Err ( user_error ( format! (
2023-02-04 06:29:44 +00:00
r # "Revset "{revision_str}" didn't resolve to any revisions"#
2022-09-22 04:44:46 +00:00
) ) ) ,
2022-12-15 11:37:14 +00:00
( Some ( commit0 ) , Some ( commit1 ) ) = > {
let mut iter = [ commit0 , commit1 ] . into_iter ( ) . chain ( iter ) ;
2022-12-16 03:51:25 +00:00
let commits : Vec < _ > = iter . by_ref ( ) . take ( 5 ) . try_collect ( ) ? ;
2022-12-15 11:37:14 +00:00
let elided = iter . next ( ) . is_some ( ) ;
2023-09-22 00:24:01 +00:00
let commits_summary = commits
. iter ( )
. map ( | c | self . format_commit_summary ( c ) )
. join ( " \n " )
+ elided . then_some ( " \n ... " ) . unwrap_or_default ( ) ;
2023-09-17 12:41:33 +00:00
let hint = if commits [ 0 ] . change_id ( ) = = commits [ 1 ] . change_id ( ) {
// Separate hint if there's commits with same change id
format! (
r #" The revset " { revision_str } " resolved to these revisions:
{ commits_summary }
Some of these commits have the same change id . Abandon one of them with ` jj abandon - r < REVISION > ` . " #,
)
} else if let RevsetExpression ::CommitRef ( RevsetCommitRef ::Symbol ( branch_name ) ) =
revset_expression . as_ref ( )
2023-09-09 22:47:27 +00:00
{
// Separate hint if there's a conflicted branch
format! (
r #" Branch {branch_name} resolved to multiple revisions because it's conflicted.
It resolved to these revisions :
{ commits_summary }
Set which revision the branch points to with ` jj branch set { branch_name } - r < REVISION > ` . " #,
)
} else {
format! (
r #" The revset " { revision_str } " resolved to these revisions:
2023-09-22 00:24:01 +00:00
{ commits_summary } " #,
2023-09-09 22:47:27 +00:00
)
} ;
2022-12-15 11:37:14 +00:00
Err ( user_error_with_hint (
2023-02-04 06:29:44 +00:00
format! ( r # "Revset "{revision_str}" resolved to more than one revision"# ) ,
2022-12-15 11:37:14 +00:00
hint ,
) )
}
2022-09-22 04:44:46 +00:00
}
}
2023-07-25 16:07:03 +00:00
/// Resolve a revset any number of revisions (including 0).
2024-02-13 06:44:35 +00:00
pub fn resolve_revset ( & self , revision_str : & str ) -> Result < Vec < Commit > , CommandError > {
let revset_expression = self . parse_revset ( revision_str ) ? ;
2023-03-16 20:36:25 +00:00
let revset = self . evaluate_revset ( revset_expression ) ? ;
2023-05-06 23:44:43 +00:00
Ok ( revset . iter ( ) . commits ( self . repo ( ) . store ( ) ) . try_collect ( ) ? )
2022-09-22 04:44:46 +00:00
}
2023-07-25 16:07:03 +00:00
/// Resolve a revset any number of revisions (including 0), but require the
/// user to indicate if they allow multiple revisions by prefixing the
/// expression with `all:`.
pub fn resolve_revset_default_single (
& self ,
revision_str : & str ,
) -> Result < Vec < Commit > , CommandError > {
// TODO: Let pest parse the prefix too once we've dropped support for `:`
if let Some ( revision_str ) = revision_str . strip_prefix ( " all: " ) {
2024-02-13 06:44:35 +00:00
self . resolve_revset ( revision_str )
2023-07-25 16:07:03 +00:00
} else {
2024-02-13 06:44:35 +00:00
self . resolve_single_rev ( revision_str )
2023-07-25 16:07:03 +00:00
. map_err ( | err | match err {
2024-01-31 11:45:03 +00:00
CommandError ::UserError { err , hint } = > CommandError ::UserError {
err ,
hint : Some ( format! (
2023-07-25 16:07:03 +00:00
" {old_hint}Prefix the expression with 'all' to allow any number of \
revisions ( i . e . ' all :{ } ' ) . " ,
revision_str ,
old_hint = hint . map ( | hint | format! ( " {hint} \n " ) ) . unwrap_or_default ( )
2024-01-31 11:45:03 +00:00
) ) ,
} ,
2023-07-25 16:07:03 +00:00
err = > err ,
} )
. map ( | commit | vec! [ commit ] )
}
}
2022-11-01 07:14:21 +00:00
pub fn parse_revset (
& self ,
revision_str : & str ,
) -> Result < Rc < RevsetExpression > , RevsetParseError > {
2023-08-19 02:26:38 +00:00
let expression = revset ::parse ( revision_str , & self . revset_parse_context ( ) ) ? ;
2022-11-01 07:14:21 +00:00
Ok ( revset ::optimize ( expression ) )
}
2022-10-23 03:55:09 +00:00
pub fn evaluate_revset < ' repo > (
& ' repo self ,
2023-03-16 20:36:25 +00:00
revset_expression : Rc < RevsetExpression > ,
2024-01-08 02:28:23 +00:00
) -> Result < Box < dyn Revset + ' repo > , CommandError > {
2023-09-30 20:16:14 +00:00
let symbol_resolver = self . revset_symbol_resolver ( ) ? ;
let revset_expression =
revset_expression . resolve_user_expression ( self . repo ( ) . as_ref ( ) , & symbol_resolver ) ? ;
2023-05-06 23:44:43 +00:00
Ok ( revset_expression . evaluate ( self . repo ( ) . as_ref ( ) ) ? )
2022-11-01 07:14:21 +00:00
}
2023-08-19 02:26:38 +00:00
pub ( crate ) fn revset_parse_context ( & self ) -> RevsetParseContext {
let workspace_context = RevsetWorkspaceContext {
2022-10-23 04:14:00 +00:00
cwd : & self . cwd ,
2023-01-24 03:55:15 +00:00
workspace_id : self . workspace_id ( ) ,
2022-10-23 04:14:00 +00:00
workspace_root : self . workspace . workspace_root ( ) ,
2023-08-19 02:26:38 +00:00
} ;
RevsetParseContext {
aliases_map : & self . revset_aliases_map ,
user_email : self . settings . user_email ( ) ,
workspace : Some ( workspace_context ) ,
2022-11-01 07:14:21 +00:00
}
2022-10-23 03:55:09 +00:00
}
2023-09-30 20:16:14 +00:00
pub ( crate ) fn revset_symbol_resolver ( & self ) -> Result < DefaultSymbolResolver < '_ > , CommandError > {
let id_prefix_context = self . id_prefix_context ( ) ? ;
2023-05-12 05:09:48 +00:00
let commit_id_resolver : revset ::PrefixResolver < CommitId > =
Box ::new ( | repo , prefix | id_prefix_context . resolve_commit_prefix ( repo , prefix ) ) ;
let change_id_resolver : revset ::PrefixResolver < Vec < CommitId > > =
Box ::new ( | repo , prefix | id_prefix_context . resolve_change_prefix ( repo , prefix ) ) ;
2023-09-30 20:16:14 +00:00
let symbol_resolver = DefaultSymbolResolver ::new ( self . repo ( ) . as_ref ( ) )
2023-05-05 23:53:27 +00:00
. with_commit_id_resolver ( commit_id_resolver )
2023-09-30 20:16:14 +00:00
. with_change_id_resolver ( change_id_resolver ) ;
Ok ( symbol_resolver )
2023-05-05 21:01:25 +00:00
}
2023-09-30 20:16:14 +00:00
pub fn id_prefix_context ( & self ) -> Result < & IdPrefixContext , CommandError > {
self . user_repo . id_prefix_context . get_or_try_init ( | | {
2023-05-12 05:09:48 +00:00
let mut context : IdPrefixContext = IdPrefixContext ::default ( ) ;
2023-05-06 00:12:08 +00:00
let revset_string : String = self
. settings
. config ( )
. get_string ( " revsets.short-prefixes " )
. unwrap_or_else ( | _ | self . settings . default_revset ( ) ) ;
if ! revset_string . is_empty ( ) {
2024-02-13 06:44:35 +00:00
let disambiguation_revset = self . parse_revset ( & revset_string ) . map_err ( | err | {
CommandError ::ConfigError ( format! ( " Invalid `revsets.short-prefixes`: {err} " ) )
} ) ? ;
2023-04-09 23:18:32 +00:00
context = context . disambiguate_within ( disambiguation_revset ) ;
2023-05-06 00:12:08 +00:00
}
2023-09-30 20:16:14 +00:00
Ok ( context )
2023-05-04 00:54:08 +00:00
} )
}
2023-02-19 08:05:50 +00:00
pub fn template_aliases_map ( & self ) -> & TemplateAliasesMap {
& self . template_aliases_map
}
2023-02-12 09:06:48 +00:00
pub fn parse_commit_template (
& self ,
template_text : & str ,
2023-09-30 20:16:14 +00:00
) -> Result < Box < dyn Template < Commit > + '_ > , CommandError > {
let id_prefix_context = self . id_prefix_context ( ) ? ;
let template = commit_templater ::parse (
2023-05-06 23:44:43 +00:00
self . repo ( ) . as_ref ( ) ,
2023-02-12 09:06:48 +00:00
self . workspace_id ( ) ,
2023-09-30 20:16:14 +00:00
id_prefix_context ,
2023-02-12 09:06:48 +00:00
template_text ,
2023-02-12 08:53:09 +00:00
& self . template_aliases_map ,
2023-09-30 20:16:14 +00:00
) ? ;
Ok ( template )
2023-02-12 09:06:48 +00:00
}
2023-01-14 09:33:18 +00:00
/// Returns one-line summary of the given `commit`.
pub fn format_commit_summary ( & self , commit : & Commit ) -> String {
let mut output = Vec ::new ( ) ;
self . write_commit_summary ( & mut PlainTextFormatter ::new ( & mut output ) , commit )
. expect ( " write() to PlainTextFormatter should never fail " ) ;
String ::from_utf8 ( output ) . expect ( " template output should be utf-8 bytes " )
}
2023-01-15 08:02:37 +00:00
/// Writes one-line summary of the given `commit`.
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2023-01-15 08:02:37 +00:00
pub fn write_commit_summary (
& self ,
formatter : & mut dyn Formatter ,
commit : & Commit ,
) -> std ::io ::Result < ( ) > {
2023-09-30 20:16:14 +00:00
let id_prefix_context = self
. id_prefix_context ( )
. expect ( " parse error should be confined by WorkspaceCommandHelper::new() " ) ;
2023-02-12 09:13:09 +00:00
let template = parse_commit_summary_template (
2023-05-06 23:44:43 +00:00
self . repo ( ) . as_ref ( ) ,
2023-01-24 03:55:15 +00:00
self . workspace_id ( ) ,
2023-09-30 20:16:14 +00:00
id_prefix_context ,
2023-02-12 08:53:09 +00:00
& self . template_aliases_map ,
2023-01-15 08:02:37 +00:00
& self . settings ,
2023-02-14 05:01:37 +00:00
)
. expect ( " parse error should be confined by WorkspaceCommandHelper::new() " ) ;
2023-09-30 20:16:14 +00:00
template . format ( commit , formatter ) ? ;
Ok ( ( ) )
2023-01-15 08:02:37 +00:00
}
2023-09-02 02:16:38 +00:00
pub fn check_rewritable < ' a > (
& self ,
commits : impl IntoIterator < Item = & ' a Commit > ,
) -> Result < ( ) , CommandError > {
let to_rewrite_revset = RevsetExpression ::commits (
commits
. into_iter ( )
. map ( | commit | commit . id ( ) . clone ( ) )
. collect ( ) ,
) ;
cli: make set of immutable commits configurable
This adds a new `revset-aliases.immutable_heads()s` config for
defining the set of immutable commits. The set is defined as the
configured revset, as well as its ancestors, and the root commit
commit (even if the configured set is empty).
This patch also adds enforcement of the config where we already had
checks preventing rewrite of the root commit. The working-copy commit
is implicitly assumed to be writable in most cases. Specifically, we
won't prevent amending the working copy even if the user includes it
in the config but we do prevent `jj edit @` in that case. That seems
good enough to me. Maybe we should emit a warning when the working
copy is in the set of immutable commits.
Maybe we should add support for something more like [Mercurial's
phases](https://wiki.mercurial-scm.org/Phases), which is propagated on
push and pull. There's already some affordance for that in the view
object's `public_heads` field. However, this is simpler, especially
since we can't propagate the phase to Git remotes, and seems like a
good start. Also, it lets you say that commits authored by other users
are immutable, for example.
For now, the functionality is in the CLI library. I'm not sure if we
want to move it into the library crate. I'm leaning towards letting
library users do whatever they want without being restricted by
immutable commits. I do think we should move the functionality into a
future `ui-lib` or `ui-util` crate. That crate would have most of the
functionality in the current `cli_util` module (but in a
non-CLI-specific form).
2023-09-02 02:12:01 +00:00
let ( params , immutable_heads_str ) = self
. revset_aliases_map
. get_function ( " immutable_heads " )
. unwrap ( ) ;
if ! params . is_empty ( ) {
return Err ( user_error (
r # "The `revset-aliases.immutable_heads()` function must be declared without arguments."# ,
) ) ;
}
2024-02-13 06:44:35 +00:00
let immutable_heads_revset = self . parse_revset ( immutable_heads_str ) ? ;
cli: make set of immutable commits configurable
This adds a new `revset-aliases.immutable_heads()s` config for
defining the set of immutable commits. The set is defined as the
configured revset, as well as its ancestors, and the root commit
commit (even if the configured set is empty).
This patch also adds enforcement of the config where we already had
checks preventing rewrite of the root commit. The working-copy commit
is implicitly assumed to be writable in most cases. Specifically, we
won't prevent amending the working copy even if the user includes it
in the config but we do prevent `jj edit @` in that case. That seems
good enough to me. Maybe we should emit a warning when the working
copy is in the set of immutable commits.
Maybe we should add support for something more like [Mercurial's
phases](https://wiki.mercurial-scm.org/Phases), which is propagated on
push and pull. There's already some affordance for that in the view
object's `public_heads` field. However, this is simpler, especially
since we can't propagate the phase to Git remotes, and seems like a
good start. Also, it lets you say that commits authored by other users
are immutable, for example.
For now, the functionality is in the CLI library. I'm not sure if we
want to move it into the library crate. I'm leaning towards letting
library users do whatever they want without being restricted by
immutable commits. I do think we should move the functionality into a
future `ui-lib` or `ui-util` crate. That crate would have most of the
functionality in the current `cli_util` module (but in a
non-CLI-specific form).
2023-09-02 02:12:01 +00:00
let immutable_revset = immutable_heads_revset
. ancestors ( )
. union ( & RevsetExpression ::commit (
self . repo ( ) . store ( ) . root_commit_id ( ) . clone ( ) ,
) ) ;
let revset = self . evaluate_revset ( to_rewrite_revset . intersection ( & immutable_revset ) ) ? ;
2023-09-02 02:16:38 +00:00
if let Some ( commit ) = revset . iter ( ) . commits ( self . repo ( ) . store ( ) ) . next ( ) {
let commit = commit ? ;
2023-10-29 03:36:57 +00:00
let error = if commit . id ( ) = = self . repo ( ) . store ( ) . root_commit_id ( ) {
user_error ( format! (
" The root commit {} is immutable " ,
short_commit_hash ( commit . id ( ) ) ,
) )
} else {
user_error_with_hint (
format! ( " Commit {} is immutable " , short_commit_hash ( commit . id ( ) ) , ) ,
" Configure the set of immutable commits via \
` revset - aliases . immutable_heads ( ) ` . " ,
)
} ;
return Err ( error ) ;
2022-09-22 04:44:46 +00:00
}
2023-09-02 02:16:38 +00:00
2022-09-22 04:44:46 +00:00
Ok ( ( ) )
}
pub fn check_non_empty ( & self , commits : & [ Commit ] ) -> Result < ( ) , CommandError > {
if commits . is_empty ( ) {
2022-11-12 22:38:43 +00:00
return Err ( user_error ( " Empty revision set " ) ) ;
2022-09-22 04:44:46 +00:00
}
Ok ( ( ) )
}
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2024-01-11 10:57:13 +00:00
fn snapshot_working_copy ( & mut self , ui : & mut Ui ) -> Result < ( ) , CommandError > {
2023-01-24 03:55:15 +00:00
let workspace_id = self . workspace_id ( ) . to_owned ( ) ;
2023-05-21 08:49:35 +00:00
let get_wc_commit = | repo : & ReadonlyRepo | -> Result < Option < _ > , _ > {
repo . view ( )
. get_wc_commit_id ( & workspace_id )
. map ( | id | repo . store ( ) . get_commit ( id ) )
. transpose ( )
} ;
let repo = self . repo ( ) . clone ( ) ;
2023-07-18 07:19:54 +00:00
let Some ( wc_commit ) = get_wc_commit ( & repo ) ? else {
2023-05-21 08:49:35 +00:00
// If the workspace has been deleted, it's unclear what to do, so we just skip
// committing the working copy.
return Ok ( ( ) ) ;
2022-09-22 04:44:46 +00:00
} ;
2024-02-16 17:54:09 +00:00
let base_ignores = self . base_ignores ( ) ? ;
2023-05-21 08:49:35 +00:00
// Compare working-copy tree and operation with repo's, and reload as needed.
2023-10-15 18:42:25 +00:00
let mut locked_ws = self . workspace . start_working_copy_mutation ( ) ? ;
let old_op_id = locked_ws . locked_wc ( ) . old_operation_id ( ) . clone ( ) ;
let ( repo , wc_commit ) =
workspace: recover from missing operation
If the operation corresponding to a workspace is missing for some reason
(the specific situation in the test in this commit is that an operation
was abandoned and garbage-collected from another workspace), currently,
jj fails with a 255 error code. Teach jj a way to recover from this
situation.
When jj detects such a situation, it prints a message and stops
operation, similar to when a workspace is stale. The message tells the
user what command to run.
When that command is run, jj loads the repo at the @ operation (instead
of the operation of the workspace), creates a new commit on the @
commit with an empty tree, and then proceeds as usual - in particular,
including the auto-snapshotting of the working tree, which creates
another commit that obsoletes the newly created commit.
There are several design points I considered.
1) Whether the recovery should be automatic, or (as in this commit)
manual in that the user should be prompted to run a command. The user
might prefer to recover in another way (e.g. by simply deleting the
workspace) and this situation is (hopefully) rare enough that I think
it's better to prompt the user.
2) Which command the user should be prompted to run (and thus, which
command should be taught to perform the recovery). I chose "workspace
update-stale" because the circumstances are very similar to it: it's
symptom is that the regular jj operation is blocked somewhere at the
beginning, and "workspace update-stale" already does some special work
before the blockage (this commit adds more of such special work). But it
might be better for something more explicitly named, or even a sequence
of commands (e.g. "create a new operation that becomes @ that no
workspace points to", "low-level command that makes a workspace point to
the operation @") but I can see how this can be unnecessarily confusing
for the user.
3) How we recover. I can think of several ways:
a) Always create a commit, and allow the automatic snapshotting to
create another commit that obsoletes this commit.
b) Create a commit but somehow teach the automatic snapshotting to
replace the created commit in-place (so it has no predecessor, as viewed
in "obslog").
c) Do either a) or b), with the added improvement that if there is no
diff between the newly created commit and the former @, to behave as if
no new commit was created (@ remains as the former @).
I chose a) since it was the simplest and most easily reasoned about,
which I think is the best way to go when recovering from a rare
situation.
2024-02-03 05:26:23 +00:00
match check_stale_working_copy ( locked_ws . locked_wc ( ) , & wc_commit , & repo ) {
Ok ( WorkingCopyFreshness ::Fresh ) = > ( repo , wc_commit ) ,
Ok ( WorkingCopyFreshness ::Updated ( wc_operation ) ) = > {
2023-10-15 18:42:25 +00:00
let repo = repo . reload_at ( & wc_operation ) ? ;
let wc_commit = if let Some ( wc_commit ) = get_wc_commit ( & repo ) ? {
wc_commit
} else {
return Ok ( ( ) ) ; // The workspace has been deleted (see
// above)
} ;
( repo , wc_commit )
}
workspace: recover from missing operation
If the operation corresponding to a workspace is missing for some reason
(the specific situation in the test in this commit is that an operation
was abandoned and garbage-collected from another workspace), currently,
jj fails with a 255 error code. Teach jj a way to recover from this
situation.
When jj detects such a situation, it prints a message and stops
operation, similar to when a workspace is stale. The message tells the
user what command to run.
When that command is run, jj loads the repo at the @ operation (instead
of the operation of the workspace), creates a new commit on the @
commit with an empty tree, and then proceeds as usual - in particular,
including the auto-snapshotting of the working tree, which creates
another commit that obsoletes the newly created commit.
There are several design points I considered.
1) Whether the recovery should be automatic, or (as in this commit)
manual in that the user should be prompted to run a command. The user
might prefer to recover in another way (e.g. by simply deleting the
workspace) and this situation is (hopefully) rare enough that I think
it's better to prompt the user.
2) Which command the user should be prompted to run (and thus, which
command should be taught to perform the recovery). I chose "workspace
update-stale" because the circumstances are very similar to it: it's
symptom is that the regular jj operation is blocked somewhere at the
beginning, and "workspace update-stale" already does some special work
before the blockage (this commit adds more of such special work). But it
might be better for something more explicitly named, or even a sequence
of commands (e.g. "create a new operation that becomes @ that no
workspace points to", "low-level command that makes a workspace point to
the operation @") but I can see how this can be unnecessarily confusing
for the user.
3) How we recover. I can think of several ways:
a) Always create a commit, and allow the automatic snapshotting to
create another commit that obsoletes this commit.
b) Create a commit but somehow teach the automatic snapshotting to
replace the created commit in-place (so it has no predecessor, as viewed
in "obslog").
c) Do either a) or b), with the added improvement that if there is no
diff between the newly created commit and the former @, to behave as if
no new commit was created (@ remains as the former @).
I chose a) since it was the simplest and most easily reasoned about,
which I think is the best way to go when recovering from a rare
situation.
2024-02-03 05:26:23 +00:00
Ok ( WorkingCopyFreshness ::WorkingCopyStale ) = > {
2023-10-15 18:42:25 +00:00
return Err ( user_error_with_hint (
format! (
" The working copy is stale (not updated since operation {}). " ,
short_operation_hash ( & old_op_id )
) ,
" Run `jj workspace update-stale` to update it.
2023-05-25 14:59:16 +00:00
See https ://github.com/martinvonz/jj/blob/main/docs/working-copy.md#stale-working-copy \
2023-10-15 18:42:25 +00:00
for more information . " ,
) ) ;
}
workspace: recover from missing operation
If the operation corresponding to a workspace is missing for some reason
(the specific situation in the test in this commit is that an operation
was abandoned and garbage-collected from another workspace), currently,
jj fails with a 255 error code. Teach jj a way to recover from this
situation.
When jj detects such a situation, it prints a message and stops
operation, similar to when a workspace is stale. The message tells the
user what command to run.
When that command is run, jj loads the repo at the @ operation (instead
of the operation of the workspace), creates a new commit on the @
commit with an empty tree, and then proceeds as usual - in particular,
including the auto-snapshotting of the working tree, which creates
another commit that obsoletes the newly created commit.
There are several design points I considered.
1) Whether the recovery should be automatic, or (as in this commit)
manual in that the user should be prompted to run a command. The user
might prefer to recover in another way (e.g. by simply deleting the
workspace) and this situation is (hopefully) rare enough that I think
it's better to prompt the user.
2) Which command the user should be prompted to run (and thus, which
command should be taught to perform the recovery). I chose "workspace
update-stale" because the circumstances are very similar to it: it's
symptom is that the regular jj operation is blocked somewhere at the
beginning, and "workspace update-stale" already does some special work
before the blockage (this commit adds more of such special work). But it
might be better for something more explicitly named, or even a sequence
of commands (e.g. "create a new operation that becomes @ that no
workspace points to", "low-level command that makes a workspace point to
the operation @") but I can see how this can be unnecessarily confusing
for the user.
3) How we recover. I can think of several ways:
a) Always create a commit, and allow the automatic snapshotting to
create another commit that obsoletes this commit.
b) Create a commit but somehow teach the automatic snapshotting to
replace the created commit in-place (so it has no predecessor, as viewed
in "obslog").
c) Do either a) or b), with the added improvement that if there is no
diff between the newly created commit and the former @, to behave as if
no new commit was created (@ remains as the former @).
I chose a) since it was the simplest and most easily reasoned about,
which I think is the best way to go when recovering from a rare
situation.
2024-02-03 05:26:23 +00:00
Ok ( WorkingCopyFreshness ::SiblingOperation ) = > {
2024-01-31 02:35:56 +00:00
return Err ( internal_error ( format! (
2023-10-15 18:42:25 +00:00
" The repo was loaded at operation {}, which seems to be a sibling of the \
working copy ' s operation { } " ,
short_operation_hash ( repo . op_id ( ) ) ,
short_operation_hash ( & old_op_id )
) ) ) ;
}
workspace: recover from missing operation
If the operation corresponding to a workspace is missing for some reason
(the specific situation in the test in this commit is that an operation
was abandoned and garbage-collected from another workspace), currently,
jj fails with a 255 error code. Teach jj a way to recover from this
situation.
When jj detects such a situation, it prints a message and stops
operation, similar to when a workspace is stale. The message tells the
user what command to run.
When that command is run, jj loads the repo at the @ operation (instead
of the operation of the workspace), creates a new commit on the @
commit with an empty tree, and then proceeds as usual - in particular,
including the auto-snapshotting of the working tree, which creates
another commit that obsoletes the newly created commit.
There are several design points I considered.
1) Whether the recovery should be automatic, or (as in this commit)
manual in that the user should be prompted to run a command. The user
might prefer to recover in another way (e.g. by simply deleting the
workspace) and this situation is (hopefully) rare enough that I think
it's better to prompt the user.
2) Which command the user should be prompted to run (and thus, which
command should be taught to perform the recovery). I chose "workspace
update-stale" because the circumstances are very similar to it: it's
symptom is that the regular jj operation is blocked somewhere at the
beginning, and "workspace update-stale" already does some special work
before the blockage (this commit adds more of such special work). But it
might be better for something more explicitly named, or even a sequence
of commands (e.g. "create a new operation that becomes @ that no
workspace points to", "low-level command that makes a workspace point to
the operation @") but I can see how this can be unnecessarily confusing
for the user.
3) How we recover. I can think of several ways:
a) Always create a commit, and allow the automatic snapshotting to
create another commit that obsoletes this commit.
b) Create a commit but somehow teach the automatic snapshotting to
replace the created commit in-place (so it has no predecessor, as viewed
in "obslog").
c) Do either a) or b), with the added improvement that if there is no
diff between the newly created commit and the former @, to behave as if
no new commit was created (@ remains as the former @).
I chose a) since it was the simplest and most easily reasoned about,
which I think is the best way to go when recovering from a rare
situation.
2024-02-03 05:26:23 +00:00
Err ( OpStoreError ::ObjectNotFound { .. } ) = > {
return Err ( user_error_with_hint (
" Could not read working copy's operation. " ,
" Run `jj workspace update-stale` to recover.
See https ://github.com/martinvonz/jj/blob/main/docs/working-copy.md#stale-working-copy \
for more information . " ,
) )
}
Err ( e ) = > return Err ( e . into ( ) ) ,
2023-10-15 18:42:25 +00:00
} ;
2023-05-06 23:44:43 +00:00
self . user_repo = ReadonlyUserRepo ::new ( repo ) ;
2023-05-06 00:12:48 +00:00
let progress = crate ::progress ::snapshot_progress ( ui ) ;
2023-10-15 18:42:25 +00:00
let new_tree_id = locked_ws . locked_wc ( ) . snapshot ( SnapshotOptions {
2023-06-27 23:10:35 +00:00
base_ignores ,
2023-07-08 09:23:32 +00:00
fsmonitor_kind : self . settings . fsmonitor_kind ( ) ? ,
2023-06-27 23:10:35 +00:00
progress : progress . as_ref ( ) . map ( | x | x as _ ) ,
2023-06-28 22:10:19 +00:00
max_new_file_size : self . settings . max_new_file_size ( ) ? ,
2023-06-27 23:10:35 +00:00
} ) ? ;
2023-05-06 00:12:48 +00:00
drop ( progress ) ;
2023-08-28 20:09:19 +00:00
if new_tree_id ! = * wc_commit . tree_id ( ) {
2023-12-12 05:42:05 +00:00
let mut tx =
start_repo_transaction ( & self . user_repo . repo , & self . settings , & self . string_args ) ;
2024-02-18 22:57:09 +00:00
tx . set_is_snapshot ( true ) ;
2022-09-22 04:44:46 +00:00
let mut_repo = tx . mut_repo ( ) ;
2022-12-25 20:58:08 +00:00
let commit = mut_repo
. rewrite_commit ( & self . settings , & wc_commit )
2023-08-26 00:24:56 +00:00
. set_tree_id ( new_tree_id )
2022-12-24 05:09:19 +00:00
. write ( ) ? ;
2023-01-24 06:09:49 +00:00
mut_repo . set_wc_commit ( workspace_id , commit . id ( ) . clone ( ) ) ? ;
2022-09-22 04:44:46 +00:00
// Rebase descendants
let num_rebased = mut_repo . rebase_descendants ( & self . settings ) ? ;
if num_rebased > 0 {
writeln! (
2023-10-10 11:07:06 +00:00
ui . stderr ( ) ,
2022-12-15 02:30:06 +00:00
" Rebased {num_rebased} descendant commits onto updated working copy "
2022-09-22 04:44:46 +00:00
) ? ;
}
2022-12-09 04:04:33 +00:00
if self . working_copy_shared_with_git {
2023-11-10 07:52:45 +00:00
let failed_branches = git ::export_refs ( mut_repo ) ? ;
2022-12-09 04:04:33 +00:00
print_failed_git_export ( ui , & failed_branches ) ? ;
}
2023-12-12 05:42:05 +00:00
self . user_repo = ReadonlyUserRepo ::new ( tx . commit ( " snapshot working copy " ) ) ;
2022-09-22 04:44:46 +00:00
}
2023-10-15 18:42:25 +00:00
locked_ws . finish ( self . user_repo . repo . op_id ( ) . clone ( ) ) ? ;
2022-09-22 04:44:46 +00:00
Ok ( ( ) )
}
2023-02-22 10:47:52 +00:00
fn update_working_copy (
& mut self ,
ui : & mut Ui ,
maybe_old_commit : Option < & Commit > ,
2023-10-03 10:18:37 +00:00
new_commit : & Commit ,
2023-02-22 10:47:52 +00:00
) -> Result < ( ) , CommandError > {
assert! ( self . may_update_working_copy ) ;
let stats = update_working_copy (
2023-05-06 23:44:43 +00:00
& self . user_repo . repo ,
2023-10-13 21:46:26 +00:00
& mut self . workspace ,
2023-02-22 10:47:52 +00:00
maybe_old_commit ,
2023-10-03 10:18:37 +00:00
new_commit ,
2023-02-22 10:47:52 +00:00
) ? ;
2023-10-03 10:18:37 +00:00
if Some ( new_commit ) ! = maybe_old_commit {
2023-10-10 11:07:06 +00:00
write! ( ui . stderr ( ) , " Working copy now at: " ) ? ;
ui . stderr_formatter ( ) . with_label ( " working_copy " , | fmt | {
2023-10-03 10:18:37 +00:00
self . write_commit_summary ( fmt , new_commit )
2023-09-07 04:48:04 +00:00
} ) ? ;
2023-10-10 11:07:06 +00:00
writeln! ( ui . stderr ( ) ) ? ;
2023-04-29 05:01:31 +00:00
for parent in new_commit . parents ( ) {
2023-10-10 11:07:06 +00:00
// "Working copy now at: "
write! ( ui . stderr ( ) , " Parent commit : " ) ? ;
self . write_commit_summary ( ui . stderr_formatter ( ) . as_mut ( ) , & parent ) ? ;
writeln! ( ui . stderr ( ) ) ? ;
2023-04-29 05:01:31 +00:00
}
2023-02-22 10:41:31 +00:00
}
2023-02-22 10:47:52 +00:00
if let Some ( stats ) = stats {
2023-10-07 00:23:23 +00:00
print_checkout_stats ( ui , stats , new_commit ) ? ;
2023-02-22 10:47:52 +00:00
}
Ok ( ( ) )
}
2023-12-12 05:42:05 +00:00
pub fn start_transaction ( & mut self ) -> WorkspaceCommandTransaction {
let tx = start_repo_transaction ( self . repo ( ) , & self . settings , & self . string_args ) ;
2023-01-15 08:28:16 +00:00
WorkspaceCommandTransaction { helper : self , tx }
2022-09-22 04:44:46 +00:00
}
2023-12-12 05:42:05 +00:00
fn finish_transaction (
& mut self ,
ui : & mut Ui ,
mut tx : Transaction ,
description : impl Into < String > ,
) -> Result < ( ) , CommandError > {
2023-10-03 15:07:45 +00:00
if ! tx . mut_repo ( ) . has_changes ( ) {
2023-10-10 11:07:06 +00:00
writeln! ( ui . stderr ( ) , " Nothing changed. " ) ? ;
2022-09-22 04:44:46 +00:00
return Ok ( ( ) ) ;
}
2023-10-03 15:07:45 +00:00
let num_rebased = tx . mut_repo ( ) . rebase_descendants ( & self . settings ) ? ;
2022-09-22 04:44:46 +00:00
if num_rebased > 0 {
2023-10-10 11:07:06 +00:00
writeln! ( ui . stderr ( ) , " Rebased {num_rebased} descendant commits " ) ? ;
2022-09-22 04:44:46 +00:00
}
2023-10-03 15:07:45 +00:00
2023-11-20 02:10:39 +00:00
let old_repo = tx . base_repo ( ) . clone ( ) ;
let maybe_old_wc_commit = old_repo
2022-09-22 04:44:46 +00:00
. view ( )
2023-01-24 03:55:15 +00:00
. get_wc_commit_id ( self . workspace_id ( ) )
2023-10-03 15:07:45 +00:00
. map ( | commit_id | tx . base_repo ( ) . store ( ) . get_commit ( commit_id ) )
2022-09-22 04:44:46 +00:00
. transpose ( ) ? ;
2023-10-03 10:18:37 +00:00
let maybe_new_wc_commit = tx
. repo ( )
. view ( )
. get_wc_commit_id ( self . workspace_id ( ) )
. map ( | commit_id | tx . repo ( ) . store ( ) . get_commit ( commit_id ) )
. transpose ( ) ? ;
2023-10-03 15:07:45 +00:00
if self . working_copy_shared_with_git {
let git_repo = self . git_backend ( ) . unwrap ( ) . open_git_repo ( ) ? ;
2023-10-03 10:18:37 +00:00
if let Some ( wc_commit ) = & maybe_new_wc_commit {
git ::reset_head ( tx . mut_repo ( ) , & git_repo , wc_commit ) ? ;
}
2023-11-10 07:52:45 +00:00
let failed_branches = git ::export_refs ( tx . mut_repo ( ) ) ? ;
2023-10-03 15:07:45 +00:00
print_failed_git_export ( ui , & failed_branches ) ? ;
}
2023-12-12 05:42:05 +00:00
self . user_repo = ReadonlyUserRepo ::new ( tx . commit ( description ) ) ;
2023-11-20 02:10:39 +00:00
self . report_repo_changes ( ui , & old_repo ) ? ;
2022-09-22 04:44:46 +00:00
if self . may_update_working_copy {
2023-10-03 10:18:37 +00:00
if let Some ( new_commit ) = & maybe_new_wc_commit {
self . update_working_copy ( ui , maybe_old_wc_commit . as_ref ( ) , new_commit ) ? ;
} else {
// It seems the workspace was deleted, so we shouldn't try to
// update it.
}
2022-09-22 04:44:46 +00:00
}
2023-01-04 08:57:36 +00:00
let settings = & self . settings ;
2023-08-16 21:10:54 +00:00
if settings . user_name ( ) . is_empty ( ) | | settings . user_email ( ) . is_empty ( ) {
2023-01-12 06:36:59 +00:00
writeln! (
ui . warning ( ) ,
2023-06-28 21:43:22 +00:00
r #" Name and email not configured. Until configured, your commits will be created with the empty identity, and can't be pushed to remotes. To configure, run:
jj config set - - user user . name " Some One "
2023-08-16 12:45:24 +00:00
jj config set - - user user . email " someone@example.com " " #
2023-01-12 06:36:59 +00:00
) ? ;
2022-10-10 00:22:20 +00:00
}
2022-09-22 04:44:46 +00:00
Ok ( ( ) )
}
2023-11-20 02:10:39 +00:00
/// Inform the user about important changes to the repo since the previous
/// operation (when `old_repo` was loaded).
fn report_repo_changes (
& self ,
ui : & mut Ui ,
old_repo : & Arc < ReadonlyRepo > ,
) -> Result < ( ) , CommandError > {
let old_view = old_repo . view ( ) ;
let new_repo = self . repo ( ) . as_ref ( ) ;
let new_view = new_repo . view ( ) ;
2023-12-21 13:15:37 +00:00
let old_heads = RevsetExpression ::commits ( old_view . heads ( ) . iter ( ) . cloned ( ) . collect ( ) ) ;
let new_heads = RevsetExpression ::commits ( new_view . heads ( ) . iter ( ) . cloned ( ) . collect ( ) ) ;
2023-11-20 02:10:39 +00:00
// Filter the revsets by conflicts instead of reading all commits and doing the
// filtering here. That way, we can afford to evaluate the revset even if there
// are millions of commits added to the repo, assuming the revset engine can
// efficiently skip non-conflicting commits. Filter out empty commits mostly so
// `jj new <conflicted commit>` doesn't result in a message about new conflicts.
let conflicts = RevsetExpression ::filter ( RevsetFilterPredicate ::HasConflict )
. intersection ( & RevsetExpression ::filter ( RevsetFilterPredicate ::File ( None ) ) ) ;
2023-12-21 13:15:37 +00:00
let removed_conflicts_expr = new_heads . range ( & old_heads ) . intersection ( & conflicts ) ;
let added_conflicts_expr = old_heads . range ( & new_heads ) . intersection ( & conflicts ) ;
2023-11-20 02:10:39 +00:00
let get_commits = | expr : Rc < RevsetExpression > | -> Result < Vec < Commit > , CommandError > {
let commits = expr
. evaluate_programmatic ( new_repo ) ?
. iter ( )
. commits ( new_repo . store ( ) )
. try_collect ( ) ? ;
Ok ( commits )
} ;
let removed_conflict_commits = get_commits ( removed_conflicts_expr ) ? ;
let added_conflict_commits = get_commits ( added_conflicts_expr ) ? ;
fn commits_by_change_id ( commits : & [ Commit ] ) -> IndexMap < & ChangeId , Vec < & Commit > > {
let mut result : IndexMap < & ChangeId , Vec < & Commit > > = IndexMap ::new ( ) ;
for commit in commits {
result . entry ( commit . change_id ( ) ) . or_default ( ) . push ( commit ) ;
}
result
}
let removed_conflicts_by_change_id = commits_by_change_id ( & removed_conflict_commits ) ;
let added_conflicts_by_change_id = commits_by_change_id ( & added_conflict_commits ) ;
let mut resolved_conflicts_by_change_id = removed_conflicts_by_change_id . clone ( ) ;
resolved_conflicts_by_change_id
. retain ( | change_id , _commits | ! added_conflicts_by_change_id . contains_key ( change_id ) ) ;
let mut new_conflicts_by_change_id = added_conflicts_by_change_id . clone ( ) ;
new_conflicts_by_change_id
. retain ( | change_id , _commits | ! removed_conflicts_by_change_id . contains_key ( change_id ) ) ;
// TODO: Also report new divergence and maybe resolved divergence
let mut fmt = ui . stderr_formatter ( ) ;
if ! resolved_conflicts_by_change_id . is_empty ( ) {
writeln! (
fmt ,
" Existing conflicts were resolved or abandoned from these commits: "
) ? ;
for ( _ , old_commits ) in & resolved_conflicts_by_change_id {
// TODO: Report which ones were resolved and which ones were abandoned. However,
// that involves resolving the change_id among the visible commits in the new
// repo, which isn't currently supported by Google's revset engine.
for commit in old_commits {
write! ( fmt , " " ) ? ;
self . write_commit_summary ( fmt . as_mut ( ) , commit ) ? ;
writeln! ( fmt ) ? ;
}
}
}
if ! new_conflicts_by_change_id . is_empty ( ) {
writeln! ( fmt , " New conflicts appeared in these commits: " ) ? ;
for ( _ , new_commits ) in & new_conflicts_by_change_id {
for commit in new_commits {
write! ( fmt , " " ) ? ;
self . write_commit_summary ( fmt . as_mut ( ) , commit ) ? ;
writeln! ( fmt ) ? ;
}
}
}
2023-11-30 07:02:18 +00:00
// Hint that the user might want to `jj new` to the first conflict commit to
// resolve conflicts. Only show the hints if there were any new or resolved
// conflicts, and only if there are still some conflicts.
if ! ( added_conflict_commits . is_empty ( )
| | resolved_conflicts_by_change_id . is_empty ( ) & & new_conflicts_by_change_id . is_empty ( ) )
{
// If the user just resolved some conflict and squashed them in, there won't be
// any new conflicts. Clarify to them that there are still some other conflicts
// to resolve. (We don't mention conflicts in commits that weren't affected by
// the operation, however.)
if new_conflicts_by_change_id . is_empty ( ) {
writeln! (
fmt ,
" There are still unresolved conflicts in rebased descendants. " ,
) ? ;
}
let root_conflicts_revset = RevsetExpression ::commits (
added_conflict_commits
. iter ( )
. map ( | commit | commit . id ( ) . clone ( ) )
. collect ( ) ,
)
. roots ( )
. evaluate_programmatic ( new_repo ) ? ;
let root_conflict_commits : Vec < _ > = root_conflicts_revset
. iter ( )
. commits ( new_repo . store ( ) )
. try_collect ( ) ? ;
if ! root_conflict_commits . is_empty ( ) {
fmt . push_label ( " hint " ) ? ;
if added_conflict_commits . len ( ) = = 1 {
writeln! ( fmt , " To resolve the conflicts, start by updating to it: " , ) ? ;
} else if root_conflict_commits . len ( ) = = 1 {
writeln! (
fmt ,
" To resolve the conflicts, start by updating to the first one: " ,
) ? ;
} else {
writeln! (
fmt ,
" To resolve the conflicts, start by updating to one of the first ones: " ,
) ? ;
}
for commit in root_conflict_commits {
writeln! ( fmt , " jj new {} " , short_change_hash ( commit . change_id ( ) ) ) ? ;
}
writeln! (
fmt ,
r #" Then use `jj resolve`, or edit the conflict markers in the file directly.
Once the conflicts are resolved , you may want inspect the result with ` jj diff ` .
Then run ` jj squash ` to move the resolution into the conflicted commit . " #,
) ? ;
fmt . pop_label ( ) ? ;
}
}
2023-11-20 02:10:39 +00:00
Ok ( ( ) )
}
2022-09-22 04:44:46 +00:00
}
2023-01-15 08:28:16 +00:00
#[ must_use ]
pub struct WorkspaceCommandTransaction < ' a > {
helper : & ' a mut WorkspaceCommandHelper ,
tx : Transaction ,
}
impl WorkspaceCommandTransaction < '_ > {
/// Workspace helper that may use the base repo.
pub fn base_workspace_helper ( & self ) -> & WorkspaceCommandHelper {
self . helper
}
2023-02-16 02:15:50 +00:00
pub fn base_repo ( & self ) -> & Arc < ReadonlyRepo > {
2023-01-15 08:28:16 +00:00
self . tx . base_repo ( )
}
pub fn repo ( & self ) -> & MutableRepo {
self . tx . repo ( )
}
pub fn mut_repo ( & mut self ) -> & mut MutableRepo {
self . tx . mut_repo ( )
}
pub fn check_out ( & mut self , commit : & Commit ) -> Result < Commit , CheckOutCommitError > {
2023-01-24 03:55:15 +00:00
let workspace_id = self . helper . workspace_id ( ) . to_owned ( ) ;
2023-01-15 08:28:16 +00:00
let settings = & self . helper . settings ;
self . tx . mut_repo ( ) . check_out ( workspace_id , settings , commit )
}
pub fn edit ( & mut self , commit : & Commit ) -> Result < ( ) , EditCommitError > {
2023-01-24 03:55:15 +00:00
let workspace_id = self . helper . workspace_id ( ) . to_owned ( ) ;
2023-01-15 08:28:16 +00:00
self . tx . mut_repo ( ) . edit ( workspace_id , commit )
}
2023-01-25 03:53:17 +00:00
pub fn run_mergetool (
& self ,
2023-07-29 01:59:41 +00:00
ui : & Ui ,
2023-08-27 05:03:53 +00:00
tree : & MergedTree ,
2023-01-25 03:53:17 +00:00
repo_path : & RepoPath ,
2023-08-27 05:03:53 +00:00
) -> Result < MergedTreeId , CommandError > {
2023-01-25 03:53:17 +00:00
let settings = & self . helper . settings ;
Ok ( crate ::merge_tools ::run_mergetool (
ui , tree , repo_path , settings ,
) ? )
}
pub fn edit_diff (
& self ,
2023-07-29 01:59:41 +00:00
ui : & Ui ,
2023-08-27 12:57:00 +00:00
left_tree : & MergedTree ,
right_tree : & MergedTree ,
2023-08-29 21:13:36 +00:00
matcher : & dyn Matcher ,
2023-01-25 03:53:17 +00:00
instructions : & str ,
2023-08-27 12:57:00 +00:00
) -> Result < MergedTreeId , CommandError > {
2024-02-16 17:54:09 +00:00
let base_ignores = self . helper . base_ignores ( ) ? ;
2023-01-25 03:53:17 +00:00
let settings = & self . helper . settings ;
Ok ( crate ::merge_tools ::edit_diff (
ui ,
2023-08-27 12:57:00 +00:00
left_tree ,
right_tree ,
2023-08-29 21:13:36 +00:00
matcher ,
2023-01-25 03:53:17 +00:00
instructions ,
base_ignores ,
settings ,
2023-08-27 12:57:00 +00:00
) ? )
2023-01-25 03:53:17 +00:00
}
pub fn select_diff (
& self ,
2023-07-29 01:59:41 +00:00
ui : & Ui ,
2023-08-27 12:57:00 +00:00
left_tree : & MergedTree ,
right_tree : & MergedTree ,
2023-08-29 21:13:36 +00:00
matcher : & dyn Matcher ,
2023-01-25 03:53:17 +00:00
instructions : & str ,
interactive : bool ,
2023-08-27 12:57:00 +00:00
) -> Result < MergedTreeId , CommandError > {
2023-01-25 03:53:17 +00:00
if interactive {
2023-08-29 21:13:36 +00:00
self . edit_diff ( ui , left_tree , right_tree , matcher , instructions )
2023-01-25 03:53:17 +00:00
} else {
2023-11-02 04:54:56 +00:00
let new_tree_id = restore_tree ( right_tree , left_tree , matcher ) ? ;
Ok ( new_tree_id )
2023-01-25 03:53:17 +00:00
}
}
2023-01-25 04:14:49 +00:00
pub fn format_commit_summary ( & self , commit : & Commit ) -> String {
let mut output = Vec ::new ( ) ;
self . write_commit_summary ( & mut PlainTextFormatter ::new ( & mut output ) , commit )
. expect ( " write() to PlainTextFormatter should never fail " ) ;
String ::from_utf8 ( output ) . expect ( " template output should be utf-8 bytes " )
}
2023-01-15 08:28:16 +00:00
pub fn write_commit_summary (
& self ,
formatter : & mut dyn Formatter ,
commit : & Commit ,
) -> std ::io ::Result < ( ) > {
2023-05-06 00:12:08 +00:00
// TODO: Use the disambiguation revset
2023-05-12 05:09:48 +00:00
let id_prefix_context = IdPrefixContext ::default ( ) ;
2023-02-12 09:13:09 +00:00
let template = parse_commit_summary_template (
2023-02-13 17:52:21 +00:00
self . tx . repo ( ) ,
2023-02-12 09:13:09 +00:00
self . helper . workspace_id ( ) ,
2023-05-04 00:54:08 +00:00
& id_prefix_context ,
2023-02-12 08:53:09 +00:00
& self . helper . template_aliases_map ,
2023-02-12 09:13:09 +00:00
& self . helper . settings ,
2023-02-14 05:01:37 +00:00
)
. expect ( " parse error should be confined by WorkspaceCommandHelper::new() " ) ;
2023-02-12 09:13:09 +00:00
template . format ( commit , formatter )
2023-01-15 08:28:16 +00:00
}
2023-12-12 05:42:05 +00:00
pub fn finish ( self , ui : & mut Ui , description : impl Into < String > ) -> Result < ( ) , CommandError > {
self . helper . finish_transaction ( ui , self . tx , description )
2023-01-15 08:28:16 +00:00
}
pub fn into_inner ( self ) -> Transaction {
self . tx
}
}
2023-12-23 10:36:32 +00:00
fn find_workspace_dir ( cwd : & Path ) -> & Path {
cwd . ancestors ( )
. find ( | path | path . join ( " .jj " ) . is_dir ( ) )
. unwrap_or ( cwd )
2023-02-27 01:11:15 +00:00
}
2023-12-23 10:36:32 +00:00
fn map_workspace_load_error ( err : WorkspaceLoadError , workspace_path : Option < & str > ) -> CommandError {
2023-02-27 01:11:15 +00:00
match err {
2023-01-10 00:53:22 +00:00
WorkspaceLoadError ::NoWorkspaceHere ( wc_path ) = > {
// Prefer user-specified workspace_path_str instead of absolute wc_path.
2023-12-23 10:36:32 +00:00
let workspace_path_str = workspace_path . unwrap_or ( " . " ) ;
2023-01-10 00:53:22 +00:00
let message = format! ( r # "There is no jj repo in "{workspace_path_str}""# ) ;
let git_dir = wc_path . join ( " .git " ) ;
if git_dir . is_dir ( ) {
user_error_with_hint (
message ,
" It looks like this is a git repo. You can create a jj repo backed by it by \
running this :
2024-02-07 14:54:38 +00:00
jj git init - - git - repo = . " ,
2023-01-10 00:53:22 +00:00
)
} else {
user_error ( message )
}
}
WorkspaceLoadError ::RepoDoesNotExist ( repo_dir ) = > user_error ( format! (
" The repository directory at {} is missing. Was it moved? " ,
2023-01-10 02:00:19 +00:00
repo_dir . display ( ) ,
2023-01-10 00:53:22 +00:00
) ) ,
2023-02-26 21:50:11 +00:00
WorkspaceLoadError ::StoreLoadError ( err @ StoreLoadError ::UnsupportedType { .. } ) = > {
2024-01-31 02:35:56 +00:00
internal_error_with_message (
" This version of the jj binary doesn't support this type of repo " ,
err ,
)
2023-02-26 21:50:11 +00:00
}
2023-07-05 13:42:08 +00:00
WorkspaceLoadError ::StoreLoadError (
err @ ( StoreLoadError ::ReadError { .. } | StoreLoadError ::Backend ( _ ) ) ,
2024-01-31 02:35:56 +00:00
) = > internal_error_with_message ( " The repository appears broken or inaccessible " , err ) ,
2023-11-24 21:08:16 +00:00
WorkspaceLoadError ::StoreLoadError ( StoreLoadError ::Signing (
err @ SignInitError ::UnknownBackend ( _ ) ,
2024-01-31 11:45:03 +00:00
) ) = > user_error ( err ) ,
2024-01-31 02:35:56 +00:00
WorkspaceLoadError ::StoreLoadError ( err ) = > internal_error ( err ) ,
2024-02-01 08:39:54 +00:00
WorkspaceLoadError ::NonUnicodePath | WorkspaceLoadError ::Path ( _ ) = > user_error ( err ) ,
2023-02-27 01:11:15 +00:00
}
2023-01-10 00:53:22 +00:00
}
2023-01-12 01:16:29 +00:00
pub fn start_repo_transaction (
repo : & Arc < ReadonlyRepo > ,
settings : & UserSettings ,
string_args : & [ String ] ,
) -> Transaction {
2023-12-12 05:42:05 +00:00
let mut tx = repo . start_transaction ( settings ) ;
2023-01-12 01:16:29 +00:00
// TODO: Either do better shell-escaping here or store the values in some list
// type (which we currently don't have).
let shell_escape = | arg : & String | {
if arg . as_bytes ( ) . iter ( ) . all ( | b | {
matches! ( b ,
b 'A' ..= b 'Z'
| b 'a' ..= b 'z'
| b '0' ..= b '9'
| b ','
| b '-'
| b '.'
| b '/'
| b ':'
| b '@'
| b '_'
)
} ) {
arg . clone ( )
} else {
format! ( " ' {} ' " , arg . replace ( '\'' , " \\ ' " ) )
}
} ;
let mut quoted_strings = vec! [ " jj " . to_string ( ) ] ;
quoted_strings . extend ( string_args . iter ( ) . skip ( 1 ) . map ( shell_escape ) ) ;
tx . set_tag ( " args " . to_string ( ) , quoted_strings . join ( " " ) ) ;
tx
}
2023-11-11 10:11:34 +00:00
/// Whether the working copy is stale or not.
#[ derive(Clone, Debug, Eq, PartialEq) ]
pub enum WorkingCopyFreshness {
/// The working copy isn't stale, and no need to reload the repo.
Fresh ,
/// The working copy was updated since we loaded the repo. The repo must be
/// reloaded at the working copy's operation.
Updated ( Box < Operation > ) ,
/// The working copy is behind the latest operation.
2022-10-02 18:59:26 +00:00
WorkingCopyStale ,
2023-11-11 10:11:34 +00:00
/// The working copy is a sibling of the latest operation.
2022-10-02 18:59:26 +00:00
SiblingOperation ,
}
2023-07-25 18:31:05 +00:00
#[ instrument(skip_all) ]
2022-10-02 17:09:46 +00:00
pub fn check_stale_working_copy (
2023-10-14 06:12:57 +00:00
locked_wc : & dyn LockedWorkingCopy ,
2022-10-02 17:39:18 +00:00
wc_commit : & Commit ,
2023-05-21 07:30:17 +00:00
repo : & ReadonlyRepo ,
2023-11-11 10:03:41 +00:00
) -> Result < WorkingCopyFreshness , OpStoreError > {
2022-10-02 18:59:26 +00:00
// Check if the working copy's tree matches the repo's view
2023-08-15 05:58:03 +00:00
let wc_tree_id = locked_wc . old_tree_id ( ) ;
2023-08-28 20:09:19 +00:00
if wc_commit . tree_id ( ) = = wc_tree_id {
2023-05-21 07:30:17 +00:00
// The working copy isn't stale, and no need to reload the repo.
2023-11-11 10:03:41 +00:00
Ok ( WorkingCopyFreshness ::Fresh )
2022-10-02 18:59:26 +00:00
} else {
2022-10-02 17:39:18 +00:00
let wc_operation_data = repo
. op_store ( )
2023-11-11 10:03:41 +00:00
. read_operation ( locked_wc . old_operation_id ( ) ) ? ;
2022-10-02 17:39:18 +00:00
let wc_operation = Operation ::new (
repo . op_store ( ) . clone ( ) ,
locked_wc . old_operation_id ( ) . clone ( ) ,
wc_operation_data ,
) ;
let repo_operation = repo . operation ( ) ;
2024-01-14 06:40:22 +00:00
let ancestor_op = dag_walk ::closest_common_node_ok (
2023-11-12 10:42:09 +00:00
[ Ok ( wc_operation . clone ( ) ) ] ,
[ Ok ( repo_operation . clone ( ) ) ] ,
2023-05-20 07:27:23 +00:00
| op : & Operation | op . id ( ) . clone ( ) ,
2023-11-12 10:42:09 +00:00
| op : & Operation | op . parents ( ) . collect_vec ( ) ,
2024-01-14 06:40:22 +00:00
) ?
. expect ( " unrelated operations " ) ;
if ancestor_op . id ( ) = = repo_operation . id ( ) {
// The working copy was updated since we loaded the repo. The repo must be
// reloaded at the working copy's operation.
Ok ( WorkingCopyFreshness ::Updated ( Box ::new ( wc_operation ) ) )
} else if ancestor_op . id ( ) = = wc_operation . id ( ) {
// The working copy was not updated when some repo operation committed,
// meaning that it's stale compared to the repo view.
Ok ( WorkingCopyFreshness ::WorkingCopyStale )
2022-10-02 17:39:18 +00:00
} else {
2024-01-14 06:40:22 +00:00
Ok ( WorkingCopyFreshness ::SiblingOperation )
2022-10-02 17:39:18 +00:00
}
}
}
2023-10-07 00:23:23 +00:00
pub fn print_checkout_stats (
ui : & mut Ui ,
stats : CheckoutStats ,
new_commit : & Commit ,
) -> Result < ( ) , std ::io ::Error > {
2022-09-22 04:44:46 +00:00
if stats . added_files > 0 | | stats . updated_files > 0 | | stats . removed_files > 0 {
writeln! (
2023-10-10 11:07:06 +00:00
ui . stderr ( ) ,
2022-09-22 04:44:46 +00:00
" Added {} files, modified {} files, removed {} files " ,
2023-10-10 11:07:06 +00:00
stats . added_files ,
stats . updated_files ,
stats . removed_files
2022-09-22 04:44:46 +00:00
) ? ;
}
2023-10-07 00:23:23 +00:00
if stats . skipped_files ! = 0 {
writeln! (
ui . warning ( ) ,
" {} of those updates were skipped because there were conflicting changes in the \
working copy . " ,
stats . skipped_files
) ? ;
writeln! (
ui . hint ( ) ,
" Hint: Inspect the changes compared to the intended target with `jj diff --from {}`.
Discard the conflicting changes with ` jj restore - - from { } ` . " ,
short_commit_hash ( new_commit . id ( ) ) ,
short_commit_hash ( new_commit . id ( ) )
) ? ;
}
2022-09-22 04:44:46 +00:00
Ok ( ( ) )
}
2024-01-15 22:31:33 +00:00
pub fn print_trackable_remote_branches ( ui : & Ui , view : & View ) -> io ::Result < ( ) > {
let remote_branch_names = view
. branches ( )
. filter ( | ( _ , branch_target ) | branch_target . local_target . is_present ( ) )
. flat_map ( | ( name , branch_target ) | {
branch_target
. remote_refs
. into_iter ( )
. filter ( | & ( _ , remote_ref ) | ! remote_ref . is_tracking ( ) )
. map ( move | ( remote , _ ) | format! ( " {name} @ {remote} " ) )
} )
. collect_vec ( ) ;
if remote_branch_names . is_empty ( ) {
return Ok ( ( ) ) ;
}
writeln! (
ui . hint ( ) ,
" The following remote branches aren't associated with the existing local branches: "
) ? ;
let mut formatter = ui . stderr_formatter ( ) ;
for full_name in & remote_branch_names {
write! ( formatter , " " ) ? ;
writeln! ( formatter . labeled ( " branch " ) , " {full_name} " ) ? ;
}
drop ( formatter ) ;
writeln! (
ui . hint ( ) ,
" Hint: Run `jj branch track {names}` to keep local branches updated on future pulls. " ,
names = remote_branch_names . join ( " " ) ,
) ? ;
Ok ( ( ) )
}
2023-10-23 23:24:27 +00:00
pub fn parse_string_pattern ( src : & str ) -> Result < StringPattern , StringPatternParseError > {
if let Some ( ( kind , pat ) ) = src . split_once ( ':' ) {
StringPattern ::from_str_kind ( pat , kind )
} else {
Ok ( StringPattern ::exact ( src ) )
}
}
2023-11-03 18:10:01 +00:00
/// Resolves revsets into revisions for use; useful for rebases or operations
/// that take multiple parents.
pub fn resolve_all_revs (
workspace_command : & WorkspaceCommandHelper ,
revisions : & [ RevisionArg ] ,
) -> Result < IndexSet < Commit > , CommandError > {
2024-02-13 06:44:35 +00:00
let commits = resolve_multiple_nonempty_revsets_default_single ( workspace_command , revisions ) ? ;
2023-11-03 18:10:01 +00:00
let root_commit_id = workspace_command . repo ( ) . store ( ) . root_commit_id ( ) ;
if commits . len ( ) > = 2 & & commits . iter ( ) . any ( | c | c . id ( ) = = root_commit_id ) {
Err ( user_error ( " Cannot merge with root revision " ) )
} else {
Ok ( commits )
}
}
2023-01-04 09:20:11 +00:00
fn load_revset_aliases (
2023-07-29 01:59:41 +00:00
ui : & Ui ,
2023-05-23 03:45:11 +00:00
layered_configs : & LayeredConfigs ,
2023-01-04 09:20:11 +00:00
) -> Result < RevsetAliasesMap , CommandError > {
2022-11-25 10:27:13 +00:00
const TABLE_KEY : & str = " revset-aliases " ;
let mut aliases_map = RevsetAliasesMap ::new ( ) ;
2023-05-23 03:45:11 +00:00
// Load from all config layers in order. 'f(x)' in default layer should be
// overridden by 'f(a)' in user.
for ( _ , config ) in layered_configs . sources ( ) {
let table = if let Some ( table ) = config . get_table ( TABLE_KEY ) . optional ( ) ? {
table
} else {
continue ;
} ;
for ( decl , value ) in table . into_iter ( ) . sorted_by ( | a , b | a . 0. cmp ( & b . 0 ) ) {
let r = value
. into_string ( )
. map_err ( | e | e . to_string ( ) )
. and_then ( | v | aliases_map . insert ( & decl , v ) . map_err ( | e | e . to_string ( ) ) ) ;
if let Err ( s ) = r {
writeln! ( ui . warning ( ) , r # "Failed to load "{TABLE_KEY}.{decl}": {s}"# ) ? ;
}
2022-11-25 10:27:13 +00:00
}
}
Ok ( aliases_map )
}
2023-02-04 23:55:03 +00:00
pub fn resolve_multiple_nonempty_revsets (
2023-02-04 23:43:01 +00:00
revision_args : & [ RevisionArg ] ,
workspace_command : & WorkspaceCommandHelper ,
) -> Result < IndexSet < Commit > , CommandError > {
let mut acc = IndexSet ::new ( ) ;
for revset in revision_args {
2024-02-13 06:44:35 +00:00
let revisions = workspace_command . resolve_revset ( revset ) ? ;
2023-02-04 23:43:01 +00:00
workspace_command . check_non_empty ( & revisions ) ? ;
acc . extend ( revisions ) ;
}
Ok ( acc )
}
2023-07-25 16:07:03 +00:00
pub fn resolve_multiple_nonempty_revsets_default_single (
2022-09-22 04:44:46 +00:00
workspace_command : & WorkspaceCommandHelper ,
2022-11-28 14:32:44 +00:00
revisions : & [ RevisionArg ] ,
2023-02-04 05:33:17 +00:00
) -> Result < IndexSet < Commit > , CommandError > {
2023-07-25 17:17:36 +00:00
let mut all_commits = IndexSet ::new ( ) ;
for revision_str in revisions {
2024-02-13 06:44:35 +00:00
let commits = workspace_command . resolve_revset_default_single ( revision_str ) ? ;
2023-07-25 16:07:03 +00:00
workspace_command . check_non_empty ( & commits ) ? ;
for commit in commits {
2023-01-31 06:32:18 +00:00
let commit_hash = short_commit_hash ( commit . id ( ) ) ;
2023-07-25 17:17:36 +00:00
if ! all_commits . insert ( commit ) {
2023-01-31 06:32:18 +00:00
return Err ( user_error ( format! (
r # "More than one revset resolved to revision {commit_hash}"# ,
) ) ) ;
}
2022-09-22 04:44:46 +00:00
}
}
2023-07-25 17:17:36 +00:00
Ok ( all_commits )
2023-02-05 00:10:42 +00:00
}
2022-09-22 04:44:46 +00:00
2022-10-02 17:09:46 +00:00
pub fn update_working_copy (
2022-09-22 04:44:46 +00:00
repo : & Arc < ReadonlyRepo > ,
2023-10-13 21:46:26 +00:00
workspace : & mut Workspace ,
2022-09-22 04:44:46 +00:00
old_commit : Option < & Commit > ,
2023-02-22 10:24:05 +00:00
new_commit : & Commit ,
2022-09-22 04:44:46 +00:00
) -> Result < Option < CheckoutStats > , CommandError > {
2023-08-28 20:09:19 +00:00
let old_tree_id = old_commit . map ( | commit | commit . tree_id ( ) . clone ( ) ) ;
let stats = if Some ( new_commit . tree_id ( ) ) ! = old_tree_id . as_ref ( ) {
2022-09-22 04:44:46 +00:00
// TODO: CheckoutError::ConcurrentCheckout should probably just result in a
// warning for most commands (but be an error for the checkout command)
2023-10-13 21:46:26 +00:00
let stats = workspace
2023-10-16 17:21:54 +00:00
. check_out ( repo . op_id ( ) . clone ( ) , old_tree_id . as_ref ( ) , new_commit )
2022-09-22 04:44:46 +00:00
. map_err ( | err | {
2024-01-31 02:35:56 +00:00
internal_error_with_message (
format! ( " Failed to check out commit {} " , new_commit . id ( ) . hex ( ) ) ,
err ,
)
2022-09-22 04:44:46 +00:00
} ) ? ;
Some ( stats )
} else {
// Record new operation id which represents the latest working-copy state
2023-10-15 18:42:25 +00:00
let locked_ws = workspace . start_working_copy_mutation ( ) ? ;
locked_ws . finish ( repo . op_id ( ) . clone ( ) ) ? ;
2022-09-22 04:44:46 +00:00
None
} ;
Ok ( stats )
}
2023-02-12 08:53:09 +00:00
fn load_template_aliases (
2023-07-29 01:59:41 +00:00
ui : & Ui ,
2023-05-23 03:45:11 +00:00
layered_configs : & LayeredConfigs ,
2023-02-12 08:53:09 +00:00
) -> Result < TemplateAliasesMap , CommandError > {
const TABLE_KEY : & str = " template-aliases " ;
let mut aliases_map = TemplateAliasesMap ::new ( ) ;
2023-05-23 03:45:11 +00:00
// Load from all config layers in order. 'f(x)' in default layer should be
// overridden by 'f(a)' in user.
for ( _ , config ) in layered_configs . sources ( ) {
let table = if let Some ( table ) = config . get_table ( TABLE_KEY ) . optional ( ) ? {
table
} else {
continue ;
} ;
for ( decl , value ) in table . into_iter ( ) . sorted_by ( | a , b | a . 0. cmp ( & b . 0 ) ) {
let r = value
. into_string ( )
. map_err ( | e | e . to_string ( ) )
. and_then ( | v | aliases_map . insert ( & decl , v ) . map_err ( | e | e . to_string ( ) ) ) ;
if let Err ( s ) = r {
writeln! ( ui . warning ( ) , r # "Failed to load "{TABLE_KEY}.{decl}": {s}"# ) ? ;
}
2023-02-12 08:53:09 +00:00
}
}
Ok ( aliases_map )
}
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2023-02-12 09:13:09 +00:00
fn parse_commit_summary_template < ' a > (
2023-02-13 17:52:21 +00:00
repo : & ' a dyn Repo ,
2022-10-06 10:20:51 +00:00
workspace_id : & WorkspaceId ,
2023-05-12 05:09:48 +00:00
id_prefix_context : & ' a IdPrefixContext ,
2023-02-12 08:53:09 +00:00
aliases_map : & TemplateAliasesMap ,
2022-10-06 10:20:51 +00:00
settings : & UserSettings ,
2023-02-14 05:12:06 +00:00
) -> Result < Box < dyn Template < Commit > + ' a > , CommandError > {
2023-02-14 14:55:30 +00:00
let template_text = settings . config ( ) . get_string ( " templates.commit_summary " ) ? ;
2023-02-18 08:22:57 +00:00
Ok ( commit_templater ::parse (
2023-02-14 05:12:06 +00:00
repo ,
workspace_id ,
2023-05-04 00:54:08 +00:00
id_prefix_context ,
2023-02-14 05:12:06 +00:00
& template_text ,
aliases_map ,
) ? )
2022-10-06 10:20:51 +00:00
}
2023-03-05 04:10:02 +00:00
/// Helper to reformat content of log-like commands.
#[ derive(Clone, Debug) ]
pub enum LogContentFormat {
NoWrap ,
Wrap { term_width : usize } ,
}
impl LogContentFormat {
pub fn new ( ui : & Ui , settings : & UserSettings ) -> Result < Self , config ::ConfigError > {
if settings . config ( ) . get_bool ( " ui.log-word-wrap " ) ? {
let term_width = usize ::from ( ui . term_width ( ) . unwrap_or ( 80 ) ) ;
Ok ( LogContentFormat ::Wrap { term_width } )
} else {
Ok ( LogContentFormat ::NoWrap )
}
}
pub fn write (
& self ,
formatter : & mut dyn Formatter ,
content_fn : impl FnOnce ( & mut dyn Formatter ) -> std ::io ::Result < ( ) > ,
) -> std ::io ::Result < ( ) > {
self . write_graph_text ( formatter , content_fn , | | 0 )
}
pub fn write_graph_text (
& self ,
formatter : & mut dyn Formatter ,
content_fn : impl FnOnce ( & mut dyn Formatter ) -> std ::io ::Result < ( ) > ,
graph_width_fn : impl FnOnce ( ) -> usize ,
) -> std ::io ::Result < ( ) > {
match self {
LogContentFormat ::NoWrap = > content_fn ( formatter ) ,
LogContentFormat ::Wrap { term_width } = > {
let mut recorder = FormatRecorder ::new ( ) ;
content_fn ( & mut recorder ) ? ;
text_util ::write_wrapped (
formatter ,
& recorder ,
term_width . saturating_sub ( graph_width_fn ( ) ) ,
) ? ;
Ok ( ( ) )
}
}
}
}
2022-12-13 06:22:08 +00:00
// TODO: Use a proper TOML library to serialize instead.
2023-01-12 06:24:39 +00:00
pub fn serialize_config_value ( value : & config ::Value ) -> String {
match & value . kind {
2022-12-13 06:22:08 +00:00
config ::ValueKind ::Table ( table ) = > format! (
" {{{}}} " ,
// TODO: Remove sorting when config crate maintains deterministic ordering.
table
2023-01-12 06:24:39 +00:00
. iter ( )
. sorted_by_key ( | ( k , _ ) | * k )
2022-12-13 06:22:08 +00:00
. map ( | ( k , v ) | format! ( " {k} = {} " , serialize_config_value ( v ) ) )
. join ( " , " )
) ,
2023-01-12 06:24:39 +00:00
config ::ValueKind ::Array ( vals ) = > {
format! ( " [ {} ] " , vals . iter ( ) . map ( serialize_config_value ) . join ( " , " ) )
}
2022-12-13 06:22:08 +00:00
config ::ValueKind ::String ( val ) = > format! ( " {val:?} " ) ,
_ = > value . to_string ( ) ,
}
}
2023-01-15 04:23:44 +00:00
pub fn write_config_value_to_file (
key : & str ,
value_str : & str ,
path : & Path ,
) -> Result < ( ) , CommandError > {
// Read config
let config_toml = std ::fs ::read_to_string ( path ) . or_else ( | err | {
match err . kind ( ) {
// If config doesn't exist yet, read as empty and we'll write one.
std ::io ::ErrorKind ::NotFound = > Ok ( " " . to_string ( ) ) ,
2024-01-31 11:45:03 +00:00
_ = > Err ( user_error_with_message (
format! ( " Failed to read file {path} " , path = path . display ( ) ) ,
err ,
) ) ,
2023-01-15 04:23:44 +00:00
}
} ) ? ;
let mut doc = toml_edit ::Document ::from_str ( & config_toml ) . map_err ( | err | {
2024-01-31 11:45:03 +00:00
user_error_with_message (
format! ( " Failed to parse file {path} " , path = path . display ( ) ) ,
err ,
)
2023-01-15 04:23:44 +00:00
} ) ? ;
// Apply config value
2023-10-11 03:47:46 +00:00
// Interpret value as string if it can't be parsed as a TOML value.
2023-01-15 04:23:44 +00:00
// TODO(#531): Infer types based on schema (w/ --type arg to override).
let item = match toml_edit ::Value ::from_str ( value_str ) {
2023-10-11 03:47:46 +00:00
Ok ( value ) = > toml_edit ::value ( value ) ,
2023-01-15 04:23:44 +00:00
_ = > toml_edit ::value ( value_str ) ,
} ;
let mut target_table = doc . as_table_mut ( ) ;
let mut key_parts_iter = key . split ( '.' ) ;
// Note: split guarantees at least one item.
let last_key_part = key_parts_iter . next_back ( ) . unwrap ( ) ;
for key_part in key_parts_iter {
target_table = target_table
. entry ( key_part )
. or_insert_with ( | | toml_edit ::Item ::Table ( toml_edit ::Table ::new ( ) ) )
. as_table_mut ( )
. ok_or_else ( | | {
user_error ( format! (
" Failed to set {key}: would overwrite non-table value with parent table "
) )
} ) ? ;
}
2023-10-11 05:02:21 +00:00
// Error out if overwriting non-scalar value for key (table or array) with
// scalar.
2023-01-15 04:23:44 +00:00
match target_table . get ( last_key_part ) {
2023-10-11 05:02:21 +00:00
None | Some ( toml_edit ::Item ::None | toml_edit ::Item ::Value ( _ ) ) = > { }
Some ( toml_edit ::Item ::Table ( _ ) | toml_edit ::Item ::ArrayOfTables ( _ ) ) = > {
2023-01-15 04:23:44 +00:00
return Err ( user_error ( format! (
2023-10-11 05:02:21 +00:00
" Failed to set {key}: would overwrite entire table "
2023-10-11 03:47:46 +00:00
) ) ) ;
2023-01-15 04:23:44 +00:00
}
}
target_table [ last_key_part ] = item ;
// Write config back
std ::fs ::write ( path , doc . to_string ( ) ) . map_err ( | err | {
2024-01-31 11:45:03 +00:00
user_error_with_message (
format! ( " Failed to write file {path} " , path = path . display ( ) ) ,
err ,
)
2023-01-15 04:23:44 +00:00
} )
}
2023-07-12 21:08:58 +00:00
pub fn get_new_config_file_path (
2023-01-15 04:23:44 +00:00
config_source : & ConfigSource ,
2023-08-13 00:38:46 +00:00
command : & CommandHelper ,
2023-01-15 04:23:44 +00:00
) -> Result < PathBuf , CommandError > {
let edit_path = match config_source {
// TODO(#531): Special-case for editors that can't handle viewing directories?
ConfigSource ::User = > {
2023-07-12 21:08:58 +00:00
new_config_path ( ) ? . ok_or_else ( | | user_error ( " No repo config path found to edit " ) ) ?
2023-01-15 04:23:44 +00:00
}
2023-08-13 00:38:46 +00:00
ConfigSource ::Repo = > command . workspace_loader ( ) ? . repo_path ( ) . join ( " config.toml " ) ,
2023-01-15 04:23:44 +00:00
_ = > {
return Err ( user_error ( format! (
" Can't get path for config source {config_source:?} "
) ) ) ;
}
} ;
Ok ( edit_path )
}
2023-01-05 04:55:20 +00:00
pub fn run_ui_editor ( settings : & UserSettings , edit_path : & PathBuf ) -> Result < ( ) , CommandError > {
2023-08-10 22:50:29 +00:00
let editor : CommandNameAndArgs = settings
. config ( )
. get ( " ui.editor " )
. map_err ( | err | CommandError ::ConfigError ( format! ( " ui.editor: {err} " ) ) ) ? ;
2023-11-23 00:10:13 +00:00
let exit_status = editor . to_command ( ) . arg ( edit_path ) . status ( ) . map_err ( | err | {
2024-01-31 11:45:03 +00:00
user_error_with_message (
format! (
// The executable couldn't be found or run; command-line arguments are not relevant
" Failed to run editor '{name}' " ,
name = editor . split_name ( ) ,
) ,
err ,
)
2023-11-23 00:10:13 +00:00
} ) ? ;
2023-01-05 04:55:20 +00:00
if ! exit_status . success ( ) {
return Err ( user_error ( format! (
" Editor '{editor}' exited with an error "
) ) ) ;
}
Ok ( ( ) )
}
2024-01-22 22:06:47 +00:00
pub fn edit_temp_file (
error_name : & str ,
tempfile_suffix : & str ,
dir : & Path ,
content : & str ,
settings : & UserSettings ,
) -> Result < String , CommandError > {
let path = ( | | -> Result < _ , io ::Error > {
let mut file = tempfile ::Builder ::new ( )
. prefix ( " editor- " )
. suffix ( tempfile_suffix )
. tempfile_in ( dir ) ? ;
file . write_all ( content . as_bytes ( ) ) ? ;
let ( _ , path ) = file . keep ( ) . map_err ( | e | e . error ) ? ;
Ok ( path )
} ) ( )
. map_err ( | e | {
2024-01-31 11:45:03 +00:00
user_error_with_message (
format! (
r # "Failed to create {} file in "{}""# ,
error_name ,
dir . display ( ) ,
) ,
e ,
)
2024-01-22 22:06:47 +00:00
} ) ? ;
run_ui_editor ( settings , & path ) ? ;
let edited = fs ::read_to_string ( & path ) . map_err ( | e | {
2024-01-31 11:45:03 +00:00
user_error_with_message (
format! ( r # "Failed to read {} file "{}""# , error_name , path . display ( ) ) ,
e ,
)
2024-01-22 22:06:47 +00:00
} ) ? ;
// Delete the file only if everything went well.
// TODO: Tell the user the name of the file we left behind.
std ::fs ::remove_file ( path ) . ok ( ) ;
Ok ( edited )
}
2022-09-22 04:44:46 +00:00
pub fn short_commit_hash ( commit_id : & CommitId ) -> String {
commit_id . hex ( ) [ 0 .. 12 ] . to_string ( )
}
2023-01-11 18:30:31 +00:00
pub fn short_change_hash ( change_id : & ChangeId ) -> String {
2023-02-12 19:49:05 +00:00
// TODO: We could avoid the unwrap() and make this more efficient by converting
// straight from binary.
to_reverse_hex ( & change_id . hex ( ) [ 0 .. 12 ] ) . unwrap ( )
2023-01-11 18:30:31 +00:00
}
2022-09-22 04:44:46 +00:00
pub fn short_operation_hash ( operation_id : & OperationId ) -> String {
operation_id . hex ( ) [ 0 .. 12 ] . to_string ( )
}
2024-01-20 22:23:43 +00:00
#[ derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd) ]
pub struct RemoteBranchName {
pub branch : String ,
pub remote : String ,
}
impl fmt ::Display for RemoteBranchName {
fn fmt ( & self , f : & mut fmt ::Formatter < '_ > ) -> fmt ::Result {
let RemoteBranchName { branch , remote } = self ;
write! ( f , " {branch}@{remote} " )
}
}
#[ derive(Clone, Debug) ]
pub struct RemoteBranchNamePattern {
pub branch : StringPattern ,
pub remote : StringPattern ,
}
impl FromStr for RemoteBranchNamePattern {
type Err = String ;
fn from_str ( src : & str ) -> Result < Self , Self ::Err > {
// The kind prefix applies to both branch and remote fragments. It's
// weird that unanchored patterns like substring:branch@remote is split
// into two, but I can't think of a better syntax.
// TODO: should we disable substring pattern? what if we added regex?
let ( maybe_kind , pat ) = src
. split_once ( ':' )
. map_or ( ( None , src ) , | ( kind , pat ) | ( Some ( kind ) , pat ) ) ;
let to_pattern = | pat : & str | {
if let Some ( kind ) = maybe_kind {
StringPattern ::from_str_kind ( pat , kind ) . map_err ( | err | err . to_string ( ) )
} else {
Ok ( StringPattern ::exact ( pat ) )
}
} ;
// TODO: maybe reuse revset parser to handle branch/remote name containing @
let ( branch , remote ) = pat
. rsplit_once ( '@' )
. ok_or_else ( | | " remote branch must be specified in branch@remote form " . to_owned ( ) ) ? ;
Ok ( RemoteBranchNamePattern {
branch : to_pattern ( branch ) ? ,
remote : to_pattern ( remote ) ? ,
} )
}
}
impl RemoteBranchNamePattern {
pub fn is_exact ( & self ) -> bool {
self . branch . is_exact ( ) & & self . remote . is_exact ( )
}
}
impl fmt ::Display for RemoteBranchNamePattern {
fn fmt ( & self , f : & mut fmt ::Formatter < '_ > ) -> fmt ::Result {
let RemoteBranchNamePattern { branch , remote } = self ;
write! ( f , " {branch}@{remote} " )
}
}
2022-09-22 04:44:46 +00:00
/// Jujutsu (An experimental VCS)
///
/// To get started, see the tutorial at https://github.com/martinvonz/jj/blob/main/docs/tutorial.md.
#[ derive(clap::Parser, Clone, Debug) ]
2023-07-06 08:38:12 +00:00
#[ command(name = " jj " ) ]
2022-09-22 04:44:46 +00:00
pub struct Args {
2022-09-29 17:42:28 +00:00
#[ command(flatten) ]
2022-09-22 04:44:46 +00:00
pub global_args : GlobalArgs ,
}
#[ derive(clap::Args, Clone, Debug) ]
2024-01-11 02:50:12 +00:00
#[ command(next_help_heading = " Global Options " ) ]
2022-09-22 04:44:46 +00:00
pub struct GlobalArgs {
/// Path to repository to operate on
///
/// By default, Jujutsu searches for the closest .jj/ directory in an
/// ancestor of the current working directory.
2024-01-11 02:50:12 +00:00
#[ arg(long, short = 'R', global = true, value_hint = clap::ValueHint::DirPath) ]
2022-09-22 04:44:46 +00:00
pub repository : Option < String > ,
2023-02-02 23:11:18 +00:00
/// Don't snapshot the working copy, and don't update it
2022-09-22 04:44:46 +00:00
///
2023-02-02 23:11:18 +00:00
/// By default, Jujutsu snapshots the working copy at the beginning of every
/// command. The working copy is also updated at the end of the command,
/// if the command modified the working-copy commit (`@`). If you want
2024-01-10 20:16:47 +00:00
/// to avoid snapshotting the working copy and instead see a possibly
2023-02-02 23:11:18 +00:00
/// stale working copy commit, you can use `--ignore-working-copy`.
2022-09-22 04:44:46 +00:00
/// This may be useful e.g. in a command prompt, especially if you have
/// another process that commits the working copy.
2023-02-02 23:11:18 +00:00
///
/// Loading the repository is at a specific operation with `--at-operation`
/// implies `--ignore-working-copy`.
2024-01-11 02:50:12 +00:00
#[ arg(long, global = true) ]
2023-02-02 23:11:18 +00:00
pub ignore_working_copy : bool ,
2022-09-22 04:44:46 +00:00
/// Operation to load the repo at
///
/// Operation to load the repo at. By default, Jujutsu loads the repo at the
/// most recent operation. You can use `--at-op=<operation ID>` to see what
/// the repo looked like at an earlier operation. For example `jj
/// --at-op=<operation ID> st` will show you what `jj st` would have
/// shown you when the given operation had just finished.
///
/// Use `jj op log` to find the operation ID you want. Any unambiguous
/// prefix of the operation ID is enough.
///
2023-02-02 23:11:18 +00:00
/// When loading the repo at an earlier operation, the working copy will be
/// ignored, as if `--ignore-working-copy` had been specified.
2022-09-22 04:44:46 +00:00
///
/// It is possible to run mutating commands when loading the repo at an
/// earlier operation. Doing that is equivalent to having run concurrent
/// commands starting at the earlier operation. There's rarely a reason to
/// do that, but it is possible.
2024-01-11 02:50:12 +00:00
#[ arg(long, visible_alias = " at-op " , global = true, default_value = " @ " ) ]
2022-09-22 04:44:46 +00:00
pub at_operation : String ,
2024-02-18 16:47:12 +00:00
/// Enable debug logging
#[ arg(long, global = true) ]
pub debug : bool ,
2022-11-22 04:46:50 +00:00
#[ command(flatten) ]
pub early_args : EarlyArgs ,
}
#[ derive(clap::Args, Clone, Debug) ]
pub struct EarlyArgs {
2022-09-22 04:44:46 +00:00
/// When to colorize output (always, never, auto)
2024-01-11 02:50:12 +00:00
#[ arg(long, value_name = " WHEN " , global = true) ]
2022-09-22 04:44:46 +00:00
pub color : Option < ColorChoice > ,
2022-11-01 00:31:30 +00:00
/// Disable the pager
2024-01-11 02:50:12 +00:00
#[ arg(long, value_name = " WHEN " , global = true, action = ArgAction::SetTrue) ]
2022-11-22 04:46:50 +00:00
// Parsing with ignore_errors will crash if this is bool, so use
// Option<bool>.
pub no_pager : Option < bool > ,
2023-09-14 23:56:45 +00:00
/// Additional configuration options (can be repeated)
2022-10-31 01:29:26 +00:00
// TODO: Introduce a `--config` option with simpler syntax for simple
// cases, designed so that `--config ui.color=auto` works
2024-01-11 02:50:12 +00:00
#[ arg(long, value_name = " TOML " , global = true) ]
2022-10-31 01:29:26 +00:00
pub config_toml : Vec < String > ,
2022-09-22 04:44:46 +00:00
}
2023-08-12 01:38:11 +00:00
/// Create a description from a list of paragraphs.
2022-12-21 04:47:10 +00:00
///
/// Based on the Git CLI behavior. See `opt_parse_m()` and `cleanup_mode` in
/// `git/builtin/commit.c`.
2023-08-12 01:38:11 +00:00
pub fn join_message_paragraphs ( paragraphs : & [ String ] ) -> String {
// Ensure each paragraph ends with a newline, then add another newline between
// paragraphs.
paragraphs
. iter ( )
. map ( | p | text_util ::complete_newline ( p . as_str ( ) ) )
. join ( " \n " )
2022-12-21 04:47:10 +00:00
}
2022-11-28 14:32:44 +00:00
#[ derive(Clone, Debug) ]
pub struct RevisionArg ( String ) ;
impl Deref for RevisionArg {
type Target = str ;
fn deref ( & self ) -> & Self ::Target {
self . 0. as_str ( )
}
}
#[ derive(Clone) ]
pub struct RevisionArgValueParser ;
impl TypedValueParser for RevisionArgValueParser {
type Value = RevisionArg ;
fn parse_ref (
& self ,
cmd : & Command ,
arg : Option < & Arg > ,
value : & OsStr ,
2023-01-26 22:19:20 +00:00
) -> Result < Self ::Value , clap ::Error > {
2022-11-28 14:32:44 +00:00
let string = NonEmptyStringValueParser ::new ( ) . parse ( cmd , arg , value . to_os_string ( ) ) ? ;
Ok ( RevisionArg ( string ) )
}
}
impl ValueParserFactory for RevisionArg {
type Parser = RevisionArgValueParser ;
fn value_parser ( ) -> RevisionArgValueParser {
RevisionArgValueParser
}
}
2023-04-14 01:49:35 +00:00
fn resolve_default_command (
2023-07-29 01:59:41 +00:00
ui : & Ui ,
2023-04-14 01:49:35 +00:00
config : & config ::Config ,
app : & Command ,
2023-07-06 08:52:11 +00:00
mut string_args : Vec < String > ,
) -> Result < Vec < String > , CommandError > {
2023-04-14 01:49:35 +00:00
const PRIORITY_FLAGS : & [ & str ] = & [ " help " , " --help " , " -h " , " --version " , " -V " ] ;
let has_priority_flag = string_args
. iter ( )
. any ( | arg | PRIORITY_FLAGS . contains ( & arg . as_str ( ) ) ) ;
if has_priority_flag {
2023-07-06 08:52:11 +00:00
return Ok ( string_args ) ;
2023-04-14 01:49:35 +00:00
}
let app_clone = app
. clone ( )
. allow_external_subcommands ( true )
. ignore_errors ( true ) ;
2023-07-06 08:52:11 +00:00
let matches = app_clone . try_get_matches_from ( & string_args ) . ok ( ) ;
2023-04-14 01:49:35 +00:00
if let Some ( matches ) = matches {
if matches . subcommand_name ( ) . is_none ( ) {
if config . get_string ( " ui.default-command " ) . is_err ( ) {
writeln! (
ui . hint ( ) ,
" Hint: Use `jj -h` for a list of available commands. "
) ? ;
writeln! (
ui . hint ( ) ,
2024-02-06 17:17:12 +00:00
" Run `jj config set --user ui.default-command log` to disable this message. "
2023-04-14 01:49:35 +00:00
) ? ;
}
let default_command = config
. get_string ( " ui.default-command " )
2023-06-05 04:57:12 +00:00
. unwrap_or_else ( | _ | " log " . to_string ( ) ) ;
2023-04-14 01:49:35 +00:00
// Insert the default command directly after the path to the binary.
string_args . insert ( 1 , default_command ) ;
}
}
2023-07-06 08:52:11 +00:00
Ok ( string_args )
2023-04-14 01:49:35 +00:00
}
2022-09-22 06:29:42 +00:00
fn resolve_aliases (
2023-01-05 05:52:12 +00:00
config : & config ::Config ,
2023-01-26 22:23:19 +00:00
app : & Command ,
2023-07-06 08:43:04 +00:00
mut string_args : Vec < String > ,
2022-09-22 04:44:46 +00:00
) -> Result < Vec < String > , CommandError > {
2023-01-26 22:26:05 +00:00
let mut aliases_map = config . get_table ( " aliases " ) ? ;
if let Ok ( alias_map ) = config . get_table ( " alias " ) {
for ( alias , definition ) in alias_map {
if aliases_map . insert ( alias . clone ( ) , definition ) . is_some ( ) {
return Err ( user_error_with_hint (
format! ( r # "Alias "{alias}" is defined in both [aliases] and [alias]"# ) ,
" [aliases] is the preferred section for aliases. Please remove the alias from \
[ alias ] . " ,
) ) ;
}
}
}
2022-09-22 04:44:46 +00:00
let mut resolved_aliases = HashSet ::new ( ) ;
let mut real_commands = HashSet ::new ( ) ;
for command in app . get_subcommands ( ) {
real_commands . insert ( command . get_name ( ) . to_string ( ) ) ;
for alias in command . get_all_aliases ( ) {
real_commands . insert ( alias . to_string ( ) ) ;
}
}
loop {
let app_clone = app . clone ( ) . allow_external_subcommands ( true ) ;
2022-12-14 02:47:52 +00:00
let matches = app_clone . try_get_matches_from ( & string_args ) . ok ( ) ;
if let Some ( ( command_name , submatches ) ) = matches . as_ref ( ) . and_then ( | m | m . subcommand ( ) ) {
2022-09-22 04:44:46 +00:00
if ! real_commands . contains ( command_name ) {
let alias_name = command_name . to_string ( ) ;
let alias_args = submatches
2022-09-29 16:12:16 +00:00
. get_many ::< OsString > ( " " )
2022-09-22 04:44:46 +00:00
. unwrap_or_default ( )
2022-09-29 16:12:16 +00:00
. map ( | arg | arg . to_str ( ) . unwrap ( ) . to_string ( ) )
2022-09-22 04:44:46 +00:00
. collect_vec ( ) ;
if resolved_aliases . contains ( & alias_name ) {
2022-11-12 22:38:43 +00:00
return Err ( user_error ( format! (
2022-09-22 04:44:46 +00:00
r # "Recursive alias definition involving "{alias_name}""#
) ) ) ;
}
2022-12-07 10:16:29 +00:00
if let Some ( value ) = aliases_map . remove ( & alias_name ) {
2022-12-07 10:26:37 +00:00
if let Ok ( alias_definition ) = value . try_deserialize ::< Vec < String > > ( ) {
2022-12-07 10:16:29 +00:00
assert! ( string_args . ends_with ( & alias_args ) ) ;
string_args . truncate ( string_args . len ( ) - 1 - alias_args . len ( ) ) ;
string_args . extend ( alias_definition ) ;
string_args . extend_from_slice ( & alias_args ) ;
resolved_aliases . insert ( alias_name . clone ( ) ) ;
continue ;
} else {
return Err ( user_error ( format! (
r # "Alias definition for "{alias_name}" must be a string list"#
) ) ) ;
2022-09-22 04:44:46 +00:00
}
2022-12-07 10:16:29 +00:00
} else {
// Not a real command and not an alias, so return what we've resolved so far
return Ok ( string_args ) ;
2022-09-22 04:44:46 +00:00
}
}
}
2022-12-14 02:47:52 +00:00
// No more alias commands, or hit unknown option
2022-09-22 04:44:46 +00:00
return Ok ( string_args ) ;
}
}
2022-09-22 06:29:42 +00:00
2022-11-22 04:46:50 +00:00
/// Parse args that must be interpreted early, e.g. before printing help.
2022-12-14 02:20:32 +00:00
fn handle_early_args (
ui : & mut Ui ,
2023-01-26 22:23:19 +00:00
app : & Command ,
2022-12-14 02:20:32 +00:00
args : & [ String ] ,
2023-01-05 06:15:56 +00:00
layered_configs : & mut LayeredConfigs ,
2022-12-14 02:20:32 +00:00
) -> Result < ( ) , CommandError > {
2023-06-28 19:29:56 +00:00
// ignore_errors() bypasses errors like missing subcommand
let early_matches = app
. clone ( )
. disable_version_flag ( true )
. disable_help_flag ( true )
. disable_help_subcommand ( true )
. ignore_errors ( true )
. try_get_matches_from ( args ) ? ;
2022-11-22 04:46:50 +00:00
let mut args : EarlyArgs = EarlyArgs ::from_arg_matches ( & early_matches ) . unwrap ( ) ;
if let Some ( choice ) = args . color {
2023-01-02 04:38:54 +00:00
args . config_toml . push ( format! ( r # "ui.color="{choice}""# ) ) ;
2022-11-22 04:46:50 +00:00
}
if args . no_pager . unwrap_or_default ( ) {
2023-08-12 04:25:42 +00:00
args . config_toml . push ( r # "ui.paginate="never""# . to_owned ( ) ) ;
2022-11-22 04:46:50 +00:00
}
if ! args . config_toml . is_empty ( ) {
2023-01-05 06:15:56 +00:00
layered_configs . parse_config_args ( & args . config_toml ) ? ;
2023-01-18 01:20:27 +00:00
ui . reset ( & layered_configs . merge ( ) ) ? ;
2022-11-22 04:46:50 +00:00
}
Ok ( ( ) )
}
2023-01-04 07:57:10 +00:00
pub fn expand_args (
2023-07-29 01:59:41 +00:00
ui : & Ui ,
2023-01-26 22:23:19 +00:00
app : & Command ,
2022-09-22 06:29:42 +00:00
args_os : ArgsOs ,
2023-01-05 05:52:12 +00:00
config : & config ::Config ,
2023-01-04 07:57:10 +00:00
) -> Result < Vec < String > , CommandError > {
2022-09-22 06:29:42 +00:00
let mut string_args : Vec < String > = vec! [ ] ;
for arg_os in args_os {
if let Some ( string_arg ) = arg_os . to_str ( ) {
string_args . push ( string_arg . to_owned ( ) ) ;
} else {
return Err ( CommandError ::CliError ( " Non-utf8 argument " . to_string ( ) ) ) ;
}
}
2023-07-06 08:52:11 +00:00
let string_args = resolve_default_command ( ui , config , app , string_args ) ? ;
2023-07-06 08:43:04 +00:00
resolve_aliases ( config , app , string_args )
2023-01-04 07:57:10 +00:00
}
pub fn parse_args (
ui : & mut Ui ,
2023-01-26 22:23:19 +00:00
app : & Command ,
2023-01-04 07:57:10 +00:00
tracing_subscription : & TracingSubscription ,
string_args : & [ String ] ,
2023-01-05 06:15:56 +00:00
layered_configs : & mut LayeredConfigs ,
2023-01-04 08:12:56 +00:00
) -> Result < ( ArgMatches , Args ) , CommandError > {
2023-01-05 06:15:56 +00:00
handle_early_args ( ui , app , string_args , layered_configs ) ? ;
2023-12-24 02:49:36 +00:00
let matches = app
. clone ( )
. arg_required_else_help ( true )
. subcommand_required ( true )
. try_get_matches_from ( string_args ) ? ;
2022-10-31 17:49:53 +00:00
2022-11-22 04:46:50 +00:00
let args : Args = Args ::from_arg_matches ( & matches ) . unwrap ( ) ;
2024-02-18 16:47:12 +00:00
if args . global_args . debug {
// TODO: set up debug logging as early as possible
tracing_subscription . enable_debug_logging ( ) ? ;
2023-01-03 07:54:17 +00:00
}
2023-01-04 08:12:56 +00:00
Ok ( ( matches , args ) )
2022-09-22 06:29:42 +00:00
}
2022-09-22 07:12:52 +00:00
2023-02-10 08:24:05 +00:00
const BROKEN_PIPE_EXIT_CODE : u8 = 3 ;
pub fn handle_command_result (
ui : & mut Ui ,
result : Result < ( ) , CommandError > ,
) -> std ::io ::Result < ExitCode > {
2024-01-31 03:33:23 +00:00
match & result {
2023-02-10 08:24:05 +00:00
Ok ( ( ) ) = > Ok ( ExitCode ::SUCCESS ) ,
2024-01-31 11:45:03 +00:00
Err ( CommandError ::UserError { err , hint } ) = > {
2024-02-03 08:26:10 +00:00
writeln! ( ui . error ( ) , " Error: {err} " ) ? ;
2024-01-31 11:45:03 +00:00
print_error_sources ( ui , err . source ( ) ) ? ;
2022-11-12 23:28:32 +00:00
if let Some ( hint ) = hint {
2023-02-10 08:24:05 +00:00
writeln! ( ui . hint ( ) , " Hint: {hint} " ) ? ;
2022-11-12 23:28:32 +00:00
}
2023-02-10 08:24:05 +00:00
Ok ( ExitCode ::from ( 1 ) )
2022-09-22 07:12:52 +00:00
}
2022-09-24 14:15:23 +00:00
Err ( CommandError ::ConfigError ( message ) ) = > {
2023-02-10 08:24:05 +00:00
writeln! ( ui . error ( ) , " Config error: {message} " ) ? ;
2023-03-31 03:23:49 +00:00
writeln! (
ui . hint ( ) ,
" For help, see https://github.com/martinvonz/jj/blob/main/docs/config.md. "
) ? ;
2023-02-10 08:24:05 +00:00
Ok ( ExitCode ::from ( 1 ) )
2022-09-24 14:15:23 +00:00
}
Err ( CommandError ::CliError ( message ) ) = > {
2023-02-10 08:24:05 +00:00
writeln! ( ui . error ( ) , " Error: {message} " ) ? ;
Ok ( ExitCode ::from ( 2 ) )
2022-09-22 07:12:52 +00:00
}
2022-10-31 17:49:53 +00:00
Err ( CommandError ::ClapCliError ( inner ) ) = > {
let clap_str = if ui . color ( ) {
inner . render ( ) . ansi ( ) . to_string ( )
} else {
inner . render ( ) . to_string ( )
} ;
2022-11-22 00:18:27 +00:00
match inner . kind ( ) {
clap ::error ::ErrorKind ::DisplayHelp
| clap ::error ::ErrorKind ::DisplayHelpOnMissingArgumentOrSubcommand = > {
ui . request_pager ( )
}
_ = > { }
} ;
2022-10-31 17:49:53 +00:00
// Definitions for exit codes and streams come from
// https://github.com/clap-rs/clap/blob/master/src/error/mod.rs
match inner . kind ( ) {
clap ::error ::ErrorKind ::DisplayHelp | clap ::error ::ErrorKind ::DisplayVersion = > {
2023-10-10 11:07:06 +00:00
write! ( ui . stdout ( ) , " {clap_str} " ) ? ;
2023-02-10 08:24:05 +00:00
Ok ( ExitCode ::SUCCESS )
2022-10-31 17:49:53 +00:00
}
_ = > {
2023-10-10 11:07:06 +00:00
write! ( ui . stderr ( ) , " {clap_str} " ) ? ;
2023-02-10 08:24:05 +00:00
Ok ( ExitCode ::from ( 2 ) )
2022-10-31 17:49:53 +00:00
}
}
}
2023-02-10 08:24:05 +00:00
Err ( CommandError ::BrokenPipe ) = > {
2023-02-14 17:59:42 +00:00
// A broken pipe is not an error, but a signal to exit gracefully.
2023-02-10 08:24:05 +00:00
Ok ( ExitCode ::from ( BROKEN_PIPE_EXIT_CODE ) )
}
2024-01-31 02:35:56 +00:00
Err ( CommandError ::InternalError ( err ) ) = > {
2024-02-03 08:26:10 +00:00
writeln! ( ui . error ( ) , " Internal error: {err} " ) ? ;
2024-01-31 03:33:23 +00:00
print_error_sources ( ui , err . source ( ) ) ? ;
2023-02-10 08:24:05 +00:00
Ok ( ExitCode ::from ( 255 ) )
2022-09-22 07:12:52 +00:00
}
}
}
2023-01-03 08:03:33 +00:00
/// CLI command builder and runner.
#[ must_use ]
2023-01-03 12:53:30 +00:00
pub struct CliRunner {
2023-01-03 08:03:33 +00:00
tracing_subscription : TracingSubscription ,
2023-01-26 22:23:19 +00:00
app : Command ,
2023-08-19 04:58:28 +00:00
extra_configs : Option < config ::Config > ,
2023-01-03 09:38:17 +00:00
store_factories : Option < StoreFactories > ,
2024-01-25 16:30:11 +00:00
working_copy_factories : Option < HashMap < String , Box < dyn WorkingCopyFactory > > > ,
2023-01-03 12:53:30 +00:00
dispatch_fn : CliDispatchFn ,
2024-01-30 23:13:01 +00:00
start_hook_fns : Vec < CliDispatchFn > ,
2023-02-04 00:13:47 +00:00
process_global_args_fns : Vec < ProcessGlobalArgsFn > ,
2023-01-03 08:03:33 +00:00
}
2023-04-29 13:31:03 +00:00
type CliDispatchFn = Box < dyn FnOnce ( & mut Ui , & CommandHelper ) -> Result < ( ) , CommandError > > ;
2023-01-03 12:53:30 +00:00
2023-02-04 00:13:47 +00:00
type ProcessGlobalArgsFn = Box < dyn FnOnce ( & mut Ui , & ArgMatches ) -> Result < ( ) , CommandError > > ;
2023-01-03 12:53:30 +00:00
impl CliRunner {
2023-01-03 08:03:33 +00:00
/// Initializes CLI environment and returns a builder. This should be called
/// as early as possible.
pub fn init ( ) -> Self {
let tracing_subscription = TracingSubscription ::init ( ) ;
crate ::cleanup_guard ::init ( ) ;
CliRunner {
tracing_subscription ,
2023-01-03 08:33:53 +00:00
app : crate ::commands ::default_app ( ) ,
2023-08-19 04:58:28 +00:00
extra_configs : None ,
2023-01-03 09:38:17 +00:00
store_factories : None ,
2023-10-15 23:01:47 +00:00
working_copy_factories : None ,
2023-01-03 12:53:30 +00:00
dispatch_fn : Box ::new ( crate ::commands ::run_command ) ,
2024-01-30 23:13:01 +00:00
start_hook_fns : vec ! [ ] ,
2023-02-04 00:13:47 +00:00
process_global_args_fns : vec ! [ ] ,
2023-01-03 08:03:33 +00:00
}
}
2023-04-20 22:17:08 +00:00
/// Set the version to be displayed by `jj version`.
2024-01-06 15:09:00 +00:00
pub fn version ( mut self , version : & str ) -> Self {
self . app = self . app . version ( version . to_string ( ) ) ;
2023-04-20 22:17:08 +00:00
self
}
2023-08-19 04:58:28 +00:00
/// Adds default configs in addition to the normal defaults.
pub fn set_extra_config ( mut self , extra_configs : config ::Config ) -> Self {
self . extra_configs = Some ( extra_configs ) ;
self
}
2023-01-03 09:38:17 +00:00
/// Replaces `StoreFactories` to be used.
2023-02-04 00:44:02 +00:00
pub fn set_store_factories ( mut self , store_factories : StoreFactories ) -> Self {
self . store_factories = Some ( store_factories ) ;
self
2023-01-03 09:38:17 +00:00
}
2023-10-15 23:01:47 +00:00
/// Replaces working copy factories to be used.
pub fn set_working_copy_factories (
mut self ,
2024-01-25 16:30:11 +00:00
working_copy_factories : HashMap < String , Box < dyn WorkingCopyFactory > > ,
2023-10-15 23:01:47 +00:00
) -> Self {
self . working_copy_factories = Some ( working_copy_factories ) ;
self
}
2024-01-30 23:13:01 +00:00
pub fn add_start_hook ( mut self , start_hook_fn : CliDispatchFn ) -> Self {
self . start_hook_fns . push ( start_hook_fn ) ;
self
}
2023-01-03 08:33:53 +00:00
/// Registers new subcommands in addition to the default ones.
2023-02-04 00:44:02 +00:00
pub fn add_subcommand < C , F > ( mut self , custom_dispatch_fn : F ) -> Self
2023-01-03 08:33:53 +00:00
where
C : clap ::Subcommand ,
2023-01-03 12:53:30 +00:00
F : FnOnce ( & mut Ui , & CommandHelper , C ) -> Result < ( ) , CommandError > + 'static ,
2023-01-03 08:33:53 +00:00
{
2023-01-03 12:53:30 +00:00
let old_dispatch_fn = self . dispatch_fn ;
let new_dispatch_fn =
2023-04-29 13:31:03 +00:00
move | ui : & mut Ui , command_helper : & CommandHelper | match C ::from_arg_matches (
command_helper . matches ( ) ,
) {
Ok ( command ) = > custom_dispatch_fn ( ui , command_helper , command ) ,
Err ( _ ) = > old_dispatch_fn ( ui , command_helper ) ,
2023-01-03 12:53:30 +00:00
} ;
2023-02-04 00:44:02 +00:00
self . app = C ::augment_subcommands ( self . app ) ;
self . dispatch_fn = Box ::new ( new_dispatch_fn ) ;
self
2023-01-03 08:03:33 +00:00
}
2023-01-18 18:28:00 +00:00
/// Registers new global arguments in addition to the default ones.
2023-02-04 00:44:02 +00:00
pub fn add_global_args < A , F > ( mut self , process_before : F ) -> Self
2023-01-18 18:28:00 +00:00
where
A : clap ::Args ,
F : FnOnce ( & mut Ui , A ) -> Result < ( ) , CommandError > + 'static ,
{
2023-02-04 00:13:47 +00:00
let process_global_args_fn = move | ui : & mut Ui , matches : & ArgMatches | {
let custom_args = A ::from_arg_matches ( matches ) . unwrap ( ) ;
process_before ( ui , custom_args )
} ;
2023-02-04 00:44:02 +00:00
self . app = A ::augment_args ( self . app ) ;
2023-02-04 00:13:47 +00:00
self . process_global_args_fns
. push ( Box ::new ( process_global_args_fn ) ) ;
2023-02-04 00:44:02 +00:00
self
2023-01-18 18:28:00 +00:00
}
2023-07-25 17:51:44 +00:00
#[ instrument(skip_all) ]
2023-01-19 15:10:18 +00:00
fn run_internal (
self ,
ui : & mut Ui ,
mut layered_configs : LayeredConfigs ,
) -> Result < ( ) , CommandError > {
2023-08-14 23:08:00 +00:00
let cwd = env ::current_dir ( ) . map_err ( | _ | {
user_error_with_hint (
" Could not determine current directory " ,
" Did you check-out a commit where the directory doesn't exist? " ,
)
} ) ? ;
2023-12-22 03:31:46 +00:00
// Use cwd-relative workspace configs to resolve default command and
// aliases. WorkspaceLoader::init() won't do any heavy lifting other
// than the path resolution.
let maybe_cwd_workspace_loader = WorkspaceLoader ::init ( find_workspace_dir ( & cwd ) )
. map_err ( | err | map_workspace_load_error ( err , None ) ) ;
2023-01-05 03:36:31 +00:00
layered_configs . read_user_config ( ) ? ;
2023-12-22 03:31:46 +00:00
if let Ok ( loader ) = & maybe_cwd_workspace_loader {
layered_configs . read_repo_config ( loader . repo_path ( ) ) ? ;
}
2023-01-05 03:36:31 +00:00
let config = layered_configs . merge ( ) ;
2023-01-18 01:20:27 +00:00
ui . reset ( & config ) ? ;
2023-12-22 03:31:46 +00:00
2023-12-22 03:57:24 +00:00
let string_args = expand_args ( ui , & self . app , env ::args_os ( ) , & config ) ? ;
2023-01-04 09:24:30 +00:00
let ( matches , args ) = parse_args (
ui ,
& self . app ,
& self . tracing_subscription ,
& string_args ,
2023-01-05 06:15:56 +00:00
& mut layered_configs ,
2023-01-04 09:24:30 +00:00
) ? ;
2023-02-04 00:13:47 +00:00
for process_global_args_fn in self . process_global_args_fns {
process_global_args_fn ( ui , & matches ) ? ;
}
2023-01-05 06:15:56 +00:00
2023-12-23 10:36:32 +00:00
let maybe_workspace_loader = if let Some ( path ) = & args . global_args . repository {
2023-12-23 10:47:20 +00:00
// Invalid -R path is an error. No need to proceed.
let loader = WorkspaceLoader ::init ( & cwd . join ( path ) )
. map_err ( | err | map_workspace_load_error ( err , Some ( path ) ) ) ? ;
2023-12-22 03:31:46 +00:00
layered_configs . read_repo_config ( loader . repo_path ( ) ) ? ;
2023-12-23 10:47:20 +00:00
Ok ( loader )
2023-12-23 10:36:32 +00:00
} else {
2023-12-22 03:31:46 +00:00
maybe_cwd_workspace_loader
2023-12-23 10:36:32 +00:00
} ;
2023-12-22 03:31:46 +00:00
// Apply workspace configs and --config-toml arguments.
2023-01-05 06:15:56 +00:00
let config = layered_configs . merge ( ) ;
2023-01-18 01:20:27 +00:00
ui . reset ( & config ) ? ;
2023-12-22 03:57:24 +00:00
// If -R is specified, check if the expanded arguments differ. Aliases
// can also be injected by --config-toml, but that's obviously wrong.
if args . global_args . repository . is_some ( ) {
let new_string_args = expand_args ( ui , & self . app , env ::args_os ( ) , & config ) . ok ( ) ;
if new_string_args . as_ref ( ) ! = Some ( & string_args ) {
writeln! (
ui . warning ( ) ,
" Command aliases cannot be loaded from -R/--repository path "
) ? ;
}
}
2023-01-05 06:15:56 +00:00
let settings = UserSettings ::from_config ( config ) ;
2023-10-15 23:01:47 +00:00
let working_copy_factories = self
. working_copy_factories
2024-01-25 16:30:11 +00:00
. unwrap_or_else ( default_working_copy_factories ) ;
2023-01-04 08:16:53 +00:00
let command_helper = CommandHelper ::new (
self . app ,
2023-01-04 08:18:45 +00:00
cwd ,
2023-01-04 08:16:53 +00:00
string_args ,
2023-04-29 13:31:03 +00:00
matches ,
2023-01-04 08:16:53 +00:00
args . global_args ,
2023-01-04 08:57:36 +00:00
settings ,
2023-01-12 06:24:39 +00:00
layered_configs ,
2023-01-10 00:53:22 +00:00
maybe_workspace_loader ,
2023-01-04 08:16:53 +00:00
self . store_factories . unwrap_or_default ( ) ,
2023-10-14 12:52:50 +00:00
working_copy_factories ,
2023-01-04 08:16:53 +00:00
) ;
2024-01-30 23:13:01 +00:00
for start_hook_fn in self . start_hook_fns {
start_hook_fn ( ui , & command_helper ) ? ;
}
2023-04-29 13:31:03 +00:00
( self . dispatch_fn ) ( ui , & command_helper )
2023-01-03 08:03:33 +00:00
}
2023-01-19 15:10:18 +00:00
#[ must_use ]
2023-07-25 17:51:44 +00:00
#[ instrument(skip(self)) ]
2023-08-19 04:58:28 +00:00
pub fn run ( mut self ) -> ExitCode {
let mut default_config = crate ::config ::default_config ( ) ;
if let Some ( extra_configs ) = self . extra_configs . take ( ) {
default_config = config ::Config ::builder ( )
. add_source ( default_config )
. add_source ( extra_configs )
. build ( )
. unwrap ( ) ;
}
let layered_configs = LayeredConfigs ::from_environment ( default_config ) ;
2023-01-18 01:20:27 +00:00
let mut ui = Ui ::with_config ( & layered_configs . merge ( ) )
. expect ( " default config should be valid, env vars are stringly typed " ) ;
2023-01-19 15:10:18 +00:00
let result = self . run_internal ( & mut ui , layered_configs ) ;
2023-02-15 00:53:09 +00:00
let exit_code = handle_command_result ( & mut ui , result )
. unwrap_or_else ( | _ | ExitCode ::from ( BROKEN_PIPE_EXIT_CODE ) ) ;
ui . finalize_pager ( ) ;
exit_code
2023-01-03 08:03:33 +00:00
}
}