From c8bae7493d2f2910b57f13ded012e86bdcfb0532 Mon Sep 17 00:00:00 2001 From: Daniel Baumann Date: Sun, 7 Apr 2024 16:47:53 +0200 Subject: Adding upstream version 1:2.39.2. Signed-off-by: Daniel Baumann --- contrib/README | 43 + contrib/buildsystems/CMakeLists.txt | 1100 ++++++ contrib/buildsystems/Generators.pm | 42 + contrib/buildsystems/Generators/QMake.pm | 189 ++ contrib/buildsystems/Generators/Vcproj.pm | 579 ++++ contrib/buildsystems/Generators/Vcxproj.pm | 402 +++ contrib/buildsystems/engine.pl | 394 +++ contrib/buildsystems/generate | 29 + contrib/buildsystems/parse.pl | 228 ++ contrib/coccinelle/.gitignore | 1 + contrib/coccinelle/README | 92 + contrib/coccinelle/array.cocci | 96 + contrib/coccinelle/commit.cocci | 52 + contrib/coccinelle/equals-null.cocci | 30 + contrib/coccinelle/flex_alloc.cocci | 13 + contrib/coccinelle/free.cocci | 45 + contrib/coccinelle/hashmap.cocci | 16 + contrib/coccinelle/index-compatibility.cocci | 139 + .../coccinelle/index-compatibility.pending.cocci | 24 + contrib/coccinelle/object_id.cocci | 75 + contrib/coccinelle/preincr.cocci | 5 + contrib/coccinelle/qsort.cocci | 37 + contrib/coccinelle/spatchcache | 304 ++ contrib/coccinelle/strbuf.cocci | 62 + contrib/coccinelle/swap.cocci | 28 + contrib/coccinelle/tests/free.c | 11 + contrib/coccinelle/tests/free.res | 9 + contrib/coccinelle/tests/unused.c | 82 + contrib/coccinelle/tests/unused.res | 45 + contrib/coccinelle/the_repository.pending.cocci | 128 + contrib/coccinelle/unused.cocci | 43 + contrib/coccinelle/xcalloc.cocci | 10 + contrib/coccinelle/xopen.cocci | 19 + contrib/coccinelle/xstrdup_or_null.cocci | 5 + contrib/completion/.gitattributes | 1 + contrib/completion/git-completion.bash | 3591 ++++++++++++++++++++ contrib/completion/git-completion.tcsh | 127 + contrib/completion/git-completion.zsh | 294 ++ contrib/completion/git-prompt.sh | 599 ++++ contrib/contacts/.gitignore | 3 + contrib/contacts/Makefile | 71 + contrib/contacts/git-contacts | 203 ++ contrib/contacts/git-contacts.txt | 94 + contrib/coverage-diff.sh | 108 + contrib/credential/gnome-keyring/.gitignore | 1 + contrib/credential/gnome-keyring/Makefile | 25 + .../gnome-keyring/git-credential-gnome-keyring.c | 470 +++ contrib/credential/libsecret/Makefile | 25 + .../libsecret/git-credential-libsecret.c | 369 ++ contrib/credential/netrc/.gitignore | 1 + contrib/credential/netrc/Makefile | 30 + contrib/credential/netrc/git-credential-netrc.perl | 443 +++ contrib/credential/netrc/t-git-credential-netrc.sh | 22 + contrib/credential/netrc/test.command-option-gpg | 2 + contrib/credential/netrc/test.git-config-gpg | 2 + contrib/credential/netrc/test.netrc | 13 + contrib/credential/netrc/test.netrc.gpg | 0 contrib/credential/netrc/test.pl | 139 + contrib/credential/osxkeychain/.gitignore | 1 + contrib/credential/osxkeychain/Makefile | 17 + .../osxkeychain/git-credential-osxkeychain.c | 189 ++ contrib/credential/wincred/Makefile | 22 + .../credential/wincred/git-credential-wincred.c | 331 ++ contrib/diff-highlight/.gitignore | 2 + contrib/diff-highlight/DiffHighlight.pm | 285 ++ contrib/diff-highlight/Makefile | 23 + contrib/diff-highlight/README | 223 ++ contrib/diff-highlight/diff-highlight.perl | 8 + contrib/diff-highlight/t/.gitignore | 2 + contrib/diff-highlight/t/Makefile | 22 + contrib/diff-highlight/t/t9400-diff-highlight.sh | 341 ++ contrib/emacs/README | 33 + contrib/emacs/git-blame.el | 6 + contrib/emacs/git.el | 6 + contrib/examples/README | 20 + contrib/fast-import/git-import.perl | 64 + contrib/fast-import/git-import.sh | 38 + contrib/fast-import/git-p4.README | 12 + contrib/fast-import/import-directories.perl | 416 +++ contrib/fast-import/import-tars.perl | 227 ++ contrib/fast-import/import-zips.py | 78 + contrib/git-jump/README | 115 + contrib/git-jump/git-jump | 78 + contrib/git-resurrect.sh | 181 + contrib/git-shell-commands/README | 18 + contrib/git-shell-commands/help | 18 + contrib/git-shell-commands/list | 10 + contrib/hg-to-git/hg-to-git.py | 254 ++ contrib/hg-to-git/hg-to-git.txt | 21 + contrib/hooks/multimail/README.Git | 7 + contrib/hooks/post-receive-email | 759 +++++ contrib/hooks/pre-auto-gc-battery | 42 + contrib/hooks/setgitperms.perl | 214 ++ contrib/hooks/update-paranoid | 421 +++ contrib/long-running-filter/example.pl | 132 + contrib/mw-to-git/.gitignore | 2 + contrib/mw-to-git/.perlcriticrc | 28 + contrib/mw-to-git/Git/Mediawiki.pm | 101 + contrib/mw-to-git/Makefile | 58 + contrib/mw-to-git/bin-wrapper/git | 14 + contrib/mw-to-git/git-mw.perl | 368 ++ contrib/mw-to-git/git-remote-mediawiki.perl | 1390 ++++++++ contrib/mw-to-git/git-remote-mediawiki.txt | 7 + contrib/mw-to-git/t/.gitignore | 4 + contrib/mw-to-git/t/Makefile | 31 + contrib/mw-to-git/t/README | 124 + contrib/mw-to-git/t/install-wiki.sh | 55 + contrib/mw-to-git/t/push-pull-tests.sh | 144 + contrib/mw-to-git/t/t9360-mw-to-git-clone.sh | 257 ++ contrib/mw-to-git/t/t9361-mw-to-git-push-pull.sh | 24 + contrib/mw-to-git/t/t9362-mw-to-git-utf8.sh | 347 ++ .../mw-to-git/t/t9363-mw-to-git-export-import.sh | 218 ++ contrib/mw-to-git/t/t9364-pull-by-rev.sh | 17 + contrib/mw-to-git/t/t9365-continuing-queries.sh | 23 + contrib/mw-to-git/t/test-gitmw-lib.sh | 432 +++ contrib/mw-to-git/t/test-gitmw.pl | 223 ++ contrib/mw-to-git/t/test.config | 40 + contrib/persistent-https/LICENSE | 202 ++ contrib/persistent-https/Makefile | 40 + contrib/persistent-https/README | 72 + contrib/persistent-https/client.go | 189 ++ contrib/persistent-https/main.go | 82 + contrib/persistent-https/proxy.go | 190 ++ contrib/persistent-https/socket.go | 97 + contrib/remote-helpers/README | 15 + contrib/remote-helpers/git-remote-bzr | 11 + contrib/remote-helpers/git-remote-hg | 11 + contrib/remotes2config.sh | 33 + contrib/rerere-train.sh | 102 + contrib/stats/git-common-hash | 26 + contrib/stats/mailmap.pl | 70 + contrib/stats/packinfo.pl | 212 ++ contrib/subtree/.gitignore | 7 + contrib/subtree/COPYING | 339 ++ contrib/subtree/INSTALL | 28 + contrib/subtree/Makefile | 103 + contrib/subtree/README | 8 + contrib/subtree/git-subtree.sh | 1092 ++++++ contrib/subtree/git-subtree.txt | 353 ++ contrib/subtree/t/Makefile | 87 + contrib/subtree/t/t7900-subtree.sh | 1526 +++++++++ contrib/subtree/todo | 48 + contrib/thunderbird-patch-inline/README | 20 + contrib/thunderbird-patch-inline/appp.sh | 55 + contrib/update-unicode/.gitignore | 3 + contrib/update-unicode/README | 20 + contrib/update-unicode/update_unicode.sh | 33 + contrib/vscode/.gitattributes | 1 + contrib/vscode/README.md | 18 + contrib/vscode/init.sh | 378 +++ contrib/workdir/.gitattributes | 1 + contrib/workdir/git-new-workdir | 105 + 152 files changed, 25130 insertions(+) create mode 100644 contrib/README create mode 100644 contrib/buildsystems/CMakeLists.txt create mode 100644 contrib/buildsystems/Generators.pm create mode 100644 contrib/buildsystems/Generators/QMake.pm create mode 100644 contrib/buildsystems/Generators/Vcproj.pm create mode 100644 contrib/buildsystems/Generators/Vcxproj.pm create mode 100755 contrib/buildsystems/engine.pl create mode 100755 contrib/buildsystems/generate create mode 100755 contrib/buildsystems/parse.pl create mode 100644 contrib/coccinelle/.gitignore create mode 100644 contrib/coccinelle/README create mode 100644 contrib/coccinelle/array.cocci create mode 100644 contrib/coccinelle/commit.cocci create mode 100644 contrib/coccinelle/equals-null.cocci create mode 100644 contrib/coccinelle/flex_alloc.cocci create mode 100644 contrib/coccinelle/free.cocci create mode 100644 contrib/coccinelle/hashmap.cocci create mode 100644 contrib/coccinelle/index-compatibility.cocci create mode 100644 contrib/coccinelle/index-compatibility.pending.cocci create mode 100644 contrib/coccinelle/object_id.cocci create mode 100644 contrib/coccinelle/preincr.cocci create mode 100644 contrib/coccinelle/qsort.cocci create mode 100755 contrib/coccinelle/spatchcache create mode 100644 contrib/coccinelle/strbuf.cocci create mode 100644 contrib/coccinelle/swap.cocci create mode 100644 contrib/coccinelle/tests/free.c create mode 100644 contrib/coccinelle/tests/free.res create mode 100644 contrib/coccinelle/tests/unused.c create mode 100644 contrib/coccinelle/tests/unused.res create mode 100644 contrib/coccinelle/the_repository.pending.cocci create mode 100644 contrib/coccinelle/unused.cocci create mode 100644 contrib/coccinelle/xcalloc.cocci create mode 100644 contrib/coccinelle/xopen.cocci create mode 100644 contrib/coccinelle/xstrdup_or_null.cocci create mode 100644 contrib/completion/.gitattributes create mode 100644 contrib/completion/git-completion.bash create mode 100644 contrib/completion/git-completion.tcsh create mode 100644 contrib/completion/git-completion.zsh create mode 100644 contrib/completion/git-prompt.sh create mode 100644 contrib/contacts/.gitignore create mode 100644 contrib/contacts/Makefile create mode 100755 contrib/contacts/git-contacts create mode 100644 contrib/contacts/git-contacts.txt create mode 100755 contrib/coverage-diff.sh create mode 100644 contrib/credential/gnome-keyring/.gitignore create mode 100644 contrib/credential/gnome-keyring/Makefile create mode 100644 contrib/credential/gnome-keyring/git-credential-gnome-keyring.c create mode 100644 contrib/credential/libsecret/Makefile create mode 100644 contrib/credential/libsecret/git-credential-libsecret.c create mode 100644 contrib/credential/netrc/.gitignore create mode 100644 contrib/credential/netrc/Makefile create mode 100755 contrib/credential/netrc/git-credential-netrc.perl create mode 100755 contrib/credential/netrc/t-git-credential-netrc.sh create mode 100755 contrib/credential/netrc/test.command-option-gpg create mode 100755 contrib/credential/netrc/test.git-config-gpg create mode 100644 contrib/credential/netrc/test.netrc create mode 100644 contrib/credential/netrc/test.netrc.gpg create mode 100755 contrib/credential/netrc/test.pl create mode 100644 contrib/credential/osxkeychain/.gitignore create mode 100644 contrib/credential/osxkeychain/Makefile create mode 100644 contrib/credential/osxkeychain/git-credential-osxkeychain.c create mode 100644 contrib/credential/wincred/Makefile create mode 100644 contrib/credential/wincred/git-credential-wincred.c create mode 100644 contrib/diff-highlight/.gitignore create mode 100644 contrib/diff-highlight/DiffHighlight.pm create mode 100644 contrib/diff-highlight/Makefile create mode 100644 contrib/diff-highlight/README create mode 100644 contrib/diff-highlight/diff-highlight.perl create mode 100644 contrib/diff-highlight/t/.gitignore create mode 100644 contrib/diff-highlight/t/Makefile create mode 100755 contrib/diff-highlight/t/t9400-diff-highlight.sh create mode 100644 contrib/emacs/README create mode 100644 contrib/emacs/git-blame.el create mode 100644 contrib/emacs/git.el create mode 100644 contrib/examples/README create mode 100755 contrib/fast-import/git-import.perl create mode 100755 contrib/fast-import/git-import.sh create mode 100644 contrib/fast-import/git-p4.README create mode 100755 contrib/fast-import/import-directories.perl create mode 100755 contrib/fast-import/import-tars.perl create mode 100755 contrib/fast-import/import-zips.py create mode 100644 contrib/git-jump/README create mode 100755 contrib/git-jump/git-jump create mode 100755 contrib/git-resurrect.sh create mode 100644 contrib/git-shell-commands/README create mode 100755 contrib/git-shell-commands/help create mode 100755 contrib/git-shell-commands/list create mode 100755 contrib/hg-to-git/hg-to-git.py create mode 100644 contrib/hg-to-git/hg-to-git.txt create mode 100644 contrib/hooks/multimail/README.Git create mode 100755 contrib/hooks/post-receive-email create mode 100755 contrib/hooks/pre-auto-gc-battery create mode 100755 contrib/hooks/setgitperms.perl create mode 100755 contrib/hooks/update-paranoid create mode 100755 contrib/long-running-filter/example.pl create mode 100644 contrib/mw-to-git/.gitignore create mode 100644 contrib/mw-to-git/.perlcriticrc create mode 100644 contrib/mw-to-git/Git/Mediawiki.pm create mode 100644 contrib/mw-to-git/Makefile create mode 100755 contrib/mw-to-git/bin-wrapper/git create mode 100755 contrib/mw-to-git/git-mw.perl create mode 100755 contrib/mw-to-git/git-remote-mediawiki.perl create mode 100644 contrib/mw-to-git/git-remote-mediawiki.txt create mode 100644 contrib/mw-to-git/t/.gitignore create mode 100644 contrib/mw-to-git/t/Makefile create mode 100644 contrib/mw-to-git/t/README create mode 100755 contrib/mw-to-git/t/install-wiki.sh create mode 100644 contrib/mw-to-git/t/push-pull-tests.sh create mode 100755 contrib/mw-to-git/t/t9360-mw-to-git-clone.sh create mode 100755 contrib/mw-to-git/t/t9361-mw-to-git-push-pull.sh create mode 100755 contrib/mw-to-git/t/t9362-mw-to-git-utf8.sh create mode 100755 contrib/mw-to-git/t/t9363-mw-to-git-export-import.sh create mode 100755 contrib/mw-to-git/t/t9364-pull-by-rev.sh create mode 100755 contrib/mw-to-git/t/t9365-continuing-queries.sh create mode 100755 contrib/mw-to-git/t/test-gitmw-lib.sh create mode 100755 contrib/mw-to-git/t/test-gitmw.pl create mode 100644 contrib/mw-to-git/t/test.config create mode 100644 contrib/persistent-https/LICENSE create mode 100644 contrib/persistent-https/Makefile create mode 100644 contrib/persistent-https/README create mode 100644 contrib/persistent-https/client.go create mode 100644 contrib/persistent-https/main.go create mode 100644 contrib/persistent-https/proxy.go create mode 100644 contrib/persistent-https/socket.go create mode 100644 contrib/remote-helpers/README create mode 100755 contrib/remote-helpers/git-remote-bzr create mode 100755 contrib/remote-helpers/git-remote-hg create mode 100755 contrib/remotes2config.sh create mode 100755 contrib/rerere-train.sh create mode 100755 contrib/stats/git-common-hash create mode 100755 contrib/stats/mailmap.pl create mode 100755 contrib/stats/packinfo.pl create mode 100644 contrib/subtree/.gitignore create mode 100644 contrib/subtree/COPYING create mode 100644 contrib/subtree/INSTALL create mode 100644 contrib/subtree/Makefile create mode 100644 contrib/subtree/README create mode 100755 contrib/subtree/git-subtree.sh create mode 100644 contrib/subtree/git-subtree.txt create mode 100644 contrib/subtree/t/Makefile create mode 100755 contrib/subtree/t/t7900-subtree.sh create mode 100644 contrib/subtree/todo create mode 100644 contrib/thunderbird-patch-inline/README create mode 100755 contrib/thunderbird-patch-inline/appp.sh create mode 100644 contrib/update-unicode/.gitignore create mode 100644 contrib/update-unicode/README create mode 100755 contrib/update-unicode/update_unicode.sh create mode 100644 contrib/vscode/.gitattributes create mode 100644 contrib/vscode/README.md create mode 100755 contrib/vscode/init.sh create mode 100644 contrib/workdir/.gitattributes create mode 100755 contrib/workdir/git-new-workdir (limited to 'contrib') diff --git a/contrib/README b/contrib/README new file mode 100644 index 0000000..05f291c --- /dev/null +++ b/contrib/README @@ -0,0 +1,43 @@ +Contributed Software + +Although these pieces are available as part of the official git +source tree, they are in somewhat different status. The +intention is to keep interesting tools around git here, maybe +even experimental ones, to give users an easier access to them, +and to give tools wider exposure, so that they can be improved +faster. + +I am not expecting to touch these myself that much. As far as +my day-to-day operation is concerned, these subdirectories are +owned by their respective primary authors. I am willing to help +if users of these components and the contrib/ subtree "owners" +have technical/design issues to resolve, but the initiative to +fix and/or enhance things _must_ be on the side of the subtree +owners. IOW, I won't be actively looking for bugs and rooms for +enhancements in them as the git maintainer -- I may only do so +just as one of the users when I want to scratch my own itch. If +you have patches to things in contrib/ area, the patch should be +first sent to the primary author, and then the primary author +should ack and forward it to me (git pull request is nicer). +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 +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 +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 +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 +of general interest for people who need to interoperate with SVN +repositories in a way git-svn works better than git-svnimport), +submit a patch to create a subdirectory of contrib/ and put your +stuff there. + +-jc diff --git a/contrib/buildsystems/CMakeLists.txt b/contrib/buildsystems/CMakeLists.txt new file mode 100644 index 0000000..2f6e019 --- /dev/null +++ b/contrib/buildsystems/CMakeLists.txt @@ -0,0 +1,1100 @@ +# +# Copyright (c) 2020 Sibi Siddharthan +# + +#[[ + +Instructions how to use this in Visual Studio: + +Open the worktree as a folder. Visual Studio 2019 and later will detect +the CMake configuration automatically and set everything up for you, +ready to build. You can then run the tests in `t/` via a regular Git Bash. + +Note: Visual Studio also has the option of opening `CMakeLists.txt` +directly; Using this option, Visual Studio will not find the source code, +though, therefore the `File>Open>Folder...` option is preferred. + +Instructions to run CMake manually: + + mkdir -p contrib/buildsystems/out + cd contrib/buildsystems/out + cmake ../ -DCMAKE_BUILD_TYPE=Release + +This will build the git binaries in contrib/buildsystems/out +directory (our top-level .gitignore file knows to ignore contents of +this directory). + +Possible build configurations(-DCMAKE_BUILD_TYPE) with corresponding +compiler flags +Debug : -g +Release: -O3 +RelWithDebInfo : -O2 -g +MinSizeRel : -Os +empty(default) : + +NOTE: -DCMAKE_BUILD_TYPE is optional. For multi-config generators like Visual Studio +this option is ignored + +This process generates a Makefile(Linux/*BSD/MacOS) , Visual Studio solution(Windows) by default. +Run `make` to build Git on Linux/*BSD/MacOS. +Open git.sln on Windows and build Git. + +NOTE: By default CMake uses Makefile as the build tool on Linux and Visual Studio in Windows, +to use another tool say `ninja` add this to the command line when configuring. +`-G Ninja` + +NOTE: By default CMake will install vcpkg locally to your source tree on configuration, +to avoid this, add `-DNO_VCPKG=TRUE` to the command line when configuring. + +]] +cmake_minimum_required(VERSION 3.14) + +#set the source directory to root of git +set(CMAKE_SOURCE_DIR ${CMAKE_CURRENT_LIST_DIR}/../..) + +option(USE_VCPKG "Whether or not to use vcpkg for obtaining dependencies. Only applicable to Windows platforms" ON) +if(NOT WIN32) + set(USE_VCPKG OFF CACHE BOOL "" FORCE) +endif() + +if(NOT DEFINED CMAKE_EXPORT_COMPILE_COMMANDS) + set(CMAKE_EXPORT_COMPILE_COMMANDS TRUE) +endif() + +if(USE_VCPKG) + set(VCPKG_DIR "${CMAKE_SOURCE_DIR}/compat/vcbuild/vcpkg") + if(NOT EXISTS ${VCPKG_DIR}) + message("Initializing vcpkg and building the Git's dependencies (this will take a while...)") + execute_process(COMMAND ${CMAKE_SOURCE_DIR}/compat/vcbuild/vcpkg_install.bat) + endif() + list(APPEND CMAKE_PREFIX_PATH "${VCPKG_DIR}/installed/x64-windows") + + # In the vcpkg edition, we need this to be able to link to libcurl + set(CURL_NO_CURL_CMAKE ON) + + # Copy the necessary vcpkg DLLs (like iconv) to the install dir + set(X_VCPKG_APPLOCAL_DEPS_INSTALL ON) + set(CMAKE_TOOLCHAIN_FILE ${VCPKG_DIR}/scripts/buildsystems/vcpkg.cmake CACHE STRING "Vcpkg toolchain file") +endif() + +find_program(SH_EXE sh PATHS "C:/Program Files/Git/bin" "$ENV{LOCALAPPDATA}/Programs/Git/bin") +if(NOT SH_EXE) + message(FATAL_ERROR "sh: shell interpreter was not found in your path, please install one." + "On Windows, you can get it as part of 'Git for Windows' install at https://gitforwindows.org/") +endif() + +#Create GIT-VERSION-FILE using GIT-VERSION-GEN +if(NOT EXISTS ${CMAKE_SOURCE_DIR}/GIT-VERSION-FILE) + message("Generating GIT-VERSION-FILE") + execute_process(COMMAND ${SH_EXE} ${CMAKE_SOURCE_DIR}/GIT-VERSION-GEN + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}) +endif() + +#Parse GIT-VERSION-FILE to get the version +file(STRINGS ${CMAKE_SOURCE_DIR}/GIT-VERSION-FILE git_version REGEX "GIT_VERSION = (.*)") +string(REPLACE "GIT_VERSION = " "" git_version ${git_version}) +string(FIND ${git_version} "GIT" location) +if(location EQUAL -1) + string(REGEX MATCH "[0-9]*\\.[0-9]*\\.[0-9]*" git_version ${git_version}) +else() + string(REGEX MATCH "[0-9]*\\.[0-9]*" git_version ${git_version}) + string(APPEND git_version ".0") #for building from a snapshot +endif() + +project(git + VERSION ${git_version} + LANGUAGES C) + + +#TODO gitk git-gui gitweb +#TODO Enable NLS on windows natively + +#macros for parsing the Makefile for sources and scripts +macro(parse_makefile_for_sources list_var regex) + file(STRINGS ${CMAKE_SOURCE_DIR}/Makefile ${list_var} REGEX "^${regex} \\+=(.*)") + string(REPLACE "${regex} +=" "" ${list_var} ${${list_var}}) + string(REPLACE "$(COMPAT_OBJS)" "" ${list_var} ${${list_var}}) #remove "$(COMPAT_OBJS)" This is only for libgit. + string(STRIP ${${list_var}} ${list_var}) #remove trailing/leading whitespaces + string(REPLACE ".o" ".c;" ${list_var} ${${list_var}}) #change .o to .c, ; is for converting the string into a list + list(TRANSFORM ${list_var} STRIP) #remove trailing/leading whitespaces for each element in list + list(REMOVE_ITEM ${list_var} "") #remove empty list elements +endmacro() + +macro(parse_makefile_for_scripts list_var regex lang) + file(STRINGS ${CMAKE_SOURCE_DIR}/Makefile ${list_var} REGEX "^${regex} \\+=(.*)") + string(REPLACE "${regex} +=" "" ${list_var} ${${list_var}}) + string(STRIP ${${list_var}} ${list_var}) #remove trailing/leading whitespaces + string(REPLACE " " ";" ${list_var} ${${list_var}}) #convert string to a list + if(NOT ${lang}) #exclude for SCRIPT_LIB + list(TRANSFORM ${list_var} REPLACE "${lang}" "") #do the replacement + endif() +endmacro() + +macro(parse_makefile_for_executables list_var regex) + file(STRINGS ${CMAKE_SOURCE_DIR}/Makefile ${list_var} REGEX "^${regex} \\+= git-(.*)") + string(REPLACE "${regex} +=" "" ${list_var} ${${list_var}}) + string(STRIP ${${list_var}} ${list_var}) #remove trailing/leading whitespaces + string(REPLACE "git-" "" ${list_var} ${${list_var}}) #strip `git-` prefix + string(REPLACE "\$X" ";" ${list_var} ${${list_var}}) #strip $X, ; is for converting the string into a list + list(TRANSFORM ${list_var} STRIP) #remove trailing/leading whitespaces for each element in list + list(REMOVE_ITEM ${list_var} "") #remove empty list elements +endmacro() + +include(CheckTypeSize) +include(CheckCSourceRuns) +include(CheckCSourceCompiles) +include(CheckIncludeFile) +include(CheckFunctionExists) +include(CheckSymbolExists) +include(CheckStructHasMember) +include(CTest) + +find_package(ZLIB REQUIRED) +find_package(CURL) +find_package(EXPAT) +find_package(Iconv) + +#Don't use libintl on Windows Visual Studio and Clang builds +if(NOT (WIN32 AND (CMAKE_C_COMPILER_ID STREQUAL "MSVC" OR CMAKE_C_COMPILER_ID STREQUAL "Clang"))) + find_package(Intl) +endif() + +find_package(PkgConfig) +if(PkgConfig_FOUND) + pkg_check_modules(PCRE2 libpcre2-8) + if(PCRE2_FOUND) + add_compile_definitions(USE_LIBPCRE2) + endif() +endif() + +if(NOT Intl_FOUND) + add_compile_definitions(NO_GETTEXT) + if(NOT Iconv_FOUND) + add_compile_definitions(NO_ICONV) + endif() +endif() + +include_directories(SYSTEM ${ZLIB_INCLUDE_DIRS}) +if(CURL_FOUND) + include_directories(SYSTEM ${CURL_INCLUDE_DIRS}) +endif() +if(EXPAT_FOUND) + include_directories(SYSTEM ${EXPAT_INCLUDE_DIRS}) +endif() +if(Iconv_FOUND) + include_directories(SYSTEM ${Iconv_INCLUDE_DIRS}) +endif() +if(Intl_FOUND) + include_directories(SYSTEM ${Intl_INCLUDE_DIRS}) +endif() +if(PCRE2_FOUND) + include_directories(SYSTEM ${PCRE2_INCLUDE_DIRS}) +endif() + + +if(WIN32 AND NOT MSVC)#not required for visual studio builds + find_program(WINDRES_EXE windres) + if(NOT WINDRES_EXE) + message(FATAL_ERROR "Install windres on Windows for resource files") + endif() +endif() + +if(NO_GETTEXT) + message(STATUS "msgfmt not used under NO_GETTEXT") +else() + find_program(MSGFMT_EXE msgfmt) + if(NOT MSGFMT_EXE) + if(USE_VCPKG) + set(MSGFMT_EXE ${CMAKE_SOURCE_DIR}/compat/vcbuild/vcpkg/downloads/tools/msys2/msys64/usr/bin/msgfmt.exe) + endif() + if(NOT EXISTS ${MSGFMT_EXE}) + message(WARNING "Text Translations won't be built") + unset(MSGFMT_EXE) + endif() + endif() +endif() + +#Force all visual studio outputs to CMAKE_BINARY_DIR +if(CMAKE_C_COMPILER_ID STREQUAL "MSVC") + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}) + set(CMAKE_RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}) + add_compile_options(/MP /std:c11) +endif() + +#default behaviour +include_directories(${CMAKE_SOURCE_DIR}) +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_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) + + +add_compile_definitions(PAGER_ENV="LESS=FRX LV=-c" + GIT_EXEC_PATH="libexec/git-core" + GIT_LOCALE_PATH="share/locale" + GIT_MAN_PATH="share/man" + GIT_INFO_PATH="share/info" + GIT_HTML_PATH="share/doc/git-doc" + DEFAULT_HELP_FORMAT="html" + DEFAULT_GIT_TEMPLATE_DIR="share/git-core/templates" + GIT_VERSION="${PROJECT_VERSION}.GIT" + GIT_USER_AGENT="git/${PROJECT_VERSION}.GIT" + BINDIR="bin" + GIT_BUILT_FROM_COMMIT="") + +if(WIN32) + set(FALLBACK_RUNTIME_PREFIX /mingw64) + # Move system config into top-level /etc/ + add_compile_definitions(FALLBACK_RUNTIME_PREFIX="${FALLBACK_RUNTIME_PREFIX}" + ETC_GITATTRIBUTES="../etc/gitattributes" + ETC_GITCONFIG="../etc/gitconfig") +else() + set(FALLBACK_RUNTIME_PREFIX /home/$ENV{USER}) + add_compile_definitions(FALLBACK_RUNTIME_PREFIX="${FALLBACK_RUNTIME_PREFIX}" + ETC_GITATTRIBUTES="etc/gitattributes" + ETC_GITCONFIG="etc/gitconfig") +endif() + + +#Platform Specific +if(CMAKE_SYSTEM_NAME STREQUAL "Windows") + if(CMAKE_C_COMPILER_ID STREQUAL "MSVC" OR CMAKE_C_COMPILER_ID STREQUAL "Clang") + include_directories(${CMAKE_SOURCE_DIR}/compat/vcbuild/include) + add_compile_definitions(_CRT_SECURE_NO_WARNINGS _CRT_NONSTDC_NO_DEPRECATE) + endif() + include_directories(${CMAKE_SOURCE_DIR}/compat/win32) + add_compile_definitions(HAVE_ALLOCA_H NO_POSIX_GOODIES NATIVE_CRLF NO_UNIX_SOCKETS WIN32 + _CONSOLE DETECT_MSYS_TTY STRIP_EXTENSION=".exe" NO_SYMLINK_HEAD UNRELIABLE_FSTAT + NOGDI OBJECT_CREATION_MODE=1 __USE_MINGW_ANSI_STDIO=0 + USE_NED_ALLOCATOR OVERRIDE_STRDUP MMAP_PREVENTS_DELETE USE_WIN32_MMAP + HAVE_WPGMPTR ENSURE_MSYSTEM_IS_SET HAVE_RTLGENRANDOM) + list(APPEND compat_SOURCES + compat/mingw.c + compat/winansi.c + compat/win32/flush.c + compat/win32/path-utils.c + compat/win32/pthread.c + compat/win32mmap.c + compat/win32/syslog.c + compat/win32/trace2_win32_process_info.c + compat/win32/dirent.c + compat/nedmalloc/nedmalloc.c + compat/strdup.c) + set(NO_UNIX_SOCKETS 1) + +elseif(CMAKE_SYSTEM_NAME STREQUAL "Linux") + add_compile_definitions(PROCFS_EXECUTABLE_PATH="/proc/self/exe" HAVE_DEV_TTY ) + list(APPEND compat_SOURCES unix-socket.c unix-stream-server.c compat/linux/procinfo.c) +endif() + +if(CMAKE_SYSTEM_NAME STREQUAL "Windows") + list(APPEND compat_SOURCES compat/simple-ipc/ipc-shared.c compat/simple-ipc/ipc-win32.c) + add_compile_definitions(SUPPORTS_SIMPLE_IPC) + set(SUPPORTS_SIMPLE_IPC 1) +else() + # Simple IPC requires both Unix sockets and pthreads on Unix-based systems. + if(NOT NO_UNIX_SOCKETS AND NOT NO_PTHREADS) + list(APPEND compat_SOURCES compat/simple-ipc/ipc-shared.c compat/simple-ipc/ipc-unix-socket.c) + add_compile_definitions(SUPPORTS_SIMPLE_IPC) + set(SUPPORTS_SIMPLE_IPC 1) + endif() +endif() + +if(SUPPORTS_SIMPLE_IPC) + if(CMAKE_SYSTEM_NAME STREQUAL "Windows") + 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) + elseif(CMAKE_SYSTEM_NAME STREQUAL "Darwin") + 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) + endif() +endif() + +set(EXE_EXTENSION ${CMAKE_EXECUTABLE_SUFFIX}) + +#header checks +check_include_file(libgen.h HAVE_LIBGEN_H) +if(NOT HAVE_LIBGEN_H) + add_compile_definitions(NO_LIBGEN_H) + list(APPEND compat_SOURCES compat/basename.c) +endif() + +check_include_file(sys/sysinfo.h HAVE_SYSINFO) +if(HAVE_SYSINFO) + add_compile_definitions(HAVE_SYSINFO) +endif() + +check_c_source_compiles(" +#include + +int main(void) +{ + char *p = (char *) alloca(2 * sizeof(int)); + + if (p) + return 0; + return 0; +}" +HAVE_ALLOCA_H) +if(HAVE_ALLOCA_H) + add_compile_definitions(HAVE_ALLOCA_H) +endif() + +check_include_file(strings.h HAVE_STRINGS_H) +if(HAVE_STRINGS_H) + add_compile_definitions(HAVE_STRINGS_H) +endif() + +check_include_file(sys/select.h HAVE_SYS_SELECT_H) +if(NOT HAVE_SYS_SELECT_H) + add_compile_definitions(NO_SYS_SELECT_H) +endif() + +check_include_file(sys/poll.h HAVE_SYS_POLL_H) +if(NOT HAVE_SYS_POLL_H) + add_compile_definitions(NO_SYS_POLL_H) +endif() + +check_include_file(poll.h HAVE_POLL_H) +if(NOT HAVE_POLL_H) + add_compile_definitions(NO_POLL_H) +endif() + +check_include_file(inttypes.h HAVE_INTTYPES_H) +if(NOT HAVE_INTTYPES_H) + add_compile_definitions(NO_INTTYPES_H) +endif() + +check_include_file(paths.h HAVE_PATHS_H) +if(HAVE_PATHS_H) + add_compile_definitions(HAVE_PATHS_H) +endif() + +#function checks +set(function_checks + strcasestr memmem strlcpy strtoimax strtoumax strtoull + setenv mkdtemp poll pread memmem) + +#unsetenv,hstrerror are incompatible with windows build +if(NOT WIN32) + list(APPEND function_checks unsetenv hstrerror) +endif() + +foreach(f ${function_checks}) + string(TOUPPER ${f} uf) + check_function_exists(${f} HAVE_${uf}) + if(NOT HAVE_${uf}) + add_compile_definitions(NO_${uf}) + endif() +endforeach() + +if(NOT HAVE_POLL_H OR NOT HAVE_SYS_POLL_H OR NOT HAVE_POLL) + include_directories(${CMAKE_SOURCE_DIR}/compat/poll) + add_compile_definitions(NO_POLL) + list(APPEND compat_SOURCES compat/poll/poll.c) +endif() + +if(NOT HAVE_STRCASESTR) + list(APPEND compat_SOURCES compat/strcasestr.c) +endif() + +if(NOT HAVE_STRLCPY) + list(APPEND compat_SOURCES compat/strlcpy.c) +endif() + +if(NOT HAVE_STRTOUMAX) + list(APPEND compat_SOURCES compat/strtoumax.c compat/strtoimax.c) +endif() + +if(NOT HAVE_SETENV) + list(APPEND compat_SOURCES compat/setenv.c) +endif() + +if(NOT HAVE_MKDTEMP) + list(APPEND compat_SOURCES compat/mkdtemp.c) +endif() + +if(NOT HAVE_PREAD) + list(APPEND compat_SOURCES compat/pread.c) +endif() + +if(NOT HAVE_MEMMEM) + list(APPEND compat_SOURCES compat/memmem.c) +endif() + +if(NOT WIN32) + if(NOT HAVE_UNSETENV) + list(APPEND compat_SOURCES compat/unsetenv.c) + endif() + + if(NOT HAVE_HSTRERROR) + list(APPEND compat_SOURCES compat/hstrerror.c) + endif() +endif() + +check_function_exists(getdelim HAVE_GETDELIM) +if(HAVE_GETDELIM) + add_compile_definitions(HAVE_GETDELIM) +endif() + +check_function_exists(clock_gettime HAVE_CLOCK_GETTIME) +check_symbol_exists(CLOCK_MONOTONIC "time.h" HAVE_CLOCK_MONOTONIC) +if(HAVE_CLOCK_GETTIME) + add_compile_definitions(HAVE_CLOCK_GETTIME) +endif() +if(HAVE_CLOCK_MONOTONIC) + add_compile_definitions(HAVE_CLOCK_MONOTONIC) +endif() + +#check for st_blocks in struct stat +check_struct_has_member("struct stat" st_blocks "sys/stat.h" STRUCT_STAT_HAS_ST_BLOCKS) +if(NOT STRUCT_STAT_HAS_ST_BLOCKS) + add_compile_definitions(NO_ST_BLOCKS_IN_STRUCT_STAT) +endif() + +#compile checks +check_c_source_runs(" +#include +#include +#include +#include + +int test_vsnprintf(char *str, size_t maxsize, const char *format, ...) +{ + int ret; + va_list ap; + + va_start(ap, format); + ret = vsnprintf(str, maxsize, format, ap); + va_end(ap); + return ret; +} + +int main(void) +{ + char buf[6]; + + if (test_vsnprintf(buf, 3, \"%s\", \"12345\") != 5 + || strcmp(buf, \"12\")) + return 1; + if (snprintf(buf, 3, \"%s\", \"12345\") != 5 + || strcmp(buf, \"12\")) + return 1; + return 0; +}" +SNPRINTF_OK) +if(NOT SNPRINTF_OK) + add_compile_definitions(SNPRINTF_RETURNS_BOGUS) + list(APPEND compat_SOURCES compat/snprintf.c) +endif() + +check_c_source_runs(" +#include + +int main(void) +{ + FILE *f = fopen(\".\", \"r\"); + + return f != NULL; +}" +FREAD_READS_DIRECTORIES_NO) +if(NOT FREAD_READS_DIRECTORIES_NO) + add_compile_definitions(FREAD_READS_DIRECTORIES) + list(APPEND compat_SOURCES compat/fopen.c) +endif() + +check_c_source_compiles(" +#include +#ifndef REG_STARTEND +#error oops we dont have it +#endif + +int main(void) +{ + return 0; +}" +HAVE_REGEX) +if(NOT HAVE_REGEX) + include_directories(${CMAKE_SOURCE_DIR}/compat/regex) + list(APPEND compat_SOURCES compat/regex/regex.c ) + add_compile_definitions(NO_REGEX NO_MBSUPPORT GAWK) +endif() + + +check_c_source_compiles(" +#include +#include +#include + +int main(void) +{ + int val, mib[2]; + size_t len; + + mib[0] = CTL_HW; + mib[1] = 1; + len = sizeof(val); + return sysctl(mib, 2, &val, &len, NULL, 0) ? 1 : 0; +}" +HAVE_BSD_SYSCTL) +if(HAVE_BSD_SYSCTL) + add_compile_definitions(HAVE_BSD_SYSCTL) +endif() + +set(CMAKE_REQUIRED_LIBRARIES ${Iconv_LIBRARIES}) +set(CMAKE_REQUIRED_INCLUDES ${Iconv_INCLUDE_DIRS}) + +check_c_source_compiles(" +#include + +extern size_t iconv(iconv_t cd, + char **inbuf, size_t *inbytesleft, + char **outbuf, size_t *outbytesleft); + +int main(void) +{ + return 0; +}" +HAVE_NEW_ICONV) +if(HAVE_NEW_ICONV) + set(HAVE_OLD_ICONV 0) +else() + set(HAVE_OLD_ICONV 1) +endif() + +check_c_source_runs(" +#include +#if ${HAVE_OLD_ICONV} +typedef const char *iconv_ibp; +#else +typedef char *iconv_ibp; +#endif + +int main(void) +{ + int v; + iconv_t conv; + char in[] = \"a\"; + iconv_ibp pin = in; + char out[20] = \"\"; + char *pout = out; + size_t isz = sizeof(in); + size_t osz = sizeof(out); + + conv = iconv_open(\"UTF-16\", \"UTF-8\"); + iconv(conv, &pin, &isz, &pout, &osz); + iconv_close(conv); + v = (unsigned char)(out[0]) + (unsigned char)(out[1]); + return v != 0xfe + 0xff; +}" +ICONV_DOESNOT_OMIT_BOM) +if(NOT ICONV_DOESNOT_OMIT_BOM) + add_compile_definitions(ICONV_OMITS_BOM) +endif() + +unset(CMAKE_REQUIRED_LIBRARIES) +unset(CMAKE_REQUIRED_INCLUDES) + + +#programs +set(PROGRAMS_BUILT + git git-daemon git-http-backend git-sh-i18n--envsubst + git-shell scalar) + +if(NOT CURL_FOUND) + list(APPEND excluded_progs git-http-fetch git-http-push) + add_compile_definitions(NO_CURL) + message(WARNING "git-http-push and git-http-fetch will not be built") +else() + list(APPEND PROGRAMS_BUILT git-http-fetch git-http-push git-imap-send git-remote-http) + if(CURL_VERSION_STRING VERSION_GREATER_EQUAL 7.34.0) + add_compile_definitions(USE_CURL_FOR_IMAP_SEND) + endif() +endif() + +if(NOT EXPAT_FOUND) + list(APPEND excluded_progs git-http-push) + add_compile_definitions(NO_EXPAT) +else() + list(APPEND PROGRAMS_BUILT git-http-push) + if(EXPAT_VERSION_STRING VERSION_LESS_EQUAL 1.2) + add_compile_definitions(EXPAT_NEEDS_XMLPARSE_H) + endif() +endif() + +list(REMOVE_DUPLICATES excluded_progs) +list(REMOVE_DUPLICATES PROGRAMS_BUILT) + + +foreach(p ${excluded_progs}) + list(APPEND EXCLUSION_PROGS --exclude-program ${p} ) +endforeach() + +#for comparing null values +list(APPEND EXCLUSION_PROGS empty) +set(EXCLUSION_PROGS_CACHE ${EXCLUSION_PROGS} CACHE STRING "Programs not built" FORCE) + +if(NOT EXISTS ${CMAKE_BINARY_DIR}/command-list.h OR NOT EXCLUSION_PROGS_CACHE STREQUAL EXCLUSION_PROGS) + list(REMOVE_ITEM EXCLUSION_PROGS empty) + message("Generating command-list.h") + execute_process(COMMAND ${SH_EXE} ${CMAKE_SOURCE_DIR}/generate-cmdlist.sh ${EXCLUSION_PROGS} command-list.txt + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_FILE ${CMAKE_BINARY_DIR}/command-list.h) +endif() + +if(NOT EXISTS ${CMAKE_BINARY_DIR}/config-list.h) + message("Generating config-list.h") + execute_process(COMMAND ${SH_EXE} ${CMAKE_SOURCE_DIR}/generate-configlist.sh + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_FILE ${CMAKE_BINARY_DIR}/config-list.h) +endif() + +if(NOT EXISTS ${CMAKE_BINARY_DIR}/hook-list.h) + message("Generating hook-list.h") + execute_process(COMMAND ${SH_EXE} ${CMAKE_SOURCE_DIR}/generate-hooklist.sh + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + OUTPUT_FILE ${CMAKE_BINARY_DIR}/hook-list.h) +endif() + +include_directories(${CMAKE_BINARY_DIR}) + +#build +#libgit +parse_makefile_for_sources(libgit_SOURCES "LIB_OBJS") + +list(TRANSFORM libgit_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/") +list(TRANSFORM compat_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/") +add_library(libgit ${libgit_SOURCES} ${compat_SOURCES}) + +#libxdiff +parse_makefile_for_sources(libxdiff_SOURCES "XDIFF_OBJS") + +list(TRANSFORM libxdiff_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/") +add_library(xdiff STATIC ${libxdiff_SOURCES}) + +#reftable +parse_makefile_for_sources(reftable_SOURCES "REFTABLE_OBJS") + +list(TRANSFORM reftable_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/") +add_library(reftable STATIC ${reftable_SOURCES}) + +if(WIN32) + if(NOT MSVC)#use windres when compiling with gcc and clang + add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/git.res + COMMAND ${WINDRES_EXE} -O coff -DMAJOR=${PROJECT_VERSION_MAJOR} -DMINOR=${PROJECT_VERSION_MINOR} + -DMICRO=${PROJECT_VERSION_PATCH} -DPATCHLEVEL=0 -DGIT_VERSION="\\\"${PROJECT_VERSION}.GIT\\\"" + -i ${CMAKE_SOURCE_DIR}/git.rc -o ${CMAKE_BINARY_DIR}/git.res + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + VERBATIM) + else()#MSVC use rc + add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/git.res + COMMAND ${CMAKE_RC_COMPILER} /d MAJOR=${PROJECT_VERSION_MAJOR} /d MINOR=${PROJECT_VERSION_MINOR} + /d MICRO=${PROJECT_VERSION_PATCH} /d PATCHLEVEL=0 /d GIT_VERSION="${PROJECT_VERSION}.GIT" + /fo ${CMAKE_BINARY_DIR}/git.res ${CMAKE_SOURCE_DIR}/git.rc + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + VERBATIM) + endif() + add_custom_target(git-rc DEPENDS ${CMAKE_BINARY_DIR}/git.res) +endif() + +#link all required libraries to common-main +add_library(common-main OBJECT ${CMAKE_SOURCE_DIR}/common-main.c) + +target_link_libraries(common-main libgit xdiff reftable ${ZLIB_LIBRARIES}) +if(Intl_FOUND) + target_link_libraries(common-main ${Intl_LIBRARIES}) +endif() +if(Iconv_FOUND) + target_link_libraries(common-main ${Iconv_LIBRARIES}) +endif() +if(PCRE2_FOUND) + target_link_libraries(common-main ${PCRE2_LIBRARIES}) + target_link_directories(common-main PUBLIC ${PCRE2_LIBRARY_DIRS}) +endif() +if(WIN32) + target_link_libraries(common-main ws2_32 ntdll ${CMAKE_BINARY_DIR}/git.res) + add_dependencies(common-main git-rc) + if(CMAKE_C_COMPILER_ID STREQUAL "GNU") + target_link_options(common-main PUBLIC -municode -Wl,--nxcompat -Wl,--dynamicbase -Wl,--pic-executable,-e,mainCRTStartup) + elseif(CMAKE_C_COMPILER_ID STREQUAL "Clang") + target_link_options(common-main PUBLIC -municode -Wl,-nxcompat -Wl,-dynamicbase -Wl,-entry:wmainCRTStartup -Wl,invalidcontinue.obj) + elseif(CMAKE_C_COMPILER_ID STREQUAL "MSVC") + target_link_options(common-main PUBLIC /IGNORE:4217 /IGNORE:4049 /NOLOGO /ENTRY:wmainCRTStartup /SUBSYSTEM:CONSOLE invalidcontinue.obj) + else() + message(FATAL_ERROR "Unhandled compiler: ${CMAKE_C_COMPILER_ID}") + endif() +elseif(UNIX) + target_link_libraries(common-main pthread rt) +endif() + +#git +parse_makefile_for_sources(git_SOURCES "BUILTIN_OBJS") + +list(TRANSFORM git_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/") +add_executable(git ${CMAKE_SOURCE_DIR}/git.c ${git_SOURCES}) +target_link_libraries(git common-main) + +add_executable(git-daemon ${CMAKE_SOURCE_DIR}/daemon.c) +target_link_libraries(git-daemon common-main) + +add_executable(git-http-backend ${CMAKE_SOURCE_DIR}/http-backend.c) +target_link_libraries(git-http-backend common-main) + +add_executable(git-sh-i18n--envsubst ${CMAKE_SOURCE_DIR}/sh-i18n--envsubst.c) +target_link_libraries(git-sh-i18n--envsubst common-main) + +add_executable(git-shell ${CMAKE_SOURCE_DIR}/shell.c) +target_link_libraries(git-shell common-main) + +add_executable(scalar ${CMAKE_SOURCE_DIR}/scalar.c) +target_link_libraries(scalar common-main) + +if(CURL_FOUND) + add_library(http_obj OBJECT ${CMAKE_SOURCE_DIR}/http.c) + + add_executable(git-imap-send ${CMAKE_SOURCE_DIR}/imap-send.c) + target_link_libraries(git-imap-send http_obj common-main ${CURL_LIBRARIES}) + + add_executable(git-http-fetch ${CMAKE_SOURCE_DIR}/http-walker.c ${CMAKE_SOURCE_DIR}/http-fetch.c) + target_link_libraries(git-http-fetch http_obj common-main ${CURL_LIBRARIES}) + + add_executable(git-remote-http ${CMAKE_SOURCE_DIR}/http-walker.c ${CMAKE_SOURCE_DIR}/remote-curl.c) + target_link_libraries(git-remote-http http_obj common-main ${CURL_LIBRARIES} ) + + if(EXPAT_FOUND) + add_executable(git-http-push ${CMAKE_SOURCE_DIR}/http-push.c) + target_link_libraries(git-http-push http_obj common-main ${CURL_LIBRARIES} ${EXPAT_LIBRARIES}) + endif() +endif() + +parse_makefile_for_executables(git_builtin_extra "BUILT_INS") + +option(SKIP_DASHED_BUILT_INS "Skip hardlinking the dashed versions of the built-ins") + +#Creating hardlinks +if(NOT SKIP_DASHED_BUILT_INS) +foreach(s ${git_SOURCES} ${git_builtin_extra}) + string(REPLACE "${CMAKE_SOURCE_DIR}/builtin/" "" s ${s}) + string(REPLACE ".c" "" s ${s}) + file(APPEND ${CMAKE_BINARY_DIR}/CreateLinks.cmake "file(CREATE_LINK git${EXE_EXTENSION} git-${s}${EXE_EXTENSION})\n") + list(APPEND git_links ${CMAKE_BINARY_DIR}/git-${s}${EXE_EXTENSION}) +endforeach() +endif() + +if(CURL_FOUND) + set(remote_exes + git-remote-https git-remote-ftp git-remote-ftps) + foreach(s ${remote_exes}) + file(APPEND ${CMAKE_BINARY_DIR}/CreateLinks.cmake "file(CREATE_LINK git-remote-http${EXE_EXTENSION} ${s}${EXE_EXTENSION})\n") + list(APPEND git_http_links ${CMAKE_BINARY_DIR}/${s}${EXE_EXTENSION}) + endforeach() +endif() + +add_custom_command(OUTPUT ${git_links} ${git_http_links} + COMMAND ${CMAKE_COMMAND} -P ${CMAKE_BINARY_DIR}/CreateLinks.cmake + DEPENDS git git-remote-http) +add_custom_target(git-links ALL DEPENDS ${git_links} ${git_http_links}) + + +#creating required scripts +set(SHELL_PATH /bin/sh) +set(PERL_PATH /usr/bin/perl) +set(LOCALEDIR ${FALLBACK_RUNTIME_PREFIX}/share/locale) +set(GITWEBDIR ${FALLBACK_RUNTIME_PREFIX}/share/locale) +set(INSTLIBDIR ${FALLBACK_RUNTIME_PREFIX}/share/perl5) + +#shell scripts +parse_makefile_for_scripts(git_sh_scripts "SCRIPT_SH" ".sh") +parse_makefile_for_scripts(git_shlib_scripts "SCRIPT_LIB" "") +set(git_shell_scripts + ${git_sh_scripts} ${git_shlib_scripts} git-instaweb) + +foreach(script ${git_shell_scripts}) + file(STRINGS ${CMAKE_SOURCE_DIR}/${script}.sh content NEWLINE_CONSUME) + string(REPLACE "@SHELL_PATH@" "${SHELL_PATH}" content "${content}") + string(REPLACE "@@DIFF@@" "diff" content "${content}") + string(REPLACE "@LOCALEDIR@" "${LOCALEDIR}" content "${content}") + string(REPLACE "@GITWEBDIR@" "${GITWEBDIR}" content "${content}") + string(REPLACE "@@NO_CURL@@" "" content "${content}") + string(REPLACE "@@USE_GETTEXT_SCHEME@@" "" content "${content}") + string(REPLACE "# @@BROKEN_PATH_FIX@@" "" content "${content}") + string(REPLACE "@@PERL@@" "${PERL_PATH}" content "${content}") + string(REPLACE "@@PAGER_ENV@@" "LESS=FRX LV=-c" content "${content}") + file(WRITE ${CMAKE_BINARY_DIR}/${script} ${content}) +endforeach() + +#perl scripts +parse_makefile_for_scripts(git_perl_scripts "SCRIPT_PERL" ".perl") + +#create perl header +file(STRINGS ${CMAKE_SOURCE_DIR}/perl/header_templates/fixed_prefix.template.pl perl_header ) +string(REPLACE "@@PATHSEP@@" ":" perl_header "${perl_header}") +string(REPLACE "@@INSTLIBDIR@@" "${INSTLIBDIR}" perl_header "${perl_header}") + +foreach(script ${git_perl_scripts}) + file(STRINGS ${CMAKE_SOURCE_DIR}/${script}.perl content NEWLINE_CONSUME) + string(REPLACE "#!/usr/bin/perl" "#!/usr/bin/perl\n${perl_header}\n" content "${content}") + string(REPLACE "@@GIT_VERSION@@" "${PROJECT_VERSION}" content "${content}") + file(WRITE ${CMAKE_BINARY_DIR}/${script} ${content}) +endforeach() + +#python script +file(STRINGS ${CMAKE_SOURCE_DIR}/git-p4.py content NEWLINE_CONSUME) +string(REPLACE "#!/usr/bin/env python" "#!/usr/bin/python" content "${content}") +file(WRITE ${CMAKE_BINARY_DIR}/git-p4 ${content}) + +#perl modules +file(GLOB_RECURSE perl_modules "${CMAKE_SOURCE_DIR}/perl/*.pm") + +foreach(pm ${perl_modules}) + string(REPLACE "${CMAKE_SOURCE_DIR}/perl/" "" file_path ${pm}) + file(STRINGS ${pm} content NEWLINE_CONSUME) + string(REPLACE "@@LOCALEDIR@@" "${LOCALEDIR}" content "${content}") + string(REPLACE "@@NO_PERL_CPAN_FALLBACKS@@" "" content "${content}") + file(WRITE ${CMAKE_BINARY_DIR}/perl/build/lib/${file_path} ${content}) +#test-lib.sh requires perl/build/lib to be the build directory of perl modules +endforeach() + + +#templates +file(GLOB templates "${CMAKE_SOURCE_DIR}/templates/*") +list(TRANSFORM templates REPLACE "${CMAKE_SOURCE_DIR}/templates/" "") +list(REMOVE_ITEM templates ".gitignore") +list(REMOVE_ITEM templates "Makefile") +list(REMOVE_ITEM templates "blt")# Prevents an error when reconfiguring for in source builds + +list(REMOVE_ITEM templates "branches--") +file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/templates/blt/branches) #create branches + +#templates have @.*@ replacement so use configure_file instead +foreach(tm ${templates}) + string(REPLACE "--" "/" blt_tm ${tm}) + string(REPLACE "this" "" blt_tm ${blt_tm})# for this-- + configure_file(${CMAKE_SOURCE_DIR}/templates/${tm} ${CMAKE_BINARY_DIR}/templates/blt/${blt_tm} @ONLY) +endforeach() + + +#translations +if(MSGFMT_EXE) + file(GLOB po_files "${CMAKE_SOURCE_DIR}/po/*.po") + list(TRANSFORM po_files REPLACE "${CMAKE_SOURCE_DIR}/po/" "") + list(TRANSFORM po_files REPLACE ".po" "") + foreach(po ${po_files}) + file(MAKE_DIRECTORY ${CMAKE_BINARY_DIR}/po/build/locale/${po}/LC_MESSAGES) + add_custom_command(OUTPUT ${CMAKE_BINARY_DIR}/po/build/locale/${po}/LC_MESSAGES/git.mo + COMMAND ${MSGFMT_EXE} --check --statistics -o ${CMAKE_BINARY_DIR}/po/build/locale/${po}/LC_MESSAGES/git.mo ${CMAKE_SOURCE_DIR}/po/${po}.po) + list(APPEND po_gen ${CMAKE_BINARY_DIR}/po/build/locale/${po}/LC_MESSAGES/git.mo) + endforeach() + add_custom_target(po-gen ALL DEPENDS ${po_gen}) +endif() + + +#to help with the install +list(TRANSFORM git_shell_scripts PREPEND "${CMAKE_BINARY_DIR}/") +list(TRANSFORM git_perl_scripts PREPEND "${CMAKE_BINARY_DIR}/") + +#install +foreach(program ${PROGRAMS_BUILT}) +if(program MATCHES "^(git|git-shell|scalar)$") +install(TARGETS ${program} + RUNTIME DESTINATION bin) +else() +install(TARGETS ${program} + RUNTIME DESTINATION libexec/git-core) +endif() +endforeach() + +install(PROGRAMS ${CMAKE_BINARY_DIR}/git-cvsserver + DESTINATION bin) + +set(bin_links + git-receive-pack git-upload-archive git-upload-pack) + +foreach(b ${bin_links}) +install(CODE "file(CREATE_LINK ${CMAKE_INSTALL_PREFIX}/bin/git${EXE_EXTENSION} ${CMAKE_INSTALL_PREFIX}/bin/${b}${EXE_EXTENSION})") +endforeach() + +install(CODE "file(CREATE_LINK ${CMAKE_INSTALL_PREFIX}/bin/git${EXE_EXTENSION} ${CMAKE_INSTALL_PREFIX}/libexec/git-core/git${EXE_EXTENSION})") +install(CODE "file(CREATE_LINK ${CMAKE_INSTALL_PREFIX}/bin/git-shell${EXE_EXTENSION} ${CMAKE_INSTALL_PREFIX}/libexec/git-core/git-shell${EXE_EXTENSION})") + +foreach(b ${git_links}) + string(REPLACE "${CMAKE_BINARY_DIR}" "" b ${b}) + install(CODE "file(CREATE_LINK ${CMAKE_INSTALL_PREFIX}/bin/git${EXE_EXTENSION} ${CMAKE_INSTALL_PREFIX}/libexec/git-core/${b})") +endforeach() + +foreach(b ${git_http_links}) + string(REPLACE "${CMAKE_BINARY_DIR}" "" b ${b}) + install(CODE "file(CREATE_LINK ${CMAKE_INSTALL_PREFIX}/libexec/git-core/git-remote-http${EXE_EXTENSION} ${CMAKE_INSTALL_PREFIX}/libexec/git-core/${b})") +endforeach() + +install(PROGRAMS ${git_shell_scripts} ${git_perl_scripts} ${CMAKE_BINARY_DIR}/git-p4 + DESTINATION libexec/git-core) + +install(DIRECTORY ${CMAKE_SOURCE_DIR}/mergetools DESTINATION libexec/git-core) +install(DIRECTORY ${CMAKE_BINARY_DIR}/perl/build/lib/ DESTINATION share/perl5 + FILES_MATCHING PATTERN "*.pm") +install(DIRECTORY ${CMAKE_BINARY_DIR}/templates/blt/ DESTINATION share/git-core/templates) + +if(MSGFMT_EXE) + install(DIRECTORY ${CMAKE_BINARY_DIR}/po/build/locale DESTINATION share) +endif() + + +if(BUILD_TESTING) + +#tests-helpers +add_executable(test-fake-ssh ${CMAKE_SOURCE_DIR}/t/helper/test-fake-ssh.c) +target_link_libraries(test-fake-ssh common-main) + +#reftable-tests +parse_makefile_for_sources(test-reftable_SOURCES "REFTABLE_TEST_OBJS") +list(TRANSFORM test-reftable_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/") + +#test-tool +parse_makefile_for_sources(test-tool_SOURCES "TEST_BUILTINS_OBJS") + +list(TRANSFORM test-tool_SOURCES PREPEND "${CMAKE_SOURCE_DIR}/t/helper/") +add_executable(test-tool ${CMAKE_SOURCE_DIR}/t/helper/test-tool.c ${test-tool_SOURCES} ${test-reftable_SOURCES}) +target_link_libraries(test-tool common-main) + +set_target_properties(test-fake-ssh test-tool + PROPERTIES RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/t/helper) + +if(MSVC) + set_target_properties(test-fake-ssh test-tool + PROPERTIES RUNTIME_OUTPUT_DIRECTORY_DEBUG ${CMAKE_BINARY_DIR}/t/helper) + set_target_properties(test-fake-ssh test-tool + PROPERTIES RUNTIME_OUTPUT_DIRECTORY_RELEASE ${CMAKE_BINARY_DIR}/t/helper) +endif() + +#wrapper scripts +set(wrapper_scripts + git git-upload-pack git-receive-pack git-upload-archive git-shell git-remote-ext scalar) + +set(wrapper_test_scripts + test-fake-ssh test-tool) + + +foreach(script ${wrapper_scripts}) + file(STRINGS ${CMAKE_SOURCE_DIR}/wrap-for-bin.sh content NEWLINE_CONSUME) + string(REPLACE "@@BUILD_DIR@@" "${CMAKE_BINARY_DIR}" content "${content}") + string(REPLACE "@@PROG@@" "${script}${EXE_EXTENSION}" content "${content}") + file(WRITE ${CMAKE_BINARY_DIR}/bin-wrappers/${script} ${content}) +endforeach() + +foreach(script ${wrapper_test_scripts}) + file(STRINGS ${CMAKE_SOURCE_DIR}/wrap-for-bin.sh content NEWLINE_CONSUME) + string(REPLACE "@@BUILD_DIR@@" "${CMAKE_BINARY_DIR}" content "${content}") + string(REPLACE "@@PROG@@" "t/helper/${script}${EXE_EXTENSION}" content "${content}") + file(WRITE ${CMAKE_BINARY_DIR}/bin-wrappers/${script} ${content}) +endforeach() + +file(STRINGS ${CMAKE_SOURCE_DIR}/wrap-for-bin.sh content NEWLINE_CONSUME) +string(REPLACE "@@BUILD_DIR@@" "${CMAKE_BINARY_DIR}" content "${content}") +string(REPLACE "@@PROG@@" "git-cvsserver" content "${content}") +file(WRITE ${CMAKE_BINARY_DIR}/bin-wrappers/git-cvsserver ${content}) + +#options for configuring test options +option(PERL_TESTS "Perform tests that use perl" ON) +option(PYTHON_TESTS "Perform tests that use python" ON) + +#GIT-BUILD-OPTIONS +set(TEST_SHELL_PATH ${SHELL_PATH}) +set(DIFF diff) +set(PYTHON_PATH /usr/bin/python) +set(TAR tar) +set(NO_CURL ) +set(NO_EXPAT ) +set(USE_LIBPCRE2 ) +set(NO_PERL ) +set(NO_PTHREADS ) +set(NO_PYTHON ) +set(PAGER_ENV "LESS=FRX LV=-c") +set(RUNTIME_PREFIX true) +set(NO_GETTEXT ) + +if(NOT CURL_FOUND) + set(NO_CURL 1) +endif() + +if(NOT EXPAT_FOUND) + set(NO_EXPAT 1) +endif() + +if(NOT Intl_FOUND) + set(NO_GETTEXT 1) +endif() + +if(NOT PERL_TESTS) + set(NO_PERL 1) +endif() + +if(NOT PYTHON_TESTS) + set(NO_PYTHON 1) +endif() + +file(WRITE ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "SHELL_PATH='${SHELL_PATH}'\n") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "TEST_SHELL_PATH='${TEST_SHELL_PATH}'\n") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "PERL_PATH='${PERL_PATH}'\n") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "DIFF='${DIFF}'\n") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "PYTHON_PATH='${PYTHON_PATH}'\n") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "TAR='${TAR}'\n") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "NO_CURL='${NO_CURL}'\n") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "NO_EXPAT='${NO_EXPAT}'\n") +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 "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") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "NO_PYTHON='${NO_PYTHON}'\n") +file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "SUPPORTS_SIMPLE_IPC='${SUPPORTS_SIMPLE_IPC}'\n") +if(USE_VCPKG) + file(APPEND ${CMAKE_BINARY_DIR}/GIT-BUILD-OPTIONS "PATH=\"$PATH:$TEST_DIRECTORY/../compat/vcbuild/vcpkg/installed/x64-windows/bin\"\n") +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}) + #Setting the build directory in test-lib.sh before running tests + file(WRITE ${CMAKE_BINARY_DIR}/CTestCustom.cmake + "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(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") + +#test +foreach(tsh ${test_scipts}) + add_test(NAME ${tsh} + 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("${CMAKE_SOURCE_DIR}/t/t7112-reset-submodule.sh" PROPERTIES TIMEOUT 4000) + +endif()#BUILD_TESTING diff --git a/contrib/buildsystems/Generators.pm b/contrib/buildsystems/Generators.pm new file mode 100644 index 0000000..aa4cbaa --- /dev/null +++ b/contrib/buildsystems/Generators.pm @@ -0,0 +1,42 @@ +package Generators; +require Exporter; + +use strict; +use File::Basename; +no strict 'refs'; +use vars qw($VERSION @AVAILABLE); + +our $VERSION = '1.00'; +our(@ISA, @EXPORT, @EXPORT_OK, @AVAILABLE); +@ISA = qw(Exporter); + +BEGIN { + local(*D); + my $me = $INC{"Generators.pm"}; + die "Couldn't find myself in \@INC, which is required to load the generators!" if ("$me" eq ""); + $me = dirname($me); + if (opendir(D,"$me/Generators")) { + foreach my $gen (readdir(D)) { + next unless ($gen =~ /\.pm$/); + require "${me}/Generators/$gen"; + $gen =~ s,\.pm,,; + push(@AVAILABLE, $gen); + } + closedir(D); + my $gens = join(', ', @AVAILABLE); + } + + push @EXPORT_OK, qw(available); +} + +sub available { + return @AVAILABLE; +} + +sub generate { + my ($gen, $git_dir, $out_dir, $rel_dir, %build_structure) = @_; + return eval("Generators::${gen}::generate(\$git_dir, \$out_dir, \$rel_dir, \%build_structure)") if grep(/^$gen$/, @AVAILABLE); + die "Generator \"${gen}\" is not available!\nAvailable generators are: @AVAILABLE\n"; +} + +1; diff --git a/contrib/buildsystems/Generators/QMake.pm b/contrib/buildsystems/Generators/QMake.pm new file mode 100644 index 0000000..ff3b657 --- /dev/null +++ b/contrib/buildsystems/Generators/QMake.pm @@ -0,0 +1,189 @@ +package Generators::QMake; +require Exporter; + +use strict; +use vars qw($VERSION); + +our $VERSION = '1.00'; +our(@ISA, @EXPORT, @EXPORT_OK, @AVAILABLE); +@ISA = qw(Exporter); + +BEGIN { + push @EXPORT_OK, qw(generate); +} + +sub generate { + my ($git_dir, $out_dir, $rel_dir, %build_structure) = @_; + + my @libs = @{$build_structure{"LIBS"}}; + foreach (@libs) { + createLibProject($_, $git_dir, $out_dir, $rel_dir, %build_structure); + } + + my @apps = @{$build_structure{"APPS"}}; + foreach (@apps) { + createAppProject($_, $git_dir, $out_dir, $rel_dir, %build_structure); + } + + createGlueProject($git_dir, $out_dir, $rel_dir, %build_structure); + return 0; +} + +sub createLibProject { + my ($libname, $git_dir, $out_dir, $rel_dir, %build_structure) = @_; + print "Generate $libname lib project\n"; + $rel_dir = "../$rel_dir"; + + my $sources = join(" \\\n\t", sort(map("$rel_dir/$_", @{$build_structure{"LIBS_${libname}_SOURCES"}}))); + my $defines = join(" \\\n\t", sort(@{$build_structure{"LIBS_${libname}_DEFINES"}})); + my $includes= join(" \\\n\t", sort(map("$rel_dir/$_", @{$build_structure{"LIBS_${libname}_INCLUDES"}}))); + my $cflags = join(" ", sort(@{$build_structure{"LIBS_${libname}_CFLAGS"}})); + + my $cflags_debug = $cflags; + $cflags_debug =~ s/-MT/-MTd/; + $cflags_debug =~ s/-O.//; + + my $cflags_release = $cflags; + $cflags_release =~ s/-MTd/-MT/; + + my @tmp = @{$build_structure{"LIBS_${libname}_LFLAGS"}}; + my @tmp2 = (); + foreach (@tmp) { + if (/^-LTCG/) { + } elsif (/^-L/) { + $_ =~ s/^-L/-LIBPATH:$rel_dir\//; + } + push(@tmp2, $_); + } + my $lflags = join(" ", sort(@tmp)); + + my $target = $libname; + $target =~ s/\//_/g; + $defines =~ s/-D//g; + $defines =~ s/"/\\\\"/g; + $includes =~ s/-I//g; + mkdir "$target" || die "Could not create the directory $target for lib project!\n"; + open F, ">$target/$target.pro" || die "Could not open $target/$target.pro for writing!\n"; + print F << "EOM"; +TEMPLATE = lib +TARGET = $target +DESTDIR = $rel_dir + +CONFIG -= qt +CONFIG += static + +QMAKE_CFLAGS = +QMAKE_CFLAGS_RELEASE = $cflags_release +QMAKE_CFLAGS_DEBUG = $cflags_debug +QMAKE_LIBFLAGS = $lflags + +DEFINES += \\ + $defines + +INCLUDEPATH += \\ + $includes + +SOURCES += \\ + $sources +EOM + close F; +} + +sub createAppProject { + my ($appname, $git_dir, $out_dir, $rel_dir, %build_structure) = @_; + print "Generate $appname app project\n"; + $rel_dir = "../$rel_dir"; + + my $sources = join(" \\\n\t", sort(map("$rel_dir/$_", @{$build_structure{"APPS_${appname}_SOURCES"}}))); + my $defines = join(" \\\n\t", sort(@{$build_structure{"APPS_${appname}_DEFINES"}})); + my $includes= join(" \\\n\t", sort(map("$rel_dir/$_", @{$build_structure{"APPS_${appname}_INCLUDES"}}))); + my $cflags = join(" ", sort(@{$build_structure{"APPS_${appname}_CFLAGS"}})); + + my $cflags_debug = $cflags; + $cflags_debug =~ s/-MT/-MTd/; + $cflags_debug =~ s/-O.//; + + my $cflags_release = $cflags; + $cflags_release =~ s/-MTd/-MT/; + + my $libs; + foreach (sort(@{$build_structure{"APPS_${appname}_LIBS"}})) { + $_ =~ s/\//_/g; + $libs .= " $_"; + } + my @tmp = @{$build_structure{"APPS_${appname}_LFLAGS"}}; + my @tmp2 = (); + foreach (@tmp) { + # next if ($_ eq "-NODEFAULTLIB:MSVCRT.lib"); + if (/^-LTCG/) { + } elsif (/^-L/) { + $_ =~ s/^-L/-LIBPATH:$rel_dir\//; + } + push(@tmp2, $_); + } + my $lflags = join(" ", sort(@tmp)); + + my $target = $appname; + $target =~ s/\.exe//; + $target =~ s/\//_/g; + $defines =~ s/-D//g; + $defines =~ s/"/\\\\"/g; + $includes =~ s/-I//g; + mkdir "$target" || die "Could not create the directory $target for app project!\n"; + open F, ">$target/$target.pro" || die "Could not open $target/$target.pro for writing!\n"; + print F << "EOM"; +TEMPLATE = app +TARGET = $target +DESTDIR = $rel_dir + +CONFIG -= qt embed_manifest_exe +CONFIG += console + +QMAKE_CFLAGS = +QMAKE_CFLAGS_RELEASE = $cflags_release +QMAKE_CFLAGS_DEBUG = $cflags_debug +QMAKE_LFLAGS = $lflags +LIBS = $libs + +DEFINES += \\ + $defines + +INCLUDEPATH += \\ + $includes + +win32:QMAKE_LFLAGS += -LIBPATH:$rel_dir +else: QMAKE_LFLAGS += -L$rel_dir + +SOURCES += \\ + $sources +EOM + close F; +} + +sub createGlueProject { + my ($git_dir, $out_dir, $rel_dir, %build_structure) = @_; + my $libs = join(" \\ \n", map("\t$_|$_.pro", @{$build_structure{"LIBS"}})); + my $apps = join(" \\ \n", map("\t$_|$_.pro", @{$build_structure{"APPS"}})); + $libs =~ s/\.a//g; + $libs =~ s/\//_/g; + $libs =~ s/\|/\//g; + $apps =~ s/\.exe//g; + $apps =~ s/\//_/g; + $apps =~ s/\|/\//g; + + my $filename = $out_dir; + $filename =~ s/.*\/([^\/]+)$/$1/; + $filename =~ s/\/$//; + print "Generate glue project $filename.pro\n"; + open F, ">$filename.pro" || die "Could not open $filename.pro for writing!\n"; + print F << "EOM"; +TEMPLATE = subdirs +CONFIG += ordered +SUBDIRS += \\ +$libs \\ +$apps +EOM + close F; +} + +1; diff --git a/contrib/buildsystems/Generators/Vcproj.pm b/contrib/buildsystems/Generators/Vcproj.pm new file mode 100644 index 0000000..737647e --- /dev/null +++ b/contrib/buildsystems/Generators/Vcproj.pm @@ -0,0 +1,579 @@ +package Generators::Vcproj; +require Exporter; + +use strict; +use vars qw($VERSION); +use Digest::SHA qw(sha256_hex); + +our $VERSION = '1.00'; +our(@ISA, @EXPORT, @EXPORT_OK, @AVAILABLE); +@ISA = qw(Exporter); + +BEGIN { + push @EXPORT_OK, qw(generate); +} + +sub generate_guid ($) { + my $hex = sha256_hex($_[0]); + $hex =~ s/^(.{8})(.{4})(.{4})(.{4})(.{12}).*/{$1-$2-$3-$4-$5}/; + $hex =~ tr/a-z/A-Z/; + return $hex; +} + +sub generate { + my ($git_dir, $out_dir, $rel_dir, %build_structure) = @_; + my @libs = @{$build_structure{"LIBS"}}; + foreach (@libs) { + createLibProject($_, $git_dir, $out_dir, $rel_dir, \%build_structure); + } + + my @apps = @{$build_structure{"APPS"}}; + foreach (@apps) { + createAppProject($_, $git_dir, $out_dir, $rel_dir, \%build_structure); + } + + createGlueProject($git_dir, $out_dir, $rel_dir, %build_structure); + return 0; +} + +sub createLibProject { + my ($libname, $git_dir, $out_dir, $rel_dir, $build_structure) = @_; + print "Generate $libname vcproj lib project\n"; + $rel_dir = "..\\$rel_dir"; + $rel_dir =~ s/\//\\/g; + + my $target = $libname; + $target =~ s/\//_/g; + $target =~ s/\.a//; + + my $uuid = generate_guid($libname); + $$build_structure{"LIBS_${target}_GUID"} = $uuid; + + my @srcs = sort(map("$rel_dir\\$_", @{$$build_structure{"LIBS_${libname}_SOURCES"}})); + my @sources; + foreach (@srcs) { + $_ =~ s/\//\\/g; + push(@sources, $_); + } + my $defines = join(",", sort(@{$$build_structure{"LIBS_${libname}_DEFINES"}})); + my $includes= join(";", sort(map(""$rel_dir\\$_"", @{$$build_structure{"LIBS_${libname}_INCLUDES"}}))); + my $cflags = join(" ", sort(@{$$build_structure{"LIBS_${libname}_CFLAGS"}})); + $cflags =~ s/\"/"/g; + $cflags =~ s//>/g; + + my $cflags_debug = $cflags; + $cflags_debug =~ s/-MT/-MTd/; + $cflags_debug =~ s/-O.//; + + my $cflags_release = $cflags; + $cflags_release =~ s/-MTd/-MT/; + + my @tmp = @{$$build_structure{"LIBS_${libname}_LFLAGS"}}; + my @tmp2 = (); + foreach (@tmp) { + if (/^-LTCG/) { + } elsif (/^-L/) { + $_ =~ s/^-L/-LIBPATH:$rel_dir\//; + } + push(@tmp2, $_); + } + my $lflags = join(" ", sort(@tmp)); + + $defines =~ s/-D//g; + $defines =~ s/\"/\\"/g; + $defines =~ s//>/g; + $defines =~ s/\'//g; + $includes =~ s/-I//g; + mkdir "$target" || die "Could not create the directory $target for lib project!\n"; + open F, ">$target/$target.vcproj" || die "Could not open $target/$target.pro for writing!\n"; + binmode F, ":crlf"; + print F << "EOM"; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +EOM + foreach(@sources) { + print F << "EOM"; + +EOM + } + print F << "EOM"; + + + + + +EOM + close F; +} + +sub createAppProject { + my ($appname, $git_dir, $out_dir, $rel_dir, $build_structure) = @_; + print "Generate $appname vcproj app project\n"; + $rel_dir = "..\\$rel_dir"; + $rel_dir =~ s/\//\\/g; + + my $target = $appname; + $target =~ s/\//_/g; + $target =~ s/\.exe//; + + my $uuid = generate_guid($appname); + $$build_structure{"APPS_${target}_GUID"} = $uuid; + + my @srcs = sort(map("$rel_dir\\$_", @{$$build_structure{"APPS_${appname}_SOURCES"}})); + my @sources; + foreach (@srcs) { + $_ =~ s/\//\\/g; + push(@sources, $_); + } + my $defines = join(",", sort(@{$$build_structure{"APPS_${appname}_DEFINES"}})); + my $includes= join(";", sort(map(""$rel_dir\\$_"", @{$$build_structure{"APPS_${appname}_INCLUDES"}}))); + my $cflags = join(" ", sort(@{$$build_structure{"APPS_${appname}_CFLAGS"}})); + $cflags =~ s/\"/"/g; + $cflags =~ s//>/g; + + my $cflags_debug = $cflags; + $cflags_debug =~ s/-MT/-MTd/; + $cflags_debug =~ s/-O.//; + + my $cflags_release = $cflags; + $cflags_release =~ s/-MTd/-MT/; + + my $libs; + foreach (sort(@{$$build_structure{"APPS_${appname}_LIBS"}})) { + $_ =~ s/\//_/g; + $libs .= " $_"; + } + my @tmp = @{$$build_structure{"APPS_${appname}_LFLAGS"}}; + my @tmp2 = (); + foreach (@tmp) { + if (/^-LTCG/) { + } elsif (/^-L/) { + $_ =~ s/^-L/-LIBPATH:$rel_dir\//; + } + push(@tmp2, $_); + } + my $lflags = join(" ", sort(@tmp)) . " -LIBPATH:$rel_dir"; + + $defines =~ s/-D//g; + $defines =~ s/\"/\\"/g; + $defines =~ s//>/g; + $defines =~ s/\'//g; + $defines =~ s/\\\\/\\/g; + $includes =~ s/-I//g; + mkdir "$target" || die "Could not create the directory $target for lib project!\n"; + open F, ">$target/$target.vcproj" || die "Could not open $target/$target.pro for writing!\n"; + binmode F, ":crlf"; + print F << "EOM"; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +EOM + foreach(@sources) { + print F << "EOM"; + +EOM + } + print F << "EOM"; + + + + + +EOM + close F; +} + +sub createGlueProject { + my ($git_dir, $out_dir, $rel_dir, %build_structure) = @_; + print "Generate solutions file\n"; + $rel_dir = "..\\$rel_dir"; + $rel_dir =~ s/\//\\/g; + my $SLN_HEAD = "Microsoft Visual Studio Solution File, Format Version 10.00\n# Visual Studio 2008\n"; + my $SLN_PRE = "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = "; + my $SLN_POST = "\nEndProject\n"; + + my @libs = @{$build_structure{"LIBS"}}; + my @tmp; + foreach (@libs) { + $_ =~ s/\//_/g; + $_ =~ s/\.a//; + push(@tmp, $_); + } + @libs = @tmp; + + my @apps = @{$build_structure{"APPS"}}; + @tmp = (); + foreach (@apps) { + $_ =~ s/\//_/g; + $_ =~ s/\.exe//; + if ($_ eq "git" ) { + unshift(@tmp, $_); + } else { + push(@tmp, $_); + } + } + @apps = @tmp; + + open F, ">git.sln" || die "Could not open git.sln for writing!\n"; + binmode F, ":crlf"; + print F "$SLN_HEAD"; + + my $uuid_libgit = $build_structure{"LIBS_libgit_GUID"}; + my $uuid_xdiff_lib = $build_structure{"LIBS_xdiff_lib_GUID"}; + foreach (@apps) { + my $appname = $_; + my $uuid = $build_structure{"APPS_${appname}_GUID"}; + print F "$SLN_PRE"; + print F "\"${appname}\", \"${appname}\\${appname}.vcproj\", \"${uuid}\"\n"; + print F " ProjectSection(ProjectDependencies) = postProject\n"; + print F " ${uuid_libgit} = ${uuid_libgit}\n"; + print F " ${uuid_xdiff_lib} = ${uuid_xdiff_lib}\n"; + print F " EndProjectSection"; + print F "$SLN_POST"; + } + foreach (@libs) { + my $libname = $_; + my $uuid = $build_structure{"LIBS_${libname}_GUID"}; + print F "$SLN_PRE"; + print F "\"${libname}\", \"${libname}\\${libname}.vcproj\", \"${uuid}\""; + print F "$SLN_POST"; + } + + print F << "EOM"; +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Win32 = Debug|Win32 + Release|Win32 = Release|Win32 + EndGlobalSection +EOM + print F << "EOM"; + GlobalSection(ProjectConfigurationPlatforms) = postSolution +EOM + foreach (@apps) { + my $appname = $_; + my $uuid = $build_structure{"APPS_${appname}_GUID"}; + print F "\t\t${uuid}.Debug|Win32.ActiveCfg = Debug|Win32\n"; + print F "\t\t${uuid}.Debug|Win32.Build.0 = Debug|Win32\n"; + print F "\t\t${uuid}.Release|Win32.ActiveCfg = Release|Win32\n"; + print F "\t\t${uuid}.Release|Win32.Build.0 = Release|Win32\n"; + } + foreach (@libs) { + my $libname = $_; + my $uuid = $build_structure{"LIBS_${libname}_GUID"}; + print F "\t\t${uuid}.Debug|Win32.ActiveCfg = Debug|Win32\n"; + print F "\t\t${uuid}.Debug|Win32.Build.0 = Debug|Win32\n"; + print F "\t\t${uuid}.Release|Win32.ActiveCfg = Release|Win32\n"; + print F "\t\t${uuid}.Release|Win32.Build.0 = Release|Win32\n"; + } + + print F << "EOM"; + EndGlobalSection +EndGlobal +EOM + close F; +} + +1; diff --git a/contrib/buildsystems/Generators/Vcxproj.pm b/contrib/buildsystems/Generators/Vcxproj.pm new file mode 100644 index 0000000..1a25789 --- /dev/null +++ b/contrib/buildsystems/Generators/Vcxproj.pm @@ -0,0 +1,402 @@ +package Generators::Vcxproj; +require Exporter; + +use strict; +use vars qw($VERSION); +use Digest::SHA qw(sha256_hex); + +our $VERSION = '1.00'; +our(@ISA, @EXPORT, @EXPORT_OK, @AVAILABLE); +@ISA = qw(Exporter); + +BEGIN { + push @EXPORT_OK, qw(generate); +} + +sub generate_guid ($) { + my $hex = sha256_hex($_[0]); + $hex =~ s/^(.{8})(.{4})(.{4})(.{4})(.{12}).*/{$1-$2-$3-$4-$5}/; + $hex =~ tr/a-z/A-Z/; + return $hex; +} + +sub generate { + my ($git_dir, $out_dir, $rel_dir, %build_structure) = @_; + my @libs = @{$build_structure{"LIBS"}}; + foreach (@libs) { + createProject($_, $git_dir, $out_dir, $rel_dir, \%build_structure, 1); + } + + my @apps = @{$build_structure{"APPS"}}; + foreach (@apps) { + createProject($_, $git_dir, $out_dir, $rel_dir, \%build_structure, 0); + } + + createGlueProject($git_dir, $out_dir, $rel_dir, %build_structure); + return 0; +} + +sub createProject { + my ($name, $git_dir, $out_dir, $rel_dir, $build_structure, $static_library) = @_; + my $label = $static_library ? "lib" : "app"; + my $prefix = $static_library ? "LIBS_" : "APPS_"; + my $config_type = $static_library ? "StaticLibrary" : "Application"; + print "Generate $name vcxproj $label project\n"; + my $cdup = $name; + $cdup =~ s/[^\/]+/../g; + $cdup =~ s/\//\\/g; + $rel_dir = $rel_dir eq "." ? $cdup : "$cdup\\$rel_dir"; + $rel_dir =~ s/\//\\/g; + + my $target = $name; + if ($static_library) { + $target =~ s/\.a//; + } else { + $target =~ s/\.exe//; + } + + my $uuid = generate_guid($name); + $$build_structure{"$prefix${target}_GUID"} = $uuid; + my $vcxproj = $target; + $vcxproj =~ s/(.*\/)?(.*)/$&\/$2.vcxproj/; + $vcxproj =~ s/([^\/]*)(\/lib)\/(lib.vcxproj)/$1$2\/$1_$3/; + $$build_structure{"$prefix${target}_VCXPROJ"} = $vcxproj; + + my @srcs = sort(map("$rel_dir\\$_", @{$$build_structure{"$prefix${name}_SOURCES"}})); + my @sources; + foreach (@srcs) { + $_ =~ s/\//\\/g; + push(@sources, $_); + } + my $defines = join(";", sort(@{$$build_structure{"$prefix${name}_DEFINES"}})); + my $includes= join(";", sort(map { s/^-I//; s/\//\\/g; File::Spec->file_name_is_absolute($_) ? $_ : "$rel_dir\\$_" } @{$$build_structure{"$prefix${name}_INCLUDES"}})); + my $cflags = join(" ", sort(map { s/^-[GLMOWZ].*//; s/.* .*/"$&"/; $_; } @{$$build_structure{"$prefix${name}_CFLAGS"}})); + $cflags =~ s//>/g; + + my $libs_release = "\n "; + my $libs_debug = "\n "; + if (!$static_library) { + $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; + $libs_debug =~ s/libexpat\.lib/libexpatd\.lib/g; + $libs_debug =~ s/libcurl\.lib/libcurl-d\.lib/g; + } + + $defines =~ s/-D//g; + $defines =~ s//>/g; + $defines =~ s/\'//g; + + die "Could not create the directory $target for $label project!\n" unless (-d "$target" || mkdir "$target"); + + open F, ">$vcxproj" or die "Could not open $vcxproj for writing!\n"; + binmode F, ":crlf :utf8"; + print F chr(0xFEFF); + print F << "EOM"; + + + + + Debug + Win32 + + + Release + Win32 + + + Debug + x64 + + + Release + x64 + + + + $uuid + Win32Proj + x86-windows + x64-windows + $cdup\\compat\\vcbuild\\vcpkg\\installed\\\$(VCPKGArch) + \$(VCPKGArchDirectory)\\debug\\bin + \$(VCPKGArchDirectory)\\debug\\lib + \$(VCPKGArchDirectory)\\bin + \$(VCPKGArchDirectory)\\lib + \$(VCPKGArchDirectory)\\include + $libs_debug + $libs_release + + + + true + true + + + false + true + + + $config_type + v140 + + ..\\ + + + + + + + + + + + + + false + true + + + + $cflags %(AdditionalOptions) + $cdup;$cdup\\compat;$cdup\\compat\\regex;$cdup\\compat\\win32;$cdup\\compat\\poll;$cdup\\compat\\vcbuild\\include;\$(VCPKGIncludeDirectory);%(AdditionalIncludeDirectories) + + OnlyExplicitInline + + ProgramDatabase + + + true + + + \$(VCPKGLibDirectory);%(AdditionalLibraryDirectories) + \$(VCPKGLibs);\$(AdditionalDependencies) + invalidcontinue.obj %(AdditionalOptions) + wmainCRTStartup + $cdup\\compat\\win32\\git.manifest + Console + +EOM + if ($target eq 'libgit') { + print F << "EOM"; + + Initialize VCPKG + del "$cdup\\compat\\vcbuild\\vcpkg" + call "$cdup\\compat\\vcbuild\\vcpkg_install.bat" + +EOM + } + print F << "EOM"; + + + + MachineX86 + + + + + Disabled + WIN32;_DEBUG;$defines;%(PreprocessorDefinitions) + MultiThreadedDebugDLL + + + true + + + + + MaxSpeed + true + WIN32;NDEBUG;$defines;%(PreprocessorDefinitions) + MultiThreadedDLL + true + Speed + + + true + true + true + + + +EOM + foreach(@sources) { + print F << "EOM"; + +EOM + } + print F << "EOM"; + +EOM + if (!$static_library || $target =~ 'vcs-svn' || $target =~ 'xdiff') { + 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"}; + + print F << "EOM"; + + + $uuid_libgit + false + +EOM + if (!($name =~ /xdiff|libreftable/)) { + print F << "EOM"; + + $uuid_libreftable + false + +EOM + } + if (!($name =~ 'xdiff')) { + print F << "EOM"; + + $uuid_xdiff_lib + false + +EOM + } + if ($name =~ /(test-(line-buffer|svn-fe)|^git-remote-testsvn)\.exe$/) { + my $uuid_vcs_svn_lib = $$build_structure{"LIBS_vcs-svn/lib_GUID"}; + print F << "EOM"; + + $uuid_vcs_svn_lib + false + +EOM + } + print F << "EOM"; + +EOM + } + print F << "EOM"; + +EOM + if (!$static_library) { + print F << "EOM"; + + + + + + + +EOM + } + if ($target eq 'git') { + print F " \n"; + } + if ($target eq 'git-remote-http') { + print F " \n"; + } + print F << "EOM"; + +EOM + close F; +} + +sub createGlueProject { + my ($git_dir, $out_dir, $rel_dir, %build_structure) = @_; + print "Generate solutions file\n"; + $rel_dir = "..\\$rel_dir"; + $rel_dir =~ s/\//\\/g; + my $SLN_HEAD = "Microsoft Visual Studio Solution File, Format Version 11.00\n# Visual Studio 2010\n"; + my $SLN_PRE = "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = "; + my $SLN_POST = "\nEndProject\n"; + + my @libs = @{$build_structure{"LIBS"}}; + my @tmp; + foreach (@libs) { + $_ =~ s/\.a//; + push(@tmp, $_); + } + @libs = @tmp; + + my @apps = @{$build_structure{"APPS"}}; + @tmp = (); + foreach (@apps) { + $_ =~ s/\.exe//; + if ($_ eq "git" ) { + unshift(@tmp, $_); + } else { + push(@tmp, $_); + } + } + @apps = @tmp; + + open F, ">git.sln" || die "Could not open git.sln for writing!\n"; + binmode F, ":crlf :utf8"; + print F chr(0xFEFF); + print F "$SLN_HEAD"; + + foreach (@apps) { + my $appname = $_; + my $uuid = $build_structure{"APPS_${appname}_GUID"}; + print F "$SLN_PRE"; + my $vcxproj = $build_structure{"APPS_${appname}_VCXPROJ"}; + $vcxproj =~ s/\//\\/g; + $appname =~ s/.*\///; + print F "\"${appname}\", \"${vcxproj}\", \"${uuid}\""; + print F "$SLN_POST"; + } + foreach (@libs) { + my $libname = $_; + my $uuid = $build_structure{"LIBS_${libname}_GUID"}; + print F "$SLN_PRE"; + my $vcxproj = $build_structure{"LIBS_${libname}_VCXPROJ"}; + $vcxproj =~ s/\//\\/g; + $libname =~ s/\//_/g; + print F "\"${libname}\", \"${vcxproj}\", \"${uuid}\""; + print F "$SLN_POST"; + } + + print F << "EOM"; +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x64 = Debug|x64 + Debug|x86 = Debug|x86 + Release|x64 = Release|x64 + Release|x86 = Release|x86 + EndGlobalSection +EOM + print F << "EOM"; + GlobalSection(ProjectConfigurationPlatforms) = postSolution +EOM + foreach (@apps) { + my $appname = $_; + my $uuid = $build_structure{"APPS_${appname}_GUID"}; + print F "\t\t${uuid}.Debug|x64.ActiveCfg = Debug|x64\n"; + print F "\t\t${uuid}.Debug|x64.Build.0 = Debug|x64\n"; + print F "\t\t${uuid}.Debug|x86.ActiveCfg = Debug|Win32\n"; + print F "\t\t${uuid}.Debug|x86.Build.0 = Debug|Win32\n"; + print F "\t\t${uuid}.Release|x64.ActiveCfg = Release|x64\n"; + print F "\t\t${uuid}.Release|x64.Build.0 = Release|x64\n"; + print F "\t\t${uuid}.Release|x86.ActiveCfg = Release|Win32\n"; + print F "\t\t${uuid}.Release|x86.Build.0 = Release|Win32\n"; + } + foreach (@libs) { + my $libname = $_; + my $uuid = $build_structure{"LIBS_${libname}_GUID"}; + print F "\t\t${uuid}.Debug|x64.ActiveCfg = Debug|x64\n"; + print F "\t\t${uuid}.Debug|x64.Build.0 = Debug|x64\n"; + print F "\t\t${uuid}.Debug|x86.ActiveCfg = Debug|Win32\n"; + print F "\t\t${uuid}.Debug|x86.Build.0 = Debug|Win32\n"; + print F "\t\t${uuid}.Release|x64.ActiveCfg = Release|x64\n"; + print F "\t\t${uuid}.Release|x64.Build.0 = Release|x64\n"; + print F "\t\t${uuid}.Release|x86.ActiveCfg = Release|Win32\n"; + print F "\t\t${uuid}.Release|x86.Build.0 = Release|Win32\n"; + } + + print F << "EOM"; + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal +EOM + close F; +} + +1; diff --git a/contrib/buildsystems/engine.pl b/contrib/buildsystems/engine.pl new file mode 100755 index 0000000..ed6c459 --- /dev/null +++ b/contrib/buildsystems/engine.pl @@ -0,0 +1,394 @@ +#!/usr/bin/perl -w +###################################################################### +# Do not call this script directly! +# +# The generate script ensures that @INC is correct before the engine +# is executed. +# +# Copyright (C) 2009 Marius Storm-Olsen +###################################################################### +use strict; +use File::Basename; +use File::Spec; +use Cwd; +use Generators; +use Text::ParseWords; + +my (%build_structure, %compile_options, @makedry); +my $out_dir = getcwd(); +my $git_dir = $out_dir; +$git_dir =~ s=\\=/=g; +$git_dir = dirname($git_dir) while (!-e "$git_dir/git.c" && "$git_dir" ne ""); +die "Couldn't find Git repo" if ("$git_dir" eq ""); + +my @gens = Generators::available(); +my $gen = "Vcproj"; + +sub showUsage +{ + my $genlist = join(', ', @gens); + print << "EOM"; +generate usage: + -g --gen Specify the buildsystem generator (default: $gen) + Available: $genlist + -o --out Specify output directory generation (default: .) + --make-out Write the output of GNU Make into a file + -i --in Specify input file, instead of running GNU Make + -h,-? --help This help +EOM + exit 0; +} + +# Parse command-line options +my $make_out; +while (@ARGV) { + my $arg = shift @ARGV; + if ("$arg" eq "-h" || "$arg" eq "--help" || "$arg" eq "-?") { + showUsage(); + exit(0); + } elsif("$arg" eq "--out" || "$arg" eq "-o") { + $out_dir = shift @ARGV; + } elsif("$arg" eq "--make-out") { + $make_out = shift @ARGV; + } elsif("$arg" eq "--gen" || "$arg" eq "-g") { + $gen = shift @ARGV; + } elsif("$arg" eq "--in" || "$arg" eq "-i") { + my $infile = shift @ARGV; + open(F, "<$infile") || die "Couldn't open file $infile"; + @makedry = ; + close(F); + } else { + die "Unknown option: " . $arg; + } +} + +# NOT using File::Spec->rel2abs($path, $base) here, as +# it fails badly for me in the msysgit environment +$git_dir = File::Spec->rel2abs($git_dir); +$out_dir = File::Spec->rel2abs($out_dir); +my $rel_dir = makeOutRel2Git($git_dir, $out_dir); + +# Print some information so the user feels informed +print << "EOM"; +----- +Generator: $gen +Git dir: $git_dir +Out dir: $out_dir +----- +Running GNU Make to figure out build structure... +EOM + +# Pipe a make --dry-run into a variable, if not already loaded from file +# Capture the make dry stderr to file for review (will be empty for a release build). + +my $ErrsFile = "msvc-build-makedryerrors.txt"; +@makedry = `make -C $git_dir -n MSVC=1 SKIP_VCPKG=1 V=1 2>$ErrsFile` +if !@makedry; +# test for an empty Errors file and remove it +unlink $ErrsFile if -f -z $ErrsFile; + +if (defined $make_out) { + open OUT, ">" . $make_out; + print OUT @makedry; + close OUT; +} + +# Parse the make output into usable info +parseMakeOutput(); + +# Finally, ask the generator to start generating.. +Generators::generate($gen, $git_dir, $out_dir, $rel_dir, %build_structure); + +# main flow ends here +# ------------------------------------------------------------------------------------------------- + + +# 1) path: /foo/bar/baz 2) path: /foo/bar/baz 3) path: /foo/bar/baz +# base: /foo/bar/baz/temp base: /foo/bar base: /tmp +# rel: .. rel: baz rel: ../foo/bar/baz +sub makeOutRel2Git +{ + my ($path, $base) = @_; + my $rel; + if ("$path" eq "$base") { + return "."; + } elsif ($base =~ /^$path/) { + # case 1 + my $tmp = $base; + $tmp =~ s/^$path//; + foreach (split('/', $tmp)) { + $rel .= "../" if ("$_" ne ""); + } + } elsif ($path =~ /^$base/) { + # case 2 + $rel = $path; + $rel =~ s/^$base//; + $rel = "./$rel"; + } else { + my $tmp = $base; + foreach (split('/', $tmp)) { + $rel .= "../" if ("$_" ne ""); + } + $rel .= $path; + } + $rel =~ s/\/\//\//g; # simplify + $rel =~ s/\/$//; # don't end with / + return $rel; +} + +sub parseMakeOutput +{ + print "Parsing GNU Make output to figure out build structure...\n"; + my $line = 0; + while (my $text = shift @makedry) { + my $ate_next; + do { + $ate_next = 0; + $line++; + chomp $text; + chop $text if ($text =~ /\r$/); + if ($text =~ /\\$/) { + $text =~ s/\\$//; + $text .= shift @makedry; + $ate_next = 1; + } + } while($ate_next); + + if ($text =~ /^test /) { + # options to test (eg -o) may be mistaken for linker options + next; + } + + if ($text =~ /^(mkdir|msgfmt) /) { + # options to the Portable Object translations + # the line "mkdir ... && msgfmt ..." contains no linker options + next; + } + + if($text =~ / -c /) { + # compilation + handleCompileLine($text, $line); + + } elsif ($text =~ / -o /) { + # linking executable + handleLinkLine($text, $line); + + } elsif ($text =~ /\.o / && $text =~ /\.a /) { + # libifying + handleLibLine($text, $line); +# +# } elsif ($text =~ /^cp /) { +# # copy file around +# +# } elsif ($text =~ /^rm -f /) { +# # shell command +# +# } elsif ($text =~ /^make[ \[]/) { +# # make output +# +# } elsif ($text =~ /^echo /) { +# # echo to file +# +# } elsif ($text =~ /^if /) { +# # shell conditional +# +# } elsif ($text =~ /^tclsh /) { +# # translation stuff +# +# } elsif ($text =~ /^umask /) { +# # handling boilerplates +# +# } elsif ($text =~ /\$\(\:\)/) { +# # ignore +# +# } elsif ($text =~ /^FLAGS=/) { +# # flags check for dependencies +# +# } elsif ($text =~ /^'\/usr\/bin\/perl' -MError -e/) { +# # perl commands for copying files +# +# } elsif ($text =~ /generate-cmdlist\.sh/) { +# # command for generating list of commands +# +# } elsif ($text =~ /new locations or Tcl/) { +# # command for detecting Tcl/Tk changes +# +# } elsif ($text =~ /mkdir -p/) { +# # command creating path +# +# } elsif ($text =~ /: no custom templates yet/) { +# # whatever +# +# } else { +# print "Unhandled (line: $line): $text\n"; + } + } + +# use Data::Dumper; +# print "Parsed build structure:\n"; +# print Dumper(%build_structure); +} + +# variables for the compilation part of each step +my (@defines, @incpaths, @cflags, @sources); + +sub clearCompileStep +{ + @defines = (); + @incpaths = (); + @cflags = (); + @sources = (); +} + +sub removeDuplicates +{ + my (%dupHash, $entry); + %dupHash = map { $_, 1 } @defines; + @defines = keys %dupHash; + + %dupHash = map { $_, 1 } @incpaths; + @incpaths = keys %dupHash; + + %dupHash = map { $_, 1 } @cflags; + @cflags = keys %dupHash; +} + +sub handleCompileLine +{ + my ($line, $lineno) = @_; + my @parts = shellwords($line); + my $sourcefile; + shift(@parts); # ignore cmd + while (my $part = shift @parts) { + if ("$part" eq "-o") { + # ignore object file + shift @parts; + } elsif ("$part" eq "-c") { + # ignore compile flag + } elsif ("$part" eq "-c") { + } elsif ($part =~ /^.?-I/) { + push(@incpaths, $part); + } elsif ($part =~ /^.?-D/) { + push(@defines, $part); + } elsif ($part =~ /^-/) { + push(@cflags, $part); + } elsif ($part =~ /\.(c|cc|cpp)$/) { + $sourcefile = $part; + } else { + die "Unhandled compiler option @ line $lineno: $part"; + } + } + @{$compile_options{"${sourcefile}_CFLAGS"}} = @cflags; + @{$compile_options{"${sourcefile}_DEFINES"}} = @defines; + @{$compile_options{"${sourcefile}_INCPATHS"}} = @incpaths; + clearCompileStep(); +} + +sub handleLibLine +{ + my ($line, $lineno) = @_; + my (@objfiles, @lflags, $libout, $part); + # kill cmd and rm 'prefix' + $line =~ s/^rm -f .* && .* rcs //; + my @parts = shellwords($line); + while ($part = shift @parts) { + if ($part =~ /^-/) { + push(@lflags, $part); + } elsif ($part =~ /\.(o|obj)$/) { + push(@objfiles, $part); + } elsif ($part =~ /\.(a|lib)$/) { + $libout = $part; + $libout =~ s/\.a$//; + } else { + die "Unhandled lib option @ line $lineno: $part"; + } + } +# print "LibOut: '$libout'\nLFlags: @lflags\nOfiles: @objfiles\n"; +# exit(1); + foreach (@objfiles) { + my $sourcefile = $_; + $sourcefile =~ s/\.o$/.c/; + push(@sources, $sourcefile); + push(@cflags, @{$compile_options{"${sourcefile}_CFLAGS"}}); + push(@defines, @{$compile_options{"${sourcefile}_DEFINES"}}); + push(@incpaths, @{$compile_options{"${sourcefile}_INCPATHS"}}); + } + removeDuplicates(); + + push(@{$build_structure{"LIBS"}}, $libout); + @{$build_structure{"LIBS_${libout}"}} = ("_DEFINES", "_INCLUDES", "_CFLAGS", "_SOURCES", + "_OBJECTS"); + @{$build_structure{"LIBS_${libout}_DEFINES"}} = @defines; + @{$build_structure{"LIBS_${libout}_INCLUDES"}} = @incpaths; + @{$build_structure{"LIBS_${libout}_CFLAGS"}} = @cflags; + @{$build_structure{"LIBS_${libout}_LFLAGS"}} = @lflags; + @{$build_structure{"LIBS_${libout}_SOURCES"}} = @sources; + @{$build_structure{"LIBS_${libout}_OBJECTS"}} = @objfiles; + clearCompileStep(); +} + +sub handleLinkLine +{ + my ($line, $lineno) = @_; + my (@objfiles, @lflags, @libs, $appout, $part); + my @parts = shellwords($line); + shift(@parts); # ignore cmd + while ($part = shift @parts) { + if ($part =~ /^-IGNORE/) { + push(@lflags, $part); + } elsif ($part =~ /^-[GRIMDO]/) { + # eat compiler flags + } elsif ("$part" eq "-o") { + $appout = shift @parts; + } elsif ("$part" eq "-lz") { + push(@libs, "zlib.lib"); + } elsif ("$part" eq "-lcrypto") { + push(@libs, "libcrypto.lib"); + } elsif ("$part" eq "-lssl") { + push(@libs, "libssl.lib"); + } elsif ("$part" eq "-lcurl") { + push(@libs, "libcurl.lib"); + } elsif ("$part" eq "-lexpat") { + push(@libs, "libexpat.lib"); + } elsif ("$part" eq "-liconv") { + push(@libs, "iconv.lib"); + } elsif ($part =~ /^[-\/]/) { + push(@lflags, $part); + } elsif ($part =~ /\.(a|lib)$/) { + $part =~ s/\.a$/.lib/; + push(@libs, $part); + } elsif ($part eq 'invalidcontinue.obj') { + # ignore - known to MSVC + } elsif ($part =~ /\.o$/) { + push(@objfiles, $part); + } elsif ($part =~ /\.obj$/) { + # do nothing, 'make' should not be producing .obj, only .o files + } else { + die "Unhandled link option @ line $lineno: $part"; + } + } +# print "AppOut: '$appout'\nLFlags: @lflags\nLibs : @libs\nOfiles: @objfiles\n"; +# exit(1); + foreach (@objfiles) { + my $sourcefile = $_; + $sourcefile =~ s/\.o$/.c/; + push(@sources, $sourcefile); + push(@cflags, @{$compile_options{"${sourcefile}_CFLAGS"}}); + push(@defines, @{$compile_options{"${sourcefile}_DEFINES"}}); + push(@incpaths, @{$compile_options{"${sourcefile}_INCPATHS"}}); + } + removeDuplicates(); + + removeDuplicates(); + push(@{$build_structure{"APPS"}}, $appout); + @{$build_structure{"APPS_${appout}"}} = ("_DEFINES", "_INCLUDES", "_CFLAGS", "_LFLAGS", + "_SOURCES", "_OBJECTS", "_LIBS"); + @{$build_structure{"APPS_${appout}_DEFINES"}} = @defines; + @{$build_structure{"APPS_${appout}_INCLUDES"}} = @incpaths; + @{$build_structure{"APPS_${appout}_CFLAGS"}} = @cflags; + @{$build_structure{"APPS_${appout}_LFLAGS"}} = @lflags; + @{$build_structure{"APPS_${appout}_SOURCES"}} = @sources; + @{$build_structure{"APPS_${appout}_OBJECTS"}} = @objfiles; + @{$build_structure{"APPS_${appout}_LIBS"}} = @libs; + clearCompileStep(); +} diff --git a/contrib/buildsystems/generate b/contrib/buildsystems/generate new file mode 100755 index 0000000..bc10f25 --- /dev/null +++ b/contrib/buildsystems/generate @@ -0,0 +1,29 @@ +#!/usr/bin/perl -w +###################################################################### +# Generate buildsystem files +# +# This script generate buildsystem files based on the output of a +# GNU Make --dry-run, enabling Windows users to develop Git with their +# trusted IDE with native projects. +# +# Note: +# It is not meant as *the* way of building Git with MSVC, but merely a +# convenience. The correct way of building Git with MSVC is to use the +# GNU Make tool to build with the maintained Makefile in the root of +# the project. If you have the msysgit environment installed and +# available in your current console, together with the Visual Studio +# environment you wish to build for, all you have to do is run the +# command: +# make MSVC=1 +# +# Copyright (C) 2009 Marius Storm-Olsen +###################################################################### +use strict; +use File::Basename; +use Cwd; + +my $git_dir = getcwd(); +$git_dir =~ s=\\=/=g; +$git_dir = dirname($git_dir) while (!-e "$git_dir/git.c" && "$git_dir" ne ""); +die "Couldn't find Git repo" if ("$git_dir" eq ""); +exec join(" ", ("PERL5LIB=${git_dir}/contrib/buildsystems ${git_dir}/contrib/buildsystems/engine.pl", @ARGV)); diff --git a/contrib/buildsystems/parse.pl b/contrib/buildsystems/parse.pl new file mode 100755 index 0000000..c9656ec --- /dev/null +++ b/contrib/buildsystems/parse.pl @@ -0,0 +1,228 @@ +#!/usr/bin/perl -w +###################################################################### +# Do not call this script directly! +# +# The generate script ensures that @INC is correct before the engine +# is executed. +# +# Copyright (C) 2009 Marius Storm-Olsen +###################################################################### +use strict; +use File::Basename; +use Cwd; + +my $file = $ARGV[0]; +die "No file provided!" if !defined $file; + +my ($cflags, $target, $type, $line); + +open(F, "<$file") || die "Couldn't open file $file"; +my @data = ; +close(F); + +while (my $text = shift @data) { + my $ate_next; + do { + $ate_next = 0; + $line++; + chomp $text; + chop $text if ($text =~ /\r$/); + if ($text =~ /\\$/) { + $text =~ s/\\$//; + $text .= shift @data; + $ate_next = 1; + } + } while($ate_next); + + if($text =~ / -c /) { + # compilation + handleCompileLine($text, $line); + + } elsif ($text =~ / -o /) { + # linking executable + handleLinkLine($text, $line); + + } elsif ($text =~ /\.o / && $text =~ /\.a /) { + # libifying + handleLibLine($text, $line); + +# } elsif ($text =~ /^cp /) { +# # copy file around +# +# } elsif ($text =~ /^rm -f /) { +# # shell command +# +# } elsif ($text =~ /^make[ \[]/) { +# # make output +# +# } elsif ($text =~ /^echo /) { +# # echo to file +# +# } elsif ($text =~ /^if /) { +# # shell conditional +# +# } elsif ($text =~ /^tclsh /) { +# # translation stuff +# +# } elsif ($text =~ /^umask /) { +# # handling boilerplates +# +# } elsif ($text =~ /\$\(\:\)/) { +# # ignore +# +# } elsif ($text =~ /^FLAGS=/) { +# # flags check for dependencies +# +# } elsif ($text =~ /^'\/usr\/bin\/perl' -MError -e/) { +# # perl commands for copying files +# +# } elsif ($text =~ /generate-cmdlist\.sh/) { +# # command for generating list of commands +# +# } elsif ($text =~ /^test / && $text =~ /|| rm -f /) { +# # commands removing executables, if they exist +# +# } elsif ($text =~ /new locations or Tcl/) { +# # command for detecting Tcl/Tk changes +# +# } elsif ($text =~ /mkdir -p/) { +# # command creating path +# +# } elsif ($text =~ /: no custom templates yet/) { +# # whatever + + } else { +# print "Unhandled (line: $line): $text\n"; + } +} +close(F); + +# use Data::Dumper; +# print "Parsed build structure:\n"; +# print Dumper(%build_structure); + +# ------------------------------------------------------------------- +# Functions under here +# ------------------------------------------------------------------- +my (%build_structure, @defines, @incpaths, @cflags, @sources); + +sub clearCompileStep +{ + @defines = (); + @incpaths = (); + @cflags = (); + @sources = (); +} + +sub removeDuplicates +{ + my (%dupHash, $entry); + %dupHash = map { $_, 1 } @defines; + @defines = keys %dupHash; + + %dupHash = map { $_, 1 } @incpaths; + @incpaths = keys %dupHash; + + %dupHash = map { $_, 1 } @cflags; + @cflags = keys %dupHash; + + %dupHash = map { $_, 1 } @sources; + @sources = keys %dupHash; +} + +sub handleCompileLine +{ + my ($line, $lineno) = @_; + my @parts = split(' ', $line); + shift(@parts); # ignore cmd + while (my $part = shift @parts) { + if ("$part" eq "-o") { + # ignore object file + shift @parts; + } elsif ("$part" eq "-c") { + # ignore compile flag + } elsif ("$part" eq "-c") { + } elsif ($part =~ /^.?-I/) { + push(@incpaths, $part); + } elsif ($part =~ /^.?-D/) { + push(@defines, $part); + } elsif ($part =~ /^-/) { + push(@cflags, $part); + } elsif ($part =~ /\.(c|cc|cpp)$/) { + push(@sources, $part); + } else { + die "Unhandled compiler option @ line $lineno: $part"; + } + } + #print "Sources: @sources\nCFlags: @cflags\nDefine: @defines\nIncpat: @incpaths\n"; + #exit(1); +} + +sub handleLibLine +{ + my ($line, $lineno) = @_; + my (@objfiles, @lflags, $libout, $part); + # kill cmd and rm 'prefix' + $line =~ s/^rm -f .* && .* rcs //; + my @parts = split(' ', $line); + while ($part = shift @parts) { + if ($part =~ /^-/) { + push(@lflags, $part); + } elsif ($part =~ /\.(o|obj)$/) { + push(@objfiles, $part); + } elsif ($part =~ /\.(a|lib)$/) { + $libout = $part; + } else { + die "Unhandled lib option @ line $lineno: $part"; + } + } + #print "LibOut: '$libout'\nLFlags: @lflags\nOfiles: @objfiles\n"; + #exit(1); + removeDuplicates(); + push(@{$build_structure{"LIBS"}}, $libout); + @{$build_structure{"LIBS_${libout}"}} = ("_DEFINES", "_INCLUDES", "_CFLAGS", "_SOURCES", + "_OBJECTS"); + @{$build_structure{"LIBS_${libout}_DEFINES"}} = @defines; + @{$build_structure{"LIBS_${libout}_INCLUDES"}} = @incpaths; + @{$build_structure{"LIBS_${libout}_CFLAGS"}} = @cflags; + @{$build_structure{"LIBS_${libout}_SOURCES"}} = @sources; + @{$build_structure{"LIBS_${libout}_OBJECTS"}} = @objfiles; + clearCompileStep(); +} + +sub handleLinkLine +{ + my ($line, $lineno) = @_; + my (@objfiles, @lflags, @libs, $appout, $part); + my @parts = split(' ', $line); + shift(@parts); # ignore cmd + while ($part = shift @parts) { + if ($part =~ /^-[GRIDO]/) { + # eat compiler flags + } elsif ("$part" eq "-o") { + $appout = shift @parts; + } elsif ($part =~ /^-/) { + push(@lflags, $part); + } elsif ($part =~ /\.(a|lib)$/) { + push(@libs, $part); + } elsif ($part =~ /\.(o|obj)$/) { + push(@objfiles, $part); + } else { + die "Unhandled lib option @ line $lineno: $part"; + } + } + #print "AppOut: '$appout'\nLFlags: @lflags\nLibs : @libs\nOfiles: @objfiles\n"; + #exit(1); + removeDuplicates(); + push(@{$build_structure{"APPS"}}, $appout); + @{$build_structure{"APPS_${appout}"}} = ("_DEFINES", "_INCLUDES", "_CFLAGS", "_LFLAGS", + "_SOURCES", "_OBJECTS", "_LIBS"); + @{$build_structure{"APPS_${appout}_DEFINES"}} = @defines; + @{$build_structure{"APPS_${appout}_INCLUDES"}} = @incpaths; + @{$build_structure{"APPS_${appout}_CFLAGS"}} = @cflags; + @{$build_structure{"APPS_${appout}_LFLAGS"}} = @lflags; + @{$build_structure{"APPS_${appout}_SOURCES"}} = @sources; + @{$build_structure{"APPS_${appout}_OBJECTS"}} = @objfiles; + @{$build_structure{"APPS_${appout}_LIBS"}} = @libs; + clearCompileStep(); +} diff --git a/contrib/coccinelle/.gitignore b/contrib/coccinelle/.gitignore new file mode 100644 index 0000000..1d45c0a --- /dev/null +++ b/contrib/coccinelle/.gitignore @@ -0,0 +1 @@ +*.patch diff --git a/contrib/coccinelle/README b/contrib/coccinelle/README new file mode 100644 index 0000000..d1daa1f --- /dev/null +++ b/contrib/coccinelle/README @@ -0,0 +1,92 @@ +This directory provides examples of Coccinelle (http://coccinelle.lip6.fr/) +semantic patches that might be useful to developers. + +There are two 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 + it is expected that any resulting patch indicates a regression. + The patches resulting from 'make coccicheck' are small and infrequent, + so once they are found, they can be sent to the mailing list as per usual. + + Example for introducing new patterns: + 67947c34ae (convert "hashcmp() != 0" to "!hasheq()", 2018-08-28) + b84c783882 (fsck: s/++i > 1/i++/, 2018-10-24) + + Example of fixes using this approach: + 248f66ed8e (run-command: use strbuf_addstr() for adding a string to + a strbuf, 2018-03-25) + f919ffebed (Use MOVE_ARRAY, 2018-01-22) + + These types of semantic patches are usually part of testing, c.f. + 0860a7641b (travis-ci: fail if Coccinelle static analysis found something + to transform, 2018-07-23) + + * Using semantic transformations in large scale refactorings throughout + the code base. + + When applying the semantic patch into a real patch, sending it to the + mailing list in the usual way, such a patch would be expected to have a + lot of textual and semantic conflicts as such large scale refactorings + change function signatures that are used widely in the code base. + A textual conflict would arise if surrounding code near any call of such + function changes. A semantic conflict arises when other patch series in + flight introduce calls to such functions. + + So to aid these large scale refactorings, semantic patches can be used. + However we do not want to store them in the same place as the checks for + bad patterns, as then automated builds would fail. + That is why semantic patches 'contrib/coccinelle/*.pending.cocci' + are ignored for checks, and can be applied using 'make coccicheck-pending'. + + 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 in the (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. diff --git a/contrib/coccinelle/array.cocci b/contrib/coccinelle/array.cocci new file mode 100644 index 0000000..aa75937 --- /dev/null +++ b/contrib/coccinelle/array.cocci @@ -0,0 +1,96 @@ +@@ +type T; +T *dst_ptr; +T *src_ptr; +expression n; +@@ +- memcpy(dst_ptr, src_ptr, (n) * \( sizeof(T) +- \| sizeof(*(dst_ptr)) +- \| sizeof(*(src_ptr)) +- \| sizeof(dst_ptr[...]) +- \| sizeof(src_ptr[...]) +- \) ) ++ COPY_ARRAY(dst_ptr, src_ptr, n) + +@@ +type T; +T *dst_ptr; +T[] src_arr; +expression n; +@@ +- memcpy(dst_ptr, src_arr, (n) * \( sizeof(T) +- \| sizeof(*(dst_ptr)) +- \| sizeof(*(src_arr)) +- \| sizeof(dst_ptr[...]) +- \| sizeof(src_arr[...]) +- \) ) ++ COPY_ARRAY(dst_ptr, src_arr, n) + +@@ +type T; +T[] dst_arr; +T *src_ptr; +expression n; +@@ +- memcpy(dst_arr, src_ptr, (n) * \( sizeof(T) +- \| sizeof(*(dst_arr)) +- \| sizeof(*(src_ptr)) +- \| sizeof(dst_arr[...]) +- \| sizeof(src_ptr[...]) +- \) ) ++ COPY_ARRAY(dst_arr, src_ptr, n) + +@@ +type T; +T[] dst_arr; +T[] src_arr; +expression n; +@@ +- memcpy(dst_arr, src_arr, (n) * \( sizeof(T) +- \| sizeof(*(dst_arr)) +- \| sizeof(*(src_arr)) +- \| sizeof(dst_arr[...]) +- \| sizeof(src_arr[...]) +- \) ) ++ COPY_ARRAY(dst_arr, src_arr, n) + +@@ +type T; +T *dst; +T *src; +expression n; +@@ +( +- memmove(dst, src, (n) * sizeof(*dst)); ++ MOVE_ARRAY(dst, src, n); +| +- memmove(dst, src, (n) * sizeof(*src)); ++ MOVE_ARRAY(dst, src, n); +| +- memmove(dst, src, (n) * sizeof(T)); ++ MOVE_ARRAY(dst, src, n); +) + +@@ +type T; +T *ptr; +expression n; +@@ +- ptr = xmalloc((n) * sizeof(*ptr)); ++ ALLOC_ARRAY(ptr, n); + +@@ +type T; +T *ptr; +expression n; +@@ +- ptr = xmalloc((n) * sizeof(T)); ++ ALLOC_ARRAY(ptr, n); + +@@ +type T; +T *ptr; +expression n != 1; +@@ +- ptr = xcalloc(n, \( sizeof(*ptr) \| sizeof(T) \) ) ++ CALLOC_ARRAY(ptr, n) diff --git a/contrib/coccinelle/commit.cocci b/contrib/coccinelle/commit.cocci new file mode 100644 index 0000000..af6dd4c --- /dev/null +++ b/contrib/coccinelle/commit.cocci @@ -0,0 +1,52 @@ +@@ +expression c; +@@ +- &c->maybe_tree->object.oid ++ get_commit_tree_oid(c) + +@@ +expression c; +@@ +- c->maybe_tree->object.oid.hash ++ get_commit_tree_oid(c)->hash + +@@ +identifier f !~ "^set_commit_tree$"; +expression c; +expression s; +@@ + f(...) {<... +- c->maybe_tree = s ++ set_commit_tree(c, s) + ...>} + +// These excluded functions must access c->maybe_tree directly. +// Note that if c->maybe_tree is written somewhere outside of these +// functions, then the recommended transformation will be bogus with +// repo_get_commit_tree() on the LHS. +@@ +identifier f !~ "^(repo_get_commit_tree|get_commit_tree_in_graph_one|load_tree_for_commit|set_commit_tree)$"; +expression c; +@@ + f(...) {<... +- c->maybe_tree ++ repo_get_commit_tree(specify_the_right_repo_here, c) + ...>} + +@@ +struct commit *c; +expression E; +@@ +( +- c->generation = E; ++ commit_graph_data_at(c)->generation = E; +| +- c->graph_pos = E; ++ commit_graph_data_at(c)->graph_pos = E; +| +- c->generation ++ commit_graph_generation(c) +| +- c->graph_pos ++ commit_graph_position(c) +) diff --git a/contrib/coccinelle/equals-null.cocci b/contrib/coccinelle/equals-null.cocci new file mode 100644 index 0000000..92c7054 --- /dev/null +++ b/contrib/coccinelle/equals-null.cocci @@ -0,0 +1,30 @@ +/* SPDX-License-Identifier: LGPL-2.1-or-later */ +@@ +expression e; +statement s; +@@ +if ( +( +!e +| +- e == NULL ++ !e +) + ) + {...} +else s + +@@ +expression e; +statement s; +@@ +if ( +( +e +| +- e != NULL ++ e +) + ) + {...} +else s diff --git a/contrib/coccinelle/flex_alloc.cocci b/contrib/coccinelle/flex_alloc.cocci new file mode 100644 index 0000000..e9f7f6d --- /dev/null +++ b/contrib/coccinelle/flex_alloc.cocci @@ -0,0 +1,13 @@ +@@ +expression str; +identifier x, flexname; +@@ +- FLEX_ALLOC_MEM(x, flexname, str, strlen(str)); ++ FLEX_ALLOC_STR(x, flexname, str); + +@@ +expression str; +identifier x, ptrname; +@@ +- FLEXPTR_ALLOC_MEM(x, ptrname, str, strlen(str)); ++ FLEXPTR_ALLOC_STR(x, ptrname, str); diff --git a/contrib/coccinelle/free.cocci b/contrib/coccinelle/free.cocci new file mode 100644 index 0000000..6fb9eb6 --- /dev/null +++ b/contrib/coccinelle/free.cocci @@ -0,0 +1,45 @@ +@@ +expression E; +@@ +- if (E) +( + free(E); +| + free_commit_list(E); +) + +@@ +expression E; +@@ +- if (!E) +( + free(E); +| + free_commit_list(E); +) + +@@ +expression E; +@@ +- free(E); ++ FREE_AND_NULL(E); +- E = NULL; + +@@ +expression E; +@@ +- if (E) +- { + free_commit_list(E); + E = NULL; +- } + +@@ +expression E; +statement S; +@@ +- if (E) { ++ if (E) + S + free_commit_list(E); +- } diff --git a/contrib/coccinelle/hashmap.cocci b/contrib/coccinelle/hashmap.cocci new file mode 100644 index 0000000..c5dbb45 --- /dev/null +++ b/contrib/coccinelle/hashmap.cocci @@ -0,0 +1,16 @@ +@@ +expression E; +struct hashmap_entry HME; +@@ +- HME.hash = E; ++ hashmap_entry_init(&HME, E); + +@@ +identifier f !~ "^hashmap_entry_init$"; +expression E; +struct hashmap_entry *HMEP; +@@ + f(...) {<... +- HMEP->hash = E; ++ hashmap_entry_init(HMEP, E); + ...>} diff --git a/contrib/coccinelle/index-compatibility.cocci b/contrib/coccinelle/index-compatibility.cocci new file mode 100644 index 0000000..8520f03 --- /dev/null +++ b/contrib/coccinelle/index-compatibility.cocci @@ -0,0 +1,139 @@ +// the_index.* variables +@@ +identifier AC = active_cache; +identifier ACC = active_cache_changed; +identifier ACT = active_cache_tree; +@@ +( +- AC ++ the_index.cache +| +- ACC ++ the_index.cache_changed +| +- ACT ++ the_index.cache_tree +) + +@@ +identifier AN = active_nr; +identifier f != prepare_to_commit; +@@ + f(...) {<... +- AN ++ the_index.cache_nr + ...>} + +// "the_repository" simple cases +@@ +@@ +( +- 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 +) + ( ++ &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 + ) diff --git a/contrib/coccinelle/index-compatibility.pending.cocci b/contrib/coccinelle/index-compatibility.pending.cocci new file mode 100644 index 0000000..01f875d --- /dev/null +++ b/contrib/coccinelle/index-compatibility.pending.cocci @@ -0,0 +1,24 @@ +// "the_repository" simple cases +@@ +@@ +( +- read_cache ++ repo_read_index +) + ( ++ the_repository, + ...) + +// "the_index" simple cases +@@ +@@ +( +- discard_cache ++ discard_index +| +- cache_name_pos ++ index_name_pos +) + ( ++ &the_index, + ...) diff --git a/contrib/coccinelle/object_id.cocci b/contrib/coccinelle/object_id.cocci new file mode 100644 index 0000000..01f8d69 --- /dev/null +++ b/contrib/coccinelle/object_id.cocci @@ -0,0 +1,75 @@ +@@ +struct object_id OID; +@@ +- hashclr(OID.hash) ++ oidclr(&OID) + +@@ +identifier f != oidclr; +struct object_id *OIDPTR; +@@ + f(...) {<... +- hashclr(OIDPTR->hash) ++ oidclr(OIDPTR) + ...>} + +@@ +struct object_id OID1, OID2; +@@ +- hashcmp(OID1.hash, OID2.hash) ++ oidcmp(&OID1, &OID2) + +@@ +identifier f != oidcmp; +struct object_id *OIDPTR1, OIDPTR2; +@@ + f(...) {<... +- hashcmp(OIDPTR1->hash, OIDPTR2->hash) ++ oidcmp(OIDPTR1, OIDPTR2) + ...>} + +@@ +struct object_id *OIDPTR; +struct object_id OID; +@@ +- hashcmp(OIDPTR->hash, OID.hash) ++ oidcmp(OIDPTR, &OID) + +@@ +struct object_id *OIDPTR; +struct object_id OID; +@@ +- hashcmp(OID.hash, OIDPTR->hash) ++ oidcmp(&OID, OIDPTR) + +@@ +struct object_id *OIDPTR1; +struct object_id *OIDPTR2; +@@ +- oidcmp(OIDPTR1, OIDPTR2) == 0 ++ oideq(OIDPTR1, OIDPTR2) + +@@ +identifier f != hasheq; +expression E1, E2; +@@ + f(...) {<... +- hashcmp(E1, E2) == 0 ++ hasheq(E1, E2) + ...>} + +@@ +struct object_id *OIDPTR1; +struct object_id *OIDPTR2; +@@ +- oidcmp(OIDPTR1, OIDPTR2) != 0 ++ !oideq(OIDPTR1, OIDPTR2) + +@@ +identifier f != hasheq; +expression E1, E2; +@@ + f(...) {<... +- hashcmp(E1, E2) != 0 ++ !hasheq(E1, E2) + ...>} diff --git a/contrib/coccinelle/preincr.cocci b/contrib/coccinelle/preincr.cocci new file mode 100644 index 0000000..ae42cb0 --- /dev/null +++ b/contrib/coccinelle/preincr.cocci @@ -0,0 +1,5 @@ +@@ +identifier i; +@@ +- ++i > 1 ++ i++ diff --git a/contrib/coccinelle/qsort.cocci b/contrib/coccinelle/qsort.cocci new file mode 100644 index 0000000..22b93a9 --- /dev/null +++ b/contrib/coccinelle/qsort.cocci @@ -0,0 +1,37 @@ +@@ +expression base, nmemb, compar; +@@ +- qsort(base, nmemb, sizeof(*base), compar); ++ QSORT(base, nmemb, compar); + +@@ +expression base, nmemb, compar; +@@ +- qsort(base, nmemb, sizeof(base[0]), compar); ++ QSORT(base, nmemb, compar); + +@@ +type T; +T *base; +expression nmemb, compar; +@@ +- qsort(base, nmemb, sizeof(T), compar); ++ QSORT(base, nmemb, compar); + +@@ +expression base, nmemb, compar; +@@ +- if (nmemb) + QSORT(base, nmemb, compar); + +@@ +expression base, nmemb, compar; +@@ +- if (nmemb > 0) + QSORT(base, nmemb, compar); + +@@ +expression base, nmemb, compar; +@@ +- if (nmemb > 1) + QSORT(base, nmemb, compar); 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 +# +# 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 new file mode 100644 index 0000000..5f06105 --- /dev/null +++ b/contrib/coccinelle/strbuf.cocci @@ -0,0 +1,62 @@ +@@ +expression E; +constant fmt !~ "%"; +@@ +- strbuf_addf ++ strbuf_addstr + (E, +( + fmt +| + _(fmt) +) + ); + +@@ +expression E; +struct strbuf SB; +format F =~ "^s$"; +@@ +- strbuf_addf(E, "%@F@", SB.buf); ++ strbuf_addbuf(E, &SB); + +@@ +expression E; +struct strbuf *SBP; +format F =~ "^s$"; +@@ +- strbuf_addf(E, "%@F@", SBP->buf); ++ strbuf_addbuf(E, SBP); + +@@ +expression E; +struct strbuf SB; +@@ +- strbuf_addstr(E, SB.buf); ++ strbuf_addbuf(E, &SB); + +@@ +expression E; +struct strbuf *SBP; +@@ +- strbuf_addstr(E, SBP->buf); ++ strbuf_addbuf(E, SBP); + +@@ +expression E1, E2; +format F =~ "^s$"; +@@ +- strbuf_addf(E1, "%@F@", E2); ++ strbuf_addstr(E1, E2); + +@@ +expression E1, E2, E3; +@@ +- strbuf_addstr(E1, find_unique_abbrev(E2, E3)); ++ strbuf_add_unique_abbrev(E1, E2, E3); + +@@ +expression E1, E2; +@@ +- strbuf_addstr(E1, real_path(E2)); ++ strbuf_add_real_path(E1, E2); diff --git a/contrib/coccinelle/swap.cocci b/contrib/coccinelle/swap.cocci new file mode 100644 index 0000000..522177a --- /dev/null +++ b/contrib/coccinelle/swap.cocci @@ -0,0 +1,28 @@ +@@ +type T; +identifier tmp; +T a, b; +@@ +- T tmp = a; ++ T tmp; ++ tmp = a; + a = b; + b = tmp; + +@ swap @ +type T; +T tmp, a, b; +@@ +- tmp = a; +- a = b; +- b = tmp; ++ SWAP(a, b); + +@ extends swap @ +identifier unused; +@@ + { + ... +- T unused; + ... when != unused + } diff --git a/contrib/coccinelle/tests/free.c b/contrib/coccinelle/tests/free.c new file mode 100644 index 0000000..96d4abc --- /dev/null +++ b/contrib/coccinelle/tests/free.c @@ -0,0 +1,11 @@ +int use_FREE_AND_NULL(int *v) +{ + free(*v); + *v = NULL; +} + +int need_no_if(int *v) +{ + if (v) + free(v); +} diff --git a/contrib/coccinelle/tests/free.res b/contrib/coccinelle/tests/free.res new file mode 100644 index 0000000..f90fd9f --- /dev/null +++ b/contrib/coccinelle/tests/free.res @@ -0,0 +1,9 @@ +int use_FREE_AND_NULL(int *v) +{ + FREE_AND_NULL(*v); +} + +int need_no_if(int *v) +{ + free(v); +} diff --git a/contrib/coccinelle/tests/unused.c b/contrib/coccinelle/tests/unused.c new file mode 100644 index 0000000..8294d73 --- /dev/null +++ b/contrib/coccinelle/tests/unused.c @@ -0,0 +1,82 @@ +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 new file mode 100644 index 0000000..6d3e745 --- /dev/null +++ b/contrib/coccinelle/tests/unused.res @@ -0,0 +1,45 @@ +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.pending.cocci b/contrib/coccinelle/the_repository.pending.cocci new file mode 100644 index 0000000..747d382 --- /dev/null +++ b/contrib/coccinelle/the_repository.pending.cocci @@ -0,0 +1,128 @@ +// 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; +@@ +- 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 new file mode 100644 index 0000000..d84046f --- /dev/null +++ b/contrib/coccinelle/unused.cocci @@ -0,0 +1,43 @@ +// 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/xcalloc.cocci b/contrib/coccinelle/xcalloc.cocci new file mode 100644 index 0000000..c291011 --- /dev/null +++ b/contrib/coccinelle/xcalloc.cocci @@ -0,0 +1,10 @@ +@@ +type T; +T *ptr; +expression n; +@@ + xcalloc( ++ n, + \( sizeof(T) \| sizeof(*ptr) \) +- , n + ) diff --git a/contrib/coccinelle/xopen.cocci b/contrib/coccinelle/xopen.cocci new file mode 100644 index 0000000..b71db67 --- /dev/null +++ b/contrib/coccinelle/xopen.cocci @@ -0,0 +1,19 @@ +@@ +identifier fd; +identifier die_fn =~ "^(die|die_errno)$"; +@@ + int fd = +- open ++ xopen + (...); +- if ( \( fd < 0 \| fd == -1 \) ) { die_fn(...); } + +@@ +expression fd; +identifier die_fn =~ "^(die|die_errno)$"; +@@ + fd = +- open ++ xopen + (...); +- if ( \( fd < 0 \| fd == -1 \) ) { die_fn(...); } diff --git a/contrib/coccinelle/xstrdup_or_null.cocci b/contrib/coccinelle/xstrdup_or_null.cocci new file mode 100644 index 0000000..9c1d293 --- /dev/null +++ b/contrib/coccinelle/xstrdup_or_null.cocci @@ -0,0 +1,5 @@ +@@ +expression E; +@@ +- xstrdup(absolute_path(E)) ++ absolute_pathdup(E) diff --git a/contrib/completion/.gitattributes b/contrib/completion/.gitattributes new file mode 100644 index 0000000..1911694 --- /dev/null +++ b/contrib/completion/.gitattributes @@ -0,0 +1 @@ +*.bash eol=lf diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash new file mode 100644 index 0000000..ba5c395 --- /dev/null +++ b/contrib/completion/git-completion.bash @@ -0,0 +1,3591 @@ +# bash/zsh completion support for core Git. +# +# Copyright (C) 2006,2007 Shawn O. Pearce +# Conceptually based on gitcompletion (http://gitweb.hawaga.org.uk/). +# Distributed under the GNU General Public License, version 2.0. +# +# The contained completion routines provide support for completing: +# +# *) local and remote branch names +# *) local and remote tag names +# *) .git/remotes file names +# *) git 'subcommands' +# *) git email aliases for git-send-email +# *) tree paths within 'ref:path/to/file' expressions +# *) file paths within current working directory and index +# *) common --long-options +# +# To use these routines: +# +# 1) Copy this file to somewhere (e.g. ~/.git-completion.bash). +# 2) Add the following line to your .bashrc/.zshrc: +# source ~/.git-completion.bash +# 3) Consider changing your PS1 to also show the current branch, +# see git-prompt.sh for details. +# +# If you use complex aliases of form '!f() { ... }; f', you can use the null +# command ':' as the first command in the function body to declare the desired +# 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 ; ... '". +# +# If you have a command that is not part of git, but you would still +# like completion, you can use __git_complete: +# +# __git_complete gl git_log +# +# Or if it's a main command (i.e. git or gitk): +# +# __git_complete gk gitk +# +# Compatible with bash 3.2.57. +# +# You can set the following environment variables to influence the behavior of +# the completion routines: +# +# GIT_COMPLETION_CHECKOUT_NO_GUESS +# +# When set to "1", do not include "DWIM" suggestions in git-checkout +# and git-switch completion (e.g., completing "foo" when "origin/foo" +# exists). +# +# GIT_COMPLETION_SHOW_ALL_COMMANDS +# +# When set to "1" suggest all commands, including plumbing commands +# which are hidden by default (e.g. "cat-file" on "git ca"). +# +# GIT_COMPLETION_SHOW_ALL +# +# When set to "1" suggest all options, including options which are +# typically hidden (e.g. '--allow-empty' for 'git commit'). + +case "$COMP_WORDBREAKS" in +*:*) : great ;; +*) COMP_WORDBREAKS="$COMP_WORDBREAKS:" +esac + +# Discovers the path to the git repository taking any '--git-dir=' and +# '-C ' options into account and stores it in the $__git_repo_path +# variable. +__git_find_repo_path () +{ + if [ -n "${__git_repo_path-}" ]; then + # we already know where it is + return + fi + + if [ -n "${__git_C_args-}" ]; then + __git_repo_path="$(git "${__git_C_args[@]}" \ + ${__git_dir:+--git-dir="$__git_dir"} \ + rev-parse --absolute-git-dir 2>/dev/null)" + elif [ -n "${__git_dir-}" ]; then + test -d "$__git_dir" && + __git_repo_path="$__git_dir" + elif [ -n "${GIT_DIR-}" ]; then + test -d "$GIT_DIR" && + __git_repo_path="$GIT_DIR" + elif [ -d .git ]; then + __git_repo_path=.git + else + __git_repo_path="$(git rev-parse --git-dir 2>/dev/null)" + fi +} + +# Deprecated: use __git_find_repo_path() and $__git_repo_path instead +# __gitdir accepts 0 or 1 arguments (i.e., location) +# returns location of .git repo +__gitdir () +{ + if [ -z "${1-}" ]; then + __git_find_repo_path || return 1 + echo "$__git_repo_path" + elif [ -d "$1/.git" ]; then + echo "$1/.git" + else + echo "$1" + fi +} + +# Runs git with all the options given as argument, respecting any +# '--git-dir=' and '-C ' options present on the command line +__git () +{ + git ${__git_C_args:+"${__git_C_args[@]}"} \ + ${__git_dir:+--git-dir="$__git_dir"} "$@" 2>/dev/null +} + +# Removes backslash escaping, single quotes and double quotes from a word, +# stores the result in the variable $dequoted_word. +# 1: The word to dequote. +__git_dequote () +{ + local rest="$1" len ch + + dequoted_word="" + + while test -n "$rest"; do + len=${#dequoted_word} + dequoted_word="$dequoted_word${rest%%[\\\'\"]*}" + rest="${rest:$((${#dequoted_word}-$len))}" + + case "${rest:0:1}" in + \\) + ch="${rest:1:1}" + case "$ch" in + $'\n') + ;; + *) + dequoted_word="$dequoted_word$ch" + ;; + esac + rest="${rest:2}" + ;; + \') + rest="${rest:1}" + len=${#dequoted_word} + dequoted_word="$dequoted_word${rest%%\'*}" + rest="${rest:$((${#dequoted_word}-$len+1))}" + ;; + \") + rest="${rest:1}" + while test -n "$rest" ; do + len=${#dequoted_word} + dequoted_word="$dequoted_word${rest%%[\\\"]*}" + rest="${rest:$((${#dequoted_word}-$len))}" + case "${rest:0:1}" in + \\) + ch="${rest:1:1}" + case "$ch" in + \"|\\|\$|\`) + dequoted_word="$dequoted_word$ch" + ;; + $'\n') + ;; + *) + dequoted_word="$dequoted_word\\$ch" + ;; + esac + rest="${rest:2}" + ;; + \") + rest="${rest:1}" + break + ;; + esac + done + ;; + esac + done +} + +# The following function is based on code from: +# +# bash_completion - programmable completion functions for bash 3.2+ +# +# Copyright © 2006-2008, Ian Macdonald +# © 2009-2010, Bash Completion Maintainers +# +# +# 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 . +# +# The latest version of this software can be obtained here: +# +# http://bash-completion.alioth.debian.org/ +# +# RELEASE: 2.x + +# This function can be used to access a tokenized list of words +# on the command line: +# +# __git_reassemble_comp_words_by_ref '=:' +# if test "${words_[cword_-1]}" = -w +# then +# ... +# fi +# +# The argument should be a collection of characters from the list of +# word completion separators (COMP_WORDBREAKS) to treat as ordinary +# characters. +# +# This is roughly equivalent to going back in time and setting +# COMP_WORDBREAKS to exclude those characters. The intent is to +# make option types like --date= and : easy to +# recognize by treating each shell word as a single token. +# +# It is best not to set COMP_WORDBREAKS directly because the value is +# shared with other completion scripts. By the time the completion +# function gets called, COMP_WORDS has already been populated so local +# changes to COMP_WORDBREAKS have no effect. +# +# Output: words_, cword_, cur_. + +__git_reassemble_comp_words_by_ref() +{ + local exclude i j first + # Which word separators to exclude? + exclude="${1//[^$COMP_WORDBREAKS]}" + cword_=$COMP_CWORD + if [ -z "$exclude" ]; then + words_=("${COMP_WORDS[@]}") + return + fi + # List of word completion separators has shrunk; + # re-assemble words to complete. + for ((i=0, j=0; i < ${#COMP_WORDS[@]}; i++, j++)); do + # Append each nonempty word consisting of just + # word separator characters to the current word. + first=t + while + [ $i -gt 0 ] && + [ -n "${COMP_WORDS[$i]}" ] && + # word consists of excluded word separators + [ "${COMP_WORDS[$i]//[^$exclude]}" = "${COMP_WORDS[$i]}" ] + do + # Attach to the previous token, + # unless the previous token is the command name. + if [ $j -ge 2 ] && [ -n "$first" ]; then + ((j--)) + fi + first= + words_[$j]=${words_[j]}${COMP_WORDS[i]} + if [ $i = $COMP_CWORD ]; then + cword_=$j + fi + if (($i < ${#COMP_WORDS[@]} - 1)); then + ((i++)) + else + # Done. + return + fi + done + words_[$j]=${words_[j]}${COMP_WORDS[i]} + if [ $i = $COMP_CWORD ]; then + cword_=$j + fi + done +} + +if ! type _get_comp_words_by_ref >/dev/null 2>&1; then +_get_comp_words_by_ref () +{ + local exclude cur_ words_ cword_ + if [ "$1" = "-n" ]; then + exclude=$2 + shift 2 + fi + __git_reassemble_comp_words_by_ref "$exclude" + cur_=${words_[cword_]} + while [ $# -gt 0 ]; do + case "$1" in + cur) + cur=$cur_ + ;; + prev) + prev=${words_[$cword_-1]} + ;; + words) + words=("${words_[@]}") + ;; + cword) + cword=$cword_ + ;; + esac + shift + done +} +fi + +# Fills the COMPREPLY array with prefiltered words without any additional +# processing. +# Callers must take care of providing only words that match the current word +# to be completed and adding any prefix and/or suffix (trailing space!), if +# necessary. +# 1: List of newline-separated matching completion words, complete with +# prefix and suffix. +__gitcomp_direct () +{ + local IFS=$'\n' + + COMPREPLY=($1) +} + +# Similar to __gitcomp_direct, but appends to COMPREPLY instead. +# Callers must take care of providing only words that match the current word +# to be completed and adding any prefix and/or suffix (trailing space!), if +# necessary. +# 1: List of newline-separated matching completion words, complete with +# prefix and suffix. +__gitcomp_direct_append () +{ + local IFS=$'\n' + + COMPREPLY+=($1) +} + +__gitcompappend () +{ + local x i=${#COMPREPLY[@]} + for x in $1; do + if [[ "$x" == "$3"* ]]; then + COMPREPLY[i++]="$2$x$4" + fi + done +} + +__gitcompadd () +{ + COMPREPLY=() + __gitcompappend "$@" +} + +# Generates completion reply, appending a space to possible completion words, +# if necessary. +# It accepts 1 to 4 arguments: +# 1: List of possible completion words. +# 2: A prefix to be added to each possible completion word (optional). +# 3: Generate possible completion matches for this word (optional). +# 4: A suffix to be appended to each possible completion word (optional). +__gitcomp () +{ + local cur_="${3-$cur}" + + case "$cur_" in + *=) + ;; + --no-*) + local c i=0 IFS=$' \t\n' + for c in $1; do + if [[ $c == "--" ]]; then + continue + fi + c="$c${4-}" + if [[ $c == "$cur_"* ]]; then + case $c in + --*=|*.) ;; + *) c="$c " ;; + esac + COMPREPLY[i++]="${2-}$c" + fi + done + ;; + *) + local c i=0 IFS=$' \t\n' + for c in $1; do + if [[ $c == "--" ]]; then + c="--no-...${4-}" + if [[ $c == "$cur_"* ]]; then + COMPREPLY[i++]="${2-}$c " + fi + break + fi + c="$c${4-}" + if [[ $c == "$cur_"* ]]; then + case $c in + *=|*.) ;; + *) c="$c " ;; + esac + COMPREPLY[i++]="${2-}$c" + fi + done + ;; + esac +} + +# Clear the variables caching builtins' options when (re-)sourcing +# the completion script. +if [[ -n ${ZSH_VERSION-} ]]; then + unset ${(M)${(k)parameters[@]}:#__gitcomp_builtin_*} 2>/dev/null +else + unset $(compgen -v __gitcomp_builtin_) +fi + +# 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 +# 2: extra options to be added on top (e.g. negative forms) +# 3: options to be excluded +__gitcomp_builtin () +{ + # 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-}" + + local var=__gitcomp_builtin_"${cmd//-/_}" + local options + eval "options=\${$var-}" + + if [ -z "$options" ]; then + local completion_helper + if [ "${GIT_COMPLETION_SHOW_ALL-}" = "1" ]; then + completion_helper="--git-completion-helper-all" + else + completion_helper="--git-completion-helper" + fi + # leading and trailing spaces are significant to make + # option removal work correctly. + options=" $incl $(__git ${cmd/_/ } $completion_helper) " || return + + for i in $excl; do + options="${options/ $i / }" + done + eval "$var=\"$options\"" + fi + + __gitcomp "$options" +} + +# Variation of __gitcomp_nl () that appends to the existing list of +# completion candidates, COMPREPLY. +__gitcomp_nl_append () +{ + local IFS=$'\n' + __gitcompappend "$1" "${2-}" "${3-$cur}" "${4- }" +} + +# Generates completion reply from newline-separated possible completion words +# by appending a space to all of them. +# It accepts 1 to 4 arguments: +# 1: List of possible completion words, separated by a single newline. +# 2: A prefix to be added to each possible completion word (optional). +# 3: Generate possible completion matches for this word (optional). +# 4: A suffix to be appended to each possible completion word instead of +# the default space (optional). If specified but empty, nothing is +# appended. +__gitcomp_nl () +{ + COMPREPLY=() + __gitcomp_nl_append "$@" +} + +# Fills the COMPREPLY array with prefiltered paths without any additional +# processing. +# Callers must take care of providing only paths that match the current path +# to be completed and adding any prefix path components, if necessary. +# 1: List of newline-separated matching paths, complete with all prefix +# path components. +__gitcomp_file_direct () +{ + local IFS=$'\n' + + COMPREPLY=($1) + + # use a hack to enable file mode in bash < 4 + compopt -o filenames +o nospace 2>/dev/null || + compgen -f /non-existing-dir/ >/dev/null || + true +} + +# Generates completion reply with compgen from newline-separated possible +# completion filenames. +# It accepts 1 to 3 arguments: +# 1: List of possible completion filenames, separated by a single newline. +# 2: A directory prefix to be added to each possible completion filename +# (optional). +# 3: Generate possible completion matches for this word (optional). +__gitcomp_file () +{ + local IFS=$'\n' + + # XXX does not work when the directory prefix contains a tilde, + # since tilde expansion is not applied. + # This means that COMPREPLY will be empty and Bash default + # completion will be used. + __gitcompadd "$1" "${2-}" "${3-$cur}" "" + + # use a hack to enable file mode in bash < 4 + compopt -o filenames +o nospace 2>/dev/null || + compgen -f /non-existing-dir/ >/dev/null || + true +} + +# 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 +# argument, and using the options specified in the second argument. +__git_ls_files_helper () +{ + if [ "$2" = "--committable" ]; then + __git -C "$1" -c core.quotePath=false diff-index \ + --name-only --relative HEAD -- "${3//\\/\\\\}*" + else + # NOTE: $2 is not quoted in order to support multiple options + __git -C "$1" -c core.quotePath=false ls-files \ + --exclude-standard $2 -- "${3//\\/\\\\}*" + fi +} + + +# __git_index_files accepts 1 or 2 arguments: +# 1: Options to pass to ls-files (required). +# 2: A directory path (optional). +# If provided, only files within the specified directory are listed. +# Sub directories are never recursed. Path must have a trailing +# slash. +# 3: List only paths matching this path component (optional). +__git_index_files () +{ + local root="$2" match="$3" + + __git_ls_files_helper "$root" "$1" "${match:-?}" | + awk -F / -v pfx="${2//\\/\\\\}" '{ + paths[$1] = 1 + } + END { + for (p in paths) { + if (substr(p, 1, 1) != "\"") { + # No special characters, easy! + print pfx p + continue + } + + # The path is quoted. + p = dequote(p) + if (p == "") + continue + + # Even when a directory name itself does not contain + # any special characters, it will still be quoted if + # any of its (stripped) trailing path components do. + # Because of this we may have seen the same directory + # both quoted and unquoted. + if (p in paths) + # We have seen the same directory unquoted, + # skip it. + continue + else + print pfx p + } + } + function dequote(p, bs_idx, out, esc, esc_idx, dec) { + # Skip opening double quote. + p = substr(p, 2) + + # Interpret backslash escape sequences. + while ((bs_idx = index(p, "\\")) != 0) { + out = out substr(p, 1, bs_idx - 1) + esc = substr(p, bs_idx + 1, 1) + p = substr(p, bs_idx + 2) + + if ((esc_idx = index("abtvfr\"\\", esc)) != 0) { + # C-style one-character escape sequence. + out = out substr("\a\b\t\v\f\r\"\\", + esc_idx, 1) + } else if (esc == "n") { + # Uh-oh, a newline character. + # We cannot reliably put a pathname + # containing a newline into COMPREPLY, + # and the newline would create a mess. + # Skip this path. + return "" + } else { + # Must be a \nnn octal value, then. + dec = esc * 64 + \ + substr(p, 1, 1) * 8 + \ + substr(p, 2, 1) + out = out sprintf("%c", dec) + p = substr(p, 3) + } + } + # Drop closing double quote, if there is one. + # (There is not any if this is a directory, as it was + # already stripped with the trailing path components.) + if (substr(p, length(p), 1) == "\"") + out = out substr(p, 1, length(p) - 1) + else + out = out p + + return out + }' +} + +# __git_complete_index_file requires 1 argument: +# 1: the options to pass to ls-file +# +# The exception is --committable, which finds the files appropriate commit. +__git_complete_index_file () +{ + local dequoted_word pfx="" cur_ + + __git_dequote "$cur" + + case "$dequoted_word" in + ?*/*) + pfx="${dequoted_word%/*}/" + cur_="${dequoted_word##*/}" + ;; + *) + cur_="$dequoted_word" + esac + + __gitcomp_file_direct "$(__git_index_files "$1" "$pfx" "$cur_")" +} + +# Lists branches from the local repository. +# 1: A prefix to be added to each listed branch (optional). +# 2: List only branches matching this word (optional; list all branches if +# unset or empty). +# 3: A suffix to be appended to each listed branch (optional). +__git_heads () +{ + local pfx="${1-}" cur_="${2-}" sfx="${3-}" + + __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \ + "refs/heads/$cur_*" "refs/heads/$cur_*/**" +} + +# Lists branches from remote repositories. +# 1: A prefix to be added to each listed branch (optional). +# 2: List only branches matching this word (optional; list all branches if +# unset or empty). +# 3: A suffix to be appended to each listed branch (optional). +__git_remote_heads () +{ + local pfx="${1-}" cur_="${2-}" sfx="${3-}" + + __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \ + "refs/remotes/$cur_*" "refs/remotes/$cur_*/**" +} + +# Lists tags from the local repository. +# Accepts the same positional parameters as __git_heads() above. +__git_tags () +{ + local pfx="${1-}" cur_="${2-}" sfx="${3-}" + + __git for-each-ref --format="${pfx//\%/%%}%(refname:strip=2)$sfx" \ + "refs/tags/$cur_*" "refs/tags/$cur_*/**" +} + +# List unique branches from refs/remotes used for 'git checkout' and 'git +# switch' tracking DWIMery. +# 1: A prefix to be added to each listed branch (optional) +# 2: List only branches matching this word (optional; list all branches if +# unset or empty). +# 3: A suffix to be appended to each listed branch (optional). +__git_dwim_remote_heads () +{ + local pfx="${1-}" cur_="${2-}" sfx="${3-}" + local fer_pfx="${pfx//\%/%%}" # "escape" for-each-ref format specifiers + + # employ the heuristic used by git checkout and git switch + # Try to find a remote branch that cur_es the completion word + # but only output if the branch name is unique + __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \ + --sort="refname:strip=3" \ + "refs/remotes/*/$cur_*" "refs/remotes/*/$cur_*/**" | \ + uniq -u +} + +# Lists refs from the local (by default) or from a remote repository. +# It accepts 0, 1 or 2 arguments: +# 1: The remote to list refs from (optional; ignored, if set but empty). +# Can be the name of a configured remote, a path, or a URL. +# 2: In addition to local refs, list unique branches from refs/remotes/ for +# 'git checkout's tracking DWIMery (optional; ignored, if set but empty). +# 3: A prefix to be added to each listed ref (optional). +# 4: List only refs matching this word (optional; list all refs if unset or +# empty). +# 5: A suffix to be appended to each listed ref (optional; ignored, if set +# but empty). +# +# Use __git_complete_refs() instead. +__git_refs () +{ + local i hash dir track="${2-}" + local list_refs_from=path remote="${1-}" + local format refs + local pfx="${3-}" cur_="${4-$cur}" sfx="${5-}" + local match="${4-}" + local fer_pfx="${pfx//\%/%%}" # "escape" for-each-ref format specifiers + + __git_find_repo_path + dir="$__git_repo_path" + + if [ -z "$remote" ]; then + if [ -z "$dir" ]; then + return + fi + else + if __git_is_configured_remote "$remote"; then + # configured remote takes precedence over a + # local directory with the same name + list_refs_from=remote + elif [ -d "$remote/.git" ]; then + dir="$remote/.git" + elif [ -d "$remote" ]; then + dir="$remote" + else + list_refs_from=url + fi + fi + + if [ "$list_refs_from" = path ]; then + if [[ "$cur_" == ^* ]]; then + pfx="$pfx^" + fer_pfx="$fer_pfx^" + cur_=${cur_#^} + match=${match#^} + fi + case "$cur_" in + refs|refs/*) + format="refname" + refs=("$match*" "$match*/**") + track="" + ;; + *) + for i in HEAD FETCH_HEAD ORIG_HEAD MERGE_HEAD REBASE_HEAD CHERRY_PICK_HEAD; do + case "$i" in + $match*) + if [ -e "$dir/$i" ]; then + echo "$pfx$i$sfx" + fi + ;; + esac + done + format="refname:strip=2" + refs=("refs/tags/$match*" "refs/tags/$match*/**" + "refs/heads/$match*" "refs/heads/$match*/**" + "refs/remotes/$match*" "refs/remotes/$match*/**") + ;; + esac + __git_dir="$dir" __git for-each-ref --format="$fer_pfx%($format)$sfx" \ + "${refs[@]}" + if [ -n "$track" ]; then + __git_dwim_remote_heads "$pfx" "$match" "$sfx" + fi + return + fi + case "$cur_" in + refs|refs/*) + __git ls-remote "$remote" "$match*" | \ + while read -r hash i; do + case "$i" in + *^{}) ;; + *) echo "$pfx$i$sfx" ;; + esac + done + ;; + *) + if [ "$list_refs_from" = remote ]; then + case "HEAD" in + $match*) echo "${pfx}HEAD$sfx" ;; + esac + __git for-each-ref --format="$fer_pfx%(refname:strip=3)$sfx" \ + "refs/remotes/$remote/$match*" \ + "refs/remotes/$remote/$match*/**" + else + local query_symref + case "HEAD" in + $match*) query_symref="HEAD" ;; + esac + __git ls-remote "$remote" $query_symref \ + "refs/tags/$match*" "refs/heads/$match*" \ + "refs/remotes/$match*" | + while read -r hash i; do + case "$i" in + *^{}) ;; + refs/*) echo "$pfx${i#refs/*/}$sfx" ;; + *) echo "$pfx$i$sfx" ;; # symbolic refs + esac + done + fi + ;; + esac +} + +# Completes refs, short and long, local and remote, symbolic and pseudo. +# +# Usage: __git_complete_refs [