summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--.gitattributes6
-rw-r--r--.gitignore3
-rw-r--r--.mailmap4
-rw-r--r--.travis.yml3
-rw-r--r--Documentation/Makefile3
-rw-r--r--Documentation/RelNotes/2.13.7.txt20
-rw-r--r--Documentation/RelNotes/2.14.4.txt5
-rw-r--r--Documentation/RelNotes/2.15.2.txt3
-rw-r--r--Documentation/RelNotes/2.16.4.txt5
-rw-r--r--Documentation/RelNotes/2.17.1.txt16
-rw-r--r--Documentation/RelNotes/2.18.0.txt371
-rw-r--r--Documentation/SubmittingPatches4
-rw-r--r--Documentation/config.txt101
-rw-r--r--Documentation/diff-options.txt4
-rw-r--r--Documentation/fetch-options.txt8
-rw-r--r--Documentation/git-add.txt4
-rw-r--r--Documentation/git-apply.txt10
-rw-r--r--Documentation/git-bisect.txt4
-rw-r--r--Documentation/git-branch.txt4
-rw-r--r--Documentation/git-bundle.txt4
-rw-r--r--Documentation/git-clone.txt4
-rw-r--r--Documentation/git-commit-graph.txt94
-rw-r--r--Documentation/git-config.txt81
-rw-r--r--Documentation/git-cvsserver.txt10
-rw-r--r--Documentation/git-diff-index.txt6
-rw-r--r--Documentation/git-diff-tree.txt2
-rw-r--r--Documentation/git-diff.txt16
-rw-r--r--Documentation/git-fast-export.txt2
-rw-r--r--Documentation/git-fast-import.txt22
-rw-r--r--Documentation/git-fetch-pack.txt2
-rw-r--r--Documentation/git-filter-branch.txt8
-rw-r--r--Documentation/git-fmt-merge-msg.txt4
-rw-r--r--Documentation/git-for-each-ref.txt2
-rw-r--r--Documentation/git-format-patch.txt2
-rw-r--r--Documentation/git-gc.txt25
-rw-r--r--Documentation/git-grep.txt2
-rw-r--r--Documentation/git-http-fetch.txt13
-rw-r--r--Documentation/git-http-push.txt2
-rw-r--r--Documentation/git-imap-send.txt4
-rw-r--r--Documentation/git-index-pack.txt4
-rw-r--r--Documentation/git-log.txt8
-rw-r--r--Documentation/git-ls-files.txt7
-rw-r--r--Documentation/git-ls-remote.txt24
-rw-r--r--Documentation/git-mktree.txt2
-rw-r--r--Documentation/git-name-rev.txt4
-rw-r--r--Documentation/git-p4.txt4
-rw-r--r--Documentation/git-pack-objects.txt26
-rw-r--r--Documentation/git-prune.txt6
-rw-r--r--Documentation/git-pull.txt6
-rw-r--r--Documentation/git-push.txt9
-rw-r--r--Documentation/git-read-tree.txt4
-rw-r--r--Documentation/git-rebase.txt170
-rw-r--r--Documentation/git-receive-pack.txt10
-rw-r--r--Documentation/git-remote-ext.txt12
-rw-r--r--Documentation/git-remote.txt2
-rw-r--r--Documentation/git-repack.txt13
-rw-r--r--Documentation/git-replace.txt11
-rw-r--r--Documentation/git-request-pull.txt4
-rw-r--r--Documentation/git-send-email.txt22
-rw-r--r--Documentation/git-send-pack.txt2
-rw-r--r--Documentation/git-shell.txt4
-rw-r--r--Documentation/git-shortlog.txt6
-rw-r--r--Documentation/git-show-branch.txt4
-rw-r--r--Documentation/git-show-ref.txt4
-rw-r--r--Documentation/git-show.txt2
-rw-r--r--Documentation/git-status.txt12
-rw-r--r--Documentation/git-submodule.txt21
-rw-r--r--Documentation/git-svn.txt2
-rw-r--r--Documentation/git-update-index.txt20
-rw-r--r--Documentation/git-update-ref.txt2
-rw-r--r--Documentation/git-var.txt4
-rw-r--r--Documentation/git-web--browse.txt2
-rw-r--r--Documentation/git-worktree.txt29
-rw-r--r--Documentation/git.txt3
-rw-r--r--Documentation/gitattributes.txt92
-rw-r--r--Documentation/githooks.txt115
-rw-r--r--Documentation/gitk.txt2
-rw-r--r--Documentation/gitremote-helpers.txt32
-rw-r--r--Documentation/glossary-content.txt2
-rw-r--r--Documentation/revisions.txt8
-rw-r--r--Documentation/technical/api-config.txt18
-rw-r--r--Documentation/technical/api-directory-listing.txt2
-rw-r--r--Documentation/technical/api-object-access.txt2
-rw-r--r--Documentation/technical/api-oid-array.txt17
-rw-r--r--Documentation/technical/api-submodule-config.txt2
-rw-r--r--Documentation/technical/commit-graph-format.txt97
-rw-r--r--Documentation/technical/commit-graph.txt163
-rw-r--r--Documentation/technical/pack-format.txt92
-rw-r--r--Documentation/technical/protocol-v2.txt414
-rw-r--r--Documentation/technical/shallow.txt20
-rw-r--r--Makefile190
-rw-r--r--advice.c51
-rw-r--r--advice.h1
-rw-r--r--alloc.c1
-rw-r--r--apply.c10
-rw-r--r--archive-tar.c4
-rw-r--r--archive-zip.c3
-rw-r--r--argv-array.c20
-rw-r--r--argv-array.h2
-rw-r--r--attr.c12
-rw-r--r--blame.c24
-rw-r--r--branch.c7
-rw-r--r--builtin.h3
-rw-r--r--builtin/add.c5
-rw-r--r--builtin/am.c30
-rw-r--r--builtin/blame.c131
-rw-r--r--builtin/branch.c9
-rw-r--r--builtin/cat-file.c16
-rw-r--r--builtin/checkout.c18
-rw-r--r--builtin/clone.c17
-rw-r--r--builtin/column.c1
-rw-r--r--builtin/commit-graph.c171
-rw-r--r--builtin/commit.c49
-rw-r--r--builtin/config.c147
-rw-r--r--builtin/count-objects.c2
-rw-r--r--builtin/describe.c6
-rw-r--r--builtin/diff.c2
-rw-r--r--builtin/difftool.c4
-rw-r--r--builtin/fast-export.c44
-rw-r--r--builtin/fetch-pack.c20
-rw-r--r--builtin/fetch.c145
-rw-r--r--builtin/fsck.c50
-rw-r--r--builtin/gc.c173
-rw-r--r--builtin/grep.c17
-rw-r--r--builtin/hash-object.c2
-rw-r--r--builtin/help.c2
-rw-r--r--builtin/index-pack.c29
-rw-r--r--builtin/init-db.c4
-rw-r--r--builtin/log.c6
-rw-r--r--builtin/ls-files.c2
-rw-r--r--builtin/ls-remote.c49
-rw-r--r--builtin/ls-tree.c2
-rw-r--r--builtin/merge-tree.c2
-rw-r--r--builtin/merge.c19
-rw-r--r--builtin/mktag.c3
-rw-r--r--builtin/mktree.c2
-rw-r--r--builtin/mv.c8
-rw-r--r--builtin/notes.c10
-rw-r--r--builtin/pack-objects.c491
-rw-r--r--builtin/pack-redundant.c62
-rw-r--r--builtin/pack-refs.c3
-rw-r--r--builtin/prune-packed.c2
-rw-r--r--builtin/prune.c3
-rw-r--r--builtin/pull.c27
-rw-r--r--builtin/push.c124
-rw-r--r--builtin/read-tree.c3
-rw-r--r--builtin/rebase--helper.c13
-rw-r--r--builtin/receive-pack.c20
-rw-r--r--builtin/reflog.c2
-rw-r--r--builtin/remote.c57
-rw-r--r--builtin/repack.c21
-rw-r--r--builtin/replace.c249
-rw-r--r--builtin/reset.c2
-rw-r--r--builtin/rev-parse.c4
-rw-r--r--builtin/rm.c3
-rw-r--r--builtin/send-pack.c44
-rw-r--r--builtin/serve.c30
-rw-r--r--builtin/submodule--helper.c79
-rw-r--r--builtin/tag.c6
-rw-r--r--builtin/unpack-objects.c9
-rw-r--r--builtin/update-index.c34
-rw-r--r--builtin/upload-pack.c74
-rw-r--r--builtin/verify-tag.c2
-rw-r--r--builtin/worktree.c106
-rw-r--r--bulk-checkin.c6
-rw-r--r--bundle.c2
-rw-r--r--cache-tree.c4
-rw-r--r--cache.h77
-rw-r--r--chdir-notify.c93
-rw-r--r--chdir-notify.h73
-rw-r--r--checkout.c5
-rwxr-xr-xci/lib-travisci.sh3
-rwxr-xr-xci/run-build-and-tests.sh5
-rw-r--r--color.c24
-rw-r--r--color.h4
-rw-r--r--column.c2
-rw-r--r--command-list.txt1
-rw-r--r--commit-graph.c761
-rw-r--r--commit-graph.h48
-rw-r--r--commit.c43
-rw-r--r--commit.h20
-rw-r--r--common-main.c6
-rw-r--r--compat/mingw.c5
-rw-r--r--config.c526
-rw-r--r--config.h26
-rw-r--r--config.mak.dev42
-rw-r--r--config.mak.uname10
-rw-r--r--configure.ac2
-rw-r--r--connect.c373
-rw-r--r--connect.h7
-rw-r--r--contrib/coccinelle/commit.cocci28
-rw-r--r--contrib/completion/git-completion.bash259
-rw-r--r--contrib/completion/git-completion.zsh9
-rwxr-xr-xcontrib/convert-grafts-to-replace-refs.sh28
-rw-r--r--contrib/credential/netrc/Makefile4
-rwxr-xr-xcontrib/credential/netrc/git-credential-netrc58
-rwxr-xr-xcontrib/credential/netrc/t-git-credential-netrc.sh31
-rwxr-xr-xcontrib/credential/netrc/test.command-option-gpg2
-rwxr-xr-xcontrib/credential/netrc/test.git-config-gpg2
-rw-r--r--contrib/credential/netrc/test.netrc.gpg0
-rwxr-xr-xcontrib/credential/netrc/test.pl88
-rw-r--r--contrib/emacs/.gitignore1
-rw-r--r--contrib/emacs/Makefile21
-rw-r--r--contrib/emacs/README32
-rw-r--r--contrib/emacs/git-blame.el489
-rw-r--r--contrib/emacs/git.el1710
-rw-r--r--contrib/mw-to-git/Makefile5
-rw-r--r--contrib/update-unicode/README6
-rwxr-xr-xcontrib/update-unicode/update_unicode.sh2
-rw-r--r--convert.c276
-rw-r--r--convert.h2
-rw-r--r--csum-file.c10
-rw-r--r--csum-file.h9
-rw-r--r--daemon.c2
-rw-r--r--date.c2
-rwxr-xr-xdetect-compiler53
-rw-r--r--diff.c35
-rw-r--r--diffcore-pickaxe.c1
-rw-r--r--dir-iterator.c2
-rw-r--r--dir.c87
-rw-r--r--dir.h17
-rw-r--r--environment.c30
-rw-r--r--exec-cmd.c365
-rw-r--r--exec-cmd.h (renamed from exec_cmd.h)4
-rw-r--r--exec_cmd.c165
-rw-r--r--fast-import.c97
-rw-r--r--fetch-pack.c363
-rw-r--r--fetch-pack.h5
-rw-r--r--fsck.c166
-rw-r--r--fsck.h7
-rw-r--r--fsmonitor.c17
-rw-r--r--gettext.c16
-rwxr-xr-xgit-add--interactive.perl11
-rw-r--r--git-compat-util.h27
-rwxr-xr-xgit-filter-branch.sh4
-rwxr-xr-xgit-gui/git-gui.sh1
-rw-r--r--git-gui/lib/sshkey.tcl5
-rw-r--r--git-gui/lib/themed.tcl15
-rwxr-xr-xgit-merge-one-file.sh2
-rwxr-xr-xgit-p4.py6
-rw-r--r--git-rebase--am.sh79
-rw-r--r--git-rebase--interactive.sh36
-rw-r--r--git-rebase--merge.sh2
-rwxr-xr-xgit-rebase.sh47
-rwxr-xr-xgit-send-email.perl45
-rwxr-xr-xgit-submodule.sh28
-rw-r--r--git.c11
-rw-r--r--gpg-interface.c43
-rw-r--r--gpg-interface.h49
-rw-r--r--grep.c18
-rw-r--r--help.c2
-rw-r--r--http-backend.c10
-rw-r--r--http-fetch.c17
-rw-r--r--http-push.c22
-rw-r--r--http.c112
-rw-r--r--http.h11
-rw-r--r--imap-send.c4
-rw-r--r--line-log.c4
-rw-r--r--list-objects-filter.c4
-rw-r--r--list-objects.c10
-rw-r--r--lockfile.c2
-rw-r--r--log-tree.c42
-rw-r--r--log-tree.h3
-rw-r--r--ls-refs.c96
-rw-r--r--ls-refs.h10
-rw-r--r--mailinfo.c2
-rw-r--r--mem-pool.c55
-rw-r--r--mem-pool.h34
-rw-r--r--merge-recursive.c202
-rw-r--r--merge.c5
-rw-r--r--mergetools/guiffy18
-rw-r--r--notes-merge.c13
-rw-r--r--object-store.h10
-rw-r--r--object.c8
-rw-r--r--object.h3
-rw-r--r--pack-bitmap-write.c21
-rw-r--r--pack-bitmap.c8
-rw-r--r--pack-bitmap.h4
-rw-r--r--pack-check.c3
-rw-r--r--pack-objects.c70
-rw-r--r--pack-objects.h316
-rw-r--r--pack-write.c5
-rw-r--r--packfile.c131
-rw-r--r--packfile.h12
-rw-r--r--pager.c11
-rw-r--r--parse-options-cb.c6
-rw-r--r--path.c86
-rw-r--r--pathspec.c12
-rw-r--r--perl/Git.pm2
-rw-r--r--perl/Git/I18N.pm2
-rw-r--r--perl/header_templates/fixed_prefix.template.pl1
-rw-r--r--perl/header_templates/runtime_prefix.template.pl42
-rw-r--r--pkt-line.c135
-rw-r--r--pkt-line.h78
-rw-r--r--pretty.c5
-rw-r--r--prio-queue.c2
-rw-r--r--protocol.c2
-rw-r--r--protocol.h1
-rw-r--r--reachable.c2
-rw-r--r--read-cache.c89
-rw-r--r--ref-filter.c347
-rw-r--r--ref-filter.h17
-rw-r--r--refs.c178
-rw-r--r--refs.h11
-rw-r--r--refs/files-backend.c32
-rw-r--r--refs/iterator.c6
-rw-r--r--refs/packed-backend.c19
-rw-r--r--refs/ref-cache.c2
-rw-r--r--refspec.c223
-rw-r--r--refspec.h48
-rw-r--r--remote-curl.c285
-rw-r--r--remote-testsvn.c2
-rw-r--r--remote.c357
-rw-r--r--remote.h63
-rw-r--r--replace-object.c73
-rw-r--r--replace-object.h36
-rw-r--r--replace_object.c120
-rw-r--r--repository.c11
-rw-r--r--repository.h6
-rw-r--r--rerere.c3
-rw-r--r--resolve-undo.c2
-rw-r--r--revision.c114
-rw-r--r--run-command.c35
-rw-r--r--sequencer.c1302
-rw-r--r--sequencer.h17
-rw-r--r--serve.c258
-rw-r--r--serve.h15
-rw-r--r--server-info.c9
-rw-r--r--setup.c13
-rw-r--r--sha1-array.c21
-rw-r--r--sha1-array.h7
-rw-r--r--sha1-file.c (renamed from sha1_file.c)123
-rw-r--r--sha1-lookup.c2
-rw-r--r--sha1-name.c (renamed from sha1_name.c)73
-rw-r--r--shallow.c8
-rw-r--r--shell.c2
-rw-r--r--sideband.c10
-rw-r--r--sigchain.c2
-rw-r--r--split-index.c10
-rw-r--r--split-index.h4
-rw-r--r--strbuf.c26
-rw-r--r--strbuf.h1
-rw-r--r--streaming.c5
-rw-r--r--submodule-config.c126
-rw-r--r--submodule-config.h29
-rw-r--r--submodule.c243
-rw-r--r--submodule.h10
-rw-r--r--t/README22
-rw-r--r--t/diff-lib.sh4
-rw-r--r--t/helper/test-chmtime.c44
-rw-r--r--t/helper/test-drop-caches.c16
-rw-r--r--t/helper/test-dump-split-index.c4
-rw-r--r--t/helper/test-dump-untracked-cache.c2
-rw-r--r--t/helper/test-example-decorate.c16
-rw-r--r--t/helper/test-path-utils.c20
-rw-r--r--t/helper/test-pkt-line.c64
-rw-r--r--t/helper/test-ref-store.c3
-rw-r--r--t/helper/test-scrap-cache-tree.c4
-rw-r--r--t/helper/test-submodule-config.c8
-rw-r--r--t/helper/test-tool.c1
-rw-r--r--t/helper/test-write-cache.c14
-rw-r--r--t/lib-diff-alternative.sh12
-rw-r--r--t/lib-pack.sh12
-rwxr-xr-xt/perf/aggregate.perl62
-rwxr-xr-xt/perf/bisect_regression73
-rwxr-xr-xt/perf/bisect_run_script53
-rwxr-xr-xt/perf/run56
-rwxr-xr-xt/t0000-basic.sh24
-rwxr-xr-xt/t0028-working-tree-encoding.sh245
-rwxr-xr-xt/t0060-path-utils.sh86
-rwxr-xr-xt/t0061-run-command.sh2
-rwxr-xr-xt/t0090-cache-tree.sh2
-rwxr-xr-xt/t1000-read-tree-m-3way.sh2
-rwxr-xr-xt/t1001-read-tree-m-2way.sh2
-rwxr-xr-xt/t1002-read-tree-m-u-2way.sh2
-rwxr-xr-xt/t1006-cat-file.sh8
-rwxr-xr-xt/t1007-hash-object.sh16
-rwxr-xr-xt/t1012-read-tree-df.sh2
-rwxr-xr-xt/t1300-config.sh (renamed from t/t1300-repo-config.sh)197
-rwxr-xr-xt/t1307-config-blob.sh4
-rwxr-xr-xt/t1310-config-default.sh36
-rwxr-xr-xt/t1400-update-ref.sh62
-rwxr-xr-xt/t1407-worktree-ref-store.sh8
-rwxr-xr-xt/t1450-fsck.sh4
-rwxr-xr-xt/t1501-work-tree.sh18
-rwxr-xr-xt/t1510-repo-setup.sh1
-rwxr-xr-xt/t1512-rev-parse-disambiguation.sh27
-rwxr-xr-xt/t1601-index-bogus.sh2
-rwxr-xr-xt/t1700-split-index.sh2
-rwxr-xr-xt/t2011-checkout-invalid-head.sh2
-rwxr-xr-xt/t2022-checkout-paths.sh4
-rwxr-xr-xt/t2025-worktree-add.sh34
-rwxr-xr-xt/t2027-worktree-list.sh2
-rwxr-xr-xt/t2028-worktree-move.sh7
-rwxr-xr-xt/t2107-update-index-basic.sh4
-rwxr-xr-xt/t2201-add-update-typechange.sh16
-rwxr-xr-xt/t2203-add-intent.sh14
-rwxr-xr-xt/t3100-ls-tree-restrict.sh2
-rwxr-xr-xt/t3101-ls-tree-dirname.sh2
-rwxr-xr-xt/t3103-ls-tree-misc.sh3
-rwxr-xr-xt/t3200-branch.sh28
-rwxr-xr-xt/t3404-rebase-interactive.sh21
-rwxr-xr-xt/t3418-rebase-continue.sh49
-rwxr-xr-xt/t3421-rebase-topology-linear.sh13
-rwxr-xr-xt/t3428-rebase-signoff.sh38
-rwxr-xr-xt/t3430-rebase-merges.sh316
-rwxr-xr-xt/t3510-cherry-pick-sequence.sh12
-rwxr-xr-xt/t3702-add-edit.sh7
-rwxr-xr-xt/t3905-stash-include-untracked.sh11
-rwxr-xr-xt/t4001-diff-rename.sh12
-rwxr-xr-xt/t4002-diff-basic.sh2
-rwxr-xr-xt/t4006-diff-mode.sh2
-rwxr-xr-xt/t4007-rename-3.sh17
-rwxr-xr-xt/t4008-diff-break-rewrite.sh59
-rwxr-xr-xt/t4014-format-patch.sh22
-rwxr-xr-xt/t4020-diff-external.sh20
-rwxr-xr-xt/t4022-diff-rewrite.sh6
-rwxr-xr-xt/t4027-diff-submodule.sh6
-rwxr-xr-xt/t4029-diff-trailing-space.sh40
-rwxr-xr-xt/t4030-diff-textconv.sh5
-rwxr-xr-xt/t4042-diff-textconv-caching.sh16
-rwxr-xr-xt/t4044-diff-index-unique-abbrev.sh6
-rwxr-xr-xt/t4045-diff-relative.sh6
-rwxr-xr-xt/t4046-diff-unmerged.sh14
-rwxr-xr-xt/t4054-diff-bogus-tree.sh12
-rwxr-xr-xt/t4058-diff-duplicates.sh12
-rwxr-xr-xt/t4150-am.sh4
-rwxr-xr-xt/t4200-rerere.sh10
-rwxr-xr-xt/t4201-shortlog.sh2
-rwxr-xr-xt/t4205-log-pretty-formats.sh8
-rwxr-xr-xt/t4208-log-magic-pathspec.sh3
-rwxr-xr-xt/t5000-tar-tree.sh2
-rwxr-xr-xt/t5150-request-pull.sh2
-rwxr-xr-xt/t5300-pack-object.sh13
-rwxr-xr-xt/t5304-prune.sh10
-rwxr-xr-xt/t5308-pack-detect-duplicates.sh6
-rwxr-xr-xt/t5309-pack-delta-cycles.sh6
-rwxr-xr-xt/t5310-pack-bitmaps.sh8
-rwxr-xr-xt/t5318-commit-graph.sh224
-rwxr-xr-xt/t5404-tracking-branches.sh2
-rwxr-xr-xt/t5512-ls-remote.sh54
-rwxr-xr-xt/t5516-fetch-push.sh32
-rwxr-xr-xt/t5527-fetch-odd-refs.sh2
-rwxr-xr-xt/t5541-http-push-smart.sh12
-rwxr-xr-xt/t5550-http-fetch-dumb.sh11
-rwxr-xr-xt/t5561-http-backend.sh10
-rwxr-xr-xt/t5571-pre-push-hook.sh8
-rwxr-xr-xt/t5701-git-serve.sh211
-rwxr-xr-xt/t5702-protocol-v2.sh431
-rwxr-xr-xt/t6001-rev-list-graft.sh9
-rwxr-xr-xt/t6006-rev-list-format.sh4
-rwxr-xr-xt/t6012-rev-list-simplify.sh2
-rwxr-xr-xt/t6022-merge-rename.sh25
-rwxr-xr-xt/t6050-replace.sh30
-rwxr-xr-xt/t6111-rev-list-treesame.sh2
-rwxr-xr-xt/t6120-describe.sh2
-rwxr-xr-xt/t6300-for-each-ref.sh2
-rwxr-xr-xt/t6301-for-each-ref-errors.sh2
-rwxr-xr-xt/t6500-gc.sh32
-rwxr-xr-xt/t6501-freshen-objects.sh6
-rwxr-xr-xt/t7001-mv.sh2
-rwxr-xr-xt/t7004-tag.sh15
-rwxr-xr-xt/t7005-editor.sh12
-rwxr-xr-xt/t7009-filter-branch-null-sha1.sh2
-rwxr-xr-xt/t7011-skip-worktree-reading.sh2
-rwxr-xr-xt/t7064-wtstatus-pv2.sh58
-rwxr-xr-xt/t7400-submodule-basic.sh16
-rwxr-xr-xt/t7408-submodule-reference.sh17
-rwxr-xr-xt/t7415-submodule-names.sh154
-rwxr-xr-xt/t7501-commit.sh12
-rwxr-xr-xt/t7506-status-submodule.sh2
-rwxr-xr-xt/t7508-status.sh4
-rwxr-xr-xt/t7525-status-rename.sh113
-rwxr-xr-xt/t7700-repack.sh27
-rwxr-xr-xt/t7701-repack-unpack-unreachable.sh6
-rwxr-xr-xt/t8012-blame-colors.sh48
-rwxr-xr-xt/t9010-svn-fe.sh14
-rwxr-xr-xt/t9300-fast-import.sh6
-rwxr-xr-xt/t9350-fast-export.sh18
-rwxr-xr-xt/t9902-completion.sh164
-rw-r--r--t/test-lib-functions.sh38
-rw-r--r--t/test-lib.sh22
-rw-r--r--tag.c2
-rwxr-xr-xtemplates/hooks--pre-commit.sample2
-rw-r--r--tmp-objdir.c2
-rw-r--r--trace.c14
-rw-r--r--trace.h1
-rw-r--r--trailer.c6
-rw-r--r--transport-helper.c126
-rw-r--r--transport-internal.h11
-rw-r--r--transport.c218
-rw-r--r--transport.h28
-rw-r--r--tree-walk.c18
-rw-r--r--tree-walk.h2
-rw-r--r--tree.c4
-rw-r--r--unicode-width.h (renamed from unicode_width.h)0
-rw-r--r--unpack-trees.c25
-rw-r--r--upload-pack.c647
-rw-r--r--upload-pack.h23
-rw-r--r--usage.c6
-rw-r--r--utf8.c125
-rw-r--r--utf8.h33
-rw-r--r--vcs-svn/fast_export.c6
-rw-r--r--walker.c19
-rw-r--r--walker.h3
-rw-r--r--worktree.c2
-rw-r--r--wrap-for-bin.sh19
-rw-r--r--wrapper.c4
-rw-r--r--write-or-die.c (renamed from write_or_die.c)0
-rw-r--r--wt-status.c40
-rw-r--r--wt-status.h4
-rw-r--r--zlib.c4
512 files changed, 17350 insertions, 6642 deletions
diff --git a/.gitattributes b/.gitattributes
index 8ce9c6b..1bdc91e 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -1,8 +1,10 @@
* whitespace=!indent,trail,space
*.[ch] whitespace=indent,trail,space diff=cpp
*.sh whitespace=indent,trail,space eol=lf
-*.perl eol=lf
-*.pm eol=lf
+*.perl eol=lf diff=perl
+*.pl eof=lf diff=perl
+*.pm eol=lf diff=perl
+*.py eol=lf diff=python
/Documentation/git-*.txt eol=lf
/command-list.txt eol=lf
/GIT-VERSION-GEN eol=lf
diff --git a/.gitignore b/.gitignore
index 833ef3b..b2a1ae4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -3,6 +3,7 @@
/GIT-LDFLAGS
/GIT-PREFIX
/GIT-PERL-DEFINES
+/GIT-PERL-HEADER
/GIT-PYTHON-VARS
/GIT-SCRIPT-DEFINES
/GIT-USER-AGENT
@@ -34,6 +35,7 @@
/git-clone
/git-column
/git-commit
+/git-commit-graph
/git-commit-tree
/git-config
/git-count-objects
@@ -140,6 +142,7 @@
/git-rm
/git-send-email
/git-send-pack
+/git-serve
/git-sh-i18n
/git-sh-i18n--envsubst
/git-sh-setup
diff --git a/.mailmap b/.mailmap
index 7c71e88..df7cf63 100644
--- a/.mailmap
+++ b/.mailmap
@@ -25,8 +25,8 @@ Ben Walton <bdwalton@gmail.com> <bwalton@artsci.utoronto.ca>
Benoit Sigoure <tsunanet@gmail.com> <tsuna@lrde.epita.fr>
Bernt Hansen <bernt@norang.ca> <bernt@alumni.uwaterloo.ca>
Brandon Casey <drafnel@gmail.com> <casey@nrlssc.navy.mil>
-brian m. carlson <sandals@crustytoothpaste.ath.cx> Brian M. Carlson <sandals@crustytoothpaste.ath.cx>
-brian m. carlson <sandals@crustytoothpaste.ath.cx> <sandals@crustytoothpaste.net>
+brian m. carlson <sandals@crustytoothpaste.net> Brian M. Carlson <sandals@crustytoothpaste.ath.cx>
+brian m. carlson <sandals@crustytoothpaste.net> <sandals@crustytoothpaste.ath.cx>
Bryan Larsen <bryan@larsen.st> <bryan.larsen@gmail.com>
Bryan Larsen <bryan@larsen.st> <bryanlarsen@yahoo.com>
Cheng Renquan <crquan@gmail.com>
diff --git a/.travis.yml b/.travis.yml
index 5f5ee4f..4d4e26c 100644
--- a/.travis.yml
+++ b/.travis.yml
@@ -16,10 +16,13 @@ compiler:
addons:
apt:
+ sources:
+ - ubuntu-toolchain-r-test
packages:
- language-pack-is
- git-svn
- apache2
+ - gcc-8
matrix:
include:
diff --git a/Documentation/Makefile b/Documentation/Makefile
index 6232143..d079d7c 100644
--- a/Documentation/Makefile
+++ b/Documentation/Makefile
@@ -78,6 +78,7 @@ TECH_DOCS += technical/pack-heuristics
TECH_DOCS += technical/pack-protocol
TECH_DOCS += technical/protocol-capabilities
TECH_DOCS += technical/protocol-common
+TECH_DOCS += technical/protocol-v2
TECH_DOCS += technical/racy-git
TECH_DOCS += technical/send-pack-pipeline
TECH_DOCS += technical/shallow
@@ -184,7 +185,7 @@ ASCIIDOC = asciidoctor
ASCIIDOC_CONF =
ASCIIDOC_HTML = xhtml5
ASCIIDOC_DOCBOOK = docbook45
-ASCIIDOC_EXTRA += -acompat-mode
+ASCIIDOC_EXTRA += -acompat-mode -atabsize=8
ASCIIDOC_EXTRA += -I. -rasciidoctor-extensions
ASCIIDOC_EXTRA += -alitdd='&\#x2d;&\#x2d;'
DBLATEX_COMMON =
diff --git a/Documentation/RelNotes/2.13.7.txt b/Documentation/RelNotes/2.13.7.txt
new file mode 100644
index 0000000..09fc014
--- /dev/null
+++ b/Documentation/RelNotes/2.13.7.txt
@@ -0,0 +1,20 @@
+Git v2.13.7 Release Notes
+=========================
+
+Fixes since v2.13.6
+-------------------
+
+ * Submodule "names" come from the untrusted .gitmodules file, but we
+ blindly append them to $GIT_DIR/modules to create our on-disk repo
+ paths. This means you can do bad things by putting "../" into the
+ name. We now enforce some rules for submodule names which will cause
+ Git to ignore these malicious names (CVE-2018-11235).
+
+ Credit for finding this vulnerability and the proof of concept from
+ which the test script was adapted goes to Etienne Stalmans.
+
+ * It was possible to trick the code that sanity-checks paths on NTFS
+ into reading random piece of memory (CVE-2018-11233).
+
+Credit for fixing for these bugs goes to Jeff King, Johannes
+Schindelin and others.
diff --git a/Documentation/RelNotes/2.14.4.txt b/Documentation/RelNotes/2.14.4.txt
new file mode 100644
index 0000000..97755a8
--- /dev/null
+++ b/Documentation/RelNotes/2.14.4.txt
@@ -0,0 +1,5 @@
+Git v2.14.4 Release Notes
+=========================
+
+This release is to forward-port the fixes made in the v2.13.7 version
+of Git. See its release notes for details.
diff --git a/Documentation/RelNotes/2.15.2.txt b/Documentation/RelNotes/2.15.2.txt
index 9f7e28f..b480e56 100644
--- a/Documentation/RelNotes/2.15.2.txt
+++ b/Documentation/RelNotes/2.15.2.txt
@@ -43,5 +43,8 @@ Fixes since v2.15.1
* Clarify and enhance documentation for "merge-base --fork-point", as
it was clear what it computed but not why/what for.
+ * This release also contains the fixes made in the v2.13.7 version of
+ Git. See its release notes for details.
+
Also contains various documentation updates and code clean-ups.
diff --git a/Documentation/RelNotes/2.16.4.txt b/Documentation/RelNotes/2.16.4.txt
new file mode 100644
index 0000000..6be538b
--- /dev/null
+++ b/Documentation/RelNotes/2.16.4.txt
@@ -0,0 +1,5 @@
+Git v2.16.4 Release Notes
+=========================
+
+This release is to forward-port the fixes made in the v2.13.7 version
+of Git. See its release notes for details.
diff --git a/Documentation/RelNotes/2.17.1.txt b/Documentation/RelNotes/2.17.1.txt
new file mode 100644
index 0000000..e01384f
--- /dev/null
+++ b/Documentation/RelNotes/2.17.1.txt
@@ -0,0 +1,16 @@
+Git v2.17.1 Release Notes
+=========================
+
+Fixes since v2.17
+-----------------
+
+ * This release contains the same fixes made in the v2.13.7 version of
+ Git, covering CVE-2018-11233 and 11235, and forward-ported to
+ v2.14.4, v2.15.2 and v2.16.4 releases. See release notes to
+ v2.13.7 for details.
+
+ * In addition to the above fixes, this release has support on the
+ server side to reject pushes to repositories that attempt to create
+ such problematic .gitmodules file etc. as tracked contents, to help
+ hosting sites protect their customers by preventing malicious
+ contents from spreading.
diff --git a/Documentation/RelNotes/2.18.0.txt b/Documentation/RelNotes/2.18.0.txt
index 5f16516..d750d01 100644
--- a/Documentation/RelNotes/2.18.0.txt
+++ b/Documentation/RelNotes/2.18.0.txt
@@ -21,6 +21,118 @@ UI, Workflows & Features
* When built with more recent cURL, GIT_SSL_VERSION can now specify
"tlsv1.3" as its value.
+ * "git gui" learned that "~/.ssh/id_ecdsa.pub" and
+ "~/.ssh/id_ed25519.pub" are also possible SSH key files.
+ (merge 2e2f0288ef bb/git-gui-ssh-key-files later to maint).
+
+ * "git gui" performs commit upon CTRL/CMD+ENTER but the
+ CTRL/CMD+KP_ENTER (i.e. enter key on the numpad) did not have the
+ same key binding. It now does.
+ (merge 28a1d94a06 bp/git-gui-bind-kp-enter later to maint).
+
+ * "git gui" has been taught to work with old versions of tk (like
+ 8.5.7) that do not support "ttk::style theme use" as a way to query
+ the current theme.
+ (merge 4891961105 cb/git-gui-ttk-style later to maint).
+
+ * "git rebase" has learned to honor "--signoff" option when using
+ backends other than "am" (but not "--preserve-merges").
+
+ * "git branch --list" during an interrupted "rebase -i" now lets
+ users distinguish the case where a detached HEAD is being rebased
+ and a normal branch is being rebased.
+
+ * "git mergetools" learned talking to guiffy.
+
+ * The scripts in contrib/emacs/ have outlived their usefulness and
+ have been replaced with a stub that errors out and tells the user
+ there are replacements.
+
+ * The new "checkout-encoding" attribute can ask Git to convert the
+ contents to the specified encoding when checking out to the working
+ tree (and the other way around when checking in).
+
+ * The "git config" command uses separate options e.g. "--int",
+ "--bool", etc. to specify what type the caller wants the value to
+ be interpreted as. A new "--type=<typename>" option has been
+ introduced, which would make it cleaner to define new types.
+
+ * "git config --get" learned the "--default" option, to help the
+ calling script. Building on top of the above changes, the
+ "git config" learns "--type=color" type. Taken together, you can
+ do things like "git config --get foo.color --default blue" and get
+ the ANSI color sequence for the color given to foo.color variable,
+ or "blue" if the variable does not exist.
+
+ * "git ls-remote" learned an option to allow sorting its output based
+ on the refnames being shown.
+
+ * The command line completion (in contrib/) has been taught that "git
+ stash save" has been deprecated ("git stash push" is the preferred
+ spelling in the new world) and does not offer it as a possible
+ completion candidate when "git stash push" can be.
+
+ * "git gc --prune=nonsense" spent long time repacking and then
+ silently failed when underlying "git prune --expire=nonsense"
+ failed to parse its command line. This has been corrected.
+
+ * Error messages from "git push" can be painted for more visibility.
+
+ * "git http-fetch" (deprecated) had an optional and experimental
+ "feature" to fetch only commits and/or trees, which nobody used.
+ This has been removed.
+
+ * The functionality of "$GIT_DIR/info/grafts" has been superseded by
+ the "refs/replace/" mechanism for some time now, but the internal
+ code had support for it in many places, which has been cleaned up
+ in order to drop support of the "grafts" mechanism.
+
+ * "git worktree add" learned to check out an existing branch.
+
+ * "git --no-pager cmd" did not have short-and-sweet single letter
+ option. Now it does as "-P".
+ (merge 7213c28818 js/no-pager-shorthand later to maint).
+
+ * "git rebase" learned "--rebase-merges" to transplant the whole
+ topology of commit graph elsewhere.
+
+ * "git status" learned to pay attention to UI related diff
+ configuration variables such as diff.renames.
+
+ * The command line completion mechanism (in contrib/) learned to load
+ custom completion file for "git $command" where $command is a
+ custom "git-$command" that the end user has on the $PATH when using
+ newer version of bash.
+
+ * "git send-email" can sometimes offer confirmation dialog "Send this
+ email?" with choices 'Yes', 'No', 'Quit', and 'All'. A new action
+ 'Edit' has been added to this dialog's choice.
+
+ * With merge.renames configuration set to false, the recursive merge
+ strategy can be told not to spend cycles trying to find renamed
+ paths and merge them accordingly.
+
+ * "git status" learned to honor a new status.renames configuration to
+ skip rename detection, which could be useful for those who want to
+ do so without disabling the default rename detection done by the
+ "git diff" command.
+
+ * Command line completion (in contrib/) learned to complete pathnames
+ for various commands better.
+
+ * "git blame" learns to unhighlight uninteresting metadata from the
+ originating commit on lines that are the same as the previous one,
+ and also paint lines in different colors depending on the age of
+ the commit.
+
+ * Transfer protocol v2 learned to support the partial clone.
+
+ * When a short hexadecimal string is used to name an object but there
+ are multiple objects that share the string as the prefix of their
+ names, the code lists these ambiguous candidates in a help message.
+ These object names are now sorted according to their types for
+ easier eyeballing.
+
Performance, Internal Implementation, Development Support etc.
@@ -76,6 +188,91 @@ Performance, Internal Implementation, Development Support etc.
* Small test-helper programs have been consolidated into a single
binary.
+ * API clean-up around ref-filter code.
+
+ * Shell completion (in contrib) that gives list of paths have been
+ optimized somewhat.
+
+ * The index file is updated to record the fsmonitor section after a
+ full scan was made, to avoid wasting the effort that has already
+ spent.
+
+ * Performance measuring framework in t/perf learned to help bisecting
+ performance regressions.
+
+ * Some multi-word source filenames are being renamed to separate
+ words with dashes instead of underscores.
+
+ * An reusable "memory pool" implementation has been extracted from
+ fast-import.c, which in turn has become the first user of the
+ mem-pool API.
+
+ * A build-time option has been added to allow Git to be told to refer
+ to its associated files relative to the main binary, in the same
+ way that has been possible on Windows for quite some time, for
+ Linux, BSDs and Darwin.
+
+ * Precompute and store information necessary for ancestry traversal
+ in a separate file to optimize graph walking.
+
+ * The effort to pass the repository in-core structure throughout the
+ API continues. This round deals with the code that implements the
+ refs/replace/ mechanism.
+
+ * The build procedure "make DEVELOPER=YesPlease" learned to enable a
+ bit more warning options depending on the compiler used to help
+ developers more. There also is "make DEVOPTS=tokens" knob
+ available now, for those who want to help fixing warnings we
+ usually ignore, for example.
+
+ * A new version of the transport protocol is being worked on.
+
+ * The code to interface to GPG has been restructured somewhat to make
+ it cleaner to integrate with other types of signature systems later.
+
+ * The code has been taught to use the duplicated information stored
+ in the commit-graph file to learn the tree object name for a commit
+ to avoid opening and parsing the commit object when it makes sense
+ to do so.
+
+ * "git gc" in a large repository takes a lot of time as it considers
+ to repack all objects into one pack by default. The command has
+ been taught to pretend as if the largest existing packfile is
+ marked with ".keep" so that it is left untouched while objects in
+ other packs and loose ones are repacked.
+
+ * The transport protocol v2 is getting updated further.
+
+ * The codepath around object-info API has been taught to take the
+ repository object (which in turn tells the API which object store
+ the objects are to be located).
+
+ * Rename detection logic in "diff" family that is used in "merge" has
+ learned to guess when all of x/a, x/b and x/c have moved to z/a,
+ z/b and z/c, it is likely that x/d added in the meantime would also
+ want to move to z/d by taking the hint that the entire directory
+ 'x' moved to 'z'. A bug causing dirty files involved in a rename
+ to be overwritten during merge has also been fixed as part of this
+ work. Incidentally, this also avoids updating a file in the
+ working tree after a (non-trivial) merge whose result matches what
+ our side originally had.
+
+ * "git pack-objects" needs to allocate tons of "struct object_entry"
+ while doing its work, and shrinking its size helps the performance
+ quite a bit.
+
+ * The implementation of "git rebase -i --root" has been updated to use
+ the sequencer machinery more.
+
+ * Developer support update, by using BUG() macro instead of die() to
+ mark codepaths that should not happen more clearly.
+
+ * Developer support. Use newer GCC on one of the builds done at
+ TravisCI.org to get more warnings and errors diagnosed.
+
+ * Conversion from uchar[20] to struct object_id continues.
+
+
Also contains various documentation updates and code clean-ups.
@@ -115,8 +312,182 @@ Fixes since v2.17
fixed.
(merge a0d51e8d0e eb/cred-helper-ignore-sigpipe later to maint).
+ * "git rebase --keep-empty" still removed an empty commit if the
+ other side contained an empty commit (due to the "does an
+ equivalent patch exist already?" check), which has been corrected.
+ (merge 3d946165e1 pw/rebase-keep-empty-fixes later to maint).
+
+ * Some codepaths, including the refs API, get and keep relative
+ paths, that go out of sync when the process does chdir(2). The
+ chdir-notify API is introduced to let these codepaths adjust these
+ cached paths to the new current directory.
+ (merge fb9c2d2703 jk/relative-directory-fix later to maint).
+
+ * "cd sub/dir && git commit ../path" ought to record the changes to
+ the file "sub/path", but this regressed long time ago.
+ (merge 86238e07ef bw/commit-partial-from-subdirectory-fix later to maint).
+
+ * Recent introduction of "--log-destination" option to "git daemon"
+ did not work well when the daemon was run under "--inetd" mode.
+ (merge e67d906d73 lw/daemon-log-destination later to maint).
+
+ * Small fix to the autoconf build procedure.
+ (merge 249482daf0 es/fread-reads-dir-autoconf-fix later to maint).
+
+ * Fix an unexploitable (because the oversized contents are not under
+ attacker's control) buffer overflow.
+ (merge d8579accfa bp/fsmonitor-bufsize-fix later to maint).
+
+ * Recent simplification of build procedure forgot a bit of tweak to
+ the build procedure of contrib/mw-to-git/
+ (merge d8698987f3 ab/simplify-perl-makefile later to maint).
+
+ * Moving a submodule that itself has submodule in it with "git mv"
+ forgot to make necessary adjustment to the nested sub-submodules;
+ now the codepath learned to recurse into the submodules.
+
+ * "git config --unset a.b", when "a.b" is the last variable in an
+ otherwise empty section "a", left an empty section "a" behind, and
+ worse yet, a subsequent "git config a.c value" did not reuse that
+ empty shell and instead created a new one. These have been
+ (partially) corrected.
+ (merge c71d8bb38a js/empty-config-section-fix later to maint).
+
+ * "git worktree remove" learned that "-f" is a shorthand for
+ "--force" option, just like for "git worktree add".
+ (merge d228eea514 sb/worktree-remove-opt-force later to maint).
+
+ * The completion script (in contrib/) learned to clear cached list of
+ command line options upon dot-sourcing it again in a more efficient
+ way.
+ (merge 94408dc71c sg/completion-clear-cached later to maint).
+
+ * "git svn" had a minor thinko/typo which has been fixed.
+ (merge 51db271587 ab/git-svn-get-record-typofix later to maint).
+
+ * During a "rebase -i" session, the code could give older timestamp
+ to commits created by later "pick" than an earlier "reword", which
+ has been corrected.
+ (merge 12f7babd6b js/ident-date-fix later to maint).
+
+ * "git submodule status" did not check the symbolic revision name it
+ computed for the submodule HEAD is not the NULL, and threw it at
+ printf routines, which has been corrected.
+ (merge 0b5e2ea7cf nd/submodule-status-fix later to maint).
+
+ * When fed input that already has In-Reply-To: and/or References:
+ headers and told to add the same information, "git send-email"
+ added these headers separately, instead of appending to an existing
+ one, which is a violation of the RFC. This has been corrected.
+ (merge 256be1d3f0 sa/send-email-dedup-some-headers later to maint).
+
+ * "git fast-export" had a regression in v2.15.0 era where it skipped
+ some merge commits in certain cases, which has been corrected.
+ (merge be011bbe00 ma/fast-export-skip-merge-fix later to maint).
+
+ * The code did not propagate the terminal width to subprocesses via
+ COLUMNS environment variable, which it now does. This caused
+ trouble to "git column" helper subprocess when "git tag --column=row"
+ tried to list the existing tags on a display with non-default width.
+ (merge b5d5a567fb nd/term-columns later to maint).
+
+ * We learned that our source files with ".pl" and ".py" extensions
+ are Perl and Python files respectively and changes to them are
+ better viewed as such with appropriate diff drivers.
+ (merge 7818b619e2 ab/perl-python-attrs later to maint).
+
+ * "git rebase -i" sometimes left intermediate "# This is a
+ combination of N commits" message meant for the human consumption
+ inside an editor in the final result in certain corner cases, which
+ has been fixed.
+ (merge 15ef69314d js/rebase-i-clean-msg-after-fixup-continue later to maint).
+
+ * A test to see if the filesystem normalizes UTF-8 filename has been
+ updated to check what we need to know in a more direct way, i.e. a
+ path created in NFC form can be accessed with NFD form (or vice
+ versa) to cope with APFS as well as HFS.
+ (merge 742ae10e35 tb/test-apfs-utf8-normalization later to maint).
+
+ * "git format-patch --cover --attach" created a broken MIME multipart
+ message for the cover letter, which has been fixed by keeping the
+ cover letter as plain text file.
+ (merge 50cd54ef4e bc/format-patch-cover-no-attach later to maint).
+
+ * The split-index feature had a long-standing and dormant bug in
+ certain use of the in-core merge machinery, which has been fixed.
+ (merge 7db118303a en/unpack-trees-split-index-fix later to maint).
+
+ * Asciidoctor gives a reasonable imitation for AsciiDoc, but does not
+ render illustration in a literal block correctly when indented with
+ HT by default. The problem is fixed by forcing 8-space tabs.
+ (merge 379805051d bc/asciidoctor-tab-width later to maint).
+
+ * Code clean-up to adjust to a more recent lockfile API convention that
+ allows lockfile instances kept on the stack.
+ (merge 0fa5a2ed8d ma/lockfile-cleanup later to maint).
+
+ * the_repository->index is not a allocated piece of memory but
+ repo_clear() indiscriminately attempted to free(3) it, which has
+ been corrected.
+ (merge 74373b5f10 nd/repo-clear-keep-the-index later to maint).
+
+ * Code clean-up to avoid non-standard-conformant pointer arithmetic.
+ (merge c112084af9 rs/no-null-ptr-arith-in-fast-export later to maint).
+
+ * Code clean-up to turn history traversal more robust in a
+ semi-corrupt repository.
+ (merge 8702b30fd7 jk/unavailable-can-be-missing later to maint).
+
+ * "git update-ref A B" is supposed to ensure that ref A does not yet
+ exist when B is a NULL OID, but this check was not done correctly
+ for pseudo-refs outside refs/ hierarchy, e.g. MERGE_HEAD.
+
+ * "git submodule update" and "git submodule add" supported the
+ "--reference" option to borrow objects from a neighbouring local
+ repository like "git clone" does, but lacked the more recent
+ invention "--dissociate". Also "git submodule add" has been taught
+ to take the "--progress" option.
+ (merge a0ef29341a cf/submodule-progress-dissociate later to maint).
+
+ * Update credential-netrc helper (in contrib/) to allow customizing
+ the GPG used to decrypt the encrypted .netrc file.
+ (merge 786ef50a23 lm/credential-netrc later to maint).
+
+ * "git submodule update" attempts two different kinds of "git fetch"
+ against the upstream repository to grab a commit bound at the
+ submodule's path, but it incorrectly gave up if the first kind
+ (i.e. a normal fetch) failed, making the second "last resort" one
+ (i.e. fetching an exact commit object by object name) ineffective.
+ This has been corrected.
+ (merge e30d833671 sb/submodule-update-try-harder later to maint).
+
* Other minor doc, test and build updates and code cleanups.
(merge 248f66ed8e nd/trace-with-env later to maint).
(merge 14ced5562c ys/bisect-object-id-missing-conversion-fix later to maint).
(merge 5988eb631a ab/doc-hash-brokenness later to maint).
(merge a4d4e32a70 pk/test-avoid-pipe-hiding-exit-status later to maint).
+ (merge 05e293c1ac jk/flockfile-stdio later to maint).
+ (merge e9184b0789 jk/t5561-missing-curl later to maint).
+ (merge b1801b85a3 nd/worktree-move later to maint).
+ (merge bbd374dd20 ak/bisect-doc-typofix later to maint).
+ (merge 4855f06fb3 mn/send-email-credential-doc later to maint).
+ (merge 8523b1e355 en/doc-typoes later to maint).
+ (merge 43b44ccfe7 js/t5404-path-fix later to maint).
+ (merge decf711fc1 ps/test-chmtime-get later to maint).
+ (merge 22d11a6e8e es/worktree-docs later to maint).
+ (merge 92a5dbbc22 tg/use-git-contacts later to maint).
+ (merge adc887221f tq/t1510 later to maint).
+ (merge bed21a8ad6 sg/doc-gc-quote-mismatch-fix later to maint).
+ (merge 73364e4f10 tz/doc-git-urls-reference later to maint).
+ (merge cd1e606bad bc/mailmap-self later to maint).
+ (merge f7997e3682 ao/config-api-doc later to maint).
+ (merge ee930754d8 jk/apply-p-doc later to maint).
+ (merge 011b648646 nd/pack-format-doc later to maint).
+ (merge 87a6bb701a sg/t5310-jgit-bitmap-test later to maint).
+ (merge f6b82970aa sg/t5516-fixes later to maint).
+ (merge 4362da078e sg/t7005-spaces-in-filenames-cleanup later to maint).
+ (merge 7d0ee47c11 js/test-unset-prereq later to maint).
+ (merge 5356a3c354 ah/misc-doc-updates later to maint).
+ (merge 92c4a7a129 nd/completion-aliasfiletype-typofix later to maint).
+ (merge 58bd77b66a nd/pack-unreachable-objects-doc later to maint).
+ (merge 4ed79d5203 sg/t6500-no-redirect-of-stdin later to maint).
diff --git a/Documentation/SubmittingPatches b/Documentation/SubmittingPatches
index a1d0fec..945f8ed 100644
--- a/Documentation/SubmittingPatches
+++ b/Documentation/SubmittingPatches
@@ -260,8 +260,8 @@ that starts with `-----BEGIN PGP SIGNED MESSAGE-----`. That is
not a text/plain, it's something else.
Send your patch with "To:" set to the mailing list, with "cc:" listing
-people who are involved in the area you are touching (the output from
-`git blame $path` and `git shortlog --no-merges $path` would help to
+people who are involved in the area you are touching (the `git
+contacts` command in `contrib/contacts/` can help to
identify them), to solicit comments and reviews.
:1: footnote:[The current maintainer: gitster@pobox.com]
diff --git a/Documentation/config.txt b/Documentation/config.txt
index 2659153..7d83834 100644
--- a/Documentation/config.txt
+++ b/Documentation/config.txt
@@ -530,6 +530,12 @@ core.autocrlf::
This variable can be set to 'input',
in which case no output conversion is performed.
+core.checkRoundtripEncoding::
+ A comma and/or whitespace separated list of encodings that Git
+ performs UTF-8 round trip checks on if they are used in an
+ `working-tree-encoding` attribute (see linkgit:gitattributes[5]).
+ The default value is `SHIFT-JIS`.
+
core.symlinks::
If false, symbolic links are checked out as small plain files that
contain the link text. linkgit:git-update-index[1] and
@@ -898,6 +904,10 @@ core.notesRef::
This setting defaults to "refs/notes/commits", and it can be overridden by
the `GIT_NOTES_REF` environment variable. See linkgit:git-notes[1].
+core.commitGraph::
+ Enable git commit graph feature. Allows reading from the
+ commit-graph file.
+
core.sparseCheckout::
Enable "sparse checkout" feature. See section "Sparse checkout" in
linkgit:git-read-tree[1] for more information.
@@ -1058,6 +1068,10 @@ branch.<name>.rebase::
"git pull" is run. See "pull.rebase" for doing this in a non
branch-specific manner.
+
+When `merges`, pass the `--rebase-merges` option to 'git rebase'
+so that the local merge commits are included in the rebase (see
+linkgit:git-rebase[1] for details).
++
When preserve, also pass `--preserve-merges` along to 'git rebase'
so that locally committed merge commits will not be flattened
by running 'git pull'.
@@ -1088,6 +1102,16 @@ clean.requireForce::
A boolean to make git-clean do nothing unless given -f,
-i or -n. Defaults to true.
+color.advice::
+ A boolean to enable/disable color in hints (e.g. when a push
+ failed, see `advice.*` for a list). May be set to `always`,
+ `false` (or `never`) or `auto` (or `true`), in which case colors
+ are used only when the error output goes to a terminal. If
+ unset, then the value of `color.ui` is used (`auto` by default).
+
+color.advice.hint::
+ Use customized color for hints.
+
color.branch::
A boolean to enable/disable color in the output of
linkgit:git-branch[1]. May be set to `always`,
@@ -1190,6 +1214,15 @@ color.pager::
A boolean to enable/disable colored output when the pager is in
use (default is true).
+color.push::
+ A boolean to enable/disable color in push errors. May be set to
+ `always`, `false` (or `never`) or `auto` (or `true`), in which
+ case colors are used only when the error output goes to a terminal.
+ If unset, then the value of `color.ui` is used (`auto` by default).
+
+color.push.error::
+ Use customized color for push errors.
+
color.showBranch::
A boolean to enable/disable color in the output of
linkgit:git-show-branch[1]. May be set to `always`,
@@ -1218,6 +1251,42 @@ color.status.<slot>::
status short-format), or
`unmerged` (files which have unmerged changes).
+color.blame.repeatedLines::
+ Use the customized color for the part of git-blame output that
+ is repeated meta information per line (such as commit id,
+ author name, date and timezone). Defaults to cyan.
+
+color.blame.highlightRecent::
+ This can be used to color the metadata of a blame line depending
+ on age of the line.
++
+This setting should be set to a comma-separated list of color and date settings,
+starting and ending with a color, the dates should be set from oldest to newest.
+The metadata will be colored given the colors if the the line was introduced
+before the given timestamp, overwriting older timestamped colors.
++
+Instead of an absolute timestamp relative timestamps work as well, e.g.
+2.weeks.ago is valid to address anything older than 2 weeks.
++
+It defaults to 'blue,12 month ago,white,1 month ago,red', which colors
+everything older than one year blue, recent changes between one month and
+one year old are kept white, and lines introduced within the last month are
+colored red.
+
+blame.coloring::
+ This determines the coloring scheme to be applied to blame
+ output. It can be 'repeatedLines', 'highlightRecent',
+ or 'none' which is the default.
+
+color.transport::
+ A boolean to enable/disable color when pushes are rejected. May be
+ set to `always`, `false` (or `never`) or `auto` (or `true`), in which
+ case colors are used only when the error output goes to a terminal.
+ If unset, then the value of `color.ui` is used (`auto` by default).
+
+color.transport.rejected::
+ Use customized color when a push was rejected.
+
color.ui::
This variable determines the default value for variables such
as `color.diff` and `color.grep` that control the use of color
@@ -1558,6 +1627,18 @@ gc.autoDetach::
Make `git gc --auto` return immediately and run in background
if the system supports it. Default is true.
+gc.bigPackThreshold::
+ If non-zero, all packs larger than this limit are kept when
+ `git gc` is run. This is very similar to `--keep-base-pack`
+ except that all packs that meet the threshold are kept, not
+ just the base pack. Defaults to zero. Common unit suffixes of
+ 'k', 'm', or 'g' are supported.
++
+Note that if the number of kept packs is more than gc.autoPackLimit,
+this configuration variable is ignored, all packs except the base pack
+will be repacked. After this the number of packs should go below
+gc.autoPackLimit and gc.bigPackThreshold should be respected again.
+
gc.logExpiry::
If the file gc.log exists, then `git gc --auto` won't run
unless that file is more than 'gc.logExpiry' old. Default is
@@ -2422,6 +2503,7 @@ pack.window::
pack.depth::
The maximum delta depth used by linkgit:git-pack-objects[1] when no
maximum depth is given on the command line. Defaults to 50.
+ Maximum value is 4095.
pack.windowMemory::
The maximum size of memory that is consumed by each thread
@@ -2458,7 +2540,8 @@ pack.deltaCacheLimit::
The maximum size of a delta, that is cached in
linkgit:git-pack-objects[1]. This cache is used to speed up the
writing object phase by not having to recompute the final delta
- result once the best match for all objects is found. Defaults to 1000.
+ result once the best match for all objects is found.
+ Defaults to 1000. Maximum value is 65535.
pack.threads::
Specifies the number of threads to spawn when searching for best
@@ -2617,6 +2700,10 @@ pull.rebase::
pull" is run. See "branch.<name>.rebase" for setting this on a
per-branch basis.
+
+When `merges`, pass the `--rebase-merges` option to 'git rebase'
+so that the local merge commits are included in the rebase (see
+linkgit:git-rebase[1] for details).
++
When preserve, also pass `--preserve-merges` along to 'git rebase'
so that locally committed merge commits will not be flattened
by running 'git pull'.
@@ -3119,6 +3206,18 @@ status.displayCommentPrefix::
behavior of linkgit:git-status[1] in Git 1.8.4 and previous.
Defaults to false.
+status.renameLimit::
+ The number of files to consider when performing rename detection
+ in linkgit:git-status[1] and linkgit:git-commit[1]. Defaults to
+ the value of diff.renameLimit.
+
+status.renames::
+ Whether and how Git detects renames in linkgit:git-status[1] and
+ linkgit:git-commit[1] . If set to "false", rename detection is
+ disabled. If set to "true", basic rename detection is enabled.
+ If set to "copies" or "copy", Git will detect copies, as well.
+ Defaults to the value of diff.renames.
+
status.showStash::
If set to true, linkgit:git-status[1] will display the number of
entries currently stashed away.
diff --git a/Documentation/diff-options.txt b/Documentation/diff-options.txt
index e3a44f0..f466600 100644
--- a/Documentation/diff-options.txt
+++ b/Documentation/diff-options.txt
@@ -568,7 +568,7 @@ the normal order.
--
+
Patterns have the same syntax and semantics as patterns used for
-fnmantch(3) without the FNM_PATHNAME flag, except a pathname also
+fnmatch(3) without the FNM_PATHNAME flag, except a pathname also
matches a pattern if removing any number of the final pathname
components matches the pattern. For example, the pattern "`foo*bar`"
matches "`fooasdfbar`" and "`foo/bar/baz/asdf`" but not "`foobarx`".
@@ -592,7 +592,7 @@ endif::git-format-patch[]
Treat all files as text.
--ignore-cr-at-eol::
- Ignore carrige-return at the end of line when doing a comparison.
+ Ignore carriage-return at the end of line when doing a comparison.
--ignore-space-at-eol::
Ignore changes in whitespace at EOL.
diff --git a/Documentation/fetch-options.txt b/Documentation/fetch-options.txt
index 8631e36..97d3217 100644
--- a/Documentation/fetch-options.txt
+++ b/Documentation/fetch-options.txt
@@ -188,6 +188,14 @@ endif::git-pull[]
is specified. This flag forces progress status even if the
standard error stream is not directed to a terminal.
+-o <option>::
+--server-option=<option>::
+ Transmit the given string to the server when communicating using
+ protocol version 2. The given string must not contain a NUL or LF
+ character.
+ When multiple `--server-option=<option>` are given, they are all
+ sent to the other side in the order listed on the command line.
+
-4::
--ipv4::
Use IPv4 addresses only, ignoring IPv6 addresses.
diff --git a/Documentation/git-add.txt b/Documentation/git-add.txt
index d50fa33..45652fe 100644
--- a/Documentation/git-add.txt
+++ b/Documentation/git-add.txt
@@ -193,7 +193,7 @@ for "git add --no-all <pathspec>...", i.e. ignored removed files.
for command-line options).
-Configuration
+CONFIGURATION
-------------
The optional configuration variable `core.excludesFile` indicates a path to a
@@ -226,7 +226,7 @@ Because this example lets the shell expand the asterisk (i.e. you are
listing the files explicitly), it does not consider
`subdir/git-foo.sh`.
-Interactive mode
+INTERACTIVE MODE
----------------
When the command enters the interactive mode, it shows the
output of the 'status' subcommand, and then goes into its
diff --git a/Documentation/git-apply.txt b/Documentation/git-apply.txt
index 4ebc3d3..6722849 100644
--- a/Documentation/git-apply.txt
+++ b/Documentation/git-apply.txt
@@ -113,8 +113,10 @@ explained for the configuration variable `core.quotePath` (see
linkgit:git-config[1]).
-p<n>::
- Remove <n> leading slashes from traditional diff paths. The
- default is 1.
+ Remove <n> leading path components (separated by slashes) from
+ traditional diff paths. E.g., with `-p2`, a patch against
+ `a/dir/file` will be applied directly to `file`. The default is
+ 1.
-C<n>::
Ensure at least <n> lines of surrounding context match before
@@ -240,7 +242,7 @@ When `git apply` is used as a "better GNU patch", the user can pass
the `--unsafe-paths` option to override this safety check. This option
has no effect when `--index` or `--cached` is in use.
-Configuration
+CONFIGURATION
-------------
apply.ignoreWhitespace::
@@ -251,7 +253,7 @@ apply.whitespace::
When no `--whitespace` flag is given from the command
line, this configuration item is used as the default.
-Submodules
+SUBMODULES
----------
If the patch contains any changes to submodules then 'git apply'
treats these changes as follows.
diff --git a/Documentation/git-bisect.txt b/Documentation/git-bisect.txt
index 4a1417b..4b45d83 100644
--- a/Documentation/git-bisect.txt
+++ b/Documentation/git-bisect.txt
@@ -165,8 +165,8 @@ To get a reminder of the currently used terms, use
git bisect terms
------------------------------------------------
-You can get just the old (respectively new) term with `git bisect term
---term-old` or `git bisect term --term-good`.
+You can get just the old (respectively new) term with `git bisect terms
+--term-old` or `git bisect terms --term-good`.
If you would like to use your own terms instead of "bad"/"good" or
"new"/"old", you can choose any names you like (except existing bisect
diff --git a/Documentation/git-branch.txt b/Documentation/git-branch.txt
index b3084c9..02eccbb 100644
--- a/Documentation/git-branch.txt
+++ b/Documentation/git-branch.txt
@@ -287,7 +287,7 @@ CONFIGURATION
`--list` is used or implied. The default is to use a pager.
See linkgit:git-config[1].
-Examples
+EXAMPLES
--------
Start development from a known tag::
@@ -318,7 +318,7 @@ See linkgit:git-fetch[1].
is currently checked out) does not have all commits from the test branch.
-Notes
+NOTES
-----
If you are creating a branch that you want to checkout immediately, it is
diff --git a/Documentation/git-bundle.txt b/Documentation/git-bundle.txt
index 3a8120c..7d6c9dc 100644
--- a/Documentation/git-bundle.txt
+++ b/Documentation/git-bundle.txt
@@ -92,8 +92,8 @@ It is okay to err on the side of caution, causing the bundle file
to contain objects already in the destination, as these are ignored
when unpacking at the destination.
-EXAMPLE
--------
+EXAMPLES
+--------
Assume you want to transfer the history from a repository R1 on machine A
to another repository R2 on machine B.
diff --git a/Documentation/git-clone.txt b/Documentation/git-clone.txt
index 42ca7b5..a55536f 100644
--- a/Documentation/git-clone.txt
+++ b/Documentation/git-clone.txt
@@ -260,7 +260,7 @@ or `--mirror` is given)
<repository>::
The (possibly remote) repository to clone from. See the
- <<URLS,URLS>> section below for more information on specifying
+ <<URLS,GIT URLS>> section below for more information on specifying
repositories.
<directory>::
@@ -273,7 +273,7 @@ or `--mirror` is given)
:git-clone: 1
include::urls.txt[]
-Examples
+EXAMPLES
--------
* Clone from upstream:
diff --git a/Documentation/git-commit-graph.txt b/Documentation/git-commit-graph.txt
new file mode 100644
index 0000000..4c97b55
--- /dev/null
+++ b/Documentation/git-commit-graph.txt
@@ -0,0 +1,94 @@
+git-commit-graph(1)
+===================
+
+NAME
+----
+git-commit-graph - Write and verify Git commit graph files
+
+
+SYNOPSIS
+--------
+[verse]
+'git commit-graph read' [--object-dir <dir>]
+'git commit-graph write' <options> [--object-dir <dir>]
+
+
+DESCRIPTION
+-----------
+
+Manage the serialized commit graph file.
+
+
+OPTIONS
+-------
+--object-dir::
+ Use given directory for the location of packfiles and commit graph
+ file. This parameter exists to specify the location of an alternate
+ that only has the objects directory, not a full .git directory. The
+ commit graph file is expected to be at <dir>/info/commit-graph and
+ the packfiles are expected to be in <dir>/pack.
+
+
+COMMANDS
+--------
+'write'::
+
+Write a commit graph file based on the commits found in packfiles.
++
+With the `--stdin-packs` option, generate the new commit graph by
+walking objects only in the specified pack-indexes. (Cannot be combined
+with --stdin-commits.)
++
+With the `--stdin-commits` option, generate the new commit graph by
+walking commits starting at the commits specified in stdin as a list
+of OIDs in hex, one OID per line. (Cannot be combined with
+--stdin-packs.)
++
+With the `--append` option, include all commits that are present in the
+existing commit-graph file.
+
+'read'::
+
+Read a graph file given by the commit-graph file and output basic
+details about the graph file. Used for debugging purposes.
+
+
+EXAMPLES
+--------
+
+* Write a commit graph file for the packed commits in your local .git folder.
++
+------------------------------------------------
+$ git commit-graph write
+------------------------------------------------
+
+* Write a graph file, extending the current graph file using commits
+* in <pack-index>.
++
+------------------------------------------------
+$ echo <pack-index> | git commit-graph write --stdin-packs
+------------------------------------------------
+
+* Write a graph file containing all reachable commits.
++
+------------------------------------------------
+$ git show-ref -s | git commit-graph write --stdin-commits
+------------------------------------------------
+
+* Write a graph file containing all commits in the current
+* commit-graph file along with those reachable from HEAD.
++
+------------------------------------------------
+$ git rev-parse HEAD | git commit-graph write --stdin-commits --append
+------------------------------------------------
+
+* Read basic information from the commit-graph file.
++
+------------------------------------------------
+$ git commit-graph read
+------------------------------------------------
+
+
+GIT
+---
+Part of the linkgit:git[1] suite
diff --git a/Documentation/git-config.txt b/Documentation/git-config.txt
index e09ed5d..18ddc78 100644
--- a/Documentation/git-config.txt
+++ b/Documentation/git-config.txt
@@ -9,13 +9,13 @@ git-config - Get and set repository or global options
SYNOPSIS
--------
[verse]
-'git config' [<file-option>] [type] [--show-origin] [-z|--null] name [value [value_regex]]
-'git config' [<file-option>] [type] --add name value
-'git config' [<file-option>] [type] --replace-all name value [value_regex]
-'git config' [<file-option>] [type] [--show-origin] [-z|--null] --get name [value_regex]
-'git config' [<file-option>] [type] [--show-origin] [-z|--null] --get-all name [value_regex]
-'git config' [<file-option>] [type] [--show-origin] [-z|--null] [--name-only] --get-regexp name_regex [value_regex]
-'git config' [<file-option>] [type] [-z|--null] --get-urlmatch name URL
+'git config' [<file-option>] [--type=<type>] [--show-origin] [-z|--null] name [value [value_regex]]
+'git config' [<file-option>] [--type=<type>] --add name value
+'git config' [<file-option>] [--type=<type>] --replace-all name value [value_regex]
+'git config' [<file-option>] [--type=<type>] [--show-origin] [-z|--null] --get name [value_regex]
+'git config' [<file-option>] [--type=<type>] [--show-origin] [-z|--null] --get-all name [value_regex]
+'git config' [<file-option>] [--type=<type>] [--show-origin] [-z|--null] [--name-only] --get-regexp name_regex [value_regex]
+'git config' [<file-option>] [--type=<type>] [-z|--null] --get-urlmatch name URL
'git config' [<file-option>] --unset name [value_regex]
'git config' [<file-option>] --unset-all name [value_regex]
'git config' [<file-option>] --rename-section old_name new_name
@@ -38,12 +38,10 @@ existing values that match the regexp are updated or unset. If
you want to handle the lines that do *not* match the regex, just
prepend a single exclamation mark in front (see also <<EXAMPLES>>).
-The type specifier can be either `--int` or `--bool`, to make
-'git config' ensure that the variable(s) are of the given type and
-convert the value to the canonical form (simple decimal number for int,
-a "true" or "false" string for bool), or `--path`, which does some
-path expansion (see `--path` below). If no type specifier is passed, no
-checks or transformations are performed on the value.
+The `--type=<type>` option instructs 'git config' to ensure that incoming and
+outgoing values are canonicalize-able under the given <type>. If no
+`--type=<type>` is given, no canonicalization will be performed. Callers may
+unset an existing `--type` specifier with `--no-type`.
When reading, the values are read from the system, global and
repository local configuration files by default, and options
@@ -160,30 +158,43 @@ See also <<FILES>>.
--list::
List all variables set in config file, along with their values.
---bool::
- 'git config' will ensure that the output is "true" or "false"
+--type <type>::
+ 'git config' will ensure that any input or output is valid under the given
+ type constraint(s), and will canonicalize outgoing values in `<type>`'s
+ canonical form.
++
+Valid `<type>`'s include:
++
+- 'bool': canonicalize values as either "true" or "false".
+- 'int': canonicalize values as simple decimal numbers. An optional suffix of
+ 'k', 'm', or 'g' will cause the value to be multiplied by 1024, 1048576, or
+ 1073741824 upon input.
+- 'bool-or-int': canonicalize according to either 'bool' or 'int', as described
+ above.
+- 'path': canonicalize by adding a leading `~` to the value of `$HOME` and
+ `~user` to the home directory for the specified user. This specifier has no
+ effect when setting the value (but you can use `git config section.variable
+ ~/` from the command line to let your shell do the expansion.)
+- 'expiry-date': canonicalize by converting from a fixed or relative date-string
+ to a timestamp. This specifier has no effect when setting the value.
+- 'color': When getting a value, canonicalize by converting to an ANSI color
+ escape sequence. When setting a value, a sanity-check is performed to ensure
+ that the given value is canonicalize-able as an ANSI color, but it is written
+ as-is.
++
+--bool::
--int::
- 'git config' will ensure that the output is a simple
- decimal number. An optional value suffix of 'k', 'm', or 'g'
- in the config file will cause the value to be multiplied
- by 1024, 1048576, or 1073741824 prior to output.
-
--bool-or-int::
- 'git config' will ensure that the output matches the format of
- either --bool or --int, as described above.
-
--path::
- `git config` will expand a leading `~` to the value of
- `$HOME`, and `~user` to the home directory for the
- specified user. This option has no effect when setting the
- value (but you can use `git config section.variable ~/`
- from the command line to let your shell do the expansion).
-
--expiry-date::
- `git config` will ensure that the output is converted from
- a fixed or relative date-string to a timestamp. This option
- has no effect when setting the value.
+ Historical options for selecting a type specifier. Prefer instead `--type`,
+ (see: above).
+
+--no-type::
+ Un-sets the previously set type specifier (if one was previously set). This
+ option requests that 'git config' not canonicalize the retrieved variable.
+ `--no-type` has no effect without `--type=<type>` or `--<type>`.
-z::
--null::
@@ -221,6 +232,8 @@ See also <<FILES>>.
output it as the ANSI color escape sequence to the standard
output. The optional `default` parameter is used instead, if
there is no color configured for `name`.
++
+`--type=color [--default=<default>]` is preferred over `--get-color`.
-e::
--edit::
@@ -233,6 +246,10 @@ See also <<FILES>>.
using `--file`, `--global`, etc) and `on` when searching all
config files.
+--default <value>::
+ When using `--get`, and the requested variable is not found, behave as if
+ <value> were the value assigned to the that variable.
+
CONFIGURATION
-------------
`pager.config` is only respected when listing configuration, i.e., when
diff --git a/Documentation/git-cvsserver.txt b/Documentation/git-cvsserver.txt
index ba90066..37b96c5 100644
--- a/Documentation/git-cvsserver.txt
+++ b/Documentation/git-cvsserver.txt
@@ -207,7 +207,7 @@ allowing access over SSH.
------
[[dbbackend]]
-Database Backend
+DATABASE BACKEND
----------------
'git-cvsserver' uses one database per Git head (i.e. CVS module) to
@@ -321,7 +321,7 @@ git-cvsserver, as described above.
When these environment variables are set, the corresponding
command-line arguments may not be used.
-Eclipse CVS Client Notes
+ECLIPSE CVS CLIENT NOTES
------------------------
To get a checkout with the Eclipse CVS client:
@@ -346,7 +346,7 @@ offer. In that case CVS_SERVER is ignored, and you will have to replace
the cvs utility on the server with 'git-cvsserver' or manipulate your `.bashrc`
so that calling 'cvs' effectively calls 'git-cvsserver'.
-Clients known to work
+CLIENTS KNOWN TO WORK
---------------------
- CVS 1.12.9 on Debian
@@ -354,7 +354,7 @@ Clients known to work
- Eclipse 3.0, 3.1.2 on MacOSX (see Eclipse CVS Client Notes)
- TortoiseCVS
-Operations supported
+OPERATIONS SUPPORTED
--------------------
All the operations required for normal use are supported, including
@@ -424,7 +424,7 @@ For best consistency with 'cvs', it is probably best to override the
defaults by setting `gitcvs.usecrlfattr` to true,
and `gitcvs.allBinary` to "guess".
-Dependencies
+DEPENDENCIES
------------
'git-cvsserver' depends on DBD::SQLite.
diff --git a/Documentation/git-diff-index.txt b/Documentation/git-diff-index.txt
index b380677..f4bd815 100644
--- a/Documentation/git-diff-index.txt
+++ b/Documentation/git-diff-index.txt
@@ -37,14 +37,14 @@ include::diff-options.txt[]
include::diff-format.txt[]
-Operating Modes
+OPERATING MODES
---------------
You can choose whether you want to trust the index file entirely
(using the `--cached` flag) or ask the diff logic to show any files
that don't match the stat state as being "tentatively changed". Both
of these operations are very useful indeed.
-Cached Mode
+CACHED MODE
-----------
If `--cached` is specified, it allows you to ask:
@@ -77,7 +77,7 @@ So doing a `git diff-index --cached` is basically very useful when you are
asking yourself "what have I already marked for being committed, and
what's the difference to a previous tree".
-Non-cached Mode
+NON-CACHED MODE
---------------
The "non-cached" mode takes a different approach, and is potentially
the more useful of the two in that what it does can't be emulated with
diff --git a/Documentation/git-diff-tree.txt b/Documentation/git-diff-tree.txt
index 7870e17..2319b2b 100644
--- a/Documentation/git-diff-tree.txt
+++ b/Documentation/git-diff-tree.txt
@@ -116,7 +116,7 @@ include::pretty-options.txt[]
include::pretty-formats.txt[]
-Limiting Output
+LIMITING OUTPUT
---------------
If you're only interested in differences in a subset of files, for
example some architecture-specific files, you might do:
diff --git a/Documentation/git-diff.txt b/Documentation/git-diff.txt
index b0c1bb9..7c2c442 100644
--- a/Documentation/git-diff.txt
+++ b/Documentation/git-diff.txt
@@ -13,7 +13,7 @@ SYNOPSIS
'git diff' [options] --cached [<commit>] [--] [<path>...]
'git diff' [options] <commit> <commit> [--] [<path>...]
'git diff' [options] <blob> <blob>
-'git diff' [options] [--no-index] [--] <path> <path>
+'git diff' [options] --no-index [--] <path> <path>
DESCRIPTION
-----------
@@ -21,7 +21,7 @@ Show changes between the working tree and the index or a tree, changes
between the index and a tree, changes between two trees, changes between
two blob objects, or changes between two files on disk.
-'git diff' [--options] [--] [<path>...]::
+'git diff' [options] [--] [<path>...]::
This form is to view the changes you made relative to
the index (staging area for the next commit). In other
@@ -29,7 +29,7 @@ two blob objects, or changes between two files on disk.
further add to the index but you still haven't. You can
stage these changes by using linkgit:git-add[1].
-'git diff' --no-index [--options] [--] [<path>...]::
+'git diff' [options] --no-index [--] <path> <path>::
This form is to compare the given two paths on the
filesystem. You can omit the `--no-index` option when
@@ -38,7 +38,7 @@ two blob objects, or changes between two files on disk.
or when running the command outside a working tree
controlled by Git.
-'git diff' [--options] --cached [<commit>] [--] [<path>...]::
+'git diff' [options] --cached [<commit>] [--] [<path>...]::
This form is to view the changes you staged for the next
commit relative to the named <commit>. Typically you
@@ -48,7 +48,7 @@ two blob objects, or changes between two files on disk.
<commit> is not given, it shows all staged changes.
--staged is a synonym of --cached.
-'git diff' [--options] <commit> [--] [<path>...]::
+'git diff' [options] <commit> [--] [<path>...]::
This form is to view the changes you have in your
working tree relative to the named <commit>. You can
@@ -56,18 +56,18 @@ two blob objects, or changes between two files on disk.
branch name to compare with the tip of a different
branch.
-'git diff' [--options] <commit> <commit> [--] [<path>...]::
+'git diff' [options] <commit> <commit> [--] [<path>...]::
This is to view the changes between two arbitrary
<commit>.
-'git diff' [--options] <commit>..<commit> [--] [<path>...]::
+'git diff' [options] <commit>..<commit> [--] [<path>...]::
This is synonymous to the previous form. If <commit> on
one side is omitted, it will have the same effect as
using HEAD instead.
-'git diff' [--options] <commit>\...<commit> [--] [<path>...]::
+'git diff' [options] <commit>\...<commit> [--] [<path>...]::
This form is to view the changes on the branch containing
and up to the second <commit>, starting at a common ancestor
diff --git a/Documentation/git-fast-export.txt b/Documentation/git-fast-export.txt
index ed57c68..4409859 100644
--- a/Documentation/git-fast-export.txt
+++ b/Documentation/git-fast-export.txt
@@ -202,7 +202,7 @@ smaller output, and it is usually easy to quickly confirm that there is
no private data in the stream.
-Limitations
+LIMITATIONS
-----------
Since 'git fast-import' cannot tag trees, you will not be
diff --git a/Documentation/git-fast-import.txt b/Documentation/git-fast-import.txt
index 3d3d219..cdf696f 100644
--- a/Documentation/git-fast-import.txt
+++ b/Documentation/git-fast-import.txt
@@ -139,7 +139,7 @@ Performance and Compression Tuning
fastimport.unpackLimit::
See linkgit:git-config[1]
-Performance
+PERFORMANCE
-----------
The design of fast-import allows it to import large projects in a minimum
amount of memory usage and processing time. Assuming the frontend
@@ -155,7 +155,7 @@ faster if the source data is stored on a different drive than the
destination Git repository (due to less IO contention).
-Development Cost
+DEVELOPMENT COST
----------------
A typical frontend for fast-import tends to weigh in at approximately 200
lines of Perl/Python/Ruby code. Most developers have been able to
@@ -165,7 +165,7 @@ an ideal situation, given that most conversion tools are throw-away
(use once, and never look back).
-Parallel Operation
+PARALLEL OPERATION
------------------
Like 'git push' or 'git fetch', imports handled by fast-import are safe to
run alongside parallel `git repack -a -d` or `git gc` invocations,
@@ -186,7 +186,7 @@ this only be used on an otherwise quiet repository. Using --force
is not necessary for an initial import into an empty repository.
-Technical Discussion
+TECHNICAL DISCUSSION
--------------------
fast-import tracks a set of branches in memory. Any branch can be created
or modified at any point during the import process by sending a
@@ -204,7 +204,7 @@ directory also allows fast-import to run very quickly, as it does not
need to perform any costly file update operations when switching
between branches.
-Input Format
+INPUT FORMAT
------------
With the exception of raw file data (which Git does not interpret)
the fast-import input format is text (ASCII) based. This text based
@@ -1131,7 +1131,7 @@ If the `--done` command-line option or `feature done` command is
in use, the `done` command is mandatory and marks the end of the
stream.
-Responses To Commands
+RESPONSES TO COMMANDS
---------------------
New objects written by fast-import are not available immediately.
Most fast-import commands have no visible effect until the next
@@ -1160,7 +1160,7 @@ To avoid deadlock, such frontends must completely consume any
pending output from `progress`, `ls`, `get-mark`, and `cat-blob` before
performing writes to fast-import that might block.
-Crash Reports
+CRASH REPORTS
-------------
If fast-import is supplied invalid input it will terminate with a
non-zero exit status and create a crash report in the top level of
@@ -1247,7 +1247,7 @@ An example crash:
END OF CRASH REPORT
====
-Tips and Tricks
+TIPS AND TRICKS
---------------
The following tips and tricks have been collected from various
users of fast-import, and are offered here as suggestions.
@@ -1349,7 +1349,7 @@ Your users will feel better knowing how much of the data stream
has been processed.
-Packfile Optimization
+PACKFILE OPTIMIZATION
---------------------
When packing a blob fast-import always attempts to deltify against the last
blob written. Unless specifically arranged for by the frontend,
@@ -1380,7 +1380,7 @@ to force recomputation of all deltas can significantly reduce the
final packfile size (30-50% smaller can be quite typical).
-Memory Utilization
+MEMORY UTILIZATION
------------------
There are a number of factors which affect how much memory fast-import
requires to perform an import. Like critical sections of core
@@ -1458,7 +1458,7 @@ and lazy loading of subtrees, allows fast-import to efficiently import
projects with 2,000+ branches and 45,114+ files in a very limited
memory footprint (less than 2.7 MiB per active branch).
-Signals
+SIGNALS
-------
Sending *SIGUSR1* to the 'git fast-import' process ends the current
packfile early, simulating a `checkpoint` command. The impatient
diff --git a/Documentation/git-fetch-pack.txt b/Documentation/git-fetch-pack.txt
index f7ebe36..c975884 100644
--- a/Documentation/git-fetch-pack.txt
+++ b/Documentation/git-fetch-pack.txt
@@ -88,7 +88,7 @@ be in a separate packet, and the list must end with a flush packet.
infinite even if there is an ancestor-chain that long.
--shallow-since=<date>::
- Deepen or shorten the history of a shallow'repository to
+ Deepen or shorten the history of a shallow repository to
include all reachable commits after <date>.
--shallow-exclude=<revision>::
diff --git a/Documentation/git-filter-branch.txt b/Documentation/git-filter-branch.txt
index b634043..e6f08ab 100644
--- a/Documentation/git-filter-branch.txt
+++ b/Documentation/git-filter-branch.txt
@@ -230,7 +230,7 @@ rewrite, the exit status is `2`. On any other error, the exit status may be
any other non-zero value.
-Examples
+EXAMPLES
--------
Suppose you want to remove a file (containing confidential information
@@ -288,7 +288,7 @@ git filter-branch --parent-filter \
or even simpler:
-----------------------------------------------
-echo "$commit-id $graft-id" >> .git/info/grafts
+git replace --graft $commit-id $graft-id
git filter-branch $graft-id..HEAD
-----------------------------------------------
@@ -406,7 +406,7 @@ git filter-branch --index-filter \
-Checklist for Shrinking a Repository
+CHECKLIST FOR SHRINKING A REPOSITORY
------------------------------------
git-filter-branch can be used to get rid of a subset of files,
@@ -445,7 +445,7 @@ warned.
(or if your git-gc is not new enough to support arguments to
`--prune`, use `git repack -ad; git prune` instead).
-Notes
+NOTES
-----
git-filter-branch allows you to make complex shell-scripted rewrites
diff --git a/Documentation/git-fmt-merge-msg.txt b/Documentation/git-fmt-merge-msg.txt
index 44892c4..423b6e0 100644
--- a/Documentation/git-fmt-merge-msg.txt
+++ b/Documentation/git-fmt-merge-msg.txt
@@ -57,8 +57,8 @@ merge.summary::
Synonym to `merge.log`; this is deprecated and will be removed in
the future.
-EXAMPLE
--------
+EXAMPLES
+--------
---------
$ git fetch origin master
diff --git a/Documentation/git-for-each-ref.txt b/Documentation/git-for-each-ref.txt
index dffa14a..085d177 100644
--- a/Documentation/git-for-each-ref.txt
+++ b/Documentation/git-for-each-ref.txt
@@ -121,7 +121,7 @@ refname::
stripping with positive <N>, or it becomes the full refname if
stripping with negative <N>. Neither is an error.
+
-`strip` can be used as a synomym to `lstrip`.
+`strip` can be used as a synonym to `lstrip`.
objecttype::
The type of the object (`blob`, `tree`, `commit`, `tag`).
diff --git a/Documentation/git-format-patch.txt b/Documentation/git-format-patch.txt
index 6cbe462..b41e132 100644
--- a/Documentation/git-format-patch.txt
+++ b/Documentation/git-format-patch.txt
@@ -47,7 +47,7 @@ There are two ways to specify which commits to operate on.
The first rule takes precedence in the case of a single <commit>. To
apply the second rule, i.e., format everything since the beginning of
-history up until <commit>, use the '\--root' option: `git format-patch
+history up until <commit>, use the `--root` option: `git format-patch
--root <commit>`. If you want to format only <commit> itself, you
can do this with `git format-patch -1 <commit>`.
diff --git a/Documentation/git-gc.txt b/Documentation/git-gc.txt
index 3126e0d..24b2dd4 100644
--- a/Documentation/git-gc.txt
+++ b/Documentation/git-gc.txt
@@ -9,7 +9,7 @@ git-gc - Cleanup unnecessary files and optimize the local repository
SYNOPSIS
--------
[verse]
-'git gc' [--aggressive] [--auto] [--quiet] [--prune=<date> | --no-prune] [--force]
+'git gc' [--aggressive] [--auto] [--quiet] [--prune=<date> | --no-prune] [--force] [--keep-largest-pack]
DESCRIPTION
-----------
@@ -56,10 +56,16 @@ single pack using `git repack -d -l`. Setting the value of `gc.auto`
to 0 disables automatic packing of loose objects.
+
If the number of packs exceeds the value of `gc.autoPackLimit`,
-then existing packs (except those marked with a `.keep` file)
+then existing packs (except those marked with a `.keep` file
+or over `gc.bigPackThreshold` limit)
are consolidated into a single pack by using the `-A` option of
-'git repack'. Setting `gc.autoPackLimit` to 0 disables
-automatic consolidation of packs.
+'git repack'.
+If the amount of memory is estimated not enough for `git repack` to
+run smoothly and `gc.bigPackThreshold` is not set, the largest
+pack will also be excluded (this is the equivalent of running `git gc`
+with `--keep-base-pack`).
+Setting `gc.autoPackLimit` to 0 disables automatic consolidation of
+packs.
+
If houskeeping is required due to many loose objects or packs, all
other housekeeping tasks (e.g. rerere, working trees, reflog...) will
@@ -84,7 +90,12 @@ be performed as well.
Force `git gc` to run even if there may be another `git gc`
instance running on this repository.
-Configuration
+--keep-largest-pack::
+ All packs except the largest pack and those marked with a
+ `.keep` files are consolidated into a single pack. When this
+ option is used, `gc.bigPackThreshold` is ignored.
+
+CONFIGURATION
-------------
The optional configuration variable `gc.reflogExpire` can be
@@ -129,7 +140,7 @@ The optional configuration variable `gc.aggressiveWindow` controls how
much time is spent optimizing the delta compression of the objects in
the repository when the --aggressive option is specified. The larger
the value, the more time is spent optimizing the delta compression. See
-the documentation for the --window' option in linkgit:git-repack[1] for
+the documentation for the --window option in linkgit:git-repack[1] for
more details. This defaults to 250.
Similarly, the optional configuration variable `gc.aggressiveDepth`
@@ -144,7 +155,7 @@ old a stale working tree should be before `git worktree prune` deletes
it. Default is "3 months ago".
-Notes
+NOTES
-----
'git gc' tries very hard not to delete objects that are referenced
diff --git a/Documentation/git-grep.txt b/Documentation/git-grep.txt
index 18b4947..312409a 100644
--- a/Documentation/git-grep.txt
+++ b/Documentation/git-grep.txt
@@ -293,7 +293,7 @@ providing this option will cause it to die.
For more details about the <pathspec> syntax, see the 'pathspec' entry
in linkgit:gitglossary[7].
-Examples
+EXAMPLES
--------
`git grep 'time_t' -- '*.[ch]'`::
diff --git a/Documentation/git-http-fetch.txt b/Documentation/git-http-fetch.txt
index 21a33d2..666b042 100644
--- a/Documentation/git-http-fetch.txt
+++ b/Documentation/git-http-fetch.txt
@@ -15,8 +15,9 @@ DESCRIPTION
-----------
Downloads a remote Git repository via HTTP.
-*NOTE*: use of this command without -a is deprecated. The -a
-behaviour will become the default in a future release.
+This command always gets all objects. Historically, there were three options
+`-a`, `-c` and `-t` for choosing which objects to download. They are now
+silently ignored.
OPTIONS
-------
@@ -24,12 +25,8 @@ commit-id::
Either the hash or the filename under [URL]/refs/ to
pull.
--c::
- Get the commit objects.
--t::
- Get trees associated with the commit objects.
--a::
- Get all the objects.
+-a, -c, -t::
+ These options are ignored for historical reasons.
-v::
Report what is downloaded.
diff --git a/Documentation/git-http-push.txt b/Documentation/git-http-push.txt
index 2aceb6f..ea03a4e 100644
--- a/Documentation/git-http-push.txt
+++ b/Documentation/git-http-push.txt
@@ -55,7 +55,7 @@ OPTIONS
The remote refs to update.
-Specifying the Refs
+SPECIFYING THE REFS
-------------------
A '<ref>' specification can be either a single pattern, or a pair
diff --git a/Documentation/git-imap-send.txt b/Documentation/git-imap-send.txt
index 5d1e4c8..032613c 100644
--- a/Documentation/git-imap-send.txt
+++ b/Documentation/git-imap-send.txt
@@ -136,8 +136,8 @@ Using direct mode with SSL:
.........................
-EXAMPLE
--------
+EXAMPLES
+--------
To submit patches using GMail's IMAP interface, first, edit your ~/.gitconfig
to specify your account settings:
diff --git a/Documentation/git-index-pack.txt b/Documentation/git-index-pack.txt
index 138edb4..d5b7560 100644
--- a/Documentation/git-index-pack.txt
+++ b/Documentation/git-index-pack.txt
@@ -93,8 +93,8 @@ OPTIONS
--max-input-size=<size>::
Die, if the pack is larger than <size>.
-Note
-----
+NOTES
+-----
Once the index has been created, the list of object names is sorted
and the SHA-1 hash of that list is printed to stdout. If --stdin was
diff --git a/Documentation/git-log.txt b/Documentation/git-log.txt
index 5437f8b..90761f1 100644
--- a/Documentation/git-log.txt
+++ b/Documentation/git-log.txt
@@ -9,7 +9,7 @@ git-log - Show commit logs
SYNOPSIS
--------
[verse]
-'git log' [<options>] [<revision range>] [[\--] <path>...]
+'git log' [<options>] [<revision range>] [[--] <path>...]
DESCRIPTION
-----------
@@ -90,13 +90,13 @@ include::line-range-format.txt[]
ways to spell <revision range>, see the 'Specifying Ranges'
section of linkgit:gitrevisions[7].
-[\--] <path>...::
+[--] <path>...::
Show only commits that are enough to explain how the files
that match the specified paths came to be. See 'History
Simplification' below for details and other simplification
modes.
+
-Paths may need to be prefixed with ``\-- '' to separate them from
+Paths may need to be prefixed with `--` to separate them from
options or the revision range, when confusion arises.
include::rev-list-options.txt[]
@@ -125,7 +125,7 @@ EXAMPLES
`git log --since="2 weeks ago" -- gitk`::
Show the changes during the last two weeks to the file 'gitk'.
- The ``--'' is necessary to avoid confusion with the *branch* named
+ The `--` is necessary to avoid confusion with the *branch* named
'gitk'
`git log --name-status release..test`::
diff --git a/Documentation/git-ls-files.txt b/Documentation/git-ls-files.txt
index 3ac3e3a..5298f1b 100644
--- a/Documentation/git-ls-files.txt
+++ b/Documentation/git-ls-files.txt
@@ -53,7 +53,8 @@ OPTIONS
Show only ignored files in the output. When showing files in the
index, print only those matched by an exclude pattern. When
showing "other" files, show only those matched by an exclude
- pattern.
+ pattern. Standard ignore rules are not automatically activated,
+ therefore at least one of the `--exclude*` options is required.
-s::
--stage::
@@ -183,7 +184,7 @@ followed by the ("attr/<eolattr>").
Files to show. If no files are given all files which match the other
specified criteria are shown.
-Output
+OUTPUT
------
'git ls-files' just outputs the filenames unless `--stage` is specified in
which case it outputs:
@@ -208,7 +209,7 @@ quoted as explained for the configuration variable `core.quotePath`
verbatim and the line is terminated by a NUL byte.
-Exclude Patterns
+EXCLUDE PATTERNS
----------------
'git ls-files' can use a list of "exclude patterns" when
diff --git a/Documentation/git-ls-remote.txt b/Documentation/git-ls-remote.txt
index 5f2628c..b9fd377 100644
--- a/Documentation/git-ls-remote.txt
+++ b/Documentation/git-ls-remote.txt
@@ -10,7 +10,7 @@ SYNOPSIS
--------
[verse]
'git ls-remote' [--heads] [--tags] [--refs] [--upload-pack=<exec>]
- [-q | --quiet] [--exit-code] [--get-url]
+ [-q | --quiet] [--exit-code] [--get-url] [--sort=<key>]
[--symref] [<repository> [<refs>...]]
DESCRIPTION
@@ -60,6 +60,24 @@ OPTIONS
upload-pack only shows the symref HEAD, so it will be the only
one shown by ls-remote.
+--sort=<key>::
+ Sort based on the key given. Prefix `-` to sort in descending order
+ of the value. Supports "version:refname" or "v:refname" (tag names
+ are treated as versions). The "version:refname" sort order can also
+ be affected by the "versionsort.suffix" configuration variable.
+ See linkgit:git-for-each-ref[1] for more sort options, but be aware
+ keys like `committerdate` that require access to the objects
+ themselves will not work for refs whose objects have not yet been
+ fetched from the remote, and will give a `missing object` error.
+
+-o <option>::
+--server-option=<option>::
+ Transmit the given string to the server when communicating using
+ protocol version 2. The given string must not contain a NUL or LF
+ character.
+ When multiple `--server-option=<option>` are given, they are all
+ sent to the other side in the order listed on the command line.
+
<repository>::
The "remote" repository to query. This parameter can be
either a URL or the name of a remote (see the GIT URLS and
@@ -90,6 +108,10 @@ EXAMPLES
c5db5456ae3b0873fc659c19fafdde22313cc441 refs/tags/v0.99.2
7ceca275d047c90c0c7d5afb13ab97efdf51bd6e refs/tags/v0.99.3
+SEE ALSO
+--------
+linkgit:git-check-ref-format[1].
+
GIT
---
Part of the linkgit:git[1] suite
diff --git a/Documentation/git-mktree.txt b/Documentation/git-mktree.txt
index c3616e7..27fe2b3 100644
--- a/Documentation/git-mktree.txt
+++ b/Documentation/git-mktree.txt
@@ -14,7 +14,7 @@ SYNOPSIS
DESCRIPTION
-----------
Reads standard input in non-recursive `ls-tree` output format, and creates
-a tree object. The order of the tree entries is normalised by mktree so
+a tree object. The order of the tree entries is normalized by mktree so
pre-sorting the input is not required. The object name of the tree object
built is written to the standard output.
diff --git a/Documentation/git-name-rev.txt b/Documentation/git-name-rev.txt
index e8e68f5..5cb0eb0 100644
--- a/Documentation/git-name-rev.txt
+++ b/Documentation/git-name-rev.txt
@@ -61,8 +61,8 @@ OPTIONS
--always::
Show uniquely abbreviated commit object as fallback.
-EXAMPLE
--------
+EXAMPLES
+--------
Given a commit, find out where it is relative to the local refs. Say somebody
wrote you about that fantastic commit 33db5f4d9027a10e477ccf054b2c1ab94f74c85a.
diff --git a/Documentation/git-p4.txt b/Documentation/git-p4.txt
index d8c8f11..b0abe2c 100644
--- a/Documentation/git-p4.txt
+++ b/Documentation/git-p4.txt
@@ -29,8 +29,8 @@ Submit Git changes back to p4 using 'git p4 submit'. The command
the updated p4 remote branch.
-EXAMPLE
--------
+EXAMPLES
+--------
* Clone a repository:
+
------------
diff --git a/Documentation/git-pack-objects.txt b/Documentation/git-pack-objects.txt
index 81bc490..d95b472 100644
--- a/Documentation/git-pack-objects.txt
+++ b/Documentation/git-pack-objects.txt
@@ -12,7 +12,7 @@ SYNOPSIS
'git pack-objects' [-q | --progress | --all-progress] [--all-progress-implied]
[--no-reuse-delta] [--delta-base-offset] [--non-empty]
[--local] [--incremental] [--window=<n>] [--depth=<n>]
- [--revs [--unpacked | --all]]
+ [--revs [--unpacked | --all]] [--keep-pack=<pack-name>]
[--stdout [--filter=<filter-spec>] | base-name]
[--shallow] [--keep-true-parents] < object-list
@@ -96,7 +96,9 @@ base-name::
it too deep affects the performance on the unpacker
side, because delta data needs to be applied that many
times to get to the necessary object.
- The default value for --window is 10 and --depth is 50.
++
+The default value for --window is 10 and --depth is 50. The maximum
+depth is 4095.
--window-memory=<n>::
This option provides an additional limit on top of `--window`;
@@ -126,6 +128,13 @@ base-name::
has a .keep file to be ignored, even if it would have
otherwise been packed.
+--keep-pack=<pack-name>::
+ This flag causes an object already in the given pack to be
+ ignored, even if it would have otherwise been
+ packed. `<pack-name>` is the the pack file name without
+ leading directory (e.g. `pack-123.pack`). The option could be
+ specified multiple times to keep multiple packs.
+
--incremental::
This flag causes an object already in a pack to be ignored
even if it would have otherwise been packed.
@@ -267,6 +276,19 @@ Unexpected missing object will raise an error.
locally created objects [without .promisor] and objects from the
promisor remote [with .promisor].) This is used with partial clone.
+--keep-unreachable::
+ Objects unreachable from the refs in packs named with
+ --unpacked= option are added to the resulting pack, in
+ addition to the reachable objects that are not in packs marked
+ with *.keep files. This implies `--revs`.
+
+--pack-loose-unreachable::
+ Pack unreachable loose objects (and their loose counterparts
+ removed). This implies `--revs`.
+
+--unpack-unreachable::
+ Keep unreachable objects in loose form. This implies `--revs`.
+
SEE ALSO
--------
linkgit:git-rev-list[1]
diff --git a/Documentation/git-prune.txt b/Documentation/git-prune.txt
index a37c0af..03552dd 100644
--- a/Documentation/git-prune.txt
+++ b/Documentation/git-prune.txt
@@ -56,8 +56,8 @@ OPTIONS
reachable from any of our references, keep objects
reachable from listed <head>s.
-EXAMPLE
--------
+EXAMPLES
+--------
To prune objects not used by your repository or another that
borrows from your repository via its
@@ -67,7 +67,7 @@ borrows from your repository via its
$ git prune $(cd ../another && git rev-parse --all)
------------
-Notes
+NOTES
-----
In most cases, users will not need to call 'git prune' directly, but
diff --git a/Documentation/git-pull.txt b/Documentation/git-pull.txt
index ce05b7a..4e0ad6f 100644
--- a/Documentation/git-pull.txt
+++ b/Documentation/git-pull.txt
@@ -101,13 +101,17 @@ Options related to merging
include::merge-options.txt[]
-r::
---rebase[=false|true|preserve|interactive]::
+--rebase[=false|true|merges|preserve|interactive]::
When true, rebase the current branch on top of the upstream
branch after fetching. If there is a remote-tracking branch
corresponding to the upstream branch and the upstream branch
was rebased since last fetched, the rebase uses that information
to avoid rebasing non-local changes.
+
+When set to `merges`, rebase using `git rebase --rebase-merges` so that
+the local merge commits are included in the rebase (see
+linkgit:git-rebase[1] for details).
++
When set to preserve, rebase with the `--preserve-merges` option passed
to `git rebase` so that locally created merge commits will not be flattened.
+
diff --git a/Documentation/git-push.txt b/Documentation/git-push.txt
index 5b08302..55277a9 100644
--- a/Documentation/git-push.txt
+++ b/Documentation/git-push.txt
@@ -11,7 +11,7 @@ SYNOPSIS
[verse]
'git push' [--all | --mirror | --tags] [--follow-tags] [--atomic] [-n | --dry-run] [--receive-pack=<git-receive-pack>]
[--repo=<repository>] [-f | --force] [-d | --delete] [--prune] [-v | --verbose]
- [-u | --set-upstream] [--push-option=<string>]
+ [-u | --set-upstream] [-o <string> | --push-option=<string>]
[--[no-]signed|--signed=(true|false|if-asked)]
[--force-with-lease[=<refname>[:<expect>]]]
[--no-verify] [<repository> [<refspec>...]]
@@ -123,6 +123,7 @@ already exists on the remote side.
will be tab-separated and sent to stdout instead of stderr. The full
symbolic names of the refs will be given.
+-d::
--delete::
All listed refs are deleted from the remote repository. This is
the same as prefixing all refs with a colon.
@@ -300,7 +301,7 @@ origin +master` to force a push to the `master` branch). See the
These options are passed to linkgit:git-send-pack[1]. A thin transfer
significantly reduces the amount of sent data when the sender and
receiver share many of the same objects in common. The default is
- \--thin.
+ `--thin`.
-q::
--quiet::
@@ -423,7 +424,7 @@ reason::
refs, no explanation is needed. For a failed ref, the reason for
failure is described.
-Note about fast-forwards
+NOTE ABOUT FAST-FORWARDS
------------------------
When an update changes a branch (or more in general, a ref) that used to
@@ -510,7 +511,7 @@ overwrite it. In other words, "git push --force" is a method reserved for
a case where you do mean to lose history.
-Examples
+EXAMPLES
--------
`git push`::
diff --git a/Documentation/git-read-tree.txt b/Documentation/git-read-tree.txt
index f2a07d5..5c70bc2 100644
--- a/Documentation/git-read-tree.txt
+++ b/Documentation/git-read-tree.txt
@@ -132,7 +132,7 @@ OPTIONS
The id of the tree object(s) to be read/merged.
-Merging
+MERGING
-------
If `-m` is specified, 'git read-tree' can perform 3 kinds of
merge, a single tree merge if only 1 tree is given, a
@@ -382,7 +382,7 @@ middle of doing, and when your working tree is ready (i.e. you
have finished your work-in-progress), attempt the merge again.
-Sparse checkout
+SPARSE CHECKOUT
---------------
"Sparse checkout" allows populating the working directory sparsely.
diff --git a/Documentation/git-rebase.txt b/Documentation/git-rebase.txt
index 3277ca1..bd5ecff 100644
--- a/Documentation/git-rebase.txt
+++ b/Documentation/git-rebase.txt
@@ -364,9 +364,10 @@ default is `--no-fork-point`, otherwise the default is `--fork-point`.
Incompatible with the --interactive option.
--signoff::
- This flag is passed to 'git am' to sign off all the rebased
- commits (see linkgit:git-am[1]). Incompatible with the
- --interactive option.
+ Add a Signed-off-by: trailer to all the rebased commits. Note
+ that if `--interactive` is given then only commits marked to be
+ picked, edited or reworded will have the trailer added. Incompatible
+ with the `--preserve-merges` option.
-i::
--interactive::
@@ -378,6 +379,33 @@ The commit list format can be changed by setting the configuration option
rebase.instructionFormat. A customized instruction format will automatically
have the long commit hash prepended to the format.
+-r::
+--rebase-merges[=(rebase-cousins|no-rebase-cousins)]::
+ By default, a rebase will simply drop merge commits from the todo
+ list, and put the rebased commits into a single, linear branch.
+ With `--rebase-merges`, the rebase will instead try to preserve
+ the branching structure within the commits that are to be rebased,
+ by recreating the merge commits. Any resolved merge conflicts or
+ manual amendments in these merge commits will have to be
+ resolved/re-applied manually.
++
+By default, or when `no-rebase-cousins` was specified, commits which do not
+have `<upstream>` as direct ancestor will keep their original branch point,
+i.e. commits that would be excluded by gitlink:git-log[1]'s
+`--ancestry-path` option will keep their original ancestry by default. If
+the `rebase-cousins` mode is turned on, such commits are instead rebased
+onto `<upstream>` (or `<onto>`, if specified).
++
+The `--rebase-merges` mode is similar in spirit to `--preserve-merges`, but
+in contrast to that option works well in interactive rebases: commits can be
+reordered, inserted and dropped at will.
++
+It is currently only possible to recreate the merge commits using the
+`recursive` merge strategy; Different merge strategies can be used only via
+explicit `exec git merge -s <strategy> [...]` commands.
++
+See also REBASING MERGES below.
+
-p::
--preserve-merges::
Recreate merge commits instead of flattening the history by replaying
@@ -775,12 +803,146 @@ The ripple effect of a "hard case" recovery is especially bad:
'everyone' downstream from 'topic' will now have to perform a "hard
case" recovery too!
+REBASING MERGES
+-----------------
+
+The interactive rebase command was originally designed to handle
+individual patch series. As such, it makes sense to exclude merge
+commits from the todo list, as the developer may have merged the
+then-current `master` while working on the branch, only to rebase
+all the commits onto `master` eventually (skipping the merge
+commits).
+
+However, there are legitimate reasons why a developer may want to
+recreate merge commits: to keep the branch structure (or "commit
+topology") when working on multiple, inter-related branches.
+
+In the following example, the developer works on a topic branch that
+refactors the way buttons are defined, and on another topic branch
+that uses that refactoring to implement a "Report a bug" button. The
+output of `git log --graph --format=%s -5` may look like this:
+
+------------
+* Merge branch 'report-a-bug'
+|\
+| * Add the feedback button
+* | Merge branch 'refactor-button'
+|\ \
+| |/
+| * Use the Button class for all buttons
+| * Extract a generic Button class from the DownloadButton one
+------------
+
+The developer might want to rebase those commits to a newer `master`
+while keeping the branch topology, for example when the first topic
+branch is expected to be integrated into `master` much earlier than the
+second one, say, to resolve merge conflicts with changes to the
+DownloadButton class that made it into `master`.
+
+This rebase can be performed using the `--rebase-merges` option.
+It will generate a todo list looking like this:
+
+------------
+label onto
+
+# Branch: refactor-button
+reset onto
+pick 123456 Extract a generic Button class from the DownloadButton one
+pick 654321 Use the Button class for all buttons
+label refactor-button
+
+# Branch: report-a-bug
+reset refactor-button # Use the Button class for all buttons
+pick abcdef Add the feedback button
+label report-a-bug
+
+reset onto
+merge -C a1b2c3 refactor-button # Merge 'refactor-button'
+merge -C 6f5e4d report-a-bug # Merge 'report-a-bug'
+------------
+
+In contrast to a regular interactive rebase, there are `label`, `reset`
+and `merge` commands in addition to `pick` ones.
+
+The `label` command associates a label with the current HEAD when that
+command is executed. These labels are created as worktree-local refs
+(`refs/rewritten/<label>`) that will be deleted when the rebase
+finishes. That way, rebase operations in multiple worktrees linked to
+the same repository do not interfere with one another. If the `label`
+command fails, it is rescheduled immediately, with a helpful message how
+to proceed.
+
+The `reset` command resets the HEAD, index and worktree to the specified
+revision. It is isimilar to an `exec git reset --hard <label>`, but
+refuses to overwrite untracked files. If the `reset` command fails, it is
+rescheduled immediately, with a helpful message how to edit the todo list
+(this typically happens when a `reset` command was inserted into the todo
+list manually and contains a typo).
+
+The `merge` command will merge the specified revision into whatever is
+HEAD at that time. With `-C <original-commit>`, the commit message of
+the specified merge commit will be used. When the `-C` is changed to
+a lower-case `-c`, the message will be opened in an editor after a
+successful merge so that the user can edit the message.
+
+If a `merge` command fails for any reason other than merge conflicts (i.e.
+when the merge operation did not even start), it is rescheduled immediately.
+
+At this time, the `merge` command will *always* use the `recursive`
+merge strategy, with no way to choose a different one. To work around
+this, an `exec` command can be used to call `git merge` explicitly,
+using the fact that the labels are worktree-local refs (the ref
+`refs/rewritten/onto` would correspond to the label `onto`, for example).
+
+Note: the first command (`label onto`) labels the revision onto which
+the commits are rebased; The name `onto` is just a convention, as a nod
+to the `--onto` option.
+
+It is also possible to introduce completely new merge commits from scratch
+by adding a command of the form `merge <merge-head>`. This form will
+generate a tentative commit message and always open an editor to let the
+user edit it. This can be useful e.g. when a topic branch turns out to
+address more than a single concern and wants to be split into two or
+even more topic branches. Consider this todo list:
+
+------------
+pick 192837 Switch from GNU Makefiles to CMake
+pick 5a6c7e Document the switch to CMake
+pick 918273 Fix detection of OpenSSL in CMake
+pick afbecd http: add support for TLS v1.3
+pick fdbaec Fix detection of cURL in CMake on Windows
+------------
+
+The one commit in this list that is not related to CMake may very well
+have been motivated by working on fixing all those bugs introduced by
+switching to CMake, but it addresses a different concern. To split this
+branch into two topic branches, the todo list could be edited like this:
+
+------------
+label onto
+
+pick afbecd http: add support for TLS v1.3
+label tlsv1.3
+
+reset onto
+pick 192837 Switch from GNU Makefiles to CMake
+pick 918273 Fix detection of OpenSSL in CMake
+pick fdbaec Fix detection of cURL in CMake on Windows
+pick 5a6c7e Document the switch to CMake
+label cmake
+
+reset onto
+merge tlsv1.3
+merge cmake
+------------
+
BUGS
----
The todo list presented by `--preserve-merges --interactive` does not
represent the topology of the revision graph. Editing commits and
rewording their commit messages should work fine, but attempts to
-reorder commits tend to produce counterintuitive results.
+reorder commits tend to produce counterintuitive results. Use
+`--rebase-merges` in such scenarios instead.
For example, an attempt to rearrange
------------
diff --git a/Documentation/git-receive-pack.txt b/Documentation/git-receive-pack.txt
index 86a4b32..dedf97e 100644
--- a/Documentation/git-receive-pack.txt
+++ b/Documentation/git-receive-pack.txt
@@ -41,7 +41,7 @@ OPTIONS
<directory>::
The repository to sync into.
-pre-receive Hook
+PRE-RECEIVE HOOK
----------------
Before any ref is updated, if $GIT_DIR/hooks/pre-receive file exists
and is executable, it will be invoked once with no parameters. The
@@ -116,7 +116,7 @@ bail out if the update is not to be supported.
See the notes on the quarantine environment below.
-update Hook
+UPDATE HOOK
-----------
Before each ref is updated, if $GIT_DIR/hooks/update file exists
and is executable, it is invoked once per ref, with three parameters:
@@ -138,7 +138,7 @@ ensure the ref will actually be updated, it is only a prerequisite.
As such it is not a good idea to send notices (e.g. email) from
this hook. Consider using the post-receive hook instead.
-post-receive Hook
+POST-RECEIVE HOOK
-----------------
After all refs were updated (or attempted to be updated), if any
ref update was successful, and if $GIT_DIR/hooks/post-receive
@@ -198,7 +198,7 @@ after it was updated by 'git-receive-pack', but before the hook was able
to evaluate it. It is recommended that hooks rely on sha1-new
rather than the current value of refname.
-post-update Hook
+POST-UPDATE HOOK
----------------
After all other processing, if at least one ref was updated, and
if $GIT_DIR/hooks/post-update file exists and is executable, then
@@ -216,7 +216,7 @@ if the repository is packed and is served via a dumb transport.
exec git update-server-info
-Quarantine Environment
+QUARANTINE ENVIRONMENT
----------------------
When `receive-pack` takes in objects, they are placed into a temporary
diff --git a/Documentation/git-remote-ext.txt b/Documentation/git-remote-ext.txt
index b25d0b5..3fc5d94 100644
--- a/Documentation/git-remote-ext.txt
+++ b/Documentation/git-remote-ext.txt
@@ -55,14 +55,14 @@ some tunnel.
the vhost field in the git:// service request (to rest of the argument).
Default is not to send vhost in such request (if sent).
-ENVIRONMENT VARIABLES:
-----------------------
+ENVIRONMENT VARIABLES
+---------------------
GIT_TRANSLOOP_DEBUG::
If set, prints debugging information about various reads/writes.
-ENVIRONMENT VARIABLES PASSED TO COMMAND:
-----------------------------------------
+ENVIRONMENT VARIABLES PASSED TO COMMAND
+---------------------------------------
GIT_EXT_SERVICE::
Set to long name (git-upload-pack, etc...) of service helper needs
@@ -73,8 +73,8 @@ GIT_EXT_SERVICE_NOPREFIX::
to invoke.
-EXAMPLES:
----------
+EXAMPLES
+--------
This remote helper is transparently used by Git when
you use commands such as "git fetch <URL>", "git clone <URL>",
, "git push <URL>" or "git remote add <nick> <URL>", where <URL>
diff --git a/Documentation/git-remote.txt b/Documentation/git-remote.txt
index 4feddc0..595948d 100644
--- a/Documentation/git-remote.txt
+++ b/Documentation/git-remote.txt
@@ -203,7 +203,7 @@ The remote configuration is achieved using the `remote.origin.url` and
`remote.origin.fetch` configuration variables. (See
linkgit:git-config[1]).
-Examples
+EXAMPLES
--------
* Add a new remote, fetch, and check out a branch from it
diff --git a/Documentation/git-repack.txt b/Documentation/git-repack.txt
index ae750e9..d90e790 100644
--- a/Documentation/git-repack.txt
+++ b/Documentation/git-repack.txt
@@ -9,7 +9,7 @@ git-repack - Pack unpacked objects in a repository
SYNOPSIS
--------
[verse]
-'git repack' [-a] [-A] [-d] [-f] [-F] [-l] [-n] [-q] [-b] [--window=<n>] [--depth=<n>] [--threads=<n>]
+'git repack' [-a] [-A] [-d] [-f] [-F] [-l] [-n] [-q] [-b] [--window=<n>] [--depth=<n>] [--threads=<n>] [--keep-pack=<pack-name>]
DESCRIPTION
-----------
@@ -90,7 +90,9 @@ other objects in that pack they already have locally.
space. `--depth` limits the maximum delta depth; making it too deep
affects the performance on the unpacker side, because delta data needs
to be applied that many times to get to the necessary object.
- The default value for --window is 10 and --depth is 50.
++
+The default value for --window is 10 and --depth is 50. The maximum
+depth is 4095.
--threads=<n>::
This option is passed through to `git pack-objects`.
@@ -133,6 +135,13 @@ other objects in that pack they already have locally.
with `-b` or `repack.writeBitmaps`, as it ensures that the
bitmapped packfile has the necessary objects.
+--keep-pack=<pack-name>::
+ Exclude the given pack from repacking. This is the equivalent
+ of having `.keep` file on the pack. `<pack-name>` is the the
+ pack file name without leading directory (e.g. `pack-123.pack`).
+ The option could be specified multiple times to keep multiple
+ packs.
+
--unpack-unreachable=<when>::
When loosening unreachable objects, do not bother loosening any
objects older than `<when>`. This can be used to optimize out
diff --git a/Documentation/git-replace.txt b/Documentation/git-replace.txt
index e5c57ae..246dc99 100644
--- a/Documentation/git-replace.txt
+++ b/Documentation/git-replace.txt
@@ -11,6 +11,7 @@ SYNOPSIS
'git replace' [-f] <object> <replacement>
'git replace' [-f] --edit <object>
'git replace' [-f] --graft <commit> [<parent>...]
+'git replace' [-f] --convert-graft-file
'git replace' -d <object>...
'git replace' [--format=<format>] [-l [<pattern>]]
@@ -87,9 +88,13 @@ OPTIONS
content as <commit> except that its parents will be
[<parent>...] instead of <commit>'s parents. A replacement ref
is then created to replace <commit> with the newly created
- commit. See contrib/convert-grafts-to-replace-refs.sh for an
- example script based on this option that can convert grafts to
- replace refs.
+ commit. Use `--convert-graft-file` to convert a
+ `$GIT_DIR/info/grafts` file and use replace refs instead.
+
+--convert-graft-file::
+ Creates graft commits for all entries in `$GIT_DIR/info/grafts`
+ and deletes that file upon success. The purpose is to help users
+ with transitioning off of the now-deprecated graft file.
-l <pattern>::
--list <pattern>::
diff --git a/Documentation/git-request-pull.txt b/Documentation/git-request-pull.txt
index c32cb0b..4d4392d 100644
--- a/Documentation/git-request-pull.txt
+++ b/Documentation/git-request-pull.txt
@@ -46,8 +46,8 @@ ref that is different from the ref you have locally, you can use the
its remote name.
-EXAMPLE
--------
+EXAMPLES
+--------
Imagine that you built your work on your `master` branch on top of
the `v1.0` release, and want it to be integrated to the project.
diff --git a/Documentation/git-send-email.txt b/Documentation/git-send-email.txt
index 71ef97b..464c15b 100644
--- a/Documentation/git-send-email.txt
+++ b/Documentation/git-send-email.txt
@@ -255,7 +255,7 @@ must be used for each option.
--batch-size=<num>::
Some email servers (e.g. smtp.163.com) limit the number emails to be
- sent per session (connection) and this will lead to a faliure when
+ sent per session (connection) and this will lead to a failure when
sending many messages. With this option, send-email will disconnect after
sending $<num> messages and wait for a few seconds (see --relogin-delay)
and reconnect, to work around such a limit. You may want to
@@ -458,8 +458,8 @@ sendemail.confirm::
one of 'always', 'never', 'cc', 'compose', or 'auto'. See `--confirm`
in the previous section for the meaning of these values.
-EXAMPLE
--------
+EXAMPLES
+--------
Use gmail as the smtp server
~~~~~~~~~~~~~~~~~~~~~~~~~~~~
To use 'git send-email' to send your patches through the GMail SMTP server,
@@ -473,16 +473,7 @@ edit ~/.gitconfig to specify your account settings:
If you have multifactor authentication setup on your gmail account, you will
need to generate an app-specific password for use with 'git send-email'. Visit
-https://security.google.com/settings/security/apppasswords to setup an
-app-specific password. Once setup, you can store it with the credentials
-helper:
-
- $ git credential fill
- protocol=smtp
- host=smtp.gmail.com
- username=youname@gmail.com
- password=app-password
-
+https://security.google.com/settings/security/apppasswords to create it.
Once your commits are ready to be sent to the mailing list, run the
following commands:
@@ -491,6 +482,11 @@ following commands:
$ edit outgoing/0000-*
$ git send-email outgoing/*
+The first time you run it, you will be prompted for your credentials. Enter the
+app-specific or your regular password as appropriate. If you have credential
+helper configured (see linkgit:git-credential[1]), the password will be saved in
+the credential store so you won't have to type it the next time.
+
Note: the following perl modules are required
Net::SMTP::SSL, MIME::Base64 and Authen::SASL
diff --git a/Documentation/git-send-pack.txt b/Documentation/git-send-pack.txt
index f51c649..44fd146 100644
--- a/Documentation/git-send-pack.txt
+++ b/Documentation/git-send-pack.txt
@@ -99,7 +99,7 @@ be in a separate packet, and the list must end with a flush packet.
The remote refs to update.
-Specifying the Refs
+SPECIFYING THE REFS
-------------------
There are three ways to specify which refs to update on the
diff --git a/Documentation/git-shell.txt b/Documentation/git-shell.txt
index 54cf256..11361f3 100644
--- a/Documentation/git-shell.txt
+++ b/Documentation/git-shell.txt
@@ -62,8 +62,8 @@ permissions.
If a `no-interactive-login` command exists, then it is run and the
interactive shell is aborted.
-EXAMPLE
--------
+EXAMPLES
+--------
To disable interactive logins, displaying a greeting instead:
diff --git a/Documentation/git-shortlog.txt b/Documentation/git-shortlog.txt
index 5e35ea1..bc80905 100644
--- a/Documentation/git-shortlog.txt
+++ b/Documentation/git-shortlog.txt
@@ -8,7 +8,7 @@ git-shortlog - Summarize 'git log' output
SYNOPSIS
--------
[verse]
-'git shortlog' [<options>] [<revision range>] [[\--] <path>...]
+'git shortlog' [<options>] [<revision range>] [[--] <path>...]
git log --pretty=short | 'git shortlog' [<options>]
DESCRIPTION
@@ -69,11 +69,11 @@ them.
ways to spell <revision range>, see the "Specifying Ranges"
section of linkgit:gitrevisions[7].
-[\--] <path>...::
+[--] <path>...::
Consider only commits that are enough to explain how the files
that match the specified paths came to be.
+
-Paths may need to be prefixed with "\-- " to separate them from
+Paths may need to be prefixed with `--` to separate them from
options or the revision range, when confusion arises.
MAPPING AUTHORS
diff --git a/Documentation/git-show-branch.txt b/Documentation/git-show-branch.txt
index 7818e0f..262db04 100644
--- a/Documentation/git-show-branch.txt
+++ b/Documentation/git-show-branch.txt
@@ -173,8 +173,8 @@ The "fixes" branch adds one commit "Introduce "reset type" flag to
The current branch is "master".
-EXAMPLE
--------
+EXAMPLES
+--------
If you keep your primary branches immediately under
`refs/heads`, and topic branches in subdirectories of
diff --git a/Documentation/git-show-ref.txt b/Documentation/git-show-ref.txt
index c0aa871..d28e615 100644
--- a/Documentation/git-show-ref.txt
+++ b/Documentation/git-show-ref.txt
@@ -120,8 +120,8 @@ $ git show-ref --heads --hash
...
-----------------------------------------------------------------------------
-EXAMPLE
--------
+EXAMPLES
+--------
To show all references called "master", whether tags or heads or anything
else, and regardless of how deep in the reference naming hierarchy they are,
diff --git a/Documentation/git-show.txt b/Documentation/git-show.txt
index e73ef54..0e1695d 100644
--- a/Documentation/git-show.txt
+++ b/Documentation/git-show.txt
@@ -77,7 +77,7 @@ EXAMPLES
Concatenates the contents of said Makefiles in the head
of the branch `master`.
-Discussion
+DISCUSSION
----------
include::i18n.txt[]
diff --git a/Documentation/git-status.txt b/Documentation/git-status.txt
index 6c230c0..c4467ff 100644
--- a/Documentation/git-status.txt
+++ b/Documentation/git-status.txt
@@ -113,7 +113,7 @@ The possible options are:
- 'matching' - Shows ignored files and directories matching an
ignore pattern.
+
-When 'matching' mode is specified, paths that explicity match an
+When 'matching' mode is specified, paths that explicitly match an
ignored pattern are shown. If a directory matches an ignore pattern,
then it is shown, but not paths contained in the ignored directory. If
a directory does not match an ignore pattern, but all contents are
@@ -135,6 +135,16 @@ ignored, then the directory is not shown, but all contents are shown.
Display or do not display detailed ahead/behind counts for the
branch relative to its upstream branch. Defaults to true.
+--renames::
+--no-renames::
+ Turn on/off rename detection regardless of user configuration.
+ See also linkgit:git-diff[1] `--no-renames`.
+
+--find-renames[=<n>]::
+ Turn on rename detection, optionally setting the similarity
+ threshold.
+ See also linkgit:git-diff[1] `--find-renames`.
+
<pathspec>...::
See the 'pathspec' entry in linkgit:gitglossary[7].
diff --git a/Documentation/git-submodule.txt b/Documentation/git-submodule.txt
index 71c5618..4a5cc38 100644
--- a/Documentation/git-submodule.txt
+++ b/Documentation/git-submodule.txt
@@ -213,8 +213,8 @@ sync [--recursive] [--] [<path>...]::
submodule URLs change upstream and you need to update your local
repositories accordingly.
+
-"git submodule sync" synchronizes all submodules while
-"git submodule sync \-- A" synchronizes submodule "A" only.
+`git submodule sync` synchronizes all submodules while
+`git submodule sync -- A` synchronizes submodule "A" only.
+
If `--recursive` is specified, this command will recurse into the
registered submodules, and sync any nested submodules within.
@@ -239,6 +239,13 @@ OPTIONS
--quiet::
Only print error messages.
+--progress::
+ This option is only valid for add and update commands.
+ Progress status is reported on the standard error stream
+ by default when it is attached to a terminal, unless -q
+ is specified. This flag forces progress status even if the
+ standard error stream is not directed to a terminal.
+
--all::
This option is only valid for the deinit command. Unregister all
submodules in the working tree.
@@ -362,7 +369,15 @@ the submodule itself.
this option will be passed to the linkgit:git-clone[1] command.
+
*NOTE*: Do *not* use this option unless you have read the note
-for linkgit:git-clone[1]'s `--reference` and `--shared` options carefully.
+for linkgit:git-clone[1]'s `--reference`, `--shared`, and `--dissociate`
+options carefully.
+
+--dissociate::
+ This option is only valid for add and update commands. These
+ commands sometimes need to clone a remote repository. In this case,
+ this option will be passed to the linkgit:git-clone[1] command.
++
+*NOTE*: see the NOTE for the `--reference` option.
--recursive::
This option is only valid for foreach, update, status and sync commands.
diff --git a/Documentation/git-svn.txt b/Documentation/git-svn.txt
index d59379e..e961595 100644
--- a/Documentation/git-svn.txt
+++ b/Documentation/git-svn.txt
@@ -707,7 +707,7 @@ creating the branch or tag.
config key: svn.useLogAuthor
--add-author-from::
- When committing to svn from Git (as part of 'commit-diff', 'set-tree' or 'dcommit'
+ When committing to svn from Git (as part of 'set-tree' or 'dcommit'
operations), if the existing log message doesn't already have a
`From:` or `Signed-off-by:` line, append a `From:` line based on the
Git commit's author string. If you use this, then `--use-log-author`
diff --git a/Documentation/git-update-index.txt b/Documentation/git-update-index.txt
index 3897a59..4e8e762 100644
--- a/Documentation/git-update-index.txt
+++ b/Documentation/git-update-index.txt
@@ -228,7 +228,7 @@ will remove the intended effect of the option.
cleaner names.
The same applies to directories ending '/' and paths with '//'
-Using --refresh
+USING --REFRESH
---------------
`--refresh` does not calculate a new sha1 file or bring the index
up to date for mode/content changes. But what it *does* do is to
@@ -239,7 +239,7 @@ the stat entry is out of date.
For example, you'd want to do this after doing a 'git read-tree', to link
up the stat index details with the proper files.
-Using --cacheinfo or --info-only
+USING --CACHEINFO OR --INFO-ONLY
--------------------------------
`--cacheinfo` is used to register a file that is not in the
current working directory. This is useful for minimum-checkout
@@ -261,7 +261,7 @@ useful when the file is available, but you do not wish to update the
object database.
-Using --index-info
+USING --INDEX-INFO
------------------
`--index-info` is a more powerful mechanism that lets you feed
@@ -317,7 +317,7 @@ $ git ls-files -s
------------
-Using ``assume unchanged'' bit
+USING ``ASSUME UNCHANGED'' BIT
------------------------------
Many operations in Git depend on your filesystem to have an
@@ -350,7 +350,7 @@ the index (use `git update-index --really-refresh` if you want
to mark them as "assume unchanged").
-Examples
+EXAMPLES
--------
To update and refresh only the files already checked out:
@@ -387,7 +387,7 @@ M foo.c
<9> now it checks with lstat(2) and finds it has been changed.
-Skip-worktree bit
+SKIP-WORKTREE BIT
-----------------
Skip-worktree bit can be defined in one (long) sentence: When reading
@@ -407,7 +407,7 @@ Although this bit looks similar to assume-unchanged bit, its goal is
different from assume-unchanged bit's. Skip-worktree also takes
precedence over assume-unchanged bit when both are set.
-Split index
+SPLIT INDEX
-----------
This mode is designed for repositories with very large indexes, and
@@ -432,7 +432,7 @@ To avoid deleting a shared index file that is still used, its
modification time is updated to the current time everytime a new split
index based on the shared index file is either created or read from.
-Untracked cache
+UNTRACKED CACHE
---------------
This cache is meant to speed up commands that involve determining
@@ -490,7 +490,7 @@ As with the bug described above the solution is to one-off do a "git
status" run with `core.untrackedCache=false` to flush out the leftover
bad data.
-File System Monitor
+FILE SYSTEM MONITOR
-------------------
This feature is intended to speed up git operations for repos that have
@@ -518,7 +518,7 @@ file system monitor is added to or removed from the index the next time
a command reads the index. When `--[no-]fsmonitor` are used, the file
system monitor is immediately added to or removed from the index.
-Configuration
+CONFIGURATION
-------------
The command honors `core.filemode` configuration variable. If
diff --git a/Documentation/git-update-ref.txt b/Documentation/git-update-ref.txt
index 969bfab..bc8fdfd 100644
--- a/Documentation/git-update-ref.txt
+++ b/Documentation/git-update-ref.txt
@@ -120,7 +120,7 @@ modifications are performed. Note that while each individual
<ref> is updated or deleted atomically, a concurrent reader may
still see a subset of the modifications.
-Logging Updates
+LOGGING UPDATES
---------------
If config parameter "core.logAllRefUpdates" is true and the ref is one under
"refs/heads/", "refs/remotes/", "refs/notes/", or the symbolic ref HEAD; or
diff --git a/Documentation/git-var.txt b/Documentation/git-var.txt
index 44ff954..6072f93 100644
--- a/Documentation/git-var.txt
+++ b/Documentation/git-var.txt
@@ -23,14 +23,14 @@ OPTIONS
as well. (However, the configuration variables listing functionality
is deprecated in favor of `git config -l`.)
-EXAMPLE
+EXAMPLES
--------
$ git var GIT_AUTHOR_IDENT
Eric W. Biederman <ebiederm@lnxi.com> 1121223278 -0600
VARIABLES
-----------
+---------
GIT_AUTHOR_IDENT::
The author of a piece of code.
diff --git a/Documentation/git-web--browse.txt b/Documentation/git-web--browse.txt
index 2d6b09a..a4ec25b 100644
--- a/Documentation/git-web--browse.txt
+++ b/Documentation/git-web--browse.txt
@@ -84,7 +84,7 @@ variable exists then 'git web{litdd}browse' will treat the specified tool
as a custom command and will use a shell eval to run the command with
the URLs passed as arguments.
-Note about konqueror
+NOTE ABOUT KONQUEROR
--------------------
When 'konqueror' is specified by a command-line option or a
diff --git a/Documentation/git-worktree.txt b/Documentation/git-worktree.txt
index e7eb24a..afc6576 100644
--- a/Documentation/git-worktree.txt
+++ b/Documentation/git-worktree.txt
@@ -14,7 +14,7 @@ SYNOPSIS
'git worktree lock' [--reason <string>] <worktree>
'git worktree move' <worktree> <new-path>
'git worktree prune' [-n] [-v] [--expire <expire>]
-'git worktree remove' [--force] <worktree>
+'git worktree remove' [-f] <worktree>
'git worktree unlock' <worktree>
DESCRIPTION
@@ -27,11 +27,12 @@ out more than one branch at a time. With `git worktree add` a new working
tree is associated with the repository. This new working tree is called a
"linked working tree" as opposed to the "main working tree" prepared by "git
init" or "git clone". A repository has one main working tree (if it's not a
-bare repository) and zero or more linked working trees.
+bare repository) and zero or more linked working trees. When you are done
+with a linked working tree, remove it with `git worktree remove`.
-When you are done with a linked working tree you can simply delete it.
-The working tree's administrative files in the repository (see
-"DETAILS" below) will eventually be removed automatically (see
+If a working tree is deleted without using `git worktree remove`, then
+its associated administrative files, which reside in the repository
+(see "DETAILS" below), will eventually be removed automatically (see
`gc.worktreePruneExpire` in linkgit:git-config[1]), or you can run
`git worktree prune` in the main or any linked working tree to
clean up any stale administrative files.
@@ -60,8 +61,13 @@ $ git worktree add --track -b <branch> <path> <remote>/<branch>
------------
+
If `<commit-ish>` is omitted and neither `-b` nor `-B` nor `--detach` used,
-then, as a convenience, a new branch based at HEAD is created automatically,
-as if `-b $(basename <path>)` was specified.
+then, as a convenience, the new worktree is associated with a branch
+(call it `<branch>`) named after `$(basename <path>)`. If `<branch>`
+doesn't exist, a new branch based on HEAD is automatically created as
+if `-b <branch>` was given. If `<branch>` does exist, it will be
+checked out in the new worktree, if it's not checked out anywhere
+else, otherwise the command will refuse to create the worktree (unless
+`--force` is used).
list::
@@ -106,7 +112,7 @@ OPTIONS
By default, `add` refuses to create a new working tree when
`<commit-ish>` is a branch name and is already checked out by
another working tree and `remove` refuses to remove an unclean
- working tree. This option overrides that safeguard.
+ working tree. This option overrides these safeguards.
-b <new-branch>::
-B <new-branch>::
@@ -232,7 +238,7 @@ The worktree list command has two output formats. The default format shows the
details on a single line with columns. For example:
------------
-S git worktree list
+$ git worktree list
/path/to/bare-source (bare)
/path/to/linked-worktree abcd1234 [master]
/path/to/other-linked-worktree 1234abc (detached HEAD)
@@ -247,7 +253,7 @@ if the value is true. An empty line indicates the end of a worktree. For
example:
------------
-S git worktree list --porcelain
+$ git worktree list --porcelain
worktree /path/to/bare-source
bare
@@ -278,8 +284,7 @@ $ pushd ../temp
# ... hack hack hack ...
$ git commit -a -m 'emergency fix for boss'
$ popd
-$ rm -rf ../temp
-$ git worktree prune
+$ git worktree remove ../temp
------------
BUGS
diff --git a/Documentation/git.txt b/Documentation/git.txt
index 4767860..c662f41 100644
--- a/Documentation/git.txt
+++ b/Documentation/git.txt
@@ -11,7 +11,7 @@ SYNOPSIS
[verse]
'git' [--version] [--help] [-C <path>] [-c <name>=<value>]
[--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
- [-p|--paginate|--no-pager] [--no-replace-objects] [--bare]
+ [-p|--paginate|-P|--no-pager] [--no-replace-objects] [--bare]
[--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
[--super-prefix=<path>]
<command> [<args>]
@@ -103,6 +103,7 @@ foo.bar= ...`) sets `foo.bar` to the empty string which `git config
configuration options (see the "Configuration Mechanism" section
below).
+-P::
--no-pager::
Do not pipe Git output into a pager.
diff --git a/Documentation/gitattributes.txt b/Documentation/gitattributes.txt
index 1094fe2..b72936a 100644
--- a/Documentation/gitattributes.txt
+++ b/Documentation/gitattributes.txt
@@ -279,6 +279,94 @@ few exceptions. Even though...
catch potential problems early, safety triggers.
+`working-tree-encoding`
+^^^^^^^^^^^^^^^^^^^^^^^
+
+Git recognizes files encoded in ASCII or one of its supersets (e.g.
+UTF-8, ISO-8859-1, ...) as text files. Files encoded in certain other
+encodings (e.g. UTF-16) are interpreted as binary and consequently
+built-in Git text processing tools (e.g. 'git diff') as well as most Git
+web front ends do not visualize the contents of these files by default.
+
+In these cases you can tell Git the encoding of a file in the working
+directory with the `working-tree-encoding` attribute. If a file with this
+attribute is added to Git, then Git reencodes the content from the
+specified encoding to UTF-8. Finally, Git stores the UTF-8 encoded
+content in its internal data structure (called "the index"). On checkout
+the content is reencoded back to the specified encoding.
+
+Please note that using the `working-tree-encoding` attribute may have a
+number of pitfalls:
+
+- Alternative Git implementations (e.g. JGit or libgit2) and older Git
+ versions (as of March 2018) do not support the `working-tree-encoding`
+ attribute. If you decide to use the `working-tree-encoding` attribute
+ in your repository, then it is strongly recommended to ensure that all
+ clients working with the repository support it.
+
+ For example, Microsoft Visual Studio resources files (`*.rc`) or
+ PowerShell script files (`*.ps1`) are sometimes encoded in UTF-16.
+ If you declare `*.ps1` as files as UTF-16 and you add `foo.ps1` with
+ a `working-tree-encoding` enabled Git client, then `foo.ps1` will be
+ stored as UTF-8 internally. A client without `working-tree-encoding`
+ support will checkout `foo.ps1` as UTF-8 encoded file. This will
+ typically cause trouble for the users of this file.
+
+ If a Git client, that does not support the `working-tree-encoding`
+ attribute, adds a new file `bar.ps1`, then `bar.ps1` will be
+ stored "as-is" internally (in this example probably as UTF-16).
+ A client with `working-tree-encoding` support will interpret the
+ internal contents as UTF-8 and try to convert it to UTF-16 on checkout.
+ That operation will fail and cause an error.
+
+- Reencoding content to non-UTF encodings can cause errors as the
+ conversion might not be UTF-8 round trip safe. If you suspect your
+ encoding to not be round trip safe, then add it to
+ `core.checkRoundtripEncoding` to make Git check the round trip
+ encoding (see linkgit:git-config[1]). SHIFT-JIS (Japanese character
+ set) is known to have round trip issues with UTF-8 and is checked by
+ default.
+
+- Reencoding content requires resources that might slow down certain
+ Git operations (e.g 'git checkout' or 'git add').
+
+Use the `working-tree-encoding` attribute only if you cannot store a file
+in UTF-8 encoding and if you want Git to be able to process the content
+as text.
+
+As an example, use the following attributes if your '*.ps1' files are
+UTF-16 encoded with byte order mark (BOM) and you want Git to perform
+automatic line ending conversion based on your platform.
+
+------------------------
+*.ps1 text working-tree-encoding=UTF-16
+------------------------
+
+Use the following attributes if your '*.ps1' files are UTF-16 little
+endian encoded without BOM and you want Git to use Windows line endings
+in the working directory. Please note, it is highly recommended to
+explicitly define the line endings with `eol` if the `working-tree-encoding`
+attribute is used to avoid ambiguity.
+
+------------------------
+*.ps1 text working-tree-encoding=UTF-16LE eol=CRLF
+------------------------
+
+You can get a list of all available encodings on your platform with the
+following command:
+
+------------------------
+iconv --list
+------------------------
+
+If you do not know the encoding of a file, then you can use the `file`
+command to guess the encoding:
+
+------------------------
+file foo.ps1
+------------------------
+
+
`ident`
^^^^^^^
@@ -1141,8 +1229,8 @@ to:
------------
-EXAMPLE
--------
+EXAMPLES
+--------
If you have these three `gitattributes` file:
diff --git a/Documentation/githooks.txt b/Documentation/githooks.txt
index f877f7b..e3c283a 100644
--- a/Documentation/githooks.txt
+++ b/Documentation/githooks.txt
@@ -31,7 +31,7 @@ Hooks can get their arguments via the environment, command-line
arguments, and stdin. See the documentation for each hook below for
details.
-'git init' may copy hooks to the new repository, depending on its
+`git init` may copy hooks to the new repository, depending on its
configuration. See the "TEMPLATE DIRECTORY" section in
linkgit:git-init[1] for details. When the rest of this document refers
to "default hooks" it's talking about the default template shipped
@@ -45,9 +45,9 @@ HOOKS
applypatch-msg
~~~~~~~~~~~~~~
-This hook is invoked by 'git am'. It takes a single
+This hook is invoked by linkgit:git-am[1]. It takes a single
parameter, the name of the file that holds the proposed commit
-log message. Exiting with a non-zero status causes 'git am' to abort
+log message. Exiting with a non-zero status causes `git am` to abort
before applying the patch.
The hook is allowed to edit the message file in place, and can
@@ -61,7 +61,7 @@ The default 'applypatch-msg' hook, when enabled, runs the
pre-applypatch
~~~~~~~~~~~~~~
-This hook is invoked by 'git am'. It takes no parameter, and is
+This hook is invoked by linkgit:git-am[1]. It takes no parameter, and is
invoked after the patch is applied, but before a commit is made.
If it exits with non-zero status, then the working tree will not be
@@ -76,33 +76,33 @@ The default 'pre-applypatch' hook, when enabled, runs the
post-applypatch
~~~~~~~~~~~~~~~
-This hook is invoked by 'git am'. It takes no parameter,
+This hook is invoked by linkgit:git-am[1]. It takes no parameter,
and is invoked after the patch is applied and a commit is made.
This hook is meant primarily for notification, and cannot affect
-the outcome of 'git am'.
+the outcome of `git am`.
pre-commit
~~~~~~~~~~
-This hook is invoked by 'git commit', and can be bypassed
+This hook is invoked by linkgit:git-commit[1], and can be bypassed
with the `--no-verify` option. It takes no parameters, and is
invoked before obtaining the proposed commit log message and
making a commit. Exiting with a non-zero status from this script
-causes the 'git commit' command to abort before creating a commit.
+causes the `git commit` command to abort before creating a commit.
The default 'pre-commit' hook, when enabled, catches introduction
of lines with trailing whitespaces and aborts the commit when
such a line is found.
-All the 'git commit' hooks are invoked with the environment
+All the `git commit` hooks are invoked with the environment
variable `GIT_EDITOR=:` if the command will not bring up an editor
to modify the commit message.
prepare-commit-msg
~~~~~~~~~~~~~~~~~~
-This hook is invoked by 'git commit' right after preparing the
+This hook is invoked by linkgit:git-commit[1] right after preparing the
default log message, and before the editor is started.
It takes one to three parameters. The first is the name of the file
@@ -114,7 +114,7 @@ commit is a merge or a `.git/MERGE_MSG` file exists); `squash`
(if a `.git/SQUASH_MSG` file exists); or `commit`, followed by
a commit SHA-1 (if a `-c`, `-C` or `--amend` option was given).
-If the exit status is non-zero, 'git commit' will abort.
+If the exit status is non-zero, `git commit` will abort.
The purpose of the hook is to edit the message file in place, and
it is not suppressed by the `--no-verify` option. A non-zero exit
@@ -127,7 +127,7 @@ help message found in the commented portion of the commit template.
commit-msg
~~~~~~~~~~
-This hook is invoked by 'git commit' and 'git merge', and can be
+This hook is invoked by linkgit:git-commit[1] and linkgit:git-merge[1], and can be
bypassed with the `--no-verify` option. It takes a single parameter,
the name of the file that holds the proposed commit log message.
Exiting with a non-zero status causes the command to abort.
@@ -143,16 +143,16 @@ The default 'commit-msg' hook, when enabled, detects duplicate
post-commit
~~~~~~~~~~~
-This hook is invoked by 'git commit'. It takes no parameters, and is
+This hook is invoked by linkgit:git-commit[1]. It takes no parameters, and is
invoked after a commit is made.
This hook is meant primarily for notification, and cannot affect
-the outcome of 'git commit'.
+the outcome of `git commit`.
pre-rebase
~~~~~~~~~~
-This hook is called by 'git rebase' and can be used to prevent a
+This hook is called by linkgit:git-rebase[1] and can be used to prevent a
branch from getting rebased. The hook may be called with one or
two parameters. The first parameter is the upstream from which
the series was forked. The second parameter is the branch being
@@ -161,17 +161,17 @@ rebased, and is not set when rebasing the current branch.
post-checkout
~~~~~~~~~~~~~
-This hook is invoked when a 'git checkout' is run after having updated the
+This hook is invoked when a linkgit:git-checkout[1] is run after having updated the
worktree. The hook is given three parameters: the ref of the previous HEAD,
the ref of the new HEAD (which may or may not have changed), and a flag
indicating whether the checkout was a branch checkout (changing branches,
flag=1) or a file checkout (retrieving a file from the index, flag=0).
-This hook cannot affect the outcome of 'git checkout'.
+This hook cannot affect the outcome of `git checkout`.
-It is also run after 'git clone', unless the --no-checkout (-n) option is
+It is also run after linkgit:git-clone[1], unless the `--no-checkout` (`-n`) option is
used. The first parameter given to the hook is the null-ref, the second the
-ref of the new HEAD and the flag is always 1. Likewise for 'git worktree add'
-unless --no-checkout is used.
+ref of the new HEAD and the flag is always 1. Likewise for `git worktree add`
+unless `--no-checkout` is used.
This hook can be used to perform repository validity checks, auto-display
differences from the previous HEAD if different, or set working dir metadata
@@ -180,10 +180,10 @@ properties.
post-merge
~~~~~~~~~~
-This hook is invoked by 'git merge', which happens when a 'git pull'
+This hook is invoked by linkgit:git-merge[1], which happens when a `git pull`
is done on a local repository. The hook takes a single parameter, a status
flag specifying whether or not the merge being done was a squash merge.
-This hook cannot affect the outcome of 'git merge' and is not executed,
+This hook cannot affect the outcome of `git merge` and is not executed,
if the merge failed due to conflicts.
This hook can be used in conjunction with a corresponding pre-commit hook to
@@ -194,10 +194,10 @@ for an example of how to do this.
pre-push
~~~~~~~~
-This hook is called by 'git push' and can be used to prevent a push from taking
-place. The hook is called with two parameters which provide the name and
-location of the destination remote, if a named remote is not being used both
-values will be the same.
+This hook is called by linkgit:git-push[1] and can be used to prevent
+a push from taking place. The hook is called with two parameters
+which provide the name and location of the destination remote, if a
+named remote is not being used both values will be the same.
Information about what is to be pushed is provided on the hook's standard
input with lines of the form:
@@ -216,7 +216,7 @@ SHA-1>` will be 40 `0`. If the local commit was specified by something other
than a name which could be expanded (such as `HEAD~`, or a SHA-1) it will be
supplied as it was originally given.
-If this hook exits with a non-zero status, 'git push' will abort without
+If this hook exits with a non-zero status, `git push` will abort without
pushing anything. Information about why the push is rejected may be sent
to the user by writing to standard error.
@@ -224,8 +224,8 @@ to the user by writing to standard error.
pre-receive
~~~~~~~~~~~
-This hook is invoked by 'git-receive-pack' when it reacts to
-'git push' and updates reference(s) in its repository.
+This hook is invoked by linkgit:git-receive-pack[1] when it reacts to
+`git push` and updates reference(s) in its repository.
Just before starting to update refs on the remote repository, the
pre-receive hook is invoked. Its exit status determines the success
or failure of the update.
@@ -246,7 +246,7 @@ updated. If the hook exits with zero, updating of individual refs can
still be prevented by the <<update,'update'>> hook.
Both standard output and standard error output are forwarded to
-'git send-pack' on the other end, so you can simply `echo` messages
+`git send-pack` on the other end, so you can simply `echo` messages
for the user.
The number of push options given on the command line of
@@ -265,8 +265,8 @@ linkgit:git-receive-pack[1] for some caveats.
update
~~~~~~
-This hook is invoked by 'git-receive-pack' when it reacts to
-'git push' and updates reference(s) in its repository.
+This hook is invoked by linkgit:git-receive-pack[1] when it reacts to
+`git push` and updates reference(s) in its repository.
Just before updating the ref on the remote repository, the update hook
is invoked. Its exit status determines the success or failure of
the ref update.
@@ -279,7 +279,7 @@ three parameters:
- and the new object name to be stored in the ref.
A zero exit from the update hook allows the ref to be updated.
-Exiting with a non-zero status prevents 'git-receive-pack'
+Exiting with a non-zero status prevents `git receive-pack`
from updating that ref.
This hook can be used to prevent 'forced' update on certain refs by
@@ -299,7 +299,7 @@ membership. See linkgit:git-shell[1] for how you might use the login
shell to restrict the user's access to only git commands.
Both standard output and standard error output are forwarded to
-'git send-pack' on the other end, so you can simply `echo` messages
+`git send-pack` on the other end, so you can simply `echo` messages
for the user.
The default 'update' hook, when enabled--and with
@@ -310,8 +310,8 @@ unannotated tags to be pushed.
post-receive
~~~~~~~~~~~~
-This hook is invoked by 'git-receive-pack' when it reacts to
-'git push' and updates reference(s) in its repository.
+This hook is invoked by linkgit:git-receive-pack[1] when it reacts to
+`git push` and updates reference(s) in its repository.
It executes on the remote repository once after all the refs have
been updated.
@@ -320,7 +320,7 @@ arguments, but gets the same information as the
<<pre-receive,'pre-receive'>>
hook does on its standard input.
-This hook does not affect the outcome of 'git-receive-pack', as it
+This hook does not affect the outcome of `git receive-pack`, as it
is called after the real work is done.
This supersedes the <<post-update,'post-update'>> hook in that it gets
@@ -328,7 +328,7 @@ both old and new values of all the refs in addition to their
names.
Both standard output and standard error output are forwarded to
-'git send-pack' on the other end, so you can simply `echo` messages
+`git send-pack` on the other end, so you can simply `echo` messages
for the user.
The default 'post-receive' hook is empty, but there is
@@ -349,8 +349,8 @@ will be set to zero, `GIT_PUSH_OPTION_COUNT=0`.
post-update
~~~~~~~~~~~
-This hook is invoked by 'git-receive-pack' when it reacts to
-'git push' and updates reference(s) in its repository.
+This hook is invoked by linkgit:git-receive-pack[1] when it reacts to
+`git push` and updates reference(s) in its repository.
It executes on the remote repository once after all the refs have
been updated.
@@ -358,7 +358,7 @@ It takes a variable number of parameters, each of which is the
name of ref that was actually updated.
This hook is meant primarily for notification, and cannot affect
-the outcome of 'git-receive-pack'.
+the outcome of `git receive-pack`.
The 'post-update' hook can tell what are the heads that were pushed,
but it does not know what their original and updated values are,
@@ -368,20 +368,20 @@ updated values of the refs. You might consider it instead if you need
them.
When enabled, the default 'post-update' hook runs
-'git update-server-info' to keep the information used by dumb
+`git update-server-info` to keep the information used by dumb
transports (e.g., HTTP) up to date. If you are publishing
a Git repository that is accessible via HTTP, you should
probably enable this hook.
Both standard output and standard error output are forwarded to
-'git send-pack' on the other end, so you can simply `echo` messages
+`git send-pack` on the other end, so you can simply `echo` messages
for the user.
push-to-checkout
~~~~~~~~~~~~~~~~
-This hook is invoked by 'git-receive-pack' when it reacts to
-'git push' and updates reference(s) in its repository, and when
+This hook is invoked by linkgit:git-receive-pack[1] when it reacts to
+`git push` and updates reference(s) in its repository, and when
the push tries to update the branch that is currently checked out
and the `receive.denyCurrentBranch` configuration variable is set to
`updateInstead`. Such a push by default is refused if the working
@@ -400,8 +400,8 @@ when the tip of the current branch is updated to the new commit, and
exit with a zero status.
For example, the hook can simply run `git read-tree -u -m HEAD "$1"`
-in order to emulate 'git fetch' that is run in the reverse direction
-with `git push`, as the two-tree form of `read-tree -u -m` is
+in order to emulate `git fetch` that is run in the reverse direction
+with `git push`, as the two-tree form of `git read-tree -u -m` is
essentially the same as `git checkout` that switches branches while
keeping the local changes in the working tree that do not interfere
with the difference between the branches.
@@ -410,15 +410,16 @@ with the difference between the branches.
pre-auto-gc
~~~~~~~~~~~
-This hook is invoked by 'git gc --auto'. It takes no parameter, and
-exiting with non-zero status from this script causes the 'git gc --auto'
-to abort.
+This hook is invoked by `git gc --auto` (see linkgit:git-gc[1]). It
+takes no parameter, and exiting with non-zero status from this script
+causes the `git gc --auto` to abort.
post-rewrite
~~~~~~~~~~~~
-This hook is invoked by commands that rewrite commits (`git commit
---amend`, 'git-rebase'; currently 'git-filter-branch' does 'not' call
+This hook is invoked by commands that rewrite commits
+(linkgit:git-commit[1] when called with `--amend` and
+linkgit:git-rebase[1]; currently `git filter-branch` does 'not' call
it!). Its first argument denotes the command it was invoked by:
currently one of `amend` or `rebase`. Further command-dependent
arguments may be passed in the future.
@@ -450,16 +451,16 @@ processed by rebase.
sendemail-validate
~~~~~~~~~~~~~~~~~~
-This hook is invoked by 'git send-email'. It takes a single parameter,
+This hook is invoked by linkgit:git-send-email[1]. It takes a single parameter,
the name of the file that holds the e-mail to be sent. Exiting with a
-non-zero status causes 'git send-email' to abort before sending any
+non-zero status causes `git send-email` to abort before sending any
e-mails.
fsmonitor-watchman
~~~~~~~~~~~~~~~~~~
-This hook is invoked when the configuration option core.fsmonitor is
-set to .git/hooks/fsmonitor-watchman. It takes two arguments, a version
+This hook is invoked when the configuration option `core.fsmonitor` is
+set to `.git/hooks/fsmonitor-watchman`. It takes two arguments, a version
(currently 1) and the time in elapsed nanoseconds since midnight,
January 1, 1970.
@@ -478,7 +479,7 @@ directories are checked for untracked files based on the path names
given.
An optimized way to tell git "all files have changed" is to return
-the filename '/'.
+the filename `/`.
The exit status determines whether git will use the data from the
hook to limit its search. On error, it will fall back to verifying
diff --git a/Documentation/gitk.txt b/Documentation/gitk.txt
index ca96c28..244cd01 100644
--- a/Documentation/gitk.txt
+++ b/Documentation/gitk.txt
@@ -8,7 +8,7 @@ gitk - The Git repository browser
SYNOPSIS
--------
[verse]
-'gitk' [<options>] [<revision range>] [\--] [<path>...]
+'gitk' [<options>] [<revision range>] [--] [<path>...]
DESCRIPTION
-----------
diff --git a/Documentation/gitremote-helpers.txt b/Documentation/gitremote-helpers.txt
index 4b8c93e..9d1459a 100644
--- a/Documentation/gitremote-helpers.txt
+++ b/Documentation/gitremote-helpers.txt
@@ -102,6 +102,14 @@ Capabilities for Pushing
+
Supported commands: 'connect'.
+'stateless-connect'::
+ Experimental; for internal use only.
+ Can attempt to connect to a remote server for communication
+ using git's wire-protocol version 2. See the documentation
+ for the stateless-connect command for more information.
++
+Supported commands: 'stateless-connect'.
+
'push'::
Can discover remote refs and push local commits and the
history leading up to them to new or existing remote refs.
@@ -136,6 +144,14 @@ Capabilities for Fetching
+
Supported commands: 'connect'.
+'stateless-connect'::
+ Experimental; for internal use only.
+ Can attempt to connect to a remote server for communication
+ using git's wire-protocol version 2. See the documentation
+ for the stateless-connect command for more information.
++
+Supported commands: 'stateless-connect'.
+
'fetch'::
Can discover remote refs and transfer objects reachable from
them to the local object store.
@@ -375,6 +391,22 @@ Supported if the helper has the "export" capability.
+
Supported if the helper has the "connect" capability.
+'stateless-connect' <service>::
+ Experimental; for internal use only.
+ Connects to the given remote service for communication using
+ git's wire-protocol version 2. Valid replies to this command
+ are empty line (connection established), 'fallback' (no smart
+ transport support, fall back to dumb transports) and just
+ exiting with error message printed (can't connect, don't bother
+ trying to fall back). After line feed terminating the positive
+ (empty) response, the output of the service starts. Messages
+ (both request and response) must consist of zero or more
+ PKT-LINEs, terminating in a flush packet. The client must not
+ expect the server to store any state in between request-response
+ pairs. After the connection ends, the remote helper exits.
++
+Supported if the helper has the "stateless-connect" capability.
+
If a fatal error occurs, the program writes the error message to
stderr and exits. The caller should expect that a suitable error
message has been printed if the child closes the connection without
diff --git a/Documentation/glossary-content.txt b/Documentation/glossary-content.txt
index 6b8888d..6c2d23d 100644
--- a/Documentation/glossary-content.txt
+++ b/Documentation/glossary-content.txt
@@ -463,7 +463,7 @@ exclude;;
[[def_push]]push::
Pushing a <<def_branch,branch>> means to get the branch's
<<def_head_ref,head ref>> from a remote <<def_repository,repository>>,
- find out if it is a direct ancestor to the branch's local
+ find out if it is an ancestor to the branch's local
head ref, and in that case, putting all
objects, which are <<def_reachable,reachable>> from the local
head ref, and which are missing from the remote
diff --git a/Documentation/revisions.txt b/Documentation/revisions.txt
index dfcc49c..7d1bd44 100644
--- a/Documentation/revisions.txt
+++ b/Documentation/revisions.txt
@@ -7,6 +7,10 @@ syntax. Here are various ways to spell object names. The
ones listed near the end of this list name trees and
blobs contained in a commit.
+NOTE: This document shows the "raw" syntax as seen by git. The shell
+and other UIs might require additional quoting to protect special
+characters and to avoid word splitting.
+
'<sha1>', e.g. 'dae86e1950b1277e545cee180551750029cfe735', 'dae86e'::
The full SHA-1 object name (40-byte hexadecimal string), or
a leading substring that is unique within the repository.
@@ -186,6 +190,8 @@ existing tag object.
is matched. ':/!-foo' performs a negative match, while ':/!!foo' matches a
literal '!' character, followed by 'foo'. Any other sequence beginning with
':/!' is reserved for now.
+ Depending on the given text, the shell's word splitting rules might
+ require additional quoting.
'<rev>:<path>', e.g. 'HEAD:README', ':README', 'master:./README'::
A suffix ':' followed by a path names the blob or tree
@@ -345,6 +351,7 @@ Here are a handful of examples using the Loeliger illustration above,
with each step in the notation's expansion and selection carefully
spelt out:
+....
Args Expanded arguments Selected commits
D G H D
D F G H I J D F
@@ -367,3 +374,4 @@ spelt out:
= B ^B^1 ^B^2 ^B^3
= B ^D ^E ^F B
F^! D = F ^I ^J D G H D F
+....
diff --git a/Documentation/technical/api-config.txt b/Documentation/technical/api-config.txt
index 9a778b0..fa39ac9 100644
--- a/Documentation/technical/api-config.txt
+++ b/Documentation/technical/api-config.txt
@@ -47,21 +47,23 @@ will first feed the user-wide one to the callback, and then the
repo-specific one; by overwriting, the higher-priority repo-specific
value is left at the end).
-The `git_config_with_options` function lets the caller examine config
+The `config_with_options` function lets the caller examine config
while adjusting some of the default behavior of `git_config`. It should
almost never be used by "regular" Git code that is looking up
configuration variables. It is intended for advanced callers like
`git-config`, which are intentionally tweaking the normal config-lookup
process. It takes two extra parameters:
-`filename`::
-If this parameter is non-NULL, it specifies the name of a file to
-parse for configuration, rather than looking in the usual files. Regular
-`git_config` defaults to `NULL`.
+`config_source`::
+If this parameter is non-NULL, it specifies the source to parse for
+configuration, rather than looking in the usual files. See `struct
+git_config_source` in `config.h` for details. Regular `git_config` defaults
+to `NULL`.
-`respect_includes`::
-Specify whether include directives should be followed in parsed files.
-Regular `git_config` defaults to `1`.
+`opts`::
+Specify options to adjust the behavior of parsing config files. See `struct
+config_options` in `config.h` for details. As an example: regular `git_config`
+sets `opts.respect_includes` to `1` by default.
Reading Specific Files
----------------------
diff --git a/Documentation/technical/api-directory-listing.txt b/Documentation/technical/api-directory-listing.txt
index 7fae00f..4f44ca2 100644
--- a/Documentation/technical/api-directory-listing.txt
+++ b/Documentation/technical/api-directory-listing.txt
@@ -53,7 +53,7 @@ The notable options are:
not be returned even if all of its contents are ignored. In
this case, the contents are returned as individual entries.
+
-If this is set, files and directories that explicity match an ignore
+If this is set, files and directories that explicitly match an ignore
pattern are reported. Implicity ignored directories (directories that
do not match an ignore pattern, but whose contents are all ignored)
are not reported, instead all of the contents are reported.
diff --git a/Documentation/technical/api-object-access.txt b/Documentation/technical/api-object-access.txt
index a1162e5..5b29622 100644
--- a/Documentation/technical/api-object-access.txt
+++ b/Documentation/technical/api-object-access.txt
@@ -1,7 +1,7 @@
object access API
=================
-Talk about <sha1_file.c> and <object.h> family, things like
+Talk about <sha1-file.c> and <object.h> family, things like
* read_sha1_file()
* read_object_with_reference()
diff --git a/Documentation/technical/api-oid-array.txt b/Documentation/technical/api-oid-array.txt
index b0c11f8..9febfb1 100644
--- a/Documentation/technical/api-oid-array.txt
+++ b/Documentation/technical/api-oid-array.txt
@@ -35,13 +35,18 @@ Functions
Free all memory associated with the array and return it to the
initial, empty state.
+`oid_array_for_each`::
+ Iterate over each element of the list, executing the callback
+ function for each one. Does not sort the list, so any custom
+ hash order is retained. If the callback returns a non-zero
+ value, the iteration ends immediately and the callback's
+ return is propagated; otherwise, 0 is returned.
+
`oid_array_for_each_unique`::
- Efficiently iterate over each unique element of the list,
- executing the callback function for each one. If the array is
- not sorted, this function has the side effect of sorting it. If
- the callback returns a non-zero value, the iteration ends
- immediately and the callback's return is propagated; otherwise,
- 0 is returned.
+ Iterate over each unique element of the list in sorted order,
+ but otherwise behave like `oid_array_for_each`. If the array
+ is not sorted, this function has the side effect of sorting
+ it.
Examples
--------
diff --git a/Documentation/technical/api-submodule-config.txt b/Documentation/technical/api-submodule-config.txt
index ee907c4..fb06089 100644
--- a/Documentation/technical/api-submodule-config.txt
+++ b/Documentation/technical/api-submodule-config.txt
@@ -38,7 +38,7 @@ Data Structures
Functions
---------
-`void submodule_free()`::
+`void submodule_free(struct repository *r)`::
Use these to free the internally cached values.
diff --git a/Documentation/technical/commit-graph-format.txt b/Documentation/technical/commit-graph-format.txt
new file mode 100644
index 0000000..ad6af81
--- /dev/null
+++ b/Documentation/technical/commit-graph-format.txt
@@ -0,0 +1,97 @@
+Git commit graph format
+=======================
+
+The Git commit graph stores a list of commit OIDs and some associated
+metadata, including:
+
+- The generation number of the commit. Commits with no parents have
+ generation number 1; commits with parents have generation number
+ one more than the maximum generation number of its parents. We
+ reserve zero as special, and can be used to mark a generation
+ number invalid or as "not computed".
+
+- The root tree OID.
+
+- The commit date.
+
+- The parents of the commit, stored using positional references within
+ the graph file.
+
+These positional references are stored as unsigned 32-bit integers
+corresponding to the array position withing the list of commit OIDs. We
+use the most-significant bit for special purposes, so we can store at most
+(1 << 31) - 1 (around 2 billion) commits.
+
+== Commit graph files have the following format:
+
+In order to allow extensions that add extra data to the graph, we organize
+the body into "chunks" and provide a binary lookup table at the beginning
+of the body. The header includes certain values, such as number of chunks
+and hash type.
+
+All 4-byte numbers are in network order.
+
+HEADER:
+
+ 4-byte signature:
+ The signature is: {'C', 'G', 'P', 'H'}
+
+ 1-byte version number:
+ Currently, the only valid version is 1.
+
+ 1-byte Hash Version (1 = SHA-1)
+ We infer the hash length (H) from this value.
+
+ 1-byte number (C) of "chunks"
+
+ 1-byte (reserved for later use)
+ Current clients should ignore this value.
+
+CHUNK LOOKUP:
+
+ (C + 1) * 12 bytes listing the table of contents for the chunks:
+ First 4 bytes describe the chunk id. Value 0 is a terminating label.
+ Other 8 bytes provide the byte-offset in current file for chunk to
+ start. (Chunks are ordered contiguously in the file, so you can infer
+ the length using the next chunk position if necessary.) Each chunk
+ ID appears at most once.
+
+ The remaining data in the body is described one chunk at a time, and
+ these chunks may be given in any order. Chunks are required unless
+ otherwise specified.
+
+CHUNK DATA:
+
+ OID Fanout (ID: {'O', 'I', 'D', 'F'}) (256 * 4 bytes)
+ The ith entry, F[i], stores the number of OIDs with first
+ byte at most i. Thus F[255] stores the total
+ number of commits (N).
+
+ OID Lookup (ID: {'O', 'I', 'D', 'L'}) (N * H bytes)
+ The OIDs for all commits in the graph, sorted in ascending order.
+
+ Commit Data (ID: {'C', 'G', 'E', 'T' }) (N * (H + 16) bytes)
+ * The first H bytes are for the OID of the root tree.
+ * The next 8 bytes are for the positions of the first two parents
+ of the ith commit. Stores value 0xffffffff if no parent in that
+ position. If there are more than two parents, the second value
+ has its most-significant bit on and the other bits store an array
+ position into the Large Edge List chunk.
+ * The next 8 bytes store the generation number of the commit and
+ the commit time in seconds since EPOCH. The generation number
+ uses the higher 30 bits of the first 4 bytes, while the commit
+ time uses the 32 bits of the second 4 bytes, along with the lowest
+ 2 bits of the lowest byte, storing the 33rd and 34th bit of the
+ commit time.
+
+ Large Edge List (ID: {'E', 'D', 'G', 'E'}) [Optional]
+ This list of 4-byte values store the second through nth parents for
+ all octopus merges. The second parent value in the commit data stores
+ an array position within this list along with the most-significant bit
+ on. Starting at that array position, iterate through this list of commit
+ positions for the parents until reaching a value with the most-significant
+ bit on. The other bits correspond to the position of the last parent.
+
+TRAILER:
+
+ H-byte HASH-checksum of all of the above.
diff --git a/Documentation/technical/commit-graph.txt b/Documentation/technical/commit-graph.txt
new file mode 100644
index 0000000..0550c6d
--- /dev/null
+++ b/Documentation/technical/commit-graph.txt
@@ -0,0 +1,163 @@
+Git Commit Graph Design Notes
+=============================
+
+Git walks the commit graph for many reasons, including:
+
+1. Listing and filtering commit history.
+2. Computing merge bases.
+
+These operations can become slow as the commit count grows. The merge
+base calculation shows up in many user-facing commands, such as 'merge-base'
+or 'status' and can take minutes to compute depending on history shape.
+
+There are two main costs here:
+
+1. Decompressing and parsing commits.
+2. Walking the entire graph to satisfy topological order constraints.
+
+The commit graph file is a supplemental data structure that accelerates
+commit graph walks. If a user downgrades or disables the 'core.commitGraph'
+config setting, then the existing ODB is sufficient. The file is stored
+as "commit-graph" either in the .git/objects/info directory or in the info
+directory of an alternate.
+
+The commit graph file stores the commit graph structure along with some
+extra metadata to speed up graph walks. By listing commit OIDs in lexi-
+cographic order, we can identify an integer position for each commit and
+refer to the parents of a commit using those integer positions. We use
+binary search to find initial commits and then use the integer positions
+for fast lookups during the walk.
+
+A consumer may load the following info for a commit from the graph:
+
+1. The commit OID.
+2. The list of parents, along with their integer position.
+3. The commit date.
+4. The root tree OID.
+5. The generation number (see definition below).
+
+Values 1-4 satisfy the requirements of parse_commit_gently().
+
+Define the "generation number" of a commit recursively as follows:
+
+ * A commit with no parents (a root commit) has generation number one.
+
+ * A commit with at least one parent has generation number one more than
+ the largest generation number among its parents.
+
+Equivalently, the generation number of a commit A is one more than the
+length of a longest path from A to a root commit. The recursive definition
+is easier to use for computation and observing the following property:
+
+ If A and B are commits with generation numbers N and M, respectively,
+ and N <= M, then A cannot reach B. That is, we know without searching
+ that B is not an ancestor of A because it is further from a root commit
+ than A.
+
+ Conversely, when checking if A is an ancestor of B, then we only need
+ to walk commits until all commits on the walk boundary have generation
+ number at most N. If we walk commits using a priority queue seeded by
+ generation numbers, then we always expand the boundary commit with highest
+ generation number and can easily detect the stopping condition.
+
+This property can be used to significantly reduce the time it takes to
+walk commits and determine topological relationships. Without generation
+numbers, the general heuristic is the following:
+
+ If A and B are commits with commit time X and Y, respectively, and
+ X < Y, then A _probably_ cannot reach B.
+
+This heuristic is currently used whenever the computation is allowed to
+violate topological relationships due to clock skew (such as "git log"
+with default order), but is not used when the topological order is
+required (such as merge base calculations, "git log --graph").
+
+In practice, we expect some commits to be created recently and not stored
+in the commit graph. We can treat these commits as having "infinite"
+generation number and walk until reaching commits with known generation
+number.
+
+Design Details
+--------------
+
+- The commit graph file is stored in a file named 'commit-graph' in the
+ .git/objects/info directory. This could be stored in the info directory
+ of an alternate.
+
+- The core.commitGraph config setting must be on to consume graph files.
+
+- The file format includes parameters for the object ID hash function,
+ so a future change of hash algorithm does not require a change in format.
+
+Future Work
+-----------
+
+- The commit graph feature currently does not honor commit grafts. This can
+ be remedied by duplicating or refactoring the current graft logic.
+
+- The 'commit-graph' subcommand does not have a "verify" mode that is
+ necessary for integration with fsck.
+
+- The file format includes room for precomputed generation numbers. These
+ are not currently computed, so all generation numbers will be marked as
+ 0 (or "uncomputed"). A later patch will include this calculation.
+
+- After computing and storing generation numbers, we must make graph
+ walks aware of generation numbers to gain the performance benefits they
+ enable. This will mostly be accomplished by swapping a commit-date-ordered
+ priority queue with one ordered by generation number. The following
+ operations are important candidates:
+
+ - paint_down_to_common()
+ - 'log --topo-order'
+
+- Currently, parse_commit_gently() requires filling in the root tree
+ object for a commit. This passes through lookup_tree() and consequently
+ lookup_object(). Also, it calls lookup_commit() when loading the parents.
+ These method calls check the ODB for object existence, even if the
+ consumer does not need the content. For example, we do not need the
+ tree contents when computing merge bases. Now that commit parsing is
+ removed from the computation time, these lookup operations are the
+ slowest operations keeping graph walks from being fast. Consider
+ loading these objects without verifying their existence in the ODB and
+ only loading them fully when consumers need them. Consider a method
+ such as "ensure_tree_loaded(commit)" that fully loads a tree before
+ using commit->tree.
+
+- The current design uses the 'commit-graph' subcommand to generate the graph.
+ When this feature stabilizes enough to recommend to most users, we should
+ add automatic graph writes to common operations that create many commits.
+ For example, one could compute a graph on 'clone', 'fetch', or 'repack'
+ commands.
+
+- A server could provide a commit graph file as part of the network protocol
+ to avoid extra calculations by clients. This feature is only of benefit if
+ the user is willing to trust the file, because verifying the file is correct
+ is as hard as computing it from scratch.
+
+Related Links
+-------------
+[0] https://bugs.chromium.org/p/git/issues/detail?id=8
+ Chromium work item for: Serialized Commit Graph
+
+[1] https://public-inbox.org/git/20110713070517.GC18566@sigill.intra.peff.net/
+ An abandoned patch that introduced generation numbers.
+
+[2] https://public-inbox.org/git/20170908033403.q7e6dj7benasrjes@sigill.intra.peff.net/
+ Discussion about generation numbers on commits and how they interact
+ with fsck.
+
+[3] https://public-inbox.org/git/20170908034739.4op3w4f2ma5s65ku@sigill.intra.peff.net/
+ More discussion about generation numbers and not storing them inside
+ commit objects. A valuable quote:
+
+ "I think we should be moving more in the direction of keeping
+ repo-local caches for optimizations. Reachability bitmaps have been
+ a big performance win. I think we should be doing the same with our
+ properties of commits. Not just generation numbers, but making it
+ cheap to access the graph structure without zlib-inflating whole
+ commit objects (i.e., packv4 or something like the "metapacks" I
+ proposed a few years ago)."
+
+[4] https://public-inbox.org/git/20180108154822.54829-1-git@jeffhostetler.com/T/#u
+ A patch to remove the ahead-behind calculation from 'status'.
diff --git a/Documentation/technical/pack-format.txt b/Documentation/technical/pack-format.txt
index 8e5bf60..70a99fd 100644
--- a/Documentation/technical/pack-format.txt
+++ b/Documentation/technical/pack-format.txt
@@ -36,6 +36,98 @@ Git pack format
- The trailer records 20-byte SHA-1 checksum of all of the above.
+=== Object types
+
+Valid object types are:
+
+- OBJ_COMMIT (1)
+- OBJ_TREE (2)
+- OBJ_BLOB (3)
+- OBJ_TAG (4)
+- OBJ_OFS_DELTA (6)
+- OBJ_REF_DELTA (7)
+
+Type 5 is reserved for future expansion. Type 0 is invalid.
+
+=== Deltified representation
+
+Conceptually there are only four object types: commit, tree, tag and
+blob. However to save space, an object could be stored as a "delta" of
+another "base" object. These representations are assigned new types
+ofs-delta and ref-delta, which is only valid in a pack file.
+
+Both ofs-delta and ref-delta store the "delta" to be applied to
+another object (called 'base object') to reconstruct the object. The
+difference between them is, ref-delta directly encodes 20-byte base
+object name. If the base object is in the same pack, ofs-delta encodes
+the offset of the base object in the pack instead.
+
+The base object could also be deltified if it's in the same pack.
+Ref-delta can also refer to an object outside the pack (i.e. the
+so-called "thin pack"). When stored on disk however, the pack should
+be self contained to avoid cyclic dependency.
+
+The delta data is a sequence of instructions to reconstruct an object
+from the base object. If the base object is deltified, it must be
+converted to canonical form first. Each instruction appends more and
+more data to the target object until it's complete. There are two
+supported instructions so far: one for copy a byte range from the
+source object and one for inserting new data embedded in the
+instruction itself.
+
+Each instruction has variable length. Instruction type is determined
+by the seventh bit of the first octet. The following diagrams follow
+the convention in RFC 1951 (Deflate compressed data format).
+
+==== Instruction to copy from base object
+
+ +----------+---------+---------+---------+---------+-------+-------+-------+
+ | 1xxxxxxx | offset1 | offset2 | offset3 | offset4 | size1 | size2 | size3 |
+ +----------+---------+---------+---------+---------+-------+-------+-------+
+
+This is the instruction format to copy a byte range from the source
+object. It encodes the offset to copy from and the number of bytes to
+copy. Offset and size are in little-endian order.
+
+All offset and size bytes are optional. This is to reduce the
+instruction size when encoding small offsets or sizes. The first seven
+bits in the first octet determines which of the next seven octets is
+present. If bit zero is set, offset1 is present. If bit one is set
+offset2 is present and so on.
+
+Note that a more compact instruction does not change offset and size
+encoding. For example, if only offset2 is omitted like below, offset3
+still contains bits 16-23. It does not become offset2 and contains
+bits 8-15 even if it's right next to offset1.
+
+ +----------+---------+---------+
+ | 10000101 | offset1 | offset3 |
+ +----------+---------+---------+
+
+In its most compact form, this instruction only takes up one byte
+(0x80) with both offset and size omitted, which will have default
+values zero. There is another exception: size zero is automatically
+converted to 0x10000.
+
+==== Instruction to add new data
+
+ +----------+============+
+ | 0xxxxxxx | data |
+ +----------+============+
+
+This is the instruction to construct target object without the base
+object. The following data is appended to the target object. The first
+seven bits of the first octet determines the size of data in
+bytes. The size must be non-zero.
+
+==== Reserved instruction
+
+ +----------+============
+ | 00000000 |
+ +----------+============
+
+This is the instruction reserved for future expansion.
+
== Original (version 1) pack-*.idx files have the following format:
- The header consists of 256 4-byte network byte order
diff --git a/Documentation/technical/protocol-v2.txt b/Documentation/technical/protocol-v2.txt
new file mode 100644
index 0000000..49bda76
--- /dev/null
+++ b/Documentation/technical/protocol-v2.txt
@@ -0,0 +1,414 @@
+ Git Wire Protocol, Version 2
+==============================
+
+This document presents a specification for a version 2 of Git's wire
+protocol. Protocol v2 will improve upon v1 in the following ways:
+
+ * Instead of multiple service names, multiple commands will be
+ supported by a single service
+ * Easily extendable as capabilities are moved into their own section
+ of the protocol, no longer being hidden behind a NUL byte and
+ limited by the size of a pkt-line
+ * Separate out other information hidden behind NUL bytes (e.g. agent
+ string as a capability and symrefs can be requested using 'ls-refs')
+ * Reference advertisement will be omitted unless explicitly requested
+ * ls-refs command to explicitly request some refs
+ * Designed with http and stateless-rpc in mind. With clear flush
+ semantics the http remote helper can simply act as a proxy
+
+In protocol v2 communication is command oriented. When first contacting a
+server a list of capabilities will advertised. Some of these capabilities
+will be commands which a client can request be executed. Once a command
+has completed, a client can reuse the connection and request that other
+commands be executed.
+
+ Packet-Line Framing
+---------------------
+
+All communication is done using packet-line framing, just as in v1. See
+`Documentation/technical/pack-protocol.txt` and
+`Documentation/technical/protocol-common.txt` for more information.
+
+In protocol v2 these special packets will have the following semantics:
+
+ * '0000' Flush Packet (flush-pkt) - indicates the end of a message
+ * '0001' Delimiter Packet (delim-pkt) - separates sections of a message
+
+ Initial Client Request
+------------------------
+
+In general a client can request to speak protocol v2 by sending
+`version=2` through the respective side-channel for the transport being
+used which inevitably sets `GIT_PROTOCOL`. More information can be
+found in `pack-protocol.txt` and `http-protocol.txt`. In all cases the
+response from the server is the capability advertisement.
+
+ Git Transport
+~~~~~~~~~~~~~~~
+
+When using the git:// transport, you can request to use protocol v2 by
+sending "version=2" as an extra parameter:
+
+ 003egit-upload-pack /project.git\0host=myserver.com\0\0version=2\0
+
+ SSH and File Transport
+~~~~~~~~~~~~~~~~~~~~~~~~
+
+When using either the ssh:// or file:// transport, the GIT_PROTOCOL
+environment variable must be set explicitly to include "version=2".
+
+ HTTP Transport
+~~~~~~~~~~~~~~~~
+
+When using the http:// or https:// transport a client makes a "smart"
+info/refs request as described in `http-protocol.txt` and requests that
+v2 be used by supplying "version=2" in the `Git-Protocol` header.
+
+ C: Git-Protocol: version=2
+ C:
+ C: GET $GIT_URL/info/refs?service=git-upload-pack HTTP/1.0
+
+A v2 server would reply:
+
+ S: 200 OK
+ S: <Some headers>
+ S: ...
+ S:
+ S: 000eversion 2\n
+ S: <capability-advertisement>
+
+Subsequent requests are then made directly to the service
+`$GIT_URL/git-upload-pack`. (This works the same for git-receive-pack).
+
+ Capability Advertisement
+--------------------------
+
+A server which decides to communicate (based on a request from a client)
+using protocol version 2, notifies the client by sending a version string
+in its initial response followed by an advertisement of its capabilities.
+Each capability is a key with an optional value. Clients must ignore all
+unknown keys. Semantics of unknown values are left to the definition of
+each key. Some capabilities will describe commands which can be requested
+to be executed by the client.
+
+ capability-advertisement = protocol-version
+ capability-list
+ flush-pkt
+
+ protocol-version = PKT-LINE("version 2" LF)
+ capability-list = *capability
+ capability = PKT-LINE(key[=value] LF)
+
+ key = 1*(ALPHA | DIGIT | "-_")
+ value = 1*(ALPHA | DIGIT | " -_.,?\/{}[]()<>!@#$%^&*+=:;")
+
+ Command Request
+-----------------
+
+After receiving the capability advertisement, a client can then issue a
+request to select the command it wants with any particular capabilities
+or arguments. There is then an optional section where the client can
+provide any command specific parameters or queries. Only a single
+command can be requested at a time.
+
+ request = empty-request | command-request
+ empty-request = flush-pkt
+ command-request = command
+ capability-list
+ [command-args]
+ flush-pkt
+ command = PKT-LINE("command=" key LF)
+ command-args = delim-pkt
+ *command-specific-arg
+
+ command-specific-args are packet line framed arguments defined by
+ each individual command.
+
+The server will then check to ensure that the client's request is
+comprised of a valid command as well as valid capabilities which were
+advertised. If the request is valid the server will then execute the
+command. A server MUST wait till it has received the client's entire
+request before issuing a response. The format of the response is
+determined by the command being executed, but in all cases a flush-pkt
+indicates the end of the response.
+
+When a command has finished, and the client has received the entire
+response from the server, a client can either request that another
+command be executed or can terminate the connection. A client may
+optionally send an empty request consisting of just a flush-pkt to
+indicate that no more requests will be made.
+
+ Capabilities
+--------------
+
+There are two different types of capabilities: normal capabilities,
+which can be used to to convey information or alter the behavior of a
+request, and commands, which are the core actions that a client wants to
+perform (fetch, push, etc).
+
+Protocol version 2 is stateless by default. This means that all commands
+must only last a single round and be stateless from the perspective of the
+server side, unless the client has requested a capability indicating that
+state should be maintained by the server. Clients MUST NOT require state
+management on the server side in order to function correctly. This
+permits simple round-robin load-balancing on the server side, without
+needing to worry about state management.
+
+ agent
+~~~~~~~
+
+The server can advertise the `agent` capability with a value `X` (in the
+form `agent=X`) to notify the client that the server is running version
+`X`. The client may optionally send its own agent string by including
+the `agent` capability with a value `Y` (in the form `agent=Y`) in its
+request to the server (but it MUST NOT do so if the server did not
+advertise the agent capability). The `X` and `Y` strings may contain any
+printable ASCII characters except space (i.e., the byte range 32 < x <
+127), and are typically of the form "package/version" (e.g.,
+"git/1.8.3.1"). The agent strings are purely informative for statistics
+and debugging purposes, and MUST NOT be used to programmatically assume
+the presence or absence of particular features.
+
+ ls-refs
+~~~~~~~~~
+
+`ls-refs` is the command used to request a reference advertisement in v2.
+Unlike the current reference advertisement, ls-refs takes in arguments
+which can be used to limit the refs sent from the server.
+
+Additional features not supported in the base command will be advertised
+as the value of the command in the capability advertisement in the form
+of a space separated list of features: "<command>=<feature 1> <feature 2>"
+
+ls-refs takes in the following arguments:
+
+ symrefs
+ In addition to the object pointed by it, show the underlying ref
+ pointed by it when showing a symbolic ref.
+ peel
+ Show peeled tags.
+ ref-prefix <prefix>
+ When specified, only references having a prefix matching one of
+ the provided prefixes are displayed.
+
+The output of ls-refs is as follows:
+
+ output = *ref
+ flush-pkt
+ ref = PKT-LINE(obj-id SP refname *(SP ref-attribute) LF)
+ ref-attribute = (symref | peeled)
+ symref = "symref-target:" symref-target
+ peeled = "peeled:" obj-id
+
+ fetch
+~~~~~~~
+
+`fetch` is the command used to fetch a packfile in v2. It can be looked
+at as a modified version of the v1 fetch where the ref-advertisement is
+stripped out (since the `ls-refs` command fills that role) and the
+message format is tweaked to eliminate redundancies and permit easy
+addition of future extensions.
+
+Additional features not supported in the base command will be advertised
+as the value of the command in the capability advertisement in the form
+of a space separated list of features: "<command>=<feature 1> <feature 2>"
+
+A `fetch` request can take the following arguments:
+
+ want <oid>
+ Indicates to the server an object which the client wants to
+ retrieve. Wants can be anything and are not limited to
+ advertised objects.
+
+ have <oid>
+ Indicates to the server an object which the client has locally.
+ This allows the server to make a packfile which only contains
+ the objects that the client needs. Multiple 'have' lines can be
+ supplied.
+
+ done
+ Indicates to the server that negotiation should terminate (or
+ not even begin if performing a clone) and that the server should
+ use the information supplied in the request to construct the
+ packfile.
+
+ thin-pack
+ Request that a thin pack be sent, which is a pack with deltas
+ which reference base objects not contained within the pack (but
+ are known to exist at the receiving end). This can reduce the
+ network traffic significantly, but it requires the receiving end
+ to know how to "thicken" these packs by adding the missing bases
+ to the pack.
+
+ no-progress
+ Request that progress information that would normally be sent on
+ side-band channel 2, during the packfile transfer, should not be
+ sent. However, the side-band channel 3 is still used for error
+ responses.
+
+ include-tag
+ Request that annotated tags should be sent if the objects they
+ point to are being sent.
+
+ ofs-delta
+ Indicate that the client understands PACKv2 with delta referring
+ to its base by position in pack rather than by an oid. That is,
+ they can read OBJ_OFS_DELTA (ake type 6) in a packfile.
+
+If the 'shallow' feature is advertised the following arguments can be
+included in the clients request as well as the potential addition of the
+'shallow-info' section in the server's response as explained below.
+
+ shallow <oid>
+ A client must notify the server of all commits for which it only
+ has shallow copies (meaning that it doesn't have the parents of
+ a commit) by supplying a 'shallow <oid>' line for each such
+ object so that the server is aware of the limitations of the
+ client's history. This is so that the server is aware that the
+ client may not have all objects reachable from such commits.
+
+ deepen <depth>
+ Requests that the fetch/clone should be shallow having a commit
+ depth of <depth> relative to the remote side.
+
+ deepen-relative
+ Requests that the semantics of the "deepen" command be changed
+ to indicate that the depth requested is relative to the client's
+ current shallow boundary, instead of relative to the requested
+ commits.
+
+ deepen-since <timestamp>
+ Requests that the shallow clone/fetch should be cut at a
+ specific time, instead of depth. Internally it's equivalent to
+ doing "git rev-list --max-age=<timestamp>". Cannot be used with
+ "deepen".
+
+ deepen-not <rev>
+ Requests that the shallow clone/fetch should be cut at a
+ specific revision specified by '<rev>', instead of a depth.
+ Internally it's equivalent of doing "git rev-list --not <rev>".
+ Cannot be used with "deepen", but can be used with
+ "deepen-since".
+
+If the 'filter' feature is advertised, the following argument can be
+included in the client's request:
+
+ filter <filter-spec>
+ Request that various objects from the packfile be omitted
+ using one of several filtering techniques. These are intended
+ for use with partial clone and partial fetch operations. See
+ `rev-list` for possible "filter-spec" values.
+
+The response of `fetch` is broken into a number of sections separated by
+delimiter packets (0001), with each section beginning with its section
+header.
+
+ output = *section
+ section = (acknowledgments | shallow-info | packfile)
+ (flush-pkt | delim-pkt)
+
+ acknowledgments = PKT-LINE("acknowledgments" LF)
+ (nak | *ack)
+ (ready)
+ ready = PKT-LINE("ready" LF)
+ nak = PKT-LINE("NAK" LF)
+ ack = PKT-LINE("ACK" SP obj-id LF)
+
+ shallow-info = PKT-LINE("shallow-info" LF)
+ *PKT-LINE((shallow | unshallow) LF)
+ shallow = "shallow" SP obj-id
+ unshallow = "unshallow" SP obj-id
+
+ packfile = PKT-LINE("packfile" LF)
+ *PKT-LINE(%x01-03 *%x00-ff)
+
+ acknowledgments section
+ * If the client determines that it is finished with negotiations
+ by sending a "done" line, the acknowledgments sections MUST be
+ omitted from the server's response.
+
+ * Always begins with the section header "acknowledgments"
+
+ * The server will respond with "NAK" if none of the object ids sent
+ as have lines were common.
+
+ * The server will respond with "ACK obj-id" for all of the
+ object ids sent as have lines which are common.
+
+ * A response cannot have both "ACK" lines as well as a "NAK"
+ line.
+
+ * The server will respond with a "ready" line indicating that
+ the server has found an acceptable common base and is ready to
+ make and send a packfile (which will be found in the packfile
+ section of the same response)
+
+ * If the server has found a suitable cut point and has decided
+ to send a "ready" line, then the server can decide to (as an
+ optimization) omit any "ACK" lines it would have sent during
+ its response. This is because the server will have already
+ determined the objects it plans to send to the client and no
+ further negotiation is needed.
+
+ shallow-info section
+ * If the client has requested a shallow fetch/clone, a shallow
+ client requests a fetch or the server is shallow then the
+ server's response may include a shallow-info section. The
+ shallow-info section will be included if (due to one of the
+ above conditions) the server needs to inform the client of any
+ shallow boundaries or adjustments to the clients already
+ existing shallow boundaries.
+
+ * Always begins with the section header "shallow-info"
+
+ * If a positive depth is requested, the server will compute the
+ set of commits which are no deeper than the desired depth.
+
+ * The server sends a "shallow obj-id" line for each commit whose
+ parents will not be sent in the following packfile.
+
+ * The server sends an "unshallow obj-id" line for each commit
+ which the client has indicated is shallow, but is no longer
+ shallow as a result of the fetch (due to its parents being
+ sent in the following packfile).
+
+ * The server MUST NOT send any "unshallow" lines for anything
+ which the client has not indicated was shallow as a part of
+ its request.
+
+ * This section is only included if a packfile section is also
+ included in the response.
+
+ packfile section
+ * This section is only included if the client has sent 'want'
+ lines in its request and either requested that no more
+ negotiation be done by sending 'done' or if the server has
+ decided it has found a sufficient cut point to produce a
+ packfile.
+
+ * Always begins with the section header "packfile"
+
+ * The transmission of the packfile begins immediately after the
+ section header
+
+ * The data transfer of the packfile is always multiplexed, using
+ the same semantics of the 'side-band-64k' capability from
+ protocol version 1. This means that each packet, during the
+ packfile data stream, is made up of a leading 4-byte pkt-line
+ length (typical of the pkt-line format), followed by a 1-byte
+ stream code, followed by the actual data.
+
+ The stream code can be one of:
+ 1 - pack data
+ 2 - progress messages
+ 3 - fatal error message just before stream aborts
+
+ server-option
+~~~~~~~~~~~~~~~
+
+If advertised, indicates that any number of server specific options can be
+included in a request. This is done by sending each option as a
+"server-option=<option>" capability line in the capability-list section of
+a request.
+
+The provided options must not contain a NUL or LF character.
diff --git a/Documentation/technical/shallow.txt b/Documentation/technical/shallow.txt
index 5183b15..01dedfe 100644
--- a/Documentation/technical/shallow.txt
+++ b/Documentation/technical/shallow.txt
@@ -8,20 +8,22 @@ repo, and therefore grafts are introduced pretending that
these commits have no parents.
*********************************************************
-The basic idea is to write the SHA-1s of shallow commits into
-$GIT_DIR/shallow, and handle its contents like the contents
-of $GIT_DIR/info/grafts (with the difference that shallow
-cannot contain parent information).
-
-This information is stored in a new file instead of grafts, or
-even the config, since the user should not touch that file
-at all (even throughout development of the shallow clone, it
-was never manually edited!).
+$GIT_DIR/shallow lists commit object names and tells Git to
+pretend as if they are root commits (e.g. "git log" traversal
+stops after showing them; "git fsck" does not complain saying
+the commits listed on their "parent" lines do not exist).
Each line contains exactly one SHA-1. When read, a commit_graft
will be constructed, which has nr_parent < 0 to make it easier
to discern from user provided grafts.
+Note that the shallow feature could not be changed easily to
+use replace refs: a commit containing a `mergetag` is not allowed
+to be replaced, not even by a root commit. Such a commit can be
+made shallow, though. Also, having a `shallow` file explicitly
+listing all the commits made shallow makes it a *lot* easier to
+do shallow-specific things such as to deepen the history.
+
Since fsck-objects relies on the library to read the objects,
it honours shallow commits automatically.
diff --git a/Makefile b/Makefile
index f181687..4bca653 100644
--- a/Makefile
+++ b/Makefile
@@ -441,6 +441,49 @@ all::
#
# When cross-compiling, define HOST_CPU as the canonical name of the CPU on
# which the built Git will run (for instance "x86_64").
+#
+# Define RUNTIME_PREFIX to configure Git to resolve its ancillary tooling and
+# support files relative to the location of the runtime binary, rather than
+# hard-coding them into the binary. Git installations built with RUNTIME_PREFIX
+# can be moved to arbitrary filesystem locations. RUNTIME_PREFIX also causes
+# Perl scripts to use a modified entry point header allowing them to resolve
+# support files at runtime.
+#
+# When using RUNTIME_PREFIX, define HAVE_BSD_KERN_PROC_SYSCTL if your platform
+# supports the KERN_PROC BSD sysctl function.
+#
+# When using RUNTIME_PREFIX, define PROCFS_EXECUTABLE_PATH if your platform
+# mounts a "procfs" filesystem capable of resolving the path of the current
+# executable. If defined, this must be the canonical path for the "procfs"
+# current executable path.
+#
+# When using RUNTIME_PREFIX, define HAVE_NS_GET_EXECUTABLE_PATH if your platform
+# supports calling _NSGetExecutablePath to retrieve the path of the running
+# executable.
+#
+# When using RUNTIME_PREFIX, define HAVE_WPGMPTR if your platform offers
+# the global variable _wpgmptr containing the absolute path of the current
+# executable (this is the case on Windows).
+#
+# Define DEVELOPER to enable more compiler warnings. Compiler version
+# and family are auto detected, but could be overridden by defining
+# COMPILER_FEATURES (see config.mak.dev)
+#
+# When DEVELOPER is set, DEVOPTS can be used to control compiler
+# options. This variable contains keywords separated by
+# whitespace. The following keywords are are recognized:
+#
+# no-error:
+#
+# suppresses the -Werror that implicitly comes with
+# DEVELOPER=1. Useful for getting the full set of errors
+# without immediately dying, or for logging them.
+#
+# extra-all:
+#
+# The DEVELOPER mode enables -Wextra with a few exceptions. By
+# setting this flag the exceptions are removed, and all of
+# -Wextra is used.
GIT-VERSION-FILE: FORCE
@$(SHELL_PATH) ./GIT-VERSION-GEN
@@ -449,15 +492,6 @@ GIT-VERSION-FILE: FORCE
# CFLAGS and LDFLAGS are for the users to override from the command line.
CFLAGS = -g -O2 -Wall
-DEVELOPER_CFLAGS = -Werror \
- -Wdeclaration-after-statement \
- -Wno-format-zero-length \
- -Wold-style-definition \
- -Woverflow \
- -Wpointer-arith \
- -Wstrict-prototypes \
- -Wunused \
- -Wvla
LDFLAGS =
ALL_CFLAGS = $(CPPFLAGS) $(CFLAGS)
ALL_LDFLAGS = $(LDFLAGS)
@@ -478,6 +512,8 @@ ARFLAGS = rcs
# mandir
# infodir
# htmldir
+# localedir
+# perllibdir
# This can help installing the suite in a relocatable way.
prefix = $(HOME)
@@ -502,7 +538,9 @@ bindir_relative = $(patsubst $(prefix)/%,%,$(bindir))
mandir_relative = $(patsubst $(prefix)/%,%,$(mandir))
infodir_relative = $(patsubst $(prefix)/%,%,$(infodir))
gitexecdir_relative = $(patsubst $(prefix)/%,%,$(gitexecdir))
+localedir_relative = $(patsubst $(prefix)/%,%,$(localedir))
htmldir_relative = $(patsubst $(prefix)/%,%,$(htmldir))
+perllibdir_relative = $(patsubst $(prefix)/%,%,$(perllibdir))
export prefix bindir sharedir sysconfdir gitwebdir perllibdir localedir
@@ -652,7 +690,6 @@ PROGRAM_OBJS += imap-send.o
PROGRAM_OBJS += sh-i18n--envsubst.o
PROGRAM_OBJS += shell.o
PROGRAM_OBJS += show-index.o
-PROGRAM_OBJS += upload-pack.o
PROGRAM_OBJS += remote-testsvn.o
# Binary suffix, set to .exe for Windows builds
@@ -701,6 +738,7 @@ TEST_PROGRAMS_NEED_X += test-dump-untracked-cache
TEST_PROGRAMS_NEED_X += test-fake-ssh
TEST_PROGRAMS_NEED_X += test-line-buffer
TEST_PROGRAMS_NEED_X += test-parse-options
+TEST_PROGRAMS_NEED_X += test-pkt-line
TEST_PROGRAMS_NEED_X += test-svn-fe
TEST_PROGRAMS_NEED_X += test-tool
@@ -783,11 +821,13 @@ LIB_OBJS += branch.o
LIB_OBJS += bulk-checkin.o
LIB_OBJS += bundle.o
LIB_OBJS += cache-tree.o
+LIB_OBJS += chdir-notify.o
LIB_OBJS += checkout.o
LIB_OBJS += color.o
LIB_OBJS += column.o
LIB_OBJS += combine-diff.o
LIB_OBJS += commit.o
+LIB_OBJS += commit-graph.o
LIB_OBJS += compat/obstack.o
LIB_OBJS += compat/terminal.o
LIB_OBJS += config.o
@@ -818,7 +858,7 @@ LIB_OBJS += ewah/bitmap.o
LIB_OBJS += ewah/ewah_bitmap.o
LIB_OBJS += ewah/ewah_io.o
LIB_OBJS += ewah/ewah_rlw.o
-LIB_OBJS += exec_cmd.o
+LIB_OBJS += exec-cmd.o
LIB_OBJS += fetch-object.o
LIB_OBJS += fetch-pack.o
LIB_OBJS += fsck.o
@@ -841,9 +881,11 @@ LIB_OBJS += list-objects-filter-options.o
LIB_OBJS += ll-merge.o
LIB_OBJS += lockfile.o
LIB_OBJS += log-tree.o
+LIB_OBJS += ls-refs.o
LIB_OBJS += mailinfo.o
LIB_OBJS += mailmap.o
LIB_OBJS += match-trees.o
+LIB_OBJS += mem-pool.o
LIB_OBJS += merge.o
LIB_OBJS += merge-blobs.o
LIB_OBJS += merge-recursive.o
@@ -886,9 +928,10 @@ LIB_OBJS += refs/files-backend.o
LIB_OBJS += refs/iterator.o
LIB_OBJS += refs/packed-backend.o
LIB_OBJS += refs/ref-cache.o
+LIB_OBJS += refspec.o
LIB_OBJS += ref-filter.o
LIB_OBJS += remote.o
-LIB_OBJS += replace_object.o
+LIB_OBJS += replace-object.o
LIB_OBJS += repository.o
LIB_OBJS += rerere.o
LIB_OBJS += resolve-undo.o
@@ -896,12 +939,13 @@ LIB_OBJS += revision.o
LIB_OBJS += run-command.o
LIB_OBJS += send-pack.o
LIB_OBJS += sequencer.o
+LIB_OBJS += serve.o
LIB_OBJS += server-info.o
LIB_OBJS += setup.o
LIB_OBJS += sha1-array.o
LIB_OBJS += sha1-lookup.o
-LIB_OBJS += sha1_file.o
-LIB_OBJS += sha1_name.o
+LIB_OBJS += sha1-file.o
+LIB_OBJS += sha1-name.o
LIB_OBJS += shallow.o
LIB_OBJS += sideband.o
LIB_OBJS += sigchain.o
@@ -924,6 +968,7 @@ LIB_OBJS += tree-diff.o
LIB_OBJS += tree.o
LIB_OBJS += tree-walk.o
LIB_OBJS += unpack-trees.o
+LIB_OBJS += upload-pack.o
LIB_OBJS += url.o
LIB_OBJS += urlmatch.o
LIB_OBJS += usage.o
@@ -936,7 +981,7 @@ LIB_OBJS += walker.o
LIB_OBJS += wildmatch.o
LIB_OBJS += worktree.o
LIB_OBJS += wrapper.o
-LIB_OBJS += write_or_die.o
+LIB_OBJS += write-or-die.o
LIB_OBJS += ws.o
LIB_OBJS += wt-status.o
LIB_OBJS += xdiff-interface.o
@@ -963,6 +1008,7 @@ BUILTIN_OBJS += builtin/clone.o
BUILTIN_OBJS += builtin/column.o
BUILTIN_OBJS += builtin/commit-tree.o
BUILTIN_OBJS += builtin/commit.o
+BUILTIN_OBJS += builtin/commit-graph.o
BUILTIN_OBJS += builtin/config.o
BUILTIN_OBJS += builtin/count-objects.o
BUILTIN_OBJS += builtin/credential.o
@@ -1028,6 +1074,7 @@ BUILTIN_OBJS += builtin/rev-parse.o
BUILTIN_OBJS += builtin/revert.o
BUILTIN_OBJS += builtin/rm.o
BUILTIN_OBJS += builtin/send-pack.o
+BUILTIN_OBJS += builtin/serve.o
BUILTIN_OBJS += builtin/shortlog.o
BUILTIN_OBJS += builtin/show-branch.o
BUILTIN_OBJS += builtin/show-ref.o
@@ -1041,6 +1088,7 @@ BUILTIN_OBJS += builtin/update-index.o
BUILTIN_OBJS += builtin/update-ref.o
BUILTIN_OBJS += builtin/update-server-info.o
BUILTIN_OBJS += builtin/upload-archive.o
+BUILTIN_OBJS += builtin/upload-pack.o
BUILTIN_OBJS += builtin/var.o
BUILTIN_OBJS += builtin/verify-commit.o
BUILTIN_OBJS += builtin/verify-pack.o
@@ -1062,7 +1110,7 @@ include config.mak.uname
-include config.mak
ifdef DEVELOPER
-CFLAGS += $(DEVELOPER_CFLAGS)
+include config.mak.dev
endif
comma := ,
@@ -1663,10 +1711,27 @@ ifdef HAVE_BSD_SYSCTL
BASIC_CFLAGS += -DHAVE_BSD_SYSCTL
endif
+ifdef HAVE_BSD_KERN_PROC_SYSCTL
+ BASIC_CFLAGS += -DHAVE_BSD_KERN_PROC_SYSCTL
+endif
+
ifdef HAVE_GETDELIM
BASIC_CFLAGS += -DHAVE_GETDELIM
endif
+ifneq ($(PROCFS_EXECUTABLE_PATH),)
+ procfs_executable_path_SQ = $(subst ','\'',$(PROCFS_EXECUTABLE_PATH))
+ BASIC_CFLAGS += '-DPROCFS_EXECUTABLE_PATH="$(procfs_executable_path_SQ)"'
+endif
+
+ifdef HAVE_NS_GET_EXECUTABLE_PATH
+ BASIC_CFLAGS += -DHAVE_NS_GET_EXECUTABLE_PATH
+endif
+
+ifdef HAVE_WPGMPTR
+ BASIC_CFLAGS += -DHAVE_WPGMPTR
+endif
+
ifeq ($(TCLTK_PATH),)
NO_TCLTK = NoThanks
endif
@@ -1751,11 +1816,13 @@ mandir_relative_SQ = $(subst ','\'',$(mandir_relative))
infodir_relative_SQ = $(subst ','\'',$(infodir_relative))
perllibdir_SQ = $(subst ','\'',$(perllibdir))
localedir_SQ = $(subst ','\'',$(localedir))
+localedir_relative_SQ = $(subst ','\'',$(localedir_relative))
gitexecdir_SQ = $(subst ','\'',$(gitexecdir))
gitexecdir_relative_SQ = $(subst ','\'',$(gitexecdir_relative))
template_dir_SQ = $(subst ','\'',$(template_dir))
htmldir_relative_SQ = $(subst ','\'',$(htmldir_relative))
prefix_SQ = $(subst ','\'',$(prefix))
+perllibdir_relative_SQ = $(subst ','\'',$(perllibdir_relative))
gitwebdir_SQ = $(subst ','\'',$(gitwebdir))
SHELL_PATH_SQ = $(subst ','\'',$(SHELL_PATH))
@@ -1766,6 +1833,31 @@ TCLTK_PATH_SQ = $(subst ','\'',$(TCLTK_PATH))
DIFF_SQ = $(subst ','\'',$(DIFF))
PERLLIB_EXTRA_SQ = $(subst ','\'',$(PERLLIB_EXTRA))
+# RUNTIME_PREFIX's resolution logic requires resource paths to be expressed
+# relative to each other and share an installation path.
+#
+# This is a dependency in:
+# - Git's binary RUNTIME_PREFIX logic in (see "exec_cmd.c").
+# - The runtime prefix Perl header (see
+# "perl/header_templates/runtime_prefix.template.pl").
+ifdef RUNTIME_PREFIX
+
+ifneq ($(filter /%,$(firstword $(gitexecdir_relative))),)
+$(error RUNTIME_PREFIX requires a relative gitexecdir, not: $(gitexecdir))
+endif
+
+ifneq ($(filter /%,$(firstword $(localedir_relative))),)
+$(error RUNTIME_PREFIX requires a relative localedir, not: $(localedir))
+endif
+
+ifndef NO_PERL
+ifneq ($(filter /%,$(firstword $(perllibdir_relative))),)
+$(error RUNTIME_PREFIX requires a relative perllibdir, not: $(perllibdir))
+endif
+endif
+
+endif
+
# We must filter out any object files from $(GITLIBS),
# as it is typically used like:
#
@@ -1986,27 +2078,44 @@ git.res: git.rc GIT-VERSION-FILE
# This makes sure we depend on the NO_PERL setting itself.
$(SCRIPT_PERL_GEN): GIT-BUILD-OPTIONS
-ifndef NO_PERL
-$(SCRIPT_PERL_GEN):
+# Used for substitution in Perl modules. Disabled when using RUNTIME_PREFIX
+# since the locale directory is injected.
+perl_localedir_SQ = $(localedir_SQ)
+ifndef NO_PERL
+PERL_HEADER_TEMPLATE = perl/header_templates/fixed_prefix.template.pl
PERL_DEFINES = $(PERL_PATH_SQ):$(PERLLIB_EXTRA_SQ):$(perllibdir_SQ)
-$(SCRIPT_PERL_GEN): % : %.perl GIT-PERL-DEFINES GIT-VERSION-FILE
+
+PERL_DEFINES := $(PERL_PATH_SQ) $(PERLLIB_EXTRA_SQ) $(perllibdir_SQ)
+PERL_DEFINES += $(RUNTIME_PREFIX)
+
+# Support Perl runtime prefix. In this mode, a different header is installed
+# into Perl scripts.
+ifdef RUNTIME_PREFIX
+
+PERL_HEADER_TEMPLATE = perl/header_templates/runtime_prefix.template.pl
+
+# Don't export a fixed $(localedir) path; it will be resolved by the Perl header
+# at runtime.
+perl_localedir_SQ =
+
+endif
+
+PERL_DEFINES += $(gitexecdir) $(perllibdir) $(localedir)
+
+$(SCRIPT_PERL_GEN): % : %.perl GIT-PERL-DEFINES GIT-PERL-HEADER GIT-VERSION-FILE
$(QUIET_GEN)$(RM) $@ $@+ && \
- INSTLIBDIR='$(perllibdir_SQ)' && \
- INSTLIBDIR_EXTRA='$(PERLLIB_EXTRA_SQ)' && \
- INSTLIBDIR="$$INSTLIBDIR$${INSTLIBDIR_EXTRA:+:$$INSTLIBDIR_EXTRA}" && \
sed -e '1{' \
-e ' s|#!.*perl|#!$(PERL_PATH_SQ)|' \
- -e ' h' \
- -e ' s=.*=use lib (split(/$(pathsep)/, $$ENV{GITPERLLIB} || "'"$$INSTLIBDIR"'"));=' \
- -e ' H' \
- -e ' x' \
+ -e ' rGIT-PERL-HEADER' \
+ -e ' G' \
-e '}' \
-e 's/@@GIT_VERSION@@/$(GIT_VERSION)/g' \
$< >$@+ && \
chmod +x $@+ && \
mv $@+ $@
+PERL_DEFINES := $(subst $(space),:,$(PERL_DEFINES))
GIT-PERL-DEFINES: FORCE
@FLAGS='$(PERL_DEFINES)'; \
if test x"$$FLAGS" != x"`cat $@ 2>/dev/null`" ; then \
@@ -2014,6 +2123,22 @@ GIT-PERL-DEFINES: FORCE
echo "$$FLAGS" >$@; \
fi
+GIT-PERL-HEADER: $(PERL_HEADER_TEMPLATE) GIT-PERL-DEFINES Makefile
+ $(QUIET_GEN)$(RM) $@ && \
+ INSTLIBDIR='$(perllibdir_SQ)' && \
+ INSTLIBDIR_EXTRA='$(PERLLIB_EXTRA_SQ)' && \
+ INSTLIBDIR="$$INSTLIBDIR$${INSTLIBDIR_EXTRA:+:$$INSTLIBDIR_EXTRA}" && \
+ sed -e 's=@@PATHSEP@@=$(pathsep)=g' \
+ -e "s=@@INSTLIBDIR@@=$$INSTLIBDIR=g" \
+ -e 's=@@PERLLIBDIR_REL@@=$(perllibdir_relative_SQ)=g' \
+ -e 's=@@GITEXECDIR_REL@@=$(gitexecdir_relative_SQ)=g' \
+ -e 's=@@LOCALEDIR_REL@@=$(localedir_relative_SQ)=g' \
+ $< >$@+ && \
+ mv $@+ $@
+
+.PHONY: perllibdir
+perllibdir:
+ @echo '$(perllibdir_SQ)'
.PHONY: gitweb
gitweb:
@@ -2155,11 +2280,12 @@ else
$(OBJECTS): $(LIB_H)
endif
-exec_cmd.sp exec_cmd.s exec_cmd.o: GIT-PREFIX
-exec_cmd.sp exec_cmd.s exec_cmd.o: EXTRA_CPPFLAGS = \
+exec-cmd.sp exec-cmd.s exec-cmd.o: GIT-PREFIX
+exec-cmd.sp exec-cmd.s exec-cmd.o: EXTRA_CPPFLAGS = \
'-DGIT_EXEC_PATH="$(gitexecdir_SQ)"' \
+ '-DGIT_LOCALE_PATH="$(localedir_relative_SQ)"' \
'-DBINDIR="$(bindir_relative_SQ)"' \
- '-DPREFIX="$(prefix_SQ)"'
+ '-DFALLBACK_RUNTIME_PREFIX="$(prefix_SQ)"'
builtin/init-db.sp builtin/init-db.s builtin/init-db.o: GIT-PREFIX
builtin/init-db.sp builtin/init-db.s builtin/init-db.o: EXTRA_CPPFLAGS = \
@@ -2175,7 +2301,7 @@ attr.sp attr.s attr.o: EXTRA_CPPFLAGS = \
gettext.sp gettext.s gettext.o: GIT-PREFIX
gettext.sp gettext.s gettext.o: EXTRA_CPPFLAGS = \
- -DGIT_LOCALE_PATH='"$(localedir_SQ)"'
+ -DGIT_LOCALE_PATH='"$(localedir_relative_SQ)"'
http-push.sp http.sp http-walker.sp remote-curl.sp imap-send.sp: SPARSE_FLAGS += \
-DCURL_DISABLE_TYPECHECK
@@ -2335,7 +2461,7 @@ endif
perl/build/lib/%.pm: perl/%.pm
$(QUIET_GEN)mkdir -p $(dir $@) && \
- sed -e 's|@@LOCALEDIR@@|$(localedir_SQ)|g' \
+ sed -e 's|@@LOCALEDIR@@|$(perl_localedir_SQ)|g' \
-e 's|@@NO_PERL_CPAN_FALLBACKS@@|$(NO_PERL_CPAN_FALLBACKS_SQ)|g' \
< $< > $@
@@ -2793,7 +2919,7 @@ ifndef NO_TCLTK
endif
$(RM) GIT-VERSION-FILE GIT-CFLAGS GIT-LDFLAGS GIT-BUILD-OPTIONS
$(RM) GIT-USER-AGENT GIT-PREFIX
- $(RM) GIT-SCRIPT-DEFINES GIT-PERL-DEFINES GIT-PYTHON-VARS
+ $(RM) GIT-SCRIPT-DEFINES GIT-PERL-DEFINES GIT-PERL-HEADER GIT-PYTHON-VARS
.PHONY: all install profile-clean clean strip
.PHONY: shell_compatibility_test please_set_SHELL_PATH_to_a_more_modern_shell
diff --git a/advice.c b/advice.c
index 406efc1..370a56d 100644
--- a/advice.c
+++ b/advice.c
@@ -1,5 +1,6 @@
#include "cache.h"
#include "config.h"
+#include "color.h"
int advice_push_update_rejected = 1;
int advice_push_non_ff_current = 1;
@@ -19,6 +20,34 @@ int advice_rm_hints = 1;
int advice_add_embedded_repo = 1;
int advice_ignored_hook = 1;
int advice_waiting_for_editor = 1;
+int advice_graft_file_deprecated = 1;
+
+static int advice_use_color = -1;
+static char advice_colors[][COLOR_MAXLEN] = {
+ GIT_COLOR_RESET,
+ GIT_COLOR_YELLOW, /* HINT */
+};
+
+enum color_advice {
+ ADVICE_COLOR_RESET = 0,
+ ADVICE_COLOR_HINT = 1,
+};
+
+static int parse_advise_color_slot(const char *slot)
+{
+ if (!strcasecmp(slot, "reset"))
+ return ADVICE_COLOR_RESET;
+ if (!strcasecmp(slot, "hint"))
+ return ADVICE_COLOR_HINT;
+ return -1;
+}
+
+static const char *advise_get_color(enum color_advice ix)
+{
+ if (want_color_stderr(advice_use_color))
+ return advice_colors[ix];
+ return "";
+}
static struct {
const char *name;
@@ -42,6 +71,7 @@ static struct {
{ "addembeddedrepo", &advice_add_embedded_repo },
{ "ignoredhook", &advice_ignored_hook },
{ "waitingforeditor", &advice_waiting_for_editor },
+ { "graftfiledeprecated", &advice_graft_file_deprecated },
/* make this an alias for backward compatibility */
{ "pushnonfastforward", &advice_push_update_rejected }
@@ -59,7 +89,10 @@ void advise(const char *advice, ...)
for (cp = buf.buf; *cp; cp = np) {
np = strchrnul(cp, '\n');
- fprintf(stderr, _("hint: %.*s\n"), (int)(np - cp), cp);
+ fprintf(stderr, _("%shint: %.*s%s\n"),
+ advise_get_color(ADVICE_COLOR_HINT),
+ (int)(np - cp), cp,
+ advise_get_color(ADVICE_COLOR_RESET));
if (*np)
np++;
}
@@ -68,9 +101,23 @@ void advise(const char *advice, ...)
int git_default_advice_config(const char *var, const char *value)
{
- const char *k;
+ const char *k, *slot_name;
int i;
+ if (!strcmp(var, "color.advice")) {
+ advice_use_color = git_config_colorbool(var, value);
+ return 0;
+ }
+
+ if (skip_prefix(var, "color.advice.", &slot_name)) {
+ int slot = parse_advise_color_slot(slot_name);
+ if (slot < 0)
+ return 0;
+ if (!value)
+ return config_error_nonbool(var);
+ return color_parse(value, advice_colors[slot]);
+ }
+
if (!skip_prefix(var, "advice.", &k))
return 0;
diff --git a/advice.h b/advice.h
index 70568fa..9f5064e 100644
--- a/advice.h
+++ b/advice.h
@@ -21,6 +21,7 @@ extern int advice_rm_hints;
extern int advice_add_embedded_repo;
extern int advice_ignored_hook;
extern int advice_waiting_for_editor;
+extern int advice_graft_file_deprecated;
int git_default_advice_config(const char *var, const char *value);
__attribute__((format (printf, 1, 2)))
diff --git a/alloc.c b/alloc.c
index 12afadf..cf4f8b6 100644
--- a/alloc.c
+++ b/alloc.c
@@ -93,6 +93,7 @@ void *alloc_commit_node(void)
struct commit *c = alloc_node(&commit_state, sizeof(struct commit));
c->object.type = OBJ_COMMIT;
c->index = alloc_commit_index();
+ c->graph_pos = COMMIT_NOT_FROM_GRAPH;
return c;
}
diff --git a/apply.c b/apply.c
index 7e5792c..d79e615 100644
--- a/apply.c
+++ b/apply.c
@@ -2375,7 +2375,7 @@ static void update_pre_post_images(struct image *preimage,
if (postlen
? postlen < new_buf - postimage->buf
: postimage->len < new_buf - postimage->buf)
- die("BUG: caller miscounted postlen: asked %d, orig = %d, used = %d",
+ BUG("caller miscounted postlen: asked %d, orig = %d, used = %d",
(int)postlen, (int) postimage->len, (int)(new_buf - postimage->buf));
/* Fix the length of the whole thing */
@@ -3509,7 +3509,7 @@ static int load_current(struct apply_state *state,
unsigned mode = patch->new_mode;
if (!patch->is_new)
- die("BUG: patch to %s is not a creation", patch->old_name);
+ BUG("patch to %s is not a creation", patch->old_name);
pos = cache_name_pos(name, strlen(name));
if (pos < 0)
@@ -3860,9 +3860,9 @@ static int check_unsafe_path(struct patch *patch)
if (!patch->is_delete)
new_name = patch->new_name;
- if (old_name && !verify_path(old_name))
+ if (old_name && !verify_path(old_name, patch->old_mode))
return error(_("invalid path '%s'"), old_name);
- if (new_name && !verify_path(new_name))
+ if (new_name && !verify_path(new_name, patch->new_mode))
return error(_("invalid path '%s'"), new_name);
return 0;
}
@@ -4058,7 +4058,7 @@ static int build_fake_ancestor(struct apply_state *state, struct patch *list)
{
struct patch *patch;
struct index_state result = { NULL };
- static struct lock_file lock;
+ struct lock_file lock = LOCK_INIT;
int res;
/* Once we start supporting the reverse patch, it may be
diff --git a/archive-tar.c b/archive-tar.c
index 3563bcb..b6f58dd 100644
--- a/archive-tar.c
+++ b/archive-tar.c
@@ -276,7 +276,7 @@ static int write_tar_entry(struct archiver_args *args,
memcpy(header.name, path, pathlen);
if (S_ISREG(mode) && !args->convert &&
- oid_object_info(oid, &size) == OBJ_BLOB &&
+ oid_object_info(the_repository, oid, &size) == OBJ_BLOB &&
size > big_file_threshold)
buffer = NULL;
else if (S_ISLNK(mode) || S_ISREG(mode)) {
@@ -441,7 +441,7 @@ static int write_tar_filter_archive(const struct archiver *ar,
int r;
if (!ar->data)
- die("BUG: tar-filter archiver called with no filter defined");
+ BUG("tar-filter archiver called with no filter defined");
strbuf_addstr(&cmd, ar->data);
if (args->compression_level >= 0)
diff --git a/archive-zip.c b/archive-zip.c
index 6b20bce..74f3fe9 100644
--- a/archive-zip.c
+++ b/archive-zip.c
@@ -325,7 +325,8 @@ static int write_zip_entry(struct archiver_args *args,
compressed_size = 0;
buffer = NULL;
} else if (S_ISREG(mode) || S_ISLNK(mode)) {
- enum object_type type = oid_object_info(oid, &size);
+ enum object_type type = oid_object_info(the_repository, oid,
+ &size);
method = 0;
attr2 = S_ISLNK(mode) ? ((mode | 0777) << 16) :
diff --git a/argv-array.c b/argv-array.c
index 449dfc1..f352ea9 100644
--- a/argv-array.c
+++ b/argv-array.c
@@ -66,6 +66,26 @@ void argv_array_pop(struct argv_array *array)
array->argc--;
}
+void argv_array_split(struct argv_array *array, const char *to_split)
+{
+ while (isspace(*to_split))
+ to_split++;
+ for (;;) {
+ const char *p = to_split;
+
+ if (!*p)
+ break;
+
+ while (*p && !isspace(*p))
+ p++;
+ argv_array_push_nodup(array, xstrndup(to_split, p - to_split));
+
+ while (isspace(*p))
+ p++;
+ to_split = p;
+ }
+}
+
void argv_array_clear(struct argv_array *array)
{
if (array->argv != empty_argv) {
diff --git a/argv-array.h b/argv-array.h
index 715c93b..a39ba43 100644
--- a/argv-array.h
+++ b/argv-array.h
@@ -19,6 +19,8 @@ LAST_ARG_MUST_BE_NULL
void argv_array_pushl(struct argv_array *, ...);
void argv_array_pushv(struct argv_array *, const char **);
void argv_array_pop(struct argv_array *);
+/* Splits by whitespace; does not handle quoted arguments! */
+void argv_array_split(struct argv_array *, const char *);
void argv_array_clear(struct argv_array *);
const char **argv_array_detach(struct argv_array *);
diff --git a/attr.c b/attr.c
index dfc3a55..067fb9e 100644
--- a/attr.c
+++ b/attr.c
@@ -10,7 +10,7 @@
#define NO_THE_INDEX_COMPATIBILITY_MACROS
#include "cache.h"
#include "config.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "attr.h"
#include "dir.h"
#include "utf8.h"
@@ -157,7 +157,7 @@ static void all_attrs_init(struct attr_hashmap *map, struct attr_check *check)
size = hashmap_get_size(&map->map);
if (size < check->all_attrs_nr)
- die("BUG: interned attributes shouldn't be deleted");
+ BUG("interned attributes shouldn't be deleted");
/*
* If the number of attributes in the global dictionary has increased
@@ -541,7 +541,7 @@ static void check_vector_remove(struct attr_check *check)
break;
if (i >= check_vector.nr)
- die("BUG: no entry found");
+ BUG("no entry found");
/* shift entries over */
for (; i < check_vector.nr - 1; i++)
@@ -599,11 +599,11 @@ struct attr_check *attr_check_initl(const char *one, ...)
const struct git_attr *attr;
param = va_arg(params, const char *);
if (!param)
- die("BUG: counted %d != ended at %d",
+ BUG("counted %d != ended at %d",
check->nr, cnt);
attr = git_attr(param);
if (!attr)
- die("BUG: %s: not a valid attribute name", param);
+ BUG("%s: not a valid attribute name", param);
check->items[cnt].attr = attr;
}
va_end(params);
@@ -714,7 +714,7 @@ void git_attr_set_direction(enum git_attr_direction new_direction,
struct index_state *istate)
{
if (is_bare_repository() && new_direction != GIT_ATTR_INDEX)
- die("BUG: non-INDEX attr direction in a bare repo");
+ BUG("non-INDEX attr direction in a bare repo");
if (new_direction != direction)
drop_all_attr_stacks();
diff --git a/blame.c b/blame.c
index 78c9808..14d0e0b 100644
--- a/blame.c
+++ b/blame.c
@@ -81,7 +81,7 @@ static void verify_working_tree_path(struct commit *work_tree, const char *path)
unsigned mode;
if (!get_tree_entry(commit_oid, path, &blob_oid, &mode) &&
- oid_object_info(&blob_oid, NULL) == OBJ_BLOB)
+ oid_object_info(the_repository, &blob_oid, NULL) == OBJ_BLOB)
return;
}
@@ -504,7 +504,7 @@ static int fill_blob_sha1_and_mode(struct blame_origin *origin)
return 0;
if (get_tree_entry(&origin->commit->object.oid, origin->path, &origin->blob_oid, &origin->mode))
goto error_out;
- if (oid_object_info(&origin->blob_oid, NULL) != OBJ_BLOB)
+ if (oid_object_info(the_repository, &origin->blob_oid, NULL) != OBJ_BLOB)
goto error_out;
return 0;
error_out:
@@ -551,10 +551,10 @@ static struct blame_origin *find_origin(struct commit *parent,
diff_setup_done(&diff_opts);
if (is_null_oid(&origin->commit->object.oid))
- do_diff_cache(&parent->tree->object.oid, &diff_opts);
+ do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
else
- diff_tree_oid(&parent->tree->object.oid,
- &origin->commit->tree->object.oid,
+ diff_tree_oid(get_commit_tree_oid(parent),
+ get_commit_tree_oid(origin->commit),
"", &diff_opts);
diffcore_std(&diff_opts);
@@ -620,10 +620,10 @@ static struct blame_origin *find_rename(struct commit *parent,
diff_setup_done(&diff_opts);
if (is_null_oid(&origin->commit->object.oid))
- do_diff_cache(&parent->tree->object.oid, &diff_opts);
+ do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
else
- diff_tree_oid(&parent->tree->object.oid,
- &origin->commit->tree->object.oid,
+ diff_tree_oid(get_commit_tree_oid(parent),
+ get_commit_tree_oid(origin->commit),
"", &diff_opts);
diffcore_std(&diff_opts);
@@ -1255,10 +1255,10 @@ static void find_copy_in_parent(struct blame_scoreboard *sb,
diff_opts.flags.find_copies_harder = 1;
if (is_null_oid(&target->commit->object.oid))
- do_diff_cache(&parent->tree->object.oid, &diff_opts);
+ do_diff_cache(get_commit_tree_oid(parent), &diff_opts);
else
- diff_tree_oid(&parent->tree->object.oid,
- &target->commit->tree->object.oid,
+ diff_tree_oid(get_commit_tree_oid(parent),
+ get_commit_tree_oid(target->commit),
"", &diff_opts);
if (!diff_opts.flags.find_copies_harder)
@@ -1806,7 +1806,7 @@ void setup_scoreboard(struct blame_scoreboard *sb, const char *path, struct blam
l->item = c;
if (add_decoration(&sb->revs->children,
&c->parents->item->object, l))
- die("BUG: not unique item in first-parent chain");
+ BUG("not unique item in first-parent chain");
c = c->parents->item;
}
diff --git a/branch.c b/branch.c
index 2672054..f967c98 100644
--- a/branch.c
+++ b/branch.c
@@ -3,12 +3,13 @@
#include "config.h"
#include "branch.h"
#include "refs.h"
+#include "refspec.h"
#include "remote.h"
#include "commit.h"
#include "worktree.h"
struct tracking {
- struct refspec spec;
+ struct refspec_item spec;
char *src;
const char *remote;
int matches;
@@ -218,8 +219,8 @@ int validate_new_branchname(const char *name, struct strbuf *ref, int force)
static int check_tracking_branch(struct remote *remote, void *cb_data)
{
char *tracking_branch = cb_data;
- struct refspec query;
- memset(&query, 0, sizeof(struct refspec));
+ struct refspec_item query;
+ memset(&query, 0, sizeof(struct refspec_item));
query.dst = tracking_branch;
return !remote_find_tracking(remote, &query);
}
diff --git a/builtin.h b/builtin.h
index 42378f3..4e0f647 100644
--- a/builtin.h
+++ b/builtin.h
@@ -149,6 +149,7 @@ extern int cmd_clone(int argc, const char **argv, const char *prefix);
extern int cmd_clean(int argc, const char **argv, const char *prefix);
extern int cmd_column(int argc, const char **argv, const char *prefix);
extern int cmd_commit(int argc, const char **argv, const char *prefix);
+extern int cmd_commit_graph(int argc, const char **argv, const char *prefix);
extern int cmd_commit_tree(int argc, const char **argv, const char *prefix);
extern int cmd_config(int argc, const char **argv, const char *prefix);
extern int cmd_count_objects(int argc, const char **argv, const char *prefix);
@@ -215,6 +216,7 @@ extern int cmd_rev_parse(int argc, const char **argv, const char *prefix);
extern int cmd_revert(int argc, const char **argv, const char *prefix);
extern int cmd_rm(int argc, const char **argv, const char *prefix);
extern int cmd_send_pack(int argc, const char **argv, const char *prefix);
+extern int cmd_serve(int argc, const char **argv, const char *prefix);
extern int cmd_shortlog(int argc, const char **argv, const char *prefix);
extern int cmd_show(int argc, const char **argv, const char *prefix);
extern int cmd_show_branch(int argc, const char **argv, const char *prefix);
@@ -231,6 +233,7 @@ extern int cmd_update_ref(int argc, const char **argv, const char *prefix);
extern int cmd_update_server_info(int argc, const char **argv, const char *prefix);
extern int cmd_upload_archive(int argc, const char **argv, const char *prefix);
extern int cmd_upload_archive_writer(int argc, const char **argv, const char *prefix);
+extern int cmd_upload_pack(int argc, const char **argv, const char *prefix);
extern int cmd_var(int argc, const char **argv, const char *prefix);
extern int cmd_verify_commit(int argc, const char **argv, const char *prefix);
extern int cmd_verify_tag(int argc, const char **argv, const char *prefix);
diff --git a/builtin/add.c b/builtin/add.c
index 9ef7fb0..8a155dd 100644
--- a/builtin/add.c
+++ b/builtin/add.c
@@ -9,7 +9,7 @@
#include "lockfile.h"
#include "dir.h"
#include "pathspec.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "cache-tree.h"
#include "run-command.h"
#include "parse-options.h"
@@ -265,8 +265,6 @@ static int edit_patch(int argc, const char **argv, const char *prefix)
return 0;
}
-static struct lock_file lock_file;
-
static const char ignore_error[] =
N_("The following paths are ignored by one of your .gitignore files:\n");
@@ -393,6 +391,7 @@ int cmd_add(int argc, const char **argv, const char *prefix)
int add_new_files;
int require_pathspec;
char *seen = NULL;
+ struct lock_file lock_file = LOCK_INIT;
git_config(add_config, NULL);
diff --git a/builtin/am.c b/builtin/am.c
index 9c82603..aa989e7 100644
--- a/builtin/am.c
+++ b/builtin/am.c
@@ -6,7 +6,7 @@
#include "cache.h"
#include "config.h"
#include "builtin.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "parse-options.h"
#include "dir.h"
#include "run-command.h"
@@ -403,11 +403,11 @@ static void am_load(struct am_state *state)
struct strbuf sb = STRBUF_INIT;
if (read_state_file(&sb, state, "next", 1) < 0)
- die("BUG: state file 'next' does not exist");
+ BUG("state file 'next' does not exist");
state->cur = strtol(sb.buf, NULL, 10);
if (read_state_file(&sb, state, "last", 1) < 0)
- die("BUG: state file 'last' does not exist");
+ BUG("state file 'last' does not exist");
state->last = strtol(sb.buf, NULL, 10);
if (read_author_script(state) < 0)
@@ -986,7 +986,7 @@ static int split_mail(struct am_state *state, enum patch_format patch_format,
case PATCH_FORMAT_MBOXRD:
return split_mail_mbox(state, paths, keep_cr, 1);
default:
- die("BUG: invalid patch_format");
+ BUG("invalid patch_format");
}
return -1;
}
@@ -1041,7 +1041,7 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
str = "b";
break;
default:
- die("BUG: invalid value for state->keep");
+ BUG("invalid value for state->keep");
}
write_state_text(state, "keep", str);
@@ -1058,7 +1058,7 @@ static void am_setup(struct am_state *state, enum patch_format patch_format,
str = "t";
break;
default:
- die("BUG: invalid value for state->scissors");
+ BUG("invalid value for state->scissors");
}
write_state_text(state, "scissors", str);
@@ -1216,7 +1216,7 @@ static int parse_mail(struct am_state *state, const char *mail)
mi.keep_non_patch_brackets_in_subject = 1;
break;
default:
- die("BUG: invalid value for state->keep");
+ BUG("invalid value for state->keep");
}
if (state->message_id)
@@ -1232,7 +1232,7 @@ static int parse_mail(struct am_state *state, const char *mail)
mi.use_scissors = 1;
break;
default:
- die("BUG: invalid value for state->scissors");
+ BUG("invalid value for state->scissors");
}
mi.input = xfopen(mail, "r");
@@ -1463,7 +1463,7 @@ static int run_apply(const struct am_state *state, const char *index_file)
int options = 0;
if (init_apply_state(&apply_state, NULL))
- die("BUG: init_apply_state() failed");
+ BUG("init_apply_state() failed");
argv_array_push(&apply_opts, "apply");
argv_array_pushv(&apply_opts, state->git_apply_opts.argv);
@@ -1489,7 +1489,7 @@ static int run_apply(const struct am_state *state, const char *index_file)
apply_state.apply_verbosity = verbosity_silent;
if (check_apply_state(&apply_state, force_apply))
- die("BUG: check_apply_state() failed");
+ BUG("check_apply_state() failed");
argv_array_push(&apply_paths, am_path(state, "patch"));
@@ -1542,7 +1542,7 @@ static int fall_back_threeway(const struct am_state *state, const char *index_pa
char *their_tree_name;
if (get_oid("HEAD", &our_tree) < 0)
- hashcpy(our_tree.hash, EMPTY_TREE_SHA1_BIN);
+ oidcpy(&our_tree, the_hash_algo->empty_tree);
if (build_fake_ancestor(state, index_path))
return error("could not build fake ancestor");
@@ -2042,7 +2042,7 @@ static void am_skip(struct am_state *state)
am_rerere_clear();
if (get_oid("HEAD", &head))
- hashcpy(head.hash, EMPTY_TREE_SHA1_BIN);
+ oidcpy(&head, the_hash_algo->empty_tree);
if (clean_index(&head, &head))
die(_("failed to clean index"));
@@ -2105,11 +2105,11 @@ static void am_abort(struct am_state *state)
curr_branch = resolve_refdup("HEAD", 0, &curr_head, NULL);
has_curr_head = curr_branch && !is_null_oid(&curr_head);
if (!has_curr_head)
- hashcpy(curr_head.hash, EMPTY_TREE_SHA1_BIN);
+ oidcpy(&curr_head, the_hash_algo->empty_tree);
has_orig_head = !get_oid("ORIG_HEAD", &orig_head);
if (!has_orig_head)
- hashcpy(orig_head.hash, EMPTY_TREE_SHA1_BIN);
+ oidcpy(&orig_head, the_hash_algo->empty_tree);
clean_index(&curr_head, &orig_head);
@@ -2407,7 +2407,7 @@ int cmd_am(int argc, const char **argv, const char *prefix)
ret = show_patch(&state);
break;
default:
- die("BUG: invalid resume value");
+ BUG("invalid resume value");
}
am_state_release(&state);
diff --git a/builtin/blame.c b/builtin/blame.c
index db38c0b..4202584 100644
--- a/builtin/blame.c
+++ b/builtin/blame.c
@@ -7,6 +7,7 @@
#include "cache.h"
#include "config.h"
+#include "color.h"
#include "builtin.h"
#include "commit.h"
#include "diff.h"
@@ -23,6 +24,7 @@
#include "dir.h"
#include "progress.h"
#include "blame.h"
+#include "string-list.h"
static char blame_usage[] = N_("git blame [<options>] [<rev-opts>] [<rev>] [--] <file>");
@@ -46,6 +48,8 @@ static int xdl_opts;
static int abbrev = -1;
static int no_whole_file_rename;
static int show_progress;
+static char repeated_meta_color[COLOR_MAXLEN];
+static int coloring_mode;
static struct date_mode blame_date_mode = { DATE_ISO8601 };
static size_t blame_date_width;
@@ -316,10 +320,12 @@ static const char *format_time(timestamp_t time, const char *tz_str,
#define OUTPUT_PORCELAIN 010
#define OUTPUT_SHOW_NAME 020
#define OUTPUT_SHOW_NUMBER 040
-#define OUTPUT_SHOW_SCORE 0100
-#define OUTPUT_NO_AUTHOR 0200
+#define OUTPUT_SHOW_SCORE 0100
+#define OUTPUT_NO_AUTHOR 0200
#define OUTPUT_SHOW_EMAIL 0400
-#define OUTPUT_LINE_PORCELAIN 01000
+#define OUTPUT_LINE_PORCELAIN 01000
+#define OUTPUT_COLOR_LINE 02000
+#define OUTPUT_SHOW_AGE_WITH_COLOR 04000
static void emit_porcelain_details(struct blame_origin *suspect, int repeat)
{
@@ -367,6 +373,63 @@ static void emit_porcelain(struct blame_scoreboard *sb, struct blame_entry *ent,
putchar('\n');
}
+static struct color_field {
+ timestamp_t hop;
+ char col[COLOR_MAXLEN];
+} *colorfield;
+static int colorfield_nr, colorfield_alloc;
+
+static void parse_color_fields(const char *s)
+{
+ struct string_list l = STRING_LIST_INIT_DUP;
+ struct string_list_item *item;
+ enum { EXPECT_DATE, EXPECT_COLOR } next = EXPECT_COLOR;
+
+ colorfield_nr = 0;
+
+ /* Ideally this would be stripped and split at the same time? */
+ string_list_split(&l, s, ',', -1);
+ ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
+
+ for_each_string_list_item(item, &l) {
+ switch (next) {
+ case EXPECT_DATE:
+ colorfield[colorfield_nr].hop = approxidate(item->string);
+ next = EXPECT_COLOR;
+ colorfield_nr++;
+ ALLOC_GROW(colorfield, colorfield_nr + 1, colorfield_alloc);
+ break;
+ case EXPECT_COLOR:
+ if (color_parse(item->string, colorfield[colorfield_nr].col))
+ die(_("expecting a color: %s"), item->string);
+ next = EXPECT_DATE;
+ break;
+ }
+ }
+
+ if (next == EXPECT_COLOR)
+ die (_("must end with a color"));
+
+ colorfield[colorfield_nr].hop = TIME_MAX;
+}
+
+static void setup_default_color_by_age(void)
+{
+ parse_color_fields("blue,12 month ago,white,1 month ago,red");
+}
+
+static void determine_line_heat(struct blame_entry *ent, const char **dest_color)
+{
+ int i = 0;
+ struct commit_info ci;
+ get_commit_info(ent->suspect->commit, &ci, 1);
+
+ while (i < colorfield_nr && ci.author_time > colorfield[i].hop)
+ i++;
+
+ *dest_color = colorfield[i].col;
+}
+
static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int opt)
{
int cnt;
@@ -375,15 +438,35 @@ static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int
struct commit_info ci;
char hex[GIT_MAX_HEXSZ + 1];
int show_raw_time = !!(opt & OUTPUT_RAW_TIMESTAMP);
+ const char *default_color = NULL, *color = NULL, *reset = NULL;
get_commit_info(suspect->commit, &ci, 1);
oid_to_hex_r(hex, &suspect->commit->object.oid);
cp = blame_nth_line(sb, ent->lno);
+
+ if (opt & OUTPUT_SHOW_AGE_WITH_COLOR) {
+ determine_line_heat(ent, &default_color);
+ color = default_color;
+ reset = GIT_COLOR_RESET;
+ }
+
for (cnt = 0; cnt < ent->num_lines; cnt++) {
char ch;
int length = (opt & OUTPUT_LONG_OBJECT_NAME) ? GIT_SHA1_HEXSZ : abbrev;
+ if (opt & OUTPUT_COLOR_LINE) {
+ if (cnt > 0) {
+ color = repeated_meta_color;
+ reset = GIT_COLOR_RESET;
+ } else {
+ color = default_color ? default_color : NULL;
+ reset = default_color ? GIT_COLOR_RESET : NULL;
+ }
+ }
+ if (color)
+ fputs(color, stdout);
+
if (suspect->commit->object.flags & UNINTERESTING) {
if (blank_boundary)
memset(hex, ' ', length);
@@ -433,6 +516,8 @@ static void emit_other(struct blame_scoreboard *sb, struct blame_entry *ent, int
printf(" %*d) ",
max_digits, ent->lno + 1 + cnt);
}
+ if (reset)
+ fputs(reset, stdout);
do {
ch = *cp++;
putchar(ch);
@@ -607,6 +692,30 @@ static int git_blame_config(const char *var, const char *value, void *cb)
parse_date_format(value, &blame_date_mode);
return 0;
}
+ if (!strcmp(var, "color.blame.repeatedlines")) {
+ if (color_parse_mem(value, strlen(value), repeated_meta_color))
+ warning(_("invalid color '%s' in color.blame.repeatedLines"),
+ value);
+ return 0;
+ }
+ if (!strcmp(var, "color.blame.highlightrecent")) {
+ parse_color_fields(value);
+ return 0;
+ }
+
+ if (!strcmp(var, "blame.coloring")) {
+ if (!strcmp(value, "repeatedLines")) {
+ coloring_mode |= OUTPUT_COLOR_LINE;
+ } else if (!strcmp(value, "highlightRecent")) {
+ coloring_mode |= OUTPUT_SHOW_AGE_WITH_COLOR;
+ } else if (!strcmp(value, "none")) {
+ coloring_mode &= ~(OUTPUT_COLOR_LINE |
+ OUTPUT_SHOW_AGE_WITH_COLOR);
+ } else {
+ warning(_("invalid value for blame.coloring"));
+ return 0;
+ }
+ }
if (git_diff_heuristic_config(var, value, cb) < 0)
return -1;
@@ -655,7 +764,7 @@ static int is_a_rev(const char *name)
if (get_oid(name, &oid))
return 0;
- return OBJ_NONE < oid_object_info(&oid, NULL);
+ return OBJ_NONE < oid_object_info(the_repository, &oid, NULL);
}
int cmd_blame(int argc, const char **argv, const char *prefix)
@@ -690,6 +799,8 @@ int cmd_blame(int argc, const char **argv, const char *prefix)
OPT_BIT('s', NULL, &output_option, N_("Suppress author name and timestamp (Default: off)"), OUTPUT_NO_AUTHOR),
OPT_BIT('e', "show-email", &output_option, N_("Show author email instead of name (Default: off)"), OUTPUT_SHOW_EMAIL),
OPT_BIT('w', NULL, &xdl_opts, N_("Ignore whitespace differences"), XDF_IGNORE_WHITESPACE),
+ OPT_BIT(0, "color-lines", &output_option, N_("color redundant metadata from previous line differently"), OUTPUT_COLOR_LINE),
+ OPT_BIT(0, "color-by-age", &output_option, N_("color lines by age"), OUTPUT_SHOW_AGE_WITH_COLOR),
/*
* The following two options are parsed by parse_revision_opt()
@@ -714,6 +825,7 @@ int cmd_blame(int argc, const char **argv, const char *prefix)
unsigned int range_i;
long anchor;
+ setup_default_color_by_age();
git_config(git_blame_config, &output_option);
init_revisions(&revs, NULL);
revs.date_mode = blame_date_mode;
@@ -949,8 +1061,17 @@ parse_done:
blame_coalesce(&sb);
- if (!(output_option & OUTPUT_PORCELAIN))
+ if (!(output_option & (OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR)))
+ output_option |= coloring_mode;
+
+ if (!(output_option & OUTPUT_PORCELAIN)) {
find_alignment(&sb, &output_option);
+ if (!*repeated_meta_color &&
+ (output_option & OUTPUT_COLOR_LINE))
+ strcpy(repeated_meta_color, GIT_COLOR_CYAN);
+ }
+ if (output_option & OUTPUT_ANNOTATE_COMPAT)
+ output_option &= ~(OUTPUT_COLOR_LINE | OUTPUT_SHOW_AGE_WITH_COLOR);
output(&sb, output_option);
free((void *)sb.final_buf);
diff --git a/builtin/branch.c b/builtin/branch.c
index 5bd2a0d..5bb5123 100644
--- a/builtin/branch.c
+++ b/builtin/branch.c
@@ -391,7 +391,6 @@ static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
struct ref_array array;
int maxwidth = 0;
const char *remote_prefix = "";
- struct strbuf out = STRBUF_INIT;
char *to_free = NULL;
/*
@@ -419,7 +418,10 @@ static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
ref_array_sort(sorting, &array);
for (i = 0; i < array.nr; i++) {
- format_ref_array_item(array.items[i], format, &out);
+ struct strbuf out = STRBUF_INIT;
+ struct strbuf err = STRBUF_INIT;
+ if (format_ref_array_item(array.items[i], format, &out, &err))
+ die("%s", err.buf);
if (column_active(colopts)) {
assert(!filter->verbose && "--column and --verbose are incompatible");
/* format to a string_list to let print_columns() do its job */
@@ -428,6 +430,7 @@ static void print_ref_list(struct ref_filter *filter, struct ref_sorting *sortin
fwrite(out.buf, 1, out.len, stdout);
putchar('\n');
}
+ strbuf_release(&err);
strbuf_release(&out);
}
@@ -497,7 +500,7 @@ static void copy_or_rename_branch(const char *oldname, const char *newname, int
if (!skip_prefix(oldref.buf, "refs/heads/", &interpreted_oldname) ||
!skip_prefix(newref.buf, "refs/heads/", &interpreted_newname)) {
- die("BUG: expected prefix missing for refs");
+ BUG("expected prefix missing for refs");
}
if (copy)
diff --git a/builtin/cat-file.c b/builtin/cat-file.c
index 2c46d25..665b581 100644
--- a/builtin/cat-file.c
+++ b/builtin/cat-file.c
@@ -77,7 +77,7 @@ static int cat_one_file(int opt, const char *exp_type, const char *obj_name,
switch (opt) {
case 't':
oi.type_name = &sb;
- if (oid_object_info_extended(&oid, &oi, flags) < 0)
+ if (oid_object_info_extended(the_repository, &oid, &oi, flags) < 0)
die("git cat-file: could not get object info");
if (sb.len) {
printf("%s\n", sb.buf);
@@ -88,7 +88,7 @@ static int cat_one_file(int opt, const char *exp_type, const char *obj_name,
case 's':
oi.sizep = &size;
- if (oid_object_info_extended(&oid, &oi, flags) < 0)
+ if (oid_object_info_extended(the_repository, &oid, &oi, flags) < 0)
die("git cat-file: could not get object info");
printf("%lu\n", size);
return 0;
@@ -116,7 +116,7 @@ static int cat_one_file(int opt, const char *exp_type, const char *obj_name,
/* else fallthrough */
case 'p':
- type = oid_object_info(&oid, NULL);
+ type = oid_object_info(the_repository, &oid, NULL);
if (type < 0)
die("Not a valid object name %s", obj_name);
@@ -140,7 +140,7 @@ static int cat_one_file(int opt, const char *exp_type, const char *obj_name,
case 0:
if (type_from_string(exp_type) == OBJ_BLOB) {
struct object_id blob_oid;
- if (oid_object_info(&oid, NULL) == OBJ_TAG) {
+ if (oid_object_info(the_repository, &oid, NULL) == OBJ_TAG) {
char *buffer = read_object_file(&oid, &type,
&size);
const char *target;
@@ -151,7 +151,7 @@ static int cat_one_file(int opt, const char *exp_type, const char *obj_name,
} else
oidcpy(&blob_oid, &oid);
- if (oid_object_info(&blob_oid, NULL) == OBJ_BLOB)
+ if (oid_object_info(the_repository, &blob_oid, NULL) == OBJ_BLOB)
return stream_blob_to_fd(1, &blob_oid, NULL, 0);
/*
* we attempted to dereference a tag to a blob
@@ -312,7 +312,7 @@ static void print_object_or_die(struct batch_options *opt, struct expand_data *d
die("could not convert '%s' %s",
oid_to_hex(oid), data->rest);
} else
- die("BUG: invalid cmdmode: %c", opt->cmdmode);
+ BUG("invalid cmdmode: %c", opt->cmdmode);
batch_write(opt, contents, size);
free(contents);
} else if (stream_blob_to_fd(1, oid, NULL, 0) < 0)
@@ -342,7 +342,7 @@ static void batch_object_write(const char *obj_name, struct batch_options *opt,
struct strbuf buf = STRBUF_INIT;
if (!data->skip_object_info &&
- oid_object_info_extended(&data->oid, &data->info,
+ oid_object_info_extended(the_repository, &data->oid, &data->info,
OBJECT_INFO_LOOKUP_REPLACE) < 0) {
printf("%s missing\n",
obj_name ? obj_name : oid_to_hex(&data->oid));
@@ -387,7 +387,7 @@ static void batch_one_object(const char *obj_name, struct batch_options *opt,
(uintmax_t)strlen(obj_name), obj_name);
break;
default:
- die("BUG: unknown get_sha1_with_context result %d\n",
+ BUG("unknown get_sha1_with_context result %d\n",
result);
break;
}
diff --git a/builtin/checkout.c b/builtin/checkout.c
index 5cebe17..2e1d237 100644
--- a/builtin/checkout.c
+++ b/builtin/checkout.c
@@ -484,7 +484,8 @@ static int merge_working_tree(const struct checkout_opts *opts,
resolve_undo_clear();
if (opts->force) {
- ret = reset_tree(new_branch_info->commit->tree, opts, 1, writeout_error);
+ ret = reset_tree(get_commit_tree(new_branch_info->commit),
+ opts, 1, writeout_error);
if (ret)
return ret;
} else {
@@ -571,18 +572,23 @@ static int merge_working_tree(const struct checkout_opts *opts,
o.verbosity = 0;
work = write_tree_from_memory(&o);
- ret = reset_tree(new_branch_info->commit->tree, opts, 1,
+ ret = reset_tree(get_commit_tree(new_branch_info->commit),
+ opts, 1,
writeout_error);
if (ret)
return ret;
o.ancestor = old_branch_info->name;
o.branch1 = new_branch_info->name;
o.branch2 = "local";
- ret = merge_trees(&o, new_branch_info->commit->tree, work,
- old_branch_info->commit->tree, &result);
+ ret = merge_trees(&o,
+ get_commit_tree(new_branch_info->commit),
+ work,
+ get_commit_tree(old_branch_info->commit),
+ &result);
if (ret < 0)
exit(128);
- ret = reset_tree(new_branch_info->commit->tree, opts, 0,
+ ret = reset_tree(get_commit_tree(new_branch_info->commit),
+ opts, 0,
writeout_error);
strbuf_release(&o.obuf);
if (ret)
@@ -1003,7 +1009,7 @@ static int parse_branchname_arg(int argc, const char **argv,
*source_tree = parse_tree_indirect(rev);
} else {
parse_commit_or_die(new_branch_info->commit);
- *source_tree = new_branch_info->commit->tree;
+ *source_tree = get_commit_tree(new_branch_info->commit);
}
if (!*source_tree) /* case (1): want a tree */
diff --git a/builtin/clone.c b/builtin/clone.c
index 7df5932..99e73da 100644
--- a/builtin/clone.c
+++ b/builtin/clone.c
@@ -14,6 +14,7 @@
#include "parse-options.h"
#include "fetch-pack.h"
#include "refs.h"
+#include "refspec.h"
#include "tree.h"
#include "tree-walk.h"
#include "unpack-trees.h"
@@ -546,7 +547,7 @@ static struct ref *find_remote_branch(const struct ref *refs, const char *branch
}
static struct ref *wanted_peer_refs(const struct ref *refs,
- struct refspec *refspec)
+ struct refspec_item *refspec)
{
struct ref *head = copy_ref(find_ref_by_name(refs, "HEAD"));
struct ref *local_refs = head;
@@ -823,7 +824,7 @@ static void write_refspec_config(const char *src_ref_prefix,
} else if (remote_head_points_at) {
const char *head = remote_head_points_at->name;
if (!skip_prefix(head, "refs/heads/", &head))
- die("BUG: remote HEAD points at non-head?");
+ BUG("remote HEAD points at non-head?");
strbuf_addf(&value, "+%s:%s%s", remote_head_points_at->name,
branch_top->buf, head);
@@ -894,8 +895,7 @@ int cmd_clone(int argc, const char **argv, const char *prefix)
int err = 0, complete_refs_before_fetch = 1;
int submodule_progress;
- struct refspec *refspec;
- const char *fetch_pattern;
+ struct refspec_item refspec;
fetch_if_missing = 0;
@@ -1077,8 +1077,7 @@ int cmd_clone(int argc, const char **argv, const char *prefix)
if (option_required_reference.nr || option_optional_reference.nr)
setup_reference();
- fetch_pattern = value.buf;
- refspec = parse_fetch_refspec(1, &fetch_pattern);
+ refspec_item_init(&refspec, value.buf, REFSPEC_FETCH);
strbuf_reset(&value);
@@ -1135,10 +1134,10 @@ int cmd_clone(int argc, const char **argv, const char *prefix)
if (transport->smart_options && !deepen && !filter_options.choice)
transport->smart_options->check_self_contained_and_connected = 1;
- refs = transport_get_remote_refs(transport);
+ refs = transport_get_remote_refs(transport, NULL);
if (refs) {
- mapped_refs = wanted_peer_refs(refs, refspec);
+ mapped_refs = wanted_peer_refs(refs, &refspec);
/*
* transport_get_remote_refs() may return refs with null sha-1
* in mapped_refs (see struct transport->get_refs_list
@@ -1232,6 +1231,6 @@ int cmd_clone(int argc, const char **argv, const char *prefix)
strbuf_release(&value);
junk_mode = JUNK_LEAVE_ALL;
- free(refspec);
+ refspec_item_clear(&refspec);
return err;
}
diff --git a/builtin/column.c b/builtin/column.c
index 0c3223d..5228ccf 100644
--- a/builtin/column.c
+++ b/builtin/column.c
@@ -42,7 +42,6 @@ int cmd_column(int argc, const char **argv, const char *prefix)
git_config(column_config, NULL);
memset(&copts, 0, sizeof(copts));
- copts.width = term_columns();
copts.padding = 1;
argc = parse_options(argc, argv, "", options, builtin_column_usage, 0);
if (argc)
diff --git a/builtin/commit-graph.c b/builtin/commit-graph.c
new file mode 100644
index 0000000..37420ae
--- /dev/null
+++ b/builtin/commit-graph.c
@@ -0,0 +1,171 @@
+#include "builtin.h"
+#include "config.h"
+#include "dir.h"
+#include "lockfile.h"
+#include "parse-options.h"
+#include "commit-graph.h"
+
+static char const * const builtin_commit_graph_usage[] = {
+ N_("git commit-graph [--object-dir <objdir>]"),
+ N_("git commit-graph read [--object-dir <objdir>]"),
+ N_("git commit-graph write [--object-dir <objdir>] [--append] [--stdin-packs|--stdin-commits]"),
+ NULL
+};
+
+static const char * const builtin_commit_graph_read_usage[] = {
+ N_("git commit-graph read [--object-dir <objdir>]"),
+ NULL
+};
+
+static const char * const builtin_commit_graph_write_usage[] = {
+ N_("git commit-graph write [--object-dir <objdir>] [--append] [--stdin-packs|--stdin-commits]"),
+ NULL
+};
+
+static struct opts_commit_graph {
+ const char *obj_dir;
+ int stdin_packs;
+ int stdin_commits;
+ int append;
+} opts;
+
+static int graph_read(int argc, const char **argv)
+{
+ struct commit_graph *graph = NULL;
+ char *graph_name;
+
+ static struct option builtin_commit_graph_read_options[] = {
+ OPT_STRING(0, "object-dir", &opts.obj_dir,
+ N_("dir"),
+ N_("The object directory to store the graph")),
+ OPT_END(),
+ };
+
+ argc = parse_options(argc, argv, NULL,
+ builtin_commit_graph_read_options,
+ builtin_commit_graph_read_usage, 0);
+
+ if (!opts.obj_dir)
+ opts.obj_dir = get_object_directory();
+
+ graph_name = get_commit_graph_filename(opts.obj_dir);
+ graph = load_commit_graph_one(graph_name);
+
+ if (!graph)
+ die("graph file %s does not exist", graph_name);
+ FREE_AND_NULL(graph_name);
+
+ printf("header: %08x %d %d %d %d\n",
+ ntohl(*(uint32_t*)graph->data),
+ *(unsigned char*)(graph->data + 4),
+ *(unsigned char*)(graph->data + 5),
+ *(unsigned char*)(graph->data + 6),
+ *(unsigned char*)(graph->data + 7));
+ printf("num_commits: %u\n", graph->num_commits);
+ printf("chunks:");
+
+ if (graph->chunk_oid_fanout)
+ printf(" oid_fanout");
+ if (graph->chunk_oid_lookup)
+ printf(" oid_lookup");
+ if (graph->chunk_commit_data)
+ printf(" commit_metadata");
+ if (graph->chunk_large_edges)
+ printf(" large_edges");
+ printf("\n");
+
+ return 0;
+}
+
+static int graph_write(int argc, const char **argv)
+{
+ const char **pack_indexes = NULL;
+ int packs_nr = 0;
+ const char **commit_hex = NULL;
+ int commits_nr = 0;
+ const char **lines = NULL;
+ int lines_nr = 0;
+ int lines_alloc = 0;
+
+ static struct option builtin_commit_graph_write_options[] = {
+ OPT_STRING(0, "object-dir", &opts.obj_dir,
+ N_("dir"),
+ N_("The object directory to store the graph")),
+ OPT_BOOL(0, "stdin-packs", &opts.stdin_packs,
+ N_("scan pack-indexes listed by stdin for commits")),
+ OPT_BOOL(0, "stdin-commits", &opts.stdin_commits,
+ N_("start walk at commits listed by stdin")),
+ OPT_BOOL(0, "append", &opts.append,
+ N_("include all commits already in the commit-graph file")),
+ OPT_END(),
+ };
+
+ argc = parse_options(argc, argv, NULL,
+ builtin_commit_graph_write_options,
+ builtin_commit_graph_write_usage, 0);
+
+ if (opts.stdin_packs && opts.stdin_commits)
+ die(_("cannot use both --stdin-commits and --stdin-packs"));
+ if (!opts.obj_dir)
+ opts.obj_dir = get_object_directory();
+
+ if (opts.stdin_packs || opts.stdin_commits) {
+ struct strbuf buf = STRBUF_INIT;
+ lines_nr = 0;
+ lines_alloc = 128;
+ ALLOC_ARRAY(lines, lines_alloc);
+
+ while (strbuf_getline(&buf, stdin) != EOF) {
+ ALLOC_GROW(lines, lines_nr + 1, lines_alloc);
+ lines[lines_nr++] = strbuf_detach(&buf, NULL);
+ }
+
+ if (opts.stdin_packs) {
+ pack_indexes = lines;
+ packs_nr = lines_nr;
+ }
+ if (opts.stdin_commits) {
+ commit_hex = lines;
+ commits_nr = lines_nr;
+ }
+ }
+
+ write_commit_graph(opts.obj_dir,
+ pack_indexes,
+ packs_nr,
+ commit_hex,
+ commits_nr,
+ opts.append);
+
+ return 0;
+}
+
+int cmd_commit_graph(int argc, const char **argv, const char *prefix)
+{
+ static struct option builtin_commit_graph_options[] = {
+ OPT_STRING(0, "object-dir", &opts.obj_dir,
+ N_("dir"),
+ N_("The object directory to store the graph")),
+ OPT_END(),
+ };
+
+ if (argc == 2 && !strcmp(argv[1], "-h"))
+ usage_with_options(builtin_commit_graph_usage,
+ builtin_commit_graph_options);
+
+ git_config(git_default_config, NULL);
+ argc = parse_options(argc, argv, prefix,
+ builtin_commit_graph_options,
+ builtin_commit_graph_usage,
+ PARSE_OPT_STOP_AT_NON_OPTION);
+
+ if (argc > 0) {
+ if (!strcmp(argv[0], "read"))
+ return graph_read(argc, argv);
+ if (!strcmp(argv[0], "write"))
+ return graph_write(argc, argv);
+ }
+
+ usage_with_options(builtin_commit_graph_usage,
+ builtin_commit_graph_options);
+}
diff --git a/builtin/commit.c b/builtin/commit.c
index 37fcb55..a842fea 100644
--- a/builtin/commit.c
+++ b/builtin/commit.c
@@ -143,6 +143,16 @@ static int opt_parse_m(const struct option *opt, const char *arg, int unset)
return 0;
}
+static int opt_parse_rename_score(const struct option *opt, const char *arg, int unset)
+{
+ const char **value = opt->value;
+ if (arg != NULL && *arg == '=')
+ arg = arg + 1;
+
+ *value = arg;
+ return 0;
+}
+
static void determine_whence(struct wt_status *s)
{
if (file_exists(git_path_merge_head()))
@@ -161,9 +171,9 @@ static void determine_whence(struct wt_status *s)
static void status_init_config(struct wt_status *s, config_fn_t fn)
{
wt_status_prepare(s);
+ init_diff_ui_defaults();
git_config(fn, s);
determine_whence(s);
- init_diff_ui_defaults();
s->hints = advice_status_hints; /* must come after git_config() */
}
@@ -218,8 +228,7 @@ static int list_paths(struct string_list *list, const char *with_tree,
if (with_tree) {
char *max_prefix = common_prefix(pattern);
- overlay_tree_on_index(&the_index, with_tree,
- max_prefix ? max_prefix : prefix);
+ overlay_tree_on_index(&the_index, with_tree, max_prefix);
free(max_prefix);
}
@@ -496,7 +505,7 @@ static int is_a_merge(const struct commit *current_head)
static void assert_split_ident(struct ident_split *id, const struct strbuf *buf)
{
if (split_ident_line(id, buf->buf, buf->len) || !id->date_begin)
- die("BUG: unable to parse our own ident: %s", buf->buf);
+ BUG("unable to parse our own ident: %s", buf->buf);
}
static void export_one(const char *var, const char *s, const char *e, int hack)
@@ -1260,11 +1269,31 @@ static int git_status_config(const char *k, const char *v, void *cb)
return error(_("Invalid untracked files mode '%s'"), v);
return 0;
}
+ if (!strcmp(k, "diff.renamelimit")) {
+ if (s->rename_limit == -1)
+ s->rename_limit = git_config_int(k, v);
+ return 0;
+ }
+ if (!strcmp(k, "status.renamelimit")) {
+ s->rename_limit = git_config_int(k, v);
+ return 0;
+ }
+ if (!strcmp(k, "diff.renames")) {
+ if (s->detect_rename == -1)
+ s->detect_rename = git_config_rename(k, v);
+ return 0;
+ }
+ if (!strcmp(k, "status.renames")) {
+ s->detect_rename = git_config_rename(k, v);
+ return 0;
+ }
return git_diff_ui_config(k, v, NULL);
}
int cmd_status(int argc, const char **argv, const char *prefix)
{
+ static int no_renames = -1;
+ static const char *rename_score_arg = (const char *)-1;
static struct wt_status s;
int fd;
struct object_id oid;
@@ -1298,6 +1327,10 @@ int cmd_status(int argc, const char **argv, const char *prefix)
N_("ignore changes to submodules, optional when: all, dirty, untracked. (Default: all)"),
PARSE_OPT_OPTARG, NULL, (intptr_t)"all" },
OPT_COLUMN(0, "column", &s.colopts, N_("list untracked files in columns")),
+ OPT_BOOL(0, "no-renames", &no_renames, N_("do not detect renames")),
+ { OPTION_CALLBACK, 'M', "find-renames", &rename_score_arg,
+ N_("n"), N_("detect renames, optionally set similarity index"),
+ PARSE_OPT_OPTARG, opt_parse_rename_score },
OPT_END(),
};
@@ -1337,6 +1370,14 @@ int cmd_status(int argc, const char **argv, const char *prefix)
s.ignore_submodule_arg = ignore_submodule_arg;
s.status_format = status_format;
s.verbose = verbose;
+ if (no_renames != -1)
+ s.detect_rename = !no_renames;
+ if ((intptr_t)rename_score_arg != -1) {
+ if (s.detect_rename < DIFF_DETECT_RENAME)
+ s.detect_rename = DIFF_DETECT_RENAME;
+ if (rename_score_arg)
+ s.rename_score = parse_rename_score(&rename_score_arg);
+ }
wt_status_collect(&s);
diff --git a/builtin/config.c b/builtin/config.c
index 01169dd..b29d26d 100644
--- a/builtin/config.c
+++ b/builtin/config.c
@@ -25,7 +25,8 @@ static char term = '\n';
static int use_global_config, use_system_config, use_local_config;
static struct git_config_source given_config_source;
-static int actions, types;
+static int actions, type;
+static char *default_value;
static int end_null;
static int respect_includes_opt = -1;
static struct config_options config_options;
@@ -55,11 +56,68 @@ static int show_origin;
#define PAGING_ACTIONS (ACTION_LIST | ACTION_GET_ALL | \
ACTION_GET_REGEXP | ACTION_GET_URLMATCH)
-#define TYPE_BOOL (1<<0)
-#define TYPE_INT (1<<1)
-#define TYPE_BOOL_OR_INT (1<<2)
-#define TYPE_PATH (1<<3)
-#define TYPE_EXPIRY_DATE (1<<4)
+#define TYPE_BOOL 1
+#define TYPE_INT 2
+#define TYPE_BOOL_OR_INT 3
+#define TYPE_PATH 4
+#define TYPE_EXPIRY_DATE 5
+#define TYPE_COLOR 6
+
+#define OPT_CALLBACK_VALUE(s, l, v, h, i) \
+ { OPTION_CALLBACK, (s), (l), (v), NULL, (h), PARSE_OPT_NOARG | \
+ PARSE_OPT_NONEG, option_parse_type, (i) }
+
+static struct option builtin_config_options[];
+
+static int option_parse_type(const struct option *opt, const char *arg,
+ int unset)
+{
+ int new_type, *to_type;
+
+ if (unset) {
+ *((int *) opt->value) = 0;
+ return 0;
+ }
+
+ /*
+ * To support '--<type>' style flags, begin with new_type equal to
+ * opt->defval.
+ */
+ new_type = opt->defval;
+ if (!new_type) {
+ if (!strcmp(arg, "bool"))
+ new_type = TYPE_BOOL;
+ else if (!strcmp(arg, "int"))
+ new_type = TYPE_INT;
+ else if (!strcmp(arg, "bool-or-int"))
+ new_type = TYPE_BOOL_OR_INT;
+ else if (!strcmp(arg, "path"))
+ new_type = TYPE_PATH;
+ else if (!strcmp(arg, "expiry-date"))
+ new_type = TYPE_EXPIRY_DATE;
+ else if (!strcmp(arg, "color"))
+ new_type = TYPE_COLOR;
+ else
+ die(_("unrecognized --type argument, %s"), arg);
+ }
+
+ to_type = opt->value;
+ if (*to_type && *to_type != new_type) {
+ /*
+ * Complain when there is a new type not equal to the old type.
+ * This allows for combinations like '--int --type=int' and
+ * '--type=int --type=int', but disallows ones like '--type=bool
+ * --int' and '--type=bool
+ * --type=int'.
+ */
+ error("only one type at a time.");
+ usage_with_options(builtin_config_usage,
+ builtin_config_options);
+ }
+ *to_type = new_type;
+
+ return 0;
+}
static struct option builtin_config_options[] = {
OPT_GROUP(N_("Config file location")),
@@ -84,16 +142,18 @@ static struct option builtin_config_options[] = {
OPT_BIT(0, "get-color", &actions, N_("find the color configured: slot [default]"), ACTION_GET_COLOR),
OPT_BIT(0, "get-colorbool", &actions, N_("find the color setting: slot [stdout-is-tty]"), ACTION_GET_COLORBOOL),
OPT_GROUP(N_("Type")),
- OPT_BIT(0, "bool", &types, N_("value is \"true\" or \"false\""), TYPE_BOOL),
- OPT_BIT(0, "int", &types, N_("value is decimal number"), TYPE_INT),
- OPT_BIT(0, "bool-or-int", &types, N_("value is --bool or --int"), TYPE_BOOL_OR_INT),
- OPT_BIT(0, "path", &types, N_("value is a path (file or directory name)"), TYPE_PATH),
- OPT_BIT(0, "expiry-date", &types, N_("value is an expiry date"), TYPE_EXPIRY_DATE),
+ OPT_CALLBACK('t', "type", &type, "", N_("value is given this type"), option_parse_type),
+ OPT_CALLBACK_VALUE(0, "bool", &type, N_("value is \"true\" or \"false\""), TYPE_BOOL),
+ OPT_CALLBACK_VALUE(0, "int", &type, N_("value is decimal number"), TYPE_INT),
+ OPT_CALLBACK_VALUE(0, "bool-or-int", &type, N_("value is --bool or --int"), TYPE_BOOL_OR_INT),
+ OPT_CALLBACK_VALUE(0, "path", &type, N_("value is a path (file or directory name)"), TYPE_PATH),
+ OPT_CALLBACK_VALUE(0, "expiry-date", &type, N_("value is an expiry date"), TYPE_EXPIRY_DATE),
OPT_GROUP(N_("Other")),
OPT_BOOL('z', "null", &end_null, N_("terminate values with NUL byte")),
OPT_BOOL(0, "name-only", &omit_values, N_("show variable names only")),
OPT_BOOL(0, "includes", &respect_includes_opt, N_("respect include directives on lookup")),
OPT_BOOL(0, "show-origin", &show_origin, N_("show origin of config (file, standard input, blob, command line)")),
+ OPT_STRING(0, "default", &default_value, N_("value"), N_("with --get, use default value when missing entry")),
OPT_END(),
};
@@ -149,30 +209,35 @@ static int format_config(struct strbuf *buf, const char *key_, const char *value
if (show_keys)
strbuf_addch(buf, key_delim);
- if (types == TYPE_INT)
+ if (type == TYPE_INT)
strbuf_addf(buf, "%"PRId64,
git_config_int64(key_, value_ ? value_ : ""));
- else if (types == TYPE_BOOL)
+ else if (type == TYPE_BOOL)
strbuf_addstr(buf, git_config_bool(key_, value_) ?
"true" : "false");
- else if (types == TYPE_BOOL_OR_INT) {
+ else if (type == TYPE_BOOL_OR_INT) {
int is_bool, v;
v = git_config_bool_or_int(key_, value_, &is_bool);
if (is_bool)
strbuf_addstr(buf, v ? "true" : "false");
else
strbuf_addf(buf, "%d", v);
- } else if (types == TYPE_PATH) {
+ } else if (type == TYPE_PATH) {
const char *v;
if (git_config_pathname(&v, key_, value_) < 0)
return -1;
strbuf_addstr(buf, v);
free((char *)v);
- } else if (types == TYPE_EXPIRY_DATE) {
+ } else if (type == TYPE_EXPIRY_DATE) {
timestamp_t t;
if (git_config_expiry_date(&t, key_, value_) < 0)
return -1;
strbuf_addf(buf, "%"PRItime, t);
+ } else if (type == TYPE_COLOR) {
+ char v[COLOR_MAXLEN];
+ if (git_config_color(v, key_, value_) < 0)
+ return -1;
+ strbuf_addstr(buf, v);
} else if (value_) {
strbuf_addstr(buf, value_);
} else {
@@ -258,6 +323,16 @@ static int get_value(const char *key_, const char *regex_)
config_with_options(collect_config, &values,
&given_config_source, &config_options);
+ if (!values.nr && default_value) {
+ struct strbuf *item;
+ ALLOC_GROW(values.items, values.nr + 1, values.alloc);
+ item = &values.items[values.nr++];
+ strbuf_init(item, 0);
+ if (format_config(item, key_, default_value) < 0)
+ die(_("failed to format default config value: %s"),
+ default_value);
+ }
+
ret = !values.nr;
for (i = 0; i < values.nr; i++) {
@@ -287,7 +362,7 @@ static char *normalize_value(const char *key, const char *value)
if (!value)
return NULL;
- if (types == 0 || types == TYPE_PATH || types == TYPE_EXPIRY_DATE)
+ if (type == 0 || type == TYPE_PATH || type == TYPE_EXPIRY_DATE)
/*
* We don't do normalization for TYPE_PATH here: If
* the path is like ~/foobar/, we prefer to store
@@ -296,11 +371,11 @@ static char *normalize_value(const char *key, const char *value)
* Also don't do normalization for expiry dates.
*/
return xstrdup(value);
- if (types == TYPE_INT)
+ if (type == TYPE_INT)
return xstrfmt("%"PRId64, git_config_int64(key, value));
- if (types == TYPE_BOOL)
+ if (type == TYPE_BOOL)
return xstrdup(git_config_bool(key, value) ? "true" : "false");
- if (types == TYPE_BOOL_OR_INT) {
+ if (type == TYPE_BOOL_OR_INT) {
int is_bool, v;
v = git_config_bool_or_int(key, value, &is_bool);
if (!is_bool)
@@ -308,8 +383,22 @@ static char *normalize_value(const char *key, const char *value)
else
return xstrdup(v ? "true" : "false");
}
+ if (type == TYPE_COLOR) {
+ char v[COLOR_MAXLEN];
+ if (git_config_color(v, key, value))
+ die("cannot parse color '%s'", value);
- die("BUG: cannot normalize type %d", types);
+ /*
+ * The contents of `v` now contain an ANSI escape
+ * sequence, not suitable for including within a
+ * configuration file. Treat the above as a
+ * "sanity-check", and return the given value, which we
+ * know is representable as valid color code.
+ */
+ return xstrdup(value);
+ }
+
+ BUG("cannot normalize type %d", type);
}
static int get_color_found;
@@ -513,6 +602,9 @@ int cmd_config(int argc, const char **argv, const char *prefix)
if (use_local_config && nongit)
die(_("--local can only be used inside a git repository"));
+ if (given_config_source.blob && nongit)
+ die(_("--blob can only be used inside a git repository"));
+
if (given_config_source.file &&
!strcmp(given_config_source.file, "-")) {
given_config_source.file = NULL;
@@ -566,12 +658,7 @@ int cmd_config(int argc, const char **argv, const char *prefix)
key_delim = '\n';
}
- if (HAS_MULTI_BITS(types)) {
- error("only one type at a time.");
- usage_with_options(builtin_config_usage, builtin_config_options);
- }
-
- if ((actions & (ACTION_GET_COLOR|ACTION_GET_COLORBOOL)) && types) {
+ if ((actions & (ACTION_GET_COLOR|ACTION_GET_COLORBOOL)) && type) {
error("--get-color and variable type are incoherent");
usage_with_options(builtin_config_usage, builtin_config_options);
}
@@ -601,6 +688,12 @@ int cmd_config(int argc, const char **argv, const char *prefix)
usage_with_options(builtin_config_usage, builtin_config_options);
}
+ if (default_value && !(actions & ACTION_GET)) {
+ error("--default is only applicable to --get");
+ usage_with_options(builtin_config_usage,
+ builtin_config_options);
+ }
+
if (actions & PAGING_ACTIONS)
setup_auto_pager("config", 1);
diff --git a/builtin/count-objects.c b/builtin/count-objects.c
index b054713..d51e2ce 100644
--- a/builtin/count-objects.c
+++ b/builtin/count-objects.c
@@ -66,7 +66,7 @@ static int count_loose(const struct object_id *oid, const char *path, void *data
else {
loose_size += on_disk_bytes(st);
loose++;
- if (verbose && has_sha1_pack(oid->hash))
+ if (verbose && has_object_pack(oid))
packed_loose++;
}
return 0;
diff --git a/builtin/describe.c b/builtin/describe.c
index de840f9..cf1ae77 100644
--- a/builtin/describe.c
+++ b/builtin/describe.c
@@ -6,7 +6,7 @@
#include "blob.h"
#include "refs.h"
#include "builtin.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "parse-options.h"
#include "revision.h"
#include "diff.h"
@@ -502,7 +502,7 @@ static void describe(const char *arg, int last_one)
if (cmit)
describe_commit(&oid, &sb);
- else if (oid_object_info(&oid, NULL) == OBJ_BLOB)
+ else if (oid_object_info(the_repository, &oid, NULL) == OBJ_BLOB)
describe_blob(oid, &sb);
else
die(_("%s is neither a commit nor blob"), arg);
@@ -612,7 +612,7 @@ int cmd_describe(int argc, const char **argv, const char *prefix)
suffix = broken;
}
} else if (dirty) {
- static struct lock_file index_lock;
+ struct lock_file index_lock = LOCK_INIT;
struct rev_info revs;
struct argv_array args = ARGV_ARRAY_INIT;
int fd, result;
diff --git a/builtin/diff.c b/builtin/diff.c
index 16bfb22..bfefff3 100644
--- a/builtin/diff.c
+++ b/builtin/diff.c
@@ -398,7 +398,7 @@ int cmd_diff(int argc, const char **argv, const char *prefix)
if (!obj)
die(_("invalid object '%s' given."), name);
if (obj->type == OBJ_COMMIT)
- obj = &((struct commit *)obj)->tree->object;
+ obj = &get_commit_tree(((struct commit *)obj))->object;
if (obj->type == OBJ_TREE) {
obj->flags |= flags;
diff --git a/builtin/difftool.c b/builtin/difftool.c
index ee8dce0..162806f 100644
--- a/builtin/difftool.c
+++ b/builtin/difftool.c
@@ -15,7 +15,7 @@
#include "config.h"
#include "builtin.h"
#include "run-command.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "parse-options.h"
#include "argv-array.h"
#include "strbuf.h"
@@ -610,7 +610,7 @@ static int run_dir_diff(const char *extcmd, int symlinks, const char *prefix,
continue;
if (!indices_loaded) {
- static struct lock_file lock;
+ struct lock_file lock = LOCK_INIT;
strbuf_reset(&buf);
strbuf_addf(&buf, "%s/wtindex", tmpdir);
if (hold_lock_file_for_update(&lock, buf.buf, 0) < 0 ||
diff --git a/builtin/fast-export.c b/builtin/fast-export.c
index a15898d..6c97687 100644
--- a/builtin/fast-export.c
+++ b/builtin/fast-export.c
@@ -7,6 +7,7 @@
#include "cache.h"
#include "config.h"
#include "refs.h"
+#include "refspec.h"
#include "commit.h"
#include "object.h"
#include "tag.h"
@@ -35,8 +36,7 @@ static int use_done_feature;
static int no_data;
static int full_tree;
static struct string_list extra_refs = STRING_LIST_INIT_NODUP;
-static struct refspec *refspecs;
-static int refspecs_nr;
+static struct refspec refspecs = REFSPEC_INIT_FETCH;
static int anonymize;
static int parse_opt_signed_tag_mode(const struct option *opt,
@@ -156,15 +156,14 @@ static void anonymize_path(struct strbuf *out, const char *path,
}
}
-/* Since intptr_t is C99, we do not use it here */
-static inline uint32_t *mark_to_ptr(uint32_t mark)
+static inline void *mark_to_ptr(uint32_t mark)
{
- return ((uint32_t *)NULL) + mark;
+ return (void *)(uintptr_t)mark;
}
static inline uint32_t ptr_to_mark(void * mark)
{
- return (uint32_t *)mark - (uint32_t *)NULL;
+ return (uint32_t)(uintptr_t)mark;
}
static inline void mark_object(struct object *object, uint32_t mark)
@@ -517,7 +516,7 @@ static void anonymize_ident_line(const char **beg, const char **end)
/* skip "committer", "author", "tagger", etc */
end_of_header = strchr(*beg, ' ');
if (!end_of_header)
- die("BUG: malformed line fed to anonymize_ident_line: %.*s",
+ BUG("malformed line fed to anonymize_ident_line: %.*s",
(int)(*end - *beg), *beg);
end_of_header++;
strbuf_add(out, *beg, end_of_header - *beg);
@@ -578,11 +577,11 @@ static void handle_commit(struct commit *commit, struct rev_info *rev,
get_object_mark(&commit->parents->item->object) != 0 &&
!full_tree) {
parse_commit_or_die(commit->parents->item);
- diff_tree_oid(&commit->parents->item->tree->object.oid,
- &commit->tree->object.oid, "", &rev->diffopt);
+ diff_tree_oid(get_commit_tree_oid(commit->parents->item),
+ get_commit_tree_oid(commit), "", &rev->diffopt);
}
else
- diff_root_tree_oid(&commit->tree->object.oid,
+ diff_root_tree_oid(get_commit_tree_oid(commit),
"", &rev->diffopt);
/* Export the referenced blobs, and remember the marks. */
@@ -651,8 +650,11 @@ static void handle_tail(struct object_array *commits, struct rev_info *revs,
struct commit *commit;
while (commits->nr) {
commit = (struct commit *)object_array_pop(commits);
- if (has_unshown_parent(commit))
+ if (has_unshown_parent(commit)) {
+ /* Queue again, to be handled later */
+ add_object_array(&commit->object, NULL, commits);
return;
+ }
handle_commit(commit, revs, paths_of_changed_objects);
}
}
@@ -826,9 +828,9 @@ static void get_tags_and_duplicates(struct rev_cmdline_info *info)
if (dwim_ref(e->name, strlen(e->name), &oid, &full_name) != 1)
continue;
- if (refspecs) {
+ if (refspecs.nr) {
char *private;
- private = apply_refspecs(refspecs, refspecs_nr, full_name);
+ private = apply_refspecs(&refspecs, full_name);
if (private) {
free(full_name);
full_name = private;
@@ -947,7 +949,7 @@ static void import_marks(char *input_file)
if (last_idnum < mark)
last_idnum = mark;
- type = oid_object_info(&oid, NULL);
+ type = oid_object_info(the_repository, &oid, NULL);
if (type < 0)
die("object not found: %s", oid_to_hex(&oid));
@@ -974,8 +976,8 @@ static void import_marks(char *input_file)
static void handle_deletes(void)
{
int i;
- for (i = 0; i < refspecs_nr; i++) {
- struct refspec *refspec = &refspecs[i];
+ for (i = 0; i < refspecs.nr; i++) {
+ struct refspec_item *refspec = &refspecs.items[i];
if (*refspec->src)
continue;
@@ -1036,18 +1038,12 @@ int cmd_fast_export(int argc, const char **argv, const char *prefix)
usage_with_options (fast_export_usage, options);
if (refspecs_list.nr) {
- const char **refspecs_str;
int i;
- ALLOC_ARRAY(refspecs_str, refspecs_list.nr);
for (i = 0; i < refspecs_list.nr; i++)
- refspecs_str[i] = refspecs_list.items[i].string;
-
- refspecs_nr = refspecs_list.nr;
- refspecs = parse_fetch_refspec(refspecs_nr, refspecs_str);
+ refspec_append(&refspecs, refspecs_list.items[i].string);
string_list_clear(&refspecs_list, 1);
- free(refspecs_str);
}
if (use_done_feature)
@@ -1086,7 +1082,7 @@ int cmd_fast_export(int argc, const char **argv, const char *prefix)
if (use_done_feature)
printf("done\n");
- free_refspec(refspecs_nr, refspecs);
+ refspec_clear(&refspecs);
return 0;
}
diff --git a/builtin/fetch-pack.c b/builtin/fetch-pack.c
index a7bc136..1a1bc63 100644
--- a/builtin/fetch-pack.c
+++ b/builtin/fetch-pack.c
@@ -4,6 +4,7 @@
#include "remote.h"
#include "connect.h"
#include "sha1-array.h"
+#include "protocol.h"
static const char fetch_pack_usage[] =
"git fetch-pack [--all] [--stdin] [--quiet | -q] [--keep | -k] [--thin] "
@@ -52,6 +53,7 @@ int cmd_fetch_pack(int argc, const char **argv, const char *prefix)
struct fetch_pack_args args;
struct oid_array shallow = OID_ARRAY_INIT;
struct string_list deepen_not = STRING_LIST_INIT_DUP;
+ struct packet_reader reader;
fetch_if_missing = 0;
@@ -211,10 +213,24 @@ int cmd_fetch_pack(int argc, const char **argv, const char *prefix)
if (!conn)
return args.diag_url ? 0 : 1;
}
- get_remote_heads(fd[0], NULL, 0, &ref, 0, NULL, &shallow);
+
+ packet_reader_init(&reader, fd[0], NULL, 0,
+ PACKET_READ_CHOMP_NEWLINE |
+ PACKET_READ_GENTLE_ON_EOF);
+
+ switch (discover_version(&reader)) {
+ case protocol_v2:
+ die("support for protocol v2 not implemented yet");
+ case protocol_v1:
+ case protocol_v0:
+ get_remote_heads(&reader, &ref, 0, NULL, &shallow);
+ break;
+ case protocol_unknown_version:
+ BUG("unknown protocol version");
+ }
ref = fetch_pack(&args, fd, conn, ref, dest, sought, nr_sought,
- &shallow, pack_lockfile_ptr);
+ &shallow, pack_lockfile_ptr, protocol_v0);
if (pack_lockfile) {
printf("lock %s\n", pack_lockfile);
fflush(stdout);
diff --git a/builtin/fetch.c b/builtin/fetch.c
index dcdfc66..c0d8ad1 100644
--- a/builtin/fetch.c
+++ b/builtin/fetch.c
@@ -5,6 +5,7 @@
#include "config.h"
#include "repository.h"
#include "refs.h"
+#include "refspec.h"
#include "commit.h"
#include "builtin.h"
#include "string-list.h"
@@ -59,9 +60,9 @@ static const char *submodule_prefix = "";
static int recurse_submodules = RECURSE_SUBMODULES_DEFAULT;
static int recurse_submodules_default = RECURSE_SUBMODULES_ON_DEMAND;
static int shown_url = 0;
-static int refmap_alloc, refmap_nr;
-static const char **refmap_array;
+static struct refspec refmap = REFSPEC_INIT_FETCH;
static struct list_objects_filter_options filter_options;
+static struct string_list server_options = STRING_LIST_INIT_DUP;
static int git_fetch_config(const char *k, const char *v, void *cb)
{
@@ -107,14 +108,12 @@ static int gitmodules_fetch_config(const char *var, const char *value, void *cb)
static int parse_refmap_arg(const struct option *opt, const char *arg, int unset)
{
- ALLOC_GROW(refmap_array, refmap_nr + 1, refmap_alloc);
-
/*
* "git fetch --refmap='' origin foo"
* can be used to tell the command not to store anywhere
*/
- if (*arg)
- refmap_array[refmap_nr++] = arg;
+ refspec_append(&refmap, arg);
+
return 0;
}
@@ -170,6 +169,7 @@ static struct option builtin_fetch_options[] = {
N_("accept refs that update .git/shallow")),
{ OPTION_CALLBACK, 0, "refmap", NULL, N_("refmap"),
N_("specify fetch refmap"), PARSE_OPT_NONEG, parse_refmap_arg },
+ OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
OPT_SET_INT('4', "ipv4", &family, N_("use IPv4 addresses only"),
TRANSPORT_FAMILY_IPV4),
OPT_SET_INT('6', "ipv6", &family, N_("use IPv6 addresses only"),
@@ -202,7 +202,7 @@ static void add_merge_config(struct ref **head,
for (i = 0; i < branch->merge_nr; i++) {
struct ref *rm, **old_tail = *tail;
- struct refspec refspec;
+ struct refspec_item refspec;
for (rm = *head; rm; rm = rm->next) {
if (branch_merge_matches(branch, i, rm->name)) {
@@ -264,7 +264,7 @@ static void find_non_local_tags(struct transport *transport,
struct string_list_item *item = NULL;
for_each_ref(add_existing, &existing_refs);
- for (ref = transport_get_remote_refs(transport); ref; ref = ref->next) {
+ for (ref = transport_get_remote_refs(transport, NULL); ref; ref = ref->next) {
if (!starts_with(ref->name, "refs/tags/"))
continue;
@@ -339,26 +339,40 @@ static void find_non_local_tags(struct transport *transport,
}
static struct ref *get_ref_map(struct transport *transport,
- struct refspec *refspecs, int refspec_count,
+ struct refspec *rs,
int tags, int *autotags)
{
int i;
struct ref *rm;
struct ref *ref_map = NULL;
struct ref **tail = &ref_map;
+ struct argv_array ref_prefixes = ARGV_ARRAY_INIT;
/* opportunistically-updated references: */
struct ref *orefs = NULL, **oref_tail = &orefs;
- const struct ref *remote_refs = transport_get_remote_refs(transport);
+ const struct ref *remote_refs;
+
+ if (rs->nr)
+ refspec_ref_prefixes(rs, &ref_prefixes);
+ else if (transport->remote && transport->remote->fetch.nr)
+ refspec_ref_prefixes(&transport->remote->fetch, &ref_prefixes);
+
+ if (ref_prefixes.argc &&
+ (tags == TAGS_SET || (tags == TAGS_DEFAULT && !rs->nr))) {
+ argv_array_push(&ref_prefixes, "refs/tags/");
+ }
+
+ remote_refs = transport_get_remote_refs(transport, &ref_prefixes);
- if (refspec_count) {
+ argv_array_clear(&ref_prefixes);
+
+ if (rs->nr) {
struct refspec *fetch_refspec;
- int fetch_refspec_nr;
- for (i = 0; i < refspec_count; i++) {
- get_fetch_map(remote_refs, &refspecs[i], &tail, 0);
- if (refspecs[i].dst && refspecs[i].dst[0])
+ for (i = 0; i < rs->nr; i++) {
+ get_fetch_map(remote_refs, &rs->items[i], &tail, 0);
+ if (rs->items[i].dst && rs->items[i].dst[0])
*autotags = 1;
}
/* Merge everything on the command line (but not --tags) */
@@ -385,17 +399,14 @@ static struct ref *get_ref_map(struct transport *transport,
* by ref_remove_duplicates() in favor of one of these
* opportunistic entries with FETCH_HEAD_IGNORE.
*/
- if (refmap_array) {
- fetch_refspec = parse_fetch_refspec(refmap_nr, refmap_array);
- fetch_refspec_nr = refmap_nr;
- } else {
- fetch_refspec = transport->remote->fetch;
- fetch_refspec_nr = transport->remote->fetch_refspec_nr;
- }
+ if (refmap.nr)
+ fetch_refspec = &refmap;
+ else
+ fetch_refspec = &transport->remote->fetch;
- for (i = 0; i < fetch_refspec_nr; i++)
- get_fetch_map(ref_map, &fetch_refspec[i], &oref_tail, 1);
- } else if (refmap_array) {
+ for (i = 0; i < fetch_refspec->nr; i++)
+ get_fetch_map(ref_map, &fetch_refspec->items[i], &oref_tail, 1);
+ } else if (refmap.nr) {
die("--refmap option is only meaningful with command-line refspec(s).");
} else {
/* Use the defaults */
@@ -403,16 +414,16 @@ static struct ref *get_ref_map(struct transport *transport,
struct branch *branch = branch_get(NULL);
int has_merge = branch_has_merge_config(branch);
if (remote &&
- (remote->fetch_refspec_nr ||
+ (remote->fetch.nr ||
/* Note: has_merge implies non-NULL branch->remote_name */
(has_merge && !strcmp(branch->remote_name, remote->name)))) {
- for (i = 0; i < remote->fetch_refspec_nr; i++) {
- get_fetch_map(remote_refs, &remote->fetch[i], &tail, 0);
- if (remote->fetch[i].dst &&
- remote->fetch[i].dst[0])
+ for (i = 0; i < remote->fetch.nr; i++) {
+ get_fetch_map(remote_refs, &remote->fetch.items[i], &tail, 0);
+ if (remote->fetch.items[i].dst &&
+ remote->fetch.items[i].dst[0])
*autotags = 1;
if (!i && !has_merge && ref_map &&
- !remote->fetch[0].pattern)
+ !remote->fetch.items[0].pattern)
ref_map->fetch_head_status = FETCH_HEAD_MERGE;
}
/*
@@ -637,7 +648,7 @@ static int update_local_ref(struct ref *ref,
struct branch *current_branch = branch_get(NULL);
const char *pretty_ref = prettify_refname(ref->name);
- type = oid_object_info(&ref->new_oid, NULL);
+ type = oid_object_info(the_repository, &ref->new_oid, NULL);
if (type < 0)
die(_("object %s not found"), oid_to_hex(&ref->new_oid));
@@ -947,11 +958,11 @@ static int fetch_refs(struct transport *transport, struct ref *ref_map)
return ret;
}
-static int prune_refs(struct refspec *refs, int ref_count, struct ref *ref_map,
- const char *raw_url)
+static int prune_refs(struct refspec *rs, struct ref *ref_map,
+ const char *raw_url)
{
int url_len, i, result = 0;
- struct ref *ref, *stale_refs = get_stale_heads(refs, ref_count, ref_map);
+ struct ref *ref, *stale_refs = get_stale_heads(rs, ref_map);
char *url;
int summary_width = transport_summary_width(stale_refs);
const char *dangling_msg = dry_run
@@ -1097,7 +1108,7 @@ static void backfill_tags(struct transport *transport, struct ref *ref_map)
}
static int do_fetch(struct transport *transport,
- struct refspec *refs, int ref_count)
+ struct refspec *rs)
{
struct string_list existing_refs = STRING_LIST_INIT_DUP;
struct ref *ref_map;
@@ -1121,7 +1132,7 @@ static int do_fetch(struct transport *transport,
goto cleanup;
}
- ref_map = get_ref_map(transport, refs, ref_count, tags, &autotags);
+ ref_map = get_ref_map(transport, rs, tags, &autotags);
if (!update_head_ok)
check_not_current_branch(ref_map);
@@ -1145,11 +1156,10 @@ static int do_fetch(struct transport *transport,
* explicitly (via command line or configuration); we
* don't care whether --tags was specified.
*/
- if (ref_count) {
- prune_refs(refs, ref_count, ref_map, transport->url);
+ if (rs->nr) {
+ prune_refs(rs, ref_map, transport->url);
} else {
- prune_refs(transport->remote->fetch,
- transport->remote->fetch_refspec_nr,
+ prune_refs(&transport->remote->fetch,
ref_map,
transport->url);
}
@@ -1338,10 +1348,8 @@ static inline void fetch_one_setup_partial(struct remote *remote)
static int fetch_one(struct remote *remote, int argc, const char **argv, int prune_tags_ok)
{
- static const char **refs = NULL;
- struct refspec *refspec;
- int ref_nr = 0;
- int j = 0;
+ struct refspec rs = REFSPEC_INIT_FETCH;
+ int i;
int exit_code;
int maybe_prune_tags;
int remote_via_config = remote_is_configured(remote, 0);
@@ -1374,37 +1382,34 @@ static int fetch_one(struct remote *remote, int argc, const char **argv, int pru
maybe_prune_tags = prune_tags_ok && prune_tags;
if (maybe_prune_tags && remote_via_config)
- add_prune_tags_to_fetch_refspec(remote);
-
- if (argc > 0 || (maybe_prune_tags && !remote_via_config)) {
- size_t nr_alloc = st_add3(argc, maybe_prune_tags, 1);
- refs = xcalloc(nr_alloc, sizeof(const char *));
- if (maybe_prune_tags) {
- refs[j++] = xstrdup("refs/tags/*:refs/tags/*");
- ref_nr++;
+ refspec_append(&remote->fetch, TAG_REFSPEC);
+
+ if (maybe_prune_tags && (argc || !remote_via_config))
+ refspec_append(&rs, TAG_REFSPEC);
+
+ for (i = 0; i < argc; i++) {
+ if (!strcmp(argv[i], "tag")) {
+ char *tag;
+ i++;
+ if (i >= argc)
+ die(_("You need to specify a tag name."));
+
+ tag = xstrfmt("refs/tags/%s:refs/tags/%s",
+ argv[i], argv[i]);
+ refspec_append(&rs, tag);
+ free(tag);
+ } else {
+ refspec_append(&rs, argv[i]);
}
}
- if (argc > 0) {
- int i;
- for (i = 0; i < argc; i++) {
- if (!strcmp(argv[i], "tag")) {
- i++;
- if (i >= argc)
- die(_("You need to specify a tag name."));
- refs[j++] = xstrfmt("refs/tags/%s:refs/tags/%s",
- argv[i], argv[i]);
- } else
- refs[j++] = argv[i];
- ref_nr++;
- }
- }
+ if (server_options.nr)
+ gtransport->server_options = &server_options;
sigchain_push_common(unlock_pack_on_signal);
atexit(unlock_pack);
- refspec = parse_fetch_refspec(ref_nr, refs);
- exit_code = do_fetch(gtransport, refspec, ref_nr);
- free_refspec(ref_nr, refspec);
+ exit_code = do_fetch(gtransport, &rs);
+ refspec_clear(&rs);
transport_disconnect(gtransport);
gtransport = NULL;
return exit_code;
diff --git a/builtin/fsck.c b/builtin/fsck.c
index 087360a..3ad4f16 100644
--- a/builtin/fsck.c
+++ b/builtin/fsck.c
@@ -67,7 +67,8 @@ static const char *printable_type(struct object *obj)
const char *ret;
if (obj->type == OBJ_NONE) {
- enum object_type type = oid_object_info(&obj->oid, NULL);
+ enum object_type type = oid_object_info(the_repository,
+ &obj->oid, NULL);
if (type > 0)
object_as_type(obj, type, 0);
}
@@ -227,7 +228,7 @@ static void check_reachable_object(struct object *obj)
if (!(obj->flags & HAS_OBJ)) {
if (is_promisor_object(&obj->oid))
return;
- if (has_sha1_pack(obj->oid.hash))
+ if (has_object_pack(&obj->oid))
return; /* it is in pack - forget about it */
printf("missing %s %s\n", printable_type(obj),
describe_object(obj));
@@ -339,7 +340,7 @@ static void check_connectivity(void)
}
}
-static int fsck_obj(struct object *obj)
+static int fsck_obj(struct object *obj, void *buffer, unsigned long size)
{
int err;
@@ -353,7 +354,7 @@ static int fsck_obj(struct object *obj)
if (fsck_walk(obj, NULL, &fsck_obj_options))
objerror(obj, "broken links");
- err = fsck_object(obj, NULL, 0, &fsck_obj_options);
+ err = fsck_object(obj, buffer, size, &fsck_obj_options);
if (err)
goto out;
@@ -398,7 +399,7 @@ static int fsck_obj_buffer(const struct object_id *oid, enum object_type type,
}
obj->flags &= ~(REACHABLE | SEEN);
obj->flags |= HAS_OBJ;
- return fsck_obj(obj);
+ return fsck_obj(obj, buffer, size);
}
static int default_refs;
@@ -506,44 +507,42 @@ static void get_default_heads(void)
}
}
-static struct object *parse_loose_object(const struct object_id *oid,
- const char *path)
+static int fsck_loose(const struct object_id *oid, const char *path, void *data)
{
struct object *obj;
- void *contents;
enum object_type type;
unsigned long size;
+ void *contents;
int eaten;
- if (read_loose_object(path, oid, &type, &size, &contents) < 0)
- return NULL;
+ if (read_loose_object(path, oid, &type, &size, &contents) < 0) {
+ errors_found |= ERROR_OBJECT;
+ error("%s: object corrupt or missing: %s",
+ oid_to_hex(oid), path);
+ return 0; /* keep checking other objects */
+ }
if (!contents && type != OBJ_BLOB)
- die("BUG: read_loose_object streamed a non-blob");
+ BUG("read_loose_object streamed a non-blob");
obj = parse_object_buffer(oid, type, size, contents, &eaten);
-
- if (!eaten)
- free(contents);
- return obj;
-}
-
-static int fsck_loose(const struct object_id *oid, const char *path, void *data)
-{
- struct object *obj = parse_loose_object(oid, path);
-
if (!obj) {
errors_found |= ERROR_OBJECT;
- error("%s: object corrupt or missing: %s",
+ error("%s: object could not be parsed: %s",
oid_to_hex(oid), path);
+ if (!eaten)
+ free(contents);
return 0; /* keep checking other objects */
}
obj->flags &= ~(REACHABLE | SEEN);
obj->flags |= HAS_OBJ;
- if (fsck_obj(obj))
+ if (fsck_obj(obj, contents, size))
errors_found |= ERROR_OBJECT;
- return 0;
+
+ if (!eaten)
+ free(contents);
+ return 0; /* keep checking other objects, even if we saw an error */
}
static int fsck_cruft(const char *basename, const char *path, void *data)
@@ -755,6 +754,9 @@ int cmd_fsck(int argc, const char **argv, const char *prefix)
}
stop_progress(&progress);
}
+
+ if (fsck_finish(&fsck_obj_options))
+ errors_found |= ERROR_OBJECT;
}
for (i = 0; i < argc; i++) {
diff --git a/builtin/gc.c b/builtin/gc.c
index 3e67124..ccfb1ce 100644
--- a/builtin/gc.c
+++ b/builtin/gc.c
@@ -22,6 +22,10 @@
#include "commit.h"
#include "packfile.h"
#include "object-store.h"
+#include "pack.h"
+#include "pack-objects.h"
+#include "blob.h"
+#include "tree.h"
#define FAILED_RUN "failed to run %s"
@@ -41,6 +45,8 @@ static timestamp_t gc_log_expire_time;
static const char *gc_log_expire = "1.day.ago";
static const char *prune_expire = "2.weeks.ago";
static const char *prune_worktrees_expire = "3.months.ago";
+static unsigned long big_pack_threshold;
+static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
static struct argv_array pack_refs_cmd = ARGV_ARRAY_INIT;
static struct argv_array reflog = ARGV_ARRAY_INIT;
@@ -128,6 +134,9 @@ static void gc_config(void)
git_config_get_expiry("gc.worktreepruneexpire", &prune_worktrees_expire);
git_config_get_expiry("gc.logexpiry", &gc_log_expire);
+ git_config_get_ulong("gc.bigpackthreshold", &big_pack_threshold);
+ git_config_get_ulong("pack.deltacachesize", &max_delta_cache_size);
+
git_config(git_default_config, NULL);
}
@@ -166,6 +175,28 @@ static int too_many_loose_objects(void)
return needed;
}
+static struct packed_git *find_base_packs(struct string_list *packs,
+ unsigned long limit)
+{
+ struct packed_git *p, *base = NULL;
+
+ for (p = get_packed_git(the_repository); p; p = p->next) {
+ if (!p->pack_local)
+ continue;
+ if (limit) {
+ if (p->pack_size >= limit)
+ string_list_append(packs, p->pack_name);
+ } else if (!base || base->pack_size < p->pack_size) {
+ base = p;
+ }
+ }
+
+ if (base)
+ string_list_append(packs, base->pack_name);
+
+ return base;
+}
+
static int too_many_packs(void)
{
struct packed_git *p;
@@ -188,7 +219,86 @@ static int too_many_packs(void)
return gc_auto_pack_limit < cnt;
}
-static void add_repack_all_option(void)
+static uint64_t total_ram(void)
+{
+#if defined(HAVE_SYSINFO)
+ struct sysinfo si;
+
+ if (!sysinfo(&si))
+ return si.totalram;
+#elif defined(HAVE_BSD_SYSCTL) && (defined(HW_MEMSIZE) || defined(HW_PHYSMEM))
+ int64_t physical_memory;
+ int mib[2];
+ size_t length;
+
+ mib[0] = CTL_HW;
+# if defined(HW_MEMSIZE)
+ mib[1] = HW_MEMSIZE;
+# else
+ mib[1] = HW_PHYSMEM;
+# endif
+ length = sizeof(int64_t);
+ if (!sysctl(mib, 2, &physical_memory, &length, NULL, 0))
+ return physical_memory;
+#elif defined(GIT_WINDOWS_NATIVE)
+ MEMORYSTATUSEX memInfo;
+
+ memInfo.dwLength = sizeof(MEMORYSTATUSEX);
+ if (GlobalMemoryStatusEx(&memInfo))
+ return memInfo.ullTotalPhys;
+#endif
+ return 0;
+}
+
+static uint64_t estimate_repack_memory(struct packed_git *pack)
+{
+ unsigned long nr_objects = approximate_object_count();
+ size_t os_cache, heap;
+
+ if (!pack || !nr_objects)
+ return 0;
+
+ /*
+ * First we have to scan through at least one pack.
+ * Assume enough room in OS file cache to keep the entire pack
+ * or we may accidentally evict data of other processes from
+ * the cache.
+ */
+ os_cache = pack->pack_size + pack->index_size;
+ /* then pack-objects needs lots more for book keeping */
+ heap = sizeof(struct object_entry) * nr_objects;
+ /*
+ * internal rev-list --all --objects takes up some memory too,
+ * let's say half of it is for blobs
+ */
+ heap += sizeof(struct blob) * nr_objects / 2;
+ /*
+ * and the other half is for trees (commits and tags are
+ * usually insignificant)
+ */
+ heap += sizeof(struct tree) * nr_objects / 2;
+ /* and then obj_hash[], underestimated in fact */
+ heap += sizeof(struct object *) * nr_objects;
+ /* revindex is used also */
+ heap += sizeof(struct revindex_entry) * nr_objects;
+ /*
+ * read_sha1_file() (either at delta calculation phase, or
+ * writing phase) also fills up the delta base cache
+ */
+ heap += delta_base_cache_limit;
+ /* and of course pack-objects has its own delta cache */
+ heap += max_delta_cache_size;
+
+ return os_cache + heap;
+}
+
+static int keep_one_pack(struct string_list_item *item, void *data)
+{
+ argv_array_pushf(&repack, "--keep-pack=%s", basename(item->string));
+ return 0;
+}
+
+static void add_repack_all_option(struct string_list *keep_pack)
{
if (prune_expire && !strcmp(prune_expire, "now"))
argv_array_push(&repack, "-a");
@@ -197,6 +307,9 @@ static void add_repack_all_option(void)
if (prune_expire)
argv_array_pushf(&repack, "--unpack-unreachable=%s", prune_expire);
}
+
+ if (keep_pack)
+ for_each_string_list(keep_pack, keep_one_pack, NULL);
}
static void add_repack_incremental_option(void)
@@ -219,9 +332,35 @@ static int need_to_gc(void)
* we run "repack -A -d -l". Otherwise we tell the caller
* there is no need.
*/
- if (too_many_packs())
- add_repack_all_option();
- else if (too_many_loose_objects())
+ if (too_many_packs()) {
+ struct string_list keep_pack = STRING_LIST_INIT_NODUP;
+
+ if (big_pack_threshold) {
+ find_base_packs(&keep_pack, big_pack_threshold);
+ if (keep_pack.nr >= gc_auto_pack_limit) {
+ big_pack_threshold = 0;
+ string_list_clear(&keep_pack, 0);
+ find_base_packs(&keep_pack, 0);
+ }
+ } else {
+ struct packed_git *p = find_base_packs(&keep_pack, 0);
+ uint64_t mem_have, mem_want;
+
+ mem_have = total_ram();
+ mem_want = estimate_repack_memory(p);
+
+ /*
+ * Only allow 1/2 of memory for pack-objects, leave
+ * the rest for the OS and other processes in the
+ * system.
+ */
+ if (!mem_have || mem_want < mem_have / 2)
+ string_list_clear(&keep_pack, 0);
+ }
+
+ add_repack_all_option(&keep_pack);
+ string_list_clear(&keep_pack, 0);
+ } else if (too_many_loose_objects())
add_repack_incremental_option();
else
return 0;
@@ -234,7 +373,7 @@ static int need_to_gc(void)
/* return NULL on success, else hostname running the gc */
static const char *lock_repo_for_gc(int force, pid_t* ret_pid)
{
- static struct lock_file lock;
+ struct lock_file lock = LOCK_INIT;
char my_host[HOST_NAME_MAX + 1];
struct strbuf sb = STRBUF_INIT;
struct stat st;
@@ -354,6 +493,8 @@ int cmd_gc(int argc, const char **argv, const char *prefix)
const char *name;
pid_t pid;
int daemonized = 0;
+ int keep_base_pack = -1;
+ timestamp_t dummy;
struct option builtin_gc_options[] = {
OPT__QUIET(&quiet, N_("suppress progress reporting")),
@@ -366,6 +507,8 @@ int cmd_gc(int argc, const char **argv, const char *prefix)
OPT_BOOL_F(0, "force", &force,
N_("force running gc even if there may be another gc running"),
PARSE_OPT_NOCOMPLETE),
+ OPT_BOOL(0, "keep-largest-pack", &keep_base_pack,
+ N_("repack all other packs except the largest pack")),
OPT_END()
};
@@ -382,7 +525,7 @@ int cmd_gc(int argc, const char **argv, const char *prefix)
/* default expiry time, overwritten in gc_config */
gc_config();
if (parse_expiry_date(gc_log_expire, &gc_log_expire_time))
- die(_("Failed to parse gc.logexpiry value %s"), gc_log_expire);
+ die(_("failed to parse gc.logexpiry value %s"), gc_log_expire);
if (pack_refs < 0)
pack_refs = !is_bare_repository();
@@ -392,6 +535,9 @@ int cmd_gc(int argc, const char **argv, const char *prefix)
if (argc > 0)
usage_with_options(builtin_gc_usage, builtin_gc_options);
+ if (prune_expire && parse_expiry_date(prune_expire, &dummy))
+ die(_("failed to parse prune expiry value %s"), prune_expire);
+
if (aggressive) {
argv_array_push(&repack, "-f");
if (aggressive_depth > 0)
@@ -431,8 +577,19 @@ int cmd_gc(int argc, const char **argv, const char *prefix)
*/
daemonized = !daemonize();
}
- } else
- add_repack_all_option();
+ } else {
+ struct string_list keep_pack = STRING_LIST_INIT_NODUP;
+
+ if (keep_base_pack != -1) {
+ if (keep_base_pack)
+ find_base_packs(&keep_pack, 0);
+ } else if (big_pack_threshold) {
+ find_base_packs(&keep_pack, big_pack_threshold);
+ }
+
+ add_repack_all_option(&keep_pack);
+ string_list_clear(&keep_pack, 0);
+ }
name = lock_repo_for_gc(force, &pid);
if (name) {
diff --git a/builtin/grep.c b/builtin/grep.c
index 5f32d2c..69f0743 100644
--- a/builtin/grep.c
+++ b/builtin/grep.c
@@ -488,7 +488,8 @@ static int grep_cache(struct grep_opt *opt, struct repository *repo,
strbuf_addstr(&name, repo->submodule_prefix);
}
- repo_read_index(repo);
+ if (repo_read_index(repo) < 0)
+ die("index file corrupt");
for (nr = 0; nr < repo->index->cache_nr; nr++) {
const struct cache_entry *ce = repo->index->cache[nr];
@@ -602,8 +603,7 @@ static int grep_tree(struct grep_opt *opt, const struct pathspec *pathspec,
}
static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
- struct object *obj, const char *name, const char *path,
- struct repository *repo)
+ struct object *obj, const char *name, const char *path)
{
if (obj->type == OBJ_BLOB)
return grep_oid(opt, &obj->oid, name, 0, path);
@@ -630,7 +630,7 @@ static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
}
init_tree_desc(&tree, data, size);
hit = grep_tree(opt, pathspec, &tree, &base, base.len,
- obj->type == OBJ_COMMIT, repo);
+ obj->type == OBJ_COMMIT, the_repository);
strbuf_release(&base);
free(data);
return hit;
@@ -639,7 +639,6 @@ static int grep_object(struct grep_opt *opt, const struct pathspec *pathspec,
}
static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
- struct repository *repo,
const struct object_array *list)
{
unsigned int i;
@@ -652,11 +651,11 @@ static int grep_objects(struct grep_opt *opt, const struct pathspec *pathspec,
/* load the gitmodules file for this rev */
if (recurse_submodules) {
- submodule_free();
+ submodule_free(the_repository);
gitmodules_config_oid(&real_obj->oid);
}
- if (grep_object(opt, pathspec, real_obj, list->objects[i].name, list->objects[i].path,
- repo)) {
+ if (grep_object(opt, pathspec, real_obj, list->objects[i].name,
+ list->objects[i].path)) {
hit = 1;
if (opt->status_only)
break;
@@ -1108,7 +1107,7 @@ int cmd_grep(int argc, const char **argv, const char *prefix)
if (cached)
die(_("both --cached and trees are given."));
- hit = grep_objects(&opt, &pathspec, the_repository, &list);
+ hit = grep_objects(&opt, &pathspec, &list);
}
if (num_threads)
diff --git a/builtin/hash-object.c b/builtin/hash-object.c
index 526da5c..a9a3a19 100644
--- a/builtin/hash-object.c
+++ b/builtin/hash-object.c
@@ -9,7 +9,7 @@
#include "blob.h"
#include "quote.h"
#include "parse-options.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
/*
* This is to create corrupt objects for debugging and as such it
diff --git a/builtin/help.c b/builtin/help.c
index 598867c..2d51071 100644
--- a/builtin/help.c
+++ b/builtin/help.c
@@ -4,7 +4,7 @@
#include "cache.h"
#include "config.h"
#include "builtin.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "parse-options.h"
#include "run-command.h"
#include "column.h"
diff --git a/builtin/index-pack.c b/builtin/index-pack.c
index d81473e..4ab31ed 100644
--- a/builtin/index-pack.c
+++ b/builtin/index-pack.c
@@ -9,7 +9,7 @@
#include "tree.h"
#include "progress.h"
#include "fsck.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "streaming.h"
#include "thread-utils.h"
#include "packfile.h"
@@ -223,7 +223,7 @@ static unsigned check_object(struct object *obj)
if (!(obj->flags & FLAG_CHECKED)) {
unsigned long size;
- int type = oid_object_info(&obj->oid, &size);
+ int type = oid_object_info(the_repository, &obj->oid, &size);
if (type <= 0)
die(_("did not receive expected object %s"),
oid_to_hex(&obj->oid));
@@ -812,7 +812,7 @@ static void sha1_object(const void *data, struct object_entry *obj_entry,
enum object_type has_type;
unsigned long has_size;
read_lock();
- has_type = oid_object_info(oid, &has_size);
+ has_type = oid_object_info(the_repository, oid, &has_size);
if (has_type < 0)
die(_("cannot read existing object info %s"), oid_to_hex(oid));
if (has_type != type || has_size != size)
@@ -837,6 +837,9 @@ static void sha1_object(const void *data, struct object_entry *obj_entry,
blob->object.flags |= FLAG_CHECKED;
else
die(_("invalid blob object %s"), oid_to_hex(oid));
+ if (do_fsck_object &&
+ fsck_object(&blob->object, (void *)data, size, &fsck_options))
+ die(_("fsck error in packed object"));
} else {
struct object *obj;
int eaten;
@@ -854,7 +857,7 @@ static void sha1_object(const void *data, struct object_entry *obj_entry,
die(_("invalid %s"), type_name(type));
if (do_fsck_object &&
fsck_object(obj, buf, size, &fsck_options))
- die(_("Error in object"));
+ die(_("fsck error in packed object"));
if (strict && fsck_walk(obj, NULL, &fsck_options))
die(_("Not all child objects of %s are reachable"), oid_to_hex(&obj->oid));
@@ -866,7 +869,7 @@ static void sha1_object(const void *data, struct object_entry *obj_entry,
if (obj->type == OBJ_COMMIT) {
struct commit *commit = (struct commit *) obj;
if (detach_commit_buffer(commit, NULL) != data)
- die("BUG: parse_object_buffer transmogrified our buffer");
+ BUG("parse_object_buffer transmogrified our buffer");
}
obj->flags |= FLAG_CHECKED;
}
@@ -1015,7 +1018,7 @@ static struct base_data *find_unresolved_deltas_1(struct base_data *base,
if (!compare_and_swap_type(&child->real_type, OBJ_REF_DELTA,
base->obj->real_type))
- die("BUG: child->real_type != OBJ_REF_DELTA");
+ BUG("child->real_type != OBJ_REF_DELTA");
resolve_delta(child, base, result);
if (base->ref_first == base->ref_last && base->ofs_last == -1)
@@ -1271,7 +1274,7 @@ static void conclude_pack(int fix_thin_pack, const char *curr_pack, unsigned cha
nr_objects - nr_objects_initial);
stop_progress_msg(&progress, msg.buf);
strbuf_release(&msg);
- hashclose(f, tail_hash, 0);
+ finalize_hashfile(f, tail_hash, 0);
hashcpy(read_hash, pack_hash);
fixup_pack_header_footer(output_fd, pack_hash,
curr_pack, nr_objects,
@@ -1479,6 +1482,9 @@ static void final(const char *final_pack_name, const char *curr_pack_name,
} else
chmod(final_index_name, 0444);
+ if (do_fsck_object)
+ add_packed_git(final_index_name, strlen(final_index_name), 0);
+
if (!from_stdin) {
printf("%s\n", sha1_to_hex(hash));
} else {
@@ -1543,12 +1549,13 @@ static void read_v2_anomalous_offsets(struct packed_git *p,
{
const uint32_t *idx1, *idx2;
uint32_t i;
+ const uint32_t hashwords = the_hash_algo->rawsz / sizeof(uint32_t);
/* The address of the 4-byte offset table */
idx1 = (((const uint32_t *)p->index_data)
+ 2 /* 8-byte header */
+ 256 /* fan out */
- + 5 * p->num_objects /* 20-byte SHA-1 table */
+ + hashwords * p->num_objects /* object ID table */
+ p->num_objects /* CRC32 table */
);
@@ -1593,7 +1600,7 @@ static void read_idx_option(struct pack_idx_option *opts, const char *pack_name)
/*
* Get rid of the idx file as we do not need it anymore.
* NEEDSWORK: extract this bit from free_pack_by_name() in
- * sha1_file.c, perhaps? It shouldn't matter very much as we
+ * sha1-file.c, perhaps? It shouldn't matter very much as we
* know we haven't installed this pack (hence we never have
* read anything from it).
*/
@@ -1820,6 +1827,10 @@ int cmd_index_pack(int argc, const char **argv, const char *prefix)
pack_hash);
else
close(input_fd);
+
+ if (do_fsck_object && fsck_finish(&fsck_options))
+ die(_("fsck error in pack objects"));
+
free(objects);
strbuf_release(&index_name_buf);
if (pack_name == NULL)
diff --git a/builtin/init-db.c b/builtin/init-db.c
index 68ff4ad..5a5844c 100644
--- a/builtin/init-db.c
+++ b/builtin/init-db.c
@@ -7,7 +7,7 @@
#include "config.h"
#include "refs.h"
#include "builtin.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "parse-options.h"
#ifndef DEFAULT_GIT_TEMPLATE_DIR
@@ -391,7 +391,7 @@ int init_db(const char *git_dir, const char *real_git_dir,
else if (get_shared_repository() == PERM_EVERYBODY)
xsnprintf(buf, sizeof(buf), "%d", OLD_PERM_EVERYBODY);
else
- die("BUG: invalid value for shared_repository");
+ BUG("invalid value for shared_repository");
git_config_set("core.sharedrepository", buf);
git_config_set("receive.denyNonFastforwards", "true");
}
diff --git a/builtin/log.c b/builtin/log.c
index 71f68a3..a15599f 100644
--- a/builtin/log.c
+++ b/builtin/log.c
@@ -1019,7 +1019,7 @@ static void make_cover_letter(struct rev_info *rev, int use_stdout,
open_next_file(NULL, rev->numbered_files ? NULL : "cover-letter", rev, quiet))
return;
- log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte);
+ log_write_email_headers(rev, head, &pp.after_subject, &need_8bit_cte, 0);
for (i = 0; !need_8bit_cte && i < nr; i++) {
const char *buf = get_commit_buffer(list[i], NULL);
@@ -1067,8 +1067,8 @@ static void make_cover_letter(struct rev_info *rev, int use_stdout,
diff_setup_done(&opts);
- diff_tree_oid(&origin->tree->object.oid,
- &head->tree->object.oid,
+ diff_tree_oid(get_commit_tree_oid(origin),
+ get_commit_tree_oid(head),
"", &opts);
diffcore_std(&opts);
diff_flush(&opts);
diff --git a/builtin/ls-files.c b/builtin/ls-files.c
index a71f6bd..967b2b3 100644
--- a/builtin/ls-files.c
+++ b/builtin/ls-files.c
@@ -166,7 +166,7 @@ static void show_killed_files(const struct index_state *istate,
*/
pos = index_name_pos(istate, ent->name, ent->len);
if (0 <= pos)
- die("BUG: killed-file %.*s not found",
+ BUG("killed-file %.*s not found",
ent->len, ent->name);
pos = -pos - 1;
while (pos < istate->cache_nr &&
diff --git a/builtin/ls-remote.c b/builtin/ls-remote.c
index 540d564..1a25df7 100644
--- a/builtin/ls-remote.c
+++ b/builtin/ls-remote.c
@@ -1,7 +1,9 @@
#include "builtin.h"
#include "cache.h"
#include "transport.h"
+#include "ref-filter.h"
#include "remote.h"
+#include "refs.h"
static const char * const ls_remote_usage[] = {
N_("git ls-remote [--heads] [--tags] [--refs] [--upload-pack=<exec>]\n"
@@ -43,10 +45,15 @@ int cmd_ls_remote(int argc, const char **argv, const char *prefix)
int show_symref_target = 0;
const char *uploadpack = NULL;
const char **pattern = NULL;
+ struct argv_array ref_prefixes = ARGV_ARRAY_INIT;
+ int i;
+ struct string_list server_options = STRING_LIST_INIT_DUP;
struct remote *remote;
struct transport *transport;
const struct ref *ref;
+ struct ref_array ref_array;
+ static struct ref_sorting *sorting = NULL, **sorting_tail = &sorting;
struct option options[] = {
OPT__QUIET(&quiet, N_("do not print remote URL")),
@@ -60,14 +67,19 @@ int cmd_ls_remote(int argc, const char **argv, const char *prefix)
OPT_BIT(0, "refs", &flags, N_("do not show peeled tags"), REF_NORMAL),
OPT_BOOL(0, "get-url", &get_url,
N_("take url.<base>.insteadOf into account")),
+ OPT_CALLBACK(0 , "sort", sorting_tail, N_("key"),
+ N_("field name to sort on"), &parse_opt_ref_sorting),
OPT_SET_INT_F(0, "exit-code", &status,
N_("exit with exit code 2 if no matching refs are found"),
2, PARSE_OPT_NOCOMPLETE),
OPT_BOOL(0, "symref", &show_symref_target,
N_("show underlying ref in addition to the object pointed by it")),
+ OPT_STRING_LIST('o', "server-option", &server_options, N_("server-specific"), N_("option to transmit")),
OPT_END()
};
+ memset(&ref_array, 0, sizeof(ref_array));
+
argc = parse_options(argc, argv, prefix, options, ls_remote_usage,
PARSE_OPT_STOP_AT_NON_OPTION);
dest = argv[0];
@@ -75,8 +87,17 @@ int cmd_ls_remote(int argc, const char **argv, const char *prefix)
if (argc > 1) {
int i;
pattern = xcalloc(argc, sizeof(const char *));
- for (i = 1; i < argc; i++)
+ for (i = 1; i < argc; i++) {
+ const char *glob;
pattern[i - 1] = xstrfmt("*/%s", argv[i]);
+
+ glob = strchr(argv[i], '*');
+ if (glob)
+ argv_array_pushf(&ref_prefixes, "%.*s",
+ (int)(glob - argv[i]), argv[i]);
+ else
+ expand_ref_prefix(&ref_prefixes, argv[i]);
+ }
}
remote = remote_get(dest);
@@ -90,28 +111,46 @@ int cmd_ls_remote(int argc, const char **argv, const char *prefix)
if (get_url) {
printf("%s\n", *remote->url);
+ UNLEAK(sorting);
return 0;
}
transport = transport_get(remote, NULL);
if (uploadpack != NULL)
transport_set_option(transport, TRANS_OPT_UPLOADPACK, uploadpack);
+ if (server_options.nr)
+ transport->server_options = &server_options;
- ref = transport_get_remote_refs(transport);
- if (transport_disconnect(transport))
+ ref = transport_get_remote_refs(transport, &ref_prefixes);
+ if (transport_disconnect(transport)) {
+ UNLEAK(sorting);
return 1;
+ }
if (!dest && !quiet)
fprintf(stderr, "From %s\n", *remote->url);
for ( ; ref; ref = ref->next) {
+ struct ref_array_item *item;
if (!check_ref_type(ref, flags))
continue;
if (!tail_match(pattern, ref->name))
continue;
+ item = ref_array_push(&ref_array, ref->name, &ref->old_oid);
+ item->symref = xstrdup_or_null(ref->symref);
+ }
+
+ if (sorting)
+ ref_array_sort(sorting, &ref_array);
+
+ for (i = 0; i < ref_array.nr; i++) {
+ const struct ref_array_item *ref = ref_array.items[i];
if (show_symref_target && ref->symref)
- printf("ref: %s\t%s\n", ref->symref, ref->name);
- printf("%s\t%s\n", oid_to_hex(&ref->old_oid), ref->name);
+ printf("ref: %s\t%s\n", ref->symref, ref->refname);
+ printf("%s\t%s\n", oid_to_hex(&ref->objectname), ref->refname);
status = 0; /* we found something */
}
+
+ UNLEAK(sorting);
+ UNLEAK(ref_array);
return status;
}
diff --git a/builtin/ls-tree.c b/builtin/ls-tree.c
index d44b4f9..409da4e 100644
--- a/builtin/ls-tree.c
+++ b/builtin/ls-tree.c
@@ -94,7 +94,7 @@ static int show_tree(const struct object_id *oid, struct strbuf *base,
char size_text[24];
if (!strcmp(type, blob_type)) {
unsigned long size;
- if (oid_object_info(oid, &size) == OBJ_BAD)
+ if (oid_object_info(the_repository, oid, &size) == OBJ_BAD)
xsnprintf(size_text, sizeof(size_text),
"BAD");
else
diff --git a/builtin/merge-tree.c b/builtin/merge-tree.c
index 32736e0..bf01e05 100644
--- a/builtin/merge-tree.c
+++ b/builtin/merge-tree.c
@@ -2,7 +2,7 @@
#include "tree-walk.h"
#include "xdiff-interface.h"
#include "blob.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "merge-blobs.h"
static const char merge_tree_usage[] = "git merge-tree <base-tree> <branch1> <branch2>";
diff --git a/builtin/merge.c b/builtin/merge.c
index 9db5a2c..d85f99b 100644
--- a/builtin/merge.c
+++ b/builtin/merge.c
@@ -14,6 +14,7 @@
#include "run-command.h"
#include "diff.h"
#include "refs.h"
+#include "refspec.h"
#include "commit.h"
#include "diffcore.h"
#include "revision.h"
@@ -280,7 +281,7 @@ out:
return rc;
}
-static void read_empty(unsigned const char *sha1, int verbose)
+static void read_empty(const struct object_id *oid, int verbose)
{
int i = 0;
const char *args[7];
@@ -290,15 +291,15 @@ static void read_empty(unsigned const char *sha1, int verbose)
args[i++] = "-v";
args[i++] = "-m";
args[i++] = "-u";
- args[i++] = EMPTY_TREE_SHA1_HEX;
- args[i++] = sha1_to_hex(sha1);
+ args[i++] = empty_tree_oid_hex();
+ args[i++] = oid_to_hex(oid);
args[i] = NULL;
if (run_command_v_opt(args, RUN_GIT_CMD))
die(_("read-tree failed"));
}
-static void reset_hard(unsigned const char *sha1, int verbose)
+static void reset_hard(const struct object_id *oid, int verbose)
{
int i = 0;
const char *args[6];
@@ -308,7 +309,7 @@ static void reset_hard(unsigned const char *sha1, int verbose)
args[i++] = "-v";
args[i++] = "--reset";
args[i++] = "-u";
- args[i++] = sha1_to_hex(sha1);
+ args[i++] = oid_to_hex(oid);
args[i] = NULL;
if (run_command_v_opt(args, RUN_GIT_CMD))
@@ -324,7 +325,7 @@ static void restore_state(const struct object_id *head,
if (is_null_oid(stash))
return;
- reset_hard(head->hash, 1);
+ reset_hard(head, 1);
args[2] = oid_to_hex(stash);
@@ -647,7 +648,7 @@ static int try_merge_strategy(const char *strategy, struct commit_list *common,
struct commit_list *remoteheads,
struct commit *head)
{
- static struct lock_file lock;
+ struct lock_file lock = LOCK_INIT;
const char *head_arg = "HEAD";
hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
@@ -805,7 +806,7 @@ static int merge_trivial(struct commit *head, struct commit_list *remoteheads)
{
struct object_id result_tree, result_commit;
struct commit_list *parents, **pptr = &parents;
- static struct lock_file lock;
+ struct lock_file lock = LOCK_INIT;
hold_locked_index(&lock, LOCK_DIE_ON_ERROR);
refresh_cache(REFRESH_QUIET);
@@ -1297,7 +1298,7 @@ int cmd_merge(int argc, const char **argv, const char *prefix)
if (remoteheads->next)
die(_("Can merge only exactly one commit into empty head"));
remote_head_oid = &remoteheads->item->object.oid;
- read_empty(remote_head_oid->hash, 0);
+ read_empty(remote_head_oid, 0);
update_ref("initial pull", "HEAD", remote_head_oid, NULL, 0,
UPDATE_REFS_DIE_ON_ERR);
goto done;
diff --git a/builtin/mktag.c b/builtin/mktag.c
index 9f5a50a..82a6e86 100644
--- a/builtin/mktag.c
+++ b/builtin/mktag.c
@@ -1,5 +1,6 @@
#include "builtin.h"
#include "tag.h"
+#include "replace-object.h"
/*
* A signature file has a very simple fixed format: four lines
@@ -24,7 +25,7 @@ static int verify_object(const struct object_id *oid, const char *expected_type)
enum object_type type;
unsigned long size;
void *buffer = read_object_file(oid, &type, &size);
- const struct object_id *repl = lookup_replace_object(oid);
+ const struct object_id *repl = lookup_replace_object(the_repository, oid);
if (buffer) {
if (type == type_from_string(expected_type))
diff --git a/builtin/mktree.c b/builtin/mktree.c
index 263c530..bb76b46 100644
--- a/builtin/mktree.c
+++ b/builtin/mktree.c
@@ -116,7 +116,7 @@ static void mktree_line(char *buf, size_t len, int nul_term_line, int allow_miss
}
/* Check the type of object identified by sha1 */
- obj_type = oid_object_info(&oid, NULL);
+ obj_type = oid_object_info(the_repository, &oid, NULL);
if (obj_type < 0) {
if (allow_missing) {
; /* no problem - missing objects are presumed to be of the right type */
diff --git a/builtin/mv.c b/builtin/mv.c
index 6d141f7..80bb967 100644
--- a/builtin/mv.c
+++ b/builtin/mv.c
@@ -72,7 +72,6 @@ static const char *add_slash(const char *path)
return path;
}
-static struct lock_file lock_file;
#define SUBMODULE_WITH_GITDIR ((const char *)1)
static void prepare_move_submodule(const char *src, int first,
@@ -131,6 +130,7 @@ int cmd_mv(int argc, const char **argv, const char *prefix)
enum update_mode { BOTH = 0, WORKING_DIRECTORY, INDEX } *modes;
struct stat st;
struct string_list src_for_dst = STRING_LIST_INIT_NODUP;
+ struct lock_file lock_file = LOCK_INIT;
git_config(git_default_config, NULL);
@@ -276,10 +276,12 @@ int cmd_mv(int argc, const char **argv, const char *prefix)
die_errno(_("renaming '%s' failed"), src);
}
if (submodule_gitfile[i]) {
- if (submodule_gitfile[i] != SUBMODULE_WITH_GITDIR)
- connect_work_tree_and_git_dir(dst, submodule_gitfile[i]);
if (!update_path_in_gitmodules(src, dst))
gitmodules_modified = 1;
+ if (submodule_gitfile[i] != SUBMODULE_WITH_GITDIR)
+ connect_work_tree_and_git_dir(dst,
+ submodule_gitfile[i],
+ 1);
}
if (mode == WORKING_DIRECTORY)
diff --git a/builtin/notes.c b/builtin/notes.c
index 921e08d..da279cd 100644
--- a/builtin/notes.c
+++ b/builtin/notes.c
@@ -14,7 +14,7 @@
#include "blob.h"
#include "pretty.h"
#include "refs.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "run-command.h"
#include "parse-options.h"
#include "string-list.h"
@@ -461,7 +461,7 @@ static int add(int argc, const char **argv, const char *prefix)
if (d.buf.len || allow_empty) {
write_note_data(&d, &new_note);
if (add_note(t, &object, &new_note, combine_notes_overwrite))
- die("BUG: combine_notes_overwrite failed");
+ BUG("combine_notes_overwrite failed");
commit_notes(t, "Notes added by 'git notes add'");
} else {
fprintf(stderr, _("Removing note for object %s\n"),
@@ -544,7 +544,7 @@ static int copy(int argc, const char **argv, const char *prefix)
}
if (add_note(t, &object, from_note, combine_notes_overwrite))
- die("BUG: combine_notes_overwrite failed");
+ BUG("combine_notes_overwrite failed");
commit_notes(t, "Notes added by 'git notes copy'");
out:
free_notes(t);
@@ -621,7 +621,7 @@ static int append_edit(int argc, const char **argv, const char *prefix)
if (d.buf.len || allow_empty) {
write_note_data(&d, &new_note);
if (add_note(t, &object, &new_note, combine_notes_overwrite))
- die("BUG: combine_notes_overwrite failed");
+ BUG("combine_notes_overwrite failed");
logmsg = xstrfmt("Notes added by 'git notes %s'", argv[0]);
} else {
fprintf(stderr, _("Removing note for object %s\n"),
@@ -831,7 +831,7 @@ static int merge(int argc, const char **argv, const char *prefix)
const char *short_ref = NULL;
if (!skip_prefix(o.local_ref, "refs/notes/", &short_ref))
- die("BUG: local ref %s is outside of refs/notes/",
+ BUG("local ref %s is outside of refs/notes/",
o.local_ref);
strbuf_addf(&merge_key, "notes.%s.mergeStrategy", short_ref);
diff --git a/builtin/pack-objects.c b/builtin/pack-objects.c
index 4bdae5a..e78f3f5 100644
--- a/builtin/pack-objects.c
+++ b/builtin/pack-objects.c
@@ -30,6 +30,19 @@
#include "list.h"
#include "packfile.h"
#include "object-store.h"
+#include "dir.h"
+
+#define IN_PACK(obj) oe_in_pack(&to_pack, obj)
+#define SIZE(obj) oe_size(&to_pack, obj)
+#define SET_SIZE(obj,size) oe_set_size(&to_pack, obj, size)
+#define DELTA_SIZE(obj) oe_delta_size(&to_pack, obj)
+#define DELTA(obj) oe_delta(&to_pack, obj)
+#define DELTA_CHILD(obj) oe_delta_child(&to_pack, obj)
+#define DELTA_SIBLING(obj) oe_delta_sibling(&to_pack, obj)
+#define SET_DELTA(obj, val) oe_set_delta(&to_pack, obj, val)
+#define SET_DELTA_SIZE(obj, val) oe_set_delta_size(&to_pack, obj, val)
+#define SET_DELTA_CHILD(obj, val) oe_set_delta_child(&to_pack, obj, val)
+#define SET_DELTA_SIBLING(obj, val) oe_set_delta_sibling(&to_pack, obj, val)
static const char *pack_usage[] = {
N_("git pack-objects --stdout [<options>...] [< <ref-list> | < <object-list>]"),
@@ -45,7 +58,7 @@ static const char *pack_usage[] = {
static struct packing_data to_pack;
static struct pack_idx_entry **written_list;
-static uint32_t nr_result, nr_written;
+static uint32_t nr_result, nr_written, nr_seen;
static int non_empty;
static int reuse_delta = 1, reuse_object = 1;
@@ -55,7 +68,8 @@ static int pack_loose_unreachable;
static int local;
static int have_non_local_packs;
static int incremental;
-static int ignore_packed_keep;
+static int ignore_packed_keep_on_disk;
+static int ignore_packed_keep_in_core;
static int allow_ofs_delta;
static struct pack_idx_option pack_idx_opts;
static const char *base_name;
@@ -80,7 +94,7 @@ static uint16_t write_bitmap_options;
static int exclude_promisor_objects;
static unsigned long delta_cache_size = 0;
-static unsigned long max_delta_cache_size = 256 * 1024 * 1024;
+static unsigned long max_delta_cache_size = DEFAULT_DELTA_CACHE_SIZE;
static unsigned long cache_max_small_delta_size = 1000;
static unsigned long window_memory_limit = 0;
@@ -127,13 +141,14 @@ static void *get_delta(struct object_entry *entry)
buf = read_object_file(&entry->idx.oid, &type, &size);
if (!buf)
die("unable to read %s", oid_to_hex(&entry->idx.oid));
- base_buf = read_object_file(&entry->delta->idx.oid, &type, &base_size);
+ base_buf = read_object_file(&DELTA(entry)->idx.oid, &type,
+ &base_size);
if (!base_buf)
die("unable to read %s",
- oid_to_hex(&entry->delta->idx.oid));
+ oid_to_hex(&DELTA(entry)->idx.oid));
delta_buf = diff_delta(base_buf, base_size,
buf, size, &delta_size, 0);
- if (!delta_buf || delta_size != entry->delta_size)
+ if (!delta_buf || delta_size != DELTA_SIZE(entry))
die("delta size changed");
free(buf);
free(base_buf);
@@ -264,10 +279,11 @@ static unsigned long write_no_reuse_object(struct hashfile *f, struct object_ent
enum object_type type;
void *buf;
struct git_istream *st = NULL;
+ const unsigned hashsz = the_hash_algo->rawsz;
if (!usable_delta) {
- if (entry->type == OBJ_BLOB &&
- entry->size > big_file_threshold &&
+ if (oe_type(entry) == OBJ_BLOB &&
+ oe_size_greater_than(&to_pack, entry, big_file_threshold) &&
(st = open_istream(&entry->idx.oid, &type, &size, NULL)) != NULL)
buf = NULL;
else {
@@ -283,15 +299,15 @@ static unsigned long write_no_reuse_object(struct hashfile *f, struct object_ent
FREE_AND_NULL(entry->delta_data);
entry->z_delta_size = 0;
} else if (entry->delta_data) {
- size = entry->delta_size;
+ size = DELTA_SIZE(entry);
buf = entry->delta_data;
entry->delta_data = NULL;
- type = (allow_ofs_delta && entry->delta->idx.offset) ?
+ type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
OBJ_OFS_DELTA : OBJ_REF_DELTA;
} else {
buf = get_delta(entry);
- size = entry->delta_size;
- type = (allow_ofs_delta && entry->delta->idx.offset) ?
+ size = DELTA_SIZE(entry);
+ type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
OBJ_OFS_DELTA : OBJ_REF_DELTA;
}
@@ -315,12 +331,12 @@ static unsigned long write_no_reuse_object(struct hashfile *f, struct object_ent
* encoding of the relative offset for the delta
* base from this object's position in the pack.
*/
- off_t ofs = entry->idx.offset - entry->delta->idx.offset;
+ off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
unsigned pos = sizeof(dheader) - 1;
dheader[pos] = ofs & 127;
while (ofs >>= 7)
dheader[--pos] = 128 | (--ofs & 127);
- if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
+ if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
if (st)
close_istream(st);
free(buf);
@@ -332,19 +348,19 @@ static unsigned long write_no_reuse_object(struct hashfile *f, struct object_ent
} else if (type == OBJ_REF_DELTA) {
/*
* Deltas with a base reference contain
- * an additional 20 bytes for the base sha1.
+ * additional bytes for the base object ID.
*/
- if (limit && hdrlen + 20 + datalen + 20 >= limit) {
+ if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
if (st)
close_istream(st);
free(buf);
return 0;
}
hashwrite(f, header, hdrlen);
- hashwrite(f, entry->delta->idx.oid.hash, 20);
- hdrlen += 20;
+ hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
+ hdrlen += hashsz;
} else {
- if (limit && hdrlen + datalen + 20 >= limit) {
+ if (limit && hdrlen + datalen + hashsz >= limit) {
if (st)
close_istream(st);
free(buf);
@@ -367,21 +383,23 @@ static unsigned long write_no_reuse_object(struct hashfile *f, struct object_ent
static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
unsigned long limit, int usable_delta)
{
- struct packed_git *p = entry->in_pack;
+ struct packed_git *p = IN_PACK(entry);
struct pack_window *w_curs = NULL;
struct revindex_entry *revidx;
off_t offset;
- enum object_type type = entry->type;
+ enum object_type type = oe_type(entry);
off_t datalen;
unsigned char header[MAX_PACK_OBJECT_HEADER],
dheader[MAX_PACK_OBJECT_HEADER];
unsigned hdrlen;
+ const unsigned hashsz = the_hash_algo->rawsz;
+ unsigned long entry_size = SIZE(entry);
- if (entry->delta)
- type = (allow_ofs_delta && entry->delta->idx.offset) ?
+ if (DELTA(entry))
+ type = (allow_ofs_delta && DELTA(entry)->idx.offset) ?
OBJ_OFS_DELTA : OBJ_REF_DELTA;
hdrlen = encode_in_pack_object_header(header, sizeof(header),
- type, entry->size);
+ type, entry_size);
offset = entry->in_pack_offset;
revidx = find_pack_revindex(p, offset);
@@ -398,7 +416,7 @@ static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
datalen -= entry->in_pack_header_size;
if (!pack_to_stdout && p->index_version == 1 &&
- check_pack_inflate(p, &w_curs, offset, datalen, entry->size)) {
+ check_pack_inflate(p, &w_curs, offset, datalen, entry_size)) {
error("corrupt packed object for %s",
oid_to_hex(&entry->idx.oid));
unuse_pack(&w_curs);
@@ -406,12 +424,12 @@ static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
}
if (type == OBJ_OFS_DELTA) {
- off_t ofs = entry->idx.offset - entry->delta->idx.offset;
+ off_t ofs = entry->idx.offset - DELTA(entry)->idx.offset;
unsigned pos = sizeof(dheader) - 1;
dheader[pos] = ofs & 127;
while (ofs >>= 7)
dheader[--pos] = 128 | (--ofs & 127);
- if (limit && hdrlen + sizeof(dheader) - pos + datalen + 20 >= limit) {
+ if (limit && hdrlen + sizeof(dheader) - pos + datalen + hashsz >= limit) {
unuse_pack(&w_curs);
return 0;
}
@@ -420,16 +438,16 @@ static off_t write_reuse_object(struct hashfile *f, struct object_entry *entry,
hdrlen += sizeof(dheader) - pos;
reused_delta++;
} else if (type == OBJ_REF_DELTA) {
- if (limit && hdrlen + 20 + datalen + 20 >= limit) {
+ if (limit && hdrlen + hashsz + datalen + hashsz >= limit) {
unuse_pack(&w_curs);
return 0;
}
hashwrite(f, header, hdrlen);
- hashwrite(f, entry->delta->idx.oid.hash, 20);
- hdrlen += 20;
+ hashwrite(f, DELTA(entry)->idx.oid.hash, hashsz);
+ hdrlen += hashsz;
reused_delta++;
} else {
- if (limit && hdrlen + datalen + 20 >= limit) {
+ if (limit && hdrlen + datalen + hashsz >= limit) {
unuse_pack(&w_curs);
return 0;
}
@@ -465,28 +483,29 @@ static off_t write_object(struct hashfile *f,
else
limit = pack_size_limit - write_offset;
- if (!entry->delta)
+ if (!DELTA(entry))
usable_delta = 0; /* no delta */
else if (!pack_size_limit)
usable_delta = 1; /* unlimited packfile */
- else if (entry->delta->idx.offset == (off_t)-1)
+ else if (DELTA(entry)->idx.offset == (off_t)-1)
usable_delta = 0; /* base was written to another pack */
- else if (entry->delta->idx.offset)
+ else if (DELTA(entry)->idx.offset)
usable_delta = 1; /* base already exists in this pack */
else
usable_delta = 0; /* base could end up in another pack */
if (!reuse_object)
to_reuse = 0; /* explicit */
- else if (!entry->in_pack)
+ else if (!IN_PACK(entry))
to_reuse = 0; /* can't reuse what we don't have */
- else if (entry->type == OBJ_REF_DELTA || entry->type == OBJ_OFS_DELTA)
+ else if (oe_type(entry) == OBJ_REF_DELTA ||
+ oe_type(entry) == OBJ_OFS_DELTA)
/* check_object() decided it for us ... */
to_reuse = usable_delta;
/* ... but pack split may override that */
- else if (entry->type != entry->in_pack_type)
+ else if (oe_type(entry) != entry->in_pack_type)
to_reuse = 0; /* pack has delta which is unusable */
- else if (entry->delta)
+ else if (DELTA(entry))
to_reuse = 0; /* we want to pack afresh */
else
to_reuse = 1; /* we have it in-pack undeltified,
@@ -538,12 +557,12 @@ static enum write_one_status write_one(struct hashfile *f,
}
/* if we are deltified, write out base object first. */
- if (e->delta) {
+ if (DELTA(e)) {
e->idx.offset = 1; /* now recurse */
- switch (write_one(f, e->delta, offset)) {
+ switch (write_one(f, DELTA(e), offset)) {
case WRITE_ONE_RECURSIVE:
/* we cannot depend on this one */
- e->delta = NULL;
+ SET_DELTA(e, NULL);
break;
default:
break;
@@ -605,34 +624,34 @@ static void add_descendants_to_write_order(struct object_entry **wo,
/* add this node... */
add_to_write_order(wo, endp, e);
/* all its siblings... */
- for (s = e->delta_sibling; s; s = s->delta_sibling) {
+ for (s = DELTA_SIBLING(e); s; s = DELTA_SIBLING(s)) {
add_to_write_order(wo, endp, s);
}
}
/* drop down a level to add left subtree nodes if possible */
- if (e->delta_child) {
+ if (DELTA_CHILD(e)) {
add_to_order = 1;
- e = e->delta_child;
+ e = DELTA_CHILD(e);
} else {
add_to_order = 0;
/* our sibling might have some children, it is next */
- if (e->delta_sibling) {
- e = e->delta_sibling;
+ if (DELTA_SIBLING(e)) {
+ e = DELTA_SIBLING(e);
continue;
}
/* go back to our parent node */
- e = e->delta;
- while (e && !e->delta_sibling) {
+ e = DELTA(e);
+ while (e && !DELTA_SIBLING(e)) {
/* we're on the right side of a subtree, keep
* going up until we can go right again */
- e = e->delta;
+ e = DELTA(e);
}
if (!e) {
/* done- we hit our original root node */
return;
}
/* pass it off to sibling at this level */
- e = e->delta_sibling;
+ e = DELTA_SIBLING(e);
}
};
}
@@ -643,7 +662,7 @@ static void add_family_to_write_order(struct object_entry **wo,
{
struct object_entry *root;
- for (root = e; root->delta; root = root->delta)
+ for (root = e; DELTA(root); root = DELTA(root))
; /* nothing */
add_descendants_to_write_order(wo, endp, root);
}
@@ -658,8 +677,8 @@ static struct object_entry **compute_write_order(void)
for (i = 0; i < to_pack.nr_objects; i++) {
objects[i].tagged = 0;
objects[i].filled = 0;
- objects[i].delta_child = NULL;
- objects[i].delta_sibling = NULL;
+ SET_DELTA_CHILD(&objects[i], NULL);
+ SET_DELTA_SIBLING(&objects[i], NULL);
}
/*
@@ -669,11 +688,11 @@ static struct object_entry **compute_write_order(void)
*/
for (i = to_pack.nr_objects; i > 0;) {
struct object_entry *e = &objects[--i];
- if (!e->delta)
+ if (!DELTA(e))
continue;
/* Mark me as the first child */
- e->delta_sibling = e->delta->delta_child;
- e->delta->delta_child = e;
+ e->delta_sibling_idx = DELTA(e)->delta_child_idx;
+ SET_DELTA_CHILD(DELTA(e), e);
}
/*
@@ -705,8 +724,8 @@ static struct object_entry **compute_write_order(void)
* And then all remaining commits and tags.
*/
for (i = last_untagged; i < to_pack.nr_objects; i++) {
- if (objects[i].type != OBJ_COMMIT &&
- objects[i].type != OBJ_TAG)
+ if (oe_type(&objects[i]) != OBJ_COMMIT &&
+ oe_type(&objects[i]) != OBJ_TAG)
continue;
add_to_write_order(wo, &wo_end, &objects[i]);
}
@@ -715,7 +734,7 @@ static struct object_entry **compute_write_order(void)
* And then all the trees.
*/
for (i = last_untagged; i < to_pack.nr_objects; i++) {
- if (objects[i].type != OBJ_TREE)
+ if (oe_type(&objects[i]) != OBJ_TREE)
continue;
add_to_write_order(wo, &wo_end, &objects[i]);
}
@@ -752,7 +771,7 @@ static off_t write_reused_pack(struct hashfile *f)
die_errno("unable to seek in reused packfile");
if (reuse_packfile_offset < 0)
- reuse_packfile_offset = reuse_packfile->pack_size - 20;
+ reuse_packfile_offset = reuse_packfile->pack_size - the_hash_algo->rawsz;
total = to_write = reuse_packfile_offset - sizeof(struct pack_header);
@@ -837,11 +856,11 @@ static void write_pack_file(void)
* If so, rewrite it like in fast-import
*/
if (pack_to_stdout) {
- hashclose(f, oid.hash, CSUM_CLOSE);
+ finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_CLOSE);
} else if (nr_written == nr_remaining) {
- hashclose(f, oid.hash, CSUM_FSYNC);
+ finalize_hashfile(f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
} else {
- int fd = hashclose(f, oid.hash, 0);
+ int fd = finalize_hashfile(f, oid.hash, 0);
fixup_pack_header_footer(fd, oid.hash, pack_tmp_name,
nr_written, oid.hash, offset);
close(fd);
@@ -878,7 +897,8 @@ static void write_pack_file(void)
if (write_bitmap_index) {
bitmap_writer_set_checksum(oid.hash);
- bitmap_writer_build_type_index(written_list, nr_written);
+ bitmap_writer_build_type_index(
+ &to_pack, written_list, nr_written);
}
finish_tmp_packfile(&tmpname, pack_tmp_name,
@@ -982,13 +1002,16 @@ static int want_found_object(int exclude, struct packed_git *p)
* Otherwise, we signal "-1" at the end to tell the caller that we do
* not know either way, and it needs to check more packs.
*/
- if (!ignore_packed_keep &&
+ if (!ignore_packed_keep_on_disk &&
+ !ignore_packed_keep_in_core &&
(!local || !have_non_local_packs))
return 1;
if (local && !p->pack_local)
return 0;
- if (ignore_packed_keep && p->pack_local && p->pack_keep)
+ if (p->pack_local &&
+ ((ignore_packed_keep_on_disk && p->pack_keep) ||
+ (ignore_packed_keep_in_core && p->pack_keep_in_core)))
return 0;
/* we don't know yet; keep looking for more packs */
@@ -1012,7 +1035,7 @@ static int want_object_in_pack(const struct object_id *oid,
int want;
struct list_head *pos;
- if (!exclude && local && has_loose_object_nonlocal(oid->hash))
+ if (!exclude && local && has_loose_object_nonlocal(oid))
return 0;
/*
@@ -1066,14 +1089,13 @@ static void create_object_entry(const struct object_id *oid,
entry = packlist_alloc(&to_pack, oid->hash, index_pos);
entry->hash = hash;
- if (type)
- entry->type = type;
+ oe_set_type(entry, type);
if (exclude)
entry->preferred_base = 1;
else
nr_result++;
if (found_pack) {
- entry->in_pack = found_pack;
+ oe_set_in_pack(&to_pack, entry, found_pack);
entry->in_pack_offset = found_offset;
}
@@ -1091,6 +1113,8 @@ static int add_object_entry(const struct object_id *oid, enum object_type type,
off_t found_offset = 0;
uint32_t index_pos;
+ display_progress(progress_state, ++nr_seen);
+
if (have_duplicate_entry(oid, exclude, &index_pos))
return 0;
@@ -1106,8 +1130,6 @@ static int add_object_entry(const struct object_id *oid, enum object_type type,
create_object_entry(oid, type, pack_name_hash(name),
exclude, name && no_try_delta(name),
index_pos, found_pack, found_offset);
-
- display_progress(progress_state, nr_result);
return 1;
}
@@ -1118,6 +1140,8 @@ static int add_object_entry_from_bitmap(const struct object_id *oid,
{
uint32_t index_pos;
+ display_progress(progress_state, ++nr_seen);
+
if (have_duplicate_entry(oid, 0, &index_pos))
return 0;
@@ -1125,8 +1149,6 @@ static int add_object_entry_from_bitmap(const struct object_id *oid,
return 0;
create_object_entry(oid, type, name_hash, 0, 0, index_pos, pack, offset);
-
- display_progress(progress_state, nr_result);
return 1;
}
@@ -1398,8 +1420,10 @@ static void cleanup_preferred_base(void)
static void check_object(struct object_entry *entry)
{
- if (entry->in_pack) {
- struct packed_git *p = entry->in_pack;
+ unsigned long canonical_size;
+
+ if (IN_PACK(entry)) {
+ struct packed_git *p = IN_PACK(entry);
struct pack_window *w_curs = NULL;
const unsigned char *base_ref = NULL;
struct object_entry *base_entry;
@@ -1407,6 +1431,8 @@ static void check_object(struct object_entry *entry)
unsigned long avail;
off_t ofs;
unsigned char *buf, c;
+ enum object_type type;
+ unsigned long in_pack_size;
buf = use_pack(p, &w_curs, entry->in_pack_offset, &avail);
@@ -1415,11 +1441,15 @@ static void check_object(struct object_entry *entry)
* since non-delta representations could still be reused.
*/
used = unpack_object_header_buffer(buf, avail,
- &entry->in_pack_type,
- &entry->size);
+ &type,
+ &in_pack_size);
if (used == 0)
goto give_up;
+ if (type < 0)
+ BUG("invalid type %d", type);
+ entry->in_pack_type = type;
+
/*
* Determine if this is a delta and if so whether we can
* reuse it or not. Otherwise let's find out as cheaply as
@@ -1428,9 +1458,10 @@ static void check_object(struct object_entry *entry)
switch (entry->in_pack_type) {
default:
/* Not a delta hence we've already got all we need. */
- entry->type = entry->in_pack_type;
+ oe_set_type(entry, entry->in_pack_type);
+ SET_SIZE(entry, in_pack_size);
entry->in_pack_header_size = used;
- if (entry->type < OBJ_COMMIT || entry->type > OBJ_BLOB)
+ if (oe_type(entry) < OBJ_COMMIT || oe_type(entry) > OBJ_BLOB)
goto give_up;
unuse_pack(&w_curs);
return;
@@ -1438,7 +1469,7 @@ static void check_object(struct object_entry *entry)
if (reuse_delta && !entry->preferred_base)
base_ref = use_pack(p, &w_curs,
entry->in_pack_offset + used, NULL);
- entry->in_pack_header_size = used + 20;
+ entry->in_pack_header_size = used + the_hash_algo->rawsz;
break;
case OBJ_OFS_DELTA:
buf = use_pack(p, &w_curs,
@@ -1484,25 +1515,29 @@ static void check_object(struct object_entry *entry)
* deltify other objects against, in order to avoid
* circular deltas.
*/
- entry->type = entry->in_pack_type;
- entry->delta = base_entry;
- entry->delta_size = entry->size;
- entry->delta_sibling = base_entry->delta_child;
- base_entry->delta_child = entry;
+ oe_set_type(entry, entry->in_pack_type);
+ SET_SIZE(entry, in_pack_size); /* delta size */
+ SET_DELTA(entry, base_entry);
+ SET_DELTA_SIZE(entry, in_pack_size);
+ entry->delta_sibling_idx = base_entry->delta_child_idx;
+ SET_DELTA_CHILD(base_entry, entry);
unuse_pack(&w_curs);
return;
}
- if (entry->type) {
+ if (oe_type(entry)) {
+ off_t delta_pos;
+
/*
* This must be a delta and we already know what the
* final object type is. Let's extract the actual
* object size from the delta header.
*/
- entry->size = get_size_from_delta(p, &w_curs,
- entry->in_pack_offset + entry->in_pack_header_size);
- if (entry->size == 0)
+ delta_pos = entry->in_pack_offset + entry->in_pack_header_size;
+ canonical_size = get_size_from_delta(p, &w_curs, delta_pos);
+ if (canonical_size == 0)
goto give_up;
+ SET_SIZE(entry, canonical_size);
unuse_pack(&w_curs);
return;
}
@@ -1516,27 +1551,34 @@ static void check_object(struct object_entry *entry)
unuse_pack(&w_curs);
}
- entry->type = oid_object_info(&entry->idx.oid, &entry->size);
- /*
- * The error condition is checked in prepare_pack(). This is
- * to permit a missing preferred base object to be ignored
- * as a preferred base. Doing so can result in a larger
- * pack file, but the transfer will still take place.
- */
+ oe_set_type(entry,
+ oid_object_info(the_repository, &entry->idx.oid, &canonical_size));
+ if (entry->type_valid) {
+ SET_SIZE(entry, canonical_size);
+ } else {
+ /*
+ * Bad object type is checked in prepare_pack(). This is
+ * to permit a missing preferred base object to be ignored
+ * as a preferred base. Doing so can result in a larger
+ * pack file, but the transfer will still take place.
+ */
+ }
}
static int pack_offset_sort(const void *_a, const void *_b)
{
const struct object_entry *a = *(struct object_entry **)_a;
const struct object_entry *b = *(struct object_entry **)_b;
+ const struct packed_git *a_in_pack = IN_PACK(a);
+ const struct packed_git *b_in_pack = IN_PACK(b);
/* avoid filesystem trashing with loose objects */
- if (!a->in_pack && !b->in_pack)
+ if (!a_in_pack && !b_in_pack)
return oidcmp(&a->idx.oid, &b->idx.oid);
- if (a->in_pack < b->in_pack)
+ if (a_in_pack < b_in_pack)
return -1;
- if (a->in_pack > b->in_pack)
+ if (a_in_pack > b_in_pack)
return 1;
return a->in_pack_offset < b->in_pack_offset ? -1 :
(a->in_pack_offset > b->in_pack_offset);
@@ -1557,29 +1599,37 @@ static int pack_offset_sort(const void *_a, const void *_b)
*/
static void drop_reused_delta(struct object_entry *entry)
{
- struct object_entry **p = &entry->delta->delta_child;
+ unsigned *idx = &to_pack.objects[entry->delta_idx - 1].delta_child_idx;
struct object_info oi = OBJECT_INFO_INIT;
+ enum object_type type;
+ unsigned long size;
+
+ while (*idx) {
+ struct object_entry *oe = &to_pack.objects[*idx - 1];
- while (*p) {
- if (*p == entry)
- *p = (*p)->delta_sibling;
+ if (oe == entry)
+ *idx = oe->delta_sibling_idx;
else
- p = &(*p)->delta_sibling;
+ idx = &oe->delta_sibling_idx;
}
- entry->delta = NULL;
+ SET_DELTA(entry, NULL);
entry->depth = 0;
- oi.sizep = &entry->size;
- oi.typep = &entry->type;
- if (packed_object_info(entry->in_pack, entry->in_pack_offset, &oi) < 0) {
+ oi.sizep = &size;
+ oi.typep = &type;
+ if (packed_object_info(the_repository, IN_PACK(entry), entry->in_pack_offset, &oi) < 0) {
/*
* We failed to get the info from this pack for some reason;
* fall back to sha1_object_info, which may find another copy.
- * And if that fails, the error will be recorded in entry->type
+ * And if that fails, the error will be recorded in oe_type(entry)
* and dealt with in prepare_pack().
*/
- entry->type = oid_object_info(&entry->idx.oid, &entry->size);
+ oe_set_type(entry,
+ oid_object_info(the_repository, &entry->idx.oid, &size));
+ } else {
+ oe_set_type(entry, type);
}
+ SET_SIZE(entry, size);
}
/*
@@ -1603,7 +1653,7 @@ static void break_delta_chains(struct object_entry *entry)
for (cur = entry, total_depth = 0;
cur;
- cur = cur->delta, total_depth++) {
+ cur = DELTA(cur), total_depth++) {
if (cur->dfs_state == DFS_DONE) {
/*
* We've already seen this object and know it isn't
@@ -1620,7 +1670,7 @@ static void break_delta_chains(struct object_entry *entry)
* is a bug.
*/
if (cur->dfs_state != DFS_NONE)
- die("BUG: confusing delta dfs state in first pass: %d",
+ BUG("confusing delta dfs state in first pass: %d",
cur->dfs_state);
/*
@@ -1628,7 +1678,7 @@ static void break_delta_chains(struct object_entry *entry)
* it's not a delta, we're done traversing, but we'll mark it
* done to save time on future traversals.
*/
- if (!cur->delta) {
+ if (!DELTA(cur)) {
cur->dfs_state = DFS_DONE;
break;
}
@@ -1651,7 +1701,7 @@ static void break_delta_chains(struct object_entry *entry)
* We keep all commits in the chain that we examined.
*/
cur->dfs_state = DFS_ACTIVE;
- if (cur->delta->dfs_state == DFS_ACTIVE) {
+ if (DELTA(cur)->dfs_state == DFS_ACTIVE) {
drop_reused_delta(cur);
cur->dfs_state = DFS_DONE;
break;
@@ -1666,7 +1716,7 @@ static void break_delta_chains(struct object_entry *entry)
* an extra "next" pointer to keep going after we reset cur->delta.
*/
for (cur = entry; cur; cur = next) {
- next = cur->delta;
+ next = DELTA(cur);
/*
* We should have a chain of zero or more ACTIVE states down to
@@ -1677,7 +1727,7 @@ static void break_delta_chains(struct object_entry *entry)
if (cur->dfs_state == DFS_DONE)
break;
else if (cur->dfs_state != DFS_ACTIVE)
- die("BUG: confusing delta dfs state in second pass: %d",
+ BUG("confusing delta dfs state in second pass: %d",
cur->dfs_state);
/*
@@ -1711,6 +1761,10 @@ static void get_object_details(void)
uint32_t i;
struct object_entry **sorted_by_offset;
+ if (progress)
+ progress_state = start_progress(_("Counting objects"),
+ to_pack.nr_objects);
+
sorted_by_offset = xcalloc(to_pack.nr_objects, sizeof(struct object_entry *));
for (i = 0; i < to_pack.nr_objects; i++)
sorted_by_offset[i] = to_pack.objects + i;
@@ -1719,9 +1773,12 @@ static void get_object_details(void)
for (i = 0; i < to_pack.nr_objects; i++) {
struct object_entry *entry = sorted_by_offset[i];
check_object(entry);
- if (big_file_threshold < entry->size)
+ if (entry->type_valid &&
+ oe_size_greater_than(&to_pack, entry, big_file_threshold))
entry->no_try_delta = 1;
+ display_progress(progress_state, i + 1);
}
+ stop_progress(&progress_state);
/*
* This must happen in a second pass, since we rely on the delta
@@ -1746,10 +1803,14 @@ static int type_size_sort(const void *_a, const void *_b)
{
const struct object_entry *a = *(struct object_entry **)_a;
const struct object_entry *b = *(struct object_entry **)_b;
+ enum object_type a_type = oe_type(a);
+ enum object_type b_type = oe_type(b);
+ unsigned long a_size = SIZE(a);
+ unsigned long b_size = SIZE(b);
- if (a->type > b->type)
+ if (a_type > b_type)
return -1;
- if (a->type < b->type)
+ if (a_type < b_type)
return 1;
if (a->hash > b->hash)
return -1;
@@ -1759,9 +1820,9 @@ static int type_size_sort(const void *_a, const void *_b)
return -1;
if (a->preferred_base < b->preferred_base)
return 1;
- if (a->size > b->size)
+ if (a_size > b_size)
return -1;
- if (a->size < b->size)
+ if (a_size < b_size)
return 1;
return a < b ? -1 : (a > b); /* newest first */
}
@@ -1814,6 +1875,46 @@ static pthread_mutex_t progress_mutex;
#endif
+/*
+ * Return the size of the object without doing any delta
+ * reconstruction (so non-deltas are true object sizes, but deltas
+ * return the size of the delta data).
+ */
+unsigned long oe_get_size_slow(struct packing_data *pack,
+ const struct object_entry *e)
+{
+ struct packed_git *p;
+ struct pack_window *w_curs;
+ unsigned char *buf;
+ enum object_type type;
+ unsigned long used, avail, size;
+
+ if (e->type_ != OBJ_OFS_DELTA && e->type_ != OBJ_REF_DELTA) {
+ read_lock();
+ if (oid_object_info(the_repository, &e->idx.oid, &size) < 0)
+ die(_("unable to get size of %s"),
+ oid_to_hex(&e->idx.oid));
+ read_unlock();
+ return size;
+ }
+
+ p = oe_in_pack(pack, e);
+ if (!p)
+ BUG("when e->type is a delta, it must belong to a pack");
+
+ read_lock();
+ w_curs = NULL;
+ buf = use_pack(p, &w_curs, e->in_pack_offset, &avail);
+ used = unpack_object_header_buffer(buf, avail, &type, &size);
+ if (used == 0)
+ die(_("unable to parse object header of %s"),
+ oid_to_hex(&e->idx.oid));
+
+ unuse_pack(&w_curs);
+ read_unlock();
+ return size;
+}
+
static int try_delta(struct unpacked *trg, struct unpacked *src,
unsigned max_depth, unsigned long *mem_usage)
{
@@ -1825,7 +1926,7 @@ static int try_delta(struct unpacked *trg, struct unpacked *src,
void *delta_buf;
/* Don't bother doing diffs between different types */
- if (trg_entry->type != src_entry->type)
+ if (oe_type(trg_entry) != oe_type(src_entry))
return -1;
/*
@@ -1836,8 +1937,8 @@ static int try_delta(struct unpacked *trg, struct unpacked *src,
* it, we will still save the transfer cost, as we already know
* the other side has it and we won't send src_entry at all.
*/
- if (reuse_delta && trg_entry->in_pack &&
- trg_entry->in_pack == src_entry->in_pack &&
+ if (reuse_delta && IN_PACK(trg_entry) &&
+ IN_PACK(trg_entry) == IN_PACK(src_entry) &&
!src_entry->preferred_base &&
trg_entry->in_pack_type != OBJ_REF_DELTA &&
trg_entry->in_pack_type != OBJ_OFS_DELTA)
@@ -1848,19 +1949,19 @@ static int try_delta(struct unpacked *trg, struct unpacked *src,
return 0;
/* Now some size filtering heuristics. */
- trg_size = trg_entry->size;
- if (!trg_entry->delta) {
- max_size = trg_size/2 - 20;
+ trg_size = SIZE(trg_entry);
+ if (!DELTA(trg_entry)) {
+ max_size = trg_size/2 - the_hash_algo->rawsz;
ref_depth = 1;
} else {
- max_size = trg_entry->delta_size;
+ max_size = DELTA_SIZE(trg_entry);
ref_depth = trg->depth;
}
max_size = (uint64_t)max_size * (max_depth - src->depth) /
(max_depth - ref_depth + 1);
if (max_size == 0)
return 0;
- src_size = src_entry->size;
+ src_size = SIZE(src_entry);
sizediff = src_size < trg_size ? trg_size - src_size : 0;
if (sizediff >= max_size)
return 0;
@@ -1922,10 +2023,14 @@ static int try_delta(struct unpacked *trg, struct unpacked *src,
delta_buf = create_delta(src->index, trg->data, trg_size, &delta_size, max_size);
if (!delta_buf)
return 0;
+ if (delta_size >= (1U << OE_DELTA_SIZE_BITS)) {
+ free(delta_buf);
+ return 0;
+ }
- if (trg_entry->delta) {
+ if (DELTA(trg_entry)) {
/* Prefer only shallower same-sized deltas. */
- if (delta_size == trg_entry->delta_size &&
+ if (delta_size == DELTA_SIZE(trg_entry) &&
src->depth + 1 >= trg->depth) {
free(delta_buf);
return 0;
@@ -1940,7 +2045,7 @@ static int try_delta(struct unpacked *trg, struct unpacked *src,
free(trg_entry->delta_data);
cache_lock();
if (trg_entry->delta_data) {
- delta_cache_size -= trg_entry->delta_size;
+ delta_cache_size -= DELTA_SIZE(trg_entry);
trg_entry->delta_data = NULL;
}
if (delta_cacheable(src_size, trg_size, delta_size)) {
@@ -1952,8 +2057,8 @@ static int try_delta(struct unpacked *trg, struct unpacked *src,
free(delta_buf);
}
- trg_entry->delta = src_entry;
- trg_entry->delta_size = delta_size;
+ SET_DELTA(trg_entry, src_entry);
+ SET_DELTA_SIZE(trg_entry, delta_size);
trg->depth = src->depth + 1;
return 1;
@@ -1961,13 +2066,13 @@ static int try_delta(struct unpacked *trg, struct unpacked *src,
static unsigned int check_delta_limit(struct object_entry *me, unsigned int n)
{
- struct object_entry *child = me->delta_child;
+ struct object_entry *child = DELTA_CHILD(me);
unsigned int m = n;
while (child) {
unsigned int c = check_delta_limit(child, n + 1);
if (m < c)
m = c;
- child = child->delta_sibling;
+ child = DELTA_SIBLING(child);
}
return m;
}
@@ -1978,7 +2083,7 @@ static unsigned long free_unpacked(struct unpacked *n)
free_delta_index(n->index);
n->index = NULL;
if (n->data) {
- freed_mem += n->entry->size;
+ freed_mem += SIZE(n->entry);
FREE_AND_NULL(n->data);
}
n->entry = NULL;
@@ -2036,7 +2141,7 @@ static void find_deltas(struct object_entry **list, unsigned *list_size,
* otherwise they would become too deep.
*/
max_depth = depth;
- if (entry->delta_child) {
+ if (DELTA_CHILD(entry)) {
max_depth -= check_delta_limit(entry, 0);
if (max_depth <= 0)
goto next;
@@ -2074,19 +2179,26 @@ static void find_deltas(struct object_entry **list, unsigned *list_size,
* between writes at that moment.
*/
if (entry->delta_data && !pack_to_stdout) {
- entry->z_delta_size = do_compress(&entry->delta_data,
- entry->delta_size);
- cache_lock();
- delta_cache_size -= entry->delta_size;
- delta_cache_size += entry->z_delta_size;
- cache_unlock();
+ unsigned long size;
+
+ size = do_compress(&entry->delta_data, DELTA_SIZE(entry));
+ if (size < (1U << OE_Z_DELTA_BITS)) {
+ entry->z_delta_size = size;
+ cache_lock();
+ delta_cache_size -= DELTA_SIZE(entry);
+ delta_cache_size += entry->z_delta_size;
+ cache_unlock();
+ } else {
+ FREE_AND_NULL(entry->delta_data);
+ entry->z_delta_size = 0;
+ }
}
/* if we made n a delta, and if n is already at max
* depth, leaving it in the window is pointless. we
* should evict it first.
*/
- if (entry->delta && max_depth <= n->depth)
+ if (DELTA(entry) && max_depth <= n->depth)
continue;
/*
@@ -2094,7 +2206,7 @@ static void find_deltas(struct object_entry **list, unsigned *list_size,
* currently deltified object, to keep it longer. It will
* be the first base object to be attempted next.
*/
- if (entry->delta) {
+ if (DELTA(entry)) {
struct unpacked swap = array[best_base];
int dist = (window + idx - best_base) % window;
int dst = best_base;
@@ -2415,13 +2527,14 @@ static void prepare_pack(int window, int depth)
for (i = 0; i < to_pack.nr_objects; i++) {
struct object_entry *entry = to_pack.objects + i;
- if (entry->delta)
+ if (DELTA(entry))
/* This happens if we decided to reuse existing
* delta from a pack. "reuse_delta &&" is implied.
*/
continue;
- if (entry->size < 50)
+ if (!entry->type_valid ||
+ oe_size_less_than(&to_pack, entry, 50))
continue;
if (entry->no_try_delta)
@@ -2429,11 +2542,11 @@ static void prepare_pack(int window, int depth)
if (!entry->preferred_base) {
nr_deltas++;
- if (entry->type < 0)
+ if (oe_type(entry) < 0)
die("unable to get type of object %s",
oid_to_hex(&entry->idx.oid));
} else {
- if (entry->type < 0) {
+ if (oe_type(entry) < 0) {
/*
* This object is not found, but we
* don't have to include it anyway.
@@ -2542,7 +2655,7 @@ static void read_object_list_from_stdin(void)
die("expected object ID, got garbage:\n %s", line);
add_preferred_base_object(p + 1);
- add_object_entry(&oid, 0, p + 1, 0);
+ add_object_entry(&oid, OBJ_NONE, p + 1, 0);
}
}
@@ -2675,7 +2788,7 @@ static void add_objects_in_unpacked_packs(struct rev_info *revs)
struct object_id oid;
struct object *o;
- if (!p->pack_local || p->pack_keep)
+ if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
continue;
if (open_pack_index(p))
die("cannot open pack index");
@@ -2706,7 +2819,7 @@ static void add_objects_in_unpacked_packs(struct rev_info *revs)
static int add_loose_object(const struct object_id *oid, const char *path,
void *data)
{
- enum object_type type = oid_object_info(oid, NULL);
+ enum object_type type = oid_object_info(the_repository, oid, NULL);
if (type < 0) {
warning("loose object at %s could not be examined", path);
@@ -2738,7 +2851,8 @@ static int has_sha1_pack_kept_or_nonlocal(const struct object_id *oid)
get_packed_git(the_repository);
while (p) {
- if ((!p->pack_local || p->pack_keep) &&
+ if ((!p->pack_local || p->pack_keep ||
+ p->pack_keep_in_core) &&
find_pack_entry_one(oid->hash, p)) {
last_found = p;
return 1;
@@ -2781,7 +2895,7 @@ static void loosen_unused_packed_objects(struct rev_info *revs)
struct object_id oid;
for (p = get_packed_git(the_repository); p; p = p->next) {
- if (!p->pack_local || p->pack_keep)
+ if (!p->pack_local || p->pack_keep || p->pack_keep_in_core)
continue;
if (open_pack_index(p))
@@ -2807,7 +2921,8 @@ static int pack_options_allow_reuse(void)
{
return pack_to_stdout &&
allow_ofs_delta &&
- !ignore_packed_keep &&
+ !ignore_packed_keep_on_disk &&
+ !ignore_packed_keep_in_core &&
(!local || !have_non_local_packs) &&
!incremental;
}
@@ -2916,6 +3031,32 @@ static void get_object_list(int ac, const char **av)
oid_array_clear(&recent_objects);
}
+static void add_extra_kept_packs(const struct string_list *names)
+{
+ struct packed_git *p;
+
+ if (!names->nr)
+ return;
+
+ for (p = get_packed_git(the_repository); p; p = p->next) {
+ const char *name = basename(p->pack_name);
+ int i;
+
+ if (!p->pack_local)
+ continue;
+
+ for (i = 0; i < names->nr; i++)
+ if (!fspathcmp(name, names->items[i].string))
+ break;
+
+ if (i < names->nr) {
+ p->pack_keep_in_core = 1;
+ ignore_packed_keep_in_core = 1;
+ continue;
+ }
+ }
+}
+
static int option_parse_index_version(const struct option *opt,
const char *arg, int unset)
{
@@ -2955,6 +3096,7 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
struct argv_array rp = ARGV_ARRAY_INIT;
int rev_list_unpacked = 0, rev_list_all = 0, rev_list_reflog = 0;
int rev_list_index = 0;
+ struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
struct option pack_objects_options[] = {
OPT_SET_INT('q', "quiet", &progress,
N_("do not show progress meter"), 0),
@@ -3019,8 +3161,10 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
N_("create thin packs")),
OPT_BOOL(0, "shallow", &shallow,
N_("create packs suitable for shallow fetches")),
- OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep,
+ OPT_BOOL(0, "honor-pack-keep", &ignore_packed_keep_on_disk,
N_("ignore packs that have companion .keep file")),
+ OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
+ N_("ignore this pack")),
OPT_INTEGER(0, "compression", &pack_compression_level,
N_("pack compression level")),
OPT_SET_INT(0, "keep-true-parents", &grafts_replace_parents,
@@ -3038,6 +3182,9 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
OPT_END(),
};
+ if (DFS_NUM_STATES > (1 << OE_DFS_STATE_BITS))
+ BUG("too many dfs states, increase OE_DFS_STATE_BITS");
+
check_replace_refs = 0;
reset_pack_idx_option(&pack_idx_opts);
@@ -3054,6 +3201,17 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
if (pack_to_stdout != !base_name || argc)
usage_with_options(pack_usage, pack_objects_options);
+ if (depth >= (1 << OE_DEPTH_BITS)) {
+ warning(_("delta chain depth %d is too deep, forcing %d"),
+ depth, (1 << OE_DEPTH_BITS) - 1);
+ depth = (1 << OE_DEPTH_BITS) - 1;
+ }
+ if (cache_max_small_delta_size >= (1U << OE_Z_DELTA_BITS)) {
+ warning(_("pack.deltaCacheLimit is too high, forcing %d"),
+ (1U << OE_Z_DELTA_BITS) - 1);
+ cache_max_small_delta_size = (1U << OE_Z_DELTA_BITS) - 1;
+ }
+
argv_array_push(&rp, "pack-objects");
if (thin) {
use_internal_rev_list = 1;
@@ -3085,6 +3243,8 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
fetch_if_missing = 0;
argv_array_push(&rp, "--exclude-promisor-objects");
}
+ if (unpack_unreachable || keep_unreachable || pack_loose_unreachable)
+ use_internal_rev_list = 1;
if (!reuse_object)
reuse_delta = 0;
@@ -3148,19 +3308,20 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
if (progress && all_progress_implied)
progress = 2;
- if (ignore_packed_keep) {
+ add_extra_kept_packs(&keep_pack_list);
+ if (ignore_packed_keep_on_disk) {
struct packed_git *p;
for (p = get_packed_git(the_repository); p; p = p->next)
if (p->pack_local && p->pack_keep)
break;
if (!p) /* no keep-able packs found */
- ignore_packed_keep = 0;
+ ignore_packed_keep_on_disk = 0;
}
if (local) {
/*
- * unlike ignore_packed_keep above, we do not want to
- * unset "local" based on looking at packs, as it
- * also covers non-local objects
+ * unlike ignore_packed_keep_on_disk above, we do not
+ * want to unset "local" based on looking at packs, as
+ * it also covers non-local objects
*/
struct packed_git *p;
for (p = get_packed_git(the_repository); p; p = p->next) {
@@ -3171,8 +3332,10 @@ int cmd_pack_objects(int argc, const char **argv, const char *prefix)
}
}
+ prepare_packing_data(&to_pack);
+
if (progress)
- progress_state = start_progress(_("Counting objects"), 0);
+ progress_state = start_progress(_("Enumerating objects"), 0);
if (!use_internal_rev_list)
read_object_list_from_stdin();
else {
diff --git a/builtin/pack-redundant.c b/builtin/pack-redundant.c
index 354478a..0494dce 100644
--- a/builtin/pack-redundant.c
+++ b/builtin/pack-redundant.c
@@ -20,7 +20,7 @@ static int load_all_packs, verbose, alt_odb;
struct llist_item {
struct llist_item *next;
- const unsigned char *sha1;
+ const struct object_id *oid;
};
static struct llist {
struct llist_item *front;
@@ -90,14 +90,14 @@ static struct llist * llist_copy(struct llist *list)
return ret;
new_item = ret->front = llist_item_get();
- new_item->sha1 = list->front->sha1;
+ new_item->oid = list->front->oid;
old_item = list->front->next;
while (old_item) {
prev = new_item;
new_item = llist_item_get();
prev->next = new_item;
- new_item->sha1 = old_item->sha1;
+ new_item->oid = old_item->oid;
old_item = old_item->next;
}
new_item->next = NULL;
@@ -108,10 +108,10 @@ static struct llist * llist_copy(struct llist *list)
static inline struct llist_item *llist_insert(struct llist *list,
struct llist_item *after,
- const unsigned char *sha1)
+ const struct object_id *oid)
{
struct llist_item *new_item = llist_item_get();
- new_item->sha1 = sha1;
+ new_item->oid = oid;
new_item->next = NULL;
if (after != NULL) {
@@ -131,21 +131,21 @@ static inline struct llist_item *llist_insert(struct llist *list,
}
static inline struct llist_item *llist_insert_back(struct llist *list,
- const unsigned char *sha1)
+ const struct object_id *oid)
{
- return llist_insert(list, list->back, sha1);
+ return llist_insert(list, list->back, oid);
}
static inline struct llist_item *llist_insert_sorted_unique(struct llist *list,
- const unsigned char *sha1, struct llist_item *hint)
+ const struct object_id *oid, struct llist_item *hint)
{
struct llist_item *prev = NULL, *l;
l = (hint == NULL) ? list->front : hint;
while (l) {
- int cmp = hashcmp(l->sha1, sha1);
+ int cmp = oidcmp(l->oid, oid);
if (cmp > 0) { /* we insert before this entry */
- return llist_insert(list, prev, sha1);
+ return llist_insert(list, prev, oid);
}
if (!cmp) { /* already exists */
return l;
@@ -154,11 +154,11 @@ static inline struct llist_item *llist_insert_sorted_unique(struct llist *list,
l = l->next;
}
/* insert at the end */
- return llist_insert_back(list, sha1);
+ return llist_insert_back(list, oid);
}
/* returns a pointer to an item in front of sha1 */
-static inline struct llist_item * llist_sorted_remove(struct llist *list, const unsigned char *sha1, struct llist_item *hint)
+static inline struct llist_item * llist_sorted_remove(struct llist *list, const struct object_id *oid, struct llist_item *hint)
{
struct llist_item *prev, *l;
@@ -166,7 +166,7 @@ redo_from_start:
l = (hint == NULL) ? list->front : hint;
prev = NULL;
while (l) {
- int cmp = hashcmp(l->sha1, sha1);
+ int cmp = oidcmp(l->oid, oid);
if (cmp > 0) /* not in list, since sorted */
return prev;
if (!cmp) { /* found */
@@ -201,7 +201,7 @@ static void llist_sorted_difference_inplace(struct llist *A,
b = B->front;
while (b) {
- hint = llist_sorted_remove(A, b->sha1, hint);
+ hint = llist_sorted_remove(A, b->oid, hint);
b = b->next;
}
}
@@ -252,13 +252,14 @@ static void cmp_two_packs(struct pack_list *p1, struct pack_list *p2)
unsigned long p1_off = 0, p2_off = 0, p1_step, p2_step;
const unsigned char *p1_base, *p2_base;
struct llist_item *p1_hint = NULL, *p2_hint = NULL;
+ const unsigned int hashsz = the_hash_algo->rawsz;
p1_base = p1->pack->index_data;
p2_base = p2->pack->index_data;
p1_base += 256 * 4 + ((p1->pack->index_version < 2) ? 4 : 8);
p2_base += 256 * 4 + ((p2->pack->index_version < 2) ? 4 : 8);
- p1_step = (p1->pack->index_version < 2) ? 24 : 20;
- p2_step = (p2->pack->index_version < 2) ? 24 : 20;
+ p1_step = hashsz + ((p1->pack->index_version < 2) ? 4 : 0);
+ p2_step = hashsz + ((p2->pack->index_version < 2) ? 4 : 0);
while (p1_off < p1->pack->num_objects * p1_step &&
p2_off < p2->pack->num_objects * p2_step)
@@ -267,9 +268,11 @@ static void cmp_two_packs(struct pack_list *p1, struct pack_list *p2)
/* cmp ~ p1 - p2 */
if (cmp == 0) {
p1_hint = llist_sorted_remove(p1->unique_objects,
- p1_base + p1_off, p1_hint);
+ (const struct object_id *)(p1_base + p1_off),
+ p1_hint);
p2_hint = llist_sorted_remove(p2->unique_objects,
- p1_base + p1_off, p2_hint);
+ (const struct object_id *)(p1_base + p1_off),
+ p2_hint);
p1_off += p1_step;
p2_off += p2_step;
continue;
@@ -359,13 +362,14 @@ static size_t sizeof_union(struct packed_git *p1, struct packed_git *p2)
size_t ret = 0;
unsigned long p1_off = 0, p2_off = 0, p1_step, p2_step;
const unsigned char *p1_base, *p2_base;
+ const unsigned int hashsz = the_hash_algo->rawsz;
p1_base = p1->index_data;
p2_base = p2->index_data;
p1_base += 256 * 4 + ((p1->index_version < 2) ? 4 : 8);
p2_base += 256 * 4 + ((p2->index_version < 2) ? 4 : 8);
- p1_step = (p1->index_version < 2) ? 24 : 20;
- p2_step = (p2->index_version < 2) ? 24 : 20;
+ p1_step = hashsz + ((p1->index_version < 2) ? 4 : 0);
+ p2_step = hashsz + ((p2->index_version < 2) ? 4 : 0);
while (p1_off < p1->num_objects * p1_step &&
p2_off < p2->num_objects * p2_step)
@@ -499,7 +503,7 @@ static void load_all_objects(void)
l = pl->all_objects->front;
while (l) {
hint = llist_insert_sorted_unique(all_objects,
- l->sha1, hint);
+ l->oid, hint);
l = l->next;
}
pl = pl->next;
@@ -558,9 +562,9 @@ static struct pack_list * add_pack(struct packed_git *p)
base = p->index_data;
base += 256 * 4 + ((p->index_version < 2) ? 4 : 8);
- step = (p->index_version < 2) ? 24 : 20;
+ step = the_hash_algo->rawsz + ((p->index_version < 2) ? 4 : 0);
while (off < p->num_objects * step) {
- llist_insert_back(l.all_objects, base + off);
+ llist_insert_back(l.all_objects, (const struct object_id *)(base + off));
off += step;
}
/* this list will be pruned in cmp_two_packs later */
@@ -601,8 +605,8 @@ int cmd_pack_redundant(int argc, const char **argv, const char *prefix)
int i;
struct pack_list *min, *red, *pl;
struct llist *ignore;
- unsigned char *sha1;
- char buf[42]; /* 40 byte sha1 + \n + \0 */
+ struct object_id *oid;
+ char buf[GIT_MAX_HEXSZ + 2]; /* hex hash + \n + \0 */
if (argc == 2 && !strcmp(argv[1], "-h"))
usage(pack_redundant_usage);
@@ -650,10 +654,10 @@ int cmd_pack_redundant(int argc, const char **argv, const char *prefix)
llist_init(&ignore);
if (!isatty(0)) {
while (fgets(buf, sizeof(buf), stdin)) {
- sha1 = xmalloc(20);
- if (get_sha1_hex(buf, sha1))
- die("Bad sha1 on stdin: %s", buf);
- llist_insert_sorted_unique(ignore, sha1, NULL);
+ oid = xmalloc(sizeof(*oid));
+ if (get_oid_hex(buf, oid))
+ die("Bad object ID on stdin: %s", buf);
+ llist_insert_sorted_unique(ignore, oid, NULL);
}
}
llist_sorted_difference_inplace(all_objects, ignore);
diff --git a/builtin/pack-refs.c b/builtin/pack-refs.c
index b106a39..f335356 100644
--- a/builtin/pack-refs.c
+++ b/builtin/pack-refs.c
@@ -1,6 +1,7 @@
#include "builtin.h"
#include "parse-options.h"
#include "refs.h"
+#include "repository.h"
static char const * const pack_refs_usage[] = {
N_("git pack-refs [<options>]"),
@@ -17,5 +18,5 @@ int cmd_pack_refs(int argc, const char **argv, const char *prefix)
};
if (parse_options(argc, argv, prefix, opts, pack_refs_usage, 0))
usage_with_options(pack_refs_usage, opts);
- return refs_pack_refs(get_main_ref_store(), flags);
+ return refs_pack_refs(get_main_ref_store(the_repository), flags);
}
diff --git a/builtin/prune-packed.c b/builtin/prune-packed.c
index 4192381..4ff525e 100644
--- a/builtin/prune-packed.c
+++ b/builtin/prune-packed.c
@@ -25,7 +25,7 @@ static int prune_object(const struct object_id *oid, const char *path,
{
int *opts = data;
- if (!has_sha1_pack(oid->hash))
+ if (!has_object_pack(oid))
return 0;
if (*opts & PRUNE_PACKED_DRY_RUN)
diff --git a/builtin/prune.c b/builtin/prune.c
index 38ced18..518ffbe 100644
--- a/builtin/prune.c
+++ b/builtin/prune.c
@@ -50,7 +50,8 @@ static int prune_object(const struct object_id *oid, const char *fullpath,
if (st.st_mtime > expire)
return 0;
if (show_only || verbose) {
- enum object_type type = oid_object_info(oid, NULL);
+ enum object_type type = oid_object_info(the_repository, oid,
+ NULL);
printf("%s %s\n", oid_to_hex(oid),
(type > 0) ? type_name(type) : "unknown");
}
diff --git a/builtin/pull.c b/builtin/pull.c
index e32d6cd..1f2ecf3 100644
--- a/builtin/pull.c
+++ b/builtin/pull.c
@@ -9,12 +9,13 @@
#include "config.h"
#include "builtin.h"
#include "parse-options.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "run-command.h"
#include "sha1-array.h"
#include "remote.h"
#include "dir.h"
#include "refs.h"
+#include "refspec.h"
#include "revision.h"
#include "submodule.h"
#include "submodule-config.h"
@@ -27,14 +28,16 @@ enum rebase_type {
REBASE_FALSE = 0,
REBASE_TRUE,
REBASE_PRESERVE,
+ REBASE_MERGES,
REBASE_INTERACTIVE
};
/**
* Parses the value of --rebase. If value is a false value, returns
* REBASE_FALSE. If value is a true value, returns REBASE_TRUE. If value is
- * "preserve", returns REBASE_PRESERVE. If value is a invalid value, dies with
- * a fatal error if fatal is true, otherwise returns REBASE_INVALID.
+ * "merges", returns REBASE_MERGES. If value is "preserve", returns
+ * REBASE_PRESERVE. If value is a invalid value, dies with a fatal error if
+ * fatal is true, otherwise returns REBASE_INVALID.
*/
static enum rebase_type parse_config_rebase(const char *key, const char *value,
int fatal)
@@ -47,6 +50,8 @@ static enum rebase_type parse_config_rebase(const char *key, const char *value,
return REBASE_TRUE;
else if (!strcmp(value, "preserve"))
return REBASE_PRESERVE;
+ else if (!strcmp(value, "merges"))
+ return REBASE_MERGES;
else if (!strcmp(value, "interactive"))
return REBASE_INTERACTIVE;
@@ -130,7 +135,7 @@ static struct option pull_options[] = {
/* Options passed to git-merge or git-rebase */
OPT_GROUP(N_("Options related to merging")),
{ OPTION_CALLBACK, 'r', "rebase", &opt_rebase,
- "false|true|preserve|interactive",
+ "false|true|merges|preserve|interactive",
N_("incorporate changes by rebasing rather than merging"),
PARSE_OPT_OPTARG, parse_opt_rebase },
OPT_PASSTHRU('n', NULL, &opt_diffstat, NULL,
@@ -539,7 +544,7 @@ static int run_fetch(const char *repo, const char **refspecs)
argv_array_push(&args, repo);
argv_array_pushv(&args, refspecs);
} else if (*refspecs)
- die("BUG: refspecs without repo?");
+ BUG("refspecs without repo?");
ret = run_command_v_opt(args.argv, RUN_GIT_CMD);
argv_array_clear(&args);
return ret;
@@ -675,12 +680,12 @@ static const char *get_upstream_branch(const char *remote)
*/
static const char *get_tracking_branch(const char *remote, const char *refspec)
{
- struct refspec *spec;
+ struct refspec_item spec;
const char *spec_src;
const char *merge_branch;
- spec = parse_fetch_refspec(1, &refspec);
- spec_src = spec->src;
+ refspec_item_init(&spec, refspec, REFSPEC_FETCH);
+ spec_src = spec.src;
if (!*spec_src || !strcmp(spec_src, "HEAD"))
spec_src = "HEAD";
else if (skip_prefix(spec_src, "heads/", &spec_src))
@@ -700,7 +705,7 @@ static const char *get_tracking_branch(const char *remote, const char *refspec)
} else
merge_branch = NULL;
- free_refspec(1, spec);
+ refspec_item_clear(&spec);
return merge_branch;
}
@@ -800,7 +805,9 @@ static int run_rebase(const struct object_id *curr_head,
argv_push_verbosity(&args);
/* Options passed to git-rebase */
- if (opt_rebase == REBASE_PRESERVE)
+ if (opt_rebase == REBASE_MERGES)
+ argv_array_push(&args, "--rebase-merges");
+ else if (opt_rebase == REBASE_PRESERVE)
argv_array_push(&args, "--preserve-merges");
else if (opt_rebase == REBASE_INTERACTIVE)
argv_array_push(&args, "--interactive");
diff --git a/builtin/push.c b/builtin/push.c
index 013c20d..9cd8e8c 100644
--- a/builtin/push.c
+++ b/builtin/push.c
@@ -4,6 +4,7 @@
#include "cache.h"
#include "config.h"
#include "refs.h"
+#include "refspec.h"
#include "run-command.h"
#include "builtin.h"
#include "remote.h"
@@ -12,12 +13,40 @@
#include "submodule.h"
#include "submodule-config.h"
#include "send-pack.h"
+#include "color.h"
static const char * const push_usage[] = {
N_("git push [<options>] [<repository> [<refspec>...]]"),
NULL,
};
+static int push_use_color = -1;
+static char push_colors[][COLOR_MAXLEN] = {
+ GIT_COLOR_RESET,
+ GIT_COLOR_RED, /* ERROR */
+};
+
+enum color_push {
+ PUSH_COLOR_RESET = 0,
+ PUSH_COLOR_ERROR = 1
+};
+
+static int parse_push_color_slot(const char *slot)
+{
+ if (!strcasecmp(slot, "reset"))
+ return PUSH_COLOR_RESET;
+ if (!strcasecmp(slot, "error"))
+ return PUSH_COLOR_ERROR;
+ return -1;
+}
+
+static const char *push_get_color(enum color_push ix)
+{
+ if (want_color_stderr(push_use_color))
+ return push_colors[ix];
+ return "";
+}
+
static int thin = 1;
static int deleterefs;
static const char *receivepack;
@@ -28,19 +57,10 @@ static enum transport_family family;
static struct push_cas_option cas;
-static const char **refspec;
-static int refspec_nr;
-static int refspec_alloc;
+static struct refspec rs = REFSPEC_INIT_PUSH;
static struct string_list push_options_config = STRING_LIST_INIT_DUP;
-static void add_refspec(const char *ref)
-{
- refspec_nr++;
- ALLOC_GROW(refspec, refspec_nr, refspec_alloc);
- refspec[refspec_nr-1] = ref;
-}
-
static const char *map_refspec(const char *ref,
struct remote *remote, struct ref *local_refs)
{
@@ -50,12 +70,11 @@ static const char *map_refspec(const char *ref,
if (count_refspec_match(ref, local_refs, &matched) != 1)
return ref;
- if (remote->push) {
- struct refspec query;
- memset(&query, 0, sizeof(struct refspec));
+ if (remote->push.nr) {
+ struct refspec_item query;
+ memset(&query, 0, sizeof(struct refspec_item));
query.src = matched->name;
- if (!query_refspecs(remote->push, remote->push_refspec_nr, &query) &&
- query.dst) {
+ if (!query_refspecs(&remote->push, &query) && query.dst) {
struct strbuf buf = STRBUF_INIT;
strbuf_addf(&buf, "%s%s:%s",
query.force ? "+" : "",
@@ -110,7 +129,7 @@ static void set_refspecs(const char **refs, int nr, const char *repo)
}
ref = map_refspec(ref, remote, local_refs);
}
- add_refspec(ref);
+ refspec_append(&rs, ref);
}
}
@@ -198,7 +217,7 @@ static void setup_push_upstream(struct remote *remote, struct branch *branch,
}
strbuf_addf(&refspec, "%s:%s", branch->refname, branch->merge[0]->src);
- add_refspec(refspec.buf);
+ refspec_append(&rs, refspec.buf);
}
static void setup_push_current(struct remote *remote, struct branch *branch)
@@ -208,7 +227,7 @@ static void setup_push_current(struct remote *remote, struct branch *branch)
if (!branch)
die(_(message_detached_head_die), remote->name);
strbuf_addf(&refspec, "%s:%s", branch->refname, branch->refname);
- add_refspec(refspec.buf);
+ refspec_append(&rs, refspec.buf);
}
static int is_workflow_triangular(struct remote *remote)
@@ -225,7 +244,7 @@ static void setup_default_push_refspecs(struct remote *remote)
switch (push_default) {
default:
case PUSH_DEFAULT_MATCHING:
- add_refspec(":");
+ refspec_append(&rs, ":");
break;
case PUSH_DEFAULT_UNSPECIFIED:
@@ -313,7 +332,8 @@ static void advise_ref_needs_force(void)
advise(_(message_advice_ref_needs_force));
}
-static int push_with_options(struct transport *transport, int flags)
+static int push_with_options(struct transport *transport, struct refspec *rs,
+ int flags)
{
int err;
unsigned int reject_reasons;
@@ -335,10 +355,12 @@ static int push_with_options(struct transport *transport, int flags)
if (verbosity > 0)
fprintf(stderr, _("Pushing to %s\n"), transport->url);
- err = transport_push(transport, refspec_nr, refspec, flags,
- &reject_reasons);
- if (err != 0)
+ err = transport_push(transport, rs, flags, &reject_reasons);
+ if (err != 0) {
+ fprintf(stderr, "%s", push_get_color(PUSH_COLOR_ERROR));
error(_("failed to push some refs to '%s'"), transport->url);
+ fprintf(stderr, "%s", push_get_color(PUSH_COLOR_RESET));
+ }
err |= transport_disconnect(transport);
if (!err)
@@ -366,6 +388,7 @@ static int do_push(const char *repo, int flags,
struct remote *remote = pushremote_get(repo);
const char **url;
int url_nr;
+ struct refspec *push_refspec = &rs;
if (!remote) {
if (repo)
@@ -386,27 +409,9 @@ static int do_push(const char *repo, int flags,
if (push_options->nr)
flags |= TRANSPORT_PUSH_OPTIONS;
- if ((flags & TRANSPORT_PUSH_ALL) && refspec) {
- if (!strcmp(*refspec, "refs/tags/*"))
- return error(_("--all and --tags are incompatible"));
- return error(_("--all can't be combined with refspecs"));
- }
-
- if ((flags & TRANSPORT_PUSH_MIRROR) && refspec) {
- if (!strcmp(*refspec, "refs/tags/*"))
- return error(_("--mirror and --tags are incompatible"));
- return error(_("--mirror can't be combined with refspecs"));
- }
-
- if ((flags & (TRANSPORT_PUSH_ALL|TRANSPORT_PUSH_MIRROR)) ==
- (TRANSPORT_PUSH_ALL|TRANSPORT_PUSH_MIRROR)) {
- return error(_("--all and --mirror are incompatible"));
- }
-
- if (!refspec && !(flags & TRANSPORT_PUSH_ALL)) {
- if (remote->push_refspec_nr) {
- refspec = remote->push_refspec;
- refspec_nr = remote->push_refspec_nr;
+ if (!push_refspec->nr && !(flags & TRANSPORT_PUSH_ALL)) {
+ if (remote->push.nr) {
+ push_refspec = &remote->push;
} else if (!(flags & TRANSPORT_PUSH_MIRROR))
setup_default_push_refspecs(remote);
}
@@ -418,7 +423,7 @@ static int do_push(const char *repo, int flags,
transport_get(remote, url[i]);
if (flags & TRANSPORT_PUSH_OPTIONS)
transport->push_options = push_options;
- if (push_with_options(transport, flags))
+ if (push_with_options(transport, push_refspec, flags))
errs++;
}
} else {
@@ -426,7 +431,7 @@ static int do_push(const char *repo, int flags,
transport_get(remote, NULL);
if (flags & TRANSPORT_PUSH_OPTIONS)
transport->push_options = push_options;
- if (push_with_options(transport, flags))
+ if (push_with_options(transport, push_refspec, flags))
errs++;
}
return !!errs;
@@ -467,6 +472,7 @@ static void set_push_cert_flags(int *flags, int v)
static int git_push_config(const char *k, const char *v, void *cb)
{
+ const char *slot_name;
int *flags = cb;
int status;
@@ -514,6 +520,16 @@ static int git_push_config(const char *k, const char *v, void *cb)
else
string_list_append(&push_options_config, v);
return 0;
+ } else if (!strcmp(k, "color.push")) {
+ push_use_color = git_config_colorbool(k, v);
+ return 0;
+ } else if (skip_prefix(k, "color.push.", &slot_name)) {
+ int slot = parse_push_color_slot(slot_name);
+ if (slot < 0)
+ return 0;
+ if (!v)
+ return config_error_nonbool(k);
+ return color_parse(v, push_colors[slot]);
}
return git_default_config(k, v, NULL);
@@ -583,6 +599,20 @@ int cmd_push(int argc, const char **argv, const char *prefix)
die(_("--delete is incompatible with --all, --mirror and --tags"));
if (deleterefs && argc < 2)
die(_("--delete doesn't make sense without any refs"));
+ if (flags & TRANSPORT_PUSH_ALL) {
+ if (tags)
+ die(_("--all and --tags are incompatible"));
+ if (argc >= 2)
+ die(_("--all can't be combined with refspecs"));
+ }
+ if (flags & TRANSPORT_PUSH_MIRROR) {
+ if (tags)
+ die(_("--mirror and --tags are incompatible"));
+ if (argc >= 2)
+ die(_("--mirror can't be combined with refspecs"));
+ }
+ if ((flags & TRANSPORT_PUSH_ALL) && (flags & TRANSPORT_PUSH_MIRROR))
+ die(_("--all and --mirror are incompatible"));
if (recurse_submodules == RECURSE_SUBMODULES_CHECK)
flags |= TRANSPORT_RECURSE_SUBMODULES_CHECK;
@@ -592,7 +622,7 @@ int cmd_push(int argc, const char **argv, const char *prefix)
flags |= TRANSPORT_RECURSE_SUBMODULES_ONLY;
if (tags)
- add_refspec("refs/tags/*");
+ refspec_append(&rs, "refs/tags/*");
if (argc > 0) {
repo = argv[0];
diff --git a/builtin/read-tree.c b/builtin/read-tree.c
index bf87a27..ebc43eb 100644
--- a/builtin/read-tree.c
+++ b/builtin/read-tree.c
@@ -107,8 +107,6 @@ static int git_read_tree_config(const char *var, const char *value, void *cb)
return git_default_config(var, value, cb);
}
-static struct lock_file lock_file;
-
int cmd_read_tree(int argc, const char **argv, const char *unused_prefix)
{
int i, stage = 0;
@@ -116,6 +114,7 @@ int cmd_read_tree(int argc, const char **argv, const char *unused_prefix)
struct tree_desc t[MAX_UNPACK_TREES];
struct unpack_trees_options opts;
int prefix_set = 0;
+ struct lock_file lock_file = LOCK_INIT;
const struct option read_tree_options[] = {
{ OPTION_CALLBACK, 0, "index-output", NULL, N_("file"),
N_("write resulting index to <file>"),
diff --git a/builtin/rebase--helper.c b/builtin/rebase--helper.c
index ad07470..f7c2a5f 100644
--- a/builtin/rebase--helper.c
+++ b/builtin/rebase--helper.c
@@ -12,8 +12,8 @@ static const char * const builtin_rebase_helper_usage[] = {
int cmd_rebase__helper(int argc, const char **argv, const char *prefix)
{
struct replay_opts opts = REPLAY_OPTS_INIT;
- unsigned flags = 0, keep_empty = 0;
- int abbreviate_commands = 0;
+ unsigned flags = 0, keep_empty = 0, rebase_merges = 0;
+ int abbreviate_commands = 0, rebase_cousins = -1;
enum {
CONTINUE = 1, ABORT, MAKE_SCRIPT, SHORTEN_OIDS, EXPAND_OIDS,
CHECK_TODO_LIST, SKIP_UNNECESSARY_PICKS, REARRANGE_SQUASH,
@@ -24,6 +24,9 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix)
OPT_BOOL(0, "keep-empty", &keep_empty, N_("keep empty commits")),
OPT_BOOL(0, "allow-empty-message", &opts.allow_empty_message,
N_("allow commits with empty messages")),
+ OPT_BOOL(0, "rebase-merges", &rebase_merges, N_("rebase merge commits")),
+ OPT_BOOL(0, "rebase-cousins", &rebase_cousins,
+ N_("keep original branch points of cousins")),
OPT_CMDMODE(0, "continue", &command, N_("continue rebase"),
CONTINUE),
OPT_CMDMODE(0, "abort", &command, N_("abort rebase"),
@@ -57,8 +60,14 @@ int cmd_rebase__helper(int argc, const char **argv, const char *prefix)
flags |= keep_empty ? TODO_LIST_KEEP_EMPTY : 0;
flags |= abbreviate_commands ? TODO_LIST_ABBREVIATE_CMDS : 0;
+ flags |= rebase_merges ? TODO_LIST_REBASE_MERGES : 0;
+ flags |= rebase_cousins > 0 ? TODO_LIST_REBASE_COUSINS : 0;
flags |= command == SHORTEN_OIDS ? TODO_LIST_SHORTEN_IDS : 0;
+ if (rebase_cousins >= 0 && !rebase_merges)
+ warning(_("--[no-]rebase-cousins has no effect without "
+ "--rebase-merges"));
+
if (command == CONTINUE && argc == 1)
return !!sequencer_continue(&opts);
if (command == ABORT && argc == 1)
diff --git a/builtin/receive-pack.c b/builtin/receive-pack.c
index c4272fb..68d36e0 100644
--- a/builtin/receive-pack.c
+++ b/builtin/receive-pack.c
@@ -7,7 +7,7 @@
#include "pkt-line.h"
#include "sideband.h"
#include "run-command.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "commit.h"
#include "object.h"
#include "remote.h"
@@ -454,21 +454,21 @@ static void hmac_sha1(unsigned char *out,
/* RFC 2104 2. (6) & (7) */
git_SHA1_Init(&ctx);
git_SHA1_Update(&ctx, k_opad, sizeof(k_opad));
- git_SHA1_Update(&ctx, out, 20);
+ git_SHA1_Update(&ctx, out, GIT_SHA1_RAWSZ);
git_SHA1_Final(out, &ctx);
}
static char *prepare_push_cert_nonce(const char *path, timestamp_t stamp)
{
struct strbuf buf = STRBUF_INIT;
- unsigned char sha1[20];
+ unsigned char sha1[GIT_SHA1_RAWSZ];
strbuf_addf(&buf, "%s:%"PRItime, path, stamp);
hmac_sha1(sha1, buf.buf, buf.len, cert_nonce_seed, strlen(cert_nonce_seed));;
strbuf_release(&buf);
/* RFC 2104 5. HMAC-SHA1-80 */
- strbuf_addf(&buf, "%"PRItime"-%.*s", stamp, 20, sha1_to_hex(sha1));
+ strbuf_addf(&buf, "%"PRItime"-%.*s", stamp, GIT_SHA1_HEXSZ, sha1_to_hex(sha1));
return strbuf_detach(&buf, NULL);
}
@@ -876,7 +876,7 @@ static void refuse_unconfigured_deny_delete_current(void)
static int command_singleton_iterator(void *cb_data, struct object_id *oid);
static int update_shallow_ref(struct command *cmd, struct shallow_info *si)
{
- static struct lock_file shallow_lock;
+ struct lock_file shallow_lock = LOCK_INIT;
struct oid_array extra = OID_ARRAY_INIT;
struct check_connected_options opt = CHECK_CONNECTED_INIT;
uint32_t mask = 1 << (cmd->index % 32);
@@ -968,7 +968,7 @@ static const char *push_to_deploy(unsigned char *sha1,
return "Working directory has unstaged changes";
/* diff-index with either HEAD or an empty tree */
- diff_index[4] = head_has_history() ? "HEAD" : EMPTY_TREE_SHA1_HEX;
+ diff_index[4] = head_has_history() ? "HEAD" : empty_tree_oid_hex();
child_process_init(&child);
child.argv = diff_index;
@@ -1378,7 +1378,7 @@ static void warn_if_skipped_connectivity_check(struct command *commands,
}
}
if (!checked_connectivity)
- die("BUG: connectivity check skipped???");
+ BUG("connectivity check skipped???");
}
static void execute_commands_non_atomic(struct command *commands,
@@ -1965,6 +1965,12 @@ int cmd_receive_pack(int argc, const char **argv, const char *prefix)
unpack_limit = receive_unpack_limit;
switch (determine_protocol_version_server()) {
+ case protocol_v2:
+ /*
+ * push support for protocol v2 has not been implemented yet,
+ * so ignore the request to use v2 and fallback to using v0.
+ */
+ break;
case protocol_v1:
/*
* v1 is just the original protocol with a version string,
diff --git a/builtin/reflog.c b/builtin/reflog.c
index a89bd1d..a48984d 100644
--- a/builtin/reflog.c
+++ b/builtin/reflog.c
@@ -154,7 +154,7 @@ static int commit_is_complete(struct commit *commit)
for (i = 0; i < found.nr; i++) {
struct commit *c =
(struct commit *)found.objects[i].item;
- if (!tree_is_complete(&c->tree->object.oid)) {
+ if (!tree_is_complete(get_commit_tree_oid(c))) {
is_incomplete = 1;
c->object.flags |= INCOMPLETE;
}
diff --git a/builtin/remote.c b/builtin/remote.c
index 805ffc0..1a82d85 100644
--- a/builtin/remote.c
+++ b/builtin/remote.c
@@ -7,6 +7,7 @@
#include "strbuf.h"
#include "run-command.h"
#include "refs.h"
+#include "refspec.h"
#include "argv-array.h"
static const char * const builtin_remote_usage[] = {
@@ -245,7 +246,9 @@ static int add(int argc, const char **argv)
struct branch_info {
char *remote_name;
struct string_list merge;
- enum { NO_REBASE, NORMAL_REBASE, INTERACTIVE_REBASE } rebase;
+ enum {
+ NO_REBASE, NORMAL_REBASE, INTERACTIVE_REBASE, REBASE_MERGES
+ } rebase;
};
static struct string_list branch_list = STRING_LIST_INIT_NODUP;
@@ -306,6 +309,8 @@ static int config_read_branches(const char *key, const char *value, void *cb)
info->rebase = v;
else if (!strcmp(value, "preserve"))
info->rebase = NORMAL_REBASE;
+ else if (!strcmp(value, "merges"))
+ info->rebase = REBASE_MERGES;
else if (!strcmp(value, "interactive"))
info->rebase = INTERACTIVE_REBASE;
}
@@ -332,10 +337,10 @@ static int get_ref_states(const struct ref *remote_refs, struct ref_states *stat
struct ref *ref, *stale_refs;
int i;
- for (i = 0; i < states->remote->fetch_refspec_nr; i++)
- if (get_fetch_map(remote_refs, states->remote->fetch + i, &tail, 1))
+ for (i = 0; i < states->remote->fetch.nr; i++)
+ if (get_fetch_map(remote_refs, &states->remote->fetch.items[i], &tail, 1))
die(_("Could not get fetch map for refspec %s"),
- states->remote->fetch_refspec[i]);
+ states->remote->fetch.raw[i]);
states->new_refs.strdup_strings = 1;
states->tracked.strdup_strings = 1;
@@ -346,8 +351,7 @@ static int get_ref_states(const struct ref *remote_refs, struct ref_states *stat
else
string_list_append(&states->tracked, abbrev_branch(ref->name));
}
- stale_refs = get_stale_heads(states->remote->fetch,
- states->remote->fetch_refspec_nr, fetch_map);
+ stale_refs = get_stale_heads(&states->remote->fetch, fetch_map);
for (ref = stale_refs; ref; ref = ref->next) {
struct string_list_item *item =
string_list_append(&states->stale, abbrev_branch(ref->name));
@@ -387,8 +391,7 @@ static int get_push_ref_states(const struct ref *remote_refs,
local_refs = get_local_heads();
push_map = copy_ref_list(remote_refs);
- match_push_refs(local_refs, &push_map, remote->push_refspec_nr,
- remote->push_refspec, MATCH_REFS_NONE);
+ match_push_refs(local_refs, &push_map, &remote->push, MATCH_REFS_NONE);
states->push.strdup_strings = 1;
for (ref = push_map; ref; ref = ref->next) {
@@ -434,14 +437,14 @@ static int get_push_ref_states_noquery(struct ref_states *states)
return 0;
states->push.strdup_strings = 1;
- if (!remote->push_refspec_nr) {
+ if (!remote->push.nr) {
item = string_list_append(&states->push, _("(matching)"));
info = item->util = xcalloc(1, sizeof(struct push_info));
info->status = PUSH_STATUS_NOTQUERIED;
info->dest = xstrdup(item->string);
}
- for (i = 0; i < remote->push_refspec_nr; i++) {
- struct refspec *spec = remote->push + i;
+ for (i = 0; i < remote->push.nr; i++) {
+ const struct refspec_item *spec = &remote->push.items[i];
if (spec->matching)
item = string_list_append(&states->push, _("(matching)"));
else if (strlen(spec->src))
@@ -461,7 +464,7 @@ static int get_head_names(const struct ref *remote_refs, struct ref_states *stat
{
struct ref *ref, *matches;
struct ref *fetch_map = NULL, **fetch_map_tail = &fetch_map;
- struct refspec refspec;
+ struct refspec_item refspec;
refspec.force = 0;
refspec.pattern = 1;
@@ -514,7 +517,7 @@ static int add_branch_for_removal(const char *refname,
const struct object_id *oid, int flags, void *cb_data)
{
struct branches_for_remote *branches = cb_data;
- struct refspec refspec;
+ struct refspec_item refspec;
struct known_remote *kr;
memset(&refspec, 0, sizeof(refspec));
@@ -585,12 +588,12 @@ static int migrate_file(struct remote *remote)
git_config_set_multivar(buf.buf, remote->url[i], "^$", 0);
strbuf_reset(&buf);
strbuf_addf(&buf, "remote.%s.push", remote->name);
- for (i = 0; i < remote->push_refspec_nr; i++)
- git_config_set_multivar(buf.buf, remote->push_refspec[i], "^$", 0);
+ for (i = 0; i < remote->push.raw_nr; i++)
+ git_config_set_multivar(buf.buf, remote->push.raw[i], "^$", 0);
strbuf_reset(&buf);
strbuf_addf(&buf, "remote.%s.fetch", remote->name);
- for (i = 0; i < remote->fetch_refspec_nr; i++)
- git_config_set_multivar(buf.buf, remote->fetch_refspec[i], "^$", 0);
+ for (i = 0; i < remote->fetch.raw_nr; i++)
+ git_config_set_multivar(buf.buf, remote->fetch.raw[i], "^$", 0);
if (remote->origin == REMOTE_REMOTES)
unlink_or_warn(git_path("remotes/%s", remote->name));
else if (remote->origin == REMOTE_BRANCHES)
@@ -645,11 +648,11 @@ static int mv(int argc, const char **argv)
strbuf_addf(&buf, "remote.%s.fetch", rename.new_name);
git_config_set_multivar(buf.buf, NULL, NULL, 1);
strbuf_addf(&old_remote_context, ":refs/remotes/%s/", rename.old_name);
- for (i = 0; i < oldremote->fetch_refspec_nr; i++) {
+ for (i = 0; i < oldremote->fetch.raw_nr; i++) {
char *ptr;
strbuf_reset(&buf2);
- strbuf_addstr(&buf2, oldremote->fetch_refspec[i]);
+ strbuf_addstr(&buf2, oldremote->fetch.raw[i]);
ptr = strstr(buf2.buf, old_remote_context.buf);
if (ptr) {
refspec_updated = 1;
@@ -833,7 +836,7 @@ static int append_ref_to_tracked_list(const char *refname,
const struct object_id *oid, int flags, void *cb_data)
{
struct ref_states *states = cb_data;
- struct refspec refspec;
+ struct refspec_item refspec;
if (flags & REF_ISSYMREF)
return 0;
@@ -862,7 +865,7 @@ static int get_remote_ref_states(const char *name,
if (query) {
transport = transport_get(states->remote, states->remote->url_nr > 0 ?
states->remote->url[0] : NULL);
- remote_refs = transport_get_remote_refs(transport);
+ remote_refs = transport_get_remote_refs(transport, NULL);
transport_disconnect(transport);
states->queried = 1;
@@ -963,9 +966,15 @@ static int show_local_info_item(struct string_list_item *item, void *cb_data)
printf(" %-*s ", show_info->width, item->string);
if (branch_info->rebase) {
- printf_ln(branch_info->rebase == INTERACTIVE_REBASE
- ? _("rebases interactively onto remote %s")
- : _("rebases onto remote %s"), merge->items[0].string);
+ const char *msg;
+ if (branch_info->rebase == INTERACTIVE_REBASE)
+ msg = _("rebases interactively onto remote %s");
+ else if (branch_info->rebase == REBASE_MERGES)
+ msg = _("rebases interactively (with merges) onto "
+ "remote %s");
+ else
+ msg = _("rebases onto remote %s");
+ printf_ln(msg, merge->items[0].string);
return 0;
} else if (show_info->any_rebase) {
printf_ln(_(" merges with remote %s"), merge->items[0].string);
diff --git a/builtin/repack.c b/builtin/repack.c
index 7bdb401..6c636e1 100644
--- a/builtin/repack.c
+++ b/builtin/repack.c
@@ -86,7 +86,8 @@ static void remove_pack_on_signal(int signo)
* have a corresponding .keep or .promisor file. These packs are not to
* be kept if we are going to pack everything into one file.
*/
-static void get_non_kept_pack_filenames(struct string_list *fname_list)
+static void get_non_kept_pack_filenames(struct string_list *fname_list,
+ const struct string_list *extra_keep)
{
DIR *dir;
struct dirent *e;
@@ -97,6 +98,14 @@ static void get_non_kept_pack_filenames(struct string_list *fname_list)
while ((e = readdir(dir)) != NULL) {
size_t len;
+ int i;
+
+ for (i = 0; i < extra_keep->nr; i++)
+ if (!fspathcmp(e->d_name, extra_keep->items[i].string))
+ break;
+ if (extra_keep->nr > 0 && i < extra_keep->nr)
+ continue;
+
if (!strip_suffix(e->d_name, ".pack", &len))
continue;
@@ -148,7 +157,7 @@ int cmd_repack(int argc, const char **argv, const char *prefix)
struct string_list rollback = STRING_LIST_INIT_NODUP;
struct string_list existing_packs = STRING_LIST_INIT_DUP;
struct strbuf line = STRBUF_INIT;
- int ext, ret, failed;
+ int i, ext, ret, failed;
FILE *out;
/* variables to be filled by option parsing */
@@ -160,6 +169,7 @@ int cmd_repack(int argc, const char **argv, const char *prefix)
const char *depth = NULL;
const char *threads = NULL;
const char *max_pack_size = NULL;
+ struct string_list keep_pack_list = STRING_LIST_INIT_NODUP;
int no_reuse_delta = 0, no_reuse_object = 0;
int no_update_server_info = 0;
int quiet = 0;
@@ -200,6 +210,8 @@ int cmd_repack(int argc, const char **argv, const char *prefix)
N_("maximum size of each packfile")),
OPT_BOOL(0, "pack-kept-objects", &pack_kept_objects,
N_("repack objects in packs marked with .keep")),
+ OPT_STRING_LIST(0, "keep-pack", &keep_pack_list, N_("name"),
+ N_("do not repack this pack")),
OPT_END()
};
@@ -230,6 +242,9 @@ int cmd_repack(int argc, const char **argv, const char *prefix)
argv_array_push(&cmd.args, "--keep-true-parents");
if (!pack_kept_objects)
argv_array_push(&cmd.args, "--honor-pack-keep");
+ for (i = 0; i < keep_pack_list.nr; i++)
+ argv_array_pushf(&cmd.args, "--keep-pack=%s",
+ keep_pack_list.items[i].string);
argv_array_push(&cmd.args, "--non-empty");
argv_array_push(&cmd.args, "--all");
argv_array_push(&cmd.args, "--reflog");
@@ -254,7 +269,7 @@ int cmd_repack(int argc, const char **argv, const char *prefix)
argv_array_push(&cmd.args, "--write-bitmap-index");
if (pack_everything & ALL_INTO_ONE) {
- get_non_kept_pack_filenames(&existing_packs);
+ get_non_kept_pack_filenames(&existing_packs, &keep_pack_list);
if (existing_packs.nr && delete_redundant) {
if (unpack_unreachable) {
diff --git a/builtin/replace.c b/builtin/replace.c
index 935647b..6da2411 100644
--- a/builtin/replace.c
+++ b/builtin/replace.c
@@ -14,12 +14,15 @@
#include "refs.h"
#include "parse-options.h"
#include "run-command.h"
+#include "object-store.h"
+#include "repository.h"
#include "tag.h"
static const char * const git_replace_usage[] = {
N_("git replace [-f] <object> <replacement>"),
N_("git replace [-f] --edit <object>"),
N_("git replace [-f] --graft <commit> [<parent>...]"),
+ N_("git replace [-f] --convert-graft-file"),
N_("git replace -d <object>..."),
N_("git replace [--format=<format>] [-l [<pattern>]]"),
NULL
@@ -53,8 +56,9 @@ static int show_reference(const char *refname, const struct object_id *oid,
if (get_oid(refname, &object))
return error("Failed to resolve '%s' as a valid ref.", refname);
- obj_type = oid_object_info(&object, NULL);
- repl_type = oid_object_info(oid, NULL);
+ obj_type = oid_object_info(the_repository, &object,
+ NULL);
+ repl_type = oid_object_info(the_repository, oid, NULL);
printf("%s (%s) -> %s (%s)\n", refname, type_name(obj_type),
oid_to_hex(oid), type_name(repl_type));
@@ -79,11 +83,11 @@ static int list_replace_refs(const char *pattern, const char *format)
else if (!strcmp(format, "long"))
data.format = REPLACE_FORMAT_LONG;
else
- die("invalid replace format '%s'\n"
- "valid formats are 'short', 'medium' and 'long'\n",
- format);
+ return error("invalid replace format '%s'\n"
+ "valid formats are 'short', 'medium' and 'long'\n",
+ format);
- for_each_replace_ref(show_reference, (void *)&data);
+ for_each_replace_ref(the_repository, show_reference, (void *)&data);
return 0;
}
@@ -134,7 +138,7 @@ static int delete_replace_ref(const char *name, const char *ref,
return 0;
}
-static void check_ref_valid(struct object_id *object,
+static int check_ref_valid(struct object_id *object,
struct object_id *prev,
struct strbuf *ref,
int force)
@@ -142,12 +146,13 @@ static void check_ref_valid(struct object_id *object,
strbuf_reset(ref);
strbuf_addf(ref, "%s%s", git_replace_ref_base, oid_to_hex(object));
if (check_refname_format(ref->buf, 0))
- die("'%s' is not a valid ref name.", ref->buf);
+ return error("'%s' is not a valid ref name.", ref->buf);
if (read_ref(ref->buf, prev))
oidclr(prev);
else if (!force)
- die("replace ref '%s' already exists", ref->buf);
+ return error("replace ref '%s' already exists", ref->buf);
+ return 0;
}
static int replace_object_oid(const char *object_ref,
@@ -161,28 +166,33 @@ static int replace_object_oid(const char *object_ref,
struct strbuf ref = STRBUF_INIT;
struct ref_transaction *transaction;
struct strbuf err = STRBUF_INIT;
+ int res = 0;
- obj_type = oid_object_info(object, NULL);
- repl_type = oid_object_info(repl, NULL);
+ obj_type = oid_object_info(the_repository, object, NULL);
+ repl_type = oid_object_info(the_repository, repl, NULL);
if (!force && obj_type != repl_type)
- die("Objects must be of the same type.\n"
- "'%s' points to a replaced object of type '%s'\n"
- "while '%s' points to a replacement object of type '%s'.",
- object_ref, type_name(obj_type),
- replace_ref, type_name(repl_type));
-
- check_ref_valid(object, &prev, &ref, force);
+ return error("Objects must be of the same type.\n"
+ "'%s' points to a replaced object of type '%s'\n"
+ "while '%s' points to a replacement object of "
+ "type '%s'.",
+ object_ref, type_name(obj_type),
+ replace_ref, type_name(repl_type));
+
+ if (check_ref_valid(object, &prev, &ref, force)) {
+ strbuf_release(&ref);
+ return -1;
+ }
transaction = ref_transaction_begin(&err);
if (!transaction ||
ref_transaction_update(transaction, ref.buf, repl, &prev,
0, NULL, &err) ||
ref_transaction_commit(transaction, &err))
- die("%s", err.buf);
+ res = error("%s", err.buf);
ref_transaction_free(transaction);
strbuf_release(&ref);
- return 0;
+ return res;
}
static int replace_object(const char *object_ref, const char *replace_ref, int force)
@@ -190,9 +200,11 @@ static int replace_object(const char *object_ref, const char *replace_ref, int f
struct object_id object, repl;
if (get_oid(object_ref, &object))
- die("Failed to resolve '%s' as a valid ref.", object_ref);
+ return error("Failed to resolve '%s' as a valid ref.",
+ object_ref);
if (get_oid(replace_ref, &repl))
- die("Failed to resolve '%s' as a valid ref.", replace_ref);
+ return error("Failed to resolve '%s' as a valid ref.",
+ replace_ref);
return replace_object_oid(object_ref, &object, replace_ref, &repl, force);
}
@@ -202,7 +214,7 @@ static int replace_object(const char *object_ref, const char *replace_ref, int f
* If "raw" is true, then the object's raw contents are printed according to
* "type". Otherwise, we pretty-print the contents for human editing.
*/
-static void export_object(const struct object_id *oid, enum object_type type,
+static int export_object(const struct object_id *oid, enum object_type type,
int raw, const char *filename)
{
struct child_process cmd = CHILD_PROCESS_INIT;
@@ -210,7 +222,7 @@ static void export_object(const struct object_id *oid, enum object_type type,
fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0666);
if (fd < 0)
- die_errno("unable to open %s for writing", filename);
+ return error_errno("unable to open %s for writing", filename);
argv_array_push(&cmd.args, "--no-replace-objects");
argv_array_push(&cmd.args, "cat-file");
@@ -223,7 +235,8 @@ static void export_object(const struct object_id *oid, enum object_type type,
cmd.out = fd;
if (run_command(&cmd))
- die("cat-file reported failure");
+ return error("cat-file reported failure");
+ return 0;
}
/*
@@ -231,14 +244,14 @@ static void export_object(const struct object_id *oid, enum object_type type,
* interpreting it as "type", and writing the result to the object database.
* The sha1 of the written object is returned via sha1.
*/
-static void import_object(struct object_id *oid, enum object_type type,
+static int import_object(struct object_id *oid, enum object_type type,
int raw, const char *filename)
{
int fd;
fd = open(filename, O_RDONLY);
if (fd < 0)
- die_errno("unable to open %s for reading", filename);
+ return error_errno("unable to open %s for reading", filename);
if (!raw && type == OBJ_TREE) {
const char *argv[] = { "mktree", NULL };
@@ -250,27 +263,40 @@ static void import_object(struct object_id *oid, enum object_type type,
cmd.in = fd;
cmd.out = -1;
- if (start_command(&cmd))
- die("unable to spawn mktree");
+ if (start_command(&cmd)) {
+ close(fd);
+ return error("unable to spawn mktree");
+ }
- if (strbuf_read(&result, cmd.out, 41) < 0)
- die_errno("unable to read from mktree");
+ if (strbuf_read(&result, cmd.out, 41) < 0) {
+ error_errno("unable to read from mktree");
+ close(fd);
+ close(cmd.out);
+ return -1;
+ }
close(cmd.out);
- if (finish_command(&cmd))
- die("mktree reported failure");
- if (get_oid_hex(result.buf, oid) < 0)
- die("mktree did not return an object name");
+ if (finish_command(&cmd)) {
+ strbuf_release(&result);
+ return error("mktree reported failure");
+ }
+ if (get_oid_hex(result.buf, oid) < 0) {
+ strbuf_release(&result);
+ return error("mktree did not return an object name");
+ }
strbuf_release(&result);
} else {
struct stat st;
int flags = HASH_FORMAT_CHECK | HASH_WRITE_OBJECT;
- if (fstat(fd, &st) < 0)
- die_errno("unable to fstat %s", filename);
+ if (fstat(fd, &st) < 0) {
+ error_errno("unable to fstat %s", filename);
+ close(fd);
+ return -1;
+ }
if (index_fd(oid, fd, &st, type, NULL, flags) < 0)
- die("unable to write object to database");
+ return error("unable to write object to database");
/* index_fd close()s fd for us */
}
@@ -278,30 +304,43 @@ static void import_object(struct object_id *oid, enum object_type type,
* No need to close(fd) here; both run-command and index-fd
* will have done it for us.
*/
+ return 0;
}
static int edit_and_replace(const char *object_ref, int force, int raw)
{
- char *tmpfile = git_pathdup("REPLACE_EDITOBJ");
+ char *tmpfile;
enum object_type type;
struct object_id old_oid, new_oid, prev;
struct strbuf ref = STRBUF_INIT;
if (get_oid(object_ref, &old_oid) < 0)
- die("Not a valid object name: '%s'", object_ref);
+ return error("Not a valid object name: '%s'", object_ref);
- type = oid_object_info(&old_oid, NULL);
+ type = oid_object_info(the_repository, &old_oid, NULL);
if (type < 0)
- die("unable to get object type for %s", oid_to_hex(&old_oid));
+ return error("unable to get object type for %s",
+ oid_to_hex(&old_oid));
- check_ref_valid(&old_oid, &prev, &ref, force);
+ if (check_ref_valid(&old_oid, &prev, &ref, force)) {
+ strbuf_release(&ref);
+ return -1;
+ }
strbuf_release(&ref);
- export_object(&old_oid, type, raw, tmpfile);
- if (launch_editor(tmpfile, NULL, NULL) < 0)
- die("editing object file failed");
- import_object(&new_oid, type, raw, tmpfile);
-
+ tmpfile = git_pathdup("REPLACE_EDITOBJ");
+ if (export_object(&old_oid, type, raw, tmpfile)) {
+ free(tmpfile);
+ return -1;
+ }
+ if (launch_editor(tmpfile, NULL, NULL) < 0) {
+ free(tmpfile);
+ return error("editing object file failed");
+ }
+ if (import_object(&new_oid, type, raw, tmpfile)) {
+ free(tmpfile);
+ return -1;
+ }
free(tmpfile);
if (!oidcmp(&old_oid, &new_oid))
@@ -310,7 +349,7 @@ static int edit_and_replace(const char *object_ref, int force, int raw)
return replace_object_oid(object_ref, &old_oid, "replacement", &new_oid, force);
}
-static void replace_parents(struct strbuf *buf, int argc, const char **argv)
+static int replace_parents(struct strbuf *buf, int argc, const char **argv)
{
struct strbuf new_parents = STRBUF_INIT;
const char *parent_start, *parent_end;
@@ -327,9 +366,15 @@ static void replace_parents(struct strbuf *buf, int argc, const char **argv)
/* prepare new parents */
for (i = 0; i < argc; i++) {
struct object_id oid;
- if (get_oid(argv[i], &oid) < 0)
- die(_("Not a valid object name: '%s'"), argv[i]);
- lookup_commit_or_die(&oid, argv[i]);
+ if (get_oid(argv[i], &oid) < 0) {
+ strbuf_release(&new_parents);
+ return error(_("Not a valid object name: '%s'"),
+ argv[i]);
+ }
+ if (!lookup_commit_reference(&oid)) {
+ strbuf_release(&new_parents);
+ return error(_("could not parse %s"), argv[i]);
+ }
strbuf_addf(&new_parents, "parent %s\n", oid_to_hex(&oid));
}
@@ -338,6 +383,7 @@ static void replace_parents(struct strbuf *buf, int argc, const char **argv)
new_parents.buf, new_parents.len);
strbuf_release(&new_parents);
+ return 0;
}
struct check_mergetag_data {
@@ -345,7 +391,7 @@ struct check_mergetag_data {
const char **argv;
};
-static void check_one_mergetag(struct commit *commit,
+static int check_one_mergetag(struct commit *commit,
struct commit_extra_header *extra,
void *data)
{
@@ -358,33 +404,35 @@ static void check_one_mergetag(struct commit *commit,
hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &tag_oid);
tag = lookup_tag(&tag_oid);
if (!tag)
- die(_("bad mergetag in commit '%s'"), ref);
+ return error(_("bad mergetag in commit '%s'"), ref);
if (parse_tag_buffer(tag, extra->value, extra->len))
- die(_("malformed mergetag in commit '%s'"), ref);
+ return error(_("malformed mergetag in commit '%s'"), ref);
/* iterate over new parents */
for (i = 1; i < mergetag_data->argc; i++) {
struct object_id oid;
if (get_oid(mergetag_data->argv[i], &oid) < 0)
- die(_("Not a valid object name: '%s'"), mergetag_data->argv[i]);
+ return error(_("Not a valid object name: '%s'"),
+ mergetag_data->argv[i]);
if (!oidcmp(&tag->tagged->oid, &oid))
- return; /* found */
+ return 0; /* found */
}
- die(_("original commit '%s' contains mergetag '%s' that is discarded; "
- "use --edit instead of --graft"), ref, oid_to_hex(&tag_oid));
+ return error(_("original commit '%s' contains mergetag '%s' that is "
+ "discarded; use --edit instead of --graft"), ref,
+ oid_to_hex(&tag_oid));
}
-static void check_mergetags(struct commit *commit, int argc, const char **argv)
+static int check_mergetags(struct commit *commit, int argc, const char **argv)
{
struct check_mergetag_data mergetag_data;
mergetag_data.argc = argc;
mergetag_data.argv = argv;
- for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
+ return for_each_mergetag(check_one_mergetag, commit, &mergetag_data);
}
-static int create_graft(int argc, const char **argv, int force)
+static int create_graft(int argc, const char **argv, int force, int gentle)
{
struct object_id old_oid, new_oid;
const char *old_ref = argv[0];
@@ -394,33 +442,81 @@ static int create_graft(int argc, const char **argv, int force)
unsigned long size;
if (get_oid(old_ref, &old_oid) < 0)
- die(_("Not a valid object name: '%s'"), old_ref);
- commit = lookup_commit_or_die(&old_oid, old_ref);
+ return error(_("Not a valid object name: '%s'"), old_ref);
+ commit = lookup_commit_reference(&old_oid);
+ if (!commit)
+ return error(_("could not parse %s"), old_ref);
buffer = get_commit_buffer(commit, &size);
strbuf_add(&buf, buffer, size);
unuse_commit_buffer(commit, buffer);
- replace_parents(&buf, argc - 1, &argv[1]);
+ if (replace_parents(&buf, argc - 1, &argv[1]) < 0) {
+ strbuf_release(&buf);
+ return -1;
+ }
if (remove_signature(&buf)) {
warning(_("the original commit '%s' has a gpg signature."), old_ref);
warning(_("the signature will be removed in the replacement commit!"));
}
- check_mergetags(commit, argc, argv);
+ if (check_mergetags(commit, argc, argv)) {
+ strbuf_release(&buf);
+ return -1;
+ }
- if (write_object_file(buf.buf, buf.len, commit_type, &new_oid))
- die(_("could not write replacement commit for: '%s'"), old_ref);
+ if (write_object_file(buf.buf, buf.len, commit_type, &new_oid)) {
+ strbuf_release(&buf);
+ return error(_("could not write replacement commit for: '%s'"),
+ old_ref);
+ }
strbuf_release(&buf);
- if (!oidcmp(&old_oid, &new_oid))
+ if (!oidcmp(&old_oid, &new_oid)) {
+ if (gentle) {
+ warning("graft for '%s' unnecessary", oid_to_hex(&old_oid));
+ return 0;
+ }
return error("new commit is the same as the old one: '%s'", oid_to_hex(&old_oid));
+ }
return replace_object_oid(old_ref, &old_oid, "replacement", &new_oid, force);
}
+static int convert_graft_file(int force)
+{
+ const char *graft_file = get_graft_file();
+ FILE *fp = fopen_or_warn(graft_file, "r");
+ struct strbuf buf = STRBUF_INIT, err = STRBUF_INIT;
+ struct argv_array args = ARGV_ARRAY_INIT;
+
+ if (!fp)
+ return -1;
+
+ while (strbuf_getline(&buf, fp) != EOF) {
+ if (*buf.buf == '#')
+ continue;
+
+ argv_array_split(&args, buf.buf);
+ if (args.argc && create_graft(args.argc, args.argv, force, 1))
+ strbuf_addf(&err, "\n\t%s", buf.buf);
+ argv_array_clear(&args);
+ }
+ fclose(fp);
+
+ strbuf_release(&buf);
+
+ if (!err.len)
+ return unlink_or_warn(graft_file);
+
+ warning(_("could not convert the following graft(s):\n%s"), err.buf);
+ strbuf_release(&err);
+
+ return -1;
+}
+
int cmd_replace(int argc, const char **argv, const char *prefix)
{
int force = 0;
@@ -432,6 +528,7 @@ int cmd_replace(int argc, const char **argv, const char *prefix)
MODE_DELETE,
MODE_EDIT,
MODE_GRAFT,
+ MODE_CONVERT_GRAFT_FILE,
MODE_REPLACE
} cmdmode = MODE_UNSPECIFIED;
struct option options[] = {
@@ -439,6 +536,7 @@ int cmd_replace(int argc, const char **argv, const char *prefix)
OPT_CMDMODE('d', "delete", &cmdmode, N_("delete replace refs"), MODE_DELETE),
OPT_CMDMODE('e', "edit", &cmdmode, N_("edit existing object"), MODE_EDIT),
OPT_CMDMODE('g', "graft", &cmdmode, N_("change a commit's parents"), MODE_GRAFT),
+ OPT_CMDMODE(0, "convert-graft-file", &cmdmode, N_("convert existing graft file"), MODE_CONVERT_GRAFT_FILE),
OPT_BOOL_F('f', "force", &force, N_("replace the ref if it exists"),
PARSE_OPT_NOCOMPLETE),
OPT_BOOL(0, "raw", &raw, N_("do not pretty-print contents for --edit")),
@@ -461,7 +559,8 @@ int cmd_replace(int argc, const char **argv, const char *prefix)
if (force &&
cmdmode != MODE_REPLACE &&
cmdmode != MODE_EDIT &&
- cmdmode != MODE_GRAFT)
+ cmdmode != MODE_GRAFT &&
+ cmdmode != MODE_CONVERT_GRAFT_FILE)
usage_msg_opt("-f only makes sense when writing a replacement",
git_replace_usage, options);
@@ -492,7 +591,13 @@ int cmd_replace(int argc, const char **argv, const char *prefix)
if (argc < 1)
usage_msg_opt("-g needs at least one argument",
git_replace_usage, options);
- return create_graft(argc, argv, force);
+ return create_graft(argc, argv, force, 0);
+
+ case MODE_CONVERT_GRAFT_FILE:
+ if (argc != 0)
+ usage_msg_opt("--convert-graft-file takes no argument",
+ git_replace_usage, options);
+ return !!convert_graft_file(force);
case MODE_LIST:
if (argc > 1)
@@ -501,6 +606,6 @@ int cmd_replace(int argc, const char **argv, const char *prefix)
return list_replace_refs(argv[0], format);
default:
- die("BUG: invalid cmdmode %d", (int)cmdmode);
+ BUG("invalid cmdmode %d", (int)cmdmode);
}
}
diff --git a/builtin/reset.c b/builtin/reset.c
index 7f1c3f0..a862c70 100644
--- a/builtin/reset.c
+++ b/builtin/reset.c
@@ -314,7 +314,7 @@ int cmd_reset(int argc, const char **argv, const char *prefix)
unborn = !strcmp(rev, "HEAD") && get_oid("HEAD", &oid);
if (unborn) {
/* reset on unborn branch: treat as reset to empty tree */
- hashcpy(oid.hash, EMPTY_TREE_SHA1_BIN);
+ oidcpy(&oid, the_hash_algo->empty_tree);
} else if (!pathspec.nr) {
struct commit *commit;
if (get_oid_committish(rev, &oid))
diff --git a/builtin/rev-parse.c b/builtin/rev-parse.c
index 36b2087..55c0b90 100644
--- a/builtin/rev-parse.c
+++ b/builtin/rev-parse.c
@@ -887,8 +887,8 @@ int cmd_rev_parse(int argc, const char **argv, const char *prefix)
if (read_cache() < 0)
die(_("Could not read the index"));
if (the_index.split_index) {
- const unsigned char *sha1 = the_index.split_index->base_sha1;
- const char *path = git_path("sharedindex.%s", sha1_to_hex(sha1));
+ const struct object_id *oid = &the_index.split_index->base_oid;
+ const char *path = git_path("sharedindex.%s", oid_to_hex(oid));
strbuf_reset(&buf);
puts(relative_path(path, prefix, &buf));
}
diff --git a/builtin/rm.c b/builtin/rm.c
index 5b6fc7e..65b448e 100644
--- a/builtin/rm.c
+++ b/builtin/rm.c
@@ -233,8 +233,6 @@ static int check_local_mod(struct object_id *head, int index_only)
return errs;
}
-static struct lock_file lock_file;
-
static int show_only = 0, force = 0, index_only = 0, recursive = 0, quiet = 0;
static int ignore_unmatch = 0;
@@ -251,6 +249,7 @@ static struct option builtin_rm_options[] = {
int cmd_rm(int argc, const char **argv, const char *prefix)
{
+ struct lock_file lock_file = LOCK_INIT;
int i;
struct pathspec pathspec;
char *seen;
diff --git a/builtin/send-pack.c b/builtin/send-pack.c
index fc4f0bb..4923b10 100644
--- a/builtin/send-pack.c
+++ b/builtin/send-pack.c
@@ -14,6 +14,7 @@
#include "sha1-array.h"
#include "gpg-interface.h"
#include "gettext.h"
+#include "protocol.h"
static const char * const send_pack_usage[] = {
N_("git send-pack [--all | --mirror] [--dry-run] [--force] "
@@ -125,8 +126,7 @@ static int send_pack_config(const char *k, const char *v, void *cb)
int cmd_send_pack(int argc, const char **argv, const char *prefix)
{
- int i, nr_refspecs = 0;
- const char **refspecs = NULL;
+ struct refspec rs = REFSPEC_INIT_PUSH;
const char *remote_name = NULL;
struct remote *remote = NULL;
const char *dest = NULL;
@@ -154,6 +154,7 @@ int cmd_send_pack(int argc, const char **argv, const char *prefix)
int progress = -1;
int from_stdin = 0;
struct push_cas_option cas = {0};
+ struct packet_reader reader;
struct option options[] = {
OPT__VERBOSITY(&verbose),
@@ -187,8 +188,7 @@ int cmd_send_pack(int argc, const char **argv, const char *prefix)
argc = parse_options(argc, argv, prefix, options, send_pack_usage, 0);
if (argc > 0) {
dest = argv[0];
- refspecs = (const char **)(argv + 1);
- nr_refspecs = argc - 1;
+ refspec_appendn(&rs, argv + 1, argc - 1);
}
if (!dest)
@@ -207,31 +207,23 @@ int cmd_send_pack(int argc, const char **argv, const char *prefix)
args.push_options = push_options.nr ? &push_options : NULL;
if (from_stdin) {
- struct argv_array all_refspecs = ARGV_ARRAY_INIT;
-
- for (i = 0; i < nr_refspecs; i++)
- argv_array_push(&all_refspecs, refspecs[i]);
-
if (args.stateless_rpc) {
const char *buf;
while ((buf = packet_read_line(0, NULL)))
- argv_array_push(&all_refspecs, buf);
+ refspec_append(&rs, buf);
} else {
struct strbuf line = STRBUF_INIT;
while (strbuf_getline(&line, stdin) != EOF)
- argv_array_push(&all_refspecs, line.buf);
+ refspec_append(&rs, line.buf);
strbuf_release(&line);
}
-
- refspecs = all_refspecs.argv;
- nr_refspecs = all_refspecs.argc;
}
/*
* --all and --mirror are incompatible; neither makes sense
* with any refspecs.
*/
- if ((nr_refspecs > 0 && (send_all || args.send_mirror)) ||
+ if ((rs.nr > 0 && (send_all || args.send_mirror)) ||
(send_all && args.send_mirror))
usage_with_options(send_pack_usage, options);
@@ -256,10 +248,22 @@ int cmd_send_pack(int argc, const char **argv, const char *prefix)
args.verbose ? CONNECT_VERBOSE : 0);
}
- get_remote_heads(fd[0], NULL, 0, &remote_refs, REF_NORMAL,
- &extra_have, &shallow);
-
- transport_verify_remote_names(nr_refspecs, refspecs);
+ packet_reader_init(&reader, fd[0], NULL, 0,
+ PACKET_READ_CHOMP_NEWLINE |
+ PACKET_READ_GENTLE_ON_EOF);
+
+ switch (discover_version(&reader)) {
+ case protocol_v2:
+ die("support for protocol v2 not implemented yet");
+ break;
+ case protocol_v1:
+ case protocol_v0:
+ get_remote_heads(&reader, &remote_refs, REF_NORMAL,
+ &extra_have, &shallow);
+ break;
+ case protocol_unknown_version:
+ BUG("unknown protocol version");
+ }
local_refs = get_local_heads();
@@ -271,7 +275,7 @@ int cmd_send_pack(int argc, const char **argv, const char *prefix)
flags |= MATCH_REFS_MIRROR;
/* match them up */
- if (match_push_refs(local_refs, &remote_refs, nr_refspecs, refspecs, flags))
+ if (match_push_refs(local_refs, &remote_refs, &rs, flags))
return -1;
if (!is_empty_cas(&cas))
diff --git a/builtin/serve.c b/builtin/serve.c
new file mode 100644
index 0000000..d3fd240
--- /dev/null
+++ b/builtin/serve.c
@@ -0,0 +1,30 @@
+#include "cache.h"
+#include "builtin.h"
+#include "parse-options.h"
+#include "serve.h"
+
+static char const * const serve_usage[] = {
+ N_("git serve [<options>]"),
+ NULL
+};
+
+int cmd_serve(int argc, const char **argv, const char *prefix)
+{
+ struct serve_options opts = SERVE_OPTIONS_INIT;
+
+ struct option options[] = {
+ OPT_BOOL(0, "stateless-rpc", &opts.stateless_rpc,
+ N_("quit after a single request/response exchange")),
+ OPT_BOOL(0, "advertise-capabilities", &opts.advertise_capabilities,
+ N_("exit immediately after advertising capabilities")),
+ OPT_END()
+ };
+
+ /* ignore all unknown cmdline switches for now */
+ argc = parse_options(argc, argv, prefix, options, serve_usage,
+ PARSE_OPT_KEEP_DASHDASH |
+ PARSE_OPT_KEEP_UNKNOWN);
+ serve(&opts);
+
+ return 0;
+}
diff --git a/builtin/submodule--helper.c b/builtin/submodule--helper.c
index a404df3..bd250ca 100644
--- a/builtin/submodule--helper.c
+++ b/builtin/submodule--helper.c
@@ -12,6 +12,7 @@
#include "run-command.h"
#include "remote.h"
#include "refs.h"
+#include "refspec.h"
#include "connect.h"
#include "revision.h"
#include "diffcore.h"
@@ -455,7 +456,7 @@ static void init_submodule(const char *path, const char *prefix,
displaypath = get_submodule_displaypath(path, prefix);
- sub = submodule_from_path(&null_oid, path);
+ sub = submodule_from_path(the_repository, &null_oid, path);
if (!sub)
die(_("No url found for submodule path '%s' in .gitmodules"),
@@ -596,8 +597,12 @@ static void print_status(unsigned int flags, char state, const char *path,
printf("%c%s %s", state, oid_to_hex(oid), displaypath);
- if (state == ' ' || state == '+')
- printf(" (%s)", compute_rev_name(path, oid_to_hex(oid)));
+ if (state == ' ' || state == '+') {
+ const char *name = compute_rev_name(path, oid_to_hex(oid));
+
+ if (name)
+ printf(" (%s)", name);
+ }
printf("\n");
}
@@ -622,7 +627,7 @@ static void status_submodule(const char *path, const struct object_id *ce_oid,
struct rev_info rev;
int diff_files_result;
- if (!submodule_from_path(&null_oid, path))
+ if (!submodule_from_path(the_repository, &null_oid, path))
die(_("no submodule mapping found in .gitmodules for path '%s'"),
path);
@@ -746,7 +751,7 @@ static int module_name(int argc, const char **argv, const char *prefix)
if (argc != 2)
usage(_("git submodule--helper name <path>"));
- sub = submodule_from_path(&null_oid, argv[1]);
+ sub = submodule_from_path(the_repository, &null_oid, argv[1]);
if (!sub)
die(_("no submodule mapping found in .gitmodules for path '%s'"),
@@ -777,7 +782,7 @@ static void sync_submodule(const char *path, const char *prefix,
if (!is_submodule_active(the_repository, path))
return;
- sub = submodule_from_path(&null_oid, path);
+ sub = submodule_from_path(the_repository, &null_oid, path);
if (sub && sub->url) {
if (starts_with_dot_dot_slash(sub->url) ||
@@ -930,7 +935,7 @@ static void deinit_submodule(const char *path, const char *prefix,
struct strbuf sb_config = STRBUF_INIT;
char *sub_git_dir = xstrfmt("%s/.git", path);
- sub = submodule_from_path(&null_oid, path);
+ sub = submodule_from_path(the_repository, &null_oid, path);
if (!sub || !sub->name)
goto cleanup;
@@ -1061,7 +1066,7 @@ static int module_deinit(int argc, const char **argv, const char *prefix)
}
static int clone_submodule(const char *path, const char *gitdir, const char *url,
- const char *depth, struct string_list *reference,
+ const char *depth, struct string_list *reference, int dissociate,
int quiet, int progress)
{
struct child_process cp = CHILD_PROCESS_INIT;
@@ -1080,6 +1085,8 @@ static int clone_submodule(const char *path, const char *gitdir, const char *url
argv_array_pushl(&cp.args, "--reference",
item->string, NULL);
}
+ if (dissociate)
+ argv_array_push(&cp.args, "--dissociate");
if (gitdir && *gitdir)
argv_array_pushl(&cp.args, "--separate-git-dir", gitdir, NULL);
@@ -1195,6 +1202,7 @@ static int module_clone(int argc, const char **argv, const char *prefix)
char *p, *path = NULL, *sm_gitdir;
struct strbuf sb = STRBUF_INIT;
struct string_list reference = STRING_LIST_INIT_NODUP;
+ int dissociate = 0;
char *sm_alternate = NULL, *error_strategy = NULL;
struct option module_clone_options[] = {
@@ -1213,6 +1221,8 @@ static int module_clone(int argc, const char **argv, const char *prefix)
OPT_STRING_LIST(0, "reference", &reference,
N_("repo"),
N_("reference repository")),
+ OPT_BOOL(0, "dissociate", &dissociate,
+ N_("use --reference only while cloning")),
OPT_STRING(0, "depth", &depth,
N_("string"),
N_("depth for shallow clones")),
@@ -1252,7 +1262,7 @@ static int module_clone(int argc, const char **argv, const char *prefix)
prepare_possible_alternates(name, &reference);
- if (clone_submodule(path, sm_gitdir, url, depth, &reference,
+ if (clone_submodule(path, sm_gitdir, url, depth, &reference, dissociate,
quiet, progress))
die(_("clone of '%s' into submodule path '%s' failed"),
url, path);
@@ -1264,8 +1274,7 @@ static int module_clone(int argc, const char **argv, const char *prefix)
strbuf_reset(&sb);
}
- /* Connect module worktree and git dir */
- connect_work_tree_and_git_dir(path, sm_gitdir);
+ connect_work_tree_and_git_dir(path, sm_gitdir, 0);
p = git_pathdup_submodule(path, "config");
if (!p)
@@ -1305,6 +1314,7 @@ struct submodule_update_clone {
int quiet;
int recommend_shallow;
struct string_list references;
+ int dissociate;
const char *depth;
const char *recursive_prefix;
const char *prefix;
@@ -1320,7 +1330,7 @@ struct submodule_update_clone {
int failed_clones_nr, failed_clones_alloc;
};
#define SUBMODULE_UPDATE_CLONE_INIT {0, MODULE_LIST_INIT, 0, \
- SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, \
+ SUBMODULE_UPDATE_STRATEGY_INIT, 0, 0, -1, STRING_LIST_INIT_DUP, 0, \
NULL, NULL, NULL, \
STRING_LIST_INIT_DUP, 0, NULL, 0, 0}
@@ -1372,7 +1382,7 @@ static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
goto cleanup;
}
- sub = submodule_from_path(&null_oid, ce->name);
+ sub = submodule_from_path(the_repository, &null_oid, ce->name);
if (suc->recursive_prefix)
displaypath = relative_path(suc->recursive_prefix,
@@ -1447,6 +1457,8 @@ static int prepare_to_clone_next_submodule(const struct cache_entry *ce,
for_each_string_list_item(item, &suc->references)
argv_array_pushl(&child->args, "--reference", item->string, NULL);
}
+ if (suc->dissociate)
+ argv_array_push(&child->args, "--dissociate");
if (suc->depth)
argv_array_push(&child->args, suc->depth);
@@ -1580,6 +1592,8 @@ static int update_clone(int argc, const char **argv, const char *prefix)
N_("rebase, merge, checkout or none")),
OPT_STRING_LIST(0, "reference", &suc.references, N_("repo"),
N_("reference repository")),
+ OPT_BOOL(0, "dissociate", &suc.dissociate,
+ N_("use --reference only while cloning")),
OPT_STRING(0, "depth", &suc.depth, "<depth>",
N_("Create a shallow clone truncated to the "
"specified number of revisions")),
@@ -1655,7 +1669,7 @@ static const char *remote_submodule_branch(const char *path)
const char *branch = NULL;
char *key;
- sub = submodule_from_path(&null_oid, path);
+ sub = submodule_from_path(the_repository, &null_oid, path);
if (!sub)
return NULL;
@@ -1740,13 +1754,14 @@ static int push_check(int argc, const char **argv, const char *prefix)
/* Check the refspec */
if (argc > 2) {
- int i, refspec_nr = argc - 2;
+ int i;
struct ref *local_refs = get_local_heads();
- struct refspec *refspec = parse_push_refspec(refspec_nr,
- argv + 2);
+ struct refspec refspec = REFSPEC_INIT_PUSH;
- for (i = 0; i < refspec_nr; i++) {
- struct refspec *rs = refspec + i;
+ refspec_appendn(&refspec, argv + 2, argc - 2);
+
+ for (i = 0; i < refspec.nr; i++) {
+ const struct refspec_item *rs = &refspec.items[i];
if (rs->pattern || rs->matching)
continue;
@@ -1773,7 +1788,7 @@ static int push_check(int argc, const char **argv, const char *prefix)
rs->src);
}
}
- free_refspec(refspec_nr, refspec);
+ refspec_clear(&refspec);
}
free(head);
@@ -1822,6 +1837,29 @@ static int is_active(int argc, const char **argv, const char *prefix)
return !is_submodule_active(the_repository, argv[1]);
}
+/*
+ * Exit non-zero if any of the submodule names given on the command line is
+ * invalid. If no names are given, filter stdin to print only valid names
+ * (which is primarily intended for testing).
+ */
+static int check_name(int argc, const char **argv, const char *prefix)
+{
+ if (argc > 1) {
+ while (*++argv) {
+ if (check_submodule_name(*argv) < 0)
+ return 1;
+ }
+ } else {
+ struct strbuf buf = STRBUF_INIT;
+ while (strbuf_getline(&buf, stdin) != EOF) {
+ if (!check_submodule_name(buf.buf))
+ printf("%s\n", buf.buf);
+ }
+ strbuf_release(&buf);
+ }
+ return 0;
+}
+
#define SUPPORT_SUPER_PREFIX (1<<0)
struct cmd_struct {
@@ -1847,6 +1885,7 @@ static struct cmd_struct commands[] = {
{"push-check", push_check, 0},
{"absorb-git-dirs", absorb_git_dirs, SUPPORT_SUPER_PREFIX},
{"is-active", is_active, 0},
+ {"check-name", check_name, 0},
};
int cmd_submodule__helper(int argc, const char **argv, const char *prefix)
diff --git a/builtin/tag.c b/builtin/tag.c
index 8cff6d0..5d0dd11 100644
--- a/builtin/tag.c
+++ b/builtin/tag.c
@@ -118,7 +118,7 @@ static int verify_tag(const char *name, const char *ref,
return -1;
if (format->format)
- pretty_print_ref(name, oid->hash, format);
+ pretty_print_ref(name, oid, format);
return 0;
}
@@ -212,7 +212,7 @@ static void create_tag(const struct object_id *object, const char *tag,
struct strbuf header = STRBUF_INIT;
char *path = NULL;
- type = oid_object_info(object, NULL);
+ type = oid_object_info(the_repository, object, NULL);
if (type <= OBJ_NONE)
die(_("bad object type."));
@@ -298,7 +298,7 @@ static void create_reflog_msg(const struct object_id *oid, struct strbuf *sb)
}
strbuf_addstr(sb, " (");
- type = oid_object_info(oid, NULL);
+ type = oid_object_info(the_repository, oid, NULL);
switch (type) {
default:
strbuf_addstr(sb, "object of unknown type");
diff --git a/builtin/unpack-objects.c b/builtin/unpack-objects.c
index b7755c6..6e81ca8 100644
--- a/builtin/unpack-objects.c
+++ b/builtin/unpack-objects.c
@@ -199,7 +199,7 @@ static int check_object(struct object *obj, int type, void *data, struct fsck_op
if (!(obj->flags & FLAG_OPEN)) {
unsigned long size;
- int type = oid_object_info(&obj->oid, &size);
+ int type = oid_object_info(the_repository, &obj->oid, &size);
if (type != obj->type || type <= 0)
die("object of unexpected type");
obj->flags |= FLAG_WRITTEN;
@@ -210,7 +210,7 @@ static int check_object(struct object *obj, int type, void *data, struct fsck_op
if (!obj_buf)
die("Whoops! Cannot find object '%s'", oid_to_hex(&obj->oid));
if (fsck_object(obj, obj_buf->buffer, obj_buf->size, &fsck_options))
- die("Error in object");
+ die("fsck error in packed object");
fsck_options.walk = check_object;
if (fsck_walk(obj, NULL, &fsck_options))
die("Error on reachable objects of %s", oid_to_hex(&obj->oid));
@@ -572,8 +572,11 @@ int cmd_unpack_objects(int argc, const char **argv, const char *prefix)
unpack_all();
the_hash_algo->update_fn(&ctx, buffer, offset);
the_hash_algo->final_fn(oid.hash, &ctx);
- if (strict)
+ if (strict) {
write_rest();
+ if (fsck_finish(&fsck_options))
+ die(_("fsck error in pack objects"));
+ }
if (hashcmp(fill(the_hash_algo->rawsz), oid.hash))
die("final sha1 did not match");
use(the_hash_algo->rawsz);
diff --git a/builtin/update-index.c b/builtin/update-index.c
index 10d070a..a8709a2 100644
--- a/builtin/update-index.c
+++ b/builtin/update-index.c
@@ -364,10 +364,9 @@ static int process_directory(const char *path, int len, struct stat *st)
return error("%s: is a directory - add files inside instead", path);
}
-static int process_path(const char *path)
+static int process_path(const char *path, struct stat *st, int stat_errno)
{
int pos, len;
- struct stat st;
const struct cache_entry *ce;
len = strlen(path);
@@ -391,13 +390,13 @@ static int process_path(const char *path)
* First things first: get the stat information, to decide
* what to do about the pathname!
*/
- if (lstat(path, &st) < 0)
- return process_lstat_error(path, errno);
+ if (stat_errno)
+ return process_lstat_error(path, stat_errno);
- if (S_ISDIR(st.st_mode))
- return process_directory(path, len, &st);
+ if (S_ISDIR(st->st_mode))
+ return process_directory(path, len, st);
- return add_one_path(ce, path, len, &st);
+ return add_one_path(ce, path, len, st);
}
static int add_cacheinfo(unsigned int mode, const struct object_id *oid,
@@ -406,7 +405,7 @@ static int add_cacheinfo(unsigned int mode, const struct object_id *oid,
int size, len, option;
struct cache_entry *ce;
- if (!verify_path(path))
+ if (!verify_path(path, mode))
return error("Invalid path '%s'", path);
len = strlen(path);
@@ -449,7 +448,18 @@ static void chmod_path(char flip, const char *path)
static void update_one(const char *path)
{
- if (!verify_path(path)) {
+ int stat_errno = 0;
+ struct stat st;
+
+ if (mark_valid_only || mark_skip_worktree_only || force_remove ||
+ mark_fsmonitor_only)
+ st.st_mode = 0;
+ else if (lstat(path, &st) < 0) {
+ st.st_mode = 0;
+ stat_errno = errno;
+ } /* else stat is valid */
+
+ if (!verify_path(path, st.st_mode)) {
fprintf(stderr, "Ignoring path %s\n", path);
return;
}
@@ -475,7 +485,7 @@ static void update_one(const char *path)
report("remove '%s'", path);
return;
}
- if (process_path(path))
+ if (process_path(path, &st, stat_errno))
die("Unable to process path %s", path);
report("add '%s'", path);
}
@@ -545,7 +555,7 @@ static void read_index_info(int nul_term_line)
path_name = uq.buf;
}
- if (!verify_path(path_name)) {
+ if (!verify_path(path_name, mode)) {
fprintf(stderr, "Ignoring path %s\n", path_name);
continue;
}
@@ -1164,7 +1174,7 @@ int cmd_update_index(int argc, const char **argv, const char *prefix)
report(_("Untracked cache enabled for '%s'"), get_git_work_tree());
break;
default:
- die("BUG: bad untracked_cache value: %d", untracked_cache);
+ BUG("bad untracked_cache value: %d", untracked_cache);
}
if (fsmonitor > 0) {
diff --git a/builtin/upload-pack.c b/builtin/upload-pack.c
new file mode 100644
index 0000000..decde5a
--- /dev/null
+++ b/builtin/upload-pack.c
@@ -0,0 +1,74 @@
+#include "cache.h"
+#include "builtin.h"
+#include "exec-cmd.h"
+#include "pkt-line.h"
+#include "parse-options.h"
+#include "protocol.h"
+#include "upload-pack.h"
+#include "serve.h"
+
+static const char * const upload_pack_usage[] = {
+ N_("git upload-pack [<options>] <dir>"),
+ NULL
+};
+
+int cmd_upload_pack(int argc, const char **argv, const char *prefix)
+{
+ const char *dir;
+ int strict = 0;
+ struct upload_pack_options opts = { 0 };
+ struct serve_options serve_opts = SERVE_OPTIONS_INIT;
+ struct option options[] = {
+ OPT_BOOL(0, "stateless-rpc", &opts.stateless_rpc,
+ N_("quit after a single request/response exchange")),
+ OPT_BOOL(0, "advertise-refs", &opts.advertise_refs,
+ N_("exit immediately after initial ref advertisement")),
+ OPT_BOOL(0, "strict", &strict,
+ N_("do not try <directory>/.git/ if <directory> is no Git directory")),
+ OPT_INTEGER(0, "timeout", &opts.timeout,
+ N_("interrupt transfer after <n> seconds of inactivity")),
+ OPT_END()
+ };
+
+ packet_trace_identity("upload-pack");
+ check_replace_refs = 0;
+
+ argc = parse_options(argc, argv, NULL, options, upload_pack_usage, 0);
+
+ if (argc != 1)
+ usage_with_options(upload_pack_usage, options);
+
+ if (opts.timeout)
+ opts.daemon_mode = 1;
+
+ setup_path();
+
+ dir = argv[0];
+
+ if (!enter_repo(dir, strict))
+ die("'%s' does not appear to be a git repository", dir);
+
+ switch (determine_protocol_version_server()) {
+ case protocol_v2:
+ serve_opts.advertise_capabilities = opts.advertise_refs;
+ serve_opts.stateless_rpc = opts.stateless_rpc;
+ serve(&serve_opts);
+ break;
+ case protocol_v1:
+ /*
+ * v1 is just the original protocol with a version string,
+ * so just fall through after writing the version string.
+ */
+ if (opts.advertise_refs || !opts.stateless_rpc)
+ packet_write_fmt(1, "version 1\n");
+
+ /* fallthrough */
+ case protocol_v0:
+ upload_pack(&opts);
+ break;
+ case protocol_unknown_version:
+ BUG("unknown protocol version");
+ }
+
+ return 0;
+}
diff --git a/builtin/verify-tag.c b/builtin/verify-tag.c
index ad7b79f..6fa04b7 100644
--- a/builtin/verify-tag.c
+++ b/builtin/verify-tag.c
@@ -72,7 +72,7 @@ int cmd_verify_tag(int argc, const char **argv, const char *prefix)
}
if (format.format)
- pretty_print_ref(name, oid.hash, &format);
+ pretty_print_ref(name, &oid, &format);
}
return had_error;
}
diff --git a/builtin/worktree.c b/builtin/worktree.c
index 40a438e..5c7d2bb 100644
--- a/builtin/worktree.c
+++ b/builtin/worktree.c
@@ -29,8 +29,6 @@ struct add_opts {
int detach;
int checkout;
int keep_locked;
- const char *new_branch;
- int force_new_branch;
};
static int show_only;
@@ -298,8 +296,6 @@ static int add_worktree(const char *path, const char *refname,
strbuf_addf(&sb, "%s/commondir", sb_repo.buf);
write_file(sb.buf, "../..");
- fprintf_ln(stderr, _("Preparing %s (identifier %s)"), path, name);
-
argv_array_pushf(&child_env, "%s=%s", GIT_DIR_ENVIRONMENT, sb_git.buf);
argv_array_pushf(&child_env, "%s=%s", GIT_WORK_TREE_ENVIRONMENT, path);
cp.git_cmd = 1;
@@ -366,18 +362,75 @@ done:
return ret;
}
+static void print_preparing_worktree_line(int detach,
+ const char *branch,
+ const char *new_branch,
+ int force_new_branch)
+{
+ if (force_new_branch) {
+ struct commit *commit = lookup_commit_reference_by_name(new_branch);
+ if (!commit)
+ printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
+ else
+ printf_ln(_("Preparing worktree (resetting branch '%s'; was at %s)"),
+ new_branch,
+ find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
+ } else if (new_branch) {
+ printf_ln(_("Preparing worktree (new branch '%s')"), new_branch);
+ } else {
+ struct strbuf s = STRBUF_INIT;
+ if (!detach && !strbuf_check_branch_ref(&s, branch) &&
+ ref_exists(s.buf))
+ printf_ln(_("Preparing worktree (checking out '%s')"),
+ branch);
+ else {
+ struct commit *commit = lookup_commit_reference_by_name(branch);
+ if (!commit)
+ die(_("invalid reference: %s"), branch);
+ printf_ln(_("Preparing worktree (detached HEAD %s)"),
+ find_unique_abbrev(&commit->object.oid, DEFAULT_ABBREV));
+ }
+ strbuf_release(&s);
+ }
+}
+
+static const char *dwim_branch(const char *path, const char **new_branch)
+{
+ int n;
+ const char *s = worktree_basename(path, &n);
+ const char *branchname = xstrndup(s, n);
+ struct strbuf ref = STRBUF_INIT;
+
+ UNLEAK(branchname);
+ if (!strbuf_check_branch_ref(&ref, branchname) &&
+ ref_exists(ref.buf)) {
+ strbuf_release(&ref);
+ return branchname;
+ }
+
+ *new_branch = branchname;
+ if (guess_remote) {
+ struct object_id oid;
+ const char *remote =
+ unique_tracking_name(*new_branch, &oid);
+ return remote;
+ }
+ return NULL;
+}
+
static int add(int ac, const char **av, const char *prefix)
{
struct add_opts opts;
const char *new_branch_force = NULL;
char *path;
const char *branch;
+ const char *new_branch = NULL;
const char *opt_track = NULL;
struct option options[] = {
OPT__FORCE(&opts.force,
N_("checkout <branch> even if already checked out in other worktree"),
PARSE_OPT_NOCOMPLETE),
- OPT_STRING('b', NULL, &opts.new_branch, N_("branch"),
+ OPT_STRING('b', NULL, &new_branch, N_("branch"),
N_("create a new branch")),
OPT_STRING('B', NULL, &new_branch_force, N_("branch"),
N_("create or reset a branch")),
@@ -395,7 +448,7 @@ static int add(int ac, const char **av, const char *prefix)
memset(&opts, 0, sizeof(opts));
opts.checkout = 1;
ac = parse_options(ac, av, prefix, options, worktree_usage, 0);
- if (!!opts.detach + !!opts.new_branch + !!new_branch_force > 1)
+ if (!!opts.detach + !!new_branch + !!new_branch_force > 1)
die(_("-b, -B, and --detach are mutually exclusive"));
if (ac < 1 || ac > 2)
usage_with_options(worktree_usage, options);
@@ -406,33 +459,25 @@ static int add(int ac, const char **av, const char *prefix)
if (!strcmp(branch, "-"))
branch = "@{-1}";
- opts.force_new_branch = !!new_branch_force;
- if (opts.force_new_branch) {
+ if (new_branch_force) {
struct strbuf symref = STRBUF_INIT;
- opts.new_branch = new_branch_force;
+ new_branch = new_branch_force;
if (!opts.force &&
- !strbuf_check_branch_ref(&symref, opts.new_branch) &&
+ !strbuf_check_branch_ref(&symref, new_branch) &&
ref_exists(symref.buf))
die_if_checked_out(symref.buf, 0);
strbuf_release(&symref);
}
- if (ac < 2 && !opts.new_branch && !opts.detach) {
- int n;
- const char *s = worktree_basename(path, &n);
- opts.new_branch = xstrndup(s, n);
- if (guess_remote) {
- struct object_id oid;
- const char *remote =
- unique_tracking_name(opts.new_branch, &oid);
- if (remote)
- branch = remote;
- }
+ if (ac < 2 && !new_branch && !opts.detach) {
+ const char *s = dwim_branch(path, &new_branch);
+ if (s)
+ branch = s;
}
- if (ac == 2 && !opts.new_branch && !opts.detach) {
+ if (ac == 2 && !new_branch && !opts.detach) {
struct object_id oid;
struct commit *commit;
const char *remote;
@@ -441,25 +486,27 @@ static int add(int ac, const char **av, const char *prefix)
if (!commit) {
remote = unique_tracking_name(branch, &oid);
if (remote) {
- opts.new_branch = branch;
+ new_branch = branch;
branch = remote;
}
}
}
- if (opts.new_branch) {
+ print_preparing_worktree_line(opts.detach, branch, new_branch, !!new_branch_force);
+
+ if (new_branch) {
struct child_process cp = CHILD_PROCESS_INIT;
cp.git_cmd = 1;
argv_array_push(&cp.args, "branch");
- if (opts.force_new_branch)
+ if (new_branch_force)
argv_array_push(&cp.args, "--force");
- argv_array_push(&cp.args, opts.new_branch);
+ argv_array_push(&cp.args, new_branch);
argv_array_push(&cp.args, branch);
if (opt_track)
argv_array_push(&cp.args, opt_track);
if (run_command(&cp))
return -1;
- branch = opts.new_branch;
+ branch = new_branch;
} else if (opt_track) {
die(_("--[no-]track can only be used if a new branch is created"));
}
@@ -783,8 +830,9 @@ static int remove_worktree(int ac, const char **av, const char *prefix)
{
int force = 0;
struct option options[] = {
- OPT_BOOL(0, "force", &force,
- N_("force removing even if the worktree is dirty")),
+ OPT__FORCE(&force,
+ N_("force removing even if the worktree is dirty"),
+ PARSE_OPT_NOCOMPLETE),
OPT_END()
};
struct worktree **worktrees, *wt;
diff --git a/bulk-checkin.c b/bulk-checkin.c
index de1f404..b7e131c 100644
--- a/bulk-checkin.c
+++ b/bulk-checkin.c
@@ -36,9 +36,9 @@ static void finish_bulk_checkin(struct bulk_checkin_state *state)
unlink(state->pack_tmp_name);
goto clear_exit;
} else if (state->nr_written == 1) {
- hashclose(state->f, oid.hash, CSUM_FSYNC);
+ finalize_hashfile(state->f, oid.hash, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
} else {
- int fd = hashclose(state->f, oid.hash, 0);
+ int fd = finalize_hashfile(state->f, oid.hash, 0);
fixup_pack_header_footer(fd, oid.hash, state->pack_tmp_name,
state->nr_written, oid.hash,
state->offset);
@@ -230,7 +230,7 @@ static int deflate_to_pack(struct bulk_checkin_state *state,
* pack, and write into it.
*/
if (!idx)
- die("BUG: should not happen");
+ BUG("should not happen");
hashfile_truncate(state->f, &checkpoint);
state->offset = checkpoint.offset;
finish_bulk_checkin(state);
diff --git a/bundle.c b/bundle.c
index 902c9b5..160bbfd 100644
--- a/bundle.c
+++ b/bundle.c
@@ -409,7 +409,7 @@ static int write_bundle_refs(int bundle_fd, struct rev_info *revs)
int create_bundle(struct bundle_header *header, const char *path,
int argc, const char **argv)
{
- static struct lock_file lock;
+ struct lock_file lock = LOCK_INIT;
int bundle_fd = -1;
int bundle_to_stdout;
int ref_count = 0;
diff --git a/cache-tree.c b/cache-tree.c
index 6a555f4..2566382 100644
--- a/cache-tree.c
+++ b/cache-tree.c
@@ -385,7 +385,7 @@ static int update_one(struct cache_tree *it,
/*
* "sub" can be an empty tree if all subentries are i-t-a.
*/
- if (contains_ita && !oidcmp(oid, &empty_tree_oid))
+ if (contains_ita && is_empty_tree_oid(oid))
continue;
strbuf_grow(&buffer, entlen + 100);
@@ -523,7 +523,7 @@ static struct cache_tree *read_one(const char **buffer, unsigned long *size_p)
if (0 <= it->entry_count) {
if (size < rawsz)
goto free_return;
- memcpy(it->oid.hash, (const unsigned char*)buf, rawsz);
+ oidread(&it->oid, (const unsigned char *)buf);
buf += rawsz;
size -= rawsz;
}
diff --git a/cache.h b/cache.h
index bbaf5c3..08a4826 100644
--- a/cache.h
+++ b/cache.h
@@ -324,7 +324,7 @@ struct index_state {
drop_cache_tree : 1;
struct hashmap name_hash;
struct hashmap dir_hash;
- unsigned char sha1[20];
+ struct object_id oid;
struct untracked_cache *untracked;
uint64_t fsmonitor_last_update;
struct ewah_bitmap *fsmonitor_dirty;
@@ -373,6 +373,13 @@ extern void free_name_hash(struct index_state *istate);
#define read_blob_data_from_cache(path, sz) read_blob_data_from_index(&the_index, (path), (sz))
#endif
+#define TYPE_BITS 3
+
+/*
+ * Values in this enum (except those outside the 3 bit range) are part
+ * of pack file format. See Documentation/technical/pack-format.txt
+ * for more information.
+ */
enum object_type {
OBJ_BAD = -1,
OBJ_NONE = 0,
@@ -428,6 +435,7 @@ static inline enum object_type object_type(unsigned int mode)
#define GIT_ICASE_PATHSPECS_ENVIRONMENT "GIT_ICASE_PATHSPECS"
#define GIT_QUARANTINE_ENVIRONMENT "GIT_QUARANTINE_PATH"
#define GIT_OPTIONAL_LOCKS_ENVIRONMENT "GIT_OPTIONAL_LOCKS"
+#define GIT_TEXT_DOMAIN_DIR_ENVIRONMENT "GIT_TEXTDOMAINDIR"
/*
* Environment variable used in handshaking the wire protocol.
@@ -477,7 +485,7 @@ extern const char *get_git_common_dir(void);
extern char *get_object_directory(void);
extern char *get_index_file(void);
extern char *get_graft_file(void);
-extern int set_git_dir(const char *path);
+extern void set_git_dir(const char *path);
extern int get_common_dir_noenv(struct strbuf *sb, const char *gitdir);
extern int get_common_dir(struct strbuf *sb, const char *gitdir);
extern const char *get_git_namespace(void);
@@ -634,7 +642,7 @@ extern int unmerged_index(const struct index_state *);
*/
extern int index_has_changes(struct strbuf *sb);
-extern int verify_path(const char *path);
+extern int verify_path(const char *path, unsigned mode);
extern int strcmp_offset(const char *s1, const char *s2, size_t *first_change);
extern int index_dir_exists(struct index_state *istate, const char *name, int namelen);
extern void adjust_dirname_case(struct index_state *istate, char *name);
@@ -805,6 +813,7 @@ extern char *git_replace_ref_base;
extern int fsync_object_files;
extern int core_preload_index;
+extern int core_commit_graph;
extern int core_apply_sparse_checkout;
extern int precomposed_unicode;
extern int protect_hfs;
@@ -1008,21 +1017,10 @@ static inline void oidclr(struct object_id *oid)
memset(oid->hash, 0, GIT_MAX_RAWSZ);
}
-
-#define EMPTY_TREE_SHA1_HEX \
- "4b825dc642cb6eb9a060e54bf8d69288fbee4904"
-#define EMPTY_TREE_SHA1_BIN_LITERAL \
- "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
- "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
-extern const struct object_id empty_tree_oid;
-#define EMPTY_TREE_SHA1_BIN (empty_tree_oid.hash)
-
-#define EMPTY_BLOB_SHA1_HEX \
- "e69de29bb2d1d6434b8b29ae775ad8c2e48c5391"
-#define EMPTY_BLOB_SHA1_BIN_LITERAL \
- "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
- "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
-extern const struct object_id empty_blob_oid;
+static inline void oidread(struct object_id *oid, const unsigned char *hash)
+{
+ memcpy(oid->hash, hash, the_hash_algo->rawsz);
+}
static inline int is_empty_blob_sha1(const unsigned char *sha1)
{
@@ -1044,6 +1042,9 @@ static inline int is_empty_tree_oid(const struct object_id *oid)
return !oidcmp(oid, the_hash_algo->empty_tree);
}
+const char *empty_tree_oid_hex(void);
+const char *empty_blob_oid_hex(void);
+
/* set default permissions by passing mode arguments to open(2) */
int git_mkstemps_mode(char *pattern, int suffix_len, int mode);
int git_mkstemp_mode(char *pattern, int mode);
@@ -1159,7 +1160,15 @@ int normalize_path_copy(char *dst, const char *src);
int longest_ancestor_length(const char *path, struct string_list *prefixes);
char *strip_path_suffix(const char *path, const char *suffix);
int daemon_avoid_alias(const char *path);
-extern int is_ntfs_dotgit(const char *name);
+
+/*
+ * These functions match their is_hfs_dotgit() counterparts; see utf8.h for
+ * details.
+ */
+int is_ntfs_dotgit(const char *name);
+int is_ntfs_dotgitmodules(const char *name);
+int is_ntfs_dotgitignore(const char *name);
+int is_ntfs_dotgitattributes(const char *name);
/*
* Returns true iff "str" could be confused as a command-line option when
@@ -1191,27 +1200,8 @@ static inline void *read_object_file(const struct object_id *oid, enum object_ty
return read_object_file_extended(oid, type, size, 1);
}
-/*
- * This internal function is only declared here for the benefit of
- * lookup_replace_object(). Please do not call it directly.
- */
-extern const struct object_id *do_lookup_replace_object(const struct object_id *oid);
-
-/*
- * If object sha1 should be replaced, return the replacement object's
- * name (replaced recursively, if necessary). The return value is
- * either sha1 or a pointer to a permanently-allocated value. When
- * object replacement is suppressed, always return sha1.
- */
-static inline const struct object_id *lookup_replace_object(const struct object_id *oid)
-{
- if (!check_replace_refs)
- return oid;
- return do_lookup_replace_object(oid);
-}
-
/* Read and unpack an object file into memory, write memory to an object file */
-extern int oid_object_info(const struct object_id *, unsigned long *);
+int oid_object_info(struct repository *r, const struct object_id *, unsigned long *);
extern int hash_object_file(const void *buf, unsigned long len,
const char *type, struct object_id *oid);
@@ -1270,7 +1260,7 @@ extern int has_object_file_with_flags(const struct object_id *oid, int flags);
* with the specified name. This function does not respect replace
* references.
*/
-extern int has_loose_object_nonlocal(const unsigned char *sha1);
+extern int has_loose_object_nonlocal(const struct object_id *oid);
extern void assert_oid_type(const struct object_id *oid, enum object_type expect);
@@ -1301,7 +1291,6 @@ static inline int hex2chr(const char *s)
#define FALLBACK_DEFAULT_ABBREV 7
struct object_context {
- unsigned char tree[20];
unsigned mode;
/*
* symlink_path is only used by get_tree_entry_follow_symlinks,
@@ -1568,7 +1557,6 @@ struct pack_window {
struct pack_entry {
off_t offset;
- unsigned char sha1[20];
struct packed_git *p;
};
@@ -1692,7 +1680,10 @@ struct object_info {
#define OBJECT_INFO_QUICK 8
/* Do not check loose object */
#define OBJECT_INFO_IGNORE_LOOSE 16
-extern int oid_object_info_extended(const struct object_id *, struct object_info *, unsigned flags);
+
+int oid_object_info_extended(struct repository *r,
+ const struct object_id *,
+ struct object_info *, unsigned flags);
/*
* Set this to 0 to prevent sha1_object_info_extended() from fetching missing
diff --git a/chdir-notify.c b/chdir-notify.c
new file mode 100644
index 0000000..5f7f2c2
--- /dev/null
+++ b/chdir-notify.c
@@ -0,0 +1,93 @@
+#include "cache.h"
+#include "chdir-notify.h"
+#include "list.h"
+#include "strbuf.h"
+
+struct chdir_notify_entry {
+ const char *name;
+ chdir_notify_callback cb;
+ void *data;
+ struct list_head list;
+};
+static LIST_HEAD(chdir_notify_entries);
+
+void chdir_notify_register(const char *name,
+ chdir_notify_callback cb,
+ void *data)
+{
+ struct chdir_notify_entry *e = xmalloc(sizeof(*e));
+ e->name = name;
+ e->cb = cb;
+ e->data = data;
+ list_add_tail(&e->list, &chdir_notify_entries);
+}
+
+static void reparent_cb(const char *name,
+ const char *old_cwd,
+ const char *new_cwd,
+ void *data)
+{
+ char **path = data;
+ char *tmp = *path;
+
+ if (!tmp)
+ return;
+
+ *path = reparent_relative_path(old_cwd, new_cwd, tmp);
+ free(tmp);
+
+ if (name) {
+ trace_printf_key(&trace_setup_key,
+ "setup: reparent %s to '%s'",
+ name, *path);
+ }
+}
+
+void chdir_notify_reparent(const char *name, char **path)
+{
+ chdir_notify_register(name, reparent_cb, path);
+}
+
+int chdir_notify(const char *new_cwd)
+{
+ struct strbuf old_cwd = STRBUF_INIT;
+ struct list_head *pos;
+
+ if (strbuf_getcwd(&old_cwd) < 0)
+ return -1;
+ if (chdir(new_cwd) < 0) {
+ int saved_errno = errno;
+ strbuf_release(&old_cwd);
+ errno = saved_errno;
+ return -1;
+ }
+
+ trace_printf_key(&trace_setup_key,
+ "setup: chdir from '%s' to '%s'",
+ old_cwd.buf, new_cwd);
+
+ list_for_each(pos, &chdir_notify_entries) {
+ struct chdir_notify_entry *e =
+ list_entry(pos, struct chdir_notify_entry, list);
+ e->cb(e->name, old_cwd.buf, new_cwd, e->data);
+ }
+
+ strbuf_release(&old_cwd);
+ return 0;
+}
+
+char *reparent_relative_path(const char *old_cwd,
+ const char *new_cwd,
+ const char *path)
+{
+ char *ret, *full;
+
+ if (is_absolute_path(path))
+ return xstrdup(path);
+
+ full = xstrfmt("%s/%s", old_cwd, path);
+ ret = xstrdup(remove_leading_path(full, new_cwd));
+ free(full);
+
+ return ret;
+}
diff --git a/chdir-notify.h b/chdir-notify.h
new file mode 100644
index 0000000..366e4c1
--- /dev/null
+++ b/chdir-notify.h
@@ -0,0 +1,73 @@
+#ifndef CHDIR_NOTIFY_H
+#define CHDIR_NOTIFY_H
+
+/*
+ * An API to let code "subscribe" to changes to the current working directory.
+ * The general idea is that some code asks to be notified when the working
+ * directory changes, and other code that calls chdir uses a special wrapper
+ * that notifies everyone.
+ */
+
+/*
+ * Callers who need to know about changes can do:
+ *
+ * void foo(const char *old_path, const char *new_path, void *data)
+ * {
+ * warning("switched from %s to %s!", old_path, new_path);
+ * }
+ * ...
+ * chdir_notify_register("description", foo, data);
+ *
+ * In practice most callers will want to move a relative path to the new root;
+ * they can use the reparent_relative_path() helper for that. If that's all
+ * you're doing, you can also use the convenience function:
+ *
+ * chdir_notify_reparent("description", &my_path);
+ *
+ * Whenever a chdir event occurs, that will update my_path (if it's relative)
+ * to adjust for the new cwd by freeing any existing string and allocating a
+ * new one.
+ *
+ * Registered functions are called in the order in which they were added. Note
+ * that there's currently no way to remove a function, so make sure that the
+ * data parameter remains valid for the rest of the program.
+ *
+ * The "name" argument is used only for printing trace output from
+ * $GIT_TRACE_SETUP. It may be NULL, but if non-NULL should point to
+ * storage which lasts as long as the registration is active.
+ */
+typedef void (*chdir_notify_callback)(const char *name,
+ const char *old_cwd,
+ const char *new_cwd,
+ void *data);
+void chdir_notify_register(const char *name, chdir_notify_callback cb, void *data);
+void chdir_notify_reparent(const char *name, char **path);
+
+/*
+ *
+ * Callers that want to chdir:
+ *
+ * chdir_notify(new_path);
+ *
+ * to switch to the new path and notify any callbacks.
+ *
+ * Note that you don't need to chdir_notify() if you're just temporarily moving
+ * to a directory and back, as long as you don't call any subscribed code in
+ * between (but it should be safe to do so if you're unsure).
+ */
+int chdir_notify(const char *new_cwd);
+
+/*
+ * Reparent a relative path from old_root to new_root. For example:
+ *
+ * reparent_relative_path("/a", "/a/b", "b/rel");
+ *
+ * would return the (newly allocated) string "rel". Note that we may return an
+ * absolute path in some cases (e.g., if the resulting path is not inside
+ * new_cwd).
+ */
+char *reparent_relative_path(const char *old_cwd,
+ const char *new_cwd,
+ const char *path);
+
+#endif /* CHDIR_NOTIFY_H */
diff --git a/checkout.c b/checkout.c
index ac42630..bdefc88 100644
--- a/checkout.c
+++ b/checkout.c
@@ -1,5 +1,6 @@
#include "cache.h"
#include "remote.h"
+#include "refspec.h"
#include "checkout.h"
struct tracking_name_data {
@@ -12,8 +13,8 @@ struct tracking_name_data {
static int check_tracking_name(struct remote *remote, void *cb_data)
{
struct tracking_name_data *cb = cb_data;
- struct refspec query;
- memset(&query, 0, sizeof(struct refspec));
+ struct refspec_item query;
+ memset(&query, 0, sizeof(struct refspec_item));
query.src = cb->src_ref;
if (remote_find_tracking(remote, &query) ||
get_oid(query.dst, cb->dst_oid)) {
diff --git a/ci/lib-travisci.sh b/ci/lib-travisci.sh
index 109ef28..ceecc88 100755
--- a/ci/lib-travisci.sh
+++ b/ci/lib-travisci.sh
@@ -99,6 +99,9 @@ export DEFAULT_TEST_TARGET=prove
export GIT_PROVE_OPTS="--timer --jobs 3 --state=failed,slow,save"
export GIT_TEST_OPTS="--verbose-log -x"
export GIT_TEST_CLONE_2GB=YesPlease
+if [ "$jobname" = linux-gcc ]; then
+ export CC=gcc-8
+fi
case "$jobname" in
linux-clang|linux-gcc)
diff --git a/ci/run-build-and-tests.sh b/ci/run-build-and-tests.sh
index 3735ce4..4b04c75 100755
--- a/ci/run-build-and-tests.sh
+++ b/ci/run-build-and-tests.sh
@@ -11,7 +11,10 @@ make --jobs=2
make --quiet test
if test "$jobname" = "linux-gcc"
then
- GIT_TEST_SPLIT_INDEX=YesPlease make --quiet test
+ export GIT_TEST_SPLIT_INDEX=yes
+ export GIT_TEST_FULL_IN_PACK_ARRAY=true
+ export GIT_TEST_OE_SIZE=10
+ make --quiet test
fi
check_unignored_build_artifacts
diff --git a/color.c b/color.c
index f277e72..b1c24c6 100644
--- a/color.c
+++ b/color.c
@@ -174,7 +174,7 @@ static char *color_output(char *out, int len, const struct color *c, char type)
break;
case COLOR_ANSI:
if (len < 2)
- die("BUG: color parsing ran out of space");
+ BUG("color parsing ran out of space");
*out++ = type;
*out++ = '0' + c->value;
break;
@@ -256,7 +256,7 @@ int color_parse_mem(const char *value, int value_len, char *dst)
#undef OUT
#define OUT(x) do { \
if (dst == end) \
- die("BUG: color parsing ran out of space"); \
+ BUG("color parsing ran out of space"); \
*dst++ = (x); \
} while(0)
@@ -319,18 +319,20 @@ int git_config_colorbool(const char *var, const char *value)
return GIT_COLOR_AUTO;
}
-static int check_auto_color(void)
+static int check_auto_color(int fd)
{
- if (color_stdout_is_tty < 0)
- color_stdout_is_tty = isatty(1);
- if (color_stdout_is_tty || (pager_in_use() && pager_use_color)) {
+ static int color_stderr_is_tty = -1;
+ int *is_tty_p = fd == 1 ? &color_stdout_is_tty : &color_stderr_is_tty;
+ if (*is_tty_p < 0)
+ *is_tty_p = isatty(fd);
+ if (*is_tty_p || (fd == 1 && pager_in_use() && pager_use_color)) {
if (!is_terminal_dumb())
return 1;
}
return 0;
}
-int want_color(int var)
+int want_color_fd(int fd, int var)
{
/*
* NEEDSWORK: This function is sometimes used from multiple threads, and
@@ -339,15 +341,15 @@ int want_color(int var)
* is listed in .tsan-suppressions for the time being.
*/
- static int want_auto = -1;
+ static int want_auto[3] = { -1, -1, -1 };
if (var < 0)
var = git_use_color_default;
if (var == GIT_COLOR_AUTO) {
- if (want_auto < 0)
- want_auto = check_auto_color();
- return want_auto;
+ if (want_auto[fd] < 0)
+ want_auto[fd] = check_auto_color(fd);
+ return want_auto[fd];
}
return var;
}
diff --git a/color.h b/color.h
index cd0bced..5b744e1 100644
--- a/color.h
+++ b/color.h
@@ -88,7 +88,9 @@ int git_config_colorbool(const char *var, const char *value);
* Return a boolean whether to use color, where the argument 'var' is
* one of GIT_COLOR_UNKNOWN, GIT_COLOR_NEVER, GIT_COLOR_ALWAYS, GIT_COLOR_AUTO.
*/
-int want_color(int var);
+int want_color_fd(int fd, int var);
+#define want_color(colorbool) want_color_fd(1, (colorbool))
+#define want_color_stderr(colorbool) want_color_fd(2, (colorbool))
/*
* Translate a Git color from 'value' into a string that the terminal can
diff --git a/column.c b/column.c
index 49ab85b..2165297 100644
--- a/column.c
+++ b/column.c
@@ -214,7 +214,7 @@ void print_columns(const struct string_list *list, unsigned int colopts,
display_table(list, colopts, &nopts);
break;
default:
- die("BUG: invalid layout mode %d", COL_LAYOUT(colopts));
+ BUG("invalid layout mode %d", COL_LAYOUT(colopts));
}
}
diff --git a/command-list.txt b/command-list.txt
index a1fad28..835c589 100644
--- a/command-list.txt
+++ b/command-list.txt
@@ -34,6 +34,7 @@ git-clean mainporcelain
git-clone mainporcelain init
git-column purehelpers
git-commit mainporcelain history
+git-commit-graph plumbingmanipulators
git-commit-tree plumbingmanipulators
git-config ancillarymanipulators
git-count-objects ancillaryinterrogators
diff --git a/commit-graph.c b/commit-graph.c
new file mode 100644
index 0000000..4c61270
--- /dev/null
+++ b/commit-graph.c
@@ -0,0 +1,761 @@
+#include "cache.h"
+#include "config.h"
+#include "git-compat-util.h"
+#include "lockfile.h"
+#include "pack.h"
+#include "packfile.h"
+#include "commit.h"
+#include "object.h"
+#include "revision.h"
+#include "sha1-lookup.h"
+#include "commit-graph.h"
+#include "object-store.h"
+
+#define GRAPH_SIGNATURE 0x43475048 /* "CGPH" */
+#define GRAPH_CHUNKID_OIDFANOUT 0x4f494446 /* "OIDF" */
+#define GRAPH_CHUNKID_OIDLOOKUP 0x4f49444c /* "OIDL" */
+#define GRAPH_CHUNKID_DATA 0x43444154 /* "CDAT" */
+#define GRAPH_CHUNKID_LARGEEDGES 0x45444745 /* "EDGE" */
+
+#define GRAPH_DATA_WIDTH 36
+
+#define GRAPH_VERSION_1 0x1
+#define GRAPH_VERSION GRAPH_VERSION_1
+
+#define GRAPH_OID_VERSION_SHA1 1
+#define GRAPH_OID_LEN_SHA1 GIT_SHA1_RAWSZ
+#define GRAPH_OID_VERSION GRAPH_OID_VERSION_SHA1
+#define GRAPH_OID_LEN GRAPH_OID_LEN_SHA1
+
+#define GRAPH_OCTOPUS_EDGES_NEEDED 0x80000000
+#define GRAPH_PARENT_MISSING 0x7fffffff
+#define GRAPH_EDGE_LAST_MASK 0x7fffffff
+#define GRAPH_PARENT_NONE 0x70000000
+
+#define GRAPH_LAST_EDGE 0x80000000
+
+#define GRAPH_FANOUT_SIZE (4 * 256)
+#define GRAPH_CHUNKLOOKUP_WIDTH 12
+#define GRAPH_MIN_SIZE (5 * GRAPH_CHUNKLOOKUP_WIDTH + GRAPH_FANOUT_SIZE + \
+ GRAPH_OID_LEN + 8)
+
+char *get_commit_graph_filename(const char *obj_dir)
+{
+ return xstrfmt("%s/info/commit-graph", obj_dir);
+}
+
+static struct commit_graph *alloc_commit_graph(void)
+{
+ struct commit_graph *g = xcalloc(1, sizeof(*g));
+ g->graph_fd = -1;
+
+ return g;
+}
+
+struct commit_graph *load_commit_graph_one(const char *graph_file)
+{
+ void *graph_map;
+ const unsigned char *data, *chunk_lookup;
+ size_t graph_size;
+ struct stat st;
+ uint32_t i;
+ struct commit_graph *graph;
+ int fd = git_open(graph_file);
+ uint64_t last_chunk_offset;
+ uint32_t last_chunk_id;
+ uint32_t graph_signature;
+ unsigned char graph_version, hash_version;
+
+ if (fd < 0)
+ return NULL;
+ if (fstat(fd, &st)) {
+ close(fd);
+ return NULL;
+ }
+ graph_size = xsize_t(st.st_size);
+
+ if (graph_size < GRAPH_MIN_SIZE) {
+ close(fd);
+ die("graph file %s is too small", graph_file);
+ }
+ graph_map = xmmap(NULL, graph_size, PROT_READ, MAP_PRIVATE, fd, 0);
+ data = (const unsigned char *)graph_map;
+
+ graph_signature = get_be32(data);
+ if (graph_signature != GRAPH_SIGNATURE) {
+ error("graph signature %X does not match signature %X",
+ graph_signature, GRAPH_SIGNATURE);
+ goto cleanup_fail;
+ }
+
+ graph_version = *(unsigned char*)(data + 4);
+ if (graph_version != GRAPH_VERSION) {
+ error("graph version %X does not match version %X",
+ graph_version, GRAPH_VERSION);
+ goto cleanup_fail;
+ }
+
+ hash_version = *(unsigned char*)(data + 5);
+ if (hash_version != GRAPH_OID_VERSION) {
+ error("hash version %X does not match version %X",
+ hash_version, GRAPH_OID_VERSION);
+ goto cleanup_fail;
+ }
+
+ graph = alloc_commit_graph();
+
+ graph->hash_len = GRAPH_OID_LEN;
+ graph->num_chunks = *(unsigned char*)(data + 6);
+ graph->graph_fd = fd;
+ graph->data = graph_map;
+ graph->data_len = graph_size;
+
+ last_chunk_id = 0;
+ last_chunk_offset = 8;
+ chunk_lookup = data + 8;
+ for (i = 0; i < graph->num_chunks; i++) {
+ uint32_t chunk_id = get_be32(chunk_lookup + 0);
+ uint64_t chunk_offset = get_be64(chunk_lookup + 4);
+ int chunk_repeated = 0;
+
+ chunk_lookup += GRAPH_CHUNKLOOKUP_WIDTH;
+
+ if (chunk_offset > graph_size - GIT_MAX_RAWSZ) {
+ error("improper chunk offset %08x%08x", (uint32_t)(chunk_offset >> 32),
+ (uint32_t)chunk_offset);
+ goto cleanup_fail;
+ }
+
+ switch (chunk_id) {
+ case GRAPH_CHUNKID_OIDFANOUT:
+ if (graph->chunk_oid_fanout)
+ chunk_repeated = 1;
+ else
+ graph->chunk_oid_fanout = (uint32_t*)(data + chunk_offset);
+ break;
+
+ case GRAPH_CHUNKID_OIDLOOKUP:
+ if (graph->chunk_oid_lookup)
+ chunk_repeated = 1;
+ else
+ graph->chunk_oid_lookup = data + chunk_offset;
+ break;
+
+ case GRAPH_CHUNKID_DATA:
+ if (graph->chunk_commit_data)
+ chunk_repeated = 1;
+ else
+ graph->chunk_commit_data = data + chunk_offset;
+ break;
+
+ case GRAPH_CHUNKID_LARGEEDGES:
+ if (graph->chunk_large_edges)
+ chunk_repeated = 1;
+ else
+ graph->chunk_large_edges = data + chunk_offset;
+ break;
+ }
+
+ if (chunk_repeated) {
+ error("chunk id %08x appears multiple times", chunk_id);
+ goto cleanup_fail;
+ }
+
+ if (last_chunk_id == GRAPH_CHUNKID_OIDLOOKUP)
+ {
+ graph->num_commits = (chunk_offset - last_chunk_offset)
+ / graph->hash_len;
+ }
+
+ last_chunk_id = chunk_id;
+ last_chunk_offset = chunk_offset;
+ }
+
+ return graph;
+
+cleanup_fail:
+ munmap(graph_map, graph_size);
+ close(fd);
+ exit(1);
+}
+
+/* global storage */
+static struct commit_graph *commit_graph = NULL;
+
+static void prepare_commit_graph_one(const char *obj_dir)
+{
+ char *graph_name;
+
+ if (commit_graph)
+ return;
+
+ graph_name = get_commit_graph_filename(obj_dir);
+ commit_graph = load_commit_graph_one(graph_name);
+
+ FREE_AND_NULL(graph_name);
+}
+
+static int prepare_commit_graph_run_once = 0;
+static void prepare_commit_graph(void)
+{
+ struct alternate_object_database *alt;
+ char *obj_dir;
+
+ if (prepare_commit_graph_run_once)
+ return;
+ prepare_commit_graph_run_once = 1;
+
+ obj_dir = get_object_directory();
+ prepare_commit_graph_one(obj_dir);
+ prepare_alt_odb(the_repository);
+ for (alt = the_repository->objects->alt_odb_list;
+ !commit_graph && alt;
+ alt = alt->next)
+ prepare_commit_graph_one(alt->path);
+}
+
+static void close_commit_graph(void)
+{
+ if (!commit_graph)
+ return;
+
+ if (commit_graph->graph_fd >= 0) {
+ munmap((void *)commit_graph->data, commit_graph->data_len);
+ commit_graph->data = NULL;
+ close(commit_graph->graph_fd);
+ }
+
+ FREE_AND_NULL(commit_graph);
+}
+
+static int bsearch_graph(struct commit_graph *g, struct object_id *oid, uint32_t *pos)
+{
+ return bsearch_hash(oid->hash, g->chunk_oid_fanout,
+ g->chunk_oid_lookup, g->hash_len, pos);
+}
+
+static struct commit_list **insert_parent_or_die(struct commit_graph *g,
+ uint64_t pos,
+ struct commit_list **pptr)
+{
+ struct commit *c;
+ struct object_id oid;
+ hashcpy(oid.hash, g->chunk_oid_lookup + g->hash_len * pos);
+ c = lookup_commit(&oid);
+ if (!c)
+ die("could not find commit %s", oid_to_hex(&oid));
+ c->graph_pos = pos;
+ return &commit_list_insert(c, pptr)->next;
+}
+
+static int fill_commit_in_graph(struct commit *item, struct commit_graph *g, uint32_t pos)
+{
+ uint32_t edge_value;
+ uint32_t *parent_data_ptr;
+ uint64_t date_low, date_high;
+ struct commit_list **pptr;
+ const unsigned char *commit_data = g->chunk_commit_data + (g->hash_len + 16) * pos;
+
+ item->object.parsed = 1;
+ item->graph_pos = pos;
+
+ item->maybe_tree = NULL;
+
+ date_high = get_be32(commit_data + g->hash_len + 8) & 0x3;
+ date_low = get_be32(commit_data + g->hash_len + 12);
+ item->date = (timestamp_t)((date_high << 32) | date_low);
+
+ pptr = &item->parents;
+
+ edge_value = get_be32(commit_data + g->hash_len);
+ if (edge_value == GRAPH_PARENT_NONE)
+ return 1;
+ pptr = insert_parent_or_die(g, edge_value, pptr);
+
+ edge_value = get_be32(commit_data + g->hash_len + 4);
+ if (edge_value == GRAPH_PARENT_NONE)
+ return 1;
+ if (!(edge_value & GRAPH_OCTOPUS_EDGES_NEEDED)) {
+ pptr = insert_parent_or_die(g, edge_value, pptr);
+ return 1;
+ }
+
+ parent_data_ptr = (uint32_t*)(g->chunk_large_edges +
+ 4 * (uint64_t)(edge_value & GRAPH_EDGE_LAST_MASK));
+ do {
+ edge_value = get_be32(parent_data_ptr);
+ pptr = insert_parent_or_die(g,
+ edge_value & GRAPH_EDGE_LAST_MASK,
+ pptr);
+ parent_data_ptr++;
+ } while (!(edge_value & GRAPH_LAST_EDGE));
+
+ return 1;
+}
+
+int parse_commit_in_graph(struct commit *item)
+{
+ if (!core_commit_graph)
+ return 0;
+ if (item->object.parsed)
+ return 1;
+
+ prepare_commit_graph();
+ if (commit_graph) {
+ uint32_t pos;
+ int found;
+ if (item->graph_pos != COMMIT_NOT_FROM_GRAPH) {
+ pos = item->graph_pos;
+ found = 1;
+ } else {
+ found = bsearch_graph(commit_graph, &(item->object.oid), &pos);
+ }
+
+ if (found)
+ return fill_commit_in_graph(item, commit_graph, pos);
+ }
+
+ return 0;
+}
+
+static struct tree *load_tree_for_commit(struct commit_graph *g, struct commit *c)
+{
+ struct object_id oid;
+ const unsigned char *commit_data = g->chunk_commit_data +
+ GRAPH_DATA_WIDTH * (c->graph_pos);
+
+ hashcpy(oid.hash, commit_data);
+ c->maybe_tree = lookup_tree(&oid);
+
+ return c->maybe_tree;
+}
+
+struct tree *get_commit_tree_in_graph(const struct commit *c)
+{
+ if (c->maybe_tree)
+ return c->maybe_tree;
+ if (c->graph_pos == COMMIT_NOT_FROM_GRAPH)
+ BUG("get_commit_tree_in_graph called from non-commit-graph commit");
+
+ return load_tree_for_commit(commit_graph, (struct commit *)c);
+}
+
+static void write_graph_chunk_fanout(struct hashfile *f,
+ struct commit **commits,
+ int nr_commits)
+{
+ int i, count = 0;
+ struct commit **list = commits;
+
+ /*
+ * Write the first-level table (the list is sorted,
+ * but we use a 256-entry lookup to be able to avoid
+ * having to do eight extra binary search iterations).
+ */
+ for (i = 0; i < 256; i++) {
+ while (count < nr_commits) {
+ if ((*list)->object.oid.hash[0] != i)
+ break;
+ count++;
+ list++;
+ }
+
+ hashwrite_be32(f, count);
+ }
+}
+
+static void write_graph_chunk_oids(struct hashfile *f, int hash_len,
+ struct commit **commits, int nr_commits)
+{
+ struct commit **list = commits;
+ int count;
+ for (count = 0; count < nr_commits; count++, list++)
+ hashwrite(f, (*list)->object.oid.hash, (int)hash_len);
+}
+
+static const unsigned char *commit_to_sha1(size_t index, void *table)
+{
+ struct commit **commits = table;
+ return commits[index]->object.oid.hash;
+}
+
+static void write_graph_chunk_data(struct hashfile *f, int hash_len,
+ struct commit **commits, int nr_commits)
+{
+ struct commit **list = commits;
+ struct commit **last = commits + nr_commits;
+ uint32_t num_extra_edges = 0;
+
+ while (list < last) {
+ struct commit_list *parent;
+ int edge_value;
+ uint32_t packedDate[2];
+
+ parse_commit(*list);
+ hashwrite(f, get_commit_tree_oid(*list)->hash, hash_len);
+
+ parent = (*list)->parents;
+
+ if (!parent)
+ edge_value = GRAPH_PARENT_NONE;
+ else {
+ edge_value = sha1_pos(parent->item->object.oid.hash,
+ commits,
+ nr_commits,
+ commit_to_sha1);
+
+ if (edge_value < 0)
+ edge_value = GRAPH_PARENT_MISSING;
+ }
+
+ hashwrite_be32(f, edge_value);
+
+ if (parent)
+ parent = parent->next;
+
+ if (!parent)
+ edge_value = GRAPH_PARENT_NONE;
+ else if (parent->next)
+ edge_value = GRAPH_OCTOPUS_EDGES_NEEDED | num_extra_edges;
+ else {
+ edge_value = sha1_pos(parent->item->object.oid.hash,
+ commits,
+ nr_commits,
+ commit_to_sha1);
+ if (edge_value < 0)
+ edge_value = GRAPH_PARENT_MISSING;
+ }
+
+ hashwrite_be32(f, edge_value);
+
+ if (edge_value & GRAPH_OCTOPUS_EDGES_NEEDED) {
+ do {
+ num_extra_edges++;
+ parent = parent->next;
+ } while (parent);
+ }
+
+ if (sizeof((*list)->date) > 4)
+ packedDate[0] = htonl(((*list)->date >> 32) & 0x3);
+ else
+ packedDate[0] = 0;
+
+ packedDate[1] = htonl((*list)->date);
+ hashwrite(f, packedDate, 8);
+
+ list++;
+ }
+}
+
+static void write_graph_chunk_large_edges(struct hashfile *f,
+ struct commit **commits,
+ int nr_commits)
+{
+ struct commit **list = commits;
+ struct commit **last = commits + nr_commits;
+ struct commit_list *parent;
+
+ while (list < last) {
+ int num_parents = 0;
+ for (parent = (*list)->parents; num_parents < 3 && parent;
+ parent = parent->next)
+ num_parents++;
+
+ if (num_parents <= 2) {
+ list++;
+ continue;
+ }
+
+ /* Since num_parents > 2, this initializer is safe. */
+ for (parent = (*list)->parents->next; parent; parent = parent->next) {
+ int edge_value = sha1_pos(parent->item->object.oid.hash,
+ commits,
+ nr_commits,
+ commit_to_sha1);
+
+ if (edge_value < 0)
+ edge_value = GRAPH_PARENT_MISSING;
+ else if (!parent->next)
+ edge_value |= GRAPH_LAST_EDGE;
+
+ hashwrite_be32(f, edge_value);
+ }
+
+ list++;
+ }
+}
+
+static int commit_compare(const void *_a, const void *_b)
+{
+ const struct object_id *a = (const struct object_id *)_a;
+ const struct object_id *b = (const struct object_id *)_b;
+ return oidcmp(a, b);
+}
+
+struct packed_commit_list {
+ struct commit **list;
+ int nr;
+ int alloc;
+};
+
+struct packed_oid_list {
+ struct object_id *list;
+ int nr;
+ int alloc;
+};
+
+static int add_packed_commits(const struct object_id *oid,
+ struct packed_git *pack,
+ uint32_t pos,
+ void *data)
+{
+ struct packed_oid_list *list = (struct packed_oid_list*)data;
+ enum object_type type;
+ off_t offset = nth_packed_object_offset(pack, pos);
+ struct object_info oi = OBJECT_INFO_INIT;
+
+ oi.typep = &type;
+ if (packed_object_info(the_repository, pack, offset, &oi) < 0)
+ die("unable to get type of object %s", oid_to_hex(oid));
+
+ if (type != OBJ_COMMIT)
+ return 0;
+
+ ALLOC_GROW(list->list, list->nr + 1, list->alloc);
+ oidcpy(&(list->list[list->nr]), oid);
+ list->nr++;
+
+ return 0;
+}
+
+static void add_missing_parents(struct packed_oid_list *oids, struct commit *commit)
+{
+ struct commit_list *parent;
+ for (parent = commit->parents; parent; parent = parent->next) {
+ if (!(parent->item->object.flags & UNINTERESTING)) {
+ ALLOC_GROW(oids->list, oids->nr + 1, oids->alloc);
+ oidcpy(&oids->list[oids->nr], &(parent->item->object.oid));
+ oids->nr++;
+ parent->item->object.flags |= UNINTERESTING;
+ }
+ }
+}
+
+static void close_reachable(struct packed_oid_list *oids)
+{
+ int i;
+ struct commit *commit;
+
+ for (i = 0; i < oids->nr; i++) {
+ commit = lookup_commit(&oids->list[i]);
+ if (commit)
+ commit->object.flags |= UNINTERESTING;
+ }
+
+ /*
+ * As this loop runs, oids->nr may grow, but not more
+ * than the number of missing commits in the reachable
+ * closure.
+ */
+ for (i = 0; i < oids->nr; i++) {
+ commit = lookup_commit(&oids->list[i]);
+
+ if (commit && !parse_commit(commit))
+ add_missing_parents(oids, commit);
+ }
+
+ for (i = 0; i < oids->nr; i++) {
+ commit = lookup_commit(&oids->list[i]);
+
+ if (commit)
+ commit->object.flags &= ~UNINTERESTING;
+ }
+}
+
+void write_commit_graph(const char *obj_dir,
+ const char **pack_indexes,
+ int nr_packs,
+ const char **commit_hex,
+ int nr_commits,
+ int append)
+{
+ struct packed_oid_list oids;
+ struct packed_commit_list commits;
+ struct hashfile *f;
+ uint32_t i, count_distinct = 0;
+ char *graph_name;
+ int fd;
+ struct lock_file lk = LOCK_INIT;
+ uint32_t chunk_ids[5];
+ uint64_t chunk_offsets[5];
+ int num_chunks;
+ int num_extra_edges;
+ struct commit_list *parent;
+
+ oids.nr = 0;
+ oids.alloc = approximate_object_count() / 4;
+
+ if (append) {
+ prepare_commit_graph_one(obj_dir);
+ if (commit_graph)
+ oids.alloc += commit_graph->num_commits;
+ }
+
+ if (oids.alloc < 1024)
+ oids.alloc = 1024;
+ ALLOC_ARRAY(oids.list, oids.alloc);
+
+ if (append && commit_graph) {
+ for (i = 0; i < commit_graph->num_commits; i++) {
+ const unsigned char *hash = commit_graph->chunk_oid_lookup +
+ commit_graph->hash_len * i;
+ hashcpy(oids.list[oids.nr++].hash, hash);
+ }
+ }
+
+ if (pack_indexes) {
+ struct strbuf packname = STRBUF_INIT;
+ int dirlen;
+ strbuf_addf(&packname, "%s/pack/", obj_dir);
+ dirlen = packname.len;
+ for (i = 0; i < nr_packs; i++) {
+ struct packed_git *p;
+ strbuf_setlen(&packname, dirlen);
+ strbuf_addstr(&packname, pack_indexes[i]);
+ p = add_packed_git(packname.buf, packname.len, 1);
+ if (!p)
+ die("error adding pack %s", packname.buf);
+ if (open_pack_index(p))
+ die("error opening index for %s", packname.buf);
+ for_each_object_in_pack(p, add_packed_commits, &oids);
+ close_pack(p);
+ }
+ strbuf_release(&packname);
+ }
+
+ if (commit_hex) {
+ for (i = 0; i < nr_commits; i++) {
+ const char *end;
+ struct object_id oid;
+ struct commit *result;
+
+ if (commit_hex[i] && parse_oid_hex(commit_hex[i], &oid, &end))
+ continue;
+
+ result = lookup_commit_reference_gently(&oid, 1);
+
+ if (result) {
+ ALLOC_GROW(oids.list, oids.nr + 1, oids.alloc);
+ oidcpy(&oids.list[oids.nr], &(result->object.oid));
+ oids.nr++;
+ }
+ }
+ }
+
+ if (!pack_indexes && !commit_hex)
+ for_each_packed_object(add_packed_commits, &oids, 0);
+
+ close_reachable(&oids);
+
+ QSORT(oids.list, oids.nr, commit_compare);
+
+ count_distinct = 1;
+ for (i = 1; i < oids.nr; i++) {
+ if (oidcmp(&oids.list[i-1], &oids.list[i]))
+ count_distinct++;
+ }
+
+ if (count_distinct >= GRAPH_PARENT_MISSING)
+ die(_("the commit graph format cannot write %d commits"), count_distinct);
+
+ commits.nr = 0;
+ commits.alloc = count_distinct;
+ ALLOC_ARRAY(commits.list, commits.alloc);
+
+ num_extra_edges = 0;
+ for (i = 0; i < oids.nr; i++) {
+ int num_parents = 0;
+ if (i > 0 && !oidcmp(&oids.list[i-1], &oids.list[i]))
+ continue;
+
+ commits.list[commits.nr] = lookup_commit(&oids.list[i]);
+ parse_commit(commits.list[commits.nr]);
+
+ for (parent = commits.list[commits.nr]->parents;
+ parent; parent = parent->next)
+ num_parents++;
+
+ if (num_parents > 2)
+ num_extra_edges += num_parents - 1;
+
+ commits.nr++;
+ }
+ num_chunks = num_extra_edges ? 4 : 3;
+
+ if (commits.nr >= GRAPH_PARENT_MISSING)
+ die(_("too many commits to write graph"));
+
+ graph_name = get_commit_graph_filename(obj_dir);
+ fd = hold_lock_file_for_update(&lk, graph_name, 0);
+
+ if (fd < 0) {
+ struct strbuf folder = STRBUF_INIT;
+ strbuf_addstr(&folder, graph_name);
+ strbuf_setlen(&folder, strrchr(folder.buf, '/') - folder.buf);
+
+ if (mkdir(folder.buf, 0777) < 0)
+ die_errno(_("cannot mkdir %s"), folder.buf);
+ strbuf_release(&folder);
+
+ fd = hold_lock_file_for_update(&lk, graph_name, LOCK_DIE_ON_ERROR);
+
+ if (fd < 0)
+ die_errno("unable to create '%s'", graph_name);
+ }
+
+ f = hashfd(lk.tempfile->fd, lk.tempfile->filename.buf);
+
+ hashwrite_be32(f, GRAPH_SIGNATURE);
+
+ hashwrite_u8(f, GRAPH_VERSION);
+ hashwrite_u8(f, GRAPH_OID_VERSION);
+ hashwrite_u8(f, num_chunks);
+ hashwrite_u8(f, 0); /* unused padding byte */
+
+ chunk_ids[0] = GRAPH_CHUNKID_OIDFANOUT;
+ chunk_ids[1] = GRAPH_CHUNKID_OIDLOOKUP;
+ chunk_ids[2] = GRAPH_CHUNKID_DATA;
+ if (num_extra_edges)
+ chunk_ids[3] = GRAPH_CHUNKID_LARGEEDGES;
+ else
+ chunk_ids[3] = 0;
+ chunk_ids[4] = 0;
+
+ chunk_offsets[0] = 8 + (num_chunks + 1) * GRAPH_CHUNKLOOKUP_WIDTH;
+ chunk_offsets[1] = chunk_offsets[0] + GRAPH_FANOUT_SIZE;
+ chunk_offsets[2] = chunk_offsets[1] + GRAPH_OID_LEN * commits.nr;
+ chunk_offsets[3] = chunk_offsets[2] + (GRAPH_OID_LEN + 16) * commits.nr;
+ chunk_offsets[4] = chunk_offsets[3] + 4 * num_extra_edges;
+
+ for (i = 0; i <= num_chunks; i++) {
+ uint32_t chunk_write[3];
+
+ chunk_write[0] = htonl(chunk_ids[i]);
+ chunk_write[1] = htonl(chunk_offsets[i] >> 32);
+ chunk_write[2] = htonl(chunk_offsets[i] & 0xffffffff);
+ hashwrite(f, chunk_write, 12);
+ }
+
+ write_graph_chunk_fanout(f, commits.list, commits.nr);
+ write_graph_chunk_oids(f, GRAPH_OID_LEN, commits.list, commits.nr);
+ write_graph_chunk_data(f, GRAPH_OID_LEN, commits.list, commits.nr);
+ write_graph_chunk_large_edges(f, commits.list, commits.nr);
+
+ close_commit_graph();
+ finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_FSYNC);
+ commit_lock_file(&lk);
+
+ free(oids.list);
+ oids.alloc = 0;
+ oids.nr = 0;
+}
diff --git a/commit-graph.h b/commit-graph.h
new file mode 100644
index 0000000..260a468
--- /dev/null
+++ b/commit-graph.h
@@ -0,0 +1,48 @@
+#ifndef COMMIT_GRAPH_H
+#define COMMIT_GRAPH_H
+
+#include "git-compat-util.h"
+
+char *get_commit_graph_filename(const char *obj_dir);
+
+/*
+ * Given a commit struct, try to fill the commit struct info, including:
+ * 1. tree object
+ * 2. date
+ * 3. parents.
+ *
+ * Returns 1 if and only if the commit was found in the packed graph.
+ *
+ * See parse_commit_buffer() for the fallback after this call.
+ */
+int parse_commit_in_graph(struct commit *item);
+
+struct tree *get_commit_tree_in_graph(const struct commit *c);
+
+struct commit_graph {
+ int graph_fd;
+
+ const unsigned char *data;
+ size_t data_len;
+
+ unsigned char hash_len;
+ unsigned char num_chunks;
+ uint32_t num_commits;
+ struct object_id oid;
+
+ const uint32_t *chunk_oid_fanout;
+ const unsigned char *chunk_oid_lookup;
+ const unsigned char *chunk_commit_data;
+ const unsigned char *chunk_large_edges;
+};
+
+struct commit_graph *load_commit_graph_one(const char *graph_file);
+
+void write_commit_graph(const char *obj_dir,
+ const char **pack_indexes,
+ int nr_packs,
+ const char **commit_hex,
+ int nr_commits,
+ int append);
+
+#endif
diff --git a/commit.c b/commit.c
index ca474a7..b0e57cc 100644
--- a/commit.c
+++ b/commit.c
@@ -1,6 +1,7 @@
#include "cache.h"
#include "tag.h"
#include "commit.h"
+#include "commit-graph.h"
#include "pkt-line.h"
#include "utf8.h"
#include "diff.h"
@@ -12,6 +13,7 @@
#include "prio-queue.h"
#include "sha1-lookup.h"
#include "wt-status.h"
+#include "advice.h"
static struct commit_extra_header *read_commit_extra_header_lines(const char *buf, size_t len, const char **);
@@ -176,6 +178,15 @@ static int read_graft_file(const char *graft_file)
struct strbuf buf = STRBUF_INIT;
if (!fp)
return -1;
+ if (advice_graft_file_deprecated)
+ advise(_("Support for <GIT_DIR>/info/grafts is deprecated\n"
+ "and will be removed in a future Git version.\n"
+ "\n"
+ "Please use \"git replace --convert-graft-file\"\n"
+ "to convert the grafts into replace refs.\n"
+ "\n"
+ "Turn this message off by running\n"
+ "\"git config advice.graftFileDeprecated false\""));
while (!strbuf_getwholeline(&buf, fp, '\n')) {
/* The format is just "Commit Parent1 Parent2 ...\n" */
struct commit_graft *graft = read_graft_line(&buf);
@@ -295,6 +306,22 @@ void free_commit_buffer(struct commit *commit)
}
}
+struct tree *get_commit_tree(const struct commit *commit)
+{
+ if (commit->maybe_tree || !commit->object.parsed)
+ return commit->maybe_tree;
+
+ if (commit->graph_pos == COMMIT_NOT_FROM_GRAPH)
+ BUG("commit has NULL tree, but was not loaded from commit-graph");
+
+ return get_commit_tree_in_graph(commit);
+}
+
+struct object_id *get_commit_tree_oid(const struct commit *commit)
+{
+ return &get_commit_tree(commit)->object.oid;
+}
+
const void *detach_commit_buffer(struct commit *commit, unsigned long *sizep)
{
struct commit_buffer *v = buffer_slab_peek(&buffer_slab, commit);
@@ -331,10 +358,10 @@ int parse_commit_buffer(struct commit *item, const void *buffer, unsigned long s
if (tail <= bufptr + tree_entry_len + 1 || memcmp(bufptr, "tree ", 5) ||
bufptr[tree_entry_len] != '\n')
return error("bogus commit object %s", oid_to_hex(&item->object.oid));
- if (get_sha1_hex(bufptr + 5, parent.hash) < 0)
+ if (get_oid_hex(bufptr + 5, &parent) < 0)
return error("bad tree pointer in commit %s",
oid_to_hex(&item->object.oid));
- item->tree = lookup_tree(&parent);
+ item->maybe_tree = lookup_tree(&parent);
bufptr += tree_entry_len + 1; /* "tree " + "hex sha1" + "\n" */
pptr = &item->parents;
@@ -343,7 +370,7 @@ int parse_commit_buffer(struct commit *item, const void *buffer, unsigned long s
struct commit *new_parent;
if (tail <= bufptr + parent_entry_len + 1 ||
- get_sha1_hex(bufptr + 7, parent.hash) ||
+ get_oid_hex(bufptr + 7, &parent) ||
bufptr[parent_entry_len] != '\n')
return error("bad parents in commit %s", oid_to_hex(&item->object.oid));
bufptr += parent_entry_len + 1;
@@ -383,6 +410,8 @@ int parse_commit_gently(struct commit *item, int quiet_on_missing)
return -1;
if (item->object.parsed)
return 0;
+ if (parse_commit_in_graph(item))
+ return 0;
buffer = read_object_file(&item->object.oid, &type, &size);
if (!buffer)
return quiet_on_missing ? -1 :
@@ -1288,17 +1317,19 @@ struct commit_extra_header *read_commit_extra_headers(struct commit *commit,
return extra;
}
-void for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data)
+int for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data)
{
struct commit_extra_header *extra, *to_free;
+ int res = 0;
to_free = read_commit_extra_headers(commit, NULL);
- for (extra = to_free; extra; extra = extra->next) {
+ for (extra = to_free; !res && extra; extra = extra->next) {
if (strcmp(extra->key, "mergetag"))
continue; /* not a merge tag */
- fn(commit, extra, data);
+ res = fn(commit, extra, data);
}
free_commit_extra_headers(to_free);
+ return res;
}
static inline int standard_header_field(const char *field, size_t len)
diff --git a/commit.h b/commit.h
index 0fb8271..c3af512 100644
--- a/commit.h
+++ b/commit.h
@@ -9,6 +9,8 @@
#include "string-list.h"
#include "pretty.h"
+#define COMMIT_NOT_FROM_GRAPH 0xFFFFFFFF
+
struct commit_list {
struct commit *item;
struct commit_list *next;
@@ -17,10 +19,17 @@ struct commit_list {
struct commit {
struct object object;
void *util;
- unsigned int index;
timestamp_t date;
struct commit_list *parents;
- struct tree *tree;
+
+ /*
+ * If the commit is loaded from the commit-graph file, then this
+ * member may be NULL. Only access it through get_commit_tree()
+ * or get_commit_tree_oid().
+ */
+ struct tree *maybe_tree;
+ uint32_t graph_pos;
+ unsigned int index;
};
extern int save_commit_buffer;
@@ -99,6 +108,9 @@ void unuse_commit_buffer(const struct commit *, const void *buffer);
*/
void free_commit_buffer(struct commit *);
+struct tree *get_commit_tree(const struct commit *);
+struct object_id *get_commit_tree_oid(const struct commit *);
+
/*
* Disassociate any cached object buffer from the commit, but do not free it.
* The buffer (or NULL, if none) is returned.
@@ -291,10 +303,10 @@ extern const char *find_commit_header(const char *msg, const char *key,
/* Find the end of the log message, the right place for a new trailer. */
extern int ignore_non_trailer(const char *buf, size_t len);
-typedef void (*each_mergetag_fn)(struct commit *commit, struct commit_extra_header *extra,
+typedef int (*each_mergetag_fn)(struct commit *commit, struct commit_extra_header *extra,
void *cb_data);
-extern void for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data);
+extern int for_each_mergetag(each_mergetag_fn fn, struct commit *commit, void *data);
struct merge_remote_desc {
struct object *obj; /* the named object, could be a tag */
diff --git a/common-main.c b/common-main.c
index 7d716d5..3728f66 100644
--- a/common-main.c
+++ b/common-main.c
@@ -1,5 +1,5 @@
#include "cache.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "attr.h"
/*
@@ -32,14 +32,14 @@ int main(int argc, const char **argv)
*/
sanitize_stdfds();
+ git_resolve_executable_dir(argv[0]);
+
git_setup_gettext();
initialize_the_repository();
attr_start();
- git_extract_argv0_path(argv[0]);
-
restore_sigpipe_to_default();
return cmd_main(argc, argv);
diff --git a/compat/mingw.c b/compat/mingw.c
index a67872b..6ded1c8 100644
--- a/compat/mingw.c
+++ b/compat/mingw.c
@@ -2221,7 +2221,7 @@ void mingw_startup(void)
die_startup();
/* determine size of argv and environ conversion buffer */
- maxlen = wcslen(_wpgmptr);
+ maxlen = wcslen(wargv[0]);
for (i = 1; i < argc; i++)
maxlen = max(maxlen, wcslen(wargv[i]));
for (i = 0; wenv[i]; i++)
@@ -2241,8 +2241,7 @@ void mingw_startup(void)
buffer = malloc_startup(maxlen);
/* convert command line arguments and environment to UTF-8 */
- __argv[0] = wcstoutfdup_startup(buffer, _wpgmptr, maxlen);
- for (i = 1; i < argc; i++)
+ for (i = 0; i < argc; i++)
__argv[i] = wcstoutfdup_startup(buffer, wargv[i], maxlen);
for (i = 0; wenv[i]; i++)
environ[i] = wcstoutfdup_startup(buffer, wenv[i], maxlen);
diff --git a/config.c b/config.c
index c698988..fbbf0f8 100644
--- a/config.c
+++ b/config.c
@@ -9,13 +9,14 @@
#include "config.h"
#include "repository.h"
#include "lockfile.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "strbuf.h"
#include "quote.h"
#include "hashmap.h"
#include "string-list.h"
#include "utf8.h"
#include "dir.h"
+#include "color.h"
struct config_source {
struct config_source *prev;
@@ -102,7 +103,7 @@ static int config_buf_ungetc(int c, struct config_source *conf)
if (conf->u.buf.pos > 0) {
conf->u.buf.pos--;
if (conf->u.buf.buf[conf->u.buf.pos] != c)
- die("BUG: config_buf can only ungetc the same character");
+ BUG("config_buf can only ungetc the same character");
return c;
}
@@ -189,7 +190,7 @@ static int prepare_include_condition_pattern(struct strbuf *pat)
strbuf_realpath(&path, cf->path, 1);
slash = find_last_dir_sep(path.buf);
if (!slash)
- die("BUG: how is this possible?");
+ BUG("how is this possible?");
strbuf_splice(pat, 0, 1, path.buf, slash - path.buf);
prefix = slash - path.buf + 1 /* slash */;
} else if (!is_absolute_path(pat->buf))
@@ -653,7 +654,45 @@ static int get_base_var(struct strbuf *name)
}
}
-static int git_parse_source(config_fn_t fn, void *data)
+struct parse_event_data {
+ enum config_event_t previous_type;
+ size_t previous_offset;
+ const struct config_options *opts;
+};
+
+static int do_event(enum config_event_t type, struct parse_event_data *data)
+{
+ size_t offset;
+
+ if (!data->opts || !data->opts->event_fn)
+ return 0;
+
+ if (type == CONFIG_EVENT_WHITESPACE &&
+ data->previous_type == type)
+ return 0;
+
+ offset = cf->do_ftell(cf);
+ /*
+ * At EOF, the parser always "inserts" an extra '\n', therefore
+ * the end offset of the event is the current file position, otherwise
+ * we will already have advanced to the next event.
+ */
+ if (type != CONFIG_EVENT_EOF)
+ offset--;
+
+ if (data->previous_type != CONFIG_EVENT_EOF &&
+ data->opts->event_fn(data->previous_type, data->previous_offset,
+ offset, data->opts->event_fn_data) < 0)
+ return -1;
+
+ data->previous_type = type;
+ data->previous_offset = offset;
+
+ return 0;
+}
+
+static int git_parse_source(config_fn_t fn, void *data,
+ const struct config_options *opts)
{
int comment = 0;
int baselen = 0;
@@ -664,8 +703,15 @@ static int git_parse_source(config_fn_t fn, void *data)
/* U+FEFF Byte Order Mark in UTF8 */
const char *bomptr = utf8_bom;
+ /* For the parser event callback */
+ struct parse_event_data event_data = {
+ CONFIG_EVENT_EOF, 0, opts
+ };
+
for (;;) {
- int c = get_next_char();
+ int c;
+
+ c = get_next_char();
if (bomptr && *bomptr) {
/* We are at the file beginning; skip UTF8-encoded BOM
* if present. Sane editors won't put this in on their
@@ -682,18 +728,33 @@ static int git_parse_source(config_fn_t fn, void *data)
}
}
if (c == '\n') {
- if (cf->eof)
+ if (cf->eof) {
+ if (do_event(CONFIG_EVENT_EOF, &event_data) < 0)
+ return -1;
return 0;
+ }
+ if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
+ return -1;
comment = 0;
continue;
}
- if (comment || isspace(c))
+ if (comment)
+ continue;
+ if (isspace(c)) {
+ if (do_event(CONFIG_EVENT_WHITESPACE, &event_data) < 0)
+ return -1;
continue;
+ }
if (c == '#' || c == ';') {
+ if (do_event(CONFIG_EVENT_COMMENT, &event_data) < 0)
+ return -1;
comment = 1;
continue;
}
if (c == '[') {
+ if (do_event(CONFIG_EVENT_SECTION, &event_data) < 0)
+ return -1;
+
/* Reset prior to determining a new stem */
strbuf_reset(var);
if (get_base_var(var) < 0 || var->len < 1)
@@ -704,6 +765,10 @@ static int git_parse_source(config_fn_t fn, void *data)
}
if (!isalpha(c))
break;
+
+ if (do_event(CONFIG_EVENT_ENTRY, &event_data) < 0)
+ return -1;
+
/*
* Truncate the var name back to the section header
* stem prior to grabbing the suffix part of the name
@@ -715,6 +780,9 @@ static int git_parse_source(config_fn_t fn, void *data)
break;
}
+ if (do_event(CONFIG_EVENT_ERROR, &event_data) < 0)
+ return -1;
+
switch (cf->origin_type) {
case CONFIG_ORIGIN_BLOB:
error_msg = xstrfmt(_("bad config line %d in blob %s"),
@@ -1000,6 +1068,15 @@ int git_config_expiry_date(timestamp_t *timestamp, const char *var, const char *
return 0;
}
+int git_config_color(char *dest, const char *var, const char *value)
+{
+ if (!value)
+ return config_error_nonbool(var);
+ if (color_parse(value, dest) < 0)
+ return -1;
+ return 0;
+}
+
static int git_default_core_config(const char *var, const char *value)
{
/* This needs a better name */
@@ -1172,6 +1249,11 @@ static int git_default_core_config(const char *var, const char *value)
return 0;
}
+ if (!strcmp(var, "core.checkroundtripencoding")) {
+ check_roundtrip_encoding = xstrdup(value);
+ return 0;
+ }
+
if (!strcmp(var, "core.notesref")) {
notes_ref_name = xstrdup(value);
return 0;
@@ -1226,6 +1308,11 @@ static int git_default_core_config(const char *var, const char *value)
return 0;
}
+ if (!strcmp(var, "core.commitgraph")) {
+ core_commit_graph = git_config_bool(var, value);
+ return 0;
+ }
+
if (!strcmp(var, "core.sparsecheckout")) {
core_apply_sparse_checkout = git_config_bool(var, value);
return 0;
@@ -1365,7 +1452,7 @@ int git_default_config(const char *var, const char *value, void *dummy)
if (starts_with(var, "mailmap."))
return git_default_mailmap_config(var, value);
- if (starts_with(var, "advice."))
+ if (starts_with(var, "advice.") || starts_with(var, "color.advice"))
return git_default_advice_config(var, value);
if (!strcmp(var, "pager.color") || !strcmp(var, "color.pager")) {
@@ -1398,7 +1485,8 @@ int git_default_config(const char *var, const char *value, void *dummy)
* fgetc, ungetc, ftell of top need to be initialized before calling
* this function.
*/
-static int do_config_from(struct config_source *top, config_fn_t fn, void *data)
+static int do_config_from(struct config_source *top, config_fn_t fn, void *data,
+ const struct config_options *opts)
{
int ret;
@@ -1410,7 +1498,7 @@ static int do_config_from(struct config_source *top, config_fn_t fn, void *data)
strbuf_init(&top->var, 1024);
cf = top;
- ret = git_parse_source(fn, data);
+ ret = git_parse_source(fn, data, opts);
/* pop config-file parsing state stack */
strbuf_release(&top->value);
@@ -1423,9 +1511,10 @@ static int do_config_from(struct config_source *top, config_fn_t fn, void *data)
static int do_config_from_file(config_fn_t fn,
const enum config_origin_type origin_type,
const char *name, const char *path, FILE *f,
- void *data)
+ void *data, const struct config_options *opts)
{
struct config_source top;
+ int ret;
top.u.file = f;
top.origin_type = origin_type;
@@ -1436,29 +1525,39 @@ static int do_config_from_file(config_fn_t fn,
top.do_ungetc = config_file_ungetc;
top.do_ftell = config_file_ftell;
- return do_config_from(&top, fn, data);
+ flockfile(f);
+ ret = do_config_from(&top, fn, data, opts);
+ funlockfile(f);
+ return ret;
}
static int git_config_from_stdin(config_fn_t fn, void *data)
{
- return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin, data);
+ return do_config_from_file(fn, CONFIG_ORIGIN_STDIN, "", NULL, stdin,
+ data, NULL);
}
-int git_config_from_file(config_fn_t fn, const char *filename, void *data)
+int git_config_from_file_with_options(config_fn_t fn, const char *filename,
+ void *data,
+ const struct config_options *opts)
{
int ret = -1;
FILE *f;
f = fopen_or_warn(filename, "r");
if (f) {
- flockfile(f);
- ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename, filename, f, data);
- funlockfile(f);
+ ret = do_config_from_file(fn, CONFIG_ORIGIN_FILE, filename,
+ filename, f, data, opts);
fclose(f);
}
return ret;
}
+int git_config_from_file(config_fn_t fn, const char *filename, void *data)
+{
+ return git_config_from_file_with_options(fn, filename, data, NULL);
+}
+
int git_config_from_mem(config_fn_t fn, const enum config_origin_type origin_type,
const char *name, const char *buf, size_t len, void *data)
{
@@ -1475,7 +1574,7 @@ int git_config_from_mem(config_fn_t fn, const enum config_origin_type origin_typ
top.do_ungetc = config_buf_ungetc;
top.do_ftell = config_buf_ftell;
- return do_config_from(&top, fn, data);
+ return do_config_from(&top, fn, data, NULL);
}
int git_config_from_blob_oid(config_fn_t fn,
@@ -1715,7 +1814,7 @@ static int configset_add_value(struct config_set *cs, const char *key, const cha
l_item->value_index = e->value_list.nr - 1;
if (!cf)
- die("BUG: configset_add_value has no source");
+ BUG("configset_add_value has no source");
if (cf->name) {
kv_info->filename = strintern(cf->name);
kv_info->linenr = cf->linenr;
@@ -2219,96 +2318,111 @@ void git_die_config(const char *key, const char *err, ...)
* Find all the stuff for git_config_set() below.
*/
-static struct {
+struct config_store_data {
int baselen;
char *key;
int do_not_match;
regex_t *value_regex;
int multi_replace;
- size_t *offset;
- unsigned int offset_alloc;
- enum { START, SECTION_SEEN, SECTION_END_SEEN, KEY_SEEN } state;
- unsigned int seen;
-} store;
+ struct {
+ size_t begin, end;
+ enum config_event_t type;
+ int is_keys_section;
+ } *parsed;
+ unsigned int parsed_nr, parsed_alloc, *seen, seen_nr, seen_alloc;
+ unsigned int key_seen:1, section_seen:1, is_keys_section:1;
+};
-static int matches(const char *key, const char *value)
+static void config_store_data_clear(struct config_store_data *store)
{
- if (strcmp(key, store.key))
+ free(store->key);
+ if (store->value_regex != NULL &&
+ store->value_regex != CONFIG_REGEX_NONE) {
+ regfree(store->value_regex);
+ free(store->value_regex);
+ }
+ free(store->parsed);
+ free(store->seen);
+ memset(store, 0, sizeof(*store));
+}
+
+static int matches(const char *key, const char *value,
+ const struct config_store_data *store)
+{
+ if (strcmp(key, store->key))
return 0; /* not ours */
- if (!store.value_regex)
+ if (!store->value_regex)
return 1; /* always matches */
- if (store.value_regex == CONFIG_REGEX_NONE)
+ if (store->value_regex == CONFIG_REGEX_NONE)
return 0; /* never matches */
- return store.do_not_match ^
- (value && !regexec(store.value_regex, value, 0, NULL, 0));
+ return store->do_not_match ^
+ (value && !regexec(store->value_regex, value, 0, NULL, 0));
+}
+
+static int store_aux_event(enum config_event_t type,
+ size_t begin, size_t end, void *data)
+{
+ struct config_store_data *store = data;
+
+ ALLOC_GROW(store->parsed, store->parsed_nr + 1, store->parsed_alloc);
+ store->parsed[store->parsed_nr].begin = begin;
+ store->parsed[store->parsed_nr].end = end;
+ store->parsed[store->parsed_nr].type = type;
+
+ if (type == CONFIG_EVENT_SECTION) {
+ if (cf->var.len < 2 || cf->var.buf[cf->var.len - 1] != '.')
+ return error("invalid section name '%s'", cf->var.buf);
+
+ /* Is this the section we were looking for? */
+ store->is_keys_section =
+ store->parsed[store->parsed_nr].is_keys_section =
+ cf->var.len - 1 == store->baselen &&
+ !strncasecmp(cf->var.buf, store->key, store->baselen);
+ if (store->is_keys_section) {
+ store->section_seen = 1;
+ ALLOC_GROW(store->seen, store->seen_nr + 1,
+ store->seen_alloc);
+ store->seen[store->seen_nr] = store->parsed_nr;
+ }
+ }
+
+ store->parsed_nr++;
+
+ return 0;
}
static int store_aux(const char *key, const char *value, void *cb)
{
- const char *ep;
- size_t section_len;
+ struct config_store_data *store = cb;
- switch (store.state) {
- case KEY_SEEN:
- if (matches(key, value)) {
- if (store.seen == 1 && store.multi_replace == 0) {
+ if (store->key_seen) {
+ if (matches(key, value, store)) {
+ if (store->seen_nr == 1 && store->multi_replace == 0) {
warning(_("%s has multiple values"), key);
}
- ALLOC_GROW(store.offset, store.seen + 1,
- store.offset_alloc);
+ ALLOC_GROW(store->seen, store->seen_nr + 1,
+ store->seen_alloc);
- store.offset[store.seen] = cf->do_ftell(cf);
- store.seen++;
+ store->seen[store->seen_nr] = store->parsed_nr;
+ store->seen_nr++;
}
- break;
- case SECTION_SEEN:
+ } else if (store->is_keys_section) {
/*
- * What we are looking for is in store.key (both
- * section and var), and its section part is baselen
- * long. We found key (again, both section and var).
- * We would want to know if this key is in the same
- * section as what we are looking for. We already
- * know we are in the same section as what should
- * hold store.key.
+ * Do not increment matches yet: this may not be a match, but we
+ * are in the desired section.
*/
- ep = strrchr(key, '.');
- section_len = ep - key;
+ ALLOC_GROW(store->seen, store->seen_nr + 1, store->seen_alloc);
+ store->seen[store->seen_nr] = store->parsed_nr;
+ store->section_seen = 1;
- if ((section_len != store.baselen) ||
- memcmp(key, store.key, section_len+1)) {
- store.state = SECTION_END_SEEN;
- break;
- }
-
- /*
- * Do not increment matches: this is no match, but we
- * just made sure we are in the desired section.
- */
- ALLOC_GROW(store.offset, store.seen + 1,
- store.offset_alloc);
- store.offset[store.seen] = cf->do_ftell(cf);
- /* fallthru */
- case SECTION_END_SEEN:
- case START:
- if (matches(key, value)) {
- ALLOC_GROW(store.offset, store.seen + 1,
- store.offset_alloc);
- store.offset[store.seen] = cf->do_ftell(cf);
- store.state = KEY_SEEN;
- store.seen++;
- } else {
- if (strrchr(key, '.') - key == store.baselen &&
- !strncmp(key, store.key, store.baselen)) {
- store.state = SECTION_SEEN;
- ALLOC_GROW(store.offset,
- store.seen + 1,
- store.offset_alloc);
- store.offset[store.seen] = cf->do_ftell(cf);
- }
+ if (matches(key, value, store)) {
+ store->seen_nr++;
+ store->key_seen = 1;
}
}
+
return 0;
}
@@ -2320,31 +2434,33 @@ static int write_error(const char *filename)
return 4;
}
-static struct strbuf store_create_section(const char *key)
+static struct strbuf store_create_section(const char *key,
+ const struct config_store_data *store)
{
const char *dot;
int i;
struct strbuf sb = STRBUF_INIT;
- dot = memchr(key, '.', store.baselen);
+ dot = memchr(key, '.', store->baselen);
if (dot) {
strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key);
- for (i = dot - key + 1; i < store.baselen; i++) {
+ for (i = dot - key + 1; i < store->baselen; i++) {
if (key[i] == '"' || key[i] == '\\')
strbuf_addch(&sb, '\\');
strbuf_addch(&sb, key[i]);
}
strbuf_addstr(&sb, "\"]\n");
} else {
- strbuf_addf(&sb, "[%.*s]\n", store.baselen, key);
+ strbuf_addf(&sb, "[%.*s]\n", store->baselen, key);
}
return sb;
}
-static ssize_t write_section(int fd, const char *key)
+static ssize_t write_section(int fd, const char *key,
+ const struct config_store_data *store)
{
- struct strbuf sb = store_create_section(key);
+ struct strbuf sb = store_create_section(key, store);
ssize_t ret;
ret = write_in_full(fd, sb.buf, sb.len);
@@ -2353,11 +2469,12 @@ static ssize_t write_section(int fd, const char *key)
return ret;
}
-static ssize_t write_pair(int fd, const char *key, const char *value)
+static ssize_t write_pair(int fd, const char *key, const char *value,
+ const struct config_store_data *store)
{
int i;
ssize_t ret;
- int length = strlen(key + store.baselen + 1);
+ int length = strlen(key + store->baselen + 1);
const char *quote = "";
struct strbuf sb = STRBUF_INIT;
@@ -2377,7 +2494,7 @@ static ssize_t write_pair(int fd, const char *key, const char *value)
quote = "\"";
strbuf_addf(&sb, "\t%.*s = %s",
- length, key + store.baselen + 1, quote);
+ length, key + store->baselen + 1, quote);
for (i = 0; value[i]; i++)
switch (value[i]) {
@@ -2403,30 +2520,85 @@ static ssize_t write_pair(int fd, const char *key, const char *value)
return ret;
}
-static ssize_t find_beginning_of_line(const char *contents, size_t size,
- size_t offset_, int *found_bracket)
+/*
+ * If we are about to unset the last key(s) in a section, and if there are
+ * no comments surrounding (or included in) the section, we will want to
+ * extend begin/end to remove the entire section.
+ *
+ * Note: the parameter `seen_ptr` points to the index into the store.seen
+ * array. * This index may be incremented if a section has more than one
+ * entry (which all are to be removed).
+ */
+static void maybe_remove_section(struct config_store_data *store,
+ const char *contents,
+ size_t *begin_offset, size_t *end_offset,
+ int *seen_ptr)
{
- size_t equal_offset = size, bracket_offset = size;
- ssize_t offset;
+ size_t begin;
+ int i, seen, section_seen = 0;
-contline:
- for (offset = offset_-2; offset > 0
- && contents[offset] != '\n'; offset--)
- switch (contents[offset]) {
- case '=': equal_offset = offset; break;
- case ']': bracket_offset = offset; break;
+ /*
+ * First, ensure that this is the first key, and that there are no
+ * comments before the entry nor before the section header.
+ */
+ seen = *seen_ptr;
+ for (i = store->seen[seen]; i > 0; i--) {
+ enum config_event_t type = store->parsed[i - 1].type;
+
+ if (type == CONFIG_EVENT_COMMENT)
+ /* There is a comment before this entry or section */
+ return;
+ if (type == CONFIG_EVENT_ENTRY) {
+ if (!section_seen)
+ /* This is not the section's first entry. */
+ return;
+ /* We encountered no comment before the section. */
+ break;
+ }
+ if (type == CONFIG_EVENT_SECTION) {
+ if (!store->parsed[i - 1].is_keys_section)
+ break;
+ section_seen = 1;
}
- if (offset > 0 && contents[offset-1] == '\\') {
- offset_ = offset;
- goto contline;
}
- if (bracket_offset < equal_offset) {
- *found_bracket = 1;
- offset = bracket_offset+1;
- } else
- offset++;
+ begin = store->parsed[i].begin;
+
+ /*
+ * Next, make sure that we are removing he last key(s) in the section,
+ * and that there are no comments that are possibly about the current
+ * section.
+ */
+ for (i = store->seen[seen] + 1; i < store->parsed_nr; i++) {
+ enum config_event_t type = store->parsed[i].type;
- return offset;
+ if (type == CONFIG_EVENT_COMMENT)
+ return;
+ if (type == CONFIG_EVENT_SECTION) {
+ if (store->parsed[i].is_keys_section)
+ continue;
+ break;
+ }
+ if (type == CONFIG_EVENT_ENTRY) {
+ if (++seen < store->seen_nr &&
+ i == store->seen[seen])
+ /* We want to remove this entry, too */
+ continue;
+ /* There is another entry in this section. */
+ return;
+ }
+ }
+
+ /*
+ * We are really removing the last entry/entries from this section, and
+ * there are no enclosed or surrounding comments. Remove the entire,
+ * now-empty section.
+ */
+ *seen_ptr = seen;
+ *begin_offset = begin;
+ if (i < store->parsed_nr)
+ *end_offset = store->parsed[i].begin;
+ else
+ *end_offset = store->parsed[store->parsed_nr - 1].end;
}
int git_config_set_in_file_gently(const char *config_filename,
@@ -2487,6 +2659,9 @@ int git_config_set_multivar_in_file_gently(const char *config_filename,
char *filename_buf = NULL;
char *contents = NULL;
size_t contents_sz;
+ struct config_store_data store;
+
+ memset(&store, 0, sizeof(store));
/* parse-key returns negative; flip the sign to feed exit(3) */
ret = 0 - git_config_parse_key(key, &store.key, &store.baselen);
@@ -2505,7 +2680,6 @@ int git_config_set_multivar_in_file_gently(const char *config_filename,
fd = hold_lock_file_for_update(&lock, config_filename, 0);
if (fd < 0) {
error_errno("could not lock config file %s", config_filename);
- free(store.key);
ret = CONFIG_NO_LOCK;
goto out_free;
}
@@ -2515,8 +2689,6 @@ int git_config_set_multivar_in_file_gently(const char *config_filename,
*/
in_fd = open(config_filename, O_RDONLY);
if ( in_fd < 0 ) {
- free(store.key);
-
if ( ENOENT != errno ) {
error_errno("opening %s", config_filename);
ret = CONFIG_INVALID_FILE; /* same as "invalid config file" */
@@ -2528,14 +2700,16 @@ int git_config_set_multivar_in_file_gently(const char *config_filename,
goto out_free;
}
- store.key = (char *)key;
- if (write_section(fd, key) < 0 ||
- write_pair(fd, key, value) < 0)
+ free(store.key);
+ store.key = xstrdup(key);
+ if (write_section(fd, key, &store) < 0 ||
+ write_pair(fd, key, value, &store) < 0)
goto write_err_out;
} else {
struct stat st;
size_t copy_begin, copy_end;
int i, new_line = 0;
+ struct config_options opts;
if (value_regex == NULL)
store.value_regex = NULL;
@@ -2552,45 +2726,38 @@ int git_config_set_multivar_in_file_gently(const char *config_filename,
if (regcomp(store.value_regex, value_regex,
REG_EXTENDED)) {
error("invalid pattern: %s", value_regex);
- free(store.value_regex);
+ FREE_AND_NULL(store.value_regex);
ret = CONFIG_INVALID_PATTERN;
goto out_free;
}
}
- ALLOC_GROW(store.offset, 1, store.offset_alloc);
- store.offset[0] = 0;
- store.state = START;
- store.seen = 0;
+ ALLOC_GROW(store.parsed, 1, store.parsed_alloc);
+ store.parsed[0].end = 0;
+
+ memset(&opts, 0, sizeof(opts));
+ opts.event_fn = store_aux_event;
+ opts.event_fn_data = &store;
/*
- * After this, store.offset will contain the *end* offset
- * of the last match, or remain at 0 if no match was found.
+ * After this, store.parsed will contain offsets of all the
+ * parsed elements, and store.seen will contain a list of
+ * matches, as indices into store.parsed.
+ *
* As a side effect, we make sure to transform only a valid
* existing config file.
*/
- if (git_config_from_file(store_aux, config_filename, NULL)) {
+ if (git_config_from_file_with_options(store_aux,
+ config_filename,
+ &store, &opts)) {
error("invalid config file %s", config_filename);
- free(store.key);
- if (store.value_regex != NULL &&
- store.value_regex != CONFIG_REGEX_NONE) {
- regfree(store.value_regex);
- free(store.value_regex);
- }
ret = CONFIG_INVALID_FILE;
goto out_free;
}
- free(store.key);
- if (store.value_regex != NULL &&
- store.value_regex != CONFIG_REGEX_NONE) {
- regfree(store.value_regex);
- free(store.value_regex);
- }
-
/* if nothing to unset, or too many matches, error out */
- if ((store.seen == 0 && value == NULL) ||
- (store.seen > 1 && multi_replace == 0)) {
+ if ((store.seen_nr == 0 && value == NULL) ||
+ (store.seen_nr > 1 && multi_replace == 0)) {
ret = CONFIG_NOTHING_SET;
goto out_free;
}
@@ -2621,18 +2788,49 @@ int git_config_set_multivar_in_file_gently(const char *config_filename,
goto out_free;
}
- if (store.seen == 0)
- store.seen = 1;
+ if (store.seen_nr == 0) {
+ if (!store.seen_alloc) {
+ /* Did not see key nor section */
+ ALLOC_GROW(store.seen, 1, store.seen_alloc);
+ store.seen[0] = store.parsed_nr
+ - !!store.parsed_nr;
+ }
+ store.seen_nr = 1;
+ }
- for (i = 0, copy_begin = 0; i < store.seen; i++) {
- if (store.offset[i] == 0) {
- store.offset[i] = copy_end = contents_sz;
- } else if (store.state != KEY_SEEN) {
- copy_end = store.offset[i];
- } else
- copy_end = find_beginning_of_line(
- contents, contents_sz,
- store.offset[i]-2, &new_line);
+ for (i = 0, copy_begin = 0; i < store.seen_nr; i++) {
+ size_t replace_end;
+ int j = store.seen[i];
+
+ new_line = 0;
+ if (!store.key_seen) {
+ copy_end = store.parsed[j].end;
+ /* include '\n' when copying section header */
+ if (copy_end > 0 && copy_end < contents_sz &&
+ contents[copy_end - 1] != '\n' &&
+ contents[copy_end] == '\n')
+ copy_end++;
+ replace_end = copy_end;
+ } else {
+ replace_end = store.parsed[j].end;
+ copy_end = store.parsed[j].begin;
+ if (!value)
+ maybe_remove_section(&store, contents,
+ &copy_end,
+ &replace_end, &i);
+ /*
+ * Swallow preceding white-space on the same
+ * line.
+ */
+ while (copy_end > 0 ) {
+ char c = contents[copy_end - 1];
+
+ if (isspace(c) && c != '\n')
+ copy_end--;
+ else
+ break;
+ }
+ }
if (copy_end > 0 && contents[copy_end-1] != '\n')
new_line = 1;
@@ -2646,16 +2844,16 @@ int git_config_set_multivar_in_file_gently(const char *config_filename,
write_str_in_full(fd, "\n") < 0)
goto write_err_out;
}
- copy_begin = store.offset[i];
+ copy_begin = replace_end;
}
/* write the pair (value == NULL means unset) */
if (value != NULL) {
- if (store.state == START) {
- if (write_section(fd, key) < 0)
+ if (!store.section_seen) {
+ if (write_section(fd, key, &store) < 0)
goto write_err_out;
}
- if (write_pair(fd, key, value) < 0)
+ if (write_pair(fd, key, value, &store) < 0)
goto write_err_out;
}
@@ -2687,6 +2885,7 @@ out_free:
munmap(contents, contents_sz);
if (in_fd >= 0)
close(in_fd);
+ config_store_data_clear(&store);
return ret;
write_err_out:
@@ -2779,7 +2978,8 @@ static int section_name_is_ok(const char *name)
/* if new_name == NULL, the section is removed instead */
static int git_config_copy_or_rename_section_in_file(const char *config_filename,
- const char *old_name, const char *new_name, int copy)
+ const char *old_name,
+ const char *new_name, int copy)
{
int ret = 0, remove = 0;
char *filename_buf = NULL;
@@ -2789,6 +2989,9 @@ static int git_config_copy_or_rename_section_in_file(const char *config_filename
FILE *config_file = NULL;
struct stat st;
struct strbuf copystr = STRBUF_INIT;
+ struct config_store_data store;
+
+ memset(&store, 0, sizeof(store));
if (new_name && !section_name_is_ok(new_name)) {
ret = error("invalid section name: %s", new_name);
@@ -2858,7 +3061,7 @@ static int git_config_copy_or_rename_section_in_file(const char *config_filename
}
store.baselen = strlen(new_name);
if (!copy) {
- if (write_section(out_fd, new_name) < 0) {
+ if (write_section(out_fd, new_name, &store) < 0) {
ret = write_error(get_lock_file_path(&lock));
goto out;
}
@@ -2879,7 +3082,7 @@ static int git_config_copy_or_rename_section_in_file(const char *config_filename
output[0] = '\t';
}
} else {
- copystr = store_create_section(new_name);
+ copystr = store_create_section(new_name, &store);
}
}
remove = 0;
@@ -2923,6 +3126,7 @@ out:
rollback_lock_file(&lock);
out_no_rollback:
free(filename_buf);
+ config_store_data_clear(&store);
return ret;
}
@@ -3004,7 +3208,7 @@ const char *current_config_origin_type(void)
else if(cf)
type = cf->origin_type;
else
- die("BUG: current_config_origin_type called outside config callback");
+ BUG("current_config_origin_type called outside config callback");
switch (type) {
case CONFIG_ORIGIN_BLOB:
@@ -3018,7 +3222,7 @@ const char *current_config_origin_type(void)
case CONFIG_ORIGIN_CMDLINE:
return "command line";
default:
- die("BUG: unknown config origin type");
+ BUG("unknown config origin type");
}
}
@@ -3030,7 +3234,7 @@ const char *current_config_name(void)
else if (cf)
name = cf->name;
else
- die("BUG: current_config_name called outside config callback");
+ BUG("current_config_name called outside config callback");
return name ? name : "";
}
diff --git a/config.h b/config.h
index ef70a9c..cdac2fc 100644
--- a/config.h
+++ b/config.h
@@ -28,15 +28,40 @@ enum config_origin_type {
CONFIG_ORIGIN_CMDLINE
};
+enum config_event_t {
+ CONFIG_EVENT_SECTION,
+ CONFIG_EVENT_ENTRY,
+ CONFIG_EVENT_WHITESPACE,
+ CONFIG_EVENT_COMMENT,
+ CONFIG_EVENT_EOF,
+ CONFIG_EVENT_ERROR
+};
+
+/*
+ * The parser event function (if not NULL) is called with the event type and
+ * the begin/end offsets of the parsed elements.
+ *
+ * Note: for CONFIG_EVENT_ENTRY (i.e. config variables), the trailing newline
+ * character is considered part of the element.
+ */
+typedef int (*config_parser_event_fn_t)(enum config_event_t type,
+ size_t begin_offset, size_t end_offset,
+ void *event_fn_data);
+
struct config_options {
unsigned int respect_includes : 1;
const char *commondir;
const char *git_dir;
+ config_parser_event_fn_t event_fn;
+ void *event_fn_data;
};
typedef int (*config_fn_t)(const char *, const char *, void *);
extern int git_default_config(const char *, const char *, void *);
extern int git_config_from_file(config_fn_t fn, const char *, void *);
+extern int git_config_from_file_with_options(config_fn_t fn, const char *,
+ void *,
+ const struct config_options *);
extern int git_config_from_mem(config_fn_t fn, const enum config_origin_type,
const char *name, const char *buf, size_t len, void *data);
extern int git_config_from_blob_oid(config_fn_t fn, const char *name,
@@ -59,6 +84,7 @@ extern int git_config_bool(const char *, const char *);
extern int git_config_string(const char **, const char *, const char *);
extern int git_config_pathname(const char **, const char *, const char *);
extern int git_config_expiry_date(timestamp_t *, const char *, const char *);
+extern int git_config_color(char *, const char *, const char *);
extern int git_config_set_in_file_gently(const char *, const char *, const char *);
extern void git_config_set_in_file(const char *, const char *, const char *);
extern int git_config_set_gently(const char *, const char *);
diff --git a/config.mak.dev b/config.mak.dev
new file mode 100644
index 0000000..2d244ca
--- /dev/null
+++ b/config.mak.dev
@@ -0,0 +1,42 @@
+ifeq ($(filter no-error,$(DEVOPTS)),)
+CFLAGS += -Werror
+endif
+CFLAGS += -Wdeclaration-after-statement
+CFLAGS += -Wno-format-zero-length
+CFLAGS += -Wold-style-definition
+CFLAGS += -Woverflow
+CFLAGS += -Wpointer-arith
+CFLAGS += -Wstrict-prototypes
+CFLAGS += -Wunused
+CFLAGS += -Wvla
+
+ifndef COMPILER_FEATURES
+COMPILER_FEATURES := $(shell ./detect-compiler $(CC))
+endif
+
+ifneq ($(filter clang4,$(COMPILER_FEATURES)),)
+CFLAGS += -Wtautological-constant-out-of-range-compare
+endif
+
+ifneq ($(or $(filter gcc6,$(COMPILER_FEATURES)),$(filter clang4,$(COMPILER_FEATURES))),)
+CFLAGS += -Wextra
+# if a function is public, there should be a prototype and the right
+# header file should be included. If not, it should be static.
+CFLAGS += -Wmissing-prototypes
+ifeq ($(filter extra-all,$(DEVOPTS)),)
+# These are disabled because we have these all over the place.
+CFLAGS += -Wno-empty-body
+CFLAGS += -Wno-missing-field-initializers
+CFLAGS += -Wno-sign-compare
+CFLAGS += -Wno-unused-function
+CFLAGS += -Wno-unused-parameter
+endif
+endif
+
+# uninitialized warnings on gcc 4.9.2 in xdiff/xdiffi.c and config.c
+# not worth fixing since newer compilers correctly stop complaining
+ifneq ($(filter gcc4,$(COMPILER_FEATURES)),)
+ifeq ($(filter gcc5,$(COMPILER_FEATURES)),)
+CFLAGS += -Wno-uninitialized
+endif
+endif
diff --git a/config.mak.uname b/config.mak.uname
index 6a1d0de..684fc5b 100644
--- a/config.mak.uname
+++ b/config.mak.uname
@@ -37,6 +37,8 @@ ifeq ($(uname_S),Linux)
HAVE_GETDELIM = YesPlease
SANE_TEXT_GREP=-a
FREAD_READS_DIRECTORIES = UnfortunatelyYes
+ BASIC_CFLAGS += -DHAVE_SYSINFO
+ PROCFS_EXECUTABLE_PATH = /proc/self/exe
endif
ifeq ($(uname_S),GNU/kFreeBSD)
HAVE_ALLOCA_H = YesPlease
@@ -111,6 +113,7 @@ ifeq ($(uname_S),Darwin)
BASIC_CFLAGS += -DPROTECT_HFS_DEFAULT=1
HAVE_BSD_SYSCTL = YesPlease
FREAD_READS_DIRECTORIES = UnfortunatelyYes
+ HAVE_NS_GET_EXECUTABLE_PATH = YesPlease
endif
ifeq ($(uname_S),SunOS)
NEEDS_SOCKET = YesPlease
@@ -205,6 +208,7 @@ ifeq ($(uname_S),FreeBSD)
HAVE_PATHS_H = YesPlease
GMTIME_UNRELIABLE_ERRORS = UnfortunatelyYes
HAVE_BSD_SYSCTL = YesPlease
+ HAVE_BSD_KERN_PROC_SYSCTL = YesPlease
PAGER_ENV = LESS=FRX LV=-c MORE=FRX
FREAD_READS_DIRECTORIES = UnfortunatelyYes
endif
@@ -217,6 +221,8 @@ ifeq ($(uname_S),OpenBSD)
BASIC_LDFLAGS += -L/usr/local/lib
HAVE_PATHS_H = YesPlease
HAVE_BSD_SYSCTL = YesPlease
+ HAVE_BSD_KERN_PROC_SYSCTL = YesPlease
+ PROCFS_EXECUTABLE_PATH = /proc/curproc/file
endif
ifeq ($(uname_S),MirBSD)
NO_STRCASESTR = YesPlease
@@ -235,6 +241,8 @@ ifeq ($(uname_S),NetBSD)
USE_ST_TIMESPEC = YesPlease
HAVE_PATHS_H = YesPlease
HAVE_BSD_SYSCTL = YesPlease
+ HAVE_BSD_KERN_PROC_SYSCTL = YesPlease
+ PROCFS_EXECUTABLE_PATH = /proc/curproc/exe
endif
ifeq ($(uname_S),AIX)
DEFAULT_PAGER = more
@@ -350,6 +358,7 @@ ifeq ($(uname_S),Windows)
SNPRINTF_RETURNS_BOGUS = YesPlease
NO_SVN_TESTS = YesPlease
RUNTIME_PREFIX = YesPlease
+ HAVE_WPGMPTR = YesWeDo
NO_ST_BLOCKS_IN_STRUCT_STAT = YesPlease
NO_NSEC = YesPlease
USE_WIN32_MMAP = YesPlease
@@ -499,6 +508,7 @@ ifneq (,$(findstring MINGW,$(uname_S)))
NO_SVN_TESTS = YesPlease
NO_PERL_MAKEMAKER = YesPlease
RUNTIME_PREFIX = YesPlease
+ HAVE_WPGMPTR = YesWeDo
NO_ST_BLOCKS_IN_STRUCT_STAT = YesPlease
NO_NSEC = YesPlease
USE_WIN32_MMAP = YesPlease
diff --git a/configure.ac b/configure.ac
index 6f1fd9d..e11b797 100644
--- a/configure.ac
+++ b/configure.ac
@@ -927,7 +927,7 @@ AC_RUN_IFELSE(
[AC_LANG_PROGRAM([AC_INCLUDES_DEFAULT],
[[
FILE *f = fopen(".", "r");
- return f)]])],
+ return f != NULL;]])],
[ac_cv_fread_reads_directories=no],
[ac_cv_fread_reads_directories=yes])
])
diff --git a/connect.c b/connect.c
index c3a014c..31aa9c8 100644
--- a/connect.c
+++ b/connect.c
@@ -12,9 +12,11 @@
#include "sha1-array.h"
#include "transport.h"
#include "strbuf.h"
+#include "version.h"
#include "protocol.h"
-static char *server_capabilities;
+static char *server_capabilities_v1;
+static struct argv_array server_capabilities_v2 = ARGV_ARRAY_INIT;
static const char *parse_feature_value(const char *, const char *, int *);
static int check_ref(const char *name, unsigned int flags)
@@ -46,8 +48,14 @@ int check_ref_type(const struct ref *ref, int flags)
return check_ref(ref->name, flags);
}
-static void die_initial_contact(int unexpected)
+static NORETURN void die_initial_contact(int unexpected)
{
+ /*
+ * A hang-up after seeing some response from the other end
+ * means that it is unexpected, as we know the other end is
+ * willing to talk to us. A hang-up before seeing any
+ * response does not necessarily mean an ACL problem, though.
+ */
if (unexpected)
die(_("The remote end hung up upon initial contact"));
else
@@ -56,6 +64,92 @@ static void die_initial_contact(int unexpected)
"and the repository exists."));
}
+/* Checks if the server supports the capability 'c' */
+int server_supports_v2(const char *c, int die_on_error)
+{
+ int i;
+
+ for (i = 0; i < server_capabilities_v2.argc; i++) {
+ const char *out;
+ if (skip_prefix(server_capabilities_v2.argv[i], c, &out) &&
+ (!*out || *out == '='))
+ return 1;
+ }
+
+ if (die_on_error)
+ die("server doesn't support '%s'", c);
+
+ return 0;
+}
+
+int server_supports_feature(const char *c, const char *feature,
+ int die_on_error)
+{
+ int i;
+
+ for (i = 0; i < server_capabilities_v2.argc; i++) {
+ const char *out;
+ if (skip_prefix(server_capabilities_v2.argv[i], c, &out) &&
+ (!*out || *(out++) == '=')) {
+ if (parse_feature_request(out, feature))
+ return 1;
+ else
+ break;
+ }
+ }
+
+ if (die_on_error)
+ die("server doesn't support feature '%s'", feature);
+
+ return 0;
+}
+
+static void process_capabilities_v2(struct packet_reader *reader)
+{
+ while (packet_reader_read(reader) == PACKET_READ_NORMAL)
+ argv_array_push(&server_capabilities_v2, reader->line);
+
+ if (reader->status != PACKET_READ_FLUSH)
+ die("expected flush after capabilities");
+}
+
+enum protocol_version discover_version(struct packet_reader *reader)
+{
+ enum protocol_version version = protocol_unknown_version;
+
+ /*
+ * Peek the first line of the server's response to
+ * determine the protocol version the server is speaking.
+ */
+ switch (packet_reader_peek(reader)) {
+ case PACKET_READ_EOF:
+ die_initial_contact(0);
+ case PACKET_READ_FLUSH:
+ case PACKET_READ_DELIM:
+ version = protocol_v0;
+ break;
+ case PACKET_READ_NORMAL:
+ version = determine_protocol_version_client(reader->line);
+ break;
+ }
+
+ switch (version) {
+ case protocol_v2:
+ process_capabilities_v2(reader);
+ break;
+ case protocol_v1:
+ /* Read the peeked version line */
+ packet_reader_read(reader);
+ break;
+ case protocol_v0:
+ break;
+ case protocol_unknown_version:
+ BUG("unknown protocol version");
+ }
+
+ return version;
+}
+
static void parse_one_symref_info(struct string_list *symref, const char *val, int len)
{
char *sym, *target;
@@ -85,7 +179,7 @@ reject:
static void annotate_refs_with_symref_info(struct ref *ref)
{
struct string_list symref = STRING_LIST_INIT_DUP;
- const char *feature_list = server_capabilities;
+ const char *feature_list = server_capabilities_v1;
while (feature_list) {
int len;
@@ -109,60 +203,21 @@ static void annotate_refs_with_symref_info(struct ref *ref)
string_list_clear(&symref, 0);
}
-/*
- * Read one line of a server's ref advertisement into packet_buffer.
- */
-static int read_remote_ref(int in, char **src_buf, size_t *src_len,
- int *responded)
-{
- int len = packet_read(in, src_buf, src_len,
- packet_buffer, sizeof(packet_buffer),
- PACKET_READ_GENTLE_ON_EOF |
- PACKET_READ_CHOMP_NEWLINE);
- const char *arg;
- if (len < 0)
- die_initial_contact(*responded);
- if (len > 4 && skip_prefix(packet_buffer, "ERR ", &arg))
- die("remote error: %s", arg);
-
- *responded = 1;
-
- return len;
-}
-
-#define EXPECTING_PROTOCOL_VERSION 0
-#define EXPECTING_FIRST_REF 1
-#define EXPECTING_REF 2
-#define EXPECTING_SHALLOW 3
-
-/* Returns 1 if packet_buffer is a protocol version pkt-line, 0 otherwise. */
-static int process_protocol_version(void)
+static void process_capabilities(const char *line, int *len)
{
- switch (determine_protocol_version_client(packet_buffer)) {
- case protocol_v1:
- return 1;
- case protocol_v0:
- return 0;
- default:
- die("server is speaking an unknown protocol");
- }
-}
-
-static void process_capabilities(int *len)
-{
- int nul_location = strlen(packet_buffer);
+ int nul_location = strlen(line);
if (nul_location == *len)
return;
- server_capabilities = xstrdup(packet_buffer + nul_location + 1);
+ server_capabilities_v1 = xstrdup(line + nul_location + 1);
*len = nul_location;
}
-static int process_dummy_ref(void)
+static int process_dummy_ref(const char *line)
{
struct object_id oid;
const char *name;
- if (parse_oid_hex(packet_buffer, &oid, &name))
+ if (parse_oid_hex(line, &oid, &name))
return 0;
if (*name != ' ')
return 0;
@@ -171,20 +226,20 @@ static int process_dummy_ref(void)
return !oidcmp(&null_oid, &oid) && !strcmp(name, "capabilities^{}");
}
-static void check_no_capabilities(int len)
+static void check_no_capabilities(const char *line, int len)
{
- if (strlen(packet_buffer) != len)
+ if (strlen(line) != len)
warning("Ignoring capabilities after first line '%s'",
- packet_buffer + strlen(packet_buffer));
+ line + strlen(line));
}
-static int process_ref(int len, struct ref ***list, unsigned int flags,
- struct oid_array *extra_have)
+static int process_ref(const char *line, int len, struct ref ***list,
+ unsigned int flags, struct oid_array *extra_have)
{
struct object_id old_oid;
const char *name;
- if (parse_oid_hex(packet_buffer, &old_oid, &name))
+ if (parse_oid_hex(line, &old_oid, &name))
return 0;
if (*name != ' ')
return 0;
@@ -200,16 +255,17 @@ static int process_ref(int len, struct ref ***list, unsigned int flags,
**list = ref;
*list = &ref->next;
}
- check_no_capabilities(len);
+ check_no_capabilities(line, len);
return 1;
}
-static int process_shallow(int len, struct oid_array *shallow_points)
+static int process_shallow(const char *line, int len,
+ struct oid_array *shallow_points)
{
const char *arg;
struct object_id old_oid;
- if (!skip_prefix(packet_buffer, "shallow ", &arg))
+ if (!skip_prefix(line, "shallow ", &arg))
return 0;
if (get_oid_hex(arg, &old_oid))
@@ -217,60 +273,68 @@ static int process_shallow(int len, struct oid_array *shallow_points)
if (!shallow_points)
die("repository on the other end cannot be shallow");
oid_array_append(shallow_points, &old_oid);
- check_no_capabilities(len);
+ check_no_capabilities(line, len);
return 1;
}
+enum get_remote_heads_state {
+ EXPECTING_FIRST_REF = 0,
+ EXPECTING_REF,
+ EXPECTING_SHALLOW,
+ EXPECTING_DONE,
+};
+
/*
* Read all the refs from the other end
*/
-struct ref **get_remote_heads(int in, char *src_buf, size_t src_len,
+struct ref **get_remote_heads(struct packet_reader *reader,
struct ref **list, unsigned int flags,
struct oid_array *extra_have,
struct oid_array *shallow_points)
{
struct ref **orig_list = list;
-
- /*
- * A hang-up after seeing some response from the other end
- * means that it is unexpected, as we know the other end is
- * willing to talk to us. A hang-up before seeing any
- * response does not necessarily mean an ACL problem, though.
- */
- int responded = 0;
- int len;
- int state = EXPECTING_PROTOCOL_VERSION;
+ int len = 0;
+ enum get_remote_heads_state state = EXPECTING_FIRST_REF;
+ const char *arg;
*list = NULL;
- while ((len = read_remote_ref(in, &src_buf, &src_len, &responded))) {
+ while (state != EXPECTING_DONE) {
+ switch (packet_reader_read(reader)) {
+ case PACKET_READ_EOF:
+ die_initial_contact(1);
+ case PACKET_READ_NORMAL:
+ len = reader->pktlen;
+ if (len > 4 && skip_prefix(reader->line, "ERR ", &arg))
+ die("remote error: %s", arg);
+ break;
+ case PACKET_READ_FLUSH:
+ state = EXPECTING_DONE;
+ break;
+ case PACKET_READ_DELIM:
+ die("invalid packet");
+ }
+
switch (state) {
- case EXPECTING_PROTOCOL_VERSION:
- if (process_protocol_version()) {
- state = EXPECTING_FIRST_REF;
- break;
- }
- state = EXPECTING_FIRST_REF;
- /* fallthrough */
case EXPECTING_FIRST_REF:
- process_capabilities(&len);
- if (process_dummy_ref()) {
+ process_capabilities(reader->line, &len);
+ if (process_dummy_ref(reader->line)) {
state = EXPECTING_SHALLOW;
break;
}
state = EXPECTING_REF;
/* fallthrough */
case EXPECTING_REF:
- if (process_ref(len, &list, flags, extra_have))
+ if (process_ref(reader->line, len, &list, flags, extra_have))
break;
state = EXPECTING_SHALLOW;
/* fallthrough */
case EXPECTING_SHALLOW:
- if (process_shallow(len, shallow_points))
+ if (process_shallow(reader->line, len, shallow_points))
break;
- die("protocol error: unexpected '%s'", packet_buffer);
- default:
- die("unexpected state %d", state);
+ die("protocol error: unexpected '%s'", reader->line);
+ case EXPECTING_DONE:
+ break;
}
}
@@ -279,6 +343,112 @@ struct ref **get_remote_heads(int in, char *src_buf, size_t src_len,
return list;
}
+/* Returns 1 when a valid ref has been added to `list`, 0 otherwise */
+static int process_ref_v2(const char *line, struct ref ***list)
+{
+ int ret = 1;
+ int i = 0;
+ struct object_id old_oid;
+ struct ref *ref;
+ struct string_list line_sections = STRING_LIST_INIT_DUP;
+ const char *end;
+
+ /*
+ * Ref lines have a number of fields which are space deliminated. The
+ * first field is the OID of the ref. The second field is the ref
+ * name. Subsequent fields (symref-target and peeled) are optional and
+ * don't have a particular order.
+ */
+ if (string_list_split(&line_sections, line, ' ', -1) < 2) {
+ ret = 0;
+ goto out;
+ }
+
+ if (parse_oid_hex(line_sections.items[i++].string, &old_oid, &end) ||
+ *end) {
+ ret = 0;
+ goto out;
+ }
+
+ ref = alloc_ref(line_sections.items[i++].string);
+
+ oidcpy(&ref->old_oid, &old_oid);
+ **list = ref;
+ *list = &ref->next;
+
+ for (; i < line_sections.nr; i++) {
+ const char *arg = line_sections.items[i].string;
+ if (skip_prefix(arg, "symref-target:", &arg))
+ ref->symref = xstrdup(arg);
+
+ if (skip_prefix(arg, "peeled:", &arg)) {
+ struct object_id peeled_oid;
+ char *peeled_name;
+ struct ref *peeled;
+ if (parse_oid_hex(arg, &peeled_oid, &end) || *end) {
+ ret = 0;
+ goto out;
+ }
+
+ peeled_name = xstrfmt("%s^{}", ref->name);
+ peeled = alloc_ref(peeled_name);
+
+ oidcpy(&peeled->old_oid, &peeled_oid);
+ **list = peeled;
+ *list = &peeled->next;
+
+ free(peeled_name);
+ }
+ }
+
+out:
+ string_list_clear(&line_sections, 0);
+ return ret;
+}
+
+struct ref **get_remote_refs(int fd_out, struct packet_reader *reader,
+ struct ref **list, int for_push,
+ const struct argv_array *ref_prefixes,
+ const struct string_list *server_options)
+{
+ int i;
+ *list = NULL;
+
+ if (server_supports_v2("ls-refs", 1))
+ packet_write_fmt(fd_out, "command=ls-refs\n");
+
+ if (server_supports_v2("agent", 0))
+ packet_write_fmt(fd_out, "agent=%s", git_user_agent_sanitized());
+
+ if (server_options && server_options->nr &&
+ server_supports_v2("server-option", 1))
+ for (i = 0; i < server_options->nr; i++)
+ packet_write_fmt(fd_out, "server-option=%s",
+ server_options->items[i].string);
+
+ packet_delim(fd_out);
+ /* When pushing we don't want to request the peeled tags */
+ if (!for_push)
+ packet_write_fmt(fd_out, "peel\n");
+ packet_write_fmt(fd_out, "symrefs\n");
+ for (i = 0; ref_prefixes && i < ref_prefixes->argc; i++) {
+ packet_write_fmt(fd_out, "ref-prefix %s\n",
+ ref_prefixes->argv[i]);
+ }
+ packet_flush(fd_out);
+
+ /* Process response from server */
+ while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
+ if (!process_ref_v2(reader->line, &list))
+ die("invalid ls-refs response: %s", reader->line);
+ }
+
+ if (reader->status != PACKET_READ_FLUSH)
+ die("expected flush after ref listing");
+
+ return list;
+}
+
static const char *parse_feature_value(const char *feature_list, const char *feature, int *lenp)
{
int len;
@@ -323,7 +493,7 @@ int parse_feature_request(const char *feature_list, const char *feature)
const char *server_feature_value(const char *feature, int *len)
{
- return parse_feature_value(server_capabilities, feature, len);
+ return parse_feature_value(server_capabilities_v1, feature, len);
}
int server_supports(const char *feature)
@@ -872,6 +1042,7 @@ static enum ssh_variant determine_ssh_variant(const char *ssh_command,
*/
static struct child_process *git_connect_git(int fd[2], char *hostandport,
const char *path, const char *prog,
+ enum protocol_version version,
int flags)
{
struct child_process *conn;
@@ -910,10 +1081,10 @@ static struct child_process *git_connect_git(int fd[2], char *hostandport,
target_host, 0);
/* If using a new version put that stuff here after a second null byte */
- if (get_protocol_version_config() > 0) {
+ if (version > 0) {
strbuf_addch(&request, '\0');
strbuf_addf(&request, "version=%d%c",
- get_protocol_version_config(), '\0');
+ version, '\0');
}
packet_write(fd[1], request.buf, request.len);
@@ -929,14 +1100,14 @@ static struct child_process *git_connect_git(int fd[2], char *hostandport,
*/
static void push_ssh_options(struct argv_array *args, struct argv_array *env,
enum ssh_variant variant, const char *port,
- int flags)
+ enum protocol_version version, int flags)
{
if (variant == VARIANT_SSH &&
- get_protocol_version_config() > 0) {
+ version > 0) {
argv_array_push(args, "-o");
argv_array_push(args, "SendEnv=" GIT_PROTOCOL_ENVIRONMENT);
argv_array_pushf(env, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
- get_protocol_version_config());
+ version);
}
if (flags & CONNECT_IPV4) {
@@ -989,7 +1160,8 @@ static void push_ssh_options(struct argv_array *args, struct argv_array *env,
/* Prepare a child_process for use by Git's SSH-tunneled transport. */
static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
- const char *port, int flags)
+ const char *port, enum protocol_version version,
+ int flags)
{
const char *ssh;
enum ssh_variant variant;
@@ -1023,14 +1195,14 @@ static void fill_ssh_args(struct child_process *conn, const char *ssh_host,
argv_array_push(&detect.args, ssh);
argv_array_push(&detect.args, "-G");
push_ssh_options(&detect.args, &detect.env_array,
- VARIANT_SSH, port, flags);
+ VARIANT_SSH, port, version, flags);
argv_array_push(&detect.args, ssh_host);
variant = run_command(&detect) ? VARIANT_SIMPLE : VARIANT_SSH;
}
argv_array_push(&conn->args, ssh);
- push_ssh_options(&conn->args, &conn->env_array, variant, port, flags);
+ push_ssh_options(&conn->args, &conn->env_array, variant, port, version, flags);
argv_array_push(&conn->args, ssh_host);
}
@@ -1051,6 +1223,15 @@ struct child_process *git_connect(int fd[2], const char *url,
char *hostandport, *path;
struct child_process *conn;
enum protocol protocol;
+ enum protocol_version version = get_protocol_version_config();
+
+ /*
+ * NEEDSWORK: If we are trying to use protocol v2 and we are planning
+ * to perform a push, then fallback to v0 since the client doesn't know
+ * how to push yet using v2.
+ */
+ if (version == protocol_v2 && !strcmp("git-receive-pack", prog))
+ version = protocol_v0;
/* Without this we cannot rely on waitpid() to tell
* what happened to our children.
@@ -1065,7 +1246,7 @@ struct child_process *git_connect(int fd[2], const char *url,
printf("Diag: path=%s\n", path ? path : "NULL");
conn = NULL;
} else if (protocol == PROTO_GIT) {
- conn = git_connect_git(fd, hostandport, path, prog, flags);
+ conn = git_connect_git(fd, hostandport, path, prog, version, flags);
} else {
struct strbuf cmd = STRBUF_INIT;
const char *const *var;
@@ -1108,12 +1289,12 @@ struct child_process *git_connect(int fd[2], const char *url,
strbuf_release(&cmd);
return NULL;
}
- fill_ssh_args(conn, ssh_host, port, flags);
+ fill_ssh_args(conn, ssh_host, port, version, flags);
} else {
transport_check_allowed("file");
- if (get_protocol_version_config() > 0) {
+ if (version > 0) {
argv_array_pushf(&conn->env_array, GIT_PROTOCOL_ENVIRONMENT "=version=%d",
- get_protocol_version_config());
+ version);
}
}
argv_array_push(&conn->args, cmd.buf);
diff --git a/connect.h b/connect.h
index 01f14cd..0e69c67 100644
--- a/connect.h
+++ b/connect.h
@@ -13,4 +13,11 @@ extern int parse_feature_request(const char *features, const char *feature);
extern const char *server_feature_value(const char *feature, int *len_ret);
extern int url_is_local_not_ssh(const char *url);
+struct packet_reader;
+extern enum protocol_version discover_version(struct packet_reader *reader);
+
+extern int server_supports_v2(const char *c, int die_on_error);
+extern int server_supports_feature(const char *c, const char *feature,
+ int die_on_error);
+
#endif
diff --git a/contrib/coccinelle/commit.cocci b/contrib/coccinelle/commit.cocci
new file mode 100644
index 0000000..a7e9215
--- /dev/null
+++ b/contrib/coccinelle/commit.cocci
@@ -0,0 +1,28 @@
+@@
+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
+
+// These excluded functions must access c->maybe_tree direcly.
+@@
+identifier f !~ "^(get_commit_tree|get_commit_tree_in_graph|load_tree_for_commit)$";
+expression c;
+@@
+ f(...) {...
+- c->maybe_tree
++ get_commit_tree(c)
+ ...}
+
+@@
+expression c;
+expression s;
+@@
+- get_commit_tree(c) = s
++ c->maybe_tree = s
diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash
index a757073..1491b72 100644
--- a/contrib/completion/git-completion.bash
+++ b/contrib/completion/git-completion.bash
@@ -94,6 +94,70 @@ __git ()
${__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+
@@ -284,7 +348,11 @@ __gitcomp ()
# Clear the variables caching builtins' options when (re-)sourcing
# the completion script.
-unset $(set |sed -ne 's/^\(__gitcomp_builtin_[a-zA-Z0-9_][a-zA-Z0-9_]*\)=.*/\1/p') 2>/dev/null
+if [[ -n ${ZSH_VERSION-} ]]; then
+ unset $(set |sed -ne 's/^\(__gitcomp_builtin_[a-zA-Z0-9_][a-zA-Z0-9_]*\)=.*/\1/p') 2>/dev/null
+else
+ unset $(compgen -v __gitcomp_builtin_)
+fi
# This function is equivalent to
#
@@ -342,6 +410,24 @@ __gitcomp_nl ()
__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 componens.
+__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:
@@ -361,7 +447,8 @@ __gitcomp_file ()
# 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
+ compgen -f /non-existing-dir/ >/dev/null ||
+ true
}
# Execute 'git ls-files', unless the --committable option is specified, in
@@ -371,10 +458,12 @@ __gitcomp_file ()
__git_ls_files_helper ()
{
if [ "$2" == "--committable" ]; then
- __git -C "$1" diff-index --name-only --relative HEAD
+ __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" ls-files --exclude-standard $2
+ __git -C "$1" -c core.quotePath=false ls-files \
+ --exclude-standard $2 -- "${3//\\/\\\\}*"
fi
}
@@ -385,17 +474,103 @@ __git_ls_files_helper ()
# 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-.}" file
+ local root="$2" match="$3"
- __git_ls_files_helper "$root" "$1" |
- while read -r file; do
- case "$file" in
- ?*/*) echo "${file%%/*}" ;;
- *) echo "$file" ;;
- esac
- done | sort | uniq
+ __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 direcory
+ # 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 cant 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 isnt 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.
@@ -714,26 +889,6 @@ __git_complete_revlist_file ()
esac
}
-
-# __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 pfx="" cur_="$cur"
-
- case "$cur_" in
- ?*/*)
- pfx="${cur_%/*}"
- cur_="${cur_##*/}"
- pfx="${pfx}/"
- ;;
- esac
-
- __gitcomp_file "$(__git_index_files "$1" ${pfx:+"$pfx"})" "$pfx" "$cur_"
-}
-
__git_complete_file ()
{
__git_complete_revlist_file
@@ -880,6 +1035,7 @@ __git_list_porcelain_commands ()
check-ref-format) : plumbing;;
checkout-index) : plumbing;;
column) : internal helper;;
+ commit-graph) : plumbing;;
commit-tree) : plumbing;;
count-objects) : infrequent;;
credential) : credentials;;
@@ -1949,7 +2105,7 @@ _git_rebase ()
--*)
__gitcomp "
--onto --merge --strategy --interactive
- --preserve-merges --stat --no-stat
+ --rebase-merges --preserve-merges --stat --no-stat
--committer-date-is-author-date --ignore-date
--ignore-whitespace --whitespace=
--autosquash --no-autosquash
@@ -2120,7 +2276,7 @@ _git_config ()
return
;;
branch.*.rebase)
- __gitcomp "false true preserve interactive"
+ __gitcomp "false true merges preserve interactive"
return
;;
remote.pushdefault)
@@ -2177,7 +2333,7 @@ _git_config ()
__gitcomp "$__git_log_date_formats"
return
;;
- sendemail.aliasesfiletype)
+ sendemail.aliasfiletype)
__gitcomp "mutt mailrc pine elm gnus"
return
;;
@@ -2350,6 +2506,7 @@ _git_config ()
core.bigFileThreshold
core.checkStat
core.commentChar
+ core.commitGraph
core.compression
core.createObject
core.deltaBaseCacheLimit
@@ -2774,13 +2931,21 @@ _git_show_branch ()
_git_stash ()
{
local save_opts='--all --keep-index --no-keep-index --quiet --patch --include-untracked'
- local subcommands='push save list show apply clear drop pop create branch'
- local subcommand="$(__git_find_on_cmdline "$subcommands")"
+ local subcommands='push list show apply clear drop pop create branch'
+ local subcommand="$(__git_find_on_cmdline "$subcommands save")"
+ if [ -n "$(__git_find_on_cmdline "-p")" ]; then
+ subcommand="push"
+ fi
if [ -z "$subcommand" ]; then
case "$cur" in
--*)
__gitcomp "$save_opts"
;;
+ sa*)
+ if [ -z "$(__git_find_on_cmdline "$save_opts")" ]; then
+ __gitcomp "save"
+ fi
+ ;;
*)
if [ -z "$(__git_find_on_cmdline "$save_opts")" ]; then
__gitcomp "$subcommands"
@@ -3064,10 +3229,17 @@ __git_support_parseopt_helper () {
__git_complete_command () {
local command="$1"
local completion_func="_git_${command//-/_}"
- if declare -f $completion_func >/dev/null 2>/dev/null; then
+ if ! declare -f $completion_func >/dev/null 2>/dev/null &&
+ declare -f _completion_loader >/dev/null 2>/dev/null
+ then
+ _completion_loader "git-$command"
+ fi
+ if declare -f $completion_func >/dev/null 2>/dev/null
+ then
$completion_func
return 0
- elif __git_support_parseopt_helper "$command"; then
+ elif __git_support_parseopt_helper "$command"
+ then
__git_complete_common "$command"
return 0
else
@@ -3216,6 +3388,15 @@ if [[ -n ${ZSH_VERSION-} ]]; then
compadd -Q -S "${4- }" -p "${2-}" -- ${=1} && _ret=0
}
+ __gitcomp_file_direct ()
+ {
+ emulate -L zsh
+
+ local IFS=$'\n'
+ compset -P '*[=:]'
+ compadd -Q -f -- ${=1} && _ret=0
+ }
+
__gitcomp_file ()
{
emulate -L zsh
diff --git a/contrib/completion/git-completion.zsh b/contrib/completion/git-completion.zsh
index c3521fb..53cb0f9 100644
--- a/contrib/completion/git-completion.zsh
+++ b/contrib/completion/git-completion.zsh
@@ -93,6 +93,15 @@ __gitcomp_nl_append ()
compadd -Q -S "${4- }" -p "${2-}" -- ${=1} && _ret=0
}
+__gitcomp_file_direct ()
+{
+ emulate -L zsh
+
+ local IFS=$'\n'
+ compset -P '*[=:]'
+ compadd -Q -f -- ${=1} && _ret=0
+}
+
__gitcomp_file ()
{
emulate -L zsh
diff --git a/contrib/convert-grafts-to-replace-refs.sh b/contrib/convert-grafts-to-replace-refs.sh
deleted file mode 100755
index 0cbc917..0000000
--- a/contrib/convert-grafts-to-replace-refs.sh
+++ /dev/null
@@ -1,28 +0,0 @@
-#!/bin/sh
-
-# You should execute this script in the repository where you
-# want to convert grafts to replace refs.
-
-GRAFTS_FILE="${GIT_DIR:-.git}/info/grafts"
-
-. $(git --exec-path)/git-sh-setup
-
-test -f "$GRAFTS_FILE" || die "Could not find graft file: '$GRAFTS_FILE'"
-
-grep '^[^# ]' "$GRAFTS_FILE" |
-while read definition
-do
- if test -n "$definition"
- then
- echo "Converting: $definition"
- git replace --graft $definition ||
- die "Conversion failed for: $definition"
- fi
-done
-
-mv "$GRAFTS_FILE" "$GRAFTS_FILE.bak" ||
- die "Could not rename '$GRAFTS_FILE' to '$GRAFTS_FILE.bak'"
-
-echo "Success!"
-echo "All the grafts in '$GRAFTS_FILE' have been converted to replace refs!"
-echo "The grafts file '$GRAFTS_FILE' has been renamed: '$GRAFTS_FILE.bak'"
diff --git a/contrib/credential/netrc/Makefile b/contrib/credential/netrc/Makefile
index 51b7613..0ffa407 100644
--- a/contrib/credential/netrc/Makefile
+++ b/contrib/credential/netrc/Makefile
@@ -1,5 +1,5 @@
test:
- ./test.pl
+ ./t-git-credential-netrc.sh
testverbose:
- ./test.pl -d -v
+ ./t-git-credential-netrc.sh -d -v
diff --git a/contrib/credential/netrc/git-credential-netrc b/contrib/credential/netrc/git-credential-netrc
index 1571a7b..0b9a941 100755
--- a/contrib/credential/netrc/git-credential-netrc
+++ b/contrib/credential/netrc/git-credential-netrc
@@ -2,11 +2,13 @@
use strict;
use warnings;
+use autodie;
use Getopt::Long;
use File::Basename;
+use Git;
-my $VERSION = "0.1";
+my $VERSION = "0.2";
my %options = (
help => 0,
@@ -54,6 +56,7 @@ GetOptions(\%options,
"insecure|k",
"verbose|v",
"file|f=s@",
+ 'gpg|g:s',
);
if ($options{help}) {
@@ -62,27 +65,31 @@ if ($options{help}) {
print <<EOHIPPUS;
-$0 [-f AUTHFILE1] [-f AUTHFILEN] [-d] [-v] [-k] get
+$0 [(-f <authfile>)...] [-g <program>] [-d] [-v] [-k] get
Version $VERSION by tzz\@lifelogs.com. License: BSD.
Options:
- -f|--file AUTHFILE : specify netrc-style files. Files with the .gpg extension
- will be decrypted by GPG before parsing. Multiple -f
- arguments are OK. They are processed in order, and the
- first matching entry found is returned via the credential
- helper protocol (see below).
+ -f|--file <authfile>: specify netrc-style files. Files with the .gpg
+ extension will be decrypted by GPG before parsing.
+ Multiple -f arguments are OK. They are processed in
+ order, and the first matching entry found is returned
+ via the credential helper protocol (see below).
- When no -f option is given, .authinfo.gpg, .netrc.gpg,
- .authinfo, and .netrc files in your home directory are used
- in this order.
+ When no -f option is given, .authinfo.gpg, .netrc.gpg,
+ .authinfo, and .netrc files in your home directory are
+ used in this order.
- -k|--insecure : ignore bad file ownership or permissions
+ -g|--gpg <program> : specify the program for GPG. By default, this is the
+ value of gpg.program in the git repository or global
+ option or gpg.
- -d|--debug : turn on debugging (developer info)
+ -k|--insecure : ignore bad file ownership or permissions
- -v|--verbose : be more verbose (show files and information found)
+ -d|--debug : turn on debugging (developer info)
+
+ -v|--verbose : be more verbose (show files and information found)
To enable this credential helper:
@@ -99,8 +106,9 @@ in the path.)
git config credential.helper '$shortname -f AUTHFILE -v'
-Only "get" mode is supported by this credential helper. It opens every AUTHFILE
-and looks for the first entry that matches the requested search criteria:
+Only "get" mode is supported by this credential helper. It opens every
+<authfile> and looks for the first entry that matches the requested search
+criteria:
'port|protocol':
The protocol that will be used (e.g., https). (protocol=X)
@@ -120,7 +128,7 @@ host=github.com
protocol=https
username=tzz
-this credential helper will look for the first entry in every AUTHFILE that
+this credential helper will look for the first entry in every <authfile> that
matches
machine github.com port https login tzz
@@ -137,8 +145,8 @@ Then, the helper will print out whatever tokens it got from the entry, including
back to "protocol". Any redundant entry tokens (part of the original query) are
skipped.
-Again, note that only the first matching entry from all the AUTHFILEs, processed
-in the sequence given on the command line, is used.
+Again, note that only the first matching entry from all the <authfile>s,
+processed in the sequence given on the command line, is used.
Netrc/authinfo tokens can be quoted as 'STRING' or "STRING".
@@ -152,7 +160,7 @@ EOHIPPUS
my $mode = shift @ARGV;
# Credentials must get a parameter, so die if it's missing.
-die "Syntax: $0 [-f AUTHFILE1] [-f AUTHFILEN] [-d] get" unless defined $mode;
+die "Syntax: $0 [(-f <authfile>)...] [-d] get" unless defined $mode;
# Only support 'get' mode; with any other unsupported ones we just exit.
exit 0 unless $mode eq 'get';
@@ -172,6 +180,8 @@ unless (scalar @$files) {
$files = $options{file} = [ map { glob $_ } @candidates ];
}
+load_config(\%options);
+
my $query = read_credential_data_from_stdin();
FILE:
@@ -233,7 +243,7 @@ sub load_netrc {
my $io;
if ($gpgmode) {
- my @cmd = (qw(gpg --decrypt), $file);
+ my @cmd = ($options{'gpg'}, qw(--decrypt), $file);
log_verbose("Using GPG to open $file: [@cmd]");
open $io, "-|", @cmd;
} else {
@@ -410,6 +420,14 @@ sub print_credential_data {
printf "%s=%s\n", $git_token, $entry->{$git_token};
}
}
+sub load_config {
+ # load settings from git config
+ my $options = shift;
+ # set from command argument, gpg.program option, or default to gpg
+ $options->{'gpg'} //= Git->repository()->config('gpg.program')
+ // 'gpg';
+ log_verbose("using $options{'gpg'} for GPG operations");
+}
sub log_verbose {
return unless $options{verbose};
printf STDERR @_;
diff --git a/contrib/credential/netrc/t-git-credential-netrc.sh b/contrib/credential/netrc/t-git-credential-netrc.sh
new file mode 100755
index 0000000..58191a6
--- /dev/null
+++ b/contrib/credential/netrc/t-git-credential-netrc.sh
@@ -0,0 +1,31 @@
+#!/bin/sh
+(
+ cd ../../../t
+ test_description='git-credential-netrc'
+ . ./test-lib.sh
+
+ if ! test_have_prereq PERL; then
+ skip_all='skipping perl interface tests, perl not available'
+ test_done
+ fi
+
+ perl -MTest::More -e 0 2>/dev/null || {
+ skip_all="Perl Test::More unavailable, skipping test"
+ test_done
+ }
+
+ # set up test repository
+
+ test_expect_success \
+ 'set up test repository' \
+ 'git config --add gpg.program test.git-config-gpg'
+
+ # The external test will outputs its own plan
+ test_external_has_tap=1
+
+ test_external \
+ 'git-credential-netrc' \
+ perl "$TEST_DIRECTORY"/../contrib/credential/netrc/test.pl
+
+ test_done
+)
diff --git a/contrib/credential/netrc/test.command-option-gpg b/contrib/credential/netrc/test.command-option-gpg
new file mode 100755
index 0000000..d8f1285
--- /dev/null
+++ b/contrib/credential/netrc/test.command-option-gpg
@@ -0,0 +1,2 @@
+#!/bin/sh
+echo machine command-option-gpg login username password password
diff --git a/contrib/credential/netrc/test.git-config-gpg b/contrib/credential/netrc/test.git-config-gpg
new file mode 100755
index 0000000..65cf594
--- /dev/null
+++ b/contrib/credential/netrc/test.git-config-gpg
@@ -0,0 +1,2 @@
+#!/bin/sh
+echo machine git-config-gpg login username password password
diff --git a/contrib/credential/netrc/test.netrc.gpg b/contrib/credential/netrc/test.netrc.gpg
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/contrib/credential/netrc/test.netrc.gpg
diff --git a/contrib/credential/netrc/test.pl b/contrib/credential/netrc/test.pl
index 169b646..1e10010 100755
--- a/contrib/credential/netrc/test.pl
+++ b/contrib/credential/netrc/test.pl
@@ -1,83 +1,115 @@
#!/usr/bin/perl
+use lib (split(/:/, $ENV{GITPERLLIB}));
use warnings;
use strict;
-use Test;
+use Test::More qw(no_plan);
+use File::Basename;
+use File::Spec::Functions qw(:DEFAULT rel2abs);
use IPC::Open2;
-BEGIN { plan tests => 15 }
+BEGIN {
+ # t-git-credential-netrc.sh kicks off our testing, so we have to go
+ # from there.
+ Test::More->builder->current_test(1);
+ Test::More->builder->no_ending(1);
+}
my @global_credential_args = @ARGV;
-my $netrc = './test.netrc';
-print "# Testing insecure file, nothing should be found\n";
+my $scriptDir = dirname rel2abs $0;
+my ($netrc, $netrcGpg, $gcNetrc) = map { catfile $scriptDir, $_; }
+ qw(test.netrc
+ test.netrc.gpg
+ git-credential-netrc);
+local $ENV{PATH} = join ':'
+ , $scriptDir
+ , $ENV{PATH}
+ ? $ENV{PATH}
+ : ();
+
+diag "Testing insecure file, nothing should be found\n";
chmod 0644, $netrc;
my $cred = run_credential(['-f', $netrc, 'get'],
{ host => 'github.com' });
-ok(scalar keys %$cred, 0, "Got 0 keys from insecure file");
+ok(scalar keys %$cred == 0, "Got 0 keys from insecure file");
-print "# Testing missing file, nothing should be found\n";
+diag "Testing missing file, nothing should be found\n";
chmod 0644, $netrc;
$cred = run_credential(['-f', '///nosuchfile///', 'get'],
{ host => 'github.com' });
-ok(scalar keys %$cred, 0, "Got 0 keys from missing file");
+ok(scalar keys %$cred == 0, "Got 0 keys from missing file");
chmod 0600, $netrc;
-print "# Testing with invalid data\n";
+diag "Testing with invalid data\n";
$cred = run_credential(['-f', $netrc, 'get'],
"bad data");
-ok(scalar keys %$cred, 4, "Got first found keys with bad data");
+ok(scalar keys %$cred == 4, "Got first found keys with bad data");
-print "# Testing netrc file for a missing corovamilkbar entry\n";
+diag "Testing netrc file for a missing corovamilkbar entry\n";
$cred = run_credential(['-f', $netrc, 'get'],
{ host => 'corovamilkbar' });
-ok(scalar keys %$cred, 0, "Got no corovamilkbar keys");
+ok(scalar keys %$cred == 0, "Got no corovamilkbar keys");
-print "# Testing netrc file for a github.com entry\n";
+diag "Testing netrc file for a github.com entry\n";
$cred = run_credential(['-f', $netrc, 'get'],
{ host => 'github.com' });
-ok(scalar keys %$cred, 2, "Got 2 Github keys");
+ok(scalar keys %$cred == 2, "Got 2 Github keys");
-ok($cred->{password}, 'carolknows', "Got correct Github password");
-ok($cred->{username}, 'carol', "Got correct Github username");
+is($cred->{password}, 'carolknows', "Got correct Github password");
+is($cred->{username}, 'carol', "Got correct Github username");
-print "# Testing netrc file for a username-specific entry\n";
+diag "Testing netrc file for a username-specific entry\n";
$cred = run_credential(['-f', $netrc, 'get'],
{ host => 'imap', username => 'bob' });
-ok(scalar keys %$cred, 2, "Got 2 username-specific keys");
+ok(scalar keys %$cred == 2, "Got 2 username-specific keys");
-ok($cred->{password}, 'bobwillknow', "Got correct user-specific password");
-ok($cred->{protocol}, 'imaps', "Got correct user-specific protocol");
+is($cred->{password}, 'bobwillknow', "Got correct user-specific password");
+is($cred->{protocol}, 'imaps', "Got correct user-specific protocol");
-print "# Testing netrc file for a host:port-specific entry\n";
+diag "Testing netrc file for a host:port-specific entry\n";
$cred = run_credential(['-f', $netrc, 'get'],
{ host => 'imap2:1099' });
-ok(scalar keys %$cred, 2, "Got 2 host:port-specific keys");
+ok(scalar keys %$cred == 2, "Got 2 host:port-specific keys");
-ok($cred->{password}, 'tzzknow', "Got correct host:port-specific password");
-ok($cred->{username}, 'tzz', "Got correct host:port-specific username");
+is($cred->{password}, 'tzzknow', "Got correct host:port-specific password");
+is($cred->{username}, 'tzz', "Got correct host:port-specific username");
-print "# Testing netrc file that 'host:port kills host' entry\n";
+diag "Testing netrc file that 'host:port kills host' entry\n";
$cred = run_credential(['-f', $netrc, 'get'],
{ host => 'imap2' });
-ok(scalar keys %$cred, 2, "Got 2 'host:port kills host' keys");
+ok(scalar keys %$cred == 2, "Got 2 'host:port kills host' keys");
+
+is($cred->{password}, 'bobwillknow', "Got correct 'host:port kills host' password");
+is($cred->{username}, 'bob', "Got correct 'host:port kills host' username");
+
+diag 'Testing netrc file decryption by git config gpg.program setting\n';
+$cred = run_credential( ['-f', $netrcGpg, 'get']
+ , { host => 'git-config-gpg' }
+ );
+
+ok(scalar keys %$cred == 2, 'Got keys decrypted by git config option');
+
+diag 'Testing netrc file decryption by gpg option\n';
+$cred = run_credential( ['-f', $netrcGpg, '-g', 'test.command-option-gpg', 'get']
+ , { host => 'command-option-gpg' }
+ );
-ok($cred->{password}, 'bobwillknow', "Got correct 'host:port kills host' password");
-ok($cred->{username}, 'bob', "Got correct 'host:port kills host' username");
+ok(scalar keys %$cred == 2, 'Got keys decrypted by command option');
sub run_credential
{
my $args = shift @_;
my $data = shift @_;
my $pid = open2(my $chld_out, my $chld_in,
- './git-credential-netrc', @global_credential_args,
+ $gcNetrc, @global_credential_args,
@$args);
die "Couldn't open pipe to netrc credential helper: $!" unless $pid;
diff --git a/contrib/emacs/.gitignore b/contrib/emacs/.gitignore
deleted file mode 100644
index c531d98..0000000
--- a/contrib/emacs/.gitignore
+++ /dev/null
@@ -1 +0,0 @@
-*.elc
diff --git a/contrib/emacs/Makefile b/contrib/emacs/Makefile
deleted file mode 100644
index 24d9312..0000000
--- a/contrib/emacs/Makefile
+++ /dev/null
@@ -1,21 +0,0 @@
-## Build and install stuff
-
-EMACS = emacs
-
-ELC = git.elc git-blame.elc
-INSTALL ?= install
-INSTALL_ELC = $(INSTALL) -m 644
-prefix ?= $(HOME)
-emacsdir = $(prefix)/share/emacs/site-lisp
-RM ?= rm -f
-
-all: $(ELC)
-
-install: all
- $(INSTALL) -d $(DESTDIR)$(emacsdir)
- $(INSTALL_ELC) $(ELC:.elc=.el) $(ELC) $(DESTDIR)$(emacsdir)
-
-%.elc: %.el
- $(EMACS) -batch -f batch-byte-compile $<
-
-clean:; $(RM) $(ELC)
diff --git a/contrib/emacs/README b/contrib/emacs/README
index 82368bd..977a16f 100644
--- a/contrib/emacs/README
+++ b/contrib/emacs/README
@@ -1,30 +1,24 @@
-This directory contains various modules for Emacs support.
+This directory used to contain various modules for Emacs support.
-To make the modules available to Emacs, you should add this directory
-to your load-path, and then require the modules you want. This can be
-done by adding to your .emacs something like this:
+These were added shortly after Git was first released. Since then
+Emacs's own support for Git got better than what was offered by these
+modes. There are also popular 3rd-party Git modes such as Magit which
+offer replacements for these.
- (add-to-list 'load-path ".../git/contrib/emacs")
- (require 'git)
- (require 'git-blame)
-
-
-The following modules are available:
+The following modules were available, and can be dug up from the Git
+history:
* git.el:
- Status manager that displays the state of all the files of the
- project, and provides easy access to the most frequently used git
- commands. The user interface is as far as possible compatible with
- the pcl-cvs mode. It can be started with `M-x git-status'.
+ Wrapper for "git status" that provided access to other git commands.
+
+ Modern alternatives to this include Magit, and VC mode that ships
+ with Emacs.
* git-blame.el:
- Emacs implementation of incremental git-blame. When you turn it on
- while viewing a file, the editor buffer will be updated by setting
- the background of individual lines to a color that reflects which
- commit it comes from. And when you move around the buffer, a
- one-line summary will be shown in the echo area.
+ A wrapper for "git blame" written before Emacs's own vc-annotate
+ mode learned to invoke git-blame, which can be done via C-x v g.
* vc-git.el:
diff --git a/contrib/emacs/git-blame.el b/contrib/emacs/git-blame.el
index 510e0f7..6a8a2b8 100644
--- a/contrib/emacs/git-blame.el
+++ b/contrib/emacs/git-blame.el
@@ -1,483 +1,6 @@
-;;; git-blame.el --- Minor mode for incremental blame for Git -*- coding: utf-8 -*-
-;;
-;; Copyright (C) 2007 David Kågedal
-;;
-;; Authors: David Kågedal <davidk@lysator.liu.se>
-;; Created: 31 Jan 2007
-;; Message-ID: <87iren2vqx.fsf@morpheus.local>
-;; License: GPL
-;; Keywords: git, version control, release management
-;;
-;; Compatibility: Emacs21, Emacs22 and EmacsCVS
-;; Git 1.5 and up
-
-;; This file is *NOT* part of GNU Emacs.
-;; This file is distributed under the same terms as GNU Emacs.
-
-;; This program is free software; you can redistribute it and/or
-;; modify it under the terms of the GNU General Public License as
-;; published by the Free Software Foundation; either version 2 of
-;; the License, or (at your option) any later version.
-
-;; This program is distributed in the hope that it will be
-;; useful, but WITHOUT ANY WARRANTY; without even the implied
-;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-;; PURPOSE. See the GNU General Public License for more details.
-
-;; You should have received a copy of the GNU General Public
-;; License along with this program; if not, see
-;; <http://www.gnu.org/licenses/>.
-
-;; http://www.fsf.org/copyleft/gpl.html
-
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;
-;;; Commentary:
-;;
-;; Here is an Emacs implementation of incremental git-blame. When you
-;; turn it on while viewing a file, the editor buffer will be updated by
-;; setting the background of individual lines to a color that reflects
-;; which commit it comes from. And when you move around the buffer, a
-;; one-line summary will be shown in the echo area.
-
-;;; Installation:
-;;
-;; To use this package, put it somewhere in `load-path' (or add
-;; directory with git-blame.el to `load-path'), and add the following
-;; line to your .emacs:
-;;
-;; (require 'git-blame)
-;;
-;; If you do not want to load this package before it is necessary, you
-;; can make use of the `autoload' feature, e.g. by adding to your .emacs
-;; the following lines
-;;
-;; (autoload 'git-blame-mode "git-blame"
-;; "Minor mode for incremental blame for Git." t)
-;;
-;; Then first use of `M-x git-blame-mode' would load the package.
-
-;;; Compatibility:
-;;
-;; It requires GNU Emacs 21 or later and Git 1.5.0 and up
-;;
-;; If you'are using Emacs 20, try changing this:
-;;
-;; (overlay-put ovl 'face (list :background
-;; (cdr (assq 'color (cddddr info)))))
-;;
-;; to
-;;
-;; (overlay-put ovl 'face (cons 'background-color
-;; (cdr (assq 'color (cddddr info)))))
-
-
-;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
-;;
-;;; Code:
-
-(eval-when-compile (require 'cl)) ; to use `push', `pop'
-(require 'format-spec)
-
-(defface git-blame-prefix-face
- '((((background dark)) (:foreground "gray"
- :background "black"))
- (((background light)) (:foreground "gray"
- :background "white"))
- (t (:weight bold)))
- "The face used for the hash prefix."
- :group 'git-blame)
-
-(defgroup git-blame nil
- "A minor mode showing Git blame information."
- :group 'git
- :link '(function-link git-blame-mode))
-
-
-(defcustom git-blame-use-colors t
- "Use colors to indicate commits in `git-blame-mode'."
- :type 'boolean
- :group 'git-blame)
-
-(defcustom git-blame-prefix-format
- "%h %20A:"
- "The format of the prefix added to each line in `git-blame'
-mode. The format is passed to `format-spec' with the following format keys:
-
- %h - the abbreviated hash
- %H - the full hash
- %a - the author name
- %A - the author email
- %c - the committer name
- %C - the committer email
- %s - the commit summary
-"
- :group 'git-blame)
-
-(defcustom git-blame-mouseover-format
- "%h %a %A: %s"
- "The format of the description shown when pointing at a line in
-`git-blame' mode. The format string is passed to `format-spec'
-with the following format keys:
-
- %h - the abbreviated hash
- %H - the full hash
- %a - the author name
- %A - the author email
- %c - the committer name
- %C - the committer email
- %s - the commit summary
-"
- :group 'git-blame)
-
-
-(defun git-blame-color-scale (&rest elements)
- "Given a list, returns a list of triples formed with each
-elements of the list.
-
-a b => bbb bba bab baa abb aba aaa aab"
- (let (result)
- (dolist (a elements)
- (dolist (b elements)
- (dolist (c elements)
- (setq result (cons (format "#%s%s%s" a b c) result)))))
- result))
-
-;; (git-blame-color-scale "0c" "04" "24" "1c" "2c" "34" "14" "3c") =>
-;; ("#3c3c3c" "#3c3c14" "#3c3c34" "#3c3c2c" "#3c3c1c" "#3c3c24"
-;; "#3c3c04" "#3c3c0c" "#3c143c" "#3c1414" "#3c1434" "#3c142c" ...)
-
-(defmacro git-blame-random-pop (l)
- "Select a random element from L and returns it. Also remove
-selected element from l."
- ;; only works on lists with unique elements
- `(let ((e (elt ,l (random (length ,l)))))
- (setq ,l (remove e ,l))
- e))
-
-(defvar git-blame-log-oneline-format
- "format:[%cr] %cn: %s"
- "*Formatting option used for describing current line in the minibuffer.
-
-This option is used to pass to git log --pretty= command-line option,
-and describe which commit the current line was made.")
-
-(defvar git-blame-dark-colors
- (git-blame-color-scale "0c" "04" "24" "1c" "2c" "34" "14" "3c")
- "*List of colors (format #RGB) to use in a dark environment.
-
-To check out the list, evaluate (list-colors-display git-blame-dark-colors).")
-
-(defvar git-blame-light-colors
- (git-blame-color-scale "c4" "d4" "cc" "dc" "f4" "e4" "fc" "ec")
- "*List of colors (format #RGB) to use in a light environment.
-
-To check out the list, evaluate (list-colors-display git-blame-light-colors).")
-
-(defvar git-blame-colors '()
- "Colors used by git-blame. The list is built once when activating git-blame
-minor mode.")
-
-(defvar git-blame-ancient-color "dark green"
- "*Color to be used for ancient commit.")
-
-(defvar git-blame-autoupdate t
- "*Automatically update the blame display while editing")
-
-(defvar git-blame-proc nil
- "The running git-blame process")
-(make-variable-buffer-local 'git-blame-proc)
-
-(defvar git-blame-overlays nil
- "The git-blame overlays used in the current buffer.")
-(make-variable-buffer-local 'git-blame-overlays)
-
-(defvar git-blame-cache nil
- "A cache of git-blame information for the current buffer")
-(make-variable-buffer-local 'git-blame-cache)
-
-(defvar git-blame-idle-timer nil
- "An idle timer that updates the blame")
-(make-variable-buffer-local 'git-blame-cache)
-
-(defvar git-blame-update-queue nil
- "A queue of update requests")
-(make-variable-buffer-local 'git-blame-update-queue)
-
-;; FIXME: docstrings
-(defvar git-blame-file nil)
-(defvar git-blame-current nil)
-
-(defvar git-blame-mode nil)
-(make-variable-buffer-local 'git-blame-mode)
-
-(defvar git-blame-mode-line-string " blame"
- "String to display on the mode line when git-blame is active.")
-
-(or (assq 'git-blame-mode minor-mode-alist)
- (setq minor-mode-alist
- (cons '(git-blame-mode git-blame-mode-line-string) minor-mode-alist)))
-
-;;;###autoload
-(defun git-blame-mode (&optional arg)
- "Toggle minor mode for displaying Git blame
-
-With prefix ARG, turn the mode on if ARG is positive."
- (interactive "P")
- (cond
- ((null arg)
- (if git-blame-mode (git-blame-mode-off) (git-blame-mode-on)))
- ((> (prefix-numeric-value arg) 0) (git-blame-mode-on))
- (t (git-blame-mode-off))))
-
-(defun git-blame-mode-on ()
- "Turn on git-blame mode.
-
-See also function `git-blame-mode'."
- (make-local-variable 'git-blame-colors)
- (if git-blame-autoupdate
- (add-hook 'after-change-functions 'git-blame-after-change nil t)
- (remove-hook 'after-change-functions 'git-blame-after-change t))
- (git-blame-cleanup)
- (let ((bgmode (cdr (assoc 'background-mode (frame-parameters)))))
- (if (eq bgmode 'dark)
- (setq git-blame-colors git-blame-dark-colors)
- (setq git-blame-colors git-blame-light-colors)))
- (setq git-blame-cache (make-hash-table :test 'equal))
- (setq git-blame-mode t)
- (git-blame-run))
-
-(defun git-blame-mode-off ()
- "Turn off git-blame mode.
-
-See also function `git-blame-mode'."
- (git-blame-cleanup)
- (if git-blame-idle-timer (cancel-timer git-blame-idle-timer))
- (setq git-blame-mode nil))
-
-;;;###autoload
-(defun git-reblame ()
- "Recalculate all blame information in the current buffer"
- (interactive)
- (unless git-blame-mode
- (error "Git-blame is not active"))
-
- (git-blame-cleanup)
- (git-blame-run))
-
-(defun git-blame-run (&optional startline endline)
- (if git-blame-proc
- ;; Should maybe queue up a new run here
- (message "Already running git blame")
- (let ((display-buf (current-buffer))
- (blame-buf (get-buffer-create
- (concat " git blame for " (buffer-name))))
- (args '("--incremental" "--contents" "-")))
- (if startline
- (setq args (append args
- (list "-L" (format "%d,%d" startline endline)))))
- (setq args (append args
- (list (file-name-nondirectory buffer-file-name))))
- (setq git-blame-proc
- (apply 'start-process
- "git-blame" blame-buf
- "git" "blame"
- args))
- (with-current-buffer blame-buf
- (erase-buffer)
- (make-local-variable 'git-blame-file)
- (make-local-variable 'git-blame-current)
- (setq git-blame-file display-buf)
- (setq git-blame-current nil))
- (set-process-filter git-blame-proc 'git-blame-filter)
- (set-process-sentinel git-blame-proc 'git-blame-sentinel)
- (process-send-region git-blame-proc (point-min) (point-max))
- (process-send-eof git-blame-proc))))
-
-(defun remove-git-blame-text-properties (start end)
- (let ((modified (buffer-modified-p))
- (inhibit-read-only t))
- (remove-text-properties start end '(point-entered nil))
- (set-buffer-modified-p modified)))
-
-(defun git-blame-cleanup ()
- "Remove all blame properties"
- (mapc 'delete-overlay git-blame-overlays)
- (setq git-blame-overlays nil)
- (remove-git-blame-text-properties (point-min) (point-max)))
-
-(defun git-blame-update-region (start end)
- "Rerun blame to get updates between START and END"
- (let ((overlays (overlays-in start end)))
- (while overlays
- (let ((overlay (pop overlays)))
- (if (< (overlay-start overlay) start)
- (setq start (overlay-start overlay)))
- (if (> (overlay-end overlay) end)
- (setq end (overlay-end overlay)))
- (setq git-blame-overlays (delete overlay git-blame-overlays))
- (delete-overlay overlay))))
- (remove-git-blame-text-properties start end)
- ;; We can be sure that start and end are at line breaks
- (git-blame-run (1+ (count-lines (point-min) start))
- (count-lines (point-min) end)))
-
-(defun git-blame-sentinel (proc status)
- (with-current-buffer (process-buffer proc)
- (with-current-buffer git-blame-file
- (setq git-blame-proc nil)
- (if git-blame-update-queue
- (git-blame-delayed-update))))
- ;;(kill-buffer (process-buffer proc))
- ;;(message "git blame finished")
- )
-
-(defvar in-blame-filter nil)
-
-(defun git-blame-filter (proc str)
- (with-current-buffer (process-buffer proc)
- (save-excursion
- (goto-char (process-mark proc))
- (insert-before-markers str)
- (goto-char (point-min))
- (unless in-blame-filter
- (let ((more t)
- (in-blame-filter t))
- (while more
- (setq more (git-blame-parse))))))))
-
-(defun git-blame-parse ()
- (cond ((looking-at "\\([0-9a-f]\\{40\\}\\) \\([0-9]+\\) \\([0-9]+\\) \\([0-9]+\\)\n")
- (let ((hash (match-string 1))
- (src-line (string-to-number (match-string 2)))
- (res-line (string-to-number (match-string 3)))
- (num-lines (string-to-number (match-string 4))))
- (delete-region (point) (match-end 0))
- (setq git-blame-current (list (git-blame-new-commit hash)
- src-line res-line num-lines)))
- t)
- ((looking-at "\\([a-z-]+\\) \\(.+\\)\n")
- (let ((key (match-string 1))
- (value (match-string 2)))
- (delete-region (point) (match-end 0))
- (git-blame-add-info (car git-blame-current) key value)
- (when (string= key "filename")
- (git-blame-create-overlay (car git-blame-current)
- (caddr git-blame-current)
- (cadddr git-blame-current))
- (setq git-blame-current nil)))
- t)
- (t
- nil)))
-
-(defun git-blame-new-commit (hash)
- (with-current-buffer git-blame-file
- (or (gethash hash git-blame-cache)
- ;; Assign a random color to each new commit info
- ;; Take care not to select the same color multiple times
- (let* ((color (if git-blame-colors
- (git-blame-random-pop git-blame-colors)
- git-blame-ancient-color))
- (info `(,hash (color . ,color))))
- (puthash hash info git-blame-cache)
- info))))
-
-(defun git-blame-create-overlay (info start-line num-lines)
- (with-current-buffer git-blame-file
- (save-excursion
- (let ((inhibit-point-motion-hooks t)
- (inhibit-modification-hooks t))
- (goto-char (point-min))
- (forward-line (1- start-line))
- (let* ((start (point))
- (end (progn (forward-line num-lines) (point)))
- (ovl (make-overlay start end))
- (hash (car info))
- (spec `((?h . ,(substring hash 0 6))
- (?H . ,hash)
- (?a . ,(git-blame-get-info info 'author))
- (?A . ,(git-blame-get-info info 'author-mail))
- (?c . ,(git-blame-get-info info 'committer))
- (?C . ,(git-blame-get-info info 'committer-mail))
- (?s . ,(git-blame-get-info info 'summary)))))
- (push ovl git-blame-overlays)
- (overlay-put ovl 'git-blame info)
- (overlay-put ovl 'help-echo
- (format-spec git-blame-mouseover-format spec))
- (if git-blame-use-colors
- (overlay-put ovl 'face (list :background
- (cdr (assq 'color (cdr info))))))
- (overlay-put ovl 'line-prefix
- (propertize (format-spec git-blame-prefix-format spec)
- 'face 'git-blame-prefix-face)))))))
-
-(defun git-blame-add-info (info key value)
- (nconc info (list (cons (intern key) value))))
-
-(defun git-blame-get-info (info key)
- (cdr (assq key (cdr info))))
-
-(defun git-blame-current-commit ()
- (let ((info (get-char-property (point) 'git-blame)))
- (if info
- (car info)
- (error "No commit info"))))
-
-(defun git-describe-commit (hash)
- (with-temp-buffer
- (call-process "git" nil t nil
- "log" "-1"
- (concat "--pretty=" git-blame-log-oneline-format)
- hash)
- (buffer-substring (point-min) (point-max))))
-
-(defvar git-blame-last-identification nil)
-(make-variable-buffer-local 'git-blame-last-identification)
-(defun git-blame-identify (&optional hash)
- (interactive)
- (let ((info (gethash (or hash (git-blame-current-commit)) git-blame-cache)))
- (when (and info (not (eq info git-blame-last-identification)))
- (message "%s" (nth 4 info))
- (setq git-blame-last-identification info))))
-
-;; (defun git-blame-after-save ()
-;; (when git-blame-mode
-;; (git-blame-cleanup)
-;; (git-blame-run)))
-;; (add-hook 'after-save-hook 'git-blame-after-save)
-
-(defun git-blame-after-change (start end length)
- (when git-blame-mode
- (git-blame-enq-update start end)))
-
-(defvar git-blame-last-update nil)
-(make-variable-buffer-local 'git-blame-last-update)
-(defun git-blame-enq-update (start end)
- "Mark the region between START and END as needing blame update"
- ;; Try to be smart and avoid multiple callouts for sequential
- ;; editing
- (cond ((and git-blame-last-update
- (= start (cdr git-blame-last-update)))
- (setcdr git-blame-last-update end))
- ((and git-blame-last-update
- (= end (car git-blame-last-update)))
- (setcar git-blame-last-update start))
- (t
- (setq git-blame-last-update (cons start end))
- (setq git-blame-update-queue (nconc git-blame-update-queue
- (list git-blame-last-update)))))
- (unless (or git-blame-proc git-blame-idle-timer)
- (setq git-blame-idle-timer
- (run-with-idle-timer 0.5 nil 'git-blame-delayed-update))))
-
-(defun git-blame-delayed-update ()
- (setq git-blame-idle-timer nil)
- (if git-blame-update-queue
- (let ((first (pop git-blame-update-queue))
- (inhibit-point-motion-hooks t))
- (git-blame-update-region (car first) (cdr first)))))
-
-(provide 'git-blame)
-
-;;; git-blame.el ends here
+(error "git-blame.el no longer ships with git. It's recommended
+to replace its use with Emacs's own vc-annotate. See
+contrib/emacs/README in git's
+sources (https://github.com/git/git/blob/master/contrib/emacs/README)
+for more info on suggested alternatives and for why this
+happened.")
diff --git a/contrib/emacs/git.el b/contrib/emacs/git.el
index 97919f2..03f9262 100644
--- a/contrib/emacs/git.el
+++ b/contrib/emacs/git.el
@@ -1,1704 +1,6 @@
-;;; git.el --- A user interface for git
-
-;; Copyright (C) 2005, 2006, 2007, 2008, 2009 Alexandre Julliard <julliard@winehq.org>
-
-;; Version: 1.0
-
-;; This program is free software; you can redistribute it and/or
-;; modify it under the terms of the GNU General Public License as
-;; published by the Free Software Foundation; either version 2 of
-;; the License, or (at your option) any later version.
-;;
-;; This program is distributed in the hope that it will be
-;; useful, but WITHOUT ANY WARRANTY; without even the implied
-;; warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
-;; PURPOSE. See the GNU General Public License for more details.
-;;
-;; You should have received a copy of the GNU General Public
-;; License along with this program; if not, see
-;; <http://www.gnu.org/licenses/>.
-
-;;; Commentary:
-
-;; This file contains an interface for the git version control
-;; system. It provides easy access to the most frequently used git
-;; commands. The user interface is as far as possible identical to
-;; that of the PCL-CVS mode.
-;;
-;; To install: put this file on the load-path and place the following
-;; in your .emacs file:
-;;
-;; (require 'git)
-;;
-;; To start: `M-x git-status'
-;;
-;; TODO
-;; - diff against other branch
-;; - renaming files from the status buffer
-;; - creating tags
-;; - fetch/pull
-;; - revlist browser
-;; - git-show-branch browser
-;;
-
-;;; Compatibility:
-;;
-;; This file works on GNU Emacs 21 or later. It may work on older
-;; versions but this is not guaranteed.
-;;
-;; It may work on XEmacs 21, provided that you first install the ewoc
-;; and log-edit packages.
-;;
-
-(eval-when-compile (require 'cl))
-(require 'ewoc)
-(require 'log-edit)
-(require 'easymenu)
-
-
-;;;; Customizations
-;;;; ------------------------------------------------------------
-
-(defgroup git nil
- "A user interface for the git versioning system."
- :group 'tools)
-
-(defcustom git-committer-name nil
- "User name to use for commits.
-The default is to fall back to the repository config,
-then to `add-log-full-name' and then to `user-full-name'."
- :group 'git
- :type '(choice (const :tag "Default" nil)
- (string :tag "Name")))
-
-(defcustom git-committer-email nil
- "Email address to use for commits.
-The default is to fall back to the git repository config,
-then to `add-log-mailing-address' and then to `user-mail-address'."
- :group 'git
- :type '(choice (const :tag "Default" nil)
- (string :tag "Email")))
-
-(defcustom git-commits-coding-system nil
- "Default coding system for the log message of git commits."
- :group 'git
- :type '(choice (const :tag "From repository config" nil)
- (coding-system)))
-
-(defcustom git-append-signed-off-by nil
- "Whether to append a Signed-off-by line to the commit message before editing."
- :group 'git
- :type 'boolean)
-
-(defcustom git-reuse-status-buffer t
- "Whether `git-status' should try to reuse an existing buffer
-if there is already one that displays the same directory."
- :group 'git
- :type 'boolean)
-
-(defcustom git-per-dir-ignore-file ".gitignore"
- "Name of the per-directory ignore file."
- :group 'git
- :type 'string)
-
-(defcustom git-show-uptodate nil
- "Whether to display up-to-date files."
- :group 'git
- :type 'boolean)
-
-(defcustom git-show-ignored nil
- "Whether to display ignored files."
- :group 'git
- :type 'boolean)
-
-(defcustom git-show-unknown t
- "Whether to display unknown files."
- :group 'git
- :type 'boolean)
-
-
-(defface git-status-face
- '((((class color) (background light)) (:foreground "purple"))
- (((class color) (background dark)) (:foreground "salmon")))
- "Git mode face used to highlight added and modified files."
- :group 'git)
-
-(defface git-unmerged-face
- '((((class color) (background light)) (:foreground "red" :bold t))
- (((class color) (background dark)) (:foreground "red" :bold t)))
- "Git mode face used to highlight unmerged files."
- :group 'git)
-
-(defface git-unknown-face
- '((((class color) (background light)) (:foreground "goldenrod" :bold t))
- (((class color) (background dark)) (:foreground "goldenrod" :bold t)))
- "Git mode face used to highlight unknown files."
- :group 'git)
-
-(defface git-uptodate-face
- '((((class color) (background light)) (:foreground "grey60"))
- (((class color) (background dark)) (:foreground "grey40")))
- "Git mode face used to highlight up-to-date files."
- :group 'git)
-
-(defface git-ignored-face
- '((((class color) (background light)) (:foreground "grey60"))
- (((class color) (background dark)) (:foreground "grey40")))
- "Git mode face used to highlight ignored files."
- :group 'git)
-
-(defface git-mark-face
- '((((class color) (background light)) (:foreground "red" :bold t))
- (((class color) (background dark)) (:foreground "tomato" :bold t)))
- "Git mode face used for the file marks."
- :group 'git)
-
-(defface git-header-face
- '((((class color) (background light)) (:foreground "blue"))
- (((class color) (background dark)) (:foreground "blue")))
- "Git mode face used for commit headers."
- :group 'git)
-
-(defface git-separator-face
- '((((class color) (background light)) (:foreground "brown"))
- (((class color) (background dark)) (:foreground "brown")))
- "Git mode face used for commit separator."
- :group 'git)
-
-(defface git-permission-face
- '((((class color) (background light)) (:foreground "green" :bold t))
- (((class color) (background dark)) (:foreground "green" :bold t)))
- "Git mode face used for permission changes."
- :group 'git)
-
-
-;;;; Utilities
-;;;; ------------------------------------------------------------
-
-(defconst git-log-msg-separator "--- log message follows this line ---")
-
-(defvar git-log-edit-font-lock-keywords
- `(("^\\(Author:\\|Date:\\|Merge:\\|Signed-off-by:\\)\\(.*\\)$"
- (1 font-lock-keyword-face)
- (2 font-lock-function-name-face))
- (,(concat "^\\(" (regexp-quote git-log-msg-separator) "\\)$")
- (1 font-lock-comment-face))))
-
-(defun git-get-env-strings (env)
- "Build a list of NAME=VALUE strings from a list of environment strings."
- (mapcar (lambda (entry) (concat (car entry) "=" (cdr entry))) env))
-
-(defun git-call-process (buffer &rest args)
- "Wrapper for call-process that sets environment strings."
- (apply #'call-process "git" nil buffer nil args))
-
-(defun git-call-process-display-error (&rest args)
- "Wrapper for call-process that displays error messages."
- (let* ((dir default-directory)
- (buffer (get-buffer-create "*Git Command Output*"))
- (ok (with-current-buffer buffer
- (let ((default-directory dir)
- (buffer-read-only nil))
- (erase-buffer)
- (eq 0 (apply #'git-call-process (list buffer t) args))))))
- (unless ok (display-message-or-buffer buffer))
- ok))
-
-(defun git-call-process-string (&rest args)
- "Wrapper for call-process that returns the process output as a string,
-or nil if the git command failed."
- (with-temp-buffer
- (and (eq 0 (apply #'git-call-process t args))
- (buffer-string))))
-
-(defun git-call-process-string-display-error (&rest args)
- "Wrapper for call-process that displays error message and returns
-the process output as a string, or nil if the git command failed."
- (with-temp-buffer
- (if (eq 0 (apply #'git-call-process (list t t) args))
- (buffer-string)
- (display-message-or-buffer (current-buffer))
- nil)))
-
-(defun git-run-process-region (buffer start end program args)
- "Run a git process with a buffer region as input."
- (let ((output-buffer (current-buffer))
- (dir default-directory))
- (with-current-buffer buffer
- (cd dir)
- (apply #'call-process-region start end program
- nil (list output-buffer t) nil args))))
-
-(defun git-run-command-buffer (buffer-name &rest args)
- "Run a git command, sending the output to a buffer named BUFFER-NAME."
- (let ((dir default-directory)
- (buffer (get-buffer-create buffer-name)))
- (message "Running git %s..." (car args))
- (with-current-buffer buffer
- (let ((default-directory dir)
- (buffer-read-only nil))
- (erase-buffer)
- (apply #'git-call-process buffer args)))
- (message "Running git %s...done" (car args))
- buffer))
-
-(defun git-run-command-region (buffer start end env &rest args)
- "Run a git command with specified buffer region as input."
- (with-temp-buffer
- (if (eq 0 (if env
- (git-run-process-region
- buffer start end "env"
- (append (git-get-env-strings env) (list "git") args))
- (git-run-process-region buffer start end "git" args)))
- (buffer-string)
- (display-message-or-buffer (current-buffer))
- nil)))
-
-(defun git-run-hook (hook env &rest args)
- "Run a git hook and display its output if any."
- (let ((dir default-directory)
- (hook-name (expand-file-name (concat ".git/hooks/" hook))))
- (or (not (file-executable-p hook-name))
- (let (status (buffer (get-buffer-create "*Git Hook Output*")))
- (with-current-buffer buffer
- (erase-buffer)
- (cd dir)
- (setq status
- (if env
- (apply #'call-process "env" nil (list buffer t) nil
- (append (git-get-env-strings env) (list hook-name) args))
- (apply #'call-process hook-name nil (list buffer t) nil args))))
- (display-message-or-buffer buffer)
- (eq 0 status)))))
-
-(defun git-get-string-sha1 (string)
- "Read a SHA1 from the specified string."
- (and string
- (string-match "[0-9a-f]\\{40\\}" string)
- (match-string 0 string)))
-
-(defun git-get-committer-name ()
- "Return the name to use as GIT_COMMITTER_NAME."
- ; copied from log-edit
- (or git-committer-name
- (git-config "user.name")
- (and (boundp 'add-log-full-name) add-log-full-name)
- (and (fboundp 'user-full-name) (user-full-name))
- (and (boundp 'user-full-name) user-full-name)))
-
-(defun git-get-committer-email ()
- "Return the email address to use as GIT_COMMITTER_EMAIL."
- ; copied from log-edit
- (or git-committer-email
- (git-config "user.email")
- (and (boundp 'add-log-mailing-address) add-log-mailing-address)
- (and (fboundp 'user-mail-address) (user-mail-address))
- (and (boundp 'user-mail-address) user-mail-address)))
-
-(defun git-get-commits-coding-system ()
- "Return the coding system to use for commits."
- (let ((repo-config (git-config "i18n.commitencoding")))
- (or git-commits-coding-system
- (and repo-config
- (fboundp 'locale-charset-to-coding-system)
- (locale-charset-to-coding-system repo-config))
- 'utf-8)))
-
-(defun git-get-logoutput-coding-system ()
- "Return the coding system used for git-log output."
- (let ((repo-config (or (git-config "i18n.logoutputencoding")
- (git-config "i18n.commitencoding"))))
- (or git-commits-coding-system
- (and repo-config
- (fboundp 'locale-charset-to-coding-system)
- (locale-charset-to-coding-system repo-config))
- 'utf-8)))
-
-(defun git-escape-file-name (name)
- "Escape a file name if necessary."
- (if (string-match "[\n\t\"\\]" name)
- (concat "\""
- (mapconcat (lambda (c)
- (case c
- (?\n "\\n")
- (?\t "\\t")
- (?\\ "\\\\")
- (?\" "\\\"")
- (t (char-to-string c))))
- name "")
- "\"")
- name))
-
-(defun git-success-message (text files)
- "Print a success message after having handled FILES."
- (let ((n (length files)))
- (if (equal n 1)
- (message "%s %s" text (car files))
- (message "%s %d files" text n))))
-
-(defun git-get-top-dir (dir)
- "Retrieve the top-level directory of a git tree."
- (let ((cdup (with-output-to-string
- (with-current-buffer standard-output
- (cd dir)
- (unless (eq 0 (git-call-process t "rev-parse" "--show-cdup"))
- (error "cannot find top-level git tree for %s." dir))))))
- (expand-file-name (concat (file-name-as-directory dir)
- (car (split-string cdup "\n"))))))
-
-;stolen from pcl-cvs
-(defun git-append-to-ignore (file)
- "Add a file name to the ignore file in its directory."
- (let* ((fullname (expand-file-name file))
- (dir (file-name-directory fullname))
- (name (file-name-nondirectory fullname))
- (ignore-name (expand-file-name git-per-dir-ignore-file dir))
- (created (not (file-exists-p ignore-name))))
- (save-window-excursion
- (set-buffer (find-file-noselect ignore-name))
- (goto-char (point-max))
- (unless (zerop (current-column)) (insert "\n"))
- (insert "/" name "\n")
- (sort-lines nil (point-min) (point-max))
- (save-buffer))
- (when created
- (git-call-process nil "update-index" "--add" "--" (file-relative-name ignore-name)))
- (git-update-status-files (list (file-relative-name ignore-name)))))
-
-; propertize definition for XEmacs, stolen from erc-compat
-(eval-when-compile
- (unless (fboundp 'propertize)
- (defun propertize (string &rest props)
- (let ((string (copy-sequence string)))
- (while props
- (put-text-property 0 (length string) (nth 0 props) (nth 1 props) string)
- (setq props (cddr props)))
- string))))
-
-;;;; Wrappers for basic git commands
-;;;; ------------------------------------------------------------
-
-(defun git-rev-parse (rev)
- "Parse a revision name and return its SHA1."
- (git-get-string-sha1
- (git-call-process-string "rev-parse" rev)))
-
-(defun git-config (key)
- "Retrieve the value associated to KEY in the git repository config file."
- (let ((str (git-call-process-string "config" key)))
- (and str (car (split-string str "\n")))))
-
-(defun git-symbolic-ref (ref)
- "Wrapper for the git-symbolic-ref command."
- (let ((str (git-call-process-string "symbolic-ref" ref)))
- (and str (car (split-string str "\n")))))
-
-(defun git-update-ref (ref newval &optional oldval reason)
- "Update a reference by calling git-update-ref."
- (let ((args (and oldval (list oldval))))
- (when newval (push newval args))
- (push ref args)
- (when reason
- (push reason args)
- (push "-m" args))
- (unless newval (push "-d" args))
- (apply 'git-call-process-display-error "update-ref" args)))
-
-(defun git-for-each-ref (&rest specs)
- "Return a list of refs using git-for-each-ref.
-Each entry is a cons of (SHORT-NAME . FULL-NAME)."
- (let (refs)
- (with-temp-buffer
- (apply #'git-call-process t "for-each-ref" "--format=%(refname)" specs)
- (goto-char (point-min))
- (while (re-search-forward "^[^/\n]+/[^/\n]+/\\(.+\\)$" nil t)
- (push (cons (match-string 1) (match-string 0)) refs)))
- (nreverse refs)))
-
-(defun git-read-tree (tree &optional index-file)
- "Read a tree into the index file."
- (let ((process-environment
- (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file))) process-environment)))
- (apply 'git-call-process-display-error "read-tree" (if tree (list tree)))))
-
-(defun git-write-tree (&optional index-file)
- "Call git-write-tree and return the resulting tree SHA1 as a string."
- (let ((process-environment
- (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file))) process-environment)))
- (git-get-string-sha1
- (git-call-process-string-display-error "write-tree"))))
-
-(defun git-commit-tree (buffer tree parent)
- "Create a commit and possibly update HEAD.
-Create a commit with the message in BUFFER using the tree with hash TREE.
-Use PARENT as the parent of the new commit. If PARENT is the current \"HEAD\",
-update the \"HEAD\" reference to the new commit."
- (let ((author-name (git-get-committer-name))
- (author-email (git-get-committer-email))
- (subject "commit (initial): ")
- author-date log-start log-end args coding-system-for-write)
- (when parent
- (setq subject "commit: ")
- (push "-p" args)
- (push parent args))
- (with-current-buffer buffer
- (goto-char (point-min))
- (if
- (setq log-start (re-search-forward (concat "^" (regexp-quote git-log-msg-separator) "\n") nil t))
- (save-restriction
- (narrow-to-region (point-min) log-start)
- (goto-char (point-min))
- (when (re-search-forward "^Author: +\\(.*?\\) *<\\(.*\\)> *$" nil t)
- (setq author-name (match-string 1)
- author-email (match-string 2)))
- (goto-char (point-min))
- (when (re-search-forward "^Date: +\\(.*\\)$" nil t)
- (setq author-date (match-string 1)))
- (goto-char (point-min))
- (when (re-search-forward "^Merge: +\\(.*\\)" nil t)
- (setq subject "commit (merge): ")
- (dolist (parent (split-string (match-string 1) " +" t))
- (push "-p" args)
- (push parent args))))
- (setq log-start (point-min)))
- (setq log-end (point-max))
- (goto-char log-start)
- (when (re-search-forward ".*$" nil t)
- (setq subject (concat subject (match-string 0))))
- (setq coding-system-for-write buffer-file-coding-system))
- (let ((commit
- (git-get-string-sha1
- (let ((env `(("GIT_AUTHOR_NAME" . ,author-name)
- ("GIT_AUTHOR_EMAIL" . ,author-email)
- ("GIT_COMMITTER_NAME" . ,(git-get-committer-name))
- ("GIT_COMMITTER_EMAIL" . ,(git-get-committer-email)))))
- (when author-date (push `("GIT_AUTHOR_DATE" . ,author-date) env))
- (apply #'git-run-command-region
- buffer log-start log-end env
- "commit-tree" tree (nreverse args))))))
- (when commit (git-update-ref "HEAD" commit parent subject))
- commit)))
-
-(defun git-empty-db-p ()
- "Check if the git db is empty (no commit done yet)."
- (not (eq 0 (git-call-process nil "rev-parse" "--verify" "HEAD"))))
-
-(defun git-get-merge-heads ()
- "Retrieve the merge heads from the MERGE_HEAD file if present."
- (let (heads)
- (when (file-readable-p ".git/MERGE_HEAD")
- (with-temp-buffer
- (insert-file-contents ".git/MERGE_HEAD" nil nil nil t)
- (goto-char (point-min))
- (while (re-search-forward "[0-9a-f]\\{40\\}" nil t)
- (push (match-string 0) heads))))
- (nreverse heads)))
-
-(defun git-get-commit-description (commit)
- "Get a one-line description of COMMIT."
- (let ((coding-system-for-read (git-get-logoutput-coding-system)))
- (let ((descr (git-call-process-string "log" "--max-count=1" "--pretty=oneline" commit)))
- (if (and descr (string-match "\\`\\([0-9a-f]\\{40\\}\\) *\\(.*\\)$" descr))
- (concat (substring (match-string 1 descr) 0 10) " - " (match-string 2 descr))
- descr))))
-
-;;;; File info structure
-;;;; ------------------------------------------------------------
-
-; fileinfo structure stolen from pcl-cvs
-(defstruct (git-fileinfo
- (:copier nil)
- (:constructor git-create-fileinfo (state name &optional old-perm new-perm rename-state orig-name marked))
- (:conc-name git-fileinfo->))
- marked ;; t/nil
- state ;; current state
- name ;; file name
- old-perm new-perm ;; permission flags
- rename-state ;; rename or copy state
- orig-name ;; original name for renames or copies
- needs-update ;; whether file needs to be updated
- needs-refresh) ;; whether file needs to be refreshed
-
-(defvar git-status nil)
-
-(defun git-set-fileinfo-state (info state)
- "Set the state of a file info."
- (unless (eq (git-fileinfo->state info) state)
- (setf (git-fileinfo->state info) state
- (git-fileinfo->new-perm info) (git-fileinfo->old-perm info)
- (git-fileinfo->rename-state info) nil
- (git-fileinfo->orig-name info) nil
- (git-fileinfo->needs-update info) nil
- (git-fileinfo->needs-refresh info) t)))
-
-(defun git-status-filenames-map (status func files &rest args)
- "Apply FUNC to the status files names in the FILES list.
-The list must be sorted."
- (when files
- (let ((file (pop files))
- (node (ewoc-nth status 0)))
- (while (and file node)
- (let* ((info (ewoc-data node))
- (name (git-fileinfo->name info)))
- (if (string-lessp name file)
- (setq node (ewoc-next status node))
- (if (string-equal name file)
- (apply func info args))
- (setq file (pop files))))))))
-
-(defun git-set-filenames-state (status files state)
- "Set the state of a list of named files. The list must be sorted"
- (when files
- (git-status-filenames-map status #'git-set-fileinfo-state files state)
- (unless state ;; delete files whose state has been set to nil
- (ewoc-filter status (lambda (info) (git-fileinfo->state info))))))
-
-(defun git-state-code (code)
- "Convert from a string to a added/deleted/modified state."
- (case (string-to-char code)
- (?M 'modified)
- (?? 'unknown)
- (?A 'added)
- (?D 'deleted)
- (?U 'unmerged)
- (?T 'modified)
- (t nil)))
-
-(defun git-status-code-as-string (code)
- "Format a git status code as string."
- (case code
- ('modified (propertize "Modified" 'face 'git-status-face))
- ('unknown (propertize "Unknown " 'face 'git-unknown-face))
- ('added (propertize "Added " 'face 'git-status-face))
- ('deleted (propertize "Deleted " 'face 'git-status-face))
- ('unmerged (propertize "Unmerged" 'face 'git-unmerged-face))
- ('uptodate (propertize "Uptodate" 'face 'git-uptodate-face))
- ('ignored (propertize "Ignored " 'face 'git-ignored-face))
- (t "? ")))
-
-(defun git-file-type-as-string (old-perm new-perm)
- "Return a string describing the file type based on its permissions."
- (let* ((old-type (lsh (or old-perm 0) -9))
- (new-type (lsh (or new-perm 0) -9))
- (str (case new-type
- (64 ;; file
- (case old-type
- (64 nil)
- (80 " (type change symlink -> file)")
- (112 " (type change subproject -> file)")))
- (80 ;; symlink
- (case old-type
- (64 " (type change file -> symlink)")
- (112 " (type change subproject -> symlink)")
- (t " (symlink)")))
- (112 ;; subproject
- (case old-type
- (64 " (type change file -> subproject)")
- (80 " (type change symlink -> subproject)")
- (t " (subproject)")))
- (72 nil) ;; directory (internal, not a real git state)
- (0 ;; deleted or unknown
- (case old-type
- (80 " (symlink)")
- (112 " (subproject)")))
- (t (format " (unknown type %o)" new-type)))))
- (cond (str (propertize str 'face 'git-status-face))
- ((eq new-type 72) "/")
- (t ""))))
-
-(defun git-rename-as-string (info)
- "Return a string describing the copy or rename associated with INFO, or an empty string if none."
- (let ((state (git-fileinfo->rename-state info)))
- (if state
- (propertize
- (concat " ("
- (if (eq state 'copy) "copied from "
- (if (eq (git-fileinfo->state info) 'added) "renamed from "
- "renamed to "))
- (git-escape-file-name (git-fileinfo->orig-name info))
- ")") 'face 'git-status-face)
- "")))
-
-(defun git-permissions-as-string (old-perm new-perm)
- "Format a permission change as string."
- (propertize
- (if (or (not old-perm)
- (not new-perm)
- (eq 0 (logand ?\111 (logxor old-perm new-perm))))
- " "
- (if (eq 0 (logand ?\111 old-perm)) "+x" "-x"))
- 'face 'git-permission-face))
-
-(defun git-fileinfo-prettyprint (info)
- "Pretty-printer for the git-fileinfo structure."
- (let ((old-perm (git-fileinfo->old-perm info))
- (new-perm (git-fileinfo->new-perm info)))
- (insert (concat " " (if (git-fileinfo->marked info) (propertize "*" 'face 'git-mark-face) " ")
- " " (git-status-code-as-string (git-fileinfo->state info))
- " " (git-permissions-as-string old-perm new-perm)
- " " (git-escape-file-name (git-fileinfo->name info))
- (git-file-type-as-string old-perm new-perm)
- (git-rename-as-string info)))))
-
-(defun git-update-node-fileinfo (node info)
- "Update the fileinfo of the specified node. The names are assumed to match already."
- (let ((data (ewoc-data node)))
- (setf
- ;; preserve the marked flag
- (git-fileinfo->marked info) (git-fileinfo->marked data)
- (git-fileinfo->needs-update data) nil)
- (when (not (equal info data))
- (setf (git-fileinfo->needs-refresh info) t
- (ewoc-data node) info))))
-
-(defun git-insert-info-list (status infolist files)
- "Insert a sorted list of file infos in the status buffer, replacing existing ones if any."
- (let* ((info (pop infolist))
- (node (ewoc-nth status 0))
- (name (and info (git-fileinfo->name info)))
- remaining)
- (while info
- (let ((nodename (and node (git-fileinfo->name (ewoc-data node)))))
- (while (and files (string-lessp (car files) name))
- (push (pop files) remaining))
- (when (and files (string-equal (car files) name))
- (setq files (cdr files)))
- (cond ((not nodename)
- (setq node (ewoc-enter-last status info))
- (setq info (pop infolist))
- (setq name (and info (git-fileinfo->name info))))
- ((string-lessp nodename name)
- (setq node (ewoc-next status node)))
- ((string-equal nodename name)
- ;; preserve the marked flag
- (git-update-node-fileinfo node info)
- (setq info (pop infolist))
- (setq name (and info (git-fileinfo->name info))))
- (t
- (setq node (ewoc-enter-before status node info))
- (setq info (pop infolist))
- (setq name (and info (git-fileinfo->name info)))))))
- (nconc (nreverse remaining) files)))
-
-(defun git-run-diff-index (status files)
- "Run git-diff-index on FILES and parse the results into STATUS.
-Return the list of files that haven't been handled."
- (let (infolist)
- (with-temp-buffer
- (apply #'git-call-process t "diff-index" "-z" "-M" "HEAD" "--" files)
- (goto-char (point-min))
- (while (re-search-forward
- ":\\([0-7]\\{6\\}\\) \\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} [0-9a-f]\\{40\\} \\(\\([ADMUT]\\)\0\\([^\0]+\\)\\|\\([CR]\\)[0-9]*\0\\([^\0]+\\)\0\\([^\0]+\\)\\)\0"
- nil t 1)
- (let ((old-perm (string-to-number (match-string 1) 8))
- (new-perm (string-to-number (match-string 2) 8))
- (state (or (match-string 4) (match-string 6)))
- (name (or (match-string 5) (match-string 7)))
- (new-name (match-string 8)))
- (if new-name ; copy or rename
- (if (eq ?C (string-to-char state))
- (push (git-create-fileinfo 'added new-name old-perm new-perm 'copy name) infolist)
- (push (git-create-fileinfo 'deleted name 0 0 'rename new-name) infolist)
- (push (git-create-fileinfo 'added new-name old-perm new-perm 'rename name) infolist))
- (push (git-create-fileinfo (git-state-code state) name old-perm new-perm) infolist)))))
- (setq infolist (sort (nreverse infolist)
- (lambda (info1 info2)
- (string-lessp (git-fileinfo->name info1)
- (git-fileinfo->name info2)))))
- (git-insert-info-list status infolist files)))
-
-(defun git-find-status-file (status file)
- "Find a given file in the status ewoc and return its node."
- (let ((node (ewoc-nth status 0)))
- (while (and node (not (string= file (git-fileinfo->name (ewoc-data node)))))
- (setq node (ewoc-next status node)))
- node))
-
-(defun git-run-ls-files (status files default-state &rest options)
- "Run git-ls-files on FILES and parse the results into STATUS.
-Return the list of files that haven't been handled."
- (let (infolist)
- (with-temp-buffer
- (apply #'git-call-process t "ls-files" "-z" (append options (list "--") files))
- (goto-char (point-min))
- (while (re-search-forward "\\([^\0]*?\\)\\(/?\\)\0" nil t 1)
- (let ((name (match-string 1)))
- (push (git-create-fileinfo default-state name 0
- (if (string-equal "/" (match-string 2)) (lsh ?\110 9) 0))
- infolist))))
- (setq infolist (nreverse infolist)) ;; assume it is sorted already
- (git-insert-info-list status infolist files)))
-
-(defun git-run-ls-files-cached (status files default-state)
- "Run git-ls-files -c on FILES and parse the results into STATUS.
-Return the list of files that haven't been handled."
- (let (infolist)
- (with-temp-buffer
- (apply #'git-call-process t "ls-files" "-z" "-s" "-c" "--" files)
- (goto-char (point-min))
- (while (re-search-forward "\\([0-7]\\{6\\}\\) [0-9a-f]\\{40\\} 0\t\\([^\0]+\\)\0" nil t)
- (let* ((new-perm (string-to-number (match-string 1) 8))
- (old-perm (if (eq default-state 'added) 0 new-perm))
- (name (match-string 2)))
- (push (git-create-fileinfo default-state name old-perm new-perm) infolist))))
- (setq infolist (nreverse infolist)) ;; assume it is sorted already
- (git-insert-info-list status infolist files)))
-
-(defun git-run-ls-unmerged (status files)
- "Run git-ls-files -u on FILES and parse the results into STATUS."
- (with-temp-buffer
- (apply #'git-call-process t "ls-files" "-z" "-u" "--" files)
- (goto-char (point-min))
- (let (unmerged-files)
- (while (re-search-forward "[0-7]\\{6\\} [0-9a-f]\\{40\\} [123]\t\\([^\0]+\\)\0" nil t)
- (push (match-string 1) unmerged-files))
- (setq unmerged-files (nreverse unmerged-files)) ;; assume it is sorted already
- (git-set-filenames-state status unmerged-files 'unmerged))))
-
-(defun git-get-exclude-files ()
- "Get the list of exclude files to pass to git-ls-files."
- (let (files
- (config (git-config "core.excludesfile")))
- (when (file-readable-p ".git/info/exclude")
- (push ".git/info/exclude" files))
- (when (and config (file-readable-p config))
- (push config files))
- files))
-
-(defun git-run-ls-files-with-excludes (status files default-state &rest options)
- "Run git-ls-files on FILES with appropriate --exclude-from options."
- (let ((exclude-files (git-get-exclude-files)))
- (apply #'git-run-ls-files status files default-state "--directory" "--no-empty-directory"
- (concat "--exclude-per-directory=" git-per-dir-ignore-file)
- (append options (mapcar (lambda (f) (concat "--exclude-from=" f)) exclude-files)))))
-
-(defun git-update-status-files (&optional files mark-files)
- "Update the status of FILES from the index.
-The FILES list must be sorted."
- (unless git-status (error "Not in git-status buffer."))
- ;; set the needs-update flag on existing files
- (if files
- (git-status-filenames-map
- git-status (lambda (info) (setf (git-fileinfo->needs-update info) t)) files)
- (ewoc-map (lambda (info) (setf (git-fileinfo->needs-update info) t) nil) git-status)
- (git-call-process nil "update-index" "--refresh")
- (when git-show-uptodate
- (git-run-ls-files-cached git-status nil 'uptodate)))
- (let ((remaining-files
- (if (git-empty-db-p) ; we need some special handling for an empty db
- (git-run-ls-files-cached git-status files 'added)
- (git-run-diff-index git-status files))))
- (git-run-ls-unmerged git-status files)
- (when (or remaining-files (and git-show-unknown (not files)))
- (setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'unknown "-o")))
- (when (or remaining-files (and git-show-ignored (not files)))
- (setq remaining-files (git-run-ls-files-with-excludes git-status remaining-files 'ignored "-o" "-i")))
- (unless files
- (setq remaining-files (git-get-filenames (ewoc-collect git-status #'git-fileinfo->needs-update))))
- (when remaining-files
- (setq remaining-files (git-run-ls-files-cached git-status remaining-files 'uptodate)))
- (git-set-filenames-state git-status remaining-files nil)
- (when mark-files (git-mark-files git-status files))
- (git-refresh-files)
- (git-refresh-ewoc-hf git-status)))
-
-(defun git-mark-files (status files)
- "Mark all the specified FILES, and unmark the others."
- (let ((file (and files (pop files)))
- (node (ewoc-nth status 0)))
- (while node
- (let ((info (ewoc-data node)))
- (if (and file (string-equal (git-fileinfo->name info) file))
- (progn
- (unless (git-fileinfo->marked info)
- (setf (git-fileinfo->marked info) t)
- (setf (git-fileinfo->needs-refresh info) t))
- (setq file (pop files))
- (setq node (ewoc-next status node)))
- (when (git-fileinfo->marked info)
- (setf (git-fileinfo->marked info) nil)
- (setf (git-fileinfo->needs-refresh info) t))
- (if (and file (string-lessp file (git-fileinfo->name info)))
- (setq file (pop files))
- (setq node (ewoc-next status node))))))))
-
-(defun git-marked-files ()
- "Return a list of all marked files, or if none a list containing just the file at cursor position."
- (unless git-status (error "Not in git-status buffer."))
- (or (ewoc-collect git-status (lambda (info) (git-fileinfo->marked info)))
- (list (ewoc-data (ewoc-locate git-status)))))
-
-(defun git-marked-files-state (&rest states)
- "Return a sorted list of marked files that are in the specified states."
- (let ((files (git-marked-files))
- result)
- (dolist (info files)
- (when (memq (git-fileinfo->state info) states)
- (push info result)))
- (nreverse result)))
-
-(defun git-refresh-files ()
- "Refresh all files that need it and clear the needs-refresh flag."
- (unless git-status (error "Not in git-status buffer."))
- (ewoc-map
- (lambda (info)
- (let ((refresh (git-fileinfo->needs-refresh info)))
- (setf (git-fileinfo->needs-refresh info) nil)
- refresh))
- git-status)
- ; move back to goal column
- (when goal-column (move-to-column goal-column)))
-
-(defun git-refresh-ewoc-hf (status)
- "Refresh the ewoc header and footer."
- (let ((branch (git-symbolic-ref "HEAD"))
- (head (if (git-empty-db-p) "Nothing committed yet"
- (git-get-commit-description "HEAD")))
- (merge-heads (git-get-merge-heads)))
- (ewoc-set-hf status
- (format "Directory: %s\nBranch: %s\nHead: %s%s\n"
- default-directory
- (if branch
- (if (string-match "^refs/heads/" branch)
- (substring branch (match-end 0))
- branch)
- "none (detached HEAD)")
- head
- (if merge-heads
- (concat "\nMerging: "
- (mapconcat (lambda (str) (git-get-commit-description str)) merge-heads "\n "))
- ""))
- (if (ewoc-nth status 0) "" " No changes."))))
-
-(defun git-get-filenames (files)
- (mapcar (lambda (info) (git-fileinfo->name info)) files))
-
-(defun git-update-index (index-file files)
- "Run git-update-index on a list of files."
- (let ((process-environment (append (and index-file (list (concat "GIT_INDEX_FILE=" index-file)))
- process-environment))
- added deleted modified)
- (dolist (info files)
- (case (git-fileinfo->state info)
- ('added (push info added))
- ('deleted (push info deleted))
- ('modified (push info modified))))
- (and
- (or (not added) (apply #'git-call-process-display-error "update-index" "--add" "--" (git-get-filenames added)))
- (or (not deleted) (apply #'git-call-process-display-error "update-index" "--remove" "--" (git-get-filenames deleted)))
- (or (not modified) (apply #'git-call-process-display-error "update-index" "--" (git-get-filenames modified))))))
-
-(defun git-run-pre-commit-hook ()
- "Run the pre-commit hook if any."
- (unless git-status (error "Not in git-status buffer."))
- (let ((files (git-marked-files-state 'added 'deleted 'modified)))
- (or (not files)
- (not (file-executable-p ".git/hooks/pre-commit"))
- (let ((index-file (make-temp-file "gitidx")))
- (unwind-protect
- (let ((head-tree (unless (git-empty-db-p) (git-rev-parse "HEAD^{tree}"))))
- (git-read-tree head-tree index-file)
- (git-update-index index-file files)
- (git-run-hook "pre-commit" `(("GIT_INDEX_FILE" . ,index-file))))
- (delete-file index-file))))))
-
-(defun git-do-commit ()
- "Perform the actual commit using the current buffer as log message."
- (interactive)
- (let ((buffer (current-buffer))
- (index-file (make-temp-file "gitidx")))
- (with-current-buffer log-edit-parent-buffer
- (if (git-marked-files-state 'unmerged)
- (message "You cannot commit unmerged files, resolve them first.")
- (unwind-protect
- (let ((files (git-marked-files-state 'added 'deleted 'modified))
- head tree head-tree)
- (unless (git-empty-db-p)
- (setq head (git-rev-parse "HEAD")
- head-tree (git-rev-parse "HEAD^{tree}")))
- (message "Running git commit...")
- (when
- (and
- (git-read-tree head-tree index-file)
- (git-update-index nil files) ;update both the default index
- (git-update-index index-file files) ;and the temporary one
- (setq tree (git-write-tree index-file)))
- (if (or (not (string-equal tree head-tree))
- (yes-or-no-p "The tree was not modified, do you really want to perform an empty commit? "))
- (let ((commit (git-commit-tree buffer tree head)))
- (when commit
- (condition-case nil (delete-file ".git/MERGE_HEAD") (error nil))
- (condition-case nil (delete-file ".git/MERGE_MSG") (error nil))
- (with-current-buffer buffer (erase-buffer))
- (git-update-status-files (git-get-filenames files))
- (git-call-process nil "rerere")
- (git-call-process nil "gc" "--auto")
- (message "Committed %s." commit)
- (git-run-hook "post-commit" nil)))
- (message "Commit aborted."))))
- (delete-file index-file))))))
-
-
-;;;; Interactive functions
-;;;; ------------------------------------------------------------
-
-(defun git-mark-file ()
- "Mark the file that the cursor is on and move to the next one."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (let* ((pos (ewoc-locate git-status))
- (info (ewoc-data pos)))
- (setf (git-fileinfo->marked info) t)
- (ewoc-invalidate git-status pos)
- (ewoc-goto-next git-status 1)))
-
-(defun git-unmark-file ()
- "Unmark the file that the cursor is on and move to the next one."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (let* ((pos (ewoc-locate git-status))
- (info (ewoc-data pos)))
- (setf (git-fileinfo->marked info) nil)
- (ewoc-invalidate git-status pos)
- (ewoc-goto-next git-status 1)))
-
-(defun git-unmark-file-up ()
- "Unmark the file that the cursor is on and move to the previous one."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (let* ((pos (ewoc-locate git-status))
- (info (ewoc-data pos)))
- (setf (git-fileinfo->marked info) nil)
- (ewoc-invalidate git-status pos)
- (ewoc-goto-prev git-status 1)))
-
-(defun git-mark-all ()
- "Mark all files."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (ewoc-map (lambda (info) (unless (git-fileinfo->marked info)
- (setf (git-fileinfo->marked info) t))) git-status)
- ; move back to goal column after invalidate
- (when goal-column (move-to-column goal-column)))
-
-(defun git-unmark-all ()
- "Unmark all files."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (ewoc-map (lambda (info) (when (git-fileinfo->marked info)
- (setf (git-fileinfo->marked info) nil)
- t)) git-status)
- ; move back to goal column after invalidate
- (when goal-column (move-to-column goal-column)))
-
-(defun git-toggle-all-marks ()
- "Toggle all file marks."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (ewoc-map (lambda (info) (setf (git-fileinfo->marked info) (not (git-fileinfo->marked info))) t) git-status)
- ; move back to goal column after invalidate
- (when goal-column (move-to-column goal-column)))
-
-(defun git-next-file (&optional n)
- "Move the selection down N files."
- (interactive "p")
- (unless git-status (error "Not in git-status buffer."))
- (ewoc-goto-next git-status n))
-
-(defun git-prev-file (&optional n)
- "Move the selection up N files."
- (interactive "p")
- (unless git-status (error "Not in git-status buffer."))
- (ewoc-goto-prev git-status n))
-
-(defun git-next-unmerged-file (&optional n)
- "Move the selection down N unmerged files."
- (interactive "p")
- (unless git-status (error "Not in git-status buffer."))
- (let* ((last (ewoc-locate git-status))
- (node (ewoc-next git-status last)))
- (while (and node (> n 0))
- (when (eq 'unmerged (git-fileinfo->state (ewoc-data node)))
- (setq n (1- n))
- (setq last node))
- (setq node (ewoc-next git-status node)))
- (ewoc-goto-node git-status last)))
-
-(defun git-prev-unmerged-file (&optional n)
- "Move the selection up N unmerged files."
- (interactive "p")
- (unless git-status (error "Not in git-status buffer."))
- (let* ((last (ewoc-locate git-status))
- (node (ewoc-prev git-status last)))
- (while (and node (> n 0))
- (when (eq 'unmerged (git-fileinfo->state (ewoc-data node)))
- (setq n (1- n))
- (setq last node))
- (setq node (ewoc-prev git-status node)))
- (ewoc-goto-node git-status last)))
-
-(defun git-insert-file (file)
- "Insert file(s) into the git-status buffer."
- (interactive "fInsert file: ")
- (git-update-status-files (list (file-relative-name file))))
-
-(defun git-add-file ()
- "Add marked file(s) to the index cache."
- (interactive)
- (let ((files (git-get-filenames (git-marked-files-state 'unknown 'ignored 'unmerged))))
- ;; FIXME: add support for directories
- (unless files
- (push (file-relative-name (read-file-name "File to add: " nil nil t)) files))
- (when (apply 'git-call-process-display-error "update-index" "--add" "--" files)
- (git-update-status-files files)
- (git-success-message "Added" files))))
-
-(defun git-ignore-file ()
- "Add marked file(s) to the ignore list."
- (interactive)
- (let ((files (git-get-filenames (git-marked-files-state 'unknown))))
- (unless files
- (push (file-relative-name (read-file-name "File to ignore: " nil nil t)) files))
- (dolist (f files) (git-append-to-ignore f))
- (git-update-status-files files)
- (git-success-message "Ignored" files)))
-
-(defun git-remove-file ()
- "Remove the marked file(s)."
- (interactive)
- (let ((files (git-get-filenames (git-marked-files-state 'added 'modified 'unknown 'uptodate 'ignored))))
- (unless files
- (push (file-relative-name (read-file-name "File to remove: " nil nil t)) files))
- (if (yes-or-no-p
- (if (cdr files)
- (format "Remove %d files? " (length files))
- (format "Remove %s? " (car files))))
- (progn
- (dolist (name files)
- (ignore-errors
- (if (file-directory-p name)
- (delete-directory name)
- (delete-file name))))
- (when (apply 'git-call-process-display-error "update-index" "--remove" "--" files)
- (git-update-status-files files)
- (git-success-message "Removed" files)))
- (message "Aborting"))))
-
-(defun git-revert-file ()
- "Revert changes to the marked file(s)."
- (interactive)
- (let ((files (git-marked-files-state 'added 'deleted 'modified 'unmerged))
- added modified)
- (when (and files
- (yes-or-no-p
- (if (cdr files)
- (format "Revert %d files? " (length files))
- (format "Revert %s? " (git-fileinfo->name (car files))))))
- (dolist (info files)
- (case (git-fileinfo->state info)
- ('added (push (git-fileinfo->name info) added))
- ('deleted (push (git-fileinfo->name info) modified))
- ('unmerged (push (git-fileinfo->name info) modified))
- ('modified (push (git-fileinfo->name info) modified))))
- ;; check if a buffer contains one of the files and isn't saved
- (dolist (file modified)
- (let ((buffer (get-file-buffer file)))
- (when (and buffer (buffer-modified-p buffer))
- (error "Buffer %s is modified. Please kill or save modified buffers before reverting." (buffer-name buffer)))))
- (let ((ok (and
- (or (not added)
- (apply 'git-call-process-display-error "update-index" "--force-remove" "--" added))
- (or (not modified)
- (apply 'git-call-process-display-error "checkout" "HEAD" modified))))
- (names (git-get-filenames files)))
- (git-update-status-files names)
- (when ok
- (dolist (file modified)
- (let ((buffer (get-file-buffer file)))
- (when buffer (with-current-buffer buffer (revert-buffer t t t)))))
- (git-success-message "Reverted" names))))))
-
-(defun git-remove-handled ()
- "Remove handled files from the status list."
- (interactive)
- (ewoc-filter git-status
- (lambda (info)
- (case (git-fileinfo->state info)
- ('ignored git-show-ignored)
- ('uptodate git-show-uptodate)
- ('unknown git-show-unknown)
- (t t))))
- (unless (ewoc-nth git-status 0) ; refresh header if list is empty
- (git-refresh-ewoc-hf git-status)))
-
-(defun git-toggle-show-uptodate ()
- "Toogle the option for showing up-to-date files."
- (interactive)
- (if (setq git-show-uptodate (not git-show-uptodate))
- (git-refresh-status)
- (git-remove-handled)))
-
-(defun git-toggle-show-ignored ()
- "Toogle the option for showing ignored files."
- (interactive)
- (if (setq git-show-ignored (not git-show-ignored))
- (progn
- (message "Inserting ignored files...")
- (git-run-ls-files-with-excludes git-status nil 'ignored "-o" "-i")
- (git-refresh-files)
- (git-refresh-ewoc-hf git-status)
- (message "Inserting ignored files...done"))
- (git-remove-handled)))
-
-(defun git-toggle-show-unknown ()
- "Toogle the option for showing unknown files."
- (interactive)
- (if (setq git-show-unknown (not git-show-unknown))
- (progn
- (message "Inserting unknown files...")
- (git-run-ls-files-with-excludes git-status nil 'unknown "-o")
- (git-refresh-files)
- (git-refresh-ewoc-hf git-status)
- (message "Inserting unknown files...done"))
- (git-remove-handled)))
-
-(defun git-expand-directory (info)
- "Expand the directory represented by INFO to list its files."
- (when (eq (lsh (git-fileinfo->new-perm info) -9) ?\110)
- (let ((dir (git-fileinfo->name info)))
- (git-set-filenames-state git-status (list dir) nil)
- (git-run-ls-files-with-excludes git-status (list (concat dir "/")) 'unknown "-o")
- (git-refresh-files)
- (git-refresh-ewoc-hf git-status)
- t)))
-
-(defun git-setup-diff-buffer (buffer)
- "Setup a buffer for displaying a diff."
- (let ((dir default-directory))
- (with-current-buffer buffer
- (diff-mode)
- (goto-char (point-min))
- (setq default-directory dir)
- (setq buffer-read-only t)))
- (display-buffer buffer)
- ; shrink window only if it displays the status buffer
- (when (eq (window-buffer) (current-buffer))
- (shrink-window-if-larger-than-buffer)))
-
-(defun git-diff-file ()
- "Diff the marked file(s) against HEAD."
- (interactive)
- (let ((files (git-marked-files)))
- (git-setup-diff-buffer
- (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M" "HEAD" "--" (git-get-filenames files)))))
-
-(defun git-diff-file-merge-head (arg)
- "Diff the marked file(s) against the first merge head (or the nth one with a numeric prefix)."
- (interactive "p")
- (let ((files (git-marked-files))
- (merge-heads (git-get-merge-heads)))
- (unless merge-heads (error "No merge in progress"))
- (git-setup-diff-buffer
- (apply #'git-run-command-buffer "*git-diff*" "diff-index" "-p" "-M"
- (or (nth (1- arg) merge-heads) "HEAD") "--" (git-get-filenames files)))))
-
-(defun git-diff-unmerged-file (stage)
- "Diff the marked unmerged file(s) against the specified stage."
- (let ((files (git-marked-files)))
- (git-setup-diff-buffer
- (apply #'git-run-command-buffer "*git-diff*" "diff-files" "-p" stage "--" (git-get-filenames files)))))
-
-(defun git-diff-file-base ()
- "Diff the marked unmerged file(s) against the common base file."
- (interactive)
- (git-diff-unmerged-file "-1"))
-
-(defun git-diff-file-mine ()
- "Diff the marked unmerged file(s) against my pre-merge version."
- (interactive)
- (git-diff-unmerged-file "-2"))
-
-(defun git-diff-file-other ()
- "Diff the marked unmerged file(s) against the other's pre-merge version."
- (interactive)
- (git-diff-unmerged-file "-3"))
-
-(defun git-diff-file-combined ()
- "Do a combined diff of the marked unmerged file(s)."
- (interactive)
- (git-diff-unmerged-file "-c"))
-
-(defun git-diff-file-idiff ()
- "Perform an interactive diff on the current file."
- (interactive)
- (let ((files (git-marked-files-state 'added 'deleted 'modified)))
- (unless (eq 1 (length files))
- (error "Cannot perform an interactive diff on multiple files."))
- (let* ((filename (car (git-get-filenames files)))
- (buff1 (find-file-noselect filename))
- (buff2 (git-run-command-buffer (concat filename ".~HEAD~") "cat-file" "blob" (concat "HEAD:" filename))))
- (ediff-buffers buff1 buff2))))
-
-(defun git-log-file ()
- "Display a log of changes to the marked file(s)."
- (interactive)
- (let* ((files (git-marked-files))
- (coding-system-for-read git-commits-coding-system)
- (buffer (apply #'git-run-command-buffer "*git-log*" "rev-list" "--pretty" "HEAD" "--" (git-get-filenames files))))
- (with-current-buffer buffer
- ; (git-log-mode) FIXME: implement log mode
- (goto-char (point-min))
- (setq buffer-read-only t))
- (display-buffer buffer)))
-
-(defun git-log-edit-files ()
- "Return a list of marked files for use in the log-edit buffer."
- (with-current-buffer log-edit-parent-buffer
- (git-get-filenames (git-marked-files-state 'added 'deleted 'modified))))
-
-(defun git-log-edit-diff ()
- "Run a diff of the current files being committed from a log-edit buffer."
- (with-current-buffer log-edit-parent-buffer
- (git-diff-file)))
-
-(defun git-append-sign-off (name email)
- "Append a Signed-off-by entry to the current buffer, avoiding duplicates."
- (let ((sign-off (format "Signed-off-by: %s <%s>" name email))
- (case-fold-search t))
- (goto-char (point-min))
- (unless (re-search-forward (concat "^" (regexp-quote sign-off)) nil t)
- (goto-char (point-min))
- (unless (re-search-forward "^Signed-off-by: " nil t)
- (setq sign-off (concat "\n" sign-off)))
- (goto-char (point-max))
- (insert sign-off "\n"))))
-
-(defun git-setup-log-buffer (buffer &optional merge-heads author-name author-email subject date msg)
- "Setup the log buffer for a commit."
- (unless git-status (error "Not in git-status buffer."))
- (let ((dir default-directory)
- (committer-name (git-get-committer-name))
- (committer-email (git-get-committer-email))
- (sign-off git-append-signed-off-by))
- (with-current-buffer buffer
- (cd dir)
- (erase-buffer)
- (insert
- (propertize
- (format "Author: %s <%s>\n%s%s"
- (or author-name committer-name)
- (or author-email committer-email)
- (if date (format "Date: %s\n" date) "")
- (if merge-heads
- (format "Merge: %s\n"
- (mapconcat 'identity merge-heads " "))
- ""))
- 'face 'git-header-face)
- (propertize git-log-msg-separator 'face 'git-separator-face)
- "\n")
- (when subject (insert subject "\n\n"))
- (cond (msg (insert msg "\n"))
- ((file-readable-p ".git/rebase-apply/msg")
- (insert-file-contents ".git/rebase-apply/msg"))
- ((file-readable-p ".git/MERGE_MSG")
- (insert-file-contents ".git/MERGE_MSG")))
- ; delete empty lines at end
- (goto-char (point-min))
- (when (re-search-forward "\n+\\'" nil t)
- (replace-match "\n" t t))
- (when sign-off (git-append-sign-off committer-name committer-email)))
- buffer))
-
-(define-derived-mode git-log-edit-mode log-edit-mode "Git-Log-Edit"
- "Major mode for editing git log messages.
-
-Set up git-specific `font-lock-keywords' for `log-edit-mode'."
- (set (make-local-variable 'font-lock-defaults)
- '(git-log-edit-font-lock-keywords t t)))
-
-(defun git-commit-file ()
- "Commit the marked file(s), asking for a commit message."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (when (git-run-pre-commit-hook)
- (let ((buffer (get-buffer-create "*git-commit*"))
- (coding-system (git-get-commits-coding-system))
- author-name author-email subject date)
- (when (eq 0 (buffer-size buffer))
- (when (file-readable-p ".git/rebase-apply/info")
- (with-temp-buffer
- (insert-file-contents ".git/rebase-apply/info")
- (goto-char (point-min))
- (when (re-search-forward "^Author: \\(.*\\)\nEmail: \\(.*\\)$" nil t)
- (setq author-name (match-string 1))
- (setq author-email (match-string 2)))
- (goto-char (point-min))
- (when (re-search-forward "^Subject: \\(.*\\)$" nil t)
- (setq subject (match-string 1)))
- (goto-char (point-min))
- (when (re-search-forward "^Date: \\(.*\\)$" nil t)
- (setq date (match-string 1)))))
- (git-setup-log-buffer buffer (git-get-merge-heads) author-name author-email subject date))
- (if (boundp 'log-edit-diff-function)
- (log-edit 'git-do-commit nil '((log-edit-listfun . git-log-edit-files)
- (log-edit-diff-function . git-log-edit-diff)) buffer 'git-log-edit-mode)
- (log-edit 'git-do-commit nil 'git-log-edit-files buffer
- 'git-log-edit-mode))
- (setq paragraph-separate (concat (regexp-quote git-log-msg-separator) "$\\|Author: \\|Date: \\|Merge: \\|Signed-off-by: \\|\f\\|[ ]*$"))
- (setq buffer-file-coding-system coding-system)
- (re-search-forward (regexp-quote (concat git-log-msg-separator "\n")) nil t))))
-
-(defun git-setup-commit-buffer (commit)
- "Setup the commit buffer with the contents of COMMIT."
- (let (parents author-name author-email subject date msg)
- (with-temp-buffer
- (let ((coding-system (git-get-logoutput-coding-system)))
- (git-call-process t "log" "-1" "--pretty=medium" "--abbrev=40" commit)
- (goto-char (point-min))
- (when (re-search-forward "^Merge: *\\(.*\\)$" nil t)
- (setq parents (cdr (split-string (match-string 1) " +"))))
- (when (re-search-forward "^Author: *\\(.*\\) <\\(.*\\)>$" nil t)
- (setq author-name (match-string 1))
- (setq author-email (match-string 2)))
- (when (re-search-forward "^Date: *\\(.*\\)$" nil t)
- (setq date (match-string 1)))
- (while (re-search-forward "^ \\(.*\\)$" nil t)
- (push (match-string 1) msg))
- (setq msg (nreverse msg))
- (setq subject (pop msg))
- (while (and msg (zerop (length (car msg))) (pop msg)))))
- (git-setup-log-buffer (get-buffer-create "*git-commit*")
- parents author-name author-email subject date
- (mapconcat #'identity msg "\n"))))
-
-(defun git-get-commit-files (commit)
- "Retrieve a sorted list of files modified by COMMIT."
- (let (files)
- (with-temp-buffer
- (git-call-process t "diff-tree" "-m" "-r" "-z" "--name-only" "--no-commit-id" "--root" commit)
- (goto-char (point-min))
- (while (re-search-forward "\\([^\0]*\\)\0" nil t 1)
- (push (match-string 1) files)))
- (sort files #'string-lessp)))
-
-(defun git-read-commit-name (prompt &optional default)
- "Ask for a commit name, with completion for local branch, remote branch and tag."
- (completing-read prompt
- (list* "HEAD" "ORIG_HEAD" "FETCH_HEAD" (mapcar #'car (git-for-each-ref)))
- nil nil nil nil default))
-
-(defun git-checkout (branch &optional merge)
- "Checkout a branch, tag, or any commit.
-Use a prefix arg if git should merge while checking out."
- (interactive
- (list (git-read-commit-name "Checkout: ")
- current-prefix-arg))
- (unless git-status (error "Not in git-status buffer."))
- (let ((args (list branch "--")))
- (when merge (push "-m" args))
- (when (apply #'git-call-process-display-error "checkout" args)
- (git-update-status-files))))
-
-(defun git-branch (branch)
- "Create a branch from the current HEAD and switch to it."
- (interactive (list (git-read-commit-name "Branch: ")))
- (unless git-status (error "Not in git-status buffer."))
- (if (git-rev-parse (concat "refs/heads/" branch))
- (if (yes-or-no-p (format "Branch %s already exists, replace it? " branch))
- (and (git-call-process-display-error "branch" "-f" branch)
- (git-call-process-display-error "checkout" branch))
- (message "Canceled."))
- (git-call-process-display-error "checkout" "-b" branch))
- (git-refresh-ewoc-hf git-status))
-
-(defun git-amend-commit ()
- "Undo the last commit on HEAD, and set things up to commit an
-amended version of it."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (when (git-empty-db-p) (error "No commit to amend."))
- (let* ((commit (git-rev-parse "HEAD"))
- (files (git-get-commit-files commit)))
- (when (if (git-rev-parse "HEAD^")
- (git-call-process-display-error "reset" "--soft" "HEAD^")
- (and (git-update-ref "ORIG_HEAD" commit)
- (git-update-ref "HEAD" nil commit)))
- (git-update-status-files files t)
- (git-setup-commit-buffer commit)
- (git-commit-file))))
-
-(defun git-cherry-pick-commit (arg)
- "Cherry-pick a commit."
- (interactive (list (git-read-commit-name "Cherry-pick commit: ")))
- (unless git-status (error "Not in git-status buffer."))
- (let ((commit (git-rev-parse (concat arg "^0"))))
- (unless commit (error "Not a valid commit '%s'." arg))
- (when (git-rev-parse (concat commit "^2"))
- (error "Cannot cherry-pick a merge commit."))
- (let ((files (git-get-commit-files commit))
- (ok (git-call-process-display-error "cherry-pick" "-n" commit)))
- (git-update-status-files files ok)
- (with-current-buffer (git-setup-commit-buffer commit)
- (goto-char (point-min))
- (if (re-search-forward "^\n*Signed-off-by:" nil t 1)
- (goto-char (match-beginning 0))
- (goto-char (point-max)))
- (insert "(cherry picked from commit " commit ")\n"))
- (when ok (git-commit-file)))))
-
-(defun git-revert-commit (arg)
- "Revert a commit."
- (interactive (list (git-read-commit-name "Revert commit: ")))
- (unless git-status (error "Not in git-status buffer."))
- (let ((commit (git-rev-parse (concat arg "^0"))))
- (unless commit (error "Not a valid commit '%s'." arg))
- (when (git-rev-parse (concat commit "^2"))
- (error "Cannot revert a merge commit."))
- (let ((files (git-get-commit-files commit))
- (subject (git-get-commit-description commit))
- (ok (git-call-process-display-error "revert" "-n" commit)))
- (git-update-status-files files ok)
- (when (string-match "^[0-9a-f]+ - \\(.*\\)$" subject)
- (setq subject (match-string 1 subject)))
- (git-setup-log-buffer (get-buffer-create "*git-commit*")
- (git-get-merge-heads) nil nil (format "Revert \"%s\"" subject) nil
- (format "This reverts commit %s.\n" commit))
- (when ok (git-commit-file)))))
-
-(defun git-find-file ()
- "Visit the current file in its own buffer."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (let ((info (ewoc-data (ewoc-locate git-status))))
- (unless (git-expand-directory info)
- (find-file (git-fileinfo->name info))
- (when (eq 'unmerged (git-fileinfo->state info))
- (smerge-mode 1)))))
-
-(defun git-find-file-other-window ()
- "Visit the current file in its own buffer in another window."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (let ((info (ewoc-data (ewoc-locate git-status))))
- (find-file-other-window (git-fileinfo->name info))
- (when (eq 'unmerged (git-fileinfo->state info))
- (smerge-mode))))
-
-(defun git-find-file-imerge ()
- "Visit the current file in interactive merge mode."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (let ((info (ewoc-data (ewoc-locate git-status))))
- (find-file (git-fileinfo->name info))
- (smerge-ediff)))
-
-(defun git-view-file ()
- "View the current file in its own buffer."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (let ((info (ewoc-data (ewoc-locate git-status))))
- (view-file (git-fileinfo->name info))))
-
-(defun git-refresh-status ()
- "Refresh the git status buffer."
- (interactive)
- (unless git-status (error "Not in git-status buffer."))
- (message "Refreshing git status...")
- (git-update-status-files)
- (message "Refreshing git status...done"))
-
-(defun git-status-quit ()
- "Quit git-status mode."
- (interactive)
- (bury-buffer))
-
-;;;; Major Mode
-;;;; ------------------------------------------------------------
-
-(defvar git-status-mode-hook nil
- "Run after `git-status-mode' is setup.")
-
-(defvar git-status-mode-map nil
- "Keymap for git major mode.")
-
-(defvar git-status nil
- "List of all files managed by the git-status mode.")
-
-(unless git-status-mode-map
- (let ((map (make-keymap))
- (commit-map (make-sparse-keymap))
- (diff-map (make-sparse-keymap))
- (toggle-map (make-sparse-keymap)))
- (suppress-keymap map)
- (define-key map "?" 'git-help)
- (define-key map "h" 'git-help)
- (define-key map " " 'git-next-file)
- (define-key map "a" 'git-add-file)
- (define-key map "c" 'git-commit-file)
- (define-key map "\C-c" commit-map)
- (define-key map "d" diff-map)
- (define-key map "=" 'git-diff-file)
- (define-key map "f" 'git-find-file)
- (define-key map "\r" 'git-find-file)
- (define-key map "g" 'git-refresh-status)
- (define-key map "i" 'git-ignore-file)
- (define-key map "I" 'git-insert-file)
- (define-key map "l" 'git-log-file)
- (define-key map "m" 'git-mark-file)
- (define-key map "M" 'git-mark-all)
- (define-key map "n" 'git-next-file)
- (define-key map "N" 'git-next-unmerged-file)
- (define-key map "o" 'git-find-file-other-window)
- (define-key map "p" 'git-prev-file)
- (define-key map "P" 'git-prev-unmerged-file)
- (define-key map "q" 'git-status-quit)
- (define-key map "r" 'git-remove-file)
- (define-key map "t" toggle-map)
- (define-key map "T" 'git-toggle-all-marks)
- (define-key map "u" 'git-unmark-file)
- (define-key map "U" 'git-revert-file)
- (define-key map "v" 'git-view-file)
- (define-key map "x" 'git-remove-handled)
- (define-key map "\C-?" 'git-unmark-file-up)
- (define-key map "\M-\C-?" 'git-unmark-all)
- ; the commit submap
- (define-key commit-map "\C-a" 'git-amend-commit)
- (define-key commit-map "\C-b" 'git-branch)
- (define-key commit-map "\C-o" 'git-checkout)
- (define-key commit-map "\C-p" 'git-cherry-pick-commit)
- (define-key commit-map "\C-v" 'git-revert-commit)
- ; the diff submap
- (define-key diff-map "b" 'git-diff-file-base)
- (define-key diff-map "c" 'git-diff-file-combined)
- (define-key diff-map "=" 'git-diff-file)
- (define-key diff-map "e" 'git-diff-file-idiff)
- (define-key diff-map "E" 'git-find-file-imerge)
- (define-key diff-map "h" 'git-diff-file-merge-head)
- (define-key diff-map "m" 'git-diff-file-mine)
- (define-key diff-map "o" 'git-diff-file-other)
- ; the toggle submap
- (define-key toggle-map "u" 'git-toggle-show-uptodate)
- (define-key toggle-map "i" 'git-toggle-show-ignored)
- (define-key toggle-map "k" 'git-toggle-show-unknown)
- (define-key toggle-map "m" 'git-toggle-all-marks)
- (setq git-status-mode-map map))
- (easy-menu-define git-menu git-status-mode-map
- "Git Menu"
- `("Git"
- ["Refresh" git-refresh-status t]
- ["Commit" git-commit-file t]
- ["Checkout..." git-checkout t]
- ["New Branch..." git-branch t]
- ["Cherry-pick Commit..." git-cherry-pick-commit t]
- ["Revert Commit..." git-revert-commit t]
- ("Merge"
- ["Next Unmerged File" git-next-unmerged-file t]
- ["Prev Unmerged File" git-prev-unmerged-file t]
- ["Interactive Merge File" git-find-file-imerge t]
- ["Diff Against Common Base File" git-diff-file-base t]
- ["Diff Combined" git-diff-file-combined t]
- ["Diff Against Merge Head" git-diff-file-merge-head t]
- ["Diff Against Mine" git-diff-file-mine t]
- ["Diff Against Other" git-diff-file-other t])
- "--------"
- ["Add File" git-add-file t]
- ["Revert File" git-revert-file t]
- ["Ignore File" git-ignore-file t]
- ["Remove File" git-remove-file t]
- ["Insert File" git-insert-file t]
- "--------"
- ["Find File" git-find-file t]
- ["View File" git-view-file t]
- ["Diff File" git-diff-file t]
- ["Interactive Diff File" git-diff-file-idiff t]
- ["Log" git-log-file t]
- "--------"
- ["Mark" git-mark-file t]
- ["Mark All" git-mark-all t]
- ["Unmark" git-unmark-file t]
- ["Unmark All" git-unmark-all t]
- ["Toggle All Marks" git-toggle-all-marks t]
- ["Hide Handled Files" git-remove-handled t]
- "--------"
- ["Show Uptodate Files" git-toggle-show-uptodate :style toggle :selected git-show-uptodate]
- ["Show Ignored Files" git-toggle-show-ignored :style toggle :selected git-show-ignored]
- ["Show Unknown Files" git-toggle-show-unknown :style toggle :selected git-show-unknown]
- "--------"
- ["Quit" git-status-quit t])))
-
-
-;; git mode should only run in the *git status* buffer
-(put 'git-status-mode 'mode-class 'special)
-
-(defun git-status-mode ()
- "Major mode for interacting with Git.
-Commands:
-\\{git-status-mode-map}"
- (kill-all-local-variables)
- (buffer-disable-undo)
- (setq mode-name "git status"
- major-mode 'git-status-mode
- goal-column 17
- buffer-read-only t)
- (use-local-map git-status-mode-map)
- (let ((buffer-read-only nil))
- (erase-buffer)
- (let ((status (ewoc-create 'git-fileinfo-prettyprint "" "")))
- (set (make-local-variable 'git-status) status))
- (set (make-local-variable 'list-buffers-directory) default-directory)
- (make-local-variable 'git-show-uptodate)
- (make-local-variable 'git-show-ignored)
- (make-local-variable 'git-show-unknown)
- (run-hooks 'git-status-mode-hook)))
-
-(defun git-find-status-buffer (dir)
- "Find the git status buffer handling a specified directory."
- (let ((list (buffer-list))
- (fulldir (expand-file-name dir))
- found)
- (while (and list (not found))
- (let ((buffer (car list)))
- (with-current-buffer buffer
- (when (and list-buffers-directory
- (string-equal fulldir (expand-file-name list-buffers-directory))
- (eq major-mode 'git-status-mode))
- (setq found buffer))))
- (setq list (cdr list)))
- found))
-
-(defun git-status (dir)
- "Entry point into git-status mode."
- (interactive "DSelect directory: ")
- (setq dir (git-get-top-dir dir))
- (if (file-exists-p (concat (file-name-as-directory dir) ".git"))
- (let ((buffer (or (and git-reuse-status-buffer (git-find-status-buffer dir))
- (create-file-buffer (expand-file-name "*git-status*" dir)))))
- (switch-to-buffer buffer)
- (cd dir)
- (git-status-mode)
- (git-refresh-status)
- (goto-char (point-min))
- (add-hook 'after-save-hook 'git-update-saved-file))
- (message "%s is not a git working tree." dir)))
-
-(defun git-update-saved-file ()
- "Update the corresponding git-status buffer when a file is saved.
-Meant to be used in `after-save-hook'."
- (let* ((file (expand-file-name buffer-file-name))
- (dir (condition-case nil (git-get-top-dir (file-name-directory file)) (error nil)))
- (buffer (and dir (git-find-status-buffer dir))))
- (when buffer
- (with-current-buffer buffer
- (let ((filename (file-relative-name file dir)))
- ; skip files located inside the .git directory
- (unless (string-match "^\\.git/" filename)
- (git-call-process nil "add" "--refresh" "--" filename)
- (git-update-status-files (list filename))))))))
-
-(defun git-help ()
- "Display help for Git mode."
- (interactive)
- (describe-function 'git-status-mode))
-
-(provide 'git)
-;;; git.el ends here
+(error "git.el no longer ships with git. It's recommended to
+replace its use with Magit, or simply delete references to git.el
+in your initialization file(s). See contrib/emacs/README in git's
+sources (https://github.com/git/git/blob/master/contrib/emacs/README)
+for suggested alternatives and for why this happened. Emacs's own
+VC mode and Magit are viable alternatives.")
diff --git a/contrib/mw-to-git/Makefile b/contrib/mw-to-git/Makefile
index a4b6f7a..4e60351 100644
--- a/contrib/mw-to-git/Makefile
+++ b/contrib/mw-to-git/Makefile
@@ -21,8 +21,9 @@ HERE=contrib/mw-to-git/
INSTALL = install
SCRIPT_PERL_FULL=$(patsubst %,$(HERE)/%,$(SCRIPT_PERL))
-INSTLIBDIR=$(shell $(MAKE) -C $(GIT_ROOT_DIR)/perl \
- -s --no-print-directory instlibdir)
+INSTLIBDIR=$(shell $(MAKE) -C $(GIT_ROOT_DIR)/ \
+ -s --no-print-directory prefix=$(prefix) \
+ perllibdir=$(perllibdir) perllibdir)
DESTDIR_SQ = $(subst ','\'',$(DESTDIR))
INSTLIBDIR_SQ = $(subst ','\'',$(INSTLIBDIR))
diff --git a/contrib/update-unicode/README b/contrib/update-unicode/README
index b9e2fc8..151a197 100644
--- a/contrib/update-unicode/README
+++ b/contrib/update-unicode/README
@@ -1,10 +1,10 @@
TL;DR: Run update_unicode.sh after the publication of a new Unicode
-standard and commit the resulting unicode_widths.h file.
+standard and commit the resulting unicode-widths.h file.
The long version
================
-The Git source code ships the file unicode_widths.h which contains
+The Git source code ships the file unicode-widths.h which contains
tables of zero and double width Unicode code points, respectively.
These tables are generated using update_unicode.sh in this directory.
update_unicode.sh itself uses a third-party tool, uniset, to query two
@@ -16,5 +16,5 @@ This requires a current-ish version of autoconf (2.69 works per December
On each run, update_unicode.sh checks whether more recent Unicode data
files are available from the Unicode consortium, and rebuilds the header
-unicode_widths.h with the new data. The new header can then be
+unicode-widths.h with the new data. The new header can then be
committed.
diff --git a/contrib/update-unicode/update_unicode.sh b/contrib/update-unicode/update_unicode.sh
index e05db92..aa90865 100755
--- a/contrib/update-unicode/update_unicode.sh
+++ b/contrib/update-unicode/update_unicode.sh
@@ -6,7 +6,7 @@
#Cf Format a format control character
#
cd "$(dirname "$0")"
-UNICODEWIDTH_H=$(git rev-parse --show-toplevel)/unicode_width.h
+UNICODEWIDTH_H=$(git rev-parse --show-toplevel)/unicode-width.h
wget -N http://www.unicode.org/Public/UCD/latest/ucd/UnicodeData.txt \
http://www.unicode.org/Public/UCD/latest/ucd/EastAsianWidth.txt &&
diff --git a/convert.c b/convert.c
index c480097..64d0d30 100644
--- a/convert.c
+++ b/convert.c
@@ -7,6 +7,7 @@
#include "sigchain.h"
#include "pkt-line.h"
#include "sub-process.h"
+#include "utf8.h"
/*
* convert.c - convert a file when checking it out and checking it in.
@@ -265,6 +266,241 @@ static int will_convert_lf_to_crlf(size_t len, struct text_stat *stats,
}
+static int validate_encoding(const char *path, const char *enc,
+ const char *data, size_t len, int die_on_error)
+{
+ /* We only check for UTF here as UTF?? can be an alias for UTF-?? */
+ if (istarts_with(enc, "UTF")) {
+ /*
+ * Check for detectable errors in UTF encodings
+ */
+ if (has_prohibited_utf_bom(enc, data, len)) {
+ const char *error_msg = _(
+ "BOM is prohibited in '%s' if encoded as %s");
+ /*
+ * This advice is shown for UTF-??BE and UTF-??LE encodings.
+ * We cut off the last two characters of the encoding name
+ * to generate the encoding name suitable for BOMs.
+ */
+ const char *advise_msg = _(
+ "The file '%s' contains a byte order "
+ "mark (BOM). Please use UTF-%s as "
+ "working-tree-encoding.");
+ const char *stripped = NULL;
+ char *upper = xstrdup_toupper(enc);
+ upper[strlen(upper)-2] = '\0';
+ if (!skip_prefix(upper, "UTF-", &stripped))
+ skip_prefix(stripped, "UTF", &stripped);
+ advise(advise_msg, path, stripped);
+ free(upper);
+ if (die_on_error)
+ die(error_msg, path, enc);
+ else {
+ return error(error_msg, path, enc);
+ }
+
+ } else if (is_missing_required_utf_bom(enc, data, len)) {
+ const char *error_msg = _(
+ "BOM is required in '%s' if encoded as %s");
+ const char *advise_msg = _(
+ "The file '%s' is missing a byte order "
+ "mark (BOM). Please use UTF-%sBE or UTF-%sLE "
+ "(depending on the byte order) as "
+ "working-tree-encoding.");
+ const char *stripped = NULL;
+ char *upper = xstrdup_toupper(enc);
+ if (!skip_prefix(upper, "UTF-", &stripped))
+ skip_prefix(stripped, "UTF", &stripped);
+ advise(advise_msg, path, stripped, stripped);
+ free(upper);
+ if (die_on_error)
+ die(error_msg, path, enc);
+ else {
+ return error(error_msg, path, enc);
+ }
+ }
+
+ }
+ return 0;
+}
+
+static void trace_encoding(const char *context, const char *path,
+ const char *encoding, const char *buf, size_t len)
+{
+ static struct trace_key coe = TRACE_KEY_INIT(WORKING_TREE_ENCODING);
+ struct strbuf trace = STRBUF_INIT;
+ int i;
+
+ strbuf_addf(&trace, "%s (%s, considered %s):\n", context, path, encoding);
+ for (i = 0; i < len && buf; ++i) {
+ strbuf_addf(
+ &trace,"| \e[2m%2i:\e[0m %2x \e[2m%c\e[0m%c",
+ i,
+ (unsigned char) buf[i],
+ (buf[i] > 32 && buf[i] < 127 ? buf[i] : ' '),
+ ((i+1) % 8 && (i+1) < len ? ' ' : '\n')
+ );
+ }
+ strbuf_addchars(&trace, '\n', 1);
+
+ trace_strbuf(&coe, &trace);
+ strbuf_release(&trace);
+}
+
+static int check_roundtrip(const char *enc_name)
+{
+ /*
+ * check_roundtrip_encoding contains a string of comma and/or
+ * space separated encodings (eg. "UTF-16, ASCII, CP1125").
+ * Search for the given encoding in that string.
+ */
+ const char *found = strcasestr(check_roundtrip_encoding, enc_name);
+ const char *next;
+ int len;
+ if (!found)
+ return 0;
+ next = found + strlen(enc_name);
+ len = strlen(check_roundtrip_encoding);
+ return (found && (
+ /*
+ * check that the found encoding is at the
+ * beginning of check_roundtrip_encoding or
+ * that it is prefixed with a space or comma
+ */
+ found == check_roundtrip_encoding || (
+ (isspace(found[-1]) || found[-1] == ',')
+ )
+ ) && (
+ /*
+ * check that the found encoding is at the
+ * end of check_roundtrip_encoding or
+ * that it is suffixed with a space or comma
+ */
+ next == check_roundtrip_encoding + len || (
+ next < check_roundtrip_encoding + len &&
+ (isspace(next[0]) || next[0] == ',')
+ )
+ ));
+}
+
+static const char *default_encoding = "UTF-8";
+
+static int encode_to_git(const char *path, const char *src, size_t src_len,
+ struct strbuf *buf, const char *enc, int conv_flags)
+{
+ char *dst;
+ int dst_len;
+ int die_on_error = conv_flags & CONV_WRITE_OBJECT;
+
+ /*
+ * No encoding is specified or there is nothing to encode.
+ * Tell the caller that the content was not modified.
+ */
+ if (!enc || (src && !src_len))
+ return 0;
+
+ /*
+ * Looks like we got called from "would_convert_to_git()".
+ * This means Git wants to know if it would encode (= modify!)
+ * the content. Let's answer with "yes", since an encoding was
+ * specified.
+ */
+ if (!buf && !src)
+ return 1;
+
+ if (validate_encoding(path, enc, src, src_len, die_on_error))
+ return 0;
+
+ trace_encoding("source", path, enc, src, src_len);
+ dst = reencode_string_len(src, src_len, default_encoding, enc,
+ &dst_len);
+ if (!dst) {
+ /*
+ * We could add the blob "as-is" to Git. However, on checkout
+ * we would try to reencode to the original encoding. This
+ * would fail and we would leave the user with a messed-up
+ * working tree. Let's try to avoid this by screaming loud.
+ */
+ const char* msg = _("failed to encode '%s' from %s to %s");
+ if (die_on_error)
+ die(msg, path, enc, default_encoding);
+ else {
+ error(msg, path, enc, default_encoding);
+ return 0;
+ }
+ }
+ trace_encoding("destination", path, default_encoding, dst, dst_len);
+
+ /*
+ * UTF supports lossless conversion round tripping [1] and conversions
+ * between UTF and other encodings are mostly round trip safe as
+ * Unicode aims to be a superset of all other character encodings.
+ * However, certain encodings (e.g. SHIFT-JIS) are known to have round
+ * trip issues [2]. Check the round trip conversion for all encodings
+ * listed in core.checkRoundtripEncoding.
+ *
+ * The round trip check is only performed if content is written to Git.
+ * This ensures that no information is lost during conversion to/from
+ * the internal UTF-8 representation.
+ *
+ * Please note, the code below is not tested because I was not able to
+ * generate a faulty round trip without an iconv error. Iconv errors
+ * are already caught above.
+ *
+ * [1] http://unicode.org/faq/utf_bom.html#gen2
+ * [2] https://support.microsoft.com/en-us/help/170559/prb-conversion-problem-between-shift-jis-and-unicode
+ */
+ if (die_on_error && check_roundtrip(enc)) {
+ char *re_src;
+ int re_src_len;
+
+ re_src = reencode_string_len(dst, dst_len,
+ enc, default_encoding,
+ &re_src_len);
+
+ trace_printf("Checking roundtrip encoding for %s...\n", enc);
+ trace_encoding("reencoded source", path, enc,
+ re_src, re_src_len);
+
+ if (!re_src || src_len != re_src_len ||
+ memcmp(src, re_src, src_len)) {
+ const char* msg = _("encoding '%s' from %s to %s and "
+ "back is not the same");
+ die(msg, path, enc, default_encoding);
+ }
+
+ free(re_src);
+ }
+
+ strbuf_attach(buf, dst, dst_len, dst_len + 1);
+ return 1;
+}
+
+static int encode_to_worktree(const char *path, const char *src, size_t src_len,
+ struct strbuf *buf, const char *enc)
+{
+ char *dst;
+ int dst_len;
+
+ /*
+ * No encoding is specified or there is nothing to encode.
+ * Tell the caller that the content was not modified.
+ */
+ if (!enc || (src && !src_len))
+ return 0;
+
+ dst = reencode_string_len(src, src_len, enc, default_encoding,
+ &dst_len);
+ if (!dst) {
+ error("failed to encode '%s' from %s to %s",
+ path, default_encoding, enc);
+ return 0;
+ }
+
+ strbuf_attach(buf, dst, dst_len, dst_len + 1);
+ return 1;
+}
+
static int crlf_to_git(const struct index_state *istate,
const char *path, const char *src, size_t len,
struct strbuf *buf,
@@ -978,6 +1214,24 @@ static int ident_to_worktree(const char *path, const char *src, size_t len,
return 1;
}
+static const char *git_path_check_encoding(struct attr_check_item *check)
+{
+ const char *value = check->value;
+
+ if (ATTR_UNSET(value) || !strlen(value))
+ return NULL;
+
+ if (ATTR_TRUE(value) || ATTR_FALSE(value)) {
+ die(_("true/false are no valid working-tree-encodings"));
+ }
+
+ /* Don't encode to the default encoding */
+ if (same_encoding(value, default_encoding))
+ return NULL;
+
+ return value;
+}
+
static enum crlf_action git_path_check_crlf(struct attr_check_item *check)
{
const char *value = check->value;
@@ -1033,6 +1287,7 @@ struct conv_attrs {
enum crlf_action attr_action; /* What attr says */
enum crlf_action crlf_action; /* When no attr is set, use core.autocrlf */
int ident;
+ const char *working_tree_encoding; /* Supported encoding or default encoding if NULL */
};
static void convert_attrs(struct conv_attrs *ca, const char *path)
@@ -1041,7 +1296,8 @@ static void convert_attrs(struct conv_attrs *ca, const char *path)
if (!check) {
check = attr_check_initl("crlf", "ident", "filter",
- "eol", "text", NULL);
+ "eol", "text", "working-tree-encoding",
+ NULL);
user_convert_tail = &user_convert;
git_config(read_convert_config, NULL);
}
@@ -1064,6 +1320,7 @@ static void convert_attrs(struct conv_attrs *ca, const char *path)
else if (eol_attr == EOL_CRLF)
ca->crlf_action = CRLF_TEXT_CRLF;
}
+ ca->working_tree_encoding = git_path_check_encoding(ccheck + 5);
} else {
ca->drv = NULL;
ca->crlf_action = CRLF_UNDEFINED;
@@ -1144,6 +1401,13 @@ int convert_to_git(const struct index_state *istate,
src = dst->buf;
len = dst->len;
}
+
+ ret |= encode_to_git(path, src, len, dst, ca.working_tree_encoding, conv_flags);
+ if (ret && dst) {
+ src = dst->buf;
+ len = dst->len;
+ }
+
if (!(conv_flags & CONV_EOL_KEEP_CRLF)) {
ret |= crlf_to_git(istate, path, src, len, dst, ca.crlf_action, conv_flags);
if (ret && dst) {
@@ -1167,6 +1431,7 @@ void convert_to_git_filter_fd(const struct index_state *istate,
if (!apply_filter(path, NULL, 0, fd, dst, ca.drv, CAP_CLEAN, NULL))
die("%s: clean filter '%s' failed", path, ca.drv->name);
+ encode_to_git(path, dst->buf, dst->len, dst, ca.working_tree_encoding, conv_flags);
crlf_to_git(istate, path, dst->buf, dst->len, dst, ca.crlf_action, conv_flags);
ident_to_git(path, dst->buf, dst->len, dst, ca.ident);
}
@@ -1198,6 +1463,12 @@ static int convert_to_working_tree_internal(const char *path, const char *src,
}
}
+ ret |= encode_to_worktree(path, src, len, dst, ca.working_tree_encoding);
+ if (ret) {
+ src = dst->buf;
+ len = dst->len;
+ }
+
ret_filter = apply_filter(
path, src, len, -1, dst, ca.drv, CAP_SMUDGE, dco);
if (!ret_filter && ca.drv && ca.drv->required)
@@ -1664,6 +1935,9 @@ struct stream_filter *get_stream_filter(const char *path, const struct object_id
if (ca.drv && (ca.drv->process || ca.drv->smudge || ca.drv->clean))
return NULL;
+ if (ca.working_tree_encoding)
+ return NULL;
+
if (ca.crlf_action == CRLF_AUTO || ca.crlf_action == CRLF_AUTO_CRLF)
return NULL;
diff --git a/convert.h b/convert.h
index 2e9b4f4..01385d9 100644
--- a/convert.h
+++ b/convert.h
@@ -12,6 +12,7 @@ struct index_state;
#define CONV_EOL_RNDTRP_WARN (1<<1) /* Warn if CRLF to LF to CRLF is different */
#define CONV_EOL_RENORMALIZE (1<<2) /* Convert CRLF to LF */
#define CONV_EOL_KEEP_CRLF (1<<3) /* Keep CRLF line endings as is */
+#define CONV_WRITE_OBJECT (1<<4) /* Content is written to the index */
extern int global_conv_flags_eol;
@@ -55,6 +56,7 @@ struct delayed_checkout {
};
extern enum eol core_eol;
+extern char *check_roundtrip_encoding;
extern const char *get_cached_convert_stats_ascii(const struct index_state *istate,
const char *path);
extern const char *get_wt_convert_stats_ascii(const char *path);
diff --git a/csum-file.c b/csum-file.c
index 5eda7fb..53ce37f 100644
--- a/csum-file.c
+++ b/csum-file.c
@@ -53,7 +53,7 @@ void hashflush(struct hashfile *f)
}
}
-int hashclose(struct hashfile *f, unsigned char *result, unsigned int flags)
+int finalize_hashfile(struct hashfile *f, unsigned char *result, unsigned int flags)
{
int fd;
@@ -61,11 +61,11 @@ int hashclose(struct hashfile *f, unsigned char *result, unsigned int flags)
the_hash_algo->final_fn(f->buffer, &f->ctx);
if (result)
hashcpy(result, f->buffer);
- if (flags & (CSUM_CLOSE | CSUM_FSYNC)) {
- /* write checksum and close fd */
+ if (flags & CSUM_HASH_IN_STREAM)
flush(f, f->buffer, the_hash_algo->rawsz);
- if (flags & CSUM_FSYNC)
- fsync_or_die(f->fd, f->name);
+ if (flags & CSUM_FSYNC)
+ fsync_or_die(f->fd, f->name);
+ if (flags & CSUM_CLOSE) {
if (close(f->fd))
die_errno("%s: sha1 file error on close", f->name);
fd = 0;
diff --git a/csum-file.h b/csum-file.h
index 992e5c0..c5a2e33 100644
--- a/csum-file.h
+++ b/csum-file.h
@@ -26,14 +26,15 @@ struct hashfile_checkpoint {
extern void hashfile_checkpoint(struct hashfile *, struct hashfile_checkpoint *);
extern int hashfile_truncate(struct hashfile *, struct hashfile_checkpoint *);
-/* hashclose flags */
-#define CSUM_CLOSE 1
-#define CSUM_FSYNC 2
+/* finalize_hashfile flags */
+#define CSUM_CLOSE 1
+#define CSUM_FSYNC 2
+#define CSUM_HASH_IN_STREAM 4
extern struct hashfile *hashfd(int fd, const char *name);
extern struct hashfile *hashfd_check(const char *name);
extern struct hashfile *hashfd_throughput(int fd, const char *name, struct progress *tp);
-extern int hashclose(struct hashfile *, unsigned char *, unsigned int);
+extern int finalize_hashfile(struct hashfile *, unsigned char *, unsigned int);
extern void hashwrite(struct hashfile *, const void *, unsigned int);
extern void hashflush(struct hashfile *f);
extern void crc32_begin(struct hashfile *);
diff --git a/daemon.c b/daemon.c
index fe833ea..9d2e0d2 100644
--- a/daemon.c
+++ b/daemon.c
@@ -1459,7 +1459,7 @@ int cmd_main(int argc, const char **argv)
die("base-path '%s' does not exist or is not a directory",
base_path);
- if (inetd_mode) {
+ if (log_destination != LOG_DESTINATION_STDERR) {
if (!freopen("/dev/null", "w", stderr))
die_errno("failed to redirect stderr to /dev/null");
}
diff --git a/date.c b/date.c
index c3e673f..49f943e 100644
--- a/date.c
+++ b/date.c
@@ -185,7 +185,7 @@ struct date_mode *date_mode_from_type(enum date_mode_type type)
{
static struct date_mode mode;
if (type == DATE_STRFTIME)
- die("BUG: cannot create anonymous strftime date_mode struct");
+ BUG("cannot create anonymous strftime date_mode struct");
mode.type = type;
mode.local = 0;
return &mode;
diff --git a/detect-compiler b/detect-compiler
new file mode 100755
index 0000000..70b7544
--- /dev/null
+++ b/detect-compiler
@@ -0,0 +1,53 @@
+#!/bin/sh
+#
+# Probe the compiler for vintage, version, etc. This is used for setting
+# optional make knobs under the DEVELOPER knob.
+
+CC="$*"
+
+# we get something like (this is at least true for gcc and clang)
+#
+# FreeBSD clang version 3.4.1 (tags/RELEASE...)
+get_version_line() {
+ $CC -v 2>&1 | grep ' version '
+}
+
+get_family() {
+ get_version_line | sed 's/^\(.*\) version [0-9][^ ]* .*/\1/'
+}
+
+get_version() {
+ get_version_line | sed 's/^.* version \([0-9][^ ]*\) .*/\1/'
+}
+
+print_flags() {
+ family=$1
+ version=$(get_version | cut -f 1 -d .)
+
+ # Print a feature flag not only for the current version, but also
+ # for any prior versions we encompass. This avoids needing to do
+ # numeric comparisons in make, which are awkward.
+ while test "$version" -gt 0
+ do
+ echo $family$version
+ version=$((version - 1))
+ done
+}
+
+case "$(get_family)" in
+gcc)
+ print_flags gcc
+ ;;
+clang)
+ print_flags clang
+ ;;
+"FreeBSD clang")
+ print_flags clang
+ ;;
+"Apple LLVM")
+ print_flags clang
+ ;;
+*)
+ : unknown compiler family
+ ;;
+esac
diff --git a/diff.c b/diff.c
index 5dfc24a..136d44b 100644
--- a/diff.c
+++ b/diff.c
@@ -1184,7 +1184,7 @@ static void emit_diff_symbol_from_struct(struct diff_options *o,
fputs(o->stat_sep, o->file);
break;
default:
- die("BUG: unknown diff symbol");
+ BUG("unknown diff symbol");
}
strbuf_release(&sb);
}
@@ -1343,7 +1343,7 @@ static struct diff_tempfile *claim_diff_tempfile(void) {
for (i = 0; i < ARRAY_SIZE(diff_temp); i++)
if (!diff_temp[i].name)
return diff_temp + i;
- die("BUG: diff is failing to clean up its tempfiles");
+ BUG("diff is failing to clean up its tempfiles");
}
static void remove_tempfile(void)
@@ -3472,7 +3472,7 @@ static int reuse_worktree_file(const char *name, const struct object_id *oid, in
* objects however would tend to be slower as they need
* to be individually opened and inflated.
*/
- if (!FAST_WORKING_DIRECTORY && !want_file && has_sha1_pack(oid->hash))
+ if (!FAST_WORKING_DIRECTORY && !want_file && has_object_pack(oid))
return 0;
/*
@@ -3638,7 +3638,8 @@ int diff_populate_filespec(struct diff_filespec *s, unsigned int flags)
else {
enum object_type type;
if (size_only || (flags & CHECK_BINARY)) {
- type = oid_object_info(&s->oid, &s->size);
+ type = oid_object_info(the_repository, &s->oid,
+ &s->size);
if (type < 0)
die("unable to read %s",
oid_to_hex(&s->oid));
@@ -3840,7 +3841,7 @@ static const char *diff_abbrev_oid(const struct object_id *oid, int abbrev)
if (abbrev < 0)
abbrev = FALLBACK_DEFAULT_ABBREV;
if (abbrev > GIT_SHA1_HEXSZ)
- die("BUG: oid abbreviation out of range: %d", abbrev);
+ BUG("oid abbreviation out of range: %d", abbrev);
if (abbrev)
hex[abbrev] = '\0';
return hex;
@@ -3897,13 +3898,14 @@ static void fill_metainfo(struct strbuf *msg,
*must_show_header = 0;
}
if (one && two && oidcmp(&one->oid, &two->oid)) {
- int abbrev = o->flags.full_index ? 40 : DEFAULT_ABBREV;
+ const unsigned hexsz = the_hash_algo->hexsz;
+ int abbrev = o->flags.full_index ? hexsz : DEFAULT_ABBREV;
if (o->flags.binary) {
mmfile_t mf;
if ((!fill_mmfile(&mf, one) && diff_filespec_is_binary(one)) ||
(!fill_mmfile(&mf, two) && diff_filespec_is_binary(two)))
- abbrev = 40;
+ abbrev = hexsz;
}
strbuf_addf(msg, "%s%sindex %s..%s", line_prefix, set,
diff_abbrev_oid(&one->oid, abbrev),
@@ -4138,6 +4140,11 @@ void diff_setup_done(struct diff_options *options)
DIFF_FORMAT_NAME_STATUS |
DIFF_FORMAT_CHECKDIFF |
DIFF_FORMAT_NO_OUTPUT;
+ /*
+ * This must be signed because we're comparing against a potentially
+ * negative value.
+ */
+ const int hexsz = the_hash_algo->hexsz;
if (options->set_default)
options->set_default(options);
@@ -4218,8 +4225,8 @@ void diff_setup_done(struct diff_options *options)
*/
read_cache();
}
- if (40 < options->abbrev)
- options->abbrev = 40; /* full */
+ if (hexsz < options->abbrev)
+ options->abbrev = hexsz; /* full */
/*
* It does not make sense to show the first hit we happened
@@ -4334,7 +4341,7 @@ static int stat_opt(struct diff_options *options, const char **av)
int argcount = 1;
if (!skip_prefix(arg, "--stat", &arg))
- die("BUG: stat option does not begin with --stat: %s", arg);
+ BUG("stat option does not begin with --stat: %s", arg);
end = (char *)arg;
switch (*arg) {
@@ -4797,8 +4804,8 @@ int diff_opt_parse(struct diff_options *options,
options->abbrev = strtoul(arg, NULL, 10);
if (options->abbrev < MINIMUM_ABBREV)
options->abbrev = MINIMUM_ABBREV;
- else if (40 < options->abbrev)
- options->abbrev = 40;
+ else if (the_hash_algo->hexsz < options->abbrev)
+ options->abbrev = the_hash_algo->hexsz;
}
else if ((argcount = parse_long_opt("src-prefix", av, &optarg))) {
options->a_prefix = optarg;
@@ -5519,7 +5526,7 @@ static void diff_flush_patch_all_file_pairs(struct diff_options *o)
struct diff_queue_struct *q = &diff_queued_diff;
if (WSEH_NEW & WS_RULE_MASK)
- die("BUG: WS rules bit mask overlaps with diff symbol flags");
+ BUG("WS rules bit mask overlaps with diff symbol flags");
if (o->color_moved)
o->emitted_symbols = &esm;
@@ -6053,7 +6060,7 @@ size_t fill_textconv(struct userdiff_driver *driver,
}
if (!driver->textconv)
- die("BUG: fill_textconv called with non-textconv driver");
+ BUG("fill_textconv called with non-textconv driver");
if (driver->textconv_cache && df->oid_valid) {
*outbuf = notes_cache_get(driver->textconv_cache,
diff --git a/diffcore-pickaxe.c b/diffcore-pickaxe.c
index 239ce51..800a899 100644
--- a/diffcore-pickaxe.c
+++ b/diffcore-pickaxe.c
@@ -215,7 +215,6 @@ static void regcomp_or_die(regex_t *regex, const char *needle, int cflags)
/* The POSIX.2 people are surely sick */
char errbuf[1024];
regerror(err, regex, errbuf, 1024);
- regfree(regex);
die("invalid regex: %s", errbuf);
}
}
diff --git a/dir-iterator.c b/dir-iterator.c
index 34182a9..f2dcd82 100644
--- a/dir-iterator.c
+++ b/dir-iterator.c
@@ -188,7 +188,7 @@ struct dir_iterator *dir_iterator_begin(const char *path)
struct dir_iterator *dir_iterator = &iter->base;
if (!path || !*path)
- die("BUG: empty path passed to dir_iterator_begin()");
+ BUG("empty path passed to dir_iterator_begin()");
strbuf_init(&iter->base.path, PATH_MAX);
strbuf_addstr(&iter->base.path, path);
diff --git a/dir.c b/dir.c
index 63a917b..ccf8b49 100644
--- a/dir.c
+++ b/dir.c
@@ -19,6 +19,7 @@
#include "varint.h"
#include "ewah/ewok.h"
#include "fsmonitor.h"
+#include "submodule-config.h"
/*
* Tells read_directory_recursive how a file or directory should be treated.
@@ -828,7 +829,7 @@ static int add_excludes(const char *fname, const char *base, int baselen,
if (size == 0) {
if (oid_stat) {
fill_stat_data(&oid_stat->stat, &st);
- oidcpy(&oid_stat->oid, &empty_blob_oid);
+ oidcpy(&oid_stat->oid, the_hash_algo->empty_blob);
oid_stat->valid = 1;
}
close(fd);
@@ -1240,11 +1241,11 @@ static void prep_exclude(struct dir_struct *dir,
(!untracked || !untracked->valid ||
/*
* .. and .gitignore does not exist before
- * (i.e. null exclude_sha1). Then we can skip
+ * (i.e. null exclude_oid). Then we can skip
* loading .gitignore, which would result in
* ENOENT anyway.
*/
- !is_null_sha1(untracked->exclude_sha1))) {
+ !is_null_oid(&untracked->exclude_oid))) {
/*
* dir->basebuf gets reused by the traversal, but we
* need fname to remain unchanged to ensure the src
@@ -1275,9 +1276,9 @@ static void prep_exclude(struct dir_struct *dir,
* order, though, if you do that.
*/
if (untracked &&
- hashcmp(oid_stat.oid.hash, untracked->exclude_sha1)) {
+ oidcmp(&oid_stat.oid, &untracked->exclude_oid)) {
invalidate_gitignore(dir->untracked, untracked);
- hashcpy(untracked->exclude_sha1, oid_stat.oid.hash);
+ oidcpy(&untracked->exclude_oid, &oid_stat.oid);
}
dir->exclude_stack = stk;
current = stk->baselen;
@@ -2622,9 +2623,10 @@ static void write_one_dir(struct untracked_cache_dir *untracked,
stat_data_to_disk(&stat_data, &untracked->stat_data);
strbuf_add(&wd->sb_stat, &stat_data, sizeof(stat_data));
}
- if (!is_null_sha1(untracked->exclude_sha1)) {
+ if (!is_null_oid(&untracked->exclude_oid)) {
ewah_set(wd->sha1_valid, i);
- strbuf_add(&wd->sb_sha1, untracked->exclude_sha1, 20);
+ strbuf_add(&wd->sb_sha1, untracked->exclude_oid.hash,
+ the_hash_algo->rawsz);
}
intlen = encode_varint(untracked->untracked_nr, intbuf);
@@ -2825,16 +2827,16 @@ static void read_stat(size_t pos, void *cb)
ud->valid = 1;
}
-static void read_sha1(size_t pos, void *cb)
+static void read_oid(size_t pos, void *cb)
{
struct read_data *rd = cb;
struct untracked_cache_dir *ud = rd->ucd[pos];
- if (rd->data + 20 > rd->end) {
+ if (rd->data + the_hash_algo->rawsz > rd->end) {
rd->data = rd->end + 1;
return;
}
- hashcpy(ud->exclude_sha1, rd->data);
- rd->data += 20;
+ hashcpy(ud->exclude_oid.hash, rd->data);
+ rd->data += the_hash_algo->rawsz;
}
static void load_oid_stat(struct oid_stat *oid_stat, const unsigned char *data,
@@ -2917,7 +2919,7 @@ struct untracked_cache *read_untracked_extension(const void *data, unsigned long
ewah_each_bit(rd.check_only, set_check_only, &rd);
rd.data = next + len;
ewah_each_bit(rd.valid, read_stat, &rd);
- ewah_each_bit(rd.sha1_valid, read_sha1, &rd);
+ ewah_each_bit(rd.sha1_valid, read_oid, &rd);
next = rd.data;
done:
@@ -2992,7 +2994,7 @@ void untracked_cache_invalidate_path(struct index_state *istate,
{
if (!istate->untracked || !istate->untracked->root)
return;
- if (!safe_path && !verify_path(path))
+ if (!safe_path && !verify_path(path, 0))
return;
invalidate_one_component(istate->untracked, istate->untracked->root,
path, strlen(path));
@@ -3010,8 +3012,57 @@ void untracked_cache_add_to_index(struct index_state *istate,
untracked_cache_invalidate_path(istate, path, 1);
}
-/* Update gitfile and core.worktree setting to connect work tree and git dir */
-void connect_work_tree_and_git_dir(const char *work_tree_, const char *git_dir_)
+static void connect_wt_gitdir_in_nested(const char *sub_worktree,
+ const char *sub_gitdir)
+{
+ int i;
+ struct repository subrepo;
+ struct strbuf sub_wt = STRBUF_INIT;
+ struct strbuf sub_gd = STRBUF_INIT;
+
+ const struct submodule *sub;
+
+ /* If the submodule has no working tree, we can ignore it. */
+ if (repo_init(&subrepo, sub_gitdir, sub_worktree))
+ return;
+
+ if (repo_read_index(&subrepo) < 0)
+ die("index file corrupt in repo %s", subrepo.gitdir);
+
+ for (i = 0; i < subrepo.index->cache_nr; i++) {
+ const struct cache_entry *ce = subrepo.index->cache[i];
+
+ if (!S_ISGITLINK(ce->ce_mode))
+ continue;
+
+ while (i + 1 < subrepo.index->cache_nr &&
+ !strcmp(ce->name, subrepo.index->cache[i + 1]->name))
+ /*
+ * Skip entries with the same name in different stages
+ * to make sure an entry is returned only once.
+ */
+ i++;
+
+ sub = submodule_from_path(&subrepo, &null_oid, ce->name);
+ if (!sub || !is_submodule_active(&subrepo, ce->name))
+ /* .gitmodules broken or inactive sub */
+ continue;
+
+ strbuf_reset(&sub_wt);
+ strbuf_reset(&sub_gd);
+ strbuf_addf(&sub_wt, "%s/%s", sub_worktree, sub->path);
+ strbuf_addf(&sub_gd, "%s/modules/%s", sub_gitdir, sub->name);
+
+ connect_work_tree_and_git_dir(sub_wt.buf, sub_gd.buf, 1);
+ }
+ strbuf_release(&sub_wt);
+ strbuf_release(&sub_gd);
+ repo_clear(&subrepo);
+}
+
+void connect_work_tree_and_git_dir(const char *work_tree_,
+ const char *git_dir_,
+ int recurse_into_nested)
{
struct strbuf gitfile_sb = STRBUF_INIT;
struct strbuf cfg_sb = STRBUF_INIT;
@@ -3041,6 +3092,10 @@ void connect_work_tree_and_git_dir(const char *work_tree_, const char *git_dir_)
strbuf_release(&gitfile_sb);
strbuf_release(&cfg_sb);
strbuf_release(&rel_path);
+
+ if (recurse_into_nested)
+ connect_wt_gitdir_in_nested(work_tree, git_dir);
+
free(work_tree);
free(git_dir);
}
@@ -3054,5 +3109,5 @@ void relocate_gitdir(const char *path, const char *old_git_dir, const char *new_
die_errno(_("could not migrate git directory from '%s' to '%s'"),
old_git_dir, new_git_dir);
- connect_work_tree_and_git_dir(path, new_git_dir);
+ connect_work_tree_and_git_dir(path, new_git_dir, 0);
}
diff --git a/dir.h b/dir.h
index b0758b8..f5fdedb 100644
--- a/dir.h
+++ b/dir.h
@@ -3,6 +3,7 @@
/* See Documentation/technical/api-directory-listing.txt */
+#include "cache.h"
#include "strbuf.h"
struct dir_entry {
@@ -118,8 +119,8 @@ struct untracked_cache_dir {
/* all data except 'dirs' in this struct are good */
unsigned int valid : 1;
unsigned int recurse : 1;
- /* null SHA-1 means this directory does not have .gitignore */
- unsigned char exclude_sha1[20];
+ /* null object ID means this directory does not have .gitignore */
+ struct object_id exclude_oid;
char name[FLEX_ARRAY];
};
@@ -359,7 +360,17 @@ struct untracked_cache *read_untracked_extension(const void *data, unsigned long
void write_untracked_extension(struct strbuf *out, struct untracked_cache *untracked);
void add_untracked_cache(struct index_state *istate);
void remove_untracked_cache(struct index_state *istate);
-extern void connect_work_tree_and_git_dir(const char *work_tree, const char *git_dir);
+
+/*
+ * Connect a worktree to a git directory by creating (or overwriting) a
+ * '.git' file containing the location of the git directory. In the git
+ * directory set the core.worktree setting to indicate where the worktree is.
+ * When `recurse_into_nested` is set, recurse into any nested submodules,
+ * connecting them as well.
+ */
+extern void connect_work_tree_and_git_dir(const char *work_tree,
+ const char *git_dir,
+ int recurse_into_nested);
extern void relocate_gitdir(const char *path,
const char *old_git_dir,
const char *new_git_dir);
diff --git a/environment.c b/environment.c
index 39b3d90..2a6de23 100644
--- a/environment.c
+++ b/environment.c
@@ -15,6 +15,7 @@
#include "commit.h"
#include "argv-array.h"
#include "object-store.h"
+#include "chdir-notify.h"
int trust_executable_bit = 1;
int trust_ctime = 1;
@@ -50,10 +51,11 @@ const char *editor_program;
const char *askpass_program;
const char *excludes_file;
enum auto_crlf auto_crlf = AUTO_CRLF_FALSE;
-int check_replace_refs = 1;
+int check_replace_refs = 1; /* NEEDSWORK: rename to read_replace_refs */
char *git_replace_ref_base;
enum eol core_eol = EOL_UNSET;
int global_conv_flags_eol = CONV_EOL_RNDTRP_WARN;
+char *check_roundtrip_encoding = "SHIFT-JIS";
unsigned whitespace_rule_cfg = WS_DEFAULT_RULE;
enum branch_track git_branch_track = BRANCH_TRACK_REMOTE;
enum rebase_setup_type autorebase = AUTOREBASE_NEVER;
@@ -64,6 +66,7 @@ enum push_default_type push_default = PUSH_DEFAULT_UNSPECIFIED;
enum object_creation_mode object_creation_mode = OBJECT_CREATION_MODE;
char *notes_ref_name;
int grafts_replace_parents = 1;
+int core_commit_graph;
int core_apply_sparse_checkout;
int merge_log_config = -1;
int precomposed_unicode = -1; /* see probe_utf8_pathname_composition() */
@@ -323,12 +326,31 @@ char *get_graft_file(void)
return the_repository->graft_file;
}
-int set_git_dir(const char *path)
+static void set_git_dir_1(const char *path)
{
if (setenv(GIT_DIR_ENVIRONMENT, path, 1))
- return error("Could not set GIT_DIR to '%s'", path);
+ die("could not set GIT_DIR to '%s'", path);
setup_git_env(path);
- return 0;
+}
+
+static void update_relative_gitdir(const char *name,
+ const char *old_cwd,
+ const char *new_cwd,
+ void *data)
+{
+ char *path = reparent_relative_path(old_cwd, new_cwd, get_git_dir());
+ trace_printf_key(&trace_setup_key,
+ "setup: move $GIT_DIR to '%s'",
+ path);
+ set_git_dir_1(path);
+ free(path);
+}
+
+void set_git_dir(const char *path)
+{
+ set_git_dir_1(path);
+ if (!is_absolute_path(path))
+ chdir_notify_register(NULL, update_relative_gitdir, NULL);
}
const char *get_log_output_encoding(void)
diff --git a/exec-cmd.c b/exec-cmd.c
new file mode 100644
index 0000000..02d31ee
--- /dev/null
+++ b/exec-cmd.c
@@ -0,0 +1,365 @@
+#include "cache.h"
+#include "exec-cmd.h"
+#include "quote.h"
+#include "argv-array.h"
+
+#if defined(RUNTIME_PREFIX)
+
+#if defined(HAVE_NS_GET_EXECUTABLE_PATH)
+#include <mach-o/dyld.h>
+#endif
+
+#if defined(HAVE_BSD_KERN_PROC_SYSCTL)
+#include <sys/param.h>
+#include <sys/types.h>
+#include <sys/sysctl.h>
+#endif
+
+#endif /* RUNTIME_PREFIX */
+
+#define MAX_ARGS 32
+
+static const char *system_prefix(void);
+
+#ifdef RUNTIME_PREFIX
+
+/**
+ * When using a runtime prefix, Git dynamically resolves paths relative to its
+ * executable.
+ *
+ * The method for determining the path of the executable is highly
+ * platform-specific.
+ */
+
+/**
+ * Path to the current Git executable. Resolved on startup by
+ * 'git_resolve_executable_dir'.
+ */
+static const char *executable_dirname;
+
+static const char *system_prefix(void)
+{
+ static const char *prefix;
+
+ assert(executable_dirname);
+ assert(is_absolute_path(executable_dirname));
+
+ if (!prefix &&
+ !(prefix = strip_path_suffix(executable_dirname, GIT_EXEC_PATH)) &&
+ !(prefix = strip_path_suffix(executable_dirname, BINDIR)) &&
+ !(prefix = strip_path_suffix(executable_dirname, "git"))) {
+ prefix = FALLBACK_RUNTIME_PREFIX;
+ trace_printf("RUNTIME_PREFIX requested, "
+ "but prefix computation failed. "
+ "Using static fallback '%s'.\n", prefix);
+ }
+ return prefix;
+}
+
+/*
+ * Resolves the executable path from argv[0], only if it is absolute.
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+static int git_get_exec_path_from_argv0(struct strbuf *buf, const char *argv0)
+{
+ const char *slash;
+
+ if (!argv0 || !*argv0)
+ return -1;
+
+ slash = find_last_dir_sep(argv0);
+ if (slash) {
+ trace_printf("trace: resolved executable path from argv0: %s\n",
+ argv0);
+ strbuf_add_absolute_path(buf, argv0);
+ return 0;
+ }
+ return -1;
+}
+
+#ifdef PROCFS_EXECUTABLE_PATH
+/*
+ * Resolves the executable path by examining a procfs symlink.
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+static int git_get_exec_path_procfs(struct strbuf *buf)
+{
+ if (strbuf_realpath(buf, PROCFS_EXECUTABLE_PATH, 0)) {
+ trace_printf(
+ "trace: resolved executable path from procfs: %s\n",
+ buf->buf);
+ return 0;
+ }
+ return -1;
+}
+#endif /* PROCFS_EXECUTABLE_PATH */
+
+#ifdef HAVE_BSD_KERN_PROC_SYSCTL
+/*
+ * Resolves the executable path using KERN_PROC_PATHNAME BSD sysctl.
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+static int git_get_exec_path_bsd_sysctl(struct strbuf *buf)
+{
+ int mib[4];
+ char path[MAXPATHLEN];
+ size_t cb = sizeof(path);
+
+ mib[0] = CTL_KERN;
+ mib[1] = KERN_PROC;
+ mib[2] = KERN_PROC_PATHNAME;
+ mib[3] = -1;
+ if (!sysctl(mib, 4, path, &cb, NULL, 0)) {
+ trace_printf(
+ "trace: resolved executable path from sysctl: %s\n",
+ path);
+ strbuf_addstr(buf, path);
+ return 0;
+ }
+ return -1;
+}
+#endif /* HAVE_BSD_KERN_PROC_SYSCTL */
+
+#ifdef HAVE_NS_GET_EXECUTABLE_PATH
+/*
+ * Resolves the executable path by querying Darwin application stack.
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+static int git_get_exec_path_darwin(struct strbuf *buf)
+{
+ char path[PATH_MAX];
+ uint32_t size = sizeof(path);
+ if (!_NSGetExecutablePath(path, &size)) {
+ trace_printf(
+ "trace: resolved executable path from Darwin stack: %s\n",
+ path);
+ strbuf_addstr(buf, path);
+ return 0;
+ }
+ return -1;
+}
+#endif /* HAVE_NS_GET_EXECUTABLE_PATH */
+
+#ifdef HAVE_WPGMPTR
+/*
+ * Resolves the executable path by using the global variable _wpgmptr.
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+static int git_get_exec_path_wpgmptr(struct strbuf *buf)
+{
+ int len = wcslen(_wpgmptr) * 3 + 1;
+ strbuf_grow(buf, len);
+ len = xwcstoutf(buf->buf, _wpgmptr, len);
+ if (len < 0)
+ return -1;
+ buf->len += len;
+ return 0;
+}
+#endif /* HAVE_WPGMPTR */
+
+/*
+ * Resolves the absolute path of the current executable.
+ *
+ * Returns 0 on success, -1 on failure.
+ */
+static int git_get_exec_path(struct strbuf *buf, const char *argv0)
+{
+ /*
+ * Identifying the executable path is operating system specific.
+ * Selectively employ all available methods in order of preference,
+ * preferring highly-available authoritative methods over
+ * selectively-available or non-authoritative methods.
+ *
+ * All cases fall back on resolving against argv[0] if there isn't a
+ * better functional method. However, note that argv[0] can be
+ * used-supplied on many operating systems, and is not authoritative
+ * in those cases.
+ *
+ * Each of these functions returns 0 on success, so evaluation will stop
+ * after the first successful method.
+ */
+ if (
+#ifdef HAVE_BSD_KERN_PROC_SYSCTL
+ git_get_exec_path_bsd_sysctl(buf) &&
+#endif /* HAVE_BSD_KERN_PROC_SYSCTL */
+
+#ifdef HAVE_NS_GET_EXECUTABLE_PATH
+ git_get_exec_path_darwin(buf) &&
+#endif /* HAVE_NS_GET_EXECUTABLE_PATH */
+
+#ifdef PROCFS_EXECUTABLE_PATH
+ git_get_exec_path_procfs(buf) &&
+#endif /* PROCFS_EXECUTABLE_PATH */
+
+#ifdef HAVE_WPGMPTR
+ git_get_exec_path_wpgmptr(buf) &&
+#endif /* HAVE_WPGMPTR */
+
+ git_get_exec_path_from_argv0(buf, argv0)) {
+ return -1;
+ }
+
+ if (strbuf_normalize_path(buf)) {
+ trace_printf("trace: could not normalize path: %s\n", buf->buf);
+ return -1;
+ }
+
+ return 0;
+}
+
+void git_resolve_executable_dir(const char *argv0)
+{
+ struct strbuf buf = STRBUF_INIT;
+ char *resolved;
+ const char *slash;
+
+ if (git_get_exec_path(&buf, argv0)) {
+ trace_printf(
+ "trace: could not determine executable path from: %s\n",
+ argv0);
+ strbuf_release(&buf);
+ return;
+ }
+
+ resolved = strbuf_detach(&buf, NULL);
+ slash = find_last_dir_sep(resolved);
+ if (slash)
+ resolved[slash - resolved] = '\0';
+
+ executable_dirname = resolved;
+ trace_printf("trace: resolved executable dir: %s\n",
+ executable_dirname);
+}
+
+#else
+
+/*
+ * When not using a runtime prefix, Git uses a hard-coded path.
+ */
+static const char *system_prefix(void)
+{
+ return FALLBACK_RUNTIME_PREFIX;
+}
+
+/*
+ * This is called during initialization, but No work needs to be done here when
+ * runtime prefix is not being used.
+ */
+void git_resolve_executable_dir(const char *argv0)
+{
+}
+
+#endif /* RUNTIME_PREFIX */
+
+char *system_path(const char *path)
+{
+ struct strbuf d = STRBUF_INIT;
+
+ if (is_absolute_path(path))
+ return xstrdup(path);
+
+ strbuf_addf(&d, "%s/%s", system_prefix(), path);
+ return strbuf_detach(&d, NULL);
+}
+
+static const char *exec_path_value;
+
+void git_set_exec_path(const char *exec_path)
+{
+ exec_path_value = exec_path;
+ /*
+ * Propagate this setting to external programs.
+ */
+ setenv(EXEC_PATH_ENVIRONMENT, exec_path, 1);
+}
+
+/* Returns the highest-priority location to look for git programs. */
+const char *git_exec_path(void)
+{
+ if (!exec_path_value) {
+ const char *env = getenv(EXEC_PATH_ENVIRONMENT);
+ if (env && *env)
+ exec_path_value = xstrdup(env);
+ else
+ exec_path_value = system_path(GIT_EXEC_PATH);
+ }
+ return exec_path_value;
+}
+
+static void add_path(struct strbuf *out, const char *path)
+{
+ if (path && *path) {
+ strbuf_add_absolute_path(out, path);
+ strbuf_addch(out, PATH_SEP);
+ }
+}
+
+void setup_path(void)
+{
+ const char *exec_path = git_exec_path();
+ const char *old_path = getenv("PATH");
+ struct strbuf new_path = STRBUF_INIT;
+
+ git_set_exec_path(exec_path);
+ add_path(&new_path, exec_path);
+
+ if (old_path)
+ strbuf_addstr(&new_path, old_path);
+ else
+ strbuf_addstr(&new_path, _PATH_DEFPATH);
+
+ setenv("PATH", new_path.buf, 1);
+
+ strbuf_release(&new_path);
+}
+
+const char **prepare_git_cmd(struct argv_array *out, const char **argv)
+{
+ argv_array_push(out, "git");
+ argv_array_pushv(out, argv);
+ return out->argv;
+}
+
+int execv_git_cmd(const char **argv)
+{
+ struct argv_array nargv = ARGV_ARRAY_INIT;
+
+ prepare_git_cmd(&nargv, argv);
+ trace_argv_printf(nargv.argv, "trace: exec:");
+
+ /* execvp() can only ever return if it fails */
+ sane_execvp("git", (char **)nargv.argv);
+
+ trace_printf("trace: exec failed: %s\n", strerror(errno));
+
+ argv_array_clear(&nargv);
+ return -1;
+}
+
+int execl_git_cmd(const char *cmd, ...)
+{
+ int argc;
+ const char *argv[MAX_ARGS + 1];
+ const char *arg;
+ va_list param;
+
+ va_start(param, cmd);
+ argv[0] = cmd;
+ argc = 1;
+ while (argc < MAX_ARGS) {
+ arg = argv[argc++] = va_arg(param, char *);
+ if (!arg)
+ break;
+ }
+ va_end(param);
+ if (MAX_ARGS <= argc)
+ return error("too many args to run %s", cmd);
+
+ argv[argc] = NULL;
+ return execv_git_cmd(argv);
+}
diff --git a/exec_cmd.h b/exec-cmd.h
index ff0b480..2522453 100644
--- a/exec_cmd.h
+++ b/exec-cmd.h
@@ -3,8 +3,8 @@
struct argv_array;
-extern void git_set_argv_exec_path(const char *exec_path);
-extern void git_extract_argv0_path(const char *path);
+extern void git_set_exec_path(const char *exec_path);
+extern void git_resolve_executable_dir(const char *path);
extern const char *git_exec_path(void);
extern void setup_path(void);
extern const char **prepare_git_cmd(struct argv_array *out, const char **argv);
diff --git a/exec_cmd.c b/exec_cmd.c
deleted file mode 100644
index ce192a2..0000000
--- a/exec_cmd.c
+++ /dev/null
@@ -1,165 +0,0 @@
-#include "cache.h"
-#include "exec_cmd.h"
-#include "quote.h"
-#include "argv-array.h"
-#define MAX_ARGS 32
-
-static const char *argv_exec_path;
-
-#ifdef RUNTIME_PREFIX
-static const char *argv0_path;
-
-static const char *system_prefix(void)
-{
- static const char *prefix;
-
- assert(argv0_path);
- assert(is_absolute_path(argv0_path));
-
- if (!prefix &&
- !(prefix = strip_path_suffix(argv0_path, GIT_EXEC_PATH)) &&
- !(prefix = strip_path_suffix(argv0_path, BINDIR)) &&
- !(prefix = strip_path_suffix(argv0_path, "git"))) {
- prefix = PREFIX;
- trace_printf("RUNTIME_PREFIX requested, "
- "but prefix computation failed. "
- "Using static fallback '%s'.\n", prefix);
- }
- return prefix;
-}
-
-void git_extract_argv0_path(const char *argv0)
-{
- const char *slash;
-
- if (!argv0 || !*argv0)
- return;
-
- slash = find_last_dir_sep(argv0);
-
- if (slash)
- argv0_path = xstrndup(argv0, slash - argv0);
-}
-
-#else
-
-static const char *system_prefix(void)
-{
- return PREFIX;
-}
-
-void git_extract_argv0_path(const char *argv0)
-{
-}
-
-#endif /* RUNTIME_PREFIX */
-
-char *system_path(const char *path)
-{
- struct strbuf d = STRBUF_INIT;
-
- if (is_absolute_path(path))
- return xstrdup(path);
-
- strbuf_addf(&d, "%s/%s", system_prefix(), path);
- return strbuf_detach(&d, NULL);
-}
-
-void git_set_argv_exec_path(const char *exec_path)
-{
- argv_exec_path = exec_path;
- /*
- * Propagate this setting to external programs.
- */
- setenv(EXEC_PATH_ENVIRONMENT, exec_path, 1);
-}
-
-
-/* Returns the highest-priority, location to look for git programs. */
-const char *git_exec_path(void)
-{
- static char *cached_exec_path;
-
- if (argv_exec_path)
- return argv_exec_path;
-
- if (!cached_exec_path) {
- const char *env = getenv(EXEC_PATH_ENVIRONMENT);
- if (env && *env)
- cached_exec_path = xstrdup(env);
- else
- cached_exec_path = system_path(GIT_EXEC_PATH);
- }
- return cached_exec_path;
-}
-
-static void add_path(struct strbuf *out, const char *path)
-{
- if (path && *path) {
- strbuf_add_absolute_path(out, path);
- strbuf_addch(out, PATH_SEP);
- }
-}
-
-void setup_path(void)
-{
- const char *old_path = getenv("PATH");
- struct strbuf new_path = STRBUF_INIT;
-
- add_path(&new_path, git_exec_path());
-
- if (old_path)
- strbuf_addstr(&new_path, old_path);
- else
- strbuf_addstr(&new_path, _PATH_DEFPATH);
-
- setenv("PATH", new_path.buf, 1);
-
- strbuf_release(&new_path);
-}
-
-const char **prepare_git_cmd(struct argv_array *out, const char **argv)
-{
- argv_array_push(out, "git");
- argv_array_pushv(out, argv);
- return out->argv;
-}
-
-int execv_git_cmd(const char **argv) {
- struct argv_array nargv = ARGV_ARRAY_INIT;
-
- prepare_git_cmd(&nargv, argv);
- trace_argv_printf(nargv.argv, "trace: exec:");
-
- /* execvp() can only ever return if it fails */
- sane_execvp("git", (char **)nargv.argv);
-
- trace_printf("trace: exec failed: %s\n", strerror(errno));
-
- argv_array_clear(&nargv);
- return -1;
-}
-
-
-int execl_git_cmd(const char *cmd,...)
-{
- int argc;
- const char *argv[MAX_ARGS + 1];
- const char *arg;
- va_list param;
-
- va_start(param, cmd);
- argv[0] = cmd;
- argc = 1;
- while (argc < MAX_ARGS) {
- arg = argv[argc++] = va_arg(param, char *);
- if (!arg)
- break;
- }
- va_end(param);
- if (MAX_ARGS <= argc)
- return error("too many args to run %s", cmd);
-
- argv[argc] = NULL;
- return execv_git_cmd(argv);
-}
diff --git a/fast-import.c b/fast-import.c
index 99f8f56..4d55910 100644
--- a/fast-import.c
+++ b/fast-import.c
@@ -170,6 +170,7 @@ Format of STDIN stream:
#include "run-command.h"
#include "packfile.h"
#include "object-store.h"
+#include "mem-pool.h"
#define PACK_ID_BITS 16
#define MAX_PACK_ID ((1<<PACK_ID_BITS)-1)
@@ -211,13 +212,6 @@ struct last_object {
unsigned no_swap : 1;
};
-struct mem_pool {
- struct mem_pool *next_pool;
- char *next_free;
- char *end;
- uintmax_t space[FLEX_ARRAY]; /* more */
-};
-
struct atom_str {
struct atom_str *next_atom;
unsigned short str_len;
@@ -306,9 +300,8 @@ static int global_argc;
static const char **global_argv;
/* Memory pools */
-static size_t mem_pool_alloc = 2*1024*1024 - sizeof(struct mem_pool);
-static size_t total_allocd;
-static struct mem_pool *mem_pool;
+static struct mem_pool fi_mem_pool = {NULL, 2*1024*1024 -
+ sizeof(struct mp_block), 0 };
/* Atom management */
static unsigned int atom_table_sz = 4451;
@@ -343,6 +336,7 @@ static unsigned int tree_entry_alloc = 1000;
static void *avail_tree_entry;
static unsigned int avail_tree_table_sz = 100;
static struct avail_tree_content **avail_tree_table;
+static size_t tree_entry_allocd;
static struct strbuf old_tree = STRBUF_INIT;
static struct strbuf new_tree = STRBUF_INIT;
@@ -636,49 +630,10 @@ static unsigned int hc_str(const char *s, size_t len)
return r;
}
-static void *pool_alloc(size_t len)
-{
- struct mem_pool *p;
- void *r;
-
- /* round up to a 'uintmax_t' alignment */
- if (len & (sizeof(uintmax_t) - 1))
- len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
-
- for (p = mem_pool; p; p = p->next_pool)
- if ((p->end - p->next_free >= len))
- break;
-
- if (!p) {
- if (len >= (mem_pool_alloc/2)) {
- total_allocd += len;
- return xmalloc(len);
- }
- total_allocd += sizeof(struct mem_pool) + mem_pool_alloc;
- p = xmalloc(st_add(sizeof(struct mem_pool), mem_pool_alloc));
- p->next_pool = mem_pool;
- p->next_free = (char *) p->space;
- p->end = p->next_free + mem_pool_alloc;
- mem_pool = p;
- }
-
- r = p->next_free;
- p->next_free += len;
- return r;
-}
-
-static void *pool_calloc(size_t count, size_t size)
-{
- size_t len = count * size;
- void *r = pool_alloc(len);
- memset(r, 0, len);
- return r;
-}
-
static char *pool_strdup(const char *s)
{
size_t len = strlen(s) + 1;
- char *r = pool_alloc(len);
+ char *r = mem_pool_alloc(&fi_mem_pool, len);
memcpy(r, s, len);
return r;
}
@@ -687,7 +642,7 @@ static void insert_mark(uintmax_t idnum, struct object_entry *oe)
{
struct mark_set *s = marks;
while ((idnum >> s->shift) >= 1024) {
- s = pool_calloc(1, sizeof(struct mark_set));
+ s = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
s->shift = marks->shift + 10;
s->data.sets[0] = marks;
marks = s;
@@ -696,7 +651,7 @@ static void insert_mark(uintmax_t idnum, struct object_entry *oe)
uintmax_t i = idnum >> s->shift;
idnum -= i << s->shift;
if (!s->data.sets[i]) {
- s->data.sets[i] = pool_calloc(1, sizeof(struct mark_set));
+ s->data.sets[i] = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
s->data.sets[i]->shift = s->shift - 10;
}
s = s->data.sets[i];
@@ -734,7 +689,7 @@ static struct atom_str *to_atom(const char *s, unsigned short len)
if (c->str_len == len && !strncmp(s, c->str_dat, len))
return c;
- c = pool_alloc(sizeof(struct atom_str) + len + 1);
+ c = mem_pool_alloc(&fi_mem_pool, sizeof(struct atom_str) + len + 1);
c->str_len = len;
memcpy(c->str_dat, s, len);
c->str_dat[len] = 0;
@@ -765,7 +720,7 @@ static struct branch *new_branch(const char *name)
if (check_refname_format(name, REFNAME_ALLOW_ONELEVEL))
die("Branch name doesn't conform to GIT standards: %s", name);
- b = pool_calloc(1, sizeof(struct branch));
+ b = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct branch));
b->name = pool_strdup(name);
b->table_next_branch = branch_table[hc];
b->branch_tree.versions[0].mode = S_IFDIR;
@@ -801,7 +756,7 @@ static struct tree_content *new_tree_content(unsigned int cnt)
avail_tree_table[hc] = f->next_avail;
} else {
cnt = cnt & 7 ? ((cnt / 8) + 1) * 8 : cnt;
- f = pool_alloc(sizeof(*t) + sizeof(t->entries[0]) * cnt);
+ f = mem_pool_alloc(&fi_mem_pool, sizeof(*t) + sizeof(t->entries[0]) * cnt);
f->entry_capacity = cnt;
}
@@ -846,7 +801,7 @@ static struct tree_entry *new_tree_entry(void)
if (!avail_tree_entry) {
unsigned int n = tree_entry_alloc;
- total_allocd += n * sizeof(struct tree_entry);
+ tree_entry_allocd += n * sizeof(struct tree_entry);
ALLOC_ARRAY(e, n);
avail_tree_entry = e;
while (n-- > 1) {
@@ -1018,7 +973,7 @@ static void end_packfile(void)
struct tag *t;
close_pack_windows(pack_data);
- hashclose(pack_file, cur_pack_oid.hash, 0);
+ finalize_hashfile(pack_file, cur_pack_oid.hash, 0);
fixup_pack_header_footer(pack_data->pack_fd, pack_data->sha1,
pack_data->pack_name, object_count,
cur_pack_oid.hash, pack_size);
@@ -1376,7 +1331,7 @@ static void *gfi_unpack_entry(
*/
p->pack_size = pack_size + the_hash_algo->rawsz;
}
- return unpack_entry(p, oe->idx.offset, &type, sizep);
+ return unpack_entry(the_repository, p, oe->idx.offset, &type, sizep);
}
static const char *get_mode(const char *str, uint16_t *modep)
@@ -1862,7 +1817,7 @@ static void dump_marks_helper(FILE *f,
static void dump_marks(void)
{
- static struct lock_file mark_lock;
+ struct lock_file mark_lock = LOCK_INIT;
FILE *f;
if (!export_marks_file || (import_marks_file && !import_marks_file_done))
@@ -1917,7 +1872,8 @@ static void read_marks(void)
die("corrupt mark line: %s", line);
e = find_object(&oid);
if (!e) {
- enum object_type type = oid_object_info(&oid, NULL);
+ enum object_type type = oid_object_info(the_repository,
+ &oid, NULL);
if (type < 0)
die("object not found: %s", oid_to_hex(&oid));
e = insert_object(&oid);
@@ -2447,7 +2403,8 @@ static void file_change_m(const char *p, struct branch *b)
enum object_type expected = S_ISDIR(mode) ?
OBJ_TREE: OBJ_BLOB;
enum object_type type = oe ? oe->type :
- oid_object_info(&oid, NULL);
+ oid_object_info(the_repository, &oid,
+ NULL);
if (type < 0)
die("%s not found: %s",
S_ISDIR(mode) ? "Tree" : "Blob",
@@ -2608,7 +2565,8 @@ static void note_change_n(const char *p, struct branch *b, unsigned char *old_fa
die("Not a blob (actually a %s): %s",
type_name(oe->type), command_buf.buf);
} else if (!is_null_oid(&oid)) {
- enum object_type type = oid_object_info(&oid, NULL);
+ enum object_type type = oid_object_info(the_repository, &oid,
+ NULL);
if (type < 0)
die("Blob not found: %s", command_buf.buf);
if (type != OBJ_BLOB)
@@ -2867,7 +2825,7 @@ static void parse_new_tag(const char *arg)
enum object_type type;
const char *v;
- t = pool_alloc(sizeof(struct tag));
+ t = mem_pool_alloc(&fi_mem_pool, sizeof(struct tag));
memset(t, 0, sizeof(struct tag));
t->name = pool_strdup(arg);
if (last_tag)
@@ -2895,7 +2853,7 @@ static void parse_new_tag(const char *arg)
} else if (!get_oid(from, &oid)) {
struct object_entry *oe = find_object(&oid);
if (!oe) {
- type = oid_object_info(&oid, NULL);
+ type = oid_object_info(the_repository, &oid, NULL);
if (type < 0)
die("Not a valid object: %s", from);
} else
@@ -3053,7 +3011,8 @@ static struct object_entry *dereference(struct object_entry *oe,
unsigned long size;
char *buf = NULL;
if (!oe) {
- enum object_type type = oid_object_info(oid, NULL);
+ enum object_type type = oid_object_info(the_repository, oid,
+ NULL);
if (type < 0)
die("object not found: %s", oid_to_hex(oid));
/* cache it! */
@@ -3466,12 +3425,12 @@ int cmd_main(int argc, const char **argv)
atom_table = xcalloc(atom_table_sz, sizeof(struct atom_str*));
branch_table = xcalloc(branch_table_sz, sizeof(struct branch*));
avail_tree_table = xcalloc(avail_tree_table_sz, sizeof(struct avail_tree_content*));
- marks = pool_calloc(1, sizeof(struct mark_set));
+ marks = mem_pool_calloc(&fi_mem_pool, 1, sizeof(struct mark_set));
global_argc = argc;
global_argv = argv;
- rc_free = pool_alloc(cmd_save * sizeof(*rc_free));
+ rc_free = mem_pool_alloc(&fi_mem_pool, cmd_save * sizeof(*rc_free));
for (i = 0; i < (cmd_save - 1); i++)
rc_free[i].next = &rc_free[i + 1];
rc_free[cmd_save - 1].next = NULL;
@@ -3545,8 +3504,8 @@ int cmd_main(int argc, const char **argv)
fprintf(stderr, "Total branches: %10lu (%10lu loads )\n", branch_count, branch_load_count);
fprintf(stderr, " marks: %10" PRIuMAX " (%10" PRIuMAX " unique )\n", (((uintmax_t)1) << marks->shift) * 1024, marks_set_count);
fprintf(stderr, " atoms: %10u\n", atom_cnt);
- fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (total_allocd + alloc_count*sizeof(struct object_entry))/1024);
- fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)(total_allocd/1024));
+ fprintf(stderr, "Memory total: %10" PRIuMAX " KiB\n", (tree_entry_allocd + fi_mem_pool.pool_alloc + alloc_count*sizeof(struct object_entry))/1024);
+ fprintf(stderr, " pools: %10lu KiB\n", (unsigned long)((tree_entry_allocd + fi_mem_pool.pool_alloc) /1024));
fprintf(stderr, " objects: %10" PRIuMAX " KiB\n", (alloc_count*sizeof(struct object_entry))/1024);
fprintf(stderr, "---------------------------------------------------------------------\n");
pack_report();
diff --git a/fetch-pack.c b/fetch-pack.c
index adc1b68..a320ce9 100644
--- a/fetch-pack.c
+++ b/fetch-pack.c
@@ -6,7 +6,7 @@
#include "pkt-line.h"
#include "commit.h"
#include "tag.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "pack.h"
#include "sideband.h"
#include "fetch-pack.h"
@@ -305,9 +305,9 @@ static void insert_one_alternate_object(struct object *obj)
#define PIPESAFE_FLUSH 32
#define LARGE_FLUSH 16384
-static int next_flush(struct fetch_pack_args *args, int count)
+static int next_flush(int stateless_rpc, int count)
{
- if (args->stateless_rpc) {
+ if (stateless_rpc) {
if (count < LARGE_FLUSH)
count <<= 1;
else
@@ -470,7 +470,7 @@ static int find_common(struct fetch_pack_args *args,
send_request(args, fd[1], &req_buf);
strbuf_setlen(&req_buf, state_len);
flushes++;
- flush_at = next_flush(args, count);
+ flush_at = next_flush(args->stateless_rpc, count);
/*
* We keep one window "ahead" of the other side, and
@@ -1080,6 +1080,350 @@ static struct ref *do_fetch_pack(struct fetch_pack_args *args,
return ref;
}
+static void add_shallow_requests(struct strbuf *req_buf,
+ const struct fetch_pack_args *args)
+{
+ if (is_repository_shallow())
+ write_shallow_commits(req_buf, 1, NULL);
+ if (args->depth > 0)
+ packet_buf_write(req_buf, "deepen %d", args->depth);
+ if (args->deepen_since) {
+ timestamp_t max_age = approxidate(args->deepen_since);
+ packet_buf_write(req_buf, "deepen-since %"PRItime, max_age);
+ }
+ if (args->deepen_not) {
+ int i;
+ for (i = 0; i < args->deepen_not->nr; i++) {
+ struct string_list_item *s = args->deepen_not->items + i;
+ packet_buf_write(req_buf, "deepen-not %s", s->string);
+ }
+ }
+}
+
+static void add_wants(const struct ref *wants, struct strbuf *req_buf)
+{
+ for ( ; wants ; wants = wants->next) {
+ const struct object_id *remote = &wants->old_oid;
+ const char *remote_hex;
+ struct object *o;
+
+ /*
+ * If that object is complete (i.e. it is an ancestor of a
+ * local ref), we tell them we have it but do not have to
+ * tell them about its ancestors, which they already know
+ * about.
+ *
+ * We use lookup_object here because we are only
+ * interested in the case we *know* the object is
+ * reachable and we have already scanned it.
+ */
+ if (((o = lookup_object(remote->hash)) != NULL) &&
+ (o->flags & COMPLETE)) {
+ continue;
+ }
+
+ remote_hex = oid_to_hex(remote);
+ packet_buf_write(req_buf, "want %s\n", remote_hex);
+ }
+}
+
+static void add_common(struct strbuf *req_buf, struct oidset *common)
+{
+ struct oidset_iter iter;
+ const struct object_id *oid;
+ oidset_iter_init(common, &iter);
+
+ while ((oid = oidset_iter_next(&iter))) {
+ packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
+ }
+}
+
+static int add_haves(struct strbuf *req_buf, int *haves_to_send, int *in_vain)
+{
+ int ret = 0;
+ int haves_added = 0;
+ const struct object_id *oid;
+
+ while ((oid = get_rev())) {
+ packet_buf_write(req_buf, "have %s\n", oid_to_hex(oid));
+ if (++haves_added >= *haves_to_send)
+ break;
+ }
+
+ *in_vain += haves_added;
+ if (!haves_added || *in_vain >= MAX_IN_VAIN) {
+ /* Send Done */
+ packet_buf_write(req_buf, "done\n");
+ ret = 1;
+ }
+
+ /* Increase haves to send on next round */
+ *haves_to_send = next_flush(1, *haves_to_send);
+
+ return ret;
+}
+
+static int send_fetch_request(int fd_out, const struct fetch_pack_args *args,
+ const struct ref *wants, struct oidset *common,
+ int *haves_to_send, int *in_vain)
+{
+ int ret = 0;
+ struct strbuf req_buf = STRBUF_INIT;
+
+ if (server_supports_v2("fetch", 1))
+ packet_buf_write(&req_buf, "command=fetch");
+ if (server_supports_v2("agent", 0))
+ packet_buf_write(&req_buf, "agent=%s", git_user_agent_sanitized());
+ if (args->server_options && args->server_options->nr &&
+ server_supports_v2("server-option", 1)) {
+ int i;
+ for (i = 0; i < args->server_options->nr; i++)
+ packet_write_fmt(fd_out, "server-option=%s",
+ args->server_options->items[i].string);
+ }
+
+ packet_buf_delim(&req_buf);
+ if (args->use_thin_pack)
+ packet_buf_write(&req_buf, "thin-pack");
+ if (args->no_progress)
+ packet_buf_write(&req_buf, "no-progress");
+ if (args->include_tag)
+ packet_buf_write(&req_buf, "include-tag");
+ if (prefer_ofs_delta)
+ packet_buf_write(&req_buf, "ofs-delta");
+
+ /* Add shallow-info and deepen request */
+ if (server_supports_feature("fetch", "shallow", 0))
+ add_shallow_requests(&req_buf, args);
+ else if (is_repository_shallow() || args->deepen)
+ die(_("Server does not support shallow requests"));
+
+ /* Add filter */
+ if (server_supports_feature("fetch", "filter", 0) &&
+ args->filter_options.choice) {
+ print_verbose(args, _("Server supports filter"));
+ packet_buf_write(&req_buf, "filter %s",
+ args->filter_options.filter_spec);
+ } else if (args->filter_options.choice) {
+ warning("filtering not recognized by server, ignoring");
+ }
+
+ /* add wants */
+ add_wants(wants, &req_buf);
+
+ if (args->no_dependents) {
+ packet_buf_write(&req_buf, "done");
+ ret = 1;
+ } else {
+ /* Add all of the common commits we've found in previous rounds */
+ add_common(&req_buf, common);
+
+ /* Add initial haves */
+ ret = add_haves(&req_buf, haves_to_send, in_vain);
+ }
+
+ /* Send request */
+ packet_buf_flush(&req_buf);
+ write_or_die(fd_out, req_buf.buf, req_buf.len);
+
+ strbuf_release(&req_buf);
+ return ret;
+}
+
+/*
+ * Processes a section header in a server's response and checks if it matches
+ * `section`. If the value of `peek` is 1, the header line will be peeked (and
+ * not consumed); if 0, the line will be consumed and the function will die if
+ * the section header doesn't match what was expected.
+ */
+static int process_section_header(struct packet_reader *reader,
+ const char *section, int peek)
+{
+ int ret;
+
+ if (packet_reader_peek(reader) != PACKET_READ_NORMAL)
+ die("error reading section header '%s'", section);
+
+ ret = !strcmp(reader->line, section);
+
+ if (!peek) {
+ if (!ret)
+ die("expected '%s', received '%s'",
+ section, reader->line);
+ packet_reader_read(reader);
+ }
+
+ return ret;
+}
+
+static int process_acks(struct packet_reader *reader, struct oidset *common)
+{
+ /* received */
+ int received_ready = 0;
+ int received_ack = 0;
+
+ process_section_header(reader, "acknowledgments", 0);
+ while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
+ const char *arg;
+
+ if (!strcmp(reader->line, "NAK"))
+ continue;
+
+ if (skip_prefix(reader->line, "ACK ", &arg)) {
+ struct object_id oid;
+ if (!get_oid_hex(arg, &oid)) {
+ struct commit *commit;
+ oidset_insert(common, &oid);
+ commit = lookup_commit(&oid);
+ mark_common(commit, 0, 1);
+ }
+ continue;
+ }
+
+ if (!strcmp(reader->line, "ready")) {
+ clear_prio_queue(&rev_list);
+ received_ready = 1;
+ continue;
+ }
+
+ die("unexpected acknowledgment line: '%s'", reader->line);
+ }
+
+ if (reader->status != PACKET_READ_FLUSH &&
+ reader->status != PACKET_READ_DELIM)
+ die("error processing acks: %d", reader->status);
+
+ /* return 0 if no common, 1 if there are common, or 2 if ready */
+ return received_ready ? 2 : (received_ack ? 1 : 0);
+}
+
+static void receive_shallow_info(struct fetch_pack_args *args,
+ struct packet_reader *reader)
+{
+ process_section_header(reader, "shallow-info", 0);
+ while (packet_reader_read(reader) == PACKET_READ_NORMAL) {
+ const char *arg;
+ struct object_id oid;
+
+ if (skip_prefix(reader->line, "shallow ", &arg)) {
+ if (get_oid_hex(arg, &oid))
+ die(_("invalid shallow line: %s"), reader->line);
+ register_shallow(&oid);
+ continue;
+ }
+ if (skip_prefix(reader->line, "unshallow ", &arg)) {
+ if (get_oid_hex(arg, &oid))
+ die(_("invalid unshallow line: %s"), reader->line);
+ if (!lookup_object(oid.hash))
+ die(_("object not found: %s"), reader->line);
+ /* make sure that it is parsed as shallow */
+ if (!parse_object(&oid))
+ die(_("error in object: %s"), reader->line);
+ if (unregister_shallow(&oid))
+ die(_("no shallow found: %s"), reader->line);
+ continue;
+ }
+ die(_("expected shallow/unshallow, got %s"), reader->line);
+ }
+
+ if (reader->status != PACKET_READ_FLUSH &&
+ reader->status != PACKET_READ_DELIM)
+ die("error processing shallow info: %d", reader->status);
+
+ setup_alternate_shallow(&shallow_lock, &alternate_shallow_file, NULL);
+ args->deepen = 1;
+}
+
+enum fetch_state {
+ FETCH_CHECK_LOCAL = 0,
+ FETCH_SEND_REQUEST,
+ FETCH_PROCESS_ACKS,
+ FETCH_GET_PACK,
+ FETCH_DONE,
+};
+
+static struct ref *do_fetch_pack_v2(struct fetch_pack_args *args,
+ int fd[2],
+ const struct ref *orig_ref,
+ struct ref **sought, int nr_sought,
+ char **pack_lockfile)
+{
+ struct ref *ref = copy_ref_list(orig_ref);
+ enum fetch_state state = FETCH_CHECK_LOCAL;
+ struct oidset common = OIDSET_INIT;
+ struct packet_reader reader;
+ int in_vain = 0;
+ int haves_to_send = INITIAL_FLUSH;
+ packet_reader_init(&reader, fd[0], NULL, 0,
+ PACKET_READ_CHOMP_NEWLINE);
+
+ while (state != FETCH_DONE) {
+ switch (state) {
+ case FETCH_CHECK_LOCAL:
+ sort_ref_list(&ref, ref_compare_name);
+ QSORT(sought, nr_sought, cmp_ref_by_name);
+
+ /* v2 supports these by default */
+ allow_unadvertised_object_request |= ALLOW_REACHABLE_SHA1;
+ use_sideband = 2;
+ if (args->depth > 0 || args->deepen_since || args->deepen_not)
+ args->deepen = 1;
+
+ if (marked)
+ for_each_ref(clear_marks, NULL);
+ marked = 1;
+
+ for_each_ref(rev_list_insert_ref_oid, NULL);
+ for_each_cached_alternate(insert_one_alternate_object);
+
+ /* Filter 'ref' by 'sought' and those that aren't local */
+ if (everything_local(args, &ref, sought, nr_sought))
+ state = FETCH_DONE;
+ else
+ state = FETCH_SEND_REQUEST;
+ break;
+ case FETCH_SEND_REQUEST:
+ if (send_fetch_request(fd[1], args, ref, &common,
+ &haves_to_send, &in_vain))
+ state = FETCH_GET_PACK;
+ else
+ state = FETCH_PROCESS_ACKS;
+ break;
+ case FETCH_PROCESS_ACKS:
+ /* Process ACKs/NAKs */
+ switch (process_acks(&reader, &common)) {
+ case 2:
+ state = FETCH_GET_PACK;
+ break;
+ case 1:
+ in_vain = 0;
+ /* fallthrough */
+ default:
+ state = FETCH_SEND_REQUEST;
+ break;
+ }
+ break;
+ case FETCH_GET_PACK:
+ /* Check for shallow-info section */
+ if (process_section_header(&reader, "shallow-info", 1))
+ receive_shallow_info(args, &reader);
+
+ /* get the pack */
+ process_section_header(&reader, "packfile", 0);
+ if (get_pack(args, fd, pack_lockfile))
+ die(_("git fetch-pack: fetch failed."));
+
+ state = FETCH_DONE;
+ break;
+ case FETCH_DONE:
+ continue;
+ }
+ }
+
+ oidset_clear(&common);
+ return ref;
+}
+
static void fetch_pack_config(void)
{
git_config_get_int("fetch.unpacklimit", &fetch_unpack_limit);
@@ -1225,7 +1569,8 @@ struct ref *fetch_pack(struct fetch_pack_args *args,
const char *dest,
struct ref **sought, int nr_sought,
struct oid_array *shallow,
- char **pack_lockfile)
+ char **pack_lockfile,
+ enum protocol_version version)
{
struct ref *ref_cpy;
struct shallow_info si;
@@ -1239,8 +1584,12 @@ struct ref *fetch_pack(struct fetch_pack_args *args,
die(_("no matching remote head"));
}
prepare_shallow_info(&si, shallow);
- ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
- &si, pack_lockfile);
+ if (version == protocol_v2)
+ ref_cpy = do_fetch_pack_v2(args, fd, ref, sought, nr_sought,
+ pack_lockfile);
+ else
+ ref_cpy = do_fetch_pack(args, fd, ref, sought, nr_sought,
+ &si, pack_lockfile);
reprepare_packed_git(the_repository);
update_shallow(args, sought, nr_sought, &si);
clear_shallow_info(&si);
diff --git a/fetch-pack.h b/fetch-pack.h
index 3e224a1..bb45a36 100644
--- a/fetch-pack.h
+++ b/fetch-pack.h
@@ -3,6 +3,7 @@
#include "string-list.h"
#include "run-command.h"
+#include "protocol.h"
#include "list-objects-filter-options.h"
struct oid_array;
@@ -14,6 +15,7 @@ struct fetch_pack_args {
const char *deepen_since;
const struct string_list *deepen_not;
struct list_objects_filter_options filter_options;
+ const struct string_list *server_options;
unsigned deepen_relative:1;
unsigned quiet:1;
unsigned keep_pack:1;
@@ -53,7 +55,8 @@ struct ref *fetch_pack(struct fetch_pack_args *args,
struct ref **sought,
int nr_sought,
struct oid_array *shallow,
- char **pack_lockfile);
+ char **pack_lockfile,
+ enum protocol_version version);
/*
* Print an appropriate error message for each sought ref that wasn't
diff --git a/fsck.c b/fsck.c
index 9218c2a..bcae2c3 100644
--- a/fsck.c
+++ b/fsck.c
@@ -10,6 +10,13 @@
#include "utf8.h"
#include "sha1-array.h"
#include "decorate.h"
+#include "oidset.h"
+#include "packfile.h"
+#include "submodule-config.h"
+#include "config.h"
+
+static struct oidset gitmodules_found = OIDSET_INIT;
+static struct oidset gitmodules_done = OIDSET_INIT;
#define FSCK_FATAL -1
#define FSCK_INFO -2
@@ -44,6 +51,7 @@
FUNC(MISSING_TAG_ENTRY, ERROR) \
FUNC(MISSING_TAG_OBJECT, ERROR) \
FUNC(MISSING_TREE, ERROR) \
+ FUNC(MISSING_TREE_OBJECT, ERROR) \
FUNC(MISSING_TYPE, ERROR) \
FUNC(MISSING_TYPE_ENTRY, ERROR) \
FUNC(MULTIPLE_AUTHORS, ERROR) \
@@ -51,6 +59,11 @@
FUNC(TREE_NOT_SORTED, ERROR) \
FUNC(UNKNOWN_TYPE, ERROR) \
FUNC(ZERO_PADDED_DATE, ERROR) \
+ FUNC(GITMODULES_MISSING, ERROR) \
+ FUNC(GITMODULES_BLOB, ERROR) \
+ FUNC(GITMODULES_PARSE, ERROR) \
+ FUNC(GITMODULES_NAME, ERROR) \
+ FUNC(GITMODULES_SYMLINK, ERROR) \
/* warnings */ \
FUNC(BAD_FILEMODE, WARN) \
FUNC(EMPTY_NAME, WARN) \
@@ -396,9 +409,11 @@ static int fsck_walk_commit(struct commit *commit, void *data, struct fsck_optio
name = get_object_name(options, &commit->object);
if (name)
- put_object_name(options, &commit->tree->object, "%s:", name);
+ put_object_name(options, &get_commit_tree(commit)->object,
+ "%s:", name);
- result = options->walk((struct object *)commit->tree, OBJ_TREE, data, options);
+ result = options->walk((struct object *)get_commit_tree(commit),
+ OBJ_TREE, data, options);
if (result < 0)
return result;
res = result;
@@ -561,10 +576,18 @@ static int fsck_tree(struct tree *item, struct fsck_options *options)
has_empty_name |= !*name;
has_dot |= !strcmp(name, ".");
has_dotdot |= !strcmp(name, "..");
- has_dotgit |= (!strcmp(name, ".git") ||
- is_hfs_dotgit(name) ||
- is_ntfs_dotgit(name));
+ has_dotgit |= is_hfs_dotgit(name) || is_ntfs_dotgit(name);
has_zero_pad |= *(char *)desc.buffer == '0';
+
+ if (is_hfs_dotgitmodules(name) || is_ntfs_dotgitmodules(name)) {
+ if (!S_ISLNK(mode))
+ oidset_insert(&gitmodules_found, oid);
+ else
+ retval += report(options, &item->object,
+ FSCK_MSG_GITMODULES_SYMLINK,
+ ".gitmodules is a symbolic link");
+ }
+
if (update_tree_entry_gently(&desc)) {
retval += report(options, &item->object, FSCK_MSG_BAD_TREE, "cannot be parsed as a tree");
break;
@@ -711,30 +734,31 @@ static int fsck_ident(const char **ident, struct object *obj, struct fsck_option
static int fsck_commit_buffer(struct commit *commit, const char *buffer,
unsigned long size, struct fsck_options *options)
{
- unsigned char tree_sha1[20], sha1[20];
+ struct object_id tree_oid, oid;
struct commit_graft *graft;
unsigned parent_count, parent_line_count = 0, author_count;
int err;
const char *buffer_begin = buffer;
+ const char *p;
if (verify_headers(buffer, size, &commit->object, options))
return -1;
if (!skip_prefix(buffer, "tree ", &buffer))
return report(options, &commit->object, FSCK_MSG_MISSING_TREE, "invalid format - expected 'tree' line");
- if (get_sha1_hex(buffer, tree_sha1) || buffer[40] != '\n') {
+ if (parse_oid_hex(buffer, &tree_oid, &p) || *p != '\n') {
err = report(options, &commit->object, FSCK_MSG_BAD_TREE_SHA1, "invalid 'tree' line format - bad sha1");
if (err)
return err;
}
- buffer += 41;
+ buffer = p + 1;
while (skip_prefix(buffer, "parent ", &buffer)) {
- if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') {
+ if (parse_oid_hex(buffer, &oid, &p) || *p != '\n') {
err = report(options, &commit->object, FSCK_MSG_BAD_PARENT_SHA1, "invalid 'parent' line format - bad sha1");
if (err)
return err;
}
- buffer += 41;
+ buffer = p + 1;
parent_line_count++;
}
graft = lookup_commit_graft(&commit->object.oid);
@@ -772,8 +796,8 @@ static int fsck_commit_buffer(struct commit *commit, const char *buffer,
err = fsck_ident(&buffer, &commit->object, options);
if (err)
return err;
- if (!commit->tree) {
- err = report(options, &commit->object, FSCK_MSG_BAD_TREE, "could not load commit's tree %s", sha1_to_hex(tree_sha1));
+ if (!get_commit_tree(commit)) {
+ err = report(options, &commit->object, FSCK_MSG_BAD_TREE, "could not load commit's tree %s", oid_to_hex(&tree_oid));
if (err)
return err;
}
@@ -799,11 +823,12 @@ static int fsck_commit(struct commit *commit, const char *data,
static int fsck_tag_buffer(struct tag *tag, const char *data,
unsigned long size, struct fsck_options *options)
{
- unsigned char sha1[20];
+ struct object_id oid;
int ret = 0;
const char *buffer;
char *to_free = NULL, *eol;
struct strbuf sb = STRBUF_INIT;
+ const char *p;
if (data)
buffer = data;
@@ -834,12 +859,12 @@ static int fsck_tag_buffer(struct tag *tag, const char *data,
ret = report(options, &tag->object, FSCK_MSG_MISSING_OBJECT, "invalid format - expected 'object' line");
goto done;
}
- if (get_sha1_hex(buffer, sha1) || buffer[40] != '\n') {
+ if (parse_oid_hex(buffer, &oid, &p) || *p != '\n') {
ret = report(options, &tag->object, FSCK_MSG_BAD_OBJECT_SHA1, "invalid 'object' line format - bad sha1");
if (ret)
goto done;
}
- buffer += 41;
+ buffer = p + 1;
if (!skip_prefix(buffer, "type ", &buffer)) {
ret = report(options, &tag->object, FSCK_MSG_MISSING_TYPE_ENTRY, "invalid format - expected 'type' line");
@@ -901,6 +926,66 @@ static int fsck_tag(struct tag *tag, const char *data,
return fsck_tag_buffer(tag, data, size, options);
}
+struct fsck_gitmodules_data {
+ struct object *obj;
+ struct fsck_options *options;
+ int ret;
+};
+
+static int fsck_gitmodules_fn(const char *var, const char *value, void *vdata)
+{
+ struct fsck_gitmodules_data *data = vdata;
+ const char *subsection, *key;
+ int subsection_len;
+ char *name;
+
+ if (parse_config_key(var, "submodule", &subsection, &subsection_len, &key) < 0 ||
+ !subsection)
+ return 0;
+
+ name = xmemdupz(subsection, subsection_len);
+ if (check_submodule_name(name) < 0)
+ data->ret |= report(data->options, data->obj,
+ FSCK_MSG_GITMODULES_NAME,
+ "disallowed submodule name: %s",
+ name);
+ free(name);
+
+ return 0;
+}
+
+static int fsck_blob(struct blob *blob, const char *buf,
+ unsigned long size, struct fsck_options *options)
+{
+ struct fsck_gitmodules_data data;
+
+ if (!oidset_contains(&gitmodules_found, &blob->object.oid))
+ return 0;
+ oidset_insert(&gitmodules_done, &blob->object.oid);
+
+ if (!buf) {
+ /*
+ * A missing buffer here is a sign that the caller found the
+ * blob too gigantic to load into memory. Let's just consider
+ * that an error.
+ */
+ return report(options, &blob->object,
+ FSCK_MSG_GITMODULES_PARSE,
+ ".gitmodules too large to parse");
+ }
+
+ data.obj = &blob->object;
+ data.options = options;
+ data.ret = 0;
+ if (git_config_from_mem(fsck_gitmodules_fn, CONFIG_ORIGIN_BLOB,
+ ".gitmodules", buf, size, &data))
+ data.ret |= report(options, &blob->object,
+ FSCK_MSG_GITMODULES_PARSE,
+ "could not parse gitmodules blob");
+
+ return data.ret;
+}
+
int fsck_object(struct object *obj, void *data, unsigned long size,
struct fsck_options *options)
{
@@ -908,7 +993,7 @@ int fsck_object(struct object *obj, void *data, unsigned long size,
return report(options, obj, FSCK_MSG_BAD_OBJECT_SHA1, "no valid object to fsck");
if (obj->type == OBJ_BLOB)
- return 0;
+ return fsck_blob((struct blob *)obj, data, size, options);
if (obj->type == OBJ_TREE)
return fsck_tree((struct tree *) obj, options);
if (obj->type == OBJ_COMMIT)
@@ -932,3 +1017,52 @@ int fsck_error_function(struct fsck_options *o,
error("object %s: %s", describe_object(o, obj), message);
return 1;
}
+
+int fsck_finish(struct fsck_options *options)
+{
+ int ret = 0;
+ struct oidset_iter iter;
+ const struct object_id *oid;
+
+ oidset_iter_init(&gitmodules_found, &iter);
+ while ((oid = oidset_iter_next(&iter))) {
+ struct blob *blob;
+ enum object_type type;
+ unsigned long size;
+ char *buf;
+
+ if (oidset_contains(&gitmodules_done, oid))
+ continue;
+
+ blob = lookup_blob(oid);
+ if (!blob) {
+ ret |= report(options, &blob->object,
+ FSCK_MSG_GITMODULES_BLOB,
+ "non-blob found at .gitmodules");
+ continue;
+ }
+
+ buf = read_object_file(oid, &type, &size);
+ if (!buf) {
+ if (is_promisor_object(&blob->object.oid))
+ continue;
+ ret |= report(options, &blob->object,
+ FSCK_MSG_GITMODULES_MISSING,
+ "unable to read .gitmodules blob");
+ continue;
+ }
+
+ if (type == OBJ_BLOB)
+ ret |= fsck_blob(blob, buf, size, options);
+ else
+ ret |= report(options, &blob->object,
+ FSCK_MSG_GITMODULES_BLOB,
+ "non-blob found at .gitmodules");
+ free(buf);
+ }
+
+
+ oidset_clear(&gitmodules_found);
+ oidset_clear(&gitmodules_done);
+ return ret;
+}
diff --git a/fsck.h b/fsck.h
index 4525510..c3cf5e0 100644
--- a/fsck.h
+++ b/fsck.h
@@ -53,4 +53,11 @@ int fsck_walk(struct object *obj, void *data, struct fsck_options *options);
int fsck_object(struct object *obj, void *data, unsigned long size,
struct fsck_options *options);
+/*
+ * Some fsck checks are context-dependent, and may end up queued; run this
+ * after completing all fsck_object() calls in order to resolve any remaining
+ * checks.
+ */
+int fsck_finish(struct fsck_options *options);
+
#endif
diff --git a/fsmonitor.c b/fsmonitor.c
index 6d7bcd5..665bd2d 100644
--- a/fsmonitor.c
+++ b/fsmonitor.c
@@ -97,19 +97,13 @@ void write_fsmonitor_extension(struct strbuf *sb, struct index_state *istate)
static int query_fsmonitor(int version, uint64_t last_update, struct strbuf *query_result)
{
struct child_process cp = CHILD_PROCESS_INIT;
- char ver[64];
- char date[64];
- const char *argv[4];
- if (!(argv[0] = core_fsmonitor))
+ if (!core_fsmonitor)
return -1;
- snprintf(ver, sizeof(version), "%d", version);
- snprintf(date, sizeof(date), "%" PRIuMAX, (uintmax_t)last_update);
- argv[1] = ver;
- argv[2] = date;
- argv[3] = NULL;
- cp.argv = argv;
+ argv_array_push(&cp.args, core_fsmonitor);
+ argv_array_pushf(&cp.args, "%d", version);
+ argv_array_pushf(&cp.args, "%" PRIuMAX, (uintmax_t)last_update);
cp.use_shell = 1;
cp.dir = get_git_work_tree();
@@ -185,6 +179,9 @@ void refresh_fsmonitor(struct index_state *istate)
for (i = 0; i < istate->cache_nr; i++)
istate->cache[i]->ce_flags &= ~CE_FSMONITOR_VALID;
+ /* If we're going to check every file, ensure we save the results */
+ istate->cache_changed |= FSMONITOR_CHANGED;
+
if (istate->untracked)
istate->untracked->use_fsmonitor = 0;
}
diff --git a/gettext.c b/gettext.c
index db727ea..7272771 100644
--- a/gettext.c
+++ b/gettext.c
@@ -2,7 +2,8 @@
* Copyright (c) 2010 Ævar Arnfjörð Bjarmason
*/
-#include "git-compat-util.h"
+#include "cache.h"
+#include "exec-cmd.h"
#include "gettext.h"
#include "strbuf.h"
#include "utf8.h"
@@ -157,15 +158,24 @@ static void init_gettext_charset(const char *domain)
void git_setup_gettext(void)
{
- const char *podir = getenv("GIT_TEXTDOMAINDIR");
+ const char *podir = getenv(GIT_TEXT_DOMAIN_DIR_ENVIRONMENT);
+ char *p = NULL;
if (!podir)
- podir = GIT_LOCALE_PATH;
+ podir = p = system_path(GIT_LOCALE_PATH);
+
+ if (!is_directory(podir)) {
+ free(p);
+ return;
+ }
+
bindtextdomain("git", podir);
setlocale(LC_MESSAGES, "");
setlocale(LC_TIME, "");
init_gettext_charset("git");
textdomain("git");
+
+ free(p);
}
/* return the number of columns of string 's' in current locale */
diff --git a/git-add--interactive.perl b/git-add--interactive.perl
index c1f52e4..36f38ce 100755
--- a/git-add--interactive.perl
+++ b/git-add--interactive.perl
@@ -205,8 +205,15 @@ my $status_head = sprintf($status_fmt, __('staged'), __('unstaged'), __('path'))
}
}
-sub get_empty_tree {
- return '4b825dc642cb6eb9a060e54bf8d69288fbee4904';
+{
+ my $empty_tree;
+ sub get_empty_tree {
+ return $empty_tree if defined $empty_tree;
+
+ $empty_tree = run_cmd_pipe(qw(git hash-object -t tree /dev/null));
+ chomp $empty_tree;
+ return $empty_tree;
+ }
}
sub get_diff_reference {
diff --git a/git-compat-util.h b/git-compat-util.h
index 07e3832..9a64998 100644
--- a/git-compat-util.h
+++ b/git-compat-util.h
@@ -284,6 +284,10 @@ extern char *gitdirname(char *);
#include <openssl/err.h>
#endif
+#ifdef HAVE_SYSINFO
+# include <sys/sysinfo.h>
+#endif
+
/* On most systems <netdb.h> would have given us this, but
* not on some systems (e.g. z/OS).
*/
@@ -455,6 +459,7 @@ extern void (*get_warn_routine(void))(const char *warn, va_list params);
extern void set_die_is_recursing_routine(int (*routine)(void));
extern int starts_with(const char *str, const char *prefix);
+extern int istarts_with(const char *str, const char *prefix);
/*
* If the string "str" begins with the string found in "prefix", return 1.
@@ -1001,6 +1006,23 @@ static inline int sane_iscase(int x, int is_lower)
return (x & 0x20) == 0;
}
+/*
+ * Like skip_prefix, but compare case-insensitively. Note that the comparison
+ * is done via tolower(), so it is strictly ASCII (no multi-byte characters or
+ * locale-specific conversions).
+ */
+static inline int skip_iprefix(const char *str, const char *prefix,
+ const char **out)
+{
+ do {
+ if (!*prefix) {
+ *out = str;
+ return 1;
+ }
+ } while (tolower(*str++) == tolower(*prefix++));
+ return 0;
+}
+
static inline int strtoul_ui(char const *s, int base, unsigned int *result)
{
unsigned long ul;
@@ -1052,7 +1074,7 @@ int git_qsort_s(void *base, size_t nmemb, size_t size,
#define QSORT_S(base, n, compar, ctx) do { \
if (qsort_s((base), (n), sizeof(*(base)), compar, ctx)) \
- die("BUG: qsort_s() failed"); \
+ BUG("qsort_s() failed"); \
} while (0)
#ifndef REG_STARTEND
@@ -1111,6 +1133,9 @@ static inline int regexec_buf(const regex_t *preg, const char *buf, size_t size,
#define HAVE_VARIADIC_MACROS 1
#endif
+/* usage.c: only to be used for testing BUG() implementation (see test-tool) */
+extern int BUG_exit_code;
+
#ifdef HAVE_VARIADIC_MACROS
__attribute__((format (printf, 3, 4))) NORETURN
void BUG_fl(const char *file, int line, const char *fmt, ...);
diff --git a/git-filter-branch.sh b/git-filter-branch.sh
index 64f2154..ccceaf1 100755
--- a/git-filter-branch.sh
+++ b/git-filter-branch.sh
@@ -11,6 +11,8 @@
# The following functions will also be available in the commit filter:
functions=$(cat << \EOF
+EMPTY_TREE=$(git hash-object -t tree /dev/null)
+
warn () {
echo "$*" >&2
}
@@ -46,7 +48,7 @@ git_commit_non_empty_tree()
{
if test $# = 3 && test "$1" = $(git rev-parse "$3^{tree}"); then
map "$3"
- elif test $# = 1 && test "$1" = 4b825dc642cb6eb9a060e54bf8d69288fbee4904; then
+ elif test $# = 1 && test "$1" = $EMPTY_TREE; then
:
else
git commit-tree "$@"
diff --git a/git-gui/git-gui.sh b/git-gui/git-gui.sh
index 91c00e6..6de74ce 100755
--- a/git-gui/git-gui.sh
+++ b/git-gui/git-gui.sh
@@ -3867,6 +3867,7 @@ bind . <$M1B-Key-equal> {show_more_context;break}
bind . <$M1B-Key-plus> {show_more_context;break}
bind . <$M1B-Key-KP_Add> {show_more_context;break}
bind . <$M1B-Key-Return> do_commit
+bind . <$M1B-Key-KP_Enter> do_commit
foreach i [list $ui_index $ui_workdir] {
bind $i <Button-1> { toggle_or_diff click %W %x %y; break }
bind $i <$M1B-Button-1> { add_one_to_selection %W %x %y; break }
diff --git a/git-gui/lib/sshkey.tcl b/git-gui/lib/sshkey.tcl
index aa6457b..589ff8f 100644
--- a/git-gui/lib/sshkey.tcl
+++ b/git-gui/lib/sshkey.tcl
@@ -2,7 +2,10 @@
# Copyright (C) 2006, 2007 Shawn Pearce
proc find_ssh_key {} {
- foreach name {~/.ssh/id_dsa.pub ~/.ssh/id_rsa.pub ~/.ssh/identity.pub} {
+ foreach name {
+ ~/.ssh/id_dsa.pub ~/.ssh/id_ecdsa.pub ~/.ssh/id_ed25519.pub
+ ~/.ssh/id_rsa.pub ~/.ssh/identity.pub
+ } {
if {[file exists $name]} {
set fh [open $name r]
set cont [read $fh]
diff --git a/git-gui/lib/themed.tcl b/git-gui/lib/themed.tcl
index 351a712..88b3119 100644
--- a/git-gui/lib/themed.tcl
+++ b/git-gui/lib/themed.tcl
@@ -1,6 +1,14 @@
# Functions for supporting the use of themed Tk widgets in git-gui.
# Copyright (C) 2009 Pat Thoyts <patthoyts@users.sourceforge.net>
+proc ttk_get_current_theme {} {
+ # Handle either current Tk or older versions of 8.5
+ if {[catch {set theme [ttk::style theme use]}]} {
+ set theme $::ttk::currentTheme
+ }
+ return $theme
+}
+
proc InitTheme {} {
# Create a color label style (bg can be overridden by widget option)
ttk::style layout Color.TLabel {
@@ -28,10 +36,7 @@ proc InitTheme {} {
}
}
- # Handle either current Tk or older versions of 8.5
- if {[catch {set theme [ttk::style theme use]}]} {
- set theme $::ttk::currentTheme
- }
+ set theme [ttk_get_current_theme]
if {[lsearch -exact {default alt classic clam} $theme] != -1} {
# Simple override of standard ttk::entry to change the field
@@ -248,7 +253,7 @@ proc tspinbox {w args} {
proc ttext {w args} {
global use_ttk
if {$use_ttk} {
- switch -- [ttk::style theme use] {
+ switch -- [ttk_get_current_theme] {
"vista" - "xpnative" {
lappend args -highlightthickness 0 -borderwidth 0
}
diff --git a/git-merge-one-file.sh b/git-merge-one-file.sh
index 9879c59..f6d9852 100755
--- a/git-merge-one-file.sh
+++ b/git-merge-one-file.sh
@@ -120,7 +120,7 @@ case "${1:-.}${2:-.}${3:-.}" in
case "$1" in
'')
echo "Added $4 in both, but differently."
- orig=$(git unpack-file e69de29bb2d1d6434b8b29ae775ad8c2e48c5391)
+ orig=$(git unpack-file $(git hash-object /dev/null))
;;
*)
echo "Auto-merging $4"
diff --git a/git-p4.py b/git-p4.py
index 7bb9cad..1afa87c 100755
--- a/git-p4.py
+++ b/git-p4.py
@@ -2099,11 +2099,11 @@ class P4Submit(Command, P4UserMap):
commits = []
if self.master:
- commitish = self.master
+ committish = self.master
else:
- commitish = 'HEAD'
+ committish = 'HEAD'
- for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, commitish)]):
+ for line in read_pipe_lines(["git", "rev-list", "--no-merges", "%s..%s" % (self.origin, committish)]):
commits.append(line.strip())
commits.reverse()
diff --git a/git-rebase--am.sh b/git-rebase--am.sh
index e5fd610..99b8c17 100644
--- a/git-rebase--am.sh
+++ b/git-rebase--am.sh
@@ -32,60 +32,47 @@ else
fi
ret=0
-if test -n "$keep_empty"
-then
- # we have to do this the hard way. git format-patch completely squashes
- # empty commits and even if it didn't the format doesn't really lend
- # itself well to recording empty patches. fortunately, cherry-pick
- # makes this easy
- git cherry-pick ${gpg_sign_opt:+"$gpg_sign_opt"} --allow-empty \
- $allow_rerere_autoupdate --right-only "$revisions" \
- $allow_empty_message \
- ${restrict_revision+^$restrict_revision}
- ret=$?
-else
- rm -f "$GIT_DIR/rebased-patches"
+rm -f "$GIT_DIR/rebased-patches"
- git format-patch -k --stdout --full-index --cherry-pick --right-only \
- --src-prefix=a/ --dst-prefix=b/ --no-renames --no-cover-letter \
- --pretty=mboxrd \
- $git_format_patch_opt \
- "$revisions" ${restrict_revision+^$restrict_revision} \
- >"$GIT_DIR/rebased-patches"
- ret=$?
+git format-patch -k --stdout --full-index --cherry-pick --right-only \
+ --src-prefix=a/ --dst-prefix=b/ --no-renames --no-cover-letter \
+ --pretty=mboxrd \
+ $git_format_patch_opt \
+ "$revisions" ${restrict_revision+^$restrict_revision} \
+ >"$GIT_DIR/rebased-patches"
+ret=$?
- if test 0 != $ret
- then
- rm -f "$GIT_DIR/rebased-patches"
- case "$head_name" in
- refs/heads/*)
- git checkout -q "$head_name"
- ;;
- *)
- git checkout -q "$orig_head"
- ;;
- esac
+if test 0 != $ret
+then
+ rm -f "$GIT_DIR/rebased-patches"
+ case "$head_name" in
+ refs/heads/*)
+ git checkout -q "$head_name"
+ ;;
+ *)
+ git checkout -q "$orig_head"
+ ;;
+ esac
- cat >&2 <<-EOF
+ cat >&2 <<-EOF
- git encountered an error while preparing the patches to replay
- these revisions:
+ git encountered an error while preparing the patches to replay
+ these revisions:
- $revisions
+ $revisions
- As a result, git cannot rebase them.
- EOF
- return $ret
- fi
+ As a result, git cannot rebase them.
+ EOF
+ return $ret
+fi
- git am $git_am_opt --rebasing --resolvemsg="$resolvemsg" \
- --patch-format=mboxrd \
- $allow_rerere_autoupdate \
- ${gpg_sign_opt:+"$gpg_sign_opt"} <"$GIT_DIR/rebased-patches"
- ret=$?
+git am $git_am_opt --rebasing --resolvemsg="$resolvemsg" \
+ --patch-format=mboxrd \
+ $allow_rerere_autoupdate \
+ ${gpg_sign_opt:+"$gpg_sign_opt"} <"$GIT_DIR/rebased-patches"
+ret=$?
- rm -f "$GIT_DIR/rebased-patches"
-fi
+rm -f "$GIT_DIR/rebased-patches"
if test 0 != $ret
then
diff --git a/git-rebase--interactive.sh b/git-rebase--interactive.sh
index 50323fc..0c92ac0 100644
--- a/git-rebase--interactive.sh
+++ b/git-rebase--interactive.sh
@@ -81,6 +81,8 @@ rewritten_pending="$state_dir"/rewritten-pending
# and leaves CR at the end instead.
cr=$(printf "\015")
+empty_tree=$(git hash-object -t tree /dev/null)
+
strategy_args=${strategy:+--strategy=$strategy}
test -n "$strategy_opts" &&
eval '
@@ -155,13 +157,19 @@ reschedule_last_action () {
append_todo_help () {
gettext "
Commands:
-p, pick = use commit
-r, reword = use commit, but edit the commit message
-e, edit = use commit, but stop for amending
-s, squash = use commit, but meld into previous commit
-f, fixup = like \"squash\", but discard this commit's log message
-x, exec = run command (the rest of the line) using shell
-d, drop = remove commit
+p, pick <commit> = use commit
+r, reword <commit> = use commit, but edit the commit message
+e, edit <commit> = use commit, but stop for amending
+s, squash <commit> = use commit, but meld into previous commit
+f, fixup <commit> = like \"squash\", but discard this commit's log message
+x, exec <commit> = run command (the rest of the line) using shell
+d, drop <commit> = remove commit
+l, label <label> = label current HEAD with a name
+t, reset <label> = reset HEAD to a label
+m, merge [-C <commit> | -c <commit>] <label> [# <oneline>]
+. create a merge commit using the original merge commit's
+. message (or the oneline, if no original merge commit was
+. specified). Use -c <commit> to reword the commit message.
These lines can be re-ordered; they are executed from top to bottom.
" | git stripspace --comment-lines >>"$todo"
@@ -238,7 +246,7 @@ is_empty_commit() {
die "$(eval_gettext "\$sha1: not a commit that can be picked")"
}
ptree=$(git rev-parse -q --verify "$1"^^{tree} 2>/dev/null) ||
- ptree=4b825dc642cb6eb9a060e54bf8d69288fbee4904
+ ptree=$empty_tree
test "$tree" = "$ptree"
}
@@ -285,7 +293,7 @@ pick_one () {
pick_one_preserving_merges "$@" && return
output eval git cherry-pick $allow_rerere_autoupdate $allow_empty_message \
${gpg_sign_opt:+$(git rev-parse --sq-quote "$gpg_sign_opt")} \
- "$strategy_args" $empty_args $ff "$@"
+ $signoff "$strategy_args" $empty_args $ff "$@"
# If cherry-pick dies it leaves the to-be-picked commit unrecorded. Reschedule
# previous task so this commit is not lost.
@@ -524,10 +532,10 @@ do_pick () {
# resolve before manually running git commit --amend then git
# rebase --continue.
git commit --allow-empty --allow-empty-message --amend \
- --no-post-rewrite -n -q -C $sha1 &&
+ --no-post-rewrite -n -q -C $sha1 $signoff &&
pick_one -n $sha1 &&
git commit --allow-empty --allow-empty-message \
- --amend --no-post-rewrite -n -q -C $sha1 \
+ --amend --no-post-rewrite -n -q -C $sha1 $signoff \
${gpg_sign_opt:+"$gpg_sign_opt"} ||
die_with_patch $sha1 "$(eval_gettext "Could not apply \$sha1... \$rest")"
else
@@ -888,6 +896,8 @@ init_revisions_and_shortrevisions () {
else
revisions=$onto...$orig_head
shortrevisions=$shorthead
+ test -z "$squash_onto" ||
+ echo "$squash_onto" >"$state_dir"/squash-onto
fi
}
@@ -942,7 +952,7 @@ EOF
die "Could not skip unnecessary pick commands"
checkout_onto
- if test -z "$rebase_root" && test ! -d "$rewritten"
+ if test ! -d "$rewritten"
then
require_clean_work_tree "rebase"
exec git rebase--helper ${force_rebase:+--no-ff} $allow_empty_message \
@@ -964,6 +974,8 @@ git_rebase__interactive () {
init_revisions_and_shortrevisions
git rebase--helper --make-script ${keep_empty:+--keep-empty} \
+ ${rebase_merges:+--rebase-merges} \
+ ${rebase_cousins:+--rebase-cousins} \
$revisions ${restrict_revision+^$restrict_revision} >"$todo" ||
die "$(gettext "Could not generate todo list")"
diff --git a/git-rebase--merge.sh b/git-rebase--merge.sh
index 685f48c..cf4c042 100644
--- a/git-rebase--merge.sh
+++ b/git-rebase--merge.sh
@@ -27,7 +27,7 @@ continue_merge () {
cmt=$(cat "$state_dir/current")
if ! git diff-index --quiet --ignore-submodules HEAD --
then
- if ! git commit ${gpg_sign_opt:+"$gpg_sign_opt"} $allow_empty_message \
+ if ! git commit ${gpg_sign_opt:+"$gpg_sign_opt"} $signoff $allow_empty_message \
--no-verify -C "$cmt"
then
echo "Commit failed, please do not call \"git commit\""
diff --git a/git-rebase.sh b/git-rebase.sh
index fb64ee1..40be59e 100755
--- a/git-rebase.sh
+++ b/git-rebase.sh
@@ -17,6 +17,7 @@ q,quiet! be quiet. implies --no-stat
autostash automatically stash/stash pop before and after
fork-point use 'merge-base --fork-point' to refine upstream
onto=! rebase onto given branch instead of upstream
+r,rebase-merges? try to rebase merges instead of skipping them
p,preserve-merges! try to recreate merges instead of ignoring them
s,strategy=! use the given merge strategy
no-ff! cherry-pick all commits, even if unchanged
@@ -62,6 +63,7 @@ $(gettext 'Resolve all conflicts manually, mark them as resolved with
You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')
"
+squash_onto=
unset onto
unset restrict_revision
cmd=
@@ -88,10 +90,13 @@ type=
state_dir=
# One of {'', continue, skip, abort}, as parsed from command line
action=
+rebase_merges=
+rebase_cousins=
preserve_merges=
autosquash=
keep_empty=
allow_empty_message=
+signoff=
test "$(git config --bool rebase.autosquash)" = "true" && autosquash=t
case "$(git config --bool commit.gpgsign)" in
true) gpg_sign_opt=-S ;;
@@ -121,6 +126,10 @@ read_basic_state () {
allow_rerere_autoupdate="$(cat "$state_dir"/allow_rerere_autoupdate)"
test -f "$state_dir"/gpg_sign_opt &&
gpg_sign_opt="$(cat "$state_dir"/gpg_sign_opt)"
+ test -f "$state_dir"/signoff && {
+ signoff="$(cat "$state_dir"/signoff)"
+ force_rebase=t
+ }
}
write_basic_state () {
@@ -135,6 +144,7 @@ write_basic_state () {
test -n "$allow_rerere_autoupdate" && echo "$allow_rerere_autoupdate" > \
"$state_dir"/allow_rerere_autoupdate
test -n "$gpg_sign_opt" && echo "$gpg_sign_opt" > "$state_dir"/gpg_sign_opt
+ test -n "$signoff" && echo "$signoff" >"$state_dir"/signoff
}
output () {
@@ -270,6 +280,22 @@ do
--allow-empty-message)
allow_empty_message=--allow-empty-message
;;
+ --no-keep-empty)
+ keep_empty=
+ ;;
+ --rebase-merges)
+ rebase_merges=t
+ test -z "$interactive_rebase" && interactive_rebase=implied
+ ;;
+ --rebase-merges=*)
+ rebase_merges=t
+ case "${1#*=}" in
+ rebase-cousins) rebase_cousins=t;;
+ no-rebase-cousins) rebase_cousins=;;
+ *) die "Unknown mode: $1";;
+ esac
+ test -z "$interactive_rebase" && interactive_rebase=implied
+ ;;
--preserve-merges)
preserve_merges=t
test -z "$interactive_rebase" && interactive_rebase=implied
@@ -332,7 +358,13 @@ do
--ignore-whitespace)
git_am_opt="$git_am_opt $1"
;;
- --committer-date-is-author-date|--ignore-date|--signoff|--no-signoff)
+ --signoff)
+ signoff=--signoff
+ ;;
+ --no-signoff)
+ signoff=
+ ;;
+ --committer-date-is-author-date|--ignore-date)
git_am_opt="$git_am_opt $1"
force_rebase=t
;;
@@ -448,6 +480,11 @@ then
test -z "$interactive_rebase" && interactive_rebase=implied
fi
+if test -n "$keep_empty"
+then
+ test -z "$interactive_rebase" && interactive_rebase=implied
+fi
+
if test -n "$interactive_rebase"
then
type=interactive
@@ -466,6 +503,14 @@ then
git_format_patch_opt="$git_format_patch_opt --progress"
fi
+if test -n "$signoff"
+then
+ test -n "$preserve_merges" &&
+ die "$(gettext "error: cannot combine '--signoff' with '--preserve-merges'")"
+ git_am_opt="$git_am_opt $signoff"
+ force_rebase=t
+fi
+
if test -z "$rebase_root"
then
case "$#" in
diff --git a/git-send-email.perl b/git-send-email.perl
index 2fa7818..8ec70e5 100755
--- a/git-send-email.perl
+++ b/git-send-email.perl
@@ -1330,9 +1330,14 @@ sub file_name_is_absolute {
return File::Spec::Functions::file_name_is_absolute($path);
}
-# Returns 1 if the message was sent, and 0 otherwise.
-# In actuality, the whole program dies when there
-# is an error sending a message.
+# Prepares the email, then asks the user what to do.
+#
+# If the user chooses to send the email, it's sent and 1 is returned.
+# If the user chooses not to send the email, 0 is returned.
+# If the user decides they want to make further edits, -1 is returned and the
+# caller is expected to call send_message again after the edits are performed.
+#
+# If an error occurs sending the email, this just dies.
sub send_message {
my @recipients = unique_email_list(@to);
@@ -1404,15 +1409,17 @@ Message-Id: $message_id
EOF
}
- # TRANSLATORS: Make sure to include [y] [n] [q] [a] in your
+ # TRANSLATORS: Make sure to include [y] [n] [e] [q] [a] in your
# translation. The program will only accept English input
# at this point.
- $_ = ask(__("Send this email? ([y]es|[n]o|[q]uit|[a]ll): "),
- valid_re => qr/^(?:yes|y|no|n|quit|q|all|a)/i,
+ $_ = ask(__("Send this email? ([y]es|[n]o|[e]dit|[q]uit|[a]ll): "),
+ valid_re => qr/^(?:yes|y|no|n|edit|e|quit|q|all|a)/i,
default => $ask_default);
die __("Send this email reply required") unless defined $_;
if (/^n/i) {
return 0;
+ } elsif (/^e/i) {
+ return -1;
} elsif (/^q/i) {
cleanup_compose_files();
exit(0);
@@ -1552,7 +1559,12 @@ $references = $initial_in_reply_to || '';
$subject = $initial_subject;
$message_num = 0;
-foreach my $t (@files) {
+# Prepares the email, prompts the user, sends it out
+# Returns 0 if an edit was done and the function should be called again, or 1
+# otherwise.
+sub process_file {
+ my ($t) = @_;
+
open my $fh, "<", $t or die sprintf(__("can't open file %s"), $t);
my $author = undef;
@@ -1642,10 +1654,15 @@ foreach my $t (@files) {
elsif (/^Content-Transfer-Encoding: (.*)/i) {
$xfer_encoding = $1 if not defined $xfer_encoding;
}
+ elsif (/^In-Reply-To: (.*)/i) {
+ $in_reply_to = $1;
+ }
+ elsif (/^References: (.*)/i) {
+ $references = $1;
+ }
elsif (!/^Date:\s/i && /^[-A-Za-z]+:\s+\S/) {
push @xh, $_;
}
-
} else {
# In the traditional
# "send lots of email" format,
@@ -1755,6 +1772,10 @@ foreach my $t (@files) {
}
my $message_was_sent = send_message();
+ if ($message_was_sent == -1) {
+ do_edit($t);
+ return 0;
+ }
# set up for the next message
if ($thread && $message_was_sent &&
@@ -1776,6 +1797,14 @@ foreach my $t (@files) {
undef $auth;
sleep($relogin_delay) if defined $relogin_delay;
}
+
+ return 1;
+}
+
+foreach my $t (@files) {
+ while (!process_file($t)) {
+ # user edited the file
+ }
}
# Execute a command (e.g. $to_cmd) to get a list of email addresses
diff --git a/git-submodule.sh b/git-submodule.sh
index 2491496..78073cd 100755
--- a/git-submodule.sh
+++ b/git-submodule.sh
@@ -42,6 +42,7 @@ prefix=
custom_name=
depth=
progress=
+dissociate=
die_if_unmatched ()
{
@@ -117,6 +118,9 @@ cmd_add()
-q|--quiet)
GIT_QUIET=1
;;
+ --progress)
+ progress=1
+ ;;
--reference)
case "$2" in '') usage ;; esac
reference_path=$2
@@ -125,6 +129,9 @@ cmd_add()
--reference=*)
reference_path="${1#--reference=}"
;;
+ --dissociate)
+ dissociate=1
+ ;;
--name)
case "$2" in '') usage ;; esac
custom_name=$2
@@ -229,6 +236,11 @@ Use -f if you really want to add it." >&2
sm_name="$sm_path"
fi
+ if ! git submodule--helper check-name "$sm_name"
+ then
+ die "$(eval_gettext "'$sm_name' is not a valid submodule name")"
+ fi
+
# perhaps the path exists and is already a git repo, else clone it
if test -e "$sm_path"
then
@@ -255,7 +267,7 @@ or you are unsure what this means choose another name with the '--name' option."
eval_gettextln "Reactivating local git directory for submodule '\$sm_name'."
fi
fi
- git submodule--helper clone ${GIT_QUIET:+--quiet} --prefix "$wt_prefix" --path "$sm_path" --name "$sm_name" --url "$realrepo" ${reference:+"$reference"} ${depth:+"$depth"} || exit
+ git submodule--helper clone ${GIT_QUIET:+--quiet} ${progress:+"--progress"} --prefix "$wt_prefix" --path "$sm_path" --name "$sm_name" --url "$realrepo" ${reference:+"$reference"} ${dissociate:+"--dissociate"} ${depth:+"$depth"} || exit
(
sanitize_submodule_env
cd "$sm_path" &&
@@ -465,7 +477,7 @@ cmd_update()
GIT_QUIET=1
;;
--progress)
- progress="--progress"
+ progress=1
;;
-i|--init)
init=1
@@ -490,6 +502,9 @@ cmd_update()
--reference=*)
reference="$1"
;;
+ --dissociate)
+ dissociate=1
+ ;;
-m|--merge)
update="merge"
;;
@@ -542,14 +557,15 @@ cmd_update()
{
git submodule--helper update-clone ${GIT_QUIET:+--quiet} \
- ${progress:+"$progress"} \
+ ${progress:+"--progress"} \
${wt_prefix:+--prefix "$wt_prefix"} \
${prefix:+--recursive-prefix "$prefix"} \
${update:+--update "$update"} \
${reference:+"$reference"} \
+ ${dissociate:+"--dissociate"} \
${depth:+--depth "$depth"} \
- ${recommend_shallow:+"$recommend_shallow"} \
- ${jobs:+$jobs} \
+ $recommend_shallow \
+ $jobs \
"$@" || echo "#unmatched" $?
} | {
err=
@@ -614,7 +630,7 @@ cmd_update()
# is not reachable from a ref.
is_tip_reachable "$sm_path" "$sha1" ||
fetch_in_submodule "$sm_path" $depth ||
- die "$(eval_gettext "Unable to fetch in submodule path '\$displaypath'")"
+ say "$(eval_gettext "Unable to fetch in submodule path '\$displaypath'")"
# Now we tried the usual fetch, but $sha1 may
# not be reachable from any of the refs
diff --git a/git.c b/git.c
index 3a89893..5771d62 100644
--- a/git.c
+++ b/git.c
@@ -1,6 +1,6 @@
#include "builtin.h"
#include "config.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "help.h"
#include "run-command.h"
@@ -25,7 +25,7 @@ struct cmd_struct {
const char git_usage_string[] =
N_("git [--version] [--help] [-C <path>] [-c <name>=<value>]\n"
" [--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]\n"
- " [-p | --paginate | --no-pager] [--no-replace-objects] [--bare]\n"
+ " [-p | --paginate | -P | --no-pager] [--no-replace-objects] [--bare]\n"
" [--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]\n"
" <command> [<args>]");
@@ -83,7 +83,7 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
*/
if (skip_prefix(cmd, "--exec-path", &cmd)) {
if (*cmd == '=')
- git_set_argv_exec_path(cmd + 1);
+ git_set_exec_path(cmd + 1);
else {
puts(git_exec_path());
exit(0);
@@ -99,7 +99,7 @@ static int handle_options(const char ***argv, int *argc, int *envchanged)
exit(0);
} else if (!strcmp(cmd, "-p") || !strcmp(cmd, "--paginate")) {
use_pager = 1;
- } else if (!strcmp(cmd, "--no-pager")) {
+ } else if (!strcmp(cmd, "-P") || !strcmp(cmd, "--no-pager")) {
use_pager = 0;
if (envchanged)
*envchanged = 1;
@@ -392,6 +392,7 @@ static struct cmd_struct commands[] = {
{ "clone", cmd_clone },
{ "column", cmd_column, RUN_SETUP_GENTLY },
{ "commit", cmd_commit, RUN_SETUP | NEED_WORK_TREE },
+ { "commit-graph", cmd_commit_graph, RUN_SETUP },
{ "commit-tree", cmd_commit_tree, RUN_SETUP | NO_PARSEOPT },
{ "config", cmd_config, RUN_SETUP_GENTLY | DELAY_PAGER_CONFIG },
{ "count-objects", cmd_count_objects, RUN_SETUP },
@@ -465,6 +466,7 @@ static struct cmd_struct commands[] = {
{ "revert", cmd_revert, RUN_SETUP | NEED_WORK_TREE },
{ "rm", cmd_rm, RUN_SETUP },
{ "send-pack", cmd_send_pack, RUN_SETUP },
+ { "serve", cmd_serve, RUN_SETUP },
{ "shortlog", cmd_shortlog, RUN_SETUP_GENTLY | USE_PAGER },
{ "show", cmd_show, RUN_SETUP },
{ "show-branch", cmd_show_branch, RUN_SETUP },
@@ -482,6 +484,7 @@ static struct cmd_struct commands[] = {
{ "update-server-info", cmd_update_server_info, RUN_SETUP },
{ "upload-archive", cmd_upload_archive, NO_PARSEOPT },
{ "upload-archive--writer", cmd_upload_archive_writer, NO_PARSEOPT },
+ { "upload-pack", cmd_upload_pack },
{ "var", cmd_var, RUN_SETUP_GENTLY | NO_PARSEOPT },
{ "verify-commit", cmd_verify_commit, RUN_SETUP },
{ "verify-pack", cmd_verify_pack },
diff --git a/gpg-interface.c b/gpg-interface.c
index 4feacf1..0647bd6 100644
--- a/gpg-interface.c
+++ b/gpg-interface.c
@@ -101,22 +101,26 @@ void print_signature_buffer(const struct signature_check *sigc, unsigned flags)
fputs(output, stderr);
}
-/*
- * Look at GPG signed content (e.g. a signed tag object), whose
- * payload is followed by a detached signature on it. Return the
- * offset where the embedded detached signature begins, or the end of
- * the data when there is no such signature.
- */
-size_t parse_signature(const char *buf, unsigned long size)
+static int is_gpg_start(const char *line)
+{
+ return starts_with(line, PGP_SIGNATURE) ||
+ starts_with(line, PGP_MESSAGE);
+}
+
+size_t parse_signature(const char *buf, size_t size)
{
- char *eol;
size_t len = 0;
- while (len < size && !starts_with(buf + len, PGP_SIGNATURE) &&
- !starts_with(buf + len, PGP_MESSAGE)) {
+ size_t match = size;
+ while (len < size) {
+ const char *eol;
+
+ if (is_gpg_start(buf + len))
+ match = len;
+
eol = memchr(buf + len, '\n', size - len);
len += eol ? eol - (buf + len) + 1 : size - len;
}
- return len;
+ return match;
}
void set_signing_key(const char *key)
@@ -128,13 +132,19 @@ void set_signing_key(const char *key)
int git_gpg_config(const char *var, const char *value, void *cb)
{
if (!strcmp(var, "user.signingkey")) {
+ if (!value)
+ return config_error_nonbool(var);
set_signing_key(value);
+ return 0;
}
+
if (!strcmp(var, "gpg.program")) {
if (!value)
return config_error_nonbool(var);
gpg_program = xstrdup(value);
+ return 0;
}
+
return 0;
}
@@ -145,12 +155,6 @@ const char *get_signing_key(void)
return git_committer_info(IDENT_STRICT|IDENT_NO_DATE);
}
-/*
- * Create a detached signature for the contents of "buffer" and append
- * it after "signature"; "buffer" and "signature" can be the same
- * strbuf instance, which would cause the detached signature appended
- * at the end.
- */
int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key)
{
struct child_process gpg = CHILD_PROCESS_INIT;
@@ -192,11 +196,6 @@ int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *sig
return 0;
}
-/*
- * Run "gpg" to see if the payload matches the detached signature.
- * gpg_output, when set, receives the diagnostic output from GPG.
- * gpg_status, when set, receives the status output from GPG.
- */
int verify_signed_buffer(const char *payload, size_t payload_size,
const char *signature, size_t signature_size,
struct strbuf *gpg_output, struct strbuf *gpg_status)
diff --git a/gpg-interface.h b/gpg-interface.h
index d2d4fd3..a5e6517 100644
--- a/gpg-interface.h
+++ b/gpg-interface.h
@@ -23,16 +23,43 @@ struct signature_check {
char *key;
};
-extern void signature_check_clear(struct signature_check *sigc);
-extern size_t parse_signature(const char *buf, unsigned long size);
-extern void parse_gpg_output(struct signature_check *);
-extern int sign_buffer(struct strbuf *buffer, struct strbuf *signature, const char *signing_key);
-extern int verify_signed_buffer(const char *payload, size_t payload_size, const char *signature, size_t signature_size, struct strbuf *gpg_output, struct strbuf *gpg_status);
-extern int git_gpg_config(const char *, const char *, void *);
-extern void set_signing_key(const char *);
-extern const char *get_signing_key(void);
-extern int check_signature(const char *payload, size_t plen,
- const char *signature, size_t slen, struct signature_check *sigc);
-void print_signature_buffer(const struct signature_check *sigc, unsigned flags);
+void signature_check_clear(struct signature_check *sigc);
+
+/*
+ * Look at GPG signed content (e.g. a signed tag object), whose
+ * payload is followed by a detached signature on it. Return the
+ * offset where the embedded detached signature begins, or the end of
+ * the data when there is no such signature.
+ */
+size_t parse_signature(const char *buf, size_t size);
+
+void parse_gpg_output(struct signature_check *);
+
+/*
+ * Create a detached signature for the contents of "buffer" and append
+ * it after "signature"; "buffer" and "signature" can be the same
+ * strbuf instance, which would cause the detached signature appended
+ * at the end.
+ */
+int sign_buffer(struct strbuf *buffer, struct strbuf *signature,
+ const char *signing_key);
+
+/*
+ * Run "gpg" to see if the payload matches the detached signature.
+ * gpg_output, when set, receives the diagnostic output from GPG.
+ * gpg_status, when set, receives the status output from GPG.
+ */
+int verify_signed_buffer(const char *payload, size_t payload_size,
+ const char *signature, size_t signature_size,
+ struct strbuf *gpg_output, struct strbuf *gpg_status);
+
+int git_gpg_config(const char *, const char *, void *);
+void set_signing_key(const char *);
+const char *get_signing_key(void);
+int check_signature(const char *payload, size_t plen,
+ const char *signature, size_t slen,
+ struct signature_check *sigc);
+void print_signature_buffer(const struct signature_check *sigc,
+ unsigned flags);
#endif
diff --git a/grep.c b/grep.c
index 65b90c1..45ec7e6 100644
--- a/grep.c
+++ b/grep.c
@@ -404,7 +404,7 @@ static void compile_pcre1_regexp(struct grep_pat *p, const struct grep_opt *opt)
die("Couldn't allocate PCRE JIT stack");
pcre_assign_jit_stack(p->pcre1_extra_info, NULL, p->pcre1_jit_stack);
} else if (p->pcre1_jit_on != 0) {
- die("BUG: The pcre1_jit_on variable should be 0 or 1, not %d",
+ BUG("The pcre1_jit_on variable should be 0 or 1, not %d",
p->pcre1_jit_on);
}
#endif
@@ -550,7 +550,7 @@ static void compile_pcre2_pattern(struct grep_pat *p, const struct grep_opt *opt
die("Couldn't allocate PCRE2 match context");
pcre2_jit_stack_assign(p->pcre2_match_context, NULL, p->pcre2_jit_stack);
} else if (p->pcre2_jit_on != 0) {
- die("BUG: The pcre2_jit_on variable should be 0 or 1, not %d",
+ BUG("The pcre2_jit_on variable should be 0 or 1, not %d",
p->pcre1_jit_on);
}
}
@@ -636,7 +636,6 @@ static void compile_fixed_regexp(struct grep_pat *p, struct grep_opt *opt)
if (err) {
char errbuf[1024];
regerror(err, &p->regexp, errbuf, sizeof(errbuf));
- regfree(&p->regexp);
compile_regexp_failed(p, errbuf);
}
}
@@ -701,7 +700,6 @@ static void compile_regexp(struct grep_pat *p, struct grep_opt *opt)
if (err) {
char errbuf[1024];
regerror(err, &p->regexp, errbuf, 1024);
- regfree(&p->regexp);
compile_regexp_failed(p, errbuf);
}
}
@@ -917,10 +915,10 @@ static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
for (p = opt->header_list; p; p = p->next) {
if (p->token != GREP_PATTERN_HEAD)
- die("BUG: a non-header pattern in grep header list.");
+ BUG("a non-header pattern in grep header list.");
if (p->field < GREP_HEADER_FIELD_MIN ||
GREP_HEADER_FIELD_MAX <= p->field)
- die("BUG: unknown header field %d", p->field);
+ BUG("unknown header field %d", p->field);
compile_regexp(p, opt);
}
@@ -933,7 +931,7 @@ static struct grep_expr *prep_header_patterns(struct grep_opt *opt)
h = compile_pattern_atom(&pp);
if (!h || pp != p->next)
- die("BUG: malformed header expr");
+ BUG("malformed header expr");
if (!header_group[p->field]) {
header_group[p->field] = h;
continue;
@@ -1652,7 +1650,7 @@ static int fill_textconv_grep(struct userdiff_driver *driver,
fill_filespec(df, &null_oid, 0, 0100644);
break;
default:
- die("BUG: attempt to textconv something without a path?");
+ BUG("attempt to textconv something without a path?");
}
/*
@@ -1748,7 +1746,7 @@ static int grep_source_1(struct grep_opt *opt, struct grep_source *gs, int colle
case GREP_BINARY_TEXT:
break;
default:
- die("BUG: unknown binary handling mode");
+ BUG("unknown binary handling mode");
}
}
@@ -2072,7 +2070,7 @@ static int grep_source_load(struct grep_source *gs)
case GREP_SOURCE_BUF:
return gs->buf ? 0 : -1;
}
- die("BUG: invalid grep_source type to load");
+ BUG("invalid grep_source type to load");
}
void grep_source_load_driver(struct grep_source *gs)
diff --git a/help.c b/help.c
index 60071a9..a4feef2 100644
--- a/help.c
+++ b/help.c
@@ -1,7 +1,7 @@
#include "cache.h"
#include "config.h"
#include "builtin.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "run-command.h"
#include "levenshtein.h"
#include "help.h"
diff --git a/http-backend.c b/http-backend.c
index 88d2a9b..adaef16 100644
--- a/http-backend.c
+++ b/http-backend.c
@@ -5,13 +5,14 @@
#include "pkt-line.h"
#include "object.h"
#include "tag.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "run-command.h"
#include "string-list.h"
#include "url.h"
#include "argv-array.h"
#include "packfile.h"
#include "object-store.h"
+#include "protocol.h"
static const char content_type[] = "Content-Type";
static const char content_length[] = "Content-Length";
@@ -468,8 +469,11 @@ static void get_info_refs(struct strbuf *hdr, char *arg)
hdr_str(hdr, content_type, buf.buf);
end_headers(hdr);
- packet_write_fmt(1, "# service=git-%s\n", svc->name);
- packet_flush(1);
+
+ if (determine_protocol_version_server() != protocol_v2) {
+ packet_write_fmt(1, "# service=git-%s\n", svc->name);
+ packet_flush(1);
+ }
argv[0] = svc->name;
run_service(argv, 0);
diff --git a/http-fetch.c b/http-fetch.c
index 8af3800..a32ac11 100644
--- a/http-fetch.c
+++ b/http-fetch.c
@@ -1,6 +1,6 @@
#include "cache.h"
#include "config.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "http.h"
#include "walker.h"
@@ -17,21 +17,13 @@ int cmd_main(int argc, const char **argv)
char *url = NULL;
int arg = 1;
int rc = 0;
- int get_tree = 0;
- int get_history = 0;
- int get_all = 0;
int get_verbosely = 0;
int get_recover = 0;
while (arg < argc && argv[arg][0] == '-') {
if (argv[arg][1] == 't') {
- get_tree = 1;
} else if (argv[arg][1] == 'c') {
- get_history = 1;
} else if (argv[arg][1] == 'a') {
- get_all = 1;
- get_tree = 1;
- get_history = 1;
} else if (argv[arg][1] == 'v') {
get_verbosely = 1;
} else if (argv[arg][1] == 'w') {
@@ -55,10 +47,6 @@ int cmd_main(int argc, const char **argv)
commits = 1;
}
- if (get_all == 0)
- warning("http-fetch: use without -a is deprecated.\n"
- "In a future release, -a will become the default.");
-
if (argv[arg])
str_end_url_with_slash(argv[arg], &url);
@@ -68,9 +56,6 @@ int cmd_main(int argc, const char **argv)
http_init(NULL, url, 0);
walker = get_http_walker(url);
- walker->get_tree = get_tree;
- walker->get_history = get_history;
- walker->get_all = get_all;
walker->get_verbosely = get_verbosely;
walker->get_recover = get_recover;
diff --git a/http-push.c b/http-push.c
index c0998fd..7e38522 100644
--- a/http-push.c
+++ b/http-push.c
@@ -6,7 +6,7 @@
#include "refs.h"
#include "diff.h"
#include "revision.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "remote.h"
#include "list-objects.h"
#include "sigchain.h"
@@ -1331,7 +1331,7 @@ static int get_delta(struct rev_info *revs, struct remote_lock *lock)
int count = 0;
while ((commit = get_revision(revs)) != NULL) {
- p = process_tree(commit->tree, p);
+ p = process_tree(get_commit_tree(commit), p);
commit->object.flags |= LOCAL;
if (!(commit->object.flags & UNINTERESTING))
count += add_send_request(&commit->object, lock);
@@ -1692,8 +1692,7 @@ int cmd_main(int argc, const char **argv)
{
struct transfer_request *request;
struct transfer_request *next_request;
- int nr_refspec = 0;
- const char **refspec = NULL;
+ struct refspec rs = REFSPEC_INIT_PUSH;
struct remote_lock *ref_lock = NULL;
struct remote_lock *info_ref_lock = NULL;
struct rev_info revs;
@@ -1756,8 +1755,7 @@ int cmd_main(int argc, const char **argv)
}
continue;
}
- refspec = argv;
- nr_refspec = argc - i;
+ refspec_appendn(&rs, argv, argc - i);
break;
}
@@ -1768,7 +1766,7 @@ int cmd_main(int argc, const char **argv)
if (!repo->url)
usage(http_push_usage);
- if (delete_branch && nr_refspec != 1)
+ if (delete_branch && rs.nr != 1)
die("You must specify only one branch name when deleting a remote branch");
setup_git_directory();
@@ -1814,18 +1812,18 @@ int cmd_main(int argc, const char **argv)
/* Remove a remote branch if -d or -D was specified */
if (delete_branch) {
- if (delete_remote_branch(refspec[0], force_delete) == -1) {
+ const char *branch = rs.items[i].src;
+ if (delete_remote_branch(branch, force_delete) == -1) {
fprintf(stderr, "Unable to delete remote branch %s\n",
- refspec[0]);
+ branch);
if (helper_status)
- printf("error %s cannot remove\n", refspec[0]);
+ printf("error %s cannot remove\n", branch);
}
goto cleanup;
}
/* match them up */
- if (match_push_refs(local_refs, &remote_refs,
- nr_refspec, (const char **) refspec, push_all)) {
+ if (match_push_refs(local_refs, &remote_refs, &rs, push_all)) {
rc = -1;
goto cleanup;
}
diff --git a/http.c b/http.c
index 3034d10..deea474 100644
--- a/http.c
+++ b/http.c
@@ -976,21 +976,6 @@ static void set_from_env(const char **var, const char *envname)
*var = val;
}
-static void protocol_http_header(void)
-{
- if (get_protocol_version_config() > 0) {
- struct strbuf protocol_header = STRBUF_INIT;
-
- strbuf_addf(&protocol_header, GIT_PROTOCOL_HEADER ": version=%d",
- get_protocol_version_config());
-
-
- extra_http_headers = curl_slist_append(extra_http_headers,
- protocol_header.buf);
- strbuf_release(&protocol_header);
- }
-}
-
void http_init(struct remote *remote, const char *url, int proactive_auth)
{
char *low_speed_limit;
@@ -1021,8 +1006,6 @@ void http_init(struct remote *remote, const char *url, int proactive_auth)
if (remote)
var_override(&http_proxy_authmethod, remote->http_proxy_authmethod);
- protocol_http_header();
-
pragma_header = curl_slist_append(http_copy_default_headers(),
"Pragma: no-cache");
no_pragma_header = curl_slist_append(http_copy_default_headers(),
@@ -1795,6 +1778,14 @@ static int http_request(const char *url,
headers = curl_slist_append(headers, buf.buf);
+ /* Add additional headers here */
+ if (options && options->extra_headers) {
+ const struct string_list_item *item;
+ for_each_string_list_item(item, options->extra_headers) {
+ headers = curl_slist_append(headers, item->string);
+ }
+ }
+
curl_easy_setopt(slot->curl, CURLOPT_URL, url);
curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, headers);
curl_easy_setopt(slot->curl, CURLOPT_ENCODING, "gzip");
@@ -1855,7 +1846,7 @@ static int update_url_from_redirect(struct strbuf *base,
return 0;
if (!skip_prefix(asked, base->buf, &tail))
- die("BUG: update_url_from_redirect: %s is not a superset of %s",
+ BUG("update_url_from_redirect: %s is not a superset of %s",
asked, base->buf);
new_len = got->len;
@@ -1903,7 +1894,7 @@ static int http_request_reauth(const char *url,
strbuf_reset(result);
break;
default:
- die("BUG: HTTP_KEEP_ERROR is only supported with strbufs");
+ BUG("HTTP_KEEP_ERROR is only supported with strbufs");
}
}
@@ -2047,7 +2038,8 @@ int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
int ret = 0, i = 0;
char *url, *data;
struct strbuf buf = STRBUF_INIT;
- unsigned char sha1[20];
+ unsigned char hash[GIT_MAX_RAWSZ];
+ const unsigned hexsz = the_hash_algo->hexsz;
end_url_with_slash(&buf, base_url);
strbuf_addstr(&buf, "objects/info/packs");
@@ -2063,13 +2055,13 @@ int http_get_info_packs(const char *base_url, struct packed_git **packs_head)
switch (data[i]) {
case 'P':
i++;
- if (i + 52 <= buf.len &&
+ if (i + hexsz + 12 <= buf.len &&
starts_with(data + i, " pack-") &&
- starts_with(data + i + 46, ".pack\n")) {
- get_sha1_hex(data + i + 6, sha1);
- fetch_and_setup_pack_index(packs_head, sha1,
+ starts_with(data + i + hexsz + 6, ".pack\n")) {
+ get_sha1_hex(data + i + 6, hash);
+ fetch_and_setup_pack_index(packs_head, hash,
base_url);
- i += 51;
+ i += hexsz + 11;
break;
}
default:
@@ -2091,6 +2083,7 @@ void release_http_pack_request(struct http_pack_request *preq)
preq->packfile = NULL;
}
preq->slot = NULL;
+ strbuf_release(&preq->tmpfile);
free(preq->url);
free(preq);
}
@@ -2113,19 +2106,19 @@ int finish_http_pack_request(struct http_pack_request *preq)
lst = &((*lst)->next);
*lst = (*lst)->next;
- if (!strip_suffix(preq->tmpfile, ".pack.temp", &len))
- die("BUG: pack tmpfile does not end in .pack.temp?");
- tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile);
+ if (!strip_suffix(preq->tmpfile.buf, ".pack.temp", &len))
+ BUG("pack tmpfile does not end in .pack.temp?");
+ tmp_idx = xstrfmt("%.*s.idx.temp", (int)len, preq->tmpfile.buf);
argv_array_push(&ip.args, "index-pack");
argv_array_pushl(&ip.args, "-o", tmp_idx, NULL);
- argv_array_push(&ip.args, preq->tmpfile);
+ argv_array_push(&ip.args, preq->tmpfile.buf);
ip.git_cmd = 1;
ip.no_stdin = 1;
ip.no_stdout = 1;
if (run_command(&ip)) {
- unlink(preq->tmpfile);
+ unlink(preq->tmpfile.buf);
unlink(tmp_idx);
free(tmp_idx);
return -1;
@@ -2133,7 +2126,7 @@ int finish_http_pack_request(struct http_pack_request *preq)
unlink(sha1_pack_index_name(p->sha1));
- if (finalize_object_file(preq->tmpfile, sha1_pack_name(p->sha1))
+ if (finalize_object_file(preq->tmpfile.buf, sha1_pack_name(p->sha1))
|| finalize_object_file(tmp_idx, sha1_pack_index_name(p->sha1))) {
free(tmp_idx);
return -1;
@@ -2152,6 +2145,7 @@ struct http_pack_request *new_http_pack_request(
struct http_pack_request *preq;
preq = xcalloc(1, sizeof(*preq));
+ strbuf_init(&preq->tmpfile, 0);
preq->target = target;
end_url_with_slash(&buf, base_url);
@@ -2159,12 +2153,11 @@ struct http_pack_request *new_http_pack_request(
sha1_to_hex(target->sha1));
preq->url = strbuf_detach(&buf, NULL);
- snprintf(preq->tmpfile, sizeof(preq->tmpfile), "%s.temp",
- sha1_pack_name(target->sha1));
- preq->packfile = fopen(preq->tmpfile, "a");
+ strbuf_addf(&preq->tmpfile, "%s.temp", sha1_pack_name(target->sha1));
+ preq->packfile = fopen(preq->tmpfile.buf, "a");
if (!preq->packfile) {
error("Unable to open local file %s for pack",
- preq->tmpfile);
+ preq->tmpfile.buf);
goto abort;
}
@@ -2191,6 +2184,7 @@ struct http_pack_request *new_http_pack_request(
return preq;
abort:
+ strbuf_release(&preq->tmpfile);
free(preq->url);
free(preq);
return NULL;
@@ -2210,7 +2204,7 @@ static size_t fwrite_sha1_file(char *ptr, size_t eltsize, size_t nmemb,
CURLcode c = curl_easy_getinfo(slot->curl, CURLINFO_HTTP_CODE,
&slot->http_code);
if (c != CURLE_OK)
- die("BUG: curl_easy_getinfo for HTTP code failed: %s",
+ BUG("curl_easy_getinfo for HTTP code failed: %s",
curl_easy_strerror(c));
if (slot->http_code >= 300)
return size;
@@ -2241,7 +2235,7 @@ struct http_object_request *new_http_object_request(const char *base_url,
{
char *hex = sha1_to_hex(sha1);
struct strbuf filename = STRBUF_INIT;
- char prevfile[PATH_MAX];
+ struct strbuf prevfile = STRBUF_INIT;
int prevlocal;
char prev_buf[PREV_BUF_SIZE];
ssize_t prev_read = 0;
@@ -2249,40 +2243,41 @@ struct http_object_request *new_http_object_request(const char *base_url,
struct http_object_request *freq;
freq = xcalloc(1, sizeof(*freq));
+ strbuf_init(&freq->tmpfile, 0);
hashcpy(freq->sha1, sha1);
freq->localfile = -1;
sha1_file_name(the_repository, &filename, sha1);
- snprintf(freq->tmpfile, sizeof(freq->tmpfile),
- "%s.temp", filename.buf);
+ strbuf_addf(&freq->tmpfile, "%s.temp", filename.buf);
- snprintf(prevfile, sizeof(prevfile), "%s.prev", filename.buf);
- unlink_or_warn(prevfile);
- rename(freq->tmpfile, prevfile);
- unlink_or_warn(freq->tmpfile);
+ strbuf_addf(&prevfile, "%s.prev", filename.buf);
+ unlink_or_warn(prevfile.buf);
+ rename(freq->tmpfile.buf, prevfile.buf);
+ unlink_or_warn(freq->tmpfile.buf);
strbuf_release(&filename);
if (freq->localfile != -1)
error("fd leakage in start: %d", freq->localfile);
- freq->localfile = open(freq->tmpfile,
+ freq->localfile = open(freq->tmpfile.buf,
O_WRONLY | O_CREAT | O_EXCL, 0666);
/*
* This could have failed due to the "lazy directory creation";
* try to mkdir the last path component.
*/
if (freq->localfile < 0 && errno == ENOENT) {
- char *dir = strrchr(freq->tmpfile, '/');
+ char *dir = strrchr(freq->tmpfile.buf, '/');
if (dir) {
*dir = 0;
- mkdir(freq->tmpfile, 0777);
+ mkdir(freq->tmpfile.buf, 0777);
*dir = '/';
}
- freq->localfile = open(freq->tmpfile,
+ freq->localfile = open(freq->tmpfile.buf,
O_WRONLY | O_CREAT | O_EXCL, 0666);
}
if (freq->localfile < 0) {
- error_errno("Couldn't create temporary file %s", freq->tmpfile);
+ error_errno("Couldn't create temporary file %s",
+ freq->tmpfile.buf);
goto abort;
}
@@ -2296,7 +2291,7 @@ struct http_object_request *new_http_object_request(const char *base_url,
* If a previous temp file is present, process what was already
* fetched.
*/
- prevlocal = open(prevfile, O_RDONLY);
+ prevlocal = open(prevfile.buf, O_RDONLY);
if (prevlocal != -1) {
do {
prev_read = xread(prevlocal, prev_buf, PREV_BUF_SIZE);
@@ -2313,7 +2308,8 @@ struct http_object_request *new_http_object_request(const char *base_url,
} while (prev_read > 0);
close(prevlocal);
}
- unlink_or_warn(prevfile);
+ unlink_or_warn(prevfile.buf);
+ strbuf_release(&prevfile);
/*
* Reset inflate/SHA1 if there was an error reading the previous temp
@@ -2328,7 +2324,7 @@ struct http_object_request *new_http_object_request(const char *base_url,
lseek(freq->localfile, 0, SEEK_SET);
if (ftruncate(freq->localfile, 0) < 0) {
error_errno("Couldn't truncate temporary file %s",
- freq->tmpfile);
+ freq->tmpfile.buf);
goto abort;
}
}
@@ -2358,6 +2354,7 @@ struct http_object_request *new_http_object_request(const char *base_url,
return freq;
abort:
+ strbuf_release(&prevfile);
free(freq->url);
free(freq);
return NULL;
@@ -2385,24 +2382,24 @@ int finish_http_object_request(struct http_object_request *freq)
if (freq->http_code == 416) {
warning("requested range invalid; we may already have all the data.");
} else if (freq->curl_result != CURLE_OK) {
- if (stat(freq->tmpfile, &st) == 0)
+ if (stat(freq->tmpfile.buf, &st) == 0)
if (st.st_size == 0)
- unlink_or_warn(freq->tmpfile);
+ unlink_or_warn(freq->tmpfile.buf);
return -1;
}
git_inflate_end(&freq->stream);
git_SHA1_Final(freq->real_sha1, &freq->c);
if (freq->zret != Z_STREAM_END) {
- unlink_or_warn(freq->tmpfile);
+ unlink_or_warn(freq->tmpfile.buf);
return -1;
}
if (hashcmp(freq->sha1, freq->real_sha1)) {
- unlink_or_warn(freq->tmpfile);
+ unlink_or_warn(freq->tmpfile.buf);
return -1;
}
sha1_file_name(the_repository, &filename, freq->sha1);
- freq->rename = finalize_object_file(freq->tmpfile, filename.buf);
+ freq->rename = finalize_object_file(freq->tmpfile.buf, filename.buf);
strbuf_release(&filename);
return freq->rename;
@@ -2410,7 +2407,7 @@ int finish_http_object_request(struct http_object_request *freq)
void abort_http_object_request(struct http_object_request *freq)
{
- unlink_or_warn(freq->tmpfile);
+ unlink_or_warn(freq->tmpfile.buf);
release_http_object_request(freq);
}
@@ -2430,4 +2427,5 @@ void release_http_object_request(struct http_object_request *freq)
release_active_slot(freq->slot);
freq->slot = NULL;
}
+ strbuf_release(&freq->tmpfile);
}
diff --git a/http.h b/http.h
index f7bd3b2..d305ca1 100644
--- a/http.h
+++ b/http.h
@@ -172,6 +172,13 @@ struct http_get_options {
* for details.
*/
struct strbuf *base_url;
+
+ /*
+ * If not NULL, contains additional HTTP headers to be sent with the
+ * request. The strings in the list must not be freed until after the
+ * request has completed.
+ */
+ struct string_list *extra_headers;
};
/* Return values for http_get_*() */
@@ -200,7 +207,7 @@ struct http_pack_request {
struct packed_git *target;
struct packed_git **lst;
FILE *packfile;
- char tmpfile[PATH_MAX];
+ struct strbuf tmpfile;
struct active_request_slot *slot;
};
@@ -212,7 +219,7 @@ extern void release_http_pack_request(struct http_pack_request *preq);
/* Helpers for fetching object */
struct http_object_request {
char *url;
- char tmpfile[PATH_MAX];
+ struct strbuf tmpfile;
int localfile;
CURLcode curl_result;
char errorstr[CURL_ERROR_SIZE];
diff --git a/imap-send.c b/imap-send.c
index ffb0a6e..b4eb886 100644
--- a/imap-send.c
+++ b/imap-send.c
@@ -24,7 +24,7 @@
#include "cache.h"
#include "config.h"
#include "credential.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "run-command.h"
#include "parse-options.h"
#ifdef NO_OPENSSL
@@ -511,7 +511,7 @@ static int nfsnprintf(char *buf, int blen, const char *fmt, ...)
va_start(va, fmt);
if (blen <= 0 || (unsigned)(ret = vsnprintf(buf, blen, fmt, va)) >= (unsigned)blen)
- die("BUG: buffer too small. Please report a bug.");
+ BUG("buffer too small. Please report a bug.");
va_end(va);
return ret;
}
diff --git a/line-log.c b/line-log.c
index ecdce08..fa9cfd5 100644
--- a/line-log.c
+++ b/line-log.c
@@ -816,8 +816,8 @@ static void queue_diffs(struct line_log_data *range,
assert(commit);
DIFF_QUEUE_CLEAR(&diff_queued_diff);
- diff_tree_oid(parent ? &parent->tree->object.oid : NULL,
- &commit->tree->object.oid, "", opt);
+ diff_tree_oid(parent ? get_commit_tree_oid(parent) : NULL,
+ get_commit_tree_oid(commit), "", opt);
if (opt->detect_rename) {
filter_diffs_for_paths(range, 1);
if (diff_might_be_rename())
diff --git a/list-objects-filter.c b/list-objects-filter.c
index 0ec83aa..5b14d27 100644
--- a/list-objects-filter.c
+++ b/list-objects-filter.c
@@ -19,7 +19,7 @@
* in the traversal (until we mark it SEEN). This is a way to
* let us silently de-dup calls to show() in the caller. This
* is subtly different from the "revision.h:SHOWN" and the
- * "sha1_name.c:ONELINE_SEEN" bits. And also different from
+ * "sha1-name.c:ONELINE_SEEN" bits. And also different from
* the non-de-dup usage in pack-bitmap.c
*/
#define FILTER_SHOWN_BUT_REVISIT (1<<21)
@@ -117,7 +117,7 @@ static enum list_objects_filter_result filter_blobs_limit(
assert(obj->type == OBJ_BLOB);
assert((obj->flags & SEEN) == 0);
- t = oid_object_info(&obj->oid, &object_length);
+ t = oid_object_info(the_repository, &obj->oid, &object_length);
if (t != OBJ_BLOB) { /* probably OBJ_NONE */
/*
* We DO NOT have the blob locally, so we cannot
diff --git a/list-objects.c b/list-objects.c
index 168bef6..3eec510 100644
--- a/list-objects.c
+++ b/list-objects.c
@@ -195,7 +195,7 @@ static void mark_edge_parents_uninteresting(struct commit *commit,
struct commit *parent = parents->item;
if (!(parent->object.flags & UNINTERESTING))
continue;
- mark_tree_uninteresting(parent->tree);
+ mark_tree_uninteresting(get_commit_tree(parent));
if (revs->edge_hint && !(parent->object.flags & SHOWN)) {
parent->object.flags |= SHOWN;
show_edge(parent);
@@ -212,7 +212,7 @@ void mark_edges_uninteresting(struct rev_info *revs, show_edge_fn show_edge)
struct commit *commit = list->item;
if (commit->object.flags & UNINTERESTING) {
- mark_tree_uninteresting(commit->tree);
+ mark_tree_uninteresting(get_commit_tree(commit));
if (revs->edge_hint_aggressive && !(commit->object.flags & SHOWN)) {
commit->object.flags |= SHOWN;
show_edge(commit);
@@ -227,7 +227,7 @@ void mark_edges_uninteresting(struct rev_info *revs, show_edge_fn show_edge)
struct commit *commit = (struct commit *)obj;
if (obj->type != OBJ_COMMIT || !(obj->flags & UNINTERESTING))
continue;
- mark_tree_uninteresting(commit->tree);
+ mark_tree_uninteresting(get_commit_tree(commit));
if (!(obj->flags & SHOWN)) {
obj->flags |= SHOWN;
show_edge(commit);
@@ -300,8 +300,8 @@ static void do_traverse(struct rev_info *revs,
* an uninteresting boundary commit may not have its tree
* parsed yet, but we are not going to show them anyway
*/
- if (commit->tree)
- add_pending_tree(revs, commit->tree);
+ if (get_commit_tree(commit))
+ add_pending_tree(revs, get_commit_tree(commit));
show_commit(commit, show_data);
if (revs->tree_blobs_in_commit_order)
diff --git a/lockfile.c b/lockfile.c
index efcb7d7..8e8ab4f 100644
--- a/lockfile.c
+++ b/lockfile.c
@@ -193,7 +193,7 @@ char *get_locked_file_path(struct lock_file *lk)
strbuf_addstr(&ret, get_tempfile_path(lk->tempfile));
if (ret.len <= LOCK_SUFFIX_LEN ||
strcmp(ret.buf + ret.len - LOCK_SUFFIX_LEN, LOCK_SUFFIX))
- die("BUG: get_locked_file_path() called for malformed lock object");
+ BUG("get_locked_file_path() called for malformed lock object");
/* remove ".lock": */
strbuf_setlen(&ret, ret.len - LOCK_SUFFIX_LEN);
return strbuf_detach(&ret, NULL);
diff --git a/log-tree.c b/log-tree.c
index d1c0bed..4aef853 100644
--- a/log-tree.c
+++ b/log-tree.c
@@ -362,7 +362,8 @@ void fmt_output_email_subject(struct strbuf *sb, struct rev_info *opt)
void log_write_email_headers(struct rev_info *opt, struct commit *commit,
const char **extra_headers_p,
- int *need_8bit_cte_p)
+ int *need_8bit_cte_p,
+ int maybe_multipart)
{
const char *extra_headers = opt->extra_headers;
const char *name = oid_to_hex(opt->zero_commit ?
@@ -385,12 +386,16 @@ void log_write_email_headers(struct rev_info *opt, struct commit *commit,
opt->ref_message_ids->items[i].string);
graph_show_oneline(opt->graph);
}
- if (opt->mime_boundary) {
- static char subject_buffer[1024];
- static char buffer[1024];
+ if (opt->mime_boundary && maybe_multipart) {
+ static struct strbuf subject_buffer = STRBUF_INIT;
+ static struct strbuf buffer = STRBUF_INIT;
struct strbuf filename = STRBUF_INIT;
*need_8bit_cte_p = -1; /* NEVER */
- snprintf(subject_buffer, sizeof(subject_buffer) - 1,
+
+ strbuf_reset(&subject_buffer);
+ strbuf_reset(&buffer);
+
+ strbuf_addf(&subject_buffer,
"%s"
"MIME-Version: 1.0\n"
"Content-Type: multipart/mixed;"
@@ -405,13 +410,13 @@ void log_write_email_headers(struct rev_info *opt, struct commit *commit,
extra_headers ? extra_headers : "",
mime_boundary_leader, opt->mime_boundary,
mime_boundary_leader, opt->mime_boundary);
- extra_headers = subject_buffer;
+ extra_headers = subject_buffer.buf;
if (opt->numbered_files)
strbuf_addf(&filename, "%d", opt->nr);
else
fmt_output_commit(&filename, commit, opt);
- snprintf(buffer, sizeof(buffer) - 1,
+ strbuf_addf(&buffer,
"\n--%s%s\n"
"Content-Type: text/x-patch;"
" name=\"%s\"\n"
@@ -422,7 +427,7 @@ void log_write_email_headers(struct rev_info *opt, struct commit *commit,
filename.buf,
opt->no_inline ? "attachment" : "inline",
filename.buf);
- opt->diffopt.stat_sep = buffer;
+ opt->diffopt.stat_sep = buffer.buf;
strbuf_release(&filename);
}
*extra_headers_p = extra_headers;
@@ -488,9 +493,9 @@ static int is_common_merge(const struct commit *commit)
&& !commit->parents->next->next);
}
-static void show_one_mergetag(struct commit *commit,
- struct commit_extra_header *extra,
- void *data)
+static int show_one_mergetag(struct commit *commit,
+ struct commit_extra_header *extra,
+ void *data)
{
struct rev_info *opt = (struct rev_info *)data;
struct object_id oid;
@@ -502,7 +507,7 @@ static void show_one_mergetag(struct commit *commit,
hash_object_file(extra->value, extra->len, type_name(OBJ_TAG), &oid);
tag = lookup_tag(&oid);
if (!tag)
- return; /* error message already given */
+ return -1; /* error message already given */
strbuf_init(&verify_message, 256);
if (parse_tag_buffer(tag, extra->value, extra->len))
@@ -536,11 +541,12 @@ static void show_one_mergetag(struct commit *commit,
show_sig_lines(opt, status, verify_message.buf);
strbuf_release(&verify_message);
+ return 0;
}
-static void show_mergetag(struct rev_info *opt, struct commit *commit)
+static int show_mergetag(struct rev_info *opt, struct commit *commit)
{
- for_each_mergetag(show_one_mergetag, commit, opt);
+ return for_each_mergetag(show_one_mergetag, commit, opt);
}
void show_log(struct rev_info *opt)
@@ -610,7 +616,7 @@ void show_log(struct rev_info *opt)
if (cmit_fmt_is_mail(opt->commit_format)) {
log_write_email_headers(opt, commit, &extra_headers,
- &ctx.need_8bit_cte);
+ &ctx.need_8bit_cte, 1);
ctx.rev = opt;
ctx.print_email_subject = 1;
} else if (opt->commit_format != CMIT_FMT_USERFORMAT) {
@@ -806,7 +812,7 @@ static int log_tree_diff(struct rev_info *opt, struct commit *commit, struct log
return 0;
parse_commit_or_die(commit);
- oid = &commit->tree->object.oid;
+ oid = get_commit_tree_oid(commit);
/* Root commit? */
parents = get_saved_parents(opt, commit);
@@ -831,7 +837,7 @@ static int log_tree_diff(struct rev_info *opt, struct commit *commit, struct log
* we merged _in_.
*/
parse_commit_or_die(parents->item);
- diff_tree_oid(&parents->item->tree->object.oid,
+ diff_tree_oid(get_commit_tree_oid(parents->item),
oid, "", &opt->diffopt);
log_tree_diff_flush(opt);
return !opt->loginfo;
@@ -846,7 +852,7 @@ static int log_tree_diff(struct rev_info *opt, struct commit *commit, struct log
struct commit *parent = parents->item;
parse_commit_or_die(parent);
- diff_tree_oid(&parent->tree->object.oid,
+ diff_tree_oid(get_commit_tree_oid(parent),
oid, "", &opt->diffopt);
log_tree_diff_flush(opt);
diff --git a/log-tree.h b/log-tree.h
index deba035..e668628 100644
--- a/log-tree.h
+++ b/log-tree.h
@@ -27,7 +27,8 @@ void format_decorations_extended(struct strbuf *sb, const struct commit *commit,
void show_decorations(struct rev_info *opt, struct commit *commit);
void log_write_email_headers(struct rev_info *opt, struct commit *commit,
const char **extra_headers_p,
- int *need_8bit_cte_p);
+ int *need_8bit_cte_p,
+ int maybe_multipart);
void load_ref_decorations(struct decoration_filter *filter, int flags);
#define FORMAT_PATCH_NAME_MAX 64
diff --git a/ls-refs.c b/ls-refs.c
new file mode 100644
index 0000000..a06f12e
--- /dev/null
+++ b/ls-refs.c
@@ -0,0 +1,96 @@
+#include "cache.h"
+#include "repository.h"
+#include "refs.h"
+#include "remote.h"
+#include "argv-array.h"
+#include "ls-refs.h"
+#include "pkt-line.h"
+
+/*
+ * Check if one of the prefixes is a prefix of the ref.
+ * If no prefixes were provided, all refs match.
+ */
+static int ref_match(const struct argv_array *prefixes, const char *refname)
+{
+ int i;
+
+ if (!prefixes->argc)
+ return 1; /* no restriction */
+
+ for (i = 0; i < prefixes->argc; i++) {
+ const char *prefix = prefixes->argv[i];
+
+ if (starts_with(refname, prefix))
+ return 1;
+ }
+
+ return 0;
+}
+
+struct ls_refs_data {
+ unsigned peel;
+ unsigned symrefs;
+ struct argv_array prefixes;
+};
+
+static int send_ref(const char *refname, const struct object_id *oid,
+ int flag, void *cb_data)
+{
+ struct ls_refs_data *data = cb_data;
+ const char *refname_nons = strip_namespace(refname);
+ struct strbuf refline = STRBUF_INIT;
+
+ if (!ref_match(&data->prefixes, refname))
+ return 0;
+
+ strbuf_addf(&refline, "%s %s", oid_to_hex(oid), refname_nons);
+ if (data->symrefs && flag & REF_ISSYMREF) {
+ struct object_id unused;
+ const char *symref_target = resolve_ref_unsafe(refname, 0,
+ &unused,
+ &flag);
+
+ if (!symref_target)
+ die("'%s' is a symref but it is not?", refname);
+
+ strbuf_addf(&refline, " symref-target:%s", symref_target);
+ }
+
+ if (data->peel) {
+ struct object_id peeled;
+ if (!peel_ref(refname, &peeled))
+ strbuf_addf(&refline, " peeled:%s", oid_to_hex(&peeled));
+ }
+
+ strbuf_addch(&refline, '\n');
+ packet_write(1, refline.buf, refline.len);
+
+ strbuf_release(&refline);
+ return 0;
+}
+
+int ls_refs(struct repository *r, struct argv_array *keys,
+ struct packet_reader *request)
+{
+ struct ls_refs_data data;
+
+ memset(&data, 0, sizeof(data));
+
+ while (packet_reader_read(request) != PACKET_READ_FLUSH) {
+ const char *arg = request->line;
+ const char *out;
+
+ if (!strcmp("peel", arg))
+ data.peel = 1;
+ else if (!strcmp("symrefs", arg))
+ data.symrefs = 1;
+ else if (skip_prefix(arg, "ref-prefix ", &out))
+ argv_array_push(&data.prefixes, out);
+ }
+
+ head_ref_namespaced(send_ref, &data);
+ for_each_namespaced_ref(send_ref, &data);
+ packet_flush(1);
+ argv_array_clear(&data.prefixes);
+ return 0;
+}
diff --git a/ls-refs.h b/ls-refs.h
new file mode 100644
index 0000000..b62877e
--- /dev/null
+++ b/ls-refs.h
@@ -0,0 +1,10 @@
+#ifndef LS_REFS_H
+#define LS_REFS_H
+
+struct repository;
+struct argv_array;
+struct packet_reader;
+extern int ls_refs(struct repository *r, struct argv_array *keys,
+ struct packet_reader *request);
+
+#endif /* LS_REFS_H */
diff --git a/mailinfo.c b/mailinfo.c
index d04142c..3281a37 100644
--- a/mailinfo.c
+++ b/mailinfo.c
@@ -716,7 +716,7 @@ static void flush_inbody_header_accum(struct mailinfo *mi)
if (!mi->inbody_header_accum.len)
return;
if (!check_header(mi, &mi->inbody_header_accum, mi->s_hdr_data, 0))
- die("BUG: inbody_header_accum, if not empty, must always contain a valid in-body header");
+ BUG("inbody_header_accum, if not empty, must always contain a valid in-body header");
strbuf_reset(&mi->inbody_header_accum);
}
diff --git a/mem-pool.c b/mem-pool.c
new file mode 100644
index 0000000..389d7af
--- /dev/null
+++ b/mem-pool.c
@@ -0,0 +1,55 @@
+/*
+ * Memory Pool implementation logic.
+ */
+
+#include "cache.h"
+#include "mem-pool.h"
+
+static struct mp_block *mem_pool_alloc_block(struct mem_pool *mem_pool, size_t block_alloc)
+{
+ struct mp_block *p;
+
+ mem_pool->pool_alloc += sizeof(struct mp_block) + block_alloc;
+ p = xmalloc(st_add(sizeof(struct mp_block), block_alloc));
+ p->next_block = mem_pool->mp_block;
+ p->next_free = (char *)p->space;
+ p->end = p->next_free + block_alloc;
+ mem_pool->mp_block = p;
+
+ return p;
+}
+
+void *mem_pool_alloc(struct mem_pool *mem_pool, size_t len)
+{
+ struct mp_block *p;
+ void *r;
+
+ /* round up to a 'uintmax_t' alignment */
+ if (len & (sizeof(uintmax_t) - 1))
+ len += sizeof(uintmax_t) - (len & (sizeof(uintmax_t) - 1));
+
+ for (p = mem_pool->mp_block; p; p = p->next_block)
+ if (p->end - p->next_free >= len)
+ break;
+
+ if (!p) {
+ if (len >= (mem_pool->block_alloc / 2)) {
+ mem_pool->pool_alloc += len;
+ return xmalloc(len);
+ }
+
+ p = mem_pool_alloc_block(mem_pool, mem_pool->block_alloc);
+ }
+
+ r = p->next_free;
+ p->next_free += len;
+ return r;
+}
+
+void *mem_pool_calloc(struct mem_pool *mem_pool, size_t count, size_t size)
+{
+ size_t len = st_mult(count, size);
+ void *r = mem_pool_alloc(mem_pool, len);
+ memset(r, 0, len);
+ return r;
+}
diff --git a/mem-pool.h b/mem-pool.h
new file mode 100644
index 0000000..829ad58
--- /dev/null
+++ b/mem-pool.h
@@ -0,0 +1,34 @@
+#ifndef MEM_POOL_H
+#define MEM_POOL_H
+
+struct mp_block {
+ struct mp_block *next_block;
+ char *next_free;
+ char *end;
+ uintmax_t space[FLEX_ARRAY]; /* more */
+};
+
+struct mem_pool {
+ struct mp_block *mp_block;
+
+ /*
+ * The amount of available memory to grow the pool by.
+ * This size does not include the overhead for the mp_block.
+ */
+ size_t block_alloc;
+
+ /* The total amount of memory allocated by the pool. */
+ size_t pool_alloc;
+};
+
+/*
+ * Alloc memory from the mem_pool.
+ */
+void *mem_pool_alloc(struct mem_pool *pool, size_t len);
+
+/*
+ * Allocate and zero memory from the memory pool.
+ */
+void *mem_pool_calloc(struct mem_pool *pool, size_t count, size_t size);
+
+#endif
diff --git a/merge-recursive.c b/merge-recursive.c
index 338f63a..ac27abb 100644
--- a/merge-recursive.c
+++ b/merge-recursive.c
@@ -23,6 +23,7 @@
#include "merge-recursive.h"
#include "dir.h"
#include "submodule.h"
+#include "revision.h"
struct path_hashmap_entry {
struct hashmap_entry e;
@@ -162,7 +163,7 @@ static struct commit *make_virtual_commit(struct tree *tree, const char *comment
struct commit *commit = alloc_commit_node();
set_merge_remote_desc(commit, comment, (struct object *)commit);
- commit->tree = tree;
+ commit->maybe_tree = tree;
commit->object.parsed = 1;
return commit;
}
@@ -398,7 +399,7 @@ struct tree *write_tree_from_memory(struct merge_options *o)
fprintf(stderr, "BUG: %d %.*s\n", ce_stage(ce),
(int)ce_namelen(ce), ce->name);
}
- die("BUG: unmerged index entries in merge-recursive.c");
+ BUG("unmerged index entries in merge-recursive.c");
}
if (!active_cache_tree)
@@ -1088,6 +1089,185 @@ static int merge_3way(struct merge_options *o,
return merge_status;
}
+static int find_first_merges(struct object_array *result, const char *path,
+ struct commit *a, struct commit *b)
+{
+ int i, j;
+ struct object_array merges = OBJECT_ARRAY_INIT;
+ struct commit *commit;
+ int contains_another;
+
+ char merged_revision[42];
+ const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
+ "--all", merged_revision, NULL };
+ struct rev_info revs;
+ struct setup_revision_opt rev_opts;
+
+ memset(result, 0, sizeof(struct object_array));
+ memset(&rev_opts, 0, sizeof(rev_opts));
+
+ /* get all revisions that merge commit a */
+ xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
+ oid_to_hex(&a->object.oid));
+ init_revisions(&revs, NULL);
+ rev_opts.submodule = path;
+ /* FIXME: can't handle linked worktrees in submodules yet */
+ revs.single_worktree = path != NULL;
+ setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
+
+ /* save all revisions from the above list that contain b */
+ if (prepare_revision_walk(&revs))
+ die("revision walk setup failed");
+ while ((commit = get_revision(&revs)) != NULL) {
+ struct object *o = &(commit->object);
+ if (in_merge_bases(b, commit))
+ add_object_array(o, NULL, &merges);
+ }
+ reset_revision_walk();
+
+ /* Now we've got all merges that contain a and b. Prune all
+ * merges that contain another found merge and save them in
+ * result.
+ */
+ for (i = 0; i < merges.nr; i++) {
+ struct commit *m1 = (struct commit *) merges.objects[i].item;
+
+ contains_another = 0;
+ for (j = 0; j < merges.nr; j++) {
+ struct commit *m2 = (struct commit *) merges.objects[j].item;
+ if (i != j && in_merge_bases(m2, m1)) {
+ contains_another = 1;
+ break;
+ }
+ }
+
+ if (!contains_another)
+ add_object_array(merges.objects[i].item, NULL, result);
+ }
+
+ object_array_clear(&merges);
+ return result->nr;
+}
+
+static void print_commit(struct commit *commit)
+{
+ struct strbuf sb = STRBUF_INIT;
+ struct pretty_print_context ctx = {0};
+ ctx.date_mode.type = DATE_NORMAL;
+ format_commit_message(commit, " %h: %m %s", &sb, &ctx);
+ fprintf(stderr, "%s\n", sb.buf);
+ strbuf_release(&sb);
+}
+
+static int merge_submodule(struct merge_options *o,
+ struct object_id *result, const char *path,
+ const struct object_id *base, const struct object_id *a,
+ const struct object_id *b)
+{
+ struct commit *commit_base, *commit_a, *commit_b;
+ int parent_count;
+ struct object_array merges;
+
+ int i;
+ int search = !o->call_depth;
+
+ /* store a in result in case we fail */
+ oidcpy(result, a);
+
+ /* we can not handle deletion conflicts */
+ if (is_null_oid(base))
+ return 0;
+ if (is_null_oid(a))
+ return 0;
+ if (is_null_oid(b))
+ return 0;
+
+ if (add_submodule_odb(path)) {
+ output(o, 1, _("Failed to merge submodule %s (not checked out)"), path);
+ return 0;
+ }
+
+ if (!(commit_base = lookup_commit_reference(base)) ||
+ !(commit_a = lookup_commit_reference(a)) ||
+ !(commit_b = lookup_commit_reference(b))) {
+ output(o, 1, _("Failed to merge submodule %s (commits not present)"), path);
+ return 0;
+ }
+
+ /* check whether both changes are forward */
+ if (!in_merge_bases(commit_base, commit_a) ||
+ !in_merge_bases(commit_base, commit_b)) {
+ output(o, 1, _("Failed to merge submodule %s (commits don't follow merge-base)"), path);
+ return 0;
+ }
+
+ /* Case #1: a is contained in b or vice versa */
+ if (in_merge_bases(commit_a, commit_b)) {
+ oidcpy(result, b);
+ if (show(o, 3)) {
+ output(o, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
+ output_commit_title(o, commit_b);
+ } else if (show(o, 2))
+ output(o, 2, _("Fast-forwarding submodule %s to %s"), path, oid_to_hex(b));
+ else
+ ; /* no output */
+
+ return 1;
+ }
+ if (in_merge_bases(commit_b, commit_a)) {
+ oidcpy(result, a);
+ if (show(o, 3)) {
+ output(o, 3, _("Fast-forwarding submodule %s to the following commit:"), path);
+ output_commit_title(o, commit_a);
+ } else if (show(o, 2))
+ output(o, 2, _("Fast-forwarding submodule %s to %s"), path, oid_to_hex(a));
+ else
+ ; /* no output */
+
+ return 1;
+ }
+
+ /*
+ * Case #2: There are one or more merges that contain a and b in
+ * the submodule. If there is only one, then present it as a
+ * suggestion to the user, but leave it marked unmerged so the
+ * user needs to confirm the resolution.
+ */
+
+ /* Skip the search if makes no sense to the calling context. */
+ if (!search)
+ return 0;
+
+ /* find commit which merges them */
+ parent_count = find_first_merges(&merges, path, commit_a, commit_b);
+ switch (parent_count) {
+ case 0:
+ output(o, 1, _("Failed to merge submodule %s (merge following commits not found)"), path);
+ break;
+
+ case 1:
+ output(o, 1, _("Failed to merge submodule %s (not fast-forward)"), path);
+ output(o, 2, _("Found a possible merge resolution for the submodule:\n"));
+ print_commit((struct commit *) merges.objects[0].item);
+ output(o, 2, _(
+ "If this is correct simply add it to the index "
+ "for example\n"
+ "by using:\n\n"
+ " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
+ "which will accept this suggestion.\n"),
+ oid_to_hex(&merges.objects[0].item->oid), path);
+ break;
+
+ default:
+ output(o, 1, _("Failed to merge submodule %s (multiple merges found)"), path);
+ for (i = 0; i < merges.nr; i++)
+ print_commit((struct commit *) merges.objects[i].item);
+ }
+
+ object_array_clear(&merges);
+ return 0;
+}
+
static int merge_file_1(struct merge_options *o,
const struct diff_filespec *one,
const struct diff_filespec *a,
@@ -1151,12 +1331,11 @@ static int merge_file_1(struct merge_options *o,
return ret;
result->clean = (merge_status == 0);
} else if (S_ISGITLINK(a->mode)) {
- result->clean = merge_submodule(&result->oid,
+ result->clean = merge_submodule(o, &result->oid,
one->path,
&one->oid,
&a->oid,
- &b->oid,
- !o->call_depth);
+ &b->oid);
} else if (S_ISLNK(a->mode)) {
switch (o->recursive_variant) {
case MERGE_RECURSIVE_NORMAL:
@@ -1172,7 +1351,7 @@ static int merge_file_1(struct merge_options *o,
break;
}
} else
- die("BUG: unsupported object type in the tree");
+ BUG("unsupported object type in the tree");
}
if (result->merge)
@@ -2425,7 +2604,7 @@ static int process_renames(struct merge_options *o,
const char *ren2_dst = ren2->pair->two->path;
enum rename_type rename_type;
if (strcmp(ren1_src, ren2_src) != 0)
- die("BUG: ren1_src != ren2_src");
+ BUG("ren1_src != ren2_src");
ren2->dst_entry->processed = 1;
ren2->processed = 1;
if (strcmp(ren1_dst, ren2_dst) != 0) {
@@ -2459,7 +2638,7 @@ static int process_renames(struct merge_options *o,
ren2 = lookup->util;
ren2_dst = ren2->pair->two->path;
if (strcmp(ren1_dst, ren2_dst) != 0)
- die("BUG: ren1_dst != ren2_dst");
+ BUG("ren1_dst != ren2_dst");
clean_merge = 0;
ren2->processed = 1;
@@ -3063,7 +3242,7 @@ static int process_entry(struct merge_options *o,
*/
remove_file(o, 1, path, !a_mode);
} else
- die("BUG: fatal merge failure, shouldn't happen.");
+ BUG("fatal merge failure, shouldn't happen.");
return clean_merge;
}
@@ -3142,7 +3321,7 @@ int merge_trees(struct merge_options *o,
for (i = 0; i < entries->nr; i++) {
struct stage_data *e = entries->items[i].util;
if (!e->processed)
- die("BUG: unprocessed path??? %s",
+ BUG("unprocessed path??? %s",
entries->items[i].string);
}
@@ -3257,7 +3436,8 @@ int merge_recursive(struct merge_options *o,
read_cache();
o->ancestor = "merged common ancestors";
- clean = merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree,
+ clean = merge_trees(o, get_commit_tree(h1), get_commit_tree(h2),
+ get_commit_tree(merged_common_ancestors),
&mrtree);
if (clean < 0) {
flush_output(o);
diff --git a/merge.c b/merge.c
index b433291..0783858 100644
--- a/merge.c
+++ b/merge.c
@@ -11,10 +11,7 @@
static const char *merge_argument(struct commit *commit)
{
- if (commit)
- return oid_to_hex(&commit->object.oid);
- else
- return EMPTY_TREE_SHA1_HEX;
+ return oid_to_hex(commit ? &commit->object.oid : the_hash_algo->empty_tree);
}
int index_has_changes(struct strbuf *sb)
diff --git a/mergetools/guiffy b/mergetools/guiffy
new file mode 100644
index 0000000..8b23a13
--- /dev/null
+++ b/mergetools/guiffy
@@ -0,0 +1,18 @@
+diff_cmd () {
+ "$merge_tool_path" "$LOCAL" "$REMOTE"
+}
+
+merge_cmd () {
+ if $base_present
+ then
+ "$merge_tool_path" -s "$LOCAL" \
+ "$REMOTE" "$BASE" "$MERGED"
+ else
+ "$merge_tool_path" -m "$LOCAL" \
+ "$REMOTE" "$MERGED"
+ fi
+}
+
+exit_code_trustable () {
+ true
+}
diff --git a/notes-merge.c b/notes-merge.c
index 8e0726a..d613e06 100644
--- a/notes-merge.c
+++ b/notes-merge.c
@@ -442,7 +442,7 @@ static int merge_one_change(struct notes_merge_options *o,
printf("Using remote notes for %s\n",
oid_to_hex(&p->obj));
if (add_note(t, &p->obj, &p->remote, combine_notes_overwrite))
- die("BUG: combine_notes_overwrite failed");
+ BUG("combine_notes_overwrite failed");
return 0;
case NOTES_MERGE_RESOLVE_UNION:
if (o->verbosity >= 2)
@@ -490,7 +490,7 @@ static int merge_changes(struct notes_merge_options *o,
trace_printf("\t\t\tno local change, adopted remote\n");
if (add_note(t, &p->obj, &p->remote,
combine_notes_overwrite))
- die("BUG: combine_notes_overwrite failed");
+ BUG("combine_notes_overwrite failed");
} else {
/* need file-level merge between local and remote */
trace_printf("\t\t\tneed content-level merge\n");
@@ -600,14 +600,14 @@ int notes_merge(struct notes_merge_options *o,
printf("No merge base found; doing history-less merge\n");
} else if (!bases->next) {
base_oid = &bases->item->object.oid;
- base_tree_oid = &bases->item->tree->object.oid;
+ base_tree_oid = get_commit_tree_oid(bases->item);
if (o->verbosity >= 4)
printf("One merge base found (%.7s)\n",
oid_to_hex(base_oid));
} else {
/* TODO: How to handle multiple merge-bases? */
base_oid = &bases->item->object.oid;
- base_tree_oid = &bases->item->tree->object.oid;
+ base_tree_oid = get_commit_tree_oid(bases->item);
if (o->verbosity >= 3)
printf("Multiple merge bases found. Using the first "
"(%.7s)\n", oid_to_hex(base_oid));
@@ -634,8 +634,9 @@ int notes_merge(struct notes_merge_options *o,
goto found_result;
}
- result = merge_from_diffs(o, base_tree_oid, &local->tree->object.oid,
- &remote->tree->object.oid, local_tree);
+ result = merge_from_diffs(o, base_tree_oid,
+ get_commit_tree_oid(local),
+ get_commit_tree_oid(remote), local_tree);
if (result != 0) { /* non-trivial merge (with or without conflicts) */
/* Commit (partial) result */
diff --git a/object-store.h b/object-store.h
index fef33f3..d683112 100644
--- a/object-store.h
+++ b/object-store.h
@@ -1,6 +1,8 @@
#ifndef OBJECT_STORE_H
#define OBJECT_STORE_H
+#include "oidmap.h"
+
struct alternate_object_database {
struct alternate_object_database *next;
@@ -69,8 +71,10 @@ struct packed_git {
int index_version;
time_t mtime;
int pack_fd;
+ int index; /* for builtin/pack-objects.c */
unsigned pack_local:1,
pack_keep:1,
+ pack_keep_in_core:1,
freshened:1,
do_not_close:1,
pack_promisor:1;
@@ -94,6 +98,12 @@ struct raw_object_store {
struct alternate_object_database **alt_odb_tail;
/*
+ * Objects that should be substituted by other objects
+ * (see git-replace(1)).
+ */
+ struct oidmap *replace_map;
+
+ /*
* private data
*
* should only be accessed directly by packfile.c
diff --git a/object.c b/object.c
index a0a756f..f7f4de3 100644
--- a/object.c
+++ b/object.c
@@ -1,5 +1,6 @@
#include "cache.h"
#include "object.h"
+#include "replace-object.h"
#include "blob.h"
#include "tree.h"
#include "commit.h"
@@ -246,7 +247,7 @@ struct object *parse_object(const struct object_id *oid)
unsigned long size;
enum object_type type;
int eaten;
- const struct object_id *repl = lookup_replace_object(oid);
+ const struct object_id *repl = lookup_replace_object(the_repository, oid);
void *buffer;
struct object *obj;
@@ -256,7 +257,7 @@ struct object *parse_object(const struct object_id *oid)
if ((obj && obj->type == OBJ_BLOB && has_object_file(oid)) ||
(!obj && has_object_file(oid) &&
- oid_object_info(oid, NULL) == OBJ_BLOB)) {
+ oid_object_info(the_repository, oid, NULL) == OBJ_BLOB)) {
if (check_object_signature(repl, NULL, 0, NULL) < 0) {
error("sha1 mismatch %s", oid_to_hex(oid));
return NULL;
@@ -480,6 +481,9 @@ void raw_object_store_clear(struct raw_object_store *o)
FREE_AND_NULL(o->objectdir);
FREE_AND_NULL(o->alternate_db);
+ oidmap_free(o->replace_map, 1);
+ FREE_AND_NULL(o->replace_map);
+
free_alt_odbs(o);
o->alt_odb_tail = NULL;
diff --git a/object.h b/object.h
index f13f85b..5c13955 100644
--- a/object.h
+++ b/object.h
@@ -25,7 +25,6 @@ struct object_array {
#define OBJECT_ARRAY_INIT { 0, 0, NULL }
-#define TYPE_BITS 3
/*
* object flag allocation:
* revision.h: 0---------10 26
@@ -37,7 +36,7 @@ struct object_array {
* bundle.c: 16
* http-push.c: 16-----19
* commit.c: 16-----19
- * sha1_name.c: 20
+ * sha1-name.c: 20
* list-objects-filter.c: 21
* builtin/fsck.c: 0--3
* builtin/index-pack.c: 2021
diff --git a/pack-bitmap-write.c b/pack-bitmap-write.c
index 41ae27f..7b2dc3e 100644
--- a/pack-bitmap-write.c
+++ b/pack-bitmap-write.c
@@ -48,7 +48,8 @@ void bitmap_writer_show_progress(int show)
/**
* Build the initial type index for the packfile
*/
-void bitmap_writer_build_type_index(struct pack_idx_entry **index,
+void bitmap_writer_build_type_index(struct packing_data *to_pack,
+ struct pack_idx_entry **index,
uint32_t index_nr)
{
uint32_t i;
@@ -57,23 +58,25 @@ void bitmap_writer_build_type_index(struct pack_idx_entry **index,
writer.trees = ewah_new();
writer.blobs = ewah_new();
writer.tags = ewah_new();
+ ALLOC_ARRAY(to_pack->in_pack_pos, to_pack->nr_objects);
for (i = 0; i < index_nr; ++i) {
struct object_entry *entry = (struct object_entry *)index[i];
enum object_type real_type;
- entry->in_pack_pos = i;
+ oe_set_in_pack_pos(to_pack, entry, i);
- switch (entry->type) {
+ switch (oe_type(entry)) {
case OBJ_COMMIT:
case OBJ_TREE:
case OBJ_BLOB:
case OBJ_TAG:
- real_type = entry->type;
+ real_type = oe_type(entry);
break;
default:
- real_type = oid_object_info(&entry->idx.oid, NULL);
+ real_type = oid_object_info(the_repository,
+ &entry->idx.oid, NULL);
break;
}
@@ -97,7 +100,7 @@ void bitmap_writer_build_type_index(struct pack_idx_entry **index,
default:
die("Missing type information for %s (%d/%d)",
oid_to_hex(&entry->idx.oid), real_type,
- entry->type);
+ oe_type(entry));
}
}
}
@@ -146,7 +149,7 @@ static uint32_t find_object_pos(const unsigned char *sha1)
"(object %s is missing)", sha1_to_hex(sha1));
}
- return entry->in_pack_pos;
+ return oe_in_pack_pos(writer.to_pack, entry);
}
static void show_object(struct object *object, const char *name, void *data)
@@ -474,7 +477,7 @@ static void write_selected_commits_v1(struct hashfile *f,
sha1_pos(stored->commit->object.oid.hash, index, index_nr, sha1_access);
if (commit_pos < 0)
- die("BUG: trying to write commit not in index");
+ BUG("trying to write commit not in index");
hashwrite_be32(f, commit_pos);
hashwrite_u8(f, stored->xor_offset);
@@ -534,7 +537,7 @@ void bitmap_writer_finish(struct pack_idx_entry **index,
if (options & BITMAP_OPT_HASH_CACHE)
write_hash_cache(f, index, index_nr);
- hashclose(f, NULL, CSUM_FSYNC);
+ finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_FSYNC | CSUM_CLOSE);
if (adjust_shared_perm(tmp_file.buf))
die_errno("unable to make temporary bitmap file readable");
diff --git a/pack-bitmap.c b/pack-bitmap.c
index 3f2dab3..0677111 100644
--- a/pack-bitmap.c
+++ b/pack-bitmap.c
@@ -255,7 +255,7 @@ static char *pack_bitmap_filename(struct packed_git *p)
size_t len;
if (!strip_suffix(p->pack_name, ".pack", &len))
- die("BUG: pack_name does not end in .pack");
+ BUG("pack_name does not end in .pack");
return xstrfmt("%.*s.bitmap", (int)len, p->pack_name);
}
@@ -723,13 +723,13 @@ int prepare_bitmap_walk(struct rev_info *revs)
revs->ignore_missing_links = 0;
if (haves_bitmap == NULL)
- die("BUG: failed to perform bitmap walk");
+ BUG("failed to perform bitmap walk");
}
wants_bitmap = find_objects(revs, wants, haves_bitmap);
if (!wants_bitmap)
- die("BUG: failed to perform bitmap walk");
+ BUG("failed to perform bitmap walk");
if (haves_bitmap)
bitmap_and_not(wants_bitmap, haves_bitmap);
@@ -1033,7 +1033,7 @@ int rebuild_existing_bitmaps(struct packing_data *mapping,
oe = packlist_find(mapping, sha1, NULL);
if (oe)
- reposition[i] = oe->in_pack_pos + 1;
+ reposition[i] = oe_in_pack_pos(mapping, oe) + 1;
}
rebuild = bitmap_new();
diff --git a/pack-bitmap.h b/pack-bitmap.h
index 3742a00..5ded2f1 100644
--- a/pack-bitmap.h
+++ b/pack-bitmap.h
@@ -44,7 +44,9 @@ int rebuild_existing_bitmaps(struct packing_data *mapping, khash_sha1 *reused_bi
void bitmap_writer_show_progress(int show);
void bitmap_writer_set_checksum(unsigned char *sha1);
-void bitmap_writer_build_type_index(struct pack_idx_entry **index, uint32_t index_nr);
+void bitmap_writer_build_type_index(struct packing_data *to_pack,
+ struct pack_idx_entry **index,
+ uint32_t index_nr);
void bitmap_writer_reuse_bitmaps(struct packing_data *to_pack);
void bitmap_writer_select_commits(struct commit **indexed_commits,
unsigned int indexed_commits_nr, int max_bitmaps);
diff --git a/pack-check.c b/pack-check.c
index 385d964..d3a57df 100644
--- a/pack-check.c
+++ b/pack-check.c
@@ -1,4 +1,5 @@
#include "cache.h"
+#include "repository.h"
#include "pack.h"
#include "pack-revindex.h"
#include "progress.h"
@@ -134,7 +135,7 @@ static int verify_packfile(struct packed_git *p,
data = NULL;
data_valid = 0;
} else {
- data = unpack_entry(p, entries[i].offset, &type, &size);
+ data = unpack_entry(the_repository, p, entries[i].offset, &type, &size);
data_valid = 1;
}
diff --git a/pack-objects.c b/pack-objects.c
index 9558d13..9270852 100644
--- a/pack-objects.c
+++ b/pack-objects.c
@@ -2,6 +2,8 @@
#include "object.h"
#include "pack.h"
#include "pack-objects.h"
+#include "packfile.h"
+#include "config.h"
static uint32_t locate_object_entry_hash(struct packing_data *pdata,
const unsigned char *sha1,
@@ -58,7 +60,7 @@ static void rehash_objects(struct packing_data *pdata)
&found);
if (found)
- die("BUG: Duplicate object in hash");
+ BUG("Duplicate object in hash");
pdata->index[ix] = i + 1;
entry++;
@@ -86,6 +88,66 @@ struct object_entry *packlist_find(struct packing_data *pdata,
return &pdata->objects[pdata->index[i] - 1];
}
+static void prepare_in_pack_by_idx(struct packing_data *pdata)
+{
+ struct packed_git **mapping, *p;
+ int cnt = 0, nr = 1U << OE_IN_PACK_BITS;
+
+ ALLOC_ARRAY(mapping, nr);
+ /*
+ * oe_in_pack() on an all-zero'd object_entry
+ * (i.e. in_pack_idx also zero) should return NULL.
+ */
+ mapping[cnt++] = NULL;
+ for (p = get_packed_git(the_repository); p; p = p->next, cnt++) {
+ if (cnt == nr) {
+ free(mapping);
+ return;
+ }
+ p->index = cnt;
+ mapping[cnt] = p;
+ }
+ pdata->in_pack_by_idx = mapping;
+}
+
+/*
+ * A new pack appears after prepare_in_pack_by_idx() has been
+ * run. This is likely a race.
+ *
+ * We could map this new pack to in_pack_by_idx[] array, but then we
+ * have to deal with full array anyway. And since it's hard to test
+ * this fall back code, just stay simple and fall back to using
+ * in_pack[] array.
+ */
+void oe_map_new_pack(struct packing_data *pack,
+ struct packed_git *p)
+{
+ uint32_t i;
+
+ REALLOC_ARRAY(pack->in_pack, pack->nr_alloc);
+
+ for (i = 0; i < pack->nr_objects; i++)
+ pack->in_pack[i] = oe_in_pack(pack, pack->objects + i);
+
+ FREE_AND_NULL(pack->in_pack_by_idx);
+}
+
+/* assume pdata is already zero'd by caller */
+void prepare_packing_data(struct packing_data *pdata)
+{
+ if (git_env_bool("GIT_TEST_FULL_IN_PACK_ARRAY", 0)) {
+ /*
+ * do not initialize in_pack_by_idx[] to force the
+ * slow path in oe_in_pack()
+ */
+ } else {
+ prepare_in_pack_by_idx(pdata);
+ }
+
+ pdata->oe_size_limit = git_env_ulong("GIT_TEST_OE_SIZE",
+ 1U << OE_SIZE_BITS);
+}
+
struct object_entry *packlist_alloc(struct packing_data *pdata,
const unsigned char *sha1,
uint32_t index_pos)
@@ -95,6 +157,9 @@ struct object_entry *packlist_alloc(struct packing_data *pdata,
if (pdata->nr_objects >= pdata->nr_alloc) {
pdata->nr_alloc = (pdata->nr_alloc + 1024) * 3 / 2;
REALLOC_ARRAY(pdata->objects, pdata->nr_alloc);
+
+ if (!pdata->in_pack_by_idx)
+ REALLOC_ARRAY(pdata->in_pack, pdata->nr_alloc);
}
new_entry = pdata->objects + pdata->nr_objects++;
@@ -107,5 +172,8 @@ struct object_entry *packlist_alloc(struct packing_data *pdata,
else
pdata->index[index_pos] = pdata->nr_objects;
+ if (pdata->in_pack)
+ pdata->in_pack[pdata->nr_objects - 1] = NULL;
+
return new_entry;
}
diff --git a/pack-objects.h b/pack-objects.h
index 03f1191..edf74da 100644
--- a/pack-objects.h
+++ b/pack-objects.h
@@ -1,45 +1,125 @@
#ifndef PACK_OBJECTS_H
#define PACK_OBJECTS_H
+#include "object-store.h"
+
+#define DEFAULT_DELTA_CACHE_SIZE (256 * 1024 * 1024)
+
+#define OE_DFS_STATE_BITS 2
+#define OE_DEPTH_BITS 12
+#define OE_IN_PACK_BITS 10
+#define OE_Z_DELTA_BITS 20
+/*
+ * Note that oe_set_size() becomes expensive when the given size is
+ * above this limit. Don't lower it too much.
+ */
+#define OE_SIZE_BITS 31
+#define OE_DELTA_SIZE_BITS 20
+
+/*
+ * State flags for depth-first search used for analyzing delta cycles.
+ *
+ * The depth is measured in delta-links to the base (so if A is a delta
+ * against B, then A has a depth of 1, and B a depth of 0).
+ */
+enum dfs_state {
+ DFS_NONE = 0,
+ DFS_ACTIVE,
+ DFS_DONE,
+ DFS_NUM_STATES
+};
+
+/*
+ * The size of struct nearly determines pack-objects's memory
+ * consumption. This struct is packed tight for that reason. When you
+ * add or reorder something in this struct, think a bit about this.
+ *
+ * basic object info
+ * -----------------
+ * idx.oid is filled up before delta searching starts. idx.crc32 is
+ * only valid after the object is written out and will be used for
+ * generating the index. idx.offset will be both gradually set and
+ * used in writing phase (base objects get offset first, then deltas
+ * refer to them)
+ *
+ * "size" is the uncompressed object size. Compressed size of the raw
+ * data for an object in a pack is not stored anywhere but is computed
+ * and made available when reverse .idx is made. Note that when a
+ * delta is reused, "size" is the uncompressed _delta_ size, not the
+ * canonical one after the delta has been applied.
+ *
+ * "hash" contains a path name hash which is used for sorting the
+ * delta list and also during delta searching. Once prepare_pack()
+ * returns it's no longer needed.
+ *
+ * source pack info
+ * ----------------
+ * The (in_pack, in_pack_offset) tuple contains the location of the
+ * object in the source pack. in_pack_header_size allows quickly
+ * skipping the header and going straight to the zlib stream.
+ *
+ * "type" and "in_pack_type" both describe object type. in_pack_type
+ * may contain a delta type, while type is always the canonical type.
+ *
+ * deltas
+ * ------
+ * Delta links (delta, delta_child and delta_sibling) are created to
+ * reflect that delta graph from the source pack then updated or added
+ * during delta searching phase when we find better deltas.
+ *
+ * delta_child and delta_sibling are last needed in
+ * compute_write_order(). "delta" and "delta_size" must remain valid
+ * at object writing phase in case the delta is not cached.
+ *
+ * If a delta is cached in memory and is compressed, delta_data points
+ * to the data and z_delta_size contains the compressed size. If it's
+ * uncompressed [1], z_delta_size must be zero. delta_size is always
+ * the uncompressed size and must be valid even if the delta is not
+ * cached.
+ *
+ * [1] during try_delta phase we don't bother with compressing because
+ * the delta could be quickly replaced with a better one.
+ */
struct object_entry {
struct pack_idx_entry idx;
- unsigned long size; /* uncompressed size */
- struct packed_git *in_pack; /* already in pack */
- off_t in_pack_offset;
- struct object_entry *delta; /* delta base object */
- struct object_entry *delta_child; /* deltified objects who bases me */
- struct object_entry *delta_sibling; /* other deltified objects who
- * uses the same base as me
- */
void *delta_data; /* cached delta (uncompressed) */
- unsigned long delta_size; /* delta data size (uncompressed) */
- unsigned long z_delta_size; /* delta data size (compressed) */
- enum object_type type;
- enum object_type in_pack_type; /* could be delta */
+ off_t in_pack_offset;
uint32_t hash; /* name hint hash */
- unsigned int in_pack_pos;
- unsigned char in_pack_header_size;
+ unsigned size_:OE_SIZE_BITS;
+ unsigned size_valid:1;
+ uint32_t delta_idx; /* delta base object */
+ uint32_t delta_child_idx; /* deltified objects who bases me */
+ uint32_t delta_sibling_idx; /* other deltified objects who
+ * uses the same base as me
+ */
+ unsigned delta_size_:OE_DELTA_SIZE_BITS; /* delta data size (uncompressed) */
+ unsigned delta_size_valid:1;
+ unsigned in_pack_idx:OE_IN_PACK_BITS; /* already in pack */
+ unsigned z_delta_size:OE_Z_DELTA_BITS;
+ unsigned type_valid:1;
+ unsigned type_:TYPE_BITS;
+ unsigned no_try_delta:1;
+ unsigned in_pack_type:TYPE_BITS; /* could be delta */
unsigned preferred_base:1; /*
* we do not pack this, but is available
* to be used as the base object to delta
* objects against.
*/
- unsigned no_try_delta:1;
unsigned tagged:1; /* near the very tip of refs */
unsigned filled:1; /* assigned write-order */
+ unsigned dfs_state:OE_DFS_STATE_BITS;
+ unsigned char in_pack_header_size;
+ unsigned depth:OE_DEPTH_BITS;
/*
- * State flags for depth-first search used for analyzing delta cycles.
+ * pahole results on 64-bit linux (gcc and clang)
+ *
+ * size: 80, bit_padding: 20 bits, holes: 8 bits
+ *
+ * and on 32-bit (gcc)
*
- * The depth is measured in delta-links to the base (so if A is a delta
- * against B, then A has a depth of 1, and B a depth of 0).
+ * size: 76, bit_padding: 20 bits, holes: 8 bits
*/
- enum {
- DFS_NONE = 0,
- DFS_ACTIVE,
- DFS_DONE
- } dfs_state;
- int depth;
};
struct packing_data {
@@ -48,8 +128,22 @@ struct packing_data {
int32_t *index;
uint32_t index_size;
+
+ unsigned int *in_pack_pos;
+
+ /*
+ * Only one of these can be non-NULL and they have different
+ * sizes. if in_pack_by_idx is allocated, oe_in_pack() returns
+ * the pack of an object using in_pack_idx field. If not,
+ * in_pack[] array is used the same way as in_pack_pos[]
+ */
+ struct packed_git **in_pack_by_idx;
+ struct packed_git **in_pack;
+
+ uintmax_t oe_size_limit;
};
+void prepare_packing_data(struct packing_data *pdata);
struct object_entry *packlist_alloc(struct packing_data *pdata,
const unsigned char *sha1,
uint32_t index_pos);
@@ -78,4 +172,178 @@ static inline uint32_t pack_name_hash(const char *name)
return hash;
}
+static inline enum object_type oe_type(const struct object_entry *e)
+{
+ return e->type_valid ? e->type_ : OBJ_BAD;
+}
+
+static inline void oe_set_type(struct object_entry *e,
+ enum object_type type)
+{
+ if (type >= OBJ_ANY)
+ BUG("OBJ_ANY cannot be set in pack-objects code");
+
+ e->type_valid = type >= OBJ_NONE;
+ e->type_ = (unsigned)type;
+}
+
+static inline unsigned int oe_in_pack_pos(const struct packing_data *pack,
+ const struct object_entry *e)
+{
+ return pack->in_pack_pos[e - pack->objects];
+}
+
+static inline void oe_set_in_pack_pos(const struct packing_data *pack,
+ const struct object_entry *e,
+ unsigned int pos)
+{
+ pack->in_pack_pos[e - pack->objects] = pos;
+}
+
+static inline struct packed_git *oe_in_pack(const struct packing_data *pack,
+ const struct object_entry *e)
+{
+ if (pack->in_pack_by_idx)
+ return pack->in_pack_by_idx[e->in_pack_idx];
+ else
+ return pack->in_pack[e - pack->objects];
+}
+
+void oe_map_new_pack(struct packing_data *pack,
+ struct packed_git *p);
+static inline void oe_set_in_pack(struct packing_data *pack,
+ struct object_entry *e,
+ struct packed_git *p)
+{
+ if (!p->index)
+ oe_map_new_pack(pack, p);
+ if (pack->in_pack_by_idx)
+ e->in_pack_idx = p->index;
+ else
+ pack->in_pack[e - pack->objects] = p;
+}
+
+static inline struct object_entry *oe_delta(
+ const struct packing_data *pack,
+ const struct object_entry *e)
+{
+ if (e->delta_idx)
+ return &pack->objects[e->delta_idx - 1];
+ return NULL;
+}
+
+static inline void oe_set_delta(struct packing_data *pack,
+ struct object_entry *e,
+ struct object_entry *delta)
+{
+ if (delta)
+ e->delta_idx = (delta - pack->objects) + 1;
+ else
+ e->delta_idx = 0;
+}
+
+static inline struct object_entry *oe_delta_child(
+ const struct packing_data *pack,
+ const struct object_entry *e)
+{
+ if (e->delta_child_idx)
+ return &pack->objects[e->delta_child_idx - 1];
+ return NULL;
+}
+
+static inline void oe_set_delta_child(struct packing_data *pack,
+ struct object_entry *e,
+ struct object_entry *delta)
+{
+ if (delta)
+ e->delta_child_idx = (delta - pack->objects) + 1;
+ else
+ e->delta_child_idx = 0;
+}
+
+static inline struct object_entry *oe_delta_sibling(
+ const struct packing_data *pack,
+ const struct object_entry *e)
+{
+ if (e->delta_sibling_idx)
+ return &pack->objects[e->delta_sibling_idx - 1];
+ return NULL;
+}
+
+static inline void oe_set_delta_sibling(struct packing_data *pack,
+ struct object_entry *e,
+ struct object_entry *delta)
+{
+ if (delta)
+ e->delta_sibling_idx = (delta - pack->objects) + 1;
+ else
+ e->delta_sibling_idx = 0;
+}
+
+unsigned long oe_get_size_slow(struct packing_data *pack,
+ const struct object_entry *e);
+static inline unsigned long oe_size(struct packing_data *pack,
+ const struct object_entry *e)
+{
+ if (e->size_valid)
+ return e->size_;
+
+ return oe_get_size_slow(pack, e);
+}
+
+static inline int oe_size_less_than(struct packing_data *pack,
+ const struct object_entry *lhs,
+ unsigned long rhs)
+{
+ if (lhs->size_valid)
+ return lhs->size_ < rhs;
+ if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
+ return 0;
+ return oe_get_size_slow(pack, lhs) < rhs;
+}
+
+static inline int oe_size_greater_than(struct packing_data *pack,
+ const struct object_entry *lhs,
+ unsigned long rhs)
+{
+ if (lhs->size_valid)
+ return lhs->size_ > rhs;
+ if (rhs < pack->oe_size_limit) /* rhs < 2^x <= lhs ? */
+ return 1;
+ return oe_get_size_slow(pack, lhs) > rhs;
+}
+
+static inline void oe_set_size(struct packing_data *pack,
+ struct object_entry *e,
+ unsigned long size)
+{
+ if (size < pack->oe_size_limit) {
+ e->size_ = size;
+ e->size_valid = 1;
+ } else {
+ e->size_valid = 0;
+ if (oe_get_size_slow(pack, e) != size)
+ BUG("'size' is supposed to be the object size!");
+ }
+}
+
+static inline unsigned long oe_delta_size(struct packing_data *pack,
+ const struct object_entry *e)
+{
+ if (e->delta_size_valid)
+ return e->delta_size_;
+ return oe_size(pack, e);
+}
+
+static inline void oe_set_delta_size(struct packing_data *pack,
+ struct object_entry *e,
+ unsigned long size)
+{
+ e->delta_size_ = size;
+ e->delta_size_valid = e->delta_size_ == size;
+ if (!e->delta_size_valid && size != oe_size(pack, e))
+ BUG("this can only happen in check_object() "
+ "where delta size is the same as entry size");
+}
+
#endif
diff --git a/pack-write.c b/pack-write.c
index d775c74..a9d46bc 100644
--- a/pack-write.c
+++ b/pack-write.c
@@ -170,8 +170,9 @@ const char *write_idx_file(const char *index_name, struct pack_idx_entry **objec
}
hashwrite(f, sha1, the_hash_algo->rawsz);
- hashclose(f, NULL, ((opts->flags & WRITE_IDX_VERIFY)
- ? CSUM_CLOSE : CSUM_FSYNC));
+ finalize_hashfile(f, NULL, CSUM_HASH_IN_STREAM | CSUM_CLOSE |
+ ((opts->flags & WRITE_IDX_VERIFY)
+ ? 0 : CSUM_FSYNC));
return index_name;
}
diff --git a/packfile.c b/packfile.c
index 0bc67d0..1a714fb 100644
--- a/packfile.c
+++ b/packfile.c
@@ -84,6 +84,7 @@ static int check_packed_git_idx(const char *path, struct packed_git *p)
uint32_t version, nr, i, *index;
int fd = git_open(path);
struct stat st;
+ const unsigned int hashsz = the_hash_algo->rawsz;
if (fd < 0)
return -1;
@@ -92,7 +93,7 @@ static int check_packed_git_idx(const char *path, struct packed_git *p)
return -1;
}
idx_size = xsize_t(st.st_size);
- if (idx_size < 4 * 256 + 20 + 20) {
+ if (idx_size < 4 * 256 + hashsz + hashsz) {
close(fd);
return error("index file %s is too small", path);
}
@@ -129,11 +130,11 @@ static int check_packed_git_idx(const char *path, struct packed_git *p)
/*
* Total size:
* - 256 index entries 4 bytes each
- * - 24-byte entries * nr (20-byte sha1 + 4-byte offset)
- * - 20-byte SHA1 of the packfile
- * - 20-byte SHA1 file checksum
+ * - 24-byte entries * nr (object ID + 4-byte offset)
+ * - hash of the packfile
+ * - file checksum
*/
- if (idx_size != 4*256 + nr * 24 + 20 + 20) {
+ if (idx_size != 4*256 + nr * (hashsz + 4) + hashsz + hashsz) {
munmap(idx_map, idx_size);
return error("wrong index v1 file size in %s", path);
}
@@ -142,16 +143,16 @@ static int check_packed_git_idx(const char *path, struct packed_git *p)
* Minimum size:
* - 8 bytes of header
* - 256 index entries 4 bytes each
- * - 20-byte sha1 entry * nr
+ * - object ID entry * nr
* - 4-byte crc entry * nr
* - 4-byte offset entry * nr
- * - 20-byte SHA1 of the packfile
- * - 20-byte SHA1 file checksum
+ * - hash of the packfile
+ * - file checksum
* And after the 4-byte offset table might be a
* variable sized table containing 8-byte entries
* for offsets larger than 2^31.
*/
- unsigned long min_size = 8 + 4*256 + nr*(20 + 4 + 4) + 20 + 20;
+ unsigned long min_size = 8 + 4*256 + nr*(hashsz + 4 + 4) + hashsz + hashsz;
unsigned long max_size = min_size;
if (nr)
max_size += (nr - 1)*8;
@@ -188,7 +189,7 @@ int open_pack_index(struct packed_git *p)
return 0;
if (!strip_suffix(p->pack_name, ".pack", &len))
- die("BUG: pack_name does not end in .pack");
+ BUG("pack_name does not end in .pack");
idx_name = xstrfmt("%.*s.idx", (int)len, p->pack_name);
ret = check_packed_git_idx(idx_name, p);
free(idx_name);
@@ -304,7 +305,7 @@ void close_pack_index(struct packed_git *p)
}
}
-static void close_pack(struct packed_git *p)
+void close_pack(struct packed_git *p)
{
close_pack_windows(p);
close_pack_fd(p);
@@ -317,7 +318,7 @@ void close_all_packs(struct raw_object_store *o)
for (p = o->packed_git; p; p = p->next)
if (p->do_not_close)
- die("BUG: want to close pack marked 'do-not-close'");
+ BUG("want to close pack marked 'do-not-close'");
else
close_pack(p);
}
@@ -444,10 +445,11 @@ static int open_packed_git_1(struct packed_git *p)
{
struct stat st;
struct pack_header hdr;
- unsigned char sha1[20];
- unsigned char *idx_sha1;
+ unsigned char hash[GIT_MAX_RAWSZ];
+ unsigned char *idx_hash;
long fd_flag;
ssize_t read_result;
+ const unsigned hashsz = the_hash_algo->rawsz;
if (!p->index_data && open_pack_index(p))
return error("packfile %s index unavailable", p->pack_name);
@@ -507,15 +509,15 @@ static int open_packed_git_1(struct packed_git *p)
" while index indicates %"PRIu32" objects",
p->pack_name, ntohl(hdr.hdr_entries),
p->num_objects);
- if (lseek(p->pack_fd, p->pack_size - sizeof(sha1), SEEK_SET) == -1)
+ if (lseek(p->pack_fd, p->pack_size - hashsz, SEEK_SET) == -1)
return error("end of packfile %s is unavailable", p->pack_name);
- read_result = read_in_full(p->pack_fd, sha1, sizeof(sha1));
+ read_result = read_in_full(p->pack_fd, hash, hashsz);
if (read_result < 0)
return error_errno("error reading from %s", p->pack_name);
- if (read_result != sizeof(sha1))
+ if (read_result != hashsz)
return error("packfile %s signature is unavailable", p->pack_name);
- idx_sha1 = ((unsigned char *)p->index_data) + p->index_size - 40;
- if (hashcmp(sha1, idx_sha1))
+ idx_hash = ((unsigned char *)p->index_data) + p->index_size - hashsz * 2;
+ if (hashcmp(hash, idx_hash))
return error("packfile %s does not match index", p->pack_name);
return 0;
}
@@ -530,7 +532,7 @@ static int open_packed_git(struct packed_git *p)
static int in_window(struct pack_window *win, off_t offset)
{
- /* We must promise at least 20 bytes (one hash) after the
+ /* We must promise at least one full hash after the
* offset is available from this window, otherwise the offset
* is not actually in this window and a different window (which
* has that one hash excess) must be used. This is to support
@@ -538,7 +540,7 @@ static int in_window(struct pack_window *win, off_t offset)
*/
off_t win_off = win->offset;
return win_off <= offset
- && (offset + 20) <= (win_off + win->len);
+ && (offset + the_hash_algo->rawsz) <= (win_off + win->len);
}
unsigned char *use_pack(struct packed_git *p,
@@ -555,7 +557,7 @@ unsigned char *use_pack(struct packed_git *p,
*/
if (!p->pack_size && p->pack_fd == -1 && open_packed_git(p))
die("packfile %s cannot be accessed", p->pack_name);
- if (offset > (p->pack_size - 20))
+ if (offset > (p->pack_size - the_hash_algo->rawsz))
die("offset beyond end of packfile (truncated pack?)");
if (offset < 0)
die(_("offset before end of packfile (broken .idx?)"));
@@ -675,7 +677,8 @@ struct packed_git *add_packed_git(const char *path, size_t path_len, int local)
p->pack_size = st.st_size;
p->pack_local = local;
p->mtime = st.st_mtime;
- if (path_len < 40 || get_sha1_hex(path + path_len - 40, p->sha1))
+ if (path_len < the_hash_algo->hexsz ||
+ get_sha1_hex(path + path_len - the_hash_algo->hexsz, p->sha1))
hashclr(p->sha1);
return p;
}
@@ -1028,7 +1031,8 @@ const struct packed_git *has_packed_and_bad(const unsigned char *sha1)
for (p = the_repository->objects->packed_git; p; p = p->next)
for (i = 0; i < p->num_bad_objects; i++)
- if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
+ if (!hashcmp(sha1,
+ p->bad_object_sha1 + the_hash_algo->rawsz * i))
return p;
return NULL;
}
@@ -1066,7 +1070,7 @@ static off_t get_delta_base(struct packed_git *p,
} else if (type == OBJ_REF_DELTA) {
/* The base entry _must_ be in the same pack */
base_offset = find_pack_entry_one(base_info, p);
- *curpos += 20;
+ *curpos += the_hash_algo->rawsz;
} else
die("I am totally screwed");
return base_offset;
@@ -1104,7 +1108,9 @@ static const unsigned char *get_delta_base_sha1(struct packed_git *p,
return NULL;
}
-static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
+static int retry_bad_packed_offset(struct repository *r,
+ struct packed_git *p,
+ off_t obj_offset)
{
int type;
struct revindex_entry *revidx;
@@ -1114,7 +1120,7 @@ static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
return OBJ_BAD;
nth_packed_object_oid(&oid, p, revidx->nr);
mark_bad_packed_object(p, oid.hash);
- type = oid_object_info(&oid, NULL);
+ type = oid_object_info(r, &oid, NULL);
if (type <= OBJ_NONE)
return OBJ_BAD;
return type;
@@ -1122,7 +1128,8 @@ static int retry_bad_packed_offset(struct packed_git *p, off_t obj_offset)
#define POI_STACK_PREALLOC 64
-static enum object_type packed_to_object_type(struct packed_git *p,
+static enum object_type packed_to_object_type(struct repository *r,
+ struct packed_git *p,
off_t obj_offset,
enum object_type type,
struct pack_window **w_curs,
@@ -1153,7 +1160,7 @@ static enum object_type packed_to_object_type(struct packed_git *p,
if (type <= OBJ_NONE) {
/* If getting the base itself fails, we first
* retry the base, otherwise unwind */
- type = retry_bad_packed_offset(p, base_offset);
+ type = retry_bad_packed_offset(r, p, base_offset);
if (type > OBJ_NONE)
goto out;
goto unwind;
@@ -1181,7 +1188,7 @@ out:
unwind:
while (poi_stack_nr) {
obj_offset = poi_stack[--poi_stack_nr];
- type = retry_bad_packed_offset(p, obj_offset);
+ type = retry_bad_packed_offset(r, p, obj_offset);
if (type > OBJ_NONE)
goto out;
}
@@ -1268,14 +1275,15 @@ static void detach_delta_base_cache_entry(struct delta_base_cache_entry *ent)
free(ent);
}
-static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset,
- unsigned long *base_size, enum object_type *type)
+static void *cache_or_unpack_entry(struct repository *r, struct packed_git *p,
+ off_t base_offset, unsigned long *base_size,
+ enum object_type *type)
{
struct delta_base_cache_entry *ent;
ent = get_delta_base_cache_entry(p, base_offset);
if (!ent)
- return unpack_entry(p, base_offset, type, base_size);
+ return unpack_entry(r, p, base_offset, type, base_size);
if (type)
*type = ent->type;
@@ -1329,8 +1337,8 @@ static void add_delta_base_cache(struct packed_git *p, off_t base_offset,
hashmap_add(&delta_base_cache, ent);
}
-int packed_object_info(struct packed_git *p, off_t obj_offset,
- struct object_info *oi)
+int packed_object_info(struct repository *r, struct packed_git *p,
+ off_t obj_offset, struct object_info *oi)
{
struct pack_window *w_curs = NULL;
unsigned long size;
@@ -1342,7 +1350,7 @@ int packed_object_info(struct packed_git *p, off_t obj_offset,
* a "real" type later if the caller is interested.
*/
if (oi->contentp) {
- *oi->contentp = cache_or_unpack_entry(p, obj_offset, oi->sizep,
+ *oi->contentp = cache_or_unpack_entry(r, p, obj_offset, oi->sizep,
&type);
if (!*oi->contentp)
type = OBJ_BAD;
@@ -1376,8 +1384,8 @@ int packed_object_info(struct packed_git *p, off_t obj_offset,
if (oi->typep || oi->type_name) {
enum object_type ptot;
- ptot = packed_to_object_type(p, obj_offset, type, &w_curs,
- curpos);
+ ptot = packed_to_object_type(r, p, obj_offset,
+ type, &w_curs, curpos);
if (oi->typep)
*oi->typep = ptot;
if (oi->type_name) {
@@ -1465,7 +1473,9 @@ struct unpack_entry_stack_ent {
unsigned long size;
};
-static void *read_object(const struct object_id *oid, enum object_type *type,
+static void *read_object(struct repository *r,
+ const struct object_id *oid,
+ enum object_type *type,
unsigned long *size)
{
struct object_info oi = OBJECT_INFO_INIT;
@@ -1474,12 +1484,12 @@ static void *read_object(const struct object_id *oid, enum object_type *type,
oi.sizep = size;
oi.contentp = &content;
- if (oid_object_info_extended(oid, &oi, 0) < 0)
+ if (oid_object_info_extended(r, oid, &oi, 0) < 0)
return NULL;
return content;
}
-void *unpack_entry(struct packed_git *p, off_t obj_offset,
+void *unpack_entry(struct repository *r, struct packed_git *p, off_t obj_offset,
enum object_type *final_type, unsigned long *final_size)
{
struct pack_window *w_curs = NULL;
@@ -1561,7 +1571,7 @@ void *unpack_entry(struct packed_git *p, off_t obj_offset,
case OBJ_OFS_DELTA:
case OBJ_REF_DELTA:
if (data)
- die("BUG: unpack_entry: left loop at a valid delta");
+ BUG("unpack_entry: left loop at a valid delta");
break;
case OBJ_COMMIT:
case OBJ_TREE:
@@ -1610,7 +1620,7 @@ void *unpack_entry(struct packed_git *p, off_t obj_offset,
oid_to_hex(&base_oid), (uintmax_t)obj_offset,
p->pack_name);
mark_bad_packed_object(p, base_oid.hash);
- base = read_object(&base_oid, &type, &base_size);
+ base = read_object(r, &base_oid, &type, &base_size);
external_base = base;
}
}
@@ -1671,6 +1681,7 @@ int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32
{
const unsigned char *index_fanout = p->index_data;
const unsigned char *index_lookup;
+ const unsigned int hashsz = the_hash_algo->rawsz;
int index_lookup_width;
if (!index_fanout)
@@ -1678,10 +1689,10 @@ int bsearch_pack(const struct object_id *oid, const struct packed_git *p, uint32
index_lookup = index_fanout + 4 * 256;
if (p->index_version == 1) {
- index_lookup_width = 24;
+ index_lookup_width = hashsz + 4;
index_lookup += 4;
} else {
- index_lookup_width = 20;
+ index_lookup_width = hashsz;
index_fanout += 8;
index_lookup += 8;
}
@@ -1694,6 +1705,7 @@ const unsigned char *nth_packed_object_sha1(struct packed_git *p,
uint32_t n)
{
const unsigned char *index = p->index_data;
+ const unsigned int hashsz = the_hash_algo->rawsz;
if (!index) {
if (open_pack_index(p))
return NULL;
@@ -1703,10 +1715,10 @@ const unsigned char *nth_packed_object_sha1(struct packed_git *p,
return NULL;
index += 4 * 256;
if (p->index_version == 1) {
- return index + 24 * n + 4;
+ return index + (hashsz + 4) * n + 4;
} else {
index += 8;
- return index + 20 * n;
+ return index + hashsz * n;
}
}
@@ -1738,12 +1750,13 @@ void check_pack_index_ptr(const struct packed_git *p, const void *vptr)
off_t nth_packed_object_offset(const struct packed_git *p, uint32_t n)
{
const unsigned char *index = p->index_data;
+ const unsigned int hashsz = the_hash_algo->rawsz;
index += 4 * 256;
if (p->index_version == 1) {
- return ntohl(*((uint32_t *)(index + 24 * n)));
+ return ntohl(*((uint32_t *)(index + (hashsz + 4) * n)));
} else {
uint32_t off;
- index += 8 + p->num_objects * (20 + 4);
+ index += 8 + p->num_objects * (hashsz + 4);
off = ntohl(*((uint32_t *)(index + 4 * n)));
if (!(off & 0x80000000))
return off;
@@ -1805,7 +1818,7 @@ struct packed_git *find_sha1_pack(const unsigned char *sha1,
}
-static int fill_pack_entry(const unsigned char *sha1,
+static int fill_pack_entry(const struct object_id *oid,
struct pack_entry *e,
struct packed_git *p)
{
@@ -1814,11 +1827,12 @@ static int fill_pack_entry(const unsigned char *sha1,
if (p->num_bad_objects) {
unsigned i;
for (i = 0; i < p->num_bad_objects; i++)
- if (!hashcmp(sha1, p->bad_object_sha1 + 20 * i))
+ if (!hashcmp(oid->hash,
+ p->bad_object_sha1 + the_hash_algo->rawsz * i))
return 0;
}
- offset = find_pack_entry_one(sha1, p);
+ offset = find_pack_entry_one(oid->hash, p);
if (!offset)
return 0;
@@ -1833,11 +1847,10 @@ static int fill_pack_entry(const unsigned char *sha1,
return 0;
e->offset = offset;
e->p = p;
- hashcpy(e->sha1, sha1);
return 1;
}
-int find_pack_entry(struct repository *r, const unsigned char *sha1, struct pack_entry *e)
+int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e)
{
struct list_head *pos;
@@ -1847,7 +1860,7 @@ int find_pack_entry(struct repository *r, const unsigned char *sha1, struct pack
list_for_each(pos, &r->objects->packed_git_mru) {
struct packed_git *p = list_entry(pos, struct packed_git, mru);
- if (fill_pack_entry(sha1, e, p)) {
+ if (fill_pack_entry(oid, e, p)) {
list_move(&p->mru, &r->objects->packed_git_mru);
return 1;
}
@@ -1855,10 +1868,10 @@ int find_pack_entry(struct repository *r, const unsigned char *sha1, struct pack
return 0;
}
-int has_sha1_pack(const unsigned char *sha1)
+int has_object_pack(const struct object_id *oid)
{
struct pack_entry e;
- return find_pack_entry(the_repository, sha1, &e);
+ return find_pack_entry(the_repository, oid, &e);
}
int has_pack_index(const unsigned char *sha1)
@@ -1869,7 +1882,7 @@ int has_pack_index(const unsigned char *sha1)
return 1;
}
-static int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
+int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn cb, void *data)
{
uint32_t i;
int r = 0;
@@ -1944,7 +1957,7 @@ static int add_promisor_object(const struct object_id *oid,
struct commit *commit = (struct commit *) obj;
struct commit_list *parents = commit->parents;
- oidset_insert(set, &commit->tree->object.oid);
+ oidset_insert(set, get_commit_tree_oid(commit));
for (; parents; parents = parents->next)
oidset_insert(set, &parents->item->object.oid);
} else if (obj->type == OBJ_TAG) {
diff --git a/packfile.h b/packfile.h
index a92c0b2..e0a38ab 100644
--- a/packfile.h
+++ b/packfile.h
@@ -65,6 +65,7 @@ extern void close_pack_index(struct packed_git *);
extern unsigned char *use_pack(struct packed_git *, struct pack_window **, off_t, unsigned long *);
extern void close_pack_windows(struct packed_git *);
+extern void close_pack(struct packed_git *);
extern void close_all_packs(struct raw_object_store *o);
extern void unuse_pack(struct pack_window **);
extern void clear_delta_base_cache(void);
@@ -115,7 +116,7 @@ extern off_t nth_packed_object_offset(const struct packed_git *, uint32_t n);
extern off_t find_pack_entry_one(const unsigned char *sha1, struct packed_git *);
extern int is_pack_valid(struct packed_git *);
-extern void *unpack_entry(struct packed_git *, off_t, enum object_type *, unsigned long *);
+extern void *unpack_entry(struct repository *r, struct packed_git *, off_t, enum object_type *, unsigned long *);
extern unsigned long unpack_object_header_buffer(const unsigned char *buf, unsigned long len, enum object_type *type, unsigned long *sizep);
extern unsigned long get_size_from_delta(struct packed_git *, struct pack_window **, off_t);
extern int unpack_object_header(struct packed_git *, struct pack_window **, off_t *, unsigned long *);
@@ -125,7 +126,9 @@ extern void release_pack_memory(size_t);
/* global flag to enable extra checks when accessing packed objects */
extern int do_check_packed_object_crc;
-extern int packed_object_info(struct packed_git *pack, off_t offset, struct object_info *);
+extern int packed_object_info(struct repository *r,
+ struct packed_git *pack,
+ off_t offset, struct object_info *);
extern void mark_bad_packed_object(struct packed_git *p, const unsigned char *sha1);
extern const struct packed_git *has_packed_and_bad(const unsigned char *sha1);
@@ -134,9 +137,9 @@ extern const struct packed_git *has_packed_and_bad(const unsigned char *sha1);
* Iff a pack file in the given repository contains the object named by sha1,
* return true and store its location to e.
*/
-extern int find_pack_entry(struct repository *r, const unsigned char *sha1, struct pack_entry *e);
+extern int find_pack_entry(struct repository *r, const struct object_id *oid, struct pack_entry *e);
-extern int has_sha1_pack(const unsigned char *sha1);
+extern int has_object_pack(const struct object_id *oid);
extern int has_pack_index(const unsigned char *sha1);
@@ -154,6 +157,7 @@ typedef int each_packed_object_fn(const struct object_id *oid,
struct packed_git *pack,
uint32_t pos,
void *data);
+extern int for_each_object_in_pack(struct packed_git *p, each_packed_object_fn, void *data);
extern int for_each_packed_object(each_packed_object_fn, void *, unsigned flags);
/*
diff --git a/pager.c b/pager.c
index 92b23e6..226828f 100644
--- a/pager.c
+++ b/pager.c
@@ -109,10 +109,15 @@ void setup_pager(void)
return;
/*
- * force computing the width of the terminal before we redirect
- * the standard output to the pager.
+ * After we redirect standard output, we won't be able to use an ioctl
+ * to get the terminal size. Let's grab it now, and then set $COLUMNS
+ * to communicate it to any sub-processes.
*/
- (void) term_columns();
+ {
+ char buf[64];
+ xsnprintf(buf, sizeof(buf), "%d", term_columns());
+ setenv("COLUMNS", buf, 0);
+ }
setenv("GIT_PAGER_IN_USE", "true", 1);
diff --git a/parse-options-cb.c b/parse-options-cb.c
index c6679cb..0f9f311 100644
--- a/parse-options-cb.c
+++ b/parse-options-cb.c
@@ -38,7 +38,11 @@ int parse_opt_approxidate_cb(const struct option *opt, const char *arg,
int parse_opt_expiry_date_cb(const struct option *opt, const char *arg,
int unset)
{
- return parse_expiry_date(arg, (timestamp_t *)opt->value);
+ if (unset)
+ arg = "never";
+ if (parse_expiry_date(arg, (timestamp_t *)opt->value))
+ die(_("malformed expiration date '%s'"), arg);
+ return 0;
}
int parse_opt_color_flag_cb(const struct option *opt, const char *arg,
diff --git a/path.c b/path.c
index 3308b7b..7f109f6 100644
--- a/path.c
+++ b/path.c
@@ -1306,7 +1306,7 @@ static int only_spaces_and_periods(const char *path, size_t len, size_t skip)
int is_ntfs_dotgit(const char *name)
{
- int len;
+ size_t len;
for (len = 0; ; len++)
if (!name[len] || name[len] == '\\' || is_dir_sep(name[len])) {
@@ -1323,6 +1323,90 @@ int is_ntfs_dotgit(const char *name)
}
}
+static int is_ntfs_dot_generic(const char *name,
+ const char *dotgit_name,
+ size_t len,
+ const char *dotgit_ntfs_shortname_prefix)
+{
+ int saw_tilde;
+ size_t i;
+
+ if ((name[0] == '.' && !strncasecmp(name + 1, dotgit_name, len))) {
+ i = len + 1;
+only_spaces_and_periods:
+ for (;;) {
+ char c = name[i++];
+ if (!c)
+ return 1;
+ if (c != ' ' && c != '.')
+ return 0;
+ }
+ }
+
+ /*
+ * Is it a regular NTFS short name, i.e. shortened to 6 characters,
+ * followed by ~1, ... ~4?
+ */
+ if (!strncasecmp(name, dotgit_name, 6) && name[6] == '~' &&
+ name[7] >= '1' && name[7] <= '4') {
+ i = 8;
+ goto only_spaces_and_periods;
+ }
+
+ /*
+ * Is it a fall-back NTFS short name (for details, see
+ * https://en.wikipedia.org/wiki/8.3_filename?
+ */
+ for (i = 0, saw_tilde = 0; i < 8; i++)
+ if (name[i] == '\0')
+ return 0;
+ else if (saw_tilde) {
+ if (name[i] < '0' || name[i] > '9')
+ return 0;
+ } else if (name[i] == '~') {
+ if (name[++i] < '1' || name[i] > '9')
+ return 0;
+ saw_tilde = 1;
+ } else if (i >= 6)
+ return 0;
+ else if (name[i] < 0) {
+ /*
+ * We know our needles contain only ASCII, so we clamp
+ * here to make the results of tolower() sane.
+ */
+ return 0;
+ } else if (tolower(name[i]) != dotgit_ntfs_shortname_prefix[i])
+ return 0;
+
+ goto only_spaces_and_periods;
+}
+
+/*
+ * Inline helper to make sure compiler resolves strlen() on literals at
+ * compile time.
+ */
+static inline int is_ntfs_dot_str(const char *name, const char *dotgit_name,
+ const char *dotgit_ntfs_shortname_prefix)
+{
+ return is_ntfs_dot_generic(name, dotgit_name, strlen(dotgit_name),
+ dotgit_ntfs_shortname_prefix);
+}
+
+int is_ntfs_dotgitmodules(const char *name)
+{
+ return is_ntfs_dot_str(name, "gitmodules", "gi7eba");
+}
+
+int is_ntfs_dotgitignore(const char *name)
+{
+ return is_ntfs_dot_str(name, "gitignore", "gi250a");
+}
+
+int is_ntfs_dotgitattributes(const char *name)
+{
+ return is_ntfs_dot_str(name, "gitattributes", "gi7d29");
+}
+
int looks_like_command_line_option(const char *str)
{
return str && str[0] == '-';
diff --git a/pathspec.c b/pathspec.c
index 82eb39c..27cd606 100644
--- a/pathspec.c
+++ b/pathspec.c
@@ -198,7 +198,7 @@ static void parse_pathspec_attr_match(struct pathspec_item *item, const char *va
}
if (item->attr_check->nr != item->attr_match_nr)
- die("BUG: should have same number of entries");
+ BUG("should have same number of entries");
string_list_clear(&list, 0);
}
@@ -422,7 +422,7 @@ static void init_pathspec_item(struct pathspec_item *item, unsigned flags,
if (pathspec_prefix >= 0 &&
(prefixlen || (prefix && *prefix)))
- die("BUG: 'prefix' magic is supposed to be used at worktree's root");
+ BUG("'prefix' magic is supposed to be used at worktree's root");
if ((magic & PATHSPEC_LITERAL) && (magic & PATHSPEC_GLOB))
die(_("%s: 'literal' and 'glob' are incompatible"), elt);
@@ -486,7 +486,7 @@ static void init_pathspec_item(struct pathspec_item *item, unsigned flags,
/* sanity checks, pathspec matchers assume these are sane */
if (item->nowildcard_len > item->len ||
item->prefix > item->len) {
- die ("BUG: error initializing pathspec_item");
+ BUG("error initializing pathspec_item");
}
}
@@ -545,7 +545,7 @@ void parse_pathspec(struct pathspec *pathspec,
if ((flags & PATHSPEC_PREFER_CWD) &&
(flags & PATHSPEC_PREFER_FULL))
- die("BUG: PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
+ BUG("PATHSPEC_PREFER_CWD and PATHSPEC_PREFER_FULL are incompatible");
/* No arguments with prefix -> prefix pathspec */
if (!entry) {
@@ -553,7 +553,7 @@ void parse_pathspec(struct pathspec *pathspec,
return;
if (!(flags & PATHSPEC_PREFER_CWD))
- die("BUG: PATHSPEC_PREFER_CWD requires arguments");
+ BUG("PATHSPEC_PREFER_CWD requires arguments");
pathspec->items = item = xcalloc(1, sizeof(*item));
item->match = xstrdup(prefix);
@@ -609,7 +609,7 @@ void parse_pathspec(struct pathspec *pathspec,
if (pathspec->magic & PATHSPEC_MAXDEPTH) {
if (flags & PATHSPEC_KEEP_ORDER)
- die("BUG: PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
+ BUG("PATHSPEC_MAXDEPTH_VALID and PATHSPEC_KEEP_ORDER are incompatible");
QSORT(pathspec->items, pathspec->nr, pathspec_item_cmp);
}
}
diff --git a/perl/Git.pm b/perl/Git.pm
index 16ebcc6..d856930 100644
--- a/perl/Git.pm
+++ b/perl/Git.pm
@@ -554,7 +554,7 @@ sub get_record {
my ($fh, $rs) = @_;
local $/ = $rs;
my $rec = <$fh>;
- chomp $rec if defined $rs;
+ chomp $rec if defined $rec;
$rec;
}
diff --git a/perl/Git/I18N.pm b/perl/Git/I18N.pm
index dba96ff..bfb4fb6 100644
--- a/perl/Git/I18N.pm
+++ b/perl/Git/I18N.pm
@@ -18,7 +18,7 @@ our @EXPORT_OK = @EXPORT;
sub __bootstrap_locale_messages {
our $TEXTDOMAIN = 'git';
- our $TEXTDOMAINDIR = $ENV{GIT_TEXTDOMAINDIR} || '@@LOCALEDIR@@';
+ our $TEXTDOMAINDIR ||= $ENV{GIT_TEXTDOMAINDIR} || '@@LOCALEDIR@@';
require POSIX;
POSIX->import(qw(setlocale));
diff --git a/perl/header_templates/fixed_prefix.template.pl b/perl/header_templates/fixed_prefix.template.pl
new file mode 100644
index 0000000..857b439
--- /dev/null
+++ b/perl/header_templates/fixed_prefix.template.pl
@@ -0,0 +1 @@
+use lib (split(/@@PATHSEP@@/, $ENV{GITPERLLIB} || '@@INSTLIBDIR@@'));
diff --git a/perl/header_templates/runtime_prefix.template.pl b/perl/header_templates/runtime_prefix.template.pl
new file mode 100644
index 0000000..9d28b3d
--- /dev/null
+++ b/perl/header_templates/runtime_prefix.template.pl
@@ -0,0 +1,42 @@
+# BEGIN RUNTIME_PREFIX generated code.
+#
+# This finds our Git::* libraries relative to the script's runtime path.
+sub __git_system_path {
+ my ($relpath) = @_;
+ my $gitexecdir_relative = '@@GITEXECDIR_REL@@';
+
+ # GIT_EXEC_PATH is supplied by `git` or the test suite.
+ my $exec_path;
+ if (exists $ENV{GIT_EXEC_PATH}) {
+ $exec_path = $ENV{GIT_EXEC_PATH};
+ } else {
+ # This can happen if this script is being directly invoked instead of run
+ # by "git".
+ require FindBin;
+ $exec_path = $FindBin::Bin;
+ }
+
+ # Trim off the relative gitexecdir path to get the system path.
+ (my $prefix = $exec_path) =~ s/\Q$gitexecdir_relative\E$//;
+
+ require File::Spec;
+ return File::Spec->catdir($prefix, $relpath);
+}
+
+BEGIN {
+ use lib split /@@PATHSEP@@/,
+ (
+ $ENV{GITPERLLIB} ||
+ do {
+ my $perllibdir = __git_system_path('@@PERLLIBDIR_REL@@');
+ (-e $perllibdir) || die("Invalid system path ($relpath): $path");
+ $perllibdir;
+ }
+ );
+
+ # Export the system locale directory to the I18N module. The locale directory
+ # is only installed if NO_GETTEXT is set.
+ $Git::I18N::TEXTDOMAINDIR = __git_system_path('@@LOCALEDIR_REL@@');
+}
+
+# END RUNTIME_PREFIX generated code.
diff --git a/pkt-line.c b/pkt-line.c
index 2827ca7..a593c08 100644
--- a/pkt-line.c
+++ b/pkt-line.c
@@ -91,6 +91,12 @@ void packet_flush(int fd)
write_or_die(fd, "0000", 4);
}
+void packet_delim(int fd)
+{
+ packet_trace("0001", 4, 1);
+ write_or_die(fd, "0001", 4);
+}
+
int packet_flush_gently(int fd)
{
packet_trace("0000", 4, 1);
@@ -105,6 +111,12 @@ void packet_buf_flush(struct strbuf *buf)
strbuf_add(buf, "0000", 4);
}
+void packet_buf_delim(struct strbuf *buf)
+{
+ packet_trace("0001", 4, 1);
+ strbuf_add(buf, "0001", 4);
+}
+
static void set_packet_header(char *buf, const int size)
{
static char hexchar[] = "0123456789abcdef";
@@ -203,6 +215,22 @@ void packet_buf_write(struct strbuf *buf, const char *fmt, ...)
va_end(args);
}
+void packet_buf_write_len(struct strbuf *buf, const char *data, size_t len)
+{
+ size_t orig_len, n;
+
+ orig_len = buf->len;
+ strbuf_addstr(buf, "0000");
+ strbuf_add(buf, data, len);
+ n = buf->len - orig_len;
+
+ if (n > LARGE_PACKET_MAX)
+ die("protocol error: impossibly long line");
+
+ set_packet_header(&buf->buf[orig_len], n);
+ packet_trace(data, len, 1);
+}
+
int write_packetized_from_fd(int fd_in, int fd_out)
{
static char buf[LARGE_PACKET_DATA_MAX];
@@ -249,7 +277,7 @@ static int get_packet_data(int fd, char **src_buf, size_t *src_size,
ssize_t ret;
if (fd >= 0 && src_buf && *src_buf)
- die("BUG: multiple sources given to packet_read");
+ BUG("multiple sources given to packet_read");
/* Read up to "size" bytes from our source, whatever it is. */
if (src_buf && *src_buf) {
@@ -280,28 +308,43 @@ static int packet_length(const char *linelen)
return (val < 0) ? val : (val << 8) | hex2chr(linelen + 2);
}
-int packet_read(int fd, char **src_buf, size_t *src_len,
- char *buffer, unsigned size, int options)
+enum packet_read_status packet_read_with_status(int fd, char **src_buffer,
+ size_t *src_len, char *buffer,
+ unsigned size, int *pktlen,
+ int options)
{
- int len, ret;
+ int len;
char linelen[4];
- ret = get_packet_data(fd, src_buf, src_len, linelen, 4, options);
- if (ret < 0)
- return ret;
+ if (get_packet_data(fd, src_buffer, src_len, linelen, 4, options) < 0) {
+ *pktlen = -1;
+ return PACKET_READ_EOF;
+ }
+
len = packet_length(linelen);
- if (len < 0)
+
+ if (len < 0) {
die("protocol error: bad line length character: %.4s", linelen);
- if (!len) {
+ } else if (!len) {
packet_trace("0000", 4, 0);
- return 0;
+ *pktlen = 0;
+ return PACKET_READ_FLUSH;
+ } else if (len == 1) {
+ packet_trace("0001", 4, 0);
+ *pktlen = 0;
+ return PACKET_READ_DELIM;
+ } else if (len < 4) {
+ die("protocol error: bad line length %d", len);
}
+
len -= 4;
- if (len >= size)
+ if ((unsigned)len >= size)
die("protocol error: bad line length %d", len);
- ret = get_packet_data(fd, src_buf, src_len, buffer, len, options);
- if (ret < 0)
- return ret;
+
+ if (get_packet_data(fd, src_buffer, src_len, buffer, len, options) < 0) {
+ *pktlen = -1;
+ return PACKET_READ_EOF;
+ }
if ((options & PACKET_READ_CHOMP_NEWLINE) &&
len && buffer[len-1] == '\n')
@@ -309,7 +352,19 @@ int packet_read(int fd, char **src_buf, size_t *src_len,
buffer[len] = 0;
packet_trace(buffer, len, 0);
- return len;
+ *pktlen = len;
+ return PACKET_READ_NORMAL;
+}
+
+int packet_read(int fd, char **src_buffer, size_t *src_len,
+ char *buffer, unsigned size, int options)
+{
+ int pktlen = -1;
+
+ packet_read_with_status(fd, src_buffer, src_len, buffer, size,
+ &pktlen, options);
+
+ return pktlen;
}
static char *packet_read_line_generic(int fd,
@@ -377,3 +432,53 @@ ssize_t read_packetized_to_strbuf(int fd_in, struct strbuf *sb_out)
}
return sb_out->len - orig_len;
}
+
+/* Packet Reader Functions */
+void packet_reader_init(struct packet_reader *reader, int fd,
+ char *src_buffer, size_t src_len,
+ int options)
+{
+ memset(reader, 0, sizeof(*reader));
+
+ reader->fd = fd;
+ reader->src_buffer = src_buffer;
+ reader->src_len = src_len;
+ reader->buffer = packet_buffer;
+ reader->buffer_size = sizeof(packet_buffer);
+ reader->options = options;
+}
+
+enum packet_read_status packet_reader_read(struct packet_reader *reader)
+{
+ if (reader->line_peeked) {
+ reader->line_peeked = 0;
+ return reader->status;
+ }
+
+ reader->status = packet_read_with_status(reader->fd,
+ &reader->src_buffer,
+ &reader->src_len,
+ reader->buffer,
+ reader->buffer_size,
+ &reader->pktlen,
+ reader->options);
+
+ if (reader->status == PACKET_READ_NORMAL)
+ reader->line = reader->buffer;
+ else
+ reader->line = NULL;
+
+ return reader->status;
+}
+
+enum packet_read_status packet_reader_peek(struct packet_reader *reader)
+{
+ /* Only allow peeking a single line */
+ if (reader->line_peeked)
+ return reader->status;
+
+ /* Peek a line by reading it and setting peeked flag */
+ packet_reader_read(reader);
+ reader->line_peeked = 1;
+ return reader->status;
+}
diff --git a/pkt-line.h b/pkt-line.h
index 3dad583..5b28d43 100644
--- a/pkt-line.h
+++ b/pkt-line.h
@@ -20,10 +20,13 @@
* side can't, we stay with pure read/write interfaces.
*/
void packet_flush(int fd);
+void packet_delim(int fd);
void packet_write_fmt(int fd, const char *fmt, ...) __attribute__((format (printf, 2, 3)));
void packet_buf_flush(struct strbuf *buf);
+void packet_buf_delim(struct strbuf *buf);
void packet_write(int fd_out, const char *buf, size_t size);
void packet_buf_write(struct strbuf *buf, const char *fmt, ...) __attribute__((format (printf, 2, 3)));
+void packet_buf_write_len(struct strbuf *buf, const char *data, size_t len);
int packet_flush_gently(int fd);
int packet_write_fmt_gently(int fd, const char *fmt, ...) __attribute__((format (printf, 2, 3)));
int write_packetized_from_fd(int fd_in, int fd_out);
@@ -66,6 +69,23 @@ int packet_read(int fd, char **src_buffer, size_t *src_len, char
*buffer, unsigned size, int options);
/*
+ * Read a packetized line into a buffer like the 'packet_read()' function but
+ * returns an 'enum packet_read_status' which indicates the status of the read.
+ * The number of bytes read will be assigined to *pktlen if the status of the
+ * read was 'PACKET_READ_NORMAL'.
+ */
+enum packet_read_status {
+ PACKET_READ_EOF,
+ PACKET_READ_NORMAL,
+ PACKET_READ_FLUSH,
+ PACKET_READ_DELIM,
+};
+enum packet_read_status packet_read_with_status(int fd, char **src_buffer,
+ size_t *src_len, char *buffer,
+ unsigned size, int *pktlen,
+ int options);
+
+/*
* Convenience wrapper for packet_read that is not gentle, and sets the
* CHOMP_NEWLINE option. The return value is NULL for a flush packet,
* and otherwise points to a static buffer (that may be overwritten by
@@ -96,6 +116,64 @@ char *packet_read_line_buf(char **src_buf, size_t *src_len, int *size);
*/
ssize_t read_packetized_to_strbuf(int fd_in, struct strbuf *sb_out);
+struct packet_reader {
+ /* source file descriptor */
+ int fd;
+
+ /* source buffer and its size */
+ char *src_buffer;
+ size_t src_len;
+
+ /* buffer that pkt-lines are read into and its size */
+ char *buffer;
+ unsigned buffer_size;
+
+ /* options to be used during reads */
+ int options;
+
+ /* status of the last read */
+ enum packet_read_status status;
+
+ /* length of data read during the last read */
+ int pktlen;
+
+ /* the last line read */
+ const char *line;
+
+ /* indicates if a line has been peeked */
+ int line_peeked;
+};
+
+/*
+ * Initialize a 'struct packet_reader' object which is an
+ * abstraction around the 'packet_read_with_status()' function.
+ */
+extern void packet_reader_init(struct packet_reader *reader, int fd,
+ char *src_buffer, size_t src_len,
+ int options);
+
+/*
+ * Perform a packet read and return the status of the read.
+ * The values of 'pktlen' and 'line' are updated based on the status of the
+ * read as follows:
+ *
+ * PACKET_READ_ERROR: 'pktlen' is set to '-1' and 'line' is set to NULL
+ * PACKET_READ_NORMAL: 'pktlen' is set to the number of bytes read
+ * 'line' is set to point at the read line
+ * PACKET_READ_FLUSH: 'pktlen' is set to '0' and 'line' is set to NULL
+ */
+extern enum packet_read_status packet_reader_read(struct packet_reader *reader);
+
+/*
+ * Peek the next packet line without consuming it and return the status.
+ * The next call to 'packet_reader_read()' will perform a read of the same line
+ * that was peeked, consuming the line.
+ *
+ * Peeking multiple times without calling 'packet_reader_read()' will return
+ * the same result.
+ */
+extern enum packet_read_status packet_reader_peek(struct packet_reader *reader);
+
#define DEFAULT_PACKET_MAX 1000
#define LARGE_PACKET_MAX 65520
#define LARGE_PACKET_DATA_MAX (LARGE_PACKET_MAX - 4)
diff --git a/pretty.c b/pretty.c
index 34fe891..703fa6f 100644
--- a/pretty.c
+++ b/pretty.c
@@ -1161,10 +1161,11 @@ static size_t format_commit_one(struct strbuf *sb, /* in UTF-8 */
strbuf_addstr(sb, diff_get_color(c->auto_color, DIFF_RESET));
return 1;
case 'T': /* tree hash */
- strbuf_addstr(sb, oid_to_hex(&commit->tree->object.oid));
+ strbuf_addstr(sb, oid_to_hex(get_commit_tree_oid(commit)));
return 1;
case 't': /* abbreviated tree hash */
- strbuf_add_unique_abbrev(sb, &commit->tree->object.oid,
+ strbuf_add_unique_abbrev(sb,
+ get_commit_tree_oid(commit),
c->pretty_ctx->abbrev);
return 1;
case 'P': /* parent hashes */
diff --git a/prio-queue.c b/prio-queue.c
index 126d096..a078451 100644
--- a/prio-queue.c
+++ b/prio-queue.c
@@ -20,7 +20,7 @@ void prio_queue_reverse(struct prio_queue *queue)
int i, j;
if (queue->compare != NULL)
- die("BUG: prio_queue_reverse() on non-LIFO queue");
+ BUG("prio_queue_reverse() on non-LIFO queue");
for (i = 0; i < (j = (queue->nr - 1) - i); i++)
swap(queue, i, j);
}
diff --git a/protocol.c b/protocol.c
index 43012b7..5e63678 100644
--- a/protocol.c
+++ b/protocol.c
@@ -8,6 +8,8 @@ static enum protocol_version parse_protocol_version(const char *value)
return protocol_v0;
else if (!strcmp(value, "1"))
return protocol_v1;
+ else if (!strcmp(value, "2"))
+ return protocol_v2;
else
return protocol_unknown_version;
}
diff --git a/protocol.h b/protocol.h
index 1b2bc94..2ad35e4 100644
--- a/protocol.h
+++ b/protocol.h
@@ -5,6 +5,7 @@ enum protocol_version {
protocol_unknown_version = -1,
protocol_v0 = 0,
protocol_v1 = 1,
+ protocol_v2 = 2,
};
/*
diff --git a/reachable.c b/reachable.c
index a6ea33a..ffb976c 100644
--- a/reachable.c
+++ b/reachable.c
@@ -78,7 +78,7 @@ static void add_recent_object(const struct object_id *oid,
* later processing, and the revision machinery expects
* commits and tags to have been parsed.
*/
- type = oid_object_info(oid, NULL);
+ type = oid_object_info(the_repository, oid, NULL);
if (type < 0)
die("unable to get object info for %s", oid_to_hex(oid));
diff --git a/read-cache.c b/read-cache.c
index 10f1c6b..3725882 100644
--- a/read-cache.c
+++ b/read-cache.c
@@ -752,7 +752,7 @@ struct cache_entry *make_cache_entry(unsigned int mode,
int size, len;
struct cache_entry *ce, *ret;
- if (!verify_path(path)) {
+ if (!verify_path(path, mode)) {
error("Invalid path '%s'", path);
return NULL;
}
@@ -817,7 +817,7 @@ int ce_same_name(const struct cache_entry *a, const struct cache_entry *b)
* Also, we don't want double slashes or slashes at the
* end that can make pathnames ambiguous.
*/
-static int verify_dotfile(const char *rest)
+static int verify_dotfile(const char *rest, unsigned mode)
{
/*
* The first character was '.', but that
@@ -831,8 +831,13 @@ static int verify_dotfile(const char *rest)
switch (*rest) {
/*
- * ".git" followed by NUL or slash is bad. This
- * shares the path end test with the ".." case.
+ * ".git" followed by NUL or slash is bad. Note that we match
+ * case-insensitively here, even if ignore_case is not set.
+ * This outlaws ".GIT" everywhere out of an abundance of caution,
+ * since there's really no good reason to allow it.
+ *
+ * Once we've seen ".git", we can also find ".gitmodules", etc (also
+ * case-insensitively).
*/
case 'g':
case 'G':
@@ -840,8 +845,15 @@ static int verify_dotfile(const char *rest)
break;
if (rest[2] != 't' && rest[2] != 'T')
break;
- rest += 2;
- /* fallthrough */
+ if (rest[3] == '\0' || is_dir_sep(rest[3]))
+ return 0;
+ if (S_ISLNK(mode)) {
+ rest += 3;
+ if (skip_iprefix(rest, "modules", &rest) &&
+ (*rest == '\0' || is_dir_sep(*rest)))
+ return 0;
+ }
+ break;
case '.':
if (rest[1] == '\0' || is_dir_sep(rest[1]))
return 0;
@@ -849,7 +861,7 @@ static int verify_dotfile(const char *rest)
return 1;
}
-int verify_path(const char *path)
+int verify_path(const char *path, unsigned mode)
{
char c;
@@ -862,12 +874,25 @@ int verify_path(const char *path)
return 1;
if (is_dir_sep(c)) {
inside:
- if (protect_hfs && is_hfs_dotgit(path))
- return 0;
- if (protect_ntfs && is_ntfs_dotgit(path))
- return 0;
+ if (protect_hfs) {
+ if (is_hfs_dotgit(path))
+ return 0;
+ if (S_ISLNK(mode)) {
+ if (is_hfs_dotgitmodules(path))
+ return 0;
+ }
+ }
+ if (protect_ntfs) {
+ if (is_ntfs_dotgit(path))
+ return 0;
+ if (S_ISLNK(mode)) {
+ if (is_ntfs_dotgitmodules(path))
+ return 0;
+ }
+ }
+
c = *path++;
- if ((c == '.' && !verify_dotfile(path)) ||
+ if ((c == '.' && !verify_dotfile(path, mode)) ||
is_dir_sep(c) || c == '\0')
return 0;
}
@@ -1184,7 +1209,7 @@ static int add_index_entry_with_check(struct index_state *istate, struct cache_e
if (!ok_to_add)
return -1;
- if (!verify_path(ce->name))
+ if (!verify_path(ce->name, ce->ce_mode))
return error("Invalid path '%s'", ce->name);
if (!skip_df_check &&
@@ -1806,7 +1831,7 @@ int do_read_index(struct index_state *istate, const char *path, int must_exist)
if (verify_hdr(hdr, mmap_size) < 0)
goto unmap;
- hashcpy(istate->sha1, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
+ hashcpy(istate->oid.hash, (const unsigned char *)hdr + mmap_size - the_hash_algo->rawsz);
istate->version = ntohl(hdr->hdr_version);
istate->cache_nr = ntohl(hdr->hdr_entries);
istate->cache_alloc = alloc_nr(istate->cache_nr);
@@ -1878,7 +1903,7 @@ int read_index_from(struct index_state *istate, const char *path,
uint64_t start = getnanotime();
struct split_index *split_index;
int ret;
- char *base_sha1_hex;
+ char *base_oid_hex;
char *base_path;
/* istate->initialized covers both .git/index and .git/sharedindex.xxx */
@@ -1889,7 +1914,7 @@ int read_index_from(struct index_state *istate, const char *path,
trace_performance_since(start, "read cache %s", path);
split_index = istate->split_index;
- if (!split_index || is_null_sha1(split_index->base_sha1)) {
+ if (!split_index || is_null_oid(&split_index->base_oid)) {
post_read_index_from(istate);
return ret;
}
@@ -1899,13 +1924,13 @@ int read_index_from(struct index_state *istate, const char *path,
else
split_index->base = xcalloc(1, sizeof(*split_index->base));
- base_sha1_hex = sha1_to_hex(split_index->base_sha1);
- base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_sha1_hex);
+ base_oid_hex = oid_to_hex(&split_index->base_oid);
+ base_path = xstrfmt("%s/sharedindex.%s", gitdir, base_oid_hex);
ret = do_read_index(split_index->base, base_path, 1);
- if (hashcmp(split_index->base_sha1, split_index->base->sha1))
+ if (oidcmp(&split_index->base_oid, &split_index->base->oid))
die("broken index, expect %s in %s, got %s",
- base_sha1_hex, base_path,
- sha1_to_hex(split_index->base->sha1));
+ base_oid_hex, base_path,
+ oid_to_hex(&split_index->base->oid));
freshen_shared_index(base_path, 0);
merge_base_index(istate);
@@ -2194,7 +2219,7 @@ static int verify_index_from(const struct index_state *istate, const char *path)
if (n != the_hash_algo->rawsz)
goto out;
- if (hashcmp(istate->sha1, hash))
+ if (hashcmp(istate->oid.hash, hash))
goto out;
close(fd);
@@ -2268,7 +2293,7 @@ static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
if (!istate->version) {
istate->version = get_index_format_default();
- if (getenv("GIT_TEST_SPLIT_INDEX"))
+ if (git_env_bool("GIT_TEST_SPLIT_INDEX", 0))
init_split_index(istate);
}
@@ -2373,7 +2398,7 @@ static int do_write_index(struct index_state *istate, struct tempfile *tempfile,
return -1;
}
- if (ce_flush(&c, newfd, istate->sha1))
+ if (ce_flush(&c, newfd, istate->oid.hash))
return -1;
if (close_tempfile_gently(tempfile)) {
error(_("could not close '%s'"), tempfile->filename.buf);
@@ -2497,10 +2522,10 @@ static int write_shared_index(struct index_state *istate,
return ret;
}
ret = rename_tempfile(temp,
- git_path("sharedindex.%s", sha1_to_hex(si->base->sha1)));
+ git_path("sharedindex.%s", oid_to_hex(&si->base->oid)));
if (!ret) {
- hashcpy(si->base_sha1, si->base->sha1);
- clean_shared_index_files(sha1_to_hex(si->base->sha1));
+ oidcpy(&si->base_oid, &si->base->oid);
+ clean_shared_index_files(oid_to_hex(&si->base->oid));
}
return ret;
@@ -2554,13 +2579,13 @@ int write_locked_index(struct index_state *istate, struct lock_file *lock,
if (!si || alternate_index_output ||
(istate->cache_changed & ~EXTMASK)) {
if (si)
- hashclr(si->base_sha1);
+ oidclr(&si->base_oid);
ret = do_write_locked_index(istate, lock, flags);
goto out;
}
- if (getenv("GIT_TEST_SPLIT_INDEX")) {
- int v = si->base_sha1[0];
+ if (git_env_bool("GIT_TEST_SPLIT_INDEX", 0)) {
+ int v = si->base_oid.hash[0];
if ((v & 15) < 6)
istate->cache_changed |= SPLIT_INDEX_ORDERED;
}
@@ -2575,7 +2600,7 @@ int write_locked_index(struct index_state *istate, struct lock_file *lock,
temp = mks_tempfile(git_path("sharedindex_XXXXXX"));
if (!temp) {
- hashclr(si->base_sha1);
+ oidclr(&si->base_oid);
ret = do_write_locked_index(istate, lock, flags);
goto out;
}
@@ -2595,7 +2620,7 @@ int write_locked_index(struct index_state *istate, struct lock_file *lock,
/* Freshen the shared index only if the split-index was written */
if (!ret && !new_shared_index) {
const char *shared_index = git_path("sharedindex.%s",
- sha1_to_hex(si->base_sha1));
+ oid_to_hex(&si->base_oid));
freshen_shared_index(shared_index, 1);
}
diff --git a/ref-filter.c b/ref-filter.c
index 9a333e2..01c1a82 100644
--- a/ref-filter.c
+++ b/ref-filter.c
@@ -101,22 +101,38 @@ static struct used_atom {
} *used_atom;
static int used_atom_cnt, need_tagged, need_symref;
-static void color_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *color_value)
+/*
+ * Expand string, append it to strbuf *sb, then return error code ret.
+ * Allow to save few lines of code.
+ */
+static int strbuf_addf_ret(struct strbuf *sb, int ret, const char *fmt, ...)
+{
+ va_list ap;
+ va_start(ap, fmt);
+ strbuf_vaddf(sb, fmt, ap);
+ va_end(ap);
+ return ret;
+}
+
+static int color_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *color_value, struct strbuf *err)
{
if (!color_value)
- die(_("expected format: %%(color:<color>)"));
+ return strbuf_addf_ret(err, -1, _("expected format: %%(color:<color>)"));
if (color_parse(color_value, atom->u.color) < 0)
- die(_("unrecognized color: %%(color:%s)"), color_value);
+ return strbuf_addf_ret(err, -1, _("unrecognized color: %%(color:%s)"),
+ color_value);
/*
* We check this after we've parsed the color, which lets us complain
* about syntactically bogus color names even if they won't be used.
*/
if (!want_color(format->use_color))
color_parse("", atom->u.color);
+ return 0;
}
-static void refname_atom_parser_internal(struct refname_atom *atom,
- const char *arg, const char *name)
+static int refname_atom_parser_internal(struct refname_atom *atom, const char *arg,
+ const char *name, struct strbuf *err)
{
if (!arg)
atom->option = R_NORMAL;
@@ -126,16 +142,18 @@ static void refname_atom_parser_internal(struct refname_atom *atom,
skip_prefix(arg, "strip=", &arg)) {
atom->option = R_LSTRIP;
if (strtol_i(arg, 10, &atom->lstrip))
- die(_("Integer value expected refname:lstrip=%s"), arg);
+ return strbuf_addf_ret(err, -1, _("Integer value expected refname:lstrip=%s"), arg);
} else if (skip_prefix(arg, "rstrip=", &arg)) {
atom->option = R_RSTRIP;
if (strtol_i(arg, 10, &atom->rstrip))
- die(_("Integer value expected refname:rstrip=%s"), arg);
+ return strbuf_addf_ret(err, -1, _("Integer value expected refname:rstrip=%s"), arg);
} else
- die(_("unrecognized %%(%s) argument: %s"), name, arg);
+ return strbuf_addf_ret(err, -1, _("unrecognized %%(%s) argument: %s"), name, arg);
+ return 0;
}
-static void remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int remote_ref_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
struct string_list params = STRING_LIST_INIT_DUP;
int i;
@@ -145,9 +163,8 @@ static void remote_ref_atom_parser(const struct ref_format *format, struct used_
if (!arg) {
atom->u.remote_ref.option = RR_REF;
- refname_atom_parser_internal(&atom->u.remote_ref.refname,
- arg, atom->name);
- return;
+ return refname_atom_parser_internal(&atom->u.remote_ref.refname,
+ arg, atom->name, err);
}
atom->u.remote_ref.nobracket = 0;
@@ -170,29 +187,38 @@ static void remote_ref_atom_parser(const struct ref_format *format, struct used_
atom->u.remote_ref.push_remote = 1;
} else {
atom->u.remote_ref.option = RR_REF;
- refname_atom_parser_internal(&atom->u.remote_ref.refname,
- arg, atom->name);
+ if (refname_atom_parser_internal(&atom->u.remote_ref.refname,
+ arg, atom->name, err)) {
+ string_list_clear(&params, 0);
+ return -1;
+ }
}
}
string_list_clear(&params, 0);
+ return 0;
}
-static void body_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int body_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
if (arg)
- die(_("%%(body) does not take arguments"));
+ return strbuf_addf_ret(err, -1, _("%%(body) does not take arguments"));
atom->u.contents.option = C_BODY_DEP;
+ return 0;
}
-static void subject_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int subject_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
if (arg)
- die(_("%%(subject) does not take arguments"));
+ return strbuf_addf_ret(err, -1, _("%%(subject) does not take arguments"));
atom->u.contents.option = C_SUB;
+ return 0;
}
-static void trailers_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int trailers_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
struct string_list params = STRING_LIST_INIT_DUP;
int i;
@@ -205,15 +231,20 @@ static void trailers_atom_parser(const struct ref_format *format, struct used_at
atom->u.contents.trailer_opts.unfold = 1;
else if (!strcmp(s, "only"))
atom->u.contents.trailer_opts.only_trailers = 1;
- else
- die(_("unknown %%(trailers) argument: %s"), s);
+ else {
+ strbuf_addf(err, _("unknown %%(trailers) argument: %s"), s);
+ string_list_clear(&params, 0);
+ return -1;
+ }
}
}
atom->u.contents.option = C_TRAILERS;
string_list_clear(&params, 0);
+ return 0;
}
-static void contents_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int contents_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
if (!arg)
atom->u.contents.option = C_BARE;
@@ -225,16 +256,19 @@ static void contents_atom_parser(const struct ref_format *format, struct used_at
atom->u.contents.option = C_SUB;
else if (skip_prefix(arg, "trailers", &arg)) {
skip_prefix(arg, ":", &arg);
- trailers_atom_parser(format, atom, *arg ? arg : NULL);
+ if (trailers_atom_parser(format, atom, *arg ? arg : NULL, err))
+ return -1;
} else if (skip_prefix(arg, "lines=", &arg)) {
atom->u.contents.option = C_LINES;
if (strtoul_ui(arg, 10, &atom->u.contents.nlines))
- die(_("positive value expected contents:lines=%s"), arg);
+ return strbuf_addf_ret(err, -1, _("positive value expected contents:lines=%s"), arg);
} else
- die(_("unrecognized %%(contents) argument: %s"), arg);
+ return strbuf_addf_ret(err, -1, _("unrecognized %%(contents) argument: %s"), arg);
+ return 0;
}
-static void objectname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int objectname_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
if (!arg)
atom->u.objectname.option = O_FULL;
@@ -244,16 +278,18 @@ static void objectname_atom_parser(const struct ref_format *format, struct used_
atom->u.objectname.option = O_LENGTH;
if (strtoul_ui(arg, 10, &atom->u.objectname.length) ||
atom->u.objectname.length == 0)
- die(_("positive value expected objectname:short=%s"), arg);
+ return strbuf_addf_ret(err, -1, _("positive value expected objectname:short=%s"), arg);
if (atom->u.objectname.length < MINIMUM_ABBREV)
atom->u.objectname.length = MINIMUM_ABBREV;
} else
- die(_("unrecognized %%(objectname) argument: %s"), arg);
+ return strbuf_addf_ret(err, -1, _("unrecognized %%(objectname) argument: %s"), arg);
+ return 0;
}
-static void refname_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int refname_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
- refname_atom_parser_internal(&atom->u.refname, arg, atom->name);
+ return refname_atom_parser_internal(&atom->u.refname, arg, atom->name, err);
}
static align_type parse_align_position(const char *s)
@@ -267,7 +303,8 @@ static align_type parse_align_position(const char *s)
return -1;
}
-static void align_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int align_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
struct align *align = &atom->u.align;
struct string_list params = STRING_LIST_INIT_DUP;
@@ -275,7 +312,7 @@ static void align_atom_parser(const struct ref_format *format, struct used_atom
unsigned int width = ~0U;
if (!arg)
- die(_("expected format: %%(align:<width>,<position>)"));
+ return strbuf_addf_ret(err, -1, _("expected format: %%(align:<width>,<position>)"));
align->position = ALIGN_LEFT;
@@ -286,49 +323,65 @@ static void align_atom_parser(const struct ref_format *format, struct used_atom
if (skip_prefix(s, "position=", &s)) {
position = parse_align_position(s);
- if (position < 0)
- die(_("unrecognized position:%s"), s);
+ if (position < 0) {
+ strbuf_addf(err, _("unrecognized position:%s"), s);
+ string_list_clear(&params, 0);
+ return -1;
+ }
align->position = position;
} else if (skip_prefix(s, "width=", &s)) {
- if (strtoul_ui(s, 10, &width))
- die(_("unrecognized width:%s"), s);
+ if (strtoul_ui(s, 10, &width)) {
+ strbuf_addf(err, _("unrecognized width:%s"), s);
+ string_list_clear(&params, 0);
+ return -1;
+ }
} else if (!strtoul_ui(s, 10, &width))
;
else if ((position = parse_align_position(s)) >= 0)
align->position = position;
- else
- die(_("unrecognized %%(align) argument: %s"), s);
+ else {
+ strbuf_addf(err, _("unrecognized %%(align) argument: %s"), s);
+ string_list_clear(&params, 0);
+ return -1;
+ }
}
- if (width == ~0U)
- die(_("positive width expected with the %%(align) atom"));
+ if (width == ~0U) {
+ string_list_clear(&params, 0);
+ return strbuf_addf_ret(err, -1, _("positive width expected with the %%(align) atom"));
+ }
align->width = width;
string_list_clear(&params, 0);
+ return 0;
}
-static void if_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int if_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err)
{
if (!arg) {
atom->u.if_then_else.cmp_status = COMPARE_NONE;
- return;
+ return 0;
} else if (skip_prefix(arg, "equals=", &atom->u.if_then_else.str)) {
atom->u.if_then_else.cmp_status = COMPARE_EQUAL;
} else if (skip_prefix(arg, "notequals=", &atom->u.if_then_else.str)) {
atom->u.if_then_else.cmp_status = COMPARE_UNEQUAL;
- } else {
- die(_("unrecognized %%(if) argument: %s"), arg);
- }
+ } else
+ return strbuf_addf_ret(err, -1, _("unrecognized %%(if) argument: %s"), arg);
+ return 0;
}
-static void head_atom_parser(const struct ref_format *format, struct used_atom *atom, const char *arg)
+static int head_atom_parser(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *unused_err)
{
atom->u.head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
+ return 0;
}
static struct {
const char *name;
cmp_type cmp_type;
- void (*parser)(const struct ref_format *format, struct used_atom *atom, const char *arg);
+ int (*parser)(const struct ref_format *format, struct used_atom *atom,
+ const char *arg, struct strbuf *err);
} valid_atom[] = {
{ "refname" , FIELD_STR, refname_atom_parser },
{ "objecttype" },
@@ -387,7 +440,8 @@ struct ref_formatting_state {
struct atom_value {
const char *s;
- void (*handler)(struct atom_value *atomv, struct ref_formatting_state *state);
+ int (*handler)(struct atom_value *atomv, struct ref_formatting_state *state,
+ struct strbuf *err);
uintmax_t value; /* used for sorting when not FIELD_STR */
struct used_atom *atom;
};
@@ -396,7 +450,8 @@ struct atom_value {
* Used to parse format string and sort specifiers
*/
static int parse_ref_filter_atom(const struct ref_format *format,
- const char *atom, const char *ep)
+ const char *atom, const char *ep,
+ struct strbuf *err)
{
const char *sp;
const char *arg;
@@ -406,7 +461,8 @@ static int parse_ref_filter_atom(const struct ref_format *format,
if (*sp == '*' && sp < ep)
sp++; /* deref */
if (ep <= sp)
- die(_("malformed field name: %.*s"), (int)(ep-atom), atom);
+ return strbuf_addf_ret(err, -1, _("malformed field name: %.*s"),
+ (int)(ep-atom), atom);
/* Do we have the atom already used elsewhere? */
for (i = 0; i < used_atom_cnt; i++) {
@@ -432,7 +488,8 @@ static int parse_ref_filter_atom(const struct ref_format *format,
}
if (ARRAY_SIZE(valid_atom) <= i)
- die(_("unknown field name: %.*s"), (int)(ep-atom), atom);
+ return strbuf_addf_ret(err, -1, _("unknown field name: %.*s"),
+ (int)(ep-atom), atom);
/* Add it in, including the deref prefix */
at = used_atom_cnt;
@@ -451,8 +508,8 @@ static int parse_ref_filter_atom(const struct ref_format *format,
}
}
memset(&used_atom[at].u, 0, sizeof(used_atom[at].u));
- if (valid_atom[i].parser)
- valid_atom[i].parser(format, &used_atom[at], arg);
+ if (valid_atom[i].parser && valid_atom[i].parser(format, &used_atom[at], arg, err))
+ return -1;
if (*atom == '*')
need_tagged = 1;
if (!strcmp(valid_atom[i].name, "symref"))
@@ -481,7 +538,8 @@ static void quote_formatting(struct strbuf *s, const char *str, int quote_style)
}
}
-static void append_atom(struct atom_value *v, struct ref_formatting_state *state)
+static int append_atom(struct atom_value *v, struct ref_formatting_state *state,
+ struct strbuf *unused_err)
{
/*
* Quote formatting is only done when the stack has a single
@@ -493,6 +551,7 @@ static void append_atom(struct atom_value *v, struct ref_formatting_state *state
quote_formatting(&state->stack->output, v->s, state->quote_style);
else
strbuf_addstr(&state->stack->output, v->s);
+ return 0;
}
static void push_stack_element(struct ref_formatting_stack **stack)
@@ -527,7 +586,8 @@ static void end_align_handler(struct ref_formatting_stack **stack)
strbuf_release(&s);
}
-static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
+static int align_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
+ struct strbuf *unused_err)
{
struct ref_formatting_stack *new_stack;
@@ -535,6 +595,7 @@ static void align_atom_handler(struct atom_value *atomv, struct ref_formatting_s
new_stack = state->stack;
new_stack->at_end = end_align_handler;
new_stack->at_end_data = &atomv->atom->u.align;
+ return 0;
}
static void if_then_else_handler(struct ref_formatting_stack **stack)
@@ -572,7 +633,8 @@ static void if_then_else_handler(struct ref_formatting_stack **stack)
free(if_then_else);
}
-static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
+static int if_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
+ struct strbuf *unused_err)
{
struct ref_formatting_stack *new_stack;
struct if_then_else *if_then_else = xcalloc(sizeof(struct if_then_else), 1);
@@ -584,6 +646,7 @@ static void if_atom_handler(struct atom_value *atomv, struct ref_formatting_stat
new_stack = state->stack;
new_stack->at_end = if_then_else_handler;
new_stack->at_end_data = if_then_else;
+ return 0;
}
static int is_empty(const char *s)
@@ -596,7 +659,8 @@ static int is_empty(const char *s)
return 1;
}
-static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
+static int then_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
+ struct strbuf *err)
{
struct ref_formatting_stack *cur = state->stack;
struct if_then_else *if_then_else = NULL;
@@ -604,11 +668,11 @@ static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_st
if (cur->at_end == if_then_else_handler)
if_then_else = (struct if_then_else *)cur->at_end_data;
if (!if_then_else)
- die(_("format: %%(then) atom used without an %%(if) atom"));
+ return strbuf_addf_ret(err, -1, _("format: %%(then) atom used without an %%(if) atom"));
if (if_then_else->then_atom_seen)
- die(_("format: %%(then) atom used more than once"));
+ return strbuf_addf_ret(err, -1, _("format: %%(then) atom used more than once"));
if (if_then_else->else_atom_seen)
- die(_("format: %%(then) atom used after %%(else)"));
+ return strbuf_addf_ret(err, -1, _("format: %%(then) atom used after %%(else)"));
if_then_else->then_atom_seen = 1;
/*
* If the 'equals' or 'notequals' attribute is used then
@@ -624,9 +688,11 @@ static void then_atom_handler(struct atom_value *atomv, struct ref_formatting_st
} else if (cur->output.len && !is_empty(cur->output.buf))
if_then_else->condition_satisfied = 1;
strbuf_reset(&cur->output);
+ return 0;
}
-static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
+static int else_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
+ struct strbuf *err)
{
struct ref_formatting_stack *prev = state->stack;
struct if_then_else *if_then_else = NULL;
@@ -634,24 +700,26 @@ static void else_atom_handler(struct atom_value *atomv, struct ref_formatting_st
if (prev->at_end == if_then_else_handler)
if_then_else = (struct if_then_else *)prev->at_end_data;
if (!if_then_else)
- die(_("format: %%(else) atom used without an %%(if) atom"));
+ return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without an %%(if) atom"));
if (!if_then_else->then_atom_seen)
- die(_("format: %%(else) atom used without a %%(then) atom"));
+ return strbuf_addf_ret(err, -1, _("format: %%(else) atom used without a %%(then) atom"));
if (if_then_else->else_atom_seen)
- die(_("format: %%(else) atom used more than once"));
+ return strbuf_addf_ret(err, -1, _("format: %%(else) atom used more than once"));
if_then_else->else_atom_seen = 1;
push_stack_element(&state->stack);
state->stack->at_end_data = prev->at_end_data;
state->stack->at_end = prev->at_end;
+ return 0;
}
-static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state)
+static int end_atom_handler(struct atom_value *atomv, struct ref_formatting_state *state,
+ struct strbuf *err)
{
struct ref_formatting_stack *current = state->stack;
struct strbuf s = STRBUF_INIT;
if (!current->at_end)
- die(_("format: %%(end) atom used without corresponding atom"));
+ return strbuf_addf_ret(err, -1, _("format: %%(end) atom used without corresponding atom"));
current->at_end(&state->stack);
/* Stack may have been popped within at_end(), hence reset the current pointer */
@@ -668,6 +736,7 @@ static void end_atom_handler(struct atom_value *atomv, struct ref_formatting_sta
}
strbuf_release(&s);
pop_stack_element(&state->stack);
+ return 0;
}
/*
@@ -702,17 +771,21 @@ int verify_ref_format(struct ref_format *format)
format->need_color_reset_at_eol = 0;
for (cp = format->format; *cp && (sp = find_next(cp)); ) {
+ struct strbuf err = STRBUF_INIT;
const char *color, *ep = strchr(sp, ')');
int at;
if (!ep)
return error(_("malformed format string %s"), sp);
/* sp points at "%(" and ep points at the closing ")" */
- at = parse_ref_filter_atom(format, sp + 2, ep);
+ at = parse_ref_filter_atom(format, sp + 2, ep, &err);
+ if (at < 0)
+ die("%s", err.buf);
cp = ep + 1;
if (skip_prefix(used_atom[at].name, "color:", &color))
format->need_color_reset_at_eol = !!strcmp(color, "reset");
+ strbuf_release(&err);
}
if (format->need_color_reset_at_eol && !want_color(format->use_color))
format->need_color_reset_at_eol = 0;
@@ -751,7 +824,7 @@ static int grab_objectname(const char *name, const struct object_id *oid,
v->s = xstrdup(find_unique_abbrev(oid, atom->u.objectname.length));
return 1;
} else
- die("BUG: unknown %%(objectname) option");
+ BUG("unknown %%(objectname) option");
}
return 0;
}
@@ -815,7 +888,7 @@ static void grab_commit_values(struct atom_value *val, int deref, struct object
if (deref)
name++;
if (!strcmp(name, "tree")) {
- v->s = xstrdup(oid_to_hex(&commit->tree->object.oid));
+ v->s = xstrdup(oid_to_hex(get_commit_tree_oid(commit)));
}
else if (!strcmp(name, "numparent")) {
v->value = commit_list_count(commit->parents);
@@ -1299,7 +1372,7 @@ static void fill_remote_ref_details(struct used_atom *atom, const char *refname,
else
*s = "";
} else
- die("BUG: unhandled RR_* enum");
+ BUG("unhandled RR_* enum");
}
char *get_head_description(void)
@@ -1309,10 +1382,14 @@ char *get_head_description(void)
memset(&state, 0, sizeof(state));
wt_status_get_state(&state, 1);
if (state.rebase_in_progress ||
- state.rebase_interactive_in_progress)
- strbuf_addf(&desc, _("(no branch, rebasing %s)"),
- state.branch);
- else if (state.bisect_in_progress)
+ state.rebase_interactive_in_progress) {
+ if (state.branch)
+ strbuf_addf(&desc, _("(no branch, rebasing %s)"),
+ state.branch);
+ else
+ strbuf_addf(&desc, _("(no branch, rebasing detached HEAD %s)"),
+ state.detached_from);
+ } else if (state.bisect_in_progress)
strbuf_addf(&desc, _("(no branch, bisect started on %s)"),
state.branch);
else if (state.detached_from) {
@@ -1354,28 +1431,30 @@ static const char *get_refname(struct used_atom *atom, struct ref_array_item *re
return show_ref(&atom->u.refname, ref->refname);
}
-static void get_object(struct ref_array_item *ref, const struct object_id *oid,
- int deref, struct object **obj)
+static int get_object(struct ref_array_item *ref, const struct object_id *oid,
+ int deref, struct object **obj, struct strbuf *err)
{
int eaten;
+ int ret = 0;
unsigned long size;
void *buf = get_obj(oid, obj, &size, &eaten);
if (!buf)
- die(_("missing object %s for %s"),
- oid_to_hex(oid), ref->refname);
- if (!*obj)
- die(_("parse_object_buffer failed on %s for %s"),
- oid_to_hex(oid), ref->refname);
-
- grab_values(ref->value, deref, *obj, buf, size);
+ ret = strbuf_addf_ret(err, -1, _("missing object %s for %s"),
+ oid_to_hex(oid), ref->refname);
+ else if (!*obj)
+ ret = strbuf_addf_ret(err, -1, _("parse_object_buffer failed on %s for %s"),
+ oid_to_hex(oid), ref->refname);
+ else
+ grab_values(ref->value, deref, *obj, buf, size);
if (!eaten)
free(buf);
+ return ret;
}
/*
* Parse the object referred by ref, and grab needed value.
*/
-static void populate_value(struct ref_array_item *ref)
+static int populate_value(struct ref_array_item *ref, struct strbuf *err)
{
struct object *obj;
int i;
@@ -1497,16 +1576,17 @@ static void populate_value(struct ref_array_item *ref)
break;
}
if (used_atom_cnt <= i)
- return;
+ return 0;
- get_object(ref, &ref->objectname, 0, &obj);
+ if (get_object(ref, &ref->objectname, 0, &obj, err))
+ return -1;
/*
* If there is no atom that wants to know about tagged
* object, we are done.
*/
if (!need_tagged || (obj->type != OBJ_TAG))
- return;
+ return 0;
/*
* If it is a tag object, see if we use a value that derefs
@@ -1520,20 +1600,23 @@ static void populate_value(struct ref_array_item *ref)
* is not consistent with what deref_tag() does
* which peels the onion to the core.
*/
- get_object(ref, tagged, 1, &obj);
+ return get_object(ref, tagged, 1, &obj, err);
}
/*
* Given a ref, return the value for the atom. This lazily gets value
* out of the object by calling populate value.
*/
-static void get_ref_atom_value(struct ref_array_item *ref, int atom, struct atom_value **v)
+static int get_ref_atom_value(struct ref_array_item *ref, int atom,
+ struct atom_value **v, struct strbuf *err)
{
if (!ref->value) {
- populate_value(ref);
+ if (populate_value(ref, err))
+ return -1;
fill_missing_values(ref->value);
}
*v = &ref->value[atom];
+ return 0;
}
/*
@@ -1824,15 +1907,30 @@ static const struct object_id *match_points_at(struct oid_array *points_at,
return NULL;
}
-/* Allocate space for a new ref_array_item and copy the objectname and flag to it */
+/*
+ * Allocate space for a new ref_array_item and copy the name and oid to it.
+ *
+ * Callers can then fill in other struct members at their leisure.
+ */
static struct ref_array_item *new_ref_array_item(const char *refname,
- const unsigned char *objectname,
- int flag)
+ const struct object_id *oid)
{
struct ref_array_item *ref;
+
FLEX_ALLOC_STR(ref, refname, refname);
- hashcpy(ref->objectname.hash, objectname);
- ref->flag = flag;
+ oidcpy(&ref->objectname, oid);
+
+ return ref;
+}
+
+struct ref_array_item *ref_array_push(struct ref_array *array,
+ const char *refname,
+ const struct object_id *oid)
+{
+ struct ref_array_item *ref = new_ref_array_item(refname, oid);
+
+ ALLOC_GROW(array->items, array->nr + 1, array->alloc);
+ array->items[array->nr++] = ref;
return ref;
}
@@ -1927,12 +2025,11 @@ static int ref_filter_handler(const char *refname, const struct object_id *oid,
* to do its job and the resulting list may yet to be pruned
* by maxcount logic.
*/
- ref = new_ref_array_item(refname, oid->hash, flag);
+ ref = ref_array_push(ref_cbdata->array, refname, oid);
ref->commit = commit;
-
- REALLOC_ARRAY(ref_cbdata->array->items, ref_cbdata->array->nr + 1);
- ref_cbdata->array->items[ref_cbdata->array->nr++] = ref;
+ ref->flag = flag;
ref->kind = kind;
+
return 0;
}
@@ -2057,9 +2154,13 @@ static int cmp_ref_sorting(struct ref_sorting *s, struct ref_array_item *a, stru
int cmp;
cmp_type cmp_type = used_atom[s->atom].type;
int (*cmp_fn)(const char *, const char *);
+ struct strbuf err = STRBUF_INIT;
- get_ref_atom_value(a, s->atom, &va);
- get_ref_atom_value(b, s->atom, &vb);
+ if (get_ref_atom_value(a, s->atom, &va, &err))
+ die("%s", err.buf);
+ if (get_ref_atom_value(b, s->atom, &vb, &err))
+ die("%s", err.buf);
+ strbuf_release(&err);
cmp_fn = s->ignore_case ? strcasecmp : strcmp;
if (s->version)
cmp = versioncmp(va->s, vb->s);
@@ -2118,9 +2219,10 @@ static void append_literal(const char *cp, const char *ep, struct ref_formatting
}
}
-void format_ref_array_item(struct ref_array_item *info,
+int format_ref_array_item(struct ref_array_item *info,
const struct ref_format *format,
- struct strbuf *final_buf)
+ struct strbuf *final_buf,
+ struct strbuf *error_buf)
{
const char *cp, *sp, *ep;
struct ref_formatting_state state = REF_FORMATTING_STATE_INIT;
@@ -2130,14 +2232,17 @@ void format_ref_array_item(struct ref_array_item *info,
for (cp = format->format; *cp && (sp = find_next(cp)); cp = ep + 1) {
struct atom_value *atomv;
+ int pos;
ep = strchr(sp, ')');
if (cp < sp)
append_literal(cp, sp, &state);
- get_ref_atom_value(info,
- parse_ref_filter_atom(format, sp + 2, ep),
- &atomv);
- atomv->handler(atomv, &state);
+ pos = parse_ref_filter_atom(format, sp + 2, ep, error_buf);
+ if (pos < 0 || get_ref_atom_value(info, pos, &atomv, error_buf) ||
+ atomv->handler(atomv, &state, error_buf)) {
+ pop_stack_element(&state.stack);
+ return -1;
+ }
}
if (*cp) {
sp = cp + strlen(cp);
@@ -2146,30 +2251,39 @@ void format_ref_array_item(struct ref_array_item *info,
if (format->need_color_reset_at_eol) {
struct atom_value resetv;
resetv.s = GIT_COLOR_RESET;
- append_atom(&resetv, &state);
+ if (append_atom(&resetv, &state, error_buf)) {
+ pop_stack_element(&state.stack);
+ return -1;
+ }
+ }
+ if (state.stack->prev) {
+ pop_stack_element(&state.stack);
+ return strbuf_addf_ret(error_buf, -1, _("format: %%(end) atom missing"));
}
- if (state.stack->prev)
- die(_("format: %%(end) atom missing"));
strbuf_addbuf(final_buf, &state.stack->output);
pop_stack_element(&state.stack);
+ return 0;
}
void show_ref_array_item(struct ref_array_item *info,
const struct ref_format *format)
{
struct strbuf final_buf = STRBUF_INIT;
+ struct strbuf error_buf = STRBUF_INIT;
- format_ref_array_item(info, format, &final_buf);
+ if (format_ref_array_item(info, format, &final_buf, &error_buf))
+ die("%s", error_buf.buf);
fwrite(final_buf.buf, 1, final_buf.len, stdout);
+ strbuf_release(&error_buf);
strbuf_release(&final_buf);
putchar('\n');
}
-void pretty_print_ref(const char *name, const unsigned char *sha1,
+void pretty_print_ref(const char *name, const struct object_id *oid,
const struct ref_format *format)
{
struct ref_array_item *ref_item;
- ref_item = new_ref_array_item(name, sha1, 0);
+ ref_item = new_ref_array_item(name, oid);
ref_item->kind = ref_kind_from_refname(name);
show_ref_array_item(ref_item, format);
free_array_item(ref_item);
@@ -2183,7 +2297,12 @@ static int parse_sorting_atom(const char *atom)
*/
struct ref_format dummy = REF_FORMAT_INIT;
const char *end = atom + strlen(atom);
- return parse_ref_filter_atom(&dummy, atom, end);
+ struct strbuf err = STRBUF_INIT;
+ int res = parse_ref_filter_atom(&dummy, atom, end, &err);
+ if (res < 0)
+ die("%s", err.buf);
+ strbuf_release(&err);
+ return res;
}
/* If no sorting option is given, use refname to sort as default */
diff --git a/ref-filter.h b/ref-filter.h
index 0d98342..85c8ebc 100644
--- a/ref-filter.h
+++ b/ref-filter.h
@@ -110,9 +110,10 @@ int verify_ref_format(struct ref_format *format);
/* Sort the given ref_array as per the ref_sorting provided */
void ref_array_sort(struct ref_sorting *sort, struct ref_array *array);
/* Based on the given format and quote_style, fill the strbuf */
-void format_ref_array_item(struct ref_array_item *info,
- const struct ref_format *format,
- struct strbuf *final_buf);
+int format_ref_array_item(struct ref_array_item *info,
+ const struct ref_format *format,
+ struct strbuf *final_buf,
+ struct strbuf *error_buf);
/* Print the ref using the given format and quote_style */
void show_ref_array_item(struct ref_array_item *info, const struct ref_format *format);
/* Parse a single sort specifier and add it to the list */
@@ -132,7 +133,15 @@ void setup_ref_filter_porcelain_msg(void);
* Print a single ref, outside of any ref-filter. Note that the
* name must be a fully qualified refname.
*/
-void pretty_print_ref(const char *name, const unsigned char *sha1,
+void pretty_print_ref(const char *name, const struct object_id *oid,
const struct ref_format *format);
+/*
+ * Push a single ref onto the array; this can be used to construct your own
+ * ref_array without using filter_refs().
+ */
+struct ref_array_item *ref_array_push(struct ref_array *array,
+ const char *refname,
+ const struct object_id *oid);
+
#endif /* REF_FILTER_H */
diff --git a/refs.c b/refs.c
index 8b7a77f..0eb379f 100644
--- a/refs.c
+++ b/refs.c
@@ -13,6 +13,8 @@
#include "tag.h"
#include "submodule.h"
#include "worktree.h"
+#include "argv-array.h"
+#include "repository.h"
/*
* List of all available backends
@@ -206,7 +208,7 @@ char *refs_resolve_refdup(struct ref_store *refs,
char *resolve_refdup(const char *refname, int resolve_flags,
struct object_id *oid, int *flags)
{
- return refs_resolve_refdup(get_main_ref_store(),
+ return refs_resolve_refdup(get_main_ref_store(the_repository),
refname, resolve_flags,
oid, flags);
}
@@ -228,7 +230,7 @@ int refs_read_ref_full(struct ref_store *refs, const char *refname,
int read_ref_full(const char *refname, int resolve_flags, struct object_id *oid, int *flags)
{
- return refs_read_ref_full(get_main_ref_store(), refname,
+ return refs_read_ref_full(get_main_ref_store(the_repository), refname,
resolve_flags, oid, flags);
}
@@ -301,7 +303,7 @@ enum peel_status peel_object(const struct object_id *name, struct object_id *oid
struct object *o = lookup_unknown_object(name->hash);
if (o->type == OBJ_NONE) {
- int type = oid_object_info(name, NULL);
+ int type = oid_object_info(the_repository, name, NULL);
if (type < 0 || !object_as_type(o, type, 0))
return PEEL_INVALID;
}
@@ -375,7 +377,7 @@ int refs_for_each_tag_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
int for_each_tag_ref(each_ref_fn fn, void *cb_data)
{
- return refs_for_each_tag_ref(get_main_ref_store(), fn, cb_data);
+ return refs_for_each_tag_ref(get_main_ref_store(the_repository), fn, cb_data);
}
int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
@@ -385,7 +387,7 @@ int refs_for_each_branch_ref(struct ref_store *refs, each_ref_fn fn, void *cb_da
int for_each_branch_ref(each_ref_fn fn, void *cb_data)
{
- return refs_for_each_branch_ref(get_main_ref_store(), fn, cb_data);
+ return refs_for_each_branch_ref(get_main_ref_store(the_repository), fn, cb_data);
}
int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
@@ -395,7 +397,7 @@ int refs_for_each_remote_ref(struct ref_store *refs, each_ref_fn fn, void *cb_da
int for_each_remote_ref(each_ref_fn fn, void *cb_data)
{
- return refs_for_each_remote_ref(get_main_ref_store(), fn, cb_data);
+ return refs_for_each_remote_ref(get_main_ref_store(the_repository), fn, cb_data);
}
int head_ref_namespaced(each_ref_fn fn, void *cb_data)
@@ -502,6 +504,19 @@ int refname_match(const char *abbrev_name, const char *full_name)
}
/*
+ * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
+ * the results to 'prefixes'
+ */
+void expand_ref_prefix(struct argv_array *prefixes, const char *prefix)
+{
+ const char **p;
+ int len = strlen(prefix);
+
+ for (p = ref_rev_parse_rules; *p; p++)
+ argv_array_pushf(prefixes, *p, len, prefix);
+}
+
+/*
* *string and *len will only be substituted, and *string returned (for
* later free()ing) if the string passed in is a magic short-hand form
* to name a branch.
@@ -600,7 +615,8 @@ int dwim_log(const char *str, int len, struct object_id *oid, char **log)
static int is_per_worktree_ref(const char *refname)
{
return !strcmp(refname, "HEAD") ||
- starts_with(refname, "refs/bisect/");
+ starts_with(refname, "refs/bisect/") ||
+ starts_with(refname, "refs/rewritten/");
}
static int is_pseudoref_syntax(const char *refname)
@@ -644,7 +660,7 @@ static int write_pseudoref(const char *pseudoref, const struct object_id *oid,
{
const char *filename;
int fd;
- static struct lock_file lock;
+ struct lock_file lock = LOCK_INIT;
struct strbuf buf = STRBUF_INIT;
int ret = -1;
@@ -654,8 +670,7 @@ static int write_pseudoref(const char *pseudoref, const struct object_id *oid,
strbuf_addf(&buf, "%s\n", oid_to_hex(oid));
filename = git_path("%s", pseudoref);
- fd = hold_lock_file_for_update_timeout(&lock, filename,
- LOCK_DIE_ON_ERROR,
+ fd = hold_lock_file_for_update_timeout(&lock, filename, 0,
get_files_ref_lock_timeout_ms());
if (fd < 0) {
strbuf_addf(err, "could not open '%s' for writing: %s",
@@ -666,10 +681,21 @@ static int write_pseudoref(const char *pseudoref, const struct object_id *oid,
if (old_oid) {
struct object_id actual_old_oid;
- if (read_ref(pseudoref, &actual_old_oid))
- die("could not read ref '%s'", pseudoref);
- if (oidcmp(&actual_old_oid, old_oid)) {
- strbuf_addf(err, "unexpected sha1 when writing '%s'", pseudoref);
+ if (read_ref(pseudoref, &actual_old_oid)) {
+ if (!is_null_oid(old_oid)) {
+ strbuf_addf(err, "could not read ref '%s'",
+ pseudoref);
+ rollback_lock_file(&lock);
+ goto done;
+ }
+ } else if (is_null_oid(old_oid)) {
+ strbuf_addf(err, "ref '%s' already exists",
+ pseudoref);
+ rollback_lock_file(&lock);
+ goto done;
+ } else if (oidcmp(&actual_old_oid, old_oid)) {
+ strbuf_addf(err, "unexpected object ID when writing '%s'",
+ pseudoref);
rollback_lock_file(&lock);
goto done;
}
@@ -690,24 +716,28 @@ done:
static int delete_pseudoref(const char *pseudoref, const struct object_id *old_oid)
{
- static struct lock_file lock;
const char *filename;
filename = git_path("%s", pseudoref);
if (old_oid && !is_null_oid(old_oid)) {
+ struct lock_file lock = LOCK_INIT;
int fd;
struct object_id actual_old_oid;
fd = hold_lock_file_for_update_timeout(
- &lock, filename, LOCK_DIE_ON_ERROR,
+ &lock, filename, 0,
get_files_ref_lock_timeout_ms());
- if (fd < 0)
- die_errno(_("Could not open '%s' for writing"), filename);
+ if (fd < 0) {
+ error_errno(_("could not open '%s' for writing"),
+ filename);
+ return -1;
+ }
if (read_ref(pseudoref, &actual_old_oid))
die("could not read ref '%s'", pseudoref);
if (oidcmp(&actual_old_oid, old_oid)) {
- warning("Unexpected sha1 when deleting %s", pseudoref);
+ error("unexpected object ID when deleting '%s'",
+ pseudoref);
rollback_lock_file(&lock);
return -1;
}
@@ -730,7 +760,7 @@ int refs_delete_ref(struct ref_store *refs, const char *msg,
struct strbuf err = STRBUF_INIT;
if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
- assert(refs == get_main_ref_store());
+ assert(refs == get_main_ref_store(the_repository));
return delete_pseudoref(refname, old_oid);
}
@@ -752,7 +782,7 @@ int refs_delete_ref(struct ref_store *refs, const char *msg,
int delete_ref(const char *msg, const char *refname,
const struct object_id *old_oid, unsigned int flags)
{
- return refs_delete_ref(get_main_ref_store(), msg, refname,
+ return refs_delete_ref(get_main_ref_store(the_repository), msg, refname,
old_oid, flags);
}
@@ -928,7 +958,7 @@ struct ref_transaction *ref_store_transaction_begin(struct ref_store *refs,
struct ref_transaction *ref_transaction_begin(struct strbuf *err)
{
- return ref_store_transaction_begin(get_main_ref_store(), err);
+ return ref_store_transaction_begin(get_main_ref_store(the_repository), err);
}
void ref_transaction_free(struct ref_transaction *transaction)
@@ -944,10 +974,10 @@ void ref_transaction_free(struct ref_transaction *transaction)
/* OK */
break;
case REF_TRANSACTION_PREPARED:
- die("BUG: free called on a prepared reference transaction");
+ BUG("free called on a prepared reference transaction");
break;
default:
- die("BUG: unexpected reference transaction state");
+ BUG("unexpected reference transaction state");
break;
}
@@ -969,7 +999,7 @@ struct ref_update *ref_transaction_add_update(
struct ref_update *update;
if (transaction->state != REF_TRANSACTION_OPEN)
- die("BUG: update called for transaction that is not open");
+ BUG("update called for transaction that is not open");
FLEX_ALLOC_STR(update, refname, refname);
ALLOC_GROW(transaction->updates, transaction->nr + 1, transaction->alloc);
@@ -1019,7 +1049,7 @@ int ref_transaction_create(struct ref_transaction *transaction,
struct strbuf *err)
{
if (!new_oid || is_null_oid(new_oid))
- die("BUG: create called without valid new_oid");
+ BUG("create called without valid new_oid");
return ref_transaction_update(transaction, refname, new_oid,
&null_oid, flags, msg, err);
}
@@ -1031,7 +1061,7 @@ int ref_transaction_delete(struct ref_transaction *transaction,
struct strbuf *err)
{
if (old_oid && is_null_oid(old_oid))
- die("BUG: delete called with old_oid set to zeros");
+ BUG("delete called with old_oid set to zeros");
return ref_transaction_update(transaction, refname,
&null_oid, old_oid,
flags, msg, err);
@@ -1044,7 +1074,7 @@ int ref_transaction_verify(struct ref_transaction *transaction,
struct strbuf *err)
{
if (!old_oid)
- die("BUG: verify called with old_oid set to NULL");
+ BUG("verify called with old_oid set to NULL");
return ref_transaction_update(transaction, refname,
NULL, old_oid,
flags, NULL, err);
@@ -1060,7 +1090,7 @@ int refs_update_ref(struct ref_store *refs, const char *msg,
int ret = 0;
if (ref_type(refname) == REF_TYPE_PSEUDOREF) {
- assert(refs == get_main_ref_store());
+ assert(refs == get_main_ref_store(the_repository));
ret = write_pseudoref(refname, new_oid, old_oid, &err);
} else {
t = ref_store_transaction_begin(refs, &err);
@@ -1099,7 +1129,7 @@ int update_ref(const char *msg, const char *refname,
const struct object_id *old_oid,
unsigned int flags, enum action_on_err onerr)
{
- return refs_update_ref(get_main_ref_store(), msg, refname, new_oid,
+ return refs_update_ref(get_main_ref_store(the_repository), msg, refname, new_oid,
old_oid, flags, onerr);
}
@@ -1132,8 +1162,8 @@ char *shorten_unambiguous_ref(const char *refname, int strict)
for (i = 0; i < nr_rules; i++) {
assert(offset < total_len);
scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + offset;
- offset += snprintf(scanf_fmts[i], total_len - offset,
- ref_rev_parse_rules[i], 2, "%s") + 1;
+ offset += xsnprintf(scanf_fmts[i], total_len - offset,
+ ref_rev_parse_rules[i], 2, "%s") + 1;
}
}
@@ -1320,7 +1350,7 @@ int refs_head_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
int head_ref(each_ref_fn fn, void *cb_data)
{
- return refs_head_ref(get_main_ref_store(), fn, cb_data);
+ return refs_head_ref(get_main_ref_store(the_repository), fn, cb_data);
}
struct ref_iterator *refs_ref_iterator_begin(
@@ -1379,7 +1409,7 @@ int refs_for_each_ref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
int for_each_ref(each_ref_fn fn, void *cb_data)
{
- return refs_for_each_ref(get_main_ref_store(), fn, cb_data);
+ return refs_for_each_ref(get_main_ref_store(the_repository), fn, cb_data);
}
int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
@@ -1390,7 +1420,7 @@ int refs_for_each_ref_in(struct ref_store *refs, const char *prefix,
int for_each_ref_in(const char *prefix, each_ref_fn fn, void *cb_data)
{
- return refs_for_each_ref_in(get_main_ref_store(), prefix, fn, cb_data);
+ return refs_for_each_ref_in(get_main_ref_store(the_repository), prefix, fn, cb_data);
}
int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsigned int broken)
@@ -1399,7 +1429,7 @@ int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data, unsig
if (broken)
flag = DO_FOR_EACH_INCLUDE_BROKEN;
- return do_for_each_ref(get_main_ref_store(),
+ return do_for_each_ref(get_main_ref_store(the_repository),
prefix, fn, 0, flag, cb_data);
}
@@ -1414,9 +1444,9 @@ int refs_for_each_fullref_in(struct ref_store *refs, const char *prefix,
return do_for_each_ref(refs, prefix, fn, 0, flag, cb_data);
}
-int for_each_replace_ref(each_ref_fn fn, void *cb_data)
+int for_each_replace_ref(struct repository *r, each_ref_fn fn, void *cb_data)
{
- return do_for_each_ref(get_main_ref_store(),
+ return do_for_each_ref(get_main_ref_store(r),
git_replace_ref_base, fn,
strlen(git_replace_ref_base),
DO_FOR_EACH_INCLUDE_BROKEN, cb_data);
@@ -1427,7 +1457,7 @@ int for_each_namespaced_ref(each_ref_fn fn, void *cb_data)
struct strbuf buf = STRBUF_INIT;
int ret;
strbuf_addf(&buf, "%srefs/", get_git_namespace());
- ret = do_for_each_ref(get_main_ref_store(),
+ ret = do_for_each_ref(get_main_ref_store(the_repository),
buf.buf, fn, 0, 0, cb_data);
strbuf_release(&buf);
return ret;
@@ -1441,7 +1471,7 @@ int refs_for_each_rawref(struct ref_store *refs, each_ref_fn fn, void *cb_data)
int for_each_rawref(each_ref_fn fn, void *cb_data)
{
- return refs_for_each_rawref(get_main_ref_store(), fn, cb_data);
+ return refs_for_each_rawref(get_main_ref_store(the_repository), fn, cb_data);
}
int refs_read_raw_ref(struct ref_store *ref_store,
@@ -1547,7 +1577,7 @@ const char *refs_resolve_ref_unsafe(struct ref_store *refs,
/* backend functions */
int refs_init_db(struct strbuf *err)
{
- struct ref_store *refs = get_main_ref_store();
+ struct ref_store *refs = get_main_ref_store(the_repository);
return refs->be->init_db(refs, err);
}
@@ -1555,7 +1585,7 @@ int refs_init_db(struct strbuf *err)
const char *resolve_ref_unsafe(const char *refname, int resolve_flags,
struct object_id *oid, int *flags)
{
- return refs_resolve_ref_unsafe(get_main_ref_store(), refname,
+ return refs_resolve_ref_unsafe(get_main_ref_store(the_repository), refname,
resolve_flags, oid, flags);
}
@@ -1607,9 +1637,6 @@ static struct ref_store_hash_entry *alloc_ref_store_hash_entry(
return entry;
}
-/* A pointer to the ref_store for the main repository: */
-static struct ref_store *main_ref_store;
-
/* A hashmap of ref_stores, stored by submodule name: */
static struct hashmap submodule_ref_stores;
@@ -1645,19 +1672,22 @@ static struct ref_store *ref_store_init(const char *gitdir,
struct ref_store *refs;
if (!be)
- die("BUG: reference backend %s is unknown", be_name);
+ BUG("reference backend %s is unknown", be_name);
refs = be->init(gitdir, flags);
return refs;
}
-struct ref_store *get_main_ref_store(void)
+struct ref_store *get_main_ref_store(struct repository *r)
{
- if (main_ref_store)
- return main_ref_store;
+ if (r->refs)
+ return r->refs;
+
+ if (!r->gitdir)
+ BUG("attempting to get main_ref_store outside of repository");
- main_ref_store = ref_store_init(get_git_dir(), REF_STORE_ALL_CAPS);
- return main_ref_store;
+ r->refs = ref_store_init(r->gitdir, REF_STORE_ALL_CAPS);
+ return r->refs;
}
/*
@@ -1673,7 +1703,7 @@ static void register_ref_store_map(struct hashmap *map,
hashmap_init(map, ref_store_hash_cmp, NULL, 0);
if (hashmap_put(map, alloc_ref_store_hash_entry(name, refs)))
- die("BUG: %s ref_store '%s' initialized twice", type, name);
+ BUG("%s ref_store '%s' initialized twice", type, name);
}
struct ref_store *get_submodule_ref_store(const char *submodule)
@@ -1726,7 +1756,7 @@ struct ref_store *get_worktree_ref_store(const struct worktree *wt)
const char *id;
if (wt->is_current)
- return get_main_ref_store();
+ return get_main_ref_store(the_repository);
id = wt->id ? wt->id : "/";
refs = lookup_ref_store_map(&worktree_ref_stores, id);
@@ -1782,7 +1812,7 @@ int refs_peel_ref(struct ref_store *refs, const char *refname,
int peel_ref(const char *refname, struct object_id *oid)
{
- return refs_peel_ref(get_main_ref_store(), refname, oid);
+ return refs_peel_ref(get_main_ref_store(the_repository), refname, oid);
}
int refs_create_symref(struct ref_store *refs,
@@ -1798,7 +1828,7 @@ int refs_create_symref(struct ref_store *refs,
int create_symref(const char *ref_target, const char *refs_heads_master,
const char *logmsg)
{
- return refs_create_symref(get_main_ref_store(), ref_target,
+ return refs_create_symref(get_main_ref_store(the_repository), ref_target,
refs_heads_master, logmsg);
}
@@ -1819,7 +1849,7 @@ int ref_update_reject_duplicates(struct string_list *refnames,
refnames->items[i].string);
return 1;
} else if (cmp > 0) {
- die("BUG: ref_update_reject_duplicates() received unsorted list");
+ BUG("ref_update_reject_duplicates() received unsorted list");
}
}
return 0;
@@ -1835,13 +1865,13 @@ int ref_transaction_prepare(struct ref_transaction *transaction,
/* Good. */
break;
case REF_TRANSACTION_PREPARED:
- die("BUG: prepare called twice on reference transaction");
+ BUG("prepare called twice on reference transaction");
break;
case REF_TRANSACTION_CLOSED:
- die("BUG: prepare called on a closed reference transaction");
+ BUG("prepare called on a closed reference transaction");
break;
default:
- die("BUG: unexpected reference transaction state");
+ BUG("unexpected reference transaction state");
break;
}
@@ -1868,10 +1898,10 @@ int ref_transaction_abort(struct ref_transaction *transaction,
ret = refs->be->transaction_abort(refs, transaction, err);
break;
case REF_TRANSACTION_CLOSED:
- die("BUG: abort called on a closed reference transaction");
+ BUG("abort called on a closed reference transaction");
break;
default:
- die("BUG: unexpected reference transaction state");
+ BUG("unexpected reference transaction state");
break;
}
@@ -1896,10 +1926,10 @@ int ref_transaction_commit(struct ref_transaction *transaction,
/* Fall through to finish. */
break;
case REF_TRANSACTION_CLOSED:
- die("BUG: commit called on a closed reference transaction");
+ BUG("commit called on a closed reference transaction");
break;
default:
- die("BUG: unexpected reference transaction state");
+ BUG("unexpected reference transaction state");
break;
}
@@ -1980,7 +2010,7 @@ int refs_verify_refname_available(struct ref_store *refs,
}
if (ok != ITER_DONE)
- die("BUG: error while iterating over references");
+ BUG("error while iterating over references");
extra_refname = find_descendant_ref(dirname.buf, extras, skip);
if (extra_refname)
@@ -2006,7 +2036,7 @@ int refs_for_each_reflog(struct ref_store *refs, each_ref_fn fn, void *cb_data)
int for_each_reflog(each_ref_fn fn, void *cb_data)
{
- return refs_for_each_reflog(get_main_ref_store(), fn, cb_data);
+ return refs_for_each_reflog(get_main_ref_store(the_repository), fn, cb_data);
}
int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
@@ -2021,7 +2051,7 @@ int refs_for_each_reflog_ent_reverse(struct ref_store *refs,
int for_each_reflog_ent_reverse(const char *refname, each_reflog_ent_fn fn,
void *cb_data)
{
- return refs_for_each_reflog_ent_reverse(get_main_ref_store(),
+ return refs_for_each_reflog_ent_reverse(get_main_ref_store(the_repository),
refname, fn, cb_data);
}
@@ -2034,7 +2064,7 @@ int refs_for_each_reflog_ent(struct ref_store *refs, const char *refname,
int for_each_reflog_ent(const char *refname, each_reflog_ent_fn fn,
void *cb_data)
{
- return refs_for_each_reflog_ent(get_main_ref_store(), refname,
+ return refs_for_each_reflog_ent(get_main_ref_store(the_repository), refname,
fn, cb_data);
}
@@ -2045,7 +2075,7 @@ int refs_reflog_exists(struct ref_store *refs, const char *refname)
int reflog_exists(const char *refname)
{
- return refs_reflog_exists(get_main_ref_store(), refname);
+ return refs_reflog_exists(get_main_ref_store(the_repository), refname);
}
int refs_create_reflog(struct ref_store *refs, const char *refname,
@@ -2057,7 +2087,7 @@ int refs_create_reflog(struct ref_store *refs, const char *refname,
int safe_create_reflog(const char *refname, int force_create,
struct strbuf *err)
{
- return refs_create_reflog(get_main_ref_store(), refname,
+ return refs_create_reflog(get_main_ref_store(the_repository), refname,
force_create, err);
}
@@ -2068,7 +2098,7 @@ int refs_delete_reflog(struct ref_store *refs, const char *refname)
int delete_reflog(const char *refname)
{
- return refs_delete_reflog(get_main_ref_store(), refname);
+ return refs_delete_reflog(get_main_ref_store(the_repository), refname);
}
int refs_reflog_expire(struct ref_store *refs,
@@ -2091,7 +2121,7 @@ int reflog_expire(const char *refname, const struct object_id *oid,
reflog_expiry_cleanup_fn cleanup_fn,
void *policy_cb_data)
{
- return refs_reflog_expire(get_main_ref_store(),
+ return refs_reflog_expire(get_main_ref_store(the_repository),
refname, oid, flags,
prepare_fn, should_prune_fn,
cleanup_fn, policy_cb_data);
@@ -2114,7 +2144,7 @@ int refs_delete_refs(struct ref_store *refs, const char *msg,
int delete_refs(const char *msg, struct string_list *refnames,
unsigned int flags)
{
- return refs_delete_refs(get_main_ref_store(), msg, refnames, flags);
+ return refs_delete_refs(get_main_ref_store(the_repository), msg, refnames, flags);
}
int refs_rename_ref(struct ref_store *refs, const char *oldref,
@@ -2125,7 +2155,7 @@ int refs_rename_ref(struct ref_store *refs, const char *oldref,
int rename_ref(const char *oldref, const char *newref, const char *logmsg)
{
- return refs_rename_ref(get_main_ref_store(), oldref, newref, logmsg);
+ return refs_rename_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);
}
int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
@@ -2136,5 +2166,5 @@ int refs_copy_existing_ref(struct ref_store *refs, const char *oldref,
int copy_existing_ref(const char *oldref, const char *newref, const char *logmsg)
{
- return refs_copy_existing_ref(get_main_ref_store(), oldref, newref, logmsg);
+ return refs_copy_existing_ref(get_main_ref_store(the_repository), oldref, newref, logmsg);
}
diff --git a/refs.h b/refs.h
index 01be5ae..cc2fb4c 100644
--- a/refs.h
+++ b/refs.h
@@ -139,6 +139,13 @@ int resolve_gitlink_ref(const char *submodule, const char *refname,
*/
int refname_match(const char *abbrev_name, const char *full_name);
+/*
+ * Given a 'prefix' expand it by the rules in 'ref_rev_parse_rules' and add
+ * the results to 'prefixes'
+ */
+struct argv_array;
+void expand_ref_prefix(struct argv_array *prefixes, const char *prefix);
+
int expand_ref(const char *str, int len, struct object_id *oid, char **ref);
int dwim_ref(const char *str, int len, struct object_id *oid, char **ref);
int dwim_log(const char *str, int len, struct object_id *oid, char **ref);
@@ -300,7 +307,7 @@ int for_each_fullref_in(const char *prefix, each_ref_fn fn, void *cb_data,
int for_each_tag_ref(each_ref_fn fn, void *cb_data);
int for_each_branch_ref(each_ref_fn fn, void *cb_data);
int for_each_remote_ref(each_ref_fn fn, void *cb_data);
-int for_each_replace_ref(each_ref_fn fn, void *cb_data);
+int for_each_replace_ref(struct repository *r, each_ref_fn fn, void *cb_data);
int for_each_glob_ref(each_ref_fn fn, const char *pattern, void *cb_data);
int for_each_glob_ref_in(each_ref_fn fn, const char *pattern,
const char *prefix, void *cb_data);
@@ -758,7 +765,7 @@ int reflog_expire(const char *refname, const struct object_id *oid,
int ref_storage_backend_exists(const char *name);
-struct ref_store *get_main_ref_store(void);
+struct ref_store *get_main_ref_store(struct repository *r);
/*
* Return the ref_store instance for the specified submodule. For the
* main repository, use submodule==NULL; such a call cannot fail. For
diff --git a/refs/files-backend.c b/refs/files-backend.c
index bec8e30..a9a066d 100644
--- a/refs/files-backend.c
+++ b/refs/files-backend.c
@@ -9,6 +9,7 @@
#include "../lockfile.h"
#include "../object.h"
#include "../dir.h"
+#include "../chdir-notify.h"
/*
* This backend uses the following flags in `ref_update::flags` for
@@ -61,10 +62,6 @@ struct ref_lock {
struct object_id old_oid;
};
-/*
- * Future: need to be in "struct repository"
- * when doing a full libification.
- */
struct files_ref_store {
struct ref_store base;
unsigned int store_flags;
@@ -106,6 +103,11 @@ static struct ref_store *files_ref_store_create(const char *gitdir,
refs->packed_ref_store = packed_ref_store_create(sb.buf, flags);
strbuf_release(&sb);
+ chdir_notify_reparent("files-backend $GIT_DIR",
+ &refs->gitdir);
+ chdir_notify_reparent("files-backend $GIT_COMMONDIR",
+ &refs->gitcommondir);
+
return ref_store;
}
@@ -119,7 +121,7 @@ static void files_assert_main_repository(struct files_ref_store *refs,
if (refs->store_flags & REF_STORE_MAIN)
return;
- die("BUG: operation %s only allowed for main ref store", caller);
+ BUG("operation %s only allowed for main ref store", caller);
}
/*
@@ -135,13 +137,13 @@ static struct files_ref_store *files_downcast(struct ref_store *ref_store,
struct files_ref_store *refs;
if (ref_store->be != &refs_be_files)
- die("BUG: ref_store is type \"%s\" not \"files\" in %s",
+ BUG("ref_store is type \"%s\" not \"files\" in %s",
ref_store->be->name, caller);
refs = (struct files_ref_store *)ref_store;
if ((refs->store_flags & required_flags) != required_flags)
- die("BUG: operation %s requires abilities 0x%x, but only have 0x%x",
+ BUG("operation %s requires abilities 0x%x, but only have 0x%x",
caller, required_flags, refs->store_flags);
return refs;
@@ -160,7 +162,7 @@ static void files_reflog_path(struct files_ref_store *refs,
strbuf_addf(sb, "%s/logs/%s", refs->gitcommondir, refname);
break;
default:
- die("BUG: unknown ref type %d of ref %s",
+ BUG("unknown ref type %d of ref %s",
ref_type(refname), refname);
}
}
@@ -178,7 +180,7 @@ static void files_ref_path(struct files_ref_store *refs,
strbuf_addf(sb, "%s/%s", refs->gitcommondir, refname);
break;
default:
- die("BUG: unknown ref type %d of ref %s",
+ BUG("unknown ref type %d of ref %s",
ref_type(refname), refname);
}
}
@@ -2004,7 +2006,7 @@ static int files_for_each_reflog_ent_reverse(struct ref_store *ref_store,
}
if (!ret && sb.len)
- die("BUG: reverse reflog parser had leftover data");
+ BUG("reverse reflog parser had leftover data");
fclose(logfp);
strbuf_release(&sb);
@@ -2082,7 +2084,7 @@ static int files_reflog_iterator_advance(struct ref_iterator *ref_iterator)
static int files_reflog_iterator_peel(struct ref_iterator *ref_iterator,
struct object_id *peeled)
{
- die("BUG: ref_iterator_peel() called for reflog_iterator");
+ BUG("ref_iterator_peel() called for reflog_iterator");
}
static int files_reflog_iterator_abort(struct ref_iterator *ref_iterator)
@@ -2867,7 +2869,7 @@ static int files_initial_transaction_commit(struct ref_store *ref_store,
assert(err);
if (transaction->state != REF_TRANSACTION_OPEN)
- die("BUG: commit called for transaction that is not open");
+ BUG("commit called for transaction that is not open");
/* Fail if a refname appears more than once in the transaction: */
for (i = 0; i < transaction->nr; i++)
@@ -2893,7 +2895,7 @@ static int files_initial_transaction_commit(struct ref_store *ref_store,
*/
if (refs_for_each_rawref(&refs->base, ref_present,
&affected_refnames))
- die("BUG: initial ref transaction called with existing refs");
+ BUG("initial ref transaction called with existing refs");
packed_transaction = ref_store_transaction_begin(refs->packed_ref_store, err);
if (!packed_transaction) {
@@ -2906,7 +2908,7 @@ static int files_initial_transaction_commit(struct ref_store *ref_store,
if ((update->flags & REF_HAVE_OLD) &&
!is_null_oid(&update->old_oid))
- die("BUG: initial ref transaction with old_sha1 set");
+ BUG("initial ref transaction with old_sha1 set");
if (refs_verify_refname_available(&refs->base, update->refname,
&affected_refnames, NULL,
err)) {
@@ -2989,7 +2991,7 @@ static int files_reflog_expire(struct ref_store *ref_store,
{
struct files_ref_store *refs =
files_downcast(ref_store, REF_STORE_WRITE, "reflog_expire");
- static struct lock_file reflog_lock;
+ struct lock_file reflog_lock = LOCK_INIT;
struct expire_reflog_cb cb;
struct ref_lock *lock;
struct strbuf log_file_sb = STRBUF_INIT;
diff --git a/refs/iterator.c b/refs/iterator.c
index bd35da4..2ac91ac 100644
--- a/refs/iterator.c
+++ b/refs/iterator.c
@@ -54,7 +54,7 @@ static int empty_ref_iterator_advance(struct ref_iterator *ref_iterator)
static int empty_ref_iterator_peel(struct ref_iterator *ref_iterator,
struct object_id *peeled)
{
- die("BUG: peel called for empty iterator");
+ BUG("peel called for empty iterator");
}
static int empty_ref_iterator_abort(struct ref_iterator *ref_iterator)
@@ -177,7 +177,7 @@ static int merge_ref_iterator_peel(struct ref_iterator *ref_iterator,
(struct merge_ref_iterator *)ref_iterator;
if (!iter->current) {
- die("BUG: peel called before advance for merge iterator");
+ BUG("peel called before advance for merge iterator");
}
return ref_iterator_peel(*iter->current, peeled);
}
@@ -338,7 +338,7 @@ static int prefix_ref_iterator_advance(struct ref_iterator *ref_iterator)
* trimming, report it as a bug:
*/
if (strlen(iter->iter0->refname) <= iter->trim)
- die("BUG: attempt to trim too many characters");
+ BUG("attempt to trim too many characters");
iter->base.refname = iter->iter0->refname + iter->trim;
} else {
iter->base.refname = iter->iter0->refname;
diff --git a/refs/packed-backend.c b/refs/packed-backend.c
index 65288c6..cec3fb9 100644
--- a/refs/packed-backend.c
+++ b/refs/packed-backend.c
@@ -5,6 +5,7 @@
#include "packed-backend.h"
#include "../iterator.h"
#include "../lockfile.h"
+#include "../chdir-notify.h"
enum mmap_strategy {
/*
@@ -202,6 +203,8 @@ struct ref_store *packed_ref_store_create(const char *path,
refs->store_flags = store_flags;
refs->path = xstrdup(path);
+ chdir_notify_reparent("packed-refs", &refs->path);
+
return ref_store;
}
@@ -218,13 +221,13 @@ static struct packed_ref_store *packed_downcast(struct ref_store *ref_store,
struct packed_ref_store *refs;
if (ref_store->be != &refs_be_packed)
- die("BUG: ref_store is type \"%s\" not \"packed\" in %s",
+ BUG("ref_store is type \"%s\" not \"packed\" in %s",
ref_store->be->name, caller);
refs = (struct packed_ref_store *)ref_store;
if ((refs->store_flags & required_flags) != required_flags)
- die("BUG: unallowed operation (%s), requires %x, has %x\n",
+ BUG("unallowed operation (%s), requires %x, has %x\n",
caller, required_flags, refs->store_flags);
return refs;
@@ -1033,7 +1036,7 @@ void packed_refs_unlock(struct ref_store *ref_store)
"packed_refs_unlock");
if (!is_lock_file_locked(&refs->lock))
- die("BUG: packed_refs_unlock() called when not locked");
+ BUG("packed_refs_unlock() called when not locked");
rollback_lock_file(&refs->lock);
}
@@ -1086,7 +1089,7 @@ static int write_with_updates(struct packed_ref_store *refs,
char *packed_refs_path;
if (!is_lock_file_locked(&refs->lock))
- die("BUG: write_with_updates() called while unlocked");
+ BUG("write_with_updates() called while unlocked");
/*
* If packed-refs is a symlink, we want to overwrite the
@@ -1560,21 +1563,21 @@ static int packed_create_symref(struct ref_store *ref_store,
const char *refname, const char *target,
const char *logmsg)
{
- die("BUG: packed reference store does not support symrefs");
+ BUG("packed reference store does not support symrefs");
}
static int packed_rename_ref(struct ref_store *ref_store,
const char *oldrefname, const char *newrefname,
const char *logmsg)
{
- die("BUG: packed reference store does not support renaming references");
+ BUG("packed reference store does not support renaming references");
}
static int packed_copy_ref(struct ref_store *ref_store,
const char *oldrefname, const char *newrefname,
const char *logmsg)
{
- die("BUG: packed reference store does not support copying references");
+ BUG("packed reference store does not support copying references");
}
static struct ref_iterator *packed_reflog_iterator_begin(struct ref_store *ref_store)
@@ -1607,7 +1610,7 @@ static int packed_create_reflog(struct ref_store *ref_store,
const char *refname, int force_create,
struct strbuf *err)
{
- die("BUG: packed reference store does not support reflogs");
+ BUG("packed reference store does not support reflogs");
}
static int packed_delete_reflog(struct ref_store *ref_store,
diff --git a/refs/ref-cache.c b/refs/ref-cache.c
index e90bd3e..9b110c8 100644
--- a/refs/ref-cache.c
+++ b/refs/ref-cache.c
@@ -23,7 +23,7 @@ struct ref_dir *get_ref_dir(struct ref_entry *entry)
dir = &entry->u.subdir;
if (entry->flag & REF_INCOMPLETE) {
if (!dir->cache->fill_ref_dir)
- die("BUG: incomplete ref_store without fill_ref_dir function");
+ BUG("incomplete ref_store without fill_ref_dir function");
dir->cache->fill_ref_dir(dir->cache->ref_store, dir, entry->name);
entry->flag &= ~REF_INCOMPLETE;
diff --git a/refspec.c b/refspec.c
new file mode 100644
index 0000000..c59a4cc
--- /dev/null
+++ b/refspec.c
@@ -0,0 +1,223 @@
+#include "cache.h"
+#include "argv-array.h"
+#include "refs.h"
+#include "refspec.h"
+
+static struct refspec_item s_tag_refspec = {
+ 0,
+ 1,
+ 0,
+ 0,
+ "refs/tags/*",
+ "refs/tags/*"
+};
+
+/* See TAG_REFSPEC for the string version */
+const struct refspec_item *tag_refspec = &s_tag_refspec;
+
+/*
+ * Parses the provided refspec 'refspec' and populates the refspec_item 'item'.
+ * Returns 1 if successful and 0 if the refspec is invalid.
+ */
+static int parse_refspec(struct refspec_item *item, const char *refspec, int fetch)
+{
+ size_t llen;
+ int is_glob;
+ const char *lhs, *rhs;
+ int flags;
+
+ is_glob = 0;
+
+ lhs = refspec;
+ if (*lhs == '+') {
+ item->force = 1;
+ lhs++;
+ }
+
+ rhs = strrchr(lhs, ':');
+
+ /*
+ * Before going on, special case ":" (or "+:") as a refspec
+ * for pushing matching refs.
+ */
+ if (!fetch && rhs == lhs && rhs[1] == '\0') {
+ item->matching = 1;
+ return 1;
+ }
+
+ if (rhs) {
+ size_t rlen = strlen(++rhs);
+ is_glob = (1 <= rlen && strchr(rhs, '*'));
+ item->dst = xstrndup(rhs, rlen);
+ }
+
+ llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
+ if (1 <= llen && memchr(lhs, '*', llen)) {
+ if ((rhs && !is_glob) || (!rhs && fetch))
+ return 0;
+ is_glob = 1;
+ } else if (rhs && is_glob) {
+ return 0;
+ }
+
+ item->pattern = is_glob;
+ item->src = xstrndup(lhs, llen);
+ flags = REFNAME_ALLOW_ONELEVEL | (is_glob ? REFNAME_REFSPEC_PATTERN : 0);
+
+ if (fetch) {
+ struct object_id unused;
+
+ /* LHS */
+ if (!*item->src)
+ ; /* empty is ok; it means "HEAD" */
+ else if (llen == GIT_SHA1_HEXSZ && !get_oid_hex(item->src, &unused))
+ item->exact_sha1 = 1; /* ok */
+ else if (!check_refname_format(item->src, flags))
+ ; /* valid looking ref is ok */
+ else
+ return 0;
+ /* RHS */
+ if (!item->dst)
+ ; /* missing is ok; it is the same as empty */
+ else if (!*item->dst)
+ ; /* empty is ok; it means "do not store" */
+ else if (!check_refname_format(item->dst, flags))
+ ; /* valid looking ref is ok */
+ else
+ return 0;
+ } else {
+ /*
+ * LHS
+ * - empty is allowed; it means delete.
+ * - when wildcarded, it must be a valid looking ref.
+ * - otherwise, it must be an extended SHA-1, but
+ * there is no existing way to validate this.
+ */
+ if (!*item->src)
+ ; /* empty is ok */
+ else if (is_glob) {
+ if (check_refname_format(item->src, flags))
+ return 0;
+ }
+ else
+ ; /* anything goes, for now */
+ /*
+ * RHS
+ * - missing is allowed, but LHS then must be a
+ * valid looking ref.
+ * - empty is not allowed.
+ * - otherwise it must be a valid looking ref.
+ */
+ if (!item->dst) {
+ if (check_refname_format(item->src, flags))
+ return 0;
+ } else if (!*item->dst) {
+ return 0;
+ } else {
+ if (check_refname_format(item->dst, flags))
+ return 0;
+ }
+ }
+
+ return 1;
+}
+
+void refspec_item_init(struct refspec_item *item, const char *refspec, int fetch)
+{
+ memset(item, 0, sizeof(*item));
+
+ if (!parse_refspec(item, refspec, fetch))
+ die("Invalid refspec '%s'", refspec);
+}
+
+void refspec_item_clear(struct refspec_item *item)
+{
+ FREE_AND_NULL(item->src);
+ FREE_AND_NULL(item->dst);
+ item->force = 0;
+ item->pattern = 0;
+ item->matching = 0;
+ item->exact_sha1 = 0;
+}
+
+void refspec_init(struct refspec *rs, int fetch)
+{
+ memset(rs, 0, sizeof(*rs));
+ rs->fetch = fetch;
+}
+
+void refspec_append(struct refspec *rs, const char *refspec)
+{
+ struct refspec_item item;
+
+ refspec_item_init(&item, refspec, rs->fetch);
+
+ ALLOC_GROW(rs->items, rs->nr + 1, rs->alloc);
+ rs->items[rs->nr++] = item;
+
+ ALLOC_GROW(rs->raw, rs->raw_nr + 1, rs->raw_alloc);
+ rs->raw[rs->raw_nr++] = xstrdup(refspec);
+}
+
+void refspec_appendn(struct refspec *rs, const char **refspecs, int nr)
+{
+ int i;
+ for (i = 0; i < nr; i++)
+ refspec_append(rs, refspecs[i]);
+}
+
+void refspec_clear(struct refspec *rs)
+{
+ int i;
+
+ for (i = 0; i < rs->nr; i++)
+ refspec_item_clear(&rs->items[i]);
+
+ FREE_AND_NULL(rs->items);
+ rs->alloc = 0;
+ rs->nr = 0;
+
+ for (i = 0; i < rs->raw_nr; i++)
+ free((char *)rs->raw[i]);
+ FREE_AND_NULL(rs->raw);
+ rs->raw_alloc = 0;
+ rs->raw_nr = 0;
+
+ rs->fetch = 0;
+}
+
+int valid_fetch_refspec(const char *fetch_refspec_str)
+{
+ struct refspec_item refspec;
+ int ret = parse_refspec(&refspec, fetch_refspec_str, REFSPEC_FETCH);
+ refspec_item_clear(&refspec);
+ return ret;
+}
+
+void refspec_ref_prefixes(const struct refspec *rs,
+ struct argv_array *ref_prefixes)
+{
+ int i;
+ for (i = 0; i < rs->nr; i++) {
+ const struct refspec_item *item = &rs->items[i];
+ const char *prefix = NULL;
+
+ if (rs->fetch == REFSPEC_FETCH)
+ prefix = item->src;
+ else if (item->dst)
+ prefix = item->dst;
+ else if (item->src && !item->exact_sha1)
+ prefix = item->src;
+
+ if (prefix) {
+ if (item->pattern) {
+ const char *glob = strchr(prefix, '*');
+ argv_array_pushf(ref_prefixes, "%.*s",
+ (int)(glob - prefix),
+ prefix);
+ } else {
+ expand_ref_prefix(ref_prefixes, prefix);
+ }
+ }
+ }
+}
diff --git a/refspec.h b/refspec.h
new file mode 100644
index 0000000..01b700e
--- /dev/null
+++ b/refspec.h
@@ -0,0 +1,48 @@
+#ifndef REFSPEC_H
+#define REFSPEC_H
+
+#define TAG_REFSPEC "refs/tags/*:refs/tags/*"
+extern const struct refspec_item *tag_refspec;
+
+struct refspec_item {
+ unsigned force : 1;
+ unsigned pattern : 1;
+ unsigned matching : 1;
+ unsigned exact_sha1 : 1;
+
+ char *src;
+ char *dst;
+};
+
+#define REFSPEC_FETCH 1
+#define REFSPEC_PUSH 0
+
+#define REFSPEC_INIT_FETCH { .fetch = REFSPEC_FETCH }
+#define REFSPEC_INIT_PUSH { .fetch = REFSPEC_PUSH }
+
+struct refspec {
+ struct refspec_item *items;
+ int alloc;
+ int nr;
+
+ const char **raw;
+ int raw_alloc;
+ int raw_nr;
+
+ int fetch;
+};
+
+void refspec_item_init(struct refspec_item *item, const char *refspec, int fetch);
+void refspec_item_clear(struct refspec_item *item);
+void refspec_init(struct refspec *rs, int fetch);
+void refspec_append(struct refspec *rs, const char *refspec);
+void refspec_appendn(struct refspec *rs, const char **refspecs, int nr);
+void refspec_clear(struct refspec *rs);
+
+int valid_fetch_refspec(const char *refspec);
+
+struct argv_array;
+void refspec_ref_prefixes(const struct refspec *rs,
+ struct argv_array *ref_prefixes);
+
+#endif /* REFSPEC_H */
diff --git a/remote-curl.c b/remote-curl.c
index a7c4c9b..ceb0534 100644
--- a/remote-curl.c
+++ b/remote-curl.c
@@ -1,10 +1,11 @@
#include "cache.h"
#include "config.h"
#include "remote.h"
+#include "connect.h"
#include "strbuf.h"
#include "walker.h"
#include "http.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "run-command.h"
#include "pkt-line.h"
#include "string-list.h"
@@ -13,6 +14,7 @@
#include "credential.h"
#include "sha1-array.h"
#include "send-pack.h"
+#include "protocol.h"
#include "quote.h"
static struct remote *remote;
@@ -184,12 +186,13 @@ static int set_option(const char *name, const char *value)
}
struct discovery {
- const char *service;
+ char *service;
char *buf_alloc;
char *buf;
size_t len;
struct ref *refs;
struct oid_array shallow;
+ enum protocol_version version;
unsigned proto_git : 1;
};
static struct discovery *last_discovery;
@@ -197,8 +200,31 @@ static struct discovery *last_discovery;
static struct ref *parse_git_refs(struct discovery *heads, int for_push)
{
struct ref *list = NULL;
- get_remote_heads(-1, heads->buf, heads->len, &list,
- for_push ? REF_NORMAL : 0, NULL, &heads->shallow);
+ struct packet_reader reader;
+
+ packet_reader_init(&reader, -1, heads->buf, heads->len,
+ PACKET_READ_CHOMP_NEWLINE |
+ PACKET_READ_GENTLE_ON_EOF);
+
+ heads->version = discover_version(&reader);
+ switch (heads->version) {
+ case protocol_v2:
+ /*
+ * Do nothing. This isn't a list of refs but rather a
+ * capability advertisement. Client would have run
+ * 'stateless-connect' so we'll dump this capability listing
+ * and let them request the refs themselves.
+ */
+ break;
+ case protocol_v1:
+ case protocol_v0:
+ get_remote_heads(&reader, &list, for_push ? REF_NORMAL : 0,
+ NULL, &heads->shallow);
+ break;
+ case protocol_unknown_version:
+ BUG("unknown protocol version");
+ }
+
return list;
}
@@ -259,6 +285,7 @@ static void free_discovery(struct discovery *d)
free(d->shallow.oid);
free(d->buf_alloc);
free_refs(d->refs);
+ free(d->service);
free(d);
}
}
@@ -290,6 +317,19 @@ static int show_http_message(struct strbuf *type, struct strbuf *charset,
return 0;
}
+static int get_protocol_http_header(enum protocol_version version,
+ struct strbuf *header)
+{
+ if (version > 0) {
+ strbuf_addf(header, GIT_PROTOCOL_HEADER ": version=%d",
+ version);
+
+ return 1;
+ }
+
+ return 0;
+}
+
static struct discovery *discover_refs(const char *service, int for_push)
{
struct strbuf exp = STRBUF_INIT;
@@ -298,9 +338,12 @@ static struct discovery *discover_refs(const char *service, int for_push)
struct strbuf buffer = STRBUF_INIT;
struct strbuf refs_url = STRBUF_INIT;
struct strbuf effective_url = STRBUF_INIT;
+ struct strbuf protocol_header = STRBUF_INIT;
+ struct string_list extra_headers = STRING_LIST_INIT_DUP;
struct discovery *last = last_discovery;
int http_ret, maybe_smart = 0;
struct http_get_options http_options;
+ enum protocol_version version = get_protocol_version_config();
if (last && !strcmp(service, last->service))
return last;
@@ -317,11 +360,24 @@ static struct discovery *discover_refs(const char *service, int for_push)
strbuf_addf(&refs_url, "service=%s", service);
}
+ /*
+ * NEEDSWORK: If we are trying to use protocol v2 and we are planning
+ * to perform a push, then fallback to v0 since the client doesn't know
+ * how to push yet using v2.
+ */
+ if (version == protocol_v2 && !strcmp("git-receive-pack", service))
+ version = protocol_v0;
+
+ /* Add the extra Git-Protocol header */
+ if (get_protocol_http_header(version, &protocol_header))
+ string_list_append(&extra_headers, protocol_header.buf);
+
memset(&http_options, 0, sizeof(http_options));
http_options.content_type = &type;
http_options.charset = &charset;
http_options.effective_url = &effective_url;
http_options.base_url = &url;
+ http_options.extra_headers = &extra_headers;
http_options.initial_request = 1;
http_options.no_cache = 1;
http_options.keep_error = 1;
@@ -345,7 +401,7 @@ static struct discovery *discover_refs(const char *service, int for_push)
warning(_("redirecting to %s"), url.buf);
last= xcalloc(1, sizeof(*last_discovery));
- last->service = service;
+ last->service = xstrdup(service);
last->buf_alloc = strbuf_detach(&buffer, &last->len);
last->buf = last->buf_alloc;
@@ -377,6 +433,9 @@ static struct discovery *discover_refs(const char *service, int for_push)
;
last->proto_git = 1;
+ } else if (maybe_smart &&
+ last->len > 5 && starts_with(last->buf + 4, "version 2")) {
+ last->proto_git = 1;
}
if (last->proto_git)
@@ -390,6 +449,8 @@ static struct discovery *discover_refs(const char *service, int for_push)
strbuf_release(&charset);
strbuf_release(&effective_url);
strbuf_release(&buffer);
+ strbuf_release(&protocol_header);
+ string_list_clear(&extra_headers, 0);
last_discovery = last;
return last;
}
@@ -426,6 +487,7 @@ struct rpc_state {
char *service_url;
char *hdr_content_type;
char *hdr_accept;
+ char *protocol_header;
char *buf;
size_t alloc;
size_t len;
@@ -612,6 +674,10 @@ static int post_rpc(struct rpc_state *rpc)
headers = curl_slist_append(headers, needs_100_continue ?
"Expect: 100-continue" : "Expect:");
+ /* Add the extra Git-Protocol header */
+ if (rpc->protocol_header)
+ headers = curl_slist_append(headers, rpc->protocol_header);
+
retry:
slot = get_active_slot();
@@ -752,6 +818,11 @@ static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
strbuf_addf(&buf, "Accept: application/x-%s-result", svc);
rpc->hdr_accept = strbuf_detach(&buf, NULL);
+ if (get_protocol_http_header(heads->version, &buf))
+ rpc->protocol_header = strbuf_detach(&buf, NULL);
+ else
+ rpc->protocol_header = NULL;
+
while (!err) {
int n = packet_read(rpc->out, NULL, NULL, rpc->buf, rpc->alloc, 0);
if (!n)
@@ -779,6 +850,7 @@ static int rpc_service(struct rpc_state *rpc, struct discovery *heads)
free(rpc->service_url);
free(rpc->hdr_content_type);
free(rpc->hdr_accept);
+ free(rpc->protocol_header);
free(rpc->buf);
strbuf_release(&buf);
return err;
@@ -797,9 +869,6 @@ static int fetch_dumb(int nr_heads, struct ref **to_fetch)
targets[i] = xstrdup(oid_to_hex(&to_fetch[i]->old_oid));
walker = get_http_walker(url.buf);
- walker->get_all = 1;
- walker->get_tree = 1;
- walker->get_history = 1;
walker->get_verbosely = options.verbosity >= 3;
walker->get_recover = 0;
ret = walker_fetch(walker, nr_heads, targets, NULL, NULL);
@@ -1056,6 +1125,202 @@ static void parse_push(struct strbuf *buf)
free(specs);
}
+/*
+ * Used to represent the state of a connection to an HTTP server when
+ * communicating using git's wire-protocol version 2.
+ */
+struct proxy_state {
+ char *service_name;
+ char *service_url;
+ struct curl_slist *headers;
+ struct strbuf request_buffer;
+ int in;
+ int out;
+ struct packet_reader reader;
+ size_t pos;
+ int seen_flush;
+};
+
+static void proxy_state_init(struct proxy_state *p, const char *service_name,
+ enum protocol_version version)
+{
+ struct strbuf buf = STRBUF_INIT;
+
+ memset(p, 0, sizeof(*p));
+ p->service_name = xstrdup(service_name);
+
+ p->in = 0;
+ p->out = 1;
+ strbuf_init(&p->request_buffer, 0);
+
+ strbuf_addf(&buf, "%s%s", url.buf, p->service_name);
+ p->service_url = strbuf_detach(&buf, NULL);
+
+ p->headers = http_copy_default_headers();
+
+ strbuf_addf(&buf, "Content-Type: application/x-%s-request", p->service_name);
+ p->headers = curl_slist_append(p->headers, buf.buf);
+ strbuf_reset(&buf);
+
+ strbuf_addf(&buf, "Accept: application/x-%s-result", p->service_name);
+ p->headers = curl_slist_append(p->headers, buf.buf);
+ strbuf_reset(&buf);
+
+ p->headers = curl_slist_append(p->headers, "Transfer-Encoding: chunked");
+
+ /* Add the Git-Protocol header */
+ if (get_protocol_http_header(version, &buf))
+ p->headers = curl_slist_append(p->headers, buf.buf);
+
+ packet_reader_init(&p->reader, p->in, NULL, 0,
+ PACKET_READ_GENTLE_ON_EOF);
+
+ strbuf_release(&buf);
+}
+
+static void proxy_state_clear(struct proxy_state *p)
+{
+ free(p->service_name);
+ free(p->service_url);
+ curl_slist_free_all(p->headers);
+ strbuf_release(&p->request_buffer);
+}
+
+/*
+ * CURLOPT_READFUNCTION callback function.
+ * Attempts to copy over a single packet-line at a time into the
+ * curl provided buffer.
+ */
+static size_t proxy_in(char *buffer, size_t eltsize,
+ size_t nmemb, void *userdata)
+{
+ size_t max;
+ struct proxy_state *p = userdata;
+ size_t avail = p->request_buffer.len - p->pos;
+
+
+ if (eltsize != 1)
+ BUG("curl read callback called with size = %"PRIuMAX" != 1",
+ (uintmax_t)eltsize);
+ max = nmemb;
+
+ if (!avail) {
+ if (p->seen_flush) {
+ p->seen_flush = 0;
+ return 0;
+ }
+
+ strbuf_reset(&p->request_buffer);
+ switch (packet_reader_read(&p->reader)) {
+ case PACKET_READ_EOF:
+ die("unexpected EOF when reading from parent process");
+ case PACKET_READ_NORMAL:
+ packet_buf_write_len(&p->request_buffer, p->reader.line,
+ p->reader.pktlen);
+ break;
+ case PACKET_READ_DELIM:
+ packet_buf_delim(&p->request_buffer);
+ break;
+ case PACKET_READ_FLUSH:
+ packet_buf_flush(&p->request_buffer);
+ p->seen_flush = 1;
+ break;
+ }
+ p->pos = 0;
+ avail = p->request_buffer.len;
+ }
+
+ if (max < avail)
+ avail = max;
+ memcpy(buffer, p->request_buffer.buf + p->pos, avail);
+ p->pos += avail;
+ return avail;
+}
+
+static size_t proxy_out(char *buffer, size_t eltsize,
+ size_t nmemb, void *userdata)
+{
+ size_t size;
+ struct proxy_state *p = userdata;
+
+ if (eltsize != 1)
+ BUG("curl read callback called with size = %"PRIuMAX" != 1",
+ (uintmax_t)eltsize);
+ size = nmemb;
+
+ write_or_die(p->out, buffer, size);
+ return size;
+}
+
+/* Issues a request to the HTTP server configured in `p` */
+static int proxy_request(struct proxy_state *p)
+{
+ struct active_request_slot *slot;
+
+ slot = get_active_slot();
+
+ curl_easy_setopt(slot->curl, CURLOPT_NOBODY, 0);
+ curl_easy_setopt(slot->curl, CURLOPT_POST, 1);
+ curl_easy_setopt(slot->curl, CURLOPT_URL, p->service_url);
+ curl_easy_setopt(slot->curl, CURLOPT_HTTPHEADER, p->headers);
+
+ /* Setup function to read request from client */
+ curl_easy_setopt(slot->curl, CURLOPT_READFUNCTION, proxy_in);
+ curl_easy_setopt(slot->curl, CURLOPT_READDATA, p);
+
+ /* Setup function to write server response to client */
+ curl_easy_setopt(slot->curl, CURLOPT_WRITEFUNCTION, proxy_out);
+ curl_easy_setopt(slot->curl, CURLOPT_WRITEDATA, p);
+
+ if (run_slot(slot, NULL) != HTTP_OK)
+ return -1;
+
+ return 0;
+}
+
+static int stateless_connect(const char *service_name)
+{
+ struct discovery *discover;
+ struct proxy_state p;
+
+ /*
+ * Run the info/refs request and see if the server supports protocol
+ * v2. If and only if the server supports v2 can we successfully
+ * establish a stateless connection, otherwise we need to tell the
+ * client to fallback to using other transport helper functions to
+ * complete their request.
+ */
+ discover = discover_refs(service_name, 0);
+ if (discover->version != protocol_v2) {
+ printf("fallback\n");
+ fflush(stdout);
+ return -1;
+ } else {
+ /* Stateless Connection established */
+ printf("\n");
+ fflush(stdout);
+ }
+
+ proxy_state_init(&p, service_name, discover->version);
+
+ /*
+ * Dump the capability listing that we got from the server earlier
+ * during the info/refs request.
+ */
+ write_or_die(p.out, discover->buf, discover->len);
+
+ /* Peek the next packet line. Until we see EOF keep sending POSTs */
+ while (packet_reader_peek(&p.reader) != PACKET_READ_EOF) {
+ if (proxy_request(&p)) {
+ /* We would have an err here */
+ break;
+ }
+ }
+
+ proxy_state_clear(&p);
+ return 0;
+}
+
int cmd_main(int argc, const char **argv)
{
struct strbuf buf = STRBUF_INIT;
@@ -1124,12 +1389,16 @@ int cmd_main(int argc, const char **argv)
fflush(stdout);
} else if (!strcmp(buf.buf, "capabilities")) {
+ printf("stateless-connect\n");
printf("fetch\n");
printf("option\n");
printf("push\n");
printf("check-connectivity\n");
printf("\n");
fflush(stdout);
+ } else if (skip_prefix(buf.buf, "stateless-connect ", &arg)) {
+ if (!stateless_connect(arg))
+ break;
} else {
error("remote-curl: unknown command '%s' from git", buf.buf);
return 1;
diff --git a/remote-testsvn.c b/remote-testsvn.c
index c4bb9a8..444d980 100644
--- a/remote-testsvn.c
+++ b/remote-testsvn.c
@@ -3,7 +3,7 @@
#include "remote.h"
#include "strbuf.h"
#include "url.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "run-command.h"
#include "vcs-svn/svndump.h"
#include "notes.h"
diff --git a/remote.c b/remote.c
index 91eb010..abe80c1 100644
--- a/remote.c
+++ b/remote.c
@@ -2,6 +2,7 @@
#include "config.h"
#include "remote.h"
#include "refs.h"
+#include "refspec.h"
#include "commit.h"
#include "diff.h"
#include "revision.h"
@@ -13,18 +14,6 @@
enum map_direction { FROM_SRC, FROM_DST };
-static struct refspec s_tag_refspec = {
- 0,
- 1,
- 0,
- 0,
- "refs/tags/*",
- "refs/tags/*"
-};
-
-/* See TAG_REFSPEC for the string version */
-const struct refspec *tag_refspec = &s_tag_refspec;
-
struct counted_string {
size_t len;
const char *s;
@@ -88,33 +77,6 @@ static const char *alias_url(const char *url, struct rewrites *r)
return xstrfmt("%s%s", r->rewrite[longest_i]->base, url + longest->len);
}
-static void add_push_refspec(struct remote *remote, const char *ref)
-{
- ALLOC_GROW(remote->push_refspec,
- remote->push_refspec_nr + 1,
- remote->push_refspec_alloc);
- remote->push_refspec[remote->push_refspec_nr++] = ref;
-}
-
-static void add_fetch_refspec(struct remote *remote, const char *ref)
-{
- ALLOC_GROW(remote->fetch_refspec,
- remote->fetch_refspec_nr + 1,
- remote->fetch_refspec_alloc);
- remote->fetch_refspec[remote->fetch_refspec_nr++] = ref;
-}
-
-void add_prune_tags_to_fetch_refspec(struct remote *remote)
-{
- int nr = remote->fetch_refspec_nr;
- int bufsize = nr + 1;
- int size = sizeof(struct refspec);
-
- remote->fetch = xrealloc(remote->fetch, size * bufsize);
- memcpy(&remote->fetch[nr], tag_refspec, size);
- add_fetch_refspec(remote, xstrdup(TAG_REFSPEC));
-}
-
static void add_url(struct remote *remote, const char *url)
{
ALLOC_GROW(remote->url, remote->url_nr + 1, remote->url_alloc);
@@ -186,9 +148,12 @@ static struct remote *make_remote(const char *name, int len)
ret = xcalloc(1, sizeof(struct remote));
ret->prune = -1; /* unspecified */
ret->prune_tags = -1; /* unspecified */
+ ret->name = xstrndup(name, len);
+ refspec_init(&ret->push, REFSPEC_PUSH);
+ refspec_init(&ret->fetch, REFSPEC_FETCH);
+
ALLOC_GROW(remotes, remotes_nr + 1, remotes_alloc);
remotes[remotes_nr++] = ret;
- ret->name = xstrndup(name, len);
hashmap_entry_init(ret, lookup_entry.hash);
replaced = hashmap_put(&remotes_hash, ret);
@@ -286,9 +251,9 @@ static void read_remotes_file(struct remote *remote)
if (skip_prefix(buf.buf, "URL:", &v))
add_url_alias(remote, xstrdup(skip_spaces(v)));
else if (skip_prefix(buf.buf, "Push:", &v))
- add_push_refspec(remote, xstrdup(skip_spaces(v)));
+ refspec_append(&remote->push, skip_spaces(v));
else if (skip_prefix(buf.buf, "Pull:", &v))
- add_fetch_refspec(remote, xstrdup(skip_spaces(v)));
+ refspec_append(&remote->fetch, skip_spaces(v));
}
strbuf_release(&buf);
fclose(f);
@@ -327,15 +292,19 @@ static void read_branches_file(struct remote *remote)
frag = "master";
add_url_alias(remote, strbuf_detach(&buf, NULL));
- add_fetch_refspec(remote, xstrfmt("refs/heads/%s:refs/heads/%s",
- frag, remote->name));
+ strbuf_addf(&buf, "refs/heads/%s:refs/heads/%s",
+ frag, remote->name);
+ refspec_append(&remote->fetch, buf.buf);
/*
* Cogito compatible push: push current HEAD to remote #branch
* (master if missing)
*/
- add_push_refspec(remote, xstrfmt("HEAD:refs/heads/%s", frag));
+ strbuf_reset(&buf);
+ strbuf_addf(&buf, "HEAD:refs/heads/%s", frag);
+ refspec_append(&remote->push, buf.buf);
remote->fetch_tags = 1; /* always auto-follow */
+ strbuf_release(&buf);
}
static int handle_config(const char *key, const char *value, void *cb)
@@ -420,12 +389,14 @@ static int handle_config(const char *key, const char *value, void *cb)
const char *v;
if (git_config_string(&v, key, value))
return -1;
- add_push_refspec(remote, v);
+ refspec_append(&remote->push, v);
+ free((char *)v);
} else if (!strcmp(subkey, "fetch")) {
const char *v;
if (git_config_string(&v, key, value))
return -1;
- add_fetch_refspec(remote, v);
+ refspec_append(&remote->fetch, v);
+ free((char *)v);
} else if (!strcmp(subkey, "receivepack")) {
const char *v;
if (git_config_string(&v, key, value))
@@ -499,158 +470,6 @@ static void read_config(void)
alias_all_urls();
}
-static struct refspec *parse_refspec_internal(int nr_refspec, const char **refspec, int fetch, int verify)
-{
- int i;
- struct refspec *rs = xcalloc(nr_refspec, sizeof(*rs));
-
- for (i = 0; i < nr_refspec; i++) {
- size_t llen;
- int is_glob;
- const char *lhs, *rhs;
- int flags;
-
- is_glob = 0;
-
- lhs = refspec[i];
- if (*lhs == '+') {
- rs[i].force = 1;
- lhs++;
- }
-
- rhs = strrchr(lhs, ':');
-
- /*
- * Before going on, special case ":" (or "+:") as a refspec
- * for pushing matching refs.
- */
- if (!fetch && rhs == lhs && rhs[1] == '\0') {
- rs[i].matching = 1;
- continue;
- }
-
- if (rhs) {
- size_t rlen = strlen(++rhs);
- is_glob = (1 <= rlen && strchr(rhs, '*'));
- rs[i].dst = xstrndup(rhs, rlen);
- }
-
- llen = (rhs ? (rhs - lhs - 1) : strlen(lhs));
- if (1 <= llen && memchr(lhs, '*', llen)) {
- if ((rhs && !is_glob) || (!rhs && fetch))
- goto invalid;
- is_glob = 1;
- } else if (rhs && is_glob) {
- goto invalid;
- }
-
- rs[i].pattern = is_glob;
- rs[i].src = xstrndup(lhs, llen);
- flags = REFNAME_ALLOW_ONELEVEL | (is_glob ? REFNAME_REFSPEC_PATTERN : 0);
-
- if (fetch) {
- struct object_id unused;
-
- /* LHS */
- if (!*rs[i].src)
- ; /* empty is ok; it means "HEAD" */
- else if (llen == GIT_SHA1_HEXSZ && !get_oid_hex(rs[i].src, &unused))
- rs[i].exact_sha1 = 1; /* ok */
- else if (!check_refname_format(rs[i].src, flags))
- ; /* valid looking ref is ok */
- else
- goto invalid;
- /* RHS */
- if (!rs[i].dst)
- ; /* missing is ok; it is the same as empty */
- else if (!*rs[i].dst)
- ; /* empty is ok; it means "do not store" */
- else if (!check_refname_format(rs[i].dst, flags))
- ; /* valid looking ref is ok */
- else
- goto invalid;
- } else {
- /*
- * LHS
- * - empty is allowed; it means delete.
- * - when wildcarded, it must be a valid looking ref.
- * - otherwise, it must be an extended SHA-1, but
- * there is no existing way to validate this.
- */
- if (!*rs[i].src)
- ; /* empty is ok */
- else if (is_glob) {
- if (check_refname_format(rs[i].src, flags))
- goto invalid;
- }
- else
- ; /* anything goes, for now */
- /*
- * RHS
- * - missing is allowed, but LHS then must be a
- * valid looking ref.
- * - empty is not allowed.
- * - otherwise it must be a valid looking ref.
- */
- if (!rs[i].dst) {
- if (check_refname_format(rs[i].src, flags))
- goto invalid;
- } else if (!*rs[i].dst) {
- goto invalid;
- } else {
- if (check_refname_format(rs[i].dst, flags))
- goto invalid;
- }
- }
- }
- return rs;
-
- invalid:
- if (verify) {
- /*
- * nr_refspec must be greater than zero and i must be valid
- * since it is only possible to reach this point from within
- * the for loop above.
- */
- free_refspec(i+1, rs);
- return NULL;
- }
- die("Invalid refspec '%s'", refspec[i]);
-}
-
-int valid_fetch_refspec(const char *fetch_refspec_str)
-{
- struct refspec *refspec;
-
- refspec = parse_refspec_internal(1, &fetch_refspec_str, 1, 1);
- free_refspec(1, refspec);
- return !!refspec;
-}
-
-struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec)
-{
- return parse_refspec_internal(nr_refspec, refspec, 1, 0);
-}
-
-struct refspec *parse_push_refspec(int nr_refspec, const char **refspec)
-{
- return parse_refspec_internal(nr_refspec, refspec, 0, 0);
-}
-
-void free_refspec(int nr_refspec, struct refspec *refspec)
-{
- int i;
-
- if (!refspec)
- return;
-
- for (i = 0; i < nr_refspec; i++) {
- free(refspec[i].src);
- free(refspec[i].dst);
- }
- free(refspec);
-}
-
static int valid_remote_nick(const char *name)
{
if (!name[0] || is_dot_or_dotdot(name))
@@ -705,9 +524,8 @@ const char *remote_ref_for_branch(struct branch *branch, int for_push,
pushremote_for_branch(branch, NULL);
struct remote *remote = remote_get(remote_name);
- if (remote && remote->push_refspec_nr &&
- (dst = apply_refspecs(remote->push,
- remote->push_refspec_nr,
+ if (remote && remote->push.nr &&
+ (dst = apply_refspecs(&remote->push,
branch->refname))) {
if (explicit)
*explicit = 1;
@@ -744,8 +562,6 @@ static struct remote *remote_get_1(const char *name,
add_url_alias(ret, name);
if (!valid_remote(ret))
return NULL;
- ret->fetch = parse_fetch_refspec(ret->fetch_refspec_nr, ret->fetch_refspec);
- ret->push = parse_push_refspec(ret->push_refspec_nr, ret->push_refspec);
return ret;
}
@@ -776,12 +592,6 @@ int for_each_remote(each_remote_fn fn, void *priv)
struct remote *r = remotes[i];
if (!r)
continue;
- if (!r->fetch)
- r->fetch = parse_fetch_refspec(r->fetch_refspec_nr,
- r->fetch_refspec);
- if (!r->push)
- r->push = parse_push_refspec(r->push_refspec_nr,
- r->push_refspec);
result = fn(r, priv);
}
return result;
@@ -887,7 +697,9 @@ static int match_name_with_pattern(const char *key, const char *name,
return ret;
}
-static void query_refspecs_multiple(struct refspec *refs, int ref_count, struct refspec *query, struct string_list *results)
+static void query_refspecs_multiple(struct refspec *rs,
+ struct refspec_item *query,
+ struct string_list *results)
{
int i;
int find_src = !query->src;
@@ -895,8 +707,8 @@ static void query_refspecs_multiple(struct refspec *refs, int ref_count, struct
if (find_src && !query->dst)
error("query_refspecs_multiple: need either src or dst");
- for (i = 0; i < ref_count; i++) {
- struct refspec *refspec = &refs[i];
+ for (i = 0; i < rs->nr; i++) {
+ struct refspec_item *refspec = &rs->items[i];
const char *key = find_src ? refspec->dst : refspec->src;
const char *value = find_src ? refspec->src : refspec->dst;
const char *needle = find_src ? query->dst : query->src;
@@ -913,7 +725,7 @@ static void query_refspecs_multiple(struct refspec *refs, int ref_count, struct
}
}
-int query_refspecs(struct refspec *refs, int ref_count, struct refspec *query)
+int query_refspecs(struct refspec *rs, struct refspec_item *query)
{
int i;
int find_src = !query->src;
@@ -923,8 +735,8 @@ int query_refspecs(struct refspec *refs, int ref_count, struct refspec *query)
if (find_src && !query->dst)
return error("query_refspecs: need either src or dst");
- for (i = 0; i < ref_count; i++) {
- struct refspec *refspec = &refs[i];
+ for (i = 0; i < rs->nr; i++) {
+ struct refspec_item *refspec = &rs->items[i];
const char *key = find_src ? refspec->dst : refspec->src;
const char *value = find_src ? refspec->src : refspec->dst;
@@ -944,23 +756,22 @@ int query_refspecs(struct refspec *refs, int ref_count, struct refspec *query)
return -1;
}
-char *apply_refspecs(struct refspec *refspecs, int nr_refspec,
- const char *name)
+char *apply_refspecs(struct refspec *rs, const char *name)
{
- struct refspec query;
+ struct refspec_item query;
- memset(&query, 0, sizeof(struct refspec));
+ memset(&query, 0, sizeof(struct refspec_item));
query.src = (char *)name;
- if (query_refspecs(refspecs, nr_refspec, &query))
+ if (query_refspecs(rs, &query))
return NULL;
return query.dst;
}
-int remote_find_tracking(struct remote *remote, struct refspec *refspec)
+int remote_find_tracking(struct remote *remote, struct refspec_item *refspec)
{
- return query_refspecs(remote->fetch, remote->fetch_refspec_nr, refspec);
+ return query_refspecs(&remote->fetch, refspec);
}
static struct ref *alloc_ref_with_prefix(const char *prefix, size_t prefixlen,
@@ -1167,7 +978,7 @@ static char *guess_ref(const char *name, struct ref *peer)
}
static int match_explicit_lhs(struct ref *src,
- struct refspec *rs,
+ struct refspec_item *rs,
struct ref **match,
int *allocated_match)
{
@@ -1193,7 +1004,7 @@ static int match_explicit_lhs(struct ref *src,
static int match_explicit(struct ref *src, struct ref *dst,
struct ref ***dst_tail,
- struct refspec *rs)
+ struct refspec_item *rs)
{
struct ref *matched_src, *matched_dst;
int allocated_src;
@@ -1262,36 +1073,37 @@ static int match_explicit(struct ref *src, struct ref *dst,
}
static int match_explicit_refs(struct ref *src, struct ref *dst,
- struct ref ***dst_tail, struct refspec *rs,
- int rs_nr)
+ struct ref ***dst_tail, struct refspec *rs)
{
int i, errs;
- for (i = errs = 0; i < rs_nr; i++)
- errs += match_explicit(src, dst, dst_tail, &rs[i]);
+ for (i = errs = 0; i < rs->nr; i++)
+ errs += match_explicit(src, dst, dst_tail, &rs->items[i]);
return errs;
}
-static char *get_ref_match(const struct refspec *rs, int rs_nr, const struct ref *ref,
- int send_mirror, int direction, const struct refspec **ret_pat)
+static char *get_ref_match(const struct refspec *rs, const struct ref *ref,
+ int send_mirror, int direction,
+ const struct refspec_item **ret_pat)
{
- const struct refspec *pat;
+ const struct refspec_item *pat;
char *name;
int i;
int matching_refs = -1;
- for (i = 0; i < rs_nr; i++) {
- if (rs[i].matching &&
- (matching_refs == -1 || rs[i].force)) {
+ for (i = 0; i < rs->nr; i++) {
+ const struct refspec_item *item = &rs->items[i];
+ if (item->matching &&
+ (matching_refs == -1 || item->force)) {
matching_refs = i;
continue;
}
- if (rs[i].pattern) {
- const char *dst_side = rs[i].dst ? rs[i].dst : rs[i].src;
+ if (item->pattern) {
+ const char *dst_side = item->dst ? item->dst : item->src;
int match;
if (direction == FROM_SRC)
- match = match_name_with_pattern(rs[i].src, ref->name, dst_side, &name);
+ match = match_name_with_pattern(item->src, ref->name, dst_side, &name);
else
- match = match_name_with_pattern(dst_side, ref->name, rs[i].src, &name);
+ match = match_name_with_pattern(dst_side, ref->name, item->src, &name);
if (match) {
matching_refs = i;
break;
@@ -1301,7 +1113,7 @@ static char *get_ref_match(const struct refspec *rs, int rs_nr, const struct ref
if (matching_refs == -1)
return NULL;
- pat = rs + matching_refs;
+ pat = &rs->items[matching_refs];
if (pat->matching) {
/*
* "matching refs"; traditionally we pushed everything
@@ -1376,7 +1188,7 @@ static void add_missing_tags(struct ref *src, struct ref **dst, struct ref ***ds
continue; /* not a tag */
if (string_list_has_string(&dst_tag, ref->name))
continue; /* they already have it */
- if (oid_object_info(&ref->new_oid, NULL) != OBJ_TAG)
+ if (oid_object_info(the_repository, &ref->new_oid, NULL) != OBJ_TAG)
continue; /* be conservative */
item = string_list_append(&src_tag, ref->name);
item->util = ref;
@@ -1443,22 +1255,20 @@ static void prepare_ref_index(struct string_list *ref_index, struct ref *ref)
* but we can catch some errors early before even talking to the
* remote side.
*/
-int check_push_refs(struct ref *src, int nr_refspec, const char **refspec_names)
+int check_push_refs(struct ref *src, struct refspec *rs)
{
- struct refspec *refspec = parse_push_refspec(nr_refspec, refspec_names);
int ret = 0;
int i;
- for (i = 0; i < nr_refspec; i++) {
- struct refspec *rs = refspec + i;
+ for (i = 0; i < rs->nr; i++) {
+ struct refspec_item *item = &rs->items[i];
- if (rs->pattern || rs->matching)
+ if (item->pattern || item->matching)
continue;
- ret |= match_explicit_lhs(src, rs, NULL, NULL);
+ ret |= match_explicit_lhs(src, item, NULL, NULL);
}
- free_refspec(nr_refspec, refspec);
return ret;
}
@@ -1471,32 +1281,29 @@ int check_push_refs(struct ref *src, int nr_refspec, const char **refspec_names)
* dst (e.g. pushing to a new branch, done in match_explicit_refs).
*/
int match_push_refs(struct ref *src, struct ref **dst,
- int nr_refspec, const char **refspec, int flags)
+ struct refspec *rs, int flags)
{
- struct refspec *rs;
int send_all = flags & MATCH_REFS_ALL;
int send_mirror = flags & MATCH_REFS_MIRROR;
int send_prune = flags & MATCH_REFS_PRUNE;
int errs;
- static const char *default_refspec[] = { ":", NULL };
struct ref *ref, **dst_tail = tail_ref(dst);
struct string_list dst_ref_index = STRING_LIST_INIT_NODUP;
- if (!nr_refspec) {
- nr_refspec = 1;
- refspec = default_refspec;
- }
- rs = parse_push_refspec(nr_refspec, (const char **) refspec);
- errs = match_explicit_refs(src, *dst, &dst_tail, rs, nr_refspec);
+ /* If no refspec is provided, use the default ":" */
+ if (!rs->nr)
+ refspec_append(rs, ":");
+
+ errs = match_explicit_refs(src, *dst, &dst_tail, rs);
/* pick the remainder */
for (ref = src; ref; ref = ref->next) {
struct string_list_item *dst_item;
struct ref *dst_peer;
- const struct refspec *pat = NULL;
+ const struct refspec_item *pat = NULL;
char *dst_name;
- dst_name = get_ref_match(rs, nr_refspec, ref, send_mirror, FROM_SRC, &pat);
+ dst_name = get_ref_match(rs, ref, send_mirror, FROM_SRC, &pat);
if (!dst_name)
continue;
@@ -1545,7 +1352,7 @@ int match_push_refs(struct ref *src, struct ref **dst,
/* We're already sending something to this ref. */
continue;
- src_name = get_ref_match(rs, nr_refspec, ref, send_mirror, FROM_DST, NULL);
+ src_name = get_ref_match(rs, ref, send_mirror, FROM_DST, NULL);
if (src_name) {
if (!src_ref_index.nr)
prepare_ref_index(&src_ref_index, src);
@@ -1557,6 +1364,7 @@ int match_push_refs(struct ref *src, struct ref **dst,
}
string_list_clear(&src_ref_index, 0);
}
+
if (errs)
return -1;
return 0;
@@ -1753,7 +1561,7 @@ static const char *tracking_for_push_dest(struct remote *remote,
{
char *ret;
- ret = apply_refspecs(remote->fetch, remote->fetch_refspec_nr, refname);
+ ret = apply_refspecs(&remote->fetch, refname);
if (!ret)
return error_buf(err,
_("push destination '%s' on remote '%s' has no local tracking branch"),
@@ -1771,12 +1579,11 @@ static const char *branch_get_push_1(struct branch *branch, struct strbuf *err)
_("branch '%s' has no remote for pushing"),
branch->name);
- if (remote->push_refspec_nr) {
+ if (remote->push.nr) {
char *dst;
const char *ret;
- dst = apply_refspecs(remote->push, remote->push_refspec_nr,
- branch->refname);
+ dst = apply_refspecs(&remote->push, branch->refname);
if (!dst)
return error_buf(err,
_("push refspecs for '%s' do not include '%s'"),
@@ -1819,7 +1626,7 @@ static const char *branch_get_push_1(struct branch *branch, struct strbuf *err)
}
}
- die("BUG: unhandled push situation");
+ BUG("unhandled push situation");
}
const char *branch_get_push(struct branch *branch, struct strbuf *err)
@@ -1849,7 +1656,7 @@ static int ignore_symref_update(const char *refname)
* local symbolic ref.
*/
static struct ref *get_expanded_map(const struct ref *remote_refs,
- const struct refspec *refspec)
+ const struct refspec_item *refspec)
{
const struct ref *ref;
struct ref *ret = NULL;
@@ -1914,7 +1721,7 @@ static struct ref *get_local_ref(const char *name)
}
int get_fetch_map(const struct ref *remote_refs,
- const struct refspec *refspec,
+ const struct refspec_item *refspec,
struct ref ***tail,
int missing_ok)
{
@@ -2252,8 +2059,7 @@ struct ref *guess_remote_head(const struct ref *head,
struct stale_heads_info {
struct string_list *ref_names;
struct ref **stale_refs_tail;
- struct refspec *refs;
- int ref_count;
+ struct refspec *rs;
};
static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
@@ -2261,12 +2067,12 @@ static int get_stale_heads_cb(const char *refname, const struct object_id *oid,
{
struct stale_heads_info *info = cb_data;
struct string_list matches = STRING_LIST_INIT_DUP;
- struct refspec query;
+ struct refspec_item query;
int i, stale = 1;
- memset(&query, 0, sizeof(struct refspec));
+ memset(&query, 0, sizeof(struct refspec_item));
query.dst = (char *)refname;
- query_refspecs_multiple(info->refs, info->ref_count, &query, &matches);
+ query_refspecs_multiple(info->rs, &query, &matches);
if (matches.nr == 0)
goto clean_exit; /* No matches */
@@ -2294,7 +2100,7 @@ clean_exit:
return 0;
}
-struct ref *get_stale_heads(struct refspec *refs, int ref_count, struct ref *fetch_map)
+struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map)
{
struct ref *ref, *stale_refs = NULL;
struct string_list ref_names = STRING_LIST_INIT_NODUP;
@@ -2302,8 +2108,7 @@ struct ref *get_stale_heads(struct refspec *refs, int ref_count, struct ref *fet
info.ref_names = &ref_names;
info.stale_refs_tail = &stale_refs;
- info.refs = refs;
- info.ref_count = ref_count;
+ info.rs = rs;
for (ref = fetch_map; ref; ref = ref->next)
string_list_append(&ref_names, ref->name);
string_list_sort(&ref_names);
@@ -2387,7 +2192,7 @@ static int remote_tracking(struct remote *remote, const char *refname,
{
char *dst;
- dst = apply_refspecs(remote->fetch, remote->fetch_refspec_nr, refname);
+ dst = apply_refspecs(&remote->fetch, refname);
if (!dst)
return -1; /* no tracking ref for refname at remote */
if (read_ref(dst, oid))
diff --git a/remote.h b/remote.h
index f09c019..45ecc6c 100644
--- a/remote.h
+++ b/remote.h
@@ -3,6 +3,7 @@
#include "parse-options.h"
#include "hashmap.h"
+#include "refspec.h"
enum {
REMOTE_UNCONFIGURED = 0,
@@ -27,15 +28,9 @@ struct remote {
int pushurl_nr;
int pushurl_alloc;
- const char **push_refspec;
- struct refspec *push;
- int push_refspec_nr;
- int push_refspec_alloc;
+ struct refspec push;
- const char **fetch_refspec;
- struct refspec *fetch;
- int fetch_refspec_nr;
- int fetch_refspec_alloc;
+ struct refspec fetch;
/*
* -1 to never fetch tags
@@ -68,18 +63,6 @@ int for_each_remote(each_remote_fn fn, void *priv);
int remote_has_url(struct remote *remote, const char *url);
-struct refspec {
- unsigned force : 1;
- unsigned pattern : 1;
- unsigned matching : 1;
- unsigned exact_sha1 : 1;
-
- char *src;
- char *dst;
-};
-
-extern const struct refspec *tag_refspec;
-
struct ref {
struct ref *next;
struct object_id old_oid;
@@ -151,10 +134,19 @@ int check_ref_type(const struct ref *ref, int flags);
void free_refs(struct ref *ref);
struct oid_array;
-extern struct ref **get_remote_heads(int in, char *src_buf, size_t src_len,
+struct packet_reader;
+struct argv_array;
+struct string_list;
+extern struct ref **get_remote_heads(struct packet_reader *reader,
struct ref **list, unsigned int flags,
struct oid_array *extra_have,
- struct oid_array *shallow);
+ struct oid_array *shallow_points);
+
+/* Used for protocol v2 in order to retrieve refs from a remote */
+extern struct ref **get_remote_refs(int fd_out, struct packet_reader *reader,
+ struct ref **list, int for_push,
+ const struct argv_array *ref_prefixes,
+ const struct string_list *server_options);
int resolve_remote_symref(struct ref *ref, struct ref *list);
int ref_newer(const struct object_id *new_oid, const struct object_id *old_oid);
@@ -168,19 +160,12 @@ int ref_newer(const struct object_id *new_oid, const struct object_id *old_oid);
*/
struct ref *ref_remove_duplicates(struct ref *ref_map);
-int valid_fetch_refspec(const char *refspec);
-struct refspec *parse_fetch_refspec(int nr_refspec, const char **refspec);
-extern struct refspec *parse_push_refspec(int nr_refspec, const char **refspec);
+int query_refspecs(struct refspec *rs, struct refspec_item *query);
+char *apply_refspecs(struct refspec *rs, const char *name);
-void free_refspec(int nr_refspec, struct refspec *refspec);
-
-extern int query_refspecs(struct refspec *specs, int nr, struct refspec *query);
-char *apply_refspecs(struct refspec *refspecs, int nr_refspec,
- const char *name);
-
-int check_push_refs(struct ref *src, int nr_refspec, const char **refspec);
+int check_push_refs(struct ref *src, struct refspec *rs);
int match_push_refs(struct ref *src, struct ref **dst,
- int nr_refspec, const char **refspec, int all);
+ struct refspec *rs, int flags);
void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
int force_update);
@@ -196,7 +181,7 @@ void set_ref_status_for_push(struct ref *remote_refs, int send_mirror,
* missing_ok is usually false, but when we are adding branch.$name.merge
* it is Ok if the branch is not at the remote anymore.
*/
-int get_fetch_map(const struct ref *remote_refs, const struct refspec *refspec,
+int get_fetch_map(const struct ref *remote_refs, const struct refspec_item *refspec,
struct ref ***tail, int missing_ok);
struct ref *get_remote_ref(const struct ref *remote_refs, const char *name);
@@ -204,7 +189,7 @@ struct ref *get_remote_ref(const struct ref *remote_refs, const char *name);
/*
* For the given remote, reads the refspec's src and sets the other fields.
*/
-int remote_find_tracking(struct remote *remote, struct refspec *refspec);
+int remote_find_tracking(struct remote *remote, struct refspec_item *refspec);
struct branch {
const char *name;
@@ -214,7 +199,7 @@ struct branch {
const char *pushremote_name;
const char **merge_name;
- struct refspec **merge;
+ struct refspec_item **merge;
int merge_nr;
int merge_alloc;
@@ -283,7 +268,7 @@ struct ref *guess_remote_head(const struct ref *head,
int all);
/* Return refs which no longer exist on remote */
-struct ref *get_stale_heads(struct refspec *refs, int ref_count, struct ref *fetch_map);
+struct ref *get_stale_heads(struct refspec *rs, struct ref *fetch_map);
/*
* Compare-and-swap
@@ -306,8 +291,4 @@ extern int parseopt_push_cas_option(const struct option *, const char *arg, int
extern int is_empty_cas(const struct push_cas_option *);
void apply_push_cas(struct push_cas_option *, struct remote *, struct ref *);
-#define TAG_REFSPEC "refs/tags/*:refs/tags/*"
-
-void add_prune_tags_to_fetch_refspec(struct remote *remote);
-
#endif
diff --git a/replace-object.c b/replace-object.c
new file mode 100644
index 0000000..801b5c1
--- /dev/null
+++ b/replace-object.c
@@ -0,0 +1,73 @@
+#include "cache.h"
+#include "oidmap.h"
+#include "object-store.h"
+#include "replace-object.h"
+#include "refs.h"
+#include "repository.h"
+#include "commit.h"
+
+static int register_replace_ref(const char *refname,
+ const struct object_id *oid,
+ int flag, void *cb_data)
+{
+ /* Get sha1 from refname */
+ const char *slash = strrchr(refname, '/');
+ const char *hash = slash ? slash + 1 : refname;
+ struct replace_object *repl_obj = xmalloc(sizeof(*repl_obj));
+
+ if (get_oid_hex(hash, &repl_obj->original.oid)) {
+ free(repl_obj);
+ warning("bad replace ref name: %s", refname);
+ return 0;
+ }
+
+ /* Copy sha1 from the read ref */
+ oidcpy(&repl_obj->replacement, oid);
+
+ /* Register new object */
+ if (oidmap_put(the_repository->objects->replace_map, repl_obj))
+ die("duplicate replace ref: %s", refname);
+
+ return 0;
+}
+
+static void prepare_replace_object(struct repository *r)
+{
+ if (r->objects->replace_map)
+ return;
+
+ r->objects->replace_map =
+ xmalloc(sizeof(*r->objects->replace_map));
+ oidmap_init(r->objects->replace_map, 0);
+
+ for_each_replace_ref(r, register_replace_ref, NULL);
+}
+
+/* We allow "recursive" replacement. Only within reason, though */
+#define MAXREPLACEDEPTH 5
+
+/*
+ * If a replacement for object oid has been set up, return the
+ * replacement object's name (replaced recursively, if necessary).
+ * The return value is either oid or a pointer to a
+ * permanently-allocated value. This function always respects replace
+ * references, regardless of the value of check_replace_refs.
+ */
+const struct object_id *do_lookup_replace_object(struct repository *r,
+ const struct object_id *oid)
+{
+ int depth = MAXREPLACEDEPTH;
+ const struct object_id *cur = oid;
+
+ prepare_replace_object(r);
+
+ /* Try to recursively replace the object */
+ while (depth-- > 0) {
+ struct replace_object *repl_obj =
+ oidmap_get(r->objects->replace_map, cur);
+ if (!repl_obj)
+ return cur;
+ cur = &repl_obj->replacement;
+ }
+ die("replace depth too high for object %s", oid_to_hex(oid));
+}
diff --git a/replace-object.h b/replace-object.h
new file mode 100644
index 0000000..f996de3
--- /dev/null
+++ b/replace-object.h
@@ -0,0 +1,36 @@
+#ifndef REPLACE_OBJECT_H
+#define REPLACE_OBJECT_H
+
+#include "oidmap.h"
+#include "repository.h"
+#include "object-store.h"
+
+struct replace_object {
+ struct oidmap_entry original;
+ struct object_id replacement;
+};
+
+/*
+ * This internal function is only declared here for the benefit of
+ * lookup_replace_object(). Please do not call it directly.
+ */
+extern const struct object_id *do_lookup_replace_object(struct repository *r,
+ const struct object_id *oid);
+
+/*
+ * If object sha1 should be replaced, return the replacement object's
+ * name (replaced recursively, if necessary). The return value is
+ * either sha1 or a pointer to a permanently-allocated value. When
+ * object replacement is suppressed, always return sha1.
+ */
+static inline const struct object_id *lookup_replace_object(struct repository *r,
+ const struct object_id *oid)
+{
+ if (!check_replace_refs ||
+ (r->objects->replace_map &&
+ r->objects->replace_map->map.tablesize == 0))
+ return oid;
+ return do_lookup_replace_object(r, oid);
+}
+
+#endif /* REPLACE_OBJECT_H */
diff --git a/replace_object.c b/replace_object.c
deleted file mode 100644
index 3363573..0000000
--- a/replace_object.c
+++ /dev/null
@@ -1,120 +0,0 @@
-#include "cache.h"
-#include "sha1-lookup.h"
-#include "refs.h"
-#include "commit.h"
-
-/*
- * An array of replacements. The array is kept sorted by the original
- * sha1.
- */
-static struct replace_object {
- struct object_id original;
- struct object_id replacement;
-} **replace_object;
-
-static int replace_object_alloc, replace_object_nr;
-
-static const unsigned char *replace_sha1_access(size_t index, void *table)
-{
- struct replace_object **replace = table;
- return replace[index]->original.hash;
-}
-
-static int replace_object_pos(const unsigned char *sha1)
-{
- return sha1_pos(sha1, replace_object, replace_object_nr,
- replace_sha1_access);
-}
-
-static int register_replace_object(struct replace_object *replace,
- int ignore_dups)
-{
- int pos = replace_object_pos(replace->original.hash);
-
- if (0 <= pos) {
- if (ignore_dups)
- free(replace);
- else {
- free(replace_object[pos]);
- replace_object[pos] = replace;
- }
- return 1;
- }
- pos = -pos - 1;
- ALLOC_GROW(replace_object, replace_object_nr + 1, replace_object_alloc);
- replace_object_nr++;
- if (pos < replace_object_nr)
- MOVE_ARRAY(replace_object + pos + 1, replace_object + pos,
- replace_object_nr - pos - 1);
- replace_object[pos] = replace;
- return 0;
-}
-
-static int register_replace_ref(const char *refname,
- const struct object_id *oid,
- int flag, void *cb_data)
-{
- /* Get sha1 from refname */
- const char *slash = strrchr(refname, '/');
- const char *hash = slash ? slash + 1 : refname;
- struct replace_object *repl_obj = xmalloc(sizeof(*repl_obj));
-
- if (get_oid_hex(hash, &repl_obj->original)) {
- free(repl_obj);
- warning("bad replace ref name: %s", refname);
- return 0;
- }
-
- /* Copy sha1 from the read ref */
- oidcpy(&repl_obj->replacement, oid);
-
- /* Register new object */
- if (register_replace_object(repl_obj, 1))
- die("duplicate replace ref: %s", refname);
-
- return 0;
-}
-
-static void prepare_replace_object(void)
-{
- static int replace_object_prepared;
-
- if (replace_object_prepared)
- return;
-
- for_each_replace_ref(register_replace_ref, NULL);
- replace_object_prepared = 1;
- if (!replace_object_nr)
- check_replace_refs = 0;
-}
-
-/* We allow "recursive" replacement. Only within reason, though */
-#define MAXREPLACEDEPTH 5
-
-/*
- * If a replacement for object oid has been set up, return the
- * replacement object's name (replaced recursively, if necessary).
- * The return value is either oid or a pointer to a
- * permanently-allocated value. This function always respects replace
- * references, regardless of the value of check_replace_refs.
- */
-const struct object_id *do_lookup_replace_object(const struct object_id *oid)
-{
- int pos, depth = MAXREPLACEDEPTH;
- const struct object_id *cur = oid;
-
- prepare_replace_object();
-
- /* Try to recursively replace the object */
- do {
- if (--depth < 0)
- die("replace depth too high for object %s",
- oid_to_hex(oid));
-
- pos = replace_object_pos(cur->hash);
- if (0 <= pos)
- cur = &replace_object[pos]->replacement;
- } while (0 <= pos);
-
- return cur;
-}
diff --git a/repository.c b/repository.c
index a4848c1..02fe884 100644
--- a/repository.c
+++ b/repository.c
@@ -135,9 +135,9 @@ static int read_and_verify_repository_format(struct repository_format *format,
* Initialize 'repo' based on the provided 'gitdir'.
* Return 0 upon success and a non-zero value upon failure.
*/
-static int repo_init(struct repository *repo,
- const char *gitdir,
- const char *worktree)
+int repo_init(struct repository *repo,
+ const char *gitdir,
+ const char *worktree)
{
struct repository_format format;
memset(repo, 0, sizeof(*repo));
@@ -176,7 +176,7 @@ int repo_submodule_init(struct repository *submodule,
struct strbuf worktree = STRBUF_INIT;
int ret = 0;
- sub = submodule_from_cache(superproject, &null_oid, path);
+ sub = submodule_from_path(superproject, &null_oid, path);
if (!sub) {
ret = -1;
goto out;
@@ -238,7 +238,8 @@ void repo_clear(struct repository *repo)
if (repo->index) {
discard_index(repo->index);
- FREE_AND_NULL(repo->index);
+ if (repo->index != &the_index)
+ FREE_AND_NULL(repo->index);
}
}
diff --git a/repository.h b/repository.h
index 09df94a..f2646f0 100644
--- a/repository.h
+++ b/repository.h
@@ -26,6 +26,9 @@ struct repository {
*/
struct raw_object_store *objects;
+ /* The store in which the refs are held. */
+ struct ref_store *refs;
+
/*
* Path to the repository's graft file.
* Cannot be NULL after initialization.
@@ -97,6 +100,9 @@ extern void repo_set_gitdir(struct repository *repo,
extern void repo_set_worktree(struct repository *repo, const char *path);
extern void repo_set_hash_algo(struct repository *repo, int algo);
extern void initialize_the_repository(void);
+extern int repo_init(struct repository *r,
+ const char *gitdir,
+ const char *worktree);
extern int repo_submodule_init(struct repository *submodule,
struct repository *superproject,
const char *path);
diff --git a/rerere.c b/rerere.c
index 18cae2d..e0862e2 100644
--- a/rerere.c
+++ b/rerere.c
@@ -703,10 +703,9 @@ out:
return ret;
}
-static struct lock_file index_lock;
-
static void update_paths(struct string_list *update)
{
+ struct lock_file index_lock = LOCK_INIT;
int i;
hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
diff --git a/resolve-undo.c b/resolve-undo.c
index aed95b4..fc5b3b8 100644
--- a/resolve-undo.c
+++ b/resolve-undo.c
@@ -90,7 +90,7 @@ struct string_list *resolve_undo_read(const char *data, unsigned long size)
continue;
if (size < rawsz)
goto error;
- memcpy(ui->oid[i].hash, (const unsigned char *)data, rawsz);
+ oidread(&ui->oid[i], (const unsigned char *)data);
size -= rawsz;
data += rawsz;
}
diff --git a/revision.c b/revision.c
index b42c836..40fd91f 100644
--- a/revision.c
+++ b/revision.c
@@ -6,6 +6,7 @@
#include "diff.h"
#include "refs.h"
#include "revision.h"
+#include "repository.h"
#include "graph.h"
#include "grep.h"
#include "reflog-walk.h"
@@ -51,12 +52,9 @@ static void mark_tree_contents_uninteresting(struct tree *tree)
{
struct tree_desc desc;
struct name_entry entry;
- struct object *obj = &tree->object;
- if (!has_object_file(&obj->oid))
+ if (parse_tree_gently(tree, 1) < 0)
return;
- if (parse_tree(tree) < 0)
- die("bad tree %s", oid_to_hex(&obj->oid));
init_tree_desc(&desc, tree->buffer, tree->size);
while (tree_entry(&desc, &entry)) {
@@ -94,50 +92,63 @@ void mark_tree_uninteresting(struct tree *tree)
mark_tree_contents_uninteresting(tree);
}
-void mark_parents_uninteresting(struct commit *commit)
+struct commit_stack {
+ struct commit **items;
+ size_t nr, alloc;
+};
+#define COMMIT_STACK_INIT { NULL, 0, 0 }
+
+static void commit_stack_push(struct commit_stack *stack, struct commit *commit)
{
- struct commit_list *parents = NULL, *l;
+ ALLOC_GROW(stack->items, stack->nr + 1, stack->alloc);
+ stack->items[stack->nr++] = commit;
+}
- for (l = commit->parents; l; l = l->next)
- commit_list_insert(l->item, &parents);
+static struct commit *commit_stack_pop(struct commit_stack *stack)
+{
+ return stack->nr ? stack->items[--stack->nr] : NULL;
+}
- while (parents) {
- struct commit *commit = pop_commit(&parents);
+static void commit_stack_clear(struct commit_stack *stack)
+{
+ FREE_AND_NULL(stack->items);
+ stack->nr = stack->alloc = 0;
+}
- while (commit) {
- /*
- * A missing commit is ok iff its parent is marked
- * uninteresting.
- *
- * We just mark such a thing parsed, so that when
- * it is popped next time around, we won't be trying
- * to parse it and get an error.
- */
- if (!commit->object.parsed &&
- !has_object_file(&commit->object.oid))
- commit->object.parsed = 1;
+static void mark_one_parent_uninteresting(struct commit *commit,
+ struct commit_stack *pending)
+{
+ struct commit_list *l;
- if (commit->object.flags & UNINTERESTING)
- break;
+ if (commit->object.flags & UNINTERESTING)
+ return;
+ commit->object.flags |= UNINTERESTING;
+
+ /*
+ * Normally we haven't parsed the parent
+ * yet, so we won't have a parent of a parent
+ * here. However, it may turn out that we've
+ * reached this commit some other way (where it
+ * wasn't uninteresting), in which case we need
+ * to mark its parents recursively too..
+ */
+ for (l = commit->parents; l; l = l->next)
+ commit_stack_push(pending, l->item);
+}
- commit->object.flags |= UNINTERESTING;
+void mark_parents_uninteresting(struct commit *commit)
+{
+ struct commit_stack pending = COMMIT_STACK_INIT;
+ struct commit_list *l;
- /*
- * Normally we haven't parsed the parent
- * yet, so we won't have a parent of a parent
- * here. However, it may turn out that we've
- * reached this commit some other way (where it
- * wasn't uninteresting), in which case we need
- * to mark its parents recursively too..
- */
- if (!commit->parents)
- break;
+ for (l = commit->parents; l; l = l->next)
+ mark_one_parent_uninteresting(l->item, &pending);
- for (l = commit->parents->next; l; l = l->next)
- commit_list_insert(l->item, &parents);
- commit = commit->parents->item;
- }
- }
+ while (pending.nr > 0)
+ mark_one_parent_uninteresting(commit_stack_pop(&pending),
+ &pending);
+
+ commit_stack_clear(&pending);
}
static void add_pending_object_with_path(struct rev_info *revs,
@@ -440,8 +451,8 @@ static void file_change(struct diff_options *options,
static int rev_compare_tree(struct rev_info *revs,
struct commit *parent, struct commit *commit)
{
- struct tree *t1 = parent->tree;
- struct tree *t2 = commit->tree;
+ struct tree *t1 = get_commit_tree(parent);
+ struct tree *t2 = get_commit_tree(commit);
if (!t1)
return REV_TREE_NEW;
@@ -477,7 +488,7 @@ static int rev_compare_tree(struct rev_info *revs,
static int rev_same_tree_as_empty(struct rev_info *revs, struct commit *commit)
{
int retval;
- struct tree *t1 = commit->tree;
+ struct tree *t1 = get_commit_tree(commit);
if (!t1)
return 0;
@@ -615,7 +626,7 @@ static void try_to_simplify_commit(struct rev_info *revs, struct commit *commit)
if (!revs->prune)
return;
- if (!commit->tree)
+ if (!get_commit_tree(commit))
return;
if (!commit->parents) {
@@ -1285,7 +1296,7 @@ void add_reflogs_to_pending(struct rev_info *revs, unsigned flags)
cb.all_revs = revs;
cb.all_flags = flags;
- cb.refs = get_main_ref_store();
+ cb.refs = get_main_ref_store(the_repository);
for_each_reflog(handle_one_reflog, &cb);
if (!revs->single_worktree)
@@ -1751,6 +1762,7 @@ static int handle_revision_opt(struct rev_info *revs, int argc, const char **arg
const char *arg = argv[0];
const char *optarg;
int argcount;
+ const unsigned hexsz = the_hash_algo->hexsz;
/* pseudo revision arguments */
if (!strcmp(arg, "--all") || !strcmp(arg, "--branches") ||
@@ -2038,8 +2050,8 @@ static int handle_revision_opt(struct rev_info *revs, int argc, const char **arg
revs->abbrev = strtoul(optarg, NULL, 10);
if (revs->abbrev < MINIMUM_ABBREV)
revs->abbrev = MINIMUM_ABBREV;
- else if (revs->abbrev > 40)
- revs->abbrev = 40;
+ else if (revs->abbrev > hexsz)
+ revs->abbrev = hexsz;
} else if (!strcmp(arg, "--abbrev-commit")) {
revs->abbrev_commit = 1;
revs->abbrev_commit_given = 1;
@@ -2107,7 +2119,7 @@ static int handle_revision_opt(struct rev_info *revs, int argc, const char **arg
revs->ignore_missing = 1;
} else if (!strcmp(arg, "--exclude-promisor-objects")) {
if (fetch_if_missing)
- die("BUG: exclude_promisor_objects can only be used when fetch_if_missing is 0");
+ BUG("exclude_promisor_objects can only be used when fetch_if_missing is 0");
revs->exclude_promisor_objects = 1;
} else {
int opts = diff_opt_parse(&revs->diffopt, argv, argc, revs->prefix);
@@ -2173,10 +2185,10 @@ static int handle_revision_pseudo_opt(const char *submodule,
* supported right now, so stick to single worktree.
*/
if (!revs->single_worktree)
- die("BUG: --single-worktree cannot be used together with submodule");
+ BUG("--single-worktree cannot be used together with submodule");
refs = get_submodule_ref_store(submodule);
} else
- refs = get_main_ref_store();
+ refs = get_main_ref_store(the_repository);
/*
* NOTE!
@@ -3086,7 +3098,7 @@ enum commit_action get_commit_action(struct rev_info *revs, struct commit *commi
{
if (commit->object.flags & SHOWN)
return commit_ignore;
- if (revs->unpacked && has_sha1_pack(commit->object.oid.hash))
+ if (revs->unpacked && has_object_pack(&commit->object.oid))
return commit_ignore;
if (commit->object.flags & UNINTERESTING)
return commit_ignore;
diff --git a/run-command.c b/run-command.c
index 84899e4..84b883c 100644
--- a/run-command.c
+++ b/run-command.c
@@ -1,6 +1,6 @@
#include "cache.h"
#include "run-command.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "sigchain.h"
#include "argv-array.h"
#include "thread-utils.h"
@@ -245,7 +245,7 @@ int sane_execvp(const char *file, char * const argv[])
static const char **prepare_shell_cmd(struct argv_array *out, const char **argv)
{
if (!argv[0])
- die("BUG: shell command is empty");
+ BUG("shell command is empty");
if (strcspn(argv[0], "|&;<>()$`\\\"' \t\n*?[#~=%") != strlen(argv[0])) {
#ifndef GIT_WINDOWS_NATIVE
@@ -383,7 +383,7 @@ static void child_err_spew(struct child_process *cmd, struct child_err *cerr)
static void prepare_cmd(struct argv_array *out, const struct child_process *cmd)
{
if (!cmd->argv[0])
- die("BUG: command is empty");
+ BUG("command is empty");
/*
* Add SHELL_PATH so in the event exec fails with ENOEXEC we can
@@ -471,15 +471,12 @@ struct atfork_state {
sigset_t old;
};
-#ifndef NO_PTHREADS
-static void bug_die(int err, const char *msg)
-{
- if (err) {
- errno = err;
- die_errno("BUG: %s", msg);
- }
-}
-#endif
+#define CHECK_BUG(err, msg) \
+ do { \
+ int e = (err); \
+ if (e) \
+ BUG("%s: %s", msg, strerror(e)); \
+ } while(0)
static void atfork_prepare(struct atfork_state *as)
{
@@ -491,9 +488,9 @@ static void atfork_prepare(struct atfork_state *as)
if (sigprocmask(SIG_SETMASK, &all, &as->old))
die_errno("sigprocmask");
#else
- bug_die(pthread_sigmask(SIG_SETMASK, &all, &as->old),
+ CHECK_BUG(pthread_sigmask(SIG_SETMASK, &all, &as->old),
"blocking all signals");
- bug_die(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
+ CHECK_BUG(pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &as->cs),
"disabling cancellation");
#endif
}
@@ -504,9 +501,9 @@ static void atfork_parent(struct atfork_state *as)
if (sigprocmask(SIG_SETMASK, &as->old, NULL))
die_errno("sigprocmask");
#else
- bug_die(pthread_setcancelstate(as->cs, NULL),
+ CHECK_BUG(pthread_setcancelstate(as->cs, NULL),
"re-enabling cancellation");
- bug_die(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
+ CHECK_BUG(pthread_sigmask(SIG_SETMASK, &as->old, NULL),
"restoring signal mask");
#endif
}
@@ -967,7 +964,7 @@ int run_command(struct child_process *cmd)
int code;
if (cmd->out < 0 || cmd->err < 0)
- die("BUG: run_command with a pipe can cause deadlock");
+ BUG("run_command with a pipe can cause deadlock");
code = start_command(cmd);
if (code)
@@ -1557,7 +1554,7 @@ static void pp_init(struct parallel_processes *pp,
pp->data = data;
if (!get_next_task)
- die("BUG: you need to specify a get_next_task function");
+ BUG("you need to specify a get_next_task function");
pp->get_next_task = get_next_task;
pp->start_failure = start_failure ? start_failure : default_start_failure;
@@ -1619,7 +1616,7 @@ static int pp_start_one(struct parallel_processes *pp)
if (pp->children[i].state == GIT_CP_FREE)
break;
if (i == pp->max_processes)
- die("BUG: bookkeeping is hard");
+ BUG("bookkeeping is hard");
code = pp->get_next_task(&pp->children[i].process,
&pp->children[i].err,
diff --git a/sequencer.c b/sequencer.c
index 667f35e..72b4d8e 100644
--- a/sequencer.c
+++ b/sequencer.c
@@ -7,7 +7,7 @@
#include "sequencer.h"
#include "tag.h"
#include "run-command.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "utf8.h"
#include "cache-tree.h"
#include "diff.h"
@@ -23,6 +23,10 @@
#include "hashmap.h"
#include "notes-utils.h"
#include "sigchain.h"
+#include "unpack-trees.h"
+#include "worktree.h"
+#include "oidmap.h"
+#include "oidset.h"
#define GIT_REFLOG_ACTION "GIT_REFLOG_ACTION"
@@ -74,13 +78,6 @@ static GIT_PATH_FUNC(rebase_path_message, "rebase-merge/message")
* previous commit and from the first squash/fixup commit are written
* to it. The commit message for each subsequent squash/fixup commit
* is appended to the file as it is processed.
- *
- * The first line of the file is of the form
- * # This is a combination of $count commits.
- * where $count is the number of commits whose messages have been
- * written to the file so far (including the initial "pick" commit).
- * Each time that a commit message is processed, this line is read and
- * updated. It is deleted just before the combined commit is made.
*/
static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
/*
@@ -92,6 +89,11 @@ static GIT_PATH_FUNC(rebase_path_squash_msg, "rebase-merge/message-squash")
*/
static GIT_PATH_FUNC(rebase_path_fixup_msg, "rebase-merge/message-fixup")
/*
+ * This file contains the list fixup/squash commands that have been
+ * accumulated into message-fixup or message-squash so far.
+ */
+static GIT_PATH_FUNC(rebase_path_current_fixups, "rebase-merge/current-fixups")
+/*
* A script to set the GIT_AUTHOR_NAME, GIT_AUTHOR_EMAIL, and
* GIT_AUTHOR_DATE that will be used for the commit that is currently
* being rebased.
@@ -120,6 +122,19 @@ static GIT_PATH_FUNC(rebase_path_stopped_sha, "rebase-merge/stopped-sha")
static GIT_PATH_FUNC(rebase_path_rewritten_list, "rebase-merge/rewritten-list")
static GIT_PATH_FUNC(rebase_path_rewritten_pending,
"rebase-merge/rewritten-pending")
+
+/*
+ * The path of the file containig the OID of the "squash onto" commit, i.e.
+ * the dummy commit used for `reset [new root]`.
+ */
+static GIT_PATH_FUNC(rebase_path_squash_onto, "rebase-merge/squash-onto")
+
+/*
+ * The path of the file listing refs that need to be deleted after the rebase
+ * finishes. This is used by the `label` command to record the need for cleanup.
+ */
+static GIT_PATH_FUNC(rebase_path_refs_to_delete, "rebase-merge/refs-to-delete")
+
/*
* The following files are written by git-rebase just after parsing the
* command-line (and are only consumed, not modified, by the sequencer).
@@ -127,6 +142,7 @@ static GIT_PATH_FUNC(rebase_path_rewritten_pending,
static GIT_PATH_FUNC(rebase_path_gpg_sign_opt, "rebase-merge/gpg_sign_opt")
static GIT_PATH_FUNC(rebase_path_orig_head, "rebase-merge/orig-head")
static GIT_PATH_FUNC(rebase_path_verbose, "rebase-merge/verbose")
+static GIT_PATH_FUNC(rebase_path_signoff, "rebase-merge/signoff")
static GIT_PATH_FUNC(rebase_path_head_name, "rebase-merge/head-name")
static GIT_PATH_FUNC(rebase_path_onto, "rebase-merge/onto")
static GIT_PATH_FUNC(rebase_path_autostash, "rebase-merge/autostash")
@@ -244,18 +260,35 @@ static const char *gpg_sign_opt_quoted(struct replay_opts *opts)
int sequencer_remove_state(struct replay_opts *opts)
{
- struct strbuf dir = STRBUF_INIT;
+ struct strbuf buf = STRBUF_INIT;
int i;
+ if (is_rebase_i(opts) &&
+ strbuf_read_file(&buf, rebase_path_refs_to_delete(), 0) > 0) {
+ char *p = buf.buf;
+ while (*p) {
+ char *eol = strchr(p, '\n');
+ if (eol)
+ *eol = '\0';
+ if (delete_ref("(rebase -i) cleanup", p, NULL, 0) < 0)
+ warning(_("could not delete '%s'"), p);
+ if (!eol)
+ break;
+ p = eol + 1;
+ }
+ }
+
free(opts->gpg_sign);
free(opts->strategy);
for (i = 0; i < opts->xopts_nr; i++)
free(opts->xopts[i]);
free(opts->xopts);
+ strbuf_release(&opts->current_fixups);
- strbuf_addstr(&dir, get_dir(opts));
- remove_dir_recursively(&dir, 0);
- strbuf_release(&dir);
+ strbuf_reset(&buf);
+ strbuf_addstr(&buf, get_dir(opts));
+ remove_dir_recursively(&buf, 0);
+ strbuf_release(&buf);
return 0;
}
@@ -345,12 +378,14 @@ static int write_message(const void *buf, size_t len, const char *filename,
if (msg_fd < 0)
return error_errno(_("could not lock '%s'"), filename);
if (write_in_full(msg_fd, buf, len) < 0) {
+ error_errno(_("could not write to '%s'"), filename);
rollback_lock_file(&msg_file);
- return error_errno(_("could not write to '%s'"), filename);
+ return -1;
}
if (append_eol && write(msg_fd, "\n", 1) < 0) {
+ error_errno(_("could not write eol to '%s'"), filename);
rollback_lock_file(&msg_file);
- return error_errno(_("could not write eol to '%s'"), filename);
+ return -1;
}
if (commit_lock_file(&msg_file) < 0)
return error(_("failed to finalize '%s'"), filename);
@@ -440,7 +475,8 @@ static int fast_forward_to(const struct object_id *to, const struct object_id *f
transaction = ref_transaction_begin(&err);
if (!transaction ||
ref_transaction_update(transaction, "HEAD",
- to, unborn ? &null_oid : from,
+ to, unborn && !is_rebase_i(opts) ?
+ &null_oid : from,
0, sb.buf, &err) ||
ref_transaction_commit(transaction, &err)) {
ref_transaction_free(transaction);
@@ -499,8 +535,8 @@ static int do_recursive_merge(struct commit *base, struct commit *next,
o.show_rename_progress = 1;
head_tree = parse_tree_indirect(head);
- next_tree = next ? next->tree : empty_tree();
- base_tree = base ? base->tree : empty_tree();
+ next_tree = next ? get_commit_tree(next) : empty_tree();
+ base_tree = base ? get_commit_tree(base) : empty_tree();
for (xopt = opts->xopts; xopt != opts->xopts + opts->xopts_nr; xopt++)
parse_merge_opt(&o, *xopt);
@@ -532,9 +568,23 @@ static int do_recursive_merge(struct commit *base, struct commit *next,
return !clean;
}
+static struct object_id *get_cache_tree_oid(void)
+{
+ if (!active_cache_tree)
+ active_cache_tree = cache_tree();
+
+ if (!cache_tree_fully_valid(active_cache_tree))
+ if (cache_tree_update(&the_index, 0)) {
+ error(_("unable to update cache tree"));
+ return NULL;
+ }
+
+ return &active_cache_tree->oid;
+}
+
static int is_index_unchanged(void)
{
- struct object_id head_oid;
+ struct object_id head_oid, *cache_tree_oid;
struct commit *head_commit;
if (!resolve_ref_unsafe("HEAD", RESOLVE_REF_READING, &head_oid, NULL))
@@ -553,15 +603,10 @@ static int is_index_unchanged(void)
if (parse_commit(head_commit))
return -1;
- if (!active_cache_tree)
- active_cache_tree = cache_tree();
-
- if (!cache_tree_fully_valid(active_cache_tree))
- if (cache_tree_update(&the_index, 0))
- return error(_("unable to update cache tree"));
+ if (!(cache_tree_oid = get_cache_tree_oid()))
+ return -1;
- return !oidcmp(&active_cache_tree->oid,
- &head_commit->tree->object.oid);
+ return !oidcmp(cache_tree_oid, get_commit_tree_oid(head_commit));
}
static int write_author_script(const char *message)
@@ -653,6 +698,52 @@ static char *get_author(const char *message)
return NULL;
}
+/* Read author-script and return an ident line (author <email> timestamp) */
+static const char *read_author_ident(struct strbuf *buf)
+{
+ const char *keys[] = {
+ "GIT_AUTHOR_NAME=", "GIT_AUTHOR_EMAIL=", "GIT_AUTHOR_DATE="
+ };
+ char *in, *out, *eol;
+ int i = 0, len;
+
+ if (strbuf_read_file(buf, rebase_path_author_script(), 256) <= 0)
+ return NULL;
+
+ /* dequote values and construct ident line in-place */
+ for (in = out = buf->buf; i < 3 && in - buf->buf < buf->len; i++) {
+ if (!skip_prefix(in, keys[i], (const char **)&in)) {
+ warning("could not parse '%s' (looking for '%s'",
+ rebase_path_author_script(), keys[i]);
+ return NULL;
+ }
+
+ eol = strchrnul(in, '\n');
+ *eol = '\0';
+ sq_dequote(in);
+ len = strlen(in);
+
+ if (i > 0) /* separate values by spaces */
+ *(out++) = ' ';
+ if (i == 1) /* email needs to be surrounded by <...> */
+ *(out++) = '<';
+ memmove(out, in, len);
+ out += len;
+ if (i == 1) /* email needs to be surrounded by <...> */
+ *(out++) = '>';
+ in = eol + 1;
+ }
+
+ if (i < 3) {
+ warning("could not parse '%s' (looking for '%s')",
+ rebase_path_author_script(), keys[i]);
+ return NULL;
+ }
+
+ buf->len = out - buf->buf;
+ return buf->buf;
+}
+
static const char staged_changes_advice[] =
N_("you have staged changes in your working tree\n"
"If these changes are meant to be squashed into the previous commit, run:\n"
@@ -672,6 +763,7 @@ N_("you have staged changes in your working tree\n"
#define AMEND_MSG (1<<2)
#define CLEANUP_MSG (1<<3)
#define VERIFY_MSG (1<<4)
+#define CREATE_ROOT_COMMIT (1<<5)
/*
* If we are cherry-pick, and if the merge did not result in
@@ -691,6 +783,40 @@ static int run_git_commit(const char *defmsg, struct replay_opts *opts,
struct child_process cmd = CHILD_PROCESS_INIT;
const char *value;
+ if (flags & CREATE_ROOT_COMMIT) {
+ struct strbuf msg = STRBUF_INIT, script = STRBUF_INIT;
+ const char *author = is_rebase_i(opts) ?
+ read_author_ident(&script) : NULL;
+ struct object_id root_commit, *cache_tree_oid;
+ int res = 0;
+
+ if (!defmsg)
+ BUG("root commit without message");
+
+ if (!(cache_tree_oid = get_cache_tree_oid()))
+ res = -1;
+
+ if (!res)
+ res = strbuf_read_file(&msg, defmsg, 0);
+
+ if (res <= 0)
+ res = error_errno(_("could not read '%s'"), defmsg);
+ else
+ res = commit_tree(msg.buf, msg.len, cache_tree_oid,
+ NULL, &root_commit, author,
+ opts->gpg_sign);
+
+ strbuf_release(&msg);
+ strbuf_release(&script);
+ if (!res) {
+ update_ref(NULL, "CHERRY_PICK_HEAD", &root_commit, NULL,
+ REF_NO_DEREF, UPDATE_REFS_MSG_ON_ERR);
+ res = update_ref(NULL, "HEAD", &root_commit, NULL, 0,
+ UPDATE_REFS_MSG_ON_ERR);
+ }
+ return res < 0 ? error(_("writing root commit")) : 0;
+ }
+
cmd.git_cmd = 1;
if (is_rebase_i(opts)) {
@@ -717,6 +843,8 @@ static int run_git_commit(const char *defmsg, struct replay_opts *opts,
argv_array_pushf(&cmd.args, "-S%s", opts->gpg_sign);
if (defmsg)
argv_array_pushl(&cmd.args, "-F", defmsg, NULL);
+ else if (!(flags & EDIT_MSG))
+ argv_array_pushl(&cmd.args, "-C", "HEAD", NULL);
if ((flags & CLEANUP_MSG))
argv_array_push(&cmd.args, "--cleanup=strip");
if ((flags & EDIT_MSG))
@@ -1118,8 +1246,8 @@ static int try_to_commit(struct strbuf *msg, const char *author,
}
if (!(flags & ALLOW_EMPTY) && !oidcmp(current_head ?
- &current_head->tree->object.oid :
- &empty_tree_oid, &tree)) {
+ get_commit_tree_oid(current_head) :
+ the_hash_algo->empty_tree, &tree)) {
res = 1; /* run 'git commit' to display error message */
goto out;
}
@@ -1148,6 +1276,8 @@ static int try_to_commit(struct strbuf *msg, const char *author,
goto out;
}
+ reset_ident_date();
+
if (commit_tree_extended(msg->buf, msg->len, &tree, parents,
oid, author, opts->gpg_sign, extra)) {
res = error(_("failed to write commit object"));
@@ -1177,7 +1307,8 @@ static int do_commit(const char *msg_file, const char *author,
{
int res = 1;
- if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG)) {
+ if (!(flags & EDIT_MSG) && !(flags & VERIFY_MSG) &&
+ !(flags & CREATE_ROOT_COMMIT)) {
struct object_id oid;
struct strbuf sb = STRBUF_INIT;
@@ -1216,12 +1347,12 @@ static int is_original_commit_empty(struct commit *commit)
if (parse_commit(parent))
return error(_("could not parse parent commit %s"),
oid_to_hex(&parent->object.oid));
- ptree_oid = &parent->tree->object.oid;
+ ptree_oid = get_commit_tree_oid(parent);
} else {
ptree_oid = the_hash_algo->empty_tree; /* commit is root */
}
- return !oidcmp(ptree_oid, &commit->tree->object.oid);
+ return !oidcmp(ptree_oid, get_commit_tree_oid(commit));
}
/*
@@ -1277,6 +1408,9 @@ enum todo_command {
TODO_SQUASH,
/* commands that do something else than handling a single commit */
TODO_EXEC,
+ TODO_LABEL,
+ TODO_RESET,
+ TODO_MERGE,
/* commands that do nothing but are counted for reporting progress */
TODO_NOOP,
TODO_DROP,
@@ -1295,6 +1429,9 @@ static struct {
{ 'f', "fixup" },
{ 's', "squash" },
{ 'x', "exec" },
+ { 'l', "label" },
+ { 't', "reset" },
+ { 'm', "merge" },
{ 0, "noop" },
{ 'd', "drop" },
{ 0, NULL }
@@ -1324,38 +1461,43 @@ static int is_fixup(enum todo_command command)
return command == TODO_FIXUP || command == TODO_SQUASH;
}
+/* Does this command create a (non-merge) commit? */
+static int is_pick_or_similar(enum todo_command command)
+{
+ switch (command) {
+ case TODO_PICK:
+ case TODO_REVERT:
+ case TODO_EDIT:
+ case TODO_REWORD:
+ case TODO_FIXUP:
+ case TODO_SQUASH:
+ return 1;
+ default:
+ return 0;
+ }
+}
+
static int update_squash_messages(enum todo_command command,
struct commit *commit, struct replay_opts *opts)
{
struct strbuf buf = STRBUF_INIT;
- int count, res;
+ int res;
const char *message, *body;
- if (file_exists(rebase_path_squash_msg())) {
+ if (opts->current_fixup_count > 0) {
struct strbuf header = STRBUF_INIT;
- char *eol, *p;
+ char *eol;
- if (strbuf_read_file(&buf, rebase_path_squash_msg(), 2048) <= 0)
+ if (strbuf_read_file(&buf, rebase_path_squash_msg(), 9) <= 0)
return error(_("could not read '%s'"),
rebase_path_squash_msg());
- p = buf.buf + 1;
- eol = strchrnul(buf.buf, '\n');
- if (buf.buf[0] != comment_line_char ||
- (p += strcspn(p, "0123456789\n")) == eol)
- return error(_("unexpected 1st line of squash message:"
- "\n\n\t%.*s"),
- (int)(eol - buf.buf), buf.buf);
- count = strtol(p, NULL, 10);
-
- if (count < 1)
- return error(_("invalid 1st line of squash message:\n"
- "\n\t%.*s"),
- (int)(eol - buf.buf), buf.buf);
+ eol = buf.buf[0] != comment_line_char ?
+ buf.buf : strchrnul(buf.buf, '\n');
strbuf_addf(&header, "%c ", comment_line_char);
- strbuf_addf(&header,
- _("This is a combination of %d commits."), ++count);
+ strbuf_addf(&header, _("This is a combination of %d commits."),
+ opts->current_fixup_count + 2);
strbuf_splice(&buf, 0, eol - buf.buf, header.buf, header.len);
strbuf_release(&header);
} else {
@@ -1378,10 +1520,8 @@ static int update_squash_messages(enum todo_command command,
rebase_path_fixup_msg());
}
- count = 2;
strbuf_addf(&buf, "%c ", comment_line_char);
- strbuf_addf(&buf, _("This is a combination of %d commits."),
- count);
+ strbuf_addf(&buf, _("This is a combination of %d commits."), 2);
strbuf_addf(&buf, "\n%c ", comment_line_char);
strbuf_addstr(&buf, _("This is the 1st commit message:"));
strbuf_addstr(&buf, "\n\n");
@@ -1398,13 +1538,14 @@ static int update_squash_messages(enum todo_command command,
if (command == TODO_SQUASH) {
unlink(rebase_path_fixup_msg());
strbuf_addf(&buf, "\n%c ", comment_line_char);
- strbuf_addf(&buf, _("This is the commit message #%d:"), count);
+ strbuf_addf(&buf, _("This is the commit message #%d:"),
+ ++opts->current_fixup_count);
strbuf_addstr(&buf, "\n\n");
strbuf_addstr(&buf, body);
} else if (command == TODO_FIXUP) {
strbuf_addf(&buf, "\n%c ", comment_line_char);
strbuf_addf(&buf, _("The commit message #%d will be skipped:"),
- count);
+ ++opts->current_fixup_count);
strbuf_addstr(&buf, "\n\n");
strbuf_add_commented_lines(&buf, body, strlen(body));
} else
@@ -1413,6 +1554,17 @@ static int update_squash_messages(enum todo_command command,
res = write_message(buf.buf, buf.len, rebase_path_squash_msg(), 0);
strbuf_release(&buf);
+
+ if (!res) {
+ strbuf_addf(&opts->current_fixups, "%s%s %s",
+ opts->current_fixups.len ? "\n" : "",
+ command_to_string(command),
+ oid_to_hex(&commit->object.oid));
+ res = write_message(opts->current_fixups.buf,
+ opts->current_fixups.len,
+ rebase_path_current_fixups(), 0);
+ }
+
return res;
}
@@ -1478,9 +1630,16 @@ static int do_pick_commit(enum todo_command command, struct commit *commit,
return error(_("your index file is unmerged."));
} else {
unborn = get_oid("HEAD", &head);
- if (unborn)
+ /* Do we want to generate a root commit? */
+ if (is_pick_or_similar(command) && opts->have_squash_onto &&
+ !oidcmp(&head, &opts->squash_onto)) {
+ if (is_fixup(command))
+ return error(_("cannot fixup root commit"));
+ flags |= CREATE_ROOT_COMMIT;
+ unborn = 1;
+ } else if (unborn)
oidcpy(&head, the_hash_algo->empty_tree);
- if (index_differs_from(unborn ? EMPTY_TREE_SHA1_HEX : "HEAD",
+ if (index_differs_from(unborn ? empty_tree_oid_hex() : "HEAD",
NULL, 0))
return error_dirty_index(opts);
}
@@ -1604,7 +1763,7 @@ static int do_pick_commit(enum todo_command command, struct commit *commit,
}
}
- if (opts->signoff)
+ if (opts->signoff && !is_fixup(command))
append_signoff(&msgbuf, 0, 0);
if (is_rebase_i(opts) && write_author_script(msg.message) < 0)
@@ -1675,6 +1834,9 @@ fast_forward_edit:
if (!res && final_fixup) {
unlink(rebase_path_fixup_msg());
unlink(rebase_path_squash_msg());
+ unlink(rebase_path_current_fixups());
+ strbuf_reset(&opts->current_fixups);
+ opts->current_fixup_count = 0;
}
leave:
@@ -1722,9 +1884,14 @@ static int read_and_refresh_cache(struct replay_opts *opts)
return 0;
}
+enum todo_item_flags {
+ TODO_EDIT_MERGE_MSG = 1
+};
+
struct todo_item {
enum todo_command command;
struct commit *commit;
+ unsigned int flags;
const char *arg;
int arg_len;
size_t offset_in_buf;
@@ -1759,6 +1926,8 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
char *end_of_object_name;
int i, saved, status, padding;
+ item->flags = 0;
+
/* left-trim */
bol += strspn(bol, " \t");
@@ -1800,13 +1969,29 @@ static int parse_insn_line(struct todo_item *item, const char *bol, char *eol)
return error(_("missing arguments for %s"),
command_to_string(item->command));
- if (item->command == TODO_EXEC) {
+ if (item->command == TODO_EXEC || item->command == TODO_LABEL ||
+ item->command == TODO_RESET) {
item->commit = NULL;
item->arg = bol;
item->arg_len = (int)(eol - bol);
return 0;
}
+ if (item->command == TODO_MERGE) {
+ if (skip_prefix(bol, "-C", &bol))
+ bol += strspn(bol, " \t");
+ else if (skip_prefix(bol, "-c", &bol)) {
+ bol += strspn(bol, " \t");
+ item->flags |= TODO_EDIT_MERGE_MSG;
+ } else {
+ item->flags |= TODO_EDIT_MERGE_MSG;
+ item->commit = NULL;
+ item->arg = bol;
+ item->arg_len = (int)(eol - bol);
+ return 0;
+ }
+ }
+
end_of_object_name = (char *) bol + strcspn(bol, " \t\n");
saved = *end_of_object_name;
*end_of_object_name = '\0';
@@ -1868,6 +2053,23 @@ static int count_commands(struct todo_list *todo_list)
return count;
}
+static int get_item_line_offset(struct todo_list *todo_list, int index)
+{
+ return index < todo_list->nr ?
+ todo_list->items[index].offset_in_buf : todo_list->buf.len;
+}
+
+static const char *get_item_line(struct todo_list *todo_list, int index)
+{
+ return todo_list->buf.buf + get_item_line_offset(todo_list, index);
+}
+
+static int get_item_line_length(struct todo_list *todo_list, int index)
+{
+ return get_item_line_offset(todo_list, index + 1)
+ - get_item_line_offset(todo_list, index);
+}
+
static ssize_t strbuf_read_file_or_whine(struct strbuf *sb, const char *path)
{
int fd;
@@ -2043,9 +2245,30 @@ static int read_populate_opts(struct replay_opts *opts)
if (file_exists(rebase_path_verbose()))
opts->verbose = 1;
+ if (file_exists(rebase_path_signoff())) {
+ opts->allow_ff = 0;
+ opts->signoff = 1;
+ }
+
read_strategy_opts(opts, &buf);
strbuf_release(&buf);
+ if (read_oneliner(&opts->current_fixups,
+ rebase_path_current_fixups(), 1)) {
+ const char *p = opts->current_fixups.buf;
+ opts->current_fixup_count = 1;
+ while ((p = strchr(p, '\n'))) {
+ opts->current_fixup_count++;
+ p++;
+ }
+ }
+
+ if (read_oneliner(&buf, rebase_path_squash_onto(), 0)) {
+ if (get_oid_hex(buf.buf, &opts->squash_onto) < 0)
+ return error(_("unusable squash-onto"));
+ opts->have_squash_onto = 1;
+ }
+
return 0;
}
@@ -2119,9 +2342,9 @@ static int save_head(const char *head)
written = write_in_full(fd, buf.buf, buf.len);
strbuf_release(&buf);
if (written < 0) {
+ error_errno(_("could not write to '%s'"), git_path_head_file());
rollback_lock_file(&head_lock);
- return error_errno(_("could not write to '%s'"),
- git_path_head_file());
+ return -1;
}
if (commit_lock_file(&head_lock) < 0)
return error(_("failed to finalize '%s'"), git_path_head_file());
@@ -2242,29 +2465,27 @@ static int save_todo(struct todo_list *todo_list, struct replay_opts *opts)
fd = hold_lock_file_for_update(&todo_lock, todo_path, 0);
if (fd < 0)
return error_errno(_("could not lock '%s'"), todo_path);
- offset = next < todo_list->nr ?
- todo_list->items[next].offset_in_buf : todo_list->buf.len;
+ offset = get_item_line_offset(todo_list, next);
if (write_in_full(fd, todo_list->buf.buf + offset,
todo_list->buf.len - offset) < 0)
return error_errno(_("could not write to '%s'"), todo_path);
if (commit_lock_file(&todo_lock) < 0)
return error(_("failed to finalize '%s'"), todo_path);
- if (is_rebase_i(opts)) {
- const char *done_path = rebase_path_done();
- int fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
- int prev_offset = !next ? 0 :
- todo_list->items[next - 1].offset_in_buf;
+ if (is_rebase_i(opts) && next > 0) {
+ const char *done = rebase_path_done();
+ int fd = open(done, O_CREAT | O_WRONLY | O_APPEND, 0666);
+ int ret = 0;
- if (fd >= 0 && offset > prev_offset &&
- write_in_full(fd, todo_list->buf.buf + prev_offset,
- offset - prev_offset) < 0) {
- close(fd);
- return error_errno(_("could not write to '%s'"),
- done_path);
- }
- if (fd >= 0)
- close(fd);
+ if (fd < 0)
+ return 0;
+ if (write_in_full(fd, get_item_line(todo_list, next - 1),
+ get_item_line_length(todo_list, next - 1))
+ < 0)
+ ret = error_errno(_("could not write to '%s'"), done);
+ if (close(fd) < 0)
+ ret = error_errno(_("failed to finalize '%s'"), done);
+ return ret;
}
return 0;
}
@@ -2392,10 +2613,9 @@ static int error_with_patch(struct commit *commit,
static int error_failed_squash(struct commit *commit,
struct replay_opts *opts, int subject_len, const char *subject)
{
- if (rename(rebase_path_squash_msg(), rebase_path_message()))
- return error(_("could not rename '%s' to '%s'"),
+ if (copy_file(rebase_path_message(), rebase_path_squash_msg(), 0666))
+ return error(_("could not copy '%s' to '%s'"),
rebase_path_squash_msg(), rebase_path_message());
- unlink(rebase_path_fixup_msg());
unlink(git_path_merge_msg());
if (copy_file(git_path_merge_msg(), rebase_path_message(), 0666))
return error(_("could not copy '%s' to '%s'"),
@@ -2448,6 +2668,377 @@ static int do_exec(const char *command_line)
return status;
}
+static int safe_append(const char *filename, const char *fmt, ...)
+{
+ va_list ap;
+ struct lock_file lock = LOCK_INIT;
+ int fd = hold_lock_file_for_update(&lock, filename,
+ LOCK_REPORT_ON_ERROR);
+ struct strbuf buf = STRBUF_INIT;
+
+ if (fd < 0)
+ return -1;
+
+ if (strbuf_read_file(&buf, filename, 0) < 0 && errno != ENOENT) {
+ error_errno(_("could not read '%s'"), filename);
+ rollback_lock_file(&lock);
+ return -1;
+ }
+ strbuf_complete(&buf, '\n');
+ va_start(ap, fmt);
+ strbuf_vaddf(&buf, fmt, ap);
+ va_end(ap);
+
+ if (write_in_full(fd, buf.buf, buf.len) < 0) {
+ error_errno(_("could not write to '%s'"), filename);
+ strbuf_release(&buf);
+ rollback_lock_file(&lock);
+ return -1;
+ }
+ if (commit_lock_file(&lock) < 0) {
+ strbuf_release(&buf);
+ rollback_lock_file(&lock);
+ return error(_("failed to finalize '%s'"), filename);
+ }
+
+ strbuf_release(&buf);
+ return 0;
+}
+
+static int do_label(const char *name, int len)
+{
+ struct ref_store *refs = get_main_ref_store(the_repository);
+ struct ref_transaction *transaction;
+ struct strbuf ref_name = STRBUF_INIT, err = STRBUF_INIT;
+ struct strbuf msg = STRBUF_INIT;
+ int ret = 0;
+ struct object_id head_oid;
+
+ if (len == 1 && *name == '#')
+ return error("Illegal label name: '%.*s'", len, name);
+
+ strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
+ strbuf_addf(&msg, "rebase -i (label) '%.*s'", len, name);
+
+ transaction = ref_store_transaction_begin(refs, &err);
+ if (!transaction) {
+ error("%s", err.buf);
+ ret = -1;
+ } else if (get_oid("HEAD", &head_oid)) {
+ error(_("could not read HEAD"));
+ ret = -1;
+ } else if (ref_transaction_update(transaction, ref_name.buf, &head_oid,
+ NULL, 0, msg.buf, &err) < 0 ||
+ ref_transaction_commit(transaction, &err)) {
+ error("%s", err.buf);
+ ret = -1;
+ }
+ ref_transaction_free(transaction);
+ strbuf_release(&err);
+ strbuf_release(&msg);
+
+ if (!ret)
+ ret = safe_append(rebase_path_refs_to_delete(),
+ "%s\n", ref_name.buf);
+ strbuf_release(&ref_name);
+
+ return ret;
+}
+
+static const char *reflog_message(struct replay_opts *opts,
+ const char *sub_action, const char *fmt, ...);
+
+static int do_reset(const char *name, int len, struct replay_opts *opts)
+{
+ struct strbuf ref_name = STRBUF_INIT;
+ struct object_id oid;
+ struct lock_file lock = LOCK_INIT;
+ struct tree_desc desc;
+ struct tree *tree;
+ struct unpack_trees_options unpack_tree_opts;
+ int ret = 0, i;
+
+ if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0)
+ return -1;
+
+ if (len == 10 && !strncmp("[new root]", name, len)) {
+ if (!opts->have_squash_onto) {
+ const char *hex;
+ if (commit_tree("", 0, the_hash_algo->empty_tree,
+ NULL, &opts->squash_onto,
+ NULL, NULL))
+ return error(_("writing fake root commit"));
+ opts->have_squash_onto = 1;
+ hex = oid_to_hex(&opts->squash_onto);
+ if (write_message(hex, strlen(hex),
+ rebase_path_squash_onto(), 0))
+ return error(_("writing squash-onto"));
+ }
+ oidcpy(&oid, &opts->squash_onto);
+ } else {
+ /* Determine the length of the label */
+ for (i = 0; i < len; i++)
+ if (isspace(name[i]))
+ len = i;
+
+ strbuf_addf(&ref_name, "refs/rewritten/%.*s", len, name);
+ if (get_oid(ref_name.buf, &oid) &&
+ get_oid(ref_name.buf + strlen("refs/rewritten/"), &oid)) {
+ error(_("could not read '%s'"), ref_name.buf);
+ rollback_lock_file(&lock);
+ strbuf_release(&ref_name);
+ return -1;
+ }
+ }
+
+ memset(&unpack_tree_opts, 0, sizeof(unpack_tree_opts));
+ setup_unpack_trees_porcelain(&unpack_tree_opts, "reset");
+ unpack_tree_opts.head_idx = 1;
+ unpack_tree_opts.src_index = &the_index;
+ unpack_tree_opts.dst_index = &the_index;
+ unpack_tree_opts.fn = oneway_merge;
+ unpack_tree_opts.merge = 1;
+ unpack_tree_opts.update = 1;
+
+ if (read_cache_unmerged()) {
+ rollback_lock_file(&lock);
+ strbuf_release(&ref_name);
+ return error_resolve_conflict(_(action_name(opts)));
+ }
+
+ if (!fill_tree_descriptor(&desc, &oid)) {
+ error(_("failed to find tree of %s"), oid_to_hex(&oid));
+ rollback_lock_file(&lock);
+ free((void *)desc.buffer);
+ strbuf_release(&ref_name);
+ return -1;
+ }
+
+ if (unpack_trees(1, &desc, &unpack_tree_opts)) {
+ rollback_lock_file(&lock);
+ free((void *)desc.buffer);
+ strbuf_release(&ref_name);
+ return -1;
+ }
+
+ tree = parse_tree_indirect(&oid);
+ prime_cache_tree(&the_index, tree);
+
+ if (write_locked_index(&the_index, &lock, COMMIT_LOCK) < 0)
+ ret = error(_("could not write index"));
+ free((void *)desc.buffer);
+
+ if (!ret)
+ ret = update_ref(reflog_message(opts, "reset", "'%.*s'",
+ len, name), "HEAD", &oid,
+ NULL, 0, UPDATE_REFS_MSG_ON_ERR);
+
+ strbuf_release(&ref_name);
+ return ret;
+}
+
+static int do_merge(struct commit *commit, const char *arg, int arg_len,
+ int flags, struct replay_opts *opts)
+{
+ int run_commit_flags = (flags & TODO_EDIT_MERGE_MSG) ?
+ EDIT_MSG | VERIFY_MSG : 0;
+ struct strbuf ref_name = STRBUF_INIT;
+ struct commit *head_commit, *merge_commit, *i;
+ struct commit_list *bases, *j, *reversed = NULL;
+ struct merge_options o;
+ int merge_arg_len, oneline_offset, can_fast_forward, ret;
+ static struct lock_file lock;
+ const char *p;
+
+ if (hold_locked_index(&lock, LOCK_REPORT_ON_ERROR) < 0) {
+ ret = -1;
+ goto leave_merge;
+ }
+
+ head_commit = lookup_commit_reference_by_name("HEAD");
+ if (!head_commit) {
+ ret = error(_("cannot merge without a current revision"));
+ goto leave_merge;
+ }
+
+ oneline_offset = arg_len;
+ merge_arg_len = strcspn(arg, " \t\n");
+ p = arg + merge_arg_len;
+ p += strspn(p, " \t\n");
+ if (*p == '#' && (!p[1] || isspace(p[1]))) {
+ p += 1 + strspn(p + 1, " \t\n");
+ oneline_offset = p - arg;
+ } else if (p - arg < arg_len)
+ BUG("octopus merges are not supported yet: '%s'", p);
+
+ strbuf_addf(&ref_name, "refs/rewritten/%.*s", merge_arg_len, arg);
+ merge_commit = lookup_commit_reference_by_name(ref_name.buf);
+ if (!merge_commit) {
+ /* fall back to non-rewritten ref or commit */
+ strbuf_splice(&ref_name, 0, strlen("refs/rewritten/"), "", 0);
+ merge_commit = lookup_commit_reference_by_name(ref_name.buf);
+ }
+
+ if (!merge_commit) {
+ ret = error(_("could not resolve '%s'"), ref_name.buf);
+ goto leave_merge;
+ }
+
+ if (opts->have_squash_onto &&
+ !oidcmp(&head_commit->object.oid, &opts->squash_onto)) {
+ /*
+ * When the user tells us to "merge" something into a
+ * "[new root]", let's simply fast-forward to the merge head.
+ */
+ rollback_lock_file(&lock);
+ ret = fast_forward_to(&merge_commit->object.oid,
+ &head_commit->object.oid, 0, opts);
+ goto leave_merge;
+ }
+
+ if (commit) {
+ const char *message = get_commit_buffer(commit, NULL);
+ const char *body;
+ int len;
+
+ if (!message) {
+ ret = error(_("could not get commit message of '%s'"),
+ oid_to_hex(&commit->object.oid));
+ goto leave_merge;
+ }
+ write_author_script(message);
+ find_commit_subject(message, &body);
+ len = strlen(body);
+ ret = write_message(body, len, git_path_merge_msg(), 0);
+ unuse_commit_buffer(commit, message);
+ if (ret) {
+ error_errno(_("could not write '%s'"),
+ git_path_merge_msg());
+ goto leave_merge;
+ }
+ } else {
+ struct strbuf buf = STRBUF_INIT;
+ int len;
+
+ strbuf_addf(&buf, "author %s", git_author_info(0));
+ write_author_script(buf.buf);
+ strbuf_reset(&buf);
+
+ if (oneline_offset < arg_len) {
+ p = arg + oneline_offset;
+ len = arg_len - oneline_offset;
+ } else {
+ strbuf_addf(&buf, "Merge branch '%.*s'",
+ merge_arg_len, arg);
+ p = buf.buf;
+ len = buf.len;
+ }
+
+ ret = write_message(p, len, git_path_merge_msg(), 0);
+ strbuf_release(&buf);
+ if (ret) {
+ error_errno(_("could not write '%s'"),
+ git_path_merge_msg());
+ goto leave_merge;
+ }
+ }
+
+ /*
+ * If HEAD is not identical to the first parent of the original merge
+ * commit, we cannot fast-forward.
+ */
+ can_fast_forward = opts->allow_ff && commit && commit->parents &&
+ !oidcmp(&commit->parents->item->object.oid,
+ &head_commit->object.oid);
+
+ /*
+ * If the merge head is different from the original one, we cannot
+ * fast-forward.
+ */
+ if (can_fast_forward) {
+ struct commit_list *second_parent = commit->parents->next;
+
+ if (second_parent && !second_parent->next &&
+ oidcmp(&merge_commit->object.oid,
+ &second_parent->item->object.oid))
+ can_fast_forward = 0;
+ }
+
+ if (can_fast_forward && commit->parents->next &&
+ !commit->parents->next->next &&
+ !oidcmp(&commit->parents->next->item->object.oid,
+ &merge_commit->object.oid)) {
+ rollback_lock_file(&lock);
+ ret = fast_forward_to(&commit->object.oid,
+ &head_commit->object.oid, 0, opts);
+ goto leave_merge;
+ }
+
+ write_message(oid_to_hex(&merge_commit->object.oid), GIT_SHA1_HEXSZ,
+ git_path_merge_head(), 0);
+ write_message("no-ff", 5, git_path_merge_mode(), 0);
+
+ bases = get_merge_bases(head_commit, merge_commit);
+ if (bases && !oidcmp(&merge_commit->object.oid,
+ &bases->item->object.oid)) {
+ ret = 0;
+ /* skip merging an ancestor of HEAD */
+ goto leave_merge;
+ }
+
+ for (j = bases; j; j = j->next)
+ commit_list_insert(j->item, &reversed);
+ free_commit_list(bases);
+
+ read_cache();
+ init_merge_options(&o);
+ o.branch1 = "HEAD";
+ o.branch2 = ref_name.buf;
+ o.buffer_output = 2;
+
+ ret = merge_recursive(&o, head_commit, merge_commit, reversed, &i);
+ if (ret <= 0)
+ fputs(o.obuf.buf, stdout);
+ strbuf_release(&o.obuf);
+ if (ret < 0) {
+ error(_("could not even attempt to merge '%.*s'"),
+ merge_arg_len, arg);
+ goto leave_merge;
+ }
+ /*
+ * The return value of merge_recursive() is 1 on clean, and 0 on
+ * unclean merge.
+ *
+ * Let's reverse that, so that do_merge() returns 0 upon success and
+ * 1 upon failed merge (keeping the return value -1 for the cases where
+ * we will want to reschedule the `merge` command).
+ */
+ ret = !ret;
+
+ if (active_cache_changed &&
+ write_locked_index(&the_index, &lock, COMMIT_LOCK)) {
+ ret = error(_("merge: Unable to write new index file"));
+ goto leave_merge;
+ }
+
+ rollback_lock_file(&lock);
+ if (ret)
+ rerere(opts->allow_rerere_auto);
+ else
+ /*
+ * In case of problems, we now want to return a positive
+ * value (a negative one would indicate that the `merge`
+ * command needs to be rescheduled).
+ */
+ ret = !!run_git_commit(git_path_merge_msg(), opts,
+ run_commit_flags);
+
+leave_merge:
+ strbuf_release(&ref_name);
+ rollback_lock_file(&lock);
+ return ret;
+}
+
static int is_final_fixup(struct todo_list *todo_list)
{
int i = todo_list->current;
@@ -2538,9 +3129,20 @@ static const char *reflog_message(struct replay_opts *opts,
return buf.buf;
}
+static const char rescheduled_advice[] =
+N_("Could not execute the todo command\n"
+"\n"
+" %.*s"
+"\n"
+"It has been rescheduled; To edit the command before continuing, please\n"
+"edit the todo list first:\n"
+"\n"
+" git rebase --edit-todo\n"
+" git rebase --continue\n");
+
static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
{
- int res = 0;
+ int res = 0, reschedule = 0;
setenv(GIT_REFLOG_ACTION, action_name(opts), 0);
if (opts->allow_ff)
@@ -2583,6 +3185,11 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
opts, is_final_fixup(todo_list));
if (is_rebase_i(opts) && res < 0) {
/* Reschedule */
+ advise(_(rescheduled_advice),
+ get_item_line_length(todo_list,
+ todo_list->current),
+ get_item_line(todo_list,
+ todo_list->current));
todo_list->current--;
if (save_todo(todo_list, opts))
return -1;
@@ -2606,7 +3213,7 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
intend_to_amend();
return error_failed_squash(item->commit, opts,
item->arg_len, item->arg);
- } else if (res && is_rebase_i(opts))
+ } else if (res && is_rebase_i(opts) && item->commit)
return res | error_with_patch(item->commit,
item->arg, item->arg_len, opts, res,
item->command == TODO_REWORD);
@@ -2632,9 +3239,44 @@ static int pick_commits(struct todo_list *todo_list, struct replay_opts *opts)
/* `current` will be incremented below */
todo_list->current = -1;
}
+ } else if (item->command == TODO_LABEL) {
+ if ((res = do_label(item->arg, item->arg_len)))
+ reschedule = 1;
+ } else if (item->command == TODO_RESET) {
+ if ((res = do_reset(item->arg, item->arg_len, opts)))
+ reschedule = 1;
+ } else if (item->command == TODO_MERGE) {
+ if ((res = do_merge(item->commit,
+ item->arg, item->arg_len,
+ item->flags, opts)) < 0)
+ reschedule = 1;
+ else if (item->commit)
+ record_in_rewritten(&item->commit->object.oid,
+ peek_command(todo_list, 1));
+ if (res > 0)
+ /* failed with merge conflicts */
+ return error_with_patch(item->commit,
+ item->arg,
+ item->arg_len, opts,
+ res, 0);
} else if (!is_noop(item->command))
return error(_("unknown command %d"), item->command);
+ if (reschedule) {
+ advise(_(rescheduled_advice),
+ get_item_line_length(todo_list,
+ todo_list->current),
+ get_item_line(todo_list, todo_list->current));
+ todo_list->current--;
+ if (save_todo(todo_list, opts))
+ return -1;
+ if (item->commit)
+ return error_with_patch(item->commit,
+ item->arg,
+ item->arg_len, opts,
+ res, 0);
+ }
+
todo_list->current++;
if (res)
return res;
@@ -2761,19 +3403,16 @@ static int continue_single_pick(void)
return run_command_v_opt(argv, RUN_GIT_CMD);
}
-static int commit_staged_changes(struct replay_opts *opts)
+static int commit_staged_changes(struct replay_opts *opts,
+ struct todo_list *todo_list)
{
unsigned int flags = ALLOW_EMPTY | EDIT_MSG;
+ unsigned int final_fixup = 0, is_clean;
if (has_unstaged_changes(1))
return error(_("cannot rebase: You have unstaged changes."));
- if (!has_uncommitted_changes(0)) {
- const char *cherry_pick_head = git_path_cherry_pick_head();
- if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
- return error(_("could not remove CHERRY_PICK_HEAD"));
- return 0;
- }
+ is_clean = !has_uncommitted_changes(0);
if (file_exists(rebase_path_amend())) {
struct strbuf rev = STRBUF_INIT;
@@ -2786,19 +3425,107 @@ static int commit_staged_changes(struct replay_opts *opts)
if (get_oid_hex(rev.buf, &to_amend))
return error(_("invalid contents: '%s'"),
rebase_path_amend());
- if (oidcmp(&head, &to_amend))
+ if (!is_clean && oidcmp(&head, &to_amend))
return error(_("\nYou have uncommitted changes in your "
"working tree. Please, commit them\n"
"first and then run 'git rebase "
"--continue' again."));
+ /*
+ * When skipping a failed fixup/squash, we need to edit the
+ * commit message, the current fixup list and count, and if it
+ * was the last fixup/squash in the chain, we need to clean up
+ * the commit message and if there was a squash, let the user
+ * edit it.
+ */
+ if (is_clean && !oidcmp(&head, &to_amend) &&
+ opts->current_fixup_count > 0 &&
+ file_exists(rebase_path_stopped_sha())) {
+ const char *p = opts->current_fixups.buf;
+ int len = opts->current_fixups.len;
+
+ opts->current_fixup_count--;
+ if (!len)
+ BUG("Incorrect current_fixups:\n%s", p);
+ while (len && p[len - 1] != '\n')
+ len--;
+ strbuf_setlen(&opts->current_fixups, len);
+ if (write_message(p, len, rebase_path_current_fixups(),
+ 0) < 0)
+ return error(_("could not write file: '%s'"),
+ rebase_path_current_fixups());
+
+ /*
+ * If a fixup/squash in a fixup/squash chain failed, the
+ * commit message is already correct, no need to commit
+ * it again.
+ *
+ * Only if it is the final command in the fixup/squash
+ * chain, and only if the chain is longer than a single
+ * fixup/squash command (which was just skipped), do we
+ * actually need to re-commit with a cleaned up commit
+ * message.
+ */
+ if (opts->current_fixup_count > 0 &&
+ !is_fixup(peek_command(todo_list, 0))) {
+ final_fixup = 1;
+ /*
+ * If there was not a single "squash" in the
+ * chain, we only need to clean up the commit
+ * message, no need to bother the user with
+ * opening the commit message in the editor.
+ */
+ if (!starts_with(p, "squash ") &&
+ !strstr(p, "\nsquash "))
+ flags = (flags & ~EDIT_MSG) | CLEANUP_MSG;
+ } else if (is_fixup(peek_command(todo_list, 0))) {
+ /*
+ * We need to update the squash message to skip
+ * the latest commit message.
+ */
+ struct commit *commit;
+ const char *path = rebase_path_squash_msg();
+
+ if (parse_head(&commit) ||
+ !(p = get_commit_buffer(commit, NULL)) ||
+ write_message(p, strlen(p), path, 0)) {
+ unuse_commit_buffer(commit, p);
+ return error(_("could not write file: "
+ "'%s'"), path);
+ }
+ unuse_commit_buffer(commit, p);
+ }
+ }
strbuf_release(&rev);
flags |= AMEND_MSG;
}
- if (run_git_commit(rebase_path_message(), opts, flags))
+ if (is_clean) {
+ const char *cherry_pick_head = git_path_cherry_pick_head();
+
+ if (file_exists(cherry_pick_head) && unlink(cherry_pick_head))
+ return error(_("could not remove CHERRY_PICK_HEAD"));
+ if (!final_fixup)
+ return 0;
+ }
+
+ if (run_git_commit(final_fixup ? NULL : rebase_path_message(),
+ opts, flags))
return error(_("could not commit staged changes."));
unlink(rebase_path_amend());
+ if (final_fixup) {
+ unlink(rebase_path_fixup_msg());
+ unlink(rebase_path_squash_msg());
+ }
+ if (opts->current_fixup_count > 0) {
+ /*
+ * Whether final fixup or not, we just cleaned up the commit
+ * message...
+ */
+ unlink(rebase_path_current_fixups());
+ strbuf_reset(&opts->current_fixups);
+ opts->current_fixup_count = 0;
+ }
return 0;
}
@@ -2810,14 +3537,16 @@ int sequencer_continue(struct replay_opts *opts)
if (read_and_refresh_cache(opts))
return -1;
+ if (read_populate_opts(opts))
+ return -1;
if (is_rebase_i(opts)) {
- if (commit_staged_changes(opts))
+ if ((res = read_populate_todo(&todo_list, opts)))
+ goto release_todo_list;
+ if (commit_staged_changes(opts, &todo_list))
return -1;
} else if (!file_exists(get_todo_path(opts)))
return continue_single_pick();
- if (read_populate_opts(opts))
- return -1;
- if ((res = read_populate_todo(&todo_list, opts)))
+ else if ((res = read_populate_todo(&todo_list, opts)))
goto release_todo_list;
if (!is_rebase_i(opts)) {
@@ -2876,7 +3605,8 @@ int sequencer_pick_revisions(struct replay_opts *opts)
if (!get_oid(name, &oid)) {
if (!lookup_commit_reference_gently(&oid, 1)) {
- enum object_type type = oid_object_info(&oid,
+ enum object_type type = oid_object_info(the_repository,
+ &oid,
NULL);
return error(_("%s: can't cherry-pick a %s"),
name, type_name(type));
@@ -2987,6 +3717,348 @@ void append_signoff(struct strbuf *msgbuf, int ignore_footer, unsigned flag)
strbuf_release(&sob);
}
+struct labels_entry {
+ struct hashmap_entry entry;
+ char label[FLEX_ARRAY];
+};
+
+static int labels_cmp(const void *fndata, const struct labels_entry *a,
+ const struct labels_entry *b, const void *key)
+{
+ return key ? strcmp(a->label, key) : strcmp(a->label, b->label);
+}
+
+struct string_entry {
+ struct oidmap_entry entry;
+ char string[FLEX_ARRAY];
+};
+
+struct label_state {
+ struct oidmap commit2label;
+ struct hashmap labels;
+ struct strbuf buf;
+};
+
+static const char *label_oid(struct object_id *oid, const char *label,
+ struct label_state *state)
+{
+ struct labels_entry *labels_entry;
+ struct string_entry *string_entry;
+ struct object_id dummy;
+ size_t len;
+ int i;
+
+ string_entry = oidmap_get(&state->commit2label, oid);
+ if (string_entry)
+ return string_entry->string;
+
+ /*
+ * For "uninteresting" commits, i.e. commits that are not to be
+ * rebased, and which can therefore not be labeled, we use a unique
+ * abbreviation of the commit name. This is slightly more complicated
+ * than calling find_unique_abbrev() because we also need to make
+ * sure that the abbreviation does not conflict with any other
+ * label.
+ *
+ * We disallow "interesting" commits to be labeled by a string that
+ * is a valid full-length hash, to ensure that we always can find an
+ * abbreviation for any uninteresting commit's names that does not
+ * clash with any other label.
+ */
+ if (!label) {
+ char *p;
+
+ strbuf_reset(&state->buf);
+ strbuf_grow(&state->buf, GIT_SHA1_HEXSZ);
+ label = p = state->buf.buf;
+
+ find_unique_abbrev_r(p, oid, default_abbrev);
+
+ /*
+ * We may need to extend the abbreviated hash so that there is
+ * no conflicting label.
+ */
+ if (hashmap_get_from_hash(&state->labels, strihash(p), p)) {
+ size_t i = strlen(p) + 1;
+
+ oid_to_hex_r(p, oid);
+ for (; i < GIT_SHA1_HEXSZ; i++) {
+ char save = p[i];
+ p[i] = '\0';
+ if (!hashmap_get_from_hash(&state->labels,
+ strihash(p), p))
+ break;
+ p[i] = save;
+ }
+ }
+ } else if (((len = strlen(label)) == GIT_SHA1_RAWSZ &&
+ !get_oid_hex(label, &dummy)) ||
+ (len == 1 && *label == '#') ||
+ hashmap_get_from_hash(&state->labels,
+ strihash(label), label)) {
+ /*
+ * If the label already exists, or if the label is a valid full
+ * OID, or the label is a '#' (which we use as a separator
+ * between merge heads and oneline), we append a dash and a
+ * number to make it unique.
+ */
+ struct strbuf *buf = &state->buf;
+
+ strbuf_reset(buf);
+ strbuf_add(buf, label, len);
+
+ for (i = 2; ; i++) {
+ strbuf_setlen(buf, len);
+ strbuf_addf(buf, "-%d", i);
+ if (!hashmap_get_from_hash(&state->labels,
+ strihash(buf->buf),
+ buf->buf))
+ break;
+ }
+
+ label = buf->buf;
+ }
+
+ FLEX_ALLOC_STR(labels_entry, label, label);
+ hashmap_entry_init(labels_entry, strihash(label));
+ hashmap_add(&state->labels, labels_entry);
+
+ FLEX_ALLOC_STR(string_entry, string, label);
+ oidcpy(&string_entry->entry.oid, oid);
+ oidmap_put(&state->commit2label, string_entry);
+
+ return string_entry->string;
+}
+
+static int make_script_with_merges(struct pretty_print_context *pp,
+ struct rev_info *revs, FILE *out,
+ unsigned flags)
+{
+ int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
+ int rebase_cousins = flags & TODO_LIST_REBASE_COUSINS;
+ struct strbuf buf = STRBUF_INIT, oneline = STRBUF_INIT;
+ struct strbuf label = STRBUF_INIT;
+ struct commit_list *commits = NULL, **tail = &commits, *iter;
+ struct commit_list *tips = NULL, **tips_tail = &tips;
+ struct commit *commit;
+ struct oidmap commit2todo = OIDMAP_INIT;
+ struct string_entry *entry;
+ struct oidset interesting = OIDSET_INIT, child_seen = OIDSET_INIT,
+ shown = OIDSET_INIT;
+ struct label_state state = { OIDMAP_INIT, { NULL }, STRBUF_INIT };
+
+ int abbr = flags & TODO_LIST_ABBREVIATE_CMDS;
+ const char *cmd_pick = abbr ? "p" : "pick",
+ *cmd_label = abbr ? "l" : "label",
+ *cmd_reset = abbr ? "t" : "reset",
+ *cmd_merge = abbr ? "m" : "merge";
+
+ oidmap_init(&commit2todo, 0);
+ oidmap_init(&state.commit2label, 0);
+ hashmap_init(&state.labels, (hashmap_cmp_fn) labels_cmp, NULL, 0);
+ strbuf_init(&state.buf, 32);
+
+ if (revs->cmdline.nr && (revs->cmdline.rev[0].flags & BOTTOM)) {
+ struct object_id *oid = &revs->cmdline.rev[0].item->oid;
+ FLEX_ALLOC_STR(entry, string, "onto");
+ oidcpy(&entry->entry.oid, oid);
+ oidmap_put(&state.commit2label, entry);
+ }
+
+ /*
+ * First phase:
+ * - get onelines for all commits
+ * - gather all branch tips (i.e. 2nd or later parents of merges)
+ * - label all branch tips
+ */
+ while ((commit = get_revision(revs))) {
+ struct commit_list *to_merge;
+ int is_octopus;
+ const char *p1, *p2;
+ struct object_id *oid;
+ int is_empty;
+
+ tail = &commit_list_insert(commit, tail)->next;
+ oidset_insert(&interesting, &commit->object.oid);
+
+ is_empty = is_original_commit_empty(commit);
+ if (!is_empty && (commit->object.flags & PATCHSAME))
+ continue;
+
+ strbuf_reset(&oneline);
+ pretty_print_commit(pp, commit, &oneline);
+
+ to_merge = commit->parents ? commit->parents->next : NULL;
+ if (!to_merge) {
+ /* non-merge commit: easy case */
+ strbuf_reset(&buf);
+ if (!keep_empty && is_empty)
+ strbuf_addf(&buf, "%c ", comment_line_char);
+ strbuf_addf(&buf, "%s %s %s", cmd_pick,
+ oid_to_hex(&commit->object.oid),
+ oneline.buf);
+
+ FLEX_ALLOC_STR(entry, string, buf.buf);
+ oidcpy(&entry->entry.oid, &commit->object.oid);
+ oidmap_put(&commit2todo, entry);
+
+ continue;
+ }
+
+ is_octopus = to_merge && to_merge->next;
+
+ if (is_octopus)
+ BUG("Octopus merges not yet supported");
+
+ /* Create a label */
+ strbuf_reset(&label);
+ if (skip_prefix(oneline.buf, "Merge ", &p1) &&
+ (p1 = strchr(p1, '\'')) &&
+ (p2 = strchr(++p1, '\'')))
+ strbuf_add(&label, p1, p2 - p1);
+ else if (skip_prefix(oneline.buf, "Merge pull request ",
+ &p1) &&
+ (p1 = strstr(p1, " from ")))
+ strbuf_addstr(&label, p1 + strlen(" from "));
+ else
+ strbuf_addbuf(&label, &oneline);
+
+ for (p1 = label.buf; *p1; p1++)
+ if (isspace(*p1))
+ *(char *)p1 = '-';
+
+ strbuf_reset(&buf);
+ strbuf_addf(&buf, "%s -C %s",
+ cmd_merge, oid_to_hex(&commit->object.oid));
+
+ /* label the tip of merged branch */
+ oid = &to_merge->item->object.oid;
+ strbuf_addch(&buf, ' ');
+
+ if (!oidset_contains(&interesting, oid))
+ strbuf_addstr(&buf, label_oid(oid, NULL, &state));
+ else {
+ tips_tail = &commit_list_insert(to_merge->item,
+ tips_tail)->next;
+
+ strbuf_addstr(&buf, label_oid(oid, label.buf, &state));
+ }
+ strbuf_addf(&buf, " # %s", oneline.buf);
+
+ FLEX_ALLOC_STR(entry, string, buf.buf);
+ oidcpy(&entry->entry.oid, &commit->object.oid);
+ oidmap_put(&commit2todo, entry);
+ }
+
+ /*
+ * Second phase:
+ * - label branch points
+ * - add HEAD to the branch tips
+ */
+ for (iter = commits; iter; iter = iter->next) {
+ struct commit_list *parent = iter->item->parents;
+ for (; parent; parent = parent->next) {
+ struct object_id *oid = &parent->item->object.oid;
+ if (!oidset_contains(&interesting, oid))
+ continue;
+ if (!oidset_contains(&child_seen, oid))
+ oidset_insert(&child_seen, oid);
+ else
+ label_oid(oid, "branch-point", &state);
+ }
+
+ /* Add HEAD as implict "tip of branch" */
+ if (!iter->next)
+ tips_tail = &commit_list_insert(iter->item,
+ tips_tail)->next;
+ }
+
+ /*
+ * Third phase: output the todo list. This is a bit tricky, as we
+ * want to avoid jumping back and forth between revisions. To
+ * accomplish that goal, we walk backwards from the branch tips,
+ * gathering commits not yet shown, reversing the list on the fly,
+ * then outputting that list (labeling revisions as needed).
+ */
+ fprintf(out, "%s onto\n", cmd_label);
+ for (iter = tips; iter; iter = iter->next) {
+ struct commit_list *list = NULL, *iter2;
+
+ commit = iter->item;
+ if (oidset_contains(&shown, &commit->object.oid))
+ continue;
+ entry = oidmap_get(&state.commit2label, &commit->object.oid);
+
+ if (entry)
+ fprintf(out, "\n# Branch %s\n", entry->string);
+ else
+ fprintf(out, "\n");
+
+ while (oidset_contains(&interesting, &commit->object.oid) &&
+ !oidset_contains(&shown, &commit->object.oid)) {
+ commit_list_insert(commit, &list);
+ if (!commit->parents) {
+ commit = NULL;
+ break;
+ }
+ commit = commit->parents->item;
+ }
+
+ if (!commit)
+ fprintf(out, "%s %s\n", cmd_reset,
+ rebase_cousins ? "onto" : "[new root]");
+ else {
+ const char *to = NULL;
+
+ entry = oidmap_get(&state.commit2label,
+ &commit->object.oid);
+ if (entry)
+ to = entry->string;
+ else if (!rebase_cousins)
+ to = label_oid(&commit->object.oid, NULL,
+ &state);
+
+ if (!to || !strcmp(to, "onto"))
+ fprintf(out, "%s onto\n", cmd_reset);
+ else {
+ strbuf_reset(&oneline);
+ pretty_print_commit(pp, commit, &oneline);
+ fprintf(out, "%s %s # %s\n",
+ cmd_reset, to, oneline.buf);
+ }
+ }
+
+ for (iter2 = list; iter2; iter2 = iter2->next) {
+ struct object_id *oid = &iter2->item->object.oid;
+ entry = oidmap_get(&commit2todo, oid);
+ /* only show if not already upstream */
+ if (entry)
+ fprintf(out, "%s\n", entry->string);
+ entry = oidmap_get(&state.commit2label, oid);
+ if (entry)
+ fprintf(out, "%s %s\n",
+ cmd_label, entry->string);
+ oidset_insert(&shown, oid);
+ }
+
+ free_commit_list(list);
+ }
+
+ free_commit_list(commits);
+ free_commit_list(tips);
+
+ strbuf_release(&label);
+ strbuf_release(&oneline);
+ strbuf_release(&buf);
+
+ oidmap_free(&commit2todo, 1);
+ oidmap_free(&state.commit2label, 1);
+ hashmap_free(&state.labels, 1);
+ strbuf_release(&state.buf);
+
+ return 0;
+}
+
int sequencer_make_script(FILE *out, int argc, const char **argv,
unsigned flags)
{
@@ -2997,11 +4069,13 @@ int sequencer_make_script(FILE *out, int argc, const char **argv,
struct commit *commit;
int keep_empty = flags & TODO_LIST_KEEP_EMPTY;
const char *insn = flags & TODO_LIST_ABBREVIATE_CMDS ? "p" : "pick";
+ int rebase_merges = flags & TODO_LIST_REBASE_MERGES;
init_revisions(&revs, NULL);
revs.verbose_header = 1;
- revs.max_parents = 1;
- revs.cherry_pick = 1;
+ if (!rebase_merges)
+ revs.max_parents = 1;
+ revs.cherry_mark = 1;
revs.limited = 1;
revs.reverse = 1;
revs.right_only = 1;
@@ -3025,9 +4099,16 @@ int sequencer_make_script(FILE *out, int argc, const char **argv,
if (prepare_revision_walk(&revs) < 0)
return error(_("make_script: error preparing revisions"));
+ if (rebase_merges)
+ return make_script_with_merges(&pp, &revs, out, flags);
+
while ((commit = get_revision(&revs))) {
+ int is_empty = is_original_commit_empty(commit);
+
+ if (!is_empty && (commit->object.flags & PATCHSAME))
+ continue;
strbuf_reset(&buf);
- if (!keep_empty && is_original_commit_empty(commit))
+ if (!keep_empty && is_empty)
strbuf_addf(&buf, "%c ", comment_line_char);
strbuf_addf(&buf, "%s %s ", insn,
oid_to_hex(&commit->object.oid));
@@ -3114,8 +4195,16 @@ int transform_todos(unsigned flags)
short_commit_name(item->commit) :
oid_to_hex(&item->commit->object.oid);
+ if (item->command == TODO_MERGE) {
+ if (item->flags & TODO_EDIT_MERGE_MSG)
+ strbuf_addstr(&buf, " -c");
+ else
+ strbuf_addstr(&buf, " -C");
+ }
+
strbuf_addf(&buf, " %s", oid);
}
+
/* add all the rest */
if (!item->arg_len)
strbuf_addch(&buf, '\n');
@@ -3295,8 +4384,7 @@ int skip_unnecessary_picks(void)
oid = &item->commit->object.oid;
}
if (i > 0) {
- int offset = i < todo_list.nr ?
- todo_list.items[i].offset_in_buf : todo_list.buf.len;
+ int offset = get_item_line_offset(&todo_list, i);
const char *done_path = rebase_path_done();
fd = open(done_path, O_CREAT | O_WRONLY | O_APPEND, 0666);
@@ -3391,7 +4479,7 @@ int rearrange_squash(void)
struct subject2item_entry *entry;
next[i] = tail[i] = -1;
- if (item->command >= TODO_EXEC) {
+ if (!item->commit || item->command == TODO_DROP) {
subjects[i] = NULL;
continue;
}
@@ -3476,12 +4564,10 @@ int rearrange_squash(void)
continue;
while (cur >= 0) {
- int offset = todo_list.items[cur].offset_in_buf;
- int end_offset = cur + 1 < todo_list.nr ?
- todo_list.items[cur + 1].offset_in_buf :
- todo_list.buf.len;
- char *bol = todo_list.buf.buf + offset;
- char *eol = todo_list.buf.buf + end_offset;
+ const char *bol =
+ get_item_line(&todo_list, cur);
+ const char *eol =
+ get_item_line(&todo_list, cur + 1);
/* replace 'pick', by 'fixup' or 'squash' */
command = todo_list.items[cur].command;
diff --git a/sequencer.h b/sequencer.h
index e45b178..c5787c6 100644
--- a/sequencer.h
+++ b/sequencer.h
@@ -44,10 +44,18 @@ struct replay_opts {
char **xopts;
size_t xopts_nr, xopts_alloc;
+ /* Used by fixup/squash */
+ struct strbuf current_fixups;
+ int current_fixup_count;
+
+ /* placeholder commit for -i --root */
+ struct object_id squash_onto;
+ int have_squash_onto;
+
/* Only used by REPLAY_NONE */
struct rev_info *revs;
};
-#define REPLAY_OPTS_INIT { -1 }
+#define REPLAY_OPTS_INIT { .action = -1, .current_fixups = STRBUF_INIT }
/* Call this to setup defaults before parsing command line options */
void sequencer_init_config(struct replay_opts *opts);
@@ -59,6 +67,13 @@ int sequencer_remove_state(struct replay_opts *opts);
#define TODO_LIST_KEEP_EMPTY (1U << 0)
#define TODO_LIST_SHORTEN_IDS (1U << 1)
#define TODO_LIST_ABBREVIATE_CMDS (1U << 2)
+#define TODO_LIST_REBASE_MERGES (1U << 3)
+/*
+ * When rebasing merges, commits that do have the base commit as ancestor
+ * ("cousins") are *not* rebased onto the new base by default. If those
+ * commits should be rebased onto the new base, this flag needs to be passed.
+ */
+#define TODO_LIST_REBASE_COUSINS (1U << 4)
int sequencer_make_script(FILE *out, int argc, const char **argv,
unsigned flags);
diff --git a/serve.c b/serve.c
new file mode 100644
index 0000000..bda085f
--- /dev/null
+++ b/serve.c
@@ -0,0 +1,258 @@
+#include "cache.h"
+#include "repository.h"
+#include "config.h"
+#include "pkt-line.h"
+#include "version.h"
+#include "argv-array.h"
+#include "ls-refs.h"
+#include "serve.h"
+#include "upload-pack.h"
+
+static int always_advertise(struct repository *r,
+ struct strbuf *value)
+{
+ return 1;
+}
+
+static int agent_advertise(struct repository *r,
+ struct strbuf *value)
+{
+ if (value)
+ strbuf_addstr(value, git_user_agent_sanitized());
+ return 1;
+}
+
+struct protocol_capability {
+ /*
+ * The name of the capability. The server uses this name when
+ * advertising this capability, and the client uses this name to
+ * specify this capability.
+ */
+ const char *name;
+
+ /*
+ * Function queried to see if a capability should be advertised.
+ * Optionally a value can be specified by adding it to 'value'.
+ * If a value is added to 'value', the server will advertise this
+ * capability as "<name>=<value>" instead of "<name>".
+ */
+ int (*advertise)(struct repository *r, struct strbuf *value);
+
+ /*
+ * Function called when a client requests the capability as a command.
+ * The function will be provided the capabilities requested via 'keys'
+ * as well as a struct packet_reader 'request' which the command should
+ * use to read the command specific part of the request. Every command
+ * MUST read until a flush packet is seen before sending a response.
+ *
+ * This field should be NULL for capabilities which are not commands.
+ */
+ int (*command)(struct repository *r,
+ struct argv_array *keys,
+ struct packet_reader *request);
+};
+
+static struct protocol_capability capabilities[] = {
+ { "agent", agent_advertise, NULL },
+ { "ls-refs", always_advertise, ls_refs },
+ { "fetch", upload_pack_advertise, upload_pack_v2 },
+ { "server-option", always_advertise, NULL },
+};
+
+static void advertise_capabilities(void)
+{
+ struct strbuf capability = STRBUF_INIT;
+ struct strbuf value = STRBUF_INIT;
+ int i;
+
+ for (i = 0; i < ARRAY_SIZE(capabilities); i++) {
+ struct protocol_capability *c = &capabilities[i];
+
+ if (c->advertise(the_repository, &value)) {
+ strbuf_addstr(&capability, c->name);
+
+ if (value.len) {
+ strbuf_addch(&capability, '=');
+ strbuf_addbuf(&capability, &value);
+ }
+
+ strbuf_addch(&capability, '\n');
+ packet_write(1, capability.buf, capability.len);
+ }
+
+ strbuf_reset(&capability);
+ strbuf_reset(&value);
+ }
+
+ packet_flush(1);
+ strbuf_release(&capability);
+ strbuf_release(&value);
+}
+
+static struct protocol_capability *get_capability(const char *key)
+{
+ int i;
+
+ if (!key)
+ return NULL;
+
+ for (i = 0; i < ARRAY_SIZE(capabilities); i++) {
+ struct protocol_capability *c = &capabilities[i];
+ const char *out;
+ if (skip_prefix(key, c->name, &out) && (!*out || *out == '='))
+ return c;
+ }
+
+ return NULL;
+}
+
+static int is_valid_capability(const char *key)
+{
+ const struct protocol_capability *c = get_capability(key);
+
+ return c && c->advertise(the_repository, NULL);
+}
+
+static int is_command(const char *key, struct protocol_capability **command)
+{
+ const char *out;
+
+ if (skip_prefix(key, "command=", &out)) {
+ struct protocol_capability *cmd = get_capability(out);
+
+ if (*command)
+ die("command '%s' requested after already requesting command '%s'",
+ out, (*command)->name);
+ if (!cmd || !cmd->advertise(the_repository, NULL) || !cmd->command)
+ die("invalid command '%s'", out);
+
+ *command = cmd;
+ return 1;
+ }
+
+ return 0;
+}
+
+int has_capability(const struct argv_array *keys, const char *capability,
+ const char **value)
+{
+ int i;
+ for (i = 0; i < keys->argc; i++) {
+ const char *out;
+ if (skip_prefix(keys->argv[i], capability, &out) &&
+ (!*out || *out == '=')) {
+ if (value) {
+ if (*out == '=')
+ out++;
+ *value = out;
+ }
+ return 1;
+ }
+ }
+
+ return 0;
+}
+
+enum request_state {
+ PROCESS_REQUEST_KEYS,
+ PROCESS_REQUEST_DONE,
+};
+
+static int process_request(void)
+{
+ enum request_state state = PROCESS_REQUEST_KEYS;
+ struct packet_reader reader;
+ struct argv_array keys = ARGV_ARRAY_INIT;
+ struct protocol_capability *command = NULL;
+
+ packet_reader_init(&reader, 0, NULL, 0,
+ PACKET_READ_CHOMP_NEWLINE |
+ PACKET_READ_GENTLE_ON_EOF);
+
+ /*
+ * Check to see if the client closed their end before sending another
+ * request. If so we can terminate the connection.
+ */
+ if (packet_reader_peek(&reader) == PACKET_READ_EOF)
+ return 1;
+ reader.options = PACKET_READ_CHOMP_NEWLINE;
+
+ while (state != PROCESS_REQUEST_DONE) {
+ switch (packet_reader_peek(&reader)) {
+ case PACKET_READ_EOF:
+ BUG("Should have already died when seeing EOF");
+ case PACKET_READ_NORMAL:
+ /* collect request; a sequence of keys and values */
+ if (is_command(reader.line, &command) ||
+ is_valid_capability(reader.line))
+ argv_array_push(&keys, reader.line);
+ else
+ die("unknown capability '%s'", reader.line);
+
+ /* Consume the peeked line */
+ packet_reader_read(&reader);
+ break;
+ case PACKET_READ_FLUSH:
+ /*
+ * If no command and no keys were given then the client
+ * wanted to terminate the connection.
+ */
+ if (!keys.argc)
+ return 1;
+
+ /*
+ * The flush packet isn't consume here like it is in
+ * the other parts of this switch statement. This is
+ * so that the command can read the flush packet and
+ * see the end of the request in the same way it would
+ * if command specific arguments were provided after a
+ * delim packet.
+ */
+ state = PROCESS_REQUEST_DONE;
+ break;
+ case PACKET_READ_DELIM:
+ /* Consume the peeked line */
+ packet_reader_read(&reader);
+
+ state = PROCESS_REQUEST_DONE;
+ break;
+ }
+ }
+
+ if (!command)
+ die("no command requested");
+
+ command->command(the_repository, &keys, &reader);
+
+ argv_array_clear(&keys);
+ return 0;
+}
+
+/* Main serve loop for protocol version 2 */
+void serve(struct serve_options *options)
+{
+ if (options->advertise_capabilities || !options->stateless_rpc) {
+ /* serve by default supports v2 */
+ packet_write_fmt(1, "version 2\n");
+
+ advertise_capabilities();
+ /*
+ * If only the list of capabilities was requested exit
+ * immediately after advertising capabilities
+ */
+ if (options->advertise_capabilities)
+ return;
+ }
+
+ /*
+ * If stateless-rpc was requested then exit after
+ * a single request/response exchange
+ */
+ if (options->stateless_rpc) {
+ process_request();
+ } else {
+ for (;;)
+ if (process_request())
+ break;
+ }
+}
diff --git a/serve.h b/serve.h
new file mode 100644
index 0000000..fe65ba9
--- /dev/null
+++ b/serve.h
@@ -0,0 +1,15 @@
+#ifndef SERVE_H
+#define SERVE_H
+
+struct argv_array;
+extern int has_capability(const struct argv_array *keys, const char *capability,
+ const char **value);
+
+struct serve_options {
+ unsigned advertise_capabilities;
+ unsigned stateless_rpc;
+};
+#define SERVE_OPTIONS_INIT { 0 }
+extern void serve(struct serve_options *options);
+
+#endif /* SERVE_H */
diff --git a/server-info.c b/server-info.c
index 83460ec..7ce6dcd 100644
--- a/server-info.c
+++ b/server-info.c
@@ -92,8 +92,6 @@ static struct pack_info {
int old_num;
int new_num;
int nr_alloc;
- int nr_heads;
- unsigned char (*head)[20];
} **info;
static int num_pack;
static const char *objdir;
@@ -225,12 +223,9 @@ static void init_pack_info(const char *infofile, int force)
else
stale = 1;
- for (i = 0; i < num_pack; i++) {
- if (stale) {
+ for (i = 0; i < num_pack; i++)
+ if (stale)
info[i]->old_num = -1;
- info[i]->nr_heads = 0;
- }
- }
/* renumber them */
QSORT(info, num_pack, compare_info);
diff --git a/setup.c b/setup.c
index 664453f..b24c811 100644
--- a/setup.c
+++ b/setup.c
@@ -3,6 +3,7 @@
#include "config.h"
#include "dir.h"
#include "string-list.h"
+#include "chdir-notify.h"
static int inside_git_dir = -1;
static int inside_work_tree = -1;
@@ -378,7 +379,7 @@ int is_inside_work_tree(void)
void setup_work_tree(void)
{
- const char *work_tree, *git_dir;
+ const char *work_tree;
static int initialized = 0;
if (initialized)
@@ -388,10 +389,7 @@ void setup_work_tree(void)
die(_("unable to set up work tree using invalid config"));
work_tree = get_git_work_tree();
- git_dir = get_git_dir();
- if (!is_absolute_path(git_dir))
- git_dir = real_path(get_git_dir());
- if (!work_tree || chdir(work_tree))
+ if (!work_tree || chdir_notify(work_tree))
die(_("this operation must be run in a work tree"));
/*
@@ -401,7 +399,6 @@ void setup_work_tree(void)
if (getenv(GIT_WORK_TREE_ENVIRONMENT))
setenv(GIT_WORK_TREE_ENVIRONMENT, ".", 1);
- set_git_dir(remove_leading_path(git_dir, work_tree));
initialized = 1;
}
@@ -542,7 +539,7 @@ void read_gitfile_error_die(int error_code, const char *path, const char *dir)
case READ_GITFILE_ERR_NOT_A_REPO:
die(_("not a git repository: %s"), dir);
default:
- die("BUG: unknown error code");
+ BUG("unknown error code");
}
}
@@ -1089,7 +1086,7 @@ const char *setup_git_directory_gently(int *nongit_ok)
"Stopping at filesystem boundary (GIT_DISCOVERY_ACROSS_FILESYSTEM not set)."),
dir.buf);
default:
- die("BUG: unhandled setup_git_directory_1() result");
+ BUG("unhandled setup_git_directory_1() result");
}
if (prefix)
diff --git a/sha1-array.c b/sha1-array.c
index 838b3bf..265941f 100644
--- a/sha1-array.c
+++ b/sha1-array.c
@@ -41,9 +41,26 @@ void oid_array_clear(struct oid_array *array)
array->sorted = 0;
}
+
+int oid_array_for_each(struct oid_array *array,
+ for_each_oid_fn fn,
+ void *data)
+{
+ int i;
+
+ /* No oid_array_sort() here! See the api-oid-array.txt docs! */
+
+ for (i = 0; i < array->nr; i++) {
+ int ret = fn(array->oid + i, data);
+ if (ret)
+ return ret;
+ }
+ return 0;
+}
+
int oid_array_for_each_unique(struct oid_array *array,
- for_each_oid_fn fn,
- void *data)
+ for_each_oid_fn fn,
+ void *data)
{
int i;
diff --git a/sha1-array.h b/sha1-array.h
index 04b0756..232bf95 100644
--- a/sha1-array.h
+++ b/sha1-array.h
@@ -16,8 +16,11 @@ void oid_array_clear(struct oid_array *array);
typedef int (*for_each_oid_fn)(const struct object_id *oid,
void *data);
+int oid_array_for_each(struct oid_array *array,
+ for_each_oid_fn fn,
+ void *data);
int oid_array_for_each_unique(struct oid_array *array,
- for_each_oid_fn fn,
- void *data);
+ for_each_oid_fn fn,
+ void *data);
#endif /* SHA1_ARRAY_H */
diff --git a/sha1_file.c b/sha1-file.c
index 77ccaab..555e780 100644
--- a/sha1_file.c
+++ b/sha1-file.c
@@ -23,6 +23,7 @@
#include "sha1-lookup.h"
#include "bulk-checkin.h"
#include "repository.h"
+#include "replace-object.h"
#include "streaming.h"
#include "dir.h"
#include "list.h"
@@ -35,12 +36,21 @@
/* The maximum size for an object header. */
#define MAX_HEADER_LEN 32
+
+#define EMPTY_TREE_SHA1_BIN_LITERAL \
+ "\x4b\x82\x5d\xc6\x42\xcb\x6e\xb9\xa0\x60" \
+ "\xe5\x4b\xf8\xd6\x92\x88\xfb\xee\x49\x04"
+
+#define EMPTY_BLOB_SHA1_BIN_LITERAL \
+ "\xe6\x9d\xe2\x9b\xb2\xd1\xd6\x43\x4b\x8b" \
+ "\x29\xae\x77\x5a\xd8\xc2\xe4\x8c\x53\x91"
+
const unsigned char null_sha1[GIT_MAX_RAWSZ];
const struct object_id null_oid;
-const struct object_id empty_tree_oid = {
+static const struct object_id empty_tree_oid = {
EMPTY_TREE_SHA1_BIN_LITERAL
};
-const struct object_id empty_blob_oid = {
+static const struct object_id empty_blob_oid = {
EMPTY_BLOB_SHA1_BIN_LITERAL
};
@@ -100,6 +110,18 @@ const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
},
};
+const char *empty_tree_oid_hex(void)
+{
+ static char buf[GIT_MAX_HEXSZ + 1];
+ return oid_to_hex_r(buf, the_hash_algo->empty_tree);
+}
+
+const char *empty_blob_oid_hex(void)
+{
+ static char buf[GIT_MAX_HEXSZ + 1];
+ return oid_to_hex_r(buf, the_hash_algo->empty_blob);
+}
+
/*
* This is meant to hold a *small* number of objects that you would
* want read_sha1_file() to be able to return, but yet you do not want
@@ -107,7 +129,7 @@ const struct git_hash_algo hash_algos[GIT_HASH_NALGOS] = {
* application).
*/
static struct cached_object {
- unsigned char sha1[20];
+ struct object_id oid;
enum object_type type;
void *buf;
unsigned long size;
@@ -115,22 +137,22 @@ static struct cached_object {
static int cached_object_nr, cached_object_alloc;
static struct cached_object empty_tree = {
- EMPTY_TREE_SHA1_BIN_LITERAL,
+ { EMPTY_TREE_SHA1_BIN_LITERAL },
OBJ_TREE,
"",
0
};
-static struct cached_object *find_cached_object(const unsigned char *sha1)
+static struct cached_object *find_cached_object(const struct object_id *oid)
{
int i;
struct cached_object *co = cached_objects;
for (i = 0; i < cached_object_nr; i++, co++) {
- if (!hashcmp(co->sha1, sha1))
+ if (!oidcmp(&co->oid, oid))
return co;
}
- if (!hashcmp(sha1, empty_tree.sha1))
+ if (!oidcmp(oid, the_hash_algo->empty_tree))
return &empty_tree;
return NULL;
}
@@ -141,7 +163,7 @@ static int get_conv_flags(unsigned flags)
if (flags & HASH_RENORMALIZE)
return CONV_EOL_RENORMALIZE;
else if (flags & HASH_WRITE_OBJECT)
- return global_conv_flags_eol;
+ return global_conv_flags_eol | CONV_WRITE_OBJECT;
else
return 0;
}
@@ -709,42 +731,42 @@ int check_and_freshen_file(const char *fn, int freshen)
return 1;
}
-static int check_and_freshen_local(const unsigned char *sha1, int freshen)
+static int check_and_freshen_local(const struct object_id *oid, int freshen)
{
static struct strbuf buf = STRBUF_INIT;
strbuf_reset(&buf);
- sha1_file_name(the_repository, &buf, sha1);
+ sha1_file_name(the_repository, &buf, oid->hash);
return check_and_freshen_file(buf.buf, freshen);
}
-static int check_and_freshen_nonlocal(const unsigned char *sha1, int freshen)
+static int check_and_freshen_nonlocal(const struct object_id *oid, int freshen)
{
struct alternate_object_database *alt;
prepare_alt_odb(the_repository);
for (alt = the_repository->objects->alt_odb_list; alt; alt = alt->next) {
- const char *path = alt_sha1_path(alt, sha1);
+ const char *path = alt_sha1_path(alt, oid->hash);
if (check_and_freshen_file(path, freshen))
return 1;
}
return 0;
}
-static int check_and_freshen(const unsigned char *sha1, int freshen)
+static int check_and_freshen(const struct object_id *oid, int freshen)
{
- return check_and_freshen_local(sha1, freshen) ||
- check_and_freshen_nonlocal(sha1, freshen);
+ return check_and_freshen_local(oid, freshen) ||
+ check_and_freshen_nonlocal(oid, freshen);
}
-int has_loose_object_nonlocal(const unsigned char *sha1)
+int has_loose_object_nonlocal(const struct object_id *oid)
{
- return check_and_freshen_nonlocal(sha1, 0);
+ return check_and_freshen_nonlocal(oid, 0);
}
-static int has_loose_object(const unsigned char *sha1)
+static int has_loose_object(const struct object_id *oid)
{
- return check_and_freshen(sha1, 0);
+ return check_and_freshen(oid, 0);
}
static void mmap_limit_check(size_t length)
@@ -1230,7 +1252,8 @@ static int sha1_loose_object_info(struct repository *r,
int fetch_if_missing = 1;
-int oid_object_info_extended(const struct object_id *oid, struct object_info *oi, unsigned flags)
+int oid_object_info_extended(struct repository *r, const struct object_id *oid,
+ struct object_info *oi, unsigned flags)
{
static struct object_info blank_oi = OBJECT_INFO_INIT;
struct pack_entry e;
@@ -1239,7 +1262,7 @@ int oid_object_info_extended(const struct object_id *oid, struct object_info *oi
int already_retried = 0;
if (flags & OBJECT_INFO_LOOKUP_REPLACE)
- real = lookup_replace_object(oid);
+ real = lookup_replace_object(r, oid);
if (is_null_oid(real))
return -1;
@@ -1248,7 +1271,7 @@ int oid_object_info_extended(const struct object_id *oid, struct object_info *oi
oi = &blank_oi;
if (!(flags & OBJECT_INFO_SKIP_CACHED)) {
- struct cached_object *co = find_cached_object(real->hash);
+ struct cached_object *co = find_cached_object(real);
if (co) {
if (oi->typep)
*(oi->typep) = co->type;
@@ -1268,29 +1291,31 @@ int oid_object_info_extended(const struct object_id *oid, struct object_info *oi
}
while (1) {
- if (find_pack_entry(the_repository, real->hash, &e))
+ if (find_pack_entry(r, real, &e))
break;
if (flags & OBJECT_INFO_IGNORE_LOOSE)
return -1;
/* Most likely it's a loose object. */
- if (!sha1_loose_object_info(the_repository, real->hash, oi, flags))
+ if (!sha1_loose_object_info(r, real->hash, oi, flags))
return 0;
/* Not a loose object; someone else may have just packed it. */
if (!(flags & OBJECT_INFO_QUICK)) {
- reprepare_packed_git(the_repository);
- if (find_pack_entry(the_repository, real->hash, &e))
+ reprepare_packed_git(r);
+ if (find_pack_entry(r, real, &e))
break;
}
/* Check if it is a missing object */
if (fetch_if_missing && repository_format_partial_clone &&
- !already_retried) {
+ !already_retried && r == the_repository) {
/*
- * TODO Investigate haveing fetch_object() return
+ * TODO Investigate having fetch_object() return
* TODO error/success and stopping the music here.
+ * TODO Pass a repository struct through fetch_object,
+ * such that arbitrary repositories work.
*/
fetch_object(repository_format_partial_clone, real->hash);
already_retried = 1;
@@ -1306,10 +1331,10 @@ int oid_object_info_extended(const struct object_id *oid, struct object_info *oi
* information below, so return early.
*/
return 0;
- rtype = packed_object_info(e.p, e.offset, oi);
+ rtype = packed_object_info(r, e.p, e.offset, oi);
if (rtype < 0) {
mark_bad_packed_object(e.p, real->hash);
- return oid_object_info_extended(real, oi, 0);
+ return oid_object_info_extended(r, real, oi, 0);
} else if (oi->whence == OI_PACKED) {
oi->u.packed.offset = e.offset;
oi->u.packed.pack = e.p;
@@ -1321,15 +1346,17 @@ int oid_object_info_extended(const struct object_id *oid, struct object_info *oi
}
/* returns enum object_type or negative */
-int oid_object_info(const struct object_id *oid, unsigned long *sizep)
+int oid_object_info(struct repository *r,
+ const struct object_id *oid,
+ unsigned long *sizep)
{
enum object_type type;
struct object_info oi = OBJECT_INFO_INIT;
oi.typep = &type;
oi.sizep = sizep;
- if (oid_object_info_extended(oid, &oi,
- OBJECT_INFO_LOOKUP_REPLACE) < 0)
+ if (oid_object_info_extended(r, oid, &oi,
+ OBJECT_INFO_LOOKUP_REPLACE) < 0)
return -1;
return type;
}
@@ -1346,7 +1373,7 @@ static void *read_object(const unsigned char *sha1, enum object_type *type,
hashcpy(oid.hash, sha1);
- if (oid_object_info_extended(&oid, &oi, 0) < 0)
+ if (oid_object_info_extended(the_repository, &oid, &oi, 0) < 0)
return NULL;
return content;
}
@@ -1357,7 +1384,7 @@ int pretend_object_file(void *buf, unsigned long len, enum object_type type,
struct cached_object *co;
hash_object_file(buf, len, type_name(type), oid);
- if (has_sha1_file(oid->hash) || find_cached_object(oid->hash))
+ if (has_sha1_file(oid->hash) || find_cached_object(oid))
return 0;
ALLOC_GROW(cached_objects, cached_object_nr + 1, cached_object_alloc);
co = &cached_objects[cached_object_nr++];
@@ -1365,7 +1392,7 @@ int pretend_object_file(void *buf, unsigned long len, enum object_type type,
co->type = type;
co->buf = xmalloc(len);
memcpy(co->buf, buf, len);
- hashcpy(co->sha1, oid->hash);
+ oidcpy(&co->oid, oid);
return 0;
}
@@ -1383,8 +1410,8 @@ void *read_object_file_extended(const struct object_id *oid,
const struct packed_git *p;
const char *path;
struct stat st;
- const struct object_id *repl = lookup_replace ? lookup_replace_object(oid)
- : oid;
+ const struct object_id *repl = lookup_replace ?
+ lookup_replace_object(the_repository, oid) : oid;
errno = 0;
data = read_object(repl->hash, type, size);
@@ -1661,15 +1688,15 @@ static int write_loose_object(const struct object_id *oid, char *hdr,
return finalize_object_file(tmp_file.buf, filename.buf);
}
-static int freshen_loose_object(const unsigned char *sha1)
+static int freshen_loose_object(const struct object_id *oid)
{
- return check_and_freshen(sha1, 1);
+ return check_and_freshen(oid, 1);
}
-static int freshen_packed_object(const unsigned char *sha1)
+static int freshen_packed_object(const struct object_id *oid)
{
struct pack_entry e;
- if (!find_pack_entry(the_repository, sha1, &e))
+ if (!find_pack_entry(the_repository, oid, &e))
return 0;
if (e.p->freshened)
return 1;
@@ -1689,7 +1716,7 @@ int write_object_file(const void *buf, unsigned long len, const char *type,
* it out into .git/objects/??/?{38} file.
*/
write_object_file_prepare(buf, len, type, oid, hdr, &hdrlen);
- if (freshen_packed_object(oid->hash) || freshen_loose_object(oid->hash))
+ if (freshen_packed_object(oid) || freshen_loose_object(oid))
return 0;
return write_loose_object(oid, hdr, hdrlen, buf, len, 0);
}
@@ -1708,7 +1735,7 @@ int hash_object_file_literally(const void *buf, unsigned long len,
if (!(flags & HASH_WRITE_OBJECT))
goto cleanup;
- if (freshen_packed_object(oid->hash) || freshen_loose_object(oid->hash))
+ if (freshen_packed_object(oid) || freshen_loose_object(oid))
goto cleanup;
status = write_loose_object(oid, header, hdrlen, buf, len, 0);
@@ -1726,7 +1753,7 @@ int force_object_loose(const struct object_id *oid, time_t mtime)
int hdrlen;
int ret;
- if (has_loose_object(oid->hash))
+ if (has_loose_object(oid))
return 0;
buf = read_object(oid->hash, &type, &len);
if (!buf)
@@ -1744,7 +1771,7 @@ int has_sha1_file_with_flags(const unsigned char *sha1, int flags)
if (!startup_info->have_repository)
return 0;
hashcpy(oid.hash, sha1);
- return oid_object_info_extended(&oid, NULL,
+ return oid_object_info_extended(the_repository, &oid, NULL,
flags | OBJECT_INFO_SKIP_CACHED) >= 0;
}
@@ -1987,7 +2014,7 @@ int read_pack_header(int fd, struct pack_header *header)
void assert_oid_type(const struct object_id *oid, enum object_type expect)
{
- enum object_type type = oid_object_info(oid, NULL);
+ enum object_type type = oid_object_info(the_repository, oid, NULL);
if (type < 0)
die("%s is not a valid object", oid_to_hex(oid));
if (type != expect)
@@ -2226,7 +2253,7 @@ int read_loose_object(const char *path,
goto out;
}
- if (*type == OBJ_BLOB) {
+ if (*type == OBJ_BLOB && *size > big_file_threshold) {
if (check_stream_sha1(&stream, hdr, *size, path, expected_oid->hash) < 0)
goto out;
} else {
diff --git a/sha1-lookup.c b/sha1-lookup.c
index 8d0b1db..796ab68 100644
--- a/sha1-lookup.c
+++ b/sha1-lookup.c
@@ -81,7 +81,7 @@ int sha1_pos(const unsigned char *sha1, void *table, size_t nr,
mi = (nr - 1) * (miv - lov) / (hiv - lov);
if (lo <= mi && mi < hi)
break;
- die("BUG: assertion failed in binary search");
+ BUG("assertion failed in binary search");
}
}
}
diff --git a/sha1_name.c b/sha1-name.c
index 5b93bf8..60d9ef3 100644
--- a/sha1_name.c
+++ b/sha1-name.c
@@ -223,7 +223,7 @@ static int finish_object_disambiguation(struct disambiguate_state *ds,
static int disambiguate_commit_only(const struct object_id *oid, void *cb_data_unused)
{
- int kind = oid_object_info(oid, NULL);
+ int kind = oid_object_info(the_repository, oid, NULL);
return kind == OBJ_COMMIT;
}
@@ -232,7 +232,7 @@ static int disambiguate_committish_only(const struct object_id *oid, void *cb_da
struct object *obj;
int kind;
- kind = oid_object_info(oid, NULL);
+ kind = oid_object_info(the_repository, oid, NULL);
if (kind == OBJ_COMMIT)
return 1;
if (kind != OBJ_TAG)
@@ -247,7 +247,7 @@ static int disambiguate_committish_only(const struct object_id *oid, void *cb_da
static int disambiguate_tree_only(const struct object_id *oid, void *cb_data_unused)
{
- int kind = oid_object_info(oid, NULL);
+ int kind = oid_object_info(the_repository, oid, NULL);
return kind == OBJ_TREE;
}
@@ -256,7 +256,7 @@ static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_
struct object *obj;
int kind;
- kind = oid_object_info(oid, NULL);
+ kind = oid_object_info(the_repository, oid, NULL);
if (kind == OBJ_TREE || kind == OBJ_COMMIT)
return 1;
if (kind != OBJ_TAG)
@@ -271,7 +271,7 @@ static int disambiguate_treeish_only(const struct object_id *oid, void *cb_data_
static int disambiguate_blob_only(const struct object_id *oid, void *cb_data_unused)
{
- int kind = oid_object_info(oid, NULL);
+ int kind = oid_object_info(the_repository, oid, NULL);
return kind == OBJ_BLOB;
}
@@ -346,11 +346,10 @@ static int show_ambiguous_object(const struct object_id *oid, void *data)
struct strbuf desc = STRBUF_INIT;
int type;
-
if (ds->fn && !ds->fn(oid, ds->cb_data))
return 0;
- type = oid_object_info(oid, NULL);
+ type = oid_object_info(the_repository, oid, NULL);
if (type == OBJ_COMMIT) {
struct commit *commit = lookup_commit(oid);
if (commit) {
@@ -373,6 +372,40 @@ static int show_ambiguous_object(const struct object_id *oid, void *data)
return 0;
}
+static int collect_ambiguous(const struct object_id *oid, void *data)
+{
+ oid_array_append(data, oid);
+ return 0;
+}
+
+static int sort_ambiguous(const void *a, const void *b)
+{
+ int a_type = oid_object_info(the_repository, a, NULL);
+ int b_type = oid_object_info(the_repository, b, NULL);
+ int a_type_sort;
+ int b_type_sort;
+
+ /*
+ * Sorts by hash within the same object type, just as
+ * oid_array_for_each_unique() would do.
+ */
+ if (a_type == b_type)
+ return oidcmp(a, b);
+
+ /*
+ * Between object types show tags, then commits, and finally
+ * trees and blobs.
+ *
+ * The object_type enum is commit, tree, blob, tag, but we
+ * want tag, commit, tree blob. Cleverly (perhaps too
+ * cleverly) do that with modulus, since the enum assigns 1 to
+ * commit, so tag becomes 0.
+ */
+ a_type_sort = a_type % 4;
+ b_type_sort = b_type % 4;
+ return a_type_sort > b_type_sort ? 1 : -1;
+}
+
static int get_short_oid(const char *name, int len, struct object_id *oid,
unsigned flags)
{
@@ -384,7 +417,7 @@ static int get_short_oid(const char *name, int len, struct object_id *oid,
return -1;
if (HAS_MULTI_BITS(flags & GET_OID_DISAMBIGUATORS))
- die("BUG: multiple get_short_oid disambiguator flags");
+ BUG("multiple get_short_oid disambiguator flags");
if (flags & GET_OID_COMMIT)
ds.fn = disambiguate_commit_only;
@@ -404,6 +437,8 @@ static int get_short_oid(const char *name, int len, struct object_id *oid,
status = finish_object_disambiguation(&ds, oid);
if (!quietly && (status == SHORT_NAME_AMBIGUOUS)) {
+ struct oid_array collect = OID_ARRAY_INIT;
+
error(_("short SHA1 %s is ambiguous"), ds.hex_pfx);
/*
@@ -416,18 +451,17 @@ static int get_short_oid(const char *name, int len, struct object_id *oid,
ds.fn = NULL;
advise(_("The candidates are:"));
- for_each_abbrev(ds.hex_pfx, show_ambiguous_object, &ds);
+ for_each_abbrev(ds.hex_pfx, collect_ambiguous, &collect);
+ QSORT(collect.oid, collect.nr, sort_ambiguous);
+
+ if (oid_array_for_each(&collect, show_ambiguous_object, &ds))
+ BUG("show_ambiguous_object shouldn't return non-zero");
+ oid_array_clear(&collect);
}
return status;
}
-static int collect_ambiguous(const struct object_id *oid, void *data)
-{
- oid_array_append(data, oid);
- return 0;
-}
-
int for_each_abbrev(const char *prefix, each_abbrev_fn fn, void *cb_data)
{
struct oid_array collect = OID_ARRAY_INIT;
@@ -864,7 +898,7 @@ struct object *peel_to_type(const char *name, int namelen,
if (o->type == OBJ_TAG)
o = ((struct tag*) o)->tagged;
else if (o->type == OBJ_COMMIT)
- o = &(((struct commit *) o)->tree->object);
+ o = &(get_commit_tree(((struct commit *)o))->object);
else {
if (name)
error("%.*s: expected %s type, but the object "
@@ -1685,8 +1719,8 @@ static int get_oid_with_context_1(const char *name,
if (new_filename)
filename = new_filename;
if (flags & GET_OID_FOLLOW_SYMLINKS) {
- ret = get_tree_entry_follow_symlinks(tree_oid.hash,
- filename, oid->hash, &oc->symlink_path,
+ ret = get_tree_entry_follow_symlinks(&tree_oid,
+ filename, oid, &oc->symlink_path,
&oc->mode);
} else {
ret = get_tree_entry(&tree_oid, filename, oid,
@@ -1698,7 +1732,6 @@ static int get_oid_with_context_1(const char *name,
name, len);
}
}
- hashcpy(oc->tree, tree_oid.hash);
if (flags & GET_OID_RECORD_PATH)
oc->path = xstrdup(filename);
@@ -1729,6 +1762,6 @@ void maybe_die_on_misspelt_object_name(const char *name, const char *prefix)
int get_oid_with_context(const char *str, unsigned flags, struct object_id *oid, struct object_context *oc)
{
if (flags & GET_OID_FOLLOW_SYMLINKS && flags & GET_OID_ONLY_TO_DIE)
- die("BUG: incompatible flags for get_sha1_with_context");
+ BUG("incompatible flags for get_sha1_with_context");
return get_oid_with_context_1(str, flags, NULL, oid, oc);
}
diff --git a/shallow.c b/shallow.c
index df4d44e..9ff83ca 100644
--- a/shallow.c
+++ b/shallow.c
@@ -20,7 +20,7 @@ static char *alternate_shallow_file;
void set_alternate_shallow_file(const char *path, int override)
{
if (is_shallow != -1)
- die("BUG: is_repository_shallow must not be called before set_alternate_shallow_file");
+ BUG("is_repository_shallow must not be called before set_alternate_shallow_file");
if (alternate_shallow_file && !override)
return;
free(alternate_shallow_file);
@@ -218,7 +218,7 @@ struct commit_list *get_shallow_commits_by_rev_list(int ac, const char **av,
static void check_shallow_file_for_update(void)
{
if (is_shallow == -1)
- die("BUG: shallow must be initialized by now");
+ BUG("shallow must be initialized by now");
if (!stat_validity_check(&shallow_stat, git_path_shallow()))
die("shallow file has changed since we read it");
@@ -353,7 +353,7 @@ void advertise_shallow_grafts(int fd)
*/
void prune_shallow(int show_only)
{
- static struct lock_file shallow_lock;
+ struct lock_file shallow_lock = LOCK_INIT;
struct strbuf sb = STRBUF_INIT;
int fd;
@@ -446,7 +446,7 @@ static uint32_t *paint_alloc(struct paint_info *info)
void *p;
if (!info->pool_count || size > info->end - info->free) {
if (size > POOL_SIZE)
- die("BUG: pool size too small for %d in paint_alloc()",
+ BUG("pool size too small for %d in paint_alloc()",
size);
info->pool_count++;
REALLOC_ARRAY(info->pools, info->pool_count);
diff --git a/shell.c b/shell.c
index 234b2d4..0200d10 100644
--- a/shell.c
+++ b/shell.c
@@ -1,6 +1,6 @@
#include "cache.h"
#include "quote.h"
-#include "exec_cmd.h"
+#include "exec-cmd.h"
#include "strbuf.h"
#include "run-command.h"
diff --git a/sideband.c b/sideband.c
index 6d7f943..325bf0e 100644
--- a/sideband.c
+++ b/sideband.c
@@ -13,7 +13,7 @@
* the remote died unexpectedly. A flush() concludes the stream.
*/
-#define PREFIX "remote: "
+#define DISPLAY_PREFIX "remote: "
#define ANSI_SUFFIX "\033[K"
#define DUMB_SUFFIX " "
@@ -49,7 +49,7 @@ int recv_sideband(const char *me, int in_stream, int out)
switch (band) {
case 3:
strbuf_addf(&outbuf, "%s%s%s", outbuf.len ? "\n" : "",
- PREFIX, buf + 1);
+ DISPLAY_PREFIX, buf + 1);
retval = SIDEBAND_REMOTE_ERROR;
break;
case 2:
@@ -67,7 +67,7 @@ int recv_sideband(const char *me, int in_stream, int out)
int linelen = brk - b;
if (!outbuf.len)
- strbuf_addstr(&outbuf, PREFIX);
+ strbuf_addstr(&outbuf, DISPLAY_PREFIX);
if (linelen > 0) {
strbuf_addf(&outbuf, "%.*s%s%c",
linelen, b, suffix, *brk);
@@ -81,8 +81,8 @@ int recv_sideband(const char *me, int in_stream, int out)
}
if (*b)
- strbuf_addf(&outbuf, "%s%s",
- outbuf.len ? "" : PREFIX, b);
+ strbuf_addf(&outbuf, "%s%s", outbuf.len ?
+ "" : DISPLAY_PREFIX, b);
break;
case 1:
write_or_die(out, buf + 1, len);
diff --git a/sigchain.c b/sigchain.c
index 2ac43bb..022677b 100644
--- a/sigchain.c
+++ b/sigchain.c
@@ -13,7 +13,7 @@ static struct sigchain_signal signals[SIGCHAIN_MAX_SIGNALS];
static void check_signum(int sig)
{
if (sig < 1 || sig >= SIGCHAIN_MAX_SIGNALS)
- die("BUG: signal out of range: %d", sig);
+ BUG("signal out of range: %d", sig);
}
int sigchain_push(int sig, sigchain_fun f)
diff --git a/split-index.c b/split-index.c
index 3eb8ff1..660c75f 100644
--- a/split-index.c
+++ b/split-index.c
@@ -18,12 +18,12 @@ int read_link_extension(struct index_state *istate,
struct split_index *si;
int ret;
- if (sz < 20)
+ if (sz < the_hash_algo->rawsz)
return error("corrupt link extension (too short)");
si = init_split_index(istate);
- hashcpy(si->base_sha1, data);
- data += 20;
- sz -= 20;
+ hashcpy(si->base_oid.hash, data);
+ data += the_hash_algo->rawsz;
+ sz -= the_hash_algo->rawsz;
if (!sz)
return 0;
si->delete_bitmap = ewah_new();
@@ -45,7 +45,7 @@ int write_link_extension(struct strbuf *sb,
struct index_state *istate)
{
struct split_index *si = istate->split_index;
- strbuf_add(sb, si->base_sha1, 20);
+ strbuf_add(sb, si->base_oid.hash, the_hash_algo->rawsz);
if (!si->delete_bitmap && !si->replace_bitmap)
return 0;
ewah_serialize_strbuf(si->delete_bitmap, sb);
diff --git a/split-index.h b/split-index.h
index 43d6682..7a435ca 100644
--- a/split-index.h
+++ b/split-index.h
@@ -1,12 +1,14 @@
#ifndef SPLIT_INDEX_H
#define SPLIT_INDEX_H
+#include "cache.h"
+
struct index_state;
struct strbuf;
struct ewah_bitmap;
struct split_index {
- unsigned char base_sha1[20];
+ struct object_id base_oid;
struct index_state *base;
struct ewah_bitmap *delete_bitmap;
struct ewah_bitmap *replace_bitmap;
diff --git a/strbuf.c b/strbuf.c
index 83d0502..b0716ac 100644
--- a/strbuf.c
+++ b/strbuf.c
@@ -12,6 +12,15 @@ int starts_with(const char *str, const char *prefix)
return 0;
}
+int istarts_with(const char *str, const char *prefix)
+{
+ for (; ; str++, prefix++)
+ if (!*prefix)
+ return 1;
+ else if (tolower(*str) != tolower(*prefix))
+ return 0;
+}
+
int skip_to_optional_arg_default(const char *str, const char *prefix,
const char **arg, const char *def)
{
@@ -325,12 +334,12 @@ void strbuf_vaddf(struct strbuf *sb, const char *fmt, va_list ap)
len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, cp);
va_end(cp);
if (len < 0)
- die("BUG: your vsnprintf is broken (returned %d)", len);
+ BUG("your vsnprintf is broken (returned %d)", len);
if (len > strbuf_avail(sb)) {
strbuf_grow(sb, len);
len = vsnprintf(sb->buf + sb->len, sb->alloc - sb->len, fmt, ap);
if (len > strbuf_avail(sb))
- die("BUG: your vsnprintf is broken (insatiable)");
+ BUG("your vsnprintf is broken (insatiable)");
}
strbuf_setlen(sb, sb->len + len);
}
@@ -809,7 +818,18 @@ char *xstrdup_tolower(const char *string)
result = xmallocz(len);
for (i = 0; i < len; i++)
result[i] = tolower(string[i]);
- result[i] = '\0';
+ return result;
+}
+
+char *xstrdup_toupper(const char *string)
+{
+ char *result;
+ size_t len, i;
+
+ len = strlen(string);
+ result = xmallocz(len);
+ for (i = 0; i < len; i++)
+ result[i] = toupper(string[i]);
return result;
}
diff --git a/strbuf.h b/strbuf.h
index c4de5e4..60a35ae 100644
--- a/strbuf.h
+++ b/strbuf.h
@@ -632,6 +632,7 @@ __attribute__((format (printf,2,3)))
extern int fprintf_ln(FILE *fp, const char *fmt, ...);
char *xstrdup_tolower(const char *);
+char *xstrdup_toupper(const char *);
/**
* Create a newly allocated string using printf format. You can do this easily
diff --git a/streaming.c b/streaming.c
index 7d55ba6..d1e6b2d 100644
--- a/streaming.c
+++ b/streaming.c
@@ -5,6 +5,7 @@
#include "streaming.h"
#include "repository.h"
#include "object-store.h"
+#include "replace-object.h"
#include "packfile.h"
enum input_source {
@@ -116,7 +117,7 @@ static enum input_source istream_source(const struct object_id *oid,
oi->typep = type;
oi->sizep = &size;
- status = oid_object_info_extended(oid, oi, 0);
+ status = oid_object_info_extended(the_repository, oid, oi, 0);
if (status < 0)
return stream_error;
@@ -139,7 +140,7 @@ struct git_istream *open_istream(const struct object_id *oid,
{
struct git_istream *st;
struct object_info oi = OBJECT_INFO_INIT;
- const struct object_id *real = lookup_replace_object(oid);
+ const struct object_id *real = lookup_replace_object(the_repository, oid);
enum input_source src = istream_source(real, type, &oi);
if (src < 0)
diff --git a/submodule-config.c b/submodule-config.c
index 3f20757..388ef1f 100644
--- a/submodule-config.c
+++ b/submodule-config.c
@@ -44,7 +44,7 @@ static int config_path_cmp(const void *unused_cmp_data,
const struct submodule_entry *b = entry_or_key;
return strcmp(a->config->path, b->config->path) ||
- hashcmp(a->config->gitmodules_sha1, b->config->gitmodules_sha1);
+ oidcmp(&a->config->gitmodules_oid, &b->config->gitmodules_oid);
}
static int config_name_cmp(const void *unused_cmp_data,
@@ -56,7 +56,7 @@ static int config_name_cmp(const void *unused_cmp_data,
const struct submodule_entry *b = entry_or_key;
return strcmp(a->config->name, b->config->name) ||
- hashcmp(a->config->gitmodules_sha1, b->config->gitmodules_sha1);
+ oidcmp(&a->config->gitmodules_oid, &b->config->gitmodules_oid);
}
static struct submodule_cache *submodule_cache_alloc(void)
@@ -109,17 +109,17 @@ void submodule_cache_free(struct submodule_cache *cache)
free(cache);
}
-static unsigned int hash_sha1_string(const unsigned char *sha1,
- const char *string)
+static unsigned int hash_oid_string(const struct object_id *oid,
+ const char *string)
{
- return memhash(sha1, 20) + strhash(string);
+ return memhash(oid->hash, the_hash_algo->rawsz) + strhash(string);
}
static void cache_put_path(struct submodule_cache *cache,
struct submodule *submodule)
{
- unsigned int hash = hash_sha1_string(submodule->gitmodules_sha1,
- submodule->path);
+ unsigned int hash = hash_oid_string(&submodule->gitmodules_oid,
+ submodule->path);
struct submodule_entry *e = xmalloc(sizeof(*e));
hashmap_entry_init(e, hash);
e->config = submodule;
@@ -129,8 +129,8 @@ static void cache_put_path(struct submodule_cache *cache,
static void cache_remove_path(struct submodule_cache *cache,
struct submodule *submodule)
{
- unsigned int hash = hash_sha1_string(submodule->gitmodules_sha1,
- submodule->path);
+ unsigned int hash = hash_oid_string(&submodule->gitmodules_oid,
+ submodule->path);
struct submodule_entry e;
struct submodule_entry *removed;
hashmap_entry_init(&e, hash);
@@ -142,8 +142,8 @@ static void cache_remove_path(struct submodule_cache *cache,
static void cache_add(struct submodule_cache *cache,
struct submodule *submodule)
{
- unsigned int hash = hash_sha1_string(submodule->gitmodules_sha1,
- submodule->name);
+ unsigned int hash = hash_oid_string(&submodule->gitmodules_oid,
+ submodule->name);
struct submodule_entry *e = xmalloc(sizeof(*e));
hashmap_entry_init(e, hash);
e->config = submodule;
@@ -151,14 +151,14 @@ static void cache_add(struct submodule_cache *cache,
}
static const struct submodule *cache_lookup_path(struct submodule_cache *cache,
- const unsigned char *gitmodules_sha1, const char *path)
+ const struct object_id *gitmodules_oid, const char *path)
{
struct submodule_entry *entry;
- unsigned int hash = hash_sha1_string(gitmodules_sha1, path);
+ unsigned int hash = hash_oid_string(gitmodules_oid, path);
struct submodule_entry key;
struct submodule key_config;
- hashcpy(key_config.gitmodules_sha1, gitmodules_sha1);
+ oidcpy(&key_config.gitmodules_oid, gitmodules_oid);
key_config.path = path;
hashmap_entry_init(&key, hash);
@@ -171,14 +171,14 @@ static const struct submodule *cache_lookup_path(struct submodule_cache *cache,
}
static struct submodule *cache_lookup_name(struct submodule_cache *cache,
- const unsigned char *gitmodules_sha1, const char *name)
+ const struct object_id *gitmodules_oid, const char *name)
{
struct submodule_entry *entry;
- unsigned int hash = hash_sha1_string(gitmodules_sha1, name);
+ unsigned int hash = hash_oid_string(gitmodules_oid, name);
struct submodule_entry key;
struct submodule key_config;
- hashcpy(key_config.gitmodules_sha1, gitmodules_sha1);
+ oidcpy(&key_config.gitmodules_oid, gitmodules_oid);
key_config.name = name;
hashmap_entry_init(&key, hash);
@@ -190,6 +190,31 @@ static struct submodule *cache_lookup_name(struct submodule_cache *cache,
return NULL;
}
+int check_submodule_name(const char *name)
+{
+ /* Disallow empty names */
+ if (!*name)
+ return -1;
+
+ /*
+ * Look for '..' as a path component. Check both '/' and '\\' as
+ * separators rather than is_dir_sep(), because we want the name rules
+ * to be consistent across platforms.
+ */
+ goto in_component; /* always start inside component */
+ while (*name) {
+ char c = *name++;
+ if (c == '/' || c == '\\') {
+in_component:
+ if (name[0] == '.' && name[1] == '.' &&
+ (!name[2] || name[2] == '/' || name[2] == '\\'))
+ return -1;
+ }
+ }
+
+ return 0;
+}
+
static int name_and_item_from_var(const char *var, struct strbuf *name,
struct strbuf *item)
{
@@ -201,18 +226,24 @@ static int name_and_item_from_var(const char *var, struct strbuf *name,
return 0;
strbuf_add(name, subsection, subsection_len);
+ if (check_submodule_name(name->buf) < 0) {
+ warning(_("ignoring suspicious submodule name: %s"), name->buf);
+ strbuf_release(name);
+ return 0;
+ }
+
strbuf_addstr(item, key);
return 1;
}
static struct submodule *lookup_or_create_by_name(struct submodule_cache *cache,
- const unsigned char *gitmodules_sha1, const char *name)
+ const struct object_id *gitmodules_oid, const char *name)
{
struct submodule *submodule;
struct strbuf name_buf = STRBUF_INIT;
- submodule = cache_lookup_name(cache, gitmodules_sha1, name);
+ submodule = cache_lookup_name(cache, gitmodules_oid, name);
if (submodule)
return submodule;
@@ -230,7 +261,7 @@ static struct submodule *lookup_or_create_by_name(struct submodule_cache *cache,
submodule->branch = NULL;
submodule->recommend_shallow = -1;
- hashcpy(submodule->gitmodules_sha1, gitmodules_sha1);
+ oidcpy(&submodule->gitmodules_oid, gitmodules_oid);
cache_add(cache, submodule);
@@ -341,12 +372,12 @@ int parse_push_recurse_submodules_arg(const char *opt, const char *arg)
return parse_push_recurse(opt, arg, 1);
}
-static void warn_multiple_config(const unsigned char *treeish_name,
+static void warn_multiple_config(const struct object_id *treeish_name,
const char *name, const char *option)
{
const char *commit_string = "WORKTREE";
if (treeish_name)
- commit_string = sha1_to_hex(treeish_name);
+ commit_string = oid_to_hex(treeish_name);
warning("%s:.gitmodules, multiple configurations found for "
"'submodule.%s.%s'. Skipping second one!",
commit_string, name, option);
@@ -354,8 +385,8 @@ static void warn_multiple_config(const unsigned char *treeish_name,
struct parse_config_parameter {
struct submodule_cache *cache;
- const unsigned char *treeish_name;
- const unsigned char *gitmodules_sha1;
+ const struct object_id *treeish_name;
+ const struct object_id *gitmodules_oid;
int overwrite;
};
@@ -371,7 +402,7 @@ static int parse_config(const char *var, const char *value, void *data)
return 0;
submodule = lookup_or_create_by_name(me->cache,
- me->gitmodules_sha1,
+ me->gitmodules_oid,
name.buf);
if (!strcmp(item.buf, "path")) {
@@ -389,7 +420,7 @@ static int parse_config(const char *var, const char *value, void *data)
}
} else if (!strcmp(item.buf, "fetchrecursesubmodules")) {
/* when parsing worktree configurations we can die early */
- int die_on_error = is_null_sha1(me->gitmodules_sha1);
+ int die_on_error = is_null_oid(me->gitmodules_oid);
if (!me->overwrite &&
submodule->fetch_recurse != RECURSE_SUBMODULES_NONE)
warn_multiple_config(me->treeish_name, submodule->name,
@@ -511,10 +542,10 @@ static const struct submodule *config_from(struct submodule_cache *cache,
switch (lookup_type) {
case lookup_name:
- submodule = cache_lookup_name(cache, oid.hash, key);
+ submodule = cache_lookup_name(cache, &oid, key);
break;
case lookup_path:
- submodule = cache_lookup_path(cache, oid.hash, key);
+ submodule = cache_lookup_path(cache, &oid, key);
break;
}
if (submodule)
@@ -526,8 +557,8 @@ static const struct submodule *config_from(struct submodule_cache *cache,
/* fill the submodule config into the cache */
parameter.cache = cache;
- parameter.treeish_name = treeish_name->hash;
- parameter.gitmodules_sha1 = oid.hash;
+ parameter.treeish_name = treeish_name;
+ parameter.gitmodules_oid = &oid;
parameter.overwrite = 0;
git_config_from_mem(parse_config, CONFIG_ORIGIN_SUBMODULE_BLOB, rev.buf,
config, config_size, &parameter);
@@ -536,9 +567,9 @@ static const struct submodule *config_from(struct submodule_cache *cache,
switch (lookup_type) {
case lookup_name:
- return cache_lookup_name(cache, oid.hash, key);
+ return cache_lookup_name(cache, &oid, key);
case lookup_path:
- return cache_lookup_path(cache, oid.hash, key);
+ return cache_lookup_path(cache, &oid, key);
default:
return NULL;
}
@@ -567,7 +598,7 @@ static int gitmodules_cb(const char *var, const char *value, void *data)
parameter.cache = repo->submodule_cache;
parameter.treeish_name = NULL;
- parameter.gitmodules_sha1 = null_sha1;
+ parameter.gitmodules_oid = &null_oid;
parameter.overwrite = 1;
return parse_config(var, value, &parameter);
@@ -619,31 +650,24 @@ static void gitmodules_read_check(struct repository *repo)
repo_read_gitmodules(repo);
}
-const struct submodule *submodule_from_name(const struct object_id *treeish_name,
+const struct submodule *submodule_from_name(struct repository *r,
+ const struct object_id *treeish_name,
const char *name)
{
- gitmodules_read_check(the_repository);
- return config_from(the_repository->submodule_cache, treeish_name, name, lookup_name);
+ gitmodules_read_check(r);
+ return config_from(r->submodule_cache, treeish_name, name, lookup_name);
}
-const struct submodule *submodule_from_path(const struct object_id *treeish_name,
+const struct submodule *submodule_from_path(struct repository *r,
+ const struct object_id *treeish_name,
const char *path)
{
- gitmodules_read_check(the_repository);
- return config_from(the_repository->submodule_cache, treeish_name, path, lookup_path);
-}
-
-const struct submodule *submodule_from_cache(struct repository *repo,
- const struct object_id *treeish_name,
- const char *key)
-{
- gitmodules_read_check(repo);
- return config_from(repo->submodule_cache, treeish_name,
- key, lookup_path);
+ gitmodules_read_check(r);
+ return config_from(r->submodule_cache, treeish_name, path, lookup_path);
}
-void submodule_free(void)
+void submodule_free(struct repository *r)
{
- if (the_repository->submodule_cache)
- submodule_cache_clear(the_repository->submodule_cache);
+ if (r->submodule_cache)
+ submodule_cache_clear(r->submodule_cache);
}
diff --git a/submodule-config.h b/submodule-config.h
index a5503a5..ca1f94e 100644
--- a/submodule-config.h
+++ b/submodule-config.h
@@ -1,6 +1,7 @@
#ifndef SUBMODULE_CONFIG_CACHE_H
#define SUBMODULE_CONFIG_CACHE_H
+#include "cache.h"
#include "hashmap.h"
#include "submodule.h"
#include "strbuf.h"
@@ -17,13 +18,13 @@ struct submodule {
const char *ignore;
const char *branch;
struct submodule_update_strategy update_strategy;
- /* the sha1 blob id of the responsible .gitmodules file */
- unsigned char gitmodules_sha1[20];
+ /* the object id of the responsible .gitmodules file */
+ struct object_id gitmodules_oid;
int recommend_shallow;
};
#define SUBMODULE_INIT { NULL, NULL, NULL, RECURSE_SUBMODULES_NONE, \
- NULL, NULL, SUBMODULE_UPDATE_STRATEGY_INIT, {0}, -1 };
+ NULL, NULL, SUBMODULE_UPDATE_STRATEGY_INIT, { { 0 } }, -1 };
struct submodule_cache;
struct repository;
@@ -39,13 +40,19 @@ extern int parse_update_recurse_submodules_arg(const char *opt, const char *arg)
extern int parse_push_recurse_submodules_arg(const char *opt, const char *arg);
extern void repo_read_gitmodules(struct repository *repo);
extern void gitmodules_config_oid(const struct object_id *commit_oid);
-extern const struct submodule *submodule_from_name(
- const struct object_id *commit_or_tree, const char *name);
-extern const struct submodule *submodule_from_path(
- const struct object_id *commit_or_tree, const char *path);
-extern const struct submodule *submodule_from_cache(struct repository *repo,
- const struct object_id *treeish_name,
- const char *key);
-extern void submodule_free(void);
+const struct submodule *submodule_from_name(struct repository *r,
+ const struct object_id *commit_or_tree,
+ const char *name);
+const struct submodule *submodule_from_path(struct repository *r,
+ const struct object_id *commit_or_tree,
+ const char *path);
+void submodule_free(struct repository *r);
+
+/*
+ * Returns 0 if the name is syntactically acceptable as a submodule "name"
+ * (e.g., that may be found in the subsection of a .gitmodules file) and -1
+ * otherwise.
+ */
+int check_submodule_name(const char *name);
#endif /* SUBMODULE_CONFIG_H */
diff --git a/submodule.c b/submodule.c
index 9a50168..edc3a20 100644
--- a/submodule.c
+++ b/submodule.c
@@ -96,7 +96,7 @@ int update_path_in_gitmodules(const char *oldpath, const char *newpath)
if (is_gitmodules_unmerged(&the_index))
die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
- submodule = submodule_from_path(&null_oid, oldpath);
+ submodule = submodule_from_path(the_repository, &null_oid, oldpath);
if (!submodule || !submodule->name) {
warning(_("Could not find section in .gitmodules where path=%s"), oldpath);
return -1;
@@ -130,7 +130,7 @@ int remove_path_from_gitmodules(const char *path)
if (is_gitmodules_unmerged(&the_index))
die(_("Cannot change unmerged .gitmodules, resolve merge conflicts first"));
- submodule = submodule_from_path(&null_oid, path);
+ submodule = submodule_from_path(the_repository, &null_oid, path);
if (!submodule || !submodule->name) {
warning(_("Could not find section in .gitmodules where path=%s"), path);
return -1;
@@ -153,7 +153,8 @@ void stage_updated_gitmodules(struct index_state *istate)
die(_("staging updated .gitmodules failed"));
}
-static int add_submodule_odb(const char *path)
+/* TODO: remove this function, use repo_submodule_init instead. */
+int add_submodule_odb(const char *path)
{
struct strbuf objects_directory = STRBUF_INIT;
int ret = 0;
@@ -174,7 +175,8 @@ done:
void set_diffopt_flags_from_submodule_config(struct diff_options *diffopt,
const char *path)
{
- const struct submodule *submodule = submodule_from_path(&null_oid, path);
+ const struct submodule *submodule = submodule_from_path(the_repository,
+ &null_oid, path);
if (submodule) {
const char *ignore;
char *key;
@@ -230,7 +232,7 @@ int is_submodule_active(struct repository *repo, const char *path)
const struct string_list *sl;
const struct submodule *module;
- module = submodule_from_cache(repo, &null_oid, path);
+ module = submodule_from_path(repo, &null_oid, path);
/* early return if there isn't a path->module mapping */
if (!module)
@@ -674,7 +676,7 @@ const struct submodule *submodule_from_ce(const struct cache_entry *ce)
if (!should_update_submodules())
return NULL;
- return submodule_from_path(&null_oid, ce->name);
+ return submodule_from_path(the_repository, &null_oid, ce->name);
}
static struct oid_array *submodule_commits(struct string_list *submodules,
@@ -731,13 +733,14 @@ static void collect_changed_submodules_cb(struct diff_queue_struct *q,
if (!S_ISGITLINK(p->two->mode))
continue;
- submodule = submodule_from_path(commit_oid, p->two->path);
+ submodule = submodule_from_path(the_repository,
+ commit_oid, p->two->path);
if (submodule)
name = submodule->name;
else {
name = default_name_or_path(p->two->path);
/* make sure name does not collide with existing one */
- submodule = submodule_from_name(commit_oid, name);
+ submodule = submodule_from_name(the_repository, commit_oid, name);
if (submodule) {
warning("Submodule in commit %s at path: "
"'%s' collides with a submodule named "
@@ -818,7 +821,7 @@ static int check_has_commit(const struct object_id *oid, void *data)
{
struct has_commit_data *cb = data;
- enum object_type type = oid_object_info(oid, NULL);
+ enum object_type type = oid_object_info(the_repository, oid, NULL);
switch (type) {
case OBJ_COMMIT:
@@ -945,7 +948,7 @@ int find_unpushed_submodules(struct oid_array *commits,
const struct submodule *submodule;
const char *path = NULL;
- submodule = submodule_from_name(&null_oid, name->string);
+ submodule = submodule_from_name(the_repository, &null_oid, name->string);
if (submodule)
path = submodule->path;
else
@@ -966,7 +969,7 @@ int find_unpushed_submodules(struct oid_array *commits,
static int push_submodule(const char *path,
const struct remote *remote,
- const char **refspec, int refspec_nr,
+ const struct refspec *rs,
const struct string_list *push_options,
int dry_run)
{
@@ -989,8 +992,8 @@ static int push_submodule(const char *path,
if (remote->origin != REMOTE_UNCONFIGURED) {
int i;
argv_array_push(&cp.args, remote->name);
- for (i = 0; i < refspec_nr; i++)
- argv_array_push(&cp.args, refspec[i]);
+ for (i = 0; i < rs->raw_nr; i++)
+ argv_array_push(&cp.args, rs->raw[i]);
}
prepare_submodule_repo_env(&cp.env_array);
@@ -1011,7 +1014,7 @@ static int push_submodule(const char *path,
*/
static void submodule_push_check(const char *path, const char *head,
const struct remote *remote,
- const char **refspec, int refspec_nr)
+ const struct refspec *rs)
{
struct child_process cp = CHILD_PROCESS_INIT;
int i;
@@ -1021,8 +1024,8 @@ static void submodule_push_check(const char *path, const char *head,
argv_array_push(&cp.args, head);
argv_array_push(&cp.args, remote->name);
- for (i = 0; i < refspec_nr; i++)
- argv_array_push(&cp.args, refspec[i]);
+ for (i = 0; i < rs->raw_nr; i++)
+ argv_array_push(&cp.args, rs->raw[i]);
prepare_submodule_repo_env(&cp.env_array);
cp.git_cmd = 1;
@@ -1041,7 +1044,7 @@ static void submodule_push_check(const char *path, const char *head,
int push_unpushed_submodules(struct oid_array *commits,
const struct remote *remote,
- const char **refspec, int refspec_nr,
+ const struct refspec *rs,
const struct string_list *push_options,
int dry_run)
{
@@ -1067,8 +1070,7 @@ int push_unpushed_submodules(struct oid_array *commits,
for (i = 0; i < needs_pushing.nr; i++)
submodule_push_check(needs_pushing.items[i].string,
- head, remote,
- refspec, refspec_nr);
+ head, remote, rs);
free(head);
}
@@ -1076,7 +1078,7 @@ int push_unpushed_submodules(struct oid_array *commits,
for (i = 0; i < needs_pushing.nr; i++) {
const char *path = needs_pushing.items[i].string;
fprintf(stderr, "Pushing submodule '%s'\n", path);
- if (!push_submodule(path, remote, refspec, refspec_nr,
+ if (!push_submodule(path, remote, rs,
push_options, dry_run)) {
fprintf(stderr, "Unable to push submodule '%s'\n", path);
ret = 0;
@@ -1113,7 +1115,7 @@ static void calculate_changed_submodule_paths(void)
const struct string_list_item *name;
/* No need to check if there are no submodules configured */
- if (!submodule_from_path(NULL, NULL))
+ if (!submodule_from_path(the_repository, NULL, NULL))
return;
argv_array_push(&argv, "--"); /* argv[0] program name */
@@ -1134,7 +1136,7 @@ static void calculate_changed_submodule_paths(void)
const struct submodule *submodule;
const char *path = NULL;
- submodule = submodule_from_name(&null_oid, name->string);
+ submodule = submodule_from_name(the_repository, &null_oid, name->string);
if (submodule)
path = submodule->path;
else
@@ -1162,7 +1164,7 @@ int submodule_touches_in_range(struct object_id *excl_oid,
int ret;
/* No need to check if there are no submodules configured */
- if (!submodule_from_path(NULL, NULL))
+ if (!submodule_from_path(the_repository, NULL, NULL))
return 0;
argv_array_push(&args, "--"); /* args[0] program name */
@@ -1234,7 +1236,7 @@ static int get_next_submodule(struct child_process *cp,
if (!S_ISGITLINK(ce->ce_mode))
continue;
- submodule = submodule_from_cache(spf->r, &null_oid, ce->name);
+ submodule = submodule_from_path(spf->r, &null_oid, ce->name);
if (!submodule) {
const char *name = default_name_or_path(ce->name);
if (name) {
@@ -1398,7 +1400,7 @@ unsigned is_submodule_modified(const char *path, int ignore_untracked)
buf.buf[0] == '2') {
/* T = line type, XY = status, SSSS = submodule state */
if (buf.len < strlen("T XY SSSS"))
- die("BUG: invalid status --porcelain=2 line %s",
+ BUG("invalid status --porcelain=2 line %s",
buf.buf);
if (buf.buf[5] == 'S' && buf.buf[8] == 'U')
@@ -1567,7 +1569,7 @@ static void submodule_reset_index(const char *path)
get_super_prefix_or_empty(), path);
argv_array_pushl(&cp.args, "read-tree", "-u", "--reset", NULL);
- argv_array_push(&cp.args, EMPTY_TREE_SHA1_HEX);
+ argv_array_push(&cp.args, empty_tree_oid_hex());
if (run_command(&cp))
die("could not reset submodule index");
@@ -1604,10 +1606,10 @@ int submodule_move_head(const char *path,
if (old_head && !is_submodule_populated_gently(path, error_code_ptr))
return 0;
- sub = submodule_from_path(&null_oid, path);
+ sub = submodule_from_path(the_repository, &null_oid, path);
if (!sub)
- die("BUG: could not get submodule information for '%s'", path);
+ BUG("could not get submodule information for '%s'", path);
if (old_head && !(flags & SUBMODULE_MOVE_HEAD_FORCE)) {
/* Check if the submodule has a dirty index. */
@@ -1623,7 +1625,7 @@ int submodule_move_head(const char *path,
} else {
char *gitdir = xstrfmt("%s/modules/%s",
get_git_common_dir(), sub->name);
- connect_work_tree_and_git_dir(path, gitdir);
+ connect_work_tree_and_git_dir(path, gitdir, 0);
free(gitdir);
/* make sure the index is clean as well */
@@ -1633,7 +1635,7 @@ int submodule_move_head(const char *path,
if (old_head && (flags & SUBMODULE_MOVE_HEAD_FORCE)) {
char *gitdir = xstrfmt("%s/modules/%s",
get_git_common_dir(), sub->name);
- connect_work_tree_and_git_dir(path, gitdir);
+ connect_work_tree_and_git_dir(path, gitdir, 1);
free(gitdir);
}
}
@@ -1659,9 +1661,9 @@ int submodule_move_head(const char *path,
argv_array_push(&cp.args, "-m");
if (!(flags & SUBMODULE_MOVE_HEAD_FORCE))
- argv_array_push(&cp.args, old_head ? old_head : EMPTY_TREE_SHA1_HEX);
+ argv_array_push(&cp.args, old_head ? old_head : empty_tree_oid_hex());
- argv_array_push(&cp.args, new_head ? new_head : EMPTY_TREE_SHA1_HEX);
+ argv_array_push(&cp.args, new_head ? new_head : empty_tree_oid_hex());
if (run_command(&cp)) {
ret = -1;
@@ -1699,171 +1701,6 @@ out:
return ret;
}
-static int find_first_merges(struct object_array *result, const char *path,
- struct commit *a, struct commit *b)
-{
- int i, j;
- struct object_array merges = OBJECT_ARRAY_INIT;
- struct commit *commit;
- int contains_another;
-
- char merged_revision[42];
- const char *rev_args[] = { "rev-list", "--merges", "--ancestry-path",
- "--all", merged_revision, NULL };
- struct rev_info revs;
- struct setup_revision_opt rev_opts;
-
- memset(result, 0, sizeof(struct object_array));
- memset(&rev_opts, 0, sizeof(rev_opts));
-
- /* get all revisions that merge commit a */
- xsnprintf(merged_revision, sizeof(merged_revision), "^%s",
- oid_to_hex(&a->object.oid));
- init_revisions(&revs, NULL);
- rev_opts.submodule = path;
- /* FIXME: can't handle linked worktrees in submodules yet */
- revs.single_worktree = path != NULL;
- setup_revisions(ARRAY_SIZE(rev_args)-1, rev_args, &revs, &rev_opts);
-
- /* save all revisions from the above list that contain b */
- if (prepare_revision_walk(&revs))
- die("revision walk setup failed");
- while ((commit = get_revision(&revs)) != NULL) {
- struct object *o = &(commit->object);
- if (in_merge_bases(b, commit))
- add_object_array(o, NULL, &merges);
- }
- reset_revision_walk();
-
- /* Now we've got all merges that contain a and b. Prune all
- * merges that contain another found merge and save them in
- * result.
- */
- for (i = 0; i < merges.nr; i++) {
- struct commit *m1 = (struct commit *) merges.objects[i].item;
-
- contains_another = 0;
- for (j = 0; j < merges.nr; j++) {
- struct commit *m2 = (struct commit *) merges.objects[j].item;
- if (i != j && in_merge_bases(m2, m1)) {
- contains_another = 1;
- break;
- }
- }
-
- if (!contains_another)
- add_object_array(merges.objects[i].item, NULL, result);
- }
-
- object_array_clear(&merges);
- return result->nr;
-}
-
-static void print_commit(struct commit *commit)
-{
- struct strbuf sb = STRBUF_INIT;
- struct pretty_print_context ctx = {0};
- ctx.date_mode.type = DATE_NORMAL;
- format_commit_message(commit, " %h: %m %s", &sb, &ctx);
- fprintf(stderr, "%s\n", sb.buf);
- strbuf_release(&sb);
-}
-
-#define MERGE_WARNING(path, msg) \
- warning("Failed to merge submodule %s (%s)", path, msg);
-
-int merge_submodule(struct object_id *result, const char *path,
- const struct object_id *base, const struct object_id *a,
- const struct object_id *b, int search)
-{
- struct commit *commit_base, *commit_a, *commit_b;
- int parent_count;
- struct object_array merges;
-
- int i;
-
- /* store a in result in case we fail */
- oidcpy(result, a);
-
- /* we can not handle deletion conflicts */
- if (is_null_oid(base))
- return 0;
- if (is_null_oid(a))
- return 0;
- if (is_null_oid(b))
- return 0;
-
- if (add_submodule_odb(path)) {
- MERGE_WARNING(path, "not checked out");
- return 0;
- }
-
- if (!(commit_base = lookup_commit_reference(base)) ||
- !(commit_a = lookup_commit_reference(a)) ||
- !(commit_b = lookup_commit_reference(b))) {
- MERGE_WARNING(path, "commits not present");
- return 0;
- }
-
- /* check whether both changes are forward */
- if (!in_merge_bases(commit_base, commit_a) ||
- !in_merge_bases(commit_base, commit_b)) {
- MERGE_WARNING(path, "commits don't follow merge-base");
- return 0;
- }
-
- /* Case #1: a is contained in b or vice versa */
- if (in_merge_bases(commit_a, commit_b)) {
- oidcpy(result, b);
- return 1;
- }
- if (in_merge_bases(commit_b, commit_a)) {
- oidcpy(result, a);
- return 1;
- }
-
- /*
- * Case #2: There are one or more merges that contain a and b in
- * the submodule. If there is only one, then present it as a
- * suggestion to the user, but leave it marked unmerged so the
- * user needs to confirm the resolution.
- */
-
- /* Skip the search if makes no sense to the calling context. */
- if (!search)
- return 0;
-
- /* find commit which merges them */
- parent_count = find_first_merges(&merges, path, commit_a, commit_b);
- switch (parent_count) {
- case 0:
- MERGE_WARNING(path, "merge following commits not found");
- break;
-
- case 1:
- MERGE_WARNING(path, "not fast-forward");
- fprintf(stderr, "Found a possible merge resolution "
- "for the submodule:\n");
- print_commit((struct commit *) merges.objects[0].item);
- fprintf(stderr,
- "If this is correct simply add it to the index "
- "for example\n"
- "by using:\n\n"
- " git update-index --cacheinfo 160000 %s \"%s\"\n\n"
- "which will accept this suggestion.\n",
- oid_to_hex(&merges.objects[0].item->oid), path);
- break;
-
- default:
- MERGE_WARNING(path, "multiple merges found");
- for (i = 0; i < merges.nr; i++)
- print_commit((struct commit *) merges.objects[i].item);
- }
-
- object_array_clear(&merges);
- return 0;
-}
-
/*
* Embeds a single submodules git directory into the superprojects git dir,
* non recursively.
@@ -1886,7 +1723,7 @@ static void relocate_single_git_dir_into_superproject(const char *prefix,
real_old_git_dir = real_pathdup(old_git_dir, 1);
- sub = submodule_from_path(&null_oid, path);
+ sub = submodule_from_path(the_repository, &null_oid, path);
if (!sub)
die(_("could not lookup name for submodule '%s'"), path);
@@ -1942,11 +1779,11 @@ void absorb_git_dir_into_superproject(const char *prefix,
* superproject did not rewrite the git file links yet,
* fix it now.
*/
- sub = submodule_from_path(&null_oid, path);
+ sub = submodule_from_path(the_repository, &null_oid, path);
if (!sub)
die(_("could not lookup name for submodule '%s'"), path);
connect_work_tree_and_git_dir(path,
- git_path("modules/%s", sub->name));
+ git_path("modules/%s", sub->name), 0);
} else {
/* Is it already absorbed into the superprojects git dir? */
char *real_sub_git_dir = real_pathdup(sub_git_dir, 1);
@@ -1965,7 +1802,7 @@ void absorb_git_dir_into_superproject(const char *prefix,
struct strbuf sb = STRBUF_INIT;
if (flags & ~ABSORB_GITDIR_RECURSE_SUBMODULES)
- die("BUG: we don't know how to pass the flags down?");
+ BUG("we don't know how to pass the flags down?");
strbuf_addstr(&sb, get_super_prefix_or_empty());
strbuf_addstr(&sb, path);
@@ -2043,7 +1880,7 @@ const char *get_superproject_working_tree(void)
if (super_sub_len > cwd_len ||
strcmp(&cwd[cwd_len - super_sub_len], super_sub))
- die (_("BUG: returned path string doesn't match cwd?"));
+ BUG("returned path string doesn't match cwd?");
super_wt = xstrdup(cwd);
super_wt[cwd_len - super_sub_len] = '\0';
@@ -2088,7 +1925,7 @@ int submodule_to_gitdir(struct strbuf *buf, const char *submodule)
strbuf_addstr(buf, git_dir);
}
if (!is_git_directory(buf->buf)) {
- sub = submodule_from_path(&null_oid, submodule);
+ sub = submodule_from_path(the_repository, &null_oid, submodule);
if (!sub) {
ret = -1;
goto cleanup;
diff --git a/submodule.h b/submodule.h
index 9589f13..a2871d0 100644
--- a/submodule.h
+++ b/submodule.h
@@ -89,10 +89,8 @@ extern int submodule_uses_gitfile(const char *path);
#define SUBMODULE_REMOVAL_IGNORE_UNTRACKED (1<<1)
#define SUBMODULE_REMOVAL_IGNORE_IGNORED_UNTRACKED (1<<2)
extern int bad_to_remove_submodule(const char *path, unsigned flags);
-extern int merge_submodule(struct object_id *result, const char *path,
- const struct object_id *base,
- const struct object_id *a,
- const struct object_id *b, int search);
+
+int add_submodule_odb(const char *path);
/* Checks if there are submodule changes in a..b. */
extern int submodule_touches_in_range(struct object_id *a,
@@ -100,12 +98,12 @@ extern int submodule_touches_in_range(struct object_id *a,
extern int find_unpushed_submodules(struct oid_array *commits,
const char *remotes_name,
struct string_list *needs_pushing);
+struct refspec;
extern int push_unpushed_submodules(struct oid_array *commits,
const struct remote *remote,
- const char **refspec, int refspec_nr,
+ const struct refspec *rs,
const struct string_list *push_options,
int dry_run);
-extern void connect_work_tree_and_git_dir(const char *work_tree, const char *git_dir);
/*
* Given a submodule path (as in the index), return the repository
* path of that submodule in 'buf'. Return -1 on error or when the
diff --git a/t/README b/t/README
index 24ddebf..8373a27 100644
--- a/t/README
+++ b/t/README
@@ -293,6 +293,28 @@ and know what setup is needed for it. Or when you want to run
everything up to a certain test.
+Running tests with special setups
+---------------------------------
+
+The whole test suite could be run to test some special features
+that cannot be easily covered by a few specific test cases. These
+could be enabled by running the test suite with correct GIT_TEST_
+environment set.
+
+GIT_TEST_SPLIT_INDEX=<boolean> forces split-index mode on the whole
+test suite. Accept any boolean values that are accepted by git-config.
+
+GIT_TEST_FULL_IN_PACK_ARRAY=<boolean> exercises the uncommon
+pack-objects code path where there are more than 1024 packs even if
+the actual number of packs in repository is below this limit. Accept
+any boolean values that are accepted by git-config.
+
+GIT_TEST_OE_SIZE=<n> exercises the uncommon pack-objects code path
+where we do not cache object size in memory and read it from existing
+packs on demand. This normally only happens when the object size is
+over 2GB. This variable forces the code path on any object larger than
+<n> bytes.
+
Naming Tests
------------
diff --git a/t/diff-lib.sh b/t/diff-lib.sh
index c211dc4..2de880f 100644
--- a/t/diff-lib.sh
+++ b/t/diff-lib.sh
@@ -1,6 +1,6 @@
:
-sanitize_diff_raw='/^:/s/ '"\($_x40\)"' '"\($_x40\)"' \([A-Z]\)[0-9]* / \1 \2 \3# /'
+sanitize_diff_raw='/^:/s/ '"\($OID_REGEX\)"' '"\($OID_REGEX\)"' \([A-Z]\)[0-9]* / \1 \2 \3# /'
compare_diff_raw () {
# When heuristics are improved, the score numbers would change.
# Ignore them while comparing.
@@ -12,7 +12,7 @@ compare_diff_raw () {
test_cmp .tmp-1 .tmp-2 && rm -f .tmp-1 .tmp-2
}
-sanitize_diff_raw_z='/^:/s/ '"$_x40"' '"$_x40"' \([A-Z]\)[0-9]*$/ X X \1#/'
+sanitize_diff_raw_z='/^:/s/ '"$OID_REGEX"' '"$OID_REGEX"' \([A-Z]\)[0-9]*$/ X X \1#/'
compare_diff_raw_z () {
# When heuristics are improved, the score numbers would change.
# Ignore them while comparing.
diff --git a/t/helper/test-chmtime.c b/t/helper/test-chmtime.c
index 1790cea..aa22af4 100644
--- a/t/helper/test-chmtime.c
+++ b/t/helper/test-chmtime.c
@@ -18,20 +18,30 @@
*
* Examples:
*
- * To just print the mtime use --verbose and set the file mtime offset to 0:
+ * To print the mtime and the file name use --verbose and set
+ * the file mtime offset to 0:
*
* test-tool chmtime -v +0 file
*
+ * To print only the mtime use --get:
+ *
+ * test-tool chmtime --get file
+ *
* To set the mtime to current time:
*
* test-tool chmtime =+0 file
*
+ * To set the file mtime offset to +1 and print the new value:
+ *
+ * test-tool chmtime --get +1 file
+ *
*/
#include "test-tool.h"
#include "git-compat-util.h"
#include <utime.h>
-static const char usage_str[] = "-v|--verbose (+|=|=+|=-|-)<seconds> <file>...";
+static const char usage_str[] =
+ "(-v|--verbose|-g|--get) (+|=|=+|=-|-)<seconds> <file>...";
static int timespec_arg(const char *arg, long int *set_time, int *set_eq)
{
@@ -47,7 +57,6 @@ static int timespec_arg(const char *arg, long int *set_time, int *set_eq)
}
*set_time = strtol(timespec, &test, 10);
if (*test) {
- fprintf(stderr, "Not a base-10 integer: %s\n", arg + 1);
return 0;
}
if ((*set_eq && *set_time < 0) || *set_eq == 2) {
@@ -60,6 +69,7 @@ static int timespec_arg(const char *arg, long int *set_time, int *set_eq)
int cmd__chmtime(int argc, const char **argv)
{
static int verbose;
+ static int get;
int i = 1;
/* no mtime change by default */
@@ -69,18 +79,34 @@ int cmd__chmtime(int argc, const char **argv)
if (argc < 3)
goto usage;
- if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0) {
+ if (strcmp(argv[i], "--get") == 0 || strcmp(argv[i], "-g") == 0) {
+ get = 1;
+ ++i;
+ } else if (strcmp(argv[i], "--verbose") == 0 || strcmp(argv[i], "-v") == 0) {
verbose = 1;
++i;
}
- if (timespec_arg(argv[i], &set_time, &set_eq))
+
+ if (i == argc) {
+ goto usage;
+ }
+
+ if (timespec_arg(argv[i], &set_time, &set_eq)) {
++i;
- else
+ } else {
+ if (get == 0) {
+ fprintf(stderr, "Not a base-10 integer: %s\n", argv[i] + 1);
+ goto usage;
+ }
+ }
+
+ if (i == argc)
goto usage;
for (; i < argc; i++) {
struct stat sb;
struct utimbuf utb;
+ uintmax_t mtime;
if (stat(argv[i], &sb) < 0) {
fprintf(stderr, "Failed to stat %s: %s\n",
@@ -100,8 +126,10 @@ int cmd__chmtime(int argc, const char **argv)
utb.actime = sb.st_atime;
utb.modtime = set_eq ? set_time : sb.st_mtime + set_time;
- if (verbose) {
- uintmax_t mtime = utb.modtime < 0 ? 0: utb.modtime;
+ mtime = utb.modtime < 0 ? 0: utb.modtime;
+ if (get) {
+ printf("%"PRIuMAX"\n", mtime);
+ } else if (verbose) {
printf("%"PRIuMAX"\t%s\n", mtime, argv[i]);
}
diff --git a/t/helper/test-drop-caches.c b/t/helper/test-drop-caches.c
index 8387608..d6bcfdd 100644
--- a/t/helper/test-drop-caches.c
+++ b/t/helper/test-drop-caches.c
@@ -2,6 +2,7 @@
#include "git-compat-util.h"
#if defined(GIT_WINDOWS_NATIVE)
+#include "lazyload.h"
static int cmd_sync(void)
{
@@ -82,8 +83,7 @@ static int cmd_dropcaches(void)
{
HANDLE hProcess = GetCurrentProcess();
HANDLE hToken;
- HMODULE ntdll;
- DWORD(WINAPI *NtSetSystemInformation)(INT, PVOID, ULONG);
+ DECLARE_PROC_ADDR(ntdll.dll, DWORD, NtSetSystemInformation, INT, PVOID, ULONG);
SYSTEM_MEMORY_LIST_COMMAND command;
int status;
@@ -95,14 +95,8 @@ static int cmd_dropcaches(void)
CloseHandle(hToken);
- ntdll = LoadLibrary("ntdll.dll");
- if (!ntdll)
- return error("Can't load ntdll.dll, wrong Windows version?");
-
- NtSetSystemInformation =
- (DWORD(WINAPI *)(INT, PVOID, ULONG))GetProcAddress(ntdll, "NtSetSystemInformation");
- if (!NtSetSystemInformation)
- return error("Can't get function addresses, wrong Windows version?");
+ if (!INIT_PROC_ADDR(NtSetSystemInformation))
+ return error("Could not find NtSetSystemInformation() function");
command = MemoryPurgeStandbyList;
status = NtSetSystemInformation(
@@ -115,8 +109,6 @@ static int cmd_dropcaches(void)
else if (status != STATUS_SUCCESS)
error("Unable to execute the memory list command %d", status);
- FreeLibrary(ntdll);
-
return status;
}
diff --git a/t/helper/test-dump-split-index.c b/t/helper/test-dump-split-index.c
index 4e2fdb5..63c689d 100644
--- a/t/helper/test-dump-split-index.c
+++ b/t/helper/test-dump-split-index.c
@@ -14,13 +14,13 @@ int cmd__dump_split_index(int ac, const char **av)
int i;
do_read_index(&the_index, av[1], 1);
- printf("own %s\n", sha1_to_hex(the_index.sha1));
+ printf("own %s\n", oid_to_hex(&the_index.oid));
si = the_index.split_index;
if (!si) {
printf("not a split index\n");
return 0;
}
- printf("base %s\n", sha1_to_hex(si->base_sha1));
+ printf("base %s\n", oid_to_hex(&si->base_oid));
for (i = 0; i < the_index.cache_nr; i++) {
struct cache_entry *ce = the_index.cache[i];
printf("%06o %s %d\t%s\n", ce->ce_mode,
diff --git a/t/helper/test-dump-untracked-cache.c b/t/helper/test-dump-untracked-cache.c
index d7c55c2..bd92fb3 100644
--- a/t/helper/test-dump-untracked-cache.c
+++ b/t/helper/test-dump-untracked-cache.c
@@ -23,7 +23,7 @@ static void dump(struct untracked_cache_dir *ucd, struct strbuf *base)
len = base->len;
strbuf_addf(base, "%s/", ucd->name);
printf("%s %s", base->buf,
- sha1_to_hex(ucd->exclude_sha1));
+ oid_to_hex(&ucd->exclude_oid));
if (ucd->recurse)
fputs(" recurse", stdout);
if (ucd->check_only)
diff --git a/t/helper/test-example-decorate.c b/t/helper/test-example-decorate.c
index 081115b..a20a616 100644
--- a/t/helper/test-example-decorate.c
+++ b/t/helper/test-example-decorate.c
@@ -30,10 +30,10 @@ int cmd__example_decorate(int argc, const char **argv)
two = lookup_unknown_object(two_oid.hash);
ret = add_decoration(&n, one, &decoration_a);
if (ret)
- die("BUG: when adding a brand-new object, NULL should be returned");
+ BUG("when adding a brand-new object, NULL should be returned");
ret = add_decoration(&n, two, NULL);
if (ret)
- die("BUG: when adding a brand-new object, NULL should be returned");
+ BUG("when adding a brand-new object, NULL should be returned");
/*
* When re-adding an already existing object, the old decoration is
@@ -41,10 +41,10 @@ int cmd__example_decorate(int argc, const char **argv)
*/
ret = add_decoration(&n, one, NULL);
if (ret != &decoration_a)
- die("BUG: when readding an already existing object, existing decoration should be returned");
+ BUG("when readding an already existing object, existing decoration should be returned");
ret = add_decoration(&n, two, &decoration_b);
if (ret)
- die("BUG: when readding an already existing object, existing decoration should be returned");
+ BUG("when readding an already existing object, existing decoration should be returned");
/*
* Lookup returns the added declarations, or NULL if the object was
@@ -52,14 +52,14 @@ int cmd__example_decorate(int argc, const char **argv)
*/
ret = lookup_decoration(&n, one);
if (ret)
- die("BUG: lookup should return added declaration");
+ BUG("lookup should return added declaration");
ret = lookup_decoration(&n, two);
if (ret != &decoration_b)
- die("BUG: lookup should return added declaration");
+ BUG("lookup should return added declaration");
three = lookup_unknown_object(three_oid.hash);
ret = lookup_decoration(&n, three);
if (ret)
- die("BUG: lookup for unknown object should return NULL");
+ BUG("lookup for unknown object should return NULL");
/*
* The user can also loop through all entries.
@@ -69,7 +69,7 @@ int cmd__example_decorate(int argc, const char **argv)
objects_noticed++;
}
if (objects_noticed != 2)
- die("BUG: should have 2 objects");
+ BUG("should have 2 objects");
return 0;
}
diff --git a/t/helper/test-path-utils.c b/t/helper/test-path-utils.c
index e115d44..ae091d9 100644
--- a/t/helper/test-path-utils.c
+++ b/t/helper/test-path-utils.c
@@ -1,6 +1,7 @@
#include "test-tool.h"
#include "cache.h"
#include "string-list.h"
+#include "utf8.h"
/*
* A "string_list_each_func_t" function that normalizes an entry from
@@ -171,6 +172,11 @@ static struct test_data dirname_data[] = {
{ NULL, NULL }
};
+static int is_dotgitmodules(const char *path)
+{
+ return is_hfs_dotgitmodules(path) || is_ntfs_dotgitmodules(path);
+}
+
int cmd__path_utils(int argc, const char **argv)
{
if (argc == 3 && !strcmp(argv[1], "normalize_path_copy")) {
@@ -271,6 +277,20 @@ int cmd__path_utils(int argc, const char **argv)
if (argc == 2 && !strcmp(argv[1], "dirname"))
return test_function(dirname_data, posix_dirname, argv[1]);
+ if (argc > 2 && !strcmp(argv[1], "is_dotgitmodules")) {
+ int res = 0, expect = 1, i;
+ for (i = 2; i < argc; i++)
+ if (!strcmp("--not", argv[i]))
+ expect = !expect;
+ else if (expect != is_dotgitmodules(argv[i]))
+ res = error("'%s' is %s.gitmodules", argv[i],
+ expect ? "not " : "");
+ else
+ fprintf(stderr, "ok: '%s' is %s.gitmodules\n",
+ argv[i], expect ? "" : "not ");
+ return !!res;
+ }
+
fprintf(stderr, "%s: unknown function name: %s\n", argv[0],
argv[1] ? argv[1] : "(there was none)");
return 1;
diff --git a/t/helper/test-pkt-line.c b/t/helper/test-pkt-line.c
new file mode 100644
index 0000000..0f19e53
--- /dev/null
+++ b/t/helper/test-pkt-line.c
@@ -0,0 +1,64 @@
+#include "pkt-line.h"
+
+static void pack_line(const char *line)
+{
+ if (!strcmp(line, "0000") || !strcmp(line, "0000\n"))
+ packet_flush(1);
+ else if (!strcmp(line, "0001") || !strcmp(line, "0001\n"))
+ packet_delim(1);
+ else
+ packet_write_fmt(1, "%s", line);
+}
+
+static void pack(int argc, const char **argv)
+{
+ if (argc) { /* read from argv */
+ int i;
+ for (i = 0; i < argc; i++)
+ pack_line(argv[i]);
+ } else { /* read from stdin */
+ char line[LARGE_PACKET_MAX];
+ while (fgets(line, sizeof(line), stdin)) {
+ pack_line(line);
+ }
+ }
+}
+
+static void unpack(void)
+{
+ struct packet_reader reader;
+ packet_reader_init(&reader, 0, NULL, 0,
+ PACKET_READ_GENTLE_ON_EOF |
+ PACKET_READ_CHOMP_NEWLINE);
+
+ while (packet_reader_read(&reader) != PACKET_READ_EOF) {
+ switch (reader.status) {
+ case PACKET_READ_EOF:
+ break;
+ case PACKET_READ_NORMAL:
+ printf("%s\n", reader.line);
+ break;
+ case PACKET_READ_FLUSH:
+ printf("0000\n");
+ break;
+ case PACKET_READ_DELIM:
+ printf("0001\n");
+ break;
+ }
+ }
+}
+
+int cmd_main(int argc, const char **argv)
+{
+ if (argc < 2)
+ die("too few arguments");
+
+ if (!strcmp(argv[1], "pack"))
+ pack(argc - 2, argv + 2);
+ else if (!strcmp(argv[1], "unpack"))
+ unpack();
+ else
+ die("invalid argument '%s'", argv[1]);
+
+ return 0;
+}
diff --git a/t/helper/test-ref-store.c b/t/helper/test-ref-store.c
index 7c4f437..e9e0541 100644
--- a/t/helper/test-ref-store.c
+++ b/t/helper/test-ref-store.c
@@ -3,6 +3,7 @@
#include "refs.h"
#include "worktree.h"
#include "object-store.h"
+#include "repository.h"
static const char *notnull(const char *arg, const char *name)
{
@@ -23,7 +24,7 @@ static const char **get_store(const char **argv, struct ref_store **refs)
if (!argv[0]) {
die("ref store required");
} else if (!strcmp(argv[0], "main")) {
- *refs = get_main_ref_store();
+ *refs = get_main_ref_store(the_repository);
} else if (skip_prefix(argv[0], "submodule:", &gitdir)) {
struct strbuf sb = STRBUF_INIT;
int ret;
diff --git a/t/helper/test-scrap-cache-tree.c b/t/helper/test-scrap-cache-tree.c
index d26d3e7..393f160 100644
--- a/t/helper/test-scrap-cache-tree.c
+++ b/t/helper/test-scrap-cache-tree.c
@@ -4,10 +4,10 @@
#include "tree.h"
#include "cache-tree.h"
-static struct lock_file index_lock;
-
int cmd__scrap_cache_tree(int ac, const char **av)
{
+ struct lock_file index_lock = LOCK_INIT;
+
setup_git_directory();
hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
if (read_cache() < 0)
diff --git a/t/helper/test-submodule-config.c b/t/helper/test-submodule-config.c
index 5c6e4b0..e269274 100644
--- a/t/helper/test-submodule-config.c
+++ b/t/helper/test-submodule-config.c
@@ -49,9 +49,11 @@ int cmd__submodule_config(int argc, const char **argv)
die_usage(argc, argv, "Commit not found.");
if (lookup_name) {
- submodule = submodule_from_name(&commit_oid, path_or_name);
+ submodule = submodule_from_name(the_repository,
+ &commit_oid, path_or_name);
} else
- submodule = submodule_from_path(&commit_oid, path_or_name);
+ submodule = submodule_from_path(the_repository,
+ &commit_oid, path_or_name);
if (!submodule)
die_usage(argc, argv, "Submodule not found.");
@@ -65,7 +67,7 @@ int cmd__submodule_config(int argc, const char **argv)
arg += 2;
}
- submodule_free();
+ submodule_free(the_repository);
return 0;
}
diff --git a/t/helper/test-tool.c b/t/helper/test-tool.c
index 87066ce..805a45d 100644
--- a/t/helper/test-tool.c
+++ b/t/helper/test-tool.c
@@ -48,6 +48,7 @@ int cmd_main(int argc, const char **argv)
{
int i;
+ BUG_exit_code = 99;
if (argc < 2)
die("I need a test name!");
diff --git a/t/helper/test-write-cache.c b/t/helper/test-write-cache.c
index 017dc30..8837717 100644
--- a/t/helper/test-write-cache.c
+++ b/t/helper/test-write-cache.c
@@ -2,22 +2,18 @@
#include "cache.h"
#include "lockfile.h"
-static struct lock_file index_lock;
-
int cmd__write_cache(int argc, const char **argv)
{
- int i, cnt = 1, lockfd;
+ struct lock_file index_lock = LOCK_INIT;
+ int i, cnt = 1;
if (argc == 2)
cnt = strtol(argv[1], NULL, 0);
setup_git_directory();
read_cache();
for (i = 0; i < cnt; i++) {
- lockfd = hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
- if (0 <= lockfd) {
- write_locked_index(&the_index, &index_lock, COMMIT_LOCK);
- } else {
- rollback_lock_file(&index_lock);
- }
+ hold_locked_index(&index_lock, LOCK_DIE_ON_ERROR);
+ if (write_locked_index(&the_index, &index_lock, COMMIT_LOCK))
+ die("unable to write index file");
}
return 0;
diff --git a/t/lib-diff-alternative.sh b/t/lib-diff-alternative.sh
index 8b4dbf2..8d1e408 100644
--- a/t/lib-diff-alternative.sh
+++ b/t/lib-diff-alternative.sh
@@ -59,9 +59,11 @@ int main(int argc, char **argv)
}
EOF
- cat >expect <<\EOF
+ file1=$(git rev-parse --short $(git hash-object file1))
+ file2=$(git rev-parse --short $(git hash-object file2))
+ cat >expect <<EOF
diff --git a/file1 b/file2
-index 6faa5a3..e3af329 100644
+index $file1..$file2 100644
--- a/file1
+++ b/file2
@@ -1,26 +1,25 @@
@@ -136,9 +138,11 @@ e
f
EOF
- cat >expect <<\EOF
+ uniq1=$(git rev-parse --short $(git hash-object uniq1))
+ uniq2=$(git rev-parse --short $(git hash-object uniq2))
+ cat >expect <<EOF
diff --git a/uniq1 b/uniq2
-index b414108..0fdf397 100644
+index $uniq1..$uniq2 100644
--- a/uniq1
+++ b/uniq2
@@ -1,6 +1,6 @@
diff --git a/t/lib-pack.sh b/t/lib-pack.sh
index 5010782..c4d907a 100644
--- a/t/lib-pack.sh
+++ b/t/lib-pack.sh
@@ -79,6 +79,18 @@ pack_obj () {
;;
esac
+ # If it's not a delta, we can convince pack-objects to generate a pack
+ # with just our entry, and then strip off the header (12 bytes) and
+ # trailer (20 bytes).
+ if test -z "$2"
+ then
+ echo "$1" | git pack-objects --stdout >pack_obj.tmp &&
+ size=$(wc -c <pack_obj.tmp) &&
+ dd if=pack_obj.tmp bs=1 count=$((size - 20 - 12)) skip=12 &&
+ rm -f pack_obj.tmp
+ return
+ fi
+
echo >&2 "BUG: don't know how to print $1${2:+ (from $2)}"
return 1
}
diff --git a/t/perf/aggregate.perl b/t/perf/aggregate.perl
index 48637ef..bc86516 100755
--- a/t/perf/aggregate.perl
+++ b/t/perf/aggregate.perl
@@ -4,6 +4,7 @@ use lib '../../perl/build/lib';
use strict;
use warnings;
use JSON;
+use Getopt::Long;
use Git;
sub get_times {
@@ -36,46 +37,34 @@ sub format_times {
return $out;
}
+sub usage {
+ print <<EOT;
+./aggregate.perl [options] [--] [<dir_or_rev>...] [--] [<test_script>...] >
+
+ Options:
+ --codespeed * Format output for Codespeed
+ --reponame <str> * Send given reponame to codespeed
+ --sort-by <str> * Sort output (only "regression" criteria is supported)
+ --subsection <str> * Use results from given subsection
+
+EOT
+ exit(1);
+}
+
my (@dirs, %dirnames, %dirabbrevs, %prefixes, @tests,
$codespeed, $sortby, $subsection, $reponame);
+
+Getopt::Long::Configure qw/ require_order /;
+
+my $rc = GetOptions("codespeed" => \$codespeed,
+ "reponame=s" => \$reponame,
+ "sort-by=s" => \$sortby,
+ "subsection=s" => \$subsection);
+usage() unless $rc;
+
while (scalar @ARGV) {
my $arg = $ARGV[0];
my $dir;
- if ($arg eq "--codespeed") {
- $codespeed = 1;
- shift @ARGV;
- next;
- }
- if ($arg =~ /--sort-by(?:=(.*))?/) {
- shift @ARGV;
- if (defined $1) {
- $sortby = $1;
- } else {
- $sortby = shift @ARGV;
- if (! defined $sortby) {
- die "'--sort-by' requires an argument";
- }
- }
- next;
- }
- if ($arg eq "--subsection") {
- shift @ARGV;
- $subsection = $ARGV[0];
- shift @ARGV;
- if (! $subsection) {
- die "empty subsection";
- }
- next;
- }
- if ($arg eq "--reponame") {
- shift @ARGV;
- $reponame = $ARGV[0];
- shift @ARGV;
- if (! $reponame) {
- die "empty reponame";
- }
- next;
- }
last if -f $arg or $arg eq "--";
if (! -d $arg) {
my $rev = Git::command_oneline(qw(rev-parse --verify), $arg);
@@ -225,7 +214,8 @@ sub print_sorted_results {
my ($sortby) = @_;
if ($sortby ne "regression") {
- die "only 'regression' is supported as '--sort-by' argument";
+ print "Only 'regression' is supported as '--sort-by' argument\n";
+ usage();
}
my @evolutions;
diff --git a/t/perf/bisect_regression b/t/perf/bisect_regression
new file mode 100755
index 0000000..a94d995
--- /dev/null
+++ b/t/perf/bisect_regression
@@ -0,0 +1,73 @@
+#!/bin/sh
+
+# Read a line coming from `./aggregate.perl --sort-by regression ...`
+# and automatically bisect to find the commit responsible for the
+# performance regression.
+#
+# Lines from `./aggregate.perl --sort-by regression ...` look like:
+#
+# +100.0% p7821-grep-engines-fixed.1 0.04(0.10+0.03) 0.08(0.11+0.08) v2.14.3 v2.15.1
+# +33.3% p7820-grep-engines.1 0.03(0.08+0.02) 0.04(0.08+0.02) v2.14.3 v2.15.1
+#
+
+die () {
+ echo >&2 "error: $*"
+ exit 1
+}
+
+while [ $# -gt 0 ]; do
+ arg="$1"
+ case "$arg" in
+ --help)
+ echo "usage: $0 [--config file] [--subsection subsection]"
+ exit 0
+ ;;
+ --config)
+ shift
+ GIT_PERF_CONFIG_FILE=$(cd "$(dirname "$1")"; pwd)/$(basename "$1")
+ export GIT_PERF_CONFIG_FILE
+ shift ;;
+ --subsection)
+ shift
+ GIT_PERF_SUBSECTION="$1"
+ export GIT_PERF_SUBSECTION
+ shift ;;
+ --*)
+ die "unrecognised option: '$arg'" ;;
+ *)
+ die "unknown argument '$arg'"
+ ;;
+ esac
+done
+
+read -r regression subtest oldtime newtime oldrev newrev
+
+test_script=$(echo "$subtest" | sed -e 's/\(.*\)\.[0-9]*$/\1.sh/')
+test_number=$(echo "$subtest" | sed -e 's/.*\.\([0-9]*\)$/\1/')
+
+# oldtime and newtime are decimal number, not integers
+
+oldtime=$(echo "$oldtime" | sed -e 's/^\([0-9]\+\.[0-9]\+\).*$/\1/')
+newtime=$(echo "$newtime" | sed -e 's/^\([0-9]\+\.[0-9]\+\).*$/\1/')
+
+test $(echo "$newtime" "$oldtime" | awk '{ print ($1 > $2) }') = 1 ||
+ die "New time '$newtime' shoud be greater than old time '$oldtime'"
+
+tmpdir=$(mktemp -d -t bisect_regression_XXXXXX) || die "Failed to create temp directory"
+echo "$oldtime" >"$tmpdir/oldtime" || die "Failed to write to '$tmpdir/oldtime'"
+echo "$newtime" >"$tmpdir/newtime" || die "Failed to write to '$tmpdir/newtime'"
+
+# Bisecting must be performed from the top level directory (even with --no-checkout)
+(
+ toplevel_dir=$(git rev-parse --show-toplevel) || die "Failed to find top level directory"
+ cd "$toplevel_dir" || die "Failed to cd into top level directory '$toplevel_dir'"
+
+ git bisect start --no-checkout "$newrev" "$oldrev" || die "Failed to start bisecting"
+
+ git bisect run t/perf/bisect_run_script "$test_script" "$test_number" "$tmpdir"
+ res="$?"
+
+ git bisect reset
+
+ exit "$res"
+)
diff --git a/t/perf/bisect_run_script b/t/perf/bisect_run_script
new file mode 100755
index 0000000..3ebaf15
--- /dev/null
+++ b/t/perf/bisect_run_script
@@ -0,0 +1,53 @@
+#!/bin/sh
+
+script="$1"
+test_number="$2"
+info_dir="$3"
+
+# This aborts the bisection immediately
+die () {
+ echo >&2 "error: $*"
+ exit 255
+}
+
+bisect_head=$(git rev-parse --verify BISECT_HEAD) || die "Failed to find BISECT_HEAD ref"
+
+script_number=$(echo "$script" | sed -e "s/^p\([0-9]*\).*\$/\1/") || die "Failed to get script number for '$script'"
+
+oldtime=$(cat "$info_dir/oldtime") || die "Failed to access '$info_dir/oldtime'"
+newtime=$(cat "$info_dir/newtime") || die "Failed to access '$info_dir/newtime'"
+
+cd t/perf || die "Failed to cd into 't/perf'"
+
+result_file="$info_dir/perf_${script_number}_${bisect_head}_results.txt"
+
+GIT_PERF_DIRS_OR_REVS="$bisect_head"
+export GIT_PERF_DIRS_OR_REVS
+
+# Don't use codespeed
+GIT_PERF_CODESPEED_OUTPUT=
+GIT_PERF_SEND_TO_CODESPEED=
+export GIT_PERF_CODESPEED_OUTPUT
+export GIT_PERF_SEND_TO_CODESPEED
+
+./run "$script" >"$result_file" 2>&1 || die "Failed to run perf test '$script'"
+
+rtime=$(sed -n "s/^$script_number\.$test_number:.*\([0-9]\+\.[0-9]\+\)(.*).*\$/\1/p" "$result_file")
+
+echo "newtime: $newtime"
+echo "rtime: $rtime"
+echo "oldtime: $oldtime"
+
+# Compare ($newtime - $rtime) with ($rtime - $oldtime)
+# Times are decimal number, not integers
+
+if test $(echo "$newtime" "$rtime" "$oldtime" | awk '{ print ($1 - $2 > $2 - $3) }') = 1
+then
+ # Current commit is considered "good/old"
+ echo "$rtime" >"$info_dir/oldtime"
+ exit 0
+else
+ # Current commit is considered "bad/new"
+ echo "$rtime" >"$info_dir/newtime"
+ exit 1
+fi
diff --git a/t/perf/run b/t/perf/run
index 213da5d..9aaa733 100755
--- a/t/perf/run
+++ b/t/perf/run
@@ -1,21 +1,34 @@
#!/bin/sh
-case "$1" in
+die () {
+ echo >&2 "error: $*"
+ exit 1
+}
+
+while [ $# -gt 0 ]; do
+ arg="$1"
+ case "$arg" in
+ --)
+ break ;;
--help)
- echo "usage: $0 [--config file] [other_git_tree...] [--] [test_scripts]"
- exit 0
- ;;
+ echo "usage: $0 [--config file] [--subsection subsec] [other_git_tree...] [--] [test_scripts]"
+ exit 0 ;;
--config)
shift
GIT_PERF_CONFIG_FILE=$(cd "$(dirname "$1")"; pwd)/$(basename "$1")
export GIT_PERF_CONFIG_FILE
shift ;;
-esac
-
-die () {
- echo >&2 "error: $*"
- exit 1
-}
+ --subsection)
+ shift
+ GIT_PERF_SUBSECTION="$1"
+ export GIT_PERF_SUBSECTION
+ shift ;;
+ --*)
+ die "unrecognised option: '$arg'" ;;
+ *)
+ break ;;
+ esac
+done
run_one_dir () {
if test $# -eq 0; then
@@ -172,9 +185,32 @@ get_subsections "perf" >test-results/run_subsections.names
if test $(wc -l <test-results/run_subsections.names) -eq 0
then
+ if test -n "$GIT_PERF_SUBSECTION"
+ then
+ if test -n "$GIT_PERF_CONFIG_FILE"
+ then
+ die "no subsections are defined in config file '$GIT_PERF_CONFIG_FILE'"
+ else
+ die "subsection '$GIT_PERF_SUBSECTION' defined without a config file"
+ fi
+ fi
(
run_subsection "$@"
)
+elif test -n "$GIT_PERF_SUBSECTION"
+then
+ egrep "^$GIT_PERF_SUBSECTION\$" test-results/run_subsections.names >/dev/null ||
+ die "subsection '$GIT_PERF_SUBSECTION' not found in '$GIT_PERF_CONFIG_FILE'"
+
+ egrep "^$GIT_PERF_SUBSECTION\$" test-results/run_subsections.names | while read -r subsec
+ do
+ (
+ GIT_PERF_SUBSECTION="$subsec"
+ export GIT_PERF_SUBSECTION
+ echo "======== Run for subsection '$GIT_PERF_SUBSECTION' ========"
+ run_subsection "$@"
+ )
+ done
else
while read -r subsec
do
diff --git a/t/t0000-basic.sh b/t/t0000-basic.sh
index 7fd87dd..af61d08 100755
--- a/t/t0000-basic.sh
+++ b/t/t0000-basic.sh
@@ -839,7 +839,7 @@ test_expect_success 'writing tree out with git write-tree' '
'
# we know the shape and contents of the tree and know the object ID for it.
-test_expect_success 'validate object ID of a known tree' '
+test_expect_success SHA1 'validate object ID of a known tree' '
test "$tree" = 7bb943559a305bdd6bdee2cef6e5df2413c3d30a
'
@@ -882,7 +882,7 @@ test_expect_success 'showing stage with git ls-files --stage' '
git ls-files --stage >current
'
-test_expect_success 'validate git ls-files output for a known tree' '
+test_expect_success SHA1 'validate git ls-files output for a known tree' '
cat >expected <<-\EOF &&
100644 f87290f8eb2cbbea7857214459a0739927eab154 0 path0
120000 15a98433ae33114b085f3eb3bb03b832b3180a01 0 path0sym
@@ -900,7 +900,7 @@ test_expect_success 'writing tree out with git write-tree' '
tree=$(git write-tree)
'
-test_expect_success 'validate object ID for a known tree' '
+test_expect_success SHA1 'validate object ID for a known tree' '
test "$tree" = 087704a96baf1c2d1c869a8b084481e121c88b5b
'
@@ -908,7 +908,7 @@ test_expect_success 'showing tree with git ls-tree' '
git ls-tree $tree >current
'
-test_expect_success 'git ls-tree output for a known tree' '
+test_expect_success SHA1 'git ls-tree output for a known tree' '
cat >expected <<-\EOF &&
100644 blob f87290f8eb2cbbea7857214459a0739927eab154 path0
120000 blob 15a98433ae33114b085f3eb3bb03b832b3180a01 path0sym
@@ -924,7 +924,7 @@ test_expect_success 'showing tree with git ls-tree -r' '
git ls-tree -r $tree >current
'
-test_expect_success 'git ls-tree -r output for a known tree' '
+test_expect_success SHA1 'git ls-tree -r output for a known tree' '
cat >expected <<-\EOF &&
100644 blob f87290f8eb2cbbea7857214459a0739927eab154 path0
120000 blob 15a98433ae33114b085f3eb3bb03b832b3180a01 path0sym
@@ -943,7 +943,7 @@ test_expect_success 'showing tree with git ls-tree -r -t' '
git ls-tree -r -t $tree >current
'
-test_expect_success 'git ls-tree -r output for a known tree' '
+test_expect_success SHA1 'git ls-tree -r output for a known tree' '
cat >expected <<-\EOF &&
100644 blob f87290f8eb2cbbea7857214459a0739927eab154 path0
120000 blob 15a98433ae33114b085f3eb3bb03b832b3180a01 path0sym
@@ -964,7 +964,7 @@ test_expect_success 'writing partial tree out with git write-tree --prefix' '
ptree=$(git write-tree --prefix=path3)
'
-test_expect_success 'validate object ID for a known tree' '
+test_expect_success SHA1 'validate object ID for a known tree' '
test "$ptree" = 21ae8269cacbe57ae09138dcc3a2887f904d02b3
'
@@ -972,7 +972,7 @@ test_expect_success 'writing partial tree out with git write-tree --prefix' '
ptree=$(git write-tree --prefix=path3/subp3)
'
-test_expect_success 'validate object ID for a known tree' '
+test_expect_success SHA1 'validate object ID for a known tree' '
test "$ptree" = 3c5e5399f3a333eddecce7a9b9465b63f65f51e2
'
@@ -1006,7 +1006,7 @@ test_expect_success 'git read-tree followed by write-tree should be idempotent'
test "$newtree" = "$tree"
'
-test_expect_success 'validate git diff-files output for a know cache/work tree state' '
+test_expect_success SHA1 'validate git diff-files output for a know cache/work tree state' '
cat >expected <<\EOF &&
:100644 100644 f87290f8eb2cbbea7857214459a0739927eab154 0000000000000000000000000000000000000000 M path0
:120000 120000 15a98433ae33114b085f3eb3bb03b832b3180a01 0000000000000000000000000000000000000000 M path0sym
@@ -1033,21 +1033,21 @@ test_expect_success 'no diff after checkout and git update-index --refresh' '
################################################################
P=087704a96baf1c2d1c869a8b084481e121c88b5b
-test_expect_success 'git commit-tree records the correct tree in a commit' '
+test_expect_success SHA1 'git commit-tree records the correct tree in a commit' '
commit0=$(echo NO | git commit-tree $P) &&
tree=$(git show --pretty=raw $commit0 |
sed -n -e "s/^tree //p" -e "/^author /q") &&
test "z$tree" = "z$P"
'
-test_expect_success 'git commit-tree records the correct parent in a commit' '
+test_expect_success SHA1 'git commit-tree records the correct parent in a commit' '
commit1=$(echo NO | git commit-tree $P -p $commit0) &&
parent=$(git show --pretty=raw $commit1 |
sed -n -e "s/^parent //p" -e "/^author /q") &&
test "z$commit0" = "z$parent"
'
-test_expect_success 'git commit-tree omits duplicated parent in a commit' '
+test_expect_success SHA1 'git commit-tree omits duplicated parent in a commit' '
commit2=$(echo NO | git commit-tree $P -p $commit0 -p $commit0) &&
parent=$(git show --pretty=raw $commit2 |
sed -n -e "s/^parent //p" -e "/^author /q" |
diff --git a/t/t0028-working-tree-encoding.sh b/t/t0028-working-tree-encoding.sh
new file mode 100755
index 0000000..12b8eb9
--- /dev/null
+++ b/t/t0028-working-tree-encoding.sh
@@ -0,0 +1,245 @@
+#!/bin/sh
+
+test_description='working-tree-encoding conversion via gitattributes'
+
+. ./test-lib.sh
+
+GIT_TRACE_WORKING_TREE_ENCODING=1 && export GIT_TRACE_WORKING_TREE_ENCODING
+
+test_expect_success 'setup test files' '
+ git config core.eol lf &&
+
+ text="hallo there!\ncan you read me?" &&
+ echo "*.utf16 text working-tree-encoding=utf-16" >.gitattributes &&
+ printf "$text" >test.utf8.raw &&
+ printf "$text" | iconv -f UTF-8 -t UTF-16 >test.utf16.raw &&
+ printf "$text" | iconv -f UTF-8 -t UTF-32 >test.utf32.raw &&
+
+ # Line ending tests
+ printf "one\ntwo\nthree\n" >lf.utf8.raw &&
+ printf "one\r\ntwo\r\nthree\r\n" >crlf.utf8.raw &&
+
+ # BOM tests
+ printf "\0a\0b\0c" >nobom.utf16be.raw &&
+ printf "a\0b\0c\0" >nobom.utf16le.raw &&
+ printf "\376\777\0a\0b\0c" >bebom.utf16be.raw &&
+ printf "\777\376a\0b\0c\0" >lebom.utf16le.raw &&
+ printf "\0\0\0a\0\0\0b\0\0\0c" >nobom.utf32be.raw &&
+ printf "a\0\0\0b\0\0\0c\0\0\0" >nobom.utf32le.raw &&
+ printf "\0\0\376\777\0\0\0a\0\0\0b\0\0\0c" >bebom.utf32be.raw &&
+ printf "\777\376\0\0a\0\0\0b\0\0\0c\0\0\0" >lebom.utf32le.raw &&
+
+ # Add only UTF-16 file, we will add the UTF-32 file later
+ cp test.utf16.raw test.utf16 &&
+ cp test.utf32.raw test.utf32 &&
+ git add .gitattributes test.utf16 &&
+ git commit -m initial
+'
+
+test_expect_success 'ensure UTF-8 is stored in Git' '
+ test_when_finished "rm -f test.utf16.git" &&
+
+ git cat-file -p :test.utf16 >test.utf16.git &&
+ test_cmp_bin test.utf8.raw test.utf16.git
+'
+
+test_expect_success 're-encode to UTF-16 on checkout' '
+ test_when_finished "rm -f test.utf16.raw" &&
+
+ rm test.utf16 &&
+ git checkout test.utf16 &&
+ test_cmp_bin test.utf16.raw test.utf16
+'
+
+test_expect_success 'check $GIT_DIR/info/attributes support' '
+ test_when_finished "rm -f test.utf32.git" &&
+ test_when_finished "git reset --hard HEAD" &&
+
+ echo "*.utf32 text working-tree-encoding=utf-32" >.git/info/attributes &&
+ git add test.utf32 &&
+
+ git cat-file -p :test.utf32 >test.utf32.git &&
+ test_cmp_bin test.utf8.raw test.utf32.git
+'
+
+for i in 16 32
+do
+ test_expect_success "check prohibited UTF-${i} BOM" '
+ test_when_finished "git reset --hard HEAD" &&
+
+ echo "*.utf${i}be text working-tree-encoding=utf-${i}be" >>.gitattributes &&
+ echo "*.utf${i}le text working-tree-encoding=utf-${i}LE" >>.gitattributes &&
+
+ # Here we add a UTF-16 (resp. UTF-32) files with BOM (big/little-endian)
+ # but we tell Git to treat it as UTF-16BE/UTF-16LE (resp. UTF-32).
+ # In these cases the BOM is prohibited.
+ cp bebom.utf${i}be.raw bebom.utf${i}be &&
+ test_must_fail git add bebom.utf${i}be 2>err.out &&
+ test_i18ngrep "fatal: BOM is prohibited .* utf-${i}be" err.out &&
+ test_i18ngrep "use UTF-${i} as working-tree-encoding" err.out &&
+
+ cp lebom.utf${i}le.raw lebom.utf${i}be &&
+ test_must_fail git add lebom.utf${i}be 2>err.out &&
+ test_i18ngrep "fatal: BOM is prohibited .* utf-${i}be" err.out &&
+ test_i18ngrep "use UTF-${i} as working-tree-encoding" err.out &&
+
+ cp bebom.utf${i}be.raw bebom.utf${i}le &&
+ test_must_fail git add bebom.utf${i}le 2>err.out &&
+ test_i18ngrep "fatal: BOM is prohibited .* utf-${i}LE" err.out &&
+ test_i18ngrep "use UTF-${i} as working-tree-encoding" err.out &&
+
+ cp lebom.utf${i}le.raw lebom.utf${i}le &&
+ test_must_fail git add lebom.utf${i}le 2>err.out &&
+ test_i18ngrep "fatal: BOM is prohibited .* utf-${i}LE" err.out &&
+ test_i18ngrep "use UTF-${i} as working-tree-encoding" err.out
+ '
+
+ test_expect_success "check required UTF-${i} BOM" '
+ test_when_finished "git reset --hard HEAD" &&
+
+ echo "*.utf${i} text working-tree-encoding=utf-${i}" >>.gitattributes &&
+
+ cp nobom.utf${i}be.raw nobom.utf${i} &&
+ test_must_fail git add nobom.utf${i} 2>err.out &&
+ test_i18ngrep "fatal: BOM is required .* utf-${i}" err.out &&
+ test_i18ngrep "use UTF-${i}BE or UTF-${i}LE" err.out &&
+
+ cp nobom.utf${i}le.raw nobom.utf${i} &&
+ test_must_fail git add nobom.utf${i} 2>err.out &&
+ test_i18ngrep "fatal: BOM is required .* utf-${i}" err.out &&
+ test_i18ngrep "use UTF-${i}BE or UTF-${i}LE" err.out
+ '
+
+ test_expect_success "eol conversion for UTF-${i} encoded files on checkout" '
+ test_when_finished "rm -f crlf.utf${i}.raw lf.utf${i}.raw" &&
+ test_when_finished "git reset --hard HEAD^" &&
+
+ cat lf.utf8.raw | iconv -f UTF-8 -t UTF-${i} >lf.utf${i}.raw &&
+ cat crlf.utf8.raw | iconv -f UTF-8 -t UTF-${i} >crlf.utf${i}.raw &&
+ cp crlf.utf${i}.raw eol.utf${i} &&
+
+ cat >expectIndexLF <<-EOF &&
+ i/lf w/-text attr/text eol.utf${i}
+ EOF
+
+ git add eol.utf${i} &&
+ git commit -m eol &&
+
+ # UTF-${i} with CRLF (Windows line endings)
+ rm eol.utf${i} &&
+ git -c core.eol=crlf checkout eol.utf${i} &&
+ test_cmp_bin crlf.utf${i}.raw eol.utf${i} &&
+
+ # Although the file has CRLF in the working tree,
+ # ensure LF in the index
+ git ls-files --eol eol.utf${i} >actual &&
+ test_cmp expectIndexLF actual &&
+
+ # UTF-${i} with LF (Unix line endings)
+ rm eol.utf${i} &&
+ git -c core.eol=lf checkout eol.utf${i} &&
+ test_cmp_bin lf.utf${i}.raw eol.utf${i} &&
+
+ # The file LF in the working tree, ensure LF in the index
+ git ls-files --eol eol.utf${i} >actual &&
+ test_cmp expectIndexLF actual
+ '
+done
+
+test_expect_success 'check unsupported encodings' '
+ test_when_finished "git reset --hard HEAD" &&
+
+ echo "*.set text working-tree-encoding" >.gitattributes &&
+ printf "set" >t.set &&
+ test_must_fail git add t.set 2>err.out &&
+ test_i18ngrep "true/false are no valid working-tree-encodings" err.out &&
+
+ echo "*.unset text -working-tree-encoding" >.gitattributes &&
+ printf "unset" >t.unset &&
+ git add t.unset &&
+
+ echo "*.empty text working-tree-encoding=" >.gitattributes &&
+ printf "empty" >t.empty &&
+ git add t.empty &&
+
+ echo "*.garbage text working-tree-encoding=garbage" >.gitattributes &&
+ printf "garbage" >t.garbage &&
+ test_must_fail git add t.garbage 2>err.out &&
+ test_i18ngrep "failed to encode" err.out
+'
+
+test_expect_success 'error if encoding round trip is not the same during refresh' '
+ BEFORE_STATE=$(git rev-parse HEAD) &&
+ test_when_finished "git reset --hard $BEFORE_STATE" &&
+
+ # Add and commit a UTF-16 file but skip the "working-tree-encoding"
+ # filter. Consequently, the in-repo representation is UTF-16 and not
+ # UTF-8. This simulates a Git version that has no working tree encoding
+ # support.
+ echo "*.utf16le text working-tree-encoding=utf-16le" >.gitattributes &&
+ echo "hallo" >nonsense.utf16le &&
+ TEST_HASH=$(git hash-object --no-filters -w nonsense.utf16le) &&
+ git update-index --add --cacheinfo 100644 $TEST_HASH nonsense.utf16le &&
+ COMMIT=$(git commit-tree -p $(git rev-parse HEAD) -m "plain commit" $(git write-tree)) &&
+ git update-ref refs/heads/master $COMMIT &&
+
+ test_must_fail git checkout HEAD^ 2>err.out &&
+ test_i18ngrep "error: .* overwritten by checkout:" err.out
+'
+
+test_expect_success 'error if encoding garbage is already in Git' '
+ BEFORE_STATE=$(git rev-parse HEAD) &&
+ test_when_finished "git reset --hard $BEFORE_STATE" &&
+
+ # Skip the UTF-16 filter for the added file
+ # This simulates a Git version that has no checkoutEncoding support
+ cp nobom.utf16be.raw nonsense.utf16 &&
+ TEST_HASH=$(git hash-object --no-filters -w nonsense.utf16) &&
+ git update-index --add --cacheinfo 100644 $TEST_HASH nonsense.utf16 &&
+ COMMIT=$(git commit-tree -p $(git rev-parse HEAD) -m "plain commit" $(git write-tree)) &&
+ git update-ref refs/heads/master $COMMIT &&
+
+ git diff 2>err.out &&
+ test_i18ngrep "error: BOM is required" err.out
+'
+
+test_expect_success 'check roundtrip encoding' '
+ test_when_finished "rm -f roundtrip.shift roundtrip.utf16" &&
+ test_when_finished "git reset --hard HEAD" &&
+
+ text="hallo there!\nroundtrip test here!" &&
+ printf "$text" | iconv -f UTF-8 -t SHIFT-JIS >roundtrip.shift &&
+ printf "$text" | iconv -f UTF-8 -t UTF-16 >roundtrip.utf16 &&
+ echo "*.shift text working-tree-encoding=SHIFT-JIS" >>.gitattributes &&
+
+ # SHIFT-JIS encoded files are round-trip checked by default...
+ GIT_TRACE=1 git add .gitattributes roundtrip.shift 2>&1 |
+ grep "Checking roundtrip encoding for SHIFT-JIS" &&
+ git reset &&
+
+ # ... unless we overwrite the Git config!
+ ! GIT_TRACE=1 git -c core.checkRoundtripEncoding=garbage \
+ add .gitattributes roundtrip.shift 2>&1 |
+ grep "Checking roundtrip encoding for SHIFT-JIS" &&
+ git reset &&
+
+ # UTF-16 encoded files should not be round-trip checked by default...
+ ! GIT_TRACE=1 git add roundtrip.utf16 2>&1 |
+ grep "Checking roundtrip encoding for UTF-16" &&
+ git reset &&
+
+ # ... unless we tell Git to check it!
+ GIT_TRACE=1 git -c core.checkRoundtripEncoding="UTF-16, UTF-32" \
+ add roundtrip.utf16 2>&1 |
+ grep "Checking roundtrip encoding for utf-16" &&
+ git reset &&
+
+ # ... unless we tell Git to check it!
+ # (here we also check that the casing of the encoding is irrelevant)
+ GIT_TRACE=1 git -c core.checkRoundtripEncoding="UTF-32, utf-16" \
+ add roundtrip.utf16 2>&1 |
+ grep "Checking roundtrip encoding for utf-16" &&
+ git reset
+'
+
+test_done
diff --git a/t/t0060-path-utils.sh b/t/t0060-path-utils.sh
index f46e3c4..21a8b53 100755
--- a/t/t0060-path-utils.sh
+++ b/t/t0060-path-utils.sh
@@ -349,4 +349,90 @@ test_submodule_relative_url "(null)" "ssh://hostname:22/repo" "../subrepo" "ssh:
test_submodule_relative_url "(null)" "user@host:path/to/repo" "../subrepo" "user@host:path/to/subrepo"
test_submodule_relative_url "(null)" "user@host:repo" "../subrepo" "user@host:subrepo"
+test_expect_success 'match .gitmodules' '
+ test-tool path-utils is_dotgitmodules \
+ .gitmodules \
+ \
+ .git${u200c}modules \
+ \
+ .Gitmodules \
+ .gitmoduleS \
+ \
+ ".gitmodules " \
+ ".gitmodules." \
+ ".gitmodules " \
+ ".gitmodules. " \
+ ".gitmodules ." \
+ ".gitmodules.." \
+ ".gitmodules " \
+ ".gitmodules. " \
+ ".gitmodules . " \
+ ".gitmodules ." \
+ \
+ ".Gitmodules " \
+ ".Gitmodules." \
+ ".Gitmodules " \
+ ".Gitmodules. " \
+ ".Gitmodules ." \
+ ".Gitmodules.." \
+ ".Gitmodules " \
+ ".Gitmodules. " \
+ ".Gitmodules . " \
+ ".Gitmodules ." \
+ \
+ GITMOD~1 \
+ gitmod~1 \
+ GITMOD~2 \
+ gitmod~3 \
+ GITMOD~4 \
+ \
+ "GITMOD~1 " \
+ "gitmod~2." \
+ "GITMOD~3 " \
+ "gitmod~4. " \
+ "GITMOD~1 ." \
+ "gitmod~2 " \
+ "GITMOD~3. " \
+ "gitmod~4 . " \
+ \
+ GI7EBA~1 \
+ gi7eba~9 \
+ \
+ GI7EB~10 \
+ GI7EB~11 \
+ GI7EB~99 \
+ GI7EB~10 \
+ GI7E~100 \
+ GI7E~101 \
+ GI7E~999 \
+ ~1000000 \
+ ~9999999 \
+ \
+ --not \
+ ".gitmodules x" \
+ ".gitmodules .x" \
+ \
+ " .gitmodules" \
+ \
+ ..gitmodules \
+ \
+ gitmodules \
+ \
+ .gitmodule \
+ \
+ ".gitmodules x " \
+ ".gitmodules .x" \
+ \
+ GI7EBA~ \
+ GI7EBA~0 \
+ GI7EBA~~1 \
+ GI7EBA~X \
+ Gx7EBA~1 \
+ GI7EBX~1 \
+ \
+ GI7EB~1 \
+ GI7EB~01 \
+ GI7EB~1X
+'
+
test_done
diff --git a/t/t0061-run-command.sh b/t/t0061-run-command.sh
index d03149b..c887ed5 100755
--- a/t/t0061-run-command.sh
+++ b/t/t0061-run-command.sh
@@ -145,7 +145,7 @@ test_trace () {
expect="$1"
shift
GIT_TRACE=1 test-tool run-command "$@" run-command true 2>&1 >/dev/null | \
- sed 's/.* run_command: //' >actual &&
+ sed -e 's/.* run_command: //' -e '/trace: .*/d' >actual &&
echo "$expect true" >expect &&
test_cmp expect actual
}
diff --git a/t/t0090-cache-tree.sh b/t/t0090-cache-tree.sh
index 4ae0995..0c61268 100755
--- a/t/t0090-cache-tree.sh
+++ b/t/t0090-cache-tree.sh
@@ -9,7 +9,7 @@ cache-tree extension.
cmp_cache_tree () {
test-tool dump-cache-tree | sed -e '/#(ref)/d' >actual &&
- sed "s/$_x40/SHA/" <actual >filtered &&
+ sed "s/$OID_REGEX/SHA/" <actual >filtered &&
test_cmp "$1" filtered
}
diff --git a/t/t1000-read-tree-m-3way.sh b/t/t1000-read-tree-m-3way.sh
index 3c4d2d6..013c5a7 100755
--- a/t/t1000-read-tree-m-3way.sh
+++ b/t/t1000-read-tree-m-3way.sh
@@ -128,7 +128,7 @@ cat >expected <<\EOF
EOF
check_result () {
- git ls-files --stage | sed -e 's/ '"$_x40"' / X /' >current &&
+ git ls-files --stage | sed -e 's/ '"$OID_REGEX"' / X /' >current &&
test_cmp expected current
}
diff --git a/t/t1001-read-tree-m-2way.sh b/t/t1001-read-tree-m-2way.sh
index 5ededd8..1057a96 100755
--- a/t/t1001-read-tree-m-2way.sh
+++ b/t/t1001-read-tree-m-2way.sh
@@ -30,7 +30,7 @@ read_tree_twoway () {
compare_change () {
sed -n >current \
-e '/^--- /d; /^+++ /d; /^@@ /d;' \
- -e 's/^\([-+][0-7][0-7][0-7][0-7][0-7][0-7]\) '"$_x40"' /\1 X /p' \
+ -e 's/^\([-+][0-7][0-7][0-7][0-7][0-7][0-7]\) '"$OID_REGEX"' /\1 X /p' \
"$1"
test_cmp expected current
}
diff --git a/t/t1002-read-tree-m-u-2way.sh b/t/t1002-read-tree-m-u-2way.sh
index 7ca2e65..9c05f5e 100755
--- a/t/t1002-read-tree-m-u-2way.sh
+++ b/t/t1002-read-tree-m-u-2way.sh
@@ -16,7 +16,7 @@ compare_change () {
-e '1{/^diff --git /d;}' \
-e '2{/^index /d;}' \
-e '/^--- /d; /^+++ /d; /^@@ /d;' \
- -e 's/^\(.[0-7][0-7][0-7][0-7][0-7][0-7]\) '"$_x40"' /\1 X /' "$1"
+ -e 's/^\(.[0-7][0-7][0-7][0-7][0-7][0-7]\) '"$OID_REGEX"' /\1 X /' "$1"
test_cmp expected current
}
diff --git a/t/t1006-cat-file.sh b/t/t1006-cat-file.sh
index 2ac3b94..13dd510 100755
--- a/t/t1006-cat-file.sh
+++ b/t/t1006-cat-file.sh
@@ -236,8 +236,8 @@ test_expect_success "--batch-check for an empty line" '
'
test_expect_success 'empty --batch-check notices missing object' '
- echo "$_z40 missing" >expect &&
- echo "$_z40" | git cat-file --batch-check="" >actual &&
+ echo "$ZERO_OID missing" >expect &&
+ echo "$ZERO_OID" | git cat-file --batch-check="" >actual &&
test_cmp expect actual
'
@@ -294,8 +294,8 @@ test_expect_success 'setup blobs which are likely to delta' '
test_expect_success 'confirm that neither loose blob is a delta' '
cat >expect <<-EOF &&
- $_z40
- $_z40
+ $ZERO_OID
+ $ZERO_OID
EOF
git cat-file --batch-check="%(deltabase)" <blobs >actual &&
test_cmp expect actual
diff --git a/t/t1007-hash-object.sh b/t/t1007-hash-object.sh
index 532682f..a377530 100755
--- a/t/t1007-hash-object.sh
+++ b/t/t1007-hash-object.sh
@@ -9,13 +9,13 @@ echo_without_newline() {
}
test_blob_does_not_exist() {
- test_expect_success 'blob does not exist in database' "
+ test_expect_success SHA1 'blob does not exist in database' "
test_must_fail git cat-file blob $1
"
}
test_blob_exists() {
- test_expect_success 'blob exists in database' "
+ test_expect_success SHA1 'blob exists in database' "
git cat-file blob $1
"
}
@@ -73,19 +73,19 @@ test_expect_success "Can't use --path with --no-filters" '
push_repo
-test_expect_success 'hash a file' '
+test_expect_success SHA1 'hash a file' '
test $hello_sha1 = $(git hash-object hello)
'
test_blob_does_not_exist $hello_sha1
-test_expect_success 'hash from stdin' '
+test_expect_success SHA1 'hash from stdin' '
test $example_sha1 = $(git hash-object --stdin < example)
'
test_blob_does_not_exist $example_sha1
-test_expect_success 'hash a file and write to database' '
+test_expect_success SHA1 'hash a file and write to database' '
test $hello_sha1 = $(git hash-object -w hello)
'
@@ -161,7 +161,7 @@ pop_repo
for args in "-w --stdin" "--stdin -w"; do
push_repo
- test_expect_success "hash from stdin and write to database ($args)" '
+ test_expect_success SHA1 "hash from stdin and write to database ($args)" '
test $example_sha1 = $(git hash-object $args < example)
'
@@ -176,14 +176,14 @@ example"
sha1s="$hello_sha1
$example_sha1"
-test_expect_success "hash two files with names on stdin" '
+test_expect_success SHA1 "hash two files with names on stdin" '
test "$sha1s" = "$(echo_without_newline "$filenames" | git hash-object --stdin-paths)"
'
for args in "-w --stdin-paths" "--stdin-paths -w"; do
push_repo
- test_expect_success "hash two files with names on stdin and write to database ($args)" '
+ test_expect_success SHA1 "hash two files with names on stdin and write to database ($args)" '
test "$sha1s" = "$(echo_without_newline "$filenames" | git hash-object $args)"
'
diff --git a/t/t1012-read-tree-df.sh b/t/t1012-read-tree-df.sh
index a6a04b6..57f0770 100755
--- a/t/t1012-read-tree-df.sh
+++ b/t/t1012-read-tree-df.sh
@@ -32,7 +32,7 @@ settree () {
checkindex () {
git ls-files -s |
- sed "s|^[0-7][0-7]* $_x40 \([0-3]\) |\1 |" >current &&
+ sed "s|^[0-7][0-7]* $OID_REGEX \([0-3]\) |\1 |" >current &&
cat >expect &&
test_cmp expect current
}
diff --git a/t/t1300-repo-config.sh b/t/t1300-config.sh
index e95b1e6..03c2237 100755
--- a/t/t1300-repo-config.sh
+++ b/t/t1300-config.sh
@@ -108,6 +108,7 @@ bar = foo
[beta]
baz = multiple \
lines
+foo = bar
EOF
test_expect_success 'unset with cont. lines' '
@@ -118,6 +119,7 @@ cat > expect <<\EOF
[alpha]
bar = foo
[beta]
+foo = bar
EOF
test_expect_success 'unset with cont. lines is correct' 'test_cmp expect .git/config'
@@ -740,7 +742,7 @@ test_expect_success bool '
do
git config --bool --get bool.true$i >>result
git config --bool --get bool.false$i >>result
- done &&
+ done &&
test_cmp expect result'
test_expect_success 'invalid bool (--get)' '
@@ -931,6 +933,36 @@ test_expect_success 'get --expiry-date' '
test_must_fail git config --expiry-date date.invalid1
'
+test_expect_success 'get --type=color' '
+ rm .git/config &&
+ git config foo.color "red" &&
+ git config --get --type=color foo.color >actual.raw &&
+ test_decode_color <actual.raw >actual &&
+ echo "<RED>" >expect &&
+ test_cmp expect actual
+'
+
+cat >expect << EOF
+[foo]
+ color = red
+EOF
+
+test_expect_success 'set --type=color' '
+ rm .git/config &&
+ git config --type=color foo.color "red" &&
+ test_cmp expect .git/config
+'
+
+test_expect_success 'get --type=color barfs on non-color' '
+ echo "[foo]bar=not-a-color" >.git/config &&
+ test_must_fail git config --get --type=color foo.bar
+'
+
+test_expect_success 'set --type=color barfs on non-color' '
+ test_must_fail git config --type=color foo.color "not-a-color" 2>error &&
+ test_i18ngrep "cannot parse color" error
+'
+
cat > expect << EOF
[quote]
leading = " test"
@@ -1411,7 +1443,7 @@ test_expect_success 'urlmatch with wildcard' '
'
# good section hygiene
-test_expect_failure 'unsetting the last key in a section removes header' '
+test_expect_success '--unset last key removes section (except if commented)' '
cat >.git/config <<-\EOF &&
# some generic comment on the configuration file itself
# a comment specific to this "section" section.
@@ -1425,13 +1457,86 @@ test_expect_failure 'unsetting the last key in a section removes header' '
cat >expect <<-\EOF &&
# some generic comment on the configuration file itself
+ # a comment specific to this "section" section.
+ [section]
+ # some intervening lines
+ # that should also be dropped
+
+ # please be careful when you update the above variable
EOF
git config --unset section.key &&
- test_cmp expect .git/config
+ test_cmp expect .git/config &&
+
+ cat >.git/config <<-\EOF &&
+ [section]
+ key = value
+ [next-section]
+ EOF
+
+ cat >expect <<-\EOF &&
+ [next-section]
+ EOF
+
+ git config --unset section.key &&
+ test_cmp expect .git/config &&
+
+ q_to_tab >.git/config <<-\EOF &&
+ [one]
+ Qkey = "multiline \
+ QQ# with comment"
+ [two]
+ key = true
+ EOF
+ git config --unset two.key &&
+ ! grep two .git/config &&
+
+ q_to_tab >.git/config <<-\EOF &&
+ [one]
+ Qkey = "multiline \
+ QQ# with comment"
+ [one]
+ key = true
+ EOF
+ git config --unset-all one.key &&
+ test_line_count = 0 .git/config &&
+
+ q_to_tab >.git/config <<-\EOF &&
+ [one]
+ Qkey = true
+ Q# a comment not at the start
+ [two]
+ Qkey = true
+ EOF
+ git config --unset two.key &&
+ grep two .git/config &&
+
+ q_to_tab >.git/config <<-\EOF &&
+ [one]
+ Qkey = not [two "subsection"]
+ [two "subsection"]
+ [two "subsection"]
+ Qkey = true
+ [TWO "subsection"]
+ [one]
+ EOF
+ git config --unset two.subsection.key &&
+ test "not [two subsection]" = "$(git config one.key)" &&
+ test_line_count = 3 .git/config
'
-test_expect_failure 'adding a key into an empty section reuses header' '
+test_expect_success '--unset-all removes section if empty & uncommented' '
+ cat >.git/config <<-\EOF &&
+ [section]
+ key = value1
+ key = value2
+ EOF
+
+ git config --unset-all section.key &&
+ test_line_count = 0 .git/config
+'
+
+test_expect_success 'adding a key into an empty section reuses header' '
cat >.git/config <<-\EOF &&
[section]
EOF
@@ -1611,4 +1716,88 @@ test_expect_success '--local requires a repo' '
test_expect_code 128 nongit git config --local foo.bar
'
+cat >.git/config <<-\EOF &&
+[core]
+foo = true
+number = 10
+big = 1M
+EOF
+
+test_expect_success 'identical modern --type specifiers are allowed' '
+ git config --type=int --type=int core.big >actual &&
+ echo 1048576 >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success 'identical legacy --type specifiers are allowed' '
+ git config --int --int core.big >actual &&
+ echo 1048576 >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success 'identical mixed --type specifiers are allowed' '
+ git config --int --type=int core.big >actual &&
+ echo 1048576 >expect &&
+ test_cmp expect actual
+'
+
+test_expect_success 'non-identical modern --type specifiers are not allowed' '
+ test_must_fail git config --type=int --type=bool core.big 2>error &&
+ test_i18ngrep "only one type at a time" error
+'
+
+test_expect_success 'non-identical legacy --type specifiers are not allowed' '
+ test_must_fail git config --int --bool core.big 2>error &&
+ test_i18ngrep "only one type at a time" error
+'
+
+test_expect_success 'non-identical mixed --type specifiers are not allowed' '
+ test_must_fail git config --type=int --bool core.big 2>error &&
+ test_i18ngrep "only one type at a time" error
+'
+
+test_expect_success '--type allows valid type specifiers' '
+ echo "true" >expect &&
+ git config --type=bool core.foo >actual &&
+ test_cmp expect actual
+'
+
+test_expect_success '--no-type unsets type specifiers' '
+ echo "10" >expect &&
+ git config --type=bool --no-type core.number >actual &&
+ test_cmp expect actual
+'
+
+test_expect_success 'unset type specifiers may be reset to conflicting ones' '
+ echo 1048576 >expect &&
+ git config --type=bool --no-type --type=int core.big >actual &&
+ test_cmp expect actual
+'
+
+test_expect_success '--type rejects unknown specifiers' '
+ test_must_fail git config --type=nonsense core.foo 2>error &&
+ test_i18ngrep "unrecognized --type argument" error
+'
+
+test_expect_success '--replace-all does not invent newlines' '
+ q_to_tab >.git/config <<-\EOF &&
+ [abc]key
+ QkeepSection
+ [xyz]
+ Qkey = 1
+ [abc]
+ Qkey = a
+ EOF
+ q_to_tab >expect <<-\EOF &&
+ [abc]
+ QkeepSection
+ [xyz]
+ Qkey = 1
+ [abc]
+ Qkey = b
+ EOF
+ git config --replace-all abc.key b &&
+ test_cmp .git/config expect
+'
+
test_done
diff --git a/t/t1307-config-blob.sh b/t/t1307-config-blob.sh
index eed31ff..37dc689 100755
--- a/t/t1307-config-blob.sh
+++ b/t/t1307-config-blob.sh
@@ -73,4 +73,8 @@ test_expect_success 'can parse blob ending with CR' '
test_cmp expect actual
'
+test_expect_success 'config --blob outside of a repository is an error' '
+ test_must_fail nongit git config --blob=foo --list
+'
+
test_done
diff --git a/t/t1310-config-default.sh b/t/t1310-config-default.sh
new file mode 100755
index 0000000..6049d91
--- /dev/null
+++ b/t/t1310-config-default.sh
@@ -0,0 +1,36 @@
+#!/bin/sh
+
+test_description='Test git config in different settings (with --default)'
+
+. ./test-lib.sh
+
+test_expect_success 'uses --default when entry missing' '
+ echo quux >expect &&
+ git config -f config --default=quux core.foo >actual &&
+ test_cmp expect actual
+'
+
+test_expect_success 'does not use --default when entry present' '
+ echo bar >expect &&
+ git -c core.foo=bar config --default=baz core.foo >actual &&
+ test_cmp expect actual
+'
+
+test_expect_success 'canonicalizes --default with appropriate type' '
+ echo true >expect &&
+ git config -f config --default=yes --bool core.foo >actual &&
+ test_cmp expect actual
+'
+
+test_expect_success 'dies when --default cannot be parsed' '
+ test_must_fail git config -f config --type=expiry-date --default=x --get \
+ not.a.section 2>error &&
+ test_i18ngrep "failed to format default config value" error
+'
+
+test_expect_success 'does not allow --default without --get' '
+ test_must_fail git config --default=quux --unset a.section >output 2>&1 &&
+ test_i18ngrep "\-\-default is only applicable to" output
+'
+
+test_done
diff --git a/t/t1400-update-ref.sh b/t/t1400-update-ref.sh
index 664a3a4..e1fd0f0 100755
--- a/t/t1400-update-ref.sh
+++ b/t/t1400-update-ref.sh
@@ -6,7 +6,7 @@
test_description='Test git update-ref and basic ref logging'
. ./test-lib.sh
-Z=$_z40
+Z=$ZERO_OID
m=refs/heads/master
n_dir=refs/heads/gu
@@ -457,6 +457,66 @@ test_expect_success 'git cat-file blob master@{2005-05-26 23:42}:F (expect OTHER
test OTHER = $(git cat-file blob "master@{2005-05-26 23:42}:F")
'
+# Test adding and deleting pseudorefs
+
+test_expect_success 'given old value for missing pseudoref, do not create' '
+ test_must_fail git update-ref PSEUDOREF $A $B 2>err &&
+ test_path_is_missing .git/PSEUDOREF &&
+ grep "could not read ref" err
+'
+
+test_expect_success 'create pseudoref' '
+ git update-ref PSEUDOREF $A &&
+ test $A = $(cat .git/PSEUDOREF)
+'
+
+test_expect_success 'overwrite pseudoref with no old value given' '
+ git update-ref PSEUDOREF $B &&
+ test $B = $(cat .git/PSEUDOREF)
+'
+
+test_expect_success 'overwrite pseudoref with correct old value' '
+ git update-ref PSEUDOREF $C $B &&
+ test $C = $(cat .git/PSEUDOREF)
+'
+
+test_expect_success 'do not overwrite pseudoref with wrong old value' '
+ test_must_fail git update-ref PSEUDOREF $D $E 2>err &&
+ test $C = $(cat .git/PSEUDOREF) &&
+ grep "unexpected object ID" err
+'
+
+test_expect_success 'delete pseudoref' '
+ git update-ref -d PSEUDOREF &&
+ test_path_is_missing .git/PSEUDOREF
+'
+
+test_expect_success 'do not delete pseudoref with wrong old value' '
+ git update-ref PSEUDOREF $A &&
+ test_must_fail git update-ref -d PSEUDOREF $B 2>err &&
+ test $A = $(cat .git/PSEUDOREF) &&
+ grep "unexpected object ID" err
+'
+
+test_expect_success 'delete pseudoref with correct old value' '
+ git update-ref -d PSEUDOREF $A &&
+ test_path_is_missing .git/PSEUDOREF
+'
+
+test_expect_success 'create pseudoref with old OID zero' '
+ git update-ref PSEUDOREF $A $Z &&
+ test $A = $(cat .git/PSEUDOREF)
+'
+
+test_expect_success 'do not overwrite pseudoref with old OID zero' '
+ test_when_finished git update-ref -d PSEUDOREF &&
+ test_must_fail git update-ref PSEUDOREF $B $Z 2>err &&
+ test $A = $(cat .git/PSEUDOREF) &&
+ grep "already exists" err
+'
+
+# Test --stdin
+
a=refs/heads/a
b=refs/heads/b
c=refs/heads/c
diff --git a/t/t1407-worktree-ref-store.sh b/t/t1407-worktree-ref-store.sh
index 2211f98..4623ae1 100755
--- a/t/t1407-worktree-ref-store.sh
+++ b/t/t1407-worktree-ref-store.sh
@@ -50,13 +50,13 @@ test_expect_success 'create_symref(FOO, refs/heads/master)' '
'
test_expect_success 'for_each_reflog()' '
- echo $_z40 > .git/logs/PSEUDO-MAIN &&
+ echo $ZERO_OID > .git/logs/PSEUDO-MAIN &&
mkdir -p .git/logs/refs/bisect &&
- echo $_z40 > .git/logs/refs/bisect/random &&
+ echo $ZERO_OID > .git/logs/refs/bisect/random &&
- echo $_z40 > .git/worktrees/wt/logs/PSEUDO-WT &&
+ echo $ZERO_OID > .git/worktrees/wt/logs/PSEUDO-WT &&
mkdir -p .git/worktrees/wt/logs/refs/bisect &&
- echo $_z40 > .git/worktrees/wt/logs/refs/bisect/wt-random &&
+ echo $ZERO_OID > .git/worktrees/wt/logs/refs/bisect/wt-random &&
$RWT for-each-reflog | cut -c 42- | sort >actual &&
cat >expected <<-\EOF &&
diff --git a/t/t1450-fsck.sh b/t/t1450-fsck.sh
index cb4b66e..91fd714 100755
--- a/t/t1450-fsck.sh
+++ b/t/t1450-fsck.sh
@@ -713,7 +713,7 @@ test_expect_success 'fsck notices dangling objects' '
test_expect_success 'fsck $name notices bogus $name' '
test_must_fail git fsck bogus &&
- test_must_fail git fsck $_z40
+ test_must_fail git fsck $ZERO_OID
'
test_expect_success 'bogus head does not fallback to all heads' '
@@ -723,7 +723,7 @@ test_expect_success 'bogus head does not fallback to all heads' '
blob=$(git rev-parse :foo) &&
test_when_finished "git rm --cached foo" &&
remove_object $blob &&
- test_must_fail git fsck $_z40 >out 2>&1 &&
+ test_must_fail git fsck $ZERO_OID >out 2>&1 &&
! grep $blob out
'
diff --git a/t/t1501-work-tree.sh b/t/t1501-work-tree.sh
index 02cf201..afcdfaf 100755
--- a/t/t1501-work-tree.sh
+++ b/t/t1501-work-tree.sh
@@ -238,10 +238,10 @@ test_expect_success '_gently() groks relative GIT_DIR & GIT_WORK_TREE' '
test_expect_success 'diff-index respects work tree under .git dir' '
cat >diff-index-cached.expected <<-EOF &&
- :000000 100644 $_z40 $EMPTY_BLOB A sub/dir/tracked
+ :000000 100644 $ZERO_OID $EMPTY_BLOB A sub/dir/tracked
EOF
cat >diff-index.expected <<-EOF &&
- :000000 100644 $_z40 $_z40 A sub/dir/tracked
+ :000000 100644 $ZERO_OID $ZERO_OID A sub/dir/tracked
EOF
(
@@ -257,7 +257,7 @@ test_expect_success 'diff-index respects work tree under .git dir' '
test_expect_success 'diff-files respects work tree under .git dir' '
cat >diff-files.expected <<-EOF &&
- :100644 100644 $EMPTY_BLOB $_z40 M sub/dir/tracked
+ :100644 100644 $EMPTY_BLOB $ZERO_OID M sub/dir/tracked
EOF
(
@@ -431,4 +431,16 @@ test_expect_success 'error out gracefully on invalid $GIT_WORK_TREE' '
)
'
+test_expect_success 'refs work with relative gitdir and work tree' '
+ git init relative &&
+ git -C relative commit --allow-empty -m one &&
+ git -C relative commit --allow-empty -m two &&
+
+ GIT_DIR=relative/.git GIT_WORK_TREE=relative git reset HEAD^ &&
+
+ git -C relative log -1 --format=%s >actual &&
+ echo one >expect &&
+ test_cmp expect actual
+'
+
test_done
diff --git a/t/t1510-repo-setup.sh b/t/t1510-repo-setup.sh
index e6854b8..972bd9c 100755
--- a/t/t1510-repo-setup.sh
+++ b/t/t1510-repo-setup.sh
@@ -238,7 +238,6 @@ test_expect_success '#0: nonbare repo, no explicit configuration' '
'
test_expect_success '#1: GIT_WORK_TREE without explicit GIT_DIR is accepted' '
- mkdir -p wt &&
try_repo 1 "$here" unset unset "" unset \
"$here/1/.git" "$here" "$here" 1/ \
"$here/1/.git" "$here" "$here" 1/sub/ 2>message &&
diff --git a/t/t1512-rev-parse-disambiguation.sh b/t/t1512-rev-parse-disambiguation.sh
index 711704b..96fe375 100755
--- a/t/t1512-rev-parse-disambiguation.sh
+++ b/t/t1512-rev-parse-disambiguation.sh
@@ -22,6 +22,12 @@ one tagged as v1.0.0. They all have one regular file each.
. ./test-lib.sh
+if ! test_have_prereq SHA1
+then
+ skip_all='not using SHA-1 for objects'
+ test_done
+fi
+
test_expect_success 'blob and tree' '
test_tick &&
(
@@ -361,4 +367,25 @@ test_expect_success 'core.disambiguate does not override context' '
git -c core.disambiguate=committish rev-parse $sha1^{tree}
'
+test_expect_success C_LOCALE_OUTPUT 'ambiguous commits are printed by type first, then hash order' '
+ test_must_fail git rev-parse 0000 2>stderr &&
+ grep ^hint: stderr >hints &&
+ grep 0000 hints >objects &&
+ cat >expected <<-\EOF &&
+ tag
+ commit
+ tree
+ blob
+ EOF
+ awk "{print \$3}" <objects >objects.types &&
+ uniq <objects.types >objects.types.uniq &&
+ test_cmp expected objects.types.uniq &&
+ for type in tag commit tree blob
+ do
+ grep $type objects >$type.objects &&
+ sort $type.objects >$type.objects.sorted &&
+ test_cmp $type.objects.sorted $type.objects
+ done
+'
+
test_done
diff --git a/t/t1601-index-bogus.sh b/t/t1601-index-bogus.sh
index 73cc932..4171f1e 100755
--- a/t/t1601-index-bogus.sh
+++ b/t/t1601-index-bogus.sh
@@ -4,7 +4,7 @@ test_description='test handling of bogus index entries'
. ./test-lib.sh
test_expect_success 'create tree with null sha1' '
- tree=$(printf "160000 commit $_z40\\tbroken\\n" | git mktree)
+ tree=$(printf "160000 commit $ZERO_OID\\tbroken\\n" | git mktree)
'
test_expect_success 'read-tree refuses to read null sha1' '
diff --git a/t/t1700-split-index.sh b/t/t1700-split-index.sh
index e4f4c4d..1e81b33 100755
--- a/t/t1700-split-index.sh
+++ b/t/t1700-split-index.sh
@@ -426,7 +426,7 @@ test_expect_success 'writing split index with null sha1 does not write cache tre
git commit -m "commit" &&
{
git ls-tree HEAD &&
- printf "160000 commit $_z40\\tbroken\\n"
+ printf "160000 commit $ZERO_OID\\tbroken\\n"
} >broken-tree &&
echo "add broken entry" >msg &&
diff --git a/t/t2011-checkout-invalid-head.sh b/t/t2011-checkout-invalid-head.sh
index c5501b0..0e8d56a 100755
--- a/t/t2011-checkout-invalid-head.sh
+++ b/t/t2011-checkout-invalid-head.sh
@@ -15,7 +15,7 @@ test_expect_success 'checkout should not start branch from a tree' '
'
test_expect_success 'checkout master from invalid HEAD' '
- echo $_z40 >.git/HEAD &&
+ echo $ZERO_OID >.git/HEAD &&
git checkout master --
'
diff --git a/t/t2022-checkout-paths.sh b/t/t2022-checkout-paths.sh
index e74d58b..fc3eb43 100755
--- a/t/t2022-checkout-paths.sh
+++ b/t/t2022-checkout-paths.sh
@@ -73,8 +73,8 @@ test_expect_success 'do not touch files that are already up-to-date' '
git checkout HEAD -- file1 file2 &&
echo one >expect &&
test_cmp expect file1 &&
- echo "1000000000 file2" >expect &&
- test-tool chmtime -v +0 file2 >actual &&
+ echo "1000000000" >expect &&
+ test-tool chmtime --get file2 >actual &&
test_cmp expect actual
'
diff --git a/t/t2025-worktree-add.sh b/t/t2025-worktree-add.sh
index d0d2e4f..d2e49f7 100755
--- a/t/t2025-worktree-add.sh
+++ b/t/t2025-worktree-add.sh
@@ -198,13 +198,25 @@ test_expect_success '"add" with <branch> omitted' '
test_cmp_rev HEAD bat
'
-test_expect_success '"add" auto-vivify does not clobber existing branch' '
- test_commit c1 &&
- test_commit c2 &&
- git branch precious HEAD~1 &&
- test_must_fail git worktree add precious &&
- test_cmp_rev HEAD~1 precious &&
- test_path_is_missing precious
+test_expect_success '"add" checks out existing branch of dwimd name' '
+ git branch dwim HEAD~1 &&
+ git worktree add dwim &&
+ test_cmp_rev HEAD~1 dwim &&
+ (
+ cd dwim &&
+ test_cmp_rev HEAD dwim
+ )
+'
+
+test_expect_success '"add <path>" dwim fails with checked out branch' '
+ git checkout -b test-branch &&
+ test_must_fail git worktree add test-branch &&
+ test_path_is_missing test-branch
+'
+
+test_expect_success '"add --force" with existing dwimd name doesnt die' '
+ git checkout test-branch &&
+ git worktree add --force test-branch
'
test_expect_success '"add" no auto-vivify with --detach and <branch> omitted' '
@@ -465,7 +477,7 @@ post_checkout_hook () {
test_expect_success '"add" invokes post-checkout hook (branch)' '
post_checkout_hook &&
{
- echo $_z40 $(git rev-parse HEAD) 1 &&
+ echo $ZERO_OID $(git rev-parse HEAD) 1 &&
echo $(pwd)/.git/worktrees/gumby &&
echo $(pwd)/gumby
} >hook.expect &&
@@ -476,7 +488,7 @@ test_expect_success '"add" invokes post-checkout hook (branch)' '
test_expect_success '"add" invokes post-checkout hook (detached)' '
post_checkout_hook &&
{
- echo $_z40 $(git rev-parse HEAD) 1 &&
+ echo $ZERO_OID $(git rev-parse HEAD) 1 &&
echo $(pwd)/.git/worktrees/grumpy &&
echo $(pwd)/grumpy
} >hook.expect &&
@@ -494,7 +506,7 @@ test_expect_success '"add --no-checkout" suppresses post-checkout hook' '
test_expect_success '"add" in other worktree invokes post-checkout hook' '
post_checkout_hook &&
{
- echo $_z40 $(git rev-parse HEAD) 1 &&
+ echo $ZERO_OID $(git rev-parse HEAD) 1 &&
echo $(pwd)/.git/worktrees/guppy &&
echo $(pwd)/guppy
} >hook.expect &&
@@ -506,7 +518,7 @@ test_expect_success '"add" in bare repo invokes post-checkout hook' '
rm -rf bare &&
git clone --bare . bare &&
{
- echo $_z40 $(git --git-dir=bare rev-parse HEAD) 1 &&
+ echo $ZERO_OID $(git --git-dir=bare rev-parse HEAD) 1 &&
echo $(pwd)/bare/worktrees/goozy &&
echo $(pwd)/goozy
} >hook.expect &&
diff --git a/t/t2027-worktree-list.sh b/t/t2027-worktree-list.sh
index 720063b..bb6fb9b 100755
--- a/t/t2027-worktree-list.sh
+++ b/t/t2027-worktree-list.sh
@@ -116,7 +116,7 @@ test_expect_success 'broken main worktree still at the top' '
git worktree add linked &&
cat >expected <<-EOF &&
worktree $(pwd)
- HEAD $_z40
+ HEAD $ZERO_OID
EOF
cd linked &&
diff --git a/t/t2028-worktree-move.sh b/t/t2028-worktree-move.sh
index 5d5b363..5f7d45b 100755
--- a/t/t2028-worktree-move.sh
+++ b/t/t2028-worktree-move.sh
@@ -72,12 +72,11 @@ test_expect_success 'move locked worktree' '
'
test_expect_success 'move worktree' '
- toplevel="$(pwd)" &&
git worktree move source destination &&
test_path_is_missing source &&
git worktree list --porcelain >out &&
- grep "^worktree.*/destination" out &&
- ! grep "^worktree.*/source" out &&
+ grep "^worktree.*/destination$" out &&
+ ! grep "^worktree.*/source$" out &&
git -C destination log --format=%s >actual2 &&
echo init >expected2 &&
test_cmp expected2 actual2
@@ -93,7 +92,7 @@ test_expect_success 'move worktree to another dir' '
test_when_finished "git worktree move some-dir/destination destination" &&
test_path_is_missing destination &&
git worktree list --porcelain >out &&
- grep "^worktree.*/some-dir/destination" out &&
+ grep "^worktree.*/some-dir/destination$" out &&
git -C some-dir/destination log --format=%s >actual2 &&
echo init >expected2 &&
test_cmp expected2 actual2
diff --git a/t/t2107-update-index-basic.sh b/t/t2107-update-index-basic.sh
index 1db7e6a..2242cd0 100755
--- a/t/t2107-update-index-basic.sh
+++ b/t/t2107-update-index-basic.sh
@@ -37,7 +37,7 @@ test_expect_success '--cacheinfo does not accept blob null sha1' '
echo content >file &&
git add file &&
git rev-parse :file >expect &&
- test_must_fail git update-index --cacheinfo 100644 $_z40 file &&
+ test_must_fail git update-index --cacheinfo 100644 $ZERO_OID file &&
git rev-parse :file >actual &&
test_cmp expect actual
'
@@ -47,7 +47,7 @@ test_expect_success '--cacheinfo does not accept gitlink null sha1' '
(cd submodule && test_commit foo) &&
git add submodule &&
git rev-parse :submodule >expect &&
- test_must_fail git update-index --cacheinfo 160000 $_z40 submodule &&
+ test_must_fail git update-index --cacheinfo 160000 $ZERO_OID submodule &&
git rev-parse :submodule >actual &&
test_cmp expect actual
'
diff --git a/t/t2201-add-update-typechange.sh b/t/t2201-add-update-typechange.sh
index 954fc51..a4eec0a 100755
--- a/t/t2201-add-update-typechange.sh
+++ b/t/t2201-add-update-typechange.sh
@@ -75,35 +75,35 @@ test_expect_success modify '
git ls-tree -r HEAD |
sed -e "s/^/:/" -e "
/ caskly/{
- s/ caskly/ $_z40 D&/
+ s/ caskly/ $ZERO_OID D&/
s/blob/000000/
}
/ nitfol/{
- s/ nitfol/ $_z40 $T_letter&/
+ s/ nitfol/ $ZERO_OID $T_letter&/
s/blob/100644/
}
/ rezrov.bozbar/{
- s/ rezrov.bozbar/ $_z40 D&/
+ s/ rezrov.bozbar/ $ZERO_OID D&/
s/blob/000000/
}
/ xyzzy/{
- s/ xyzzy/ $_z40 D&/
+ s/ xyzzy/ $ZERO_OID D&/
s/blob/000000/
}
/ yomin/{
- s/ yomin/ $_z40 T&/
+ s/ yomin/ $ZERO_OID T&/
s/blob/160000/
}
"
} >expect &&
{
cat expect
- echo ":100644 160000 $_empty $_z40 T yonk"
- echo ":100644 000000 $_empty $_z40 D zifmia"
+ echo ":100644 160000 $_empty $ZERO_OID T yonk"
+ echo ":100644 000000 $_empty $ZERO_OID D zifmia"
} >expect-files &&
{
cat expect
- echo ":000000 160000 $_z40 $_z40 A yonk"
+ echo ":000000 160000 $ZERO_OID $ZERO_OID A yonk"
} >expect-index &&
{
echo "100644 $_empty 0 nitfol"
diff --git a/t/t2203-add-intent.sh b/t/t2203-add-intent.sh
index 78236dc..04d840a 100755
--- a/t/t2203-add-intent.sh
+++ b/t/t2203-add-intent.sh
@@ -27,12 +27,12 @@ test_expect_success 'git status' '
test_expect_success 'git status with porcelain v2' '
git status --porcelain=v2 | grep -v "^?" >actual &&
- nam1=d00491fd7e5bb6fa28c517a0bb32b8b506539d4d &&
- nam2=ce013625030ba8dba906f756967f9e9ca394464a &&
+ nam1=$(echo 1 | git hash-object --stdin) &&
+ nam2=$(git hash-object elif) &&
cat >expect <<-EOF &&
- 1 DA N... 100644 000000 100644 $nam1 $_z40 1.t
- 1 A. N... 000000 100644 100644 $_z40 $nam2 elif
- 1 .A N... 000000 000000 100644 $_z40 $_z40 file
+ 1 DA N... 100644 000000 100644 $nam1 $ZERO_OID 1.t
+ 1 A. N... 000000 100644 100644 $ZERO_OID $nam2 elif
+ 1 .A N... 000000 000000 100644 $ZERO_OID $ZERO_OID file
EOF
test_cmp expect actual
'
@@ -181,7 +181,7 @@ test_expect_success 'rename detection finds the right names' '
EOF
test_cmp expected.2 actual.2 &&
- hash=12f00e90b6ef79117ce6e650416b8cf517099b78 &&
+ hash=$(git hash-object third) &&
git status --porcelain=v2 | grep -v "^?" >actual.3 &&
cat >expected.3 <<-EOF &&
2 .R N... 100644 100644 100644 $hash $hash R100 third first
@@ -212,7 +212,7 @@ test_expect_success 'double rename detection in status' '
EOF
test_cmp expected.2 actual.2 &&
- hash=12f00e90b6ef79117ce6e650416b8cf517099b78 &&
+ hash=$(git hash-object third) &&
git status --porcelain=v2 | grep -v "^?" >actual.3 &&
cat >expected.3 <<-EOF &&
2 R. N... 100644 100644 100644 $hash $hash R100 second first
diff --git a/t/t3100-ls-tree-restrict.sh b/t/t3100-ls-tree-restrict.sh
index 325114f..18baf49 100755
--- a/t/t3100-ls-tree-restrict.sh
+++ b/t/t3100-ls-tree-restrict.sh
@@ -32,7 +32,7 @@ test_expect_success \
echo $tree'
test_output () {
- sed -e "s/ $_x40 / X /" <current >check
+ sed -e "s/ $OID_REGEX / X /" <current >check
test_cmp expected check
}
diff --git a/t/t3101-ls-tree-dirname.sh b/t/t3101-ls-tree-dirname.sh
index 327ded4..12bf310 100755
--- a/t/t3101-ls-tree-dirname.sh
+++ b/t/t3101-ls-tree-dirname.sh
@@ -40,7 +40,7 @@ test_expect_success 'setup' '
'
test_output () {
- sed -e "s/ $_x40 / X /" <current >check &&
+ sed -e "s/ $OID_REGEX / X /" <current >check &&
test_cmp expected check
}
diff --git a/t/t3103-ls-tree-misc.sh b/t/t3103-ls-tree-misc.sh
index 09dcf04..1452091 100755
--- a/t/t3103-ls-tree-misc.sh
+++ b/t/t3103-ls-tree-misc.sh
@@ -17,7 +17,8 @@ test_expect_success 'setup' '
'
test_expect_success 'ls-tree fails with non-zero exit code on broken tree' '
- rm -f .git/objects/5f/cffbd6e4c5c5b8d81f5e9314b20e338e3ffff5 &&
+ tree=$(git rev-parse HEAD:a) &&
+ rm -f .git/objects/$(echo $tree | sed -e "s,^\(..\),\1/,") &&
test_must_fail git ls-tree -r HEAD
'
diff --git a/t/t3200-branch.sh b/t/t3200-branch.sh
index 6c0b7ea..b52c655 100755
--- a/t/t3200-branch.sh
+++ b/t/t3200-branch.sh
@@ -6,6 +6,7 @@
test_description='git branch assorted tests'
. ./test-lib.sh
+. "$TEST_DIRECTORY"/lib-rebase.sh
test_expect_success 'prepare a trivial repository' '
echo Hello >A &&
@@ -46,7 +47,7 @@ test_expect_success 'git branch HEAD should fail' '
'
cat >expect <<EOF
-$_z40 $HEAD $GIT_COMMITTER_NAME <$GIT_COMMITTER_EMAIL> 1117150200 +0000 branch: Created from master
+$ZERO_OID $HEAD $GIT_COMMITTER_NAME <$GIT_COMMITTER_EMAIL> 1117150200 +0000 branch: Created from master
EOF
test_expect_success 'git branch -l d/e/f should create a branch and a log' '
GIT_COMMITTER_DATE="2005-05-26 23:30" \
@@ -900,7 +901,7 @@ test_expect_success '--set-upstream-to notices an error to set branch as own ups
# Keep this test last, as it changes the current branch
cat >expect <<EOF
-$_z40 $HEAD $GIT_COMMITTER_NAME <$GIT_COMMITTER_EMAIL> 1117150200 +0000 branch: Created from master
+$ZERO_OID $HEAD $GIT_COMMITTER_NAME <$GIT_COMMITTER_EMAIL> 1117150200 +0000 branch: Created from master
EOF
test_expect_success 'git checkout -b g/h/i -l should create a branch and a log' '
GIT_COMMITTER_DATE="2005-05-26 23:30" \
@@ -1246,6 +1247,29 @@ test_expect_success '--merged is incompatible with --no-merged' '
test_must_fail git branch --merged HEAD --no-merged HEAD
'
+test_expect_success '--list during rebase' '
+ test_when_finished "reset_rebase" &&
+ git checkout master &&
+ FAKE_LINES="1 edit 2" &&
+ export FAKE_LINES &&
+ set_fake_editor &&
+ git rebase -i HEAD~2 &&
+ git branch --list >actual &&
+ test_i18ngrep "rebasing master" actual
+'
+
+test_expect_success '--list during rebase from detached HEAD' '
+ test_when_finished "reset_rebase && git checkout master" &&
+ git checkout master^0 &&
+ oid=$(git rev-parse --short HEAD) &&
+ FAKE_LINES="1 edit 2" &&
+ export FAKE_LINES &&
+ set_fake_editor &&
+ git rebase -i HEAD~2 &&
+ git branch --list >actual &&
+ test_i18ngrep "rebasing detached HEAD $oid" actual
+'
+
test_expect_success 'tracking with unexpected .fetch refspec' '
rm -rf a b c d &&
git init a &&
diff --git a/t/t3404-rebase-interactive.sh b/t/t3404-rebase-interactive.sh
index 756de26..c65826d 100755
--- a/t/t3404-rebase-interactive.sh
+++ b/t/t3404-rebase-interactive.sh
@@ -717,7 +717,7 @@ test_expect_success 'avoid unnecessary reset' '
set_fake_editor &&
git rebase -i HEAD~4 &&
test $HEAD = $(git rev-parse HEAD) &&
- MTIME=$(test-tool chmtime -v +0 file3 | sed 's/[^0-9].*$//') &&
+ MTIME=$(test-tool chmtime --get file3) &&
test 123456789 = $MTIME
'
@@ -1204,10 +1204,6 @@ test_expect_success 'drop' '
test A = $(git cat-file commit HEAD^^ | sed -ne \$p)
'
-cat >expect <<EOF
-Successfully rebased and updated refs/heads/missing-commit.
-EOF
-
test_expect_success 'rebase -i respects rebase.missingCommitsCheck = ignore' '
test_config rebase.missingCommitsCheck ignore &&
rebase_setup_and_clean missing-commit &&
@@ -1215,7 +1211,9 @@ test_expect_success 'rebase -i respects rebase.missingCommitsCheck = ignore' '
FAKE_LINES="1 2 3 4" \
git rebase -i --root 2>actual &&
test D = $(git cat-file commit HEAD | sed -ne \$p) &&
- test_i18ncmp expect actual
+ test_i18ngrep \
+ "Successfully rebased and updated refs/heads/missing-commit" \
+ actual
'
cat >expect <<EOF
@@ -1227,15 +1225,24 @@ To avoid this message, use "drop" to explicitly remove a commit.
Use 'git config rebase.missingCommitsCheck' to change the level of warnings.
The possible behaviours are: ignore, warn, error.
+Rebasing (1/4)
+Rebasing (2/4)
+Rebasing (3/4)
+Rebasing (4/4)
Successfully rebased and updated refs/heads/missing-commit.
EOF
+cr_to_nl () {
+ tr '\015' '\012'
+}
+
test_expect_success 'rebase -i respects rebase.missingCommitsCheck = warn' '
test_config rebase.missingCommitsCheck warn &&
rebase_setup_and_clean missing-commit &&
set_fake_editor &&
FAKE_LINES="1 2 3 4" \
- git rebase -i --root 2>actual &&
+ git rebase -i --root 2>actual.2 &&
+ cr_to_nl <actual.2 >actual &&
test_i18ncmp expect actual &&
test D = $(git cat-file commit HEAD | sed -ne \$p)
'
diff --git a/t/t3418-rebase-continue.sh b/t/t3418-rebase-continue.sh
index 9214d0b..03bf1b8 100755
--- a/t/t3418-rebase-continue.sh
+++ b/t/t3418-rebase-continue.sh
@@ -88,6 +88,55 @@ test_expect_success 'rebase passes merge strategy options correctly' '
git rebase --continue
'
+test_expect_success '--skip after failed fixup cleans commit message' '
+ test_when_finished "test_might_fail git rebase --abort" &&
+ git checkout -b with-conflicting-fixup &&
+ test_commit wants-fixup &&
+ test_commit "fixup! wants-fixup" wants-fixup.t 1 wants-fixup-1 &&
+ test_commit "fixup! wants-fixup" wants-fixup.t 2 wants-fixup-2 &&
+ test_commit "fixup! wants-fixup" wants-fixup.t 3 wants-fixup-3 &&
+ test_must_fail env FAKE_LINES="1 fixup 2 squash 4" \
+ git rebase -i HEAD~4 &&
+
+ : now there is a conflict, and comments in the commit message &&
+ git show HEAD >out &&
+ grep "fixup! wants-fixup" out &&
+
+ : skip and continue &&
+ echo "cp \"\$1\" .git/copy.txt" | write_script copy-editor.sh &&
+ (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) &&
+
+ : the user should not have had to edit the commit message &&
+ test_path_is_missing .git/copy.txt &&
+
+ : now the comments in the commit message should have been cleaned up &&
+ git show HEAD >out &&
+ ! grep "fixup! wants-fixup" out &&
+
+ : now, let us ensure that "squash" is handled correctly &&
+ git reset --hard wants-fixup-3 &&
+ test_must_fail env FAKE_LINES="1 squash 4 squash 2 squash 4" \
+ git rebase -i HEAD~4 &&
+
+ : the first squash failed, but there are two more in the chain &&
+ (test_set_editor "$PWD/copy-editor.sh" &&
+ test_must_fail git rebase --skip) &&
+
+ : not the final squash, no need to edit the commit message &&
+ test_path_is_missing .git/copy.txt &&
+
+ : The first squash was skipped, therefore: &&
+ git show HEAD >out &&
+ test_i18ngrep "# This is a combination of 2 commits" out &&
+
+ (test_set_editor "$PWD/copy-editor.sh" && git rebase --skip) &&
+ git show HEAD >out &&
+ test_i18ngrep ! "# This is a combination" out &&
+
+ : Final squash failed, but there was still a squash &&
+ test_i18ngrep "# This is a combination of 2 commits" .git/copy.txt
+'
+
test_expect_success 'setup rerere database' '
rm -fr .git/rebase-* &&
git reset --hard commit-new-file-F3-on-topic-branch &&
diff --git a/t/t3421-rebase-topology-linear.sh b/t/t3421-rebase-topology-linear.sh
index 68fe200..99b2aac 100755
--- a/t/t3421-rebase-topology-linear.sh
+++ b/t/t3421-rebase-topology-linear.sh
@@ -199,7 +199,7 @@ test_run_rebase () {
"
}
test_run_rebase success ''
-test_run_rebase failure -m
+test_run_rebase success -m
test_run_rebase success -i
test_run_rebase failure -p
@@ -214,9 +214,10 @@ test_run_rebase () {
"
}
test_run_rebase success ''
-test_run_rebase failure -m
-test_run_rebase failure -i
+test_run_rebase success -m
+test_run_rebase success -i
test_run_rebase failure -p
+test_run_rebase success --rebase-merges
# m
# /
@@ -327,9 +328,9 @@ test_run_rebase () {
test_cmp_rev c HEAD
"
}
-test_run_rebase failure ''
-test_run_rebase failure -m
-test_run_rebase failure -i
+test_run_rebase success ''
+test_run_rebase success -m
+test_run_rebase success -i
test_run_rebase failure -p
test_run_rebase () {
diff --git a/t/t3428-rebase-signoff.sh b/t/t3428-rebase-signoff.sh
index 2afb564..f6993b7 100755
--- a/t/t3428-rebase-signoff.sh
+++ b/t/t3428-rebase-signoff.sh
@@ -12,6 +12,13 @@ cat >file <<EOF
a
EOF
+# Expected commit message for initial commit after rebase --signoff
+cat >expected-initial-signed <<EOF
+Initial empty commit
+
+Signed-off-by: $(git var GIT_COMMITTER_IDENT | sed -e "s/>.*/>/")
+EOF
+
# Expected commit message after rebase --signoff
cat >expected-signed <<EOF
first
@@ -43,4 +50,35 @@ test_expect_success 'rebase --no-signoff does not add a sign-off line' '
test_cmp expected-unsigned actual
'
+test_expect_success 'rebase --exec --signoff adds a sign-off line' '
+ test_when_finished "rm exec" &&
+ git commit --amend -m "first" &&
+ git rebase --exec "touch exec" --signoff HEAD^ &&
+ test_path_is_file exec &&
+ git cat-file commit HEAD | sed -e "1,/^\$/d" >actual &&
+ test_cmp expected-signed actual
+'
+
+test_expect_success 'rebase --root --signoff adds a sign-off line' '
+ git commit --amend -m "first" &&
+ git rebase --root --keep-empty --signoff &&
+ git cat-file commit HEAD^ | sed -e "1,/^\$/d" >actual &&
+ test_cmp expected-initial-signed actual &&
+ git cat-file commit HEAD | sed -e "1,/^\$/d" >actual &&
+ test_cmp expected-signed actual
+'
+
+test_expect_success 'rebase -i --signoff fails' '
+ git commit --amend -m "first" &&
+ git rebase -i --signoff HEAD^ &&
+ git cat-file commit HEAD | sed -e "1,/^\$/d" >actual &&
+ test_cmp expected-signed actual
+'
+
+test_expect_success 'rebase -m --signoff fails' '
+ git commit --amend -m "first" &&
+ git rebase -m --signoff HEAD^ &&
+ git cat-file commit HEAD | sed -e "1,/^\$/d" >actual &&
+ test_cmp expected-signed actual
+'
test_done
diff --git a/t/t3430-rebase-merges.sh b/t/t3430-rebase-merges.sh
new file mode 100755
index 0000000..ce6de6f
--- /dev/null
+++ b/t/t3430-rebase-merges.sh
@@ -0,0 +1,316 @@
+#!/bin/sh
+#
+# Copyright (c) 2018 Johannes E. Schindelin
+#
+
+test_description='git rebase -i --rebase-merges
+
+This test runs git rebase "interactively", retaining the branch structure by
+recreating merge commits.
+
+Initial setup:
+
+ -- B -- (first)
+ / \
+ A - C - D - E - H (master)
+ \ /
+ F - G (second)
+'
+. ./test-lib.sh
+. "$TEST_DIRECTORY"/lib-rebase.sh
+
+test_cmp_graph () {
+ cat >expect &&
+ git log --graph --boundary --format=%s "$@" >output &&
+ sed "s/ *$//" <output >output.trimmed &&
+ test_cmp expect output.trimmed
+}
+
+test_expect_success 'setup' '
+ write_script replace-editor.sh <<-\EOF &&
+ mv "$1" "$(git rev-parse --git-path ORIGINAL-TODO)"
+ cp script-from-scratch "$1"
+ EOF
+
+ test_commit A &&
+ git checkout -b first &&
+ test_commit B &&
+ git checkout master &&
+ test_commit C &&
+ test_commit D &&
+ git merge --no-commit B &&
+ test_tick &&
+ git commit -m E &&
+ git tag -m E E &&
+ git checkout -b second C &&
+ test_commit F &&
+ test_commit G &&
+ git checkout master &&
+ git merge --no-commit G &&
+ test_tick &&
+ git commit -m H &&
+ git tag -m H H
+'
+
+test_expect_success 'create completely different structure' '
+ cat >script-from-scratch <<-\EOF &&
+ label onto
+
+ # onebranch
+ pick G
+ pick D
+ label onebranch
+
+ # second
+ reset onto
+ pick B
+ label second
+
+ reset onto
+ merge -C H second
+ merge onebranch # Merge the topic branch '\''onebranch'\''
+ EOF
+ test_config sequence.editor \""$PWD"/replace-editor.sh\" &&
+ test_tick &&
+ git rebase -i -r A &&
+ test_cmp_graph <<-\EOF
+ * Merge the topic branch '\''onebranch'\''
+ |\
+ | * D
+ | * G
+ * | H
+ |\ \
+ | |/
+ |/|
+ | * B
+ |/
+ * A
+ EOF
+'
+
+test_expect_success 'generate correct todo list' '
+ cat >expect <<-\EOF &&
+ label onto
+
+ reset onto
+ pick d9df450 B
+ label E
+
+ reset onto
+ pick 5dee784 C
+ label branch-point
+ pick ca2c861 F
+ pick 088b00a G
+ label H
+
+ reset branch-point # C
+ pick 12bd07b D
+ merge -C 2051b56 E # E
+ merge -C 233d48a H # H
+
+ EOF
+
+ grep -v "^#" <.git/ORIGINAL-TODO >output &&
+ test_cmp expect output
+'
+
+test_expect_success '`reset` refuses to overwrite untracked files' '
+ git checkout -b refuse-to-reset &&
+ test_commit dont-overwrite-untracked &&
+ git checkout @{-1} &&
+ : >dont-overwrite-untracked.t &&
+ echo "reset refs/tags/dont-overwrite-untracked" >script-from-scratch &&
+ test_config sequence.editor \""$PWD"/replace-editor.sh\" &&
+ test_must_fail git rebase -r HEAD &&
+ git rebase --abort
+'
+
+test_expect_success 'failed `merge` writes patch (may be rescheduled, too)' '
+ test_when_finished "test_might_fail git rebase --abort" &&
+ git checkout -b conflicting-merge A &&
+
+ : fail because of conflicting untracked file &&
+ >G.t &&
+ echo "merge -C H G" >script-from-scratch &&
+ test_config sequence.editor \""$PWD"/replace-editor.sh\" &&
+ test_tick &&
+ test_must_fail git rebase -ir HEAD &&
+ grep "^merge -C .* G$" .git/rebase-merge/done &&
+ grep "^merge -C .* G$" .git/rebase-merge/git-rebase-todo &&
+ test_path_is_file .git/rebase-merge/patch &&
+
+ : fail because of merge conflict &&
+ rm G.t .git/rebase-merge/patch &&
+ git reset --hard &&
+ test_commit conflicting-G G.t not-G conflicting-G &&
+ test_must_fail git rebase --continue &&
+ ! grep "^merge -C .* G$" .git/rebase-merge/git-rebase-todo &&
+ test_path_is_file .git/rebase-merge/patch
+'
+
+test_expect_success 'with a branch tip that was cherry-picked already' '
+ git checkout -b already-upstream master &&
+ base="$(git rev-parse --verify HEAD)" &&
+
+ test_commit A1 &&
+ test_commit A2 &&
+ git reset --hard $base &&
+ test_commit B1 &&
+ test_tick &&
+ git merge -m "Merge branch A" A2 &&
+
+ git checkout -b upstream-with-a2 $base &&
+ test_tick &&
+ git cherry-pick A2 &&
+
+ git checkout already-upstream &&
+ test_tick &&
+ git rebase -i -r upstream-with-a2 &&
+ test_cmp_graph upstream-with-a2.. <<-\EOF
+ * Merge branch A
+ |\
+ | * A1
+ * | B1
+ |/
+ o A2
+ EOF
+'
+
+test_expect_success 'do not rebase cousins unless asked for' '
+ git checkout -b cousins master &&
+ before="$(git rev-parse --verify HEAD)" &&
+ test_tick &&
+ git rebase -r HEAD^ &&
+ test_cmp_rev HEAD $before &&
+ test_tick &&
+ git rebase --rebase-merges=rebase-cousins HEAD^ &&
+ test_cmp_graph HEAD^.. <<-\EOF
+ * Merge the topic branch '\''onebranch'\''
+ |\
+ | * D
+ | * G
+ |/
+ o H
+ EOF
+'
+
+test_expect_success 'refs/rewritten/* is worktree-local' '
+ git worktree add wt &&
+ cat >wt/script-from-scratch <<-\EOF &&
+ label xyz
+ exec GIT_DIR=../.git git rev-parse --verify refs/rewritten/xyz >a || :
+ exec git rev-parse --verify refs/rewritten/xyz >b
+ EOF
+
+ test_config -C wt sequence.editor \""$PWD"/replace-editor.sh\" &&
+ git -C wt rebase -i HEAD &&
+ test_must_be_empty wt/a &&
+ test_cmp_rev HEAD "$(cat wt/b)"
+'
+
+test_expect_success 'post-rewrite hook and fixups work for merges' '
+ git checkout -b post-rewrite &&
+ test_commit same1 &&
+ git reset --hard HEAD^ &&
+ test_commit same2 &&
+ git merge -m "to fix up" same1 &&
+ echo same old same old >same2.t &&
+ test_tick &&
+ git commit --fixup HEAD same2.t &&
+ fixup="$(git rev-parse HEAD)" &&
+
+ mkdir -p .git/hooks &&
+ test_when_finished "rm .git/hooks/post-rewrite" &&
+ echo "cat >actual" | write_script .git/hooks/post-rewrite &&
+
+ test_tick &&
+ git rebase -i --autosquash -r HEAD^^^ &&
+ printf "%s %s\n%s %s\n%s %s\n%s %s\n" >expect $(git rev-parse \
+ $fixup^^2 HEAD^2 \
+ $fixup^^ HEAD^ \
+ $fixup^ HEAD \
+ $fixup HEAD) &&
+ test_cmp expect actual
+'
+
+test_expect_success 'refuse to merge ancestors of HEAD' '
+ echo "merge HEAD^" >script-from-scratch &&
+ test_config -C wt sequence.editor \""$PWD"/replace-editor.sh\" &&
+ before="$(git rev-parse HEAD)" &&
+ git rebase -i HEAD &&
+ test_cmp_rev HEAD $before
+'
+
+test_expect_success 'root commits' '
+ git checkout --orphan unrelated &&
+ (GIT_AUTHOR_NAME="Parsnip" GIT_AUTHOR_EMAIL="root@example.com" \
+ test_commit second-root) &&
+ test_commit third-root &&
+ cat >script-from-scratch <<-\EOF &&
+ pick third-root
+ label first-branch
+ reset [new root]
+ pick second-root
+ merge first-branch # Merge the 3rd root
+ EOF
+ test_config sequence.editor \""$PWD"/replace-editor.sh\" &&
+ test_tick &&
+ git rebase -i --force --root -r &&
+ test "Parsnip" = "$(git show -s --format=%an HEAD^)" &&
+ test $(git rev-parse second-root^0) != $(git rev-parse HEAD^) &&
+ test $(git rev-parse second-root:second-root.t) = \
+ $(git rev-parse HEAD^:second-root.t) &&
+ test_cmp_graph HEAD <<-\EOF &&
+ * Merge the 3rd root
+ |\
+ | * third-root
+ * second-root
+ EOF
+
+ : fast forward if possible &&
+ before="$(git rev-parse --verify HEAD)" &&
+ test_might_fail git config --unset sequence.editor &&
+ test_tick &&
+ git rebase -i --root -r &&
+ test_cmp_rev HEAD $before
+'
+
+test_expect_success 'a "merge" into a root commit is a fast-forward' '
+ head=$(git rev-parse HEAD) &&
+ cat >script-from-scratch <<-EOF &&
+ reset [new root]
+ merge $head
+ EOF
+ test_config sequence.editor \""$PWD"/replace-editor.sh\" &&
+ test_tick &&
+ git rebase -i -r HEAD^ &&
+ test_cmp_rev HEAD $head
+'
+
+test_expect_success 'A root commit can be a cousin, treat it that way' '
+ git checkout --orphan khnum &&
+ test_commit yama &&
+ git checkout -b asherah master &&
+ test_commit shamkat &&
+ git merge --allow-unrelated-histories khnum &&
+ test_tick &&
+ git rebase -f -r HEAD^ &&
+ ! test_cmp_rev HEAD^2 khnum &&
+ test_cmp_graph HEAD^.. <<-\EOF &&
+ * Merge branch '\''khnum'\'' into asherah
+ |\
+ | * yama
+ o shamkat
+ EOF
+ test_tick &&
+ git rebase --rebase-merges=rebase-cousins HEAD^ &&
+ test_cmp_graph HEAD^.. <<-\EOF
+ * Merge branch '\''khnum'\'' into asherah
+ |\
+ | * yama
+ |/
+ o shamkat
+ EOF
+'
+
+test_done
diff --git a/t/t3510-cherry-pick-sequence.sh b/t/t3510-cherry-pick-sequence.sh
index 9f93445..b42cd66 100755
--- a/t/t3510-cherry-pick-sequence.sh
+++ b/t/t3510-cherry-pick-sequence.sh
@@ -122,7 +122,7 @@ test_expect_success '--quit keeps HEAD and conflicted index intact' '
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
test_cmp expect actual
'
@@ -220,7 +220,7 @@ test_expect_success 'cherry-pick still writes sequencer state when one commit is
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
cat >expect <<-\EOF &&
OBJID
@@ -247,9 +247,9 @@ test_expect_success '--abort after last commit in sequence' '
test_expect_success 'cherry-pick does not implicitly stomp an existing operation' '
pristine_detach initial &&
test_expect_code 1 git cherry-pick base..anotherpick &&
- test-tool chmtime -v +0 .git/sequencer >expect &&
+ test-tool chmtime --get .git/sequencer >expect &&
test_expect_code 128 git cherry-pick unrelatedpick &&
- test-tool chmtime -v +0 .git/sequencer >actual &&
+ test-tool chmtime --get .git/sequencer >actual &&
test_cmp expect actual
'
@@ -317,7 +317,7 @@ test_expect_success '--continue after resolving conflicts' '
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual.log &&
test_cmp expect foo &&
test_cmp expect.log actual.log
@@ -334,7 +334,7 @@ test_expect_success '--continue after resolving conflicts and committing' '
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
cat >expect <<-\EOF &&
OBJID
diff --git a/t/t3702-add-edit.sh b/t/t3702-add-edit.sh
index 3cb74ca..c6af7f8 100755
--- a/t/t3702-add-edit.sh
+++ b/t/t3702-add-edit.sh
@@ -40,7 +40,6 @@ test_expect_success 'setup' '
cat > expected-patch << EOF
diff --git a/file b/file
-index b9834b5..9020acb 100644
--- a/file
+++ b/file
@@ -1,11 +1,6 @@
@@ -80,7 +79,6 @@ EOF
cat > expected << EOF
diff --git a/file b/file
-index b9834b5..ef6e94c 100644
--- a/file
+++ b/file
@@ -1,10 +1,12 @@
@@ -100,7 +98,7 @@ EOF
echo "#!$SHELL_PATH" >fake-editor.sh
cat >> fake-editor.sh <<\EOF
-mv -f "$1" orig-patch &&
+egrep -v '^index' "$1" >orig-patch &&
mv -f patch "$1"
EOF
@@ -113,7 +111,8 @@ test_expect_success 'add -e' '
git add -e &&
test_cmp second-part file &&
test_cmp orig-patch expected-patch &&
- git diff --cached > out &&
+ git diff --cached >actual &&
+ grep -v index actual >out &&
test_cmp out expected
'
diff --git a/t/t3905-stash-include-untracked.sh b/t/t3905-stash-include-untracked.sh
index 3ea5b9b..597b063 100755
--- a/t/t3905-stash-include-untracked.sh
+++ b/t/t3905-stash-include-untracked.sh
@@ -35,24 +35,26 @@ test_expect_success 'stash save --include-untracked cleaned the untracked files'
test_cmp expect actual
'
+tracked=$(git rev-parse --short $(echo 1 | git hash-object --stdin))
+untracked=$(git rev-parse --short $(echo untracked | git hash-object --stdin))
cat > expect.diff <<EOF
diff --git a/HEAD b/HEAD
new file mode 100644
-index 0000000..d00491f
+index 0000000..$tracked
--- /dev/null
+++ b/HEAD
@@ -0,0 +1 @@
+1
diff --git a/file2 b/file2
new file mode 100644
-index 0000000..d00491f
+index 0000000..$tracked
--- /dev/null
+++ b/file2
@@ -0,0 +1 @@
+1
diff --git a/untracked/untracked b/untracked/untracked
new file mode 100644
-index 0000000..5a72eb2
+index 0000000..$untracked
--- /dev/null
+++ b/untracked/untracked
@@ -0,0 +1 @@
@@ -109,10 +111,11 @@ test_expect_success 'stash save -u dirty index' '
git stash -u
'
+blob=$(git rev-parse --short $(echo 4 | git hash-object --stdin))
cat > expect <<EOF
diff --git a/file3 b/file3
new file mode 100644
-index 0000000..b8626c4
+index 0000000..$blob
--- /dev/null
+++ b/file3
@@ -0,0 +1 @@
diff --git a/t/t4001-diff-rename.sh b/t/t4001-diff-rename.sh
index a07816d..bf40303 100755
--- a/t/t4001-diff-rename.sh
+++ b/t/t4001-diff-rename.sh
@@ -138,6 +138,18 @@ test_expect_success 'favour same basenames over different ones' '
test_i18ngrep "renamed: .*path1 -> subdir/path1" out
'
+test_expect_success 'test diff.renames=true for git status' '
+ git -c diff.renames=true status >out &&
+ test_i18ngrep "renamed: .*path1 -> subdir/path1" out
+'
+
+test_expect_success 'test diff.renames=false for git status' '
+ git -c diff.renames=false status >out &&
+ test_i18ngrep ! "renamed: .*path1 -> subdir/path1" out &&
+ test_i18ngrep "new file: .*subdir/path1" out &&
+ test_i18ngrep "deleted: .*[^/]path1" out
+'
+
test_expect_success 'favour same basenames even with minor differences' '
git show HEAD:path1 | sed "s/15/16/" > subdir/path1 &&
git status >out &&
diff --git a/t/t4002-diff-basic.sh b/t/t4002-diff-basic.sh
index a5e8b83..3a6c21e 100755
--- a/t/t4002-diff-basic.sh
+++ b/t/t4002-diff-basic.sh
@@ -131,7 +131,7 @@ cmp_diff_files_output () {
# object ID for the changed files because it wants you to look at the
# filesystem.
sed <"$2" >.test-tmp \
- -e '/^:000000 /d;s/'$_x40'\( [MCRNDU][0-9]*\) /'$_z40'\1 /' &&
+ -e '/^:000000 /d;s/'$OID_REGEX'\( [MCRNDU][0-9]*\) /'$ZERO_OID'\1 /' &&
test_cmp "$1" .test-tmp
}
diff --git a/t/t4006-diff-mode.sh b/t/t4006-diff-mode.sh
index 76f643b..a8e01ec 100755
--- a/t/t4006-diff-mode.sh
+++ b/t/t4006-diff-mode.sh
@@ -8,7 +8,7 @@ test_description='Test mode change diffs.
'
. ./test-lib.sh
-sed_script='s/\(:100644 100755\) \('"$_x40"'\) \2 /\1 X X /'
+sed_script='s/\(:100644 100755\) \('"$OID_REGEX"'\) \2 /\1 X X /'
test_expect_success 'setup' '
echo frotz >rezrov &&
diff --git a/t/t4007-rename-3.sh b/t/t4007-rename-3.sh
index dae327f..b187b7f 100755
--- a/t/t4007-rename-3.sh
+++ b/t/t4007-rename-3.sh
@@ -17,6 +17,7 @@ test_expect_success 'prepare reference tree' '
echo $tree
'
+blob=$(git hash-object "$TEST_DIRECTORY/diff-lib/COPYING")
test_expect_success 'prepare work tree' '
cp path0/COPYING path1/COPYING &&
git update-index --add --remove path0/COPYING path1/COPYING
@@ -26,8 +27,8 @@ test_expect_success 'prepare work tree' '
# path1 both have COPYING and the latter is a copy of path0/COPYING.
# Comparing the full tree with cache should tell us so.
-cat >expected <<\EOF
-:100644 100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 6ff87c4664981e4397625791c8ea3bbb5f2279a3 C100 path0/COPYING path1/COPYING
+cat >expected <<EOF
+:100644 100644 $blob $blob C100 path0/COPYING path1/COPYING
EOF
test_expect_success 'copy detection' '
@@ -46,8 +47,8 @@ test_expect_success 'copy detection, cached' '
# path1/COPYING suddenly appearing from nowhere, not detected as
# a copy from path0/COPYING.
-cat >expected <<\EOF
-:000000 100644 0000000000000000000000000000000000000000 6ff87c4664981e4397625791c8ea3bbb5f2279a3 A path1/COPYING
+cat >expected <<EOF
+:000000 100644 $ZERO_OID $blob A path1/COPYING
EOF
test_expect_success 'copy, limited to a subtree' '
@@ -64,8 +65,8 @@ test_expect_success 'tweak work tree' '
# path0/COPYING. Showing the full tree with cache should tell us about
# the rename.
-cat >expected <<\EOF
-:100644 100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 6ff87c4664981e4397625791c8ea3bbb5f2279a3 R100 path0/COPYING path1/COPYING
+cat >expected <<EOF
+:100644 100644 $blob $blob R100 path0/COPYING path1/COPYING
EOF
test_expect_success 'rename detection' '
@@ -78,8 +79,8 @@ test_expect_success 'rename detection' '
# path0/COPYING. When we say we care only about path1, we should just
# see path1/COPYING appearing from nowhere.
-cat >expected <<\EOF
-:000000 100644 0000000000000000000000000000000000000000 6ff87c4664981e4397625791c8ea3bbb5f2279a3 A path1/COPYING
+cat >expected <<EOF
+:000000 100644 $ZERO_OID $blob A path1/COPYING
EOF
test_expect_success 'rename, limited to a subtree' '
diff --git a/t/t4008-diff-break-rewrite.sh b/t/t4008-diff-break-rewrite.sh
index 9dd1bc5..b1ccd41 100755
--- a/t/t4008-diff-break-rewrite.sh
+++ b/t/t4008-diff-break-rewrite.sh
@@ -27,29 +27,32 @@ Further, with -B and -M together, these should turn into two renames.
test_expect_success setup '
cat "$TEST_DIRECTORY"/diff-lib/README >file0 &&
cat "$TEST_DIRECTORY"/diff-lib/COPYING >file1 &&
+ blob0_id=$(git hash-object file0) &&
+ blob1_id=$(git hash-object file1) &&
git update-index --add file0 file1 &&
git tag reference $(git write-tree)
'
test_expect_success 'change file1 with copy-edit of file0 and remove file0' '
sed -e "s/git/GIT/" file0 >file1 &&
+ blob2_id=$(git hash-object file1) &&
rm -f file0 &&
git update-index --remove file0 file1
'
test_expect_success 'run diff with -B (#1)' '
git diff-index -B --cached reference >current &&
- cat >expect <<-\EOF &&
- :100644 000000 548142c327a6790ff8821d67c2ee1eff7a656b52 0000000000000000000000000000000000000000 D file0
- :100644 100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 2fbedd0b5d4b8126e4750c3bee305e8ff79f80ec M100 file1
+ cat >expect <<-EOF &&
+ :100644 000000 $blob0_id $ZERO_OID D file0
+ :100644 100644 $blob1_id $blob2_id M100 file1
EOF
compare_diff_raw expect current
'
test_expect_success 'run diff with -B and -M (#2)' '
git diff-index -B -M reference >current &&
- cat >expect <<-\EOF &&
- :100644 100644 548142c327a6790ff8821d67c2ee1eff7a656b52 2fbedd0b5d4b8126e4750c3bee305e8ff79f80ec R100 file0 file1
+ cat >expect <<-EOF &&
+ :100644 100644 $blob0_id $blob2_id R100 file0 file1
EOF
compare_diff_raw expect current
'
@@ -66,18 +69,18 @@ test_expect_success 'swap file0 and file1' '
test_expect_success 'run diff with -B (#3)' '
git diff-index -B reference >current &&
- cat >expect <<-\EOF &&
- :100644 100644 548142c327a6790ff8821d67c2ee1eff7a656b52 6ff87c4664981e4397625791c8ea3bbb5f2279a3 M100 file0
- :100644 100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 548142c327a6790ff8821d67c2ee1eff7a656b52 M100 file1
+ cat >expect <<-EOF &&
+ :100644 100644 $blob0_id $blob1_id M100 file0
+ :100644 100644 $blob1_id $blob0_id M100 file1
EOF
compare_diff_raw expect current
'
test_expect_success 'run diff with -B and -M (#4)' '
git diff-index -B -M reference >current &&
- cat >expect <<-\EOF &&
- :100644 100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 6ff87c4664981e4397625791c8ea3bbb5f2279a3 R100 file1 file0
- :100644 100644 548142c327a6790ff8821d67c2ee1eff7a656b52 548142c327a6790ff8821d67c2ee1eff7a656b52 R100 file0 file1
+ cat >expect <<-EOF &&
+ :100644 100644 $blob1_id $blob1_id R100 file1 file0
+ :100644 100644 $blob0_id $blob0_id R100 file0 file1
EOF
compare_diff_raw expect current
'
@@ -85,14 +88,15 @@ test_expect_success 'run diff with -B and -M (#4)' '
test_expect_success 'make file0 into something completely different' '
rm -f file0 &&
test_ln_s_add frotz file0 &&
+ slink_id=$(printf frotz | git hash-object --stdin) &&
git update-index file1
'
test_expect_success 'run diff with -B (#5)' '
git diff-index -B reference >current &&
- cat >expect <<-\EOF &&
- :100644 120000 548142c327a6790ff8821d67c2ee1eff7a656b52 67be421f88824578857624f7b3dc75e99a8a1481 T file0
- :100644 100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 548142c327a6790ff8821d67c2ee1eff7a656b52 M100 file1
+ cat >expect <<-EOF &&
+ :100644 120000 $blob0_id $slink_id T file0
+ :100644 100644 $blob1_id $blob0_id M100 file1
EOF
compare_diff_raw expect current
'
@@ -103,9 +107,9 @@ test_expect_success 'run diff with -B -M (#6)' '
# file0 changed from regular to symlink. file1 is the same as the preimage
# of file0. Because the change does not make file0 disappear, file1 is
# denoted as a copy of file0
- cat >expect <<-\EOF &&
- :100644 120000 548142c327a6790ff8821d67c2ee1eff7a656b52 67be421f88824578857624f7b3dc75e99a8a1481 T file0
- :100644 100644 548142c327a6790ff8821d67c2ee1eff7a656b52 548142c327a6790ff8821d67c2ee1eff7a656b52 C file0 file1
+ cat >expect <<-EOF &&
+ :100644 120000 $blob0_id $slink_id T file0
+ :100644 100644 $blob0_id $blob0_id C file0 file1
EOF
compare_diff_raw expect current
'
@@ -115,9 +119,9 @@ test_expect_success 'run diff with -M (#7)' '
# This should not mistake file0 as the copy source of new file1
# due to type differences.
- cat >expect <<-\EOF &&
- :100644 120000 548142c327a6790ff8821d67c2ee1eff7a656b52 67be421f88824578857624f7b3dc75e99a8a1481 T file0
- :100644 100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 548142c327a6790ff8821d67c2ee1eff7a656b52 M file1
+ cat >expect <<-EOF &&
+ :100644 120000 $blob0_id $slink_id T file0
+ :100644 100644 $blob1_id $blob0_id M file1
EOF
compare_diff_raw expect current
'
@@ -128,25 +132,26 @@ test_expect_success 'file1 edited to look like file0 and file0 rename-edited to
git checkout-index -f -u -a &&
sed -e "s/git/GIT/" file0 >file1 &&
sed -e "s/git/GET/" file0 >file2 &&
+ blob3_id=$(git hash-object file2) &&
rm -f file0 &&
git update-index --add --remove file0 file1 file2
'
test_expect_success 'run diff with -B (#8)' '
git diff-index -B reference >current &&
- cat >expect <<-\EOF &&
- :100644 000000 548142c327a6790ff8821d67c2ee1eff7a656b52 0000000000000000000000000000000000000000 D file0
- :100644 100644 6ff87c4664981e4397625791c8ea3bbb5f2279a3 2fbedd0b5d4b8126e4750c3bee305e8ff79f80ec M100 file1
- :000000 100644 0000000000000000000000000000000000000000 69a939f651686f56322566e2fd76715947a24162 A file2
+ cat >expect <<-EOF &&
+ :100644 000000 $blob0_id $ZERO_OID D file0
+ :100644 100644 $blob1_id $blob2_id M100 file1
+ :000000 100644 $ZERO_OID $blob3_id A file2
EOF
compare_diff_raw expect current
'
test_expect_success 'run diff with -B -C (#9)' '
git diff-index -B -C reference >current &&
- cat >expect <<-\EOF &&
- :100644 100644 548142c327a6790ff8821d67c2ee1eff7a656b52 2fbedd0b5d4b8126e4750c3bee305e8ff79f80ec C095 file0 file1
- :100644 100644 548142c327a6790ff8821d67c2ee1eff7a656b52 69a939f651686f56322566e2fd76715947a24162 R095 file0 file2
+ cat >expect <<-EOF &&
+ :100644 100644 $blob0_id $blob2_id C095 file0 file1
+ :100644 100644 $blob0_id $blob3_id R095 file0 file2
EOF
compare_diff_raw expect current
'
diff --git a/t/t4014-format-patch.sh b/t/t4014-format-patch.sh
index 482112c..028d550 100755
--- a/t/t4014-format-patch.sh
+++ b/t/t4014-format-patch.sh
@@ -578,7 +578,11 @@ test_expect_success 'excessive subject' '
rm -rf patches/ &&
git checkout side &&
+ before=$(git hash-object file) &&
+ before=$(git rev-parse --short $before) &&
for i in 5 6 1 2 3 A 4 B C 7 8 9 10 D E F; do echo "$i"; done >>file &&
+ after=$(git hash-object file) &&
+ after=$(git rev-parse --short $after) &&
git update-index file &&
git commit -m "This is an excessively long subject line for a message due to the habit some projects have of not having a short, one-line subject at the start of the commit message, but rather sticking a whole paragraph right at the start as the only thing in the commit message. It had better not become the filename for the patch." &&
git format-patch -o patches/ master..side &&
@@ -586,7 +590,6 @@ test_expect_success 'excessive subject' '
'
test_expect_success 'cover-letter inherits diff options' '
-
git mv file foo &&
git commit -m foo &&
git format-patch --no-renames --cover-letter -1 &&
@@ -616,7 +619,7 @@ test_expect_success 'shortlog of cover-letter wraps overly-long onelines' '
'
cat > expect << EOF
-index 40f36c6..2dc5c23 100644
+index $before..$after 100644
--- a/file
+++ b/file
@@ -13,4 +13,20 @@ C
@@ -640,7 +643,7 @@ test_expect_success 'format-patch respects -U' '
cat > expect << EOF
diff --git a/file b/file
-index 40f36c6..2dc5c23 100644
+index $before..$after 100644
--- a/file
+++ b/file
@@ -14,3 +14,19 @@ C
@@ -1523,14 +1526,14 @@ test_expect_success 'cover letter auto user override' '
test_expect_success 'format-patch --zero-commit' '
git format-patch --zero-commit --stdout v2..v1 >patch2 &&
grep "^From " patch2 | sort | uniq >actual &&
- echo "From $_z40 Mon Sep 17 00:00:00 2001" >expect &&
+ echo "From $ZERO_OID Mon Sep 17 00:00:00 2001" >expect &&
test_cmp expect actual
'
test_expect_success 'From line has expected format' '
git format-patch --stdout v2..v1 >patch2 &&
grep "^From " patch2 >from &&
- grep "^From $_x40 Mon Sep 17 00:00:00 2001$" patch2 >filtered &&
+ grep "^From $OID_REGEX Mon Sep 17 00:00:00 2001$" patch2 >filtered &&
test_cmp from filtered
'
@@ -1661,6 +1664,15 @@ test_expect_success 'format-patch --base with --attach' '
test_write_lines 1 2 >expect &&
test_cmp expect actual
'
+test_expect_success 'format-patch --attach cover-letter only is non-multipart' '
+ test_when_finished "rm -fr patches" &&
+ git format-patch -o patches --cover-letter --attach=mimemime --base=HEAD~ -1 &&
+ ! egrep "^--+mimemime" patches/0000*.patch &&
+ egrep "^--+mimemime$" patches/0001*.patch >output &&
+ test_line_count = 2 output &&
+ egrep "^--+mimemime--$" patches/0001*.patch >output &&
+ test_line_count = 1 output
+'
test_expect_success 'format-patch --pretty=mboxrd' '
sp=" " &&
diff --git a/t/t4020-diff-external.sh b/t/t4020-diff-external.sh
index 0446201..e009826 100755
--- a/t/t4020-diff-external.sh
+++ b/t/t4020-diff-external.sh
@@ -13,6 +13,8 @@ test_expect_success setup '
test_tick &&
echo second >file &&
+ before=$(git hash-object file) &&
+ before=$(git rev-parse --short $before) &&
git add file &&
git commit -m second &&
@@ -26,7 +28,7 @@ test_expect_success 'GIT_EXTERNAL_DIFF environment' '
read path oldfile oldhex oldmode newfile newhex newmode &&
test "z$path" = zfile &&
test "z$oldmode" = z100644 &&
- test "z$newhex" = "z$_z40" &&
+ test "z$newhex" = "z$ZERO_OID" &&
test "z$newmode" = z100644 &&
oh=$(git rev-parse --verify HEAD:file) &&
test "z$oh" = "z$oldhex"
@@ -55,7 +57,7 @@ test_expect_success SYMLINKS 'typechange diff' '
read path oldfile oldhex oldmode newfile newhex newmode &&
test "z$path" = zfile &&
test "z$oldmode" = z100644 &&
- test "z$newhex" = "z$_z40" &&
+ test "z$newhex" = "z$ZERO_OID" &&
test "z$newmode" = z120000 &&
oh=$(git rev-parse --verify HEAD:file) &&
test "z$oh" = "z$oldhex"
@@ -73,7 +75,7 @@ test_expect_success 'diff.external' '
read path oldfile oldhex oldmode newfile newhex newmode &&
test "z$path" = zfile &&
test "z$oldmode" = z100644 &&
- test "z$newhex" = "z$_z40" &&
+ test "z$newhex" = "z$ZERO_OID" &&
test "z$newmode" = z100644 &&
oh=$(git rev-parse --verify HEAD:file) &&
test "z$oh" = "z$oldhex"
@@ -104,7 +106,7 @@ test_expect_success 'diff attribute' '
read path oldfile oldhex oldmode newfile newhex newmode &&
test "z$path" = zfile &&
test "z$oldmode" = z100644 &&
- test "z$newhex" = "z$_z40" &&
+ test "z$newhex" = "z$ZERO_OID" &&
test "z$newmode" = z100644 &&
oh=$(git rev-parse --verify HEAD:file) &&
test "z$oh" = "z$oldhex"
@@ -137,7 +139,7 @@ test_expect_success 'diff attribute' '
read path oldfile oldhex oldmode newfile newhex newmode &&
test "z$path" = zfile &&
test "z$oldmode" = z100644 &&
- test "z$newhex" = "z$_z40" &&
+ test "z$newhex" = "z$ZERO_OID" &&
test "z$newmode" = z100644 &&
oh=$(git rev-parse --verify HEAD:file) &&
test "z$oh" = "z$oldhex"
@@ -180,9 +182,13 @@ test_expect_success 'no diff with -diff' '
echo NULZbetweenZwords | perl -pe 'y/Z/\000/' > file
test_expect_success 'force diff with "diff"' '
+ after=$(git hash-object file) &&
+ after=$(git rev-parse --short $after) &&
echo >.gitattributes "file diff" &&
git diff >actual &&
- test_cmp "$TEST_DIRECTORY"/t4020/diff.NUL actual
+ sed -e "s/^index .*/index $before..$after 100644/" \
+ "$TEST_DIRECTORY"/t4020/diff.NUL >expected-diff &&
+ test_cmp expected-diff actual
'
test_expect_success 'GIT_EXTERNAL_DIFF with more than one changed files' '
@@ -237,7 +243,7 @@ test_expect_success 'diff --cached' '
git update-index --assume-unchanged file &&
echo second >file &&
git diff --cached >actual &&
- test_cmp "$TEST_DIRECTORY"/t4020/diff.NUL actual
+ test_cmp expected-diff actual
'
test_expect_success 'clean up crlf leftovers' '
diff --git a/t/t4022-diff-rewrite.sh b/t/t4022-diff-rewrite.sh
index cb51d9f..6d1c3d9 100755
--- a/t/t4022-diff-rewrite.sh
+++ b/t/t4022-diff-rewrite.sh
@@ -13,6 +13,8 @@ test_expect_success setup '
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM" \
<"$TEST_DIRECTORY"/../COPYING >test &&
echo "to be deleted" >test2 &&
+ blob=$(git hash-object test2) &&
+ blob=$(git rev-parse --short $blob) &&
git add test2
'
@@ -27,7 +29,7 @@ test_expect_success 'detect rewrite' '
cat >expect <<EOF
diff --git a/test2 b/test2
deleted file mode 100644
-index 4202011..0000000
+index $blob..0000000
--- a/test2
+++ /dev/null
@@ -1 +0,0 @@
@@ -43,7 +45,7 @@ test_expect_success 'show deletion diff without -D' '
cat >expect <<EOF
diff --git a/test2 b/test2
deleted file mode 100644
-index 4202011..0000000
+index $blob..0000000
EOF
test_expect_success 'suppress deletion diff with -D' '
diff --git a/t/t4027-diff-submodule.sh b/t/t4027-diff-submodule.sh
index 2ffd11a..6304130 100755
--- a/t/t4027-diff-submodule.sh
+++ b/t/t4027-diff-submodule.sh
@@ -31,7 +31,7 @@ test_expect_success setup '
cd sub &&
git rev-list HEAD
) &&
- echo ":160000 160000 $3 $_z40 M sub" >expect &&
+ echo ":160000 160000 $3 $ZERO_OID M sub" >expect &&
subtip=$3 subprev=$2
'
@@ -250,7 +250,7 @@ test_expect_success 'conflicted submodule setup' '
# 39 efs
c=fffffffffffffffffffffffffffffffffffffff &&
(
- echo "000000 $_z40 0 sub" &&
+ echo "000000 $ZERO_OID 0 sub" &&
echo "160000 1$c 1 sub" &&
echo "160000 2$c 2 sub" &&
echo "160000 3$c 3 sub"
@@ -265,7 +265,7 @@ index 2ffffff,3ffffff..0000000
++Subproject commit 0000000000000000000000000000000000000000'\'' &&
hh=$(git rev-parse HEAD) &&
- sed -e "s/$_z40/$hh/" expect.nosub >expect.withsub
+ sed -e "s/$ZERO_OID/$hh/" expect.nosub >expect.withsub
'
diff --git a/t/t4029-diff-trailing-space.sh b/t/t4029-diff-trailing-space.sh
index 3ccc237..32b6e9a 100755
--- a/t/t4029-diff-trailing-space.sh
+++ b/t/t4029-diff-trailing-space.sh
@@ -6,7 +6,7 @@ test_description='diff honors config option, diff.suppressBlankEmpty'
. ./test-lib.sh
-cat <<\EOF > exp ||
+cat <<\EOF >expected ||
diff --git a/f b/f
index 5f6a263..8cb8bae 100644
--- a/f
@@ -18,22 +18,26 @@ index 5f6a263..8cb8bae 100644
EOF
exit 1
-test_expect_success \
- "$test_description" \
- 'printf "\nx\n" > f &&
- git add f &&
- git commit -q -m. f &&
- printf "\ny\n" > f &&
- git config --bool diff.suppressBlankEmpty true &&
- git diff f > actual &&
- test_cmp exp actual &&
- perl -i.bak -p -e "s/^\$/ /" exp &&
- git config --bool diff.suppressBlankEmpty false &&
- git diff f > actual &&
- test_cmp exp actual &&
- git config --bool --unset diff.suppressBlankEmpty &&
- git diff f > actual &&
- test_cmp exp actual
- '
+test_expect_success "$test_description" '
+ printf "\nx\n" > f &&
+ before=$(git hash-object f) &&
+ before=$(git rev-parse --short $before) &&
+ git add f &&
+ git commit -q -m. f &&
+ printf "\ny\n" > f &&
+ after=$(git hash-object f) &&
+ after=$(git rev-parse --short $after) &&
+ sed -e "s/^index .*/index $before..$after 100644/" expected >exp &&
+ git config --bool diff.suppressBlankEmpty true &&
+ git diff f > actual &&
+ test_cmp exp actual &&
+ perl -i.bak -p -e "s/^\$/ /" exp &&
+ git config --bool diff.suppressBlankEmpty false &&
+ git diff f > actual &&
+ test_cmp exp actual &&
+ git config --bool --unset diff.suppressBlankEmpty &&
+ git diff f > actual &&
+ test_cmp exp actual
+'
test_done
diff --git a/t/t4030-diff-textconv.sh b/t/t4030-diff-textconv.sh
index aad6c7f..4cb9f0e 100755
--- a/t/t4030-diff-textconv.sh
+++ b/t/t4030-diff-textconv.sh
@@ -148,7 +148,8 @@ test_expect_success 'diffstat does not run textconv' '
# restore working setup
echo file diff=foo >.gitattributes
-cat >expect.typechange <<'EOF'
+symlink=$(git rev-parse --short $(printf frotz | git hash-object --stdin))
+cat >expect.typechange <<EOF
--- a/file
+++ /dev/null
@@ -1,2 +0,0 @@
@@ -156,7 +157,7 @@ cat >expect.typechange <<'EOF'
-1
diff --git a/file b/file
new file mode 120000
-index 0000000..67be421
+index 0000000..$symlink
--- /dev/null
+++ b/file
@@ -0,0 +1 @@
diff --git a/t/t4042-diff-textconv-caching.sh b/t/t4042-diff-textconv-caching.sh
index 04a44d5..bf33aed 100755
--- a/t/t4042-diff-textconv-caching.sh
+++ b/t/t4042-diff-textconv-caching.sh
@@ -15,9 +15,13 @@ test_expect_success 'setup' '
echo bar content 1 >bar.bin &&
git add . &&
git commit -m one &&
+ foo1=$(git rev-parse --short HEAD:foo.bin) &&
+ bar1=$(git rev-parse --short HEAD:bar.bin) &&
echo foo content 2 >foo.bin &&
echo bar content 2 >bar.bin &&
git commit -a -m two &&
+ foo2=$(git rev-parse --short HEAD:foo.bin) &&
+ bar2=$(git rev-parse --short HEAD:bar.bin) &&
echo "*.bin diff=magic" >.gitattributes &&
git config diff.magic.textconv ./helper &&
git config diff.magic.cachetextconv true
@@ -25,14 +29,14 @@ test_expect_success 'setup' '
cat >expect <<EOF
diff --git a/bar.bin b/bar.bin
-index fcf9166..28283d5 100644
+index $bar1..$bar2 100644
--- a/bar.bin
+++ b/bar.bin
@@ -1 +1 @@
-converted: bar content 1
+converted: bar content 2
diff --git a/foo.bin b/foo.bin
-index d5b9fe3..1345db2 100644
+index $foo1..$foo2 100644
--- a/foo.bin
+++ b/foo.bin
@@ -1 +1 @@
@@ -59,7 +63,7 @@ test_expect_success 'cached textconv does not run helper' '
cat >expect <<EOF
diff --git a/bar.bin b/bar.bin
-index fcf9166..28283d5 100644
+index $bar1..$bar2 100644
--- a/bar.bin
+++ b/bar.bin
@@ -1,2 +1,2 @@
@@ -67,7 +71,7 @@ index fcf9166..28283d5 100644
-converted: bar content 1
+converted: bar content 2
diff --git a/foo.bin b/foo.bin
-index d5b9fe3..1345db2 100644
+index $foo1..$foo2 100644
--- a/foo.bin
+++ b/foo.bin
@@ -1,2 +1,2 @@
@@ -84,7 +88,7 @@ test_expect_success 'changing textconv invalidates cache' '
cat >expect <<EOF
diff --git a/bar.bin b/bar.bin
-index fcf9166..28283d5 100644
+index $bar1..$bar2 100644
--- a/bar.bin
+++ b/bar.bin
@@ -1,2 +1,2 @@
@@ -92,7 +96,7 @@ index fcf9166..28283d5 100644
-converted: bar content 1
+converted: bar content 2
diff --git a/foo.bin b/foo.bin
-index d5b9fe3..1345db2 100644
+index $foo1..$foo2 100644
--- a/foo.bin
+++ b/foo.bin
@@ -1 +1 @@
diff --git a/t/t4044-diff-index-unique-abbrev.sh b/t/t4044-diff-index-unique-abbrev.sh
index d5ce72b..647905e 100755
--- a/t/t4044-diff-index-unique-abbrev.sh
+++ b/t/t4044-diff-index-unique-abbrev.sh
@@ -3,6 +3,12 @@
test_description='test unique sha1 abbreviation on "index from..to" line'
. ./test-lib.sh
+if ! test_have_prereq SHA1
+then
+ skip_all='not using SHA-1 for objects'
+ test_done
+fi
+
cat >expect_initial <<EOF
100644 blob 51d2738463ea4ca66f8691c91e33ce64b7d41bb1 foo
EOF
diff --git a/t/t4045-diff-relative.sh b/t/t4045-diff-relative.sh
index 6471a68..36f8ed8 100755
--- a/t/t4045-diff-relative.sh
+++ b/t/t4045-diff-relative.sh
@@ -8,6 +8,7 @@ test_expect_success 'setup' '
echo content >file1 &&
mkdir subdir &&
echo other content >subdir/file2 &&
+ blob=$(git hash-object subdir/file2) &&
git add . &&
git commit -m one
'
@@ -17,10 +18,11 @@ check_diff () {
shift
expect=$1
shift
+ short_blob=$(git rev-parse --short $blob)
cat >expected <<-EOF
diff --git a/$expect b/$expect
new file mode 100644
- index 0000000..25c05ef
+ index 0000000..$short_blob
--- /dev/null
+++ b/$expect
@@ -0,0 +1 @@
@@ -68,7 +70,7 @@ check_raw () {
expect=$1
shift
cat >expected <<-EOF
- :000000 100644 0000000000000000000000000000000000000000 25c05ef3639d2d270e7fe765a67668f098092bc5 A $expect
+ :000000 100644 0000000000000000000000000000000000000000 $blob A $expect
EOF
test_expect_success "--raw $*" "
git -C '$dir' diff --no-abbrev --raw $* HEAD^ >actual &&
diff --git a/t/t4046-diff-unmerged.sh b/t/t4046-diff-unmerged.sh
index d0f1447..ff7cfd8 100755
--- a/t/t4046-diff-unmerged.sh
+++ b/t/t4046-diff-unmerged.sh
@@ -37,7 +37,7 @@ test_expect_success 'diff-files -0' '
for path in $paths
do
>"$path" &&
- echo ":000000 100644 $_z40 $_z40 U $path"
+ echo ":000000 100644 $ZERO_OID $ZERO_OID U $path"
done >diff-files-0.expect &&
git diff-files -0 >diff-files-0.actual &&
test_cmp diff-files-0.expect diff-files-0.actual
@@ -47,9 +47,9 @@ test_expect_success 'diff-files -1' '
for path in $paths
do
>"$path" &&
- echo ":000000 100644 $_z40 $_z40 U $path" &&
+ echo ":000000 100644 $ZERO_OID $ZERO_OID U $path" &&
case "$path" in
- x??) echo ":100644 100644 $blob1 $_z40 M $path"
+ x??) echo ":100644 100644 $blob1 $ZERO_OID M $path"
esac
done >diff-files-1.expect &&
git diff-files -1 >diff-files-1.actual &&
@@ -60,9 +60,9 @@ test_expect_success 'diff-files -2' '
for path in $paths
do
>"$path" &&
- echo ":000000 100644 $_z40 $_z40 U $path" &&
+ echo ":000000 100644 $ZERO_OID $ZERO_OID U $path" &&
case "$path" in
- ?x?) echo ":100644 100644 $blob2 $_z40 M $path"
+ ?x?) echo ":100644 100644 $blob2 $ZERO_OID M $path"
esac
done >diff-files-2.expect &&
git diff-files -2 >diff-files-2.actual &&
@@ -75,9 +75,9 @@ test_expect_success 'diff-files -3' '
for path in $paths
do
>"$path" &&
- echo ":000000 100644 $_z40 $_z40 U $path" &&
+ echo ":000000 100644 $ZERO_OID $ZERO_OID U $path" &&
case "$path" in
- ??x) echo ":100644 100644 $blob3 $_z40 M $path"
+ ??x) echo ":100644 100644 $blob3 $ZERO_OID M $path"
esac
done >diff-files-3.expect &&
git diff-files -3 >diff-files-3.actual &&
diff --git a/t/t4054-diff-bogus-tree.sh b/t/t4054-diff-bogus-tree.sh
index 18f42c5..fcae82f 100755
--- a/t/t4054-diff-bogus-tree.sh
+++ b/t/t4054-diff-bogus-tree.sh
@@ -19,37 +19,37 @@ test_expect_success 'create tree with matching file' '
'
test_expect_success 'raw diff shows null sha1 (addition)' '
- echo ":000000 100644 $_z40 $_z40 A foo" >expect &&
+ echo ":000000 100644 $ZERO_OID $ZERO_OID A foo" >expect &&
git diff-tree $EMPTY_TREE $bogus_tree >actual &&
test_cmp expect actual
'
test_expect_success 'raw diff shows null sha1 (removal)' '
- echo ":100644 000000 $_z40 $_z40 D foo" >expect &&
+ echo ":100644 000000 $ZERO_OID $ZERO_OID D foo" >expect &&
git diff-tree $bogus_tree $EMPTY_TREE >actual &&
test_cmp expect actual
'
test_expect_success 'raw diff shows null sha1 (modification)' '
- echo ":100644 100644 $blob $_z40 M foo" >expect &&
+ echo ":100644 100644 $blob $ZERO_OID M foo" >expect &&
git diff-tree $good_tree $bogus_tree >actual &&
test_cmp expect actual
'
test_expect_success 'raw diff shows null sha1 (other direction)' '
- echo ":100644 100644 $_z40 $blob M foo" >expect &&
+ echo ":100644 100644 $ZERO_OID $blob M foo" >expect &&
git diff-tree $bogus_tree $good_tree >actual &&
test_cmp expect actual
'
test_expect_success 'raw diff shows null sha1 (reverse)' '
- echo ":100644 100644 $_z40 $blob M foo" >expect &&
+ echo ":100644 100644 $ZERO_OID $blob M foo" >expect &&
git diff-tree -R $good_tree $bogus_tree >actual &&
test_cmp expect actual
'
test_expect_success 'raw diff shows null sha1 (index)' '
- echo ":100644 100644 $_z40 $blob M foo" >expect &&
+ echo ":100644 100644 $ZERO_OID $blob M foo" >expect &&
git diff-index $bogus_tree >actual &&
test_cmp expect actual
'
diff --git a/t/t4058-diff-duplicates.sh b/t/t4058-diff-duplicates.sh
index 0a23242..c24ee17 100755
--- a/t/t4058-diff-duplicates.sh
+++ b/t/t4058-diff-duplicates.sh
@@ -59,12 +59,12 @@ test_expect_success 'create trees with duplicate entries' '
test_expect_success 'diff-tree between trees' '
{
- printf ":000000 100644 $_z40 $blob_two A\touter/inner\n" &&
- printf ":000000 100644 $_z40 $blob_two A\touter/inner\n" &&
- printf ":000000 100644 $_z40 $blob_two A\touter/inner\n" &&
- printf ":100644 000000 $blob_two $_z40 D\touter/inner\n" &&
- printf ":100644 000000 $blob_two $_z40 D\touter/inner\n" &&
- printf ":100644 000000 $blob_two $_z40 D\touter/inner\n"
+ printf ":000000 100644 $ZERO_OID $blob_two A\touter/inner\n" &&
+ printf ":000000 100644 $ZERO_OID $blob_two A\touter/inner\n" &&
+ printf ":000000 100644 $ZERO_OID $blob_two A\touter/inner\n" &&
+ printf ":100644 000000 $blob_two $ZERO_OID D\touter/inner\n" &&
+ printf ":100644 000000 $blob_two $ZERO_OID D\touter/inner\n" &&
+ printf ":100644 000000 $blob_two $ZERO_OID D\touter/inner\n"
} >expect &&
git diff-tree -r --no-abbrev one two >actual &&
test_cmp expect actual
diff --git a/t/t4150-am.sh b/t/t4150-am.sh
index 1eccfb7..1ebc587 100755
--- a/t/t4150-am.sh
+++ b/t/t4150-am.sh
@@ -140,8 +140,8 @@ test_expect_success setup '
echo "# User $GIT_AUTHOR_NAME <$GIT_AUTHOR_EMAIL>" &&
echo "# Date $test_tick 25200" &&
echo "# $(git show --pretty="%aD" -s second)" &&
- echo "# Node ID $_z40" &&
- echo "# Parent $_z40" &&
+ echo "# Node ID $ZERO_OID" &&
+ echo "# Parent $ZERO_OID" &&
cat msg &&
echo &&
git diff-tree --no-commit-id -p second
diff --git a/t/t4200-rerere.sh b/t/t4200-rerere.sh
index deafaa3..8417e5a 100755
--- a/t/t4200-rerere.sh
+++ b/t/t4200-rerere.sh
@@ -166,7 +166,7 @@ test_expect_success 'first postimage wins' '
git commit -q -a -m "prefer first over second" &&
test -f $rr/postimage &&
- oldmtimepost=$(test-tool chmtime -v -60 $rr/postimage | cut -f 1) &&
+ oldmtimepost=$(test-tool chmtime --get -60 $rr/postimage) &&
git checkout -b third master &&
git show second^:a1 | sed "s/To die: t/To die! T/" >a1 &&
@@ -179,7 +179,7 @@ test_expect_success 'first postimage wins' '
'
test_expect_success 'rerere updates postimage timestamp' '
- newmtimepost=$(test-tool chmtime -v +0 $rr/postimage | cut -f 1) &&
+ newmtimepost=$(test-tool chmtime --get $rr/postimage) &&
test $oldmtimepost -lt $newmtimepost
'
@@ -243,7 +243,7 @@ rerere_gc_custom_expiry_test () {
five_days="$1" right_now="$2"
test_expect_success "rerere gc with custom expiry ($five_days, $right_now)" '
rm -fr .git/rr-cache &&
- rr=.git/rr-cache/$_z40 &&
+ rr=.git/rr-cache/$ZERO_OID &&
mkdir -p "$rr" &&
>"$rr/preimage" &&
>"$rr/postimage" &&
@@ -512,7 +512,7 @@ test_expect_success 'multiple identical conflicts' '
count_pre_post 2 0 &&
# Pretend that the conflicts were made quite some time ago
- find .git/rr-cache/ -type f | xargs test-tool chmtime -172800 &&
+ test-tool chmtime -172800 $(find .git/rr-cache/ -type f) &&
# Unresolved entries have not expired yet
git -c gc.rerereresolved=5 -c gc.rerereunresolved=5 rerere gc &&
@@ -568,7 +568,7 @@ test_expect_success 'multiple identical conflicts' '
git rerere &&
# Pretend that the resolutions are old again
- find .git/rr-cache/ -type f | xargs test-tool chmtime -172800 &&
+ test-tool chmtime -172800 $(find .git/rr-cache/ -type f) &&
# Resolved entries have not expired yet
git -c gc.rerereresolved=5 -c gc.rerereunresolved=5 rerere gc &&
diff --git a/t/t4201-shortlog.sh b/t/t4201-shortlog.sh
index ff6649e..58c2773 100755
--- a/t/t4201-shortlog.sh
+++ b/t/t4201-shortlog.sh
@@ -59,7 +59,7 @@ test_expect_success 'setup' '
fuzz() {
file=$1 &&
sed "
- s/$_x40/OBJECT_NAME/g
+ s/$OID_REGEX/OBJECT_NAME/g
s/$_x35/OBJID/g
s/^ \{6\}[CTa].*/ SUBJECT/g
s/^ \{8\}[^ ].*/ CONTINUATION/g
diff --git a/t/t4205-log-pretty-formats.sh b/t/t4205-log-pretty-formats.sh
index 591f35d..2052cad 100755
--- a/t/t4205-log-pretty-formats.sh
+++ b/t/t4205-log-pretty-formats.sh
@@ -516,22 +516,22 @@ test_expect_success 'log decoration properly follows tag chain' '
git commit --amend -m shorter &&
git log --no-walk --tags --pretty="%H %d" --decorate=full >actual &&
cat <<-EOF >expected &&
- $head1 (tag: refs/tags/tag2)
$head2 (tag: refs/tags/message-one)
$old_head1 (tag: refs/tags/message-two)
+ $head1 (tag: refs/tags/tag2)
EOF
- sort actual >actual1 &&
+ sort -k3 actual >actual1 &&
test_cmp expected actual1
'
test_expect_success 'clean log decoration' '
git log --no-walk --tags --pretty="%H %D" --decorate=full >actual &&
cat >expected <<-EOF &&
- $head1 tag: refs/tags/tag2
$head2 tag: refs/tags/message-one
$old_head1 tag: refs/tags/message-two
+ $head1 tag: refs/tags/tag2
EOF
- sort actual >actual1 &&
+ sort -k3 actual >actual1 &&
test_cmp expected actual1
'
diff --git a/t/t4208-log-magic-pathspec.sh b/t/t4208-log-magic-pathspec.sh
index a1705f7..62f335b 100755
--- a/t/t4208-log-magic-pathspec.sh
+++ b/t/t4208-log-magic-pathspec.sh
@@ -45,8 +45,9 @@ test_expect_success 'git log -- :' '
'
test_expect_success 'git log HEAD -- :/' '
+ initial=$(git rev-parse --short HEAD^) &&
cat >expected <<-EOF &&
- 24b24cf initial
+ $initial initial
EOF
(cd sub && git log --oneline HEAD -- :/ >../actual) &&
test_cmp expected actual
diff --git a/t/t5000-tar-tree.sh b/t/t5000-tar-tree.sh
index af4d9b8..2a97b27 100755
--- a/t/t5000-tar-tree.sh
+++ b/t/t5000-tar-tree.sh
@@ -192,7 +192,7 @@ test_expect_success \
'validate file modification time' \
'mkdir extract &&
"$TAR" xf b.tar -C extract a/a &&
- test-tool chmtime -v +0 extract/a/a |cut -f 1 >b.mtime &&
+ test-tool chmtime --get extract/a/a >b.mtime &&
echo "1117231200" >expected.mtime &&
test_cmp expected.mtime b.mtime'
diff --git a/t/t5150-request-pull.sh b/t/t5150-request-pull.sh
index 08c210f..fca001e 100755
--- a/t/t5150-request-pull.sh
+++ b/t/t5150-request-pull.sh
@@ -81,7 +81,7 @@ test_expect_success 'setup: two scripts for reading pull requests' '
cat <<-EOT >fuzz.sed
#!/bin/sed -nf
s/$downstream_url_for_sed/URL/g
- s/$_x40/OBJECT_NAME/g
+ s/$OID_REGEX/OBJECT_NAME/g
s/A U Thor/AUTHOR/g
s/[-0-9]\{10\} [:0-9]\{8\} [-+][0-9]\{4\}/DATE/g
s/ [^ ].*/ SUBJECT/g
diff --git a/t/t5300-pack-object.sh b/t/t5300-pack-object.sh
index 65ff60f..87a590c 100755
--- a/t/t5300-pack-object.sh
+++ b/t/t5300-pack-object.sh
@@ -457,6 +457,11 @@ test_expect_success !PTHREADS,C_LOCALE_OUTPUT 'pack-objects --threads=N or pack.
grep -F "no threads support, ignoring pack.threads" err
'
+test_expect_success 'pack-objects in too-many-packs mode' '
+ GIT_TEST_FULL_IN_PACK_ARRAY=1 git repack -ad &&
+ git fsck
+'
+
#
# WARNING!
#
@@ -466,9 +471,11 @@ test_expect_success !PTHREADS,C_LOCALE_OUTPUT 'pack-objects --threads=N or pack.
test_expect_success \
'fake a SHA1 hash collision' \
- 'test -f .git/objects/c8/2de19312b6c3695c0c18f70709a6c535682a67 &&
- cp -f .git/objects/9d/235ed07cd19811a6ceb342de82f190e49c9f68 \
- .git/objects/c8/2de19312b6c3695c0c18f70709a6c535682a67'
+ 'long_a=$(git hash-object a | sed -e "s!^..!&/!") &&
+ long_b=$(git hash-object b | sed -e "s!^..!&/!") &&
+ test -f .git/objects/$long_b &&
+ cp -f .git/objects/$long_a \
+ .git/objects/$long_b'
test_expect_success \
'make sure index-pack detects the SHA1 collision' \
diff --git a/t/t5304-prune.sh b/t/t5304-prune.sh
index f0f6e2a..f20f03c 100755
--- a/t/t5304-prune.sh
+++ b/t/t5304-prune.sh
@@ -320,4 +320,14 @@ test_expect_success 'prune: handle HEAD reflog in multiple worktrees' '
test_cmp expected actual
'
+test_expect_success 'prune: handle expire option correctly' '
+ test_must_fail git prune --expire 2>error &&
+ test_i18ngrep "requires a value" error &&
+
+ test_must_fail git prune --expire=nyah 2>error &&
+ test_i18ngrep "malformed expiration" error &&
+
+ git prune --no-expire
+'
+
test_done
diff --git a/t/t5308-pack-detect-duplicates.sh b/t/t5308-pack-detect-duplicates.sh
index 156ae9e..6845c1f 100755
--- a/t/t5308-pack-detect-duplicates.sh
+++ b/t/t5308-pack-detect-duplicates.sh
@@ -4,6 +4,12 @@ test_description='handling of duplicate objects in incoming packfiles'
. ./test-lib.sh
. "$TEST_DIRECTORY"/lib-pack.sh
+if ! test_have_prereq SHA1
+then
+ skip_all='not using SHA-1 for objects'
+ test_done
+fi
+
# The sha1s we have in our pack. It's important that these have the same
# starting byte, so that they end up in the same fanout section of the index.
# That lets us make sure we are exercising the binary search with both sets.
diff --git a/t/t5309-pack-delta-cycles.sh b/t/t5309-pack-delta-cycles.sh
index 3e7861b..491556da 100755
--- a/t/t5309-pack-delta-cycles.sh
+++ b/t/t5309-pack-delta-cycles.sh
@@ -4,6 +4,12 @@ test_description='test index-pack handling of delta cycles in packfiles'
. ./test-lib.sh
. "$TEST_DIRECTORY"/lib-pack.sh
+if ! test_have_prereq SHA1
+then
+ skip_all='not using SHA-1 for objects'
+ test_done
+fi
+
# Two similar-ish objects that we have computed deltas between.
A=01d7713666f4de822776c7622c10f1b07de280dc
B=e68fe8129b546b101aee9510c5328e7f21ca1d18
diff --git a/t/t5310-pack-bitmaps.sh b/t/t5310-pack-bitmaps.sh
index f6d600f..423c0a4 100755
--- a/t/t5310-pack-bitmaps.sh
+++ b/t/t5310-pack-bitmaps.sh
@@ -264,9 +264,9 @@ test_expect_success 'pack with missing parent' '
'
test_expect_success JGIT 'we can read jgit bitmaps' '
- git clone . compat-jgit &&
+ git clone --bare . compat-jgit.git &&
(
- cd compat-jgit &&
+ cd compat-jgit.git &&
rm -f .git/objects/pack/*.bitmap &&
jgit gc &&
git rev-list --test-bitmap HEAD
@@ -274,9 +274,9 @@ test_expect_success JGIT 'we can read jgit bitmaps' '
'
test_expect_success JGIT 'jgit can read our bitmaps' '
- git clone . compat-us &&
+ git clone --bare . compat-us.git &&
(
- cd compat-us &&
+ cd compat-us.git &&
git repack -adb &&
# jgit gc will barf if it does not like our bitmaps
jgit gc
diff --git a/t/t5318-commit-graph.sh b/t/t5318-commit-graph.sh
new file mode 100755
index 0000000..a380419
--- /dev/null
+++ b/t/t5318-commit-graph.sh
@@ -0,0 +1,224 @@
+#!/bin/sh
+
+test_description='commit graph'
+. ./test-lib.sh
+
+test_expect_success 'setup full repo' '
+ mkdir full &&
+ cd "$TRASH_DIRECTORY/full" &&
+ git init &&
+ git config core.commitGraph true &&
+ objdir=".git/objects"
+'
+
+test_expect_success 'write graph with no packs' '
+ cd "$TRASH_DIRECTORY/full" &&
+ git commit-graph write --object-dir . &&
+ test_path_is_file info/commit-graph
+'
+
+test_expect_success 'create commits and repack' '
+ cd "$TRASH_DIRECTORY/full" &&
+ for i in $(test_seq 3)
+ do
+ test_commit $i &&
+ git branch commits/$i
+ done &&
+ git repack
+'
+
+graph_git_two_modes() {
+ git -c core.graph=true $1 >output
+ git -c core.graph=false $1 >expect
+ test_cmp output expect
+}
+
+graph_git_behavior() {
+ MSG=$1
+ DIR=$2
+ BRANCH=$3
+ COMPARE=$4
+ test_expect_success "check normal git operations: $MSG" '
+ cd "$TRASH_DIRECTORY/$DIR" &&
+ graph_git_two_modes "log --oneline $BRANCH" &&
+ graph_git_two_modes "log --topo-order $BRANCH" &&
+ graph_git_two_modes "log --graph $COMPARE..$BRANCH" &&
+ graph_git_two_modes "branch -vv" &&
+ graph_git_two_modes "merge-base -a $BRANCH $COMPARE"
+ '
+}
+
+graph_git_behavior 'no graph' full commits/3 commits/1
+
+graph_read_expect() {
+ OPTIONAL=""
+ NUM_CHUNKS=3
+ if test ! -z $2
+ then
+ OPTIONAL=" $2"
+ NUM_CHUNKS=$((3 + $(echo "$2" | wc -w)))
+ fi
+ cat >expect <<- EOF
+ header: 43475048 1 1 $NUM_CHUNKS 0
+ num_commits: $1
+ chunks: oid_fanout oid_lookup commit_metadata$OPTIONAL
+ EOF
+ git commit-graph read >output &&
+ test_cmp expect output
+}
+
+test_expect_success 'write graph' '
+ cd "$TRASH_DIRECTORY/full" &&
+ graph1=$(git commit-graph write) &&
+ test_path_is_file $objdir/info/commit-graph &&
+ graph_read_expect "3"
+'
+
+graph_git_behavior 'graph exists' full commits/3 commits/1
+
+test_expect_success 'Add more commits' '
+ cd "$TRASH_DIRECTORY/full" &&
+ git reset --hard commits/1 &&
+ for i in $(test_seq 4 5)
+ do
+ test_commit $i &&
+ git branch commits/$i
+ done &&
+ git reset --hard commits/2 &&
+ for i in $(test_seq 6 7)
+ do
+ test_commit $i &&
+ git branch commits/$i
+ done &&
+ git reset --hard commits/2 &&
+ git merge commits/4 &&
+ git branch merge/1 &&
+ git reset --hard commits/4 &&
+ git merge commits/6 &&
+ git branch merge/2 &&
+ git reset --hard commits/3 &&
+ git merge commits/5 commits/7 &&
+ git branch merge/3 &&
+ git repack
+'
+
+# Current graph structure:
+#
+# __M3___
+# / | \
+# 3 M1 5 M2 7
+# |/ \|/ \|
+# 2 4 6
+# |___/____/
+# 1
+
+test_expect_success 'write graph with merges' '
+ cd "$TRASH_DIRECTORY/full" &&
+ git commit-graph write &&
+ test_path_is_file $objdir/info/commit-graph &&
+ graph_read_expect "10" "large_edges"
+'
+
+graph_git_behavior 'merge 1 vs 2' full merge/1 merge/2
+graph_git_behavior 'merge 1 vs 3' full merge/1 merge/3
+graph_git_behavior 'merge 2 vs 3' full merge/2 merge/3
+
+test_expect_success 'Add one more commit' '
+ cd "$TRASH_DIRECTORY/full" &&
+ test_commit 8 &&
+ git branch commits/8 &&
+ ls $objdir/pack | grep idx >existing-idx &&
+ git repack &&
+ ls $objdir/pack| grep idx | grep -v --file=existing-idx >new-idx
+'
+
+# Current graph structure:
+#
+# 8
+# |
+# __M3___
+# / | \
+# 3 M1 5 M2 7
+# |/ \|/ \|
+# 2 4 6
+# |___/____/
+# 1
+
+graph_git_behavior 'mixed mode, commit 8 vs merge 1' full commits/8 merge/1
+graph_git_behavior 'mixed mode, commit 8 vs merge 2' full commits/8 merge/2
+
+test_expect_success 'write graph with new commit' '
+ cd "$TRASH_DIRECTORY/full" &&
+ git commit-graph write &&
+ test_path_is_file $objdir/info/commit-graph &&
+ graph_read_expect "11" "large_edges"
+'
+
+graph_git_behavior 'full graph, commit 8 vs merge 1' full commits/8 merge/1
+graph_git_behavior 'full graph, commit 8 vs merge 2' full commits/8 merge/2
+
+test_expect_success 'write graph with nothing new' '
+ cd "$TRASH_DIRECTORY/full" &&
+ git commit-graph write &&
+ test_path_is_file $objdir/info/commit-graph &&
+ graph_read_expect "11" "large_edges"
+'
+
+graph_git_behavior 'cleared graph, commit 8 vs merge 1' full commits/8 merge/1
+graph_git_behavior 'cleared graph, commit 8 vs merge 2' full commits/8 merge/2
+
+test_expect_success 'build graph from latest pack with closure' '
+ cd "$TRASH_DIRECTORY/full" &&
+ cat new-idx | git commit-graph write --stdin-packs &&
+ test_path_is_file $objdir/info/commit-graph &&
+ graph_read_expect "9" "large_edges"
+'
+
+graph_git_behavior 'graph from pack, commit 8 vs merge 1' full commits/8 merge/1
+graph_git_behavior 'graph from pack, commit 8 vs merge 2' full commits/8 merge/2
+
+test_expect_success 'build graph from commits with closure' '
+ cd "$TRASH_DIRECTORY/full" &&
+ git tag -a -m "merge" tag/merge merge/2 &&
+ git rev-parse tag/merge >commits-in &&
+ git rev-parse merge/1 >>commits-in &&
+ cat commits-in | git commit-graph write --stdin-commits &&
+ test_path_is_file $objdir/info/commit-graph &&
+ graph_read_expect "6"
+'
+
+graph_git_behavior 'graph from commits, commit 8 vs merge 1' full commits/8 merge/1
+graph_git_behavior 'graph from commits, commit 8 vs merge 2' full commits/8 merge/2
+
+test_expect_success 'build graph from commits with append' '
+ cd "$TRASH_DIRECTORY/full" &&
+ git rev-parse merge/3 | git commit-graph write --stdin-commits --append &&
+ test_path_is_file $objdir/info/commit-graph &&
+ graph_read_expect "10" "large_edges"
+'
+
+graph_git_behavior 'append graph, commit 8 vs merge 1' full commits/8 merge/1
+graph_git_behavior 'append graph, commit 8 vs merge 2' full commits/8 merge/2
+
+test_expect_success 'setup bare repo' '
+ cd "$TRASH_DIRECTORY" &&
+ git clone --bare --no-local full bare &&
+ cd bare &&
+ git config core.commitGraph true &&
+ baredir="./objects"
+'
+
+graph_git_behavior 'bare repo, commit 8 vs merge 1' bare commits/8 merge/1
+graph_git_behavior 'bare repo, commit 8 vs merge 2' bare commits/8 merge/2
+
+test_expect_success 'write graph in bare repo' '
+ cd "$TRASH_DIRECTORY/bare" &&
+ git commit-graph write &&
+ test_path_is_file $baredir/info/commit-graph &&
+ graph_read_expect "11" "large_edges"
+'
+
+graph_git_behavior 'bare repo with graph, commit 8 vs merge 1' bare commits/8 merge/1
+graph_git_behavior 'bare repo with graph, commit 8 vs merge 2' bare commits/8 merge/2
+
+test_done
diff --git a/t/t5404-tracking-branches.sh b/t/t5404-tracking-branches.sh
index 2b8c0ba..2762f42 100755
--- a/t/t5404-tracking-branches.sh
+++ b/t/t5404-tracking-branches.sh
@@ -56,7 +56,7 @@ test_expect_success 'deleted branches have their tracking branches removed' '
test_expect_success 'already deleted tracking branches ignored' '
git branch -d -r origin/b3 &&
git push origin :b3 >output 2>&1 &&
- ! grep error output
+ ! grep "^error: " output
'
test_done
diff --git a/t/t5512-ls-remote.sh b/t/t5512-ls-remote.sh
index 02106c9..6a94948 100755
--- a/t/t5512-ls-remote.sh
+++ b/t/t5512-ls-remote.sh
@@ -10,6 +10,9 @@ test_expect_success setup '
test_tick &&
git commit -m initial &&
git tag mark &&
+ git tag mark1.1 &&
+ git tag mark1.2 &&
+ git tag mark1.10 &&
git show-ref --tags -d | sed -e "s/ / /" >expected.tag &&
(
echo "$(git rev-parse HEAD) HEAD"
@@ -39,6 +42,39 @@ test_expect_success 'ls-remote self' '
test_cmp expected.all actual
'
+test_expect_success 'ls-remote --sort="version:refname" --tags self' '
+ cat >expect <<-EOF &&
+ $(git rev-parse mark) refs/tags/mark
+ $(git rev-parse mark1.1) refs/tags/mark1.1
+ $(git rev-parse mark1.2) refs/tags/mark1.2
+ $(git rev-parse mark1.10) refs/tags/mark1.10
+ EOF
+ git ls-remote --sort="version:refname" --tags self >actual &&
+ test_cmp expect actual
+'
+
+test_expect_success 'ls-remote --sort="-version:refname" --tags self' '
+ cat >expect <<-EOF &&
+ $(git rev-parse mark1.10) refs/tags/mark1.10
+ $(git rev-parse mark1.2) refs/tags/mark1.2
+ $(git rev-parse mark1.1) refs/tags/mark1.1
+ $(git rev-parse mark) refs/tags/mark
+ EOF
+ git ls-remote --sort="-version:refname" --tags self >actual &&
+ test_cmp expect actual
+'
+
+test_expect_success 'ls-remote --sort="-refname" --tags self' '
+ cat >expect <<-EOF &&
+ $(git rev-parse mark1.2) refs/tags/mark1.2
+ $(git rev-parse mark1.10) refs/tags/mark1.10
+ $(git rev-parse mark1.1) refs/tags/mark1.1
+ $(git rev-parse mark) refs/tags/mark
+ EOF
+ git ls-remote --sort="-refname" --tags self >actual &&
+ test_cmp expect actual
+'
+
test_expect_success 'dies when no remote specified and no default remotes found' '
test_must_fail git ls-remote
'
@@ -131,7 +167,7 @@ test_expect_success 'Report no-match with --exit-code' '
test_expect_success 'Report match with --exit-code' '
git ls-remote --exit-code other.git "refs/tags/*" >actual &&
- git ls-remote . tags/mark >expect &&
+ git ls-remote . tags/mark* >expect &&
test_cmp expect actual
'
@@ -171,13 +207,17 @@ test_expect_success 'overrides work between mixed transfer/upload-pack hideRefs'
'
test_expect_success 'ls-remote --symref' '
- cat >expect <<-\EOF &&
+ git fetch origin &&
+ cat >expect <<-EOF &&
ref: refs/heads/master HEAD
- 1bd44cb9d13204b0fe1958db0082f5028a16eb3a HEAD
- 1bd44cb9d13204b0fe1958db0082f5028a16eb3a refs/heads/master
- 1bd44cb9d13204b0fe1958db0082f5028a16eb3a refs/remotes/origin/HEAD
- 1bd44cb9d13204b0fe1958db0082f5028a16eb3a refs/remotes/origin/master
- 1bd44cb9d13204b0fe1958db0082f5028a16eb3a refs/tags/mark
+ $(git rev-parse HEAD) HEAD
+ $(git rev-parse refs/heads/master) refs/heads/master
+ $(git rev-parse HEAD) refs/remotes/origin/HEAD
+ $(git rev-parse refs/remotes/origin/master) refs/remotes/origin/master
+ $(git rev-parse refs/tags/mark) refs/tags/mark
+ $(git rev-parse refs/tags/mark1.1) refs/tags/mark1.1
+ $(git rev-parse refs/tags/mark1.10) refs/tags/mark1.10
+ $(git rev-parse refs/tags/mark1.2) refs/tags/mark1.2
EOF
git ls-remote --symref >actual &&
test_cmp expect actual
diff --git a/t/t5516-fetch-push.sh b/t/t5516-fetch-push.sh
index 8223913..f4d2828 100755
--- a/t/t5516-fetch-push.sh
+++ b/t/t5516-fetch-push.sh
@@ -94,6 +94,9 @@ mk_child() {
}
check_push_result () {
+ test $# -ge 3 ||
+ error "bug in the test script: check_push_result requires at least 3 parameters"
+
repo_name="$1"
shift
@@ -553,10 +556,7 @@ test_expect_success 'branch.*.pushremote config order is irrelevant' '
test_expect_success 'push with dry-run' '
mk_test testrepo heads/master &&
- (
- cd testrepo &&
- old_commit=$(git show-ref -s --verify refs/heads/master)
- ) &&
+ old_commit=$(git -C testrepo show-ref -s --verify refs/heads/master) &&
git push --dry-run testrepo : &&
check_push_result testrepo $old_commit heads/master
'
@@ -612,7 +612,7 @@ test_expect_success 'push does not update local refs on failure' '
chmod +x testrepo/.git/hooks/pre-receive &&
(
cd child &&
- git pull .. master
+ git pull .. master &&
test_must_fail git push &&
test $(git rev-parse master) != \
$(git rev-parse remotes/origin/master)
@@ -634,7 +634,7 @@ test_expect_success 'pushing valid refs triggers post-receive and post-update ho
orgmaster=$(cd testrepo && git show-ref -s --verify refs/heads/master) &&
newmaster=$(git show-ref -s --verify refs/heads/master) &&
orgnext=$(cd testrepo && git show-ref -s --verify refs/heads/next) &&
- newnext=$_z40 &&
+ newnext=$ZERO_OID &&
git push testrepo refs/heads/master:refs/heads/master :refs/heads/next &&
(
cd testrepo/.git &&
@@ -672,15 +672,15 @@ test_expect_success 'deleting dangling ref triggers hooks with correct args' '
(
cd testrepo/.git &&
cat >pre-receive.expect <<-EOF &&
- $_z40 $_z40 refs/heads/master
+ $ZERO_OID $ZERO_OID refs/heads/master
EOF
cat >update.expect <<-EOF &&
- refs/heads/master $_z40 $_z40
+ refs/heads/master $ZERO_OID $ZERO_OID
EOF
cat >post-receive.expect <<-EOF &&
- $_z40 $_z40 refs/heads/master
+ $ZERO_OID $ZERO_OID refs/heads/master
EOF
cat >post-update.expect <<-EOF &&
@@ -703,12 +703,12 @@ test_expect_success 'deletion of a non-existent ref is not fed to post-receive a
cd testrepo/.git &&
cat >pre-receive.expect <<-EOF &&
$orgmaster $newmaster refs/heads/master
- $_z40 $_z40 refs/heads/nonexistent
+ $ZERO_OID $ZERO_OID refs/heads/nonexistent
EOF
cat >update.expect <<-EOF &&
refs/heads/master $orgmaster $newmaster
- refs/heads/nonexistent $_z40 $_z40
+ refs/heads/nonexistent $ZERO_OID $ZERO_OID
EOF
cat >post-receive.expect <<-EOF &&
@@ -732,11 +732,11 @@ test_expect_success 'deletion of a non-existent ref alone does trigger post-rece
(
cd testrepo/.git &&
cat >pre-receive.expect <<-EOF &&
- $_z40 $_z40 refs/heads/nonexistent
+ $ZERO_OID $ZERO_OID refs/heads/nonexistent
EOF
cat >update.expect <<-EOF &&
- refs/heads/nonexistent $_z40 $_z40
+ refs/heads/nonexistent $ZERO_OID $ZERO_OID
EOF
test_cmp pre-receive.expect pre-receive.actual &&
@@ -751,7 +751,7 @@ test_expect_success 'mixed ref updates, deletes, invalid deletes trigger hooks w
orgmaster=$(cd testrepo && git show-ref -s --verify refs/heads/master) &&
newmaster=$(git show-ref -s --verify refs/heads/master) &&
orgnext=$(cd testrepo && git show-ref -s --verify refs/heads/next) &&
- newnext=$_z40 &&
+ newnext=$ZERO_OID &&
orgpu=$(cd testrepo && git show-ref -s --verify refs/heads/pu) &&
newpu=$(git show-ref -s --verify refs/heads/master) &&
git push testrepo refs/heads/master:refs/heads/master \
@@ -763,14 +763,14 @@ test_expect_success 'mixed ref updates, deletes, invalid deletes trigger hooks w
$orgmaster $newmaster refs/heads/master
$orgnext $newnext refs/heads/next
$orgpu $newpu refs/heads/pu
- $_z40 $_z40 refs/heads/nonexistent
+ $ZERO_OID $ZERO_OID refs/heads/nonexistent
EOF
cat >update.expect <<-EOF &&
refs/heads/master $orgmaster $newmaster
refs/heads/next $orgnext $newnext
refs/heads/pu $orgpu $newpu
- refs/heads/nonexistent $_z40 $_z40
+ refs/heads/nonexistent $ZERO_OID $ZERO_OID
EOF
cat >post-receive.expect <<-EOF &&
diff --git a/t/t5527-fetch-odd-refs.sh b/t/t5527-fetch-odd-refs.sh
index 207899a..3b0cb98 100755
--- a/t/t5527-fetch-odd-refs.sh
+++ b/t/t5527-fetch-odd-refs.sh
@@ -27,7 +27,7 @@ test_expect_success 'suffix ref is ignored during fetch' '
'
test_expect_success 'try to create repo with absurdly long refname' '
- ref240=$_z40/$_z40/$_z40/$_z40/$_z40/$_z40 &&
+ ref240=$ZERO_OID/$ZERO_OID/$ZERO_OID/$ZERO_OID/$ZERO_OID/$ZERO_OID &&
ref1440=$ref240/$ref240/$ref240/$ref240/$ref240/$ref240 &&
git init long &&
(
diff --git a/t/t5541-http-push-smart.sh b/t/t5541-http-push-smart.sh
index 21340e8..a2af693 100755
--- a/t/t5541-http-push-smart.sh
+++ b/t/t5541-http-push-smart.sh
@@ -377,5 +377,17 @@ test_expect_success 'push status output scrubs password' '
grep "^To $HTTPD_URL/smart/test_repo.git" status
'
+test_expect_success 'colorize errors/hints' '
+ cd "$ROOT_PATH"/test_repo_clone &&
+ test_must_fail git -c color.transport=always -c color.advice=always \
+ -c color.push=always \
+ push origin origin/master^:master 2>act &&
+ test_decode_color <act >decoded &&
+ test_i18ngrep "<RED>.*rejected.*<RESET>" decoded &&
+ test_i18ngrep "<RED>error: failed to push some refs" decoded &&
+ test_i18ngrep "<YELLOW>hint: " decoded &&
+ test_i18ngrep ! "^hint: " decoded
+'
+
stop_httpd
test_done
diff --git a/t/t5550-http-fetch-dumb.sh b/t/t5550-http-fetch-dumb.sh
index 8552184..6d7d88c 100755
--- a/t/t5550-http-fetch-dumb.sh
+++ b/t/t5550-http-fetch-dumb.sh
@@ -169,6 +169,17 @@ test_expect_success 'fetch changes via manual http-fetch' '
test_cmp file clone2/file
'
+test_expect_success 'manual http-fetch without -a works just as well' '
+ cp -R clone-tmpl clone3 &&
+
+ HEAD=$(git rev-parse --verify HEAD) &&
+ (cd clone3 &&
+ git http-fetch -w heads/master-new $HEAD $(git config remote.origin.url) &&
+ git checkout master-new &&
+ test $HEAD = $(git rev-parse --verify HEAD)) &&
+ test_cmp file clone3/file
+'
+
test_expect_success 'http remote detects correct HEAD' '
git push public master:other &&
(cd clone &&
diff --git a/t/t5561-http-backend.sh b/t/t5561-http-backend.sh
index 90e0d6f..84a9557 100755
--- a/t/t5561-http-backend.sh
+++ b/t/t5561-http-backend.sh
@@ -3,10 +3,16 @@
test_description='test git-http-backend'
. ./test-lib.sh
. "$TEST_DIRECTORY"/lib-httpd.sh
+
+if ! test_have_prereq CURL; then
+ skip_all='skipping raw http-backend tests, curl not available'
+ test_done
+fi
+
start_httpd
GET() {
- curl --include "$HTTPD_URL/$SMART/repo.git/$1" >out 2>/dev/null &&
+ curl --include "$HTTPD_URL/$SMART/repo.git/$1" >out &&
tr '\015' Q <out |
sed '
s/Q$//
@@ -19,7 +25,7 @@ GET() {
POST() {
curl --include --data "$2" \
--header "Content-Type: application/x-$1-request" \
- "$HTTPD_URL/smart/repo.git/$1" >out 2>/dev/null &&
+ "$HTTPD_URL/smart/repo.git/$1" >out &&
tr '\015' Q <out |
sed '
s/Q$//
diff --git a/t/t5571-pre-push-hook.sh b/t/t5571-pre-push-hook.sh
index ba975bb..ac53d63 100755
--- a/t/t5571-pre-push-hook.sh
+++ b/t/t5571-pre-push-hook.sh
@@ -78,8 +78,8 @@ test_expect_success 'push to default' '
cat >expected <<EOF
parent1
repo1
-refs/tags/one $COMMIT1 refs/tags/tag1 $_z40
-HEAD~ $COMMIT2 refs/heads/prev $_z40
+refs/tags/one $COMMIT1 refs/tags/tag1 $ZERO_OID
+HEAD~ $COMMIT2 refs/heads/prev $ZERO_OID
EOF
test_expect_success 'push non-branches' '
@@ -90,7 +90,7 @@ test_expect_success 'push non-branches' '
cat >expected <<EOF
parent1
repo1
-(delete) $_z40 refs/heads/prev $COMMIT2
+(delete) $ZERO_OID refs/heads/prev $COMMIT2
EOF
test_expect_success 'push delete' '
@@ -101,7 +101,7 @@ test_expect_success 'push delete' '
cat >expected <<EOF
repo1
repo1
-HEAD $COMMIT3 refs/heads/other $_z40
+HEAD $COMMIT3 refs/heads/other $ZERO_OID
EOF
test_expect_success 'push to URL' '
diff --git a/t/t5701-git-serve.sh b/t/t5701-git-serve.sh
new file mode 100755
index 0000000..75ec79e
--- /dev/null
+++ b/t/t5701-git-serve.sh
@@ -0,0 +1,211 @@
+#!/bin/sh
+
+test_description='test git-serve and server commands'
+
+. ./test-lib.sh
+
+test_expect_success 'test capability advertisement' '
+ cat >expect <<-EOF &&
+ version 2
+ agent=git/$(git version | cut -d" " -f3)
+ ls-refs
+ fetch=shallow
+ server-option
+ 0000
+ EOF
+
+ git serve --advertise-capabilities >out &&
+ test-pkt-line unpack <out >actual &&
+ test_cmp actual expect
+'
+
+test_expect_success 'stateless-rpc flag does not list capabilities' '
+ # Empty request
+ test-pkt-line pack >in <<-EOF &&
+ 0000
+ EOF
+ git serve --stateless-rpc >out <in &&
+ test_must_be_empty out &&
+
+ # EOF
+ git serve --stateless-rpc >out &&
+ test_must_be_empty out
+'
+
+test_expect_success 'request invalid capability' '
+ test-pkt-line pack >in <<-EOF &&
+ foobar
+ 0000
+ EOF
+ test_must_fail git serve --stateless-rpc 2>err <in &&
+ test_i18ngrep "unknown capability" err
+'
+
+test_expect_success 'request with no command' '
+ test-pkt-line pack >in <<-EOF &&
+ agent=git/test
+ 0000
+ EOF
+ test_must_fail git serve --stateless-rpc 2>err <in &&
+ test_i18ngrep "no command requested" err
+'
+
+test_expect_success 'request invalid command' '
+ test-pkt-line pack >in <<-EOF &&
+ command=foo
+ agent=git/test
+ 0000
+ EOF
+ test_must_fail git serve --stateless-rpc 2>err <in &&
+ test_i18ngrep "invalid command" err
+'
+
+# Test the basics of ls-refs
+#
+test_expect_success 'setup some refs and tags' '
+ test_commit one &&
+ git branch dev master &&
+ test_commit two &&
+ git symbolic-ref refs/heads/release refs/heads/master &&
+ git tag -a -m "annotated tag" annotated-tag
+'
+
+test_expect_success 'basics of ls-refs' '
+ test-pkt-line pack >in <<-EOF &&
+ command=ls-refs
+ 0000
+ EOF
+
+ cat >expect <<-EOF &&
+ $(git rev-parse HEAD) HEAD
+ $(git rev-parse refs/heads/dev) refs/heads/dev
+ $(git rev-parse refs/heads/master) refs/heads/master
+ $(git rev-parse refs/heads/release) refs/heads/release
+ $(git rev-parse refs/tags/annotated-tag) refs/tags/annotated-tag
+ $(git rev-parse refs/tags/one) refs/tags/one
+ $(git rev-parse refs/tags/two) refs/tags/two
+ 0000
+ EOF
+
+ git serve --stateless-rpc <in >out &&
+ test-pkt-line unpack <out >actual &&
+ test_cmp actual expect
+'
+
+test_expect_success 'basic ref-prefixes' '
+ test-pkt-line pack >in <<-EOF &&
+ command=ls-refs
+ 0001
+ ref-prefix refs/heads/master
+ ref-prefix refs/tags/one
+ 0000
+ EOF
+
+ cat >expect <<-EOF &&
+ $(git rev-parse refs/heads/master) refs/heads/master
+ $(git rev-parse refs/tags/one) refs/tags/one
+ 0000
+ EOF
+
+ git serve --stateless-rpc <in >out &&
+ test-pkt-line unpack <out >actual &&
+ test_cmp actual expect
+'
+
+test_expect_success 'refs/heads prefix' '
+ test-pkt-line pack >in <<-EOF &&
+ command=ls-refs
+ 0001
+ ref-prefix refs/heads/
+ 0000
+ EOF
+
+ cat >expect <<-EOF &&
+ $(git rev-parse refs/heads/dev) refs/heads/dev
+ $(git rev-parse refs/heads/master) refs/heads/master
+ $(git rev-parse refs/heads/release) refs/heads/release
+ 0000
+ EOF
+
+ git serve --stateless-rpc <in >out &&
+ test-pkt-line unpack <out >actual &&
+ test_cmp actual expect
+'
+
+test_expect_success 'peel parameter' '
+ test-pkt-line pack >in <<-EOF &&
+ command=ls-refs
+ 0001
+ peel
+ ref-prefix refs/tags/
+ 0000
+ EOF
+
+ cat >expect <<-EOF &&
+ $(git rev-parse refs/tags/annotated-tag) refs/tags/annotated-tag peeled:$(git rev-parse refs/tags/annotated-tag^{})
+ $(git rev-parse refs/tags/one) refs/tags/one
+ $(git rev-parse refs/tags/two) refs/tags/two
+ 0000
+ EOF
+
+ git serve --stateless-rpc <in >out &&
+ test-pkt-line unpack <out >actual &&
+ test_cmp actual expect
+'
+
+test_expect_success 'symrefs parameter' '
+ test-pkt-line pack >in <<-EOF &&
+ command=ls-refs
+ 0001
+ symrefs
+ ref-prefix refs/heads/
+ 0000
+ EOF
+
+ cat >expect <<-EOF &&
+ $(git rev-parse refs/heads/dev) refs/heads/dev
+ $(git rev-parse refs/heads/master) refs/heads/master
+ $(git rev-parse refs/heads/release) refs/heads/release symref-target:refs/heads/master
+ 0000
+ EOF
+
+ git serve --stateless-rpc <in >out &&
+ test-pkt-line unpack <out >actual &&
+ test_cmp actual expect
+'
+
+test_expect_success 'sending server-options' '
+ test-pkt-line pack >in <<-EOF &&
+ command=ls-refs
+ server-option=hello
+ server-option=world
+ 0001
+ ref-prefix HEAD
+ 0000
+ EOF
+
+ cat >expect <<-EOF &&
+ $(git rev-parse HEAD) HEAD
+ 0000
+ EOF
+
+ git serve --stateless-rpc <in >out &&
+ test-pkt-line unpack <out >actual &&
+ test_cmp actual expect
+'
+
+test_expect_success 'unexpected lines are not allowed in fetch request' '
+ git init server &&
+
+ test-pkt-line pack >in <<-EOF &&
+ command=fetch
+ 0001
+ this-is-not-a-command
+ 0000
+ EOF
+
+ test_must_fail git -C server serve --stateless-rpc <in >/dev/null 2>err &&
+ grep "unexpected line: .this-is-not-a-command." err
+'
+
+test_done
diff --git a/t/t5702-protocol-v2.sh b/t/t5702-protocol-v2.sh
new file mode 100755
index 0000000..a4fe650
--- /dev/null
+++ b/t/t5702-protocol-v2.sh
@@ -0,0 +1,431 @@
+#!/bin/sh
+
+test_description='test git wire-protocol version 2'
+
+TEST_NO_CREATE_REPO=1
+
+. ./test-lib.sh
+
+# Test protocol v2 with 'git://' transport
+#
+. "$TEST_DIRECTORY"/lib-git-daemon.sh
+start_git_daemon --export-all --enable=receive-pack
+daemon_parent=$GIT_DAEMON_DOCUMENT_ROOT_PATH/parent
+
+test_expect_success 'create repo to be served by git-daemon' '
+ git init "$daemon_parent" &&
+ test_commit -C "$daemon_parent" one
+'
+
+test_expect_success 'list refs with git:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -c protocol.version=2 \
+ ls-remote --symref "$GIT_DAEMON_URL/parent" >actual &&
+
+ # Client requested to use protocol v2
+ grep "git> .*\\\0\\\0version=2\\\0$" log &&
+ # Server responded using protocol v2
+ grep "git< version 2" log &&
+
+ git ls-remote --symref "$GIT_DAEMON_URL/parent" >expect &&
+ test_cmp actual expect
+'
+
+test_expect_success 'ref advertisment is filtered with ls-remote using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -c protocol.version=2 \
+ ls-remote "$GIT_DAEMON_URL/parent" master >actual &&
+
+ cat >expect <<-EOF &&
+ $(git -C "$daemon_parent" rev-parse refs/heads/master)$(printf "\t")refs/heads/master
+ EOF
+
+ test_cmp actual expect
+'
+
+test_expect_success 'clone with git:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -c protocol.version=2 \
+ clone "$GIT_DAEMON_URL/parent" daemon_child &&
+
+ git -C daemon_child log -1 --format=%s >actual &&
+ git -C "$daemon_parent" log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ # Client requested to use protocol v2
+ grep "clone> .*\\\0\\\0version=2\\\0$" log &&
+ # Server responded using protocol v2
+ grep "clone< version 2" log
+'
+
+test_expect_success 'fetch with git:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ test_commit -C "$daemon_parent" two &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -C daemon_child -c protocol.version=2 \
+ fetch &&
+
+ git -C daemon_child log -1 --format=%s origin/master >actual &&
+ git -C "$daemon_parent" log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ # Client requested to use protocol v2
+ grep "fetch> .*\\\0\\\0version=2\\\0$" log &&
+ # Server responded using protocol v2
+ grep "fetch< version 2" log
+'
+
+test_expect_success 'pull with git:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -C daemon_child -c protocol.version=2 \
+ pull &&
+
+ git -C daemon_child log -1 --format=%s >actual &&
+ git -C "$daemon_parent" log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ # Client requested to use protocol v2
+ grep "fetch> .*\\\0\\\0version=2\\\0$" log &&
+ # Server responded using protocol v2
+ grep "fetch< version 2" log
+'
+
+test_expect_success 'push with git:// and a config of v2 does not request v2' '
+ test_when_finished "rm -f log" &&
+
+ # Till v2 for push is designed, make sure that if a client has
+ # protocol.version configured to use v2, that the client instead falls
+ # back and uses v0.
+
+ test_commit -C daemon_child three &&
+
+ # Push to another branch, as the target repository has the
+ # master branch checked out and we cannot push into it.
+ GIT_TRACE_PACKET="$(pwd)/log" git -C daemon_child -c protocol.version=2 \
+ push origin HEAD:client_branch &&
+
+ git -C daemon_child log -1 --format=%s >actual &&
+ git -C "$daemon_parent" log -1 --format=%s client_branch >expect &&
+ test_cmp expect actual &&
+
+ # Client requested to use protocol v2
+ ! grep "push> .*\\\0\\\0version=2\\\0$" log &&
+ # Server responded using protocol v2
+ ! grep "push< version 2" log
+'
+
+stop_git_daemon
+
+# Test protocol v2 with 'file://' transport
+#
+test_expect_success 'create repo to be served by file:// transport' '
+ git init file_parent &&
+ test_commit -C file_parent one
+'
+
+test_expect_success 'list refs with file:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -c protocol.version=2 \
+ ls-remote --symref "file://$(pwd)/file_parent" >actual &&
+
+ # Server responded using protocol v2
+ grep "git< version 2" log &&
+
+ git ls-remote --symref "file://$(pwd)/file_parent" >expect &&
+ test_cmp actual expect
+'
+
+test_expect_success 'ref advertisment is filtered with ls-remote using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -c protocol.version=2 \
+ ls-remote "file://$(pwd)/file_parent" master >actual &&
+
+ cat >expect <<-EOF &&
+ $(git -C file_parent rev-parse refs/heads/master)$(printf "\t")refs/heads/master
+ EOF
+
+ test_cmp actual expect
+'
+
+test_expect_success 'server-options are sent when using ls-remote' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -c protocol.version=2 \
+ ls-remote -o hello -o world "file://$(pwd)/file_parent" master >actual &&
+
+ cat >expect <<-EOF &&
+ $(git -C file_parent rev-parse refs/heads/master)$(printf "\t")refs/heads/master
+ EOF
+
+ test_cmp actual expect &&
+ grep "server-option=hello" log &&
+ grep "server-option=world" log
+'
+
+
+test_expect_success 'clone with file:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -c protocol.version=2 \
+ clone "file://$(pwd)/file_parent" file_child &&
+
+ git -C file_child log -1 --format=%s >actual &&
+ git -C file_parent log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ # Server responded using protocol v2
+ grep "clone< version 2" log
+'
+
+test_expect_success 'fetch with file:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ test_commit -C file_parent two &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -C file_child -c protocol.version=2 \
+ fetch origin &&
+
+ git -C file_child log -1 --format=%s origin/master >actual &&
+ git -C file_parent log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ # Server responded using protocol v2
+ grep "fetch< version 2" log
+'
+
+test_expect_success 'ref advertisment is filtered during fetch using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ test_commit -C file_parent three &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -C file_child -c protocol.version=2 \
+ fetch origin master &&
+
+ git -C file_child log -1 --format=%s origin/master >actual &&
+ git -C file_parent log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ ! grep "refs/tags/one" log &&
+ ! grep "refs/tags/two" log &&
+ ! grep "refs/tags/three" log
+'
+
+test_expect_success 'server-options are sent when fetching' '
+ test_when_finished "rm -f log" &&
+
+ test_commit -C file_parent four &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -C file_child -c protocol.version=2 \
+ fetch -o hello -o world origin master &&
+
+ git -C file_child log -1 --format=%s origin/master >actual &&
+ git -C file_parent log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ grep "server-option=hello" log &&
+ grep "server-option=world" log
+'
+
+test_expect_success 'upload-pack respects config using protocol v2' '
+ git init server &&
+ write_script server/.git/hook <<-\EOF &&
+ touch hookout
+ "$@"
+ EOF
+ test_commit -C server one &&
+
+ test_config_global uploadpack.packobjectshook ./hook &&
+ test_path_is_missing server/.git/hookout &&
+ git -c protocol.version=2 clone "file://$(pwd)/server" client &&
+ test_path_is_file server/.git/hookout
+'
+
+test_expect_success 'setup filter tests' '
+ rm -rf server client &&
+ git init server &&
+
+ # 1 commit to create a file, and 1 commit to modify it
+ test_commit -C server message1 a.txt &&
+ test_commit -C server message2 a.txt &&
+ git -C server config protocol.version 2 &&
+ git -C server config uploadpack.allowfilter 1 &&
+ git -C server config uploadpack.allowanysha1inwant 1 &&
+ git -C server config protocol.version 2
+'
+
+test_expect_success 'partial clone' '
+ GIT_TRACE_PACKET="$(pwd)/trace" git -c protocol.version=2 \
+ clone --filter=blob:none "file://$(pwd)/server" client &&
+ grep "version 2" trace &&
+
+ # Ensure that the old version of the file is missing
+ git -C client rev-list master --quiet --objects --missing=print \
+ >observed.oids &&
+ grep "$(git -C server rev-parse message1:a.txt)" observed.oids &&
+
+ # Ensure that client passes fsck
+ git -C client fsck
+'
+
+test_expect_success 'dynamically fetch missing object' '
+ rm "$(pwd)/trace" &&
+ GIT_TRACE_PACKET="$(pwd)/trace" git -C client -c protocol.version=2 \
+ cat-file -p $(git -C server rev-parse message1:a.txt) &&
+ grep "version 2" trace
+'
+
+test_expect_success 'partial fetch' '
+ rm -rf client "$(pwd)/trace" &&
+ git init client &&
+ SERVER="file://$(pwd)/server" &&
+ test_config -C client extensions.partialClone "$SERVER" &&
+
+ GIT_TRACE_PACKET="$(pwd)/trace" git -C client -c protocol.version=2 \
+ fetch --filter=blob:none "$SERVER" master:refs/heads/other &&
+ grep "version 2" trace &&
+
+ # Ensure that the old version of the file is missing
+ git -C client rev-list other --quiet --objects --missing=print \
+ >observed.oids &&
+ grep "$(git -C server rev-parse message1:a.txt)" observed.oids &&
+
+ # Ensure that client passes fsck
+ git -C client fsck
+'
+
+test_expect_success 'do not advertise filter if not configured to do so' '
+ SERVER="file://$(pwd)/server" &&
+
+ rm "$(pwd)/trace" &&
+ git -C server config uploadpack.allowfilter 1 &&
+ GIT_TRACE_PACKET="$(pwd)/trace" git -c protocol.version=2 \
+ ls-remote "$SERVER" &&
+ grep "fetch=.*filter" trace &&
+
+ rm "$(pwd)/trace" &&
+ git -C server config uploadpack.allowfilter 0 &&
+ GIT_TRACE_PACKET="$(pwd)/trace" git -c protocol.version=2 \
+ ls-remote "$SERVER" &&
+ grep "fetch=" trace >fetch_capabilities &&
+ ! grep filter fetch_capabilities
+'
+
+test_expect_success 'partial clone warns if filter is not advertised' '
+ rm -rf client &&
+ git -C server config uploadpack.allowfilter 0 &&
+ git -c protocol.version=2 \
+ clone --filter=blob:none "file://$(pwd)/server" client 2>err &&
+ test_i18ngrep "filtering not recognized by server, ignoring" err
+'
+
+test_expect_success 'even with handcrafted request, filter does not work if not advertised' '
+ git -C server config uploadpack.allowfilter 0 &&
+
+ # Custom request that tries to filter even though it is not advertised.
+ test-pkt-line pack >in <<-EOF &&
+ command=fetch
+ 0001
+ want $(git -C server rev-parse master)
+ filter blob:none
+ 0000
+ EOF
+
+ test_must_fail git -C server serve --stateless-rpc <in >/dev/null 2>err &&
+ grep "unexpected line: .filter blob:none." err &&
+
+ # Exercise to ensure that if advertised, filter works
+ git -C server config uploadpack.allowfilter 1 &&
+ git -C server serve --stateless-rpc <in >/dev/null
+'
+
+test_expect_success 'default refspec is used to filter ref when fetchcing' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -C file_child -c protocol.version=2 \
+ fetch origin &&
+
+ git -C file_child log -1 --format=%s three >actual &&
+ git -C file_parent log -1 --format=%s three >expect &&
+ test_cmp expect actual &&
+
+ grep "ref-prefix refs/heads/" log &&
+ grep "ref-prefix refs/tags/" log
+'
+
+# Test protocol v2 with 'http://' transport
+#
+. "$TEST_DIRECTORY"/lib-httpd.sh
+start_httpd
+
+test_expect_success 'create repo to be served by http:// transport' '
+ git init "$HTTPD_DOCUMENT_ROOT_PATH/http_parent" &&
+ git -C "$HTTPD_DOCUMENT_ROOT_PATH/http_parent" config http.receivepack true &&
+ test_commit -C "$HTTPD_DOCUMENT_ROOT_PATH/http_parent" one
+'
+
+test_expect_success 'clone with http:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" GIT_TRACE_CURL="$(pwd)/log" git -c protocol.version=2 \
+ clone "$HTTPD_URL/smart/http_parent" http_child &&
+
+ git -C http_child log -1 --format=%s >actual &&
+ git -C "$HTTPD_DOCUMENT_ROOT_PATH/http_parent" log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ # Client requested to use protocol v2
+ grep "Git-Protocol: version=2" log &&
+ # Server responded using protocol v2
+ grep "git< version 2" log
+'
+
+test_expect_success 'fetch with http:// using protocol v2' '
+ test_when_finished "rm -f log" &&
+
+ test_commit -C "$HTTPD_DOCUMENT_ROOT_PATH/http_parent" two &&
+
+ GIT_TRACE_PACKET="$(pwd)/log" git -C http_child -c protocol.version=2 \
+ fetch &&
+
+ git -C http_child log -1 --format=%s origin/master >actual &&
+ git -C "$HTTPD_DOCUMENT_ROOT_PATH/http_parent" log -1 --format=%s >expect &&
+ test_cmp expect actual &&
+
+ # Server responded using protocol v2
+ grep "git< version 2" log
+'
+
+test_expect_success 'push with http:// and a config of v2 does not request v2' '
+ test_when_finished "rm -f log" &&
+ # Till v2 for push is designed, make sure that if a client has
+ # protocol.version configured to use v2, that the client instead falls
+ # back and uses v0.
+
+ test_commit -C http_child three &&
+
+ # Push to another branch, as the target repository has the
+ # master branch checked out and we cannot push into it.
+ GIT_TRACE_PACKET="$(pwd)/log" git -C http_child -c protocol.version=2 \
+ push origin HEAD:client_branch &&
+
+ git -C http_child log -1 --format=%s >actual &&
+ git -C "$HTTPD_DOCUMENT_ROOT_PATH/http_parent" log -1 --format=%s client_branch >expect &&
+ test_cmp expect actual &&
+
+ # Client didnt request to use protocol v2
+ ! grep "Git-Protocol: version=2" log &&
+ # Server didnt respond using protocol v2
+ ! grep "git< version 2" log
+'
+
+
+stop_httpd
+
+test_done
diff --git a/t/t6001-rev-list-graft.sh b/t/t6001-rev-list-graft.sh
index 05ddc69..7504ba4 100755
--- a/t/t6001-rev-list-graft.sh
+++ b/t/t6001-rev-list-graft.sh
@@ -110,4 +110,13 @@ do
"
done
+
+test_expect_success 'show advice that grafts are deprecated' '
+ git show HEAD 2>err &&
+ test_i18ngrep "git replace" err &&
+ test_config advice.graftFileDeprecated false &&
+ git show HEAD 2>err &&
+ test_i18ngrep ! "git replace" err
+'
+
test_done
diff --git a/t/t6006-rev-list-format.sh b/t/t6006-rev-list-format.sh
index 98be78b..ec42c2f 100755
--- a/t/t6006-rev-list-format.sh
+++ b/t/t6006-rev-list-format.sh
@@ -447,8 +447,8 @@ test_expect_success '--abbrev' '
git log -1 --format="%h %h %h" HEAD >actual1 &&
git log -1 --abbrev=5 --format="%h %h %h" HEAD >actual2 &&
git log -1 --abbrev=5 --format="%H %H %H" HEAD >actual3 &&
- sed -e "s/$_x40/LONG/g" -e "s/$_x05/SHORT/g" <actual2 >fuzzy2 &&
- sed -e "s/$_x40/LONG/g" -e "s/$_x05/SHORT/g" <actual3 >fuzzy3 &&
+ sed -e "s/$OID_REGEX/LONG/g" -e "s/$_x05/SHORT/g" <actual2 >fuzzy2 &&
+ sed -e "s/$OID_REGEX/LONG/g" -e "s/$_x05/SHORT/g" <actual3 >fuzzy3 &&
test_cmp expect2 fuzzy2 &&
test_cmp expect3 fuzzy3 &&
! test_cmp actual1 actual2
diff --git a/t/t6012-rev-list-simplify.sh b/t/t6012-rev-list-simplify.sh
index 2a0fbb8..b5a1190 100755
--- a/t/t6012-rev-list-simplify.sh
+++ b/t/t6012-rev-list-simplify.sh
@@ -9,7 +9,7 @@ note () {
}
unnote () {
- git name-rev --tags --stdin | sed -e "s|$_x40 (tags/\([^)]*\)) |\1 |g"
+ git name-rev --tags --stdin | sed -e "s|$OID_REGEX (tags/\([^)]*\)) |\1 |g"
}
test_expect_success setup '
diff --git a/t/t6022-merge-rename.sh b/t/t6022-merge-rename.sh
index 6df2650..b760c22 100755
--- a/t/t6022-merge-rename.sh
+++ b/t/t6022-merge-rename.sh
@@ -635,10 +635,9 @@ test_expect_success 'setup avoid unnecessary update, normal rename' '
test_expect_success 'avoid unnecessary update, normal rename' '
git checkout -q avoid-unnecessary-update-1^0 &&
- test-tool chmtime =1000000000 rename &&
- test-tool chmtime -v +0 rename >expect &&
+ test-tool chmtime --get =1000000000 rename >expect &&
git merge merge-branch-1 &&
- test-tool chmtime -v +0 rename >actual &&
+ test-tool chmtime --get rename >actual &&
test_cmp expect actual # "rename" should have stayed intact
'
@@ -668,10 +667,9 @@ test_expect_success 'setup to test avoiding unnecessary update, with D/F conflic
test_expect_success 'avoid unnecessary update, with D/F conflict' '
git checkout -q avoid-unnecessary-update-2^0 &&
- test-tool chmtime =1000000000 df &&
- test-tool chmtime -v +0 df >expect &&
+ test-tool chmtime --get =1000000000 df >expect &&
git merge merge-branch-2 &&
- test-tool chmtime -v +0 df >actual &&
+ test-tool chmtime --get df >actual &&
test_cmp expect actual # "df" should have stayed intact
'
@@ -700,10 +698,9 @@ test_expect_success 'setup avoid unnecessary update, dir->(file,nothing)' '
test_expect_success 'avoid unnecessary update, dir->(file,nothing)' '
git checkout -q master^0 &&
- test-tool chmtime =1000000000 df &&
- test-tool chmtime -v +0 df >expect &&
+ test-tool chmtime --get =1000000000 df >expect &&
git merge side &&
- test-tool chmtime -v +0 df >actual &&
+ test-tool chmtime --get df >actual &&
test_cmp expect actual # "df" should have stayed intact
'
@@ -730,10 +727,9 @@ test_expect_success 'setup avoid unnecessary update, modify/delete' '
test_expect_success 'avoid unnecessary update, modify/delete' '
git checkout -q master^0 &&
- test-tool chmtime =1000000000 file &&
- test-tool chmtime -v +0 file >expect &&
+ test-tool chmtime --get =1000000000 file >expect &&
test_must_fail git merge side &&
- test-tool chmtime -v +0 file >actual &&
+ test-tool chmtime --get file >actual &&
test_cmp expect actual # "file" should have stayed intact
'
@@ -759,10 +755,9 @@ test_expect_success 'setup avoid unnecessary update, rename/add-dest' '
test_expect_success 'avoid unnecessary update, rename/add-dest' '
git checkout -q master^0 &&
- test-tool chmtime =1000000000 newfile &&
- test-tool chmtime -v +0 newfile >expect &&
+ test-tool chmtime --get =1000000000 newfile >expect &&
git merge side &&
- test-tool chmtime -v +0 newfile >actual &&
+ test-tool chmtime --get newfile >actual &&
test_cmp expect actual # "file" should have stayed intact
'
diff --git a/t/t6050-replace.sh b/t/t6050-replace.sh
index c630aba..aa3e249 100755
--- a/t/t6050-replace.sh
+++ b/t/t6050-replace.sh
@@ -4,8 +4,6 @@
#
test_description='Tests replace refs functionality'
-exec </dev/null
-
. ./test-lib.sh
. "$TEST_DIRECTORY/lib-gpg.sh"
@@ -444,4 +442,32 @@ test_expect_success GPG '--graft on a commit with a mergetag' '
git replace -d $HASH10
'
+test_expect_success '--convert-graft-file' '
+ git checkout -b with-graft-file &&
+ test_commit root2 &&
+ git reset --hard root2^ &&
+ test_commit root1 &&
+ test_commit after-root1 &&
+ test_tick &&
+ git merge -m merge-root2 root2 &&
+
+ : add and convert graft file &&
+ printf "%s\n%s %s\n\n# comment\n%s\n" \
+ $(git rev-parse HEAD^^ HEAD^ HEAD^^ HEAD^2) \
+ >.git/info/grafts &&
+ git replace --convert-graft-file &&
+ test_path_is_missing .git/info/grafts &&
+
+ : verify that the history is now "grafted" &&
+ git rev-list HEAD >out &&
+ test_line_count = 4 out &&
+
+ : create invalid graft file and verify that it is not deleted &&
+ test_when_finished "rm -f .git/info/grafts" &&
+ echo $EMPTY_BLOB $EMPTY_TREE >.git/info/grafts &&
+ test_must_fail git replace --convert-graft-file 2>err &&
+ test_i18ngrep "$EMPTY_BLOB $EMPTY_TREE" err &&
+ test_i18ngrep "$EMPTY_BLOB $EMPTY_TREE" .git/info/grafts
+'
+
test_done
diff --git a/t/t6111-rev-list-treesame.sh b/t/t6111-rev-list-treesame.sh
index 32474c2..4244638 100755
--- a/t/t6111-rev-list-treesame.sh
+++ b/t/t6111-rev-list-treesame.sh
@@ -20,7 +20,7 @@ note () {
}
unnote () {
- git name-rev --tags --stdin | sed -e "s|$_x40 (tags/\([^)]*\))\([ ]\)|\1\2|g"
+ git name-rev --tags --stdin | sed -e "s|$OID_REGEX (tags/\([^)]*\))\([ ]\)|\1\2|g"
}
test_expect_success setup '
diff --git a/t/t6120-describe.sh b/t/t6120-describe.sh
index bae78c4..84dd1cb 100755
--- a/t/t6120-describe.sh
+++ b/t/t6120-describe.sh
@@ -383,7 +383,7 @@ test_expect_success 'describe complains about tree object' '
'
test_expect_success 'describe complains about missing object' '
- test_must_fail git describe $_z40
+ test_must_fail git describe $ZERO_OID
'
test_done
diff --git a/t/t6300-for-each-ref.sh b/t/t6300-for-each-ref.sh
index 295d147..48379aa 100755
--- a/t/t6300-for-each-ref.sh
+++ b/t/t6300-for-each-ref.sh
@@ -310,7 +310,7 @@ test_expect_success 'exercise strftime with odd fields' '
echo >expected &&
git for-each-ref --format="%(authordate:format:)" refs/heads >actual &&
test_cmp expected actual &&
- long="long format -- $_z40$_z40$_z40$_z40$_z40$_z40$_z40" &&
+ long="long format -- $ZERO_OID$ZERO_OID$ZERO_OID$ZERO_OID$ZERO_OID$ZERO_OID$ZERO_OID" &&
echo $long >expected &&
git for-each-ref --format="%(authordate:format:$long)" refs/heads >actual &&
test_cmp expected actual
diff --git a/t/t6301-for-each-ref-errors.sh b/t/t6301-for-each-ref-errors.sh
index c734ce2..49cc65b 100755
--- a/t/t6301-for-each-ref-errors.sh
+++ b/t/t6301-for-each-ref-errors.sh
@@ -4,7 +4,7 @@ test_description='for-each-ref errors for broken refs'
. ./test-lib.sh
-ZEROS=$_z40
+ZEROS=$ZERO_OID
MISSING=abababababababababababababababababababab
test_expect_success setup '
diff --git a/t/t6500-gc.sh b/t/t6500-gc.sh
index d5255dd..818435f 100755
--- a/t/t6500-gc.sh
+++ b/t/t6500-gc.sh
@@ -5,6 +5,13 @@ test_description='basic git gc tests
. ./test-lib.sh
+test_expect_success 'setup' '
+ # do not let the amount of physical memory affects gc
+ # behavior, make sure we always pack everything to one pack by
+ # default
+ git config gc.bigPackThreshold 2g
+'
+
test_expect_success 'gc empty repository' '
git gc
'
@@ -43,6 +50,31 @@ test_expect_success 'gc is not aborted due to a stale symref' '
)
'
+test_expect_success 'gc --keep-largest-pack' '
+ test_create_repo keep-pack &&
+ (
+ cd keep-pack &&
+ test_commit one &&
+ test_commit two &&
+ test_commit three &&
+ git gc &&
+ ( cd .git/objects/pack && ls *.pack ) >pack-list &&
+ test_line_count = 1 pack-list &&
+ BASE_PACK=.git/objects/pack/pack-*.pack &&
+ test_commit four &&
+ git repack -d &&
+ test_commit five &&
+ git repack -d &&
+ ( cd .git/objects/pack && ls *.pack ) >pack-list &&
+ test_line_count = 3 pack-list &&
+ git gc --keep-largest-pack &&
+ ( cd .git/objects/pack && ls *.pack ) >pack-list &&
+ test_line_count = 2 pack-list &&
+ test_path_is_file $BASE_PACK &&
+ git fsck
+ )
+'
+
test_expect_success 'auto gc with too many loose objects does not attempt to create bitmaps' '
test_config gc.auto 3 &&
test_config gc.autodetach false &&
diff --git a/t/t6501-freshen-objects.sh b/t/t6501-freshen-objects.sh
index 765cced..033871e 100755
--- a/t/t6501-freshen-objects.sh
+++ b/t/t6501-freshen-objects.sh
@@ -72,8 +72,7 @@ for repack in '' true; do
'
test_expect_success "simulate time passing ($title)" '
- find .git/objects -type f |
- xargs test-tool chmtime -v -86400
+ test-tool chmtime --get -86400 $(find .git/objects -type f)
'
test_expect_success "start writing new commit with old blob ($title)" '
@@ -103,8 +102,7 @@ for repack in '' true; do
test_expect_success "abandon objects again ($title)" '
git reset --hard HEAD^ &&
- find .git/objects -type f |
- xargs test-tool chmtime -v -86400
+ test-tool chmtime --get -86400 $(find .git/objects -type f)
'
test_expect_success "start writing new commit with same tree ($title)" '
diff --git a/t/t7001-mv.sh b/t/t7001-mv.sh
index e96cbdb..cc3fd2b 100755
--- a/t/t7001-mv.sh
+++ b/t/t7001-mv.sh
@@ -495,7 +495,7 @@ test_expect_success 'moving a submodule in nested directories' '
test_cmp expect actual
'
-test_expect_failure 'moving nested submodules' '
+test_expect_success 'moving nested submodules' '
git commit -am "cleanup commit" &&
mkdir sub_nested_nested &&
(cd sub_nested_nested &&
diff --git a/t/t7004-tag.sh b/t/t7004-tag.sh
index 2aac77a..d7b319e 100755
--- a/t/t7004-tag.sh
+++ b/t/t7004-tag.sh
@@ -363,7 +363,7 @@ test_expect_success 'tag -l <pattern> -l <pattern> works, as our buggy documenta
'
test_expect_success 'listing tags in column' '
- COLUMNS=40 git tag -l --column=row >actual &&
+ COLUMNS=41 git tag -l --column=row >actual &&
cat >expected <<\EOF &&
a1 aa1 cba t210 t211
v0.2.1 v1.0 v1.0.1 v1.1.3
@@ -1056,7 +1056,18 @@ test_expect_success GPG \
git tag -s -F sigblanknonlfile blanknonlfile-signed-tag &&
get_tag_msg blanknonlfile-signed-tag >actual &&
test_cmp expect actual &&
- git tag -v signed-tag
+ git tag -v blanknonlfile-signed-tag
+'
+
+test_expect_success GPG 'signed tag with embedded PGP message' '
+ cat >msg <<-\EOF &&
+ -----BEGIN PGP MESSAGE-----
+
+ this is not a real PGP message
+ -----END PGP MESSAGE-----
+ EOF
+ git tag -s -F msg confusing-pgp-message &&
+ git tag -v confusing-pgp-message
'
# messages with commented lines for signed tags:
diff --git a/t/t7005-editor.sh b/t/t7005-editor.sh
index 29e5043..b2ca77b 100755
--- a/t/t7005-editor.sh
+++ b/t/t7005-editor.sh
@@ -111,14 +111,8 @@ do
'
done
-if echo 'echo space > "$1"' > "e space.sh"
-then
- # FS supports spaces in filenames
- test_set_prereq SPACES_IN_FILENAMES
-fi
-
-test_expect_success SPACES_IN_FILENAMES 'editor with a space' '
-
+test_expect_success 'editor with a space' '
+ echo "echo space >\$1" >"e space.sh" &&
chmod a+x "e space.sh" &&
GIT_EDITOR="./e\ space.sh" git commit --amend &&
test space = "$(git show -s --pretty=format:%s)"
@@ -126,7 +120,7 @@ test_expect_success SPACES_IN_FILENAMES 'editor with a space' '
'
unset GIT_EDITOR
-test_expect_success SPACES_IN_FILENAMES 'core.editor with a space' '
+test_expect_success 'core.editor with a space' '
git config core.editor \"./e\ space.sh\" &&
git commit --amend &&
diff --git a/t/t7009-filter-branch-null-sha1.sh b/t/t7009-filter-branch-null-sha1.sh
index a8d9ec4..9ba9f24 100755
--- a/t/t7009-filter-branch-null-sha1.sh
+++ b/t/t7009-filter-branch-null-sha1.sh
@@ -12,7 +12,7 @@ test_expect_success 'setup: base commits' '
test_expect_success 'setup: a commit with a bogus null sha1 in the tree' '
{
git ls-tree HEAD &&
- printf "160000 commit $_z40\\tbroken\\n"
+ printf "160000 commit $ZERO_OID\\tbroken\\n"
} >broken-tree &&
echo "add broken entry" >msg &&
diff --git a/t/t7011-skip-worktree-reading.sh b/t/t7011-skip-worktree-reading.sh
index 84f4145..37525ca 100755
--- a/t/t7011-skip-worktree-reading.sh
+++ b/t/t7011-skip-worktree-reading.sh
@@ -118,7 +118,7 @@ test_expect_success 'grep with skip-worktree file' '
test "$(git grep --no-ext-grep test)" = "1:test"
'
-echo ":000000 100644 $_z40 $EMPTY_BLOB A 1" > expected
+echo ":000000 100644 $ZERO_OID $EMPTY_BLOB A 1" > expected
test_expect_success 'diff-index does not examine skip-worktree absent entries' '
setup_absent &&
git diff-index HEAD -- 1 > result &&
diff --git a/t/t7064-wtstatus-pv2.sh b/t/t7064-wtstatus-pv2.sh
index 8f79532..b9a86d3 100755
--- a/t/t7064-wtstatus-pv2.sh
+++ b/t/t7064-wtstatus-pv2.sh
@@ -46,11 +46,11 @@ test_expect_success 'before initial commit, things added' '
cat >expect <<-EOF &&
# branch.oid (initial)
# branch.head master
- 1 A. N... 000000 100644 100644 $_z40 $OID_A dir1/file_a
- 1 A. N... 000000 100644 100644 $_z40 $OID_B dir1/file_b
- 1 A. N... 000000 100644 100644 $_z40 $OID_X file_x
- 1 A. N... 000000 100644 100644 $_z40 $OID_Y file_y
- 1 A. N... 000000 100644 100644 $_z40 $OID_Z file_z
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_A dir1/file_a
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_B dir1/file_b
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_X file_x
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_Y file_y
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_Z file_z
? actual
? expect
EOF
@@ -63,11 +63,11 @@ test_expect_success 'before initial commit, things added (-z)' '
lf_to_nul >expect <<-EOF &&
# branch.oid (initial)
# branch.head master
- 1 A. N... 000000 100644 100644 $_z40 $OID_A dir1/file_a
- 1 A. N... 000000 100644 100644 $_z40 $OID_B dir1/file_b
- 1 A. N... 000000 100644 100644 $_z40 $OID_X file_x
- 1 A. N... 000000 100644 100644 $_z40 $OID_Y file_y
- 1 A. N... 000000 100644 100644 $_z40 $OID_Z file_z
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_A dir1/file_a
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_B dir1/file_b
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_X file_x
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_Y file_y
+ 1 A. N... 000000 100644 100644 $ZERO_OID $OID_Z file_z
? actual
? expect
EOF
@@ -128,7 +128,7 @@ test_expect_success 'after first commit, stage existing changes' '
# branch.oid $H0
# branch.head master
1 M. N... 100644 100644 100644 $OID_X $OID_X1 file_x
- 1 D. N... 100644 000000 000000 $OID_Z $_z40 file_z
+ 1 D. N... 100644 000000 000000 $OID_Z $ZERO_OID file_z
? actual
? expect
EOF
@@ -145,7 +145,7 @@ test_expect_success 'rename causes 2 path lines' '
# branch.oid $H0
# branch.head master
1 M. N... 100644 100644 100644 $OID_X $OID_X1 file_x
- 1 D. N... 100644 000000 000000 $OID_Z $_z40 file_z
+ 1 D. N... 100644 000000 000000 $OID_Z $ZERO_OID file_z
2 R. N... 100644 100644 100644 $OID_Y $OID_Y R100 renamed_yQfile_y
? actual
? expect
@@ -163,7 +163,7 @@ test_expect_success 'rename causes 2 path lines (-z)' '
# branch.oid $H0
# branch.head master
1 M. N... 100644 100644 100644 $OID_X $OID_X1 file_x
- 1 D. N... 100644 000000 000000 $OID_Z $_z40 file_z
+ 1 D. N... 100644 000000 000000 $OID_Z $ZERO_OID file_z
2 R. N... 100644 100644 100644 $OID_Y $OID_Y R100 renamed_yQfile_y
? actual
? expect
@@ -246,8 +246,8 @@ test_expect_success 'verify --intent-to-add output' '
git add --intent-to-add intent1.add intent2.add &&
cat >expect <<-EOF &&
- 1 .A N... 000000 000000 100644 $_z40 $_z40 intent1.add
- 1 .A N... 000000 000000 100644 $_z40 $_z40 intent2.add
+ 1 .A N... 000000 000000 100644 $ZERO_OID $ZERO_OID intent1.add
+ 1 .A N... 000000 000000 100644 $ZERO_OID $ZERO_OID intent2.add
EOF
git status --porcelain=v2 >actual &&
@@ -280,7 +280,7 @@ test_expect_success 'verify AA (add-add) conflict' '
cat >expect <<-EOF &&
# branch.oid $HM
# branch.head AA_M
- u AA N... 000000 100644 100644 100644 $_z40 $OID_AA_B $OID_AA_A conflict.txt
+ u AA N... 000000 100644 100644 100644 $ZERO_OID $OID_AA_B $OID_AA_A conflict.txt
EOF
git status --porcelain=v2 --branch --untracked-files=all >actual &&
@@ -373,7 +373,7 @@ test_expect_success 'verify upstream fields in branch header' '
## Test upstream-gone case. Fake this by pointing origin/master at
## a non-existing commit.
OLD=$(git rev-parse origin/master) &&
- NEW=$_z40 &&
+ NEW=$ZERO_OID &&
mv .git/packed-refs .git/old-packed-refs &&
sed "s/$OLD/$NEW/g" <.git/old-packed-refs >.git/packed-refs &&
@@ -469,8 +469,8 @@ test_expect_success 'create and add submodule, submodule appears clean (A. S...)
# branch.head master
# branch.upstream origin/master
# branch.ab +0 -0
- 1 A. N... 000000 100644 100644 $_z40 $HMOD .gitmodules
- 1 A. S... 000000 160000 160000 $_z40 $HSUB sub1
+ 1 A. N... 000000 100644 100644 $ZERO_OID $HMOD .gitmodules
+ 1 A. S... 000000 160000 160000 $ZERO_OID $HSUB sub1
EOF
git status --porcelain=v2 --branch --untracked-files=all >actual &&
@@ -494,8 +494,8 @@ test_expect_success 'untracked changes in added submodule (AM S..U)' '
# branch.head master
# branch.upstream origin/master
# branch.ab +0 -0
- 1 A. N... 000000 100644 100644 $_z40 $HMOD .gitmodules
- 1 AM S..U 000000 160000 160000 $_z40 $HSUB sub1
+ 1 A. N... 000000 100644 100644 $ZERO_OID $HMOD .gitmodules
+ 1 AM S..U 000000 160000 160000 $ZERO_OID $HSUB sub1
EOF
git status --porcelain=v2 --branch --untracked-files=all >actual &&
@@ -519,8 +519,8 @@ test_expect_success 'staged changes in added submodule (AM S.M.)' '
# branch.head master
# branch.upstream origin/master
# branch.ab +0 -0
- 1 A. N... 000000 100644 100644 $_z40 $HMOD .gitmodules
- 1 AM S.M. 000000 160000 160000 $_z40 $HSUB sub1
+ 1 A. N... 000000 100644 100644 $ZERO_OID $HMOD .gitmodules
+ 1 AM S.M. 000000 160000 160000 $ZERO_OID $HSUB sub1
EOF
git status --porcelain=v2 --branch --untracked-files=all >actual &&
@@ -546,8 +546,8 @@ test_expect_success 'staged and unstaged changes in added (AM S.M.)' '
# branch.head master
# branch.upstream origin/master
# branch.ab +0 -0
- 1 A. N... 000000 100644 100644 $_z40 $HMOD .gitmodules
- 1 AM S.M. 000000 160000 160000 $_z40 $HSUB sub1
+ 1 A. N... 000000 100644 100644 $ZERO_OID $HMOD .gitmodules
+ 1 AM S.M. 000000 160000 160000 $ZERO_OID $HSUB sub1
EOF
git status --porcelain=v2 --branch --untracked-files=all >actual &&
@@ -573,8 +573,8 @@ test_expect_success 'staged and untracked changes in added submodule (AM S.MU)'
# branch.head master
# branch.upstream origin/master
# branch.ab +0 -0
- 1 A. N... 000000 100644 100644 $_z40 $HMOD .gitmodules
- 1 AM S.MU 000000 160000 160000 $_z40 $HSUB sub1
+ 1 A. N... 000000 100644 100644 $ZERO_OID $HMOD .gitmodules
+ 1 AM S.MU 000000 160000 160000 $ZERO_OID $HSUB sub1
EOF
git status --porcelain=v2 --branch --untracked-files=all >actual &&
@@ -600,8 +600,8 @@ test_expect_success 'commit within the submodule appears as new commit in super
# branch.head master
# branch.upstream origin/master
# branch.ab +0 -0
- 1 A. N... 000000 100644 100644 $_z40 $HMOD .gitmodules
- 1 AM SC.. 000000 160000 160000 $_z40 $HSUB sub1
+ 1 A. N... 000000 100644 100644 $ZERO_OID $HMOD .gitmodules
+ 1 AM SC.. 000000 160000 160000 $ZERO_OID $HSUB sub1
EOF
git status --porcelain=v2 --branch --untracked-files=all >actual &&
diff --git a/t/t7400-submodule-basic.sh b/t/t7400-submodule-basic.sh
index 1521044..2f53252 100755
--- a/t/t7400-submodule-basic.sh
+++ b/t/t7400-submodule-basic.sh
@@ -126,6 +126,22 @@ test_expect_success 'submodule add' '
test_cmp empty untracked
'
+test_create_repo parent &&
+test_commit -C parent one
+
+test_expect_success 'redirected submodule add does not show progress' '
+ git -C addtest submodule add "file://$submodurl/parent" submod-redirected \
+ 2>err &&
+ ! grep % err &&
+ test_i18ngrep ! "Checking connectivity" err
+'
+
+test_expect_success 'redirected submodule add --progress does show progress' '
+ git -C addtest submodule add --progress "file://$submodurl/parent" \
+ submod-redirected-progress 2>err && \
+ grep % err
+'
+
test_expect_success 'submodule add to .gitignored path fails' '
(
cd addtest-ignore &&
diff --git a/t/t7408-submodule-reference.sh b/t/t7408-submodule-reference.sh
index e159fc5..08d9add 100755
--- a/t/t7408-submodule-reference.sh
+++ b/t/t7408-submodule-reference.sh
@@ -59,6 +59,16 @@ test_expect_success 'submodule add --reference uses alternates' '
test_alternate_is_used super/.git/modules/sub/objects/info/alternates super/sub
'
+test_expect_success 'submodule add --reference with --dissociate does not use alternates' '
+ (
+ cd super &&
+ git submodule add --reference ../B --dissociate "file://$base_dir/A" sub-dissociate &&
+ git commit -m B-super-added &&
+ git repack -ad
+ ) &&
+ test_path_is_missing super/.git/modules/sub-dissociate/objects/info/alternates
+'
+
test_expect_success 'that reference gets used with add' '
(
cd super/sub &&
@@ -82,6 +92,13 @@ test_expect_success 'updating superproject keeps alternates' '
test_alternate_is_used super-clone/.git/modules/sub/objects/info/alternates super-clone/sub
'
+test_expect_success 'updating superproject with --dissociate does not keep alternates' '
+ test_when_finished "rm -rf super-clone" &&
+ git clone super super-clone &&
+ git -C super-clone submodule update --init --reference ../B --dissociate &&
+ test_path_is_missing super-clone/.git/modules/sub/objects/info/alternates
+'
+
test_expect_success 'submodules use alternates when cloning a superproject' '
test_when_finished "rm -rf super-clone" &&
git clone --reference super --recursive super super-clone &&
diff --git a/t/t7415-submodule-names.sh b/t/t7415-submodule-names.sh
new file mode 100755
index 0000000..a770d92
--- /dev/null
+++ b/t/t7415-submodule-names.sh
@@ -0,0 +1,154 @@
+#!/bin/sh
+
+test_description='check handling of .. in submodule names
+
+Exercise the name-checking function on a variety of names, and then give a
+real-world setup that confirms we catch this in practice.
+'
+. ./test-lib.sh
+. "$TEST_DIRECTORY"/lib-pack.sh
+
+test_expect_success 'check names' '
+ cat >expect <<-\EOF &&
+ valid
+ valid/with/paths
+ EOF
+
+ git submodule--helper check-name >actual <<-\EOF &&
+ valid
+ valid/with/paths
+
+ ../foo
+ /../foo
+ ..\foo
+ \..\foo
+ foo/..
+ foo/../
+ foo\..
+ foo\..\
+ foo/../bar
+ EOF
+
+ test_cmp expect actual
+'
+
+test_expect_success 'create innocent subrepo' '
+ git init innocent &&
+ git -C innocent commit --allow-empty -m foo
+'
+
+test_expect_success 'submodule add refuses invalid names' '
+ test_must_fail \
+ git submodule add --name ../../modules/evil "$PWD/innocent" evil
+'
+
+test_expect_success 'add evil submodule' '
+ git submodule add "$PWD/innocent" evil &&
+
+ mkdir modules &&
+ cp -r .git/modules/evil modules &&
+ write_script modules/evil/hooks/post-checkout <<-\EOF &&
+ echo >&2 "RUNNING POST CHECKOUT"
+ EOF
+
+ git config -f .gitmodules submodule.evil.update checkout &&
+ git config -f .gitmodules --rename-section \
+ submodule.evil submodule.../../modules/evil &&
+ git add modules &&
+ git commit -am evil
+'
+
+# This step seems like it shouldn't be necessary, since the payload is
+# contained entirely in the evil submodule. But due to the vagaries of the
+# submodule code, checking out the evil module will fail unless ".git/modules"
+# exists. Adding another submodule (with a name that sorts before "evil") is an
+# easy way to make sure this is the case in the victim clone.
+test_expect_success 'add other submodule' '
+ git submodule add "$PWD/innocent" another-module &&
+ git add another-module &&
+ git commit -am another
+'
+
+test_expect_success 'clone evil superproject' '
+ git clone --recurse-submodules . victim >output 2>&1 &&
+ ! grep "RUNNING POST CHECKOUT" output
+'
+
+test_expect_success 'fsck detects evil superproject' '
+ test_must_fail git fsck
+'
+
+test_expect_success 'transfer.fsckObjects detects evil superproject (unpack)' '
+ rm -rf dst.git &&
+ git init --bare dst.git &&
+ git -C dst.git config transfer.fsckObjects true &&
+ test_must_fail git push dst.git HEAD
+'
+
+test_expect_success 'transfer.fsckObjects detects evil superproject (index)' '
+ rm -rf dst.git &&
+ git init --bare dst.git &&
+ git -C dst.git config transfer.fsckObjects true &&
+ git -C dst.git config transfer.unpackLimit 1 &&
+ test_must_fail git push dst.git HEAD
+'
+
+# Normally our packs contain commits followed by trees followed by blobs. This
+# reverses the order, which requires backtracking to find the context of a
+# blob. We'll start with a fresh gitmodules-only tree to make it simpler.
+test_expect_success 'create oddly ordered pack' '
+ git checkout --orphan odd &&
+ git rm -rf --cached . &&
+ git add .gitmodules &&
+ git commit -m odd &&
+ {
+ pack_header 3 &&
+ pack_obj $(git rev-parse HEAD:.gitmodules) &&
+ pack_obj $(git rev-parse HEAD^{tree}) &&
+ pack_obj $(git rev-parse HEAD)
+ } >odd.pack &&
+ pack_trailer odd.pack
+'
+
+test_expect_success 'transfer.fsckObjects handles odd pack (unpack)' '
+ rm -rf dst.git &&
+ git init --bare dst.git &&
+ test_must_fail git -C dst.git unpack-objects --strict <odd.pack
+'
+
+test_expect_success 'transfer.fsckObjects handles odd pack (index)' '
+ rm -rf dst.git &&
+ git init --bare dst.git &&
+ test_must_fail git -C dst.git index-pack --strict --stdin <odd.pack
+'
+
+test_expect_success 'fsck detects symlinked .gitmodules file' '
+ git init symlink &&
+ (
+ cd symlink &&
+
+ # Make the tree directly to avoid index restrictions.
+ #
+ # Because symlinks store the target as a blob, choose
+ # a pathname that could be parsed as a .gitmodules file
+ # to trick naive non-symlink-aware checking.
+ tricky="[foo]bar=true" &&
+ content=$(git hash-object -w ../.gitmodules) &&
+ target=$(printf "$tricky" | git hash-object -w --stdin) &&
+ tree=$(
+ {
+ printf "100644 blob $content\t$tricky\n" &&
+ printf "120000 blob $target\t.gitmodules\n"
+ } | git mktree
+ ) &&
+ commit=$(git commit-tree $tree) &&
+
+ # Check not only that we fail, but that it is due to the
+ # symlink detector; this grep string comes from the config
+ # variable name and will not be translated.
+ test_must_fail git fsck 2>output &&
+ grep gitmodulesSymlink output
+ )
+'
+
+test_done
diff --git a/t/t7501-commit.sh b/t/t7501-commit.sh
index fa61b1a..9dbbd01 100755
--- a/t/t7501-commit.sh
+++ b/t/t7501-commit.sh
@@ -52,6 +52,18 @@ test_expect_success PERL 'can use paths with --interactive' '
git reset --hard HEAD^
'
+test_expect_success 'removed files and relative paths' '
+ test_when_finished "rm -rf foo" &&
+ git init foo &&
+ >foo/foo.txt &&
+ git -C foo add foo.txt &&
+ git -C foo commit -m first &&
+ git -C foo rm foo.txt &&
+
+ mkdir -p foo/bar &&
+ git -C foo/bar commit -m second ../foo.txt
+'
+
test_expect_success 'using invalid commit with -C' '
test_must_fail git commit --allow-empty -C bogus
'
diff --git a/t/t7506-status-submodule.sh b/t/t7506-status-submodule.sh
index 9edf657..b4b74db 100755
--- a/t/t7506-status-submodule.sh
+++ b/t/t7506-status-submodule.sh
@@ -18,7 +18,7 @@ test_create_repo_with_commit () {
}
sanitize_output () {
- sed -e "s/$_x40/HASH/" -e "s/$_x40/HASH/" output >output2 &&
+ sed -e "s/$OID_REGEX/HASH/" -e "s/$OID_REGEX/HASH/" output >output2 &&
mv output2 output
}
diff --git a/t/t7508-status.sh b/t/t7508-status.sh
index 7afadb1..18a4025 100755
--- a/t/t7508-status.sh
+++ b/t/t7508-status.sh
@@ -1674,10 +1674,10 @@ test_expect_success '"Initial commit" should not be noted in commit template' '
test_expect_success '--no-optional-locks prevents index update' '
test-tool chmtime =1234567890 .git/index &&
git --no-optional-locks status &&
- test-tool chmtime -v +0 .git/index >out &&
+ test-tool chmtime --get .git/index >out &&
grep ^1234567890 out &&
git status &&
- test-tool chmtime -v +0 .git/index >out &&
+ test-tool chmtime --get .git/index >out &&
! grep ^1234567890 out
'
diff --git a/t/t7525-status-rename.sh b/t/t7525-status-rename.sh
new file mode 100755
index 0000000..ef8b1b3
--- /dev/null
+++ b/t/t7525-status-rename.sh
@@ -0,0 +1,113 @@
+#!/bin/sh
+
+test_description='git status rename detection options'
+
+. ./test-lib.sh
+
+test_expect_success 'setup' '
+ echo 1 >original &&
+ git add . &&
+ git commit -m"Adding original file." &&
+ mv original renamed &&
+ echo 2 >> renamed &&
+ git add . &&
+ cat >.gitignore <<-\EOF
+ .gitignore
+ expect*
+ actual*
+ EOF
+'
+
+test_expect_success 'status no-options' '
+ git status >actual &&
+ test_i18ngrep "renamed:" actual
+'
+
+test_expect_success 'status --no-renames' '
+ git status --no-renames >actual &&
+ test_i18ngrep "deleted:" actual &&
+ test_i18ngrep "new file:" actual
+'
+
+test_expect_success 'status.renames inherits from diff.renames false' '
+ git -c diff.renames=false status >actual &&
+ test_i18ngrep "deleted:" actual &&
+ test_i18ngrep "new file:" actual
+'
+
+test_expect_success 'status.renames inherits from diff.renames true' '
+ git -c diff.renames=true status >actual &&
+ test_i18ngrep "renamed:" actual
+'
+
+test_expect_success 'status.renames overrides diff.renames false' '
+ git -c diff.renames=true -c status.renames=false status >actual &&
+ test_i18ngrep "deleted:" actual &&
+ test_i18ngrep "new file:" actual
+'
+
+test_expect_success 'status.renames overrides from diff.renames true' '
+ git -c diff.renames=false -c status.renames=true status >actual &&
+ test_i18ngrep "renamed:" actual
+'
+
+test_expect_success 'status status.renames=false' '
+ git -c status.renames=false status >actual &&
+ test_i18ngrep "deleted:" actual &&
+ test_i18ngrep "new file:" actual
+'
+
+test_expect_success 'status status.renames=true' '
+ git -c status.renames=true status >actual &&
+ test_i18ngrep "renamed:" actual
+'
+
+test_expect_success 'commit honors status.renames=false' '
+ git -c status.renames=false commit --dry-run >actual &&
+ test_i18ngrep "deleted:" actual &&
+ test_i18ngrep "new file:" actual
+'
+
+test_expect_success 'commit honors status.renames=true' '
+ git -c status.renames=true commit --dry-run >actual &&
+ test_i18ngrep "renamed:" actual
+'
+
+test_expect_success 'status config overridden' '
+ git -c status.renames=true status --no-renames >actual &&
+ test_i18ngrep "deleted:" actual &&
+ test_i18ngrep "new file:" actual
+'
+
+test_expect_success 'status score=100%' '
+ git status -M=100% >actual &&
+ test_i18ngrep "deleted:" actual &&
+ test_i18ngrep "new file:" actual &&
+
+ git status --find-rename=100% >actual &&
+ test_i18ngrep "deleted:" actual &&
+ test_i18ngrep "new file:" actual
+'
+
+test_expect_success 'status score=01%' '
+ git status -M=01% >actual &&
+ test_i18ngrep "renamed:" actual &&
+
+ git status --find-rename=01% >actual &&
+ test_i18ngrep "renamed:" actual
+'
+
+test_expect_success 'copies not overridden by find-rename' '
+ cp renamed copy &&
+ git add copy &&
+
+ git -c status.renames=copies status -M=01% >actual &&
+ test_i18ngrep "copied:" actual &&
+ test_i18ngrep "renamed:" actual &&
+
+ git -c status.renames=copies status --find-rename=01% >actual &&
+ test_i18ngrep "copied:" actual &&
+ test_i18ngrep "renamed:" actual
+'
+
+test_done
diff --git a/t/t7700-repack.sh b/t/t7700-repack.sh
index 6061a04..6162e2a 100755
--- a/t/t7700-repack.sh
+++ b/t/t7700-repack.sh
@@ -4,6 +4,12 @@ test_description='git repack works correctly'
. ./test-lib.sh
+commit_and_pack() {
+ test_commit "$@" >/dev/null &&
+ SHA1=$(git pack-objects --all --unpacked --incremental .git/objects/pack/pack </dev/null) &&
+ echo pack-${SHA1}.pack
+}
+
test_expect_success 'objects in packs marked .keep are not repacked' '
echo content1 > file1 &&
echo content2 > file2 &&
@@ -194,7 +200,26 @@ test_expect_success 'objects made unreachable by grafts only are kept' '
git reflog expire --expire=$test_tick --expire-unreachable=$test_tick --all &&
git repack -a -d &&
git cat-file -t $H1
- '
+'
+
+test_expect_success 'repack --keep-pack' '
+ test_create_repo keep-pack &&
+ (
+ cd keep-pack &&
+ P1=$(commit_and_pack 1) &&
+ P2=$(commit_and_pack 2) &&
+ P3=$(commit_and_pack 3) &&
+ P4=$(commit_and_pack 4) &&
+ ls .git/objects/pack/*.pack >old-counts &&
+ test_line_count = 4 old-counts &&
+ git repack -a -d --keep-pack $P1 --keep-pack $P4 &&
+ ls .git/objects/pack/*.pack >new-counts &&
+ grep -q $P1 new-counts &&
+ grep -q $P4 new-counts &&
+ test_line_count = 3 new-counts &&
+ git fsck
+ )
+'
test_done
diff --git a/t/t7701-repack-unpack-unreachable.sh b/t/t7701-repack-unpack-unreachable.sh
index 8a586ab..48261ba 100755
--- a/t/t7701-repack-unpack-unreachable.sh
+++ b/t/t7701-repack-unpack-unreachable.sh
@@ -55,8 +55,8 @@ test_expect_success '-A with -d option leaves unreachable objects unpacked' '
compare_mtimes ()
{
- read tref rest &&
- while read t rest; do
+ read tref &&
+ while read t; do
test "$tref" = "$t" || return 1
done
}
@@ -90,7 +90,7 @@ test_expect_success 'unpacked objects receive timestamp of pack file' '
tmppack=".git/objects/pack/tmp_pack" &&
ln "$packfile" "$tmppack" &&
git repack -A -l -d &&
- test-tool chmtime -v +0 "$tmppack" "$fsha1path" "$csha1path" "$tsha1path" \
+ test-tool chmtime --get "$tmppack" "$fsha1path" "$csha1path" "$tsha1path" \
> mtimes &&
compare_mtimes < mtimes
'
diff --git a/t/t8012-blame-colors.sh b/t/t8012-blame-colors.sh
new file mode 100755
index 0000000..ed38f74
--- /dev/null
+++ b/t/t8012-blame-colors.sh
@@ -0,0 +1,48 @@
+#!/bin/sh
+
+test_description='colored git blame'
+. ./test-lib.sh
+
+PROG='git blame -c'
+. "$TEST_DIRECTORY"/annotate-tests.sh
+
+test_expect_success 'colored blame colors contiguous lines' '
+ git -c color.blame.repeatedLines=yellow blame --color-lines --abbrev=12 hello.c >actual.raw &&
+ git -c color.blame.repeatedLines=yellow -c blame.coloring=repeatedLines blame --abbrev=12 hello.c >actual.raw.2 &&
+ test_cmp actual.raw actual.raw.2 &&
+ test_decode_color <actual.raw >actual &&
+ grep "<YELLOW>" <actual >darkened &&
+ grep "(F" darkened > F.expect &&
+ grep "(H" darkened > H.expect &&
+ test_line_count = 2 F.expect &&
+ test_line_count = 3 H.expect
+'
+
+test_expect_success 'color by age consistently colors old code' '
+ git blame --color-by-age hello.c >actual.raw &&
+ git -c blame.coloring=highlightRecent blame hello.c >actual.raw.2 &&
+ test_cmp actual.raw actual.raw.2 &&
+ test_decode_color <actual.raw >actual &&
+ grep "<BLUE>" <actual >colored &&
+ test_line_count = 10 colored
+'
+
+test_expect_success 'blame color by age: new code is different' '
+ cat >>hello.c <<-EOF &&
+ void qfunc();
+ EOF
+ git add hello.c &&
+ GIT_AUTHOR_DATE="" git commit -m "new commit" &&
+
+ git -c color.blame.highlightRecent="yellow,1 month ago, cyan" blame --color-by-age hello.c >actual.raw &&
+ test_decode_color <actual.raw >actual &&
+
+ grep "<YELLOW>" <actual >colored &&
+ test_line_count = 10 colored &&
+
+ grep "<CYAN>" <actual >colored &&
+ test_line_count = 1 colored &&
+ grep qfunc colored
+'
+
+test_done
diff --git a/t/t9010-svn-fe.sh b/t/t9010-svn-fe.sh
index 8eaaca6..0b20b07 100755
--- a/t/t9010-svn-fe.sh
+++ b/t/t9010-svn-fe.sh
@@ -473,7 +473,7 @@ test_expect_failure 'change file mode but keep old content' '
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
git show HEAD:greeting >actual.blob &&
git show HEAD^:greeting >actual.target &&
@@ -573,7 +573,7 @@ test_expect_success 'NUL in log message, file content, and property name' '
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
{
git cat-file commit HEAD | nul_to_q &&
@@ -659,7 +659,7 @@ test_expect_success 'change file mode and reiterate content' '
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
git show HEAD:greeting >actual.blob &&
git show HEAD^:greeting >actual.target &&
@@ -792,7 +792,7 @@ test_expect_success 'property deltas supported' '
{
git rev-list HEAD |
git diff-tree --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
test_cmp expect actual
'
@@ -846,7 +846,7 @@ test_expect_success 'properties on /' '
{
git rev-list HEAD |
git diff-tree --root --always --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
test_cmp expect actual
'
@@ -931,7 +931,7 @@ test_expect_success 'deltas for typechange' '
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
test_cmp expect actual
'
@@ -1030,7 +1030,7 @@ test_expect_success 'deltas need not consume the whole preimage' '
{
git rev-list HEAD |
git diff-tree --root --stdin |
- sed "s/$_x40/OBJID/g"
+ sed "s/$OID_REGEX/OBJID/g"
} >actual &&
test_cmp expect actual &&
git show HEAD:postimage >actual.3 &&
diff --git a/t/t9300-fast-import.sh b/t/t9300-fast-import.sh
index dc79df7..9e7f962 100755
--- a/t/t9300-fast-import.sh
+++ b/t/t9300-fast-import.sh
@@ -1185,7 +1185,7 @@ test_expect_success PIPE 'N: empty directory reads as missing' '
test_cmp expect.response response &&
git rev-list read-empty |
git diff-tree -r --root --stdin |
- sed "s/$_x40/OBJNAME/g" >actual &&
+ sed "s/$OID_REGEX/OBJNAME/g" >actual &&
test_cmp expect actual
'
@@ -1271,7 +1271,7 @@ test_expect_success 'N: delete directory by copying' '
git fast-import <input &&
git rev-list N-delete |
git diff-tree -r --stdin --root --always |
- sed -e "s/$_x40/OBJID/g" >actual &&
+ sed -e "s/$OID_REGEX/OBJID/g" >actual &&
test_cmp expect actual
'
@@ -2602,7 +2602,7 @@ test_expect_success 'R: terminating "done" within commit' '
EOF
git rev-list done-ends |
git diff-tree -r --stdin --root --always |
- sed -e "s/$_x40/OBJID/g" >actual &&
+ sed -e "s/$OID_REGEX/OBJID/g" >actual &&
test_cmp expect actual
'
diff --git a/t/t9350-fast-export.sh b/t/t9350-fast-export.sh
index d5679ff..6a392e8 100755
--- a/t/t9350-fast-export.sh
+++ b/t/t9350-fast-export.sh
@@ -538,4 +538,22 @@ test_expect_success 'when using -C, do not declare copy when source of copy is a
test_cmp expected actual
'
+test_expect_success 'merge commit gets exported with --import-marks' '
+ test_create_repo merging &&
+ (
+ cd merging &&
+ test_commit initial &&
+ git checkout -b topic &&
+ test_commit on-topic &&
+ git checkout master &&
+ test_commit on-master &&
+ test_tick &&
+ git merge --no-ff -m Yeah topic &&
+
+ echo ":1 $(git rev-parse HEAD^^)" >marks &&
+ git fast-export --import-marks=marks master >out &&
+ grep Yeah out
+ )
+'
+
test_done
diff --git a/t/t9902-completion.sh b/t/t9902-completion.sh
index 1b34caa..1b6d275 100755
--- a/t/t9902-completion.sh
+++ b/t/t9902-completion.sh
@@ -84,10 +84,11 @@ test_completion ()
then
printf '%s\n' "$2" >expected
else
- sed -e 's/Z$//' >expected
+ sed -e 's/Z$//' |sort >expected
fi &&
run_completion "$1" &&
- test_cmp expected out
+ sort out >out_sorted &&
+ test_cmp expected out_sorted
}
# Test __gitcomp.
@@ -400,6 +401,46 @@ test_expect_success '__gitdir - remote as argument' '
test_cmp expected "$actual"
'
+
+test_expect_success '__git_dequote - plain unquoted word' '
+ __git_dequote unquoted-word &&
+ verbose test unquoted-word = "$dequoted_word"
+'
+
+# input: b\a\c\k\'\\\"s\l\a\s\h\es
+# expected: back'\"slashes
+test_expect_success '__git_dequote - backslash escaped' '
+ __git_dequote "b\a\c\k\\'\''\\\\\\\"s\l\a\s\h\es" &&
+ verbose test "back'\''\\\"slashes" = "$dequoted_word"
+'
+
+# input: sin'gle\' '"quo'ted
+# expected: single\ "quoted
+test_expect_success '__git_dequote - single quoted' '
+ __git_dequote "'"sin'gle\\\\' '\\\"quo'ted"'" &&
+ verbose test '\''single\ "quoted'\'' = "$dequoted_word"
+'
+
+# input: dou"ble\\" "\"\quot"ed
+# expected: double\ "\quoted
+test_expect_success '__git_dequote - double quoted' '
+ __git_dequote '\''dou"ble\\" "\"\quot"ed'\'' &&
+ verbose test '\''double\ "\quoted'\'' = "$dequoted_word"
+'
+
+# input: 'open single quote
+test_expect_success '__git_dequote - open single quote' '
+ __git_dequote "'\''open single quote" &&
+ verbose test "open single quote" = "$dequoted_word"
+'
+
+# input: "open double quote
+test_expect_success '__git_dequote - open double quote' '
+ __git_dequote "\"open double quote" &&
+ verbose test "open double quote" = "$dequoted_word"
+'
+
+
test_expect_success '__gitcomp_direct - puts everything into COMPREPLY as-is' '
sed -e "s/Z$//g" >expected <<-EOF &&
with-trailing-space Z
@@ -1168,6 +1209,124 @@ test_expect_success 'teardown after ref completion' '
git remote remove other
'
+
+test_path_completion ()
+{
+ test $# = 2 || error "bug in the test script: not 2 parameters to test_path_completion"
+
+ local cur="$1" expected="$2"
+ echo "$expected" >expected &&
+ (
+ # In the following tests calling this function we only
+ # care about how __git_complete_index_file() deals with
+ # unusual characters in path names. By requesting only
+ # untracked files we dont have to bother adding any
+ # paths to the index in those tests.
+ __git_complete_index_file --others &&
+ print_comp
+ ) &&
+ test_cmp expected out
+}
+
+test_expect_success 'setup for path completion tests' '
+ mkdir simple-dir \
+ "spaces in dir" \
+ árvíztűrő &&
+ touch simple-dir/simple-file \
+ "spaces in dir/spaces in file" \
+ "árvíztűrő/Сайн яваарай" &&
+ if test_have_prereq !MINGW &&
+ mkdir BS\\dir \
+ '$'separators\034in\035dir'' &&
+ touch BS\\dir/DQ\"file \
+ '$'separators\034in\035dir/sep\036in\037file''
+ then
+ test_set_prereq FUNNYNAMES
+ else
+ rm -rf BS\\dir '$'separators\034in\035dir''
+ fi
+'
+
+test_expect_success '__git_complete_index_file - simple' '
+ test_path_completion simple simple-dir && # Bash is supposed to
+ # add the trailing /.
+ test_path_completion simple-dir/simple simple-dir/simple-file
+'
+
+test_expect_success \
+ '__git_complete_index_file - escaped characters on cmdline' '
+ test_path_completion spac "spaces in dir" && # Bash will turn this
+ # into "spaces\ in\ dir"
+ test_path_completion "spaces\\ i" \
+ "spaces in dir" &&
+ test_path_completion "spaces\\ in\\ dir/s" \
+ "spaces in dir/spaces in file" &&
+ test_path_completion "spaces\\ in\\ dir/spaces\\ i" \
+ "spaces in dir/spaces in file"
+'
+
+test_expect_success \
+ '__git_complete_index_file - quoted characters on cmdline' '
+ # Testing with an opening but without a corresponding closing
+ # double quote is important.
+ test_path_completion \"spac "spaces in dir" &&
+ test_path_completion "\"spaces i" \
+ "spaces in dir" &&
+ test_path_completion "\"spaces in dir/s" \
+ "spaces in dir/spaces in file" &&
+ test_path_completion "\"spaces in dir/spaces i" \
+ "spaces in dir/spaces in file"
+'
+
+test_expect_success '__git_complete_index_file - UTF-8 in ls-files output' '
+ test_path_completion á árvíztűrő &&
+ test_path_completion árvíztűrő/С "árvíztűrő/Сайн яваарай"
+'
+
+test_expect_success FUNNYNAMES \
+ '__git_complete_index_file - C-style escapes in ls-files output' '
+ test_path_completion BS \
+ BS\\dir &&
+ test_path_completion BS\\\\d \
+ BS\\dir &&
+ test_path_completion BS\\\\dir/DQ \
+ BS\\dir/DQ\"file &&
+ test_path_completion BS\\\\dir/DQ\\\"f \
+ BS\\dir/DQ\"file
+'
+
+test_expect_success FUNNYNAMES \
+ '__git_complete_index_file - \nnn-escaped characters in ls-files output' '
+ test_path_completion sep '$'separators\034in\035dir'' &&
+ test_path_completion '$'separators\034i'' \
+ '$'separators\034in\035dir'' &&
+ test_path_completion '$'separators\034in\035dir/sep'' \
+ '$'separators\034in\035dir/sep\036in\037file'' &&
+ test_path_completion '$'separators\034in\035dir/sep\036i'' \
+ '$'separators\034in\035dir/sep\036in\037file''
+'
+
+test_expect_success FUNNYNAMES \
+ '__git_complete_index_file - removing repeated quoted path components' '
+ test_when_finished rm -r repeated-quoted &&
+ mkdir repeated-quoted && # A directory whose name in itself
+ # would not be quoted ...
+ >repeated-quoted/0-file &&
+ >repeated-quoted/1\"file && # ... but here the file makes the
+ # dirname quoted ...
+ >repeated-quoted/2-file &&
+ >repeated-quoted/3\"file && # ... and here, too.
+
+ # Still, we shold only list the directory name only once.
+ test_path_completion repeated repeated-quoted
+'
+
+test_expect_success 'teardown after path completion tests' '
+ rm -rf simple-dir "spaces in dir" árvíztűrő \
+ BS\\dir '$'separators\034in\035dir''
+'
+
+
test_expect_success '__git_get_config_variables' '
cat >expect <<-EOF &&
name-1
@@ -1365,6 +1524,7 @@ test_expect_success 'complete files' '
echo "expected" > .gitignore &&
echo "out" >> .gitignore &&
+ echo "out_sorted" >> .gitignore &&
git add .gitignore &&
test_completion "git commit " ".gitignore" &&
diff --git a/t/test-lib-functions.sh b/t/test-lib-functions.sh
index 7d620bf..2b2181d 100644
--- a/t/test-lib-functions.sh
+++ b/t/test-lib-functions.sh
@@ -145,12 +145,28 @@ test_pause () {
"$SHELL_PATH" <&6 >&5 2>&7
}
-# Wrap git in gdb. Adding this to a command can make it easier to
-# understand what is going on in a failing test.
+# Wrap git with a debugger. Adding this to a command can make it easier
+# to understand what is going on in a failing test.
#
-# Example: "debug git checkout master".
+# Examples:
+# debug git checkout master
+# debug --debugger=nemiver git $ARGS
+# debug -d "valgrind --tool=memcheck --track-origins=yes" git $ARGS
debug () {
- GIT_TEST_GDB=1 "$@" <&6 >&5 2>&7
+ case "$1" in
+ -d)
+ GIT_DEBUGGER="$2" &&
+ shift 2
+ ;;
+ --debugger=*)
+ GIT_DEBUGGER="${1#*=}" &&
+ shift 1
+ ;;
+ *)
+ GIT_DEBUGGER=1
+ ;;
+ esac &&
+ GIT_DEBUGGER="${GIT_DEBUGGER}" "$@" <&6 >&5 2>&7
}
# Call test_commit with the arguments
@@ -278,8 +294,20 @@ write_script () {
# The single parameter is the prerequisite tag (a simple word, in all
# capital letters by convention).
+test_unset_prereq () {
+ ! test_have_prereq "$1" ||
+ satisfied_prereq="${satisfied_prereq% $1 *} ${satisfied_prereq#* $1 }"
+}
+
test_set_prereq () {
- satisfied_prereq="$satisfied_prereq$1 "
+ case "$1" in
+ !*)
+ test_unset_prereq "${1#!}"
+ ;;
+ *)
+ satisfied_prereq="$satisfied_prereq$1 "
+ ;;
+ esac
}
satisfied_prereq=" "
lazily_testable_prereq= lazily_tested_prereq=
diff --git a/t/test-lib.sh b/t/test-lib.sh
index 483c8d6..2831570 100644
--- a/t/test-lib.sh
+++ b/t/test-lib.sh
@@ -184,6 +184,8 @@ _x40="$_x35$_x05"
# Zero SHA-1
_z40=0000000000000000000000000000000000000000
+OID_REGEX="$_x40"
+ZERO_OID=$_z40
EMPTY_TREE=4b825dc642cb6eb9a060e54bf8d69288fbee4904
EMPTY_BLOB=e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
@@ -195,7 +197,7 @@ LF='
# when case-folding filenames
u200c=$(printf '\342\200\214')
-export _x05 _x35 _x40 _z40 LF u200c EMPTY_TREE EMPTY_BLOB
+export _x05 _x35 _x40 _z40 LF u200c EMPTY_TREE EMPTY_BLOB ZERO_OID OID_REGEX
# Each test should start with something like this, after copyright notices:
#
@@ -1106,12 +1108,7 @@ test_lazy_prereq UTF8_NFD_TO_NFC '
auml=$(printf "\303\244")
aumlcdiar=$(printf "\141\314\210")
>"$auml" &&
- case "$(echo *)" in
- "$aumlcdiar")
- true ;;
- *)
- false ;;
- esac
+ test -f "$aumlcdiar"
'
test_lazy_prereq AUTOIDENT '
@@ -1208,3 +1205,14 @@ test_lazy_prereq LONG_IS_64BIT '
test_lazy_prereq TIME_IS_64BIT 'test-tool date is64bit'
test_lazy_prereq TIME_T_IS_64BIT 'test-tool date time_t-is64bit'
+
+test_lazy_prereq CURL '
+ curl --version
+'
+
+# SHA1 is a test if the hash algorithm in use is SHA-1. This is both for tests
+# which will not work with other hash algorithms and tests that work but don't
+# test anything meaningful (e.g. special values which cause short collisions).
+test_lazy_prereq SHA1 '
+ test $(git hash-object /dev/null) = e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
+'
diff --git a/tag.c b/tag.c
index 86b1dcb..3d37c1b 100644
--- a/tag.c
+++ b/tag.c
@@ -41,7 +41,7 @@ int gpg_verify_tag(const struct object_id *oid, const char *name_to_report,
unsigned long size;
int ret;
- type = oid_object_info(oid, NULL);
+ type = oid_object_info(the_repository, oid, NULL);
if (type != OBJ_TAG)
return error("%s: cannot verify a non-tag object of type %s.",
name_to_report ?
diff --git a/templates/hooks--pre-commit.sample b/templates/hooks--pre-commit.sample
index 68d62d5..6a75641 100755
--- a/templates/hooks--pre-commit.sample
+++ b/templates/hooks--pre-commit.sample
@@ -12,7 +12,7 @@ then
against=HEAD
else
# Initial commit: diff against an empty tree object
- against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
+ against=$(git hash-object -t tree /dev/null)
fi
# If you want to allow non-ASCII filenames set this variable to true.
diff --git a/tmp-objdir.c b/tmp-objdir.c
index fea3f55..91c0056 100644
--- a/tmp-objdir.c
+++ b/tmp-objdir.c
@@ -127,7 +127,7 @@ struct tmp_objdir *tmp_objdir_create(void)
struct tmp_objdir *t;
if (the_tmp_objdir)
- die("BUG: only one tmp_objdir can be used at a time");
+ BUG("only one tmp_objdir can be used at a time");
t = xmalloc(sizeof(*t));
strbuf_init(&t->path, 0);
diff --git a/trace.c b/trace.c
index 7f3b08e..fc623e9 100644
--- a/trace.c
+++ b/trace.c
@@ -26,6 +26,7 @@
struct trace_key trace_default_key = { "GIT_TRACE", 0, 0, 0 };
struct trace_key trace_perf_key = TRACE_KEY_INIT(PERFORMANCE);
+struct trace_key trace_setup_key = TRACE_KEY_INIT(SETUP);
/* Get a trace file descriptor from "key" env variable. */
static int get_trace_fd(struct trace_key *key)
@@ -300,11 +301,10 @@ static const char *quote_crnl(const char *path)
/* FIXME: move prefix to startup_info struct and get rid of this arg */
void trace_repo_setup(const char *prefix)
{
- static struct trace_key key = TRACE_KEY_INIT(SETUP);
const char *git_work_tree;
char *cwd;
- if (!trace_want(&key))
+ if (!trace_want(&trace_setup_key))
return;
cwd = xgetcwd();
@@ -315,11 +315,11 @@ void trace_repo_setup(const char *prefix)
if (!prefix)
prefix = "(null)";
- trace_printf_key(&key, "setup: git_dir: %s\n", quote_crnl(get_git_dir()));
- trace_printf_key(&key, "setup: git_common_dir: %s\n", quote_crnl(get_git_common_dir()));
- trace_printf_key(&key, "setup: worktree: %s\n", quote_crnl(git_work_tree));
- trace_printf_key(&key, "setup: cwd: %s\n", quote_crnl(cwd));
- trace_printf_key(&key, "setup: prefix: %s\n", quote_crnl(prefix));
+ trace_printf_key(&trace_setup_key, "setup: git_dir: %s\n", quote_crnl(get_git_dir()));
+ trace_printf_key(&trace_setup_key, "setup: git_common_dir: %s\n", quote_crnl(get_git_common_dir()));
+ trace_printf_key(&trace_setup_key, "setup: worktree: %s\n", quote_crnl(git_work_tree));
+ trace_printf_key(&trace_setup_key, "setup: cwd: %s\n", quote_crnl(cwd));
+ trace_printf_key(&trace_setup_key, "setup: prefix: %s\n", quote_crnl(prefix));
free(cwd);
}
diff --git a/trace.h b/trace.h
index 88055ab..2b6a1bc 100644
--- a/trace.h
+++ b/trace.h
@@ -15,6 +15,7 @@ extern struct trace_key trace_default_key;
#define TRACE_KEY_INIT(name) { "GIT_TRACE_" #name, 0, 0, 0 }
extern struct trace_key trace_perf_key;
+extern struct trace_key trace_setup_key;
extern void trace_repo_setup(const char *prefix);
extern int trace_want(struct trace_key *key);
diff --git a/trailer.c b/trailer.c
index c508c9b..4e30946 100644
--- a/trailer.c
+++ b/trailer.c
@@ -298,7 +298,7 @@ static void apply_arg_if_exists(struct trailer_item *in_tok,
free_arg_item(arg_tok);
break;
default:
- die("BUG: trailer.c: unhandled value %d",
+ BUG("trailer.c: unhandled value %d",
arg_tok->conf.if_exists);
}
}
@@ -323,7 +323,7 @@ static void apply_arg_if_missing(struct list_head *head,
list_add(&to_add->list, head);
break;
default:
- die("BUG: trailer.c: unhandled value %d",
+ BUG("trailer.c: unhandled value %d",
arg_tok->conf.if_missing);
}
}
@@ -557,7 +557,7 @@ static int git_trailer_config(const char *conf_key, const char *value, void *cb)
warning(_("unknown value '%s' for key '%s'"), value, conf_key);
break;
default:
- die("BUG: trailer.c: unhandled type %d", type);
+ BUG("trailer.c: unhandled type %d", type);
}
return 0;
}
diff --git a/transport-helper.c b/transport-helper.c
index 3f380d8..1f8ff7e 100644
--- a/transport-helper.c
+++ b/transport-helper.c
@@ -11,7 +11,9 @@
#include "sigchain.h"
#include "argv-array.h"
#include "refs.h"
+#include "refspec.h"
#include "transport-internal.h"
+#include "protocol.h"
static int debug;
@@ -26,6 +28,7 @@ struct helper_data {
option : 1,
push : 1,
connect : 1,
+ stateless_connect : 1,
signed_tags : 1,
check_connectivity : 1,
no_disconnect_req : 1,
@@ -33,8 +36,7 @@ struct helper_data {
char *export_marks;
char *import_marks;
/* These go from remote name (as in "list") to private name */
- struct refspec *refspecs;
- int refspec_nr;
+ struct refspec rs;
/* Transport options for fetch-pack/send-pack (should one of
* those be invoked).
*/
@@ -49,7 +51,7 @@ static void sendline(struct helper_data *helper, struct strbuf *buffer)
die_errno("Full write to remote helper failed");
}
-static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
+static int recvline_fh(FILE *helper, struct strbuf *buffer)
{
strbuf_reset(buffer);
if (debug)
@@ -67,7 +69,7 @@ static int recvline_fh(FILE *helper, struct strbuf *buffer, const char *name)
static int recvline(struct helper_data *helper, struct strbuf *buffer)
{
- return recvline_fh(helper->out, buffer, helper->name);
+ return recvline_fh(helper->out, buffer);
}
static void write_constant(int fd, const char *str)
@@ -104,9 +106,6 @@ static struct child_process *get_helper(struct transport *transport)
struct helper_data *data = transport->data;
struct strbuf buf = STRBUF_INIT;
struct child_process *helper;
- const char **refspecs = NULL;
- int refspec_nr = 0;
- int refspec_alloc = 0;
int duped;
int code;
@@ -136,6 +135,7 @@ static struct child_process *get_helper(struct transport *transport)
data->helper = helper;
data->no_disconnect_req = 0;
+ refspec_init(&data->rs, REFSPEC_FETCH);
/*
* Open the output as FILE* so strbuf_getline_*() family of
@@ -181,13 +181,12 @@ static struct child_process *get_helper(struct transport *transport)
data->export = 1;
else if (!strcmp(capname, "check-connectivity"))
data->check_connectivity = 1;
- else if (!data->refspecs && skip_prefix(capname, "refspec ", &arg)) {
- ALLOC_GROW(refspecs,
- refspec_nr + 1,
- refspec_alloc);
- refspecs[refspec_nr++] = xstrdup(arg);
+ else if (skip_prefix(capname, "refspec ", &arg)) {
+ refspec_append(&data->rs, arg);
} else if (!strcmp(capname, "connect")) {
data->connect = 1;
+ } else if (!strcmp(capname, "stateless-connect")) {
+ data->stateless_connect = 1;
} else if (!strcmp(capname, "signed-tags")) {
data->signed_tags = 1;
} else if (skip_prefix(capname, "export-marks ", &arg)) {
@@ -202,14 +201,7 @@ static struct child_process *get_helper(struct transport *transport)
capname);
}
}
- if (refspecs) {
- int i;
- data->refspec_nr = refspec_nr;
- data->refspecs = parse_fetch_refspec(refspec_nr, refspecs);
- for (i = 0; i < refspec_nr; i++)
- free((char *)refspecs[i]);
- free(refspecs);
- } else if (data->import || data->bidi_import || data->export) {
+ if (!data->rs.nr && (data->import || data->bidi_import || data->export)) {
warning("This remote helper should implement refspec capability.");
}
strbuf_release(&buf);
@@ -373,8 +365,7 @@ static int release_helper(struct transport *transport)
{
int res = 0;
struct helper_data *data = transport->data;
- free_refspec(data->refspec_nr, data->refspecs);
- data->refspecs = NULL;
+ refspec_clear(&data->rs);
res = disconnect_helper(transport);
free(transport->data);
return res;
@@ -531,8 +522,8 @@ static int fetch_with_import(struct transport *transport,
if (posn->status & REF_STATUS_UPTODATE)
continue;
name = posn->symref ? posn->symref : posn->name;
- if (data->refspecs)
- private = apply_refspecs(data->refspecs, data->refspec_nr, name);
+ if (data->rs.nr)
+ private = apply_refspecs(&data->rs, name);
else
private = xstrdup(name);
if (private) {
@@ -545,14 +536,13 @@ static int fetch_with_import(struct transport *transport,
return 0;
}
-static int process_connect_service(struct transport *transport,
- const char *name, const char *exec)
+static int run_connect(struct transport *transport, struct strbuf *cmdbuf)
{
struct helper_data *data = transport->data;
- struct strbuf cmdbuf = STRBUF_INIT;
- struct child_process *helper;
- int r, duped, ret = 0;
+ int ret = 0;
+ int duped;
FILE *input;
+ struct child_process *helper;
helper = get_helper(transport);
@@ -568,44 +558,61 @@ static int process_connect_service(struct transport *transport,
input = xfdopen(duped, "r");
setvbuf(input, NULL, _IONBF, 0);
+ sendline(data, cmdbuf);
+ if (recvline_fh(input, cmdbuf))
+ exit(128);
+
+ if (!strcmp(cmdbuf->buf, "")) {
+ data->no_disconnect_req = 1;
+ if (debug)
+ fprintf(stderr, "Debug: Smart transport connection "
+ "ready.\n");
+ ret = 1;
+ } else if (!strcmp(cmdbuf->buf, "fallback")) {
+ if (debug)
+ fprintf(stderr, "Debug: Falling back to dumb "
+ "transport.\n");
+ } else {
+ die("Unknown response to connect: %s",
+ cmdbuf->buf);
+ }
+
+ fclose(input);
+ return ret;
+}
+
+static int process_connect_service(struct transport *transport,
+ const char *name, const char *exec)
+{
+ struct helper_data *data = transport->data;
+ struct strbuf cmdbuf = STRBUF_INIT;
+ int ret = 0;
+
/*
* Handle --upload-pack and friends. This is fire and forget...
* just warn if it fails.
*/
if (strcmp(name, exec)) {
- r = set_helper_option(transport, "servpath", exec);
+ int r = set_helper_option(transport, "servpath", exec);
if (r > 0)
warning("Setting remote service path not supported by protocol.");
else if (r < 0)
warning("Invalid remote service path.");
}
- if (data->connect)
+ if (data->connect) {
strbuf_addf(&cmdbuf, "connect %s\n", name);
- else
- goto exit;
-
- sendline(data, &cmdbuf);
- if (recvline_fh(input, &cmdbuf, name))
- exit(128);
-
- if (!strcmp(cmdbuf.buf, "")) {
- data->no_disconnect_req = 1;
- if (debug)
- fprintf(stderr, "Debug: Smart transport connection "
- "ready.\n");
- ret = 1;
- } else if (!strcmp(cmdbuf.buf, "fallback")) {
- if (debug)
- fprintf(stderr, "Debug: Falling back to dumb "
- "transport.\n");
- } else
- die("Unknown response to connect: %s",
- cmdbuf.buf);
+ ret = run_connect(transport, &cmdbuf);
+ } else if (data->stateless_connect &&
+ (get_protocol_version_config() == protocol_v2) &&
+ !strcmp("git-upload-pack", name)) {
+ strbuf_addf(&cmdbuf, "stateless-connect %s\n", name);
+ ret = run_connect(transport, &cmdbuf);
+ if (ret)
+ transport->stateless_rpc = 1;
+ }
-exit:
strbuf_release(&cmdbuf);
- fclose(input);
return ret;
}
@@ -794,11 +801,11 @@ static int push_update_refs_status(struct helper_data *data,
if (push_update_ref_status(&buf, &ref, remote_refs))
continue;
- if (flags & TRANSPORT_PUSH_DRY_RUN || !data->refspecs || data->no_private_update)
+ if (flags & TRANSPORT_PUSH_DRY_RUN || !data->rs.nr || data->no_private_update)
continue;
/* propagate back the update to the remote namespace */
- private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
+ private = apply_refspecs(&data->rs, ref->name);
if (!private)
continue;
update_ref("update by helper", private, &ref->new_oid, NULL,
@@ -918,7 +925,7 @@ static int push_refs_with_export(struct transport *transport,
struct string_list revlist_args = STRING_LIST_INIT_DUP;
struct strbuf buf = STRBUF_INIT;
- if (!data->refspecs)
+ if (!data->rs.nr)
die("remote-helper doesn't support push; refspec needed");
set_common_push_options(transport, data->name, flags);
@@ -935,7 +942,7 @@ static int push_refs_with_export(struct transport *transport,
char *private;
struct object_id oid;
- private = apply_refspecs(data->refspecs, data->refspec_nr, ref->name);
+ private = apply_refspecs(&data->rs, ref->name);
if (private && !get_oid(private, &oid)) {
strbuf_addf(&buf, "^%s", private);
string_list_append_nodup(&revlist_args,
@@ -1031,7 +1038,8 @@ static int has_attribute(const char *attrs, const char *attr) {
}
}
-static struct ref *get_refs_list(struct transport *transport, int for_push)
+static struct ref *get_refs_list(struct transport *transport, int for_push,
+ const struct argv_array *ref_prefixes)
{
struct helper_data *data = transport->data;
struct child_process *helper;
@@ -1044,7 +1052,7 @@ static struct ref *get_refs_list(struct transport *transport, int for_push)
if (process_connect(transport, for_push)) {
do_take_over(transport);
- return transport->vtable->get_refs_list(transport, for_push);
+ return transport->vtable->get_refs_list(transport, for_push, ref_prefixes);
}
if (data->push && for_push)
diff --git a/transport-internal.h b/transport-internal.h
index 3c1a29d..1cde625 100644
--- a/transport-internal.h
+++ b/transport-internal.h
@@ -3,6 +3,7 @@
struct ref;
struct transport;
+struct argv_array;
struct transport_vtable {
/**
@@ -17,11 +18,19 @@ struct transport_vtable {
* the transport to try to share connections, for_push is a
* hint as to whether the ultimate operation is a push or a fetch.
*
+ * If communicating using protocol v2 a list of prefixes can be
+ * provided to be sent to the server to enable it to limit the ref
+ * advertisement. Since ref filtering is done on the server's end, and
+ * only when using protocol v2, this list will be ignored when not
+ * using protocol v2 meaning this function can return refs which don't
+ * match the provided ref_prefixes.
+ *
* If the transport is able to determine the remote hash for
* the ref without a huge amount of effort, it should store it
* in the ref's old_sha1 field; otherwise it should be all 0.
**/
- struct ref *(*get_refs_list)(struct transport *transport, int for_push);
+ struct ref *(*get_refs_list)(struct transport *transport, int for_push,
+ const struct argv_array *ref_prefixes);
/**
* Fetch the objects for the given refs. Note that this gets
diff --git a/transport.c b/transport.c
index 94eccf2..a32da30 100644
--- a/transport.c
+++ b/transport.c
@@ -11,6 +11,7 @@
#include "bundle.h"
#include "dir.h"
#include "refs.h"
+#include "refspec.h"
#include "branch.h"
#include "url.h"
#include "submodule.h"
@@ -18,7 +19,58 @@
#include "sha1-array.h"
#include "sigchain.h"
#include "transport-internal.h"
+#include "protocol.h"
#include "object-store.h"
+#include "color.h"
+
+static int transport_use_color = -1;
+static char transport_colors[][COLOR_MAXLEN] = {
+ GIT_COLOR_RESET,
+ GIT_COLOR_RED /* REJECTED */
+};
+
+enum color_transport {
+ TRANSPORT_COLOR_RESET = 0,
+ TRANSPORT_COLOR_REJECTED = 1
+};
+
+static int transport_color_config(void)
+{
+ const char *keys[] = {
+ "color.transport.reset",
+ "color.transport.rejected"
+ }, *key = "color.transport";
+ char *value;
+ int i;
+ static int initialized;
+
+ if (initialized)
+ return 0;
+ initialized = 1;
+
+ if (!git_config_get_string(key, &value))
+ transport_use_color = git_config_colorbool(key, value);
+
+ if (!want_color_stderr(transport_use_color))
+ return 0;
+
+ for (i = 0; i < ARRAY_SIZE(keys); i++)
+ if (!git_config_get_string(keys[i], &value)) {
+ if (!value)
+ return config_error_nonbool(keys[i]);
+ if (color_parse(value, transport_colors[i]) < 0)
+ return -1;
+ }
+
+ return 0;
+}
+
+static const char *transport_get_color(enum color_transport ix)
+{
+ if (want_color_stderr(transport_use_color))
+ return transport_colors[ix];
+ return "";
+}
static void set_upstreams(struct transport *transport, struct ref *refs,
int pretend)
@@ -72,7 +124,9 @@ struct bundle_transport_data {
struct bundle_header header;
};
-static struct ref *get_refs_from_bundle(struct transport *transport, int for_push)
+static struct ref *get_refs_from_bundle(struct transport *transport,
+ int for_push,
+ const struct argv_array *ref_prefixes)
{
struct bundle_transport_data *data = transport->data;
struct ref *result = NULL;
@@ -118,6 +172,7 @@ struct git_transport_data {
struct child_process *conn;
int fd[2];
unsigned got_remote_heads : 1;
+ enum protocol_version version;
struct oid_array extra_have;
struct oid_array shallow;
};
@@ -197,16 +252,35 @@ static int connect_setup(struct transport *transport, int for_push)
return 0;
}
-static struct ref *get_refs_via_connect(struct transport *transport, int for_push)
+static struct ref *get_refs_via_connect(struct transport *transport, int for_push,
+ const struct argv_array *ref_prefixes)
{
struct git_transport_data *data = transport->data;
- struct ref *refs;
+ struct ref *refs = NULL;
+ struct packet_reader reader;
connect_setup(transport, for_push);
- get_remote_heads(data->fd[0], NULL, 0, &refs,
- for_push ? REF_NORMAL : 0,
- &data->extra_have,
- &data->shallow);
+
+ packet_reader_init(&reader, data->fd[0], NULL, 0,
+ PACKET_READ_CHOMP_NEWLINE |
+ PACKET_READ_GENTLE_ON_EOF);
+
+ data->version = discover_version(&reader);
+ switch (data->version) {
+ case protocol_v2:
+ get_remote_refs(data->fd[1], &reader, &refs, for_push,
+ ref_prefixes, transport->server_options);
+ break;
+ case protocol_v1:
+ case protocol_v0:
+ get_remote_heads(&reader, &refs,
+ for_push ? REF_NORMAL : 0,
+ &data->extra_have,
+ &data->shallow);
+ break;
+ case protocol_unknown_version:
+ BUG("unknown protocol version");
+ }
data->got_remote_heads = 1;
return refs;
@@ -217,7 +291,7 @@ static int fetch_refs_via_pack(struct transport *transport,
{
int ret = 0;
struct git_transport_data *data = transport->data;
- struct ref *refs;
+ struct ref *refs = NULL;
char *dest = xstrdup(transport->url);
struct fetch_pack_args args;
struct ref *refs_tmp = NULL;
@@ -242,18 +316,30 @@ static int fetch_refs_via_pack(struct transport *transport,
args.from_promisor = data->options.from_promisor;
args.no_dependents = data->options.no_dependents;
args.filter_options = data->options.filter_options;
-
- if (!data->got_remote_heads) {
- connect_setup(transport, 0);
- get_remote_heads(data->fd[0], NULL, 0, &refs_tmp, 0,
- NULL, &data->shallow);
- data->got_remote_heads = 1;
+ args.stateless_rpc = transport->stateless_rpc;
+ args.server_options = transport->server_options;
+
+ if (!data->got_remote_heads)
+ refs_tmp = get_refs_via_connect(transport, 0, NULL);
+
+ switch (data->version) {
+ case protocol_v2:
+ refs = fetch_pack(&args, data->fd, data->conn,
+ refs_tmp ? refs_tmp : transport->remote_refs,
+ dest, to_fetch, nr_heads, &data->shallow,
+ &transport->pack_lockfile, data->version);
+ break;
+ case protocol_v1:
+ case protocol_v0:
+ refs = fetch_pack(&args, data->fd, data->conn,
+ refs_tmp ? refs_tmp : transport->remote_refs,
+ dest, to_fetch, nr_heads, &data->shallow,
+ &transport->pack_lockfile, data->version);
+ break;
+ case protocol_unknown_version:
+ BUG("unknown protocol version");
}
- refs = fetch_pack(&args, data->fd, data->conn,
- refs_tmp ? refs_tmp : transport->remote_refs,
- dest, to_fetch, nr_heads, &data->shallow,
- &transport->pack_lockfile);
close(data->fd[0]);
close(data->fd[1]);
if (finish_connect(data->conn))
@@ -305,7 +391,7 @@ int transport_refs_pushed(struct ref *ref)
void transport_update_tracking_ref(struct remote *remote, struct ref *ref, int verbose)
{
- struct refspec rs;
+ struct refspec_item rs;
if (ref->status != REF_STATUS_OK && ref->status != REF_STATUS_UPTODATE)
return;
@@ -339,7 +425,13 @@ static void print_ref_status(char flag, const char *summary,
else
fprintf(stdout, "%s\n", summary);
} else {
- fprintf(stderr, " %c %-*s ", flag, summary_width, summary);
+ const char *red = "", *reset = "";
+ if (push_had_errors(to)) {
+ red = transport_get_color(TRANSPORT_COLOR_REJECTED);
+ reset = transport_get_color(TRANSPORT_COLOR_RESET);
+ }
+ fprintf(stderr, " %s%c %-*s%s ", red, flag, summary_width,
+ summary, reset);
if (from)
fprintf(stderr, "%s -> %s", prettify_refname(from->name), prettify_refname(to->name));
else
@@ -488,6 +580,9 @@ void transport_print_push_status(const char *dest, struct ref *refs,
char *head;
int summary_width = transport_summary_width(refs);
+ if (transport_color_config() < 0)
+ warning(_("could not parse transport.color.* config"));
+
head = resolve_refdup("HEAD", RESOLVE_REF_READING, NULL, NULL);
if (verbose) {
@@ -525,43 +620,17 @@ void transport_print_push_status(const char *dest, struct ref *refs,
free(head);
}
-void transport_verify_remote_names(int nr_heads, const char **heads)
-{
- int i;
-
- for (i = 0; i < nr_heads; i++) {
- const char *local = heads[i];
- const char *remote = strrchr(heads[i], ':');
-
- if (*local == '+')
- local++;
-
- /* A matching refspec is okay. */
- if (remote == local && remote[1] == '\0')
- continue;
-
- remote = remote ? (remote + 1) : local;
- if (check_refname_format(remote,
- REFNAME_ALLOW_ONELEVEL|REFNAME_REFSPEC_PATTERN))
- die("remote part of refspec is not a valid name in %s",
- heads[i]);
- }
-}
-
static int git_transport_push(struct transport *transport, struct ref *remote_refs, int flags)
{
struct git_transport_data *data = transport->data;
struct send_pack_args args;
- int ret;
+ int ret = 0;
- if (!data->got_remote_heads) {
- struct ref *tmp_refs;
- connect_setup(transport, 1);
+ if (transport_color_config() < 0)
+ return -1;
- get_remote_heads(data->fd[0], NULL, 0, &tmp_refs, REF_NORMAL,
- NULL, &data->shallow);
- data->got_remote_heads = 1;
- }
+ if (!data->got_remote_heads)
+ get_refs_via_connect(transport, 1, NULL);
memset(&args, 0, sizeof(args));
args.send_mirror = !!(flags & TRANSPORT_PUSH_MIRROR);
@@ -583,8 +652,18 @@ static int git_transport_push(struct transport *transport, struct ref *remote_re
else
args.push_cert = SEND_PACK_PUSH_CERT_NEVER;
- ret = send_pack(&args, data->fd, data->conn, remote_refs,
- &data->extra_have);
+ switch (data->version) {
+ case protocol_v2:
+ die("support for protocol v2 not implemented yet");
+ break;
+ case protocol_v1:
+ case protocol_v0:
+ ret = send_pack(&args, data->fd, data->conn, remote_refs,
+ &data->extra_have);
+ break;
+ case protocol_unknown_version:
+ BUG("unknown protocol version");
+ }
close(data->fd[1]);
close(data->fd[0]);
@@ -636,7 +715,7 @@ void transport_take_over(struct transport *transport,
struct git_transport_data *data;
if (!transport->smart_options)
- die("BUG: taking over transport requires non-NULL "
+ BUG("taking over transport requires non-NULL "
"smart_options field.");
data = xcalloc(1, sizeof(*data));
@@ -761,7 +840,7 @@ int is_transport_allowed(const char *type, int from_user)
return from_user;
}
- die("BUG: invalid protocol_allow_config type");
+ BUG("invalid protocol_allow_config type");
}
void transport_check_allowed(const char *type)
@@ -992,11 +1071,13 @@ static int run_pre_push_hook(struct transport *transport,
}
int transport_push(struct transport *transport,
- int refspec_nr, const char **refspec, int flags,
+ struct refspec *rs, int flags,
unsigned int *reject_reasons)
{
*reject_reasons = 0;
- transport_verify_remote_names(refspec_nr, refspec);
+
+ if (transport_color_config() < 0)
+ return -1;
if (transport->vtable->push_refs) {
struct ref *remote_refs;
@@ -1007,11 +1088,17 @@ int transport_push(struct transport *transport,
int porcelain = flags & TRANSPORT_PUSH_PORCELAIN;
int pretend = flags & TRANSPORT_PUSH_DRY_RUN;
int push_ret, ret, err;
+ struct argv_array ref_prefixes = ARGV_ARRAY_INIT;
- if (check_push_refs(local_refs, refspec_nr, refspec) < 0)
+ if (check_push_refs(local_refs, rs) < 0)
return -1;
- remote_refs = transport->vtable->get_refs_list(transport, 1);
+ refspec_ref_prefixes(rs, &ref_prefixes);
+
+ remote_refs = transport->vtable->get_refs_list(transport, 1,
+ &ref_prefixes);
+
+ argv_array_clear(&ref_prefixes);
if (flags & TRANSPORT_PUSH_ALL)
match_flags |= MATCH_REFS_ALL;
@@ -1022,10 +1109,8 @@ int transport_push(struct transport *transport,
if (flags & TRANSPORT_PUSH_FOLLOW_TAGS)
match_flags |= MATCH_REFS_FOLLOW_TAGS;
- if (match_push_refs(local_refs, &remote_refs,
- refspec_nr, refspec, match_flags)) {
+ if (match_push_refs(local_refs, &remote_refs, rs, match_flags))
return -1;
- }
if (transport->smart_options &&
transport->smart_options->cas &&
@@ -1054,7 +1139,7 @@ int transport_push(struct transport *transport,
if (!push_unpushed_submodules(&commits,
transport->remote,
- refspec, refspec_nr,
+ rs,
transport->push_options,
pretend)) {
oid_array_clear(&commits);
@@ -1117,10 +1202,13 @@ int transport_push(struct transport *transport,
return 1;
}
-const struct ref *transport_get_remote_refs(struct transport *transport)
+const struct ref *transport_get_remote_refs(struct transport *transport,
+ const struct argv_array *ref_prefixes)
{
if (!transport->got_remote_refs) {
- transport->remote_refs = transport->vtable->get_refs_list(transport, 0);
+ transport->remote_refs =
+ transport->vtable->get_refs_list(transport, 0,
+ ref_prefixes);
transport->got_remote_refs = 1;
}
diff --git a/transport.h b/transport.h
index 3c68d73..7792b08 100644
--- a/transport.h
+++ b/transport.h
@@ -60,11 +60,23 @@ struct transport {
unsigned cloning : 1;
/*
+ * Indicates that the transport is connected via a half-duplex
+ * connection and should operate in stateless-rpc mode.
+ */
+ unsigned stateless_rpc : 1;
+
+ /*
* These strings will be passed to the {pre, post}-receive hook,
* on the remote side, if both sides support the push options capability.
*/
const struct string_list *push_options;
+ /*
+ * These strings will be passed to the remote side on each command
+ * request, if both sides support the server-option capability.
+ */
+ const struct string_list *server_options;
+
char *pack_lockfile;
signed verbose : 3;
/**
@@ -191,10 +203,20 @@ void transport_set_verbosity(struct transport *transport, int verbosity,
#define REJECT_NEEDS_FORCE 0x10
int transport_push(struct transport *connection,
- int refspec_nr, const char **refspec, int flags,
+ struct refspec *rs, int flags,
unsigned int * reject_reasons);
-const struct ref *transport_get_remote_refs(struct transport *transport);
+/*
+ * Retrieve refs from a remote.
+ *
+ * Optionally a list of ref prefixes can be provided which can be sent to the
+ * server (when communicating using protocol v2) to enable it to limit the ref
+ * advertisement. Since ref filtering is done on the server's end (and only
+ * when using protocol v2), this can return refs which don't match the provided
+ * ref_prefixes.
+ */
+const struct ref *transport_get_remote_refs(struct transport *transport,
+ const struct argv_array *ref_prefixes);
int transport_fetch_refs(struct transport *transport, struct ref *refs);
void transport_unlock_pack(struct transport *transport);
@@ -211,8 +233,6 @@ int transport_helper_init(struct transport *transport, const char *name);
int bidirectional_transfer_loop(int input, int output);
/* common methods used by transport.c and builtin/send-pack.c */
-void transport_verify_remote_names(int nr_heads, const char **heads);
-
void transport_update_tracking_ref(struct remote *remote, struct ref *ref, int verbose);
int transport_refs_pushed(struct ref *ref);
diff --git a/tree-walk.c b/tree-walk.c
index e11b306..8f50908 100644
--- a/tree-walk.c
+++ b/tree-walk.c
@@ -105,7 +105,7 @@ static void entry_extract(struct tree_desc *t, struct name_entry *a)
static int update_tree_entry_internal(struct tree_desc *desc, struct strbuf *err)
{
const void *buf = desc->buffer;
- const unsigned char *end = desc->entry.oid->hash + 20;
+ const unsigned char *end = desc->entry.oid->hash + the_hash_algo->rawsz;
unsigned long size = desc->size;
unsigned long len = end - (const unsigned char *)buf;
@@ -488,7 +488,7 @@ int traverse_trees(int n, struct tree_desc *t, struct traverse_info *info)
struct dir_state {
void *tree;
unsigned long size;
- unsigned char sha1[20];
+ struct object_id oid;
};
static int find_tree_entry(struct tree_desc *t, const char *name, struct object_id *result, unsigned *mode)
@@ -576,7 +576,7 @@ int get_tree_entry(const struct object_id *tree_oid, const char *name, struct ob
* See the code for enum follow_symlink_result for a description of
* the return values.
*/
-enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_sha1, const char *name, unsigned char *result, struct strbuf *result_path, unsigned *mode)
+enum follow_symlinks_result get_tree_entry_follow_symlinks(struct object_id *tree_oid, const char *name, struct object_id *result, struct strbuf *result_path, unsigned *mode)
{
int retval = MISSING_OBJECT;
struct dir_state *parents = NULL;
@@ -589,7 +589,7 @@ enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_s
init_tree_desc(&t, NULL, 0UL);
strbuf_addstr(&namebuf, name);
- hashcpy(current_tree_oid.hash, tree_sha1);
+ oidcpy(&current_tree_oid, tree_oid);
while (1) {
int find_result;
@@ -609,11 +609,11 @@ enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_s
ALLOC_GROW(parents, parents_nr + 1, parents_alloc);
parents[parents_nr].tree = tree;
parents[parents_nr].size = size;
- hashcpy(parents[parents_nr].sha1, root.hash);
+ oidcpy(&parents[parents_nr].oid, &root);
parents_nr++;
if (namebuf.buf[0] == '\0') {
- hashcpy(result, root.hash);
+ oidcpy(result, &root);
retval = FOUND;
goto done;
}
@@ -663,7 +663,7 @@ enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_s
/* We could end up here via a symlink to dir/.. */
if (namebuf.buf[0] == '\0') {
- hashcpy(result, parents[parents_nr - 1].sha1);
+ oidcpy(result, &parents[parents_nr - 1].oid);
retval = FOUND;
goto done;
}
@@ -677,7 +677,7 @@ enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_s
if (S_ISDIR(*mode)) {
if (!remainder) {
- hashcpy(result, current_tree_oid.hash);
+ oidcpy(result, &current_tree_oid);
retval = FOUND;
goto done;
}
@@ -687,7 +687,7 @@ enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_s
1 + first_slash - namebuf.buf);
} else if (S_ISREG(*mode)) {
if (!remainder) {
- hashcpy(result, current_tree_oid.hash);
+ oidcpy(result, &current_tree_oid);
retval = FOUND;
} else {
retval = NOT_DIR;
diff --git a/tree-walk.h b/tree-walk.h
index 4617dee..805f58f 100644
--- a/tree-walk.h
+++ b/tree-walk.h
@@ -64,7 +64,7 @@ enum follow_symlinks_result {
*/
};
-enum follow_symlinks_result get_tree_entry_follow_symlinks(unsigned char *tree_sha1, const char *name, unsigned char *result, struct strbuf *result_path, unsigned *mode);
+enum follow_symlinks_result get_tree_entry_follow_symlinks(struct object_id *tree_oid, const char *name, struct object_id *result, struct strbuf *result_path, unsigned *mode);
struct traverse_info {
const char *traverse_path;
diff --git a/tree.c b/tree.c
index 1c68ea5..244eb5e 100644
--- a/tree.c
+++ b/tree.c
@@ -109,7 +109,7 @@ static int read_tree_1(struct tree *tree, struct strbuf *base,
oid_to_hex(entry.oid),
base->buf, entry.path);
- oidcpy(&oid, &commit->tree->object.oid);
+ oidcpy(&oid, get_commit_tree_oid(commit));
}
else
continue;
@@ -248,7 +248,7 @@ struct tree *parse_tree_indirect(const struct object_id *oid)
if (obj->type == OBJ_TREE)
return (struct tree *) obj;
else if (obj->type == OBJ_COMMIT)
- obj = &(((struct commit *) obj)->tree->object);
+ obj = &(get_commit_tree(((struct commit *)obj))->object);
else if (obj->type == OBJ_TAG)
obj = ((struct tag *) obj)->tagged;
else
diff --git a/unicode_width.h b/unicode-width.h
index 6dee2c7..6dee2c7 100644
--- a/unicode_width.h
+++ b/unicode-width.h
diff --git a/unpack-trees.c b/unpack-trees.c
index 73a6dc1..3a85a02 100644
--- a/unpack-trees.c
+++ b/unpack-trees.c
@@ -301,7 +301,7 @@ static void load_gitmodules_file(struct index_state *index,
if (!state && ce->ce_flags & CE_WT_REMOVE) {
repo_read_gitmodules(the_repository);
} else if (state && (ce->ce_flags & CE_UPDATE)) {
- submodule_free();
+ submodule_free(the_repository);
checkout_entry(ce, state, NULL);
repo_read_gitmodules(the_repository);
}
@@ -409,7 +409,7 @@ static int check_updates(struct unpack_trees_options *o)
if (ce->ce_flags & CE_UPDATE) {
if (ce->ce_flags & CE_WT_REMOVE)
- die("BUG: both update and delete flags are set on %s",
+ BUG("both update and delete flags are set on %s",
ce->name);
display_progress(progress, ++cnt);
ce->ce_flags &= ~CE_UPDATE;
@@ -1295,10 +1295,21 @@ int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options
o->result.timestamp.sec = o->src_index->timestamp.sec;
o->result.timestamp.nsec = o->src_index->timestamp.nsec;
o->result.version = o->src_index->version;
- o->result.split_index = o->src_index->split_index;
- if (o->result.split_index)
+ if (!o->src_index->split_index) {
+ o->result.split_index = NULL;
+ } else if (o->src_index == o->dst_index) {
+ /*
+ * o->dst_index (and thus o->src_index) will be discarded
+ * and overwritten with o->result at the end of this function,
+ * so just use src_index's split_index to avoid having to
+ * create a new one.
+ */
+ o->result.split_index = o->src_index->split_index;
o->result.split_index->refcount++;
- hashcpy(o->result.sha1, o->src_index->sha1);
+ } else {
+ o->result.split_index = init_split_index(&o->result);
+ }
+ oidcpy(&o->result.oid, &o->src_index->oid);
o->merge_size = len;
mark_all_ce_unused(o->src_index);
@@ -1412,7 +1423,6 @@ int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options
}
}
- o->src_index = NULL;
ret = check_updates(o) ? (-2) : 0;
if (o->dst_index) {
if (!ret) {
@@ -1423,12 +1433,13 @@ int unpack_trees(unsigned len, struct tree_desc *t, struct unpack_trees_options
WRITE_TREE_SILENT |
WRITE_TREE_REPAIR);
}
- move_index_extensions(&o->result, o->dst_index);
+ move_index_extensions(&o->result, o->src_index);
discard_index(o->dst_index);
*o->dst_index = o->result;
} else {
discard_index(&o->result);
}
+ o->src_index = NULL;
done:
clear_exclude_list(&el);
diff --git a/upload-pack.c b/upload-pack.c
index 4a82602..87c6722 100644
--- a/upload-pack.c
+++ b/upload-pack.c
@@ -6,7 +6,6 @@
#include "tag.h"
#include "object.h"
#include "commit.h"
-#include "exec_cmd.h"
#include "diff.h"
#include "revision.h"
#include "list-objects.h"
@@ -17,16 +16,12 @@
#include "sigchain.h"
#include "version.h"
#include "string-list.h"
-#include "parse-options.h"
#include "argv-array.h"
#include "prio-queue.h"
#include "protocol.h"
#include "quote.h"
-
-static const char * const upload_pack_usage[] = {
- N_("git upload-pack [<options>] <dir>"),
- NULL
-};
+#include "upload-pack.h"
+#include "serve.h"
/* Remember to update object flag allocation in object.h */
#define THEY_HAVE (1u << 11)
@@ -64,7 +59,6 @@ static int keepalive = 5;
* otherwise maximum packet size (up to 65520 bytes).
*/
static int use_sideband;
-static int advertise_refs;
static int stateless_rpc;
static const char *pack_objects_hook;
@@ -450,7 +444,7 @@ static int get_common_commits(void)
break;
default:
got_common = 1;
- memcpy(last_hex, oid_to_hex(&oid), 41);
+ oid_to_hex_r(last_hex, &oid);
if (multi_ack == 2)
packet_write_fmt(1, "ACK %s common\n", last_hex);
else if (multi_ack)
@@ -492,7 +486,7 @@ static int do_reachable_revlist(struct child_process *cmd,
"rev-list", "--stdin", NULL,
};
struct object *o;
- char namebuf[42]; /* ^ + SHA-1 + LF */
+ char namebuf[GIT_MAX_HEXSZ + 2]; /* ^ + hash + LF */
int i;
cmd->argv = argv;
@@ -561,15 +555,17 @@ static int get_reachable_list(struct object_array *src,
struct child_process cmd = CHILD_PROCESS_INIT;
int i;
struct object *o;
- char namebuf[42]; /* ^ + SHA-1 + LF */
+ char namebuf[GIT_MAX_HEXSZ + 2]; /* ^ + hash + LF */
+ const unsigned hexsz = the_hash_algo->hexsz;
if (do_reachable_revlist(&cmd, src, reachable) < 0)
return -1;
- while ((i = read_in_full(cmd.out, namebuf, 41)) == 41) {
+ while ((i = read_in_full(cmd.out, namebuf, hexsz + 1)) == hexsz + 1) {
struct object_id sha1;
+ const char *p;
- if (namebuf[40] != '\n' || get_oid_hex(namebuf, &sha1))
+ if (parse_oid_hex(namebuf, &sha1, &p) || *p != '\n')
break;
o = lookup_object(sha1.hash);
@@ -734,7 +730,6 @@ static void deepen(int depth, int deepen_relative,
}
send_unshallow(shallows);
- packet_flush(1);
}
static void deepen_by_rev_list(int ac, const char **av,
@@ -746,7 +741,122 @@ static void deepen_by_rev_list(int ac, const char **av,
send_shallow(result);
free_commit_list(result);
send_unshallow(shallows);
- packet_flush(1);
+}
+
+/* Returns 1 if a shallow list is sent or 0 otherwise */
+static int send_shallow_list(int depth, int deepen_rev_list,
+ timestamp_t deepen_since,
+ struct string_list *deepen_not,
+ struct object_array *shallows)
+{
+ int ret = 0;
+
+ if (depth > 0 && deepen_rev_list)
+ die("git upload-pack: deepen and deepen-since (or deepen-not) cannot be used together");
+ if (depth > 0) {
+ deepen(depth, deepen_relative, shallows);
+ ret = 1;
+ } else if (deepen_rev_list) {
+ struct argv_array av = ARGV_ARRAY_INIT;
+ int i;
+
+ argv_array_push(&av, "rev-list");
+ if (deepen_since)
+ argv_array_pushf(&av, "--max-age=%"PRItime, deepen_since);
+ if (deepen_not->nr) {
+ argv_array_push(&av, "--not");
+ for (i = 0; i < deepen_not->nr; i++) {
+ struct string_list_item *s = deepen_not->items + i;
+ argv_array_push(&av, s->string);
+ }
+ argv_array_push(&av, "--not");
+ }
+ for (i = 0; i < want_obj.nr; i++) {
+ struct object *o = want_obj.objects[i].item;
+ argv_array_push(&av, oid_to_hex(&o->oid));
+ }
+ deepen_by_rev_list(av.argc, av.argv, shallows);
+ argv_array_clear(&av);
+ ret = 1;
+ } else {
+ if (shallows->nr > 0) {
+ int i;
+ for (i = 0; i < shallows->nr; i++)
+ register_shallow(&shallows->objects[i].item->oid);
+ }
+ }
+
+ shallow_nr += shallows->nr;
+ return ret;
+}
+
+static int process_shallow(const char *line, struct object_array *shallows)
+{
+ const char *arg;
+ if (skip_prefix(line, "shallow ", &arg)) {
+ struct object_id oid;
+ struct object *object;
+ if (get_oid_hex(arg, &oid))
+ die("invalid shallow line: %s", line);
+ object = parse_object(&oid);
+ if (!object)
+ return 1;
+ if (object->type != OBJ_COMMIT)
+ die("invalid shallow object %s", oid_to_hex(&oid));
+ if (!(object->flags & CLIENT_SHALLOW)) {
+ object->flags |= CLIENT_SHALLOW;
+ add_object_array(object, NULL, shallows);
+ }
+ return 1;
+ }
+
+ return 0;
+}
+
+static int process_deepen(const char *line, int *depth)
+{
+ const char *arg;
+ if (skip_prefix(line, "deepen ", &arg)) {
+ char *end = NULL;
+ *depth = (int)strtol(arg, &end, 0);
+ if (!end || *end || *depth <= 0)
+ die("Invalid deepen: %s", line);
+ return 1;
+ }
+
+ return 0;
+}
+
+static int process_deepen_since(const char *line, timestamp_t *deepen_since, int *deepen_rev_list)
+{
+ const char *arg;
+ if (skip_prefix(line, "deepen-since ", &arg)) {
+ char *end = NULL;
+ *deepen_since = parse_timestamp(arg, &end, 0);
+ if (!end || *end || !deepen_since ||
+ /* revisions.c's max_age -1 is special */
+ *deepen_since == -1)
+ die("Invalid deepen-since: %s", line);
+ *deepen_rev_list = 1;
+ return 1;
+ }
+ return 0;
+}
+
+static int process_deepen_not(const char *line, struct string_list *deepen_not, int *deepen_rev_list)
+{
+ const char *arg;
+ if (skip_prefix(line, "deepen-not ", &arg)) {
+ char *ref = NULL;
+ struct object_id oid;
+ if (expand_ref(arg, strlen(arg), &oid, &ref) != 1)
+ die("git upload-pack: ambiguous deepen-not: %s", line);
+ string_list_append(deepen_not, ref);
+ free(ref);
+ *deepen_rev_list = 1;
+ return 1;
+ }
+ return 0;
}
static void receive_needs(void)
@@ -770,61 +880,26 @@ static void receive_needs(void)
if (!line)
break;
- if (skip_prefix(line, "shallow ", &arg)) {
- struct object_id oid;
- struct object *object;
- if (get_oid_hex(arg, &oid))
- die("invalid shallow line: %s", line);
- object = parse_object(&oid);
- if (!object)
- continue;
- if (object->type != OBJ_COMMIT)
- die("invalid shallow object %s", oid_to_hex(&oid));
- if (!(object->flags & CLIENT_SHALLOW)) {
- object->flags |= CLIENT_SHALLOW;
- add_object_array(object, NULL, &shallows);
- }
+ if (process_shallow(line, &shallows))
continue;
- }
- if (skip_prefix(line, "deepen ", &arg)) {
- char *end = NULL;
- depth = strtol(arg, &end, 0);
- if (!end || *end || depth <= 0)
- die("Invalid deepen: %s", line);
+ if (process_deepen(line, &depth))
continue;
- }
- if (skip_prefix(line, "deepen-since ", &arg)) {
- char *end = NULL;
- deepen_since = parse_timestamp(arg, &end, 0);
- if (!end || *end || !deepen_since ||
- /* revisions.c's max_age -1 is special */
- deepen_since == -1)
- die("Invalid deepen-since: %s", line);
- deepen_rev_list = 1;
+ if (process_deepen_since(line, &deepen_since, &deepen_rev_list))
continue;
- }
- if (skip_prefix(line, "deepen-not ", &arg)) {
- char *ref = NULL;
- struct object_id oid;
- if (expand_ref(arg, strlen(arg), &oid, &ref) != 1)
- die("git upload-pack: ambiguous deepen-not: %s", line);
- string_list_append(&deepen_not, ref);
- free(ref);
- deepen_rev_list = 1;
+ if (process_deepen_not(line, &deepen_not, &deepen_rev_list))
continue;
- }
+
if (skip_prefix(line, "filter ", &arg)) {
if (!filter_capability_requested)
die("git upload-pack: filtering capability not negotiated");
parse_list_objects_filter(&filter_options, arg);
continue;
}
+
if (!skip_prefix(line, "want ", &arg) ||
- get_oid_hex(arg, &oid_buf))
+ parse_oid_hex(arg, &oid_buf, &features))
die("git upload-pack: protocol error, "
- "expected to get sha, not '%s'", line);
-
- features = arg + 40;
+ "expected to get object ID, not '%s'", line);
if (parse_feature_request(features, "deepen-relative"))
deepen_relative = 1;
@@ -881,40 +956,10 @@ static void receive_needs(void)
if (depth == 0 && !deepen_rev_list && shallows.nr == 0)
return;
- if (depth > 0 && deepen_rev_list)
- die("git upload-pack: deepen and deepen-since (or deepen-not) cannot be used together");
- if (depth > 0)
- deepen(depth, deepen_relative, &shallows);
- else if (deepen_rev_list) {
- struct argv_array av = ARGV_ARRAY_INIT;
- int i;
- argv_array_push(&av, "rev-list");
- if (deepen_since)
- argv_array_pushf(&av, "--max-age=%"PRItime, deepen_since);
- if (deepen_not.nr) {
- argv_array_push(&av, "--not");
- for (i = 0; i < deepen_not.nr; i++) {
- struct string_list_item *s = deepen_not.items + i;
- argv_array_push(&av, s->string);
- }
- argv_array_push(&av, "--not");
- }
- for (i = 0; i < want_obj.nr; i++) {
- struct object *o = want_obj.objects[i].item;
- argv_array_push(&av, oid_to_hex(&o->oid));
- }
- deepen_by_rev_list(av.argc, av.argv, &shallows);
- argv_array_clear(&av);
- }
- else
- if (shallows.nr > 0) {
- int i;
- for (i = 0; i < shallows.nr; i++)
- register_shallow(&shallows.objects[i].item->oid);
- }
-
- shallow_nr += shallows.nr;
+ if (send_shallow_list(depth, deepen_rev_list, deepen_since,
+ &deepen_not, &shallows))
+ packet_flush(1);
object_array_clear(&shallows);
}
@@ -1004,33 +1049,6 @@ static int find_symref(const char *refname, const struct object_id *oid,
return 0;
}
-static void upload_pack(void)
-{
- struct string_list symref = STRING_LIST_INIT_DUP;
-
- head_ref_namespaced(find_symref, &symref);
-
- if (advertise_refs || !stateless_rpc) {
- reset_timeout();
- head_ref_namespaced(send_ref, &symref);
- for_each_namespaced_ref(send_ref, &symref);
- advertise_shallow_grafts(1);
- packet_flush(1);
- } else {
- head_ref_namespaced(check_ref, NULL);
- for_each_namespaced_ref(check_ref, NULL);
- }
- string_list_clear(&symref, 1);
- if (advertise_refs)
- return;
-
- receive_needs();
- if (want_obj.nr) {
- get_common_commits();
- create_pack_file();
- }
-}
-
static int upload_pack_config(const char *var, const char *value, void *unused)
{
if (!strcmp("uploadpack.allowtipsha1inwant", var)) {
@@ -1061,58 +1079,371 @@ static int upload_pack_config(const char *var, const char *value, void *unused)
return parse_hide_refs_config(var, value, "uploadpack");
}
-int cmd_main(int argc, const char **argv)
+void upload_pack(struct upload_pack_options *options)
{
- const char *dir;
- int strict = 0;
- struct option options[] = {
- OPT_BOOL(0, "stateless-rpc", &stateless_rpc,
- N_("quit after a single request/response exchange")),
- OPT_BOOL(0, "advertise-refs", &advertise_refs,
- N_("exit immediately after initial ref advertisement")),
- OPT_BOOL(0, "strict", &strict,
- N_("do not try <directory>/.git/ if <directory> is no Git directory")),
- OPT_INTEGER(0, "timeout", &timeout,
- N_("interrupt transfer after <n> seconds of inactivity")),
- OPT_END()
- };
+ struct string_list symref = STRING_LIST_INIT_DUP;
- packet_trace_identity("upload-pack");
- check_replace_refs = 0;
+ stateless_rpc = options->stateless_rpc;
+ timeout = options->timeout;
+ daemon_mode = options->daemon_mode;
- argc = parse_options(argc, argv, NULL, options, upload_pack_usage, 0);
+ git_config(upload_pack_config, NULL);
- if (argc != 1)
- usage_with_options(upload_pack_usage, options);
+ head_ref_namespaced(find_symref, &symref);
- if (timeout)
- daemon_mode = 1;
+ if (options->advertise_refs || !stateless_rpc) {
+ reset_timeout();
+ head_ref_namespaced(send_ref, &symref);
+ for_each_namespaced_ref(send_ref, &symref);
+ advertise_shallow_grafts(1);
+ packet_flush(1);
+ } else {
+ head_ref_namespaced(check_ref, NULL);
+ for_each_namespaced_ref(check_ref, NULL);
+ }
+ string_list_clear(&symref, 1);
+ if (options->advertise_refs)
+ return;
+
+ receive_needs();
+ if (want_obj.nr) {
+ get_common_commits();
+ create_pack_file();
+ }
+}
+
+struct upload_pack_data {
+ struct object_array wants;
+ struct oid_array haves;
- setup_path();
+ struct object_array shallows;
+ struct string_list deepen_not;
+ int depth;
+ timestamp_t deepen_since;
+ int deepen_rev_list;
+ int deepen_relative;
- dir = argv[0];
+ unsigned stateless_rpc : 1;
- if (!enter_repo(dir, strict))
- die("'%s' does not appear to be a git repository", dir);
+ unsigned use_thin_pack : 1;
+ unsigned use_ofs_delta : 1;
+ unsigned no_progress : 1;
+ unsigned use_include_tag : 1;
+ unsigned done : 1;
+};
+
+static void upload_pack_data_init(struct upload_pack_data *data)
+{
+ struct object_array wants = OBJECT_ARRAY_INIT;
+ struct oid_array haves = OID_ARRAY_INIT;
+ struct object_array shallows = OBJECT_ARRAY_INIT;
+ struct string_list deepen_not = STRING_LIST_INIT_DUP;
+
+ memset(data, 0, sizeof(*data));
+ data->wants = wants;
+ data->haves = haves;
+ data->shallows = shallows;
+ data->deepen_not = deepen_not;
+}
+
+static void upload_pack_data_clear(struct upload_pack_data *data)
+{
+ object_array_clear(&data->wants);
+ oid_array_clear(&data->haves);
+ object_array_clear(&data->shallows);
+ string_list_clear(&data->deepen_not, 0);
+}
+
+static int parse_want(const char *line)
+{
+ const char *arg;
+ if (skip_prefix(line, "want ", &arg)) {
+ struct object_id oid;
+ struct object *o;
+
+ if (get_oid_hex(arg, &oid))
+ die("git upload-pack: protocol error, "
+ "expected to get oid, not '%s'", line);
+
+ o = parse_object(&oid);
+ if (!o) {
+ packet_write_fmt(1,
+ "ERR upload-pack: not our ref %s",
+ oid_to_hex(&oid));
+ die("git upload-pack: not our ref %s",
+ oid_to_hex(&oid));
+ }
+
+ if (!(o->flags & WANTED)) {
+ o->flags |= WANTED;
+ add_object_array(o, NULL, &want_obj);
+ }
+
+ return 1;
+ }
+
+ return 0;
+}
+
+static int parse_have(const char *line, struct oid_array *haves)
+{
+ const char *arg;
+ if (skip_prefix(line, "have ", &arg)) {
+ struct object_id oid;
+
+ if (get_oid_hex(arg, &oid))
+ die("git upload-pack: expected SHA1 object, got '%s'", arg);
+ oid_array_append(haves, &oid);
+ return 1;
+ }
+
+ return 0;
+}
+
+static void process_args(struct packet_reader *request,
+ struct upload_pack_data *data)
+{
+ while (packet_reader_read(request) != PACKET_READ_FLUSH) {
+ const char *arg = request->line;
+ const char *p;
+
+ /* process want */
+ if (parse_want(arg))
+ continue;
+ /* process have line */
+ if (parse_have(arg, &data->haves))
+ continue;
+
+ /* process args like thin-pack */
+ if (!strcmp(arg, "thin-pack")) {
+ use_thin_pack = 1;
+ continue;
+ }
+ if (!strcmp(arg, "ofs-delta")) {
+ use_ofs_delta = 1;
+ continue;
+ }
+ if (!strcmp(arg, "no-progress")) {
+ no_progress = 1;
+ continue;
+ }
+ if (!strcmp(arg, "include-tag")) {
+ use_include_tag = 1;
+ continue;
+ }
+ if (!strcmp(arg, "done")) {
+ data->done = 1;
+ continue;
+ }
+
+ /* Shallow related arguments */
+ if (process_shallow(arg, &data->shallows))
+ continue;
+ if (process_deepen(arg, &data->depth))
+ continue;
+ if (process_deepen_since(arg, &data->deepen_since,
+ &data->deepen_rev_list))
+ continue;
+ if (process_deepen_not(arg, &data->deepen_not,
+ &data->deepen_rev_list))
+ continue;
+ if (!strcmp(arg, "deepen-relative")) {
+ data->deepen_relative = 1;
+ continue;
+ }
+
+ if (allow_filter && skip_prefix(arg, "filter ", &p)) {
+ parse_list_objects_filter(&filter_options, p);
+ continue;
+ }
+
+ /* ignore unknown lines maybe? */
+ die("unexpected line: '%s'", arg);
+ }
+}
+
+static int process_haves(struct oid_array *haves, struct oid_array *common)
+{
+ int i;
+
+ /* Process haves */
+ for (i = 0; i < haves->nr; i++) {
+ const struct object_id *oid = &haves->oid[i];
+ struct object *o;
+ int we_knew_they_have = 0;
+
+ if (!has_object_file(oid))
+ continue;
+
+ oid_array_append(common, oid);
+
+ o = parse_object(oid);
+ if (!o)
+ die("oops (%s)", oid_to_hex(oid));
+ if (o->type == OBJ_COMMIT) {
+ struct commit_list *parents;
+ struct commit *commit = (struct commit *)o;
+ if (o->flags & THEY_HAVE)
+ we_knew_they_have = 1;
+ else
+ o->flags |= THEY_HAVE;
+ if (!oldest_have || (commit->date < oldest_have))
+ oldest_have = commit->date;
+ for (parents = commit->parents;
+ parents;
+ parents = parents->next)
+ parents->item->object.flags |= THEY_HAVE;
+ }
+ if (!we_knew_they_have)
+ add_object_array(o, NULL, &have_obj);
+ }
+
+ return 0;
+}
+
+static int send_acks(struct oid_array *acks, struct strbuf *response)
+{
+ int i;
+
+ packet_buf_write(response, "acknowledgments\n");
+
+ /* Send Acks */
+ if (!acks->nr)
+ packet_buf_write(response, "NAK\n");
+
+ for (i = 0; i < acks->nr; i++) {
+ packet_buf_write(response, "ACK %s\n",
+ oid_to_hex(&acks->oid[i]));
+ }
+
+ if (ok_to_give_up()) {
+ /* Send Ready */
+ packet_buf_write(response, "ready\n");
+ return 1;
+ }
+
+ return 0;
+}
+
+static int process_haves_and_send_acks(struct upload_pack_data *data)
+{
+ struct oid_array common = OID_ARRAY_INIT;
+ struct strbuf response = STRBUF_INIT;
+ int ret = 0;
+
+ process_haves(&data->haves, &common);
+ if (data->done) {
+ ret = 1;
+ } else if (send_acks(&common, &response)) {
+ packet_buf_delim(&response);
+ ret = 1;
+ } else {
+ /* Add Flush */
+ packet_buf_flush(&response);
+ ret = 0;
+ }
+
+ /* Send response */
+ write_or_die(1, response.buf, response.len);
+ strbuf_release(&response);
+
+ oid_array_clear(&data->haves);
+ oid_array_clear(&common);
+ return ret;
+}
+
+static void send_shallow_info(struct upload_pack_data *data)
+{
+ /* No shallow info needs to be sent */
+ if (!data->depth && !data->deepen_rev_list && !data->shallows.nr &&
+ !is_repository_shallow())
+ return;
+
+ packet_write_fmt(1, "shallow-info\n");
+
+ if (!send_shallow_list(data->depth, data->deepen_rev_list,
+ data->deepen_since, &data->deepen_not,
+ &data->shallows) && is_repository_shallow())
+ deepen(INFINITE_DEPTH, data->deepen_relative, &data->shallows);
+
+ packet_delim(1);
+}
+
+enum fetch_state {
+ FETCH_PROCESS_ARGS = 0,
+ FETCH_SEND_ACKS,
+ FETCH_SEND_PACK,
+ FETCH_DONE,
+};
+
+int upload_pack_v2(struct repository *r, struct argv_array *keys,
+ struct packet_reader *request)
+{
+ enum fetch_state state = FETCH_PROCESS_ARGS;
+ struct upload_pack_data data;
git_config(upload_pack_config, NULL);
- switch (determine_protocol_version_server()) {
- case protocol_v1:
- /*
- * v1 is just the original protocol with a version string,
- * so just fall through after writing the version string.
- */
- if (advertise_refs || !stateless_rpc)
- packet_write_fmt(1, "version 1\n");
-
- /* fallthrough */
- case protocol_v0:
- upload_pack();
- break;
- case protocol_unknown_version:
- BUG("unknown protocol version");
+ upload_pack_data_init(&data);
+ use_sideband = LARGE_PACKET_MAX;
+
+ while (state != FETCH_DONE) {
+ switch (state) {
+ case FETCH_PROCESS_ARGS:
+ process_args(request, &data);
+
+ if (!want_obj.nr) {
+ /*
+ * Request didn't contain any 'want' lines,
+ * guess they didn't want anything.
+ */
+ state = FETCH_DONE;
+ } else if (data.haves.nr) {
+ /*
+ * Request had 'have' lines, so lets ACK them.
+ */
+ state = FETCH_SEND_ACKS;
+ } else {
+ /*
+ * Request had 'want's but no 'have's so we can
+ * immedietly go to construct and send a pack.
+ */
+ state = FETCH_SEND_PACK;
+ }
+ break;
+ case FETCH_SEND_ACKS:
+ if (process_haves_and_send_acks(&data))
+ state = FETCH_SEND_PACK;
+ else
+ state = FETCH_DONE;
+ break;
+ case FETCH_SEND_PACK:
+ send_shallow_info(&data);
+
+ packet_write_fmt(1, "packfile\n");
+ create_pack_file();
+ state = FETCH_DONE;
+ break;
+ case FETCH_DONE:
+ continue;
+ }
}
+ upload_pack_data_clear(&data);
return 0;
}
+
+int upload_pack_advertise(struct repository *r,
+ struct strbuf *value)
+{
+ if (value) {
+ int allow_filter_value;
+ strbuf_addstr(value, "shallow");
+ if (!repo_config_get_bool(the_repository,
+ "uploadpack.allowfilter",
+ &allow_filter_value) &&
+ allow_filter_value)
+ strbuf_addstr(value, " filter");
+ }
+ return 1;
+}
diff --git a/upload-pack.h b/upload-pack.h
new file mode 100644
index 0000000..cab2178
--- /dev/null
+++ b/upload-pack.h
@@ -0,0 +1,23 @@
+#ifndef UPLOAD_PACK_H
+#define UPLOAD_PACK_H
+
+struct upload_pack_options {
+ int stateless_rpc;
+ int advertise_refs;
+ unsigned int timeout;
+ int daemon_mode;
+};
+
+void upload_pack(struct upload_pack_options *options);
+
+struct repository;
+struct argv_array;
+struct packet_reader;
+extern int upload_pack_v2(struct repository *r, struct argv_array *keys,
+ struct packet_reader *request);
+
+struct strbuf;
+extern int upload_pack_advertise(struct repository *r,
+ struct strbuf *value);
+
+#endif /* UPLOAD_PACK_H */
diff --git a/usage.c b/usage.c
index cdd534c..cc80333 100644
--- a/usage.c
+++ b/usage.c
@@ -148,6 +148,7 @@ static const char *fmt_with_err(char *buf, int n, const char *fmt)
}
}
str_error[j] = 0;
+ /* Truncation is acceptable here */
snprintf(buf, n, "%s: %s", fmt, str_error);
return buf;
}
@@ -210,6 +211,9 @@ void warning(const char *warn, ...)
va_end(params);
}
+/* Only set this, ever, from t/helper/, when verifying that bugs are caught. */
+int BUG_exit_code;
+
static NORETURN void BUG_vfl(const char *file, int line, const char *fmt, va_list params)
{
char prefix[256];
@@ -221,6 +225,8 @@ static NORETURN void BUG_vfl(const char *file, int line, const char *fmt, va_lis
snprintf(prefix, sizeof(prefix), "BUG: ");
vreportf(prefix, fmt, params);
+ if (BUG_exit_code)
+ exit(BUG_exit_code);
abort();
}
diff --git a/utf8.c b/utf8.c
index 2c27ce0..d55e20c 100644
--- a/utf8.c
+++ b/utf8.c
@@ -81,7 +81,7 @@ static int git_wcwidth(ucs_char_t ch)
/*
* Sorted list of non-overlapping intervals of non-spacing characters,
*/
-#include "unicode_width.h"
+#include "unicode-width.h"
/* test for 8-bit control characters */
if (ch == 0)
@@ -401,18 +401,40 @@ out:
strbuf_release(&sb_dst);
}
+/*
+ * Returns true (1) if the src encoding name matches the dst encoding
+ * name directly or one of its alternative names. E.g. UTF-16BE is the
+ * same as UTF16BE.
+ */
+static int same_utf_encoding(const char *src, const char *dst)
+{
+ if (istarts_with(src, "utf") && istarts_with(dst, "utf")) {
+ /* src[3] or dst[3] might be '\0' */
+ int i = (src[3] == '-' ? 4 : 3);
+ int j = (dst[3] == '-' ? 4 : 3);
+ return !strcasecmp(src+i, dst+j);
+ }
+ return 0;
+}
+
int is_encoding_utf8(const char *name)
{
if (!name)
return 1;
- if (!strcasecmp(name, "utf-8") || !strcasecmp(name, "utf8"))
+ if (same_utf_encoding("utf-8", name))
return 1;
return 0;
}
int same_encoding(const char *src, const char *dst)
{
- if (is_encoding_utf8(src) && is_encoding_utf8(dst))
+ static const char utf8[] = "UTF-8";
+
+ if (!src)
+ src = utf8;
+ if (!dst)
+ dst = utf8;
+ if (same_utf_encoding(src, dst))
return 1;
return !strcasecmp(src, dst);
}
@@ -538,6 +560,45 @@ char *reencode_string_len(const char *in, int insz,
}
#endif
+static int has_bom_prefix(const char *data, size_t len,
+ const char *bom, size_t bom_len)
+{
+ return data && bom && (len >= bom_len) && !memcmp(data, bom, bom_len);
+}
+
+static const char utf16_be_bom[] = {0xFE, 0xFF};
+static const char utf16_le_bom[] = {0xFF, 0xFE};
+static const char utf32_be_bom[] = {0x00, 0x00, 0xFE, 0xFF};
+static const char utf32_le_bom[] = {0xFF, 0xFE, 0x00, 0x00};
+
+int has_prohibited_utf_bom(const char *enc, const char *data, size_t len)
+{
+ return (
+ (same_utf_encoding("UTF-16BE", enc) ||
+ same_utf_encoding("UTF-16LE", enc)) &&
+ (has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
+ has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
+ ) || (
+ (same_utf_encoding("UTF-32BE", enc) ||
+ same_utf_encoding("UTF-32LE", enc)) &&
+ (has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
+ has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
+ );
+}
+
+int is_missing_required_utf_bom(const char *enc, const char *data, size_t len)
+{
+ return (
+ (same_utf_encoding(enc, "UTF-16")) &&
+ !(has_bom_prefix(data, len, utf16_be_bom, sizeof(utf16_be_bom)) ||
+ has_bom_prefix(data, len, utf16_le_bom, sizeof(utf16_le_bom)))
+ ) || (
+ (same_utf_encoding(enc, "UTF-32")) &&
+ !(has_bom_prefix(data, len, utf32_be_bom, sizeof(utf32_be_bom)) ||
+ has_bom_prefix(data, len, utf32_le_bom, sizeof(utf32_le_bom)))
+ );
+}
+
/*
* Returns first character length in bytes for multi-byte `text` according to
* `encoding`.
@@ -620,28 +681,33 @@ static ucs_char_t next_hfs_char(const char **in)
}
}
-int is_hfs_dotgit(const char *path)
+static int is_hfs_dot_generic(const char *path,
+ const char *needle, size_t needle_len)
{
ucs_char_t c;
c = next_hfs_char(&path);
if (c != '.')
return 0;
- c = next_hfs_char(&path);
/*
* there's a great deal of other case-folding that occurs
- * in HFS+, but this is enough to catch anything that will
- * convert to ".git"
+ * in HFS+, but this is enough to catch our fairly vanilla
+ * hard-coded needles.
*/
- if (c != 'g' && c != 'G')
- return 0;
- c = next_hfs_char(&path);
- if (c != 'i' && c != 'I')
- return 0;
- c = next_hfs_char(&path);
- if (c != 't' && c != 'T')
- return 0;
+ for (; needle_len > 0; needle++, needle_len--) {
+ c = next_hfs_char(&path);
+
+ /*
+ * We know our needles contain only ASCII, so we clamp here to
+ * make the results of tolower() sane.
+ */
+ if (c > 127)
+ return 0;
+ if (tolower(c) != *needle)
+ return 0;
+ }
+
c = next_hfs_char(&path);
if (c && !is_dir_sep(c))
return 0;
@@ -649,6 +715,35 @@ int is_hfs_dotgit(const char *path)
return 1;
}
+/*
+ * Inline wrapper to make sure the compiler resolves strlen() on literals at
+ * compile time.
+ */
+static inline int is_hfs_dot_str(const char *path, const char *needle)
+{
+ return is_hfs_dot_generic(path, needle, strlen(needle));
+}
+
+int is_hfs_dotgit(const char *path)
+{
+ return is_hfs_dot_str(path, "git");
+}
+
+int is_hfs_dotgitmodules(const char *path)
+{
+ return is_hfs_dot_str(path, "gitmodules");
+}
+
+int is_hfs_dotgitignore(const char *path)
+{
+ return is_hfs_dot_str(path, "gitignore");
+}
+
+int is_hfs_dotgitattributes(const char *path)
+{
+ return is_hfs_dot_str(path, "gitattributes");
+}
+
const char utf8_bom[] = "\357\273\277";
int skip_utf8_bom(char **text, size_t len)
diff --git a/utf8.h b/utf8.h
index 6bbcf31..db73a2d 100644
--- a/utf8.h
+++ b/utf8.h
@@ -52,8 +52,13 @@ int mbs_chrlen(const char **text, size_t *remainder_p, const char *encoding);
* The path should be NUL-terminated, but we will match variants of both ".git\0"
* and ".git/..." (but _not_ ".../.git"). This makes it suitable for both fsck
* and verify_path().
+ *
+ * Likewise, the is_hfs_dotgitfoo() variants look for ".gitfoo".
*/
int is_hfs_dotgit(const char *path);
+int is_hfs_dotgitmodules(const char *path);
+int is_hfs_dotgitignore(const char *path);
+int is_hfs_dotgitattributes(const char *path);
typedef enum {
ALIGN_LEFT,
@@ -70,4 +75,32 @@ typedef enum {
void strbuf_utf8_align(struct strbuf *buf, align_type position, unsigned int width,
const char *s);
+/*
+ * If a data stream is declared as UTF-16BE or UTF-16LE, then a UTF-16
+ * BOM must not be used [1]. The same applies for the UTF-32 equivalents.
+ * The function returns true if this rule is violated.
+ *
+ * [1] http://unicode.org/faq/utf_bom.html#bom10
+ */
+int has_prohibited_utf_bom(const char *enc, const char *data, size_t len);
+
+/*
+ * If the endianness is not defined in the encoding name, then we
+ * require a BOM. The function returns true if a required BOM is missing.
+ *
+ * The Unicode standard instructs to assume big-endian if there in no
+ * BOM for UTF-16/32 [1][2]. However, the W3C/WHATWG encoding standard
+ * used in HTML5 recommends to assume little-endian to "deal with
+ * deployed content" [3].
+ *
+ * Therefore, strictly requiring a BOM seems to be the safest option for
+ * content in Git.
+ *
+ * [1] http://unicode.org/faq/utf_bom.html#gen6
+ * [2] http://www.unicode.org/versions/Unicode10.0.0/ch03.pdf
+ * Section 3.10, D98, page 132
+ * [3] https://encoding.spec.whatwg.org/#utf-16le
+ */
+int is_missing_required_utf_bom(const char *enc, const char *data, size_t len);
+
#endif
diff --git a/vcs-svn/fast_export.c b/vcs-svn/fast_export.c
index 3fd047a..b5b8913 100644
--- a/vcs-svn/fast_export.c
+++ b/vcs-svn/fast_export.c
@@ -320,7 +320,8 @@ const char *fast_export_read_path(const char *path, uint32_t *mode_out)
err = fast_export_ls(path, mode_out, &buf);
if (err) {
if (errno != ENOENT)
- die_errno("BUG: unexpected fast_export_ls error");
+ BUG("unexpected fast_export_ls error: %s",
+ strerror(errno));
/* Treat missing paths as directories. */
*mode_out = S_IFDIR;
return NULL;
@@ -338,7 +339,8 @@ void fast_export_copy(uint32_t revision, const char *src, const char *dst)
err = fast_export_ls_rev(revision, src, &mode, &data);
if (err) {
if (errno != ENOENT)
- die_errno("BUG: unexpected fast_export_ls_rev error");
+ BUG("unexpected fast_export_ls_rev error: %s",
+ strerror(errno));
fast_export_delete(dst);
return;
}
diff --git a/walker.c b/walker.c
index dffb9c8..0b162a0 100644
--- a/walker.c
+++ b/walker.c
@@ -72,6 +72,8 @@ static struct commit_list *complete = NULL;
static int process_commit(struct walker *walker, struct commit *commit)
{
+ struct commit_list *parents;
+
if (parse_commit(commit))
return -1;
@@ -86,19 +88,14 @@ static int process_commit(struct walker *walker, struct commit *commit)
walker_say(walker, "walk %s\n", oid_to_hex(&commit->object.oid));
- if (walker->get_tree) {
- if (process(walker, &commit->tree->object))
+ if (process(walker, &get_commit_tree(commit)->object))
+ return -1;
+
+ for (parents = commit->parents; parents; parents = parents->next) {
+ if (process(walker, &parents->item->object))
return -1;
- if (!walker->get_all)
- walker->get_tree = 0;
- }
- if (walker->get_history) {
- struct commit_list *parents = commit->parents;
- for (; parents; parents = parents->next) {
- if (process(walker, &parents->item->object))
- return -1;
- }
}
+
return 0;
}
diff --git a/walker.h b/walker.h
index a869013..6d8ae00 100644
--- a/walker.h
+++ b/walker.h
@@ -9,9 +9,6 @@ struct walker {
void (*prefetch)(struct walker *, unsigned char *sha1);
int (*fetch)(struct walker *, unsigned char *sha1);
void (*cleanup)(struct walker *);
- int get_tree;
- int get_history;
- int get_all;
int get_verbosely;
int get_recover;
diff --git a/worktree.c b/worktree.c
index 28989cf..97cda5f 100644
--- a/worktree.c
+++ b/worktree.c
@@ -338,7 +338,7 @@ void update_worktree_location(struct worktree *wt, const char *path_)
struct strbuf path = STRBUF_INIT;
if (is_main_worktree(wt))
- die("BUG: can't relocate main worktree");
+ BUG("can't relocate main worktree");
strbuf_realpath(&path, path_, 1);
if (fspathcmp(wt->path, path.buf)) {
diff --git a/wrap-for-bin.sh b/wrap-for-bin.sh
index 5842408..95851b8 100644
--- a/wrap-for-bin.sh
+++ b/wrap-for-bin.sh
@@ -20,10 +20,17 @@ PATH='@@BUILD_DIR@@/bin-wrappers:'"$PATH"
export GIT_EXEC_PATH GITPERLLIB PATH GIT_TEXTDOMAINDIR
-if test -n "$GIT_TEST_GDB"
-then
- unset GIT_TEST_GDB
- exec gdb --args "${GIT_EXEC_PATH}/@@PROG@@" "$@"
-else
+case "$GIT_DEBUGGER" in
+'')
exec "${GIT_EXEC_PATH}/@@PROG@@" "$@"
-fi
+ ;;
+1)
+ unset GIT_DEBUGGER
+ exec gdb --args "${GIT_EXEC_PATH}/@@PROG@@" "$@"
+ ;;
+*)
+ GIT_DEBUGGER_ARGS="$GIT_DEBUGGER"
+ unset GIT_DEBUGGER
+ exec ${GIT_DEBUGGER_ARGS} "${GIT_EXEC_PATH}/@@PROG@@" "$@"
+ ;;
+esac
diff --git a/wrapper.c b/wrapper.c
index 1fd5e33..e4fa9d8 100644
--- a/wrapper.c
+++ b/wrapper.c
@@ -643,9 +643,9 @@ int xsnprintf(char *dst, size_t max, const char *fmt, ...)
va_end(ap);
if (len < 0)
- die("BUG: your snprintf is broken");
+ BUG("your snprintf is broken");
if (len >= max)
- die("BUG: attempt to snprintf into too-small buffer");
+ BUG("attempt to snprintf into too-small buffer");
return len;
}
diff --git a/write_or_die.c b/write-or-die.c
index eab8c8d..eab8c8d 100644
--- a/write_or_die.c
+++ b/write-or-die.c
diff --git a/wt-status.c b/wt-status.c
index 50815e5..d1c0514 100644
--- a/wt-status.c
+++ b/wt-status.c
@@ -138,6 +138,9 @@ void wt_status_prepare(struct wt_status *s)
s->show_stash = 0;
s->ahead_behind_flags = AHEAD_BEHIND_UNSPECIFIED;
s->display_comment_prefix = 0;
+ s->detect_rename = -1;
+ s->rename_score = -1;
+ s->rename_limit = -1;
}
static void wt_longstatus_print_unmerged_header(struct wt_status *s)
@@ -264,7 +267,7 @@ static const char *wt_status_unmerged_status_string(int stagemask)
case 7:
return _("both modified:");
default:
- die("BUG: unhandled unmerged status %x", stagemask);
+ BUG("unhandled unmerged status %x", stagemask);
}
}
@@ -377,7 +380,7 @@ static void wt_longstatus_print_change_data(struct wt_status *s,
status = d->worktree_status;
break;
default:
- die("BUG: unhandled change_type %d in wt_longstatus_print_change_data",
+ BUG("unhandled change_type %d in wt_longstatus_print_change_data",
change_type);
}
@@ -395,7 +398,7 @@ static void wt_longstatus_print_change_data(struct wt_status *s,
status_printf(s, color(WT_STATUS_HEADER, s), "\t");
what = wt_status_diff_status_string(status);
if (!what)
- die("BUG: unhandled diff status %c", status);
+ BUG("unhandled diff status %c", status);
len = label_width - utf8_strwidth(what);
assert(len >= 0);
if (one_name != two_name)
@@ -470,7 +473,7 @@ static void wt_status_collect_changed_cb(struct diff_queue_struct *q,
case DIFF_STATUS_COPIED:
case DIFF_STATUS_RENAMED:
if (d->rename_status)
- die("BUG: multiple renames on the same target? how?");
+ BUG("multiple renames on the same target? how?");
d->rename_source = xstrdup(p->one->path);
d->rename_score = p->score * 100 / MAX_SCORE;
d->rename_status = p->status;
@@ -484,7 +487,7 @@ static void wt_status_collect_changed_cb(struct diff_queue_struct *q,
break;
default:
- die("BUG: unhandled diff-files status '%c'", p->status);
+ BUG("unhandled diff-files status '%c'", p->status);
break;
}
@@ -547,7 +550,7 @@ static void wt_status_collect_updated_cb(struct diff_queue_struct *q,
case DIFF_STATUS_COPIED:
case DIFF_STATUS_RENAMED:
if (d->rename_status)
- die("BUG: multiple renames on the same target? how?");
+ BUG("multiple renames on the same target? how?");
d->rename_source = xstrdup(p->one->path);
d->rename_score = p->score * 100 / MAX_SCORE;
d->rename_status = p->status;
@@ -569,7 +572,7 @@ static void wt_status_collect_updated_cb(struct diff_queue_struct *q,
break;
default:
- die("BUG: unhandled diff-index status '%c'", p->status);
+ BUG("unhandled diff-index status '%c'", p->status);
break;
}
}
@@ -592,6 +595,9 @@ static void wt_status_collect_changes_worktree(struct wt_status *s)
}
rev.diffopt.format_callback = wt_status_collect_changed_cb;
rev.diffopt.format_callback_data = s;
+ rev.diffopt.detect_rename = s->detect_rename >= 0 ? s->detect_rename : rev.diffopt.detect_rename;
+ rev.diffopt.rename_limit = s->rename_limit >= 0 ? s->rename_limit : rev.diffopt.rename_limit;
+ rev.diffopt.rename_score = s->rename_score >= 0 ? s->rename_score : rev.diffopt.rename_score;
copy_pathspec(&rev.prune_data, &s->pathspec);
run_diff_files(&rev, 0);
}
@@ -603,7 +609,7 @@ static void wt_status_collect_changes_index(struct wt_status *s)
init_revisions(&rev, NULL);
memset(&opt, 0, sizeof(opt));
- opt.def = s->is_initial ? EMPTY_TREE_SHA1_HEX : s->reference;
+ opt.def = s->is_initial ? empty_tree_oid_hex() : s->reference;
setup_revisions(0, NULL, &rev, &opt);
rev.diffopt.flags.override_submodule_config = 1;
@@ -625,9 +631,9 @@ static void wt_status_collect_changes_index(struct wt_status *s)
rev.diffopt.output_format |= DIFF_FORMAT_CALLBACK;
rev.diffopt.format_callback = wt_status_collect_updated_cb;
rev.diffopt.format_callback_data = s;
- rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
- rev.diffopt.rename_limit = 200;
- rev.diffopt.break_opt = 0;
+ rev.diffopt.detect_rename = s->detect_rename >= 0 ? s->detect_rename : rev.diffopt.detect_rename;
+ rev.diffopt.rename_limit = s->rename_limit >= 0 ? s->rename_limit : rev.diffopt.rename_limit;
+ rev.diffopt.rename_score = s->rename_score >= 0 ? s->rename_score : rev.diffopt.rename_score;
copy_pathspec(&rev.prune_data, &s->pathspec);
run_diff_index(&rev, 1);
}
@@ -981,11 +987,13 @@ static void wt_longstatus_print_verbose(struct wt_status *s)
rev.diffopt.ita_invisible_in_index = 1;
memset(&opt, 0, sizeof(opt));
- opt.def = s->is_initial ? EMPTY_TREE_SHA1_HEX : s->reference;
+ opt.def = s->is_initial ? empty_tree_oid_hex() : s->reference;
setup_revisions(0, NULL, &rev, &opt);
rev.diffopt.output_format |= DIFF_FORMAT_PATCH;
- rev.diffopt.detect_rename = DIFF_DETECT_RENAME;
+ rev.diffopt.detect_rename = s->detect_rename >= 0 ? s->detect_rename : rev.diffopt.detect_rename;
+ rev.diffopt.rename_limit = s->rename_limit >= 0 ? s->rename_limit : rev.diffopt.rename_limit;
+ rev.diffopt.rename_score = s->rename_score >= 0 ? s->rename_score : rev.diffopt.rename_score;
rev.diffopt.file = s->fp;
rev.diffopt.close_file = 0;
/*
@@ -2158,7 +2166,7 @@ static void wt_porcelain_v2_print_unmerged_entry(
case 6: key = "AA"; break; /* both added */
case 7: key = "UU"; break; /* both modified */
default:
- die("BUG: unhandled unmerged status %x", d->stagemask);
+ BUG("unhandled unmerged status %x", d->stagemask);
}
/*
@@ -2185,7 +2193,7 @@ static void wt_porcelain_v2_print_unmerged_entry(
sum |= (1 << (stage - 1));
}
if (sum != d->stagemask)
- die("BUG: observed stagemask 0x%x != expected stagemask 0x%x", sum, d->stagemask);
+ BUG("observed stagemask 0x%x != expected stagemask 0x%x", sum, d->stagemask);
if (s->null_termination)
path_index = it->string;
@@ -2289,7 +2297,7 @@ void wt_status_print(struct wt_status *s)
wt_porcelain_v2_print(s);
break;
case STATUS_FORMAT_UNSPECIFIED:
- die("BUG: finalize_deferred_config() should have been called");
+ BUG("finalize_deferred_config() should have been called");
break;
case STATUS_FORMAT_NONE:
case STATUS_FORMAT_LONG:
diff --git a/wt-status.h b/wt-status.h
index 430770b..1673d14 100644
--- a/wt-status.h
+++ b/wt-status.h
@@ -89,7 +89,9 @@ struct wt_status {
int show_stash;
int hints;
enum ahead_behind_flags ahead_behind_flags;
-
+ int detect_rename;
+ int rename_score;
+ int rename_limit;
enum wt_status_format status_format;
unsigned char sha1_commit[GIT_MAX_RAWSZ]; /* when not Initial */
diff --git a/zlib.c b/zlib.c
index 4223f1a..d594cba 100644
--- a/zlib.c
+++ b/zlib.c
@@ -52,9 +52,9 @@ static void zlib_post_call(git_zstream *s)
bytes_consumed = s->z.next_in - s->next_in;
bytes_produced = s->z.next_out - s->next_out;
if (s->z.total_out != s->total_out + bytes_produced)
- die("BUG: total_out mismatch");
+ BUG("total_out mismatch");
if (s->z.total_in != s->total_in + bytes_consumed)
- die("BUG: total_in mismatch");
+ BUG("total_in mismatch");
s->total_out = s->z.total_out;
s->total_in = s->z.total_in;