diff options
255 files changed, 7813 insertions, 3547 deletions
diff --git a/Documentation/RelNotes-1.6.0.3.txt b/Documentation/RelNotes-1.6.0.3.txt new file mode 100644 index 0000000000..c0f037d6db --- /dev/null +++ b/Documentation/RelNotes-1.6.0.3.txt @@ -0,0 +1,120 @@ +GIT v1.6.0.3 Release Notes +========================== + +Fixes since v1.6.0.2 +-------------------- + +* "git archive --format=zip" did not honor core.autocrlf while + --format=tar did. + +* Continuing "git rebase -i" was very confused when the user left modified + files in the working tree while resolving conflicts. + +* Continuing "git rebase -i" was also very confused when the user left + some staged changes in the index after "edit". + +* "git rebase -i" now honors the pre-rebase hook, just like the + other rebase implementations "git rebase" and "git rebase -m". + +* "git rebase -i" incorrectly aborted when there is no commit to replay. + +* Behaviour of "git diff --quiet" was inconsistent with "diff --exit-code" + with the output redirected to /dev/null. + +* "git diff --no-index" on binary files no longer outputs a bogus + "diff --git" header line. + +* "git diff" hunk header patterns with multiple elements separated by LF + were not used correctly. + +* "git gc" when ejecting otherwise unreachable objects from packfiles into + loose form leaked memory. + +* Hunk headers in "git diff" default to using extended regular + expressions, fixing some of the internal patterns on non-GNU + platforms. + +* New config "diff.*.xfuncname" exposes extended regular expressions + for user specified hunk header patterns. + +* "git index-pack" was recently broken and mishandled objects added by + thin-pack completion processing under memory pressure. + +* "git stash apply sash@{1}" was fixed to error out. Prior versions + would have applied stash@{0} incorrectly. + +* "git stash apply" now offers a better suggestion on how to continue + if the working tree is currently dirty. + +* "git for-each-ref --format=%(subject)" fixed for commits with no + no newline in the message body. + +* "git remote" fixed to protect printf from user input. + +* "git remote show -v" now displays all URLs of a remote. + +* "git checkout -b branch" was confused when branch already existed. + +* "git checkout -q" once again suppresses the locally modified file list. + +* "git clone -q", "git fetch -q" asks remote side to not send + progress messages, actually making their output quiet. + +* Cross-directory renames are no longer used when creating packs. This + allows more graceful behavior on filesystems like sshfs. + +* Stale temporary files under $GIT_DIR/objects/pack are now cleaned up + automatically by "git prune". + +* "git merge" once again removes directories after the last file has + been removed from it during the merge. + +* "git merge" did not allocate enough memory for the structure itself when + enumerating the parents of the resulting commit. + +* "git blame -C -C" no longer segfaults while trying to pass blame if + it encounters a submodule reference. + +* "git rm" incorrectly claimed that you have local modifications when a + path was merely stat-dirty. + +* "git svn" fixed to display an error message when 'set-tree' failed, + instead of a Perl compile error. + +* "git submodule" fixed to handle checking out a different commit + than HEAD after initializing the submodule. + +* The "git commit" error message when there are still unmerged + files present was clarified to match "git write-tree". + +* "git init" was confused when core.bare or core.sharedRepository are set + in system or user global configuration file by mistake. When --bare or + --shared is given from the command line, these now override such + settings made outside the repositories. + +* Some segfaults due to uncaught NULL pointers were fixed in multiple + tools such as apply, reset, update-index. + +* Solaris builds now default to OLD_ICONV=1 to avoid compile warnings; + Solaris 8 does not define NEEDS_LIBICONV by default. + +* "Git.pm" tests relied on unnecessarily more recent version of Perl. + +* "gitweb" triggered undef warning on commits without log messages. + +* "gitweb" triggered undef warnings on missing trees. + +* "gitweb" now removes PATH_INFO from its URLs so users don't have + to manually set the URL in the gitweb configuration. + +* Bash completion removed support for legacy "git-fetch", "git-push" + and "git-pull" as these are no longer installed. Dashless form + ("git fetch") is still however supported. + +Many other documentation updates. + +-- +exec >/var/tmp/1 +O=v1.6.0.2-110-gf07c3c5 +echo O=$(git describe maint) +git shortlog --no-merges $O..maint diff --git a/Documentation/RelNotes-1.6.1.txt b/Documentation/RelNotes-1.6.1.txt index 609d4ca562..afd1150eaa 100644 --- a/Documentation/RelNotes-1.6.1.txt +++ b/Documentation/RelNotes-1.6.1.txt @@ -16,13 +16,16 @@ on. * gitk can call out to git-gui to view "git blame" output; git-gui in turn can run gitk from its blame view. -(portability) +* Various git-gui updates including updated translations. + +* Various gitweb updates from repo.or.cz installation. -* ... +(portability) -(documentation) +* A few test scripts used nonportable "grep" that did not work well on + some platforms, e.g. Solaris. -* ... +* Sample pre-auto-gc script has OS X support. (performance) @@ -32,27 +35,74 @@ on. * Most of the test scripts (but not the ones that try to run servers) can be run in parallel. +* Bash completion of refnames in a repository with massive number of + refs has been optimized. + +* Cygwin port uses native stat/lstat implementations when applicable, + which leads to improved performance. + +* "git push" pays attention to alternate repositories to avoid sending + unnecessary objects. + +* "git svn" can rebuild an out-of-date rev_map file. + (usability, bells and whistles) +* When you mistype a command name, git helpfully suggests what it guesses + you might have meant to say. help.autocorrect configuration can be set + to a non-zero value to accept the suggestion when git can uniquely + guess. + +* "git add -N path..." adds the named paths as an empty blob, so that + subsequent "git diff" will show a diff as if they are creation events. + +* "git apply" learned --include=paths option, similar to the existing + --exclude=paths option. + +* "git bisect" is careful about a user mistake and suggests testing of + merge base first when good is not a strict ancestor of bad. + * "git checkout --track origin/hack" used to be a syntax error. It now DWIMs to create a corresponding local branch "hack", i.e. acts as if you said "git checkout --track -b hack origin/hack". +* "git checkout --ours/--theirs" can be used to check out one side of a + conflicting merge during conflict resolution. + +* "git checkout -m" can be used to recreate the initial conflicted state + during conflict resolution. + * "git cherry-pick" can also utilize rerere for conflict resolution. * "git commit --author=$name" can look up author name from existing commits. +* output from "git commit" has been reworded in a more concise and yet + more informative way. + * "git count-objects" reports the on-disk footprint for packfiles and their corresponding idx files. * "git daemon" learned --max-connections=<count> option. -* "git diff" learned to mimick --suppress-blank-empty from GNU diff via a +* "git diff" learned to mimic --suppress-blank-empty from GNU diff via a configuration option. -* "git diff" learned to put more sensible hunk headers for Python and - HTML contents. +* "git diff" learned to put more sensible hunk headers for Python, + HTML and ObjC contents. + +* "git diff" learned to vary the a/ vs b/ prefix depending on what are + being compared, controlled by diff.mnemonicprefix configuration. + +* "git diff" learned --dirstat-by-file to count changed files, not number + of lines, when summarizing the global picture. + +* "git diff" hunk header pattern for ObjC has been added. + +* "git for-each-ref" learned "refname:short" token that gives an + unambiguously abbreviated refname. + +* "git grep" learned to accept -z similar to GNU grep. * "git help" learned to use GIT_MAN_VIEWER environment variable before using "man" program. @@ -68,6 +118,9 @@ on. * "git log" learned --simplify-merges, a milder variant of --full-history; "gitk --simplify-merges" is easier to view than with --full-history. +* "git log --pretty=format:" learned "%d" format element that inserts + names of tags that point at the commit. + * "git merge --squash" and "git merge --no-ff" into an unborn branch are noticed as user errors. @@ -83,12 +136,18 @@ on. * "git submodule sync" subcommands allows you to update the origin URL recorded in submodule directories from the toplevel .gitmodules file. +* "git svn branch" can create new branches on the other end. + (internal) * "git hash-object" learned to lie about the path being hashed, so that correct gitattributes processing can be done while hashing contents stored in a temporary file. +* various callers of git-merge-recursive avoid forking it as an external + process. + + Fixes since v1.6.0 ------------------ @@ -101,9 +160,14 @@ release, unless otherwise noted. is a path in it). * "git diff --stdin" used to take two trees on a line and compared them, - but we droppped support for such a use case long time ago. This has + but we dropped support for such a use case long time ago. This has been resurrected. +* Giving 3 or more tree-ish to "git diff" is supposed to show the combined + diff from second and subsequent trees to the first one. b75271d ("git + diff <tree>{3,}": do not reverse order of arguments, 2008-10-10) needs + to be cherry-picked to 'maint'. + * "git filter-branch" failed to rewrite a tag name with slashes in it. * "git push --tags --all $there" failed with generic usage message without @@ -115,6 +179,6 @@ release, unless otherwise noted. -- exec >/var/tmp/1 -O=v1.6.0.1-266-gaf9552f +O=v1.6.0.2-553-g58e0fa5 echo O=$(git describe master) git shortlog --no-merges $O..master ^maint diff --git a/Documentation/config.txt b/Documentation/config.txt index 922ac7b44d..29369d051b 100644 --- a/Documentation/config.txt +++ b/Documentation/config.txt @@ -117,6 +117,17 @@ core.fileMode:: the working copy are ignored; useful on broken filesystems like FAT. See linkgit:git-update-index[1]. True by default. +core.ignoreCygwinFSTricks:: + This option is only used by Cygwin implementation of Git. If false, + the Cygwin stat() and lstat() functions are used. This may be useful + if your repository consists of a few separate directories joined in + one hierarchy using Cygwin mount. If true, Git uses native Win32 API + whenever it is possible and falls back to Cygwin functions only to + handle symbol links. The native mode is more than twice faster than + normal Cygwin l/stat() functions. True by default, unless core.filemode + is true, in which case ignoreCygwinFSTricks is ignored as Cygwin's + POSIX emulation is required to support core.filemode. + core.trustctime:: If false, the ctime differences between the index and the working copy are ignored; useful when the inode change time @@ -363,8 +374,17 @@ core.pager:: variable. Note that git sets the `LESS` environment variable to `FRSX` if it is unset when it runs the pager. One can change these settings by setting the - `LESS` variable to some other value or by giving the - `core.pager` option a value such as "`less -+FRSX`". + `LESS` variable to some other value. Alternately, + these settings can be overridden on a project or + global basis by setting the `core.pager` option. + Setting `core.pager` has no affect on the `LESS` + environment variable behaviour above, so if you want + to override git's default settings this way, you need + to be explicit. For example, to disable the S option + in a backward compatible manner, set `core.pager` + to "`less -+$LESS -FRX`". This will be passed to the + shell by git, which will translate the final command to + "`LESS=FRSX less -+FRSX -FRX`". core.whitespace:: A comma separated list of common whitespace problems to @@ -585,6 +605,22 @@ diff.external:: you want to use an external diff program only on a subset of your files, you might want to use linkgit:gitattributes[5] instead. +diff.mnemonicprefix:: + If set, 'git-diff' uses a prefix pair that is different from the + standard "a/" and "b/" depending on what is being compared. When + this configuration is in effect, reverse diff output also swaps + the order of the prefixes: +'git-diff';; + compares the (i)ndex and the (w)ork tree; +'git-diff HEAD';; + compares a (c)ommit and the (w)ork tree; +'git diff --cached';; + compares a (c)ommit and the (i)ndex; +'git-diff HEAD:file1 file2';; + compares an (o)bject and a (w)ork tree entity; +'git diff --no-index a b';; + compares two non-git things (1) and (2). + diff.renameLimit:: The number of files to consider when performing the copy/rename detection; equivalent to the 'git-diff' option '-l'. @@ -606,10 +642,11 @@ fetch.unpackLimit:: `transfer.unpackLimit` is used instead. format.numbered:: - A boolean which can enable sequence numbers in patch subjects. - Setting this option to "auto" will enable it only if there is - more than one patch. See --numbered option in - linkgit:git-format-patch[1]. + A boolean which can enable or disable sequence numbers in patch + subjects. It defaults to "auto" which enables it only if there + is more than one patch. It can be enabled or disabled for all + messages by setting it to "true" or "false". See --numbered + option in linkgit:git-format-patch[1]. format.headers:: Additional email headers to include in a patch to be submitted @@ -902,6 +939,14 @@ man.<tool>.path:: Override the path for the given tool that may be used to display help in the 'man' format. See linkgit:git-help[1]. +merge.conflictstyle:: + Specify the style in which conflicted hunks are written out to + working tree files upon merge. The default is "merge", which + shows `<<<<<<<` conflict marker, change made by one side, + `=======` marker, change made by the other side, and then + `>>>>>>>` marker. An alternate style, "diff3", adds `|||||||` + marker and the original text before `=======` marker. + mergetool.<tool>.path:: Override the path for the given tool. This is useful in case your tool is not in the PATH. diff --git a/Documentation/diff-options.txt b/Documentation/diff-options.txt index 6e268326da..c62b45cdba 100644 --- a/Documentation/diff-options.txt +++ b/Documentation/diff-options.txt @@ -65,6 +65,9 @@ endif::git-format-patch[] can be set with "--dirstat=limit". Changes in a child directory is not counted for the parent directory, unless "--cumulative" is used. +--dirstat-by-file[=limit]:: + Same as --dirstat, but counts changed files instead of lines. + --summary:: Output a condensed summary of extended header information such as creations, renames and mode changes. @@ -134,7 +137,8 @@ endif::git-format-patch[] --diff-filter=[ACDMRTUXB*]:: Select only files that are Added (`A`), Copied (`C`), Deleted (`D`), Modified (`M`), Renamed (`R`), have their - type (mode) changed (`T`), are Unmerged (`U`), are + type (i.e. regular file, symlink, submodule, ...) changed (`T`), + are Unmerged (`U`), are Unknown (`X`), or have had their pairing Broken (`B`). Any combination of the filter characters may be used. When `*` (All-or-none) is added to the combination, all diff --git a/Documentation/git-apply.txt b/Documentation/git-apply.txt index feb51f124a..e726510ab1 100644 --- a/Documentation/git-apply.txt +++ b/Documentation/git-apply.txt @@ -14,7 +14,8 @@ SYNOPSIS [--allow-binary-replacement | --binary] [--reject] [-z] [-pNUM] [-CNUM] [--inaccurate-eof] [--recount] [--cached] [--whitespace=<nowarn|warn|fix|error|error-all>] - [--exclude=PATH] [--directory=<root>] [--verbose] [<patch>...] + [--exclude=PATH] [--include=PATH] [--directory=<root>] + [--verbose] [<patch>...] DESCRIPTION ----------- @@ -137,6 +138,17 @@ discouraged. be useful when importing patchsets, where you want to exclude certain files or directories. +--include=<path-pattern>:: + Apply changes to files matching the given path pattern. This can + be useful when importing patchsets, where you want to include certain + files or directories. ++ +When --exclude and --include patterns are used, they are examined in the +order they appear on the command line, and the first match determines if a +patch to each path is used. A patch to a path that does not match any +include/exclude pattern is used by default if there is no include pattern +on the command line, and ignored if there is any include pattern. + --whitespace=<action>:: When applying a patch, detect a new or modified line that has whitespace errors. What are considered whitespace errors is diff --git a/Documentation/git-check-attr.txt b/Documentation/git-check-attr.txt index 2b821f2a1d..256659a6b0 100644 --- a/Documentation/git-check-attr.txt +++ b/Documentation/git-check-attr.txt @@ -8,7 +8,9 @@ git-check-attr - Display gitattributes information. SYNOPSIS -------- +[verse] 'git check-attr' attr... [--] pathname... +'git check-attr' --stdin [-z] attr... < <list-of-paths> DESCRIPTION ----------- @@ -17,11 +19,68 @@ For every pathname, this command will list if each attr is 'unspecified', OPTIONS ------- +--stdin:: + Read file names from stdin instead of from the command-line. + +-z:: + Only meaningful with `--stdin`; paths are separated with + NUL character instead of LF. + \--:: Interpret all preceding arguments as attributes, and all following arguments as path names. If not supplied, only the first argument will be treated as an attribute. +OUTPUT +------ + +The output is of the form: +<path> COLON SP <attribute> COLON SP <info> LF + +Where <path> is the path of a file being queried, <attribute> is an attribute +being queried and <info> can be either: + +'unspecified';; when the attribute is not defined for the path. +'unset';; when the attribute is defined to false. +'set';; when the attribute is defined to true. +<value>;; when a value has been assigned to the attribute. + +EXAMPLES +-------- + +In the examples, the following '.gitattributes' file is used: +--------------- +*.java diff=java -crlf myAttr +NoMyAttr.java !myAttr +README caveat=unspecified +--------------- + +* Listing a single attribute: +--------------- +$ git check-attr diff org/example/MyClass.java +org/example/MyClass.java: diff: java +--------------- + +* Listing multiple attributes for a file: +--------------- +$ git check-attr crlf diff myAttr -- org/example/MyClass.java +org/example/MyClass.java: crlf: unset +org/example/MyClass.java: diff: java +org/example/MyClass.java: myAttr: set +--------------- + +* Listing attribute for multiple files: +--------------- +$ git check-attr myAttr -- org/example/MyClass.java org/example/NoMyAttr.java +org/example/MyClass.java: myAttr: set +org/example/NoMyAttr.java: myAttr: unspecified +--------------- + +* Not all values are equally unambiguous: +--------------- +$ git check-attr caveat README +README: caveat: unspecified +--------------- SEE ALSO -------- diff --git a/Documentation/git-checkout.txt b/Documentation/git-checkout.txt index be54a0299f..168333a588 100644 --- a/Documentation/git-checkout.txt +++ b/Documentation/git-checkout.txt @@ -9,7 +9,7 @@ SYNOPSIS -------- [verse] 'git checkout' [-q] [-f] [--track | --no-track] [-b <new_branch> [-l]] [-m] [<branch>] -'git checkout' [<tree-ish>] [--] <paths>... +'git checkout' [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>... DESCRIPTION ----------- @@ -27,14 +27,20 @@ the first namespace level. When <paths> are given, this command does *not* switch branches. It updates the named paths in the working tree from -the index file (i.e. it runs `git checkout-index -f -u`), or -from a named commit. In -this case, the `-f` and `-b` options are meaningless and giving +the index file, or from a named commit. In +this case, the `-b` options is meaningless and giving either of them results in an error. <tree-ish> argument can be used to specify a specific tree-ish (i.e. commit, tag or tree) to update the index for the given paths before updating the working tree. +The index may contain unmerged entries after a failed merge. By +default, if you try to check out such an entry from the index, the +checkout operation will fail and nothing will be checked out. +Using -f will ignore these unmerged entries. The contents from a +specific side of the merge can be checked out of the index by +using --ours or --theirs. With -m, changes made to the working tree +file can be discarded to recreate the original conflicted merge result. OPTIONS ------- @@ -42,8 +48,17 @@ OPTIONS Quiet, suppress feedback messages. -f:: - Proceed even if the index or the working tree differs - from HEAD. This is used to throw away local changes. + When switching branches, proceed even if the index or the + working tree differs from HEAD. This is used to throw away + local changes. ++ +When checking out paths from the index, do not fail upon unmerged +entries; instead, unmerged entries are ignored. + +--ours:: +--theirs:: + When checking out paths from the index, check out stage #2 + ('ours') or #3 ('theirs') for unmerged paths. -b:: Create a new branch named <new_branch> and start it at @@ -73,7 +88,7 @@ This would tell us to use "hack" as the local branch when branching off of "origin/hack" (or "remotes/origin/hack", or even "refs/remotes/origin/hack"). If the given name has no slash, or the above guessing results in an empty name, the guessing is aborted. You can -exlicitly give a name with '-b' in such a case. +explicitly give a name with '-b' in such a case. --no-track:: Ignore the branch.autosetupmerge configuration variable. @@ -84,7 +99,9 @@ exlicitly give a name with '-b' in such a case. based sha1 expressions such as "<branchname>@\{yesterday}". -m:: - If you have local modifications to one or more files that +--merge:: + When switching branches, + if you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context. @@ -96,6 +113,16 @@ When a merge conflict happens, the index entries for conflicting paths are left unmerged, and you need to resolve the conflicts and mark the resolved paths with `git add` (or `git rm` if the merge should result in deletion of the path). ++ +When checking out paths from the index, this option lets you recreate +the conflicted merge in the specified paths. + +--conflict=<style>:: + The same as --merge option above, but changes the way the + conflicting hunks are presented, overriding the + merge.conflictstyle configuration variable. Possible values are + "merge" (default) and "diff3" (in addition to what is shown by + "merge" style, shows the original contents). <new_branch>:: Name for the new branch. diff --git a/Documentation/git-clone.txt b/Documentation/git-clone.txt index 0e14e732fd..95f08b9114 100644 --- a/Documentation/git-clone.txt +++ b/Documentation/git-clone.txt @@ -90,6 +90,11 @@ then the cloned repository will become corrupt. Operate quietly. This flag is also passed to the `rsync' command when given. +--verbose:: +-v:: + Display the progressbar, even in case the standard output is not + a terminal. + --no-checkout:: -n:: No checkout of HEAD is performed after the clone is complete. diff --git a/Documentation/git-commit.txt b/Documentation/git-commit.txt index eeba58df2b..2e62165fa9 100644 --- a/Documentation/git-commit.txt +++ b/Documentation/git-commit.txt @@ -94,7 +94,8 @@ OPTIONS -s:: --signoff:: - Add Signed-off-by line at the end of the commit message. + Add Signed-off-by line by the commiter at the end of the commit + log message. -n:: --no-verify:: diff --git a/Documentation/git-describe.txt b/Documentation/git-describe.txt index c4dbc2ae34..3d79f05995 100644 --- a/Documentation/git-describe.txt +++ b/Documentation/git-describe.txt @@ -18,6 +18,9 @@ shown. Otherwise, it suffixes the tag name with the number of additional commits on top of the tagged object and the abbreviated object name of the most recent commit. +By default (without --all or --tags) `git describe` only shows +annotated tags. For more information about creating annotated tags +see the -a and -s options to linkgit:git-tag[1]. OPTIONS ------- @@ -26,11 +29,13 @@ OPTIONS --all:: Instead of using only the annotated tags, use any ref - found in `.git/refs/`. + found in `.git/refs/`. This option enables matching + any known branch, remote branch, or lightweight tag. --tags:: Instead of using only the annotated tags, use any tag - found in `.git/refs/tags`. + found in `.git/refs/tags`. This option enables matching + a lightweight (non-annotated) tag. --contains:: Instead of finding the tag that predates the commit, find diff --git a/Documentation/git-for-each-ref.txt b/Documentation/git-for-each-ref.txt index ebd7c5fbb3..5061d3e4e7 100644 --- a/Documentation/git-for-each-ref.txt +++ b/Documentation/git-for-each-ref.txt @@ -74,6 +74,7 @@ For all objects, the following names can be used: refname:: The name of the ref (the part after $GIT_DIR/). + For a non-ambiguous short name of the ref append `:short`. 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 adb4ea7b1b..ac36ce8717 100644 --- a/Documentation/git-format-patch.txt +++ b/Documentation/git-format-patch.txt @@ -58,8 +58,10 @@ output, unless the --stdout option is specified. If -o is specified, output files are created in <dir>. Otherwise they are created in the current working directory. -If -n is specified, instead of "[PATCH] Subject", the first line -is formatted as "[PATCH n/m] Subject". +By default, the subject of a single patch is "[PATCH] First Line" and +the subject when multiple patches are output is "[PATCH n/m] First +Line". To force 1/1 to be added for a single patch, use -n. To omit +patch numbers from the subject, use -N If given --thread, 'git-format-patch' will generate In-Reply-To and References headers to make the second and subsequent patch mails appear @@ -81,7 +83,7 @@ include::diff-options.txt[] -n:: --numbered:: - Name output in '[PATCH n/m]' format. + Name output in '[PATCH n/m]' format, even with a single patch. -N:: --no-numbered:: diff --git a/Documentation/git-grep.txt b/Documentation/git-grep.txt index fa4d133c1b..553da6cbb1 100644 --- a/Documentation/git-grep.txt +++ b/Documentation/git-grep.txt @@ -15,6 +15,7 @@ SYNOPSIS [-E | --extended-regexp] [-G | --basic-regexp] [-F | --fixed-strings] [-n] [-l | --files-with-matches] [-L | --files-without-match] + [-z | --null] [-c | --count] [--all-match] [-A <post-context>] [-B <pre-context>] [-C <context>] [-f <file>] [-e] <pattern> @@ -94,6 +95,11 @@ OPTIONS For better compatibility with 'git-diff', --name-only is a synonym for --files-with-matches. +-z:: +--null:: + Output \0 instead of the character that normally follows a + file name. + -c:: --count:: Instead of showing every matched line, show the number of diff --git a/Documentation/git-log.txt b/Documentation/git-log.txt index 0446bad7e5..93a2a227c4 100644 --- a/Documentation/git-log.txt +++ b/Documentation/git-log.txt @@ -8,7 +8,7 @@ git-log - Show commit logs SYNOPSIS -------- -'git log' <option>... +'git log' [<options>] [<since>..<until>] [[\--] <path>...] DESCRIPTION ----------- @@ -57,8 +57,11 @@ include::diff-options.txt[] Note that only message is considered, if also a diff is shown its size is not included. -<path>...:: - Show only commits that affect any of the specified paths. +[\--] <path>...:: + Show only commits that affect any of the specified paths. To + prevent confusion with options and branch names, paths may need + to be prefixed with "\-- " to separate them from options or + refnames. include::rev-list-options.txt[] diff --git a/Documentation/git-merge.txt b/Documentation/git-merge.txt index 685e1fed58..1f30830d46 100644 --- a/Documentation/git-merge.txt +++ b/Documentation/git-merge.txt @@ -119,6 +119,71 @@ When there are conflicts, these things happen: same and the index entries for them stay as they were, i.e. matching `HEAD`. +HOW CONFLICTS ARE PRESENTED +--------------------------- + +During a merge, the working tree files are updated to reflect the result +of the merge. Among the changes made to the common ancestor's version, +non-overlapping ones (that is, you changed an area of the file while the +other side left that area intact, or vice versa) are incorporated in the +final result verbatim. When both sides made changes to the same area, +however, git cannot randomly pick one side over the other, and asks you to +resolve it by leaving what both sides did to that area. + +By default, git uses the same style as that is used by "merge" program +from the RCS suite to present such a conflicted hunk, like this: + +------------ +Here are lines that are either unchanged from the common +ancestor, or cleanly resolved because only one side changed. +<<<<<<< yours:sample.txt +Conflict resolution is hard; +let's go shopping. +======= +Git makes conflict resolution easy. +>>>>>>> theirs:sample.txt +And here is another line that is cleanly resolved or unmodified. +------------ + +The area a pair of conflicting changes happened is marked with markers +"`<<<<<<<`", "`=======`", and "`>>>>>>>`". The part before the "`=======`" +is typically your side, and the part after it is typically their side. + +The default format does not show what the original said in the conflicted +area. You cannot tell how many lines are deleted and replaced with the +Barbie's remark by your side. The only thing you can tell is that your +side wants to say it is hard and you'd prefer to go shopping, while the +other side wants to claim it is easy. + +An alternative style can be used by setting the "merge.conflictstyle" +configuration variable to "diff3". In "diff3" style, the above conflict +may look like this: + +------------ +Here are lines that are either unchanged from the common +ancestor, or cleanly resolved because only one side changed. +<<<<<<< yours:sample.txt +Conflict resolution is hard; +let's go shopping. +||||||| +Conflict resolution is hard. +======= +Git makes conflict resolution easy. +>>>>>>> theirs:sample.txt +And here is another line that is cleanly resolved or unmodified. +------------ + +In addition to the "`<<<<<<<`", "`=======`", and "`>>>>>>>`" markers, it uses +another "`|||||||`" marker that is followed by the original text. You can +tell that the original just stated a fact, and your side simply gave in to +that statement and gave up, while the other side tried to have a more +positive attitude. You can sometimes come up with a better resolution by +viewing the original. + + +HOW TO RESOLVE CONFLICTS +------------------------ + After seeing a conflict, you can do two things: * Decide not to merge. The only clean-up you need are to reset diff --git a/Documentation/git-prune.txt b/Documentation/git-prune.txt index 54f1dab38d..da6055d4b8 100644 --- a/Documentation/git-prune.txt +++ b/Documentation/git-prune.txt @@ -8,7 +8,7 @@ git-prune - Prune all unreachable objects from the object database SYNOPSIS -------- -'git-prune' [-n] [--expire <expire>] [--] [<head>...] +'git-prune' [-n] [-v] [--expire <expire>] [--] [<head>...] DESCRIPTION ----------- @@ -34,6 +34,9 @@ OPTIONS Do not remove anything; just report what it would remove. +-v:: + Report all removed objects. + \--:: Do not interpret any more arguments as options. diff --git a/Documentation/git-push.txt b/Documentation/git-push.txt index 45c96435fa..6150b1b959 100644 --- a/Documentation/git-push.txt +++ b/Documentation/git-push.txt @@ -9,8 +9,8 @@ git-push - Update remote refs along with associated objects SYNOPSIS -------- [verse] -'git push' [--all] [--dry-run] [--tags] [--receive-pack=<git-receive-pack>] - [--repo=all] [-f | --force] [-v | --verbose] +'git push' [--all | --mirror] [--dry-run] [--tags] [--receive-pack=<git-receive-pack>] + [--repo=<repository>] [-f | --force] [-v | --verbose] [<repository> <refspec>...] DESCRIPTION @@ -101,9 +101,23 @@ nor in any Push line of the corresponding remotes file---see below). This flag disables the check. This can cause the remote repository to lose commits; use it with care. ---repo=<repo>:: - When no repository is specified the command defaults to - "origin"; this overrides it. +--repo=<repository>:: + This option is only relevant if no <repository> argument is + passed in the invocation. In this case, 'git-push' derives the + remote name from the current branch: If it tracks a remote + branch, then that remote repository is pushed to. Otherwise, + the name "origin" is used. For this latter case, this option + can be used to override the name "origin". In other words, + the difference between these two commands ++ +-------------------------- +git push public #1 +git push --repo=public #2 +-------------------------- ++ +is that #1 always pushes to "public" whereas #2 pushes to "public" +only if the current branch does not track a remote branch. This is +useful if you write an alias or script around 'git-push'. --thin:: --no-thin:: diff --git a/Documentation/git-read-tree.txt b/Documentation/git-read-tree.txt index 6f4b9b017f..7160fa1536 100644 --- a/Documentation/git-read-tree.txt +++ b/Documentation/git-read-tree.txt @@ -160,7 +160,10 @@ Here are the "carry forward" rules: 0 nothing nothing nothing (does not happen) 1 nothing nothing exists use M 2 nothing exists nothing remove path from index - 3 nothing exists exists use M + 3 nothing exists exists, use M if "initial checkout" + H == M keep index otherwise + exists fail + H != M clean I==H I==M ------------------ @@ -207,6 +210,12 @@ you picked it up via e-mail in a patch form), `git diff-index merge, but it would not show in `git diff-index --cached $M` output after two-tree merge. +Case #3 is slightly tricky and needs explanation. The result from this +rule logically should be to remove the path if the user staged the removal +of the path and then switching to a new branch. That however will prevent +the initial checkout from happening, so the rule is modified to use M (new +tree) only when the contents of the index is empty. Otherwise the removal +of the path is kept as long as $H and $M are the same. 3-Way Merge ~~~~~~~~~~~ diff --git a/Documentation/git-rebase.txt b/Documentation/git-rebase.txt index 35cae59cf9..c8ad86a56f 100644 --- a/Documentation/git-rebase.txt +++ b/Documentation/git-rebase.txt @@ -9,7 +9,7 @@ SYNOPSIS -------- [verse] 'git rebase' [-i | --interactive] [-v | --verbose] [-m | --merge] - [-s <strategy> | --strategy=<strategy>] + [-s <strategy> | --strategy=<strategy>] [--no-verify] [-C<n>] [ --whitespace=<option>] [-p | --preserve-merges] [--onto <newbase>] <upstream> [<branch>] 'git rebase' --continue | --skip | --abort @@ -92,7 +92,7 @@ branch to another, to pretend that you forked the topic branch from the latter branch, using `rebase --onto`. First let's assume your 'topic' is based on branch 'next'. -For example feature developed in 'topic' depends on some +For example, a feature developed in 'topic' depends on some functionality which is found in 'next'. ------------ @@ -103,9 +103,9 @@ functionality which is found in 'next'. o---o---o topic ------------ -We would want to make 'topic' forked from branch 'master', -for example because the functionality 'topic' branch depend on -got merged into more stable 'master' branch, like this: +We want to make 'topic' forked from branch 'master'; for example, +because the functionality on which 'topic' depends was merged into the +more stable 'master' branch. We want our tree to look like this: ------------ o---o---o---o---o master @@ -232,6 +232,9 @@ OPTIONS --verbose:: Display a diffstat of what changed upstream since the last rebase. +--no-verify:: + This option bypasses the pre-rebase hook. See also linkgit:githooks[5]. + -C<n>:: Ensure at least <n> lines of surrounding context match before and after each change. When fewer lines of surrounding @@ -250,8 +253,7 @@ OPTIONS -p:: --preserve-merges:: - Instead of ignoring merges, try to recreate them. This option - only works in interactive mode. + Instead of ignoring merges, try to recreate them. include::merge-strategies.txt[] diff --git a/Documentation/git-repack.txt b/Documentation/git-repack.txt index 38ac60947b..bbe1485a97 100644 --- a/Documentation/git-repack.txt +++ b/Documentation/git-repack.txt @@ -60,7 +60,7 @@ OPTIONS linkgit:git-pack-objects[1]. -f:: - Pass the `--no-reuse-delta` option to 'git-pack-objects'. See + Pass the `--no-reuse-object` option to `git-pack-objects`, see linkgit:git-pack-objects[1]. -q:: diff --git a/Documentation/git-rev-list.txt b/Documentation/git-rev-list.txt index fd1de92e34..1c9cc28895 100644 --- a/Documentation/git-rev-list.txt +++ b/Documentation/git-rev-list.txt @@ -32,9 +32,9 @@ SYNOPSIS [ \--cherry-pick ] [ \--encoding[=<encoding>] ] [ \--(author|committer|grep)=<pattern> ] - [ \--regexp-ignore-case | \-i ] - [ \--extended-regexp | \-E ] - [ \--fixed-strings | \-F ] + [ \--regexp-ignore-case | -i ] + [ \--extended-regexp | -E ] + [ \--fixed-strings | -F ] [ \--date={local|relative|default|iso|rfc|short} ] [ [\--objects | \--objects-edge] [ \--unpacked ] ] [ \--pretty | \--header ] diff --git a/Documentation/git-send-email.txt b/Documentation/git-send-email.txt index 3c3e1b0e77..82f505686e 100644 --- a/Documentation/git-send-email.txt +++ b/Documentation/git-send-email.txt @@ -11,7 +11,6 @@ SYNOPSIS 'git send-email' [options] <file|directory> [... file|directory] - DESCRIPTION ----------- Takes the patches given on the command line and emails them out. @@ -20,12 +19,16 @@ The header of the email is configurable by command line options. If not specified on the command line, the user will be prompted with a ReadLine enabled interface to provide the necessary information. + OPTIONS ------- -The options available are: + +Composing +~~~~~~~~~ --bcc:: - Specify a "Bcc:" value for each email. + Specify a "Bcc:" value for each email. Default is the value of + 'sendemail.bcc'. + The --bcc option must be repeated for each user you want on the bcc list. @@ -34,22 +37,6 @@ The --bcc option must be repeated for each user you want on the bcc list. + The --cc option must be repeated for each user you want on the cc list. ---cc-cmd:: - Specify a command to execute once per patch file which - should generate patch file specific "Cc:" entries. - Output of this command must be single email address per line. - Default is the value of 'sendemail.cccmd' configuration value. - ---chain-reply-to:: ---no-chain-reply-to:: - If this is set, each email will be sent as a reply to the previous - email sent. If disabled with "--no-chain-reply-to", all emails after - the first will be sent as replies to the first email sent. When using - this, it is recommended that the first file given be an overview of the - entire patch series. - Default is the value of the 'sendemail.chainreplyto' configuration - value; if that is unspecified, default to --chain-reply-to. - --compose:: Use $GIT_EDITOR, core.editor, $VISUAL, or $EDITOR to edit an introductory message for the patch series. @@ -66,22 +53,47 @@ The --cc option must be repeated for each user you want on the cc list. Only necessary if --compose is also set. If --compose is not set, this will be prompted for. ---signed-off-by-cc:: ---no-signed-off-by-cc:: - If this is set, add emails found in Signed-off-by: or Cc: lines to the - cc list. - Default is the value of 'sendemail.signedoffcc' configuration value; - if that is unspecified, default to --signed-off-by-cc. +--subject:: + Specify the initial subject of the email thread. + Only necessary if --compose is also set. If --compose + is not set, this will be prompted for. + +--to:: + Specify the primary recipient of the emails generated. Generally, this + will be the upstream maintainer of the project involved. Default is the + value of the 'sendemail.to' configuration value; if that is unspecified, + this will be prompted for. ++ +The --to option must be repeated for each user you want on the to list. ---quiet:: - Make git-send-email less verbose. One line per email should be - all that is output. ---identity:: - A configuration identity. When given, causes values in the - 'sendemail.<identity>' subsection to take precedence over - values in the 'sendemail' section. The default identity is - the value of 'sendemail.identity'. +Sending +~~~~~~~ + +--envelope-sender:: + Specify the envelope sender used to send the emails. + This is useful if your default address is not the address that is + subscribed to a list. If you use the sendmail binary, you must have + suitable privileges for the -f parameter. Default is the value of + the 'sendemail.envelopesender' configuration variable; if that is + unspecified, choosing the envelope sender is left to your MTA. + +--smtp-encryption:: + Specify the encryption to use, either 'ssl' or 'tls'. Any other + value reverts to plain SMTP. Default is the value of + 'sendemail.smtpencryption'. + +--smtp-pass:: + Password for SMTP-AUTH. The argument is optional: If no + argument is specified, then the empty string is used as + the password. Default is the value of 'sendemail.smtppass', + however '--smtp-pass' always overrides this value. ++ +Furthermore, passwords need not be specified in configuration files +or on the command line. If a username has been specified (with +'--smtp-user' or a 'sendemail.smtpuser'), but no password has been +specified (with '--smtp-pass' or 'sendemail.smtppass'), then the +user is prompted for a password while the input is masked for privacy. --smtp-server:: If set, specifies the outgoing SMTP server to use (e.g. @@ -96,61 +108,44 @@ The --cc option must be repeated for each user you want on the cc list. --smtp-server-port:: Specifies a port different from the default port (SMTP servers typically listen to smtp port 25 and ssmtp port - 465). + 465). This can be set with 'sendemail.smtpserverport'. + +--smtp-ssl:: + Legacy alias for '--smtp-encryption ssl'. --smtp-user:: - Username for SMTP-AUTH. In place of this option, the following - configuration variables can be specified: -+ --- - * sendemail.smtpuser - * sendemail.<identity>.smtpuser (see sendemail.identity). --- -+ -However, --smtp-user always overrides these variables. -+ -If a username is not specified (with --smtp-user or a -configuration variable), then authentication is not attempted. + Username for SMTP-AUTH. Default is the value of 'sendemail.smtpuser'; + if a username is not specified (with '--smtp-user' or 'sendemail.smtpuser'), + then authentication is not attempted. ---smtp-pass:: - Password for SMTP-AUTH. The argument is optional: If no - argument is specified, then the empty string is used as - the password. -+ -In place of this option, the following configuration variables -can be specified: -+ --- - * sendemail.smtppass - * sendemail.<identity>.smtppass (see sendemail.identity). --- -+ -However, --smtp-pass always overrides these variables. -+ -Furthermore, passwords need not be specified in configuration files -or on the command line. If a username has been specified (with ---smtp-user or a configuration variable), but no password has been -specified (with --smtp-pass or a configuration variable), then the -user is prompted for a password while the input is masked for privacy. ---smtp-encryption:: - Specify the encryption to use, either 'ssl' or 'tls'. Any other - value reverts to plain SMTP. Default is the value of - 'sendemail.smtpencryption'. +Automating +~~~~~~~~~~ ---smtp-ssl:: - Legacy alias for '--smtp-encryption=ssl'. +--cc-cmd:: + Specify a command to execute once per patch file which + should generate patch file specific "Cc:" entries. + Output of this command must be single email address per line. + Default is the value of 'sendemail.cccmd' configuration value. ---subject:: - Specify the initial subject of the email thread. - Only necessary if --compose is also set. If --compose - is not set, this will be prompted for. +--[no-]chain-reply-to:: + If this is set, each email will be sent as a reply to the previous + email sent. If disabled with "--no-chain-reply-to", all emails after + the first will be sent as replies to the first email sent. When using + this, it is recommended that the first file given be an overview of the + entire patch series. Default is the value of the 'sendemail.chainreplyto' + configuration value; if that is unspecified, default to --chain-reply-to. + +--identity:: + A configuration identity. When given, causes values in the + 'sendemail.<identity>' subsection to take precedence over + values in the 'sendemail' section. The default identity is + the value of 'sendemail.identity'. ---suppress-from:: ---no-suppress-from:: - If this is set, do not add the From: address to the cc: list. - Default is the value of 'sendemail.suppressfrom' configuration value; - if that is unspecified, default to --no-suppress-from. +--[no-]signed-off-by-cc:: + If this is set, add emails found in Signed-off-by: or Cc: lines to the + cc list. Default is the value of 'sendemail.signedoffbycc' configuration + value; if that is unspecified, default to --signed-off-by-cc. --suppress-cc:: Specify an additional category of recipients to suppress the @@ -163,44 +158,43 @@ user is prompted for a password while the input is masked for privacy. if that is unspecified, default to 'self' if --suppress-from is specified, as well as 'sob' if --no-signed-off-cc is specified. ---thread:: ---no-thread:: +--[no-]suppress-from:: + If this is set, do not add the From: address to the cc: list. + Default is the value of 'sendemail.suppressfrom' configuration + value; if that is unspecified, default to --no-suppress-from. + +--[no-]thread:: If this is set, the In-Reply-To header will be set on each email sent. If disabled with "--no-thread", no emails will have the In-Reply-To - header set. - Default is the value of the 'sendemail.thread' configuration value; - if that is unspecified, default to --thread. + header set. Default is the value of the 'sendemail.thread' configuration + value; if that is unspecified, default to --thread. + + +Administering +~~~~~~~~~~~~~ --dry-run:: Do everything except actually send the emails. ---envelope-sender:: - Specify the envelope sender used to send the emails. - This is useful if your default address is not the address that is - subscribed to a list. If you use the sendmail binary, you must have - suitable privileges for the -f parameter. - Default is the value of the 'sendemail.envelopesender' configuration - variable; if that is unspecified, choosing the envelope sender is left - to your MTA. +--quiet:: + Make git-send-email less verbose. One line per email should be + all that is output. ---to:: - Specify the primary recipient of the emails generated. - Generally, this will be the upstream maintainer of the - project involved. - Default is the value of the 'sendemail.to' configuration value; - if that is unspecified, this will be prompted for. +--[no-]validate:: + Perform sanity checks on patches. + Currently, validation means the following: + -The --to option must be repeated for each user you want on the to list. +-- + * Warn of patches that contain lines longer than 998 characters; this + is due to SMTP limits as described by http://www.ietf.org/rfc/rfc2821.txt. +-- ++ +Default is the value of 'sendemail.validate'; if this is not set, +default to '--validate'. CONFIGURATION ------------- -sendemail.identity:: - The default configuration identity. When specified, - 'sendemail.<identity>.<item>' will have higher precedence than - 'sendemail.<item>'. This is useful to declare multiple SMTP - identities and to hoist sensitive authentication information - out of the repository and into the global configuration file. sendemail.aliasesfile:: To avoid typing long email addresses, point this to one or more @@ -210,38 +204,6 @@ sendemail.aliasfiletype:: Format of the file(s) specified in sendemail.aliasesfile. Must be one of 'mutt', 'mailrc', 'pine', or 'gnus'. -sendemail.to:: - Email address (or alias) to always send to. - -sendemail.cccmd:: - Command to execute to generate per patch file specific "Cc:"s. - -sendemail.bcc:: - Email address (or alias) to always bcc. - -sendemail.chainreplyto:: - Boolean value specifying the default to the '--chain_reply_to' - parameter. - -sendemail.smtpserver:: - Default SMTP server to use. - -sendemail.smtpserverport:: - Default SMTP server port to use. - -sendemail.smtpuser:: - Default SMTP-AUTH username. - -sendemail.smtppass:: - Default SMTP-AUTH password. - -sendemail.smtpencryption:: - Default encryption method. Use 'ssl' for SSL (and specify an - appropriate port), or 'tls' for TLS. Takes precedence over - 'smtpssl' if both are specified. - -sendemail.smtpssl:: - Legacy boolean that sets 'smtpencryption=ssl' if enabled. Author ------ @@ -250,10 +212,12 @@ Written by Ryan Anderson <ryan@michonline.com> git-send-email is originally based upon send_lots_of_email.pl by Greg Kroah-Hartman. + Documentation -------------- Documentation by Ryan Anderson + GIT --- Part of the linkgit:git[1] suite diff --git a/Documentation/git-svn.txt b/Documentation/git-svn.txt index 1e644ca6dc..84c8f3cde0 100644 --- a/Documentation/git-svn.txt +++ b/Documentation/git-svn.txt @@ -149,6 +149,22 @@ and have no uncommitted changes. is very strongly discouraged. -- +'branch':: + Create a branch in the SVN repository. + +-m;; +--message;; + Allows to specify the commit message. + +-t;; +--tag;; + Create a tag by using the tags_subdir instead of the branches_subdir + specified during git svn init. + +'tag':: + Create a tag in the SVN repository. This is a shorthand for + 'branch -t'. + 'log':: This should make it easy to look up svn log messages when svn users refer to -r/--revision numbers. @@ -372,7 +388,8 @@ Passed directly to 'git-rebase' when using 'dcommit' if a -n:: --dry-run:: -This can be used with the 'dcommit' and 'rebase' commands. +This can be used with the 'dcommit', 'rebase', 'branch' and 'tag' +commands. For 'dcommit', print out the series of git arguments that would show which diffs would be committed to SVN. @@ -381,6 +398,9 @@ For 'rebase', display the local branch associated with the upstream svn repository associated with the current branch and the URL of svn repository that will be fetched from. +For 'branch' and 'tag', display the urls that will be used for copying when +creating the branch or tag. + -- ADVANCED OPTIONS @@ -473,7 +493,7 @@ Tracking and contributing to the trunk of a Subversion-managed project: ------------------------------------------------------------------------ # Clone a repo (like git clone): - git svn clone http://svn.foo.org/project/trunk + git svn clone http://svn.example.com/project/trunk # Enter the newly cloned directory: cd trunk # You should be on master branch, double-check with git-branch @@ -495,9 +515,11 @@ Tracking and contributing to an entire Subversion-managed project ------------------------------------------------------------------------ # Clone a repo (like git clone): - git svn clone http://svn.foo.org/project -T trunk -b branches -t tags + git svn clone http://svn.example.com/project -T trunk -b branches -t tags # View all branches and tags you have cloned: git branch -r +# Create a new branch in SVN + git svn branch waldo # Reset your master to trunk (or any other branch, replacing 'trunk' # with the appropriate name): git reset --hard remotes/trunk @@ -514,7 +536,7 @@ have each person clone that repository with 'git-clone': ------------------------------------------------------------------------ # Do the initial import on a server - ssh server "cd /pub && git svn clone http://svn.foo.org/project + ssh server "cd /pub && git svn clone http://svn.example.com/project # Clone locally - make sure the refs/remotes/ space matches the server mkdir project cd project @@ -523,7 +545,7 @@ have each person clone that repository with 'git-clone': git config --add remote.origin.fetch '+refs/remotes/*:refs/remotes/*' git fetch # Initialize git-svn locally (be sure to use the same URL and -T/-b/-t options as were used on server) - git svn init http://svn.foo.org/project + git svn init http://svn.example.com/project # Pull the latest changes from Subversion git svn rebase ------------------------------------------------------------------------ diff --git a/Documentation/git-web--browse.txt b/Documentation/git-web--browse.txt index 7f7a45b2ea..278cf73527 100644 --- a/Documentation/git-web--browse.txt +++ b/Documentation/git-web--browse.txt @@ -26,6 +26,7 @@ The following browsers (or commands) are currently supported: * lynx * dillo * open (this is the default under Mac OS X GUI) +* start (this is the default under MinGW) Custom commands may also be specified. diff --git a/Documentation/gitattributes.txt b/Documentation/gitattributes.txt index 6f3551dc82..26945593cb 100644 --- a/Documentation/gitattributes.txt +++ b/Documentation/gitattributes.txt @@ -270,31 +270,31 @@ See linkgit:git[1] for details. Defining a custom hunk-header ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -Each group of changes (called "hunk") in the textual diff output +Each group of changes (called a "hunk") in the textual diff output is prefixed with a line of the form: @@ -k,l +n,m @@ TEXT -The text is called 'hunk header', and by default a line that -begins with an alphabet, an underscore or a dollar sign is used, -which matches what GNU 'diff -p' output uses. This default -selection however is not suited for some contents, and you can -use customized pattern to make a selection. +This is called a 'hunk header'. The "TEXT" portion is by default a line +that begins with an alphabet, an underscore or a dollar sign; this +matches what GNU 'diff -p' output uses. This default selection however +is not suited for some contents, and you can use a customized pattern +to make a selection. -First in .gitattributes, you would assign the `diff` attribute +First, in .gitattributes, you would assign the `diff` attribute for paths. ------------------------ *.tex diff=tex ------------------------ -Then, you would define "diff.tex.funcname" configuration to +Then, you would define a "diff.tex.xfuncname" configuration to specify a regular expression that matches a line that you would -want to appear as the hunk header, like this: +want to appear as the hunk header "TEXT", like this: ------------------------ [diff "tex"] - funcname = "^\\(\\\\\\(sub\\)*section{.*\\)$" + xfuncname = "^(\\\\(sub)*section\\{.*)$" ------------------------ Note. A single level of backslashes are eaten by the @@ -315,6 +315,8 @@ patterns are available: - `java` suitable for source code in the Java language. +- `objc` suitable for source code in the Objective-C language. + - `pascal` suitable for source code in the Pascal/Delphi language. - `php` suitable for source code in the PHP language. diff --git a/Documentation/gitdiffcore.txt b/Documentation/gitdiffcore.txt index 2bdbc3d4f6..e8041bc08f 100644 --- a/Documentation/gitdiffcore.txt +++ b/Documentation/gitdiffcore.txt @@ -36,11 +36,25 @@ files: - 'git-diff-tree' compares contents of two "tree" objects; -In all of these cases, the commands themselves compare -corresponding paths in the two sets of files. The result of -comparison is passed from these commands to what is internally -called "diffcore", in a format similar to what is output when -the -p option is not used. E.g. +In all of these cases, the commands themselves first optionally limit +the two sets of files by any pathspecs given on their command-lines, +and compare corresponding paths in the two resulting sets of files. + +The pathspecs are used to limit the world diff operates in. They remove +the filepairs outside the specified sets of pathnames. E.g. If the +input set of filepairs included: + +------------------------------------------------ +:100644 100644 bcd1234... 0123456... M junkfile +------------------------------------------------ + +but the command invocation was `git diff-files myfile`, then the +junkfile entry would be removed from the list because only "myfile" +is under consideration. + +The result of comparison is passed from these commands to what is +internally called "diffcore", in a format similar to what is output +when the -p option is not used. E.g. ------------------------------------------------ in-place edit :100644 100644 bcd1234... 0123456... M file0 @@ -52,9 +66,8 @@ unmerged :000000 000000 0000000... 0000000... U file6 The diffcore mechanism is fed a list of such comparison results (each of which is called "filepair", although at this point each of them talks about a single file), and transforms such a list -into another list. There are currently 6 such transformations: +into another list. There are currently 5 such transformations: -- diffcore-pathspec - diffcore-break - diffcore-rename - diffcore-merge-broken @@ -62,38 +75,14 @@ into another list. There are currently 6 such transformations: - diffcore-order These are applied in sequence. The set of filepairs 'git-diff-{asterisk}' -commands find are used as the input to diffcore-pathspec, and -the output from diffcore-pathspec is used as the input to the +commands find are used as the input to diffcore-break, and +the output from diffcore-break is used as the input to the next transformation. The final result is then passed to the output routine and generates either diff-raw format (see Output format sections of the manual for 'git-diff-{asterisk}' commands) or diff-patch format. -diffcore-pathspec: For Ignoring Files Outside Our Consideration ---------------------------------------------------------------- - -The first transformation in the chain is diffcore-pathspec, and -is controlled by giving the pathname parameters to the -'git-diff-{asterisk}' commands on the command line. The pathspec is used -to limit the world diff operates in. It removes the filepairs -outside the specified set of pathnames. E.g. If the input set -of filepairs included: - ------------------------------------------------- -:100644 100644 bcd1234... 0123456... M junkfile ------------------------------------------------- - -but the command invocation was `git diff-files myfile`, then the -junkfile entry would be removed from the list because only "myfile" -is under consideration. - -Implementation note. For performance reasons, 'git-diff-tree' -uses the pathname parameters on the command line to cull set of -filepairs it feeds the diffcore mechanism itself, and does not -use diffcore-pathspec, but the end result is the same. - - diffcore-break: For Splitting Up "Complete Rewrites" ---------------------------------------------------- diff --git a/Documentation/githooks.txt b/Documentation/githooks.txt index 046a2a7fe7..5faaaa5fed 100644 --- a/Documentation/githooks.txt +++ b/Documentation/githooks.txt @@ -87,12 +87,12 @@ default log message, and before the editor is started. It takes one to three parameters. The first is the name of the file that the commit log message. The second is the source of the commit -message, and can be: `message` (if a `\-m` or `\-F` option was -given); `template` (if a `\-t` option was given or the +message, and can be: `message` (if a `-m` or `-F` option was +given); `template` (if a `-t` option was given or the configuration option `commit.template` is set); `merge` (if the 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 SHA1 (if a `\-c`, `\-C` or `\--amend` option was given). +a commit SHA1 (if a `-c`, `-C` or `\--amend` option was given). If the exit status is non-zero, 'git-commit' will abort. @@ -130,6 +130,13 @@ parameter, and is invoked after a commit is made. This hook is meant primarily for notification, and cannot affect the outcome of 'git-commit'. +pre-rebase +---------- + +This hook is called by 'git-rebase' and can be used to prevent a branch +from getting rebased. + + post-checkout ----------- diff --git a/Documentation/gittutorial-2.txt b/Documentation/gittutorial-2.txt index 660904686c..bab0f34b45 100644 --- a/Documentation/gittutorial-2.txt +++ b/Documentation/gittutorial-2.txt @@ -32,22 +32,27 @@ Initialized empty Git repository in .git/ $ echo 'hello world' > file.txt $ git add . $ git commit -a -m "initial commit" -Created initial commit 54196cc2703dc165cbd373a65a4dcf22d50ae7f7 +[master (root-commit)] created 54196cc: "initial commit" + 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file.txt $ echo 'hello world!' >file.txt $ git commit -a -m "add emphasis" -Created commit c4d59f390b9cfd4318117afde11d601c1085f241 +[master] created c4d59f3: "add emphasis" + 1 files changed, 1 insertions(+), 1 deletions(-) ------------------------------------------------ -What are the 40 digits of hex that git responded to the commit with? +What are the 7 digits of hex that git responded to the commit with? We saw in part one of the tutorial that commits have names like this. It turns out that every object in the git history is stored under -such a 40-digit hex name. That name is the SHA1 hash of the object's +a 40-digit hex name. That name is the SHA1 hash of the object's contents; among other things, this ensures that git will never store the same data twice (since identical data is given an identical SHA1 name), and that the contents of a git object will never change (since -that would change the object's name as well). +that would change the object's name as well). The 7 char hex strings +here are simply the abbreviation of such 40 character long strings. +Abbreviations can be used everywhere where the 40 character strings +can be used, so long as they are unambiguous. It is expected that the content of the commit object you created while following the example above generates a different SHA1 hash than diff --git a/Documentation/howto/rebase-and-edit.txt b/Documentation/howto/rebase-and-edit.txt deleted file mode 100644 index 554909fe08..0000000000 --- a/Documentation/howto/rebase-and-edit.txt +++ /dev/null @@ -1,79 +0,0 @@ -Date: Sat, 13 Aug 2005 22:16:02 -0700 (PDT) -From: Linus Torvalds <torvalds@osdl.org> -To: Steve French <smfrench@austin.rr.com> -cc: git@vger.kernel.org -Subject: Re: sending changesets from the middle of a git tree -Abstract: In this article, Linus demonstrates how a broken commit - in a sequence of commits can be removed by rewinding the head and - reapplying selected changes. - -On Sat, 13 Aug 2005, Linus Torvalds wrote: - -> That's correct. Same things apply: you can move a patch over, and create a -> new one with a modified comment, but basically the _old_ commit will be -> immutable. - -Let me clarify. - -You can entirely _drop_ old branches, so commits may be immutable, but -nothing forces you to keep them. Of course, when you drop a commit, you'll -always end up dropping all the commits that depended on it, and if you -actually got somebody else to pull that commit you can't drop it from -_their_ repository, but undoing things is not impossible. - -For example, let's say that you've made a mess of things: you've committed -three commits "old->a->b->c", and you notice that "a" was broken, but you -want to save "b" and "c". What you can do is - - # Create a branch "broken" that is the current code - # for reference - git branch broken - - # Reset the main branch to three parents back: this - # effectively undoes the three top commits - git reset HEAD^^^ - git checkout -f - - # Check the result visually to make sure you know what's - # going on - gitk --all - - # Re-apply the two top ones from "broken" - # - # First "parent of broken" (aka b): - git-diff-tree -p broken^ | git-apply --index - git commit --reedit=broken^ - - # Then "top of broken" (aka c): - git-diff-tree -p broken | git-apply --index - git commit --reedit=broken - -and you've now re-applied (and possibly edited the comments) the two -commits b/c, and commit "a" is basically gone (it still exists in the -"broken" branch, of course). - -Finally, check out the end result again: - - # Look at the new commit history - gitk --all - -to see that everything looks sensible. - -And then, you can just remove the broken branch if you decide you really -don't want it: - - # remove 'broken' branch - git branch -d broken - - # Prune old objects if you're really really sure - git prune - -And yeah, I'm sure there are other ways of doing this. And as usual, the -above is totally untested, and I just wrote it down in this email, so if -I've done something wrong, you'll have to figure it out on your own ;) - - Linus -- -To unsubscribe from this list: send the line "unsubscribe git" in -the body of a message to majordomo@vger.kernel.org -More majordomo info at http://vger.kernel.org/majordomo-info.html diff --git a/Documentation/pretty-formats.txt b/Documentation/pretty-formats.txt index 388d4925e6..f18d33e00b 100644 --- a/Documentation/pretty-formats.txt +++ b/Documentation/pretty-formats.txt @@ -116,6 +116,7 @@ The placeholders are: - '%cr': committer date, relative - '%ct': committer date, UNIX timestamp - '%ci': committer date, ISO 8601 format +- '%d': ref names, like the --decorate option of linkgit:git-log[1] - '%e': encoding - '%s': subject - '%b': body diff --git a/Documentation/technical/api-run-command.txt b/Documentation/technical/api-run-command.txt index 75aa5d4923..82e9e831b6 100644 --- a/Documentation/technical/api-run-command.txt +++ b/Documentation/technical/api-run-command.txt @@ -30,7 +30,7 @@ Functions start_command() followed by finish_command(). Takes a pointer to a `struct child_process` that specifies the details. -`run_command_v_opt`, `run_command_v_opt_cd`, `run_command_v_opt_cd_env`:: +`run_command_v_opt`, `run_command_v_opt_cd_env`:: Convenience functions that encapsulate a sequence of start_command() followed by finish_command(). The argument argv @@ -294,7 +294,6 @@ PROGRAMS += git-mktag$X PROGRAMS += git-mktree$X PROGRAMS += git-pack-redundant$X PROGRAMS += git-patch-id$X -PROGRAMS += git-receive-pack$X PROGRAMS += git-send-pack$X PROGRAMS += git-shell$X PROGRAMS += git-show-index$X @@ -347,6 +346,7 @@ LIB_H += cache.h LIB_H += cache-tree.h LIB_H += commit.h LIB_H += compat/mingw.h +LIB_H += compat/cygwin.h LIB_H += csum-file.h LIB_H += decorate.h LIB_H += delta.h @@ -444,6 +444,7 @@ LIB_OBJS += log-tree.o LIB_OBJS += mailmap.o LIB_OBJS += match-trees.o LIB_OBJS += merge-file.o +LIB_OBJS += merge-recursive.o LIB_OBJS += name-hash.o LIB_OBJS += object.o LIB_OBJS += pack-check.o @@ -546,6 +547,7 @@ BUILTIN_OBJS += builtin-prune-packed.o BUILTIN_OBJS += builtin-prune.o BUILTIN_OBJS += builtin-push.o BUILTIN_OBJS += builtin-read-tree.o +BUILTIN_OBJS += builtin-receive-pack.o BUILTIN_OBJS += builtin-reflog.o BUILTIN_OBJS += builtin-remote.o BUILTIN_OBJS += builtin-rerere.o @@ -647,8 +649,8 @@ ifeq ($(uname_S),SunOS) NO_MEMMEM = YesPlease NO_HSTRERROR = YesPlease NO_MKDTEMP = YesPlease + OLD_ICONV = UnfortunatelyYes ifeq ($(uname_R),5.8) - NEEDS_LIBICONV = YesPlease NO_UNSETENV = YesPlease NO_SETENV = YesPlease NO_C99_FORMAT = YesPlease @@ -747,6 +749,9 @@ ifeq ($(uname_S),HP-UX) NO_SYS_SELECT_H = YesPlease SNPRINTF_RETURNS_BOGUS = YesPlease endif +ifneq (,$(findstring CYGWIN,$(uname_S))) + COMPAT_OBJS += compat/cygwin.o +endif ifneq (,$(findstring MINGW,$(uname_S))) NO_MMAP = YesPlease NO_PREAD = YesPlease @@ -1,5 +1,16 @@ #include "cache.h" +/* + * Do not use this for inspecting *tracked* content. When path is a + * symlink to a directory, we do not want to say it is a directory when + * dealing with tracked content in the working tree. + */ +int is_directory(const char *path) +{ + struct stat st; + return (!stat(path, &st) && S_ISDIR(st.st_mode)); +} + /* We allow "recursive" symbolic links. Only within reason, though. */ #define MAXDEPTH 5 @@ -17,7 +28,7 @@ const char *make_absolute_path(const char *path) die ("Too long path: %.*s", 60, path); while (depth--) { - if (stat(buf, &st) || !S_ISDIR(st.st_mode)) { + if (!is_directory(buf)) { char *last_slash = strrchr(buf, '/'); if (last_slash) { *last_slash = '\0'; diff --git a/archive-tar.c b/archive-tar.c index 13029619e5..ba890ebdec 100644 --- a/archive-tar.c +++ b/archive-tar.c @@ -124,11 +124,10 @@ static int write_tar_entry(struct archiver_args *args, unsigned int mode, void *buffer, unsigned long size) { struct ustar_header header; - struct strbuf ext_header; + struct strbuf ext_header = STRBUF_INIT; int err = 0; memset(&header, 0, sizeof(header)); - strbuf_init(&ext_header, 0); if (!sha1) { *header.typeflag = TYPEFLAG_GLOBAL_HEADER; @@ -211,10 +210,9 @@ static int write_tar_entry(struct archiver_args *args, static int write_global_extended_header(struct archiver_args *args) { const unsigned char *sha1 = args->commit_sha1; - struct strbuf ext_header; + struct strbuf ext_header = STRBUF_INIT; int err; - strbuf_init(&ext_header, 0); strbuf_append_ext_header(&ext_header, "comment", sha1_to_hex(sha1), 40); err = write_tar_entry(args, NULL, NULL, 0, 0, ext_header.buf, ext_header.len); @@ -15,7 +15,7 @@ static char const * const archive_usage[] = { #define USES_ZLIB_COMPRESSION 1 -const struct archiver { +static const struct archiver { const char *name; write_archive_fn_t write_archive; unsigned int flags; @@ -29,11 +29,10 @@ static void format_subst(const struct commit *commit, struct strbuf *buf) { char *to_free = NULL; - struct strbuf fmt; + struct strbuf fmt = STRBUF_INIT; if (src == buf->buf) to_free = strbuf_detach(buf, NULL); - strbuf_init(&fmt, 0); for (;;) { const char *b, *c; @@ -65,10 +64,9 @@ static void *sha1_file_to_archive(const char *path, const unsigned char *sha1, buffer = read_sha1_file(sha1, type, sizep); if (buffer && S_ISREG(mode)) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; size_t size = 0; - strbuf_init(&buf, 0); strbuf_attach(&buf, buffer, *sizep, *sizep + 1); convert_to_working_tree(path, buf.buf, buf.len, &buf); if (commit) diff --git a/arm/sha1.c b/arm/sha1.c index 9e3ae038e8..c61ad4aff9 100644 --- a/arm/sha1.c +++ b/arm/sha1.c @@ -8,9 +8,9 @@ #include <string.h> #include "sha1.h" -extern void sha_transform(uint32_t *hash, const unsigned char *data, uint32_t *W); +extern void arm_sha_transform(uint32_t *hash, const unsigned char *data, uint32_t *W); -void SHA1_Init(SHA_CTX *c) +void arm_SHA1_Init(arm_SHA_CTX *c) { c->len = 0; c->hash[0] = 0x67452301; @@ -20,7 +20,7 @@ void SHA1_Init(SHA_CTX *c) c->hash[4] = 0xc3d2e1f0; } -void SHA1_Update(SHA_CTX *c, const void *p, unsigned long n) +void arm_SHA1_Update(arm_SHA_CTX *c, const void *p, unsigned long n) { uint32_t workspace[80]; unsigned int partial; @@ -32,12 +32,12 @@ void SHA1_Update(SHA_CTX *c, const void *p, unsigned long n) if (partial) { done = 64 - partial; memcpy(c->buffer + partial, p, done); - sha_transform(c->hash, c->buffer, workspace); + arm_sha_transform(c->hash, c->buffer, workspace); partial = 0; } else done = 0; while (n >= done + 64) { - sha_transform(c->hash, p + done, workspace); + arm_sha_transform(c->hash, p + done, workspace); done += 64; } } else @@ -46,7 +46,7 @@ void SHA1_Update(SHA_CTX *c, const void *p, unsigned long n) memcpy(c->buffer + partial, p + done, n - done); } -void SHA1_Final(unsigned char *hash, SHA_CTX *c) +void arm_SHA1_Final(unsigned char *hash, arm_SHA_CTX *c) { uint64_t bitlen; uint32_t bitlen_hi, bitlen_lo; @@ -57,7 +57,7 @@ void SHA1_Final(unsigned char *hash, SHA_CTX *c) bitlen = c->len << 3; offset = c->len & 0x3f; padlen = ((offset < 56) ? 56 : (64 + 56)) - offset; - SHA1_Update(c, padding, padlen); + arm_SHA1_Update(c, padding, padlen); bitlen_hi = bitlen >> 32; bitlen_lo = bitlen & 0xffffffff; @@ -69,7 +69,7 @@ void SHA1_Final(unsigned char *hash, SHA_CTX *c) bits[5] = bitlen_lo >> 16; bits[6] = bitlen_lo >> 8; bits[7] = bitlen_lo; - SHA1_Update(c, bits, 8); + arm_SHA1_Update(c, bits, 8); for (i = 0; i < 5; i++) { uint32_t v = c->hash[i]; diff --git a/arm/sha1.h b/arm/sha1.h index 3952646349..b61b618486 100644 --- a/arm/sha1.h +++ b/arm/sha1.h @@ -7,12 +7,17 @@ #include <stdint.h> -typedef struct sha_context { +typedef struct { uint64_t len; uint32_t hash[5]; unsigned char buffer[64]; -} SHA_CTX; +} arm_SHA_CTX; -void SHA1_Init(SHA_CTX *c); -void SHA1_Update(SHA_CTX *c, const void *p, unsigned long n); -void SHA1_Final(unsigned char *hash, SHA_CTX *c); +void arm_SHA1_Init(arm_SHA_CTX *c); +void arm_SHA1_Update(arm_SHA_CTX *c, const void *p, unsigned long n); +void arm_SHA1_Final(unsigned char *hash, arm_SHA_CTX *c); + +#define git_SHA_CTX arm_SHA_CTX +#define git_SHA1_Init arm_SHA1_Init +#define git_SHA1_Update arm_SHA1_Update +#define git_SHA1_Final arm_SHA1_Final diff --git a/arm/sha1_arm.S b/arm/sha1_arm.S index 8c1cb99fb4..41e92636e0 100644 --- a/arm/sha1_arm.S +++ b/arm/sha1_arm.S @@ -10,7 +10,7 @@ */ .text - .globl sha_transform + .globl arm_sha_transform /* * void sha_transform(uint32_t *hash, const unsigned char *data, uint32_t *W); @@ -18,7 +18,7 @@ * note: the "data" pointer may be unaligned. */ -sha_transform: +arm_sha_transform: stmfd sp!, {r4 - r8, lr} @@ -168,5 +168,6 @@ void remove_branch_state(void) unlink(git_path("MERGE_HEAD")); unlink(git_path("MERGE_RR")); unlink(git_path("MERGE_MSG")); + unlink(git_path("MERGE_MODE")); unlink(git_path("SQUASH_MSG")); } diff --git a/builtin-add.c b/builtin-add.c index 7c874e3115..ea4e77169a 100644 --- a/builtin-add.c +++ b/builtin-add.c @@ -166,7 +166,7 @@ static const char ignore_error[] = "The following paths are ignored by one of your .gitignore files:\n"; static int verbose = 0, show_only = 0, ignored_too = 0, refresh_only = 0; -static int ignore_add_errors, addremove; +static int ignore_add_errors, addremove, intent_to_add; static struct option builtin_add_options[] = { OPT__DRY_RUN(&show_only), @@ -176,6 +176,7 @@ static struct option builtin_add_options[] = { OPT_BOOLEAN('p', "patch", &patch_interactive, "interactive patching"), OPT_BOOLEAN('f', "force", &ignored_too, "allow adding otherwise ignored files"), OPT_BOOLEAN('u', "update", &take_worktree_changes, "update tracked files"), + OPT_BOOLEAN('N', "intent-to-add", &intent_to_add, "record only the fact that the path will be added later"), OPT_BOOLEAN('A', "all", &addremove, "add all, noticing removal of tracked files"), OPT_BOOLEAN( 0 , "refresh", &refresh_only, "don't add, only refresh the index"), OPT_BOOLEAN( 0 , "ignore-errors", &ignore_add_errors, "just skip files which cannot be added because of errors"), @@ -246,6 +247,7 @@ int cmd_add(int argc, const char **argv, const char *prefix) flags = ((verbose ? ADD_CACHE_VERBOSE : 0) | (show_only ? ADD_CACHE_PRETEND : 0) | + (intent_to_add ? ADD_CACHE_INTENT : 0) | (ignore_add_errors ? ADD_CACHE_IGNORE_ERRORS : 0) | (!(addremove || take_worktree_changes) ? ADD_CACHE_IGNORE_REMOVAL : 0)); diff --git a/builtin-apply.c b/builtin-apply.c index 20bef1f21d..cfd8fceb90 100644 --- a/builtin-apply.c +++ b/builtin-apply.c @@ -13,6 +13,7 @@ #include "delta.h" #include "builtin.h" #include "string-list.h" +#include "dir.h" /* * --check turns on checking that the working tree matches the @@ -320,13 +321,12 @@ static char *find_name(const char *line, char *def, int p_value, int terminate) const char *start = line; if (*line == '"') { - struct strbuf name; + struct strbuf name = STRBUF_INIT; /* * Proposed "new-style" GNU patch/diff format; see * http://marc.theaimsgroup.com/?l=git&m=112927316408690&w=2 */ - strbuf_init(&name, 0); if (!unquote_c_style(&name, line, NULL)) { char *cp; @@ -674,11 +674,8 @@ static char *git_header_name(char *line, int llen) if (*line == '"') { const char *cp; - struct strbuf first; - struct strbuf sp; - - strbuf_init(&first, 0); - strbuf_init(&sp, 0); + struct strbuf first = STRBUF_INIT; + struct strbuf sp = STRBUF_INIT; if (unquote_c_style(&first, line, &second)) goto free_and_fail1; @@ -740,10 +737,9 @@ static char *git_header_name(char *line, int llen) */ for (second = name; second < line + llen; second++) { if (*second == '"') { - struct strbuf sp; + struct strbuf sp = STRBUF_INIT; const char *np; - strbuf_init(&sp, 0); if (unquote_c_style(&sp, second, NULL)) goto free_and_fail2; @@ -809,6 +805,13 @@ static int parse_git_header(char *line, int len, unsigned int size, struct patch * the default name from the header. */ patch->def_name = git_header_name(line, len); + if (patch->def_name && root) { + char *s = xmalloc(root_len + strlen(patch->def_name) + 1); + strcpy(s, root); + strcpy(s + root_len, patch->def_name); + free(patch->def_name); + patch->def_name = s; + } line += len; size -= len; @@ -1507,11 +1510,10 @@ static const char minuses[]= static void show_stats(struct patch *patch) { - struct strbuf qname; + struct strbuf qname = STRBUF_INIT; char *cp = patch->new_name ? patch->new_name : patch->old_name; int max, add, del; - strbuf_init(&qname, 0); quote_c_style(cp, &qname, NULL, 0); /* @@ -1696,7 +1698,7 @@ static int match_fragment(struct image *img, fixlen = ws_fix_copy(buf, orig, oldlen, ws_rule, NULL); /* Try fixing the line in the target */ - if (sizeof(tgtfixbuf) < tgtlen) + if (sizeof(tgtfixbuf) > tgtlen) tgtfix = tgtfixbuf; else tgtfix = xmalloc(tgtlen); @@ -2291,14 +2293,12 @@ static void add_to_fn_table(struct patch *patch) static int apply_data(struct patch *patch, struct stat *st, struct cache_entry *ce) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; struct image image; size_t len; char *img; struct patch *tpatch; - strbuf_init(&buf, 0); - if (!(patch->is_copy || patch->is_rename) && ((tpatch = in_fn_table(patch->old_name)) != NULL)) { if (tpatch == (struct patch *) -1) { @@ -2585,6 +2585,8 @@ static void build_fake_ancestor(struct patch *list, const char *filename) sha1_ptr = sha1; ce = make_cache_entry(patch->old_mode, sha1_ptr, name, 0, 0); + if (!ce) + die("make_cache_entry failed for path '%s'", name); if (add_index_entry(&result, ce, ADD_CACHE_OK_TO_ADD)) die ("Could not add %s to temporary index", name); } @@ -2735,15 +2737,7 @@ static void remove_file(struct patch *patch, int rmdir_empty) warning("unable to remove submodule %s", patch->old_name); } else if (!unlink(patch->old_name) && rmdir_empty) { - char *name = xstrdup(patch->old_name); - char *end = strrchr(name, '/'); - while (end) { - *end = 0; - if (rmdir(name)) - break; - end = strrchr(name, '/'); - } - free(name); + remove_path(patch->old_name); } } } @@ -2784,7 +2778,7 @@ static void add_index_file(const char *path, unsigned mode, void *buf, unsigned static int try_create_file(const char *path, unsigned int mode, const char *buf, unsigned long size) { int fd; - struct strbuf nbuf; + struct strbuf nbuf = STRBUF_INIT; if (S_ISGITLINK(mode)) { struct stat st; @@ -2803,7 +2797,6 @@ static int try_create_file(const char *path, unsigned int mode, const char *buf, if (fd < 0) return -1; - strbuf_init(&nbuf, 0); if (convert_to_working_tree(path, buf, size, &nbuf)) { size = nbuf.len; buf = nbuf.buf; @@ -2994,29 +2987,45 @@ static int write_out_results(struct patch *list, int skipped_patch) static struct lock_file lock_file; -static struct excludes { - struct excludes *next; - const char *path; -} *excludes; +static struct string_list limit_by_name; +static int has_include; +static void add_name_limit(const char *name, int exclude) +{ + struct string_list_item *it; + + it = string_list_append(name, &limit_by_name); + it->util = exclude ? NULL : (void *) 1; +} static int use_patch(struct patch *p) { const char *pathname = p->new_name ? p->new_name : p->old_name; - struct excludes *x = excludes; - while (x) { - if (fnmatch(x->path, pathname, 0) == 0) - return 0; - x = x->next; - } + int i; + + /* Paths outside are not touched regardless of "--include" */ if (0 < prefix_length) { int pathlen = strlen(pathname); if (pathlen <= prefix_length || memcmp(prefix, pathname, prefix_length)) return 0; } - return 1; + + /* See if it matches any of exclude/include rule */ + for (i = 0; i < limit_by_name.nr; i++) { + struct string_list_item *it = &limit_by_name.items[i]; + if (!fnmatch(it->string, pathname, 0)) + return (it->util != NULL); + } + + /* + * If we had any include, a path that does not match any rule is + * not used. Otherwise, we saw bunch of exclude rules (or none) + * and such a path is used. + */ + return !has_include; } + static void prefix_one(char **name) { char *old_name = *name; @@ -3049,13 +3058,12 @@ static void prefix_patches(struct patch *p) static int apply_patch(int fd, const char *filename, int options) { size_t offset; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; struct patch *list = NULL, **listp = &list; int skipped_patch = 0; /* FIXME - memory leak when using multiple patch files as inputs */ memset(&fn_table, 0, sizeof(struct string_list)); - strbuf_init(&buf, 0); patch_input_file = filename; read_patch_file(&buf, fd); offset = 0; @@ -3157,10 +3165,12 @@ int cmd_apply(int argc, const char **argv, const char *unused_prefix) continue; } if (!prefixcmp(arg, "--exclude=")) { - struct excludes *x = xmalloc(sizeof(*x)); - x->path = arg + 10; - x->next = excludes; - excludes = x; + add_name_limit(arg + 10, 1); + continue; + } + if (!prefixcmp(arg, "--include=")) { + add_name_limit(arg + 10, 0); + has_include = 1; continue; } if (!prefixcmp(arg, "-p")) { diff --git a/builtin-archive.c b/builtin-archive.c index 5ceec433fd..432ce2acc6 100644 --- a/builtin-archive.c +++ b/builtin-archive.c @@ -111,6 +111,8 @@ int cmd_archive(int argc, const char **argv, const char *prefix) { const char *remote = NULL; + git_config(git_default_config, NULL); + remote = extract_remote_arg(&argc, argv); if (remote) return run_remote_archiver(remote, argc, argv); diff --git a/builtin-blame.c b/builtin-blame.c index 6b7b9f4466..48cc0c175d 100644 --- a/builtin-blame.c +++ b/builtin-blame.c @@ -1132,6 +1132,8 @@ static int find_copy_in_parent(struct scoreboard *sb, if (!DIFF_FILE_VALID(p->one)) continue; /* does not exist in parent */ + if (S_ISGITLINK(p->one->mode)) + continue; /* ignore git links */ if (porigin && !strcmp(p->one->path, porigin->path)) /* find_move already dealt with this path */ continue; @@ -2060,7 +2062,7 @@ static struct commit *fake_working_tree_commit(const char *path, const char *con struct commit *commit; struct origin *origin; unsigned char head_sha1[20]; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; const char *ident; time_t now; int size, len; @@ -2080,7 +2082,6 @@ static struct commit *fake_working_tree_commit(const char *path, const char *con origin = make_origin(commit, path); - strbuf_init(&buf, 0); if (!contents_from || strcmp("-", contents_from)) { struct stat st; const char *read_from; diff --git a/builtin-branch.c b/builtin-branch.c index b1a2ad7a6b..8d634ff571 100644 --- a/builtin-branch.c +++ b/builtin-branch.c @@ -334,11 +334,10 @@ static void print_ref_item(struct ref_item *item, int maxwidth, int verbose, } if (verbose) { - struct strbuf subject; + struct strbuf subject = STRBUF_INIT; const char *sub = " **** invalid ref ****"; char stat[128]; - strbuf_init(&subject, 0); stat[0] = '\0'; commit = item->commit; diff --git a/builtin-cat-file.c b/builtin-cat-file.c index 3fba6b9e74..30d00a6664 100644 --- a/builtin-cat-file.c +++ b/builtin-cat-file.c @@ -189,9 +189,8 @@ static int batch_one_object(const char *obj_name, int print_contents) static int batch_objects(int print_contents) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; - strbuf_init(&buf, 0); while (strbuf_getline(&buf, stdin, '\n') != EOF) { int error = batch_one_object(buf.buf, print_contents); if (error) diff --git a/builtin-check-attr.c b/builtin-check-attr.c index cb783fc77e..4921341e33 100644 --- a/builtin-check-attr.c +++ b/builtin-check-attr.c @@ -2,21 +2,84 @@ #include "cache.h" #include "attr.h" #include "quote.h" +#include "parse-options.h" -static const char check_attr_usage[] = -"git check-attr attr... [--] pathname..."; +static int stdin_paths; +static const char * const check_attr_usage[] = { +"git check-attr attr... [--] pathname...", +"git check-attr --stdin attr... < <list-of-paths>", +NULL +}; + +static int null_term_line; + +static const struct option check_attr_options[] = { + OPT_BOOLEAN(0 , "stdin", &stdin_paths, "read file names from stdin"), + OPT_BOOLEAN('z', NULL, &null_term_line, + "input paths are terminated by a null character"), + OPT_END() +}; + +static void check_attr(int cnt, struct git_attr_check *check, + const char** name, const char *file) +{ + int j; + if (git_checkattr(file, cnt, check)) + die("git_checkattr died"); + for (j = 0; j < cnt; j++) { + const char *value = check[j].value; + + if (ATTR_TRUE(value)) + value = "set"; + else if (ATTR_FALSE(value)) + value = "unset"; + else if (ATTR_UNSET(value)) + value = "unspecified"; + + quote_c_style(file, NULL, stdout, 0); + printf(": %s: %s\n", name[j], value); + } +} + +static void check_attr_stdin_paths(int cnt, struct git_attr_check *check, + const char** name) +{ + struct strbuf buf, nbuf; + int line_termination = null_term_line ? 0 : '\n'; + + strbuf_init(&buf, 0); + strbuf_init(&nbuf, 0); + while (strbuf_getline(&buf, stdin, line_termination) != EOF) { + if (line_termination && buf.buf[0] == '"') { + strbuf_reset(&nbuf); + if (unquote_c_style(&nbuf, buf.buf, NULL)) + die("line is badly quoted"); + strbuf_swap(&buf, &nbuf); + } + check_attr(cnt, check, name, buf.buf); + maybe_flush_or_die(stdout, "attribute to stdout"); + } + strbuf_release(&buf); + strbuf_release(&nbuf); +} int cmd_check_attr(int argc, const char **argv, const char *prefix) { struct git_attr_check *check; int cnt, i, doubledash; + const char *errstr = NULL; + + argc = parse_options(argc, argv, check_attr_options, check_attr_usage, + PARSE_OPT_KEEP_DASHDASH); + if (!argc) + usage_with_options(check_attr_usage, check_attr_options); if (read_cache() < 0) { die("invalid cache"); } doubledash = -1; - for (i = 1; doubledash < 0 && i < argc; i++) { + for (i = 0; doubledash < 0 && i < argc; i++) { if (!strcmp(argv[i], "--")) doubledash = i; } @@ -24,41 +87,37 @@ int cmd_check_attr(int argc, const char **argv, const char *prefix) /* If there is no double dash, we handle only one attribute */ if (doubledash < 0) { cnt = 1; - doubledash = 1; + doubledash = 0; } else - cnt = doubledash - 1; + cnt = doubledash; doubledash++; - if (cnt <= 0 || argc < doubledash) - usage(check_attr_usage); + if (cnt <= 0) + errstr = "No attribute specified"; + else if (stdin_paths && doubledash < argc) + errstr = "Can't specify files with --stdin"; + if (errstr) { + error (errstr); + usage_with_options(check_attr_usage, check_attr_options); + } + check = xcalloc(cnt, sizeof(*check)); for (i = 0; i < cnt; i++) { const char *name; struct git_attr *a; - name = argv[i + 1]; + name = argv[i]; a = git_attr(name, strlen(name)); if (!a) return error("%s: not a valid attribute name", name); check[i].attr = a; } - for (i = doubledash; i < argc; i++) { - int j; - if (git_checkattr(argv[i], cnt, check)) - die("git_checkattr died"); - for (j = 0; j < cnt; j++) { - const char *value = check[j].value; - - if (ATTR_TRUE(value)) - value = "set"; - else if (ATTR_FALSE(value)) - value = "unset"; - else if (ATTR_UNSET(value)) - value = "unspecified"; - - quote_c_style(argv[i], NULL, stdout, 0); - printf(": %s: %s\n", argv[j+1], value); - } + if (stdin_paths) + check_attr_stdin_paths(cnt, check, argv); + else { + for (i = doubledash; i < argc; i++) + check_attr(cnt, check, argv, argv[i]); + maybe_flush_or_die(stdout, "attribute to stdout"); } return 0; } diff --git a/builtin-checkout-index.c b/builtin-checkout-index.c index 55b7aafe06..4ba27024c5 100644 --- a/builtin-checkout-index.c +++ b/builtin-checkout-index.c @@ -268,13 +268,11 @@ int cmd_checkout_index(int argc, const char **argv, const char *prefix) } if (read_from_stdin) { - struct strbuf buf, nbuf; + struct strbuf buf = STRBUF_INIT, nbuf = STRBUF_INIT; if (all) die("git checkout-index: don't mix '--all' and '--stdin'"); - strbuf_init(&buf, 0); - strbuf_init(&nbuf, 0); while (strbuf_getline(&buf, stdin, line_termination) != EOF) { const char *p; if (line_termination && buf.buf[0] == '"') { diff --git a/builtin-checkout.c b/builtin-checkout.c index d986ac7abb..57b94d2829 100644 --- a/builtin-checkout.c +++ b/builtin-checkout.c @@ -13,6 +13,9 @@ #include "diff.h" #include "revision.h" #include "remote.h" +#include "blob.h" +#include "xdiff-interface.h" +#include "ll-merge.h" static const char * const checkout_usage[] = { "git checkout [options] <branch>", @@ -20,6 +23,18 @@ static const char * const checkout_usage[] = { NULL, }; +struct checkout_opts { + int quiet; + int merge; + int force; + int writeout_stage; + int writeout_error; + + const char *new_branch; + int new_branch_log; + enum branch_track track; +}; + static int post_checkout_hook(struct commit *old, struct commit *new, int changed) { @@ -84,8 +99,121 @@ static int skip_same_name(struct cache_entry *ce, int pos) return pos; } +static int check_stage(int stage, struct cache_entry *ce, int pos) +{ + while (pos < active_nr && + !strcmp(active_cache[pos]->name, ce->name)) { + if (ce_stage(active_cache[pos]) == stage) + return 0; + pos++; + } + return error("path '%s' does not have %s version", + ce->name, + (stage == 2) ? "our" : "their"); +} + +static int check_all_stages(struct cache_entry *ce, int pos) +{ + if (ce_stage(ce) != 1 || + active_nr <= pos + 2 || + strcmp(active_cache[pos+1]->name, ce->name) || + ce_stage(active_cache[pos+1]) != 2 || + strcmp(active_cache[pos+2]->name, ce->name) || + ce_stage(active_cache[pos+2]) != 3) + return error("path '%s' does not have all three versions", + ce->name); + return 0; +} + +static int checkout_stage(int stage, struct cache_entry *ce, int pos, + struct checkout *state) +{ + while (pos < active_nr && + !strcmp(active_cache[pos]->name, ce->name)) { + if (ce_stage(active_cache[pos]) == stage) + return checkout_entry(active_cache[pos], state, NULL); + pos++; + } + return error("path '%s' does not have %s version", + ce->name, + (stage == 2) ? "our" : "their"); +} + +/* NEEDSWORK: share with merge-recursive */ +static void fill_mm(const unsigned char *sha1, mmfile_t *mm) +{ + unsigned long size; + enum object_type type; + + if (!hashcmp(sha1, null_sha1)) { + mm->ptr = xstrdup(""); + mm->size = 0; + return; + } + + mm->ptr = read_sha1_file(sha1, &type, &size); + if (!mm->ptr || type != OBJ_BLOB) + die("unable to read blob object %s", sha1_to_hex(sha1)); + mm->size = size; +} + +static int checkout_merged(int pos, struct checkout *state) +{ + struct cache_entry *ce = active_cache[pos]; + const char *path = ce->name; + mmfile_t ancestor, ours, theirs; + int status; + unsigned char sha1[20]; + mmbuffer_t result_buf; + + if (ce_stage(ce) != 1 || + active_nr <= pos + 2 || + strcmp(active_cache[pos+1]->name, path) || + ce_stage(active_cache[pos+1]) != 2 || + strcmp(active_cache[pos+2]->name, path) || + ce_stage(active_cache[pos+2]) != 3) + return error("path '%s' does not have all 3 versions", path); + + fill_mm(active_cache[pos]->sha1, &ancestor); + fill_mm(active_cache[pos+1]->sha1, &ours); + fill_mm(active_cache[pos+2]->sha1, &theirs); + + status = ll_merge(&result_buf, path, &ancestor, + &ours, "ours", &theirs, "theirs", 1); + free(ancestor.ptr); + free(ours.ptr); + free(theirs.ptr); + if (status < 0 || !result_buf.ptr) { + free(result_buf.ptr); + return error("path '%s': cannot merge", path); + } + + /* + * NEEDSWORK: + * There is absolutely no reason to write this as a blob object + * and create a phoney cache entry just to leak. This hack is + * primarily to get to the write_entry() machinery that massages + * the contents to work-tree format and writes out which only + * allows it for a cache entry. The code in write_entry() needs + * to be refactored to allow us to feed a <buffer, size, mode> + * instead of a cache entry. Such a refactoring would help + * merge_recursive as well (it also writes the merge result to the + * object database even when it may contain conflicts). + */ + if (write_sha1_file(result_buf.ptr, result_buf.size, + blob_type, sha1)) + die("Unable to add merge result for '%s'", path); + ce = make_cache_entry(create_ce_mode(active_cache[pos+1]->ce_mode), + sha1, + path, 2, 0); + if (!ce) + die("make_cache_entry failed for path '%s'", path); + status = checkout_entry(ce, state, NULL); + return status; +} -static int checkout_paths(struct tree *source_tree, const char **pathspec) +static int checkout_paths(struct tree *source_tree, const char **pathspec, + struct checkout_opts *opts) { int pos; struct checkout state; @@ -94,7 +222,8 @@ static int checkout_paths(struct tree *source_tree, const char **pathspec) int flag; struct commit *head; int errs = 0; - + int stage = opts->writeout_stage; + int merge = opts->merge; int newfd; struct lock_file *lock_file = xcalloc(1, sizeof(struct lock_file)); @@ -122,8 +251,16 @@ static int checkout_paths(struct tree *source_tree, const char **pathspec) if (pathspec_match(pathspec, NULL, ce->name, 0)) { if (!ce_stage(ce)) continue; - errs = 1; - error("path '%s' is unmerged", ce->name); + if (opts->force) { + warning("path '%s' is unmerged", ce->name); + } else if (stage) { + errs |= check_stage(stage, ce, pos); + } else if (opts->merge) { + errs |= check_all_stages(ce, pos); + } else { + errs = 1; + error("path '%s' is unmerged", ce->name); + } pos = skip_same_name(ce, pos) - 1; } } @@ -141,6 +278,10 @@ static int checkout_paths(struct tree *source_tree, const char **pathspec) errs |= checkout_entry(ce, &state, NULL); continue; } + if (stage) + errs |= checkout_stage(stage, ce, pos, &state); + else if (merge) + errs |= checkout_merged(pos, &state); pos = skip_same_name(ce, pos) - 1; } } @@ -169,8 +310,7 @@ static void show_local_changes(struct object *head) static void describe_detached_head(char *msg, struct commit *commit) { - struct strbuf sb; - strbuf_init(&sb, 0); + struct strbuf sb = STRBUF_INIT; parse_commit(commit); pretty_print_commit(CMIT_FMT_ONELINE, commit, &sb, 0, NULL, NULL, 0, 0); fprintf(stderr, "%s %s... %s\n", msg, @@ -178,17 +318,6 @@ static void describe_detached_head(char *msg, struct commit *commit) strbuf_release(&sb); } -struct checkout_opts { - int quiet; - int merge; - int force; - int writeout_error; - - const char *new_branch; - int new_branch_log; - enum branch_track track; -}; - static int reset_tree(struct tree *tree, struct checkout_opts *o, int worktree) { struct unpack_trees_options opts; @@ -230,8 +359,7 @@ struct branch_info { static void setup_branch_path(struct branch_info *branch) { - struct strbuf buf; - strbuf_init(&buf, 0); + struct strbuf buf = STRBUF_INIT; strbuf_addstr(&buf, "refs/heads/"); strbuf_addstr(&buf, branch->name); branch->path = strbuf_detach(&buf, NULL); @@ -269,6 +397,8 @@ static int merge_working_tree(struct checkout_opts *opts, } /* 2-way merge to the new branch */ + topts.initial_checkout = (!active_nr && + (old->commit == new->commit)); topts.update = 1; topts.merge = 1; topts.gently = opts->merge; @@ -291,6 +421,7 @@ static int merge_working_tree(struct checkout_opts *opts, */ struct tree *result; struct tree *work; + struct merge_options o; if (!opts->merge) return 1; parse_commit(old->commit); @@ -309,13 +440,17 @@ static int merge_working_tree(struct checkout_opts *opts, */ add_files_to_cache(NULL, NULL, 0); - work = write_tree_from_memory(); + init_merge_options(&o); + o.verbosity = 0; + work = write_tree_from_memory(&o); ret = reset_tree(new->commit->tree, opts, 1); if (ret) return ret; - merge_trees(new->commit->tree, work, old->commit->tree, - new->name, "local", &result); + o.branch1 = new->name; + o.branch2 = "local"; + merge_trees(&o, new->commit->tree, work, + old->commit->tree, &result); ret = reset_tree(new->commit->tree, opts, 0); if (ret) return ret; @@ -326,7 +461,7 @@ static int merge_working_tree(struct checkout_opts *opts, commit_locked_index(lock_file)) die("unable to write new index file"); - if (!opts->force) + if (!opts->force && !opts->quiet) show_local_changes(&new->commit->object); return 0; @@ -347,7 +482,7 @@ static void update_refs_for_switch(struct checkout_opts *opts, struct branch_info *old, struct branch_info *new) { - struct strbuf msg; + struct strbuf msg = STRBUF_INIT; const char *old_desc; if (opts->new_branch) { create_branch(old->name, opts->new_branch, new->name, 0, @@ -356,7 +491,6 @@ static void update_refs_for_switch(struct checkout_opts *opts, setup_branch_path(new); } - strbuf_init(&msg, 0); old_desc = old->name; if (!old_desc) old_desc = sha1_to_hex(old->commit->object.sha1); @@ -438,6 +572,11 @@ static int switch_branches(struct checkout_opts *opts, struct branch_info *new) return ret || opts->writeout_error; } +static int git_checkout_config(const char *var, const char *value, void *cb) +{ + return git_xmerge_config(var, value, cb); +} + int cmd_checkout(int argc, const char **argv, const char *prefix) { struct checkout_opts opts; @@ -445,14 +584,21 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) const char *arg; struct branch_info new; struct tree *source_tree = NULL; + char *conflict_style = NULL; struct option options[] = { OPT__QUIET(&opts.quiet), OPT_STRING('b', NULL, &opts.new_branch, "new branch", "branch"), OPT_BOOLEAN('l', NULL, &opts.new_branch_log, "log for new branch"), OPT_SET_INT('t', "track", &opts.track, "track", BRANCH_TRACK_EXPLICIT), + OPT_SET_INT('2', "ours", &opts.writeout_stage, "stage", + 2), + OPT_SET_INT('3', "theirs", &opts.writeout_stage, "stage", + 3), OPT_BOOLEAN('f', NULL, &opts.force, "force"), - OPT_BOOLEAN('m', NULL, &opts.merge, "merge"), + OPT_BOOLEAN('m', "merge", &opts.merge, "merge"), + OPT_STRING(0, "conflict", &conflict_style, "style", + "conflict style (merge or diff3)"), OPT_END(), }; int has_dash_dash; @@ -460,7 +606,7 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) memset(&opts, 0, sizeof(opts)); memset(&new, 0, sizeof(new)); - git_config(git_default_config, NULL); + git_config(git_checkout_config, NULL); opts.track = BRANCH_TRACK_UNSPECIFIED; @@ -484,6 +630,10 @@ int cmd_checkout(int argc, const char **argv, const char *prefix) if (opts.track == BRANCH_TRACK_UNSPECIFIED) opts.track = git_branch_track; + if (conflict_style) { + opts.merge = 1; /* implied */ + git_xmerge_config("merge.conflictstyle", conflict_style, NULL); + } if (opts.force && opts.merge) die("git checkout: -f and -m are incompatible"); @@ -567,20 +717,36 @@ no_reference: die("invalid path specification"); /* Checkout paths */ - if (opts.new_branch || opts.force || opts.merge) { + if (opts.new_branch) { if (argc == 1) { - die("git checkout: updating paths is incompatible with switching branches/forcing\nDid you intend to checkout '%s' which can not be resolved as commit?", argv[0]); + die("git checkout: updating paths is incompatible with switching branches.\nDid you intend to checkout '%s' which can not be resolved as commit?", argv[0]); } else { - die("git checkout: updating paths is incompatible with switching branches/forcing"); + die("git checkout: updating paths is incompatible with switching branches."); } } - return checkout_paths(source_tree, pathspec); + if (1 < !!opts.writeout_stage + !!opts.force + !!opts.merge) + die("git checkout: --ours/--theirs, --force and --merge are incompatible when\nchecking out of the index."); + + return checkout_paths(source_tree, pathspec, &opts); + } + + if (opts.new_branch) { + struct strbuf buf = STRBUF_INIT; + strbuf_addstr(&buf, "refs/heads/"); + strbuf_addstr(&buf, opts.new_branch); + if (!get_sha1(buf.buf, rev)) + die("git checkout: branch %s already exists", opts.new_branch); + if (check_ref_format(buf.buf)) + die("git checkout: we do not like '%s' as a branch name.", opts.new_branch); + strbuf_release(&buf); } if (new.name && !new.commit) { die("Cannot switch branch to a non-commit."); } + if (opts.writeout_stage) + die("--ours/--theirs is incompatible with switching branches."); return switch_branches(&opts, &new); } diff --git a/builtin-clean.c b/builtin-clean.c index 48bf29f40a..f78c2fb108 100644 --- a/builtin-clean.c +++ b/builtin-clean.c @@ -31,11 +31,11 @@ int cmd_clean(int argc, const char **argv, const char *prefix) int i; int show_only = 0, remove_directories = 0, quiet = 0, ignored = 0; int ignored_only = 0, baselen = 0, config_set = 0, errors = 0; - struct strbuf directory; + struct strbuf directory = STRBUF_INIT; struct dir_struct dir; const char *path, *base; static const char **pathspec; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; const char *qname; char *seen = NULL; struct option options[] = { @@ -58,7 +58,6 @@ int cmd_clean(int argc, const char **argv, const char *prefix) argc = parse_options(argc, argv, options, builtin_clean_usage, 0); - strbuf_init(&buf, 0); memset(&dir, 0, sizeof(dir)); if (ignored_only) dir.show_ignored = 1; @@ -88,7 +87,6 @@ int cmd_clean(int argc, const char **argv, const char *prefix) if (baselen) path = base = xmemdupz(*pathspec, baselen); read_directory(&dir, path, base, baselen, pathspec); - strbuf_init(&directory, 0); if (pathspec) seen = xmalloc(argc > 0 ? argc : 1); diff --git a/builtin-clone.c b/builtin-clone.c index c8435295ce..8e1a1d3995 100644 --- a/builtin-clone.c +++ b/builtin-clone.c @@ -38,9 +38,11 @@ static int option_local, option_no_hardlinks, option_shared; static char *option_template, *option_reference, *option_depth; static char *option_origin = NULL; static char *option_upload_pack = "git-upload-pack"; +static int option_verbose; static struct option builtin_clone_options[] = { OPT__QUIET(&option_quiet), + OPT__VERBOSE(&option_verbose), OPT_BOOLEAN('n', "no-checkout", &option_no_checkout, "don't create a checkout"), OPT_BOOLEAN(0, "bare", &option_bare, "create a bare repository"), @@ -58,7 +60,7 @@ static struct option builtin_clone_options[] = { OPT_STRING(0, "reference", &option_reference, "repo", "reference repository"), OPT_STRING('o', "origin", &option_origin, "branch", - "use <branch> instead or 'origin' to track upstream"), + "use <branch> instead of 'origin' to track upstream"), OPT_STRING('u', "upload-pack", &option_upload_pack, "path", "path to git-upload-pack on the remote"), OPT_STRING(0, "depth", &option_depth, "depth", @@ -77,7 +79,7 @@ static char *get_repo_path(const char *repo, int *is_bundle) for (i = 0; i < ARRAY_SIZE(suffix); i++) { const char *path; path = mkpath("%s%s", repo, suffix[i]); - if (!stat(path, &st) && S_ISDIR(st.st_mode)) { + if (is_directory(path)) { *is_bundle = 0; return xstrdup(make_nonrelative_path(path)); } @@ -140,13 +142,6 @@ static char *guess_dir_name(const char *repo, int is_bundle, int is_bare) return xstrndup(start, end - start); } -static int is_directory(const char *path) -{ - struct stat buf; - - return !stat(path, &buf) && S_ISDIR(buf.st_mode); -} - static void strip_trailing_slashes(char *dir) { char *end = dir + strlen(dir); @@ -271,10 +266,9 @@ pid_t junk_pid; static void remove_junk(void) { - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; if (getpid() != junk_pid) return; - strbuf_init(&sb, 0); if (junk_git_dir) { strbuf_addstr(&sb, junk_git_dir); remove_dir_recursively(&sb, 0); @@ -361,7 +355,7 @@ int cmd_clone(int argc, const char **argv, const char *prefix) char *path, *dir; const struct ref *refs, *head_points_at, *remote_head, *mapped_refs; char branch_top[256], key[256], value[256]; - struct strbuf reflog_msg; + struct strbuf reflog_msg = STRBUF_INIT; struct transport *transport = NULL; char *src_ref_prefix = "refs/heads/"; @@ -411,7 +405,6 @@ int cmd_clone(int argc, const char **argv, const char *prefix) if (!stat(dir, &buf)) die("destination directory '%s' already exists.", dir); - strbuf_init(&reflog_msg, 0); strbuf_addf(&reflog_msg, "clone: from %s", repo); if (option_bare) @@ -513,6 +506,8 @@ int cmd_clone(int argc, const char **argv, const char *prefix) if (option_quiet) transport->verbose = -1; + else if (option_verbose) + transport->progress = 1; if (option_upload_pack) transport_set_option(transport, TRANS_OPT_UPLOADPACK, @@ -533,7 +528,7 @@ int cmd_clone(int argc, const char **argv, const char *prefix) create_symref("HEAD", head_points_at->name, NULL); if (!option_bare) { - struct strbuf head_ref; + struct strbuf head_ref = STRBUF_INIT; const char *head = head_points_at->name; if (!prefixcmp(head, "refs/heads/")) @@ -546,7 +541,6 @@ int cmd_clone(int argc, const char **argv, const char *prefix) head_points_at->old_sha1, NULL, 0, DIE_ON_ERR); - strbuf_init(&head_ref, 0); strbuf_addstr(&head_ref, branch_top); strbuf_addstr(&head_ref, "HEAD"); diff --git a/builtin-commit-tree.c b/builtin-commit-tree.c index f2684bb75e..0453425c47 100644 --- a/builtin-commit-tree.c +++ b/builtin-commit-tree.c @@ -46,7 +46,8 @@ static const char commit_utf8_warn[] = "variable i18n.commitencoding to the encoding your project uses.\n"; int commit_tree(const char *msg, unsigned char *tree, - struct commit_list *parents, unsigned char *ret) + struct commit_list *parents, unsigned char *ret, + const char *author) { int result; int encoding_is_utf8; @@ -74,7 +75,9 @@ int commit_tree(const char *msg, unsigned char *tree, } /* Person/date information */ - strbuf_addf(&buffer, "author %s\n", git_author_info(IDENT_ERROR_ON_NO_NAME)); + if (!author) + author = git_author_info(IDENT_ERROR_ON_NO_NAME); + strbuf_addf(&buffer, "author %s\n", author); strbuf_addf(&buffer, "committer %s\n", git_committer_info(IDENT_ERROR_ON_NO_NAME)); if (!encoding_is_utf8) strbuf_addf(&buffer, "encoding %s\n", git_commit_encoding); @@ -123,7 +126,7 @@ int cmd_commit_tree(int argc, const char **argv, const char *prefix) if (strbuf_read(&buffer, 0, 0) < 0) die("git commit-tree: read returned %s", strerror(errno)); - if (!commit_tree(buffer.buf, tree_sha1, parents, commit_sha1)) { + if (!commit_tree(buffer.buf, tree_sha1, parents, commit_sha1, NULL)) { printf("%s\n", sha1_to_hex(commit_sha1)); return 0; } diff --git a/builtin-commit.c b/builtin-commit.c index 8165bb3d31..33b659edce 100644 --- a/builtin-commit.c +++ b/builtin-commit.c @@ -448,7 +448,7 @@ static int prepare_to_commit(const char *index_file, const char *prefix) { struct stat statbuf; int commitable, saved_color_setting; - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; char *buffer; FILE *fp; const char *hook_arg1 = NULL; @@ -458,7 +458,6 @@ static int prepare_to_commit(const char *index_file, const char *prefix) if (!no_verify && run_hook(index_file, "pre-commit", NULL)) return 0; - strbuf_init(&sb, 0); if (message.len) { strbuf_addbuf(&sb, &message); hook_arg1 = "message"; @@ -511,10 +510,9 @@ static int prepare_to_commit(const char *index_file, const char *prefix) stripspace(&sb, 0); if (signoff) { - struct strbuf sob; + struct strbuf sob = STRBUF_INIT; int i; - strbuf_init(&sob, 0); strbuf_addstr(&sob, sign_off_header); strbuf_addstr(&sob, fmt_name(getenv("GIT_COMMITTER_NAME"), getenv("GIT_COMMITTER_EMAIL"))); @@ -639,7 +637,7 @@ static int prepare_to_commit(const char *index_file, const char *prefix) active_cache_tree = cache_tree(); if (cache_tree_update(active_cache_tree, active_cache, active_nr, 0, 0) < 0) { - error("Error building trees"); + error("Error building trees; the index is unmerged?"); return 0; } @@ -667,20 +665,19 @@ static int prepare_to_commit(const char *index_file, const char *prefix) } /* - * Find out if the message starting at position 'start' in the strbuf - * contains only whitespace and Signed-off-by lines. + * Find out if the message in the strbuf contains only whitespace and + * Signed-off-by lines. */ -static int message_is_empty(struct strbuf *sb, int start) +static int message_is_empty(struct strbuf *sb) { - struct strbuf tmpl; + struct strbuf tmpl = STRBUF_INIT; const char *nl; - int eol, i; + int eol, i, start = 0; if (cleanup_mode == CLEANUP_NONE && sb->len) return 0; /* See if the template is just a prefix of the message. */ - strbuf_init(&tmpl, 0); if (template_file && strbuf_read_file(&tmpl, template_file, 0) > 0) { stripspace(&tmpl, cleanup_mode == CLEANUP_ALL); if (start + tmpl.len <= sb->len && @@ -882,6 +879,9 @@ static void print_summary(const char *prefix, const unsigned char *sha1) { struct rev_info rev; struct commit *commit; + static const char *format = "format:%h: \"%s\""; + unsigned char junk_sha1[20]; + const char *head = resolve_ref("HEAD", junk_sha1, 0, NULL); commit = lookup_commit(sha1); if (!commit) @@ -899,18 +899,24 @@ static void print_summary(const char *prefix, const unsigned char *sha1) rev.verbose_header = 1; rev.show_root_diff = 1; - get_commit_format("format:%h: %s", &rev); + get_commit_format(format, &rev); rev.always_show_header = 0; rev.diffopt.detect_rename = 1; rev.diffopt.rename_limit = 100; rev.diffopt.break_opt = 0; diff_setup_done(&rev.diffopt); - printf("Created %scommit ", initial_commit ? "initial " : ""); + printf("[%s%s]: created ", + !prefixcmp(head, "refs/heads/") ? + head + 11 : + !strcmp(head, "HEAD") ? + "detached HEAD" : + head, + initial_commit ? " (root-commit)" : ""); if (!log_tree_commit(&rev, commit)) { struct strbuf buf = STRBUF_INIT; - format_commit_message(commit, "%h: %s", &buf, DATE_NORMAL); + format_commit_message(commit, format + 7, &buf, DATE_NORMAL); printf("%s\n", buf.buf); strbuf_release(&buf); } @@ -929,34 +935,16 @@ static const char commit_utf8_warn[] = "You may want to amend it after fixing the message, or set the config\n" "variable i18n.commitencoding to the encoding your project uses.\n"; -static void add_parent(struct strbuf *sb, const unsigned char *sha1) -{ - struct object *obj = parse_object(sha1); - const char *parent = sha1_to_hex(sha1); - const char *cp; - - if (!obj) - die("Unable to find commit parent %s", parent); - if (obj->type != OBJ_COMMIT) - die("Parent %s isn't a proper commit", parent); - - for (cp = sb->buf; cp && (cp = strstr(cp, "\nparent ")); cp += 8) { - if (!memcmp(cp + 8, parent, 40) && cp[48] == '\n') { - error("duplicate parent %s ignored", parent); - return; - } - } - strbuf_addf(sb, "parent %s\n", parent); -} - int cmd_commit(int argc, const char **argv, const char *prefix) { - int header_len; - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; const char *index_file, *reflog_msg; char *nl, *p; unsigned char commit_sha1[20]; struct ref_lock *ref_lock; + struct commit_list *parents = NULL, **pptr = &parents; + struct stat statbuf; + int allow_fast_forward = 1; git_config(git_commit_config, NULL); @@ -971,13 +959,6 @@ int cmd_commit(int argc, const char **argv, const char *prefix) return 1; } - /* - * The commit object - */ - strbuf_init(&sb, 0); - strbuf_addf(&sb, "tree %s\n", - sha1_to_hex(active_cache_tree->sha1)); - /* Determine parents */ if (initial_commit) { reflog_msg = "commit (initial)"; @@ -991,14 +972,13 @@ int cmd_commit(int argc, const char **argv, const char *prefix) die("could not parse HEAD commit"); for (c = commit->parents; c; c = c->next) - add_parent(&sb, c->item->object.sha1); + pptr = &commit_list_insert(c->item, pptr)->next; } else if (in_merge) { - struct strbuf m; + struct strbuf m = STRBUF_INIT; FILE *fp; reflog_msg = "commit (merge)"; - add_parent(&sb, head_sha1); - strbuf_init(&m, 0); + pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next; fp = fopen(git_path("MERGE_HEAD"), "r"); if (fp == NULL) die("could not open %s for reading: %s", @@ -1007,24 +987,26 @@ int cmd_commit(int argc, const char **argv, const char *prefix) unsigned char sha1[20]; if (get_sha1_hex(m.buf, sha1) < 0) die("Corrupt MERGE_HEAD file (%s)", m.buf); - add_parent(&sb, sha1); + pptr = &commit_list_insert(lookup_commit(sha1), pptr)->next; } fclose(fp); strbuf_release(&m); + if (!stat(git_path("MERGE_MODE"), &statbuf)) { + if (strbuf_read_file(&sb, git_path("MERGE_MODE"), 0) < 0) + die("could not read MERGE_MODE: %s", + strerror(errno)); + if (!strcmp(sb.buf, "no-ff")) + allow_fast_forward = 0; + } + if (allow_fast_forward) + parents = reduce_heads(parents); } else { reflog_msg = "commit"; - strbuf_addf(&sb, "parent %s\n", sha1_to_hex(head_sha1)); + pptr = &commit_list_insert(lookup_commit(head_sha1), pptr)->next; } - strbuf_addf(&sb, "author %s\n", - fmt_ident(author_name, author_email, author_date, IDENT_ERROR_ON_NO_NAME)); - strbuf_addf(&sb, "committer %s\n", git_committer_info(IDENT_ERROR_ON_NO_NAME)); - if (!is_encoding_utf8(git_commit_encoding)) - strbuf_addf(&sb, "encoding %s\n", git_commit_encoding); - strbuf_addch(&sb, '\n'); - /* Finally, get the commit message */ - header_len = sb.len; + strbuf_reset(&sb); if (strbuf_read_file(&sb, git_path(commit_editmsg), 0) < 0) { rollback_index_files(); die("could not read commit message"); @@ -1037,16 +1019,15 @@ int cmd_commit(int argc, const char **argv, const char *prefix) if (cleanup_mode != CLEANUP_NONE) stripspace(&sb, cleanup_mode == CLEANUP_ALL); - if (sb.len < header_len || message_is_empty(&sb, header_len)) { + if (message_is_empty(&sb)) { rollback_index_files(); fprintf(stderr, "Aborting commit due to empty commit message.\n"); exit(1); } - strbuf_addch(&sb, '\0'); - if (is_encoding_utf8(git_commit_encoding) && !is_utf8(sb.buf)) - fprintf(stderr, commit_utf8_warn); - if (write_sha1_file(sb.buf, sb.len - 1, commit_type, commit_sha1)) { + if (commit_tree(sb.buf, active_cache_tree->sha1, parents, commit_sha1, + fmt_ident(author_name, author_email, author_date, + IDENT_ERROR_ON_NO_NAME))) { rollback_index_files(); die("failed to write commit object"); } @@ -1055,12 +1036,11 @@ int cmd_commit(int argc, const char **argv, const char *prefix) initial_commit ? NULL : head_sha1, 0); - nl = strchr(sb.buf + header_len, '\n'); + nl = strchr(sb.buf, '\n'); if (nl) strbuf_setlen(&sb, nl + 1 - sb.buf); else strbuf_addch(&sb, '\n'); - strbuf_remove(&sb, 0, header_len); strbuf_insert(&sb, 0, reflog_msg, strlen(reflog_msg)); strbuf_insert(&sb, strlen(reflog_msg), ": ", 2); @@ -1075,6 +1055,7 @@ int cmd_commit(int argc, const char **argv, const char *prefix) unlink(git_path("MERGE_HEAD")); unlink(git_path("MERGE_MSG")); + unlink(git_path("MERGE_MODE")); unlink(git_path("SQUASH_MSG")); if (commit_index_files()) diff --git a/builtin-describe.c b/builtin-describe.c index ec404c839b..d2cfb1b083 100644 --- a/builtin-describe.c +++ b/builtin-describe.c @@ -15,8 +15,8 @@ static const char * const describe_usage[] = { }; static int debug; /* Display lots of verbose info */ -static int all; /* Default to annotated tags only */ -static int tags; /* But allow any tags if --tags is specified */ +static int all; /* Any valid ref can be used */ +static int tags; /* Allow lightweight tags */ static int longformat; static int abbrev = DEFAULT_ABBREV; static int max_candidates = 10; @@ -112,8 +112,6 @@ static int compare_pt(const void *a_, const void *b_) { struct possible_tag *a = (struct possible_tag *)a_; struct possible_tag *b = (struct possible_tag *)b_; - if (a->name->prio != b->name->prio) - return b->name->prio - a->name->prio; if (a->depth != b->depth) return a->depth - b->depth; if (a->found_order != b->found_order) diff --git a/builtin-diff-files.c b/builtin-diff-files.c index 9bf10bb37e..2b578c714d 100644 --- a/builtin-diff-files.c +++ b/builtin-diff-files.c @@ -50,7 +50,12 @@ int cmd_diff_files(int argc, const char **argv, const char *prefix) 3 < rev.max_count) usage(diff_files_usage); - if (rev.max_count == -1 && + /* + * "diff-files --base -p" should not combine merges because it + * was not asked to. "diff-files -c -p" should not densify + * (the user should ask with "diff-files --cc" explicitly). + */ + if (rev.max_count == -1 && !rev.combine_merges && (rev.diffopt.output_format & DIFF_FORMAT_PATCH)) rev.combine_merges = rev.dense_combined_merges = 1; diff --git a/builtin-diff.c b/builtin-diff.c index 037c3039a4..9c8c295732 100644 --- a/builtin-diff.c +++ b/builtin-diff.c @@ -74,6 +74,8 @@ static int builtin_diff_b_f(struct rev_info *revs, if (!(S_ISREG(st.st_mode) || S_ISLNK(st.st_mode))) die("'%s': not a regular file or symlink", path); + diff_set_mnemonic_prefix(&revs->diffopt, "o/", "w/"); + if (blob[0].mode == S_IFINVALID) blob[0].mode = canon_mode(st.st_mode); @@ -175,10 +177,8 @@ static int builtin_diff_combined(struct rev_info *revs, if (!revs->dense_combined_merges && !revs->combine_merges) revs->dense_combined_merges = revs->combine_merges = 1; parent = xmalloc(ents * sizeof(*parent)); - /* Again, the revs are all reverse */ for (i = 0; i < ents; i++) - hashcpy((unsigned char *)(parent + i), - ent[ents - 1 - i].item->sha1); + hashcpy((unsigned char *)(parent + i), ent[i].item->sha1); diff_tree_combined(parent[0], parent + 1, ents - 1, revs->dense_combined_merges, revs); return 0; @@ -223,7 +223,13 @@ static int builtin_diff_files(struct rev_info *revs, int argc, const char **argv argv++; argc--; } - if (revs->max_count == -1 && + /* + * "diff --base" should not combine merges because it was not + * asked to. "diff -c" should not densify (if the user wants + * dense one, --cc can be explicitly asked for, or just rely + * on the default). + */ + if (revs->max_count == -1 && !revs->combine_merges && (revs->diffopt.output_format & DIFF_FORMAT_PATCH)) revs->combine_merges = revs->dense_combined_merges = 1; diff --git a/builtin-fetch--tool.c b/builtin-fetch--tool.c index 7460ab7fce..469b07e240 100644 --- a/builtin-fetch--tool.c +++ b/builtin-fetch--tool.c @@ -5,8 +5,7 @@ static char *get_stdin(void) { - struct strbuf buf; - strbuf_init(&buf, 0); + struct strbuf buf = STRBUF_INIT; if (strbuf_read(&buf, 0, 1024) < 0) { die("error reading standard input: %s", strerror(errno)); } diff --git a/builtin-fetch-pack.c b/builtin-fetch-pack.c index 4dfef29bcd..fa3c936493 100644 --- a/builtin-fetch-pack.c +++ b/builtin-fetch-pack.c @@ -735,7 +735,7 @@ int cmd_fetch_pack(int argc, const char **argv, const char *prefix) conn = git_connect(fd, (char *)dest, args.uploadpack, args.verbose ? CONNECT_VERBOSE : 0); if (conn) { - get_remote_heads(fd[0], &ref, 0, NULL, 0); + get_remote_heads(fd[0], &ref, 0, NULL, 0, NULL); ref = fetch_pack(&args, fd, conn, ref, dest, nr_heads, heads, NULL); close(fd[0]); diff --git a/builtin-fmt-merge-msg.c b/builtin-fmt-merge-msg.c index df02ba7afd..df18f4070f 100644 --- a/builtin-fmt-merge-msg.c +++ b/builtin-fmt-merge-msg.c @@ -5,8 +5,10 @@ #include "revision.h" #include "tag.h" -static const char *fmt_merge_msg_usage = - "git fmt-merge-msg [--log] [--no-log] [--file <file>]"; +static const char * const fmt_merge_msg_usage[] = { + "git fmt-merge-msg [--log|--no-log] [--file <file>]", + NULL +}; static int merge_summary; @@ -347,46 +349,35 @@ int fmt_merge_msg(int merge_summary, struct strbuf *in, struct strbuf *out) { int cmd_fmt_merge_msg(int argc, const char **argv, const char *prefix) { + const char *inpath = NULL; + struct option options[] = { + OPT_BOOLEAN(0, "log", &merge_summary, "populate log with the shortlog"), + OPT_BOOLEAN(0, "summary", &merge_summary, "alias for --log"), + OPT_STRING('F', "file", &inpath, "file", "file to read from"), + OPT_END() + }; + FILE *in = stdin; - struct strbuf input, output; + struct strbuf input = STRBUF_INIT, output = STRBUF_INIT; int ret; git_config(fmt_merge_msg_config, NULL); - - while (argc > 1) { - if (!strcmp(argv[1], "--log") || !strcmp(argv[1], "--summary")) - merge_summary = 1; - else if (!strcmp(argv[1], "--no-log") - || !strcmp(argv[1], "--no-summary")) - merge_summary = 0; - else if (!strcmp(argv[1], "-F") || !strcmp(argv[1], "--file")) { - if (argc < 3) - die ("Which file?"); - if (!strcmp(argv[2], "-")) - in = stdin; - else { - fclose(in); - in = fopen(argv[2], "r"); - if (!in) - die("cannot open %s", argv[2]); - } - argc--; argv++; - } else - break; - argc--; argv++; + argc = parse_options(argc, argv, options, fmt_merge_msg_usage, 0); + if (argc > 0) + usage_with_options(fmt_merge_msg_usage, options); + + if (inpath && strcmp(inpath, "-")) { + in = fopen(inpath, "r"); + if (!in) + die("cannot open %s", inpath); } - if (argc > 1) - usage(fmt_merge_msg_usage); - - strbuf_init(&input, 0); if (strbuf_read(&input, fileno(in), 0) < 0) die("could not read input file %s", strerror(errno)); - strbuf_init(&output, 0); ret = fmt_merge_msg(merge_summary, &input, &output); if (ret) return ret; - printf("%s", output.buf); + write_in_full(STDOUT_FILENO, output.buf, output.len); return 0; } diff --git a/builtin-for-each-ref.c b/builtin-for-each-ref.c index 21e92bbcb5..fa6c1ed752 100644 --- a/builtin-for-each-ref.c +++ b/builtin-for-each-ref.c @@ -320,9 +320,7 @@ static const char *find_wholine(const char *who, int wholen, const char *buf, un static const char *copy_line(const char *buf) { - const char *eol = strchr(buf, '\n'); - if (!eol) - return ""; + const char *eol = strchrnul(buf, '\n'); return xmemdupz(buf, eol - buf); } @@ -546,6 +544,107 @@ static void grab_values(struct atom_value *val, int deref, struct object *obj, v } /* + * generate a format suitable for scanf from a ref_rev_parse_rules + * rule, that is replace the "%.*s" spec with a "%s" spec + */ +static void gen_scanf_fmt(char *scanf_fmt, const char *rule) +{ + char *spec; + + spec = strstr(rule, "%.*s"); + if (!spec || strstr(spec + 4, "%.*s")) + die("invalid rule in ref_rev_parse_rules: %s", rule); + + /* copy all until spec */ + strncpy(scanf_fmt, rule, spec - rule); + scanf_fmt[spec - rule] = '\0'; + /* copy new spec */ + strcat(scanf_fmt, "%s"); + /* copy remaining rule */ + strcat(scanf_fmt, spec + 4); + + return; +} + +/* + * Shorten the refname to an non-ambiguous form + */ +static char *get_short_ref(struct refinfo *ref) +{ + int i; + static char **scanf_fmts; + static int nr_rules; + char *short_name; + + /* pre generate scanf formats from ref_rev_parse_rules[] */ + if (!nr_rules) { + size_t total_len = 0; + + /* the rule list is NULL terminated, count them first */ + for (; ref_rev_parse_rules[nr_rules]; nr_rules++) + /* no +1 because strlen("%s") < strlen("%.*s") */ + total_len += strlen(ref_rev_parse_rules[nr_rules]); + + scanf_fmts = xmalloc(nr_rules * sizeof(char *) + total_len); + + total_len = 0; + for (i = 0; i < nr_rules; i++) { + scanf_fmts[i] = (char *)&scanf_fmts[nr_rules] + + total_len; + gen_scanf_fmt(scanf_fmts[i], ref_rev_parse_rules[i]); + total_len += strlen(ref_rev_parse_rules[i]); + } + } + + /* bail out if there are no rules */ + if (!nr_rules) + return ref->refname; + + /* buffer for scanf result, at most ref->refname must fit */ + short_name = xstrdup(ref->refname); + + /* skip first rule, it will always match */ + for (i = nr_rules - 1; i > 0 ; --i) { + int j; + int short_name_len; + + if (1 != sscanf(ref->refname, scanf_fmts[i], short_name)) + continue; + + short_name_len = strlen(short_name); + + /* + * check if the short name resolves to a valid ref, + * but use only rules prior to the matched one + */ + for (j = 0; j < i; j++) { + const char *rule = ref_rev_parse_rules[j]; + unsigned char short_objectname[20]; + + /* + * the short name is ambiguous, if it resolves + * (with this previous rule) to a valid ref + * read_ref() returns 0 on success + */ + if (!read_ref(mkpath(rule, short_name_len, short_name), + short_objectname)) + break; + } + + /* + * short name is non-ambiguous if all previous rules + * haven't resolved to a valid ref + */ + if (j == i) + return short_name; + } + + free(short_name); + return ref->refname; +} + + +/* * Parse the object referred by ref, and grab needed value. */ static void populate_value(struct refinfo *ref) @@ -570,13 +669,33 @@ static void populate_value(struct refinfo *ref) for (i = 0; i < used_atom_cnt; i++) { const char *name = used_atom[i]; struct atom_value *v = &ref->value[i]; - if (!strcmp(name, "refname")) - v->s = ref->refname; - else if (!strcmp(name, "*refname")) { - int len = strlen(ref->refname); - char *s = xmalloc(len + 4); - sprintf(s, "%s^{}", ref->refname); - v->s = s; + int deref = 0; + if (*name == '*') { + deref = 1; + name++; + } + if (!prefixcmp(name, "refname")) { + const char *formatp = strchr(name, ':'); + const char *refname = ref->refname; + + /* look for "short" refname format */ + if (formatp) { + formatp++; + if (!strcmp(formatp, "short")) + refname = get_short_ref(ref); + else + die("unknown refname format %s", + formatp); + } + + if (!deref) + v->s = refname; + else { + int len = strlen(refname); + char *s = xmalloc(len + 4); + sprintf(s, "%s^{}", refname); + v->s = s; + } } } diff --git a/builtin-gc.c b/builtin-gc.c index fac200e0b0..7af65bb31b 100644 --- a/builtin-gc.c +++ b/builtin-gc.c @@ -26,7 +26,7 @@ static int pack_refs = 1; static int aggressive_window = -1; static int gc_auto_threshold = 6700; static int gc_auto_pack_limit = 50; -static char *prune_expire = "2.weeks.ago"; +static const char *prune_expire = "2.weeks.ago"; #define MAX_ADD 10 static const char *argv_pack_refs[] = {"pack-refs", "--all", "--prune", NULL}; @@ -57,15 +57,12 @@ static int gc_config(const char *var, const char *value, void *cb) return 0; } if (!strcmp(var, "gc.pruneexpire")) { - if (!value) - return config_error_nonbool(var); - if (strcmp(value, "now")) { + if (value && strcmp(value, "now")) { unsigned long now = approxidate("now"); if (approxidate(value) >= now) return error("Invalid %s: '%s'", var, value); } - prune_expire = xstrdup(value); - return 0; + return git_config_string(&prune_expire, var, value); } return git_default_config(var, value, cb); } diff --git a/builtin-grep.c b/builtin-grep.c index 3a51662a35..624f86e287 100644 --- a/builtin-grep.c +++ b/builtin-grep.c @@ -295,6 +295,9 @@ static int external_grep(struct grep_opt *opt, const char **paths, int cached) push_arg("-l"); if (opt->unmatch_name_only) push_arg("-L"); + if (opt->null_following_name) + /* in GNU grep git's "-z" translates to "-Z" */ + push_arg("-Z"); if (opt->count) push_arg("-c"); if (opt->post_context || opt->pre_context) { @@ -599,6 +602,11 @@ int cmd_grep(int argc, const char **argv, const char *prefix) opt.unmatch_name_only = 1; continue; } + if (!strcmp("-z", arg) || + !strcmp("--null", arg)) { + opt.null_following_name = 1; + continue; + } if (!strcmp("-c", arg) || !strcmp("--count", arg)) { opt.count = 1; diff --git a/builtin-help.c b/builtin-help.c index 64207cbfe9..f076efa921 100644 --- a/builtin-help.c +++ b/builtin-help.c @@ -322,11 +322,9 @@ static const char *cmd_to_page(const char *git_cmd) static void setup_man_path(void) { - struct strbuf new_path; + struct strbuf new_path = STRBUF_INIT; const char *old_path = getenv("MANPATH"); - strbuf_init(&new_path, 0); - /* We should always put ':' after our path. If there is no * old_path, the ':' at the end will let 'man' to try * system-wide paths after ours to find the manual page. If diff --git a/builtin-init-db.c b/builtin-init-db.c index baf0d09ac4..d30c3fe2ca 100644 --- a/builtin-init-db.c +++ b/builtin-init-db.c @@ -17,6 +17,9 @@ #define TEST_FILEMODE 1 #endif +static int init_is_bare_repository = 0; +static int init_shared_repository = -1; + static void safe_create_dir(const char *dir, int share) { if (mkdir(dir, 0777) < 0) { @@ -37,7 +40,7 @@ static void copy_templates_1(char *path, int baselen, /* Note: if ".git/hooks" file exists in the repository being * re-initialized, /etc/core-git/templates/hooks/update would - * cause git-init to fail here. I think this is sane but + * cause "git init" to fail here. I think this is sane but * it means that the set of templates we ship by default, along * with the way the namespace under .git/ is organized, should * be really carefully chosen. @@ -191,6 +194,9 @@ static int create_default_files(const char *template_path) copy_templates(template_path); git_config(git_default_config, NULL); + is_bare_repository_cfg = init_is_bare_repository; + if (init_shared_repository != -1) + shared_repository = init_shared_repository; /* * We would have created the above under user's umask -- under @@ -277,6 +283,8 @@ int init_db(const char *template_dir, unsigned int flags) safe_create_dir(get_git_dir(), 0); + init_is_bare_repository = is_bare_repository(); + /* Check to see if the repository version is right. * Note that a newly created repository does not have * config file, so this will not fail. What we are catching @@ -381,9 +389,9 @@ int cmd_init_db(int argc, const char **argv, const char *prefix) setenv(GIT_DIR_ENVIRONMENT, getcwd(git_dir, sizeof(git_dir)), 0); } else if (!strcmp(arg, "--shared")) - shared_repository = PERM_GROUP; + init_shared_repository = PERM_GROUP; else if (!prefixcmp(arg, "--shared=")) - shared_repository = git_config_perm("arg", arg+9); + init_shared_repository = git_config_perm("arg", arg+9); else if (!strcmp(arg, "-q") || !strcmp(arg, "--quiet")) flags |= INIT_DB_QUIET; else diff --git a/builtin-log.c b/builtin-log.c index 1d3c5cbf58..a0944f70a4 100644 --- a/builtin-log.c +++ b/builtin-log.c @@ -14,7 +14,6 @@ #include "tag.h" #include "reflog-walk.h" #include "patch-ids.h" -#include "refs.h" #include "run-command.h" #include "shortlog.h" @@ -25,31 +24,6 @@ static int default_show_root = 1; static const char *fmt_patch_subject_prefix = "PATCH"; static const char *fmt_pretty; -static void add_name_decoration(const char *prefix, const char *name, struct object *obj) -{ - int plen = strlen(prefix); - int nlen = strlen(name); - struct name_decoration *res = xmalloc(sizeof(struct name_decoration) + plen + nlen); - memcpy(res->name, prefix, plen); - memcpy(res->name + plen, name, nlen + 1); - res->next = add_decoration(&name_decoration, obj, res); -} - -static int add_ref_decoration(const char *refname, const unsigned char *sha1, int flags, void *cb_data) -{ - struct object *obj = parse_object(sha1); - if (!obj) - return 0; - add_name_decoration("", refname, obj); - while (obj->type == OBJ_TAG) { - obj = ((struct tag *)obj)->tagged; - if (!obj) - break; - add_name_decoration("tag: ", refname, obj); - } - return 0; -} - static void cmd_log_init(int argc, const char **argv, const char *prefix, struct rev_info *rev) { @@ -80,8 +54,7 @@ static void cmd_log_init(int argc, const char **argv, const char *prefix, for (i = 1; i < argc; i++) { const char *arg = argv[i]; if (!strcmp(arg, "--decorate")) { - if (!decorate) - for_each_ref(add_ref_decoration, NULL); + load_ref_decorations(); decorate = 1; } else die("unrecognized argument: %s", arg); @@ -453,7 +426,7 @@ static int istitlechar(char c) static const char *fmt_patch_suffix = ".patch"; static int numbered = 0; -static int auto_number = 0; +static int auto_number = 1; static char **extra_hdr; static int extra_hdr_nr; @@ -512,6 +485,7 @@ static int git_format_config(const char *var, const char *value, void *cb) return 0; } numbered = git_config_bool(var, value); + auto_number = auto_number && numbered; return 0; } @@ -655,10 +629,9 @@ static void gen_message_id(struct rev_info *info, char *base) const char *committer = git_committer_info(IDENT_WARN_ON_NO_NAME); const char *email_start = strrchr(committer, '<'); const char *email_end = strrchr(committer, '>'); - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; if (!email_start || !email_end || email_start > email_end - 1) die("Could not extract email from committer identity."); - strbuf_init(&buf, 0); strbuf_addf(&buf, "%s.%lu.git.%.*s", base, (unsigned long) time(NULL), (int)(email_end - email_start - 1), email_start + 1); @@ -677,7 +650,7 @@ static void make_cover_letter(struct rev_info *rev, int use_stdout, const char *msg; const char *extra_headers = rev->extra_headers; struct shortlog log; - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; int i; const char *encoding = "utf-8"; struct diff_options opts; @@ -698,7 +671,6 @@ static void make_cover_letter(struct rev_info *rev, int use_stdout, committer = git_committer_info(0); msg = body; - strbuf_init(&sb, 0); pp_user_info(NULL, CMIT_FMT_EMAIL, &sb, committer, DATE_RFC2822, encoding); pp_title_line(CMIT_FMT_EMAIL, &msg, &sb, subject_start, extra_headers, @@ -780,7 +752,7 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) const char *in_reply_to = NULL; struct patch_ids ids; char *add_signoff = NULL; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; git_config(git_format_config, NULL); init_revisions(&rev, prefix); @@ -844,7 +816,7 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) committer = git_committer_info(IDENT_ERROR_ON_NO_NAME); endpos = strchr(committer, '>'); if (!endpos) - die("bogos committer info %s\n", committer); + die("bogus committer info %s\n", committer); add_signoff = xmemdupz(committer, endpos - committer + 1); } else if (!strcmp(argv[i], "--attach")) { @@ -888,8 +860,6 @@ int cmd_format_patch(int argc, const char **argv, const char *prefix) } argc = j; - strbuf_init(&buf, 0); - for (i = 0; i < extra_hdr_nr; i++) { strbuf_addstr(&buf, extra_hdr[i]); strbuf_addch(&buf, '\n'); @@ -1166,8 +1136,7 @@ int cmd_cherry(int argc, const char **argv, const char *prefix) sign = '-'; if (verbose) { - struct strbuf buf; - strbuf_init(&buf, 0); + struct strbuf buf = STRBUF_INIT; pretty_print_commit(CMIT_FMT_ONELINE, commit, &buf, 0, NULL, NULL, 0, 0); printf("%c %s %s\n", sign, diff --git a/builtin-merge-base.c b/builtin-merge-base.c index b08da516e4..03fc1c2114 100644 --- a/builtin-merge-base.c +++ b/builtin-merge-base.c @@ -1,6 +1,7 @@ #include "builtin.h" #include "cache.h" #include "commit.h" +#include "parse-options.h" static int show_merge_base(struct commit **rev, int rev_nr, int show_all) { @@ -21,8 +22,10 @@ static int show_merge_base(struct commit **rev, int rev_nr, int show_all) return 0; } -static const char merge_base_usage[] = -"git merge-base [--all] <commit-id> <commit-id>..."; +static const char * const merge_base_usage[] = { + "git merge-base [--all] <commit-id> <commit-id>...", + NULL +}; static struct commit *get_commit_reference(const char *arg) { @@ -44,25 +47,17 @@ int cmd_merge_base(int argc, const char **argv, const char *prefix) int rev_nr = 0; int show_all = 0; - git_config(git_default_config, NULL); - - while (1 < argc && argv[1][0] == '-') { - const char *arg = argv[1]; - if (!strcmp(arg, "-a") || !strcmp(arg, "--all")) - show_all = 1; - else - usage(merge_base_usage); - argc--; argv++; - } - if (argc < 3) - usage(merge_base_usage); - - rev = xmalloc((argc - 1) * sizeof(*rev)); - - do { - rev[rev_nr++] = get_commit_reference(argv[1]); - argc--; argv++; - } while (argc > 1); + struct option options[] = { + OPT_BOOLEAN('a', "all", &show_all, "outputs all common ancestors"), + OPT_END() + }; + git_config(git_default_config, NULL); + argc = parse_options(argc, argv, options, merge_base_usage, 0); + if (argc < 2) + usage_with_options(merge_base_usage, options); + rev = xmalloc(argc * sizeof(*rev)); + while (argc-- > 0) + rev[rev_nr++] = get_commit_reference(*argv++); return show_merge_base(rev, rev_nr, show_all); } diff --git a/builtin-merge-file.c b/builtin-merge-file.c index 3605960c2d..9d4e874809 100644 --- a/builtin-merge-file.c +++ b/builtin-merge-file.c @@ -2,57 +2,76 @@ #include "cache.h" #include "xdiff/xdiff.h" #include "xdiff-interface.h" +#include "parse-options.h" -static const char merge_file_usage[] = -"git merge-file [-p | --stdout] [-q | --quiet] [-L name1 [-L orig [-L name2]]] file1 orig_file file2"; +static const char *const merge_file_usage[] = { + "git merge-file [options] [-L name1 [-L orig [-L name2]]] file1 orig_file file2", + NULL +}; + +static int label_cb(const struct option *opt, const char *arg, int unset) +{ + static int label_count = 0; + const char **names = (const char **)opt->value; + + if (label_count >= 3) + return error("too many labels on the command line"); + names[label_count++] = arg; + return 0; +} int cmd_merge_file(int argc, const char **argv, const char *prefix) { - const char *names[3]; + const char *names[3] = { NULL, NULL, NULL }; mmfile_t mmfs[3]; mmbuffer_t result = {NULL, 0}; xpparam_t xpp = {XDF_NEED_MINIMAL}; int ret = 0, i = 0, to_stdout = 0; + int merge_level = XDL_MERGE_ZEALOUS_ALNUM; + int merge_style = 0, quiet = 0; + int nongit; - while (argc > 4) { - if (!strcmp(argv[1], "-L") && i < 3) { - names[i++] = argv[2]; - argc--; - argv++; - } else if (!strcmp(argv[1], "-p") || - !strcmp(argv[1], "--stdout")) - to_stdout = 1; - else if (!strcmp(argv[1], "-q") || - !strcmp(argv[1], "--quiet")) - freopen("/dev/null", "w", stderr); - else - usage(merge_file_usage); - argc--; - argv++; - } + struct option options[] = { + OPT_BOOLEAN('p', "stdout", &to_stdout, "send results to standard output"), + OPT_SET_INT(0, "diff3", &merge_style, "use a diff3 based merge", XDL_MERGE_DIFF3), + OPT__QUIET(&quiet), + OPT_CALLBACK('L', NULL, names, "name", + "set labels for file1/orig_file/file2", &label_cb), + OPT_END(), + }; - if (argc != 4) - usage(merge_file_usage); + prefix = setup_git_directory_gently(&nongit); + if (!nongit) { + /* Read the configuration file */ + git_config(git_xmerge_config, NULL); + if (0 <= git_xmerge_style) + merge_style = git_xmerge_style; + } - for (; i < 3; i++) - names[i] = argv[i + 1]; + argc = parse_options(argc, argv, options, merge_file_usage, 0); + if (argc != 3) + usage_with_options(merge_file_usage, options); + if (quiet) + freopen("/dev/null", "w", stderr); for (i = 0; i < 3; i++) { - if (read_mmfile(mmfs + i, argv[i + 1])) + if (!names[i]) + names[i] = argv[i]; + if (read_mmfile(mmfs + i, argv[i])) return -1; if (buffer_is_binary(mmfs[i].ptr, mmfs[i].size)) return error("Cannot merge binary files: %s\n", - argv[i + 1]); + argv[i]); } ret = xdl_merge(mmfs + 1, mmfs + 0, names[0], mmfs + 2, names[2], - &xpp, XDL_MERGE_ZEALOUS_ALNUM, &result); + &xpp, merge_level | merge_style, &result); for (i = 0; i < 3; i++) free(mmfs[i].ptr); if (ret >= 0) { - const char *filename = argv[1]; + const char *filename = argv[0]; FILE *f = to_stdout ? stdout : fopen(filename, "wb"); if (!f) diff --git a/builtin-merge-recursive.c b/builtin-merge-recursive.c index dfb363ee2f..6b534c1a66 100644 --- a/builtin-merge-recursive.c +++ b/builtin-merge-recursive.c @@ -1,1307 +1,8 @@ -/* - * Recursive Merge algorithm stolen from git-merge-recursive.py by - * Fredrik Kuivinen. - * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006 - */ #include "cache.h" -#include "cache-tree.h" #include "commit.h" -#include "blob.h" -#include "builtin.h" -#include "tree-walk.h" -#include "diff.h" -#include "diffcore.h" #include "tag.h" -#include "unpack-trees.h" -#include "string-list.h" -#include "xdiff-interface.h" -#include "ll-merge.h" -#include "interpolate.h" -#include "attr.h" #include "merge-recursive.h" -static int subtree_merge; - -static struct tree *shift_tree_object(struct tree *one, struct tree *two) -{ - unsigned char shifted[20]; - - /* - * NEEDSWORK: this limits the recursion depth to hardcoded - * value '2' to avoid excessive overhead. - */ - shift_tree(one->object.sha1, two->object.sha1, shifted, 2); - if (!hashcmp(two->object.sha1, shifted)) - return two; - return lookup_tree(shifted); -} - -/* - * A virtual commit has - * - (const char *)commit->util set to the name, and - * - *(int *)commit->object.sha1 set to the virtual id. - */ - -static struct commit *make_virtual_commit(struct tree *tree, const char *comment) -{ - struct commit *commit = xcalloc(1, sizeof(struct commit)); - static unsigned virtual_id = 1; - commit->tree = tree; - commit->util = (void*)comment; - *(int*)commit->object.sha1 = virtual_id++; - /* avoid warnings */ - commit->object.parsed = 1; - return commit; -} - -/* - * Since we use get_tree_entry(), which does not put the read object into - * the object pool, we cannot rely on a == b. - */ -static int sha_eq(const unsigned char *a, const unsigned char *b) -{ - if (!a && !b) - return 2; - return a && b && hashcmp(a, b) == 0; -} - -/* - * Since we want to write the index eventually, we cannot reuse the index - * for these (temporary) data. - */ -struct stage_data -{ - struct - { - unsigned mode; - unsigned char sha[20]; - } stages[4]; - unsigned processed:1; -}; - -static struct string_list current_file_set = {NULL, 0, 0, 1}; -static struct string_list current_directory_set = {NULL, 0, 0, 1}; - -static int call_depth = 0; -static int verbosity = 2; -static int diff_rename_limit = -1; -static int merge_rename_limit = -1; -static int buffer_output = 1; -static struct strbuf obuf = STRBUF_INIT; - -static int show(int v) -{ - return (!call_depth && verbosity >= v) || verbosity >= 5; -} - -static void flush_output(void) -{ - if (obuf.len) { - fputs(obuf.buf, stdout); - strbuf_reset(&obuf); - } -} - -static void output(int v, const char *fmt, ...) -{ - int len; - va_list ap; - - if (!show(v)) - return; - - strbuf_grow(&obuf, call_depth * 2 + 2); - memset(obuf.buf + obuf.len, ' ', call_depth * 2); - strbuf_setlen(&obuf, obuf.len + call_depth * 2); - - va_start(ap, fmt); - len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap); - va_end(ap); - - if (len < 0) - len = 0; - if (len >= strbuf_avail(&obuf)) { - strbuf_grow(&obuf, len + 2); - va_start(ap, fmt); - len = vsnprintf(obuf.buf + obuf.len, strbuf_avail(&obuf), fmt, ap); - va_end(ap); - if (len >= strbuf_avail(&obuf)) { - die("this should not happen, your snprintf is broken"); - } - } - strbuf_setlen(&obuf, obuf.len + len); - strbuf_add(&obuf, "\n", 1); - if (!buffer_output) - flush_output(); -} - -static void output_commit_title(struct commit *commit) -{ - int i; - flush_output(); - for (i = call_depth; i--;) - fputs(" ", stdout); - if (commit->util) - printf("virtual %s\n", (char *)commit->util); - else { - printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV)); - if (parse_commit(commit) != 0) - printf("(bad commit)\n"); - else { - const char *s; - int len; - for (s = commit->buffer; *s; s++) - if (*s == '\n' && s[1] == '\n') { - s += 2; - break; - } - for (len = 0; s[len] && '\n' != s[len]; len++) - ; /* do nothing */ - printf("%.*s\n", len, s); - } - } -} - -static int add_cacheinfo(unsigned int mode, const unsigned char *sha1, - const char *path, int stage, int refresh, int options) -{ - struct cache_entry *ce; - ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh); - if (!ce) - return error("addinfo_cache failed for path '%s'", path); - return add_cache_entry(ce, options); -} - -/* - * This is a global variable which is used in a number of places but - * only written to in the 'merge' function. - * - * index_only == 1 => Don't leave any non-stage 0 entries in the cache and - * don't update the working directory. - * 0 => Leave unmerged entries in the cache and update - * the working directory. - */ -static int index_only = 0; - -static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree) -{ - parse_tree(tree); - init_tree_desc(desc, tree->buffer, tree->size); -} - -static int git_merge_trees(int index_only, - struct tree *common, - struct tree *head, - struct tree *merge) -{ - int rc; - struct tree_desc t[3]; - struct unpack_trees_options opts; - - memset(&opts, 0, sizeof(opts)); - if (index_only) - opts.index_only = 1; - else - opts.update = 1; - opts.merge = 1; - opts.head_idx = 2; - opts.fn = threeway_merge; - opts.src_index = &the_index; - opts.dst_index = &the_index; - - init_tree_desc_from_tree(t+0, common); - init_tree_desc_from_tree(t+1, head); - init_tree_desc_from_tree(t+2, merge); - - rc = unpack_trees(3, t, &opts); - cache_tree_free(&active_cache_tree); - return rc; -} - -struct tree *write_tree_from_memory(void) -{ - struct tree *result = NULL; - - if (unmerged_cache()) { - int i; - output(0, "There are unmerged index entries:"); - for (i = 0; i < active_nr; i++) { - struct cache_entry *ce = active_cache[i]; - if (ce_stage(ce)) - output(0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name); - } - return NULL; - } - - if (!active_cache_tree) - active_cache_tree = cache_tree(); - - if (!cache_tree_fully_valid(active_cache_tree) && - cache_tree_update(active_cache_tree, - active_cache, active_nr, 0, 0) < 0) - die("error building trees"); - - result = lookup_tree(active_cache_tree->sha1); - - return result; -} - -static int save_files_dirs(const unsigned char *sha1, - const char *base, int baselen, const char *path, - unsigned int mode, int stage, void *context) -{ - int len = strlen(path); - char *newpath = xmalloc(baselen + len + 1); - memcpy(newpath, base, baselen); - memcpy(newpath + baselen, path, len); - newpath[baselen + len] = '\0'; - - if (S_ISDIR(mode)) - string_list_insert(newpath, ¤t_directory_set); - else - string_list_insert(newpath, ¤t_file_set); - free(newpath); - - return READ_TREE_RECURSIVE; -} - -static int get_files_dirs(struct tree *tree) -{ - int n; - if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs, NULL)) - return 0; - n = current_file_set.nr + current_directory_set.nr; - return n; -} - -/* - * Returns an index_entry instance which doesn't have to correspond to - * a real cache entry in Git's index. - */ -static struct stage_data *insert_stage_data(const char *path, - struct tree *o, struct tree *a, struct tree *b, - struct string_list *entries) -{ - struct string_list_item *item; - struct stage_data *e = xcalloc(1, sizeof(struct stage_data)); - get_tree_entry(o->object.sha1, path, - e->stages[1].sha, &e->stages[1].mode); - get_tree_entry(a->object.sha1, path, - e->stages[2].sha, &e->stages[2].mode); - get_tree_entry(b->object.sha1, path, - e->stages[3].sha, &e->stages[3].mode); - item = string_list_insert(path, entries); - item->util = e; - return e; -} - -/* - * Create a dictionary mapping file names to stage_data objects. The - * dictionary contains one entry for every path with a non-zero stage entry. - */ -static struct string_list *get_unmerged(void) -{ - struct string_list *unmerged = xcalloc(1, sizeof(struct string_list)); - int i; - - unmerged->strdup_strings = 1; - - for (i = 0; i < active_nr; i++) { - struct string_list_item *item; - struct stage_data *e; - struct cache_entry *ce = active_cache[i]; - if (!ce_stage(ce)) - continue; - - item = string_list_lookup(ce->name, unmerged); - if (!item) { - item = string_list_insert(ce->name, unmerged); - item->util = xcalloc(1, sizeof(struct stage_data)); - } - e = item->util; - e->stages[ce_stage(ce)].mode = ce->ce_mode; - hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1); - } - - return unmerged; -} - -struct rename -{ - struct diff_filepair *pair; - struct stage_data *src_entry; - struct stage_data *dst_entry; - unsigned processed:1; -}; - -/* - * Get information of all renames which occurred between 'o_tree' and - * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and - * 'b_tree') to be able to associate the correct cache entries with - * the rename information. 'tree' is always equal to either a_tree or b_tree. - */ -static struct string_list *get_renames(struct tree *tree, - struct tree *o_tree, - struct tree *a_tree, - struct tree *b_tree, - struct string_list *entries) -{ - int i; - struct string_list *renames; - struct diff_options opts; - - renames = xcalloc(1, sizeof(struct string_list)); - diff_setup(&opts); - DIFF_OPT_SET(&opts, RECURSIVE); - opts.detect_rename = DIFF_DETECT_RENAME; - opts.rename_limit = merge_rename_limit >= 0 ? merge_rename_limit : - diff_rename_limit >= 0 ? diff_rename_limit : - 500; - opts.warn_on_too_large_rename = 1; - opts.output_format = DIFF_FORMAT_NO_OUTPUT; - if (diff_setup_done(&opts) < 0) - die("diff setup failed"); - diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts); - diffcore_std(&opts); - for (i = 0; i < diff_queued_diff.nr; ++i) { - struct string_list_item *item; - struct rename *re; - struct diff_filepair *pair = diff_queued_diff.queue[i]; - if (pair->status != 'R') { - diff_free_filepair(pair); - continue; - } - re = xmalloc(sizeof(*re)); - re->processed = 0; - re->pair = pair; - item = string_list_lookup(re->pair->one->path, entries); - if (!item) - re->src_entry = insert_stage_data(re->pair->one->path, - o_tree, a_tree, b_tree, entries); - else - re->src_entry = item->util; - - item = string_list_lookup(re->pair->two->path, entries); - if (!item) - re->dst_entry = insert_stage_data(re->pair->two->path, - o_tree, a_tree, b_tree, entries); - else - re->dst_entry = item->util; - item = string_list_insert(pair->one->path, renames); - item->util = re; - } - opts.output_format = DIFF_FORMAT_NO_OUTPUT; - diff_queued_diff.nr = 0; - diff_flush(&opts); - return renames; -} - -static int update_stages(const char *path, struct diff_filespec *o, - struct diff_filespec *a, struct diff_filespec *b, - int clear) -{ - int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE; - if (clear) - if (remove_file_from_cache(path)) - return -1; - if (o) - if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options)) - return -1; - if (a) - if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options)) - return -1; - if (b) - if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options)) - return -1; - return 0; -} - -static int remove_path(const char *name) -{ - int ret; - char *slash, *dirs; - - ret = unlink(name); - if (ret) - return ret; - dirs = xstrdup(name); - while ((slash = strrchr(name, '/'))) { - *slash = '\0'; - if (rmdir(name) != 0) - break; - } - free(dirs); - return ret; -} - -static int remove_file(int clean, const char *path, int no_wd) -{ - int update_cache = index_only || clean; - int update_working_directory = !index_only && !no_wd; - - if (update_cache) { - if (remove_file_from_cache(path)) - return -1; - } - if (update_working_directory) { - unlink(path); - if (errno != ENOENT || errno != EISDIR) - return -1; - remove_path(path); - } - return 0; -} - -static char *unique_path(const char *path, const char *branch) -{ - char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1); - int suffix = 0; - struct stat st; - char *p = newpath + strlen(path); - strcpy(newpath, path); - *(p++) = '~'; - strcpy(p, branch); - for (; *p; ++p) - if ('/' == *p) - *p = '_'; - while (string_list_has_string(¤t_file_set, newpath) || - string_list_has_string(¤t_directory_set, newpath) || - lstat(newpath, &st) == 0) - sprintf(p, "_%d", suffix++); - - string_list_insert(newpath, ¤t_file_set); - return newpath; -} - -static void flush_buffer(int fd, const char *buf, unsigned long size) -{ - while (size > 0) { - long ret = write_in_full(fd, buf, size); - if (ret < 0) { - /* Ignore epipe */ - if (errno == EPIPE) - break; - die("merge-recursive: %s", strerror(errno)); - } else if (!ret) { - die("merge-recursive: disk full?"); - } - size -= ret; - buf += ret; - } -} - -static int make_room_for_path(const char *path) -{ - int status; - const char *msg = "failed to create path '%s'%s"; - - status = safe_create_leading_directories_const(path); - if (status) { - if (status == -3) { - /* something else exists */ - error(msg, path, ": perhaps a D/F conflict?"); - return -1; - } - die(msg, path, ""); - } - - /* Successful unlink is good.. */ - if (!unlink(path)) - return 0; - /* .. and so is no existing file */ - if (errno == ENOENT) - return 0; - /* .. but not some other error (who really cares what?) */ - return error(msg, path, ": perhaps a D/F conflict?"); -} - -static void update_file_flags(const unsigned char *sha, - unsigned mode, - const char *path, - int update_cache, - int update_wd) -{ - if (index_only) - update_wd = 0; - - if (update_wd) { - enum object_type type; - void *buf; - unsigned long size; - - if (S_ISGITLINK(mode)) - die("cannot read object %s '%s': It is a submodule!", - sha1_to_hex(sha), path); - - buf = read_sha1_file(sha, &type, &size); - if (!buf) - die("cannot read object %s '%s'", sha1_to_hex(sha), path); - if (type != OBJ_BLOB) - die("blob expected for %s '%s'", sha1_to_hex(sha), path); - if (S_ISREG(mode)) { - struct strbuf strbuf; - strbuf_init(&strbuf, 0); - if (convert_to_working_tree(path, buf, size, &strbuf)) { - free(buf); - size = strbuf.len; - buf = strbuf_detach(&strbuf, NULL); - } - } - - if (make_room_for_path(path) < 0) { - update_wd = 0; - free(buf); - goto update_index; - } - if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) { - int fd; - if (mode & 0100) - mode = 0777; - else - mode = 0666; - fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); - if (fd < 0) - die("failed to open %s: %s", path, strerror(errno)); - flush_buffer(fd, buf, size); - close(fd); - } else if (S_ISLNK(mode)) { - char *lnk = xmemdupz(buf, size); - safe_create_leading_directories_const(path); - unlink(path); - symlink(lnk, path); - free(lnk); - } else - die("do not know what to do with %06o %s '%s'", - mode, sha1_to_hex(sha), path); - free(buf); - } - update_index: - if (update_cache) - add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD); -} - -static void update_file(int clean, - const unsigned char *sha, - unsigned mode, - const char *path) -{ - update_file_flags(sha, mode, path, index_only || clean, !index_only); -} - -/* Low level file merging, update and removal */ - -struct merge_file_info -{ - unsigned char sha[20]; - unsigned mode; - unsigned clean:1, - merge:1; -}; - -static void fill_mm(const unsigned char *sha1, mmfile_t *mm) -{ - unsigned long size; - enum object_type type; - - if (!hashcmp(sha1, null_sha1)) { - mm->ptr = xstrdup(""); - mm->size = 0; - return; - } - - mm->ptr = read_sha1_file(sha1, &type, &size); - if (!mm->ptr || type != OBJ_BLOB) - die("unable to read blob object %s", sha1_to_hex(sha1)); - mm->size = size; -} - -static int merge_3way(mmbuffer_t *result_buf, - struct diff_filespec *o, - struct diff_filespec *a, - struct diff_filespec *b, - const char *branch1, - const char *branch2) -{ - mmfile_t orig, src1, src2; - char *name1, *name2; - int merge_status; - - name1 = xstrdup(mkpath("%s:%s", branch1, a->path)); - name2 = xstrdup(mkpath("%s:%s", branch2, b->path)); - - fill_mm(o->sha1, &orig); - fill_mm(a->sha1, &src1); - fill_mm(b->sha1, &src2); - - merge_status = ll_merge(result_buf, a->path, &orig, - &src1, name1, &src2, name2, - index_only); - - free(name1); - free(name2); - free(orig.ptr); - free(src1.ptr); - free(src2.ptr); - return merge_status; -} - -static struct merge_file_info merge_file(struct diff_filespec *o, - struct diff_filespec *a, struct diff_filespec *b, - const char *branch1, const char *branch2) -{ - struct merge_file_info result; - result.merge = 0; - result.clean = 1; - - if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) { - result.clean = 0; - if (S_ISREG(a->mode)) { - result.mode = a->mode; - hashcpy(result.sha, a->sha1); - } else { - result.mode = b->mode; - hashcpy(result.sha, b->sha1); - } - } else { - if (!sha_eq(a->sha1, o->sha1) && !sha_eq(b->sha1, o->sha1)) - result.merge = 1; - - /* - * Merge modes - */ - if (a->mode == b->mode || a->mode == o->mode) - result.mode = b->mode; - else { - result.mode = a->mode; - if (b->mode != o->mode) { - result.clean = 0; - result.merge = 1; - } - } - - if (sha_eq(a->sha1, b->sha1) || sha_eq(a->sha1, o->sha1)) - hashcpy(result.sha, b->sha1); - else if (sha_eq(b->sha1, o->sha1)) - hashcpy(result.sha, a->sha1); - else if (S_ISREG(a->mode)) { - mmbuffer_t result_buf; - int merge_status; - - merge_status = merge_3way(&result_buf, o, a, b, - branch1, branch2); - - if ((merge_status < 0) || !result_buf.ptr) - die("Failed to execute internal merge"); - - if (write_sha1_file(result_buf.ptr, result_buf.size, - blob_type, result.sha)) - die("Unable to add %s to database", - a->path); - - free(result_buf.ptr); - result.clean = (merge_status == 0); - } else if (S_ISGITLINK(a->mode)) { - result.clean = 0; - hashcpy(result.sha, a->sha1); - } else if (S_ISLNK(a->mode)) { - hashcpy(result.sha, a->sha1); - - if (!sha_eq(a->sha1, b->sha1)) - result.clean = 0; - } else { - die("unsupported object type in the tree"); - } - } - - return result; -} - -static void conflict_rename_rename(struct rename *ren1, - const char *branch1, - struct rename *ren2, - const char *branch2) -{ - char *del[2]; - int delp = 0; - const char *ren1_dst = ren1->pair->two->path; - const char *ren2_dst = ren2->pair->two->path; - const char *dst_name1 = ren1_dst; - const char *dst_name2 = ren2_dst; - if (string_list_has_string(¤t_directory_set, ren1_dst)) { - dst_name1 = del[delp++] = unique_path(ren1_dst, branch1); - output(1, "%s is a directory in %s adding as %s instead", - ren1_dst, branch2, dst_name1); - remove_file(0, ren1_dst, 0); - } - if (string_list_has_string(¤t_directory_set, ren2_dst)) { - dst_name2 = del[delp++] = unique_path(ren2_dst, branch2); - output(1, "%s is a directory in %s adding as %s instead", - ren2_dst, branch1, dst_name2); - remove_file(0, ren2_dst, 0); - } - if (index_only) { - remove_file_from_cache(dst_name1); - remove_file_from_cache(dst_name2); - /* - * Uncomment to leave the conflicting names in the resulting tree - * - * update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1); - * update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2); - */ - } else { - update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1); - update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1); - } - while (delp--) - free(del[delp]); -} - -static void conflict_rename_dir(struct rename *ren1, - const char *branch1) -{ - char *new_path = unique_path(ren1->pair->two->path, branch1); - output(1, "Renaming %s to %s instead", ren1->pair->one->path, new_path); - remove_file(0, ren1->pair->two->path, 0); - update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path); - free(new_path); -} - -static void conflict_rename_rename_2(struct rename *ren1, - const char *branch1, - struct rename *ren2, - const char *branch2) -{ - char *new_path1 = unique_path(ren1->pair->two->path, branch1); - char *new_path2 = unique_path(ren2->pair->two->path, branch2); - output(1, "Renaming %s to %s and %s to %s instead", - ren1->pair->one->path, new_path1, - ren2->pair->one->path, new_path2); - remove_file(0, ren1->pair->two->path, 0); - update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1); - update_file(0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2); - free(new_path2); - free(new_path1); -} - -static int process_renames(struct string_list *a_renames, - struct string_list *b_renames, - const char *a_branch, - const char *b_branch) -{ - int clean_merge = 1, i, j; - struct string_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0}; - const struct rename *sre; - - for (i = 0; i < a_renames->nr; i++) { - sre = a_renames->items[i].util; - string_list_insert(sre->pair->two->path, &a_by_dst)->util - = sre->dst_entry; - } - for (i = 0; i < b_renames->nr; i++) { - sre = b_renames->items[i].util; - string_list_insert(sre->pair->two->path, &b_by_dst)->util - = sre->dst_entry; - } - - for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) { - int compare; - char *src; - struct string_list *renames1, *renames2, *renames2Dst; - struct rename *ren1 = NULL, *ren2 = NULL; - const char *branch1, *branch2; - const char *ren1_src, *ren1_dst; - - if (i >= a_renames->nr) { - compare = 1; - ren2 = b_renames->items[j++].util; - } else if (j >= b_renames->nr) { - compare = -1; - ren1 = a_renames->items[i++].util; - } else { - compare = strcmp(a_renames->items[i].string, - b_renames->items[j].string); - if (compare <= 0) - ren1 = a_renames->items[i++].util; - if (compare >= 0) - ren2 = b_renames->items[j++].util; - } - - /* TODO: refactor, so that 1/2 are not needed */ - if (ren1) { - renames1 = a_renames; - renames2 = b_renames; - renames2Dst = &b_by_dst; - branch1 = a_branch; - branch2 = b_branch; - } else { - struct rename *tmp; - renames1 = b_renames; - renames2 = a_renames; - renames2Dst = &a_by_dst; - branch1 = b_branch; - branch2 = a_branch; - tmp = ren2; - ren2 = ren1; - ren1 = tmp; - } - src = ren1->pair->one->path; - - ren1->dst_entry->processed = 1; - ren1->src_entry->processed = 1; - - if (ren1->processed) - continue; - ren1->processed = 1; - - ren1_src = ren1->pair->one->path; - ren1_dst = ren1->pair->two->path; - - if (ren2) { - const char *ren2_src = ren2->pair->one->path; - const char *ren2_dst = ren2->pair->two->path; - /* Renamed in 1 and renamed in 2 */ - if (strcmp(ren1_src, ren2_src) != 0) - die("ren1.src != ren2.src"); - ren2->dst_entry->processed = 1; - ren2->processed = 1; - if (strcmp(ren1_dst, ren2_dst) != 0) { - clean_merge = 0; - output(1, "CONFLICT (rename/rename): " - "Rename \"%s\"->\"%s\" in branch \"%s\" " - "rename \"%s\"->\"%s\" in \"%s\"%s", - src, ren1_dst, branch1, - src, ren2_dst, branch2, - index_only ? " (left unresolved)": ""); - if (index_only) { - remove_file_from_cache(src); - update_file(0, ren1->pair->one->sha1, - ren1->pair->one->mode, src); - } - conflict_rename_rename(ren1, branch1, ren2, branch2); - } else { - struct merge_file_info mfi; - remove_file(1, ren1_src, 1); - mfi = merge_file(ren1->pair->one, - ren1->pair->two, - ren2->pair->two, - branch1, - branch2); - if (mfi.merge || !mfi.clean) - output(1, "Renaming %s->%s", src, ren1_dst); - - if (mfi.merge) - output(2, "Auto-merging %s", ren1_dst); - - if (!mfi.clean) { - output(1, "CONFLICT (content): merge conflict in %s", - ren1_dst); - clean_merge = 0; - - if (!index_only) - update_stages(ren1_dst, - ren1->pair->one, - ren1->pair->two, - ren2->pair->two, - 1 /* clear */); - } - update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst); - } - } else { - /* Renamed in 1, maybe changed in 2 */ - struct string_list_item *item; - /* we only use sha1 and mode of these */ - struct diff_filespec src_other, dst_other; - int try_merge, stage = a_renames == renames1 ? 3: 2; - - remove_file(1, ren1_src, index_only || stage == 3); - - hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha); - src_other.mode = ren1->src_entry->stages[stage].mode; - hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha); - dst_other.mode = ren1->dst_entry->stages[stage].mode; - - try_merge = 0; - - if (string_list_has_string(¤t_directory_set, ren1_dst)) { - clean_merge = 0; - output(1, "CONFLICT (rename/directory): Rename %s->%s in %s " - " directory %s added in %s", - ren1_src, ren1_dst, branch1, - ren1_dst, branch2); - conflict_rename_dir(ren1, branch1); - } else if (sha_eq(src_other.sha1, null_sha1)) { - clean_merge = 0; - output(1, "CONFLICT (rename/delete): Rename %s->%s in %s " - "and deleted in %s", - ren1_src, ren1_dst, branch1, - branch2); - update_file(0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst); - } else if (!sha_eq(dst_other.sha1, null_sha1)) { - const char *new_path; - clean_merge = 0; - try_merge = 1; - output(1, "CONFLICT (rename/add): Rename %s->%s in %s. " - "%s added in %s", - ren1_src, ren1_dst, branch1, - ren1_dst, branch2); - new_path = unique_path(ren1_dst, branch2); - output(1, "Adding as %s instead", new_path); - update_file(0, dst_other.sha1, dst_other.mode, new_path); - } else if ((item = string_list_lookup(ren1_dst, renames2Dst))) { - ren2 = item->util; - clean_merge = 0; - ren2->processed = 1; - output(1, "CONFLICT (rename/rename): Rename %s->%s in %s. " - "Rename %s->%s in %s", - ren1_src, ren1_dst, branch1, - ren2->pair->one->path, ren2->pair->two->path, branch2); - conflict_rename_rename_2(ren1, branch1, ren2, branch2); - } else - try_merge = 1; - - if (try_merge) { - struct diff_filespec *o, *a, *b; - struct merge_file_info mfi; - src_other.path = (char *)ren1_src; - - o = ren1->pair->one; - if (a_renames == renames1) { - a = ren1->pair->two; - b = &src_other; - } else { - b = ren1->pair->two; - a = &src_other; - } - mfi = merge_file(o, a, b, - a_branch, b_branch); - - if (mfi.clean && - sha_eq(mfi.sha, ren1->pair->two->sha1) && - mfi.mode == ren1->pair->two->mode) - /* - * This messaged is part of - * t6022 test. If you change - * it update the test too. - */ - output(3, "Skipped %s (merged same as existing)", ren1_dst); - else { - if (mfi.merge || !mfi.clean) - output(1, "Renaming %s => %s", ren1_src, ren1_dst); - if (mfi.merge) - output(2, "Auto-merging %s", ren1_dst); - if (!mfi.clean) { - output(1, "CONFLICT (rename/modify): Merge conflict in %s", - ren1_dst); - clean_merge = 0; - - if (!index_only) - update_stages(ren1_dst, - o, a, b, 1); - } - update_file(mfi.clean, mfi.sha, mfi.mode, ren1_dst); - } - } - } - } - string_list_clear(&a_by_dst, 0); - string_list_clear(&b_by_dst, 0); - - return clean_merge; -} - -static unsigned char *stage_sha(const unsigned char *sha, unsigned mode) -{ - return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha; -} - -/* Per entry merge function */ -static int process_entry(const char *path, struct stage_data *entry, - const char *branch1, - const char *branch2) -{ - /* - printf("processing entry, clean cache: %s\n", index_only ? "yes": "no"); - print_index_entry("\tpath: ", entry); - */ - int clean_merge = 1; - unsigned o_mode = entry->stages[1].mode; - unsigned a_mode = entry->stages[2].mode; - unsigned b_mode = entry->stages[3].mode; - unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode); - unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode); - unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode); - - if (o_sha && (!a_sha || !b_sha)) { - /* Case A: Deleted in one */ - if ((!a_sha && !b_sha) || - (sha_eq(a_sha, o_sha) && !b_sha) || - (!a_sha && sha_eq(b_sha, o_sha))) { - /* Deleted in both or deleted in one and - * unchanged in the other */ - if (a_sha) - output(2, "Removing %s", path); - /* do not touch working file if it did not exist */ - remove_file(1, path, !a_sha); - } else { - /* Deleted in one and changed in the other */ - clean_merge = 0; - if (!a_sha) { - output(1, "CONFLICT (delete/modify): %s deleted in %s " - "and modified in %s. Version %s of %s left in tree.", - path, branch1, - branch2, branch2, path); - update_file(0, b_sha, b_mode, path); - } else { - output(1, "CONFLICT (delete/modify): %s deleted in %s " - "and modified in %s. Version %s of %s left in tree.", - path, branch2, - branch1, branch1, path); - update_file(0, a_sha, a_mode, path); - } - } - - } else if ((!o_sha && a_sha && !b_sha) || - (!o_sha && !a_sha && b_sha)) { - /* Case B: Added in one. */ - const char *add_branch; - const char *other_branch; - unsigned mode; - const unsigned char *sha; - const char *conf; - - if (a_sha) { - add_branch = branch1; - other_branch = branch2; - mode = a_mode; - sha = a_sha; - conf = "file/directory"; - } else { - add_branch = branch2; - other_branch = branch1; - mode = b_mode; - sha = b_sha; - conf = "directory/file"; - } - if (string_list_has_string(¤t_directory_set, path)) { - const char *new_path = unique_path(path, add_branch); - clean_merge = 0; - output(1, "CONFLICT (%s): There is a directory with name %s in %s. " - "Adding %s as %s", - conf, path, other_branch, path, new_path); - remove_file(0, path, 0); - update_file(0, sha, mode, new_path); - } else { - output(2, "Adding %s", path); - update_file(1, sha, mode, path); - } - } else if (a_sha && b_sha) { - /* Case C: Added in both (check for same permissions) and */ - /* case D: Modified in both, but differently. */ - const char *reason = "content"; - struct merge_file_info mfi; - struct diff_filespec o, a, b; - - if (!o_sha) { - reason = "add/add"; - o_sha = (unsigned char *)null_sha1; - } - output(2, "Auto-merging %s", path); - o.path = a.path = b.path = (char *)path; - hashcpy(o.sha1, o_sha); - o.mode = o_mode; - hashcpy(a.sha1, a_sha); - a.mode = a_mode; - hashcpy(b.sha1, b_sha); - b.mode = b_mode; - - mfi = merge_file(&o, &a, &b, - branch1, branch2); - - clean_merge = mfi.clean; - if (mfi.clean) - update_file(1, mfi.sha, mfi.mode, path); - else if (S_ISGITLINK(mfi.mode)) - output(1, "CONFLICT (submodule): Merge conflict in %s " - "- needs %s", path, sha1_to_hex(b.sha1)); - else { - output(1, "CONFLICT (%s): Merge conflict in %s", - reason, path); - - if (index_only) - update_file(0, mfi.sha, mfi.mode, path); - else - update_file_flags(mfi.sha, mfi.mode, path, - 0 /* update_cache */, 1 /* update_working_directory */); - } - } else if (!o_sha && !a_sha && !b_sha) { - /* - * this entry was deleted altogether. a_mode == 0 means - * we had that path and want to actively remove it. - */ - remove_file(1, path, !a_mode); - } else - die("Fatal merge failure, shouldn't happen."); - - return clean_merge; -} - -int merge_trees(struct tree *head, - struct tree *merge, - struct tree *common, - const char *branch1, - const char *branch2, - struct tree **result) -{ - int code, clean; - - if (subtree_merge) { - merge = shift_tree_object(head, merge); - common = shift_tree_object(head, common); - } - - if (sha_eq(common->object.sha1, merge->object.sha1)) { - output(0, "Already uptodate!"); - *result = head; - return 1; - } - - code = git_merge_trees(index_only, common, head, merge); - - if (code != 0) - die("merging of trees %s and %s failed", - sha1_to_hex(head->object.sha1), - sha1_to_hex(merge->object.sha1)); - - if (unmerged_cache()) { - struct string_list *entries, *re_head, *re_merge; - int i; - string_list_clear(¤t_file_set, 1); - string_list_clear(¤t_directory_set, 1); - get_files_dirs(head); - get_files_dirs(merge); - - entries = get_unmerged(); - re_head = get_renames(head, common, head, merge, entries); - re_merge = get_renames(merge, common, head, merge, entries); - clean = process_renames(re_head, re_merge, - branch1, branch2); - for (i = 0; i < entries->nr; i++) { - const char *path = entries->items[i].string; - struct stage_data *e = entries->items[i].util; - if (!e->processed - && !process_entry(path, e, branch1, branch2)) - clean = 0; - } - - string_list_clear(re_merge, 0); - string_list_clear(re_head, 0); - string_list_clear(entries, 1); - - } - else - clean = 1; - - if (index_only) - *result = write_tree_from_memory(); - - return clean; -} - -static struct commit_list *reverse_commit_list(struct commit_list *list) -{ - struct commit_list *next = NULL, *current, *backup; - for (current = list; current; current = backup) { - backup = current->next; - current->next = next; - next = current; - } - return next; -} - -/* - * Merge the commits h1 and h2, return the resulting virtual - * commit object and a flag indicating the cleanness of the merge. - */ -int merge_recursive(struct commit *h1, - struct commit *h2, - const char *branch1, - const char *branch2, - struct commit_list *ca, - struct commit **result) -{ - struct commit_list *iter; - struct commit *merged_common_ancestors; - struct tree *mrtree = mrtree; - int clean; - - if (show(4)) { - output(4, "Merging:"); - output_commit_title(h1); - output_commit_title(h2); - } - - if (!ca) { - ca = get_merge_bases(h1, h2, 1); - ca = reverse_commit_list(ca); - } - - if (show(5)) { - output(5, "found %u common ancestor(s):", commit_list_count(ca)); - for (iter = ca; iter; iter = iter->next) - output_commit_title(iter->item); - } - - merged_common_ancestors = pop_commit(&ca); - if (merged_common_ancestors == NULL) { - /* if there is no common ancestor, make an empty tree */ - struct tree *tree = xcalloc(1, sizeof(struct tree)); - - tree->object.parsed = 1; - tree->object.type = OBJ_TREE; - pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1); - merged_common_ancestors = make_virtual_commit(tree, "ancestor"); - } - - for (iter = ca; iter; iter = iter->next) { - call_depth++; - /* - * When the merge fails, the result contains files - * with conflict markers. The cleanness flag is - * ignored, it was never actually used, as result of - * merge_trees has always overwritten it: the committed - * "conflicts" were already resolved. - */ - discard_cache(); - merge_recursive(merged_common_ancestors, iter->item, - "Temporary merge branch 1", - "Temporary merge branch 2", - NULL, - &merged_common_ancestors); - call_depth--; - - if (!merged_common_ancestors) - die("merge returned no commit"); - } - - discard_cache(); - if (!call_depth) { - read_cache(); - index_only = 0; - } else - index_only = 1; - - clean = merge_trees(h1->tree, h2->tree, merged_common_ancestors->tree, - branch1, branch2, &mrtree); - - if (index_only) { - *result = make_virtual_commit(mrtree, "merged tree"); - commit_list_insert(h1, &(*result)->parents); - commit_list_insert(h2, &(*result)->parents->next); - } - flush_output(); - return clean; -} - static const char *better_branch_name(const char *branch) { static char githead_env[8 + 40 + 1]; @@ -1314,103 +15,58 @@ static const char *better_branch_name(const char *branch) return name ? name : branch; } -static struct commit *get_ref(const char *ref) -{ - unsigned char sha1[20]; - struct object *object; - - if (get_sha1(ref, sha1)) - die("Could not resolve ref '%s'", ref); - object = deref_tag(parse_object(sha1), ref, strlen(ref)); - if (!object) - return NULL; - if (object->type == OBJ_TREE) - return make_virtual_commit((struct tree*)object, - better_branch_name(ref)); - if (object->type != OBJ_COMMIT) - return NULL; - if (parse_commit((struct commit *)object)) - die("Could not parse commit '%s'", sha1_to_hex(object->sha1)); - return (struct commit *)object; -} - -static int merge_config(const char *var, const char *value, void *cb) -{ - if (!strcasecmp(var, "merge.verbosity")) { - verbosity = git_config_int(var, value); - return 0; - } - if (!strcasecmp(var, "diff.renamelimit")) { - diff_rename_limit = git_config_int(var, value); - return 0; - } - if (!strcasecmp(var, "merge.renamelimit")) { - merge_rename_limit = git_config_int(var, value); - return 0; - } - return git_default_config(var, value, cb); -} - int cmd_merge_recursive(int argc, const char **argv, const char *prefix) { - static const char *bases[20]; - static unsigned bases_count = 0; - int i, clean; - const char *branch1, *branch2; - struct commit *result, *h1, *h2; - struct commit_list *ca = NULL; - struct lock_file *lock = xcalloc(1, sizeof(struct lock_file)); - int index_fd; + const unsigned char *bases[21]; + unsigned bases_count = 0; + int i, failed; + unsigned char h1[20], h2[20]; + struct merge_options o; + struct commit *result; + init_merge_options(&o); if (argv[0]) { int namelen = strlen(argv[0]); if (8 < namelen && !strcmp(argv[0] + namelen - 8, "-subtree")) - subtree_merge = 1; + o.subtree_merge = 1; } - git_config(merge_config, NULL); - if (getenv("GIT_MERGE_VERBOSITY")) - verbosity = strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10); - if (argc < 4) die("Usage: %s <base>... -- <head> <remote> ...\n", argv[0]); for (i = 1; i < argc; ++i) { if (!strcmp(argv[i], "--")) break; - if (bases_count < sizeof(bases)/sizeof(*bases)) - bases[bases_count++] = argv[i]; + if (bases_count < ARRAY_SIZE(bases)-1) { + unsigned char *sha = xmalloc(20); + if (get_sha1(argv[i], sha)) + die("Could not parse object '%s'", argv[i]); + bases[bases_count++] = sha; + } + else + warning("Cannot handle more than %zu bases. " + "Ignoring %s.", ARRAY_SIZE(bases)-1, argv[i]); } if (argc - i != 3) /* "--" "<head>" "<remote>" */ die("Not handling anything other than two heads merge."); - if (verbosity >= 5) - buffer_output = 0; - branch1 = argv[++i]; - branch2 = argv[++i]; + o.branch1 = argv[++i]; + o.branch2 = argv[++i]; - h1 = get_ref(branch1); - h2 = get_ref(branch2); + if (get_sha1(o.branch1, h1)) + die("Could not resolve ref '%s'", o.branch1); + if (get_sha1(o.branch2, h2)) + die("Could not resolve ref '%s'", o.branch2); - branch1 = better_branch_name(branch1); - branch2 = better_branch_name(branch2); - - if (show(3)) - printf("Merging %s with %s\n", branch1, branch2); - - index_fd = hold_locked_index(lock, 1); - - for (i = 0; i < bases_count; i++) { - struct commit *ancestor = get_ref(bases[i]); - ca = commit_list_insert(ancestor, &ca); - } - clean = merge_recursive(h1, h2, branch1, branch2, ca, &result); + o.branch1 = better_branch_name(o.branch1); + o.branch2 = better_branch_name(o.branch2); - if (active_cache_changed && - (write_cache(index_fd, active_cache, active_nr) || - commit_locked_index(lock))) - die ("unable to write %s", get_index_file()); + if (o.verbosity >= 3) + printf("Merging %s with %s\n", o.branch1, o.branch2); - return clean ? 0: 1; + failed = merge_recursive_generic(&o, h1, h2, bases_count, bases, &result); + if (failed < 0) + return 128; /* die() error code */ + return failed; } diff --git a/builtin-merge.c b/builtin-merge.c index 9ad9791068..5e7910bd8d 100644 --- a/builtin-merge.c +++ b/builtin-merge.c @@ -23,6 +23,7 @@ #include "color.h" #include "rerere.h" #include "help.h" +#include "merge-recursive.h" #define DEFAULT_TWOHEAD (1<<0) #define DEFAULT_OCTOPUS (1<<1) @@ -122,8 +123,7 @@ static struct strategy *get_strategy(const char *name) exit(1); } - ret = xmalloc(sizeof(struct strategy)); - memset(ret, 0, sizeof(struct strategy)); + ret = xcalloc(1, sizeof(struct strategy)); ret->name = xstrdup(name); return ret; } @@ -179,6 +179,7 @@ static void drop_save(void) { unlink(git_path("MERGE_HEAD")); unlink(git_path("MERGE_MSG")); + unlink(git_path("MERGE_MODE")); } static void save_state(void) @@ -226,7 +227,7 @@ static void reset_hard(unsigned const char *sha1, int verbose) static void restore_state(void) { - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; const char *args[] = { "stash", "apply", NULL, NULL }; if (is_null_sha1(stash)) @@ -234,7 +235,6 @@ static void restore_state(void) reset_hard(head, 1); - strbuf_init(&sb, 0); args[2] = sha1_to_hex(stash); /* @@ -258,7 +258,7 @@ static void squash_message(void) { struct rev_info rev; struct commit *commit; - struct strbuf out; + struct strbuf out = STRBUF_INIT; struct commit_list *j; int fd; @@ -282,7 +282,6 @@ static void squash_message(void) if (prepare_revision_walk(&rev)) die("revision walk setup failed"); - strbuf_init(&out, 0); strbuf_addstr(&out, "Squashed commit of the following:\n"); while ((commit = get_revision(&rev)) != NULL) { strbuf_addch(&out, '\n'); @@ -327,9 +326,8 @@ static int run_hook(const char *name) static void finish(const unsigned char *new_head, const char *msg) { - struct strbuf reflog_message; + struct strbuf reflog_message = STRBUF_INIT; - strbuf_init(&reflog_message, 0); if (!msg) strbuf_addstr(&reflog_message, getenv("GIT_REFLOG_ACTION")); else { @@ -380,7 +378,7 @@ static void merge_name(const char *remote, struct strbuf *msg) { struct object *remote_head; unsigned char branch_head[20], buf_sha[20]; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; const char *ptr; int len, early; @@ -389,7 +387,6 @@ static void merge_name(const char *remote, struct strbuf *msg) if (!remote_head) die("'%s' does not point to a commit", remote); - strbuf_init(&buf, 0); strbuf_addstr(&buf, "refs/heads/"); strbuf_addstr(&buf, remote); resolve_ref(buf.buf, branch_head, 0, 0); @@ -444,10 +441,9 @@ static void merge_name(const char *remote, struct strbuf *msg) if (!strcmp(remote, "FETCH_HEAD") && !access(git_path("FETCH_HEAD"), R_OK)) { FILE *fp; - struct strbuf line; + struct strbuf line = STRBUF_INIT; char *ptr; - strbuf_init(&line, 0); fp = fopen(git_path("FETCH_HEAD"), "r"); if (!fp) die("could not open %s for reading: %s", @@ -476,6 +472,8 @@ static int git_merge_config(const char *k, const char *v, void *cb) buf = xstrdup(v); argc = split_cmdline(buf, &argv); + if (argc < 0) + die("Bad branch.%s.mergeoptions string", branch); argv = xrealloc(argv, sizeof(*argv) * (argc + 2)); memmove(argv + 1, argv, sizeof(*argv) * (argc + 1)); argc++; @@ -543,30 +541,76 @@ static int try_merge_strategy(const char *strategy, struct commit_list *common, const char **args; int i = 0, ret; struct commit_list *j; - struct strbuf buf; - - args = xmalloc((4 + commit_list_count(common) + - commit_list_count(remoteheads)) * sizeof(char *)); - strbuf_init(&buf, 0); - strbuf_addf(&buf, "merge-%s", strategy); - args[i++] = buf.buf; - for (j = common; j; j = j->next) - args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1)); - args[i++] = "--"; - args[i++] = head_arg; - for (j = remoteheads; j; j = j->next) - args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1)); - args[i] = NULL; - ret = run_command_v_opt(args, RUN_GIT_CMD); - strbuf_release(&buf); - i = 1; - for (j = common; j; j = j->next) - free((void *)args[i++]); - i += 2; - for (j = remoteheads; j; j = j->next) - free((void *)args[i++]); - free(args); - return -ret; + struct strbuf buf = STRBUF_INIT; + int index_fd; + struct lock_file *lock = xcalloc(1, sizeof(struct lock_file)); + + index_fd = hold_locked_index(lock, 1); + refresh_cache(REFRESH_QUIET); + if (active_cache_changed && + (write_cache(index_fd, active_cache, active_nr) || + commit_locked_index(lock))) + return error("Unable to write index."); + rollback_lock_file(lock); + + if (!strcmp(strategy, "recursive") || !strcmp(strategy, "subtree")) { + int clean; + struct commit *result; + struct lock_file *lock = xcalloc(1, sizeof(struct lock_file)); + int index_fd; + struct commit_list *reversed = NULL; + struct merge_options o; + + if (remoteheads->next) { + error("Not handling anything other than two heads merge."); + return 2; + } + + init_merge_options(&o); + if (!strcmp(strategy, "subtree")) + o.subtree_merge = 1; + + o.branch1 = head_arg; + o.branch2 = remoteheads->item->util; + + for (j = common; j; j = j->next) + commit_list_insert(j->item, &reversed); + + index_fd = hold_locked_index(lock, 1); + clean = merge_recursive(&o, lookup_commit(head), + remoteheads->item, reversed, &result); + if (active_cache_changed && + (write_cache(index_fd, active_cache, active_nr) || + commit_locked_index(lock))) + die ("unable to write %s", get_index_file()); + rollback_lock_file(lock); + return clean ? 0 : 1; + } else { + args = xmalloc((4 + commit_list_count(common) + + commit_list_count(remoteheads)) * sizeof(char *)); + strbuf_addf(&buf, "merge-%s", strategy); + args[i++] = buf.buf; + for (j = common; j; j = j->next) + args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1)); + args[i++] = "--"; + args[i++] = head_arg; + for (j = remoteheads; j; j = j->next) + args[i++] = xstrdup(sha1_to_hex(j->item->object.sha1)); + args[i] = NULL; + ret = run_command_v_opt(args, RUN_GIT_CMD); + strbuf_release(&buf); + i = 1; + for (j = common; j; j = j->next) + free((void *)args[i++]); + i += 2; + for (j = remoteheads; j; j = j->next) + free((void *)args[i++]); + free(args); + discard_cache(); + if (read_cache() < 0) + die("failed to read the cache"); + return -ret; + } } static void count_diff_files(struct diff_queue_struct *q, @@ -683,15 +727,15 @@ static void add_strategies(const char *string, unsigned attr) static int merge_trivial(void) { unsigned char result_tree[20], result_commit[20]; - struct commit_list *parent = xmalloc(sizeof(struct commit_list *)); + struct commit_list *parent = xmalloc(sizeof(*parent)); write_tree_trivial(result_tree); printf("Wonderful.\n"); parent->item = lookup_commit(head); - parent->next = xmalloc(sizeof(struct commit_list *)); + parent->next = xmalloc(sizeof(*parent->next)); parent->next->item = remoteheads->item; parent->next->next = NULL; - commit_tree(merge_msg.buf, result_tree, parent, result_commit); + commit_tree(merge_msg.buf, result_tree, parent, result_commit, NULL); finish(result_commit, "In-index merge"); drop_save(); return 0; @@ -720,7 +764,7 @@ static int finish_automerge(struct commit_list *common, } free_commit_list(remoteheads); strbuf_addch(&merge_msg, '\n'); - commit_tree(merge_msg.buf, result_tree, parents, result_commit); + commit_tree(merge_msg.buf, result_tree, parents, result_commit, NULL); strbuf_addf(&buf, "Merge made by %s.", wt_strategy); finish(result_commit, buf.buf); strbuf_release(&buf); @@ -777,10 +821,6 @@ static int evaluate_result(void) int cnt = 0; struct rev_info rev; - discard_cache(); - if (read_cache() < 0) - die("failed to read the cache"); - /* Check how many files differ. */ init_revisions(&rev, ""); setup_revisions(0, NULL, &rev, NULL); @@ -802,7 +842,7 @@ static int evaluate_result(void) int cmd_merge(int argc, const char **argv, const char *prefix) { unsigned char result_tree[20]; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; const char *head_arg; int flag, head_invalid = 0, i; int best_cnt = -1, merge_was_ok = 0, automerge_was_ok = 0; @@ -851,7 +891,6 @@ int cmd_merge(int argc, const char **argv, const char *prefix) * Traditional format never would have "-m" so it is an * additional safety measure to check for it. */ - strbuf_init(&buf, 0); if (!have_message && is_old_style_invocation(argc, argv)) { strbuf_addstr(&merge_msg, argv[0]); @@ -881,7 +920,7 @@ int cmd_merge(int argc, const char **argv, const char *prefix) reset_hard(remote_head->sha1, 0); return 0; } else { - struct strbuf msg; + struct strbuf msg = STRBUF_INIT; /* We are invoked directly as the first-class UI. */ head_arg = "HEAD"; @@ -894,7 +933,6 @@ int cmd_merge(int argc, const char **argv, const char *prefix) * codepath so we discard the error in this * loop. */ - strbuf_init(&msg, 0); for (i = 0; i < argc; i++) merge_name(argv[i], &msg); fmt_merge_msg(option_log, &msg, &merge_msg); @@ -914,12 +952,14 @@ int cmd_merge(int argc, const char **argv, const char *prefix) for (i = 0; i < argc; i++) { struct object *o; + struct commit *commit; o = peel_to_type(argv[i], 0, NULL, OBJ_COMMIT); if (!o) die("%s - not something we can merge", argv[i]); - remotes = &commit_list_insert(lookup_commit(o->sha1), - remotes)->next; + commit = lookup_commit(o->sha1); + commit->util = (void *)argv[i]; + remotes = &commit_list_insert(commit, remotes)->next; strbuf_addf(&buf, "GITHEAD_%s", sha1_to_hex(o->sha1)); setenv(buf.buf, argv[i], 1); @@ -967,7 +1007,7 @@ int cmd_merge(int argc, const char **argv, const char *prefix) !common->next && !hashcmp(common->item->object.sha1, head)) { /* Again the most common case of merging one remote. */ - struct strbuf msg; + struct strbuf msg = STRBUF_INIT; struct object *o; char hex[41]; @@ -977,7 +1017,6 @@ int cmd_merge(int argc, const char **argv, const char *prefix) hex, find_unique_abbrev(remoteheads->item->object.sha1, DEFAULT_ABBREV)); - strbuf_init(&msg, 0); strbuf_addstr(&msg, "Fast forward"); if (have_message) strbuf_addstr(&msg, @@ -1113,7 +1152,6 @@ int cmd_merge(int argc, const char **argv, const char *prefix) } /* Automerge succeeded. */ - discard_cache(); write_tree_trivial(result_tree); automerge_was_ok = 1; break; @@ -1173,6 +1211,15 @@ int cmd_merge(int argc, const char **argv, const char *prefix) merge_msg.len) die("Could not write to %s", git_path("MERGE_MSG")); close(fd); + fd = open(git_path("MERGE_MODE"), O_WRONLY | O_CREAT | O_TRUNC, 0666); + if (fd < 0) + die("Could open %s for writing", git_path("MERGE_MODE")); + strbuf_reset(&buf); + if (!allow_fast_forward) + strbuf_addf(&buf, "no-ff"); + if (write_in_full(fd, buf.buf, buf.len) != buf.len) + die("Could not write to %s", git_path("MERGE_MODE")); + close(fd); } if (merge_was_ok) { diff --git a/builtin-pack-objects.c b/builtin-pack-objects.c index ba2cf00f5e..59c30d1caa 100644 --- a/builtin-pack-objects.c +++ b/builtin-pack-objects.c @@ -23,7 +23,7 @@ #endif static const char pack_usage[] = "\ -git-pack-objects [{ -q | --progress | --all-progress }] \n\ +git pack-objects [{ -q | --progress | --all-progress }] \n\ [--max-pack-size=N] [--local] [--incremental] \n\ [--window=N] [--window-memory=N] [--depth=N] \n\ [--no-reuse-delta] [--no-reuse-object] [--delta-base-offset] \n\ @@ -465,7 +465,7 @@ static void write_pack_file(void) char tmpname[PATH_MAX]; int fd; snprintf(tmpname, sizeof(tmpname), - "%s/tmp_pack_XXXXXX", get_object_directory()); + "%s/pack/tmp_pack_XXXXXX", get_object_directory()); fd = xmkstemp(tmpname); pack_tmp_name = xstrdup(tmpname); f = sha1fd(fd, pack_tmp_name); @@ -1369,12 +1369,10 @@ static void find_deltas(struct object_entry **list, unsigned *list_size, int window, int depth, unsigned *processed) { uint32_t i, idx = 0, count = 0; - unsigned int array_size = window * sizeof(struct unpacked); struct unpacked *array; unsigned long mem_usage = 0; - array = xmalloc(array_size); - memset(array, 0, array_size); + array = xcalloc(window, sizeof(struct unpacked)); for (;;) { struct object_entry *entry = *list++; @@ -1725,6 +1723,14 @@ static void prepare_pack(int window, int depth) if (entry->type < 0) die("unable to get type of object %s", sha1_to_hex(entry->idx.sha1)); + } else { + if (entry->type < 0) { + /* + * This object is not found, but we + * don't have to include it anyway. + */ + continue; + } } delta_list[n++] = entry; @@ -1872,7 +1878,7 @@ static void mark_in_pack_object(struct object *object, struct packed_git *p, str /* * Compare the objects in the offset order, in order to emulate the - * "git-rev-list --objects" output that produced the pack originally. + * "git rev-list --objects" output that produced the pack originally. */ static int ofscmp(const void *a_, const void *b_) { diff --git a/builtin-prune.c b/builtin-prune.c index c767a0ac89..7b4ec80e62 100644 --- a/builtin-prune.c +++ b/builtin-prune.c @@ -7,13 +7,14 @@ #include "parse-options.h" static const char * const prune_usage[] = { - "git prune [-n] [--expire <time>] [--] [<head>...]", + "git prune [-n] [-v] [--expire <time>] [--] [<head>...]", NULL }; static int show_only; +static int verbose; static unsigned long expire; -static int prune_tmp_object(char *path, const char *filename) +static int prune_tmp_object(const char *path, const char *filename) { const char *fullpath = mkpath("%s/%s", path, filename); if (expire) { @@ -39,11 +40,12 @@ static int prune_object(char *path, const char *filename, const unsigned char *s if (st.st_mtime > expire) return 0; } - if (show_only) { + if (show_only || verbose) { enum object_type type = sha1_object_info(sha1, NULL); printf("%s %s\n", sha1_to_hex(sha1), (type > 0) ? typename(type) : "unknown"); - } else + } + if (!show_only) unlink(fullpath); return 0; } @@ -110,24 +112,22 @@ static void prune_object_dir(const char *path) /* * Write errors (particularly out of space) can result in * failed temporary packs (and more rarely indexes and other - * files begining with "tmp_") accumulating in the - * object directory. + * files begining with "tmp_") accumulating in the object + * and the pack directories. */ -static void remove_temporary_files(void) +static void remove_temporary_files(const char *path) { DIR *dir; struct dirent *de; - char* dirname=get_object_directory(); - dir = opendir(dirname); + dir = opendir(path); if (!dir) { - fprintf(stderr, "Unable to open object directory %s\n", - dirname); + fprintf(stderr, "Unable to open directory %s\n", path); return; } while ((de = readdir(dir)) != NULL) if (!prefixcmp(de->d_name, "tmp_")) - prune_tmp_object(dirname, de->d_name); + prune_tmp_object(path, de->d_name); closedir(dir); } @@ -137,10 +137,13 @@ int cmd_prune(int argc, const char **argv, const char *prefix) const struct option options[] = { OPT_BOOLEAN('n', NULL, &show_only, "do not remove, show only"), + OPT_BOOLEAN('v', NULL, &verbose, + "report pruned objects"), OPT_DATE(0, "expire", &expire, "expire objects older than <time>"), OPT_END() }; + char *s; save_commit_buffer = 0; init_revisions(&revs, prefix); @@ -163,6 +166,9 @@ int cmd_prune(int argc, const char **argv, const char *prefix) prune_object_dir(get_object_directory()); prune_packed_objects(show_only); - remove_temporary_files(); + remove_temporary_files(get_object_directory()); + s = xstrdup(mkpath("%s/pack", get_object_directory())); + remove_temporary_files(s); + free(s); return 0; } diff --git a/builtin-push.c b/builtin-push.c index cc6666f75e..122fdcfbdc 100644 --- a/builtin-push.c +++ b/builtin-push.c @@ -10,7 +10,7 @@ #include "parse-options.h" static const char * const push_usage[] = { - "git push [--all | --mirror] [--dry-run] [--tags] [--receive-pack=<git-receive-pack>] [--repo=all] [-f | --force] [-v] [<repository> <refspec>...]", + "git push [--all | --mirror] [--dry-run] [--tags] [--receive-pack=<git-receive-pack>] [--repo=<repository>] [-f | --force] [-v] [<repository> <refspec>...]", NULL, }; diff --git a/builtin-read-tree.c b/builtin-read-tree.c index dddc3044b8..0706c95818 100644 --- a/builtin-read-tree.c +++ b/builtin-read-tree.c @@ -64,7 +64,7 @@ static void prime_cache_tree(void) } -static const char read_tree_usage[] = "git-read-tree (<sha> | [[-m [--trivial] [--aggressive] | --reset | --prefix=<prefix>] [-u | -i]] [--exclude-per-directory=<gitignore>] [--index-output=<file>] <sha1> [<sha2> [<sha3>]])"; +static const char read_tree_usage[] = "git read-tree (<sha> | [[-m [--trivial] [--aggressive] | --reset | --prefix=<prefix>] [-u | -i]] [--exclude-per-directory=<gitignore>] [--index-output=<file>] <sha1> [<sha2> [<sha3>]])"; static struct lock_file lock_file; @@ -206,6 +206,7 @@ int cmd_read_tree(int argc, const char **argv, const char *unused_prefix) break; case 2: opts.fn = twoway_merge; + opts.initial_checkout = !active_nr; break; case 3: default: diff --git a/receive-pack.c b/builtin-receive-pack.c index b81678a970..45e3cd90fd 100644 --- a/receive-pack.c +++ b/builtin-receive-pack.c @@ -6,6 +6,8 @@ #include "exec_cmd.h" #include "commit.h" #include "object.h" +#include "remote.h" +#include "transport.h" static const char receive_pack_usage[] = "git-receive-pack <git-dir>"; @@ -462,14 +464,48 @@ static int delete_only(struct command *cmd) return 1; } -int main(int argc, char **argv) +static int add_refs_from_alternate(struct alternate_object_database *e, void *unused) +{ + char *other = xstrdup(make_absolute_path(e->base)); + size_t len = strlen(other); + struct remote *remote; + struct transport *transport; + const struct ref *extra; + + while (other[len-1] == '/') + other[--len] = '\0'; + if (len < 8 || memcmp(other + len - 8, "/objects", 8)) + return 0; + /* Is this a git repository with refs? */ + memcpy(other + len - 8, "/refs", 6); + if (!is_directory(other)) + return 0; + other[len - 8] = '\0'; + remote = remote_get(other); + transport = transport_get(remote, other); + for (extra = transport_get_remote_refs(transport); + extra; + extra = extra->next) { + add_extra_ref(".have", extra->old_sha1, 0); + } + transport_disconnect(transport); + free(other); + return 0; +} + +static void add_alternate_refs(void) +{ + foreach_alt_odb(add_refs_from_alternate, NULL); +} + +int cmd_receive_pack(int argc, const char **argv, const char *prefix) { int i; char *dir = NULL; argv++; for (i = 1; i < argc; i++) { - char *arg = *argv++; + const char *arg = *argv++; if (*arg == '-') { /* Do flag handling here */ @@ -477,7 +513,7 @@ int main(int argc, char **argv) } if (dir) usage(receive_pack_usage); - dir = arg; + dir = xstrdup(arg); } if (!dir) usage(receive_pack_usage); @@ -497,7 +533,9 @@ int main(int argc, char **argv) else if (0 <= receive_unpack_limit) unpack_limit = receive_unpack_limit; + add_alternate_refs(); write_head_info(); + clear_extra_refs(); /* EOF */ packet_flush(1); diff --git a/builtin-remote.c b/builtin-remote.c index 01945a8651..6b3325dfa9 100644 --- a/builtin-remote.c +++ b/builtin-remote.c @@ -54,7 +54,7 @@ static int add(int argc, const char **argv) struct string_list track = { NULL, 0, 0 }; const char *master = NULL; struct remote *remote; - struct strbuf buf, buf2; + struct strbuf buf = STRBUF_INIT, buf2 = STRBUF_INIT; const char *name, *url; int i; @@ -81,9 +81,6 @@ static int add(int argc, const char **argv) remote->fetch_refspec_nr)) die("remote %s already exists.", name); - strbuf_init(&buf, 0); - strbuf_init(&buf2, 0); - strbuf_addf(&buf2, "refs/heads/test:refs/remotes/%s/test", name); if (!valid_fetch_refspec(buf2.buf)) die("'%s' is not a valid remote name", name); @@ -352,7 +349,7 @@ static int rm(int argc, const char **argv) OPT_END() }; struct remote *remote; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; struct known_remotes known_remotes = { NULL, NULL }; struct string_list branches = { NULL, 0, 0, 1 }; struct branches_for_remote cb_data = { NULL, &branches, &known_remotes }; @@ -368,7 +365,6 @@ static int rm(int argc, const char **argv) known_remotes.to_delete = remote; for_each_remote(add_known_remote, &known_remotes); - strbuf_init(&buf, 0); strbuf_addf(&buf, "remote.%s", remote->name); if (git_config_rename_section(buf.buf, NULL) < 1) return error("Could not remove config section '%s'", buf.buf); @@ -407,14 +403,15 @@ static int rm(int argc, const char **argv) return i; } -static void show_list(const char *title, struct string_list *list) +static void show_list(const char *title, struct string_list *list, + const char *extra_arg) { int i; if (!list->nr) return; - printf(title, list->nr > 1 ? "es" : ""); + printf(title, list->nr > 1 ? "es" : "", extra_arg); printf("\n "); for (i = 0; i < list->nr; i++) printf("%s%s", i ? " " : "", list->items[i].string); @@ -477,7 +474,6 @@ static int show(int argc, const char **argv) memset(&states, 0, sizeof(states)); for (; argc; argc--, argv++) { - struct strbuf buf; int i; get_remote_ref_states(*argv, &states, !no_query); @@ -503,18 +499,16 @@ static int show(int argc, const char **argv) } if (!no_query) { - strbuf_init(&buf, 0); - strbuf_addf(&buf, " New remote branch%%s (next fetch " - "will store in remotes/%s)", states.remote->name); - show_list(buf.buf, &states.new); - strbuf_release(&buf); + show_list(" New remote branch%s (next fetch " + "will store in remotes/%s)", + &states.new, states.remote->name); show_list(" Stale tracking branch%s (use 'git remote " - "prune')", &states.stale); + "prune')", &states.stale, ""); } if (no_query) for_each_ref(append_ref_to_tracked_list, &states); - show_list(" Tracked remote branch%s", &states.tracked); + show_list(" Tracked remote branch%s", &states.tracked, ""); if (states.remote->push_refspec_nr) { printf(" Local branch%s pushed with 'git push'\n ", @@ -652,10 +646,13 @@ static int get_one_entry(struct remote *remote, void *priv) { struct string_list *list = priv; - string_list_append(remote->name, list)->util = remote->url_nr ? - (void *)remote->url[0] : NULL; - if (remote->url_nr > 1) - warning("Remote %s has more than one URL", remote->name); + if (remote->url_nr > 0) { + int i; + + for (i = 0; i < remote->url_nr; i++) + string_list_append(remote->name, list)->util = (void *)remote->url[i]; + } else + string_list_append(remote->name, list)->util = NULL; return 0; } @@ -671,10 +668,14 @@ static int show_all(void) sort_string_list(&list); for (i = 0; i < list.nr; i++) { struct string_list_item *item = list.items + i; - printf("%s%s%s\n", item->string, - verbose ? "\t" : "", - verbose && item->util ? - (const char *)item->util : ""); + if (verbose) + printf("%s\t%s\n", item->string, + item->util ? (const char *)item->util : ""); + else { + if (i && !strcmp((item - 1)->string, item->string)) + continue; + printf("%s\n", item->string); + } } } return result; diff --git a/builtin-reset.c b/builtin-reset.c index c24c219091..16e6bb20f1 100644 --- a/builtin-reset.c +++ b/builtin-reset.c @@ -121,6 +121,9 @@ static void update_index_from_diff(struct diff_queue_struct *q, struct cache_entry *ce; ce = make_cache_entry(one->mode, one->sha1, one->path, 0, 0); + if (!ce) + die("make_cache_entry failed for path '%s'", + one->path); add_cache_entry(ce, ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE); } else diff --git a/builtin-rev-list.c b/builtin-rev-list.c index c023003b2b..06cdeb7ebe 100644 --- a/builtin-rev-list.c +++ b/builtin-rev-list.c @@ -107,8 +107,7 @@ static void show_commit(struct commit *commit) putchar('\n'); if (revs.verbose_header && commit->buffer) { - struct strbuf buf; - strbuf_init(&buf, 0); + struct strbuf buf = STRBUF_INIT; pretty_print_commit(revs.commit_format, commit, &buf, revs.abbrev, NULL, NULL, revs.date_mode, 0); @@ -178,7 +177,7 @@ static void finish_object(struct object_array_entry *p) static void show_object(struct object_array_entry *p) { /* An object with name "foo\n0000000..." can be used to - * confuse downstream git-pack-objects very badly. + * confuse downstream "git pack-objects" very badly. */ const char *ep = strchr(p->name, '\n'); diff --git a/builtin-rev-parse.c b/builtin-rev-parse.c index 9aa049ec17..81d5a6ffc9 100644 --- a/builtin-rev-parse.c +++ b/builtin-rev-parse.c @@ -307,19 +307,17 @@ static int cmd_parseopt(int argc, const char **argv, const char *prefix) OPT_END(), }; - struct strbuf sb, parsed; + struct strbuf sb = STRBUF_INIT, parsed = STRBUF_INIT; const char **usage = NULL; struct option *opts = NULL; int onb = 0, osz = 0, unb = 0, usz = 0; - strbuf_init(&parsed, 0); strbuf_addstr(&parsed, "set --"); argc = parse_options(argc, argv, parseopt_opts, parseopt_usage, PARSE_OPT_KEEP_DASHDASH); if (argc < 1 || strcmp(argv[0], "--")) usage_with_options(parseopt_usage, parseopt_opts); - strbuf_init(&sb, 0); /* get the usage up to the first line with a -- on it */ for (;;) { if (strbuf_getline(&sb, stdin, '\n') == EOF) diff --git a/builtin-revert.c b/builtin-revert.c index 36677053f8..8486539740 100644 --- a/builtin-revert.c +++ b/builtin-revert.c @@ -12,6 +12,7 @@ #include "diff.h" #include "revision.h" #include "rerere.h" +#include "merge-recursive.h" /* * This implements the builtins revert and cherry-pick. @@ -201,36 +202,6 @@ static void set_author_ident_env(const char *message) sha1_to_hex(commit->object.sha1)); } -static int merge_recursive(const char *base_sha1, - const char *head_sha1, const char *head_name, - const char *next_sha1, const char *next_name) -{ - char buffer[256]; - const char *argv[6]; - int i = 0; - - sprintf(buffer, "GITHEAD_%s", head_sha1); - setenv(buffer, head_name, 1); - sprintf(buffer, "GITHEAD_%s", next_sha1); - setenv(buffer, next_name, 1); - - /* - * This three way merge is an interesting one. We are at - * $head, and would want to apply the change between $commit - * and $prev on top of us (when reverting), or the change between - * $prev and $commit on top of us (when cherry-picking or replaying). - */ - argv[i++] = "merge-recursive"; - if (base_sha1) - argv[i++] = base_sha1; - argv[i++] = "--"; - argv[i++] = head_sha1; - argv[i++] = next_sha1; - argv[i++] = NULL; - - return run_command_v_opt(argv, RUN_COMMAND_NO_STDIN | RUN_GIT_CMD); -} - static char *help_msg(const unsigned char *sha1) { static char helpbuf[1024]; @@ -263,14 +234,27 @@ static int index_is_dirty(void) return !!DIFF_OPT_TST(&rev.diffopt, HAS_CHANGES); } +static struct tree *empty_tree(void) +{ + struct tree *tree = xcalloc(1, sizeof(struct tree)); + + tree->object.parsed = 1; + tree->object.type = OBJ_TREE; + pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1); + return tree; +} + static int revert_or_cherry_pick(int argc, const char **argv) { unsigned char head[20]; struct commit *base, *next, *parent; - int i; + int i, index_fd, clean; char *oneline, *reencoded_message = NULL; const char *message, *encoding; const char *defmsg = xstrdup(git_path("MERGE_MSG")); + struct merge_options o; + struct tree *result, *next_tree, *base_tree, *head_tree; + static struct lock_file index_lock; git_config(git_default_config, NULL); me = action == REVERT ? "revert" : "cherry-pick"; @@ -281,6 +265,8 @@ static int revert_or_cherry_pick(int argc, const char **argv) if (action == REVERT && !no_replay) die("revert is incompatible with replay"); + if (read_cache() < 0) + die("git %s: failed to read the index", me); if (no_commit) { /* * We do not intend to commit immediately. We just want to @@ -293,12 +279,12 @@ static int revert_or_cherry_pick(int argc, const char **argv) } else { if (get_sha1("HEAD", head)) die ("You do not have a valid HEAD"); - if (read_cache() < 0) - die("could not read the index"); if (index_is_dirty()) die ("Dirty index: cannot %s", me); - discard_cache(); } + discard_cache(); + + index_fd = hold_locked_index(&index_lock, 1); if (!commit->parents) { if (action == REVERT) @@ -332,6 +318,10 @@ static int revert_or_cherry_pick(int argc, const char **argv) die ("Cannot get commit message for %s", sha1_to_hex(commit->object.sha1)); + if (parent && parse_commit(parent) < 0) + die("%s: cannot parse parent commit %s", + me, sha1_to_hex(parent->object.sha1)); + /* * "commit" is an existing commit. We would want to apply * the difference it introduces since its first parent "prev" @@ -374,13 +364,26 @@ static int revert_or_cherry_pick(int argc, const char **argv) } } - if (merge_recursive(base == NULL ? - NULL : sha1_to_hex(base->object.sha1), - sha1_to_hex(head), "HEAD", - sha1_to_hex(next->object.sha1), oneline) || - write_cache_as_tree(head, 0, NULL)) { + read_cache(); + init_merge_options(&o); + o.branch1 = "HEAD"; + o.branch2 = oneline; + + head_tree = parse_tree_indirect(head); + next_tree = next ? next->tree : empty_tree(); + base_tree = base ? base->tree : empty_tree(); + + clean = merge_trees(&o, + head_tree, + next_tree, base_tree, &result); + + if (active_cache_changed && + (write_cache(index_fd, active_cache, active_nr) || + commit_locked_index(&index_lock))) + die("%s: Unable to write new index file", me); + + if (!clean) { add_to_msg("\nConflicts:\n\n"); - read_cache(); for (i = 0; i < active_nr;) { struct cache_entry *ce = active_cache[i++]; if (ce_stage(ce)) { diff --git a/builtin-rm.c b/builtin-rm.c index 6bd82111d2..e06640cf8d 100644 --- a/builtin-rm.c +++ b/builtin-rm.c @@ -29,26 +29,6 @@ static void add_list(const char *name) list.name[list.nr++] = name; } -static int remove_file(const char *name) -{ - int ret; - char *slash; - - ret = unlink(name); - if (ret && errno == ENOENT) - /* The user has removed it from the filesystem by hand */ - ret = errno = 0; - - if (!ret && (slash = strrchr(name, '/'))) { - char *n = xstrdup(name); - do { - n[slash - name] = 0; - name = n; - } while (!rmdir(name) && (slash = strrchr(name, '/'))); - } - return ret; -} - static int check_local_mod(unsigned char *head, int index_only) { /* items in list are already sorted in the cache order, @@ -104,7 +84,7 @@ static int check_local_mod(unsigned char *head, int index_only) "from both the file and the HEAD\n" "(use -f to force removal)", name); else if (!index_only) { - /* It's not dangerous to git-rm --cached a + /* It's not dangerous to "git rm --cached" a * file if the index matches the file or the * HEAD, since it means the deleted content is * still available somewhere. @@ -157,6 +137,7 @@ int cmd_rm(int argc, const char **argv, const char *prefix) if (read_cache() < 0) die("index file corrupt"); + refresh_cache(REFRESH_QUIET); pathspec = get_pathspec(prefix, argv); seen = NULL; @@ -239,7 +220,7 @@ int cmd_rm(int argc, const char **argv, const char *prefix) int removed = 0; for (i = 0; i < list.nr; i++) { const char *path = list.name[i]; - if (!remove_file(path)) { + if (!remove_path(path)) { removed = 1; continue; } diff --git a/builtin-send-pack.c b/builtin-send-pack.c index 7588d22885..910db92b62 100644 --- a/builtin-send-pack.c +++ b/builtin-send-pack.c @@ -18,7 +18,7 @@ static struct send_pack_args args = { /* * Make a pack stream and spit it out into file descriptor fd */ -static int pack_objects(int fd, struct ref *refs) +static int pack_objects(int fd, struct ref *refs, struct extra_have_objects *extra) { /* * The child becomes pack-objects --revs; we feed @@ -34,6 +34,8 @@ static int pack_objects(int fd, struct ref *refs) NULL, }; struct child_process po; + int i; + char buf[42]; if (args.use_thin_pack) argv[4] = "--thin"; @@ -43,15 +45,21 @@ static int pack_objects(int fd, struct ref *refs) po.out = fd; po.git_cmd = 1; if (start_command(&po)) - die("git-pack-objects failed (%s)", strerror(errno)); + die("git pack-objects failed (%s)", strerror(errno)); /* * We feed the pack-objects we just spawned with revision * parameters by writing to the pipe. */ - while (refs) { - char buf[42]; + for (i = 0; i < extra->nr; i++) { + memcpy(buf + 1, sha1_to_hex(&extra->array[i][0]), 40); + buf[0] = '^'; + buf[41] = '\n'; + if (!write_or_whine(po.in, buf, 42, "send-pack: send refs")) + break; + } + while (refs) { if (!is_null_sha1(refs->old_sha1) && has_sha1_file(refs->old_sha1)) { memcpy(buf + 1, sha1_to_hex(refs->old_sha1), 40); @@ -381,14 +389,17 @@ static int do_send_pack(int in, int out, struct remote *remote, const char *dest int expect_status_report = 0; int flags = MATCH_REFS_NONE; int ret; + struct extra_have_objects extra_have; + memset(&extra_have, 0, sizeof(extra_have)); if (args.send_all) flags |= MATCH_REFS_ALL; if (args.send_mirror) flags |= MATCH_REFS_MIRROR; /* No funny business with the matcher */ - remote_tail = get_remote_heads(in, &remote_refs, 0, NULL, REF_NORMAL); + remote_tail = get_remote_heads(in, &remote_refs, 0, NULL, REF_NORMAL, + &extra_have); get_local_heads(); /* Does the other end support the reporting? */ @@ -496,7 +507,7 @@ static int do_send_pack(int in, int out, struct remote *remote, const char *dest packet_flush(out); if (new_refs && !args.dry_run) { - if (pack_objects(out, remote_refs) < 0) + if (pack_objects(out, remote_refs, &extra_have) < 0) return -1; } else diff --git a/builtin-show-branch.c b/builtin-show-branch.c index 233eed499d..306b850c72 100644 --- a/builtin-show-branch.c +++ b/builtin-show-branch.c @@ -259,11 +259,10 @@ static void join_revs(struct commit_list **list_p, static void show_one_commit(struct commit *commit, int no_name) { - struct strbuf pretty; + struct strbuf pretty = STRBUF_INIT; const char *pretty_str = "(unavailable)"; struct commit_name *name = commit->util; - strbuf_init(&pretty, 0); if (commit->object.parsed) { pretty_print_commit(CMIT_FMT_ONELINE, commit, &pretty, 0, NULL, NULL, 0, 0); diff --git a/builtin-stripspace.c b/builtin-stripspace.c index c0b21301ba..d6e3896c00 100644 --- a/builtin-stripspace.c +++ b/builtin-stripspace.c @@ -70,14 +70,13 @@ void stripspace(struct strbuf *sb, int skip_comments) int cmd_stripspace(int argc, const char **argv, const char *prefix) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; int strip_comments = 0; if (argc > 1 && (!strcmp(argv[1], "-s") || !strcmp(argv[1], "--strip-comments"))) strip_comments = 1; - strbuf_init(&buf, 0); if (strbuf_read(&buf, 0, 1024) < 0) die("could not read the input"); diff --git a/builtin-tag.c b/builtin-tag.c index f2853d08c7..b13fa34d8c 100644 --- a/builtin-tag.c +++ b/builtin-tag.c @@ -338,7 +338,7 @@ static int parse_msg_arg(const struct option *opt, const char *arg, int unset) int cmd_tag(int argc, const char **argv, const char *prefix) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; unsigned char object[20], prev[20]; char ref[PATH_MAX]; const char *object_ref, *tag; @@ -388,7 +388,6 @@ int cmd_tag(int argc, const char **argv, const char *prefix) if (verify) return for_each_tag_name(argv, verify_tag); - strbuf_init(&buf, 0); if (msg.given || msgfile) { if (msg.given && msgfile) die("only one -F or -m option is allowed."); diff --git a/builtin-tar-tree.c b/builtin-tar-tree.c index cb7007e25f..0713bca778 100644 --- a/builtin-tar-tree.c +++ b/builtin-tar-tree.c @@ -9,26 +9,26 @@ static const char tar_tree_usage[] = "git tar-tree [--remote=<repo>] <tree-ish> [basedir]\n" -"*** Note that this command is now deprecated; use git-archive instead."; +"*** Note that this command is now deprecated; use \"git archive\" instead."; int cmd_tar_tree(int argc, const char **argv, const char *prefix) { /* - * git-tar-tree is now a wrapper around git-archive --format=tar + * "git tar-tree" is now a wrapper around "git archive --format=tar" * * $0 --remote=<repo> arg... ==> - * git-archive --format=tar --remote=<repo> arg... + * git archive --format=tar --remote=<repo> arg... * $0 tree-ish ==> - * git-archive --format=tar tree-ish + * git archive --format=tar tree-ish * $0 tree-ish basedir ==> - * git-archive --format-tar --prefix=basedir tree-ish + * git archive --format-tar --prefix=basedir tree-ish */ int i; const char **nargv = xcalloc(sizeof(*nargv), argc + 2); char *basedir_arg; int nargc = 0; - nargv[nargc++] = "git-archive"; + nargv[nargc++] = "archive"; nargv[nargc++] = "--format=tar"; if (2 <= argc && !prefixcmp(argv[1], "--remote=")) { @@ -53,8 +53,8 @@ int cmd_tar_tree(int argc, const char **argv, const char *prefix) nargv[nargc] = NULL; fprintf(stderr, - "*** git-tar-tree is now deprecated.\n" - "*** Running git-archive instead.\n***"); + "*** \"git tar-tree\" is now deprecated.\n" + "*** Running \"git archive\" instead.\n***"); for (i = 0; i < nargc; i++) { fputc(' ', stderr); sq_quote_print(stderr, nargv[i]); diff --git a/builtin-unpack-objects.c b/builtin-unpack-objects.c index a891866665..9f4bdd3296 100644 --- a/builtin-unpack-objects.c +++ b/builtin-unpack-objects.c @@ -13,13 +13,13 @@ #include "fsck.h" static int dry_run, quiet, recover, has_errors, strict; -static const char unpack_usage[] = "git-unpack-objects [-n] [-q] [-r] [--strict] < pack-file"; +static const char unpack_usage[] = "git unpack-objects [-n] [-q] [-r] [--strict] < pack-file"; /* We always read in 4kB chunks. */ static unsigned char buffer[4096]; static unsigned int offset, len; static off_t consumed_bytes; -static SHA_CTX ctx; +static git_SHA_CTX ctx; /* * When running under --strict mode, objects whose reachability are @@ -59,7 +59,7 @@ static void *fill(int min) if (min > sizeof(buffer)) die("cannot fill %d bytes", min); if (offset) { - SHA1_Update(&ctx, buffer, offset); + git_SHA1_Update(&ctx, buffer, offset); memmove(buffer, buffer + offset, len); offset = 0; } @@ -477,8 +477,7 @@ static void unpack_all(void) if (!quiet) progress = start_progress("Unpacking objects", nr_objects); - obj_list = xmalloc(nr_objects * sizeof(*obj_list)); - memset(obj_list, 0, nr_objects * sizeof(*obj_list)); + obj_list = xcalloc(nr_objects, sizeof(*obj_list)); for (i = 0; i < nr_objects; i++) { unpack_one(i); display_progress(progress, i + 1); @@ -539,10 +538,10 @@ int cmd_unpack_objects(int argc, const char **argv, const char *prefix) /* We don't take any non-flag arguments now.. Maybe some day */ usage(unpack_usage); } - SHA1_Init(&ctx); + git_SHA1_Init(&ctx); unpack_all(); - SHA1_Update(&ctx, buffer, offset); - SHA1_Final(sha1, &ctx); + git_SHA1_Update(&ctx, buffer, offset); + git_SHA1_Final(sha1, &ctx); if (strict) write_rest(); if (hashcmp(fill(20), sha1)) diff --git a/builtin-update-index.c b/builtin-update-index.c index ce83224756..65d5775107 100644 --- a/builtin-update-index.c +++ b/builtin-update-index.c @@ -14,7 +14,7 @@ * Default to not allowing changes to the list of files. The * tool doesn't actually care, but this makes it harder to add * files to the revision control by mistake by doing something - * like "git-update-index *" and suddenly having all the object + * like "git update-index *" and suddenly having all the object * files be revision controlled. */ static int allow_add; @@ -218,7 +218,7 @@ static int add_cacheinfo(unsigned int mode, const unsigned char *sha1, struct cache_entry *ce; if (!verify_path(path)) - return -1; + return error("Invalid path '%s'", path); len = strlen(path); size = cache_entry_size(len); @@ -297,11 +297,9 @@ static void update_one(const char *path, const char *prefix, int prefix_length) static void read_index_info(int line_termination) { - struct strbuf buf; - struct strbuf uq; + struct strbuf buf = STRBUF_INIT; + struct strbuf uq = STRBUF_INIT; - strbuf_init(&buf, 0); - strbuf_init(&uq, 0); while (strbuf_getline(&buf, stdin, line_termination) != EOF) { char *ptr, *tab; char *path_name; @@ -313,18 +311,18 @@ static void read_index_info(int line_termination) /* This reads lines formatted in one of three formats: * * (1) mode SP sha1 TAB path - * The first format is what "git-apply --index-info" + * The first format is what "git apply --index-info" * reports, and used to reconstruct a partial tree * that is used for phony merge base tree when falling * back on 3-way merge. * * (2) mode SP type SP sha1 TAB path - * The second format is to stuff git-ls-tree output + * The second format is to stuff "git ls-tree" output * into the index file. * * (3) mode SP sha1 SP stage TAB path * This format is to put higher order stages into the - * index file and matches git-ls-files --stage output. + * index file and matches "git ls-files --stage" output. */ errno = 0; ul = strtoul(buf.buf, &ptr, 8); @@ -717,10 +715,8 @@ int cmd_update_index(int argc, const char **argv, const char *prefix) free((char*)p); } if (read_from_stdin) { - struct strbuf buf, nbuf; + struct strbuf buf = STRBUF_INIT, nbuf = STRBUF_INIT; - strbuf_init(&buf, 0); - strbuf_init(&nbuf, 0); setup_work_tree(); while (strbuf_getline(&buf, stdin, line_termination) != EOF) { const char *p; @@ -17,7 +17,8 @@ extern int read_line_with_nul(char *buf, int size, FILE *file); extern int fmt_merge_msg(int merge_summary, struct strbuf *in, struct strbuf *out); extern int commit_tree(const char *msg, unsigned char *tree, - struct commit_list *parents, unsigned char *ret); + struct commit_list *parents, unsigned char *ret, + const char *author); extern int check_pager_config(const char *cmd); extern int cmd_add(int argc, const char **argv, const char *prefix); @@ -78,6 +79,7 @@ extern int cmd_prune(int argc, const char **argv, const char *prefix); extern int cmd_prune_packed(int argc, const char **argv, const char *prefix); extern int cmd_push(int argc, const char **argv, const char *prefix); extern int cmd_read_tree(int argc, const char **argv, const char *prefix); +extern int cmd_receive_pack(int argc, const char **argv, const char *prefix); extern int cmd_reflog(int argc, const char **argv, const char *prefix); extern int cmd_remote(int argc, const char **argv, const char *prefix); extern int cmd_config(int argc, const char **argv, const char *prefix); @@ -6,8 +6,14 @@ #include "hash.h" #include SHA1_HEADER -#include <zlib.h> +#ifndef git_SHA_CTX +#define git_SHA_CTX SHA_CTX +#define git_SHA1_Init SHA1_Init +#define git_SHA1_Update SHA1_Update +#define git_SHA1_Final SHA1_Final +#endif +#include <zlib.h> #if defined(NO_DEFLATE_BOUND) || ZLIB_VERNUM < 0x1200 #define deflateBound(c,s) ((s) + (((s) + 7) >> 3) + (((s) + 63) >> 6) + 11) #endif @@ -313,6 +319,7 @@ extern int is_bare_repository(void); extern int is_inside_git_dir(void); extern char *git_work_tree_cfg; extern int is_inside_work_tree(void); +extern int have_git_dir(void); extern const char *get_git_dir(void); extern char *get_object_directory(void); extern char *get_index_file(void); @@ -371,6 +378,7 @@ extern int index_name_pos(const struct index_state *, const char *name, int name #define ADD_CACHE_OK_TO_REPLACE 2 /* Ok to replace file/directory */ #define ADD_CACHE_SKIP_DFCHECK 4 /* Ok to skip DF conflict checks */ #define ADD_CACHE_JUST_APPEND 8 /* Append only; tree.c::read_tree() */ +#define ADD_CACHE_NEW_ONLY 16 /* Do not replace existing ones */ extern int add_index_entry(struct index_state *, struct cache_entry *ce, int option); extern struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really); extern void rename_index_entry_at(struct index_state *, int pos, const char *new_name); @@ -380,6 +388,7 @@ extern int remove_file_from_index(struct index_state *, const char *path); #define ADD_CACHE_PRETEND 2 #define ADD_CACHE_IGNORE_ERRORS 4 #define ADD_CACHE_IGNORE_REMOVAL 8 +#define ADD_CACHE_INTENT 16 extern int add_to_index(struct index_state *, const char *path, struct stat *, int flags); extern int add_file_to_index(struct index_state *, const char *path, int flags); extern struct cache_entry *make_cache_entry(unsigned int mode, const unsigned char *sha1, const char *path, int stage, int refresh); @@ -533,6 +542,7 @@ static inline int is_absolute_path(const char *path) { return path[0] == '/' || has_dos_drive_prefix(path); } +int is_directory(const char *); const char *make_absolute_path(const char *path); const char *make_nonrelative_path(const char *path); const char *make_relative_path(const char *abs, const char *base); @@ -640,6 +650,8 @@ extern struct alternate_object_database { } *alt_odb_list; extern void prepare_alt_odb(void); extern void add_to_alternates_file(const char *reference); +typedef int alt_odb_fn(struct alternate_object_database *, void *); +extern void foreach_alt_odb(alt_odb_fn, void*); struct pack_window { struct pack_window *next; @@ -708,7 +720,11 @@ extern struct child_process *git_connect(int fd[2], const char *url, const char extern int finish_connect(struct child_process *conn); extern int path_match(const char *path, int nr, char **match); extern int get_ack(int fd, unsigned char *result_sha1); -extern struct ref **get_remote_heads(int in, struct ref **list, int nr_match, char **match, unsigned int flags); +struct extra_have_objects { + int nr, alloc; + unsigned char (*array)[20]; +}; +extern struct ref **get_remote_heads(int in, struct ref **list, int nr_match, char **match, unsigned int flags, struct extra_have_objects *); extern int server_supports(const char *feature); extern struct packed_git *parse_pack_index(unsigned char *sha1); @@ -742,7 +758,6 @@ 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(config_fn_t fn, void *); -extern int git_parse_long(const char *, long *); extern int git_parse_ulong(const char *, unsigned long *); extern int git_config_int(const char *, const char *); extern unsigned long git_config_ulong(const char *, const char *); diff --git a/combine-diff.c b/combine-diff.c index dcb90b1701..5aa1104d34 100644 --- a/combine-diff.c +++ b/combine-diff.c @@ -683,9 +683,13 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent, int i, show_hunks; int working_tree_file = is_null_sha1(elem->sha1); int abbrev = DIFF_OPT_TST(opt, FULL_INDEX) ? 40 : DEFAULT_ABBREV; + const char *a_prefix, *b_prefix; mmfile_t result_file; context = opt->context; + a_prefix = opt->a_prefix ? opt->a_prefix : "a/"; + b_prefix = opt->b_prefix ? opt->b_prefix : "b/"; + /* Read the result of merge first */ if (!working_tree_file) result = grab_blob(elem->sha1, &result_size); @@ -738,9 +742,8 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent, /* If not a fake symlink, apply filters, e.g. autocrlf */ if (is_file) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; - strbuf_init(&buf, 0); if (convert_to_git(elem->path, result, len, &buf, safe_crlf)) { free(result); result = strbuf_detach(&buf, &len); @@ -861,13 +864,13 @@ static void show_patch_diff(struct combine_diff_path *elem, int num_parent, dump_quoted_path("--- ", "", "/dev/null", c_meta, c_reset); else - dump_quoted_path("--- ", opt->a_prefix, elem->path, + dump_quoted_path("--- ", a_prefix, elem->path, c_meta, c_reset); if (deleted) dump_quoted_path("+++ ", "", "/dev/null", c_meta, c_reset); else - dump_quoted_path("+++ ", opt->b_prefix, elem->path, + dump_quoted_path("+++ ", b_prefix, elem->path, c_meta, c_reset); dump_sline(sline, cnt, num_parent, DIFF_OPT_TST(opt, COLOR_DIFF)); @@ -160,7 +160,7 @@ struct commit_graft *read_graft_line(char *buf, int len) return graft; } -int read_graft_file(const char *graft_file) +static int read_graft_file(const char *graft_file) { FILE *fp = fopen(graft_file, "r"); char buf[1024]; @@ -118,7 +118,6 @@ struct commit_graft { struct commit_graft *read_graft_line(char *buf, int len); int register_commit_graft(struct commit_graft *, int); -int read_graft_file(const char *graft_file); struct commit_graft *lookup_commit_graft(const unsigned char *sha1); extern struct commit_list *get_merge_bases(struct commit *rev1, struct commit *rev2, int cleanup); diff --git a/compat/cygwin.c b/compat/cygwin.c new file mode 100644 index 0000000000..f1967532ba --- /dev/null +++ b/compat/cygwin.c @@ -0,0 +1,137 @@ +#define WIN32_LEAN_AND_MEAN +#include "../git-compat-util.h" +#include "win32.h" +#include "../cache.h" /* to read configuration */ + +static inline void filetime_to_timespec(const FILETIME *ft, struct timespec *ts) +{ + long long winTime = ((long long)ft->dwHighDateTime << 32) + + ft->dwLowDateTime; + winTime -= 116444736000000000LL; /* Windows to Unix Epoch conversion */ + /* convert 100-nsecond interval to seconds and nanoseconds */ + ts->tv_sec = (time_t)(winTime/10000000); + ts->tv_nsec = (long)(winTime - ts->tv_sec*10000000LL) * 100; +} + +#define size_to_blocks(s) (((s)+511)/512) + +/* do_stat is a common implementation for cygwin_lstat and cygwin_stat. + * + * To simplify its logic, in the case of cygwin symlinks, this implementation + * falls back to the cygwin version of stat/lstat, which is provided as the + * last argument. + */ +static int do_stat(const char *file_name, struct stat *buf, stat_fn_t cygstat) +{ + WIN32_FILE_ATTRIBUTE_DATA fdata; + + if (file_name[0] == '/') + return cygstat (file_name, buf); + + if (!(errno = get_file_attr(file_name, &fdata))) { + /* + * If the system attribute is set and it is not a directory then + * it could be a symbol link created in the nowinsymlinks mode. + * Normally, Cygwin works in the winsymlinks mode, so this situation + * is very unlikely. For the sake of simplicity of our code, let's + * Cygwin to handle it. + */ + if ((fdata.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) && + !(fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + return cygstat(file_name, buf); + + /* fill out the stat structure */ + buf->st_dev = buf->st_rdev = 0; /* not used by Git */ + buf->st_ino = 0; + buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes); + buf->st_nlink = 1; + buf->st_uid = buf->st_gid = 0; +#ifdef __CYGWIN_USE_BIG_TYPES__ + buf->st_size = ((_off64_t)fdata.nFileSizeHigh << 32) + + fdata.nFileSizeLow; +#else + buf->st_size = (off_t)fdata.nFileSizeLow; +#endif + buf->st_blocks = size_to_blocks(buf->st_size); + filetime_to_timespec(&fdata.ftLastAccessTime, &buf->st_atim); + filetime_to_timespec(&fdata.ftLastWriteTime, &buf->st_mtim); + filetime_to_timespec(&fdata.ftCreationTime, &buf->st_ctim); + return 0; + } else if (errno == ENOENT) { + /* + * In the winsymlinks mode (which is the default), Cygwin + * emulates symbol links using Windows shortcut files. These + * files are formed by adding .lnk extension. So, if we have + * not found the specified file name, it could be that it is + * a symbol link. Let's Cygwin to deal with that. + */ + return cygstat(file_name, buf); + } + return -1; +} + +/* We provide our own lstat/stat functions, since the provided Cygwin versions + * of these functions are too slow. These stat functions are tailored for Git's + * usage, and therefore they are not meant to be complete and correct emulation + * of lstat/stat functionality. + */ +static int cygwin_lstat(const char *path, struct stat *buf) +{ + return do_stat(path, buf, lstat); +} + +static int cygwin_stat(const char *path, struct stat *buf) +{ + return do_stat(path, buf, stat); +} + + +/* + * At start up, we are trying to determine whether Win32 API or cygwin stat + * functions should be used. The choice is determined by core.ignorecygwinfstricks. + * Reading this option is not always possible immediately as git_dir may be + * not be set yet. So until it is set, use cygwin lstat/stat functions. + * However, if the trust_executable_bit is set, we must use the Cygwin posix + * stat/lstat as the Windows stat fuctions do not determine posix filemode. + */ +static int native_stat = 1; +extern int trust_executable_bit; + +static int git_cygwin_config(const char *var, const char *value, void *cb) +{ + if (!strcmp(var, "core.ignorecygwinfstricks")) { + native_stat = git_config_bool(var, value); + return 0; + } + return git_default_config(var, value, cb); +} + +static int init_stat(void) +{ + if (have_git_dir()) { + git_config(git_cygwin_config, NULL); + if (!trust_executable_bit && native_stat) { + cygwin_stat_fn = cygwin_stat; + cygwin_lstat_fn = cygwin_lstat; + } else { + cygwin_stat_fn = stat; + cygwin_lstat_fn = lstat; + } + return 0; + } + return 1; +} + +static int cygwin_stat_stub(const char *file_name, struct stat *buf) +{ + return (init_stat() ? stat : *cygwin_stat_fn)(file_name, buf); +} + +static int cygwin_lstat_stub(const char *file_name, struct stat *buf) +{ + return (init_stat() ? lstat : *cygwin_lstat_fn)(file_name, buf); +} + +stat_fn_t cygwin_stat_fn = cygwin_stat_stub; +stat_fn_t cygwin_lstat_fn = cygwin_lstat_stub; + diff --git a/compat/cygwin.h b/compat/cygwin.h new file mode 100644 index 0000000000..a3229f5b4f --- /dev/null +++ b/compat/cygwin.h @@ -0,0 +1,9 @@ +#include <sys/types.h> +#include <sys/stat.h> + +typedef int (*stat_fn_t)(const char*, struct stat*); +extern stat_fn_t cygwin_stat_fn; +extern stat_fn_t cygwin_lstat_fn; + +#define stat(path, buf) (*cygwin_stat_fn)(path, buf) +#define lstat(path, buf) (*cygwin_lstat_fn)(path, buf) diff --git a/compat/mingw.c b/compat/mingw.c index ccfa2a0a3d..09858f6c59 100644 --- a/compat/mingw.c +++ b/compat/mingw.c @@ -1,4 +1,5 @@ #include "../git-compat-util.h" +#include "win32.h" #include "../strbuf.h" unsigned int _CRT_fmode = _O_BINARY; @@ -31,7 +32,6 @@ static inline time_t filetime_to_time_t(const FILETIME *ft) return (time_t)winTime; } -extern int _getdrive( void ); /* We keep the do_lstat code in a separate function to avoid recursion. * When a path ends with a slash, the stat will fail with ENOENT. In * this case, we strip the trailing slashes and stat again. @@ -40,46 +40,19 @@ static int do_lstat(const char *file_name, struct stat *buf) { WIN32_FILE_ATTRIBUTE_DATA fdata; - if (GetFileAttributesExA(file_name, GetFileExInfoStandard, &fdata)) { - int fMode = S_IREAD; - if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - fMode |= S_IFDIR; - else - fMode |= S_IFREG; - if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) - fMode |= S_IWRITE; - + if (!(errno = get_file_attr(file_name, &fdata))) { buf->st_ino = 0; buf->st_gid = 0; buf->st_uid = 0; buf->st_nlink = 1; - buf->st_mode = fMode; + buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes); buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */ - buf->st_dev = buf->st_rdev = (_getdrive() - 1); + buf->st_dev = buf->st_rdev = 0; /* not used by Git */ buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime)); buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime)); buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime)); - errno = 0; return 0; } - - switch (GetLastError()) { - case ERROR_ACCESS_DENIED: - case ERROR_SHARING_VIOLATION: - case ERROR_LOCK_VIOLATION: - case ERROR_SHARING_BUFFER_EXCEEDED: - errno = EACCES; - break; - case ERROR_BUFFER_OVERFLOW: - errno = ENAMETOOLONG; - break; - case ERROR_NOT_ENOUGH_MEMORY: - errno = ENOMEM; - break; - default: - errno = ENOENT; - break; - } return -1; } @@ -131,21 +104,13 @@ int mingw_fstat(int fd, struct stat *buf) return fstat(fd, buf); if (GetFileInformationByHandle(fh, &fdata)) { - int fMode = S_IREAD; - if (fdata.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) - fMode |= S_IFDIR; - else - fMode |= S_IFREG; - if (!(fdata.dwFileAttributes & FILE_ATTRIBUTE_READONLY)) - fMode |= S_IWRITE; - buf->st_ino = 0; buf->st_gid = 0; buf->st_uid = 0; buf->st_nlink = 1; - buf->st_mode = fMode; + buf->st_mode = file_attr_to_st_mode(fdata.dwFileAttributes); buf->st_size = fdata.nFileSizeLow; /* Can't use nFileSizeHigh, since it's not a stat64 */ - buf->st_dev = buf->st_rdev = (_getdrive() - 1); + buf->st_dev = buf->st_rdev = 0; /* not used by Git */ buf->st_atime = filetime_to_time_t(&(fdata.ftLastAccessTime)); buf->st_mtime = filetime_to_time_t(&(fdata.ftLastWriteTime)); buf->st_ctime = filetime_to_time_t(&(fdata.ftCreationTime)); @@ -263,8 +228,13 @@ int poll(struct pollfd *ufds, unsigned int nfds, int timeout) { int i, pending; - if (timeout != -1) + if (timeout >= 0) { + if (nfds == 0) { + Sleep(timeout); + return 0; + } return errno = EINVAL, error("poll timeout not supported"); + } /* When there is only one fd to wait for, then we pretend that * input is available and let the actual wait happen when the diff --git a/compat/win32.h b/compat/win32.h new file mode 100644 index 0000000000..c26384e595 --- /dev/null +++ b/compat/win32.h @@ -0,0 +1,34 @@ +/* common Win32 functions for MinGW and Cygwin */ +#include <windows.h> + +static inline int file_attr_to_st_mode (DWORD attr) +{ + int fMode = S_IREAD; + if (attr & FILE_ATTRIBUTE_DIRECTORY) + fMode |= S_IFDIR; + else + fMode |= S_IFREG; + if (!(attr & FILE_ATTRIBUTE_READONLY)) + fMode |= S_IWRITE; + return fMode; +} + +static inline int get_file_attr(const char *fname, WIN32_FILE_ATTRIBUTE_DATA *fdata) +{ + if (GetFileAttributesExA(fname, GetFileExInfoStandard, fdata)) + return 0; + + switch (GetLastError()) { + case ERROR_ACCESS_DENIED: + case ERROR_SHARING_VIOLATION: + case ERROR_LOCK_VIOLATION: + case ERROR_SHARING_BUFFER_EXCEEDED: + return EACCES; + case ERROR_BUFFER_OVERFLOW: + return ENAMETOOLONG; + case ERROR_NOT_ENOUGH_MEMORY: + return ENOMEM; + default: + return ENOENT; + } +} @@ -205,8 +205,27 @@ static int git_parse_file(config_fn_t fn, void *data) int baselen = 0; static char var[MAXNAME]; + /* U+FEFF Byte Order Mark in UTF8 */ + static const unsigned char *utf8_bom = (unsigned char *) "\xef\xbb\xbf"; + const unsigned char *bomptr = utf8_bom; + for (;;) { int 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 + * own, but e.g. Windows Notepad will do it happily. */ + if ((unsigned char) c == *bomptr) { + bomptr++; + continue; + } else { + /* Do not tolerate partial BOM. */ + if (bomptr != utf8_bom) + break; + /* No BOM at file beginning. Cool. */ + bomptr = NULL; + } + } if (c == '\n') { if (config_file_eof) return 0; @@ -255,7 +274,7 @@ static int parse_unit_factor(const char *end, unsigned long *val) return 0; } -int git_parse_long(const char *value, long *ret) +static int git_parse_long(const char *value, long *ret) { if (value && *value) { char *end; @@ -291,7 +310,7 @@ static void die_bad_config(const char *name) int git_config_int(const char *name, const char *value) { - long ret; + long ret = 0; if (!git_parse_long(value, &ret)) die_bad_config(name); return ret; @@ -734,9 +753,8 @@ static int store_write_section(int fd, const char* key) { const char *dot; int i, success; - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; - strbuf_init(&sb, 0); dot = memchr(key, '.', store.baselen); if (dot) { strbuf_addf(&sb, "[%.*s \"", (int)(dot - key), key); @@ -761,7 +779,7 @@ static int store_write_pair(int fd, const char* key, const char* value) int i, success; int length = strlen(key + store.baselen + 1); const char *quote = ""; - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; /* * Check to see if the value needs to be surrounded with a dq pair. @@ -778,7 +796,6 @@ static int store_write_pair(int fd, const char* key, const char* value) if (i && value[i - 1] == ' ') quote = "\""; - strbuf_init(&sb, 0); strbuf_addf(&sb, "\t%.*s = %s", length, key + store.baselen + 1, quote); @@ -41,12 +41,20 @@ int check_ref_type(const struct ref *ref, int flags) return check_ref(ref->name, strlen(ref->name), flags); } +static void add_extra_have(struct extra_have_objects *extra, unsigned char *sha1) +{ + ALLOC_GROW(extra->array, extra->nr + 1, extra->alloc); + hashcpy(&(extra->array[extra->nr][0]), sha1); + extra->nr++; +} + /* * Read all the refs from the other end */ struct ref **get_remote_heads(int in, struct ref **list, int nr_match, char **match, - unsigned int flags) + unsigned int flags, + struct extra_have_objects *extra_have) { *list = NULL; for (;;) { @@ -72,6 +80,12 @@ struct ref **get_remote_heads(int in, struct ref **list, server_capabilities = xstrdup(name + name_len + 1); } + if (extra_have && + name_len == 5 && !memcmp(".have", name, 5)) { + add_extra_have(extra_have, old_sha1); + continue; + } + if (!check_ref(name, name_len, flags)) continue; if (nr_match && !path_match(name, nr_match, match)) diff --git a/contrib/completion/git-completion.bash b/contrib/completion/git-completion.bash index d3fb6ae507..d192927c20 100755 --- a/contrib/completion/git-completion.bash +++ b/contrib/completion/git-completion.bash @@ -154,11 +154,8 @@ __git_heads () { local cmd i is_hash=y dir="$(__gitdir "$1")" if [ -d "$dir" ]; then - for i in $(git --git-dir="$dir" \ - for-each-ref --format='%(refname)' \ - refs/heads ); do - echo "${i#refs/heads/}" - done + git --git-dir="$dir" for-each-ref --format='%(refname:short)' \ + refs/heads return fi for i in $(git ls-remote "$1" 2>/dev/null); do @@ -175,11 +172,8 @@ __git_tags () { local cmd i is_hash=y dir="$(__gitdir "$1")" if [ -d "$dir" ]; then - for i in $(git --git-dir="$dir" \ - for-each-ref --format='%(refname)' \ - refs/tags ); do - echo "${i#refs/tags/}" - done + git --git-dir="$dir" for-each-ref --format='%(refname:short)' \ + refs/tags return fi for i in $(git ls-remote "$1" 2>/dev/null); do @@ -197,16 +191,8 @@ __git_refs () local cmd i is_hash=y dir="$(__gitdir "$1")" if [ -d "$dir" ]; then if [ -e "$dir/HEAD" ]; then echo HEAD; fi - for i in $(git --git-dir="$dir" \ - for-each-ref --format='%(refname)' \ - refs/tags refs/heads refs/remotes); do - case "$i" in - refs/tags/*) echo "${i#refs/tags/}" ;; - refs/heads/*) echo "${i#refs/heads/}" ;; - refs/remotes/*) echo "${i#refs/remotes/}" ;; - *) echo "$i" ;; - esac - done + git --git-dir="$dir" for-each-ref --format='%(refname:short)' \ + refs/tags refs/heads refs/remotes return fi for i in $(git ls-remote "$dir" 2>/dev/null); do @@ -750,7 +736,7 @@ _git_commit () --*) __gitcomp " --all --author= --signoff --verify --no-verify - --edit --amend --include --only + --edit --amend --include --only --interactive " return esac @@ -799,14 +785,9 @@ _git_fetch () { local cur="${COMP_WORDS[COMP_CWORD]}" - case "${COMP_WORDS[0]},$COMP_CWORD" in - git-fetch*,1) - __gitcomp "$(__git_remotes)" - ;; - git,2) + if [ "$COMP_CWORD" = 2 ]; then __gitcomp "$(__git_remotes)" - ;; - *) + else case "$cur" in *:*) local pfx="" @@ -825,8 +806,7 @@ _git_fetch () __gitcomp "$(__git_refs2 "$remote")" ;; esac - ;; - esac + fi } _git_format_patch () @@ -1063,36 +1043,25 @@ _git_pull () { local cur="${COMP_WORDS[COMP_CWORD]}" - case "${COMP_WORDS[0]},$COMP_CWORD" in - git-pull*,1) - __gitcomp "$(__git_remotes)" - ;; - git,2) + if [ "$COMP_CWORD" = 2 ]; then __gitcomp "$(__git_remotes)" - ;; - *) + else local remote case "${COMP_WORDS[0]}" in git-pull) remote="${COMP_WORDS[1]}" ;; git) remote="${COMP_WORDS[2]}" ;; esac __gitcomp "$(__git_refs "$remote")" - ;; - esac + fi } _git_push () { local cur="${COMP_WORDS[COMP_CWORD]}" - case "${COMP_WORDS[0]},$COMP_CWORD" in - git-push*,1) - __gitcomp "$(__git_remotes)" - ;; - git,2) + if [ "$COMP_CWORD" = 2 ]; then __gitcomp "$(__git_remotes)" - ;; - *) + else case "$cur" in *:*) local remote @@ -1116,8 +1085,7 @@ _git_push () __gitcomp "$(__git_refs)" ;; esac - ;; - esac + fi } _git_rebase () @@ -1155,7 +1123,8 @@ _git_send_email () --no-suppress-from --no-thread --quiet --signed-off-by-cc --smtp-pass --smtp-server --smtp-server-port --smtp-ssl --smtp-user --subject - --suppress-cc --suppress-from --thread --to" + --suppress-cc --suppress-from --thread --to + --validate --no-validate" return ;; esac diff --git a/contrib/examples/git-remote.perl b/contrib/examples/git-remote.perl index 36bd54c985..b17952a785 100755 --- a/contrib/examples/git-remote.perl +++ b/contrib/examples/git-remote.perl @@ -309,7 +309,7 @@ sub update_remote { } } } else { - print STDERR "Remote group $name does not exists.\n"; + print STDERR "Remote group $name does not exist.\n"; exit(1); } for (@remotes) { diff --git a/contrib/hooks/pre-auto-gc-battery b/contrib/hooks/pre-auto-gc-battery index 0096f57b7e..1f914c94aa 100644 --- a/contrib/hooks/pre-auto-gc-battery +++ b/contrib/hooks/pre-auto-gc-battery @@ -1,9 +1,9 @@ #!/bin/sh # # An example hook script to verify if you are on battery, in case you -# are running Linux. Called by git-gc --auto with no arguments. The hook -# should exit with non-zero status after issuing an appropriate message -# if it wants to stop the auto repacking. +# are running Linux or OS X. Called by git-gc --auto with no arguments. +# The hook should exit with non-zero status after issuing an appropriate +# message if it wants to stop the auto repacking. # # This hook is stored in the contrib/hooks directory. Your distribution # may have put this somewhere else. If you want to use this hook, you @@ -30,6 +30,13 @@ then elif grep -q '0x01$' /proc/apm 2>/dev/null then exit 0 +elif grep -q "AC Power \+: 1" /proc/pmu/info 2>/dev/null +then + exit 0 +elif test -x /usr/bin/pmset && /usr/bin/pmset -g batt | + grep -q "Currently drawing from 'AC Power'" +then + exit 0 fi echo "Auto packing deferred; not on AC" diff --git a/contrib/hooks/setgitperms.perl b/contrib/hooks/setgitperms.perl index dab7c8e3a1..a577ad095f 100644 --- a/contrib/hooks/setgitperms.perl +++ b/contrib/hooks/setgitperms.perl @@ -50,7 +50,7 @@ if ((@ARGV < 0) || !GetOptions( )) { die $usage; } die $usage unless ($read_mode xor $write_mode); -my $topdir = `git-rev-parse --show-cdup` or die "\n"; chomp $topdir; +my $topdir = `git rev-parse --show-cdup` or die "\n"; chomp $topdir; my $gitdir = $topdir . '.git'; my $gitmeta = $topdir . '.gitmeta'; @@ -155,7 +155,7 @@ elsif ($read_mode) { open (OUT, ">$gitmeta.tmp") or die "Could not open $gitmeta.tmp for writing: $!\n"; } - my @files = `git-ls-files`; + my @files = `git ls-files`; my %dirs; foreach my $path (@files) { diff --git a/contrib/rerere-train.sh b/contrib/rerere-train.sh new file mode 100755 index 0000000000..2cfe1b936b --- /dev/null +++ b/contrib/rerere-train.sh @@ -0,0 +1,52 @@ +#!/bin/sh +# Copyright (c) 2008, Nanako Shiraishi +# Prime rerere database from existing merge commits + +me=rerere-train +USAGE="$me rev-list-args" + +SUBDIRECTORY_OK=Yes +OPTIONS_SPEC= +. git-sh-setup +require_work_tree +cd_to_toplevel + +# Remember original branch +branch=$(git symbolic-ref -q HEAD) || +original_HEAD=$(git rev-parse --verify HEAD) || { + echo >&2 "Not on any branch and no commit yet?" + exit 1 +} + +mkdir -p "$GIT_DIR/rr-cache" || exit + +git rev-list --parents "$@" | +while read commit parent1 other_parents +do + if test -z "$other_parents" + then + # Skip non-merges + continue + fi + git checkout -q "$parent1^0" + if git merge $other_parents >/dev/null 2>&1 + then + # Cleanly merges + continue + fi + if test -s "$GIT_DIR/MERGE_RR" + then + git show -s --pretty=format:"Learning from %h %s" "$commit" + git rerere + git checkout -q $commit -- . + git rerere + fi + git reset -q --hard +done + +if test -z "$branch" +then + git checkout "$original_HEAD" +else + git checkout "${branch#refs/heads/}" +fi diff --git a/contrib/stats/packinfo.pl b/contrib/stats/packinfo.pl index f4a7b62cd9..be188c0f11 100755 --- a/contrib/stats/packinfo.pl +++ b/contrib/stats/packinfo.pl @@ -1,9 +1,9 @@ #!/usr/bin/perl # # This tool will print vaguely pretty information about a pack. It -# expects the output of "git-verify-pack -v" as input on stdin. +# expects the output of "git verify-pack -v" as input on stdin. # -# $ git-verify-pack -v | packinfo.pl +# $ git verify-pack -v | packinfo.pl # # This prints some full-pack statistics; currently "all sizes", "all # path sizes", "tree sizes", "tree path sizes", and "depths". @@ -20,7 +20,7 @@ # # When run as: # -# $ git-verify-pack -v | packinfo.pl -tree +# $ git verify-pack -v | packinfo.pl -tree # # the trees of objects are output along with the stats. This looks # like: @@ -43,7 +43,7 @@ # # When run as: # -# $ git-verify-pack -v | packinfo.pl -tree -filenames +# $ git verify-pack -v | packinfo.pl -tree -filenames # # it adds filenames to the tree. Getting this information is slow: # @@ -58,7 +58,7 @@ # # When run as: # -# $ git-verify-pack -v | packinfo.pl -dump +# $ git verify-pack -v | packinfo.pl -dump # # it prints out "sha1 size pathsize depth" for each sha1 in lexical # order. @@ -106,7 +106,7 @@ while (<STDIN>) { } if ($filenames && ($tree || $dump)) { - open(NAMES, "git-name-rev --all|"); + open(NAMES, "git name-rev --all|"); while (<NAMES>) { if (/^(\S+)\s+(.*)$/) { my ($sha1, $name) = ($1, $2); @@ -117,7 +117,7 @@ if ($filenames && ($tree || $dump)) { for my $commit (@commits) { my $name = $names{$commit}; - open(TREE, "git-ls-tree -t -r $commit|"); + open(TREE, "git ls-tree -t -r $commit|"); print STDERR "Plumbing tree $name\n"; while (<TREE>) { if (/^(\S+)\s+(\S+)\s+(\S+)\s+(.*)$/) { diff --git a/contrib/vim/README b/contrib/vim/README index 9e7881fea9..c487346eba 100644 --- a/contrib/vim/README +++ b/contrib/vim/README @@ -1,8 +1,30 @@ -To syntax highlight git's commit messages, you need to: - 1. Copy syntax/gitcommit.vim to vim's syntax directory: - $ mkdir -p $HOME/.vim/syntax - $ cp syntax/gitcommit.vim $HOME/.vim/syntax - 2. Auto-detect the editing of git commit files: - $ cat >>$HOME/.vimrc <<'EOF' - autocmd BufNewFile,BufRead COMMIT_EDITMSG set filetype=gitcommit - EOF +Syntax highlighting for git commit messages, config files, etc. is +included with the vim distribution as of vim 7.2, and should work +automatically. + +If you have an older version of vim, you can get the latest syntax +files from the vim project: + + http://vim.svn.sourceforge.net/viewvc/vim/trunk/runtime/syntax/git.vim + http://vim.svn.sourceforge.net/viewvc/vim/trunk/runtime/syntax/gitcommit.vim + http://vim.svn.sourceforge.net/viewvc/vim/trunk/runtime/syntax/gitconfig.vim + http://vim.svn.sourceforge.net/viewvc/vim/trunk/runtime/syntax/gitrebase.vim + http://vim.svn.sourceforge.net/viewvc/vim/trunk/runtime/syntax/gitsendemail.vim + +To install: + + 1. Copy these files to vim's syntax directory $HOME/.vim/syntax + 2. To auto-detect the editing of various git-related filetypes: + $ cat >>$HOME/.vim/filetype.vim <<'EOF' + autocmd BufNewFile,BufRead *.git/COMMIT_EDITMSG setf gitcommit + autocmd BufNewFile,BufRead *.git/config,.gitconfig setf gitconfig + autocmd BufNewFile,BufRead git-rebase-todo setf gitrebase + autocmd BufNewFile,BufRead .msg.[0-9]* + \ if getline(1) =~ '^From.*# This line is ignored.$' | + \ setf gitsendemail | + \ endif + autocmd BufNewFile,BufRead *.git/** + \ if getline(1) =~ '^\x\{40\}\>\|^ref: ' | + \ setf git | + \ endif + EOF diff --git a/contrib/vim/syntax/gitcommit.vim b/contrib/vim/syntax/gitcommit.vim deleted file mode 100644 index 332121b40e..0000000000 --- a/contrib/vim/syntax/gitcommit.vim +++ /dev/null @@ -1,18 +0,0 @@ -syn region gitLine start=/^#/ end=/$/ -syn region gitCommit start=/^# Changes to be committed:$/ end=/^#$/ contains=gitHead,gitCommitFile -syn region gitHead contained start=/^# (.*)/ end=/^#$/ -syn region gitChanged start=/^# Changed but not updated:/ end=/^#$/ contains=gitHead,gitChangedFile -syn region gitUntracked start=/^# Untracked files:/ end=/^#$/ contains=gitHead,gitUntrackedFile - -syn match gitCommitFile contained /^#\t.*/hs=s+2 -syn match gitChangedFile contained /^#\t.*/hs=s+2 -syn match gitUntrackedFile contained /^#\t.*/hs=s+2 - -hi def link gitLine Comment -hi def link gitCommit Comment -hi def link gitChanged Comment -hi def link gitHead Comment -hi def link gitUntracked Comment -hi def link gitCommitFile Type -hi def link gitChangedFile Constant -hi def link gitUntrackedFile Constant @@ -281,7 +281,7 @@ static int apply_filter(const char *path, const char *src, size_t len, * (child --> cmd) --> us */ int ret = 1; - struct strbuf nbuf; + struct strbuf nbuf = STRBUF_INIT; struct async async; struct filter_params params; @@ -299,7 +299,6 @@ static int apply_filter(const char *path, const char *src, size_t len, if (start_async(&async)) return 0; /* error was already reported */ - strbuf_init(&nbuf, 0); if (strbuf_read(&nbuf, async.out, len) < 0) { error("read from external filter %s failed", cmd); ret = 0; diff --git a/csum-file.c b/csum-file.c index 28389541a3..2ddb12a0b7 100644 --- a/csum-file.c +++ b/csum-file.c @@ -11,10 +11,8 @@ #include "progress.h" #include "csum-file.h" -static void sha1flush(struct sha1file *f, unsigned int count) +static void flush(struct sha1file *f, void * buf, unsigned int count) { - void *buf = f->buffer; - for (;;) { int ret = xwrite(f->fd, buf, count); if (ret > 0) { @@ -32,22 +30,28 @@ static void sha1flush(struct sha1file *f, unsigned int count) } } -int sha1close(struct sha1file *f, unsigned char *result, unsigned int flags) +void sha1flush(struct sha1file *f) { - int fd; unsigned offset = f->offset; if (offset) { - SHA1_Update(&f->ctx, f->buffer, offset); - sha1flush(f, offset); + git_SHA1_Update(&f->ctx, f->buffer, offset); + flush(f, f->buffer, offset); f->offset = 0; } - SHA1_Final(f->buffer, &f->ctx); +} + +int sha1close(struct sha1file *f, unsigned char *result, unsigned int flags) +{ + int fd; + + sha1flush(f); + git_SHA1_Final(f->buffer, &f->ctx); if (result) hashcpy(result, f->buffer); if (flags & (CSUM_CLOSE | CSUM_FSYNC)) { /* write checksum and close fd */ - sha1flush(f, 20); + flush(f, f->buffer, 20); if (flags & CSUM_FSYNC) fsync_or_die(f->fd, f->name); if (close(f->fd)) @@ -62,21 +66,30 @@ int sha1close(struct sha1file *f, unsigned char *result, unsigned int flags) int sha1write(struct sha1file *f, void *buf, unsigned int count) { - if (f->do_crc) - f->crc32 = crc32(f->crc32, buf, count); while (count) { unsigned offset = f->offset; unsigned left = sizeof(f->buffer) - offset; unsigned nr = count > left ? left : count; + void *data; + + if (f->do_crc) + f->crc32 = crc32(f->crc32, buf, nr); + + if (nr == sizeof(f->buffer)) { + /* process full buffer directly without copy */ + data = buf; + } else { + memcpy(f->buffer + offset, buf, nr); + data = f->buffer; + } - memcpy(f->buffer + offset, buf, nr); count -= nr; offset += nr; buf = (char *) buf + nr; left -= nr; if (!left) { - SHA1_Update(&f->ctx, f->buffer, offset); - sha1flush(f, offset); + git_SHA1_Update(&f->ctx, data, offset); + flush(f, data, offset); offset = 0; } f->offset = offset; @@ -98,7 +111,7 @@ struct sha1file *sha1fd_throughput(int fd, const char *name, struct progress *tp f->tp = tp; f->name = name; f->do_crc = 0; - SHA1_Init(&f->ctx); + git_SHA1_Init(&f->ctx); return f; } diff --git a/csum-file.h b/csum-file.h index 72c9487f4f..294add2a91 100644 --- a/csum-file.h +++ b/csum-file.h @@ -7,7 +7,7 @@ struct progress; struct sha1file { int fd; unsigned int offset; - SHA_CTX ctx; + git_SHA_CTX ctx; off_t total; struct progress *tp; const char *name; @@ -24,6 +24,7 @@ extern struct sha1file *sha1fd(int fd, const char *name); extern struct sha1file *sha1fd_throughput(int fd, const char *name, struct progress *tp); extern int sha1close(struct sha1file *, unsigned char *, unsigned int); extern int sha1write(struct sha1file *, void *, unsigned int); +extern void sha1flush(struct sha1file *f); extern void crc32_begin(struct sha1file *); extern uint32_t crc32_end(struct sha1file *); @@ -1083,7 +1083,8 @@ int main(int argc, char **argv) openlog("git-daemon", LOG_PID, LOG_DAEMON); set_die_routine(daemon_die); } else - setlinebuf(stderr); /* avoid splitting a message in the middle */ + /* avoid splitting a message in the middle */ + setvbuf(stderr, NULL, _IOLBF, 0); if (inetd_mode && (group_name || user_name)) die("--user and --group are incompatible with --inetd"); @@ -1115,13 +1116,9 @@ int main(int argc, char **argv) if (strict_paths && (!ok_paths || !*ok_paths)) die("option --strict-paths requires a whitelist"); - if (base_path) { - struct stat st; - - if (stat(base_path, &st) || !S_ISDIR(st.st_mode)) - die("base-path '%s' does not exist or " - "is not a directory", base_path); - } + if (base_path && !is_directory(base_path)) + die("base-path '%s' does not exist or is not a directory", + base_path); if (inetd_mode) { struct sockaddr_storage ss; @@ -402,6 +402,15 @@ static int match_multi_number(unsigned long num, char c, const char *date, char return end - date; } +/* Have we filled in any part of the time/date yet? */ +static inline int nodate(struct tm *tm) +{ + return tm->tm_year < 0 && + tm->tm_mon < 0 && + tm->tm_mday < 0 && + !(tm->tm_hour | tm->tm_min | tm->tm_sec); +} + /* * We've seen a digit. Time? Year? Date? */ @@ -418,7 +427,7 @@ static int match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt * more than 8 digits. This is because we don't want to rule out * numbers like 20070606 as a YYYYMMDD date. */ - if (num >= 100000000) { + if (num >= 100000000 && nodate(tm)) { time_t time = num; if (gmtime_r(&time, tm)) { *tm_gmt = 1; @@ -463,6 +472,13 @@ static int match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt } /* + * Ignore lots of numerals. We took care of 4-digit years above. + * Days or months must be one or two digits. + */ + if (n > 2) + return n; + + /* * NOTE! We will give precedence to day-of-month over month or * year numbers in the 1-12 range. So 05 is always "mday 5", * unless we already have a mday.. @@ -488,10 +504,6 @@ static int match_digit(const char *date, struct tm *tm, int *offset, int *tm_gmt if (num > 0 && num < 32) { tm->tm_mday = num; - } else if (num > 1900) { - tm->tm_year = num - 1900; - } else if (num > 70) { - tm->tm_year = num; } else if (num > 0 && num < 13) { tm->tm_mon = num-1; } @@ -823,7 +835,9 @@ static const char *approxidate_digit(const char *date, struct tm *tm, int *num) } } - *num = number; + /* Accept zero-padding only for small numbers ("Dec 02", never "Dec 0002") */ + if (date[0] != '0' || end - date <= 2) + *num = number; return end; } diff --git a/diff-lib.c b/diff-lib.c index e7eaff9a68..ae96c64ca2 100644 --- a/diff-lib.c +++ b/diff-lib.c @@ -63,6 +63,8 @@ int run_diff_files(struct rev_info *revs, unsigned int option) ? CE_MATCH_RACY_IS_DIRTY : 0); char symcache[PATH_MAX]; + diff_set_mnemonic_prefix(&revs->diffopt, "i/", "w/"); + if (diff_unmerged_stage < 0) diff_unmerged_stage = 2; entries = active_nr; @@ -469,6 +471,7 @@ int run_diff_index(struct rev_info *revs, int cached) if (unpack_trees(1, &t, &opts)) exit(128); + diff_set_mnemonic_prefix(&revs->diffopt, "c/", cached ? "i/" : "w/"); diffcore_std(&revs->diffopt); diff_flush(&revs->diffopt); return 0; diff --git a/diff-no-index.c b/diff-no-index.c index 7d68b7f1be..b60d3455da 100644 --- a/diff-no-index.c +++ b/diff-no-index.c @@ -252,6 +252,7 @@ void diff_no_index(struct rev_info *revs, if (queue_diff(&revs->diffopt, revs->diffopt.paths[0], revs->diffopt.paths[1])) exit(1); + diff_set_mnemonic_prefix(&revs->diffopt, "1/", "2/"); diffcore_std(&revs->diffopt); diff_flush(&revs->diffopt); @@ -24,6 +24,7 @@ static int diff_suppress_blank_empty; int diff_use_color_default = -1; static const char *external_diff_cmd_cfg; int diff_auto_refresh_index = 1; +static int diff_mnemonic_prefix; static char diff_colors[][COLOR_MAXLEN] = { "\033[m", /* reset */ @@ -95,32 +96,37 @@ static int parse_lldiff_command(const char *var, const char *ep, const char *val * to define a customized regexp to find the beginning of a function to * be used for hunk header lines of "diff -p" style output. */ -static struct funcname_pattern { +struct funcname_pattern_entry { char *name; char *pattern; - struct funcname_pattern *next; + int cflags; +}; +static struct funcname_pattern_list { + struct funcname_pattern_list *next; + struct funcname_pattern_entry e; } *funcname_pattern_list; -static int parse_funcname_pattern(const char *var, const char *ep, const char *value) +static int parse_funcname_pattern(const char *var, const char *ep, const char *value, int cflags) { const char *name; int namelen; - struct funcname_pattern *pp; + struct funcname_pattern_list *pp; name = var + 5; /* "diff." */ namelen = ep - name; for (pp = funcname_pattern_list; pp; pp = pp->next) - if (!strncmp(pp->name, name, namelen) && !pp->name[namelen]) + if (!strncmp(pp->e.name, name, namelen) && !pp->e.name[namelen]) break; if (!pp) { pp = xcalloc(1, sizeof(*pp)); - pp->name = xmemdupz(name, namelen); + pp->e.name = xmemdupz(name, namelen); pp->next = funcname_pattern_list; funcname_pattern_list = pp; } - free(pp->pattern); - pp->pattern = xstrdup(value); + free(pp->e.pattern); + pp->e.pattern = xstrdup(value); + pp->e.cflags = cflags; return 0; } @@ -150,6 +156,10 @@ int git_diff_ui_config(const char *var, const char *value, void *cb) diff_auto_refresh_index = git_config_bool(var, value); return 0; } + if (!strcmp(var, "diff.mnemonicprefix")) { + diff_mnemonic_prefix = git_config_bool(var, value); + return 0; + } if (!strcmp(var, "diff.external")) return git_config_string(&external_diff_cmd_cfg, var, value); if (!prefixcmp(var, "diff.")) { @@ -189,7 +199,13 @@ int git_diff_basic_config(const char *var, const char *value, void *cb) if (!strcmp(ep, ".funcname")) { if (!value) return config_error_nonbool(var); - return parse_funcname_pattern(var, ep, value); + return parse_funcname_pattern(var, ep, value, + 0); + } else if (!strcmp(ep, ".xfuncname")) { + if (!value) + return config_error_nonbool(var); + return parse_funcname_pattern(var, ep, value, + REG_EXTENDED); } } } @@ -201,9 +217,8 @@ static char *quote_two(const char *one, const char *two) { int need_one = quote_c_style(one, NULL, NULL, 1); int need_two = quote_c_style(two, NULL, NULL, 1); - struct strbuf res; + struct strbuf res = STRBUF_INIT; - strbuf_init(&res, 0); if (need_one + need_two) { strbuf_addch(&res, '"'); quote_c_style(one, &res, NULL, 1); @@ -312,6 +327,15 @@ static void emit_rewrite_diff(const char *name_a, const char *new = diff_get_color(color_diff, DIFF_FILE_NEW); const char *reset = diff_get_color(color_diff, DIFF_RESET); static struct strbuf a_name = STRBUF_INIT, b_name = STRBUF_INIT; + const char *a_prefix, *b_prefix; + + if (diff_mnemonic_prefix && DIFF_OPT_TST(o, REVERSE_DIFF)) { + a_prefix = o->b_prefix; + b_prefix = o->a_prefix; + } else { + a_prefix = o->a_prefix; + b_prefix = o->b_prefix; + } name_a += (*name_a == '/'); name_b += (*name_b == '/'); @@ -320,8 +344,8 @@ static void emit_rewrite_diff(const char *name_a, strbuf_reset(&a_name); strbuf_reset(&b_name); - quote_two_c_style(&a_name, o->a_prefix, name_a, 0); - quote_two_c_style(&b_name, o->b_prefix, name_b, 0); + quote_two_c_style(&a_name, a_prefix, name_a, 0); + quote_two_c_style(&b_name, b_prefix, name_b, 0); diff_populate_filespec(one, 0); diff_populate_filespec(two, 0); @@ -658,7 +682,7 @@ static char *pprint_rename(const char *a, const char *b) { const char *old = a; const char *new = b; - struct strbuf name; + struct strbuf name = STRBUF_INIT; int pfx_length, sfx_length; int len_a = strlen(a); int len_b = strlen(b); @@ -666,7 +690,6 @@ static char *pprint_rename(const char *a, const char *b) int qlen_a = quote_c_style(a, NULL, NULL, 0); int qlen_b = quote_c_style(b, NULL, NULL, 0); - strbuf_init(&name, 0); if (qlen_a || qlen_b) { quote_c_style(a, &name, NULL, 0); strbuf_addstr(&name, " => "); @@ -809,8 +832,7 @@ static void fill_print_name(struct diffstat_file *file) return; if (!file->is_renamed) { - struct strbuf buf; - strbuf_init(&buf, 0); + struct strbuf buf = STRBUF_INIT; if (quote_c_style(file->name, &buf, NULL, 0)) { pname = strbuf_detach(&buf, NULL); } else { @@ -1117,9 +1139,13 @@ static void show_dirstat(struct diff_options *options) /* * Original minus copied is the removed material, * added is the new material. They are both damages - * made to the preimage. + * made to the preimage. In --dirstat-by-file mode, count + * damaged files, not damaged lines. This is done by + * counting only a single damaged line per file. */ damage = (p->one->size - copied) + added; + if (DIFF_OPT_TST(options, DIRSTAT_BY_FILE) && damage > 0) + damage = 1; ALLOC_GROW(dir.files, dir.nr + 1, dir.alloc); dir.files[dir.nr].name = name; @@ -1382,42 +1408,53 @@ int diff_filespec_is_binary(struct diff_filespec *one) return one->is_binary; } -static const char *funcname_pattern(const char *ident) +static const struct funcname_pattern_entry *funcname_pattern(const char *ident) { - struct funcname_pattern *pp; + struct funcname_pattern_list *pp; for (pp = funcname_pattern_list; pp; pp = pp->next) - if (!strcmp(ident, pp->name)) - return pp->pattern; + if (!strcmp(ident, pp->e.name)) + return &pp->e; return NULL; } -static struct builtin_funcname_pattern { - const char *name; - const char *pattern; -} builtin_funcname_pattern[] = { - { "bibtex", "\\(@[a-zA-Z]\\{1,\\}[ \t]*{\\{0,1\\}[ \t]*[^ \t\"@',\\#}{~%]*\\).*$" }, - { "html", "^\\s*\\(<[Hh][1-6]\\s.*>.*\\)$" }, - { "java", "!^[ ]*\\(catch\\|do\\|for\\|if\\|instanceof\\|" - "new\\|return\\|switch\\|throw\\|while\\)\n" - "^[ ]*\\(\\([ ]*" - "[A-Za-z_][A-Za-z_0-9]*\\)\\{2,\\}" - "[ ]*([^;]*\\)$" }, - { "pascal", "^\\(\\(procedure\\|function\\|constructor\\|" - "destructor\\|interface\\|implementation\\|" - "initialization\\|finalization\\)[ \t]*.*\\)$" - "\\|" - "^\\(.*=[ \t]*\\(class\\|record\\).*\\)$" - }, - { "php", "^[\t ]*\\(\\(function\\|class\\).*\\)" }, - { "python", "^\\s*\\(\\(class\\|def\\)\\s.*\\)$" }, - { "ruby", "^\\s*\\(\\(class\\|module\\|def\\)\\s.*\\)$" }, - { "tex", "^\\(\\\\\\(\\(sub\\)*section\\|chapter\\|part\\)\\*\\{0,1\\}{.*\\)$" }, +static const struct funcname_pattern_entry builtin_funcname_pattern[] = { + { "bibtex", "(@[a-zA-Z]{1,}[ \t]*\\{{0,1}[ \t]*[^ \t\"@',\\#}{~%]*).*$", + REG_EXTENDED }, + { "html", "^[ \t]*(<[Hh][1-6][ \t].*>.*)$", REG_EXTENDED }, + { "java", + "!^[ \t]*(catch|do|for|if|instanceof|new|return|switch|throw|while)\n" + "^[ \t]*(([ \t]*[A-Za-z_][A-Za-z_0-9]*){2,}[ \t]*\\([^;]*)$", + REG_EXTENDED }, + { "objc", + /* Negate C statements that can look like functions */ + "!^[ \t]*(do|for|if|else|return|switch|while)\n" + /* Objective-C methods */ + "^[ \t]*([-+][ \t]*\\([ \t]*[A-Za-z_][A-Za-z_0-9* \t]*\\)[ \t]*[A-Za-z_].*)$\n" + /* C functions */ + "^[ \t]*(([ \t]*[A-Za-z_][A-Za-z_0-9]*){2,}[ \t]*\\([^;]*)$\n" + /* Objective-C class/protocol definitions */ + "^(@(implementation|interface|protocol)[ \t].*)$", + REG_EXTENDED }, + { "pascal", + "^((procedure|function|constructor|destructor|interface|" + "implementation|initialization|finalization)[ \t]*.*)$" + "\n" + "^(.*=[ \t]*(class|record).*)$", + REG_EXTENDED }, + { "php", "^[\t ]*((function|class).*)", REG_EXTENDED }, + { "python", "^[ \t]*((class|def)[ \t].*)$", REG_EXTENDED }, + { "ruby", "^[ \t]*((class|module|def)[ \t].*)$", + REG_EXTENDED }, + { "tex", + "^(\\\\((sub)*section|chapter|part)\\*{0,1}\\{.*)$", + REG_EXTENDED }, }; -static const char *diff_funcname_pattern(struct diff_filespec *one) +static const struct funcname_pattern_entry *diff_funcname_pattern(struct diff_filespec *one) { - const char *ident, *pattern; + const char *ident; + const struct funcname_pattern_entry *pe; int i; diff_filespec_check_attr(one); @@ -1432,9 +1469,9 @@ static const char *diff_funcname_pattern(struct diff_filespec *one) return funcname_pattern("default"); /* Look up custom "funcname.$ident" regexp from config. */ - pattern = funcname_pattern(ident); - if (pattern) - return pattern; + pe = funcname_pattern(ident); + if (pe) + return pe; /* * And define built-in fallback patterns here. Note that @@ -1442,11 +1479,19 @@ static const char *diff_funcname_pattern(struct diff_filespec *one) */ for (i = 0; i < ARRAY_SIZE(builtin_funcname_pattern); i++) if (!strcmp(ident, builtin_funcname_pattern[i].name)) - return builtin_funcname_pattern[i].pattern; + return &builtin_funcname_pattern[i]; return NULL; } +void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b) +{ + if (!options->a_prefix) + options->a_prefix = a; + if (!options->b_prefix) + options->b_prefix = b; +} + static void builtin_diff(const char *name_a, const char *name_b, struct diff_filespec *one, @@ -1460,9 +1505,23 @@ static void builtin_diff(const char *name_a, char *a_one, *b_two; const char *set = diff_get_color_opt(o, DIFF_METAINFO); const char *reset = diff_get_color_opt(o, DIFF_RESET); + const char *a_prefix, *b_prefix; - a_one = quote_two(o->a_prefix, name_a + (*name_a == '/')); - b_two = quote_two(o->b_prefix, name_b + (*name_b == '/')); + diff_set_mnemonic_prefix(o, "a/", "b/"); + if (DIFF_OPT_TST(o, REVERSE_DIFF)) { + a_prefix = o->b_prefix; + b_prefix = o->a_prefix; + } else { + a_prefix = o->a_prefix; + b_prefix = o->b_prefix; + } + + /* Never use a non-valid filename anywhere if at all possible */ + name_a = DIFF_FILE_VALID(one) ? name_a : name_b; + name_b = DIFF_FILE_VALID(two) ? name_b : name_a; + + a_one = quote_two(a_prefix, name_a + (*name_a == '/')); + b_two = quote_two(b_prefix, name_b + (*name_b == '/')); lbl[0] = DIFF_FILE_VALID(one) ? a_one : "/dev/null"; lbl[1] = DIFF_FILE_VALID(two) ? b_two : "/dev/null"; fprintf(o->file, "%sdiff --git %s %s%s\n", set, a_one, b_two, reset); @@ -1520,11 +1579,11 @@ static void builtin_diff(const char *name_a, xdemitconf_t xecfg; xdemitcb_t ecb; struct emit_callback ecbdata; - const char *funcname_pattern; + const struct funcname_pattern_entry *pe; - funcname_pattern = diff_funcname_pattern(one); - if (!funcname_pattern) - funcname_pattern = diff_funcname_pattern(two); + pe = diff_funcname_pattern(one); + if (!pe) + pe = diff_funcname_pattern(two); memset(&xecfg, 0, sizeof(xecfg)); memset(&ecbdata, 0, sizeof(ecbdata)); @@ -1536,8 +1595,8 @@ static void builtin_diff(const char *name_a, xpp.flags = XDF_NEED_MINIMAL | o->xdl_opts; xecfg.ctxlen = o->context; xecfg.flags = XDL_EMIT_FUNCNAMES; - if (funcname_pattern) - xdiff_set_find_func(&xecfg, funcname_pattern); + if (pe) + xdiff_set_find_func(&xecfg, pe->pattern, pe->cflags); if (!diffopts) ; else if (!prefixcmp(diffopts, "--unified=")) @@ -1758,10 +1817,9 @@ static int reuse_worktree_file(const char *name, const unsigned char *sha1, int static int populate_from_stdin(struct diff_filespec *s) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; size_t size = 0; - strbuf_init(&buf, 0); if (strbuf_read(&buf, 0, 0) < 0) return error("error while reading from stdin %s", strerror(errno)); @@ -1813,7 +1871,7 @@ int diff_populate_filespec(struct diff_filespec *s, int size_only) if (!s->sha1_valid || reuse_worktree_file(s->path, s->sha1, 0)) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; struct stat st; int fd; @@ -1856,7 +1914,6 @@ int diff_populate_filespec(struct diff_filespec *s, int size_only) /* * Convert from working tree format to canonical git format */ - strbuf_init(&buf, 0); if (convert_to_git(s->path, s->data, s->size, &buf, safe_crlf)) { size_t size = 0; munmap(s->data, s->size); @@ -2319,8 +2376,10 @@ void diff_setup(struct diff_options *options) DIFF_OPT_CLR(options, COLOR_DIFF); options->detect_rename = diff_detect_rename_default; - options->a_prefix = "a/"; - options->b_prefix = "b/"; + if (!diff_mnemonic_prefix) { + options->a_prefix = "a/"; + options->b_prefix = "b/"; + } } int diff_setup_done(struct diff_options *options) @@ -2403,13 +2462,6 @@ int diff_setup_done(struct diff_options *options) DIFF_OPT_SET(options, EXIT_WITH_STATUS); } - /* - * If we postprocess in diffcore, we cannot simply return - * upon the first hit. We need to run diff as usual. - */ - if (options->pickaxe || options->filter) - DIFF_OPT_CLR(options, QUIET); - return 0; } @@ -2484,6 +2536,10 @@ int diff_opt_parse(struct diff_options *options, const char **av, int ac) else if (!strcmp(arg, "--cumulative")) { options->output_format |= DIFF_FORMAT_DIRSTAT; DIFF_OPT_SET(options, DIRSTAT_CUMULATIVE); + } else if (opt_arg(arg, 0, "dirstat-by-file", + &options->dirstat_percent)) { + options->output_format |= DIFF_FORMAT_DIRSTAT; + DIFF_OPT_SET(options, DIRSTAT_BY_FILE); } else if (!strcmp(arg, "--check")) options->output_format |= DIFF_FORMAT_CHECKDIFF; @@ -3040,7 +3096,7 @@ static void diff_summary(FILE *file, struct diff_filepair *p) } struct patch_id_t { - SHA_CTX *ctx; + git_SHA_CTX *ctx; int patchlen; }; @@ -3068,7 +3124,7 @@ static void patch_id_consume(void *priv, char *line, unsigned long len) new_len = remove_space(line, len); - SHA1_Update(data->ctx, line, new_len); + git_SHA1_Update(data->ctx, line, new_len); data->patchlen += new_len; } @@ -3077,11 +3133,11 @@ static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1) { struct diff_queue_struct *q = &diff_queued_diff; int i; - SHA_CTX ctx; + git_SHA_CTX ctx; struct patch_id_t data; char buffer[PATH_MAX * 4 + 20]; - SHA1_Init(&ctx); + git_SHA1_Init(&ctx); memset(&data, 0, sizeof(struct patch_id_t)); data.ctx = &ctx; @@ -3143,7 +3199,7 @@ static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1) len2, p->two->path, len1, p->one->path, len2, p->two->path); - SHA1_Update(&ctx, buffer, len1); + git_SHA1_Update(&ctx, buffer, len1); xpp.flags = XDF_NEED_MINIMAL; xecfg.ctxlen = 3; @@ -3152,7 +3208,7 @@ static int diff_get_patch_id(struct diff_options *options, unsigned char *sha1) &xpp, &xecfg, &ecb); } - SHA1_Final(sha1, &ctx); + git_SHA1_Final(sha1, &ctx); return 0; } @@ -3397,10 +3453,7 @@ static void diffcore_skip_stat_unmatch(struct diff_options *diffopt) void diffcore_std(struct diff_options *options) { - if (DIFF_OPT_TST(options, QUIET)) - return; - - if (options->skip_stat_unmatch && !DIFF_OPT_TST(options, FIND_COPIES_HARDER)) + if (options->skip_stat_unmatch) diffcore_skip_stat_unmatch(options); if (options->break_opt != -1) diffcore_break(options->break_opt); @@ -64,6 +64,7 @@ typedef void (*diff_format_fn_t)(struct diff_queue_struct *q, #define DIFF_OPT_RELATIVE_NAME (1 << 17) #define DIFF_OPT_IGNORE_SUBMODULES (1 << 18) #define DIFF_OPT_DIRSTAT_CUMULATIVE (1 << 19) +#define DIFF_OPT_DIRSTAT_BY_FILE (1 << 20) #define DIFF_OPT_TST(opts, flag) ((opts)->flags & DIFF_OPT_##flag) #define DIFF_OPT_SET(opts, flag) ((opts)->flags |= DIFF_OPT_##flag) #define DIFF_OPT_CLR(opts, flag) ((opts)->flags &= ~DIFF_OPT_##flag) @@ -160,6 +161,8 @@ extern void diff_tree_combined(const unsigned char *sha1, const unsigned char pa extern void diff_tree_combined_merge(const unsigned char *sha1, int, struct rev_info *); +void diff_set_mnemonic_prefix(struct diff_options *options, const char *a, const char *b); + extern void diff_addremove(struct diff_options *, int addremove, unsigned mode, diff --git a/diffcore.h b/diffcore.h index cc96c20734..8ae35785fd 100644 --- a/diffcore.h +++ b/diffcore.h @@ -92,7 +92,6 @@ extern struct diff_filepair *diff_queue(struct diff_queue_struct *, struct diff_filespec *); extern void diff_q(struct diff_queue_struct *, struct diff_filepair *); -extern void diffcore_pathspec(const char **pathspec); extern void diffcore_break(int); extern void diffcore_rename(struct diff_options *); extern void diffcore_merge_broken(void); @@ -382,7 +382,7 @@ static struct dir_entry *dir_entry_new(const char *pathname, int len) return ent; } -struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len) +static struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len) { if (cache_name_exists(pathname, len, ignore_case)) return NULL; @@ -391,7 +391,7 @@ struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int return dir->entries[dir->nr++] = dir_entry_new(pathname, len); } -struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len) +static struct dir_entry *dir_add_ignored(struct dir_struct *dir, const char *pathname, int len) { if (cache_name_pos(pathname, len) >= 0) return NULL; @@ -831,3 +831,23 @@ void setup_standard_excludes(struct dir_struct *dir) if (excludes_file && !access(excludes_file, R_OK)) add_excludes_from_file(dir, excludes_file); } + +int remove_path(const char *name) +{ + char *slash; + + if (unlink(name) && errno != ENOENT) + return -1; + + slash = strrchr(name, '/'); + if (slash) { + char *dirs = xstrdup(name); + slash = dirs + (slash - name); + do { + *slash = '\0'; + } while (rmdir(dirs) && (slash = strrchr(dirs, '/'))); + free(dirs); + } + return 0; +} + @@ -73,7 +73,6 @@ extern void add_excludes_from_file(struct dir_struct *, const char *fname); extern void add_exclude(const char *string, const char *base, int baselen, struct exclude_list *which); extern int file_exists(const char *); -extern struct dir_entry *dir_add_name(struct dir_struct *dir, const char *pathname, int len); extern char *get_relative_cwd(char *buffer, int size, const char *dir); extern int is_inside_dir(const char *dir); @@ -81,4 +80,7 @@ extern int is_inside_dir(const char *dir); extern void setup_standard_excludes(struct dir_struct *dir); extern int remove_dir_recursively(struct strbuf *path, int only_empty); +/* tries to remove the path with empty directories along it, ignores ENOENT */ +extern int remove_path(const char *path); + #endif @@ -26,9 +26,8 @@ int launch_editor(const char *path, struct strbuf *buffer, const char *const *en int i = 0; int failed; const char *args[6]; - struct strbuf arg0; + struct strbuf arg0 = STRBUF_INIT; - strbuf_init(&arg0, 0); if (strcspn(editor, "$ \t'") != len) { /* there are specials */ strbuf_addf(&arg0, "%s \"$@\"", editor); diff --git a/environment.c b/environment.c index 0c6d11f6a0..0693cd9a42 100644 --- a/environment.c +++ b/environment.c @@ -80,6 +80,11 @@ int is_bare_repository(void) return is_bare_repository_cfg && !get_git_work_tree(); } +int have_git_dir(void) +{ + return !!git_dir; +} + const char *get_git_dir(void) { if (!git_dir) diff --git a/exec_cmd.c b/exec_cmd.c index ce6741eb68..cdd35f9195 100644 --- a/exec_cmd.c +++ b/exec_cmd.c @@ -59,9 +59,7 @@ static void add_path(struct strbuf *out, const char *path) void setup_path(void) { const char *old_path = getenv("PATH"); - struct strbuf new_path; - - strbuf_init(&new_path, 0); + struct strbuf new_path = STRBUF_INIT; add_path(&new_path, argv_exec_path); add_path(&new_path, getenv(EXEC_PATH_ENVIRONMENT)); diff --git a/fast-import.c b/fast-import.c index ccdf2e57b0..3c035a5788 100644 --- a/fast-import.c +++ b/fast-import.c @@ -816,7 +816,7 @@ static void start_packfile(void) int pack_fd; snprintf(tmpfile, sizeof(tmpfile), - "%s/tmp_pack_XXXXXX", get_object_directory()); + "%s/pack/tmp_pack_XXXXXX", get_object_directory()); pack_fd = xmkstemp(tmpfile); p = xcalloc(1, sizeof(*p) + strlen(tmpfile) + 2); strcpy(p->pack_name, tmpfile); @@ -845,7 +845,7 @@ static int oecmp (const void *a_, const void *b_) static char *create_index(void) { static char tmpfile[PATH_MAX]; - SHA_CTX ctx; + git_SHA_CTX ctx; struct sha1file *f; struct object_entry **idx, **c, **last, *e; struct object_entry_pool *o; @@ -878,21 +878,21 @@ static char *create_index(void) } snprintf(tmpfile, sizeof(tmpfile), - "%s/tmp_idx_XXXXXX", get_object_directory()); + "%s/pack/tmp_idx_XXXXXX", get_object_directory()); idx_fd = xmkstemp(tmpfile); f = sha1fd(idx_fd, tmpfile); sha1write(f, array, 256 * sizeof(int)); - SHA1_Init(&ctx); + git_SHA1_Init(&ctx); for (c = idx; c != last; c++) { uint32_t offset = htonl((*c)->offset); sha1write(f, &offset, 4); sha1write(f, (*c)->sha1, sizeof((*c)->sha1)); - SHA1_Update(&ctx, (*c)->sha1, 20); + git_SHA1_Update(&ctx, (*c)->sha1, 20); } sha1write(f, pack_data->sha1, sizeof(pack_data->sha1)); sha1close(f, NULL, CSUM_FSYNC); free(idx); - SHA1_Final(pack_data->sha1, &ctx); + git_SHA1_Final(pack_data->sha1, &ctx); return tmpfile; } @@ -1033,15 +1033,15 @@ static int store_object( unsigned char hdr[96]; unsigned char sha1[20]; unsigned long hdrlen, deltalen; - SHA_CTX c; + git_SHA_CTX c; z_stream s; hdrlen = sprintf((char*)hdr,"%s %lu", typename(type), (unsigned long)dat->len) + 1; - SHA1_Init(&c); - SHA1_Update(&c, hdr, hdrlen); - SHA1_Update(&c, dat->buf, dat->len); - SHA1_Final(sha1, &c); + git_SHA1_Init(&c); + git_SHA1_Update(&c, hdr, hdrlen); + git_SHA1_Update(&c, dat->buf, dat->len); + git_SHA1_Final(sha1, &c); if (sha1out) hashcpy(sha1out, sha1); @@ -307,9 +307,8 @@ int fsck_error_function(struct object *obj, int type, const char *fmt, ...) { va_list ap; int len; - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; - strbuf_init(&sb, 0); strbuf_addf(&sb, "object %s:", obj->sha1?sha1_to_hex(obj->sha1):"(null)"); va_start(ap, fmt); diff --git a/git-bisect.sh b/git-bisect.sh index 97ac600873..79de7017e8 100755 --- a/git-bisect.sh +++ b/git-bisect.sh @@ -172,6 +172,25 @@ bisect_write() { test -n "$nolog" || echo "git bisect $state $rev" >>"$GIT_DIR/BISECT_LOG" } +is_expected_rev() { + test -f "$GIT_DIR/BISECT_EXPECTED_REV" && + test "$1" = $(cat "$GIT_DIR/BISECT_EXPECTED_REV") +} + +mark_expected_rev() { + echo "$1" > "$GIT_DIR/BISECT_EXPECTED_REV" +} + +check_expected_revs() { + for _rev in "$@"; do + if ! is_expected_rev "$_rev"; then + rm -f "$GIT_DIR/BISECT_ANCESTORS_OK" + rm -f "$GIT_DIR/BISECT_EXPECTED_REV" + return + fi + done +} + bisect_state() { bisect_autostart state=$1 @@ -181,7 +200,8 @@ bisect_state() { 1,bad|1,good|1,skip) rev=$(git rev-parse --verify HEAD) || die "Bad rev input: HEAD" - bisect_write "$state" "$rev" ;; + bisect_write "$state" "$rev" + check_expected_revs "$rev" ;; 2,bad|*,good|*,skip) shift eval='' @@ -191,7 +211,8 @@ bisect_state() { die "Bad rev input: $rev" eval="$eval bisect_write '$state' '$sha'; " done - eval "$eval" ;; + eval "$eval" + check_expected_revs "$@" ;; *,bad) die "'git bisect bad' can take only one argument." ;; *) @@ -243,33 +264,18 @@ bisect_auto_next() { bisect_next_check && bisect_next || : } -eval_rev_list() { - _eval="$1" - - eval $_eval - res=$? - - if [ $res -ne 0 ]; then - echo >&2 "'git rev-list --bisect-vars' failed:" - echo >&2 "maybe you mistake good and bad revs?" - exit $res - fi - - return $res -} - filter_skipped() { _eval="$1" _skip="$2" if [ -z "$_skip" ]; then - eval_rev_list "$_eval" + eval "$_eval" return fi # Let's parse the output of: # "git rev-list --bisect-vars --bisect-all ..." - eval_rev_list "$_eval" | while read hash line + eval "$_eval" | while read hash line do case "$VARS,$FOUND,$TRIED,$hash" in # We display some vars. @@ -332,20 +338,133 @@ exit_if_skipped_commits () { fi } +bisect_checkout() { + _rev="$1" + _msg="$2" + echo "Bisecting: $_msg" + mark_expected_rev "$_rev" + git checkout -q "$_rev" || exit + git show-branch "$_rev" +} + +is_among() { + _rev="$1" + _list="$2" + case "$_list" in *$_rev*) return 0 ;; esac + return 1 +} + +handle_bad_merge_base() { + _badmb="$1" + _good="$2" + if is_expected_rev "$_badmb"; then + cat >&2 <<EOF +The merge base $_badmb is bad. +This means the bug has been fixed between $_badmb and [$_good]. +EOF + exit 3 + else + cat >&2 <<EOF +Some good revs are not ancestor of the bad rev. +git bisect cannot work properly in this case. +Maybe you mistake good and bad revs? +EOF + exit 1 + fi +} + +handle_skipped_merge_base() { + _mb="$1" + _bad="$2" + _good="$3" + cat >&2 <<EOF +Warning: the merge base between $_bad and [$_good] must be skipped. +So we cannot be sure the first bad commit is between $_mb and $_bad. +We continue anyway. +EOF +} + +# +# "check_merge_bases" checks that merge bases are not "bad". +# +# - If one is "good", that's good, we have nothing to do. +# - If one is "bad", it means the user assumed something wrong +# and we must exit. +# - If one is "skipped", we can't know but we should warn. +# - If we don't know, we should check it out and ask the user to test. +# +# In the last case we will return 1, and otherwise 0. +# +check_merge_bases() { + _bad="$1" + _good="$2" + _skip="$3" + for _mb in $(git merge-base --all $_bad $_good) + do + if is_among "$_mb" "$_good"; then + continue + elif test "$_mb" = "$_bad"; then + handle_bad_merge_base "$_bad" "$_good" + elif is_among "$_mb" "$_skip"; then + handle_skipped_merge_base "$_mb" "$_bad" "$_good" + else + bisect_checkout "$_mb" "a merge base must be tested" + return 1 + fi + done + return 0 +} + +# +# "check_good_are_ancestors_of_bad" checks that all "good" revs are +# ancestor of the "bad" rev. +# +# If that's not the case, we need to check the merge bases. +# If a merge base must be tested by the user we return 1 and +# otherwise 0. +# +check_good_are_ancestors_of_bad() { + test -f "$GIT_DIR/BISECT_ANCESTORS_OK" && + return + + _bad="$1" + _good=$(echo $2 | sed -e 's/\^//g') + _skip="$3" + + # Bisecting with no good rev is ok + test -z "$_good" && return + + _side=$(git rev-list $_good ^$_bad) + if test -n "$_side"; then + # Return if a checkout was done + check_merge_bases "$_bad" "$_good" "$_skip" || return + fi + + : > "$GIT_DIR/BISECT_ANCESTORS_OK" + + return 0 +} + bisect_next() { case "$#" in 0) ;; *) usage ;; esac bisect_autostart bisect_next_check good + # Get bad, good and skipped revs + bad=$(git rev-parse --verify refs/bisect/bad) && + good=$(git for-each-ref --format='^%(objectname)' \ + "refs/bisect/good-*" | tr '\012' ' ') && skip=$(git for-each-ref --format='%(objectname)' \ - "refs/bisect/skip-*" | tr '\012' ' ') || exit + "refs/bisect/skip-*" | tr '\012' ' ') && + + # Maybe some merge bases must be tested first + check_good_are_ancestors_of_bad "$bad" "$good" "$skip" + # Return now if a checkout has already been done + test "$?" -eq "1" && return + # Get bisection information BISECT_OPT='' test -n "$skip" && BISECT_OPT='--bisect-all' - - bad=$(git rev-parse --verify refs/bisect/bad) && - good=$(git for-each-ref --format='^%(objectname)' \ - "refs/bisect/good-*" | tr '\012' ' ') && eval="git rev-list --bisect-vars $BISECT_OPT $good $bad --" && eval="$eval $(cat "$GIT_DIR/BISECT_NAMES")" && eval=$(filter_skipped "$eval" "$skip") && @@ -366,9 +485,7 @@ bisect_next() { # commit is also a "skip" commit (see above). exit_if_skipped_commits "$bisect_rev" - echo "Bisecting: $bisect_nr revisions left to test after this" - git checkout -q "$bisect_rev" || exit - git show-branch "$bisect_rev" + bisect_checkout "$bisect_rev" "$bisect_nr revisions left to test after this" } bisect_visualize() { @@ -415,6 +532,8 @@ bisect_clean_state() { do git update-ref -d $ref $hash || exit done + rm -f "$GIT_DIR/BISECT_EXPECTED_REV" && + rm -f "$GIT_DIR/BISECT_ANCESTORS_OK" && rm -f "$GIT_DIR/BISECT_LOG" && rm -f "$GIT_DIR/BISECT_NAMES" && rm -f "$GIT_DIR/BISECT_RUN" && diff --git a/git-compat-util.h b/git-compat-util.h index db2836fbde..e20b1e858c 100644 --- a/git-compat-util.h +++ b/git-compat-util.h @@ -85,6 +85,7 @@ #undef _XOPEN_SOURCE #include <grp.h> #define _XOPEN_SOURCE 600 +#include "compat/cygwin.h" #else #undef _ALL_SOURCE /* AIX 5.3L defines a struct list with _ALL_SOURCE. */ #include <grp.h> @@ -154,10 +155,7 @@ extern void die(const char *err, ...) NORETURN __attribute__((format (printf, 1, extern int error(const char *err, ...) __attribute__((format (printf, 1, 2))); extern void warning(const char *err, ...) __attribute__((format (printf, 1, 2))); -extern void set_usage_routine(void (*routine)(const char *err) NORETURN); extern void set_die_routine(void (*routine)(const char *err, va_list params) NORETURN); -extern void set_error_routine(void (*routine)(const char *err, va_list params)); -extern void set_warn_routine(void (*routine)(const char *warn, va_list params)); extern int prefixcmp(const char *str, const char *prefix); extern time_t tm_to_time_t(const struct tm *tm); diff --git a/git-gui/.gitattributes b/git-gui/.gitattributes new file mode 100644 index 0000000000..f96112d47f --- /dev/null +++ b/git-gui/.gitattributes @@ -0,0 +1,3 @@ +* encoding=US-ASCII +git-gui.sh encoding=UTF-8 +/po/*.po encoding=UTF-8 diff --git a/git-gui/git-gui.sh b/git-gui/git-gui.sh index 10d8a4422f..4085e8fea5 100755 --- a/git-gui/git-gui.sh +++ b/git-gui/git-gui.sh @@ -521,6 +521,19 @@ proc kill_file_process {fd} { } } +proc gitattr {path attr default} { + if {[catch {set r [git check-attr $attr -- $path]}]} { + set r unspecified + } else { + set r [join [lrange [split $r :] 2 end] :] + regsub {^ } $r {} r + } + if {$r eq {unspecified}} { + return $default + } + return $r +} + proc sq {value} { regsub -all ' $value "'\\''" value return "'$value'" @@ -665,6 +678,7 @@ set default_config(merge.verbosity) 2 set default_config(user.name) {} set default_config(user.email) {} +set default_config(gui.encoding) [encoding system] set default_config(gui.matchtrackingbranch) false set default_config(gui.pruneduringfetch) false set default_config(gui.trustmtime) false @@ -948,10 +962,32 @@ blame { } citool { enable_option singlecommit + enable_option retcode disable_option multicommit disable_option branch disable_option transport + + while {[llength $argv] > 0} { + set a [lindex $argv 0] + switch -- $a { + --amend { + enable_option initialamend + } + --nocommit { + enable_option nocommit + enable_option nocommitmsg + } + --commitmsg { + disable_option nocommitmsg + } + default { + break + } + } + + set argv [lrange $argv 1 end] + } } } @@ -1023,8 +1059,12 @@ set current_branch {} set is_detached 0 set current_diff_path {} set is_3way_diff 0 +set is_conflict_diff 0 set selected_commit_type new +set nullid "0000000000000000000000000000000000000000" +set nullid2 "0000000000000000000000000000000000000001" + ###################################################################### ## ## task management @@ -1105,6 +1145,20 @@ proc PARENT {} { return $empty_tree } +proc force_amend {} { + global selected_commit_type + global HEAD PARENT MERGE_HEAD commit_type + + repository_state newType newHEAD newMERGE_HEAD + set HEAD $newHEAD + set PARENT $newHEAD + set MERGE_HEAD $newMERGE_HEAD + set commit_type $newType + + set selected_commit_type amend + do_select_commit_type +} + proc rescan {after {honor_trustmtime 1}} { global HEAD PARENT MERGE_HEAD commit_type global ui_index ui_workdir ui_comm @@ -1131,6 +1185,7 @@ proc rescan {after {honor_trustmtime 1}} { || [string trim [$ui_comm get 0.0 end]] eq {})} { if {[string match amend* $commit_type]} { } elseif {[load_message GITGUI_MSG]} { + } elseif {[run_prepare_commit_msg_hook]} { } elseif {[load_message MERGE_MSG]} { } elseif {[load_message SQUASH_MSG]} { } @@ -1230,6 +1285,70 @@ proc load_message {file} { return 0 } +proc run_prepare_commit_msg_hook {} { + global pch_error + + # prepare-commit-msg requires PREPARE_COMMIT_MSG exist. From git-gui + # it will be .git/MERGE_MSG (merge), .git/SQUASH_MSG (squash), or an + # empty file but existant file. + + set fd_pcm [open [gitdir PREPARE_COMMIT_MSG] a] + + if {[file isfile [gitdir MERGE_MSG]]} { + set pcm_source "merge" + set fd_mm [open [gitdir MERGE_MSG] r] + puts -nonewline $fd_pcm [read $fd_mm] + close $fd_mm + } elseif {[file isfile [gitdir SQUASH_MSG]]} { + set pcm_source "squash" + set fd_sm [open [gitdir SQUASH_MSG] r] + puts -nonewline $fd_pcm [read $fd_sm] + close $fd_sm + } else { + set pcm_source "" + } + + close $fd_pcm + + set fd_ph [githook_read prepare-commit-msg \ + [gitdir PREPARE_COMMIT_MSG] $pcm_source] + if {$fd_ph eq {}} { + catch {file delete [gitdir PREPARE_COMMIT_MSG]} + return 0; + } + + ui_status [mc "Calling prepare-commit-msg hook..."] + set pch_error {} + + fconfigure $fd_ph -blocking 0 -translation binary -eofchar {} + fileevent $fd_ph readable \ + [list prepare_commit_msg_hook_wait $fd_ph] + + return 1; +} + +proc prepare_commit_msg_hook_wait {fd_ph} { + global pch_error + + append pch_error [read $fd_ph] + fconfigure $fd_ph -blocking 1 + if {[eof $fd_ph]} { + if {[catch {close $fd_ph}]} { + ui_status [mc "Commit declined by prepare-commit-msg hook."] + hook_failed_popup prepare-commit-msg $pch_error + catch {file delete [gitdir PREPARE_COMMIT_MSG]} + exit 1 + } else { + load_message PREPARE_COMMIT_MSG + } + set pch_error {} + catch {file delete [gitdir PREPARE_COMMIT_MSG]} + return + } + fconfigure $fd_ph -blocking 0 + catch {file delete [gitdir PREPARE_COMMIT_MSG]} +} + proc read_diff_index {fd after} { global buf_rdi @@ -1751,11 +1870,19 @@ proc do_gitk {revs} { } set is_quitting 0 +set ret_code 1 + +proc terminate_me {win} { + global ret_code + if {$win ne {.}} return + exit $ret_code +} -proc do_quit {} { +proc do_quit {{rc {1}}} { global ui_comm is_quitting repo_config commit_type global GITGUI_BCK_exists GITGUI_BCK_i global ui_comm_spell + global ret_code if {$is_quitting} return set is_quitting 1 @@ -1810,6 +1937,7 @@ proc do_quit {} { } } + set ret_code $rc destroy . } @@ -1951,19 +2079,21 @@ proc toggle_or_diff {w x y} { $ui_index tag remove in_sel 0.0 end $ui_workdir tag remove in_sel 0.0 end - # Do not stage files with conflicts + # Determine the state of the file if {[info exists file_states($path)]} { set state [lindex $file_states($path) 0] } else { set state {__} } - if {[string first {U} $state] >= 0} { - set col 1 - } - # Restage the file, or simply show the diff if {$col == 0 && $y > 1} { + # Conflicts need special handling + if {[string first {U} $state] >= 0} { + merge_stage_workdir $path $w $lno + return + } + if {[string index $state 1] eq {O}} { set mmask {} } else { @@ -2212,26 +2342,36 @@ if {[is_enabled branch]} { # -- Commit Menu # +proc commit_btn_caption {} { + if {[is_enabled nocommit]} { + return [mc "Done"] + } else { + return [mc Commit@@verb] + } +} + if {[is_enabled multicommit] || [is_enabled singlecommit]} { menu .mbar.commit - .mbar.commit add radiobutton \ - -label [mc "New Commit"] \ - -command do_select_commit_type \ - -variable selected_commit_type \ - -value new - lappend disable_on_lock \ - [list .mbar.commit entryconf [.mbar.commit index last] -state] + if {![is_enabled nocommit]} { + .mbar.commit add radiobutton \ + -label [mc "New Commit"] \ + -command do_select_commit_type \ + -variable selected_commit_type \ + -value new + lappend disable_on_lock \ + [list .mbar.commit entryconf [.mbar.commit index last] -state] - .mbar.commit add radiobutton \ - -label [mc "Amend Last Commit"] \ - -command do_select_commit_type \ - -variable selected_commit_type \ - -value amend - lappend disable_on_lock \ - [list .mbar.commit entryconf [.mbar.commit index last] -state] + .mbar.commit add radiobutton \ + -label [mc "Amend Last Commit"] \ + -command do_select_commit_type \ + -variable selected_commit_type \ + -value amend + lappend disable_on_lock \ + [list .mbar.commit entryconf [.mbar.commit index last] -state] - .mbar.commit add separator + .mbar.commit add separator + } .mbar.commit add command -label [mc Rescan] \ -command ui_do_rescan \ @@ -2273,11 +2413,13 @@ if {[is_enabled multicommit] || [is_enabled singlecommit]} { .mbar.commit add separator - .mbar.commit add command -label [mc "Sign Off"] \ - -command do_signoff \ - -accelerator $M1T-S + if {![is_enabled nocommit]} { + .mbar.commit add command -label [mc "Sign Off"] \ + -command do_signoff \ + -accelerator $M1T-S + } - .mbar.commit add command -label [mc Commit@@verb] \ + .mbar.commit add command -label [commit_btn_caption] \ -command do_commit \ -accelerator $M1T-Return lappend disable_on_lock \ @@ -2601,19 +2743,23 @@ pack .vpane.lower.commarea.buttons.incall -side top -fill x lappend disable_on_lock \ {.vpane.lower.commarea.buttons.incall conf -state} -button .vpane.lower.commarea.buttons.signoff -text [mc "Sign Off"] \ - -command do_signoff -pack .vpane.lower.commarea.buttons.signoff -side top -fill x +if {![is_enabled nocommit]} { + button .vpane.lower.commarea.buttons.signoff -text [mc "Sign Off"] \ + -command do_signoff + pack .vpane.lower.commarea.buttons.signoff -side top -fill x +} -button .vpane.lower.commarea.buttons.commit -text [mc Commit@@verb] \ +button .vpane.lower.commarea.buttons.commit -text [commit_btn_caption] \ -command do_commit pack .vpane.lower.commarea.buttons.commit -side top -fill x lappend disable_on_lock \ {.vpane.lower.commarea.buttons.commit conf -state} -button .vpane.lower.commarea.buttons.push -text [mc Push] \ - -command do_push_anywhere -pack .vpane.lower.commarea.buttons.push -side top -fill x +if {![is_enabled nocommit]} { + button .vpane.lower.commarea.buttons.push -text [mc Push] \ + -command do_push_anywhere + pack .vpane.lower.commarea.buttons.push -side top -fill x +} # -- Commit Message Buffer # @@ -2621,20 +2767,24 @@ frame .vpane.lower.commarea.buffer frame .vpane.lower.commarea.buffer.header set ui_comm .vpane.lower.commarea.buffer.t set ui_coml .vpane.lower.commarea.buffer.header.l -radiobutton .vpane.lower.commarea.buffer.header.new \ - -text [mc "New Commit"] \ - -command do_select_commit_type \ - -variable selected_commit_type \ - -value new -lappend disable_on_lock \ - [list .vpane.lower.commarea.buffer.header.new conf -state] -radiobutton .vpane.lower.commarea.buffer.header.amend \ - -text [mc "Amend Last Commit"] \ - -command do_select_commit_type \ - -variable selected_commit_type \ - -value amend -lappend disable_on_lock \ - [list .vpane.lower.commarea.buffer.header.amend conf -state] + +if {![is_enabled nocommit]} { + radiobutton .vpane.lower.commarea.buffer.header.new \ + -text [mc "New Commit"] \ + -command do_select_commit_type \ + -variable selected_commit_type \ + -value new + lappend disable_on_lock \ + [list .vpane.lower.commarea.buffer.header.new conf -state] + radiobutton .vpane.lower.commarea.buffer.header.amend \ + -text [mc "Amend Last Commit"] \ + -command do_select_commit_type \ + -variable selected_commit_type \ + -value amend + lappend disable_on_lock \ + [list .vpane.lower.commarea.buffer.header.amend conf -state] +} + label $ui_coml \ -anchor w \ -justify left @@ -2652,8 +2802,11 @@ proc trace_commit_type {varname args} { } trace add variable commit_type write trace_commit_type pack $ui_coml -side left -fill x -pack .vpane.lower.commarea.buffer.header.amend -side right -pack .vpane.lower.commarea.buffer.header.new -side right + +if {![is_enabled nocommit]} { + pack .vpane.lower.commarea.buffer.header.amend -side right + pack .vpane.lower.commarea.buffer.header.new -side right +} text $ui_comm -background white -foreground black \ -borderwidth 1 \ @@ -2860,6 +3013,14 @@ proc create_common_diff_popup {ctxm} { -command {incr_font_size font_diff 1} lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state] $ctxm add separator + set emenu $ctxm.enc + menu $emenu + build_encoding_menu $emenu [list force_diff_encoding] + $ctxm add cascade \ + -label [mc "Encoding"] \ + -menu $emenu + lappend diff_actions [list $ctxm entryconf [$ctxm index last] -state] + $ctxm add separator $ctxm add command -label [mc "Options..."] \ -command do_options } @@ -3191,7 +3352,20 @@ lock_index begin-read if {![winfo ismapped .]} { wm deiconify . } -after 1 do_rescan +after 1 { + if {[is_enabled initialamend]} { + force_amend + } else { + do_rescan + } + + if {[is_enabled nocommitmsg]} { + $ui_comm configure -state disabled -background gray + } +} if {[is_enabled multicommit]} { after 1000 hint_gc } +if {[is_enabled retcode]} { + bind . <Destroy> {+terminate_me %W} +} diff --git a/git-gui/lib/blame.tcl b/git-gui/lib/blame.tcl index 827c85d67f..eb61374d2d 100644 --- a/git-gui/lib/blame.tcl +++ b/git-gui/lib/blame.tcl @@ -256,9 +256,16 @@ constructor new {i_commit i_path i_jump} { $w.ctxm add command \ -label [mc "Copy Commit"] \ -command [cb _copycommit] + $w.ctxm add separator + menu $w.ctxm.enc + build_encoding_menu $w.ctxm.enc [cb _setencoding] + $w.ctxm add cascade \ + -label [mc "Encoding"] \ + -menu $w.ctxm.enc $w.ctxm add command \ -label [mc "Do Full Copy Detection"] \ -command [cb _fullcopyblame] + $w.ctxm add separator $w.ctxm add command \ -label [mc "Show History Context"] \ -command [cb _gitkcommit] @@ -399,7 +406,10 @@ method _load {jump} { } else { set fd [git_read cat-file blob "$commit:$path"] } - fconfigure $fd -blocking 0 -translation lf -encoding binary + fconfigure $fd \ + -blocking 0 \ + -translation lf \ + -encoding [get_path_encoding $path] fileevent $fd readable [cb _read_file $fd $jump] set current_fd $fd } @@ -508,7 +518,7 @@ method _exec_blame {cur_w cur_d options cur_s} { } lappend options -- $path set fd [eval git_read --nice blame $options] - fconfigure $fd -blocking 0 -translation lf -encoding binary + fconfigure $fd -blocking 0 -translation lf -encoding utf-8 fileevent $fd readable [cb _read_blame $fd $cur_w $cur_d] set current_fd $fd set blame_lines 0 @@ -788,6 +798,16 @@ method _click {cur_w pos} { _showcommit $this $cur_w $lno } +method _setencoding {enc} { + force_path_encoding $path $enc + _load $this [list \ + $highlight_column \ + $highlight_line \ + [lindex [$w_file xview] 0] \ + [lindex [$w_file yview] 0] \ + ] +} + method _load_commit {cur_w cur_d pos} { upvar #0 $cur_d line_data set lno [lindex [split [$cur_w index $pos] .] 0] @@ -881,12 +901,6 @@ method _showcommit {cur_w lno} { set enc [tcl_encoding $enc] if {$enc ne {}} { set msg [encoding convertfrom $enc $msg] - set author_name [encoding convertfrom $enc $author_name] - set committer_name [encoding convertfrom $enc $committer_name] - set header($cmit,author) $author_name - set header($cmit,committer) $committer_name - set header($cmit,summary) \ - [encoding convertfrom $enc $header($cmit,summary)] } set msg [string trim $msg] } @@ -942,9 +956,20 @@ method _format_offset_date {base offset} { } method _gitkcommit {} { + global nullid + set dat [_get_click_amov_info $this] if {$dat ne {}} { set cmit [lindex $dat 0] + + # If the line belongs to the working copy, use HEAD instead + if {$cmit eq $nullid} { + if {[catch {set cmit [git rev-parse --verify HEAD]} err]} { + error_popup [strcat [mc "Cannot find HEAD commit:"] "\n\n$err"] + return; + } + } + set radius [get_config gui.blamehistoryctx] set cmdline [list --select-commit=$cmit] @@ -981,12 +1006,20 @@ method _gitkcommit {} { } method _blameparent {} { + global nullid + set dat [_get_click_amov_info $this] if {$dat ne {}} { set cmit [lindex $dat 0] set new_path [lindex $dat 1] - if {[catch {set cparent [git rev-parse --verify "$cmit^"]}]} { + # Allow using Blame Parent on lines modified in the working copy + if {$cmit eq $nullid} { + set parent_ref "HEAD" + } else { + set parent_ref "$cmit^" + } + if {[catch {set cparent [git rev-parse --verify $parent_ref]} err]} { error_popup [strcat [mc "Cannot find parent commit:"] "\n\n$err"] return; } @@ -996,8 +1029,12 @@ method _blameparent {} { # Generate a diff between the commit and its parent, # and use the hunks to update the line number. # Request zero context to simplify calculations. - if {[catch {set fd [eval git_read diff-tree \ - --unified=0 $cparent $cmit $new_path]} err]} { + if {$cmit eq $nullid} { + set diffcmd [list diff-index --unified=0 $cparent -- $new_path] + } else { + set diffcmd [list diff-tree --unified=0 $cparent $cmit -- $new_path] + } + if {[catch {set fd [eval git_read $diffcmd]} err]} { $status stop [mc "Unable to display parent"] error_popup [strcat [mc "Error loading diff:"] "\n\n$err"] return diff --git a/git-gui/lib/commit.tcl b/git-gui/lib/commit.tcl index 2977315624..334514996a 100644 --- a/git-gui/lib/commit.tcl +++ b/git-gui/lib/commit.tcl @@ -168,7 +168,7 @@ File %s cannot be committed by this program. } } } - if {!$files_ready && ![string match *merge $curType]} { + if {!$files_ready && ![string match *merge $curType] && ![is_enabled nocommit]} { info_popup [mc "No changes to commit. You must stage at least 1 file before you can commit. @@ -177,6 +177,8 @@ You must stage at least 1 file before you can commit. return } + if {[is_enabled nocommitmsg]} { do_quit 0 } + # -- A message is required. # set msg [string trim [$ui_comm get 1.0 end]] @@ -212,6 +214,8 @@ A good commit message has the following format: puts $msg_wt $msg close $msg_wt + if {[is_enabled nocommit]} { do_quit 0 } + # -- Run the pre-commit hook. # set fd_ph [githook_read pre-commit] @@ -410,7 +414,7 @@ A rescan will be automatically started now. set ::GITGUI_BCK_exists 0 } - if {[is_enabled singlecommit]} do_quit + if {[is_enabled singlecommit]} { do_quit 0 } # -- Update in memory status # diff --git a/git-gui/lib/diff.tcl b/git-gui/lib/diff.tcl index a30c80a935..abe502d971 100644 --- a/git-gui/lib/diff.tcl +++ b/git-gui/lib/diff.tcl @@ -40,6 +40,15 @@ proc reshow_diff {} { } } +proc force_diff_encoding {enc} { + global current_diff_path + + if {$current_diff_path ne {}} { + force_path_encoding $current_diff_path $enc + reshow_diff + } +} + proc handle_empty_diff {} { global current_diff_path file_states file_lists @@ -60,9 +69,9 @@ A rescan will be automatically started to find other files which may have the sa rescan ui_ready 0 } -proc show_diff {path w {lno {}} {scroll_pos {}}} { +proc show_diff {path w {lno {}} {scroll_pos {}} {callback {}}} { global file_states file_lists - global is_3way_diff diff_active repo_config + global is_3way_diff is_conflict_diff diff_active repo_config global ui_diff ui_index ui_workdir global current_diff_path current_diff_side current_diff_header global current_diff_queue @@ -83,36 +92,42 @@ proc show_diff {path w {lno {}} {scroll_pos {}}} { set s $file_states($path) set m [lindex $s 0] + set is_conflict_diff 0 set current_diff_path $path set current_diff_side $w set current_diff_queue {} ui_status [mc "Loading diff of %s..." [escape_path $path]] + set cont_info [list $scroll_pos $callback] + if {[string first {U} $m] >= 0} { - merge_load_stages $path [list show_unmerged_diff $scroll_pos] + merge_load_stages $path [list show_unmerged_diff $cont_info] } elseif {$m eq {_O}} { - show_other_diff $path $w $m $scroll_pos + show_other_diff $path $w $m $cont_info } else { - start_show_diff $scroll_pos + start_show_diff $cont_info } } -proc show_unmerged_diff {scroll_pos} { +proc show_unmerged_diff {cont_info} { global current_diff_path current_diff_side - global merge_stages ui_diff + global merge_stages ui_diff is_conflict_diff global current_diff_queue if {$merge_stages(2) eq {}} { + set is_conflict_diff 1 lappend current_diff_queue \ [list "LOCAL: deleted\nREMOTE:\n" d======= \ [list ":1:$current_diff_path" ":3:$current_diff_path"]] } elseif {$merge_stages(3) eq {}} { + set is_conflict_diff 1 lappend current_diff_queue \ [list "REMOTE: deleted\nLOCAL:\n" d======= \ [list ":1:$current_diff_path" ":2:$current_diff_path"]] } elseif {[lindex $merge_stages(1) 0] eq {120000} || [lindex $merge_stages(2) 0] eq {120000} || [lindex $merge_stages(3) 0] eq {120000}} { + set is_conflict_diff 1 lappend current_diff_queue \ [list "LOCAL:\n" d======= \ [list ":1:$current_diff_path" ":2:$current_diff_path"]] @@ -120,14 +135,14 @@ proc show_unmerged_diff {scroll_pos} { [list "REMOTE:\n" d======= \ [list ":1:$current_diff_path" ":3:$current_diff_path"]] } else { - start_show_diff $scroll_pos + start_show_diff $cont_info return } - advance_diff_queue $scroll_pos + advance_diff_queue $cont_info } -proc advance_diff_queue {scroll_pos} { +proc advance_diff_queue {cont_info} { global current_diff_queue ui_diff set item [lindex $current_diff_queue 0] @@ -137,10 +152,10 @@ proc advance_diff_queue {scroll_pos} { $ui_diff insert end [lindex $item 0] [lindex $item 1] $ui_diff conf -state disabled - start_show_diff $scroll_pos [lindex $item 2] + start_show_diff $cont_info [lindex $item 2] } -proc show_other_diff {path w m scroll_pos} { +proc show_other_diff {path w m cont_info} { global file_states file_lists global is_3way_diff diff_active repo_config global ui_diff ui_index ui_workdir @@ -165,7 +180,9 @@ proc show_other_diff {path w m scroll_pos} { } file { set fd [open $path r] - fconfigure $fd -eofchar {} + fconfigure $fd \ + -eofchar {} \ + -encoding [get_path_encoding $path] set content [read $fd $max_sz] close $fd set sz [file size $path] @@ -217,16 +234,21 @@ proc show_other_diff {path w m scroll_pos} { $ui_diff conf -state disabled set diff_active 0 unlock_index + set scroll_pos [lindex $cont_info 0] if {$scroll_pos ne {}} { update $ui_diff yview moveto $scroll_pos } ui_ready + set callback [lindex $cont_info 1] + if {$callback ne {}} { + eval $callback + } return } } -proc start_show_diff {scroll_pos {add_opts {}}} { +proc start_show_diff {cont_info {add_opts {}}} { global file_states file_lists global is_3way_diff diff_active repo_config global ui_diff ui_index ui_workdir @@ -279,14 +301,14 @@ proc start_show_diff {scroll_pos {add_opts {}}} { set ::current_diff_inheader 1 fconfigure $fd \ -blocking 0 \ - -encoding binary \ - -translation binary - fileevent $fd readable [list read_diff $fd $scroll_pos] + -encoding [get_path_encoding $path] \ + -translation lf + fileevent $fd readable [list read_diff $fd $cont_info] } -proc read_diff {fd scroll_pos} { +proc read_diff {fd cont_info} { global ui_diff diff_active - global is_3way_diff current_diff_header + global is_3way_diff is_conflict_diff current_diff_header global current_diff_queue $ui_diff conf -state normal @@ -334,6 +356,7 @@ proc read_diff {fd scroll_pos} { {--} {set tags d_--} {++} { if {[regexp {^\+\+([<>]{7} |={7})} $line _g op]} { + set is_conflict_diff 1 set line [string replace $line 0 1 { }] set tags d$op } else { @@ -353,6 +376,7 @@ proc read_diff {fd scroll_pos} { {-} {set tags d_-} {+} { if {[regexp {^\+([<>]{7} |={7})} $line _g op]} { + set is_conflict_diff 1 set line [string replace $line 0 0 { }] set tags d$op } else { @@ -377,12 +401,13 @@ proc read_diff {fd scroll_pos} { close $fd if {$current_diff_queue ne {}} { - advance_diff_queue $scroll_pos + advance_diff_queue $cont_info return } set diff_active 0 unlock_index + set scroll_pos [lindex $cont_info 0] if {$scroll_pos ne {}} { update $ui_diff yview moveto $scroll_pos @@ -392,6 +417,10 @@ proc read_diff {fd scroll_pos} { if {[$ui_diff index end] eq {2.0}} { handle_empty_diff } + set callback [lindex $cont_info 1] + if {$callback ne {}} { + eval $callback + } } } @@ -432,8 +461,9 @@ proc apply_hunk {x y} { } if {[catch { + set enc [get_path_encoding $current_diff_path] set p [eval git_write $apply_cmd] - fconfigure $p -translation binary -encoding binary + fconfigure $p -translation binary -encoding $enc puts -nonewline $p $current_diff_header puts -nonewline $p [$ui_diff get $s_lno $e_lno] close $p} err]} { @@ -601,8 +631,9 @@ proc apply_line {x y} { set patch "@@ -$hln,$n +$hln,[eval expr $n $sign 1] @@\n$patch" if {[catch { + set enc [get_path_encoding $current_diff_path] set p [eval git_write $apply_cmd] - fconfigure $p -translation binary -encoding binary + fconfigure $p -translation binary -encoding $enc puts -nonewline $p $current_diff_header puts -nonewline $p $patch close $p} err]} { diff --git a/git-gui/lib/encoding.tcl b/git-gui/lib/encoding.tcl index 7f06b0d47f..32668fc9c6 100644 --- a/git-gui/lib/encoding.tcl +++ b/git-gui/lib/encoding.tcl @@ -206,7 +206,7 @@ set encoding_aliases { { ISO-8859-16 iso-ir-226 ISO_8859-16:2001 ISO_8859-16 latin10 l10 } { GBK CP936 MS936 windows-936 } { JIS_Encoding csJISEncoding } - { Shift_JIS MS_Kanji csShiftJIS } + { Shift_JIS MS_Kanji csShiftJIS ShiftJIS Shift-JIS } { Extended_UNIX_Code_Packed_Format_for_Japanese csEUCPkdFmtJapanese EUC-JP } { Extended_UNIX_Code_Fixed_Width_for_Japanese csEUCFixWidJapanese } @@ -240,37 +240,227 @@ set encoding_aliases { { Big5 csBig5 } } +set encoding_groups { + {"" "" + {"Unicode" UTF-8} + {"Western" ISO-8859-1}} + {we "West European" + {"Western" ISO-8859-15 CP-437 CP-850 MacRoman CP-1252 Windows-1252} + {"Celtic" ISO-8859-14} + {"Greek" ISO-8859-14 ISO-8859-7 CP-737 CP-869 MacGreek CP-1253 Windows-1253} + {"Icelandic" MacIceland MacIcelandic CP-861} + {"Nordic" ISO-8859-10 CP-865} + {"Portuguese" CP-860} + {"South European" ISO-8859-3}} + {ee "East European" + {"Baltic" CP-775 ISO-8859-4 ISO-8859-13 CP-1257 Windows-1257} + {"Central European" CP-852 ISO-8859-2 MacCE CP-1250 Windows-1250} + {"Croatian" MacCroatian} + {"Cyrillic" CP-855 ISO-8859-5 ISO-IR-111 KOI8-R MacCyrillic CP-1251 Windows-1251} + {"Russian" CP-866} + {"Ukrainian" KOI8-U MacUkraine MacUkrainian} + {"Romanian" ISO-8859-16 MacRomania MacRomanian}} + {ea "East Asian" + {"Generic" ISO-2022} + {"Chinese Simplified" GB2312 GB1988 GB12345 GB2312-RAW GBK EUC-CN GB18030 HZ ISO-2022-CN} + {"Chinese Traditional" Big5 Big5-HKSCS EUC-TW CP-950} + {"Japanese" EUC-JP ISO-2022-JP Shift-JIS JIS-0212 JIS-0208 JIS-0201 CP-932 MacJapan} + {"Korean" EUC-KR UHC JOHAB ISO-2022-KR CP-949 KSC5601}} + {sa "SE & SW Asian" + {"Armenian" ARMSCII-8} + {"Georgian" GEOSTD8} + {"Thai" TIS-620 ISO-8859-11 CP-874 Windows-874 MacThai} + {"Turkish" CP-857 CP857 ISO-8859-9 MacTurkish CP-1254 Windows-1254} + {"Vietnamese" TCVN VISCII VPS CP-1258 Windows-1258} + {"Hindi" MacDevanagari} + {"Gujarati" MacGujarati} + {"Gurmukhi" MacGurmukhi}} + {me "Middle Eastern" + {"Arabic" ISO-8859-6 Windows-1256 CP-1256 CP-864 MacArabic} + {"Farsi" MacFarsi} + {"Hebrew" ISO-8859-8-I Windows-1255 CP-1255 ISO-8859-8 CP-862 MacHebrew}} + {mi "Misc" + {"7-bit" ASCII} + {"16-bit" Unicode} + {"Legacy" CP-863 EBCDIC} + {"Symbol" Symbol Dingbats MacDingbats MacCentEuro}} +} + +proc build_encoding_table {} { + global encoding_aliases encoding_lookup_table + + # Prepare the lookup list; cannot use lsort -nocase because + # of compatibility issues with older Tcl (e.g. in msysgit) + set names [list] + foreach item [encoding names] { + lappend names [list [string tolower $item] $item] + } + set names [lsort -ascii -index 0 $names] + # neither can we use lsearch -index + set lnames [list] + foreach item $names { + lappend lnames [lindex $item 0] + } + + foreach grp $encoding_aliases { + set target {} + foreach item $grp { + set i [lsearch -sorted -ascii $lnames \ + [string tolower $item]] + if {$i >= 0} { + set target [lindex $names $i 1] + break + } + } + if {$target eq {}} continue + foreach item $grp { + set encoding_lookup_table([string tolower $item]) $target + } + } + + foreach item $names { + set encoding_lookup_table([lindex $item 0]) [lindex $item 1] + } +} + proc tcl_encoding {enc} { - global encoding_aliases - set names [encoding names] - set lcnames [string tolower $names] - set enc [string tolower $enc] - set i [lsearch -exact $lcnames $enc] - if {$i < 0} { - # look for "isonnn" instead of "iso-nnn" or "iso_nnn" - if {[regsub {^iso[-_]} $enc iso encx]} { - set i [lsearch -exact $lcnames $encx] + global encoding_lookup_table + if {$enc eq {}} { + return {} + } + if {![info exists encoding_lookup_table]} { + build_encoding_table + } + set enc [string tolower $enc] + if {![info exists encoding_lookup_table($enc)]} { + # look for "isonnn" instead of "iso-nnn" or "iso_nnn" + if {[regsub {^(iso|cp|ibm|jis)[-_]} $enc {\1} encx]} { + set enc $encx + } + } + if {[info exists encoding_lookup_table($enc)]} { + return $encoding_lookup_table($enc) + } else { + return {} + } +} + +proc force_path_encoding {path enc} { + global path_encoding_overrides last_encoding_override + + set enc [tcl_encoding $enc] + if {$enc eq {}} { + catch { unset last_encoding_override } + catch { unset path_encoding_overrides($path) } + } else { + set last_encoding_override $enc + if {$path ne {}} { + set path_encoding_overrides($path) $enc + } + } +} + +proc get_path_encoding {path} { + global path_encoding_overrides last_encoding_override + + if {[info exists last_encoding_override]} { + set tcl_enc $last_encoding_override + } else { + set tcl_enc [tcl_encoding [get_config gui.encoding]] } - } - if {$i < 0} { - foreach l $encoding_aliases { - set ll [string tolower $l] - if {[lsearch -exact $ll $enc] < 0} continue - # look through the aliases for one that tcl knows about - foreach e $ll { - set i [lsearch -exact $lcnames $e] - if {$i < 0} { - if {[regsub {^iso[-_]} $e iso ex]} { - set i [lsearch -exact $lcnames $ex] - } + if {$tcl_enc eq {}} { + set tcl_enc [encoding system] + } + if {$path ne {}} { + if {[info exists path_encoding_overrides($path)]} { + set enc2 $path_encoding_overrides($path) + } else { + set enc2 [tcl_encoding [gitattr $path encoding $tcl_enc]] + } + if {$enc2 ne {}} { + set tcl_enc $enc2 + } + } + return $tcl_enc +} + +proc build_encoding_submenu {parent grp cmd} { + global used_encodings + + set mid [lindex $grp 0] + set gname [mc [lindex $grp 1]] + + set smenu {} + foreach subset [lrange $grp 2 end] { + set name [mc [lindex $subset 0]] + + foreach enc [lrange $subset 1 end] { + set tcl_enc [tcl_encoding $enc] + if {$tcl_enc eq {}} continue + + if {$smenu eq {}} { + if {$mid eq {}} { + set smenu $parent + } else { + set smenu "$parent.$mid" + menu $smenu + $parent add cascade \ + -label $gname \ + -menu $smenu + } + } + + if {$name ne {}} { + set lbl "$name ($enc)" + } else { + set lbl $enc + } + $smenu add command \ + -label $lbl \ + -command [concat $cmd [list $tcl_enc]] + + lappend used_encodings $tcl_enc + } + } +} + +proc popup_btn_menu {m b} { + tk_popup $m [winfo pointerx $b] [winfo pointery $b] +} + +proc build_encoding_menu {emenu cmd {nodef 0}} { + $emenu configure -postcommand \ + [list do_build_encoding_menu $emenu $cmd $nodef] +} + +proc do_build_encoding_menu {emenu cmd {nodef 0}} { + global used_encodings encoding_groups + + $emenu configure -postcommand {} + + if {!$nodef} { + $emenu add command \ + -label [mc "Default"] \ + -command [concat $cmd [list {}]] + } + set sysenc [encoding system] + $emenu add command \ + -label [mc "System (%s)" $sysenc] \ + -command [concat $cmd [list $sysenc]] + + # Main encoding tree + set used_encodings [list identity] + $emenu add separator + foreach grp $encoding_groups { + build_encoding_submenu $emenu $grp $cmd + } + + # Add unclassified encodings + set unused_grp [list [mc Other]] + foreach enc [encoding names] { + if {[lsearch -exact $used_encodings $enc] < 0} { + lappend unused_grp $enc } - if {$i >= 0} break - } - break } - } - if {$i >= 0} { - return [lindex $names $i] - } - return {} + build_encoding_submenu $emenu [list other [mc Other] $unused_grp] $cmd } diff --git a/git-gui/lib/mergetool.tcl b/git-gui/lib/mergetool.tcl index 79c58bc7bc..6ab5701d93 100644 --- a/git-gui/lib/mergetool.tcl +++ b/git-gui/lib/mergetool.tcl @@ -5,24 +5,51 @@ proc merge_resolve_one {stage} { global current_diff_path switch -- $stage { - 1 { set target [mc "the base version"] } - 2 { set target [mc "this branch"] } - 3 { set target [mc "the other branch"] } + 1 { set targetquestion [mc "Force resolution to the base version?"] } + 2 { set targetquestion [mc "Force resolution to this branch?"] } + 3 { set targetquestion [mc "Force resolution to the other branch?"] } } - set op_question [mc "Force resolution to %s? -Note that the diff shows only conflicting changes. + set op_question [strcat $targetquestion "\n" \ +[mc "Note that the diff shows only conflicting changes. %s will be overwritten. This operation can be undone only by restarting the merge." \ - $target [short_path $current_diff_path]] + [short_path $current_diff_path]]] if {[ask_popup $op_question] eq {yes}} { merge_load_stages $current_diff_path [list merge_force_stage $stage] } } +proc merge_stage_workdir {path w lno} { + global current_diff_path diff_active + + if {$diff_active} return + + if {$path ne $current_diff_path} { + show_diff $path $w $lno {} [list do_merge_stage_workdir $path] + } else { + do_merge_stage_workdir $path + } +} + +proc do_merge_stage_workdir {path} { + global current_diff_path is_conflict_diff + + if {$path ne $current_diff_path} return; + + if {$is_conflict_diff} { + if {[ask_popup [mc "File %s seems to have unresolved conflicts, still stage?" \ + [short_path $path]]] ne {yes}} { + return + } + } + + merge_add_resolution $path +} + proc merge_add_resolution {path} { global current_diff_path ui_workdir diff --git a/git-gui/lib/option.tcl b/git-gui/lib/option.tcl index 9b865f6a75..c80c939878 100644 --- a/git-gui/lib/option.tcl +++ b/git-gui/lib/option.tcl @@ -1,6 +1,28 @@ # git-gui options editor # Copyright (C) 2006, 2007 Shawn Pearce +proc config_check_encodings {} { + global repo_config_new global_config_new + + set enc $global_config_new(gui.encoding) + if {$enc eq {}} { + set global_config_new(gui.encoding) [encoding system] + } elseif {[tcl_encoding $enc] eq {}} { + error_popup [mc "Invalid global encoding '%s'" $enc] + return 0 + } + + set enc $repo_config_new(gui.encoding) + if {$enc eq {}} { + set repo_config_new(gui.encoding) [encoding system] + } elseif {[tcl_encoding $enc] eq {}} { + error_popup [mc "Invalid repo encoding '%s'" $enc] + return 0 + } + + return 1 +} + proc save_config {} { global default_config font_descs global repo_config global_config @@ -130,6 +152,7 @@ proc do_options {} { {i-1..99 gui.diffcontext {mc "Number of Diff Context Lines"}} {i-0..99 gui.commitmsgwidth {mc "Commit Message Text Width"}} {t gui.newbranchtemplate {mc "New Branch Name Template"}} + {c gui.encoding {mc "Default File Contents Encoding"}} } { set type [lindex $option 0] set name [lindex $option 1] @@ -159,6 +182,7 @@ proc do_options {} { pack $w.$f.$optid.v -side right -anchor e -padx 5 pack $w.$f.$optid -side top -anchor w -fill x } + c - t { frame $w.$f.$optid label $w.$f.$optid.l -text "$text:" @@ -171,6 +195,16 @@ proc do_options {} { pack $w.$f.$optid.v -side left -anchor w \ -fill x -expand 1 \ -padx 5 + if {$type eq {c}} { + menu $w.$f.$optid.m + build_encoding_menu $w.$f.$optid.m \ + [list set ${f}_config_new($name)] 1 + button $w.$f.$optid.b \ + -text [mc "Change"] \ + -command [list popup_btn_menu \ + $w.$f.$optid.m $w.$f.$optid.b] + pack $w.$f.$optid.b -side left -anchor w + } pack $w.$f.$optid -side top -anchor w -fill x } } @@ -275,6 +309,7 @@ proc do_restore_defaults {} { } proc do_save_config {w} { + if {![config_check_encodings]} return if {[catch {save_config} err]} { error_popup [strcat [mc "Failed to completely save options:"] "\n\n$err"] } diff --git a/git-gui/po/de.po b/git-gui/po/de.po index fa43947ad0..793cca1e79 100644 --- a/git-gui/po/de.po +++ b/git-gui/po/de.po @@ -7,8 +7,8 @@ msgid "" msgstr "" "Project-Id-Version: git-gui\n" "Report-Msgid-Bugs-To: \n" -"POT-Creation-Date: 2008-08-02 08:58+0200\n" -"PO-Revision-Date: 2008-08-02 09:09+0200\n" +"POT-Creation-Date: 2008-09-13 10:20+0200\n" +"PO-Revision-Date: 2008-09-13 10:24+0200\n" "Last-Translator: Christian Stimming <stimming@tuhh.de>\n" "Language-Team: German\n" "MIME-Version: 1.0\n" @@ -110,7 +110,15 @@ msgstr "Teilweise bereitgestellt zum Eintragen" msgid "Staged for commit, missing" msgstr "Bereitgestellt zum Eintragen, fehlend" -#: git-gui.sh:1597 +#: git-gui.sh:1658 +msgid "File type changed, not staged" +msgstr "Dateityp geändert, nicht bereitgestellt" + +#: git-gui.sh:1659 +msgid "File type changed, staged" +msgstr "Dateityp geändert, bereitgestellt" + +#: git-gui.sh:1661 msgid "Untracked, not staged" msgstr "Nicht unter Versionskontrolle, nicht bereitgestellt" @@ -396,15 +404,7 @@ msgstr "Alle kopieren" msgid "File:" msgstr "Datei:" -#: git-gui.sh:2589 -msgid "Apply/Reverse Hunk" -msgstr "Kontext anwenden/umkehren" - -#: git-gui.sh:2696 -msgid "Apply/Reverse Line" -msgstr "Zeile anwenden/umkehren" - -#: git-gui.sh:2711 +#: git-gui.sh:2834 msgid "Refresh" msgstr "Aktualisieren" @@ -416,7 +416,35 @@ msgstr "Schriftgröße verkleinern" msgid "Increase Font Size" msgstr "Schriftgröße vergrößern" -#: git-gui.sh:2646 +#: git-gui.sh:2870 +msgid "Apply/Reverse Hunk" +msgstr "Kontext anwenden/umkehren" + +#: git-gui.sh:2875 +msgid "Apply/Reverse Line" +msgstr "Zeile anwenden/umkehren" + +#: git-gui.sh:2885 +msgid "Run Merge Tool" +msgstr "Zusammenführungswerkzeug" + +#: git-gui.sh:2890 +msgid "Use Remote Version" +msgstr "Entfernte Version benutzen" + +#: git-gui.sh:2894 +msgid "Use Local Version" +msgstr "Lokale Version benutzen" + +#: git-gui.sh:2898 +msgid "Revert To Base" +msgstr "Ursprüngliche Version benutzen" + +#: git-gui.sh:2906 +msgid "Stage Working Copy" +msgstr "Arbeitskopie bereitstellen" + +#: git-gui.sh:2925 msgid "Unstage Hunk From Commit" msgstr "Kontext aus Bereitstellung herausnehmen" @@ -498,7 +526,15 @@ msgstr "Version kopieren" msgid "Do Full Copy Detection" msgstr "Volle Kopie-Erkennung" -#: lib/blame.tcl:388 +#: lib/blame.tcl:263 +msgid "Show History Context" +msgstr "Historien-Kontext anzeigen" + +#: lib/blame.tcl:266 +msgid "Blame Parent Commit" +msgstr "Elternversion annotieren" + +#: lib/blame.tcl:394 #, tcl-format msgid "Reading %s..." msgstr "%s lesen..." @@ -547,7 +583,19 @@ msgstr "Eintragender:" msgid "Original File:" msgstr "Ursprüngliche Datei:" -#: lib/blame.tcl:925 +#: lib/blame.tcl:990 +msgid "Cannot find parent commit:" +msgstr "Elternversion kann nicht gefunden werden:" + +#: lib/blame.tcl:1001 +msgid "Unable to display parent" +msgstr "Elternversion kann nicht angezeigt werden" + +#: lib/blame.tcl:1002 lib/diff.tcl:191 +msgid "Error loading diff:" +msgstr "Fehler beim Laden des Vergleichs:" + +#: lib/blame.tcl:1142 msgid "Originally By:" msgstr "Ursprünglich von:" @@ -1494,11 +1542,7 @@ msgstr "Git-Projektarchiv (Unterprojekt)" msgid "* Binary file (not showing content)." msgstr "* Binärdatei (Inhalt wird nicht angezeigt)" -#: lib/diff.tcl:185 -msgid "Error loading diff:" -msgstr "Fehler beim Laden des Vergleichs:" - -#: lib/diff.tcl:303 +#: lib/diff.tcl:313 msgid "Failed to unstage selected hunk." msgstr "" "Fehler beim Herausnehmen des gewählten Kontexts aus der Bereitstellung." @@ -1586,6 +1630,15 @@ msgstr "" msgid "Do Nothing" msgstr "Nichts tun" +#: lib/index.tcl:419 +msgid "Reverting selected files" +msgstr "Änderungen in gewählten Dateien verwerfen" + +#: lib/index.tcl:423 +#, tcl-format +msgid "Reverting %s" +msgstr "Änderungen in %s verwerfen" + #: lib/merge.tcl:13 msgid "" "Cannot merge while amending.\n" @@ -1730,6 +1783,96 @@ msgstr "Abbruch fehlgeschlagen." msgid "Abort completed. Ready." msgstr "Abbruch durchgeführt. Bereit." +#: lib/mergetool.tcl:14 +msgid "Force resolution to the base version?" +msgstr "Konflikt durch Basisversion ersetzen?" + +#: lib/mergetool.tcl:15 +msgid "Force resolution to this branch?" +msgstr "Konflikt durch diesen Zweig ersetzen?" + +#: lib/mergetool.tcl:16 +msgid "Force resolution to the other branch?" +msgstr "Konflikt durch anderen Zweig ersetzen?" + +#: lib/mergetool.tcl:20 +#, tcl-format +msgid "" +"Note that the diff shows only conflicting changes.\n" +"\n" +"%s will be overwritten.\n" +"\n" +"This operation can be undone only by restarting the merge." +msgstr "" +"Hinweis: Der Vergleich zeigt nur konfliktverursachende Änderungen an.\n" +"\n" +"»%s« wird überschrieben.\n" +"\n" +"Diese Operation kann nur rückgängig gemacht werden, wenn die\n" +"Zusammenführung erneut gestartet wird." + +#: lib/mergetool.tcl:32 +#, tcl-format +msgid "Adding resolution for %s" +msgstr "Auflösung hinzugefügt für %s" + +#: lib/mergetool.tcl:119 +msgid "Cannot resolve deletion or link conflicts using a tool" +msgstr "" +"Konflikte durch gelöschte Dateien oder symbolische Links können nicht durch " +"das Zusamenführungswerkzeug gelöst werden." + +#: lib/mergetool.tcl:124 +msgid "Conflict file does not exist" +msgstr "Konflikt-Datei existiert nicht" + +#: lib/mergetool.tcl:236 +#, tcl-format +msgid "Not a GUI merge tool: '%s'" +msgstr "Kein GUI Zusammenführungswerkzeug: »%s«" + +#: lib/mergetool.tcl:240 +#, tcl-format +msgid "Unsupported merge tool '%s'" +msgstr "Unbekanntes Zusammenführungswerkzeug: »%s«" + +#: lib/mergetool.tcl:275 +msgid "Merge tool is already running, terminate it?" +msgstr "Zusammenführungswerkzeug läuft bereits. Soll es abgebrochen werden?" + +#: lib/mergetool.tcl:295 +#, tcl-format +msgid "" +"Error retrieving versions:\n" +"%s" +msgstr "" +"Fehler beim Abrufen der Dateiversionen:\n" +"%s" + +#: lib/mergetool.tcl:315 +#, tcl-format +msgid "" +"Could not start the merge tool:\n" +"\n" +"%s" +msgstr "" +"Zusammenführungswerkzeug konnte nicht gestartet werden:\n" +"\n" +"%s" + +#: lib/mergetool.tcl:319 +msgid "Running merge tool..." +msgstr "Zusammenführungswerkzeug starten..." + +#: lib/mergetool.tcl:347 lib/mergetool.tcl:363 +msgid "Merge tool failed." +msgstr "Zusammenführungswerkzeug fehlgeschlagen." + +#: lib/mergetool.tcl:353 +#, tcl-format +msgid "File %s unchanged, still accept as resolved?" +msgstr "Datei »%s« unverändert. Trotzdem Konflikt als gelöst akzeptieren?" + #: lib/option.tcl:95 msgid "Restore Defaults" msgstr "Voreinstellungen wiederherstellen" @@ -1767,7 +1910,11 @@ msgstr "Ausführlichkeit der Zusammenführen-Meldungen" msgid "Show Diffstat After Merge" msgstr "Vergleichsstatistik nach Zusammenführen anzeigen" -#: lib/option.tcl:123 +#: lib/option.tcl:122 +msgid "Use Merge Tool" +msgstr "Zusammenführungswerkzeug" + +#: lib/option.tcl:124 msgid "Trust File Modification Timestamps" msgstr "Auf Dateiänderungsdatum verlassen" @@ -1788,6 +1935,10 @@ msgid "Minimum Letters To Blame Copy On" msgstr "Mindestzahl Zeichen für Kopie-Annotieren" #: lib/option.tcl:128 +msgid "Blame History Context Radius (days)" +msgstr "Anzahl Tage für Historien-Kontext" + +#: lib/option.tcl:129 msgid "Number of Diff Context Lines" msgstr "Anzahl der Kontextzeilen beim Vergleich" diff --git a/git-rebase--interactive.sh b/git-rebase--interactive.sh index 929d681c47..86290f63b2 100755 --- a/git-rebase--interactive.sh +++ b/git-rebase--interactive.sh @@ -26,6 +26,7 @@ i,interactive always used (no-op) continue continue rebasing process abort abort rebasing process and restore original branch skip skip current patch and continue rebasing process +no-verify override pre-rebase hook from stopping the operation " . git-sh-setup @@ -41,6 +42,7 @@ PRESERVE_MERGES= STRATEGY= ONTO= VERBOSE= +OK_TO_SKIP_PRE_REBASE= GIT_CHERRY_PICK_HELP=" After resolving the conflicts, mark the corrected paths with 'git add <paths>', and @@ -65,6 +67,17 @@ output () { esac } +run_pre_rebase_hook () { + if test -z "$OK_TO_SKIP_PRE_REBASE" && + test -x "$GIT_DIR/hooks/pre-rebase" + then + "$GIT_DIR/hooks/pre-rebase" ${1+"$@"} || { + echo >&2 "The pre-rebase hook refused to rebase." + exit 1 + } + fi +} + require_clean_work_tree () { # test if working tree is dirty git rev-parse --verify HEAD > /dev/null && @@ -267,7 +280,7 @@ do_next () { "$DOTEST"/amend || exit read command sha1 rest < "$TODO" case "$command" in - '#'*|'') + '#'*|''|noop) mark_action_done ;; pick|p) @@ -284,7 +297,7 @@ do_next () { pick_one $sha1 || die_with_patch $sha1 "Could not apply $sha1... $rest" make_patch $sha1 - : > "$DOTEST"/amend + git rev-parse --verify HEAD > "$DOTEST"/amend warn "Stopped at $sha1... $rest" warn "You can amend the commit now, with" warn @@ -304,23 +317,28 @@ do_next () { mark_action_done make_squash_message $sha1 > "$MSG" + failed=f + author_script=$(get_author_ident_from_commit HEAD) + output git reset --soft HEAD^ + pick_one -n $sha1 || failed=t case "$(peek_next_command)" in squash|s) EDIT_COMMIT= USE_OUTPUT=output + MSG_OPT=-F + MSG_FILE="$MSG" cp "$MSG" "$SQUASH_MSG" ;; *) EDIT_COMMIT=-e USE_OUTPUT= + MSG_OPT= + MSG_FILE= rm -f "$SQUASH_MSG" || exit + cp "$MSG" "$GIT_DIR"/SQUASH_MSG + rm -f "$GIT_DIR"/MERGE_MSG || exit ;; esac - - failed=f - author_script=$(get_author_ident_from_commit HEAD) - output git reset --soft HEAD^ - pick_one -n $sha1 || failed=t echo "$author_script" > "$DOTEST"/author-script if test $failed = f then @@ -329,7 +347,7 @@ do_next () { GIT_AUTHOR_NAME="$GIT_AUTHOR_NAME" \ GIT_AUTHOR_EMAIL="$GIT_AUTHOR_EMAIL" \ GIT_AUTHOR_DATE="$GIT_AUTHOR_DATE" \ - $USE_OUTPUT git commit --no-verify -F "$MSG" $EDIT_COMMIT || failed=t + $USE_OUTPUT git commit --no-verify $MSG_OPT "$MSG_FILE" $EDIT_COMMIT || failed=t fi if test $failed = t then @@ -406,6 +424,11 @@ get_saved_options () { while test $# != 0 do case "$1" in + --no-verify) + OK_TO_SKIP_PRE_REBASE=yes + ;; + --verify) + ;; --continue) is_standalone "$@" || usage get_saved_options @@ -427,14 +450,22 @@ do else . "$DOTEST"/author-script || die "Cannot find the author identity" + amend= if test -f "$DOTEST"/amend then + amend=$(git rev-parse --verify HEAD) + test "$amend" = $(cat "$DOTEST"/amend) || + die "\ +You have uncommitted changes in your working tree. Please, commit them +first and then run 'git rebase --continue' again." git reset --soft HEAD^ || die "Cannot rewind the HEAD" fi export GIT_AUTHOR_NAME GIT_AUTHOR_EMAIL GIT_AUTHOR_DATE && - git commit --no-verify -F "$DOTEST"/message -e || - die "Could not commit staged changes." + git commit --no-verify -F "$DOTEST"/message -e || { + test -n "$amend" && git reset --soft $amend + die "Could not commit staged changes." + } fi require_clean_work_tree @@ -499,6 +530,7 @@ do ;; --) shift + run_pre_rebase_hook ${1+"$@"} test $# -eq 1 -o $# -eq 2 || usage test -d "$DOTEST" && die "Interactive rebase already started" @@ -560,6 +592,7 @@ do --abbrev=7 --reverse --left-right --cherry-pick \ $UPSTREAM...$HEAD | \ sed -n "s/^>/pick /p" > "$TODO" + test -s "$TODO" || echo noop >> "$TODO" cat >> "$TODO" << EOF # Rebase $SHORTUPSTREAM..$SHORTHEAD onto $SHORTONTO diff --git a/git-rebase.sh b/git-rebase.sh index 528b604cd5..023a6dc94a 100755 --- a/git-rebase.sh +++ b/git-rebase.sh @@ -34,6 +34,7 @@ set_reflog_action rebase require_work_tree cd_to_toplevel +OK_TO_SKIP_PRE_REBASE= RESOLVEMSG=" When you have resolved this problem run \"git rebase --continue\". If you would prefer to skip this patch, instead run \"git rebase --skip\". @@ -138,10 +139,37 @@ finish_rb_merge () { } is_interactive () { - test -f "$dotest"/interactive || - while :; do case $#,"$1" in 0,|*,-i|*,--interactive) break ;; esac + while test $# != 0 + do + case "$1" in + -i|--interactive) + interactive_rebase=explicit + break + ;; + -p|--preserve-merges) + interactive_rebase=implied + ;; + esac shift - done && test -n "$1" + done + + if [ "$interactive_rebase" = implied ]; then + GIT_EDITOR=: + export GIT_EDITOR + fi + + test -n "$interactive_rebase" || test -f "$dotest"/interactive +} + +run_pre_rebase_hook () { + if test -z "$OK_TO_SKIP_PRE_REBASE" && + test -x "$GIT_DIR/hooks/pre-rebase" + then + "$GIT_DIR/hooks/pre-rebase" ${1+"$@"} || { + echo >&2 "The pre-rebase hook refused to rebase." + exit 1 + } + fi } test -f "$GIT_DIR"/rebase-apply/applying && @@ -160,6 +188,9 @@ fi while test $# != 0 do case "$1" in + --no-verify) + OK_TO_SKIP_PRE_REBASE=yes + ;; --continue) test -d "$dotest" -o -d "$GIT_DIR"/rebase-apply || die "No rebase in progress?" @@ -320,13 +351,7 @@ onto_name=${newbase-"$upstream_name"} onto=$(git rev-parse --verify "${onto_name}^0") || exit # If a hook exists, give it a chance to interrupt -if test -x "$GIT_DIR/hooks/pre-rebase" -then - "$GIT_DIR/hooks/pre-rebase" ${1+"$@"} || { - echo >&2 "The pre-rebase hook refused to rebase." - exit 1 - } -fi +run_pre_rebase_hook ${1+"$@"} # If the branch to rebase is given, that is the branch we will rebase # $branch_name -- branch being rebased, or HEAD (already detached) diff --git a/git-repack.sh b/git-repack.sh index 683960b04d..d39eb6cea6 100755 --- a/git-repack.sh +++ b/git-repack.sh @@ -10,7 +10,7 @@ git repack [options] a pack everything in a single pack A same as -a, and turn unreachable objects loose d remove redundant packs, and run git-prune-packed -f pass --no-reuse-delta to git-pack-objects +f pass --no-reuse-object to git-pack-objects n do not run git-update-server-info q,quiet be quiet l pass --local to git-pack-objects diff --git a/git-send-email.perl b/git-send-email.perl index d2fd899076..bdbfac6625 100755 --- a/git-send-email.perl +++ b/git-send-email.perl @@ -39,75 +39,40 @@ package main; sub usage { print <<EOT; git send-email [options] <file | directory>... -Options: - --from Specify the "From:" line of the email to be sent. - --to Specify the primary "To:" line of the email. - - --cc Specify an initial "Cc:" list for the entire series - of emails. - - --cc-cmd Specify a command to execute per file which adds - per file specific cc address entries - - --bcc Specify a list of email addresses that should be Bcc: - on all the emails. - - --compose Use \$GIT_EDITOR, core.editor, \$EDITOR, or \$VISUAL to edit - an introductory message for the patch series. - - --subject Specify the initial "Subject:" line. - Only necessary if --compose is also set. If --compose - is not set, this will be prompted for. - - --in-reply-to Specify the first "In-Reply-To:" header line. - Only used if --compose is also set. If --compose is not - set, this will be prompted for. - - --chain-reply-to If set, the replies will all be to the previous - email sent, rather than to the first email sent. - Defaults to on. - - --signed-off-cc Automatically add email addresses that appear in - Signed-off-by: or Cc: lines to the cc: list. Defaults to on. - - --identity The configuration identity, a subsection to prioritise over - the default section. - - --smtp-server If set, specifies the outgoing SMTP server to use. - Defaults to localhost. Port number can be specified here with - hostname:port format or by using --smtp-server-port option. - - --smtp-server-port Specify a port on the outgoing SMTP server to connect to. - - --smtp-user The username for SMTP-AUTH. - - --smtp-pass The password for SMTP-AUTH. - - --smtp-encryption Specify 'tls' for STARTTLS encryption, or 'ssl' for SSL. - Any other value disables the feature. - - --smtp-ssl Synonym for '--smtp-encryption=ssl'. Deprecated. - - --suppress-cc Suppress the specified category of auto-CC. The category - can be one of 'author' for the patch author, 'self' to - avoid copying yourself, 'sob' for Signed-off-by lines, - 'cccmd' for the output of the cccmd, or 'all' to suppress - all of these. - - --suppress-from Suppress sending emails to yourself. Defaults to off. - - --thread Specify that the "In-Reply-To:" header should be set on all - emails. Defaults to on. - - --quiet Make git-send-email less verbose. One line per email - should be all that is output. - - --dry-run Do everything except actually send the emails. - - --envelope-sender Specify the envelope sender used to send the emails. - - --no-validate Don't perform any sanity checks on patches. + Composing: + --from <str> * Email From: + --to <str> * Email To: + --cc <str> * Email Cc: + --bcc <str> * Email Bcc: + --subject <str> * Email "Subject:" + --in-reply-to <str> * Email "In-Reply-To:" + --compose * Open an editor for introduction. + + Sending: + --envelope-sender <str> * Email envelope sender. + --smtp-server <str:int> * Outgoing SMTP server to use. The port + is optional. Default 'localhost'. + --smtp-server-port <int> * Outgoing SMTP server port. + --smtp-user <str> * Username for SMTP-AUTH. + --smtp-pass <str> * Password for SMTP-AUTH; not necessary. + --smtp-encryption <str> * tls or ssl; anything else disables. + --smtp-ssl * Deprecated. Use '--smtp-encryption ssl'. + + Automating: + --identity <str> * Use the sendemail.<id> options. + --cc-cmd <str> * Email Cc: via `<str> \$patch_path` + --suppress-cc <str> * author, self, sob, cccmd, all. + --[no-]signed-off-by-cc * Send to Cc: and Signed-off-by: + addresses. Default on. + --[no-]suppress-from * Send to self. Default off. + --[no-]chain-reply-to * Chain In-Reply-To: fields. Default on. + --[no-]thread * Use In-Reply-To: field. Default on. + + Administering: + --quiet * Output one line of info per email. + --dry-run * Don't actually send the emails. + --[no-]validate * Perform patch sanity checks. Default on. EOT exit(1); @@ -186,17 +151,19 @@ if ($@) { my ($quiet, $dry_run) = (0, 0); # Variables with corresponding config settings -my ($thread, $chain_reply_to, $suppress_from, $signed_off_cc, $cc_cmd); +my ($thread, $chain_reply_to, $suppress_from, $signed_off_by_cc, $cc_cmd); my ($smtp_server, $smtp_server_port, $smtp_authuser, $smtp_encryption); my ($identity, $aliasfiletype, @alias_files, @smtp_host_parts); -my ($no_validate); +my ($validate); my (@suppress_cc); my %config_bool_settings = ( "thread" => [\$thread, 1], "chainreplyto" => [\$chain_reply_to, 1], "suppressfrom" => [\$suppress_from, undef], - "signedoffcc" => [\$signed_off_cc, undef], + "signedoffbycc" => [\$signed_off_by_cc, undef], + "signedoffcc" => [\$signed_off_by_cc, undef], # Deprecated + "validate" => [\$validate, 1], ); my %config_settings = ( @@ -259,11 +226,11 @@ my $rc = GetOptions("sender|from=s" => \$sender, "cc-cmd=s" => \$cc_cmd, "suppress-from!" => \$suppress_from, "suppress-cc=s" => \@suppress_cc, - "signed-off-cc|signed-off-by-cc!" => \$signed_off_cc, + "signed-off-cc|signed-off-by-cc!" => \$signed_off_by_cc, "dry-run" => \$dry_run, "envelope-sender=s" => \$envelope_sender, "thread!" => \$thread, - "no-validate" => \$no_validate, + "validate!" => \$validate, ); unless ($rc) { @@ -335,7 +302,7 @@ if ($suppress_cc{'all'}) { # If explicit old-style ones are specified, they trump --suppress-cc. $suppress_cc{'self'} = $suppress_from if defined $suppress_from; -$suppress_cc{'sob'} = !$signed_off_cc if defined $signed_off_cc; +$suppress_cc{'sob'} = !$signed_off_by_cc if defined $signed_off_by_cc; # Debugging, print out the suppressions. if (0) { @@ -416,7 +383,7 @@ for my $f (@ARGV) { } } -if (!$no_validate) { +if ($validate) { foreach my $f (@files) { unless (-p $f) { my $error = validate_patch($f); diff --git a/git-stash.sh b/git-stash.sh index d799c76378..b9ace99704 100755 --- a/git-stash.sh +++ b/git-stash.sh @@ -144,17 +144,16 @@ show_stash () { then flags=--stat fi - s=$(git rev-parse --revs-only --no-flags --default $ref_stash "$@") - w_commit=$(git rev-parse --verify "$s") && - b_commit=$(git rev-parse --verify "$s^") && + w_commit=$(git rev-parse --verify --default $ref_stash "$@") && + b_commit=$(git rev-parse --verify "$w_commit^") && git diff $flags $b_commit $w_commit } apply_stash () { git update-index -q --refresh && git diff-files --quiet --ignore-submodules || - die 'Cannot restore on top of a dirty state' + die 'Cannot apply to a dirty working tree, please stage your changes' unstash_index= case "$1" in @@ -169,7 +168,7 @@ apply_stash () { # stash records the work tree, and is a merge between the # base commit (first parent) and the index tree (second parent). - s=$(git rev-parse --revs-only --no-flags --default $ref_stash "$@") && + s=$(git rev-parse --verify --default $ref_stash "$@") && w_tree=$(git rev-parse --verify "$s:") && b_tree=$(git rev-parse --verify "$s^1:") && i_tree=$(git rev-parse --verify "$s^2:") || @@ -229,7 +228,7 @@ drop_stash () { shift fi # Verify supplied argument looks like a stash entry - s=$(git rev-parse --revs-only --no-flags "$@") && + s=$(git rev-parse --verify "$@") && git rev-parse --verify "$s:" > /dev/null 2>&1 && git rev-parse --verify "$s^1:" > /dev/null 2>&1 && git rev-parse --verify "$s^2:" > /dev/null 2>&1 || diff --git a/git-submodule.sh b/git-submodule.sh index 1c39b593a6..65178ae8e3 100755 --- a/git-submodule.sh +++ b/git-submodule.sh @@ -194,7 +194,7 @@ cmd_add() else module_clone "$path" "$realrepo" || exit - (unset GIT_DIR; cd "$path" && git checkout -q ${branch:+-b "$branch" "origin/$branch"}) || + (unset GIT_DIR; cd "$path" && git checkout -f -q ${branch:+-b "$branch" "origin/$branch"}) || die "Unable to checkout submodule '$path'" fi @@ -340,8 +340,13 @@ cmd_update() if test "$subsha1" != "$sha1" then + force= + if test -z "$subsha1" + then + force="-f" + fi (unset GIT_DIR; cd "$path" && git-fetch && - git-checkout -q "$sha1") || + git-checkout $force -q "$sha1") || die "Unable to checkout '$sha1' in submodule path '$path'" say "Submodule path '$path': checked out '$sha1'" @@ -634,6 +639,14 @@ cmd_sync() do name=$(module_name "$path") url=$(git config -f .gitmodules --get submodule."$name".url) + + # Possibly a url relative to parent + case "$url" in + ./*|../*) + url=$(resolve_relative_url "$url") || exit + ;; + esac + if test -e "$path"/.git then ( diff --git a/git-svn.perl b/git-svn.perl index 88066c9a75..ef6d773df1 100755 --- a/git-svn.perl +++ b/git-svn.perl @@ -66,7 +66,7 @@ my ($_stdin, $_help, $_edit, $_version, $_fetch_all, $_no_rebase, $_merge, $_strategy, $_dry_run, $_local, $_prefix, $_no_checkout, $_url, $_verbose, - $_git_format, $_commit_url); + $_git_format, $_commit_url, $_tag); $Git::SVN::_follow_parent = 1; my %remote_opts = ( 'username=s' => \$Git::SVN::Prompt::_username, 'config-dir=s' => \$Git::SVN::Ra::config_dir, @@ -131,6 +131,15 @@ my %cmd = ( 'revision|r=i' => \$_revision, 'no-rebase' => \$_no_rebase, %cmt_opts, %fc_opts } ], + branch => [ \&cmd_branch, + 'Create a branch in the SVN repository', + { 'message|m=s' => \$_message, + 'dry-run|n' => \$_dry_run, + 'tag|t' => \$_tag } ], + tag => [ sub { $_tag = 1; cmd_branch(@_) }, + 'Create a tag in the SVN repository', + { 'message|m=s' => \$_message, + 'dry-run|n' => \$_dry_run } ], 'set-tree' => [ \&cmd_set_tree, "Set an SVN repository to a git tree-ish", { 'stdin|' => \$_stdin, %cmt_opts, %fc_opts, } ], @@ -537,6 +546,42 @@ sub cmd_dcommit { unlink $gs->{index}; } +sub cmd_branch { + my ($branch_name, $head) = @_; + + unless (defined $branch_name && length $branch_name) { + die(($_tag ? "tag" : "branch") . " name required\n"); + } + $head ||= 'HEAD'; + + my ($src, $rev, undef, $gs) = working_head_info($head); + + my $remote = Git::SVN::read_all_remotes()->{svn}; + my $glob = $remote->{ $_tag ? 'tags' : 'branches' }; + my ($lft, $rgt) = @{ $glob->{path} }{qw/left right/}; + my $dst = join '/', $remote->{url}, $lft, $branch_name, ($rgt || ()); + + my $ctx = SVN::Client->new( + auth => Git::SVN::Ra::_auth_providers(), + log_msg => sub { + ${ $_[0] } = defined $_message + ? $_message + : 'Create ' . ($_tag ? 'tag ' : 'branch ' ) + . $branch_name; + }, + ); + + eval { + $ctx->ls($dst, 'HEAD', 0); + } and die "branch ${branch_name} already exists\n"; + + print "Copying ${src} at r${rev} to ${dst}...\n"; + $ctx->copy($src, $rev, $dst) + unless $_dry_run; + + $gs->fetch_all; +} + sub cmd_find_rev { my $revision_or_hash = shift or die "SVN or git revision required ", "as a command-line argument\n"; @@ -2591,7 +2636,7 @@ sub set_tree { my ($self, $tree) = (shift, shift); my $log_entry = ::get_commit_entry($tree); unless ($self->{last_rev}) { - fatal("Must have an existing revision to commit"); + ::fatal("Must have an existing revision to commit"); } my %ed_opts = ( r => $self->{last_rev}, log => $log_entry->{log}, @@ -2626,9 +2671,9 @@ sub rebuild_from_rev_db { sub rebuild { my ($self) = @_; my $map_path = $self->map_path; - return if (-e $map_path && ! -z $map_path); + my $partial = (-e $map_path && ! -z $map_path); return unless ::verify_ref($self->refname.'^0'); - if ($self->use_svm_props || $self->no_metadata) { + if (!$partial && ($self->use_svm_props || $self->no_metadata)) { my $rev_db = $self->rev_db_path; $self->rebuild_from_rev_db($rev_db); if ($self->use_svm_props) { @@ -2638,10 +2683,13 @@ sub rebuild { $self->unlink_rev_db_symlink; return; } - print "Rebuilding $map_path ...\n"; + print "Rebuilding $map_path ...\n" if (!$partial); + my ($base_rev, $head) = ($partial ? $self->rev_map_max_norebuild(1) : + (undef, undef)); my ($log, $ctx) = command_output_pipe(qw/rev-list --pretty=raw --no-color --reverse/, - $self->refname, '--'); + ($head ? "$head.." : "") . $self->refname, + '--'); my $metadata_url = $self->metadata_url; remove_username($metadata_url); my $svn_uuid = $self->ra_uuid; @@ -2664,12 +2712,17 @@ sub rebuild { ($metadata_url && $url && ($url ne $metadata_url))) { next; } + if ($partial && $head) { + print "Partial-rebuilding $map_path ...\n"; + print "Currently at $base_rev = $head\n"; + $head = undef; + } $self->rev_map_set($rev, $c); print "r$rev = $c\n"; } command_close_pipe($log, $ctx); - print "Done rebuilding $map_path\n"; + print "Done rebuilding $map_path\n" if (!$partial || !$head); my $rev_db_path = $self->rev_db_path; if (-f $self->rev_db_path) { unlink $self->rev_db_path or croak "unlink: $!"; @@ -2809,6 +2862,12 @@ sub rev_map_set { sub rev_map_max { my ($self, $want_commit) = @_; $self->rebuild; + my ($r, $c) = $self->rev_map_max_norebuild($want_commit); + $want_commit ? ($r, $c) : $r; +} + +sub rev_map_max_norebuild { + my ($self, $want_commit) = @_; my $map_path = $self->map_path; stat $map_path or return $want_commit ? (0, undef) : 0; sysopen(my $fh, $map_path, O_RDONLY) or croak "open: $!"; @@ -4010,20 +4069,19 @@ sub gs_do_switch { my $old_url = $full_url; $full_url .= '/' . escape_uri_only($path) if length $path; my ($ra, $reparented); - if ($old_url ne $full_url) { - if ($old_url !~ m#^svn(\+ssh)?://#) { - SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, - $pool); - $self->{url} = $full_url; - $reparented = 1; - } else { - $_[0] = undef; - $self = undef; - $RA = undef; - $ra = Git::SVN::Ra->new($full_url); - $ra_invalid = 1; - } + + if ($old_url =~ m#^svn(\+ssh)?://#) { + $_[0] = undef; + $self = undef; + $RA = undef; + $ra = Git::SVN::Ra->new($full_url); + $ra_invalid = 1; + } elsif ($old_url ne $full_url) { + SVN::_Ra::svn_ra_reparent($self->{session}, $full_url, $pool); + $self->{url} = $full_url; + $reparented = 1; } + $ra ||= $self; $url_b = escape_url($url_b); my $reporter = $ra->do_switch($rev_b, '', 1, $url_b, $editor, $pool); diff --git a/git-web--browse.sh b/git-web--browse.sh index 384148a59f..78d236b77f 100755 --- a/git-web--browse.sh +++ b/git-web--browse.sh @@ -31,7 +31,7 @@ valid_custom_tool() valid_tool() { case "$1" in - firefox | iceweasel | konqueror | w3m | links | lynx | dillo | open) + firefox | iceweasel | konqueror | w3m | links | lynx | dillo | open | start) ;; # happy *) valid_custom_tool "$1" || return 1 @@ -114,6 +114,10 @@ if test -z "$browser" ; then if test -n "$SECURITYSESSIONID"; then browser_candidates="open $browser_candidates" fi + # /bin/start indicates MinGW + if test -n /bin/start; then + browser_candidates="start $browser_candidates" + fi for i in $browser_candidates; do init_browser_path $i @@ -157,7 +161,7 @@ case "$browser" in ;; esac ;; - w3m|links|lynx|open) + w3m|links|lynx|open|start) eval "$browser_path" "$@" ;; dillo) @@ -162,6 +162,8 @@ static int handle_alias(int *argcp, const char ***argv) alias_string + 1, alias_command); } count = split_cmdline(alias_string, &new_argv); + if (count < 0) + die("Bad alias.%s string", alias_command); option_count = handle_options(&new_argv, &count, &envchanged); if (envchanged) die("alias '%s' changes environment variables\n" @@ -328,6 +330,7 @@ static void handle_internal_command(int argc, const char **argv) { "prune-packed", cmd_prune_packed, RUN_SETUP }, { "push", cmd_push, RUN_SETUP }, { "read-tree", cmd_read_tree, RUN_SETUP }, + { "receive-pack", cmd_receive_pack }, { "reflog", cmd_reflog, RUN_SETUP }, { "remote", cmd_remote, RUN_SETUP }, { "repo-config", cmd_config }, @@ -386,10 +389,9 @@ static void handle_internal_command(int argc, const char **argv) static void execv_dashed_external(const char **argv) { - struct strbuf cmd; + struct strbuf cmd = STRBUF_INIT; const char *tmp; - strbuf_init(&cmd, 0); strbuf_addf(&cmd, "git-%s", argv[0]); /* diff --git a/git.spec.in b/git.spec.in index c6492e5be2..6733b6f555 100644 --- a/git.spec.in +++ b/git.spec.in @@ -145,6 +145,7 @@ rm -rf $RPM_BUILD_ROOT %files cvs %defattr(-,root,root) %doc Documentation/*git-cvs*.txt +%{_bindir}/git-cvsserver %{_libexecdir}/git-core/*cvs* %{!?_without_docs: %{_mandir}/man1/*cvs*.1*} %{!?_without_docs: %doc Documentation/*git-cvs*.html } @@ -188,6 +189,9 @@ rm -rf $RPM_BUILD_ROOT # No files for you! %changelog +* Fri Sep 12 2008 Quy Tonthat <qtonthat@gmail.com> +- move git-cvsserver to bindir. + * Sun Jun 15 2008 Junio C Hamano <gitster@pobox.com> - Remove curl from Requires list. diff --git a/gitweb/gitweb.css b/gitweb/gitweb.css index 07f5b53788..a01eac814e 100644 --- a/gitweb/gitweb.css +++ b/gitweb/gitweb.css @@ -435,6 +435,10 @@ div.search { right: 12px } +p.projsearch { + text-align: center; +} + td.linenr { text-align: right; } diff --git a/gitweb/gitweb.perl b/gitweb/gitweb.perl index 29e21564c8..c5254afa7f 100755 --- a/gitweb/gitweb.perl +++ b/gitweb/gitweb.perl @@ -27,6 +27,15 @@ our $version = "++GIT_VERSION++"; our $my_url = $cgi->url(); our $my_uri = $cgi->url(-absolute => 1); +# if we're called with PATH_INFO, we have to strip that +# from the URL to find our real URL +# we make $path_info global because it's also used later on +my $path_info = $ENV{"PATH_INFO"}; +if ($path_info) { + $my_url =~ s,\Q$path_info\E$,,; + $my_uri =~ s,\Q$path_info\E$,,; +} + # core git executable to use # this can just be "git" if your webserver has a sensible PATH our $GIT = "++GIT_BINDIR++/git"; @@ -275,6 +284,44 @@ our %feature = ( 'forks' => { 'override' => 0, 'default' => [0]}, + + # Insert custom links to the action bar of all project pages. + # This enables you mainly to link to third-party scripts integrating + # into gitweb; e.g. git-browser for graphical history representation + # or custom web-based repository administration interface. + + # The 'default' value consists of a list of triplets in the form + # (label, link, position) where position is the label after which + # to inster the link and link is a format string where %n expands + # to the project name, %f to the project path within the filesystem, + # %h to the current hash (h gitweb parameter) and %b to the current + # hash base (hb gitweb parameter). + + # To enable system wide have in $GITWEB_CONFIG e.g. + # $feature{'actions'}{'default'} = [('graphiclog', + # '/git-browser/by-commit.html?r=%n', 'summary')]; + # Project specific override is not supported. + 'actions' => { + 'override' => 0, + 'default' => []}, + + # Allow gitweb scan project content tags described in ctags/ + # of project repository, and display the popular Web 2.0-ish + # "tag cloud" near the project list. Note that this is something + # COMPLETELY different from the normal Git tags. + + # gitweb by itself can show existing tags, but it does not handle + # tagging itself; you need an external application for that. + # For an example script, check Girocco's cgi/tagproj.cgi. + # You may want to install the HTML::TagCloud Perl module to get + # a pretty tag cloud instead of just a list of tags. + + # To enable system wide have in $GITWEB_CONFIG + # $feature{'ctags'}{'default'} = ['path_to_tag_script']; + # Project specific override is not supported. + 'ctags' => { + 'override' => 0, + 'default' => [0]}, ); sub gitweb_check_feature { @@ -383,34 +430,155 @@ $projects_list ||= $projectroot; # ====================================================================== # input validation and dispatch -our $action = $cgi->param('a'); + +# input parameters can be collected from a variety of sources (presently, CGI +# and PATH_INFO), so we define an %input_params hash that collects them all +# together during validation: this allows subsequent uses (e.g. href()) to be +# agnostic of the parameter origin + +my %input_params = (); + +# input parameters are stored with the long parameter name as key. This will +# also be used in the href subroutine to convert parameters to their CGI +# equivalent, and since the href() usage is the most frequent one, we store +# the name -> CGI key mapping here, instead of the reverse. +# +# XXX: Warning: If you touch this, check the search form for updating, +# too. + +my @cgi_param_mapping = ( + project => "p", + action => "a", + file_name => "f", + file_parent => "fp", + hash => "h", + hash_parent => "hp", + hash_base => "hb", + hash_parent_base => "hpb", + page => "pg", + order => "o", + searchtext => "s", + searchtype => "st", + snapshot_format => "sf", + extra_options => "opt", + search_use_regexp => "sr", +); +my %cgi_param_mapping = @cgi_param_mapping; + +# we will also need to know the possible actions, for validation +my %actions = ( + "blame" => \&git_blame, + "blobdiff" => \&git_blobdiff, + "blobdiff_plain" => \&git_blobdiff_plain, + "blob" => \&git_blob, + "blob_plain" => \&git_blob_plain, + "commitdiff" => \&git_commitdiff, + "commitdiff_plain" => \&git_commitdiff_plain, + "commit" => \&git_commit, + "forks" => \&git_forks, + "heads" => \&git_heads, + "history" => \&git_history, + "log" => \&git_log, + "rss" => \&git_rss, + "atom" => \&git_atom, + "search" => \&git_search, + "search_help" => \&git_search_help, + "shortlog" => \&git_shortlog, + "summary" => \&git_summary, + "tag" => \&git_tag, + "tags" => \&git_tags, + "tree" => \&git_tree, + "snapshot" => \&git_snapshot, + "object" => \&git_object, + # those below don't need $project + "opml" => \&git_opml, + "project_list" => \&git_project_list, + "project_index" => \&git_project_index, +); + +# finally, we have the hash of allowed extra_options for the commands that +# allow them +my %allowed_options = ( + "--no-merges" => [ qw(rss atom log shortlog history) ], +); + +# fill %input_params with the CGI parameters. All values except for 'opt' +# should be single values, but opt can be an array. We should probably +# build an array of parameters that can be multi-valued, but since for the time +# being it's only this one, we just single it out +while (my ($name, $symbol) = each %cgi_param_mapping) { + if ($symbol eq 'opt') { + $input_params{$name} = [ $cgi->param($symbol) ]; + } else { + $input_params{$name} = $cgi->param($symbol); + } +} + +# now read PATH_INFO and update the parameter list for missing parameters +sub evaluate_path_info { + return if defined $input_params{'project'}; + return if !$path_info; + $path_info =~ s,^/+,,; + return if !$path_info; + + # find which part of PATH_INFO is project + my $project = $path_info; + $project =~ s,/+$,,; + while ($project && !check_head_link("$projectroot/$project")) { + $project =~ s,/*[^/]*$,,; + } + return unless $project; + $input_params{'project'} = $project; + + # do not change any parameters if an action is given using the query string + return if $input_params{'action'}; + $path_info =~ s,^\Q$project\E/*,,; + + my ($refname, $pathname) = split(/:/, $path_info, 2); + if (defined $pathname) { + # we got "project.git/branch:filename" or "project.git/branch:dir/" + # we could use git_get_type(branch:pathname), but it needs $git_dir + $pathname =~ s,^/+,,; + if (!$pathname || substr($pathname, -1) eq "/") { + $input_params{'action'} = "tree"; + $pathname =~ s,/$,,; + } else { + $input_params{'action'} = "blob_plain"; + } + $input_params{'hash_base'} ||= $refname; + $input_params{'file_name'} ||= $pathname; + } elsif (defined $refname) { + # we got "project.git/branch" + $input_params{'action'} = "shortlog"; + $input_params{'hash'} ||= $refname; + } +} +evaluate_path_info(); + +our $action = $input_params{'action'}; if (defined $action) { - if ($action =~ m/[^0-9a-zA-Z\.\-_]/) { + if (!validate_action($action)) { die_error(400, "Invalid action parameter"); } } # parameters which are pathnames -our $project = $cgi->param('p'); +our $project = $input_params{'project'}; if (defined $project) { - if (!validate_pathname($project) || - !(-d "$projectroot/$project") || - !check_head_link("$projectroot/$project") || - ($export_ok && !(-e "$projectroot/$project/$export_ok")) || - ($strict_export && !project_in_list($project))) { + if (!validate_project($project)) { undef $project; die_error(404, "No such project"); } } -our $file_name = $cgi->param('f'); +our $file_name = $input_params{'file_name'}; if (defined $file_name) { if (!validate_pathname($file_name)) { die_error(400, "Invalid file parameter"); } } -our $file_parent = $cgi->param('fp'); +our $file_parent = $input_params{'file_parent'}; if (defined $file_parent) { if (!validate_pathname($file_parent)) { die_error(400, "Invalid file parent parameter"); @@ -418,44 +586,41 @@ if (defined $file_parent) { } # parameters which are refnames -our $hash = $cgi->param('h'); +our $hash = $input_params{'hash'}; if (defined $hash) { if (!validate_refname($hash)) { die_error(400, "Invalid hash parameter"); } } -our $hash_parent = $cgi->param('hp'); +our $hash_parent = $input_params{'hash_parent'}; if (defined $hash_parent) { if (!validate_refname($hash_parent)) { die_error(400, "Invalid hash parent parameter"); } } -our $hash_base = $cgi->param('hb'); +our $hash_base = $input_params{'hash_base'}; if (defined $hash_base) { if (!validate_refname($hash_base)) { die_error(400, "Invalid hash base parameter"); } } -my %allowed_options = ( - "--no-merges" => [ qw(rss atom log shortlog history) ], -); - -our @extra_options = $cgi->param('opt'); -if (defined @extra_options) { - foreach my $opt (@extra_options) { - if (not exists $allowed_options{$opt}) { - die_error(400, "Invalid option parameter"); - } - if (not grep(/^$action$/, @{$allowed_options{$opt}})) { - die_error(400, "Invalid option parameter for this action"); - } +our @extra_options = @{$input_params{'extra_options'}}; +# @extra_options is always defined, since it can only be (currently) set from +# CGI, and $cgi->param() returns the empty array in array context if the param +# is not set +foreach my $opt (@extra_options) { + if (not exists $allowed_options{$opt}) { + die_error(400, "Invalid option parameter"); + } + if (not grep(/^$action$/, @{$allowed_options{$opt}})) { + die_error(400, "Invalid option parameter for this action"); } } -our $hash_parent_base = $cgi->param('hpb'); +our $hash_parent_base = $input_params{'hash_parent_base'}; if (defined $hash_parent_base) { if (!validate_refname($hash_parent_base)) { die_error(400, "Invalid hash parent base parameter"); @@ -463,23 +628,23 @@ if (defined $hash_parent_base) { } # other parameters -our $page = $cgi->param('pg'); +our $page = $input_params{'page'}; if (defined $page) { if ($page =~ m/[^0-9]/) { die_error(400, "Invalid page parameter"); } } -our $searchtype = $cgi->param('st'); +our $searchtype = $input_params{'searchtype'}; if (defined $searchtype) { if ($searchtype =~ m/[^a-z]/) { die_error(400, "Invalid searchtype parameter"); } } -our $search_use_regexp = $cgi->param('sr'); +our $search_use_regexp = $input_params{'search_use_regexp'}; -our $searchtext = $cgi->param('s'); +our $searchtext = $input_params{'searchtext'}; our $search_regexp; if (defined $searchtext) { if (length($searchtext) < 2) { @@ -488,86 +653,11 @@ if (defined $searchtext) { $search_regexp = $search_use_regexp ? $searchtext : quotemeta $searchtext; } -# now read PATH_INFO and use it as alternative to parameters -sub evaluate_path_info { - return if defined $project; - my $path_info = $ENV{"PATH_INFO"}; - return if !$path_info; - $path_info =~ s,^/+,,; - return if !$path_info; - # find which part of PATH_INFO is project - $project = $path_info; - $project =~ s,/+$,,; - while ($project && !check_head_link("$projectroot/$project")) { - $project =~ s,/*[^/]*$,,; - } - # validate project - $project = validate_pathname($project); - if (!$project || - ($export_ok && !-e "$projectroot/$project/$export_ok") || - ($strict_export && !project_in_list($project))) { - undef $project; - return; - } - # do not change any parameters if an action is given using the query string - return if $action; - $path_info =~ s,^\Q$project\E/*,,; - my ($refname, $pathname) = split(/:/, $path_info, 2); - if (defined $pathname) { - # we got "project.git/branch:filename" or "project.git/branch:dir/" - # we could use git_get_type(branch:pathname), but it needs $git_dir - $pathname =~ s,^/+,,; - if (!$pathname || substr($pathname, -1) eq "/") { - $action ||= "tree"; - $pathname =~ s,/$,,; - } else { - $action ||= "blob_plain"; - } - $hash_base ||= validate_refname($refname); - $file_name ||= validate_pathname($pathname); - } elsif (defined $refname) { - # we got "project.git/branch" - $action ||= "shortlog"; - $hash ||= validate_refname($refname); - } -} -evaluate_path_info(); - # path to the current git repository our $git_dir; $git_dir = "$projectroot/$project" if $project; # dispatch -my %actions = ( - "blame" => \&git_blame, - "blobdiff" => \&git_blobdiff, - "blobdiff_plain" => \&git_blobdiff_plain, - "blob" => \&git_blob, - "blob_plain" => \&git_blob_plain, - "commitdiff" => \&git_commitdiff, - "commitdiff_plain" => \&git_commitdiff_plain, - "commit" => \&git_commit, - "forks" => \&git_forks, - "heads" => \&git_heads, - "history" => \&git_history, - "log" => \&git_log, - "rss" => \&git_rss, - "atom" => \&git_atom, - "search" => \&git_search, - "search_help" => \&git_search_help, - "shortlog" => \&git_shortlog, - "summary" => \&git_summary, - "tag" => \&git_tag, - "tags" => \&git_tags, - "tree" => \&git_tree, - "snapshot" => \&git_snapshot, - "object" => \&git_object, - # those below don't need $project - "opml" => \&git_opml, - "project_list" => \&git_project_list, - "project_index" => \&git_project_index, -); - if (!defined $action) { if (defined $hash) { $action = git_get_type($hash); @@ -597,35 +687,12 @@ sub href (%) { # default is to use -absolute url() i.e. $my_uri my $href = $params{-full} ? $my_url : $my_uri; - # XXX: Warning: If you touch this, check the search form for updating, - # too. - - my @mapping = ( - project => "p", - action => "a", - file_name => "f", - file_parent => "fp", - hash => "h", - hash_parent => "hp", - hash_base => "hb", - hash_parent_base => "hpb", - page => "pg", - order => "o", - searchtext => "s", - searchtype => "st", - snapshot_format => "sf", - extra_options => "opt", - search_use_regexp => "sr", - ); - my %mapping = @mapping; - $params{'project'} = $project unless exists $params{'project'}; if ($params{-replay}) { - while (my ($name, $symbol) = each %mapping) { + while (my ($name, $symbol) = each %cgi_param_mapping) { if (!exists $params{$name}) { - # to allow for multivalued params we use arrayref form - $params{$name} = [ $cgi->param($symbol) ]; + $params{$name} = $input_params{$name}; } } } @@ -644,8 +711,8 @@ sub href (%) { # now encode the parameters explicitly my @result = (); - for (my $i = 0; $i < @mapping; $i += 2) { - my ($name, $symbol) = ($mapping[$i], $mapping[$i+1]); + for (my $i = 0; $i < @cgi_param_mapping; $i += 2) { + my ($name, $symbol) = ($cgi_param_mapping[$i], $cgi_param_mapping[$i+1]); if (defined $params{$name}) { if (ref($params{$name}) eq "ARRAY") { foreach my $par (@{$params{$name}}) { @@ -665,6 +732,25 @@ sub href (%) { ## ====================================================================== ## validation, quoting/unquoting and escaping +sub validate_action { + my $input = shift || return undef; + return undef unless exists $actions{$input}; + return $input; +} + +sub validate_project { + my $input = shift || return undef; + if (!validate_pathname($input) || + !(-d "$projectroot/$input") || + !check_head_link("$projectroot/$input") || + ($export_ok && !(-e "$projectroot/$input/$export_ok")) || + ($strict_export && !project_in_list($input))) { + return undef; + } else { + return $input; + } +} + sub validate_pathname { my $input = shift || return undef; @@ -775,7 +861,7 @@ sub quot_cec { ); my $chr = ( (exists $es{$cntrl}) ? $es{$cntrl} - : sprintf('\%03o', ord($cntrl)) ); + : sprintf('\%2x', ord($cntrl)) ); if ($opts{-nohtml}) { return $chr; } else { @@ -1755,6 +1841,67 @@ sub git_get_project_description { return $descr; } +sub git_get_project_ctags { + my $path = shift; + my $ctags = {}; + + $git_dir = "$projectroot/$path"; + foreach (<$git_dir/ctags/*>) { + open CT, $_ or next; + my $val = <CT>; + chomp $val; + close CT; + my $ctag = $_; $ctag =~ s#.*/##; + $ctags->{$ctag} = $val; + } + $ctags; +} + +sub git_populate_project_tagcloud { + my $ctags = shift; + + # First, merge different-cased tags; tags vote on casing + my %ctags_lc; + foreach (keys %$ctags) { + $ctags_lc{lc $_}->{count} += $ctags->{$_}; + if (not $ctags_lc{lc $_}->{topcount} + or $ctags_lc{lc $_}->{topcount} < $ctags->{$_}) { + $ctags_lc{lc $_}->{topcount} = $ctags->{$_}; + $ctags_lc{lc $_}->{topname} = $_; + } + } + + my $cloud; + if (eval { require HTML::TagCloud; 1; }) { + $cloud = HTML::TagCloud->new; + foreach (sort keys %ctags_lc) { + # Pad the title with spaces so that the cloud looks + # less crammed. + my $title = $ctags_lc{$_}->{topname}; + $title =~ s/ / /g; + $title =~ s/^/ /g; + $title =~ s/$/ /g; + $cloud->add($title, $home_link."?by_tag=".$_, $ctags_lc{$_}->{count}); + } + } else { + $cloud = \%ctags_lc; + } + $cloud; +} + +sub git_show_project_tagcloud { + my ($cloud, $count) = @_; + print STDERR ref($cloud)."..\n"; + if (ref $cloud eq 'HTML::TagCloud') { + return $cloud->html_and_css($count); + } else { + my @tags = sort { $cloud->{$a}->{count} <=> $cloud->{$b}->{count} } keys %$cloud; + return '<p align="center">' . join (', ', map { + "<a href=\"$home_link?by_tag=$_\">$cloud->{$_}->{topname}</a>" + } splice(@tags, 0, $count)) . '</p>'; + } +} + sub git_get_project_url_list { my $path = shift; @@ -1803,9 +1950,7 @@ sub git_get_projects_list { my $subdir = substr($File::Find::name, $pfxlen + 1); # we check related file in $projectroot - if ($check_forks and $subdir =~ m#/.#) { - $File::Find::prune = 1; - } elsif (check_export_ok("$projectroot/$filter/$subdir")) { + if (check_export_ok("$projectroot/$filter/$subdir")) { push @list, { path => ($filter ? "$filter/" : '') . $subdir }; $File::Find::prune = 1; } @@ -2123,7 +2268,7 @@ sub parse_commit_text { last; } } - if ($co{'title'} eq "") { + if (! defined $co{'title'} || $co{'title'} eq "") { $co{'title'} = $co{'title_short'} = '(no commit message)'; } # remove added spaces @@ -2757,13 +2902,26 @@ sub git_print_page_nav { } } } + $arg{'tree'}{'hash'} = $treehead if defined $treehead; $arg{'tree'}{'hash_base'} = $treebase if defined $treebase; + my @actions = gitweb_check_feature('actions'); + while (@actions) { + my ($label, $link, $pos) = (shift(@actions), shift(@actions), shift(@actions)); + @navs = map { $_ eq $pos ? ($_, $label) : $_ } @navs; + # munch munch + $link =~ s#%n#$project#g; + $link =~ s#%f#$git_dir#g; + $treehead ? $link =~ s#%h#$treehead#g : $link =~ s#%h##g; + $treebase ? $link =~ s#%b#$treebase#g : $link =~ s#%b##g; + $arg{$label}{'_href'} = $link; + } + print "<div class=\"page_nav\">\n" . (join " | ", map { $_ eq $current ? - $_ : $cgi->a({-href => href(%{$arg{$_}})}, "$_") + $_ : $cgi->a({-href => ($arg{$_}{_href} ? $arg{$_}{_href} : href(%{$arg{$_}}))}, "$_") } @navs); print "<br/>\n$extra<br/>\n" . "</div>\n"; @@ -3573,6 +3731,7 @@ sub fill_project_list_info { my ($projlist, $check_forks) = @_; my @projects; + my $show_ctags = gitweb_check_feature('ctags'); PROJECT: foreach my $pr (@$projlist) { my (@activity) = git_get_last_activity($pr->{'path'}); @@ -3599,25 +3758,20 @@ sub fill_project_list_info { $pr->{'forks'} = 0; } } + $show_ctags and $pr->{'ctags'} = git_get_project_ctags($pr->{'path'}); push @projects, $pr; } return @projects; } -# print 'sort by' <th> element, either sorting by $key if $name eq $order -# (changing $list), or generating 'sort by $name' replay link otherwise +# print 'sort by' <th> element, generating 'sort by $name' replay link +# if that order is not selected sub print_sort_th { - my ($str_sort, $name, $order, $key, $header, $list) = @_; - $key ||= $name; + my ($name, $order, $header) = @_; $header ||= ucfirst($name); if ($order eq $name) { - if ($str_sort) { - @$list = sort {$a->{$key} cmp $b->{$key}} @$list; - } else { - @$list = sort {$a->{$key} <=> $b->{$key}} @$list; - } print "<th>$header</th>\n"; } else { print "<th>" . @@ -3627,15 +3781,8 @@ sub print_sort_th { } } -sub print_sort_th_str { - print_sort_th(1, @_); -} - -sub print_sort_th_num { - print_sort_th(0, @_); -} - sub git_project_list_body { + # actually uses global variable $project my ($projlist, $order, $from, $to, $extra, $no_header) = @_; my ($check_forks) = gitweb_check_feature('forks'); @@ -3645,26 +3792,60 @@ sub git_project_list_body { $from = 0 unless defined $from; $to = $#projects if (!defined $to || $#projects < $to); + my %order_info = ( + project => { key => 'path', type => 'str' }, + descr => { key => 'descr_long', type => 'str' }, + owner => { key => 'owner', type => 'str' }, + age => { key => 'age', type => 'num' } + ); + my $oi = $order_info{$order}; + if ($oi->{'type'} eq 'str') { + @projects = sort {$a->{$oi->{'key'}} cmp $b->{$oi->{'key'}}} @projects; + } else { + @projects = sort {$a->{$oi->{'key'}} <=> $b->{$oi->{'key'}}} @projects; + } + + my $show_ctags = gitweb_check_feature('ctags'); + if ($show_ctags) { + my %ctags; + foreach my $p (@projects) { + foreach my $ct (keys %{$p->{'ctags'}}) { + $ctags{$ct} += $p->{'ctags'}->{$ct}; + } + } + my $cloud = git_populate_project_tagcloud(\%ctags); + print git_show_project_tagcloud($cloud, 64); + } + print "<table class=\"project_list\">\n"; unless ($no_header) { print "<tr>\n"; if ($check_forks) { print "<th></th>\n"; } - print_sort_th_str('project', $order, 'path', - 'Project', \@projects); - print_sort_th_str('descr', $order, 'descr_long', - 'Description', \@projects); - print_sort_th_str('owner', $order, 'owner', - 'Owner', \@projects); - print_sort_th_num('age', $order, 'age', - 'Last Change', \@projects); + print_sort_th('project', $order, 'Project'); + print_sort_th('descr', $order, 'Description'); + print_sort_th('owner', $order, 'Owner'); + print_sort_th('age', $order, 'Last Change'); print "<th></th>\n" . # for links "</tr>\n"; } my $alternate = 1; + my $tagfilter = $cgi->param('by_tag'); for (my $i = $from; $i <= $to; $i++) { my $pr = $projects[$i]; + + next if $tagfilter and $show_ctags and not grep { lc $_ eq lc $tagfilter } keys %{$pr->{'ctags'}}; + next if $searchtext and not $pr->{'path'} =~ /$searchtext/ + and not $pr->{'descr_long'} =~ /$searchtext/; + # Weed out forks or non-matching entries of search + if ($check_forks) { + my $forkbase = $project; $forkbase ||= ''; $forkbase =~ s#\.git$#/#; + $forkbase="^$forkbase" if $forkbase; + next if not $searchtext and not $tagfilter and $show_ctags + and $pr->{'path'} =~ m#$forkbase.*/.*#; # regexp-safe + } + if ($alternate) { print "<tr class=\"dark\">\n"; } else { @@ -3981,7 +4162,7 @@ sub git_search_grep_body { ## actions sub git_project_list { - my $order = $cgi->param('o'); + my $order = $input_params{'order'}; if (defined $order && $order !~ m/none|project|descr|owner|age/) { die_error(400, "Unknown order parameter"); } @@ -3999,12 +4180,17 @@ sub git_project_list { close $fd; print "</div>\n"; } + print $cgi->startform(-method => "get") . + "<p class=\"projsearch\">Search:\n" . + $cgi->textfield(-name => "s", -value => $searchtext) . "\n" . + "</p>" . + $cgi->end_form() . "\n"; git_project_list_body(\@list, $order); git_footer_html(); } sub git_forks { - my $order = $cgi->param('o'); + my $order = $input_params{'order'}; if (defined $order && $order !~ m/none|project|descr|owner|age/) { die_error(400, "Unknown order parameter"); } @@ -4070,10 +4256,10 @@ sub git_summary { print "<div class=\"title\"> </div>\n"; print "<table class=\"projects_list\">\n" . - "<tr><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" . - "<tr><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n"; + "<tr id=\"metadata_desc\"><td>description</td><td>" . esc_html($descr) . "</td></tr>\n" . + "<tr id=\"metadata_owner\"><td>owner</td><td>" . esc_html($owner) . "</td></tr>\n"; if (defined $cd{'rfc2822'}) { - print "<tr><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n"; + print "<tr id=\"metadata_lchange\"><td>last change</td><td>$cd{'rfc2822'}</td></tr>\n"; } # use per project git URL list in $projectroot/$project/cloneurl @@ -4083,9 +4269,23 @@ sub git_summary { @url_list = map { "$_/$project" } @git_base_url_list unless @url_list; foreach my $git_url (@url_list) { next unless $git_url; - print "<tr><td>$url_tag</td><td>$git_url</td></tr>\n"; + print "<tr class=\"metadata_url\"><td>$url_tag</td><td>$git_url</td></tr>\n"; $url_tag = ""; } + + # Tag cloud + my $show_ctags = (gitweb_check_feature('ctags'))[0]; + if ($show_ctags) { + my $ctags = git_get_project_ctags($project); + my $cloud = git_populate_project_tagcloud($ctags); + print "<tr id=\"metadata_ctags\"><td>Content tags:<br />"; + print "</td>\n<td>" unless %$ctags; + print "<form action=\"$show_ctags\" method=\"post\"><input type=\"hidden\" name=\"p\" value=\"$project\" />Add: <input type=\"text\" name=\"t\" size=\"8\" /></form>"; + print "</td>\n<td>" if %$ctags; + print git_show_project_tagcloud($cloud, 48); + print "</td></tr>"; + } + print "</table>\n"; if (-s "$projectroot/$project/README.html") { @@ -4124,10 +4324,10 @@ sub git_summary { if (@forklist) { git_print_header_div('forks'); - git_project_list_body(\@forklist, undef, 0, 15, + git_project_list_body(\@forklist, 'age', 0, 15, $#forklist <= 15 ? undef : $cgi->a({-href => href(action=>"forks")}, "..."), - 'noheader'); + 'no_header'); } git_footer_html(); @@ -4445,6 +4645,7 @@ sub git_tree { $hash = $hash_base; } } + die_error(404, "No such tree") unless defined($hash); $/ = "\0"; open my $fd, "-|", git_cmd(), "ls-tree", '-z', $hash or die_error(500, "Open git-ls-tree failed"); @@ -4485,8 +4686,8 @@ sub git_tree { if ($basedir ne '' && substr($basedir, -1) ne '/') { $basedir .= '/'; } + git_print_page_path($file_name, 'tree', $hash_base); } - git_print_page_path($file_name, 'tree', $hash_base); print "<div class=\"page_body\">\n"; print "<table class=\"tree\">\n"; my $alternate = 1; @@ -4537,7 +4738,7 @@ sub git_snapshot { my @supported_fmts = gitweb_check_feature('snapshot'); @supported_fmts = filter_snapshot_fmts(@supported_fmts); - my $format = $cgi->param('sf'); + my $format = $input_params{'snapshot_format'}; if (!@supported_fmts) { die_error(403, "Snapshots not allowed"); } @@ -5498,7 +5699,11 @@ sub git_shortlog { } my $refs = git_get_references(); - my @commitlist = parse_commits($hash, 101, (100 * $page)); + my $commit_hash = $hash; + if (defined $hash_parent) { + $commit_hash = "$hash_parent..$hash"; + } + my @commitlist = parse_commits($commit_hash, 101, (100 * $page)); my $paging_nav = format_paging_nav('shortlog', $hash, $head, $page, $#commitlist >= 100); my $next_link = ''; @@ -4,6 +4,43 @@ #include "diff.h" #include "revision.h" +/* Internal API */ + +/* + * Output the next line for a graph. + * This formats the next graph line into the specified strbuf. It is not + * terminated with a newline. + * + * Returns 1 if the line includes the current commit, and 0 otherwise. + * graph_next_line() will return 1 exactly once for each time + * graph_update() is called. + */ +static int graph_next_line(struct git_graph *graph, struct strbuf *sb); + +/* + * Output a padding line in the graph. + * This is similar to graph_next_line(). However, it is guaranteed to + * never print the current commit line. Instead, if the commit line is + * next, it will simply output a line of vertical padding, extending the + * branch lines downwards, but leaving them otherwise unchanged. + */ +static void graph_padding_line(struct git_graph *graph, struct strbuf *sb); + +/* + * Print a strbuf to stdout. If the graph is non-NULL, all lines but the + * first will be prefixed with the graph output. + * + * If the strbuf ends with a newline, the output will end after this + * newline. A new graph line will not be printed after the final newline. + * If the strbuf is empty, no output will be printed. + * + * Since the first line will not include the graph ouput, the caller is + * responsible for printing this line's graph (perhaps via + * graph_show_commit() or graph_show_oneline()) before calling + * graph_show_strbuf(). + */ +static void graph_show_strbuf(struct git_graph *graph, struct strbuf const *sb); + /* * TODO: * - Add colors to the graph. @@ -180,14 +217,6 @@ struct git_graph *graph_init(struct rev_info *opt) return graph; } -void graph_release(struct git_graph *graph) -{ - free(graph->columns); - free(graph->new_columns); - free(graph->mapping); - free(graph); -} - static void graph_update_state(struct git_graph *graph, enum graph_state s) { graph->prev_state = graph->state; @@ -685,7 +714,7 @@ static void graph_output_commit_char(struct git_graph *graph, struct strbuf *sb) strbuf_addch(sb, '*'); } -void graph_output_commit_line(struct git_graph *graph, struct strbuf *sb) +static void graph_output_commit_line(struct git_graph *graph, struct strbuf *sb) { int seen_this = 0; int i, j; @@ -760,7 +789,7 @@ void graph_output_commit_line(struct git_graph *graph, struct strbuf *sb) graph_update_state(graph, GRAPH_COLLAPSING); } -void graph_output_post_merge_line(struct git_graph *graph, struct strbuf *sb) +static void graph_output_post_merge_line(struct git_graph *graph, struct strbuf *sb) { int seen_this = 0; int i, j; @@ -801,7 +830,7 @@ void graph_output_post_merge_line(struct git_graph *graph, struct strbuf *sb) graph_update_state(graph, GRAPH_COLLAPSING); } -void graph_output_collapsing_line(struct git_graph *graph, struct strbuf *sb) +static void graph_output_collapsing_line(struct git_graph *graph, struct strbuf *sb) { int i; int *tmp_mapping; @@ -906,7 +935,7 @@ void graph_output_collapsing_line(struct git_graph *graph, struct strbuf *sb) graph_update_state(graph, GRAPH_PADDING); } -int graph_next_line(struct git_graph *graph, struct strbuf *sb) +static int graph_next_line(struct git_graph *graph, struct strbuf *sb) { switch (graph->state) { case GRAPH_PADDING: @@ -933,7 +962,7 @@ int graph_next_line(struct git_graph *graph, struct strbuf *sb) return 0; } -void graph_padding_line(struct git_graph *graph, struct strbuf *sb) +static void graph_padding_line(struct git_graph *graph, struct strbuf *sb) { int i, j; @@ -981,14 +1010,12 @@ int graph_is_commit_finished(struct git_graph const *graph) void graph_show_commit(struct git_graph *graph) { - struct strbuf msgbuf; + struct strbuf msgbuf = STRBUF_INIT; int shown_commit_line = 0; if (!graph) return; - strbuf_init(&msgbuf, 0); - while (!shown_commit_line) { shown_commit_line = graph_next_line(graph, &msgbuf); fwrite(msgbuf.buf, sizeof(char), msgbuf.len, stdout); @@ -1002,12 +1029,11 @@ void graph_show_commit(struct git_graph *graph) void graph_show_oneline(struct git_graph *graph) { - struct strbuf msgbuf; + struct strbuf msgbuf = STRBUF_INIT; if (!graph) return; - strbuf_init(&msgbuf, 0); graph_next_line(graph, &msgbuf); fwrite(msgbuf.buf, sizeof(char), msgbuf.len, stdout); strbuf_release(&msgbuf); @@ -1015,12 +1041,11 @@ void graph_show_oneline(struct git_graph *graph) void graph_show_padding(struct git_graph *graph) { - struct strbuf msgbuf; + struct strbuf msgbuf = STRBUF_INIT; if (!graph) return; - strbuf_init(&msgbuf, 0); graph_padding_line(graph, &msgbuf); fwrite(msgbuf.buf, sizeof(char), msgbuf.len, stdout); strbuf_release(&msgbuf); @@ -1028,7 +1053,7 @@ void graph_show_padding(struct git_graph *graph) int graph_show_remainder(struct git_graph *graph) { - struct strbuf msgbuf; + struct strbuf msgbuf = STRBUF_INIT; int shown = 0; if (!graph) @@ -1037,7 +1062,6 @@ int graph_show_remainder(struct git_graph *graph) if (graph_is_commit_finished(graph)) return 0; - strbuf_init(&msgbuf, 0); for (;;) { graph_next_line(graph, &msgbuf); fwrite(msgbuf.buf, sizeof(char), msgbuf.len, stdout); @@ -1055,7 +1079,7 @@ int graph_show_remainder(struct git_graph *graph) } -void graph_show_strbuf(struct git_graph *graph, struct strbuf const *sb) +static void graph_show_strbuf(struct git_graph *graph, struct strbuf const *sb) { char *p; @@ -11,11 +11,6 @@ struct git_graph; struct git_graph *graph_init(struct rev_info *opt); /* - * Destroy a struct git_graph and free associated memory. - */ -void graph_release(struct git_graph *graph); - -/* * Update a git_graph with a new commit. * This will cause the graph to begin outputting lines for the new commit * the next time graph_next_line() is called. @@ -27,26 +22,6 @@ void graph_release(struct git_graph *graph); void graph_update(struct git_graph *graph, struct commit *commit); /* - * Output the next line for a graph. - * This formats the next graph line into the specified strbuf. It is not - * terminated with a newline. - * - * Returns 1 if the line includes the current commit, and 0 otherwise. - * graph_next_line() will return 1 exactly once for each time - * graph_update() is called. - */ -int graph_next_line(struct git_graph *graph, struct strbuf *sb); - -/* - * Output a padding line in the graph. - * This is similar to graph_next_line(). However, it is guaranteed to - * never print the current commit line. Instead, if the commit line is - * next, it will simply output a line of vertical padding, extending the - * branch lines downwards, but leaving them otherwise unchanged. - */ -void graph_padding_line(struct git_graph *graph, struct strbuf *sb); - -/* * Determine if a graph has finished outputting lines for the current * commit. * @@ -90,21 +65,6 @@ void graph_show_padding(struct git_graph *graph); int graph_show_remainder(struct git_graph *graph); /* - * Print a strbuf to stdout. If the graph is non-NULL, all lines but the - * first will be prefixed with the graph output. - * - * If the strbuf ends with a newline, the output will end after this - * newline. A new graph line will not be printed after the final newline. - * If the strbuf is empty, no output will be printed. - * - * Since the first line will not include the graph ouput, the caller is - * responsible for printing this line's graph (perhaps via - * graph_show_commit() or graph_show_oneline()) before calling - * graph_show_strbuf(). - */ -void graph_show_strbuf(struct git_graph *graph, struct strbuf const *sb); - -/* * Print a commit message strbuf and the remainder of the graph to stdout. * * This is similar to graph_show_strbuf(), but it always prints the @@ -239,6 +239,8 @@ static int word_char(char ch) static void show_line(struct grep_opt *opt, const char *bol, const char *eol, const char *name, unsigned lno, char sign) { + if (opt->null_following_name) + sign = '\0'; if (opt->pathname) printf("%s%c", name, sign); if (opt->linenum) @@ -246,6 +248,11 @@ static void show_line(struct grep_opt *opt, const char *bol, const char *eol, printf("%.*s\n", (int)(eol-bol), bol); } +static void show_name(struct grep_opt *opt, const char *name) +{ + printf("%s%c", name, opt->null_following_name ? '\0' : '\n'); +} + static int fixmatch(const char *pattern, char *line, regmatch_t *match) { char *hit = strstr(line, pattern); @@ -489,7 +496,7 @@ static int grep_buffer_1(struct grep_opt *opt, const char *name, return 1; } if (opt->name_only) { - printf("%s\n", name); + show_name(opt, name); return 1; } /* Hit at this line. If we haven't shown the @@ -555,7 +562,7 @@ static int grep_buffer_1(struct grep_opt *opt, const char *name, return 0; if (opt->unmatch_name_only) { /* We did not see any hit, so we want to show this */ - printf("%s\n", name); + show_name(opt, name); return 1; } @@ -565,7 +572,8 @@ static int grep_buffer_1(struct grep_opt *opt, const char *name, * make it another option? For now suppress them. */ if (opt->count && count) - printf("%s:%u\n", name, count); + printf("%s%c%u\n", name, + opt->null_following_name ? '\0' : ':', count); return !!last_hit; } @@ -74,6 +74,7 @@ struct grep_opt { unsigned extended:1; unsigned relative:1; unsigned pathname:1; + unsigned null_following_name:1; int regflags; unsigned pre_context; unsigned post_context; diff --git a/hash-object.c b/hash-object.c index a4d127cf78..20937ff94c 100644 --- a/hash-object.c +++ b/hash-object.c @@ -34,10 +34,8 @@ static void hash_object(const char *path, const char *type, int write_object, static void hash_stdin_paths(const char *type, int write_objects) { - struct strbuf buf, nbuf; + struct strbuf buf = STRBUF_INIT, nbuf = STRBUF_INIT; - strbuf_init(&buf, 0); - strbuf_init(&nbuf, 0); while (strbuf_getline(&buf, stdin, '\n') != EOF) { if (buf.buf[0] == '"') { strbuf_reset(&nbuf); @@ -204,8 +204,8 @@ void load_command_list(const char *prefix, while (1) { if ((colon = strchr(path, PATH_SEP))) *colon = 0; - - list_commands_in_dir(other_cmds, path, prefix); + if (!exec_path || strcmp(path, exec_path)) + list_commands_in_dir(other_cmds, path, prefix); if (!colon) break; @@ -262,11 +262,15 @@ int is_in_cmdlist(struct cmdnames *c, const char *s) } static int autocorrect; +static struct cmdnames aliases; static int git_unknown_cmd_config(const char *var, const char *value, void *cb) { if (!strcmp(var, "help.autocorrect")) autocorrect = git_config_int(var,value); + /* Also use aliases for command lookup */ + if (!prefixcmp(var, "alias.")) + add_cmdname(&aliases, var + 6, strlen(var + 6)); return git_default_config(var, value, cb); } @@ -280,6 +284,18 @@ static int levenshtein_compare(const void *p1, const void *p2) return l1 != l2 ? l1 - l2 : strcmp(s1, s2); } +static void add_cmd_list(struct cmdnames *cmds, struct cmdnames *old) +{ + int i; + ALLOC_GROW(cmds->names, cmds->cnt + old->cnt, cmds->alloc); + + for (i = 0; i < old->cnt; i++) + cmds->names[cmds->cnt++] = old->names[i]; + free(old->names); + old->cnt = 0; + old->names = NULL; +} + const char *help_unknown_cmd(const char *cmd) { int i, n, best_similarity = 0; @@ -287,17 +303,17 @@ const char *help_unknown_cmd(const char *cmd) memset(&main_cmds, 0, sizeof(main_cmds)); memset(&other_cmds, 0, sizeof(main_cmds)); + memset(&aliases, 0, sizeof(aliases)); git_config(git_unknown_cmd_config, NULL); load_command_list("git-", &main_cmds, &other_cmds); - ALLOC_GROW(main_cmds.names, main_cmds.cnt + other_cmds.cnt, - main_cmds.alloc); - memcpy(main_cmds.names + main_cmds.cnt, other_cmds.names, - other_cmds.cnt * sizeof(other_cmds.names[0])); - main_cmds.cnt += other_cmds.cnt; - free(other_cmds.names); + add_cmd_list(&main_cmds, &aliases); + add_cmd_list(&main_cmds, &other_cmds); + qsort(main_cmds.names, main_cmds.cnt, + sizeof(main_cmds.names), cmdname_compare); + uniq(&main_cmds); /* This reuses cmdname->len for similarity index */ for (i = 0; i < main_cmds.cnt; ++i) diff --git a/http-push.c b/http-push.c index c9dd9a1f64..42f4d78e54 100644 --- a/http-push.c +++ b/http-push.c @@ -126,7 +126,7 @@ struct transfer_request char errorstr[CURL_ERROR_SIZE]; long http_code; unsigned char real_sha1[20]; - SHA_CTX c; + git_SHA_CTX c; z_stream stream; int zret; int rename; @@ -209,7 +209,7 @@ static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb, request->stream.next_out = expn; request->stream.avail_out = sizeof(expn); request->zret = inflate(&request->stream, Z_SYNC_FLUSH); - SHA1_Update(&request->c, expn, + git_SHA1_Update(&request->c, expn, sizeof(expn) - request->stream.avail_out); } while (request->stream.avail_in && request->zret == Z_OK); data_received++; @@ -270,7 +270,7 @@ static void start_fetch_loose(struct transfer_request *request) inflateInit(&request->stream); - SHA1_Init(&request->c); + git_SHA1_Init(&request->c); url = xmalloc(strlen(remote->url) + 50); request->url = xmalloc(strlen(remote->url) + 50); @@ -310,7 +310,7 @@ static void start_fetch_loose(struct transfer_request *request) if (prev_read == -1) { memset(&request->stream, 0, sizeof(request->stream)); inflateInit(&request->stream); - SHA1_Init(&request->c); + git_SHA1_Init(&request->c); if (prev_posn>0) { prev_posn = 0; lseek(request->local_fileno, 0, SEEK_SET); @@ -742,7 +742,7 @@ static void finish_request(struct transfer_request *request) fprintf(stderr, "Warning: requested range invalid; we may already have all the data.\n"); inflateEnd(&request->stream); - SHA1_Final(request->real_sha1, &request->c); + git_SHA1_Final(request->real_sha1, &request->c); if (request->zret != Z_STREAM_END) { unlink(request->tmpfile); } else if (hashcmp(request->obj->sha1, request->real_sha1)) { diff --git a/http-walker.c b/http-walker.c index 9dc6b27b45..7271c7d19d 100644 --- a/http-walker.c +++ b/http-walker.c @@ -36,7 +36,7 @@ struct object_request char errorstr[CURL_ERROR_SIZE]; long http_code; unsigned char real_sha1[20]; - SHA_CTX c; + git_SHA_CTX c; z_stream stream; int zret; int rename; @@ -83,7 +83,7 @@ static size_t fwrite_sha1_file(void *ptr, size_t eltsize, size_t nmemb, obj_req->stream.next_out = expn; obj_req->stream.avail_out = sizeof(expn); obj_req->zret = inflate(&obj_req->stream, Z_SYNC_FLUSH); - SHA1_Update(&obj_req->c, expn, + git_SHA1_Update(&obj_req->c, expn, sizeof(expn) - obj_req->stream.avail_out); } while (obj_req->stream.avail_in && obj_req->zret == Z_OK); data_received++; @@ -144,7 +144,7 @@ static void start_object_request(struct walker *walker, inflateInit(&obj_req->stream); - SHA1_Init(&obj_req->c); + git_SHA1_Init(&obj_req->c); url = xmalloc(strlen(obj_req->repo->base) + 51); obj_req->url = xmalloc(strlen(obj_req->repo->base) + 51); @@ -184,7 +184,7 @@ static void start_object_request(struct walker *walker, if (prev_read == -1) { memset(&obj_req->stream, 0, sizeof(obj_req->stream)); inflateInit(&obj_req->stream); - SHA1_Init(&obj_req->c); + git_SHA1_Init(&obj_req->c); if (prev_posn>0) { prev_posn = 0; lseek(obj_req->local, 0, SEEK_SET); @@ -244,7 +244,7 @@ static void finish_object_request(struct object_request *obj_req) } inflateEnd(&obj_req->stream); - SHA1_Final(obj_req->real_sha1, &obj_req->c); + git_SHA1_Final(obj_req->real_sha1, &obj_req->c); if (obj_req->zret != Z_STREAM_END) { unlink(obj_req->tmpfile); return; @@ -165,7 +165,16 @@ static CURL* get_curl_handle(void) { CURL* result = curl_easy_init(); - curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, curl_ssl_verify); + if (!curl_ssl_verify) { + curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 0); + curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 0); + } else { + /* Verify authenticity of the peer's certificate */ + curl_easy_setopt(result, CURLOPT_SSL_VERIFYPEER, 1); + /* The name in the cert must match whom we tried to connect */ + curl_easy_setopt(result, CURLOPT_SSL_VERIFYHOST, 2); + } + #if LIBCURL_VERSION_NUM >= 0x070907 curl_easy_setopt(result, CURLOPT_NETRC, CURL_NETRC_OPTIONAL); #endif diff --git a/imap-send.c b/imap-send.c index af7e08c094..3703dbd1af 100644 --- a/imap-send.c +++ b/imap-send.c @@ -1266,10 +1266,9 @@ static int imap_store_msg(struct store *gctx, struct msg_data *data, int *uid) static int read_message(FILE *f, struct msg_data *msg) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; memset(msg, 0, sizeof(*msg)); - strbuf_init(&buf, 0); do { if (strbuf_fread(&buf, CHUNKSIZE, f) <= 0) diff --git a/index-pack.c b/index-pack.c index a6e91fe3ba..aec11cb940 100644 --- a/index-pack.c +++ b/index-pack.c @@ -67,7 +67,7 @@ static struct progress *progress; static unsigned char input_buffer[4096]; static unsigned int input_offset, input_len; static off_t consumed_bytes; -static SHA_CTX input_ctx; +static git_SHA_CTX input_ctx; static uint32_t input_crc32; static int input_fd, output_fd, pack_fd; @@ -119,7 +119,7 @@ static void flush(void) if (input_offset) { if (output_fd >= 0) write_or_die(output_fd, input_buffer, input_offset); - SHA1_Update(&input_ctx, input_buffer, input_offset); + git_SHA1_Update(&input_ctx, input_buffer, input_offset); memmove(input_buffer, input_buffer + input_offset, input_len); input_offset = 0; } @@ -172,7 +172,7 @@ static char *open_pack_file(char *pack_name) if (!pack_name) { static char tmpfile[PATH_MAX]; snprintf(tmpfile, sizeof(tmpfile), - "%s/tmp_pack_XXXXXX", get_object_directory()); + "%s/pack/tmp_pack_XXXXXX", get_object_directory()); output_fd = xmkstemp(tmpfile); pack_name = xstrdup(tmpfile); } else @@ -188,7 +188,7 @@ static char *open_pack_file(char *pack_name) output_fd = -1; pack_fd = input_fd; } - SHA1_Init(&input_ctx); + git_SHA1_Init(&input_ctx); return pack_name; } @@ -365,8 +365,11 @@ static void *get_data_from_pack(struct object_entry *obj) data = src; do { ssize_t n = pread(pack_fd, data + rdy, len - rdy, from + rdy); - if (n <= 0) + if (n < 0) die("cannot pread pack file: %s", strerror(errno)); + if (!n) + die("premature end of pack file, %lu bytes missing", + len - rdy); rdy += n; } while (rdy < len); data = xmalloc(obj->size); @@ -588,7 +591,7 @@ static void parse_pack_objects(unsigned char *sha1) /* Check pack integrity */ flush(); - SHA1_Final(sha1, &input_ctx); + git_SHA1_Final(sha1, &input_ctx); if (hashcmp(fill(20), sha1)) die("pack is corrupted (SHA1 mismatch)"); use(20); @@ -704,6 +707,7 @@ static struct object_entry *append_obj_to_pack(struct sha1file *f, obj[1].idx.offset = obj[0].idx.offset + n; obj[1].idx.offset += write_compressed(f, buf, size); obj[0].idx.crc32 = crc32_end(f); + sha1flush(f); hashcpy(obj->idx.sha1, sha1); return obj; } @@ -786,7 +790,6 @@ static void final(const char *final_pack_name, const char *curr_pack_name, err = close(output_fd); if (err) die("error while closing pack file: %s", strerror(errno)); - chmod(curr_pack_name, 0444); } if (keep_msg) { @@ -820,8 +823,9 @@ static void final(const char *final_pack_name, const char *curr_pack_name, if (move_temp_to_file(curr_pack_name, final_pack_name)) die("cannot store pack file"); } + if (from_stdin) + chmod(final_pack_name, 0444); - chmod(curr_index_name, 0444); if (final_index_name != curr_index_name) { if (!final_index_name) { snprintf(name, sizeof(name), "%s/pack/pack-%s.idx", @@ -831,6 +835,7 @@ static void final(const char *final_pack_name, const char *curr_pack_name, if (move_temp_to_file(curr_index_name, final_index_name)) die("cannot store index file"); } + chmod(final_index_name, 0444); if (!from_stdin) { printf("%s\n", sha1_to_hex(sha1)); diff --git a/ll-merge.c b/ll-merge.c index 9837c842a3..4a716146f6 100644 --- a/ll-merge.c +++ b/ll-merge.c @@ -63,6 +63,7 @@ static int ll_xdl_merge(const struct ll_merge_driver *drv_unused, int virtual_ancestor) { xpparam_t xpp; + int style = 0; if (buffer_is_binary(orig->ptr, orig->size) || buffer_is_binary(src1->ptr, src1->size) || @@ -77,10 +78,12 @@ static int ll_xdl_merge(const struct ll_merge_driver *drv_unused, } memset(&xpp, 0, sizeof(xpp)); + if (git_xmerge_style >= 0) + style = git_xmerge_style; return xdl_merge(orig, src1, name1, src2, name2, - &xpp, XDL_MERGE_ZEALOUS, + &xpp, XDL_MERGE_ZEALOUS | style, result); } @@ -95,10 +98,15 @@ static int ll_union_merge(const struct ll_merge_driver *drv_unused, char *src, *dst; long size; const int marker_size = 7; - - int status = ll_xdl_merge(drv_unused, result, path_unused, - orig, src1, NULL, src2, NULL, - virtual_ancestor); + int status, saved_style; + + /* We have to force the RCS "merge" style */ + saved_style = git_xmerge_style; + git_xmerge_style = 0; + status = ll_xdl_merge(drv_unused, result, path_unused, + orig, src1, NULL, src2, NULL, + virtual_ancestor); + git_xmerge_style = saved_style; if (status <= 0) return status; size = result->size; diff --git a/log-tree.c b/log-tree.c index 30cd5bb228..cec3c06136 100644 --- a/log-tree.c +++ b/log-tree.c @@ -1,12 +1,48 @@ #include "cache.h" #include "diff.h" #include "commit.h" +#include "tag.h" #include "graph.h" #include "log-tree.h" #include "reflog-walk.h" +#include "refs.h" struct decoration name_decoration = { "object names" }; +static void add_name_decoration(const char *prefix, const char *name, struct object *obj) +{ + int plen = strlen(prefix); + int nlen = strlen(name); + struct name_decoration *res = xmalloc(sizeof(struct name_decoration) + plen + nlen); + memcpy(res->name, prefix, plen); + memcpy(res->name + plen, name, nlen + 1); + res->next = add_decoration(&name_decoration, obj, res); +} + +static int add_ref_decoration(const char *refname, const unsigned char *sha1, int flags, void *cb_data) +{ + struct object *obj = parse_object(sha1); + if (!obj) + return 0; + add_name_decoration("", refname, obj); + while (obj->type == OBJ_TAG) { + obj = ((struct tag *)obj)->tagged; + if (!obj) + break; + add_name_decoration("tag: ", refname, obj); + } + return 0; +} + +void load_ref_decorations(void) +{ + static int loaded; + if (!loaded) { + loaded = 1; + for_each_ref(add_ref_decoration, NULL); + } +} + static void show_parents(struct commit *commit, int abbrev) { struct commit_list *p; @@ -216,7 +252,7 @@ void log_write_email_headers(struct rev_info *opt, const char *name, void show_log(struct rev_info *opt) { - struct strbuf msgbuf; + struct strbuf msgbuf = STRBUF_INIT; struct log_info *log = opt->loginfo; struct commit *commit = log->commit, *parent = log->parent; int abbrev = opt->diffopt.abbrev; @@ -345,7 +381,6 @@ void show_log(struct rev_info *opt) /* * And then the pretty-printed message itself */ - strbuf_init(&msgbuf, 0); if (need_8bit_cte >= 0) need_8bit_cte = has_non_ascii(opt->add_signoff); pretty_print_commit(opt->commit_format, commit, &msgbuf, diff --git a/log-tree.h b/log-tree.h index 59ba4c48b7..3c8127bb7c 100644 --- a/log-tree.h +++ b/log-tree.h @@ -17,5 +17,6 @@ void log_write_email_headers(struct rev_info *opt, const char *name, const char **subject_p, const char **extra_headers_p, int *need_8bit_cte_p); +void load_ref_decorations(void); #endif diff --git a/merge-recursive.c b/merge-recursive.c new file mode 100644 index 0000000000..7472d3ecc9 --- /dev/null +++ b/merge-recursive.c @@ -0,0 +1,1356 @@ +/* + * Recursive Merge algorithm stolen from git-merge-recursive.py by + * Fredrik Kuivinen. + * The thieves were Alex Riesen and Johannes Schindelin, in June/July 2006 + */ +#include "cache.h" +#include "cache-tree.h" +#include "commit.h" +#include "blob.h" +#include "builtin.h" +#include "tree-walk.h" +#include "diff.h" +#include "diffcore.h" +#include "tag.h" +#include "unpack-trees.h" +#include "string-list.h" +#include "xdiff-interface.h" +#include "ll-merge.h" +#include "interpolate.h" +#include "attr.h" +#include "merge-recursive.h" +#include "dir.h" + +static struct tree *shift_tree_object(struct tree *one, struct tree *two) +{ + unsigned char shifted[20]; + + /* + * NEEDSWORK: this limits the recursion depth to hardcoded + * value '2' to avoid excessive overhead. + */ + shift_tree(one->object.sha1, two->object.sha1, shifted, 2); + if (!hashcmp(two->object.sha1, shifted)) + return two; + return lookup_tree(shifted); +} + +/* + * A virtual commit has (const char *)commit->util set to the name. + */ + +struct commit *make_virtual_commit(struct tree *tree, const char *comment) +{ + struct commit *commit = xcalloc(1, sizeof(struct commit)); + commit->tree = tree; + commit->util = (void*)comment; + /* avoid warnings */ + commit->object.parsed = 1; + return commit; +} + +/* + * Since we use get_tree_entry(), which does not put the read object into + * the object pool, we cannot rely on a == b. + */ +static int sha_eq(const unsigned char *a, const unsigned char *b) +{ + if (!a && !b) + return 2; + return a && b && hashcmp(a, b) == 0; +} + +/* + * Since we want to write the index eventually, we cannot reuse the index + * for these (temporary) data. + */ +struct stage_data +{ + struct + { + unsigned mode; + unsigned char sha[20]; + } stages[4]; + unsigned processed:1; +}; + +static int show(struct merge_options *o, int v) +{ + return (!o->call_depth && o->verbosity >= v) || o->verbosity >= 5; +} + +static void flush_output(struct merge_options *o) +{ + if (o->obuf.len) { + fputs(o->obuf.buf, stdout); + strbuf_reset(&o->obuf); + } +} + +static void output(struct merge_options *o, int v, const char *fmt, ...) +{ + int len; + va_list ap; + + if (!show(o, v)) + return; + + strbuf_grow(&o->obuf, o->call_depth * 2 + 2); + memset(o->obuf.buf + o->obuf.len, ' ', o->call_depth * 2); + strbuf_setlen(&o->obuf, o->obuf.len + o->call_depth * 2); + + va_start(ap, fmt); + len = vsnprintf(o->obuf.buf + o->obuf.len, strbuf_avail(&o->obuf), fmt, ap); + va_end(ap); + + if (len < 0) + len = 0; + if (len >= strbuf_avail(&o->obuf)) { + strbuf_grow(&o->obuf, len + 2); + va_start(ap, fmt); + len = vsnprintf(o->obuf.buf + o->obuf.len, strbuf_avail(&o->obuf), fmt, ap); + va_end(ap); + if (len >= strbuf_avail(&o->obuf)) { + die("this should not happen, your snprintf is broken"); + } + } + strbuf_setlen(&o->obuf, o->obuf.len + len); + strbuf_add(&o->obuf, "\n", 1); + if (!o->buffer_output) + flush_output(o); +} + +static void output_commit_title(struct merge_options *o, struct commit *commit) +{ + int i; + flush_output(o); + for (i = o->call_depth; i--;) + fputs(" ", stdout); + if (commit->util) + printf("virtual %s\n", (char *)commit->util); + else { + printf("%s ", find_unique_abbrev(commit->object.sha1, DEFAULT_ABBREV)); + if (parse_commit(commit) != 0) + printf("(bad commit)\n"); + else { + const char *s; + int len; + for (s = commit->buffer; *s; s++) + if (*s == '\n' && s[1] == '\n') { + s += 2; + break; + } + for (len = 0; s[len] && '\n' != s[len]; len++) + ; /* do nothing */ + printf("%.*s\n", len, s); + } + } +} + +static int add_cacheinfo(unsigned int mode, const unsigned char *sha1, + const char *path, int stage, int refresh, int options) +{ + struct cache_entry *ce; + ce = make_cache_entry(mode, sha1 ? sha1 : null_sha1, path, stage, refresh); + if (!ce) + return error("addinfo_cache failed for path '%s'", path); + return add_cache_entry(ce, options); +} + +static void init_tree_desc_from_tree(struct tree_desc *desc, struct tree *tree) +{ + parse_tree(tree); + init_tree_desc(desc, tree->buffer, tree->size); +} + +static int git_merge_trees(int index_only, + struct tree *common, + struct tree *head, + struct tree *merge) +{ + int rc; + struct tree_desc t[3]; + struct unpack_trees_options opts; + + memset(&opts, 0, sizeof(opts)); + if (index_only) + opts.index_only = 1; + else + opts.update = 1; + opts.merge = 1; + opts.head_idx = 2; + opts.fn = threeway_merge; + opts.src_index = &the_index; + opts.dst_index = &the_index; + + init_tree_desc_from_tree(t+0, common); + init_tree_desc_from_tree(t+1, head); + init_tree_desc_from_tree(t+2, merge); + + rc = unpack_trees(3, t, &opts); + cache_tree_free(&active_cache_tree); + return rc; +} + +struct tree *write_tree_from_memory(struct merge_options *o) +{ + struct tree *result = NULL; + + if (unmerged_cache()) { + int i; + output(o, 0, "There are unmerged index entries:"); + for (i = 0; i < active_nr; i++) { + struct cache_entry *ce = active_cache[i]; + if (ce_stage(ce)) + output(o, 0, "%d %.*s", ce_stage(ce), ce_namelen(ce), ce->name); + } + return NULL; + } + + if (!active_cache_tree) + active_cache_tree = cache_tree(); + + if (!cache_tree_fully_valid(active_cache_tree) && + cache_tree_update(active_cache_tree, + active_cache, active_nr, 0, 0) < 0) + die("error building trees"); + + result = lookup_tree(active_cache_tree->sha1); + + return result; +} + +static int save_files_dirs(const unsigned char *sha1, + const char *base, int baselen, const char *path, + unsigned int mode, int stage, void *context) +{ + int len = strlen(path); + char *newpath = xmalloc(baselen + len + 1); + struct merge_options *o = context; + + memcpy(newpath, base, baselen); + memcpy(newpath + baselen, path, len); + newpath[baselen + len] = '\0'; + + if (S_ISDIR(mode)) + string_list_insert(newpath, &o->current_directory_set); + else + string_list_insert(newpath, &o->current_file_set); + free(newpath); + + return READ_TREE_RECURSIVE; +} + +static int get_files_dirs(struct merge_options *o, struct tree *tree) +{ + int n; + if (read_tree_recursive(tree, "", 0, 0, NULL, save_files_dirs, o)) + return 0; + n = o->current_file_set.nr + o->current_directory_set.nr; + return n; +} + +/* + * Returns an index_entry instance which doesn't have to correspond to + * a real cache entry in Git's index. + */ +static struct stage_data *insert_stage_data(const char *path, + struct tree *o, struct tree *a, struct tree *b, + struct string_list *entries) +{ + struct string_list_item *item; + struct stage_data *e = xcalloc(1, sizeof(struct stage_data)); + get_tree_entry(o->object.sha1, path, + e->stages[1].sha, &e->stages[1].mode); + get_tree_entry(a->object.sha1, path, + e->stages[2].sha, &e->stages[2].mode); + get_tree_entry(b->object.sha1, path, + e->stages[3].sha, &e->stages[3].mode); + item = string_list_insert(path, entries); + item->util = e; + return e; +} + +/* + * Create a dictionary mapping file names to stage_data objects. The + * dictionary contains one entry for every path with a non-zero stage entry. + */ +static struct string_list *get_unmerged(void) +{ + struct string_list *unmerged = xcalloc(1, sizeof(struct string_list)); + int i; + + unmerged->strdup_strings = 1; + + for (i = 0; i < active_nr; i++) { + struct string_list_item *item; + struct stage_data *e; + struct cache_entry *ce = active_cache[i]; + if (!ce_stage(ce)) + continue; + + item = string_list_lookup(ce->name, unmerged); + if (!item) { + item = string_list_insert(ce->name, unmerged); + item->util = xcalloc(1, sizeof(struct stage_data)); + } + e = item->util; + e->stages[ce_stage(ce)].mode = ce->ce_mode; + hashcpy(e->stages[ce_stage(ce)].sha, ce->sha1); + } + + return unmerged; +} + +struct rename +{ + struct diff_filepair *pair; + struct stage_data *src_entry; + struct stage_data *dst_entry; + unsigned processed:1; +}; + +/* + * Get information of all renames which occurred between 'o_tree' and + * 'tree'. We need the three trees in the merge ('o_tree', 'a_tree' and + * 'b_tree') to be able to associate the correct cache entries with + * the rename information. 'tree' is always equal to either a_tree or b_tree. + */ +static struct string_list *get_renames(struct merge_options *o, + struct tree *tree, + struct tree *o_tree, + struct tree *a_tree, + struct tree *b_tree, + struct string_list *entries) +{ + int i; + struct string_list *renames; + struct diff_options opts; + + renames = xcalloc(1, sizeof(struct string_list)); + diff_setup(&opts); + DIFF_OPT_SET(&opts, RECURSIVE); + opts.detect_rename = DIFF_DETECT_RENAME; + opts.rename_limit = o->merge_rename_limit >= 0 ? o->merge_rename_limit : + o->diff_rename_limit >= 0 ? o->diff_rename_limit : + 500; + opts.warn_on_too_large_rename = 1; + opts.output_format = DIFF_FORMAT_NO_OUTPUT; + if (diff_setup_done(&opts) < 0) + die("diff setup failed"); + diff_tree_sha1(o_tree->object.sha1, tree->object.sha1, "", &opts); + diffcore_std(&opts); + for (i = 0; i < diff_queued_diff.nr; ++i) { + struct string_list_item *item; + struct rename *re; + struct diff_filepair *pair = diff_queued_diff.queue[i]; + if (pair->status != 'R') { + diff_free_filepair(pair); + continue; + } + re = xmalloc(sizeof(*re)); + re->processed = 0; + re->pair = pair; + item = string_list_lookup(re->pair->one->path, entries); + if (!item) + re->src_entry = insert_stage_data(re->pair->one->path, + o_tree, a_tree, b_tree, entries); + else + re->src_entry = item->util; + + item = string_list_lookup(re->pair->two->path, entries); + if (!item) + re->dst_entry = insert_stage_data(re->pair->two->path, + o_tree, a_tree, b_tree, entries); + else + re->dst_entry = item->util; + item = string_list_insert(pair->one->path, renames); + item->util = re; + } + opts.output_format = DIFF_FORMAT_NO_OUTPUT; + diff_queued_diff.nr = 0; + diff_flush(&opts); + return renames; +} + +static int update_stages(const char *path, struct diff_filespec *o, + struct diff_filespec *a, struct diff_filespec *b, + int clear) +{ + int options = ADD_CACHE_OK_TO_ADD | ADD_CACHE_OK_TO_REPLACE; + if (clear) + if (remove_file_from_cache(path)) + return -1; + if (o) + if (add_cacheinfo(o->mode, o->sha1, path, 1, 0, options)) + return -1; + if (a) + if (add_cacheinfo(a->mode, a->sha1, path, 2, 0, options)) + return -1; + if (b) + if (add_cacheinfo(b->mode, b->sha1, path, 3, 0, options)) + return -1; + return 0; +} + +static int remove_file(struct merge_options *o, int clean, + const char *path, int no_wd) +{ + int update_cache = o->call_depth || clean; + int update_working_directory = !o->call_depth && !no_wd; + + if (update_cache) { + if (remove_file_from_cache(path)) + return -1; + } + if (update_working_directory) { + if (remove_path(path) && errno != ENOENT) + return -1; + } + return 0; +} + +static char *unique_path(struct merge_options *o, const char *path, const char *branch) +{ + char *newpath = xmalloc(strlen(path) + 1 + strlen(branch) + 8 + 1); + int suffix = 0; + struct stat st; + char *p = newpath + strlen(path); + strcpy(newpath, path); + *(p++) = '~'; + strcpy(p, branch); + for (; *p; ++p) + if ('/' == *p) + *p = '_'; + while (string_list_has_string(&o->current_file_set, newpath) || + string_list_has_string(&o->current_directory_set, newpath) || + lstat(newpath, &st) == 0) + sprintf(p, "_%d", suffix++); + + string_list_insert(newpath, &o->current_file_set); + return newpath; +} + +static void flush_buffer(int fd, const char *buf, unsigned long size) +{ + while (size > 0) { + long ret = write_in_full(fd, buf, size); + if (ret < 0) { + /* Ignore epipe */ + if (errno == EPIPE) + break; + die("merge-recursive: %s", strerror(errno)); + } else if (!ret) { + die("merge-recursive: disk full?"); + } + size -= ret; + buf += ret; + } +} + +static int make_room_for_path(const char *path) +{ + int status; + const char *msg = "failed to create path '%s'%s"; + + status = safe_create_leading_directories_const(path); + if (status) { + if (status == -3) { + /* something else exists */ + error(msg, path, ": perhaps a D/F conflict?"); + return -1; + } + die(msg, path, ""); + } + + /* Successful unlink is good.. */ + if (!unlink(path)) + return 0; + /* .. and so is no existing file */ + if (errno == ENOENT) + return 0; + /* .. but not some other error (who really cares what?) */ + return error(msg, path, ": perhaps a D/F conflict?"); +} + +static void update_file_flags(struct merge_options *o, + const unsigned char *sha, + unsigned mode, + const char *path, + int update_cache, + int update_wd) +{ + if (o->call_depth) + update_wd = 0; + + if (update_wd) { + enum object_type type; + void *buf; + unsigned long size; + + if (S_ISGITLINK(mode)) + die("cannot read object %s '%s': It is a submodule!", + sha1_to_hex(sha), path); + + buf = read_sha1_file(sha, &type, &size); + if (!buf) + die("cannot read object %s '%s'", sha1_to_hex(sha), path); + if (type != OBJ_BLOB) + die("blob expected for %s '%s'", sha1_to_hex(sha), path); + if (S_ISREG(mode)) { + struct strbuf strbuf = STRBUF_INIT; + if (convert_to_working_tree(path, buf, size, &strbuf)) { + free(buf); + size = strbuf.len; + buf = strbuf_detach(&strbuf, NULL); + } + } + + if (make_room_for_path(path) < 0) { + update_wd = 0; + free(buf); + goto update_index; + } + if (S_ISREG(mode) || (!has_symlinks && S_ISLNK(mode))) { + int fd; + if (mode & 0100) + mode = 0777; + else + mode = 0666; + fd = open(path, O_WRONLY | O_TRUNC | O_CREAT, mode); + if (fd < 0) + die("failed to open %s: %s", path, strerror(errno)); + flush_buffer(fd, buf, size); + close(fd); + } else if (S_ISLNK(mode)) { + char *lnk = xmemdupz(buf, size); + safe_create_leading_directories_const(path); + unlink(path); + symlink(lnk, path); + free(lnk); + } else + die("do not know what to do with %06o %s '%s'", + mode, sha1_to_hex(sha), path); + free(buf); + } + update_index: + if (update_cache) + add_cacheinfo(mode, sha, path, 0, update_wd, ADD_CACHE_OK_TO_ADD); +} + +static void update_file(struct merge_options *o, + int clean, + const unsigned char *sha, + unsigned mode, + const char *path) +{ + update_file_flags(o, sha, mode, path, o->call_depth || clean, !o->call_depth); +} + +/* Low level file merging, update and removal */ + +struct merge_file_info +{ + unsigned char sha[20]; + unsigned mode; + unsigned clean:1, + merge:1; +}; + +static void fill_mm(const unsigned char *sha1, mmfile_t *mm) +{ + unsigned long size; + enum object_type type; + + if (!hashcmp(sha1, null_sha1)) { + mm->ptr = xstrdup(""); + mm->size = 0; + return; + } + + mm->ptr = read_sha1_file(sha1, &type, &size); + if (!mm->ptr || type != OBJ_BLOB) + die("unable to read blob object %s", sha1_to_hex(sha1)); + mm->size = size; +} + +static int merge_3way(struct merge_options *o, + mmbuffer_t *result_buf, + struct diff_filespec *one, + struct diff_filespec *a, + struct diff_filespec *b, + const char *branch1, + const char *branch2) +{ + mmfile_t orig, src1, src2; + char *name1, *name2; + int merge_status; + + name1 = xstrdup(mkpath("%s:%s", branch1, a->path)); + name2 = xstrdup(mkpath("%s:%s", branch2, b->path)); + + fill_mm(one->sha1, &orig); + fill_mm(a->sha1, &src1); + fill_mm(b->sha1, &src2); + + merge_status = ll_merge(result_buf, a->path, &orig, + &src1, name1, &src2, name2, + o->call_depth); + + free(name1); + free(name2); + free(orig.ptr); + free(src1.ptr); + free(src2.ptr); + return merge_status; +} + +static struct merge_file_info merge_file(struct merge_options *o, + struct diff_filespec *one, + struct diff_filespec *a, + struct diff_filespec *b, + const char *branch1, + const char *branch2) +{ + struct merge_file_info result; + result.merge = 0; + result.clean = 1; + + if ((S_IFMT & a->mode) != (S_IFMT & b->mode)) { + result.clean = 0; + if (S_ISREG(a->mode)) { + result.mode = a->mode; + hashcpy(result.sha, a->sha1); + } else { + result.mode = b->mode; + hashcpy(result.sha, b->sha1); + } + } else { + if (!sha_eq(a->sha1, one->sha1) && !sha_eq(b->sha1, one->sha1)) + result.merge = 1; + + /* + * Merge modes + */ + if (a->mode == b->mode || a->mode == one->mode) + result.mode = b->mode; + else { + result.mode = a->mode; + if (b->mode != one->mode) { + result.clean = 0; + result.merge = 1; + } + } + + if (sha_eq(a->sha1, b->sha1) || sha_eq(a->sha1, one->sha1)) + hashcpy(result.sha, b->sha1); + else if (sha_eq(b->sha1, one->sha1)) + hashcpy(result.sha, a->sha1); + else if (S_ISREG(a->mode)) { + mmbuffer_t result_buf; + int merge_status; + + merge_status = merge_3way(o, &result_buf, one, a, b, + branch1, branch2); + + if ((merge_status < 0) || !result_buf.ptr) + die("Failed to execute internal merge"); + + if (write_sha1_file(result_buf.ptr, result_buf.size, + blob_type, result.sha)) + die("Unable to add %s to database", + a->path); + + free(result_buf.ptr); + result.clean = (merge_status == 0); + } else if (S_ISGITLINK(a->mode)) { + result.clean = 0; + hashcpy(result.sha, a->sha1); + } else if (S_ISLNK(a->mode)) { + hashcpy(result.sha, a->sha1); + + if (!sha_eq(a->sha1, b->sha1)) + result.clean = 0; + } else { + die("unsupported object type in the tree"); + } + } + + return result; +} + +static void conflict_rename_rename(struct merge_options *o, + struct rename *ren1, + const char *branch1, + struct rename *ren2, + const char *branch2) +{ + char *del[2]; + int delp = 0; + const char *ren1_dst = ren1->pair->two->path; + const char *ren2_dst = ren2->pair->two->path; + const char *dst_name1 = ren1_dst; + const char *dst_name2 = ren2_dst; + if (string_list_has_string(&o->current_directory_set, ren1_dst)) { + dst_name1 = del[delp++] = unique_path(o, ren1_dst, branch1); + output(o, 1, "%s is a directory in %s adding as %s instead", + ren1_dst, branch2, dst_name1); + remove_file(o, 0, ren1_dst, 0); + } + if (string_list_has_string(&o->current_directory_set, ren2_dst)) { + dst_name2 = del[delp++] = unique_path(o, ren2_dst, branch2); + output(o, 1, "%s is a directory in %s adding as %s instead", + ren2_dst, branch1, dst_name2); + remove_file(o, 0, ren2_dst, 0); + } + if (o->call_depth) { + remove_file_from_cache(dst_name1); + remove_file_from_cache(dst_name2); + /* + * Uncomment to leave the conflicting names in the resulting tree + * + * update_file(o, 0, ren1->pair->two->sha1, ren1->pair->two->mode, dst_name1); + * update_file(o, 0, ren2->pair->two->sha1, ren2->pair->two->mode, dst_name2); + */ + } else { + update_stages(dst_name1, NULL, ren1->pair->two, NULL, 1); + update_stages(dst_name2, NULL, NULL, ren2->pair->two, 1); + } + while (delp--) + free(del[delp]); +} + +static void conflict_rename_dir(struct merge_options *o, + struct rename *ren1, + const char *branch1) +{ + char *new_path = unique_path(o, ren1->pair->two->path, branch1); + output(o, 1, "Renaming %s to %s instead", ren1->pair->one->path, new_path); + remove_file(o, 0, ren1->pair->two->path, 0); + update_file(o, 0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path); + free(new_path); +} + +static void conflict_rename_rename_2(struct merge_options *o, + struct rename *ren1, + const char *branch1, + struct rename *ren2, + const char *branch2) +{ + char *new_path1 = unique_path(o, ren1->pair->two->path, branch1); + char *new_path2 = unique_path(o, ren2->pair->two->path, branch2); + output(o, 1, "Renaming %s to %s and %s to %s instead", + ren1->pair->one->path, new_path1, + ren2->pair->one->path, new_path2); + remove_file(o, 0, ren1->pair->two->path, 0); + update_file(o, 0, ren1->pair->two->sha1, ren1->pair->two->mode, new_path1); + update_file(o, 0, ren2->pair->two->sha1, ren2->pair->two->mode, new_path2); + free(new_path2); + free(new_path1); +} + +static int process_renames(struct merge_options *o, + struct string_list *a_renames, + struct string_list *b_renames) +{ + int clean_merge = 1, i, j; + struct string_list a_by_dst = {NULL, 0, 0, 0}, b_by_dst = {NULL, 0, 0, 0}; + const struct rename *sre; + + for (i = 0; i < a_renames->nr; i++) { + sre = a_renames->items[i].util; + string_list_insert(sre->pair->two->path, &a_by_dst)->util + = sre->dst_entry; + } + for (i = 0; i < b_renames->nr; i++) { + sre = b_renames->items[i].util; + string_list_insert(sre->pair->two->path, &b_by_dst)->util + = sre->dst_entry; + } + + for (i = 0, j = 0; i < a_renames->nr || j < b_renames->nr;) { + int compare; + char *src; + struct string_list *renames1, *renames2, *renames2Dst; + struct rename *ren1 = NULL, *ren2 = NULL; + const char *branch1, *branch2; + const char *ren1_src, *ren1_dst; + + if (i >= a_renames->nr) { + compare = 1; + ren2 = b_renames->items[j++].util; + } else if (j >= b_renames->nr) { + compare = -1; + ren1 = a_renames->items[i++].util; + } else { + compare = strcmp(a_renames->items[i].string, + b_renames->items[j].string); + if (compare <= 0) + ren1 = a_renames->items[i++].util; + if (compare >= 0) + ren2 = b_renames->items[j++].util; + } + + /* TODO: refactor, so that 1/2 are not needed */ + if (ren1) { + renames1 = a_renames; + renames2 = b_renames; + renames2Dst = &b_by_dst; + branch1 = o->branch1; + branch2 = o->branch2; + } else { + struct rename *tmp; + renames1 = b_renames; + renames2 = a_renames; + renames2Dst = &a_by_dst; + branch1 = o->branch2; + branch2 = o->branch1; + tmp = ren2; + ren2 = ren1; + ren1 = tmp; + } + src = ren1->pair->one->path; + + ren1->dst_entry->processed = 1; + ren1->src_entry->processed = 1; + + if (ren1->processed) + continue; + ren1->processed = 1; + + ren1_src = ren1->pair->one->path; + ren1_dst = ren1->pair->two->path; + + if (ren2) { + const char *ren2_src = ren2->pair->one->path; + const char *ren2_dst = ren2->pair->two->path; + /* Renamed in 1 and renamed in 2 */ + if (strcmp(ren1_src, ren2_src) != 0) + die("ren1.src != ren2.src"); + ren2->dst_entry->processed = 1; + ren2->processed = 1; + if (strcmp(ren1_dst, ren2_dst) != 0) { + clean_merge = 0; + output(o, 1, "CONFLICT (rename/rename): " + "Rename \"%s\"->\"%s\" in branch \"%s\" " + "rename \"%s\"->\"%s\" in \"%s\"%s", + src, ren1_dst, branch1, + src, ren2_dst, branch2, + o->call_depth ? " (left unresolved)": ""); + if (o->call_depth) { + remove_file_from_cache(src); + update_file(o, 0, ren1->pair->one->sha1, + ren1->pair->one->mode, src); + } + conflict_rename_rename(o, ren1, branch1, ren2, branch2); + } else { + struct merge_file_info mfi; + remove_file(o, 1, ren1_src, 1); + mfi = merge_file(o, + ren1->pair->one, + ren1->pair->two, + ren2->pair->two, + branch1, + branch2); + if (mfi.merge || !mfi.clean) + output(o, 1, "Renaming %s->%s", src, ren1_dst); + + if (mfi.merge) + output(o, 2, "Auto-merging %s", ren1_dst); + + if (!mfi.clean) { + output(o, 1, "CONFLICT (content): merge conflict in %s", + ren1_dst); + clean_merge = 0; + + if (!o->call_depth) + update_stages(ren1_dst, + ren1->pair->one, + ren1->pair->two, + ren2->pair->two, + 1 /* clear */); + } + update_file(o, mfi.clean, mfi.sha, mfi.mode, ren1_dst); + } + } else { + /* Renamed in 1, maybe changed in 2 */ + struct string_list_item *item; + /* we only use sha1 and mode of these */ + struct diff_filespec src_other, dst_other; + int try_merge, stage = a_renames == renames1 ? 3: 2; + + remove_file(o, 1, ren1_src, o->call_depth || stage == 3); + + hashcpy(src_other.sha1, ren1->src_entry->stages[stage].sha); + src_other.mode = ren1->src_entry->stages[stage].mode; + hashcpy(dst_other.sha1, ren1->dst_entry->stages[stage].sha); + dst_other.mode = ren1->dst_entry->stages[stage].mode; + + try_merge = 0; + + if (string_list_has_string(&o->current_directory_set, ren1_dst)) { + clean_merge = 0; + output(o, 1, "CONFLICT (rename/directory): Rename %s->%s in %s " + " directory %s added in %s", + ren1_src, ren1_dst, branch1, + ren1_dst, branch2); + conflict_rename_dir(o, ren1, branch1); + } else if (sha_eq(src_other.sha1, null_sha1)) { + clean_merge = 0; + output(o, 1, "CONFLICT (rename/delete): Rename %s->%s in %s " + "and deleted in %s", + ren1_src, ren1_dst, branch1, + branch2); + update_file(o, 0, ren1->pair->two->sha1, ren1->pair->two->mode, ren1_dst); + } else if (!sha_eq(dst_other.sha1, null_sha1)) { + const char *new_path; + clean_merge = 0; + try_merge = 1; + output(o, 1, "CONFLICT (rename/add): Rename %s->%s in %s. " + "%s added in %s", + ren1_src, ren1_dst, branch1, + ren1_dst, branch2); + new_path = unique_path(o, ren1_dst, branch2); + output(o, 1, "Adding as %s instead", new_path); + update_file(o, 0, dst_other.sha1, dst_other.mode, new_path); + } else if ((item = string_list_lookup(ren1_dst, renames2Dst))) { + ren2 = item->util; + clean_merge = 0; + ren2->processed = 1; + output(o, 1, "CONFLICT (rename/rename): " + "Rename %s->%s in %s. " + "Rename %s->%s in %s", + ren1_src, ren1_dst, branch1, + ren2->pair->one->path, ren2->pair->two->path, branch2); + conflict_rename_rename_2(o, ren1, branch1, ren2, branch2); + } else + try_merge = 1; + + if (try_merge) { + struct diff_filespec *one, *a, *b; + struct merge_file_info mfi; + src_other.path = (char *)ren1_src; + + one = ren1->pair->one; + if (a_renames == renames1) { + a = ren1->pair->two; + b = &src_other; + } else { + b = ren1->pair->two; + a = &src_other; + } + mfi = merge_file(o, one, a, b, + o->branch1, o->branch2); + + if (mfi.clean && + sha_eq(mfi.sha, ren1->pair->two->sha1) && + mfi.mode == ren1->pair->two->mode) + /* + * This messaged is part of + * t6022 test. If you change + * it update the test too. + */ + output(o, 3, "Skipped %s (merged same as existing)", ren1_dst); + else { + if (mfi.merge || !mfi.clean) + output(o, 1, "Renaming %s => %s", ren1_src, ren1_dst); + if (mfi.merge) + output(o, 2, "Auto-merging %s", ren1_dst); + if (!mfi.clean) { + output(o, 1, "CONFLICT (rename/modify): Merge conflict in %s", + ren1_dst); + clean_merge = 0; + + if (!o->call_depth) + update_stages(ren1_dst, + one, a, b, 1); + } + update_file(o, mfi.clean, mfi.sha, mfi.mode, ren1_dst); + } + } + } + } + string_list_clear(&a_by_dst, 0); + string_list_clear(&b_by_dst, 0); + + return clean_merge; +} + +static unsigned char *stage_sha(const unsigned char *sha, unsigned mode) +{ + return (is_null_sha1(sha) || mode == 0) ? NULL: (unsigned char *)sha; +} + +/* Per entry merge function */ +static int process_entry(struct merge_options *o, + const char *path, struct stage_data *entry) +{ + /* + printf("processing entry, clean cache: %s\n", index_only ? "yes": "no"); + print_index_entry("\tpath: ", entry); + */ + int clean_merge = 1; + unsigned o_mode = entry->stages[1].mode; + unsigned a_mode = entry->stages[2].mode; + unsigned b_mode = entry->stages[3].mode; + unsigned char *o_sha = stage_sha(entry->stages[1].sha, o_mode); + unsigned char *a_sha = stage_sha(entry->stages[2].sha, a_mode); + unsigned char *b_sha = stage_sha(entry->stages[3].sha, b_mode); + + if (o_sha && (!a_sha || !b_sha)) { + /* Case A: Deleted in one */ + if ((!a_sha && !b_sha) || + (sha_eq(a_sha, o_sha) && !b_sha) || + (!a_sha && sha_eq(b_sha, o_sha))) { + /* Deleted in both or deleted in one and + * unchanged in the other */ + if (a_sha) + output(o, 2, "Removing %s", path); + /* do not touch working file if it did not exist */ + remove_file(o, 1, path, !a_sha); + } else { + /* Deleted in one and changed in the other */ + clean_merge = 0; + if (!a_sha) { + output(o, 1, "CONFLICT (delete/modify): %s deleted in %s " + "and modified in %s. Version %s of %s left in tree.", + path, o->branch1, + o->branch2, o->branch2, path); + update_file(o, 0, b_sha, b_mode, path); + } else { + output(o, 1, "CONFLICT (delete/modify): %s deleted in %s " + "and modified in %s. Version %s of %s left in tree.", + path, o->branch2, + o->branch1, o->branch1, path); + update_file(o, 0, a_sha, a_mode, path); + } + } + + } else if ((!o_sha && a_sha && !b_sha) || + (!o_sha && !a_sha && b_sha)) { + /* Case B: Added in one. */ + const char *add_branch; + const char *other_branch; + unsigned mode; + const unsigned char *sha; + const char *conf; + + if (a_sha) { + add_branch = o->branch1; + other_branch = o->branch2; + mode = a_mode; + sha = a_sha; + conf = "file/directory"; + } else { + add_branch = o->branch2; + other_branch = o->branch1; + mode = b_mode; + sha = b_sha; + conf = "directory/file"; + } + if (string_list_has_string(&o->current_directory_set, path)) { + const char *new_path = unique_path(o, path, add_branch); + clean_merge = 0; + output(o, 1, "CONFLICT (%s): There is a directory with name %s in %s. " + "Adding %s as %s", + conf, path, other_branch, path, new_path); + remove_file(o, 0, path, 0); + update_file(o, 0, sha, mode, new_path); + } else { + output(o, 2, "Adding %s", path); + update_file(o, 1, sha, mode, path); + } + } else if (a_sha && b_sha) { + /* Case C: Added in both (check for same permissions) and */ + /* case D: Modified in both, but differently. */ + const char *reason = "content"; + struct merge_file_info mfi; + struct diff_filespec one, a, b; + + if (!o_sha) { + reason = "add/add"; + o_sha = (unsigned char *)null_sha1; + } + output(o, 2, "Auto-merging %s", path); + one.path = a.path = b.path = (char *)path; + hashcpy(one.sha1, o_sha); + one.mode = o_mode; + hashcpy(a.sha1, a_sha); + a.mode = a_mode; + hashcpy(b.sha1, b_sha); + b.mode = b_mode; + + mfi = merge_file(o, &one, &a, &b, + o->branch1, o->branch2); + + clean_merge = mfi.clean; + if (mfi.clean) + update_file(o, 1, mfi.sha, mfi.mode, path); + else if (S_ISGITLINK(mfi.mode)) + output(o, 1, "CONFLICT (submodule): Merge conflict in %s " + "- needs %s", path, sha1_to_hex(b.sha1)); + else { + output(o, 1, "CONFLICT (%s): Merge conflict in %s", + reason, path); + + if (o->call_depth) + update_file(o, 0, mfi.sha, mfi.mode, path); + else + update_file_flags(o, mfi.sha, mfi.mode, path, + 0 /* update_cache */, 1 /* update_working_directory */); + } + } else if (!o_sha && !a_sha && !b_sha) { + /* + * this entry was deleted altogether. a_mode == 0 means + * we had that path and want to actively remove it. + */ + remove_file(o, 1, path, !a_mode); + } else + die("Fatal merge failure, shouldn't happen."); + + return clean_merge; +} + +int merge_trees(struct merge_options *o, + struct tree *head, + struct tree *merge, + struct tree *common, + struct tree **result) +{ + int code, clean; + + if (o->subtree_merge) { + merge = shift_tree_object(head, merge); + common = shift_tree_object(head, common); + } + + if (sha_eq(common->object.sha1, merge->object.sha1)) { + output(o, 0, "Already uptodate!"); + *result = head; + return 1; + } + + code = git_merge_trees(o->call_depth, common, head, merge); + + if (code != 0) + die("merging of trees %s and %s failed", + sha1_to_hex(head->object.sha1), + sha1_to_hex(merge->object.sha1)); + + if (unmerged_cache()) { + struct string_list *entries, *re_head, *re_merge; + int i; + string_list_clear(&o->current_file_set, 1); + string_list_clear(&o->current_directory_set, 1); + get_files_dirs(o, head); + get_files_dirs(o, merge); + + entries = get_unmerged(); + re_head = get_renames(o, head, common, head, merge, entries); + re_merge = get_renames(o, merge, common, head, merge, entries); + clean = process_renames(o, re_head, re_merge); + for (i = 0; i < entries->nr; i++) { + const char *path = entries->items[i].string; + struct stage_data *e = entries->items[i].util; + if (!e->processed + && !process_entry(o, path, e)) + clean = 0; + } + + string_list_clear(re_merge, 0); + string_list_clear(re_head, 0); + string_list_clear(entries, 1); + + } + else + clean = 1; + + if (o->call_depth) + *result = write_tree_from_memory(o); + + return clean; +} + +static struct commit_list *reverse_commit_list(struct commit_list *list) +{ + struct commit_list *next = NULL, *current, *backup; + for (current = list; current; current = backup) { + backup = current->next; + current->next = next; + next = current; + } + return next; +} + +/* + * Merge the commits h1 and h2, return the resulting virtual + * commit object and a flag indicating the cleanness of the merge. + */ +int merge_recursive(struct merge_options *o, + struct commit *h1, + struct commit *h2, + struct commit_list *ca, + struct commit **result) +{ + struct commit_list *iter; + struct commit *merged_common_ancestors; + struct tree *mrtree = mrtree; + int clean; + + if (show(o, 4)) { + output(o, 4, "Merging:"); + output_commit_title(o, h1); + output_commit_title(o, h2); + } + + if (!ca) { + ca = get_merge_bases(h1, h2, 1); + ca = reverse_commit_list(ca); + } + + if (show(o, 5)) { + output(o, 5, "found %u common ancestor(s):", commit_list_count(ca)); + for (iter = ca; iter; iter = iter->next) + output_commit_title(o, iter->item); + } + + merged_common_ancestors = pop_commit(&ca); + if (merged_common_ancestors == NULL) { + /* if there is no common ancestor, make an empty tree */ + struct tree *tree = xcalloc(1, sizeof(struct tree)); + + tree->object.parsed = 1; + tree->object.type = OBJ_TREE; + pretend_sha1_file(NULL, 0, OBJ_TREE, tree->object.sha1); + merged_common_ancestors = make_virtual_commit(tree, "ancestor"); + } + + for (iter = ca; iter; iter = iter->next) { + const char *saved_b1, *saved_b2; + o->call_depth++; + /* + * When the merge fails, the result contains files + * with conflict markers. The cleanness flag is + * ignored, it was never actually used, as result of + * merge_trees has always overwritten it: the committed + * "conflicts" were already resolved. + */ + discard_cache(); + saved_b1 = o->branch1; + saved_b2 = o->branch2; + o->branch1 = "Temporary merge branch 1"; + o->branch2 = "Temporary merge branch 2"; + merge_recursive(o, merged_common_ancestors, iter->item, + NULL, &merged_common_ancestors); + o->branch1 = saved_b1; + o->branch2 = saved_b2; + o->call_depth--; + + if (!merged_common_ancestors) + die("merge returned no commit"); + } + + discard_cache(); + if (!o->call_depth) + read_cache(); + + clean = merge_trees(o, h1->tree, h2->tree, merged_common_ancestors->tree, + &mrtree); + + if (o->call_depth) { + *result = make_virtual_commit(mrtree, "merged tree"); + commit_list_insert(h1, &(*result)->parents); + commit_list_insert(h2, &(*result)->parents->next); + } + flush_output(o); + return clean; +} + +static struct commit *get_ref(const unsigned char *sha1, const char *name) +{ + struct object *object; + + object = deref_tag(parse_object(sha1), name, strlen(name)); + if (!object) + return NULL; + if (object->type == OBJ_TREE) + return make_virtual_commit((struct tree*)object, name); + if (object->type != OBJ_COMMIT) + return NULL; + if (parse_commit((struct commit *)object)) + return NULL; + return (struct commit *)object; +} + +int merge_recursive_generic(struct merge_options *o, + const unsigned char *head, + const unsigned char *merge, + int num_base_list, + const unsigned char **base_list, + struct commit **result) +{ + int clean, index_fd; + struct lock_file *lock = xcalloc(1, sizeof(struct lock_file)); + struct commit *head_commit = get_ref(head, o->branch1); + struct commit *next_commit = get_ref(merge, o->branch2); + struct commit_list *ca = NULL; + + if (base_list) { + int i; + for (i = 0; i < num_base_list; ++i) { + struct commit *base; + if (!(base = get_ref(base_list[i], sha1_to_hex(base_list[i])))) + return error("Could not parse object '%s'", + sha1_to_hex(base_list[i])); + commit_list_insert(base, &ca); + } + } + + index_fd = hold_locked_index(lock, 1); + clean = merge_recursive(o, head_commit, next_commit, ca, + result); + if (active_cache_changed && + (write_cache(index_fd, active_cache, active_nr) || + commit_locked_index(lock))) + return error("Unable to write index."); + + return clean ? 0 : 1; +} + +static int merge_recursive_config(const char *var, const char *value, void *cb) +{ + struct merge_options *o = cb; + if (!strcasecmp(var, "merge.verbosity")) { + o->verbosity = git_config_int(var, value); + return 0; + } + if (!strcasecmp(var, "diff.renamelimit")) { + o->diff_rename_limit = git_config_int(var, value); + return 0; + } + if (!strcasecmp(var, "merge.renamelimit")) { + o->merge_rename_limit = git_config_int(var, value); + return 0; + } + return git_xmerge_config(var, value, cb); +} + +void init_merge_options(struct merge_options *o) +{ + memset(o, 0, sizeof(struct merge_options)); + o->verbosity = 2; + o->buffer_output = 1; + o->diff_rename_limit = -1; + o->merge_rename_limit = -1; + git_config(merge_recursive_config, o); + if (getenv("GIT_MERGE_VERBOSITY")) + o->verbosity = + strtol(getenv("GIT_MERGE_VERBOSITY"), NULL, 10); + if (o->verbosity >= 5) + o->buffer_output = 0; + strbuf_init(&o->obuf, 0); + memset(&o->current_file_set, 0, sizeof(struct string_list)); + o->current_file_set.strdup_strings = 1; + memset(&o->current_directory_set, 0, sizeof(struct string_list)); + o->current_directory_set.strdup_strings = 1; +} diff --git a/merge-recursive.h b/merge-recursive.h index f37630a8ad..fd138ca140 100644 --- a/merge-recursive.h +++ b/merge-recursive.h @@ -1,20 +1,48 @@ #ifndef MERGE_RECURSIVE_H #define MERGE_RECURSIVE_H -int merge_recursive(struct commit *h1, +#include "string-list.h" + +struct merge_options { + const char *branch1; + const char *branch2; + unsigned subtree_merge : 1; + unsigned buffer_output : 1; + int verbosity; + int diff_rename_limit; + int merge_rename_limit; + int call_depth; + struct strbuf obuf; + struct string_list current_file_set; + struct string_list current_directory_set; +}; + +/* merge_trees() but with recursive ancestor consolidation */ +int merge_recursive(struct merge_options *o, + struct commit *h1, struct commit *h2, - const char *branch1, - const char *branch2, struct commit_list *ancestors, struct commit **result); -int merge_trees(struct tree *head, +/* rename-detecting three-way merge, no recursion */ +int merge_trees(struct merge_options *o, + struct tree *head, struct tree *merge, struct tree *common, - const char *branch1, - const char *branch2, struct tree **result); -struct tree *write_tree_from_memory(void); +/* + * "git-merge-recursive" can be fed trees; wrap them into + * virtual commits and call merge_recursive() proper. + */ +int merge_recursive_generic(struct merge_options *o, + const unsigned char *head, + const unsigned char *merge, + int num_ca, + const unsigned char **ca, + struct commit **result); + +void init_merge_options(struct merge_options *o); +struct tree *write_tree_from_memory(struct merge_options *o); #endif diff --git a/merge-tree.c b/merge-tree.c index 02fc10f7e6..2d1413efbb 100644 --- a/merge-tree.c +++ b/merge-tree.c @@ -158,9 +158,8 @@ static int same_entry(struct name_entry *a, struct name_entry *b) static struct merge_list *create_entry(unsigned stage, unsigned mode, const unsigned char *sha1, const char *path) { - struct merge_list *res = xmalloc(sizeof(*res)); + struct merge_list *res = xcalloc(1, sizeof(*res)); - memset(res, 0, sizeof(*res)); res->stage = stage; res->path = path; res->mode = mode; @@ -153,7 +153,7 @@ static int verify_tag(char *buffer, unsigned long size) int main(int argc, char **argv) { - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; unsigned char result_sha1[20]; if (argc != 1) @@ -161,7 +161,6 @@ int main(int argc, char **argv) setup_git_directory(); - strbuf_init(&buf, 0); if (strbuf_read(&buf, 0, 4096) < 0) { die("could not read from stdin"); } @@ -65,8 +65,8 @@ static const char mktree_usage[] = "git-mktree [-z]"; int main(int ac, char **av) { - struct strbuf sb; - struct strbuf p_uq; + struct strbuf sb = STRBUF_INIT; + struct strbuf p_uq = STRBUF_INIT; unsigned char sha1[20]; int line_termination = '\n'; @@ -82,8 +82,6 @@ int main(int ac, char **av) av++; } - strbuf_init(&sb, 0); - strbuf_init(&p_uq, 0); while (strbuf_getline(&sb, stdin, line_termination) != EOF) { char *ptr, *ntr; unsigned mode; diff --git a/mozilla-sha1/sha1.c b/mozilla-sha1/sha1.c index 3f06b83567..95a4ebf496 100644 --- a/mozilla-sha1/sha1.c +++ b/mozilla-sha1/sha1.c @@ -35,9 +35,9 @@ #include "sha1.h" -static void shaHashBlock(SHA_CTX *ctx); +static void shaHashBlock(moz_SHA_CTX *ctx); -void SHA1_Init(SHA_CTX *ctx) { +void moz_SHA1_Init(moz_SHA_CTX *ctx) { int i; ctx->lenW = 0; @@ -56,7 +56,7 @@ void SHA1_Init(SHA_CTX *ctx) { } -void SHA1_Update(SHA_CTX *ctx, const void *_dataIn, int len) { +void moz_SHA1_Update(moz_SHA_CTX *ctx, const void *_dataIn, int len) { const unsigned char *dataIn = _dataIn; int i; @@ -75,7 +75,7 @@ void SHA1_Update(SHA_CTX *ctx, const void *_dataIn, int len) { } -void SHA1_Final(unsigned char hashout[20], SHA_CTX *ctx) { +void moz_SHA1_Final(unsigned char hashout[20], moz_SHA_CTX *ctx) { unsigned char pad0x80 = 0x80; unsigned char pad0x00 = 0x00; unsigned char padlen[8]; @@ -91,10 +91,10 @@ void SHA1_Final(unsigned char hashout[20], SHA_CTX *ctx) { padlen[5] = (unsigned char)((ctx->sizeLo >> 16) & 255); padlen[6] = (unsigned char)((ctx->sizeLo >> 8) & 255); padlen[7] = (unsigned char)((ctx->sizeLo >> 0) & 255); - SHA1_Update(ctx, &pad0x80, 1); + moz_SHA1_Update(ctx, &pad0x80, 1); while (ctx->lenW != 56) - SHA1_Update(ctx, &pad0x00, 1); - SHA1_Update(ctx, padlen, 8); + moz_SHA1_Update(ctx, &pad0x00, 1); + moz_SHA1_Update(ctx, padlen, 8); /* Output hash */ @@ -106,13 +106,13 @@ void SHA1_Final(unsigned char hashout[20], SHA_CTX *ctx) { /* * Re-initialize the context (also zeroizes contents) */ - SHA1_Init(ctx); + moz_SHA1_Init(ctx); } #define SHA_ROT(X,n) (((X) << (n)) | ((X) >> (32-(n)))) -static void shaHashBlock(SHA_CTX *ctx) { +static void shaHashBlock(moz_SHA_CTX *ctx) { int t; unsigned int A,B,C,D,E,TEMP; diff --git a/mozilla-sha1/sha1.h b/mozilla-sha1/sha1.h index 16f2d3d43c..aa48a46cf7 100644 --- a/mozilla-sha1/sha1.h +++ b/mozilla-sha1/sha1.h @@ -38,8 +38,13 @@ typedef struct { unsigned int W[80]; int lenW; unsigned int sizeHi,sizeLo; -} SHA_CTX; +} moz_SHA_CTX; -void SHA1_Init(SHA_CTX *ctx); -void SHA1_Update(SHA_CTX *ctx, const void *dataIn, int len); -void SHA1_Final(unsigned char hashout[20], SHA_CTX *ctx); +void moz_SHA1_Init(moz_SHA_CTX *ctx); +void moz_SHA1_Update(moz_SHA_CTX *ctx, const void *dataIn, int len); +void moz_SHA1_Final(unsigned char hashout[20], moz_SHA_CTX *ctx); + +#define git_SHA_CTX moz_SHA_CTX +#define git_SHA1_Init moz_SHA1_Init +#define git_SHA1_Update moz_SHA1_Update +#define git_SHA1_Final moz_SHA1_Final diff --git a/pack-check.c b/pack-check.c index f596bf2db5..90c33b1b84 100644 --- a/pack-check.c +++ b/pack-check.c @@ -47,7 +47,7 @@ static int verify_packfile(struct packed_git *p, { off_t index_size = p->index_size; const unsigned char *index_base = p->index_data; - SHA_CTX ctx; + git_SHA_CTX ctx; unsigned char sha1[20], *pack_sig; off_t offset = 0, pack_sig_ofs = p->pack_size - 20; uint32_t nr_objects, i; @@ -60,16 +60,16 @@ static int verify_packfile(struct packed_git *p, * immediately. */ - SHA1_Init(&ctx); + git_SHA1_Init(&ctx); while (offset < pack_sig_ofs) { unsigned int remaining; unsigned char *in = use_pack(p, w_curs, offset, &remaining); offset += remaining; if (offset > pack_sig_ofs) remaining -= (unsigned int)(offset - pack_sig_ofs); - SHA1_Update(&ctx, in, remaining); + git_SHA1_Update(&ctx, in, remaining); } - SHA1_Final(sha1, &ctx); + git_SHA1_Final(sha1, &ctx); pack_sig = use_pack(p, w_curs, pack_sig_ofs, NULL); if (hashcmp(sha1, pack_sig)) err = error("%s SHA1 checksum mismatch", @@ -135,7 +135,7 @@ int verify_pack(struct packed_git *p) { off_t index_size; const unsigned char *index_base; - SHA_CTX ctx; + git_SHA_CTX ctx; unsigned char sha1[20]; int err = 0; struct pack_window *w_curs = NULL; @@ -146,9 +146,9 @@ int verify_pack(struct packed_git *p) index_base = p->index_data; /* Verify SHA1 sum of the index file */ - SHA1_Init(&ctx); - SHA1_Update(&ctx, index_base, (unsigned int)(index_size - 20)); - SHA1_Final(sha1, &ctx); + git_SHA1_Init(&ctx); + git_SHA1_Update(&ctx, index_base, (unsigned int)(index_size - 20)); + git_SHA1_Final(sha1, &ctx); if (hashcmp(sha1, index_base + index_size - 20)) err = error("Packfile index for %s SHA1 mismatch", p->pack_name); diff --git a/pack-write.c b/pack-write.c index 939ed56362..b426006c58 100644 --- a/pack-write.c +++ b/pack-write.c @@ -25,7 +25,7 @@ char *write_idx_file(char *index_name, struct pack_idx_entry **objects, off_t last_obj_offset = 0; uint32_t array[256]; int i, fd; - SHA_CTX ctx; + git_SHA_CTX ctx; uint32_t index_version; if (nr_objects) { @@ -45,7 +45,7 @@ char *write_idx_file(char *index_name, struct pack_idx_entry **objects, if (!index_name) { static char tmpfile[PATH_MAX]; snprintf(tmpfile, sizeof(tmpfile), - "%s/tmp_idx_XXXXXX", get_object_directory()); + "%s/pack/tmp_idx_XXXXXX", get_object_directory()); fd = xmkstemp(tmpfile); index_name = xstrdup(tmpfile); } else { @@ -86,7 +86,7 @@ char *write_idx_file(char *index_name, struct pack_idx_entry **objects, sha1write(f, array, 256 * 4); /* compute the SHA1 hash of sorted object names. */ - SHA1_Init(&ctx); + git_SHA1_Init(&ctx); /* * Write the actual SHA1 entries.. @@ -99,7 +99,7 @@ char *write_idx_file(char *index_name, struct pack_idx_entry **objects, sha1write(f, &offset, 4); } sha1write(f, obj->sha1, 20); - SHA1_Update(&ctx, obj->sha1, 20); + git_SHA1_Update(&ctx, obj->sha1, 20); } if (index_version >= 2) { @@ -140,7 +140,7 @@ char *write_idx_file(char *index_name, struct pack_idx_entry **objects, sha1write(f, sha1, 20); sha1close(f, NULL, CSUM_FSYNC); - SHA1_Final(sha1, &ctx); + git_SHA1_Final(sha1, &ctx); return index_name; } @@ -168,12 +168,12 @@ void fixup_pack_header_footer(int pack_fd, off_t partial_pack_offset) { int aligned_sz, buf_sz = 8 * 1024; - SHA_CTX old_sha1_ctx, new_sha1_ctx; + git_SHA_CTX old_sha1_ctx, new_sha1_ctx; struct pack_header hdr; char *buf; - SHA1_Init(&old_sha1_ctx); - SHA1_Init(&new_sha1_ctx); + git_SHA1_Init(&old_sha1_ctx); + git_SHA1_Init(&new_sha1_ctx); if (lseek(pack_fd, 0, SEEK_SET) != 0) die("Failed seeking to start of %s: %s", pack_name, strerror(errno)); @@ -181,9 +181,9 @@ void fixup_pack_header_footer(int pack_fd, die("Unable to reread header of %s: %s", pack_name, strerror(errno)); if (lseek(pack_fd, 0, SEEK_SET) != 0) die("Failed seeking to start of %s: %s", pack_name, strerror(errno)); - SHA1_Update(&old_sha1_ctx, &hdr, sizeof(hdr)); + git_SHA1_Update(&old_sha1_ctx, &hdr, sizeof(hdr)); hdr.hdr_entries = htonl(object_count); - SHA1_Update(&new_sha1_ctx, &hdr, sizeof(hdr)); + git_SHA1_Update(&new_sha1_ctx, &hdr, sizeof(hdr)); write_or_die(pack_fd, &hdr, sizeof(hdr)); partial_pack_offset -= sizeof(hdr); @@ -198,7 +198,7 @@ void fixup_pack_header_footer(int pack_fd, break; if (n < 0) die("Failed to checksum %s: %s", pack_name, strerror(errno)); - SHA1_Update(&new_sha1_ctx, buf, n); + git_SHA1_Update(&new_sha1_ctx, buf, n); aligned_sz -= n; if (!aligned_sz) @@ -207,11 +207,11 @@ void fixup_pack_header_footer(int pack_fd, if (!partial_pack_sha1) continue; - SHA1_Update(&old_sha1_ctx, buf, n); + git_SHA1_Update(&old_sha1_ctx, buf, n); partial_pack_offset -= n; if (partial_pack_offset == 0) { unsigned char sha1[20]; - SHA1_Final(sha1, &old_sha1_ctx); + git_SHA1_Final(sha1, &old_sha1_ctx); if (hashcmp(sha1, partial_pack_sha1) != 0) die("Unexpected checksum for %s " "(disk corruption?)", pack_name); @@ -220,7 +220,7 @@ void fixup_pack_header_footer(int pack_fd, * pack, which also means making partial_pack_offset * big enough not to matter anymore. */ - SHA1_Init(&old_sha1_ctx); + git_SHA1_Init(&old_sha1_ctx); partial_pack_offset = ~partial_pack_offset; partial_pack_offset -= MSB(partial_pack_offset, 1); } @@ -228,8 +228,8 @@ void fixup_pack_header_footer(int pack_fd, free(buf); if (partial_pack_sha1) - SHA1_Final(partial_pack_sha1, &old_sha1_ctx); - SHA1_Final(new_pack_sha1, &new_sha1_ctx); + git_SHA1_Final(partial_pack_sha1, &old_sha1_ctx); + git_SHA1_Final(new_pack_sha1, &new_sha1_ctx); write_or_die(pack_fd, new_pack_sha1, 20); fsync_or_die(pack_fd, pack_name); } diff --git a/patch-id.c b/patch-id.c index 9349bc5580..871f1d20c0 100644 --- a/patch-id.c +++ b/patch-id.c @@ -1,6 +1,6 @@ #include "cache.h" -static void flush_current_id(int patchlen, unsigned char *id, SHA_CTX *c) +static void flush_current_id(int patchlen, unsigned char *id, git_SHA_CTX *c) { unsigned char result[20]; char name[50]; @@ -8,10 +8,10 @@ static void flush_current_id(int patchlen, unsigned char *id, SHA_CTX *c) if (!patchlen) return; - SHA1_Final(result, c); + git_SHA1_Final(result, c); memcpy(name, sha1_to_hex(id), 41); printf("%s %s\n", sha1_to_hex(result), name); - SHA1_Init(c); + git_SHA1_Init(c); } static int remove_space(char *line) @@ -31,10 +31,10 @@ static void generate_id_list(void) { static unsigned char sha1[20]; static char line[1000]; - SHA_CTX ctx; + git_SHA_CTX ctx; int patchlen = 0; - SHA1_Init(&ctx); + git_SHA1_Init(&ctx); while (fgets(line, sizeof(line), stdin) != NULL) { unsigned char n[20]; char *p = line; @@ -67,7 +67,7 @@ static void generate_id_list(void) /* Compute the sha without whitespace */ len = remove_space(line); patchlen += len; - SHA1_Update(&ctx, line, len); + git_SHA1_Update(&ctx, line, len); } flush_current_id(patchlen, sha1, &ctx); } diff --git a/ppc/sha1.c b/ppc/sha1.c index 738e36c1e8..ec6a1926d4 100644 --- a/ppc/sha1.c +++ b/ppc/sha1.c @@ -10,10 +10,10 @@ #include <string.h> #include "sha1.h" -extern void sha1_core(uint32_t *hash, const unsigned char *p, - unsigned int nblocks); +extern void ppc_sha1_core(uint32_t *hash, const unsigned char *p, + unsigned int nblocks); -int SHA1_Init(SHA_CTX *c) +int ppc_SHA1_Init(ppc_SHA_CTX *c) { c->hash[0] = 0x67452301; c->hash[1] = 0xEFCDAB89; @@ -25,7 +25,7 @@ int SHA1_Init(SHA_CTX *c) return 0; } -int SHA1_Update(SHA_CTX *c, const void *ptr, unsigned long n) +int ppc_SHA1_Update(ppc_SHA_CTX *c, const void *ptr, unsigned long n) { unsigned long nb; const unsigned char *p = ptr; @@ -38,12 +38,12 @@ int SHA1_Update(SHA_CTX *c, const void *ptr, unsigned long n) nb = n; memcpy(&c->buf.b[c->cnt], p, nb); if ((c->cnt += nb) == 64) { - sha1_core(c->hash, c->buf.b, 1); + ppc_sha1_core(c->hash, c->buf.b, 1); c->cnt = 0; } } else { nb = n >> 6; - sha1_core(c->hash, p, nb); + ppc_sha1_core(c->hash, p, nb); nb <<= 6; } n -= nb; @@ -52,7 +52,7 @@ int SHA1_Update(SHA_CTX *c, const void *ptr, unsigned long n) return 0; } -int SHA1_Final(unsigned char *hash, SHA_CTX *c) +int ppc_SHA1_Final(unsigned char *hash, ppc_SHA_CTX *c) { unsigned int cnt = c->cnt; @@ -60,13 +60,13 @@ int SHA1_Final(unsigned char *hash, SHA_CTX *c) if (cnt > 56) { if (cnt < 64) memset(&c->buf.b[cnt], 0, 64 - cnt); - sha1_core(c->hash, c->buf.b, 1); + ppc_sha1_core(c->hash, c->buf.b, 1); cnt = 0; } if (cnt < 56) memset(&c->buf.b[cnt], 0, 56 - cnt); c->buf.l[7] = c->len; - sha1_core(c->hash, c->buf.b, 1); + ppc_sha1_core(c->hash, c->buf.b, 1); memcpy(hash, c->hash, 20); return 0; } diff --git a/ppc/sha1.h b/ppc/sha1.h index c3c51aa4d4..c405f734c2 100644 --- a/ppc/sha1.h +++ b/ppc/sha1.h @@ -5,7 +5,7 @@ */ #include <stdint.h> -typedef struct sha_context { +typedef struct { uint32_t hash[5]; uint32_t cnt; uint64_t len; @@ -13,8 +13,13 @@ typedef struct sha_context { unsigned char b[64]; uint64_t l[8]; } buf; -} SHA_CTX; +} ppc_SHA_CTX; -int SHA1_Init(SHA_CTX *c); -int SHA1_Update(SHA_CTX *c, const void *p, unsigned long n); -int SHA1_Final(unsigned char *hash, SHA_CTX *c); +int ppc_SHA1_Init(ppc_SHA_CTX *c); +int ppc_SHA1_Update(ppc_SHA_CTX *c, const void *p, unsigned long n); +int ppc_SHA1_Final(unsigned char *hash, ppc_SHA_CTX *c); + +#define git_SHA_CTX ppc_SHA_CTX +#define git_SHA1_Init ppc_SHA1_Init +#define git_SHA1_Update ppc_SHA1_Update +#define git_SHA1_Final ppc_SHA1_Final diff --git a/ppc/sha1ppc.S b/ppc/sha1ppc.S index f132696ee7..1711eef6e7 100644 --- a/ppc/sha1ppc.S +++ b/ppc/sha1ppc.S @@ -162,8 +162,8 @@ add RE(t),RE(t),%r0; rotlwi RB(t),RB(t),30 STEPUP4(fn, (t)+12, (s)+12,); \ STEPUP4(fn, (t)+16, (s)+16, loadk) - .globl sha1_core -sha1_core: + .globl ppc_sha1_core +ppc_sha1_core: stwu %r1,-80(%r1) stmw %r13,4(%r1) @@ -5,6 +5,7 @@ #include "revision.h" #include "string-list.h" #include "mailmap.h" +#include "log-tree.h" static char *user_format; @@ -233,7 +234,7 @@ static char *get_header(const struct commit *commit, const char *key) static char *replace_encoding_header(char *buf, const char *encoding) { - struct strbuf tmp; + struct strbuf tmp = STRBUF_INIT; size_t start, len; char *cp = buf; @@ -249,7 +250,6 @@ static char *replace_encoding_header(char *buf, const char *encoding) return buf; /* should not happen but be defensive */ len = cp + 1 - (buf + start); - strbuf_init(&tmp, 0); strbuf_attach(&tmp, buf, strlen(buf), strlen(buf) + 1); if (is_encoding_utf8(encoding)) { /* we have re-coded to UTF-8; drop the header */ @@ -481,6 +481,23 @@ static void parse_commit_header(struct format_commit_context *context) context->commit_header_parsed = 1; } +static void format_decoration(struct strbuf *sb, const struct commit *commit) +{ + struct name_decoration *d; + const char *prefix = " ("; + + load_ref_decorations(); + d = lookup_decoration(&name_decoration, &commit->object); + while (d) { + strbuf_addstr(sb, prefix); + prefix = ", "; + strbuf_addstr(sb, d->name); + d = d->next; + } + if (prefix[0] == ',') + strbuf_addch(sb, ')'); +} + static size_t format_commit_item(struct strbuf *sb, const char *placeholder, void *context) { @@ -573,6 +590,9 @@ static size_t format_commit_item(struct strbuf *sb, const char *placeholder, ? '<' : '>'); return 1; + case 'd': + format_decoration(sb, commit); + return 1; } /* For the rest we have to parse the commit header. */ diff --git a/read-cache.c b/read-cache.c index 5150c1e14b..c229fd4d0d 100644 --- a/read-cache.c +++ b/read-cache.c @@ -13,6 +13,7 @@ #include "diff.h" #include "diffcore.h" #include "revision.h" +#include "blob.h" /* Index extensions. * @@ -511,6 +512,14 @@ static struct cache_entry *create_alias_ce(struct cache_entry *ce, struct cache_ return new; } +static void record_intent_to_add(struct cache_entry *ce) +{ + unsigned char sha1[20]; + if (write_sha1_file("", 0, blob_type, sha1)) + die("cannot create an empty blob in the object database"); + hashcpy(ce->sha1, sha1); +} + int add_to_index(struct index_state *istate, const char *path, struct stat *st, int flags) { int size, namelen, was_same; @@ -519,6 +528,9 @@ int add_to_index(struct index_state *istate, const char *path, struct stat *st, unsigned ce_option = CE_MATCH_IGNORE_VALID|CE_MATCH_RACY_IS_DIRTY; int verbose = flags & (ADD_CACHE_VERBOSE | ADD_CACHE_PRETEND); int pretend = flags & ADD_CACHE_PRETEND; + int intent_only = flags & ADD_CACHE_INTENT; + int add_option = (ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE| + (intent_only ? ADD_CACHE_NEW_ONLY : 0)); if (!S_ISREG(st_mode) && !S_ISLNK(st_mode) && !S_ISDIR(st_mode)) return error("%s: can only add regular files, symbolic links or git-directories", path); @@ -532,7 +544,8 @@ int add_to_index(struct index_state *istate, const char *path, struct stat *st, ce = xcalloc(1, size); memcpy(ce->name, path, namelen); ce->ce_flags = namelen; - fill_stat_cache_info(ce, st); + if (!intent_only) + fill_stat_cache_info(ce, st); if (trust_executable_bit && has_symlinks) ce->ce_mode = create_ce_mode(st_mode); @@ -555,8 +568,12 @@ int add_to_index(struct index_state *istate, const char *path, struct stat *st, alias->ce_flags |= CE_ADDED; return 0; } - if (index_path(ce->sha1, path, st, 1)) - return error("unable to index file %s", path); + if (!intent_only) { + if (index_path(ce->sha1, path, st, 1)) + return error("unable to index file %s", path); + } else + record_intent_to_add(ce); + if (ignore_case && alias && different_name(ce, alias)) ce = create_alias_ce(ce, alias); ce->ce_flags |= CE_ADDED; @@ -569,7 +586,7 @@ int add_to_index(struct index_state *istate, const char *path, struct stat *st, if (pretend) ; - else if (add_index_entry(istate, ce, ADD_CACHE_OK_TO_ADD|ADD_CACHE_OK_TO_REPLACE)) + else if (add_index_entry(istate, ce, add_option)) return error("unable to add %s to index",path); if (verbose && !was_same) printf("add '%s'\n", path); @@ -591,8 +608,10 @@ struct cache_entry *make_cache_entry(unsigned int mode, int size, len; struct cache_entry *ce; - if (!verify_path(path)) + if (!verify_path(path)) { + error("Invalid path '%s'", path); return NULL; + } len = strlen(path); size = cache_entry_size(len); @@ -848,13 +867,15 @@ static int add_index_entry_with_check(struct index_state *istate, struct cache_e int ok_to_add = option & ADD_CACHE_OK_TO_ADD; int ok_to_replace = option & ADD_CACHE_OK_TO_REPLACE; int skip_df_check = option & ADD_CACHE_SKIP_DFCHECK; + int new_only = option & ADD_CACHE_NEW_ONLY; cache_tree_invalidate_path(istate->cache_tree, ce->name); pos = index_name_pos(istate, ce->name, ce->ce_flags); /* existing match? Just replace it. */ if (pos >= 0) { - replace_index_entry(istate, pos, ce); + if (!new_only) + replace_index_entry(istate, pos, ce); return 0; } pos = -pos-1; @@ -874,7 +895,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)) - return -1; + return error("Invalid path '%s'", ce->name); if (!skip_df_check && check_file_directory_conflict(istate, ce, pos, ok_to_replace)) { @@ -1072,16 +1093,16 @@ struct cache_entry *refresh_cache_entry(struct cache_entry *ce, int really) static int verify_hdr(struct cache_header *hdr, unsigned long size) { - SHA_CTX c; + git_SHA_CTX c; unsigned char sha1[20]; if (hdr->hdr_signature != htonl(CACHE_SIGNATURE)) return error("bad signature"); if (hdr->hdr_version != htonl(2)) return error("bad index version"); - SHA1_Init(&c); - SHA1_Update(&c, hdr, size - 20); - SHA1_Final(sha1, &c); + git_SHA1_Init(&c); + git_SHA1_Update(&c, hdr, size - 20); + git_SHA1_Final(sha1, &c); if (hashcmp(sha1, (unsigned char *)hdr + size - 20)) return error("bad index file sha1 signature"); return 0; @@ -1253,6 +1274,7 @@ int discard_index(struct index_state *istate) istate->cache_nr = 0; istate->cache_changed = 0; istate->timestamp = 0; + istate->name_hash_initialized = 0; free_hash(&istate->name_hash); cache_tree_free(&(istate->cache_tree)); free(istate->alloc); @@ -1277,11 +1299,11 @@ int unmerged_index(const struct index_state *istate) static unsigned char write_buffer[WRITE_BUFFER_SIZE]; static unsigned long write_buffer_len; -static int ce_write_flush(SHA_CTX *context, int fd) +static int ce_write_flush(git_SHA_CTX *context, int fd) { unsigned int buffered = write_buffer_len; if (buffered) { - SHA1_Update(context, write_buffer, buffered); + git_SHA1_Update(context, write_buffer, buffered); if (write_in_full(fd, write_buffer, buffered) != buffered) return -1; write_buffer_len = 0; @@ -1289,7 +1311,7 @@ static int ce_write_flush(SHA_CTX *context, int fd) return 0; } -static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len) +static int ce_write(git_SHA_CTX *context, int fd, void *data, unsigned int len) { while (len) { unsigned int buffered = write_buffer_len; @@ -1311,7 +1333,7 @@ static int ce_write(SHA_CTX *context, int fd, void *data, unsigned int len) return 0; } -static int write_index_ext_header(SHA_CTX *context, int fd, +static int write_index_ext_header(git_SHA_CTX *context, int fd, unsigned int ext, unsigned int sz) { ext = htonl(ext); @@ -1320,13 +1342,13 @@ static int write_index_ext_header(SHA_CTX *context, int fd, (ce_write(context, fd, &sz, 4) < 0)) ? -1 : 0; } -static int ce_flush(SHA_CTX *context, int fd) +static int ce_flush(git_SHA_CTX *context, int fd) { unsigned int left = write_buffer_len; if (left) { write_buffer_len = 0; - SHA1_Update(context, write_buffer, left); + git_SHA1_Update(context, write_buffer, left); } /* Flush first if not enough space for SHA1 signature */ @@ -1337,7 +1359,7 @@ static int ce_flush(SHA_CTX *context, int fd) } /* Append the SHA1 signature at the end */ - SHA1_Final(write_buffer + left, context); + git_SHA1_Final(write_buffer + left, context); left += 20; return (write_in_full(fd, write_buffer, left) != left) ? -1 : 0; } @@ -1391,7 +1413,7 @@ static void ce_smudge_racily_clean_entry(struct cache_entry *ce) } } -static int ce_write_entry(SHA_CTX *c, int fd, struct cache_entry *ce) +static int ce_write_entry(git_SHA_CTX *c, int fd, struct cache_entry *ce) { int size = ondisk_ce_size(ce); struct ondisk_cache_entry *ondisk = xcalloc(1, size); @@ -1415,7 +1437,7 @@ static int ce_write_entry(SHA_CTX *c, int fd, struct cache_entry *ce) int write_index(const struct index_state *istate, int newfd) { - SHA_CTX c; + git_SHA_CTX c; struct cache_header hdr; int i, err, removed; struct cache_entry **cache = istate->cache; @@ -1429,7 +1451,7 @@ int write_index(const struct index_state *istate, int newfd) hdr.hdr_version = htonl(2); hdr.hdr_entries = htonl(entries - removed); - SHA1_Init(&c); + git_SHA1_Init(&c); if (ce_write(&c, newfd, &hdr, sizeof(hdr)) < 0) return -1; @@ -1445,9 +1467,8 @@ int write_index(const struct index_state *istate, int newfd) /* Write extension data here */ if (istate->cache_tree) { - struct strbuf sb; + struct strbuf sb = STRBUF_INIT; - strbuf_init(&sb, 0); cache_tree_write(&sb, istate->cache_tree); err = write_index_ext_header(&c, newfd, CACHE_EXT_TREE, sb.len) < 0 || ce_write(&c, newfd, sb.buf, sb.len) < 0; @@ -245,7 +245,7 @@ static void read_branches_file(struct remote *remote) { const char *slash = strchr(remote->name, '/'); char *frag; - struct strbuf branch; + struct strbuf branch = STRBUF_INIT; int n = slash ? slash - remote->name : 1000; FILE *f = fopen(git_path("branches/%.*s", n, remote->name), "r"); char *s, *p; @@ -283,7 +283,6 @@ static void read_branches_file(struct remote *remote) * #branch specified. The "master" (or specified) branch is * fetched and stored in the local branch of the same name. */ - strbuf_init(&branch, 0); frag = strchr(p, '#'); if (frag) { *(frag++) = '\0'; @@ -342,13 +341,14 @@ static int handle_config(const char *key, const char *value, void *cb) if (prefixcmp(key, "remote.")) return 0; name = key + 7; + if (*name == '/') { + warning("Config remote shorthand cannot begin with '/': %s", + name); + return 0; + } subkey = strrchr(name, '.'); if (!subkey) return error("Config with no key for remote %s", name); - if (*subkey == '/') { - warning("Config remote shorthand cannot begin with '/': %s", name); - return 0; - } remote = make_remote(name, subkey - name); if (!strcmp(subkey, ".mirror")) remote->mirror = git_config_bool(key, value); @@ -455,7 +455,7 @@ static int verify_refname(char *name, int is_glob) * and dst pointers are always freeable pointers as well * as the refspec pointer itself. */ -void free_refspecs(struct refspec *refspec, int nr_refspec) +static void free_refspecs(struct refspec *refspec, int nr_refspec) { int i; @@ -613,7 +613,7 @@ 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) +static struct refspec *parse_push_refspec(int nr_refspec, const char **refspec) { return parse_refspec_internal(nr_refspec, refspec, 0, 0); } @@ -751,8 +751,7 @@ int remote_find_tracking(struct remote *remote, struct refspec *refspec) struct ref *alloc_ref(unsigned namelen) { - struct ref *ret = xmalloc(sizeof(struct ref) + namelen); - memset(ret, 0, sizeof(struct ref) + namelen); + struct ref *ret = xcalloc(1, sizeof(struct ref) + namelen); return ret; } @@ -783,7 +782,7 @@ struct ref *copy_ref_list(const struct ref *ref) return ret; } -void free_ref(struct ref *ref) +static void free_ref(struct ref *ref) { if (!ref) return; @@ -77,8 +77,6 @@ void 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); -struct refspec *parse_push_refspec(int nr_refspec, const char **refspec); -void free_refspecs(struct refspec *refspec, int nr_refspec); int match_refs(struct ref *src, struct ref *dst, struct ref ***dst_tail, int nr_refspec, const char **refspec, int all); @@ -73,10 +73,13 @@ static int write_rr(struct string_list *rr, int out_fd) static int handle_file(const char *path, unsigned char *sha1, const char *output) { - SHA_CTX ctx; + git_SHA_CTX ctx; char buf[1024]; - int hunk = 0, hunk_no = 0; - struct strbuf one, two; + int hunk_no = 0; + enum { + RR_CONTEXT = 0, RR_SIDE_1, RR_SIDE_2, RR_ORIGINAL, + } hunk = RR_CONTEXT; + struct strbuf one = STRBUF_INIT, two = STRBUF_INIT; FILE *f = fopen(path, "r"); FILE *out = NULL; @@ -92,26 +95,28 @@ static int handle_file(const char *path, } if (sha1) - SHA1_Init(&ctx); + git_SHA1_Init(&ctx); - strbuf_init(&one, 0); - strbuf_init(&two, 0); while (fgets(buf, sizeof(buf), f)) { if (!prefixcmp(buf, "<<<<<<< ")) { - if (hunk) + if (hunk != RR_CONTEXT) goto bad; - hunk = 1; + hunk = RR_SIDE_1; + } else if (!prefixcmp(buf, "|||||||") && isspace(buf[7])) { + if (hunk != RR_SIDE_1) + goto bad; + hunk = RR_ORIGINAL; } else if (!prefixcmp(buf, "=======") && isspace(buf[7])) { - if (hunk != 1) + if (hunk != RR_SIDE_1 && hunk != RR_ORIGINAL) goto bad; - hunk = 2; + hunk = RR_SIDE_2; } else if (!prefixcmp(buf, ">>>>>>> ")) { - if (hunk != 2) + if (hunk != RR_SIDE_2) goto bad; if (strbuf_cmp(&one, &two) > 0) strbuf_swap(&one, &two); hunk_no++; - hunk = 0; + hunk = RR_CONTEXT; if (out) { fputs("<<<<<<<\n", out); fwrite(one.buf, one.len, 1, out); @@ -120,16 +125,18 @@ static int handle_file(const char *path, fputs(">>>>>>>\n", out); } if (sha1) { - SHA1_Update(&ctx, one.buf ? one.buf : "", + git_SHA1_Update(&ctx, one.buf ? one.buf : "", one.len + 1); - SHA1_Update(&ctx, two.buf ? two.buf : "", + git_SHA1_Update(&ctx, two.buf ? two.buf : "", two.len + 1); } strbuf_reset(&one); strbuf_reset(&two); - } else if (hunk == 1) + } else if (hunk == RR_SIDE_1) strbuf_addstr(&one, buf); - else if (hunk == 2) + else if (hunk == RR_ORIGINAL) + ; /* discard */ + else if (hunk == RR_SIDE_2) strbuf_addstr(&two, buf); else if (out) fputs(buf, out); @@ -145,8 +152,8 @@ static int handle_file(const char *path, if (out) fclose(out); if (sha1) - SHA1_Final(sha1, &ctx); - if (hunk) { + git_SHA1_Final(sha1, &ctx); + if (hunk != RR_CONTEXT) { if (output) unlink(output); return error("Could not parse conflict hunks in %s", path); @@ -319,7 +326,6 @@ static int git_rerere_config(const char *var, const char *value, void *cb) static int is_rerere_enabled(void) { - struct stat st; const char *rr_cache; int rr_cache_exists; @@ -327,7 +333,7 @@ static int is_rerere_enabled(void) return 0; rr_cache = git_path("rr-cache"); - rr_cache_exists = !stat(rr_cache, &st) && S_ISDIR(st.st_mode); + rr_cache_exists = is_directory(rr_cache); if (rerere_enabled < 0) return rr_cache_exists; diff --git a/revision.c b/revision.c index 499f0e0225..2f646deab0 100644 --- a/revision.c +++ b/revision.c @@ -1793,26 +1793,6 @@ static struct commit *get_revision_internal(struct rev_info *revs) return c; } - if (revs->reverse) { - int limit = -1; - - if (0 <= revs->max_count) { - limit = revs->max_count; - if (0 < revs->skip_count) - limit += revs->skip_count; - } - l = NULL; - while ((c = get_revision_1(revs))) { - commit_list_insert(c, &l); - if ((0 < limit) && !--limit) - break; - } - revs->commits = l; - revs->reverse = 0; - revs->max_count = -1; - c = NULL; - } - /* * Now pick up what they want to give us */ @@ -1885,7 +1865,23 @@ static struct commit *get_revision_internal(struct rev_info *revs) struct commit *get_revision(struct rev_info *revs) { - struct commit *c = get_revision_internal(revs); + struct commit *c; + struct commit_list *reversed; + + if (revs->reverse) { + reversed = NULL; + while ((c = get_revision_internal(revs))) { + commit_list_insert(c, &reversed); + } + revs->commits = reversed; + revs->reverse = 0; + revs->reverse_output_stage = 1; + } + + if (revs->reverse_output_stage) + return pop_commit(&revs->commits); + + c = get_revision_internal(revs); if (c && revs->graph) graph_update(revs->graph, c); return c; diff --git a/revision.h b/revision.h index fc23522b38..2fdb2dd0ff 100644 --- a/revision.h +++ b/revision.h @@ -54,6 +54,7 @@ struct rev_info { rewrite_parents:1, print_parents:1, reverse:1, + reverse_output_stage:1, cherry_pick:1, first_parent_only:1; diff --git a/run-command.c b/run-command.c index caab374577..c90cdc50e3 100644 --- a/run-command.c +++ b/run-command.c @@ -273,14 +273,6 @@ int run_command_v_opt(const char **argv, int opt) return run_command(&cmd); } -int run_command_v_opt_cd(const char **argv, int opt, const char *dir) -{ - struct child_process cmd; - prepare_run_command_v_opt(&cmd, argv, opt); - cmd.dir = dir; - return run_command(&cmd); -} - int run_command_v_opt_cd_env(const char **argv, int opt, const char *dir, const char *const *env) { struct child_process cmd; diff --git a/run-command.h b/run-command.h index 4f2b7d7d40..a8b0c209e9 100644 --- a/run-command.h +++ b/run-command.h @@ -53,7 +53,6 @@ int run_command(struct child_process *); #define RUN_GIT_CMD 2 /*If this is to be git sub-command */ #define RUN_COMMAND_STDOUT_TO_STDERR 4 int run_command_v_opt(const char **argv, int opt); -int run_command_v_opt_cd(const char **argv, int opt, const char *dir); /* * env (the environment) is to be formatted like environ: "VAR=VALUE". @@ -110,9 +110,7 @@ const char *prefix_path(const char *prefix, int len, const char *path) if (strncmp(sanitized, work_tree, len) || (sanitized[len] != '\0' && sanitized[len] != '/')) { error_out: - error("'%s' is outside repository", orig); - free(sanitized); - return NULL; + die("'%s' is outside repository", orig); } if (sanitized[len] == '/') len++; @@ -216,10 +214,7 @@ const char **get_pathspec(const char *prefix, const char **pathspec) prefixlen = prefix ? strlen(prefix) : 0; while (*src) { const char *p = prefix_path(prefix, prefixlen, *src); - if (p) - *(dst++) = p; - else - exit(128); /* error message already given */ + *(dst++) = p; src++; } *dst = NULL; diff --git a/sha1_file.c b/sha1_file.c index 9ee1ed16ad..70bb453be2 100644 --- a/sha1_file.c +++ b/sha1_file.c @@ -99,7 +99,11 @@ int safe_create_leading_directories(char *path) pos = strchr(pos, '/'); if (!pos) break; - *pos = 0; + while (*++pos == '/') + ; + if (!*pos) + break; + *--pos = '\0'; if (!stat(path, &st)) { /* path exists */ if (!S_ISDIR(st.st_mode)) { @@ -250,7 +254,6 @@ static void read_info_alternates(const char * alternates, int depth); */ static int link_alt_odb_entry(const char * entry, int len, const char * relative_base, int depth) { - struct stat st; const char *objdir = get_object_directory(); struct alternate_object_database *ent; struct alternate_object_database *alt; @@ -281,7 +284,7 @@ static int link_alt_odb_entry(const char * entry, int len, const char * relative ent->base[pfxlen] = ent->base[entlen-1] = 0; /* Detect cases where alternate disappeared */ - if (stat(ent->base, &st) || !S_ISDIR(st.st_mode)) { + if (!is_directory(ent->base)) { error("object directory %s does not exist; " "check .git/objects/info/alternates.", ent->base); @@ -394,6 +397,16 @@ void add_to_alternates_file(const char *reference) link_alt_odb_entries(alt, alt + strlen(alt), '\n', NULL, 0); } +void foreach_alt_odb(alt_odb_fn fn, void *cb) +{ + struct alternate_object_database *ent; + + prepare_alt_odb(); + for (ent = alt_odb_list; ent; ent = ent->next) + if (fn(ent, cb)) + return; +} + void prepare_alt_odb(void) { const char *alt; @@ -1558,11 +1571,9 @@ static void *cache_or_unpack_entry(struct packed_git *p, off_t base_offset, struct delta_base_cache_entry *ent = delta_base_cache + hash; ret = ent->data; - if (ret && ent->p == p && ent->base_offset == base_offset) - goto found_cache_entry; - return unpack_entry(p, base_offset, type, base_size); + if (!ret || ent->p != p || ent->base_offset != base_offset) + return unpack_entry(p, base_offset, type, base_size); -found_cache_entry: if (!keep_cache) { ent->data = NULL; ent->lru.next->prev = ent->lru.prev; @@ -2119,16 +2130,16 @@ static void write_sha1_file_prepare(const void *buf, unsigned long len, const char *type, unsigned char *sha1, char *hdr, int *hdrlen) { - SHA_CTX c; + git_SHA_CTX c; /* Generate the header */ *hdrlen = sprintf(hdr, "%s %lu", type, len)+1; /* Sha1.. */ - SHA1_Init(&c); - SHA1_Update(&c, hdr, *hdrlen); - SHA1_Update(&c, buf, len); - SHA1_Final(sha1, &c); + git_SHA1_Init(&c); + git_SHA1_Update(&c, hdr, *hdrlen); + git_SHA1_Update(&c, buf, len); + git_SHA1_Final(sha1, &c); } /* @@ -2136,7 +2147,9 @@ static void write_sha1_file_prepare(const void *buf, unsigned long len, */ int move_temp_to_file(const char *tmpfile, const char *filename) { - int ret = link(tmpfile, filename); + int ret = 0; + if (link(tmpfile, filename)) + ret = errno; /* * Coda hack - coda doesn't like cross-directory links, @@ -2320,6 +2333,7 @@ int force_object_loose(const unsigned char *sha1, time_t mtime) enum object_type type; char hdr[32]; int hdrlen; + int ret; if (has_loose_object(sha1)) return 0; @@ -2327,7 +2341,10 @@ int force_object_loose(const unsigned char *sha1, time_t mtime) if (!buf) return error("cannot read sha1_file for %s", sha1_to_hex(sha1)); hdrlen = sprintf(hdr, "%s %lu", typename(type), len) + 1; - return write_loose_object(sha1, hdr, hdrlen, buf, len, mtime); + ret = write_loose_object(sha1, hdr, hdrlen, buf, len, mtime); + free(buf); + + return ret; } int has_pack_index(const unsigned char *sha1) @@ -2373,8 +2390,7 @@ static int index_mem(unsigned char *sha1, void *buf, size_t size, * Convert blobs to git internal format */ if ((type == OBJ_BLOB) && path) { - struct strbuf nbuf; - strbuf_init(&nbuf, 0); + struct strbuf nbuf = STRBUF_INIT; if (convert_to_git(path, buf, size, &nbuf, write_object ? safe_crlf : 0)) { buf = strbuf_detach(&nbuf, &size); @@ -2398,8 +2414,7 @@ int index_fd(unsigned char *sha1, int fd, struct stat *st, int write_object, size_t size = xsize_t(st->st_size); if (!S_ISREG(st->st_mode)) { - struct strbuf sbuf; - strbuf_init(&sbuf, 0); + struct strbuf sbuf = STRBUF_INIT; if (strbuf_read(&sbuf, fd, 4096) >= 0) ret = index_mem(sha1, sbuf.buf, sbuf.len, write_object, type, path); diff --git a/t/lib-git-svn.sh b/t/lib-git-svn.sh index c526eedd62..67c431d4eb 100644 --- a/t/lib-git-svn.sh +++ b/t/lib-git-svn.sh @@ -138,3 +138,20 @@ close $wr or die $!; close $rd or die $!; EOF } + +require_svnserve () { + if test -z "$SVNSERVE_PORT" + then + say 'skipping svnserve test. (set $SVNSERVE_PORT to enable)' + test_done + exit + fi +} + +start_svnserve () { + svnserve --listen-port $SVNSERVE_PORT \ + --root "$rawsvnrepo" \ + --listen-once \ + --listen-host 127.0.0.1 & +} + diff --git a/t/t0001-init.sh b/t/t0001-init.sh index 620da5b320..5ac0a273a9 100755 --- a/t/t0001-init.sh +++ b/t/t0001-init.sh @@ -167,4 +167,36 @@ test_expect_success 'init with --template (blank)' ' ! test -f template-blank/.git/info/exclude ' +test_expect_success 'init --bare/--shared overrides system/global config' ' + ( + HOME="`pwd`" && + export HOME && + test_config="$HOME"/.gitconfig && + unset GIT_CONFIG_NOGLOBAL && + git config -f "$test_config" core.bare false && + git config -f "$test_config" core.sharedRepository 0640 && + mkdir init-bare-shared-override && + cd init-bare-shared-override && + git init --bare --shared=0666 + ) && + check_config init-bare-shared-override true unset && + test x0666 = \ + x`git config -f init-bare-shared-override/config core.sharedRepository` +' + +test_expect_success 'init honors global core.sharedRepository' ' + ( + HOME="`pwd`" && + export HOME && + test_config="$HOME"/.gitconfig && + unset GIT_CONFIG_NOGLOBAL && + git config -f "$test_config" core.sharedRepository 0666 && + mkdir shared-honor-global && + cd shared-honor-global && + git init + ) && + test x0666 = \ + x`git config -f shared-honor-global/.git/config core.sharedRepository` +' + test_done diff --git a/t/t0002-gitfile.sh b/t/t0002-gitfile.sh index 4db4ac44c9..cb144258cc 100755 --- a/t/t0002-gitfile.sh +++ b/t/t0002-gitfile.sh @@ -32,7 +32,7 @@ test_expect_success 'bad setup: invalid .git file format' ' echo "git rev-parse accepted an invalid .git file" false fi && - if ! grep -qe "Invalid gitfile format" .err + if ! grep "Invalid gitfile format" .err then echo "git rev-parse returned wrong error" false @@ -46,7 +46,7 @@ test_expect_success 'bad setup: invalid .git file path' ' echo "git rev-parse accepted an invalid .git file path" false fi && - if ! grep -qe "Not a git repository" .err + if ! grep "Not a git repository" .err then echo "git rev-parse returned wrong error" false diff --git a/t/t0003-attributes.sh b/t/t0003-attributes.sh index 3d8e06a20f..1c77192eb3 100755 --- a/t/t0003-attributes.sh +++ b/t/t0003-attributes.sh @@ -47,6 +47,23 @@ test_expect_success 'attribute test' ' ' +test_expect_success 'attribute test: read paths from stdin' ' + + cat <<EOF > expect +f: test: f +a/f: test: f +a/c/f: test: f +a/g: test: a/g +a/b/g: test: a/b/g +b/g: test: unspecified +a/b/h: test: a/b/h +a/b/d/g: test: a/b/d/* +EOF + + sed -e "s/:.*//" < expect | git check-attr --stdin test > actual && + test_cmp expect actual +' + test_expect_success 'root subdir attribute test' ' attr_check a/i a/i && diff --git a/t/t0024-crlf-archive.sh b/t/t0024-crlf-archive.sh new file mode 100755 index 0000000000..e5330395fc --- /dev/null +++ b/t/t0024-crlf-archive.sh @@ -0,0 +1,46 @@ +#!/bin/sh + +test_description='respect crlf in git archive' + +. ./test-lib.sh +UNZIP=${UNZIP:-unzip} + +test_expect_success setup ' + + git config core.autocrlf true + + printf "CRLF line ending\r\nAnd another\r\n" > sample && + git add sample && + + test_tick && + git commit -m Initial + +' + +test_expect_success 'tar archive' ' + + git archive --format=tar HEAD | + ( mkdir untarred && cd untarred && "$TAR" -xf - ) + + test_cmp sample untarred/sample + +' + +"$UNZIP" -v >/dev/null 2>&1 +if [ $? -eq 127 ]; then + echo "Skipping ZIP test, because unzip was not found" + test_done + exit +fi + +test_expect_success 'zip archive' ' + + git archive --format=zip HEAD >test.zip && + + ( mkdir unzipped && cd unzipped && unzip ../test.zip ) && + + test_cmp sample unzipped/sample + +' + +test_done diff --git a/t/t1300-repo-config.sh b/t/t1300-repo-config.sh index 64567fb94d..11b82f43dd 100755 --- a/t/t1300-repo-config.sh +++ b/t/t1300-repo-config.sh @@ -741,4 +741,14 @@ test_expect_success 'symlinked configuration' ' ' +test_expect_success 'check split_cmdline return' " + git config alias.split-cmdline-fix 'echo \"' && + test_must_fail git split-cmdline-fix && + echo foo > foo && + git add foo && + git commit -m 'initial commit' && + git config branch.master.mergeoptions 'echo \"' && + test_must_fail git merge master + " + test_done diff --git a/t/t1301-shared-repo.sh b/t/t1301-shared-repo.sh index dc85e8b60a..2275caa317 100755 --- a/t/t1301-shared-repo.sh +++ b/t/t1301-shared-repo.sh @@ -7,6 +7,9 @@ test_description='Test shared repository initialization' . ./test-lib.sh +# Remove a default ACL from the test dir if possible. +setfacl -k . 2>/dev/null + # User must have read permissions to the repo -> failure on --shared=0400 test_expect_success 'shared = 0400 (faulty permission u-w)' ' mkdir sub && ( diff --git a/t/t1501-worktree.sh b/t/t1501-worktree.sh index c039ee3fd8..f6a6f839a1 100755 --- a/t/t1501-worktree.sh +++ b/t/t1501-worktree.sh @@ -171,7 +171,7 @@ test_expect_success 'git diff' ' test_expect_success 'git grep' ' (cd repo.git/work/sub && - GIT_DIR=../.. GIT_WORK_TREE=.. git grep -l changed | grep -q dir/tracked) + GIT_DIR=../.. GIT_WORK_TREE=.. git grep -l changed | grep dir/tracked) ' test_done diff --git a/t/t2203-add-intent.sh b/t/t2203-add-intent.sh new file mode 100755 index 0000000000..d4de35ea06 --- /dev/null +++ b/t/t2203-add-intent.sh @@ -0,0 +1,36 @@ +#!/bin/sh + +test_description='Intent to add' + +. ./test-lib.sh + +test_expect_success 'intent to add' ' + echo hello >file && + echo hello >elif && + git add -N file && + git add elif +' + +test_expect_success 'check result of "add -N"' ' + git ls-files -s file >actual && + empty=$(git hash-object --stdin </dev/null) && + echo "100644 $empty 0 file" >expect && + test_cmp expect actual +' + +test_expect_success 'intent to add is just an ordinary empty blob' ' + git add -u && + git ls-files -s file >actual && + git ls-files -s elif | sed -e "s/elif/file/" >expect && + test_cmp expect actual +' + +test_expect_success 'intent to add does not clobber existing paths' ' + git add -N file elif && + empty=$(git hash-object --stdin </dev/null) && + git ls-files -s >actual && + ! grep "$empty" actual +' + +test_done + diff --git a/t/t3030-merge-recursive.sh b/t/t3030-merge-recursive.sh index de0cdb1cf4..0de613dc53 100755 --- a/t/t3030-merge-recursive.sh +++ b/t/t3030-merge-recursive.sh @@ -535,4 +535,15 @@ test_expect_success 'reset and bind merge' ' ' +test_expect_success 'merge removes empty directories' ' + + git reset --hard master && + git checkout -b rm && + git rm d/e && + git commit -mremoved-d/e && + git checkout master && + git merge -s recursive rm && + test_must_fail test -d d +' + test_done diff --git a/t/t3404-rebase-interactive.sh b/t/t3404-rebase-interactive.sh index e0ded197ec..7d10a27f1d 100755 --- a/t/t3404-rebase-interactive.sh +++ b/t/t3404-rebase-interactive.sh @@ -419,4 +419,15 @@ test_expect_success 'rebase with a file named HEAD in worktree' ' ' +test_expect_success 'do "noop" when there is nothing to cherry-pick' ' + + git checkout -b branch4 HEAD && + GIT_EDITOR=: git commit --amend \ + --author="Somebody else <somebody@else.com>" + test $(git rev-parse branch3) != $(git rev-parse branch4) && + git rebase -i branch3 && + test $(git rev-parse branch3) = $(git rev-parse branch4) + +' + test_done diff --git a/t/t3409-rebase-hook.sh b/t/t3409-rebase-hook.sh new file mode 100755 index 0000000000..1f1b850677 --- /dev/null +++ b/t/t3409-rebase-hook.sh @@ -0,0 +1,142 @@ +#!/bin/sh + +test_description='git rebase with its hook(s)' + +. ./test-lib.sh + +test_expect_success setup ' + echo hello >file && + git add file && + test_tick && + git commit -m initial && + echo goodbye >file && + git add file && + test_tick && + git commit -m second && + git checkout -b side HEAD^ && + echo world >git && + git add git && + test_tick && + git commit -m side && + git checkout master && + git log --pretty=oneline --abbrev-commit --graph --all && + git branch test side +' + +test_expect_success 'rebase' ' + git checkout test && + git reset --hard side && + git rebase master && + test "z$(cat git)" = zworld +' + +test_expect_success 'rebase -i' ' + git checkout test && + git reset --hard side && + EDITOR=true git rebase -i master && + test "z$(cat git)" = zworld +' + +test_expect_success 'setup pre-rebase hook' ' + mkdir -p .git/hooks && + cat >.git/hooks/pre-rebase <<EOF && +#!$SHELL_PATH +echo "\$1,\$2" >.git/PRE-REBASE-INPUT +EOF + chmod +x .git/hooks/pre-rebase +' + +test_expect_success 'pre-rebase hook gets correct input (1)' ' + git checkout test && + git reset --hard side && + git rebase master && + test "z$(cat git)" = zworld && + test "z$(cat .git/PRE-REBASE-INPUT)" = zmaster, + +' + +test_expect_success 'pre-rebase hook gets correct input (2)' ' + git checkout test && + git reset --hard side && + git rebase master test && + test "z$(cat git)" = zworld && + test "z$(cat .git/PRE-REBASE-INPUT)" = zmaster,test +' + +test_expect_success 'pre-rebase hook gets correct input (3)' ' + git checkout test && + git reset --hard side && + git checkout master && + git rebase master test && + test "z$(cat git)" = zworld && + test "z$(cat .git/PRE-REBASE-INPUT)" = zmaster,test +' + +test_expect_success 'pre-rebase hook gets correct input (4)' ' + git checkout test && + git reset --hard side && + EDITOR=true git rebase -i master && + test "z$(cat git)" = zworld && + test "z$(cat .git/PRE-REBASE-INPUT)" = zmaster, + +' + +test_expect_success 'pre-rebase hook gets correct input (5)' ' + git checkout test && + git reset --hard side && + EDITOR=true git rebase -i master test && + test "z$(cat git)" = zworld && + test "z$(cat .git/PRE-REBASE-INPUT)" = zmaster,test +' + +test_expect_success 'pre-rebase hook gets correct input (6)' ' + git checkout test && + git reset --hard side && + git checkout master && + EDITOR=true git rebase -i master test && + test "z$(cat git)" = zworld && + test "z$(cat .git/PRE-REBASE-INPUT)" = zmaster,test +' + +test_expect_success 'setup pre-rebase hook that fails' ' + mkdir -p .git/hooks && + cat >.git/hooks/pre-rebase <<EOF && +#!$SHELL_PATH +false +EOF + chmod +x .git/hooks/pre-rebase +' + +test_expect_success 'pre-rebase hook stops rebase (1)' ' + git checkout test && + git reset --hard side && + test_must_fail git rebase master && + test "z$(git symbolic-ref HEAD)" = zrefs/heads/test && + test 0 = $(git rev-list HEAD...side | wc -l) +' + +test_expect_success 'pre-rebase hook stops rebase (2)' ' + git checkout test && + git reset --hard side && + EDITOR=true test_must_fail git rebase -i master && + test "z$(git symbolic-ref HEAD)" = zrefs/heads/test && + test 0 = $(git rev-list HEAD...side | wc -l) +' + +test_expect_success 'rebase --no-verify overrides pre-rebase (1)' ' + git checkout test && + git reset --hard side && + git rebase --no-verify master && + test "z$(git symbolic-ref HEAD)" = zrefs/heads/test && + test "z$(cat git)" = zworld +' + +test_expect_success 'rebase --no-verify overrides pre-rebase (2)' ' + git checkout test && + git reset --hard side && + EDITOR=true git rebase --no-verify -i master && + test "z$(git symbolic-ref HEAD)" = zrefs/heads/test && + test "z$(cat git)" = zworld +' + +test_done diff --git a/t/t3409-rebase-preserve-merges.sh b/t/t3409-rebase-preserve-merges.sh new file mode 100755 index 0000000000..8cde40f8e8 --- /dev/null +++ b/t/t3409-rebase-preserve-merges.sh @@ -0,0 +1,61 @@ +#!/bin/sh +# +# Copyright(C) 2008 Stephen Habermann & Andreas Ericsson +# +test_description='git rebase -p should preserve merges + +Run "git rebase -p" and check that merges are properly carried along +' +. ./test-lib.sh + +GIT_AUTHOR_EMAIL=bogus_email_address +export GIT_AUTHOR_EMAIL + +#echo 'Setting up: +# +#A1--A2 <-- origin/master +# \ \ +# B1--M <-- topic +# \ +# B2 <-- origin/topic +# +#' + +test_expect_success 'setup for merge-preserving rebase' \ + 'echo First > A && + git add A && + git-commit -m "Add A1" && + git checkout -b topic && + echo Second > B && + git add B && + git-commit -m "Add B1" && + git checkout -f master && + echo Third >> A && + git-commit -a -m "Modify A2" && + + git clone ./. clone1 && + cd clone1 && + git checkout -b topic origin/topic && + git merge origin/master && + cd .. + + git clone ./. clone2 + cd clone2 && + git checkout -b topic origin/topic && + git merge origin/master && + cd .. && + + git checkout topic && + echo Fourth >> B && + git commit -a -m "Modify B2" +' + +test_expect_success 'rebase -p fakes interactive rebase' ' + cd clone2 && + git fetch && + git rebase -p origin/topic && + test 1 = $(git rev-list --all --pretty=oneline | grep "Modify A" | wc -l) && + test 1 = $(git rev-list --all --pretty=oneline | grep "Merge commit" | wc -l) +' + +test_done diff --git a/t/t3600-rm.sh b/t/t3600-rm.sh index 558c80edbf..66aca99fd3 100755 --- a/t/t3600-rm.sh +++ b/t/t3600-rm.sh @@ -219,14 +219,23 @@ test_expect_success 'Remove nonexistent file returns nonzero exit status' ' test_expect_success 'Call "rm" from outside the work tree' ' mkdir repo && - cd repo && - git init && - echo something > somefile && - git add somefile && - git commit -m "add a file" && - (cd .. && - git --git-dir=repo/.git --work-tree=repo rm somefile) && - test_must_fail git ls-files --error-unmatch somefile + (cd repo && + git init && + echo something > somefile && + git add somefile && + git commit -m "add a file" && + (cd .. && + git --git-dir=repo/.git --work-tree=repo rm somefile) && + test_must_fail git ls-files --error-unmatch somefile) +' + +test_expect_success 'refresh index before checking if it is up-to-date' ' + + git reset --hard && + test-chmtime -86400 frotz/nitfol && + git rm frotz/nitfol && + test ! -f frotz/nitfol + ' test_done diff --git a/t/t3700-add.sh b/t/t3700-add.sh index 2ac93a346d..9f6454d2ff 100755 --- a/t/t3700-add.sh +++ b/t/t3700-add.sh @@ -226,7 +226,7 @@ test_expect_success 'git add '\''fo\[ou\]bar'\'' ignores foobar' ' git reset --hard && touch fo\[ou\]bar foobar && git add '\''fo\[ou\]bar'\'' && - git ls-files fo\[ou\]bar | grep -F fo\[ou\]bar && + git ls-files fo\[ou\]bar | fgrep fo\[ou\]bar && ! ( git ls-files foobar | grep foobar ) ' diff --git a/t/t4012-diff-binary.sh b/t/t4012-diff-binary.sh index b8ec6e90af..421f4bba3f 100755 --- a/t/t4012-diff-binary.sh +++ b/t/t4012-diff-binary.sh @@ -77,4 +77,25 @@ test_expect_success 'apply binary patch' \ tree1=`git write-tree` && test "$tree1" = "$tree0"' +q_to_nul() { + perl -pe 'y/Q/\000/' +} + +nul_to_q() { + perl -pe 'y/\000/Q/' +} + +test_expect_success 'diff --no-index with binary creation' ' + echo Q | q_to_nul >binary && + (:# hide error code from diff, which just indicates differences + git diff --binary --no-index /dev/null binary >current || + true + ) && + rm binary && + git apply --binary <current && + echo Q >expected && + nul_to_q <binary >actual && + test_cmp expected actual +' + test_done diff --git a/t/t4013-diff-various.sh b/t/t4013-diff-various.sh index 1a6b52234d..aeb5405cfe 100755 --- a/t/t4013-diff-various.sh +++ b/t/t4013-diff-various.sh @@ -236,12 +236,15 @@ show --patch-with-stat --summary side format-patch --stdout initial..side format-patch --stdout initial..master^ format-patch --stdout initial..master +format-patch --stdout --no-numbered initial..master +format-patch --stdout --numbered initial..master format-patch --attach --stdout initial..side format-patch --attach --stdout initial..master^ format-patch --attach --stdout initial..master format-patch --inline --stdout initial..side format-patch --inline --stdout initial..master^ format-patch --inline --stdout initial..master +format-patch --inline --stdout initial..master format-patch --inline --stdout --subject-prefix=TESTCASE initial..master config format.subjectprefix DIFFERENT_PREFIX format-patch --inline --stdout initial..master^^ @@ -258,6 +261,7 @@ diff --patch-with-stat -r initial..side diff --patch-with-raw -r initial..side diff --name-status dir2 dir diff --no-index --name-status dir2 dir +diff master master^ side EOF test_done diff --git a/t/t4013/diff.diff_master_master^_side b/t/t4013/diff.diff_master_master^_side new file mode 100644 index 0000000000..50ec9cadd6 --- /dev/null +++ b/t/t4013/diff.diff_master_master^_side @@ -0,0 +1,29 @@ +$ git diff master master^ side +diff --cc dir/sub +index cead32e,7289e35..992913c +--- a/dir/sub ++++ b/dir/sub +@@@ -1,6 -1,4 +1,8 @@@ + A + B + +C + +D + +E + +F ++ 1 ++ 2 +diff --cc file0 +index b414108,f4615da..10a8a9f +--- a/file0 ++++ b/file0 +@@@ -1,6 -1,6 +1,9 @@@ + 1 + 2 + 3 + +4 + +5 + +6 ++ A ++ B ++ C +$ diff --git a/t/t4013/diff.format-patch_--attach_--stdout_initial..master b/t/t4013/diff.format-patch_--attach_--stdout_initial..master index 43346b9ba4..e5ab74437e 100644 --- a/t/t4013/diff.format-patch_--attach_--stdout_initial..master +++ b/t/t4013/diff.format-patch_--attach_--stdout_initial..master @@ -2,7 +2,7 @@ $ git format-patch --attach --stdout initial..master From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:01:00 +0000 -Subject: [PATCH] Second +Subject: [PATCH 1/3] Second MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" @@ -63,7 +63,7 @@ index 01e79c3..0000000 From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:02:00 +0000 -Subject: [PATCH] Third +Subject: [PATCH 2/3] Third MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" @@ -111,7 +111,7 @@ index 0000000..b1e6722 From c7a2ab9e8eac7b117442a607d5a9b3950ae34d5a Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:03:00 +0000 -Subject: [PATCH] Side +Subject: [PATCH 3/3] Side MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" diff --git a/t/t4013/diff.format-patch_--attach_--stdout_initial..master^ b/t/t4013/diff.format-patch_--attach_--stdout_initial..master^ index d7490a9fd7..2c71d20d37 100644 --- a/t/t4013/diff.format-patch_--attach_--stdout_initial..master^ +++ b/t/t4013/diff.format-patch_--attach_--stdout_initial..master^ @@ -2,7 +2,7 @@ $ git format-patch --attach --stdout initial..master^ From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:01:00 +0000 -Subject: [PATCH] Second +Subject: [PATCH 1/2] Second MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" @@ -63,7 +63,7 @@ index 01e79c3..0000000 From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:02:00 +0000 -Subject: [PATCH] Third +Subject: [PATCH 2/2] Third MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" diff --git a/t/t4013/diff.format-patch_--inline_--stdout_--subject-prefix=TESTCASE_initial..master b/t/t4013/diff.format-patch_--inline_--stdout_--subject-prefix=TESTCASE_initial..master index fca5cce373..58f8a7b7d6 100644 --- a/t/t4013/diff.format-patch_--inline_--stdout_--subject-prefix=TESTCASE_initial..master +++ b/t/t4013/diff.format-patch_--inline_--stdout_--subject-prefix=TESTCASE_initial..master @@ -2,7 +2,7 @@ $ git format-patch --inline --stdout --subject-prefix=TESTCASE initial..master From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:01:00 +0000 -Subject: [TESTCASE] Second +Subject: [TESTCASE 1/3] Second MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" @@ -63,7 +63,7 @@ index 01e79c3..0000000 From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:02:00 +0000 -Subject: [TESTCASE] Third +Subject: [TESTCASE 2/3] Third MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" @@ -111,7 +111,7 @@ index 0000000..b1e6722 From c7a2ab9e8eac7b117442a607d5a9b3950ae34d5a Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:03:00 +0000 -Subject: [TESTCASE] Side +Subject: [TESTCASE 3/3] Side MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" diff --git a/t/t4013/diff.format-patch_--inline_--stdout_initial..master b/t/t4013/diff.format-patch_--inline_--stdout_initial..master index 6d6fac3908..9e7bbdffa2 100644 --- a/t/t4013/diff.format-patch_--inline_--stdout_initial..master +++ b/t/t4013/diff.format-patch_--inline_--stdout_initial..master @@ -2,7 +2,7 @@ $ git format-patch --inline --stdout initial..master From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:01:00 +0000 -Subject: [PATCH] Second +Subject: [PATCH 1/3] Second MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" @@ -63,7 +63,7 @@ index 01e79c3..0000000 From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:02:00 +0000 -Subject: [PATCH] Third +Subject: [PATCH 2/3] Third MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" @@ -111,7 +111,7 @@ index 0000000..b1e6722 From c7a2ab9e8eac7b117442a607d5a9b3950ae34d5a Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:03:00 +0000 -Subject: [PATCH] Side +Subject: [PATCH 3/3] Side MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" diff --git a/t/t4013/diff.format-patch_--inline_--stdout_initial..master^ b/t/t4013/diff.format-patch_--inline_--stdout_initial..master^ index 18a1110def..f881f644cc 100644 --- a/t/t4013/diff.format-patch_--inline_--stdout_initial..master^ +++ b/t/t4013/diff.format-patch_--inline_--stdout_initial..master^ @@ -2,7 +2,7 @@ $ git format-patch --inline --stdout initial..master^ From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:01:00 +0000 -Subject: [PATCH] Second +Subject: [PATCH 1/2] Second MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" @@ -63,7 +63,7 @@ index 01e79c3..0000000 From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:02:00 +0000 -Subject: [PATCH] Third +Subject: [PATCH 2/2] Third MIME-Version: 1.0 Content-Type: multipart/mixed; boundary="------------g-i-t--v-e-r-s-i-o-n" diff --git a/t/t4013/diff.format-patch_--stdout_--no-numbered_initial..master b/t/t4013/diff.format-patch_--stdout_--no-numbered_initial..master new file mode 100644 index 0000000000..f7752ebbea --- /dev/null +++ b/t/t4013/diff.format-patch_--stdout_--no-numbered_initial..master @@ -0,0 +1,127 @@ +$ git format-patch --stdout --no-numbered initial..master +From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 +From: A U Thor <author@example.com> +Date: Mon, 26 Jun 2006 00:01:00 +0000 +Subject: [PATCH] Second + +This is the second commit. +--- + dir/sub | 2 ++ + file0 | 3 +++ + file2 | 3 --- + 3 files changed, 5 insertions(+), 3 deletions(-) + delete mode 100644 file2 + +diff --git a/dir/sub b/dir/sub +index 35d242b..8422d40 100644 +--- a/dir/sub ++++ b/dir/sub +@@ -1,2 +1,4 @@ + A + B ++C ++D +diff --git a/file0 b/file0 +index 01e79c3..b414108 100644 +--- a/file0 ++++ b/file0 +@@ -1,3 +1,6 @@ + 1 + 2 + 3 ++4 ++5 ++6 +diff --git a/file2 b/file2 +deleted file mode 100644 +index 01e79c3..0000000 +--- a/file2 ++++ /dev/null +@@ -1,3 +0,0 @@ +-1 +-2 +-3 +-- +g-i-t--v-e-r-s-i-o-n + + +From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 +From: A U Thor <author@example.com> +Date: Mon, 26 Jun 2006 00:02:00 +0000 +Subject: [PATCH] Third + +--- + dir/sub | 2 ++ + file1 | 3 +++ + 2 files changed, 5 insertions(+), 0 deletions(-) + create mode 100644 file1 + +diff --git a/dir/sub b/dir/sub +index 8422d40..cead32e 100644 +--- a/dir/sub ++++ b/dir/sub +@@ -2,3 +2,5 @@ A + B + C + D ++E ++F +diff --git a/file1 b/file1 +new file mode 100644 +index 0000000..b1e6722 +--- /dev/null ++++ b/file1 +@@ -0,0 +1,3 @@ ++A ++B ++C +-- +g-i-t--v-e-r-s-i-o-n + + +From c7a2ab9e8eac7b117442a607d5a9b3950ae34d5a Mon Sep 17 00:00:00 2001 +From: A U Thor <author@example.com> +Date: Mon, 26 Jun 2006 00:03:00 +0000 +Subject: [PATCH] Side + +--- + dir/sub | 2 ++ + file0 | 3 +++ + file3 | 4 ++++ + 3 files changed, 9 insertions(+), 0 deletions(-) + create mode 100644 file3 + +diff --git a/dir/sub b/dir/sub +index 35d242b..7289e35 100644 +--- a/dir/sub ++++ b/dir/sub +@@ -1,2 +1,4 @@ + A + B ++1 ++2 +diff --git a/file0 b/file0 +index 01e79c3..f4615da 100644 +--- a/file0 ++++ b/file0 +@@ -1,3 +1,6 @@ + 1 + 2 + 3 ++A ++B ++C +diff --git a/file3 b/file3 +new file mode 100644 +index 0000000..7289e35 +--- /dev/null ++++ b/file3 +@@ -0,0 +1,4 @@ ++A ++B ++1 ++2 +-- +g-i-t--v-e-r-s-i-o-n + +$ diff --git a/t/t4013/diff.format-patch_--stdout_--numbered_initial..master b/t/t4013/diff.format-patch_--stdout_--numbered_initial..master new file mode 100644 index 0000000000..8e67dbf76f --- /dev/null +++ b/t/t4013/diff.format-patch_--stdout_--numbered_initial..master @@ -0,0 +1,127 @@ +$ git format-patch --stdout --numbered initial..master +From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 +From: A U Thor <author@example.com> +Date: Mon, 26 Jun 2006 00:01:00 +0000 +Subject: [PATCH 1/3] Second + +This is the second commit. +--- + dir/sub | 2 ++ + file0 | 3 +++ + file2 | 3 --- + 3 files changed, 5 insertions(+), 3 deletions(-) + delete mode 100644 file2 + +diff --git a/dir/sub b/dir/sub +index 35d242b..8422d40 100644 +--- a/dir/sub ++++ b/dir/sub +@@ -1,2 +1,4 @@ + A + B ++C ++D +diff --git a/file0 b/file0 +index 01e79c3..b414108 100644 +--- a/file0 ++++ b/file0 +@@ -1,3 +1,6 @@ + 1 + 2 + 3 ++4 ++5 ++6 +diff --git a/file2 b/file2 +deleted file mode 100644 +index 01e79c3..0000000 +--- a/file2 ++++ /dev/null +@@ -1,3 +0,0 @@ +-1 +-2 +-3 +-- +g-i-t--v-e-r-s-i-o-n + + +From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 +From: A U Thor <author@example.com> +Date: Mon, 26 Jun 2006 00:02:00 +0000 +Subject: [PATCH 2/3] Third + +--- + dir/sub | 2 ++ + file1 | 3 +++ + 2 files changed, 5 insertions(+), 0 deletions(-) + create mode 100644 file1 + +diff --git a/dir/sub b/dir/sub +index 8422d40..cead32e 100644 +--- a/dir/sub ++++ b/dir/sub +@@ -2,3 +2,5 @@ A + B + C + D ++E ++F +diff --git a/file1 b/file1 +new file mode 100644 +index 0000000..b1e6722 +--- /dev/null ++++ b/file1 +@@ -0,0 +1,3 @@ ++A ++B ++C +-- +g-i-t--v-e-r-s-i-o-n + + +From c7a2ab9e8eac7b117442a607d5a9b3950ae34d5a Mon Sep 17 00:00:00 2001 +From: A U Thor <author@example.com> +Date: Mon, 26 Jun 2006 00:03:00 +0000 +Subject: [PATCH 3/3] Side + +--- + dir/sub | 2 ++ + file0 | 3 +++ + file3 | 4 ++++ + 3 files changed, 9 insertions(+), 0 deletions(-) + create mode 100644 file3 + +diff --git a/dir/sub b/dir/sub +index 35d242b..7289e35 100644 +--- a/dir/sub ++++ b/dir/sub +@@ -1,2 +1,4 @@ + A + B ++1 ++2 +diff --git a/file0 b/file0 +index 01e79c3..f4615da 100644 +--- a/file0 ++++ b/file0 +@@ -1,3 +1,6 @@ + 1 + 2 + 3 ++A ++B ++C +diff --git a/file3 b/file3 +new file mode 100644 +index 0000000..7289e35 +--- /dev/null ++++ b/file3 +@@ -0,0 +1,4 @@ ++A ++B ++1 ++2 +-- +g-i-t--v-e-r-s-i-o-n + +$ diff --git a/t/t4013/diff.format-patch_--stdout_initial..master b/t/t4013/diff.format-patch_--stdout_initial..master index 8b88ca4927..7b89978e32 100644 --- a/t/t4013/diff.format-patch_--stdout_initial..master +++ b/t/t4013/diff.format-patch_--stdout_initial..master @@ -2,7 +2,7 @@ $ git format-patch --stdout initial..master From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:01:00 +0000 -Subject: [PATCH] Second +Subject: [PATCH 1/3] Second This is the second commit. --- @@ -48,7 +48,7 @@ g-i-t--v-e-r-s-i-o-n From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:02:00 +0000 -Subject: [PATCH] Third +Subject: [PATCH 2/3] Third --- dir/sub | 2 ++ @@ -82,7 +82,7 @@ g-i-t--v-e-r-s-i-o-n From c7a2ab9e8eac7b117442a607d5a9b3950ae34d5a Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:03:00 +0000 -Subject: [PATCH] Side +Subject: [PATCH 3/3] Side --- dir/sub | 2 ++ diff --git a/t/t4013/diff.format-patch_--stdout_initial..master^ b/t/t4013/diff.format-patch_--stdout_initial..master^ index 47a4b88637..b7f9725dc4 100644 --- a/t/t4013/diff.format-patch_--stdout_initial..master^ +++ b/t/t4013/diff.format-patch_--stdout_initial..master^ @@ -2,7 +2,7 @@ $ git format-patch --stdout initial..master^ From 1bde4ae5f36c8d9abe3a0fce0c6aab3c4a12fe44 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:01:00 +0000 -Subject: [PATCH] Second +Subject: [PATCH 1/2] Second This is the second commit. --- @@ -48,7 +48,7 @@ g-i-t--v-e-r-s-i-o-n From 9a6d4949b6b76956d9d5e26f2791ec2ceff5fdc0 Mon Sep 17 00:00:00 2001 From: A U Thor <author@example.com> Date: Mon, 26 Jun 2006 00:02:00 +0000 -Subject: [PATCH] Third +Subject: [PATCH 2/2] Third --- dir/sub | 2 ++ diff --git a/t/t4018-diff-funcname.sh b/t/t4018-diff-funcname.sh index 18bcd9713d..be541348c6 100755 --- a/t/t4018-diff-funcname.sh +++ b/t/t4018-diff-funcname.sh @@ -32,7 +32,18 @@ EOF sed 's/beer\\/beer,\\/' < Beer.java > Beer-correct.java +builtin_patterns="bibtex html java objc pascal php python ruby tex" +for p in $builtin_patterns +do + test_expect_success "builtin $p pattern compiles" ' + echo "*.java diff=$p" > .gitattributes && + ! ( git diff --no-index Beer.java Beer-correct.java 2>&1 | + grep "fatal" > /dev/null ) + ' +done + test_expect_success 'default behaviour' ' + rm -f .gitattributes && git diff --no-index Beer.java Beer-correct.java | grep "^@@.*@@ public class Beer" ' @@ -54,11 +65,18 @@ test_expect_success 'custom pattern' ' test_expect_success 'last regexp must not be negated' ' git config diff.java.funcname "!static" && - test_must_fail git diff --no-index Beer.java Beer-correct.java + git diff --no-index Beer.java Beer-correct.java 2>&1 | + grep "fatal: Last expression must not be negated:" +' + +test_expect_success 'pattern which matches to end of line' ' + git config diff.java.funcname "Beer$" && + git diff --no-index Beer.java Beer-correct.java | + grep "^@@.*@@ Beer" ' test_expect_success 'alternation in pattern' ' - git config diff.java.funcname "^[ ]*\\(\\(public\\|static\\).*\\)$" + git config diff.java.xfuncname "^[ ]*((public|static).*)$" && git diff --no-index Beer.java Beer-correct.java | grep "^@@.*@@ public static void main(" ' diff --git a/t/t4021-format-patch-numbered.sh b/t/t4021-format-patch-numbered.sh index 43d64bbd82..390af2389f 100755 --- a/t/t4021-format-patch-numbered.sh +++ b/t/t4021-format-patch-numbered.sh @@ -45,17 +45,22 @@ test_numbered() { grep "^Subject: \[PATCH 2/2\]" $1 } -test_expect_success 'Default: no numbered' ' +test_expect_success 'single patch defaults to no numbers' ' + git format-patch --stdout HEAD~1 >patch0.single && + test_single_no_numbered patch0.single +' + +test_expect_success 'multiple patch defaults to numbered' ' - git format-patch --stdout HEAD~2 >patch0 && - test_no_numbered patch0 + git format-patch --stdout HEAD~2 >patch0.multiple && + test_numbered patch0.multiple ' test_expect_success 'Use --numbered' ' - git format-patch --numbered --stdout HEAD~2 >patch1 && - test_numbered patch1 + git format-patch --numbered --stdout HEAD~1 >patch1 && + test_single_numbered patch1 ' diff --git a/t/t4128-apply-root.sh b/t/t4128-apply-root.sh index 2dd0c75f96..8f6aea48d8 100755 --- a/t/t4128-apply-root.sh +++ b/t/t4128-apply-root.sh @@ -40,4 +40,56 @@ test_expect_success 'apply --directory -p (2) ' ' ' +cat > patch << EOF +diff --git a/newfile b/newfile +new file mode 100644 +index 0000000..d95f3ad +--- /dev/null ++++ b/newfile +@@ -0,0 +1 @@ ++content +EOF + +test_expect_success 'apply --directory (new file)' ' + git reset --hard initial && + git apply --directory=some/sub/dir/ --index patch && + test content = $(git show :some/sub/dir/newfile) && + test content = $(cat some/sub/dir/newfile) +' + +cat > patch << EOF +diff --git a/delfile b/delfile +deleted file mode 100644 +index d95f3ad..0000000 +--- a/delfile ++++ /dev/null +@@ -1 +0,0 @@ +-content +EOF + +test_expect_success 'apply --directory (delete file)' ' + git reset --hard initial && + echo content >some/sub/dir/delfile && + git add some/sub/dir/delfile && + git apply --directory=some/sub/dir/ --index patch && + ! (git ls-files | grep delfile) +' + +cat > patch << 'EOF' +diff --git "a/qu\157tefile" "b/qu\157tefile" +new file mode 100644 +index 0000000..d95f3ad +--- /dev/null ++++ "b/qu\157tefile" +@@ -0,0 +1 @@ ++content +EOF + +test_expect_success 'apply --directory (quoted filename)' ' + git reset --hard initial && + git apply --directory=some/sub/dir/ --index patch && + test content = $(git show :some/sub/dir/quotefile) && + test content = $(cat some/sub/dir/quotefile) +' + test_done diff --git a/t/t4150-am.sh b/t/t4150-am.sh index 1be5fb3f9d..796f795267 100755 --- a/t/t4150-am.sh +++ b/t/t4150-am.sh @@ -165,7 +165,7 @@ test_expect_success 'am --keep really keeps the subject' ' git am --keep patch4 && ! test -d .git/rebase-apply && git cat-file commit HEAD | - grep -q -F "Re: Re: Re: [PATCH 1/5 v2] third" + fgrep "Re: Re: Re: [PATCH 1/5 v2] third" ' test_expect_success 'am -3 falls back to 3-way merge' ' diff --git a/t/t4151-am-abort.sh b/t/t4151-am-abort.sh index 4448aba7e0..2b912d7728 100755 --- a/t/t4151-am-abort.sh +++ b/t/t4151-am-abort.sh @@ -22,7 +22,7 @@ test_expect_success setup ' test_tick && git commit -a -m $i || break done && - git format-patch initial && + git format-patch --no-numbered initial && git checkout -b side initial && echo local change >file-2-expect ' diff --git a/t/t5300-pack-object.sh b/t/t5300-pack-object.sh index 3a0ef8759c..b335c6b42d 100755 --- a/t/t5300-pack-object.sh +++ b/t/t5300-pack-object.sh @@ -272,7 +272,8 @@ test_expect_success \ test_expect_success \ 'make sure index-pack detects the SHA1 collision' \ - 'test_must_fail git index-pack -o bad.idx test-3.pack' + 'test_must_fail git index-pack -o bad.idx test-3.pack 2>msg && + grep "SHA1 COLLISION FOUND" msg' test_expect_success \ 'honor pack.packSizeLimit' \ diff --git a/t/t5510-fetch.sh b/t/t5510-fetch.sh index de26c20327..9aae4965da 100755 --- a/t/t5510-fetch.sh +++ b/t/t5510-fetch.sh @@ -303,4 +303,24 @@ test_expect_success 'pushing nonexistent branch by mistake should not segv' ' ' +test_expect_success 'auto tag following fetches minimum' ' + + cd "$D" && + git clone .git follow && + git checkout HEAD^0 && + ( + for i in 1 2 3 4 5 6 7 + do + echo $i >>file && + git commit -m $i -a && + git tag -a -m $i excess-$i || exit 1 + done + ) && + git checkout master && + ( + cd follow && + git fetch + ) +' + test_done diff --git a/t/t5702-clone-options.sh b/t/t5702-clone-options.sh index 328e4d9a33..27825f5f31 100755 --- a/t/t5702-clone-options.sh +++ b/t/t5702-clone-options.sh @@ -19,4 +19,17 @@ test_expect_success 'clone -o' ' ' +test_expect_success 'redirected clone' ' + + git clone "file://$(pwd)/parent" clone-redirected >out 2>err && + test ! -s err + +' +test_expect_success 'redirected clone -v' ' + + git clone -v "file://$(pwd)/parent" clone-redirected-v >out 2>err && + test -s err + +' + test_done diff --git a/t/t6013-rev-list-reverse-parents.sh b/t/t6013-rev-list-reverse-parents.sh new file mode 100755 index 0000000000..59fc2f06e0 --- /dev/null +++ b/t/t6013-rev-list-reverse-parents.sh @@ -0,0 +1,42 @@ +#!/bin/sh + +test_description='--reverse combines with --parents' + +. ./test-lib.sh + + +commit () { + test_tick && + echo $1 > foo && + git add foo && + git commit -m "$1" +} + +test_expect_success 'set up --reverse example' ' + commit one && + git tag root && + commit two && + git checkout -b side HEAD^ && + commit three && + git checkout master && + git merge -s ours side && + commit five + ' + +test_expect_success '--reverse --parents --full-history combines correctly' ' + git rev-list --parents --full-history master -- foo | + perl -e "print reverse <>" > expected && + git rev-list --reverse --parents --full-history master -- foo \ + > actual && + test_cmp actual expected + ' + +test_expect_success '--boundary does too' ' + git rev-list --boundary --parents --full-history master ^root -- foo | + perl -e "print reverse <>" > expected && + git rev-list --boundary --reverse --parents --full-history \ + master ^root -- foo > actual && + test_cmp actual expected + ' + +test_done diff --git a/t/t6023-merge-file.sh b/t/t6023-merge-file.sh index 5e18d68c97..f8942bc890 100755 --- a/t/t6023-merge-file.sh +++ b/t/t6023-merge-file.sh @@ -161,4 +161,48 @@ test_expect_success 'ZEALOUS_ALNUM' ' ' +cat >expect <<\EOF +Dominus regit me, +<<<<<<< new8.txt +et nihil mihi deerit; + + + + +In loco pascuae ibi me collocavit; +super aquam refectionis educavit me. +||||||| +et nihil mihi deerit. +In loco pascuae ibi me collocavit, +super aquam refectionis educavit me; +======= +et nihil mihi deerit, + + + + +In loco pascuae ibi me collocavit -- +super aquam refectionis educavit me, +>>>>>>> new9.txt +animam meam convertit, +deduxit me super semitas jusitiae, +propter nomen suum. +Nam et si ambulavero in medio umbrae mortis, +non timebo mala, quoniam TU mecum es: +virga tua et baculus tuus ipsa me consolata sunt. +EOF + +test_expect_success '"diff3 -m" style output (1)' ' + test_must_fail git merge-file -p --diff3 \ + new8.txt new5.txt new9.txt >actual && + test_cmp expect actual +' + +test_expect_success '"diff3 -m" style output (2)' ' + git config merge.conflictstyle diff3 && + test_must_fail git merge-file -p \ + new8.txt new5.txt new9.txt >actual && + test_cmp expect actual +' + test_done diff --git a/t/t6026-merge-attr.sh b/t/t6026-merge-attr.sh index 4b423e937d..1ba0a25223 100755 --- a/t/t6026-merge-attr.sh +++ b/t/t6026-merge-attr.sh @@ -142,4 +142,26 @@ test_expect_success 'custom merge backend' ' rm -f $o $a $b ' +test_expect_success 'up-to-date merge without common ancestor' ' + test_create_repo repo1 && + test_create_repo repo2 && + test_tick && + ( + cd repo1 && + >a && + git add a && + git commit -m initial + ) && + test_tick && + ( + cd repo2 && + git commit --allow-empty -m initial + ) && + test_tick && + ( + cd repo1 && + git pull ../repo2 master + ) +' + test_done diff --git a/t/t6030-bisect-porcelain.sh b/t/t6030-bisect-porcelain.sh index 36c9a6965f..85fa39cf0b 100755 --- a/t/t6030-bisect-porcelain.sh +++ b/t/t6030-bisect-porcelain.sh @@ -350,6 +350,120 @@ test_expect_success 'bisect does not create a "bisect" branch' ' git branch -D bisect ' +# This creates a "side" branch to test "siblings" cases. +# +# H1-H2-H3-H4-H5-H6-H7 <--other +# \ +# S5-S6-S7 <--side +# +test_expect_success 'side branch creation' ' + git bisect reset && + git checkout -b side $HASH4 && + add_line_into_file "5(side): first line on a side branch" hello2 && + SIDE_HASH5=$(git rev-parse --verify HEAD) && + add_line_into_file "6(side): second line on a side branch" hello2 && + SIDE_HASH6=$(git rev-parse --verify HEAD) && + add_line_into_file "7(side): third line on a side branch" hello2 && + SIDE_HASH7=$(git rev-parse --verify HEAD) +' + +test_expect_success 'good merge base when good and bad are siblings' ' + git bisect start "$HASH7" "$SIDE_HASH7" > my_bisect_log.txt && + grep "merge base must be tested" my_bisect_log.txt && + grep $HASH4 my_bisect_log.txt && + git bisect good > my_bisect_log.txt && + test_must_fail grep "merge base must be tested" my_bisect_log.txt && + grep $HASH6 my_bisect_log.txt && + git bisect reset +' +test_expect_success 'skipped merge base when good and bad are siblings' ' + git bisect start "$SIDE_HASH7" "$HASH7" > my_bisect_log.txt && + grep "merge base must be tested" my_bisect_log.txt && + grep $HASH4 my_bisect_log.txt && + git bisect skip > my_bisect_log.txt 2>&1 && + grep "Warning" my_bisect_log.txt && + grep $SIDE_HASH6 my_bisect_log.txt && + git bisect reset +' + +test_expect_success 'bad merge base when good and bad are siblings' ' + git bisect start "$HASH7" HEAD > my_bisect_log.txt && + grep "merge base must be tested" my_bisect_log.txt && + grep $HASH4 my_bisect_log.txt && + test_must_fail git bisect bad > my_bisect_log.txt 2>&1 && + grep "merge base $HASH4 is bad" my_bisect_log.txt && + grep "fixed between $HASH4 and \[$SIDE_HASH7\]" my_bisect_log.txt && + git bisect reset +' + +# This creates a few more commits (A and B) to test "siblings" cases +# when a good and a bad rev have many merge bases. +# +# We should have the following: +# +# H1-H2-H3-H4-H5-H6-H7 +# \ \ \ +# S5-A \ +# \ \ +# S6-S7----B +# +# And there A and B have 2 merge bases (S5 and H5) that should be +# reported by "git merge-base --all A B". +# +test_expect_success 'many merge bases creation' ' + git checkout "$SIDE_HASH5" && + git merge -m "merge HASH5 and SIDE_HASH5" "$HASH5" && + A_HASH=$(git rev-parse --verify HEAD) && + git checkout side && + git merge -m "merge HASH7 and SIDE_HASH7" "$HASH7" && + B_HASH=$(git rev-parse --verify HEAD) && + git merge-base --all "$A_HASH" "$B_HASH" > merge_bases.txt && + test $(wc -l < merge_bases.txt) = "2" && + grep "$HASH5" merge_bases.txt && + grep "$SIDE_HASH5" merge_bases.txt +' + +test_expect_success 'good merge bases when good and bad are siblings' ' + git bisect start "$B_HASH" "$A_HASH" > my_bisect_log.txt && + grep "merge base must be tested" my_bisect_log.txt && + git bisect good > my_bisect_log2.txt && + grep "merge base must be tested" my_bisect_log2.txt && + { + { + grep "$SIDE_HASH5" my_bisect_log.txt && + grep "$HASH5" my_bisect_log2.txt + } || { + grep "$SIDE_HASH5" my_bisect_log2.txt && + grep "$HASH5" my_bisect_log.txt + } + } && + git bisect reset +' + +check_trace() { + grep "$1" "$GIT_TRACE" | grep "\^$2" | grep "$3" >/dev/null +} + +test_expect_success 'optimized merge base checks' ' + GIT_TRACE="$(pwd)/trace.log" && + export GIT_TRACE && + git bisect start "$HASH7" "$SIDE_HASH7" > my_bisect_log.txt && + grep "merge base must be tested" my_bisect_log.txt && + grep "$HASH4" my_bisect_log.txt && + check_trace "rev-list" "$HASH7" "$SIDE_HASH7" && + git bisect good > my_bisect_log2.txt && + test -f ".git/BISECT_ANCESTORS_OK" && + test "$HASH6" = $(git rev-parse --verify HEAD) && + : > "$GIT_TRACE" && + git bisect bad > my_bisect_log3.txt && + test_must_fail check_trace "rev-list" "$HASH6" "$SIDE_HASH7" && + git bisect good "$A_HASH" > my_bisect_log4.txt && + grep "merge base must be tested" my_bisect_log4.txt && + test_must_fail test -f ".git/BISECT_ANCESTORS_OK" && + check_trace "rev-list" "$HASH6" "$A_HASH" && + unset GIT_TRACE +' + # # test_done diff --git a/t/t6040-tracking-info.sh b/t/t6040-tracking-info.sh index aac212e936..ba9060190d 100755 --- a/t/t6040-tracking-info.sh +++ b/t/t6040-tracking-info.sh @@ -53,7 +53,7 @@ test_expect_success 'checkout' ' ( cd test && git checkout b1 ) >actual && - grep -e "have 1 and 1 different" actual + grep "have 1 and 1 different" actual ' test_expect_success 'status' ' @@ -63,7 +63,7 @@ test_expect_success 'status' ' # reports nothing to commit test_must_fail git status ) >actual && - grep -e "have 1 and 1 different" actual + grep "have 1 and 1 different" actual ' diff --git a/t/t6120-describe.sh b/t/t6120-describe.sh index 16cc635813..e6c9e59b61 100755 --- a/t/t6120-describe.sh +++ b/t/t6120-describe.sh @@ -91,10 +91,10 @@ check_describe D-* HEAD^^ check_describe A-* HEAD^^2 check_describe B HEAD^^2^ -check_describe A-* --tags HEAD -check_describe A-* --tags HEAD^ -check_describe D-* --tags HEAD^^ -check_describe A-* --tags HEAD^^2 +check_describe c-* --tags HEAD +check_describe c-* --tags HEAD^ +check_describe e-* --tags HEAD^^ +check_describe c-* --tags HEAD^^2 check_describe B --tags HEAD^^2^ check_describe B-0-* --long HEAD^^2^ diff --git a/t/t6300-for-each-ref.sh b/t/t6300-for-each-ref.sh index 26995b3cdd..8bfae44a83 100755 --- a/t/t6300-for-each-ref.sh +++ b/t/t6300-for-each-ref.sh @@ -262,6 +262,50 @@ for i in "--perl --shell" "-s --python" "--python --tcl" "--tcl --perl"; do " done +cat >expected <<\EOF +master +testtag +EOF + +test_expect_success 'Check short refname format' ' + (git for-each-ref --format="%(refname:short)" refs/heads && + git for-each-ref --format="%(refname:short)" refs/tags) >actual && + test_cmp expected actual +' + +test_expect_success 'Check for invalid refname format' ' + test_must_fail git for-each-ref --format="%(refname:INVALID)" +' + +cat >expected <<\EOF +heads/master +master +EOF + +test_expect_success 'Check ambiguous head and tag refs' ' + git checkout -b newtag && + echo "Using $datestamp" > one && + git add one && + git commit -m "Branch" && + setdate_and_increment && + git tag -m "Tagging at $datestamp" master && + git for-each-ref --format "%(refname:short)" refs/heads/master refs/tags/master >actual && + test_cmp expected actual +' + +cat >expected <<\EOF +heads/ambiguous +ambiguous +EOF + +test_expect_success 'Check ambiguous head and tag refs II' ' + git checkout master && + git tag ambiguous testtag^0 && + git branch ambiguous testtag^0 && + git for-each-ref --format "%(refname:short)" refs/heads/ambiguous refs/tags/ambiguous >actual && + test_cmp expected actual +' + test_expect_success 'an unusual tag with an incomplete line' ' git tag -m "bogo" bogo && diff --git a/t/t7002-grep.sh b/t/t7002-grep.sh index 5e359cb561..18fe6f2d57 100755 --- a/t/t7002-grep.sh +++ b/t/t7002-grep.sh @@ -109,7 +109,7 @@ do ' test_expect_success "grep -c $L (no /dev/null)" ' - ! git grep -c test $H | grep -q /dev/null + ! git grep -c test $H | grep /dev/null ' done diff --git a/t/t7201-co.sh b/t/t7201-co.sh index 25181388f8..82769b89fc 100755 --- a/t/t7201-co.sh +++ b/t/t7201-co.sh @@ -369,7 +369,7 @@ test_expect_success \ 'checkout with --track, but without -b, fails with too short tracked name' ' test_must_fail git checkout --track renamer' -test_expect_success 'checkout an unmerged path should fail' ' +setup_conflicting_index () { rm -f .git/index && O=$(echo original | git hash-object -w --stdin) && A=$(echo ourside | git hash-object -w --stdin) && @@ -380,7 +380,11 @@ test_expect_success 'checkout an unmerged path should fail' ' echo "100644 $A 2 file" && echo "100644 $B 3 file" && echo "100644 $A 0 filf" - ) | git update-index --index-info && + ) | git update-index --index-info +} + +test_expect_success 'checkout an unmerged path should fail' ' + setup_conflicting_index && echo "none of the above" >sample && cat sample >fild && cat sample >file && @@ -391,4 +395,129 @@ test_expect_success 'checkout an unmerged path should fail' ' test_cmp sample file ' +test_expect_success 'checkout with an unmerged path can be ignored' ' + setup_conflicting_index && + echo "none of the above" >sample && + echo ourside >expect && + cat sample >fild && + cat sample >file && + cat sample >filf && + git checkout -f fild file filf && + test_cmp expect fild && + test_cmp expect filf && + test_cmp sample file +' + +test_expect_success 'checkout unmerged stage' ' + setup_conflicting_index && + echo "none of the above" >sample && + echo ourside >expect && + cat sample >fild && + cat sample >file && + cat sample >filf && + git checkout --ours . && + test_cmp expect fild && + test_cmp expect filf && + test_cmp expect file && + git checkout --theirs file && + test ztheirside = "z$(cat file)" +' + +test_expect_success 'checkout with --merge' ' + setup_conflicting_index && + echo "none of the above" >sample && + echo ourside >expect && + cat sample >fild && + cat sample >file && + cat sample >filf && + git checkout -m -- fild file filf && + ( + echo "<<<<<<< ours" + echo ourside + echo "=======" + echo theirside + echo ">>>>>>> theirs" + ) >merged && + test_cmp expect fild && + test_cmp expect filf && + test_cmp merged file +' + +test_expect_success 'checkout with --merge, in diff3 -m style' ' + git config merge.conflictstyle diff3 && + setup_conflicting_index && + echo "none of the above" >sample && + echo ourside >expect && + cat sample >fild && + cat sample >file && + cat sample >filf && + git checkout -m -- fild file filf && + ( + echo "<<<<<<< ours" + echo ourside + echo "|||||||" + echo original + echo "=======" + echo theirside + echo ">>>>>>> theirs" + ) >merged && + test_cmp expect fild && + test_cmp expect filf && + test_cmp merged file +' + +test_expect_success 'checkout --conflict=merge, overriding config' ' + git config merge.conflictstyle diff3 && + setup_conflicting_index && + echo "none of the above" >sample && + echo ourside >expect && + cat sample >fild && + cat sample >file && + cat sample >filf && + git checkout --conflict=merge -- fild file filf && + ( + echo "<<<<<<< ours" + echo ourside + echo "=======" + echo theirside + echo ">>>>>>> theirs" + ) >merged && + test_cmp expect fild && + test_cmp expect filf && + test_cmp merged file +' + +test_expect_success 'checkout --conflict=diff3' ' + git config --unset merge.conflictstyle + setup_conflicting_index && + echo "none of the above" >sample && + echo ourside >expect && + cat sample >fild && + cat sample >file && + cat sample >filf && + git checkout --conflict=diff3 -- fild file filf && + ( + echo "<<<<<<< ours" + echo ourside + echo "|||||||" + echo original + echo "=======" + echo theirside + echo ">>>>>>> theirs" + ) >merged && + test_cmp expect fild && + test_cmp expect filf && + test_cmp merged file +' + +test_expect_success 'failing checkout -b should not break working tree' ' + git reset --hard master && + git symbolic-ref HEAD refs/heads/master && + test_must_fail git checkout -b renamer side^ && + test $(git symbolic-ref HEAD) = refs/heads/master && + git diff --exit-code && + git diff --cached --exit-code + +' + test_done diff --git a/t/t7403-submodule-sync.sh b/t/t7403-submodule-sync.sh new file mode 100755 index 0000000000..7538756487 --- /dev/null +++ b/t/t7403-submodule-sync.sh @@ -0,0 +1,64 @@ +#!/bin/sh +# +# Copyright (c) 2008 David Aguilar +# + +test_description='git submodule sync + +These tests exercise the "git submodule sync" subcommand. +' + +. ./test-lib.sh + +test_expect_success setup ' + echo file > file && + git add file && + test_tick && + git commit -m upstream + git clone . super && + git clone super submodule && + (cd super && + git submodule add ../submodule submodule && + test_tick && + git commit -m "submodule" + ) && + git clone super super-clone && + (cd super-clone && git submodule update --init) +' + +test_expect_success 'change submodule' ' + (cd submodule && + echo second line >> file && + test_tick && + git commit -a -m "change submodule" + ) +' + +test_expect_success 'change submodule url' ' + (cd super && + cd submodule && + git checkout master && + git pull + ) && + mv submodule moved-submodule && + (cd super && + git config -f .gitmodules submodule.submodule.url ../moved-submodule + test_tick && + git commit -a -m moved-submodule + ) +' + +test_expect_success '"git submodule sync" should update submodule URLs' ' + (cd super-clone && + git pull && + git submodule sync + ) && + test -d "$(git config -f super-clone/submodule/.git/config \ + remote.origin.url)" && + (cd super-clone/submodule && + git checkout master && + git pull + ) +' + +test_done diff --git a/t/t7502-status.sh b/t/t7502-status.sh index c8e4c2e7b4..1905fb34cd 100755 --- a/t/t7502-status.sh +++ b/t/t7502-status.sh @@ -46,6 +46,7 @@ cat > expect << \EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # @@ -76,6 +77,7 @@ cat >expect <<EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # @@ -104,6 +106,7 @@ cat >expect <<EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # @@ -138,6 +141,7 @@ cat >expect <<EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # @@ -174,6 +178,7 @@ cat > expect << \EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: modified # @@ -204,6 +209,7 @@ cat > expect << \EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # @@ -267,6 +273,7 @@ cat >expect <<EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # @@ -297,6 +304,7 @@ cat >expect <<EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # @@ -326,6 +334,7 @@ cat >expect <<EOF # On branch master # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # @@ -357,6 +366,7 @@ cat >expect <<EOF # # Changed but not updated: # (use "git add <file>..." to update what will be committed) +# (use "git checkout -- <file>..." to discard changes in working directory) # # modified: dir1/modified # diff --git a/t/t7600-merge.sh b/t/t7600-merge.sh index 9516f541e9..e5b210bc96 100755 --- a/t/t7600-merge.sh +++ b/t/t7600-merge.sh @@ -511,4 +511,53 @@ test_expect_success 'in-index merge' ' test_debug 'gitk --all' +test_expect_success 'refresh the index before merging' ' + git reset --hard c1 && + sleep 1 && + touch file && + git merge c3 +' + +cat >expected <<EOF +Merge branch 'c5' (early part) +EOF + +test_expect_success 'merge early part of c2' ' + git reset --hard c3 && + echo c4 > c4.c && + git add c4.c && + git commit -m c4 && + git tag c4 && + echo c5 > c5.c && + git add c5.c && + git commit -m c5 && + git tag c5 && + git reset --hard c3 && + echo c6 > c6.c && + git add c6.c && + git commit -m c6 && + git tag c6 && + git merge c5~1 && + git show -s --pretty=format:%s HEAD > actual && + test_cmp actual expected +' + +test_debug 'gitk --all' + +test_expect_success 'merge --no-ff --no-commit && commit' ' + git reset --hard c0 && + git merge --no-ff --no-commit c1 && + EDITOR=: git commit && + verify_parents $c0 $c1 +' + +test_debug 'gitk --all' + +test_expect_success 'amending no-ff merge commit' ' + EDITOR=: git commit --amend && + verify_parents $c0 $c1 +' + +test_debug 'gitk --all' + test_done diff --git a/t/t7603-merge-reduce-heads.sh b/t/t7603-merge-reduce-heads.sh index b47b7b9757..7e17eb490d 100755 --- a/t/t7603-merge-reduce-heads.sh +++ b/t/t7603-merge-reduce-heads.sh @@ -60,4 +60,57 @@ test_expect_success 'merge c1 with c2, c3, c4, c5' ' test -f c5.c ' +test_expect_success 'setup' ' + for i in A B C D E + do + echo $i > $i.c && + git add $i.c && + git commit -m $i && + git tag $i + done && + git reset --hard A && + for i in F G H I + do + echo $i > $i.c && + git add $i.c && + git commit -m $i && + git tag $i + done +' + +test_expect_success 'merge E and I' ' + git reset --hard A && + git merge E I +' + +test_expect_success 'verify merge result' ' + test $(git rev-parse HEAD^1) = $(git rev-parse E) && + test $(git rev-parse HEAD^2) = $(git rev-parse I) +' + +test_expect_success 'add conflicts' ' + git reset --hard E && + echo foo > file.c && + git add file.c && + git commit -m E2 && + git tag E2 && + git reset --hard I && + echo bar >file.c && + git add file.c && + git commit -m I2 && + git tag I2 +' + +test_expect_success 'merge E2 and I2, causing a conflict and resolve it' ' + git reset --hard A && + test_must_fail git merge E2 I2 && + echo baz > file.c && + git add file.c && + git commit -m "resolve conflict" +' + +test_expect_success 'verify merge result' ' + test $(git rev-parse HEAD^1) = $(git rev-parse E2) && + test $(git rev-parse HEAD^2) = $(git rev-parse I2) +' test_done diff --git a/t/t7701-repack-unpack-unreachable.sh b/t/t7701-repack-unpack-unreachable.sh index 531dac060a..b48046e261 100755 --- a/t/t7701-repack-unpack-unreachable.sh +++ b/t/t7701-repack-unpack-unreachable.sh @@ -29,7 +29,7 @@ test_expect_success '-A option leaves unreachable objects unpacked' ' git repack -A -d -l && # verify objects are packed in repository test 3 = $(git verify-pack -v -- .git/objects/pack/*.idx | - grep -e "^$fsha1 " -e "^$csha1 " -e "^$tsha1 " | + egrep "^($fsha1|$csha1|$tsha1) " | sort | uniq | wc -l) && git show $fsha1 && git show $csha1 && @@ -41,7 +41,7 @@ test_expect_success '-A option leaves unreachable objects unpacked' ' git repack -A -d -l && # verify objects are retained unpacked test 0 = $(git verify-pack -v -- .git/objects/pack/*.idx | - grep -e "^$fsha1 " -e "^$csha1 " -e "^$tsha1 " | + egrep "^($fsha1|$csha1|$tsha1) " | sort | uniq | wc -l) && git show $fsha1 && git show $csha1 && diff --git a/t/t9001-send-email.sh b/t/t9001-send-email.sh index d098a01ba3..561ae7d0a6 100755 --- a/t/t9001-send-email.sh +++ b/t/t9001-send-email.sh @@ -109,7 +109,7 @@ test_expect_success 'allow long lines with --no-validate' ' --from="Example <nobody@example.com>" \ --to=nobody@example.com \ --smtp-server="$(pwd)/fake.sendmail" \ - --no-validate \ + --novalidate \ $patches longline.patch \ 2>errors ' diff --git a/t/t9113-git-svn-dcommit-new-file.sh b/t/t9113-git-svn-dcommit-new-file.sh index 250c53022b..e9b6128b3f 100755 --- a/t/t9113-git-svn-dcommit-new-file.sh +++ b/t/t9113-git-svn-dcommit-new-file.sh @@ -12,19 +12,7 @@ test_description='git svn dcommit new files over svn:// test' . ./lib-git-svn.sh -if test -z "$SVNSERVE_PORT" -then - say 'skipping svnserve test. (set $SVNSERVE_PORT to enable)' - test_done - exit -fi - -start_svnserve () { - svnserve --listen-port $SVNSERVE_PORT \ - --root "$rawsvnrepo" \ - --listen-once \ - --listen-host 127.0.0.1 & -} +require_svnserve test_expect_success 'start tracking an empty repo' ' svn mkdir -m "empty dir" "$svnrepo"/empty-dir && diff --git a/t/t9126-git-svn-follow-deleted-readded-directory.sh b/t/t9126-git-svn-follow-deleted-readded-directory.sh new file mode 100755 index 0000000000..edec640e97 --- /dev/null +++ b/t/t9126-git-svn-follow-deleted-readded-directory.sh @@ -0,0 +1,22 @@ +#!/bin/sh +# +# Copyright (c) 2008 Alec Berryman + +test_description='git svn fetch repository with deleted and readded directory' + +. ./lib-git-svn.sh + +# Don't run this by default; it opens up a port. +require_svnserve + +test_expect_success 'load repository' ' + svnadmin load -q "$rawsvnrepo" < "$TEST_DIRECTORY"/t9126/follow-deleted-readded.dump + ' + +test_expect_success 'fetch repository' ' + start_svnserve && + git svn init svn://127.0.0.1:$SVNSERVE_PORT && + git svn fetch + ' + +test_done diff --git a/t/t9126/follow-deleted-readded.dump b/t/t9126/follow-deleted-readded.dump new file mode 100644 index 0000000000..19da5d1ddc --- /dev/null +++ b/t/t9126/follow-deleted-readded.dump @@ -0,0 +1,201 @@ +SVN-fs-dump-format-version: 2 + +UUID: 1807dc6f-c693-4cda-9710-00e1be8c1f21 + +Revision-number: 0 +Prop-content-length: 56 +Content-length: 56 + +K 8 +svn:date +V 27 +2008-09-14T19:53:13.006748Z +PROPS-END + +Revision-number: 1 +Prop-content-length: 111 +Content-length: 111 + +K 7 +svn:log +V 12 +Create trunk +K 10 +svn:author +V 4 +alec +K 8 +svn:date +V 27 +2008-09-14T19:53:13.239689Z +PROPS-END + +Node-path: trunk +Node-kind: dir +Node-action: add +Prop-content-length: 10 +Content-length: 10 + +PROPS-END + + +Revision-number: 2 +Prop-content-length: 119 +Content-length: 119 + +K 7 +svn:log +V 20 +Create trunk/project +K 10 +svn:author +V 4 +alec +K 8 +svn:date +V 27 +2008-09-14T19:53:13.548860Z +PROPS-END + +Node-path: trunk/project +Node-kind: dir +Node-action: add +Prop-content-length: 10 +Content-length: 10 + +PROPS-END + + +Revision-number: 3 +Prop-content-length: 111 +Content-length: 111 + +K 7 +svn:log +V 12 +add new file +K 10 +svn:author +V 4 +alec +K 8 +svn:date +V 27 +2008-09-14T19:53:15.433630Z +PROPS-END + +Node-path: trunk/project/foo +Node-kind: file +Node-action: add +Prop-content-length: 10 +Text-content-length: 4 +Text-content-md5: d3b07384d113edec49eaa6238ad5ff00 +Content-length: 14 + +PROPS-END +foo + + +Revision-number: 4 +Prop-content-length: 116 +Content-length: 116 + +K 7 +svn:log +V 17 +change foo to bar +K 10 +svn:author +V 4 +alec +K 8 +svn:date +V 27 +2008-09-14T19:53:17.339884Z +PROPS-END + +Node-path: trunk/project/foo +Node-kind: file +Node-action: change +Text-content-length: 4 +Text-content-md5: c157a79031e1c40f85931829bc5fc552 +Content-length: 4 + +bar + + +Revision-number: 5 +Prop-content-length: 114 +Content-length: 114 + +K 7 +svn:log +V 15 +don't like that +K 10 +svn:author +V 4 +alec +K 8 +svn:date +V 27 +2008-09-14T19:53:19.335001Z +PROPS-END + +Node-path: trunk/project +Node-action: delete + + +Revision-number: 6 +Prop-content-length: 110 +Content-length: 110 + +K 7 +svn:log +V 11 +reset trunk +K 10 +svn:author +V 4 +alec +K 8 +svn:date +V 27 +2008-09-14T19:53:19.845897Z +PROPS-END + +Node-path: trunk/project +Node-kind: dir +Node-action: add +Node-copyfrom-rev: 4 +Node-copyfrom-path: trunk/project + + +Revision-number: 7 +Prop-content-length: 113 +Content-length: 113 + +K 7 +svn:log +V 14 +change to quux +K 10 +svn:author +V 4 +alec +K 8 +svn:date +V 27 +2008-09-14T19:53:21.367947Z +PROPS-END + +Node-path: trunk/project/foo +Node-kind: file +Node-action: change +Text-content-length: 5 +Text-content-md5: d3b07a382ec010c01889250fce66fb13 +Content-length: 5 + +quux + + diff --git a/t/t9127-git-svn-partial-rebuild.sh b/t/t9127-git-svn-partial-rebuild.sh new file mode 100755 index 0000000000..87696a92dc --- /dev/null +++ b/t/t9127-git-svn-partial-rebuild.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# +# Copyright (c) 2008 Deskin Miller +# + +test_description='git svn partial-rebuild tests' +. ./lib-git-svn.sh + +test_expect_success 'initialize svnrepo' ' + mkdir import && + ( + cd import && + mkdir trunk branches tags && + cd trunk && + echo foo > foo && + cd .. && + svn import -m "import for git-svn" . "$svnrepo" >/dev/null && + svn copy "$svnrepo"/trunk "$svnrepo"/branches/a \ + -m "created branch a" && + cd .. && + rm -rf import && + svn co "$svnrepo"/trunk trunk && + cd trunk && + echo bar >> foo && + svn ci -m "updated trunk" && + cd .. && + svn co "$svnrepo"/branches/a a && + cd a && + echo baz >> a && + svn add a && + svn ci -m "updated a" && + cd .. && + git svn init --stdlayout "$svnrepo" + ) +' + +test_expect_success 'import an early SVN revision into git' ' + git svn fetch -r1:2 +' + +test_expect_success 'make full git mirror of SVN' ' + mkdir mirror && + ( + cd mirror && + git init && + git svn init --stdlayout "$svnrepo" && + git svn fetch && + cd .. + ) +' + +test_expect_success 'fetch from git mirror and partial-rebuild' ' + git config --add remote.origin.url "file://$PWD/mirror/.git" && + git config --add remote.origin.fetch refs/remotes/*:refs/remotes/* && + git fetch origin && + git svn fetch +' + +test_done diff --git a/t/t9128-git-svn-cmd-branch.sh b/t/t9128-git-svn-cmd-branch.sh new file mode 100755 index 0000000000..47c4d4d938 --- /dev/null +++ b/t/t9128-git-svn-cmd-branch.sh @@ -0,0 +1,59 @@ +#!/bin/sh +# +# Copyright (c) 2008 Deskin Miller +# + +test_description='git svn partial-rebuild tests' +. ./lib-git-svn.sh + +test_expect_success 'initialize svnrepo' ' + mkdir import && + ( + cd import && + mkdir trunk branches tags && + cd trunk && + echo foo > foo && + cd .. && + svn import -m "import for git-svn" . "$svnrepo" >/dev/null && + cd .. && + rm -rf import && + svn co "$svnrepo"/trunk trunk && + cd trunk && + echo bar >> foo && + svn ci -m "updated trunk" && + cd .. && + rm -rf trunk + ) +' + +test_expect_success 'import into git' ' + git svn init --stdlayout "$svnrepo" && + git svn fetch && + git checkout remotes/trunk +' + +test_expect_success 'git svn branch tests' ' + git svn branch a && + base=$(git rev-parse HEAD:) && + test $base = $(git rev-parse remotes/a:) && + git svn branch -m "created branch b blah" b && + test $base = $(git rev-parse remotes/b:) && + test_must_fail git branch -m "no branchname" && + git svn branch -n c && + test_must_fail git rev-parse remotes/c && + test_must_fail git svn branch a && + git svn branch -t tag1 && + test $base = $(git rev-parse remotes/tags/tag1:) && + git svn branch --tag tag2 && + test $base = $(git rev-parse remotes/tags/tag2:) && + git svn tag tag3 && + test $base = $(git rev-parse remotes/tags/tag3:) && + git svn tag -m "created tag4 foo" tag4 && + test $base = $(git rev-parse remotes/tags/tag4:) && + test_must_fail git svn tag -m "no tagname" && + git svn tag -n tag5 && + test_must_fail git rev-parse remotes/tags/tag5 && + test_must_fail git svn tag tag1 +' + +test_done diff --git a/t/t9500-gitweb-standalone-no-errors.sh b/t/t9500-gitweb-standalone-no-errors.sh index 46ba19be7d..64c4cce58b 100755 --- a/t/t9500-gitweb-standalone-no-errors.sh +++ b/t/t9500-gitweb-standalone-no-errors.sh @@ -56,7 +56,7 @@ gitweb_run () { rm -f gitweb.log && perl -- "$TEST_DIRECTORY/../gitweb/gitweb.perl" \ >/dev/null 2>gitweb.log && - if grep -q -s "^[[]" gitweb.log >/dev/null; then false; else true; fi + if grep "^[[]" gitweb.log >/dev/null 2>&1; then false; else true; fi # gitweb.log is left for debugging } @@ -503,6 +503,55 @@ test_expect_success \ test_debug 'cat gitweb.log' # ---------------------------------------------------------------------- +# path_info links +test_expect_success \ + 'path_info: project' \ + 'gitweb_run "" "/.git"' +test_debug 'cat gitweb.log' + +test_expect_success \ + 'path_info: project/branch' \ + 'gitweb_run "" "/.git/b"' +test_debug 'cat gitweb.log' + +test_expect_success \ + 'path_info: project/branch:file' \ + 'gitweb_run "" "/.git/master:file"' +test_debug 'cat gitweb.log' + +test_expect_success \ + 'path_info: project/branch:dir/' \ + 'gitweb_run "" "/.git/master:foo/"' +test_debug 'cat gitweb.log' + +test_expect_success \ + 'path_info: project/branch:file (non-existent)' \ + 'gitweb_run "" "/.git/master:non-existent"' +test_debug 'cat gitweb.log' + +test_expect_success \ + 'path_info: project/branch:dir/ (non-existent)' \ + 'gitweb_run "" "/.git/master:non-existent/"' +test_debug 'cat gitweb.log' + + +test_expect_success \ + 'path_info: project/branch:/file' \ + 'gitweb_run "" "/.git/master:/file"' +test_debug 'cat gitweb.log' + +test_expect_success \ + 'path_info: project/:/file (implicit HEAD)' \ + 'gitweb_run "" "/.git/:/file"' +test_debug 'cat gitweb.log' + +test_expect_success \ + 'path_info: project/:/ (implicit HEAD, top tree)' \ + 'gitweb_run "" "/.git/:/"' +test_debug 'cat gitweb.log' + + +# ---------------------------------------------------------------------- # feed generation test_expect_success \ diff --git a/t/t9700/test.pl b/t/t9700/test.pl index 851cea4a4b..697daf3ffd 100755 --- a/t/t9700/test.pl +++ b/t/t9700/test.pl @@ -9,7 +9,6 @@ use Test::More qw(no_plan); use Cwd; use File::Basename; -use File::Temp; BEGIN { use_ok('Git') } @@ -35,7 +34,7 @@ is($r->get_color("color.test.slot1", "red"), $ansi_green, "get_color"); # Failure cases for config: # Save and restore STDERR; we will probably extract this into a # "dies_ok" method and possibly move the STDERR handling to Git.pm. -open our $tmpstderr, ">&", STDERR or die "cannot save STDERR"; close STDERR; +open our $tmpstderr, ">&STDERR" or die "cannot save STDERR"; close STDERR; eval { $r->config("test.dupstring") }; ok($@, "config: duplicate entry in scalar context fails"); eval { $r->config_bool("test.boolother") }; @@ -66,21 +65,25 @@ is($r->ident_person("Name", "email", "123 +0000"), "Name <email>", # objects and hashes ok(our $file1hash = $r->command_oneline('rev-parse', "HEAD:file1"), "(get file hash)"); -our $tmpfile = File::Temp->new; -is($r->cat_blob($file1hash, $tmpfile), 15, "cat_blob: size"); +my $tmpfile = "file.tmp"; +open TEMPFILE, "+>$tmpfile" or die "Can't open $tmpfile: $!"; +is($r->cat_blob($file1hash, \*TEMPFILE), 15, "cat_blob: size"); our $blobcontents; -{ local $/; seek $tmpfile, 0, 0; $blobcontents = <$tmpfile>; } +{ local $/; seek TEMPFILE, 0, 0; $blobcontents = <TEMPFILE>; } is($blobcontents, "changed file 1\n", "cat_blob: data"); -seek $tmpfile, 0, 0; +close TEMPFILE or die "Failed writing to $tmpfile: $!"; is(Git::hash_object("blob", $tmpfile), $file1hash, "hash_object: roundtrip"); -$tmpfile = File::Temp->new(); -print $tmpfile my $test_text = "test blob, to be inserted\n"; +open TEMPFILE, ">$tmpfile" or die "Can't open $tmpfile: $!"; +print TEMPFILE my $test_text = "test blob, to be inserted\n"; +close TEMPFILE or die "Failed writing to $tmpfile: $!"; like(our $newhash = $r->hash_and_insert_object($tmpfile), qr/[0-9a-fA-F]{40}/, "hash_and_insert_object: returns hash"); -$tmpfile = File::Temp->new; -is($r->cat_blob($newhash, $tmpfile), length $test_text, "cat_blob: roundtrip size"); -{ local $/; seek $tmpfile, 0, 0; $blobcontents = <$tmpfile>; } +open TEMPFILE, "+>$tmpfile" or die "Can't open $tmpfile: $!"; +is($r->cat_blob($newhash, \*TEMPFILE), length $test_text, "cat_blob: roundtrip size"); +{ local $/; seek TEMPFILE, 0, 0; $blobcontents = <TEMPFILE>; } is($blobcontents, $test_text, "cat_blob: roundtrip data"); +close TEMPFILE; +unlink $tmpfile; # paths is($r->repo_path, "./.git", "repo_path"); diff --git a/t/test-lib.sh b/t/test-lib.sh index e2b106cb6a..8936173ee2 100644 --- a/t/test-lib.sh +++ b/t/test-lib.sh @@ -112,8 +112,9 @@ if test -n "$color"; then *) test -n "$quiet" && return;; esac shift - echo "* $*" + printf "* %s" "$*" tput sgr0 + echo ) } else diff --git a/templates/Makefile b/templates/Makefile index 0722a926f7..a12c6e214e 100644 --- a/templates/Makefile +++ b/templates/Makefile @@ -31,9 +31,11 @@ boilerplates.made : $(bpsrc) dir=`expr "$$dst" : '\(.*\)/'` && \ mkdir -p blt/$$dir && \ case "$$boilerplate" in \ - *--) ;; \ - *) cp -p $$boilerplate blt/$$dst ;; \ - esac || exit; \ + *--) continue;; \ + esac && \ + cp $$boilerplate blt/$$dst && \ + if test -x "blt/$$dst"; then rx=rx; else rx=r; fi && \ + chmod a+$$rx "blt/$$dst" || exit; \ done && \ date >$@ diff --git a/test-sha1.c b/test-sha1.c index 78d7e983a7..9b98d07c78 100644 --- a/test-sha1.c +++ b/test-sha1.c @@ -2,7 +2,7 @@ int main(int ac, char **av) { - SHA_CTX ctx; + git_SHA_CTX ctx; unsigned char sha1[20]; unsigned bufsz = 8192; char *buffer; @@ -20,7 +20,7 @@ int main(int ac, char **av) die("OOPS"); } - SHA1_Init(&ctx); + git_SHA1_Init(&ctx); while (1) { ssize_t sz, this_sz; @@ -39,9 +39,9 @@ int main(int ac, char **av) } if (this_sz == 0) break; - SHA1_Update(&ctx, buffer, this_sz); + git_SHA1_Update(&ctx, buffer, this_sz); } - SHA1_Final(sha1, &ctx); + git_SHA1_Final(sha1, &ctx); puts(sha1_to_hex(sha1)); exit(0); } diff --git a/transport.c b/transport.c index 71433d9997..1c510a3360 100644 --- a/transport.c +++ b/transport.c @@ -619,7 +619,7 @@ static struct ref *get_refs_via_connect(struct transport *transport) struct ref *refs; connect_setup(transport); - get_remote_heads(data->fd[0], &refs, 0, NULL, 0); + get_remote_heads(data->fd[0], &refs, 0, NULL, 0, NULL); return refs; } @@ -643,8 +643,8 @@ static int fetch_refs_via_pack(struct transport *transport, args.use_thin_pack = data->thin; args.include_tag = data->followtags; args.verbose = (transport->verbose > 0); - args.quiet = args.no_progress = (transport->verbose < 0); - args.no_progress = !isatty(1); + args.quiet = (transport->verbose < 0); + args.no_progress = args.quiet || (!transport->progress && !isatty(1)); args.depth = data->depth; for (i = 0; i < nr_heads; i++) @@ -652,7 +652,7 @@ static int fetch_refs_via_pack(struct transport *transport, if (!data->conn) { connect_setup(transport); - get_remote_heads(data->fd[0], &refs_tmp, 0, NULL, 0); + get_remote_heads(data->fd[0], &refs_tmp, 0, NULL, 0, NULL); } refs = fetch_pack(&args, data->fd, data->conn, diff --git a/transport.h b/transport.h index d0b52053ff..6bbc1a8264 100644 --- a/transport.h +++ b/transport.h @@ -25,6 +25,8 @@ struct transport { int (*disconnect)(struct transport *connection); char *pack_lockfile; signed verbose : 2; + /* Force progress even if the output is not a tty */ + unsigned progress : 1; }; #define TRANSPORT_PUSH_ALL 1 diff --git a/unpack-trees.c b/unpack-trees.c index ef21c62195..e59d144d28 100644 --- a/unpack-trees.c +++ b/unpack-trees.c @@ -941,8 +941,17 @@ int twoway_merge(struct cache_entry **src, struct unpack_trees_options *o) return -1; } } - else if (newtree) + else if (newtree) { + if (oldtree && !o->initial_checkout) { + /* + * deletion of the path was staged; + */ + if (same(oldtree, newtree)) + return 1; + return reject_merge(oldtree, o); + } return merged_entry(newtree, current, o); + } return deleted_entry(oldtree, current, o); } diff --git a/unpack-trees.h b/unpack-trees.h index 94e567265a..0d26f3d73e 100644 --- a/unpack-trees.h +++ b/unpack-trees.h @@ -26,6 +26,7 @@ struct unpack_trees_options { verbose_update:1, aggressive:1, skip_unmerged:1, + initial_checkout:1, gently:1; const char *prefix; int pos; @@ -41,27 +41,11 @@ static void (*die_routine)(const char *err, va_list params) NORETURN = die_built static void (*error_routine)(const char *err, va_list params) = error_builtin; static void (*warn_routine)(const char *err, va_list params) = warn_builtin; -void set_usage_routine(void (*routine)(const char *err) NORETURN) -{ - usage_routine = routine; -} - void set_die_routine(void (*routine)(const char *err, va_list params) NORETURN) { die_routine = routine; } -void set_error_routine(void (*routine)(const char *err, va_list params)) -{ - error_routine = routine; -} - -void set_warn_routine(void (*routine)(const char *warn, va_list params)) -{ - warn_routine = routine; -} - - void usage(const char *err) { usage_routine(err); @@ -215,9 +215,8 @@ static int mark_complete(const char *path, const unsigned char *sha1, int flag, int walker_targets_stdin(char ***target, const char ***write_ref) { int targets = 0, targets_alloc = 0; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; *target = NULL; *write_ref = NULL; - strbuf_init(&buf, 0); while (1) { char *rf_one = NULL; char *tg_one; @@ -99,8 +99,7 @@ unsigned whitespace_rule(const char *pathname) /* The returned string should be freed by the caller. */ char *whitespace_error_string(unsigned ws) { - struct strbuf err; - strbuf_init(&err, 0); + struct strbuf err = STRBUF_INIT; if (ws & WS_TRAILING_SPACE) strbuf_addstr(&err, "trailing whitespace"); if (ws & WS_SPACE_BEFORE_TAB) { diff --git a/wt-status.c b/wt-status.c index 889e50f89f..d2eac36aea 100644 --- a/wt-status.c +++ b/wt-status.c @@ -22,12 +22,6 @@ static char wt_status_colors[][COLOR_MAXLEN] = { "\033[31m", /* WT_STATUS_NOBRANCH: red */ }; -static const char use_add_msg[] = -"use \"git add <file>...\" to update what will be committed"; -static const char use_add_rm_msg[] = -"use \"git add/rm <file>...\" to update what will be committed"; -static const char use_add_to_include_msg[] = -"use \"git add <file>...\" to include in what will be committed"; enum untracked_status_type show_untracked_files = SHOW_NORMAL_UNTRACKED_FILES; static int parse_status_slot(const char *var, int offset) @@ -76,12 +70,24 @@ static void wt_status_print_cached_header(struct wt_status *s) color_fprintf_ln(s->fp, c, "#"); } -static void wt_status_print_header(struct wt_status *s, - const char *main, const char *sub) +static void wt_status_print_dirty_header(struct wt_status *s, + int has_deleted) { const char *c = color(WT_STATUS_HEADER); - color_fprintf_ln(s->fp, c, "# %s:", main); - color_fprintf_ln(s->fp, c, "# (%s)", sub); + color_fprintf_ln(s->fp, c, "# Changed but not updated:"); + if (!has_deleted) + color_fprintf_ln(s->fp, c, "# (use \"git add <file>...\" to update what will be committed)"); + else + color_fprintf_ln(s->fp, c, "# (use \"git add/rm <file>...\" to update what will be committed)"); + color_fprintf_ln(s->fp, c, "# (use \"git checkout -- <file>...\" to discard changes in working directory)"); + color_fprintf_ln(s->fp, c, "#"); +} + +static void wt_status_print_untracked_header(struct wt_status *s) +{ + const char *c = color(WT_STATUS_HEADER); + color_fprintf_ln(s->fp, c, "# Untracked files:"); + color_fprintf_ln(s->fp, c, "# (use \"git add <file>...\" to include in what will be committed)"); color_fprintf_ln(s->fp, c, "#"); } @@ -97,10 +103,8 @@ static void wt_status_print_filepair(struct wt_status *s, { const char *c = color(t); const char *one, *two; - struct strbuf onebuf, twobuf; + struct strbuf onebuf = STRBUF_INIT, twobuf = STRBUF_INIT; - strbuf_init(&onebuf, 0); - strbuf_init(&twobuf, 0); one = quote_path(p->one->path, -1, &onebuf, s->prefix); two = quote_path(p->two->path, -1, &twobuf, s->prefix); @@ -166,14 +170,14 @@ static void wt_status_print_changed_cb(struct diff_queue_struct *q, struct wt_status *s = data; int i; if (q->nr) { - const char *msg = use_add_msg; + int has_deleted = 0; s->workdir_dirty = 1; for (i = 0; i < q->nr; i++) if (q->queue[i]->status == DIFF_STATUS_DELETED) { - msg = use_add_rm_msg; + has_deleted = 1; break; } - wt_status_print_header(s, "Changed but not updated", msg); + wt_status_print_dirty_header(s, has_deleted); } for (i = 0; i < q->nr; i++) wt_status_print_filepair(s, WT_STATUS_CHANGED, q->queue[i]); @@ -184,9 +188,8 @@ static void wt_status_print_changed_cb(struct diff_queue_struct *q, static void wt_status_print_initial(struct wt_status *s) { int i; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; - strbuf_init(&buf, 0); if (active_nr) { s->commitable = 1; wt_status_print_cached_header(s); @@ -262,9 +265,8 @@ static void wt_status_print_untracked(struct wt_status *s) struct dir_struct dir; int i; int shown_header = 0; - struct strbuf buf; + struct strbuf buf = STRBUF_INIT; - strbuf_init(&buf, 0); memset(&dir, 0, sizeof(dir)); if (!s->untracked) { @@ -291,8 +293,7 @@ static void wt_status_print_untracked(struct wt_status *s) } if (!shown_header) { s->workdir_untracked = 1; - wt_status_print_header(s, "Untracked files", - use_add_to_include_msg); + wt_status_print_untracked_header(s); shown_header = 1; } color_fprintf(s->fp, color(WT_STATUS_HEADER), "#\t"); diff --git a/xdiff-interface.c b/xdiff-interface.c index 944ad9887f..49e06af710 100644 --- a/xdiff-interface.c +++ b/xdiff-interface.c @@ -191,34 +191,57 @@ struct ff_regs { static long ff_regexp(const char *line, long len, char *buffer, long buffer_size, void *priv) { - char *line_buffer = xstrndup(line, len); /* make NUL terminated */ + char *line_buffer; struct ff_regs *regs = priv; regmatch_t pmatch[2]; - int result = 0, i; + int i; + int result = -1; + + /* Exclude terminating newline (and cr) from matching */ + if (len > 0 && line[len-1] == '\n') { + if (len > 1 && line[len-2] == '\r') + len -= 2; + else + len--; + } + + line_buffer = xstrndup(line, len); /* make NUL terminated */ + + /* Exclude terminating newline (and cr) from matching */ + if (len > 0 && line[len-1] == '\n') { + if (len > 1 && line[len-2] == '\r') + len -= 2; + else + len--; + } + + line_buffer = xstrndup(line, len); /* make NUL terminated */ for (i = 0; i < regs->nr; i++) { struct ff_reg *reg = regs->array + i; - if (reg->negate ^ !!regexec(®->re, - line_buffer, 2, pmatch, 0)) { - free(line_buffer); - return -1; + if (!regexec(®->re, line_buffer, 2, pmatch, 0)) { + if (reg->negate) + goto fail; + break; } } + if (regs->nr <= i) + goto fail; i = pmatch[1].rm_so >= 0 ? 1 : 0; line += pmatch[i].rm_so; result = pmatch[i].rm_eo - pmatch[i].rm_so; if (result > buffer_size) result = buffer_size; else - while (result > 0 && (isspace(line[result - 1]) || - line[result - 1] == '\n')) + while (result > 0 && (isspace(line[result - 1]))) result--; memcpy(buffer, line, result); + fail: free(line_buffer); return result; } -void xdiff_set_find_func(xdemitconf_t *xecfg, const char *value) +void xdiff_set_find_func(xdemitconf_t *xecfg, const char *value, int cflags) { int i; struct ff_regs *regs; @@ -243,9 +266,29 @@ void xdiff_set_find_func(xdemitconf_t *xecfg, const char *value) expression = buffer = xstrndup(value, ep - value); else expression = value; - if (regcomp(®->re, expression, 0)) + if (regcomp(®->re, expression, cflags)) die("Invalid regexp to look for hunk header: %s", expression); free(buffer); value = ep + 1; } } + +int git_xmerge_style = -1; + +int git_xmerge_config(const char *var, const char *value, void *cb) +{ + if (!strcasecmp(var, "merge.conflictstyle")) { + if (!value) + die("'%s' is not a boolean", var); + if (!strcmp(value, "diff3")) + git_xmerge_style = XDL_MERGE_DIFF3; + else if (!strcmp(value, "merge")) + git_xmerge_style = 0; + else + die("unknown style '%s' given for '%s'", + value, var); + return 0; + } + return git_default_config(var, value, cb); +} + diff --git a/xdiff-interface.h b/xdiff-interface.h index 558492ba38..eaf9cd3498 100644 --- a/xdiff-interface.h +++ b/xdiff-interface.h @@ -16,6 +16,8 @@ int parse_hunk_header(char *line, int len, int read_mmfile(mmfile_t *ptr, const char *filename); int buffer_is_binary(const char *ptr, unsigned long size); -extern void xdiff_set_find_func(xdemitconf_t *xecfg, const char *line); +extern void xdiff_set_find_func(xdemitconf_t *xecfg, const char *line, int cflags); +extern int git_xmerge_config(const char *var, const char *value, void *cb); +extern int git_xmerge_style; #endif diff --git a/xdiff/xdiff.h b/xdiff/xdiff.h index 413082e1fd..deebe02cd3 100644 --- a/xdiff/xdiff.h +++ b/xdiff/xdiff.h @@ -50,10 +50,16 @@ extern "C" { #define XDL_BDOP_CPY 2 #define XDL_BDOP_INSB 3 +/* merge simplification levels */ #define XDL_MERGE_MINIMAL 0 #define XDL_MERGE_EAGER 1 #define XDL_MERGE_ZEALOUS 2 #define XDL_MERGE_ZEALOUS_ALNUM 3 +#define XDL_MERGE_LEVEL_MASK 0x0f + +/* merge output styles */ +#define XDL_MERGE_DIFF3 0x8000 +#define XDL_MERGE_STYLE_MASK 0x8000 typedef struct s_mmfile { char *ptr; diff --git a/xdiff/xmerge.c b/xdiff/xmerge.c index 82b3573e7a..d9737f04c2 100644 --- a/xdiff/xmerge.c +++ b/xdiff/xmerge.c @@ -30,17 +30,32 @@ typedef struct s_xdmerge { * 2 = no conflict, take second. */ int mode; + /* + * These point at the respective postimages. E.g. <i1,chg1> is + * how side #1 wants to change the common ancestor; if there is no + * overlap, lines before i1 in the postimage of side #1 appear + * in the merge result as a region touched by neither side. + */ long i1, i2; long chg1, chg2; + /* + * These point at the preimage; of course there is just one + * preimage, that is from the shared common ancestor. + */ + long i0; + long chg0; } xdmerge_t; static int xdl_append_merge(xdmerge_t **merge, int mode, - long i1, long chg1, long i2, long chg2) + long i0, long chg0, + long i1, long chg1, + long i2, long chg2) { xdmerge_t *m = *merge; if (m && (i1 <= m->i1 + m->chg1 || i2 <= m->i2 + m->chg2)) { if (mode != m->mode) m->mode = 0; + m->chg0 = i0 + chg0 - m->i0; m->chg1 = i1 + chg1 - m->i1; m->chg2 = i2 + chg2 - m->i2; } else { @@ -49,6 +64,8 @@ static int xdl_append_merge(xdmerge_t **merge, int mode, return -1; m->next = NULL; m->mode = mode; + m->i0 = i0; + m->chg0 = chg0; m->i1 = i1; m->chg1 = chg1; m->i2 = i2; @@ -91,11 +108,13 @@ static int xdl_merge_cmp_lines(xdfenv_t *xe1, int i1, xdfenv_t *xe2, int i2, return 0; } -static int xdl_recs_copy(xdfenv_t *xe, int i, int count, int add_nl, char *dest) +static int xdl_recs_copy_0(int use_orig, xdfenv_t *xe, int i, int count, int add_nl, char *dest) { - xrecord_t **recs = xe->xdf2.recs + i; + xrecord_t **recs; int size = 0; + recs = (use_orig ? xe->xdf1.recs : xe->xdf2.recs) + i; + if (count < 1) return 0; @@ -113,65 +132,109 @@ static int xdl_recs_copy(xdfenv_t *xe, int i, int count, int add_nl, char *dest) return size; } -static int xdl_fill_merge_buffer(xdfenv_t *xe1, const char *name1, - xdfenv_t *xe2, const char *name2, xdmerge_t *m, char *dest) +static int xdl_recs_copy(xdfenv_t *xe, int i, int count, int add_nl, char *dest) +{ + return xdl_recs_copy_0(0, xe, i, count, add_nl, dest); +} + +static int xdl_orig_copy(xdfenv_t *xe, int i, int count, int add_nl, char *dest) +{ + return xdl_recs_copy_0(1, xe, i, count, add_nl, dest); +} + +static int fill_conflict_hunk(xdfenv_t *xe1, const char *name1, + xdfenv_t *xe2, const char *name2, + int size, int i, int style, + xdmerge_t *m, char *dest) { const int marker_size = 7; int marker1_size = (name1 ? strlen(name1) + 1 : 0); int marker2_size = (name2 ? strlen(name2) + 1 : 0); - int conflict_marker_size = 3 * (marker_size + 1) - + marker1_size + marker2_size; - int size, i1, j; - - for (size = i1 = 0; m; m = m->next) { - if (m->mode == 0) { - size += xdl_recs_copy(xe1, i1, m->i1 - i1, 0, - dest ? dest + size : NULL); - if (dest) { - for (j = 0; j < marker_size; j++) - dest[size++] = '<'; - if (marker1_size) { - dest[size] = ' '; - memcpy(dest + size + 1, name1, - marker1_size - 1); - size += marker1_size; - } - dest[size++] = '\n'; - } else - size += conflict_marker_size; - size += xdl_recs_copy(xe1, m->i1, m->chg1, 1, - dest ? dest + size : NULL); - if (dest) { - for (j = 0; j < marker_size; j++) - dest[size++] = '='; - dest[size++] = '\n'; - } - size += xdl_recs_copy(xe2, m->i2, m->chg2, 1, - dest ? dest + size : NULL); - if (dest) { - for (j = 0; j < marker_size; j++) - dest[size++] = '>'; - if (marker2_size) { - dest[size] = ' '; - memcpy(dest + size + 1, name2, - marker2_size - 1); - size += marker2_size; - } - dest[size++] = '\n'; - } - } else if (m->mode == 1) - size += xdl_recs_copy(xe1, i1, m->i1 + m->chg1 - i1, 0, - dest ? dest + size : NULL); + int j; + + /* Before conflicting part */ + size += xdl_recs_copy(xe1, i, m->i1 - i, 0, + dest ? dest + size : NULL); + + if (!dest) { + size += marker_size + 1 + marker1_size; + } else { + for (j = 0; j < marker_size; j++) + dest[size++] = '<'; + if (marker1_size) { + dest[size] = ' '; + memcpy(dest + size + 1, name1, marker1_size - 1); + size += marker1_size; + } + dest[size++] = '\n'; + } + + /* Postimage from side #1 */ + size += xdl_recs_copy(xe1, m->i1, m->chg1, 1, + dest ? dest + size : NULL); + + if (style == XDL_MERGE_DIFF3) { + /* Shared preimage */ + if (!dest) { + size += marker_size + 1; + } else { + for (j = 0; j < marker_size; j++) + dest[size++] = '|'; + dest[size++] = '\n'; + } + size += xdl_orig_copy(xe1, m->i0, m->chg0, 1, + dest ? dest + size : NULL); + } + + if (!dest) { + size += marker_size + 1; + } else { + for (j = 0; j < marker_size; j++) + dest[size++] = '='; + dest[size++] = '\n'; + } + + /* Postimage from side #2 */ + size += xdl_recs_copy(xe2, m->i2, m->chg2, 1, + dest ? dest + size : NULL); + if (!dest) { + size += marker_size + 1 + marker2_size; + } else { + for (j = 0; j < marker_size; j++) + dest[size++] = '>'; + if (marker2_size) { + dest[size] = ' '; + memcpy(dest + size + 1, name2, marker2_size - 1); + size += marker2_size; + } + dest[size++] = '\n'; + } + return size; +} + +static int xdl_fill_merge_buffer(xdfenv_t *xe1, const char *name1, + xdfenv_t *xe2, const char *name2, + xdmerge_t *m, char *dest, int style) +{ + int size, i; + + for (size = i = 0; m; m = m->next) { + if (m->mode == 0) + size = fill_conflict_hunk(xe1, name1, xe2, name2, + size, i, style, m, dest); + else if (m->mode == 1) + size += xdl_recs_copy(xe1, i, m->i1 + m->chg1 - i, 0, + dest ? dest + size : NULL); else if (m->mode == 2) - size += xdl_recs_copy(xe2, m->i2 - m->i1 + i1, - m->i1 + m->chg2 - i1, 0, - dest ? dest + size : NULL); + size += xdl_recs_copy(xe2, m->i2 - m->i1 + i, + m->i1 + m->chg2 - i, 0, + dest ? dest + size : NULL); else continue; - i1 = m->i1 + m->chg1; + i = m->i1 + m->chg1; } - size += xdl_recs_copy(xe1, i1, xe1->xdf2.nrec - i1, 0, - dest ? dest + size : NULL); + size += xdl_recs_copy(xe1, i, xe1->xdf2.nrec - i, 0, + dest ? dest + size : NULL); return size; } @@ -323,9 +386,20 @@ static int xdl_simplify_non_conflicts(xdfenv_t *xe1, xdmerge_t *m, */ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, xdfenv_t *xe2, xdchange_t *xscr2, const char *name2, - int level, xpparam_t const *xpp, mmbuffer_t *result) { + int flags, xpparam_t const *xpp, mmbuffer_t *result) { xdmerge_t *changes, *c; - int i1, i2, chg1, chg2; + int i0, i1, i2, chg0, chg1, chg2; + int level = flags & XDL_MERGE_LEVEL_MASK; + int style = flags & XDL_MERGE_STYLE_MASK; + + if (style == XDL_MERGE_DIFF3) { + /* + * "diff3 -m" output does not make sense for anything + * more aggressive than XDL_MERGE_EAGER. + */ + if (XDL_MERGE_EAGER < level) + level = XDL_MERGE_EAGER; + } c = changes = NULL; @@ -333,11 +407,14 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, if (!changes) changes = c; if (xscr1->i1 + xscr1->chg1 < xscr2->i1) { + i0 = xscr1->i1; i1 = xscr1->i2; i2 = xscr2->i2 - xscr2->i1 + xscr1->i1; + chg0 = xscr1->chg1; chg1 = xscr1->chg2; chg2 = xscr1->chg1; - if (xdl_append_merge(&c, 1, i1, chg1, i2, chg2)) { + if (xdl_append_merge(&c, 1, + i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } @@ -345,18 +422,21 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, continue; } if (xscr2->i1 + xscr2->chg1 < xscr1->i1) { + i0 = xscr2->i1; i1 = xscr1->i2 - xscr1->i1 + xscr2->i1; i2 = xscr2->i2; + chg0 = xscr2->chg1; chg1 = xscr2->chg1; chg2 = xscr2->chg2; - if (xdl_append_merge(&c, 2, i1, chg1, i2, chg2)) { + if (xdl_append_merge(&c, 2, + i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } xscr2 = xscr2->next; continue; } - if (level < 1 || xscr1->i1 != xscr2->i1 || + if (level == XDL_MERGE_MINIMAL || xscr1->i1 != xscr2->i1 || xscr1->chg1 != xscr2->chg1 || xscr1->chg2 != xscr2->chg2 || xdl_merge_cmp_lines(xe1, xscr1->i2, @@ -366,19 +446,25 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, int off = xscr1->i1 - xscr2->i1; int ffo = off + xscr1->chg1 - xscr2->chg1; + i0 = xscr1->i1; i1 = xscr1->i2; i2 = xscr2->i2; - if (off > 0) + if (off > 0) { + i0 -= off; i1 -= off; + } else i2 += off; + chg0 = xscr1->i1 + xscr1->chg1 - i0; chg1 = xscr1->i2 + xscr1->chg2 - i1; chg2 = xscr2->i2 + xscr2->chg2 - i2; - if (ffo > 0) - chg2 += ffo; - else + if (ffo < 0) { + chg0 -= ffo; chg1 -= ffo; - if (xdl_append_merge(&c, 0, i1, chg1, i2, chg2)) { + } else + chg2 += ffo; + if (xdl_append_merge(&c, 0, + i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } @@ -395,11 +481,14 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, while (xscr1) { if (!changes) changes = c; + i0 = xscr1->i1; i1 = xscr1->i2; i2 = xscr1->i1 + xe2->xdf2.nrec - xe2->xdf1.nrec; + chg0 = xscr1->chg1; chg1 = xscr1->chg2; chg2 = xscr1->chg1; - if (xdl_append_merge(&c, 1, i1, chg1, i2, chg2)) { + if (xdl_append_merge(&c, 1, + i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } @@ -408,11 +497,14 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, while (xscr2) { if (!changes) changes = c; + i0 = xscr2->i1; i1 = xscr2->i1 + xe1->xdf2.nrec - xe1->xdf1.nrec; i2 = xscr2->i2; + chg0 = xscr2->chg1; chg1 = xscr2->chg1; chg2 = xscr2->chg2; - if (xdl_append_merge(&c, 2, i1, chg1, i2, chg2)) { + if (xdl_append_merge(&c, 2, + i0, chg0, i1, chg1, i2, chg2)) { xdl_cleanup_merge(changes); return -1; } @@ -421,16 +513,17 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, if (!changes) changes = c; /* refine conflicts */ - if (level > 1 && + if (XDL_MERGE_ZEALOUS <= level && (xdl_refine_conflicts(xe1, xe2, changes, xpp) < 0 || - xdl_simplify_non_conflicts(xe1, changes, level > 2) < 0)) { + xdl_simplify_non_conflicts(xe1, changes, + XDL_MERGE_ZEALOUS < level) < 0)) { xdl_cleanup_merge(changes); return -1; } /* output */ if (result) { int size = xdl_fill_merge_buffer(xe1, name1, xe2, name2, - changes, NULL); + changes, NULL, style); result->ptr = xdl_malloc(size); if (!result->ptr) { xdl_cleanup_merge(changes); @@ -438,14 +531,14 @@ static int xdl_do_merge(xdfenv_t *xe1, xdchange_t *xscr1, const char *name1, } result->size = size; xdl_fill_merge_buffer(xe1, name1, xe2, name2, changes, - result->ptr); + result->ptr, style); } return xdl_cleanup_merge(changes); } int xdl_merge(mmfile_t *orig, mmfile_t *mf1, const char *name1, mmfile_t *mf2, const char *name2, - xpparam_t const *xpp, int level, mmbuffer_t *result) { + xpparam_t const *xpp, int flags, mmbuffer_t *result) { xdchange_t *xscr1, *xscr2; xdfenv_t xe1, xe2; int status; @@ -482,7 +575,7 @@ int xdl_merge(mmfile_t *orig, mmfile_t *mf1, const char *name1, } else { status = xdl_do_merge(&xe1, xscr1, name1, &xe2, xscr2, name2, - level, xpp, result); + flags, xpp, result); } xdl_free_script(xscr1); xdl_free_script(xscr2); |