diff options
Diffstat (limited to 'contrib')
46 files changed, 2269 insertions, 1474 deletions
diff --git a/contrib/README b/contrib/README index 05f291c..21d3d0e 100644 --- a/contrib/README +++ b/contrib/README @@ -23,7 +23,7 @@ This is the same way as how I have been treating gitk, and to a lesser degree various foreign SCM interfaces, so you know the drill. -I expect that things that start their life in the contrib/ area +I expect things that start their life in the contrib/ area to graduate out of contrib/ once they mature, either by becoming projects on their own, or moving to the toplevel directory. On the other hand, I expect I'll be proposing removal of disused @@ -31,7 +31,7 @@ and inactive ones from time to time. If you have new things to add to this area, please first propose it on the git mailing list, and after a list discussion proves -there are some general interests (it does not have to be a +there is general interest (it does not have to be a list-wide consensus for a tool targeted to a relatively narrow audience -- for example I do not work with projects whose upstream is svn, so I have no use for git-svn myself, but it is diff --git a/contrib/buildsystems/CMakeLists.txt b/contrib/buildsystems/CMakeLists.txt index ea2a531..804629c 100644 --- a/contrib/buildsystems/CMakeLists.txt +++ b/contrib/buildsystems/CMakeLists.txt @@ -227,7 +227,7 @@ add_compile_definitions(GIT_HOST_CPU="${CMAKE_SYSTEM_PROCESSOR}") add_compile_definitions(SHA256_BLK INTERNAL_QSORT RUNTIME_PREFIX) add_compile_definitions(NO_OPENSSL SHA1_DC SHA1DC_NO_STANDARD_INCLUDES SHA1DC_INIT_SAFE_HASH_DEFAULT=0 - SHA1DC_CUSTOM_INCLUDE_SHA1_C="cache.h" + SHA1DC_CUSTOM_INCLUDE_SHA1_C="git-compat-util.h" SHA1DC_CUSTOM_INCLUDE_UBC_CHECK_C="git-compat-util.h" ) list(APPEND compat_SOURCES sha1dc_git.c sha1dc/sha1.c sha1dc/ubc_check.c block-sha1/sha1.c sha256/block/sha256.c compat/qsort_s.c) @@ -308,6 +308,8 @@ if(SUPPORTS_SIMPLE_IPC) add_compile_definitions(HAVE_FSMONITOR_DAEMON_BACKEND) list(APPEND compat_SOURCES compat/fsmonitor/fsm-listen-win32.c) list(APPEND compat_SOURCES compat/fsmonitor/fsm-health-win32.c) + list(APPEND compat_SOURCES compat/fsmonitor/fsm-ipc-win32.c) + list(APPEND compat_SOURCES compat/fsmonitor/fsm-path-utils-win32.c) add_compile_definitions(HAVE_FSMONITOR_OS_SETTINGS) list(APPEND compat_SOURCES compat/fsmonitor/fsm-settings-win32.c) @@ -315,6 +317,8 @@ if(SUPPORTS_SIMPLE_IPC) add_compile_definitions(HAVE_FSMONITOR_DAEMON_BACKEND) list(APPEND compat_SOURCES compat/fsmonitor/fsm-listen-darwin.c) list(APPEND compat_SOURCES compat/fsmonitor/fsm-health-darwin.c) + list(APPEND compat_SOURCES compat/fsmonitor/fsm-ipc-darwin.c) + list(APPEND compat_SOURCES compat/fsmonitor/fsm-path-utils-darwin.c) add_compile_definitions(HAVE_FSMONITOR_OS_SETTINGS) list(APPEND compat_SOURCES compat/fsmonitor/fsm-settings-darwin.c) @@ -734,6 +738,15 @@ if(WIN32) else() message(FATAL_ERROR "Unhandled compiler: ${CMAKE_C_COMPILER_ID}") endif() + + add_executable(headless-git ${CMAKE_SOURCE_DIR}/compat/win32/headless.c) + if(CMAKE_C_COMPILER_ID STREQUAL "GNU" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_link_options(headless-git PUBLIC -municode -Wl,-subsystem,windows) + elseif(CMAKE_C_COMPILER_ID STREQUAL "MSVC") + target_link_options(headless-git PUBLIC /NOLOGO /ENTRY:wWinMainCRTStartup /SUBSYSTEM:WINDOWS) + else() + message(FATAL_ERROR "Unhandled compiler: ${CMAKE_C_COMPILER_ID}") + endif() elseif(UNIX) target_link_libraries(common-main pthread rt) endif() @@ -961,6 +974,35 @@ target_link_libraries(test-fake-ssh common-main) parse_makefile_for_sources(test-reftable_SOURCES "REFTABLE_TEST_OBJS") list(TRANSFORM test-reftable_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/") +#unit-tests +add_library(unit-test-lib OBJECT ${CMAKE_SOURCE_DIR}/t/unit-tests/test-lib.c) + +parse_makefile_for_scripts(unit_test_PROGRAMS "UNIT_TEST_PROGRAMS" "") +foreach(unit_test ${unit_test_PROGRAMS}) + add_executable("${unit_test}" "${CMAKE_SOURCE_DIR}/t/unit-tests/${unit_test}.c") + target_link_libraries("${unit_test}" unit-test-lib common-main) + set_target_properties("${unit_test}" + PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/t/unit-tests/bin) + if(MSVC) + set_target_properties("${unit_test}" + PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}/t/unit-tests/bin) + set_target_properties("${unit_test}" + PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/t/unit-tests/bin) + endif() + list(APPEND PROGRAMS_BUILT "${unit_test}") + + # t-basic intentionally fails tests, to validate the unit-test infrastructure. + # Therefore, it should only be run as part of t0080, which verifies that it + # fails only in the expected ways. + # + # All other unit tests should be run. + if(NOT ${unit_test} STREQUAL "t-basic") + add_test(NAME "t.unit-tests.${unit_test}" + COMMAND "./${unit_test}" + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/t/unit-tests/bin) + endif() +endforeach() + #test-tool parse_makefile_for_sources(test-tool_SOURCES "TEST_BUILTINS_OBJS") @@ -1021,7 +1063,6 @@ set(NO_PERL ) set(NO_PTHREADS ) set(NO_PYTHON ) set(PAGER_ENV "LESS=FRX LV=-c") -set(DC_SHA1 YesPlease) set(RUNTIME_PREFIX true) set(NO_GETTEXT ) @@ -1057,7 +1098,6 @@ file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "NO_PERL='${NO_PERL}'\n") file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "NO_PTHREADS='${NO_PTHREADS}'\n") file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "NO_UNIX_SOCKETS='${NO_UNIX_SOCKETS}'\n") file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "PAGER_ENV='${PAGER_ENV}'\n") -file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "DC_SHA1='${DC_SHA1}'\n") file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "X='${EXE_EXTENSION}'\n") file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "NO_GETTEXT='${NO_GETTEXT}'\n") file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "RUNTIME_PREFIX='${RUNTIME_PREFIX}'\n") @@ -1070,29 +1110,30 @@ endif() #Make the tests work when building out of the source tree get_filename_component(CACHE_PATH ${CMAKE_CURRENT_LIST_DIR}/../../CMakeCache.txt ABSOLUTE) if(NOT ${CMAKE_BINARY_DIR}/CMakeCache.txt STREQUAL ${CACHE_PATH}) - file(RELATIVE_PATH BUILD_DIR_RELATIVE ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/CMakeCache.txt) - string(REPLACE "/CMakeCache.txt" "" BUILD_DIR_RELATIVE ${BUILD_DIR_RELATIVE}) #Setting the build directory in test-lib.sh before running tests file(WRITE ${CMAKE_BINARY_DIR}/CTestCustom.cmake - "file(STRINGS ${CMAKE_SOURCE_DIR}/t/test-lib.sh GIT_BUILD_DIR_REPL REGEX \"GIT_BUILD_DIR=(.*)\")\n" - "file(STRINGS ${CMAKE_SOURCE_DIR}/t/test-lib.sh content NEWLINE_CONSUME)\n" - "string(REPLACE \"\${GIT_BUILD_DIR_REPL}\" \"GIT_BUILD_DIR=\\\"$TEST_DIRECTORY/../${BUILD_DIR_RELATIVE}\\\"\" content \"\${content}\")\n" - "file(WRITE ${CMAKE_SOURCE_DIR}/t/test-lib.sh \${content})") + "file(WRITE ${CMAKE_SOURCE_DIR}/GIT-BUILD-DIR \"${CMAKE_BINARY_DIR}\")") #misc copies file(COPY ${CMAKE_SOURCE_DIR}/t/chainlint.pl DESTINATION ${CMAKE_BINARY_DIR}/t/) file(COPY ${CMAKE_SOURCE_DIR}/po/is.po DESTINATION ${CMAKE_BINARY_DIR}/po/) - file(COPY ${CMAKE_SOURCE_DIR}/mergetools/tkdiff DESTINATION ${CMAKE_BINARY_DIR}/mergetools/) + file(GLOB mergetools "${CMAKE_SOURCE_DIR}/mergetools/*") + file(COPY ${mergetools} DESTINATION ${CMAKE_BINARY_DIR}/mergetools/) file(COPY ${CMAKE_SOURCE_DIR}/contrib/completion/git-prompt.sh DESTINATION ${CMAKE_BINARY_DIR}/contrib/completion/) file(COPY ${CMAKE_SOURCE_DIR}/contrib/completion/git-completion.bash DESTINATION ${CMAKE_BINARY_DIR}/contrib/completion/) endif() -file(GLOB test_scipts "${CMAKE_SOURCE_DIR}/t/t[0-9]*.sh") +file(GLOB test_scripts "${CMAKE_SOURCE_DIR}/t/t[0-9]*.sh") #test -foreach(tsh ${test_scipts}) - add_test(NAME ${tsh} - COMMAND ${SH_EXE} ${tsh} +foreach(tsh ${test_scripts}) + string(REGEX REPLACE ".*/(.*)\\.sh" "\\1" test_name ${tsh}) + add_test(NAME "t.suite.${test_name}" + COMMAND ${SH_EXE} ${tsh} --no-bin-wrappers --no-chain-lint -vx WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}/t) endforeach() +# This test script takes an extremely long time and is known to time out even +# on fast machines because it requires in excess of one hour to run +set_tests_properties("t.suite.t7112-reset-submodule" PROPERTIES TIMEOUT 4000) + endif()#BUILD_TESTING diff --git a/contrib/buildsystems/Generators/Vcxproj.pm b/contrib/buildsystems/Generators/Vcxproj.pm index 1a25789..b2e68a1 100644 --- a/contrib/buildsystems/Generators/Vcxproj.pm +++ b/contrib/buildsystems/Generators/Vcxproj.pm @@ -76,7 +76,7 @@ sub createProject { my $libs_release = "\n "; my $libs_debug = "\n "; - if (!$static_library) { + if (!$static_library && $name ne 'headless-git') { $libs_release = join(";", sort(grep /^(?!libgit\.lib|xdiff\/lib\.lib|vcs-svn\/lib\.lib|reftable\/libreftable\.lib)/, @{$$build_structure{"$prefix${name}_LIBS"}})); $libs_debug = $libs_release; $libs_debug =~ s/zlib\.lib/zlibd\.lib/g; @@ -230,7 +230,7 @@ EOM print F << "EOM"; </ItemGroup> EOM - if (!$static_library || $target =~ 'vcs-svn' || $target =~ 'xdiff') { + if ((!$static_library || $target =~ 'vcs-svn' || $target =~ 'xdiff') && !($name =~ /headless-git/)) { my $uuid_libgit = $$build_structure{"LIBS_libgit_GUID"}; my $uuid_libreftable = $$build_structure{"LIBS_reftable/libreftable_GUID"}; my $uuid_xdiff_lib = $$build_structure{"LIBS_xdiff/lib_GUID"}; diff --git a/contrib/buildsystems/engine.pl b/contrib/buildsystems/engine.pl index ed6c459..069be7e 100755 --- a/contrib/buildsystems/engine.pl +++ b/contrib/buildsystems/engine.pl @@ -371,6 +371,7 @@ sub handleLinkLine # exit(1); foreach (@objfiles) { my $sourcefile = $_; + $sourcefile =~ s/^headless-git\.o$/compat\/win32\/headless.c/; $sourcefile =~ s/\.o$/.c/; push(@sources, $sourcefile); push(@cflags, @{$compile_options{"${sourcefile}_CFLAGS"}}); diff --git a/contrib/coccinelle/.gitignore b/contrib/coccinelle/.gitignore index d3f2964..1d45c0a 100644 --- a/contrib/coccinelle/.gitignore +++ b/contrib/coccinelle/.gitignore @@ -1 +1 @@ -*.patch* +*.patch diff --git a/contrib/coccinelle/README b/contrib/coccinelle/README index f0e80bd..055ad0e 100644 --- a/contrib/coccinelle/README +++ b/contrib/coccinelle/README @@ -1,7 +1,9 @@ -This directory provides examples of Coccinelle (http://coccinelle.lip6.fr/) -semantic patches that might be useful to developers. += coccinelle -There are two types of semantic patches: +This directory provides Coccinelle (http://coccinelle.lip6.fr/) semantic patches +that might be useful to developers. + +== Types of semantic patches * Using the semantic transformation to check for bad patterns in the code; The target 'make coccicheck' is designed to check for these patterns and @@ -41,3 +43,82 @@ There are two types of semantic patches: This allows to expose plans of pending large scale refactorings without impacting the bad pattern checks. + +== Git-specific tips & things to know about how we run "spatch": + + * The "make coccicheck" will piggy-back on + "COMPUTE_HEADER_DEPENDENCIES". If you've built a given object file + the "coccicheck" target will consider its depednency to decide if + it needs to re-run on the corresponding source file. + + This means that a "make coccicheck" will re-compile object files + before running. This might be unexpected, but speeds up the run in + the common case, as e.g. a change to "column.h" won't require all + coccinelle rules to be re-run against "grep.c" (or another file + that happens not to use "column.h"). + + To disable this behavior use the "SPATCH_USE_O_DEPENDENCIES=NoThanks" + flag. + + * To speed up our rules the "make coccicheck" target will by default + concatenate all of the *.cocci files here into an "ALL.cocci", and + apply it to each source file. + + This makes the run faster, as we don't need to run each rule + against each source file. See the Makefile for further discussion, + this behavior can be disabled with "SPATCH_CONCAT_COCCI=". + + But since they're concatenated any <id> in the <rulname> (e.g. "@ + my_name", v.s. anonymous "@@") needs to be unique across all our + *.cocci files. You should only need to name rules if other rules + depend on them (currently only one rule is named). + + * To speed up incremental runs even more use the "spatchcache" tool + in this directory as your "SPATCH". It aimns to be a "ccache" for + coccinelle, and piggy-backs on "COMPUTE_HEADER_DEPENDENCIES". + + It caches in Redis by default, see it source for a how-to. + + In one setup with a primed cache "make coccicheck" followed by a + "make clean && make" takes around 10s to run, but 2m30s with the + default of "SPATCH_CONCAT_COCCI=Y". + + With "SPATCH_CONCAT_COCCI=" the total runtime is around ~6m, sped + up to ~1m with "spatchcache". + + Most of the 10s (or ~1m) being spent on re-running "spatch" on + files we couldn't cache, as we didn't compile them (in contrib/* + and compat/* mostly). + + The absolute times will differ for you, but the relative speedup + from caching should be on that order. + +== Authoring and reviewing coccinelle changes + +* When a .cocci is made, both the Git changes and .cocci file should be + reviewed. When reviewing such a change, do your best to understand the .cocci + changes (e.g. by asking the author to explain the change) and be explicit + about your understanding of the changes. This helps us decide whether input + from coccinelle experts is needed or not. If you aren't sure of the cocci + changes, indicate what changes you actively endorse and leave an Acked-by + (instead of Reviewed-by). + +* Authors should consider that reviewers may not be coccinelle experts, thus the + the .cocci changes may not be self-evident. A plain text description of the + changes is strongly encouraged, especially when using more esoteric features + of the language. + +* .cocci rules should target only the problem it is trying to solve; "collateral + damage" is not allowed. Reviewers should look out and flag overly-broad rules. + +* Consider the cost-benefit ratio of .cocci changes. In particular, consider the + effect on the runtime of "make coccicheck", and how often your .cocci check + will catch something valuable. As a rule of thumb, rules that can bail early + if a file doesn't have a particular token will have a small impact on runtime, + and vice-versa. + +* .cocci files used for refactoring should be temporarily kept in-tree to aid + the refactoring of out-of-tree code (e.g. in-flight topics). Periodically + evaluate the cost-benefit ratio to determine when the file should be removed. + For example, consider how many out-of-tree users are left and how much this + slows down "make coccicheck". diff --git a/contrib/coccinelle/array.cocci b/contrib/coccinelle/array.cocci index aa75937..27a3b47 100644 --- a/contrib/coccinelle/array.cocci +++ b/contrib/coccinelle/array.cocci @@ -94,3 +94,10 @@ expression n != 1; @@ - ptr = xcalloc(n, \( sizeof(*ptr) \| sizeof(T) \) ) + CALLOC_ARRAY(ptr, n) + +@@ +expression dst, src, n; +@@ +-ALLOC_ARRAY(dst, n); +-COPY_ARRAY(dst, src, n); ++DUP_ARRAY(dst, src, n); diff --git a/contrib/coccinelle/config_fn_ctx.pending.cocci b/contrib/coccinelle/config_fn_ctx.pending.cocci new file mode 100644 index 0000000..6d3d100 --- /dev/null +++ b/contrib/coccinelle/config_fn_ctx.pending.cocci @@ -0,0 +1,144 @@ +@ get_fn @ +identifier fn, R; +@@ +( +( +git_config_from_file +| +git_config_from_file_with_options +| +git_config_from_mem +| +git_config_from_blob_oid +| +read_early_config +| +read_very_early_config +| +config_with_options +| +git_config +| +git_protected_config +| +config_from_gitmodules +) + (fn, ...) +| +repo_config(R, fn, ...) +) + +@ extends get_fn @ +identifier C1, C2, D; +@@ +int fn(const char *C1, const char *C2, ++ const struct config_context *ctx, + void *D); + +@ extends get_fn @ +@@ +int fn(const char *, const char *, ++ const struct config_context *, + void *); + +@ extends get_fn @ +// Don't change fns that look like callback fns but aren't +identifier fn2 != tar_filter_config && != git_diff_heuristic_config && + != git_default_submodule_config && != git_color_config && + != bundle_list_update && != parse_object_filter_config; +identifier C1, C2, D1, D2, S; +attribute name UNUSED; +@@ +int fn(const char *C1, const char *C2, ++ const struct config_context *ctx, + void *D1) { +<+... +( +fn2(C1, C2 ++ , ctx +, D2); +| +if(fn2(C1, C2 ++ , ctx +, D2) < 0) { ... } +| +return fn2(C1, C2 ++ , ctx +, D2); +| +S = fn2(C1, C2 ++ , ctx +, D2); +) +...+> + } + +@ extends get_fn@ +identifier C1, C2, D; +attribute name UNUSED; +@@ +int fn(const char *C1, const char *C2, ++ const struct config_context *ctx UNUSED, + void *D) {...} + + +// The previous rules don't catch all callbacks, especially if they're defined +// in a separate file from the git_config() call. Fix these manually. +@@ +identifier C1, C2, D; +attribute name UNUSED; +@@ +int +( +git_ident_config +| +urlmatch_collect_fn +| +write_one_config +| +forbid_remote_url +| +credential_config_callback +) + (const char *C1, const char *C2, ++ const struct config_context *ctx UNUSED, + void *D) {...} + +@@ +identifier C1, C2, D, D2, S, fn2; +@@ +int +( +http_options +| +git_status_config +| +git_commit_config +| +git_default_core_config +| +grep_config +) + (const char *C1, const char *C2, ++ const struct config_context *ctx, + void *D) { +<+... +( +fn2(C1, C2 ++ , ctx +, D2); +| +if(fn2(C1, C2 ++ , ctx +, D2) < 0) { ... } +| +return fn2(C1, C2 ++ , ctx +, D2); +| +S = fn2(C1, C2 ++ , ctx +, D2); +) +...+> + } diff --git a/contrib/coccinelle/git_config_number.cocci b/contrib/coccinelle/git_config_number.cocci new file mode 100644 index 0000000..7b57dce --- /dev/null +++ b/contrib/coccinelle/git_config_number.cocci @@ -0,0 +1,27 @@ +@@ +identifier C1, C2, C3; +@@ +( +( +git_config_int +| +git_config_int64 +| +git_config_ulong +| +git_config_ssize_t +) + (C1, C2 ++ , ctx->kvi + ) +| +( +git_configset_get_value +| +git_config_bool_or_int +) + (C1, C2 ++ , ctx->kvi + , C3 + ) +) diff --git a/contrib/coccinelle/hashmap.cocci b/contrib/coccinelle/hashmap.cocci index d69e120..c5dbb45 100644 --- a/contrib/coccinelle/hashmap.cocci +++ b/contrib/coccinelle/hashmap.cocci @@ -1,4 +1,4 @@ -@ hashmap_entry_init_usage @ +@@ expression E; struct hashmap_entry HME; @@ diff --git a/contrib/coccinelle/index-compatibility.cocci b/contrib/coccinelle/index-compatibility.cocci new file mode 100644 index 0000000..31e36cf --- /dev/null +++ b/contrib/coccinelle/index-compatibility.cocci @@ -0,0 +1,157 @@ +// the_index.* variables +@@ +identifier AC = active_cache; +identifier AN = active_nr; +identifier ACC = active_cache_changed; +identifier ACT = active_cache_tree; +@@ +( +- AC ++ the_index.cache +| +- AN ++ the_index.cache_nr +| +- ACC ++ the_index.cache_changed +| +- ACT ++ the_index.cache_tree +) + +// "the_repository" simple cases +@@ +@@ +( +- read_cache ++ repo_read_index +| +- read_cache_unmerged ++ repo_read_index_unmerged +| +- hold_locked_index ++ repo_hold_locked_index +) + ( ++ the_repository, + ...) + +// "the_repository" special-cases +@@ +@@ +( +- read_cache_preload ++ repo_read_index_preload +) + ( ++ the_repository, + ... ++ , 0 + ) + +// "the_index" simple cases +@@ +@@ +( +- is_cache_unborn ++ is_index_unborn +| +- unmerged_cache ++ unmerged_index +| +- rename_cache_entry_at ++ rename_index_entry_at +| +- chmod_cache_entry ++ chmod_index_entry +| +- cache_file_exists ++ index_file_exists +| +- cache_name_is_other ++ index_name_is_other +| +- unmerge_cache_entry_at ++ unmerge_index_entry_at +| +- add_to_cache ++ add_to_index +| +- add_file_to_cache ++ add_file_to_index +| +- add_cache_entry ++ add_index_entry +| +- remove_file_from_cache ++ remove_file_from_index +| +- ce_match_stat ++ ie_match_stat +| +- ce_modified ++ ie_modified +| +- resolve_undo_clear ++ resolve_undo_clear_index +| +- cache_name_pos ++ index_name_pos +| +- update_main_cache_tree ++ cache_tree_update +| +- discard_cache ++ discard_index +) + ( ++ &the_index, + ...) + +@@ +@@ +( +- refresh_and_write_cache ++ repo_refresh_and_write_index +) + ( ++ the_repository, + ... ++ , NULL, NULL, NULL + ) + +// "the_index" special-cases +@@ +@@ +( +- read_cache_from ++ read_index_from +) + ( ++ &the_index, + ... ++ , get_git_dir() + ) + +@@ +@@ +( +- refresh_cache ++ refresh_index +) + ( ++ &the_index, + ... ++ , NULL, NULL, NULL + ) + +@@ +expression O; +@@ +- write_cache_as_tree ++ write_index_as_tree + ( +- O, ++ O, &the_index, get_index_file(), + ... + ) diff --git a/contrib/coccinelle/preincr.cocci b/contrib/coccinelle/preincr.cocci index 7fe1e8d..ae42cb0 100644 --- a/contrib/coccinelle/preincr.cocci +++ b/contrib/coccinelle/preincr.cocci @@ -1,4 +1,4 @@ -@ preincrement @ +@@ identifier i; @@ - ++i > 1 diff --git a/contrib/coccinelle/spatchcache b/contrib/coccinelle/spatchcache new file mode 100755 index 0000000..29e9352 --- /dev/null +++ b/contrib/coccinelle/spatchcache @@ -0,0 +1,304 @@ +#!/bin/sh +# +# spatchcache: a poor-man's "ccache"-alike for "spatch" in git.git +# +# This caching command relies on the peculiarities of the Makefile +# driving "spatch" in git.git, in particular if we invoke: +# +# make +# # See "spatchCache.cacheWhenStderr" for why "--very-quiet" is +# # used +# make coccicheck SPATCH_FLAGS=--very-quiet +# +# We can with COMPUTE_HEADER_DEPENDENCIES (auto-detected as true with +# "gcc" and "clang") write e.g. a .depend/grep.o.d for grep.c, when we +# compile grep.o. +# +# The .depend/grep.o.d will have the full header dependency tree of +# grep.c, and we can thus cache the output of "spatch" by: +# +# 1. Hashing all of those files +# 2. Hashing our source file, and the *.cocci rule we're +# applying +# 3. Running spatch, if suggests no changes (by far the common +# case) we invoke "spatchCache.getCmd" and +# "spatchCache.setCmd" with a hash SHA-256 to ask "does this +# ID have no changes" or "say that ID had no changes> +# 4. If no "spatchCache.{set,get}Cmd" is specified we'll use +# "redis-cli" and maintain a SET called "spatch-cache". Set +# appropriate redis memory policies to keep it from growing +# out of control. +# +# This along with the general incremental "make" support for +# "contrib/coccinelle" makes it viable to (re-)run coccicheck +# e.g. when merging integration branches. +# +# Note that the "--very-quiet" flag is currently critical. The cache +# will refuse to cache anything that has output on STDERR (which might +# be errors from spatch), but see spatchCache.cacheWhenStderr below. +# +# The STDERR (and exit code) could in principle be cached (as with +# ccache), but then the simple structure in the Redis cache would need +# to change, so just supply "--very-quiet" for now. +# +# To use this, simply set SPATCH to +# contrib/coccinelle/spatchcache. Then optionally set: +# +# [spatchCache] +# # Optional: path to a custom spatch +# spatch = ~/g/coccicheck/spatch.opt +# +# As well as this trace config (debug implies trace): +# +# cacheWhenStderr = true +# trace = false +# debug = false +# +# The ".depend/grep.o.d" can also be customized, as a string that will +# be eval'd, it has access to a "$dirname" and "$basename": +# +# [spatchCache] +# dependFormat = "$dirname/.depend/${basename%.c}.o.d" +# +# Setting "trace" to "true" allows for seeing when we have a cache HIT +# or MISS. To debug whether the cache is working do that, and run e.g.: +# +# redis-cli FLUSHALL +# <make && make coccicheck, as above> +# grep -hore HIT -e MISS -e SET -e NOCACHE -e CANTCACHE .build/contrib/coccinelle | sort | uniq -c +# 600 CANTCACHE +# 7365 MISS +# 7365 SET +# +# A subsequent "make cocciclean && make coccicheck" should then have +# all "HIT"'s and "CANTCACHE"'s. +# +# The "spatchCache.cacheWhenStderr" option is critical when using +# spatchCache.{trace,debug} to debug whether something is set in the +# cache, as we'll write to the spatch logs in .build/* we'd otherwise +# always emit a NOCACHE. +# +# Reading the config can make the command much slower, to work around +# this the config can be set in the environment, with environment +# variable name corresponding to the config key. "default" can be used +# to use whatever's the script default, e.g. setting +# spatchCache.cacheWhenStderr=true and deferring to the defaults for +# the rest is: +# +# export GIT_CONTRIB_SPATCHCACHE_DEBUG=default +# export GIT_CONTRIB_SPATCHCACHE_TRACE=default +# export GIT_CONTRIB_SPATCHCACHE_CACHEWHENSTDERR=true +# export GIT_CONTRIB_SPATCHCACHE_SPATCH=default +# export GIT_CONTRIB_SPATCHCACHE_DEPENDFORMAT=default +# export GIT_CONTRIB_SPATCHCACHE_SETCMD=default +# export GIT_CONTRIB_SPATCHCACHE_GETCMD=default + +set -e + +env_or_config () { + env="$1" + shift + if test "$env" = "default" + then + # Avoid expensive "git config" invocation + return + elif test -n "$env" + then + echo "$env" + else + git config $@ || : + fi +} + +## Our own configuration & options +debug=$(env_or_config "$GIT_CONTRIB_SPATCHCACHE_DEBUG" --bool "spatchCache.debug") +if test "$debug" != "true" +then + debug= +fi +if test -n "$debug" +then + set -x +fi + +trace=$(env_or_config "$GIT_CONTRIB_SPATCHCACHE_TRACE" --bool "spatchCache.trace") +if test "$trace" != "true" +then + trace= +fi +if test -n "$debug" +then + # debug implies trace + trace=true +fi + +cacheWhenStderr=$(env_or_config "$GIT_CONTRIB_SPATCHCACHE_CACHEWHENSTDERR" --bool "spatchCache.cacheWhenStderr") +if test "$cacheWhenStderr" != "true" +then + cacheWhenStderr= +fi + +trace_it () { + if test -z "$trace" + then + return + fi + echo "$@" >&2 +} + +spatch=$(env_or_config "$GIT_CONTRIB_SPATCHCACHE_SPATCH" --path "spatchCache.spatch") +if test -n "$spatch" +then + if test -n "$debug" + then + trace_it "custom spatchCache.spatch='$spatch'" + fi +else + spatch=spatch +fi + +dependFormat='$dirname/.depend/${basename%.c}.o.d' +dependFormatCfg=$(env_or_config "$GIT_CONTRIB_SPATCHCACHE_DEPENDFORMAT" "spatchCache.dependFormat") +if test -n "$dependFormatCfg" +then + dependFormat="$dependFormatCfg" +fi + +set=$(env_or_config "$GIT_CONTRIB_SPATCHCACHE_SETCMD" "spatchCache.setCmd") +get=$(env_or_config "$GIT_CONTRIB_SPATCHCACHE_GETCMD" "spatchCache.getCmd") + +## Parse spatch()-like command-line for caching info +arg_sp= +arg_file= +args="$@" +spatch_opts() { + while test $# != 0 + do + arg_file="$1" + case "$1" in + --sp-file) + arg_sp="$2" + ;; + esac + shift + done +} +spatch_opts "$@" +if ! test -f "$arg_file" +then + arg_file= +fi + +hash_for_cache() { + # Parameters that should affect the cache + echo "args=$args" + echo "config spatchCache.spatch=$spatch" + echo "config spatchCache.debug=$debug" + echo "config spatchCache.trace=$trace" + echo "config spatchCache.cacheWhenStderr=$cacheWhenStderr" + echo + + # Our target file and its dependencies + git hash-object "$1" "$2" $(grep -E -o '^[^:]+:$' "$3" | tr -d ':') +} + +# Sanity checks +if ! test -f "$arg_sp" && ! test -f "$arg_file" +then + echo $0: no idea how to cache "$@" >&2 + exit 128 +fi + +# Main logic +dirname=$(dirname "$arg_file") +basename=$(basename "$arg_file") +eval "dep=$dependFormat" + +if ! test -f "$dep" +then + trace_it "$0: CANTCACHE have no '$dep' for '$arg_file'!" + exec "$spatch" "$@" +fi + +if test -n "$debug" +then + trace_it "$0: The full cache input for '$arg_sp' '$arg_file' '$dep'" + hash_for_cache "$arg_sp" "$arg_file" "$dep" >&2 +fi +sum=$(hash_for_cache "$arg_sp" "$arg_file" "$dep" | git hash-object --stdin) + +trace_it "$0: processing '$arg_file' with '$arg_sp' rule, and got hash '$sum' for it + '$dep'" + +getret= +if test -z "$get" +then + if test $(redis-cli SISMEMBER spatch-cache "$sum") = 1 + then + getret=0 + else + getret=1 + fi +else + $set "$sum" + getret=$? +fi + +if test "$getret" = 0 +then + trace_it "$0: HIT for '$arg_file' with '$arg_sp'" + exit 0 +else + trace_it "$0: MISS: for '$arg_file' with '$arg_sp'" +fi + +out="$(mktemp)" +err="$(mktemp)" + +set +e +"$spatch" "$@" >"$out" 2>>"$err" +ret=$? +cat "$out" +cat "$err" >&2 +set -e + +nocache= +if test $ret != 0 +then + nocache="exited non-zero: $ret" +elif test -s "$out" +then + nocache="had patch output" +elif test -z "$cacheWhenStderr" && test -s "$err" +then + nocache="had stderr (use --very-quiet or spatchCache.cacheWhenStderr=true?)" +fi + +if test -n "$nocache" +then + trace_it "$0: NOCACHE ($nocache): for '$arg_file' with '$arg_sp'" + exit "$ret" +fi + +trace_it "$0: SET: for '$arg_file' with '$arg_sp'" + +setret= +if test -z "$set" +then + if test $(redis-cli SADD spatch-cache "$sum") = 1 + then + setret=0 + else + setret=1 + fi +else + "$set" "$sum" + setret=$? +fi + +if test "$setret" != 0 +then + echo "FAILED to set '$sum' in cache!" >&2 + exit 128 +fi + +exit "$ret" diff --git a/contrib/coccinelle/strbuf.cocci b/contrib/coccinelle/strbuf.cocci index 0970d98..5f06105 100644 --- a/contrib/coccinelle/strbuf.cocci +++ b/contrib/coccinelle/strbuf.cocci @@ -1,4 +1,4 @@ -@ strbuf_addf_with_format_only @ +@@ expression E; constant fmt !~ "%"; @@ diff --git a/contrib/coccinelle/swap.cocci b/contrib/coccinelle/swap.cocci index a0934d1..522177a 100644 --- a/contrib/coccinelle/swap.cocci +++ b/contrib/coccinelle/swap.cocci @@ -1,4 +1,4 @@ -@ swap_with_declaration @ +@@ type T; identifier tmp; T a, b; diff --git a/contrib/coccinelle/tests/unused.c b/contrib/coccinelle/tests/unused.c deleted file mode 100644 index 8294d73..0000000 --- a/contrib/coccinelle/tests/unused.c +++ /dev/null @@ -1,82 +0,0 @@ -void test_strbuf(void) -{ - struct strbuf sb1 = STRBUF_INIT; - struct strbuf sb2 = STRBUF_INIT; - struct strbuf sb3 = STRBUF_INIT; - struct strbuf sb4 = STRBUF_INIT; - struct strbuf sb5; - struct strbuf sb6 = { 0 }; - struct strbuf sb7 = STRBUF_INIT; - struct strbuf sb8 = STRBUF_INIT; - struct strbuf *sp1; - struct strbuf *sp2; - struct strbuf *sp3; - struct strbuf *sp4 = xmalloc(sizeof(struct strbuf)); - struct strbuf *sp5 = xmalloc(sizeof(struct strbuf)); - struct strbuf *sp6 = xmalloc(sizeof(struct strbuf)); - struct strbuf *sp7; - - strbuf_init(&sb5, 0); - strbuf_init(sp1, 0); - strbuf_init(sp2, 0); - strbuf_init(sp3, 0); - strbuf_init(sp4, 0); - strbuf_init(sp5, 0); - strbuf_init(sp6, 0); - strbuf_init(sp7, 0); - sp7 = xmalloc(sizeof(struct strbuf)); - - use_before(&sb3); - use_as_str("%s", sb7.buf); - use_as_str("%s", sp1->buf); - use_as_str("%s", sp6->buf); - pass_pp(&sp3); - - strbuf_release(&sb1); - strbuf_reset(&sb2); - strbuf_release(&sb3); - strbuf_release(&sb4); - strbuf_release(&sb5); - strbuf_release(&sb6); - strbuf_release(&sb7); - strbuf_release(sp1); - strbuf_release(sp2); - strbuf_release(sp3); - strbuf_release(sp4); - strbuf_release(sp5); - strbuf_release(sp6); - strbuf_release(sp7); - - use_after(&sb4); - - if (when_strict()) - return; - strbuf_release(&sb8); -} - -void test_other(void) -{ - struct string_list l = STRING_LIST_INIT_DUP; - struct strbuf sb = STRBUF_INIT; - - string_list_clear(&l, 0); - string_list_clear(&sb, 0); -} - -void test_worktrees(void) -{ - struct worktree **w1 = get_worktrees(); - struct worktree **w2 = get_worktrees(); - struct worktree **w3; - struct worktree **w4; - - w3 = get_worktrees(); - w4 = get_worktrees(); - - use_it(w4); - - free_worktrees(w1); - free_worktrees(w2); - free_worktrees(w3); - free_worktrees(w4); -} diff --git a/contrib/coccinelle/tests/unused.res b/contrib/coccinelle/tests/unused.res deleted file mode 100644 index 6d3e745..0000000 --- a/contrib/coccinelle/tests/unused.res +++ /dev/null @@ -1,45 +0,0 @@ -void test_strbuf(void) -{ - struct strbuf sb3 = STRBUF_INIT; - struct strbuf sb4 = STRBUF_INIT; - struct strbuf sb7 = STRBUF_INIT; - struct strbuf *sp1; - struct strbuf *sp3; - struct strbuf *sp6 = xmalloc(sizeof(struct strbuf)); - strbuf_init(sp1, 0); - strbuf_init(sp3, 0); - strbuf_init(sp6, 0); - - use_before(&sb3); - use_as_str("%s", sb7.buf); - use_as_str("%s", sp1->buf); - use_as_str("%s", sp6->buf); - pass_pp(&sp3); - - strbuf_release(&sb3); - strbuf_release(&sb4); - strbuf_release(&sb7); - strbuf_release(sp1); - strbuf_release(sp3); - strbuf_release(sp6); - - use_after(&sb4); - - if (when_strict()) - return; -} - -void test_other(void) -{ -} - -void test_worktrees(void) -{ - struct worktree **w4; - - w4 = get_worktrees(); - - use_it(w4); - - free_worktrees(w4); -} diff --git a/contrib/coccinelle/the_repository.cocci b/contrib/coccinelle/the_repository.cocci new file mode 100644 index 0000000..765ad68 --- /dev/null +++ b/contrib/coccinelle/the_repository.cocci @@ -0,0 +1,123 @@ +// Fully migrated "the_repository" additions +@@ +@@ +( +// cache.h +- get_oid ++ repo_get_oid +| +- get_oid_commit ++ repo_get_oid_commit +| +- get_oid_committish ++ repo_get_oid_committish +| +- get_oid_tree ++ repo_get_oid_tree +| +- get_oid_treeish ++ repo_get_oid_treeish +| +- get_oid_blob ++ repo_get_oid_blob +| +- get_oid_mb ++ repo_get_oid_mb +| +- find_unique_abbrev ++ repo_find_unique_abbrev +| +- find_unique_abbrev_r ++ repo_find_unique_abbrev_r +| +- for_each_abbrev ++ repo_for_each_abbrev +| +- interpret_branch_name ++ repo_interpret_branch_name +| +- peel_to_type ++ repo_peel_to_type +// commit-reach.h +| +- get_merge_bases ++ repo_get_merge_bases +| +- get_merge_bases_many ++ repo_get_merge_bases_many +| +- get_merge_bases_many_dirty ++ repo_get_merge_bases_many_dirty +| +- in_merge_bases ++ repo_in_merge_bases +| +- in_merge_bases_many ++ repo_in_merge_bases_many +// commit.h +| +- parse_commit_internal ++ repo_parse_commit_internal +| +- parse_commit ++ repo_parse_commit +| +- get_commit_buffer ++ repo_get_commit_buffer +| +- unuse_commit_buffer ++ repo_unuse_commit_buffer +| +- logmsg_reencode ++ repo_logmsg_reencode +| +- get_commit_tree ++ repo_get_commit_tree +// diff.h +| +- diff_setup ++ repo_diff_setup +// object-store.h +| +- read_object_file ++ repo_read_object_file +| +- has_object_file ++ repo_has_object_file +| +- has_object_file_with_flags ++ repo_has_object_file_with_flags +// pretty.h +| +- format_commit_message ++ repo_format_commit_message +// packfile.h +| +- approximate_object_count ++ repo_approximate_object_count +// promisor-remote.h +| +- promisor_remote_reinit ++ repo_promisor_remote_reinit +| +- promisor_remote_find ++ repo_promisor_remote_find +| +- has_promisor_remote ++ repo_has_promisor_remote +// refs.h +| +- dwim_ref ++ repo_dwim_ref +// rerere.h +| +- rerere ++ repo_rerere +// revision.h +| +- init_revisions ++ repo_init_revisions +) + ( ++ the_repository, + ...) diff --git a/contrib/coccinelle/the_repository.pending.cocci b/contrib/coccinelle/the_repository.pending.cocci deleted file mode 100644 index 072ea0d..0000000 --- a/contrib/coccinelle/the_repository.pending.cocci +++ /dev/null @@ -1,129 +0,0 @@ -// This file is used for the ongoing refactoring of -// bringing the index or repository struct in all of -// our code base. - -@@ -expression E; -expression F; -expression G; -@@ -- read_object_file( -+ repo_read_object_file(the_repository, - E, F, G) - -@@ -expression E; -@@ -- has_object_file( -+ repo_has_object_file(the_repository, - E) - -@@ -expression E; -expression F; -@@ -- has_object_file_with_flags( -+ repo_has_object_file_with_flags(the_repository, - E) - -@@ -expression E; -expression F; -expression G; -@@ -- parse_commit_internal( -+ repo_parse_commit_internal(the_repository, - E, F, G) - -@@ -expression E; -expression F; -@@ -- parse_commit_gently( -+ repo_parse_commit_gently(the_repository, - E, F) - -@@ -expression E; -@@ -- parse_commit( -+ repo_parse_commit(the_repository, - E) - -@@ -expression E; -expression F; -@@ -- get_merge_bases( -+ repo_get_merge_bases(the_repository, - E, F); - -@@ -expression E; -expression F; -expression G; -@@ -- get_merge_bases_many( -+ repo_get_merge_bases_many(the_repository, - E, F, G); - -@@ -expression E; -expression F; -expression G; -@@ -- get_merge_bases_many_dirty( -+ repo_get_merge_bases_many_dirty(the_repository, - E, F, G); - -@@ -expression E; -expression F; -@@ -- in_merge_bases( -+ repo_in_merge_bases(the_repository, - E, F); - -@@ -expression E; -expression F; -expression G; -@@ -- in_merge_bases_many( -+ repo_in_merge_bases_many(the_repository, - E, F, G); - -@@ -expression E; -expression F; -@@ -- get_commit_buffer( -+ repo_get_commit_buffer(the_repository, - E, F); - -@@ -expression E; -expression F; -@@ -- unuse_commit_buffer( -+ repo_unuse_commit_buffer(the_repository, - E, F); - -@@ -expression E; -expression F; -expression G; -@@ -- logmsg_reencode( -+ repo_logmsg_reencode(the_repository, - E, F, G); - -@@ -expression E; -expression F; -expression G; -expression H; -@@ -- format_commit_message( -+ repo_format_commit_message(the_repository, - E, F, G, H); diff --git a/contrib/coccinelle/unused.cocci b/contrib/coccinelle/unused.cocci deleted file mode 100644 index d84046f..0000000 --- a/contrib/coccinelle/unused.cocci +++ /dev/null @@ -1,43 +0,0 @@ -// This rule finds sequences of "unused" declerations and uses of a -// variable, where "unused" is defined to include only calling the -// equivalent of alloc, init & free functions on the variable. -@@ -type T; -identifier I; -// STRBUF_INIT, but also e.g. STRING_LIST_INIT_DUP (so no anchoring) -constant INIT_MACRO =~ "_INIT"; -identifier MALLOC1 =~ "^x?[mc]alloc$"; -identifier INIT_ASSIGN1 =~ "^get_worktrees$"; -identifier INIT_CALL1 =~ "^[a-z_]*_init$"; -identifier REL1 =~ "^[a-z_]*_(release|reset|clear|free)$"; -identifier REL2 =~ "^(release|clear|free)_[a-z_]*$"; -@@ - -( -- T I; -| -- T I = { 0 }; -| -- T I = INIT_MACRO; -| -- T I = MALLOC1(...); -| -- T I = INIT_ASSIGN1(...); -) - -<... when != \( I \| &I \) -( -- \( INIT_CALL1 \)( \( I \| &I \), ...); -| -- I = \( INIT_ASSIGN1 \)(...); -| -- I = MALLOC1(...); -) -...> - -( -- \( REL1 \| REL2 \)( \( I \| &I \), ...); -| -- \( REL1 \| REL2 \)( \( &I \| I \) ); -) - ... when != \( I \| &I \) diff --git a/contrib/coccinelle/xstrncmpz.cocci b/contrib/coccinelle/xstrncmpz.cocci new file mode 100644 index 0000000..ccb39e2 --- /dev/null +++ b/contrib/coccinelle/xstrncmpz.cocci @@ -0,0 +1,28 @@ +@@ +expression S, T, L; +@@ +( +- strncmp(S, T, L) || S[L] ++ !!xstrncmpz(S, T, L) +| +- strncmp(S, T, L) || S[L] != '\0' ++ !!xstrncmpz(S, T, L) +| +- strncmp(S, T, L) || T[L] ++ !!xstrncmpz(T, S, L) +| +- strncmp(S, T, L) || T[L] != '\0' ++ !!xstrncmpz(T, S, L) +| +- !strncmp(S, T, L) && !S[L] ++ !xstrncmpz(S, T, L) +| +- !strncmp(S, T, L) && S[L] == '\0' ++ !xstrncmpz(S, T, L) +| +- !strncmp(S, T, L) && !T[L] ++ !xstrncmpz(T, S, L) +| +- !strncmp(S, T, L) && T[L] == '\0' ++ !xstrncmpz(T, S, L) +) diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash index ba5c395..75193de 100644 --- a/contrib/completion/git-completion.bash +++ b/contrib/completion/git-completion.bash @@ -28,6 +28,8 @@ # completion style. For example '!f() { : git commit ; ... }; f' will # tell the completion to use commit completion. This also works with aliases # of form "!sh -c '...'". For example, "!sh -c ': git commit ; ... '". +# Note that "git" is optional --- '!f() { : commit; ...}; f' would complete +# just like the 'git commit' command. # # If you have a command that is not part of git, but you would still # like completion, you can use __git_complete: @@ -58,6 +60,12 @@ # # When set to "1" suggest all options, including options which are # typically hidden (e.g. '--allow-empty' for 'git commit'). +# +# GIT_COMPLETION_IGNORE_CASE +# +# When set, uses for-each-ref '--ignore-case' to find refs that match +# case insensitively, even on systems with case sensitive file systems +# (e.g., completing tag name "FOO" on "git checkout f<TAB>"). case "$COMP_WORDBREAKS" in *:*) : great ;; @@ -114,6 +122,40 @@ __git () ${__git_dir:+--git-dir="$__git_dir"} "$@" 2>/dev/null } +# Helper function to read the first line of a file into a variable. +# __git_eread requires 2 arguments, the file path and the name of the +# variable, in that order. +# +# This is taken from git-prompt.sh. +__git_eread () +{ + test -r "$1" && IFS=$'\r\n' read -r "$2" <"$1" +} + +# Runs git in $__git_repo_path to determine whether a pseudoref exists. +# 1: The pseudo-ref to search +__git_pseudoref_exists () +{ + local ref=$1 + local head + + __git_find_repo_path + + # If the reftable is in use, we have to shell out to 'git rev-parse' + # to determine whether the ref exists instead of looking directly in + # the filesystem to determine whether the ref exists. Otherwise, use + # Bash builtins since executing Git commands are expensive on some + # platforms. + if __git_eread "$__git_repo_path/HEAD" head; then + if [ "$head" == "ref: refs/heads/.invalid" ]; then + __git show-ref --exists "$ref" + return $? + fi + fi + + [ -f "$__git_repo_path/$ref" ] +} + # Removes backslash escaping, single quotes and double quotes from a word, # stores the result in the variable $dequoted_word. # 1: The word to dequote. @@ -412,16 +454,18 @@ fi # This function is equivalent to # -# __gitcomp "$(git xxx --git-completion-helper) ..." +# ___git_resolved_builtins=$(git xxx --git-completion-helper) # -# except that the output is cached. Accept 1-3 arguments: +# except that the result of the execution is cached. +# +# Accept 1-3 arguments: # 1: the git command to execute, this is also the cache key +# (use "_" when the command contains spaces, e.g. "remote add" +# becomes "remote_add") # 2: extra options to be added on top (e.g. negative forms) # 3: options to be excluded -__gitcomp_builtin () +__git_resolve_builtins () { - # spaces must be replaced with underscore for multi-word - # commands, e.g. "git remote add" becomes remote_add. local cmd="$1" local incl="${2-}" local excl="${3-}" @@ -447,7 +491,24 @@ __gitcomp_builtin () eval "$var=\"$options\"" fi - __gitcomp "$options" + ___git_resolved_builtins="$options" +} + +# This function is equivalent to +# +# __gitcomp "$(git xxx --git-completion-helper) ..." +# +# except that the output is cached. Accept 1-3 arguments: +# 1: the git command to execute, this is also the cache key +# (use "_" when the command contains spaces, e.g. "remote add" +# becomes "remote_add") +# 2: extra options to be added on top (e.g. negative forms) +# 3: options to be excluded +__gitcomp_builtin () +{ + __git_resolve_builtins "$1" "$2" "$3" + + __gitcomp "$___git_resolved_builtins" } # Variation of __gitcomp_nl () that appends to the existing list of @@ -514,6 +575,26 @@ __gitcomp_file () true } +# Find the current subcommand for commands that follow the syntax: +# +# git <command> <subcommand> +# +# 1: List of possible subcommands. +# 2: Optional subcommand to return when none is found. +__git_find_subcommand () +{ + local subcommand subcommands="$1" default_subcommand="$2" + + for subcommand in $subcommands; do + if [ "$subcommand" = "${words[__git_cmd_idx+1]}" ]; then + echo $subcommand + return + fi + done + + echo $default_subcommand +} + # Execute 'git ls-files', unless the --committable option is specified, in # which case it runs 'git diff-index' to find out the files that can be # committed. It return paths relative to the directory specified in the first @@ -646,6 +727,7 @@ __git_heads () local pfx="${1-}" cur_="${2-}" sfx="${3-}" __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \ + ${GIT_COMPLETION_IGNORE_CASE+--ignore-case} \ "refs/heads/$cur_*" "refs/heads/$cur_*/**" } @@ -659,6 +741,7 @@ __git_remote_heads () local pfx="${1-}" cur_="${2-}" sfx="${3-}" __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \ + ${GIT_COMPLETION_IGNORE_CASE+--ignore-case} \ "refs/remotes/$cur_*" "refs/remotes/$cur_*/**" } @@ -669,6 +752,7 @@ __git_tags () local pfx="${1-}" cur_="${2-}" sfx="${3-}" __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \ + ${GIT_COMPLETION_IGNORE_CASE+--ignore-case} \ "refs/tags/$cur_*" "refs/tags/$cur_*/**" } @@ -688,6 +772,7 @@ __git_dwim_remote_heads () # but only output if the branch name is unique __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \ --sort="refname:strip=3" \ + ${GIT_COMPLETION_IGNORE_CASE+--ignore-case} \ "refs/remotes/*/$cur_*" "refs/remotes/*/$cur_*/**" | \ uniq -u } @@ -712,6 +797,7 @@ __git_refs () local format refs local pfx="${3-}" cur_="${4-$cur}" sfx="${5-}" local match="${4-}" + local umatch="${4-}" local fer_pfx="${pfx//\%/%%}" # "escape" for-each-ref format specifiers __git_find_repo_path @@ -735,12 +821,19 @@ __git_refs () fi fi + if test "${GIT_COMPLETION_IGNORE_CASE:+1}" = "1" + then + # uppercase with tr instead of ${match,^^} for bash 3.2 compatibility + umatch=$(echo "$match" | tr a-z A-Z 2>/dev/null || echo "$match") + fi + if [ "$list_refs_from" = path ]; then if [[ "$cur_" == ^* ]]; then pfx="$pfx^" fer_pfx="$fer_pfx^" cur_=${cur_#^} match=${match#^} + umatch=${umatch#^} fi case "$cur_" in refs|refs/*) @@ -749,9 +842,9 @@ __git_refs () track="" ;; *) - for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD REBASE_HEAD CHERRY_PICK_HEAD; do + for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD REBASE_HEAD CHERRY_PICK_HEAD REVERT_HEAD BISECT_HEAD AUTO_MERGE; do case "$i" in - $match*) + $match*|$umatch*) if [ -e "$dir/$i" ]; then echo "$pfx$i$sfx" fi @@ -765,6 +858,7 @@ __git_refs () ;; esac __git_dir="$dir" __git for-each-ref --format="$fer_pfx%($format)$sfx" \ + ${GIT_COMPLETION_IGNORE_CASE+--ignore-case} \ "${refs[@]}" if [ -n "$track" ]; then __git_dwim_remote_heads "$pfx" "$match" "$sfx" @@ -784,15 +878,16 @@ __git_refs () *) if [ "$list_refs_from" = remote ]; then case "HEAD" in - $match*) echo "${pfx}HEAD$sfx" ;; + $match*|$umatch*) echo "${pfx}HEAD$sfx" ;; esac __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \ + ${GIT_COMPLETION_IGNORE_CASE+--ignore-case} \ "refs/remotes/$remote/$match*" \ "refs/remotes/$remote/$match*/**" else local query_symref case "HEAD" in - $match*) query_symref="HEAD" ;; + $match*|$umatch*) query_symref="HEAD" ;; esac __git ls-remote "$remote" $query_symref \ "refs/tags/$match*" "refs/heads/$match*" \ @@ -1162,7 +1257,7 @@ __git_aliased_command () :) : skip null command ;; \'*) : skip opening quote after sh -c ;; *) - cur="$word" + cur="${word%;}" break esac done @@ -1427,12 +1522,32 @@ _git_bisect () { __git_has_doubledash && return - local subcommands="start bad good skip reset visualize replay log run" - local subcommand="$(__git_find_on_cmdline "$subcommands")" + __git_find_repo_path + + # If a bisection is in progress get the terms being used. + local term_bad term_good + if [ -f "$__git_repo_path"/BISECT_TERMS ]; then + term_bad=$(__git bisect terms --term-bad) + term_good=$(__git bisect terms --term-good) + fi + + # We will complete any custom terms, but still always complete the + # more usual bad/new/good/old because git bisect gives a good error + # message if these are given when not in use, and that's better than + # silent refusal to complete if the user is confused. + # + # We want to recognize 'view' but not complete it, because it overlaps + # with 'visualize' too much and is just an alias for it. + # + local completable_subcommands="start bad new $term_bad good old $term_good terms skip reset visualize replay log run help" + local all_subcommands="$completable_subcommands view" + + local subcommand="$(__git_find_on_cmdline "$all_subcommands")" + if [ -z "$subcommand" ]; then __git_find_repo_path if [ -f "$__git_repo_path"/BISECT_START ]; then - __gitcomp "$subcommands" + __gitcomp "$completable_subcommands" else __gitcomp "replay start" fi @@ -1440,7 +1555,26 @@ _git_bisect () fi case "$subcommand" in - bad|good|reset|skip|start) + start) + case "$cur" in + --*) + __gitcomp "--first-parent --no-checkout --term-new --term-bad --term-old --term-good" + return + ;; + *) + __git_complete_refs + ;; + esac + ;; + terms) + __gitcomp "--term-good --term-old --term-bad --term-new" + return + ;; + visualize|view) + __git_complete_log_opts + return + ;; + bad|new|"$term_bad"|good|old|"$term_good"|reset|skip) __git_complete_refs ;; *) @@ -1587,7 +1721,7 @@ _git_checkout () if [ -n "$(__git_find_on_cmdline "-b -B -d --detach --orphan")" ]; then __git_complete_refs --mode="refs" - elif [ -n "$(__git_find_on_cmdline "--track")" ]; then + elif [ -n "$(__git_find_on_cmdline "-t --track")" ]; then __git_complete_refs --mode="remote-heads" else __git_complete_refs $dwim_opt --mode="refs" @@ -1602,8 +1736,7 @@ __git_cherry_pick_inprogress_options=$__git_sequencer_inprogress_options _git_cherry_pick () { - __git_find_repo_path - if [ -f "$__git_repo_path"/CHERRY_PICK_HEAD ]; then + if __git_pseudoref_exists CHERRY_PICK_HEAD; then __gitcomp "$__git_cherry_pick_inprogress_options" return fi @@ -1657,6 +1790,11 @@ _git_clone () __git_untracked_file_modes="all no normal" +__git_trailer_tokens () +{ + __git config --name-only --get-regexp '^trailer\..*\.key$' | cut -d. -f 2- | rev | cut -d. -f2- | rev +} + _git_commit () { case "$prev" in @@ -1681,6 +1819,10 @@ _git_commit () __gitcomp "$__git_untracked_file_modes" "" "${cur##--untracked-files=}" return ;; + --trailer=*) + __gitcomp_nl "$(__git_trailer_tokens)" "" "${cur##--trailer=}" ":" + return + ;; --*) __gitcomp_builtin commit return @@ -1713,32 +1855,44 @@ __git_color_moved_opts="no default plain blocks zebra dimmed-zebra" __git_color_moved_ws_opts="no ignore-space-at-eol ignore-space-change ignore-all-space allow-indentation-change" +__git_ws_error_highlight_opts="context old new all default" + +# Options for the diff machinery (diff, log, show, stash, range-diff, ...) __git_diff_common_options="--stat --numstat --shortstat --summary --patch-with-stat --name-only --name-status --color --no-color --color-words --no-renames --check --color-moved --color-moved= --no-color-moved --color-moved-ws= --no-color-moved-ws --full-index --binary --abbrev --diff-filter= + --find-copies --find-object --find-renames + --no-relative --relative --find-copies-harder --ignore-cr-at-eol --text --ignore-space-at-eol --ignore-space-change --ignore-all-space --ignore-blank-lines --exit-code - --quiet --ext-diff --no-ext-diff + --quiet --ext-diff --no-ext-diff --unified= --no-prefix --src-prefix= --dst-prefix= - --inter-hunk-context= + --inter-hunk-context= --function-context --patience --histogram --minimal --raw --word-diff --word-diff-regex= --dirstat --dirstat= --dirstat-by-file --dirstat-by-file= --cumulative - --diff-algorithm= + --diff-algorithm= --default-prefix --submodule --submodule= --ignore-submodules --indent-heuristic --no-indent-heuristic - --textconv --no-textconv - --patch --no-patch - --anchored= + --textconv --no-textconv --break-rewrites + --patch --no-patch --cc --combined-all-paths + --anchored= --compact-summary --ignore-matching-lines= + --irreversible-delete --line-prefix --no-stat + --output= --output-indicator-context= + --output-indicator-new= --output-indicator-old= + --ws-error-highlight= + --pickaxe-all --pickaxe-regex --patch-with-raw " -__git_diff_difftool_options="--cached --staged --pickaxe-all --pickaxe-regex - --base --ours --theirs --no-index --relative --merge-base +# Options for diff/difftool +__git_diff_difftool_options="--cached --staged + --base --ours --theirs --no-index --merge-base + --ita-invisible-in-index --ita-visible-in-index $__git_diff_common_options" _git_diff () @@ -1762,6 +1916,10 @@ _git_diff () __gitcomp "$__git_color_moved_ws_opts" "" "${cur##--color-moved-ws=}" return ;; + --ws-error-highlight=*) + __gitcomp "$__git_ws_error_highlight_opts" "" "${cur##--ws-error-highlight=}" + return + ;; --*) __gitcomp "$__git_diff_difftool_options" return @@ -1992,6 +2150,16 @@ __git_log_common_options=" --min-age= --until= --before= --min-parents= --max-parents= --no-min-parents --no-max-parents + --alternate-refs --ancestry-path + --author-date-order --basic-regexp + --bisect --boundary --exclude-first-parent-only + --exclude-hidden --extended-regexp + --fixed-strings --grep-reflog + --ignore-missing --left-only --perl-regexp + --reflog --regexp-ignore-case --remove-empty + --right-only --show-linear-break + --show-notes-by-default --show-pulls + --since-as-filter --single-worktree " # Options that go well for log and gitk (not shortlog) __git_log_gitk_options=" @@ -2004,17 +2172,26 @@ __git_log_shortlog_options=" --author= --committer= --grep= --all-match --invert-grep " +# Options accepted by log and show +__git_log_show_options=" + --diff-merges --diff-merges= --no-diff-merges --dd --remerge-diff + --encoding= +" + +__git_diff_merges_opts="off none on first-parent 1 separate m combined c dense-combined cc remerge r" __git_log_pretty_formats="oneline short medium full fuller reference email raw format: tformat: mboxrd" __git_log_date_formats="relative iso8601 iso8601-strict rfc2822 short local default human raw unix auto: format:" -_git_log () +# Complete porcelain (i.e. not git-rev-list) options and at least some +# option arguments accepted by git-log. Note that this same set of options +# are also accepted by some other git commands besides git-log. +__git_complete_log_opts () { - __git_has_doubledash && return - __git_find_repo_path + COMPREPLY=() local merge="" - if [ -f "$__git_repo_path/MERGE_HEAD" ]; then + if __git_pseudoref_exists MERGE_HEAD; then merge="--merge" fi case "$prev,$cur" in @@ -2052,15 +2229,24 @@ _git_log () __gitcomp "$__git_diff_submodule_formats" "" "${cur##--submodule=}" return ;; + --ws-error-highlight=*) + __gitcomp "$__git_ws_error_highlight_opts" "" "${cur##--ws-error-highlight=}" + return + ;; --no-walk=*) __gitcomp "sorted unsorted" "" "${cur##--no-walk=}" return ;; + --diff-merges=*) + __gitcomp "$__git_diff_merges_opts" "" "${cur##--diff-merges=}" + return + ;; --*) __gitcomp " $__git_log_common_options $__git_log_shortlog_options $__git_log_gitk_options + $__git_log_show_options --root --topo-order --date-order --reverse --follow --full-diff --abbrev-commit --no-abbrev-commit --abbrev= @@ -2075,9 +2261,10 @@ _git_log () --no-walk --no-walk= --do-walk --parents --children --expand-tabs --expand-tabs= --no-expand-tabs + --clear-decorations --decorate-refs= + --decorate-refs-exclude= $merge $__git_diff_common_options - --pickaxe-all --pickaxe-regex " return ;; @@ -2097,6 +2284,16 @@ _git_log () return ;; esac +} + +_git_log () +{ + __git_has_doubledash && return + __git_find_repo_path + + __git_complete_log_opts + [ ${#COMPREPLY[@]} -eq 0 ] || return + __git_complete_revlist } @@ -2313,13 +2510,30 @@ _git_rebase () _git_reflog () { - local subcommands="show delete expire" - local subcommand="$(__git_find_on_cmdline "$subcommands")" + local subcommands subcommand - if [ -z "$subcommand" ]; then - __gitcomp "$subcommands" - else - __git_complete_refs + __git_resolve_builtins "reflog" + + subcommands="$___git_resolved_builtins" + subcommand="$(__git_find_subcommand "$subcommands" "show")" + + case "$subcommand,$cur" in + show,--*) + __gitcomp " + $__git_log_common_options + " + return + ;; + $subcommand,--*) + __gitcomp_builtin "reflog_$subcommand" + return + ;; + esac + + __git_complete_refs + + if [ $((cword - __git_cmd_idx)) -eq 1 ]; then + __gitcompappend "$subcommands" "" "$cur" " " fi } @@ -2464,7 +2678,7 @@ _git_switch () if [ -n "$(__git_find_on_cmdline "-c -C -d --detach")" ]; then __git_complete_refs --mode="refs" - elif [ -n "$(__git_find_on_cmdline "--track")" ]; then + elif [ -n "$(__git_find_on_cmdline "-t --track")" ]; then __git_complete_refs --mode="remote-heads" else __git_complete_refs $dwim_opt --mode="heads" @@ -2502,6 +2716,33 @@ __git_compute_config_vars () __git_config_vars="$(git help --config-for-completion)" } +__git_config_vars_all= +__git_compute_config_vars_all () +{ + test -n "$__git_config_vars_all" || + __git_config_vars_all="$(git --no-pager help --config)" +} + +__git_compute_first_level_config_vars_for_section () +{ + local section="$1" + __git_compute_config_vars + local this_section="__git_first_level_config_vars_for_section_${section}" + test -n "${!this_section}" || + printf -v "__git_first_level_config_vars_for_section_${section}" %s \ + "$(echo "$__git_config_vars" | awk -F. "/^${section}\.[a-z]/ { print \$2 }")" +} + +__git_compute_second_level_config_vars_for_section () +{ + local section="$1" + __git_compute_config_vars_all + local this_section="__git_second_level_config_vars_for_section_${section}" + test -n "${!this_section}" || + printf -v "__git_second_level_config_vars_for_section_${section}" %s \ + "$(echo "$__git_config_vars_all" | awk -F. "/^${section}\.</ { print \$3 }")" +} + __git_config_sections= __git_compute_config_sections () { @@ -2646,73 +2887,50 @@ __git_complete_config_variable_name () done case "$cur_" in - branch.*.*) + branch.*.*|guitool.*.*|difftool.*.*|man.*.*|mergetool.*.*|remote.*.*|submodule.*.*|url.*.*) local pfx="${cur_%.*}." cur_="${cur_##*.}" - __gitcomp "remote pushRemote merge mergeOptions rebase" "$pfx" "$cur_" "$sfx" + local section="${pfx%.*.}" + __git_compute_second_level_config_vars_for_section "${section}" + local this_section="__git_second_level_config_vars_for_section_${section}" + __gitcomp "${!this_section}" "$pfx" "$cur_" "$sfx" return ;; branch.*) local pfx="${cur_%.*}." cur_="${cur_#*.}" + local section="${pfx%.}" __gitcomp_direct "$(__git_heads "$pfx" "$cur_" ".")" - __gitcomp_nl_append $'autoSetupMerge\nautoSetupRebase\n' "$pfx" "$cur_" "${sfx- }" - return - ;; - guitool.*.*) - local pfx="${cur_%.*}." - cur_="${cur_##*.}" - __gitcomp " - argPrompt cmd confirm needsFile noConsole noRescan - prompt revPrompt revUnmerged title - " "$pfx" "$cur_" "$sfx" - return - ;; - difftool.*.*) - local pfx="${cur_%.*}." - cur_="${cur_##*.}" - __gitcomp "cmd path" "$pfx" "$cur_" "$sfx" - return - ;; - man.*.*) - local pfx="${cur_%.*}." - cur_="${cur_##*.}" - __gitcomp "cmd path" "$pfx" "$cur_" "$sfx" - return - ;; - mergetool.*.*) - local pfx="${cur_%.*}." - cur_="${cur_##*.}" - __gitcomp "cmd path trustExitCode" "$pfx" "$cur_" "$sfx" + __git_compute_first_level_config_vars_for_section "${section}" + local this_section="__git_first_level_config_vars_for_section_${section}" + __gitcomp_nl_append "${!this_section}" "$pfx" "$cur_" "${sfx:- }" return ;; pager.*) local pfx="${cur_%.*}." cur_="${cur_#*.}" __git_compute_all_commands - __gitcomp_nl "$__git_all_commands" "$pfx" "$cur_" "${sfx- }" - return - ;; - remote.*.*) - local pfx="${cur_%.*}." - cur_="${cur_##*.}" - __gitcomp " - url proxy fetch push mirror skipDefaultUpdate - receivepack uploadpack tagOpt pushurl - " "$pfx" "$cur_" "$sfx" + __gitcomp_nl "$__git_all_commands" "$pfx" "$cur_" "${sfx:- }" return ;; remote.*) local pfx="${cur_%.*}." cur_="${cur_#*.}" + local section="${pfx%.}" __gitcomp_nl "$(__git_remotes)" "$pfx" "$cur_" "." - __gitcomp_nl_append "pushDefault" "$pfx" "$cur_" "${sfx- }" + __git_compute_first_level_config_vars_for_section "${section}" + local this_section="__git_first_level_config_vars_for_section_${section}" + __gitcomp_nl_append "${!this_section}" "$pfx" "$cur_" "${sfx:- }" return ;; - url.*.*) + submodule.*) local pfx="${cur_%.*}." - cur_="${cur_##*.}" - __gitcomp "insteadOf pushInsteadOf" "$pfx" "$cur_" "$sfx" + cur_="${cur_#*.}" + local section="${pfx%.}" + __gitcomp_nl "$(__git config -f "$(__git rev-parse --show-toplevel)/.gitmodules" --get-regexp 'submodule.*.path' | awk -F. '{print $2}')" "$pfx" "$cur_" "." + __git_compute_first_level_config_vars_for_section "${section}" + local this_section="__git_first_level_config_vars_for_section_${section}" + __gitcomp_nl_append "${!this_section}" "$pfx" "$cur_" "${sfx:- }" return ;; *.*) @@ -2891,7 +3109,7 @@ _git_restore () __gitcomp_builtin restore ;; *) - if __git rev-parse --verify --quiet HEAD >/dev/null; then + if __git_pseudoref_exists HEAD; then __git_complete_index_file "--modified" fi esac @@ -2901,8 +3119,7 @@ __git_revert_inprogress_options=$__git_sequencer_inprogress_options _git_revert () { - __git_find_repo_path - if [ -f "$__git_repo_path"/REVERT_HEAD ]; then + if __git_pseudoref_exists REVERT_HEAD; then __gitcomp "$__git_revert_inprogress_options" return fi @@ -2972,10 +3189,19 @@ _git_show () __gitcomp "$__git_color_moved_ws_opts" "" "${cur##--color-moved-ws=}" return ;; + --ws-error-highlight=*) + __gitcomp "$__git_ws_error_highlight_opts" "" "${cur##--ws-error-highlight=}" + return + ;; + --diff-merges=*) + __gitcomp "$__git_diff_merges_opts" "" "${cur##--diff-merges=}" + return + ;; --*) __gitcomp "--pretty= --format= --abbrev-commit --no-abbrev-commit --oneline --show-signature --expand-tabs --expand-tabs= --no-expand-tabs + $__git_log_show_options $__git_diff_common_options " return @@ -3014,12 +3240,119 @@ __gitcomp_directories () COMPREPLY+=("$c/") _found=1 fi - done < <(git ls-tree -z -d --name-only HEAD $_tmp_dir) + done < <(__git ls-tree -z -d --name-only HEAD $_tmp_dir) if [[ $_found == 0 ]] && [[ "$cur" =~ /$ ]]; then # No possible further completions any deeper, so assume we're at # a leaf directory and just consider it complete __gitcomp_direct_append "$cur " + elif [[ $_found == 0 ]]; then + # No possible completions found. Avoid falling back to + # bash's default file and directory completion, because all + # valid completions have already been searched and the + # fallbacks can do nothing but mislead. In fact, they can + # mislead in three different ways: + # 1) Fallback file completion makes no sense when asking + # for directory completions, as this function does. + # 2) Fallback directory completion is bad because + # e.g. "/pro" is invalid and should NOT complete to + # "/proc". + # 3) Fallback file/directory completion only completes + # on paths that exist in the current working tree, + # i.e. which are *already* part of their + # sparse-checkout. Thus, normal file and directory + # completion is always useless for "git + # sparse-checkout add" and is also probelmatic for + # "git sparse-checkout set" unless using it to + # strictly narrow the checkout. + COMPREPLY=( "" ) + fi +} + +# In non-cone mode, the arguments to {set,add} are supposed to be +# patterns, relative to the toplevel directory. These can be any kind +# of general pattern, like 'subdir/*.c' and we can't complete on all +# of those. However, if the user presses Tab to get tab completion, we +# presume that they are trying to provide a pattern that names a specific +# path. +__gitcomp_slash_leading_paths () +{ + local dequoted_word pfx="" cur_ toplevel + + # Since we are dealing with a sparse-checkout, subdirectories may not + # exist in the local working copy. Therefore, we want to run all + # ls-files commands relative to the repository toplevel. + toplevel="$(git rev-parse --show-toplevel)/" + + __git_dequote "$cur" + + # If the paths provided by the user already start with '/', then + # they are considered relative to the toplevel of the repository + # already. If they do not start with /, then we need to adjust + # them to start with the appropriate prefix. + case "$cur" in + /*) + cur="${cur:1}" + ;; + *) + pfx="$(__git rev-parse --show-prefix)" + esac + + # Since sparse-index is limited to cone-mode, in non-cone-mode the + # list of valid paths is precisely the cached files in the index. + # + # NEEDSWORK: + # 1) We probably need to take care of cases where ls-files + # responds with special quoting. + # 2) We probably need to take care of cases where ${cur} has + # some kind of special quoting. + # 3) On top of any quoting from 1 & 2, we have to provide an extra + # level of quoting for any paths that contain a '*', '?', '\', + # '[', ']', or leading '#' or '!' since those will be + # interpreted by sparse-checkout as something other than a + # literal path character. + # Since there are two types of quoting here, this might get really + # complex. For now, just punt on all of this... + completions="$(__git -C "${toplevel}" -c core.quotePath=false \ + ls-files --cached -- "${pfx}${cur}*" \ + | sed -e s%^%/% -e 's%$% %')" + # Note, above, though that we needed all of the completions to be + # prefixed with a '/', and we want to add a space so that bash + # completion will actually complete an entry and let us move on to + # the next one. + + # Return what we've found. + if test -n "$completions"; then + # We found some completions; return them + local IFS=$'\n' + COMPREPLY=($completions) + else + # Do NOT fall back to bash-style all-local-files-and-dirs + # when we find no match. Such options are worse than + # useless: + # 1. "git sparse-checkout add" needs paths that are NOT + # currently in the working copy. "git + # sparse-checkout set" does as well, except in the + # special cases when users are only trying to narrow + # their sparse checkout to a subset of what they + # already have. + # + # 2. A path like '.config' is ambiguous as to whether + # the user wants all '.config' files throughout the + # tree, or just the one under the current directory. + # It would result in a warning from the + # sparse-checkout command due to this. As such, all + # completions of paths should be prefixed with a + # '/'. + # + # 3. We don't want paths prefixed with a '/' to + # complete files in the system root directory, we + # want it to complete on files relative to the + # repository root. + # + # As such, make sure that NO completions are offered rather + # than falling back to bash's default completions. + COMPREPLY=( "" ) fi } @@ -3027,6 +3360,7 @@ _git_sparse_checkout () { local subcommands="list init set disable add reapply" local subcommand="$(__git_find_on_cmdline "$subcommands")" + local using_cone=true if [ -z "$subcommand" ]; then __gitcomp "$subcommands" return @@ -3037,9 +3371,18 @@ _git_sparse_checkout () __gitcomp_builtin sparse-checkout_$subcommand "" "--" ;; set,*|add,*) - if [ "$(__git config core.sparseCheckoutCone)" == "true" ] || - [ -n "$(__git_find_on_cmdline --cone)" ]; then + if [[ "$(__git config core.sparseCheckout)" == "true" && + "$(__git config core.sparseCheckoutCone)" == "false" && + -z "$(__git_find_on_cmdline --cone)" ]]; then + using_cone=false + fi + if [[ -n "$(__git_find_on_cmdline --no-cone)" ]]; then + using_cone=false + fi + if [[ "$using_cone" == "true" ]]; then __gitcomp_directories + else + __gitcomp_slash_leading_paths fi esac } @@ -3286,7 +3629,7 @@ __git_complete_worktree_paths () # Generate completion reply from worktree list skipping the first # entry: it's the path of the main worktree, which can't be moved, # removed, locked, etc. - __gitcomp_nl "$(git worktree list --porcelain | + __gitcomp_nl "$(__git worktree list --porcelain | sed -n -e '2,$ s/^worktree //p')" } @@ -3522,7 +3865,7 @@ __gitk_main () __git_find_repo_path local merge="" - if [ -f "$__git_repo_path/MERGE_HEAD" ]; then + if __git_pseudoref_exists MERGE_HEAD; then merge="--merge" fi case "$cur" in diff --git a/contrib/completion/git-prompt.sh b/contrib/completion/git-prompt.sh index 57972c2..5330e76 100644 --- a/contrib/completion/git-prompt.sh +++ b/contrib/completion/git-prompt.sh @@ -100,9 +100,7 @@ # # If you would like a colored hint about the current dirty state, set # GIT_PS1_SHOWCOLORHINTS to a nonempty value. The colors are based on -# the colored output of "git status -sb" and are available only when -# using __git_ps1 for PROMPT_COMMAND or precmd in Bash, -# but always available in Zsh. +# the colored output of "git status -sb". # # If you would like __git_ps1 to do nothing in the case when the current # directory is set up to be ignored by git, then set @@ -143,7 +141,7 @@ __git_ps1_show_upstream () # parse configuration values local option - for option in ${GIT_PS1_SHOWUPSTREAM}; do + for option in ${GIT_PS1_SHOWUPSTREAM-}; do case "$option" in git|svn) upstream_type="$option" ;; verbose) verbose=1 ;; @@ -259,12 +257,12 @@ __git_ps1_colorize_gitstring () local c_lblue='%F{blue}' local c_clear='%f' else - # Using \[ and \] around colors is necessary to prevent + # Using \001 and \002 around colors is necessary to prevent # issues with command line editing/browsing/completion! - local c_red='\[\e[31m\]' - local c_green='\[\e[32m\]' - local c_lblue='\[\e[1;34m\]' - local c_clear='\[\e[0m\]' + local c_red=$'\001\e[31m\002' + local c_green=$'\001\e[32m\002' + local c_lblue=$'\001\e[1;34m\002' + local c_clear=$'\001\e[0m\002' fi local bad_color=$c_red local ok_color=$c_green @@ -300,7 +298,7 @@ __git_ps1_colorize_gitstring () # variable, in that order. __git_eread () { - test -r "$1" && IFS=$'\r\n' read "$2" <"$1" + test -r "$1" && IFS=$'\r\n' read -r "$2" <"$1" } # see if a cherry-pick or revert is in progress, if the user has committed a @@ -410,7 +408,7 @@ __git_ps1 () local repo_info rev_parse_exit_code repo_info="$(git rev-parse --git-dir --is-inside-git-dir \ - --is-bare-repository --is-inside-work-tree \ + --is-bare-repository --is-inside-work-tree --show-ref-format \ --short HEAD 2>/dev/null)" rev_parse_exit_code="$?" @@ -423,6 +421,8 @@ __git_ps1 () short_sha="${repo_info##*$'\n'}" repo_info="${repo_info%$'\n'*}" fi + local ref_format="${repo_info##*$'\n'}" + repo_info="${repo_info%$'\n'*}" local inside_worktree="${repo_info##*$'\n'}" repo_info="${repo_info%$'\n'*}" local bare_repo="${repo_info##*$'\n'}" @@ -481,12 +481,25 @@ __git_ps1 () b="$(git symbolic-ref HEAD 2>/dev/null)" else local head="" - if ! __git_eread "$g/HEAD" head; then - return $exit - fi - # is it a symbolic ref? - b="${head#ref: }" - if [ "$head" = "$b" ]; then + + case "$ref_format" in + files) + if ! __git_eread "$g/HEAD" head; then + return $exit + fi + + if [[ $head == "ref: "* ]]; then + head="${head#ref: }" + else + head="" + fi + ;; + *) + head="$(git symbolic-ref HEAD 2>/dev/null)" + ;; + esac + + if test -z "$head"; then detached=yes b="$( case "${GIT_PS1_DESCRIBE_STYLE-}" in @@ -504,6 +517,8 @@ __git_ps1 () b="$short_sha..." b="($b)" + else + b="$head" fi fi fi @@ -513,7 +528,7 @@ __git_ps1 () fi local conflict="" # state indicator for unresolved conflicts - if [[ "${GIT_PS1_SHOWCONFLICTSTATE}" == "yes" ]] && + if [[ "${GIT_PS1_SHOWCONFLICTSTATE-}" == "yes" ]] && [[ $(git ls-files --unmerged 2>/dev/null) ]]; then conflict="|CONFLICT" fi @@ -574,11 +589,8 @@ __git_ps1 () b="\${__git_ps1_branch_name}" fi - # NO color option unless in PROMPT_COMMAND mode or it's Zsh if [ -n "${GIT_PS1_SHOWCOLORHINTS-}" ]; then - if [ $pcmode = yes ] || [ -n "${ZSH_VERSION-}" ]; then - __git_ps1_colorize_gitstring - fi + __git_ps1_colorize_gitstring fi local f="$h$w$i$s$u$p" diff --git a/contrib/coverage-diff.sh b/contrib/coverage-diff.sh index 4ec419f..6ce9603 100755 --- a/contrib/coverage-diff.sh +++ b/contrib/coverage-diff.sh @@ -74,8 +74,7 @@ do sort >uncovered_lines.txt comm -12 uncovered_lines.txt new_lines.txt | - sed -e 's/$/\)/' | - sed -e 's/^/ /' >uncovered_new_lines.txt + sed -e 's/$/\)/' -e 's/^/ /' >uncovered_new_lines.txt grep -q '[^[:space:]]' <uncovered_new_lines.txt && echo $file >>coverage-data.txt && @@ -91,11 +90,7 @@ cat coverage-data.txt echo "Commits introducing uncovered code:" -commit_list=$(cat coverage-data.txt | - grep -E '^[0-9a-f]{7,} ' | - awk '{print $1;}' | - sort | - uniq) +commit_list=$(awk '/^[0-9a-f]{7,}/ { print $1 }' coverage-data.txt | sort -u) ( for commit in $commit_list diff --git a/contrib/credential/gnome-keyring/.gitignore b/contrib/credential/gnome-keyring/.gitignore deleted file mode 100644 index 88d8fcd..0000000 --- a/contrib/credential/gnome-keyring/.gitignore +++ /dev/null @@ -1 +0,0 @@ -git-credential-gnome-keyring diff --git a/contrib/credential/gnome-keyring/Makefile b/contrib/credential/gnome-keyring/Makefile deleted file mode 100644 index 22c19df..0000000 --- a/contrib/credential/gnome-keyring/Makefile +++ /dev/null @@ -1,25 +0,0 @@ -MAIN:=git-credential-gnome-keyring -all:: $(MAIN) - -CC = gcc -RM = rm -f -CFLAGS = -g -O2 -Wall -PKG_CONFIG = pkg-config - --include ../../../config.mak.autogen --include ../../../config.mak - -INCS:=$(shell $(PKG_CONFIG) --cflags gnome-keyring-1 glib-2.0) -LIBS:=$(shell $(PKG_CONFIG) --libs gnome-keyring-1 glib-2.0) - -SRCS:=$(MAIN).c -OBJS:=$(SRCS:.c=.o) - -%.o: %.c - $(CC) $(CFLAGS) $(CPPFLAGS) $(INCS) -o $@ -c $< - -$(MAIN): $(OBJS) - $(CC) -o $@ $(LDFLAGS) $^ $(LIBS) - -clean: - @$(RM) $(MAIN) $(OBJS) diff --git a/contrib/credential/gnome-keyring/git-credential-gnome-keyring.c b/contrib/credential/gnome-keyring/git-credential-gnome-keyring.c deleted file mode 100644 index 5927e27..0000000 --- a/contrib/credential/gnome-keyring/git-credential-gnome-keyring.c +++ /dev/null @@ -1,470 +0,0 @@ -/* - * Copyright (C) 2011 John Szakmeister <john@szakmeister.net> - * 2012 Philipp A. Hartmann <pah@qo.cx> - * - * This program is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This program is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this program; if not, see <http://www.gnu.org/licenses/>. - */ - -/* - * Credits: - * - GNOME Keyring API handling originally written by John Szakmeister - * - ported to credential helper API by Philipp A. Hartmann - */ - -#include <stdio.h> -#include <string.h> -#include <stdlib.h> -#include <glib.h> -#include <gnome-keyring.h> - -#ifdef GNOME_KEYRING_DEFAULT - - /* Modern gnome-keyring */ - -#include <gnome-keyring-memory.h> - -#else - - /* - * Support ancient gnome-keyring, circ. RHEL 5.X. - * GNOME_KEYRING_DEFAULT seems to have been introduced with Gnome 2.22, - * and the other features roughly around Gnome 2.20, 6 months before. - * Ubuntu 8.04 used Gnome 2.22 (I think). Not sure any distro used 2.20. - * So the existence/non-existence of GNOME_KEYRING_DEFAULT seems like - * a decent thing to use as an indicator. - */ - -#define GNOME_KEYRING_DEFAULT NULL - -/* - * ancient gnome-keyring returns DENIED when an entry is not found. - * Setting NO_MATCH to DENIED will prevent us from reporting DENIED - * errors during get and erase operations, but we will still report - * DENIED errors during a store. - */ -#define GNOME_KEYRING_RESULT_NO_MATCH GNOME_KEYRING_RESULT_DENIED - -#define gnome_keyring_memory_alloc g_malloc -#define gnome_keyring_memory_free gnome_keyring_free_password -#define gnome_keyring_memory_strdup g_strdup - -static const char *gnome_keyring_result_to_message(GnomeKeyringResult result) -{ - switch (result) { - case GNOME_KEYRING_RESULT_OK: - return "OK"; - case GNOME_KEYRING_RESULT_DENIED: - return "Denied"; - case GNOME_KEYRING_RESULT_NO_KEYRING_DAEMON: - return "No Keyring Daemon"; - case GNOME_KEYRING_RESULT_ALREADY_UNLOCKED: - return "Already UnLocked"; - case GNOME_KEYRING_RESULT_NO_SUCH_KEYRING: - return "No Such Keyring"; - case GNOME_KEYRING_RESULT_BAD_ARGUMENTS: - return "Bad Arguments"; - case GNOME_KEYRING_RESULT_IO_ERROR: - return "IO Error"; - case GNOME_KEYRING_RESULT_CANCELLED: - return "Cancelled"; - case GNOME_KEYRING_RESULT_ALREADY_EXISTS: - return "Already Exists"; - default: - return "Unknown Error"; - } -} - -/* - * Support really ancient gnome-keyring, circ. RHEL 4.X. - * Just a guess for the Glib version. Glib 2.8 was roughly Gnome 2.12 ? - * Which was released with gnome-keyring 0.4.3 ?? - */ -#if GLIB_MAJOR_VERSION == 2 && GLIB_MINOR_VERSION < 8 - -static void gnome_keyring_done_cb(GnomeKeyringResult result, gpointer user_data) -{ - gpointer *data = (gpointer *)user_data; - int *done = (int *)data[0]; - GnomeKeyringResult *r = (GnomeKeyringResult *)data[1]; - - *r = result; - *done = 1; -} - -static void wait_for_request_completion(int *done) -{ - GMainContext *mc = g_main_context_default(); - while (!*done) - g_main_context_iteration(mc, TRUE); -} - -static GnomeKeyringResult gnome_keyring_item_delete_sync(const char *keyring, guint32 id) -{ - int done = 0; - GnomeKeyringResult result; - gpointer data[] = { &done, &result }; - - gnome_keyring_item_delete(keyring, id, gnome_keyring_done_cb, data, - NULL); - - wait_for_request_completion(&done); - - return result; -} - -#endif -#endif - -/* - * This credential struct and API is simplified from git's credential.{h,c} - */ -struct credential { - char *protocol; - char *host; - unsigned short port; - char *path; - char *username; - char *password; -}; - -#define CREDENTIAL_INIT { 0 } - -typedef int (*credential_op_cb)(struct credential *); - -struct credential_operation { - char *name; - credential_op_cb op; -}; - -#define CREDENTIAL_OP_END { NULL, NULL } - -/* ----------------- GNOME Keyring functions ----------------- */ - -/* create a special keyring option string, if path is given */ -static char *keyring_object(struct credential *c) -{ - if (!c->path) - return NULL; - - if (c->port) - return g_strdup_printf("%s:%hd/%s", c->host, c->port, c->path); - - return g_strdup_printf("%s/%s", c->host, c->path); -} - -static int keyring_get(struct credential *c) -{ - char *object = NULL; - GList *entries; - GnomeKeyringNetworkPasswordData *password_data; - GnomeKeyringResult result; - - if (!c->protocol || !(c->host || c->path)) - return EXIT_FAILURE; - - object = keyring_object(c); - - result = gnome_keyring_find_network_password_sync( - c->username, - NULL /* domain */, - c->host, - object, - c->protocol, - NULL /* authtype */, - c->port, - &entries); - - g_free(object); - - if (result == GNOME_KEYRING_RESULT_NO_MATCH) - return EXIT_SUCCESS; - - if (result == GNOME_KEYRING_RESULT_CANCELLED) - return EXIT_SUCCESS; - - if (result != GNOME_KEYRING_RESULT_OK) { - g_critical("%s", gnome_keyring_result_to_message(result)); - return EXIT_FAILURE; - } - - /* pick the first one from the list */ - password_data = (GnomeKeyringNetworkPasswordData *)entries->data; - - gnome_keyring_memory_free(c->password); - c->password = gnome_keyring_memory_strdup(password_data->password); - - if (!c->username) - c->username = g_strdup(password_data->user); - - gnome_keyring_network_password_list_free(entries); - - return EXIT_SUCCESS; -} - - -static int keyring_store(struct credential *c) -{ - guint32 item_id; - char *object = NULL; - GnomeKeyringResult result; - - /* - * Sanity check that what we are storing is actually sensible. - * In particular, we can't make a URL without a protocol field. - * Without either a host or pathname (depending on the scheme), - * we have no primary key. And without a username and password, - * we are not actually storing a credential. - */ - if (!c->protocol || !(c->host || c->path) || - !c->username || !c->password) - return EXIT_FAILURE; - - object = keyring_object(c); - - result = gnome_keyring_set_network_password_sync( - GNOME_KEYRING_DEFAULT, - c->username, - NULL /* domain */, - c->host, - object, - c->protocol, - NULL /* authtype */, - c->port, - c->password, - &item_id); - - g_free(object); - - if (result != GNOME_KEYRING_RESULT_OK && - result != GNOME_KEYRING_RESULT_CANCELLED) { - g_critical("%s", gnome_keyring_result_to_message(result)); - return EXIT_FAILURE; - } - - return EXIT_SUCCESS; -} - -static int keyring_erase(struct credential *c) -{ - char *object = NULL; - GList *entries; - GnomeKeyringNetworkPasswordData *password_data; - GnomeKeyringResult result; - - /* - * Sanity check that we actually have something to match - * against. The input we get is a restrictive pattern, - * so technically a blank credential means "erase everything". - * But it is too easy to accidentally send this, since it is equivalent - * to empty input. So explicitly disallow it, and require that the - * pattern have some actual content to match. - */ - if (!c->protocol && !c->host && !c->path && !c->username) - return EXIT_FAILURE; - - object = keyring_object(c); - - result = gnome_keyring_find_network_password_sync( - c->username, - NULL /* domain */, - c->host, - object, - c->protocol, - NULL /* authtype */, - c->port, - &entries); - - g_free(object); - - if (result == GNOME_KEYRING_RESULT_NO_MATCH) - return EXIT_SUCCESS; - - if (result == GNOME_KEYRING_RESULT_CANCELLED) - return EXIT_SUCCESS; - - if (result != GNOME_KEYRING_RESULT_OK) { - g_critical("%s", gnome_keyring_result_to_message(result)); - return EXIT_FAILURE; - } - - /* pick the first one from the list (delete all matches?) */ - password_data = (GnomeKeyringNetworkPasswordData *)entries->data; - - result = gnome_keyring_item_delete_sync( - password_data->keyring, password_data->item_id); - - gnome_keyring_network_password_list_free(entries); - - if (result != GNOME_KEYRING_RESULT_OK) { - g_critical("%s", gnome_keyring_result_to_message(result)); - return EXIT_FAILURE; - } - - return EXIT_SUCCESS; -} - -/* - * Table with helper operation callbacks, used by generic - * credential helper main function. - */ -static struct credential_operation const credential_helper_ops[] = { - { "get", keyring_get }, - { "store", keyring_store }, - { "erase", keyring_erase }, - CREDENTIAL_OP_END -}; - -/* ------------------ credential functions ------------------ */ - -static void credential_init(struct credential *c) -{ - memset(c, 0, sizeof(*c)); -} - -static void credential_clear(struct credential *c) -{ - g_free(c->protocol); - g_free(c->host); - g_free(c->path); - g_free(c->username); - gnome_keyring_memory_free(c->password); - - credential_init(c); -} - -static int credential_read(struct credential *c) -{ - char *buf; - size_t line_len; - char *key; - char *value; - - key = buf = gnome_keyring_memory_alloc(1024); - - while (fgets(buf, 1024, stdin)) { - line_len = strlen(buf); - - if (line_len && buf[line_len-1] == '\n') - buf[--line_len] = '\0'; - - if (!line_len) - break; - - value = strchr(buf, '='); - if (!value) { - g_warning("invalid credential line: %s", key); - gnome_keyring_memory_free(buf); - return -1; - } - *value++ = '\0'; - - if (!strcmp(key, "protocol")) { - g_free(c->protocol); - c->protocol = g_strdup(value); - } else if (!strcmp(key, "host")) { - g_free(c->host); - c->host = g_strdup(value); - value = strrchr(c->host, ':'); - if (value) { - *value++ = '\0'; - c->port = atoi(value); - } - } else if (!strcmp(key, "path")) { - g_free(c->path); - c->path = g_strdup(value); - } else if (!strcmp(key, "username")) { - g_free(c->username); - c->username = g_strdup(value); - } else if (!strcmp(key, "password")) { - gnome_keyring_memory_free(c->password); - c->password = gnome_keyring_memory_strdup(value); - while (*value) - *value++ = '\0'; - } - /* - * Ignore other lines; we don't know what they mean, but - * this future-proofs us when later versions of git do - * learn new lines, and the helpers are updated to match. - */ - } - - gnome_keyring_memory_free(buf); - - return 0; -} - -static void credential_write_item(FILE *fp, const char *key, const char *value) -{ - if (!value) - return; - fprintf(fp, "%s=%s\n", key, value); -} - -static void credential_write(const struct credential *c) -{ - /* only write username/password, if set */ - credential_write_item(stdout, "username", c->username); - credential_write_item(stdout, "password", c->password); -} - -static void usage(const char *name) -{ - struct credential_operation const *try_op = credential_helper_ops; - const char *basename = strrchr(name, '/'); - - basename = (basename) ? basename + 1 : name; - fprintf(stderr, "usage: %s <", basename); - while (try_op->name) { - fprintf(stderr, "%s", (try_op++)->name); - if (try_op->name) - fprintf(stderr, "%s", "|"); - } - fprintf(stderr, "%s", ">\n"); -} - -int main(int argc, char *argv[]) -{ - int ret = EXIT_SUCCESS; - - struct credential_operation const *try_op = credential_helper_ops; - struct credential cred = CREDENTIAL_INIT; - - if (!argv[1]) { - usage(argv[0]); - exit(EXIT_FAILURE); - } - - g_set_application_name("Git Credential Helper"); - - /* lookup operation callback */ - while (try_op->name && strcmp(argv[1], try_op->name)) - try_op++; - - /* unsupported operation given -- ignore silently */ - if (!try_op->name || !try_op->op) - goto out; - - ret = credential_read(&cred); - if (ret) - goto out; - - /* perform credential operation */ - ret = (*try_op->op)(&cred); - - credential_write(&cred); - -out: - credential_clear(&cred); - return ret; -} diff --git a/contrib/credential/libsecret/.gitignore b/contrib/credential/libsecret/.gitignore new file mode 100644 index 0000000..4fa2235 --- /dev/null +++ b/contrib/credential/libsecret/.gitignore @@ -0,0 +1 @@ +git-credential-libsecret diff --git a/contrib/credential/libsecret/git-credential-libsecret.c b/contrib/credential/libsecret/git-credential-libsecret.c index 2c5d76d..90034d0 100644 --- a/contrib/credential/libsecret/git-credential-libsecret.c +++ b/contrib/credential/libsecret/git-credential-libsecret.c @@ -39,6 +39,8 @@ struct credential { char *path; char *username; char *password; + char *password_expiry_utc; + char *oauth_refresh_token; }; #define CREDENTIAL_INIT { 0 } @@ -52,8 +54,29 @@ struct credential_operation { #define CREDENTIAL_OP_END { NULL, NULL } +static void credential_clear(struct credential *c); + /* ----------------- Secret Service functions ----------------- */ +static const SecretSchema schema = { + "org.git.Password", + /* Ignore schema name during search for backwards compatibility */ + SECRET_SCHEMA_DONT_MATCH_NAME, + { + /* + * libsecret assumes attribute values are non-confidential and + * unchanging, so we can't include oauth_refresh_token or + * password_expiry_utc. + */ + { "user", SECRET_SCHEMA_ATTRIBUTE_STRING }, + { "object", SECRET_SCHEMA_ATTRIBUTE_STRING }, + { "protocol", SECRET_SCHEMA_ATTRIBUTE_STRING }, + { "port", SECRET_SCHEMA_ATTRIBUTE_INTEGER }, + { "server", SECRET_SCHEMA_ATTRIBUTE_STRING }, + { NULL, 0 }, + } +}; + static char *make_label(struct credential *c) { if (c->port) @@ -101,7 +124,7 @@ static int keyring_get(struct credential *c) attributes = make_attr_list(c); items = secret_service_search_sync(service, - SECRET_SCHEMA_COMPAT_NETWORK, + &schema, attributes, SECRET_SEARCH_LOAD_SECRETS | SECRET_SEARCH_UNLOCK, NULL, @@ -117,6 +140,7 @@ static int keyring_get(struct credential *c) SecretItem *item; SecretValue *secret; const char *s; + gchar **parts; item = items->data; secret = secret_item_get_secret(item); @@ -130,8 +154,30 @@ static int keyring_get(struct credential *c) s = secret_value_get_text(secret); if (s) { - g_free(c->password); - c->password = g_strdup(s); + /* + * Passwords and other attributes encoded in following format: + * hunter2 + * password_expiry_utc=1684189401 + * oauth_refresh_token=xyzzy + */ + parts = g_strsplit(s, "\n", 0); + if (g_strv_length(parts) >= 1) { + g_free(c->password); + c->password = g_strdup(parts[0]); + } else { + g_free(c->password); + c->password = g_strdup(""); + } + for (int i = 1; i < g_strv_length(parts); i++) { + if (g_str_has_prefix(parts[i], "password_expiry_utc=")) { + g_free(c->password_expiry_utc); + c->password_expiry_utc = g_strdup(&parts[i][20]); + } else if (g_str_has_prefix(parts[i], "oauth_refresh_token=")) { + g_free(c->oauth_refresh_token); + c->oauth_refresh_token = g_strdup(&parts[i][20]); + } + } + g_strfreev(parts); } g_hash_table_unref(attributes); @@ -148,6 +194,7 @@ static int keyring_store(struct credential *c) char *label = NULL; GHashTable *attributes = NULL; GError *error = NULL; + GString *secret = NULL; /* * Sanity check that what we are storing is actually sensible. @@ -162,13 +209,23 @@ static int keyring_store(struct credential *c) label = make_label(c); attributes = make_attr_list(c); - secret_password_storev_sync(SECRET_SCHEMA_COMPAT_NETWORK, + secret = g_string_new(c->password); + if (c->password_expiry_utc) { + g_string_append_printf(secret, "\npassword_expiry_utc=%s", + c->password_expiry_utc); + } + if (c->oauth_refresh_token) { + g_string_append_printf(secret, "\noauth_refresh_token=%s", + c->oauth_refresh_token); + } + secret_password_storev_sync(&schema, attributes, NULL, label, - c->password, + secret->str, NULL, &error); + g_string_free(secret, TRUE); g_free(label); g_hash_table_unref(attributes); @@ -185,6 +242,7 @@ static int keyring_erase(struct credential *c) { GHashTable *attributes = NULL; GError *error = NULL; + struct credential existing = CREDENTIAL_INIT; /* * Sanity check that we actually have something to match @@ -197,8 +255,22 @@ static int keyring_erase(struct credential *c) if (!c->protocol && !c->host && !c->path && !c->username) return EXIT_FAILURE; + if (c->password) { + existing.host = g_strdup(c->host); + existing.path = g_strdup(c->path); + existing.port = c->port; + existing.protocol = g_strdup(c->protocol); + existing.username = g_strdup(c->username); + keyring_get(&existing); + if (existing.password && strcmp(c->password, existing.password)) { + credential_clear(&existing); + return EXIT_SUCCESS; + } + credential_clear(&existing); + } + attributes = make_attr_list(c); - secret_password_clearv_sync(SECRET_SCHEMA_COMPAT_NETWORK, + secret_password_clearv_sync(&schema, attributes, NULL, &error); @@ -238,23 +310,24 @@ static void credential_clear(struct credential *c) g_free(c->path); g_free(c->username); g_free(c->password); + g_free(c->password_expiry_utc); + g_free(c->oauth_refresh_token); credential_init(c); } static int credential_read(struct credential *c) { - char *buf; - size_t line_len; + char *buf = NULL; + size_t alloc; + ssize_t line_len; char *key; char *value; - key = buf = g_malloc(1024); - - while (fgets(buf, 1024, stdin)) { - line_len = strlen(buf); + while ((line_len = getline(&buf, &alloc, stdin)) > 0) { + key = buf; - if (line_len && buf[line_len-1] == '\n') + if (buf[line_len-1] == '\n') buf[--line_len] = '\0'; if (!line_len) @@ -285,11 +358,19 @@ static int credential_read(struct credential *c) } else if (!strcmp(key, "username")) { g_free(c->username); c->username = g_strdup(value); + } else if (!strcmp(key, "password_expiry_utc")) { + g_free(c->password_expiry_utc); + c->password_expiry_utc = g_strdup(value); } else if (!strcmp(key, "password")) { g_free(c->password); c->password = g_strdup(value); while (*value) *value++ = '\0'; + } else if (!strcmp(key, "oauth_refresh_token")) { + g_free(c->oauth_refresh_token); + c->oauth_refresh_token = g_strdup(value); + while (*value) + *value++ = '\0'; } /* * Ignore other lines; we don't know what they mean, but @@ -298,7 +379,7 @@ static int credential_read(struct credential *c) */ } - g_free(buf); + free(buf); return 0; } @@ -315,6 +396,10 @@ static void credential_write(const struct credential *c) /* only write username/password, if set */ credential_write_item(stdout, "username", c->username); credential_write_item(stdout, "password", c->password); + credential_write_item(stdout, "password_expiry_utc", + c->password_expiry_utc); + credential_write_item(stdout, "oauth_refresh_token", + c->oauth_refresh_token); } static void usage(const char *name) diff --git a/contrib/credential/netrc/git-credential-netrc.perl b/contrib/credential/netrc/git-credential-netrc.perl index bc57cc6..9fb998a 100755 --- a/contrib/credential/netrc/git-credential-netrc.perl +++ b/contrib/credential/netrc/git-credential-netrc.perl @@ -356,7 +356,10 @@ sub read_credential_data_from_stdin { next unless m/^([^=]+)=(.+)/; my ($token, $value) = ($1, $2); - die "Unknown search token $token" unless exists $q{$token}; + + # skip any unknown tokens + next unless exists $q{$token}; + $q{$token} = $value; log_debug("We were given search token $token and value $value"); } diff --git a/contrib/credential/osxkeychain/Makefile b/contrib/credential/osxkeychain/Makefile index 4b3a08a..238f5f8 100644 --- a/contrib/credential/osxkeychain/Makefile +++ b/contrib/credential/osxkeychain/Makefile @@ -8,7 +8,8 @@ CFLAGS = -g -O2 -Wall -include ../../../config.mak git-credential-osxkeychain: git-credential-osxkeychain.o - $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS) -Wl,-framework -Wl,Security + $(CC) $(CFLAGS) -o $@ $< $(LDFLAGS) \ + -framework Security -framework CoreFoundation git-credential-osxkeychain.o: git-credential-osxkeychain.c $(CC) -c $(CFLAGS) $< diff --git a/contrib/credential/osxkeychain/git-credential-osxkeychain.c b/contrib/credential/osxkeychain/git-credential-osxkeychain.c index bf77748..6a40917 100644 --- a/contrib/credential/osxkeychain/git-credential-osxkeychain.c +++ b/contrib/credential/osxkeychain/git-credential-osxkeychain.c @@ -3,14 +3,51 @@ #include <stdlib.h> #include <Security/Security.h> -static SecProtocolType protocol; -static char *host; -static char *path; -static char *username; -static char *password; -static UInt16 port; - -__attribute__((format (printf, 1, 2))) +#define ENCODING kCFStringEncodingUTF8 +static CFStringRef protocol; /* Stores constant strings - not memory managed */ +static CFStringRef host; +static CFNumberRef port; +static CFStringRef path; +static CFStringRef username; +static CFDataRef password; +static CFDataRef password_expiry_utc; +static CFDataRef oauth_refresh_token; + +static void clear_credential(void) +{ + if (host) { + CFRelease(host); + host = NULL; + } + if (port) { + CFRelease(port); + port = NULL; + } + if (path) { + CFRelease(path); + path = NULL; + } + if (username) { + CFRelease(username); + username = NULL; + } + if (password) { + CFRelease(password); + password = NULL; + } + if (password_expiry_utc) { + CFRelease(password_expiry_utc); + password_expiry_utc = NULL; + } + if (oauth_refresh_token) { + CFRelease(oauth_refresh_token); + oauth_refresh_token = NULL; + } +} + +#define STRING_WITH_LENGTH(s) s, sizeof(s) - 1 + +__attribute__((format (printf, 1, 2), __noreturn__)) static void die(const char *err, ...) { char msg[4096]; @@ -19,70 +56,199 @@ static void die(const char *err, ...) vsnprintf(msg, sizeof(msg), err, params); fprintf(stderr, "%s\n", msg); va_end(params); + clear_credential(); exit(1); } -static void *xstrdup(const char *s1) +static void *xmalloc(size_t len) { - void *ret = strdup(s1); + void *ret = malloc(len); if (!ret) die("Out of memory"); return ret; } -#define KEYCHAIN_ITEM(x) (x ? strlen(x) : 0), x -#define KEYCHAIN_ARGS \ - NULL, /* default keychain */ \ - KEYCHAIN_ITEM(host), \ - 0, NULL, /* account domain */ \ - KEYCHAIN_ITEM(username), \ - KEYCHAIN_ITEM(path), \ - port, \ - protocol, \ - kSecAuthenticationTypeDefault - -static void write_item(const char *what, const char *buf, int len) +static CFDictionaryRef create_dictionary(CFAllocatorRef allocator, ...) +{ + va_list args; + const void *key; + CFMutableDictionaryRef result; + + result = CFDictionaryCreateMutable(allocator, + 0, + &kCFTypeDictionaryKeyCallBacks, + &kCFTypeDictionaryValueCallBacks); + + + va_start(args, allocator); + while ((key = va_arg(args, const void *)) != NULL) { + const void *value; + value = va_arg(args, const void *); + if (value) + CFDictionarySetValue(result, key, value); + } + va_end(args); + + return result; +} + +#define CREATE_SEC_ATTRIBUTES(...) \ + create_dictionary(kCFAllocatorDefault, \ + kSecClass, kSecClassInternetPassword, \ + kSecAttrServer, host, \ + kSecAttrAccount, username, \ + kSecAttrPath, path, \ + kSecAttrPort, port, \ + kSecAttrProtocol, protocol, \ + kSecAttrAuthenticationType, \ + kSecAttrAuthenticationTypeDefault, \ + __VA_ARGS__); + +static void write_item(const char *what, const char *buf, size_t len) { printf("%s=", what); fwrite(buf, 1, len, stdout); putchar('\n'); } -static void find_username_in_item(SecKeychainItemRef item) +static void find_username_in_item(CFDictionaryRef item) { - SecKeychainAttributeList list; - SecKeychainAttribute attr; + CFStringRef account_ref; + char *username_buf; + CFIndex buffer_len; - list.count = 1; - list.attr = &attr; - attr.tag = kSecAccountItemAttr; + account_ref = CFDictionaryGetValue(item, kSecAttrAccount); + if (!account_ref) + { + write_item("username", "", 0); + return; + } - if (SecKeychainItemCopyContent(item, NULL, &list, NULL, NULL)) + username_buf = (char *)CFStringGetCStringPtr(account_ref, ENCODING); + if (username_buf) + { + write_item("username", username_buf, strlen(username_buf)); return; + } - write_item("username", attr.data, attr.length); - SecKeychainItemFreeContent(&list, NULL); + /* If we can't get a CString pointer then + * we need to allocate our own buffer */ + buffer_len = CFStringGetMaximumSizeForEncoding( + CFStringGetLength(account_ref), ENCODING) + 1; + username_buf = xmalloc(buffer_len); + if (CFStringGetCString(account_ref, + username_buf, + buffer_len, + ENCODING)) { + write_item("username", username_buf, buffer_len - 1); + } + free(username_buf); } -static void find_internet_password(void) +static OSStatus find_internet_password(void) { - void *buf; - UInt32 len; - SecKeychainItemRef item; + CFDictionaryRef attrs; + CFDictionaryRef item; + CFDataRef data; + OSStatus result; - if (SecKeychainFindInternetPassword(KEYCHAIN_ARGS, &len, &buf, &item)) - return; + attrs = CREATE_SEC_ATTRIBUTES(kSecMatchLimit, kSecMatchLimitOne, + kSecReturnAttributes, kCFBooleanTrue, + kSecReturnData, kCFBooleanTrue, + NULL); + result = SecItemCopyMatching(attrs, (CFTypeRef *)&item); + if (result) { + goto out; + } - write_item("password", buf, len); + data = CFDictionaryGetValue(item, kSecValueData); + + write_item("password", + (const char *)CFDataGetBytePtr(data), + CFDataGetLength(data)); if (!username) find_username_in_item(item); - SecKeychainItemFreeContent(NULL, buf); + CFRelease(item); + +out: + CFRelease(attrs); + + /* We consider not found to not be an error */ + if (result == errSecItemNotFound) + result = errSecSuccess; + + return result; } -static void delete_internet_password(void) +static OSStatus delete_ref(const void *itemRef) { - SecKeychainItemRef item; + CFArrayRef item_ref_list; + CFDictionaryRef delete_query; + OSStatus result; + + item_ref_list = CFArrayCreate(kCFAllocatorDefault, + &itemRef, + 1, + &kCFTypeArrayCallBacks); + delete_query = create_dictionary(kCFAllocatorDefault, + kSecClass, kSecClassInternetPassword, + kSecMatchItemList, item_ref_list, + NULL); + + if (password) { + /* We only want to delete items with a matching password */ + CFIndex capacity; + CFMutableDictionaryRef query; + CFDataRef data; + + capacity = CFDictionaryGetCount(delete_query) + 1; + query = CFDictionaryCreateMutableCopy(kCFAllocatorDefault, + capacity, + delete_query); + CFDictionarySetValue(query, kSecReturnData, kCFBooleanTrue); + result = SecItemCopyMatching(query, (CFTypeRef *)&data); + if (!result) { + CFDataRef kc_password; + const UInt8 *raw_data; + const UInt8 *line; + + /* Don't match appended metadata */ + raw_data = CFDataGetBytePtr(data); + line = memchr(raw_data, '\n', CFDataGetLength(data)); + if (line) + kc_password = CFDataCreateWithBytesNoCopy( + kCFAllocatorDefault, + raw_data, + line - raw_data, + kCFAllocatorNull); + else + kc_password = data; + + if (CFEqual(kc_password, password)) + result = SecItemDelete(delete_query); + + if (line) + CFRelease(kc_password); + CFRelease(data); + } + + CFRelease(query); + } else { + result = SecItemDelete(delete_query); + } + + CFRelease(delete_query); + CFRelease(item_ref_list); + + return result; +} + +static OSStatus delete_internet_password(void) +{ + CFDictionaryRef attrs; + CFArrayRef refs; + OSStatus result; /* * Require at least a protocol and host for removal, which is what git @@ -90,37 +256,83 @@ static void delete_internet_password(void) * Keychain manager. */ if (!protocol || !host) - return; + return -1; - if (SecKeychainFindInternetPassword(KEYCHAIN_ARGS, 0, NULL, &item)) - return; + attrs = CREATE_SEC_ATTRIBUTES(kSecMatchLimit, kSecMatchLimitAll, + kSecReturnRef, kCFBooleanTrue, + NULL); + result = SecItemCopyMatching(attrs, (CFTypeRef *)&refs); + CFRelease(attrs); + + if (!result) { + for (CFIndex i = 0; !result && i < CFArrayGetCount(refs); i++) + result = delete_ref(CFArrayGetValueAtIndex(refs, i)); + + CFRelease(refs); + } + + /* We consider not found to not be an error */ + if (result == errSecItemNotFound) + result = errSecSuccess; - SecKeychainItemDelete(item); + return result; } -static void add_internet_password(void) +static OSStatus add_internet_password(void) { + CFMutableDataRef data; + CFDictionaryRef attrs; + OSStatus result; + /* Only store complete credentials */ if (!protocol || !host || !username || !password) - return; + return -1; - if (SecKeychainAddInternetPassword( - KEYCHAIN_ARGS, - KEYCHAIN_ITEM(password), - NULL)) - return; + data = CFDataCreateMutableCopy(kCFAllocatorDefault, 0, password); + if (password_expiry_utc) { + CFDataAppendBytes(data, + (const UInt8 *)STRING_WITH_LENGTH("\npassword_expiry_utc=")); + CFDataAppendBytes(data, + CFDataGetBytePtr(password_expiry_utc), + CFDataGetLength(password_expiry_utc)); + } + if (oauth_refresh_token) { + CFDataAppendBytes(data, + (const UInt8 *)STRING_WITH_LENGTH("\noauth_refresh_token=")); + CFDataAppendBytes(data, + CFDataGetBytePtr(oauth_refresh_token), + CFDataGetLength(oauth_refresh_token)); + } + + attrs = CREATE_SEC_ATTRIBUTES(kSecValueData, data, + NULL); + + result = SecItemAdd(attrs, NULL); + if (result == errSecDuplicateItem) { + CFDictionaryRef query; + query = CREATE_SEC_ATTRIBUTES(NULL); + result = SecItemUpdate(query, attrs); + CFRelease(query); + } + + CFRelease(data); + CFRelease(attrs); + + return result; } static void read_credential(void) { - char buf[1024]; + char *buf = NULL; + size_t alloc; + ssize_t line_len; - while (fgets(buf, sizeof(buf), stdin)) { + while ((line_len = getline(&buf, &alloc, stdin)) > 0) { char *v; if (!strcmp(buf, "\n")) break; - buf[strlen(buf)-1] = '\0'; + buf[line_len-1] = '\0'; v = strchr(buf, '='); if (!v) @@ -129,41 +341,73 @@ static void read_credential(void) if (!strcmp(buf, "protocol")) { if (!strcmp(v, "imap")) - protocol = kSecProtocolTypeIMAP; + protocol = kSecAttrProtocolIMAP; else if (!strcmp(v, "imaps")) - protocol = kSecProtocolTypeIMAPS; + protocol = kSecAttrProtocolIMAPS; else if (!strcmp(v, "ftp")) - protocol = kSecProtocolTypeFTP; + protocol = kSecAttrProtocolFTP; else if (!strcmp(v, "ftps")) - protocol = kSecProtocolTypeFTPS; + protocol = kSecAttrProtocolFTPS; else if (!strcmp(v, "https")) - protocol = kSecProtocolTypeHTTPS; + protocol = kSecAttrProtocolHTTPS; else if (!strcmp(v, "http")) - protocol = kSecProtocolTypeHTTP; + protocol = kSecAttrProtocolHTTP; else if (!strcmp(v, "smtp")) - protocol = kSecProtocolTypeSMTP; - else /* we don't yet handle other protocols */ + protocol = kSecAttrProtocolSMTP; + else { + /* we don't yet handle other protocols */ + clear_credential(); exit(0); + } } else if (!strcmp(buf, "host")) { char *colon = strchr(v, ':'); if (colon) { + UInt16 port_i; *colon++ = '\0'; - port = atoi(colon); + port_i = atoi(colon); + port = CFNumberCreate(kCFAllocatorDefault, + kCFNumberShortType, + &port_i); } - host = xstrdup(v); + host = CFStringCreateWithCString(kCFAllocatorDefault, + v, + ENCODING); } else if (!strcmp(buf, "path")) - path = xstrdup(v); + path = CFStringCreateWithCString(kCFAllocatorDefault, + v, + ENCODING); else if (!strcmp(buf, "username")) - username = xstrdup(v); + username = CFStringCreateWithCString( + kCFAllocatorDefault, + v, + ENCODING); else if (!strcmp(buf, "password")) - password = xstrdup(v); + password = CFDataCreate(kCFAllocatorDefault, + (UInt8 *)v, + strlen(v)); + else if (!strcmp(buf, "password_expiry_utc")) + password_expiry_utc = CFDataCreate(kCFAllocatorDefault, + (UInt8 *)v, + strlen(v)); + else if (!strcmp(buf, "oauth_refresh_token")) + oauth_refresh_token = CFDataCreate(kCFAllocatorDefault, + (UInt8 *)v, + strlen(v)); + /* + * Ignore other lines; we don't know what they mean, but + * this future-proofs us when later versions of git do + * learn new lines, and the helpers are updated to match. + */ } + + free(buf); } int main(int argc, const char **argv) { + OSStatus result = 0; const char *usage = "usage: git credential-osxkeychain <get|store|erase>"; @@ -173,12 +417,17 @@ int main(int argc, const char **argv) read_credential(); if (!strcmp(argv[1], "get")) - find_internet_password(); + result = find_internet_password(); else if (!strcmp(argv[1], "store")) - add_internet_password(); + result = add_internet_password(); else if (!strcmp(argv[1], "erase")) - delete_internet_password(); + result = delete_internet_password(); /* otherwise, ignore unknown action */ + if (result) + die("failed to %s: %d", argv[1], (int)result); + + clear_credential(); + return 0; } diff --git a/contrib/credential/wincred/git-credential-wincred.c b/contrib/credential/wincred/git-credential-wincred.c index 5091048..4be0d58 100644 --- a/contrib/credential/wincred/git-credential-wincred.c +++ b/contrib/credential/wincred/git-credential-wincred.c @@ -6,6 +6,7 @@ #include <stdio.h> #include <io.h> #include <fcntl.h> +#include <wincred.h> /* common helpers */ @@ -33,65 +34,8 @@ static void *xmalloc(size_t size) return ret; } -/* MinGW doesn't have wincred.h, so we need to define stuff */ - -typedef struct _CREDENTIAL_ATTRIBUTEW { - LPWSTR Keyword; - DWORD Flags; - DWORD ValueSize; - LPBYTE Value; -} CREDENTIAL_ATTRIBUTEW, *PCREDENTIAL_ATTRIBUTEW; - -typedef struct _CREDENTIALW { - DWORD Flags; - DWORD Type; - LPWSTR TargetName; - LPWSTR Comment; - FILETIME LastWritten; - DWORD CredentialBlobSize; - LPBYTE CredentialBlob; - DWORD Persist; - DWORD AttributeCount; - PCREDENTIAL_ATTRIBUTEW Attributes; - LPWSTR TargetAlias; - LPWSTR UserName; -} CREDENTIALW, *PCREDENTIALW; - -#define CRED_TYPE_GENERIC 1 -#define CRED_PERSIST_LOCAL_MACHINE 2 -#define CRED_MAX_ATTRIBUTES 64 - -typedef BOOL (WINAPI *CredWriteWT)(PCREDENTIALW, DWORD); -typedef BOOL (WINAPI *CredEnumerateWT)(LPCWSTR, DWORD, DWORD *, - PCREDENTIALW **); -typedef VOID (WINAPI *CredFreeT)(PVOID); -typedef BOOL (WINAPI *CredDeleteWT)(LPCWSTR, DWORD, DWORD); - -static HMODULE advapi; -static CredWriteWT CredWriteW; -static CredEnumerateWT CredEnumerateW; -static CredFreeT CredFree; -static CredDeleteWT CredDeleteW; - -static void load_cred_funcs(void) -{ - /* load DLLs */ - advapi = LoadLibraryExA("advapi32.dll", NULL, - LOAD_LIBRARY_SEARCH_SYSTEM32); - if (!advapi) - die("failed to load advapi32.dll"); - - /* get function pointers */ - CredWriteW = (CredWriteWT)GetProcAddress(advapi, "CredWriteW"); - CredEnumerateW = (CredEnumerateWT)GetProcAddress(advapi, - "CredEnumerateW"); - CredFree = (CredFreeT)GetProcAddress(advapi, "CredFree"); - CredDeleteW = (CredDeleteWT)GetProcAddress(advapi, "CredDeleteW"); - if (!CredWriteW || !CredEnumerateW || !CredFree || !CredDeleteW) - die("failed to load functions"); -} - -static WCHAR *wusername, *password, *protocol, *host, *path, target[1024]; +static WCHAR *wusername, *password, *protocol, *host, *path, target[1024], + *password_expiry_utc, *oauth_refresh_token; static void write_item(const char *what, LPCWSTR wbuf, int wlen) { @@ -165,7 +109,18 @@ static int match_part_last(LPCWSTR *ptarget, LPCWSTR want, LPCWSTR delim) return match_part_with_last(ptarget, want, delim, 1); } -static int match_cred(const CREDENTIALW *cred) +static int match_cred_password(const CREDENTIALW *cred) { + int ret; + WCHAR *cred_password = xmalloc(cred->CredentialBlobSize); + wcsncpy_s(cred_password, cred->CredentialBlobSize, + (LPCWSTR)cred->CredentialBlob, + cred->CredentialBlobSize / sizeof(WCHAR)); + ret = !wcscmp(cred_password, password); + free(cred_password); + return ret; +} + +static int match_cred(const CREDENTIALW *cred, int match_password) { LPCWSTR target = cred->TargetName; if (wusername && wcscmp(wusername, cred->UserName ? cred->UserName : L"")) @@ -175,7 +130,8 @@ static int match_cred(const CREDENTIALW *cred) match_part(&target, protocol, L"://") && match_part_last(&target, wusername, L"@") && match_part(&target, host, L"/") && - match_part(&target, path, L""); + match_part(&target, path, L"") && + (!match_password || match_cred_password(cred)); } static void get_credential(void) @@ -183,18 +139,47 @@ static void get_credential(void) CREDENTIALW **creds; DWORD num_creds; int i; + CREDENTIAL_ATTRIBUTEW *attr; + WCHAR *secret; + WCHAR *line; + WCHAR *remaining_lines; + WCHAR *part; + WCHAR *remaining_parts; if (!CredEnumerateW(L"git:*", 0, &num_creds, &creds)) return; /* search for the first credential that matches username */ for (i = 0; i < num_creds; ++i) - if (match_cred(creds[i])) { + if (match_cred(creds[i], 0)) { write_item("username", creds[i]->UserName, creds[i]->UserName ? wcslen(creds[i]->UserName) : 0); - write_item("password", - (LPCWSTR)creds[i]->CredentialBlob, - creds[i]->CredentialBlobSize / sizeof(WCHAR)); + if (creds[i]->CredentialBlobSize > 0) { + secret = xmalloc(creds[i]->CredentialBlobSize); + wcsncpy_s(secret, creds[i]->CredentialBlobSize, (LPCWSTR)creds[i]->CredentialBlob, creds[i]->CredentialBlobSize / sizeof(WCHAR)); + line = wcstok_s(secret, L"\r\n", &remaining_lines); + write_item("password", line, line ? wcslen(line) : 0); + while(line != NULL) { + part = wcstok_s(line, L"=", &remaining_parts); + if (!wcscmp(part, L"oauth_refresh_token")) { + write_item("oauth_refresh_token", remaining_parts, remaining_parts ? wcslen(remaining_parts) : 0); + } + line = wcstok_s(NULL, L"\r\n", &remaining_lines); + } + free(secret); + } else { + write_item("password", + (LPCWSTR)creds[i]->CredentialBlob, + creds[i]->CredentialBlobSize / sizeof(WCHAR)); + } + for (int j = 0; j < creds[i]->AttributeCount; j++) { + attr = creds[i]->Attributes + j; + if (!wcscmp(attr->Keyword, L"git_password_expiry_utc")) { + write_item("password_expiry_utc", (LPCWSTR)attr->Value, + attr->ValueSize / sizeof(WCHAR)); + break; + } + } break; } @@ -204,22 +189,43 @@ static void get_credential(void) static void store_credential(void) { CREDENTIALW cred; + CREDENTIAL_ATTRIBUTEW expiry_attr; + WCHAR *secret; + int wlen; if (!wusername || !password) return; + if (oauth_refresh_token) { + wlen = _scwprintf(L"%s\r\noauth_refresh_token=%s", password, oauth_refresh_token); + secret = xmalloc(sizeof(WCHAR) * wlen); + _snwprintf_s(secret, sizeof(WCHAR) * wlen, wlen, L"%s\r\noauth_refresh_token=%s", password, oauth_refresh_token); + } else { + secret = _wcsdup(password); + } + cred.Flags = 0; cred.Type = CRED_TYPE_GENERIC; cred.TargetName = target; cred.Comment = L"saved by git-credential-wincred"; - cred.CredentialBlobSize = (wcslen(password)) * sizeof(WCHAR); - cred.CredentialBlob = (LPVOID)password; + cred.CredentialBlobSize = wcslen(secret) * sizeof(WCHAR); + cred.CredentialBlob = (LPVOID)_wcsdup(secret); cred.Persist = CRED_PERSIST_LOCAL_MACHINE; cred.AttributeCount = 0; cred.Attributes = NULL; + if (password_expiry_utc != NULL) { + expiry_attr.Keyword = L"git_password_expiry_utc"; + expiry_attr.Value = (LPVOID)password_expiry_utc; + expiry_attr.ValueSize = (wcslen(password_expiry_utc)) * sizeof(WCHAR); + expiry_attr.Flags = 0; + cred.Attributes = &expiry_attr; + cred.AttributeCount = 1; + } cred.TargetAlias = NULL; cred.UserName = wusername; + free(secret); + if (!CredWriteW(&cred, 0)) die("CredWrite failed"); } @@ -234,7 +240,7 @@ static void erase_credential(void) return; for (i = 0; i < num_creds; ++i) { - if (match_cred(creds[i])) + if (match_cred(creds[i], password != NULL)) CredDeleteW(creds[i]->TargetName, creds[i]->Type, 0); } @@ -249,17 +255,28 @@ static WCHAR *utf8_to_utf16_dup(const char *str) return wstr; } +#define KB (1024) + static void read_credential(void) { - char buf[1024]; + size_t alloc = 100 * KB; + char *buf = calloc(alloc, sizeof(*buf)); - while (fgets(buf, sizeof(buf), stdin)) { + while (fgets(buf, alloc, stdin)) { char *v; - int len = strlen(buf); + size_t len = strlen(buf); + int ends_in_newline = 0; /* strip trailing CR / LF */ - while (len && strchr("\r\n", buf[len - 1])) + if (len && buf[len - 1] == '\n') { + buf[--len] = 0; + ends_in_newline = 1; + } + if (len && buf[len - 1] == '\r') buf[--len] = 0; + if (!ends_in_newline) + die("bad input: %s", buf); + if (!*buf) break; @@ -278,9 +295,18 @@ static void read_credential(void) wusername = utf8_to_utf16_dup(v); } else if (!strcmp(buf, "password")) password = utf8_to_utf16_dup(v); - else - die("unrecognized input"); + else if (!strcmp(buf, "password_expiry_utc")) + password_expiry_utc = utf8_to_utf16_dup(v); + else if (!strcmp(buf, "oauth_refresh_token")) + oauth_refresh_token = utf8_to_utf16_dup(v); + /* + * Ignore other lines; we don't know what they mean, but + * this future-proofs us when later versions of git do + * learn new lines, and the helpers are updated to match. + */ } + + free(buf); } int main(int argc, char *argv[]) @@ -289,7 +315,7 @@ int main(int argc, char *argv[]) "usage: git credential-wincred <get|store|erase>\n"; if (!argv[1]) - die(usage); + die("%s", usage); /* git use binary pipes to avoid CRLF-issues */ _setmode(_fileno(stdin), _O_BINARY); @@ -297,8 +323,6 @@ int main(int argc, char *argv[]) read_credential(); - load_cred_funcs(); - if (!protocol || !(host || path)) return 0; diff --git a/contrib/diff-highlight/DiffHighlight.pm b/contrib/diff-highlight/DiffHighlight.pm index 376f577..636add6 100644 --- a/contrib/diff-highlight/DiffHighlight.pm +++ b/contrib/diff-highlight/DiffHighlight.pm @@ -1,6 +1,6 @@ package DiffHighlight; -use 5.008; +use 5.008001; use warnings FATAL => 'all'; use strict; diff --git a/contrib/git-jump/README b/contrib/git-jump/README index 8bcace2..3211841 100644 --- a/contrib/git-jump/README +++ b/contrib/git-jump/README @@ -79,6 +79,14 @@ git jump grep -i foo_bar git config jump.grepCmd "ag --column" -------------------------------------------------- +You can use the optional argument '--stdout' to print the listing to +standard output instead of feeding it to the editor. You can use the +argument with M-x grep on Emacs: + +-------------------------------------------------- +# In Emacs, M-x grep and invoke "git jump --stdout <mode>" +M-x grep<RET>git jump --stdout diff<RET> +-------------------------------------------------- Related Programs ---------------- @@ -100,7 +108,7 @@ Limitations ----------- This script was written and tested with vim. Given that the quickfix -format is the same as what gcc produces, I expect emacs users have a +format is the same as what gcc produces, I expect other tools have a similar feature for iterating through the list, but I know nothing about how to activate it. diff --git a/contrib/git-jump/git-jump b/contrib/git-jump/git-jump index 92dbd4c..47e0c55 100755 --- a/contrib/git-jump/git-jump +++ b/contrib/git-jump/git-jump @@ -2,25 +2,43 @@ usage() { cat <<\EOF -usage: git jump <mode> [<args>] +usage: git jump [--stdout] <mode> [<args>] Jump to interesting elements in an editor. The <mode> parameter is one of: diff: elements are diff hunks. Arguments are given to diff. -merge: elements are merge conflicts. Arguments are ignored. +merge: elements are merge conflicts. Arguments are given to ls-files -u. grep: elements are grep hits. Arguments are given to git grep or, if configured, to the command in `jump.grepCmd`. ws: elements are whitespace errors. Arguments are given to diff --check. + +If the optional argument `--stdout` is given, print the quickfix +lines to standard output instead of feeding it to the editor. EOF } open_editor() { editor=`git var GIT_EDITOR` - eval "$editor -q \$1" + case "$editor" in + *emacs*) + # Supported editor values are: + # - emacs + # - emacsclient + # - emacsclient -t + # + # Wait for completion of the asynchronously executed process + # to avoid race conditions in case of "emacsclient". + eval "$editor --eval \"(let ((buf (grep \\\"cat \$1\\\"))) (pop-to-buffer buf) (select-frame-set-input-focus (selected-frame)) (while (get-buffer-process buf) (sleep-for 0.1)))\"" + ;; + *) + # assume anything else is vi-compatible + eval "$editor -q \$1" + ;; + esac } mode_diff() { @@ -64,15 +82,36 @@ mode_ws() { git diff --check "$@" } +use_stdout= +while test $# -gt 0; do + case "$1" in + --stdout) + use_stdout=t + ;; + --*) + usage >&2 + exit 1 + ;; + *) + break + ;; + esac + shift +done if test $# -lt 1; then usage >&2 exit 1 fi mode=$1; shift +type "mode_$mode" >/dev/null 2>&1 || { usage >&2; exit 1; } + +if test "$use_stdout" = "t"; then + "mode_$mode" "$@" + exit 0 +fi trap 'rm -f "$tmp"' 0 1 2 3 15 tmp=`mktemp -t git-jump.XXXXXX` || exit 1 -type "mode_$mode" >/dev/null 2>&1 || { usage >&2; exit 1; } "mode_$mode" "$@" >"$tmp" test -s "$tmp" || exit 0 open_editor "$tmp" diff --git a/contrib/hg-to-git/hg-to-git.py b/contrib/hg-to-git/hg-to-git.py deleted file mode 100755 index 7eb1b24..0000000 --- a/contrib/hg-to-git/hg-to-git.py +++ /dev/null @@ -1,254 +0,0 @@ -#!/usr/bin/env python - -""" hg-to-git.py - A Mercurial to GIT converter - - Copyright (C)2007 Stelian Pop <stelian@popies.net> - - This program is free software; you can redistribute it and/or modify - it under the terms of the GNU General Public License as published by - the Free Software Foundation; either version 2, or (at your option) - any later version. - - This program is distributed in the hope that it will be useful, - but WITHOUT ANY WARRANTY; without even the implied warranty of - MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - GNU General Public License for more details. - - You should have received a copy of the GNU General Public License - along with this program; if not, see <http://www.gnu.org/licenses/>. -""" - -import os, os.path, sys -import tempfile, pickle, getopt -import re - -if sys.hexversion < 0x02030000: - # The behavior of the pickle module changed significantly in 2.3 - sys.stderr.write("hg-to-git.py: requires Python 2.3 or later.\n") - sys.exit(1) - -# Maps hg version -> git version -hgvers = {} -# List of children for each hg revision -hgchildren = {} -# List of parents for each hg revision -hgparents = {} -# Current branch for each hg revision -hgbranch = {} -# Number of new changesets converted from hg -hgnewcsets = 0 - -#------------------------------------------------------------------------------ - -def usage(): - - print("""\ -%s: [OPTIONS] <hgprj> - -options: - -s, --gitstate=FILE: name of the state to be saved/read - for incrementals - -n, --nrepack=INT: number of changesets that will trigger - a repack (default=0, -1 to deactivate) - -v, --verbose: be verbose - -required: - hgprj: name of the HG project to import (directory) -""" % sys.argv[0]) - -#------------------------------------------------------------------------------ - -def getgitenv(user, date): - env = '' - elems = re.compile('(.*?)\s+<(.*)>').match(user) - if elems: - env += 'export GIT_AUTHOR_NAME="%s" ;' % elems.group(1) - env += 'export GIT_COMMITTER_NAME="%s" ;' % elems.group(1) - env += 'export GIT_AUTHOR_EMAIL="%s" ;' % elems.group(2) - env += 'export GIT_COMMITTER_EMAIL="%s" ;' % elems.group(2) - else: - env += 'export GIT_AUTHOR_NAME="%s" ;' % user - env += 'export GIT_COMMITTER_NAME="%s" ;' % user - env += 'export GIT_AUTHOR_EMAIL= ;' - env += 'export GIT_COMMITTER_EMAIL= ;' - - env += 'export GIT_AUTHOR_DATE="%s" ;' % date - env += 'export GIT_COMMITTER_DATE="%s" ;' % date - return env - -#------------------------------------------------------------------------------ - -state = '' -opt_nrepack = 0 -verbose = False - -try: - opts, args = getopt.getopt(sys.argv[1:], 's:t:n:v', ['gitstate=', 'tempdir=', 'nrepack=', 'verbose']) - for o, a in opts: - if o in ('-s', '--gitstate'): - state = a - state = os.path.abspath(state) - if o in ('-n', '--nrepack'): - opt_nrepack = int(a) - if o in ('-v', '--verbose'): - verbose = True - if len(args) != 1: - raise Exception('params') -except: - usage() - sys.exit(1) - -hgprj = args[0] -os.chdir(hgprj) - -if state: - if os.path.exists(state): - if verbose: - print('State does exist, reading') - f = open(state, 'r') - hgvers = pickle.load(f) - else: - print('State does not exist, first run') - -sock = os.popen('hg tip --template "{rev}"') -tip = sock.read() -if sock.close(): - sys.exit(1) -if verbose: - print('tip is', tip) - -# Calculate the branches -if verbose: - print('analysing the branches...') -hgchildren["0"] = () -hgparents["0"] = (None, None) -hgbranch["0"] = "master" -for cset in range(1, int(tip) + 1): - hgchildren[str(cset)] = () - prnts = os.popen('hg log -r %d --template "{parents}"' % cset).read().strip().split(' ') - prnts = map(lambda x: x[:x.find(':')], prnts) - if prnts[0] != '': - parent = prnts[0].strip() - else: - parent = str(cset - 1) - hgchildren[parent] += ( str(cset), ) - if len(prnts) > 1: - mparent = prnts[1].strip() - hgchildren[mparent] += ( str(cset), ) - else: - mparent = None - - hgparents[str(cset)] = (parent, mparent) - - if mparent: - # For merge changesets, take either one, preferably the 'master' branch - if hgbranch[mparent] == 'master': - hgbranch[str(cset)] = 'master' - else: - hgbranch[str(cset)] = hgbranch[parent] - else: - # Normal changesets - # For first children, take the parent branch, for the others create a new branch - if hgchildren[parent][0] == str(cset): - hgbranch[str(cset)] = hgbranch[parent] - else: - hgbranch[str(cset)] = "branch-" + str(cset) - -if "0" not in hgvers: - print('creating repository') - os.system('git init') - -# loop through every hg changeset -for cset in range(int(tip) + 1): - - # incremental, already seen - if str(cset) in hgvers: - continue - hgnewcsets += 1 - - # get info - log_data = os.popen('hg log -r %d --template "{tags}\n{date|date}\n{author}\n"' % cset).readlines() - tag = log_data[0].strip() - date = log_data[1].strip() - user = log_data[2].strip() - parent = hgparents[str(cset)][0] - mparent = hgparents[str(cset)][1] - - #get comment - (fdcomment, filecomment) = tempfile.mkstemp() - csetcomment = os.popen('hg log -r %d --template "{desc}"' % cset).read().strip() - os.write(fdcomment, csetcomment) - os.close(fdcomment) - - print('-----------------------------------------') - print('cset:', cset) - print('branch:', hgbranch[str(cset)]) - print('user:', user) - print('date:', date) - print('comment:', csetcomment) - if parent: - print('parent:', parent) - if mparent: - print('mparent:', mparent) - if tag: - print('tag:', tag) - print('-----------------------------------------') - - # checkout the parent if necessary - if cset != 0: - if hgbranch[str(cset)] == "branch-" + str(cset): - print('creating new branch', hgbranch[str(cset)]) - os.system('git checkout -b %s %s' % (hgbranch[str(cset)], hgvers[parent])) - else: - print('checking out branch', hgbranch[str(cset)]) - os.system('git checkout %s' % hgbranch[str(cset)]) - - # merge - if mparent: - if hgbranch[parent] == hgbranch[str(cset)]: - otherbranch = hgbranch[mparent] - else: - otherbranch = hgbranch[parent] - print('merging', otherbranch, 'into', hgbranch[str(cset)]) - os.system(getgitenv(user, date) + 'git merge --no-commit -s ours "" %s %s' % (hgbranch[str(cset)], otherbranch)) - - # remove everything except .git and .hg directories - os.system('find . \( -path "./.hg" -o -path "./.git" \) -prune -o ! -name "." -print | xargs rm -rf') - - # repopulate with checkouted files - os.system('hg update -C %d' % cset) - - # add new files - os.system('git ls-files -x .hg --others | git update-index --add --stdin') - # delete removed files - os.system('git ls-files -x .hg --deleted | git update-index --remove --stdin') - - # commit - os.system(getgitenv(user, date) + 'git commit --allow-empty --allow-empty-message -a -F %s' % filecomment) - os.unlink(filecomment) - - # tag - if tag and tag != 'tip': - os.system(getgitenv(user, date) + 'git tag %s' % tag) - - # delete branch if not used anymore... - if mparent and len(hgchildren[str(cset)]): - print("Deleting unused branch:", otherbranch) - os.system('git branch -d %s' % otherbranch) - - # retrieve and record the version - vvv = os.popen('git show --quiet --pretty=format:%H').read() - print('record', cset, '->', vvv) - hgvers[str(cset)] = vvv - -if hgnewcsets >= opt_nrepack and opt_nrepack != -1: - os.system('git repack -a -d') - -# write the state for incrementals -if state: - if verbose: - print('Writing state') - f = open(state, 'w') - pickle.dump(hgvers, f) - -# vim: et ts=8 sw=4 sts=4 diff --git a/contrib/hg-to-git/hg-to-git.txt b/contrib/hg-to-git/hg-to-git.txt deleted file mode 100644 index 91f8fe6..0000000 --- a/contrib/hg-to-git/hg-to-git.txt +++ /dev/null @@ -1,21 +0,0 @@ -hg-to-git.py is able to convert a Mercurial repository into a git one, -and preserves the branches in the process (unlike tailor) - -hg-to-git.py can probably be greatly improved (it's a rather crude -combination of shell and python) but it does already work quite well for -me. Features: - - supports incremental conversion - (for keeping a git repo in sync with a hg one) - - supports hg branches - - converts hg tags - -Note that the git repository will be created 'in place' (at the same -location as the source hg repo). You will have to manually remove the -'.hg' directory after the conversion. - -Also note that the incremental conversion uses 'simple' hg changesets -identifiers (ordinals, as opposed to SHA-1 ids), and since these ids -are not stable across different repositories the hg-to-git.py state file -is forever tied to one hg repository. - -Stelian Pop <stelian@popies.net> diff --git a/contrib/mw-to-git/Git/Mediawiki.pm b/contrib/mw-to-git/Git/Mediawiki.pm index 917d9e2..ff78112 100644 --- a/contrib/mw-to-git/Git/Mediawiki.pm +++ b/contrib/mw-to-git/Git/Mediawiki.pm @@ -1,6 +1,6 @@ package Git::Mediawiki; -use 5.008; +use 5.008001; use strict; use POSIX; use Git; diff --git a/contrib/mw-to-git/t/t9363-mw-to-git-export-import.sh b/contrib/mw-to-git/t/t9363-mw-to-git-export-import.sh index 6187ec6..7139995 100755 --- a/contrib/mw-to-git/t/t9363-mw-to-git-export-import.sh +++ b/contrib/mw-to-git/t/t9363-mw-to-git-export-import.sh @@ -161,7 +161,7 @@ test_expect_success 'git push properly warns about insufficient permissions' ' git add foo.forbidden && git commit -m "add a file" && git push 2>actual && - test_i18ngrep "foo.forbidden is not a permitted file" actual + test_grep "foo.forbidden is not a permitted file" actual ) ' diff --git a/contrib/subtree/git-subtree.sh b/contrib/subtree/git-subtree.sh index 7562a39..5dab3f5 100755 --- a/contrib/subtree/git-subtree.sh +++ b/contrib/subtree/git-subtree.sh @@ -33,19 +33,19 @@ git subtree split --prefix=<prefix> [<commit>] git subtree pull --prefix=<prefix> <repository> <ref> git subtree push --prefix=<prefix> <repository> <refspec> -- -h,help show the help -q quiet -d show debug messages +h,help! show the help +q,quiet! quiet +d,debug! show debug messages P,prefix= the name of the subdir to split out options for 'split' (also: 'push') annotate= add a prefix to commit message of new commits -b,branch= create a new branch from the split subtree +b,branch!= create a new branch from the split subtree ignore-joins ignore prior --rejoin commits onto= try connecting new tree to an existing one rejoin merge the new branch back into HEAD options for 'add' and 'merge' (also: 'pull', 'split --rejoin', and 'push --rejoin') squash merge subtree changes as a single commit -m,message= use the given message as the commit message for the merge commit +m,message!= use the given message as the commit message for the merge commit " indent=0 @@ -98,10 +98,18 @@ progress () { assert () { if ! "$@" then - die "assertion failed: $*" + die "fatal: assertion failed: $*" fi } +# Usage: die_incompatible_opt OPTION COMMAND +die_incompatible_opt () { + assert test "$#" = 2 + opt="$1" + arg_command="$2" + die "fatal: the '$opt' flag does not make sense with 'git subtree $arg_command'." +} + main () { if test $# -eq 0 then @@ -147,7 +155,7 @@ main () { allow_addmerge=$arg_split_rejoin ;; *) - die "Unknown command '$arg_command'" + die "fatal: unknown command '$arg_command'" ;; esac # Reset the arguments array for "real" flag parsing. @@ -176,16 +184,16 @@ main () { arg_debug=1 ;; --annotate) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" arg_split_annotate="$1" shift ;; --no-annotate) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" arg_split_annotate= ;; -b) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" arg_split_branch="$1" shift ;; @@ -194,7 +202,7 @@ main () { shift ;; -m) - test -n "$allow_addmerge" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_addmerge" || die_incompatible_opt "$opt" "$arg_command" arg_addmerge_message="$1" shift ;; @@ -202,41 +210,41 @@ main () { arg_prefix= ;; --onto) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" arg_split_onto="$1" shift ;; --no-onto) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" arg_split_onto= ;; --rejoin) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" ;; --no-rejoin) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" ;; --ignore-joins) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" arg_split_ignore_joins=1 ;; --no-ignore-joins) - test -n "$allow_split" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_split" || die_incompatible_opt "$opt" "$arg_command" arg_split_ignore_joins= ;; --squash) - test -n "$allow_addmerge" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_addmerge" || die_incompatible_opt "$opt" "$arg_command" arg_addmerge_squash=1 ;; --no-squash) - test -n "$allow_addmerge" || die "The '$opt' flag does not make sense with 'git subtree $arg_command'." + test -n "$allow_addmerge" || die_incompatible_opt "$opt" "$arg_command" arg_addmerge_squash= ;; --) break ;; *) - die "Unexpected option: $opt" + die "fatal: unexpected option: $opt" ;; esac done @@ -244,17 +252,17 @@ main () { if test -z "$arg_prefix" then - die "You must provide the --prefix option." + die "fatal: you must provide the --prefix option." fi case "$arg_command" in add) test -e "$arg_prefix" && - die "prefix '$arg_prefix' already exists." + die "fatal: prefix '$arg_prefix' already exists." ;; *) test -e "$arg_prefix" || - die "'$arg_prefix' does not exist; use 'git subtree add'" + die "fatal: '$arg_prefix' does not exist; use 'git subtree add'" ;; esac @@ -274,11 +282,11 @@ cache_setup () { assert test $# = 0 cachedir="$GIT_DIR/subtree-cache/$$" rm -rf "$cachedir" || - die "Can't delete old cachedir: $cachedir" + die "fatal: can't delete old cachedir: $cachedir" mkdir -p "$cachedir" || - die "Can't create new cachedir: $cachedir" + die "fatal: can't create new cachedir: $cachedir" mkdir -p "$cachedir/notree" || - die "Can't create new cachedir: $cachedir/notree" + die "fatal: can't create new cachedir: $cachedir/notree" debug "Using cachedir: $cachedir" >&2 } @@ -334,7 +342,7 @@ cache_set () { test "$oldrev" != "latest_new" && test -e "$cachedir/$oldrev" then - die "cache for $oldrev already exists!" + die "fatal: cache for $oldrev already exists!" fi echo "$newrev" >"$cachedir/$oldrev" } @@ -363,13 +371,49 @@ try_remove_previous () { fi } -# Usage: find_latest_squash DIR +# Usage: process_subtree_split_trailer SPLIT_HASH MAIN_HASH [REPOSITORY] +process_subtree_split_trailer () { + assert test $# -ge 2 + assert test $# -le 3 + b="$1" + sq="$2" + repository="" + if test "$#" = 3 + then + repository="$3" + fi + fail_msg="fatal: could not rev-parse split hash $b from commit $sq" + if ! sub="$(git rev-parse --verify --quiet "$b^{commit}")" + then + # if 'repository' was given, try to fetch the 'git-subtree-split' hash + # before 'rev-parse'-ing it again, as it might be a tag that we do not have locally + if test -n "${repository}" + then + git fetch "$repository" "$b" + sub="$(git rev-parse --verify --quiet "$b^{commit}")" || + die "$fail_msg" + else + hint1=$(printf "hint: hash might be a tag, try fetching it from the subtree repository:") + hint2=$(printf "hint: git fetch <subtree-repository> $b") + fail_msg=$(printf "$fail_msg\n$hint1\n$hint2") + die "$fail_msg" + fi + fi +} + +# Usage: find_latest_squash DIR [REPOSITORY] find_latest_squash () { - assert test $# = 1 - debug "Looking for latest squash ($dir)..." + assert test $# -ge 1 + assert test $# -le 2 + dir="$1" + repository="" + if test "$#" = 2 + then + repository="$2" + fi + debug "Looking for latest squash (dir=$dir, repository=$repository)..." local indent=$(($indent + 1)) - dir="$1" sq= main= sub= @@ -387,8 +431,7 @@ find_latest_squash () { main="$b" ;; git-subtree-split:) - sub="$(git rev-parse "$b^{commit}")" || - die "could not rev-parse split hash $b from commit $sq" + process_subtree_split_trailer "$b" "$sq" "$repository" ;; END) if test -n "$sub" @@ -412,14 +455,20 @@ find_latest_squash () { done || exit $? } -# Usage: find_existing_splits DIR REV +# Usage: find_existing_splits DIR REV [REPOSITORY] find_existing_splits () { - assert test $# = 2 + assert test $# -ge 2 + assert test $# -le 3 debug "Looking for prior splits..." local indent=$(($indent + 1)) dir="$1" rev="$2" + repository="" + if test "$#" = 3 + then + repository="$3" + fi main= sub= local grep_format="^git-subtree-dir: $dir/*\$" @@ -439,18 +488,17 @@ find_existing_splits () { main="$b" ;; git-subtree-split:) - sub="$(git rev-parse "$b^{commit}")" || - die "could not rev-parse split hash $b from commit $sq" + process_subtree_split_trailer "$b" "$sq" "$repository" ;; END) debug "Main is: '$main'" - if test -z "$main" -a -n "$sub" + if test -z "$main" && test -n "$sub" then # squash commits refer to a subtree debug " Squash: $sq from $sub" cache_set "$sq" "$sub" fi - if test -n "$main" -a -n "$sub" + if test -n "$main" && test -n "$sub" then debug " Prior: $main -> $sub" cache_set $main $sub @@ -490,7 +538,7 @@ copy_commit () { cat ) | git commit-tree "$2" $3 # reads the rest of stdin - ) || die "Can't copy commit $1" + ) || die "fatal: can't copy commit $1" } # Usage: add_msg DIR LATEST_OLD LATEST_NEW @@ -593,10 +641,16 @@ subtree_for_commit () { while read mode type tree name do assert test "$name" = "$dir" - assert test "$type" = "tree" -o "$type" = "commit" - test "$type" = "commit" && continue # ignore submodules - echo $tree - break + + case "$type" in + commit) + continue;; # ignore submodules + tree) + echo $tree + break;; + *) + die "fatal: tree entry is of type ${type}, expected tree or commit";; + esac done || exit $? } @@ -718,11 +772,11 @@ ensure_clean () { assert test $# = 0 if ! git diff-index HEAD --exit-code --quiet 2>&1 then - die "Working tree has modifications. Cannot add." + die "fatal: working tree has modifications. Cannot add." fi if ! git diff-index --cached HEAD --exit-code --quiet 2>&1 then - die "Index has modifications. Cannot add." + die "fatal: index has modifications. Cannot add." fi } @@ -730,7 +784,23 @@ ensure_clean () { ensure_valid_ref_format () { assert test $# = 1 git check-ref-format "refs/heads/$1" || - die "'$1' does not look like a ref" + die "fatal: '$1' does not look like a ref" +} + +# Usage: check if a commit from another subtree should be +# ignored from processing for splits +should_ignore_subtree_split_commit () { + assert test $# = 1 + local rev="$1" + if test -n "$(git log -1 --grep="git-subtree-dir:" $rev)" + then + if test -z "$(git log -1 --grep="git-subtree-mainline:" $rev)" && + test -z "$(git log -1 --grep="git-subtree-dir: $arg_prefix$" $rev)" + then + return 0 + fi + fi + return 1 } # Usage: process_split_commit REV PARENTS @@ -796,7 +866,7 @@ cmd_add () { if test $# -eq 1 then git rev-parse -q --verify "$1^{commit}" >/dev/null || - die "'$1' does not refer to a commit" + die "fatal: '$1' does not refer to a commit" cmd_add_commit "$@" @@ -811,7 +881,7 @@ cmd_add () { cmd_add_repository "$@" else - say >&2 "error: parameters were '$*'" + say >&2 "fatal: parameters were '$*'" die "Provide either a commit or a repository and commit." fi } @@ -843,7 +913,7 @@ cmd_add_commit () { git checkout -- "$dir" || exit $? tree=$(git write-tree) || exit $? - headrev=$(git rev-parse HEAD) || exit $? + headrev=$(git rev-parse --verify HEAD) || exit $? if test -n "$headrev" && test "$headrev" != "$rev" then headp="-p $headrev" @@ -866,17 +936,22 @@ cmd_add_commit () { say >&2 "Added dir '$dir'" } -# Usage: cmd_split [REV] +# Usage: cmd_split [REV] [REPOSITORY] cmd_split () { if test $# -eq 0 then rev=$(git rev-parse HEAD) - elif test $# -eq 1 + elif test $# -eq 1 || test $# -eq 2 then rev=$(git rev-parse -q --verify "$1^{commit}") || - die "'$1' does not refer to a commit" + die "fatal: '$1' does not refer to a commit" else - die "You must provide exactly one revision. Got: '$*'" + die "fatal: you must provide exactly one revision, and optionnally a repository. Got: '$*'" + fi + repository="" + if test "$#" = 2 + then + repository="$2" fi if test -n "$arg_split_rejoin" @@ -900,7 +975,7 @@ cmd_split () { done || exit $? fi - unrevs="$(find_existing_splits "$dir" "$rev")" || exit $? + unrevs="$(find_existing_splits "$dir" "$rev" "$repository")" || exit $? # We can't restrict rev-list to only $dir here, because some of our # parents have the $dir contents the root, and those won't match. @@ -913,13 +988,25 @@ cmd_split () { eval "$grl" | while read rev parents do - process_split_commit "$rev" "$parents" + if should_ignore_subtree_split_commit "$rev" + then + continue + fi + parsedparents='' + for parent in $parents + do + if ! should_ignore_subtree_split_commit "$parent" + then + parsedparents="$parsedparents$parent " + fi + done + process_split_commit "$rev" "$parsedparents" done || exit $? latest_new=$(cache_get latest_new) || exit $? if test -z "$latest_new" then - die "No new revisions were found" + die "fatal: no new revisions were found" fi if test -n "$arg_split_rejoin" @@ -940,7 +1027,7 @@ cmd_split () { then if ! git merge-base --is-ancestor "$arg_split_branch" "$latest_new" then - die "Branch '$arg_split_branch' is not an ancestor of commit '$latest_new'." + die "fatal: branch '$arg_split_branch' is not an ancestor of commit '$latest_new'." fi action='Updated' else @@ -954,20 +1041,28 @@ cmd_split () { exit 0 } -# Usage: cmd_merge REV +# Usage: cmd_merge REV [REPOSITORY] cmd_merge () { - test $# -eq 1 || - die "You must provide exactly one revision. Got: '$*'" + if test $# -lt 1 || test $# -gt 2 + then + die "fatal: you must provide exactly one revision, and optionally a repository. Got: '$*'" + fi + rev=$(git rev-parse -q --verify "$1^{commit}") || - die "'$1' does not refer to a commit" + die "fatal: '$1' does not refer to a commit" + repository="" + if test "$#" = 2 + then + repository="$2" + fi ensure_clean if test -n "$arg_addmerge_squash" then - first_split="$(find_latest_squash "$dir")" || exit $? + first_split="$(find_latest_squash "$dir" "$repository")" || exit $? if test -z "$first_split" then - die "Can't squash-merge: '$dir' was never added." + die "fatal: can't squash-merge: '$dir' was never added." fi set $first_split old=$1 @@ -995,19 +1090,21 @@ cmd_merge () { cmd_pull () { if test $# -ne 2 then - die "You must provide <repository> <ref>" + die "fatal: you must provide <repository> <ref>" fi + repository="$1" + ref="$2" ensure_clean - ensure_valid_ref_format "$2" - git fetch "$@" || exit $? - cmd_merge FETCH_HEAD + ensure_valid_ref_format "$ref" + git fetch "$repository" "$ref" || exit $? + cmd_merge FETCH_HEAD "$repository" } # Usage: cmd_push REPOSITORY [+][LOCALREV:]REMOTEREF cmd_push () { if test $# -ne 2 then - die "You must provide <repository> <refspec>" + die "fatal: you must provide <repository> <refspec>" fi if test -e "$dir" then @@ -1022,13 +1119,13 @@ cmd_push () { fi ensure_valid_ref_format "$remoteref" localrev_presplit=$(git rev-parse -q --verify "$localrevname_presplit^{commit}") || - die "'$localrevname_presplit' does not refer to a commit" + die "fatal: '$localrevname_presplit' does not refer to a commit" echo "git push using: " "$repository" "$refspec" - localrev=$(cmd_split "$localrev_presplit") || die + localrev=$(cmd_split "$localrev_presplit" "$repository") || die git push "$repository" "$localrev":"refs/heads/$remoteref" else - die "'$dir' must already exist. Try 'git subtree add'." + die "fatal: '$dir' must already exist. Try 'git subtree add'." fi } diff --git a/contrib/subtree/git-subtree.txt b/contrib/subtree/git-subtree.txt index 9cddfa2..004abf4 100644 --- a/contrib/subtree/git-subtree.txt +++ b/contrib/subtree/git-subtree.txt @@ -11,7 +11,7 @@ SYNOPSIS [verse] 'git subtree' [<options>] -P <prefix> add <local-commit> 'git subtree' [<options>] -P <prefix> add <repository> <remote-ref> -'git subtree' [<options>] -P <prefix> merge <local-commit> +'git subtree' [<options>] -P <prefix> merge <local-commit> [<repository>] 'git subtree' [<options>] -P <prefix> split [<local-commit>] [verse] @@ -76,7 +76,7 @@ add <repository> <remote-ref>:: only a single commit from the subproject, rather than its entire history. -merge <local-commit>:: +merge <local-commit> [<repository>]:: Merge recent changes up to <local-commit> into the <prefix> subtree. As with normal 'git merge', this doesn't remove your own local changes; it just merges those @@ -88,8 +88,13 @@ If you use '--squash', the merge direction doesn't always have to be forward; you can use this command to go back in time from v2.5 to v2.4, for example. If your merge introduces a conflict, you can resolve it in the usual ways. ++ +When using '--squash', and the previous merge with '--squash' merged an +annotated tag of the subtree repository, that tag needs to be available locally. +If <repository> is given, a missing tag will automatically be fetched from that +repository. -split [<local-commit>]:: +split [<local-commit>] [<repository>]:: Extract a new, synthetic project history from the history of the <prefix> subtree of <local-commit>, or of HEAD if no <local-commit> is given. The new history @@ -109,6 +114,11 @@ settings passed to 'split' (such as '--annotate') are the same. Because of this, if you add new commits and then re-split, the new commits will be attached as commits on top of the history you generated last time, so 'git merge' and friends will work as expected. ++ +When a previous merge with '--squash' merged an annotated tag of the +subtree repository, that tag needs to be available locally. +If <repository> is given, a missing tag will automatically be fetched from that +repository. pull <repository> <remote-ref>:: Exactly like 'merge', but parallels 'git pull' in that diff --git a/contrib/subtree/t/Makefile b/contrib/subtree/t/Makefile index 4655e09..093399c 100644 --- a/contrib/subtree/t/Makefile +++ b/contrib/subtree/t/Makefile @@ -74,9 +74,7 @@ aggregate-results-and-cleanup: $(T) $(MAKE) clean aggregate-results: - for f in '$(TEST_RESULTS_DIRECTORY_SQ)'/t*-*.counts; do \ - echo "$$f"; \ - done | '$(SHELL_PATH_SQ)' ../../../t/aggregate-results.sh + @'$(SHELL_PATH_SQ)' ../../../t/aggregate-results.sh '$(TEST_RESULTS_DIRECTORY_SQ)' valgrind: $(MAKE) GIT_TEST_OPTS="$(GIT_TEST_OPTS) --valgrind" diff --git a/contrib/subtree/t/t7900-subtree.sh b/contrib/subtree/t/t7900-subtree.sh index 1c1f76f..c3bd2a5 100755 --- a/contrib/subtree/t/t7900-subtree.sh +++ b/contrib/subtree/t/t7900-subtree.sh @@ -43,11 +43,35 @@ last_commit_subject () { git log --pretty=format:%s -1 } +# Upon 'git subtree add|merge --squash' of an annotated tag, +# pre-2.32.0 versions of 'git subtree' would write the hash of the tag +# (sub1 below), instead of the commit (sub1^{commit}) in the +# "git-subtree-split" trailer. +# We immitate this behaviour below using a replace ref. +# This function creates 3 repositories: +# - $1 +# - $1-sub (added as subtree "sub" in $1) +# - $1-clone (clone of $1) +test_create_pre2_32_repo () { + subtree_test_create_repo "$1" && + subtree_test_create_repo "$1-sub" && + test_commit -C "$1" main1 && + test_commit -C "$1-sub" --annotate sub1 && + git -C "$1" subtree add --prefix="sub" --squash "../$1-sub" sub1 && + tag=$(git -C "$1" rev-parse FETCH_HEAD) && + commit=$(git -C "$1" rev-parse FETCH_HEAD^{commit}) && + git -C "$1" log -1 --format=%B HEAD^2 >msg && + test_commit -C "$1-sub" --annotate sub2 && + git clone --no-local "$1" "$1-clone" && + new_commit=$(sed -e "s/$commit/$tag/" msg | git -C "$1-clone" commit-tree HEAD^2^{tree}) && + git -C "$1-clone" replace HEAD^2 $new_commit +} + test_expect_success 'shows short help text for -h' ' test_expect_code 129 git subtree -h >out 2>err && test_must_be_empty err && grep -e "^ *or: git subtree pull" out && - grep -e --annotate out + grep -F -e "--[no-]annotate" out ' # @@ -264,6 +288,13 @@ test_expect_success 'merge new subproj history into subdir/ with a slash appende ) ' +test_expect_success 'merge with --squash after annotated tag was added/merged with --squash pre-v2.32.0 ' ' + test_create_pre2_32_repo "$test_count" && + git -C "$test_count-clone" fetch "../$test_count-sub" sub2 && + test_must_fail git -C "$test_count-clone" subtree merge --prefix="sub" --squash FETCH_HEAD && + git -C "$test_count-clone" subtree merge --prefix="sub" --squash FETCH_HEAD "../$test_count-sub" +' + # # Tests for 'git subtree split' # @@ -277,7 +308,7 @@ test_expect_success 'split requires option --prefix' ' cd "$test_count" && git fetch ./"sub proj" HEAD && git subtree add --prefix="sub dir" FETCH_HEAD && - echo "You must provide the --prefix option." >expected && + echo "fatal: you must provide the --prefix option." >expected && test_must_fail git subtree split >actual 2>&1 && test_debug "printf '"expected: "'" && test_debug "cat expected" && @@ -296,7 +327,7 @@ test_expect_success 'split requires path given by option --prefix must exist' ' cd "$test_count" && git fetch ./"sub proj" HEAD && git subtree add --prefix="sub dir" FETCH_HEAD && - echo "'\''non-existent-directory'\'' does not exist; use '\''git subtree add'\''" >expected && + echo "fatal: '\''non-existent-directory'\'' does not exist; use '\''git subtree add'\''" >expected && test_must_fail git subtree split --prefix=non-existent-directory >actual 2>&1 && test_debug "printf '"expected: "'" && test_debug "cat expected" && @@ -354,6 +385,46 @@ test_expect_success 'split sub dir/ with --rejoin' ' ) ' +# Tests that commits from other subtrees are not processed as +# part of a split. +# +# This test performs the following: +# - Creates Repo with subtrees 'subA' and 'subB' +# - Creates commits in the repo including changes to subtrees +# - Runs the following 'split' and commit' commands in order: +# - Perform 'split' on subtree A +# - Perform 'split' on subtree B +# - Create new commits with changes to subtree A and B +# - Perform split on subtree A +# - Check that the commits in subtree B are not processed +# as part of the subtree A split +test_expect_success 'split with multiple subtrees' ' + subtree_test_create_repo "$test_count" && + subtree_test_create_repo "$test_count/subA" && + subtree_test_create_repo "$test_count/subB" && + test_create_commit "$test_count" main1 && + test_create_commit "$test_count/subA" subA1 && + test_create_commit "$test_count/subA" subA2 && + test_create_commit "$test_count/subA" subA3 && + test_create_commit "$test_count/subB" subB1 && + git -C "$test_count" fetch ./subA HEAD && + git -C "$test_count" subtree add --prefix=subADir FETCH_HEAD && + git -C "$test_count" fetch ./subB HEAD && + git -C "$test_count" subtree add --prefix=subBDir FETCH_HEAD && + test_create_commit "$test_count" subADir/main-subA1 && + test_create_commit "$test_count" subBDir/main-subB1 && + git -C "$test_count" subtree split --prefix=subADir \ + --squash --rejoin -m "Sub A Split 1" && + git -C "$test_count" subtree split --prefix=subBDir \ + --squash --rejoin -m "Sub B Split 1" && + test_create_commit "$test_count" subADir/main-subA2 && + test_create_commit "$test_count" subBDir/main-subB2 && + git -C "$test_count" subtree split --prefix=subADir \ + --squash --rejoin -m "Sub A Split 2" && + test "$(git -C "$test_count" subtree split --prefix=subBDir \ + --squash --rejoin -d -m "Sub B Split 1" 2>&1 | grep -w "\[1\]")" = "" +' + test_expect_success 'split sub dir/ with --rejoin from scratch' ' subtree_test_create_repo "$test_count" && test_create_commit "$test_count" main1 && @@ -551,6 +622,12 @@ test_expect_success 'split "sub dir"/ with --branch for an incompatible branch' ) ' +test_expect_success 'split after annotated tag was added/merged with --squash pre-v2.32.0' ' + test_create_pre2_32_repo "$test_count" && + test_must_fail git -C "$test_count-clone" subtree split --prefix="sub" HEAD && + git -C "$test_count-clone" subtree split --prefix="sub" HEAD "../$test_count-sub" +' + # # Tests for 'git subtree pull' # @@ -570,7 +647,7 @@ test_expect_success 'pull requires option --prefix' ' cd "$test_count" && test_must_fail git subtree pull ./"sub proj" HEAD >out 2>err && - echo "You must provide the --prefix option." >expected && + echo "fatal: you must provide the --prefix option." >expected && test_must_be_empty out && test_cmp expected err ) @@ -584,7 +661,7 @@ test_expect_success 'pull requires path given by option --prefix must exist' ' ( test_must_fail git subtree pull --prefix="sub dir" ./"sub proj" HEAD >out 2>err && - echo "'\''sub dir'\'' does not exist; use '\''git subtree add'\''" >expected && + echo "fatal: '\''sub dir'\'' does not exist; use '\''git subtree add'\''" >expected && test_must_be_empty out && test_cmp expected err ) @@ -630,6 +707,11 @@ test_expect_success 'pull rejects flags for split' ' ) ' +test_expect_success 'pull with --squash after annotated tag was added/merged with --squash pre-v2.32.0 ' ' + test_create_pre2_32_repo "$test_count" && + git -C "$test_count-clone" subtree -d pull --prefix="sub" --squash "../$test_count-sub" sub2 +' + # # Tests for 'git subtree push' # @@ -643,7 +725,7 @@ test_expect_success 'push requires option --prefix' ' cd "$test_count" && git fetch ./"sub proj" HEAD && git subtree add --prefix="sub dir" FETCH_HEAD && - echo "You must provide the --prefix option." >expected && + echo "fatal: you must provide the --prefix option." >expected && test_must_fail git subtree push "./sub proj" from-mainline >actual 2>&1 && test_debug "printf '"expected: "'" && test_debug "cat expected" && @@ -662,7 +744,7 @@ test_expect_success 'push requires path given by option --prefix must exist' ' cd "$test_count" && git fetch ./"sub proj" HEAD && git subtree add --prefix="sub dir" FETCH_HEAD && - echo "'\''non-existent-directory'\'' does not exist; use '\''git subtree add'\''" >expected && + echo "fatal: '\''non-existent-directory'\'' does not exist; use '\''git subtree add'\''" >expected && test_must_fail git subtree push --prefix=non-existent-directory "./sub proj" from-mainline >actual 2>&1 && test_debug "printf '"expected: "'" && test_debug "cat expected" && @@ -953,6 +1035,12 @@ test_expect_success 'push "sub dir"/ with a local rev' ' ) ' +test_expect_success 'push after annotated tag was added/merged with --squash pre-v2.32.0' ' + test_create_pre2_32_repo "$test_count" && + test_create_commit "$test_count-clone" sub/main-sub1 && + git -C "$test_count-clone" subtree push --prefix="sub" "../$test_count-sub" from-mainline +' + # # Validity checking # diff --git a/contrib/vscode/init.sh b/contrib/vscode/init.sh index 521d303..f2d61bb 100755 --- a/contrib/vscode/init.sh +++ b/contrib/vscode/init.sh @@ -92,7 +92,6 @@ cat >.vscode/settings.json.new <<\EOF || "isexe", "iskeychar", "kompare", - "mksnpath", "mktag", "mktree", "mmblob", diff --git a/contrib/workdir/git-new-workdir b/contrib/workdir/git-new-workdir index 888c34a..989197a 100755 --- a/contrib/workdir/git-new-workdir +++ b/contrib/workdir/git-new-workdir @@ -79,7 +79,7 @@ trap cleanup $siglist # create the links to the original repo. explicitly exclude index, HEAD and # logs/HEAD from the list since they are purely related to the current working # directory, and should not be shared. -for x in config refs logs/refs objects info hooks packed-refs remotes rr-cache svn +for x in config refs logs/refs objects info hooks packed-refs remotes rr-cache svn reftable do # create a containing directory if needed case $x in |